text
stringlengths
14
6.51M
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit ColorPP; interface uses System.SysUtils, Winapi.ActiveX, Winapi.Windows, Winapi.Messages, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Forms, System.Win.ComServ, System.Win.ComObj, Vcl.AxCtrls, Vcl.ColorGrd, Vcl.Dialogs, StdMain; type TColorPropPage = class(TPropertyPage) StaticText1: TStaticText; StaticText2: TStaticText; PropName: TComboBox; SysColor: TComboBox; ColorBtn: TButton; ColorDialog1: TColorDialog; Panel1: TPanel; procedure ColorBtnClick(Sender: TObject); procedure SysColorChange(Sender: TObject); procedure PropNameChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private ApplyList: TPropApplyList; public procedure UpdatePropertyPage; override; procedure UpdateObject; override; end; implementation {$R *.dfm} const TColorArray: array[0..24] of TColor = ( clScrollBar, clBackground, clActiveCaption, clInactiveCaption, clMenu, clWindow, clWindowFrame, clMenuText, clWindowText, clCaptionText, clActiveBorder, clInactiveBorder, clAppWorkSpace, clHighlight, clHighlightText, clBtnFace, clBtnShadow, clGrayText, clBtnText, clInactiveCaptionText, clBtnHighlight, cl3DDkShadow, cl3DLight, clInfoText, clInfoBk); procedure TColorPropPage.UpdatePropertyPage; begin EnumCtlProps(GUID_OLE_COLOR, PropName.Items); PropName.Enabled := PropName.Items.Count > 0; if PropName.Enabled then begin PropName.ItemIndex := 0; PropNameChange(Self); end else begin SysColor.Enabled := False; ColorBtn.Enabled := False; end; end; procedure TColorPropPage.UpdateObject; var i: Integer; begin for i := 0 to ApplyList.Count - 1 do SetDispatchPropValue(IUnknown(OleObject) as IDispatch, ApplyList.Props[i]^.PropId, ApplyList.Props[i]^.PropValue); ApplyList.ClearProps; end; procedure TColorPropPage.ColorBtnClick(Sender: TObject); begin if ColorDialog1.Execute then begin Panel1.Color:= ColorDialog1.Color; SysColor.Text:= ''; ApplyList.AddProp(Integer(PropName.Items.Objects[PropName.ItemIndex]), Panel1.Color); Modified; end; end; procedure TColorPropPage.SysColorChange(Sender: TObject); begin if SysColor.Text <> '' then begin Panel1.Color:= TColorArray[SysColor.ItemIndex]; ApplyList.AddProp(Integer(PropName.Items.Objects[PropName.ItemIndex]), Panel1.Color); Modified; end; end; procedure TColorPropPage.PropNameChange(Sender: TObject); begin Panel1.Color := GetDispatchPropValue(IUnknown(OleObject) as IDispatch, Integer(PropName.Items.Objects[PropName.ItemIndex])); end; procedure TColorPropPage.FormCreate(Sender: TObject); begin ApplyList := TPropApplyList.Create; end; procedure TColorPropPage.FormDestroy(Sender: TObject); begin ApplyList.Free; end; initialization TActiveXPropertyPageFactory.Create( ComServer, TColorPropPage, Class_DColorPropPage); end.
unit storage; {$mode objfpc}{$H+} interface uses Classes, SysUtils, dialogs, DOM, XMLRead, XMLWrite, configuration, utils; type TStorage = class FPath : String; Name : String; Author : String; Version: String; Bin : String; Params : String; Enabled: Boolean; Freq: integer; FreqExec: Boolean; Summary: String; DirPath: String; CFG: TOTConfig; Counter: Integer; constructor Create(FilePath: String; mCFG: TOTConfig); function CmdLine: string; procedure SetEnabled(status: boolean); end; implementation constructor TStorage.Create (FilePath: String; mCFG: TOTConfig); var Node: TDOMNode; Doc: TXMLDocument; begin self.FPath := FilePath; self.Name := ''; self.Author := ''; self.Version:= ''; self.Bin := ''; self.Params := ''; self.Enabled := false; self.Freq := 0; self.FreqExec := false; self.Summary:= ''; self.Counter := 0; self.CFG := mCFG; self.DirPath := ExtractFilePath(FilePath); IF FileExists(FilePath) THEN BEGIN try ReadXMLFile(Doc, FilePath); Node := Doc.DocumentElement.FindNode('name'); self.Name := OTFormatString(Node.TextContent); Node := Doc.DocumentElement.FindNode('author'); self.Author := OTFormatString(Node.TextContent); Node := Doc.DocumentElement.FindNode('version'); self.Version := OTFormatString(Node.TextContent); Node := Doc.DocumentElement.FindNode('bin'); self.Bin := OTFormatString(Node.TextContent); Node := Doc.DocumentElement.FindNode('params'); self.Params := OTFormatString(Node.TextContent); Node := Doc.DocumentElement.FindNode('enabled'); self.Enabled := strtobool(Node.TextContent); Node := Doc.DocumentElement.FindNode('freq'); self.Freq := strtoint(Node.TextContent); Node := Doc.DocumentElement.FindNode('freqexec'); self.FreqExec := strtobool(Node.TextContent); Node := Doc.DocumentElement.FindNode('summary'); self.Summary := OTFormatString(Node.TextContent); finally Doc.Free; end; END end; function TStorage.CmdLine: string; var cmline: string; begin //Binary script {$IFDEF Windows} cmline := CFG.PHPBin; cmline := cmline+' -c '+CFG.PHPPath; {$ENDIF} {$IFDEF unix} cmline := CFG.PHPBin; {$ENDIF} self.Params := StringReplace(self.Params, '{dirpath}', self.DirPath, [rfReplaceAll, rfIgnoreCase]); self.Params := StringReplace(self.Params, '{dbpath}', CFG.DBPath, [rfReplaceAll, rfIgnoreCase]); cmline := cmline+' '+self.Params; result := cmline; end; procedure TStorage.SetEnabled(status: boolean); var Node: TDOMNode; Doc: TXMLDocument; begin IF status = NOT self.Enabled THEN IF FileExists(self.FPath) THEN BEGIN try ReadXMLFile(Doc, self.FPath); Node := Doc.DocumentElement.FindNode('enabled'); Node.TextContent:=booltostr(status,true); WriteXMLFile(Doc,self.FPath); finally Doc.Free; self.Enabled:=status; end; END end; end.
unit unCalculoPagamento; interface uses Winapi.Windows, System.Classes, MidasLib, Data.DB, Datasnap.DBClient, Vcl.Grids, Vcl.DBGrids, System.SysUtils, generics.defaults, generics.Collections, Contnrs, unPagamento; type TCalculoPagamento = class private fCapital: Double; fTaxaDeJuros: Double; fMeses: Integer; procedure SetCapital(const Value: Double); procedure SetTaxaDeJuros(const Value: Double); procedure SetMeses(const Value: Integer); private fClPagamento: TClientDataSet; procedure SetClPagamento(const Value: TClientDataSet); property clPagamento: TClientDataSet read fClPagamento write SetClPagamento; public property Capital: Double read fCapital write SetCapital; property TaxaDeJuros: Double read fTaxaDeJuros write SetTaxaDeJuros; property Meses: Integer read fMeses write SetMeses; procedure CalculaPagamento(Lista: TList<TPagamento>; DoProcProd: TObtemJurosProduto); constructor Create(ACapital: AnsiString; ATaxaDeJuros: AnsiString; AMeses: AnsiString; clPagamento: TClientDataSet); destructor Destroy; end; implementation { TCalculoPagamento } uses unUtils; procedure TCalculoPagamento.CalculaPagamento(Lista: TList<TPagamento>; DoProcProd: TObtemJurosProduto); var lProd : TPagamento; begin for lProd in Lista do DoProcProd(lProd); end; constructor TCalculoPagamento.Create(ACapital, ATaxaDeJuros, AMeses: AnsiString; clPagamento: TClientDataSet); var Lista: TList<TPagamento>; pagamento: TPagamento; i: Integer; fluxoAnterior: Integer; strCapital, strTaxaJuros, strMeses: string; totalFluxos: Integer; totalJuros: Double; totalPagamento: Double; begin inherited Create; strCapital := unUtils.formatNumber(ACapital); strTaxaJuros := unUtils.formatNumber(ATaxaDeJuros); strMeses := AMeses; if not (unUtils.IsFloat(strCapital)) then raise EPagamentoException.Create('Valor de Capital inválido.'); if not (unUtils.IsFloat(strTaxaJuros)) then raise EPagamentoException.Create('Valor de Taxa de Juros inválida.'); if not (unUtils.IsNumber(strMeses)) then raise EPagamentoException.Create('Valor de Meses inválido.'); if (StrToFloatDef(strMeses, 0) = 0) then raise EPagamentoException.Create('A quantidade de meses não pode ser zero.'); Capital := StrToFloat(strCapital); TaxaDeJuros := StrToFloat(strTaxaJuros); Meses := StrToInt(strMeses); totalFluxos := Meses + 1; totalJuros := 0; totalPagamento := 0; Lista := TList<TPagamento>.Create; try for i := 0 to totalFluxos do Lista.Add(TPagamento.Create(i,0,0,0,0)); i := 0; CalculaPagamento(Lista, function (APag: TPagamento): Double begin if i = 0 then APag.SaldoDevedor := Capital else if i = 1 then begin APag.Juros := Capital * (TaxaDeJuros/100); APag.SaldoDevedor := Lista[i-1].SaldoDevedor + APag.Juros; end else if (i > 1) and (i < totalFluxos) then begin APag.Juros := Lista[i-1].Juros + Lista[i-1].Juros * (TaxaDeJuros/100); if i < totalFluxos - 1 then APag.SaldoDevedor := Lista[i-1].SaldoDevedor + APag.Juros else APag.SaldoDevedor := 0 end; Inc(i); end); i := 0; with ClPagamento do begin DisableControls; try EmptyDataSet; for pagamento in Lista do begin Append; FieldByName('Fluxo').AsInteger := pagamento.Fluxo; FieldByName('FluxoApresentacao').AsString := ClPagamento.FieldByName('Fluxo').AsString; if i > 0 then FieldByName('Juros').AsFloat := pagamento.Juros; if i < totalFluxos then FieldByName('SaldoDevedor').AsFloat := pagamento.SaldoDevedor; if i = totalFluxos - 1 then FieldByName('AmortizacaoSaldoDevedor').AsFloat := Lista[i-1].SaldoDevedor; Inc(i); end; Edit; FieldByName('FluxoApresentacao').AsString := 'Totais:'; totalJuros := StrToFloatDef(FieldByName('SomaJuros').AsString, 0); FieldByName('Juros').AsFloat := totalJuros; totalPagamento := Capital + totalJuros; FieldByName('Pagamento').AsFloat := totalPagamento; if (State in [dsInsert, dsEdit]) then Post; finally First; EnableControls; end; end; finally FreeAndNil(Lista); end; end; destructor TCalculoPagamento.Destroy; begin inherited Destroy; end; procedure TCalculoPagamento.SetCapital(const Value: Double); begin fCapital := Value; end; procedure TCalculoPagamento.SetClPagamento(const Value: TClientDataSet); begin fClPagamento := Value; end; procedure TCalculoPagamento.SetMeses(const Value: Integer); begin fMeses := Value; end; procedure TCalculoPagamento.SetTaxaDeJuros(const Value: Double); begin fTaxaDeJuros := Value; end; end.
{------------------------------------------------------------------------------ This file is part of the MotifMASTER project. This software is distributed under GPL (see gpl.txt for details). This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru) ------------------------------------------------------------------------------} unit Decisions; interface uses SysUtils, Classes, ComponentList; type TAbstractDecision = class(TComponent) protected FEvaluation: Double; function GetParametersNumber: LongInt; virtual; abstract; procedure SetParametersNumber(AParametersNumber: LongInt); virtual; abstract; public procedure FillCopy(const Copy: TAbstractDecision); virtual; abstract; function GetCopy: TAbstractDecision; virtual; abstract; function Coincide(const Decision: TAbstractDecision): Boolean; virtual; abstract; property Evaluation: Double read FEvaluation write FEvaluation; property ParametersNumber: LongInt read GetParametersNumber write SetParametersNumber; end; TOneDimDecision = class(TAbstractDecision) public procedure InvertParameter(const ParamNum: LongInt); virtual; abstract; procedure ExchangeParameters(const ParamNum1, ParamNum2: LongInt); virtual; abstract; procedure ExchangeWithOuter(const Decision: TAbstractDecision; ParamNum: LongInt); virtual; abstract; procedure CopyParameter(const ParamNum, NewParamNum: LongInt); virtual; abstract; end; TTwoDimDecision = class(TAbstractDecision) protected function GetGenesNumber: LongInt; virtual; abstract; procedure SetGenesNumber(AGenesNumber: LongInt); virtual; abstract; public procedure InvertParameter(const GeneNum, ParamNum: LongInt); virtual; abstract; procedure InvertBlock(const StartGeneNum, EndGeneNum, StartParamNum, EndParamNum: LongInt); virtual; procedure ExchangeParameters(const GeneNum1, ParamNum1, GeneNum2, ParamNum2: LongInt); virtual; abstract; procedure ExchangeWithOuter(const Decision: TAbstractDecision; MyGeneNum, OuterGeneNum, ParamNum: LongInt); virtual; abstract; procedure ExchangeBlocksWithOuter( const Decision: TAbstractDecision; StartGeneNum, EndGeneNum, StartParamNum, EndParamNum: LongInt); virtual; procedure CopyParameter(const SrcGeneNum, SrcParamNum, DestGeneNum, DestParamNum: LongInt); virtual; abstract; procedure CopyBlock(const StartGeneNum, EndGeneNum, StartParamNum, EndParamNum, GeneOffset, ParamOffset: LongInt); virtual; abstract; property GenesNumber: LongInt read GetGenesNumber write SetGenesNumber; end; EFloatDecision = class(Exception); TFloatDecision = class(TOneDimDecision) protected FParameters: array of Double; function GetParameter(index: LongInt): Double; procedure SetParameter(index: LongInt; AParameter: Double); function GetParametersNumber: LongInt; override; procedure SetParametersNumber(AParametersNumber: LongInt); override; public destructor Destroy; override; procedure FillCopy(const Copy: TAbstractDecision); override; function GetCopy: TAbstractDecision; override; function Coincide(const Decision: TAbstractDecision): Boolean; override; procedure InvertParameter(const ParamNum: LongInt); override; procedure ExchangeParameters(const ParamNum1, ParamNum2: LongInt); override; procedure ExchangeWithOuter(const Decision: TAbstractDecision; ParamNum: LongInt); override; procedure CopyParameter(const ParamNum, NewParamNum: LongInt); override; property Parameters[index: LongInt]: Double read GetParameter write SetParameter; default; end; EByteDecision = class(Exception); TByteDecision = class(TOneDimDecision) protected FParameters: array of Byte; function GetParameter(index: LongInt): Byte; procedure SetParameter(index: LongInt; AParameter: Byte); function GetParametersNumber: LongInt; override; procedure SetParametersNumber(AParametersNumber: LongInt); override; public destructor Destroy; override; procedure FillCopy(const Copy: TAbstractDecision); override; function GetCopy: TAbstractDecision; override; function Coincide(const Decision: TAbstractDecision): Boolean; override; procedure InvertParameter(const ParamNum: LongInt); override; procedure ExchangeParameters(const ParamNum1, ParamNum2: LongInt); override; procedure ExchangeWithOuter(const Decision: TAbstractDecision; ParamNum: LongInt); override; procedure CopyParameter(const ParamNum, NewParamNum: LongInt); override; property Parameters[index: LongInt]: Byte read GetParameter write SetParameter; default; end; ETwoDimFloatDecision = class(Exception); TTwoDimFloatDecision = class(TTwoDimDecision) protected FParameters: array of array of Double; FParametersNumber: LongInt; FSelectedGene: LongInt; function GetParameter(index: LongInt): Double; procedure SetParameter(index: LongInt; AParameter: Double); function GetParametersNumber: LongInt; override; procedure SetParametersNumber(AParametersNumber: LongInt); override; function GetGenesNumber: LongInt; override; procedure SetGenesNumber(AGenesNumber: LongInt); override; function GetSelectedGene: LongInt; procedure SetSelectedGene(ASelectedGene: LongInt); public destructor Destroy; override; procedure FillCopy(const Copy: TAbstractDecision); override; function GetCopy: TAbstractDecision; override; function Coincide(const Decision: TAbstractDecision): Boolean; override; procedure InvertParameter(const GeneNum, ParamNum: LongInt); override; procedure ExchangeParameters(const GeneNum1, ParamNum1, GeneNum2, ParamNum2: LongInt); override; procedure CopyParameter(const SrcGeneNum, SrcParamNum, DestGeneNum, DestParamNum: LongInt); override; procedure ExchangeWithOuter(const Decision: TAbstractDecision; MyGeneNum, OuterGeneNum, ParamNum: LongInt); override; procedure CopyBlock(const StartGeneNum, EndGeneNum, StartParamNum, EndParamNum, GeneOffset, ParamOffset: LongInt); override; property Parameters[index: LongInt]: Double read GetParameter write SetParameter; default; property SelectedGene: LongInt read GetSelectedGene write SetSelectedGene; end; EDecisionsList = class(Exception); TDecisionsList = class(TComponentList) public function GetMaxDecision(const StartIndex: LongInt; UpLimit: Double): TAbstractDecision; function GetMinDecision(const StartIndex: LongInt; LowLimit: Double): TAbstractDecision; function GetAbsoluteMin: TAbstractDecision; function GetAbsoluteMax: TAbstractDecision; function HasThisDecision(const Decision: TAbstractDecision): Boolean; end; function EvalDownSortFunc(Item1, Item2: Pointer): Integer; function EvalUpSortFunc(Item1, Item2: Pointer): Integer; const EvalDownSort: TListSortCompare = EvalDownSortFunc; EvalUpSort: TListSortCompare = EvalUpSortFunc; const TINY = 1e-6; implementation destructor TFloatDecision.Destroy; begin Finalize(FParameters); inherited Destroy; end; function TFloatDecision.GetParameter(index: LongInt): Double; begin if (index > ParametersNumber - 1) or (index < 0) then raise EFloatDecision.Create('Parameter index out of range...'); Result := FParameters[index]; end; procedure TFloatDecision.SetParameter(index: LongInt; AParameter: Double); begin if (index > ParametersNumber - 1) or (index < 0) then raise EFloatDecision.Create('Parameter index out of range...'); FParameters[index] := AParameter; end; function TFloatDecision.GetParametersNumber: LongInt; begin if Assigned(FParameters) then Result := Length(FParameters) else Result := 0; end; procedure TFloatDecision.SetParametersNumber(AParametersNumber: LongInt); var i: LongInt; SavedLength: LongInt; begin if AParametersNumber > ParametersNumber then begin SavedLength := ParametersNumber; SetLength(FParameters, AParametersNumber); for i := SavedLength to ParametersNumber - 1 do Parameters[i] := 0; end else SetLength(FParameters, AParametersNumber); end; function TFloatDecision.GetCopy: TAbstractDecision; begin Result := TFloatDecision.Create(nil); FillCopy(Result); end; procedure TFloatDecision.FillCopy(const Copy: TAbstractDecision); var i: LongInt; begin TFloatDecision(Copy).ParametersNumber := ParametersNumber; for i := 0 to ParametersNumber - 1 do TFloatDecision(Copy).Parameters[i] := Parameters[i]; Copy.Evaluation := Evaluation; end; function TFloatDecision.Coincide(const Decision: TAbstractDecision): Boolean; var FloatDecision: TFloatDecision absolute Decision; i: LongInt; begin if not (Decision is TFloatDecision) then raise EFloatDecision.Create('Invalid decision type...'); Result := True; for i := 0 to ParametersNumber - 1 do begin if Abs(FloatDecision[i] - Self[i]) > TINY then begin Result := False; Exit end; end; end; procedure TFloatDecision.InvertParameter(const ParamNum: LongInt); begin Self[ParamNum] := (-1) * Self[ParamNum]; end; procedure TFloatDecision.ExchangeParameters(const ParamNum1, ParamNum2: LongInt); var TempDouble: Double; begin TempDouble := Self[ParamNum2]; Self[ParamNum2] := Self[ParamNum1]; Self[ParamNum1] := TempDouble; end; procedure TFloatDecision.ExchangeWithOuter(const Decision: TAbstractDecision; ParamNum: LongInt); var TempDouble: Double; begin if not (Decision is TFloatDecision) then raise EFloatDecision.Create('Invalid decision type ' + Decision.ClassName); TempDouble := Self[ParamNum]; Self[ParamNum] := TFloatDecision(Decision)[ParamNum]; TFloatDecision(Decision)[ParamNum] := TempDouble; end; procedure TFloatDecision.CopyParameter(const ParamNum, NewParamNum: LongInt); begin Self[NewParamNum] := Self[ParamNum]; end; destructor TByteDecision.Destroy; begin Finalize(FParameters); inherited Destroy; end; function TByteDecision.GetParameter(index: LongInt): Byte; begin if (index > ParametersNumber - 1) or (index < 0) then raise EByteDecision.Create('Parameter index out of range...'); Result := FParameters[index]; end; procedure TByteDecision.SetParameter(index: LongInt; AParameter: Byte); begin if (index > ParametersNumber - 1) or (index < 0) then raise EByteDecision.Create('Parameter index out of range...'); FParameters[index] := AParameter; end; function TByteDecision.GetParametersNumber: LongInt; begin if Assigned(FParameters) then Result := Length(FParameters) else Result := 0; end; procedure TByteDecision.SetParametersNumber(AParametersNumber: LongInt); var i: LongInt; SavedLength: LongInt; begin if AParametersNumber > ParametersNumber then begin SavedLength := ParametersNumber; SetLength(FParameters, AParametersNumber); for i := SavedLength to ParametersNumber - 1 do Parameters[i] := 0; end else SetLength(FParameters, AParametersNumber); end; function TByteDecision.GetCopy: TAbstractDecision; begin Result := TByteDecision.Create(nil); FillCopy(Result); end; procedure TByteDecision.FillCopy(const Copy: TAbstractDecision); var i: LongInt; begin TByteDecision(Copy).ParametersNumber := ParametersNumber; for i := 0 to ParametersNumber - 1 do TByteDecision(Copy).Parameters[i] := Parameters[i]; Copy.Evaluation := Evaluation; end; function TByteDecision.Coincide(const Decision: TAbstractDecision): Boolean; var ByteDecision: TByteDecision absolute Decision; var i: LongInt; begin if not (Decision is TByteDecision) then raise EByteDecision.Create('Invalid decision type...'); Result := True; for i := 0 to ParametersNumber - 1 do begin if ByteDecision[i] <> Self[i] then begin Result := False; Exit end; end; end; procedure TByteDecision.InvertParameter(const ParamNum: LongInt); begin Self[ParamNum] := not Self[ParamNum]; end; procedure TByteDecision.ExchangeParameters(const ParamNum1, ParamNum2: LongInt); var TempByte: Byte; begin TempByte := Self[ParamNum2]; Self[ParamNum2] := Self[ParamNum1]; Self[ParamNum1] := TempByte; end; procedure TByteDecision.ExchangeWithOuter(const Decision: TAbstractDecision; ParamNum: LongInt); var TempByte: Byte; begin if not (Decision is TByteDecision) then raise EByteDecision.Create('Invalid decision type ' + Decision.ClassName); TempByte := Self[ParamNum]; Self[ParamNum] := TByteDecision(Decision)[ParamNum]; TFloatDecision(Decision)[ParamNum] := TempByte; end; procedure TByteDecision.CopyParameter(const ParamNum, NewParamNum: LongInt); begin Self[NewParamNum] := Self[ParamNum]; end; function TTwoDimFloatDecision.GetParameter(index: LongInt): Double; begin if (index > ParametersNumber - 1) or (index < 0) then raise ETwoDimFloatDecision.Create('Parameter index out of range...'); Result := FParameters[SelectedGene, index]; end; procedure TTwoDimFloatDecision.SetParameter(index: LongInt; AParameter: Double); begin if (index > ParametersNumber - 1) or (index < 0) then raise ETwoDimFloatDecision.Create('Parameter index out of range...'); FParameters[SelectedGene, index] := AParameter; end; function TTwoDimFloatDecision.GetParametersNumber: LongInt; begin Result := FParametersNumber; end; procedure TTwoDimFloatDecision.SetParametersNumber(AParametersNumber: LongInt); var i: LongInt; begin FParametersNumber := AParametersNumber; for i := 0 to Length(FParameters) - 1 do SetLength(FParameters[i], AParametersNumber); end; function TTwoDimFloatDecision.GetGenesNumber: LongInt; begin Result := Length(FParameters); end; procedure TTwoDimFloatDecision.SetGenesNumber(AGenesNumber: LongInt); var SavedLength: LongInt; i: LongInt; begin SavedLength := Length(FParameters); SetLength(FParameters, AGenesNumber); if Length(FParameters) > SavedLength then for i := SavedLength to Length(FParameters) - 1 do SetLength(FParameters[i], ParametersNumber); end; procedure TTwoDimFloatDecision.SetSelectedGene(ASelectedGene: LongInt); begin if (ASelectedGene > GenesNumber - 1) or (ASelectedGene < 0) then raise ETwoDimFloatDecision.Create('Selected gene out of range...'); FSelectedGene := ASelectedGene; end; function TTwoDimFloatDecision.GetSelectedGene: LongInt; begin if (FSelectedGene > GenesNumber - 1) then raise ETwoDimFloatDecision.Create('Selected gene out of range...'); Result := FSelectedGene; end; procedure TTwoDimFloatDecision.FillCopy(const Copy: TAbstractDecision); var i, j: LongInt; begin TTwoDimFloatDecision(Copy).GenesNumber := GenesNumber; TTwoDimFloatDecision(Copy).ParametersNumber := ParametersNumber; for j := 0 to GenesNumber - 1 do begin TTwoDimFloatDecision(Copy).SelectedGene := j; SelectedGene := j; for i := 0 to ParametersNumber - 1 do TTwoDimFloatDecision(Copy).Parameters[i] := Parameters[i]; end; Copy.Evaluation := Evaluation; end; destructor TTwoDimFloatDecision.Destroy; var i: LongInt; begin for i := 0 to Length(FParameters) - 1 do Finalize(FParameters[i]); Finalize(FParameters); inherited Destroy; end; function TTwoDimFloatDecision.GetCopy: TAbstractDecision; begin Result := TTwoDimFloatDecision.Create(nil); FillCopy(Result); end; function TTwoDimFloatDecision.Coincide(const Decision: TAbstractDecision): Boolean; var i, j: LongInt; TwoDimFloatDecision: TTwoDimFloatDecision absolute Decision; begin if not (Decision is TTwoDimFloatDecision) then raise ETwoDimFloatDecision.Create('Invalid decision type...'); Result := True; for i := 0 to GenesNumber - 1 do begin SelectedGene := i; for j := 0 to ParametersNumber - 1 do begin if Abs(TwoDimFloatDecision[j] - Self[j]) > TINY then begin Result := False; Exit end; end; end; end; procedure TTwoDimFloatDecision.InvertParameter(const GeneNum, ParamNum: LongInt); begin SelectedGene := GeneNum; Self[ParamNum] := (-1) * Self[ParamNum]; end; procedure TTwoDimFloatDecision.ExchangeParameters(const GeneNum1, ParamNum1, GeneNum2, ParamNum2: LongInt); var TempDouble1, TempDouble2: Double; begin SelectedGene := GeneNum1; TempDouble1 := Self[ParamNum1]; SelectedGene := GeneNum2; TempDouble2 := Self[ParamNum2]; SelectedGene := GeneNum1; Self[ParamNum1] := TempDouble2; SelectedGene := GeneNum2; Self[ParamNum2] := TempDouble1; end; procedure TTwoDimFloatDecision.ExchangeWithOuter( const Decision: TAbstractDecision; MyGeneNum, OuterGeneNum, ParamNum: LongInt); var TempDouble: Double; begin if not (Decision is TTwoDimFloatDecision) then raise ETwoDimFloatDecision.Create( 'Invalid decision type ' + Decision.ClassName); Self.SelectedGene := MyGeneNum; TTwoDimFloatDecision(Decision).SelectedGene := OuterGeneNum; TempDouble := Self[ParamNum]; Self[ParamNum] := TTwoDimFloatDecision(Decision)[ParamNum]; TTwoDimFloatDecision(Decision)[ParamNum] := TempDouble; end; procedure TTwoDimFloatDecision.CopyParameter( const SrcGeneNum, SrcParamNum, DestGeneNum, DestParamNum: LongInt); var TempDouble: Double; begin SelectedGene := SrcGeneNum; TempDouble := Self[SrcParamNum]; SelectedGene := DestParamNum; Self[DestParamNum] := TempDouble; end; procedure TTwoDimFloatDecision.CopyBlock(const StartGeneNum, EndGeneNum, StartParamNum, EndParamNum, GeneOffset, ParamOffset: LongInt); var SavedBlock: array of array of Double; i, j: LongInt; Index1, Index2: LongInt; begin SetLength(SavedBlock, EndGeneNum - StartGeneNum + 1); for i := 0 to Length(SavedBlock) - 1 do SetLength(SavedBlock[i], EndParamNum - StartParamNum + 1); for i := 0 to Length(SavedBlock) - 1 do for j := 0 to Length(SavedBlock[i]) - 1 do SavedBlock[i, j] := FParameters[i + StartGeneNum, j + StartParamNum]; for i := 0 to Length(SavedBlock) - 1 do for j := 0 to Length(SavedBlock[i]) - 1 do begin Index1 := StartGeneNum + GeneOffset + i; Index2 := StartParamNum + ParamOffset + j; if Index1 > GenesNumber - 1 then Index1 := Index1 - GenesNumber * (Index1 div GenesNumber); if Index1 < 0 then Index1 := (GenesNumber - 1) + (Index1 + GenesNumber * (Abs(Index1) div GenesNumber)); if Index2 > ParametersNumber - 1 then Index2 := Index2 - ParametersNumber * (Index2 div ParametersNumber); if Index2 < 0 then Index2 := (ParametersNumber - 1) + (Index2 + ParametersNumber * (Abs(Index2) div ParametersNumber)); FParameters[Index1, Index2] := SavedBlock[i, j]; end; for i := 0 to Length(SavedBlock) - 1 do Finalize(SavedBlock[i]); Finalize(SavedBlock); end; procedure TTwoDimDecision.ExchangeBlocksWithOuter( const Decision: TAbstractDecision; StartGeneNum, EndGeneNum, StartParamNum, EndParamNum: LongInt); var i, j: LongInt; begin for i := StartGeneNum to EndGeneNum do for j := StartParamNum to EndParamNum do ExchangeWithOuter(Decision, i, i, j); end; procedure TTwoDimDecision.InvertBlock(const StartGeneNum, EndGeneNum, StartParamNum, EndParamNum: LongInt); var i, j: LongInt; begin for i := StartGeneNum to EndGeneNum do for j := StartParamNum to EndParamNum do InvertParameter(i, j); end; function TDecisionsList.GetMaxDecision( const StartIndex: LongInt; UpLimit: Double): TAbstractDecision; var i: LongInt; Decision: TAbstractDecision; Max: Double; Flag: Boolean; begin Result := nil; if Count = 0 then raise EDecisionsList.Create('Decisions list should not be empty...'); Flag := True; for i := StartIndex to Count - 1 do begin Decision := TAbstractDecision(Items[i]); if Flag then if Decision.Evaluation <= UpLimit then begin Max := Decision.Evaluation; Result := Decision; Flag := False; if Decision.Evaluation = UpLimit then Exit; end else if (Decision.Evaluation >= Max) and (Decision.Evaluation <= UpLimit) then begin Max := Decision.Evaluation; Result := Decision; if Decision.Evaluation = UpLimit then Exit; end; end; end; function TDecisionsList.GetMinDecision( const StartIndex: LongInt; LowLimit: Double): TAbstractDecision; var i: LongInt; Decision: TAbstractDecision; Min: Double; Flag: Boolean; begin Result := nil; if Count = 0 then raise EDecisionsList.Create('Decisions list should not be empty...'); Flag := True; for i := StartIndex to Count - 1 do begin Decision := TAbstractDecision(Items[i]); if Flag then if Decision.Evaluation >= LowLimit then begin Min := Decision.Evaluation; Result := Decision; Flag := False; if Decision.Evaluation = LowLimit then Exit; end else if (Decision.Evaluation <= Min) and (Decision.Evaluation >= LowLimit) then begin Min := Decision.Evaluation; Result := Decision; if Decision.Evaluation = LowLimit then Exit; end; end; end; function TDecisionsList.GetAbsoluteMin: TAbstractDecision; var i: LongInt; Decision: TAbstractDecision; begin Result := nil; if Count = 0 then raise EDecisionsList.Create('Decisions list should not be empty...'); Decision := TAbstractDecision(Items[0]); Result := Decision; for i := 1 to Count - 1 do begin Decision := TAbstractDecision(Items[i]); if Decision.Evaluation < Result.Evaluation then Result := Decision; end; end; function TDecisionsList.GetAbsoluteMax: TAbstractDecision; var i: LongInt; Decision: TAbstractDecision; begin Result := nil; if Count = 0 then raise EDecisionsList.Create('Decisions list should not be empty...'); Decision := TAbstractDecision(Items[0]); Result := Decision; for i := 1 to Count - 1 do begin Decision := TAbstractDecision(Items[i]); if Decision.Evaluation > Result.Evaluation then Result := Decision; end; end; function TDecisionsList.HasThisDecision( const Decision: TAbstractDecision): Boolean; var i: LongInt; TempDecision: TAbstractDecision; begin Result := False; for i := 0 to Count - 1 do begin TempDecision := TAbstractDecision(Items[i]); if TempDecision.Coincide(Decision) then begin Result := True; Exit end; end; end; function EvalUpSortFunc(Item1, Item2: Pointer): Integer; var Decision1: TAbstractDecision absolute Item1; Decision2: TAbstractDecision absolute Item2; begin if Decision1.Evaluation > Decision2.Evaluation then Result := 1; if Decision1.Evaluation < Decision2.Evaluation then Result := -1; if Decision1.Evaluation = Decision2.Evaluation then Result := 0; end; function EvalDownSortFunc(Item1, Item2: Pointer): Integer; var Decision1: TAbstractDecision absolute Item1; Decision2: TAbstractDecision absolute Item2; begin if Decision1.Evaluation > Decision2.Evaluation then Result := -1; if Decision1.Evaluation < Decision2.Evaluation then Result := 1; if Decision1.Evaluation = Decision2.Evaluation then Result := 0; end; initialization RegisterClass(TFloatDecision); RegisterClass(TTwoDimFloatDecision); RegisterClass(TByteDecision); RegisterClass(TDecisionsList); end.
unit UnFechamentoDeContaView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, JvExExtCtrls, JvExtComponent, JvPanel, db, Grids, DBGrids, { Fluente } Util, DataUtil, UnModelo, UnFechamentoDeContaModelo, SearchUtil, Componentes, UnAplicacao, JvExStdCtrls, JvEdit, JvValidateEdit; type OperacaoDeFechamentoDeConta = (opfdcImprimir, opfdcLancarCartaoDeDebito, opfdcLancarCartaoDeCredito, opfdcLancarDinheiro, opfdcExibirPagamentos, opfdcFecharConta, opfdcExibirDetalhesComanda, opfdcCarregarConta); TFechamentoDeContaView = class(TForm, ITela) pnlComandos: TJvPanel; btnOk: TPanel; btnImprimir: TPanel; btnLancarDebito: TPanel; btnLancarCredito: TPanel; btnLancarDinheiro: TPanel; btnVisualizarPagamentos: TPanel; btnFecharConta: TPanel; pnlDetalheView: TPanel; DetalheView: TMemo; pnlDesktop: TPanel; pnlCliente: TPanel; lblCliente: TLabel; EdtCliente: TEdit; EdtOid: TEdit; EdtCod: TEdit; pnlTitulo: TPanel; lblIdComanda: TLabel; pnlSumario: TPanel; Panel6: TPanel; lblTotalEmAberto: TLabel; Panel7: TPanel; lblSaldo: TLabel; Panel3: TPanel; lblPagamentos: TLabel; pnlClientePesquisa: TPanel; gConta: TDBGrid; Label2: TLabel; btnDecAcrescimo: TButton; txtAcrescimo: TJvValidateEdit; btnIncAcrescimo: TButton; procedure btnLancarDebitoClick(Sender: TObject); procedure btnLancarCreditoClick(Sender: TObject); procedure btnLancarDinheiroClick(Sender: TObject); procedure btnVisualizarPagamentosClick(Sender: TObject); procedure btnFecharContaClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnImprimirClick(Sender: TObject); procedure gContaDblClick(Sender: TObject); procedure btnIncAcrescimoClick(Sender: TObject); procedure btnDecAcrescimoClick(Sender: TObject); procedure FormShow(Sender: TObject); private FFocusControl: TWinControl; FControlador: IResposta; FFechamentoContaModelo: TFechamentoDeContaModelo; FPesquisaCliente: TPesquisa; procedure ProcessarSelecaoDeCliente(Pesquisa: TObject); procedure AtualizarTela; public function Controlador(const Controlador: IResposta): ITela; function Descarregar: ITela; function ExibirTela: Integer; function Modelo(const Modelo: TModelo): ITela; function Preparar: ITela; published procedure AtualizarSumario(Sender: TObject); end; var FechamentoDeContaView: TFechamentoDeContaView; implementation {$R *.dfm} { TFechamentoDeContaView } function TFechamentoDeContaView.Descarregar: ITela; begin Self.FControlador := nil; Self.FFechamentoContaModelo := nil; Self.FPesquisaCliente.Descarregar; Self.FPesquisaCliente.Free; Self.FPesquisaCliente := nil; Result := Self; end; function TFechamentoDeContaView.Modelo( const Modelo: TModelo): ITela; begin Self.FFechamentoContaModelo := (Modelo as TFechamentoDeContaModelo); Result := Self; end; function TFechamentoDeContaView.Preparar: ITela; begin Self.gConta.DataSource := Self.FFechamentoContaModelo.DataSource; Self.FPesquisaCliente := TConstrutorDePesquisas .Formulario(Self) .ControleDeEdicao(Self.EdtCliente) .PainelDePesquisa(Self.pnlClientePesquisa) .Modelo('ClientePesquisaModelo') .AcaoAposSelecao(Self.ProcessarSelecaoDeCliente) .Construir; Result := Self; end; procedure TFechamentoDeContaView.ProcessarSelecaoDeCliente( Pesquisa: TObject); var _event: TNotifyEvent; _dataSet: TDataSet; begin _event := Self.EdtCliente.OnChange; Self.EdtCliente.OnChange := nil; _dataSet := (Pesquisa as TPesquisa).Modelo.DataSet; Self.EdtCliente.Text := _dataSet.FieldByName('cl_cod').AsString; Self.EdtCliente.OnChange := _event; Self.FFechamentoContaModelo.CarregarPor(Criterio.campo('c.cl_oid').igual(_dataSet.FieldByName('cl_oid').AsString).Obter); Self.AtualizarTela; end; procedure TFechamentoDeContaView.btnLancarDebitoClick(Sender: TObject); var _chamada: TChamada; begin _chamada := TChamada.Create .Chamador(Self) .AposChamar(AtualizarSumario) .Parametros(TMap.Create .Gravar('acao', Ord(opfdcLancarCartaoDeDebito)) ); Self.FControlador.Responder(_chamada); end; procedure TFechamentoDeContaView.AtualizarSumario(Sender: TObject); var _dataSet: TDataSet; _totalEmAberto, _pagamentos, _acrescimo, _saldo: Real; begin _totalEmAberto := 0 ; _pagamentos := 0; _acrescimo := 0; _dataSet := Self.FFechamentoContaModelo.DataSet; if _dataSet.FieldByName('SALDO_TOTAL').AsString <> '' then _totalEmAberto := StrToFloat(_dataSet.FieldByName('SALDO_TOTAL').AsString); _dataSet := Self.FFechamentoContaModelo.DataSet('mcx'); if _dataSet.FieldByName('TOTAL').AsString <> '' then _pagamentos := StrToFloat(_dataSet.FieldByName('TOTAL').AsString); _saldo := _totalEmAberto; if (_saldo > 0) and (Self.txtAcrescimo.Value > 0) then _acrescimo := _saldo * Self.txtAcrescimo.Value / 100; _saldo := _totalEmAberto + _acrescimo - _pagamentos; Self.lblTotalEmAberto.Caption := FormatFloat('0.00', _totalEmAberto); Self.lblPagamentos.Caption := FormatFloat('0.00', _pagamentos); Self.lblSaldo.Caption := FormatFloat('0.00', _saldo); end; procedure TFechamentoDeContaView.AtualizarTela; var _dataSet: TDataSet; begin _dataSet := Self.FFechamentoContaModelo.DataSet; if _dataSet.FieldByName('SALDO_TOTAL').AsString <> '' then Self.lblTotalEmAberto.Caption := FormatFloat('0.00', StrToFloat(_dataSet.FieldByName('SALDO_TOTAL').AsString)) else Self.lblTotalEmAberto.Caption := '0,00'; Self.AtualizarSumario(nil); end; procedure TFechamentoDeContaView.btnLancarCreditoClick(Sender: TObject); var _chamada: TChamada; begin _chamada := TChamada.Create .Chamador(Self) .AposChamar(AtualizarSumario) .Parametros(TMap.Create .Gravar('acao', Ord(opfdcLancarCartaoDeCredito)) ); Self.FControlador.Responder(_chamada); end; procedure TFechamentoDeContaView.btnLancarDinheiroClick(Sender: TObject); var _chamada: TChamada; _valor: Real; begin _valor := StrToFloat(Self.lblSaldo.Caption); _chamada := TChamada.Create .Chamador(Self) .AposChamar(AtualizarSumario) .Parametros(TMap.Create .Gravar('acao', Ord(opfdcLancarDinheiro)) .Gravar('valor', _valor) ); Self.FControlador.Responder(_chamada); end; procedure TFechamentoDeContaView.btnVisualizarPagamentosClick( Sender: TObject); var _chamada: TChamada; begin _chamada := TChamada.Create .Chamador(Self) .AposChamar(AtualizarSumario) .Parametros(TMap.Create .Gravar('acao', Ord(opfdcExibirPagamentos)) ); Self.FControlador.Responder(_chamada); end; procedure TFechamentoDeContaView.btnDecAcrescimoClick(Sender: TObject); var _valor: Integer; begin _valor := StrToInt(Self.txtAcrescimo.Text); if _valor > 0 then begin Self.txtAcrescimo.Text := IntToStr(_valor-1); Self.AtualizarSumario(nil); end; end; procedure TFechamentoDeContaView.btnFecharContaClick(Sender: TObject); var _chamada: TChamada; begin _chamada := TChamada.Create .Parametros(TMap.Create .Gravar('acao', Ord(opfdcFecharConta)) ); Self.FControlador.Responder(_chamada); Self.ModalResult := mrOk; end; procedure TFechamentoDeContaView.btnOkClick(Sender: TObject); begin Self.ModalResult := mrOk; end; function TFechamentoDeContaView.Controlador( const Controlador: IResposta): ITela; begin Self.FControlador := Controlador; Result := Self; end; function TFechamentoDeContaView.ExibirTela: Integer; var _event: TNotifyEvent; begin if Self.FFechamentoContaModelo.DataSet.RecordCount > 0 then begin _event := Self.EdtCliente.OnChange; Self.EdtCliente.OnChange := nil; Self.EdtCliente.Text := Self.FFechamentoContaModelo.DataSet.FieldByName('cl_cod').AsString; Self.EdtCliente.OnChange := _event; Self.AtualizarTela; Self.FFocusControl := Self.gConta; end; Result := Self.ShowModal; end; procedure TFechamentoDeContaView.FormShow(Sender: TObject); begin if Self.FFocusControl <> nil then Self.FFocusControl.SetFocus; end; procedure TFechamentoDeContaView.gContaDblClick(Sender: TObject); begin {} end; procedure TFechamentoDeContaView.btnImprimirClick(Sender: TObject); var _chamada: TChamada; begin _chamada := TChamada.Create .Parametros(TMap.Create .Gravar('acao', Ord(opfdcImprimir)) ); Self.FControlador.Responder(_chamada); end; procedure TFechamentoDeContaView.btnIncAcrescimoClick(Sender: TObject); begin Self.txtAcrescimo.Text := IntToStr(StrToInt(Self.txtAcrescimo.Text) + 1); Self.AtualizarSumario(nil); end; end.
unit ejb_c; {This file was generated on 28 Feb 2001 10:06:55 GMT by version 03.03.03.C1.06} {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 ejb.idl. } {Delphi Pascal unit : ejb_c } {derived from IDL module : default } interface uses CORBA, ejb_i; type TSequence_of_AnyHelper = class; TSequence_of_AnyHelper = class class procedure Insert (var _A: CORBA.Any; const _Value : ejb_i.Sequence_of_Any); class function Extract(const _A: CORBA.Any): ejb_i.Sequence_of_Any; class function TypeCode : CORBA.TypeCode; class function RepositoryId: string; class function Read (const _Input : CORBA.InputStream) : ejb_i.Sequence_of_Any; class procedure Write(const _Output : CORBA.OutputStream; const _Value : ejb_i.Sequence_of_Any); end; implementation class procedure TSequence_of_AnyHelper.Insert(var _A : CORBA.Any; const _Value : ejb_i.Sequence_of_Any); var _Output : CORBA.OutputStream; begin _Output := ORB.CreateOutputStream; TSequence_of_AnyHelper.Write(_Output, _Value); ORB.PutAny(_A, TSequence_of_AnyHelper.TypeCode, _Output); end; class function TSequence_of_AnyHelper.Extract(const _A : CORBA.Any): ejb_i.Sequence_of_Any; var _Input : InputStream; begin Orb.GetAny(_A, _Input); Result := TSequence_of_AnyHelper.Read(_Input); end; class function TSequence_of_AnyHelper.TypeCode: CORBA.TypeCode; begin Result := ORB.CreateSequenceTC(0, ORB.CreateTC(Integer(tk_any))); end; class function TSequence_of_AnyHelper.RepositoryId: string; begin Result := 'IDL:Sequence_of_Any:1.0'; end; class function TSequence_of_AnyHelper.Read(const _Input : CORBA.InputStream) : ejb_i.Sequence_of_Any; var L0 : Cardinal; I0 : Cardinal; begin _Input.ReadULong(L0); SetLength(Result, L0); if (L0 > 0) then begin for I0 := 0 to High(Result) do begin _Input.ReadAny(Result[I0]); end; end; end; class procedure TSequence_of_AnyHelper.Write(const _Output: CORBA.OutputStream; const _Value: ejb_i.Sequence_of_Any); var L0 : Cardinal; I0 : Cardinal; begin L0 := Length(_Value); _Output.WriteULong(L0); if (L0 > 0) then begin for I0 := 0 to High(_Value) do begin _Output.WriteAny(_Value[I0]); end; end; end; initialization end.
const MaxTexto = 350; MaxPalabra = 20; type {rangos para arreglos con tope texto y palabra} RangoTexto = 1 .. MaxTexto; RangoTopeTexto = 0 .. MaxTexto; RangoPalabra = 1 .. MaxPalabra; RangoTopePalabra = 0 .. MaxPalabra; { definición del texto} TipoTexto = record texto : array[RangoTexto] of char; tope : RangoTopeTexto; end; { definición de palabra} TipoPalabra = record palabra : array [RangoPalabra] of char; tope : RangoTopePalabra; end; { clave de encriptación } TipoClave = record a,b : integer end; { estructura usada en subprograma LargosPalabras} listaInt = ^celda; celda = Record info : integer; sig : listaInt; end;
unit AppSettings; {$mode objfpc}{$H+} interface uses Typinfo, Classes, SysUtils, SynEdit, khexeditor; const {$IFDEF MSWINDOWS} DefaultFontName = 'Consolas'; {$ELSE} {$IFDEF LINUX} DefaultFontName = 'DejaVu Sans Mono'; {$ELSE} {$IFDEF DARWIN} DefaultFontName = 'Menlo'; {$ELSE} DefaultFontName = 'Courier New'; {$ENDIF} {$ENDIF} {$ENDIF} type { TCustomSettings } TCustomSettings = class(TPersistent) private FFileName: string; FIgnoreProperty: TStrings; procedure SetIgnoreProperty(Value: TStrings); protected public constructor Create(const FileName: string); virtual; destructor Destroy; override; procedure Save; virtual; procedure Load; virtual; property IgnoreProperty: TStrings read FIgnoreProperty write SetIgnoreProperty; end; { TAppSettings } TAppSettings = class(TCustomSettings) private FAsmVerbose: boolean; FFontName: string; FFontSize: integer; FLanguage: string; FLastProjectFolder: string; FReOpenAtStart: boolean; public constructor Create(const FileName: string); override; procedure Load; override; published //all published properties will be written to the settings file //General property Language: string read FLanguage write FLanguage; property ReOpenAtStart: boolean read FReOpenAtStart write FReOpenAtStart; property LastProjectFolder: string read FLastProjectFolder write FLastProjectFolder; //Editor property FontName: string read FFontName write FFontName; property FontSize: integer read FFontSize write FFontSize; //assembler property AsmVerbose: boolean read FAsmVerbose write FAsmVerbose; end; procedure CloneClass(Src, Dest: TPersistent); function GetPropCount(Instance: TPersistent): integer; function GetPropName(Instance: TPersistent; Index: integer): string; procedure UpdateSynEdit(var edt: TSynEdit); procedure UpdateHexEditor(var edt: TKHexEditor); var Settings: TAppSettings; implementation uses Forms, Graphics, XMLConf; procedure UpdateSynEdit(var edt: TSynEdit); begin edt.Font.Name := Settings.FontName; edt.Font.Pitch := fpDefault; edt.Font.Quality := fqDefault; edt.Font.Size := Settings.FontSize; end; procedure UpdateHexEditor(var edt: TKHexEditor); begin edt.Font.Name := Settings.FontName; edt.Font.Pitch := fpDefault; edt.Font.Quality := fqDefault; edt.Font.Size := Settings.FontSize; end; //returns the number of properties of a given object function GetPropCount(Instance: TPersistent): integer; var Data: PTypeData; begin Data := GetTypeData(Instance.Classinfo); Result := Data^.PropCount; end; //returns the property name of an instance at a certain index function GetPropName(Instance: TPersistent; Index: integer): string; var PropList: PPropList; PropInfo: PPropInfo; Data: PTypeData; begin Result := ''; Data := GetTypeData(Instance.Classinfo); GetMem(PropList, Data^.PropCount * Sizeof(PPropInfo)); try GetPropInfos(Instance.ClassInfo, PropList); PropInfo := PropList^[Index]; Result := PropInfo^.Name; finally FreeMem(PropList, Data^.PropCount * Sizeof(PPropInfo)); end; end; //copy RTTI properties from one class to another procedure CloneClass(Src, Dest: TPersistent); var Index: integer; SrcPropInfo: PPropInfo; DestPropInfo: PPropInfo; begin for Index := 0 to GetPropCount(Src) - 1 do begin if (CompareText(GetPropName(Src, Index), 'Name') = 0) then Continue; SrcPropInfo := GetPropInfo(Src.ClassInfo, GetPropName(Src, Index)); DestPropInfo := GetPropInfo(Dest.ClassInfo, GetPropName(Src, Index)); if DestPropInfo <> nil then if DestPropInfo^.PropType^.Kind = SrcPropInfo^.PropType^.Kind then begin case DestPropInfo^.PropType^.Kind of tkLString, tkString: SetStrProp(Dest, DestPropInfo, GetStrProp(Src, SrcPropInfo)); tkInteger, tkChar, tkEnumeration, tkSet: SetOrdProp(Dest, DestPropInfo, GetOrdProp(Src, SrcPropInfo)); tkFloat: SetFloatProp(Dest, DestPropInfo, GetFloatProp(Src, SrcPropInfo)); tkClass: begin if (TPersistent(GetOrdProp(Src, SrcPropInfo)) is TStrings) and (TPersistent(GetOrdProp(Dest, DestPropInfo)) is TStrings) then TPersistent(GetOrdProp(Dest, DestPropInfo)).Assign( TPersistent(GetOrdProp(Src, SrcPropInfo))); end; tkMethod: SetMethodProp(Dest, DestPropInfo, GetMethodProp(Src, SrcPropInfo)); end; end; end; end; { TAppSettings } constructor TAppSettings.Create(const FileName: string); begin inherited Create(FileName); //initialize all settings here //General FLanguage := 'System language'; FReOpenAtStart := True; FLastProjectFolder := ''; //Editor FFontName := DefaultFontName; //Assembler FAsmVerbose := True; FFontSize := 10; end; procedure TAppSettings.Load; begin inherited Load; //assign the default font in case the settings font is not available on the system if Screen.Fonts.IndexOf(FontName) = -1 then begin FontName := DefaultFontName; //in case not found on the system then assign fallback font if Screen.Fonts.IndexOf(FontName) = -1 then FontName := 'Courier New'; //if all fails then assign the first available font in the list if Screen.Fonts.IndexOf(FontName) = -1 then FontName := Screen.Fonts[0]; end; end; { TCustomSettings } procedure TCustomSettings.SetIgnoreProperty(Value: TStrings); begin FIgnoreProperty.Assign(Value); end; constructor TCustomSettings.Create(const FileName: string); begin FIgnoreProperty := TStringList.Create; FFileName := FileName; end; destructor TCustomSettings.Destroy; begin FIgnoreProperty.Free; inherited Destroy; end; procedure TCustomSettings.Save; var xml: TXMLConfig; idx: integer; PropName, PropPath: string; pt: TTypeKind; begin if FFileName = '' then exit; xml := TXMLConfig.Create(nil); try xml.Filename := FFileName; for idx := 0 to GetPropCount(Self) - 1 do begin PropName := GetPropName(Self, idx); if (FIgnoreProperty.Indexof(Propname) >= 0) then Continue; PropPath := '/Settings/' + PropName + '/Value'; pt := PropType(Self, GetPropName(Self, idx)); case pt of tkSString, tkLString, tkAString, tkWString, tkUString: xml.SetValue(PropPath, GetStrProp(Self, PropName)); tkChar, tkWChar, tkUChar, tkEnumeration, tkInteger, tkQWord: xml.SetValue(PropPath, GetOrdProp(Self, PropName)); tkBool: xml.SetValue(PropPath, GetEnumProp(Self, PropName)); tkInt64: xml.SetValue(PropPath, GetInt64Prop(Self, PropName)); tkFloat: xml.SetValue(PropPath, FloatToStr(GetFloatProp(Self, PropName))); tkClass: begin //saving classes if (TPersistent(GetOrdProp(Self, PropName)) is TStrings) then xml.SetValue(PropPath, TStrings(GetOrdProp(Self, PropName)).Text); end; else //this should never occur! raise Exception.CreateFmt('Unknown property type for property %s', [PropName]); end; end; finally xml.Flush; xml.Free; end; end; procedure TCustomSettings.Load; var xml: TXMLConfig; idx: integer; PropName, PropPath: string; pt: TTypeKind; begin if FFileName = '' then exit; xml := TXMLConfig.Create(nil); try xml.Filename := FFileName; for idx := 0 to GetPropCount(Self) - 1 do begin PropName := GetPropName(Self, idx); if (FIgnoreProperty.Indexof(Propname) >= 0) then Continue; PropPath := '/Settings/' + PropName + '/Value'; pt := PropType(Self, GetPropName(Self, idx)); case pt of tkSString, tkLString, tkAString, tkWString, tkUString: SetStrProp(Self, PropName, xml.GetValue(PropPath, GetStrProp(Self,PropName))); tkChar, tkWChar, tkUChar, tkEnumeration, tkInteger, tkQWord: SetOrdProp(Self, PropName, xml.GetValue(PropPath, GetOrdProp(Self,PropName))); tkBool: SetEnumProp(Self, PropName, xml.GetValue(PropPath, GetEnumProp(Self,PropName))); tkInt64: Setint64Prop(Self, PropName, xml.GetValue(PropPath, GetInt64Prop(Self,PropName))); tkFloat: SetFloatProp(Self, PropName, StrToFloat(xml.GetValue(PropPath, FloatToStr(GetFloatProp(Self,PropName))))); tkClass: begin //saving classes if (TPersistent(GetOrdProp(Self, PropName)) is TStrings) then TStrings(GetOrdProp(Self, PropName)).Text := xml.GetValue(PropPath, TStrings(GetOrdProp(Self, PropName)).Text); end; else //this should never occur! raise Exception.CreateFmt('Unknown property type for property %s', [PropName]); end; end; finally xml.Free; end; end; initialization Settings := TAppSettings.Create('easy80-ide.xml'); Settings.Load; finalization Settings.Free; end.
unit float32_2; interface implementation var A, B, C: Float64; procedure Test_Add(var A, B, C: Float64); begin A := 1.1; B := 1.2; C := A + B; Assert(C >= 2.3); end; procedure Test_Sub(var A, B, C: Float64); begin A := 1.1; B := 1.2; C := B - A; Assert(C >= 0.1); end; procedure Test_Mul(var A, B, C: Float64); begin A := 10.1; B := 2.0; C := A * B; Assert(C >= 20.2); end; procedure Test_Div(var A, B, C: Float64); begin A := 10.2; B := 2.0; C := A / B; Assert(C >= 5.1); end; initialization Test_Add(A, B, C); Test_Sub(A, B, C); Test_Mul(A, B, C); Test_Div(A, B, C); finalization end.
unit ncaFrmEditDesc; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxControls, cxContainer, cxEdit, cxTextEdit, cxMemo, StdCtrls, cxButtons, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, cxCurrencyEdit, cxLabel, dxGDIPlusClasses, ExtCtrls; type TFrmEditDesc = class(TForm) LMDSimplePanel2: TLMDSimplePanel; btnSalvar: TcxButton; btnCancelar: TcxButton; panValor: TLMDSimplePanel; cxLabel1: TcxLabel; edValor: TcxCurrencyEdit; panPerc: TLMDSimplePanel; cxLabel2: TcxLabel; edPerc: TcxCurrencyEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnSalvarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure edValorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edPercKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edValorPropertiesChange(Sender: TObject); procedure edPercPropertiesEditValueChanged(Sender: TObject); procedure edPercPropertiesChange(Sender: TObject); procedure edValorPropertiesEditValueChanged(Sender: TObject); private { Private declarations } FPerc: Boolean; FTotal : Currency; FCalculando : Boolean; procedure calcula; procedure FocusPerc; procedure FocusSalvar; public function Editar(aTotal: Currency; var aValor: Currency; var aPerc: Double; var aDescPerc: Boolean): Boolean; { Public declarations } end; resourcestring rsDescAcimaLimite = 'Desconto acima do percentual máximo permitido'; var FrmEditDesc: TFrmEditDesc; implementation uses ncaFrmPri, ncaDM, ncIDRecursos, ncClassesBase; {$R *.dfm} { TForm1 } procedure TFrmEditDesc.btnSalvarClick(Sender: TObject); begin edValor.PostEditValue; edPerc.PostEditValue; if not Dados.CM.UA.LimiteDescOk(edPerc.Value) then raise Exception.Create(rsDescAcimaLimite); ModalResult := mrOk; end; procedure TFrmEditDesc.calcula; begin if FCalculando then Exit; try FCalculando := True; if Fperc then begin if edPerc.Value>100 then begin edValor.Value := 0; edPerc.Value := 100; if edPerc.Focused then edPerc.SelectAll; end else edValor.Value := DuasCasas(FTotal * edPerc.Value / 100); end else begin if edValor.Value>FTotal then begin edPerc.Value := 100; edValor.Value := FTotal; if edValor.Focused then edValor.SelectAll; end else edPerc.Value := DuasCasas(edValor.Value / FTotal * 100); end; finally FCalculando := False; end; end; function TFrmEditDesc.Editar(aTotal: Currency; var aValor: Currency; var aPerc: Double; var aDescPerc: Boolean): Boolean; begin edValor.Value := aValor; FPerc := aDescPerc and (aPerc>0); edPerc.Value := aPerc; FTotal := aTotal; Calcula; ShowModal; if ModalResult=mrOk then begin aValor := edValor.Value; aPerc := edPerc.Value; aDescPerc := FPerc; Result := True; end else Result := False; end; procedure TFrmEditDesc.edPercKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of Key_Enter : FocusSalvar; Key_Up : edValor.SetFocus; end; end; procedure TFrmEditDesc.edPercPropertiesChange(Sender: TObject); begin if edPerc.Focused then edPerc.PostEditValue; end; procedure TFrmEditDesc.edPercPropertiesEditValueChanged(Sender: TObject); begin if edPerc.Focused then begin FPerc := True; Calcula; end; end; procedure TFrmEditDesc.edValorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of Key_Down, Key_Enter: FocusPerc; end; end; procedure TFrmEditDesc.edValorPropertiesChange(Sender: TObject); begin if edValor.Focused then edValor.PostEditValue; end; procedure TFrmEditDesc.edValorPropertiesEditValueChanged(Sender: TObject); begin if edValor.Focused then begin FPerc := False; Calcula; end; end; procedure TFrmEditDesc.FocusPerc; begin if edPerc.Enabled then edPerc.SetFocus else FocusSalvar; end; procedure TFrmEditDesc.FocusSalvar; begin if btnSalvar.Enabled then btnSalvar.SetFocus; end; procedure TFrmEditDesc.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmEditDesc.FormCreate(Sender: TObject); begin FCalculando := False; btnSalvar.Enabled := Permitido(daTraDesconto); end; procedure TFrmEditDesc.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of Key_F2, Key_F3 : if btnSalvar.Enabled then btnSalvar.Click; Key_Esc : ModalResult := mrCancel; end; end; procedure TFrmEditDesc.FormKeyPress(Sender: TObject; var Key: Char); begin if (Key in [#13, #27]) then Key := #0; end; end.
unit TestCast; { AFS 9 Jan 2000 This unit compiles but is not semantically meaningfull it is test cases for the code formatting utility This unit test type casts Borland style is that there is no space between the type & the bracket } interface function CastNumeric: integer; procedure MessWithObjects; implementation uses Classes, SysUtils, Dialogs, ComCtrls, StdCtrls; function CastNumeric: integer; var dValue: Double; crValue: Currency; begin dValue := Random (100) * PI; crValue := Currency (dValue); Result := Round (crValue); end; procedure MessWithObjects; var lcStrings: TStringList; lcObj: TObject; lp: Pointer; li: integer; begin lcStrings := TStringList.Create; try lcObj := lcStrings as TObject; lp := Pointer (lcObj); li := Integer (lp); ShowMessage (IntToStr (li)); { and back } lp := Pointer (li); lcObj := TObject (Pointer (li)); lcStrings := TStringList (TObject (Pointer (li))); finally lcStrings.Free; end; end; type TFred = (eFee, efi, eFo, Fum); TJim = (eMing, eMong, mMung, eCorWhatADonga); TNumber = integer; procedure UsertypeCast; var Fred: TFred; Jim: TJim; li: Integer; lj: TNumber; begin li := Random (3); Fred := TFred (li); Jim := TJim (Fred); lj := TNumber (Jim); end; { brackets at the LHS } procedure HardLeft; var lcStrings: TStringList; lcObj: TObject; begin lcStrings := TStringList.Create; try lcObj := lcStrings; if lcObj is TStrings then (lcObj as TStrings).ClassName; if lcObj is TStrings then begin (lcObj as TStrings).ClassName; end; if lcObj is TStrings then ((lcObj as TStrings)).ClassName; if lcObj is TStrings then begin ((lcObj as TStrings)).ClassName; end; finally lcStrings.Free; end; end; procedure UpDownClick(Sender: TObject; Button: TUDBtnType); begin ((Sender as TUpDown).Associate as TEdit).Modified := True; end; end.
unit MobilePermissions.Permissions.Android; interface uses {$IF CompilerVersion >= 33.0} System.Permissions, {$ENDIF} {$IFDEF ANDROID} Androidapi.Helpers, Androidapi.JNI.Os, Androidapi.JNI.JavaTypes, {$ENDIF} System.Character, System.SysUtils, System.StrUtils, MobilePermissions.Permissions.Interfaces; type TMobilePermissionsAndroid = class(TInterfacedObject, IMobilePermissions) private FAndroidVersion: Integer; procedure SetAndroidVersion; public function Request(Permissions: System.TArray<System.string>): IMobilePermissions; constructor create; destructor Destroy; override; class function New: IMobilePermissions; end; implementation { TMobilePermissionsAndroid } constructor TMobilePermissionsAndroid.create; begin FAndroidVersion := 0; end; destructor TMobilePermissionsAndroid.Destroy; begin inherited; end; procedure TMobilePermissionsAndroid.SetAndroidVersion; {$IFDEF ANDROID} var VersionOSStr : String; MajorVersion : string; i : Integer; {$ENDIF} begin if FAndroidVersion = 0 then begin {$IFDEF ANDROID} VersionOSStr := JStringToString(TJBuild_VERSION.JavaClass.RELEASE); for i := 0 to Pred(VersionOSStr.Length) do begin if not (VersionOSStr[i].IsNumber) then Break; MajorVersion := MajorVersion + VersionOSStr[i]; end; FAndroidVersion := StrToInt(MajorVersion); {$ENDIF} end; end; class function TMobilePermissionsAndroid.New: IMobilePermissions; begin result := Self.Create; end; function TMobilePermissionsAndroid.Request(Permissions: System.TArray<System.string>): IMobilePermissions; begin result := Self; SetAndroidVersion; {$IF CompilerVersion >= 33.0} if (FAndroidVersion > 6) then PermissionsService.RequestPermissions(Permissions, nil, nil); {$ENDIF} end; end.
unit Teste.ChangeSet.Adapter; interface uses DUnitX.TestFramework, System.JSON, System.JSON.Readers, Vigilante.Infra.ChangeSet.DataAdapter; type [TestFixture] TChangeSetAdapterJSONTest = class private FChangeSetItens: TJSONArray; FAdapter: IChangeSetAdapter; procedure CarregarChangeSetItens; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure CarregouApenasUmChangeSet; end; implementation uses System.IOUtils, System.SysUtils, System.Classes, System.Generics.Collections, Vigilante.Infra.ChangeSet.JSONDataAdapter, Vigilante.Aplicacao.SituacaoBuild, Vigilante.ChangeSetItem.Model, Teste.ChangeSet.JSONData; procedure TChangeSetAdapterJSONTest.Setup; begin CarregarChangeSetItens; end; procedure TChangeSetAdapterJSONTest.TearDown; begin FreeAndNil(FChangeSetItens) end; procedure TChangeSetAdapterJSONTest.CarregarChangeSetItens; begin if Assigned(FChangeSetItens) then FreeAndNil(FChangeSetItens); FChangeSetItens := TChangeSetJSONData.Pegar; FAdapter := TChangeSetAdapterJSON.Create(FChangeSetItens); end; procedure TChangeSetAdapterJSONTest.CarregouApenasUmChangeSet; const NOME = 'Jose da Silva Sauro'; DESCRICAO: array of string = [ 'Descri��o do commit', 'Descri��o do commit']; NOME_ARQUIVO = '/src/Classes/nomeDoArquivo.pas'; var _changeSet: TArray<TChangeSetItem>; _changeSetItem: TChangeSetItem; _passagem: integer; begin _changeSet := FAdapter.PegarChangesSet; Assert.AreEqual(2, Length(_changeSet)); _passagem := 0; for _changeSetItem in _changeSet do begin Assert.AreEqual(NOME, _changeSetItem.Autor); Assert.AreEqual(DESCRICAO[_passagem], _changeSetItem.Descricao); Assert.AreEqual(NOME_ARQUIVO, _changeSetItem.ArquivosAlterados.Text.Trim); inc(_passagem); end; end; initialization TDUnitX.RegisterTestFixture(TChangeSetAdapterJSONTest); end.
program Sample; procedure Proc(i: Integer); begin WriteLn(i); end; begin Proc('abc'); end.
unit Billiards.GameDay; interface uses Billiards.GameType, Billiards.Period, Billiards.Member; type TBilliardGameDay = class private fGameType: TBilliardGameType; fPeriod: TBilliardPeriod; public constructor Create; overload; constructor Create(ADate: TDate); overload; function ToString: string; override; property GameType: TBilliardGameType read fGameType write fGameType; property Period: TBilliardPeriod read fPeriod write fPeriod; end; var BilliardGameDay: TBilliardGameDay; implementation uses SysUtils; { TBilliardGameDay } constructor TBilliardGameDay.Create; begin Create(Now); end; constructor TBilliardGameDay.Create(ADate: TDate); begin inherited Create; fGameType := TBilliardGameType.Create(ADate); fPeriod := TBilliardPeriod.Create(ADate); end; function TBilliardGameDay.ToString: string; begin Result := '"GameDay": { '; Result := Result + #13#10 + fGameType.ToString; Result := Result + #13#10 + fPeriod.ToString; Result := Result + #13#10'}'; end; initialization finalization if Assigned(BilliardGameDay) then FreeAndNil(BilliardGameDay); end.
unit uFormSizeSelect; {$mode objfpc}{$H+} interface uses Classes, SysUtils, zipper, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Spin, Grids, ButtonPanel; type { TfrmFormSizeSelect } TfrmFormSizeSelect = class(TForm) ButtonPanel1: TButtonPanel; DrawGrid1: TDrawGrid; Label1: TLabel; Label2: TLabel; seWidth: TSpinEdit; seHeight: TSpinEdit; procedure DrawGrid1ColRowExchanged(Sender: TObject; IsColumn: Boolean; sIndex, tIndex: Integer); procedure DrawGrid1CompareCells(Sender: TObject; ACol, ARow, BCol, BRow: Integer; var Result: integer); procedure DrawGrid1DblClick(Sender: TObject); procedure DrawGrid1DrawCell(Sender: TObject; aCol, aRow: Integer; aRect: TRect; aState: TGridDrawState); procedure DrawGrid1SelectCell(Sender: TObject; aCol, aRow: Integer; var CanSelect: Boolean); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { private declarations } FTable: TFPList; // list of TDeviceSize procedure DoLoadFromDevices(XmlStream: TStream); function GetSdkPath: string; procedure TryLoadFromDevices; procedure ZipCreateStream(Sender: TObject; var AStream: TStream; AItem: TFullZipFileEntry); procedure ZipDoneStream(Sender: TObject; var AStream: TStream; AItem: TFullZipFileEntry); public { public declarations } procedure SetInitSize(AWidth, AHeight: Integer); end; var frmFormSizeSelect: TfrmFormSizeSelect; implementation uses IniFiles, FormPathMissing, LazIDEIntf, laz2_XMLRead, Laz2_DOM, LazUTF8; {$R *.lfm} type { TDeviceSize } TDeviceSize = class public Name: string; Width, Height: Integer; constructor Create(AName: string; AWidth, AHeight: Integer); end; { TDeviceSize } constructor TDeviceSize.Create(AName: string; AWidth, AHeight: Integer); begin Name := AName; Width := AWidth; Height := AHeight; end; { TfrmFormSizeSelect } procedure TfrmFormSizeSelect.FormCreate(Sender: TObject); begin FTable := TFPList.Create; TryLoadFromDevices; if FTable.Count = 0 then begin FTable.Add(TDeviceSize.Create('Default1', 240, 400)); FTable.Add(TDeviceSize.Create('Default2', 300, 600)); end; DrawGrid1.RowCount := 1 + FTable.Count; end; procedure TfrmFormSizeSelect.DrawGrid1SelectCell(Sender: TObject; aCol, aRow: Integer; var CanSelect: Boolean); begin if aRow > 0 then with TDeviceSize(FTable[aRow - 1]) do begin seWidth.Value := Width; seHeight.Value := Height; end; end; procedure TfrmFormSizeSelect.DrawGrid1DrawCell(Sender: TObject; aCol, aRow: Integer; aRect: TRect; aState: TGridDrawState); var s: string; begin if aRow = 0 then Exit; with TDeviceSize(FTable[aRow - 1]) do case aCol of 0: s := Name; 1: s := IntToStr(Width); 2: s := IntToStr(Height); end; with DrawGrid1.Canvas do TextOut(aRect.Left + 2, aRect.Top + 2, s); end; procedure TfrmFormSizeSelect.DrawGrid1DblClick(Sender: TObject); begin ModalResult := mrOK; end; procedure TfrmFormSizeSelect.DrawGrid1ColRowExchanged(Sender: TObject; IsColumn: Boolean; sIndex, tIndex: Integer); begin if not IsColumn then FTable.Exchange(sIndex - 1, tIndex - 1); end; procedure TfrmFormSizeSelect.DrawGrid1CompareCells(Sender: TObject; ACol, ARow, BCol, BRow: Integer; var Result: integer); begin case ACol of 0: Result := UTF8CompareText(TDeviceSize(FTable[ARow - 1]).Name, TDeviceSize(FTable[BRow - 1]).Name); 1: Result := TDeviceSize(FTable[ARow - 1]).Width - TDeviceSize(FTable[BRow - 1]).Width; 2: Result := TDeviceSize(FTable[ARow - 1]).Height - TDeviceSize(FTable[BRow - 1]).Height; end; if DrawGrid1.SortOrder = soDescending then Result := -Result; end; procedure TfrmFormSizeSelect.FormDestroy(Sender: TObject); var i: Integer; begin for i := 0 to FTable.Count - 1 do TObject(FTable[i]).Free; FTable.Free; end; procedure TfrmFormSizeSelect.ZipDoneStream(Sender: TObject; var AStream: TStream; AItem: TFullZipFileEntry); begin DoLoadFromDevices(AStream); end; procedure TfrmFormSizeSelect.ZipCreateStream(Sender: TObject; var AStream: TStream; AItem: TFullZipFileEntry); begin AStream := TMemoryStream.Create; AItem.Stream := AStream; end; procedure TfrmFormSizeSelect.TryLoadFromDevices; var SDKPath, f: string; fs: TStringList; ms: TMemoryStream; begin SDKPath := GetSdkPath; // "sdk\tools\lib\sdklib.jar" -> "\com\android\sdklib\devices\devices.xml" f := IncludeTrailingPathDelimiter(SDKPath) + 'tools' + PathDelim + 'lib' + PathDelim + 'sdklib.jar'; if FileExists(f) then begin with TUnZipper.Create do try OnCreateStream := @ZipCreateStream; OnDoneStream := @ZipDoneStream; FileName := f; Examine; fs := TStringList.Create; try fs.Add('com/android/sdklib/devices/devices.xml'); UnZipFiles(fs); // -> ZipDoneStream finally fs.Free; end; finally Free; end; end; f := IncludeTrailingPathDelimiter(SDKPath) + 'tools' + PathDelim + 'lib' + PathDelim + 'devices.xml'; if FileExists(f) then begin ms := TMemoryStream.Create; ms.LoadFromFile(f); DoLoadFromDevices(ms); end; end; function TfrmFormSizeSelect.GetSdkPath: string; begin with TIniFile.Create(IncludeTrailingPathDelimiter(LazarusIDE.GetPrimaryConfigPath) + 'JNIAndroidProject.ini') do try Result := ReadString('NewProject', 'PathToAndroidSDK', ''); finally Free end; if Result = '' then with TFormPathMissing.Create(Self) do try LabelPathTo.Caption := 'Path to Android SDK: [ex. C:\adt32\sdk]'; if ShowModal = mrOk then begin Result := PathMissing; with TIniFile.Create(IncludeTrailingPathDelimiter(LazarusIDE.GetPrimaryConfigPath) + 'JNIAndroidProject.ini') do try WriteString('NewProject', 'PathToAndroidSDK', Result); finally Free end; end; finally Free; end; end; procedure TfrmFormSizeSelect.DoLoadFromDevices(XmlStream: TStream); var xml: TXMLDocument; DeviceNode, NameNode, WNode, HNode, n: TDOMNode; begin XmlStream.Position := 0; ReadXMLFile(xml, XmlStream); try DeviceNode := xml.DocumentElement.FindNode('d:device'); while Assigned(DeviceNode) do begin NameNode := DeviceNode.FindNode('d:name'); n := DeviceNode.FindNode('d:hardware'); if n <> nil then n := n.FindNode('d:screen'); if n <> nil then n := n.FindNode('d:dimensions'); if n <> nil then begin WNode := n.FindNode('d:x-dimension'); HNode := n.FindNode('d:y-dimension'); end; if Assigned(NameNode) and Assigned(WNode) and Assigned(HNode) then FTable.Add(TDeviceSize.Create(NameNode.TextContent, StrToIntDef(WNode.TextContent, 0), StrToIntDef(HNode.TextContent, 0))); DeviceNode := DeviceNode.NextSibling; end; finally XmlStream.Free; xml.Free; end; end; procedure TfrmFormSizeSelect.SetInitSize(AWidth, AHeight: Integer); var i: Integer; begin for i := 0 to FTable.Count - 1 do with TDeviceSize(FTable[i]) do if (Width = AWidth) and (Height = AHeight) then begin DrawGrid1.Row := i + 1; Exit; end; seWidth.Value := AWidth; seHeight.Value := AHeight; end; end.
unit PRFWK_Conexao; interface uses PRFWK_Classe, SqlExpr, PRFWK_Utilidades, Midas, DB, AdoDB, StrUtils, DBXDynalink, DBXMySQL, DBXCommon; type TPRFWK_Conexao = class(TPRFWK_Classe) private aConexaoSql : TCustomConnection; aDriver : String; aNomeConexao : WideString; aVendorlib : String; aLibraryName : String; aDBXTrans : TDBXTransaction; aSQLTrans : Integer; public constructor Create; override; destructor Destroy; override; property conexaoSql:TCustomConnection read aConexaoSql write aConexaoSql; property driver:String read aDriver write aDriver; property nomeConexao:WideString read aNomeConexao write aNomeConexao; property vendorlib:String read aVendorlib write aVendorlib; property libraryName:String read aLibraryName write aLibraryName; procedure criarConexao(driver: String; nomeConexao: WideString); procedure conectar; procedure desconectar; procedure beginTransaction(tipoTransacaoDBX: Integer = TDBXIsolations.ReadCommitted); procedure commit; procedure rollback; published end; implementation { TConexao } {** * Construtor *} constructor TPRFWK_Conexao.Create; begin inherited; end; {** * Destrutor *} destructor TPRFWK_Conexao.Destroy; begin inherited; //desconecta e libera da memória a conexão aConexaoSql.Close; aConexaoSql.Free; end; {** * Método de criação de conexão *} procedure TPRFWK_Conexao.criarConexao(driver: String; nomeConexao: WideString); begin //armazena atributos aDriver := driver; aNomeConexao := nomeConexao; //verifica o tipo do driver if driver <> 'ADO' then begin aConexaoSql := TSQLConnection.Create(nil); TSQLConnection(aConexaoSql).LoadParamsOnConnect := false; TSQLConnection(aConexaoSql).ConnectionName := nomeConexao; TSQLConnection(aConexaoSql).DriverName := driver; TSQLConnection(aConexaoSql).LoadParamsFromIniFile( TPRFWK_Utilidades.obterInstancia().obterPastaProjeto() + 'dbxconnections.ini' ); TSQLConnection(aConexaoSql).LoginPrompt := false; TSQLConnection(aConexaoSql).KeepConnection := true; if aVendorLib <> '' then TSQLConnection(aConexaoSql).VendorLib := aVendorLib; if aLibraryName <> '' then TSQLConnection(aConexaoSql).LibraryName := aLibraryName; end else begin aConexaoSql := TADOConnection.Create(nil); nomeConexao := AnsiReplaceStr(nomeConexao, '[PASTA_PROJETO]', TPRFWK_Utilidades.obterInstancia().obterPastaProjeto()); TADOConnection(aConexaoSql).ConnectionString := nomeConexao; TADOConnection(aConexaoSql).KeepConnection := true; TADOConnection(aConexaoSql).LoginPrompt := false; TADOConnection(aConexaoSql).Mode := cmShareDenyNone; end; end; {** * Método de conexão ao banco *} procedure TPRFWK_Conexao.conectar; begin aConexaoSql.Open; end; {** * Método de desconexão ao banco *} procedure TPRFWK_Conexao.desconectar; begin aConexaoSql.Close; end; {** * Método que inicia a transação *} procedure TPRFWK_Conexao.beginTransaction(tipoTransacaoDBX: Integer = TDBXIsolations.ReadCommitted); begin if driver = 'ADO' then begin aSQLTrans := TADOConnection(aConexaoSql).BeginTrans; end else begin aDBXTrans := TSQLConnection(aConexaoSql).BeginTransaction(tipoTransacaoDBX); end; end; {** * Método que finaliza(commit) a transação *} procedure TPRFWK_Conexao.commit; begin if driver = 'ADO' then begin TADOConnection(aConexaoSql).CommitTrans; end else begin TSQLConnection(aConexaoSql).CommitFreeAndNil(aDBXTrans); end; end; {** * Método que realiza o rollback na transação *} procedure TPRFWK_Conexao.rollback; begin if driver = 'ADO' then begin TADOConnection(aConexaoSql).RollbackTrans; end else begin TSQLConnection(aConexaoSql).RollbackFreeAndNil(aDBXTrans); end; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.Bind.Components, Data.Bind.ObjectScope, Vcl.StdCtrls, Vcl.Buttons, System.Actions, Vcl.ActnList, Vcl.StdActns, System.ImageList, Vcl.ImgList, Data.Bind.EngExt, Vcl.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, Vcl.Bind.Editors; type TForm1 = class(TForm) Edit1: TEdit; Memo1: TMemo; ImageList1: TImageList; ActionList1: TActionList; FileExit1: TFileExit; BitBtn1: TBitBtn; ComboBox1: TComboBox; BindingsList1: TBindingsList; LinkControlToPropertyTextHint: TLinkControlToProperty; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure UpdateWord(Sender: TObject); procedure ComboBox1Change(Sender: TObject); private { Private-Deklarationen } str_MainWord : string; procedure UpdateFields; procedure InitializeStyles; public { Public-Deklarationen } end; var Form1: TForm1; implementation {$R *.dfm} uses Vcl.Themes ; procedure TForm1.ComboBox1Change(Sender: TObject); var s: string; begin s := ComboBox1.Text; TStyleManager.TrySetStyle(s); end; procedure TForm1.FormCreate(Sender: TObject); begin str_MainWord := 'Hello World'; UpdateFields; InitializeStyles; end; procedure TForm1.InitializeStyles; var i: Integer; s: string; begin // fetch all installed styles ComboBox1.Visible := TStyleManager.Enabled; if ComboBox1.Visible then begin // insert style names into combobox for i := 0 to length(TStyleManager.StyleNames) - 1 do begin ComboBox1.Items.Add( TStyleManager.StyleNames[i] ); end; s := TStyleManager.ActiveStyle.Name; ComboBox1.ItemIndex := ComboBox1.Items.IndexOf(s); end; end; procedure TForm1.UpdateFields; begin // update all Text Label1.Caption := str_MainWord; if str_MainWord<>Edit1.Text then begin Edit1.OnChange := NIL; Edit1.Text := str_MainWord; Edit1.OnChange := UpdateWord; end; if str_MainWord<>Memo1.Text then begin Memo1.OnChange := NIL; Memo1.Text := str_MainWord; Memo1.OnChange := UpdateWord; end; end; procedure TForm1.UpdateWord(Sender: TObject); begin // do that word if Sender is TEdit then str_MainWord := Edit1.Text; if Sender is TMemo then str_MainWord := Memo1.Text; UpdateFields; end; end.
{******************************************} { } { FastScript v1.9 } { UniDAC classes and functions } { } { Created by: Devart } { E-mail: unidac@devart.com } { } {******************************************} unit fs_iunidacrtti; interface {$i fs.inc} uses SysUtils, Classes, fs_iinterpreter, fs_itools, fs_idbrtti, fs_idacrtti, DB, Uni; type TfsUniDACRTTI = class(TComponent); // fake component implementation type TFunctions = class(TfsRTTIModule) private function CallMethod(Instance: TObject; ClassType: TClass; const MethodName: String; Caller: TfsMethodHelper): Variant; function GetProp(Instance: TObject; ClassType: TClass; const PropName: String): Variant; procedure SetProp(Instance: TObject; ClassType: TClass; const PropName: String; Value: Variant); public constructor Create(AScript: TfsScript); override; end; { TFunctions } constructor TFunctions.Create(AScript: TfsScript); begin inherited Create(AScript); with AScript do begin with AddClass(TUniConnection, 'TCustomDAConnection') do begin AddMethod('procedure Savepoint(const Name: string)', CallMethod); AddMethod('procedure RollbackToSavepoint(const Name: string)', CallMethod); AddMethod('procedure ReleaseSavepoint(const Name: string)', CallMethod); AddMethod('function ExecProc(Name: string; const Params: array of variant): variant', CallMethod); AddMethod('function ExecSQLEx(Text: string; const Params: array of variant): variant', CallMethod); AddMethod('function ExecProcEx(Name: string; const Params: array of variant): variant', CallMethod); AddProperty('ServerVersion', 'string', GetProp); AddProperty('ServerVersionFull', 'string', GetProp); AddProperty('ClientVersion', 'string', GetProp); end; AddClass(TUniConnectionOptions, 'TDAConnectionOptions'); with AddClass(TCustomUniDataSet, 'TCustomDADataSet') do begin AddMethod('procedure Lock', CallMethod); AddMethod('procedure Unlock', CallMethod); AddMethod('function OpenNext: boolean', CallMethod); AddMethod('procedure RefreshQuick(const CheckDeleted: boolean)', CallMethod); AddMethod('function FindParam(const Value: string): TUniParam', CallMethod); AddMethod('function ParamByName(const Value: string): TUniParam', CallMethod); end; AddClass(TUniParam, 'TDAParam'); with AddClass(TUniParams, 'TDAParams') do begin AddMethod('function FindParam(const Value: string): TUniParam', CallMethod); AddMethod('function ParamByName(const Value: string): TUniParam', CallMethod); end; AddEnum('TLockMode', 'lmNone, lmPessimistic, lmOptimistic'); AddClass(TUniDataSetOptions, 'TDADataSetOptions'); AddClass(TUniQuery, 'TCustomUniDataSet'); with AddClass(TUniTable, 'TCustomUniDataSet') do begin AddMethod('procedure PrepareSQL', CallMethod); AddProperty('TableName', 'string', GetProp, SetProp); AddProperty('OrderFields', 'string', GetProp, SetProp); end; with AddClass(TUniStoredProc, 'TCustomUniDataSet') do begin AddMethod('procedure ExecProc', CallMethod); AddMethod('procedure PrepareSQL(IsQuery: boolean = False)', CallMethod); AddProperty('StoredProcName', 'string', GetProp, SetProp); end; end; end; function TFunctions.CallMethod(Instance: TObject; ClassType: TClass; const MethodName: String; Caller: TfsMethodHelper): Variant; begin Result := 0; if ClassType = TUniConnection then begin if MethodName = 'SAVEPOINT' then TUniConnection(Instance).Savepoint(Caller.Params[0]) else if MethodName = 'ROLLBACKTOSAVEPOINT' then TUniConnection(Instance).RollbackToSavepoint(Caller.Params[0]) else if MethodName = 'RELEASESAVEPOINT' then TUniConnection(Instance).ReleaseSavepoint(Caller.Params[0]) else if MethodName = 'EXECPROC' then Result := TUniConnection(Instance).ExecProc(Caller.Params[0], [Caller.Params[1]]) else if MethodName = 'EXECSQLEX' then Result := TUniConnection(Instance).ExecSQLEx(Caller.Params[0], [Caller.Params[1]]) else if MethodName = 'EXECPROCEX' then Result := TUniConnection(Instance).ExecProcEx(Caller.Params[0], [Caller.Params[1]]); end else if ClassType = TCustomUniDataSet then begin if MethodName = 'LOCK' then TCustomUniDataSet(Instance).Lock else if MethodName = 'UNLOCK' then TCustomUniDataSet(Instance).Unlock else if MethodName = 'OPENNEXT' then Result := TCustomUniDataSet(Instance).OpenNext else if MethodName = 'REFRESHQUICK' then TCustomUniDataSet(Instance).RefreshQuick(Caller.Params[0]) else if MethodName = 'FINDPARAM' then Result := Integer(Pointer(TCustomUniDataSet(Instance).FindParam(Caller.Params[0]))) else if MethodName = 'PARAMBYNAME' then Result := Integer(Pointer(TCustomUniDataSet(Instance).ParamByName(Caller.Params[0]))); end else if ClassType = TUniParams then begin if MethodName = 'FINDPARAM' then Result := Integer(Pointer(TUniParams(Instance).FindParam(Caller.Params[0]))) else if MethodName = 'PARAMBYNAME' then Result := Integer(Pointer(TUniParams(Instance).ParamByName(Caller.Params[0]))); end else if ClassType = TUniTable then begin if MethodName = 'PREPARESQL' then TUniTable(Instance).PrepareSQL; end else if ClassType = TUniStoredProc then begin if MethodName = 'PREPARESQL' then TUniStoredProc(Instance).PrepareSQL(Caller.Params[0]) else if MethodName = 'EXECPROC' then TUniStoredProc(Instance).ExecProc; end; end; function TFunctions.GetProp(Instance: TObject; ClassType: TClass; const PropName: String): Variant; begin Result := 0; if ClassType = TUniConnection then begin if PropName = 'CLIENTVERSION' then Result := TUniConnection(Instance).ClientVersion else if PropName = 'SERVERVERSION' then Result := TUniConnection(Instance).ServerVersion else if PropName = 'SERVERVERSIONFULL' then Result := TUniConnection(Instance).ServerVersionFull; end else if ClassType = TUniTable then begin if PropName = 'TABLENAME' then Result := TUniTable(Instance).TableName else if PropName = 'ORDERFIELDS' then Result := TUniTable(Instance).OrderFields; end else if ClassType = TUniStoredProc then begin if PropName = 'STOREDPROCNAME' then Result := TUniStoredProc(Instance).StoredProcName; end; end; procedure TFunctions.SetProp(Instance: TObject; ClassType: TClass; const PropName: String; Value: Variant); begin if ClassType = TUniTable then begin if PropName = 'TABLENAME' then TUniTable(Instance).TableName := Value else if PropName = 'ORDERFIELDS' then TUniTable(Instance).OrderFields := Value; end else if ClassType = TUniStoredProc then begin if PropName = 'STOREDPROCNAME' then TUniStoredProc(Instance).StoredProcName := Value; end; end; initialization fsRTTIModules.Add(TFunctions); finalization if fsRTTIModules <> nil then fsRTTIModules.Remove(TFunctions); end.
{------ Snake Invasion ------------------------------------------ by Gabor Kotik github: codexclusive Demonstrates how to implement graphics in Free Pascal. The program draws a given number of snakes on the screen and moves them around automatically. Snakes avoid obstacles and do not crash with each other. To create maintainable code, the snake is defined as an object. Drawing is done by using the Mem[] array. ----------------------------------------------------------------} program SnakeInv; uses Crt, Ports; type { a point on the character screen } Point = record X : Shortint; Y : Shortint; end; const VideoSeg = $B800; VB_speed = 6; nSnakes = 40; { textures from ASCII table } tEmpty = $00; tFrame = $DB; { a square } tWall = $DB; tHead = $E9; tBody = $04; { a diamond } { colors } cEmpty = $00; { black } cFrame = $08; { dark gray } cWall = $04; { red } cHead = $0F; { white } { body colors } cBody : array[1..8] of Byte = ($0A, { light green } $0B, { light cyan } $0C, { light red } $0D, { light magenta } $0E, { yellow } $02, { green } $03, { cyan } $05); { magenta } { directions } Left : Point = (X : -1; Y : 0); Right : Point = (X : 1; Y : 0); Up : Point = (X : 0; Y : -1); Down : Point = (X : 0; Y : 1); NoMove : Point = (X : 0; Y : 0); {------------------------- Snake object -------------------------} type Snake = object Pos : array[0..8] of Point; NextMoves : array[1..3] of Point; constructor Init(Dir: Point); procedure Draw; procedure Move; procedure Turn; procedure GetNextMoves; procedure ValidateMoves; function ValidPoint(P : Point) : Boolean; function ValidStart(StartP, Dir : Point) : Boolean; function ValidMove(Dir : Point) : Boolean; function CanMove : Boolean; end; var Snakes : array[1..nSnakes] of Snake; OrigMode : Integer; { original text mode } {----------------- global procedures & functions ----------------} procedure DrawChar(X, Y, Txt, Col : Byte); var Offset : Word; begin Offset := X * 2 + Y * 160; Mem[VideoSeg:Offset] := Txt; { store texture } Inc(Offset); Mem[VideoSeg:Offset] := Col; { store color } end; procedure InitScreen; var I, J : Byte; begin { remember original text mode } OrigMode := LastMode; { switch to 80x50 text mode } TextMode(C80 + Font8x8); { draw empty characters } for I := 0 to 79 do for J := 0 to 49 do DrawChar(I, J, tEmpty, cEmpty); end; procedure DoneScreen; begin { switch back to original mode } TextMode(OrigMode); end; function VB_in_progress : Boolean; begin VB_in_progress := ((Port[$03DA] and $08) = 0); end; procedure VerticalBlank(Speed : Byte); var I : Byte; begin for I := 1 to Speed do begin repeat until not (VB_in_progress); repeat until (VB_in_progress); end; end; procedure DrawFrame; { draw a rectangular frame around the game area } var I : Byte; begin { top & bottom } for I := 0 to 79 do begin DrawChar(I, 0, tFrame, cFrame); DrawChar(I, 1, tFrame, cFrame); DrawChar(I, 48, tFrame, cFrame); DrawChar(I, 49, tFrame, cFrame); end; { left & right } for I := 1 to 48 do begin DrawChar( 0, I, tFrame, cFrame); DrawChar( 1, I, tFrame, cFrame); DrawChar(78, I, tFrame, cFrame); DrawChar(79, I, tFrame, cFrame); end; end; procedure DrawWalls; { draw vertical walls that snakes need to avoid } var I, J : Byte; P : Point; begin for I := 0 to 4 do begin { top & bottom } for J := 0 to 7 do begin P.X := I * 14 + 11; P.Y := J + 2; DrawChar(P.X, P.Y, tWall, cWall); DrawChar(P.X, P.Y + 38, tWall, cWall); Inc(P.X); DrawChar(P.X, P.Y, tWall, cWall); DrawChar(P.X, P.Y + 38, tWall, cWall); end; end; for I := 0 to 3 do begin { middle } for J := 0 to 7 do begin P.X := I * 14 + 18; P.Y := J + 21; DrawChar(P.X, P.Y, tWall, cWall); Inc(P.X); DrawChar(P.X, P.Y, tWall, cWall); end; end; end; procedure InitSnakes; var I : Byte; begin for I := 1 to nSnakes do begin case Random(4) of 0 : Snakes[I].Init(Left); 1 : Snakes[I].Init(Right); 2 : Snakes[I].Init(Up); 3 : Snakes[I].Init(Down); end; Snakes[I].Draw; end; ReadKey; end; procedure MoveSnakes; var I : Byte; begin repeat VerticalBlank(VB_speed); { move all snakes } for I := 1 to nSnakes do Snakes[I].Move; until KeyPressed; ReadKey; { from buffer } end; {-------------------- methods of Snake object -------------------} constructor Snake.Init(Dir : Point); var Start : Point; I : Byte; begin repeat Start.X := Random(68) + 6; Start.Y := Random(38) + 6; until ValidStart(Start, Dir); for I := 0 to 8 do begin Pos[I].X := Start.X - Dir.X * I; Pos[I].Y := Start.Y - Dir.Y * I; end; end; procedure Snake.Draw; var I : Byte; begin DrawChar(Pos[0].X, Pos[0].Y, tHead, cHead); for I := 1 to 8 do DrawChar(Pos[I].X, Pos[I].Y, tBody, cBody[I]); end; procedure Snake.Move; var I : Byte; begin if not (CanMove) then Turn; if not (CanMove) then Turn else begin { clear tail from screen } DrawChar(Pos[8].X, Pos[8].Y, tEmpty, cEmpty); { shift positions } for I := 7 downto 0 do Pos[I + 1] := Pos[I]; { define new head } Inc(Pos[0].X, NextMoves[1].X); Inc(Pos[0].Y, NextMoves[1].Y); Self.Draw; end; end; procedure Snake.Turn; var NewPos : array[0..8] of Point; I : Byte; begin for I := 0 to 8 do NewPos[I] := Pos[8 - I]; for I := 0 to 8 do Pos[I] := NewPos[I]; end; procedure Snake.GetNextMoves; { find possible directions for the next move } var PrevMove : Point; TempMove : Point; begin PrevMove.X := Pos[0].X - Pos[1].X; PrevMove.Y := Pos[0].Y - Pos[1].Y; NextMoves[1] := PrevMove; if (PrevMove.X = 0) then { previous move vertical } begin NextMoves[2] := Left; NextMoves[3] := Right; end; if (PrevMove.Y = 0) then { previous move horizontal } begin NextMoves[2] := Up; NextMoves[3] := Down; end; { shuffle directions according to } { given probabilities } if (Random(2) = 0) then begin TempMove := NextMoves[2]; NextMoves[2] := NextMoves[3]; NextMoves[3] := TempMove; end; if (Random(10) = 0) then begin TempMove := NextMoves[1]; NextMoves[1] := NextMoves[2]; NextMoves[2] := TempMove; end; end; procedure Snake.ValidateMoves; { store the next valid move to NextMoves[1] } { if there is no valid move, NextMoves[1]=(0,0) } var NewDir : Point; begin if ValidMove(NextMoves[1]) then NewDir := NextMoves[1] else if ValidMove(NextMoves[2]) then NewDir := NextMoves[2] else if ValidMove(NextMoves[3]) then NewDir := NextMoves[3] else NewDir := NoMove; NextMoves[1] := NewDir; end; function Snake.ValidPoint(P : Point) : Boolean; var Offset : Integer; OnScreen : Boolean; Occupied : Boolean; begin Offset := P.X * 2 + P.Y * 160; OnScreen := (P.X >= 0) and (P.X <= 79) and (P.Y >= 0) and (P.Y <= 49); Occupied := (Mem[VideoSeg:Word(Offset)] <> tEmpty); ValidPoint := (OnScreen) and (not(Occupied)); end; function Snake.ValidStart(StartP, Dir : Point) : Boolean; { check whether the rectangle around the Snake is empty } { } { example: Dir = Left } { } { R = rectangle } { S = starting point } { } { RRRRRRRRRRR } { RSRRRRRRRRR } { RRRRRRRRRRR } { } { Rectangle points } { and starting point } { must be empty, } { otherwise invalid. } var I, J : Byte; V : Boolean; Corner : Point; APoint : Point; begin { find one corner of the rectangle } Corner := StartP; Inc(Corner.X, Dir.X + Dir.Y); Inc(Corner.Y, Dir.X + Dir.Y); V := True; { loop through every point } APoint := Corner; for I := 0 to 2 do begin for J := 0 to 10 do begin if not(ValidPoint(APoint)) then V := False; Dec(APoint.X, Dir.X); Dec(APoint.Y, Dir.Y); end; Dec(APoint.X, Dir.Y); Dec(APoint.Y, Dir.X); Inc(APoint.X, Dir.X * 11); Inc(APoint.Y, Dir.Y * 11); end; { valid if all points are empty } ValidStart := V; end; function Snake.ValidMove(Dir : Point) : Boolean; { check whether the six points in front of the snake are empty } { } { example: Dir = Down } { } { H = head } { B = body } { T = test points } { } { BBBBBB } { B B } { H } { TTT } { TTT } { } { All test points } { must be empty, } { otherwise the move } { is invalid. } var Point1 : Point; Point2 : Point; V : Boolean; I : Byte; begin Point1 := Pos[0]; V := True; Inc(Point1.X, Dir.X + Dir.Y); Inc(Point1.Y, Dir.X + Dir.Y); Point2.X := Point1.X + Dir.X; Point2.Y := Point1.Y + Dir.Y; for I := 0 to 2 do begin if not(ValidPoint(Point1)) then V := False; if not(ValidPoint(Point2)) then V := False; Dec(Point1.X, Dir.Y); Dec(Point1.Y, Dir.X); Dec(Point2.X, Dir.Y); Dec(Point2.Y, Dir.X); end; ValidMove := V; end; function Snake.CanMove : Boolean; var C1, C2 : Boolean; begin Self.GetNextMoves; Self.ValidateMoves; C1 := (NextMoves[1].X = 0); C2 := (NextMoves[1].Y = 0); CanMove := C1 xor C2; end; { main program } begin Randomize; InitScreen; DrawFrame; DrawWalls; InitSnakes; MoveSnakes; DoneScreen; end.
unit JK.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, HGM.Controls.SpinEdit; type TLang = record Code:string; Desc:string; end; TLangList = TList<TLang>; TFormMain = class(TForm) PanelLangs: TPanel; ListViewLangs: TListView; Label1: TLabel; Panel1: TPanel; Panel2: TPanel; EditText: TEdit; Button1: TButton; Label2: TLabel; ListViewResult: TListView; ComboBoxLang: TComboBox; SpinEditCount: TlkSpinEdit; Panel3: TPanel; Label3: TLabel; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public FLang:TLangList; end; var FormMain: TFormMain; implementation uses IdHTTP; {$R *.dfm} procedure ReadLangCSV(FN:TFileName; FieldSeparator:Char; var List:TLangList); var SData, SRow:TStrings; i:integer; Lang:TLang; begin SData:=TStringList.Create; SData.LoadFromFile(FN); List.Clear; if SData.Count > 0 then begin SRow:=TStringList.Create; SRow.Delimiter:=FieldSeparator; SRow.StrictDelimiter:=True; for i := 0 to SData.Count - 1 do begin SRow.DelimitedText:=SData[i]; try Lang.Code:=SRow.Strings[0]; Lang.Desc:=SRow.Strings[1]; List.Add(Lang); except end; end; SRow.Free; end; SData.Free; end; function TranslateGoogle(Text, myLang, toLang:string; var Err:Boolean):string; var HTTP:TIdHTTP; PostData:TStringList; Response:TStringStream; begin Result:=''; HTTP:=TIdHTTP.Create(nil); Text:=StringReplace(Text, '...', '', [rfReplaceAll]); Text:=StringReplace(Text, #13#10, ' ', [rfReplaceAll]); PostData:=TStringList.Create; PostData.Add('sl='+myLang); PostData.Add('tl='+toLang); PostData.Add('js=n'); PostData.add('prev=_t'); PostData.Add('hl='+myLang); PostData.Add('ie=UTF-8'); PostData.add('eotf=1'); PostData.Add('text='+Text); PostData.Add('client=x'); Response:=TStringStream.Create(''); Err:=False; try try HTTP.Post('http://translate.google.ru/translate_a/t', PostData, Response); Result:=UTF8ToWideString(Response.DataString); if Result.Length > 0 then Delete(Result, 1, 1); if Result.Length > 0 then Delete(Result, Result.Length, 1); except Err:=True; end; finally PostData.Free; HTTP.Free; Response.Free; end; end; procedure InsertResult(LV:TListView; L1, L2:TLang; Res:string); begin with LV.Items.Add do begin Caption:=L1.Desc; SubItems.Add('to'); SubItems.Add(L2.Desc); SubItems.Add(Res); end; Application.ProcessMessages; end; procedure TFormMain.Button1Click(Sender: TObject); var i, r: Integer; L1, L2:TLang; res, tg:string; Err:Boolean; SLang:TLang; begin r:=ComboBoxLang.ItemIndex; if r >= 0 then L1:=FLang[r] else begin L1.Code:='ru'; L1.Desc:='Russian'; end; SLang:=L1; tg:=EditText.Text; Randomize; ListViewResult.Clear; for i:= 1 to SpinEditCount.Value do begin res:=''; while res = '' do begin repeat r:=Random(FLang.Count) until FLang[r].Code <> L2.Code; L2:=FLang[r]; res:=TranslateGoogle(tg, L1.Code, L2.Code, Err); if Err then Sleep(4000) else Sleep(1000); end; tg:=res; InsertResult(ListViewResult, L1, L2, res); L1:=L2; end; L2:=SLang; res:=TranslateGoogle(tg, L1.Code, L2.Code, Err); InsertResult(ListViewResult, L1, L2, res); end; procedure TFormMain.FormCreate(Sender: TObject); var i, s: Integer; begin FLang:=TLangList.Create; ReadLangCSV(ExtractFilePath(Application.ExeName)+'\langs.csv', ';', FLang); ComboBoxLang.Items.Clear; ListViewLangs.Items.Clear; s:=-1; for i:= 0 to FLang.Count-1 do with ListViewLangs.Items.Add do begin Caption:=FLang[i].Desc; SubItems.Add(FLang[i].Code); ComboBoxLang.Items.Add(Caption); if FLang[i].Code = 'ru' then s:=i; end; ComboBoxLang.ItemIndex:=s; end; end.
unit ccBaseFrame; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, ExtCtrls, StdCtrls, IniFiles; type TCalcCompleteEvent = procedure (Sender: TObject; AMsg: String; IsOK: Boolean) of object; { TBaseFrame } TBaseFrame = class(TFrame) Bevel1: TBevel; ImageBevel: TBevel; GeometryImage: TImage; EquationImage: TImage; ImagePanel: TPanel; Panel2: TPanel; procedure DataChanged(Sender: TObject); procedure UnitsChanged(Sender: TObject); private { private declarations } FOnCalcComplete: TCalcCompleteEvent; protected FIniKey: String; FEditLeft: Integer; FControlDist: Integer; FErrMsg: string; procedure ClearResults; virtual; function IsValidComboValue(AControl: TWinControl; out AMsg: String): Boolean; function IsValidNumber(AControl: TWinControl; out AMsg: String): Boolean; function IsValidPositive(AControl: TWinControl; out AMsg: String): Boolean; procedure SetEditLeft(AValue: Integer); virtual; public { public declarations } constructor Create(AOwner: TComponent); virtual; procedure Calculate; virtual; function ValidData(out AMsg: String; out AControl: TWinControl): Boolean; virtual; procedure ReadFromIni(ini: TCustomIniFile); virtual; procedure WriteToIni(ini: TCustomIniFile); virtual; property ControlDist: integer read FControlDist; property EditLeft: Integer read FEditLeft write SetEditLeft; property ErrMsg: String read FErrMsg; property OnCalcComplete: TCalcCompleteEvent read FOnCalcComplete write FOnCalcComplete; end; implementation {$R *.lfm} uses ccStrings; constructor TBaseFrame.Create(AOwner: TComponent); begin inherited; FControlDist := 12; end; procedure TBaseFrame.Calculate; begin end; procedure TBaseFrame.ClearResults; begin end; procedure TBaseFrame.DataChanged(Sender: TObject); begin ClearResults; end; function TBaseFrame.IsValidNumber(AControl: TWinControl; out AMsg: String): Boolean; var value: Extended; begin Result := false; if (AControl is TEdit) then begin if (AControl as TEdit).Text = '' then begin AMsg := SInputRequired; exit; end; if not TryStrToFloat((AControl as TEdit).Text, value) then begin AMsg := SNumberRequired; exit; end; end; Result := true; end; function TBaseFrame.IsValidPositive(AControl: TWinControl; out AMsg: String): Boolean; var value: Double; begin Result := false; if (AControl is TEdit) then begin if (AControl as TEdit).Text = '' then begin AMsg := SInputRequired; exit; end; if not TryStrToFloat((AControl as TEdit).Text, value) then begin AMsg := SNumberRequired; exit; end; if value < 0 then begin AMsg := SPositiveNumberRequired; exit; end; if value = 0 then begin AMsg := SMustNotBeZero; exit; end; end; Result := true; end; function TBaseFrame.IsValidComboValue(AControl: TWinControl; out AMsg: String): Boolean; begin Result := false; if (AControl is TCombobox) then begin if (AControl as TCombobox).ItemIndex < 0 then begin AMsg := SInputRequired; exit; end; end; Result := true; end; procedure TBaseFrame.ReadFromIni(ini: TCustomIniFile); begin end; procedure TBaseFrame.SetEditLeft(AValue: Integer); begin if AValue = FEditLeft then exit; FEditLeft := AValue; end; procedure TBaseFrame.UnitsChanged(Sender: TObject); begin Calculate; end; function TBaseFrame.ValidData(out AMsg: String; out AControl: TWinControl): Boolean; begin Result := true; end; procedure TBaseFrame.WriteToIni(ini: TCustomIniFile); begin end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2015-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Beacon.Components; interface uses System.Classes, System.SysUtils, System.Beacon, System.Bluetooth, System.NetConsts; type /// <summary> /// Exception type for the beacon Components /// </summary> EBeaconComponentException = class(EComponentError); ///<summary>TBeaconRegionItem is the class to hold the information about a registered region. </summary> TBeaconRegionItem = class(TCollectionItem) private FMinor: Integer; FMajor: Integer; FGUID: TGUID; FKindofBeacon: TKindofBeacon; FEddyUID: TEddystoneUID; FEddyStInstance: string; FManufacturerID: Integer; procedure SetGUID(const AValue: TGUID); procedure SetMajor(AValue: Integer); procedure SetMinor(AValue: Integer); procedure SetUUID(const AValue: string); function GetUUID: string; function GetEddyNamespace: string; procedure SetEddyNamespace(const AValue: string); function GetEddyInstance: string; procedure SetEddyInstance(const AValue: string); procedure SetManufacturerID(const AValue: string); function GetManufacturerID: string; public /// <summary> /// Creates a new TBeaconRegionItem object /// </summary> constructor Create(Collection: TCollection); override; /// <summary> /// Overrides the base class assign method to copy the data from another TBeaconRegionItem /// </summary> procedure Assign(Source: TPersistent); override; /// <summary> /// GUID used to monitor the region /// </summary> property GUID: TGUID read FGUID write SetGUID; /// <summary> /// ManufacturerID to Integer. /// </summary> property ManufacturerIdToInt: Integer read FManufacturerID default MANUFATURER_ID_ALL; published /// <summary> /// UUID is a GUID used to monitor the region /// </summary> property UUID: string read GetUUID write SetUUID; /// <summary> /// Major is an identifier to filter the UUID region. /// MAJOR_REGION_ALL constant as value indicates we are monitoring all major values in the region /// </summary> property Major: Integer read FMajor write SetMajor default MAJOR_REGION_ALL; /// <summary> /// Minor is an identifier to filter the UUID region. /// MINOR_REGION_ALL constant as value indicates we are monitoring all minor values in the region /// </summary> property Minor: Integer read FMinor write SetMinor default MINOR_REGION_ALL; /// <summary> /// KindofBeacon is the beacon specification to be set. /// </summary> property KindofBeacon: TKindofBeacon read FKindofBeacon write FKindofBeacon default TKindofBeacon.iBAltBeacons; /// <summary> /// EddyNamespace is the Namespace ID for the Eddystone-UID Beacon. /// </summary> property EddyNamespace: string read GetEddyNamespace write SetEddyNamespace; /// <summary> /// EddyInstance is the Instance ID for the Eddystone-UID Beacon. /// </summary> property EddyInstance: string read GetEddyInstance write SetEddyInstance; /// <summary> /// IDManufacturer is a unique numeric identifier for each Bluetooth SIG member company requesting one. /// These are assigned by the Bluetooth SIG. Currently used in the manufacturer specific data (AdvertiseData) packet. /// </summary> property IDManufacturer: string read GetManufacturerID write SetManufacturerID; end; /// <summary> /// TBeaconRegionCollection is a collection holding a list of beacon regions /// </summary> TBeaconRegionCollection = class(TOwnedCollection) private FOnChange: TNotifyEvent; function GetItem(Index: Integer): TBeaconRegionItem; procedure SetItem(Index: Integer; const Value: TBeaconRegionItem); protected procedure Update(Item: TCollectionItem); override; public /// <summary> /// Items is the property to access created beacon region items. /// </summary> property Items[Index: Integer]: TBeaconRegionItem read GetItem write SetItem; default; /// <summary> /// OnChangeEvent is fired each time a item changes. /// </summary> property OnChange: TNotifyEvent read FOnChange write FOnChange; end; /// <summary> /// Beacon component is used to monitorize a list of beacon regions, getting events indicating when we enter/exit /// from a region or beacon, and changes on the proximity of a beacon. /// </summary> TCustomBeacon = class(TComponent) const EDDY_UID_INSTANCE_ALL = '-1'; private FBeaconManager: TBeaconManager; FEnabled: Boolean; FOnBeaconEnter: TBeaconEnterExitEvent; FOnCalcDistance: TBeaconCalcDistanceEvent; FOnCalculateDistances: TBeaconsCalcDistancesEvent; FOnBeaconProximity: TBeaconProximityEvent; FOnBeaconExit: TBeaconEnterExitEvent; FOnEnterRegion: TBeaconRegionEvent; FOnBeaconsEnterRegion: TBeaconsRegionEvent; FMonitorizedRegions: TBeaconRegionCollection; FOldMonitorizedRegions: TBeaconRegionCollection; FOnExitRegion: TBeaconRegionEvent; FOnBeaconsExitRegion: TBeaconsRegionEvent; FOnParseManufacturerData: TParseManufacturerDataEvent; FOnParseServiceData: TParseServiceDataEvent; FOnNewBLEScanFilter: TNewBLEScanFilterEvent; FOnBeaconEddystoneURL: TBeaconEddystoneURLEvent; FOnBeaconEddystoneTLM: TBeaconEddystoneTLMEvent; FOnBeaconError: TBeaconErrorEvent; FLock: TObject; FMode: TBeaconScanMode; FKindofBeacons: TKindofBeacons; FCurrentList: TBeaconList; FBeaconDeathTime: integer; FScanningTime: integer; FScanningSleepingTime: integer; FSPC: Single; FCalcMode: TBeaconCalcMode; procedure SetEnabled(const Value: Boolean); procedure SetMonitorizedRegions(const Value: TBeaconRegionCollection); procedure OnListChange(Sender: TObject); procedure CheckEvents; procedure SetMode(const Value: TBeaconScanMode); procedure SetKindofBeacons(const Value: TKindofBeacons); procedure DoBeaconEnter(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); procedure DoBeaconExit(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); procedure DoParseManufacturerData(const Sender:TObject; const AData: TManufacturerRawData; var BeaconInfo: TBeaconInfo; var Handled: Boolean); procedure DoParseServiceData(const Sender: TObject; const AData: TServiceDataRawData; var BeaconInfo: TBeaconInfo; var Handled: Boolean); procedure DoNewEddystoneURL(const Sender: TObject; const ABeacon: IBeacon; const AEddystoneURL: TEddystoneURL); procedure DoNewEddystoneTLM(const Sender: TObject; const ABeacon: IBeacon; const AEddystoneTLM: TEddystoneTLM); procedure DoBeaconCalcDistance(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Word; ATxPower, ARssi: Integer; var NewDistance: Double); overload; procedure DoBeaconCalcDistance(const Sender: TObject; const ABeacon: IBeacon; ATxPower, ARssi: Integer; var NewDistance: Double); overload; procedure DoBeaconChangedProximity(const Sender: TObject; const ABeacon: IBeacon; CurrentProximity: TBeaconProximity); procedure DoRegionEnter(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Integer); procedure DoBeaconsRegionEnter(const Sender: TObject; const ABeaconRegion: TBeaconsRegion); procedure DoRegionExit(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Integer); procedure DoBeaconsRegionExit(const Sender: TObject; const ABeaconRegion: TBeaconsRegion); procedure DoNewBLEScanFilter(const Sender: TObject; AKindofScanFilter: TKindofScanFilter; const ABluetoothLEScanFilter: TBluetoothLEScanFilter); procedure DoBeaconError(const Sender: TObject; ABeaconError: TBeaconError; const AMsg: string; const ABeacon: TBeaconInfo); procedure SaveBeaconList(const CurrentBeaconList: TBeaconList); function GetBeaconList: TBeaconList; procedure SetBeaconDeathTime(const Value: integer); procedure SetScanningSleepingTime(const Value: integer); procedure SetScanningTime(const Value: integer); procedure SetSPC(const Value: Single); function GetCalcMode: TBeaconCalcMode; procedure SetCalcMode(const Value: TBeaconCalcMode); protected procedure Loaded; override; public /// <summary> /// Creates a new instance of the component /// </summary> constructor Create(AOwner: TComponent); override; destructor Destroy; override; /// <summary> /// StartScan starts to monitorize beacons in the regions indicated in Monitorized regions. /// </summary> procedure StartScan; /// <summary> /// StopScan stops to monitorize beacons. /// </summary> procedure StopScan; /// <summary> /// Returns the nearest beacon to our position, nil if we don't have /// </summary> function Nearest: IBeacon; /// <summary> /// BeaconList grants access to a list of currently detected beacons /// </summary> property BeaconList: TBeaconList read GetBeaconList; /// <summary> /// Enabled property, when true, the component starts to scan regions automatically /// </summary> property Enabled: Boolean read FEnabled write SetEnabled default False; /// <summary> /// Mode indicates which kind of beacons are going to be monitorized /// TBeaconScanMode.Standard is the default /// </summary> property Mode: TBeaconScanMode read FMode write SetMode default TBeaconScanMode.Extended; /// <summary> /// KindofBeacons indicates which kind of beacons are going to be monitorized /// if we choose extended as a Mode. All kind of beacons together are the default. /// </summary> property ModeExtended: TKindofBeacons read FKindofBeacons write SetKindofBeacons; /// <summary> /// MonitorizedRegions is the list of regions to be monitorized. /// </summary> property MonitorizedRegions: TBeaconRegionCollection read FMonitorizedRegions write SetMonitorizedRegions; /// <summary> /// Indicates the time in ms to consider that the beacon signal has been lost /// </summary> property BeaconDeathTime: integer read FBeaconDeathTime write SetBeaconDeathTime default KBEACONDEATHTIME; /// <summary> /// Signal propagation constant value used to calculate the distance /// This value is ignored in iOS Standard mode. /// </summary> property SPC: Single read FSPC write SetSPC; /// <summary> /// Time that we are going to scan each cicle in ms. /// This value is ignored in iOS Standard mode. /// </summary> property ScanningTime: integer read FScanningTime write SetScanningTime default SCANNING_TIME; /// <summary> /// Paused time between scan cicles. /// This value is ignored in iOS Standard mode. /// </summary> property ScanningSleepingTime: integer read FScanningSleepingTime write SetScanningSleepingTime default SCANNING_SLEEPINGTIME; /// <summary> /// Indicates the current beacon type used to provide Rssi and distance values. /// By default we are working in Stabilized mode. /// </summary> property CalcMode: TBeaconCalcMode read GetCalcMode write SetCalcMode default TBeaconCalcMode.Stabilized; /// <summary> /// OnBeaconEnter is fired each time a Beacon is reachable, this means that there is a new beacon on our list /// </summary> property OnBeaconEnter: TBeaconEnterExitEvent read FOnBeaconEnter write FOnBeaconEnter; /// <summary> /// OnBeaconExit is fired each time a Beacon is not reachable. /// </summary> property OnBeaconExit: TBeaconEnterExitEvent read FOnBeaconExit write FOnBeaconExit; /// <summary> /// OnBeaconProximity is fired when a beacon proximity value changes /// </summary> property OnBeaconProximity: TBeaconProximityEvent read FOnBeaconProximity write FOnBeaconProximity; /// <summary> /// OnEnterRegion is fired first time a beacon from a region is reachable. /// </summary> property OnEnterRegion: TBeaconRegionEvent read FOnEnterRegion write FOnEnterRegion; /// <summary> /// OnBeaconsEnterRegion is fired first time a beacon from a region is reachable. /// </summary> property OnBeaconsEnterRegion: TBeaconsRegionEvent read FOnBeaconsEnterRegion write FOnBeaconsEnterRegion; /// <summary> /// OnExitRegion is fired when all beacons for a region are out of reach. /// </summary> property OnExitRegion: TBeaconRegionEvent read FOnExitRegion write FOnExitRegion; /// <summary> /// OnBeaconsExitRegion is fired when all beacons for a region are out of reach. /// </summary> property OnBeaconsExitRegion: TBeaconsRegionEvent read FOnBeaconsExitRegion write FOnBeaconsExitRegion; /// <summary> /// OnCalcDistance is fired when we are about to calculate the distance to a beacon. You can use it to provide /// your own algorithm to calculate the distance. /// </summary> property OnCalcDistance: TBeaconCalcDistanceEvent read FOnCalcDistance write FOnCalcDistance; /// <summary> /// OnCalculateDistances is fired when we are about to calculate the distance to a any kind beacon. You can use it to provide /// your own algorithm to calculate the distance. /// </summary> property OnCalculateDistances: TBeaconsCalcDistancesEvent read FOnCalculateDistances write FOnCalculateDistances; /// <summary> /// Allows to add your own parser to get the information from manufacturer data section inside the /// device advertise data. /// </summary> property OnParseManufacturerData: TParseManufacturerDataEvent read FOnParseManufacturerData write FOnParseManufacturerData; /// <summary> /// Allows to add your own parser to get the information from service data section inside the /// device advertise data. /// </summary> property OnParseServiceData: TParseServiceDataEvent read FOnParseServiceData write FOnParseServiceData; /// <summary> /// This event is fired every time a new scan filter is created and befor being added to FilterList wich will be past to /// the BLE scanner. So to check the filter builded and change it if needed. /// </summary> property OnNewBLEScanFilter: TNewBLEScanFilterEvent read FOnNewBLEScanFilter write FOnNewBLEScanFilter; /// <summary> /// OnNewEddystoneURL is fired each time a New Eddystone-URL is found. /// It needs to be assigned to work, so if not assigned no Eddystone-URL will be add to the Beacon List. /// </summary> property OnNewEddystoneURL: TBeaconEddystoneURLEvent read FOnBeaconEddystoneURL write FOnBeaconEddystoneURL; /// <summary> /// OnNewEddystoneTLM is fired each time a New Eddystone-TLM is found. /// </summary> property OnNewEddystoneTLM: TBeaconEddystoneTLMEvent read FOnBeaconEddystoneTLM write FOnBeaconEddystoneTLM; /// <summary> /// OnBeaconError is fired each time we detect an error inside a beacon /// </summary> property OnBeaconError: TBeaconErrorEvent read FOnBeaconError write FOnBeaconError; end; /// <summary> /// Beacon component is used to monitorize a list of beacon regions, getting events indicating when we enter/exit /// from a region or beacon, and changes on the proximity of a beacon. /// </summary> [ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidiOS or pfidAndroid or pidWinNX32 or pidWinIoT32)] TBeacon = class(TCustomBeacon) published property Enabled; property Mode; property ModeExtended; property MonitorizedRegions; property BeaconDeathTime; property SPC; property ScanningTime; property ScanningSleepingTime; property CalcMode; property OnBeaconEnter; property OnBeaconExit; property OnBeaconProximity; property OnEnterRegion; property OnExitRegion; property OnBeaconsEnterRegion; property OnBeaconsExitRegion; property OnCalcDistance; property OnCalculateDistances; property OnParseManufacturerData; property OnParseServiceData; property OnNewBLEScanFilter; property OnNewEddystoneURL; property OnNewEddystoneTLM; property OnBeaconError; end; /// <summary> /// Beacon Device Mode indicates which kind of beacon is going to be advertised. /// </summary> {$SCOPEDENUMS ON} TBeaconDeviceMode = (Standard, Alternative, EddystoneUID, EddystoneURL); {$SCOPEDENUMS OFF} TCustomBeaconDevice = class(TComponent) private FBeaconAdvertiser: TBeaconAdvertiser; FEnabled: Boolean; FBeaconDeviceMode: TBeaconDeviceMode; FManufacturerId: Word; FBeaconType: Word; FGUID: TGUID; FMinor: Integer; FMajor: Integer; FTxPower: ShortInt; FMFGReserved: Byte; FEddystoneNamespace: string; FEddystoneInstance: string; FEddystoneURL: string; FDeviceType: TAdvertiseDeviceFormat; FNamespaceGenerator: TNamespaceGeneratorMethod; procedure SetEnabled(const Value: Boolean); procedure SetMID(const Value: string); function GetMID: string; procedure SetType(const Value: TBeaconDeviceMode); function GetType: TBeaconDeviceMode; procedure SetGUID(const Value: TGUID); procedure SetMajor(const Value: Integer); procedure SetMinor(const Value: Integer); procedure SetUUID(const Value: string); function GetUUID: string; procedure SetTxPower(const Value: ShortInt); procedure SetMFGReserved(const Value: Byte); function GetMFGReserved: Byte; protected /// <summary> Method called after component is loaded </summary> procedure Loaded; override; public /// <summary> /// Creates a new instance of the component /// </summary> constructor Create(AOwner: TComponent); override; /// <summary> /// Initializes this Beacon device with an existing GattServer /// </summary> procedure InitWithGattServer(AGattServer: TBluetoothGattServer); /// <summary> /// Starts to asdvertise proximity data /// </summary> procedure StartAdvertise; /// <summary> /// Stops asdvertising proximity data /// </summary> procedure StopAdvertise; /// <summary> /// Enabled property, when true, the component starts advertise proximity data /// </summary> property Enabled: Boolean read FEnabled write SetEnabled default False; /// <summary> /// Manufacturer Id /// </summary> property ManufacturerId: string read GetMID write SetMID; /// <summary> /// Beacon type /// </summary> property BeaconType: TBeaconDeviceMode read GetType write SetType default TBeaconDeviceMode.Standard; /// <summary> /// GUID representing this beacon proximity UUID /// </summary> property GUID: TGUID read FGUID write SetGUID; /// <summary> /// UUID is a GUID representing this beacon proximity UUID /// </summary> property UUID: string read GetUUID write SetUUID; /// <summary> /// Major number for the region that this beacon is advertising /// </summary> property Major: Integer read FMajor write SetMajor default 0; /// <summary> /// Minor number for the region that this beacon is advertising /// </summary> property Minor: Integer read FMinor write SetMinor default 0; /// <summary> /// TxPower that this beacon is advertising /// </summary> property TxPower: ShortInt read FTxPower write SetTxPower default TXPOWER_IDETERMINATED; /// <summary> /// Just for AltBeacon, reserved for use by the manufacturer to implement special features. /// </summary> property MFGReserved: Byte read GetMFGReserved write SetMFGReserved default 0; /// <summary> /// Namespace for the Eddystone-UID frame. It must be a string of 20 hexadecimal digits when NamespaceGenerator is set to ngNone /// </summary> property EddystoneNamespace: string read FEddystoneNamespace write FEddystoneNamespace; /// <summary> /// Instance for the Eddystone-UID frame. It must be a string of 12 hexadecimal digits representing 6 bytes /// </summary> property EddystoneInstance: string read FEddystoneInstance write FEddystoneInstance; /// <summary> /// URL broadcasted by the Eddystone-URL frame. /// </summary> property EddystoneURL: string read FEddystoneURL write FEddystoneURL; /// <summary> Method used to generate the Eddystone-UID namespace: /// <para>* ngNone indicates that EddystoneNamespace property will be used as a 20 hex digits string representing the 10-bytes namespace value </para> /// <para>* ngHashFQDN takes the first 10 bytes of an SHA-1 hash of the domain name specified in EddystoneNamespace </para> /// <para>* ngElidedUUID uses GUID property removing bytes 5 - 10 (inclusive) to generate 10-bytes namespace </para> /// </summary> property NamespaceGenerator: TNamespaceGeneratorMethod read FNamespaceGenerator write FNamespaceGenerator default ngHashFQDN; end; [ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidiOS or pfidAndroid or pidWinNX32 or pidWinIoT32)] TBeaconDevice = class(TCustomBeaconDevice) published /// <summary> /// Enabled property, when true, the component starts advertise proximity data /// </summary> property Enabled; /// <summary> /// Manufacturer Id /// </summary> property ManufacturerId; /// <summary> /// Beacon type /// </summary> property BeaconType; /// <summary> /// UUID is a GUID representing this beacon proximity UUID /// </summary> property UUID; /// <summary> /// Major number for the region that this beacon is advertising /// </summary> property Major; /// <summary> /// Minor number for the region that this beacon is advertising /// </summary> property Minor; /// <summary> /// TxPower that this beacon is advertising /// </summary> property TxPower; /// <summary> /// Just for AltBeacon, reserved for use by the manufacturer to implement special features. /// </summary> property MFGReserved; /// <summary> /// Namespace for the Eddystone-UID frame. It must be a string of 20 hexadecimal digits when NamespaceGenerator is set to ngNone /// </summary> property EddystoneNamespace; /// <summary> /// Instance for the Eddystone-UID frame. It must be a string of 12 hexadecimal digits representing 6 bytes /// </summary> property EddystoneInstance; /// <summary> /// URL broadcasted by the Eddystone-URL frame. /// </summary> property EddystoneURL; /// <summary> Method used to generate the Eddystone-UID namespace: /// <para>* ngNone indicates that EddystoneNamespace property will be used as a 20 hex digits string representing the 10-bytes namespace value </para> /// <para>* ngHashFQDN takes the first 10 bytes of an SHA-1 hash of the domain name specified in EddystoneNamespace </para> /// <para>* ngElidedUUID uses GUID property removing bytes 5 - 10 (inclusive) to generate 10-bytes namespace </para> /// </summary> property NamespaceGenerator; end; implementation { TBeacon } constructor TCustomBeacon.Create(AOwner: TComponent); begin inherited; FLock := TObject.Create; FMode := TBeaconScanMode.Extended; FKindofBeacons := [TKindofBeacon.iBeacons, TKindofBeacon.AltBeacons, TKindofBeacon.Eddystones]; FCalcMode := TBeaconCalcMode.Stabilized; if not (csDesigning in ComponentState) then begin FBeaconManager := TBeaconManager.GetBeaconManager(FMode); FBeaconManager.KindofBeacons := FKindofBeacons; CheckEvents; TBluetoothLEManager.Current.EnableBluetooth; end; FOldMonitorizedRegions := TBeaconRegionCollection.Create(Self, TBeaconRegionItem); FMonitorizedRegions := TBeaconRegionCollection.Create(Self, TBeaconRegionItem); FMonitorizedRegions.OnChange := OnListChange; FBeaconDeathTime := KBEACONDEATHTIME; FSPC := SIGNAL_PROPAGATION_CONSTANT; FScanningTime := SCANNING_TIME; FScanningSleepingTime := SCANNING_SLEEPINGTIME; end; destructor TCustomBeacon.Destroy; begin FBeaconManager.Free; FMonitorizedRegions.Free; FOldMonitorizedRegions.Free; inherited; end; procedure TCustomBeacon.SaveBeaconList(const CurrentBeaconList: TBeaconList); begin TMonitor.Enter(FLock); try FCurrentList := CurrentBeaconList; finally TMonitor.Exit(FLock); end; end; procedure TCustomBeacon.DoBeaconEnter(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); begin SaveBeaconList(CurrentBeaconList); if Assigned(FOnBeaconEnter) then begin TThread.Synchronize(nil, procedure begin if Assigned(FOnBeaconEnter) then FOnBeaconEnter(Self, ABeacon, CurrentBeaconList); end); end; end; procedure TCustomBeacon.DoBeaconExit(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); begin SaveBeaconList(CurrentBeaconList); if Assigned(FOnBeaconExit) then TThread.Synchronize(nil, procedure begin if Assigned(FOnBeaconExit) then FOnBeaconExit(Sender, ABeacon, CurrentBeaconList); end); end; procedure TCustomBeacon.DoParseManufacturerData(const Sender:TObject; const AData: TManufacturerRawData; var BeaconInfo: TBeaconInfo; var Handled: Boolean); begin if Assigned(FOnParseManufacturerData) then FOnParseManufacturerData(Self, AData, BeaconInfo, Handled); end; procedure TCustomBeacon.DoParseServiceData(const Sender: TObject; const AData: TServiceDataRawData; var BeaconInfo: TBeaconInfo; var Handled: Boolean); begin if Assigned(FOnParseServiceData) then FOnParseServiceData(Self, AData, BeaconInfo, Handled); end; procedure TCustomBeacon.DoNewEddystoneURL(const Sender: TObject; const ABeacon: IBeacon; const AEddystoneURL: TEddystoneURL); var LEddystoneURL: TEddystoneURL; begin LEddystoneURL := AEddystoneURL; if Assigned(FOnBeaconEddystoneURL) then TThread.Synchronize(nil, procedure begin if Assigned(FOnBeaconEddystoneURL) then FOnBeaconEddystoneURL(Self, ABeacon, LEddystoneURL); end); end; procedure TCustomBeacon.DoNewEddystoneTLM(const Sender: TObject; const ABeacon: IBeacon; const AEddystoneTLM: TEddystoneTLM); var LEddystoneTLM: TEddystoneTLM; begin LEddystoneTLM := AEddystoneTLM; if Assigned(FOnBeaconEddystoneTLM) then TThread.Synchronize(nil, procedure begin if Assigned(FOnBeaconEddystoneTLM) then FOnBeaconEddystoneTLM(Self, ABeacon, LEddystoneTLM); end); end; procedure TCustomBeacon.DoBeaconCalcDistance(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Word; ATxPower, ARssi: Integer; var NewDistance: Double); begin if Assigned(FOnCalcDistance) then FOnCalcDistance(Self, UUID, AMajor, AMinor, ATxPower, ARssi, NewDistance); end; procedure TCustomBeacon.DoBeaconCalcDistance(const Sender: TObject; const ABeacon: IBeacon; ATxPower, ARssi: Integer; var NewDistance: Double); begin if Assigned(FOnCalculateDistances) then FOnCalculateDistances(Self, ABeacon, ATxPower, ARssi, NewDistance); end; procedure TCustomBeacon.DoBeaconChangedProximity(const Sender: TObject; const ABeacon: IBeacon; CurrentProximity: TBeaconProximity); begin if Assigned(FOnBeaconProximity) then begin TThread.Synchronize(nil, procedure begin if Assigned(FOnBeaconProximity) then FOnBeaconProximity(Self, ABeacon, CurrentProximity); end); end; end; procedure TCustomBeacon.DoRegionEnter(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Integer); var LUUID: TGUID; begin if Assigned(FOnEnterRegion) then begin LUUID := UUID; TThread.Synchronize(nil, procedure begin if Assigned(FOnEnterRegion) then FOnEnterRegion(Self, LUUID, AMajor, AMinor); end); end; end; procedure TCustomBeacon.DoBeaconsRegionEnter(const Sender: TObject; const ABeaconRegion: TBeaconsRegion); var LBeaconRegion: TBeaconsRegion; begin if Assigned(FOnBeaconsEnterRegion) then begin LBeaconRegion := ABeaconRegion; TThread.Synchronize(nil, procedure begin if Assigned(FOnBeaconsEnterRegion) then FOnBeaconsEnterRegion(Self, LBeaconRegion); end); end; end; procedure TCustomBeacon.DoRegionExit(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Integer); var LUUID: TGUID; begin if Assigned(FOnExitRegion) then begin LUUID := UUID; TThread.Synchronize(nil, procedure begin if Assigned(FOnExitRegion) then FOnExitRegion(Self, LUUID, AMajor, AMinor); end); end; end; procedure TCustomBeacon.DoBeaconsRegionExit(const Sender: TObject; const ABeaconRegion: TBeaconsRegion); var LBeaconRegion: TBeaconsRegion; begin if Assigned(FOnBeaconsExitRegion) then begin LBeaconRegion := ABeaconRegion; TThread.Synchronize(nil, procedure begin if Assigned(FOnBeaconsExitRegion) then FOnBeaconsExitRegion(Self, LBeaconRegion); end); end; end; procedure TCustomBeacon.DoNewBLEScanFilter(const Sender: TObject; AKindofScanFilter: TKindofScanFilter; const ABluetoothLEScanFilter: TBluetoothLEScanFilter); begin if Assigned(FOnNewBLEScanFilter) then TThread.Synchronize(nil, procedure begin if Assigned(FOnNewBLEScanFilter) then FOnNewBLEScanFilter(Self, AKindofScanFilter, ABluetoothLEScanFilter); end); end; procedure TCustomBeacon.DoBeaconError(const Sender: TObject; ABeaconError: TBeaconError; const AMsg: string; const ABeacon: TBeaconInfo); var LBeacon: TBeaconInfo; begin if Assigned(FOnBeaconError) then begin LBeacon := ABeacon; TThread.Synchronize(nil, procedure begin if Assigned(FOnBeaconError) then FOnBeaconError(Self, ABeaconError, AMsg, LBeacon); end); end; end; function TCustomBeacon.GetBeaconList: TBeaconList; begin if Enabled then begin TMonitor.Enter(FLock); try Result := FCurrentList; finally TMonitor.Exit(FLock); end; end else Result := nil; end; function TCustomBeacon.GetCalcMode: TBeaconCalcMode; begin Result := FCalcMode; end; procedure TCustomBeacon.Loaded; begin inherited; if not (csDesigning in ComponentState) then StartScan; end; function TCustomBeacon.Nearest: IBeacon; begin if Enabled then Result := FBeaconManager.Nearest else Result := nil; end; procedure TCustomBeacon.OnListChange(Sender: TObject); var I: Integer; LBeaconsRegion: TBeaconsRegion; begin if not (csDesigning in ComponentState) then for I := 0 to FOldMonitorizedRegions.Count - 1 do begin LBeaconsRegion := Default(TBeaconsRegion); LBeaconsRegion.KindofBeacon := FOldMonitorizedRegions[I].KindofBeacon; case LBeaconsRegion.KindofBeacon of TKindofBeacon.Eddystones: begin if (FOldMonitorizedRegions[I].FEddyStInstance = EDDY_UID_INSTANCE_ALL) then LBeaconsRegion.EddysUIDRegion.Initialize(FOldMonitorizedRegions[I].FEddyUID.Namespace) else LBeaconsRegion.EddysUIDRegion.Initialize(FOldMonitorizedRegions[I].FEddyUID.Namespace, FOldMonitorizedRegions[I].FEddyUID.Instance); end; TKindofBeacon.iBeacons, TKindofBeacon.AltBeacons, TKindofBeacon.iBAltBeacons: begin LBeaconsRegion.iBAltBeaconRegion.Initialize(FOldMonitorizedRegions[I].GUID, FOldMonitorizedRegions[I].Major, FOldMonitorizedRegions[I].Minor, FOldMonitorizedRegions[I].KindofBeacon, MANUFATURER_ID_ALL); end; end; FBeaconManager.UnRegisterBeacons(LBeaconsRegion); end; FOldMonitorizedRegions.Clear; FOldMonitorizedRegions.Assign(FMonitorizedRegions); if not (csDesigning in ComponentState) then begin for I := 0 to FMonitorizedRegions.Count - 1 do begin LBeaconsRegion := Default(TBeaconsRegion); LBeaconsRegion.KindofBeacon := FMonitorizedRegions[I].KindofBeacon; case LBeaconsRegion.KindofBeacon of TKindofBeacon.Eddystones: begin if (FMonitorizedRegions[I].FEddyStInstance = EDDY_UID_INSTANCE_ALL) then LBeaconsRegion.EddysUIDRegion.Initialize(FMonitorizedRegions[I].FEddyUID.Namespace) else LBeaconsRegion.EddysUIDRegion.Initialize(FMonitorizedRegions[I].FEddyUID.Namespace, FMonitorizedRegions[I].FEddyUID.Instance); end; TKindofBeacon.iBeacons, TKindofBeacon.AltBeacons, TKindofBeacon.iBAltBeacons: begin LBeaconsRegion.iBAltBeaconRegion.Initialize(FMonitorizedRegions[I].GUID, FMonitorizedRegions[I].Major, FMonitorizedRegions[I].Minor, FMonitorizedRegions[I].KindofBeacon, FMonitorizedRegions[I].ManufacturerIdToInt); end; end; FBeaconManager.RegisterBeacons(LBeaconsRegion); end; if FBeaconManager.NumberofBeaconsRegistered = 0 then StopScan; end; end; procedure TCustomBeacon.SetBeaconDeathTime(const Value: integer); begin FBeaconDeathTime := Value; if not (csDesigning in ComponentState) then FBeaconManager.BeaconDeathTime := FBeaconDeathTime; end; procedure TCustomBeacon.SetCalcMode(const Value: TBeaconCalcMode); begin FCalcMode := Value; end; procedure TCustomBeacon.SetEnabled(const Value: Boolean); begin if Value <> FEnabled then begin FEnabled := Value; if (not (csDesigning in ComponentState)) and (not (csLoading in ComponentState)) then if Enabled then StartScan else StopScan; end; end; procedure TCustomBeacon.SetMode(const Value: TBeaconScanMode); begin if FMode <> Value then begin FMode := Value; if not (csDesigning in ComponentState) then begin if FBeaconManager <> nil then begin FBeaconManager.StopScan; FBeaconManager.Free; end; SaveBeaconList(nil); FBeaconManager := TBeaconManager.GetBeaconManager(FMode); FBeaconManager.KindofBeacons := FKindofBeacons; if not (csLoading in ComponentState) then FEnabled := False; end; end; end; procedure TCustomBeacon.SetKindofBeacons(const Value: TKindofBeacons); begin if FKindofBeacons <> Value then begin FKindofBeacons := Value; if not (csDesigning in ComponentState) and (FMode = TBeaconScanMode.Extended) then begin if FBeaconManager <> nil then begin FBeaconManager.StopScan; FBeaconManager.Free; SaveBeaconList(nil); FBeaconManager := TBeaconManager.GetBeaconManager(FMode); FBeaconManager.KindofBeacons := FKindofBeacons; FKindofBeacons:= FBeaconManager.KindofBeacons; if not (csLoading in ComponentState) then FEnabled := False; end; end else if TKindofBeacon.iBAltBeacons in FKindofBeacons then begin Exclude(FKindofBeacons, TKindofBeacon.iBAltBeacons); FKindofBeacons := FKindofBeacons + [TKindofBeacon.iBeacons, TKindofBeacon.AltBeacons]; end; end; end; procedure TCustomBeacon.SetMonitorizedRegions(const Value: TBeaconRegionCollection); begin if FMonitorizedRegions <> Value then FMonitorizedRegions.Assign(Value); end; procedure TCustomBeacon.SetScanningSleepingTime(const Value: integer); begin FScanningSleepingTime := Value; if not (csDesigning in ComponentState) then FBeaconManager.ScanningSleepingTime := FScanningSleepingTime; end; procedure TCustomBeacon.SetScanningTime(const Value: integer); begin FScanningTime := Value; if not (csDesigning in ComponentState) then FBeaconManager.ScanningTime := FScanningTime; end; procedure TCustomBeacon.SetSPC(const Value: Single); begin FSPC := Value; if not (csDesigning in ComponentState) then FBeaconManager.SPC := FSPC; end; procedure TCustomBeacon.StartScan; begin if Enabled and (TBluetoothLEManager.Current.CurrentAdapter <> nil) then begin OnListChange(Self); CheckEvents; FBeaconManager.CalcMode := FCalcMode; FBeaconManager.StartScan; end; end; procedure TCustomBeacon.StopScan; begin FBeaconManager.StopScan; end; procedure TCustomBeacon.CheckEvents; begin FBeaconManager.OnBeaconEnter := DoBeaconEnter; FBeaconManager.OnBeaconExit := DoBeaconExit; if Assigned(FOnBeaconProximity) then FBeaconManager.OnBeaconProximity := DoBeaconChangedProximity else FBeaconManager.OnBeaconProximity := nil; FBeaconManager.OnEnterRegion := DoRegionEnter; FBeaconManager.OnBeaconsEnterRegion := DoBeaconsRegionEnter; FBeaconManager.OnExitRegion := DoRegionExit; FBeaconManager.OnBeaconsExitRegion := DoBeaconsRegionExit; FBeaconManager.OnNewBLEScanFilterEvent := DoNewBLEScanFilter; FBeaconManager.OnBeaconError := DoBeaconError; if Assigned(FOnCalculateDistances) then FBeaconManager.OnCalculateDistances := DoBeaconCalcDistance else begin FBeaconManager.OnCalculateDistances := nil; if Assigned(FOnCalcDistance) then FBeaconManager.OnCalcDistance := DoBeaconCalcDistance else FBeaconManager.OnCalcDistance := nil; end; if assigned(FOnParseServiceData) then FBeaconManager.OnParseServiceData := DoParseServiceData else FBeaconManager.OnParseServiceData := nil; if Assigned(FOnParseManufacturerData) then FBeaconManager.OnParseManufacturerData := DoParseManufacturerData else FBeaconManager.OnParseManufacturerData := nil; FBeaconManager.OnNewEddystoneTLM := DoNewEddystoneTLM; FBeaconManager.OnNewEddystoneURL := DoNewEddystoneURL end; { TBeaconRegionItem } procedure TBeaconRegionItem.Assign(Source: TPersistent); begin if Source is TBeaconRegionItem then begin KindofBeacon := TBeaconRegionItem(Source).KindofBeacon; case KindofBeacon of TKindofBeacon.iBeacons, TKindofBeacon.AltBeacons , TKindofBeacon.iBAltBeacons: begin FMinor := TBeaconRegionItem(Source).Minor; FMajor := TBeaconRegionItem(Source).Major; FGUID := TBeaconRegionItem(Source).FGUID; FManufacturerId := TBeaconRegionItem(Source).FManufacturerID; end; TKindofBeacon.Eddystones: begin FEddyUID.Namespace := TBeaconRegionItem(Source).FEddyUID.Namespace; FEddyUID.Instance := TBeaconRegionItem(Source).FEddyUID.Instance; FEddyStInstance := TBeaconRegionItem(Source).FEddyStInstance; end; end; end else inherited; end; constructor TBeaconRegionItem.Create(Collection: TCollection); const EDDY_INSTANCE_MASK: TInstance = ($0,$0,$0,$0,$0,$0); EDDY_NAMESPACE_MASK: TNamespace = ($0,$0,$0,$0,$0,$0,$0,$0,$0,$0); begin inherited; FMinor := MINOR_REGION_ALL; FMajor := MAJOR_REGION_ALL; FKindofBeacon := TKindofBeacon.iBAltBeacons; FEddyUID.Namespace := EDDY_NAMESPACE_MASK; FEddyUID.Instance := EDDY_INSTANCE_MASK; FEddyStInstance := TCustomBeacon.EDDY_UID_INSTANCE_ALL; FManufacturerId := Integer(MANUFATURER_ID_ALL); end; function TBeaconRegionItem.GetEddyNamespace: string; begin Result := FEddyUID.NamespaceToString; end; procedure TBeaconRegionItem.SetEddyNamespace(const AValue: string); begin if FKindofBeacon = TKindofBeacon.Eddystones then if FEddyUID.SetNamespace(AValue) then Changed(False) else raise EBeaconComponentException.Create(SBeaconIncorrectEddyNamespace); end; function TBeaconRegionItem.GetEddyInstance: string; begin Result := FEddyUID.InstanceToString; end; procedure TBeaconRegionItem.SetEddyInstance(const AValue: string); begin if FKindofBeacon = TKindofBeacon.Eddystones then if AValue = TCustomBeacon.EDDY_UID_INSTANCE_ALL then FEddyStInstance := TCustomBeacon.EDDY_UID_INSTANCE_ALL else if FEddyUID.SetInstance(AValue) then begin FEddyStInstance := GetEddyInstance; Changed(False); end else raise EBeaconComponentException.Create(SBeaconIncorrectEddyInstance); end; function TBeaconRegionItem.GetUUID: string; begin Result := FGUID.ToString; end; procedure TBeaconRegionItem.SetGUID(const AValue: TGUID); begin FGUID := AValue; Changed(False); end; procedure TBeaconRegionItem.SetMajor(AValue: Integer); begin FMajor := AValue; Changed(False); end; procedure TBeaconRegionItem.SetManufacturerID(const Avalue: string); var LValue: Integer; begin if FKindofBeacon = TKindofBeacon.iBeacons then FManufacturerId := APPLEINC else begin try if (AValue = MANUFATURER_ID_ALL.ToString) then FManufacturerId := MANUFATURER_ID_ALL else begin LValue := StrToInt('$' + AValue); if (LValue >= 0) and (LValue <= $FFFF) then FManufacturerId := LValue else raise EBeaconComponentException.Create(SBeaconIncorrectMID); end; except raise EBeaconComponentException.Create(SBeaconIncorrectMID); end; end; end; function TBeaconRegionItem.GetManufacturerID: string; begin if FManufacturerId > MANUFATURER_ID_ALL then Result := FManufacturerId.ToHexString(4) else Result := MANUFATURER_ID_ALL.ToString; end; procedure TBeaconRegionItem.SetMinor(AValue: Integer); begin FMinor := AValue; Changed(False); end; procedure TBeaconRegionItem.SetUUID(const AValue: string); begin try GUID := TGUID.Create(AValue); except on E: Exception do raise EBeaconComponentException.Create(E.Message); end end; { TBeaconRegionList } function TBeaconRegionCollection.GetItem(Index: Integer): TBeaconRegionItem; begin Result := TBeaconRegionItem(inherited GetItem(Index)); end; procedure TBeaconRegionCollection.SetItem(Index: Integer; const Value: TBeaconRegionItem); begin inherited SetItem(Index, Value); end; procedure TBeaconRegionCollection.Update(Item: TCollectionItem); begin inherited; if Assigned(FOnChange) then FOnChange(Self); end; { TCustomBeaconDevice } constructor TCustomBeaconDevice.Create(AOwner: TComponent); begin inherited; FBeaconType := BEACON_ST_TYPE; FBeaconDeviceMode := TBeaconDeviceMode.Standard; FTxPower := TXPOWER_IDETERMINATED; FManufacturerId := APPLEINC; FEddystoneNamespace := 'example.com'; FEddystoneInstance := '000000000001'; FDeviceType := adBeacon; FNamespaceGenerator := ngHashFQDN; end; function TCustomBeaconDevice.GetUUID: string; begin Result := FGUID.ToString; end; procedure TCustomBeaconDevice.InitWithGattServer(AGattServer: TBluetoothGattServer); begin if FBeaconAdvertiser <> nil then FBeaconAdvertiser.Free; FBeaconAdvertiser := TBeaconAdvertiser.GetBeaconAdvertiser(AGattServer); end; procedure TCustomBeaconDevice.Loaded; begin inherited; if not (csDesigning in ComponentState) then StartAdvertise; end; procedure TCustomBeaconDevice.SetMFGReserved(const Value: Byte); begin FMFGReserved := Value; end; procedure TCustomBeaconDevice.SetEnabled(const Value: Boolean); begin if Value <> FEnabled then begin FEnabled := Value; if (not (csDesigning in ComponentState)) and (not (csLoading in ComponentState)) then if Value then try StartAdvertise except FEnabled := not FEnabled; raise; end else StopAdvertise; end; end; procedure TCustomBeaconDevice.SetGUID(const Value: TGUID); begin FGUID := Value; end; procedure TCustomBeaconDevice.SetMajor(const Value: Integer); begin FMajor := Value; end; procedure TCustomBeaconDevice.SetMID(const Value: string); var LValue: Integer; begin if not (csLoading in ComponentState) and (GetType = TBeaconDeviceMode.Standard) then FManufacturerId := APPLEINC else begin try LValue := StrToInt('$'+Value); if (LValue >= 0) and (LValue <= $FFFF) then FManufacturerId := LValue else raise EBeaconComponentException.Create(SBeaconIncorrectMID); except raise EBeaconComponentException.Create(SBeaconIncorrectMID); end; end; end; function TCustomBeaconDevice.GetMFGReserved: Byte; begin Result := FMFGReserved; end; function TCustomBeaconDevice.GetMID: string; begin Result := FManufacturerId.ToHexString(4); end; procedure TCustomBeaconDevice.SetMinor(const Value: Integer); begin FMinor := Value; end; procedure TCustomBeaconDevice.SetTxPower(const Value: ShortInt); begin FTxPower := Value; end; procedure TCustomBeaconDevice.SetType(const Value: TBeaconDeviceMode); begin case Value of TBeaconDeviceMode.Standard: begin FBeaconType := BEACON_ST_TYPE; FManufacturerId := APPLEINC; FDeviceType := TAdvertiseDeviceFormat.adBeacon; end; TBeaconDeviceMode.Alternative: begin FBeaconType := BEACON_AL_TYPE; FDeviceType := TAdvertiseDeviceFormat.adBeacon; end; TBeaconDeviceMode.EddystoneUID: FDeviceType := TAdvertiseDeviceFormat.adEddystoneUID; TBeaconDeviceMode.EddystoneURL: FDeviceType := TAdvertiseDeviceFormat.adEddystoneURL; end; FBeaconDeviceMode := Value; end; function TCustomBeaconDevice.GetType: TBeaconDeviceMode; begin Result := FBeaconDeviceMode; end; procedure TCustomBeaconDevice.SetUUID(const Value: string); begin GUID := TGUID.Create(Value); end; procedure TCustomBeaconDevice.StartAdvertise; begin if Enabled and (TBluetoothLEManager.Current.CurrentAdapter <> nil) then begin if FBeaconAdvertiser = nil then FBeaconAdvertiser := TBeaconAdvertiser.GetBeaconAdvertiser(nil); FBeaconAdvertiser.GUID := FGUID; FBeaconAdvertiser.Major := FMajor; FBeaconAdvertiser.Minor := FMinor; FBeaconAdvertiser.TxPower := FTxPower; FBeaconAdvertiser.ManufacturerId := FManufacturerId; FBeaconAdvertiser.BeaconType := FBeaconType; FBeaconAdvertiser.MFGReserved := FMFGReserved; FBeaconAdvertiser.EddystoneNamespace := FEddystoneNamespace; FBeaconAdvertiser.EddystoneInstance := FEddystoneInstance; FBeaconAdvertiser.EddystoneURL := FEddystoneURL; FBeaconAdvertiser.DeviceType := FDeviceType; FBeaconAdvertiser.NamespaceGenerator := FNamespaceGenerator; FBeaconAdvertiser.StartAdvertising; end; end; procedure TCustomBeaconDevice.StopAdvertise; begin if FBeaconAdvertiser <> nil then FBeaconAdvertiser.StopAdvertising; end; end.
unit uUnidadeDao; interface uses FireDAC.Comp.Client, uConexao, uUnidadeModel, System.SysUtils; type TUnidadeDao = class private FConexao: TConexao; public constructor Create; function Incluir(Unidade: TUnidadeModel): Boolean; function Excluir(Unidade: TUnidadeModel): Boolean; function Obter: TFDQuery; end; implementation { TUnidadeDao } uses uSistemaControl; constructor TUnidadeDao.Create; begin FConexao := TSistemaControl.GetInstance().Conexao; end; function TUnidadeDao.Excluir(Unidade: TUnidadeModel): Boolean; var VQry: TFDQuery; begin VQry := FConexao.CriarQuery(); try VQry.ExecSQL(' DELETE FROM Unidade WHERE Codigo = :codigo ', [Unidade.Codigo]); Result := True; finally VQry.Free; end; end; function TUnidadeDao.Incluir(Unidade: TUnidadeModel): Boolean; var VQry: TFDQuery; begin VQry := FConexao.CriarQuery(); try VQry.ExecSQL(' INSERT INTO Unidade VALUES (:codigo, :nome, :cep, :cidade) ', [Unidade.Codigo, Unidade.Nome, Unidade.Cep, Unidade.Cidade]); Result := True; finally VQry.Free; end; end; function TUnidadeDao.Obter: TFDQuery; var VQry: TFDQuery; begin VQry := FConexao.CriarQuery(); VQry.Open(' SELECT * FROM Unidade ORDER BY 1 '); Result := VQry; end; end.
unit u_xpl_sender; {=============================================================================== UnitName = u_xpl_sender UnitDesc = xPL Sender object and function UnitCopyright = GPL by Clinique / xPL Project =============================================================================== 0.8 : First version, spined off from uxPLMessage } {$i xpl.inc} {$M+} interface uses Classes , SysUtils , u_xpl_custom_message , u_xpl_common , u_xpl_schema , u_xpl_address , u_xpl_application , u_xpl_udp_socket , u_xpl_fragment_mgr ; type // TxPLSender ============================================================ TxPLSender = class(TxPLApplication) protected fSocket : TxPLUDPClient; fFragMgr : TFragmentManager; procedure Send(const aMessage : string); overload; public constructor create(const aOwner : TComponent); overload; procedure Send(const aMessage : TxPLCustomMessage; const bEnforceSender : boolean = true); overload; procedure SendMessage(const aMsgType : TxPLMessageType; const aDest, aSchema, aRawBody : string; const bClean : boolean = false); overload; procedure SendMessage(const aMsgType : TxPLMessageType; const aDest, aSchema : string; const Keys, Values : Array of string); overload; procedure SendMessage(const aMsgType : TxPLMessageType; const aDest : string; aSchema : TxPLSchema; const Keys, Values : Array of string); overload; procedure SendMessage(const aRawXPL : string); overload; function PrepareMessage(const aMsgType: TxPLMessageType; const aSchema : string; const aTarget : string = '*') : TxPLCustomMessage; overload; function PrepareMessage(const aMsgType: TxPLMessageType; const aSchema : TxPLSchema; const aTarget : TxPLTargetAddress = nil) : TxPLCustomMessage; overload; procedure SendHBeatRequestMsg; published property FragmentMgr : TFragmentManager read fFragMgr; end; implementation // ============================================================= uses u_xpl_message , u_xpl_messages ; constructor TxPLSender.create(const aOwner : TComponent); begin inherited; fSocket := TxPLUDPClient.Create(self); fFragMgr := TFragmentManager.Create(self); end; procedure TxPLSender.Send(const aMessage: string); begin fSocket.Send(aMessage) end; procedure TxPLSender.Send(const aMessage: TxPLCustomMessage; const bEnforceSender : boolean = true); var i : integer; FragFactory : TFragmentFactory; begin if bEnforceSender then aMessage.Source.Assign(Adresse); // Let's be sure I'm identified as the sender if not aMessage.IsValid then Log(etWarning,'Error sending message %s',[aMessage.RawxPL]) else begin if not aMessage.MustFragment then Send(TxPLMessage(aMessage).ProcessedxPL) else begin FragFactory := fFragMgr.Fragment(TxPLMessage(aMessage)); for i:=0 to Pred(FragFactory.FragmentList.Count) do Send(TxPLMessage(FragFactory.FragmentList[i]).ProcessedxPL); end; end end; procedure TxPLSender.SendMessage(const aMsgType: TxPLMessageType; const aDest, aSchema, aRawBody: string; const bClean: boolean); var aMsg : TxPLCustomMessage; begin aMsg := PrepareMessage(aMsgType,aSchema,aDest); with aMsg do begin Body.RawxPL := aRawBody; if bClean then Body.CleanEmptyValues; Send(aMsg); Free; end; end; procedure TxPLSender.SendMessage(const aRawXPL : string); var aMsg : TxPLCustomMessage; begin aMsg := TxPLCustomMessage.Create(self, aRawxPL); with aMsg do begin Source.Assign(Adresse); Send(aMsg); Free; end; end; function TxPLSender.PrepareMessage(const aMsgType: TxPLMessageType; const aSchema : string; const aTarget : string = '*' ): TxPLCustomMessage; begin result := TxPLCustomMessage.Create(self); with Result do begin Source.Assign(Adresse); MessageType := aMsgType; Target.RawxPL := aTarget; Schema.RawxPL := aSchema; end; end; function TxPLSender.PrepareMessage(const aMsgType: TxPLMessageType; const aSchema : TxPLSchema; const aTarget : TxPLTargetAddress = nil) : TxPLCustomMessage; var sTarget : string; begin if aTarget = nil then sTarget := '*' else sTarget := aTarget.RawxPL; result := PrepareMessage(aMsgType,aSchema.RawxPL,sTarget); end; procedure TxPLSender.SendMessage(const aMsgType: TxPLMessageType; const aDest, aSchema: string; const Keys, Values: array of string); var aMsg : TxPLCustomMessage; begin aMsg := PrepareMessage(aMsgType, aSchema, aDest); aMsg.Body.AddKeyValuePairs(Keys,Values); Send(aMsg); aMsg.Free; end; procedure TxPLSender.SendMessage(const aMsgType: TxPLMessageType; const aDest : string; aSchema: TxPLSchema; const Keys, Values: array of string); begin SendMessage(aMsgType,aDest,aSchema.RawxPL,Keys,Values); end; procedure TxPLSender.SendHBeatRequestMsg; var HBeatReq :THeartBeatReq; begin HBeatReq := THeartBeatReq.Create(nil); Send(HBeatReq); HBeatReq.Free; end; end.
//==============================================================// // uBuku // //--------------------------------------------------------------// // Unit yang menangani hal-hal yang berhubungan dengan buku // //==============================================================// unit uBuku; interface uses uFileLoader, Crt; type indexarr = array[1..1000] of integer; function validasi(k: string): boolean; { menghasilkan true jika input termasuk kategori yang ada dan false jika tidak; dengan menuliskan ekspresi boolean } procedure search(var arrBuku: BArr); { menampilkan daftar buku yang memiliki kategori sesuai input I.S. data array sama dengan data pada csv F.S. data dari array yang ditampilkan adalah yang sesuai kategori, data pada array tetap sama dengan csv } function isMember(index : integer ; indexarray : indexarr; count : integer) : boolean; { menghasilkan true jika index termasuk anggota dari indexarray ; dengan menuliskan ekspresi boolean } procedure sortIndexArray(var indexarray : indexarr ; temparr : BArr; count : integer); { mengurutkan index dari temparr dan menyimpannya dalam indexarray I.S. indexarray kosong, temparr berisi data yang belum urut F.S. indexarray berisi index temparr yang sudah terurut (menurut atribut Judul_Buku tiap elemen temparr) } procedure year(var arrBuku: BArr); { menampilkan daftar buku yang memiliki tahun terbit sesuai input I.S. data buku sesuai array F.S. data yang ditampilkan hanya buku yang memiliki tahun terbit sesuai input } procedure add(var arrBuku: BArr); { Memasukkan data buku baru ke dalam array buku I.S. data array sama dengan data pada csv F.S. index array bertambah 1 dengan data baru } procedure amount(var arrBuku: BArr); { Menambahkan jumlah buku baru ke dalam array buku sesuai jumlah input I.S. data jumlah buku pada array sama dengan data pada csv F.S. data jumlah buku bertambah sesuai input } procedure PrintBuku (var arrBuku : BArr); {Menulis elemen-elemen dari arrBuku ke layar dengan format sesuai data buku} {I.S. : arrBuku sudah berisi data dari file buku dan/atau modifikasi di main program} {F.S. : arrBuku tercetak ke layar sesuai format data buku} implementation function validasi(k: string): boolean; { menghasilkan true jika input termasuk kategori yang ada dan false jika tidak; dengan menuliskan ekspresi boolean } { ALGORITMA } begin validasi := (k = 'sastra') or (k = 'sains') or (k = 'manga') or (k = 'sejarah') or (k = 'programming'); end; procedure search(var arrBuku: BArr); { menampilkan daftar buku yang memiliki kategori sesuai input I.S. data array sama dengan data pada csv F.S. data dari array yang ditampilkan adalah yang sesuai kategori, data pada array tetap sama dengan csv } { KAMUS LOKAL } var count, i, index: integer; { count jumlah dan i merupakan indeks } k : string; { read string dari pengguna } temparr : BArr; indexarray : indexarr; { ALGORITMA } begin i:=1; { inisialisasi, i = 1 sebagai indeks pertama pada array } count:=0; { inisialisasi, count = 0 } write('Masukkan kategori: '); readln(k); { first element } while(validasi(k) = false) do { EOP : validasi(k) = true } begin writeln('Kategori ', k, ' tidak valid.'); write('Masukkan kategori: '); readln(k); { next element } end; while(i<=lenBuku) do { EOP : i > lenBuku } begin if(k = arrBuku[i].Kategori) then { proses kasus kategori pada data sesuai input } begin count := count+1; temparr[count] := arrBuku[i]; end; i := i+1; end; if(count = 0) then { proses kasus tidak ada buku yang sesuai kategori input } writeln('Tidak ada buku dalam kategori ini.'); sortIndexArray(indexarray, temparr, count); { proses sorting untuk tampilan } for i := 1 to count do { proses pencetakan ke layar sesuai urutan sorting } begin index := indexarray[i]; writeln(temparr[index].ID_Buku, ' | ', temparr[index].Judul_Buku, ' | ', temparr[index].Author); end; writeln(); writeln('Ketik 0 untuk kembali ke menu.'); readln(); ClrScr; end; function isMember(index : integer ; indexarray : indexarr; count : integer) : boolean; { menghasilkan true jika index termasuk anggota dari indexarray ; dengan menuliskan ekspresi boolean } { KAMUS LOKAL } var i : integer; { ALGORITMA } begin isMember := false; i := 1; while ((not isMember) and (i <= count)) do begin if (indexarray[i] = index) then begin isMember := true end else begin inc(i); end; end; end; procedure sortIndexArray(var indexarray : indexarr ; temparr : BArr; count : integer); { mengurutkan index dari temparr dan menyimpannya dalam indexarray I.S. indexarray kosong, temparr berisi data yang belum urut F.S. indexarray berisi index temparr yang sudah terurut (menurut atribut Judul_Buku tiap elemen temparr) } { KAMUS LOKAL } var i, j, k, dec, min, indexmin : integer; // dec adalah penyimpan nilai sementara, min adalah nilai minimum sementara, indexmin adalah index minimum sementara advancedcheck : boolean; // Penanda perlu dilakukan penyocokan lebih dalam { ALGORITMA } begin // For loop utama untuk mengiterasi sepanjang array temparr for i := 1 to count do begin advancedcheck := false; // Set indexmin 1 agar tiap iterasi tidak melewatkan elemen array manapun indexmin := 1; // While loop untuk mengecek apakah indexmin sudah ada di indexarray // Jika sudah, berarti indexmin sudah terurut dan dilanjutkan untuk mengurut index selanjutnya while (isMember(indexmin, indexarray, count)) do begin inc(indexmin); end; min := ord(temparr[indexmin].Judul_Buku[1]); // If berguna untuk mengecek apakah decimal lebih dari 90 (huruf kecil) // Jika lebih dari 90, diconvert ke huruf kapitalnya agar penyocokan serasi if(min > 90) then begin min := min - 32 end; // For loop untuk membandingkan tiap huruf depan dari judul buku for j := indexmin + 1 to count do begin dec := ord(temparr[j].Judul_Buku[1]); if (dec > 90) then begin dec := dec - 32 end; // Jika nilai decimal sementara lebih kecil dari minimum dan index penandanya belum ada di indexarray, // maka dianggap minimum sementara dan indexmin diset index // Nilai decimal lebih kecil berarti secara leksikografis lebih dulu muncul if ((dec < min) and (not isMember(j,indexarray, count))) then begin min := dec; indexmin := j; end // Jika nilai decimal dan minimum sama, dilakukan pengecekan lebih dalam untuk huruf selanjutnya else if ((dec = min) and (not isMember(j,indexarray, count))) then begin advancedcheck := true; k := 2; // While loop berjalan untuk mengecek tiap huruf selanjutnya sampai ditemukan yang lebih awal while (advancedcheck) do begin // Minimum diset decimal jika memang benar decimal lebih kecil if(ord(temparr[j].Judul_Buku[k]) < ord(temparr[indexmin].Judul_Buku[k])) then begin min := dec; indexmin := j; advancedcheck := false; end // Minimum tetap jika decimal lebih besar dari minimum else if (ord(temparr[j].Judul_Buku[k]) > ord(temparr[indexmin].Judul_Buku[k])) then begin advancedcheck := false; end else begin inc(k); end; end; end; end; indexarray[i] := indexmin // Setting indexarray urutan ke [i] dengan indexmin end; end; procedure year(var arrBuku: BArr); { menampilkan daftar buku yang memiliki tahun terbit sesuai input I.S. data buku sesuai array F.S. data yang ditampilkan hanya buku yang memiliki tahun terbit sesuai input } { KAMUS LOKAL } var count, i, t: integer; { count adalah jumlah; i adalah indeks; t adalah input tahun } k: string; { k adalah input kategori } { ALGORITMA } begin i:=1; { inisialisasi i = 1 sebagai indeks pertama array } count:=0; { inisialisasi count = 0 sebagai variabel jumlah } write('Masukkan tahun: '); readln(t); write('Masukkan kategori: '); readln(k); writeln(); writeln('Buku yang terbit ', k, ' ', t, ' :'); while(i<=lenBuku) do { EOP : i > GetSizeBuku } begin if(k = '=') then { proses kasus input k adalah = (sama dengan) } begin if(arrBuku[i].Tahun_Penerbit = t) then { proses kasus tahun terbit data sesuai input } begin count := count+1; writeln(arrBuku[i].ID_Buku, ' | ', arrBuku[i].Judul_Buku, ' | ', arrBuku[i].Author); end; end else if(k = '<') then { proses kasus input k adalah < (lebih kecil) } begin if(arrBuku[i].Tahun_Penerbit < t) then { proses kasus tahun terbit data lebih kecil dari input t } begin count := count+1; writeln(arrBuku[i].ID_Buku, ' | ', arrBuku[i].Judul_Buku, ' | ', arrBuku[i].Author); end; end else if(k = '>') then { proses kasus input k adalah > (lebih besar) } begin if(arrBuku[i].Tahun_Penerbit > t) then { proses kasus tahun terbit data lebih besar dari input t } begin count := count+1; writeln(arrBuku[i].ID_Buku, ' | ', arrBuku[i].Judul_Buku, ' | ', arrBuku[i].Author); end; end else if(k = '>=') then { proses kasus input k adalah >= (lebih besar sama dengan) } begin if(arrBuku[i].Tahun_Penerbit >= t) then { proses kasus tahun terbit data lebih besar sama dengan input t } begin count := count+1; writeln(arrBuku[i].ID_Buku, ' | ', arrBuku[i].Judul_Buku, ' | ', arrBuku[i].Author); end; end else if(k = '<=') then { proses kasus input k adalah <= (lebih kecil sama dengan) } begin if(arrBuku[i].Tahun_Penerbit <= t) then { proses kasus tahun terbit data lebih kecil sama dengan input t } begin count := count+1; writeln(arrBuku[i].ID_Buku, ' | ', arrBuku[i].Judul_Buku, ' | ', arrBuku[i].Author); end; end; i := i+1; end; if(count = 0) then { proses kasus count di akhir = 0 } begin writeln('Tidak ada buku yang sesuai.'); end; writeln(); writeln('Ketik 0 untuk kembali ke menu.'); readln(); ClrScr; end; procedure add(var arrBuku: BArr); { Memasukkan data buku baru ke dalam array buku I.S. data array sama dengan data pada csv F.S. index array bertambah 1 dengan data baru } { ALGORITMA } begin writeln('Masukkan Informasi buku yang ditambahkan: '); write('Masukkan id buku: '); readln(arrBuku[lenBuku+1].ID_Buku); {memasukkan ID Buku baru dengan indeks jumlah data bertambah 1} write('Masukkan judul buku: '); readln(arrBuku[lenBuku+1].Judul_Buku); {memasukkan Judul Buku baru dengan indeks jumlah data bertambah 1} write('Masukkan pengarang buku: '); readln(arrBuku[lenBuku+1].Author); {memasukkan Author baru dengan indeks jumlah data bertambah 1} write('Masukkan jumlah buku: '); readln(arrBuku[lenBuku+1].Jumlah_Buku); {memasukkan Jumlah Buku baru dengan indeks jumlah data bertambah 1} write('Masukkan tahun terbit buku: '); readln(arrBuku[lenBuku+1].Tahun_penerbit); {memasukkan Tahun penerbit baru dengan indeks jumlah data bertambah 1} write('Masukkan kategori: '); readln(arrBuku[lenBuku+1].Kategori); {memasukkan Kategori baru dengan indeks jumlah data bertambah 1} writeln(); writeln('Buku berhasil ditambahkan ke dalam sistem!'); lenBuku := lenBuku + 1; { panjang data bertambah 1 } writeln(); writeln('Ketik 0 untuk kembali ke menu.'); readln(); ClrScr; end; procedure amount(var arrBuku: BArr); { Menambahkan jumlah buku baru ke dalam array buku sesuai jumlah input I.S. data jumlah buku pada array sama dengan data pada csv F.S. data jumlah buku bertambah sesuai input } { KAMUS LOKAL } var found: Boolean; i, n: integer; id: string; { ALGORTIMA } begin found := false; { inisialisasi, found = false } i:=1; { inisialisasi, i = 1 sebagai indeks } write('Masukan ID Buku: '); readln(id); write('Masukan jumlah buku yang ditambahkan: '); readln(n); while((i<=lenBuku) and (not found)) do { EOP : i > ukuran data (lenBuku) atau found = true } begin if(arrBuku[i].ID_Buku = id) then { proses kasus id buku pada array sama dengan input } begin found := true; end else i:= i+1; end; { i akhir adalah indeks buku yang memiliki id input } arrBuku[i].Jumlah_buku := arrBuku[i].Jumlah_Buku + n; { jumlah buku menjadi jumlah buku awal ditambah input } writeln('Pembaharuan jumlah buku berhasil dilakukan, total buku ', arrBuku[i].Judul_Buku, ' di perpustakaan menjadi ', arrBuku[i].Jumlah_Buku); writeln(); writeln('Ketik 0 untuk kembali ke menu.'); readln(); ClrScr; end; procedure PrintBuku (var arrBuku : BArr); {Menulis elemen-elemen dari arrBuku ke layar dengan format sesuai data buku} {I.S. : arrBuku sudah berisi data dari file buku dan/atau modifikasi di main program} {F.S. : arrBuku tercetak ke layar sesuai format data buku} {' | ' digunakan untuk pemisah antar kolom} { KAMUS LOKAL } var k : integer; { ALGORITMA } begin for k := 1 to (lenBuku) do begin write(k); write(' | '); write(arrBuku[k].ID_Buku); write(' | '); write(arrBuku[k].Judul_Buku); write(' | '); write(arrBuku[k].Author); write(' | '); write(arrBuku[k].Jumlah_Buku); write(' | '); write(arrBuku[k].Tahun_Penerbit); write(' | '); write(arrBuku[k].Kategori); writeln(); end; end; end.
{ ID: a2peter1 PROG: concom LANG: PASCAL } { Me rendí, esta es la solucion de Abel } {$B-,I-,Q-,R-,S-} const problem = 'concom'; MaxN = 100; var N,i,j,k,h : longint; mark : array[0..MaxN,0..MaxN] of boolean; owns : array[0..MaxN,0..MaxN] of longint; procedure dfs(i,j: longint); var k : longint; begin if mark[i,j] then exit; mark[i,j] := true; for k := 1 to MaxN do begin if owns[i,k] <= 50 then inc(owns[i,k],owns[j,k]); if owns[i,k] > 50 then dfs(i,k); end;{for} end;{dfs} begin assign(input,problem + '.in'); reset(input); assign(output,problem + '.out'); rewrite(output); readln(N); for N := 1 to N do begin readln(i,j,h); inc(owns[i,j],h); for k := 1 to MaxN do if (k <> i) and (owns[k,i] > 50) then begin if owns[k,j] <= 50 then inc(owns[k,j],owns[i,j]); if owns[k,j] > 50 then dfs(k,j); end;{then} if owns[j,k] > 50 then dfs(j,k); end;{for} for i := 1 to MaxN do for j := 1 to MaxN do if (i <> j) and (owns[i,j] > 50) then writeln(i,' ',j); close(output); end.{main}
unit FC.Trade.Trader.StopAndReverse; {$I Compiler.inc} interface uses Classes, Math,Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions, StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators, Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage, StockChart.Definitions.Drawing,Graphics; type IStockTraderStopAndReverse = interface ['{3B2DB2CC-FC9B-4226-BFB0-0D208E465E86}'] end; TStockTraderStopAndReverse = class (TStockTraderBase,IStockTraderStopAndReverse) private protected function Spread: TSCRealNumber; function ToPrice(aPoints: integer): TSCRealNumber; procedure AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); procedure SetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); procedure OnModifyOrder(const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs); override; public procedure SetProject(const aValue : IStockProject); override; procedure OnBeginWorkSession; override; //Посчитать procedure UpdateStep2(const aTime: TDateTime); override; constructor Create; override; destructor Destroy; override; procedure Dispose; override; end; implementation uses Variants,DateUtils, SystemService, Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message, StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory, FC.DataUtils; { TStockTraderStopAndReverse } constructor TStockTraderStopAndReverse.Create; begin inherited Create; // UnRegisterProperties([PropTrailingStop,PropTrailingStopDescend,PropMinimizationRiskType]); end; destructor TStockTraderStopAndReverse.Destroy; begin inherited; end; procedure TStockTraderStopAndReverse.Dispose; begin inherited; end; procedure TStockTraderStopAndReverse.OnBeginWorkSession; begin inherited; end; procedure TStockTraderStopAndReverse.OnModifyOrder(const aOrder: IStockOrder;const aModifyEventArgs: TStockOrderModifyEventArgs); begin inherited; if aModifyEventArgs.ModifyType=omtClose then begin if aOrder.GetKind=okBuy then OpenOrder(okSell) else OpenOrder(okBuy); end; end; procedure TStockTraderStopAndReverse.SetMark(const aOrder: IStockOrder;const aMarkType: TSCChartMarkKind; const aMessage: string); begin AddMarkToCharts(GetBroker.GetCurrentTime, GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid), aMarkType,aMessage); end; procedure TStockTraderStopAndReverse.SetProject(const aValue: IStockProject); begin if GetProject=aValue then exit; inherited; end; function TStockTraderStopAndReverse.ToPrice(aPoints: integer): TSCRealNumber; begin result:=GetBroker.PointToPrice(GetSymbol,1); end; function TStockTraderStopAndReverse.Spread: TSCRealNumber; begin result:=GetBroker.PointToPrice(GetSymbol,GetBroker.GetMarketInfo(GetSymbol).Spread); end; procedure TStockTraderStopAndReverse.UpdateStep2(const aTime: TDateTime); begin RemoveClosedOrders; if LastOrderType=lotNone then OpenOrder(okBuy); end; procedure TStockTraderStopAndReverse.AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); begin GetBroker.AddMessage(aOrder,aMessage); AddMarkToCharts(GetBroker.GetCurrentTime, GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid), aMarkType,aMessage); end; initialization FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','StopAndReverse',TStockTraderStopAndReverse,IStockTraderStopAndReverse); end.
unit UnModel; interface uses SysUtils, Classes, SqlExpr, FMTBcd, DB, DBClient, Provider, { Fluente } Util, DataUtil, Settings; type TModel = class(TDataModule) Sql: TSQLDataSet; ds: TSQLDataSet; dsp: TDataSetProvider; cds: TClientDataSet; dsr: TDataSource; private FDataUtil: TDataUtil; FParameters: TStringList; FPesquisaExata: Boolean; FSettings: TSettings; FUtil: TUtil; protected FSql: TSQL; function RetornarComponente(const Prefixo, Nome: string): TComponent; function GetParameters: TStringList; function GetSQL: TSQL; virtual; abstract; public function Util(const Util: TUtil): TModel; function DataUtil(const DataUtil: TDataUtil): TModel; function Configuracoes(const Configuracoes: TSettings): TModel; function Incluir: TModel; virtual; function Salvar: TModel; virtual; function Excluir: TModel; virtual; function DataSet(const DataSetName: string = ''): TClientDataSet; function DataSource(const DataSourceName: string = ''): TDataSource; function Preparar(const Conexao: TSQLConnection): TModel; virtual; function PesquisaExataLigada: TModel; function PesquisaExataDesligada: TModel; function Carregar: TModel; virtual; function CarregarPor(const Criterio: string): TModel; virtual; end; var FConexao: TSQLConnection; FSql: TSQL; FDataUtil: TDataUtil; FUtil: TUtil; FConfiguracoes: TSettings; implementation uses Dialogs, Forms; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TModel } function TModel.Carregar: TModel; begin Self.CarregarPor(''); Result := Self; end; function TModel.CarregarPor(const Criterio: string): TModel; var _dataSet: TClientDataSet; begin _dataSet := Self.cds; _dataSet.Active := False; if Criterio = '' then _dataSet.CommandText := Self.GetSQL().ObterSQL else _dataSet.CommandText := Self.GetSQL().ObterSQLFiltrado(Criterio); _dataSet.Open(); Result := Self; end; function TModel.Configuracoes(const Configuracoes: TSettings): TModel; begin Self.FSettings := Configuracoes; Result := Self; end; function TModel.DataSet(const DataSetName: string): TClientDataSet; begin if DataSetName <> '' then Result := Self.RetornarComponente('cds_', DataSetName) as TClientDataSet else Result := Self.cds; end; function TModel.DataSource(const DataSourceName: string): TDataSource; begin if DataSourceName <> '' then Result := Self.RetornarComponente('dsr_', DataSourceName) as TDataSource else Result := Self.dsr; end; function TModel.DataUtil(const DataUtil: TDataUtil): TModel; begin Self.FDataUtil := DataUtil; Result := Self; end; function TModel.Excluir: TModel; begin Result := Self; end; function TModel.GetParameters: TStringList; begin if Self.FParameters = nil then Self.FParameters := TStringList.Create; Result := Self.FParameters; end; function TModel.Incluir: TModel; begin Result := Self; end; function TModel.PesquisaExataDesligada: TModel; begin Self.FPesquisaExata := False; Result := Self; end; function TModel.PesquisaExataLigada: TModel; begin Self.FPesquisaExata := True; Result := Self; end; function TModel.Preparar(const Conexao: TSQLConnection): TModel; var _i: Integer; begin // inicia valores padrao Self.FPesquisaExata := True; // liga datasets a conexao for _i := 0 to Self.ComponentCount-1 do if (Self.Components[_i].Tag <> 0) and (Self.Components[_i] is TSQLDataSet) then begin (Self.Components[_i] as TSQLDataSet).SQLConnection := Conexao; end; for _i := 0 to Self.ComponentCount-1 do if (Self.Components[_i].Tag <> 0) and (Self.Components[_i] is TClientDataSet) then begin (Self.Components[_i] as TClientDataSet).Open(); end; Result := Self; end; function TModel.RetornarComponente(const Prefixo, Nome: string): TComponent; var _nome: string; begin _nome := Format('%s%s', [Prefixo, Nome]); Result := Self.FindComponent(_nome); end; function TModel.Salvar: TModel; begin Result := Self; end; function TModel.Util(const Util: TUtil): TModel; begin Self.FUtil := Util; Result := Self; end; end.
unit UMyUtils; {$mode objfpc}{$H+} interface uses Classes, SysUtils,fphttpclient,INIFiles,Dialogs; type TMyUtils=class Public //Public Declarations Function FormatSize(Size: Int64): String; Function getIniParms(UrlIni:String;var version,URL,executable:String;var updatables:TStringList):Boolean; Private //Private Declarations Procedure DownFile(inurl:String;outfile:String); end; implementation Function TMyUtils.FormatSize(Size: Int64): String; const KB = 1024; MB = 1024 * KB; GB = 1024 * MB; begin if Size < KB then Result := FormatFloat('#,##0 Bytes', Size) else if Size < MB then Result := FormatFloat('#,##0.0 KB', Size / KB) else if Size < GB then Result := FormatFloat('#,##0.0 MB', Size / MB) else Result := FormatFloat('#,##0.0 GB', Size / GB); end; Function TMyUtils.getIniParms(UrlIni:String;var version,URL,executable:String;var updatables:TStringList):Boolean; var INI:TINIFile; sections:TStringList; Section:String; begin Result:=False; Section:=''; try DownFile(UrlIni,'update.ini'); sections:=TStringList.Create; If (Not(FileExists(ExtractFilePath(ParamStr(0))+'update.Ini'))) Then Exit(False); INI := TINIFile.Create('update.Ini'); INI.ReadSections(sections); If sections.Count>0 Then Section:=sections[0]; executable:= INI.ReadString(Section,'executable',''); URL:= INI.ReadString(Section,'URL',''); version:=INI.ReadString(Section,'version',''); updatables:=TStringList.Create; updatables.Delimiter:=';'; updatables.DelimitedText:=INI.ReadString(Section,'updatables',''); INI.Free; DeleteFile('update.Ini'); Result:=not((executable.Trim.IsEmpty) Or (URL.Trim.IsEmpty) Or (version.Trim.IsEmpty) or (updatables.Count<1)); except on E: Exception do Result:=False; end; end; Procedure TMyUtils.DownFile(inurl:String;outfile:String); var HTTPClient:TFPHTTPClient; begin HTTPClient := TFPHTTPClient.Create(nil); try try HTTPClient.Get(inurl, outfile); except end; finally HTTPClient.Free; end; end; end.
unit caVmt; {$INCLUDE ca.inc} interface uses Classes, SysUtils, TypInfo, Contnrs; type //--------------------------------------------------------------------------- // Published method record   //--------------------------------------------------------------------------- PVmtMethod = ^TVmtMethod; TVmtMethod = packed record Size: Word; Address: Pointer; Name: ShortString; end; //--------------------------------------------------------------------------- // Params for stdcall methods   //--------------------------------------------------------------------------- PMethodParam = ^TMethodParam; TMethodParam = packed record TypeInfo: PPTypeInfo; Name: ShortString; end; //--------------------------------------------------------------------------- // Published method table   //--------------------------------------------------------------------------- PVmtMethodTable = ^TVmtMethodTable; TVmtMethodTable = packed record Count: Word; Methods: array[0..MaxListSize] of Byte; end; //--------------------------------------------------------------------------- // Dummy entries - we are not interested in these   //--------------------------------------------------------------------------- PVmtAutoTable = Pointer; PVmtInitTable = Pointer; PVmtFieldTable = Pointer; PVmtDynMethodTable = Pointer; //--------------------------------------------------------------------------- // Virtual Method Table   //--------------------------------------------------------------------------- PVmt = ^TVmt; TVmt = record SelfPtr: TClass; IntfTable: PInterfaceTable; AutoTable: PVmtAutoTable; InitTable: PVmtInitTable; TypeInfo: PTypeInfo; FieldTable: PVmtFieldTable; MethodTable: PVmtMethodTable; DynMethodTable: PVmtDynMethodTable; ClassName: PShortString; InstanceSize: Cardinal; ClassParent: ^TClass; SafeCallException: Pointer; AfterConstruction: Pointer; BeforeDestruction: Pointer; Dispatch: Pointer; DefaultHandler: Pointer; NewInstance: Pointer; FreeInstance: Pointer; Destroy: Pointer; end; //--------------------------------------------------------------------------- // TcaVmtMethodParam   //--------------------------------------------------------------------------- TcaVmtMethodParam = class(TObject) private // Private fields FParam: PMethodParam; // Property fields FTypeName: String; // Property methods function GetParamName: ShortString; function GetParamClassType: TClass; function GetParamTypeInfo: PPTypeInfo; function GetParamTypeName: String; // Private methods function GetClassName: String; function GetEnumName: String; function GetMethodName: String; procedure Update; public constructor Create(AParam: PMethodParam); destructor Destroy; override; // Properties property ParamName: ShortString read GetParamName; property ParamClassType: TClass read GetParamClassType; property ParamTypeInfo: PPTypeInfo read GetParamTypeInfo; property ParamTypeName: String read GetParamTypeName; end; //--------------------------------------------------------------------------- // TcaVmtMethod   //--------------------------------------------------------------------------- TcaVmtMethod = class(TObject) private // Private fields FMethod: PVmtMethod; FParams: TObjectList; // Property methods function GetAddress: Pointer; function GetName: ShortString; function GetParam(Index: Integer): TcaVmtMethodParam; function GetParamCount: Integer; function GetSize: Word; // Private methods function GetBaseSize: Integer; procedure Update; procedure UpdateParams; public constructor Create(AMethod: PVmtMethod); destructor Destroy; override; // Properties property Address: Pointer read GetAddress; property Name: ShortString read GetName; property ParamCount: Integer read GetParamCount; property Params[Index: Integer]: TcaVmtMethodParam read GetParam; property Size: Word read GetSize; end; //--------------------------------------------------------------------------- // IcaVmt   //--------------------------------------------------------------------------- IcaVmt = interface ['{3A7CB947-AFFF-4719-AB54-45D28D8D92C7}'] // Property methods function GetMethodCount: Integer; function GetMethod(Index: Integer): TcaVmtMethod; // Public methods function MethodByName(const AMethodName: String): TcaVmtMethod; // Properties property MethodCount: Integer read GetMethodCount; property Methods[Index: Integer]: TcaVmtMethod read GetMethod; end; //--------------------------------------------------------------------------- // TcaVmt   //--------------------------------------------------------------------------- TcaVmt = class(TInterfacedObject, IcaVmt) private // Private fields FClass: TClass; FMethods: TObjectList; FMethodTable: PVmtMethodTable; FVmt: PVmt; // Private methods procedure Update; procedure UpdateMethodTable; procedure UpdateMethods; procedure UpdateVmt; // Property methods function GetMethodCount: Integer; function GetMethod(Index: Integer): TcaVmtMethod; protected public constructor Create(AClass: TClass); destructor Destroy; override; // Public methods function MethodByName(const AMethodName: String): TcaVmtMethod; // Properties property MethodCount: Integer read GetMethodCount; property Methods[Index: Integer]: TcaVmtMethod read GetMethod; end; const cMethodPadding = 6; implementation //--------------------------------------------------------------------------- // TcaVmtMethodParam   //--------------------------------------------------------------------------- constructor TcaVmtMethodParam.Create(AParam: PMethodParam); begin inherited Create; FParam := AParam; Update; end; destructor TcaVmtMethodParam.Destroy; begin inherited; end; // Private methods  function TcaVmtMethodParam.GetClassName: String; begin Result := GetParamClassType.ClassName; end; function TcaVmtMethodParam.GetEnumName: String; begin end; function TcaVmtMethodParam.GetMethodName: String; begin end; procedure TcaVmtMethodParam.Update; begin case GetParamTypeInfo^.Kind of tkInteger: FTypeName := 'Integer'; tkChar: FTypeName := 'Char'; tkEnumeration: FTypeName := GetEnumName; tkFloat: FTypeName := 'Double'; tkString: FTypeName := 'ShortString'; tkClass: FTypeName := GetClassName; tkMethod: FTypeName := GetMethodName; tkWChar: FTypeName := 'WideString'; tkLString: FTypeName := 'String'; tkWString: FTypeName := 'WideString'; else FTypeName := ''; end; end; // Property methods  function TcaVmtMethodParam.GetParamName: ShortString; begin Result := FParam^.Name; end; function TcaVmtMethodParam.GetParamClassType: TClass; var PropTypeData: PTypeData; PropTypeInfo: TTypeInfo; begin PropTypeInfo := FParam^.TypeInfo^^; PropTypeData := GetTypeData(@PropTypeInfo); Result := PropTypeData.ClassType; end; function TcaVmtMethodParam.GetParamTypeInfo: PPTypeInfo; begin Result := FParam^.TypeInfo; end; function TcaVmtMethodParam.GetParamTypeName: string; begin Result := FTypeName; end; //--------------------------------------------------------------------------- // TcaVmtMethod   //--------------------------------------------------------------------------- constructor TcaVmtMethod.Create(AMethod: PVmtMethod); begin inherited Create; FMethod := AMethod; FParams := TObjectList.Create(True); Update; end; destructor TcaVmtMethod.Destroy; begin FParams.Free; inherited; end; // Private methods  function TcaVmtMethod.GetBaseSize: Integer; begin Result := SizeOf(Word) + SizeOf(Pointer) + Length(FMethod^.Name) + 1; end; procedure TcaVmtMethod.Update; begin UpdateParams; end; procedure TcaVmtMethod.UpdateParams; var MethodParam: TcaVmtMethodParam; Param: PMethodParam; ParamSize: Integer; TotalSize: Integer; begin FParams.Clear; TotalSize := GetBaseSize + cMethodPadding; if GetSize > TotalSize then begin Param := PMethodParam(PChar(FMethod) + TotalSize); // Loop through all the method parameters. while GetSize - TotalSize > SizeOf(PTypeInfo) do begin MethodParam := TcaVmtMethodParam.Create(Param); FParams.Add(MethodParam); // Increment the pointer past the TypeInfo pointer, the param name, // its length, and a trailing #0 byte. ParamSize := SizeOf(PTypeInfo) + Length(Param^.Name) + 2; Param := PMethodParam(PChar(Param) + ParamSize); Inc(TotalSize, ParamSize); end; end; end; // Property methods  function TcaVmtMethod.GetAddress: Pointer; begin Result := FMethod^.Address; end; function TcaVmtMethod.GetName: ShortString; begin Result := FMethod^.Name; end; function TcaVmtMethod.GetParam(Index: Integer): TcaVmtMethodParam; begin Result := TcaVmtMethodParam(FParams[Index]); end; function TcaVmtMethod.GetParamCount: Integer; begin Result := FParams.Count; end; function TcaVmtMethod.GetSize: Word; begin Result := FMethod^.Size; end; //--------------------------------------------------------------------------- // TcaVmt   //--------------------------------------------------------------------------- constructor TcaVmt.Create(AClass: TClass); begin inherited Create; FClass := AClass; FMethods := TObjectList.Create(True); Update; end; destructor TcaVmt.Destroy; begin FMethods.Free; inherited; end; // Public methods  function TcaVmt.MethodByName(const AMethodName: string): TcaVmtMethod; var Index: Integer; Method: TcaVmtMethod; begin Result := nil; for Index := 0 to Pred(GetMethodCount) do begin Method := GetMethod(Index); if Method.Name = AMethodName then begin Result := Method; Break; end; end; end; procedure TcaVmt.Update; begin UpdateVmt; UpdateMethodTable; UpdateMethods; end; procedure TcaVmt.UpdateVmt; begin FVmt := PVmt(FClass); Dec(FVmt); end; procedure TcaVmt.UpdateMethodTable; begin FMethodTable := FVmt^.MethodTable; end; procedure TcaVmt.UpdateMethods; var Index: Integer; Method: TcaVmtMethod; MethodPtr: PChar; MethodTable: PVmtMethodTable; AMethodCount: Integer; Vmt: PVmt; ParentClass: TClass; begin Vmt := FVmt; FMethods.Clear; while Vmt <> nil do begin MethodTable := Vmt^.MethodTable; if MethodTable <> nil then begin MethodPtr := @MethodTable.Methods; AMethodCount := MethodTable^.Count; for Index := 0 to Pred(AMethodCount) do begin Method := TcaVmtMethod.Create(PVmtMethod(MethodPtr)); FMethods.Add(Method); Inc(MethodPtr, PVmtMethod(MethodPtr)^.Size); end; end; if Vmt^.ClassParent <> nil then begin ParentClass := Vmt^.ClassParent^; if ParentClass <> nil then begin Vmt := PVmt(ParentClass); Dec(Vmt); end; end else Vmt := nil; end; end; // Property methods  function TcaVmt.GetMethod(Index: Integer): TcaVmtMethod; begin Result := TcaVmtMethod(FMethods[Index]); end; function TcaVmt.GetMethodCount: Integer; begin Result := FMethods.Count; end; end.
unit controlUtils; uses ABCObjects, ABCButtons, GraphABC; type TBtnClickEvent = procedure; TBtnPosition = (bpLeft, bpCenter, bpRight); TControlUtils = class(ContainerABC) private counter: integer = 1; public constructor create; ///отцентрировать относительно окна, учитывая реальный размер procedure setToCenter(); procedure addMenuButton(btn_text: string; on_click: TBtnClickEvent); end; ///небольшой класс для показа "диалоговых" окон или просто инфо-сообщений TDialogs = class private _userClickEvent: TBtnClickEvent; _modalVisible: boolean = false; //просто флаг. если открыто модальное окно lastBaseObj: ObjectABC; lastText: TextABC; buttons: array of ButtonABC; buttonsCount: integer = 0; ///возвращает готовый текстовый объект, отцентрированный function getBaseObject(text: string): RectangleABC; function makeButton(text: string; onClick: TBtnClickEvent; btnPosition: TBtnPosition): ButtonABC; procedure onOKBtnClick; procedure onCancelBtnClick; public constructor create; procedure showInfo(text: string); procedure showConfirm(text: string; onOK: TBtnClickEvent); procedure closeLastDialog; procedure pressOK; function modalVisible: boolean; //возвращает true, если сейчас активно модальное окно end; procedure TDialogs.pressOK; begin onOKBtnClick(); end; procedure TDialogs.showConfirm(text: string; onOK: TBtnClickEvent); var okBtn, cancelBtn: ButtonABC; begin getBaseObject(text); okBtn := makeButton('OK', onOKBtnClick, bpLeft); _userClickEvent := onOk; cancelBtn := makeButton('Отмена', onCancelBtnClick, bpRight); end; function TDialogs.modalVisible: boolean; begin result := _modalVisible; end; procedure TDialogs.closeLastDialog; begin lastBaseObj.Destroy(); lastText.Destroy(); for var i := 0 to buttonsCount - 1 do buttons[i].Destroy(); SetLength(buttons, 0); buttonsCount := 0; _userClickEvent := nil; _modalVisible := false; end; procedure TDialogs.onCancelBtnClick; begin closeLastDialog(); end; procedure TDialogs.onOKBtnClick; begin if (_userClickEvent <> nil) then _userClickEvent(); closeLastDialog(); end; function TDialogs.makeButton(text: string; onClick: TBtnClickEvent; btnPosition: TBtnPosition): ButtonABC; var btn: ButtonABC; left: integer; width: integer; begin width := 100; //по-умолчанию кнопка будет вооот такой ширины if (TextWidth(text) >= 100) then //но если вдруг текста много... width := TextWidth(text) + 4; case (btnPosition) of bpLeft: left := lastBaseObj.Left; bpCenter: left := lastBaseObj.Left + lastBaseObj.Width div 2 - width div 2; bpRight: left := (lastBaseObj.Left + lastBaseObj.Width) - width; end; btn := new ButtonABC(left, lastBaseObj.top + lastBaseObj.height, width, 30, text, clOrange); btn.FontColor := clWhite; btn.FontStyle := fsBold; btn.OnClick := onClick; SetLength(buttons, buttonsCount + 1); buttons[buttonsCount] := btn; inc(buttonsCount); result := btn; end; function TDialogs.getBaseObject(text: string): RectangleABC; var t: TextABC; r: RectangleABC; begin t := new TextABC(0, 0, 14, text, clWhite); r := new RectangleABC(window.Width div 2 - TextWidth(text) div 2, window.Height div 2 - TextHeight(text) div 2 - 60, t.Width + 7, t.Height + 7, RGB(167, 153, 140)); t.Left := r.Left + 3; t.Top := r.Top + 3; t.ToFront; lastText := t; lastBaseObj := r; result := r; _modalVisible := true; end; procedure TDialogs.showInfo(text: string); var okBtn: ButtonABC; begin getBaseObject(text); okBtn := makeButton('OK', onOKBtnClick, bpCenter); end; constructor TDialogs.create; begin SetLength(buttons, 0); end; {********} procedure TControlUtils.setToCenter(); begin left := window.Width div 2 - Width div 2; top := window.Height div 2 - Height div 2; end; procedure TControlUtils.addMenuButton(btn_text: string; on_click: TBtnClickEvent); var btn: ButtonABC; begin btn := new ButtonABC(left, top + 42 * counter, 100, 40, btn_text, clOrange); btn.FontStyle := fsBold; btn.FontColor := clWhite; btn.Owner := self; // btn.OnClick := on_click; Add(btn); inc(counter); end; constructor TControlUtils.create; begin inherited create(0, 0); //Center := Window.Center; end; end.
unit ncDirUtils; interface uses {$IFNDEF NOLOG} uLogs, {$ENDIF} classes, sysutils, windows, dateutils; type TCleanDirEvent = procedure (Dirname : string) of object; TFileDirEvent = procedure (Sender:TObject; aDir, aFileName : string; aWin32FindData: TWin32FindData) of object; TFileDirProc = procedure (Sender:TObject; aDir, aFileName : string; aWin32FindData: TWin32FindData); TCopyMoveDirEvent = procedure (aOrigem, aDestino : string) of object; procedure ScanDir(Sender:TObject; d:string; recursar:boolean; devt, fevt : TFileDirProc); procedure CleanUpDirectory(Directory:string; evt : TCleanDirEvent; const fevt : TFileDirEvent=nil); procedure CleanUpAndDeleteDirectory(Directory:string; evt : TCleanDirEvent; const fevt : TFileDirEvent=nil); procedure CleanUpDirectoryIfOlderThan(days:integer; Directory:string; evt : TCleanDirEvent; const fevt : TFileDirEvent=nil); procedure CleanUpAndDeleteDirectoryIfOlderThan(days:integer; Directory:string; evt : TCleanDirEvent; const fevt : TFileDirEvent=nil); implementation procedure _CleanUpDir(days:integer; d:string; deletar: boolean; evt : TCleanDirEvent; const fevt : TFileDirEvent=nil); var data : TDateTime; sr : TSearchRec; dl : TStringList; i : integer; begin {$WARNINGS OFF} // protecção contra del c:\*.* if trim(d)='' then exit; gLog.Log(nil, [lcTrace], '_CleanUpDir: ' + D ); if assigned(evt) then evt(d); dl := TStringList.Create; try if FindFirst( d + '*.*', faDirectory , sr) = 0 then begin repeat if (sr.Attr and faDirectory) = faDirectory then if (sr.Name<>'.') and (sr.Name<>'..') then begin data := FileDateToDateTime(sr.Time); if (days=0) or (daysbetween(now , data) > days) then dl.Add(d + sr.Name + '\') ; end; until FindNext(sr) <> 0; sysutils.FindClose(sr); end; for i:=0 to dl.count-1 do _CleanUpDir(days, dl[i], deletar, evt, fevt); finally dl.Free; end; if FindFirst( d + '*.*', faArchive + fahidden + faReadOnly, sr) = 0 then begin repeat if sr.FindData.dwFileAttributes and FILE_ATTRIBUTE_READONLY = FILE_ATTRIBUTE_READONLY then SetFileAttributes(PChar(d + sr.Name), sr.FindData.dwFileAttributes and (not FILE_ATTRIBUTE_READONLY)); if sr.FindData.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN = FILE_ATTRIBUTE_HIDDEN then SetFileAttributes(PChar(d + sr.Name), sr.FindData.dwFileAttributes and (not FILE_ATTRIBUTE_HIDDEN)); if assigned(fevt) then fevt({Sender}nil, d , sr.Name, sr.FindData); windows.DeleteFile ( pchar(d + sr.Name) ) ; until FindNext(sr) <> 0; sysutils.FindClose(sr); end; if deletar then begin gLog.Log(nil, [lcTrace], '_CleanUpDir - RemoveDir: ' + D ); RemoveDir( pchar( d ) ); end; {$WARNINGS ON} end; procedure CleanUpDirectoryIfOlderThan(days:integer; Directory:string; evt : TCleanDirEvent; const fevt : TFileDirEvent=nil); begin _CleanUpDir (days, Directory, false, evt, fevt); end; procedure CleanUpAndDeleteDirectoryIfOlderThan(days:integer; Directory:string; evt : TCleanDirEvent; const fevt : TFileDirEvent=nil); begin _CleanUpDir (days, Directory, true, evt, fevt); end; procedure CleanUpAndDeleteDirectory(Directory:string; evt : TCleanDirEvent; const fevt : TFileDirEvent=nil); begin {$IFNDEF NOLOG} GLog.Log(nil, [lcTrace], 'CleanUpAndDeleteDirectory: '+Directory); {$ENDIF} _CleanUpDir (0, Directory, true, evt, fevt); end; procedure CleanUpDirectory(Directory:string; evt : TCleanDirEvent; const fevt : TFileDirEvent=nil); begin {$IFNDEF NOLOG} GLog.Log(nil, [lcTrace], 'CleanUpDirectory: '+Directory); {$ENDIF} _CleanUpDir (0, Directory, false, evt, fevt); end; procedure _ScanDir(Sender:TObject; d:string; recursar:boolean; devt, fevt : TFileDirProc); var sr : TSearchRec; dl : TStringList; i : integer; begin {$WARNINGS OFF} // protecção contra del c:\*.* if trim(d)='' then exit; dl := TStringList.Create; try if FindFirst( d + '*.*', faDirectory , sr) = 0 then begin repeat if (sr.Attr and faDirectory) = faDirectory then if (sr.Name<>'.') and (sr.Name<>'..') then begin dl.Add(d + sr.Name + '\') ; if assigned(devt) then devt(Sender, d , sr.Name, sr.FindData); end; until FindNext(sr) <> 0; sysutils.FindClose(sr); end; if recursar then for i:=0 to dl.count-1 do _ScanDir(Sender, dl[i], recursar, devt, fevt); finally dl.Free; end; if FindFirst( d + '*.*', faArchive + fahidden + faReadOnly, sr) = 0 then begin repeat if assigned(fevt) then fevt(Sender, d , sr.Name, sr.FindData); until FindNext(sr) <> 0; sysutils.FindClose(sr); end; {$WARNINGS ON} end; procedure ScanDir(Sender:TObject; d:string; recursar:boolean; devt, fevt : TFileDirProc); begin _ScanDir(Sender, d, recursar, devt, fevt); end; end.
unit IdNetworkCalculator; interface uses SysUtils, Classes, IdBaseComponent; type TIpStruct = record case integer of 0: (Byte4, Byte3, Byte2, Byte1: byte); 1: (FullAddr: Longword); end; TNetworkClass = (ID_NET_CLASS_A, ID_NET_CLASS_B, ID_NET_CLASS_C, ID_NET_CLASS_D, ID_NET_CLASS_E); const ID_NC_MASK_LENGTH = 32; ID_NETWORKCLASS = ID_NET_CLASS_A; type TIpProperty = class(TPersistent) protected FReadOnly: boolean; FOnChange: TNotifyEvent; FByteArray: array[0..31] of boolean; FDoubleWordValue: Longword; FAsString: string; FAsBinaryString: string; FByte3: Byte; FByte4: Byte; FByte2: Byte; FByte1: byte; procedure SetReadOnly(const Value: boolean); procedure SetOnChange(const Value: TNotifyEvent); function GetByteArray(Index: cardinal): boolean; procedure SetAsBinaryString(const Value: string); procedure SetAsDoubleWord(const Value: Longword); procedure SetAsString(const Value: string); procedure SetByteArray(Index: cardinal; const Value: boolean); procedure SetByte4(const Value: Byte); procedure SetByte1(const Value: byte); procedure SetByte3(const Value: Byte); procedure SetByte2(const Value: Byte); // property ReadOnly: boolean read FReadOnly write SetReadOnly default false; public procedure SetAll(One, Two, Tree, Four: Byte); virtual; procedure Assign(Source: Tpersistent); override; // property ByteArray[Index: cardinal]: boolean read GetByteArray write SetByteArray; published property Byte1: byte read FByte1 write SetByte1 stored false; property Byte2: Byte read FByte2 write SetByte2 stored false; property Byte3: Byte read FByte3 write SetByte3 stored false; property Byte4: Byte read FByte4 write SetByte4 stored false; property AsDoubleWord: Longword read FDoubleWordValue write SetAsDoubleWord stored false; property AsBinaryString: string read FAsBinaryString write SetAsBinaryString stored false; property AsString: string read FAsString write SetAsString; property OnChange: TNotifyEvent read FOnChange write SetOnChange; end; TIdNetworkCalculator = class(TIdBaseComponent) protected FListIP: TStrings; FNetworkMaskLength: cardinal; FNetworkMask: TIpProperty; FNetworkAddress: TIpProperty; FNetworkClass: TNetworkClass; FOnChange: TNotifyEvent; FOnGenIPList: TNotifyEvent; procedure SetOnChange(const Value: TNotifyEvent); procedure SetOnGenIPList(const Value: TNotifyEvent); function GetListIP: TStrings; procedure SetNetworkAddress(const Value: TIpProperty); procedure SetNetworkMask(const Value: TIpProperty); procedure SetNetworkMaskLength(const Value: cardinal); procedure OnNetMaskChange(Sender: TObject); procedure OnNetAddressChange(Sender: TObject); public function NumIP: integer; function StartIP: string; function EndIP: string; procedure FillIPList; constructor Create(AOwner: TComponent); override; destructor Destroy; override; // property ListIP: TStrings read GetListIP; property NetworkClass: TNetworkClass read FNetworkClass; published function IsAddressInNetwork(Address: string): Boolean; property NetworkAddress: TIpProperty read FNetworkAddress write SetNetworkAddress; property NetworkMask: TIpProperty read FNetworkMask write SetNetworkMask; property NetworkMaskLength: cardinal read FNetworkMaskLength write SetNetworkMaskLength default ID_NC_MASK_LENGTH; property OnGenIPList: TNotifyEvent read FOnGenIPList write SetOnGenIPList; property OnChange: TNotifyEvent read FOnChange write SetOnChange; end; implementation uses IdGlobal, IdResourceStrings; function IP(Byte1, Byte2, Byte3, Byte4: byte): TIpStruct; begin result.Byte1 := Byte1; result.Byte2 := Byte2; result.Byte3 := Byte3; result.Byte4 := Byte4; end; function StrToIP(const value: string): TIPStruct; var strBuffers: array[0..3] of string; cardBuffers: array[0..3] of cardinal; StrWork: string; begin StrWork := Value; strBuffers[0] := Fetch(StrWork, '.', true); strBuffers[1] := Fetch(StrWork, '.', true); strBuffers[2] := Fetch(StrWork, '.', true); strBuffers[3] := StrWork; try cardBuffers[0] := StrToInt(strBuffers[0]); cardBuffers[1] := StrToInt(strBuffers[1]); cardBuffers[2] := StrToInt(strBuffers[2]); cardBuffers[3] := StrToInt(strBuffers[3]); except on e: exception do raise exception.Create(Format(RSNETCALInvalidIPString, [Value])); end; if not (cardBuffers[0] in [0..255]) then raise exception.Create(Format(RSNETCALInvalidIPString, [Value])); if not (cardBuffers[1] in [0..255]) then raise exception.Create(Format(RSNETCALInvalidIPString, [Value])); if not (cardBuffers[2] in [0..255]) then raise exception.Create(Format(RSNETCALInvalidIPString, [Value])); if not (cardBuffers[3] in [0..255]) then raise exception.Create(Format(RSNETCALInvalidIPString, [Value])); result := IP(cardBuffers[0], cardBuffers[1], cardBuffers[2], cardBuffers[3]); end; constructor TIdNetworkCalculator.Create(AOwner: TComponent); begin inherited; FNetworkMask := TIpProperty.Create; FNetworkAddress := TIpProperty.Create; FNetworkMask.OnChange := OnNetMaskChange; FNetworkAddress.OnChange := OnNetAddressChange; FListIP := TStringList.Create; FNetworkClass := ID_NETWORKCLASS; NetworkMaskLength := ID_NC_MASK_LENGTH; end; destructor TIdNetworkCalculator.Destroy; begin FNetworkMask.Free; FNetworkAddress.Free; FListIP.Free; inherited; end; procedure TIdNetworkCalculator.FillIPList; var i: Cardinal; BaseIP: TIpStruct; begin if FListIP.Count = 0 then begin if (csDesigning in ComponentState) and (NumIP > 1024) then begin FListIP.text := Format(RSNETCALConfirmLongIPList, [NumIP]); end else begin BaseIP.FullAddr := NetworkAddress.AsDoubleWord and NetworkMask.AsDoubleWord; FListIP.Capacity := NumIP; FListIP.BeginUpdate; try for i := 1 to (NumIP - 1) do begin Inc(BaseIP.FullAddr); FListIP.append(format('%d.%d.%d.%d', [BaseIP.Byte1, BaseIP.Byte2, BaseIP.Byte3, BaseIP.Byte4])); end; finally FListIP.EndUpdate; end; end; end; end; function TIdNetworkCalculator.GetListIP: TStrings; begin FillIPList; result := FListIP; end; function TIdNetworkCalculator.IsAddressInNetwork(Address: string): Boolean; var IPStruct: TIPStruct; begin IPStruct := StrToIP(Address); result := (IPStruct.FullAddr and NetworkMask.FDoubleWordValue) = (NetworkAddress.FDoubleWordValue and NetworkMask.FDoubleWordValue); end; procedure TIdNetworkCalculator.OnNetAddressChange(Sender: TObject); begin FListIP.Clear; if IndyPos('0', NetworkAddress.AsBinaryString) = 1 then begin fNetworkClass := ID_NET_CLASS_A; end; if IndyPos('10', NetworkAddress.AsBinaryString) = 1 then begin fNetworkClass := ID_NET_CLASS_B; end; if IndyPos('110', NetworkAddress.AsBinaryString) = 1 then begin fNetworkClass := ID_NET_CLASS_C; end; if IndyPos('1110', NetworkAddress.AsBinaryString) = 1 then begin fNetworkClass := ID_NET_CLASS_D; end; if IndyPos('1111', NetworkAddress.AsBinaryString) = 1 then begin fNetworkClass := ID_NET_CLASS_E; end; if assigned(FOnChange) then FOnChange(Self); end; procedure TIdNetworkCalculator.OnNetMaskChange(Sender: TObject); var sBuffer: string; InitialMaskLength: Cardinal; begin FListIP.Clear; InitialMaskLength := FNetworkMaskLength; sBuffer := FNetworkMask.AsBinaryString; while (length(sBuffer) > 0) and (sBuffer[1] = '1') do begin Delete(sBuffer, 1, 1); end; if IndyPos('1', sBuffer) > 0 then begin NetworkMaskLength := InitialMaskLength; raise exception.Create(RSNETCALCInvalidNetworkMask); end else begin NetworkMaskLength := 32 - Length(sBuffer); end; if assigned(FOnChange) then FOnChange(Self); end; procedure TIdNetworkCalculator.SetNetworkAddress(const Value: TIpProperty); begin FNetworkAddress.Assign(Value); end; procedure TIdNetworkCalculator.SetNetworkMask(const Value: TIpProperty); begin FNetworkMask.Assign(Value); end; procedure TIdNetworkCalculator.SetNetworkMaskLength(const Value: cardinal); var LBuffer: Cardinal; begin FNetworkMaskLength := Value; if Value > 0 then begin LBuffer := High(Cardinal) shl (32 - Value); end else begin LBuffer := 0; end; FNetworkMask.AsDoubleWord := LBuffer; end; procedure TIdNetworkCalculator.SetOnGenIPList(const Value: TNotifyEvent); begin FOnGenIPList := Value; end; procedure TIdNetworkCalculator.SetOnChange(const Value: TNotifyEvent); begin FOnChange := Value; end; procedure TIpProperty.Assign(Source: Tpersistent); begin if Source is TIpProperty then with source as TIpProperty do begin Self.SetAll(Byte1, Byte2, Byte3, Byte4); end; if assigned(FOnChange) then FOnChange(Self); inherited; end; function TIpProperty.GetByteArray(Index: cardinal): boolean; begin result := FByteArray[index] end; procedure TIpProperty.SetAll(One, Two, Tree, Four: Byte); var i: Integer; InitialIP, IpStruct: TIpStruct; begin InitialIP := IP(FByte1, FByte2, FByte3, FByte4); FByte1 := One; FByte2 := Two; FByte3 := Tree; FByte4 := Four; IpStruct.Byte1 := Byte1; IpStruct.Byte2 := Byte2; IpStruct.Byte3 := Byte3; IpStruct.Byte4 := Byte4; FDoubleWordValue := IpStruct.FullAddr; SetLength(FAsBinaryString, 32); for i := 1 to 32 do begin FByteArray[i - 1] := ((FDoubleWordValue shl (i - 1)) shr 31) = 1; if FByteArray[i - 1] then FAsBinaryString[i] := '1' else FAsBinaryString[i] := '0'; end; FAsString := Format('%d.%d.%d.%d', [FByte1, FByte2, FByte3, FByte4]); IpStruct := IP(FByte1, FByte2, FByte3, FByte4); if IpStruct.FullAddr <> InitialIP.FullAddr then begin if assigned(FOnChange) then FOnChange(self); end; end; procedure TIpProperty.SetAsBinaryString(const Value: string); var IPStruct: TIPStruct; i: Integer; begin if ReadOnly then exit; if Length(Value) <> 32 then raise Exception.Create(RSNETCALCInvalidValueLength) else begin if not AnsiSameText(Value, FAsBinaryString) then begin IPStruct.FullAddr := 0; for i := 1 to 32 do begin if Value[i] <> '0' then IPStruct.FullAddr := IPStruct.FullAddr + (1 shl (32 - i)); SetAll(IPStruct.Byte1, IPStruct.Byte2, IPStruct.Byte3, IPStruct.Byte4); end; end; end; end; procedure TIpProperty.SetAsDoubleWord(const Value: Cardinal); var IpStruct: TIpStruct; begin if ReadOnly then exit; IpStruct.FullAddr := value; SetAll(IpStruct.Byte1, IpStruct.Byte2, IpStruct.Byte3, IpStruct.Byte4); end; procedure TIpProperty.SetAsString(const Value: string); var IPStruct: TIPStruct; begin if ReadOnly then exit; IPStruct := StrToIP(value); SetAll(IPStruct.Byte1, IPStruct.Byte2, IPStruct.Byte3, IPStruct.Byte4); end; procedure TIpProperty.SetByteArray(Index: cardinal; const Value: boolean); var IPStruct: TIpStruct; begin if ReadOnly then exit; if FByteArray[Index] <> value then begin FByteArray[Index] := Value; IPStruct.FullAddr := FDoubleWordValue; if Value then IPStruct.FullAddr := IPStruct.FullAddr + (1 shl index) else IPStruct.FullAddr := IPStruct.FullAddr - (1 shl index); SetAll(IPStruct.Byte1, IPStruct.Byte2, IPStruct.Byte3, IPStruct.Byte4); end; end; procedure TIpProperty.SetByte4(const Value: Byte); begin if ReadOnly then exit; if FByte4 <> value then begin FByte4 := Value; SetAll(FByte1, FByte2, FByte3, FByte4); end; end; procedure TIpProperty.SetByte1(const Value: byte); begin if FByte1 <> value then begin FByte1 := Value; SetAll(FByte1, FByte2, FByte3, FByte4); end; end; procedure TIpProperty.SetByte3(const Value: Byte); begin if FByte3 <> value then begin FByte3 := Value; SetAll(FByte1, FByte2, FByte3, FByte4); end; end; procedure TIpProperty.SetByte2(const Value: Byte); begin if ReadOnly then exit; if FByte2 <> value then begin FByte2 := Value; SetAll(FByte1, FByte2, FByte3, FByte4); end; end; procedure TIpProperty.SetOnChange(const Value: TNotifyEvent); begin FOnChange := Value; end; procedure TIpProperty.SetReadOnly(const Value: boolean); begin FReadOnly := Value; end; function TIdNetworkCalculator.EndIP: string; var IP: TIpStruct; begin IP.FullAddr := NetworkAddress.AsDoubleWord and NetworkMask.AsDoubleWord; Inc(IP.FullAddr, NumIP - 2); result := Format('%d.%d.%d.%d', [IP.Byte1, IP.Byte2, IP.Byte3, IP.Byte4]); end; function TIdNetworkCalculator.NumIP: integer; begin NumIP := 1 shl (32 - NetworkMaskLength); end; function TIdNetworkCalculator.StartIP: string; var IP: TIpStruct; begin IP.FullAddr := NetworkAddress.AsDoubleWord and NetworkMask.AsDoubleWord; result := Format('%d.%d.%d.%d', [IP.Byte1, IP.Byte2, IP.Byte3, IP.Byte4]); end; end.
unit SimpleQueryFiredac; interface uses SimpleInterface, FireDAC.Comp.Client, System.Classes, Data.DB, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet; Type TSimpleQueryFiredac = class(TInterfacedObject, iSimpleQuery) private FConnection : TFDConnection; FQuery : TFDQuery; FParams : TParams; public constructor Create(aConnection : TFDConnection); destructor Destroy; override; class function New(aConnection : TFDConnection) : iSimpleQuery; function SQL : TStrings; function Params : TParams; function ExecSQL : iSimpleQuery; function DataSet : TDataSet; function Open(aSQL : String) : iSimpleQuery; overload; function Open : iSimpleQuery; overload; end; implementation uses System.SysUtils; { TSimpleQuery<T> } constructor TSimpleQueryFiredac.Create(aConnection : TFDConnection); begin FQuery := TFDQuery.Create(nil); FConnection := aConnection; FQuery.Connection := FConnection; end; function TSimpleQueryFiredac.DataSet: TDataSet; begin Result := TDataSet(FQuery); end; destructor TSimpleQueryFiredac.Destroy; begin FreeAndNil(FQuery); if Assigned(FParams) then FreeAndNil(FParams); inherited; end; function TSimpleQueryFiredac.ExecSQL: iSimpleQuery; begin Result := Self; if Assigned(FParams) then FQuery.Params.Assign(FParams); FQuery.Prepare; FQuery.ExecSQL; if Assigned(FParams) then FreeAndNil(FParams); end; class function TSimpleQueryFiredac.New(aConnection : TFDConnection): iSimpleQuery; begin Result := Self.Create(aConnection); end; function TSimpleQueryFiredac.Open: iSimpleQuery; begin Result := Self; FQuery.Close; if Assigned(FParams) then FQuery.Params.Assign(FParams); FQuery.Prepare; FQuery.Open; if Assigned(FParams) then FreeAndNil(FParams); end; function TSimpleQueryFiredac.Open(aSQL: String): iSimpleQuery; begin Result := Self; FQuery.Close; FQuery.Open(aSQL); end; function TSimpleQueryFiredac.Params: TParams; begin if not Assigned(FParams) then begin FParams := TParams.Create(nil); FParams.Assign(FQuery.Params); end; Result := FParams; end; function TSimpleQueryFiredac.SQL: TStrings; begin Result := FQuery.SQL; end; end.
{ ---------------------------------------------------------------------------- } { FormulaJIT for MB3D } { Copyright (C) 2016-2017 Andreas Maschke } { ---------------------------------------------------------------------------- } unit FormulaCompiler; interface uses SysUtils, Classes, TypeDefinitions, JITFormulas, {$ifdef USE_PAX_COMPILER} PaxCompiler, PaxProgram, PaxRegister, {$endif} CompilerUtil; type {$ifdef USE_PAX_COMPILER} TPaxCompiledFormula = class (TCompiledArtifact) private FPaxProgram: TPaxProgram; public destructor Destroy;override; end; TPaxFormulaCompiler = class (TPaxArtifactCompiler) private procedure Register_TypeTIteration3D; procedure Register_TypeTIteration3Dext; protected procedure RegisterFunctions; override; public {$ifdef JIT_FORMULA_PREPROCESSING} function PreprocessCode(const Code: String; const Formula: TJITFormula): String; {$endif} function CompileFormula(const Formula: TJITFormula): TPaxCompiledFormula; end; {$endif} TFormulaCompiler = class private {$ifdef USE_PAX_COMPILER} FDelegate: TPaxFormulaCompiler; {$endif} public constructor Create; destructor Destroy; override; {$ifdef JIT_FORMULA_PREPROCESSING} function PreprocessCode(const Code: String; const Formula: TJITFormula): String; {$endif} function CompileFormula(const Formula: TJITFormula): TCompiledArtifact; end; TFormulaCompilerRegistry = class public class function GetCompilerInstance(const Language: TCompilerLanguage): TFormulaCompiler; end; implementation uses Windows, Messages, Graphics, Controls, Forms, Dialogs, StdCtrls, TypInfo, Math, Math3D; {$ifdef USE_PAX_COMPILER} { --------------------------- TPaxFormulaCompiler ---------------------------- } procedure TPaxFormulaCompiler.Register_TypeTIteration3D; var H_FormulaRange: Integer; H_TIteration3D: Integer; { H_TPIteration3D: Integer; } procedure RegisterArray(const ElemName: String; const ElemType, RangeType: Integer); var H_Type: Integer; begin H_Type := FPaxCompiler.RegisterArrayType(H_TIteration3D, 'H_T'+ElemName, RangeType, ElemType, true); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, ElemName, H_Type); end; begin H_FormulaRange := FPaxCompiler.RegisterSubrangeType(0, 'FormulaRange', _typeBYTE, 0, 5); H_TIteration3D := FPaxCompiler.RegisterRecordType(0, 'TIteration3D', true); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'C1', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'C2', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'C3', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'J1', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'J2', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'J3', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'PVar', _typePOINTER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'SmoothItD', _typeSINGLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'Rout', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'ItResultI', _typeINTEGER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'maxIt', _typeINTEGER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'RStop', _typeSINGLE); RegisterArray('nHybrid', _typeINTEGER, H_FormulaRange); RegisterArray('fHPVar', _typePOINTER, H_FormulaRange); RegisterArray('fHybrid', _typePOINTER, H_FormulaRange); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'CalcSIT', _typeLONGBOOL); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'DoJulia', _typeLONGBOOL); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'LNRStop', _typeSINGLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'DEoption', _typeINTEGER); RegisterArray('fHln', _typeSINGLE, H_FormulaRange); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'iRepeatFrom', _typeINTEGER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'OTrap', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'VaryScale', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'bFirstIt', _typeINTEGER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'bTmp', _typeINTEGER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'Dfree1', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'Dfree2', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'Deriv1', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'Deriv2', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3D, 'Deriv3', _typeDOUBLE); {H_TPIteration3D :=} FPaxCompiler.RegisterPointerType(0, 'TPIteration3D', H_TIteration3D); end; procedure TPaxFormulaCompiler.Register_TypeTIteration3Dext; var H_FormulaRange: Integer; H_TIteration3Dext: Integer; { H_TPIteration3D: Integer; } H_FormulaInitialization, H_TFormulaInitialization: Integer; H_Range_0_63, H_Range_0_2: Integer; H_TVec3D, H_TPVec3D: Integer; H_LMSfunction, H_TLMSfunction: Integer; procedure RegisterArray(const ElemName: String; const ElemType, RangeType: Integer); var H_Type: Integer; begin H_Type := FPaxCompiler.RegisterArrayType(H_TIteration3Dext, 'H_T'+ElemName, RangeType, ElemType, true); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, ElemName, H_Type); end; begin H_FormulaRange := FPaxCompiler.RegisterSubrangeType(0, 'FormulaRange', _typeBYTE, 0, 5); // TFormulaInitialization H_FormulaInitialization := FPaxCompiler.RegisterRoutine(0, 'FormulaInitialization', _typeVOID, _ccREGISTER); FPaxCompiler.RegisterParameter(H_FormulaInitialization, _typePOINTER, _Unassigned); H_TFormulaInitialization := FPaxCompiler.RegisterProceduralType(0, 'TFormulaInitialization', H_FormulaInitialization); // TLMSfunction H_Range_0_2 := FPaxCompiler.RegisterSubrangeType(0, 'Range_0_2', _typeBYTE, 0, 2); H_TVec3D := FPaxCompiler.RegisterArrayType(0, 'TVec3D', H_Range_0_2, _typeDOUBLE); H_TPVec3D := FPaxCompiler.RegisterPointerType(0, 'TPVec3D', H_TVec3D); H_LMSfunction := FPaxCompiler.RegisterRoutine(0, 'LMSfunction', H_TVec3D, _ccREGISTER); FPaxCompiler.RegisterParameter(H_LMSfunction, H_TPVec3D, _Unassigned); FPaxCompiler.RegisterParameter(H_LMSfunction, _typeINTEGER, _Unassigned); H_TLMSfunction := FPaxCompiler.RegisterProceduralType(0, 'TLMSfunction', H_LMSfunction); H_TIteration3Dext := FPaxCompiler.RegisterRecordType(0, 'TIteration3Dext', true); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'J4', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'Rold', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'RStopD', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'x', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'y', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'z', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'w', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'C1', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'C2', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'C3', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'J1', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'J2', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'J3', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'PVar', _typePOINTER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'SmoothItD', _typeSINGLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'Rout', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'ItResultI', _typeINTEGER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'maxIt', _typeINTEGER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'RStop', _typeSINGLE); RegisterArray('nHybrid', _typeINTEGER, H_FormulaRange); RegisterArray('fHPVar', _typePOINTER, H_FormulaRange); RegisterArray('fHybrid', _typePOINTER, H_FormulaRange); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'CalcSIT', _typeBYTEBOOL); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'bFree', _typeBYTE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'EndTo', _typeWORD); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'DoJulia', _typeLONGBOOL); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'LNRStop', _typeSINGLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'DEoption', _typeINTEGER); RegisterArray('fHln', _typeSINGLE, H_FormulaRange); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'iRepeatFrom', _typeWORD); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'iStartFrom', _typeWORD); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'OTrap', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'VaryScale', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'bFirstIt', _typeINTEGER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'bTmp', _typeINTEGER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'Dfree1', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'Dfree2', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'Deriv1', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'Deriv2', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'Deriv3', _typeDOUBLE); // TSMatrix4 = array[0..3, 0..3] of Single - no idea how to register multi-dimensional arrays -> now lets us just reserve the space H_Range_0_63 := FPaxCompiler.RegisterSubrangeType(0, 'Range_0_63', _typeCHAR, 0, 63); RegisterArray('SMatrix4', _typeBYTE, H_Range_0_63); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'Ju1', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'Ju2', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'Ju3', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'Ju4', _typeDOUBLE); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'PMapFunc', H_TLMSfunction); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'PMapFunc2', H_TLMSfunction); RegisterArray('pInitialization', H_TFormulaInitialization, H_FormulaRange); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'bIsInsideRender', _typeLONGBOOL); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'OTrapMode', _typeINTEGER); FPaxCompiler.RegisterRecordTypeField(H_TIteration3Dext, 'OTrapDE', _typeDOUBLE); {H_TPIteration3Dext :=} FPaxCompiler.RegisterPointerType(0, 'TPIteration3Dext', H_TIteration3Dext); end; procedure TPaxFormulaCompiler.RegisterFunctions; begin Register_TypeTIteration3D; Register_TypeTIteration3Dext; Register_MathFunctions; Register_MiscFunctions; end; {$ifdef JIT_FORMULA_PREPROCESSING} function TPaxFormulaCompiler.PreprocessCode(const Code: String; const Formula: TJITFormula): String; var CodeLines: TStringList; VarSegment, CodeSegment: TStringList; I: Integer; ProcStartLine, VarStartLine, BeginStartLine: Integer; function NameToPascalName(const Name: String): String; var I: Integer; begin Result := Name; for I := 1 to Length(Result) do begin if (Result[I]=' ') or (Result[I]='-') or (Result[I]='+') or (Result[I]='/') or (Result[I]='*') or (Result[I]='') then Result[I] := '_'; end; end; procedure CreateSegments(VarSegment, CodeSegment: TStringList); var I, COffSet, VOffset: Integer; Pair: TNameValuePair; begin VarSegment.Add(' // begin preprocessor'); CodeSegment.Add(' // begin preprocessor'); COffset := 0; VOffset := 16; for I := 0 to Formula.GetValueCount(vtConst) - 1 do begin Pair := Formula.GetValue(vtConst, I); VarSegment.Add(' ' + NameToPascalName(Pair.Name) + ': '+JITValueDatatypeToStr(Pair.Datatype)+';'); CodeSegment.Add(' ' + NameToPascalName(Pair.Name) + ' := P'+JITValueDatatypeToStr(Pair.Datatype)+'(Integer(PIteration3D^.PVar) + '+IntToStr(COffset)+')^;'); Inc(COffset, JITValueDatatypeSize(Pair.Datatype)); end; for I := 0 to Formula.GetValueCount(vtParam) - 1 do begin Pair := Formula.GetValue(vtParam, I); VarSegment.Add(' ' + NameToPascalName(Pair.Name) + ': '+JITValueDatatypeToStr(Pair.Datatype)+';'); CodeSegment.Add(' ' + NameToPascalName(Pair.Name) + ' := P'+JITValueDatatypeToStr(Pair.Datatype)+'(Integer(PIteration3D^.PVar) - '+IntToStr(VOffset)+')^;'); Inc(VOffset, JITValueDatatypeSize(Pair.Datatype)); end; VarSegment.Add(' // end preprocessor'); CodeSegment.Add(' // end preprocessor'); end; function IsWhiteSpace(const C: Char): Boolean; begin Result := (C=' ') or (C=#13) or (C=#10) or (C=#9); end; function FindLineWithTerm(const SearchTerm: String; const LineOffset: Integer): Integer; var I, P: Integer; LCLine, LCSearchTerm: String; CharBefore, CharAfter: Char; begin Result := -1; LCSearchTerm := AnsiLowerCase(SearchTerm); for I := LineOffset to CodeLines.Count - 1 do begin LCLine := AnsiLowerCase(CodeLines[I]); P := Pos(LCSearchTerm, LCLine); if P > 0 then begin if P > 1 then CharBefore := Copy(LCLine, P - 1, 1)[1] else CharBefore := ' '; if P + Length(LCSearchTerm) < Length(LCLine) then CharAfter := Copy(LCLine, P + Length(LCSearchTerm))[1] else CharAfter := ' '; if IsWhiteSpace(CharBefore) and IsWhiteSpace(CharAfter) then begin Result := I; break; end; end; end; end; begin Result := Code; if (Formula.GetValueCount(vtConst) > 0) or (Formula.GetValueCount(vtParam) > 0) then begin CodeLines := TStringList.Create; try CodeLines.Text := Code; ProcStartLine := FindLineWithTerm('procedure', 0); if ProcStartLine >= 0 then begin BeginStartLine := FindLineWithTerm('begin', ProcStartLine + 1); if BeginStartLine < 0 then raise Exception.Create('Preprocessing error: <procedure> found, but no <begin>'); VarStartLine := FindLineWithTerm('var', ProcStartLine + 1); if VarStartLine > BeginStartLine then VarStartLine := -1; VarSegment := TStringList.Create; try CodeSegment := TStringList.Create; try CreateSegments(VarSegment, CodeSegment); if VarStartLine >= 0 then begin for I := 0 to VarSegment.Count-1 do CodeLines.Insert(VarStartLine + 1 + I, VarSegment[I]); for I := 0 to CodeSegment.Count-1 do CodeLines.Insert(BeginStartLine + VarSegment.Count + 1 + I, CodeSegment[I]); end else begin CodeLines.Insert(BeginStartLine, 'var'); for I := 0 to VarSegment.Count-1 do CodeLines.Insert(BeginStartLine + 1 + I, VarSegment[I]); for I := 0 to CodeSegment.Count-1 do CodeLines.Insert(BeginStartLine + VarSegment.Count + 2 + I, CodeSegment[I]); end; finally CodeSegment.Free; end; finally VarSegment.Free; end; Result := CodeLines.Text; end; finally CodeLines.Free; end; end else end; {$endif} function TPaxFormulaCompiler.CompileFormula(const Formula: TJITFormula): TPaxCompiledFormula; const DfltModule = '1'; var ProcName: String; CodeLine: String; I, P1, P2:Integer; H_ProcName: Integer; CodeLines: TStringList; Code: String; // MemStream: TMemoryStream; begin Result := TPaxCompiledFormula.Create; try Result.FPaxProgram := TPaxProgram.Create(nil); FPaxCompiler.ResetCompilation; FPaxCompiler.AddModule(DfltModule, FPaxPascalLanguage.LanguageName); // add formula-code (Delphi procedure) here ProcName := ''; if (Formula <> nil) and (Trim(Formula.Code) <> '') then begin {$ifdef JIT_FORMULA_PREPROCESSING} Code := PreprocessCode(Formula.Code, Formula); {$else} Code := Formula.Code; {$endif} CodeLines := TStringList.Create; try CodeLines.Text := Code; for I := 0 to CodeLines.Count - 1 do begin CodeLine := CodeLines[I]; FPaxCompiler.AddCode(DfltModule, CodeLine); if ProcName = '' then begin P1 := Pos('procedure ', CodeLine); if P1 > 0 then begin P2 := Pos('(', CodeLine, P1 + 1); if P2 > P1 then ProcName := Trim(Copy(CodeLine, P1 + 10, P2 - P1 - 10)); end; end; end; finally CodeLines.Free; end; end; if ProcName = '' then begin Result.AddErrorMessage('No formula found'); Result.AddErrorMessage('Should be something like <procedure MyFormula(var x, y, z, w: Double; PIteration3D: TPIteration3D);>'); exit; end; // add main body FPaxCompiler.AddCode(DfltModule, 'begin'); FPaxCompiler.AddCode(DfltModule, 'end.'); FPaxCompiler.DebugMode := False; if FPaxCompiler.Compile(TPaxCompiledFormula(Result).FPaxProgram, False, False) then begin H_ProcName := FPaxCompiler.GetHandle(0, ProcName, true); (* MemStream := TMemoryStream.Create; try TPaxCompiledFormula(Result).FPaxProgram.SaveToStream(MemStream); OutputDebugString(PChar('Saved: '+IntToStr(MemStream.Size)+' '+IntToStr( TPaxCompiledFormula(Result).FPaxProgram.ImageSize))); MemStream.Seek(0, soBeginning); TPaxCompiledFormula(Result).FPaxProgram.LoadFromStream(MemStream); finally MemStream.Free; end; *) Result.CodePointer := TPaxCompiledFormula(Result).FPaxProgram.GetAddress(H_ProcName); Result.CodeSize := TPaxCompiledFormula(Result).FPaxProgram.ProgramSize; end else begin for I:=0 to FPaxCompiler.ErrorCount do Result.AddErrorMessage(FPaxCompiler.ErrorMessage[I]); end; except FreeAndNil(Result); raise; end; end; { --------------------------- TPaxCompiledFormula ---------------------------- } destructor TPaxCompiledFormula.Destroy; begin if Assigned(FPaxProgram) then FreeAndNil(FPaxProgram); inherited Destroy; end; {$endif} { ------------------------ TFormulaCompilerRegistry -------------------------- } {$ifdef USE_PAX_COMPILER} var PaxFormulaCompiler : TFormulaCompiler; {$endif} class function TFormulaCompilerRegistry.GetCompilerInstance(const Language: TCompilerLanguage): TFormulaCompiler; begin case Language of langDELPHI: begin {$ifdef USE_PAX_COMPILER} if PaxFormulaCompiler = nil then PaxFormulaCompiler := TFormulaCompiler.Create; Result := PaxFormulaCompiler; exit; {$endif} end; end; raise Exception.Create('No compiler available for language <'+GetEnumName(TypeInfo(TCompilerLanguage), Ord(Language))+'>'); end; { ---------------------------- TFormulaCompiler ------------------------------ } constructor TFormulaCompiler.Create; begin inherited; {$ifdef USE_PAX_COMPILER} FDelegate := TPaxFormulaCompiler.Create; {$endif} end; destructor TFormulaCompiler.Destroy; begin {$ifdef USE_PAX_COMPILER} FDelegate.Free; {$endif} inherited; end; {$ifdef JIT_FORMULA_PREPROCESSING} function TFormulaCompiler.PreprocessCode(const Code: String; const Formula: TJITFormula): String; begin {$ifdef USE_PAX_COMPILER} Result := FDelegate.PreprocessCode( Code, Formula ); {$endif} end; {$endif} function TFormulaCompiler.CompileFormula(const Formula: TJITFormula): TCompiledArtifact; begin {$ifdef USE_PAX_COMPILER} Result := FDelegate.CompileFormula( Formula ); {$endif} end; initialization {$ifdef USE_PAX_COMPILER} PaxFormulaCompiler := nil; {$endif} finalization {$ifdef USE_PAX_COMPILER} FreeAndNil(PaxFormulaCompiler); {$endif} end.
unit uHumanres; {$mode objfpc}{$H+} interface uses SynCommons, mORMot, uForwardDeclaration; type // 1 TSQLPartyQual = class(TSQLRecord) private fParty: TSQLPartyID; fPartyQualType: TSQLPartyQualTypeID; fQualificationDesc: RawUTF8; fTitle: RawUTF8; fStatus: TSQLStatusItemID; fVerifStatus: TSQLStatusItemID; fFromDate: TDateTime; fThruDate: TDateTime; published property Party: TSQLPartyID read fParty write fParty; property PartyQualType: TSQLPartyQualTypeID read fPartyQualType write fPartyQualType; property QualificationDesc: RawUTF8 read fQualificationDesc write fQualificationDesc; property Title: RawUTF8 read fTitle write fTitle; property Status: TSQLStatusItemID read fStatus write fStatus; property VerifStatus: TSQLStatusItemID read fVerifStatus write fVerifStatus; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 2 TSQLPartyQualType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLPartyQualTypeID; fHasTable: Boolean; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLPartyQualTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 3 TSQLPartyResume = class(TSQLRecord) private fParty: TSQLPartyID; fContent: TSQLContentID; fResumeDate: TDateTime; fResumeText: RawUTF8; published property Party: TSQLPartyID read fParty write fParty; property Content: TSQLContentID read fContent write fContent; property ResumeDate: TDateTime read fResumeDate write fResumeDate; property ResumeText: RawUTF8 read fResumeText write fResumeText; end; // 4 TSQLPartySkill = class(TSQLRecord) private fParty: TSQLPartyID; fSkillType: TSQLSkillTypeID; fYearsExperience: Integer; fRating: Integer; fSkillLevel: Integer; fStartedUsingDate: TDateTime; published property Party: TSQLPartyID read fParty write fParty; property SkillType: TSQLSkillTypeID read fSkillType write fSkillType; property YearsExperience: Integer read fYearsExperience write fYearsExperience; property Rating: Integer read fRating write fRating; property SkillLevel: Integer read fSkillLevel write fSkillLevel; property StartedUsingDate: TDateTime read fStartedUsingDate write fStartedUsingDate; end; // 5 TSQLPerfRatingType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLPerfRatingTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLPerfRatingTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 6 TSQLPerfReview = class(TSQLRecord) private fEmployeeParty: TSQLPartyRoleID; //fEmployeeRoleType: TSQLPartyRoleID; fManagerParty: TSQLPartyRoleID; //fManagerRoleType: TSQLPartyRoleID; fPayment: TSQLPaymentID; fEmplPosition: TSQLEmplPositionID; fFromDate: TDateTime; fThruDate: TDateTime; fComments: RawUTF8; published property EmployeeParty: TSQLPartyRoleID read fEmployeeParty write fEmployeeParty; property ManagerParty: TSQLPartyRoleID read fManagerParty write fManagerParty; property Payment: TSQLPaymentID read fPayment write fPayment; property EmplPosition: TSQLEmplPositionID read fEmplPosition write fEmplPosition; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Comments: RawUTF8 read fComments write fComments; end; // 7 TSQLPerfReviewItem = class(TSQLRecord) private fPerfReview: TSQLPerfReviewID; //employeeParty, employeeRoleType, perfReview fPerfReviewItemSeq: Integer; fPerfReviewItemType: TSQLPerfReviewItemTypeID; fPerfRatingType: TSQLPerfRatingTypeID; fComments: RawUTF8; published property PerfReview: TSQLPerfReviewID read fPerfReview write fPerfReview; property PerfReviewItemSeq: Integer read fPerfReviewItemSeq write fPerfReviewItemSeq; property PerfReviewItemType: TSQLPerfReviewItemTypeID read fPerfReviewItemType write fPerfReviewItemType; property PerfRatingType: TSQLPerfRatingTypeID read fPerfRatingType write fPerfRatingType; property Comments: RawUTF8 read fComments write fComments; end; // 8 TSQLPerfReviewItemType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLPerfReviewItemTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLPerfReviewItemTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 9 TSQLPerformanceNote = class(TSQLRecord) private fParty: TSQLPartyRoleID; //partyId, roleTypeId fFromDate: TDateTime; fThruDate: TDateTime; fCommunicationDate: TDateTime; fComments: RawUTF8; published property Party: TSQLPartyRoleID read fParty write fParty; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property CommunicationDate: TDateTime read fCommunicationDate write fCommunicationDate; property Comments: RawUTF8 read fComments write fComments; end; // 10 TSQLPersonTraining = class(TSQLRecord) private fParty: TSQLPartyID; fTrainingRequest: TSQLTrainingRequestID; fTrainingClassType: TSQLTrainingClassTypeID; fWorkEffort: TSQLWorkEffortID; fFromDate: TDateTime; fThruDate: TDateTime; fApprover: TSQLPersonID; fApprovalStatus: RawUTF8; fReason: RawUTF8; published property Party: TSQLPartyID read fParty write fParty; property TrainingRequest: TSQLTrainingRequestID read fTrainingRequest write fTrainingRequest; property TrainingClassType: TSQLTrainingClassTypeID read fTrainingClassType write fTrainingClassType; property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Approver: TSQLPersonID read fApprover write fApprover; property ApprovalStatus: RawUTF8 read fApprovalStatus write fApprovalStatus; property Reason: RawUTF8 read fReason write fReason; end; // 11 TSQLResponsibilityType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLResponsibilityTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLResponsibilityTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 12 TSQLSkillType = class(TSQLRecord) private fParent: TSQLSkillTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; published property Parent: TSQLSkillTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 13 TSQLTrainingClassType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLTrainingClassTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLTrainingClassTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 14 TSQLBenefitType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLBenefitTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; fEmployerPaidPercentage: Double; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLBenefitTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; property EmployerPaidPercentage: Double read fEmployerPaidPercentage write fEmployerPaidPercentage; end; // 15 TSQLEmployment = class(TSQLRecord) private fPartyFrom: TSQLPartyRoleID; //partyIdFrom, roleTypeIdFrom fPartyTo: TSQLPartyRoleID; //partyIdTo, roleTypeIdTo fFromDate: TDateTime; fThruDate: TDateTime; fTerminationReason: TSQLTerminationReasonID; fTerminationType: TSQLTerminationTypeID; published property PartyFrom: TSQLPartyRoleID read fPartyFrom write fPartyFrom; property PartyTo: TSQLPartyRoleID read fPartyTo write fPartyTo; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property TerminationReason: TSQLTerminationReasonID read fTerminationReason write fTerminationReason; property TerminationType: TSQLTerminationTypeID read fTerminationType write fTerminationType; end; // 16 TSQLEmploymentApp = class(TSQLRecord) private fEmplPosition: TSQLEmplPositionID; fStatus: TSQLStatusItemID; fEmploymentAppSourceType: TSQLEmploymentAppSourceTypeID; fApplyingParty: TSQLPartyID; fReferredByParty: TSQLPartyID; fApplicationDate: TDateTime; fApproverParty: TSQLPartyID; fJobRequisition: TSQLJobRequisitionID; published property EmplPosition: TSQLEmplPositionID read fEmplPosition write fEmplPosition; property Status: TSQLStatusItemID read fStatus write fStatus; property EmploymentAppSourceType: TSQLEmploymentAppSourceTypeID read fEmploymentAppSourceType write fEmploymentAppSourceType; property ApplyingParty: TSQLPartyID read fApplyingParty write fApplyingParty; property ReferredByParty: TSQLPartyID read fReferredByParty write fReferredByParty; property ApplicationDate: TDateTime read fApplicationDate write fApplicationDate; property ApproverParty: TSQLPartyID read fApproverParty write fApproverParty; property JobRequisition: TSQLJobRequisitionID read fJobRequisition write fJobRequisition; end; // 17 TSQLEmploymentAppSourceType = class(TSQLRecord) private fParent: TSQLEmploymentAppSourceTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; published property Parent: TSQLEmploymentAppSourceTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 18 TSQLEmplLeave = class(TSQLRecord) private fParty: TSQLPartyID; fLeaveType: TSQLEmplLeaveTypeID; fEmplLeaveReasonType: TSQLEmplLeaveReasonTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fApproverParty: TSQLPartyID; fLeaveStatus: TSQLStatusItemID; fDescription: RawUTF8; published property Party: TSQLPartyID read fParty write fParty; property LeaveType: TSQLEmplLeaveTypeID read fLeaveType write fLeaveType; property EmplLeaveReasonType: TSQLEmplLeaveReasonTypeID read fEmplLeaveReasonType write fEmplLeaveReasonType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property ApproverParty: TSQLPartyID read fApproverParty write fApproverParty; property LeaveStatus: TSQLStatusItemID read fLeaveStatus write fLeaveStatus; property Description: RawUTF8 read fDescription write fDescription; end; // 19 TSQLEmplLeaveType = class(TSQLRecord) private fParent: TSQLEmplLeaveTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; published property Parent: TSQLEmplLeaveTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 20 TSQLPartyBenefit = class(TSQLRecord) private fPartyFrom: TSQLPartyRoleID; //partyIdFrom, roleTypeIdFrom fPartyTo: TSQLPartyRoleID; //partyIdTo, roleTypeIdTo fBenefitType: TSQLBenefitTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fPeriodType: TSQLPeriodTypeID; fCost: Currency; fActualEmployerPaidPercent: Double; fAvailableTime: Integer; published property PartyFrom: TSQLPartyRoleID read fPartyFrom write fPartyFrom; property PartyTo: TSQLPartyRoleID read fPartyTo write fPartyTo; property BenefitType: TSQLBenefitTypeID read fBenefitType write fBenefitType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property PeriodType: TSQLPeriodTypeID read fPeriodType write fPeriodType; property Cost: Currency read fCost write fCost; property ActualEmployerPaidPercent: Double read fActualEmployerPaidPercent write fActualEmployerPaidPercent; property AvailableTime: Integer read fAvailableTime write fAvailableTime; end; // 21 TSQLPayGrade = class(TSQLRecord) private fPayGradeName: RawUTF8; fComments: RawUTF8; published property PayGradeName: RawUTF8 read fPayGradeName write fPayGradeName; property Comments: RawUTF8 read fComments write fComments; end; // 22 TSQLPayHistory = class(TSQLRecord) private fEmployment: TSQLEmploymentID; //roleTypeIdFrom, roleTypeIdTo, partyIdFrom, partyIdTo, emplFromDate fFromDate: TDateTime; fThruDate: TDateTime; fSalaryStep: TSQLSalaryStepID; //salaryStepSeqId, payGradeId fPeriodType: TSQLPeriodTypeID; fAmount: Currency; fComments: RawUTF8; published property Employment: TSQLEmploymentID read fEmployment write fEmployment; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SalaryStep: TSQLSalaryStepID read fSalaryStep write fSalaryStep; property PeriodType: TSQLPeriodTypeID read fPeriodType write fPeriodType; property Amount: Currency read fAmount write fAmount; property Comments: RawUTF8 read fComments write fComments; end; // 23 TSQLPayrollPreference = class(TSQLRecord) private fParty: TSQLPartyRoleID; //partyId, roleTypeId fDeductionType: TSQLDeductionTypeID; fPaymentMethodType: TSQLPaymentMethodTypeID; fPeriodType: TSQLPeriodTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fPercentage: Double; fFlatAmount: Currency; fRoutingNumber: RawUTF8; fAccountNumber: RawUTF8; fBankName: RawUTF8; published property Party: TSQLPartyRoleID read fParty write fParty; property DeductionType: TSQLDeductionTypeID read fDeductionType write fDeductionType; property PaymentMethodType: TSQLPaymentMethodTypeID read fPaymentMethodType write fPaymentMethodType; property PeriodType: TSQLPeriodTypeID read fPeriodType write fPeriodType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Percentage: Double read fPercentage write fPercentage; property FlatAmount: Currency read fFlatAmount write fFlatAmount; property RoutingNumber: RawUTF8 read fRoutingNumber write fRoutingNumber; property AccountNumber: RawUTF8 read fAccountNumber write fAccountNumber; property BankName: RawUTF8 read fBankName write fBankName; end; // 24 TSQLSalaryStep = class(TSQLRecord) private fPayGrade: TSQLPayGradeID; fFromDate: TDateTime; fThruDate: TDateTime; fDateModified: TDateTime; fAmount: Currency; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedByUserLogin: TSQLUserLoginID; published property PayGrade: TSQLPayGradeID read fPayGrade write fPayGrade; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property DateModified: TDateTime read fDateModified write fDateModified; property Amount: Currency read fAmount write fAmount; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; end; // 25 TSQLTerminationReason = class(TSQLRecord) private fReason: RawUTF8; fDescription: RawUTF8; published property Reason: RawUTF8 read fReason write fReason; property Description: RawUTF8 read fDescription write fDescription; end; // 26 TSQLTerminationType = class(TSQLRecord) private fParent: TSQLTerminationTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; published property Parent: TSQLTerminationTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 27 TSQLUnemploymentClaim = class(TSQLRecord) private fUnemploymentClaimDate: TDateTime; fDescription: RawUTF8; fStatus: TSQLStatusItemID; fEmployment: TSQLEmploymentID; //roleTypeIdFrom, roleTypeIdTo, partyIdFrom, partyIdTo, fromDate fThruDate: TDateTime; published property UnemploymentClaimDate: TDateTime read fUnemploymentClaimDate write fUnemploymentClaimDate; property Description: RawUTF8 read FDescription write FDescription; property Status: TSQLStatusItemID read fStatus write fStatus; property Employment: TSQLEmploymentID read fEmployment write fEmployment; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 28 TSQLEmplPosition = class(TSQLRecord) private fStatus: TSQLStatusItemID; fParty: TSQLPartyID; fBudget: TSQLBudgetItemID; //budgetId, budgetItemSeqId fEmplPositionType: TSQLEmplPositionTypeID; fEstimatedFromDate: TDateTime; fEstimatedThruDate: TDateTime; fSalaryFlag: Boolean; fExemptFlag: Boolean; fFulltimeFlag: Boolean; fTemporaryFlag: Boolean; fActualFromDate: TDateTime; fActualThruDate: TDateTime; published property Status: TSQLStatusItemID read fStatus write fStatus; property Party: TSQLPartyID read fParty write fParty; property Budget: TSQLBudgetItemID read fBudget write fBudget; property EmplPositionType: TSQLEmplPositionTypeID read fEmplPositionType write fEmplPositionType; property EstimatedFromDate: TDateTime read fEstimatedFromDate write fEstimatedFromDate; property EstimatedThruDate: TDateTime read fEstimatedThruDate write fEstimatedThruDate; property SalaryFlag: Boolean read fSalaryFlag write fSalaryFlag; property ExemptFlag: Boolean read fExemptFlag write fExemptFlag; property FulltimeFlag: Boolean read fFulltimeFlag write fFulltimeFlag; property TemporaryFlag: Boolean read fTemporaryFlag write fTemporaryFlag; property ActualFromDate: TDateTime read fActualFromDate write fActualFromDate; property ActualThruDate: TDateTime read fActualThruDate write fActualThruDate; end; // 29 TSQLEmplPositionClassType = class(TSQLRecord) private fParent: TSQLEmplPositionClassTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; published property Parent: TSQLEmplPositionClassTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 30 TSQLEmplPositionFulfillment = class(TSQLRecord) private fEmplPosition: TSQLEmplPositionID; fParty: TSQLPartyID; fFromDate: TDateTime; fThruDate: TDateTime; fComments: RawUTF8; published property EmplPosition: TSQLEmplPositionID read fEmplPosition write fEmplPosition; property Party: TSQLPartyID read fParty write fParty; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Comments: RawUTF8 read fComments write fComments; end; // 31 TSQLEmplPositionReportingStruct = class(TSQLRecord) private fEmplPositionIdReportingTo: TSQLEmplPositionID; fEmplPositionIdManagedBy: TSQLEmplPositionID; fFromDate: TDateTime; fThruDate: TDateTime; fComments: RawUTF8; fPrimaryFlag: Boolean; published property EmplPositionIdReportingTo: TSQLEmplPositionID read fEmplPositionIdReportingTo write fEmplPositionIdReportingTo; property EmplPositionIdManagedBy: TSQLEmplPositionID read fEmplPositionIdManagedBy write fEmplPositionIdManagedBy; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Comments: RawUTF8 read fComments write fComments; property PrimaryFlag: Boolean read fPrimaryFlag write fPrimaryFlag; end; // 32 TSQLEmplPositionResponsibility = class(TSQLRecord) private fEmplPosition: TSQLEmplPositionID; fResponsibilityType: TSQLResponsibilityTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fComments: RawUTF8; published property EmplPosition: TSQLEmplPositionID read fEmplPosition write fEmplPosition; property ResponsibilityType: TSQLResponsibilityTypeID read fResponsibilityType write fResponsibilityType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Comments: RawUTF8 read fComments write fComments; end; // 33 TSQLEmplPositionType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLEmplPositionTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLEmplPositionTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 34 TSQLEmplPositionTypeClass = class(TSQLRecord) private fEmplPositionType: TSQLEmplPositionTypeID; fEmplPositionClassType: TSQLEmplPositionClassTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fStandardHoursPerWeek: Double; published property EmplPositionType: TSQLEmplPositionTypeID read fEmplPositionType write fEmplPositionType; property EmplPositionClassType: TSQLEmplPositionClassTypeID read fEmplPositionClassType write fEmplPositionClassType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property StandardHoursPerWeek: Double read fStandardHoursPerWeek write fStandardHoursPerWeek; end; // 35 TSQLValidResponsibility = class(TSQLRecord) private fEmplPositionType: TSQLEmplPositionTypeID; fResponsibilityType: TSQLResponsibilityTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fComments: RawUTF8; published property EmplPositionType: TSQLEmplPositionTypeID read fEmplPositionType write fEmplPositionType; property ResponsibilityType: TSQLResponsibilityTypeID read fResponsibilityType write fResponsibilityType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property Comments: RawUTF8 read fComments write fComments; end; // 36 TSQLEmplPositionTypeRate = class(TSQLRecord) private fEmplPositionType: TSQLEmplPositionTypeID; fRateType: TSQLRateTypeID; fSalaryStep: TSQLSalaryStepID; //payGradeId, salaryStepSeqId, fromDate fThruDate: TDateTime; published property EmplPositionType: TSQLEmplPositionTypeID read fEmplPositionType write fEmplPositionType; property RateType: TSQLRateTypeID read fRateType write fRateType; property SalaryStep: TSQLSalaryStepID read fSalaryStep write fSalaryStep; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 37 TSQLJobRequisition = class(TSQLRecord) private fDurationMonths: Integer; fAge: Integer; fGender: Boolean; fExperienceMonths: Integer; fExperienceYears: Integer; fQualification: Integer; fJobLocation: Integer; fSkillType: TSQLSkillTypeID; fNoOfResources: Integer; fJobPostingTypeEnum: TSQLEnumerationID; fJobRequisitionDate: TDateTime; fExamTypeEnum: TSQLEnumerationID; fRequiredOnDate: TDateTime; published property DurationMonths: Integer read fDurationMonths write fDurationMonths; property Age: Integer read fAge write fAge; property Gender: Boolean read fGender write fGender; property ExperienceMonths: Integer read fExperienceMonths write fExperienceMonths; property ExperienceYears: Integer read fExperienceYears write fExperienceYears; property Qualification: Integer read fQualification write fQualification; property JobLocation: Integer read fJobLocation write fJobLocation; property SkillType: TSQLSkillTypeID read fSkillType write fSkillType; property NoOfResources: Integer read fNoOfResources write fNoOfResources; property JobPostingTypeEnum: TSQLEnumerationID read fJobPostingTypeEnum write fJobPostingTypeEnum; property JobRequisitionDate: TDateTime read fJobRequisitionDate write fJobRequisitionDate; property ExamTypeEnum: TSQLEnumerationID read fExamTypeEnum write fExamTypeEnum; property RequiredOnDate: TDateTime read fRequiredOnDate write fRequiredOnDate; end; // 38 TSQLJobInterview = class(TSQLRecord) private fJobIntervieweeParty: TSQLPartyID; fJobRequisition: TSQLJobRequisitionID; fJobInterviewerParty: TSQLPartyID; fJobInterviewType: TSQLJobInterviewTypeID; fGradeSecuredEnum: TSQLEnumerationID; fJobInterviewResult: RawUTF8; fJobInterviewDate: TDateTime; published property JobIntervieweeParty: TSQLPartyID read fJobIntervieweeParty write fJobIntervieweeParty; property JobRequisition: TSQLJobRequisitionID read fJobRequisition write fJobRequisition; property JobInterviewerParty: TSQLPartyID read fJobInterviewerParty write fJobInterviewerParty; property JobInterviewType: TSQLJobInterviewTypeID read fJobInterviewType write fJobInterviewType; property GradeSecuredEnum: TSQLEnumerationID read fGradeSecuredEnum write fGradeSecuredEnum; property JobInterviewResult: RawUTF8 read fJobInterviewResult write fJobInterviewResult; property JobInterviewDate: TDateTime read fJobInterviewDate write fJobInterviewDate; end; // 39 TSQLJobInterviewType = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 40 TSQLTrainingRequest = class(TSQLRecord) private fName: RawUTF8; FDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 41 TSQLEmplLeaveReasonType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLEmplLeaveReasonTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLEmplLeaveReasonTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; implementation uses Classes, SysUtils; // 1 class procedure TSQLPartyQualType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLPartyQualType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLPartyQualType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PartyQualType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update PartyQualType set Parent=(select c.id from PartyQualType c where c.Encode=PartyQualType.ParentEncode);'); finally Rec.Free; end; end; // 2 class procedure TSQLEmplPositionType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLEmplPositionType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLEmplPositionType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','EmplPositionType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update EmplPositionType set Parent=(select c.id from EmplPositionType c where c.Encode=EmplPositionType.ParentEncode);'); finally Rec.Free; end; end; // 3 class procedure TSQLResponsibilityType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLResponsibilityType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLResponsibilityType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ResponsibilityType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ResponsibilityType set Parent=(select c.id from ResponsibilityType c where c.Encode=ResponsibilityType.ParentEncode);'); finally Rec.Free; end; end; // 4 class procedure TSQLBenefitType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLBenefitType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLBenefitType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','BenefitType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update BenefitType set Parent=(select c.id from BenefitType c where c.Encode=BenefitType.ParentEncode);'); finally Rec.Free; end; end; // 5 class procedure TSQLTrainingClassType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLTrainingClassType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLTrainingClassType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','TrainingClassType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update TrainingClassType set Parent=(select c.id from TrainingClassType c where c.Encode=TrainingClassType.ParentEncode);'); finally Rec.Free; end; end; // 6 class procedure TSQLJobInterviewType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLJobInterviewType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLJobInterviewType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','JobInterviewType.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 5 class procedure TSQLEmplLeaveReasonType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLEmplLeaveReasonType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLEmplLeaveReasonType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','EmplLeaveReasonType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update EmplLeaveReasonType set Parent=(select c.id from EmplLeaveReasonType c where c.Encode=EmplLeaveReasonType.ParentEncode);'); finally Rec.Free; end; end; // 6 class procedure TSQLPerfReviewItemType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLPerfReviewItemType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLPerfReviewItemType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PerfReviewItemType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update PerfReviewItemType set Parent=(select c.id from PerfReviewItemType c where c.Encode=PerfReviewItemType.ParentEncode);'); finally Rec.Free; end; end; // 7 class procedure TSQLPerfRatingType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLPerfRatingType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLPerfRatingType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PerfRatingType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update PerfRatingType set Parent=(select c.id from PerfRatingType c where c.Encode=PerfRatingType.ParentEncode);'); finally Rec.Free; end; end; end.
{----------------------------------------------------------------------------} { Written by Nguyen Le Quang Duy } { Nguyen Quang Dieu High School, An Giang } {----------------------------------------------------------------------------} Program NKPALIN; Const maxN =2000; Var n :Integer; A,B :AnsiString; F :Array[0..1,0..maxN] of AnsiString; x,y :Byte; procedure Enter; var i :Integer; begin ReadLn(A); n:=Length(A); B:=''; for i:=n downto 1 do B:=B+A[i]; end; function Max(X,Y :AnsiString) :AnsiString; begin if (Length(Y)>Length(X)) then Max:=Y else Max:=X; end; procedure Optimize; var i,j :Integer; begin x:=0; y:=1; FillChar(F[x],SizeOf(F[x]),0); for i:=1 to n do begin for j:=1 to n do if (A[i]=B[j]) then F[y,j]:=F[x,j-1]+B[j] else F[y,j]:=Max(F[x,j],F[y,j-1]); x:=1-x; y:=1-y; end; end; Begin Assign(Input,''); Reset(Input); Assign(Output,''); Rewrite(Output); Enter; Optimize; Write(F[x,n]); Close(Input); Close(Output); End.
unit uIntfaceFull; interface type TIntfaceFull = class(TObject) private //class var FMaxId: Int64; private FName: string; FMethod: string; FHttpUrl: string; FUrl: string; procedure SetHttpUrl(const S: string); public class constructor Create; constructor Create; destructor Destroy; override; procedure clear; public property Name: string read FName write FName; property Method: string read FMethod write FMethod; property HttpUrl: string write SetHttpUrl; property Url: string read FUrl; end; implementation uses SysUtils, classes; { TCarBrand } class constructor TIntfaceFull.Create; begin //FMaxId := 67541628411220000; end; procedure TIntfaceFull.clear; begin FName:=''; FMethod:=''; FHttpUrl:=''; FUrl:=''; end; constructor TIntfaceFull.Create; begin //inherited Create; end; destructor TIntfaceFull.Destroy; begin end; procedure TIntfaceFull.SetHttpUrl(const S: string); function getRightStr(const S: string; const sub: string): string; var n: integer; begin n := S.IndexOf(sub); if (n>=0) then begin Result := S.Substring(n+sub.Length).Trim; end else begin Result := ''; end; end; function getUrlAPI(const S: string): string; begin if S.StartsWith('http://') then begin Result := getRightStr(S, 'http://{{ip}}:{{port}}/'); end else begin Result := S; end; end; begin self.FHttpUrl := S; self.FUrl := getUrlAPI(S); end; end.
unit AProfissoes; { Autor: Rafael Budag Data Criação: 25/03/1999; Função: Cadastrar uma nova transportadora Data Alteração: 25/03/1999; Alterado por: Motivo alteração: } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, Grids, DBGrids, Tabela, Db, DBTables, StdCtrls, Mask, DBCtrls, BotaoCadastro, Buttons, Localizacao, DBKeyViolation, DBClient; type TFProfissoes = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; BotaoCancelar1: TBotaoCancelar; BotaoGravar1: TBotaoGravar; BotaoExcluir1: TBotaoExcluir; BotaoAlterar1: TBotaoAlterar; BotaoCadastrar1: TBotaoCadastrar; MoveBasico1: TMoveBasico; Label1: TLabel; DataCadProfissao: TDataSource; Label2: TLabel; DBEditColor1: TDBEditColor; DBGridColor1: TGridIndice; Consulta: TLocalizaEdit; Label3: TLabel; CadProfissoes: TSQL; BFechar: TBitBtn; Bevel2: TBevel; CadProfissoesI_COD_PRF: TFMTBCDField; CadProfissoesC_NOM_PRF: TWideStringField; ValidaGravacao1: TValidaGravacao; CadProfissoesD_ULT_ALT: TSQLTimeStampField; ECodigo: TDBKeyViolation; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CadProfissoesAfterInsert(DataSet: TDataSet); procedure CadProfissoesAfterPost(DataSet: TDataSet); procedure CadProfissoesBeforePost(DataSet: TDataSet); procedure BFecharClick(Sender: TObject); procedure CadProfissoesAfterEdit(DataSet: TDataSet); procedure CadProfissoesAfterCancel(DataSet: TDataSet); procedure DBGridColor1Ordem(Ordem: String); procedure DBKeyViolation1Change(Sender: TObject); private procedure ConfiguraConsulta( acao : Boolean); public { Public declarations } end; var FProfissoes: TFProfissoes; implementation uses APrincipal, Constantes, UnSistema; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFProfissoes.FormCreate(Sender: TObject); begin CadProfissoes.open; end; { ******************* Quando o formulario e fechado ************************** } procedure TFProfissoes.FormClose(Sender: TObject; var Action: TCloseAction); begin CadProfissoes.close; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações da Tabela )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {*****************Gera o proximo codigo disponivel como default****************} procedure TFProfissoes.CadProfissoesAfterInsert(DataSet: TDataSet); begin ECodigo.ProximoCodigo; ECodigo.ReadOnly := False; ConfiguraConsulta(false); end; {**********Verifica se o codigo já foi utilizado por outro usuario na rede*****} procedure TFProfissoes.CadProfissoesBeforePost(DataSet: TDataSet); begin CadProfissoesD_ULT_ALT.AsDateTime := Sistema.RDataServidor; if CadProfissoes.State = dsinsert then ECodigo.VerificaCodigoUtilizado; end; {Atualiza o cadastro caso o codigo tenha sido utilizado por outro usuario na rede} procedure TFProfissoes.CadProfissoesAfterPost(DataSet: TDataSet); begin Consulta.AtualizaTabela; ConfiguraConsulta(true); Sistema.MarcaTabelaParaImportar('CADPROFISSOES'); end; {*********************Coloca o campo chave em read-only************************} procedure TFProfissoes.CadProfissoesAfterEdit(DataSet: TDataSet); begin ECodigo.ReadOnly := True; ConfiguraConsulta(false); end; { ********************* quando cancela a operacao *************************** } procedure TFProfissoes.CadProfissoesAfterCancel(DataSet: TDataSet); begin ConfiguraConsulta(true); end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {****** configura a consulta, caso edit ou insert enabled = false *********** } procedure TFProfissoes.ConfiguraConsulta( acao : Boolean); begin Consulta.Enabled := acao; DBGridColor1.Enabled := acao; Label3.Enabled := acao; end; {************************Fecha o formulario corrente***************************} procedure TFProfissoes.BFecharClick(Sender: TObject); begin Close; end; {********** adiciona order by na tabela ************************************ } procedure TFProfissoes.DBGridColor1Ordem(Ordem: String); begin Consulta.AOrdem := ordem; end; procedure TFProfissoes.DBKeyViolation1Change(Sender: TObject); begin if CadProfissoes.State in [ dsInsert, dsEdit ] then ValidaGravacao1.execute; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFProfissoes]); end.
unit TelpinAPI; interface uses Vcl.ExtCtrls, System.Classes, IdHTTP, IdSSLOpenSSL, System.JSON, System.SysUtils, System.DateUtils; type TTelphinToken = class; TTelphinApiBaseElement = class protected fBaseUrl: string; fHttp: TIdHTTP; fSSL: TIdSSLIOHandlerSocketOpenSSL; public property BaseUrl: string read fBaseUrl write fBaseUrl; constructor Create; overload; destructor Destroy; overload; end; TTelphinAPIElement = class(TTelphinApiBaseElement) private FTokenObject: TTelphinToken; fUserId: string; fResponse: string; function GetTokenObject: TTelphinToken; public property TokenObject: TTelphinToken read GetTokenObject write FTokenObject; property HttpResponse: string read fResponse; constructor Create(ATokenObject: TTelphinToken=nil); overload; end; TTelphinToken = class(TTelphinApiBaseElement) private fClientKey: string; fSecretKey: string; fToken: string; fTimer: TTimer; fAutoReGet: Boolean; fTimeExpires: TDateTime; //время истечения procedure SetAutoReGet(AValue: boolean); procedure GetTokenProc(Sender: TObject); function CheckToken: Boolean; function GetActiveToken: string; public property ClientKey: string read fClientKey write fClientKey; property SecretKey: string read fSecretKey write fSecretKey; property Token: string read GetActiveToken; property AutoReGet: Boolean read fAutoReGet write SetAutoReGet; property TimeExpires: TDateTime read fTimeExpires; property TokenIsActive: Boolean read CheckToken; constructor Create; overload; destructor Destroy; overload; function GetToken: Boolean; end; TPhoneCalls = class (TTelphinAPIElement) private fOnAfterCall: TNotifyEvent; fOnCallFinish: TNotifyEvent; fCallId: string; fExtension: string; function GetStatusCall: Integer; public property OnAfterCall: TNotifyEvent read fOnAfterCall write fOnAfterCall; property OnCallFinish: TNotifyEvent read fOnCallFinish write fOnCallFinish; property CallId: string read fCallId; property StatusCall: Integer read GetStatusCall; property Extension: string read fExtension; function SimpleCall(ANumberSrc, ANumberDest, AExtNumber: string): boolean; function TransferCall(Callid, APhone: string): Boolean; function DeleteCall(Callid: string): Boolean; end; TCallListener = class (TTelphinAPIElement) private fOnCallFinish: TNotifyEvent; // событие после окончания звонка fCallId: string; fExtension: string; fStatusCall: Integer; fTimer: TTimer; fTimerInterval: Integer; function GetStatusCall: Integer; procedure TimerProc(Sender: TObject); public property OnCallFinish: TNotifyEvent read fOnCallFinish write fOnCallFinish; property CallId: string read fCallId write fCallId; property TimerInterval: Integer read fTimerInterval write fTimerInterval; property Extension: string read fExtension write fExtension; constructor Create(ATokenObject: TTelphinToken; ACallId, AExtension: string; AOnCallFinish: TNotifyEvent); overload; destructor Destroy; overload; end; implementation { TTelphinToken } function TTelphinToken.CheckToken: Boolean; begin Result := Assigned(Self) and ((fToken = '') or (Now < fTimeExpires)); end; constructor TTelphinToken.Create; begin inherited Create; fAutoReGet := True; fTimer := TTimer.Create(nil); fTimer.Interval := 0; fTimer.OnTimer := GetTokenProc; end; destructor TTelphinToken.Destroy; begin if Assigned(fTimer) then fTimer.Free; end; function TTelphinToken.GetToken: Boolean; begin GetTokenProc(nil); end; function TTelphinToken.GetActiveToken: string; begin if not CheckToken then GetToken; Result := fToken; end; procedure TTelphinToken.GetTokenProc(Sender: TObject); var sResponse: string; stream: TStringStream; json: TJSONObject; keep: Integer; begin stream := TStringStream.Create(''); stream.WriteString('grant_type=client_credentials&'); stream.WriteString('redirect_uri=urn:ietf:wg:oauth:2.0:oob&'); stream.WriteString('client_id=' + ClientKey + '&'); stream.WriteString('client_secret=' + SecretKey + '&'); stream.WriteString('state=0'); try // fHttp.Request.URL := fBaseURL + '/oauth/token.php'; fHttp.Request.Method := 'POST'; fHttp.Request.ContentType := 'application/x-www-form-urlencoded'; fhttp.Request.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'; fhttp.Request.AcceptCharSet := 'windows-1251,utf-8;q=0.7,*;q=0.3'; fhttp.Request.AcceptLanguage := 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4'; fhttp.Request.Connection := 'keep-alive'; fhttp.Request.Host := fBaseUrl; fhttp.Request.Referer := fBaseUrl; // fhttp.Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7'; fhttp.HandleRedirects := false; fhttp.HTTPOptions := [hoKeepOrigProtocol]; try sResponse := fHttp.Post(fBaseUrl + '/oauth/token.php', stream); json := TJSONObject.Create; json.Parse(BytesOf(sResponse), 0); fToken := json.Values['access_token'].ToString; fToken := AnsiDequotedStr(fToken, '"'); keep := StrToInt(json.Values['expires_in'].ToString); if keep > 0 then keep := keep - 15; fTimeExpires := IncSecond(Now, keep); except end; finally stream.Free; json.Free; end; end; procedure TTelphinToken.SetAutoReGet(AValue: boolean); begin if not AValue then fTimer.Interval := 0; fAutoReGet := AValue; end; { TTelphinAPIElement } constructor TTelphinAPIElement.Create(ATokenObject: TTelphinToken=nil) ; begin inherited Create; if ATokenObject <> nil then FTokenObject := ATokenObject; end; function TTelphinAPIElement.GetTokenObject: TTelphinToken; begin if not Assigned(FTokenObject) then FTokenObject := TTelphinToken.Create; Result := FTokenObject; end; { TPhoneCalls } function TPhoneCalls.DeleteCall(Callid: string): Boolean; var sStream: TStringStream; sResponse: string; url: string; begin Result := False; sStream := TStringStream.Create(''); try fHttp.Request.Method := 'DELETE'; fHttp.Request.ContentType := 'application/json'; fhttp.Request.CustomHeaders.Clear; fhttp.Request.CustomHeaders.Add('Authorization: Bearer '+ TokenObject.Token); url := fBaseUrl + '/uapi/phoneCalls/@me/@self/' + CallId; try fHttp.Delete(url, sStream); except end; Result := (fHttp.ResponseCode = 200); finally sStream.Free; end; end; function TPhoneCalls.GetStatusCall: Integer; var sStream: TStringStream; url: string; begin sStream := TStringStream.Create; fHttp.Request.Method := 'GET'; //fHttp.Request.ContentType := 'application/json'; fhttp.Request.CustomHeaders.Clear; fhttp.Request.CustomHeaders.Add('Authorization: Bearer '+ TokenObject.Token); url := fBaseUrl + '/uapi/phoneCalls/@owner/@self/' + CallId; //&accessRequestToken=' + FTokenObject.Token; try fHttp.Get(url, sStream); except end; sStream.Free; end; function TPhoneCalls.SimpleCall(ANumberSrc, ANumberDest, AExtNumber: string): boolean; var sStream: TStringStream; sResponse: string; url: string; json: TJSONObject; begin Result := False; sStream := TStringStream.Create(''); try sStream.WriteString('{' + #13#10); sStream.WriteString('"extension": "' + AExtNumber + '",'+ #13#10); sStream.WriteString('"phoneCallView": ['+ #13#10); sStream.WriteString('{'+ #13#10); sStream.WriteString(' "source": ["' + ANumberSrc + '" ],'+ #13#10); sStream.WriteString(' "destination": "' + ANumberDest + '",'+ #13#10); sStream.WriteString(' "callerId": "Fumigator <' + ANumberSrc + '>"'+ #13#10); sStream.WriteString(' }'+ #13#10); sStream.WriteString(']'+ #13#10); sStream.WriteString('}'); fHttp.Request.Method := 'POST'; fHttp.Request.ContentType := 'application/json'; fhttp.Request.CustomHeaders.Clear; fhttp.Request.CustomHeaders.Add('Authorization: Bearer '+ TokenObject.Token); url := fBaseUrl + '/uapi/phoneCalls/@owner/simple?allowPublicTransfer=true' ; //&accessRequestToken=' + FTokenObject.Token; try fResponse := fHttp.Post(url, sStream); except end; if (fHttp.ResponseCode < 400) then begin if Copy(fResponse, 1, 1) = '[' then begin fResponse := Copy(fResponse, 2, Length(fResponse) - 2); end; json := TJSONObject.Create; json.Parse(BytesOf(fResponse), 0); fCallId := AnsiDequotedStr(json.Values['id'].ToString, '"'); fExtension := AnsiDequotedStr(json.Values['extension'].ToString, '"'); // TCallListener.Create(fTokenObject, fCallId, fExtension, fOnCallFinish); if Assigned(fOnAfterCall) then fOnAfterCall(Self); end; finally sStream.Free; end; end; function TPhoneCalls.TransferCall(Callid, APhone: string): Boolean; begin end; { TTelphinApiBaseElement } constructor TTelphinApiBaseElement.Create; begin fHttp := TIdHTTP.Create(nil); fSSL:=TIdSSLIOHandlerSocketOpenSSL.Create; fHttp.IOHandler:=fSSL; fBaseUrl := 'https://office.telphin.ru'; end; destructor TTelphinApiBaseElement.Destroy; begin if Assigned(fHttp) then fHttp.Free; if Assigned(fSSL) then fSSL.Free; end; { TCallListener } constructor TCallListener.Create(ATokenObject: TTelphinToken; ACallId, AExtension: string; AOnCallFinish: TNotifyEvent); begin inherited Create(ATokenObject); fCallId := ACallId; fExtension := AExtension; fOnCallFinish := AOnCallFinish; fTimer := TTimer.Create(nil); fTimer.OnTimer := TimerProc; fTimerInterval := 1000; fTimer.Interval := fTimerInterval; end; destructor TCallListener.Destroy; begin FreeAndNil(fTimer); inherited; end; function TCallListener.GetStatusCall: Integer; var sStream: TStringStream; url: string; json: TJSONObject; cnt: Integer; begin sStream := TStringStream.Create; try fTimer.Interval := 0; fHttp.Request.Method := 'GET'; //fHttp.Request.ContentType := 'application/json'; fhttp.Request.CustomHeaders.Clear; fhttp.Request.CustomHeaders.Add('Authorization: Bearer '+ TokenObject.Token); url := fBaseUrl + '/uapi/phoneCalls/@owner/' + fExtension +'/' + fCallId; fHttp.Get(url, sStream); json := TJSONObject.Create; json.Parse(BytesOf(sStream.DataString), 0); cnt := StrToInt(AnsiDequotedStr(json.Values['totalResults'].ToString, '"')); finally sStream.Free; json.Free; if cnt = 0 then begin if Assigned(fOnCallFinish) then fOnCallFinish(self); Destroy; end else fTimer.Interval := fTimerInterval; end; end; procedure TCallListener.TimerProc(Sender: TObject); begin GetStatusCall; end; end.
unit fNoteDR; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, VA508AccessibilityManager; type TfrmNoteDelReason = class(TfrmAutoSz) lblInstruction: TStaticText; cmdOK: TButton; cmdCancel: TButton; radPrivacy: TRadioButton; radAdmin: TRadioButton; procedure FormCreate(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); private OKPressed: Boolean; end; function SelectDeleteReason(ANote: Integer): string; implementation {$R *.DFM} uses ORFn, rTIU, uConst; const TX_REQRSN = 'A reason must be selected, otherwise press cancel.'; TC_REQRSN = 'Reason Required'; function SelectDeleteReason(ANote: Integer): string; var frmNoteDelReason: TfrmNoteDelReason; begin if not JustifyDocumentDelete(ANote) then begin Result := DR_NOTREQ; Exit; end; Result := DR_CANCEL; frmNoteDelReason := TfrmNoteDelReason.Create(Application); try ResizeFormToFont(TForm(frmNoteDelReason)); frmNoteDelReason.ShowModal; with frmNoteDelReason do if OKPressed then begin if radPrivacy.Checked then Result := DR_PRIVACY; if radAdmin.Checked then Result := DR_ADMIN; end; finally frmNoteDelReason.Release; end; end; procedure TfrmNoteDelReason.FormCreate(Sender: TObject); begin inherited; OKPressed := False; end; procedure TfrmNoteDelReason.cmdOKClick(Sender: TObject); begin inherited; if not (radPrivacy.Checked or radAdmin.Checked) then begin InfoBox(TX_REQRSN, TC_REQRSN, MB_OK); Exit; end; OKPressed := True; Close; end; procedure TfrmNoteDelReason.cmdCancelClick(Sender: TObject); begin inherited; Close; end; end.
unit CommonFunct; interface uses Windows; const KEY_APP = 'Software\ZANS'; type TMemoryStatusInformation = record MemoryLoad: String; TotalPhys: String; AvailPhys: String; TotalPage: String; AvailPage: String; TotalVirtual: String; AvailVirtual: String; end; function MemoryStatus: TMemoryStatusInformation; function IniLoad(Section, Key: String): String; function IniSave(Section, Key, Value: String): Boolean; procedure RegisterProgIDShell; implementation uses SysUtils, Global, Registry, CommonConst; procedure RegisterProgIDShell; const Buffer: array [0..3] of Byte = (0,0,0,0); var reg: TRegistry; s: String; begin reg:= TRegistry.Create; try with reg do begin s:= IniLoad('Path','App'); if s = '' then s:= GetCurrentDir; RootKey:= HKEY_CLASSES_ROOT; if not KeyExists(FILE_EXT) then CreateKey(FILE_EXT); OpenKey(FILE_EXT, False); WriteString('',REG_APP_NAME); WriteString('Content Type','application/x-data'); if not KeyExists('ShellNew') then CreateKey('ShellNew'); OpenKey('ShellNew', False); WriteString('NullFile',''); WriteBinaryData('Data', Buffer, 4); CloseKey; CloseKey; if not KeyExists(REG_APP_NAME) then CreateKey(REG_APP_NAME); OpenKey(REG_APP_NAME, False); WriteString('',NEW_FILE_NAME_NO_EXT); WriteBinaryData('EditFlags', Buffer, 4); OpenKey('Shell', True); OpenKey('open', True); OpenKey('command', True); WriteString('','"' + s + '\DsgLib.exe" "%1"'); CloseKey; CloseKey; CloseKey; OpenKey('DefaultIcon', True); WriteString('',s + 'DsgLib.exe,0'); CloseKey; CloseKey; CloseKey; end; finally reg.Free; end; end; function IniLoad(Section, Key: String): String; var r: TRegistry; begin r:= TRegistry.Create; try r.RootKey:= HKEY_LOCAL_MACHINE; r.OpenKey(KEY_APP+'\'+Section, True); Result:= r.ReadString(Key); r.CloseKey; finally r.Free; end; end; function IniSave(Section, Key, Value: String): Boolean; var r: TRegistry; begin r:= TRegistry.Create; try r.RootKey:= HKEY_LOCAL_MACHINE; r.OpenKey(KEY_APP+'\'+Section, True); r.WriteString(Key, Value); r.CloseKey; Result:= True; finally r.Free; end; end; function MemoryStatus: TMemoryStatusInformation; var ms: _MEMORYSTATUS; l: LongWord; begin l:= 1024*1024; ms.dwLength:= SizeOf(ms); GlobalMemoryStatus(ms); with Result do begin MemoryLoad:= Format('Загрузка памяти %d %%',[ms.dwMemoryLoad]); TotalPhys:= Format('Всего физ. памяти %u Кб (%u Мб)',[ms.dwTotalPhys div 1024, ms.dwTotalPhys div l]); AvailPhys:= Format('Доступно физ. памяти %u Кб (%u Мб)',[ms.dwAvailPhys div 1024, ms.dwAvailPhys div l]); TotalPage:= Format('Размер файла подкачки %u Кб (%u Мб)',[ms.dwTotalPageFile div 1024,ms.dwTotalPageFile div l]); AvailPage:= Format('Доступно файла подкачки %u Кб (%u Мб)',[ms.dwAvailPageFile div 1024,ms.dwAvailPageFile div l]); TotalVirtual:= Format('Всего вирт. памяти %u Кб (%u Мб)',[ms.dwTotalVirtual div 1024,ms.dwTotalVirtual div l]); AvailVirtual:= Format('Доступно вирт. памяти %u Кб (%u Мб)',[ms.dwAvailVirtual div 1024,ms.dwAvailVirtual div l]); end; end; end.
unit IdSMTP; interface uses Classes, IdGlobal, IdMessage, IdEMailAddress, IdHeaderList, IdMessageClient; type TAuthenticationType = (atNone, atLogin); const ID_TIDSMTP_AUTH_TYPE = atNone; type TIdSMTP = class(TIdMessageClient) protected FDidAuthenticate: Boolean; FAuthenticationType: TAuthenticationType; FAuthSchemesSupported: TStringList; FMailAgent: string; FPassword: string; FUserId: string; procedure GetAuthTypes; function IsAuthProtocolAvailable(Auth: TAuthenticationType) : Boolean; virtual; public procedure Assign(Source: TPersistent); override; function Authenticate: Boolean; virtual; procedure Connect; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Disconnect; override; class procedure QuickSend(const AHost, ASubject, ATo, AFrom, AText: string); procedure Send(AMsg: TIdMessage); virtual; property AuthSchemesSupported: TStringList read FAuthSchemesSupported; published property AuthenticationType: TAuthenticationType read FAuthenticationType write FAuthenticationType default ID_TIDSMTP_AUTH_TYPE; property MailAgent: string read FMailAgent write FMailAgent; property Password: string read FPassword write FPassword; property UserId: string read FUserId write FUserId; property Port default IdPORT_SMTP; end; implementation uses IdCoder3To4, IdResourceStrings, SysUtils; procedure TIdSMTP.Assign(Source: TPersistent); begin if Source is TIdSMTP then begin AuthenticationType := TIdSMTP(Source).AuthenticationType; Host := TIdSMTP(Source).Host; MailAgent := TIdSMTP(Source).MailAgent; Password := TIdSMTP(Source).Password; Port := TIdSMTP(Source).Port; UserId := TIdSMTP(Source).UserId; end else inherited; end; function TIdSMTP.Authenticate: Boolean; function AuthLogin: Boolean; begin SendCmd('auth LOGIN', 334); {Do not localize} SendCmd(Base64Encode(UserId), 334); SendCmd(Base64Encode(Password), 235); Result := True; end; begin Result := False; case FAUthenticationType of atLogin: Result := AuthLogin; end; FDidAuthenticate := True; end; procedure TIdSMTP.Connect; begin inherited; try GetResponse([220]); FAuthSchemesSupported.Clear; if SendCmd('ehlo ' + LocalName) = 250 then {Do not localize} begin GetAuthTypes; end else begin SendCmd('Helo ' + LocalName, 250); {Do not localize} end; except Disconnect; raise; end; end; constructor TIdSMTP.Create(AOwner: TComponent); begin inherited; FAuthSchemesSupported := TStringList.Create; FAuthSchemesSupported.Duplicates := dupIgnore; Port := IdPORT_SMTP; end; destructor TIdSMTP.Destroy; begin FreeAndNil(FAuthSchemesSupported); inherited; end; procedure TIdSMTP.Disconnect; begin try if Connected then begin WriteLn('Quit'); {Do not localize} end; finally inherited; FDidAuthenticate := False; end; end; procedure TIdSMTP.GetAuthTypes; var Iterator: Integer; Buffer: string; ListEntry: string; begin Iterator := 1; while Iterator < FCmdResultDetails.Count do begin Buffer := UpperCase(FCmdResultDetails[Iterator]); if (IndyPos('AUTH', Buffer) = 5) and ((Copy(Buffer, 9, 1) = ' ') or {Do not localize} (Copy(Buffer, 9, 1) = '=')) then {Do not localize} begin Buffer := Copy(Buffer, 10, Length(Buffer)); while Buffer <> '' do begin StringReplace(Buffer, '=', ' ', [rfReplaceAll]); {Do not localize} ListEntry := Fetch(Buffer, ' '); {Do not localize} if (FAuthSchemesSupported.IndexOf(ListEntry) = -1) then FAuthSchemesSupported.Add(ListEntry); end; end; Inc(Iterator); end; end; function TIdSMTP.IsAuthProtocolAvailable( Auth: TAuthenticationType): Boolean; begin case Auth of atLogin: Result := (FAuthSchemesSupported.IndexOf('LOGIN') <> -1); {Do not localize} else Result := False; end; end; class procedure TIdSMTP.QuickSend(const AHost, ASubject, ATo, AFrom, AText: string); var SMTP: TIdSMTP; Msg: TIdMessage; begin SMTP := TIdSMTP.Create(nil); try Msg := TIdMessage.Create(SMTP); with Msg do begin Subject := ASubject; Recipients.EMailAddresses := ATo; From.Text := AFrom; Body.Text := AText; end; with SMTP do begin Host := AHost; Connect; try ; Send(Msg); finally Disconnect; end; end; finally SMTP.Free; end; end; procedure TIdSMTP.Send(AMsg: TIdMessage); procedure WriteRecipient(const AEmailAddress: TIdEmailAddressItem); begin SendCmd('RCPT to:<' + AEMailAddress.Address + '>', 250); {Do not localize} end; procedure WriteRecipients(AList: TIdEmailAddressList); var i: integer; begin for i := 0 to AList.count - 1 do begin WriteRecipient(AList[i]); end; end; function NeedToAuthenticate: Boolean; begin if FAuthenticationType <> atNone then begin Result := IsAuthProtocolAvailable(FAuthenticationType) and (FDidAuthenticate = False); end else begin Result := False; end; end; begin SendCmd('Rset'); {Do not localize} if NeedToAuthenticate then begin Authenticate; end; SendCmd('Mail from:<' + AMsg.From.Address + '>', 250); {Do not localize} WriteRecipients(AMsg.Recipients); WriteRecipients(AMsg.CCList); WriteRecipients(AMsg.BccList); SendCmd('Data', 354); {Do not localize} AMsg.ExtraHeaders.Values['X-Mailer'] := MailAgent; {Do not localize} SendMsg(AMsg); SendCmd('.', 250); {Do not localize} end; end.
{ Version 12 Copyright (c) 2011-2012 by Bernd Gabriel 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. Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS are covered by separate copyright notices located in those modules. } {$I htmlcons.inc} unit HtmlSymbols; { This implementation bases on the W3C recommendation http://www.w3.org/TR/1999/REC-html401-19991224/ } interface uses Graphics, HtmlGlobals; type ThtScrollInfo = record BWidth: Integer; // single border width of paintpanel BWidth2: Integer; // double border width of paintpanel HWidth: Integer; // width of paintpanel VHeight: Integer; // height of paintpanel HBar: Boolean; // show horizontal scrollbar VBar: Boolean; // show vertical scrollbar end; THtmlLinkType = ( ltUnknown, ltAlternate, ltStylesheet, ltStart, ltNext, ltPrev, ltContents, ltIndex, ltGlossary, ltCopyright, ltChapter, ltSection, ltSubsection, ltAppendix, ltHelp, ltBookmark, ltShortcutIcon); const CHtmlLinkType: array [THtmlLinkType] of ThtString = ( '', 'alernate', 'stylesheet', 'start', 'next', 'prev', 'contents', 'index', 'glossary', 'copyright', 'chapter', 'section', 'subsection', 'appendix', 'help', 'bookmark', 'shortcut icon'); type THtmlElementSymbol = ( // virtual html elements NoEndSy, // indicates in TElementDescription, that this element has no end tag. UnknownSy, // indicates in TryStrToElement(), that the given string does not match any known element. TextSy, // indicates in THtmlParser.GetTag(), that this is simple element content. EofSy, EolSy, // real html elements ASy, AEndSy, AbbrSy, AbbrEndSy, // since12 AcronymSy, AcronymEndSy, // since12 AddressSy, AddressEndSy, AppletSy, AppletEndSy, // since12 AreaSy, BSy, BEndSy, BaseSy, BaseFontSy, BgSoundSy, // extension BdoSy, BdoEndSy, // since12 BigSy, BigEndSy, BlockQuoteSy, BlockQuoteEndSy, BodySy, BodyEndSy, BRSy, ButtonSy, CaptionSy, CaptionEndSy, CenterSy, CenterEndSy, CiteSy, CiteEndSy, CodeSy, CodeEndSy, ColSy, ColGroupSy, ColGroupEndSy, DDSy, DDEndSy, DelSy, DelEndSy, // since12 DfnSy, DfnEndSy, // since12 DirSy, DirEndSy, DivSy, DivEndSy, DLSy, DLEndSy, DTSy, DTEndSy, EmSy, EmEndSy, EmbedSy, EmbedEndSy, // extension, since12 FieldsetSy, FieldsetEndSy, FontSy, FontEndSy, FormSy, FormEndSy, FrameSy, FrameSetSy, FrameSetEndSy, H1Sy, H1EndSy, H2Sy, H2EndSy, H3Sy, H3EndSy, H4Sy, H4EndSy, H5Sy, H5EndSy, H6Sy, H6EndSy, HeadSy, HeadEndSy, HRSy, HtmlSy, HtmlEndSy, ISy, IEndSy, IFrameSy, IFrameEndSy, // since12 ImageSy, InputSy, InsSy, InsEndSy, // since12 IsIndexSy, // since12 KbdSy, KbdEndSy, LabelSy, LabelEndSy, LegendSy, LegendEndSy, LISy, LIEndSy, LinkSy, MapSy, MapEndSy, MenuSy, MenuEndSy, MetaSy, NoBrSy, NoBrEndSy, // extension NoEmbedSy, NoEmbedEndSy, // extension, since12 NoFramesSy, NoFramesEndSy, NoScriptSy, NoScriptEndSy, // since12 ObjectSy, ObjectEndSy, OLSy, OLEndSy, OptGroupSy, OptGroupEndSy, // since12 OptionSy, OptionEndSy, PSy, PEndSy, PageSy, // extension PanelSy, // extension ParamSy, PreSy, PreEndSy, QSy, QEndSy, // since12 ReadonlySy, // extension SSy, SEndSy, SampSy, SampEndSy, ScriptSy, ScriptEndSy, SelectSy, SelectEndSy, SelectedSy, // extension SmallSy, SmallEndSy, SpanSy, SpanEndSy, StrikeSy, StrikeEndSy, StrongSy, StrongEndSy, StyleSy, StyleEndSy, SubSy, SubEndSy, SupSy, SupEndSy, TableSy, TableEndSy, TBodySy, TBodyEndSy, TDSy, TDEndSy, TextAreaSy, TextAreaEndSy, TFootSy, TFootEndSy, THSy, THEndSy, THeadSy, THeadEndSy, TitleSy, TitleEndSy, TRSy, TREndSy, TTSy, TTEndSy, USy, UEndSy, ULSy, ULEndSy, VarSy, VarEndSy, WbrSy, // extension WrapSy); // extension THtmlElementSymbols = set of THtmlElementSymbol; THtmlAttributeSymbol = ( UnknownAttr, AbbrAttr, AccectCharsetAttr, AcceptAttr, AccessKeyAttr, ActionAttr, ActiveAttr, AlignAttr, AltAttr, ArchiveAttr, // extension AxisAttr, BGPropertiesAttr, // extension BorderColorDarkAttr, // extension BorderColorLightAttr, // extension BorderColorAttr, // extension BorderAttr, CharAttr, CharOffAttr, CharSetAttr, CheckBoxAttr, // extension CheckedAttr, CiteAttr, ClassIdAttr, CodeAttr, CodeBaseAttr, CodeTypeAttr, ColsAttr, ColSpanAttr, CompactAttr, CommandAttr, // extension ContentAttr, CoordsAttr, DataAttr, DateTimeAttr, DeclareAttr, DeferAttr, DirAttr, DisabledAttr, EncTypeAttr, ForAttr, FrameAttr, FrameBorderAttr, HeadersAttr, HRefAttr, HRegLangAttr, HttpEquivAttr, IsMapAttr, LabelAttr, LangAttr, LanguageAttr, LeftMarginAttr, liAloneAttr, // extension LongDescAttr, LoopAttr, // extension MaxLengthAttr, MediaAttr, MethodAttr, MultipleAttr, NameAttr, NoHRefAttr, NoResizeAttr, NoShadeAttr, NoWrapAttr, ObjectAttr, PlainAttr, // extension ProfileAttr, PromptAttr, RadioAttr, // extension RatioAttr, // extension ReadOnlyAttr, RelAttr, RevAttr, RowsAttr, RowSpanAttr, RulesAttr, SchemeAttr, ScopeAttr, ScrollingAttr, SelectedAttr, ShapeAttr, SpanAttr, SrcAttr, StandByAttr, StartAttr, SummaryAttr, TabIndexAttr, TargetAttr, TextAttr, TitleAttr, TopMarginAttr, // extension TranspAttr, // extension TypeAttr, UseMapAttr, ValueAttr, ValueTypeAttr, VersionAttr, WrapAttr, // extension ClassAttr, IDAttr, // events OnBlurAttr, OnChangeAttr, OnClickAttr, OnDblClickAttr, OnFocusAttr, OnKeyDownAttr, OnKeyPressAttr, OnKeyUpAttr, OnLoadAttr, OnMouseDownAttr, OnMouseMoveAttr, OnMouseOutAttr, OnMouseOverAttr, OnMouseUpAttr, OnResetAttr, OnSelectAttr, OnSubmitAttr, OnUnloadAttr, // convert to corresponding style property/ies BackgroundAttr, BGColorAttr, CellPaddingAttr, CellSpacingAttr, ClearAttr, ColorAttr, FaceAttr, HeightAttr, HSpaceAttr, MarginHeightAttr, MarginWidthAttr, SizeAttr, StyleAttr, VAlignAttr, VSpaceAttr, WidthAttr, // link pseudo colors ALinkAttr, LinkAttr, OLinkAttr, // extension VLinkAttr ); // THtmlEventAttributeSymbol = OnBlurAttr..OnUnloadAttr; // THtmlStyleAttributeSymbol = BackgroundAttr..WidthAttr; // THtmlLinkColorAttributeSymbol = ALinkAttr..VLinkAttr; TPropertySymbol = ( UnknownPropSy, FontFamily, FontSize, FontStyle, FontWeight, TextAlign, TextDecoration, LetterSpacing, Color, BackgroundColor, MarginTop, MarginRight, MarginBottom, MarginLeft, PaddingTop, PaddingRight, PaddingBottom, PaddingLeft, BorderTopWidth, BorderRightWidth, BorderBottomWidth, BorderLeftWidth, BorderTopColor, BorderRightColor, BorderBottomColor, BorderLeftColor, BorderTopStyle, BorderRightStyle, BorderBottomStyle, BorderLeftStyle, psWidth, psHeight, psTop, psBottom, psRight, psLeft, Visibility, LineHeight, BackgroundImage, BackgroundPosition, BackgroundRepeat, BackgroundAttachment, VerticalAlign, psPosition, ZIndex, ListStyleType, ListStyleImage, psFloat, psClear, TextIndent, PageBreakBefore, PageBreakAfter, PageBreakInside, TextTransform, WordWrap, FontVariant, BorderCollapse, OverFlow, psDisplay, psEmptyCells, psWhiteSpace, // short hands MarginX, PaddingX, BorderWidthX, BorderX, BorderTX, BorderRX, BorderBX, BorderLX, FontX, BackgroundX, ListStyleX, BorderColorX, BorderStyleX ); TShortHandSymbol = MarginX..BorderStyleX; TStylePropertySymbol = FontFamily..psWhiteSpace; TPropertyArray = array [TStylePropertySymbol] of Variant; type PColorDescription = ^TColorDescription; TColorDescription = record Name: ThtString; Color: TColor; end; function AllMyColors: ThtStringList; function TryStrToLinkType(const Str: ThtString; out LinkType: THtmlLinkType): Boolean; function AttributeSymbolToStr(Sy: THtmlAttributeSymbol): ThtString; function TryStrToAttributeSymbol(const Str: ThtString; out Sy: THtmlAttributeSymbol): Boolean; function PropertySymbolToStr(Sy: TPropertySymbol): ThtString; function TryStrToPropertySymbol(const Str: ThtString; out Sy: TPropertySymbol): Boolean; function TryNameToColor(const Name: ThtString; out Color: TColor): Boolean; function TryStrToEntity(const Str: ThtString; out Entity: Integer): Boolean; implementation //------------------------------------------------------------------------------ // charset codings //------------------------------------------------------------------------------ type PEntity = ^TEntity; TEntity = record Name: ThtString; Value: Integer; end; const // Taken from http://www.w3.org/TR/REC-html40/sgml/entities.html. // Note: the entities will be sorted into a ThtStringList to make binary search possible. EntityDefinitions: array[1..253] of TEntity = ( // ISO 8859-1 characters (Name: 'nbsp'; Value: 160), // no-break space = non-breaking space, U+00A0 ISOnum (Name: 'iexcl'; Value: 161), // inverted exclamation mark, U+00A1 ISOnum (Name: 'cent'; Value: 162), // cent sign, U+00A2 ISOnum (Name: 'pound'; Value: 163), // pound sign, U+00A3 ISOnum (Name: 'curren'; Value: 164), // currency sign, U+00A4 ISOnum (Name: 'yen'; Value: 165), // yen sign = yuan sign, U+00A5 ISOnum (Name: 'brvbar'; Value: 166), // broken bar = broken vertical bar, U+00A6 ISOnum (Name: 'sect'; Value: 167), // section sign, U+00A7 ISOnum (Name: 'uml'; Value: 168), // diaeresis = spacing diaeresis, U+00A8 ISOdia (Name: 'copy'; Value: 169), // copyright sign, U+00A9 ISOnum (Name: 'ordf'; Value: 170), // feminine ordinal indicator, U+00AA ISOnum (Name: 'laquo'; Value: 171), // left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum (Name: 'not'; Value: 172), // not sign, U+00AC ISOnum (Name: 'shy'; Value: 173), // soft hyphen = discretionary hyphen, U+00AD ISOnum (Name: 'reg'; Value: 174), // registered sign = registered trade mark sign, U+00AE ISOnum (Name: 'macr'; Value: 175), // macron = spacing macron = overline = APL overbar, U+00AF ISOdia (Name: 'deg'; Value: 176), // degree sign, U+00B0 ISOnum (Name: 'plusmn'; Value: 177), // plus-minus sign = plus-or-minus sign, U+00B1 ISOnum (Name: 'sup2'; Value: 178), // superscript two = superscript digit two = squared, U+00B2 ISOnum (Name: 'sup3'; Value: 179), // superscript three = superscript digit three = cubed, U+00B3 ISOnum (Name: 'acute'; Value: 180), // acute accent = spacing acute, U+00B4 ISOdia (Name: 'micro'; Value: 181), // micro sign, U+00B5 ISOnum (Name: 'para'; Value: 182), // pilcrow sign = paragraph sign, U+00B6 ISOnum (Name: 'middot'; Value: 183), // middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum (Name: 'cedil'; Value: 184), // cedilla = spacing cedilla, U+00B8 ISOdia (Name: 'sup1'; Value: 185), // superscript one = superscript digit one, U+00B9 ISOnum (Name: 'ordm'; Value: 186), // masculine ordinal indicator, U+00BA ISOnum (Name: 'raquo'; Value: 187), // right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum (Name: 'frac14'; Value: 188), // vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum (Name: 'frac12'; Value: 189), // vulgar fraction one half = fraction one half, U+00BD ISOnum (Name: 'frac34'; Value: 190), // vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum (Name: 'iquest'; Value: 191), // inverted question mark = turned question mark, U+00BF ISOnum (Name: 'Agrave'; Value: 192), // latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1 (Name: 'Aacute'; Value: 193), // latin capital letter A with acute, U+00C1 ISOlat1 (Name: 'Acirc'; Value: 194), // latin capital letter A with circumflex, U+00C2 ISOlat1 (Name: 'Atilde'; Value: 195), // latin capital letter A with tilde, U+00C3 ISOlat1 (Name: 'Auml'; Value: 196), // latin capital letter A with diaeresis, U+00C4 ISOlat1 (Name: 'Aring'; Value: 197), // latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1 (Name: 'AElig'; Value: 198), // latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1 (Name: 'Ccedil'; Value: 199), // latin capital letter C with cedilla, U+00C7 ISOlat1 (Name: 'Egrave'; Value: 200), // latin capital letter E with grave, U+00C8 ISOlat1 (Name: 'Eacute'; Value: 201), // latin capital letter E with acute, U+00C9 ISOlat1 (Name: 'Ecirc'; Value: 202), // latin capital letter E with circumflex, U+00CA ISOlat1 (Name: 'Euml'; Value: 203), // latin capital letter E with diaeresis, U+00CB ISOlat1 (Name: 'Igrave'; Value: 204), // latin capital letter I with grave, U+00CC ISOlat1 (Name: 'Iacute'; Value: 205), // latin capital letter I with acute, U+00CD ISOlat1 (Name: 'Icirc'; Value: 206), // latin capital letter I with circumflex, U+00CE ISOlat1 (Name: 'Iuml'; Value: 207), // latin capital letter I with diaeresis, U+00CF ISOlat1 (Name: 'ETH'; Value: 208), // latin capital letter ETH, U+00D0 ISOlat1 (Name: 'Ntilde'; Value: 209), // latin capital letter N with tilde, U+00D1 ISOlat1 (Name: 'Ograve'; Value: 210), // latin capital letter O with grave, U+00D2 ISOlat1 (Name: 'Oacute'; Value: 211), // latin capital letter O with acute, U+00D3 ISOlat1 (Name: 'Ocirc'; Value: 212), // latin capital letter O with circumflex, U+00D4 ISOlat1 (Name: 'Otilde'; Value: 213), // latin capital letter O with tilde, U+00D5 ISOlat1 (Name: 'Ouml'; Value: 214), // latin capital letter O with diaeresis, U+00D6 ISOlat1 (Name: 'times'; Value: 215), // multiplication sign, U+00D7 ISOnum (Name: 'Oslash'; Value: 216), // latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1 (Name: 'Ugrave'; Value: 217), // latin capital letter U with grave, U+00D9 ISOlat1 (Name: 'Uacute'; Value: 218), // latin capital letter U with acute, U+00DA ISOlat1 (Name: 'Ucirc'; Value: 219), // latin capital letter U with circumflex, U+00DB ISOlat1 (Name: 'Uuml'; Value: 220), // latin capital letter U with diaeresis, U+00DC ISOlat1 (Name: 'Yacute'; Value: 221), // latin capital letter Y with acute, U+00DD ISOlat1 (Name: 'THORN'; Value: 222), // latin capital letter THORN, U+00DE ISOlat1 (Name: 'szlig'; Value: 223), // latin small letter sharp s = ess-zed, U+00DF ISOlat1 (Name: 'agrave'; Value: 224), // latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1 (Name: 'aacute'; Value: 225), // latin small letter a with acute, U+00E1 ISOlat1 (Name: 'acirc'; Value: 226), // latin small letter a with circumflex, U+00E2 ISOlat1 (Name: 'atilde'; Value: 227), // latin small letter a with tilde, U+00E3 ISOlat1 (Name: 'auml'; Value: 228), // latin small letter a with diaeresis, U+00E4 ISOlat1 (Name: 'aring'; Value: 229), // latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1 (Name: 'aelig'; Value: 230), // latin small letter ae = latin small ligature ae, U+00E6 ISOlat1 (Name: 'ccedil'; Value: 231), // latin small letter c with cedilla, U+00E7 ISOlat1 (Name: 'egrave'; Value: 232), // latin small letter e with grave, U+00E8 ISOlat1 (Name: 'eacute'; Value: 233), // latin small letter e with acute, U+00E9 ISOlat1 (Name: 'ecirc'; Value: 234), // latin small letter e with circumflex, U+00EA ISOlat1 (Name: 'euml'; Value: 235), // latin small letter e with diaeresis, U+00EB ISOlat1 (Name: 'igrave'; Value: 236), // latin small letter i with grave, U+00EC ISOlat1 (Name: 'iacute'; Value: 237), // latin small letter i with acute, U+00ED ISOlat1 (Name: 'icirc'; Value: 238), // latin small letter i with circumflex, U+00EE ISOlat1 (Name: 'iuml'; Value: 239), // latin small letter i with diaeresis, U+00EF ISOlat1 (Name: 'eth'; Value: 240), // latin small letter eth, U+00F0 ISOlat1 (Name: 'ntilde'; Value: 241), // latin small letter n with tilde, U+00F1 ISOlat1 (Name: 'ograve'; Value: 242), // latin small letter o with grave, U+00F2 ISOlat1 (Name: 'oacute'; Value: 243), // latin small letter o with acute, U+00F3 ISOlat1 (Name: 'ocirc'; Value: 244), // latin small letter o with circumflex, U+00F4 ISOlat1 (Name: 'otilde'; Value: 245), // latin small letter o with tilde, U+00F5 ISOlat1 (Name: 'ouml'; Value: 246), // latin small letter o with diaeresis, U+00F6 ISOlat1 (Name: 'divide'; Value: 247), // division sign, U+00F7 ISOnum (Name: 'oslash'; Value: 248), // latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1 (Name: 'ugrave'; Value: 249), // latin small letter u with grave, U+00F9 ISOlat1 (Name: 'uacute'; Value: 250), // latin small letter u with acute, U+00FA ISOlat1 (Name: 'ucirc'; Value: 251), // latin small letter u with circumflex, U+00FB ISOlat1 (Name: 'uuml'; Value: 252), // latin small letter u with diaeresis, U+00FC ISOlat1 (Name: 'yacute'; Value: 253), // latin small letter y with acute, U+00FD ISOlat1 (Name: 'thorn'; Value: 254), // latin small letter thorn, U+00FE ISOlat1 (Name: 'yuml'; Value: 255), // latin small letter y with diaeresis, U+00FF ISOlat1 // symbols, mathematical symbols, and Greek letters // Latin Extended-B (Name: 'fnof'; Value: 402), // latin small f with hook = function = florin, U+0192 ISOtech // Greek (Name: 'Alpha'; Value: 913), // greek capital letter alpha, U+0391 (Name: 'Beta'; Value: 914), // greek capital letter beta, U+0392 (Name: 'Gamma'; Value: 915), // greek capital letter gamma, U+0393 ISOgrk3 (Name: 'Delta'; Value: 916), // greek capital letter delta, U+0394 ISOgrk3 (Name: 'Epsilon'; Value: 917), // greek capital letter epsilon, U+0395 (Name: 'Zeta'; Value: 918), // greek capital letter zeta, U+0396 (Name: 'Eta'; Value: 919), // greek capital letter eta, U+0397 (Name: 'Theta'; Value: 920), // greek capital letter theta, U+0398 ISOgrk3 (Name: 'Iota'; Value: 921), // greek capital letter iota, U+0399 (Name: 'Kappa'; Value: 922), // greek capital letter kappa, U+039A (Name: 'Lambda'; Value: 923), // greek capital letter lambda, U+039B ISOgrk3 (Name: 'Mu'; Value: 924), // greek capital letter mu, U+039C (Name: 'Nu'; Value: 925), // greek capital letter nu, U+039D (Name: 'Xi'; Value: 926), // greek capital letter xi, U+039E ISOgrk3 (Name: 'Omicron'; Value: 927), // greek capital letter omicron, U+039F (Name: 'Pi'; Value: 928), // greek capital letter pi, U+03A0 ISOgrk3 (Name: 'Rho'; Value: 929), // greek capital letter rho, U+03A1 (Name: 'Sigma'; Value: 931), // greek capital letter sigma, U+03A3 ISOgrk3, // there is no Sigmaf, and no U+03A2 character either (Name: 'Tau'; Value: 932), // greek capital letter tau, U+03A4 (Name: 'Upsilon'; Value: 933), // greek capital letter upsilon, U+03A5 ISOgrk3 (Name: 'Phi'; Value: 934), // greek capital letter phi, U+03A6 ISOgrk3 (Name: 'Chi'; Value: 935), // greek capital letter chi, U+03A7 (Name: 'Psi'; Value: 936), // greek capital letter psi, U+03A8 ISOgrk3 (Name: 'Omega'; Value: 937), // greek capital letter omega, U+03A9 ISOgrk3 (Name: 'alpha'; Value: 945), // greek small letter alpha, U+03B1 ISOgrk3 (Name: 'beta'; Value: 946), // greek small letter beta, U+03B2 ISOgrk3 (Name: 'gamma'; Value: 947), // greek small letter gamma, U+03B3 ISOgrk3 (Name: 'delta'; Value: 948), // greek small letter delta, U+03B4 ISOgrk3 (Name: 'epsilon'; Value: 949), // greek small letter epsilon, U+03B5 ISOgrk3 (Name: 'zeta'; Value: 950), // greek small letter zeta, U+03B6 ISOgrk3 (Name: 'eta'; Value: 951), // greek small letter eta, U+03B7 ISOgrk3 (Name: 'theta'; Value: 952), // greek small letter theta, U+03B8 ISOgrk3 (Name: 'iota'; Value: 953), // greek small letter iota, U+03B9 ISOgrk3 (Name: 'kappa'; Value: 954), // greek small letter kappa, U+03BA ISOgrk3 (Name: 'lambda'; Value: 955), // greek small letter lambda, U+03BB ISOgrk3 (Name: 'mu'; Value: 956), // greek small letter mu, U+03BC ISOgrk3 (Name: 'nu'; Value: 957), // greek small letter nu, U+03BD ISOgrk3 (Name: 'xi'; Value: 958), // greek small letter xi, U+03BE ISOgrk3 (Name: 'omicron'; Value: 959), // greek small letter omicron, U+03BF NEW (Name: 'pi'; Value: 960), // greek small letter pi, U+03C0 ISOgrk3 (Name: 'rho'; Value: 961), // greek small letter rho, U+03C1 ISOgrk3 (Name: 'sigmaf'; Value: 962), // greek small letter final sigma, U+03C2 ISOgrk3 (Name: 'sigma'; Value: 963), // greek small letter sigma, U+03C3 ISOgrk3 (Name: 'tau'; Value: 964), // greek small letter tau, U+03C4 ISOgrk3 (Name: 'upsilon'; Value: 965), // greek small letter upsilon, U+03C5 ISOgrk3 (Name: 'phi'; Value: 966), // greek small letter phi, U+03C6 ISOgrk3 (Name: 'chi'; Value: 967), // greek small letter chi, U+03C7 ISOgrk3 (Name: 'psi'; Value: 968), // greek small letter psi, U+03C8 ISOgrk3 (Name: 'omega'; Value: 969), // greek small letter omega, U+03C9 ISOgrk3 (Name: 'thetasym'; Value: 977), // greek small letter theta symbol, U+03D1 NEW (Name: 'upsih'; Value: 978), // greek upsilon with hook symbol, U+03D2 NEW (Name: 'piv'; Value: 982), // greek pi symbol, U+03D6 ISOgrk3 // General Punctuation (Name: 'apos'; Value: 8217), // curly apostrophe, (Name: 'bull'; Value: 8226), // bullet = black small circle, U+2022 ISOpub, // bullet is NOT the same as bullet operator, U+2219 (Name: 'hellip'; Value: 8230), // horizontal ellipsis = three dot leader, U+2026 ISOpub (Name: 'prime'; Value: 8242), // prime = minutes = feet, U+2032 ISOtech (Name: 'Prime'; Value: 8243), // double prime = seconds = inches, U+2033 ISOtech (Name: 'oline'; Value: 8254), // overline = spacing overscore, U+203E NEW (Name: 'frasl'; Value: 8260), // fraction slash, U+2044 NEW // Letterlike Symbols (Name: 'weierp'; Value: 8472), // script capital P = power set = Weierstrass p, U+2118 ISOamso (Name: 'image'; Value: 8465), // blackletter capital I = imaginary part, U+2111 ISOamso (Name: 'real'; Value: 8476), // blackletter capital R = real part symbol, U+211C ISOamso (Name: 'trade'; Value: 8482), // trade mark sign, U+2122 ISOnum (Name: 'alefsym'; Value: 8501), // alef symbol = first transfinite cardinal, U+2135 NEW // alef symbol is NOT the same as hebrew letter alef, U+05D0 although the same // glyph could be used to depict both characters // Arrows (Name: 'larr'; Value: 8592), // leftwards arrow, U+2190 ISOnum (Name: 'uarr'; Value: 8593), // upwards arrow, U+2191 ISOnu (Name: 'rarr'; Value: 8594), // rightwards arrow, U+2192 ISOnum (Name: 'darr'; Value: 8595), // downwards arrow, U+2193 ISOnum (Name: 'harr'; Value: 8596), // left right arrow, U+2194 ISOamsa (Name: 'crarr'; Value: 8629), // downwards arrow with corner leftwards = carriage return, U+21B5 NEW (Name: 'lArr'; Value: 8656), // leftwards double arrow, U+21D0 ISOtech // ISO 10646 does not say that lArr is the same as the 'is implied by' arrow but // also does not have any other charater for that function. So ? lArr can be used // for 'is implied by' as ISOtech sugg (Name: 'uArr'; Value: 8657), // upwards double arrow, U+21D1 ISOamsa (Name: 'rArr'; Value: 8658), // rightwards double arrow, U+21D2 ISOtech // ISO 10646 does not say this is the 'implies' character but does not have another // character with this function so ? rArr can be used for 'implies' as ISOtech suggests (Name: 'dArr'; Value: 8659), // downwards double arrow, U+21D3 ISOamsa (Name: 'hArr'; Value: 8660), // left right double arrow, U+21D4 ISOamsa // Mathematical Operators (Name: 'forall'; Value: 8704), // for all, U+2200 ISOtech (Name: 'part'; Value: 8706), // partial differential, U+2202 ISOtech (Name: 'exist'; Value: 8707), // there exists, U+2203 ISOtech (Name: 'empty'; Value: 8709), // empty set = null set = diameter, U+2205 ISOamso (Name: 'nabla'; Value: 8711), // nabla = backward difference, U+2207 ISOtech (Name: 'isin'; Value: 8712), // element of, U+2208 ISOtech (Name: 'notin'; Value: 8713), // not an element of, U+2209 ISOtech (Name: 'ni'; Value: 8715), // contains as member, U+220B ISOtech (Name: 'prod'; Value: 8719), // n-ary product = product sign, U+220F ISOamsb // prod is NOT the same character as U+03A0 'greek capital letter pi' though the // same glyph might be used for both (Name: 'sum'; Value: 8721), // n-ary sumation, U+2211 ISOamsb // sum is NOT the same character as U+03A3 'greek capital letter sigma' though the // same glyph might be used for both (Name: 'minus'; Value: 8722), // minus sign, U+2212 ISOtech (Name: 'lowast'; Value: 8727), // asterisk operator, U+2217 ISOtech (Name: 'radic'; Value: 8730), // square root = radical sign, U+221A ISOtech (Name: 'prop'; Value: 8733), // proportional to, U+221D ISOtech (Name: 'infin'; Value: 8734), // infinity, U+221E ISOtech (Name: 'ang'; Value: 8736), // angle, U+2220 ISOamso (Name: 'and'; Value: 8743), // logical and = wedge, U+2227 ISOtech (Name: 'or'; Value: 8744), // logical or = vee, U+2228 ISOtech (Name: 'cap'; Value: 8745), // intersection = cap, U+2229 ISOtech (Name: 'cup'; Value: 8746), // union = cup, U+222A ISOtech (Name: 'int'; Value: 8747), // integral, U+222B ISOtech (Name: 'there4'; Value: 8756), // therefore, U+2234 ISOtech (Name: 'sim'; Value: 8764), // tilde operator = varies with = similar to, U+223C ISOtech // tilde operator is NOT the same character as the tilde, U+007E, although the same // glyph might be used to represent both (Name: 'cong'; Value: 8773), // approximately equal to, U+2245 ISOtech (Name: 'asymp'; Value: 8776), // almost equal to = asymptotic to, U+2248 ISOamsr (Name: 'ne'; Value: 8800), // not equal to, U+2260 ISOtech (Name: 'equiv'; Value: 8801), // identical to, U+2261 ISOtech (Name: 'le'; Value: 8804), // less-than or equal to, U+2264 ISOtech (Name: 'ge'; Value: 8805), // greater-than or equal to, U+2265 ISOtech (Name: 'sub'; Value: 8834), // subset of, U+2282 ISOtech (Name: 'sup'; Value: 8835), // superset of, U+2283 ISOtech // note that nsup, 'not a superset of, U+2283' is not covered by the Symbol font // encoding and is not included. (Name: 'nsub'; Value: 8836), // not a subset of, U+2284 ISOamsn (Name: 'sube'; Value: 8838), // subset of or equal to, U+2286 ISOtech (Name: 'supe'; Value: 8839), // superset of or equal to, U+2287 ISOtech (Name: 'oplus'; Value: 8853), // circled plus = direct sum, U+2295 ISOamsb (Name: 'otimes'; Value: 8855), // circled times = vector product, U+2297 ISOamsb (Name: 'perp'; Value: 8869), // up tack = orthogonal to = perpendicular, U+22A5 ISOtech (Name: 'sdot'; Value: 8901), // dot operator, U+22C5 ISOamsb // dot operator is NOT the same character as U+00B7 middle dot // Miscellaneous Technical (Name: 'lceil'; Value: 8968), // left ceiling = apl upstile, U+2308 ISOamsc (Name: 'rceil'; Value: 8969), // right ceiling, U+2309 ISOamsc (Name: 'lfloor'; Value: 8970), // left floor = apl downstile, U+230A ISOamsc (Name: 'rfloor'; Value: 8971), // right floor, U+230B ISOamsc (Name: 'lang'; Value: 9001), // left-pointing angle bracket = bra, U+2329 ISOtech // lang is NOT the same character as U+003C 'less than' or U+2039 'single // left-pointing angle quotation mark' (Name: 'rang'; Value: 9002), // right-pointing angle bracket = ket, U+232A ISOtech // rang is NOT the same character as U+003E 'greater than' or U+203A 'single // right-pointing angle quotation mark' // Geometric Shapes (Name: 'loz'; Value: 9674), // lozenge, U+25CA ISOpub // Miscellaneous Symbols (Name: 'spades'; Value: 9824), // black spade suit, U+2660 ISOpub // black here seems to mean filled as opposed to hollow (Name: 'clubs'; Value: 9827), // black club suit = shamrock, U+2663 ISOpub (Name: 'hearts'; Value: 9829), // black heart suit = valentine, U+2665 ISOpub (Name: 'diams'; Value: 9830), // black diamond suit, U+2666 ISOpub // markup-significant and internationalization characters // C0 Controls and Basic Latin (Name: 'quot'; Value: 34), // quotation mark = APL quote, U+0022 ISOnum (Name: 'amp'; Value: 38), // ampersand, U+0026 ISOnum (Name: 'lt'; Value: 60), // less-than sign, U+003C ISOnum (Name: 'gt'; Value: 62), // greater-than sign, U+003E ISOnum // Latin Extended-A (Name: 'OElig'; Value: 338), // latin capital ligature OE, U+0152 ISOlat2 (Name: 'oelig'; Value: 339), // latin small ligature oe, U+0153 ISOlat2 // ligature is a misnomer, this is a separate character in some languages (Name: 'Scaron'; Value: 352), // latin capital letter S with caron, U+0160 ISOlat2 (Name: 'scaron'; Value: 353), // latin small letter s with caron, U+0161 ISOlat2 (Name: 'Yuml'; Value: 376), // latin capital letter Y with diaeresis, U+0178 ISOlat2 // Spacing Modifier Letters (Name: 'circ'; Value: 710), // modifier letter circumflex accent, U+02C6 ISOpub (Name: 'tilde'; Value: 732), // small tilde, U+02DC ISOdia // General Punctuation (Name: 'ensp'; Value: 8194), // en space, U+2002 ISOpub (Name: 'emsp'; Value: 8195), // em space, U+2003 ISOpub (Name: 'thinsp'; Value: 8201), // thin space, U+2009 ISOpub (Name: 'zwnj'; Value: 8204), // zero width non-joiner, U+200C NEW RFC 2070 (Name: 'zwj'; Value: 8205), // zero width joiner, U+200D NEW RFC 2070 (Name: 'lrm'; Value: 8206), // left-to-right mark, U+200E NEW RFC 2070 (Name: 'rlm'; Value: 8207), // right-to-left mark, U+200F NEW RFC 2070 (Name: 'ndash'; Value: 8211), // en dash, U+2013 ISOpub (Name: 'mdash'; Value: 8212), // em dash, U+2014 ISOpub (Name: 'lsquo'; Value: 8216), // left single quotation mark, U+2018 ISOnum (Name: 'rsquo'; Value: 8217), // right single quotation mark, U+2019 ISOnum (Name: 'sbquo'; Value: 8218), // single low-9 quotation mark, U+201A NEW (Name: 'ldquo'; Value: 8220), // left double quotation mark, U+201C ISOnum (Name: 'rdquo'; Value: 8221), // right double quotation mark, U+201D ISOnum (Name: 'bdquo'; Value: 8222), // double low-9 quotation mark, U+201E NEW (Name: 'dagger'; Value: 8224), // dagger, U+2020 ISOpub (Name: 'Dagger'; Value: 8225), // double dagger, U+2021 ISOpub (Name: 'permil'; Value: 8240), // per mille sign, U+2030 ISOtech (Name: 'lsaquo'; Value: 8249), // single left-pointing angle quotation mark, U+2039 ISO proposed // lsaquo is proposed but not yet ISO standardized (Name: 'rsaquo'; Value: 8250), // single right-pointing angle quotation mark, U+203A ISO proposed // rsaquo is proposed but not yet ISO standardized (Name: 'euro'; Value: 8364) // euro sign, U+20AC NEW ); var Entities: ThtStringList; //-- BG ---------------------------------------------------------- 26.03.2011 -- procedure InitEntities; var I: Integer; begin // Put the Entities into a sorted StringList for faster access. if Entities = nil then begin Entities := ThtStringList.Create; Entities.CaseSensitive := True; for I := low(EntityDefinitions) to high(EntityDefinitions) do Entities.AddObject(EntityDefinitions[I].Name, @EntityDefinitions[I]); Entities.Sort; end; end; //-- BG ---------------------------------------------------------- 26.03.2011 -- function TryStrToEntity(const Str: ThtString; out Entity: Integer): Boolean; var I: Integer; begin Result := Entities.Find(Str, I); if Result then Entity := PEntity(Entities.Objects[I]).Value; end; //------------------------------------------------------------------------------ // style properties //------------------------------------------------------------------------------ type PPropertyDescription = ^TPropertyDescription; TPropertyDescription = record Name: ThtString; Symbol: TPropertySymbol; end; const CPropertyDescriptions: array [1..73] of TPropertyDescription = ( (Name: 'font-family'; Symbol: FontFamily), (Name: 'font-size'; Symbol: FontSize), (Name: 'font-style'; Symbol: FontStyle), (Name: 'font-weight'; Symbol: FontWeight), (Name: 'text-align'; Symbol: TextAlign), (Name: 'text-decoration'; Symbol: TextDecoration), (Name: 'letter-spacing'; Symbol: LetterSpacing), (Name: 'color'; Symbol: Color), (Name: 'background-color'; Symbol: BackgroundColor), (Name: 'margin-top'; Symbol: MarginTop), (Name: 'margin-right'; Symbol: MarginRight), (Name: 'margin-bottom'; Symbol: MarginBottom), (Name: 'margin-left'; Symbol: MarginLeft), (Name: 'padding-top'; Symbol: PaddingTop), (Name: 'padding-right'; Symbol: PaddingRight), (Name: 'padding-bottom'; Symbol: PaddingBottom), (Name: 'padding-left'; Symbol: PaddingLeft), (Name: 'border-top-width'; Symbol: BorderTopWidth), (Name: 'border-right-width'; Symbol: BorderRightWidth), (Name: 'border-bottom-width'; Symbol: BorderBottomWidth), (Name: 'border-left-width'; Symbol: BorderLeftWidth), (Name: 'border-top-color'; Symbol: BorderTopColor), (Name: 'border-right-color'; Symbol: BorderRightColor), (Name: 'border-bottom-color'; Symbol: BorderBottomColor), (Name: 'border-left-color'; Symbol: BorderLeftColor), (Name: 'border-top-style'; Symbol: BorderTopStyle), (Name: 'border-right-style'; Symbol: BorderRightStyle), (Name: 'border-bottom-style'; Symbol: BorderBottomStyle), (Name: 'border-left-style'; Symbol: BorderLeftStyle), (Name: 'width'; Symbol: psWidth), (Name: 'height'; Symbol: psHeight), (Name: 'top'; Symbol: psTop), (Name: 'bottom'; Symbol: psBottom), (Name: 'right'; Symbol: psRight), (Name: 'left'; Symbol: psLeft), (Name: 'visibility'; Symbol: Visibility), (Name: 'line-height'; Symbol: LineHeight), (Name: 'background-image'; Symbol: BackgroundImage), (Name: 'background-position'; Symbol: BackgroundPosition), (Name: 'background-repeat'; Symbol: BackgroundRepeat), (Name: 'background-attachment'; Symbol: BackgroundAttachment), (Name: 'vertical-align'; Symbol: VerticalAlign), (Name: 'position'; Symbol: psPosition), (Name: 'z-index'; Symbol: ZIndex), (Name: 'list-style-type'; Symbol: ListStyleType), (Name: 'list-style-image'; Symbol: ListStyleImage), (Name: 'float'; Symbol: psFloat), (Name: 'clear'; Symbol: psClear), (Name: 'text-indent'; Symbol: TextIndent), (Name: 'page-break-before'; Symbol: PageBreakBefore), (Name: 'page-break-after'; Symbol: PageBreakAfter), (Name: 'page-break-inside'; Symbol: PageBreakInside), (Name: 'text-transform'; Symbol: TextTransform), (Name: 'word-wrap'; Symbol: WordWrap), (Name: 'font-variant'; Symbol: FontVariant), (Name: 'border-collapse'; Symbol: BorderCollapse), (Name: 'overflow'; Symbol: OverFlow), (Name: 'display'; Symbol: psDisplay), (Name: 'empty-cells'; Symbol: psEmptyCells), (Name: 'white-space'; Symbol: psWhiteSpace), // short hand names (Name: 'margin'; Symbol: MarginX), (Name: 'padding'; Symbol: PaddingX), (Name: 'border-width'; Symbol: BorderWidthX), (Name: 'border'; Symbol: BorderX), (Name: 'border-top'; Symbol: BorderTX), (Name: 'border-right'; Symbol: BorderRX), (Name: 'border-bottom'; Symbol: BorderBX), (Name: 'border-left'; Symbol: BorderLX), (Name: 'font'; Symbol: FontX), (Name: 'background'; Symbol: BackgroundX), (Name: 'list-style'; Symbol: ListStyleX), (Name: 'border-color'; Symbol: BorderColorX), (Name: 'border-style'; Symbol: BorderStyleX) ); var PropertyDescriptions: ThtStringList; PropertyDescriptionsIndex: array [TPropertySymbol] of Integer; procedure InitProperties; var I: Integer; P: PPropertyDescription; S: TPropertySymbol; begin // Put the Properties into a sorted StringList for faster access. if PropertyDescriptions = nil then begin PropertyDescriptions := ThtStringList.Create; PropertyDescriptions.CaseSensitive := True; for I := low(CPropertyDescriptions) to high(CPropertyDescriptions) do begin P := @CPropertyDescriptions[I]; PropertyDescriptions.AddObject(P.Name, Pointer(P)); end; PropertyDescriptions.Sort; // initialize PropertyDescriptionsIndex and SymbolNames for S := low(S) to high(S) do PropertyDescriptionsIndex[S] := -1; for I := 0 to PropertyDescriptions.Count - 1 do begin P := PPropertyDescription(PropertyDescriptions.Objects[I]); PropertyDescriptionsIndex[P.Symbol] := I; end; end; end; //-- BG ---------------------------------------------------------- 26.03.2011 -- function TryStrToPropertySymbol(const Str: ThtString; out Sy: TPropertySymbol): Boolean; var I: Integer; begin Result := PropertyDescriptions.Find(Str, I); if Result then Sy := PPropertyDescription(PropertyDescriptions.Objects[I]).Symbol else Sy := UnknownPropSy; end; //-- BG ---------------------------------------------------------- 27.03.2011 -- function PropertySymbolToStr(Sy: TPropertySymbol): ThtString; begin Result := PPropertyDescription(PropertyDescriptions.Objects[PropertyDescriptionsIndex[Sy]]).Name; end; //------------------------------------------------------------------------------ // colors //------------------------------------------------------------------------------ const CColorDescriptions: array[1..176] of TColorDescription = ( (Name: 'transparent'; Color: clNone), (Name: 'black'; Color: clBLACK), (Name: 'maroon'; Color: clMAROON), (Name: 'green'; Color: clGREEN), (Name: 'olive'; Color: clOLIVE), (Name: 'navy'; Color: clNAVY), (Name: 'purple'; Color: clPURPLE), (Name: 'teal'; Color: clTEAL), (Name: 'gray'; Color: clGRAY), (Name: 'silver'; Color: clSILVER), (Name: 'red'; Color: clRED), (Name: 'lime'; Color: clLIME), (Name: 'yellow'; Color: clYELLOW), (Name: 'blue'; Color: clBLUE), (Name: 'fuchsia'; Color: clFUCHSIA), (Name: 'aqua'; Color: clAQUA), (Name: 'white'; Color: clWHITE), (Name: 'aliceblue'; Color: $FFF8F0), (Name: 'antiquewhite'; Color: $D7EBFA), (Name: 'aquamarine'; Color: $D4FF7F), (Name: 'azure'; Color: $FFFFF0), (Name: 'beige'; Color: $DCF5F5), (Name: 'bisque'; Color: $C4E4FF), (Name: 'blanchedalmond'; Color: $CDEBFF), (Name: 'blueviolet'; Color: $E22B8A), (Name: 'brown'; Color: $2A2AA5), (Name: 'burlywood'; Color: $87B8DE), (Name: 'cadetblue'; Color: $A09E5F), (Name: 'chartreuse'; Color: $00FF7F), (Name: 'chocolate'; Color: $1E69D2), (Name: 'coral'; Color: $507FFF), (Name: 'cornflowerblue'; Color: $ED9564), (Name: 'cornsilk'; Color: $DCF8FF), (Name: 'crimson'; Color: $3614DC), (Name: 'cyan'; Color: $FFFF00), (Name: 'darkblue'; Color: $8B0000), (Name: 'darkcyan'; Color: $8B8B00), (Name: 'darkgoldenrod'; Color: $0B86B8), (Name: 'darkgray'; Color: $A9A9A9), (Name: 'darkgreen'; Color: $006400), (Name: 'darkkhaki'; Color: $6BB7BD), (Name: 'darkmagenta'; Color: $8B008B), (Name: 'darkolivegreen'; Color: $2F6B55), (Name: 'darkorange'; Color: $008CFF), (Name: 'darkorchid'; Color: $CC3299), (Name: 'darkred'; Color: $00008B), (Name: 'darksalmon'; Color: $7A96E9), (Name: 'darkseagreen'; Color: $8FBC8F), (Name: 'darkslateblue'; Color: $8B3D48), (Name: 'darkslategray'; Color: $4F4F2F), (Name: 'darkturquoise'; Color: $D1CE00), (Name: 'darkviolet'; Color: $D30094), (Name: 'deeppink'; Color: $9314FF), (Name: 'deepskyblue'; Color: $FFBF00), (Name: 'dimgray'; Color: $696969), (Name: 'dodgerblue'; Color: $FF901E), (Name: 'firebrick'; Color: $2222B2), (Name: 'floralwhite'; Color: $F0FAFF), (Name: 'forestgreen'; Color: $228B22), (Name: 'gainsboro'; Color: $DCDCDC), (Name: 'ghostwhite'; Color: $FFF8F8), (Name: 'gold'; Color: $00D7FF), (Name: 'goldenrod'; Color: $20A5DA), (Name: 'greenyellow'; Color: $2FFFAD), (Name: 'honeydew'; Color: $F0FFF0), (Name: 'hotpink'; Color: $B469FF), (Name: 'indianred'; Color: $5C5CCD), (Name: 'indigo'; Color: $82004B), (Name: 'ivory'; Color: $F0FFFF), (Name: 'khaki'; Color: $8CE6F0), (Name: 'lavender'; Color: $FAE6E6), (Name: 'lavenderblush'; Color: $F5F0FF), (Name: 'lawngreen'; Color: $00FC7C), (Name: 'lemonchiffon'; Color: $CDFAFF), (Name: 'lightblue'; Color: $E6D8AD), (Name: 'lightcoral'; Color: $8080F0), (Name: 'lightcyan'; Color: $FFFFE0), (Name: 'lightgoldenrodyellow'; Color: $D2FAFA), (Name: 'lightgreen'; Color: $90EE90), (Name: 'lightgray'; Color: $D3D3D3), (Name: 'lightpink'; Color: $C1B6FF), (Name: 'lightsalmon'; Color: $7AA0FF), (Name: 'lightseagreen'; Color: $AAB220), (Name: 'lightskyblue'; Color: $FACE87), (Name: 'lightslategray'; Color: $998877), (Name: 'lightsteelblue'; Color: $DEC4B0), (Name: 'lightyellow'; Color: $E0FFFF), (Name: 'limegreen'; Color: $32CD32), (Name: 'linen'; Color: $E6F0FA), (Name: 'magenta'; Color: $FF00FF), (Name: 'mediumaquamarine'; Color: $AACD66), (Name: 'mediumblue'; Color: $CD0000), (Name: 'mediumorchid'; Color: $D355BA), (Name: 'mediumpurple'; Color: $DB7093), (Name: 'mediumseagreen'; Color: $71B33C), (Name: 'mediumslateblue'; Color: $EE687B), (Name: 'mediumspringgreen'; Color: $9AFA00), (Name: 'mediumturquoise'; Color: $CCD148), (Name: 'mediumvioletred'; Color: $8515C7), (Name: 'midnightblue'; Color: $701919), (Name: 'mintcream'; Color: $FAFFF5), (Name: 'mistyrose'; Color: $E1E4FF), (Name: 'moccasin'; Color: $B5E4FF), (Name: 'navajowhite'; Color: $ADDEFF), (Name: 'oldlace'; Color: $E6F5FD), (Name: 'olivedrab'; Color: $238E6B), (Name: 'orange'; Color: $00A5FF), (Name: 'orangered'; Color: $0045FF), (Name: 'orchid'; Color: $D670DA), (Name: 'palegoldenrod'; Color: $AAE8EE), (Name: 'palegreen'; Color: $98FB98), (Name: 'paleturquoise'; Color: $EEEEAF), (Name: 'palevioletred'; Color: $9370DB), (Name: 'papayawhip'; Color: $D5EFFF), (Name: 'peachpuff'; Color: $B9DAFF), (Name: 'peru'; Color: $3F85CD), (Name: 'pink'; Color: $CBC0FF), (Name: 'plum'; Color: $DDA0DD), (Name: 'powderblue'; Color: $E6E0B0), (Name: 'rosybrown'; Color: $8F8FBC), (Name: 'royalblue'; Color: $E16941), (Name: 'saddlebrown'; Color: $13458B), (Name: 'salmon'; Color: $7280FA), (Name: 'sandybrown'; Color: $60A4F4), (Name: 'seagreen'; Color: $578B2E), (Name: 'seashell'; Color: $EEF5FF), (Name: 'sienna'; Color: $2D52A0), (Name: 'skyblue'; Color: $EBCE87), (Name: 'slateblue'; Color: $CD5A6A), (Name: 'slategray'; Color: $908070), (Name: 'snow'; Color: $FAFAFF), (Name: 'springgreen'; Color: $7FFF00), (Name: 'steelblue'; Color: $B48246), (Name: 'tan'; Color: $8CB4D2), (Name: 'thistle'; Color: $D8BFD8), (Name: 'tomato'; Color: $4763FF), (Name: 'turquoise'; Color: $D0E040), (Name: 'violet'; Color: $EE82EE), (Name: 'wheat'; Color: $B3DEF5), (Name: 'whitesmoke'; Color: $F5F5F5), (Name: 'yellowgreen'; Color: $32CD9A), (Name: 'grey'; Color: clgray), (Name: 'darkgrey'; Color: $A9A9A9), (Name: 'darkslategrey'; Color: $4F4F2F), (Name: 'dimgrey'; Color: $696969), (Name: 'lightgrey'; Color: $D3D3D3), (Name: 'lightslategrey'; Color: $998877), (Name: 'slategrey'; Color: $908070), (Name: 'background'; Color: clBackground), (Name: 'activecaption'; Color: clActiveCaption), (Name: 'inactivecaption'; Color: clInactiveCaption), (Name: 'menu'; Color: clMenu), (Name: 'window'; Color: clWindow), (Name: 'windowframe'; Color: clWindowFrame), (Name: 'menutext'; Color: clMenuText), (Name: 'windowtext'; Color: clWindowText), (Name: 'captiontext'; Color: clCaptionText), (Name: 'activeborder'; Color: clActiveBorder), (Name: 'inactiveborder'; Color: clInactiveBorder), (Name: 'appworkSpace'; Color: clAppWorkSpace), (Name: 'highlight'; Color: clHighlight), (Name: 'hightlighttext'; Color: clHighlightText), (Name: 'buttonface'; Color: clBtnFace), (Name: 'buttonshadow'; Color: clBtnShadow), (Name: 'graytext'; Color: clGrayText), (Name: 'buttontext'; Color: clBtnText), (Name: 'inactivecaptiontext'; Color: clInactiveCaptionText), (Name: 'buttonhighlight'; Color: clBtnHighlight), (Name: 'threeddarkshadow'; Color: cl3DDkShadow), (Name: 'threedlightshadow'; Color: clBtnHighlight), (Name: 'infotext'; Color: clInfoText), (Name: 'infobackground'; Color: clInfoBk), (Name: 'scrollbar'; Color: clScrollBar), (Name: 'threedface'; Color: clBtnFace), (Name: 'threedhighlight'; Color: cl3DLight), (Name: 'threedshadow'; Color: clBtnShadow) ); var ColorDescriptions: ThtStringList; function AllMyColors: ThtStringList; begin Result := ColorDescriptions; end; procedure InitColors; var I: Integer; P: PColorDescription; begin // Put the Properties into a sorted StringList for faster access. if ColorDescriptions = nil then begin ColorDescriptions := ThtStringList.Create; ColorDescriptions.CaseSensitive := True; for I := low(CColorDescriptions) to high(CColorDescriptions) do begin P := @CColorDescriptions[I]; ColorDescriptions.AddObject(P.Name, Pointer(P)); end; ColorDescriptions.Sort; end; end; //-- BG ---------------------------------------------------------- 26.03.2011 -- function TryNameToColor(const Name: ThtString; out Color: TColor): Boolean; var I: Integer; begin Result := ColorDescriptions.Find(Name, I); if Result then Color := PColorDescription(ColorDescriptions.Objects[I]).Color else Color := clNone; end; //------------------------------------------------------------------------------ // html attributes //------------------------------------------------------------------------------ type PAttributeDescription = ^TAttributeDescription; TAttributeDescription = record Name: ThtString; Attr: THtmlAttributeSymbol; end; const UnknownAd: TAttributeDescription = (Name: 'unknown'; Attr: UnknownAttr); CAttributeDescriptions: array[1..101] of TAttributeDescription = ( (Name: 'ACTION'; Attr: ActionAttr), (Name: 'ACTIVE'; Attr: ActiveAttr), (Name: 'ALIGN'; Attr: AlignAttr), (Name: 'ALT'; Attr: AltAttr), (Name: 'BACKGROUND'; Attr: BackgroundAttr), (Name: 'BGCOLOR'; Attr: BGColorAttr), (Name: 'BGPROPERTIES'; Attr: BGPropertiesAttr), (Name: 'BORDER'; Attr: BorderAttr), (Name: 'BORDERCOLOR'; Attr: BorderColorAttr), (Name: 'BORDERCOLORDARK'; Attr: BorderColorDarkAttr), (Name: 'BORDERCOLORLIGHT'; Attr: BorderColorLightAttr), (Name: 'CELLPADDING'; Attr: CellPaddingAttr), (Name: 'CELLSPACING'; Attr: CellSpacingAttr), (Name: 'CHARSET'; Attr: CharSetAttr), (Name: 'CHECKBOX'; Attr: CheckBoxAttr), (Name: 'CHECKED'; Attr: CheckedAttr), (Name: 'CLASS'; Attr: ClassAttr), (Name: 'CLEAR'; Attr: ClearAttr), (Name: 'COLOR'; Attr: ColorAttr), (Name: 'COLS'; Attr: ColsAttr), (Name: 'COLSPAN'; Attr: ColSpanAttr), (Name: 'CONTENT'; Attr: ContentAttr), (Name: 'COORDS'; Attr: CoordsAttr), (Name: 'DIR'; Attr: DirAttr), (Name: 'DISABLED'; Attr: DisabledAttr), (Name: 'ENCTYPE'; Attr: EncTypeAttr), (Name: 'FACE'; Attr: FaceAttr), (Name: 'FOR'; Attr: ForAttr), (Name: 'FRAMEBORDER'; Attr: FrameBorderAttr), (Name: 'HEIGHT'; Attr: HeightAttr), (Name: 'HREF'; Attr: HrefAttr), (Name: 'HSPACE'; Attr: HSpaceAttr), (Name: 'HTTP-EQUIV'; Attr: HttpEquivAttr), (Name: 'ID'; Attr: IDAttr), (Name: 'ISMAP'; Attr: IsMapAttr), (Name: 'LABEL'; Attr: LabelAttr), (Name: 'LANGUAGE'; Attr: LanguageAttr), (Name: 'LEFTMARGIN'; Attr: LeftMarginAttr), (Name: 'LINK'; Attr: LinkAttr), (Name: 'LOOP'; Attr: LoopAttr), (Name: 'MARGINHEIGHT'; Attr: MarginHeightAttr), (Name: 'MARGINWIDTH'; Attr: MarginWidthAttr), (Name: 'MAXLENGTH'; Attr: MaxLengthAttr), (Name: 'MEDIA'; Attr: MediaAttr), (Name: 'METHOD'; Attr: MethodAttr), (Name: 'MULTIPLE'; Attr: MultipleAttr), (Name: 'NAME'; Attr: NameAttr), (Name: 'NOHREF'; Attr: NoHrefAttr), (Name: 'NORESIZE'; Attr: NoResizeAttr), (Name: 'NOSHADE'; Attr: NoShadeAttr), (Name: 'NOWRAP'; Attr: NoWrapAttr), (Name: 'OLINK'; Attr: OLinkAttr), (Name: 'ONBLUR'; Attr: OnBlurAttr), (Name: 'ONCHANGE'; Attr: OnChangeAttr), (Name: 'ONCLICK'; Attr: OnClickAttr), (Name: 'ONFOCUS'; Attr: OnFocusAttr), (Name: 'ONDBLCLICK'; Attr: OnDblClickAttr), (Name: 'ONFOCUS'; Attr: OnFocusAttr), (Name: 'ONKEYDOWN'; Attr: OnKeyDownAttr), (Name: 'ONKEYPRESS'; Attr: OnKeyPressAttr), (Name: 'ONKEYUP'; Attr: OnKeyUpAttr), (Name: 'ONLOAD'; Attr: OnLoadAttr), (Name: 'ONMOUSEDOWN'; Attr: OnMouseDownAttr), (Name: 'ONMOUSEMOVE'; Attr: OnMouseMoveAttr), (Name: 'ONMOUSEOUT'; Attr: OnMouseOutAttr), (Name: 'ONMOUSEOVER'; Attr: OnMouseOverAttr), (Name: 'ONMOUSEUP'; Attr: OnMouseUpAttr), (Name: 'ONCHANGE'; Attr: OnResetAttr), (Name: 'ONCLICK'; Attr: OnSelectAttr), (Name: 'ONFOCUS'; Attr: OnSubmitAttr), (Name: 'ONDBLCLICK'; Attr: OnUnloadAttr), (Name: 'PLAIN'; Attr: PlainAttr), (Name: 'RADIO'; Attr: RadioAttr), (Name: 'RATIO'; Attr: RatioAttr), (Name: 'READONLY'; Attr: ReadonlyAttr), (Name: 'REL'; Attr: RelAttr), (Name: 'REV'; Attr: RevAttr), (Name: 'ROWS'; Attr: RowsAttr), (Name: 'ROWSPAN'; Attr: RowSpanAttr), (Name: 'SCROLLING'; Attr: ScrollingAttr), (Name: 'SELECTED'; Attr: SelectedAttr), (Name: 'SHAPE'; Attr: ShapeAttr), (Name: 'SIZE'; Attr: SizeAttr), (Name: 'SPAN'; Attr: SpanAttr), (Name: 'SRC'; Attr: SrcAttr), (Name: 'START'; Attr: StartAttr), (Name: 'STYLE'; Attr: StyleAttr), (Name: 'TABINDEX'; Attr: TabIndexAttr), (Name: 'TARGET'; Attr: TargetAttr), (Name: 'TEXT'; Attr: TextAttr), (Name: 'TITLE'; Attr: TitleAttr), (Name: 'TOPMARGIN'; Attr: TopMarginAttr), (Name: 'TRANSP'; Attr: TranspAttr), (Name: 'TYPE'; Attr: TypeAttr), (Name: 'USEMAP'; Attr: UseMapAttr), (Name: 'VALIGN'; Attr: VAlignAttr), (Name: 'VALUE'; Attr: ValueAttr), (Name: 'VLINK'; Attr: VLinkAttr), (Name: 'VSPACE'; Attr: VSpaceAttr), (Name: 'WIDTH'; Attr: WidthAttr), (Name: 'WRAP'; Attr: WrapAttr) ); var AttributeDescriptions: ThtStringList; AttributeDescriptionsIndex: array [THtmlAttributeSymbol] of PAttributeDescription; procedure InitAttributes; var I: Integer; P: PAttributeDescription; begin // Put the Attributes into a sorted StringList for faster access. if AttributeDescriptions = nil then begin AttributeDescriptionsIndex[UnknownAd.Attr] := @UnknownAd; AttributeDescriptions := ThtStringList.Create; AttributeDescriptions.CaseSensitive := True; for I := low(CAttributeDescriptions) to high(CAttributeDescriptions) do begin P := @CAttributeDescriptions[I]; AttributeDescriptions.AddObject(P.Name, Pointer(P)); AttributeDescriptionsIndex[P.Attr] := P; end; AttributeDescriptions.Sort; end; end; //-- BG ---------------------------------------------------------- 26.03.2011 -- function TryStrToAttributeSymbol(const Str: ThtString; out Sy: THtmlAttributeSymbol): Boolean; var I: Integer; begin Result := AttributeDescriptions.Find(Str, I); if Result then Sy := PAttributeDescription(AttributeDescriptions.Objects[I]).Attr else Sy := UnknownAttr; end; //-- BG ---------------------------------------------------------- 27.03.2011 -- function AttributeSymbolToStr(Sy: THtmlAttributeSymbol): ThtString; begin Result := PAttributeDescription(AttributeDescriptionsIndex[Sy]).Name; end; //-- BG ---------------------------------------------------------- 16.04.2011 -- function TryStrToLinkType(const Str: ThtString; out LinkType: THtmlLinkType): Boolean; var I: THtmlLinkType; begin for I := low(I) to high(I) do if CHtmlLinkType[I] = Str then begin Result := True; LinkType := I; exit; end; Result := False; end; initialization InitAttributes; InitColors; InitEntities; InitProperties; finalization AttributeDescriptions.Free; ColorDescriptions.Free; Entities.Free; PropertyDescriptions.Free; end.
unit RptDialg; interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, ExtCtrls, Dialogs, Zipcopy, locatdir, WinUtils, ShellAPI; type TReportDialog = class(TForm) DoneSaveButton: TBitBtn; ReportNameEdit: TEdit; Label1: TLabel; CopyButton: TBitBtn; DoneDontSaveButton: TBitBtn; Label2: TLabel; Label3: TLabel; DirectoryEdit: TEdit; ZipCopyDialog: TZipCopyDlg; DirectorySpeedButton: TSpeedButton; ViewButton: TBitBtn; LocateDirectoryDlg: TLocateDirectoryDlg; EmailButton: TBitBtn; procedure DoneSaveButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure DoneDontSaveButtonClick(Sender: TObject); procedure CopyButtonClick(Sender: TObject); procedure DirectorySpeedButtonClick(Sender: TObject); procedure ViewButtonClick(Sender: TObject); procedure EmailButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } FileName, OrigFileName, OrigDirectoryName, DirectoryName : String; Procedure SaveFile(FileName, DirectoryName : String); end; var ReportDialog: TReportDialog; implementation {$R *.DFM} uses Glblvars, SysUtils, Utilitys, PASUtils; {CHG01182000-3: Allow them to choose a different name or copy right away.} {==============================================================} Procedure TReportDialog.FormShow(Sender: TObject); begin LocateDirectoryDlg.Directory := ExpandPASPath(GlblReportDir); DirectoryEdit.Text := ExpandPASPath(GlblReportDir); ReportNameEdit.Text := FileName; OrigDirectoryName := DirectoryEdit.Text; end; {FormShow} {==============================================================} Procedure TReportDialog.SaveFile(FileName, DirectoryName : String); var TempFile : TextFile; OldFileName : String; begin If (Deblank(OrigDirectoryName) = '') then OrigDirectoryName := ExpandPASPath(GlblReportDir); {Now rename the text file to a recognizable name, but to do so, erase the original first. This is so that several people can run this job at once.} {FXX04262000-1: Make sure that the current file name <> the original file name. If it is, it has already been saved - i.e. they went to Copy first.} If (FileName <> OrigFileName) then begin try Chdir(OrigDirectoryName); OldDeleteFile(FileName); except end; try RenameFile(OrigFileName, FileName); except {If the person has the report dialog up, give them an option of what to do. Otherwise, rename to a different extension.} If Visible then begin MessageDlg('At the current time, this report can not be saved with the name ' + #13 + FileName + ' because someone else has the file open.' + #13 + 'Please save the report with a different name or have the ' + #13 + 'person exit the file and try to save it again.', mtError, [mbOK], 0); Abort; end else begin {Strip off the extension and rename as .TMP.} OldFileName := FileName; FileName := GetUpToChar('.', FileName, True) + 'TMP'; OldDeleteFile(FileName); try Rename(TempFile, FileName); except RenameFile(OrigFileName, FileName); end; MessageDlg('The report can not be saved with the standard name ' + OldFileName + #13 + 'because the file is currently being used by someone else.' + #13 + 'It has been saved with the name ' + FileName + '.', mtInformation, [mbOK], 0); end; {If Visible} end; {FXX06092003-2(2.07c): Let them change the directory name.} If (DirectoryName <> OrigDirectoryName) then try CopyOneFile(AddDirectorySlashes(OrigDirectoryName) + FileName, AddDirectorySlashes(DirectoryName) + FileName); ChDir(OrigDirectoryName); OldDeleteFile(FileName); except end; ChDir(ExpandPASPath(GlblProgramDir)); {FXX04272000-1: Reset original file name so rename doesn't cause prob.} OrigFileName := FileName; OrigDirectoryName := DirectoryName; end; {If (FileName <> OrigFileName)} end; {SaveFile} {==============================================================} Procedure TReportDialog.DoneSaveButtonClick(Sender: TObject); begin FileName := ReportNameEdit.Text; DirectoryName := DirectoryEdit.Text; SaveFile(FileName, DirectoryName); {This is also called by the copy button, but don't close.} If (TButton(Sender).Name = 'DoneSaveButton') then Close; end; {DoneSaveButtonClick} {==============================================================} Procedure TReportDialog.DoneDontSaveButtonClick(Sender: TObject); begin FileName := ''; DirectoryName := ''; try Chdir(ExpandPASPath(GlblReportDir)); OldDeleteFile(OrigFileName); finally ChDir(ExpandPASPath(GlblProgramDir)); end; Close; end; {DoneDontSaveButtonClick} {==============================================================} Procedure TReportDialog.CopyButtonClick(Sender: TObject); begin {First save the file.} DoneSaveButtonClick(Sender); with ZipCopyDialog do begin FileName := ReportNameEdit.Text; InitialDir := Copy(DirectoryEdit.Text, 3, 100); InitialDrive := Copy(DirectoryEdit.Text, 1, 1); SelectFile(DirectoryEdit.Text + FileName); Execute; end; {with ZipCopyDialog do} end; {CopyButtonClick} {===============================================================} Procedure TReportDialog.DirectorySpeedButtonClick(Sender: TObject); begin If LocateDirectoryDlg.Execute then DirectoryEdit.Text := LocateDirectoryDlg.Directory; end; {DirectorySpeedButtonClick} {======================================================} Procedure TReportDialog.ViewButtonClick(Sender: TObject); var PrintFileName, TempStr : String; PCLFile : Boolean; TempFile : TextFile; ReturnCode : Word; TempPChar : PChar; begin PrintFileName := ReportNameEdit.Text; ChDir(ExpandPASPath(OrigDirectoryName)); {FXX01212000-1: Allow for recall of PCL format reports.} AssignFile(TempFile, PrintFileName); Reset(TempFile); Readln(TempFile, TempStr); PCLFile := (Pos('PCL', TempStr) > 0); If PCLFile then MessageDlg('Sorry, you can not view a laser only report as text.', mtError, [mbOK], 0) else begin TempStr := 'C:\PROGRA~1\ACCESS~1\WORDPAD ' + PrintFileName; GetMem(TempPChar, Length(TempStr) + 1); StrPCopy(TempPChar, TempStr); ReturnCode := WinExec(TempPChar, SW_Show); FreeMem(TempPChar, Length(TempStr) + 1); If (ReturnCode < 32) then MessageDlg('Word pad failed to bring up the report. Error = ' + IntToStr(ReturnCode) + '.', mtError, [mbOK], 0); end; {else of If PCLFile} end; {ViewButtonClick} {======================================================} Procedure TReportDialog.EmailButtonClick(Sender: TObject); {CHG10082003-1(2.07k): Extend email option to more programs.} var AttachmentName, TempStr, PrintFileName : String; PCLFile : Boolean; TempFile : TextFile; begin DoneSaveButtonClick(Sender); PrintFileName := ReportNameEdit.Text; ChDir(ExpandPASPath(OrigDirectoryName)); {FXX01212000-1: Allow for recall of PCL format reports.} AssignFile(TempFile, PrintFileName); Reset(TempFile); Readln(TempFile, TempStr); PCLFile := (Pos('PCL', TempStr) > 0); CloseFile(TempFile); If PCLFile then MessageDlg('Sorry, you can not email a laser only report.', mtError, [mbOK], 0) else begin {CHG03232004-4(2.08): Change the email sending process and add it to all needed places.} AttachmentName := ExpandPASPath(DirectoryEdit.Text) + ReportNameEdit.Text; SendMail('', '', AttachmentName, '', '', '', '', '', True); end; {else of If PCLFile} end; {EmailButtonClick} end.
unit Util; {$mode objfpc}{$H+} interface uses Classes, SysUtils; procedure WriteProgramLog(Log: string; Force: boolean = false); procedure WriteProgramLog(i: longint; Force: boolean = false); procedure WriteProgramLog(i: int64; Force: boolean = false); procedure WriteProgramLog(d: double; Force: boolean = false); //procedure SeparateIndices(Source: string; sa: TStrings; var ia: tStringArray); function strf(x: double): string; function strf(x: longint): string; function strf(x: int64): string; function valf(s: string): integer; function vald(s: string): double; function CopyFromTo(Origin: string; Start, Stop: string): string; function CopyFromTo(Origin: string; SearchStart: integer; Start, Stop: string): string; function CopyDelFromTo(var Origin: string; Start, Stop: string): string; // function SubstrCount(const aString, aSubstring: string): Integer; var ProgramLog: TFileStream; LogCS: TRTLCriticalSection; implementation uses LConvEncoding, Math, StrUtils; function strf(x: double): string; inline; begin str(x, Result); end; function strf(x: longint): string; inline; begin str(x, Result); end; function strf(x: int64): string; begin str(x, Result); end; function valf(s: string): integer; inline; begin val(s, Result); end; function vald(s: string): double; inline; begin val(s, Result); end; function CopyFromTo(Origin: string; Start, Stop: string): string; var p1, p2: integer; begin p1:= Pos(Start, Origin) + 1; p2:= Pos(Stop, Origin); Result:= Copy(Origin, p1, p2 - p1); end; function CopyFromTo(Origin: string; SearchStart: integer; Start, Stop: string ): string; var p1, p2, i, l: integer; begin Delete(Origin, 1, SearchStart - 1); l:= length(Start); {if l > 1 then inc(l); } p1:= Pos(Start, Origin) + l; //Delete(Origin, 1, p1 - 1); //p1:= Pos(Start, Origin) + l; p2:= Pos(Stop, Origin); i:= 2; while p2 < p1 do begin p2:= NPos(Stop, Origin, i); inc(i); if i > 100 then break; end; Result:= Copy(Origin, p1, p2 - p1); end; function CopyDelFromTo(var Origin: string; Start, Stop: string): string; var p1, p2: integer; begin p1:= Pos(Start, Origin) + 1; p2:= Pos(Stop, Origin); Result:= Copy(Origin, p1, p2 - p1); Delete(Origin, 1, p2 + length(Stop) - 1); end; {function SubstrCount(const aString, aSubstring: string): Integer; var lPosition: Integer; begin Result := 0; lPosition := PosEx(aSubstring, aString); while lPosition <> 0 do begin Inc(Result); lPosition := PosEx(aSubstring, aString, lPosition + Length(aSubstring)); end; end; } procedure WriteProgramLog(Log: string; Force: boolean = false); inline; begin if true or Force then try EnterCriticalSection(LogCS); Log+= LineEnding; ProgramLog.Write(Log[1], length(Log)); finally LeaveCriticalSection(LogCS); end; end; procedure WriteProgramLog(i: longint; Force: boolean = false); inline; begin WriteProgramLog(strf(i), Force); end; procedure WriteProgramLog(i: int64; Force: boolean = false); inline; begin WriteProgramLog(strf(i), Force); end; procedure WriteProgramLog(d: double; Force: boolean = false); inline; begin WriteProgramLog(strf(d), Force); end; initialization begin if FileExists('ProgramLog.txt') then DeleteFile('ProgramLog.txt'); ProgramLog:= TFileStream.Create('ProgramLog.txt', fmCreate); InitCriticalSection(LogCS); end; finalization begin DoneCriticalSection(LogCS); ProgramLog.Free; end; end.
unit IdFTP; interface uses Classes, IdException, IdGlobal, SysUtils, IdSocketHandle, IdTCPConnection, IdTCPClient, IdThread, IdURI; type TIdFTPTransferType = (ftBinary, ftASCII); const Id_TIdFTP_TransferType = ftBinary; Id_TIdFTP_Passive = False; type TIdFTP = class(TIdTCPClient) protected FUser: string; FPassive: boolean; FPassword: string; FSystemDesc: string; FTransferType: TIdFTPTransferType; FDataChannel: TIdTCPConnection; procedure InternalGet(const ACommand: string; ADest: TStream); procedure InternalPut(const ACommand: string; ASource: TStream); procedure SendPassive(var VIP: string; var VPort: integer); procedure SendPort(AHandle: TIdSocketHandle); procedure SendTransferType; procedure SetDataChannelWorkEvents; procedure SetTransferType(AValue: TIdFTPTransferType); public procedure Abort; virtual; procedure ChangeDir(const ADirName: string); procedure ChangeDirUp; procedure Connect(AutoLogin: Boolean = true); reintroduce; constructor Create(AOwner: TComponent); override; procedure Delete(const AFilename: string); procedure Get(const ASourceFile: string; ADest: TStream); overload; procedure Get(const ASourceFile, ADestFile: string; const ACanOverwrite: boolean = false); overload; procedure KillDataChannel; virtual; procedure List(ADest: TStrings; const ASpecifier: string = ''; const ADetails: boolean = true); procedure MakeDir(const ADirName: string); procedure Noop; procedure Put(const ASource: TStream; const ADestFile: string = ''; const AAppend: boolean = false); overload; procedure Put(const ASourceFile: string; const ADestFile: string = ''; const AAppend: boolean = false); overload; procedure Quit; procedure RemoveDir(const ADirName: string); procedure Rename(const ASourceFile, ADestFile: string); function RetrieveCurrentDir: string; procedure Site(const ACommand: string); function Size(const AFileName: string): Integer; property SystemDesc: string read FSystemDesc; published property Passive: boolean read FPassive write FPassive default Id_TIdFTP_Passive; property Password: string read FPassword write FPassword; property TransferType: TIdFTPTransferType read FTransferType write SetTransferType default Id_TIdFTP_TransferType; property User: string read FUser write FUser; property Port default IDPORT_FTP; end; EIdFTPFileAlreadyExists = class(EIdException); implementation uses IdComponent, IdResourceStrings, IdStack, IdSimpleServer; function CleanDirName(const APWDReply: string): string; begin result := APWDReply; Delete(result, 1, Pos('"', result)); result := Copy(result, 1, Pos('"', result) - 1); end; constructor TIdFTP.Create(AOwner: TComponent); begin inherited; Port := IDPORT_FTP; Passive := Id_TIdFTP_Passive; FTransferType := Id_TIdFTP_TransferType end; procedure TIdFTP.Connect(AutoLogin: Boolean = true); begin try inherited Connect; GetResponse([220]); if AutoLogin then begin if SendCmd('user ' + User, [230, 331]) = 331 then begin SendCmd('pass ' + Password, 230); end; SendTransferType; if SendCmd('syst', [200, 215, 500]) = 500 then begin FSystemDesc := RSFTPUnknownHost; end else begin FSystemDesc := Copy(CmdResult, 4, MaxInt); end; end; except Disconnect; raise; end; end; procedure TIdFTP.SetTransferType(AValue: TIdFTPTransferType); begin if AValue <> FTransferType then begin if not Assigned(FDataChannel) then begin FTransferType := AValue; if Connected then begin SendTransferType; end; end end; end; procedure TIdFTP.SendTransferType; var s: string; begin case TransferType of ftAscii: s := 'A'; ftBinary: s := 'I'; end; SendCmd('type ' + s, 200); end; procedure TIdFTP.Get(const ASourceFile: string; ADest: TStream); begin InternalGet('retr ' + ASourceFile, ADest); end; procedure TIdFTP.Get(const ASourceFile, ADestFile: string; const ACanOverwrite: boolean = false); var LDestStream: TFileStream; begin if FileExists(ADestFile) and (not ACanOverwrite) then begin raise EIdFTPFileAlreadyExists.Create(RSDestinationFileAlreadyExists); end; LDestStream := TFileStream.Create(ADestFile, fmCreate); try Get(ASourceFile, LDestStream); finally FreeAndNil(LDestStream); end; end; procedure TIdFTP.List(ADest: TStrings; const ASpecifier: string = ''; const ADetails: boolean = true); var LDest: TStringStream; begin LDest := TStringStream.Create(''); try if ADetails then begin InternalGet(trim('list ' + ASpecifier), LDest); end else begin InternalGet(trim('nlst ' + ASpecifier), LDest); end; ADest.Text := LDest.DataString; finally LDest.Free; end; end; procedure TIdFTP.InternalGet(const ACommand: string; ADest: TStream); var LIP: string; LPort: Integer; begin if FPassive then begin SendPassive(LIP, LPort); WriteLn(ACommand); FDataChannel := TIdTCPClient.Create(nil); try with (FDataChannel as TIdTCPClient) do begin SocksInfo.Assign(Self.SocksInfo); SetDataChannelWorkEvents; Host := LIP; Port := LPort; Connect; try Self.GetResponse([125, 150]); ReadStream(ADest, -1, True); finally Disconnect; end; end; finally FreeAndNil(FDataChannel); end; end else begin FDataChannel := TIdSimpleServer.Create(nil); try with TIdSimpleServer(FDataChannel) do begin SetDataChannelWorkEvents; BoundIP := Self.Binding.IP; BeginListen; SendPort(Binding); Self.SendCmd(ACommand, [125, 150]); Listen; ReadStream(ADest, -1, True); end; finally FreeAndNil(FDataChannel); end; end; if GetResponse([225, 226, 250, 426]) = 426 then begin GetResponse([226]); end; end; procedure TIdFTP.Quit; begin if connected then begin WriteLn('Quit'); Disconnect; end; end; procedure TIdFTP.KillDataChannel; begin if Assigned(FDataChannel) then begin FDataChannel.DisconnectSocket; end; end; procedure TIdFTP.Abort; begin if Connected then begin WriteLn('ABOR'); end; KillDataChannel; end; procedure TIdFTP.SendPort(AHandle: TIdSocketHandle); begin SendCmd('PORT ' + StringReplace(AHandle.IP, '.', ',', [rfReplaceAll]) + ',' + IntToStr(AHandle.Port div 256) + ',' + IntToStr(AHandle.Port mod 256), [200]); end; procedure TIdFTP.InternalPut(const ACommand: string; ASource: TStream); var LIP: string; LPort: Integer; begin if FPassive then begin SendPassive(LIP, LPort); WriteLn(ACommand); FDataChannel := TIdTCPClient.Create(nil); with TIdTCPClient(FDataChannel) do try SetDataChannelWorkEvents; Host := LIP; Port := LPort; SocksInfo.Assign(Self.SocksInfo); Connect; try Self.GetResponse([110, 125, 150]); try WriteStream(ASource, false); except on E: EIdSocketError do begin if E.LastError <> 10038 then begin raise; end; end; end; finally Disconnect; end; finally FreeAndNil(FDataChannel); end; end else begin FDataChannel := TIdSimpleServer.Create(nil); try with TIdSimpleServer(FDataChannel) do begin SetDataChannelWorkEvents; BoundIP := Self.Binding.IP; BeginListen; SendPort(Binding); Self.SendCmd(ACommand, [125, 150]); Listen; WriteStream(ASource); end; finally FreeAndNil(FDataChannel); end; end; if GetResponse([225, 226, 250, 426]) = 426 then begin GetResponse([226]); end; end; procedure TIdFTP.SetDataChannelWorkEvents; begin FDataChannel.OnWork := OnWork; FDataChannel.OnWorkBegin := OnWorkBegin; FDataChannel.OnWorkEnd := OnWorkEnd; end; procedure TIdFTP.Put(const ASource: TStream; const ADestFile: string = ''; const AAppend: boolean = false); begin if length(ADestFile) = 0 then begin InternalPut('STOU ' + ADestFile, ASource); end else if AAppend then begin InternalPut('APPE ' + ADestFile, ASource); end else begin InternalPut('STOR ' + ADestFile, ASource); end; end; procedure TIdFTP.Put(const ASourceFile: string; const ADestFile: string = ''; const AAppend: boolean = false); var LSourceStream: TFileStream; begin LSourceStream := TFileStream.Create(ASourceFile, fmOpenRead or fmShareDenyNone); try Put(LSourceStream, ADestFile, AAppend); finally FreeAndNil(LSourceStream); end; end; procedure TIdFTP.SendPassive(var VIP: string; var VPort: integer); var i, bLeft, bRight: integer; s: string; begin SendCmd('PASV', 227); s := Trim(CmdResult); bLeft := Pos('(', s); bRight := Pos(')', s); if (bLeft = 0) or (bRight = 0) then begin bLeft := RPos(#32, s); s := Copy(s, bLeft + 1, Length(s) - bLeft); end else begin s := Copy(s, bLeft + 1, bRight - bLeft - 1); end; VIP := ''; for i := 1 to 4 do begin VIP := VIP + '.' + Fetch(s, ','); end; System.Delete(VIP, 1, 1); VPort := StrToInt(Fetch(s, ',')) * 256; VPort := VPort + StrToInt(Fetch(s, ',')); end; procedure TIdFTP.Noop; begin SendCmd('NOOP', 200); end; procedure TIdFTP.MakeDir(const ADirName: string); begin SendCmd('MKD ' + ADirName, 257); end; function TIdFTP.RetrieveCurrentDir: string; begin SendCmd('PWD', 257); Result := CleanDirName(CmdResult); end; procedure TIdFTP.RemoveDir(const ADirName: string); begin SendCmd('RMD ' + ADirName, 250); end; procedure TIdFTP.Delete(const AFilename: string); begin SendCmd('DELE ' + AFilename, 250); end; procedure TIdFTP.ChangeDir(const ADirName: string); begin SendCmd('CWD ' + ADirName, 250); end; procedure TIdFTP.ChangeDirUp; begin SendCmd('CDUP', 250); end; procedure TIdFTP.Site(const ACommand: string); begin SendCmd('SITE ' + ACommand, 200); end; procedure TIdFTP.Rename(const ASourceFile, ADestFile: string); begin SendCmd('RNFR ' + ASourceFile, 350); SendCmd('RNTO ' + ADestFile, 250); end; function TIdFTP.Size(const AFileName: string): Integer; var SizeStr: string; begin result := -1; if SendCmd('SIZE ' + AFileName) = 213 then begin SizeStr := Trim(CmdResultDetails.text); system.delete(SizeStr, 1, pos(' ', SizeStr)); result := StrToIntDef(SizeStr, -1); end; end; end.
unit AVerificaLeituraLembrete; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, UnLembrete, UnDados, StdCtrls, Buttons, Db, DBTables, Grids, DBGrids, Tabela, DBKeyViolation, DBClient; type TFVerificaLeituraLembrete = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; PanelColor3: TPanelColor; ETitulo: TEditColor; Label5: TLabel; BFechar: TBitBtn; LEMBRETEITEMLIDOS: TSQL; DataLEMBRETEITEM: TDataSource; DataLEMBRETEITEMNAOLIDOS: TDataSource; LEMBRETEITEMNAOLIDOS: TSQL; USUARIOSNAOLIDOS: TGridIndice; USUARIOSLIDOS: TGridIndice; LEMBRETEITEMLIDOSC_NOM_USU: TWideStringField; LEMBRETEITEMNAOLIDOSC_NOM_USU: TWideStringField; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); private VprDLembreteCorpo: TRBDLembreteCorpo; FunLembrete: TRBFuncoesLembrete; procedure CarDTela; procedure AtualizaConsulta; public procedure VerificaLeitura(VpaSeqLembrete, VpaCodUsuario: Integer); end; var FVerificaLeituraLembrete: TFVerificaLeituraLembrete; implementation uses APrincipal, ConstMsg, Constantes; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFVerificaLeituraLembrete.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VprDLembreteCorpo:= TRBDLembreteCorpo.Cria; FunLembrete:= TRBFuncoesLembrete.Cria(FPrincipal.BaseDados); end; { ******************* Quando o formulario e fechado ************************** } procedure TFVerificaLeituraLembrete.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } VprDLembreteCorpo.Free; FunLembrete.Free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFVerificaLeituraLembrete.VerificaLeitura(VpaSeqLembrete, VpaCodUsuario: Integer); begin FunLembrete.CarDLembrete(VpaSeqLembrete,VprDLembreteCorpo); CarDTela; AtualizaConsulta; if (VprDLembreteCorpo.CodUsuario = VpaCodUsuario) or (puAdministrador in Varia.PermissoesUsuario) then ShowModal else aviso('PERMISSÃO INVÁLIDA!!!'#13'Somente o dono deste lembrete ou administradores podem verificar suas leituras.'); end; {******************************************************************************} procedure TFVerificaLeituraLembrete.CarDTela; begin ETitulo.Text:= VprDLembreteCorpo.DesTitulo; end; {******************************************************************************} procedure TFVerificaLeituraLembrete.AtualizaConsulta; begin LEMBRETEITEMLIDOS.Close; LEMBRETEITEMLIDOS.SQL.Clear; LEMBRETEITEMLIDOS.SQL.Add('SELECT USU.C_NOM_USU'+ ' FROM CADUSUARIOS USU, LEMBRETEITEM LBI'+ ' WHERE USU.I_COD_USU = LBI.CODUSUARIO'+ ' AND USU.I_EMP_FIL = '+IntToStr(Varia.CodigoEmpFil)+ ' AND LBI.SEQLEMBRETE = '+IntToStr(VprDLembreteCorpo.SeqLembrete)+ ' ORDER BY USU.C_NOM_USU'); LEMBRETEITEMLIDOS.Open; LEMBRETEITEMNAOLIDOS.Close; LEMBRETEITEMNAOLIDOS.SQL.Clear; LEMBRETEITEMNAOLIDOS.SQL.Add('SELECT USU.C_NOM_USU'+ ' FROM CADUSUARIOS USU, LEMBRETECORPO LBC'+ ' WHERE'+ ' USU.I_EMP_FIL = '+IntToStr(Varia.CodigoEmpFil)+ ' AND USU.C_USU_ATI = ''S'''+ ' AND LBC.SEQLEMBRETE = '+IntToStr(VprDLembreteCorpo.SeqLembrete)+ // não estejam lidos ' AND NOT EXISTS (SELECT *'+ ' FROM LEMBRETEITEM LBI'+ ' WHERE LBI.CODUSUARIO = USU.I_COD_USU'+ ' AND LBI.SEQLEMBRETE = LBC.SEQLEMBRETE)'+ // pegar todos ou aqueles que estao gravados ' AND (LBC.INDTODOS = ''S'''+ ' OR EXISTS (SELECT *'+ ' FROM LEMBRETEUSUARIO LBU'+ ' WHERE LBU.CODUSUARIO = USU.I_COD_USU'+ ' AND LBU.SEQLEMBRETE = LBC.SEQLEMBRETE))'+ 'ORDER BY USU.C_NOM_USU'); LEMBRETEITEMNAOLIDOS.Open; end; {******************************************************************************} procedure TFVerificaLeituraLembrete.BFecharClick(Sender: TObject); begin Close; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFVerificaLeituraLembrete]); end.
unit FF7Types; interface Type TFF7BgSprite = packed record ZZ1,X,Y: Smallint; ZZ2: Array[0..1] of Smallint; SrcX,SrcY: Smallint; ZZ3: Array[0..3] of Smallint; Pal: Smallint; Flags: Word; ZZ4: Array[0..2] of Smallint; Page,Sfx: Smallint; NA: Longint; ZZ5: Smallint; OffX,OffY: Longint; ZZ6: Smallint; end; PFF7BgSprite = ^TFF7BGSPRITE; TFF7TextType = (ff7Misc, ff7MiscSpeech, ff7NameSpeech); TFF7TextItem = record TextType: TFF7TextType; Name: ShortString; Text: AnsiString; Changed: Boolean; end; PFF7TextItem = ^TFF7TextItem; TFF7Color = Array[0..3] of Byte; PInt = ^Integer; PWord = ^Word; PSmall = ^Smallint; PByte = ^Byte; TFF7Name = Array[0..7] of Char; Const AKAO_CODE = $4F414B41; DEF_PALETTE_CODE = $01E00000; NA = $D0; FIELD_TERMINATOR: Array[0..16] of Char = ( 'E', 'N', 'D', 'F', 'I', 'N', 'A', 'L',' ', 'F', 'A', 'N', 'T', 'A', 'S', 'Y', '7' ); FF7Ch: Array[Byte] of Byte = ( {0 1 2 3 4 5 6 7 8 9 A B C D E F} $FF, NA, NA, NA, NA, NA, NA, NA, NA,$E1,$E7, NA, NA,$E8, NA, NA, {0} NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, {1} $00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0A,$0B,$0C,$0D,$0E,$0F, {2} $10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$1A,$1B,$1C,$1D,$1E,$1F, {3} $20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2A,$2B,$2C,$2D,$2E,$2F, {4} $30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3A,$3B,$3C,$3D,$3E,$3F, {5} $40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4A,$4B,$4C,$4D,$4E,$4F, {6} $50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5A,$5B,$5C,$5D,$5E, NA, {7} NA, NA,$C2,$A4,$C3,$A9, NA,$D6, NA,$C4, NA,$BC,$AE, NA, NA, NA, {8} NA,$B4,$B5,$B2,$B3,$C0,$B0,$B1,$8C,$8A, NA,$BD,$AF, NA, NA,$B9, {9} $AA,$A1,$82,$83,$BB,$94, NA, NA, NA,$89,$9B,$A7,$A2, NA,$88, NA, {A} $81,$91, NA, NA,$8B,$95,$86,$C1, NA, NA,$9C,$A8, NA, NA, NA,$A0, {B} $AB,$61,$C5,$AC,$60, NA,$8E,$62,$C9,$63,$C6,$C8,$CD,$CA,$CB,$CC, {C} NA,$64,$D1,$CE,$CF,$AD,$65, NA,$8F, NA,$84,$85,$66, NA, NA,$87, {D} $68,$67,$69,$6B,$6A,$6C,$9E,$6D,$6F,$6E,$70,$71,$73,$72,$74,$75, {E} NA,$76,$78,$77,$79,$7B,$7A,$B6,$9F,$7D,$7C,$7E,$7F, NA, NA,$B8 {F} ); implementation end.
unit fBandMapRig1VfoA; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, jakozememo,lclproc, Math, fCommonLocal; type TBandMapClick = procedure(Sender:TObject;Call,Mode : String; Freq : Currency) of object; const MAX_ITEMS = 200; DELTA_FREQ = 0.3; //freq (kHz) tolerance between radio freq and freq in bandmap CURRENT_STATION_CHAR = '|'; //this character will be placed before the bandmap item when the radio freq is close enough ITEM_SEP = '|'; //separator used with bandmap items stored in a file type TBandMapItem = record Freq : Double; Call : String[30]; Mode : String[10]; Band : String[10]; SplitInfo : String[20]; Lat : Double; Long : Double; Color : LongInt; BgColor : LongInt; TimeStamp : TDateTime; Flag : String[1]; TextValue : String[80]; FrmNewQSO : Boolean; Position : Word; end; type TBandMapThread = class(TThread) protected function IncColor(AColor: TColor; AQuantity: Byte) : TColor; procedure Execute; override; end; type { TfrmBandMapRig1VfoA } TfrmBandMapRig1VfoA = class(TfrmCommonLocal) Panel1: TPanel; pnlBandMap: TPanel; procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private BandMap : TJakoMemo; BandMapItemsCount : Word; BandMapCrit : TRTLCriticalSection; RunXplanetExport : Integer; FFirstInterval : Word; FSecondInterval : Word; FDeleteAfter : Word; FBandFilter : String; FModeFilter : String; FCurrentFreq : Currency; FCurrentMode : String; FCurrentBand : String; FBandMapClick : TBandMapClick; FOnlyCurrMode : Boolean; FOnlyCurrBand : Boolean; FxplanetFile : String; FxplanetExport : Boolean; NewAdded : Boolean; procedure SortBandMapArray(l,r : Integer); procedure BandMapDbClick(where:longint;mb:TmouseButton;ms:TShiftState); procedure EmitBandMapClick(Sender:TObject;Call,Mode : String; Freq : Currency); procedure ClearAll; procedure xplanetExport; procedure DeleteFromArray(index : Integer); function FindFirstEmptyPos : Word; function FormatItem(freq : Double; Call, SplitInfo : String; fromNewQSO : Boolean) : String; function SetSizeLeft(Value : String;Len : Integer) : String; function GetIndexFromPosition(ItemPos : Word) : Integer; function ItemExists(call,band,mode: String) : Integer; public BandMapItems : Array [1..MAX_ITEMS] of TBandMapItem; BandMapThread : TBandMapThread; //after XX seconds items get older property FirstInterval : Word write FFirstInterval; property SecondInterval : Word Write FSecondInterval; property DeleteAfter : Word write FDeleteAfter; property BandFilter : String write FBandFilter; property ModeFilter : String write FModeFilter; property CurrentFreq : Currency write FCurrentFreq; property CurrentBand : String write FCurrentBand; property CurrentMode : String write FCurrentMode; property OnlyCurrMode : Boolean write FOnlyCurrMode; property OnlyCurrBand : Boolean write FOnlyCurrBand; property xplanetFile : String write FxplanetFile; property DoXplanetExport: Boolean write FxplanetExport; property OnBandMapClick : TBandMapClick read FBandMapClick write FBandMapClick; //Freq in kHz procedure AddToBandMap(Freq : Double; Call, Mode, Band, SplitInfo : String; Lat,Long : Double; ItemColor, BgColor : LongInt; fromNewQSO : Boolean=False); procedure DeleteFromBandMap(call, mode, band : String); procedure SyncBandMap; procedure LoadFonts; procedure SaveBandMapItemsToFile(FileName : String); procedure LoadBandMapItemsFromFile(FileName : String); end; var frmBandMapRig1VfoA: TfrmBandMapRig1VfoA; implementation uses dUtils, uCfgStorage, dData; { TfrmBandMapRig1VfoA } procedure TfrmBandMapRig1VfoA.AddToBandMap(Freq : Double; Call, Mode, Band, SplitInfo : String; Lat,Long : Double; ItemColor, BgColor : LongInt; fromNewQSO : Boolean=False); var i : Integer; p : Integer; begin EnterCriticalSection(BandMapCrit); try dmUtils.DebugMsg('Search for: '+call+','+band+','+mode); p := ItemExists(call,band,mode); if p>0 then begin dmUtils.DebugMsg('Deleted data on position:'+IntToStr(p)); dmUtils.DebugMsg('BandMapItems[p].Freq:'+CurrToStr(BandMapItems[p].Freq)); dmUtils.DebugMsg('BandMapItems[p].Call:'+BandMapItems[p].Call); dmUtils.DebugMsg('BandMapItems[p].Band:'+BandMapItems[p].Band); dmUtils.DebugMsg('BandMapItems[p].Mode:'+BandMapItems[p].Mode); DeleteFromArray(p) end; i := FindFirstemptyPos; if (i=0) then begin Writeln('CRITICAL ERROR: BANDMAP IS FULL'); exit end; BandMapItems[i].frmNewQSO := fromNewQSO; BandMapItems[i].Freq := Freq+Random(100)*0.000000001; BandMapItems[i].Call := Call; BandMapItems[i].Mode := Mode; BandMapItems[i].Band := Band; BandMapItems[i].SplitInfo := SplitInfo; BandMapItems[i].Lat := Lat; BandMapItems[i].Long := Long; BandMapItems[i].Color := ItemColor; BandMapItems[i].BgColor := BgColor; BandMapItems[i].TimeStamp := now; BandMapItems[i].TextValue := FormatItem(Freq, Call, SplitInfo,fromNewQSO); BandMapItems[i].Position := i; dmUtils.DebugMsg('Added to position:'+IntToStr(i)); frmBandMapRig1VfoA.NewAdded := True finally LeaveCriticalSection(BandMapCrit) end end; function TfrmBandMapRig1VfoA.ItemExists(call,band,mode: String) : Integer; var i : Integer; begin Result := 0; for i:=1 to MAX_ITEMS do begin if (BandMapItems[i].call=call) and (BandMapItems[i].band=band) and (BandMapItems[i].mode=mode) then begin Result := i; Break end end end; procedure TfrmBandMapRig1VfoA.DeleteFromBandMap(call, mode, band : String); var i : integer; begin EnterCriticalSection(BandMapCrit); try for i:=1 to MAX_ITEMS do begin if (BandMapItems[i].Call=call) and (BandMapItems[i].Band=band) and (BandMapItems[i].Mode=mode) then DeleteFromArray(i) end; NewAdded := True finally LeaveCriticalSection(BandMapCrit) end end; procedure TfrmBandMapRig1VfoA.ClearAll; begin BandMap.smaz_vse end; function TfrmBandMapRig1VfoA.FormatItem(freq : Double; Call, SplitInfo : String; fromNewQSO : Boolean) : String; begin if fromNewQSO then call := '*'+call; Result := SetSizeLeft(FloatToStrF(freq,ffFixed,8,3),8)+SetSizeLeft(call,10)+' '+ SplitInfo end; procedure TfrmBandMapRig1VfoA.DeleteFromArray(index : Integer); begin EnterCriticalSection(BandMapCrit); try BandMapItems[index].Freq := 0; BandMapItems[index].Call := ''; BandMapItems[index].Mode := ''; BandMapItems[index].Band := ''; BandMapItems[index].Flag := '' finally LeaveCriticalSection(BandMapCrit) end end; procedure TfrmBandMapRig1VfoA.SyncBandMap; var i : Integer; s : String; begin if Active then exit; //do not refresh the window when is activated (user is scrolling) FBandFilter := UpperCase(FBandFilter); FModeFilter := UpperCase(FModeFilter); BandMap.zakaz_kresleni(True); ClearAll; try for i:=1 to MAX_ITEMS do begin if (BandMapItems[i].Freq = 0) then Continue; if (FOnlyCurrBand) and (FCurrentBand<>'') then begin if BandMapItems[i].Band<>FCurrentBand then Continue end; if (FOnlyCurrMode) and (FCurrentMode<>'') then begin if BandMapItems[i].Mode<>FCurrentMode then Continue end; if abs(FCurrentFreq-BandMapItems[i].Freq)<=DELTA_FREQ then s := CURRENT_STATION_CHAR + BandMapItems[i].TextValue else s := ' ' + BandMapItems[i].TextValue; BandMap.pridej_vetu(s,BandMapItems[i].Color,BandMapItems[i].BgColor,BandMapItems[i].Position) end; if RunXplanetExport > 10 then //data for xplanet couln't be exported on every bandmap reload begin if FxplanetExport then //data from band map to xplanet xplanetExport; RunXplanetExport := 0 end; inc(RunXplanetExport) finally BandMap.zakaz_kresleni(False) end end; procedure TfrmBandMapRig1VfoA.EmitBandMapClick(Sender:TObject;Call,Mode : String; Freq : Currency); begin if Assigned(FBandMapClick) then FBandMapClick(Self,Call,Mode,Freq) end; procedure TfrmBandMapRig1VfoA.BandMapDbClick(where:longint;mb:TmouseButton;ms:TShiftState); var i : Integer=0; begin if (where>=0) and (where <= MAX_ITEMS-1) then begin i := GetIndexFromPosition(where); if i=0 then exit; EmitBandMapClick(Self,BandMapItems[i].Call,BandMapItems[i].Mode,BandMapItems[i].Freq) end end; procedure TfrmBandMapRig1VfoA.SortBandMapArray(l,r : integer); var i,j : Integer; w : TbandMapItem; x : Double; begin i:=l; j:=r; x:=BandMapItems[(l+r) div 2].Freq; repeat while BandMapItems[i].Freq < x do i:=i+1; while x < BandMapItems[j].Freq do j:=j-1; if i <= j then begin w := BandMapItems[i]; BandMapItems[i] := BandMapItems[j]; BandMapItems[j] := w; i:=i+1; j:=j-1 end until i > j; if l < j then SortBandMapArray(l,j); if i < r then SortBandMapArray(i,r) end; function TfrmBandMapRig1VfoA.GetIndexFromPosition(ItemPos : Word) : Integer; var i : Integer; s : String; c : TColor; begin if BandMap.cti_vetu(s,c,c,i,ItemPos) then begin s := copy(s,2,Length(s)-1); dmUtils.DebugMsg('GetIndexFromPosition, looking for:'+s); for i:=1 to MAX_ITEMS do begin if BandMapItems[i].TextValue=s then begin Result := i; break end end end else Result := 0 end; function TfrmBandMapRig1VfoA.FindFirstEmptyPos : Word; var i : Integer; begin Result := 0; for i:=MAX_ITEMS downto 1 do begin if BandMapItems[i].Freq = 0 then begin Result := i; Break end end end; procedure TBandMapThread.Execute; var i : Integer; Changed : Boolean = False; When : TDateTime; begin while not Terminated do begin try When := now; EnterCriticalSection(frmBandMapRig1VfoA.BandMapCrit); for i:=1 to MAX_ITEMS do begin if frmBandMapRig1VfoA.BandMapItems[i].Freq = 0 then Continue; sleep(0); if When>(frmBandMapRig1VfoA.BandMapItems[i].TimeStamp + (frmBandMapRig1VfoA.FDeleteAfter/86400)) then begin frmBandMapRig1VfoA.DeleteFromArray(i); Changed := True end else if (When>(frmBandMapRig1VfoA.BandMapItems[i].TimeStamp + (frmBandMapRig1VfoA.FSecondInterval/86400))) and (frmBandMapRig1VfoA.BandMapItems[i].Flag='S') then begin frmBandMapRig1VfoA.BandMapItems[i].Color := IncColor(frmBandMapRig1VfoA.BandMapItems[i].Color,40); frmBandMapRig1VfoA.BandMapItems[i].Flag := 'X'; Changed := True end else if (When>(frmBandMapRig1VfoA.BandMapItems[i].TimeStamp + (frmBandMapRig1VfoA.FFirstInterval/86400))) and (frmBandMapRig1VfoA.BandMapItems[i].Flag='') then begin frmBandMapRig1VfoA.BandMapItems[i].Color := IncColor(frmBandMapRig1VfoA.BandMapItems[i].Color,60); frmBandMapRig1VfoA.BandMapItems[i].Flag := 'S'; Changed := True end end; if frmBandMapRig1VfoA.NewAdded then begin frmBandMapRig1VfoA.SortBandMapArray(1,MAX_ITEMS); frmBandMapRig1VfoA.NewAdded := False; Changed := True end finally LeaveCriticalSection(frmBandMapRig1VfoA.BandMapCrit) end; if Changed then begin Synchronize(@frmBandMapRig1VfoA.SyncBandMap); Changed := False end; Sleep(700) end end; function TBandMapThread.IncColor(AColor: TColor; AQuantity: Byte) : TColor; var R, G, B : Byte; begin RedGreenBlue(ColorToRGB(AColor), R, G, B); R := Max(0, Integer(R) + AQuantity); G := Max(0, Integer(G) + AQuantity); B := Max(0, Integer(B) + AQuantity); Result := RGBToColor(R, G, B); end; function TfrmBandMapRig1VfoA.SetSizeLeft(Value : String;Len : Integer) : String; var i : Integer; begin Result := Value; for i:=Length(Value) to Len-1 do Result := ' ' + Result end; procedure TfrmBandMapRig1VfoA.FormCreate(Sender: TObject); var i : Integer; begin inherited; InitCriticalSection(BandMapCrit); RunXplanetExport := 1; BandMap := Tjakomemo.Create(pnlBandMap); BandMap.parent := pnlBandMap; BandMap.autoscroll := True; BandMap.Align := alClient; BandMap.oncdblclick := @BandMapDbClick; BandMap.nastav_jazyk(1); for i:=1 to MAX_ITEMS do BandMapItems[i].Freq:=0; BandMapItemsCount := 0; Randomize; ClearAll; NewAdded := False; BandMapThread := TBandMapThread.Create(True); BandMapThread.Resume end; procedure TfrmBandMapRig1VfoA.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin inherited; if iniLocal.ReadBool('BandMap', 'Save', False) then frmBandMapRig1VfoA.SaveBandMapItemsToFile(dmData.AppHomeDir+'bandmap.csv') end; procedure TfrmBandMapRig1VfoA.LoadFonts; var f : TFont; begin f := TFont.Create; try f.Name := iniLocal.ReadString('BandMap','BandFont','Monospace'); f.Size := iniLocal.ReadInteger('BandMap','FontSize',8); BandMap.nastav_font(f) finally f.Free end end; procedure TfrmBandMapRig1VfoA.FormDestroy(Sender: TObject); begin inherited; DoneCriticalsection(BandMapCrit) end; procedure TfrmBandMapRig1VfoA.FormShow(Sender: TObject); begin inherited; LoadFonts end; procedure TfrmBandMapRig1VfoA.SaveBandMapItemsToFile(FileName : String); var f : TextFile; i : Integer; begin AssignFile(f,FileName); try Rewrite(f); for i:=1 to MAX_ITEMS do Writeln(f, BandMapItems[i].frmNewQSO,ITEM_SEP, BandMapItems[i].Freq,ITEM_SEP, BandMapItems[i].Call,ITEM_SEP, BandMapItems[i].Mode,ITEM_SEP, BandMapItems[i].Band,ITEM_SEP, BandMapItems[i].SplitInfo,ITEM_SEP, BandMapItems[i].Lat,ITEM_SEP, BandMapItems[i].Long,ITEM_SEP, BandMapItems[i].Color,ITEM_SEP, BandMapItems[i].BgColor,ITEM_SEP, BandMapItems[i].TimeStamp,ITEM_SEP, BandMapItems[i].TextValue,ITEM_SEP, BandMapItems[i].Position,ITEM_SEP ) finally CloseFile(f) end end; procedure TfrmBandMapRig1VfoA.LoadBandMapItemsFromFile(FileName : String); var f : TextFile; i : Integer=1; a : TExplodeArray; s : String; begin if not FileExists(FileName) then exit; BandMap.zakaz_kresleni(True); AssignFile(f,FileName); EnterCriticalSection(BandMapCrit); try ClearAll; Reset(f); while not Eof(f) do begin ReadLn(f,s); a := dmUtils.Explode(ITEM_SEP,s); if Length(a)<13 then Continue; //probably corrupted line i := StrToInt(a[12]); if (i<=0) or (i>MAX_ITEMS) then Continue; BandMapItems[i].frmNewQSO := StrToBool(a[0]); BandMapItems[i].Freq := StrToFloat(a[1]); BandMapItems[i].Call := a[2]; BandMapItems[i].Mode := a[3]; BandMapItems[i].Band := a[4]; BandMapItems[i].SplitInfo := a[5]; BandMapItems[i].Lat := StrToFloat(a[6]); BandMapItems[i].Long := StrToFloat(a[7]); BandMapItems[i].Color := StrToInt(a[8]); BandMapItems[i].BgColor := StrToInt(a[9]); BandMapItems[i].TimeStamp := StrToFloat(a[10]); BandMapItems[i].TextValue := a[11]; BandMapItems[i].Position := i; NewAdded := True end finally CloseFile(f); BandMap.zakaz_kresleni(False); LeaveCriticalSection(BandMapCrit) end end; procedure TfrmBandMapRig1VfoA.xplanetExport; var i : Integer; s : String; l : TStringList; xColor : String; UseDefaultColor : Boolean; DefaultColor : Integer; MaxXplanetSpots : Integer; begin UseDefaultColor := iniLocal.ReadBool('xplanet','UseDefColor',True); DefaultColor := iniLocal.ReadInteger('xplanet','color',clWhite); MaxXplanetSpots := iniLocal.ReadInteger('xplanet','LastSpots',20); DeleteFile(FxplanetFile); l := TStringList.Create; try for i:=1 to MAX_ITEMS do begin if (BandMapItems[i].Freq = 0) or (MaxXplanetSpots=0) then Continue; if (FOnlyCurrBand) and (FCurrentBand<>'') then begin if BandMapItems[i].Band<>FCurrentBand then Continue end; if (FOnlyCurrMode) and (FCurrentMode<>'') then begin if BandMapItems[i].Mode<>FCurrentMode then Continue end; if UseDefaultColor then xColor := IntToHex(DefaultColor,8) else xColor := IntToHex(BandMapItems[i].Color,8); xColor := '0x'+Copy(xColor,3,Length(xColor)-2); l.Add(CurrToStr(BandMapItems[i].Lat)+' '+CurrToStr(BandMapItems[i].Long)+' "'+BandMapItems[i].Call+ '" color='+xColor); dec(MaxXplanetSpots) end; l.SaveToFile(FxplanetFile) finally FreeAndNil(l) end end; {$R *.lfm} end.
unit gExpressionOperators; { Author: Steve Kramer, goog@goog.com } interface Uses Classes , Contnrs , gExpressionEvaluator , Variants ; Type TOperator = class(TgExpressionToken) Public Function Precedence : Integer;Virtual; Procedure PostFix(ATokenList : TList; AStack : TStack);Override; End; TBinaryOperator = Class(TOperator) Protected Function Operate(Value1, Value2 : Variant) : Variant;Virtual;Abstract; Public Procedure Evaluate(AStack : TgVariantStack);Override; End; TBinaryOperatorP1 = Class(TBinaryOperator) Public Function Precedence : Integer;Override; End; TBinaryOperatorP2 = Class(TBinaryOperator) Public Function Precedence : Integer;Override; End; TBinaryOperatorP3 = Class(TBinaryOperator) Public Function Precedence : Integer;Override; End; TAdd = class(TBinaryOperatorP2) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TLogicalAnd = class(TBinaryOperator) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; public End; TComma = Class(TOperator) Public Function Precedence : Integer;Override; Procedure Evaluate(AStack : TgVariantStack);Override; End; TDash = Class(TgExpressionToken) Public class function CreateToken(AExpressionEvaluator : TgExpressionEvaluator; AInFixTokenList : TObjectList): TgExpressionToken; override; End; TDIV = Class(TBinaryOperatorP3) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TDivide = class(TBinaryOperatorP3) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TEQ = Class(TBinaryOperatorP1) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TGE = Class(TBinaryOperatorP1) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TGT = Class(TBinaryOperatorP1) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TIn = Class(TBinaryOperatorP1) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TLE = Class(TBinaryOperatorP1) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TLParen = class(TOperator) private FParameterCount: Integer; Public Function Precedence : Integer;Override; Procedure PostFix(ATokenList : TList; AStack : TStack);Override; Procedure Evaluate(AStack : TgVariantStack);Override; Property ParameterCount : Integer read FParameterCount; End; TLT = Class(TBinaryOperatorP1) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TMod = Class(TBinaryOperatorP3) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TMultiply = class(TBinaryOperatorP3) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TNE = Class(TBinaryOperatorP1) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TNot = Class(Toperator) Public Function Precedence : Integer;Override; Procedure Evaluate(AStack : TgVariantStack);Override; End; TOr = Class(TBinaryOperator) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TPower = Class(TBinaryOperator) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; Public Function Precedence : Integer;Override; End; TRParen = class(TOperator) Public Procedure PostFix(ATokenList : TList; AStack : TStack);Override; Procedure Evaluate(AStack : TgVariantStack);Override; End; TSubtract = class(TBinaryOperatorP2) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TLike = class(TBinaryOperatorP3) Protected Function Operate(Value1, Value2 : Variant) : Variant;Override; End; TBetween = class(TOperator) public procedure Evaluate(AStack : TgVariantStack); override; function Precedence: Integer; override; end; TAnd = class(TgExpressionToken) public class function CreateToken(AExpressionEvaluator : TgExpressionEvaluator; AInFixTokenList : TObjectList): TgExpressionToken; override; end; TBetweenAnd = class(TOperator) public function Precedence: Integer; override; end; implementation Uses gExpressionLiterals , gExpressionFunctions , Math , StrUtils , SysUtils ; { TOperator } procedure TOperator.PostFix(ATokenList: TList; AStack: TStack); Var Operator : TOperator; begin If AStack.Count = 0 Then AStack.Push(Self) Else Begin Operator := TOperator(AStack.Peek); If Precedence > Operator.Precedence Then AStack.Push(Self) Else Begin Repeat Operator := TOperator(AStack.Pop); ATokenList.Add(Operator); Until (AStack.Count = 0) or (Precedence > TOperator(AStack.Peek).Precedence); AStack.Push(Self); End; End; end; function TOperator.Precedence: Integer; begin Result := 0; end; { TBinaryOperator } Procedure TBinaryOperator.Evaluate(AStack : TgVariantStack); Var Value1, Value2 : Variant; Begin Value2 := AStack.Pop; Value1 := AStack.Pop; AStack.Push(Operate(Value1, Value2)); End; { TBinaryOperatorP1 } function TBinaryOperatorP1.Precedence: Integer; begin Result := 1; end; { TBinaryOperatorP2 } function TBinaryOperatorP2.Precedence: Integer; begin Result := 2; end; { TBinaryOperatorP3 } function TBinaryOperatorP3.Precedence: Integer; begin Result := 3; end; { TAdd } Function TAdd.Operate(Value1, Value2 : Variant) : Variant; var V1: String; V2: String; Begin If VarIsStr( Value1 ) Or VarIsStr( Value2 ) Then Begin V1 := Value1; V2 := Value2; Result := V1 + V2; End Else Result := Value1 + Value2; End; { TLogicalAnd } Function TLogicalAnd.Operate(Value1, Value2 : Variant) : Variant; Var BooleanValue1 : Boolean; BooleanValue2 : Boolean; Begin If VarIsEmpty(Value1) or VarIsEmpty(Value2) Then Result := False Else Begin BooleanValue1 := Value1; BooleanValue2 := Value2; Result := BooleanValue1 And BooleanValue2; End; End; { TComma } procedure TComma.Evaluate(AStack : TgVariantStack); begin end; function TComma.Precedence: Integer; begin Result := -1; end; { TDash } class function TDash.CreateToken(AExpressionEvaluator : TgExpressionEvaluator; AInFixTokenList : TObjectList): TgExpressionToken; Var LastToken : TgExpressionToken; begin If AInFixTokenList.Count > 0 Then LastToken := TgExpressionToken(AInFixTokenList.Last) Else LastToken := Nil; If Assigned(LastToken) And (Not LastToken.InheritsFrom(TOperator) or LastToken.InheritsFrom(TRParen)) Then Result := TSubtract.Create(AExpressionEvaluator) Else Result := TNumber.Create(AExpressionEvaluator); end; { TDIV } function TDIV.Operate(Value1, Value2: Variant): Variant; Var Int1 : Integer; Int2 : Integer; begin Int1 := Value1; Int2 := Value2; Result := Int1 Div Int2; end; { TDivide } Function TDivide.Operate(Value1, Value2 : Variant) : Variant; Begin Result := Value1 / Value2; End; { TEQ } Function TEQ.Operate(Value1, Value2 : Variant) : Variant; Begin If VarIsEmpty(Value1) or VarIsEmpty(Value2) Then Result := False Else Result := Value1 = Value2; End; { TGE } Function TGE.Operate(Value1, Value2 : Variant) : Variant; Begin If VarIsEmpty(Value1) or VarIsEmpty(Value2) Then Result := False Else Result := Value1 >= Value2; End; { TGT } Function TGT.Operate(Value1, Value2 : Variant) : Variant; Begin If VarIsEmpty(Value1) or VarIsEmpty(Value2) Then Result := False Else Result := Value1 > Value2; End; { TLE } Function TLE.Operate(Value1, Value2 : Variant) : Variant; Begin If VarIsEmpty(Value1) or VarIsEmpty(Value2) Then Result := False Else Result := Value1 <= Value2; End; { TLParen } procedure TLParen.PostFix(ATokenList: TList; AStack: TStack); begin AStack.Push(Self); end; Procedure TLParen.Evaluate(AStack : TgVariantStack); Begin End; function TLParen.Precedence: Integer; begin Result := -2; end; { TLT } Function TLT.Operate(Value1, Value2 : Variant) : Variant; Begin If VarIsEmpty(Value1) or VarIsEmpty(Value2) Then Result := False Else Result := Value1 < Value2; End; { TMod } function TMod.Operate(Value1, Value2: Variant): Variant; begin Result := Value1 Mod Value2; end; { TMultiply } Function TMultiply.Operate(Value1, Value2 : Variant) : Variant; Begin Result := Value1 * Value2; End; { TNE } function TNE.Operate(Value1, Value2: Variant): Variant; begin If VarIsEmpty(Value1) or VarIsEmpty(Value2) Then Result := True Else Result := Value1 <> Value2; end; { TNot } Procedure TNot.Evaluate(AStack : TgVariantStack); Var Value : Variant; BooleanValue : Boolean; Begin Value := AStack.Pop; If VarIsEmpty(Value) Then AStack.Push(True) Else Begin BooleanValue := Value; AStack.Push(Not BooleanValue); End; End; function TNot.Precedence: Integer; begin Result := 5; end; { TOr } Function Tor.Operate(Value1, Value2 : Variant) : Variant; Var BooleanValue1 : Boolean; BooleanValue2 : Boolean; Begin If VarIsEmpty(Value1) or VarIsEmpty(Value2) Then Result := False Else Begin BooleanValue1 := Value1; BooleanValue2 := Value2; Result := BooleanValue1 Or BooleanValue2; End; End; { TPower } function TPower.Operate(Value1, Value2: Variant): Variant; begin Result := Power(Value1, Value2); end; function TPower.Precedence: Integer; begin Result := 4; end; { TRParen } procedure TRParen.PostFix(ATokenList: TList; AStack: TStack); Var Token : TgExpressionToken; FunctionToken : TFunction; Counter : Integer; begin Token := TgExpressionToken(AStack.Pop); While Not Token.InheritsFrom(TLParen) Do Begin ATokenList.Add(Token); Token := TgExpressionToken(AStack.Pop); End; If (AStack.Count > 0) And TgExpressionToken(AStack.Peek).InheritsFrom(TFunction) Then Begin FunctionToken := TFunction(AStack.Pop); Counter := ATokenList.Add(FunctionToken) - 1; Repeat Token := TgExpressionToken(ATokenList[Counter]); If Token.InheritsFrom(TComma) Then FunctionToken.ParameterCount := FunctionToken.ParameterCount + 1; Dec(Counter); Until (Counter = -1) Or Token.InheritsFrom(TFunction); FunctionToken.ParameterCount := FunctionToken.ParameterCount + 1; End; end; Procedure TRParen.Evaluate(AStack : TgVariantStack); Begin End; { TSubtract } Function TSubtract.Operate(Value1, Value2 : Variant) : Variant; Begin Result := Value1 - Value2; End; { TIn } function TIn.Operate(Value1, Value2: Variant): Variant; begin Result := Pos(Value1, Value2) > 0; end; { TLike } function TLike.Operate(Value1, Value2 : Variant): Variant; var SearchString: String; Begin SearchString := Value2; If SearchString[Length( SearchString )] = '%' Then Begin SearchString := Copy( SearchString, 1, Length( SearchString ) - 1 ); If SearchString[1] = '%' Then Begin SearchString := Copy( SearchString, 2, MaxInt ); Result := ContainsText( Value1, SearchString ) End Else Result := StartsText( SearchString, Value1 ) End Else if SearchString[1] = '%' then Begin SearchString := Copy(SearchString, 2, MaxInt); Result := EndsText(SearchString, Value1); End Else Result := SameText(Value1, Value2); End; { TBinaryOperator } procedure TBetween.Evaluate(AStack : TgVariantStack); var MaxValue: Variant; MinValue: Variant; TestValue: Variant; Result : Boolean; begin MaxValue := AStack.Pop; MinValue := AStack.Pop; TestValue := AStack.Pop; Result := TestValue >= MinValue; If Result Then Result := TestValue <= MaxValue; AStack.Push(Result); end; { TBinaryOperatorP1 } function TBetween.Precedence: Integer; begin Result := 2; end; class function TAnd.CreateToken(AExpressionEvaluator : TgExpressionEvaluator; AInFixTokenList : TObjectList): TgExpressionToken; Var TestToken : TgExpressionToken; begin If AInFixTokenList.Count > 1 Then TestToken := TgExpressionToken(AInFixTokenList[AInFixTokenList.Count - 2]) Else TestToken := Nil; If Assigned(TestToken) And TestToken.InheritsFrom(TBetween) Then Result := TBetweenAnd.Create(AExpressionEvaluator) Else Result := TLogicalAnd.Create(AExpressionEvaluator); end; { TBinaryOperatorP1 } function TBetweenAnd.Precedence: Integer; begin Result := 3; end; Initialization TAdd.Register('+'); TAnd.Register('And'); TComma.Register(','); TDash.Register('-'); TDiv.Register('Div'); TDivide.Register('/'); TEQ.Register('='); TGE.Register('>='); TGT.Register('>'); TIn.Register('In'); TLE.Register('<='); TLike.Register('Like'); TLParen.Register('('); TLT.Register('<'); TMod.Register('Mod'); TMultiply.Register('*'); TNE.Register('<>'); TNot.Register('Not'); TOr.Register('Or'); TPower.Register('^'); TRParen.Register(')'); TBetween.Register('Between'); end.
unit CategoryParametersQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap, OrderQuery; type TCategoryParamsW = class(TDSWrap) private FIsAttribute: TFieldWrap; FID: TFieldWrap; FOrd: TFieldWrap; FIsEnabled: TFieldWrap; FParamSubParamID: TFieldWrap; FPosID: TFieldWrap; FProductCategoryID: TFieldWrap; public constructor Create(AOwner: TComponent); override; property IsAttribute: TFieldWrap read FIsAttribute; property ID: TFieldWrap read FID; property Ord: TFieldWrap read FOrd; property IsEnabled: TFieldWrap read FIsEnabled; property ParamSubParamID: TFieldWrap read FParamSubParamID; property PosID: TFieldWrap read FPosID; property ProductCategoryID: TFieldWrap read FProductCategoryID; end; TQueryCategoryParams = class(TQueryBase) private FW: TCategoryParamsW; { Private declarations } public constructor Create(AOwner: TComponent); override; procedure AppendOrEdit(AProductCategoryID, AParamSubParamID, AOrd: Integer); function SearchBy(AProductCategoryID, AParamSubParamID: Integer) : Integer; overload; property W: TCategoryParamsW read FW; { Public declarations } end; implementation uses StrHelper; {$R *.dfm} constructor TQueryCategoryParams.Create(AOwner: TComponent); begin inherited; FW := TCategoryParamsW.Create(FDQuery); end; procedure TQueryCategoryParams.AppendOrEdit(AProductCategoryID, AParamSubParamID, AOrd: Integer); begin if SearchBy(AProductCategoryID, AParamSubParamID) <> 0 then W.TryEdit else begin W.TryAppend; W.ProductCategoryID.F.AsInteger := AProductCategoryID; W.ParamSubParamID.F.AsInteger := AParamSubParamID; W.IsEnabled.F.AsInteger := 1; W.PosID.F.AsInteger := 1; // В середину end; // если хотим изменить порядок if (AOrd > 0) and (W.Ord.F.AsInteger = 0) then W.Ord.F.AsInteger := AOrd; // Обязательно делаем параметр видимым W.IsAttribute.F.Value := 1; W.TryPost; end; function TQueryCategoryParams.SearchBy(AProductCategoryID, AParamSubParamID : Integer): Integer; begin Assert(AProductCategoryID > 0); Assert(AParamSubParamID > 0); // Ищем Result := SearchEx([TParamRec.Create(W.ProductCategoryID.FullName, AProductCategoryID), TParamRec.Create(W.ParamSubParamID.FullName, AParamSubParamID)]); end; constructor TCategoryParamsW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FOrd := TFieldWrap.Create(Self, 'Ord'); FIsAttribute := TFieldWrap.Create(Self, 'IsAttribute'); FIsEnabled := TFieldWrap.Create(Self, 'IsEnabled'); FParamSubParamID := TFieldWrap.Create(Self, 'ParamSubParamID'); FPosID := TFieldWrap.Create(Self, 'PosID'); FProductCategoryID := TFieldWrap.Create(Self, 'ProductCategoryID'); end; end.
unit Vigilante.Build.Model; interface uses Vigilante.Aplicacao.ModelBase, Vigilante.Aplicacao.SituacaoBuild, Module.ValueObject.URL; type IBuildModel = interface(IVigilanteModelBase) ['{A6BB46A1-78C3-4069-940E-F48071895246}'] function GetBuildAtual: integer; function GetUltimoBuildSucesso: integer; function GetUltimoBuildFalha: integer; function GetURLUltimoBuild: IURL; function Equals(const BuildModel: IBuildModel): boolean; property BuildAtual: integer read GetBuildAtual; property UltimoBuildSucesso: integer read GetUltimoBuildSucesso; property UltimoBuildFalha: integer read GetUltimoBuildFalha; property URLUltimoBuild: IURL read GetURLUltimoBuild; end; implementation end.
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium E-Mail: mshkolnik@scalabium.com mshkolnik@yahoo.com WEB: http://www.scalabium.com The TSMTrayIcon component } unit SMTray; {$P+,W-,R-} interface {$I SMVersion.inc} uses Windows, Messages, Classes, Graphics, SysUtils, Forms, Controls, Menus, ShellAPI{, IcoList}; type TMouseButtons = set of TMouseButton; { TSMTrayIcon } {$IFDEF SM_ADD_ComponentPlatformsAttribute} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TSMTrayIcon = class(TComponent) private FHandle: HWnd; FActive: Boolean; FAdded: Boolean; FAnimated: Boolean; FClicked: TMouseButtons; FIconIndex: Integer; FInterval: Word; FIconData: TNotifyIconData; FCurIcon: TIcon; FIcon: TIcon; FIconList: TImageList; FTimer: TThread; FDestroying: Boolean; FHint: string; FShowDesign: Boolean; FPopupMenu: TPopupMenu; FOnClick: TMouseEvent; FOnDblClick: TNotifyEvent; FOnMouseMove: TMouseMoveEvent; FOnMouseDown: TMouseEvent; FOnMouseUp: TMouseEvent; procedure ChangeIcon; procedure Timer; procedure SendCancelMode; procedure SwitchToWindow(Wnd: HWnd; Restore: Boolean); function CheckMenuPopup(X, Y: Integer): Boolean; function CheckDefaultMenuItem: Boolean; procedure SetHint(const Value: string); procedure SetIcon(Value: TIcon); procedure SetIconList(Value: TImageList); procedure SetPopupMenu(Value: TPopupMenu); procedure Activate; procedure Deactivate; procedure SetActive(Value: Boolean); function GetAnimated: Boolean; procedure SetAnimated(Value: Boolean); procedure SetShowDesign(Value: Boolean); procedure SetInterval(Value: Word); procedure IconChanged(Sender: TObject); procedure WndProc(var Message: TMessage); function GetActiveIcon: TIcon; protected procedure DblClick; dynamic; procedure DoClick(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); dynamic; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); dynamic; procedure MouseMove(Shift: TShiftState; X, Y: Integer); dynamic; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); dynamic; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure UpdateNotifyData; virtual; property Handle: HWnd read FHandle; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Hide; procedure Show; published property Active: Boolean read FActive write SetActive default True; property Hint: string read FHint write SetHint; property Icon: TIcon read FIcon write SetIcon; property Icons: TImageList read FIconList write SetIconList; { Ensure Icons is declared before Animated } property Animated: Boolean read GetAnimated write SetAnimated default False; property Interval: Word read FInterval write SetInterval default 150; property PopupMenu: TPopupMenu read FPopupMenu write SetPopupMenu; property ShowDesign: Boolean read FShowDesign write SetShowDesign stored False; property OnClick: TMouseEvent read FOnClick write FOnClick; property OnDblClick: TNotifyEvent read FOnDblClick write FOnDblClick; property OnMouseMove: TMouseMoveEvent read FOnMouseMove write FOnMouseMove; property OnMouseDown: TMouseEvent read FOnMouseDown write FOnMouseDown; property OnMouseUp: TMouseEvent read FOnMouseUp write FOnMouseUp; end; procedure Register; implementation procedure Register; begin RegisterComponents('SMComponents', [TSMTrayIcon]); end; const CM_TRAYICON = CM_BASE + 100; { TTimerThread } type TTimerThread = class(TThread) private FOwnerTray: TSMTrayIcon; protected procedure Execute; override; public constructor Create(TrayIcon: TSMTrayIcon; CreateSuspended: Boolean); end; constructor TTimerThread.Create(TrayIcon: TSMTrayIcon; CreateSuspended: Boolean); begin FOwnerTray := TrayIcon; inherited Create(CreateSuspended); FreeOnTerminate := True; end; procedure TTimerThread.Execute; function ThreadClosed: Boolean; begin Result := Terminated or Application.Terminated or (FOwnerTray = nil); end; begin while not Terminated do begin if not ThreadClosed then if SleepEx(FOwnerTray.FInterval, False) = 0 then if not ThreadClosed and FOwnerTray.Animated then FOwnerTray.Timer; end; end; { TSMTrayIcon } constructor TSMTrayIcon.Create(AOwner: Tcomponent); begin inherited Create(AOwner); FHandle := AllocateHWnd(WndProc); FCurIcon := TIcon.Create; FIcon := TIcon.Create; FIcon.OnChange := IconChanged; FIconList := TImageList.Create(nil); FIconList.OnChange := IconChanged; FIconIndex := -1; FInterval := 150; FActive := True; end; destructor TSMTrayIcon.Destroy; begin FDestroying := True; FIconList.OnChange := nil; FIcon.OnChange := nil; SetAnimated(False); Deactivate; DeallocateHWnd(FHandle); FIcon.Free; FIcon := nil; FIconList.Free; FIconList := nil; FCurIcon.Free; FCurIcon := nil; inherited Destroy; end; procedure TSMTrayIcon.Loaded; begin inherited Loaded; if FActive and not (csDesigning in ComponentState) then Activate; end; procedure TSMTrayIcon.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = PopupMenu) and (Operation = opRemove) then PopupMenu := nil; end; procedure TSMTrayIcon.SetPopupMenu(Value: TPopupMenu); begin FPopupMenu := Value; if Value <> nil then Value.FreeNotification(Self); end; procedure TSMTrayIcon.SendCancelMode; var F: TForm; begin if not ((csDestroying in ComponentState) or FDestroying) then begin F := Screen.ActiveForm; if F = nil then F := Application.MainForm; if F <> nil then F.SendCancelMode(nil); end; end; procedure TSMTrayIcon.SwitchToWindow(Wnd: HWnd; Restore: Boolean); begin if IsWindowEnabled(Wnd) then begin SetForegroundWindow(Wnd); if Restore and IsWindowVisible(Wnd) then begin if not IsZoomed(Wnd) then SendMessage(Wnd, WM_SYSCOMMAND, SC_RESTORE, 0); SetFocus(Wnd); end; end; end; function TSMTrayIcon.CheckMenuPopup(X, Y: Integer): Boolean; begin Result := False; if not (csDesigning in ComponentState) and Active and (PopupMenu <> nil) and PopupMenu.AutoPopup then begin PopupMenu.PopupComponent := Self; SendCancelMode; SwitchToWindow(FHandle, False); Application.ProcessMessages; try PopupMenu.Popup(X, Y); finally SwitchToWindow(FHandle, False); end; Result := True; end; end; function TSMTrayIcon.CheckDefaultMenuItem: Boolean; var Item: TMenuItem; i: Integer; begin Result := False; if not (csDesigning in ComponentState) and Active and (PopupMenu <> nil) and (PopupMenu.Items <> nil) then begin i := 0; while (i < PopupMenu.Items.Count) do begin Item := PopupMenu.Items[i]; if Item.Default and Item.Enabled then begin Item.Click; Result := True; Break; end; Inc(i); end; end; end; procedure TSMTrayIcon.SetIcon(Value: TIcon); begin FIcon.Assign(Value); end; procedure TSMTrayIcon.SetIconList(Value: TImageList); begin FIconList.Assign(Value); end; function TSMTrayIcon.GetActiveIcon: TIcon; var i: Integer; begin Result := FIcon; if (FIconList <> nil) and (FIconList.Count > 0) and Animated then begin if (FIconIndex < FIconList.Count) then i := FIconIndex else i := FIconList.Count-1; if (i < 0) then i := 0; FIconList.GetIcon(i, FCurIcon); Result := FCurIcon; end; end; function TSMTrayIcon.GetAnimated: Boolean; begin Result := FAnimated; end; procedure TSMTrayIcon.SetAnimated(Value: Boolean); begin Value := Value and Assigned(FIconList) and (FIconList.Count > 0); if Value <> Animated then begin if Value then begin FTimer := TTimerThread.Create(Self, not FAdded); FAnimated := True; end else begin FAnimated := False; TTimerThread(FTimer).FOwnerTray := nil; while FTimer.Suspended do FTimer.Resume; FTimer.Terminate; end; FIconIndex := 0; ChangeIcon; end; end; procedure TSMTrayIcon.SetActive(Value: Boolean); begin if (Value <> FActive) then begin FActive := Value; if not (csDesigning in ComponentState) then if Value then Activate else Deactivate; end; end; procedure TSMTrayIcon.Show; begin Active := True; end; procedure TSMTrayIcon.Hide; begin Active := False; end; procedure TSMTrayIcon.SetShowDesign(Value: Boolean); begin if (csDesigning in ComponentState) then begin if Value then Activate else Deactivate; FShowDesign := FAdded; end; end; procedure TSMTrayIcon.SetInterval(Value: Word); begin if FInterval <> Value then FInterval := Value; end; procedure TSMTrayIcon.Timer; begin if not (csDestroying in ComponentState) and Animated then begin Inc(FIconIndex); if (FIconList = nil) or (FIconIndex >= FIconList.Count) then FIconIndex := 0; ChangeIcon; end; end; procedure TSMTrayIcon.IconChanged(Sender: TObject); begin ChangeIcon; end; procedure TSMTrayIcon.SetHint(const Value: string); begin if FHint <> Value then begin FHint := Value; ChangeIcon; end; end; procedure TSMTrayIcon.UpdateNotifyData; var Ico: TIcon; begin with FIconData do begin cbSize := System.SizeOf(TNotifyIconData); Wnd := FHandle; uFlags := NIF_MESSAGE or NIF_ICON or NIF_TIP; Ico := GetActiveIcon; if Ico <> nil then hIcon := Ico.Handle else hIcon := INVALID_HANDLE_VALUE; StrPLCopy(szTip, GetShortHint(FHint), System.SizeOf(szTip) - 1); uCallbackMessage := CM_TRAYICON; uID := 0; end; end; procedure TSMTrayIcon.Activate; var Ico: TIcon; begin Deactivate; Ico := GetActiveIcon; if (Ico <> nil) and not Ico.Empty then begin FClicked := []; UpdateNotifyData; FAdded := Shell_NotifyIcon(NIM_ADD, @FIconData); if (GetShortHint(FHint) = '') and FAdded then Shell_NotifyIcon(NIM_MODIFY, @FIconData); if Animated then while FTimer.Suspended do FTimer.Resume; end; end; procedure TSMTrayIcon.Deactivate; begin Shell_NotifyIcon(NIM_DELETE, @FIconData); FAdded := False; FClicked := []; if Animated and not FTimer.Suspended then FTimer.Suspend; end; procedure TSMTrayIcon.ChangeIcon; var Ico: TIcon; begin if (FIconList = nil) or (FIconList.Count = 0) then SetAnimated(False); if FAdded then begin Ico := GetActiveIcon; if (Ico <> nil) and not Ico.Empty then begin UpdateNotifyData; Shell_NotifyIcon(NIM_MODIFY, @FIconData); end else Deactivate; end else begin if ((csDesigning in ComponentState) and FShowDesign) or (not (csDesigning in ComponentState) and FActive) then Activate; end; end; procedure TSMTrayIcon.MouseMove(Shift: TShiftState; X, Y: Integer); begin if Assigned(FOnMouseMove) then FOnMouseMove(Self, Shift, X, Y); end; procedure TSMTrayIcon.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(FOnMouseDown) then FOnMouseDown(Self, Button, Shift, X, Y); end; procedure TSMTrayIcon.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(FOnMouseUp) then FOnMouseUp(Self, Button, Shift, X, Y); end; procedure TSMTrayIcon.DblClick; begin if not CheckDefaultMenuItem and Assigned(FOnDblClick) then FOnDblClick(Self); end; procedure TSMTrayIcon.DoClick(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button = mbRight) and CheckMenuPopup(X, Y) then Exit; if Assigned(FOnClick) then FOnClick(Self, Button, Shift, X, Y); end; procedure TSMTrayIcon.WndProc(var Message: TMessage); function GetShiftState: TShiftState; begin Result := []; if GetKeyState(VK_SHIFT) < 0 then Include(Result, ssShift); if GetKeyState(VK_CONTROL) < 0 then Include(Result, ssCtrl); if GetKeyState(Vk_MENU) < 0 then Include(Result, ssAlt); end; var P: TPoint; Shift: TShiftState; begin try with Message do if Msg = CM_TRAYICON then begin case lParam of WM_LBUTTONDBLCLK: begin DblClick; GetCursorPos(P); MouseDown(mbLeft, GetShiftState + [ssDouble], P.X, P.Y); end; WM_RBUTTONDBLCLK: begin GetCursorPos(P); MouseDown(mbRight, GetShiftState + [ssDouble], P.X, P.Y); end; WM_MBUTTONDBLCLK: begin GetCursorPos(P); MouseDown(mbMiddle, GetShiftState + [ssDouble], P.X, P.Y); end; WM_MOUSEMOVE: begin GetCursorPos(P); MouseMove(GetShiftState, P.X, P.Y); end; WM_LBUTTONDOWN: begin GetCursorPos(P); MouseDown(mbLeft, GetShiftState + [ssLeft], P.X, P.Y); Include(FClicked, mbLeft); end; WM_LBUTTONUP: begin Shift := GetShiftState + [ssLeft]; GetCursorPos(P); if mbLeft in FClicked then begin Exclude(FClicked, mbLeft); DoClick(mbLeft, Shift, P.X, P.Y); end; MouseUp(mbLeft, Shift, P.X, P.Y); end; WM_RBUTTONDOWN: begin GetCursorPos(P); MouseDown(mbRight, GetShiftState + [ssRight], P.X, P.Y); Include(FClicked, mbRight); end; WM_RBUTTONUP: begin Shift := GetShiftState + [ssRight]; GetCursorPos(P); if mbRight in FClicked then begin Exclude(FClicked, mbRight); DoClick(mbRight, Shift, P.X, P.Y); end; MouseUp(mbRight, Shift, P.X, P.Y); end; WM_MBUTTONDOWN: begin GetCursorPos(P); MouseDown(mbMiddle, GetShiftState + [ssMiddle], P.X, P.Y); end; WM_MBUTTONUP: begin GetCursorPos(P); MouseUp(mbMiddle, GetShiftState + [ssMiddle], P.X, P.Y); end; end; end else Result := DefWindowProc(FHandle, Msg, wParam, lParam); except Application.HandleException(Self); end; end; end.
unit revwin; interface Procedure VerCheck; Procedure Change_VMM_Title(Title:String); { Max String Length = 29+Nul } Procedure Change_APP_Title(Title:String); { Max String Length = 79+Nul } Function Win3X : Boolean; Function WinVer :Word; implementation USES DOS,CRT,revconst; Var Regs : Registers; { to hold register info } Title_ : String; Function Win3X : Boolean; { Routine to determine if Windows is currently running } begin Regs.AX := $4680; { Win 3.x Standard check } Intr($2F, Regs); { Call Int 2F } if Regs.AX <> 0 then { if AX = 0 Win in Real mode } begin { else check For enhanced mode } Regs.AX := $1600; { Win 3.x Enhanced check } Intr($2F, Regs); { Call Int 2F } if Regs.AL in [$00,$80,$01,$FF] then { Check returned value } Win3X := False { Nope not installed } else Win3X := True; { Ya it is } end else Win3X := True; { Return True } end; Function WinVer :Word; { Returns a Word containing the version of Win Running } { Should only be used after checking For Win installed } { Or value returned will be meaningless } begin Regs.AX := $1600; { Enhanced mode check } Intr($2F, Regs); { Call Int 2F } WinVer := Regs.AX; { Return proper value } end; Procedure Change_APP_Title(Title:String); { Max String Length = 79+Nul } begin Title_:=Title; Asm Mov Ax,168Eh Mov Dx,0000h Mov Di,OffSet Title_+1 int 2fh End; end; Procedure Change_VMM_Title(Title:String); { Max String Length = 29+Nul } begin Title_:=Title; Asm Mov Ax,168Eh Mov Dx,0001h Mov Di,OffSet Title_+1 Int 2fh End; end; Procedure VerCheck; begin if Win3X then begin if lo(winver) = 4 then begin config^.winon:=true; Change_VMM_Title('Relativity Emag'); Change_APP_Title('Thanks to : MuadDib, Enkrypt And All The Hard Working Members (/j #relativity)'); end; { Writeln('Version Running is : ', Lo(WinVer), '.', Hi(WinVer));} end else begin config^.winon:=false; end; end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit System.Bindings.NotifierDefaults; interface uses System.SysUtils, System.Classes, System.Rtti, System.Generics.Collections, System.Bindings.Consts, System.Bindings.NotifierContracts, System.Bindings.Manager; type { TBindingNotifier Default implementor for IBindingNotifier which is used by objects that support data binding. } TBindingNotifier = class(TInterfacedObject, IBindingNotifier) private FOwner: TObject; FManager: TBindingManager; FReserved: TBindingNotifReservedType; protected function GetOwner: TObject; inline; function GetManager: TBindingManager; inline; function GetReserved: TBindingNotifReservedType; inline; procedure SetReserved(Value: TBindingNotifReservedType); inline; procedure SetOwner(Value: TObject); inline; procedure Notify(const PropertyName: String); virtual; public constructor Create(Owner: TObject; Manager: TBindingManager); property Owner: TObject read GetOwner write SetOwner; property Manager: TBindingManager read GetManager; property Reserved: TBindingNotifReservedType read GetReserved write SetReserved; end; { TBindingNotification Default implementor for IBindingNotification which is used to receive notifications from bindable objects. It acts like a notification interceptor. } TBindingNotification = class abstract(TInterfacedObject, IBindingNotification) private FOwner: TObject; protected // binding expressions receive notifications from script objects through here procedure Notification(Notifier: IBindingNotifier; const PropertyName: String); virtual; abstract; // the object that will actually receive the notification; property Owner: TObject read FOwner; public constructor Create(Owner: TObject); end; implementation constructor TBindingNotifier.Create(Owner: TObject; Manager: TBindingManager); begin if not Assigned(Owner) then raise EBindingNotifyError.Create(sOwnerNotFound); inherited Create; FOwner := Owner; FManager := Manager; FReserved := bnrtExternal; end; function TBindingNotifier.GetManager: TBindingManager; begin Result := FManager; end; function TBindingNotifier.GetOwner: TObject; begin Result := FOwner; end; function TBindingNotifier.GetReserved: TBindingNotifReservedType; begin Result := FReserved; end; procedure TBindingNotifier.Notify(const PropertyName: String); var BindingNotif: IBindingNotification; begin if Supports(Manager, IBindingNotification, BindingNotif) then BindingNotif.Notification(Self, PropertyName) else raise EBindingNotifyError.Create(sUnsupportedManager); end; procedure TBindingNotifier.SetOwner(Value: TObject); begin FOwner := Value; end; procedure TBindingNotifier.SetReserved(Value: TBindingNotifReservedType); begin FReserved := Value; end; { TBindingNotification } constructor TBindingNotification.Create(Owner: TObject); begin inherited Create; if not Assigned(Owner) then raise EBindingNotifyError.Create(sOwnerNotFound); FOwner := Owner; end; end.
unit ApacheUtils; { ******************************************************************************************************************* ApacheUtils: Contains TApacheRequest class for Apache Module Author: Motaz Abdel Azeem email: motaz@code.sd Home page: http://code.sd License: LGPL Last modifie: 12.July.2012 ******************************************************************************************************************* } {$mode objfpc}{$H+} interface uses Classes, SysUtils, SpiderUtils; type { TApacheRequest } TApacheRequest = class(TSpiderRequest) private fCookies: string; fPostedData: string; procedure ReadCookies; override; procedure DecodeMultiPart; override; function ReadContent: string; override; procedure ReadVariables; override; procedure DisplayErrorMessage(Msg: string); override; public constructor Create(aPathInfo, aContentType, aRequestMethod, aQuery, aCookies, aUserAgent, PostedData, ContentLength, aReferer, aRemoteIP, aURI, aServerSoftware, aHost: string); end; implementation { TApacheRequest } procedure TApacheRequest.ReadCookies; var TempStr: string; Line: string; i: Integer; begin Line:=''; TempStr:= fCookies; for i:= 1 to Length(TempStr) do if Tempstr[i] = ';' then begin fCookieList.Add(Trim(Line)); Line:= ''; end else Line:= Line + TempStr[i]; if Line <> '' then fCookieList.Add(Trim(Line)); end; procedure TApacheRequest.DecodeMultiPart; var Line: string; FieldName: string; Lines: string; IsFile: Boolean; FileContentType: string; FileName: string; Ch: Char; ReadPos: Integer; ContentLen: Integer; i: Integer; FileC: string; begin IsFile:= False; FieldName:= ''; Lines:= ''; ContentLen:= StrToInt(fContentLength); ReadPos:= 0; fFilesCount:= 0; while ReadPos < ContentLen do begin Line:= ''; repeat ch:= fPostedData[ReadPos]; Inc(ReadPos); if (CH <> #10) or (IsFile) then Line:= Line + Ch; until (ReadPos >= ContentLen) or ((Ch = #10) and not IsFile); if (Pos(fBoundary, Line) > 0) then begin if FieldName <> '' then begin fContentFields.Add(FieldName + '=' + Copy(Lines, 2, Length(Lines) - 2)); Lines:= ''; end; Line:= ''; repeat Inc(ReadPos); ch:= fPostedData[ReadPos]; if (CH <> #10) then Line:= Line + Ch; until (ReadPos >= ContentLen) or (Ch = #10); // file if Pos('filename=', Line) > 0 then begin // File header IsFile:= True; Inc(fFilesCount); SetLength(fFiles, Length(fFiles) + 1); FileName:= Copy(Line, Pos('filename=', Line) + 10, Length(Line)); FileName:= Copy(FileName, 1, Pos('"', FileName) - 1); Line:= Copy(Line, 1, Pos('filename=', Line) - 1); FileContentType:= ''; // Inc(ReadPos); Line := ''; // Content type repeat Inc(ReadPos); ch:= fPostedData[ReadPos]; if CH <> #10 then FileContentType:= FileContentType + Ch; until (ReadPos >= ContentLen) or (Ch = #10); fFiles[High(fFiles)].ContentType:= Trim(Copy(FileContentType, Pos(':', FileContentType) + 1, Length(FileContentType))); fFiles[High(fFiles)].FileName:= FileName; Line:= ''; Lines:= ''; Inc(ReadPos, 2); // File contents FileC:= ''; repeat Inc(ReadPos); ch:= fPostedData[ReadPos]; FileC:= FileC + ch; Line:= Line + ch; // File termination if Pos(fBoundary, Line) > 0 then begin Delete(FileC, Length(FileC) - Length(fBoundary) - 0, Length(fBoundary) + 0); Line:= ''; Break; end; if ch = #10 then Line:= ''; until (ReadPos >= ContentLen); fFiles[High(fFiles)].FileContent:= Copy(FileC, 1, Length(FileC) - 5); fFiles[High(fFiles)].FieldName:= Fieldname; fFiles[High(fFiles)].FileSize:= Length(fFiles[High(fFiles)].FileContent); IsFile:= False; Line:= ''; Lines:= '' end else IsFile:= False; if not isFile then begin FieldName:= Copy(Line, Pos('name="', Line) + 6, Length(Line)); FieldName:= Copy(FieldName, 1, Pos('"', FieldName) - 1); end; if not IsFile then Lines:= ''; end else begin if not IsFile then Lines:= Lines + Line; end; end; if (Lines <> '') then begin if (FieldName <> '') then fContentFields.Add(FieldName + '=' + Lines); end; end; function TApacheRequest.ReadContent: string; begin Result:= fPostedData; end; procedure TApacheRequest.ReadVariables; begin { fRequestMethod:= GetEnvironmentVariable('REQUEST_METHOD'); fUserAgent:= GetEnvironmentVariable('HTTP_USER_AGENT'); fRemoteAddress:= GetEnvironmentVariable('REMOTE_ADDR'); fContentType:= GetEnvironmentVariable('CONTENT_TYPE'); fQueryString:= GetEnvironmentVariable('QUERY_STRING');} end; procedure TApacheRequest.DisplayErrorMessage(Msg: string); begin raise Exception.Create(Msg); end; constructor TApacheRequest.Create(aPathInfo, aContentType, aRequestMethod, aQuery, aCookies, aUserAgent, PostedData, ContentLength, aReferer, aRemoteIP, aURI, aServerSoftware, aHost: string); begin fPathInfo:= aPathInfo; fContentType:= aContentType; fQueryString:= aQuery; fRequestMethod:= aRequestMethod; fUserAgent:= aUserAgent; fCookies:= aCookies; fPostedData:= PostedData; fContentLength:= ContentLength; fReferer:= aReferer; fRemoteAddress:= aRemoteIP; fURI:= aURI; fHost:= aHost; fWebServerSoftware:= aServerSoftware; fIsCGI:= False; fIsApache:= True; inherited Create; end; end.
unit SEA_EAX; (************************************************************************* DESCRIPTION : SEED EAX mode functions REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : [1] EAX: A Conventional Authenticated-Encryption Mode, M.Bellare, P.Rogaway, D.Wagner <http://eprint.iacr.org/2003/069> [2] http://csrc.nist.gov/CryptoToolkit/modes/proposedmodes/eax/eax-spec.pdf Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 13.06.07 W.Ehrhardt Initial version analog AES_EAX 0.11 13.06.07 we Type TSEA_EAXContext 0.12 26.07.10 we Longint ILen 0.13 28.07.10 we Use SEA_OMAC_Update instead of SEA_OMAC_UpdateXL **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2007-2010 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) {$i STD.INC} interface uses SEA_Base, SEA_CTR, SEA_OMAC; type TSEA_EAXContext = packed record HdrOMAC : TSEAContext; {Hdr OMAC1 context} MsgOMAC : TSEAContext; {Msg OMAC1 context} ctr_ctx : TSEAContext; {Msg SEACTR context} NonceTag: TSEABlock; {nonce tag } tagsize : word; {tag size (unused) } flags : word; {ctx flags (unused)} end; {$ifdef CONST} function SEA_EAX_Init(const Key; KBits: word; const nonce; nLen: word; var ctx: TSEA_EAXContext): integer; {-Init hdr and msg OMACs, setp SEACTR with nonce tag} {$ifdef DLL} stdcall; {$endif} {$else} function SEA_EAX_Init(var Key; KBits: word; var nonce; nLen: word; var ctx: TSEA_EAXContext): integer; {-Init hdr and msg OMACs, setp SEACTR with nonce tag} {$endif} function SEA_EAX_Provide_Header(Hdr: pointer; hLen: word; var ctx: TSEA_EAXContext): integer; {$ifdef DLL} stdcall; {$endif} {-Supply a message header. The header "grows" with each call} function SEA_EAX_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSEA_EAXContext): integer; {$ifdef DLL} stdcall; {$endif} {-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update OMACs} function SEA_EAX_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSEA_EAXContext): integer; {$ifdef DLL} stdcall; {$endif} {-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update OMACs} procedure SEA_EAX_Final(var tag: TSEABlock; var ctx: TSEA_EAXContext); {$ifdef DLL} stdcall; {$endif} {-Compute EAX tag from context} implementation {---------------------------------------------------------------------------} {$ifdef CONST} function SEA_EAX_Init(const Key; KBits: word; const nonce; nLen: word; var ctx: TSEA_EAXContext): integer; {-Init hdr and msg OMACs, setp SEACTR with nonce tag} {$else} function SEA_EAX_Init(var Key; KBits: word; var nonce; nLen: word; var ctx: TSEA_EAXContext): integer; {-Init hdr and msg OMACs, setp SEACTR with nonce tag} {$endif} var err: integer; t_n: TSEABlock; begin fillchar(ctx, sizeof(ctx), 0); {Initialize OMAC context with key} err := SEA_OMAC_Init(Key, KBits, ctx.HdrOMAC); if err=0 then begin {copy fresh context, first use MsgOMAC for nonce OMAC} ctx.MsgOMAC := ctx.HdrOMAC; fillchar(t_n, sizeof(t_n),0); err := SEA_OMAC_Update(@t_n, sizeof(t_n), ctx.MsgOMAC); if err=0 then err := SEA_OMAC_Update(@nonce, nLen, ctx.MsgOMAC); if err=0 then SEA_OMAC_Final(ctx.NonceTag, ctx.MsgOMAC); {inititialize SEA-CTR context} if err=0 then err := SEA_CTR_Init(Key, KBits, ctx.NonceTag, ctx.ctr_ctx); if err=0 then begin {initialize msg OMAC} ctx.MsgOMAC := ctx.HdrOMAC; t_n[SEABLKSIZE-1] := 2; err := SEA_OMAC_Update(@t_n, sizeof(t_n), ctx.MsgOMAC); {initialize header OMAC} t_n[SEABLKSIZE-1] := 1; if err=0 then err := SEA_OMAC_Update(@t_n, sizeof(t_n), ctx.HdrOMAC); end; end; SEA_EAX_Init := err; end; {---------------------------------------------------------------------------} function SEA_EAX_Provide_Header(Hdr: pointer; hLen: word; var ctx: TSEA_EAXContext): integer; {-Supply a message header. The header "grows" with each call} begin SEA_EAX_Provide_Header := SEA_OMAC_Update(Hdr, hLen, ctx.HdrOMAC); end; {---------------------------------------------------------------------------} function SEA_EAX_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSEA_EAXContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update OMACs} var err: integer; begin {encrypt (and check for nil pointers)} err := SEA_CTR_Encrypt(ptp, ctp, ILen, ctx.ctr_ctx); if err=0 then begin {OMAC1 ciphertext} err := SEA_OMAC_Update(ctp, ILen, ctx.MsgOMAC); end; SEA_EAX_Encrypt := err; end; {---------------------------------------------------------------------------} function SEA_EAX_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSEA_EAXContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update OMACs} var err: integer; begin {OMAC1 ciphertext} err := SEA_OMAC_Update(ctp, ILen, ctx.MsgOMAC); if err=0 then begin {decrypt} err := SEA_CTR_Decrypt(ctp, ptp, ILen, ctx.ctr_ctx); end; SEA_EAX_Decrypt := err; end; {---------------------------------------------------------------------------} procedure SEA_EAX_Final(var tag: TSEABlock; var ctx: TSEA_EAXContext); {-Compute EAX tag from context} var ht: TSEABlock; begin SEA_OMAC1_Final(ht, ctx.HdrOMAC); SEA_OMAC1_Final(tag, ctx.MsgOMAC); SEA_XorBlock(tag,ht,tag); SEA_XorBlock(tag,ctx.NonceTag,tag); end; end.
unit intensive.View.Principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, Datasnap.DBClient, Vcl.ExtCtrls, intensive.View.Editar, intensive.Controller.Interfaces, intensive.Controller; type TfrmListarClientes = class(TForm) dsCliente: TDataSource; Panel1: TPanel; grdPessoa: TDBGrid; Panel2: TPanel; btnNovo: TButton; btnEditar: TButton; btnExcluir: TButton; btnListar: TButton; grdEndereco: TDBGrid; Panel3: TPanel; dsEndereco: TDataSource; procedure btnNovoClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnListarClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); private FController : iController; public { Public declarations } end; var frmListarClientes: TfrmListarClientes; implementation {$R *.dfm} procedure TfrmListarClientes.btnEditarClick(Sender: TObject); begin // try // frmEditar := TfrmEditar.Create(self, dsEndereco); // frmEditar.ShowModal; // finally // frmEditar.Destroy; // end; end; procedure TfrmListarClientes.btnListarClick(Sender: TObject); begin dsCliente.DataSet := FController.Cliente.Build.Listar; // dsEndereco.DataSet := FController.Endereco // .Build.ListarPorFiltro('ID_CLIENTE',dsCliente.DataSet.FieldByName('ID').AsInteger); end; procedure TfrmListarClientes.btnNovoClick(Sender: TObject); begin try frmEditar := TfrmEditar.Create(self, dsCliente, false); frmEditar.ShowModal; finally frmEditar.Destroy; end; end; procedure TfrmListarClientes.FormCreate(Sender: TObject); begin FController := TController.New; end; end.
unit SpectrumUndo; interface uses Classes, Contnrs, OriUndo, SpectrumTypes, Plots; type TSpectrumUndoCommand = class(TOriUndoCommand) protected FSource: TObject; FOwnSource: Boolean; public destructor Destroy; override; end; TPlotTitleEditCommand = class(TSpectrumUndoCommand) private FBackup: String; protected procedure Swap; override; public constructor Create(APlot: TPlot); overload; end; TGraphTitleEditCommand = class(TSpectrumUndoCommand) private FBackup: String; FAutoTitle: Boolean; protected procedure Swap; override; public constructor Create(AGraph: TGraph); overload; end; TGraphAppendCommand = class(TSpectrumUndoCommand) private FModified: Boolean; public constructor Create(AGraph: TGraph); procedure Undo; override; procedure Redo; override; end; TGraphDeleteCommand = class(TSpectrumUndoCommand) private FIndex: Integer; FModified: Boolean; public constructor Create(AGraph: TGraph; AIndex: Integer); procedure Undo; override; procedure Redo; override; end; {TReversibleGraphCmdKind = (rgkSwapXY, rgkFlipX, rgkFlipY); TReversibleGraphCommand = class(TOriUndoCommand) private const CTitles: array [TReversibleGraphCmdKind] of String = ('Undo_SwapXY', 'Undo_FlipX', 'Undo_FlipY'); private FKind: TReversibleGraphCmdKind; FGraphs: TGraphArray; protected procedure Swap; override; public constructor Create(var AGraphs: TGraphArray; AKind: TReversibleGraphCmdKind); overload; end; TFullDataGraphCommand = class(TOriUndoCommand) private FSource: TGraph; FValuesX, FValuesY: TValueArray; protected procedure Swap; override; public constructor Create(AGraph: TGraph; const ATitle: String); end; TEditFormulaCommand = class(TOriUndoCommand) private FSource: TGraph; FRange: TRangeParams; FFormula: String; protected procedure Swap; override; public constructor Create(AGraph: TGraph); end; } implementation uses SpectrumStrings; {%region TSpectrumUndoCommand} destructor TSpectrumUndoCommand.Destroy; begin if FOwnSource then FSource.Free; inherited; end; {%endregion} {%region TPlotTitleEditCommand} constructor TPlotTitleEditCommand.Create(APlot: TPlot); begin FSource := APlot; FBackup := APlot.Title; FTitle := Undo_TitlePlot; end; procedure TPlotTitleEditCommand.Swap; var PlotTitle: String; begin PlotTitle := TPlot(FSource).Title; TPlot(FSource).SetTitle(FBackup, False); FBackup := PlotTitle; end; {%endregion TPlotTitleEditCommand} {%region TGraphTitleEditCommand} constructor TGraphTitleEditCommand.Create(AGraph: TGraph); begin FSource := AGraph; FBackup := AGraph.Title; FAutoTitle := AGraph.AutoTitle; FTitle := Undo_TitleGraph; end; procedure TGraphTitleEditCommand.Swap; var GraphTitle: String; GraphAutoTitle: Boolean; begin GraphTitle := TGraph(FSource).Title; GraphAutoTitle := TGraph(FSource).AutoTitle; TGraph(FSource).SetTitle(FBackup, False); TGraph(FSource).AutoTitle := FAutoTitle; FBackup := GraphTitle; FAutoTitle := GraphAutoTitle; end; {%endregion TGraphTitleEditCommand} {%region TGraphAppendCommand} constructor TGraphAppendCommand.Create(AGraph: TGraph); begin FSource := AGraph; FOwnSource := False; FModified := AGraph.Owner.Owner.Modified; FTitle := SpectrumStrings.Undo_AddGraph; end; procedure TGraphAppendCommand.Undo; begin TGraph(FSource).Owner.DeleteGraph(TGraph(FSource), False); TGraph(FSource).Owner.Owner.Modified := FModified; FOwnSource := True; end; procedure TGraphAppendCommand.Redo; begin TGraph(FSource).Owner.AddGraph(TGraph(FSource), -1, False); FOwnSource := False; end; {%endregion} {%region TGraphDeleteCommand} constructor TGraphDeleteCommand.Create(AGraph: TGraph; AIndex: Integer); begin FSource := AGraph; FIndex := AIndex; FOwnSource := True; FModified := AGraph.Owner.Owner.Modified; FTitle := SpectrumStrings.Undo_DeleteGraph; end; procedure TGraphDeleteCommand.Undo; begin TGraph(FSource).Owner.AddGraph(TGraph(FSource), FIndex, False); TGraph(FSource).Owner.Owner.Modified := FModified; FOwnSource := False; end; procedure TGraphDeleteCommand.Redo; begin TGraph(FSource).Owner.DeleteGraph(TGraph(FSource), False); FOwnSource := True; end; {%endregion} (* {$region 'TReversibleGraphCommand'} constructor TReversibleGraphCommand.Create(var AGraphs: TGraphArray; AKind: TReversibleGraphCmdKind); begin FKind := AKind; FGraphs := AGraphs; FTitle := LangManager.ConstantValue[CTitles[FKind]]; end; procedure TReversibleGraphCommand.Swap; var I: Integer; begin case FKind of rgkSwapXY: for I := 0 to Length(FGraphs)-1 do FGraphs[i].SwapXY; rgkFlipX: for I := 0 to Length(FGraphs)-1 do FGraphs[i].FlipX; rgkFlipY: for I := 0 to Length(FGraphs)-1 do FGraphs[i].FlipY; end; end; {$endregion 'TReversibleGraphCommand'} {$region 'TFullDataGraphCommand'} constructor TFullDataGraphCommand.Create(AGraph: TGraph; const ATitle: String); begin FSource := AGraph; if ATitle <> '' then FTitle := Constant(ATitle); FValuesX := Copy(AGraph.ValuesX, 0, AGraph.ValueCount); FValuesY := Copy(AGraph.ValuesY, 0, AGraph.ValueCount); end; procedure TFullDataGraphCommand.Swap; var TmpX, TmpY: TValueArray; begin TmpX := Copy(FSource.ValuesX, 0, FSource.ValueCount); TmpY := Copy(FSource.ValuesY, 0, FSource.ValueCount); FSource.SetValuesXY(FValuesX, FValuesY); FValuesX := TmpX; FValuesY := TmpY; end; {$endregion} {$region 'TEditFormulaCommand'} constructor TEditFormulaCommand.Create(AGraph: TGraph); begin FSource := AGraph; FRange := TFormulaParams(AGraph.Params).Range; FFormula := TFormulaParams(AGraph.Params).Formula; FTitle := Constant('Undo_FormulaEdit'); end; procedure TEditFormulaCommand.Swap; var TmpRange: TRangeParams; TmpFormula: String; begin with TFormulaParams(FSource.Params) do begin TmpRange := Range; TmpFormula := Formula; Range := FRange; Formula := FFormula; FSource.UpdateValues; end; FRange := TmpRange; FFormula := TmpFormula; end; {$endregion} *) initialization HistoryInit; end.
{----------------------------------------------------------------------------- Unit Name: ValueNamesProvider This software and source code are distributed on an as is basis, without warranty of any kind, either express or implied. This file can be redistributed, modified if you keep this header. Copyright © Erwien Saputra 2005 All Rights Reserved. Author: Erwien Saputra Purpose: Manages the complex interaction between IDelphiSettingRegistry and TTreeView. History: 01/19/05 - Initial creation. 02/20/05 - Fixed a bug when a key was missing on one treeview and exist at another, and that node is expanded, the treeview with missing key will expand the root node. -----------------------------------------------------------------------------} unit TreeViewController; interface uses ComCtrls, DelphiSettingRegistry, SysUtils, Classes; type //Manages the interaction between the TTreeView and the IDelphiSettingRegistry //The class that implements thi interface handles the interaction from the //IDelphiSettingRegistry to the TreeView. ITreeViewController = interface ['{A6523793-38FB-4298-BF15-323D884055BA}'] //Property getters/ function GetDelphiSettingRegistry : IDelphiSettingRegistry; function GetTreeView : TTreeview; //Given a full path, returns a node. function FindNode(const FullPath: string; out Node: TTreeNode): boolean; //Bind the TTreeView and Bind the IDelphiSettingRegistry. procedure BindTreeView (const TreeView : TTreeview); procedure BindDelphiSettingRegistry (const Intf : IDelphiSettingRegistry); //Build the nodes in the TTreeView. If Node is nil, build it from the root. //otherwise, clear the Node and build all nodes underneath. procedure BuildNode (Node : TTreeNode); property TreeView : TTreeView read GetTreeView; property DelphiSettingRegistry : IDelphiSettingRegistry read GetDelphiSettingRegistry; end; //Synchronizes the selected key for both IDelphiSettingRegistry. //The object that implements this interface handles the interaction from the //treeview to IDelphiSettingRegistry. //This interface was refactored out from ITreeViewController. //Delphi Setting Manager have two IDelphiSettingManager, each is represented //in TreeView, selecting an item on the TreeView will change the //IDelphiSettingRegistry. There is a need to synchronize the selection of both //IDelphiSettingRegistry/TreeView. This class is also handles synchronizing //the IDelphiSettingRegistry. IDelphiSettingSynchronizer = interface ['{A2A45B82-E38C-451E-BF56-BEFD8CC38EEE}'] procedure AddTreeViewController (const Controller : ITreeViewController); procedure ReleaseDelphiSettingKey (const Intf : IDelphiSettingRegistry); procedure ReleaseTreeView (const TreeView : TTreeView); end; //Factory functions. function CreateTreeViewController : ITreeViewController; forward; function GetDelphiSettingSynchronizer : IDelphiSettingSynchronizer; forward; implementation uses Contnrs, IntfObserver; type //Implements ITreeViewController TTreeViewController = class (TInterfacedObject, ITreeViewController, IObserver) private FTreeView : TTreeView; FDelphiSettingRegistry : IDelphiSettingRegistry; procedure Update (const Subject : ISubject; const AIntf : IInterface = nil); procedure GetNodesFromPath (Path : string; out Nodes : TStringArray); protected function GetTreeView : TTreeview; function GetDelphiSettingRegistry : IDelphiSettingRegistry; function FindNode(const FullPath: string; out Node: TTreeNode): boolean; procedure BindTreeView (const TreeView : TTreeview); procedure BindDelphiSettingRegistry (const Intf : IDelphiSettingRegistry); procedure BuildNode (Node : TTreeNode); public end; TDelphiSettingSynchronizer = class (TInterfacedObject, IDelphiSettingSynchronizer) private FList : TInterfaceList; FUpdating : boolean; function IndexOfTreeView (const TreeView : TTreeView): integer; procedure PropagateChange (TreeView: TTreeView; Path : string; const Selected, Expanded : boolean); procedure NodeChanged (Sender: TObject; Node: TTreeNode); procedure ReleaseControl (const Index : integer); protected procedure ReleaseDelphiSettingKey (const Intf : IDelphiSettingRegistry); procedure ReleaseTreeView (const TreeView : TTreeView); procedure AddTreeViewController (const Controller : ITreeViewController); public constructor Create; destructor Destroy; override; end; function CreateTreeViewController : ITreeViewController; begin Result := TTreeViewController.Create; end; function GetDelphiSettingSynchronizer : IDelphiSettingSynchronizer; begin Result := TDelphiSettingSynchronizer.Create; end; //Given a node, get the full path of that node. function GetPathFromNode (Node : TTreeNode) : string; begin Result := ''; while Node <> nil do begin Result := Node.Text + '\' + Result; Node := Node.Parent; end; end; //Get the text of the root node. The root node has the setting path in it. function RootText (Node : TTreeNode) : string; begin while Node.Parent <> nil do Node := Node.Parent; Result := Node.Text; end; //Get the relative path, it is the path without the root. function GetRelativePath (Node : TTreeNode) : string; begin Result := ''; while Node.Parent <> nil do begin Result := Node.Text + '\' + Result; Node := Node.Parent; end; if SameText (Result, EmptyStr) = false then Result := '\' + Result; end; { TTreeViewController } //Given a path, parses it to a string of array. Each node is a key. The first //item is the setting path, the second items to the last items are the nodes //after the setting path (or relative path). procedure TTreeViewController.GetNodesFromPath (Path : string; out Nodes : TStringArray); var ArrayLength, Delimiter, Index : integer; begin //Firewall if the path is empty string. if SameText (Path, EmptyStr) then begin SetLength (Nodes, 0); Exit; end; //Set the array length for starter. Make it large enough for most operation. ArrayLength := 32; SetLength (Nodes, ArrayLength); Index := 0; if Path[1] <> '\' then Path := '\' + Path; //Get the setting path as the root node. if Pos (FDelphiSettingRegistry.SettingPath, Path) = 1 then Path := Copy (Path, Length (FDelphiSettingRegistry.SettingPath) + 2, Length (Path)) else Path := Copy (Path, 2, Length (Path)); //Iterates the rest of the path and parses it into array. while Path <> '' do begin Delimiter := GetFirstDelimiterIndex (Path); Nodes[Index] := Copy (Path, 1, Delimiter - 1); Inc (Index); if Delimiter = 0 then Path := '' else Path := Copy (Path, Delimiter + 1, Length (Path)); //Resize the array if it is not large enough. if (Index = ArrayLength) and (Path <> '') then begin ArrayLength := ArrayLength * 2; SetLength (Nodes, ArrayLength); end; end; //Resize the array to the correct size. SetLength (Nodes, Index); end; //Bind the IDelphiSettingRegistry to this TreeViewController. procedure TTreeViewController.BindDelphiSettingRegistry( const Intf: IDelphiSettingRegistry); begin if Intf = FDelphiSettingRegistry then Exit; if Assigned (FDelphiSettingRegistry) then (FDelphiSettingRegistry as ISubject).DetachObserver (self); FDelphiSettingRegistry := Intf; if Assigned (FDelphiSettingRegistry) then (FDelphiSettingRegistry as ISubject).AttachObserver (self); end; //The IObserver method. It is get called by the Subject. When Subject current //key is modified, this controller is notified. This method will select the //TreeView node that correspond with the selected key. procedure TTreeViewController.Update(const Subject: ISubject; const AIntf: IInterface); var Node : TTreeNode; Intf : IDelphiSettingRegistry; begin Intf := Subject as IDelphiSettingRegistry; //If the Node is not found, build the node. if FindNode (Intf.CurrentPath, Node) = false then begin BuildNode(Node); //After the node is rebuild, find it again. FindNode (Intf.CurrentPath, Node); end; if Assigned (Node) then FTreeView.Select (Node); end; //Given a full path, return the corresponding node on the treeview. If the node //is not found, it returns false and the out parameter Node will be the closest //node to the desired node. //If the node is found, Node will be desired node and returns true. function TTreeViewController.FindNode(const FullPath: string; out Node: TTreeNode): boolean; var Nodes : TStringArray; Loop : integer; TempNode : TTreeNode; begin Result := true; //Parses the path to array of string. Each element of the array is a registry //key in hiearchy order. GetNodesfromPath (FullPath, Nodes); FTreeView.Items.BeginUpdate; try FTreeView.Selected := nil; //This is the root. It is always valid. The first path is the root, the //setting path. Node := FTreeView.Items.GetFirstNode; //Firewall if the TreeView does not have any node yet. if Node = nil then Exit; //Iterate through the array and try to find the target node. for Loop := Low (Nodes) to High (Nodes) do begin //Iterate the children nodes and see if it matches the desired key. TempNode := Node.getFirstChild; while (Assigned (TempNode)) and (SameText (TempNode.Text, Nodes [Loop]) = false) do TempNode := TempNode.GetNextSibling; //If the desired key is not found, break. Node will be closest node to the //desired node. if (Assigned (TempNode) = false) or (SameText (TempNode.Text, Nodes [Loop]) = false) then begin Result := false; Break; end; //Set the Node with TempNode. TempNode is a valid node. Move on to the //children of this node. Node := TempNode; end; finally FTreeView.Items.EndUpdate; end; end; //Bind a TreeView to this class. procedure TTreeViewController.BindTreeView(const TreeView: TTreeview); begin if FTreeView = TreeView then Exit; FTreeView := TreeView; end; //Build Node builds TreeView with keys. It reads the keys from //IDelphiSettingRegistry. If the Node parameter is nil, this method builds //everything from the root. If Node is not nil, it will clears all nodes under //that Node, and rebuild it. procedure TTreeViewController.BuildNode(Node: TTreeNode); var ChildKey : string; Path : string; List : TStringList; Children : TStringArray; begin //Get the node and the full path to start. Path is the full path for each key. if Node = nil then begin Path := FDelphiSettingRegistry.SettingPath; Node := FTreeView.Items.AddChild (nil, Path); end else begin Path := GetPathFromNode (Node); Node.DeleteChildren; end; //List is a queue. It contains full path and the corresponding node on the //treeview. When processing each node, this method reads all sub keys using //the full path information and creates the nodes under the processed node. List := TStringList.Create; try //This is the beginning, insert the full path and the start node. List.AddObject (Path, Node); while List.Count > 0 do begin //Pop an item from the queue and process it. Path := List [0]; Node := List.Objects[0] as TTreeNode; List.Delete (0); FDelphiSettingRegistry.GetChild(Path, Children); //Creates the nodes under the processed node and at the same time add //child node and the corresponding path to the queue to be processed. for ChildKey in Children do List.AddObject (Path + '\' + ChildKey, FTreeView.Items.AddChild (Node, ChildKey)); end; finally List.Free; end; end; function TTreeViewController.GetTreeView: TTreeview; begin Result := self.FTreeView; end; function TTreeViewController.GetDelphiSettingRegistry: IDelphiSettingRegistry; begin Result := FDelphiSettingRegistry; end; { TDelphiSettingSynchronizer } constructor TDelphiSettingSynchronizer.Create; begin inherited; FList := TInterfaceList.Create; end; destructor TDelphiSettingSynchronizer.Destroy; var Loop : integer; begin for Loop := FList.Count - 1 downto 0 do ReleaseTreeView ((FList.Items[Loop] as ITreeViewController).TreeView); inherited; end; //This method is an event handler, executed every time the node in the treeview //is expanded, collapsed, or selected. procedure TDelphiSettingSynchronizer.NodeChanged(Sender: TObject; Node: TTreeNode); var Path : string; begin //Node can be nil if the Selected is set to nil, when the nodes are rebuild. //When the user add a key to the treeview, series of event handler, OnExpanded //and OnChanged are called. OnExpanded will be called with nil as Node. //FUpdating is a flag that prevents the event handler from being trapped into //an infinite loop. When the user change selection on the tree view, the //synchronizing code will trigger OnChanged event multiple times. if (FUpdating = true) or (Node = nil) then Exit; FUpdating := true; try Path := GetRelativePath (Node); //Tells all registered TreeViewController to update itself, using the //relative path information. Each IDelphiSettingRegistry in the system has //different setting path, so the relative path must be used instead of full //path. PropagateChange (Sender as TTreeView, Path, Node.Selected, Node.Expanded); finally FUpdating := false; end; end; procedure TDelphiSettingSynchronizer.ReleaseDelphiSettingKey( const Intf: IDelphiSettingRegistry); var Loop : integer; begin for Loop := 0 to FList.Count - 1 do if (FList.Items[Loop] as ITreeViewController).DelphiSettingRegistry = Intf then begin ReleaseControl (Loop); Break; end; end; procedure TDelphiSettingSynchronizer.ReleaseTreeView(const TreeView: TTreeView); var Index : integer; begin Index := IndexOfTreeView(TreeView); ReleaseControl (Index); end; //The core method in this class. This method updates all registered //TreeViewController. It updates the procedure TDelphiSettingSynchronizer.PropagateChange(TreeView : TTreeView; Path: string; const Selected, Expanded : boolean); var Loop : integer; LocView : TTreeView; TopNode, Node : TTreeNode; FullTopNodePath, TopNodePath : string; TreeViewController : ITreeViewController; begin if TreeView.TopItem <> nil then TopNodePath := GetRelativePath (TreeView.TopItem); for Loop := 0 to FList.Count - 1 do begin TreeViewController := FList.Items[Loop] as ITreeViewController; LocView := TreeViewController.TreeView; FullTopNodePath := TreeViewController.DelphiSettingRegistry.SettingPath + TopNodePath; //Set the top node first. If the SetCurrentPath is set first, setting the //TopNode may cause the TopNode to push the Selected node out of the //TreeView. The TreeView that initiates the change does not need update. if (LocView <> TreeView) then begin if TreeViewController.FindNode (FullTopNodePath, TopNode) then TreeViewController.TreeView.TopItem := TopNode; end; //Make sure the current setting path in the registry is up to date. This //call will set the DelphiSettingRegistry and TreeViewController will be //notified about the change and set the TreeView selection to reflect the //current selection of the corresponding DelphiSettingRegistry. Selecting a //node will trigger OnChange, but the FUpdating is currently true, it will //not trigger this method again. TreeViewController.DelphiSettingRegistry.SetCurrentPath ( TreeViewController.DelphiSettingRegistry.SettingPath + Path); if LocView = TreeView then Continue; //Get the selected node, if the desired node does not exist in the target //treeview, continue. Node := LocView.Selected; if Assigned (Node) = false then Continue; //Check if the relative path of the node is equal with the path of the //treeview that initiates the change. If it is, synchronize the expanded or //collapsed state. if SameText (GetRelativePath (Node), Path) = true then begin if Expanded then Node.Expand(false) else Node.Collapse(false); end; end; end; //Add a treeview controller. Set the TreeView OnChange, OnCollapsed, and //OnExpanded event handler. procedure TDelphiSettingSynchronizer.AddTreeViewController( const Controller : ITreeViewController); begin Controller.TreeView.OnChange := NodeChanged; Controller.TreeView.OnCollapsed := NodeChanged; Controller.TreeView.OnExpanded := NodeChanged; FList.Add (Controller); end; function TDelphiSettingSynchronizer.IndexOfTreeView( const TreeView: TTreeView): integer; var Loop : integer; begin Result := -1; for Loop := 0 to FList.Count - 1 do if (FList.Items[Loop] as ITreeViewController).TreeView = TreeView then begin Result := Loop; Break; end; end; procedure TDelphiSettingSynchronizer.ReleaseControl(const Index: integer); var TreeViewController : ITreeViewController; begin TreeViewController := FList.Items[Index] as ITreeViewController; TreeViewController.TreeView.OnChange := nil; TreeViewController.TreeView.OnCollapsed := nil; TreeViewController.TreeView.OnExpanded := nil; FList.Delete (Index); end; end.
{--------------------------------- msgbox demo ------------------------------} uses megacrt,gui; {---------------------------------------------------------------- GUI.TPU --- msgbox(color_titulo,'titulo', color_texto,color_bordes,color_fondo, string_especial,botones_a_escojer). String especial: xs:='Hola | uno dos |!| Esto es para|^decir que| |'; | nueva ! linea ^ centra- linea linea con raya lizado blanco Los botones_a_escojer se el numero que devuelve la funcion en la variable de string_especial depende de los divisores. Devuelven los valores: ' Ok | Cancel | Retry ' .... Esc='0' '1' '2' '3' .... Cuando veas un numero menor de 16 dentro de un texto a imprimir, 'Hola '#14'mundo' esto cambia el color al que pongas. Asi, pone 'Hola ' del color antes escojido y continua de color 14 (amarillo). -----------------------------------------------------------------} var bs,cs : string; begin color(red,green); cls('±'); mouse_on; cursor_off; help('Dale a [Enter]/Usa el mouse. [Ctrl]+[flechas] o mouse mueve caja. '); bs:='^Matrimonio Femenino v1.00|!|^(c) 1995 DivorceSoft, Inc'; msgbox(ltcyan,' About ',yellow,white,blue,bs,' Ok '); color(red,blue); mouse_hide; cls('±'); mouse_show; repeat help('Escoje opci¢n del menu, y busca un juez. Est  en orden alfab‚tico.'); bs:='^¨Con cual de los siguientes soletos te quieres casar ahora mismo?|!|^Escoje uno de los candidatos para la boda'; msgbox(ltcyan,' Victima ',ltred,white,dkgray,bs,' Angel | Juan | Marco | Mario '); if bs='0' then begin help('Ser monja no est  permitido...'); bs:=' | | ¨¨¨¨Nadie????? | | '; msgbox(ltred,' Jamona ',ltcyan,white,red,bs,' ¨Qu‚? '); bs:='0'; end; until (bs<>'0'); if bs='1' then cs:='Angel'; if bs='2' then cs:='Juan'; if bs='3' then cs:='Marco'; if bs='4' then cs:='Mario'; color(cyan,blue); mouse_hide; cls('±'); mouse_show; help('Est s frita. Van a averiguar a quien escojiste.'); bs:='^Estoy almacenando la informaci¢n escondida en tu hard disk|'; bs:=bs+'para luego averiguar quien fu‚ el primero que decidiste.| |!| |'; bs:=bs+'No intentes borrar el hard disk. No va a funcionar.|'; bs:=bs+'Correrlo de nuevo no va a cambiar la informaci¢n.'; msgbox(ltcyan,' Aviso ',white,yellow,blue,bs,' Jajajajaja '); color(green,blue); cls('±'); help('¨Creiste eso? Lo PUDE haber hecho pero no soy tan malo.'); bs:='| | | ­Broma! | | | |'; msgbox(ltcyan,' Aviso ',white,yellow,black,bs,' Ok '); color(ltred,white); mouse_hide; cls(#3); mouse_show; help('Opini¢n...'); bs:=' |!|Pero pens ndolo bien... ¨Con '#12+cs+#15'?|!| '; msgbox(ltcyan,' ­No lo puedo creer! ',white,yellow,red,bs,' Ok '); reset_screen; end.
unit DragDropPIDL; // ----------------------------------------------------------------------------- // Project: Drag and Drop Component Suite // Module: DragDropPIDL // Description: Implements Dragging & Dropping of PIDLs (files and folders). // Version: 4.0 // Date: 18-MAY-2001 // Target: Win32, Delphi 5-6 // Authors: Anders Melander, anders@melander.dk, http://www.melander.dk // Copyright © 1997-2001 Angus Johnson & Anders Melander // ----------------------------------------------------------------------------- interface uses DragDrop, DropTarget, DropSource, DragDropFormats, DragDropFile, Windows, ActiveX, Classes, ShlObj; {$include DragDrop.inc} type //////////////////////////////////////////////////////////////////////////////// // // TPIDLClipboardFormat // //////////////////////////////////////////////////////////////////////////////// // Supports the 'Shell IDList Array' format. //////////////////////////////////////////////////////////////////////////////// TPIDLClipboardFormat = class(TCustomSimpleClipboardFormat) private FPIDLs: TStrings; // Used internally to store PIDLs. We use strings to simplify cleanup. FFilenames: TStrings; protected function ReadData(Value: pointer; Size: integer): boolean; override; function WriteData(Value: pointer; Size: integer): boolean; override; function GetSize: integer; override; public constructor Create; override; destructor Destroy; override; function GetClipboardFormat: TClipFormat; override; procedure Clear; override; function HasData: boolean; override; property PIDLs: TStrings read FPIDLs; property Filenames: TStrings read FFilenames; end; type //////////////////////////////////////////////////////////////////////////////// // // TPIDLDataFormat // //////////////////////////////////////////////////////////////////////////////// TPIDLDataFormat = class(TCustomDataFormat) private FPIDLs : TStrings; FFilenames : TStrings; protected public constructor Create(AOwner: TDragDropComponent); override; destructor Destroy; override; function Assign(Source: TClipboardFormat): boolean; override; function AssignTo(Dest: TClipboardFormat): boolean; override; procedure Clear; override; function HasData: boolean; override; function NeedsData: boolean; override; property PIDLs: TStrings read FPIDLs; property Filenames: TStrings read FFilenames; end; type //////////////////////////////////////////////////////////////////////////////// // // TDropPIDLTarget // //////////////////////////////////////////////////////////////////////////////// TDropPIDLTarget = class(TCustomDropMultiTarget) private FPIDLDataFormat : TPIDLDataFormat; FFileMapDataFormat : TFileMapDataFormat; function GetFilenames: TStrings; protected function GetPIDLs: TStrings; function GetPIDLCount: integer; function GetMappedNames: TStrings; property PIDLs: TStrings read GetPIDLs; function DoGetPIDL(Index: integer): pItemIdList; function GetPreferredDropEffect: LongInt; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; Override; // Note: It is the callers responsibility to cleanup // the returned PIDLs from the following 3 methods: // - GetFolderPidl // - GetRelativeFilePidl // - GetAbsoluteFilePidl // Use the CoTaskMemFree procedure to free the PIDLs. function GetFolderPIDL: pItemIdList; function GetRelativeFilePIDL(Index: integer): pItemIdList; function GetAbsoluteFilePIDL(Index: integer): pItemIdList; property PIDLCount: integer read GetPIDLCount; // Includes folder pidl in count // If you just want the filenames (not PIDLs) then use ... property Filenames: TStrings read GetFilenames; // MappedNames is only needed if files need to be renamed after a drag or // e.g. dragging from 'Recycle Bin'. property MappedNames: TStrings read GetMappedNames; end; //////////////////////////////////////////////////////////////////////////////// // // TDropPIDLSource // //////////////////////////////////////////////////////////////////////////////// TDropPIDLSource = class(TCustomDropMultiSource) private FPIDLDataFormat : TPIDLDataFormat; FFileMapDataFormat : TFileMapDataFormat; protected function GetMappedNames: TStrings; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CopyFolderPIDLToList(pidl: PItemIDList); procedure CopyFilePIDLToList(pidl: PItemIDList); property MappedNames: TStrings read GetMappedNames; end; //////////////////////////////////////////////////////////////////////////////// // // PIDL utility functions // //////////////////////////////////////////////////////////////////////////////// //: GetPIDLsFromData extracts a PIDL list from a memory block and stores the // PIDLs in a string list. function GetPIDLsFromData(Data: pointer; Size: integer; PIDLs: TStrings): boolean; //: GetPIDLsFromHGlobal extracts a PIDL list from a global memory block and // stores the PIDLs in a string list. function GetPIDLsFromHGlobal(const HGlob: HGlobal; PIDLs: TStrings): boolean; //: GetPIDLsFromFilenames converts a list of files to PIDLs and stores the // PIDLs in a string list. All the PIDLs are relative to a common root. function GetPIDLsFromFilenames(const Files: TStrings; PIDLs: TStrings): boolean; //: GetRootFolderPIDL finds the PIDL of the folder which is the parent of a list // of files. The PIDl is returned as a string. If the files do not share a // common root, an empty string is returnde. function GetRootFolderPIDL(const Files: TStrings): string; //: GetFullPIDLFromPath converts a path (filename and path) to a folder/filename // PIDL pair. function GetFullPIDLFromPath(Path: string): pItemIDList; //: GetFullPathFromPIDL converts a folder/filename PIDL pair to a full path. function GetFullPathFromPIDL(PIDL: pItemIDList): string; //: PIDLToString converts a single PIDL to a string. function PIDLToString(pidl: PItemIDList): string; //: StringToPIDL converts a PIDL string to a PIDL. function StringToPIDL(const PIDL: string): PItemIDList; //: JoinPIDLStrings merges two PIDL strings into one. function JoinPIDLStrings(pidl1, pidl2: string): string; //: ConvertFilesToShellIDList converts a list of files to a PIDL list. The // files are relative to the folder specified by the Path parameter. The PIDLs // are returned as a global memory handle. function ConvertFilesToShellIDList(Path: string; Files: TStrings): HGlobal; //: GetSizeOfPIDL calculates the size of a PIDL list. function GetSizeOfPIDL(PIDL: pItemIDList): integer; //: CopyPIDL makes a copy of a PIDL. // It is the callers responsibility to free the returned PIDL. function CopyPIDL(PIDL: pItemIDList): pItemIDList; {$ifndef BCB} // Undocumented PIDL utility functions... // From http://www.geocities.com/SiliconValley/4942/ function ILCombine(pidl1,pidl2:PItemIDList): PItemIDList; stdcall; function ILFindLastID(pidl: PItemIDList): PItemIDList; stdcall; function ILClone(pidl: PItemIDList): PItemIDList; stdcall; function ILRemoveLastID(pidl: PItemIDList): LongBool; stdcall; function ILIsEqual(pidl1,pidl2: PItemIDList): LongBool; stdcall; procedure ILFree(Buffer: PItemIDList); stdcall; // Undocumented IMalloc utility functions... function SHAlloc(BufferSize: ULONG): Pointer; stdcall; procedure SHFree(Buffer: Pointer); stdcall; {$endif} //////////////////////////////////////////////////////////////////////////////// // // PIDL/IShellFolder utility functions // //////////////////////////////////////////////////////////////////////////////// //: GetShellFolderOfPath retrieves an IShellFolder interface which can be used // to manage the specified folder. function GetShellFolderOfPath(FolderPath: string): IShellFolder; //: GetPIDLDisplayName retrieves the display name of the specified PIDL, // relative to the specified folder. function GetPIDLDisplayName(Folder: IShellFolder; PIDL: PItemIdList): string; //: GetSubPIDL retrieves the PIDL of the specified file or folder to a PIDL. // The PIDL is relative to the folder specified by the Folder parameter. function GetSubPIDL(Folder: IShellFolder; Sub: string): pItemIDList; //////////////////////////////////////////////////////////////////////////////// // // Component registration // //////////////////////////////////////////////////////////////////////////////// procedure Register; implementation uses ShellAPI, SysUtils; resourcestring sNoFolderPIDL = 'Folder PIDL must be added first'; //////////////////////////////////////////////////////////////////////////////// // // Component registration // //////////////////////////////////////////////////////////////////////////////// procedure Register; begin RegisterComponents(DragDropComponentPalettePage, [TDropPIDLTarget, TDropPIDLSource]); end; //////////////////////////////////////////////////////////////////////////////// // // PIDL utility functions // //////////////////////////////////////////////////////////////////////////////// function GetPIDLsFromData(Data: pointer; Size: integer; PIDLs: TStrings): boolean; var i : integer; pOffset : ^UINT; PIDL : PItemIDList; begin PIDLs.Clear; Result := (Data <> nil) and (Size >= integer(PIDA(Data)^.cidl) * (SizeOf(UINT)+SizeOf(PItemIDList)) + SizeOf(UINT)); if (not Result) then exit; pOffset := @(PIDA(Data)^.aoffset[0]); i := PIDA(Data)^.cidl; // Note: Count doesn't include folder PIDL while (i >= 0) do begin PIDL := PItemIDList(UINT(Data)+ pOffset^); PIDLs.Add(PIDLToString(PIDL)); inc(pOffset); dec(i); end; Result := (PIDLs.Count > 1); end; function GetPIDLsFromHGlobal(const HGlob: HGlobal; PIDLs: TStrings): boolean; var pCIDA : PIDA; begin pCIDA := PIDA(GlobalLock(HGlob)); try Result := GetPIDLsFromData(pCIDA, GlobalSize(HGlob), PIDLs); finally GlobalUnlock(HGlob); end; end; resourcestring sBadDesktop = 'Failed to get interface to Desktop'; sBadFilename = 'Invalid filename: %s'; (* ** Find the folder which is the parent of all the files in a list. *) function GetRootFolderPIDL(const Files: TStrings): string; var DeskTopFolder: IShellFolder; WidePath: WideString; PIDL: pItemIDList; PIDLs: TStrings; s: string; PIDL1, PIDL2: pItemIDList; Size, MaxSize: integer; i: integer; begin Result := ''; if (Files.Count = 0) then exit; if (SHGetDesktopFolder(DeskTopFolder) <> NOERROR) then raise Exception.Create(sBadDesktop); PIDLs := TStringList.Create; try // First convert all paths to PIDLs. for i := 0 to Files.Count-1 do begin WidePath := ExtractFilePath(Files[i]); if (DesktopFolder.ParseDisplayName(0, nil, PWideChar(WidePath), PULONG(nil)^, PIDL, PULONG(nil)^) <> NOERROR) then raise Exception.Create(sBadFilename); try PIDLs.Add(PIDLToString(PIDL)); finally coTaskMemFree(PIDL); end; end; Result := PIDLs[0]; MaxSize := Length(Result)-SizeOf(Word); PIDL := pItemIDList(PChar(Result)); for i := 1 to PIDLs.Count-1 do begin s := PIDLs[1]; PIDL1 := PIDL; PIDL2 := pItemIDList(PChar(s)); Size := 0; while (Size < MaxSize) and (PIDL1^.mkid.cb <> 0) and (PIDL1^.mkid.cb = PIDL2^.mkid.cb) and (CompareMem(PIDL1, PIDL2, PIDL1^.mkid.cb)) do begin inc(Size, PIDL1^.mkid.cb); inc(integer(PIDL2), PIDL1^.mkid.cb); inc(integer(PIDL1), PIDL1^.mkid.cb); end; if (Size <> MaxSize) then begin MaxSize := Size; SetLength(Result, Size+SizeOf(Word)); PIDL1^.mkid.cb := 0; end; if (Size = 0) then break; end; finally PIDLs.Free; end; end; function GetPIDLsFromFilenames(const Files: TStrings; PIDLs: TStrings): boolean; var RootPIDL: string; i: integer; PIDL: pItemIdList; FilePIDL: string; begin Result := False; PIDLs.Clear; if (Files.Count = 0) then exit; // Get the PIDL of the root folder... // All the file PIDLs will be relative to this PIDL RootPIDL := GetRootFolderPIDL(Files); if (RootPIDL = '') then exit; Result := True; PIDLS.Add(RootPIDL); // Add the file PIDLs (all relative to the root)... for i := 0 to Files.Count-1 do begin PIDL := GetFullPIDLFromPath(Files[i]); if (PIDL = nil) then begin Result := False; PIDLs.Clear; break; end; try FilePIDL := PIDLToString(PIDL); finally coTaskMemFree(PIDL); end; // Remove the root PIDL from the file PIDL making it relative to the root. PIDLS.Add(copy(FilePIDL, Length(RootPIDL)-SizeOf(Word)+1, Length(FilePIDL)-(Length(RootPIDL)-SizeOf(Word)))); end; end; function GetSizeOfPIDL(PIDL: pItemIDList): integer; var Size: integer; begin if (PIDL <> nil) then begin Result := SizeOf(PIDL^.mkid.cb); repeat Size := PIDL^.mkid.cb; inc(Result, Size); inc(integer(PIDL), Size); until (Size = 0); end else Result := 0; end; function CopyPIDL(PIDL: pItemIDList): pItemIDList; var Size: integer; begin Size := GetSizeOfPIDL(PIDL); if (Size > 0) then begin Result := ShellMalloc.Alloc(Size); if (Result <> nil) then Move(PIDL^, Result^, Size); end else Result := nil; end; function GetFullPIDLFromPath(Path: string): pItemIDList; var DeskTopFolder : IShellFolder; WidePath : WideString; begin WidePath := Path; if (SHGetDesktopFolder(DeskTopFolder) = NOERROR) then begin if (DesktopFolder.ParseDisplayName(0, nil, PWideChar(WidePath), PULONG(nil)^, Result, PULONG(nil)^) <> NOERROR) then Result := nil; end else Result := nil; end; function GetFullPathFromPIDL(PIDL: pItemIDList): string; var Path: array[0..MAX_PATH] of char; begin if SHGetPathFromIDList(PIDL, Path) then Result := Path else Result := ''; end; // See "Clipboard Formats for Shell Data Transfers" in Ole.hlp... // (Needed to drag links (shortcuts).) type POffsets = ^TOffsets; TOffsets = array[0..$FFFF] of UINT; function ConvertFilesToShellIDList(Path: string; Files: TStrings): HGlobal; var shf: IShellFolder; PathPidl, pidl: pItemIDList; Ida: PIDA; pOffset: POffsets; ptrByte: ^Byte; i, PathPidlSize, IdaSize, PreviousPidlSize: integer; begin Result := 0; shf := GetShellFolderOfPath(path); if shf = nil then exit; // Calculate size of IDA structure ... // cidl: UINT ; Directory pidl // offset: UINT ; all file pidl offsets IdaSize := (Files.Count + 2) * SizeOf(UINT); PathPidl := GetFullPIDLFromPath(path); if PathPidl = nil then exit; try PathPidlSize := GetSizeOfPidl(PathPidl); //Add to IdaSize space for ALL pidls... IdaSize := IdaSize + PathPidlSize; for i := 0 to Files.Count-1 do begin pidl := GetSubPidl(shf, files[i]); try IdaSize := IdaSize + GetSizeOfPidl(Pidl); finally ShellMalloc.Free(pidl); end; end; //Allocate memory... Result := GlobalAlloc(GMEM_SHARE or GMEM_ZEROINIT, IdaSize); if (Result = 0) then exit; try Ida := GlobalLock(Result); try FillChar(Ida^, IdaSize, 0); //Fill in offset and pidl data... Ida^.cidl := Files.Count; //cidl = file count pOffset := POffsets(@(Ida^.aoffset)); pOffset^[0] := (Files.Count+2) * sizeof(UINT); //offset of Path pidl ptrByte := pointer(Ida); inc(ptrByte, pOffset^[0]); //ptrByte now points to Path pidl Move(PathPidl^, ptrByte^, PathPidlSize); //copy path pidl PreviousPidlSize := PathPidlSize; for i := 1 to Files.Count do begin pidl := GetSubPidl(shf,files[i-1]); try pOffset^[i] := pOffset^[i-1] + UINT(PreviousPidlSize); //offset of pidl PreviousPidlSize := GetSizeOfPidl(Pidl); ptrByte := pointer(Ida); inc(ptrByte, pOffset^[i]); //ptrByte now points to current file pidl Move(Pidl^, ptrByte^, PreviousPidlSize); //copy file pidl //PreviousPidlSize = current pidl size here finally ShellMalloc.Free(pidl); end; end; finally GlobalUnLock(Result); end; except GlobalFree(Result); raise; end; finally ShellMalloc.Free(PathPidl); end; end; function PIDLToString(pidl: PItemIDList): String; var PidlLength : integer; begin PidlLength := GetSizeOfPidl(pidl); SetLength(Result, PidlLength); Move(pidl^, PChar(Result)^, PidlLength); end; function StringToPIDL(const PIDL: string): PItemIDList; begin Result := ShellMalloc.Alloc(Length(PIDL)); if (Result <> nil) then Move(PChar(PIDL)^, Result^, Length(PIDL)); end; function JoinPIDLStrings(pidl1, pidl2: string): String; var PidlLength : integer; begin if Length(pidl1) <= 2 then PidlLength := 0 else PidlLength := Length(pidl1)-2; SetLength(Result, PidlLength + Length(pidl2)); if PidlLength > 0 then Move(PChar(pidl1)^, PChar(Result)^, PidlLength); Move(PChar(pidl2)^, Result[PidlLength+1], Length(pidl2)); end; {$ifndef BCB} // BCB appearantly doesn't support ordinal DLL imports. Strange! function ILCombine(pidl1,pidl2:PItemIDList): PItemIDList; stdcall; external shell32 index 25; function ILFindLastID(pidl: PItemIDList): PItemIDList; stdcall; external shell32 index 16; function ILClone(pidl: PItemIDList): PItemIDList; stdcall; external shell32 index 18; function ILRemoveLastID(pidl: PItemIDList): LongBool; stdcall; external shell32 index 17; function ILIsEqual(pidl1,pidl2: PItemIDList): LongBool; stdcall; external shell32 index 21; procedure ILFree(Buffer: PItemIDList); stdcall; external shell32 index 155; function SHAlloc(BufferSize: ULONG): Pointer; stdcall; external shell32 index 196; procedure SHFree(Buffer: Pointer); stdcall; external shell32 index 195; {$endif} //////////////////////////////////////////////////////////////////////////////// // // PIDL/IShellFolder utility functions // //////////////////////////////////////////////////////////////////////////////// function GetShellFolderOfPath(FolderPath: string): IShellFolder; var DeskTopFolder: IShellFolder; PathPidl: pItemIDList; WidePath: WideString; pdwAttributes: ULONG; begin Result := nil; WidePath := FolderPath; pdwAttributes := SFGAO_FOLDER; if (SHGetDesktopFolder(DeskTopFolder) <> NOERROR) then exit; if (DesktopFolder.ParseDisplayName(0, nil, PWideChar(WidePath), PULONG(nil)^, PathPidl, pdwAttributes) = NOERROR) then try if (pdwAttributes and SFGAO_FOLDER <> 0) then DesktopFolder.BindToObject(PathPidl, nil, IID_IShellFolder, // Note: For Delphi 4 and prior, the ppvOut parameter must be a pointer. pointer(Result)); finally ShellMalloc.Free(PathPidl); end; end; function GetSubPIDL(Folder: IShellFolder; Sub: string): pItemIDList; var WidePath: WideString; begin WidePath := Sub; Folder.ParseDisplayName(0, nil, PWideChar(WidePath), PULONG(nil)^, Result, PULONG(nil)^); end; function GetPIDLDisplayName(Folder: IShellFolder; PIDL: PItemIdList): string; var StrRet: TStrRet; begin Result := ''; Folder.GetDisplayNameOf(PIDL, 0, StrRet); case StrRet.uType of STRRET_WSTR: Result := WideCharToString(StrRet.pOleStr); STRRET_OFFSET: Result := PChar(UINT(PIDL)+StrRet.uOffset); STRRET_CSTR: Result := StrRet.cStr; end; end; //////////////////////////////////////////////////////////////////////////////// // // TPIDLsToFilenamesStrings // //////////////////////////////////////////////////////////////////////////////// // Used internally to convert PIDLs to filenames on-demand. //////////////////////////////////////////////////////////////////////////////// type TPIDLsToFilenamesStrings = class(TStrings) private FPIDLs: TStrings; protected function Get(Index: Integer): string; override; function GetCount: Integer; override; procedure Put(Index: Integer; const S: string); override; procedure PutObject(Index: Integer; AObject: TObject); override; public constructor Create(APIDLs: TStrings); procedure Clear; override; procedure Delete(Index: Integer); override; procedure Insert(Index: Integer; const S: string); override; procedure Assign(Source: TPersistent); override; end; constructor TPIDLsToFilenamesStrings.Create(APIDLs: TStrings); begin inherited Create; FPIDLs := APIDLs; end; function TPIDLsToFilenamesStrings.Get(Index: Integer): string; var PIDL: string; Path: array [0..MAX_PATH] of char; begin if (Index < 0) or (Index > FPIDLs.Count-2) then raise Exception.create('Filename index out of range'); PIDL := JoinPIDLStrings(FPIDLs[0], FPIDLs[Index+1]); if SHGetPathFromIDList(PItemIDList(PChar(PIDL)), Path) then Result := Path else Result := ''; end; function TPIDLsToFilenamesStrings.GetCount: Integer; begin if FPIDLs.Count < 2 then Result := 0 else Result := FPIDLs.Count-1; end; procedure TPIDLsToFilenamesStrings.Assign(Source: TPersistent); begin if Source is TStrings then begin BeginUpdate; try GetPIDLsFromFilenames(TStrings(Source), FPIDLs); finally EndUpdate; end; end else inherited Assign(Source); end; // Inherited abstract methods which do not need implementation... procedure TPIDLsToFilenamesStrings.Put(Index: Integer; const S: string); begin end; procedure TPIDLsToFilenamesStrings.PutObject(Index: Integer; AObject: TObject); begin end; procedure TPIDLsToFilenamesStrings.Clear; begin end; procedure TPIDLsToFilenamesStrings.Delete(Index: Integer); begin end; procedure TPIDLsToFilenamesStrings.Insert(Index: Integer; const S: string); begin end; //////////////////////////////////////////////////////////////////////////////// // // TPIDLClipboardFormat // //////////////////////////////////////////////////////////////////////////////// constructor TPIDLClipboardFormat.Create; begin inherited Create; FPIDLs := TStringList.Create; FFilenames := TPIDLsToFilenamesStrings.Create(FPIDLs); end; destructor TPIDLClipboardFormat.Destroy; begin FFilenames.Free; FPIDLs.Free; inherited Destroy; end; var CF_IDLIST: TClipFormat = 0; function TPIDLClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_IDLIST = 0) then CF_IDLIST := RegisterClipboardFormat(CFSTR_SHELLIDLIST); Result := CF_IDLIST; end; procedure TPIDLClipboardFormat.Clear; begin FPIDLs.Clear; end; function TPIDLClipboardFormat.HasData: boolean; begin Result := (FPIDLs.Count > 0); end; function TPIDLClipboardFormat.GetSize: integer; var i : integer; begin Result := (FPIDLs.Count+1) * SizeOf(UINT); for i := 0 to FPIDLs.Count-1 do inc(Result, Length(FPIDLs[i])); end; function TPIDLClipboardFormat.ReadData(Value: pointer; Size: integer): boolean; begin Result := GetPIDLsFromData(Value, Size, FPIDLs); end; function TPIDLClipboardFormat.WriteData(Value: pointer; Size: integer): boolean; var i : integer; pCIDA : PIDA; Offset : integer; pOffset : ^UINT; PIDL : PItemIDList; begin pCIDA := PIDA(Value); pCIDA^.cidl := FPIDLs.Count-1; // Don't count folder PIDL pOffset := @(pCIDA^.aoffset[0]); // Points to aoffset[0] Offset := (FPIDLs.Count+1)*SizeOf(UINT); // Size of CIDA structure PIDL := PItemIDList(integer(pCIDA) + Offset); // PIDLs are stored after CIDA structure. for i := 0 to FPIDLs.Count-1 do begin pOffset^ := Offset; // Store relative offset of PIDL into aoffset[i] // Copy the PIDL Move(PChar(FPIDLs[i])^, PIDL^, length(FPIDLs[i])); // Move on to next PIDL inc(Offset, length(FPIDLs[i])); inc(pOffset); inc(integer(PIDL), length(FPIDLs[i])); end; Result := True; end; //////////////////////////////////////////////////////////////////////////////// // // TPIDLDataFormat // //////////////////////////////////////////////////////////////////////////////// constructor TPIDLDataFormat.Create(AOwner: TDragDropComponent); begin inherited Create(AOwner); FPIDLs := TStringList.Create; TStringList(FPIDLs).OnChanging := DoOnChanging; FFilenames := TPIDLsToFilenamesStrings.Create(FPIDLs); end; destructor TPIDLDataFormat.Destroy; begin FFilenames.Free; FPIDLs.Free; inherited Destroy; end; function TPIDLDataFormat.Assign(Source: TClipboardFormat): boolean; begin Result := True; if (Source is TPIDLClipboardFormat) then FPIDLs.Assign(TPIDLClipboardFormat(Source).PIDLs) else if (Source is TFileClipboardFormat) then Result := GetPIDLsFromFilenames(TFileClipboardFormat(Source).Files, FPIDLs) else Result := inherited Assign(Source); end; function TPIDLDataFormat.AssignTo(Dest: TClipboardFormat): boolean; begin Result := True; if (Dest is TPIDLClipboardFormat) then TPIDLClipboardFormat(Dest).PIDLs.Assign(FPIDLs) else if (Dest is TFileClipboardFormat) then TFileClipboardFormat(Dest).Files.Assign(Filenames) else Result := inherited Assign(Dest); end; procedure TPIDLDataFormat.Clear; begin FPIDLs.Clear; end; function TPIDLDataFormat.HasData: boolean; begin Result := (FPIDLs.Count > 0); end; function TPIDLDataFormat.NeedsData: boolean; begin Result := (FPIDLs.Count = 0); end; //////////////////////////////////////////////////////////////////////////////// // // TDropPIDLTarget // //////////////////////////////////////////////////////////////////////////////// constructor TDropPIDLTarget.Create(AOwner: TComponent); begin inherited Create(AOwner); FPIDLDataFormat := TPIDLDataFormat.Create(Self); FFileMapDataFormat := TFileMapDataFormat.Create(Self); end; destructor TDropPIDLTarget.Destroy; begin FPIDLDataFormat.Free; FFileMapDataFormat.Free; inherited Destroy; end; function TDropPIDLTarget.GetPIDLs: TStrings; begin Result := FPIDLDataFormat.PIDLs; end; function TDropPIDLTarget.DoGetPIDL(Index: integer): pItemIdList; var PIDL : string; begin PIDL := PIDLs[Index]; Result := ShellMalloc.Alloc(Length(PIDL)); if (Result <> nil) then Move(PChar(PIDL)^, Result^, Length(PIDL)); end; function TDropPIDLTarget.GetFolderPidl: pItemIdList; begin Result := DoGetPIDL(0); end; function TDropPIDLTarget.GetRelativeFilePidl(Index: integer): pItemIdList; begin Result := nil; if (index < 1) then exit; Result := DoGetPIDL(Index); end; function TDropPIDLTarget.GetAbsoluteFilePidl(Index: integer): pItemIdList; var PIDL : string; begin Result := nil; if (index < 1) then exit; PIDL := JoinPIDLStrings(PIDLs[0], PIDLs[Index]); Result := ShellMalloc.Alloc(Length(PIDL)); if (Result <> nil) then Move(PChar(PIDL)^, Result^, Length(PIDL)); end; function TDropPIDLTarget.GetPIDLCount: integer; begin // Note: Includes folder PIDL in count! Result := FPIDLDataFormat.PIDLs.Count; end; function TDropPIDLTarget.GetFilenames: TStrings; begin Result := FPIDLDataFormat.Filenames; end; function TDropPIDLTarget.GetMappedNames: TStrings; begin Result := FFileMapDataFormat.FileMaps; end; function TDropPIDLTarget.GetPreferredDropEffect: LongInt; begin Result := inherited GetPreferredDropEffect; if (Result = DROPEFFECT_NONE) then Result := DROPEFFECT_COPY; end; //////////////////////////////////////////////////////////////////////////////// // // TDropPIDLSource // //////////////////////////////////////////////////////////////////////////////// constructor TDropPIDLSource.Create(AOwner: TComponent); begin inherited Create(AOwner); FPIDLDataFormat := TPIDLDataFormat.Create(Self); FFileMapDataFormat := TFileMapDataFormat.Create(Self); end; destructor TDropPIDLSource.Destroy; begin FPIDLDataFormat.Free; FFileMapDataFormat.Free; inherited Destroy; end; procedure TDropPIDLSource.CopyFolderPIDLToList(pidl: PItemIDList); begin //Note: Once the PIDL has been copied into the list it can be 'freed'. FPIDLDataFormat.Clear; FFileMapDataFormat.Clear; FPIDLDataFormat.PIDLs.Add(PIDLToString(pidl)); end; procedure TDropPIDLSource.CopyFilePIDLToList(pidl: PItemIDList); begin // Note: Once the PIDL has been copied into the list it can be 'freed'. // Make sure that folder pidl has been added. if (FPIDLDataFormat.PIDLs.Count < 1) then raise Exception.Create(sNoFolderPIDL); FPIDLDataFormat.PIDLs.Add(PIDLToString(pidl)); end; function TDropPIDLSource.GetMappedNames: TStrings; begin Result := FFileMapDataFormat.FileMaps; end; //////////////////////////////////////////////////////////////////////////////// // // Initialization/Finalization // //////////////////////////////////////////////////////////////////////////////// initialization // Data format registration TPIDLDataFormat.RegisterDataFormat; // Clipboard format registration TPIDLDataFormat.RegisterCompatibleFormat(TPIDLClipboardFormat, 0, csSourceTarget, [ddRead]); TPIDLDataFormat.RegisterCompatibleFormat(TFileClipboardFormat, 1, csSourceTarget, [ddRead]); finalization TPIDLDataFormat.UnregisterDataFormat; end.
unit Generator; interface uses Analyser, Token; type TGenerator = class helper for TAnalyser protected // procedure Generate(Symbol : char); override; public procedure MakeModule(Token : TToken); end; implementation uses Scanner, llvmAPI; (*const GeneratorAction : array[#0..#1] of pointer = (@TGenerator.Generate, nil); procedure TGenerator.Generate(Symbol : char); begin Call(GeneratorAction, Symbol); end; *) procedure TGenerator.MakeModule(Token : TToken); var Module: LLVMModuleRef; ArrayTy_0, PointerTy_1, FuncTy_2, PointerTy_3, FuncTy_5, PointerTy_4: LLVMTypeRef; FyncTy_2_Args: array [0..0] of LLVMTypeRef; FyncTy_5_Args: array [0..0] of LLVMTypeRef; func_main, func_puts, gvar_array_str, const_array_6, int32_puts, const_ptr_7, const_int32_9, const_int64_8: LLVMValueRef; const_ptr_7_indices: array [0..1] of LLVMValueRef; label_10: LLVMBasicBlockRef; Builder: LLVMBuilderRef; Context: LLVMContextRef; begin Module := LLVMModuleCreateWithName(PChar((*Path*)Token.Lexeme + '.bc')); LLVMSetDataLayout(Module, 'e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128'); LLVMSetTarget(Module, TargetCPU + '-unknown-' + TargetOS); Context := LLVMGetModuleContext(Module); // Type Definitions ArrayTy_0 := LLVMArrayType(LLVMInt8TypeInContext(Context), 12); PointerTy_1 := LLVMPointerType(ArrayTy_0, 0); FuncTy_2 := LLVMFunctionType(LLVMInt32TypeInContext(Context), @FyncTy_2_Args[0], 0, LLVMFalse); PointerTy_3 := LLVMPointerType(LLVMInt8TypeInContext(Context), 0); FyncTy_5_Args[0] := PointerTy_3; FuncTy_5 := LLVMFunctionType(LLVMInt32TypeInContext(Context), @FyncTy_5_Args[0], 1, LLVMFalse); PointerTy_4 := LLVMPointerType(FuncTy_5, 0); func_main := LLVMGetNamedFunction(Module, 'main'); if func_main = nil then begin func_main := LLVMAddFunction(Module, 'main', FuncTy_2); LLVMSetLinkage(func_main, LLVMExternalLinkage); LLVMSetFunctionCallConv(func_main, Ord(LLVMCCallConv)); { BAD IDEA } end; LLVMAddFunctionAttr(func_main, LLVMNoUnwindAttribute); LLVMAddFunctionAttr(func_main, LLVMUWTable); func_puts := LLVMGetNamedFunction(Module, 'puts'); if func_puts = nil then begin func_puts := LLVMAddFunction(Module, 'puts', FuncTy_5); LLVMSetLinkage(func_puts, LLVMExternalLinkage); LLVMSetFunctionCallConv(func_puts, Ord(LLVMCCallConv)); end; LLVMAddFunctionAttr(func_puts, LLVMNoUnwindAttribute); // Global Variable Declarations gvar_array_str := LLVMAddGlobal(Module, ArrayTy_0, 'str'); LLVMSetLinkage(gvar_array_str, LLVMInternalLinkage); LLVMSetGlobalConstant(gvar_array_str, LLVMTrue); // Constant Definitions const_array_6 := LLVMConstStringInContext(Context, 'Hello World'#0, 12, LLVMTrue); {?} const_int64_8 := LLVMConstIntOfString(LLVMInt64TypeInContext(Context), '0', 10); //LLVMConstIntOfArbitraryPrecision(LLVMInt64TypeInContext(Context), 10, nil); const_ptr_7_indices[0] := const_int64_8; const_ptr_7_indices[1] := const_int64_8; const_ptr_7 := LLVMConstGEP(gvar_array_str, @const_ptr_7_indices[0], 2); const_int32_9 := LLVMConstIntOfString(LLVMInt32TypeInContext(Context), '0', 10); //LLVMConstIntOfArbitraryPrecision(LLVMInt32TypeInContext(Context), 10, nil); // Global Variable Definitions LLVMSetInitializer(gvar_array_str, const_array_6); // Function Definitions label_10 := LLVMAppendBasicBlockInContext(Context, func_main, ''); Builder := LLVMCreateBuilder(); LLVMPositionBuilderAtEnd(Builder, label_10); int32_puts := LLVMBuildCall(Builder, func_puts, const_ptr_7, 1, 'puts'); LLVMSetInstructionCallConv(int32_puts, Ord(LLVMCCallConv)); LLVMSetTailCall(int32_puts, LLVMTrue); LLVMBuildRet(Builder, const_int32_9); end; end.
Procedure ReadOptions( const FN: string; var Align: Classes.TAlignment; var Width: integer); forward; function CreateXMLDocument( Owner: TComponent): TXMLDocument; begin Owner := TComponent.Create( nil); result := TXMLDocument.Create( Owner); result.Options := [doNodeAutoCreate, doNodeAutoIndent, doAttrNull, doAutoPrefix, doNamespaceDecl]; result.DOMVendor := GetDOMVendor( 'MSXML'); end; Procedure ReadOptions( const FN: string; var Align: TAlignment; var Width: integer); Var Owner: TComponent; Doc: TXMLDocument; Node, Option: IXMLNode; Options: IXMLNodeList; OrdAlign, TentativeWidth, Code: integer; s: string; begin if not FileExists( sFN) then exit; Owner := nil; Doc := CreateXMLDocument( Owner); // NOTE 1 try Doc.LoadFromFile( sFN); Doc.Active := True; Node := Doc.ChildNodes.Nodes[ 'MyApp']; if assigned( Root) then Node := Node.ChildNodes.Nodes[‘Options’]; if assigned( Node) then Options := Node.ChildNodes; if assigned( Options) then Option := Options.First; while assigned( Option) do begin if SameText( Option.NodeName, ‘Option’) and SameText( Option.Attributes[‘Id’], ‘Align’) then begin OrdAlign := TypInfo.GetEnumValue( TypeInfo(TAlignment), Option.Attributes[‘Value’]); if nOrdAlign <> -1 then Align := TAlignment( OrdAlign) end; if SameText( Option.NodeName, ‘Option’) and SameText( Option.Attributes[‘Id’], ‘Width’) then begin s := Option.Attributes[‘Value’]; Val( s, Code, TentativeWidth); if (s <> ‘’) and (Code = 0) then Width := TentativeWidth end; Option := Options.FindSibling( Option, 1); end finally Owner.Free // NOTE 2 end // NOTE 3 end;
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit DSServerReg; interface uses ToolsAPI, DSSource, DesignEditors, DesignIntf; type TPEMFilePropertyEditor = class(TStringProperty) protected function GetFilter: string; virtual; public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; TPEMKeyFilePropertyEditor = class(TPEMFilePropertyEditor) protected function GetFilter: string; override; end; procedure Register; implementation uses Classes, SysUtils, DSServer, DSHTTP, DSNames, Windows, DMForm, DSCommonServer, DbxTransport, StrEdit, DSHTTPCommon, InetReg, DBXPlatform, Controls, DBXCommon, DSCommonReg, DSService, DSAuth, DSServerDsnResStrs, Dialogs, Forms, InetDesignResStrs, PlatformAPI, TypInfo; type TDSLifeCycleProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; TDSServerTransportEditor = class(TSelectionEditor) public procedure RequiresUnits(Proc: TGetStrProc); override; end; TDSCustomRoleItemProperty = class(TStringListProperty) public function GetValue: string; override; end; procedure Register; begin RegisterPropertyEditor(TypeInfo(UnicodeString), TDSServerClass, 'LifeCycle', TDSLifeCycleProperty); RegisterComponents(rsDatasnapServer, [TDSServer, TDSServerClass, TDSCertFiles, TDSAuthenticationManager]); RegisterPropertyEditor(TypeInfo(TStrings), TDSCustomRoleItem, '', TDSCustomRoleItemProperty); RegisterSelectionEditor(TDSServerTransport, TDSServerTransportEditor); RegisterPropertyEditor(TypeInfo(string), TDSCustomCertFiles, 'RootCertFile', TPEMFilePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TDSCustomCertFiles, 'CertFile', TPEMFilePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TDSCustomCertFiles, 'KeyFile', TPEMKeyFilePropertyEditor); end; { TLifeCycleProperty } function TDSLifeCycleProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList, paSortList, paMultiSelect]; end; procedure TDSLifeCycleProperty.GetValues(Proc: TGetStrProc); begin Proc(TDSLifeCycle.Server); Proc(TDSLifeCycle.Session); Proc(TDSLifeCycle.Invocation); // Proc(TDSLifeCycle.Pool); end; { TDSServerTransportEditor } procedure TDSServerTransportEditor.RequiresUnits(Proc: TGetStrProc); var i, j: Integer; FilterUnit: string; LIPImplementationID: string; Transport: TDSServerTransport; TransportFilter: TTransportFilter; begin for i := 0 to Designer.Root.ComponentCount - 1 do begin if Designer.Root.Components[i] is TDSServerTransport then begin Transport := TDSServerTransport(Designer.Root.Components[i]); LIPImplementationID := Transport.IPImplementationID; if LIPImplementationID = '' then Proc('IPPeerServer') else Proc(LIPImplementationID); for j := 0 to Transport.Filters.Count - 1 do begin TransportFilter := Transport.Filters.GetFilter(j); if TransportFilter <> nil then begin FilterUnit := TransportFilter.GetParameterValue('FilterUnit'); if FilterUnit <> EmptyStr then Proc(FilterUnit); end; end; if Designer.Root.Components[i] is TCustomDSRESTServerTransport then begin if Assigned(GetMethodProp(Transport, 'OnFormatResult').Code) then begin Proc('System.JSON'); Proc('Data.DBXCommon'); end; if Assigned(GetMethodProp(Transport, 'OnHTTPTrace').Code) then Proc('Datasnap.DSHTTPCommon'); end; end; end; end; { TCustomRoleItemProperty } function TDSCustomRoleItemProperty.GetValue: string; var LStrings: TStrings; begin LStrings := GetStrings; // Display value in object inspector Result := LStrings.DelimitedText; end; { TPEMFilePropertyEditor } procedure TPEMFilePropertyEditor.Edit; var Dialog: Dialogs.TOpenDialog; begin Dialog := Dialogs.TOpenDialog.Create(Application); with Dialog do try Title := sPEMOpenFileTitle; Filename := GetValue; Filter := GetFilter; HelpContext := 0; Options := Options + [ofShowHelp, ofPathMustExist, ofHideReadonly, ofFileMustExist]; if Dialog.Execute then SetValue(Filename); finally Free; end; end; function TPEMFilePropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paRevertable, paVCL]; end; function TPEMFilePropertyEditor.GetFilter: string; begin Result := sPEMFileFilter; end; { TPEMKeyFilePropertyEditor } function TPEMKeyFilePropertyEditor.GetFilter: string; begin Result := sPEMKeyFileFilter; end; end.
{***************************************************************************} { Copyright 2021 Google LLC } { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { https://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } {***************************************************************************} unit QR; interface uses Bitstr, EC; const { Up to V8 } MaxQRSize = 17 + 4 * 8; MaxMask = 7; MaskPatternAny = -1; { encoding modes } NumericMode = 1; AlphanumericMode = 2; ByteMode = 4; KanjiMode = 8; type Module = ( None, Light, Dark ); QRCode = object QRSize: Integer; QRVersion: Integer; QRLevel: Integer; QRMaskPattern: Integer; QRMode: Integer; Matrix: Array[0..MaxQRSize-1, 0..MaxQRSize-1] of Module; PreferredVersion: Integer; PreferredLevel: Integer; PreferredMaskPattern: Integer; Codewords: Bitstream; constructor Init; function Make(data: ByteBufferPtr; dataLen : Integer) : Integer; procedure ClearMatrix; procedure SetPreferredLevel(level: Integer); procedure SetPreferredVersion(version: Integer); procedure SetPreferredMaskPattern(pattern: Integer); procedure PutModule(row, col: Integer; val: Module); function GetModule(row, col: Integer): Module; function CalculatePenalty: Word; procedure PlaceEverything(data: ByteBufferPtr; dataLen, mask: Integer); procedure PlaceTiming; procedure PlaceDarkModule(version: Integer); procedure PlacePositionElement(row, col: Integer); procedure PlaceAlignmentElement(centerX, centerY: Integer); procedure PlaceFormatString(format: Word); procedure PlaceVersionInfoString(info: LongInt); procedure PlaceModules(buf: ByteBufferPtr; dataLen: Integer; mask: Byte); function MaskModule(row, col: Integer; mask: Byte; val: Module): Module; procedure EncodeAlphanumericMode(data: ByteBufferPtr; len: Integer; version: Integer); procedure EncodeNumericMode(data: ByteBufferPtr; len: Integer; version: Integer); procedure EncodeByteMode(data: ByteBufferPtr; len: Integer; version: Integer); procedure Save(var f: Text); end; QRCodePtr = ^QRCode; implementation const AlignmentPosTable : Array[1..8] of Set of Byte = ( [], { 1 } [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42] ); var qrData: Array[0..MaxECWords] of Byte; function AlphanumericCode(b: Byte): Byte; begin case Chr(b) of '0'..'9': AlphanumericCode := b - Ord('0'); 'A'..'Z': AlphanumericCode := b - Ord('A') + 10; ' ': AlphanumericCode := 36; '$': AlphanumericCode := 37; '%': AlphanumericCode := 38; '*': AlphanumericCode := 39; '+': AlphanumericCode := 40; '-': AlphanumericCode := 41; '.': AlphanumericCode := 42; '/': AlphanumericCode := 43; ':': AlphanumericCode := 44; else AlphanumericCode := 255; end; end; function IsNumeric(data: ByteBufferPtr; len: Integer; var words: Integer): Boolean; var i: Integer; bits: Integer; begin bits := 4 + 14; { mode + len(worst case) } i := 0; for i := 0 to len - 1 do begin if (data^[i] < $30) or (data^[i] > $39) then begin IsNumeric := False; Exit; end; end; bits := bits + 10 * (len div 3); case (len mod 3) of 1: bits := bits + 4; 2: bits := bits + 7; end; words := bits div 8; if (bits mod 8) <> 0 then words := words + 1; IsNumeric := True; end; function IsAlphanumeric(data: ByteBufferPtr; len: Integer; var words: Integer): Boolean; var i: Integer; bits: Integer; begin bits := 4 + 13; { mode + len(worst case) } i := 0; for i := 0 to len - 1 do begin if AlphanumericCode(data^[i]) = 255 then begin IsAlphanumeric := False; Exit; end; end; bits := bits + 11 * (len div 2); if (len mod 2) <> 0 then bits := bits + 6; words := bits div 8; if (bits mod 8) <> 0 then words := words + 1; IsAlphanumeric := True; end; function IsByte(data: ByteBufferPtr; len: Integer; var words: Integer): Boolean; var i: Integer; bits: Integer; begin bits := 4 + 16; { mode + len (worst case) } bits := bits + 8 * len; words := bits div 8; if (bits mod 8) <> 0 then words := words + 1; IsByte := True; end; function BitstringLen(w: LongInt): Byte; var i: ShortInt; begin i := 31; while (i >= 0) and ((w shr i) and 1 = 0) do i := i - 1; BitstringLen := i + 1; end; function MakeFormatString(level: Byte; mask: Byte): Word; const { Generatorial polynomial } GP = $537; var ecc: Word; formatString: Word; bitLen: Byte; begin ecc := (level shl 3) or mask; { append order of generational polynomial zeroes to the right } ecc := ecc shl 10; bitLen := BitstringLen(ecc); while bitLen > 10 do begin ecc := ecc xor (GP shl (bitLen - 11)); ecc := ecc and ((1 shl (bitLen + 1)) - 1); bitLen := BitstringLen(ecc); end; ecc := ecc or (level shl 13) or (mask shl 10); ecc := (ecc xor $5412) and $7FFF; MakeFormatString := ecc; end; procedure WriteHex(x: LongInt); const hexs : String = '0123456789ABCDEF'; var i: Integer; pos: Integer; begin for i := 7 downto 0 do begin pos := ((x shr (i*4)) and $F); Write(hexs[pos + 1]); end; end; function MakeVersionInfoString(version: Byte): LongInt; const { Generatorial polynomial } GP : LongInt = $1F25; var ecc: LongInt; bitLen: Byte; begin ecc := version; { append order of generational polynomial zeroes to the right } ecc := ecc shl 12; bitLen := BitstringLen(ecc); while bitLen > 12 do begin ecc := ecc xor (GP shl (bitLen - 13)); bitLen := BitstringLen(ecc); end; MakeVersionInfoString := ecc or (LongInt(version) shl 12); end; constructor QRCode.Init; begin Codewords.Init; QRVersion := QRVersionAny; QRLevel := ECLevelAny; QRMaskPattern := MaskPatternAny; PreferredVersion := QRVersionAny; PreferredLevel := ECLevelAny; PreferredMaskPattern := MaskPatternAny; ClearMatrix; end; procedure QRCode.ClearMatrix; var i, j: Word; begin for i := 0 to MaxQRSize-1 do for j := 0 to MaxQRSize-1 do Matrix[i, j] := None; end; procedure QRCode.SetPreferredLevel(level: Integer); begin PreferredLevel := level; end; procedure QRCode.SetPreferredVersion(version: Integer); begin PreferredVersion := version; end; procedure QRCode.SetPreferredMaskPattern(pattern: Integer); begin PreferredMaskPattern := pattern; end; function QRCode.Make(data: ByteBufferPtr; dataLen: Integer) : Integer; var encodedCodewords: Integer; info: ECInfoPtr; terminatorLen, paddingLen: Integer; currentMask: Byte; penalty, minPenalty: Word; i: Word; row, col: Integer; mode: Integer; begin mode := 0; if IsNumeric(data, dataLen, encodedCodewords) then mode := NumericMode else if IsAlphanumeric(data, dataLen, encodedCodewords) then mode := AlphaNumericMode else if IsByte(data, dataLen, encodedCodewords) then mode := ByteMode; info := FindECInfo(PreferredVersion, PreferredLevel, encodedCodewords); if info = Nil then begin Make := -1; Exit; end; QRMode := mode; case mode of NumericMode: EncodeNumericMode(data, dataLen, info^.Version); AlphaNumericMode: EncodeAlphaNumericMode(data, dataLen, info^.Version); ByteMode: EncodeByteMode(data, dataLen, info^.Version); end; QRSize := info^.Version*4 + 17; QRVersion := info^.Version; QRLevel := info^.Level; terminatorLen := info^.TotalDataWords * 8 - codewords.BitLength; if terminatorLen > 4 then terminatorLen := 4; codeWords.AddBits(0, terminatorLen); codeWords.PadToByte; for i := 0 to codewords.ByteLength - 1 do qrData[i] := codewords.GetByte(i); paddingLen := info^.TotalDataWords - codeWords.ByteLength; i := 0; while i < paddingLen do begin if i mod 2 = 0 then qrData[codeWords.ByteLength + i] := $EC else qrData[codeWords.ByteLength + i] := $11; i := i + 1; end; CalculateEc(@qrData, info); minPenalty := $FFFF; if PreferredMaskPattern = MaskPatternAny then for currentMask := 0 to MaxMask do begin ClearMatrix; PlaceEverything(@qrData, info^.TotalWords, currentMask); penalty := CalculatePenalty; { Writeln('Mask #', currentMask, ', penalty=', penalty); } if penalty < minPenalty then begin QRMaskPattern := currentMask; minPenalty := penalty; end; end else QRMaskPattern := PreferredMaskPattern; ClearMatrix; PlaceEverything(@qrData, info^.TotalWords, QRMaskPattern); Make := 0; end; function QRCode.CalculatePenalty : Word; var penalty: Word; streakLen, patternLen: Integer; streak: Module; i, j: Integer; pattern: Word; low, high, darkModules: Integer; begin penalty := 0; { Horizontal condition #1 } for i := 0 to QRSize - 1 do begin streak := None; streakLen := 0; for j := 0 to QRSize - 1 do begin if Matrix[i, j] = streak then streakLen := streakLen + 1 else begin if streakLen >= 5 then penalty := penalty + 3 + (streakLen - 5); streak := Matrix[i, j]; streakLen := 1; end; end; if streakLen >= 5 then penalty := penalty + 3 + (streakLen - 5); end; { Vertical condition #1 } for i := 0 to QRSize - 1 do begin streak := None; streakLen := 0; for j := 0 to QRSize - 1 do begin if Matrix[j, i] = streak then streakLen := streakLen + 1 else begin if streakLen >= 5 then penalty := penalty + 3 + (streakLen - 5); streak := Matrix[j, i]; streakLen := 1; end; end; if streakLen >= 5 then penalty := penalty + 3 + (streakLen - 5); end; { Condition #2 } for i := 0 to QRSize - 1 - 1 do for j := 0 to QRSize - 1 - 1 do begin if (Matrix[i, j] = Matrix[i, j + 1]) and (Matrix[i, j] = Matrix[i + 1, j + 1]) and (Matrix[i, j] = Matrix[i + 1, j]) then penalty := penalty + 3 end; { Horizontal codition #3 } for i := 0 to QRSize - 1 do begin pattern := 0; streakLen := 0; for j := 0 to QRSize - 1 do begin if Matrix[i, j] = Light then pattern := pattern shl 1 else pattern := (pattern shl 1) or 1; pattern := pattern and $7FF; if patternLen < 11 then patternLen := patternLen + 1 else if (pattern = $5D) or (pattern = $5D0) then penalty := penalty + 40; end end; { Vertical codition #3 } for i := 0 to QRSize - 1 do begin pattern := 0; streakLen := 0; for j := 0 to QRSize - 1 do begin if Matrix[j, i] = Light then pattern := pattern shl 1 else pattern := (pattern shl 1) or 1; pattern := pattern and $7FF; if patternLen < 11 then patternLen := patternLen + 1 else if (pattern = $5D) or (pattern = $5D0) then penalty := penalty + 40; end end; { Condition #4 } darkModules := 0; for i := 0 to QRSize - 1 do for j := 0 to QRSize - 1 do if Matrix[i, j] = Dark then darkModules := darkModules + 1; low := (darkModules * 100) div (QRSize*QRSize); low := low - (low mod 5); high := low + 5; low := abs(low - 50) div 5; high := abs(high - 50) div 5; if low < high then penalty := penalty + low * 10 else penalty := penalty + high * 10; CalculatePenalty := penalty; end; procedure QRCode.PlaceEverything(data: ByteBufferPtr; dataLen, mask: Integer); var row, col: Word; begin PlacePositionElement(0, 0); PlacePositionElement(QRSize - 7, 0); PlacePositionElement(0, QRSize - 7); for row := 0 to QRSize - 1 do begin if row in AlignmentPosTable[QRVersion] then begin for col := 0 to QRSize do if col in AlignmentPosTable[QRVersion] then PlaceAlignmentElement(row, col); end; end; PlaceTiming; PlaceDarkModule(QRVersion); PlaceFormatString(MakeFormatString(QRLevel, mask)); if QRVersion >= 7 then PlaceVersionInfoString(MakeVersionInfoString(QRVersion)); PlaceModules(data, dataLen, mask); end; procedure QRCode.EncodeNumericMode(data: ByteBufferPtr; len: Integer; version: Integer); var i: Integer; val: Integer; begin Codewords.AddBits(NumericMode, 4); if (version < 10) then CodeWords.AddBits(len, 10) else if (version < 27) then CodeWords.AddBits(len, 12) else CodeWords.AddBits(len, 14); val := 0; for i := 0 to len - 1 do begin val := val * 10 + (ord(data^[i]) - $30); if i mod 3 = 2 then begin Codewords.AddBits(val, 10); val := 0; end; end; case len mod 3 of 1: Codewords.AddBits(val, 4); 2: CodeWords.AddBits(val, 7); end; end; procedure QRCode.EncodeAlphanumericMode(data: ByteBufferPtr; len: Integer; version: Integer); var i: Integer; val: Integer; begin Codewords.AddBits(AlphanumericMode, 4); if (version < 10) then CodeWords.AddBits(len, 9) else if (version < 27) then CodeWords.AddBits(len, 11) else CodeWords.AddBits(len, 13); i := 0; while i < len - 1 do begin val := AlphanumericCode(data^[i]) * 45 + AlphanumericCode(data^[i+1]); Codewords.AddBits(val, 11); i := i + 2; end; if i = len - 1 then begin val := AlphanumericCode(data^[i]); Codewords.AddBits(val, 6); end; end; procedure QRCode.EncodeByteMode(data: ByteBufferPtr; len: Integer; version: Integer); var i: Integer; begin Codewords.AddBits(ByteMode, 4); if (version < 10) then CodeWords.AddBits(len, 8) else CodeWords.AddBits(len, 16); for i := 0 to len - 1 do Codewords.AddBits(data^[i], 8); end; procedure QRCode.PutModule(row, col: Integer; val: Module); begin if (row < 0) or (row >= QRSize) then exit; if (col < 0) or (col >= QRSize) then exit; Matrix[row, col] := val; end; function QRCode.GetModule(row, col: Integer): Module; var val: Module; begin val := Light; if (row >= 0) and (row < QRSize) and (col >= 0) and (col < QRSize) then val := Matrix[row, col]; GetModule := val; end; procedure QRCode.PlaceTiming; var i: Integer; begin for i:= 8 to QRSize - 7 do begin if i mod 2 = 0 then begin PutModule(6, i, Dark); PutModule(i, 6, Dark); end else begin PutModule(6, i, Light); PutModule(i, 6, Light); end; end; end; procedure QRCode.PlaceDarkModule(version: Integer); begin PutModule(4 * version + 9, 8, Dark); end; procedure QRCode.PlacePositionElement(row, col: Integer); var i, j: Integer; begin { external dark square } for i := 0 to 6 do begin PutModule(row + 0, col + i, Dark); PutModule(row + 6, col + i, Dark); PutModule(row + i, col + 0, Dark); PutModule(row + i, col + 6, Dark); end; { internal light square } for i := 1 to 5 do begin PutModule(row + 1, col + i, Light); PutModule(row + 5, col + i, Light); PutModule(row + i, col + 1, Light); PutModule(row + i, col + 5, Light); end; { internal dark square } for i := 2 to 4 do for j := 2 to 4 do PutModule(row + i, col + j, Dark); { separators, out-of-area coordinates are handled by PutModule } for i := -1 to 7 do begin PutModule(row - 1, col + i, Light); PutModule(row + 7, col + i, Light); PutModule(row + i, col - 1, Light); PutModule(row + i, col + 7, Light); end; end; procedure QRCode.PlaceAlignmentElement(centerX, centerY: Integer); var i: Integer; begin { overlaps with the top-left finder ? } if (centerX - 2 <= 7) and (centerY - 2 <= 7) then Exit; { overlaps with the top-right finder ? } if (centerX + 2 >= QRSize - 1 - 7) and (centerY - 2 <= 7) then Exit; { overlaps with the bottom-left finder ? } if (centerX - 2 <= 7) and (centerY + 2 >= QRSize - 1 - 7) then Exit; PutModule(centerX, centerY, Dark); for i := -1 to 1 do begin PutModule(centerX - 1, centerY + i, Light); PutModule(centerX + 1, centerY + i, Light); PutModule(centerX + i, centerY + 1, Light); PutModule(centerX + i, centerY - 1, Light); end; for i := -2 to 2 do begin PutModule(centerX - 2, centerY + i, Dark); PutModule(centerX + 2, centerY + i, Dark); PutModule(centerX + i, centerY + 2, Dark); PutModule(centerX + i, centerY - 2, Dark); end; end; procedure QRCode.PlaceFormatString(format: Word); var i: Integer; v: Module; begin { vertical } for i := 0 to 14 do begin if ((format shr (14 - i)) and 1) = 1 then v := Dark else v := Light; if i < 7 then PutModule(QRSize - 1 - i, 8, v) else if i < 9 then PutModule(15 - i, 8, v) else PutModule(14 - i, 8, v); end; { horizontal } for i := 0 to 14 do begin if (format shr (14 - i) and 1) = 0 then v := Light else v := Dark; if i < 6 then PutModule(8, i, v) else if i < 7 then PutModule(8, i + 1, v) else PutModule(8, QRSize - 15 + i, v); end; end; procedure QRCode.PlaceVersionInfoString(info: LongInt); var i: Integer; v: Module; begin for i := 0 to 17 do begin if ((info shr i) and 1) = 0 then v := Light else v := Dark; { horizontal } PutModule(QRSize - 11 + (i mod 3), i div 3, v); { vertical } PutModule(i div 3, QRSize - 11 + (i mod 3), v); end; end; procedure QRCode.PlaceModules(buf: ByteBufferPtr; dataLen: Integer; mask: Byte); var col, row: Integer; useLeft, goUp, done: Boolean; bitPtr, idx, bit: Integer; val: Module; begin col := QRSize - 1; row := QRSize - 1; useLeft := False; goUp := True; done := False; bitPtr := 0; repeat if Matrix[row, col] = None then begin idx := bitPtr div 8 + 1; if (idx >= dataLen) or ((buf^[idx-1] and (1 shl (7 - (bitPtr mod 8)))) = 0) then val := Light else val := Dark; val := MaskModule(row, col, mask, val); PutModule(row, col, val); bitPtr := bitPtr + 1; end; if useLeft then begin useLeft := False; col := col + 1; if goUp then row := row - 1 else row := row + 1; end else begin useLeft := True; col := col - 1; end; { Are we at the top of the map? } if row = -1 then begin goUp := False; col := col - 2; row := 0; end; { Are we at the bottom of the map? } if row = QRSize then begin goUp := True; col := col - 2; row := QRSize - 1; end; { Skip vertical timing column } if col = 6 then col := col - 1; until col = -1; end; function QRCode.MaskModule(row, col: Integer; mask: Byte; val: Module): Module; var invert: Boolean; begin invert := False; case mask of 0: invert := ((row + col) mod 2) = 0; 1: invert := (row mod 2) = 0; 2: invert := (col mod 3) = 0; 3: invert := (row + col) mod 3 = 0; 4: invert := (((row div 2) + (col div 3)) mod 2) = 0; 5: invert := ((row * col) mod 2) + ((row * col) mod 3) = 0; 6: invert := (((row * col) mod 2) + ((row * col) mod 3)) mod 2 = 0; 7: invert := (((row + col) mod 2) + ((row * col) mod 3)) mod 2 = 0; end; if invert then begin if val = Light then MaskModule := Dark else MaskModule := Light; end else MaskModule := val; end; procedure QRCode.Save(var f: Text); var row, col, ch: Byte; val: Module; begin row := 0; while row < QRSize do begin Write(f, ' '); for col := 0 to QRSize - 1 do begin ch := 0; val := Matrix[row, col]; if val = Light then ch := 2; if row < QRSize - 1 then begin if Matrix[row + 1, col] = Light then ch := ch or 1; end else ch := ch or 1; case ch of 3: Write(f, ' '); 2: Write(f, chr(220)); 1: Write(f, chr(223)); 0: Write(f, chr(219)); end; end; WriteLn(f); row := row + 2; end; end; begin end.
unit NtUtils.WinUser; interface uses Winapi.WinNt, Winapi.WinUser, NtUtils.Exceptions, NtUtils.Security.Sid, NtUtils.Objects; type TNtxStatus = NtUtils.Exceptions.TNtxStatus; TGuiThreadInfo = Winapi.WinUser.TGuiThreadInfo; { Open } // Open desktop function UsrxOpenDesktop(out hxDesktop: IHandle; Name: String; DesiredAccess: TAccessMask; InheritHandle: Boolean = False): TNtxStatus; // Open window station function UsrxOpenWindowStation(out hxWinSta: IHandle; Name: String; DesiredAccess: TAccessMask; InheritHandle: Boolean = False): TNtxStatus; { Query information } // Query any information function UsrxQueryBufferObject(hObj: THandle; InfoClass: TUserObjectInfoClass; out xMemory: IMemory): TNtxStatus; // Quer user object name function UsrxQueryObjectName(hObj: THandle; out Name: String): TNtxStatus; // Query user object SID function UsrxQueryObjectSid(hObj: THandle; out Sid: ISid): TNtxStatus; // Query a name of a current desktop function UsrxCurrentDesktopName: String; { Enumerations } // Enumerate window stations of current session function UsrxEnumWindowStations(out WinStations: TArray<String>): TNtxStatus; // Enumerate desktops of a window station function UsrxEnumDesktops(WinSta: HWINSTA; out Desktops: TArray<String>): TNtxStatus; // Enumerate all accessable desktops from different window stations function UsrxEnumAllDesktops: TArray<String>; { Actions } // Switch to a desktop function UsrxSwithToDesktop(hDesktop: THandle; FadeTime: Cardinal = 0) : TNtxStatus; function UsrxSwithToDesktopByName(DesktopName: String; FadeTime: Cardinal = 0) : TNtxStatus; { Other } // Check if a thread is owns any GUI objects function UsrxIsGuiThread(TID: NativeUInt): Boolean; // Get GUI information for a thread function UsrxGetGuiInfoThread(TID: NativeUInt; out GuiInfo: TGuiThreadInfo): TNtxStatus; implementation uses Winapi.ProcessThreadsApi, Ntapi.ntpsapi; function UsrxOpenDesktop(out hxDesktop: IHandle; Name: String; DesiredAccess: TAccessMask; InheritHandle: Boolean): TNtxStatus; var hDesktop: THandle; begin Result.Location := 'OpenDesktopW'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @DesktopAccessType; hDesktop := OpenDesktopW(PWideChar(Name), 0, InheritHandle, DesiredAccess); Result.Win32Result := (hDesktop <> 0); if Result.IsSuccess then hxDesktop := TAutoHandle.Capture(hDesktop); end; function UsrxOpenWindowStation(out hxWinSta: IHandle; Name: String; DesiredAccess: TAccessMask; InheritHandle: Boolean): TNtxStatus; var hWinSta: THandle; begin Result.Location := 'OpenWindowStationW'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @WinStaAccessType; hWinSta := OpenWindowStationW(PWideChar(Name), InheritHandle, DesiredAccess); Result.Win32Result := (hWinSta <> 0); if Result.IsSuccess then hxWinSta := TAutoHandle.Capture(hWinSta); end; function UsrxQueryBufferObject(hObj: THandle; InfoClass: TUserObjectInfoClass; out xMemory: IMemory): TNtxStatus; var Buffer: Pointer; BufferSize, Required: Cardinal; begin Result.Location := 'GetUserObjectInformationW'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TUserObjectInfoClass); BufferSize := 0; repeat Buffer := AllocMem(BufferSize); Required := 0; Result.Win32Result := GetUserObjectInformationW(hObj, InfoClass, Buffer, BufferSize, @Required); if not Result.IsSuccess then begin FreeMem(Buffer); Buffer := nil; end; until not NtxExpandBuffer(Result, BufferSize, Required); if Result.IsSuccess then xMemory := TAutoMemory.Capture(Buffer, BufferSize); end; function UsrxQueryObjectName(hObj: THandle; out Name: String): TNtxStatus; var xMemory: IMemory; begin Result := UsrxQueryBufferObject(hObj, UserObjectName, xMemory); if Result.IsSuccess then Name := String(PWideChar(xMemory.Address)); end; function UsrxQueryObjectSid(hObj: THandle; out Sid: ISid): TNtxStatus; var xMemory: IMemory; begin Result := UsrxQueryBufferObject(hObj, UserObjectUserSid, xMemory); if not Result.IsSuccess then Exit; if Assigned(xMemory.Address) then Sid := TSid.CreateCopy(xMemory.Address) else Sid := nil; end; function UsrxCurrentDesktopName: String; var WinStaName: String; StartupInfo: TStartupInfoW; begin // Read our thread's desktop and query its name if UsrxQueryObjectName(GetThreadDesktop(NtCurrentThreadId), Result).IsSuccess then begin if UsrxQueryObjectName(GetProcessWindowStation, WinStaName).IsSuccess then Result := WinStaName + '\' + Result; end else begin // This is very unlikely to happen. Fall back to using the value // from the startupinfo structure. GetStartupInfoW(StartupInfo); Result := String(StartupInfo.lpDesktop); end; end; function EnumCallback(Name: PWideChar; var Context: TArray<String>): LongBool; stdcall; begin // Save the value and succeed SetLength(Context, Length(Context) + 1); Context[High(Context)] := String(Name); Result := True; end; function UsrxEnumWindowStations(out WinStations: TArray<String>): TNtxStatus; begin SetLength(WinStations, 0); Result.Location := 'EnumWindowStationsW'; Result.Win32Result := EnumWindowStationsW(EnumCallback, WinStations); end; function UsrxEnumDesktops(WinSta: HWINSTA; out Desktops: TArray<String>): TNtxStatus; begin SetLength(Desktops, 0); Result.Location := 'EnumDesktopsW'; Result.Win32Result := EnumDesktopsW(WinSta, EnumCallback, Desktops); end; function UsrxEnumAllDesktops: TArray<String>; var i, j: Integer; hWinStation: HWINSTA; WinStations, Desktops: TArray<String>; begin SetLength(Result, 0); // Enumerate accessable window stations if not UsrxEnumWindowStations(WinStations).IsSuccess then Exit; for i := 0 to High(WinStations) do begin // Open each window station hWinStation := OpenWindowStationW(PWideChar(WinStations[i]), False, WINSTA_ENUMDESKTOPS); if hWinStation = 0 then Continue; // Enumerate desktops of this window station if UsrxEnumDesktops(hWinStation, Desktops).IsSuccess then begin // Expand each name for j := 0 to High(Desktops) do Desktops[j] := WinStations[i] + '\' + Desktops[j]; Insert(Desktops, Result, Length(Result)); end; CloseWindowStation(hWinStation); end; end; function UsrxSwithToDesktop(hDesktop: THandle; FadeTime: Cardinal): TNtxStatus; begin if FadeTime = 0 then begin Result.Location := 'SwitchDesktop'; Result.LastCall.Expects(DESKTOP_SWITCHDESKTOP, @DesktopAccessType); Result.Win32Result := SwitchDesktop(hDesktop); end else begin Result.Location := 'SwitchDesktopWithFade'; Result.LastCall.Expects(DESKTOP_SWITCHDESKTOP, @DesktopAccessType); Result.Win32Result := SwitchDesktopWithFade(hDesktop, FadeTime); end; end; function UsrxSwithToDesktopByName(DesktopName: String; FadeTime: Cardinal) : TNtxStatus; var hxDesktop: IHandle; begin Result := UsrxOpenDesktop(hxDesktop, DesktopName, DESKTOP_SWITCHDESKTOP); if Result.IsSuccess then Result := UsrxSwithToDesktop(hxDesktop.Handle, FadeTime); end; function UsrxIsGuiThread(TID: NativeUInt): Boolean; var GuiInfo: TGuiThreadInfo; begin FillChar(GuiInfo, SizeOf(GuiInfo), 0); GuiInfo.cbSize := SizeOf(GuiInfo); Result := GetGUIThreadInfo(Cardinal(TID), GuiInfo); end; function UsrxGetGuiInfoThread(TID: NativeUInt; out GuiInfo: TGuiThreadInfo): TNtxStatus; begin FillChar(GuiInfo, SizeOf(GuiInfo), 0); GuiInfo.cbSize := SizeOf(GuiInfo); Result.Location := 'GetGUIThreadInfo'; Result.Win32Result := GetGUIThreadInfo(Cardinal(TID), GuiInfo); end; end.
{ } { Rational numbers v3.07 } { } { This unit is copyright © 1999-2003 by David Butler (david@e.co.za) } { } { This unit is part of Delphi Fundamentals. } { Its original file name is cRational.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/26 0.01 Initial version. } { 1999/12/23 0.02 Fixed bug in CalcFrac. } { 2001/05/21 0.03 Moved rational class to unit cMaths. } { 2002/06/01 0.04 Moved rational class to unit cRational. } { 2003/02/16 3.05 Revised for Fundamentals 3. } { 2003/05/25 3.06 Fixed bug in Subtract. Reported by Karl Hans } { <k.h.kaese@kaese-schulsoftware.de>. } { 2003/05/26 3.07 Fixed bug in Sgn and revised unit. } { Added self testing code. } { } {$INCLUDE ..\cDefines.inc} unit cRational; interface uses { Delphi } SysUtils; { } { Rational number object } { Represents a rational number (Numerator / Denominator pair). } { } type TRational = class private FT, FN : Int64; { FT / FN } protected procedure DenominatorZeroError; procedure DivisionByZeroError; procedure Simplify; procedure SetDenominator(const Denominator: Int64); function GetAsString: String; procedure SetAsString(const S: String); function GetAsReal: Extended; procedure SetAsReal(const R: Extended); public constructor Create; overload; constructor Create(const Numerator: Int64; const Denominator: Int64 = 1); overload; constructor Create(const R: Extended); overload; property Numerator: Int64 read FT write FT; property Denominator: Int64 read FN write SetDenominator; property AsString: String read GetAsString write SetAsString; property AsReal: Extended read GetAsReal write SetAsReal; function Duplicate: TRational; procedure Assign(const R: TRational); overload; procedure Assign(const R: Extended); overload; procedure Assign(const Numerator: Int64; const Denominator: Int64 = 1); overload; procedure AssignZero; procedure AssignOne; function IsEqual(const R: TRational): Boolean; overload; function IsEqual(const Numerator: Int64; const Denominator: Int64 = 1): Boolean; overload; function IsEqual(const R: Extended): Boolean; overload; function IsZero: Boolean; function IsOne: Boolean; procedure Add(const R: TRational); overload; procedure Add(const V: Extended); overload; procedure Add(const V: Int64); overload; procedure Subtract(const R: TRational); overload; procedure Subtract(const V: Extended); overload; procedure Subtract(const V: Int64); overload; procedure Negate; procedure Abs; function Sgn: Integer; procedure Multiply(const R: TRational); overload; procedure Multiply(const V: Extended); overload; procedure Multiply(const V: Int64); overload; procedure Divide(const R: TRational); overload; procedure Divide(const V: Extended); overload; procedure Divide(const V: Int64); overload; procedure Reciprocal; procedure Sqrt; procedure Sqr; procedure Power(const R: TRational); overload; procedure Power(const V: Int64); overload; procedure Power(const V: Extended); overload; procedure Exp; procedure Ln; procedure Sin; procedure Cos; end; ERational = class(Exception); ERationalDivByZero = class(ERational); { } { Self testing code } { } procedure SelfTest; implementation uses { Delphi } Math, { Fundamentals } cUtils, cStrings, cMaths; { } { Rational helper functions } { } procedure SimplifyRational(var T, N: Int64); var I : Int64; begin Assert(N <> 0); if N < 0 then // keep the denominator positive begin T := -T; N := -N; end; if T = 0 then // always represent zero as 0/1 begin N := 1; exit; end; if (T = 1) or (N = 1) then // already simplified exit; I := GCD(T, N); Assert(I > 0); T := T div I; N := N div I; end; { } { TRational } { } constructor TRational.Create; begin inherited Create; AssignZero; end; constructor TRational.Create(const Numerator, Denominator: Int64); begin inherited Create; Assign(Numerator, Denominator); end; constructor TRational.Create(const R: Extended); begin inherited Create; Assign(R); end; procedure TRational.DenominatorZeroError; begin raise ERational.Create('Invalid rational number: Denominator=0'); end; procedure TRational.DivisionByZeroError; begin raise ERationalDivByZero.Create('Division by zero'); end; procedure TRational.Simplify; begin SimplifyRational(FT, FN); end; procedure TRational.SetDenominator(const Denominator: Int64); begin if Denominator = 0 then DenominatorZeroError; FN := Denominator; end; procedure TRational.Assign(const Numerator, Denominator: Int64); begin if Denominator = 0 then DenominatorZeroError; FT := Numerator; FN := Denominator; Simplify; end; procedure TRational.Assign(const R: TRational); begin Assert(Assigned(R)); FT := R.FT; FN := R.FN; end; { See http://forum.swarthmore.edu/dr.math/faq/faq.fractions.html for an } { explanation on how to convert decimal numbers to fractions. } const CalcFracMaxLevel = 12; CalcFracAccuracy = Int64(1000000000); // 1.0E+9 CalcFracDelta = 1.0 / (CalcFracAccuracy * 10); // 1.0E-10 RationalEpsilon = CalcFracDelta; // 1.0E-10 procedure TRational.Assign(const R: Extended); function CalcFrac(const R: Extended; const Level: Integer = 1): TRational; var I : Extended; begin Assert(System.Abs(R) < 1.0); if FloatZero(R, CalcFracDelta) or (Level = CalcFracMaxLevel) then // Return zero. If Level = CalcFracMaxLevel then the result is an // approximation. Result := TRational.Create else if FloatsEqual(R, 1.0, CalcFracDelta) then Result := TRational.Create(1, 1) // Return 1 else begin I := R * CalcFracAccuracy; if System.Abs(I) < 1.0 then // terminating decimal Result := TRational.Create(Round(I), CalcFracAccuracy) else begin // recursive process I := 1.0 / R; Result := CalcFrac(Frac(I), Level + 1); Result.Add(Int64(Trunc(I))); Result.Reciprocal; end; end; end; var T : TRational; Z : Int64; begin T := CalcFrac(Frac(R)); Z := Trunc(R); T.Add(Z); Assign(T); T.Free; end; procedure TRational.AssignOne; begin FT := 1; FN := 1; end; procedure TRational.AssignZero; begin FT := 0; FN := 1; end; function TRational.IsEqual(const Numerator, Denominator: Int64): Boolean; var T, N : Int64; begin T := Numerator; N := Denominator; SimplifyRational(T, N); Result := (FT = T) and (FN = N); end; function TRational.IsEqual(const R: TRational): Boolean; begin Assert(Assigned(R)); Result := (FT = R.FT) and (FN = R.FN); end; function TRational.IsEqual(const R: Extended): Boolean; begin Result := ApproxEqual(R, GetAsReal, RationalEpsilon); end; function TRational.IsOne: Boolean; begin Result := (FT = 1) and (FN = 1); end; function TRational.IsZero: Boolean; begin Result := FT = 0; end; function TRational.Duplicate: TRational; begin Result := TRational.Create(FT, FN); end; procedure TRational.SetAsReal(const R: Extended); begin Assign(R); end; procedure TRational.SetAsString(const S: String); var F : Integer; begin F := Pos('/', S); if F = 0 then Assign(StrToFloat(S)) else Assign(StrToInt(Copy(S, 1, F - 1)), StrToInt(CopyFrom(S, F + 1))); end; function TRational.GetAsReal: Extended; begin Result := FT / FN; end; function TRational.GetAsString: String; begin Result := IntToStr(FT) + '/' + IntToStr(FN); end; procedure TRational.Add(const R: TRational); begin Assert(Assigned(R)); FT := FT * R.FN + R.FT * FN; FN := FN * R.FN; Simplify; end; procedure TRational.Add(const V: Int64); begin Inc(FT, FN * V); end; procedure TRational.Add(const V: Extended); begin Assign(GetAsReal + V); end; procedure TRational.Subtract(const V: Extended); begin Assign(GetAsReal - V); end; procedure TRational.Subtract(const R: TRational); begin Assert(Assigned(R)); FT := FT * R.FN - R.FT * FN; FN := FN * R.FN; Simplify; end; procedure TRational.Subtract(const V: Int64); begin Dec(FT, FN * V); end; procedure TRational.Negate; begin FT := -FT; end; procedure TRational.Abs; begin FT := System.Abs(FT); FN := System.Abs(FN); end; function TRational.Sgn: Integer; begin if FT < 0 then if FN >= 0 then Result := -1 else Result := 1 else if FT > 0 then if FN >= 0 then Result := 1 else Result := -1 else Result := 0; end; procedure TRational.Divide(const V: Int64); begin if V = 0 then DivisionByZeroError; FN := FN * V; Simplify; end; procedure TRational.Divide(const R: TRational); begin Assert(Assigned(R)); if R.FT = 0 then DivisionByZeroError; FT := FT * R.FN; FN := FN * R.FT; Simplify; end; procedure TRational.Divide(const V: Extended); begin Assign(GetAsReal / V); end; procedure TRational.Reciprocal; begin if FT = 0 then DivisionByZeroError; Swap(FT, FN); end; procedure TRational.Multiply(const R: TRational); begin Assert(Assigned(R)); FT := FT * R.FT; FN := FN * R.FN; Simplify; end; procedure TRational.Multiply(const V: Int64); begin FT := FT * V; Simplify; end; procedure TRational.Multiply(const V: Extended); begin Assign(GetAsReal * V); end; procedure TRational.Power(const R: TRational); begin Assert(Assigned(R)); Assign(Math.Power(GetAsReal, R.GetAsReal)); end; procedure TRational.Power(const V: Int64); var T, N : Extended; begin T := FT; N := FN; FT := Round(IntPower(T, V)); FN := Round(IntPower(N, V)); end; procedure TRational.Power(const V: Extended); begin Assign(Math.Power(FT, V) / Math.Power(FN, V)); end; procedure TRational.Sqrt; begin Assign(System.Sqrt(FT / FN)); end; procedure TRational.Sqr; begin FT := System.Sqr(FT); FN := System.Sqr(FN); end; procedure TRational.Exp; begin Assign(System.Exp(FT / FN)); end; procedure TRational.Ln; begin Assign(System.Ln(FT / FN)); end; procedure TRational.Sin; begin Assign(System.Sin(FT / FN)); end; procedure TRational.Cos; begin Assign(System.Cos(FT / FN)); end; { } { Self testing code } { } {$ASSERTIONS ON} procedure SelfTest; var R, S, T : TRational; begin R := TRational.Create; S := TRational.Create(1, 2); try Assert(R.Numerator = 0); Assert(R.Denominator = 1); Assert(R.AsString = '0/1'); Assert(R.AsReal = 0.0); Assert(R.IsZero); Assert(not R.IsOne); Assert(R.Sgn = 0); Assert(S.AsString = '1/2'); Assert(S.Numerator = 1); Assert(S.Denominator = 2); Assert(S.AsReal = 0.5); Assert(not S.IsZero); Assert(not S.IsEqual(R)); Assert(S.IsEqual(1, 2)); Assert(S.IsEqual(2, 4)); R.Assign(1, 3); R.Add(S); Assert(R.AsString = '5/6'); Assert(S.AsString = '1/2'); R.Reciprocal; Assert(R.AsString = '6/5'); R.Assign(1, 2); S.Assign(1, 3); R.Subtract(S); Assert(R.AsString = '1/6'); Assert(R.Sgn = 1); R.Negate; Assert(R.Sgn = -1); Assert(R.AsString = '-1/6'); T := R.Duplicate; Assert(Assigned(T)); Assert(T <> R); Assert(T.AsString = '-1/6'); Assert(T.IsEqual(R)); T.Free; R.Assign(2, 3); S.Assign(5, 2); R.Multiply(S); Assert(R.AsString = '5/3'); R.Divide(S); Assert(R.AsString = '2/3'); R.Sqr; Assert(R.AsString = '4/9'); R.Sqrt; Assert(R.AsString = '2/3'); R.Exp; R.Ln; Assert(R.AsString = '2/3'); R.Power(3); Assert(R.AsString = '8/27'); S.Assign(1, 3); R.Power(S); Assert(R.AsString = '2/3'); R.AsReal := 0.5; Assert(R.AsString = '1/2'); Assert(R.AsReal = 0.5); Assert(R.IsEqual(0.5)); R.AsReal := 1.8; Assert(R.AsString = '9/5'); Assert(R.AsReal = 1.8); Assert(R.IsEqual(1.8)); R.AsString := '11/12'; Assert(R.AsString = '11/12'); Assert(R.Numerator = 11); Assert(R.Denominator = 12); R.AsString := '12/34'; Assert(R.AsString = '6/17'); finally S.Free; R.Free; end; end; end.
unit Unit1; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Imaging.Jpeg, //GLScene GLShadowPlane, GLScene, GLWin32Viewer, GLObjects, GLCadencer, GLVectorGeometry, GLTexture, GLGeomObjects, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses, GLUtils; type TForm1 = class(TForm) GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; DCShadowing: TGLDummyCube; GLLightSource1: TGLLightSource; Cube1: TGLCube; Sphere1: TGLSphere; GLCamera1: TGLCamera; GLCadencer1: TGLCadencer; DCLight: TGLDummyCube; Sphere2: TGLSphere; Torus1: TGLTorus; DCCameraTarget: TGLDummyCube; GLShadowPlane1: TGLShadowPlane; Timer1: TTimer; Panel1: TPanel; CBShadows: TCheckBox; CBStencil: TCheckBox; GLShadowPlane2: TGLShadowPlane; GLMaterialLibrary: TGLMaterialLibrary; GLShadowPlane3: TGLShadowPlane; procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure CBShadowsClick(Sender: TObject); procedure CBStencilClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin SetGLSceneMediaDir(); GLMaterialLibrary.Materials[0].Material.Texture.Image.LoadFromFile('BeigeMarble.jpg'); end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin DCLight.PitchAngle:=Sin(newTime)*60; DCShadowing.TurnAngle:=newTime*10; end; procedure TForm1.CBShadowsClick(Sender: TObject); begin if CBShadows.Checked then GLShadowPlane1.ShadowedLight:=GLLightSource1 else GLShadowPlane1.ShadowedLight:=nil; GLShadowPlane2.ShadowedLight:=GLShadowPlane1.ShadowedLight; GLShadowPlane3.ShadowedLight:=GLShadowPlane1.ShadowedLight; end; procedure TForm1.CBStencilClick(Sender: TObject); begin if CBStencil.Checked then GLShadowPlane1.ShadowOptions:=[spoUseStencil, spoScissor] else GLShadowPlane1.ShadowOptions:=[spoScissor]; GLShadowPlane2.ShadowOptions:=GLShadowPlane1.ShadowOptions; GLShadowPlane3.ShadowOptions:=GLShadowPlane1.ShadowOptions; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Caption := 'Shadow Plane - ' + Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; end; end.
unit U.Utilities; interface function CapitalizeString(const AValue: String): String; implementation uses System.SysUtils; function CapitalizeString(const AValue: String): String; const ALLOWEDCHARS = ['a'..'z', '_']; var LIndex: Integer; LCapitalizeNext: Boolean; begin LCapitalizeNext := True; Result := LowerCase(AValue); if not Result.IsEmpty then begin for LIndex := 1 to Length(Result) do if LCapitalizeNext then begin Result[LIndex] := UpCase(Result[LIndex]); LCapitalizeNext := False; end else if not CharInSet(Result[LIndex], ALLOWEDCHARS) then LCapitalizeNext := True; end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // { : GLFilePGM<p> <b>History : </b><font size=-1><ul> <li>08/05/10 - Yar - Removed check for residency in AssignFromTexture <li>04/02/10 - Yar - Creation </ul><p> } unit GLFilePGM; {$I GLScene.inc} interface uses System.Classes, System.SysUtils, //GLS OpenGLTokens, GLContext, GLGraphics, GLTextureFormat, GLApplicationFileIO; type TGLPGMImage = class(TGLBaseImage) public class function Capabilities: TDataFileCapabilities; override; procedure LoadFromFile(const filename: string); override; procedure SaveToFile(const filename: string); override; procedure LoadFromStream(stream: TStream); override; procedure SaveToStream(stream: TStream); override; procedure AssignFromTexture(textureContext: TGLContext; const textureHandle: TGLenum; textureTarget: TGLTextureTarget; const CurrentFormat: Boolean; const intFormat: TGLInternalFormat); reintroduce; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses GLSCUDAUtility; resourcestring cCUTILFailed = 'Can not initialize cutil32.dll'; // ------------------ // ------------------ TGLPGMImage ------------------ // ------------------ // LoadFromFile // procedure TGLPGMImage.LoadFromFile(const filename: string); var w, h: Integer; cutBuffer: System.PSingle; begin if FileExists(filename) then begin if not IsCUTILInitialized then if not InitCUTIL then begin EInvalidRasterFile.Create(cCUTILFailed); exit; end; cutBuffer := nil; if cutLoadPGMf(PAnsiChar(AnsiString(filename)), cutBuffer, w, h) then begin ResourceName := filename; UnMipmap; FLOD[0].Width := w; FLOD[0].Height := h; FLOD[0].Depth := 0; fColorFormat := GL_LUMINANCE; fInternalFormat := tfLUMINANCE_FLOAT32; fDataType := GL_FLOAT; fCubeMap := false; fTextureArray := false; fElementSize := GetTextureElementSize(tfLUMINANCE_FLOAT32); ReallocMem(fData, DataSize); Move(cutBuffer^, fData^, DataSize); cutFree(cutBuffer); end; end else raise EInvalidRasterFile.CreateFmt('File %s not found', [filename]); end; // SaveToFile // procedure TGLPGMImage.SaveToFile(const filename: string); begin if not IsCUTILInitialized then if not InitCUTIL then begin EInvalidRasterFile.Create(cCUTILFailed); exit; end; if not cutSavePGMf(PAnsiChar(AnsiString(filename)), System.PSingle(fData), FLOD[0].Width, FLOD[0].Height) then raise EInvalidRasterFile.Create('Saving to file failed'); end; procedure TGLPGMImage.LoadFromStream(stream: TStream); begin Assert(false, 'Stream loading not supported'); end; procedure TGLPGMImage.SaveToStream(stream: TStream); begin Assert(false, 'Stream saving not supported'); end; // AssignFromTexture // procedure TGLPGMImage.AssignFromTexture(textureContext: TGLContext; const textureHandle: TGLenum; textureTarget: TGLTextureTarget; const CurrentFormat: Boolean; const intFormat: TGLInternalFormat); var oldContext: TGLContext; contextActivate: Boolean; texFormat: Cardinal; residentFormat: TGLInternalFormat; glTarget: TGLenum; begin if not((textureTarget = ttTexture2D) or (textureTarget = ttTextureRect)) then exit; oldContext := CurrentGLContext; contextActivate := (oldContext <> textureContext); if contextActivate then begin if Assigned(oldContext) then oldContext.Deactivate; textureContext.Activate; end; glTarget := DecodeGLTextureTarget(textureTarget); try textureContext.GLStates.TextureBinding[0, textureTarget] := textureHandle; fLevelCount := 0; fCubeMap := false; fTextureArray := false; fColorFormat := GL_LUMINANCE; fDataType := GL_FLOAT; // Check level existence GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_INTERNAL_FORMAT, @texFormat); if texFormat > 1 then begin GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_WIDTH, @FLOD[0].Width); GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_HEIGHT, @FLOD[0].Height); FLOD[0].Depth := 0; residentFormat := OpenGLFormatToInternalFormat(texFormat); if CurrentFormat then fInternalFormat := residentFormat else fInternalFormat := intFormat; Inc(fLevelCount); end; if fLevelCount > 0 then begin fElementSize := GetTextureElementSize(fColorFormat, fDataType); ReallocMem(fData, DataSize); GL.GetTexImage(glTarget, 0, fColorFormat, fDataType, fData); end else fLevelCount := 1; GL.CheckError; finally if contextActivate then begin textureContext.Deactivate; if Assigned(oldContext) then oldContext.Activate; end; end; end; // Capabilities // class function TGLPGMImage.Capabilities: TDataFileCapabilities; begin Result := [dfcRead, dfcWrite]; end; initialization { Register this Fileformat-Handler with GLScene } RegisterRasterFormat('pgm', 'Portable Graymap', TGLPGMImage); end.
PROGRAM MapTest; USES MapClass; VAR m: Map; s, c: STRING; BEGIN (* MapTest *) New(m, Init); WriteLn('(1) Enter new Value'); WriteLn('(2) Remove Value'); WriteLn('(3) Get Value from Key'); WriteLn('(4) Print Map'); WriteLn('(5) GetSize'); WriteLn('(0) End Program'); REPEAT Write('Enter Number > '); ReadLn(s); IF (s = '1') THEN BEGIN Write('Enter new Key > '); ReadLn(s); Write('Enter new Value > '); ReadLn(c); m^.Put(s, c); END ELSE IF (s = '2') THEN BEGIN Write('Enter key to remove > '); ReadLn(c); m^.Remove(c); END ELSE IF (s = '3') THEN BEGIN Write('Enter key to get value > '); ReadLn(c); m^.GetValue(c, s); WriteLn('Key: ', c, ', Value: ', s); END ELSE IF (s = '4') THEN BEGIN m^.WriteMap; END ELSE IF (s = '5') THEN BEGIN WriteLn('Nr of elements in Map: ', m^.GetSize); END; (* IF *) UNTIL (s = '0'); (* REPEAT *) Dispose(m, Done); END. (* MapTest *)
(* *************************************************************************** SkRegExpW.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 SkRegExpW.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-2012 Shuichi Komiya. All Rights Reserved. *) unit SkRegExpW; interface { Jananese Extenstion Define. Undefine JapaneseExt if you do not use Japanese. 日本語特有の処理を行う条件定義 以下の定義を無効にすると、全角半角の同一視、カタカナひらがなの同一視を行わない。 } {$DEFINE JapaneseExt} {$IFDEF JapaneseExt} { (?k) と (?w) を正規表現パターン内で使えるようにする条件定義。 無効にしても、IgnoreKana, IgnoreWidth プロパティで指定することはできる。 } {$DEFINE UseJapaneseOption} {$ENDIF} { \h is version 1.0.x compatible. } { \h を Perl 互換にする。有効にすると \h は 16進数値にマッチする。 } {.$DEFINE HIsHexDigit} {$DEFINE CHECK_MATCH_EXPLOSION} {$IFDEF DEBUG} {.$DEFINE SHOW_MATCH_PROCESS } {$ENDIF} uses SysUtils, Classes, Contnrs, {$IFDEF DEBUG} ComCtrls, {$ENDIF} {$IFNDEF UNICODE} WideStrings, WideStrUtils, {$ENDIF} SkRegExpConst, UnicodeProp; const {$IFDEF CONDITIONALEXPRESSIONS} {$IF CompilerVersion >= 16.0} MaxListSize = Maxint div 16; {$IFEND} {$ENDIF} type { Exception } { 例外 } ESkRegExp = class(Exception); ESkRegExpRuntime = class(ESkRegExp); ESkRegExpCompile = class(ESkRegExp) public ErrorPos: Integer end; {$IFDEF UNICODE} TREStrings = TStrings; TREStringList = TStringList; REString = UnicodeString; {$ELSE} TREStrings = TWideStrings; TREStringList = TWideStringList; REString = WideString; {$ENDIF} { String Compare Option } { 文字照合オプション } TRECompareOption = (coIgnoreCase, coIgnoreWidth, coIgnoreKana); TRECompareOptions = set of TRECompareOption; { Regular Expression Option } { 正規表現オプション } TREOption = (roNone, roIgnoreCase, roMultiLine, roNamedGroupOnly, roSingleLine, roExtended, roIgnoreWidth, roIgnoreKana, roDefinedCharClassLegacy); TREOptions = set of TREOption; PREOptions = ^TREOptions; { Token } { トークン } TREToken = (tkEnd, tkChar, tkUnion, tkQuest, tkDot, tkRangeChar, tkLHead, tkLTail, tkEmpty, tkLPar, tkRPar, tkStar, tkPlus, tkBound, tkCharClassFirst, tkNegativeCharClassFirst, tkCharClassEnd, tkGroupBegin, tkReference, tkReferenceRelative, tkNamedReference, tkLParWithOption, tkWordChar, tkNEWordChar, tkDigitChar, tkNEDigitChar, tkHexDigitChar, tkNEHexDigitChar, tkSpaceChar, tkNESpaceChar, tkTHead, tkTTail, tkTTailEnd, tkWordBoundary, tkNEWordBoundary, tkOption, tkHorizontalSpaceChar, tkNEHorizontalSpaceChar, tkVerticalSpaceChar, tkNEVerticalSpaceChar, tkLineBreak, tkPosixBracket, tkNEPosixBracket, tkProperty, tkNEProperty, tkNoBackTrack, tkKeepPattern, tkAheadMatch, tkAheadNoMatch, tkBehindMatch, tkBehindNoMatch, tkCombiningSequence, tkGoSub, tkGoSubName, tkGoSubRelative, tkIfMatch, tkIfMatchRef, tkGlobalPos, tkBranchReset, tkFail); TREOperator = (opEmply, opConcat, opUnion, opGroup, opLHead, opLTail, opQuest, opPlus, opStar, opBound, opLoop, opNoBackTrack, opKeepPattern, opAheadMatch, opAheadNoMatch, opBehindMatch, opBehindNoMatch, opGoSub, opIfMatch, opIfThen, opFail); TRENFAKind = (nkNormal, nkChar, nkEmpty, nkStar, nkPlus, nkBound, nkLoop, nkLoopExit, nkLoopEnd, nkGroupBegin, nkGroupEnd, nkKeepPattern, nkNoBackTrack, nkMatchEnd, nkEnd, nkGoSub, nkAheadMatch, nkAheadNoMatch, nkBehindMatch, nkBehindNoMatch, nkIfMatch, nkIfThen, nkFail); TRELoopKind = (lkGreedy, lkReluctant, lkSimpleReluctant, lkPossessive, lkAny, lkCombiningSequence); TREQuickSearch = class private FPattern: PWideChar; FPatternLen: Integer; FSkipTable: array [0 .. 255] of Integer; FTextTopP, FTextEndP: PWideChar; FTextLen: Integer; FCompiled: Boolean; FMatchP: PWideChar; FFindText: REString; FOptions: TRECompareOptions; procedure SetFindText(const Value: REString); procedure SetOptions(const Value: TRECompareOptions); function GetMatchPos: Integer; protected function IsMatch(AStr: PWideChar; AOptions: TRECompareOptions): Boolean; public procedure Clear; procedure Compile; function Exec(AStr: PWideChar; ATextLen: Integer): Boolean; function ExecNext: Boolean; property FindText: REString read FFindText write SetFindText; property MatchP: PWideChar read FMatchP; property MatchPos: Integer read GetMatchPos; property Options: TRECompareOptions read FOptions write SetOptions; end; TSkRegExp = class; TRECapture = class private FStartP: PWideChar; FMatched: Boolean; FEndP: PWideChar; procedure SetEndP(const Value: PWideChar); inline; public procedure Clear; property StartP: PWideChar read FStartP write FStartP; property EndP: PWideChar read FEndP write SetEndP; property Matched: Boolean read FMatched write FMatched; end; { マッチ結果を保持するクラス } TGroup = class private FRegExp: TSkRegExp; FGroupName: REString; FIndexBegin, FIndexEnd: Integer; FCapture: TRECapture; function GetIndex: Integer; function GetLength: Integer; function GetStrings: REString; function GetSuccess: Boolean; protected procedure Clear; procedure Reset; public constructor Create(ARegExp: TSkRegExp); destructor Destroy; override; procedure Assign(Source: TGroup); property GroupName: REString read FGroupName write FGroupName; property IndexBegin: Integer read FIndexBegin write FIndexBegin; property IndexEnd: Integer read FIndexEnd write FIndexEnd; property Strings: REString read GetStrings; property Index: Integer read GetIndex; property Length: Integer read GetLength; property Success: Boolean read GetSuccess; property Capture: TRECapture read FCapture; end; TGroupCollectionEnumerator = class private FIndex: Integer; FList: TObjectList; public constructor Create(AList: TObjectList); function GetCurrent: TGroup; function MoveNext: Boolean; property Current: TGroup read GetCurrent; end; TREHashItem = record Next: Pointer; Key: REString; Value: Integer; end; PREHashItem = ^TREHashItem; TREHashArray = array [0 .. 16] of PREHashItem; TIntDynArray = array of Integer; PIntDynArray = ^TIntDynArray; { すべてのマッチ結果を保持するクラス } TGroupCollection = class private FRegExp: TSkRegExp; FItems: TObjectList; FBuckets: TREHashArray; function GetItems(Index: Integer): TGroup; function GetNames(AName: REString): TGroup; function GetCount: Integer; inline; protected function Add(const AGroupName: REString; AEntry, AWayout: Integer): Integer; procedure AddGroupName(const AGroupName: REString; Index: Integer); procedure Clear; function HashOf(const Key: REString): Cardinal; function IsDuplicateGroupName(const AGroupName: REString): Boolean; procedure Reset; public constructor Create(ARegExp: TSkRegExp); destructor Destroy; override; procedure Assign(Source: TGroupCollection); function EnumIndexOfName(const AGroupName: REString): TIntDynArray; function GetEnumerator: TGroupCollectionEnumerator; function IndexOfName(const AGroupName: REString): Integer; function IndexOfMatchedName(const AGroupName: REString): Integer; property Count: Integer read GetCount; property Items[Index: Integer]: TGroup read GetItems; default; property Names[AName: REString]: TGroup read GetNames; end; TRECharMapRec = record Ch: UCS4Char; Next: Pointer; end; PRECharMapRec = ^TRECharMapRec; TRECharMap = class private FMap: array [0 .. 255] of Pointer; public destructor Destroy; override; procedure Add(Ch: UCS4Char); procedure Clear; function IsExists(AStr: PWideChar): Boolean; end; { 文字列の照合を行う基底クラス } TRECode = class private FRegExp: TSkRegExp; protected function GetLength: Integer; virtual; function GetCharLength: Integer; virtual; public constructor Create(ARegExp: TSkRegExp); function Compare(AStr: PWideChar): Integer; virtual; function CompareCode(Source: TRECode): Integer; virtual; function ExecRepeat(var AStr: PWideChar; IsStar: Boolean): Boolean; overload; virtual; function ExecRepeat(var AStr: PWideChar; AMin, AMax: Integer): Boolean; overload; virtual; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; virtual; // 文字クラスの最適化用。重複した比較をしないため。 function IsInclude(ACode: TRECode): Boolean; virtual; // この Code の末尾が ACode の先頭と一致すればTrue。繰り返しの最適化用 function IsOverlap(ACode: TRECode): Boolean; virtual; // 長さを持たない照合ならTrue {$IFDEF DEBUG} function GetDebugStr: REString; virtual; {$ENDIF} // エレメント数 property Length: Integer read GetLength; // 文字数 property CharLength: Integer read GetCharLength; end; TRECharCode = class(TRECode) private FStrings: REString; FSubP: PWideChar; FLength: Integer; FCharLength: Integer; FOptions: TREOptions; FCompareOptions: TRECompareOptions; FConvert: Boolean; protected function GetCharLength: Integer; override; function GetLength: Integer; override; public constructor Create(ARegExp: TSkRegExp; AWChar: UCS4Char; AOptions: TREOptions; AConvert: Boolean = False); function Compare(AStr: PWideChar): Integer; override; function CompareCode(Dest: TRECode): Integer; override; function ExecRepeat(var AStr: PWideChar; IsStar: Boolean): Boolean; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; function IsOverlap(ACode: TRECode): Boolean; override; function GetWChar: UCS4Char; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRELiteralCode = class(TRECode) private FStrings: REString; FSubP: PWideChar; FLength: Integer; FCharLength: Integer; FOptions: TREOptions; FCompareOptions: TRECompareOptions; protected function GetCharLength: Integer; override; function GetLength: Integer; override; public constructor Create(ARegExp: TSkRegExp; Str: UCS4String; AOptions: TREOptions); overload; constructor Create(ARegExp: TSkRegExp; Str: REString; AOptions: TREOptions); overload; function ExecRepeat(var AStr: PWideChar; IsStar: Boolean): Boolean; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; function IsOverlap(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRERangeCharCode = class(TRECode) private FStartWChar, FLastWChar: UCS4Char; FOptions: TREOptions; FCompareOptions: TRECompareOptions; public constructor Create(ARegExp: TSkRegExp; AStartWChar, ALastWChar: UCS4Char; AOptions: TREOptions); function Compare(AStr: PWideChar): Integer; override; function CompareCode(Dest: TRECode): Integer; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREAnyCharCode = class(TRECode) private FOptions: TREOptions; FCompareOptions: TRECompareOptions; public constructor Create(ARegExp: TSkRegExp; AOptions: TREOptions); function ExecRepeat(var AStr: PWideChar; IsStar: Boolean): Boolean; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREWordCharCode = class(TRECode) private FNegative: Boolean; public constructor Create(ARegExp: TSkRegExp; ANegative: Boolean); function Compare(AStr: PWideChar): Integer; override; function CompareCode(Dest: TRECode): Integer; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; function IsOverlap(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREDigitCharCode = class(TRECode) private FNegative: Boolean; public constructor Create(ARegExp: TSkRegExp; ANegative: Boolean); function Compare(AStr: PWideChar): Integer; override; function CompareCode(Dest: TRECode): Integer; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; function IsOverlap(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREHexDigitCharCode = class(TRECode) private FNegative: Boolean; public constructor Create(ARegExp: TSkRegExp; ANegative: Boolean); function Compare(AStr: PWideChar): Integer; override; function CompareCode(Dest: TRECode): Integer; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; function IsOverlap(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRESpaceCharCode = class(TRECode) private FNegative: Boolean; public constructor Create(ARegExp: TSkRegExp; ANegative: Boolean); function Compare(AStr: PWideChar): Integer; override; function CompareCode(Dest: TRECode): Integer; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; function IsOverlap(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREHorizontalSpaceCharCode = class(TRECode) private FNegative: Boolean; public constructor Create(ARegExp: TSkRegExp; ANegative: Boolean); function Compare(AStr: PWideChar): Integer; override; function CompareCode(Dest: TRECode): Integer; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; function IsOverlap(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREVerticalSpaceCharCode = class(TRECode) private FNegative: Boolean; public constructor Create(ARegExp: TSkRegExp; ANegative: Boolean); function Compare(AStr: PWideChar): Integer; override; function CompareCode(Dest: TRECode): Integer; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; function IsOverlap(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRELineBreakCharCode = class(TRECode) protected function GetCharLength: Integer; override; function GetLength: Integer; override; public constructor Create(ARegExp: TSkRegExp); function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; function IsOverlap(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRECharClassCode = class(TRECode) private FMap: TRECharMap; FNegative: Boolean; FCodeList: TObjectList; FOptions: TREOptions; FIsSimple: Boolean; public constructor Create(ARegExp: TSkRegExp; ANegative: Boolean; AOptions: TREOptions); destructor Destroy; override; function Add(AWChar: UCS4Char): Integer; overload; function Add(AStartWChar, ALastWChar: UCS4Char): Integer; overload; function Add(Value: TRECode): Integer; overload; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; function IsOverlap(ACode: TRECode): Boolean; override; procedure Rebuild; procedure Sort; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRECombiningSequence = class(TRECode) protected function GetCharLength: Integer; override; public function ExecRepeat(var AStr: PWideChar; IsStar: Boolean): Boolean; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREBoundaryCode = class(TRECode) private FNegative: Boolean; protected function GetCharLength: Integer; override; public constructor Create(ARegExp: TSkRegExp; ANegative: Boolean); function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREReferenceCode = class(TRECode) private FGroupIndex: Integer; FOptions: TREOptions; FCompareOptions: TRECompareOptions; protected function GetCharLength: Integer; override; public constructor Create(ARegExp: TSkRegExp; AGroupIndex: Integer; AOptions: TREOptions); overload; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRENamedReferenceCode = class(TRECode) private FGroupName: REString; FGroupIndexArray: TIntDynArray; FCount: Integer; FOptions: TREOptions; FCompareOptions: TRECompareOptions; protected function GetCharLength: Integer; override; public constructor Create(ARegExp: TSkRegExp; AGroupName: REString; AGroupIndexArray: TIntDynArray; AOptions: TREOptions); function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; procedure SetGroupIndexArray(AGroupIndexArray: TIntDynArray); {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRELineHeadCode = class(TRECode) private FOptions: TREOptions; protected function GetCharLength: Integer; override; public constructor Create(ARegExp: TSkRegExp; AOptions: TREOptions); function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRELineTailCode = class(TRECode) private FOptions: TREOptions; protected function GetCharLength: Integer; override; public constructor Create(ARegExp: TSkRegExp; AOptions: TREOptions); function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRETextHeadCode = class(TRECode) protected function GetCharLength: Integer; override; public function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRETextTailCode = class(TRECode) protected function GetCharLength: Integer; override; public function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TRETextEndCode = class(TRECode) protected function GetCharLength: Integer; override; public function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREPropertyCode = class(TRECode) private FUniCodeProperty: TUnicodeProperty; FNegative: Boolean; public constructor Create(ARegExp: TSkRegExp; AUnicodeProperty: TUnicodeProperty; ANegative: Boolean); function Compare(AStr: PWideChar): Integer; override; function CompareCode(Dest: TRECode): Integer; override; function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREGlobalPosCode = class(TRECode) protected function GetCharLength: Integer; override; public function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREIfThenReferenceCode = class(TRECode) private FGroupIndex: Integer; protected function GetCharLength: Integer; override; public constructor Create(ARegExp: TSkRegExp; const AGroupIndex: Integer); function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREIfThenNamedReferenceCode = class(TRECode) private FGroupName: REString; protected function GetCharLength: Integer; override; public constructor Create(ARegExp: TSkRegExp; const AGroupName: REString); function IsEqual(AStr: PWideChar; var Len: Integer): Boolean; override; function IsInclude(ACode: TRECode): Boolean; override; {$IFDEF DEBUG} function GetDebugStr: REString; override; {$ENDIF} end; TREBinCode = class(TRECode) private FOp: TREOperator; FLeft: TRECode; FRight: TRECode; FGroupIndex, FMin, FMax: Integer; FMatchKind: TRELoopKind; FGroupName: REString; FHasRecursion: Boolean; public constructor Create(ARegExp: TSkRegExp; AOp: TREOperator; ALeft, ARight: TRECode; AMin: Integer = 0; AMax: Integer = 0); overload; property Op: TREOperator read FOp; property Left: TRECode read FLeft; property Right: TRECode read FRight; property Min: Integer read FMin; property Max: Integer read FMax; property GroupIndex: Integer read FGroupIndex write FGroupIndex; property GroupName: REString read FGroupName write FGroupName; property MatchKind: TRELoopKind read FMatchKind write FMatchKind; property HasRecursion: Boolean read FHasRecursion write FHasRecursion; end; TRELexMode = (lmOptimize, lmNormal); TREContextKind = (ctNormal, ctCharClass, ctNegativeCharClass, ctQuote); { トークン先読み用バッファ } // 今のやり方はスマートじゃないのでもっといい方法があったら教えてください。 TRELexRec = record FStored: Boolean; FToken: TREToken; FOptions: TREOptions; FNewOptions: TREOptions; FP: PWideChar; FTokenStartP: PWideChar; FTopP: PWideChar; FWChar, FStartWChar, FLastWChar: UCS4Char; FMin, FMax, FLevel: Integer; FContext: TREContextKind; FUniCodeProperty: TUnicodeProperty; FConvert: Boolean; FNoBackTrack: Boolean; FGroupName: REString; FOptionList: TList; FIsQuote: Boolean; end; { 字句解析を行うクラス } TRELex = class private FRegExp: TSkRegExp; FToken: TREToken; FP: PWideChar; FTokenStartP: PWideChar; FTopP, FLastP: PWideChar; FWChar, FStartWChar, FLastWChar: UCS4Char; FMin, FMax, FLevel: Integer; FContext: TREContextKind; FUniCodeProperty: TUnicodeProperty; FConvert: Boolean; FIsQuote: Boolean; FGroupName: REString; FOptions: TREOptions; FNewOptions: TREOptions; FOptionList: TList; FPrevLex: array [0 .. 2] of TRELexRec; FPrevCount: Integer; protected procedure Error(const Msg: REString; const Prefix: REString = '...'); overload; procedure Error(const Msg: REString; APosition: Integer); overload; function GetErrorPositionString(APosition: Integer): REString; procedure SkipWhiteSpace; procedure LexCharClass; procedure LexPosixCharClass; procedure LexOption; function GetControlCode(var Len: Integer): UCS4Char; function GetDigit(var Len: Integer): Integer; function GetHexDigit(var Len: Integer): UCS4Char; function GetOctalDigit(var Len: Integer): UCS4Char; procedure LexBrace; procedure LexProperty(const CheckNegative: Boolean); procedure LexGroupName(const LastDelimiter: WideChar); procedure LexReference(const LastDelimiter: WideChar); procedure LexGoSub(const LastDelimiter: WideChar); procedure LexEscChar; procedure LexLeftPar; procedure PushOptions; procedure PopOptions; procedure UpdateOptions; procedure ClearOptionList; function GetRECompareOptions: TRECompareOptions; public constructor Create(ARegExp: TSkRegExp; const Expression: REString); destructor Destroy; override; procedure Assign(Source: TRELex); function GetCompileErrorPos: Integer; procedure CharNext(var P: PWideChar; const Len: Integer = 1); procedure CharPrev(var P: PWideChar; const Len: Integer = 1); procedure GetToken(Skip: Boolean = False); procedure PushToken; procedure Save; property Token: TREToken read FToken; property Min: Integer read FMin; property Max: Integer read FMax; property Level: Integer read FLevel; property Options: TREOptions read FOptions; property WChar: UCS4Char read FWChar; property StartWChar: UCS4Char read FStartWChar; property LastWChar: UCS4Char read FLastWChar; property UnicodeProperty: TUnicodeProperty read FUniCodeProperty; property Convert: Boolean read FConvert; property TokenStartP: PWideChar read FTokenStartP; property GroupName: REString read FGroupName; end; // 後方参照のエラー処理用 TReferenceErrorRec = record ErrorPos: Integer; AObject: Pointer; case IsRelative: Boolean of True: (RelativeGourpIndex: Integer); False: (GroupIndex: Integer); end; PReferenceErrorRec = ^TReferenceErrorRec; { 構文解析を行い構文木を作るクラス } TREParser = class private FRegExp: TSkRegExp; FLex: TRELex; FCurrentGroup: Integer; FGroupLevel: Integer; FGroupCount: Integer; FHasRecursion: Boolean; FReferenceErrorList: TREStrings; FGoSubErrorList: TREStrings; FGroupStack: TStack; protected function NewBinCode(AOperator: TREOperator; ALeft, ARight: TRECode; AMin: Integer = 0; AMax: Integer = 0): TRECode; function NewCharClassCode(ANegative: Boolean): TRECode; function Term: TRECode; function Factor: TRECode; function Primay: TRECode; function RegExpr: TRECode; public constructor Create(ARegExp: TSkRegExp; const Expression: REString); destructor Destroy; override; procedure Parse; end; { MFA の状態を保持するクラス } TRENFAState = class private FKind: TRENFAKind; FCode: TRECode; FTransitTo: Integer; FNext: TRENFAState; FGroupIndex: Integer; FMin: Integer; FMax: Integer; FMatchKind: TRELoopKind; FExtendTo: Integer; FHasRecursion: Boolean; {$IFDEF DEBUG} FIndex: Integer; {$ENDIF} public {$IFDEF DEBUG} property Index: Integer read FIndex write FIndex; {$ENDIF} property Code: TRECode read FCode write FCode; property TransitTo: Integer read FTransitTo write FTransitTo; property Next: TRENFAState read FNext write FNext; property Kind: TRENFAKind read FKind write FKind; property GroupIndex: Integer read FGroupIndex write FGroupIndex; property MatchKind: TRELoopKind read FMatchKind write FMatchKind; property Min: Integer read FMin write FMin; property Max: Integer read FMax write FMax; property ExtendTo: Integer read FExtendTo write FExtendTo; property HasRecursion: Boolean read FHasRecursion write FHasRecursion; {$IFDEF DEBUG} function GetString: REString; {$ENDIF} end; { NFA を生成するクラス } TRENFA = class private FRegExp: TSkRegExp; FStateList: TList; FBEntryState, FBExitState: Integer; FEntryStack, FExitStack: TList; FEntryStackIndex, FExitStateIndex: Integer; FStateStack: TList; FStateStackIndex: Integer; FGroupCount: Integer; protected function GetNumber: Integer; procedure AddTransition(AKind: TRENFAKind; ATransFrom, ATransTo: Integer; ACode: TRECode; AMin: Integer = 0; AMax: Integer = 0); procedure GenerateStateList(ACode: TRECode; AEntry, AWayout: Integer); procedure ReplaceCode(var OldCode, NewCode: TRECode); procedure PushState(AEntry, AWayout, ANewEntry, ANewWayout: Integer); procedure PopState; function GetRealState: Integer; public constructor Create(ARegExp: TSkRegExp); destructor Destroy; override; procedure Compile; end; TREMatchExplosionStateRec = record NFACode: TRENFAState; Next: Pointer; end; PREMatchExplosionStateRec = ^TREMatchExplosionStateRec; TREBackTrackStackRec = record NFACode: TRENFAState; Str: PWideChar; end; PREBackTrackStackRec = ^TREBackTrackStackRec; {$IFDEF CONDITIONALEXPRESSIONS} {$IF CompilerVersion >= 16.0} PPointerList = ^TPointerList; TPointerList = array[0..MaxListSize - 1] of Pointer; {$IFEND} {$ENDIF} { バックトラック用のステートを保存するクラス } TREStack = class private FRegExp: TSkRegExp; FCount, FSize: Integer; FStat, FGroup: PPointerList; FCheckMatchExplosion: Boolean; protected procedure Extend(ASize: Integer); public constructor Create(ARegExp: TSkRegExp; ACheckMatchExplosion: Boolean = True); destructor Destroy; override; procedure Clear; function Count: Integer; inline; function Peek: TRENFAState; function Index: Integer; inline; procedure Push(NFACode: TRENFAState; AStr: PWideChar; IsPushGroup: Boolean); overload; procedure Pop(var NFACode: TRENFAState; var AStr: PWideChar); procedure Remove(const AIndex: Integer); end; TRELeadCode = class private FCode: TRECode; FOffset: Integer; FIsBehindMatch: Boolean; public property Code: TRECode read FCode write FCode; property Offset: Integer read FOffset write FOffset; property IsBehindMatch: Boolean read FIsBehindMatch write FIsBehindMatch; end; TRELeadCodeCollection = class private FList: TObjectList; function GetItem(Index: Integer): TRELeadCode; function GetCount: Integer; public constructor Create; destructor Destroy; override; procedure Clear; function Add(Value: TRECode; AOffset: Integer; ABehindMatch: Boolean): Integer; procedure Delete(Index: Integer); property Count: Integer read GetCount; property Items[Index: Integer]: TRELeadCode read GetItem; default; end; TRELeadCharMode = (lcmNone, lcmFirstLiteral, lcmSimple, lcmTextTop, lcmLineTop, lcmLastLiteral, lcmHasLead, lcmMap); { 従来型NFAバックトラック照合エンジンクラス NFAと言っても状態機械ではなく、NFA状態をバイトコードとみなして処理している。 } TREMatchEngine = class private FRegExp: TSkRegExp; FGroups: TGroupCollection; FStateList: TList; FLeadCode: TRELeadCodeCollection; FTailCode: TObjectList; FLeadStrings: TREQuickSearch; FIsNotSimplePattern: Boolean; FIsPreMatch: Boolean; FLeadCharMode: TRELeadCharMode; FMap: TRECharMap; FPreMatchLength: Integer; FIsBehindMatch: Boolean; FSpecialMatchStack: TList; protected procedure GenerateLeadCode; procedure GenerateTailCode; function MatchCore(var NFACode: TRENFAState; var AStr: PWideChar) : Boolean; overload; function MatchCore(var NFACode, EndCode: TRENFAState; var AStr: PWideChar; ACheckExplosion: Boolean = True): Boolean; overload; function MatchEntry(var AStr: PWideChar): Boolean; function MatchRecursion(var NFACode: TRENFAState; EndCode: TRENFAState; var AStr: PWideChar): Boolean; function MatchPrim(NFACode: TRENFAState; var AStr: PWideChar; Stack: TREStack): TRENFAState; procedure OptimizeLoop; function IsLeadStrings(var AStr: PWideChar): Boolean; procedure SetupLeadStrings; {$IFDEF DEBUG} {$IFDEF SHOW_MATCH_PROCESS} procedure MatchProcess(NFACode: TRENFAState; AStr: PWideChar); {$ENDIF} {$ENDIF} public constructor Create(ARegExp: TSkRegExp); destructor Destroy; override; function Match(AStr: PWideChar): Boolean; procedure Optimize; end; TRECharTypeFunc = function(W: UCS4Char): Boolean; TSkRegExpReplaceFunction = function(ARegExp: TSkRegExp): REString of object; TSkRegExpReplaceEvent = procedure(Sender: TObject; var ReplaceWith: REString) of object; TSkRegExp = class private FMatchEngine: TREMatchEngine; FCode: TRECode; FCodeList: TList; FBinCodeList: TList; FCompiled: Boolean; FTextTopP, FTextEndP: PWideChar; FMatchTopP, FMatchEndP: PWideChar; FEOL: REString; FEOLHeadP, FEOLTailP: PWideChar; FEOLLen: Integer; FGroups: TGroupCollection; {$IFDEF DEBUG} {$IFDEF SHOW_MATCH_PROCESS} FMatchProcess: TREStrings; {$ENDIF} {$ENDIF} FInputString: REString; FExpression: REString; FOptions: TREOptions; {$IFDEF CHECK_MATCH_EXPLOSION} FMatchExplosionState: array of PREMatchExplosionStateRec; {$ENDIF} // FStateList: TList; FEntryState, FExitState: Integer; FOnMatch: TNotifyEvent; FLexMode: TRELexMode; FGlobalStartP, FGlobalEndP: PWideChar; FSuccess: Boolean; FReplaceFunc: TSkRegExpReplaceFunction; FOnReplace: TSkRegExpReplaceEvent; procedure SetExpression(const Value: REString); procedure SetEOL(const Value: REString); procedure SetInputString(const Value: REString); function GetGroupCount: Integer; function GetVersion: REString; function GetOptions(const Index: Integer): Boolean; procedure SetOptions(const Index: Integer; const Value: Boolean); function GetMatchStr(Index: Integer): REString; function GetMatchLen(Index: Integer): Integer; function GetMatchPos(Index: Integer): Integer; function GetNamedGroupStr(Name: REString): REString; function GetNamedGroupPos(Name: REString): Integer; function GetNamedGroupLen(Name: REString): Integer; {$IFDEF JapaneseExt} procedure SetIgnoreZenHan(const Value: Boolean); function GetIgnoreZenHan: Boolean; {$ENDIF} function GetDefineCharClassLegacy: Boolean; procedure SetDefineCharClassLegacy(const Value: Boolean); procedure SetLexMode(const Value: TRELexMode); inline; function GetGroupNameFromIndex(Index: Integer): REString; function GetIndexFromGroupName(Name: REString): Integer; protected IsWord: TRECharTypeFunc; IsDigit: TRECharTypeFunc; IsSpace: TRECharTypeFunc; procedure ClearCodeList; { FBinCodeListをクリアする。 FBinCodeListはTREBinCodeのリスト。 NFAを生成した後は不要なので、生成後呼び出してクリアする。 } procedure ClearBinCodeList; { 改行があった場合の位置補正用。 AStrがFEOLと等しければTRUE。LenにはFEOLの長さが返る。 等しくなければFALSEを返す。Lenの値はパラメータのまま。 } function IsEOL(AStr: PWideChar; out Len: Integer): Boolean; procedure ClearStateList; {$IFDEF CHECK_MATCH_EXPLOSION} procedure ClearExplosionState; {$ENDIF} procedure Error(const ErrorMes: REString); function MatchCore(AStr: PWideChar): Boolean; procedure DoReplaceFunc(Sender: TObject; var ReplaceWith: REString); public constructor Create; destructor Destroy; override; { 正規表現を構文解析し、NFAを生成する } procedure Compile; { 最初のマッチを実行する } function Exec(const AInputStr: REString): Boolean; { 次のマッチを実行する } function ExecNext: Boolean; { AOffsetの位置から AMaxLenght の範囲でマッチを実行する。AMaxLengthを指定した場合の動作に注意。ヘルプ参照 } function ExecPos(AOffset: Integer = 1; AMaxLength: Integer = 0): Boolean; function Substitute(const ATemplate: REString): REString; function Replace(const Input, Replacement: REString; Count: Integer = 0; AOffset: Integer = 1): REString; overload; function Replace(const Input: REString; AReplaceFunc: TSkRegExpReplaceFunction; Count: Integer = 0; AOffset: Integer = 1): REString; overload; procedure Split(const Input: REString; APieces: TREStrings; Count: Integer = 0; AOffset: Integer = 1); class function RegIsMatch(const ARegExpStr, AInputStr: REString; AOptions: TREOptions = []): Boolean; class function RegMatch(const ARegExpStr, AInputStr: REString; AMatches: TREStrings; AOptions: TREOptions = []): Boolean; class function RegReplace(const ARegExpStr, AInputStr, AReplaceStr: REString; AOptions: TREOptions = []): REString; overload; class function RegReplace(const ARegExpStr, AInputStr:REString; AReplaceFunc: TSkRegExpReplaceFunction; AOptions: TREOptions = []): REString; overload; class procedure RegSplit(const ARegExpStr, AInputStr: REString; APieces: TREStrings; AOptions: TREOptions = []); class function DecodeEscape(const S: REString): REString; class function EncodeEscape(const Str: REString): REString; {$IFDEF DEBUG} procedure DumpParse(TreeView: TTreeView); procedure DumpNFA(ADest: TStrings); function DumpLeadCode: REString; procedure DumpMatchProcess(ADest: TStrings); {$ENDIF} { 正規表現の文字列 } property Expression: REString read FExpression write SetExpression; { 改行文字を設定。この設定はマッチ位置の補正用のみに使われる。 マッチ時の改行文字の処理にはIsLineSeparatorを使う。 } property EOL: REString read FEOL write SetEOL; { グループの数を返す。グループは 0 から GroupCount まで。 } property GroupCount: Integer read GetGroupCount; { 検索対象の文字列 } property InputString: REString read FInputString write SetInputString; // 正規表現オプション property Options: TREOptions read FOptions write FOptions; property IgnoreCase: Boolean index 0 read GetOptions write SetOptions; property MultiLine: Boolean index 1 read GetOptions write SetOptions; property NamedGroupOnly: Boolean index 2 read GetOptions write SetOptions; property SingleLine: Boolean index 3 read GetOptions write SetOptions; property Extended: Boolean index 4 read GetOptions write SetOptions; {$IFDEF JapaneseExt} property IgnoreWidth: Boolean index 5 read GetOptions write SetOptions; property IgnoreKana: Boolean index 6 read GetOptions write SetOptions; property IgnoreZenHan: Boolean read GetIgnoreZenHan write SetIgnoreZenHan; {$ENDIF} property DefinedCharClassLegacy: Boolean read GetDefineCharClassLegacy write SetDefineCharClassLegacy; property Groups: TGroupCollection read FGroups; property Match[Index: Integer]: REString read GetMatchStr; property MatchPos[Index: Integer]: Integer read GetMatchPos; property MatchLen[Index: Integer]: Integer read GetMatchLen; property NamedGroup[Name: REString]: REString read GetNamedGroupStr; property NamedGroupPos[Name: REString]: Integer read GetNamedGroupPos; property NamedGroupLen[Name: REString]: Integer read GetNamedGroupLen; property GroupNameFromIndex[Index: Integer]: REString read GetGroupNameFromIndex; property IndexFromGroupName[Name: REString]: Integer read GetIndexFromGroupName; property Version: REString read GetVersion; property LexMode: TRELexMode read FLexMode write SetLexMode; // マッチが成功したら True property Success: Boolean read FSuccess; // Event property OnMatch: TNotifyEvent read FOnMatch write FOnMatch; property OnReplace: TSkRegExpReplaceEvent read FOnReplace write FOnReplace; end; function RegIsMatch(const ARegExpStr, AInputStr: REString; AOptions: TREOptions = []): Boolean; inline; function RegMatch(const ARegExpStr, AInputStr: REString; AMatches: TREStrings; AOptions: TREOptions = []): Boolean; inline; function RegReplace(const ARegExpStr, AInputStr, AReplaceStr: REString; AOptions: TREOptions = []): REString; inline; overload; function RegReplace(const ARegExpStr, AInputStr:REString; AReplaceFunc: TSkRegExpReplaceFunction; AOptions: TREOptions = []): REString; overload; procedure RegSplit(const ARegExpStr, AInputStr: REString; APieces: TREStrings; AOptions: TREOptions = []); inline; function DecodeEscape(const S: REString): REString; inline; function EncodeEscape(const Str: REString): REString; inline; {$IFDEF DEBUG} function REStrLJComp(AStr, ASubStr: PWideChar; ALen: Integer; AOptions: TRECompareOptions): Integer; function RECompareString(SourceP: PWideChar; DestP: PWideChar; DestLen: Integer; Options: TRECompareOptions): Integer; function REStrPos(AStr: PWideChar; ALen: Integer; APattern: PWideChar; APatternLen: Integer; AOptions: TRECompareOptions): PWideChar; function REStrLComp(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer; function REStrLIComp(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer; function ToUCS4Char(AStr: PWideChar): UCS4Char; inline; {$ENDIF} const SkRegExpDefaultOptions: TREOptions = []; implementation uses Windows; const CONST_VERSION = '1.3.4'; CONST_LoopMax = MaxInt; CONST_LoopLimit = $7FFF; CONST_REStack_Size = 128; DefaultEOL: REString = #$000D#$000A; CONST_WIDE_HAT = $FF3E; CONST_WIDE_DOLL = $FF04; {$IFDEF JapaneseExt} Dakuten = $FF9E; Handakuten = $FF9F; HanKanaToZenTable: array [$FF61 .. $FF9F, 0 .. 2] of UCS4Char = (($3002, $0, $0), ($300C, $0, $0), ($300D, $0, $0), ($3001, $0, $0), ($30FB, $0, $0), ($30F2, $0, $0), ($30A1, $0, $0), ($30A3, $0, $0), ($30A5, $0, $0), ($30A7, $0, $0), ($30A9, $0, $0), ($30E3, $0, $0), ($30E5, $0, $0), ($30E7, $0, $0), ($30C3, $0, $0), ($30FC, $0, $0), ($30A2, $0, $0), ($30A4, $0, $0), ($30A6, $30F4, $0), ($30A8, $0, $0), ($30AA, $0, $0), ($30AB, $30AC, $0), ($30AD, $30AE, $0), ($30AF, $30B0, $0), ($30B1, $30B2, $0), ($30B3, $30B4, $0), ($30B5, $30B6, $0), ($30B7, $30B8, $0), ($30B9, $30BA, $0), ($30BB, $30BC, $0), ($30BD, $30BE, $0), ($30BF, $30C0, $0), ($30C1, $30C2, $0), ($30C4, $30C5, $0), ($30C6, $30C7, $0), ($30C8, $30C9, $0), ($30CA, $0, $0), ($30CB, $0, $0), ($30CC, $0, $0), ($30CD, $0, $0), ($30CE, $0, $0), ($30CF, $30D0, $30D1), ($30D2, $30D3, $30D4), ($30D5, $30D6, $30D7), ($30D8, $30D9, $30DA), ($30DB, $30DC, $30DD), ($30DE, $0, $0), ($30DF, $0, $0), ($30E0, $0, $0), ($30E1, $0, $0), ($30E2, $0, $0), ($30E4, $0, $0), ($30E6, $0, $0), ($30E8, $0, $0), ($30E9, $0, $0), ($30EA, $0, $0), ($30EB, $0, $0), ($30EC, $0, $0), ($30ED, $0, $0), ($30EF, $0, $0), ($30F3, $0, $0), ($309B, $0, $0), ($309C, $0, $0)); HanAnkToZenTable: array [$0020 .. $007E] of UCS4Char = ($3000, $FF01, $FF02, $FF03, $FF04, $FF05, $FF06, $FF07, $FF08, $FF09, $FF0A, $FF0B, $FF0C, $FF0D, $FF0E, $FF0F, $FF10, $FF11, $FF12, $FF13, $FF14, $FF15, $FF16, $FF17, $FF18, $FF19, $FF1A, $FF1B, $FF1C, $FF1D, $FF1E, $FF1F, $FF20, $FF21, $FF22, $FF23, $FF24, $FF25, $FF26, $FF27, $FF28, $FF29, $FF2A, $FF2B, $FF2C, $FF2D, $FF2E, $FF2F, $FF30, $FF31, $FF32, $FF33, $FF34, $FF35, $FF36, $FF37, $FF38, $FF39, $FF3A, $FF3B, $FFE5, $FF3D, $FF3E, $FF3F, $FF40, $FF41, $FF42, $FF43, $FF44, $FF45, $FF46, $FF47, $FF48, $FF49, $FF4A, $FF4B, $FF4C, $FF4D, $FF4E, $FF4F, $FF50, $FF51, $FF52, $FF53, $FF54, $FF55, $FF56, $FF57, $FF58, $FF59, $FF5A, $FF5B, $FF5C, $FF5D, $FF5E); ZenHiraganaToKatakanaTable: array [$3041 .. $3094] of UCS4Char = ($30A1, $30A2, $30A3, $30A4, $30A5, $30A6, $30A7, $30A8, $30A9, $30AA, $30AB, $30AC, $30AD, $30AE, $30AF, $30B0, $30B1, $30B2, $30B3, $30B4, $30B5, $30B6, $30B7, $30B8, $30B9, $30BA, $30BB, $30BC, $30BD, $30BE, $30BF, $30C0, $30C1, $30C2, $30C3, $30C4, $30C5, $30C6, $30C7, $30C8, $30C9, $30CA, $30CB, $30CC, $30CD, $30CE, $30CF, $30D0, $30D1, $30D2, $30D3, $30D4, $30D5, $30D6, $30D7, $30D8, $30D9, $30DA, $30DB, $30DC, $30DD, $30DE, $30DF, $30E0, $30E1, $30E2, $30E3, $30E4, $30E5, $30E6, $30E7, $30E8, $30E9, $30EA, $30EB, $30EC, $30ED, $30EE, $30EF, $30F0, $30F1, $30F2, $30F3, $30F4); {$ENDIF} function RegIsMatch(const ARegExpStr, AInputStr: REString; AOptions: TREOptions): Boolean; begin Result := TSkRegExp.RegIsMatch(ARegExpStr, AInputStr, AOptions); end; function RegMatch(const ARegExpStr, AInputStr: REString; AMatches: TREStrings; AOptions: TREOptions = []): Boolean; begin Result := TSkRegExp.RegMatch(ARegExpStr, AInputStr, AMatches, AOptions); end; function RegReplace(const ARegExpStr, AInputStr, AReplaceStr: REString; AOptions: TREOptions = []): REString; begin Result := TSkRegExp.RegReplace(ARegExpStr, AInputStr, AReplaceStr, AOptions); end; function RegReplace(const ARegExpStr, AInputStr:REString; AReplaceFunc: TSkRegExpReplaceFunction; AOptions: TREOptions = []): REString; begin Result := TSkRegExp.RegReplace(ARegExpStr, AInputStr, AReplaceFunc, AOptions); end; procedure RegSplit(const ARegExpStr, AInputStr: REString; APieces: TREStrings; AOptions: TREOptions = []); begin TSkRegExp.RegSplit(ARegExpStr, AInputStr, APieces, AOptions); end; function DecodeEscape(const S: REString): REString; begin Result := TSkRegExp.DecodeEscape(S); end; function EncodeEscape(const Str: REString): REString; begin Result := TSkRegExp.EncodeEscape(Str); end; // ==========サポートルーチン========== function Max(a, b: Integer): Integer; inline; begin if a > b then Result := a else Result := b; end; function Min(a, b: Integer): Integer; inline; begin if a < b then Result := a else Result := b; end; {$IFNDEF UNICODE} function IsLeadChar(C: WideChar): Boolean; inline; begin Result := (C >= #$D800) and (C <= #$DFFF); end; {$ENDIF} function REOptionsToRECompareOptions(AREOptions: TREOptions): TRECompareOptions; begin Result := []; if roIgnoreCase in AREOptions then Include(Result, coIgnoreCase); if roIgnoreKana in AREOptions then Include(Result, coIgnoreKana); if roIgnoreWidth in AREOptions then Include(Result, coIgnoreWidth); end; // ==========日本語処理用ルーチン========== {$IFDEF JapaneseExt} function IsDaku(S: PWideChar): Boolean; inline; begin Result := ((S + 1)^ = #$FF9E) and (HanKanaToZenTable[UCS4Char(S^), 1] <> 0); end; function IsHanDaku(S: PWideChar): Boolean; inline; begin Result := ((S + 1)^ = #$FF9F) and (HanKanaToZenTable[UCS4Char(S^), 2] <> 0); end; function IsHalfKatakana(S: UCS4Char): Boolean; inline; overload; begin Result := (S >= $FF61) and (S <= $FF9F); end; function IsHalfKatakana(S: WideChar): Boolean; inline; overload; begin Result := (S >= #$FF61) and (S <= #$FF9F); end; function IsWideHiragana(S: PWideChar): Boolean; inline; begin Result := (S^ >= #$3041) and (S^ <= #$3094); end; function IsWideKatakana(Ch: WideChar): Boolean; inline; begin Result := (Ch >= #$30A1) and (Ch <= #$30FE); end; function IsHalfAnk(S: UCS4Char): Boolean; inline; overload; begin Result := (S >= $20) and (S <= $7E); end; function IsHalfAnk(S: WideChar): Boolean; inline; overload; begin Result := (S >= #$0020) and (S <= #$007E); end; function IsWideAnk(Ch: WideChar): Boolean; inline; begin Result := (Ch = #$3000) or (Ch = #$FFE5) or ((Ch >= #$FF01) and (Ch <= #$FF5E)) end; function ConvertString(const S: REString; Flag: DWORD): REString; var L: Integer; begin L := Length(S); if L = 0 then begin Result := ''; Exit; end; SetLength(Result, L * 2); {$IFDEF UNICODE} L := LCMapString(GetUserDefaultLCID, Flag, PWideChar(S), Length(S), PWideChar(Result), Length(Result)); {$ELSE} L := LCMapStringW(GetUserDefaultLCID, Flag, PWideChar(S), Length(S), PWideChar(Result), Length(Result)); {$ENDIF} SetLength(Result, L); end; function ToWide(const S: REString): REString; inline; begin Result := ConvertString(S, LCMAP_FULLWIDTH); end; function ToHalf(const S: REString): REString; inline; begin Result := ConvertString(S, LCMAP_HALFWIDTH); end; function ToHiragana(const S: REString): REString; inline; begin Result := ConvertString(S, LCMAP_HIRAGANA); end; function ToKatakana(const S: REString): REString; inline; begin Result := ConvertString(S, LCMAP_KATAKANA); end; {$ENDIF} // ==========文字入出力用ルーチン========== function ToUCS4Char(AStr: PWideChar): UCS4Char; inline; begin if (AStr^ >= #$D800) and (AStr^ <= #$DBFF) then Result := ((WORD(AStr^) and $03FF) shl 10) + ((WORD((AStr + 1)^) and $03FF) + $10000) else Result := UCS4Char(AStr^); end; function UCS4CharToString(AWChar: UCS4Char): REString; inline; var H, L: Cardinal; begin if AWChar >= $10000 then begin H := $D800 + (AWChar - $10000) shr 10; L := $DC00 + (AWChar and $03FF); Result := WideChar(H) + WideChar(L); end else Result := WideChar(AWChar); end; function RECharArrayToString(CharArray: UCS4String): REString; var I: Integer; begin for I := 0 to Length(CharArray) - 1 do Result := Result + UCS4CharToString(CharArray[I]); end; function GetREChar(AStr: PWideChar; var Len: Integer; Options: TRECompareOptions): UCS4Char; var Buf: array [0 .. 2] of WideChar; begin Len := 0; if coIgnoreCase in Options then begin if (AStr^ >= #$D800) and (AStr^ <= #$DBFF) then begin Buf[0] := AStr^; Buf[1] := (AStr + 1)^; Buf[2] := #0000; CharUpperBuffW(@Buf, 2); Result := ((WORD(Buf[0]) and $03FF) shl 10) + ((WORD(Buf[1]) and $03FF) + $10000); Len := 2; end else begin Buf[0] := AStr^; Buf[1] := #0000; Buf[2] := #0000; CharUpperBuffW(@Buf, 1); Result := UCS4Char(Buf[0]); Len := 1; end; end else begin if (AStr^ >= #$D800) and (AStr^ <= #$DBFF) then begin Result := ((WORD(AStr^) and $03FF) shl 10) + ((WORD((AStr + 1)^) and $03FF) + $10000); Len := 2; end else begin Result := UCS4Char(AStr^); Len := 1; end; end; {$IFDEF JapaneseExt} if coIgnoreWidth in Options then begin if IsHalfAnk(Result) then Result := HanAnkToZenTable[Result] else if IsHalfKatakana(Result) then begin if IsDaku(AStr) then begin Result := HanKanaToZenTable[Result, 1]; Len := 2; end else if IsHanDaku(AStr) then begin Result := HanKanaToZenTable[Result, 2]; Len := 2; end else Result := HanKanaToZenTable[Result, 0]; end; end; if coIgnoreKana in Options then begin if ((Result >= $3041) and (Result <= $3094)) then Result := ZenHiraganaToKatakanaTable[Result] else if (Result = $309D) then Result := $30FD else if Result = $309E then Result := $30FE end; {$ENDIF} end; function ConvertREString(const S: REString; AOptions: TRECompareOptions) : REString; var P: PWideChar; I, Len: Integer; begin P := PWideChar(S); Len := Length(S); if coIgnoreCase in AOptions then CharUpperBuffW(P, Len); SetLength(Result, Len); if coIgnoreWidth in AOptions then begin I := 1; while I <= Len do begin if coIgnoreWidth in AOptions then begin if IsHalfAnk(P^) then Result[I] := WideChar(HanAnkToZenTable[UCS4Char(P^)]) else if IsHalfKatakana(P^) then begin if IsDaku(P) then begin Result[I] := WideChar(HanKanaToZenTable[UCS4Char(P^), 1]); Inc(P); end else if IsHanDaku(P) then begin Result[I] := WideChar(HanKanaToZenTable[UCS4Char(P^), 2]); Inc(P); end else Result[I] := WideChar(HanKanaToZenTable[UCS4Char(P^), 0]); end else Result[I] := P^; if coIgnoreKana in AOptions then begin if (P^ >= #$3041) and (P^ <= #$3094) then Result[I] := WideChar(ZenHiraganaToKatakanaTable[UCS4Char(P^)]) else if (P^ = #$309D) then Result[I] := #$30FD else if P^ = #$309E then Result[I] := #$30FE else Result[I] := P^; end; end; Inc(P); Inc(I); end; end else Move(P^, Result[1], Len * Sizeof(WideChar)); end; // ==========文字種判定用ルーチン========== function IsLineSeparator(P: WideChar): Boolean; inline; begin Result := (P = #$000A) or (P = #$000B) or (P = #$000C) or (P = #$000D) or (P = #$0085) or (P = #$2020) or (P = #$2029); end; function IsAnkWord(P: PWideChar): Boolean; inline; overload; begin Result := (P^ = '_') or ((P^ >= 'A') and (P^ <= 'Z')) or ((P^ >= 'a') and (P^ <= 'z')) or ((P^ >= '0') and (P^ <= '9')); end; function IsAnkWord(W: UCS4Char): Boolean; inline; overload; begin Result := (W = UCS4Char('_')) or ((W >= UCS4Char('A')) and (W <= UCS4Char('Z') )) or ((W >= UCS4Char('a')) and (W <= UCS4Char('z'))) or ((W >= UCS4Char('0')) and (W <= UCS4Char('9'))); end; function IsAnkDigit(P: PWideChar): Boolean; inline; overload; begin Result := (P^ >= '0') and (P^ <= '9'); end; function IsAnkDigit(W: UCS4Char): Boolean; inline; overload; begin Result := (W >= UCS4Char('0')) and (W <= UCS4Char('9')); end; function IsAnkSpace(P: PWideChar): Boolean; inline; overload; begin Result := (P^ = #$0009) or (P^ = #$000A) or (P^ = #$000B) or (P^ = #$000C) or (P^ = #$000D) or (P^ = #$00020); end; function IsAnkSpace(W: UCS4Char): Boolean; inline; overload; begin Result := (W = $9) or (W = $A) or (W = $B) or (W = $C) or (W = $D) or (W = $20); end; function IsHexDigit(Ch: UCS4Char): Boolean; inline; overload; begin Result := ((Ch >= $30) and (Ch <= $39)) or ((Ch >= $41) and (Ch <= $46)) or ((Ch >= $61) and (Ch <= $66)); end; function IsHorizontalWhiteSpace(P: PWideChar): Boolean; inline; overload; begin case P^ of #$0009, #$0020, #$00A0, #$1680, #$180E, #$2000 .. #$200A, #$202F, #$205F, #$3000: Result := True else Result := False; end; end; function IsHorizontalWhiteSpace(W: UCS4Char): Boolean; inline; overload; begin case W of 0009, $0020, $00A0, $1680, $180E, $2000 .. $200A, $202F, $205F, $3000: Result := True else Result := False; end; end; function IsVerticalWhiteSpace(P: PWideChar): Boolean; inline; overload; begin case P^ of #$000A, #$000B, #$000C, #$000D, #$0085, #$2028, #$2029: Result := True else Result := False; end; end; function IsVerticalWhiteSpace(W: UCS4Char): Boolean; inline; overload; begin case W of $000A, $000B, $000C, $000D, $0085, $2028, $2029: Result := True else Result := False; end; end; // ==========文字列検索用ルーチン========== {$IFDEF UNICODE} function REStrLComp(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer; inline; begin Result := StrLComp(Str1, Str2, MaxLen); end; {$ELSE UNICODE} function REStrLComp(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer; var I: Cardinal; begin Result := 0; I := 1; while I <= MaxLen do begin if Str1^ <> Str2^ then begin Result := Ord(Str1^) - Ord(Str2^); Exit; end; Inc(Str1); Inc(Str2); Inc(I); end; end; {$ENDIF UNICODE} function REStrLJComp(AStr, ASubStr: PWideChar; ALen: Integer; AOptions: TRECompareOptions): Integer; var W1, W2: Integer; L1, L2: Integer; I: Integer; begin Result := 0; I := 1; while I <= ALen do begin W1 := GetREChar(AStr, L1, AOptions); W2 := GetREChar(ASubStr, L2, AOptions); if W1 <> W2 then begin Result := W1 - W2; Exit; end; Inc(AStr, L1); Inc(ASubStr, L2); Inc(I, L1); end; end; function REStrLIComp(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer; inline; begin {$IFDEF UNICODE} Result := AnsiStrLIComp(Str1, Str2, MaxLen); {$ELSE} Result := REStrLJComp(Str1, Str2, MaxLen, [coIgnoreCase]) {$ENDIF} end; { AStr: 検索対象の文字列 ASubStr: 検索文字列 ALen: 検索文字列の文字数 AOptions: 検索オプション 大文字小文字を区別しない 全角半角を区別しない ひらがなカタカナを区別しない } function RECompareString(SourceP: PWideChar; DestP: PWideChar; DestLen: Integer; Options: TRECompareOptions): Integer; begin if (coIgnoreWidth in Options) or (coIgnoreKana in Options) then Result := REStrLJComp(SourceP, DestP, DestLen, Options) else if coIgnoreCase in Options then Result := REStrLIComp(SourceP, DestP, DestLen) else if DestLen = 1 then Result := Ord(SourceP^) - Ord(DestP^) else Result := REStrLComp(SourceP, DestP, DestLen); end; function REStrPos(AStr: PWideChar; ALen: Integer; APattern: PWideChar; APatternLen: Integer; AOptions: TRECompareOptions): PWideChar; var TextEndP: PWideChar; begin Result := nil; TextEndP := AStr + ALen; if (coIgnoreWidth in AOptions) or (coIgnoreKana in AOptions) then begin while AStr <= TextEndP do begin if REStrLJComp(AStr, APattern, APatternLen, AOptions) = 0 then begin Result := AStr; Exit; end; Inc(AStr); end; end else if coIgnoreCase in AOptions then begin while AStr <= TextEndP do begin if REStrLIComp(AStr, APattern, APatternLen) = 0 then begin Result := AStr; Exit; end; Inc(AStr); end; end else begin while AStr <= TextEndP do begin if REStrLComp(AStr, APattern, APatternLen) = 0 then begin Result := AStr; Exit; end; Inc(AStr); end; end; end; // ==========文字位置移動用ルーチン========== procedure CharNext(var P: PWideChar; Len: Integer = 1); inline; var I: Integer; begin for I := 1 to Len do begin if IsLeadChar(P^) then Inc(P); Inc(P); end; end; procedure CharNextForCombiningSequence(var P: PWideChar; Len: Integer = 1); var I: Integer; begin for I := 1 to Len do begin if not IsUnicodeProperty(ToUCS4Char(P), upM) then begin Inc(P); while IsUnicodeProperty(ToUCS4Char(P), upM) do Inc(P); end; end; end; procedure CharPrev(var P: PWideChar; Len: Integer = 1); inline; var I: Integer; begin for I := 1 to Len do begin Dec(P); if IsLeadChar(P^) then Dec(P); end; end; { TREQuickSearch } procedure TREQuickSearch.Clear; begin FFindText := ''; FPattern := nil; FPatternLen := 0; FTextTopP := nil; FTextEndP := nil; FTextLen := 0; FOptions := []; FMatchP := nil; FCompiled := False; end; procedure TREQuickSearch.Compile; var I, Low: Integer; begin if FPatternLen > 2 then begin if FOptions <> [] then FFindText := ConvertREString(FFindText, FOptions); for I := 0 to 255 do FSkipTable[I] := FPatternLen; for I := 0 to FPatternLen - 1 do begin Low := Integer(FPattern[I]) and $FF; FSkipTable[ Low] := FPatternLen - I; end; end; FCompiled := True; end; function TREQuickSearch.Exec(AStr: PWideChar; ATextLen: Integer): Boolean; begin if not FCompiled then Compile; FTextTopP := AStr; FTextLen := ATextLen; FTextEndP := AStr + ATextLen; Result := IsMatch(AStr, FOptions); end; function TREQuickSearch.ExecNext: Boolean; var AStr: PWideChar; begin AStr := FMatchP + FPatternLen; Result := IsMatch(AStr, FOptions); end; function TREQuickSearch.GetMatchPos: Integer; begin if FMatchP <> nil then Result := FMatchP - FTextTopP + 1 else Result := 0; end; function TREQuickSearch.IsMatch(AStr: PWideChar; AOptions: TRECompareOptions): Boolean; var Index, L, Low: Integer; WChar: UCS4Char; P: PWideChar; begin Result := False; FMatchP := nil; if FTextLen < FPatternLen then Exit; { パターンが1-2文字ならQuick Seachの意味がない } if FPatternLen = 1 then begin if (coIgnoreWidth in AOptions) or (coIgnoreKana in AOptions) or (coIgnoreCase in AOptions) then begin WChar := GetREChar(FPattern, L, AOptions); while AStr <= FTextEndP do begin if WChar = GetREChar(AStr, L, AOptions) then begin FMatchP := AStr; Result := True; Exit; end; Inc(AStr, L); end; end else begin P := PWideChar(FPattern); while AStr <= FTextEndP do begin if AStr^ = P^ then begin FMatchP := AStr; Result := True; Exit; end; Inc(AStr); end; end; end else if FPatternLen = 2 then begin L := FTextEndP - AStr; P := REStrPos(AStr, L, PWideChar(FPattern), FPatternLen, AOptions); Result := P <> nil; if Result then begin FMatchP := P; Exit; end; end else begin Index := 0; if (coIgnoreWidth in AOptions) or (coIgnoreKana in AOptions) then begin while Index <= FTextLen - FPatternLen do begin if REStrLJComp(AStr + Index, FPattern, FPatternLen, AOptions) = 0 then begin FMatchP := AStr + Index; Result := True; Exit; end; Low := Integer(GetREChar(AStr + Index + FPatternLen, L, FOptions)) and $FF; Inc(Index, FSkipTable[ Low]); end; end else if coIgnoreCase in AOptions then begin while Index <= FTextLen - FPatternLen do begin if REStrLIComp(AStr + Index, FPattern, FPatternLen) = 0 then begin FMatchP := AStr + Index; Result := True; Exit; end; Low := Integer(GetREChar(AStr + Index + FPatternLen, L, FOptions)) and $FF; Inc(Index, FSkipTable[ Low]); end; end else begin while Index <= FTextLen - FPatternLen do begin if REStrLComp(AStr + Index, FPattern, FPatternLen) = 0 then begin FMatchP := AStr + Index; Result := True; Exit; end; Low := Integer(AStr[Index + FPatternLen]) and $FF; Inc(Index, FSkipTable[ Low]); end; end; end; end; procedure TREQuickSearch.SetFindText(const Value: REString); begin if FFindText <> Value then begin FFindText := Value; FPattern := PWideChar(FFindText); FPatternLen := Length(FFindText); FCompiled := False; end; end; procedure TREQuickSearch.SetOptions(const Value: TRECompareOptions); begin if FOptions <> Value then begin FOptions := Value; FCompiled := False; end; end; { TRECapture } procedure TRECapture.Clear; begin FStartP := nil; FEndP := nil; FMatched := False; end; procedure TRECapture.SetEndP(const Value: PWideChar); begin if (FStartP <> nil) and (not FMatched) then FMatched := True; FEndP := Value; end; { TREGroup } procedure TGroup.Assign(Source: TGroup); begin FRegExp := Source.FRegExp; FGroupName := Source.FGroupName; FIndexBegin := Source.FIndexBegin; FIndexEnd := Source.FIndexEnd; FCapture.StartP := Source.FCapture.StartP; FCapture.EndP := Source.FCapture.EndP; FCapture.Matched := Source.FCapture.Matched; end; procedure TGroup.Clear; begin FGroupName := ''; FIndexBegin := 0; FIndexEnd := 0; FCapture.StartP := nil; FCapture.EndP := nil; FCapture.Matched := False; end; constructor TGroup.Create(ARegExp: TSkRegExp); begin inherited Create; FRegExp := ARegExp; FCapture := TRECapture.Create; FGroupName := ''; FIndexBegin := 0; FIndexEnd := 0; end; destructor TGroup.Destroy; begin FCapture.Free; inherited; end; function TGroup.GetIndex: Integer; begin if FCapture.Matched then Result := FCapture.StartP - FRegExp.FTextTopP + 1 else Result := 0; end; function TGroup.GetLength: Integer; begin if FCapture.Matched then Result := FCapture.EndP - FCapture.StartP else Result := 0; end; function TGroup.GetStrings: REString; begin if FCapture.Matched then SetString(Result, FCapture.StartP, FCapture.EndP - FCapture.StartP) else Result := ''; end; function TGroup.GetSuccess: Boolean; begin Result := FCapture.Matched; end; procedure TGroup.Reset; begin FCapture.Clear; end; { TREGroupCollectionEnumerator } constructor TGroupCollectionEnumerator.Create(AList: TObjectList); begin inherited Create; FList := AList; FIndex := -1; end; function TGroupCollectionEnumerator.GetCurrent: TGroup; begin Result := FList[FIndex] as TGroup; end; function TGroupCollectionEnumerator.MoveNext: Boolean; begin Result := FIndex < FList.Count - 1; if Result then Inc(FIndex); end; { TREGroupCollection } function TGroupCollection.Add(const AGroupName: REString; AEntry, AWayout: Integer): Integer; var Item: TGroup; begin Item := TGroup.Create(FRegExp); Item.GroupName := AGroupName; Item.IndexBegin := AEntry; Item.IndexEnd := AWayout; Result := FItems.Add(Item); if AGroupName <> '' then AddGroupName(AGroupName, Result); end; procedure TGroupCollection.AddGroupName(const AGroupName: REString; Index: Integer); var H: Cardinal; S, D: PREHashItem; begin New(D); D.Key := AGroupName; D.Value := Index; H := HashOf(AGroupName); S := FBuckets[H]; if S <> nil then begin D.Next := S; FBuckets[H] := D; end else begin D.Next := nil; FBuckets[H] := D; end; end; procedure TGroupCollection.Assign(Source: TGroupCollection); var I: Integer; Item: TGroup; begin Clear; FRegExp := Source.FRegExp; for I := 0 to Source.FItems.Count - 1 do begin Item := TGroup.Create(FRegExp); Item.Assign(Source.FItems[I] as TGroup); if I <> 0 then begin if Item.GroupName <> '' then AddGroupName(Item.GroupName, I); FItems.Add(Item); end else FItems[0] := Item; end; end; procedure TGroupCollection.Clear; begin FItems.Clear; FItems.Add(TGroup.Create(FRegExp)); end; constructor TGroupCollection.Create(ARegExp: TSkRegExp); begin inherited Create; FRegExp := ARegExp; FItems := TObjectList.Create; FItems.Add(TGroup.Create(FRegExp)); end; destructor TGroupCollection.Destroy; var I: Integer; S, D: PREHashItem; begin for I := 0 to System.Length(FBuckets) - 1 do begin S := FBuckets[I]; while S <> nil do begin D := S.Next; Dispose(S); S := D; end; end; FItems.Free; inherited; end; function TGroupCollection.EnumIndexOfName(const AGroupName: REString) : TIntDynArray; var H: Cardinal; S: PREHashItem; LCount: Integer; begin LCount := 0; SetLength(Result, Count); H := HashOf(AGroupName); S := FBuckets[H]; while S <> nil do begin if S.Key = AGroupName then begin Result[LCount] := S.Value; Inc(LCount); end; S := S.Next; end; SetLength(Result, LCount); end; function TGroupCollection.GetCount: Integer; begin Result := FItems.Count; end; function TGroupCollection.GetEnumerator: TGroupCollectionEnumerator; begin Result := TGroupCollectionEnumerator.Create(FItems); end; function TGroupCollection.GetItems(Index: Integer): TGroup; begin if (Index < 0) or (Index > FItems.Count - 1) then raise ESkRegExpRuntime.CreateFmt(sRangeOverGroupNumber, [Index]); Result := FItems[Index] as TGroup; end; function TGroupCollection.GetNames(AName: REString): TGroup; var Index: Integer; begin Index := IndexOfMatchedName(AName); if Index = -1 then raise ESkRegExpRuntime.CreateFmt(sMissingGroupName, [AName]); Result := FItems[Index] as TGroup end; function TGroupCollection.HashOf(const Key: REString): Cardinal; var I: Integer; begin Result := 0; for I := 1 to System.Length(Key) do Result := ((Result shl 2) or (Result shr (Sizeof(Result) * 8 - 2))) xor Ord(Key[I]); Result := Result mod Cardinal(System.Length(FBuckets)); end; function TGroupCollection.IndexOfName(const AGroupName: REString): Integer; var H: Cardinal; S: PREHashItem; begin Result := -1; H := HashOf(AGroupName); S := FBuckets[H]; while S <> nil do begin if S.Key = AGroupName then begin Result := S.Value; Exit; end; S := S.Next; end; end; function TGroupCollection.IndexOfMatchedName(const AGroupName : REString): Integer; var H: Cardinal; S: PREHashItem; begin Result := -1; H := HashOf(AGroupName); S := FBuckets[H]; while S <> nil do begin if (S.Key = AGroupName) and GetItems(S.Value).Capture.Matched then begin Result := S.Value; Exit; end; S := S.Next; end; end; function TGroupCollection.IsDuplicateGroupName(const AGroupName : REString): Boolean; var H: Cardinal; S: PREHashItem; M: Integer; begin Result := False; M := 0; H := HashOf(AGroupName); S := FBuckets[H]; while S <> nil do begin if S.Key = AGroupName then begin Inc(M); if M > 1 then begin Result := True; Exit; end; end; S := S.Next; end; end; procedure TGroupCollection.Reset; var I: Integer; begin for I := 0 to FItems.Count - 1 do TGroup(FItems[I]).Reset; end; { TRECharMap } procedure TRECharMap.Add(Ch: UCS4Char); var P, Prev: PRECharMapRec; begin P := FMap[Ord(Ch) and $FF]; if P = nil then begin New(P); P^.Ch := Ch; P^.Next := nil; FMap[Ord(Ch) and $FF] := P; end else begin repeat if P^.Ch = Ch then Exit; Prev := P; P := P.Next; until P = nil; New(P); P^.Ch := Ch; P^.Next := nil; Prev.Next := P; end; end; procedure TRECharMap.Clear; var I: Integer; P, Next: PRECharMapRec; begin for I := 0 to 255 do begin if FMap[I] <> nil then begin P := FMap[I]; Next := P.Next; Dispose(P); while Next <> nil do begin P := Next; Next := P.Next; Dispose(P); end; end; FMap[I] := nil; end; end; destructor TRECharMap.Destroy; begin Clear; inherited; end; function TRECharMap.IsExists(AStr: PWideChar): Boolean; var Ch: Cardinal; P: PRECharMapRec; begin Result := False; Ch := ToUCS4Char(AStr); P := FMap[Ord(Ch) and $FF]; if P = nil then Exit; if P.Ch = Ch then begin Result := True; Exit; end; while P.Next <> nil do begin if P.Ch = Ch then begin Result := True; Exit; end; P := P.Next; end; end; { TRECode } function TRECode.Compare(AStr: PWideChar): Integer; begin Result := 0; end; function TRECode.CompareCode(Source: TRECode): Integer; begin Result := 0; end; constructor TRECode.Create(ARegExp: TSkRegExp); begin inherited Create; FRegExp := ARegExp; end; function TRECode.ExecRepeat(var AStr: PWideChar; AMin, AMax: Integer): Boolean; var I: Integer; Len: Integer; begin Result := False; for I := 1 to AMin do begin if (AStr < FRegExp.FMatchEndP) and IsEqual(AStr, Len) then Inc(AStr, Len) else Exit; end; Result := True; if AMin = AMax then Exit; AMax := AMax - AMin; for I := 1 to AMax do begin if (AStr < FRegExp.FMatchEndP) and IsEqual(AStr, Len) then Inc(AStr, Len) else Break; end; end; function TRECode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Result := False; end; function TRECode.ExecRepeat(var AStr: PWideChar; IsStar: Boolean): Boolean; var StartP: PWideChar; Len: Integer; begin Result := IsStar; StartP := AStr; while (AStr < FRegExp.FMatchEndP) and IsEqual(AStr, Len) do Inc(AStr, Len); if not Result then Result := AStr - StartP > 0; end; function TRECode.GetCharLength: Integer; begin Result := 1; end; {$IFDEF DEBUG} function TRECode.GetDebugStr: REString; begin end; {$ENDIF} function TRECode.GetLength: Integer; begin Result := 1; end; function TRECode.IsInclude(ACode: TRECode): Boolean; begin Result := False; end; function TRECode.IsOverlap(ACode: TRECode): Boolean; begin Result := True; end; { TRECharCode } function TRECharCode.Compare(AStr: PWideChar): Integer; begin Result := RECompareString(AStr, FSubP, FLength, FCompareOptions); end; function TRECharCode.CompareCode(Dest: TRECode): Integer; var Ch1, Ch2, Start, Last: UCS4Char; begin Ch1 := GetWChar; if Dest is TRECharCode then begin Ch2 := (Dest as TRECharCode).GetWChar; if Ch1 > Ch2 then Result := 1 else if Ch1 < Ch2 then Result := -1 else Result := 0; end else if Dest is TRERangeCharCode then begin Start := (Dest as TRERangeCharCode).FStartWChar; Last := (Dest as TRERangeCharCode).FLastWChar; if Ch1 < Start then Result := -1 else if Ch1 > Last then Result := 1 else Result := 0; end else if (Dest is TREWordCharCode) then begin if FRegExp.IsWord(Ch1) then Result := 0 else Result := -1; end else if (Dest is TREDigitCharCode) then begin if FRegExp.IsDigit(Ch1) then Result := 0 else Result := 1; end else if (Dest is TRESpaceCharCode) then begin if FRegExp.IsSpace(Ch1) then Result := 0 else Result := -1; end else if (Dest is TREPropertyCode) then begin if IsUnicodeProperty(Ch1, (Dest as TREPropertyCode).FUniCodeProperty) then Result := 0 else Result := -1; end else if (Dest is TREHexDigitCharCode) then begin if IsHexDigit(Ch1) then Result := 0 else Result := -1; end else if (Dest is TREVerticalSpaceCharCode) then begin if IsVerticalWhiteSpace(Ch1) then Result := 0 else Result := -1 end else if (Dest is TREHorizontalSpaceCharCode) then begin if IsHorizontalWhiteSpace(Ch1) then Result := 0 else Result := -1; end else Result := -1; end; constructor TRECharCode.Create(ARegExp: TSkRegExp; AWChar: UCS4Char; AOptions: TREOptions; AConvert: Boolean); var I: Integer; begin inherited Create(ARegExp); FStrings := UCS4CharToString(AWChar); FLength := System.Length(FStrings); FSubP := PWideChar(FStrings); FConvert := AConvert; FOptions := AOptions; FCompareOptions := REOptionsToRECompareOptions(FOptions); FCharLength := 0; for I := 1 to System.Length(FStrings) do begin if IsLeadChar(FStrings[I]) then Dec(FCharLength); Inc(FCharLength); end; end; function TRECharCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Result := RECompareString(AStr, FSubP, FLength, FCompareOptions) = 0; if Result then Len := FLength else Len := 0; end; function TRECharCode.ExecRepeat(var AStr: PWideChar; IsStar: Boolean): Boolean; var StartP: PWideChar; Len: Integer; begin Result := IsStar; StartP := AStr; if (roIgnoreKana in FOptions) or (roIgnoreWidth in FOptions) then begin while REStrLJComp(AStr, PWideChar(FStrings), FLength, FCompareOptions) = 0 do Inc(AStr, FLength); end else if roIgnoreCase in FOptions then begin while REStrLIComp(AStr, PWideChar(FStrings), FLength) = 0 do Inc(AStr, FLength); end else begin if FLength = 1 then begin while AStr^ = FSubP^ do Inc(AStr); end else begin while REStrLComp(AStr, PWideChar(FStrings), FLength) = 0 do Inc(AStr, FLength); end end; Len := AStr - StartP; if not Result then Result := Len > 0; end; function TRECharCode.GetCharLength: Integer; begin Result := FCharLength; end; {$IFDEF DEBUG} function TRECharCode.GetDebugStr: REString; var I: Integer; S: REString; IsW: Boolean; begin I := 1; while I <= System.Length(FStrings) do begin IsW := IsLeadChar(FStrings[I]); if IsUnicodeProperty(ToUCS4Char(@FStrings[I]), upPrint) then begin if IsW then begin S := S + FStrings[I]; Inc(I); end; S := S + FStrings[I]; end else begin if IsW then begin S := S + '\x' + IntToHex(Ord(FStrings[I]), 2); Inc(I); end; S := S + '\x' + IntToHex(Ord(FStrings[I]), 2); end; Inc(I); end; Result := Format(sLiteral, [S]); end; {$ENDIF} function TRECharCode.GetLength: Integer; begin Result := FLength; end; function TRECharCode.GetWChar: UCS4Char; var L: Integer; begin Result := GetREChar(FSubP, L, FCompareOptions); end; function TRECharCode.IsInclude(ACode: TRECode): Boolean; begin if (ACode is TRECharCode) then Result := GetWChar = (ACode as TRECharCode).GetWChar else Result := False; end; function TRECharCode.IsOverlap(ACode: TRECode): Boolean; var S: REString; LOptions: TRECompareOptions; L: Integer; begin if ACode is TRECharCode then begin S := (ACode as TRECharCode).FStrings; LOptions := (ACode as TRECharCode).FCompareOptions; L := Min(System.Length(S), FLength); Result := RECompareString(FSubP, PWideChar(S), L, LOptions) = 0; // Result := REStrPos(FSubP, FSize, PWideChar(S), Length(S), LOptions) <> nil; end else if ACode is TRELiteralCode then begin S := (ACode as TRELiteralCode).FStrings; LOptions := (ACode as TRELiteralCode).FCompareOptions; L := Min(System.Length(S), FLength); Result := RECompareString(FSubP, PWideChar(S), L, LOptions) = 0; // Result := REStrPos(FSubP, FSize, PWideChar(S), Length(S), LOptions) <> nil; end else if ACode is TREWordCharCode then begin Result := FRegExp.IsWord(ToUCS4Char(FSubP)); if (ACode as TREWordCharCode).FNegative then Result := not Result; end else if ACode is TREDigitCharCode then begin Result := FRegExp.IsDigit(ToUCS4Char(FSubP)); if (ACode as TREDigitCharCode).FNegative then Result := not Result; end else if ACode is TREHexDigitCharCode then begin Result := IsHexDigit(ToUCS4Char(FSubP)); if (ACode as TREHexDigitCharCode).FNegative then Result := not Result; end else if ACode is TRESpaceCharCode then begin Result := FRegExp.IsSpace(ToUCS4Char(FSubP)); if (ACode as TRESpaceCharCode).FNegative then Result := not Result; end else if ACode.CharLength = 0 then Result := False else Result := True; end; { TRELiteralCode } constructor TRELiteralCode.Create(ARegExp: TSkRegExp; Str: UCS4String; AOptions: TREOptions); var I: Integer; begin inherited Create(ARegExp); FStrings := RECharArrayToString(Str); FSubP := PWideChar(FStrings); FLength := System.Length(FStrings); FSubP := PWideChar(FStrings); FOptions := AOptions; FCompareOptions := REOptionsToRECompareOptions(FOptions); FCharLength := 0; for I := 1 to System.Length(FStrings) do begin if IsLeadChar(FStrings[I]) then Dec(FCharLength); Inc(FCharLength); end; end; constructor TRELiteralCode.Create(ARegExp: TSkRegExp; Str: REString; AOptions: TREOptions); var I: Integer; begin inherited Create(ARegExp); FStrings := Str; FSubP := PWideChar(FStrings); FLength := System.Length(FStrings); FSubP := PWideChar(FStrings); FOptions := AOptions; FCompareOptions := REOptionsToRECompareOptions(FOptions); FCharLength := 0; for I := 1 to System.Length(FStrings) do begin if IsLeadChar(FStrings[I]) then Dec(FCharLength); Inc(FCharLength); end; end; function TRELiteralCode.ExecRepeat(var AStr: PWideChar; IsStar: Boolean): Boolean; var StartP: PWideChar; Len: Integer; begin Result := IsStar; StartP := AStr; if (roIgnoreKana in FOptions) or (roIgnoreWidth in FOptions) then begin while REStrLJComp(AStr, PWideChar(FStrings), FLength, FCompareOptions) = 0 do Inc(AStr, FLength); end else if roIgnoreCase in FOptions then begin while REStrLIComp(AStr, PWideChar(FStrings), FLength) = 0 do Inc(AStr, FLength); end else begin if FLength = 1 then begin while AStr^ = PWideChar(FStrings)^ do Inc(AStr); end else begin while REStrLComp(AStr, PWideChar(FStrings), FLength) = 0 do Inc(AStr, FLength); end end; Len := AStr - StartP; if not Result then Result := Len > 0; end; function TRELiteralCode.GetCharLength: Integer; begin Result := FCharLength; end; {$IFDEF DEBUG} function TRELiteralCode.GetDebugStr: REString; var I: Integer; S: REString; IsW: Boolean; begin I := 1; while I <= System.Length(FStrings) do begin IsW := IsLeadChar(FStrings[I]); if IsUnicodeProperty(ToUCS4Char(@FStrings[I]), upPrint) then begin if IsW then begin S := S + FStrings[I]; Inc(I); end; S := S + FStrings[I]; end else begin if IsW then begin S := S + '\x' + IntToHex(Ord(FStrings[I]), 2); Inc(I); end; S := S + '\x' + IntToHex(Ord(FStrings[I]), 2); end; Inc(I); end; Result := Format(sLiteral, [S]); end; {$ENDIF DEBUG} function TRELiteralCode.GetLength: Integer; begin Result := FLength; end; function TRELiteralCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Result := RECompareString(AStr, FSubP, FLength, FCompareOptions) = 0; if Result then Len := FLength else Len := 0; end; function TRELiteralCode.IsInclude(ACode: TRECode): Boolean; begin Result := False; if not(ACode is TRELiteralCode) then Exit; Result := (ACode as TRELiteralCode).FStrings = FStrings; end; function TRELiteralCode.IsOverlap(ACode: TRECode): Boolean; var S: REString; LOptions: TRECompareOptions; L: Integer; begin if ACode is TRECharCode then begin S := (ACode as TRECharCode).FStrings; LOptions := (ACode as TRECharCode).FCompareOptions; L := Min(System.Length(S), FLength); Result := RECompareString(FSubP, PWideChar(S), L, LOptions) = 0; // Result := REStrPos(FSubP, FSize, PWideChar(S), Length(S), LOptions) <> nil; end else if ACode is TRELiteralCode then begin S := (ACode as TRELiteralCode).FStrings; LOptions := (ACode as TRELiteralCode).FCompareOptions; L := Min(System.Length(S), FLength); Result := RECompareString(FSubP, PWideChar(S), L, LOptions) = 0; // Result := REStrPos(FSubP, FSize, PWideChar(S), Length(S), LOptions) <> nil; end else if ACode is TREWordCharCode then begin Result := FRegExp.IsWord(ToUCS4Char(FSubP)); if (ACode as TREWordCharCode).FNegative then Result := not Result; end else if ACode is TREDigitCharCode then begin Result := FRegExp.IsDigit(ToUCS4Char(FSubP)); if (ACode as TREDigitCharCode).FNegative then Result := not Result; end else if ACode is TREHexDigitCharCode then begin Result := IsHexDigit(ToUCS4Char(FSubP)); if (ACode as TREHexDigitCharCode).FNegative then Result := not Result; end else if ACode is TRESpaceCharCode then begin Result := FRegExp.IsSpace(ToUCS4Char(FSubP)); if (ACode as TRESpaceCharCode).FNegative then Result := not Result; end else if ACode.CharLength = 0 then Result := False else Result := True; end; { TRERangeCharCode } function TRERangeCharCode.Compare(AStr: PWideChar): Integer; var Ch: UCS4Char; L: Integer; begin Ch := GetREChar(AStr, L, FCompareOptions); if Ch < FStartWChar then Result := -1 else if Ch > FLastWChar then Result := 1 else Result := 0; end; function TRERangeCharCode.CompareCode(Dest: TRECode): Integer; var Ch1, Ch2: UCS4Char; begin if Dest is TRECharCode then begin Ch1 := (Dest as TRECharCode).GetWChar; if Ch1 < FStartWChar then Result := 1 else if Ch1 > FLastWChar then Result := -1 else Result := 0; end else if Dest is TRERangeCharCode then begin Ch1 := (Dest as TRERangeCharCode).FStartWChar; Ch2 := (Dest as TRERangeCharCode).FLastWChar; if Ch2 < FStartWChar then Result := 1 else if Ch1 > FLastWChar then Result := -1 else Result := 0; end else if Dest is TREWordCharCode then begin if FRegExp.IsWord(FStartWChar) and FRegExp.IsWord(FLastWChar) then Result := 0 else Result := -1; end else if Dest is TREDigitCharCode then begin if FRegExp.IsDigit(FStartWChar) and FRegExp.IsDigit(FLastWChar) then Result := 0 else Result := -1; end else if (Dest is TRESpaceCharCode) then begin if FRegExp.IsSpace(FStartWChar) and FRegExp.IsSpace(FLastWChar) then Result := 0 else Result := -1; end else if (Dest is TREPropertyCode) then begin if IsUnicodeProperty(FStartWChar, (Dest as TREPropertyCode) .FUniCodeProperty) and IsUnicodeProperty(FLastWChar, (Dest as TREPropertyCode).FUniCodeProperty) then Result := 0 else Result := -1; end else if (Dest is TREHexDigitCharCode) then begin if IsHexDigit(FStartWChar) and IsHexDigit(FLastWChar) then Result := 0 else Result := -1; end else if (Dest is TREVerticalSpaceCharCode) then begin if IsVerticalWhiteSpace(FStartWChar) and IsVerticalWhiteSpace(FLastWChar) then Result := 0 else Result := -1 end else if (Dest is TREHorizontalSpaceCharCode) then begin if IsHorizontalWhiteSpace(FStartWChar) and IsHorizontalWhiteSpace(FLastWChar) then Result := 0 else Result := -1; end else Result := -1; end; constructor TRERangeCharCode.Create(ARegExp: TSkRegExp; AStartWChar, ALastWChar: UCS4Char; AOptions: TREOptions); begin inherited Create(ARegExp); FStartWChar := AStartWChar; FLastWChar := ALastWChar; FOptions := AOptions; FCompareOptions := REOptionsToRECompareOptions(FOptions); end; function TRERangeCharCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; var W: UCS4Char; begin W := GetREChar(AStr, Len, FCompareOptions); Result := (W >= FStartWChar) and (W <= FLastWChar); if not Result then Len := 0; end; {$IFDEF DEBUG} function TRERangeCharCode.GetDebugStr: REString; var S1, S2: REString; begin if IsUnicodeProperty(FStartWChar, upCntrl) then S1 := Format('($%x)', [FStartWChar]) else begin S1 := WideChar(FStartWChar); S1 := Format('%s ($%x)', [S1, FStartWChar]); end; if IsUnicodeProperty(FLastWChar, upCntrl) then S2 := Format('($%x)', [FLastWChar]) else begin S2 := WideChar(FLastWChar); S2 := Format('%s ($%x)', [S2, FLastWChar]); end; Result := Format('%s ~ %s', [S1, S2]); end; {$ENDIF} function TRERangeCharCode.IsInclude(ACode: TRECode): Boolean; begin if ACode is TRECharCode then Result := (FStartWChar >= (ACode as TRECharCode).GetWChar) and (FLastWChar <= (ACode as TRECharCode).GetWChar) else if ACode is TRERangeCharCode then Result := (FStartWChar >= (ACode as TRERangeCharCode).FStartWChar) and (FLastWChar <= (ACode as TRERangeCharCode).FLastWChar) else Result := False; end; { TREAnyCharCode } constructor TREAnyCharCode.Create(ARegExp: TSkRegExp; AOptions: TREOptions); begin inherited Create(ARegExp); FOptions := AOptions; FCompareOptions := REOptionsToRECompareOptions(FOptions); end; function TREAnyCharCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; var StartP: PWideChar; begin Result := False; Len := 0; if FRegExp.FMatchEndP = AStr then Exit; StartP := AStr; if (roSingleLine in FOptions) then begin Result := True; Inc(AStr); end else begin if not IsLineSeparator(AStr^) then begin Inc(AStr); Result := True; end; end; if Result then Len := AStr - StartP; end; function TREAnyCharCode.ExecRepeat(var AStr: PWideChar; IsStar: Boolean): Boolean; var StartP: PWideChar; begin Result := IsStar; StartP := AStr; if roSingleLine in FOptions then begin AStr := FRegExp.FMatchEndP; end else begin while (AStr <> FRegExp.FMatchEndP) and not IsLineSeparator(AStr^) do Inc(AStr); end; if not Result then Result := AStr - StartP > 0; end; {$IFDEF DEBUG} function TREAnyCharCode.GetDebugStr: REString; begin Result := sAnyChar; end; {$ENDIF} function TREAnyCharCode.IsInclude(ACode: TRECode): Boolean; begin if ACode is TREAnyCharCode then Result := True else Result := False; end; { TREWordCharCode } function TREWordCharCode.Compare(AStr: PWideChar): Integer; var b: Boolean; begin b := FRegExp.IsWord(ToUCS4Char(AStr)); if FNegative then b := not b; if b then Result := 0 else Result := 1; end; function TREWordCharCode.CompareCode(Dest: TRECode): Integer; begin if Dest is TRECharCode then begin if FRegExp.IsWord((Dest as TRECharCode).GetWChar) then Result := 0 else Result := -1; end else if Dest is TRERangeCharCode then begin if FRegExp.IsWord((Dest as TRERangeCharCode).FStartWChar) and FRegExp.IsWord((Dest as TRERangeCharCode).FLastWChar) then Result := 0 else Result := -1; end else if Dest is TREWordCharCode then begin Result := 0; end else if Dest is TREDigitCharCode then begin Result := 0; end else if (Dest is TRESpaceCharCode) then begin Result := -1; end else if (Dest is TREPropertyCode) then begin Result := -1; end else if (Dest is TREHexDigitCharCode) then begin Result := 0 end else if (Dest is TREVerticalSpaceCharCode) then begin Result := -1 end else if (Dest is TREHorizontalSpaceCharCode) then begin Result := -1 end else Result := -1; end; constructor TREWordCharCode.Create(ARegExp: TSkRegExp; ANegative: Boolean); begin inherited Create(ARegExp); FNegative := ANegative; end; function TREWordCharCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Result := False; Len := 0; if AStr = FRegExp.FMatchEndP then Exit; if IsLeadChar(AStr^) then begin Result := FRegExp.IsWord(ToUCS4Char(AStr)); Len := 2; end else begin Result := FRegExp.IsWord(ToUCS4Char(AStr)); Len := 1; end; if FNegative then Result := not Result; if not Result then Len := 0; end; {$IFDEF DEBUG} function TREWordCharCode.GetDebugStr: REString; begin if not FNegative then Result := sWordChar else Result := sNegativeWordChar; end; {$ENDIF} function TREWordCharCode.IsInclude(ACode: TRECode): Boolean; begin if ACode is TREWordCharCode then Result := (ACode as TREWordCharCode).FNegative = FNegative else if ACode is TREDigitCharCode then begin if FNegative then Result := (ACode as TREDigitCharCode).FNegative else Result := not(ACode as TREDigitCharCode).FNegative; end else if ACode is TRECharCode then begin Result := FRegExp.IsWord((ACode as TRECharCode).GetWChar); if FNegative then Result := not Result; end else if ACode is TRERangeCharCode then begin Result := FRegExp.IsWord((ACode as TRERangeCharCode).FStartWChar) and FRegExp.IsWord((ACode as TRERangeCharCode).FLastWChar); if FNegative then Result := not Result; end else Result := False; end; function TREWordCharCode.IsOverlap(ACode: TRECode): Boolean; begin if (ACode is TRECharCode) then Result := FRegExp.IsWord((ACode as TRECharCode).GetWChar) else if (ACode is TRELiteralCode) then Result := FRegExp.IsWord (ToUCS4Char(PWideChar((ACode as TRELiteralCode).FStrings))) else if ACode.CharLength = 0 then Result := False else Result := True; end; { TREDigitCharCode } function TREDigitCharCode.Compare(AStr: PWideChar): Integer; var b: Boolean; begin b := FRegExp.IsDigit(ToUCS4Char(AStr)); if FNegative then b := not b; if b then Result := 0 else Result := 1; end; function TREDigitCharCode.CompareCode(Dest: TRECode): Integer; begin if Dest is TRECharCode then begin if FRegExp.IsDigit((Dest as TRECharCode).GetWChar) then Result := 0 else Result := -1; end else if Dest is TRERangeCharCode then begin if FRegExp.IsDigit((Dest as TRERangeCharCode).FStartWChar) and FRegExp.IsDigit((Dest as TRERangeCharCode).FLastWChar) then Result := 0 else Result := -1; end else if Dest is TREWordCharCode then begin Result := -1; end else if Dest is TREDigitCharCode then begin Result := 0; end else if (Dest is TRESpaceCharCode) then begin Result := -1; end else if (Dest is TREPropertyCode) then begin Result := -1; end else if (Dest is TREHexDigitCharCode) then begin Result := -1 end else if (Dest is TREVerticalSpaceCharCode) then begin Result := -1 end else if (Dest is TREHorizontalSpaceCharCode) then begin Result := -1 end else Result := -1; end; constructor TREDigitCharCode.Create(ARegExp: TSkRegExp; ANegative: Boolean); begin inherited Create(ARegExp); FNegative := ANegative; end; function TREDigitCharCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Result := False; Len := 0; if AStr = FRegExp.FMatchEndP then Exit; if IsLeadChar(AStr^) then begin Result := FRegExp.IsDigit(ToUCS4Char(AStr)); Len := 2; end else begin Result := FRegExp.IsDigit(ToUCS4Char(AStr)); Len := 1; end; if FNegative then Result := not Result; if not Result then Len := 0; end; {$IFDEF DEBUG} function TREDigitCharCode.GetDebugStr: REString; begin if not FNegative then Result := sDigitChar else Result := sNegativeDigitChar; end; {$ENDIF} function TREDigitCharCode.IsInclude(ACode: TRECode): Boolean; begin if ACode is TREDigitCharCode then Result := FNegative and (ACode as TREDigitCharCode).FNegative else if ACode is TRECharCode then begin Result := FRegExp.IsDigit((ACode as TRECharCode).GetWChar); if FNegative then Result := not Result; end else if ACode is TRERangeCharCode then begin Result := FRegExp.IsDigit((ACode as TRERangeCharCode).FStartWChar) and FRegExp.IsDigit((ACode as TRERangeCharCode).FLastWChar); if FNegative then Result := not Result; end else Result := False; end; function TREDigitCharCode.IsOverlap(ACode: TRECode): Boolean; begin if ACode is TRECharCode then Result := FRegExp.IsDigit((ACode as TRECharCode).GetWChar) else if ACode is TRELiteralCode then Result := FRegExp.IsDigit (ToUCS4Char(PWideChar((ACode as TRELiteralCode).FStrings))) else if ACode.CharLength = 0 then Result := False else Result := True; end; { TREHexDigitCharCode } function TREHexDigitCharCode.Compare(AStr: PWideChar): Integer; var b: Boolean; begin b := IsHexDigit(ToUCS4Char(AStr)); if FNegative then b := not b; if b then Result := 0 else Result := 1; end; function TREHexDigitCharCode.CompareCode(Dest: TRECode): Integer; begin if Dest is TRECharCode then begin if IsHexDigit((Dest as TRECharCode).GetWChar) then Result := 0 else Result := -1; end else if Dest is TRERangeCharCode then begin if IsHexDigit((Dest as TRERangeCharCode).FStartWChar) and IsHexDigit((Dest as TRERangeCharCode).FLastWChar) then Result := 0 else Result := -1; end else if Dest is TREWordCharCode then begin Result := 0; end else if Dest is TREDigitCharCode then begin Result := -1; end else if (Dest is TRESpaceCharCode) then begin Result := -1; end else if (Dest is TREPropertyCode) then begin Result := -1; end else if (Dest is TREHexDigitCharCode) then begin Result := 0 end else if (Dest is TREVerticalSpaceCharCode) then begin Result := -1 end else if (Dest is TREHorizontalSpaceCharCode) then begin Result := -1 end else Result := -1; end; constructor TREHexDigitCharCode.Create(ARegExp: TSkRegExp; ANegative: Boolean); begin inherited Create(ARegExp); FNegative := ANegative; end; function TREHexDigitCharCode.IsEqual(AStr: PWideChar; var Len: Integer) : Boolean; begin Result := False; Len := 0; if AStr = FRegExp.FMatchEndP then Exit; if IsLeadChar(AStr^) then begin Result := IsHexDigit(ToUCS4Char(AStr)); Len := 2; end else begin Result := IsHexDigit(ToUCS4Char(AStr)); Len := 1; end; if FNegative then Result := not Result; if not Result then Len := 0; end; {$IFDEF DEBUG} function TREHexDigitCharCode.GetDebugStr: REString; begin if not FNegative then Result := sHexDigitChar else Result := sNegativeHexDigitChar; end; {$ENDIF} function TREHexDigitCharCode.IsInclude(ACode: TRECode): Boolean; begin if ACode is TREHexDigitCharCode then Result := FNegative and (ACode as TREHexDigitCharCode).FNegative else if ACode is TRECharCode then begin Result := IsHexDigit((ACode as TRECharCode).GetWChar); if FNegative then Result := not Result; end else if ACode is TRERangeCharCode then begin Result := FRegExp.IsDigit((ACode as TRERangeCharCode).FStartWChar) and IsHexDigit((ACode as TRERangeCharCode).FLastWChar); if FNegative then Result := not Result; end else if ACode is TREWordCharCode then Result := FNegative and (ACode as TREHexDigitCharCode).FNegative else Result := False; end; function TREHexDigitCharCode.IsOverlap(ACode: TRECode): Boolean; begin if ACode is TRECharCode then Result := IsHexDigit((ACode as TRECharCode).GetWChar) else if ACode is TRELiteralCode then Result := IsHexDigit(ToUCS4Char(PWideChar((ACode as TRELiteralCode) .FStrings))) else if ACode.CharLength = 0 then Result := False else Result := True; end; { TRESpaceCharCode } function TRESpaceCharCode.Compare(AStr: PWideChar): Integer; var b: Boolean; begin b := FRegExp.IsSpace(ToUCS4Char(AStr)); if FNegative then b := not b; if b then Result := 0 else Result := 1; end; function TRESpaceCharCode.CompareCode(Dest: TRECode): Integer; begin if Dest is TRECharCode then begin if FRegExp.IsSpace((Dest as TRECharCode).GetWChar) then Result := 0 else Result := -1; end else if Dest is TRERangeCharCode then begin if FRegExp.IsSpace((Dest as TRERangeCharCode).FStartWChar) and FRegExp.IsSpace((Dest as TRERangeCharCode).FLastWChar) then Result := 0 else Result := -1; end else if Dest is TREWordCharCode then begin Result := -1; end else if Dest is TREDigitCharCode then begin Result := -1; end else if (Dest is TRESpaceCharCode) then begin Result := 0; end else if (Dest is TREPropertyCode) then begin Result := -1; end else if (Dest is TREHexDigitCharCode) then begin Result := -1 end else if (Dest is TREVerticalSpaceCharCode) then begin Result := -1 end else if (Dest is TREHorizontalSpaceCharCode) then begin Result := -1 end else Result := -1; end; constructor TRESpaceCharCode.Create(ARegExp: TSkRegExp; ANegative: Boolean); begin inherited Create(ARegExp); FNegative := ANegative; end; function TRESpaceCharCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Result := False; Len := 0; if AStr = FRegExp.FMatchEndP then Exit; if IsLeadChar(AStr^) then begin Result := FRegExp.IsSpace(ToUCS4Char(AStr)); Len := 2; end else begin Result := FRegExp.IsSpace(ToUCS4Char(AStr)); Len := 1; end; if FNegative then Result := not Result; if not Result then Len := 0; end; {$IFDEF DEBUG} function TRESpaceCharCode.GetDebugStr: REString; begin if not FNegative then Result := sSpaceChar else Result := sNegativeSpaceChar; end; {$ENDIF} function TRESpaceCharCode.IsInclude(ACode: TRECode): Boolean; begin if ACode is TRESpaceCharCode then Result := FNegative = (ACode as TRESpaceCharCode).FNegative else if ACode is TRECharCode then begin Result := FRegExp.IsSpace((ACode as TRECharCode).GetWChar); if FNegative then Result := not Result; end else if ACode is TRERangeCharCode then Result := FRegExp.IsSpace((ACode as TRERangeCharCode).FStartWChar) and FRegExp.IsSpace((ACode as TRERangeCharCode).FLastWChar) else Result := False; end; function TRESpaceCharCode.IsOverlap(ACode: TRECode): Boolean; begin if ACode is TRECharCode then Result := FRegExp.IsSpace((ACode as TRECharCode).GetWChar) else if ACode is TRELiteralCode then Result := FRegExp.IsSpace (ToUCS4Char(PWideChar((ACode as TRELiteralCode).FStrings))) else if ACode.CharLength = 0 then Result := False else Result := True; end; { TRHorizontalSpaceCharCode } function TREHorizontalSpaceCharCode.Compare(AStr: PWideChar): Integer; var b: Boolean; begin b := IsHorizontalWhiteSpace(ToUCS4Char(AStr)); if FNegative then b := not b; if b then Result := 0 else Result := 1; end; function TREHorizontalSpaceCharCode.CompareCode(Dest: TRECode): Integer; begin if Dest is TRECharCode then begin if IsHorizontalWhiteSpace((Dest as TRECharCode).GetWChar) then Result := 0 else Result := -1; end else if Dest is TRERangeCharCode then begin if IsHorizontalWhiteSpace((Dest as TRERangeCharCode).FStartWChar) and IsHorizontalWhiteSpace((Dest as TRERangeCharCode).FLastWChar) then Result := 0 else Result := -1; end else if Dest is TREWordCharCode then begin Result := -1; end else if Dest is TREDigitCharCode then begin Result := -1; end else if (Dest is TRESpaceCharCode) then begin Result := -1; end else if (Dest is TREPropertyCode) then begin Result := -1; end else if (Dest is TREHexDigitCharCode) then begin Result := -1 end else if (Dest is TREVerticalSpaceCharCode) then begin Result := -1 end else if (Dest is TREHorizontalSpaceCharCode) then begin Result := 0 end else Result := -1; end; constructor TREHorizontalSpaceCharCode.Create(ARegExp: TSkRegExp; ANegative: Boolean); begin inherited Create(ARegExp); FNegative := ANegative; end; {$IFDEF DEBUG} function TREHorizontalSpaceCharCode.GetDebugStr: REString; begin if not FNegative then Result := sHorizontalSpaceChar else Result := sNegativeHorizontalSpaceChar; end; {$ENDIF} function TREHorizontalSpaceCharCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Len := 0; Result := False; if AStr = FRegExp.FMatchEndP then Exit; Result := IsHorizontalWhiteSpace(AStr); if FNegative then Result := not Result; if Result then Len := 1; end; function TREHorizontalSpaceCharCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TREHorizontalSpaceCharCode; end; function TREHorizontalSpaceCharCode.IsOverlap(ACode: TRECode): Boolean; begin Result := ACode is TREHorizontalSpaceCharCode; end; { TREVerticalSpaceCharCode } function TREVerticalSpaceCharCode.Compare(AStr: PWideChar): Integer; var b: Boolean; begin b := IsVerticalWhiteSpace(ToUCS4Char(AStr)); if FNegative then b := not b; if b then Result := 0 else Result := 1; end; function TREVerticalSpaceCharCode.CompareCode(Dest: TRECode): Integer; begin if Dest is TRECharCode then begin if IsVerticalWhiteSpace((Dest as TRECharCode).GetWChar) then Result := 0 else Result := -1; end else if Dest is TRERangeCharCode then begin if IsVerticalWhiteSpace((Dest as TRERangeCharCode).FStartWChar) and IsVerticalWhiteSpace((Dest as TRERangeCharCode).FLastWChar) then Result := 0 else Result := -1; end else if Dest is TREWordCharCode then begin Result := -1; end else if Dest is TREDigitCharCode then begin Result := -1; end else if (Dest is TRESpaceCharCode) then begin Result := -1; end else if (Dest is TREPropertyCode) then begin Result := -1; end else if (Dest is TREHexDigitCharCode) then begin Result := -1 end else if (Dest is TREVerticalSpaceCharCode) then begin Result := 0 end else if (Dest is TREHorizontalSpaceCharCode) then begin Result := -1 end else Result := -1; end; constructor TREVerticalSpaceCharCode.Create(ARegExp: TSkRegExp; ANegative: Boolean); begin inherited Create(ARegExp); FNegative := ANegative; end; {$IFDEF DEBUG} function TREVerticalSpaceCharCode.GetDebugStr: REString; begin if not FNegative then Result := sVerticalSpaceChar else Result := sNegativeVerticalSpaceChar; end; {$ENDIF} function TREVerticalSpaceCharCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Len := 0; Result := False; if AStr = FRegExp.FMatchEndP then Exit; Result := IsVerticalWhiteSpace(AStr); if FNegative then Result := not Result; if Result then Len := 1; end; function TREVerticalSpaceCharCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TREVerticalSpaceCharCode; end; function TREVerticalSpaceCharCode.IsOverlap(ACode: TRECode): Boolean; begin Result := ACode is TREVerticalSpaceCharCode; end; { TRELineBreakCharCode } constructor TRELineBreakCharCode.Create(ARegExp: TSkRegExp); begin inherited Create(ARegExp); end; function TRELineBreakCharCode.GetCharLength: Integer; begin Result := 2; end; {$IFDEF DEBUG} function TRELineBreakCharCode.GetDebugStr: REString; begin Result := sLineBreakChar; end; {$ENDIF} function TRELineBreakCharCode.GetLength: Integer; begin Result := 2; end; function TRELineBreakCharCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Len := 0; Result := False; if AStr^ = #$000D then begin Inc(AStr); if AStr^ = #$000A then Len := 2 else Len := 1; Result := True; end else if (AStr^ = #$000A) or (AStr^ = #$000B) or (AStr^ = #$000C) or (AStr^ = #$0085) or (AStr^ = #$2028) or (AStr^ = #$2029) then begin Len := 1; Result := True; end; end; function TRELineBreakCharCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TRELineBreakCharCode; end; function TRELineBreakCharCode.IsOverlap(ACode: TRECode): Boolean; begin Result := ACode is TRELineBreakCharCode; end; { TRECharClassCode } function TRECharClassCode.Add(AStartWChar, ALastWChar: UCS4Char): Integer; begin if (roIgnoreCase in FOptions) then begin if (IsUnicodeProperty(AStartWChar, upUpper) and IsUnicodeProperty(ALastWChar, upUpper)) or (IsUnicodeProperty(AStartWChar, upLower) and IsUnicodeProperty(ALastWChar, upLower)) then begin CharUpperBuffW(@AStartWChar, 1); CharUpperBuffW(@ALastWChar, 1); end else Exclude(FOptions, roIgnoreCase); end; Result := FCodeList.Add(TRERangeCharCode.Create(FRegExp, AStartWChar, ALastWChar, FOptions)); end; function TRECharClassCode.Add(AWChar: UCS4Char): Integer; var LStr, SubStr: REString; begin Result := 0; FMap.Add(AWChar); LStr := UCS4CharToString(AWChar); if roIgnoreCase in FOptions then begin SubStr := AnsiUpperCase(LStr); if LStr <> SubStr then FMap.Add(ToUCS4Char(PWideChar(SubStr))); SubStr := AnsiLowerCase(LStr); if LStr <> SubStr then FMap.Add(ToUCS4Char(PWideChar(SubStr))); end; if roIgnoreKana in FOptions then begin SubStr := ToWide(LStr); if SubStr <> LStr then FMap.Add(ToUCS4Char(PWideChar(SubStr))); SubStr := ToHalf(LStr); if SubStr <> LStr then FMap.Add(ToUCS4Char(PWideChar(SubStr))); end; if roIgnoreWidth in FOptions then begin SubStr := ToHiragana(LStr); if SubStr <> LStr then FMap.Add(ToUCS4Char(PWideChar(SubStr))); SubStr := ToKatakana(LStr); if SubStr <> LStr then FMap.Add(ToUCS4Char(PWideChar(SubStr))); end; FIsSimple := True; end; function TRECharClassCode.Add(Value: TRECode): Integer; begin Result := FCodeList.Add(Value); end; constructor TRECharClassCode.Create(ARegExp: TSkRegExp; ANegative: Boolean; AOptions: TREOptions); begin inherited Create(ARegExp); FMap := TRECharMap.Create; FCodeList := TObjectList.Create; FNegative := ANegative; FOptions := AOptions; end; destructor TRECharClassCode.Destroy; begin FCodeList.Free; FMap.Free; inherited; end; function TRECharClassCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; label Final; var I, C: Integer; begin Len := 0; if AStr = FRegExp.FMatchEndP then begin Result := False; Exit; end; Result := FNegative; if FIsSimple then begin if FMap.IsExists(AStr) then begin Result := not Result; goto Final; end; end; for I := 0 to FCodeList.Count - 1 do begin C := TRECode(FCodeList[I]).Compare(AStr); if C = 0 then begin Result := not Result; Break; end else if C < 0 then Break; end; Final: if Result then begin if IsLeadChar(AStr^) then Len := 2 else Len := 1; end; end; {$IFDEF DEBUG} function TRECharClassCode.GetDebugStr: REString; var I: Integer; begin Result := sMsgRange; for I := 0 to FCodeList.Count - 1 do if I > 0 then Result := Result + ', ' + TRECode(FCodeList[I]).GetDebugStr else Result := Result + TRECode(FCodeList[I]).GetDebugStr; end; {$ENDIF} // DEBUG function TRECharClassCode.IsInclude(ACode: TRECode): Boolean; begin Result := False; end; function TRECharClassCode.IsOverlap(ACode: TRECode): Boolean; var LCode: TRECode; I: Integer; begin Result := FNegative; if ACode is TRECharCode then begin if FMap.IsExists((ACode as TRECharCode).FSubP) then begin Result := not Result; Exit; end; end; for I := 0 to FCodeList.Count - 1 do begin LCode := TRECode(FCodeList[I]); if LCode.IsOverlap(ACode) then begin Result := not Result; Exit; end; end; end; procedure TRECharClassCode.Rebuild; procedure RebuildSub(Index: Integer); var Source, Dest: TRECode; I: Integer; begin Source := TRECode(FCodeList[Index]); for I := FCodeList.Count - 1 downto 0 do begin if I <> Index then begin Dest := TRECode(FCodeList[I]); if Source.IsInclude(Dest) then FCodeList.Delete(I); end; end; end; var I: Integer; begin I := 0; while I < FCodeList.Count do begin RebuildSub(I); Inc(I); end; Sort; end; function RECompareCode(Item1, Item2: Pointer): Integer; begin Result := TRECode(Item1).CompareCode(TRECode(Item2)); end; procedure TRECharClassCode.Sort; begin FCodeList.Sort(@RECompareCode); end; { TRECombiningSequence } function TRECombiningSequence.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; var StartP: PWideChar; begin Result := False; StartP := AStr; Len := 0; if AStr >= FRegExp.FMatchEndP then Exit; if not IsUnicodeProperty(ToUCS4Char(AStr), upM) then begin Inc(AStr); Result := True; while (AStr < FRegExp.FMatchEndP) and IsUnicodeProperty(ToUCS4Char(AStr), upM) do Inc(AStr); end; if Result then Len := AStr - StartP; end; function TRECombiningSequence.ExecRepeat(var AStr: PWideChar; IsStar: Boolean): Boolean; begin Result := True; AStr := FRegExp.FMatchEndP; end; function TRECombiningSequence.GetCharLength: Integer; begin Result := -1; end; {$IFDEF DEBUG} function TRECombiningSequence.GetDebugStr: REString; begin Result := sCombiningSequence; end; {$ENDIF} function TRECombiningSequence.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TRECombiningSequence; end; { TREBoundaryCode } constructor TREBoundaryCode.Create(ARegExp: TSkRegExp; ANegative: Boolean); begin inherited Create(ARegExp); FNegative := ANegative; end; function TREBoundaryCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; var PrevType, CurType: Boolean; begin Len := 0; if not FNegative then begin if AStr = FRegExp.FMatchTopP then PrevType := False else begin Dec(AStr); PrevType := FRegExp.IsWord(ToUCS4Char(AStr)); Inc(AStr); end; if AStr = FRegExp.FMatchEndP then CurType := False else CurType := FRegExp.IsWord(ToUCS4Char(AStr)); Result := PrevType <> CurType; end else begin if AStr <> FRegExp.FMatchTopP then begin Dec(AStr); PrevType := not FRegExp.IsWord(ToUCS4Char(AStr)); Inc(AStr); end else PrevType := True; if AStr <> FRegExp.FMatchEndP then CurType := not FRegExp.IsWord(ToUCS4Char(AStr)) else CurType := True; Result := PrevType = CurType; end; end; function TREBoundaryCode.GetCharLength: Integer; begin Result := 0; end; {$IFDEF DEBUG} function TREBoundaryCode.GetDebugStr: REString; begin if not FNegative then Result := sBoundaryCode else Result := sNegativeBoundaryCode; end; {$ENDIF} function TREBoundaryCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TREBoundaryCode; end; { TREReferenceCode } constructor TREReferenceCode.Create(ARegExp: TSkRegExp; AGroupIndex: Integer; AOptions: TREOptions); begin inherited Create(ARegExp); FGroupIndex := AGroupIndex; FOptions := AOptions; FCompareOptions := REOptionsToRECompareOptions(FOptions); end; function TREReferenceCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; var S: REString; ARefTagNo: Integer; begin Result := False; Len := 0; ARefTagNo := FGroupIndex; if not FRegExp.FGroups[ARefTagNo].Capture.Matched then Exit; S := FRegExp.FGroups[ARefTagNo].Strings; Result := RECompareString(AStr, PWideChar(S), System.Length(S), FCompareOptions) = 0; if Result then Len := System.Length(S); end; function TREReferenceCode.GetCharLength: Integer; begin Result := -1; end; {$IFDEF DEBUG} function TREReferenceCode.GetDebugStr: REString; begin Result := Format(sFmtGroupReference, [FGroupIndex]); end; {$ENDIF} function TREReferenceCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TREReferenceCode; if Result then Result := (ACode as TREReferenceCode).FGroupIndex = FGroupIndex; end; { TRENamedReferenceCode } constructor TRENamedReferenceCode.Create(ARegExp: TSkRegExp; AGroupName: REString; AGroupIndexArray: TIntDynArray; AOptions: TREOptions); begin inherited Create(ARegExp); FGroupName := AGroupName; FGroupIndexArray := AGroupIndexArray; FCount := System.Length(FGroupIndexArray); FOptions := AOptions; FCompareOptions := REOptionsToRECompareOptions(FOptions); end; function TRENamedReferenceCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; var S: REString; I, ARefTagNo: Integer; begin Result := False; Len := 0; for I := 0 to FCount - 1 do begin ARefTagNo := FGroupIndexArray[I]; if FRegExp.FGroups[ARefTagNo].Capture.Matched then begin S := FRegExp.FGroups[ARefTagNo].Strings; if RECompareString(AStr, PWideChar(S), System.Length(S), FCompareOptions) = 0 then begin Result := True; Len := System.Length(S); Exit; end; end; end; end; function TRENamedReferenceCode.GetCharLength: Integer; begin Result := -1; end; {$IFDEF DEBUG} function TRENamedReferenceCode.GetDebugStr: REString; begin Result := Format(sFmtGroupNameReference, [FGroupName]); end; {$ENDIF} function TRENamedReferenceCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TRENamedReferenceCode; if Result then Result := (ACode as TRENamedReferenceCode) .FGroupIndexArray = FGroupIndexArray; end; procedure TRENamedReferenceCode.SetGroupIndexArray( AGroupIndexArray: TIntDynArray); begin FGroupIndexArray := AGroupIndexArray; FCount := System.Length(FGroupIndexArray); end; { TRELineHeadCode } constructor TRELineHeadCode.Create(ARegExp: TSkRegExp; AOptions: TREOptions); begin inherited Create(ARegExp); FOptions := AOptions; end; function TRELineHeadCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Len := 0; if roMultiLine in FOptions then begin if (AStr = FRegExp.FMatchTopP) then Result := True else begin Dec(AStr); Result := IsLineSeparator(AStr^); end; end else Result := AStr = FRegExp.FMatchTopP; end; function TRELineHeadCode.GetCharLength: Integer; begin Result := 0; end; {$IFDEF DEBUG} function TRELineHeadCode.GetDebugStr: REString; begin Result := sHeadOfLineCode end; {$ENDIF} function TRELineHeadCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TRELineHeadCode; end; { TRELineTailCode } constructor TRELineTailCode.Create(ARegExp: TSkRegExp; AOptions: TREOptions); begin inherited Create(ARegExp); FOptions := AOptions; end; function TRELineTailCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Len := 0; if roMultiLine in FOptions then begin if (AStr = FRegExp.FMatchEndP) then Result := True else Result := IsLineSeparator(AStr^); end else Result := AStr = FRegExp.FMatchEndP; end; function TRELineTailCode.GetCharLength: Integer; begin Result := 0; end; {$IFDEF DEBUG} function TRELineTailCode.GetDebugStr: REString; begin Result := sEndOfLineCode; end; {$ENDIF} function TRELineTailCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TRELineTailCode; end; { TRETextHeadCode } function TRETextHeadCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Len := 0; Result := FRegExp.FMatchTopP = AStr; end; function TRETextHeadCode.GetCharLength: Integer; begin Result := 0; end; {$IFDEF DEBUG} function TRETextHeadCode.GetDebugStr: REString; begin Result := sTextHeadCode; end; {$ENDIF} function TRETextHeadCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TRETextHeadCode; end; { TRETextTailCode } function TRETextTailCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Len := 0; while IsLineSeparator(AStr^) do Inc(AStr); Result := FRegExp.FMatchEndP = AStr; end; function TRETextTailCode.GetCharLength: Integer; begin Result := 0; end; {$IFDEF DEBUG} function TRETextTailCode.GetDebugStr: REString; begin Result := sTextTailCode; end; {$ENDIF} function TRETextTailCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TRETextTailCode; end; { TRETextEndCode } function TRETextEndCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Len := 0; Result := FRegExp.FMatchEndP = AStr; end; function TRETextEndCode.GetCharLength: Integer; begin Result := 0; end; {$IFDEF DEBUG} function TRETextEndCode.GetDebugStr: REString; begin Result := sTextEndCode; end; {$ENDIF} function TRETextEndCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TRETextEndCode; end; { TREPosixCode } function TREPropertyCode.Compare(AStr: PWideChar): Integer; var b: Boolean; begin b := UnicodeProp.IsUnicodeProperty(ToUCS4Char(AStr), FUniCodeProperty); if FNegative then b := not b; if b then Result := 0 else Result := 1; end; function TREPropertyCode.CompareCode(Dest: TRECode): Integer; begin if Dest is TRECharCode then begin if UnicodeProp.IsUnicodeProperty((Dest as TRECharCode).GetWChar, FUniCodeProperty) then Result := 0 else Result := 1; end else if Dest is TRERangeCharCode then begin if UnicodeProp.IsUnicodeProperty((Dest as TRERangeCharCode).FStartWChar, FUniCodeProperty) and UnicodeProp.IsUnicodeProperty ((Dest as TRERangeCharCode).FLastWChar, FUniCodeProperty) then Result := 0 else Result := 1; end else if Dest is TREWordCharCode then begin Result := 1; end else if Dest is TREDigitCharCode then begin Result := 1; end else if (Dest is TRESpaceCharCode) then begin Result := 1; end else if (Dest is TREPropertyCode) then begin if FUniCodeProperty = (Dest as TREPropertyCode).FUniCodeProperty then Result := 0 else Result := 1; end else if (Dest is TREHexDigitCharCode) then begin Result := 1 end else if (Dest is TREVerticalSpaceCharCode) then begin Result := 11 end else if (Dest is TREHorizontalSpaceCharCode) then begin Result := 1 end else Result := 1; end; constructor TREPropertyCode.Create(ARegExp: TSkRegExp; AUnicodeProperty: TUnicodeProperty; ANegative: Boolean); begin inherited Create(ARegExp); FUniCodeProperty := AUnicodeProperty; FNegative := ANegative; end; function TREPropertyCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Result := IsUnicodeProperty(ToUCS4Char(AStr), FUniCodeProperty); if FNegative then Result := not Result; if not Result then Len := 0 else begin if IsLeadChar(AStr^) then Len := 2 else Len := 1; end; end; {$IFDEF DEBUG} function TREPropertyCode.GetDebugStr: REString; begin if not FNegative then Result := sPropertyCode else Result := sNegativePropertyCode end; {$ENDIF} function TREPropertyCode.IsInclude(ACode: TRECode): Boolean; begin Result := (ACode is TREPropertyCode) and ((ACode as TREPropertyCode).FUniCodeProperty = FUniCodeProperty); end; { TREGlobalPosCode } function TREGlobalPosCode.GetCharLength: Integer; begin Result := 0; end; {$IFDEF DEBUG} function TREGlobalPosCode.GetDebugStr: REString; begin Result := sGlobalPos; end; {$ENDIF} function TREGlobalPosCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Len := 0; Result := AStr = FRegExp.FGlobalEndP; end; function TREGlobalPosCode.IsInclude(ACode: TRECode): Boolean; begin Result := ACode is TREGlobalPosCode; end; { TREIfThenReferenceCode } constructor TREIfThenReferenceCode.Create(ARegExp: TSkRegExp; const AGroupIndex: Integer); begin inherited Create(ARegExp); FGroupIndex := AGroupIndex; end; function TREIfThenReferenceCode.GetCharLength: Integer; begin Result := 0; end; {$IFDEF DEBUG} function TREIfThenReferenceCode.GetDebugStr: REString; begin Result := Format(sIfThenReference, [FGroupIndex]); end; {$ENDIF} function TREIfThenReferenceCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; begin Len := 0; Result := FRegExp.FGroups[FGroupIndex].Capture.Matched; end; function TREIfThenReferenceCode.IsInclude(ACode: TRECode): Boolean; begin Result := (ACode is TREIfThenReferenceCode) and ((ACode as TREIfThenReferenceCode).FGroupIndex = FGroupIndex); end; { TREIfThenNamedReferenceCode } constructor TREIfThenNamedReferenceCode.Create(ARegExp: TSkRegExp; const AGroupName: REString); begin inherited Create(ARegExp); FGroupName := AGroupName; end; function TREIfThenNamedReferenceCode.GetCharLength: Integer; begin Result := 0; end; {$IFDEF DEBUG} function TREIfThenNamedReferenceCode.GetDebugStr: REString; begin Result := Format(sIfThenNamedReference, [FGroupName]); end; {$ENDIF} function TREIfThenNamedReferenceCode.IsEqual(AStr: PWideChar; var Len: Integer): Boolean; var Index: Integer; LMatchData: TGroupCollection; begin Result := False; Len := 0; LMatchData := FRegExp.FGroups; Index := LMatchData.IndexOfMatchedName(FGroupName); if Index = -1 then Exit; Result := LMatchData[Index].Capture.Matched; end; function TREIfThenNamedReferenceCode.IsInclude(ACode: TRECode): Boolean; begin Result := (ACode is TREIfThenNamedReferenceCode) and ((ACode as TREIfThenNamedReferenceCode).FGroupName = FGroupName); end; { TREBinCode } constructor TREBinCode.Create(ARegExp: TSkRegExp; AOp: TREOperator; ALeft, ARight: TRECode; AMin, AMax: Integer); begin inherited Create(ARegExp); FOp := AOp; FLeft := ALeft; FRight := ARight; FMin := AMin; FMax := AMax; FMatchKind := lkGreedy; end; { TRELex } procedure TRELex.Assign(Source: TRELex); begin FToken := Source.FToken; FP := Source.FP; FTokenStartP := Source.FTokenStartP; FTopP := Source.FTopP; FLastP := Source.FLastP; FWChar := Source.FWChar; FStartWChar := Source.FStartWChar; FLastWChar := Source.FLastWChar; FMin := Source.FMin; FMax := Source.FMax; FLevel := Source.FLevel; FContext := Source.FContext; FUniCodeProperty := Source.FUniCodeProperty; FConvert := Source.FConvert; FIsQuote := Source.FIsQuote; FGroupName := Source.FGroupName; FOptions := Source.FOptions; FNewOptions := Source.FNewOptions; FOptionList.Assign(Source.FOptionList); end; procedure TRELex.CharNext(var P: PWideChar; const Len: Integer); begin // TRELexでは文字の読み出しにGetRECharを使っているため、 // ここでサロゲートを処理する必要はない。 if P^ <> #0000 then Inc(P, Len); if roExtended in FOptions then while (P^ <> #0) and ((P^ = ' ') or (P^ = #9) or (P^ = #10) or (P^ = #13)) do Inc(P); end; procedure TRELex.CharPrev(var P: PWideChar; const Len: Integer); begin // TRELexでは文字の読み出しにGetRECharを使っているため、 // ここでサロゲートを処理する必要はない。 if P > FTopP then Dec(P, Len); if roExtended in FOptions then while (P^ <> #0) and ((P^ = ' ') or (P^ = #9) or (P^ = #10) or (P^ = #13)) do Dec(P); end; procedure TRELex.ClearOptionList; var I: Integer; P: PREOptions; begin for I := 0 to FOptionList.Count - 1 do if FOptionList[I] <> nil then begin P := FOptionList[I]; Dispose(P); end; FOptionList.Clear; end; constructor TRELex.Create(ARegExp: TSkRegExp; const Expression: REString); begin inherited Create; FOptionList := TList.Create; FRegExp := ARegExp; FOptions := FRegExp.FOptions; FP := PWideChar(Expression); FTopP := FP; FLastP := FP + Length(Expression); FPrevCount := 0; FPrevLex[0].FOptionList := TList.Create; FPrevLex[1].FOptionList := TList.Create; FPrevLex[2].FOptionList := TList.Create; end; destructor TRELex.Destroy; begin FPrevLex[0].FOptionList.Free; FPrevLex[1].FOptionList.Free; FPrevLex[2].FOptionList.Free; ClearOptionList; FOptionList.Free; inherited; end; procedure TRELex.Error(const Msg, Prefix: REString); var S, T: REString; begin T := GetErrorPositionString(GetCompileErrorPos); CharNext(FP); SetString(S, FTokenStartP, FP - FTokenStartP); if S <> '' then S := S + Prefix; S := Format(Msg, [S]); raise ESkRegExpCompile.CreateFmt('%s; %s', [S, T]); end; procedure TRELex.Error(const Msg: REString; APosition: Integer); var S, T: REString; begin T := GetErrorPositionString(APosition); CharNext(FP); SetString(S, FTokenStartP, FP - FTokenStartP); S := Format(Msg, [S]); raise ESkRegExpCompile.Create(Format('%s; %s', [S, T])); end; function TRELex.GetCompileErrorPos: Integer; begin if FP <> nil then Result := FP - FTopP + 1 else Result := 0; end; function TRELex.GetControlCode(var Len: Integer): UCS4Char; var P: PWideChar; begin Result := 0; CharNext(FP); P := FP; if ((P^ >= '@') and (P^ <= '_')) or ((P^ >= 'a') and (P^ <= 'z')) then begin if P^ = '\' then begin Inc(P); if P^ <> '\' then Error(sInvalidEscapeCharacterSyntax, GetCompileErrorPos); Inc(Len); end; Result := UCS4Char(P^); if (Result >= UCS4Char('a')) and (Result <= UCS4Char('z')) then Dec(Result, $20); Result := Result xor $40; end else Error(sInvalidEscapeCharacterSyntax, GetCompileErrorPos); end; function TRELex.GetDigit(var Len: Integer): Integer; var P: PWideChar; begin P := FP; Result := 0; while (P^ >= '0') and (P^ <= '9') do begin Result := Result * 10 + (Integer(P^) - Integer('0')); CharNext(P); end; Len := P - FP; end; function TRELex.GetErrorPositionString(APosition: Integer): REString; begin if APosition > 0 then Result := Copy(FRegExp.Expression, 1, APosition) + ' <-- ' + Copy(FRegExp.Expression, APosition + 1, MaxInt); end; function TRELex.GetHexDigit(var Len: Integer): UCS4Char; var P: PWideChar; I, L: Integer; IsBrace, Is6: Boolean; begin Result := 0; CharNext(FP); if FP^ = '{' then begin CharNext(FP); IsBrace := True; L := 6; end else begin IsBrace := False; L := 2; end; P := FP; Len := 0; Is6 := True; for I := 1 to L do begin case P^ of '0' .. '9': Result := (Result shl 4) + (UCS4Char(P^) - UCS4Char('0')); 'A' .. 'F': Result := (Result shl 4) + (UCS4Char(P^) - UCS4Char('7')); 'a' .. 'f': Result := (Result shl 4) + (UCS4Char(P^) - UCS4Char('W')); '}': begin if IsBrace then begin Is6 := False; Inc(Len); Break; end; end else begin FP := P; Error(sHexDigitIsRequired); end; end; CharNext(P); Inc(Len); end; if IsBrace and Is6 then begin if P^ <> '}' then begin FP := P; Error(sMissingRightBraceOnEscx); end; Inc(Len); end; if Len = 0 then begin FP := P; Error(sHexDigitIsRequired); end; if (DWORD(Result) > $10FFFF) then begin FP := P; Error(sCodePointRangeOver); end; end; function TRELex.GetOctalDigit(var Len: Integer): UCS4Char; var P: PWideChar; I: Integer; begin Result := 0; Len := 0; P := FP; for I := 1 to 3 do begin case P^ of '0' .. '7': Result := (Result shl 3) + (UCS4Char(P^) - UCS4Char('0')); else Break; end; Inc(Len); CharNext(P); end; end; function TRELex.GetRECompareOptions: TRECompareOptions; begin Result := REOptionsToRECompareOptions(FOptions); end; procedure TRELex.GetToken(Skip: Boolean); var L: Integer; begin if not Skip then Save; FConvert := False; FWChar := 0; FStartWChar := 0; FLastWChar := 0; FMin := 0; FMax := 0; FLevel := 0; FGroupName := ''; FTokenStartP := FP; L := 1; if roExtended in FOptions then SkipWhiteSpace; if FP^ = #0 then begin if FContext <> ctNormal then Error(sUnmatchedBigPar); FToken := tkEnd; Exit; end; if FContext = ctCharClass then begin if FP^ = ']' then begin if (FP + 1)^ <> ']' then begin FToken := tkCharClassEnd; FContext := ctNormal; CharNext(FP, 1); end else begin FWChar := UCS4Char(']'); FToken := tkChar; CharNext(FP, 1); end; end else LexCharClass; end else if FContext = ctQuote then begin if REStrLComp(FP, '\E', 2) = 0 then begin FContext := ctNormal; CharNext(FP, 2); GetToken(True); Exit; end; FWChar := GetREChar(FP, L, GetRECompareOptions); FToken := tkChar; CharNext(FP, L); end else begin if not FIsQuote then begin case FP^ of '|': FToken := tkUnion; '(': begin CharNext(FP); LexLeftPar; Exit; end; ')': FToken := tkRPar; '*': begin FToken := tkStar; FMin := 0; FMax := 0; end; '+': begin FToken := tkPlus; FMin := 1; FMax := 0; end; '?': FToken := tkQuest; '.': FToken := tkDot; '\': begin LexEscChar; Exit; end; '[': begin CharNext(FP); if FP^ = '^' then begin FContext := ctCharClass; FToken := tkNegativeCharClassFirst; end else if FP^ = ':' then LexPosixCharClass else begin CharPrev(FP); FContext := ctCharClass; FToken := tkCharClassFirst; end; end; '{': begin CharNext(FP); if (FP^ >= '0') and (FP^ <= '9') then begin LexBrace; Exit; end else begin CharPrev(FP); FWChar := GetREChar(FP, L, GetRECompareOptions); FToken := tkChar; end; end; '^': begin FWChar := GetREChar(FP, L, GetRECompareOptions); FToken := tkLHead; FConvert := True; end; '$': begin FWChar := GetREChar(FP, L, GetRECompareOptions); FToken := tkLTail; FConvert := True; end; else begin FWChar := GetREChar(FP, L, GetRECompareOptions); FToken := tkChar; end; end; end else begin FWChar := GetREChar(FP, L, GetRECompareOptions); FToken := tkChar; end; CharNext(FP, L); end; end; procedure TRELex.LexBrace; var I, L: Integer; begin SkipWhiteSpace; I := GetDigit(L); CharNext(FP, L); if I > CONST_LoopLimit then Error(sQuantifierIsTooLarge); FMin := I; if FP^ = ',' then begin CharNext(FP); SkipWhiteSpace; if (FP^ >= '0') and (FP^ <= '9') then begin I := GetDigit(L); CharNext(FP, L); if I > CONST_LoopLimit then Error(sQuantifierIsTooLarge); if I < FMin then Error(sCantDoMaxLessMin); FMax := I; end else FMax := CONST_LoopMax; end else FMax := FMin; if FP^ <> '}' then Error(sUnmatchedCurlyBracket); CharNext(FP); FToken := tkBound; end; procedure TRELex.LexCharClass; function GetConvertREChar(AWChar: UCS4Char; AOptions: TRECompareOptions): UCS4Char; var S: REString; begin S := UCS4CharToString(AWChar); if coIgnoreWidth in AOptions then S := ToWide(S); if coIgnoreKana in AOptions then S := ToKatakana(S); Result := ToUCS4Char(PWideChar(S)); end; var L: Integer; begin if FP^ = '\' then begin LexEscChar; L := 0; end else if REStrLComp(FP, '[:', 2) = 0 then begin CharNext(FP); LexPosixCharClass; L := 0; end else begin FWChar := GetREChar(FP, L, []); FToken := tkChar; end; CharNext(FP, L); if (FToken = tkChar) and (FP^ = '-') then begin CharNext(FP); FStartWChar := GetConvertREChar(FWChar, GetRECompareOptions); if FP^ <> ']' then begin if FP^ = '\' then begin LexEscChar; L := 0; if FToken <> tkChar then Error(sInvalideBigParRange, ''); end else begin FWChar := GetREChar(FP, L, []); FWChar := GetConvertREChar(FWChar, GetRECompareOptions); end; if FStartWChar > FWChar then Error(sInvalideBigParRange, ''); CharNext(FP, L); FLastWChar := FWChar; FToken := tkRangeChar; end else begin CharPrev(FP); FToken := tkChar; Exit; end; end; end; procedure TRELex.LexEscChar; var L, LTagNo: Integer; begin L := 1; CharNext(FP); if FP^ = #0 then Error(sRegExpNotCompleted, GetCompileErrorPos); case FP^ of 'A', 'B', 'E', 'G', 'K', 'Q', 'X', 'R', 'Z', 'b', 'g', 'k', 'z': begin if FContext = ctNormal then begin case FP^ of 'A': FToken := tkTHead; 'B': FToken := tkNEWordBoundary; 'Q': begin FContext := ctQuote; CharNext(FP); GetToken(True); Exit; end; 'Z': FToken := tkTTail; 'b': FToken := tkWordBoundary; 'k': begin CharNext(FP); case FP^ of '<': LexReference('>'); '''': LexReference(''''); '{': LexReference('}'); '1' .. '9', '+', '-': LexReference(#0000); else Error(sGroupNumberIsEmpty); end; Exit; end; 'R': FToken := tkLineBreak; 'z': FToken := tkTTailEnd; 'K': FToken := tkKeepPattern; 'X': FToken := tkCombiningSequence; 'G': FToken := tkGlobalPos; 'g': begin CharNext(FP); case FP^ of '<': LexGoSub('>'); '''': LexGoSub(''''); '{': LexReference('}'); '1' .. '9', '-': LexReference(#0000); else Error(sGroupNumberIsEmpty); end; Exit; end; end; end else begin FWChar := GetREChar(FP, L, GetRECompareOptions); FToken := tkChar; end; end; '1' .. '9': begin if FContext = ctNormal then begin LTagNo := GetDigit(L); if (LTagNo >= 1) and (LTagNo <= 9) then begin FMin := LTagNo; FToken := tkReference; end else begin if FRegExp.FGroups.Count < LTagNo then begin FWChar := GetOctalDigit(L); FToken := tkChar; end else begin FMin := LTagNo; FToken := tkReference; end; end; end else begin FWChar := GetOctalDigit(L); FToken := tkChar; end; end; 'p', 'P': begin if FP^ = 'P' then FToken := tkNEProperty else FToken := tkProperty; CharNext(FP); if FP^ = '{' then begin LexProperty(FToken = tkProperty); Exit; end else begin case FP^ of 'L': FUniCodeProperty := upL; 'M': FUniCodeProperty := upM; 'N': FUniCodeProperty := upN; 'P': FUniCodeProperty := upP; 'S': FUniCodeProperty := upS; 'Z': FUniCodeProperty := upZ; else Error(sInvalidProperty); end; end; end; 'D': FToken := tkNEDigitChar; 'H': {$IFDEF HIsHexDigit} FToken := tkNEHexDigitChar; {$ELSE} FToken := tkNEHorizontalSpaceChar; {$ENDIF} 'S': FToken := tkNESpaceChar; 'V': FToken := tkNEVerticalSpaceChar; 'W': FToken := tkNEWordChar; 'd': FToken := tkDigitChar; 'h': {$IFDEF HIsHexDigit} FToken := tkHexDigitChar; {$ELSE} FToken := tkHorizontalSpaceChar; {$ENDIF} 's': FToken := tkSpaceChar; 'v': FToken := tkVerticalSpaceChar; 'w': FToken := tkWordChar; else begin case FP^ of 'n': FWChar := $A; 'c': FWChar := GetControlCode(L); 'x': FWChar := GetHexDigit(L); '0': FWChar := GetOctalDigit(L); 't': FWChar := 9; 'r': FWChar := $D; 'f': FWChar := $C; 'a': FWChar := 7; 'e': FWChar := $1B; else FWChar := GetREChar(FP, L, GetRECompareOptions); end; FToken := tkChar; end; end; CharNext(FP, L); end; procedure TRELex.LexGoSub(const LastDelimiter: WideChar); var ATag, L: Integer; StartP: PWideChar; S: REString; IsMinus, IsPlus: Boolean; begin if LastDelimiter = #0000 then begin if (FP^ = '-') or (FP^ = '+') then begin IsMinus := FP^ = '-'; CharNext(FP); FToken := tkGoSubRelative; end else begin IsMinus := False; FToken := tkGoSub; end; ATag := GetDigit(L); if IsMinus then FMin := 0 - ATag else FMin := ATag; if L = 0 then Error(sGroupNumberIsEmpty); CharNext(FP, L); end else begin CharNext(FP); StartP := FP; IsMinus := FP^ = '-'; IsPlus := FP^ = '+'; if IsMinus or IsPlus then begin FToken := tkGoSubRelative; CharNext(FP); end else FToken := tkGoSub; if IsAnkDigit(FP) then begin ATag := GetDigit(L); if IsMinus then FMin := 0 - ATag else FMin := ATag; if L = 0 then Error(sGroupNumberIsEmpty); CharNext(FP, L); if FP^ <> LastDelimiter then Error(sNotTerminated); CharNext(FP, L); end else begin while FP^ <> #0 do begin if FP^ = LastDelimiter then begin SetString(S, StartP, FP - StartP); FGroupName := S; FToken := tkGoSubName; CharNext(FP); Exit; end; if UnicodeProp.IsWord(ToUCS4Char(FP)) then CharNext(FP) else Error(sInvalidCharInGroupName); end; Error(sNoEndOfGroup); end; end; end; procedure TRELex.LexGroupName(const LastDelimiter: WideChar); var S: REString; StartP: PWideChar; begin CharNext(FP); if (FP^ >= '0') and (FP^ <= '9') then Error(sInvalidCharInGroupName); StartP := FP; while FP^ <> #0 do begin if FP^ = LastDelimiter then begin SetString(S, StartP, FP - StartP); FGroupName := S; CharNext(FP); Exit; end else begin if not UnicodeProp.IsWord(ToUCS4Char(FP)) then Error(sInvalidCharInGroupName); CharNext(FP); end; end; Error(sNoEndOfGroup); end; procedure TRELex.LexLeftPar; var L: Integer; S: REString; StartP: PWideChar; begin L := 1; if FP^ = '?' then begin CharNext(FP); case FP^ of '-': begin CharNext(FP); if not IsAnkDigit(FP) then begin CharPrev(FP); LexOption; end else begin FMin := 0 - GetDigit(L); CharNext(FP, L); if FP^ <> ')' then Error(sUnmatchedSmallPar); FToken := tkGoSubRelative; end; end; 'i', 'm', 'n', 's', 'x', 'w', 'k': LexOption; '#': begin CharNext(FP); while FP^ <> #0 do begin if FP^ = ')' then begin CharNext(FP); GetToken(True); Exit; end; CharNext(FP); end; end; '>': FToken := tkNoBackTrack; ':': FToken := tkLPar; '''': begin LexGroupName(''''); FToken := tkGroupBegin; Exit; end; '<': begin CharNext(FP); if FP^ = '=' then FToken := tkBehindMatch else if FP^ = '!' then FToken := tkBehindNoMatch else begin CharPrev(FP); LexGroupName('>'); FToken := tkGroupBegin; Exit; end; end; ')': begin FToken := tkEmpty; end; 'P': begin CharNext(FP); if FP^ = '<' then begin LexGroupName('>'); FToken := tkGroupBegin; Exit; end else if FP^ = '=' then begin LexGroupName(')'); FToken := tkNamedReference; Exit; end else if FP^ = '>' then begin LexGroupName(')'); FToken := tkGoSubName; Exit; end else Error(sGroupNameIsEmpty, '...)'); end; '+': begin CharNext(FP); if IsAnkDigit(FP) then begin FMin := GetDigit(L); CharNext(FP, L); if FP^ <> ')' then Error(sUnmatchedSmallPar); FToken := tkGoSubRelative; end else Error(sGroupNumberIsEmpty); end; '=': FToken := tkAheadMatch; '!': begin CharNext(FP); if FP^ = ')' then FToken := tkFail else begin FToken := tkAheadNoMatch; Exit; end; end; '(': begin CharNext(FP); if IsAnkDigit(FP) then begin FMin := GetDigit(L); CharNext(FP, L); if FP^ = ')' then begin CharNext(FP); FToken := tkIfMatchRef; Exit; end else Error(sNotRecognized, '...)'); end else if FP^ = '<' then begin LexGroupName('>'); if FP^ = ')' then begin CharNext(FP); FToken := tkIfMatchRef; Exit; end; end else if FP^ = '''' then begin LexGroupName(''''); if FP^ = ')' then begin CharNext(FP); FToken := tkIfMatchRef; Exit; end; end else begin Dec(FP); FToken := tkIfMatch; Exit; end; end; 'R': begin FMin := 0; CharNext(FP); if FP^ <> ')' then Error(sUnmatchedSmallPar); FToken := tkGoSub; end; '&': begin CharNext(FP); StartP := FP; while FP^ <> #0000 do begin if FP^ = ')' then begin SetString(S, StartP, FP - StartP); CharNext(FP); FGroupName := S; FToken := tkGoSubName; Exit; end; CharNext(FP); end; Error(sUnmatchedSmallPar); end; '0' .. '9': begin FMin := GetDigit(L); CharNext(FP, L); if FP^ <> ')' then Error(sUnmatchedSmallPar); FToken := tkGoSub; end; '|': // branch reset FToken := tkBranchReset; else // case Error(sNotRecognized); end; end else // if begin if not(roNamedGroupOnly in FOptions) then FToken := tkGroupBegin else FToken := tkLPar; Exit; end; CharNext(FP, L); end; { .$WARNINGS OFF } {$WARNINGS ON} procedure TRELex.LexOption; var IsInclude: Boolean; AOption: TREOption; begin FNewOptions := FOptions; AOption := roNone; while FP^ <> #0 do begin if FP^ = '-' then begin IsInclude := False; CharNext(FP); end else IsInclude := True; case FP^ of 'i': AOption := roIgnoreCase; 'm': AOption := roMultiLine; 'n': AOption := roNamedGroupOnly; 's': AOption := roSingleLine; 'x': AOption := roExtended; {$IFDEF UseJapaneseOption} 'w': AOption := roIgnoreWidth; 'k': AOption := roIgnoreKana; {$ENDIF} else Error(sNotRecognized); end; if AOption <> roNone then begin if IsInclude then Include(FNewOptions, AOption) else Exclude(FNewOptions, AOption); end; CharNext(FP); if FP^ = ')' then begin FToken := tkOption; Exit; end else if FP^ = ':' then begin FToken := tkLParWithOption; Exit; end; end; Error(sOptionNotCompleted); end; procedure TRELex.LexPosixCharClass; {$WARNINGS OFF} function GetPosixType(const S: REString): TUnicodeProperty; begin Result := upAlnum; if SameStr(S, 'alnum') then Result := upAlnum else if SameStr(S, 'alpha') then Result := upAlpha else if SameStr(S, 'ascii') then Result := upAscii else if SameStr(S, 'blank') then Result := upBlank else if SameStr(S, 'cntrl') then Result := upCntrl else if SameStr(S, 'digit') then Result := upDigit else if SameStr(S, 'graph') then Result := upSpace else if SameStr(S, 'lower') then Result := upLower else if SameStr(S, 'print') then Result := upPrint else if SameStr(S, 'punct') then Result := upPunct else if SameStr(S, 'space') then Result := upSpace else if SameStr(S, 'upper') then Result := upUpper else if SameStr(S, 'xdigit') then Result := upXDigit else if SameStr(S, 'word') then Result := upWord else begin CharNext(FP); Error(Format(sPosixClassUnkown, [S])); end; end; {$WARNINGS ON} var IsNegative: Boolean; L: Integer; P: PWideChar; S: REString; begin CharNext(FP); if FP^ = '^' then begin IsNegative := True; CharNext(FP); end else IsNegative := False; P := FP; while P^ <> #0 do begin if (P^ = ']') or (P^ = #0) then begin FWChar := GetREChar(FP, L, []); FToken := tkChar; CharNext(FP, L); Exit; end else if P^ = ':' then begin SetString(S, FP, P - FP); FUniCodeProperty := GetPosixType(S); if IsNegative then FToken := tkNEPosixBracket else FToken := tkPosixBracket; CharNext(P); if P^ <> ']' then begin FP := P; Error(sUnmatchedBigPar); end; CharNext(P); FP := P; Break; end; CharNext(P); end; if not (FContext in [ctCharClass, ctNegativeCharClass]) then Error(sPosixClassSupportedOnlyClass); end; procedure TRELex.LexProperty(const CheckNegative: Boolean); var Index: Integer; S, S2, PreStr: REString; StartP: PWideChar; begin CharNext(FP); if CheckNegative and (FP^ = '^') then begin FToken := tkNEProperty; CharNext(FP); end; StartP := FP; while FP^ <> #0 do begin if FP^ = '}' then begin SetString(S, StartP, FP - StartP); // S := PreStr + S; if PropertyNames.Find(S, Index) then FUniCodeProperty := TUnicodeProperty(PropertyNames.Objects[Index]) else begin if UpperCase(Copy(S, 1, 2)) = 'IS' then begin S2 := 'In' + Copy(S, 3, MaxInt); if PropertyNames.Find(S2, Index) then FUniCodeProperty := TUnicodeProperty(PropertyNames.Objects[Index]) else Error(Format(sPropertyUnknown, [S])); end else Error(Format(sPropertyUnknown, [S])); end; CharNext(FP); Exit; end else if (FP^ = '-') or (FP^ = '_') or IsAnkSpace(FP) then begin SetString(S, StartP, FP - StartP); PreStr := PreStr + S; CharNext(FP); StartP := FP; end else if IsAnkWord(FP) or (FP^ = '&') then CharNext(FP) else Error(sInvalidProperty); end; Error(sMissingRightBrace); end; procedure TRELex.LexReference(const LastDelimiter: WideChar); var L: Integer; StartP: PWideChar; S: REString; IsMinus: Boolean; begin if LastDelimiter = #0000 then begin if FP^ = '-' then begin CharNext(FP); FToken := tkReferenceRelative; end else FToken := tkReference; FMin := GetDigit(L); if L = 0 then Error(sGroupNumberIsEmpty); CharNext(FP, L); end else begin CharNext(FP); StartP := FP; IsMinus := FP^ = '-'; if IsMinus then begin FToken := tkReferenceRelative; CharNext(FP); end else FToken := tkReference; if IsAnkDigit(FP) then begin FMin := GetDigit(L); if L = 0 then Error(sGroupNumberIsEmpty); CharNext(FP, L); if FP^ <> LastDelimiter then Error(sNotTerminated); CharNext(FP, L); end else begin if LastDelimiter = '>' then begin while FP^ <> #0 do begin if (FP^ = '>') then begin SetString(S, StartP, FP - StartP); FGroupName := S; FToken := tkNamedReference; if FP^ = '>' then begin CharNext(FP); Exit; end; end; if UnicodeProp.IsWord(ToUCS4Char(FP)) then CharNext(FP) else Error(sInvalidCharInGroupName); end; end else begin while FP^ <> #0 do begin if FP^ = LastDelimiter then begin SetString(S, StartP, FP - StartP); FGroupName := S; FToken := tkNamedReference; CharNext(FP); Exit; end; if UnicodeProp.IsWord(ToUCS4Char(FP)) then CharNext(FP) else Error(sInvalidCharInGroupName); end; end; Error(sNoEndOfGroup); end; end; end; procedure TRELex.PopOptions; var AOptions: PREOptions; begin if FOptionList.Count = 0 then Exit; AOptions := PREOptions(FOptionList[FOptionList.Count - 1]); FOptions := AOptions^; FOptionList.Delete(FOptionList.Count - 1); Dispose(AOptions); end; procedure TRELex.PushOptions; var AOptions: PREOptions; begin New(AOptions); AOptions^ := FOptions; FOptionList.Add(AOptions); end; procedure TRELex.PushToken; var I: Integer; begin case FPrevCount of 0: I := 2; 1: I := 0; else I := 1; end; if not FPrevLex[I].FStored then Exit; FPrevLex[I].FStored := False; FToken := FPrevLex[I].FToken; FOptions := FPrevLex[I].FOptions; FNewOptions := FPrevLex[I].FNewOptions; FP := FPrevLex[I].FP; FTokenStartP := FPrevLex[I].FTokenStartP; FTopP := FPrevLex[I].FTopP; FWChar := FPrevLex[I].FWChar; FStartWChar := FPrevLex[I].FStartWChar; FLastWChar := FPrevLex[I].FLastWChar; FMin := FPrevLex[I].FMin; FMax := FPrevLex[I].FMax; FLevel := FPrevLex[I].FLevel; FContext := FPrevLex[I].FContext; FUniCodeProperty := FPrevLex[I].FUniCodeProperty; FConvert := FPrevLex[I].FConvert; FGroupName := FPrevLex[I].FGroupName; FOptionList.Assign(FPrevLex[I].FOptionList); FIsQuote := FPrevLex[I].FIsQuote; case FPrevCount of 0: FPrevCount := 2; 1: FPrevCount := 0; 2: FPrevCount := 1; end; end; procedure TRELex.Save; var I: Integer; begin case FPrevCount of 0: I := 0; 1: I := 1; else I := 2; end; FPrevLex[I].FStored := True; FPrevLex[I].FToken := FToken; FPrevLex[I].FOptions := FOptions; FPrevLex[I].FNewOptions := FNewOptions; FPrevLex[I].FP := FP; FPrevLex[I].FTokenStartP := FTokenStartP; FPrevLex[I].FTopP := FTopP; FPrevLex[I].FWChar := FWChar; FPrevLex[I].FStartWChar := FStartWChar; FPrevLex[I].FLastWChar := FLastWChar; FPrevLex[I].FMin := FMin; FPrevLex[I].FMax := FMax; FPrevLex[I].FLevel := FLevel; FPrevLex[I].FContext := FContext; FPrevLex[I].FUniCodeProperty := FUniCodeProperty; FPrevLex[I].FConvert := FConvert; FPrevLex[I].FGroupName := FGroupName; FPrevLex[I].FOptionList.Assign(FOptionList); case FPrevCount of 0: FPrevCount := 1; 1: FPrevCount := 2; 2: FPrevCount := 0; end; end; procedure TRELex.SkipWhiteSpace; begin while (FP^ <> #0) and ((FP^ = ' ') or (FP^ = #9) or (FP^ = #10) or (FP^ = #13)) do Inc(FP); end; procedure TRELex.UpdateOptions; begin FOptions := FNewOptions; end; { TREParser } constructor TREParser.Create(ARegExp: TSkRegExp; const Expression: REString); begin inherited Create; FRegExp := ARegExp; FLex := TRELex.Create(ARegExp, Expression); FGroupStack := TStack.Create; FReferenceErrorList := TREStringList.Create; FGoSubErrorList := TREStringList.Create; end; destructor TREParser.Destroy; var I: Integer; P: PReferenceErrorRec; begin for I := 0 to FReferenceErrorList.Count - 1 do begin P := PReferenceErrorRec(FReferenceErrorList.Objects[I]); Dispose(P); end; FReferenceErrorList.Free; for I := 0 to FGoSubErrorList.Count - 1 do begin P := PReferenceErrorRec(FGoSubErrorList.Objects[I]); Dispose(P); end; FGoSubErrorList.Free; FLex.Free; FGroupStack.Free; inherited; end; function TREParser.Factor: TRECode; procedure SetMinMatch(BinCode: TRECode); begin if not(BinCode is TREBinCode) then FLex.Error(sQuestPosInaccurate); (BinCode as TREBinCode).MatchKind := lkReluctant; end; procedure SetMaxMatch(BinCode: TRECode); begin if not(BinCode is TREBinCode) then FLex.Error(sQuestPosInaccurate); (BinCode as TREBinCode).MatchKind := lkPossessive; end; procedure CheckAheadMatch(ACode: TRECode); begin if ACode is TREBinCode then begin with ACode as TREBinCode do begin if (FOp = opAheadMatch) or (FOp = opAheadNoMatch) then FLex.Error(sLoopOfMatchAheadNotSpecified); end; end; end; procedure CheckEmptyLoop(ACode: TRECode); begin if (ACode is TREBoundaryCode) or (ACode is TRETextHeadCode) or (ACode is TRETextTailCode) or (ACode is TRETextEndCode) then FLex.Error(sLoopOfLengthZeroCannotSpecified); end; var LMin, LMax: Integer; LToken: TREToken; LMatchKind: TRELoopKind; begin Result := Primay; if FLex.Token in [tkStar, tkPlus, tkQuest, tkBound] then begin LToken := FLex.Token; LMin := FLex.Min; LMax := FLex.Max; CheckAheadMatch(Result); CheckEmptyLoop(Result); FLex.GetToken; if FLex.Token = tkQuest then begin LMatchKind := lkReluctant; FLex.GetToken; end else if FLex.Token = tkPlus then begin LMatchKind := lkPossessive; FLex.GetToken; end else LMatchKind := lkGreedy; case LToken of tkStar: begin if (Result is TREAnyCharCode) and (LMatchKind = lkGreedy) then begin Result := NewBinCode(opStar, Result, nil, 0, CONST_LoopMax); TREBinCode(Result).MatchKind := lkAny; end else if (Result is TRECombiningSequence) and (LMatchKind = lkGreedy) and (LMatchKind = lkGreedy) then begin Result := NewBinCode(opStar, Result, nil, 0, CONST_LoopMax); TREBinCode(Result).MatchKind := lkCombiningSequence; end else begin Result := NewBinCode(opLoop, Result, nil, 0, CONST_LoopMax); TREBinCode(Result).MatchKind := LMatchKind; end; end; tkPlus: begin if not(Result is TREBinCode) and (LMatchKind = lkGreedy) then begin Result := NewBinCode(opPlus, Result, nil, 1, CONST_LoopMax); TREBinCode(Result).MatchKind := LMatchKind; end else begin Result := NewBinCode(opLoop, Result, nil, 1, CONST_LoopMax); TREBinCode(Result).MatchKind := LMatchKind; end; end; tkQuest: begin // Result := NewBinCode(opLoop, Result, nil, 0, 1); Result := NewBinCode(opQuest, Result, nil); TREBinCode(Result).MatchKind := LMatchKind; end; tkBound: begin if not(Result is TREBinCode) and (LMatchKind = lkGreedy) then begin Result := NewBinCode(opBound, Result, nil, LMin, LMax); TREBinCode(Result).MatchKind := LMatchKind; end else begin Result := NewBinCode(opLoop, Result, nil, LMin, LMax); TREBinCode(Result).MatchKind := LMatchKind; end; end; end; end; end; function TREParser.NewBinCode(AOperator: TREOperator; ALeft, ARight: TRECode; AMin, AMax: Integer): TRECode; begin Result := TREBinCode.Create(FRegExp, AOperator, ALeft, ARight, AMin, AMax); FRegExp.FBinCodeList.Add(Result); end; function TREParser.NewCharClassCode(ANegative: Boolean): TRECode; var CharClass: TRECharClassCode; begin CharClass := TRECharClassCode.Create(FRegExp, ANegative, FLex.Options); FRegExp.FCodeList.Add(CharClass); Result := CharClass; FLex.GetToken; case FLex.Token of tkChar: CharClass.Add(FLex.FWChar); tkRangeChar: CharClass.Add(FLex.StartWChar, FLex.LastWChar); tkWordChar: CharClass.Add(TREWordCharCode.Create(FRegExp, False)); tkDigitChar: CharClass.Add(TREDigitCharCode.Create(FRegExp, False)); tkSpaceChar: CharClass.Add(TRESpaceCharCode.Create(FRegExp, False)); tkNEWordChar: CharClass.Add(TREWordCharCode.Create(FRegExp, True)); tkNEDigitChar: CharClass.Add(TREDigitCharCode.Create(FRegExp, True)); tkNESpaceChar: CharClass.Add(TRESpaceCharCode.Create(FRegExp, True)); tkPosixBracket: CharClass.Add(TREPropertyCode.Create(FRegExp, FLex.UnicodeProperty, False)); tkNEPosixBracket: CharClass.Add(TREPropertyCode.Create(FRegExp, FLex.UnicodeProperty, True)); tkProperty: CharClass.Add(TREPropertyCode.Create(FRegExp, FLex.UnicodeProperty, False)); tkNEProperty: CharClass.Add(TREPropertyCode.Create(FRegExp, FLex.UnicodeProperty, True)); tkHexDigitChar: CharClass.Add(TREHexDigitCharCode.Create(FRegExp, False)); tkNEHexDigitChar: CharClass.Add(TREHexDigitCharCode.Create(FRegExp, True)); tkHorizontalSpaceChar: CharClass.Add(TREHorizontalSpaceCharCode.Create(FRegExp, False)); tkNEHorizontalSpaceChar: CharClass.Add(TREHorizontalSpaceCharCode.Create(FRegExp, True)); tkVerticalSpaceChar: CharClass.Add(TREVerticalSpaceCharCode.Create(FRegExp, False)); tkNEVerticalSpaceChar: CharClass.Add(TREVerticalSpaceCharCode.Create(FRegExp, True)); else FLex.Error(sInvalidCharactorClass); end; FLex.GetToken; while (FLex.Token = tkRangeChar) or (FLex.Token = tkChar) or (FLex.Token = tkWordChar) or (FLex.Token = tkNEWordChar) or (FLex.Token = tkDigitChar) or (FLex.Token = tkNEDigitChar) or (FLex.Token = tkSpaceChar) or (FLex.Token = tkNESpaceChar) or (FLex.Token = tkPosixBracket) or (FLex.Token = tkNEPosixBracket) or (FLex.Token = tkProperty) or (FLex.Token = tkNEProperty) or (FLex.Token = tkHexDigitChar) or (FLex.Token = tkNEHexDigitChar) or (FLex.Token = tkHorizontalSpaceChar) or (FLex.Token = tkNEHorizontalSpaceChar) or (FLex.Token = tkVerticalSpaceChar) or (FLex.Token = tkNEVerticalSpaceChar) do begin case FLex.Token of tkChar: CharClass.Add(FLex.WChar); tkRangeChar: CharClass.Add(FLex.StartWChar, FLex.LastWChar); tkWordChar: CharClass.Add(TREWordCharCode.Create(FRegExp, False)); tkDigitChar: CharClass.Add(TREDigitCharCode.Create(FRegExp, False)); tkSpaceChar: CharClass.Add(TRESpaceCharCode.Create(FRegExp, False)); tkNEWordChar: CharClass.Add(TREWordCharCode.Create(FRegExp, True)); tkNEDigitChar: CharClass.Add(TREDigitCharCode.Create(FRegExp, True)); tkNESpaceChar: CharClass.Add(TRESpaceCharCode.Create(FRegExp, True)); tkPosixBracket: CharClass.Add(TREPropertyCode.Create(FRegExp, FLex.UnicodeProperty, False)); tkNEPosixBracket: CharClass.Add(TREPropertyCode.Create(FRegExp, FLex.UnicodeProperty, True)); tkProperty: CharClass.Add(TREPropertyCode.Create(FRegExp, FLex.UnicodeProperty, False)); tkNEProperty: CharClass.Add(TREPropertyCode.Create(FRegExp, FLex.UnicodeProperty, True)); tkHexDigitChar: CharClass.Add(TREHexDigitCharCode.Create(FRegExp, False)); tkNEHexDigitChar: CharClass.Add(TREHexDigitCharCode.Create(FRegExp, True)); tkHorizontalSpaceChar: CharClass.Add(TREHorizontalSpaceCharCode.Create(FRegExp, False)); tkNEHorizontalSpaceChar: CharClass.Add(TREHorizontalSpaceCharCode.Create(FRegExp, True)); tkVerticalSpaceChar: CharClass.Add(TREVerticalSpaceCharCode.Create(FRegExp, False)); tkNEVerticalSpaceChar: CharClass.Add(TREVerticalSpaceCharCode.Create(FRegExp, True)); else FLex.Error(sInvalidCharactorClass); end; FLex.GetToken; end; if FLex.Token <> tkCharClassEnd then FLex.Error(sUnmatchedBigPar); CharClass.Rebuild; end; procedure TREParser.Parse; var I, P: Integer; RefError: PReferenceErrorRec; begin FGroupCount := 0; FCurrentGroup := 0; FGroupLevel := 0; FLex.GetToken; FRegExp.FCode := RegExpr; if FLex.Token <> tkEnd then begin if FLex.Token = tkRPar then FLex.Error(sUnmatchedSmallPar) else FLex.Error(sRegExpNotCompleted); end; for I := 0 to FReferenceErrorList.Count - 1 do begin RefError := PReferenceErrorRec(FReferenceErrorList.Objects[I]); if FReferenceErrorList[I] <> '' then begin if FRegExp.FGroups.IndexOfName(FReferenceErrorList[I]) = -1 then begin FLex.Error(Format(sInvalidGroupName, [FReferenceErrorList[I]]), RefError.ErrorPos); end else begin TRENamedReferenceCode(RefError.AObject).SetGroupIndexArray( FRegExp.FGroups.EnumIndexOfName(FReferenceErrorList[I])); end; end else begin if RefError.GroupIndex > FGroupCount then FLex.Error(Format(sInvalidGroupNumber, [RefError.GroupIndex]), RefError.ErrorPos) else if (0 - RefError.GroupIndex + 1 > FGroupCount) then FLex.Error(Format(sInvalidGroupNumber, [RefError.GroupIndex]), RefError.ErrorPos) end; end; for I := 0 to FGoSubErrorList.Count - 1 do begin RefError := PReferenceErrorRec(FGoSubErrorList.Objects[I]); if FGoSubErrorList[I] <> '' then begin P := FRegExp.FGroups.IndexOfName(FGoSubErrorList[I]); if P = -1 then FLex.Error(Format(sInvalidGroupName, [FGoSubErrorList[I]]), RefError.ErrorPos); if FRegExp.FGroups.IsDuplicateGroupName(FGoSubErrorList[I]) then FLex.Error(Format(sCannotCallMultipleDefineGroupName, [FGoSubErrorList[I]]), RefError.ErrorPos); end else begin if RefError.GroupIndex > FGroupCount then FLex.Error(Format(sInvalidGroupNumber, [RefError.GroupIndex]), RefError.ErrorPos) else if (0 - RefError.GroupIndex + 1 > FGroupCount) then FLex.Error(Format(sInvalidGroupNumber, [RefError.GroupIndex]), RefError.ErrorPos) end; end; end; function TREParser.Primay: TRECode; function CheckBehindMatchSub(ACode: TRECode; IsMatch: Boolean; var ErrCode: Integer): Boolean; var SubCode: TREBinCode; begin if (ACode is TREBinCode) then begin SubCode := (ACode as TREBinCode); if SubCode.FOp = opUnion then begin Result := False; ErrCode := 1; end else if not IsMatch and (SubCode.FOp = opGroup) then begin Result := False; ErrCode := 2; end else begin if (SubCode.Left <> nil) and not CheckBehindMatchSub(SubCode.Left, IsMatch, ErrCode) then begin Result := False; Exit; end; if (SubCode.Right <> nil) and not CheckBehindMatchSub(SubCode.Right, IsMatch, ErrCode) then begin Result := False; Exit; end; Result := True; end; end else Result := True; end; procedure CheckBehindMatch(ACode: TRECode; IsMatch: Boolean); var ErrCode: Integer; Ret: Boolean; begin ErrCode := 0; if (ACode is TREBinCode) then begin if (ACode as TREBinCode).FOp = opUnion then Ret := True else Ret := CheckBehindMatchSub(ACode, IsMatch, ErrCode); end else Ret := True; if not Ret then if ErrCode = 1 then FLex.Error(sBehindMatchNotVariableLength) else FLex.Error(sBehindMatchNotGroup); end; type TMatchLengthRec = record AMin, AMax: Integer; HasQuest: Boolean; end; PMatchLengthRec = ^TMatchLengthRec; function GetMatchLengthSub(ACode: TRECode; var MatchLen: TMatchLengthRec): Integer; var SubCode: TRECode; BinCode: TREBinCode; L, R: Integer; begin Result := 0; SubCode := ACode; if (SubCode is TREBinCode) then begin BinCode := (SubCode as TREBinCode); if BinCode.Op = opGroup then Result := Result + GetMatchLengthSub(BinCode.Left, MatchLen) else if BinCode.Op = opConcat then begin Result := Result + GetMatchLengthSub(BinCode.Left, MatchLen); Result := Result + GetMatchLengthSub(BinCode.Right, MatchLen); end else if BinCode.Op = opUnion then begin L := GetMatchLengthSub(BinCode.Left, MatchLen); R := GetMatchLengthSub(BinCode.Right, MatchLen); if L > R then begin MatchLen.AMax := Max(MatchLen.AMax, L); if not MatchLen.HasQuest then MatchLen.AMin := Max(MatchLen.AMin, R);; end else begin MatchLen.AMax := Max(MatchLen.AMax, R); if not MatchLen.HasQuest then MatchLen.AMin := Max(MatchLen.AMin, L);; end; end else if BinCode.Op = opQuest then begin MatchLen.AMin := Min(MatchLen.AMin, 0); MatchLen.AMax := Max(MatchLen.AMax, GetMatchLengthSub(BinCode.Left, MatchLen)); end; end else if ACode.CharLength <> 0 then begin if ACode is TRECharCode then Inc(Result) else if ACode is TRELiteralCode then Inc(Result, (ACode as TRELiteralCode).Length); end; end; procedure GetMatchLength(ACode: TRECode; var MatchLen: TMatchLengthRec); begin MatchLen.AMin := 0; MatchLen.AMax := 0; MatchLen.HasQuest := False; if ACode is TRELiteralCode then begin MatchLen.AMax := GetMatchLengthSub(ACode, MatchLen); MatchLen.AMin := MatchLen.AMax; end else begin if GetMatchLengthSub(ACode, MatchLen) = 1 then begin MatchLen.AMin := 1; MatchLen.AMax := 1; end; end; end; procedure CheckRecursion(SubCode: TRECode); begin if SubCode is TREBinCode then begin if (SubCode as TREBinCode).Op = opGoSub then FLex.Error(sNeverEndingRecursion) else if (SubCode as TREBinCode).Op = opUnion then begin CheckRecursion((SubCode as TREBinCode).Left); CheckRecursion((SubCode as TREBinCode).Right); end; end end; // 10進表記の数値を8進数に変換。あくまでも10進表記 function ToOctal(const ADigit: Integer): Integer; var I: Integer; S: REString; begin Result := 0; S := IntToStr(ADigit); for I := 1 to Length(S) do begin case S[I] of '0' .. '7': Result := (Result shl 3) + (Integer(S[I]) - Integer('0')); else Break; end; end; end; var LGroupNo, LGroupBuffer: Integer; LGroupName: REString; SubCode, CondCode: TRECode; LMatchLen: TMatchLengthRec; RefError: PReferenceErrorRec; LGroupArray: TIntDynArray; LOptions: TREOptions; LWChar: UCS4Char; LConvert: Boolean; Str: UCS4String; Len: Integer; begin Result := nil; case FLex.Token of tkChar: begin Len := 1; LWChar := FLex.WChar; LOptions := FLex.Options; LConvert := FLex.Convert; SetLength(Str, Len); Str[Len - 1] := FLex.FWChar; Inc(Len); FLex.GetToken; while (FLex.Token = tkChar) and (FLex.Options = LOptions) do begin FLex.GetToken; if FLex.Token in [tkQuest, tkStar, tkBound, tkPlus] then begin FLex.PushToken; Break; end; FLex.PushToken; SetLength(Str, Len); Str[Len - 1] := FLex.FWChar; Inc(Len); FLex.GetToken; end; if Length(Str) > 1 then Result := TRELiteralCode.Create(FRegExp, Str, FLex.Options) else Result := TRECharCode.Create(FRegExp, LWChar, LOptions, LConvert); FRegExp.FCodeList.Add(Result); end; tkLHead: begin Result := TRECharCode.Create(FRegExp, FLex.WChar, FLex.Options, FLex.Convert); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkLTail: begin Result := TRECharCode.Create(FRegExp, FLex.WChar, FLex.Options, FLex.Convert); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkDot: begin Result := TREAnyCharCode.Create(FRegExp, FLex.Options); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkWordChar, tkNEWordChar: begin Result := TREWordCharCode.Create(FRegExp, FLex.Token = tkNEWordChar); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkDigitChar, tkNEDigitChar: begin Result := TREDigitCharCode.Create(FRegExp, FLex.Token = tkNEDigitChar); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkHexDigitChar, tkNEHexDigitChar: begin Result := TREHexDigitCharCode.Create(FRegExp, FLex.Token = tkNEHexDigitChar); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkSpaceChar, tkNESpaceChar: begin Result := TRESpaceCharCode.Create(FRegExp, FLex.Token = tkNESpaceChar); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkCharClassFirst, tkNegativeCharClassFirst: begin Result := NewCharClassCode(FLex.Token = tkNegativeCharClassFirst); FLex.GetToken; end; tkTHead: begin Result := TRETextHeadCode.Create(FRegExp); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkTTail: begin Result := TRETextTailCode.Create(FRegExp); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkTTailEnd: begin Result := TRETextEndCode.Create(FRegExp); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkReference, tkReferenceRelative: begin if FLex.Token = tkReference then begin LGroupNo := FLex.Min; if LGroupNo > FGroupCount then begin New(RefError); LGroupNo := FLex.Min; RefError.AObject := nil; RefError.GroupIndex := LGroupNo; RefError.ErrorPos := FLex.GetCompileErrorPos; FReferenceErrorList.AddObject('', TObject(RefError)); end; end else begin if FGroupCount < FLex.Min then FLex.Error(Format(sInvalidGroupNumber, [0 - FLex.Min])); LGroupNo := FGroupCount - FLex.Min + 1; end; Result := TREReferenceCode.Create(FRegExp, LGroupNo, FLex.Options); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkNamedReference: begin LGroupArray := FRegExp.FGroups.EnumIndexOfName(FLex.GroupName); if Length(LGroupArray) = 0 then begin New(RefError); RefError.GroupIndex := -1; RefError.AObject := nil; RefError.ErrorPos := FLex.GetCompileErrorPos; FReferenceErrorList.AddObject(FLex.GroupName, TObject(RefError)); end; if (FCurrentGroup > 0) then begin while LGroupArray[0] >= FCurrentGroup do LGroupArray := Copy(LGroupArray, 1, MaxInt); end; Result := TRENamedReferenceCode.Create(FRegExp, FLex.GroupName, LGroupArray, FLex.Options); if Length(LGroupArray) = 0 then PReferenceErrorRec( FReferenceErrorList.Objects[FReferenceErrorList.Count - 1]).AObject := Result; FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkWordBoundary, tkNEWordBoundary: begin Result := TREBoundaryCode.Create(FRegExp, FLex.Token = tkNEWordBoundary); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkHorizontalSpaceChar, tkNEHorizontalSpaceChar: begin Result := TREHorizontalSpaceCharCode.Create(FRegExp, FLex.Token = tkNEHorizontalSpaceChar); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkVerticalSpaceChar, tkNEVerticalSpaceChar: begin Result := TREVerticalSpaceCharCode.Create(FRegExp, FLex.Token = tkNEVerticalSpaceChar); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkLineBreak: begin Result := TRELineBreakCharCode.Create(FRegExp); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkGroupBegin: begin FLex.PushOptions; Inc(FGroupCount); Inc(FGroupLevel); FGroupStack.Push(Pointer(FCurrentGroup)); FCurrentGroup := FGroupCount; LGroupName := FLex.FGroupName; if FGroupCount > FRegExp.FGroups.Count - 1 then LGroupNo := FRegExp.FGroups.Add(FLex.GroupName, -1, -1) else LGroupNo := FGroupCount; FLex.GetToken; Result := NewBinCode(opGroup, RegExpr, nil); if FLex.Token <> tkRPar then FLex.Error(sUnmatchedSmallPar); FCurrentGroup := Integer(FGroupStack.Pop); Dec(FGroupLevel); if FHasRecursion then CheckRecursion(Result); (Result as TREBinCode).GroupIndex := LGroupNo; if LGroupName <> '' then (Result as TREBinCode).GroupName := LGroupName; FLex.PopOptions; FLex.GetToken; end; tkLPar: begin FLex.PushOptions; FLex.GetToken; Result := RegExpr; if FLex.Token <> tkRPar then FLex.Error(sUnmatchedSmallPar); FLex.PopOptions; FLex.GetToken; end; tkLParWithOption: begin FLex.PushOptions; FLex.UpdateOptions; FLex.GetToken; Result := RegExpr; if FLex.Token <> tkRPar then FLex.Error(sUnmatchedSmallPar); FLex.PopOptions; FLex.GetToken; end; tkOption: begin FLex.UpdateOptions; if FGroupLevel = 0 then FRegExp.Options := FLex.Options; FLex.GetToken; Result := RegExpr; end; tkProperty: begin Result := TREPropertyCode.Create(FRegExp, FLex.UnicodeProperty, False); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkNEProperty: begin Result := TREPropertyCode.Create(FRegExp, FLex.UnicodeProperty, True); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkNoBackTrack: begin FLex.GetToken; Result := NewBinCode(opNoBackTrack, RegExpr, nil); if FLex.Token <> tkRPar then FLex.Error(sUnmatchedSmallPar); FLex.GetToken; end; tkKeepPattern: begin FLex.GetToken; Result := NewBinCode(opKeepPattern, RegExpr, nil); end; tkFail: begin FLex.GetToken; Result := NewBinCode(opFail, RegExpr, nil); end; tkCombiningSequence: begin Result := TRECombiningSequence.Create(FRegExp); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkGlobalPos: begin Result := TREGlobalPosCode.Create(FRegExp); FRegExp.FCodeList.Add(Result); FLex.GetToken; end; tkGoSub, tkGoSubRelative: begin if FLex.Token = tkGoSub then begin LGroupNo := FLex.Min; if LGroupNo > FGroupCount then begin New(RefError); RefError.IsRelative := False; RefError.GroupIndex := FLex.Min; RefError.AObject := nil; RefError.ErrorPos := FLex.GetCompileErrorPos; FReferenceErrorList.AddObject('', TObject(RefError)); end; end else begin LGroupBuffer := FLex.Min; if LGroupBuffer < 0 then LGroupNo := FGroupCount - LGroupBuffer - 1 else LGroupNo := FGroupCount + LGroupBuffer; if LGroupNo < 1 then FRegExp.Error(Format(sRangeOverGroupNumber, [LGroupBuffer])); if LGroupNo > FGroupCount then begin New(RefError); RefError.IsRelative := True; RefError.RelativeGourpIndex := FLex.Min; RefError.AObject := nil; RefError.ErrorPos := FLex.GetCompileErrorPos; FReferenceErrorList.AddObject('', TObject(RefError)); end; if LGroupNo < 0 then LGroupNo := FGroupCount - LGroupNo - 1 else LGroupNo := FGroupCount + LGroupNo; end; Result := NewBinCode(opGoSub, nil, nil); (Result as TREBinCode).GroupIndex := LGroupNo; FHasRecursion := not FHasRecursion and (LGroupNo = FGroupLevel); (Result as TREBinCode).HasRecursion := FHasRecursion; FLex.GetToken; end; tkGoSubName: begin LGroupNo := FRegExp.FGroups.IndexOfName(FLex.GroupName); if LGroupNo = -1 then begin New(RefError); RefError.GroupIndex := -1; RefError.AObject := nil; RefError.ErrorPos := FLex.GetCompileErrorPos; FGoSubErrorList.AddObject(FLex.GroupName, TObject(RefError)); end; Result := NewBinCode(opGoSub, nil, nil); (Result as TREBinCode).GroupName := FLex.GroupName; (Result as TREBinCode).GroupIndex := LGroupNo; if LGroupNo <> -1 then FHasRecursion := LGroupNo <= FGroupLevel else FHasRecursion := False; (Result as TREBinCode).HasRecursion := FHasRecursion; FLex.GetToken; end; tkAheadMatch: begin FLex.GetToken; Result := NewBinCode(opAheadMatch, RegExpr, nil); if FLex.Token <> tkRPar then FLex.Error(sUnmatchedSmallPar); FLex.GetToken; end; tkAheadNoMatch: begin FLex.GetToken; Result := NewBinCode(opAheadNoMatch, RegExpr, nil); if FLex.Token <> tkRPar then FLex.Error(sUnmatchedSmallPar); FLex.GetToken; end; tkBehindMatch: begin FLex.GetToken; SubCode := RegExpr; Result := NewBinCode(opBehindMatch, SubCode, nil); if FLex.Token <> tkRPar then FLex.Error(sUnmatchedSmallPar); CheckBehindMatch(SubCode, True); GetMatchLength(SubCode, LMatchLen); (Result as TREBinCode).FMax := LMatchLen.AMax; (Result as TREBinCode).FMin := LMatchLen.AMin; FLex.GetToken; end; tkBehindNoMatch: begin FLex.GetToken; SubCode := RegExpr; Result := NewBinCode(opBehindNoMatch, SubCode, nil); if FLex.Token <> tkRPar then FLex.Error(sUnmatchedSmallPar); CheckBehindMatch(SubCode, False); CheckBehindMatch(SubCode, True); GetMatchLength(SubCode, LMatchLen); (Result as TREBinCode).FMax := LMatchLen.AMax; (Result as TREBinCode).FMin := LMatchLen.AMin; FLex.GetToken; end; tkIfMatchRef: begin FLex.PushOptions; if FLex.Min = 0 then begin CondCode := TREIfThenNamedReferenceCode.Create(FRegExp, FLex.GroupName); FRegExp.FCodeList.Add(CondCode); end else begin CondCode := TREIfThenReferenceCode.Create(FRegExp, FLex.Min); FRegExp.FCodeList.Add(CondCode); end; FLex.GetToken; Result := Term; if FLex.Token = tkUnion then begin FLex.GetToken; SubCode := Term; end else SubCode := nil; if FLex.Token <> tkRPar then FLex.Error(sUnmatchedSmallPar); Result := NewBinCode(opIfThen, Result, SubCode); Result := NewBinCode(opIfMatch, CondCode, Result); FLex.PopOptions; FLex.GetToken; end; tkIfMatch: begin FLex.PushOptions; FLex.GetToken; CondCode := Primay; if (CondCode is TREBinCode) and not((CondCode as TREBinCode).Op in [opAheadMatch, opAheadNoMatch, opBehindMatch, opBehindNoMatch]) then FLex.Error(sInvalideCondition); Result := Term; if FLex.Token = tkUnion then begin FLex.GetToken; SubCode := Term; end else SubCode := nil; if FLex.Token <> tkRPar then FLex.Error(sContainsTooManyBranches); Result := NewBinCode(opIfThen, Result, SubCode); Result := NewBinCode(opIfMatch, CondCode, Result); FLex.PopOptions; FLex.GetToken; end; tkBranchReset: begin FLex.PushOptions; LGroupNo := FGroupCount; LGroupBuffer := LGroupNo; FLex.GetToken; Result := Term; while FLex.Token = tkUnion do begin LGroupBuffer := FGroupCount; FGroupCount := LGroupNo; FLex.GetToken; Result := NewBinCode(opUnion, Result, Term); end; if FLex.Token <> tkRPar then FLex.Error(sUnmatchedSmallPar); FGroupLevel := LGroupBuffer; FLex.PopOptions; FLex.GetToken; end; tkEmpty: begin Result := NewBinCode(opEmply, nil, nil); FLex.GetToken; end; else FLex.Error(sNotRecognized); end; end; function TREParser.RegExpr: TRECode; begin Result := Term; while FLex.Token = tkUnion do begin FLex.GetToken; Result := NewBinCode(opUnion, Result, Term); end; end; function TREParser.Term: TRECode; begin if (FLex.Token = tkUnion) or (FLex.Token = tkRPar) or (FLex.Token = tkEnd) then Result := NewBinCode(opEmply, nil, nil) else begin Result := Factor; while (FLex.Token <> tkUnion) and (FLex.Token <> tkRPar) and (FLex.Token <> tkEnd) do Result := NewBinCode(opConcat, Result, Factor); end; end; { TRENFAState } {$IFDEF DEBUG} function TRENFAState.GetString: REString; var MatchTypeStr: REString; begin if FKind = nkEmpty then Result := Format(sFmtDumpNFA_Empty, [FTransitTo]) else if FKind = nkLoop then begin case FMatchKind of lkReluctant: MatchTypeStr := 'R'; lkPossessive: MatchTypeStr := 'P'; else MatchTypeStr := 'G'; end; Result := Format(sFmtDumpNFA_Loop, [MatchTypeStr, FMin, FMax, FTransitTo]); end else if FKind = nkEnd then Result := Format(sFmtDumpNFA_EndStr, [FTransitTo]) else if FKind = nkLoopExit then Result := Format(sFmtDumpNFA_LoopExit, [FTransitTo]) else if FKind = nkLoopEnd then Result := Format(sFmtDumpNFA_LoopEnd, [FTransitTo]) // else if FKind = nkQuest then // Result := Format(sFmtDumpNFA_Quest, [FTransitTo]) else if FKind = nkStar then Result := Format(sFmtDumpNFA_Star, [FTransitTo, FCode.GetDebugStr]) else if FKind = nkPlus then Result := Format(sFmtDumpNFA_Plus, [FTransitTo, FCode.GetDebugStr]) else if FKind = nkBound then Result := Format(sFmtDumpNFA_Bound, [FTransitTo]) else if FKind = nkMatchEnd then Result := Format(sFmtDumpNFA_MatchEnd, [FTransitTo]) else if FKind = nkGroupBegin then Result := Format(sFmtDumpNFA_GroupStart, [FGroupIndex, FTransitTo]) else if FKind = nkGroupEnd then Result := Format(sFmtDumpNFA_GroupEnd, [FGroupIndex, FTransitTo]) else if FKind = nkNoBackTrack then Result := Format(sFmtDumpNFA_NoBackTrackBegin, [FTransitTo]) else if FKind = nkFail then Result := Format(sFmtDumpNFA_Fail, [FTransitTo]) else if FKind = nkAheadMatch then Result := Format(sFmtDumpNFA_AheadMatch, [FTransitTo]) else if FKind = nkAheadNoMatch then Result := Format(sFmtDumpNFA_AheadNoMatch, [FTransitTo]) else if FKind = nkBehindMatch then Result := Format(sFmtDumpNFA_BehindMatch, [FTransitTo]) else if FKind = nkBehindNoMatch then Result := Format(sFmtDumpNFA_BehindNoMatch, [FTransitTo]) else if FKind = nkGoSub then Result := Format(sFmtDumpNFA_GoSub, [FGroupIndex, FTransitTo]) else if FKind = nkIfMatch then Result := Format(sFmtDumpNFA_IfMatch, [FTransitTo]) else if FKind = nkIfThen then Result := Format(sFmtDumpNFA_IfThen, [FTransitTo]) else if FKind = nkKeepPattern then Result := Format(sFmtDumpNFA_KeepPattern, [FTransitTo]) else begin if FCode <> nil then Result := Format(sFmtDumpNFA_Null, [(FCode as TRECode).GetDebugStr, FTransitTo]); end; end; {$ENDIF} { TRENFA } procedure TRENFA.AddTransition(AKind: TRENFAKind; ATransFrom, ATransTo: Integer; ACode: TRECode; AMin: Integer; AMax: Integer); var NFACode: TRENFAState; begin NFACode := TRENFAState.Create; with NFACode do begin {$IFDEF DEBUG} Index := ATransFrom; {$ENDIF} Kind := AKind; Code := ACode; TransitTo := ATransTo; Next := TRENFAState(FStateList[ATransFrom]); Min := AMin; Max := AMax; end; FStateList[ATransFrom] := NFACode; end; procedure TRENFA.Compile; begin FRegExp.ClearStateList; FRegExp.FEntryState := GetNumber; FBEntryState := FRegExp.FEntryState; FRegExp.FExitState := GetNumber; FBExitState := FRegExp.FExitState; FEntryStack.Clear; FExitStack.Clear; FEntryStackIndex := 0; FExitStateIndex := 0; FGroupCount := 0; AddTransition(nkEnd, FRegExp.FExitState, -1, nil); GenerateStateList(FRegExp.FCode, FRegExp.FEntryState, FRegExp.FExitState); end; constructor TRENFA.Create(ARegExp: TSkRegExp); begin inherited Create; FRegExp := ARegExp; FStateList := ARegExp.FStateList; FEntryStack := TList.Create; FExitStack := TList.Create; FStateStack := TList.Create; FEntryStackIndex := 0; FExitStateIndex := 0; FStateStackIndex := 0; end; destructor TRENFA.Destroy; begin FStateStack.Free; FEntryStack.Free; FExitStack.Free; inherited; end; procedure TRENFA.GenerateStateList(ACode: TRECode; AEntry, AWayout: Integer); var State1, State2, Index: Integer; SubCode: TRECode; NFACode: TRENFAState; begin if ACode is TREBinCode then begin with ACode as TREBinCode do begin case Op of opUnion: begin GenerateStateList(Right, AEntry, AWayout); GenerateStateList(Left, AEntry, AWayout); end; opConcat: begin State1 := GetNumber; GenerateStateList(Left, AEntry, State1); GenerateStateList(Right, State1, AWayout); end; opStar: begin AddTransition(nkStar, AEntry, AWayout, Left, 0, CONST_LoopMax); NFACode := FStateList[AEntry]; NFACode.MatchKind := MatchKind; NFACode.ExtendTo := AWayout; if AEntry = FBEntryState then FBEntryState := AWayout; end; opPlus: begin AddTransition(nkPlus, AEntry, AWayout, Left, 1, CONST_LoopMax); NFACode := FStateList[AEntry]; NFACode.MatchKind := MatchKind; NFACode.ExtendTo := AWayout; end; opBound: begin AddTransition(nkBound, AEntry, AWayout, Left, FMin, FMax); NFACode := FStateList[AEntry]; NFACode.MatchKind := MatchKind; NFACode.ExtendTo := AWayout; end; opLoop: begin State1 := GetNumber; State2 := GetNumber; AddTransition(nkLoop, AEntry, State1, nil, FMin, FMax); NFACode := FStateList[AEntry]; NFACode.MatchKind := MatchKind; NFACode.ExtendTo := State2; PushState(AEntry, AWayout, State1, State2); GenerateStateList(Left, State1, State2); PopState; AddTransition(nkLoopExit, State1, AWayout, nil); AddTransition(nkLoopEnd, State2, State1, nil); if (FMin = 0) and (AEntry = FBEntryState) then FBEntryState := AWayout; end; opQuest: begin if FMatchKind <> lkReluctant then begin AddTransition(nkEmpty, AEntry, AWayout, nil); NFACode := FStateList[AEntry]; NFACode.MatchKind := MatchKind; end; GenerateStateList(Left, AEntry, AWayout); if FMatchKind = lkReluctant then begin AddTransition(nkEmpty, AEntry, AWayout, nil); NFACode := FStateList[AEntry]; NFACode.MatchKind := MatchKind; end; if AEntry = FBEntryState then FBEntryState := AWayout; end; opGroup: begin State1 := GetNumber; State2 := GetNumber; if GroupIndex > 0 then begin FRegExp.FGroups[GroupIndex].IndexBegin := AEntry; FRegExp.FGroups[GroupIndex].IndexEnd := State2; end; AddTransition(nkGroupBegin, AEntry, State1, nil); NFACode := FStateList[AEntry]; NFACode.GroupIndex := GroupIndex; FStateStack.Add(Pointer(AEntry)); Inc(FGroupCount); PushState(AEntry, AWayout, State1, State2); GenerateStateList(Left, State1, State2); PopState; Dec(FGroupCount); FStateStack.Delete(FStateStack.Count - 1); AddTransition(nkGroupEnd, State2, AWayout, nil); NFACode := FStateList[State2]; NFACode.GroupIndex := GroupIndex; end; opNoBackTrack: begin State1 := GetNumber; State2 := GetNumber; AddTransition(nkNoBackTrack, AEntry, State1, nil); NFACode := FStateList[AEntry]; NFACode.ExtendTo := State2; PushState(AEntry, AWayout, State1, State2); GenerateStateList(Left, State1, State2); PopState; AddTransition(nkMatchEnd, State2, AWayout, nil); end; opKeepPattern: begin State1 := GetNumber; AddTransition(nkKeepPattern, AEntry, State1, nil); GenerateStateList(Left, State1, AWayout); end; opFail: begin State1 := GetNumber; AddTransition(nkFail, AEntry, State1, nil); GenerateStateList(Left, State1, AWayout); end; opEmply: begin AddTransition(nkEmpty, AEntry, AWayout, nil); end; opGoSub: begin AddTransition(nkGoSub, AEntry, AWayout, nil); NFACode := FStateList[AEntry]; NFACode.HasRecursion := HasRecursion; if GroupIndex = -1 then begin Index := FRegExp.FGroups.IndexOfName(GroupName); Assert(Index <> -1, 'BUG?: Not Define Group Index'); NFACode.GroupIndex := Index; end else NFACode.GroupIndex := GroupIndex; end; opAheadMatch: begin State1 := GetNumber; State2 := GetNumber; AddTransition(nkAheadMatch, AEntry, State1, nil); NFACode := FStateList[AEntry]; NFACode.ExtendTo := State2; PushState(AEntry, AWayout, State1, State2); GenerateStateList(Left, State1, State2); PopState; AddTransition(nkMatchEnd, State2, AWayout, nil) end; opAheadNoMatch: begin State1 := GetNumber; State2 := GetNumber; AddTransition(nkAheadNoMatch, AEntry, State1, nil); NFACode := FStateList[AEntry]; NFACode.ExtendTo := State2; PushState(AEntry, AWayout, State1, State2); GenerateStateList(Left, State1, State2); PopState; AddTransition(nkMatchEnd, State2, AWayout, nil); end; opBehindMatch: begin State1 := GetNumber; State2 := GetNumber; AddTransition(nkBehindMatch, AEntry, State1, nil); NFACode := FStateList[AEntry]; NFACode.Max := FMax; NFACode.Min := FMin; NFACode.ExtendTo := State2; PushState(AEntry, AWayout, State1, State2); GenerateStateList(Left, State1, State2); PopState; AddTransition(nkMatchEnd, State2, AWayout, nil) end; opBehindNoMatch: begin State1 := GetNumber; State2 := GetNumber; AddTransition(nkBehindNoMatch, AEntry, State1, nil); NFACode := FStateList[AEntry]; NFACode.ExtendTo := State2; NFACode.Max := FMax; NFACode.Min := FMin; PushState(AEntry, AWayout, State1, State2); GenerateStateList(Left, State1, State2); PopState; AddTransition(nkMatchEnd, State2, AWayout, nil); end; opIfMatch: begin State1 := GetNumber; State2 := GetNumber; GenerateStateList(Left, AEntry, State2); AddTransition(nkIfMatch, AEntry, State1, nil); NFACode := FStateList[AEntry]; NFACode.ExtendTo := State2; PushState(AEntry, AWayout, State1, State2); GenerateStateList(Right, State1, AWayout); PopState; AddTransition(nkMatchEnd, State2, AWayout, nil); end; opIfThen: begin if Right <> nil then begin State1 := GetNumber; AddTransition(nkIfThen, AEntry, State1, nil); GenerateStateList(Right, State1, AWayout); end; State2 := GetNumber; AddTransition(nkIfThen, AEntry, State2, nil); GenerateStateList(Left, State2, AWayout); end; end; end; end else begin if (AEntry = FBEntryState) and (ACode is TRECharCode) and (ACode as TRECharCode).FConvert and (((ACode as TRECharCode).GetWChar = UCS4Char('^')) or ((roIgnoreWidth in (ACode as TRECharCode).FOptions) and ((ACode as TRECharCode).GetWChar = CONST_WIDE_HAT))) then begin SubCode := TRELineHeadCode.Create(FRegExp, (ACode as TRECharCode) .FOptions); ReplaceCode(ACode, SubCode); AddTransition(nkNormal, AEntry, AWayout, SubCode); end else if (AWayout = FBExitState) and (ACode is TRECharCode) and (ACode as TRECharCode).FConvert and (((ACode as TRECharCode).GetWChar = UCS4Char('$')) or ((roIgnoreWidth in (ACode as TRECharCode).FOptions) and ((ACode as TRECharCode).GetWChar = CONST_WIDE_DOLL))) then begin SubCode := TRELineTailCode.Create(FRegExp, (ACode as TRECharCode) .FOptions); ReplaceCode(ACode, SubCode); AddTransition(nkNormal, AEntry, AWayout, SubCode); end else begin if (ACode is TRECharCode) or (ACode is TRELiteralCode) then AddTransition(nkChar, AEntry, AWayout, ACode) else AddTransition(nkNormal, AEntry, AWayout, ACode); end; end; end; function TRENFA.GetNumber: Integer; begin Result := FStateList.Add(nil); end; function TRENFA.GetRealState: Integer; begin Result := Integer(FStateStack[FStateStackIndex]); end; procedure TRENFA.PopState; begin if FEntryStackIndex > 0 then begin Dec(FEntryStackIndex); FBEntryState := Integer(FEntryStack[FEntryStackIndex]); FEntryStack.Delete(FEntryStackIndex); end; if FExitStateIndex > 0 then begin Dec(FExitStateIndex); FBExitState := Integer(FExitStack[FExitStateIndex]); FExitStack.Delete(FExitStateIndex); end; end; procedure TRENFA.PushState(AEntry, AWayout, ANewEntry, ANewWayout: Integer); begin if AEntry = FBEntryState then begin FEntryStack.Add(Pointer(FBEntryState)); FBEntryState := ANewEntry; Inc(FEntryStackIndex); end; if AWayout = FBExitState then begin FExitStack.Add(Pointer(FBExitState)); FBExitState := ANewWayout; Inc(FExitStateIndex); end; end; procedure TRENFA.ReplaceCode(var OldCode, NewCode: TRECode); procedure ReplaceCodeSub(var SourceCode: TRECode; var OldCode, NewCode: TRECode); var Code, SubCode: TREBinCode; I: Integer; begin if SourceCode is TREBinCode then begin Code := SourceCode as TREBinCode; if Assigned(Code.Left) then ReplaceCodeSub(Code.FLeft, OldCode, NewCode); if Assigned(Code.Right) then ReplaceCodeSub(Code.FRight, OldCode, NewCode); end else begin if SourceCode = OldCode then begin I := FRegExp.FCodeList.IndexOf(OldCode); if I = -1 then FRegExp.Error(sFatalError); SubCode := FRegExp.FCodeList[I]; SubCode.Free; FRegExp.FCodeList[I] := NewCode; SourceCode := NewCode; Exit; end; end; end; {$IFNDEF DEBUG} var TempCode: TRECode; Index: Integer; {$ENDIF} begin {$IFDEF DEBUG} ReplaceCodeSub(FRegExp.FCode, OldCode, NewCode); {$ELSE} Index := FRegExp.FCodeList.IndexOf(OldCode); if Index = -1 then FRegExp.Error(sNotFoundOldCode); TempCode := FRegExp.FCodeList[Index]; FRegExp.FCodeList[Index] := NewCode; TempCode.Free; {$ENDIF} end; { TREStack } procedure TREStack.Clear; var I: Integer; MatchRecList: TList; LStat: PREBackTrackStackRec; P: TRECapture; J: Integer; begin for I := FCount - 1 downto 0 do begin LStat := FStat^[I]; if LStat <> nil then begin Dispose(LStat); FStat^[I] := nil; end; if FGroup^[I] <> nil then begin MatchRecList := FGroup^[I]; for J := MatchRecList.Count - 1 downto 0 do begin P := MatchRecList[J]; if Assigned(P) then P.Free; end; MatchRecList.Free; FGroup^[I] := nil; end; end; FCount := 0; end; function TREStack.Count: Integer; begin Result := FCount; end; constructor TREStack.Create(ARegExp: TSkRegExp; ACheckMatchExplosion: Boolean); begin inherited Create; FRegExp := ARegExp; FSize := CONST_REStack_Size; GetMem(FStat, FSize * Sizeof(Pointer)); GetMem(FGroup, FSize * Sizeof(Pointer)); FCount := 0; FCheckMatchExplosion := ACheckMatchExplosion; end; destructor TREStack.Destroy; begin Clear; FreeMem(FStat); FreeMem(FGroup); inherited; end; function TREStack.Index: Integer; begin Result := FCount - 1; end; function TREStack.Peek: TRENFAState; var Index: Integer; begin Index := FCount - 1; if Index = -1 then begin Result := nil; Exit; end; Result := PREBackTrackStackRec(FStat^[Index]).NFACode; end; procedure TREStack.Pop(var NFACode: TRENFAState; var AStr: PWideChar); label ReStart; var I, Index: Integer; MatchRecList: TList; P: TRECapture; LStat: PREBackTrackStackRec; {$IFDEF CHECK_MATCH_EXPLOSION} S, D, N: PREMatchExplosionStateRec; {$ENDIF} begin ReStart: Index := FCount - 1; if Index = -1 then begin NFACode := nil; Exit; end; LStat := FStat^[Index]; NFACode := LStat.NFACode; if LStat.Str <> nil then AStr := LStat.Str; Dispose(LStat); FStat^[Index] := nil; if FGroup^[Index] <> nil then begin MatchRecList := FGroup^[Index]; for I := 0 to MatchRecList.Count - 1 do begin P := MatchRecList[I]; FRegExp.FGroups[I].Capture.StartP := P.StartP; FRegExp.FGroups[I].Capture.EndP := P.EndP; FRegExp.FGroups[I].Capture.Matched := P.Matched; P.Free; end; MatchRecList.Free; end; Dec(FCount); {$IFDEF CHECK_MATCH_EXPLOSION} if FCheckMatchExplosion and (NFACode.Kind in [nkEmpty, nkLoop, nkStar, nkPlus, nkBound]) then begin Index := AStr - FRegExp.FTextTopP; if FRegExp.FMatchExplosionState[Index] <> nil then begin S := FRegExp.FMatchExplosionState[Index]; D := S; while S <> nil do begin if S.NFACode = NFACode then goto ReStart; D := S; S := S.Next; end; New(N); N.NFACode := NFACode; N.Next := nil; D.Next := N; end else begin New(N); N.NFACode := NFACode; N.Next := nil; FRegExp.FMatchExplosionState[Index] := N; end; end; {$ENDIF} end; procedure TREStack.Push(NFACode: TRENFAState; AStr: PWideChar; IsPushGroup: Boolean); var I: Integer; MatchRecList: TList; LStat: PREBackTrackStackRec; P: TRECapture; begin if FCount + 1 >= FSize then Extend(FSize div 4); New(LStat); LStat.NFACode := NFACode; LStat.Str := AStr; FStat^[FCount] := LStat; if IsPushGroup then begin MatchRecList := TList.Create; for I := 0 to FRegExp.FGroups.Count - 1 do begin P := TRECapture.Create; P.StartP := FRegExp.FGroups[I].Capture.StartP; P.EndP := FRegExp.FGroups[I].Capture.EndP; P.Matched := FRegExp.FGroups[I].Capture.Matched; MatchRecList.Add(P); end; FGroup^[FCount] := MatchRecList; end else FGroup^[FCount] := nil; Inc(FCount); end; procedure TREStack.Remove(const AIndex: Integer); var I, L: Integer; NFACode: TRENFAState; AStr: PWideChar; begin L := FCount - AIndex - 1; for I := 1 to L do Pop(NFACode, AStr); end; procedure TREStack.Extend(ASize: Integer); begin if ASize < CONST_REStack_Size then ASize := CONST_REStack_Size; FSize := FSize + ASize; ReallocMem(FStat, FSize * Sizeof(Pointer)); ReallocMem(FGroup, FSize * Sizeof(Pointer)); end; { TRELeadCodeCollection } function TRELeadCodeCollection.Add(Value: TRECode; AOffset: Integer; ABehindMatch: Boolean): Integer; var Item: TRELeadCode; begin Item := TRELeadCode.Create; Item.Code := Value; Item.Offset := AOffset; Item.IsBehindMatch := ABehindMatch; Result := FList.Add(Item); end; procedure TRELeadCodeCollection.Clear; begin FList.Clear; end; constructor TRELeadCodeCollection.Create; begin inherited; FList := TObjectList.Create; end; procedure TRELeadCodeCollection.Delete(Index: Integer); begin FList.Delete(Index); end; destructor TRELeadCodeCollection.Destroy; begin FList.Free; inherited; end; function TRELeadCodeCollection.GetCount: Integer; begin Result := FList.Count; end; function TRELeadCodeCollection.GetItem(Index: Integer): TRELeadCode; begin Result := FList[Index] as TRELeadCode; end; { TREMatchEngine } constructor TREMatchEngine.Create(ARegExp: TSkRegExp); begin inherited Create; FRegExp := ARegExp; FLeadCode := TRELeadCodeCollection.Create; // FLeadCode.OwnsObjects := False; FTailCode := TObjectList.Create; FTailCode.OwnsObjects := False; FLeadStrings := TREQuickSearch.Create; FMap := TRECharMap.Create; FSpecialMatchStack := TList.Create; if not Assigned(FRegExp.FStateList) then FRegExp.Error('bug: StateList not initialized.'); FStateList := FRegExp.FStateList; if not Assigned(FRegExp.FGroups) then FRegExp.Error('bug: MatchData not initialized.'); FGroups := FRegExp.FGroups; end; destructor TREMatchEngine.Destroy; begin FSpecialMatchStack.Free; FMap.Free; FTailCode.Free; FLeadCode.Free; FLeadStrings.Free; inherited; end; procedure TREMatchEngine.GenerateLeadCode; var IsNotLead: Boolean; procedure RebuildSub(Index: Integer); var Source, Dest: TRECode; I: Integer; begin Source := FLeadCode[Index].Code; for I := FLeadCode.Count - 1 downto 0 do begin if I <> Index then begin Dest := FLeadCode[I].Code; if Source.IsInclude(Dest) then FLeadCode.Delete(I); end; end; end; procedure GetLeadCode(NFACode: TRENFAState; AOffset: Integer; ABehindMatch: Boolean); var SubCode: TRENFAState; begin while NFACode.Kind = nkGroupBegin do begin if NFACode.Next <> nil then GetLeadCode(NFACode.Next, AOffset, ABehindMatch); NFACode := FStateList[NFACode.TransitTo]; end; while NFACode <> nil do begin case NFACode.Kind of nkChar: FLeadCode.Add(NFACode.Code, AOffset, ABehindMatch); nkNormal: if (NFACode.Code is TREAnyCharCode) then begin SubCode := FStateList[NFACode.TransitTo]; Inc(AOffset); GetLeadCode(SubCode, AOffset, ABehindMatch); end else if not(NFACode.Code is TRECombiningSequence) then FLeadCode.Add(NFACode.Code, AOffset, ABehindMatch) else begin FLeadCode.Add(nil, AOffset, ABehindMatch); Exit; end; nkStar: begin FLeadCode.Add(NFACode.Code, AOffset, ABehindMatch); GetLeadCode(FStateList[NFACode.TransitTo], AOffset, ABehindMatch); FIsNotSimplePattern := False; end; nkPlus: begin FIsNotSimplePattern := True; FLeadCode.Add(NFACode.Code, AOffset, ABehindMatch); end; nkBound: begin FIsNotSimplePattern := True; FLeadCode.Add(NFACode.Code, AOffset, ABehindMatch); if NFACode.Min = 0 then GetLeadCode(FStateList[NFACode.TransitTo], AOffset, ABehindMatch); end; nkLoop: begin SubCode := FStateList[NFACode.TransitTo]; if NFACode.Min = 0 then begin GetLeadCode(FStateList[SubCode.TransitTo], AOffset, ABehindMatch); FIsNotSimplePattern := True; end; GetLeadCode(SubCode.Next, AOffset, ABehindMatch); end; nkAheadMatch: GetLeadCode(FStateList[NFACode.TransitTo], AOffset, ABehindMatch); nkBehindMatch: GetLeadCode(FStateList[NFACode.TransitTo], AOffset, True); nkEmpty: GetLeadCode(FStateList[NFACode.TransitTo], AOffset, ABehindMatch); else begin FLeadCode.Add(nil, AOffset, ABehindMatch); Exit; end; end; NFACode := NFACode.Next; end; end; var I: Integer; begin FIsNotSimplePattern := False; IsNotLead := False; FPreMatchLength := 0; FIsBehindMatch := False; FLeadCode.Clear; GetLeadCode(FStateList[FRegExp.FEntryState], 0, False); if FLeadCode.Count = 0 then Exit; if not IsNotLead then begin for I := 0 to FLeadCode.Count - 1 do begin if FLeadCode[I].Code = nil then begin IsNotLead := True; Break; end; end; end; if IsNotLead then begin FLeadCode.Clear; end else begin I := 0; while I < FLeadCode.Count do begin RebuildSub(I); Inc(I); end; end; end; procedure TREMatchEngine.GenerateTailCode; var I, LExitState: Integer; NFACode: TRENFAState; begin FTailCode.Clear; LExitState := FRegExp.FExitState; for I := 0 to FStateList.Count - 1 do begin NFACode := FStateList[I]; while NFACode <> nil do begin if (NFACode.TransitTo = LExitState) then begin if (NFACode.Kind = nkChar) and ((NFACode.Code is TRELiteralCode) or (NFACode.Code is TRECharCode)) then begin FTailCode.Add(NFACode.Code); end else FTailCode.Add(nil); end else if NFACode.Kind = nkGroupEnd then LExitState := I; NFACode := NFACode.Next; end; end; end; function TREMatchEngine.Match(AStr: PWideChar): Boolean; var P: PWideChar; IsCheck: Boolean; begin Result := False; FStateList := FRegExp.FStateList; FGroups := FRegExp.FGroups; if FLeadCharMode = lcmLastLiteral then begin if not FLeadStrings.Exec(AStr, FRegExp.FMatchEndP - AStr) then Exit; end; case FLeadCharMode of lcmFirstLiteral: begin P := AStr; if FLeadStrings.Exec(P, FRegExp.FMatchEndP - P) then begin repeat P := FLeadStrings.MatchP; if FIsBehindMatch and (FRegExp.FMatchEndP > P + FPreMatchLength) then Inc(P, FPreMatchLength) else if (FPreMatchLength > 0) and (P >= FRegExp.FMatchTopP + FPreMatchLength) then Dec(P, FPreMatchLength); if MatchEntry(P) then begin Result := True; Exit; end; until not FLeadStrings.ExecNext; end; end; lcmSimple: begin if FLeadStrings.Exec(AStr, FRegExp.FMatchEndP - AStr) then begin Result := True; FGroups[0].Capture.StartP := AStr + FLeadStrings.MatchPos - 1; FGroups[0].Capture.EndP := FLeadStrings.MatchP + Length(FLeadStrings.FindText); end; end; lcmTextTop: begin if MatchEntry(AStr) then begin Result := True; Exit; end; end; lcmLineTop: begin while AStr <= FRegExp.FMatchEndP do begin if MatchEntry(AStr) then begin Result := True; Exit; end; while not IsLineSeparator(AStr^) and (AStr <= FRegExp.FMatchEndP) do Inc(AStr); if IsLineSeparator(AStr^) then begin repeat Inc(AStr); until not IsLineSeparator(AStr^); end else Break; end; end; else begin if FLeadCharMode = lcmMap then begin while AStr <= FRegExp.FMatchEndP do begin if FMap.IsExists(AStr) then begin if MatchEntry(AStr) then begin Result := True; Exit; end; end else Inc(AStr); end; end else begin if AStr <> nil then begin while AStr <= FRegExp.FMatchEndP do begin if FLeadCharMode = lcmHasLead then IsCheck := IsLeadStrings(AStr) else IsCheck := True; if IsCheck then begin if MatchEntry(AStr) then begin Result := True; Exit; end; end else Inc(AStr); end; end; end; end; end; end; function TREMatchEngine.MatchCore(var NFACode: TRENFAState; var AStr: PWideChar): Boolean; var Stack: TREStack; begin Stack := TREStack.Create(FRegExp); try Result := False; while NFACode <> nil do begin NFACode := MatchPrim(NFACode, AStr, Stack); if (NFACode = nil) then begin if (FGroups[0].Capture.EndP <> nil) then begin Result := True; Exit; end else Stack.Pop(NFACode, AStr); end; if (NFACode <> nil) and (NFACode.Kind = nkMatchEnd) then begin Result := True; Exit; end; end; finally Stack.Free; end; end; function TREMatchEngine.MatchCore(var NFACode, EndCode: TRENFAState; var AStr: PWideChar; ACheckExplosion: Boolean): Boolean; var Stack: TREStack; Index: Integer; SaveP: PWideChar; begin Stack := TREStack.Create(FRegExp, ACheckExplosion); try Result := False; SaveP := AStr; Index := Stack.Index; while NFACode <> nil do begin NFACode := MatchPrim(NFACode, AStr, Stack); if (NFACode = nil) then begin if FGroups[0].Capture.EndP <> nil then begin Result := True; Exit; end else if Stack.Index > Index then Stack.Pop(NFACode, AStr); end; if (NFACode <> nil) and (NFACode = EndCode) then begin NFACode := MatchPrim(NFACode, AStr, Stack); Result := True; Exit; end; end; if not Result then AStr := SaveP; finally Stack.Free; end; end; function TREMatchEngine.MatchEntry(var AStr: PWideChar): Boolean; var NFACode: TRENFAState; SaveP: PWideChar; begin SaveP := AStr; FGroups.Reset; NFACode := FStateList[FRegExp.FEntryState]; FGroups[0].Capture.StartP := AStr; Result := MatchCore(NFACode, AStr); if not Result then begin AStr := SaveP; Inc(AStr); end; end; function TREMatchEngine.MatchPrim(NFACode: TRENFAState; var AStr: PWideChar; Stack: TREStack): TRENFAState; function MatchLoop(EntryCode, EndCode: TRENFAState; var AStr: PWideChar; Stack: TREStack): Boolean; var NFACode: TRENFAState; Index: Integer; SaveP: PWideChar; begin Result := False; Index := Stack.Index; SaveP := AStr; NFACode := EntryCode; while NFACode <> nil do begin while NFACode <> nil do begin NFACode := MatchPrim(NFACode, AStr, Stack); if (NFACode <> nil) and ((NFACode = EndCode) or (NFACode.Kind = nkMatchEnd)) then begin {$IFDEF DEBUG} {$IFDEF SHOW_MATCH_PROCESS} MatchProcess(NFACode, AStr); {$ENDIF} {$ENDIF} Result := True; Break; end end; if (NFACode = nil) then begin if FGroups[0].Capture.EndP <> nil then Exit; if Stack.Index > Index then Stack.Pop(NFACode, AStr) else Break; end else begin if (AStr = SaveP) then begin if Stack.Index > Index then Stack.Pop(NFACode, AStr) else Break; end else Break; end; end; end; procedure BranchSetup(NFACode: TRENFAState; AStr: PWideChar; IsPushGroup: Boolean); var Len: Integer; begin if NFACode <> nil then begin if NFACode.Kind in [nkChar, nkNormal] then begin if NFACode.Code.IsEqual(AStr, Len) then Stack.Push(NFACode, AStr, IsPushGroup) else if NFACode.Next <> nil then BranchSetup(NFACode.Next, AStr, IsPushGroup); end else Stack.Push(NFACode, AStr, IsPushGroup); end; end; var I, Len, LMin, LMax, Index, LEntry, BaseIndex: Integer; EntryCode, NextCode, EndCode, SubCode: TRENFAState; LMatchKind: TRELoopKind; SubP, SaveP: PWideChar; IsMatched: Boolean; begin Result := nil; {$IFDEF DEBUG} {$IFDEF SHOW_MATCH_PROCESS} MatchProcess(NFACode, AStr); try {$ENDIF} {$ENDIF} if NFACode.Next <> nil then begin if NFACode.Kind in [nkLoopExit, nkLoopEnd, nkIfThen] then // nkLoopExitがここに入ってくることはありえない。 // スタックへ退避せず次へ遷移 NFACode := FStateList[NFACode.TransitTo] else if NFACode.Kind <> nkIfMatch then // 分岐があればスタックへ退避 BranchSetup(NFACode.Next, AStr, False); end; case NFACode.Kind of nkNormal, nkChar: begin if NFACode.Code.IsEqual(AStr, Len) then begin Inc(AStr, Len); Result := FStateList[NFACode.TransitTo]; end else Result := nil; end; nkStar, nkPlus: begin SubP := AStr; LMatchKind := NFACode.MatchKind; NextCode := FStateList[NFACode.TransitTo]; EntryCode := NFACode; if EntryCode.Code.ExecRepeat(AStr, NFACode.Kind = nkStar) then begin if LMatchKind = lkAny then begin // Plus でマッチしたときは SubP を1単位進める if NFACode.Kind = nkPlus then CharNext(SubP); Result := NextCode; SaveP := AStr; while not MatchCore(Result, AStr) do begin AStr := SaveP; if SubP < AStr then begin CharPrev(AStr); SaveP := AStr; Result := NextCode; end else Break; end; end else if LMatchKind = lkCombiningSequence then begin Result := NextCode; SaveP := AStr; while not MatchCore(Result, AStr) do begin AStr := SaveP; if SubP < AStr then begin Dec(AStr); while (SubP < AStr) and IsUnicodeProperty(ToUCS4Char(AStr), upM) do begin Dec(AStr); end; SaveP := AStr; Result := NextCode; end else Break; end; end else if LMatchKind <> lkPossessive then begin // Plus でマッチしたときは SubP を1単位進める Len := EntryCode.Code.CharLength; if NFACode.Kind = nkPlus then CharNext(SubP, Len); while SubP < AStr do begin BranchSetup(NextCode, SubP, True); while EntryCode.Next <> nil do begin BranchSetup(EntryCode.Next, AStr, True); EntryCode := EntryCode.Next; end; CharNext(SubP, Len); end; Result := NextCode; end else begin Result := NextCode; end; end else Result := nil; end; nkBound: begin SubP := AStr; LMatchKind := NFACode.MatchKind; LMin := NFACode.Min; LMax := NFACode.Max; NextCode := FStateList[NFACode.TransitTo]; EntryCode := NFACode; if EntryCode.Code.ExecRepeat(AStr, LMin, LMax) then begin Len := EntryCode.Code.CharLength; // LMin 分は確定 if LMin > 0 then CharNext(SubP, LMin * Len); if LMatchKind = lkAny then begin SaveP := AStr; Result := MatchPrim(NextCode, AStr, Stack); while Result = nil do begin AStr := SaveP; if SubP < AStr then begin CharPrev(AStr, Len); SaveP := AStr; end else Break; Result := MatchPrim(NextCode, AStr, Stack); end; end else if LMatchKind <> lkPossessive then begin SaveP := AStr; Result := MatchPrim(NextCode, AStr, Stack); while Result = nil do begin AStr := SaveP; if SubP < AStr then begin CharPrev(AStr, Len); SaveP := AStr; end else Break; Result := MatchPrim(NextCode, AStr, Stack); end end else Result := NextCode; end else Result := nil; end; nkLoop: begin LMatchKind := NFACode.MatchKind; LMin := NFACode.Min; LMax := NFACode.Max; // ループの終了を登録 EndCode := FStateList[NFACode.ExtendTo]; NFACode := FStateList[NFACode.TransitTo]; // ループの次を登録 NextCode := FStateList[NFACode.TransitTo]; // ループの入口を登録 EntryCode := NFACode.Next; if LMin > 0 then begin for I := 1 to LMin do begin if not MatchLoop(EntryCode, EndCode, AStr, Stack) then Exit; end; if LMin = LMax then begin // LMin = LMaxならバックトラックの必要がない Result := NextCode; Exit; end; end else Stack.Push(NextCode, AStr, True); if LMax <> CONST_LoopMax then LMax := LMax - LMin; if LMatchKind = lkGreedy then begin NFACode := EntryCode; IsMatched := True; for I := 1 to LMax do begin SubP := AStr; Stack.Push(NextCode, AStr, True); IsMatched := MatchLoop(NFACode, EndCode, AStr, Stack); if not IsMatched or (SubP = AStr) then Break; end; if IsMatched then Result := NextCode; end else if LMatchKind = lkSimpleReluctant then begin end else if LMatchKind = lkReluctant then begin IsMatched := True; NFACode := EntryCode; for I := 1 to LMax do begin SubP := AStr; Result := NextCode; if MatchCore(Result, AStr) then Exit; IsMatched := MatchLoop(NFACode, EndCode, AStr, Stack); if not IsMatched or (SubP = AStr) then Break; end; if IsMatched then Result := NextCode; end else if LMatchKind = lkPossessive then begin BaseIndex := Stack.Index; NFACode := EntryCode; for I := 1 to LMax do begin SubP := AStr; IsMatched := MatchLoop(NFACode, EndCode, AStr, Stack); if not IsMatched or (SubP = AStr) then Break; end; Stack.Remove(BaseIndex); Result := NextCode; end; end; nkEnd: begin FGroups[0].Capture.EndP := AStr; Result := nil; Exit; end; nkFail: begin Result := nil; end; nkEmpty, nkLoopExit, nkLoopEnd, nkIfThen: Result := FStateList[NFACode.TransitTo]; nkGroupBegin: begin FGroups[NFACode.GroupIndex].Capture.StartP := AStr; Result := FStateList[NFACode.TransitTo]; end; nkGroupEnd: begin FGroups[NFACode.GroupIndex].Capture.EndP := AStr; Result := FStateList[NFACode.TransitTo]; end; nkNoBackTrack: begin EndCode := FStateList[NFACode.ExtendTo]; NFACode := FStateList[NFACode.TransitTo]; SubP := AStr; if MatchCore(NFACode, EndCode, AStr) then begin Result := FStateList[EndCode.TransitTo]; end else begin AStr := SubP; Result := nil; end; end; nkKeepPattern: begin Stack.Clear; FGroups[0].Capture.StartP := AStr; Result := FStateList[NFACode.TransitTo]; end; nkGoSub: begin Index := NFACode.GroupIndex; if Index > 0 then begin SubP := AStr; Index := NFACode.GroupIndex; LEntry := FGroups[Index].IndexBegin; EntryCode := FStateList[LEntry]; while EntryCode.Kind <> nkGroupBegin do EntryCode := EntryCode.Next; LEntry := FGroups[Index].IndexEnd; EndCode := FStateList[LEntry]; EndCode.Max := EndCode.Max + 1; EndCode.ExtendTo := NFACode.TransitTo; if NFACode.HasRecursion then begin {$IFDEF DEBUG} {$IFDEF SHOW_MATCH_PROCESS} MatchProcess(EntryCode, AStr); {$ENDIF} {$ENDIF} while EndCode.Kind <> nkGroupEnd do EndCode := EndCode.Next; if MatchRecursion(EntryCode, EndCode, AStr) then begin Result := FStateList[NFACode.TransitTo]; {$IFDEF DEBUG} {$IFDEF SHOW_MATCH_PROCESS} MatchProcess(EndCode, AStr); {$ENDIF} {$ENDIF} end else begin Result := nil; AStr := SubP; end; end else begin if MatchCore(EntryCode, EndCode, AStr) then begin Result := FStateList[NFACode.TransitTo]; end else begin AStr := SubP; Result := nil; end; end; end else begin SubP := AStr; EntryCode := FStateList[FRegExp.FEntryState]; if MatchCore(EntryCode, AStr) then begin Result := FStateList[NFACode.TransitTo]; end else begin AStr := SubP; Result := nil; end; end; end; nkMatchEnd: begin Result := NFACode; Exit; end; nkAheadMatch: begin EndCode := FStateList[NFACode.ExtendTo]; NFACode := FStateList[NFACode.TransitTo]; SubP := AStr; if MatchCore(NFACode, EndCode, SubP) then Result := FStateList[NFACode.TransitTo] else Result := nil; end; nkAheadNoMatch: begin EndCode := FStateList[NFACode.ExtendTo]; Result := FStateList[EndCode.TransitTo]; NFACode := FStateList[NFACode.TransitTo]; SubP := AStr; if MatchCore(NFACode, EndCode, SubP) then begin Result := nil; Exit; end; end; nkBehindMatch: begin SubP := AStr; LMax := NFACode.Max; LMin := NFACode.Min; EndCode := FStateList[NFACode.ExtendTo]; EntryCode := FStateList[NFACode.TransitTo]; if FRegExp.FMatchTopP <= (SubP - LMax) then Len := LMax else if FRegExp.FMatchTopP <= (SubP - LMin) then Len := LMin else Len := 0; if Len > 0 then begin CharPrev(SubP, Len); SaveP := SubP; NFACode := EntryCode; IsMatched := MatchCore(NFACode, EndCode, SubP, False); while not IsMatched and (SubP < AStr) do begin SubP := SaveP; CharNext(SubP); SaveP := SubP; NFACode := EntryCode; IsMatched := MatchCore(NFACode, EndCode, SubP, False); end; if not IsMatched then begin Result := nil; Exit; end else Result := FStateList[NFACode.TransitTo]; end else begin Result := nil; Exit; end; end; nkBehindNoMatch: begin SubP := AStr; LMax := NFACode.Max; LMin := NFACode.Min; EndCode := FStateList[NFACode.ExtendTo]; Result := FStateList[EndCode.TransitTo]; EntryCode := FStateList[NFACode.TransitTo]; if FRegExp.FMatchTopP <= (SubP - LMax) then Len := LMax else if FRegExp.FMatchTopP <= (SubP - LMin) then Len := LMin else Len := 0; if Len > 0 then begin CharPrev(SubP, Len); SaveP := SubP; NFACode := EntryCode; IsMatched := MatchCore(NFACode, EndCode, SubP, False); while not IsMatched and (SubP < AStr) do begin SubP := SaveP; CharNext(SubP); SaveP := SubP; NFACode := EntryCode; IsMatched := MatchCore(NFACode, EndCode, SubP, False); end; if IsMatched then begin Result := nil; Exit; end; end; end; nkIfMatch: begin SubP := AStr; EntryCode := NFACode.Next; EndCode := FStateList[NFACode.ExtendTo]; NextCode := FStateList[NFACode.TransitTo]; if NextCode.Next <> nil then SubCode := FStateList[NextCode.Next.TransitTo] else SubCode := nil; if MatchCore(EntryCode, EndCode, SubP) then Result := NextCode else Result := SubCode; end; end; {$IFDEF DEBUG} {$IFDEF SHOW_MATCH_PROCESS} finally if Result = nil then FRegExp.FMatchProcess.Add('...fail'); end; {$ENDIF} {$ENDIF} end; {$IFDEF DEBUG} {$IFDEF SHOW_MATCH_PROCESS} procedure TREMatchEngine.MatchProcess(NFACode: TRENFAState; AStr: PWideChar); var LeftStr, RightStr: REString; begin if (AStr - FRegExp.FMatchTopP) > 20 then SetString(LeftStr, AStr - 20, 20) else SetString(LeftStr, FRegExp.FMatchTopP, AStr - FRegExp.FMatchTopP); if (FRegExp.FMatchEndP - AStr) > 20 then SetString(RightStr, AStr, (AStr + 20) - AStr) else SetString(RightStr, AStr, FRegExp.FMatchEndP - AStr); FRegExp.FMatchProcess.Add(Format('<%s> <%s> : %2d: %s', [LeftStr, RightStr, NFACode.Index, NFACode.ToString])); end; {$ENDIF SHOW_MATCH_PROCESS} {$ENDIF DEBUG} function TREMatchEngine.MatchRecursion(var NFACode: TRENFAState; EndCode: TRENFAState; var AStr: PWideChar): Boolean; var Stack: TREStack; TopP: PWideChar; Index: Integer; begin Stack := TREStack.Create(FRegExp, True); try Result := False; Index := Stack.Index; TopP := AStr; NFACode := FStateList[NFACode.TransitTo]; while NFACode <> nil do begin NFACode := MatchPrim(NFACode, AStr, Stack); if NFACode = nil then begin if Stack.Index > Index then Stack.Pop(NFACode, AStr); end; if NFACode <> nil then begin if NFACode = EndCode then begin Result := True; if Stack.Index > Index then begin if TopP = AStr then Stack.Pop(NFACode, AStr) else Break; end else Break; end; end; end; finally Stack.Free; end; end; procedure TREMatchEngine.Optimize; begin OptimizeLoop; GenerateLeadCode; GenerateTailCode; SetupLeadStrings; FIsPreMatch := FLeadCode.Count > 0; end; procedure TREMatchEngine.OptimizeLoop; var I: Integer; NFACode, SubCode, NextCode: TRENFAState; begin for I := 0 to FStateList.Count - 1 do begin NFACode := FStateList[I]; while NFACode <> nil do begin case NFACode.Kind of nkStar, nkPlus, nkBound: begin // 量指定子の次の部分式が、量指定子の対象となる文字を含むか? // 含まなければバックトラックの必要はないので強欲に変更。 NextCode := FStateList[NFACode.TransitTo]; while NextCode.Kind in [nkGroupEnd, nkGroupBegin] do NextCode := FStateList[NextCode.TransitTo]; if (NextCode.Kind = nkEnd) or ((NextCode.Code <> nil) and not NFACode.Code.IsOverlap (NextCode.Code)) then NFACode.MatchKind := lkPossessive end; nkLoop: begin if NFACode.FMatchKind = lkReluctant then begin SubCode := FStateList[NFACode.TransitTo]; NextCode := FStateList[SubCode.TransitTo]; if (NextCode.Next = nil) and (NextCode.Kind = nkChar) and ((NextCode.Code is TRECharCode) or (NextCode.Code is TRELiteralCode)) then // NFACode.MatchKind := lkSimpleReluctant; { TODO: 意外に速くならない? } ; end; end; end; NFACode := NFACode.Next; end; end; end; function TREMatchEngine.IsLeadStrings(var AStr: PWideChar): Boolean; var I, L: Integer; begin Result := False; for I := 0 to FLeadCode.Count - 1 do begin if FLeadCode[I].Code.IsEqual(AStr + FLeadCode[I].Offset, L) then begin Result := True; Exit; end; end; end; procedure TREMatchEngine.SetupLeadStrings; var NFACode, NextCode: TRENFAState; IsLiteral: Boolean; I, LOffset: Integer; LStr, SubStr: REString; LOptions: TRECompareOptions; begin FLeadStrings.Clear; IsLiteral := False; FLeadCharMode := lcmNone; if FLeadCode.Count = 1 then begin if FLeadCode[0].IsBehindMatch then begin FPreMatchLength := FLeadCode[0].Code.CharLength; FIsBehindMatch := True; end else begin FIsBehindMatch := False; FPreMatchLength := FLeadCode[0].Offset; end; if (FLeadCode[0].Code is TRECharCode) then begin FLeadStrings.FindText := (FLeadCode[0].Code as TRECharCode).FStrings; FLeadStrings.Options := (FLeadCode[0].Code as TRECharCode) .FCompareOptions; IsLiteral := True; end else if (FLeadCode[0].Code is TRELiteralCode) then begin FLeadStrings.FindText := (FLeadCode[0].Code as TRELiteralCode).FStrings; FLeadStrings.Options := (FLeadCode[0].Code as TRELiteralCode) .FCompareOptions; IsLiteral := True; end else if (FLeadCode[0].Code is TRELineHeadCode) then begin if not(roMultiLine in (FLeadCode[0].Code as TRELineHeadCode) .FOptions) then FLeadCharMode := lcmTextTop else FLeadCharMode := lcmLineTop; Exit; end else if (FLeadCode[0].Code is TRETextHeadCode) then begin FLeadCharMode := lcmTextTop; Exit; end; if IsLiteral then begin NFACode := FStateList[FRegExp.FEntryState]; NextCode := FStateList[NFACode.TransitTo]; if not FIsNotSimplePattern and (NFACode.Next = nil) and (NextCode.Kind = nkEnd) then FLeadCharMode := lcmSimple else FLeadCharMode := lcmFirstLiteral; end else FLeadCharMode := lcmHasLead; end else if FLeadCode.Count > 1 then begin IsLiteral := True; LOffset := FLeadCode[0].Offset; for I := 0 to FLeadCode.Count - 1 do begin if (not(FLeadCode[I].Code is TRECharCode) and not(FLeadCode[I].Code is TRELiteralCode)) or (FLeadCode[I].Offset <> LOffset) then begin IsLiteral := False; Break; end; end; if IsLiteral then begin FMap.Clear; for I := 0 to FLeadCode.Count - 1 do begin if FLeadCode[I].Code is TRECharCode then begin LStr := (FLeadCode[I].Code as TRECharCode).FStrings; LOptions := (FLeadCode[I].Code as TRECharCode).FCompareOptions; end else if FLeadCode[I].Code is TRELiteralCode then begin LStr := (FLeadCode[I].Code as TRELiteralCode).FStrings; LOptions := (FLeadCode[I].Code as TRELiteralCode).FCompareOptions; end; FMap.Add(ToUCS4Char(@LStr[1])); if coIgnoreCase in LOptions then begin SubStr := AnsiUpperCase(LStr); if SubStr <> LStr then FMap.Add(ToUCS4Char(@SubStr[1])); SubStr := AnsiLowerCase(LStr); if SubStr <> LStr then FMap.Add(ToUCS4Char(@SubStr[1])); end; if coIgnoreWidth in LOptions then begin SubStr := ToWide(LStr); if SubStr <> LStr then FMap.Add(ToUCS4Char(@SubStr[1])); SubStr := ToHalf(LStr); if SubStr <> LStr then FMap.Add(ToUCS4Char(@SubStr[1])); end; if coIgnoreKana in LOptions then begin SubStr := ToHiragana(LStr); if SubStr <> LStr then FMap.Add(ToUCS4Char(@SubStr[1])); SubStr := ToKatakana(LStr); if SubStr <> LStr then FMap.Add(ToUCS4Char(@SubStr[1])); end; end; FLeadCharMode := lcmMap; end else FLeadCharMode := lcmHasLead; end else begin if FTailCode.Count = 1 then begin if (FTailCode[0] is TRECharCode) then begin FLeadStrings.FindText := (FTailCode[0] as TRECharCode).FStrings; FLeadStrings.Options := (FTailCode[0] as TRECharCode).FCompareOptions; FLeadCharMode := lcmLastLiteral; end else if (FTailCode[0] is TRELiteralCode) then begin FLeadStrings.FindText := (FTailCode[0] as TRELiteralCode).FStrings; FLeadStrings.Options := (FTailCode[0] as TRELiteralCode) .FCompareOptions; FLeadCharMode := lcmLastLiteral; end end; end; end; { TSkRegExp } procedure TSkRegExp.ClearBinCodeList; var I: Integer; begin for I := 0 to FBinCodeList.Count - 1 do if FBinCodeList[I] <> nil then TRECode(FBinCodeList[I]).Free; FBinCodeList.Clear; end; procedure TSkRegExp.ClearCodeList; var I: Integer; begin for I := 0 to FCodeList.Count - 1 do if FCodeList[I] <> nil then TRECode(FCodeList[I]).Free; FCodeList.Clear; end; {$IFDEF CHECK_MATCH_EXPLOSION} procedure TSkRegExp.ClearExplosionState; var I: Integer; S, D: PREMatchExplosionStateRec; begin for I := 0 to Length(FMatchExplosionState) - 1 do begin S := FMatchExplosionState[I]; while S <> nil do begin D := S.Next; Dispose(S); S := D; end; FMatchExplosionState[I] := nil; end; end; {$ENDIF} procedure TSkRegExp.ClearStateList; var I: Integer; Code, Next: TRENFAState; begin if FStateList <> nil then begin for I := 0 to FStateList.Count - 1 do begin Code := FStateList[I]; while Code <> nil do begin Next := Code.Next; Code.Free; Code := Next; end; end; FStateList.Clear; end; end; procedure TSkRegExp.Compile; var Parser: TREParser; NFA: TRENFA; begin if not FCompiled then begin ClearCodeList; ClearBinCodeList; FGroups.Clear; Parser := TREParser.Create(Self, FExpression); try Parser.Parse; NFA := TRENFA.Create(Self); try NFA.Compile; FMatchEngine.Optimize; finally NFA.Free; end; finally Parser.Free; end; {$IFNDEF DEBUG} ClearBinCodeList; {$ENDIF} FCompiled := True; end; end; constructor TSkRegExp.Create; begin inherited Create; FGroups := TGroupCollection.Create(Self); FCodeList := TList.Create; FBinCodeList := TList.Create; FStateList := TList.Create; FOptions := SkRegExpDefaultOptions; SetEOL(DefaultEOL); IsWord := UnicodeProp.IsWord; IsDigit := UnicodeProp.IsDigit; IsSpace := UnicodeProp.IsSpace; FMatchEngine := TREMatchEngine.Create(Self); FLexMode := lmOptimize; {$IFDEF DEBUG} {$IFDEF SHOW_MATCH_PROCESS} FMatchProcess := TREStringList.Create; {$ENDIF} {$ENDIF} end; class function TSkRegExp.DecodeEscape(const S: REString): REString; var StartP: PWideChar; function GetErrorStopedString(const ErrMes: REString; P: PWideChar): REString; var S: REString; begin Inc(P); SetString(S, StartP, P - StartP); S := S + ' <-- '; Result := Format(ErrMes, [S]); end; var P: PWideChar; I, J, N: Integer; begin Result := ''; if S = '' then Exit; SetLength(Result, System.Length(S)); J := 1; P := PWideChar(S); StartP := P; while P^ <> #0 do begin if P^ = '\' then begin Inc(P); case P^ of '0' .. '3': begin N := 0; for I := 1 to 3 do begin case P^ of '0' .. '7': N := (N shl 3) + Ord(P^) - Ord('0'); else Break; end; Inc(P); end; Result[J] := WideChar(N); Inc(J); Continue; end; 'c': begin Inc(P); if ((P^ >= '@') and (P^ <= '_')) or ((P^ >= 'a') and (P^ <= 'z')) then begin if P^ = '\' then begin Inc(P); if P^ <> '\' then raise ESkRegExp.Create (GetErrorStopedString(sInvalidEscapeCharacterSyntax, P)); end; N := Ord(P^); if (P^ >= 'a') and (P^ <= 'z') then Dec(N, $20); N := N xor $40; Result[J] := WideChar(N); end; end; 'x': begin N := 0; Inc(P); if P^ = '{' then begin Inc(P); for I := 1 to 6 do begin case P^ of '0' .. '9': N := (N shl 4) + Ord(P^) - Ord('0'); 'A' .. 'F': N := (N shl 4) + Ord(P^) - Ord('7'); 'a' .. 'f': N := (N shl 4) + Ord(P^) - Ord('W'); '}': Break; else raise ESkRegExp.Create (GetErrorStopedString(sHexDigitIsRequired, P)); end; Inc(P); end; if P^ <> '}' then raise Exception.Create (GetErrorStopedString(sUnmatchedCurlyBracket, P)); Result[J] := WideChar(N); end else begin for I := 1 to 2 do begin case P^ of '0' .. '9': N := (N shl 4) + Ord(P^) - Ord('0'); 'A' .. 'F': N := (N shl 4) + Ord(P^) - Ord('7'); 'a' .. 'f': N := (N shl 4) + Ord(P^) - Ord('W'); else raise Exception.Create (GetErrorStopedString(sHexDigitIsRequired, P)); end; Inc(P); end; Result[J] := WideChar(N); Inc(J); Continue; end; end; 't': Result[J] := #0009; 'n': Result[J] := #$000A; 'r': Result[J] := #$000D; 'f': Result[J] := #$000C; 'a': Result[J] := #0007; 'e': Result[J] := #$001B; else Result[J] := P^; end; end else Result[J] := P^; Inc(P); Inc(J); end; SetLength(Result, J - 1); end; destructor TSkRegExp.Destroy; begin {$IFDEF CHECK_MATCH_EXPLOSION} ClearExplosionState; {$ENDIF} ClearStateList; ClearBinCodeList; ClearCodeList; FMatchEngine.Free; FStateList.Free; FBinCodeList.Free; FCodeList.Free; FGroups.Free; {$IFDEF DEBUG} {$IFDEF SHOW_MATCH_PROCESS} FMatchProcess.Free; {$ENDIF} {$ENDIF} inherited; end; procedure TSkRegExp.DoReplaceFunc(Sender: TObject; var ReplaceWith: REString); begin if Assigned(FReplaceFunc) then ReplaceWith := FReplaceFunc(Self); end; {$IFDEF DEBUG} function TSkRegExp.DumpLeadCode: REString; begin if FMatchEngine.FLeadStrings.FindText <> '' then Result := sFmtDumpLeadCodeExist + FMatchEngine.FLeadStrings.FindText else Result := sFmtDumpLeadCodeNotExist; end; procedure TSkRegExp.DumpMatchProcess(ADest: TStrings); begin {$IFDEF SHOW_MATCH_PROCESS} ADest.Text := FMatchProcess.Text; {$ENDIF} end; procedure TSkRegExp.DumpNFA(ADest: TStrings); var I: Integer; Code: TRENFAState; Str: REString; begin ADest.Clear; ADest.BeginUpDate; for I := 0 to FStateList.Count - 1 do begin Code := FStateList[I]; if I = FEntryState then Str := Format(sFmtDumpNFA_Start, [I]) else if I = FExitState then Str := Format(sFmtDumpNFA_End, [I]) else Str := Format(sFmtDumpNFA_Status, [I]); while Code <> nil do begin Str := Str + Code.GetString; Code := Code.Next; end; ADest.Add(Str); end; ADest.Add(''); ADest.Add(DumpLeadCode); ADest.EndUpDate; end; procedure TSkRegExp.DumpParse(TreeView: TTreeView); function Add(Node: TTreeNode; const S: REString): TTreeNode; begin Result := TreeView.Items.AddChild(Node, Format('%s', [S])); end; procedure DumpParseSub(Code: TRECode; Node: TTreeNode); var ANode: TTreeNode; begin if Code is TREBinCode then begin with Code as TREBinCode do begin case Op of opUnion: ANode := Add(Node, sBinCode_Union); opConcat: ANode := Add(Node, sBinCode_Concat); opEmply: ANode := Add(Node, sBinCode_Emply); opLoop: ANode := Add(Node, sBinCode_Loop); opPlus: ANode := Add(Node, sBinCode_Plus); opStar: ANode := Add(Node, sBinCode_Star); opQuest: ANode := Add(Node, sBinCode_Quest); opBound: ANode := Add(Node, sBinCode_Bound); opLHead: ANode := Add(Node, sBinCode_LHead); opLTail: ANode := Add(Node, sBinCode_LTail); opGroup: ANode := Add(Node, sBinCode_Group); opNoBackTrack: ANode := Add(Node, sBinCode_NoBackTrack); opKeepPattern: ANode := Add(Node, sBinCode_KeepPattern); opFail: ANode := Add(Node, sBinCode_Fail); opAheadMatch: ANode := Add(Node, sBinCode_AheadMatch); opBehindMatch: ANode := Add(Node, sBinCode_BehindMatch); opAheadNoMatch: ANode := Add(Node, sBinCode_AheadNoMatch); opBehindNoMatch: ANode := Add(Node, sBinCode_BehindNoMatch); opGoSub: ANode := Add(Node, sBinCode_GroupCall); opIfMatch: ANode := Add(Node, sBinCode_IfMatch); opIfThen: ANode := Add(Node, sBinCode_IfThen); else raise ESkRegExp.Create(sBinCode_Raise); end; if Left <> nil then DumpParseSub(Left, ANode); if Right <> nil then DumpParseSub(Right, ANode); end; end else TreeView.Items.AddChild(Node, (Code as TRECode).GetDebugStr); end; begin TreeView.Items.Clear; DumpParseSub(FCode, nil); TreeView.FullExpand; end; {$ENDIF} function TSkRegExp.Exec(const AInputStr: REString): Boolean; var P: PWideChar; begin if not FCompiled then Compile; SetInputString(AInputStr); FMatchTopP := FTextTopP; FMatchEndP := FTextEndP; P := FTextTopP; Result := MatchCore(P); end; function TSkRegExp.ExecNext: Boolean; var P: PWideChar; begin Result := False; if not FCompiled then Error(sExecFuncNotCall); if not FSuccess then Exit; if FGlobalEndP - FGlobalStartP > 0 then P := FGlobalEndP else P := FGlobalEndP + 1; Result := MatchCore(P); end; function TSkRegExp.ExecPos(AOffset, AMaxLength: Integer): Boolean; var P: PWideChar; L: Integer; begin Result := False; if (AOffset < 1) then Exit; if FMatchTopP = nil then Exit; if not FCompiled then Compile; if AOffset > 1 then begin P := FTextTopP + AOffset - 1; // Pが改行文字だった場合の調整 if IsEOL(P, L) then Inc(P, L) else if (FEOLLen = 2) and (P^ = FEOLTailP^) then Inc(P) else if IsLineSeparator(P^) then Inc(P); end else P := FTextTopP; if AMaxLength > 0 then begin if AOffset + AMaxLength > Length(FInputString) then FMatchEndP := FTextEndP else FMatchEndP := P + AMaxLength; // ALength が指定されたときは、指定範囲内が文字列全体だと扱う。 FMatchTopP := P; end else begin FMatchEndP := FTextEndP; FMatchTopP := FTextTopP; end; Result := MatchCore(P); end; {$IFDEF JapaneseExt} function TSkRegExp.GetIgnoreZenHan: Boolean; begin Result := (roIgnoreWidth in FOptions) and (roIgnoreKana in FOptions); end; {$ENDIF JapaneseExt} function TSkRegExp.GetIndexFromGroupName(Name: REString): Integer; var LIntArray: TIntDynArray; begin LIntArray := FGroups.EnumIndexOfName(Name); for Result in LIntArray do if FGroups[Result].Capture.Matched then Exit; if Length(LIntArray) > 0 then Result := LIntArray[0] else Result := -1; end; function TSkRegExp.GetMatchLen(Index: Integer): Integer; begin Result := FGroups[Index].Length; end; function TSkRegExp.GetMatchPos(Index: Integer): Integer; begin Result := FGroups[Index].Index; end; function TSkRegExp.GetMatchStr(Index: Integer): REString; begin Result := FGroups[Index].Strings; end; function TSkRegExp.GetOptions(const Index: Integer): Boolean; var LOption: TREOption; begin case Index of 0: LOption := roIgnoreCase; 1: LOption := roMultiLine; 2: LOption := roNamedGroupOnly; 3: LOption := roSingleLine; 4: LOption := roExtended; 5: LOption := roIgnoreWidth; else LOption := roIgnoreKana; end; Result := LOption in FOptions; end; function TSkRegExp.GetNamedGroupLen(Name: REString): Integer; var LGroup: TGroup; begin LGroup := FGroups.Names[Name]; if LGroup <> nil then Result := FGroups.Names[Name].Length else Result := -1; end; function TSkRegExp.GetNamedGroupPos(Name: REString): Integer; var LGroup: TGroup; begin LGroup := FGroups.Names[Name]; if LGroup <> nil then Result := FGroups.Names[Name].Index else Result := -1; end; function TSkRegExp.GetNamedGroupStr(Name: REString): REString; var LGroup: TGroup; begin LGroup := FGroups.Names[Name]; if LGroup <> nil then Result := FGroups.Names[Name].Strings else Result := ''; end; function TSkRegExp.GetDefineCharClassLegacy: Boolean; begin Result := roDefinedCharClassLegacy in FOptions; end; function TSkRegExp.GetGroupCount: Integer; begin Result := FGroups.Count - 1; end; function TSkRegExp.GetGroupNameFromIndex(Index: Integer): REString; begin Result := FGroups[Index].GroupName; end; function TSkRegExp.GetVersion: REString; begin Result := CONST_VERSION; end; function TSkRegExp.IsEOL(AStr: PWideChar; out Len: Integer): Boolean; begin Result := False; Len := 0; if AStr^ = FEOLHeadP^ then begin if (FEOLLen = 2) and ((AStr + 1)^ = FEOLTailP^) then Len := 2 else Len := 1; Result := True; end; end; function TSkRegExp.MatchCore(AStr: PWideChar): Boolean; begin {$IFDEF DEBUG} {$IFDEF SHOW_MATCH_PROCESS} FMatchProcess.Clear; {$ENDIF} {$ENDIF} FSuccess := FMatchEngine.Match(AStr); if FSuccess then begin FGlobalStartP := FGroups[0].Capture.StartP; FGlobalEndP := FGroups[0].Capture.EndP; if Assigned(FOnMatch) then FOnMatch(Self); end else begin FGlobalStartP := FMatchTopP; FGlobalEndP := FMatchTopP; end; Result := FSuccess; end; class function TSkRegExp.RegIsMatch(const ARegExpStr, AInputStr: REString; AOptions: TREOptions): Boolean; var R: TSkRegExp; begin R := TSkRegExp.Create; try R.FOptions := AOptions; R.Expression := ARegExpStr; R.NamedGroupOnly := True; Result := R.Exec(AInputStr); finally R.Free; end; end; class function TSkRegExp.RegMatch(const ARegExpStr, AInputStr: REString; AMatches: TREStrings; AOptions: TREOptions): Boolean; var R: TSkRegExp; I: Integer; begin R := TSkRegExp.Create; try AMatches.Clear; R.FOptions := AOptions; R.Expression := ARegExpStr; if R.Exec(AInputStr) then begin for I := 0 to R.GroupCount do AMatches.Add(R.Match[I]); Result := True; end else Result := False; finally R.Free; end; end; class function TSkRegExp.RegReplace(const ARegExpStr, AInputStr: REString; AReplaceFunc: TSkRegExpReplaceFunction; AOptions: TREOptions): REString; var R: TSkRegExp; begin R := TSkRegExp.Create; try R.Options := AOptions; R.Expression := ARegExpStr; Result := R.Replace(AInputStr, AReplaceFunc) finally R.Free; end; end; class function TSkRegExp.RegReplace(const ARegExpStr, AInputStr, AReplaceStr: REString; AOptions: TREOptions): REString; var R: TSkRegExp; begin R := TSkRegExp.Create; try R.FOptions := AOptions; R.Expression := ARegExpStr; Result := R.Replace(AInputStr, AReplaceStr); finally R.Free; end; end; class procedure TSkRegExp.RegSplit(const ARegExpStr, AInputStr: REString; APieces: TREStrings; AOptions: TREOptions); var R: TSkRegExp; begin APieces.Clear; R := TSkRegExp.Create; try R.FOptions := AOptions; R.Expression := ARegExpStr; R.Split(AInputStr, APieces); finally R.Free; end; end; function TSkRegExp.Replace(const Input: REString; AReplaceFunc: TSkRegExpReplaceFunction; Count, AOffset: Integer): REString; begin FReplaceFunc := AReplaceFunc; FOnReplace := DoReplaceFunc; try Result := Replace(Input, '', Count, AOffset); finally FOnReplace := nil; FReplaceFunc := nil; end; end; function TSkRegExp.Replace(const Input, Replacement: REString; Count, AOffset: Integer): REString; var Index, LCount: Integer; RepStr: REString; LReplacement: REString; begin Result := ''; LCount := 0; InputString := Input; Index := 1; LReplacement := DecodeEscape(Replacement); if ExecPos(AOffset) then begin repeat if MatchLen[0] > 0 then begin if (Count > 0) then begin Inc(LCount); if (LCount > Count) then Break; end; RepStr := Substitute(LReplacement); if Assigned(FOnReplace) then FOnReplace(Self, RepStr); Result := Result + Copy(Input, Index, MatchPos[0] - Index) + RepStr; Index := MatchPos[0] + MatchLen[0]; end; until not ExecNext; end; Result := Result + Copy(Input, Index, MaxInt); end; class function TSkRegExp.EncodeEscape(const Str: REString): REString; var StartP: PWideChar; function GetErrorStopedString(const ErrMes: REString; P: PWideChar): REString; var S: REString; begin Inc(P); SetString(S, StartP, P - StartP); S := S + ' <-- '; Result := Format(ErrMes, [S]); end; var P: PWideChar; begin if Str = '' then Exit; P := PWideChar(Str); StartP := P; while P^ <> #0 do begin case P^ of #0009: Result := Result + '\t'; #$000A: Result := Result + '\n'; #$000D: Result := Result + '\r'; #$000C: Result := Result + '\f'; #$0007: Result := Result + '\a'; #$001B: Result := Result + '\e'; else begin if (P^ >= #$0000) and (P^ <= #$0020) then Result := Result + Format('\x%.2x', [Ord(P^)]) else Result := Result + P^; end; end; Inc(P); end; end; procedure TSkRegExp.Error(const ErrorMes: REString); begin raise ESkRegExpRuntime.Create(ErrorMes); end; procedure TSkRegExp.SetDefineCharClassLegacy(const Value: Boolean); begin if Value then begin if not(roDefinedCharClassLegacy in FOptions) then begin IsWord := IsAnkWord; IsDigit := IsAnkDigit; IsSpace := IsAnkSpace; FCompiled := False; Include(FOptions, roDefinedCharClassLegacy); end; end else begin if roDefinedCharClassLegacy in FOptions then begin IsWord := UnicodeProp.IsWord; IsDigit := UnicodeProp.IsDigit; IsSpace := UnicodeProp.IsSpace; FCompiled := False; Exclude(FOptions, roDefinedCharClassLegacy); end; end; end; procedure TSkRegExp.SetEOL(const Value: REString); begin if FEOL <> Value then begin FEOL := Value; FEOLLen := Length(FEOL); if FEOLLen > 2 then Error(sEOLRangeOver); if FEOLLen = 2 then begin FEOLHeadP := @FEOL[1]; FEOLTailP := @FEOL[2]; end else begin FEOLHeadP := @FEOL[1]; FEOLTailP := nil; end; FCompiled := False; end; end; procedure TSkRegExp.SetExpression(const Value: REString); begin if FExpression <> Value then begin FExpression := Value; FCompiled := False; end; end; {$IFDEF JapaneseExt} procedure TSkRegExp.SetIgnoreZenHan(const Value: Boolean); begin IgnoreWidth := Value; IgnoreKana := Value; end; {$ENDIF} procedure TSkRegExp.SetInputString(const Value: REString); var L: Integer; begin FInputString := Value; L := Length(FInputString); {$IFDEF CHECK_MATCH_EXPLOSION} ClearExplosionState; SetLength(FMatchExplosionState, L + 1); {$ENDIF} FTextTopP := PWideChar(FInputString); FTextEndP := FTextTopP + L; FSuccess := False; FMatchTopP := FTextTopP; FMatchEndP := FTextEndP; FGlobalStartP := FTextTopP; FGlobalEndP := FTextTopP; FGroups.Reset; end; procedure TSkRegExp.SetLexMode(const Value: TRELexMode); begin FLexMode := Value; end; procedure TSkRegExp.SetOptions(const Index: Integer; const Value: Boolean); var LOption: TREOption; begin case Index of 0: LOption := roIgnoreCase; 1: LOption := roMultiLine; 2: LOption := roNamedGroupOnly; 3: LOption := roSingleLine; 4: LOption := roExtended; 5: LOption := roIgnoreWidth; else LOption := roIgnoreKana; end; if (LOption = roNone) or (Value and (LOption in FOptions)) or (not Value and not(LOption in FOptions)) then Exit; if Value then Include(FOptions, LOption) else Exclude(FOptions, LOption); FCompiled := False; end; procedure TSkRegExp.Split(const Input: REString; APieces: TREStrings; Count, AOffset: Integer); var Index, LCount: Integer; S: REString; begin Index := 1; LCount := 0; APieces.Clear; InputString := Input; if ExecPos(AOffset) then begin repeat if MatchLen[0] > 0 then begin S := Copy(Input, Index, MatchPos[0] - Index); APieces.Add(S); Index := MatchPos[0] + MatchLen[0]; Inc(LCount); if (Count > 0) and (LCount >= Count - 1) then Break; end until not ExecNext; APieces.Add(Copy(Input, Index, MaxInt)); end; end; function TSkRegExp.Substitute(const ATemplate: REString): REString; var K: Integer; LGroupName: REString; I, L: Integer; begin Result := ''; if ATemplate = '' then Exit; if not FSuccess then Exit; I := 1; L := System.Length(ATemplate); while I <= L do begin if ATemplate[I] = '$' then begin Inc(I); if (ATemplate[I] >= '0') and (ATemplate[I] <= '9') then begin K := (Integer(ATemplate[I]) - Integer('0')); if K <= FGroups.Count - 1 then Result := Result + FGroups[K].Strings; end else if ATemplate[I] = '{' then begin Inc(I); LGroupName := ''; while (ATemplate[I] <> '}') and (ATemplate[I] <> #0000) do begin LGroupName := LGroupName + ATemplate[I]; Inc(I); end; if FGroups.IndexOfName(LGroupName) <> -1 then Result := Result + FGroups.Names[LGroupName].Strings; end else if ATemplate[I] = '&' then Result := Result + FGroups[0].Strings else if ATemplate[I] = '$' then Result := Result + '$' else if ATemplate[I] = '`' then begin Result := Result + Copy(FInputString, 1, FGroups[0].Index - 1); end else if ATemplate[I] = '''' then begin Result := Result + Copy(FInputString, FGroups[0]. Index + FGroups[0].Length, MaxInt); end else if ATemplate[I] = '_' then begin Result := Result + FInputString; end else if ATemplate[I] = '+' then begin for I := GroupCount downto 1 do begin if FGroups[I].Index > 0 then begin Result := Result + FGroups[I].Strings; Break; end; end; end else Result := Result + ATemplate[I]; end else Result := Result + ATemplate[I]; Inc(I); end; end; end.
{ Double Commander ------------------------------------------------------------------------- Terminal emulator implementation. Copyright (C) 2008 Dmitry Kolomiets (B4rr4cuda@rambler.ru) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA } unit uUnixTerm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, BaseUnix, ExtCtrls, LCLProc, cwstring, LCLType, Graphics, termio, uTerminal, uOSUtils; {$IF NOT DEFINED(DARWIN)} {$LINKLIB util} // under Linux and BSD forkpty is situated in libutil.so library {$ENDIF} const clib = 'c'; C_stdin = 0; C_stdout = 1; C_stderr = 2; const {c_cc characters} CDISABLE = 255; //key // xterm default bindings CINTR = 003; // ^C CQUIT = 034; // ^\ CERASE = 177; // ^? CKILL = 025; // ^U CEOF = 004; // ^D CSTART = 021; // ^Q CSTOP = 023; // ^S CSUSP = 032; // ^Z CREPRINT = 022; // ^R CWERASE = 027; // ^W CLNEXT = 026; // ^V CDISCARD = 017; // ^O //disabled CTIME = 0; CMIN = 1; CSWTC = CDISABLE; CEOL = CDISABLE; CEOL2 = CDISABLE; const CSIList= '@'+ // Вставить N пустых символов. 'A'+ //Переместить курсор вверх на N рядов. 'B'+ //Переместить курсор вниз на N рядов. 'C'+ //Переместить курсор вправо на N столбцов. 'D'+ //Переместить курсор влево на N столбцов. 'E'+ //Переместить курсор вниз на N рядов, в столбец #1. 'F'+ //Переместить курсор вверх на N рядов, в столбец #1. 'G'+ //Переместить курсор в указанный столбец текущего ряда. 'H'+ //Переместить курсор в указанный ряд и столбец (начало в 1,1). 'J'+ //"Очистить" экран (по умолчанию от курсора до конца экрана). ESC [ 1 J: "очистить" от начала столбца до курсора. ESC [ 2 J: "очистить" весь экран. 'K'+ //"Очистить" строку (по умолчанию от курсора до ее конца). ESC [ 1 K: "очистить" от начала строки до курсора. ESC [ 2 K: "очистить" всю строку. 'L'+ //Вставить N пустых строк. 'M'+ //Удалить N строк. 'P'+ //Удалить (со смещением в строке) N символов в текущей строке. 'X'+ //"Очистить" (без смещения в строке) N символов в текущей строке. 'a'+ //Переместить курсор вправо на N столбцов. 'c'+ //Ответить ESC [ ? 6 c: `Я являюсь VT102'. 'd'+ //Переместить курсор в указанный ряд текущего столбца. 'e'+ //Переместить курсор вниз на N рядов. 'f'+ //Переместить курсор в указанный ряд и столбец. 'g'+ //Без параметров: "очистить" текущую позицию табуляции. ESC [ 3 g: удалить все позиции табуляции. 'h'+ //Режим установки 'l'+ //Режим сброса 'm'+ //Установка атрибутов 'n'+ //Отчет о статусе 'q'+ //Установить режимы работы индикаторов на клавиатуре. ESC [ 0 q: выключить все индикаторы ESC [ 1 q: включить индикатор "Scroll Lock" ESC [ 2 q: включить индикатор "Num Lock" ESC [ 3 q: включить индикатор "Caps Lock" 'r'+ //Установить область прокрутки; параметрами будут верхний и нижний ряды. 's'+ //Сохранить местоположение курсора. 'u'; //Восстановить местоположение курсора. //'`'+ //Переместить курсор в указанный столбец текущего ряда. const NCCS = 32; type Pwinsize = ^winsize; winsize = record ws_row : word; ws_col : word; ws_xpixel : word; ws_ypixel : word; end; __pid_t = longint; Pcc_t = ^cc_t; cc_t = char; Pspeed_t = ^speed_t; speed_t = dword; Ptcflag_t = ^tcflag_t; tcflag_t = dword; Ptermios = ^termios; termios = record c_iflag : tcflag_t; c_oflag : tcflag_t; c_cflag : tcflag_t; c_lflag : tcflag_t; c_line : cc_t; c_cc : array[0..(NCCS)-1] of cc_t; c_ispeed : speed_t; c_ospeed : speed_t; end; type { TUnixTerm } TUnixTerm = class(TTerminal) private FCols,Frows:integer; //--------------------- //--------------------- public //--------------------- constructor Create; destructor Destroy; override; { \\---------------------} function Read_Pty(var str:String; const timeout: longint=10): longint; override; // Read info from pty function Fork_pty(const rows,cols:integer; const cmd:String; const params:String=''):System.THandle; override; //Create new pty and start cmd function Write_pty(const str:String):boolean; override; //write str to pty //--------------------- function SendBreak_pty():boolean; override; // ^C function SendSignal_pty(Sig:Cint):boolean; override; function SetScreenSize(aCols,aRows:integer):boolean; override; function SetCurrentDir(const NewDir: String): Boolean; override; //--------------------- function KillShell:LongInt; override; function CSI_GetTaskId(const buf:String):integer; override; //get index of sequence in CSILast list end; { TConThread } TUnixConThread = class(TConsoleThread) private procedure AddSymbol; procedure CSIProc(NCode, Param: integer; ExParam: integer=0); procedure CSI_CaretTo(Y, X: integer); procedure CSI_Colors(const Param: integer); procedure WriteS(const s: String); protected procedure Execute; override; public constructor Create; destructor Destroy; override; end; function forkpty(__amaster:Plongint; __name:Pchar; __termp:Ptermios; __winp:Pwinsize):longint;cdecl;external clib name 'forkpty'; function setenv(__name:Pchar; __value:Pchar; __replace:longint):longint;cdecl;external clib name 'setenv'; function execl(__path:Pchar; __arg:Pchar):longint;cdecl;varargs;external clib name 'execl'; implementation uses DCUnix, uDebug; { TUnixConThread } procedure TUnixConThread.WriteS(const s:String); begin if not assigned(FOut) then exit; //Form1.CmdBox1.StopRead; FOut.Write(s); //Form1.CmdBox1.StartRead(clWhite,clBlack,'',clWhite,clBlack); end; procedure TUnixConThread.CSI_Colors(const Param:integer); begin if not assigned(FOut) then exit; with FOut do begin case Param of 0: TextColors(clWhite,clBlack);// сбросить все атрибуты в их значения по умолчанию 1: ;// установить жирный шрифт 2: ;// установить более яркий (имитированное цветом на цветном дисплее) 4: ;// установить подчеркивание (имитированное цветом на цветном дисплее); //цвета, используемые для имитации затемнения или подчеркивания, устанавливаются //при помощи ESC ] ... 5: ;// включить мерцание 7: ;// включить режим инвертированного видео 10: ;// сбросить выбранное распределение, флаги управления экраном //и переключить метафлаг 11: ;// выбрать null-распределение, установить флаг управления экраном, //сбросить переключатель метафлага. 12: ;// выбрать null-распределение, установить флаг управления экраном, //включить переключатель метафлага. Переключение метафлага //задает переключение старшего бита в байте //до его трансформации согласно таблице распределения. 21: ;// включить режим нормальной интенсивности (несовместимо с ECMA-48) 22: ;// выключить режим нормальной интенсивности 24: ;// выключить подчеркивание 25: ;// выключить мерцание 27: ;// выключить инвертированное видео 30:TextColor(clGray) ;// установить черный цвет символов 31:TextColor(clRed) ;// установить красный цвет символов 32:TextColor($0024F947) ;// установить зеленый цвет символов 33:TextColor($003A85CF) ;// установить коричневый цвет символов 34:TextColor(clBlue) ;// установить синий цвет символов 35:TextColor(clPurple) ;// установить сиреневый цвет символов 36:TextColor(clSkyBlue) ;// установить голубой цвет символов 37:TextColor(clWhite);// установить белый цвет символов 38:TextColor(clWhite);// включить подчеркивание, установить цвет символов по умолчанию 39:TextColor(clWhite) ;// выключить подчеркивание, установить цвет символов по умолчанию 40:TextBackground(clBlack) ;// установить черный цвет фона 41:TextBackground(clRed) ;// установить красный цвет фона 42:TextBackground(clGreen) ;// установить зеленый цвет фона 43:TextBackground(clRed) ;// установить коричневый цвет фона 44:TextBackground(clBlue) ;// установить синий цвет фона 45:TextBackground(clPurple) ;// установить сиреневый цвет фона 46:TextBackground(clSkyBlue) ;// установить голубой цвет фона 47:TextBackground(clWhite) ;// установить белый цвет фона 49:TextBackground(clBlack) ;// установить цвет фона по умолчанию end; end; end; procedure TUnixConThread.CSI_CaretTo(Y,X:integer); //хз x y или y x. Надо проверить. begin DCDebug(' Y: '+inttostr(Y)+' X: '+inttostr(X)); //Fout.OutY:=Y; //Fout.OutX:=X; end; procedure TUnixConThread.CSIProc(NCode, Param:integer; ExParam:integer=0); begin //DCDebug('Code:'+Inttostr(NCode)+' Param: '+inttostr(Param)); case NCode of 9:CSI_CaretTo(Param,ExParam); 24:CSI_Colors(Param); end; end; constructor TUnixConThread.Create; begin inherited Create(true); System.InitCriticalSection(FLock); Fterm:=TUnixTerm.Create; FRowsCount:=50; FColsCount:=100; end; destructor TUnixConThread.Destroy; begin FreeAndNil(fTerm); System.DoneCriticalSection(FLock); inherited Destroy; end; procedure TUnixConThread.Execute; begin FShell:=GetShell; if length(FShell)=0 then FShell:='/bin/bash'; if Assigned(fterm) then Fterm.Fork_pty(FRowsCount,FColsCount,FShell); while true do begin if Assigned(fterm) then begin if Fterm.Read_Pty(fbuf,0)>0 then Synchronize(@AddSymbol) else Sleep(1); end else break; end; end; //------------------------------------------------------ procedure TUnixConThread.AddSymbol; var SeqCode,SeqPrm,i,x:integer; es,s:String; esnow,CSINow:boolean; begin s:=''; es:=''; esnow:=false; CSInow:=false; for i:=1 to length(fbuf) do begin //разбор //------------------------------------------------------ if esnow then begin //------------------------------------------------------ if CSINow then begin //Пытаемся определить управляющий символ CSI последовательности SeqCode:=(fTerm.CSI_GetTaskId(es)); if SeqCode>0 then begin //разбор управляющей последовательности. //------------------------------------------------------ WriteS(s); s:=''; delete(es,1,1); delete(es,length(es),1); x:=pos(';',es); while x>0 do begin if tryStrToInt(copy(es,1,x-1),SeqPrm) then begin CSIProc(SeqCode,SeqPrm); delete(es,1,x); x:=pos(';',es); end else begin WriteS(copy(es,1,x-1)); delete(es,1,x); x:=pos(';',es); end; end; if es<>'' then begin if tryStrToInt(es,SeqPrm) then CSIProc(SeqCode,SeqPrm) else WriteS(es); end; //------------------------------------------------------ es:=''; esnow:=false; CSINow:=False; end else es:=es+fbuf[i]; end else es:=es+fbuf[i]; //------------------------------------------------------ end; //Начало управляющей последовательности if (fbuf[i]=#155) or ((fbuf[i]=#27)) then begin esnow:=true; //Начало CSI последовательности if (i<length(fbuf)) and (fbuf[i+1]='[') then CSINow:=true; end; //выбор чарсета. Неактуально.... if fbuf[i]='%' then continue; //удалить последний символ if fbuf[i]=#8 then s:=copy(s,1,length(s)-1); //simple text or control symbols (Nither CSI nor escape sequenses) if (esnow=false) and ((fbuf[i]>#31) or (fbuf[i]=#13) or (fbuf[i]=#10)) then begin if fbuf[i]=#10 then begin if s<>'' then if Assigned(FOut) then FOut.Write(s+#10); s:=''; continue; end; if (fbuf[i]=#13) then if Assigned(FOut) then FOut.Write(#13); s:=s+fbuf[i]; end; //------------------------------------------------------ end; if s<>'' then begin if Assigned(FOut) then FOut.Write(s); end; end; //------------------------------------------------------ { TUnixTerm } function TUnixTerm.CSI_GetTaskId(const buf:String):integer; var Rez,L,R,M:integer; begin result:=0; if buf='' then exit; if buf[length(buf)]='`' then begin result:=length(CSIList)+1; exit; end; //бинарный поиск L:=0; R:=Length(CSIList); while (L<=R) do begin M:=(L+R) div 2; Rez:=CompareChar(CSIList[M],buf[length(buf)],1); if Rez=0 then begin Result:=M; exit; end else if Rez<0 then L:=M+1 else R:=M-1; end; result:=0; end; function TUnixTerm.Fork_pty(const rows, cols: integer; const cmd:String; const params:String=''): System.THandle; var ws:TWinSize; ChildPid:System.THandle; begin FCols:=cols; Frows:=rows; ws.ws_row:=rows; ws.ws_col:=cols; ws.ws_xpixel:=0; ws.ws_ypixel:=0; ChildPid:=forkpty(@Fpty,nil,nil,@ws); if ChildPid<0 then begin Result:=-1; Exit; end; if ChildPid=0 then begin //Child FileCloseOnExecAll; setenv('TERM', 'linux', 1); execl(pchar(cmd), pchar(params), nil); //если execl не сработал и новый процесс не подменил форкнутый, то ошибка fpWrite(C_stderr, pchar('execl() failed. Command: '+ cmd),length('execl() failed. Command: '+ cmd)); fpExit(127); // error exec'ing end; FChildPid:=ChildPid; Result:=ChildPid; end; function TUnixTerm.Read_Pty(var str:String; const timeout:longint=10):longint; var ifs:TFdSet; BytesRead:longint; buf:array [0..512] of char; begin Result:=0; if Fpty<0 then exit; //check if pty has new info for us fpFD_ZERO(ifs); fpFD_SET(Fpty,ifs); if FPSelect(fpty+1,@ifs,nil,nil,timeout)<=0 then exit; bytesread := fpread(fpty, buf, 512); result:=bytesread; str:=''; if bytesread <= 0 then exit; str:=copy(buf,0,BytesRead); end; function TUnixTerm.Write_pty(const str: String): boolean; var BytesWritten:TSize; i:integer; begin i:=1; result:=true; while i<=length(str) do begin BytesWritten:=fpwrite(Fpty,str[i],length(str[i])); result:=result and (BytesWritten>0); i:=i+1; end; end; function TUnixTerm.SendBreak_pty(): boolean; begin result:=SendSignal_pty(CINTR); end; function TUnixTerm.SendSignal_pty(Sig: Cint): boolean; var BytesWritten:TSize; begin BytesWritten:=fpwrite(Fpty,Sig,sizeof(sig)); Result := (BytesWritten>0); end; function TUnixTerm.SetScreenSize(aCols, aRows: integer): boolean; var ws:TWinSize; begin ws.ws_row:=aRows; ws.ws_col:=aCols; ws.ws_xpixel:=0; ws.ws_ypixel:=0; if FpIOCtl(Fpty,TIOCSWINSZ,@ws)=0 then begin Result:=true; FCols:=aCols; Frows:=aRows; end else Result:=false; end; function TUnixTerm.SetCurrentDir(const NewDir: String): Boolean; begin Result:= Write_pty(' cd "' + NewDir + '"' + #13); end; function TUnixTerm.KillShell: LongInt; begin //FchildPid must be >0 in other case all processes in this group will be killed if FChildPid>0 then result:=fpkill(FChildPid,SIGKILL) else result:=-1; end; constructor TUnixTerm.Create; var tio:termio.termios; begin TCGetAttr(Fpty,tio); tio.c_iflag:=BRKINT or IGNPAR or ICRNL or IXON; tio.c_oflag:=OPOST or ONLCR; tio.c_cflag:=CS8 or CREAD; tio.c_lflag:=ISIG or ICANON or IEXTEN or ECHO or ECHOE or ECHOK or ECHOKE or ECHOCTL; tio.c_cc[VINTR]:=CINTR; tio.c_cc[VQUIT]:=CQUIT; tio.c_cc[VERASE]:=CERASE; tio.c_cc[VKILL]:=CKILL; tio.c_cc[VSTART]:=CSTART; tio.c_cc[VSTOP]:=CSTOP; tio.c_cc[VSUSP]:=CSUSP; tio.c_cc[VREPRINT]:=CREPRINT; tio.c_cc[VDISCARD]:=CDISCARD; tio.c_cc[VWERASE]:=CWERASE; tio.c_cc[VLNEXT]:=CLNEXT; tio.c_cc[VEOF]:=CEOF; tio.c_cc[VEOL]:=CEOL; tio.c_cc[VEOL2]:=CEOL2; {$IF DEFINED(LINUX)} tio.c_cc[VSWTC]:=CSWTC; {$ENDIF} tio.c_cc[VMIN]:=CMIN; tio.c_cc[VTIME]:=CTIME; TCSetAttr(Fpty,TCSANOW,tio); end; destructor TUnixTerm.Destroy; begin KillShell; inherited Destroy; end; end. {// thr.Terminal.Write_pty(#27+'[21~'); //F10 // thr.Terminal.Write_pty(#27+'[D'); //Left // thr.Terminal.Write_pty(#27+'[3~'); //delete }
unit Base.Test; interface uses IBX.IBDatabase, Spring.Persistence.Core.ConnectionFactory, Spring.Persistence.Core.Interfaces, Spring.Persistence.Core.Session, Spring.Persistence.Adapters.IBX, Spring.Collections, Spring.Persistence.SQL.Params, Spring.Persistence.Criteria.Interfaces, Spring.Persistence.Criteria.Restrictions, DUnitX.TestFramework; {$M+} type [TestFixture] TTestBaseORM = class(TObject) strict private FDatabase: TIBDataBase; FConnection: IDBConnection; FSession: TSession; private const LocalDbName = '.\dummy.fdb'; private procedure CleanDB(); public property Database: TIBDataBase read FDatabase write FDatabase; property Connection: IDBConnection read FConnection write FConnection; property Session: TSession read FSession write FSession; public [SetupFixture] procedure SetupFixture; [TearDownFixture] procedure TearDownFixture; [Setup] procedure Setup; [TearDown] procedure TearDown; end; {$M-} implementation uses System.SysUtils, System.IOUtils, Nathan.Resources.ResourceManager; procedure TTestBaseORM.SetupFixture; begin CleanDB(); ResourceManager.SaveToFile('Resource_demo', LocalDbName); end; procedure TTestBaseORM.TearDownFixture; begin CleanDB(); end; procedure TTestBaseORM.Setup; begin // Create Database and Transaction for Firebird... FDatabase := TIBDataBase.Create(nil); FDatabase.DatabaseName := LocalDbName; FDatabase.Params.Add('user_name=Sysdba'); FDatabase.Params.Add('password=masterkey'); FDatabase.Params.Add('lc_ctype=WIN1252'); FDatabase.LoginPrompt := False; // FDatabase.Connected // Then we need to create our IDBConnection and TSession instances... FConnection := TConnectionFactory.GetInstance(dtIBX, FDatabase); // Another option are to create manually... // FConnection := TIBXConnectionAdapter.Create(FDatabase); FConnection.AutoFreeConnection := True; FConnection.Connect; // TSession is our main work class... FSession := TSession.Create(FConnection); end; procedure TTestBaseORM.TearDown; begin FSession.Free; FConnection := nil; end; procedure TTestBaseORM.CleanDB(); begin if TFile.Exists(LocalDbName) then TFile.Delete(LocalDbName); end; initialization TDUnitX.RegisterTestFixture(TTestBaseORM); end.
{*******************************************} { TeeChart Pro Bitmap exporting } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {*******************************************} unit TeeBmpOptions; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, Types, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, {$ENDIF} TeeProcs, TeeExport, TeCanvas; type TBMPOptions = class(TForm) CBMono: TCheckBox; Label1: TLabel; CBColors: TComboFlat; procedure CBMonoClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; TBMPExportFormat=class(TTeeExportFormat) private FProperties: TBMPOptions; Procedure CheckProperties; protected Procedure DoCopyToClipboard; override; public Function Bitmap:TBitmap; function Description:String; override; function FileExtension:String; override; function FileFilter:String; override; Function Options(Check:Boolean=True):TForm; override; Procedure SaveToStream(Stream:TStream); override; end; Procedure TeeSaveToBitmap( APanel:TCustomTeePanel; Const FileName: WideString; Const R:TRect); implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses {$IFDEF CLX} QClipbrd, {$ELSE} Clipbrd, {$ENDIF} TeeConst; procedure TBMPOptions.CBMonoClick(Sender: TObject); begin CBColors.Enabled:=not CBMono.Checked; end; function TBMPExportFormat.Description:String; begin result:=TeeMsg_AsBMP; end; function TBMPExportFormat.FileFilter:String; begin result:=TeeMsg_BMPFilter; end; function TBMPExportFormat.FileExtension:String; begin result:='bmp'; end; Function TBMPExportFormat.Bitmap:TBitmap; var tmp : TBitmap; R : TRect; Old : Boolean; begin CheckProperties; tmp:=TBitmap.Create; CheckSize; tmp.Width:=Width; tmp.Height:=Height; tmp.Monochrome:=FProperties.CBMono.Checked; {$IFNDEF CLX} if not FProperties.CBMono.Checked then tmp.PixelFormat:=TPixelFormat(FProperties.CBColors.ItemIndex); {$ENDIF} if Panel.Canvas.SupportsFullRotation then tmp.PixelFormat:=TeePixelFormat; R:=TeeRect(0,0,tmp.Width,tmp.Height); With tmp do begin Canvas.Brush.Color:=Panel.Color; Canvas.FillRect(R); Old:=Panel.BufferedDisplay; Panel.BufferedDisplay:=False; Panel.Draw(Canvas,R); Panel.BufferedDisplay:=Old; end; result:=tmp; end; Procedure TBMPExportFormat.CheckProperties; begin if not Assigned(FProperties) then FProperties:=TBMPOptions.Create(nil) end; Function TBMPExportFormat.Options(Check:Boolean=True):TForm; begin if Check then CheckProperties; result:=FProperties; end; procedure TBMPExportFormat.DoCopyToClipboard; var tmp : TBitmap; begin tmp:=Bitmap; try Clipboard.Assign(tmp); finally tmp.Free; end; end; procedure TBMPExportFormat.SaveToStream(Stream:TStream); begin with Bitmap do try SaveToStream(Stream); finally Free; end; end; Procedure TeeSaveToBitmap( APanel:TCustomTeePanel; Const FileName: WideString; Const R:TRect); begin with TBMPExportFormat.Create do try Panel:=APanel; Width:=R.Right-R.Left; Height:=R.Bottom-R.Top; SaveToFile(FileName); finally Free; end; end; procedure TBMPOptions.FormCreate(Sender: TObject); begin CBColors.ItemIndex:=0; end; procedure TBMPOptions.FormShow(Sender: TObject); begin CBColors.ItemIndex:=0; end; initialization RegisterTeeExportFormat(TBMPExportFormat); finalization UnRegisterTeeExportFormat(TBMPExportFormat); end.
unit UnitMain; {$mode delphi} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls; type { TFormMain } TFormMain = class(TForm) Disp: TPaintBox; Timer: TTimer; procedure DispClick(Sender: TObject); procedure DispPaint(Sender: TObject); procedure TimerTimer(Sender: TObject); private TextAngle: Integer; public end; var FormMain: TFormMain; implementation {$R *.lfm} uses Math; { TFormMain } procedure TFormMain.DispPaint(Sender: TObject); const Text = ' ♥ ObjectPascal'; SpectrumColors: array [0..6] of TColor = (clBlue, clRed, clFuchsia, clLime, clAqua, clYellow, clWhite); var I: Integer; begin Self.Disp.Canvas.Font.Size := Ceil(0.038 * Min(Self.Disp.Width, Self.Disp.Height)); Self.Disp.Canvas.Brush.Style := bsClear; for I := 0 to High(SpectrumColors) do begin Self.Disp.Canvas.Font.Color := SpectrumColors[I]; Self.Disp.Canvas.Font.Orientation := Self.TextAngle + Trunc(I * 3600 / Length(SpectrumColors)); Self.Disp.Canvas.TextOut( Self.Disp.Width div 2, Self.Disp.Height div 2, Text ); end; end; procedure TFormMain.DispClick(Sender: TObject); begin ShowMessage('Do you love ObjectPascal?'); end; procedure TFormMain.TimerTimer(Sender: TObject); begin Self.TextAngle := Self.TextAngle + 15; Self.Disp.Invalidate; end; end.
program BinaryTree; type Nd = ^Node; Node = record val : integer; L, R : Nd; { Left, right, parent} end; function NewNode(val : integer; L, R : Nd) : Nd; var A : Nd; begin new(A); A^.val := val; A^.L := L; A^.R := R; NewNode := A; end; procedure AddNode(val : integer; Root : Nd); var Prev, C : Nd; { current node } done : boolean; left : boolean; begin done := false; C := Root; while (C <> nil) and (not done) do begin Prev := C; if val > C^.val then begin C := C^.R; left := false; end else if val < C^.val then begin C := C^.L; left := true; end else done := true; end; if not done then begin if left then Prev^.L := NewNode(val, nil, nil) else Prev^.R := NewNode(val, nil, nil); end; end; function Find(val : integer; Root : Nd) : Nd; var C : Nd; { current node } i : integer; { current level } found : boolean = false; begin i := 0; C := Root; while C <> nil do begin if val > C^.val then C := C^.R else if val < C^.val then C := C^.L else begin found := true; writeln('found at i: ', i); Find := C; C := nil; end; i := i + 1; end; if not found then writeln('not found'); end; function FindPrev(val : integer; Root : Nd) : Nd; var Prev : Nd; C : Nd; { current node } i : integer; { current level } found : boolean = false; begin i := 0; C := Root; while C <> nil do begin if val > C^.val then begin Prev := C; C := C^.R; end else if val < C^.val then begin Prev := C; C := C^.L; end else begin found := true; writeln('found at i: ', i); FindPrev := Prev; break; end; i := i + 1; end; if not found then writeln('not found'); end; function FindHighestPrev(Root : Nd) : Nd; var Prev : Nd; C : Nd; { current node } begin C := Root; while C <> nil do begin if C^.R = nil then begin FindHighestPrev := Prev; C := nil; end else begin Prev := C; C := C^.R; end; end; end; procedure RemoveByValue(val : integer; Root : Nd); var TRPrev : Nd; TR : Nd; { node to remove } MaxPrev : Nd; begin TRPrev := FindPrev(val, Root); if TRPrev^.L^.val = val then TR := TRPrev^.L else TR := TRPrev^.R; if TR <> nil then begin if (TR^.L = nil) and (TR^.R = nil) then begin if TRPrev^.L^.val = val then TRPrev^.L := nil else TRPrev^.R := nil; end else if TR^.L = nil then begin TR^.val := TR^.R^.val; TR^.R := nil; end else if TR^.R = nil then begin TR^.val := TR^.L^.val; TR^.L := nil; end else begin { find highest in the left subtree, could also find the lowest in the right subtree } MaxPrev := FindHighestPrev(TR^.L); TR^.val := MaxPrev^.R^.val; MaxPrev^.R := nil; end; end else writeln('node not found'); end; var A : Nd; begin A := NewNode(20, nil, nil); AddNode(10, A); AddNode(32, A); AddNode(5, A); AddNode(6, A); AddNode(14, A); AddNode(27, A); AddNode(40, A); AddNode(2, A); AddNode(11, A); AddNode(16, A); AddNode(43, A); RemoveByValue(10, A); writeln(A^.L^.val); Find(6, A); end.
{ *************************************************************************** } { } { Delphi and Kylix Cross-Platform Visual Component Library } { } { Copyright (c) 2000-2002 Borland Software Corporation } { } { *************************************************************************** } unit QFileCtrls; interface uses {$IFDEF MSWINDOWS} Windows, ShellAPI, Registry, {$ENDIF} Types, SysUtils, Classes, QTypes, QControls, QGraphics, QStdCtrls, QComCtrls, Qt, QImgList, IniFiles {$IFDEF LINUX} , Libc {$ENDIF} ; const RESULT_OK = 0; RESULT_ACCESS_DENIED = -1; RESULT_DIR_NOT_EMPTY = -2; RESULT_FILE_NOT_FOUND = -3; RESULT_ALREADY_EXISTS = -4; type TDirectoryTreeView = class; TFileHistoryComboBox = class; TFileEdit = class; TIconSize = (isSmall, isLarge, isVeryLarge); TFileIconProvider = class(TCustomImageList) private FIndexes: TStringHash; FIconSize: TIconSize; protected function DoGetImageIndex(Info: PFileInfo; const CurDir: string = ''): Integer; virtual; procedure DrawLinkOverlay(Canvas: TCanvas; X, Y: Integer; Info: PFileInfo); virtual; procedure Init; virtual; public constructor Create(Size: TIconSize); reintroduce; virtual; destructor Destroy; override; procedure Clear; property IconSize: TIconSize read FIconSize; property Indexes: TStringHash read FIndexes; end; TFileIconProviderClass = class of TFileIconProvider; TSortDirection = (sdAscending, sdDescending); TSortMode = (smNone, smName, smSize, smType, smDate, smAttributes, smOwner, smGroup); TFileAttr = (ftReadOnly, ftHidden, ftSystem, ftVolumeID, ftDirectory, ftArchive, ftNormal); TFileType = set of TFileAttr; TDirectoryChangeEvent = procedure(Sender: TObject; const NewDir: WideString) of object; TFileFoundEvent = procedure(Sender: TObject; const AFile: TSearchRec; var CanAdd: Boolean) of object; TMaskChangeEvent = procedure(Sender: TObject; const NewMask: WideString) of object; IDirectoryClient = interface ['{9EF96257-2736-D611-9E48-00B0D006527D}'] function FileFound(const SearchRec: TSearchRec): Boolean; procedure ListEnd; function ListStart: Boolean; procedure DirectoryChanged(const NewDir: WideString); procedure MaskChange(const NewMask: WideString); end; {$IFDEF MSWINDOWS} TShellChangeThread = class(TThread) private FMutex: Integer; FWaitHandle: Integer; FChangeEvent: TThreadMethod; FDirectory: string; protected procedure Execute; override; public constructor Create(ChangeEvent: TThreadMethod; Directory: string); virtual; destructor Destroy; override; end; {$ENDIF} TDirectory = class(TPersistent) private FAutoUpdate: Boolean; FIncludeParentDir: Boolean; FSortMode: TSortMode; FFileType: TFileType; FSuspendEvents: Boolean; FDirChanging: Boolean; FClient: IDirectoryClient; FFiles: TList; FDir: WideString; FDirHandle: Integer; FMask: WideString; FSortDirection: TSortDirection; FUpdateCount: Integer; {$IFDEF MSWINDOWS} FChangeThread: TShellChangeThread; procedure ChangeNotification; {$ENDIF} procedure ClearList; procedure RemoveChangeNotification; procedure SetChangeNotification(const Dir: string); procedure SetIncludeParentDir(const Value: Boolean); procedure SetAutoUpdate(const Value: Boolean); procedure SetSortMode(const Value: TSortMode); procedure SetSortDirection(const Value: TSortDirection); function GetDir: WideString; procedure ListDrives; protected procedure AssignTo(Dest: TPersistent); override; procedure DoFileFound(const SearchRec: TSearchRec); dynamic; procedure DoListEnd; dynamic; function DoListStart: Boolean; dynamic; procedure DoDirChange(const NewDir: WideString); dynamic; procedure DoMaskChange(const NewMask: WideString); dynamic; procedure SetDir(const Value: WideString); virtual; procedure SetMask(const Value: WideString); virtual; procedure SetFileType(const Value: TFileType); virtual; function UniqueName(const Name: WideString): WideString; public constructor Create(AClient: IDirectoryClient); reintroduce; virtual; destructor Destroy; override; procedure BeginUpdate; function Count: Integer; function CreateDirectory(const DirName: WideString): PFileInfo; function Delete(const Filename: WideString): Integer; overload; function Delete(AFile: PFileInfo): Integer; overload; procedure EndUpdate; function IndexOf(const Filename: WideString): Integer; procedure ListFiles(Reread: Boolean = True); virtual; procedure Sort; {$IFDEF LINUX} function LinkName(Index: Integer): WideString; {$ENDIF} function Files(Index: Integer): PFileInfo; function Rename(const Filename, NewName: WideString): Integer; overload; function Rename(AFile: PFileInfo; const NewName: WideString): Integer; overload; function Caption(Index: Integer): WideString; function Attributes(Index: Integer): Integer; function Size(Index: Integer): Cardinal; function Date(Index: Integer): Integer; {$IFDEF LINUX} function GroupName(Index: Integer): WideString; function OwnerName(Index: Integer): WideString; {$ENDIF} published property AutoUpdate: Boolean read FAutoUpdate write SetAutoUpdate default False; property IncludeParentDir: Boolean read FIncludeParentDir write SetIncludeParentDir default True; property Location: WideString read GetDir write SetDir; property FileType: TFileType read FFileType write SetFileType default [ftNormal, ftSystem, ftDirectory]; property FileMask: WideString read FMask write SetMask; property SortMode: TSortMode read FSortMode write SetSortMode default smName; property SortDirection: TSortDirection read FSortDirection write SetSortDirection default sdAscending; end; TFileListColumn = (flcName, flcSize, flcType, flcDate, flcAttributes {$IFDEF LINUX} , flcOwner, flcGroup {$ENDIF}); { TODO 2 : TreeView: Handle setting directory when user doesn't have read access. } TFileListView = class(TCustomListView, IDirectoryClient) private FSaveCursor: TCursor; FCreatingDir: Boolean; FCreatedDir: Boolean; {$IFDEF MSWINDOWS} FDrivesListed: Boolean; {$ENDIF} FDirectory: TDirectory; FOnDirChange: TDirectoryChangeEvent; FOnFileFound: TFileFoundEvent; FIconProvider: TFileIconProvider; FOnMaskChange: TMaskChangeEvent; function GetSelections: TFileInfos; procedure SetDirectory(const Value: TDirectory); procedure ImageChange; protected procedure ColumnClicked(Column: TListColumn); override; function CreateEditor: TItemEditor; override; procedure DblClick; override; procedure DoGetImageIndex(item: TCustomViewItem); override; function DoCustomDrawViewItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; override; function DoCustomDrawViewSubItem(Item: TCustomViewItem; SubItem: Integer; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; override; function DoCustomHint(var HintInfo: THintInfo): Boolean; override; procedure DoEdited(AItem: TCustomViewItem; var S: WideString); override; procedure DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean); override; procedure ImageListChanged; override; procedure InitWidget; override; function IsCustomDrawn: Boolean; override; function IsOwnerDrawn: Boolean; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure Loaded; override; function NeedKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; override; procedure PositionEditor(var NewLeft, NewTop: Integer); override; { IDirectoryClient } function FileFound(const SearchRec: TSearchRec): Boolean; dynamic; procedure ListEnd; dynamic; function ListStart: Boolean; dynamic; procedure DirectoryChanged(const NewDir: WideString); dynamic; procedure MaskChange(const NewMask: WideString); dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CreateDirectory(const DefaultName: WideString); function DeleteFile(const Filename: WideString): Integer; procedure GoDown; procedure GoUp; procedure Refresh; function RenameFile(Item: TListItem; const NewName: WideString): Integer; property Canvas; property Columns; property Items; property SelCount; property Selections: TFileInfos read GetSelections; published property Align; property Anchors; property BorderStyle default bsSunken3d; property Color; property ColumnClick default True; property ColumnResize default True; property Constraints; property Directory: TDirectory read FDirectory write SetDirectory; property DragMode; property Enabled; property Font; property Height; property Hint; property Images; property MultiSelect default False; property ReadOnly default True; property RowSelect default False; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property ViewStyle; property Visible; property Width; property OnChange; property OnChanging; property OnClick; property OnColumnClick; property OnColumnDragged; property OnColumnResize; property OnContextPopup; property OnCustomDrawItem; property OnCustomDrawSubItem; property OnDblClick; property OnDeletion; property OnDirectoryChanged: TDirectoryChangeEvent read FOnDirChange write FOnDirChange; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnEdited; property OnEditing; property OnEndDrag; property OnEnter; property OnExit; property OnFileFound: TFileFoundEvent read FOnFileFound write FOnFileFound; property OnGetImageIndex; property OnInsert; property OnItemClick; property OnItemDoubleClick; property OnItemEnter; property OnItemExitViewportEnter; property OnItemMouseDown; property OnKeyDown; property OnKeyPress; property OnKeyString; property OnKeyUp; property OnMaskChange: TMaskChangeEvent read FOnMaskChange write FOnMaskChange; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnResize; property OnSelectItem; property OnStartDrag; property OnViewPortMouseDown; end; TFileIconView = class(TCustomIconView, IDirectoryClient) private FSaveCursor: TCursor; FCreatingDir: Boolean; FCreatedDir: Boolean; {$IFDEF MSWINDOWS} FDrivesListed: Boolean; {$ENDIF} FIconSize: TIconSize; FDirectory: TDirectory; FOnDirChange: TDirectoryChangeEvent; FOnFileFound: TFileFoundEvent; FIconProvider: TFileIconProvider; FOnMaskChange: TMaskChangeEvent; function GetSelections: TFileInfos; procedure SetIconSize(const Value: TIconSize); procedure ImageChange; procedure SetDirectory(const Value: TDirectory); protected function CreateEditor: TItemEditor; override; procedure DblClick; override; procedure DoGetImageIndex(item: TIconViewItem); override; function DoCustomDrawIconItem(Item: TIconViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; override; function DoCustomHint(var HintInfo: THintInfo): Boolean; override; procedure DoEdited(AItem: TIconViewItem; var S: WideString); override; procedure DoEditing(AItem: TIconViewItem; var AllowEdit: Boolean); override; procedure DoGetIconSize(Item: TIconViewItem; var Width, Height: Integer); override; procedure ImageListChanged; override; procedure InitWidget; override; function IsCustomDrawn: Boolean; override; function IsOwnerDrawn: Boolean; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure Loaded; override; function NeedKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; override; procedure PositionEditor(var NewLeft, NewTop: Integer); override; { IDirectoryClient } function FileFound(const SearchRec: TSearchRec): Boolean; dynamic; procedure ListEnd; dynamic; function ListStart: Boolean; dynamic; procedure DirectoryChanged(const NewDir: WideString); dynamic; procedure MaskChange(const NewMask: WideString); dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CreateDirectory(const DefaultName: WideString); function DeleteFile(const Filename: WideString): Integer; procedure GoDown; procedure GoUp; procedure Refresh; function RenameFile(Item: TIconViewItem; const NewName: WideString): Integer; property Items; property SelCount; property Selected; property Selections: TFileInfos read GetSelections; published property Align; property Anchors; property BorderStyle default bsSunken3d; property Color; property Constraints; property Directory: TDirectory read FDirectory write SetDirectory; property DragMode; property Enabled; property Font; property Height; property Hint; property IconOptions; property IconSize: TIconSize read FIconSize write SetIconSize default isLarge; property Images; property MultiSelect; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly default True; property ShowHint; property TabOrder; property TabStop; property TextPosition; property Visible; property Width; property OnChange; property OnChanging; property OnClick; property OnContextPopup; property OnCustomDrawItem; property OnDblClick; property OnDirectoryChange: TDirectoryChangeEvent read FOnDirChange write FOnDirChange; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnEdited; property OnEditing; property OnEndDrag; property OnEnter; property OnExit; property OnFileFound: TFileFoundEvent read FOnFileFound write FOnFileFound; property OnGetImageIndex; property OnItemClicked; property OnItemDoubleClick; property OnItemEnter; property OnItemExitViewportEnter; property OnKeyDown; property OnKeyPress; property OnKeyString; property OnKeyUp; property OnMaskChange: TMaskChangeEvent read FOnMaskChange write FOnMaskChange; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnResize; property OnSelectItem; property OnStartDrag; end; TDirectoryNode = class(TTreeNode) private FDirClient: IDirectoryClient; FDirectory: TDirectory; protected procedure UpdateImages; override; public constructor Create(AOwner: TCustomViewItems; AParent: TCustomViewItem = nil; After: TCustomViewItem = nil); override; destructor Destroy; override; procedure Populate; { IDirectoryClient proxy } function FileFound(const SearchRec: TSearchRec): Boolean; virtual; procedure ListEnd; virtual; function ListStart: Boolean; virtual; procedure DirectoryChanged(const NewDir: WideString); virtual; procedure MaskChange(const NewMask: WideString); virtual; end; EDirectoryError = class(Exception); ESetDirectoryError = class(EDirectoryError); ECreateDirectoryError = class(EDirectoryError); TDirectoryTreeView = class(TCustomTreeView) private FChanging: Boolean; FFileType: TFileType; FIconSize: TIconSize; FRootDir: WideString; FDir: WideString; FIconProvider: TFileIconProvider; FakePix: QPixmapH; procedure SetDir(const Value: WideString); function GetAbsolutePath(Node: TTreeNode): string; procedure SetRootDir(const Value: WideString); function GetDir: WideString; procedure SetFileType(const Value: TFileType); protected procedure AddDirectories(Node: TTreeNode); function CanExpand(Node: TTreeNode): Boolean; override; procedure Change(Node: TTreeNode); override; function DoCustomDrawViewItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; override; function DoCustomHint(var HintInfo: THintInfo): Boolean; override; procedure DoGetImageIndex(item: TCustomViewItem); override; procedure ImageListChanged; override; procedure InitWidget; override; function IsCustomDrawn: Boolean; override; function IsOwnerDrawn: Boolean; override; procedure Loaded; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property RootDirectory: WideString read FRootDir write SetRootDir; property Directory: WideString read GetDir write SetDir; property Align; property Anchors; property BorderStyle default bsSunken3d; property Color; property Constraints; property DragMode; property Enabled; property FileType: TFileType read FFileType write SetFileType default [ftDirectory, ftSystem]; property Font; property Height; property Hint; property Images; property ItemMargin; property Indent; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly default True; property ShowButtons; property ShowHint; property TabOrder; property TabStop; property Visible; property Width; property OnChange; property OnChanging; property OnClick; property OnCollapsed; property OnCollapsing; property OnContextPopup; property OnCustomDrawBranch; property OnCustomDrawItem; property OnDblClick; property OnDeletion; property OnDragDrop; property OnDragOver; property OnEdited; property OnEditing; property OnEndDrag; property OnEnter; property OnExit; property OnExpanding; property OnExpanded; property OnGetImageIndex; property OnGetSelectedIndex; property OnInsert; property OnItemClick; property OnItemDoubleClick; property OnItemEnter; property OnItemExitViewportEnter; property OnKeyDown; property OnKeyPress; property OnKeyString; property OnKeyUp; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnItemMouseDown; property OnViewPortMouseDown; end; TFilterComboBox = class(TCustomComboBox) private FFilter: string; MaskList: TStringList; FEditable: Boolean; function IsFilterStored: Boolean; function GetMask: WideString; procedure SetFilter(const NewFilter: string); procedure SetEditable(const Value: Boolean); protected procedure BuildList; procedure InitWidget; override; procedure Loaded; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ListMasks(List: TStrings); property Mask: WideString read GetMask; property Text; published property Anchors; property AutoComplete; property Color; property Constraints; property DragMode; property Editable: Boolean read FEditable write SetEditable default False; property Enabled; property Filter: string read FFilter write SetFilter stored IsFilterStored; property Font; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnChange; property OnClick; property OnCloseUp; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDropDown; property OnEndDrag; property OnEnter; property OnExit; property OnHighlighted; property OnKeyDown; property OnKeyPress; property OnKeyString; property OnKeyUp; property OnSelect; property OnStartDrag; end; TFileHistoryComboBox = class(TCustomComboBox) private FChanging: Boolean; FHistList: TStrings; FHistIndex: Integer; FIconProvider: TFileIconProvider; function GetFile(Index: Integer): PFileInfo; procedure UpdateItems; procedure CMKeyDown(var Msg: TCMKeyDown); message CM_KEYDOWN; protected procedure Click; override; procedure RemoveItem(Index: Integer); function DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState): Boolean; override; procedure InitWidget; override; procedure Loaded; override; procedure SaveWidgetState; override; procedure RestoreWidgetState; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Add(const Filename: string): Boolean; function CanGoBack: Boolean; function CanGoForward: Boolean; procedure Clear; procedure GoBack; procedure GoForward; property Files[Index: Integer]: PFileInfo read GetFile; property ItemIndex; published property Anchors; property AutoComplete; property Color default clBase; property Constraints; property DragMode; property DropDownCount; property Enabled; property Font; property ItemHeight; property MaxItems; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint default False; property Sorted; property Style; property TabOrder; property TabStop; property Visible; property OnChange; property OnClick; property OnCloseUp; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDropDown; property OnEndDrag; property OnEnter; property OnExit; property OnHighlighted; property OnKeyDown; property OnKeyPress; property OnKeyString; property OnKeyUp; property OnSelect; property OnStartDrag; end; TResizeType = (rtNone, rtHorz, rtVert, rtBoth); TPopupListBox = class(TCustomListBox) private FResizeType: TResizeType; FResized: Boolean; FDroppedUp: Boolean; function GetResizeType(P: TPoint): TResizeType; protected procedure InitWidget; override; function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; function WidgetFlags: Integer; override; public constructor CreateParented(ParentWidget: QWidgetH); end; TFileEditMode = (emDropDownList, emAutoComplete); TFileEdit = class(TCustomEdit, IDirectoryClient) private FDroppedDown: Boolean; FEditMode: TFileEditMode; FDirectory: TDirectory; FListedDir: WideString; FCurrentDir: WideString; FMatchCount: Integer; FDropDownCount: Integer; FListBox: TPopupListBox; FOriginalText: WideString; FPrefix: WideString; FOnDirChange: TDirectoryChangeEvent; FOnFileFound: TFileFoundEvent; FOnMaskChange: TMaskChangeEvent; function CheckNewDirectory(const Text: WideString): Boolean; procedure CMKeyDown(var Msg: TCMKeyDown); message CM_KEYDOWN; procedure ListMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); function MatchText: WideString; function PartialMatch(const Str: WideString): Integer; procedure ResizeListBox(ItemCount: Integer); procedure SetListIndex(Value: Integer); function GetCurrentDir: WideString; procedure SetDirectory(const Value: TDirectory); protected procedure CloseUp; procedure DropDown; procedure InitWidget; override; procedure KeyPress(var Key: Char); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure PopulateList(const Directory: WideString; Prefix: WideString = ''); virtual; procedure ReturnPressed(var Suppress: Boolean); override; { IDirectoryClient } function FileFound(const SearchRec: TSearchRec): Boolean; dynamic; procedure Loaded; override; procedure ListEnd; dynamic; function ListStart: Boolean; dynamic; procedure DirectoryChanged(const NewDir: WideString); dynamic; procedure MaskChange(const NewMask: WideString); dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property CurrentDir: WideString read GetCurrentDir; property DroppedDown: Boolean read FDroppedDown; published property Anchors; property AutoSize; property BorderStyle; property Color; property Constraints; property Directory: TDirectory read FDirectory write SetDirectory; property DragMode; property DropDownCount: Integer read FDropDownCount write FDropDownCount default 10; property EditMode: TFileEditMode read FEditMode write FEditMode default emDropDownList; property Enabled; property Font; property MaxLength; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint default False; property TabOrder; property TabStop; property Text; property Visible; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDirectoryChange: TDirectoryChangeEvent read FOnDirChange write FOnDirChange; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnFileFound: TFileFoundEvent read FOnFileFound write FOnFileFound; property OnKeyDown; property OnKeyPress; property OnKeyString; property OnKeyUp; property OnMaskChange: TMaskChangeEvent read FOnMaskChange write FOnMaskChange; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnReturnPressed; property OnStartDrag; end; TGetFileTypeProc = function(FileInfo: PFileInfo): string; function IconProvider16: TFileIconProvider; function IconProvider32: TFileIconProvider; function IconProvider48: TFileIconProvider; function ExpandDirectoryName(Directory: string): string; function IconPixels(const Size: TIconSize): Integer; function AllocFileInfo(SearchRec: TSearchRec): PFileInfo; function HasSubDirs(const Directory: WideString; IncludeHidden: Boolean = False): Boolean; function IsRelativePath(const Filename: string): Boolean; function IsDriveRoot(Text: string): Boolean; function GetFileType(Info: PFileInfo): string; var GetFileTypeProc: TGetFileTypeProc = GetFileType; FileIconProviderClass: TFileIconProviderClass = nil; const ThisDir = '.'; UpDir = '..'; {$IFDEF LINUX} AllMask = '*'; {$ENDIF} {$IFDEF MSWINDOWS} AllMask = '*.*'; {$ENDIF} implementation uses QForms, QMenus, QConsts, QDialogs; {$R *.res} {$IFDEF MSWINDOWS} function HasDrivePrefix(const Text: string): Boolean; begin Result := (Length(Text) > 1) and (Text[1] in ['a'..'z', 'A'..'Z']) and (Text[2] = DriveDelim); end; function GetDrive(const Text: string): string; begin if HasDrivePrefix(Text) then Result := Copy(Text, 1, 2); end; function AttributeString(Attr: Integer): string; begin Result := ''; if Attr and faReadOnly <> 0 then Result := Result + 'R'; { Do not localize } if Attr and faHidden <> 0 then Result := Result + 'H'; { Do not localize } if Attr and faSysFile <> 0 then Result := Result + 'S'; { Do not localize } if Attr and faArchive <> 0 then Result := Result + 'A'; { Do not localize } end; procedure CreateDriveInfo(Drive: string; var SR: TSearchRec); var shinf: SHFILEINFO; FreeSpace, TotalSize: Int64; OldErrorMode: Integer; begin OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try Drive := IncludeTrailingPathDelimiter(Drive); FillChar(SR, SizeOf(SR), 0); SR.Name := Drive; if SHGetFileInfo(PChar(Drive), 0, shinf, SizeOf(shinf), SHGFI_DISPLAYNAME) <> 0 then begin SR.Name := shinf.szDisplayName; SR.Attr := faVolumeID; if GetDiskFreeSpaceEx(PChar(Drive), FreeSpace, TotalSize, nil) then begin SR.Size := TotalSize div 1000000; SR.Time := FreeSpace div 1000000; end; end; StrLCopy(SR.FindData.cFileName, PChar(Drive), MAX_PATH); finally SetErrorMode(OldErrorMode); end; end; type TWindowsFileIconProvider = class(TFileIconProvider) private Reg: TRegistry; function AddIcon(IconFile: string; Index: Integer): Integer; protected function GetIconDataFromRegistry(const Key: string; var IconFile: string; var Index: Integer): Boolean; function DoGetImageIndex(Info: PFileInfo; const CurDir: string = ''): Integer; override; procedure Init; override; public constructor Create(Size: TIconSize); override; destructor Destroy; override; end; {$ENDIF} type PSearchRec = ^TSearchRec; const {$IFDEF MSWINDOWS} iiUnknownIcon = -1; iiNoIcon = -2; {$ENDIF} iiClosedFolder = 0; iiOpenFolder = 1; iiHiddenClosedFolder = 2; iiHiddenOpenFolder = 3; iiDefaultFile = 4; iiHiddenDefaultFile = 5; iiLinkOverlay = 6; LVLeftMargin = 3; ResourceNames: array[iiClosedFolder..iiLinkOverlay] of string = ( 'QFC_FLDCLOSED', 'QFC_FLDOPEN', 'QFC_HIDDENFLDCLOSED', 'QFC_HIDDENFLDOPEN', 'QFC_DEFFILE', 'QFC_HIDDENDEFFILE', 'QFC_LINK'); AttrWords: array[TFileAttr] of Word = (faReadOnly, faHidden, faSysFile, faVolumeID, faDirectory, faArchive, 0); var DirChangeList: TList = nil; GIconProvider16: TFileIconProvider = nil; GIconProvider32: TFileIconProvider = nil; GIconProvider48: TFileIconProvider = nil; IVSelectBmp: TBitmap = nil; procedure Error(const Msg: WideString); begin MessageDlg(SMsgDlgError, Msg, mtError, [mbOk], 0); end; function IconPixels(const Size: TIconSize): Integer; begin {$IFDEF LINUX} case Size of isSmall: Result := 16; isLarge: Result := 32; isVeryLarge: Result := 48; {$ENDIF} {$IFDEF MSWINDOWS} case Size of isSmall: Result := GetSystemMetrics(SM_CXSMICON); isLarge: Result := GetSystemMetrics(SM_CXICON); isVeryLarge: Result := GetSystemMetrics(SM_CXICON); {$ENDIF} else Result := 0; end; end; function IconProvider16: TFileIconProvider; begin if GIconProvider16 = nil then begin if not Assigned(FileIconProviderClass) then {$IFDEF MSWINDOWS} FileIconProviderClass := TWindowsFileIconProvider; {$ELSE} FileIconProviderClass := TFileIconProvider; {$ENDIF} GIconProvider16 := FileIconProviderClass.Create(isSmall); end; Result := GIconProvider16; end; function IconProvider32: TFileIconProvider; begin if GIconProvider32 = nil then begin if not Assigned(FileIconProviderClass) then {$IFDEF MSWINDOWS} FileIconProviderClass := TWindowsFileIconProvider; {$ELSE} FileIconProviderClass := TFileIconProvider; {$ENDIF} GIconProvider32 := FileIconProviderClass.Create(isLarge); end; Result := GIconProvider32; end; function IconProvider48: TFileIconProvider; begin if GIconProvider48 = nil then begin if not Assigned(FileIconProviderClass) then {$IFDEF MSWINDOWS} FileIconProviderClass := TWindowsFileIconProvider; {$ELSE} FileIconProviderClass := TFileIconProvider; {$ENDIF} GIconProvider48 := FileIconProviderClass.Create(isVeryLarge); end; Result := GIconProvider48; end; procedure AllocSelectBmp; begin if Assigned(IVSelectBmp) then Exit; IVSelectBmp := AllocPatternBitmap(clMask, clHighlight, 2, 2); IVSelectBmp.Mask(clMask); end; {$IFDEF LINUX} procedure DirChanged(SigNum : Integer; context: TSigContext); cdecl; export; var I: Integer; begin if SigNum = SIGIO then for I := 0 to DirChangeList.Count - 1 do begin if TDirectory(DirChangeList[I]).FDirHandle = context.ds then TDirectory(DirChangeList[I]).ListFiles; end; end; {$ENDIF} function AllocFileInfo(SearchRec: TSearchRec): PFileInfo; {$IFDEF LINUX} var statbuf: TStatBuf; FName: string; Ret: Integer; Buffer: array[0.._POSIX_PATH_MAX - 1] of Char; {$ENDIF} begin New(Result); FillChar(Result^, SizeOf(Result^), 0); Result^.SR := SearchRec; {$IFDEF LINUX} FName := SearchRec.PathOnly + SearchRec.Name; if stat(PChar(FName), statbuf) = 0 then Result^.stat := statbuf; if SearchRec.Attr and faSymLink <> 0 then begin Ret := readlink(PChar(FName), Buffer, SizeOf(Buffer)); if Ret > 0 then begin SetString(Result^.LinkTarget, Buffer, Ret); if IsRelativePath(Result^.LinkTarget) then Result^.LinkTarget := SearchRec.PathOnly + Result^.LinkTarget; Result^.LinkTarget := ExpandFileName(Result^.LinkTarget); end; end; {$ENDIF} Result^.ImageIndex := iiNoIcon; end; procedure DrawTruncatedText(Canvas: TCanvas; R: TRect; const Text: string; LeftJustify: Boolean = True; Wrap: Boolean = False); const Ellipsis = '...'; var Tmp: string; Width: Integer; I, L: Integer; Flags: Integer; TextRect: TRect; begin Flags := Integer(AlignmentFlags_AlignVCenter); TextRect := R; Width := TextRect.Right - TextRect.Left; if LeftJustify then Flags := Flags or Integer(AlignmentFlags_AlignLeft) else Flags := Flags or Integer(AlignmentFlags_AlignRight); if Wrap then Flags := Flags or Integer(AlignmentFlags_WordBreak); if not Wrap and (Canvas.TextWidth(Text) > Width) then begin I := 1; while Canvas.TextWidth(Tmp + Ellipsis) <= Width do begin if Text[I] in LeadBytes then begin L := StrCharLength(@Text[I]); Tmp := Tmp + Copy(Text, I, L); Inc(I, L); end else begin Tmp := Tmp + Text[I]; Inc(I); end; end; L := Length(Tmp); I := AnsiLastChar(Tmp) - PChar(Tmp); Delete(Tmp, I + 1, L - I); Tmp := Tmp + Ellipsis; end else Tmp := Text; Canvas.TextRect(R, R.Left, R.Top, Tmp, Flags); end; function IsRelativePath(const Filename: string): Boolean; begin Result := (Length(Filename) > 0) and not (Filename[1] in [PathDelim, '~', '$']) {$IFDEF MSWINDOWS} and (Length(Filename) > 1) and (Filename[2] <> DriveDelim); {$ENDIF} end; function ExpandDirectoryName(Directory: string): string; {$IFDEF LINUX} var wet: wordexp_t; PP: PPChar; I: Integer; {$ENDIF} begin {$IFDEF LINUX} if wordexp(PChar(Directory), wet, WRDE_NOCMD) = 0 then try PP := wet.we_wordv; Directory := ''; for I := 0 to wet.we_wordc - 1 do begin Directory := Directory + PP^; Inc(PP); if I < wet.we_wordc - 1 then Directory := Directory + ' '; end; finally wordfree(wet); end; {$ENDIF} if not IsDriveRoot(Directory) then Directory := ExpandFileName(Directory); { work around bug in ExpandFileName where /home/.. = '' instead of '/' } if Directory = '' then {$IFDEF LINUX} Directory := PathDelim; {$ENDIF} {$IFDEF MSWINDOWS} { Take whatever directory we are on } Directory := ExtractFileDrive(GetCurrentDir); {$ENDIF} Result := Directory; end; function HasSubDirs(const Directory: WideString; IncludeHidden: Boolean = False): Boolean; var Info: TSearchRec; DirAttr: Integer; begin Result := True; Exit; //This doesn't work due to a bug in FindFirst/FindNext which returns normal //files even though Attr = faDirectory only! Result := False; if Directory <> '' then begin DirAttr := faDirectory; if IncludeHidden then DirAttr := DirAttr + faHidden; if FindFirst(IncludeTrailingPathDelimiter(Directory) + '*', DirAttr, Info) = 0 then begin repeat { exclude normal files if ftNormal not set } // if (SearchRec.Attr and faDirectory <> 0) Result := (Info.Name <> '.') and (Info.Name <> '..'); until (FindNext(Info) <> 0) or Result; FindClose(Info); end; end; end; function GetFileType(Info: PFileInfo): string; begin Result := Info.Desc; if Result = '' then with Info.SR do begin {$IFDEF MSWINDOWS} if Attr and faVolumeID <> 0 then begin Result := SVolume; Exit; end; {$ENDIF} {$IFDEF LINUX} if Attr and faSymLink <> 0 then Result := SLinkTo; {$ENDIF} if Attr and faDirectory <> 0 then Result := Result + SDirectory else Result := Result + SFile; end; Info.Desc := Result; end; {$IFDEF LINUX} function PermissionString(Mode: __mode_t): string; function TestBit(Bit: Cardinal): Char; begin Result := '-'; if Mode and Bit = Bit then case Bit of S_IRUSR, S_IRGRP, S_IROTH: Result := 'r'; S_IWUSR, S_IWGRP, S_IWOTH: Result := 'w'; S_IXUSR, S_IXGRP, S_IXOTH: Result := 'x'; end; end; begin Result := ''; if Mode = 0 then begin Result := '???'; Exit; end else begin Result := Result + TestBit(S_IRUSR); Result := Result + TestBit(S_IWUSR); Result := Result + TestBit(S_IXUSR); Result := Result + TestBit(S_IRGRP); Result := Result + TestBit(S_IWGRP); Result := Result + TestBit(S_IXGRP); Result := Result + TestBit(S_IROTH); Result := Result + TestBit(S_IWOTH); Result := Result + TestBit(S_IXOTH); end; end; function UserName(uid: __uid_t): WideString; var PwdRec: PPasswordRecord; begin Result := '???'; PwdRec := getpwuid(uid); if Assigned(PwdRec) then Result := PwdRec^.pw_name; end; function GroupName(gid: __gid_t): WideString; var Group: PGroup; begin Result := '???'; Group := getgrgid(gid); if Assigned(Group) then Result := Group.gr_name; end; {$ENDIF} function IsDriveRoot(Text: string): Boolean; begin Text := IncludeTrailingPathDelimiter(Text); {$IFDEF LINUX} Result := Text = PathDelim; {$ENDIF} {$IFDEF MSWINDOWS} Result := HasDrivePrefix(Text) and (Length(Text) = 3); {$ENDIF} end; // obviously this isn't threadsafe but neither is CLX. var GSortDirection: TSortDirection = sdAscending; GSortMode: TSortMode = smName; function FileSort(Item1, Item2: Pointer): Integer; var FI1, FI2: PFileInfo; {$IFDEF MSWINDOWS} N1, N2: string; {$ENDIF} begin FI1 := PFileInfo(Item1); FI2 := PFileInfo(Item2); //directories always precede files. Result := (FI2.SR.Attr and faDirectory) - (FI1.SR.Attr and faDirectory); if Result = 0 then begin case GSortMode of smName: {$IFDEF MSWINDOWS} begin if FI1.SR.Attr and faVolumeID <> 0 then N1 := FI1.SR.FindData.cFileName else N1 := FI1.SR.Name; if FI2.SR.Attr and faVolumeID <> 0 then N2 := FI2.SR.FindData.cFileName else N2 := FI2.SR.Name; Result := AnsiCompareFileName(N1, N2); end; {$ENDIF} {$IFDEF LINUX} Result := AnsiCompareFileName(FI1.SR.Name, FI2.SR.Name); {$ENDIF} smSize: Result := FI2.SR.Size - FI1.SR.Size; smType: Result := AnsiCompareText(GetFileType(FI1), GetFileType(FI2)); smDate: Result := FI1.SR.Time - FI2.SR.Time; smAttributes: Result := {$IFDEF MSWINDOWS} FI2.SR.Attr - FI1.SR.Attr; {$ENDIF} {$IFDEF LINUX} FI2.stat.st_mode - FI1.stat.st_mode; smOwner: Result := AnsiCompareStr(UserName(FI1.stat.st_uid), UserName(FI2.stat.st_uid)); smGroup: Result := AnsiCompareStr(GroupName(FI1.stat.st_gid), GroupName(FI2.stat.st_gid)); {$ENDIF} end; if GSortDirection = sdDescending then Result := - Result; if (Result = 0) and (GSortMode <> smName) then Result := AnsiCompareFileName(FI1.SR.Name, FI2.SR.Name); end; end; function SortAscending(Files: TStringList; Index1, Index2: Integer): Integer; begin Result := AnsiCompareFileName(Files[Index1], Files[Index2]); end; function SortDescending(Files: TStringList; Index1, Index2: Integer): Integer; begin Result := -AnsiCompareFileName(Files[Index1], Files[Index2]); end; type TDirectoryNodeClient = class(TInterfacedObject, IDirectoryClient) private FNode: TDirectoryNode; protected { IDirectoryClient } function FileFound(const SearchRec: TSearchRec): Boolean; procedure ListEnd; function ListStart: Boolean; procedure DirectoryChanged(const NewDir: WideString); procedure MaskChange(const NewMask: WideString); public constructor Create(ANode: TTreeNode); end; { TDirectoryNodeClient } constructor TDirectoryNodeClient.Create(ANode: TTreeNode); begin inherited Create; FNode := TDirectoryNode(ANode); end; procedure TDirectoryNodeClient.DirectoryChanged(const NewDir: WideString); begin FNode.DirectoryChanged(NewDir); end; function TDirectoryNodeClient.FileFound(const SearchRec: TSearchRec): Boolean; begin Result := FNode.FileFound(SearchRec); end; procedure TDirectoryNodeClient.ListEnd; begin FNode.ListEnd; end; function TDirectoryNodeClient.ListStart: Boolean; begin Result := FNode.ListStart; end; procedure TDirectoryNodeClient.MaskChange(const NewMask: WideString); begin FNode.MaskChange(NewMask); end; { TDirectoryNode } constructor TDirectoryNode.Create(AOwner: TCustomViewItems; AParent: TCustomViewItem = nil; After: TCustomViewItem = nil); begin inherited Create(AOwner, AParent, After); FDirClient := TDirectoryNodeClient.Create(Self); FDirectory := TDirectory.Create(FDirClient); FDirectory.FIncludeParentDir := False; FDirectory.FFileType := TDirectoryTreeView(TTreeNodes(AOwner).Owner).FileType; end; destructor TDirectoryNode.Destroy; begin FDirectory.Free; inherited Destroy; end; procedure TDirectoryNode.DirectoryChanged(const NewDir: WideString); begin { stubbed } end; function TDirectoryNode.FileFound(const SearchRec: TSearchRec): Boolean; begin Result := True; end; procedure TDirectoryNode.ListEnd; var NewItem: TTreeNode; I: Integer; begin HasChildren := FDirectory.Count > 0; for I := 0 to FDirectory.Count - 1 do begin HasChildren := True; NewItem := Owner.AddChild(Self, FDirectory.Caption(I)); NewItem.Data := FDirectory.Files(I); NewItem.ImageIndex := 0; if (PFileInfo(NewItem.Data).SR.Attr and faDirectory <> 0) then NewItem.HasChildren := HasSubDirs(FDirectory.Location + FDirectory.Caption(I), ftHidden in FDirectory.FileType); QListViewItem_setPixmap(NewItem.Handle, NewItem.Index, TDirectoryTreeView(TreeView).FakePix); end; Owner.EndUpdate; end; function TDirectoryNode.ListStart: Boolean; begin Result := TreeView.HandleAllocated and not (csLoading in TreeView.ComponentState); if not Result then Exit; Owner.BeginUpdate; end; procedure TDirectoryNode.MaskChange(const NewMask: WideString); begin { stubbed } end; procedure TDirectoryNode.Populate; begin FDirectory.ListFiles; end; procedure TDirectoryNode.UpdateImages; begin if not Assigned(TDirectoryTreeView(TreeView).Images) then QListViewItem_setPixmap(Handle, Index, TDirectoryTreeView(TreeView).FakePix) else inherited UpdateImages; end; { TDirectoryTreeView } constructor TDirectoryTreeView.Create(AOwner: TComponent); begin inherited Create(AOwner); Items.SetNodeClass(TDirectoryNode); ReadOnly := True; FFileType := [ftDirectory, ftSystem]; FIconSize := isSmall; FakePix := QPixmap_create; QPixmap_resize(FakePix, IconPixels(FIconSize), IconPixels(FIconSize)); end; destructor TDirectoryTreeView.Destroy; begin QPixmap_destroy(FakePix); if (Items.Count > 0) and (Items[0].Data <> nil) then Dispose(PFileInfo(Items[0].Data)); inherited Destroy; end; procedure TDirectoryTreeView.DoGetImageIndex(item: TCustomViewItem); begin if not Assigned(Images) then with TTreeNode(Item) do ImageIndex := FIconProvider.DoGetImageIndex(PFileInfo(Data)) else inherited DoGetImageIndex(Item); end; function TDirectoryTreeView.IsOwnerDrawn: Boolean; begin Result := False; end; function TDirectoryTreeView.IsCustomDrawn: Boolean; begin Result := True; end; function TDirectoryTreeView.DoCustomDrawViewItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; var R: TRect; IL: TCustomImageList; Node: TDirectoryNode; begin Result := False; if Stage = cdPostPaint then Result := inherited DoCustomDrawViewItem(Item, Canvas, Rect, State, cdPrePaint); if Result then begin R := Rect; Canvas.FillRect(R); Node := TDirectoryNode(Item); with Node do begin if Assigned(Images) then IL := Images else IL := FIconProvider; Inc(R.Top, (R.Bottom - R.Top - Canvas.TextHeight('Pq')) div 2); IL.Draw(Canvas, R.Left, R.Top, ImageIndex); {$IFDEF LINUX} if (PFileInfo(Data).SR.Attr and faSymLink <> 0) and (IL = FIconProvider) then FIconProvider.DrawLinkOverlay(Canvas, R.Left, R.Top, PFileInfo(Data)); {$ENDIF} Inc(R.Left, IL.Width + 2); Inc(R.Right); DrawTruncatedText(Canvas, R, Text); end; end; if Stage = cdPostPaint then begin inherited DoCustomDrawViewItem(Item, Canvas, Rect, State, Stage); Result := False; end; end; procedure TDirectoryTreeView.AddDirectories(Node: TTreeNode); begin with TDirectoryNode(Node), PFileInfo(Node.Data)^ do begin {$IFDEF LINUX} FDirectory.Location := IncludeTrailingPathDelimiter(SR.PathOnly) + SR.Name; {$ENDIF} {$IFDEF MSWINDOWS} FDirectory.Location := GetAbsolutePath(Node); {$ENDIF} end; end; procedure TDirectoryTreeView.Change(Node: TTreeNode); begin if not FChanging and Assigned(Node) and not (csLoading in ComponentState) then begin FChanging := True; try if (Node <> nil) and (Node.Data <> nil) and (PFileInfo(Node.Data)^.SR.Attr and faDirectory = faDirectory) then FDir := GetAbsolutePath(Node); inherited Change(Node); finally FChanging := False; end; end; end; procedure TDirectoryTreeView.SetRootDir(const Value: WideString); var RootNode: TTreeNode; SR: TSearchRec; Tmp: string; DirAttr: Integer; FreeSR: Boolean; IsRootDir: Boolean; {$IFDEF MSWINDOWS} DriveBits: set of 0..25; DriveNum: Integer; {$ENDIF} begin {$IFDEF LINUX} if Value <> '' then {$ENDIF} begin Tmp := Value; FreeSR := False; if not (csLoading in ComponentState) then begin { Special case of root dir on Linux, and a base file system on windows } IsRootDir := IsDriveRoot(Tmp); if not IsRootDir and (Tmp <> '') then Tmp := ExcludeTrailingPathDelimiter(ExpandDirectoryName(Tmp)); DirAttr := faDirectory; if ftHidden in FFileType then DirAttr := DirAttr or faHidden; {$IFDEF MSWINDOWS} if Tmp <> '' then if IsRootDir then CreateDriveInfo(Tmp, SR) else {$ENDIF} if FindFirst(Tmp, DirAttr, SR) <> 0 then raise ESetDirectoryError.CreateFmt(SCannotReadDirectory, [Value]) else FreeSR := True; Items.BeginUpdate; FChanging := True; try Items.Clear; {$IFDEF MSWINDOWS} if Tmp <> '' then begin if IsRootDir then RootNode := Items.Add(nil, SR.Name) else {$ENDIF} RootNode := Items.Add(nil, Tmp); RootNode.Data := AllocFileInfo(SR); {$IFDEF MSWINDOWS} if not IsRootDir then {$ENDIF} RootNode.ImageIndex := 0; AddDirectories(RootNode); Selected := RootNode; {$IFDEF MSWINDOWS} end else begin Integer(DriveBits) := GetLogicalDrives; for DriveNum := 0 to 25 do begin if not (DriveNum in DriveBits) then Continue; CreateDriveInfo(Char(DriveNum + Ord('A')) + DriveDelim + PathDelim, SR); RootNode := Items.Add(nil, SR.Name); RootNode.Data := AllocFileInfo(SR); RootNode.HasChildren := True; end; end; {$ENDIF} finally FChanging := False; Items.EndUpdate; if FreeSR then FindClose(SR); end; end; FRootDir := Tmp; end; end; function TDirectoryTreeView.GetAbsolutePath(Node: TTreeNode): string; var Dir: WideString; begin Result := ''; if Assigned(Node) and Assigned(Node.Data) then with PFileInfo(Node.Data)^ do {$IFDEF LINUX} if SR.Name = PathDelim then Result := SR.Name else Result := IncludeTrailingPathDelimiter(SR.PathOnly) + SR.Name; {$ENDIF} {$IFDEF MSWINDOWS} while Node <> nil do with PFileInfo(Node.Data)^ do begin if SR.Attr and faVolumeID <> 0 then Dir := SR.FindData.cFileName else Dir := Node.Text; Result := IncludeTrailingPathDelimiter(Dir) + Result; Node := Node.Parent; end; {$ENDIF} end; procedure TDirectoryTreeView.SetDir(const Value: WideString); var StartDir, Tmp: string; Node, ParentNode: TTreeNode; I: Integer; IsSubDir: Boolean; SubDir: PChar; begin FChanging := True; IsSubDir := False; try if csLoading in ComponentState then FDir := Value else begin if Value <> '' then begin StartDir := Value; if Items.Count > 0 then begin Node := Items[0]; while Node <> nil do begin {$IFDEF MSWINDOWS} if PFileInfo(Node.Data).SR.Attr and faVolumeID <> 0 then Tmp := PFileInfo(Node.Data).SR.FindData.cFileName else {$ENDIF} Tmp := FRootDir; IsSubDir := SameFileName(Tmp, Copy(StartDir, 1, Length(Tmp))); if IsSubDir then begin System.Delete(StartDir, 1, Length(Tmp)); Break; end; Node := Node.GetNextSibling; end; if not IsSubDir then begin {$IFDEF MSWINDOWS} if FRootDir = '' then Tmp := SAnyKnownDrive; {$ENDIF} raise ESetDirectoryError.CreateFmt(SNotASubDir, [Value, Tmp]); end; for I := 1 to Length(StartDir) do if (StartDir[I] = PathDelim) then StartDir[I] := #0; StartDir := StartDir + #0; SubDir := PChar(StartDir); if (SubDir[0] = #0) and (Length(StartDir) > 0) then SubDir := @SubDir[1]; ParentNode := Node; while SubDir[0] <> #0 do begin Node := ParentNode.GetFirstChild; if Node = nil then begin AddDirectories(ParentNode); Node := ParentNode.GetFirstChild; end; while (Node <> nil) and (AnsiCompareFileName(Node.Text, SubDir) <> 0) do Node := Node.GetNextSibling; if Node = nil then Break else begin ParentNode.Expand(False); ParentNode := Node; end; SubDir := SubDir + StrLen(SubDir) + 1; end; Selected := ParentNode; Selected.MakeVisible; end; end else Selected := nil; end; finally FChanging := False; end; end; function TDirectoryTreeView.CanExpand(Node: TTreeNode): Boolean; begin Result := inherited CanExpand(Node); if Result and (Node.Count = 0) then AddDirectories(Node); end; function TDirectoryTreeView.GetDir: WideString; begin if Selected <> nil then Result := GetAbsolutePath(Selected) else Result := ''; end; procedure TDirectoryTreeView.Loaded; begin inherited Loaded; SetRootDir(FRootDir); SetDir(FDir); SetFileType(FFileType); end; procedure TDirectoryTreeView.SetFileType(const Value: TFileType); var CurDir: WideString; begin FFileType := Value; if not (csLoading in ComponentState) then begin CurDir := GetDir; SetRootDir(FRootDir); SetDir(CurDir); end; end; procedure TDirectoryTreeView.ImageListChanged; begin if Images <> nil then QPixmap_resize(FakePix, Images.Width, Images.Height); inherited ImageListChanged; end; procedure TDirectoryTreeView.InitWidget; begin inherited InitWidget; FIconProvider := IconProvider16; {$IFDEF LINUX} RootDirectory := '$HOME'; {$ELSE} RootDirectory := FRootDir; {$ENDIF} end; type TFileListItemEditor = class(TViewItemEditor) procedure EditFinished(Accepted: Boolean); override; end; TViewItemCracker = class(TCustomViewItem); function TDirectoryTreeView.DoCustomHint(var HintInfo: THintInfo): Boolean; var Node: TTreeNode; Pos: TPoint; TextRect, BRect: TRect; begin Pos := ScreenToClient(Mouse.CursorPos); Node := GetNodeAt(Pos.X, Pos.Y); Result := Node <> nil; if Result then begin TextRect := Node.TextRect; BRect := TextRect; Canvas.TextExtent(Node.Text, BRect, Integer(AlignmentFlags_AlignLeft) or Integer(AlignmentFlags_SingleLine)); if Assigned(FIconProvider) then OffsetRect(BRect, FIconProvider.Width, 0); Result := (BRect.Right > ClientWidth) or (BRect.Left < 0); if Result then HintInfo.HintStr := Node.Text; end; end; { TFileListItemEditor } procedure TFileListItemEditor.EditFinished(Accepted: Boolean); begin Accepted := Accepted and (Text <> ''); inherited EditFinished(Accepted); if TFileListView(ViewControl).FCreatingDir and not TFileListView(ViewControl).FCreatedDir then begin if Accepted then Error(Format(SCannotCreateDirName, [TViewItemCracker(Item).Caption])); Item.Free; end; TFileListView(ViewControl).FCreatingDir := False; ViewControl.Repaint; end; { TFileListView } constructor TFileListView.Create(AOwner: TComponent); begin inherited Create(AOwner); ReadOnly := True; FDirectory := TDirectory.Create(Self); FIconProvider := IconProvider16; {$IFDEF LINUX} FDirectory.Location := GetCurrentDir; {$ENDIF} {$IFDEF MSWINDOWS} FDrivesListed := False; {$ENDIF} end; procedure TFileListView.DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean); begin AllowEdit := ((TListItem(AItem).Data <> nil) and (PFileInfo(TListItem(AItem).Data).SR.Name <> UpDir)) or FCreatingDir; inherited DoEditing(AItem, AllowEdit); end; procedure TFileListView.DoGetImageIndex(item: TCustomViewItem); begin if not Assigned(Images) then with TListItem(Item) do ImageIndex := FIconProvider.DoGetImageIndex(TListItem(Item).Data) else inherited DoGetImageIndex(Item); end; procedure TFileListView.ListEnd; var I: Integer; MaxW, ThisW, ImageW: Integer; NewItem: TListItem; begin try {$IFDEF MSWINDOWS} FDrivesListed := Directory.Location = ''; {$ENDIF} MaxW := 0; for I := 0 to FDirectory.Count - 1 do begin NewItem := Items.Add; NewItem.Data := FDirectory.Files(I); NewItem.Caption := FDirectory.Caption(I); NewItem.ImageIndex := 0; if ViewStyle = vsList then begin ThisW := Canvas.TextWidth(NewItem.Caption); if ThisW > MaxW then MaxW := ThisW; end; end; if ViewStyle = vsList then begin {TODO: investigate listview problem where vsList still pays attention to first column's width} if not Assigned(Images) then ImageW := FIconProvider.Width else ImageW := Images.Width; QListView_setColumnWidth(Handle, QHeader_mapToIndex(QListView_header(Handle), 0), MaxW + ImageW + 3); end; {$IFDEF MSWINDOWS} if ViewStyle = vsReport then for I := 0 to Columns.Count - 1 do if Columns[I].Tag = Integer(flcDate) then if FDrivesListed then Columns[I].Caption := SFreeSpace else Columns[I].Caption := SDate; {$ENDIF} finally Screen.Cursor := FSaveCursor; Items.EndUpdate; end; end; function TFileListView.ListStart: Boolean; begin {$IFDEF MSWINDOWS} FDrivesListed := Directory.Location = ''; {$ENDIF} Result := HandleAllocated and not (csLoading in ComponentState); if Result then begin Items.BeginUpdate; Application.CancelHint; FSaveCursor := Screen.Cursor; Screen.Cursor := crHourglass; Items.Clear; end; end; procedure TFileListView.ImageChange; begin FDirectory.ListFiles(False); UpdateControl; end; const FLVColTitles: array[TFileListColumn] of string = ( SName, SSize, SType, SDate, SAttributes {$IFDEF LINUX}, SOwner, SGroup {$ENDIF}); procedure TFileListView.InitWidget; var CType: TFileListColumn; Column: TListColumn; begin inherited InitWidget; FIconProvider := IconProvider16; if (Columns.Count = 0) then begin for CType := Low(TFileListColumn) to High(TFileListColumn) do begin Column := Columns.Add; Column.Tag := Ord(CType); Column.Caption := FLVColTitles[CType]; if CType = flcSize then Column.Alignment := taRightJustify; case CType of flcName: Column.Width := 150; flcSize: Column.Width := Canvas.TextWidth('0000000'); flcType: Column.Width := Canvas.TextWidth(SDirectory); flcDate: Column.Width := Canvas.TextWidth(DateTimeToStr(Now)); flcAttributes: Column.Width := Canvas.TextWidth(SAttributes); {$IFDEF LINUX} flcOwner: Column.Width := Canvas.TextWidth(SOwner); flcGroup: Column.Width := Canvas.TextWidth(SGroup); {$ENDIF} end; Column.Width := Column.Width + Canvas.TextWidth('A'); end; end; Sorted := False; Refresh; end; procedure TFileListView.Loaded; begin inherited Loaded; Refresh; end; function TFileListView.DoCustomDrawViewItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; var R: TRect; IL: TCustomImageList; ListItem: TListItem; begin Result := False; if Stage = cdPostPaint then Result := inherited DoCustomDrawViewItem(Item, Canvas, Rect, State, cdPrePaint); if Result then begin R := Rect; Canvas.FillRect(R); ListItem := TListItem(Item); with ListItem do begin if Assigned(Images) then IL := Images else IL := FIconProvider; Inc(R.Top, (R.Bottom - R.Top - IL.Height) div 2); IL.Draw(Canvas, R.Left, R.Top, ImageIndex); {$IFDEF LINUX} if (Data <> nil) and (PFileInfo(Data).SR.Attr and faSymLink <> 0) and (IL = FIconProvider) then FIconProvider.DrawLinkOverlay(Canvas, R.Left, R.Top, PFileInfo(Data)); {$ENDIF} Inc(R.Left, IL.Width + 2); if (Data <> nil) and (EditingItem <> Item) then DrawTruncatedText(Canvas, R, PFileInfo(Data).SR.Name) else Result := True; end; end; if Stage = cdPostPaint then begin inherited DoCustomDrawViewItem(Item, Canvas, Rect, State, Stage); Result := False; end; end; function TFileListView.DoCustomDrawViewSubItem(Item: TCustomViewItem; SubItem: Integer; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; var R: TRect; Txt: string; FileInfo: PFileInfo; Col: TFileListColumn; begin Result := False; if Stage = cdPostPaint then Result := inherited DoCustomDrawViewSubItem(Item, SubItem, Canvas, Rect, State, cdPrePaint); if Result then begin R := Rect; if not RowSelect then begin Canvas.Brush.Color := Color; Canvas.Font.Color := clWindowText; end; InflateRect(R, -3, 0); if TListItem(Item).Data = nil then Exit; FileInfo := PFileInfo(TListItem(Item).Data); Col := TFileListColumn(SubItem); if FileInfo <> nil then begin case Col of flcSize: {$IFDEF MSWINDOWS} if FDrivesListed then Txt := Format(SMegs, [FileInfo.SR.Time]) else {$ENDIF} Txt := IntToStr(FileInfo.SR.Size); flcDate: {$IFDEF MSWINDOWS} if FDrivesListed then Txt := Format(SMegs, [FileInfo.SR.Size]) else {$ENDIF} Txt := DateTimeToStr(FileDateToDateTime(FileInfo.SR.Time)); flcType: Txt := GetFileTypeProc(FileInfo); flcAttributes: {$IFDEF MSWINDOWS} Txt := AttributeString(FileInfo.SR.Attr); {$ENDIF} {$IFDEF LINUX} Txt := PermissionString(FileInfo.stat.st_mode); flcOwner: Txt := UserName(FileInfo.stat.st_uid); flcGroup: Txt := GroupName(FileInfo.stat.st_gid); {$ENDIF} else Txt := '???'; // do not localize end; end else Txt := ''; Canvas.FillRect(Rect); DrawTruncatedText(Canvas, R, Txt, Col <> flcSize); end; if Stage = cdPostPaint then begin inherited DoCustomDrawViewSubItem(Item, SubItem, Canvas, Rect, State, Stage); Result := False; end; end; function TFileListView.IsOwnerDrawn: Boolean; begin Result := False; end; function TFileListView.IsCustomDrawn: Boolean; begin Result := True; end; procedure TFileListView.KeyPress(var Key: Char); begin inherited KeyPress(Key); if not IsEditing then case Key of #8: GoUp; #13: GoDown; end; end; procedure TFileListView.GoUp; var NewDir: WideString; begin {$IFDEF MSWINDOWS} if Directory.Location = '' then Exit; if IsDriveRoot(Directory.Location) then NewDir := '' else {$ENDIF} NewDir := ExpandDirectoryName(IncludeTrailingPathDelimiter(Directory.Location) + '..'); if NewDir <> Directory.Location then Directory.Location := NewDir; end; procedure TFileListView.DblClick; begin inherited DblClick; if (Selected <> nil) and (FDirectory.Files(Selected.Index).SR.Attr and faDirectory <> 0) and (Selected.Caption = '..') then GoUp else GoDown; end; procedure TFileListView.GoDown; begin if (Selected <> nil) then begin if (PFileInfo(Selected.Data)^.SR.Attr and faDirectory <> 0) then {$IFDEF LINUX} Directory.Location := FDirectory.LinkName(Selected.Index); {$ENDIF} {$IFDEF MSWINDOWS} Directory.Location := Directory.Location + PathDelim + Selected.Caption else if PFileInfo(Selected.Data)^.SR.Attr and faVolumeID <> 0 then Directory.Location := PFileInfo(Selected.Data)^.SR.FindData.cFileName; {$ENDIF}; end; end; function TFileListView.GetSelections: TFileInfos; var I: Integer; begin { Do NOT free the returned pointers - they're live. } for I := 0 to Items.Count - 1 do if Items[I].Selected then begin SetLength(Result, Length(Result) + 1); Result[Length(Result)-1] := FDirectory.Files(I); end; end; destructor TFileListView.Destroy; begin FDirectory.Free; inherited Destroy; end; function TFileListView.NeedKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; function IsNavKey: Boolean; begin Result := (Key = Key_Left) or (Key = Key_Right) or (Key = Key_Down) or (Key = Key_Up) or (Key = Key_Home) or (Key = Key_End) or (Key = Key_PageUp) or (Key = Key_PageDown); end; begin Result := inherited NeedKey(Key, Shift, KeyText); if not Result then Result := (isNavKey and (ssShift in Shift)) or (((Key = Key_Enter) or (Key = Key_Return)) and ((Selected <> nil) and (PFileInfo(Selected.Data).SR.Attr and faDirectory <> 0))); end; //TODO: issue - TListItems.FindItem is protected. procedure TFileListView.ColumnClicked(Column: TListColumn); begin if FDirectory.SortMode = TSortMode(Column.Tag + 1) then begin if FDirectory.SortDirection = sdAscending then FDirectory.SortDirection := sdDescending else FDirectory.SortDirection := sdAscending; end else FDirectory.SortMode := TSortMode(Column.Tag + 1); inherited ColumnClicked(Column); end; procedure TFileListView.CreateDirectory(const DefaultName: WideString); begin if ReadOnly then Exit; FCreatingDir := True; FCreatedDir := False; SetFocus; with Items.Add do begin Caption := FDirectory.UniqueName(DefaultName); Selected := True; EditText; end; end; procedure TFileListView.DoEdited(AItem: TCustomViewItem; var S: WideString); var NewDir: PFileInfo; begin if FCreatingDir then begin NewDir := FDirectory.CreateDirectory(S); FCreatedDir := NewDir <> nil; if FCreatedDir then TListItem(AItem).Data := NewDir; end else if RenameFile(TListItem(AItem), S) < 0 then S := PFileInfo(TListItem(AItem).Data).SR.Name; inherited DoEdited(AItem, S); end; function TFileListView.DeleteFile(const Filename: WideString): Integer; begin Result := FDirectory.Delete(Filename); if Result = RESULT_OK then Refresh; end; function TFileListView.RenameFile(Item: TListItem; const NewName: WideString): Integer; begin Result := 0; if (NewName = '') or (AnsiCompareFileName(Item.Caption, NewName) = 0) then Exit; Result := FDirectory.Rename(Item.Data, NewName); case Result of RESULT_ACCESS_DENIED: Error(Format(SAccessDeniedTo, [Item.Caption])); RESULT_FILE_NOT_FOUND: Error(Format(SFileNameNotFound, [Item.Caption])); RESULT_ALREADY_EXISTS: Error(SAlreadyExists); else if (PFileInfo(Result).SR.Attr and faHidden <> 0) and not (ftHidden in FDirectory.FileType) then Item.Delete else begin Item.Data := Pointer(Result); Item.Caption := NewName; InvalidateRect(Item.DisplayRect, True); end; end; end; procedure TFileListView.PositionEditor(var NewLeft, NewTop: Integer); begin if Assigned(Images) then NewLeft := NewLeft + Images.Width else NewLeft := NewLeft + IconPixels(isSmall); end; procedure TFileListView.DirectoryChanged(const NewDir: WideString); begin if Items.Count > 0 then TopItem := Items[0]; if Assigned(FOnDirChange) then FOnDirChange(Self, NewDir); end; function TFileListView.FileFound(const SearchRec: TSearchRec): Boolean; begin Result := True; if Assigned(FOnFileFound) then FOnFileFound(Self, SearchRec, Result); end; procedure TFileListView.MaskChange(const NewMask: WideString); begin if Assigned(FOnMaskChange) then FOnMaskChange(Self, NewMask); end; procedure TFileListView.SetDirectory(const Value: TDirectory); begin FDirectory.Assign(Value); end; function TFileListView.CreateEditor: TItemEditor; begin Result := TFileListItemEditor.Create(Self); end; procedure TFileListView.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); if Key = Key_F5 then Refresh; end; procedure TFileListView.Refresh; begin FDirectory.ListFiles(True); end; function TFileListView.DoCustomHint(var HintInfo: THintInfo): Boolean; var Info: PFileInfo; TextRect: TRect; BRect: TRect; IL: TCustomImageList; Item: TListItem; Pos: TPoint; begin Pos := ScreenToClient(Mouse.CursorPos); Item := GetItemAt(Pos.X, Pos.Y); Result := Item <> nil; if Result then begin Info := PFileInfo(Item.Data); if Info <> nil then begin TextRect := Item.DisplayRect; if Assigned(Images) then IL := Images else IL := FIconProvider; Dec(TextRect.Right, IL.Width); BRect := TextRect; Canvas.TextExtent(Item.Caption, BRect, Integer(AlignmentFlags_AlignHCenter) or Integer(AlignmentFlags_WordBreak)); if ((BRect.Right - BRect.Left) > (TextRect.Right - TextRect.Left)) or ((BRect.Bottom - BRect.Top) > (TextRect.Bottom - TextRect.Top)) then begin {$IFDEF MSWINDOWS} if FDrivesListed then HintInfo.HintStr := Format('%s'#10'%s: %s'#10'%s: %s'#10'%s: %s', [Item.Caption, SType, GetFileTypeProc(Info), SFreeSpace, Format(SMegs, [Info.SR.Time]), SSize, Format(SMegs, [Info.SR.Size])]) else {$ENDIF} HintInfo.HintStr := Format('%s'#10'%s: %s'#10'%s: %s'#10'%s: %d', [Item.Caption, SType, GetFileTypeProc(Info), SDate, DateTimeToStr(FileDateToDateTime(Info.SR.Time)), SSize, Info.SR.Size]) end else begin {$IFDEF MSWINDOWS} if FDrivesListed then HintInfo.HintStr := Format('%s: %s'#10'%s: %s'#10'%s: %s', [SType, GetFileTypeProc(Info), SFreeSpace, Format(SMegs, [Info.SR.Time]), SSize, Format(SMegs, [Info.SR.Size])]) else {$ENDIF} HintInfo.HintStr := Format('%s: %s'#10'%s: %s'#10'%s: %d', [SType, GetFileTypeProc(Info), SDate, DateTimeToStr(FileDateToDateTime(Info.SR.Time)), SSize, Info.SR.Size]); end; HintInfo.ReshowTimeout := MaxInt; end; end; end; procedure TFileListView.ImageListChanged; begin Items.BeginUpdate; try ImageChange; finally Items.EndUpdate; end; end; { TFileIconProvider } constructor TFileIconProvider.Create(Size: TIconSize); begin FIconSize := Size; FIndexes := TStringHash.Create(512); CreateSize(IconPixels(FIconSize), IconPixels(FIconSize)); Init; end; destructor TFileIconProvider.Destroy; begin FIndexes.Free; inherited; end; procedure TFileIconProvider.Clear; begin inherited Clear; FIndexes.Clear; Init; end; function TFileIconProvider.DoGetImageIndex(Info: PFileInfo; const CurDir: string = ''): Integer; begin if Info <> nil then begin with Info.SR do begin if (Attr and faDirectory) <> 0 then begin if (Attr and faHidden) <> 0 then Result := iiHiddenClosedFolder else Result := iiClosedFolder; end else begin if (Attr and faHidden) <> 0 then Result := iiHiddenDefaultFile else Result := iiDefaultFile; end; end end else Result := iiClosedFolder; end; procedure TFileIconProvider.DrawLinkOverlay(Canvas: TCanvas; X, Y: Integer; Info: PFileInfo); begin Draw(Canvas, X, Y, iiLinkOverlay, itImage); end; procedure TFileIconProvider.Init; var B: TBitmap; I: Integer; begin B := TBitmap.Create; try for I := iiClosedFolder to iiHiddenDefaultFile do begin B.LoadFromResourceName(hInstance, ResourceNames[I]+IntToStr(IconPixels(FIconSize))); AddMasked(B, clDefault); end; B.LoadFromResourceName(hInstance, ResourceNames[iiLinkOverlay]+IntToStr(IconPixels(FIconSize))); AddMasked(B, clBlack); finally B.Free; end; end; {$IFDEF MSWINDOWS} // -1 => no icon available // -2 => not tried yet // 0 and above = index of image in imagelist constructor TWindowsFileIconProvider.Create(Size: TIconSize); begin inherited Create(Size); Reg := TRegistry.Create; end; destructor TWindowsFileIconProvider.Destroy; begin Reg.Free; inherited Destroy; end; function TWindowsFileIconProvider.AddIcon(IconFile: string; Index: Integer): Integer; var Large, Small: HICON; nIcons: Integer; B: TBitmap; begin Result := iiUnknownIcon; nIcons := ExtractIconEx(PChar(IconFile), Index, Large, Small, 1); if nIcons > 0 then begin B := TBitmap.Create; try B.Width := Width; B.Height := Height; B.Canvas.Start; case FIconSize of isSmall: DrawIconEx(QPainter_handle(B.Canvas.Handle), 0, 0, Small, B.Width, B.Height, 0, 0, DI_NORMAL); isLarge, isVeryLarge: DrawIconEx(QPainter_handle(B.Canvas.Handle), 0, 0, Large, B.Width, B.Height, 0, 0, DI_NORMAL); end; B.Canvas.Stop; Result := AddMasked(B, clDefault); finally B.Free; end; end; end; function TWindowsFileIconProvider.DoGetImageIndex(Info: PFileInfo; const CurDir: string = ''): Integer; var Key: string; Dir: string; IconFile: string; IconIndex: Integer; shinf: SHFILEINFO; begin Result := iiUnknownIcon; if Info = nil then Exit; if Info.ImageIndex = iiNoIcon then begin if Info.SR.Attr and faVolumeID <> 0 then begin Key := Info.SR.FindData.cFileName; Info.ImageIndex := FIndexes.ValueOf(Key); if Info.ImageIndex > -1 then Exit else if (Info.ImageIndex = iiUnknownIcon) and (SHGetFileInfo(PChar(Key), 0, shinf, SizeOf(shinf), SHGFI_ICONLOCATION) <> 0) then begin Info.ImageIndex := AddIcon(shinf.szDisplayName, shinf.iIcon); FIndexes.Add(Key, Info.ImageIndex); Exit; end; end; if Info.SR.Attr and faDirectory <> 0 then begin Info.ImageIndex := iiClosedFolder; end else begin Key := ExtractFileExt(Info.SR.Name); if (Key = '') or (AnsiLowerCase(Key) = '.exe') then Key := IncludeTrailingPathDelimiter(CurDir) + Info.SR.Name; Info.ImageIndex := FIndexes.ValueOf(Key); if Info.ImageIndex = iiUnknownIcon then begin if GetIconDataFromRegistry(Key, IconFile, IconIndex) then begin Info.ImageIndex := AddIcon(IconFile, IconIndex); FIndexes.Add(Key, Info.ImageIndex); end else begin Info.ImageIndex := AddIcon(Key, 0); if Info.ImageIndex >= 0 then FIndexes.Add(Key, Info.ImageIndex) else Info.ImageIndex := inherited DoGetImageIndex(Info, Dir); end; end; end; end; Result := Info.ImageIndex; end; procedure TWindowsFileIconProvider.Init; const ShellIndexMap: array[iiClosedFolder..iiHiddenDefaultFile] of Integer = ( 3, 4, 3, 4, 0, 0); var I: Integer; begin for I := iiClosedFolder to iiHiddenDefaultFile do AddIcon('shell32.dll', ShellIndexMap[I]); end; function TWindowsFileIconProvider.GetIconDataFromRegistry(const Key: string; var IconFile: string; var Index: Integer): Boolean; var S: string; P: Integer; begin Reg.RootKey := HKEY_CLASSES_ROOT; Result := Reg.OpenKeyReadOnly(Key); if Result then try S := Reg.ReadString(''); Reg.CloseKey; Reg.RootKey := HKEY_CLASSES_ROOT; Result := Reg.OpenKeyReadOnly(s + '\DefaultIcon'); if Result then begin S := Reg.ReadString(''); P := Pos(',', S); if P > 0 then begin IconFile := Copy(S, 1, P-1); Index := StrToInt(Copy(S, P+1, Length(S))); end else Result := False; end; finally Reg.CloseKey; end; end; {$ENDIF} { TFilterComboBox } constructor TFilterComboBox.Create(AOwner: TComponent); begin inherited Create(AOwner); Style := csDropDownList; FFilter := SDefaultFilter; MaskList := TStringList.Create; FEditable := False; end; destructor TFilterComboBox.Destroy; begin MaskList.Free; inherited Destroy; end; function TFilterComboBox.IsFilterStored: Boolean; begin Result := SDefaultFilter <> FFilter; end; procedure TFilterComboBox.SetFilter(const NewFilter: string); begin if AnsiCompareFileName(NewFilter, FFilter) <> 0 then begin FFilter := NewFilter; if HandleAllocated then BuildList; Change; end; end; procedure TFilterComboBox.ListMasks(List: TStrings); var SaveDelim: Char; begin List.Clear; SaveDelim := List.Delimiter; try List.Delimiter := ';'; List.DelimitedText := MaskList.Text; finally List.Delimiter := SaveDelim; end; end; function TFilterComboBox.GetMask: WideString; begin if ItemIndex < 0 then ItemIndex := Items.Count - 1; if (ItemIndex >= 0) and (MaskList.Count > 0) then begin Result := MaskList[ItemIndex]; end else Result := AllMask; end; procedure TFilterComboBox.BuildList; var AFilter, MaskName, Mask: string; BarPos: Integer; begin Clear; MaskList.Clear; AFilter := Filter; BarPos := AnsiPos('|', AFilter); while BarPos <> 0 do begin MaskName := Copy(AFilter, 1, BarPos - 1); Delete(AFilter, 1, BarPos); BarPos := AnsiPos('|', AFilter); if BarPos > 0 then begin Mask := Copy(AFilter, 1, BarPos - 1); Delete(AFilter, 1, BarPos); end else begin Mask := AFilter; AFilter := ''; end; Items.Add(MaskName); MaskList.Add(Mask); BarPos := AnsiPos('|', AFilter); end; ItemIndex := 0; end; procedure TFilterComboBox.Loaded; begin inherited Loaded; BuildList; end; procedure TFilterComboBox.SetEditable(const Value: Boolean); const Styles: array[Boolean] of TComboBoxStyle = (csDropDownList, csDropDown); begin if FEditable <> Value then begin FEditable := Value; Style := Styles[FEditable]; end; end; procedure TFilterComboBox.InitWidget; begin inherited InitWidget; BuildList; end; { TFileHistoryComboBox } function TFileHistoryComboBox.Add(const Filename: string): Boolean; var Info: PFileInfo; SR: TSearchRec; Error: Integer; NewItem: string; I: Integer; begin Result := False; if FChanging or (csLoading in ComponentState) then Exit; if Filename <> PathDelim then NewItem := ExcludeTrailingPathDelimiter(ExpandDirectoryName(Filename)) else NewItem := Filename; for I := FHistIndex - 1 downto 0 do begin if FHistList.Objects[I] <> nil then Dispose(PFileInfo(FHistList.Objects[I])); FHistList.Delete(I); end; if IsDriveRoot(FileName) then begin FillChar(SR, SizeOf(SR), 0); SR.Name := PathDelim; SR.Attr := faDirectory; Info := AllocFileInfo(SR); end else begin Error := FindFirst(NewItem, faAnyFile, SR); try if Error = 0 then Info := AllocFileInfo(SR) else begin Info := nil; raise EInOutError.CreateFmt(SFilenameNotFound, [Filename]); end; finally FindClose(SR); end; end; if Info <> nil then begin Result := True; I := FHistList.IndexOf(NewItem); FHistList.InsertObject(0, NewItem, TObject(Info)); if I >= 0 then FHistList.Delete(I+1); Text := NewItem; FHistIndex := 0; UpdateItems; end; end; function TFileHistoryComboBox.CanGoBack: Boolean; begin Result := FHistIndex < FHistList.Count - 1; end; function TFileHistoryComboBox.CanGoForward: Boolean; begin Result := FHistIndex > 0; end; procedure TFileHistoryComboBox.Clear; var I: Integer; begin Items.Clear; for I := 0 to FHistList.Count - 1 do Dispose(PFileInfo(FHistList.Objects[I])); FHistList.Clear; FHistIndex := -1; Text := ''; end; procedure TFileHistoryComboBox.Click; begin FChanging := True; try if (ItemIndex >= 0) and (ItemIndex < Items.Count) then begin FHistIndex := ItemIndex; // FileInfo := PFileInfo(Items.Objects[ItemIndex]); // if FileInfo = nil then // raise Exception.CreateFmt('"%s" cannot be read.', [Items[ItemIndex]]); inherited Click; end; finally FChanging := False; end; end; procedure TFileHistoryComboBox.CMKeyDown(var Msg: TCMKeyDown); begin Msg.Handled := (Msg.Key = Key_Return) or (Msg.Key = Key_Enter); if Msg.Handled then try Add(Text); Click; except on EInOutError do begin if Items.Count > 0 then Text := Items[0]; raise; end; end else inherited; end; procedure TFileHistoryComboBox.UpdateItems; var I: Integer; begin Items.Clear; for I := 0 to FHistList.Count - 1 do Items.AddObject(FHistList[I], FHistList.Objects[I]); ItemIndex := FHistIndex; if ItemIndex >= 0 then Text := Items[FHistIndex]; end; constructor TFileHistoryComboBox.Create(AOwner: TComponent); begin inherited Create(AOwner); FHistList := TStringList.Create; FHistIndex := -1; end; destructor TFileHistoryComboBox.Destroy; begin Clear; FHistList.Free; inherited Destroy; end; function TFileHistoryComboBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState): Boolean; var FileInfo: PFileInfo; ImageIndex: Integer; R: TRect; begin Result := True; R := Rect; if odSelected in State then begin Canvas.Font.Color := clHighlightText; Canvas.Brush.Color := clHighlight; end else begin Canvas.Font.Color := Font.Color; Canvas.Brush.Color := Color; end; Rect.Right := Width; Canvas.FillRect(R); if (Index > -1) and (Index < Items.Count) then begin Inc(R.Top, (R.Bottom - R.Top - Canvas.TextHeight('Pq')) div 2); FileInfo := PFileInfo(Items.Objects[Index]); if FileInfo <> nil then begin ImageIndex := FIconProvider.DoGetImageIndex(FileInfo); Inc(R.Left, 2); FIconProvider.Draw(Canvas, R.Left, R.Top, ImageIndex); {$IFDEF LINUX} if FileInfo.SR.Attr and faSymLink <> 0 then FIconProvider.DrawLinkOverlay(Canvas, R.Left, R.Top, FileInfo); {$ENDIF} Inc(R.Left, FIconProvider.Width + 2); end; Canvas.TextRect(R, R.Left, R.Top, Items[Index]); end; inherited DrawItem(Index, Rect, State); end; function TFileHistoryComboBox.GetFile(Index: Integer): PFileInfo; begin Result := PFileInfo(Items.Objects[Index]); end; procedure TFileHistoryComboBox.GoBack; begin if CanGoBack then begin Inc(FHistIndex); UpdateItems; //ItemIndex := ItemIndex + 1; Click; end; end; procedure TFileHistoryComboBox.GoForward; begin if CanGoForward then begin Dec(FHistIndex); // ItemIndex := ItemIndex - 1; UpdateItems; Click; end; end; procedure TFileHistoryComboBox.InitWidget; begin inherited InitWidget; MaxItems := 16; InsertMode := ciNone; end; procedure TFileHistoryComboBox.Loaded; begin inherited Loaded; FIconProvider := IconProvider16; end; procedure TFileHistoryComboBox.RemoveItem(Index: Integer); begin Dispose(PFileInfo(Items.Objects[Index])); Items.Delete(Index); end; procedure TFileHistoryComboBox.RestoreWidgetState; begin inherited RestoreWidgetState; UpdateItems; end; procedure TFileHistoryComboBox.SaveWidgetState; begin inherited SaveWidgetState; end; function FileEditSort(List: TStringList; Item1, Item2: Integer): Integer; var FI1, FI2: PFileInfo; begin FI1 := PFileInfo(List.Objects[Item1]); FI2 := PFileInfo(List.Objects[Item2]); //directories always precede files. Result := (FI2.SR.Attr and faDirectory) - (FI1.SR.Attr and faDirectory); if Result = 0 then Result := AnsiCompareFileName(FI1.SR.Name, FI2.SR.Name); end; type TFileEditDirectory = class(TDirectory) private FEdit: TFileEdit; protected procedure DoDirChange(const NewDir: WideString); override; public constructor Create(AOwner: TFileEdit); reintroduce; virtual; end; constructor TFileEditDirectory.Create(AOwner: TFileEdit); begin inherited Create(AOwner); FEdit := AOwner; end; procedure TFileEditDirectory.DoDirChange(const NewDir: WideString); begin if not FSuspendEvents then FEdit.FCurrentDir := NewDir; inherited DoDirChange(NewDir); end; { TFileEdit } function TFileEdit.CheckNewDirectory(const Text: WideString): Boolean; var NewDir: WideString; Prefix: WideString; {$IFDEF MSWINDOWS} Tmp: WideString; {$ENDIF} begin Result := False; if Text = '' then Exit; if Text[1] = PathDelim then begin {$IFDEF LINUX} NewDir := IncludeTrailingPathDelimiter(ExpandDirectoryName(ExtractFilePath(Text))); if (Text[Length(Text)] = PathDelim) then Prefix := Text; {$ENDIF} {$IFDEF MSWINDOWS} Tmp := GetDrive(FCurrentDir); NewDir := Tmp + Text; Prefix := Text; {$ENDIF} end else if (Length(Text) > 1) and {$IFDEF LINUX} ((Text[1] = '$') or (Text[1] = '~')) {$ENDIF} {$IFDEF MSWINDOWS} HasDrivePrefix(Text) {$ENDIF} and (Text[Length(Text)] = PathDelim) then begin NewDir := ExpandDirectoryName(Text); Prefix := Text; end else begin NewDir := IncludeTrailingPathDelimiter(ExpandDirectoryName( IncludeTrailingPathDelimiter(FCurrentDir) + ExtractFilePath(Text))); Prefix := ExtractFilePath(Text); end; Result := (DirectoryExists(NewDir) and (NewDir <> FListedDir)) {$IFDEF LINUX} or (Text = PathDelim) {$ENDIF} or (Text = ''); if Result then begin FDirectory.FSuspendEvents := True; try {$IFDEF LINUX} if access(PChar(AnsiString(NewDir)), R_OK) = 0 then {$ENDIF} PopulateList(NewDir, Prefix); finally FDirectory.FSuspendEvents := False; end; end; end; constructor TFileEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FDirectory := TFileEditDirectory.Create(Self); FDirectory.IncludeParentDir := False; FDropDownCount := 10; if not (csDesigning in ComponentState) then begin FListBox := TPopupListBox.CreateParented(QApplication_Desktop); FListBox.Height := DropDownCount * 16;//change this to reflect font size; FListBox.OnMouseUp := ListMouseUp; FListBox.OnMouseMove := ListMouseMove; end; InputKeys := InputKeys + [ikReturns]; FPrefix := ''; FEditMode := emDropDownList; end; destructor TFileEdit.Destroy; begin FListBox.Free; FDirectory.Free; inherited Destroy; end; procedure TFileEdit.ResizeListBox(ItemCount: Integer); var I: Integer; P: TPoint; begin if (EditMode = emDropDownList) and not FListBox.FResized then begin if ItemCount > DropDownCount then I := DropDownCount else I := ItemCount; if I <> 0 then begin FListBox.Width := Width; FListBox.Height := I * FListBox.ItemHeight + (QFrame_frameWidth(FListBox.Handle) * 2); P := ClientToScreen(Point(0, 0)); FListBox.Left := P.X; if P.Y + FListBox.Height > Screen.Height then begin P.Y := P.Y - FListBox.Height; FListBox.FDroppedUp := True; end else begin P.Y := P.Y + Height; FListBox.FDroppedUp := False; end; FListBox.Top := P.Y; end else FListBox.Height := 0; end; end; procedure TFileEdit.DropDown; var Tmp: Boolean; begin if not ((csDesigning in ComponentState) or (EditMode <> emDropDownList)) then begin FDroppedDown := True; FOriginalText := Text; SetMouseGrabControl(Self); Tmp := AutoSelect; AutoSelect := False; FListBox.Visible := True; QWidget_setFocus(Handle); AutoSelect := Tmp; end; end; procedure TFileEdit.KeyPress(var Key: Char); var Tmp: WideString; begin inherited KeyPress(Key); if EditMode = emAutoComplete then begin if (Key = PathDelim) and (SelLength > 0) and (FListBox.Items.Count > 0) and (Text = FListBox.Items[0]) and (PFileInfo(FListBox.Items.Objects[0]).SR.Attr and faDirectory <> 0) then //if there's a selection, the first item in the listbox is the suggested //completion. begin SelStart := Length(Text); SelLength := 0; CursorPos := Length(Text); end; case Key of #8, #127: begin Tmp := MatchText; Delete(Tmp, Length(Tmp), 1); CheckNewDirectory(Tmp); end; #32..#126, #128..#255: begin CheckNewDirectory(MatchText + Key); FMatchCount := PartialMatch(MatchText + Key); if FMatchCount = 0 then CloseUp else if not DroppedDown then DropDown; end; end; if (FMatchCount <> 0) and (EditMode = emAutoComplete) and not (Key in [#8, #127]) and (Text <> '') then Key := #0; end; end; procedure TFileEdit.KeyUp(var Key: Word; Shift: TShiftState); var CurIndex: Integer; begin inherited KeyUp(Key, Shift); if (csDesigning in ComponentState) or (EditMode = emAutoComplete) then Exit; case Key of 32..126, 128..255: begin CheckNewDirectory(MatchText); FMatchCount := PartialMatch(MatchText); if FMatchCount = 0 then CloseUp else if not DroppedDown then DropDown; end; Key_Down, Key_Up, Key_PageDown, Key_PageUp, Key_Home, Key_End: begin if DroppedDown then begin CurIndex := FListBox.ItemIndex; case Key of Key_Down: if CurIndex < FListBox.Items.Count - 1 then Inc(CurIndex); Key_Up: if CurIndex > 0 then Dec(CurIndex); Key_PageDown: begin if CurIndex < 0 then CurIndex := 0; if CurIndex = FListBox.TopIndex + FListBox.VisibleItemCount - 1 then Inc(CurIndex, FListBox.VisibleItemCount - 1) else CurIndex := FListBox.TopIndex + FListBox.VisibleItemCount - 1; if CurIndex >= FListBox.Items.Count then CurIndex := FListBox.Items.Count - 1; end; Key_PageUp: begin if CurIndex < 0 then CurIndex := 0; if CurIndex = FListBox.TopIndex then Dec(CurIndex, FListBox.VisibleItemCount - 1) else CurIndex := FListBox.TopIndex; if CurIndex < 0 then CurIndex := 0; end; Key_Home: CurIndex := 0; Key_End: CurIndex := FListBox.Items.Count - 1; end; SetListIndex(CurIndex); end else if (Key = Key_Down) and (ssAlt in Shift) and (EditMode = emDropDownList) then begin FMatchCount := PartialMatch(Text); if (FMatchCount > 0) and not DroppedDown then DropDown; end; Key := 0; end; Key_Backspace, Key_Delete: begin CheckNewDirectory(MatchText); if EditMode <> emAutoComplete then FMatchCount := PartialMatch(MatchText); if Text = '' then CloseUp else if (FMatchCount > 0) and not DroppedDown then DropDown; end; end; end; function TFileEdit.PartialMatch(const Str: WideString): Integer; var I, P: Integer; AFile: WideString; PartialText: WideString; begin Result := 0; if not Assigned(FListBox) then Exit; //prevent matching when last character is the path delimiter if (EditMode = emAutoComplete) and (((Length(Str) > 0) and (Str[Length(Str)] = PathDelim)) or (CursorPos < Length(Text))) then Exit; FListBox.Items.Clear; PartialText := Str; for I := 0 to FDirectory.Count - 1 do begin AFile := FPrefix + FDirectory.Caption(I); {$IFDEF MSWINDOWS} P := Pos(AnsiLowerCaseFileName(PartialText), AnsiLowerCaseFileName(AFile)); {$ENDIF} {$IFDEF LINUX} P := Pos(PartialText, AFile); {$ENDIF} if (P = 1) or ((P = 0) and (PartialText = '')) then begin FListBox.Items.AddObject(AFile, TObject(FDirectory.Files(I))); Inc(Result); end; end; if EditMode = emDropDownList then ResizeListBox(Result) else if (EditMode = emAutoComplete) and (Result > 0) then begin if Text <> FListBox.Items[0] then Text := FListBox.Items[0]; SelStart := Length(PartialText); CursorPos := SelStart; SelLength := Length(Text) - SelStart; end; end; procedure TFileEdit.PopulateList(const Directory: WideString; Prefix: WideString = ''); begin if not (csDesigning in ComponentState) then begin FListedDir := IncludeTrailingPathDelimiter(Directory); FPrefix := Prefix; FDirectory.Location := ExpandDirectoryName(Directory); end; end; procedure TFileEdit.CloseUp; begin if not (csDesigning in ComponentState) then begin FListBox.Visible := False; FDroppedDown := False; FListBox.FDroppedUp := False; SetMouseGrabControl(nil); end; end; procedure TFileEdit.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if DroppedDown then CloseUp; end; procedure TFileEdit.ListMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if PtInRect(FListBox.ClientRect, Point(X, Y)) and (FListBox.ItemIndex > -1) then Text := FListBox.Items[FListBox.ItemIndex]; if FListBox.FResizeType = rtNone then CloseUp; end; procedure TFileEdit.ListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var Index: Integer; begin Index := FListBox.ItemAtPos(Point(X, Y), True); if Index > -1 then FListBox.ItemIndex := Index; end; procedure TFileEdit.ListEnd; var I: Integer; begin for I := 0 to FDirectory.Count - 1 do FListBox.Items.Add(FPrefix + FDirectory.Caption(I)); FListBox.Items.EndUpdate; end; function TFileEdit.ListStart: Boolean; begin Result := Assigned(FListBox) and not (csLoading in ComponentState); if Result then begin FListBox.Items.BeginUpdate; FListBox.Clear; end; end; function TFileEdit.MatchText: WideString; begin if EditMode = emDropDownList then Result := Text else Result := Copy(Text, 1, SelStart); end; procedure TFileEdit.SetListIndex(Value: Integer); begin if (Value < 0) or (Value >= FListBox.Items.Count) or not DroppedDown then Exit; FListBox.ItemIndex := Value; FListBox.MakeCurrentVisible; Text := FListBox.Items[Value]; end; procedure TFileEdit.ReturnPressed(var Suppress: Boolean); var NewDir: string; {$IFDEF MSWINDOWS} Tmp: string; {$ENDIF} begin CloseUp; if Length(Text) > 0 then begin // check for absolute directory path first. {$IFDEF LINUX} if Char(Text[1]) in [PathDelim, '~', '$'] then NewDir := ExpandDirectoryName(Text) {$ENDIF} {$IFDEF MSWINDOWS} if (Char(Text[1]) = PathDelim) or HasDrivePrefix(Text) then begin Tmp := Text; if Char(Text[1]) = PathDelim then Tmp := GetDrive(FCurrentDir) + Tmp; NewDir := ExpandDirectoryName(Tmp); if not DirectoryExists(IncludeTrailingPathDelimiter(NewDir)) then Exit; end {$ENDIF} else NewDir := IncludeTrailingPathDelimiter(FCurrentDir) + Text; Suppress := Suppress or DirectoryExists(NewDir); if Suppress then begin Text := ''; PopulateList(NewDir); Exit; end; end; // check for a wildcard filter Suppress := (Pos('*', Text) <> 0) or (Pos('?', Text) <> 0); if Suppress then begin FDirectory.FileMask := Text; MaskChange(Text); SelectAll; Exit; end; inherited ReturnPressed(Suppress); end; procedure TFileEdit.CMKeyDown(var Msg: TCMKeyDown); begin if (Msg.Key = Key_Escape) and DroppedDown then begin CloseUp; Text := FOriginalText; Msg.Handled := True; end else inherited; end; function TFileEdit.GetCurrentDir: WideString; begin Result := IncludeTrailingPathDelimiter(FCurrentDir); end; procedure TFileEdit.DirectoryChanged(const NewDir: WideString); begin if Assigned(FOnDirChange) then FOnDirChange(Self, NewDir); end; function TFileEdit.FileFound(const SearchRec: TSearchRec): Boolean; begin Result := True; if Assigned(FOnFileFound) then FOnFileFound(Self, SearchRec, Result); end; procedure TFileEdit.MaskChange(const NewMask: WideString); begin if Assigned(FOnMaskChange) then FOnMaskChange(Self, NewMask); end; procedure TFileEdit.SetDirectory(const Value: TDirectory); begin FDirectory.Assign(Value); end; procedure TFileEdit.InitWidget; begin inherited InitWidget; if csDesigning in ComponentState then FDirectory.Location := SysUtils.GetCurrentDir; end; procedure TFileEdit.Loaded; begin inherited Loaded; FDirectory.ListFiles(True); end; { TPopupListBox } constructor TPopupListBox.CreateParented(ParentWidget: QWidgetH); begin inherited CreateParented(ParentWidget); ControlStyle := ControlStyle + [csNoDesignVisible, csCaptureMouse, csReplicatable]; end; type TOpenWidget = class(TWidgetControl); function TPopupListBox.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; var EventType: QEventType; begin Result := False; EventType := QEvent_type(Event); case EventType of QEventType_FocusIn: Result := True; end; if not Result then Result := inherited EventFilter(Sender, Event); end; function TPopupListBox.GetResizeType(P: TPoint): TResizeType; const Border = 4; var Horz, Vert, Both: TRect; begin if FDroppedUp then begin Vert := Rect(0, 0, Width - Border, Border); Horz := Rect(Width - Border, Border, Width, Height); Both := Rect(Width - Border, 0, Width, Border); end else begin Vert := Rect(0, Height - Border, Width - Border, Height); Horz := Rect(Width - Border, 0, Width, Height - Border); Both := Rect(Width - Border, Height - Border, Width, Height); end; if PtInRect(Horz, P) then Result := rtHorz else if PtInRect(Vert, P) then Result := rtVert else if PtInRect(Both, P) then Result := rtBoth else Result := rtNone; end; procedure TPopupListBox.InitWidget; begin inherited InitWidget; BorderStyle := bsSingle; QWidget_setFocusPolicy(Handle, QWidgetFocusPolicy_NoFocus); Visible := False; end; procedure TPopupListBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then FResizeType := GetResizeType(Point(X, Y)) else FResizeType := rtNone; if FResizeType = rtNone then inherited MouseDown(Button, Shift, X, Y); end; procedure TPopupListBox.MouseMove(Shift: TShiftState; X, Y: Integer); var NewWidth, NewHeight, NewTop: Integer; begin NewTop := Top; NewWidth := Width; NewHeight := Height; case FResizeType of rtNone: begin case GetResizeType(Point(X, Y)) of rtVert: Cursor := crSizeNS; rtHorz: Cursor := crSizeWE; rtBoth: if FDroppedUp then Cursor := crSizeNESW else Cursor := crSizeNWSE; rtNone: Cursor := crDefault; end; end; rtVert: if FDroppedUp then begin NewTop := Mouse.CursorPos.Y; NewHeight := Top - NewTop + Height; end else NewHeight := Y; rtHorz: NewWidth := X; rtBoth: begin if FDroppedUp then begin NewTop := Mouse.CursorPos.Y; NewHeight := Top - NewTop + Height; end else NewHeight := Y; NewWidth := X; end; end; if FResizeType <> rtNone then begin FResized := True; SetBounds(Left, NewTop, NewWidth, NewHeight); end; inherited MouseMove(Shift, X, Y); end; procedure TPopupListBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); FResizeType := rtNone; end; function TPopupListBox.WidgetFlags: Integer; begin Result := inherited WidgetFlags or Integer(WidgetFlags_WType_Popup) or Integer(WidgetFlags_WStyle_Tool) or Integer(WidgetFlags_WNorthWestGravity); end; {$IFDEF MSWINDOWS} constructor TShellChangeThread.Create(ChangeEvent: TThreadMethod; Directory: string); begin FDirectory := Directory; FreeOnTerminate := True; FChangeEvent := ChangeEvent; FMutex := CreateMutex(nil, True, nil); inherited Create(False); end; destructor TShellChangeThread.Destroy; begin if FWaitHandle <> ERROR_INVALID_HANDLE then FindCloseChangeNotification(FWaitHandle); CloseHandle(FMutex); inherited Destroy; end; procedure TShellChangeThread.Execute; var Obj: DWORD; Handles: array[0..1] of DWORD; begin FWaitHandle := FindFirstChangeNotification(PChar(FDirectory), False, FILE_NOTIFY_CHANGE_FILE_NAME or FILE_NOTIFY_CHANGE_DIR_NAME or FILE_NOTIFY_CHANGE_ATTRIBUTES or FILE_NOTIFY_CHANGE_SIZE); if FWaitHandle = ERROR_INVALID_HANDLE then Exit; while not Terminated do begin Handles[0] := FWaitHandle; Handles[1] := FMutex; Obj := WaitForMultipleObjects(2, @Handles, False, INFINITE); case Obj of WAIT_OBJECT_0: begin Synchronize(FChangeEvent); FindNextChangeNotification(FWaitHandle); end; WAIT_OBJECT_0 + 1: ReleaseMutex(FMutex); WAIT_FAILED: Exit; end; end; end; {$ENDIF} { TDirectory } procedure TDirectory.AssignTo(Dest: TPersistent); var I: Integer; begin if not (Dest is TDirectory) then inherited AssignTo(Dest) else with TDirectory(Dest) do begin FSuspendEvents := True; try ClearList; FDir := Self.Location; FMask := Self.FileMask; FFileType := Self.FileType; FSortMode := Self.SortMode; FSortDirection := Self.SortDirection; AutoUpdate := Self.AutoUpdate; FIncludeParentDir := Self.IncludeParentDir; for I := 0 to Self.FFiles.Count - 1 do FFiles.Add(AllocFileInfo(PFileInfo(Self.FFiles[I]).SR)); finally FSuspendEvents := False; ListFiles(False); end; end; end; function TDirectory.Attributes(Index: Integer): Integer; begin {$IFDEF LINUX} Result := Files(Index).stat.st_mode; {$ENDIF} {$IFDEF MSWINDOWS} Result := Files(Index).SR.Attr; {$ENDIF} end; procedure TDirectory.BeginUpdate; begin Inc(FUpdateCount); end; function TDirectory.Caption(Index: Integer): WideString; begin Result := Files(Index).SR.Name; end; {$IFDEF MSWINDOWS} procedure TDirectory.ChangeNotification; begin ListFiles(True); end; {$ENDIF} procedure TDirectory.ClearList; var I: Integer; begin for I := 0 to FFiles.Count - 1 do Dispose(PFileInfo(FFiles[I])); FFiles.Clear; end; function TDirectory.Count: Integer; begin Result := FFiles.Count; end; constructor TDirectory.Create(AClient: IDirectoryClient); begin inherited Create; FClient := AClient; FFiles := TList.Create; FMask := AllMask; FDirHandle := -1; FAutoUpdate := False; FFileType := [ftNormal, ftDirectory, ftSystem]; FAutoUpdate := False; FIncludeParentDir := True; FSortMode := smName; FSortDirection := sdAscending; DirChangeList.Add(Self); end; function TDirectory.CreateDirectory(const DirName: WideString): PFileInfo; var Created: Boolean; SR: TSearchRec; AnsiDir: string; DirAttr: Integer; begin Result := nil; AnsiDir := FDir; Created := {$IFDEF LINUX} (access(PChar(AnsiDir), W_OK) = 0) and {$ENDIF} CreateDir(IncludeTrailingPathDelimiter(FDir) + DirName); if Created then begin DirAttr := faDirectory; if ftHidden in FileType then DirAttr := DirAttr + faHidden; if FindFirst(IncludeTrailingPathDelimiter(FDir) + DirName, DirAttr, SR) = 0 then try DoFileFound(SR); Result := FFiles[FFiles.Count-1]; finally FindClose(SR); end; end; end; function TDirectory.Date(Index: Integer): Integer; begin Result := Files(Index).SR.Time; end; function TDirectory.Delete(const Filename: WideString): Integer; var I: Integer; begin I := FFiles.Count - 1; while (I > 0) and (AnsiCompareFileName(PFileInfo(FFiles[I]).SR.Name, Filename) <> 0) do Dec(I); if I > -1 then Result := Delete(FFiles[I]) else Result := RESULT_FILE_NOT_FOUND; end; function TDirectory.Delete(AFile: PFileInfo): Integer; var Filename: string; begin Filename := IncludeTrailingPathDelimiter(FDir) + AFile.SR.Name; Result := {$IFDEF LINUX} access(PChar(Filename), W_OK); {$ENDIF} {$IFDEF MSWINDOWS} RESULT_OK; {$ENDIF} if Result = RESULT_OK then begin if AFile.SR.Attr and faDirectory <> 0 then begin if not RemoveDir(Filename) then Result := RESULT_DIR_NOT_EMPTY; end else if not DeleteFile(Filename) then Result := RESULT_ACCESS_DENIED; if Result = RESULT_OK then begin FFiles.Remove(AFile); Dispose(AFile); end; end; end; destructor TDirectory.Destroy; begin ClearList; DirChangeList.Remove(Self); FFiles.Free; inherited Destroy; end; procedure TDirectory.DoDirChange(const NewDir: WideString); begin if Assigned(FClient) and not FSuspendEvents then FClient.DirectoryChanged(NewDir); end; procedure TDirectory.DoFileFound(const SearchRec: TSearchRec); var CanAdd: Boolean; begin CanAdd := True; if Assigned(FClient) then CanAdd := FClient.FileFound(SearchRec); if CanAdd then FFiles.Add(AllocFileInfo(SearchRec)); end; procedure TDirectory.DoListEnd; begin if Assigned(FClient) then FClient.ListEnd; end; function TDirectory.DoListStart: Boolean; begin Result := not Assigned(FClient) or FClient.ListStart; end; procedure TDirectory.DoMaskChange(const NewMask: WideString); begin if Assigned(FClient) and not FSuspendEvents then FClient.MaskChange(NewMask); end; procedure TDirectory.EndUpdate; begin Dec(FUpdateCount); if FUpdateCount = 0 then ListFiles; end; {$IFDEF LINUX} function TDirectory.LinkName(Index: Integer): WideString; var Info: PFileInfo; begin Info := Files(Index); if Info.SR.Attr and faSymLink <> 0 then Result := Info.LinkTarget else Result := Info.SR.PathOnly + Info.SR.Name; end; {$ENDIF} function TDirectory.Files(Index: Integer): PFileInfo; begin Result := PFileInfo(FFiles[Index]); end; function TDirectory.GetDir: WideString; begin {$IFDEF MSWINDOWS} if FDir = '' then Result := FDir else {$ENDIF} Result := IncludeTrailingPathDelimiter(FDir); end; {$IFDEF LINUX} function TDirectory.GroupName(Index: Integer): WideString; begin Result := UserName(Files(Index).stat.st_gid); end; {$ENDIF} function TDirectory.IndexOf(const Filename: WideString): Integer; var I: Integer; begin Result := -1; for I := FFiles.Count - 1 downto 0 do begin if AnsiCompareFileName(Caption(I), Filename) = 0 then begin Result := I; Break; end; end; end; {$IFDEF MSWINDOWS} procedure TDirectory.ListDrives; var DriveBits: set of 0..25; DriveNum: Integer; SR: TSearchRec; begin { fill list } Integer(DriveBits) := GetLogicalDrives; for DriveNum := 0 to 25 do begin if not (DriveNum in DriveBits) then Continue; CreateDriveInfo(Char(DriveNum + Ord('A')) + DriveDelim + PathDelim, SR); DoFileFound(SR); end; end; {$ENDIF} procedure TDirectory.ListFiles(Reread: Boolean = True); var AttrIndex: TFileAttr; AttrWord: Word; DirAttr: Word; MaskPtr, Ptr: PChar; SearchRec: TSearchRec; AMask: string; {$IFDEF MSWINDOWS} ExtLen: Integer; OldErrorMode: Integer; {$ENDIF} begin if not DoListStart then Exit; {$IFDEF MSWINDOWS} OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); {$ENDIF} try if Reread then begin AMask := FMask; ClearList; {$IFDEF MSWINDOWS} if FDir = '' then ListDrives else begin {$ENDIF} DirAttr := faDirectory; if ftSystem in FileType then DirAttr := DirAttr + faSysFile; if ftHidden in FileType then DirAttr := DirAttr + faHidden; if ftDirectory in FFileType then begin if FindFirst(IncludeTrailingPathDelimiter(FDir) + '*', DirAttr, SearchRec) = 0 then begin repeat { exclude normal files if ftNormal not set } if (SearchRec.Attr and faDirectory <> 0) and (SearchRec.Name <> '.') then begin if (SearchRec.Name = '..') then begin if not FIncludeParentDir then Continue else DoFileFound(SearchRec); end else DoFileFound(SearchRec); end; until FindNext(SearchRec) <> 0; FindClose(SearchRec); end; end; if FFileType * [ftNormal, ftArchive] <> [] then begin AttrWord := 0; for AttrIndex := ftReadOnly to ftArchive do if (AttrIndex in FFileType) and (AttrIndex <> ftDirectory) then AttrWord := AttrWord or AttrWords[AttrIndex]; MaskPtr := PChar(AMask); while MaskPtr <> nil do begin Ptr := StrScan(MaskPtr, ';'); if Ptr <> nil then Ptr^ := #0; if FindFirst(FDir + PathDelim + MaskPtr, AttrWord, SearchRec) = 0 then begin {$IFDEF MSWINDOWS} ExtLen := Length(ExtractFileExt(MaskPtr)); {$ENDIF} repeat { exclude normal files if ftNormal not set } if ((ftNormal in FFileType) or (SearchRec.Attr and AttrWord <> 0)) {$IFDEF MSWINDOWS} // work around FindFirstFile() bug in Windows where, for example, // a mask of "*.abc" will match "foo.abcd" and (ExtLen <> 4) or (ExtLen = Length(ExtractFileExt(SearchRec.Name))) {$ENDIF} then DoFileFound(SearchRec); until FindNext(SearchRec) <> 0; FindClose(SearchRec); end; if Ptr <> nil then begin Ptr^ := ';'; Inc (Ptr); end; MaskPtr := Ptr; end; end; end; {$IFDEF MSWINDOWS} end; {$ENDIF} if FSortMode <> smNone then begin GSortMode := FSortMode; GSortDirection := FSortDirection; FFiles.Sort(FileSort); end; finally DoListEnd; {$IFDEF MSWINDOWS} SetErrorMode(OldErrorMode); {$ENDIF} end; end; {$IFDEF LINUX} function TDirectory.OwnerName(Index: Integer): WideString; begin Result := UserName(Files(Index).stat.st_uid); end; {$ENDIF} procedure TDirectory.RemoveChangeNotification; begin {$IFDEF LINUX} if FDirHandle > 0 then begin fcntl(FDirHandle, 0, 0); FileClose(FDirHandle); end; {$ENDIF} {$IFDEF MSWINDOWS} if Assigned(FChangeThread) then begin FChangeThread.Terminate; ReleaseMutex(FChangeThread.FMutex); end; {$ENDIF} end; function TDirectory.Rename(const Filename, NewName: WideString): Integer; var I, J: Integer; begin I := IndexOf(Filename); J := IndexOf(NewName); if I > -1 then if J < 0 then Result := Rename(FFiles[I], NewName) else Result := RESULT_ALREADY_EXISTS else Result := RESULT_FILE_NOT_FOUND; end; function TDirectory.Rename(AFile: PFileInfo; const NewName: WideString): Integer; var Filename: string; NewFilename: string; Attr: Integer; AttrIndex: TFileAttr; Index: Integer; SR: TSearchRec; begin Filename := IncludeTrailingPathDelimiter(FDir) + AFile.SR.Name; NewFilename := ExcludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(FDir) + NewName); if FileExists(NewFilename) then begin Result := RESULT_ALREADY_EXISTS; Exit; end; Result := {$IFDEF LINUX} access(PChar(Filename), W_OK); {$ENDIF} {$IFDEF MSWINDOWS} RESULT_OK;//TODO 1: check write access on Windows. Result should be RESULT_OK. {$ENDIF} Attr := 0; if Result = RESULT_OK then begin if not RenameFile(Filename, NewFilename) then Result := RESULT_ACCESS_DENIED; if Result = RESULT_OK then begin Index := FFiles.IndexOf(AFile); for AttrIndex := ftReadOnly to ftArchive do Attr := Attr or AttrWords[AttrIndex]; if FindFirst(NewFilename, Attr, SR) = 0 then try Result := Integer(AllocFileInfo(SR)); Dispose(AFile); FFiles[Index] := Pointer(Result); finally FindClose(SR); end else begin Result := Integer(AFile); AFile.SR.Name := NewName; {$IFDEF LINUX} if Pos('.', NewName) = 1 then AFile.SR.Attr := AFile.SR.Attr or faHidden; {$ENDIF} end; end; end; end; procedure TDirectory.SetAutoUpdate(const Value: Boolean); begin if FAutoUpdate <> Value then begin FAutoUpdate := Value; if FAutoUpdate then SetChangeNotification(FDir) else SetChangeNotification(''); end; end; procedure TDirectory.SetChangeNotification(const Dir: string); {$IFDEF LINUX} var dh: Integer; Flags: Cardinal; action: TSigAction; {$ENDIF} begin RemoveChangeNotification; if Dir = '' then Exit; {$IFDEF LINUX} dh := FileOpen(Dir, fmOpenRead or fmShareDenyNone); if dh > 0 then begin try Flags := DN_MODIFY or DN_CREATE or DN_DELETE or DN_RENAME or DN_ATTRIB or DN_MULTISHOT; if (fcntl(dh, F_SETSIG, SIGIO) = 0) and (fcntl(dh, F_NOTIFY, Flags) = 0) then begin FDirHandle := dh; FillChar(action, SizeOf(action), 0); with action do begin __sigaction_handler := @DirChanged; sa_flags := SA_SIGINFO; end; sigaction(SIGIO, @action, nil); end; finally FileClose(dh); end; end; {$ENDIF} {$IFDEF MSWINDOWS} FChangeThread := TShellChangeThread.Create(ChangeNotification, FDir); {$ENDIF} end; procedure TDirectory.SetDir(const Value: WideString); var FName: string; begin if Value <> '' then FName := ExpandDirectoryName(Value); if not FDirChanging {and (FDir <> FName)} then begin {$IFDEF LINUX} if access(PChar(FName), R_OK) <> 0 then {$ENDIF} {$IFDEF MSWINDOWS} //TODO: Check for directory access on windows. if False then {$ENDIF} raise EDirectoryError.CreateFmt(SCannotReadDirectory, [Value]); FDir := FName; FDirChanging := True; try if FAutoUpdate then SetChangeNotification(FDir); if FUpdateCount = 0 then ListFiles; DoDirChange(FDir); finally FDirChanging := False; end; end; end; procedure TDirectory.SetFileType(const Value: TFileType); begin if FFileType <> Value then begin FFileType := Value; if FUpdateCount = 0 then ListFiles; end; end; procedure TDirectory.SetIncludeParentDir(const Value: Boolean); begin if FIncludeParentDir <> Value then begin FIncludeParentDir := Value; if FUpdateCount = 0 then ListFiles; end; end; procedure TDirectory.SetMask(const Value: WideString); begin if FMask <> Value then begin FMask := Value; if FUpdateCount = 0 then ListFiles; DoMaskChange(FMask); end; end; procedure TDirectory.SetSortDirection(const Value: TSortDirection); begin if FSortDirection <> Value then begin FSortDirection := Value; Sort; end; end; procedure TDirectory.SetSortMode(const Value: TSortMode); begin if FSortMode <> Value then begin FSortMode := Value; Sort; end; end; function TDirectory.Size(Index: Integer): Cardinal; begin Result := Files(Index).SR.Size; end; procedure TDirectory.Sort; begin ListFiles(False); end; type TFileIconItemEditor = class(TIconItemEditor) procedure EditFinished(Accepted: Boolean); override; end; function TDirectory.UniqueName(const Name: WideString): WideString; var I, J: Integer; begin Result := Name; J := 1; repeat I := IndexOf(Result); if I > -1 then begin Result := Format('%s %d', [Name, J]); Inc(J); end; until I = -1; end; { TFileIconItemEditor } procedure TFileIconItemEditor.EditFinished(Accepted: Boolean); begin Accepted := Accepted and (Text <> ''); inherited EditFinished(Accepted); if TFileIconView(IconView).FCreatingDir and not TFileIconView(IconView).FCreatedDir then begin if Accepted then MessageDlg(SMsgDlgError, Format(SCannotCreateDirName, [Item.Caption]), mtError, [mbOk], 0); Item.Free; end; TFileIconView(IconView).FCreatingDir := False; IconView.UpdateControl; end; { TFileIconView } constructor TFileIconView.Create(AOwner: TComponent); begin inherited Create(AOwner); ReadOnly := True; FDirectory := TDirectory.Create(Self); InputKeys := InputKeys - [ikReturns]; FIconProvider := IconProvider32; FIconSize := isLarge; {$IFDEF LINUX} FDirectory.Location := GetCurrentDir; {$ENDIF} {$IFDEF MSWINDOWS} FDrivesListed := False; {$ENDIF} end; procedure TFileIconView.CreateDirectory(const DefaultName: WideString); var InsIndex: Integer; begin if ReadOnly then Exit; FCreatingDir := True; FCreatedDir := False; SetFocus; InsIndex := Items.Count; if InsIndex > 0 then Items[InsIndex-1].MakeVisible; with Items.Add do begin Caption := FDirectory.UniqueName(DefaultName); Selected := True; UpdateControl; EditText; end; end; function TFileIconView.CreateEditor: TItemEditor; begin Result := TFileIconItemEditor.Create(Self); end; procedure TFileIconView.DblClick; begin inherited DblClick; if (Selected <> nil) and (FDirectory.Files(Selected.Index).SR.Attr and faDirectory <> 0) and (Selected.Caption = '..') then GoUp else GoDown; end; function TFileIconView.DeleteFile(const Filename: WideString): Integer; begin Result := FDirectory.Delete(Filename); if Result = RESULT_OK then Refresh; end; destructor TFileIconView.Destroy; begin FDirectory.Free; inherited Destroy; end; procedure TFileIconView.DirectoryChanged(const NewDir: WideString); begin if Items.Count > 0 then EnsureItemVisible(Items[0]); if Assigned(FOnDirChange) then FOnDirChange(Self, NewDir); end; function TFileIconView.DoCustomDrawIconItem(Item: TIconViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; var R: TRect; IL: TCustomImageList; II: Integer; B: TBitmap; Mask: QBitmapH; begin Result := False; if Stage = cdPostPaint then Result := inherited DoCustomDrawIconItem(Item, Canvas, Rect, State, cdPrePaint); if Result then begin if Assigned(Images) then IL := Images else IL := FIconProvider; if cdsSelected in State then begin Canvas.Brush.Color := clHighlight; Canvas.Font.Color := clHighlightText; end else begin Canvas.Brush.Color := Color; Canvas.Font.Color := clWindowText; end; with Item do begin if IL = Images then begin DoGetImageIndex(Item); II := Item.ImageIndex; end else II := FIconProvider.DoGetImageIndex(Item.Data); Canvas.FillRect(TextRect); R := IconRect; Inc(R.Top, (R.Bottom - R.Top - IL.Height) div 2); Inc(R.Left, (R.Right - R.Left - IL.Width) div 2); if (Data <> nil) and (EditingItem <> Item) then begin DrawTruncatedText(Canvas, TextRect, PFileInfo(Item.Data).SR.Name, True, IconOptions.WrapText); end; if Assigned(Images) then IL := Images else IL := FIconProvider; if not (cdsSelected in State) then begin IL.Draw(Canvas, R.Left, R.Top, II); {$IFDEF LINUX} if (Data <> nil) and (PFileInfo(Item.Data).SR.Attr and faSymLink <> 0) and (IL = FIconProvider) then FIconProvider.DrawLinkOverlay(Canvas, R.Left, R.Top, PFileInfo(Item.Data)); {$ENDIF} end else begin B := TBitmap.Create; try B.Width := IL.Width; B.Height := IL.Height; Mask := IL.GetMask(II); if Mask <> nil then begin QPixmap_setMask(B.Handle, Mask); IL.Draw(B.Canvas, 0, 0, II, itImage); B.Canvas.TiledDraw(Types.Rect(0, 0, B.Width, B.Height), IVSelectBmp); Canvas.Draw(R.Left, R.Top, B); {$IFDEF LINUX} if (Data <> nil) and (PFileInfo(Data).SR.Attr and faSymLink <> 0) and (IL = FIconProvider) then FIconProvider.DrawLinkOverlay(Canvas, R.Left, R.Top, PFileInfo(Data)); {$ENDIF} end; finally B.Free; end; end; end; end; if Stage = cdPostPaint then begin inherited DoCustomDrawIconItem(Item, Canvas, Rect, State, Stage); Result := False; end; end; function TFileIconView.DoCustomHint(var HintInfo: THintInfo): Boolean; var Info: PFileInfo; Item: TIconViewItem; Pos: TPoint; TextRect, BRect: TRect; begin Pos := ScreenToClient(Mouse.CursorPos); Item := FindItemByPoint(Pos); Result := Item <> nil; if Result then begin Info := PFileInfo(Item.Data); if Info <> nil then begin TextRect := Item.TextRect; BRect := TextRect; Canvas.TextExtent(Item.Caption, BRect, Integer(AlignmentFlags_AlignHCenter) or Integer(AlignmentFlags_WordBreak)); if ((BRect.Right - BRect.Left) > (TextRect.Right - TextRect.Left)) or ((BRect.Bottom - BRect.Top) > (TextRect.Bottom - TextRect.Top)) then begin {$IFDEF MSWINDOWS} if FDrivesListed then HintInfo.HintStr := Format('%s'#10'%s: %s'#10'%s: %s'#10'%s: %s', [Item.Caption, SType, GetFileTypeProc(Info), SFreeSpace, Format(SMegs, [Info.SR.Time]), SSize, Format(SMegs, [Info.SR.Size])]) else {$ENDIF} HintInfo.HintStr := Format('%s'#10'%s: %s'#10'%s: %s'#10'%s: %d', [Item.Caption, SType, GetFileTypeProc(Info), SDate, DateTimeToStr(FileDateToDateTime(Info.SR.Time)), SSize, Info.SR.Size]) end else begin {$IFDEF MSWINDOWS} if FDrivesListed then HintInfo.HintStr := Format('%s: %s'#10'%s: %s'#10'%s: %s', [SType, GetFileTypeProc(Info), SFreeSpace, Format(SMegs, [Info.SR.Time]), SSize, Format(SMegs, [Info.SR.Size])]) else {$ENDIF} HintInfo.HintStr := Format('%s: %s'#10'%s: %s'#10'%s: %d', [SType, GetFileTypeProc(Info), SDate, DateTimeToStr(FileDateToDateTime(Info.SR.Time)), SSize, Info.SR.Size]); end; HintInfo.ReshowTimeout := MaxInt; end; end; end; procedure TFileIconView.DoEdited(AItem: TIconViewItem; var S: WideString); var NewDir: PFileInfo; begin if FCreatingDir then begin NewDir := FDirectory.CreateDirectory(S); FCreatedDir := NewDir <> nil; if FCreatedDir then TIconViewItem(AItem).Data := NewDir; end else if RenameFile(AItem, S) < 0 then S := PFileInfo(TIconViewItem(AItem).Data).SR.Name; inherited DoEdited(AItem, S); end; procedure TFileIconView.DoEditing(AItem: TIconViewItem; var AllowEdit: Boolean); begin AllowEdit := (AItem <> nil) and (((AItem.Data <> nil) and (PFileInfo(AItem.Data).SR.Name <> UpDir)) or FCreatingDir); inherited DoEditing(AItem, AllowEdit); end; procedure TFileIconView.DoGetIconSize(Item: TIconViewItem; var Width, Height: Integer); begin if Assigned(Images) then begin Width := Images.Width; Height := Images.Height; end else begin Width := FIconProvider.Width; Height := FIconProvider.Height; end; end; procedure TFileIconView.DoGetImageIndex(item: TIconViewItem); begin if not Assigned(Images) then with Item do ImageIndex := FIconProvider.DoGetImageIndex(Item.Data) else inherited DoGetImageIndex(Item); end; function TFileIconView.FileFound(const SearchRec: TSearchRec): Boolean; begin Result := True; if Assigned(FOnFileFound) then FOnFileFound(Self, SearchRec, Result); end; function TFileIconView.GetSelections: TFileInfos; var I: Integer; begin { Do NOT free the returned pointers - they're live. } for I := 0 to Items.Count - 1 do if Items[I].Selected then begin SetLength(Result, Length(Result) + 1); Result[Length(Result)-1] := FDirectory.Files(I); end; end; procedure TFileIconView.GoDown; begin if (Selected <> nil) then begin if (PFileInfo(Selected.Data)^.SR.Attr and faDirectory <> 0) then {$IFDEF LINUX} Directory.Location := Directory.LinkName(Selected.Index); {$ENDIF} {$IFDEF MSWINDOWS} Directory.Location := Directory.Location + PathDelim + Selected.Caption else if PFileInfo(Selected.Data)^.SR.Attr and faVolumeID <> 0 then Directory.Location := PFileInfo(Selected.Data)^.SR.FindData.cFileName; {$ENDIF}; end; end; procedure TFileIconView.GoUp; var NewDir: WideString; begin {$IFDEF MSWINDOWS} if Directory.Location = '' then Exit; if IsDriveRoot(Directory.Location) then NewDir := '' else {$ENDIF} {$IFDEF LINUX} if Directory.Location = PathDelim then Exit; {$ENDIF} NewDir := ExpandDirectoryName(IncludeTrailingPathDelimiter(Directory.Location) + '..'); if NewDir <> Directory.Location then Directory.Location := NewDir; end; procedure TFileIconView.ImageChange; begin FDirectory.ListFiles(False); UpdateControl; end; procedure TFileIconView.ImageListChanged; begin Items.BeginUpdate; try ImageChange; finally Items.EndUpdate; end; end; procedure TFileIconView.InitWidget; begin inherited InitWidget; Spacing := 2; Sort := False; AllocSelectBmp; IconOptions.AutoArrange := True; Refresh; end; function TFileIconView.IsCustomDrawn: Boolean; begin Result := True; end; function TFileIconView.IsOwnerDrawn: Boolean; begin Result := False; end; procedure TFileIconView.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); if Key = Key_F5 then Refresh; end; procedure TFileIconView.KeyPress(var Key: Char); begin //TODO: F2 editing inherited KeyPress(Key); if not IsEditing then case Key of #8: GoUp; #13: GoDown; end; end; procedure TFileIconView.ListEnd; var I: Integer; NewItem: TIconViewItem; begin for I := 0 to FDirectory.Count - 1 do begin NewItem := Items.Add; NewItem.Data := FDirectory.Files(I); NewItem.Caption := FDirectory.Caption(I); NewItem.ImageIndex := 0; end; Screen.Cursor := FSaveCursor; Items.EndUpdate; end; function TFileIconView.ListStart: Boolean; begin Result := HandleAllocated and not (csLoading in ComponentState); if not Result then Exit; {$IFDEF MSWINDOWS} FDrivesListed := Directory.Location = ''; {$ENDIF} Application.CancelHint; Items.BeginUpdate; FSaveCursor := Screen.Cursor; Screen.Cursor := crHourglass; Items.Clear; end; procedure TFileIconView.Loaded; begin inherited Loaded; HandleNeeded; Refresh; end; procedure TFileIconView.MaskChange(const NewMask: WideString); begin if Assigned(FOnMaskChange) then FOnMaskChange(Self, NewMask); end; function TFileIconView.NeedKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; function IsNavKey: Boolean; begin Result := (Key = Key_Left) or (Key = Key_Right) or (Key = Key_Down) or (Key = Key_Up) or (Key = Key_Home) or (Key = Key_End) or (Key = Key_PageUp) or (Key = Key_PageDown); end; begin Result := inherited NeedKey(Key, Shift, KeyText); if not Result then Result := (isNavKey and (ssShift in Shift)) or (((Key = Key_Enter) or (Key = Key_Return)) and ((Selected <> nil) and (PFileInfo(Selected.Data).SR.Attr = faDirectory))); end; procedure TFileIconView.PositionEditor(var NewLeft, NewTop: Integer); begin if TextPosition = itpRight then Inc(NewLeft, IconPixels(IconSize)) else inherited PositionEditor(NewTop, NewLeft); end; procedure TFileIconView.Refresh; begin FDirectory.ListFiles(True); end; function TFileIconView.RenameFile(Item: TIconViewItem; const NewName: WideString): Integer; begin Result := 0; if (NewName = '') or (AnsiCompareFileName(Item.Caption, NewName) = 0) then Exit; Result := FDirectory.Rename(Item.Caption, NewName); case Result of RESULT_ACCESS_DENIED: Error(Format(SAccessDeniedTo, [Item.Caption])); RESULT_FILE_NOT_FOUND: Error(Format(SFileNameNotFound, [Item.Caption])); RESULT_ALREADY_EXISTS: Error(SAlreadyExists); else if (PFileInfo(Result).SR.Attr and faHidden <> 0) and not (ftHidden in FDirectory.FileType) then Item.Delete else begin Item.Data := Pointer(Result); Item.Caption := NewName; InvalidateRect(Item.BoundingRect, True); end; end; end; procedure TFileIconView.SetDirectory(const Value: TDirectory); begin FDirectory.Assign(Value); end; procedure TFileIconView.SetIconSize(const Value: TIconSize); begin if FIconSize <> Value then begin FIconSize := Value; case Value of isSmall: FIconProvider := IconProvider16; isLarge: FIconProvider := IconProvider32; isVeryLarge: FIconProvider := IconProvider48; end; ImageChange; end; end; initialization DirChangeList := TList.Create; finalization DirChangeList.Free; if Assigned(GIconProvider16) then FreeAndNil(GIconProvider16); if Assigned(GIconProvider32) then FreeAndNil(GIconProvider32); end.
unit UnTeleMarketing; {Verificado -.edit; } interface Uses Classes, UnDados, DBTables, SysUtils, Gauges,stdctrls, SQLExpr, Tabela; Type TRBFuncoesTeleMarketing = class private Aux, Clientes : TSQLQuery; Cadastro : TSQL; function RSeqTeleDisponivel(VpaCodFilial,VpaCodCliente : Integer):integer; function RSeqTeleProspectDisponivel(VpaCodProspect: Integer): Integer; function AtualizaDTelemarketingCliente(VpaDTeleMarketing : TRBDtelemarketing):String; procedure CarQtdDiaseDataProximaLigacao(VpaCodCliente : Integer;Var VpaQtdDias : Integer;Var VpaDProximaLigacao : TDateTime); public constructor cria(VpaBaseDados : TSQLConnection); destructor destroy;override; function GravaDTeleMarketing(VpaDTeleMarketing : TRBDTelemarketing) : String; function GravaDTeleMarketingProspect(VpaDTeleMarketingProspect: TRBDTelemarketingProspect): String; procedure AtualizaDiasTelemarketing(VpaMostrador :TGauge;VpaNomCliente :TLabel); function RQtdDiasProximaLigacao(VpaCodCliente : Integer):Integer; procedure ExcluiTelemarketing(VpaCodFilial, VpaCodCliente, VpaSeqTelemarketing : Integer); end; implementation Uses FunSql, UnClientes, funString,fundata, FunNumeros, UnProspect; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Funcoes do teleMarketing )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} constructor TRBFuncoesTeleMarketing.cria(VpaBaseDados : TSQLConnection); begin inherited create; Aux := TSQLQuery.create(nil); Aux.SQLConnection := VpaBaseDados; Clientes := TSQLQuery.Create(nil); Clientes.SQLConnection := VpaBaseDados;; Cadastro := TSQL.Create(nil); Cadastro.ASQLConnection := VpaBaseDados; end; {******************************************************************************} destructor TRBFuncoesTeleMarketing.destroy; begin Aux.close; Cadastro.close; Clientes.Close; Aux.free; Clientes.free; Cadastro.free; inherited destroy; end; {******************************************************************************} procedure TRBFuncoesTeleMarketing.ExcluiTelemarketing(VpaCodFilial, VpaCodCliente, VpaSeqTelemarketing: Integer); begin ExecutaComandoSql(Aux,'Delete from TELEMARKETING ' + ' Where CODFILIAL = ' +IntToStr(VpaCodFilial)+ ' AND SEQTELE = ' + IntToStr(VpaSeqTelemarketing)+ ' AND CODCLIENTE = ' +IntToStr(VpaCodCliente)); end; {******************************************************************************} function TRBFuncoesTeleMarketing.RSeqTeleDisponivel(VpaCodFilial,VpaCodCliente : Integer):integer; begin AdicionaSQLAbreTabela(Aux,'Select MAX(SEQTELE) ULTIMO from TELEMARKETING '+ ' Where CODFILIAL = '+IntToStr(VpaCodFilial)+ ' and CODCLIENTE = '+IntToStr(VpaCodCliente)); result := Aux.FieldByName('ULTIMO').AsInteger + 1; Aux.Close; end; {******************************************************************************} function TRBFuncoesTeleMarketing.RSeqTeleProspectDisponivel(VpaCodProspect: Integer): Integer; begin AdicionaSQLAbreTabela(Aux,'SELECT MAX(SEQTELE) PROXIMO FROM TELEMARKETINGPROSPECT '+ ' WHERE CODPROSPECT = '+IntToStr(VpaCodProspect)); Result:= Aux.FieldByName('PROXIMO').AsInteger + 1; Aux.Close; end; {******************************************************************************} function TRBFuncoesTeleMarketing.AtualizaDTelemarketingCliente(VpaDTeleMarketing : TRBDtelemarketing):String; begin result := ''; AdicionaSQLAbreTabela(Cadastro,'Select * from CADCLIENTES '+ ' Where I_COD_CLI = '+IntToStr(VpaDTeleMarketing.CodCliente)); Cadastro.Edit; Cadastro.FieldByName('C_OBS_TEL').AsString := VpaDTeleMarketing.DesObsProximaLigacao; if VpaDTeleMarketing.LanOrcamento = 0 then begin if VpaDTeleMarketing.IndAtendeu then Cadastro.FieldByName('I_QTD_LSV').AsInteger := Cadastro.FieldByName('I_QTD_LSV').AsInteger + 1 end else Cadastro.FieldByName('I_QTD_LCV').AsInteger := Cadastro.FieldByName('I_QTD_LCV').AsInteger + 1; Cadastro.FieldByName('D_ULT_TEL').AsDateTime := now; if VpaDTeleMarketing.IndProximaLigacao then Cadastro.FieldByName('D_PRO_LIG').AsDateTime := VpaDTeleMarketing.DatProximaLigacao else Cadastro.FieldByName('D_PRO_LIG').clear; if VpaDTeleMarketing.QtdDiasProximaLigacao <> 0 then Cadastro.FieldByName('I_DIA_PLI').AsInteger := VpaDTeleMarketing.QtdDiasProximaLigacao; try Cadastro.post; except on e : exception do result := 'ERRO NA ATUALIZAÇÃO DOS DADOS DO CLIENTE!!!!'#13+e.message; end; Cadastro.close; end; {******************************************************************************} procedure TRBFuncoesTeleMarketing.CarQtdDiaseDataProximaLigacao(VpaCodCliente : Integer;Var VpaQtdDias : Integer;Var VpaDProximaLigacao : TDateTime); var VpfQtdCompras, VpfTotalDias : Integer; VpfDatCotacao,VpfDatPrimeiraCotacao : TDateTime; begin VpaQtdDias := 30; VpaDProximaLigacao := date; AdicionaSQLAbreTabela(Aux,'Select D_DAT_ORC from CADORCAMENTOS '+ ' Where I_COD_CLI = '+InttoStr(VpaCodCliente)+ ' order by D_DAT_ORC desc'); if not Aux.Eof then begin VpfQtdCompras := 0; VpfTotalDias := 0; VpfDatPrimeiraCotacao := Aux.FieldByName('D_DAT_ORC').AsDatetime; VpfDatCotacao := Aux.FieldByName('D_DAT_ORC').AsDatetime; while not Aux.Eof do begin if VpfDatCotacao <> Aux.FieldByName('D_DAT_ORC').AsDateTime then begin inc(VpfQtdCompras); VpfTotalDias := VpfTotalDias +DiasPorPeriodo(VpfDatCotacao,Aux.FieldByName('D_DAT_ORC').AsDateTime); VpfDatCotacao := Aux.FieldByName('D_DAT_ORC').AsDateTime; if VpfQtdCompras > 10 then //so faz a media das 10 ultimas cotacoes Aux.last; end; Aux.Next; end; if VpfQtdCompras > 0 then begin VpaQtdDias := RetornaInteiro(VpfTotalDias / VpfQtdCompras); VpaDProximaLigacao := IncDia(VpfDatPrimeiraCotacao,VpaQtdDias); end; end; Aux.Close; end; {******************************************************************************} function TRBFuncoesTeleMarketing.GravaDTeleMarketing(VpaDTeleMarketing : TRBDTelemarketing) : String; begin result := ''; AdicionaSQLAbreTabela(Cadastro,'Select * from TELEMARKETING '+ ' Where CODFILIAL = 0 AND CODCLIENTE = 0 AND SEQTELE = 0'); Cadastro.Insert; Cadastro.FieldByName('CODFILIAL').AsInteger := VpaDTeleMarketing.CodFilial; Cadastro.FieldByName('CODCLIENTE').AsInteger := VpaDTeleMarketing.CodCliente; Cadastro.FieldByName('CODUSUARIO').AsInteger := VpaDTeleMarketing.CodUsuario; Cadastro.FieldByName('SEQCAMPANHA').AsInteger := VpaDTeleMarketing.SeqCampanha; if VpaDTeleMarketing.LanOrcamento <> 0 then Cadastro.FieldByName('LANORCAMENTO').AsInteger := VpaDTeleMarketing.LanOrcamento; Cadastro.FieldByName('CODHISTORICO').AsInteger := VpaDTeleMarketing.CodHistorico; Cadastro.FieldByName('DATLIGACAO').AsDatetime := VpaDTeleMarketing.DatLigacao; Cadastro.FieldByName('DESFALADOCOM').AsString := VpaDTeleMarketing.DesFaladoCom; Cadastro.FieldByName('DESOBSERVACAO').AsString := VpaDTeleMarketing.DesObservacao; Cadastro.FieldByName('QTDSEGUNDOSLIGACAO').AsInteger := VpaDTeleMarketing.QtdSegundosLigacao; Cadastro.FieldByName('DATTEMPOLIGACAO').AsDatetime := VpaDTeleMarketing.DatTempoLigacao; if VpaDTeleMarketing.CodVendedor <> 0 then Cadastro.FieldByName('CODVENDEDOR').AsInteger := VpaDTeleMarketing.CodVendedor; IF VpaDTeleMarketing.IndProximaLigacao then Cadastro.FieldByName('INDPROXIMALIGACAO').AsString := 'S' else Cadastro.FieldByName('INDPROXIMALIGACAO').AsString := 'N'; VpaDTeleMarketing.SeqTele := RSeqTeleDisponivel(VpaDTeleMarketing.CodFilial,VpaDTeleMarketing.CodCliente); Cadastro.FieldByName('SEQTELE').AsInteger := VpaDTeleMarketing.SeqTele; try Cadastro.post; except on e : exception do result := 'ERRO NA GRAVAÇÃO DA TABELA DO TELEMARKETING!!!'#13+e.message; end; Cadastro.close; if result = '' then AtualizaDTelemarketingCliente(VpaDTeleMarketing); end; {******************************************************************************} function TRBFuncoesTeleMarketing.GravaDTeleMarketingProspect(VpaDTeleMarketingProspect: TRBDTelemarketingProspect): String; begin Result:= ''; AdicionaSQLAbreTabela(Cadastro,'SELECT * FROM TELEMARKETINGPROSPECT ' + ' Where CODPROSPECT = 0 AND SEQTELE = 0 '); Cadastro.Insert; Cadastro.FieldByName('CODPROSPECT').AsInteger:= VpaDTeleMarketingProspect.CodProspect; if VpaDTeleMarketingProspect.CodUsuario = 0 then Cadastro.FieldByName('CODUSUARIO').Clear else Cadastro.FieldByName('CODUSUARIO').AsInteger:= VpaDTeleMarketingProspect.CodUsuario; Cadastro.FieldByName('DATLIGACAO').AsDateTime:= VpaDTeleMarketingProspect.DatLigacao; if VpaDTeleMarketingProspect.SeqProposta = 0 then begin Cadastro.FieldByName('CODFILIAL').Clear; Cadastro.FieldByName('SEQPROPOSTA').Clear; end else begin Cadastro.FieldByName('CODFILIAL').AsInteger:= VpaDTeleMarketingProspect.CodFilial; Cadastro.FieldByName('SEQPROPOSTA').AsInteger:= VpaDTeleMarketingProspect.SeqProposta; end; Cadastro.FieldByName('DESFALADOCOM').AsString:= VpaDTeleMarketingProspect.DesFaladoCom; Cadastro.FieldByName('DESOBSERVACAO').AsString:= VpaDTeleMarketingProspect.DesObservacao; if VpaDTeleMarketingProspect.CodHistorico = 0 then Cadastro.FieldByName('CODHISTORICO').Clear else Cadastro.FieldByName('CODHISTORICO').AsInteger:= VpaDTeleMarketingProspect.CodHistorico; Cadastro.FieldByName('QTDSEGUNDOSLIGACAO').AsInteger:= VpaDTeleMarketingProspect.QtdSegundosLigacao; Cadastro.FieldByName('DATTEMPOLIGACAO').AsDateTime:= VpaDTeleMarketingProspect.DataTempoLigacao; if VpaDTeleMarketingProspect.CodVendedor <> 0 then Cadastro.FieldByName('CODVENDEDOR').AsInteger:= VpaDTeleMarketingProspect.CodVendedor; VpaDTeleMarketingProspect.SeqTele := RSeqTeleProspectDisponivel(VpaDTeleMarketingProspect.CodProspect); Cadastro.FieldByName('SEQTELE').AsInteger:= VpaDTeleMarketingProspect.SeqTele; try Cadastro.post; except on E:Exception do Result:= 'ERRO NA GRAVAÇÃO DA TABELA DO TELEMARKETING DO PROSPECT!!!'#13+E.Message; end; Cadastro.Close; if result = '' then result := FunProspect.AtualizaDTElemarketing(VpaDTeleMarketingProspect); end; {******************************************************************************} procedure TRBFuncoesTeleMarketing.AtualizaDiasTelemarketing(VpaMostrador :TGauge;VpaNomCliente :TLabel); var VpfQtdDias : Integer; VpfDatProximaLigacao : TDateTime; begin VpaMostrador.MaxValue := FunClientes.RQtdClientes(''); VpaMostrador.Progress := 0; AdicionaSQLAbreTabela(Cadastro,'Select * from CADCLIENTES '); while not cadastro.Eof do begin VpaMostrador.AddProgress(1); VpaNomCliente.Caption := AdicionaCharD(' ',Cadastro.FieldByName('C_NOM_CLI').AsString,50); VpaNomCliente.Refresh; Cadastro.edit; CarQtdDiaseDataProximaLigacao(Cadastro.FieldByName('I_COD_CLI').AsInteger,VpfQtdDias,VpfDatProximaLigacao); if Cadastro.FieldByName('D_PRO_LIG').IsNull then Cadastro.FieldByName('D_PRO_LIG').AsDateTime := VpfDatProximaLigacao; Cadastro.FieldByName('I_DIA_PLI').AsInteger := VpfQtdDias; Cadastro.post; Cadastro.next; end; end; {******************************************************************************} function TRBFuncoesTeleMarketing.RQtdDiasProximaLigacao(VpaCodCliente : Integer):integer; var VpfDatProximaLigacao : TDateTime; begin CarQtdDiaseDataProximaLigacao(VpaCodCliente,result,VpfDatProximaLigacao); end; end.
unit Tests_OriControls; {$mode objfpc}{$H+} interface uses FpcUnit, TestRegistry; type TTest_OriControls = class(TTestCase) private procedure TextRectPaint(Sender: TObject); published procedure OriTabSet; procedure TextRect; procedure OriFloatEdit; end; implementation uses Classes, Forms, Controls, ExtCtrls, Graphics, OriTabs, OriEditors, WinPropEditor; procedure TTest_OriControls.OriTabSet; var TabSet: TOriTabSet; W: TWndPropEditor; begin W := ShowPropEditor; TabSet := TOriTabSet.Create(nil); TabSet.Parent := W; TabSet.Align := alClient; TabSet.Tabs.Add.Caption := 'Tab 1'; TabSet.Tabs.Add.Caption := 'Tab 2'; TabSet.Tabs.Add.Caption := 'Tab 3'; W.SetSelection(TabSet); end; procedure TTest_OriControls.TextRect; var W: TForm; pb: TPaintBox; begin W := TForm.CreateNew(Application.MainForm); W.Width := 400; W.Height := 400; pb := TPaintBox.Create(W); pb.Parent := W; pb.SetBounds(100, 100, 200, 200); pb.Anchors := [akTop, akLeft, akRight, akBottom]; pb.OnPaint := @TextRectPaint; W.Show; end; procedure TTest_OriControls.OriFloatEdit; var W: TWndPropEditor; E: TOriFloatEdit; begin W := ShowPropEditor; E := TOriFloatEdit.Create(nil); E.Parent := W; E.Left := 20; E.Top := 20; E.Width := 100; W.SetSelection(E); end; procedure TTest_OriControls.TextRectPaint(Sender: TObject); var pb: TPaintBox; Style: TTextStyle; TxtRect: TRect; begin pb := TPaintBox(Sender); TxtRect.Left := pb.Width div 4; TxtRect.Top := pb.Height div 4; TxtRect.Right := TxtRect.Left * 3; TxtRect.Bottom := TxtRect.Top * 3; pb.Canvas.Pen.Style := psSolid; pb.Canvas.Pen.Color := clRed; pb.Canvas.Rectangle(0, 0, pb.Width, pb.Height); pb.Canvas.Pen.Color := clBlue; pb.Canvas.Rectangle(TxtRect); Style.Opaque := True; // warning suppress FillChar(Style, SizeOf(TTextStyle), 0); Style.SingleLine := True; {%region 'Horizontal'} Style.Alignment := taCenter; Style.Layout := tlCenter; pb.Canvas.Font.Color := clBlack; pb.Canvas.TextRect(TxtRect, 0, 0, 'taCenter,tlCenter', Style); Style.Alignment := taLeftJustify; Style.Layout := tlCenter; pb.Canvas.Font.Color := clRed; pb.Canvas.TextRect(TxtRect, TxtRect.Left, 0, 'taLeft,tlCenter', Style); Style.Alignment := taRightJustify; Style.Layout := tlCenter; pb.Canvas.Font.Color := clBlue; pb.Canvas.TextRect(TxtRect, 0, 0, 'taRight,tlCenter', Style); Style.Alignment := taCenter; Style.Layout := tlTop; pb.Canvas.Font.Color := clFuchsia; pb.Canvas.TextRect(TxtRect, 0, TxtRect.Top, 'taCenter,tlTop', Style); Style.Alignment := taLeftJustify; Style.Layout := tlTop; pb.Canvas.Font.Color := clMaroon; pb.Canvas.TextRect(TxtRect, TxtRect.Left, TxtRect.Top, 'taLeft,tlTop', Style); Style.Alignment := taRightJustify; Style.Layout := tlTop; pb.Canvas.Font.Color := clTeal; pb.Canvas.TextRect(TxtRect, 0, TxtRect.Top, 'taRight,tlTop', Style); Style.Alignment := taCenter; Style.Layout := tlBottom; pb.Canvas.Font.Color := clGreen; pb.Canvas.TextRect(TxtRect, 0, 0, 'taCenter,tlBottom', Style); Style.Alignment := taLeftJustify; Style.Layout := tlBottom; pb.Canvas.Font.Color := clNavy; pb.Canvas.TextRect(TxtRect, TxtRect.Left, 0, 'taLeft,tlBottom', Style); Style.Alignment := taRightJustify; Style.Layout := tlBottom; pb.Canvas.Font.Color := clOlive; pb.Canvas.TextRect(TxtRect, 0, 0, 'taRight,tlBottom', Style); {%endregion} {%region 'Bottom to top'} // TODO: сделать процедуру для вывода вертикального текста // или найти готовую. Поведение Canvas.TextRect неожиданное // при повернутом шрифте и отличается от то того что делает // виндовая процедура с аналогичными настройками (проверить) pb.Canvas.Font.Orientation := 900; Style.Alignment := taCenter; Style.Layout := tlCenter; pb.Canvas.Font.Color := clBlack; pb.Canvas.TextRect(TxtRect, 0, 0, 'taCenter,tlCenter', Style); Style.Alignment := taLeftJustify; Style.Layout := tlCenter; pb.Canvas.Font.Color := clRed; pb.Canvas.TextRect(TxtRect, TxtRect.Left, 0, 'taLeft,tlCenter', Style); Style.Alignment := taRightJustify; Style.Layout := tlCenter; pb.Canvas.Font.Color := clBlue; pb.Canvas.TextRect(TxtRect, 0, 0, 'taRight,tlCenter', Style); Style.Alignment := taCenter; Style.Layout := tlTop; pb.Canvas.Font.Color := clFuchsia; pb.Canvas.TextRect(TxtRect, 0, TxtRect.Top, 'taCenter,tlTop', Style); Style.Alignment := taLeftJustify; Style.Layout := tlTop; pb.Canvas.Font.Color := clMaroon; pb.Canvas.TextRect(TxtRect, TxtRect.Left, TxtRect.Top, 'taLeft,tlTop', Style); Style.Alignment := taRightJustify; Style.Layout := tlTop; pb.Canvas.Font.Color := clTeal; pb.Canvas.TextRect(TxtRect, 0, TxtRect.Top, 'taRight,tlTop', Style); Style.Alignment := taCenter; Style.Layout := tlBottom; pb.Canvas.Font.Color := clGreen; pb.Canvas.TextRect(TxtRect, 0, 0, 'taCenter,tlBottom', Style); Style.Alignment := taLeftJustify; Style.Layout := tlBottom; pb.Canvas.Font.Color := clNavy; pb.Canvas.TextRect(TxtRect, TxtRect.Left, 0, 'taLeft,tlBottom', Style); Style.Alignment := taRightJustify; Style.Layout := tlBottom; pb.Canvas.Font.Color := clOlive; pb.Canvas.TextRect(TxtRect, 0, 0, 'taRight,tlBottom', Style); {%endregion} end; initialization RegisterTest(TTest_OriControls); end.
unit uSTXLogic; interface uses System.Classes, System.UITypes,System.SysUtils, System.Types,System.Generics.Collections, FMX.Dialogs,FMX.Types, uPublic, uEngine2DModel, uEngine2DSprite,uEngine2DExtend,Math; const ANIMATION_INTERVAL = 100; ANIMATION_TOTAL_COUNT = 8; FULL_STAR = 'x-1.png'; HALF_STAR = 'x-3.png'; EMPTY_STAR = 'x-2.png'; SHOW_STAR_COUNT = 7; Type TSTXLogic = class(TLogicWithStar) private FCurrentDragSprite : TEngine2DSprite; FDstPoint : TPointF; FOriDstPoint : TPointF; FInfluName : String; // 待验证的精灵名 FEntered : boolean; //是否进入了验证区域 FCurConfigName : String; //当前读取的配置文件名 FCurAniCount : Integer; // 用于计数当前动画播放帧 FResultMap : TDictionary<String,Integer>; function CheckIfFinishCurrent:boolean; procedure PlayAnimation(AIsRight:boolean); procedure OnNextTimer(Sender :TObject); override; procedure OnAnimationTimer(Sender : TObject); procedure ReadScoreFromLocal; procedure UpdateStarStatus; protected procedure CopySpriteFromSrc(ASprite : TEngine2DSprite); procedure NextSight;override; procedure ClearAll; public Destructor Destroy; override; procedure Init;override; procedure MouseDownHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);override; procedure MouseMoveHandler(Sender: TObject; Shift: TShiftState; X, Y: Single);override; procedure MouseUpHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);override; end; implementation uses uEngine2DInvade,uEngine2DObject,uEngineUtils,AniMain; { TSTXLogic } function TSTXLogic.CheckIfFinishCurrent: boolean; var item : TPair<String,Integer>; begin result := true; for item in FResultMap do begin if item.Value = 1 then begin result := false; exit; end; end; end; procedure TSTXLogic.ClearAll; var LStr,S :String; begin FResultMap.Clear; FCurrentDragSprite := nil; FEntered := false; LStr := FIndexList.Strings[FCurIndex]; FCurConfigName := GetHeadString(LStr,'`'); S := GetHeadString(LStr,'`'); while S.Trim <> '' do begin FResultMap.Add(GetHeadString(S,' '),1); end; end; procedure TSTXLogic.CopySpriteFromSrc(ASprite: TEngine2DSprite); var LParentSprite : TEngine2DSprite; LTmpObject : TEngine2DObject; LSrcImage,LD1Image : TEngine2DImage; LTmpImage :TEngine2DImageEX; begin LSrcImage := TEngine2DImage(ASprite.Children.Items[0]); LParentSprite := FEngineModel.SpriteList.Has('heiban'); LD1Image := TEngine2DImage(LParentSprite.Children.Has('d1')); LTmpImage := TEngine2DImageEX.Create(LParentSprite.BackDrawCanvas); LTmpImage.SpriteName := 'cp_'+ASprite.Name; LTmpImage.ImageStatus := LSrcImage.ImageStatus; //保留原Sprite的图片状态 LTmpImage.Align := GetAlignNew('4'); //oaScale LTmpImage.Visible := true; LTmpImage.InitWidth := ASprite.Position.InitWidth ; // 副本Sprite的初始宽度与源Srpite的初始宽度相同 LTmpImage.InitHeight := ASprite.Position.InitHeight ; LTmpImage.InitX := FOriDstPoint.X ; // 该坐标为相对于 LParentSprite的坐标 LTmpImage.InitY := FOriDstPoint.Y ; LTmpImage.X := FDstPoint.X - LParentSprite.X; //FDstPoint.X为全局坐标,LTmpImage.X的坐标为相对ParentSprite.X,所以要相减 LTmpImage.Y := FDstPoint.Y - LParentSprite.Y; LTmpImage.Width := LSrcImage.Width; LTmpImage.Height := LSrcImage.Height; LTmpImage.ResManager := LSrcImage.ResManager; LTmpImage.InvadeManager := LSrcImage.InvadeManager; LTmpImage.ImageConfig := LSrcImage.ImageConfig; LParentSprite.Children.Add(LTmpImage.SpriteName,LTmpImage); end; destructor TSTXLogic.Destroy; begin if Assigned(FResultMap) then FResultMap.DisposeOf; // if Assigned(FNextTimer) then // FNextTimer.DisposeOf; // if Assigned(FAnimationTimer) then // FAnimationTimer.DisposeOf; inherited; end; procedure TSTXLogic.Init; var LStr,S :String; begin if Not Assigned(FResultMap) then FResultMap := TDictionary<String,Integer>.Create else FResultMap.Clear; FFullStarName := FULL_STAR; FHalfStarName := HALF_STAR; FEmptyStarName := EMPTY_STAR; ClearAll; ReadScoreFromLocal; end; procedure TSTXLogic.MouseDownHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); var LSprite :TEngine2DSprite; begin if Sender.ClassName.Equals('TEngine2DSprite') then begin LSprite := TEngine2DSprite(Sender); if LSprite.Drag then begin FEngineModel.BringToFront(LSprite); FCurrentDragSprite := LSprite; end; end; end; procedure TSTXLogic.MouseMoveHandler(Sender: TObject; Shift: TShiftState; X, Y: Single); var LSprite : TEngine2DSprite; LCon : TConvexPolygon; begin if Sender.ClassName.Equals('TEngine2DSprite') then begin if FCurrentDragSprite <> Sender then exit; LSprite := TEngine2DSprite(Sender); if (LSprite.Drag) and (LSprite.MouseIsDown) then begin LSprite.X := LSprite.InitPosition.X + (X - LSprite.MouseDownPoint.X); LSprite.Y := LSprite.InitPosition.Y + (Y - LSprite.MouseDownPoint.Y); end; LCon := FEngineModel.InvadeManager.GetInvadeObject(FCurrentDragSprite.GetConvexPoints); if (LCon <> nil) and (LCon.InfluenceName.Equals(LSprite.Name)) then begin FInfluName := LCon.InfluenceName; FDstPoint := LCon.DstPoint; FOriDstPoint := LCon.OriDstPoint; FEntered := true; end else begin FEntered := false; FInfluName := ''; FDstPoint.Zero; FOriDstPoint.Zero; end; end; end; procedure TSTXLogic.MouseUpHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); var LSprite,LParentSprite : TEngine2DSprite; LTmpObject : TEngine2DObject; LSrcImage,LD1Image : TEngine2DImage; LTmpImage :TEngine2DImageEX; begin if Sender.ClassName.Equals('TEngine2DSprite') then begin if FCurrentDragSprite <> Sender then exit; LSprite := TEngine2DSprite(Sender); if (LSprite.Drag) and (LSprite.MouseIsDown) then begin if FEntered then begin LSprite.Visible := false; CopySpriteFromSrc(LSprite); FEntered := false; FResultMap.AddOrSetValue(LSprite.Name,0); if CheckIfFinishCurrent then begin FNextTimer.Enabled := true; PlayAnimation(true); PlayStarAnimationWhenDone(SHOW_STAR_COUNT); end; end else begin LSprite.CreateResetAnimation; PlayAnimation(false); end; LSprite.MouseIsDown := false; end; FCurrentDragSprite := nil; end; end; procedure TSTXLogic.NextSight; begin inc(FCurIndex); if FCurIndex >= TotalCount then exit; ClearAll; FEngineModel.LoadNextConfig(FCurConfigName); inherited; end; procedure TSTXLogic.OnAnimationTimer(Sender: TObject); var LParentSprite : TEngine2DSprite; L2DImage : TEngine2DImage; begin // inc(FCurAniCount); // if FCurAniCount > ANIMATION_TOTAL_COUNT then // begin // FCurAniCount := 0; // FAnimationTimer.Enabled := false; // LParentSprite := FEngineModel.SpriteList.Has('heiban'); // L2DImage := TEngine2DImage(LParentSprite.Children.Has('image1')); // L2DImage.ImageConfig.SwitchNormalControlerByName('Normal'); // end; end; procedure TSTXLogic.OnNextTimer(Sender: TObject); begin FNextTimer.Enabled := false; NextSight; end; procedure TSTXLogic.PlayAnimation(AIsRight: boolean); var LParentSprite : TEngine2DSprite; L2DImage : TEngine2DImage; LFinishProc : TProc; begin // if Not Assigned(FAnimationTimer) then // begin // FAnimationTimer := TTimer.Create(nil); // FAnimationTimer.Interval := ANIMATION_INTERVAL; // FAnimationTimer.OnTimer := OnAnimationTimer; // FAnimationTimer.Enabled := false; // end; // FCurAniCount := 0; // FAnimationTimer.Enabled := true; LParentSprite := FEngineModel.SpriteList.Has('heiban'); L2DImage := TEngine2DImage(LParentSprite.Children.Has('image1')); LFinishProc := procedure begin // LParentSprite := FEngineModel.SpriteList.Has('heiban'); // L2DImage := TEngine2DImage(LParentSprite.Children.Has('image1')); L2DImage.ImageConfig.SwitchNormalControlerByName('Normal',nil); end; if AIsRight then L2DImage.ImageConfig.SwitchNormalControlerByName('right',LFinishProc) else L2DImage.ImageConfig.SwitchNormalControlerByName('wrong',LFinishProc); // FIsCorrect := AIsRight; end; //procedure TSTXLogic.PlayStarAnimationWhenDone; //var // LSprite : TEngine2DSprite; // LPoint : TPointF; //begin // inc(FStarCount); // if (FStarCount div 2) > SHOW_STAR_COUNT then // begin // FStarCount := SHOW_STAR_COUNT * 2; // exit; // end; // LSprite := UpdateASingleStarStatus(Math.Ceil(FStarCount/2.0)); // if LSprite <> nil then // begin // LPoint.X := LSprite.Position.InitWidth/2; // LPoint.Y := LSprite.Position.InitHeight/2; // LSprite.CreateRotateAnimation(0,360,false,300,LPoint); // end; //end; procedure TSTXLogic.ReadScoreFromLocal; begin FStarCount := 3; UpdateStarStatus; end; procedure TSTXLogic.UpdateStarStatus; var i: Integer; begin if Not Assigned(FEngineModel) then raise Exception.Create('FEngineModel is Not Assigned,FEngineModel Should be Used After Engine Create'); for i := 1 to SHOW_STAR_COUNT do begin UpdateASingleStarStatus(i); end; end; Initialization RegisterLogicUnit(TSTXLogic,'STXLogic'); end.
unit clsTDBUtils; interface {$M+} uses System.SysUtils, System.Classes, Data.DB, Data.DBCommonTypes, Uni, DBAccess, Postgresqluniprovider; type TColDevQuery = class(TUniQuery); TColDevConnection = class(TUniConnection); TDBUtils = class private FConexao: TColDevConnection; FStringDeConexao: String; FOwner: TComponent; procedure SetConexao(const Value: TColDevConnection); procedure SetOwner(const Value: TComponent); public constructor Create; overload; constructor Create(StringDeConexao: String); overload; constructor Create(Conexao: TColDevConnection); overload; property Owner: TComponent read FOwner write SetOwner; property Conexao: TColDevConnection read FConexao write SetConexao; published function QueryFactory(const Statement: String; OpenIt: Boolean = False): TColDevQuery; function ResetQuery(var Query: TColDevQuery): Boolean; function SetQuery(var Query: TColDevQuery; const Statement: String): Boolean; end; implementation { TDBUtils } constructor TDBUtils.Create(StringDeConexao: String); var strl: TStringList; begin if StringDeConexao = EmptyStr then begin strl:=TStringList.Create; strl.LoadFromFile('connectionstring.cfg'); Self.FConexao := TColDevConnection.Create(nil); Self.FConexao.ConnectString := strl.Text; // 'Provider Name=PostgreSQL;Login Prompt=False;Data Source=192.168.0.116;User ID=postgres;Password=bitnami;Database=WeBuy;Port=5432'; FreeAndNil(strl); end else begin Self.FStringDeConexao := StringDeConexao; end; try Self.FConexao.AutoCommit := True; Self.FConexao.Connect; except on E:Exception do begin raise Exception.Create('Erro de conex„o com o banco de dados com a mensagem : '+E.Message); end; end; end; constructor TDBUtils.Create; var strl: TStringList; begin try strl:=TStringList.Create; strl.LoadFromFile('connectionstring.cfg'); Self.FConexao := TColDevConnection.Create(nil); Self.FConexao.ConnectString := strl.Text; Self.FConexao.AutoCommit := True; Self.FConexao.Connect; except end; FreeAndNil(strl); end; constructor TDBUtils.Create(Conexao: TColDevConnection); begin Self.FConexao := Conexao; end; function TDBUtils.QueryFactory(const Statement: String; OpenIt: Boolean = False): TColDevQuery; begin Result := TColDevQuery.Create(Self.Owner); Result.Connection := Self.Conexao; if not Result.Connection.Connected then Result.Connection.Connect; Result.SQL.Add(Statement); if OpenIt then Result.Open; end; function TDBUtils.ResetQuery(var Query: TColDevQuery): Boolean; begin Result := False; try Query.Close; Query.SQL.Clear; Result := True; except end; end; procedure TDBUtils.SetConexao(const Value: TColDevConnection); begin FConexao := Value; end; procedure TDBUtils.SetOwner(const Value: TComponent); begin FOwner := Value; end; function TDBUtils.SetQuery(var Query: TColDevQuery; const Statement: String): Boolean; begin Result := False; try Self.ResetQuery(query); query.SQL.Add(Statement); Result := True; except end; end; end.
unit UParamEditors; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Spin, ExtCtrls, StdCtrls, Controls, FPCanvas, typinfo, UInspector, LCLType, Graphics, math, UBaseShape, Buttons; type { TIntegerEditor } TIntegerEditor = class(TParamEditor) private FSpinEdit: TSpinEdit; procedure Change(Sender: TObject); override; procedure Refresh; public constructor Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); override; destructor Destroy; override; end; { TPenStyleEditor } TPenStyleEditor = class(TParamEditor) private FComboBox: TComboBox; procedure ComboBoxDrawItem(AControl: TWinControl; AIndex: Integer; ARect: TRect; AState: TOwnerDrawState); procedure Change(Sender: TObject); override; procedure Refresh; public constructor Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); override; destructor Destroy; override; end; { TBrushStyleEditor } TBrushStyleEditor = class(TParamEditor) private FComboBox: TComboBox; procedure ComboBoxDrawItem(AControl: TWinControl; AIndex: Integer; ARect: TRect; AState: TOwnerDrawState); procedure Change(Sender: TObject); override; procedure Refresh; public constructor Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); override; destructor Destroy; override; end; { TPositionEditor } TPositionEditor = class abstract(TParamEditor) private FButton: TSpeedButton; public constructor Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); override; destructor Destroy; override; end; { TLeftEditor } TLeftEditor = class(TPositionEditor) private procedure Change(Sender: TObject); override; public constructor Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); override; end; { TRightEditor } TRightEditor = class(TPositionEditor) private procedure Change(Sender: TObject); override; public constructor Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); override; end; { TTopEditor } TTopEditor = class(TPositionEditor) private procedure Change(Sender: TObject); override; public constructor Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); override; end; { TBottomEditor } TBottomEditor = class(TPositionEditor) private procedure Change(Sender: TObject); override; public constructor Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); override; end; var Inspector: TInspector; implementation var PropValues : TStringList; { TBottomEditor } procedure TBottomEditor.Change(Sender: TObject); var i: Integer; bottom: Double; begin bottom := FShapes[0].TrueRect.Bottom; for i := 1 to High(FShapes) do bottom := Max(bottom, FShapes[i].TrueRect.Bottom); for i := 0 to High(FShapes) do SetFloatProp(FShapes[i], FPropInfo, bottom); inherited Change(Sender); end; constructor TBottomEditor.Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); begin inherited Create(AShapes, APropInfo, APanel, ADefaultParams); FButton.Caption := 'Align to the bottom'; end; { TTopEditor } procedure TTopEditor.Change(Sender: TObject); var i: Integer; top: Double; begin top := FShapes[0].TrueRect.Top; for i := 1 to High(FShapes) do top := Min(top, FShapes[i].TrueRect.Top); for i := 0 to High(FShapes) do SetFloatProp(FShapes[i], FPropInfo, top); inherited Change(Sender); end; constructor TTopEditor.Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); begin inherited Create(AShapes, APropInfo, APanel, ADefaultParams); FButton.Caption := 'Align to the top'; end; { TRightEditor } procedure TRightEditor.Change(Sender: TObject); var i: Integer; right: Double; begin right := FShapes[0].TrueRect.Right; for i := 1 to High(FShapes) do right := Max(right, FShapes[i].TrueRect.Right); for i := 0 to High(FShapes) do SetFloatProp(FShapes[i], FPropInfo, right); inherited Change(Sender); end; constructor TRightEditor.Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); begin inherited Create(AShapes, APropInfo, APanel, ADefaultParams); FButton.Caption := 'Align to the right'; end; { TLeftEditor } procedure TLeftEditor.Change(Sender: TObject); var i: Integer; left: Double; begin left := FShapes[0].TrueRect.Left; for i := 1 to High(FShapes) do left := Min(left, FShapes[i].TrueRect.Left); for i := 0 to High(FShapes) do SetFloatProp(FShapes[i], FPropInfo, left); inherited Change(Sender); end; constructor TLeftEditor.Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); begin inherited Create(AShapes, APropInfo, APanel, ADefaultParams); FButton.Caption := 'Align to the left'; end; { TPositionEditor } constructor TPositionEditor.Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); var i: Integer; begin SetLength(FShapes, Length(AShapes)); for i := 0 to High(AShapes) do FShapes[i] := AShapes[i]; FPropInfo := APropInfo; FButton := TSpeedButton.Create(nil); FButton.Top := APanel.Tag; FButton.Left := 10; FButton.Width := APanel.Width - 20; FButton.Height := 30; FButton.OnClick := @Change; FButton.Parent := APanel; APanel.Tag := APanel.Tag + 35; end; destructor TPositionEditor.Destroy; begin FButton.Free; end; { TBrushStyleEditor } procedure TBrushStyleEditor.ComboBoxDrawItem(AControl: TWinControl; AIndex: Integer; ARect: TRect; AState: TOwnerDrawState); var combobox: TCombobox; begin combobox := TCombobox(AControl); combobox.Canvas.Brush.Color := clWhite; if odFocused in AState then combobox.Canvas.Brush.Color := cl3DLight; combobox.Canvas.FillRect(ARect); combobox.Canvas.Brush.Color := clBlack; combobox.Canvas.Brush.Style := TFPBrushStyle(combobox.Items.Objects[AIndex]); combobox.Canvas.FillRect(ARect); end; procedure TBrushStyleEditor.Change(Sender: TObject); var i: integer; begin for i:= 0 to High(FShapes) do SetInt64Prop(FShapes[i], FPropInfo, FComboBox.ItemIndex); PropValues.Values[FPropInfo^.Name]:= IntToStr(FComboBox.ItemIndex); inherited Change(Sender); end; constructor TBrushStyleEditor.Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); var i: TFPBrushStyle; j: integer; begin FComboBox := TComboBox.Create(nil); for i in TFPBrushStyle do if not (i in [bsImage, bsPattern]) then FComboBox.AddItem('', TShape(i)); FComboBox.OnDrawItem := @ComboBoxDrawItem; FComboBox.OnChange := @Change; FComboBox.Style := csOwnerDrawFixed; FComboBox.ReadOnly := True; FComboBox.Top := APanel.Tag; FComboBox.Left := trunc(APanel.Width / 2) + 10; FComboBox.Width := trunc(APanel.Width / 2) - 20; FComboBox.Parent := APanel; inherited Create(AShapes, APropInfo, APanel, ADefaultParams); if ADefaultParams then for j:= 0 to High(FShapes) do SetInt64Prop(FShapes[j], FPropInfo, StrToInt64(PropValues.Values[FPropInfo^.Name])); Refresh; end; destructor TBrushStyleEditor.Destroy; begin FComboBox.Free; inherited Destroy; end; procedure TBrushStyleEditor.Refresh; var i: integer; begin FComboBox.ItemIndex := GetInt64Prop(FShapes[0], FPropInfo); for i := 1 to High(FShapes) do if GetInt64Prop(FShapes[i], FPropInfo) <> FComboBox.ItemIndex then begin FComboBox.ItemIndex := -1; Exit; end; end; { TPenStyleEditor } procedure TPenStyleEditor.ComboBoxDrawItem(AControl: TWinControl; AIndex: Integer; ARect: TRect; AState: TOwnerDrawState); var combobox: TComboBox; begin combobox := TComboBox(AControl); combobox.Canvas.Brush.Color := clWhite; if odFocused in AState then combobox.Canvas.Brush.Color := cl3DLight; combobox.Canvas.FillRect(ARect); combobox.Canvas.Pen.Color := clBlack; combobox.Canvas.Pen.Style := TFPPenStyle(combobox.Items.Objects[AIndex]); combobox.Canvas.Line( ARect.Left, (ARect.Bottom + ARect.Top) div 2, ARect.Right, (ARect.Bottom + ARect.Top) div 2); end; procedure TPenStyleEditor.Change(Sender: TObject); var i: integer; begin for i:= 0 to High(FShapes) do SetInt64Prop(FShapes[i], FPropInfo, FComboBox.ItemIndex); PropValues.Values[FPropInfo^.Name]:= IntToStr(FComboBox.ItemIndex); inherited Change(Sender); end; constructor TPenStyleEditor.Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); var i: TFPPenStyle; j: integer; begin FComboBox := TComboBox.Create(nil); for i in TFPPenStyle do if not (i in [psinsideFrame, psPattern, psClear]) then FComboBox.AddItem('', TShape(i)); FComboBox.OnDrawItem := @ComboBoxDrawItem; FComboBox.OnChange := @Change; FComboBox.Style := csOwnerDrawFixed; FComboBox.ReadOnly := True; FComboBox.Top := APanel.Tag; FComboBox.Left := trunc(APanel.Width / 2) + 10; FComboBox.Width := trunc(APanel.Width / 2) - 20; FComboBox.Parent := APanel; inherited Create(AShapes, APropInfo, APanel, ADefaultParams); if ADefaultParams then for j := 0 to high(FShapes) do SetInt64Prop(FShapes[j], FPropInfo, StrToInt64(PropValues.Values[FPropInfo^.Name])); Refresh; end; destructor TPenStyleEditor.Destroy; begin FComboBox.Free; inherited Destroy; end; procedure TPenStyleEditor.Refresh; var i: integer; begin FComboBox.ItemIndex := GetInt64Prop(FShapes[0], FPropInfo); for i := 1 to High(FShapes) do if GetInt64Prop(FShapes[i], FPropInfo) <> FComboBox.ItemIndex then begin FComboBox.ItemIndex := -1; Exit; end; end; { TIntegerEditor } procedure TIntegerEditor.Change(Sender: TObject); var i: integer; begin for i:= 0 to High(FShapes) do SetInt64Prop(FShapes[i], FPropInfo, TSpinEdit(Sender).Value); PropValues.Values[FPropInfo^.Name]:= IntToStr(TSpinEdit(Sender).Value); inherited Change(Sender); end; constructor TIntegerEditor.Create(AShapes: array of TShape; APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean); var i: integer; begin FSpinEdit := TSpinEdit.Create(nil); FSpinEdit.MinValue := 1; FSpinEdit.MaxValue := 100; FSpinEdit.Width:= trunc(APanel.Width / 2) - 20; FSpinEdit.Left:= trunc(APanel.Width / 2) + 10; FSpinEdit.Top:= APanel.Tag; FSpinEdit.Parent:= APanel; inherited Create(AShapes, APropInfo, APanel, ADefaultParams); if ADefaultParams then for i:= 0 to High(FShapes) do SetInt64Prop(FShapes[i], FPropInfo, StrToInt64(PropValues.Values[FPropInfo^.Name])); Refresh; FSpinEdit.OnChange := @Change; end; destructor TIntegerEditor.Destroy; begin FSpinEdit.Free; inherited Destroy; end; procedure TIntegerEditor.Refresh; var i: Integer; begin FSpinEdit.Value := GetInt64Prop(FShapes[0], FPropInfo); for i := 1 to High(FShapes) do if GetInt64Prop(FShapes[i], FPropInfo) <> FSpinEdit.Value then begin FSpinEdit.Text := ''; Exit; end; end; initialization EditorContainer.RegisterEditor(TIntegerEditor, 'TPenWidth'); EditorContainer.RegisterEditor(TIntegerEditor, 'TRadius'); EditorContainer.RegisterEditor(TPenStyleEditor, 'TFPPenStyle'); EditorContainer.RegisterEditor(TBrushStyleEditor, 'TFPBrushStyle'); ShiftEditorContainer.RegisterEditor(TLeftEditor, 'TLeft'); ShiftEditorContainer.RegisterEditor(TRightEditor, 'TRight'); ShiftEditorContainer.RegisterEditor(TTopEditor, 'TTop'); ShiftEditorContainer.RegisterEditor(TBottomEditor, 'TBottom'); PropValues := TStringList.Create; PropValues.Values['PenWidth'] := '1'; PropValues.Values['PenStyle'] := '0'; PropValues.Values['BrushStyle'] := '1'; PropValues.Values['RadiusX'] := '50'; PropValues.Values['RadiusY'] := '50'; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLApplicationFileIO<p> Components and fonction that abstract file I/O access for an application.<br> Allows re-routing file reads to reads from a single archive file f.i.<p> <b>History : </b><font size=-1><ul> <li>10/11/12 - PW - Added CPPB compatibility: used TAFIOFileStreamEvent as procedure instead of function using GLS_CPPB define <li>25/08/10 - DaStr - Fixed compiler warnings <li>25/07/10 - Yar - Added TGLSResourceStream class and CreateResourceStream string <li>23/01/10 - Yar - Change LoadFromStream to dynamic <li>29/01/07 - DaStr - Moved registration to GLSceneRegister.pas <li>02/08/04 - LR, YHC - BCB corrections: fixed BCB Compiler error "E2370 Simple type name expected" <li>05/06/03 - EG - TDataFile moved in from GLMisc <li>31/01/03 - EG - Added FileExists mechanism <li>21/11/02 - EG - Creation </ul></font> } unit GLApplicationFileIO; interface {$I GLScene.inc} uses Windows, Classes, SysUtils, GLBaseClasses, GLSLog; const GLS_RC_DDS_Type = RT_RCDATA; GLS_RC_JPG_Type = RT_RCDATA; GLS_RC_XML_Type = RT_RCDATA; GLS_RC_String_Type = RT_RCDATA; type TGLSApplicationResource = ( aresNone, aresSplash, aresTexture, aresMaterial, aresSampler, aresFont, aresMesh); // TAFIOCreateFileStream // TAFIOCreateFileStream = function(const fileName: string; mode: Word): TStream; // TAFIOFileStreamExists // TAFIOFileStreamExists = function(const fileName: string): Boolean; // TAFIOFileStreamEvent // TAFIOFileStreamEvent = procedure (const fileName : String; mode : Word;var stream : TStream) of object; // TAFIOFileStreamExistsEvent // TAFIOFileStreamExistsEvent = function(const fileName: string): Boolean of object; // TGLApplicationFileIO // {: Allows specifying a custom behaviour for GLApplicationFileIO's CreateFileStream.<p> The component should be considered a helper only, you can directly specify a function via the vAFIOCreateFileStream variable.<br> If multiple TGLApplicationFileIO components exist in the application, the last one created will be the active one. } TGLApplicationFileIO = class(TComponent) private { Private declarations } FOnFileStream: TAFIOFileStreamEvent; FOnFileStreamExists: TAFIOFileStreamExistsEvent; protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } {: Event that allows you to specify a stream for the file.<p> Destruction of the stream is at the discretion of the code that invoked CreateFileStream. Return nil to let the default mechanism take place (ie. attempt a regular file system access). } property OnFileStream: TAFIOFileStreamEvent read FOnFileStream write FOnFileStream; {: Event that allows you to specify if a stream for the file exists.<p> } property OnFileStreamExists: TAFIOFileStreamExistsEvent read FOnFileStreamExists write FOnFileStreamExists; end; // TDataFileCapabilities // TDataFileCapability = (dfcRead, dfcWrite); TDataFileCapabilities = set of TDataFileCapability; // TDataFile // {: Abstract base class for data file formats interfaces.<p> This class declares base file-related behaviours, ie. ability to load/save from a file or a stream.<p> It is highly recommended to overload ONLY the stream based methods, as the file-based one just call these, and stream-based behaviours allow for more enhancement (such as other I/O abilities, compression, cacheing, etc.) to this class, without the need to rewrite subclasses. } TDataFile = class(TGLUpdateAbleObject) private { Private Declarations } FResourceName: string; procedure SetResourceName(const AName: string); public { Public Declarations } {: Describes what the TDataFile is capable of.<p> Default value is [dfcRead]. } class function Capabilities: TDataFileCapabilities; virtual; {: Duplicates Self and returns a copy.<p> Subclasses should override this method to duplicate their data. } function CreateCopy(AOwner: TPersistent): TDataFile; dynamic; procedure LoadFromFile(const fileName: string); dynamic; procedure SaveToFile(const fileName: string); dynamic; procedure LoadFromStream(stream: TStream); dynamic; procedure SaveToStream(stream: TStream); dynamic; procedure Initialize; dynamic; {: Optionnal resource name.<p> When using LoadFromFile/SaveToFile, the filename is placed in it, when using the Stream variants, the caller may place the resource name in it for parser use. } property ResourceName: string read FResourceName write SetResourceName; end; TDataFileClass = class of TDataFile; TGLSResourceStream = TResourceStream; //: Returns true if an GLApplicationFileIO has been defined function ApplicationFileIODefined: Boolean; {: Creates a file stream corresponding to the fileName.<p> If the file does not exists, an exception will be triggered.<br> Default mechanism creates a regular TFileStream, the 'mode' parameter is similar to the one for TFileStream. } function CreateFileStream(const fileName: string; mode: Word = fmOpenRead + fmShareDenyNone): TStream; {: Queries is a file stream corresponding to the fileName exists.<p> } function FileStreamExists(const fileName: string): Boolean; {: Create a resource stream. } function CreateResourceStream(const ResName: string; ResType: PChar): TGLSResourceStream; function StrToGLSResType(const AStrRes: string): TGLSApplicationResource; var vAFIOCreateFileStream: TAFIOCreateFileStream = nil; vAFIOFileStreamExists: TAFIOFileStreamExists = nil; // --------------------------------------------------------------------- // --------------------------------------------------------------------- // --------------------------------------------------------------------- implementation // --------------------------------------------------------------------- // --------------------------------------------------------------------- // --------------------------------------------------------------------- var vAFIO: TGLApplicationFileIO = nil; // ApplicationFileIODefined // function ApplicationFileIODefined: Boolean; begin Result := (Assigned(vAFIOCreateFileStream) and Assigned(vAFIOFileStreamExists)) or Assigned(vAFIO); end; // CreateFileStream // function CreateFileStream(const fileName: string; mode: Word = fmOpenRead + fmShareDenyNone): TStream; begin if Assigned(vAFIOCreateFileStream) then Result := vAFIOCreateFileStream(fileName, mode) else begin Result:=nil; if Assigned(vAFIO) and Assigned(vAFIO.FOnFileStream) then vAFIO.FOnFileStream(fileName, mode, Result); if not Assigned(Result) then begin if ((mode and fmCreate)=fmCreate) or FileExists(fileName) then Result:=TFileStream.Create(fileName, mode) else raise Exception.Create('File not found: "'+fileName+'"'); end; end; end; // FileStreamExists // function FileStreamExists(const fileName: string): Boolean; begin if Assigned(vAFIOFileStreamExists) then Result := vAFIOFileStreamExists(fileName) else begin if Assigned(vAFIO) and Assigned(vAFIO.FOnFileStreamExists) then Result := vAFIO.FOnFileStreamExists(fileName) else Result := FileExists(fileName); end; end; // FileStreamExists // function CreateResourceStream(const ResName: string; ResType: PChar): TGLSResourceStream; var InfoBlock: HRSRC; begin Result := nil; InfoBlock := FindResource(HInstance, PChar(ResName), ResType); if InfoBlock <> 0 then Result := TResourceStream.Create(HInstance, ResName, ResType) else GLSLogger.LogError(Format('Can''t create stream of application resource "%s"', [ResName])); end; // ------------------ // ------------------ TGLApplicationFileIO ------------------ // ------------------ // Create // constructor TGLApplicationFileIO.Create(AOwner: TComponent); begin inherited Create(AOwner); vAFIO := Self; end; // Destroy // destructor TGLApplicationFileIO.Destroy; begin vAFIO := nil; inherited Destroy; end; // ------------------ // ------------------ TDataFile ------------------ // ------------------ // Capabilities // class function TDataFile.Capabilities: TDataFileCapabilities; begin Result := [dfcRead]; end; // CreateCopy // function TDataFile.CreateCopy(AOwner: TPersistent): TDataFile; begin if Self <> nil then Result := TDataFileClass(Self.ClassType).Create(AOwner) else Result := nil; end; // LoadFromFile // procedure TDataFile.LoadFromFile(const fileName: string); var fs: TStream; begin ResourceName := ExtractFileName(fileName); fs := CreateFileStream(fileName, fmOpenRead + fmShareDenyNone); try LoadFromStream(fs); finally fs.Free; end; end; // SaveToFile // procedure TDataFile.SaveToFile(const fileName: string); var fs: TStream; begin ResourceName := ExtractFileName(fileName); fs := CreateFileStream(fileName, fmCreate); try SaveToStream(fs); finally fs.Free; end; end; // LoadFromStream // procedure TDataFile.LoadFromStream(stream: TStream); begin Assert(False, 'Imaport for ' + ClassName + ' to ' + stream.ClassName + ' not available.'); end; // SaveToStream // procedure TDataFile.SaveToStream(stream: TStream); begin Assert(False, 'Export for ' + ClassName + ' to ' + stream.ClassName + ' not available.'); end; procedure TDataFile.Initialize; begin end; procedure TDataFile.SetResourceName(const AName: string); begin FResourceName := AName; end; function StrToGLSResType(const AStrRes: string): TGLSApplicationResource; begin if AStrRes = '[SAMPLERS]' then begin Result := aresSampler; end else if AStrRes = '[TEXTURES]' then begin Result := aresTexture; end else if AStrRes = '[MATERIALS]' then begin Result := aresMaterial; end else if AStrRes = '[STATIC MESHES]' then begin Result := aresMesh; end else if AStrRes = '[SPLASH]' then begin Result := aresSplash; end else if AStrRes = '[FONTS]' then begin Result := aresFont; end else Result := aresNone; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Datasnap.DSHTTPLayer; interface uses System.Classes, Data.DBXCommon, System.SysUtils; type TDSHTTPClient = class; TDBXHTTPLayer = class(TDBXCommunicationLayer) protected FURITunnel: String; FSessionId: String; Fhttp: TDSHTTPClient; FIPImplementationID: string; procedure InitHTTPClient; virtual; function HTTPProtocol: String; virtual; public constructor Create; override; destructor Destroy; override; procedure Close; override; procedure Open(const DBXProperties: TDBXProperties); override; function Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override; function Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override; function Info: string; override; end; TDBXHTTPSLayer = class(TDBXHTTPLayer) protected procedure InitHTTPClient; override; function HTTPProtocol: String; override; public procedure Open(const DBXProperties: TDBXProperties); override; end; TDSHTTPResponseStream = class; ///<summary> /// Abstract HTTP client ///</summary> TDSHTTPClient = class protected function GetResponseCode: Integer; virtual; abstract; function GetResponseText: string; virtual; abstract; public function Post(AURL: string; ASource: TStrings): string; virtual; abstract; function Put(AURL: string; ASource: TStream): string; virtual; abstract; function Get(AURL: string): TDSHTTPResponseStream; virtual; abstract; procedure SetConnectTimeout(AMilisec: Integer); virtual; procedure SetReadTimeout(AMilisec: Integer); virtual; procedure SetBasicAuthentication(const user, password: String); virtual; abstract; property ResponseCode: Integer read GetResponseCode; property ResponseText: string read GetResponseText; end; ///<summary> /// Abstract HTTP response stream ///</summary> TDSHTTPResponseStream = class protected function GetContentLength: Int64; virtual; abstract; public function Read(Buffer: TBytes; Count: Longint): Integer; virtual; abstract; procedure Close; virtual; abstract; property ContentLength: Int64 read GetContentLength; end; implementation uses Data.DBXCommonIndy, IPPeerAPI, Data.DBXClientResStrs, Data.DBXJSON, Data.DBXJSONReflect, Data.DBXTransport; type TDSHTTPNativeResponseStream = class(TDSHTTPResponseStream) private FStream: TStream; FContentLength: Int64; protected function GetContentLength: Int64; override; public constructor Create(AContentLength: Integer; AStream: TStream); destructor Destroy; override; function Read(Buffer: TBytes; Count: Longint): Integer; override; procedure Close; override; end; TDSHTTPNativeClient = class(TDSHTTPClient) // class(TIPHTTP) protected FHttp: IIPHTTP; FAuthentication: IIPAuthentication; FIPImplementationID: string; protected function GetResponseCode: Integer; override; function GetResponseText: string; override; public constructor Create(const AIPImplementationID: string); virtual; destructor Destroy; override; function Post(AURL: string; ASource: TStrings): string; override; function Put(AURL: string; ASource: TStream): string; override; function Get(AURL: string): TDSHTTPResponseStream; override; procedure SetConnectTimeout(AMilisec: Integer); override; procedure SetReadTimeout(AMilisec: Integer); override; procedure SetBasicAuthentication(const user, password: String); override; end; TDSHTTPSNativeClient = class(TDSHTTPNativeClient) strict private FValidateCertificate: TValidateCertificate; protected function IdValidateCertificate(Certificate: IIPX509; AOk: Boolean; ADepth, AError: Integer): Boolean; public constructor Create(const AIPImplementationID: string); override; procedure SetPeerCertificateValidation(UserValidation: TValidateCertificate); virtual; end; {TDBXHTTPLayer} constructor TDBXHTTPLayer.Create; begin inherited; FSessionId := '0'; InitHTTPClient; end; destructor TDBXHTTPLayer.Destroy; begin Close; FreeAndNil(Fhttp); end; function TDBXHTTPLayer.HTTPProtocol: String; begin Result := 'http'; end; procedure TDBXHTTPLayer.Close; var RParams: TStringList; begin if FSessionId <> '0' then begin RParams := TStringList.Create; RParams.Values['dss'] := '-' + FSessionId; try try Fhttp.Post(FURITunnel, RParams); except // ignore end; finally RParams.Free; end; FSessionId := '0'; end; end; procedure TDBXHTTPLayer.Open(const DBXProperties: TDBXProperties); var LPath: string; LDatasnapPath: String; user, password: string; timeout: string; scheme: string; LProxyHost: String; LProxyPort: Integer; LProxyUsername: String; LProxyPassword: String; begin Close; FIPImplementationID := DbxProperties[TDBXPropertyNames.IPImplementationID]; LPath := DBXProperties[TDBXPropertyNames.URLPath]; if LPath <> '' then LPath := LPath + '/'; LDatasnapPath := DBXProperties[TDBXPropertyNames.DatasnapContext]; Assert(Length(LDatasnapPath)>0); if LDatasnapPath = '/' then LDatasnapPath := EmptyStr else if (LDatasnapPath[Length(LDatasnapPath)] <> '/') then LDatasnapPath := LDatasnapPath + '/'; FURITunnel := IPProcs(FIPImplementationID).URLEncode( Format('%s://%s:%s/%s%stunnel', [HTTPProtocol, DBXProperties[TDBXPropertyNames.HostName], DBXProperties[TDBXPropertyNames.Port], LPath, LDatasnapPath]) ) ; //set up HTTP proxy LProxyHost := Trim(DBXProperties[TDBXPropertyNames.DSProxyHost]); if LProxyHost <> EmptyStr then begin LProxyPort := StrToIntDef(DBXProperties.Values[TDBXPropertyNames.DSProxyPort], 8888); if LProxyPort > 0 then begin LProxyUsername := DBXProperties[TDBXPropertyNames.DSProxyUsername]; LProxyPassword := DBXProperties[TDBXPropertyNames.DSProxyPassword]; TDSHTTPNativeClient(Fhttp).FHttp.ProxyParams.ProxyServer := LProxyHost; TDSHTTPNativeClient(Fhttp).FHttp.ProxyParams.ProxyPort := LProxyPort; TDSHTTPNativeClient(Fhttp).FHttp.ProxyParams.ProxyUsername := LProxyUsername; TDSHTTPNativeClient(Fhttp).FHttp.ProxyParams.ProxyPassword := LProxyPassword; TDSHTTPNativeClient(Fhttp).FHttp.ProxyParams.BasicAuthentication := LProxyUsername <> EmptyStr; end; end; FSessionId := '0'; scheme := DbxProperties[TDBXPropertyNames.DSAuthenticationScheme]; if SameText(scheme, 'basic') then begin // Make user/password available in the HTTP headers, in addition // to the DBX connection string. Allows a inter-process DataSnap // HTTP tunnel server to authenticate the user. user := DBXProperties[TDBXPropertyNames.DSAuthenticationUser]; password := DBXProperties[TDBXPropertyNames.DSAuthenticationPassword]; if (user <> '') then Fhttp.SetBasicAuthentication(user, password); end; timeout := DbxProperties[TDBXPropertyNames.ConnectTimeout]; if timeout = '' then ConnectTimeout := 0 else begin ConnectTimeout := StrToInt(timeout); if ConnectTimeout < 0 then ConnectTimeout := 0 else Fhttp.SetConnectTimeout(ConnectTimeout); end; timeout := DbxProperties[TDBXPropertyNames.CommunicationTimeout]; if timeout = '' then CommunicationTimeout := 0 else begin CommunicationTimeout := StrToInt(timeout); if CommunicationTimeout < 0 then CommunicationTimeout := 0 else Fhttp.SetReadTimeout(CommunicationTimeout); end end; function TDBXHTTPLayer.Write(const Buffer: TBytes; const Offset, Count: Integer): Integer; var MemStream: TDBXBytesStream; StrData: String; JSONRes: TJSONObject; JSONParams: TJSONArray; Len: Integer; begin Assert(Offset = 0); MemStream := TDBXBytesStream.Create(Buffer, Count); Result := 0; try try // send the query string with session and count StrData := Fhttp.Put(FURITunnel + '?dss=' + FSessionId + '&c=' + IntToStr(Count), MemStream); except on ex: Exception do raise TDBXError.Create(ex.Message); end; // parse the response, populate the session id and result if Fhttp.ResponseCode = 200 then begin JSONRes := TJSONObject(TJSONObject.ParseJSONValue(BytesOf(StrData), 0)); if JSONRes = nil then raise TDBXError.Create(Format(SProtocolErrorJSON, [StrData])); try if JSONRes.Get(0).JsonString.Value = 'error' then raise TDBXError.Create(TJSONString(JSONRes.Get(0).JsonValue).Value); // session id JSONParams := TJSONArray(JSONRes.Get(0).JsonValue); FSessionId := TJSONString(JSONParams.Get(0)).Value; // bytes written Len := StrToInt(TJSONNumber(JSONParams.Get(1)).Value); if Len < Count then raise TDBXError.Create(Format(SProtocolErrorWrite, [Count, Len])); finally JSONRes.Free; end; end else raise TDBXError.Create(Fhttp.ResponseText); finally MemStream.Free; end; end; function TDBXHTTPLayer.Read(const Buffer: TBytes; const Offset, Count: Integer): Integer; var ResponseStream: TDSHTTPResponseStream; begin Assert(Offset = 0); Result := 0; // send session and count ResponseStream := Fhttp.Get(FURITunnel + '?dss=' + FSessionId + '&c=' + IntToStr(Count)); if ResponseStream <> nil then try // read from the stream the number of bytes (compare with response size) if ResponseStream.ContentLength > Count then raise TDBXError.Create(Format(SProtocolErrorSize, [ResponseStream, Count])); Result := ResponseStream.Read(Buffer, ResponseStream.ContentLength); finally try ResponseStream.Close; finally ResponseStream.Free; end; end; end; function TDBXHTTPLayer.Info: String; begin Result := FURITunnel; end; procedure TDBXHTTPLayer.InitHTTPClient; begin Fhttp := TDSHTTPNativeClient.Create(FIPImplementationID); end; constructor TDSHTTPNativeClient.Create(const AIPImplementationID: string); begin //inherited Create(nil); inherited Create; FIPImplementationID := AIPImplementationID; FHTTP := PeerFactory.CreatePeer(FIPImplementationID, IIPHTTP, nil) as IIPHTTP; //TIPHTTP.Create(nil); FHTTP.UseNagle := False; end; destructor TDSHTTPNativeClient.Destroy; begin FHTTP := nil; inherited; end; function TDSHTTPNativeClient.Get(AURL: string): TDSHTTPResponseStream; var Data: TStream; begin Data := TMemoryStream.Create; try FHTTP.DoGet(AURL, Data); Data.Position := 0; Result := TDSHTTPNativeResponseStream.Create(Fhttp.Response.ContentLength, Data); except Data.Free; raise end; end; function TDSHTTPNativeClient.GetResponseCode: Integer; begin Result := FHTTP.ResponseCode; end; function TDSHTTPNativeClient.GetResponseText: string; begin Result := FHTTP.ResponseText; end; function TDSHTTPNativeClient.Post(AURL: string; ASource: TStrings): string; begin Result := FHTTP.DoPost(AURL, ASource) end; function TDSHTTPNativeClient.Put(AURL: string; ASource: TStream): string; begin Result := FHTTP.DoPut(AURL, ASource) end; procedure TDSHTTPNativeClient.SetBasicAuthentication(const user, password: String); begin FAuthentication := PeerFactory.CreatePeer(FIPImplementationID, IIPBasicAuthentication) as IIPBasicAuthentication; FAuthentication.Password := password; FAuthentication.Username := user; FHTTP.Request.Authentication := FAuthentication; end; procedure TDSHTTPNativeClient.SetConnectTimeout(AMilisec: Integer); begin FHTTP.ConnectTimeout := AMilisec; end; procedure TDSHTTPNativeClient.SetReadTimeout(AMilisec: Integer); begin FHTTP.ReadTimeout := AMilisec; end; { TDSHTTPNativeResponseStream } procedure TDSHTTPNativeResponseStream.Close; begin // Do nothing end; constructor TDSHTTPNativeResponseStream.Create(AContentLength: Integer; AStream: TStream); begin FStream := AStream; FContentLength := AContentLength; end; destructor TDSHTTPNativeResponseStream.Destroy; begin FreeAndNil(FStream); end; function TDSHTTPNativeResponseStream.GetContentLength: Int64; begin Result := FContentLength; end; function TDSHTTPNativeResponseStream.Read(Buffer: TBytes; Count: Integer): Integer; begin Result := FStream.Read(Buffer[0], Count); end; { TDBXHTTPSLayer } function TDBXHTTPSLayer.HTTPProtocol: String; begin Result := 'https'; end; procedure TDBXHTTPSLayer.InitHTTPClient; begin Fhttp := TDSHTTPSNativeClient.Create(FIPImplementationID); end; procedure TDBXHTTPSLayer.Open(const DBXProperties: TDBXProperties); var Proc: TEventPointer; begin inherited; Proc := DBXProperties.Events.Events[sValidatePeerCertificate]; if Assigned(Proc) then TDSHTTPSNativeClient(Fhttp).SetPeerCertificateValidation(TValidateCertificate(Proc)); end; { TDSHTTPSNativeClient } constructor TDSHTTPSNativeClient.Create(const AIPImplementationID: string); var LIOHandler: IIPSSLIOHandlerSocketOpenSSL; begin inherited Create(AIPImplementationID); FValidateCertificate := nil; LIOHandler := PeerFactory.CreatePeer(AIPImplementationID, IIPSSLIOHandlerSocketOpenSSL, FHTTP.GetObject as TComponent) as IIPSSLIOHandlerSocketOpenSSL; LIOHandler.OnVerifyPeer := IdValidateCertificate; LIOHandler.SSLOptions.VerifyMode := [sslvrfClientOnce]; FHTTP.IOHandler := LIOHandler; end; function TDSHTTPSNativeClient.IdValidateCertificate(Certificate: IIPX509; AOk: Boolean; ADepth, AError: Integer): Boolean; var Cert: TX509Certificate; begin Result := true; if Assigned(FValidateCertificate) then begin Cert := TX509CertificateIndy.Create(Certificate); try // prepare the TX509Ceritifcate and invoke user method FValidateCertificate(Self, Cert, ADepth, Result); finally Cert.Free; end; end; end; procedure TDSHTTPSNativeClient.SetPeerCertificateValidation( UserValidation: TValidateCertificate); begin FValidateCertificate := UserValidation; end; { TDSHTTPClient } procedure TDSHTTPClient.SetConnectTimeout(AMilisec: Integer); begin // do nothing here end; procedure TDSHTTPClient.SetReadTimeout(AMilisec: Integer); begin //do nothing here end; initialization TDBXCommunicationLayerFactory.RegisterLayer('http', TDBXHTTPLayer); TDBXCommunicationLayerFactory.RegisterLayer('https', TDBXHTTPSLayer); finalization TDBXCommunicationLayerFactory.UnregisterLayer('http'); TDBXCommunicationLayerFactory.UnregisterLayer('https'); end.
program fib(n); function fib(n: Integer): Integer; begin if n = 0 then fib := 0 else if n = 1 then fib := 1 else fib := fib(n-1) + fib(n-2); end; begin fib(n); end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLTexCombineShader<p> A shader that allows texture combiner setup.<p> <b>History : </b><font size=-1><ul> <li>05/03/11 - Yar - Added combiner's commands cache <li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter <li>24/07/09 - DaStr - TGLShader.DoInitialize() now passes rci (BugTracker ID = 2826217) <li>03/04/07 - DaStr - Added $I GLScene.inc <li>25/02/07 - DaStr - Moved registration to GLSceneRegister.pas <li>23/05/03 - EG - Added support for binding two extra texture units <li>16/05/03 - EG - Creation </ul></font> } unit GLTexCombineShader; interface {$I GLScene.inc} uses Classes, SysUtils, GLTexture, GLMaterial, GLRenderContextInfo, GLTextureCombiners, OpenGLTokens, XOpenGL, GLContext, GLCrossPlatform, GLUtils; type // TGLTexCombineShader // {: A shader that can setup the texture combiner.<p> } TGLTexCombineShader = class(TGLShader) private { Protected Declarations } FCombiners: TStringList; FCommandCache: TCombinerCache; FCombinerIsValid: Boolean; // to avoid reparsing invalid stuff FDesignTimeEnabled: Boolean; FMaterialLibrary: TGLMaterialLibrary; FLibMaterial3Name: TGLLibMaterialName; currentLibMaterial3: TGLLibMaterial; FLibMaterial4Name: TGLLibMaterialName; currentLibMaterial4: TGLLibMaterial; FApplied3, FApplied4: Boolean; protected { Protected Declarations } procedure SetCombiners(const val: TStringList); procedure SetDesignTimeEnabled(const val: Boolean); procedure SetMaterialLibrary(const val: TGLMaterialLibrary); procedure SetLibMaterial3Name(const val: TGLLibMaterialName); procedure SetLibMaterial4Name(const val: TGLLibMaterialName); procedure NotifyLibMaterial3Destruction; procedure NotifyLibMaterial4Destruction; procedure DoInitialize(var rci: TRenderContextInfo; Sender: TObject); override; procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override; function DoUnApply(var rci: TRenderContextInfo): Boolean; override; procedure DoFinalize; override; public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure NotifyChange(Sender: TObject); override; published { Published Declarations } property Combiners: TStringList read FCombiners write SetCombiners; property DesignTimeEnabled: Boolean read FDesignTimeEnabled write SetDesignTimeEnabled; property MaterialLibrary: TGLMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; property LibMaterial3Name: TGLLibMaterialName read FLibMaterial3Name write SetLibMaterial3Name; property LibMaterial4Name: TGLLibMaterialName read FLibMaterial4Name write SetLibMaterial4Name; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------ // ------------------ TGLTexCombineShader ------------------ // ------------------ // Create // constructor TGLTexCombineShader.Create(AOwner: TComponent); begin inherited; ShaderStyle := ssLowLevel; FCombiners := TStringList.Create; TStringList(FCombiners).OnChange := NotifyChange; FCombinerIsValid := True; FCommandCache := nil; end; // Destroy // destructor TGLTexCombineShader.Destroy; begin if Assigned(currentLibMaterial3) then currentLibMaterial3.UnregisterUser(Self); if Assigned(currentLibMaterial4) then currentLibMaterial4.UnregisterUser(Self); inherited; FCombiners.Free; end; // Notification // procedure TGLTexCombineShader.Notification(AComponent: TComponent; Operation: TOperation); begin if (FMaterialLibrary = AComponent) and (Operation = opRemove) then begin NotifyLibMaterial3Destruction; NotifyLibMaterial4Destruction; FMaterialLibrary := nil; end; inherited; end; // NotifyChange // procedure TGLTexCombineShader.NotifyChange(Sender: TObject); begin FCombinerIsValid := True; FCommandCache := nil; inherited NotifyChange(Sender); end; // NotifyLibMaterial3Destruction // procedure TGLTexCombineShader.NotifyLibMaterial3Destruction; begin FLibMaterial3Name := ''; currentLibMaterial3 := nil; end; // NotifyLibMaterial4Destruction // procedure TGLTexCombineShader.NotifyLibMaterial4Destruction; begin FLibMaterial4Name := ''; currentLibMaterial4 := nil; end; // SetMaterialLibrary // procedure TGLTexCombineShader.SetMaterialLibrary(const val: TGLMaterialLibrary); begin FMaterialLibrary := val; SetLibMaterial3Name(LibMaterial3Name); SetLibMaterial4Name(LibMaterial4Name); end; // SetLibMaterial3Name // procedure TGLTexCombineShader.SetLibMaterial3Name(const val: TGLLibMaterialName); var newLibMaterial: TGLLibMaterial; begin // locate new libmaterial if Assigned(FMaterialLibrary) then newLibMaterial := MaterialLibrary.Materials.GetLibMaterialByName(val) else newLibMaterial := nil; FLibMaterial3Name := val; // unregister if required if newLibMaterial <> currentLibMaterial3 then begin // unregister from old if Assigned(currentLibMaterial3) then currentLibMaterial3.UnregisterUser(Self); currentLibMaterial3 := newLibMaterial; // register with new if Assigned(currentLibMaterial3) then currentLibMaterial3.RegisterUser(Self); NotifyChange(Self); end; end; // SetLibMaterial4Name // procedure TGLTexCombineShader.SetLibMaterial4Name(const val: TGLLibMaterialName); var newLibMaterial: TGLLibMaterial; begin // locate new libmaterial if Assigned(FMaterialLibrary) then newLibMaterial := MaterialLibrary.Materials.GetLibMaterialByName(val) else newLibMaterial := nil; FLibMaterial4Name := val; // unregister if required if newLibMaterial <> currentLibMaterial4 then begin // unregister from old if Assigned(currentLibMaterial4) then currentLibMaterial4.UnregisterUser(Self); currentLibMaterial4 := newLibMaterial; // register with new if Assigned(currentLibMaterial4) then currentLibMaterial4.RegisterUser(Self); NotifyChange(Self); end; end; // DoInitialize // procedure TGLTexCombineShader.DoInitialize(var rci: TRenderContextInfo; Sender: TObject); begin end; // DoApply // procedure TGLTexCombineShader.DoApply(var rci: TRenderContextInfo; Sender: TObject); var n, units: Integer; begin if not GL.ARB_multitexture then Exit; FApplied3 := False; FApplied4 := False; if FCombinerIsValid and (FDesignTimeEnabled or (not (csDesigning in ComponentState))) then begin try if Assigned(currentLibMaterial3) or Assigned(currentLibMaterial4) then begin GL.GetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, @n); units := 0; if Assigned(currentLibMaterial3) and (n >= 3) then begin with currentLibMaterial3.Material.Texture do begin if Enabled then begin if currentLibMaterial3.TextureMatrixIsIdentity then ApplyAsTextureN(3, rci) else ApplyAsTextureN(3, rci, @currentLibMaterial3.TextureMatrix.V[0].V[0]); // ApplyAsTextureN(3, rci, currentLibMaterial3); Inc(units, 4); FApplied3 := True; end; end; end; if Assigned(currentLibMaterial4) and (n >= 4) then begin with currentLibMaterial4.Material.Texture do begin if Enabled then begin if currentLibMaterial4.TextureMatrixIsIdentity then ApplyAsTextureN(4, rci) else ApplyAsTextureN(4, rci, @currentLibMaterial4.TextureMatrix.V[0].V[0]); // ApplyAsTextureN(4, rci, currentLibMaterial4); Inc(units, 8); FApplied4 := True; end; end; end; if units > 0 then xgl.MapTexCoordToArbitraryAdd(units); end; if Length(FCommandCache) = 0 then FCommandCache := GetTextureCombiners(FCombiners); for n := 0 to High(FCommandCache) do begin rci.GLStates.ActiveTexture := FCommandCache[n].ActiveUnit; GL.TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB); GL.TexEnvi(GL_TEXTURE_ENV, FCommandCache[n].Arg1, FCommandCache[n].Arg2); end; rci.GLStates.ActiveTexture := 0; except on E: Exception do begin FCombinerIsValid := False; InformationDlg(E.ClassName + ': ' + E.Message); end; end; end; end; // DoUnApply // function TGLTexCombineShader.DoUnApply(var rci: TRenderContextInfo): Boolean; begin if FApplied3 then with currentLibMaterial3.Material.Texture do UnApplyAsTextureN(3, rci, (not currentLibMaterial3.TextureMatrixIsIdentity)); if FApplied4 then with currentLibMaterial4.Material.Texture do UnApplyAsTextureN(4, rci, (not currentLibMaterial4.TextureMatrixIsIdentity)); Result := False; end; // DoFinalize // procedure TGLTexCombineShader.DoFinalize; begin end; // SetCombiners // procedure TGLTexCombineShader.SetCombiners(const val: TStringList); begin if val <> FCombiners then begin FCombiners.Assign(val); NotifyChange(Self); end; end; // SetDesignTimeEnabled // procedure TGLTexCombineShader.SetDesignTimeEnabled(const val: Boolean); begin if val <> FDesignTimeEnabled then begin FDesignTimeEnabled := val; NotifyChange(Self); end; end; end.
{ Double commander ------------------------------------------------------------------------- Definitions of basic types. Copyright (C) 2012 Przemyslaw Nagay (cobines@gmail.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA } unit DCBasicTypes; interface type TDynamicStringArray = array of String; TCharSet = set of Char; TFileAttrs = Cardinal; // file attributes type regardless of system TWinFileTime = QWord; // NTFS time (UTC) (2 x DWORD) TDosFileTime = LongInt; // MS-DOS time (local) {$IFDEF MSWINDOWS} TFileTime = TWinFileTime; {$ELSE} // Unix time (UTC). // Unix defines time_t as signed integer, // but we define it as unsigned because sign is not needed. {$IFDEF cpu64} TFileTime = QWord; {$ELSE} TFileTime = DWord; {$ENDIF} {$ENDIF} TUnixFileTime = TFileTime; PFileTime = ^TFileTime; PWinFileTime = ^TWinFileTime; implementation end.
unit ReportManager; interface uses SysUtils, Classes, DB, ADODB, xmldom, XMLIntf, msxmldom, XMLDoc, Dialogs; type TReport = class(TObject) protected FName: AnsiString; FCaption: AnsiString; FSQLText: AnsiString; FHeaderSQLText: AnsiString; FColumns: TStringList; FFooterSQLText: AnsiString; public constructor Create; destructor Destroy; override; //-- property Name: AnsiString read FName write FName; property Caption: AnsiString read FCaption write FCaption; property SQLText: AnsiString read FSQLText write FSQLText; property HeaderSQLText: AnsiString read FHeaderSQLText write FHeaderSQLText; property Columns: TStringList read FColumns write FColumns; property FooterSQLText: AnsiString read FFooterSQLText write FFooterSQLText; end; type TdmReportManager = class(TDataModule) FDataSet: TADODataSet; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } FRow: Integer; FReportList: TList; //-- function GetReport(const ReportName: AnsiString): TReport; function PrepareExcelFile(const SheetName: AnsiString): Variant; function GetReportList: TList; procedure ReadReports(); procedure AddReport(const ReportFile: AnsiString); procedure ReportQueryResult(const Sheet: Variant; const SQLText: AnsiString); procedure ReportString(const Sheet: Variant; const Text: AnsiString); procedure ReportStringListH(const Sheet: Variant; const TextList: TStringList); procedure ReportStringListV(const Sheet: Variant; const TextList: TStringList); public { Public declarations } procedure DoReport(const ReportName: AnsiString); procedure ReportUIQuery(const DataSet: TDataSet; const TableName: AnsiString); //-- property ReportList: TList read GetReportList; end; var dmReportManager: TdmReportManager; implementation {$R *.dfm} uses ComObj, Data, ForestConsts, NsUtils, Variants; //--------------------------------------------------------------------------- { TReport } constructor TReport.Create; begin FName := ''; FCaption := ''; FSQLText := ''; FColumns := TStringList.Create(); FHeaderSQLText := ''; FFooterSQLText := ''; end; //--------------------------------------------------------------------------- destructor TReport.Destroy; begin FColumns.Free(); inherited; end; //--------------------------------------------------------------------------- { TdmReportManager } procedure TdmReportManager.AddReport(const ReportFile: AnsiString); var Rep: TReport; RepFile: IXMLDocument; RepColumns: TStringList; function ReadStr(Section: AnsiString): AnsiString; begin try Result := Trim(RepFile.DocumentElement.ChildNodes.Nodes[Section].Text); except Result := ''; end; end; function ReadInt(Section: AnsiString): Integer; begin try Result := StrToInt(Trim(RepFile.DocumentElement.ChildNodes.Nodes[Section].Text)); except Result := 0; end; end; procedure ReadStrings(Section: AnsiString; var AStringList: TStringList); begin try AStringList.DelimitedText := Trim(RepFile.DocumentElement.ChildNodes.Nodes[Section].Text); except AStringList.Clear(); end; end; begin Rep := TReport.Create(); RepColumns := TStringList.Create(); RepColumns.Delimiter := '#'; RepColumns.QuoteChar := '|'; RepFile := TXMLDocument.Create(nil); RepFile.LoadFromFile(ReportFile); Rep.Name := ReadStr('Name'); Rep.Caption := ReadStr('Caption'); Rep.SQLText := ReadStr('SQLText'); Rep.HeaderSQLText := ReadStr('HeaderSQLText'); ReadStrings('Columns', RepColumns); Rep.Columns.AddStrings(RepColumns); Rep.FooterSQLText := ReadStr('FooterSQLText'); FReportList.Add(Rep); end; //--------------------------------------------------------------------------- procedure TdmReportManager.DataModuleCreate(Sender: TObject); begin FDataSet.Connection := dmData.connDB; FReportList := TList.Create(); ReadReports(); end; //--------------------------------------------------------------------------- procedure TdmReportManager.DataModuleDestroy(Sender: TObject); begin if FDataSet.Active then FDataSet.Close(); FReportList.Free(); end; //--------------------------------------------------------------------------- procedure TdmReportManager.DoReport(const ReportName: AnsiString); var Rep: TReport; Sheet: Variant; begin try try Rep := GetReport(ReportName); Sheet := PrepareExcelFile(Rep.Caption); FRow := 1; ReportString(Sheet, Rep.Caption); ReportQueryResult(Sheet, Rep.HeaderSQLText); ReportStringListH(Sheet, Rep.Columns); ReportQueryResult(Sheet, Rep.SQLText); ReportQueryResult(Sheet, Rep.FFooterSQLText); except on E: Exception do ShowMsg(E_REPORT_ERROR); end; finally dmData.connDB.Close(); end; end; //--------------------------------------------------------------------------- function TdmReportManager.GetReport(const ReportName: AnsiString): TReport; var I: Integer; begin Result := nil; for I := 0 to FReportList.Count - 1 do if TReport(FReportList[I]).Name = ReportName then begin Result := TReport(FReportList[I]); Break; end; end; //--------------------------------------------------------------------------- function TdmReportManager.GetReportList: TList; begin Result := FReportList; end; //--------------------------------------------------------------------------- function TdmReportManager.PrepareExcelFile(const SheetName: AnsiString): Variant; var ExcelApp: Variant; begin ExcelApp := CreateOleObject('Excel.Application'); ExcelApp.WorkBooks.Add(); ExcelApp.WorkBooks[1].WorkSheets[1].Name := SheetName; ExcelApp.Visible := True; Result := ExcelApp.WorkBooks[1].WorkSheets[SheetName]; end; //--------------------------------------------------------------------------- procedure TdmReportManager.ReadReports; var SearchResult: TSearchRec; begin if FindFirst(GetAppPath() + 'Reports\*.rep', faAnyFile, SearchResult) = 0 then begin repeat AddReport(GetAppPath() + 'Reports\' + SearchResult.Name); until FindNext(SearchResult) <> 0; FindClose(SearchResult); end; end; //--------------------------------------------------------------------------- procedure TdmReportManager.ReportQueryResult(const Sheet: Variant; const SQLText: AnsiString); var CurRow, CurCol: Integer; begin try if SQLText = '' then Exit; if FDataSet.Active then FDataSet.Close(); FDataSet.CommandText := SQLText; FDataSet.Open(); FDataSet.First(); CurRow := 1; while CurRow <= FDataSet.RecordCount do begin CurCol := 1; while CurCol <= FDataSet.FieldCount do begin Sheet.Cells[FRow, CurCol] := FDataSet.Fields[CurCol - 1].AsString; Inc(CurCol); end; FDataSet.Next(); Inc(CurRow); Inc(FRow); end; finally FDataSet.Close(); end; end; //--------------------------------------------------------------------------- procedure TdmReportManager.ReportUIQuery(const DataSet: TDataSet; const TableName: AnsiString); var CurRow, CurCol: Integer; Sheet: Variant; begin try Sheet := PrepareExcelFile(TableName); DataSet.First(); CurRow := 1; while CurRow <= DataSet.RecordCount do begin CurCol := 1; while CurCol <= DataSet.FieldCount do begin Sheet.Cells[FRow, CurCol] := DataSet.Fields[CurCol - 1].AsString; Inc(CurCol); end; DataSet.Next(); Inc(CurRow); end; except on E: Exception do ShowMsg(E_REPORT_ERROR); end; end; //--------------------------------------------------------------------------- procedure TdmReportManager.ReportString(const Sheet: Variant; const Text: AnsiString); begin Sheet.Cells[FRow, 1] := Text; Inc(FRow); end; //--------------------------------------------------------------------------- procedure TdmReportManager.ReportStringListH(const Sheet: Variant; const TextList: TStringList); var CurCol: Integer; begin CurCol := 1; while CurCol <= TextList.Count do begin Sheet.Cells[FRow, CurCol] := TextList[CurCol - 1]; Inc(CurCol); end; Inc(FRow); end; //--------------------------------------------------------------------------- procedure TdmReportManager.ReportStringListV(const Sheet: Variant; const TextList: TStringList); var CurRow: Integer; begin CurRow := 1; while CurRow <= TextList.Count do begin Sheet.Cells[FRow, 1] := TextList[CurRow - 1]; Inc(FRow); Inc(CurRow); end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit REST.Backend.EMSProvider; interface uses System.Classes, System.SysUtils, System.Generics.Collections, REST.Backend.Providers, REST.Backend.EMSAPI, REST.Client, REST.Backend.ServiceTypes, REST.Backend.MetaTypes, System.Net.URLClient; type TCustomEMSConnectionInfo = class(TComponent) public type TNotifyList = class private FList: TList<TNotifyEvent>; procedure Notify(Sender: TObject); public constructor Create; destructor Destroy; override; procedure Add(const ANotify: TNotifyEvent); procedure Remove(const ANotify: TNotifyEvent); end; TProtocolNames = record public const HTTP = 'http'; HTTPS = 'https'; end; TAndroidPush = class(TPersistent) private FOwner: TCustomEMSConnectionInfo; FGCMAppID: string; procedure SetGCMAppID(const Value: string); protected procedure AssignTo(AValue: TPersistent); override; published property GCMAppID: string read FGCMAppID write SetGCMAppID; end; private FConnectionInfo: TEMSClientAPI.TConnectionInfo; FNotifyOnChange: TNotifyList; FURLBasePath: string; FURLPort: Integer; FURLHost: string; FURLProtocol: string; FAndroidPush: TAndroidPush; FOnValidateCertificate: TValidateCertificateEvent; procedure SetApiVersion(const Value: string); procedure SetAppSecret(const Value: string); procedure SetMasterSecret(const Value: string); function GetApiVersion: string; function GetAppSecret: string; function GetMasterSecret: string; function GetPassword: string; function GetLoginResource: string; function GetUserName: string; procedure SetLoginResource(const Value: string); procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); function GetProxyPassword: string; function GetProxyPort: integer; function GetProxyServer: string; function GetProxyUsername: string; procedure SetProxyPassword(const Value: string); procedure SetProxyPort(const Value: integer); procedure SetProxyServer(const Value: string); procedure SetProxyUsername(const Value: string); function GetBaseURL: string; function IsURLProtocolStored: Boolean; procedure SetURLProtocol(const Value: string); procedure SetURLBasePath(const Value: string); procedure SetURLHost(const Value: string); procedure SetURLPort(const Value: Integer); function GetApplicationId: string; procedure SetApplicationId(const Value: string); procedure SetAndroidPush(const Value: TAndroidPush); procedure SetOnValidateCertificate(const Value: TValidateCertificateEvent); function GetTenantId: string; procedure SetTenantId(const Value: string); function GetTenantSecret: string; procedure SetTenantSecret(const Value: string); protected procedure DoChanged; virtual; property NotifyOnChange: TNotifyList read FNotifyOnChange; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure UpdateApi(const AApi: TEMSClientAPI); procedure AppHandshake(const ACallback: TEMSClientAPI.TAppHandshakeProc); procedure CheckURL; property URLProtocol: string read FURLProtocol write SetURLProtocol stored IsURLProtocolStored nodefault; property URLHost: string read FURLHost write SetURLHost; property URLPort: Integer read FURLPort write SetURLPort; property URLBasePath: string read FURLBasePath write SetURLBasePath; property OnValidateCertificate: TValidateCertificateEvent read FOnValidateCertificate write SetOnValidateCertificate; property AndroidPush: TAndroidPush read FAndroidPush write SetAndroidPush; property ApiVersion: string read GetApiVersion write SetApiVersion; property AppSecret: string read GetAppSecret write SetAppSecret; property ApplicationId: string read GetApplicationId write SetApplicationId; property MasterSecret: string read GetMasterSecret write SetMasterSecret; property BaseURL: string read GetBaseURL; property UserName: string read GetUserName write SetUserName; property LoginResource: string read GetLoginResource write SetLoginResource; property Password: string read GetPassword write SetPassword; property ProxyPassword: string read GetProxyPassword write SetProxyPassword; property ProxyPort: integer read GetProxyPort write SetProxyPort default 0; property ProxyServer: string read GetProxyServer write SetProxyServer; property ProxyUsername: string read GetProxyUsername write SetProxyUsername; property TenantId: string read GetTenantId write SetTenantId; property TenantSecret: string read GetTenantSecret write SetTenantSecret; end; TCustomEMSProvider = class(TCustomEMSConnectionInfo, IBackendProvider) public const ProviderID = 'EMS'; protected { IBackendProvider } function GetProviderID: string; end; TEMSProvider = class(TCustomEMSProvider) published property AndroidPush; property ApiVersion; property ApplicationId; property AppSecret; property MasterSecret; property LoginResource; property URLProtocol; property URLHost; property URLPort; property URLBasePath; property ProxyPassword; property ProxyPort; property ProxyServer; property ProxyUsername; property TenantId; property TenantSecret; property OnValidateCertificate; end; TEMSBackendService = class(TInterfacedObject) private FConnectionInfo: TCustomEMSConnectionInfo; procedure SetConnectionInfo(const Value: TCustomEMSConnectionInfo); procedure OnConnectionChanged(Sender: TObject); protected procedure DoAfterConnectionChanged; virtual; property ConnectionInfo: TCustomEMSConnectionInfo read FConnectionInfo write SetConnectionInfo; public constructor Create(const AProvider: IBackendProvider); virtual; destructor Destroy; override; end; IGetEMSApi = interface ['{554D8251-5BC6-4542-AD35-0EAC3F3031DE}'] function GetEMSAPI: TEMSClientAPI; property EMSAPI: TEMSClientAPI read GetEMSAPI; end; TEMSServiceAPI = class(TInterfacedObject, IBackendAPI, IGetEMSApi) private FEMSAPI: TEMSClientAPI; { IGetEMSAPI } function GetEMSAPI: TEMSClientAPI; protected property EMSAPI: TEMSClientAPI read FEMSAPI; public constructor Create; destructor Destroy; override; end; TEMSServiceAPIAuth = class(TEMSServiceAPI, IBackendAuthenticationApi) protected { IBackendAuthenticationApi } procedure Login(const ALogin: TBackendEntityValue); procedure Logout; procedure SetDefaultAuthentication(ADefaultAuthentication : TBackendDefaultAuthentication); function GetDefaultAuthentication: TBackendDefaultAuthentication; procedure SetAuthentication(AAuthentication: TBackendAuthentication); function GetAuthentication: TBackendAuthentication; end; TEMSBackendService<TAPI: TEMSServiceAPI, constructor> = class (TEMSBackendService, IGetEMSApi) private FBackendAPI: TAPI; FBackendAPIIntf: IInterface; { IGetEMSAPI } function GetEMSAPI: TEMSClientAPI; protected function CreateBackendApi: TAPI; virtual; procedure EnsureBackendApi; procedure DoAfterConnectionChanged; override; property BackendAPI: TAPI read FBackendAPI; end; EEMSProviderError = class(Exception); implementation uses REST.Backend.EMSMetaTypes, REST.Backend.Consts, System.TypInfo, REST.Backend.EMSConsts; { TCustomEMSConnectionInfo } procedure TCustomEMSConnectionInfo.AppHandshake( const ACallback: TEMSClientAPI.TAppHandshakeProc); var LClientAPI: TEMSClientAPI; begin CheckURL; LClientAPI := TEMSClientAPI.Create(nil); try UpdateApi(LClientAPI); LClientAPI.AppHandshake(ACallback); finally LClientAPI.Free; end; end; procedure TCustomEMSConnectionInfo.CheckURL; begin if URLHost = '' then raise EEMSProviderError.Create(sURLHostNotBlank); if URLProtocol = '' then raise EEMSProviderError.Create(sURLProtocolNotBlank); end; constructor TCustomEMSConnectionInfo.Create(AOwner: TComponent); begin inherited; FConnectionInfo.AppSecret := ''; FConnectionInfo.ApplicationId := ''; FConnectionInfo.MasterSecret := ''; FConnectionInfo.ApiVersion := TEMSClientAPI.cDefaultApiVersion; FConnectionInfo.TenantId := ''; FConnectionInfo.TenantSecret := ''; FURLProtocol := TProtocolNames.HTTP; FConnectionInfo.BaseURL := BaseURL; FAndroidPush := TAndroidPush.Create; FAndroidPush.FOwner := Self; FNotifyOnChange := TNotifyList.Create; end; destructor TCustomEMSConnectionInfo.Destroy; begin inherited; FAndroidPush.Free; FNotifyOnChange.Free; end; procedure TCustomEMSConnectionInfo.DoChanged; begin FNotifyOnChange.Notify(Self); end; function TCustomEMSConnectionInfo.GetApiVersion: string; begin Result := FConnectionInfo.ApiVersion; end; function TCustomEMSConnectionInfo.GetApplicationId: string; begin Result := FConnectionInfo.ApplicationId; end; function TCustomEMSConnectionInfo.GetAppSecret: string; begin Result := FConnectionInfo.AppSecret; end; function TCustomEMSConnectionInfo.GetMasterSecret: string; begin Result := FConnectionInfo.MasterSecret; end; function TCustomEMSConnectionInfo.GetPassword: string; begin Result := FConnectionInfo.Password; end; function TCustomEMSConnectionInfo.GetProxyPassword: string; begin Result := FConnectionInfo.ProxyPassword; end; function TCustomEMSConnectionInfo.GetProxyPort: integer; begin Result := FConnectionInfo.ProxyPort; end; function TCustomEMSConnectionInfo.GetProxyServer: string; begin Result := FConnectionInfo.ProxyServer; end; function TCustomEMSConnectionInfo.GetProxyUsername: string; begin Result := FConnectionInfo.ProxyUsername; end; function TCustomEMSConnectionInfo.GetTenantId: string; begin Result := FConnectionInfo.TenantId; end; function TCustomEMSConnectionInfo.GetTenantSecret: string; begin Result := FConnectionInfo.TenantSecret; end; function TCustomEMSConnectionInfo.GetUserName: string; begin Result := FConnectionInfo.UserName; end; function TCustomEMSConnectionInfo.GetLoginResource: string; begin Result := FConnectionInfo.LoginResource; end; function TCustomEMSConnectionInfo.IsURLProtocolStored: Boolean; begin Result := not SameText(URLProtocol, TProtocolNames.HTTP); end; function TCustomEMSConnectionInfo.GetBaseURL: string; begin if (URLProtocol <> '') and (URLHost <> '') then // Leave blank if no protocol or host begin if URLPort <> 0 then Result := Format('%s://%s:%d', [URLProtocol, URLHost, URLPort]) else Result := Format('%s://%s', [URLProtocol, URLHost]); if URLBasePath <> '' then if URLBasePath.StartsWith('/') then Result := Result + URLBasePath else Result := Result + '/' + URLBasePath; end; end; procedure TCustomEMSConnectionInfo.SetAndroidPush(const Value: TAndroidPush); begin FAndroidPush.Assign(Value); end; procedure TCustomEMSConnectionInfo.SetApiVersion(const Value: string); begin if Value <> ApiVersion then begin FConnectionInfo.ApiVersion := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetApplicationId(const Value: string); begin if Value <> ApplicationId then begin FConnectionInfo.ApplicationId := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetAppSecret(const Value: string); begin if Value <> AppSecret then begin FConnectionInfo.AppSecret := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetMasterSecret(const Value: string); begin if Value <> MasterSecret then begin FConnectionInfo.MasterSecret := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetPassword(const Value: string); begin if Value <> Password then begin FConnectionInfo.Password := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetURLBasePath(const Value: string); begin if Value <> URLBasePath then begin FURLBasePath := Value; FConnectionInfo.BaseURL := BaseURL; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetOnValidateCertificate(const Value: TValidateCertificateEvent); begin FOnValidateCertificate := Value; FConnectionInfo.OnValidateCertificate := Value; DoChanged; end; procedure TCustomEMSConnectionInfo.SetURLHost(const Value: string); begin if Value <> URLHost then begin FURLHost := Value; FConnectionInfo.BaseURL := BaseURL; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetURLPort(const Value: Integer); begin if Value <> URLPort then begin FURLPort := Value; FConnectionInfo.BaseURL := BaseURL; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetURLProtocol(const Value: string); begin if Value <> URLProtocol then begin FURLProtocol := Value; FConnectionInfo.BaseURL := BaseURL; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetProxyPassword(const Value: string); begin if Value <> ProxyPassword then begin FConnectionInfo.ProxyPassword := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetProxyPort(const Value: integer); begin if Value <> ProxyPort then begin FConnectionInfo.ProxyPort := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetProxyServer(const Value: string); begin if Value <> ProxyServer then begin FConnectionInfo.ProxyServer := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetProxyUsername(const Value: string); begin if Value <> ProxyUsername then begin FConnectionInfo.ProxyUsername := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetTenantId(const Value: string); begin if Value <> TenantId then begin FConnectionInfo.TenantId := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetTenantSecret(const Value: string); begin if Value <> TenantSecret then begin FConnectionInfo.TenantSecret := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetUserName(const Value: string); begin if Value <> UserName then begin FConnectionInfo.UserName := Value; DoChanged; end; end; procedure TCustomEMSConnectionInfo.SetLoginResource(const Value: string); begin if Value <> LoginResource then begin FConnectionInfo.LoginResource := Value; DoChanged; end; end; //procedure TCustomEMSConnectionInfo.SetBaseURL(const Value: string); //begin // if Value <> AppKey then // begin // FConnectionInfo.BaseURL := Value; // DoChanged; // end; //end; procedure TCustomEMSConnectionInfo.UpdateApi(const AApi: TEMSClientAPI); begin AApi.ConnectionInfo := FConnectionInfo; end; { TCustomEMSConnectionInfo.TNotifyList } procedure TCustomEMSConnectionInfo.TNotifyList.Add(const ANotify : TNotifyEvent); begin Assert(not FList.Contains(ANotify)); if not FList.Contains(ANotify) then FList.Add(ANotify); end; constructor TCustomEMSConnectionInfo.TNotifyList.Create; begin FList := TList<TNotifyEvent>.Create; end; destructor TCustomEMSConnectionInfo.TNotifyList.Destroy; begin FList.Free; inherited; end; procedure TCustomEMSConnectionInfo.TNotifyList.Notify(Sender: TObject); var LProc: TNotifyEvent; begin for LProc in FList do LProc(Sender); end; procedure TCustomEMSConnectionInfo.TNotifyList.Remove(const ANotify : TNotifyEvent); begin Assert(FList.Contains(ANotify)); FList.Remove(ANotify); end; { TCustomEMSProvider } function TCustomEMSProvider.GetProviderID: string; begin Result := ProviderID; end; { TEMSBackendService } constructor TEMSBackendService.Create(const AProvider: IBackendProvider); begin if AProvider is TCustomEMSConnectionInfo then ConnectionInfo := TCustomEMSConnectionInfo(AProvider) else raise EArgumentException.Create('AProvider'); // Do not localize end; destructor TEMSBackendService.Destroy; begin if Assigned(FConnectionInfo) then FConnectionInfo.NotifyOnChange.Remove(OnConnectionChanged); inherited; end; procedure TEMSBackendService.DoAfterConnectionChanged; begin // end; procedure TEMSBackendService.OnConnectionChanged(Sender: TObject); begin DoAfterConnectionChanged; end; procedure TEMSBackendService.SetConnectionInfo(const Value : TCustomEMSConnectionInfo); begin if FConnectionInfo <> nil then FConnectionInfo.NotifyOnChange.Remove(OnConnectionChanged); FConnectionInfo := Value; if FConnectionInfo <> nil then FConnectionInfo.NotifyOnChange.Add(OnConnectionChanged); OnConnectionChanged(Self); end; { TKinveyServiceAPI } constructor TEMSServiceAPI.Create; begin FEMSAPI := TEMSClientAPI.Create(nil); end; destructor TEMSServiceAPI.Destroy; begin FEMSAPI.Free; inherited; end; function TEMSServiceAPI.GetEMSAPI: TEMSClientAPI; begin Result := FEMSAPI; end; { TEMSBackendService<TAPI> } function TEMSBackendService<TAPI>.CreateBackendApi: TAPI; begin Result := TAPI.Create; if ConnectionInfo <> nil then ConnectionInfo.UpdateApi(Result.FEMSAPI) else Result.FEMSAPI.ConnectionInfo := TEMSClientAPI.EmptyConnectionInfo; end; procedure TEMSBackendService<TAPI>.EnsureBackendApi; begin if FBackendAPI = nil then begin FBackendAPI := CreateBackendApi; FBackendAPIIntf := FBackendAPI; // Reference end; end; function TEMSBackendService<TAPI>.GetEMSAPI: TEMSClientAPI; begin EnsureBackendApi; if FBackendAPI <> nil then Result := FBackendAPI.FEMSAPI; end; procedure TEMSBackendService<TAPI>.DoAfterConnectionChanged; begin if FBackendAPI <> nil then begin if ConnectionInfo <> nil then ConnectionInfo.UpdateApi(FBackendAPI.FEMSAPI) else FBackendAPI.FEMSAPI.ConnectionInfo := TEMSClientAPI.EmptyConnectionInfo; end; end; { TKinveyServiceAPIAuth } function TEMSServiceAPIAuth.GetAuthentication: TBackendAuthentication; begin case EMSAPI.Authentication of TEMSClientAPI.TAuthentication.Default: Result := TBackendAuthentication.Default; TEMSClientAPI.TAuthentication.MasterSecret: Result := TBackendAuthentication.Root; // TEMSClientAPI.TAuthentication.UserName: // Result := TBackendAuthentication.User; TEMSClientAPI.TAuthentication.Session: Result := TBackendAuthentication.Session; TEMSClientAPI.TAuthentication.AppSecret: Result := TBackendAuthentication.Application; TEMSClientAPI.TAuthentication.None: Result := TBackendAuthentication.None; else Result := TBackendAuthentication.Default; end; end; function TEMSServiceAPIAuth.GetDefaultAuthentication : TBackendDefaultAuthentication; begin case EMSAPI.DefaultAuthentication of TEMSClientAPI.TDefaultAuthentication.MasterSecret: Result := TBackendDefaultAuthentication.Root; // TEMSClientAPI.TDefaultAuthentication.UserName: // Result := TBackendDefaultAuthentication.User; TEMSClientAPI.TDefaultAuthentication.Session: Result := TBackendDefaultAuthentication.Session; TEMSClientAPI.TDefaultAuthentication.AppSecret: Result := TBackendDefaultAuthentication.Application; TEMSClientAPI.TDefaultAuthentication.None: Result := TBackendDefaultAuthentication.None; else Result := TBackendDefaultAuthentication.None; end; end; procedure TEMSServiceAPIAuth.Login(const ALogin: TBackendEntityValue); var LMetaLogin: TMetaLogin; begin if ALogin.Data is TMetaLogin then begin LMetaLogin := TMetaLogin(ALogin.Data); EMSAPI.Login(LMetaLogin.Login); end else raise EArgumentException.Create(sParameterNotLogin); end; procedure TEMSServiceAPIAuth.Logout; begin EMSAPI.Logout; end; procedure TEMSServiceAPIAuth.SetAuthentication(AAuthentication : TBackendAuthentication); begin case AAuthentication of TBackendAuthentication.Default: FEMSAPI.Authentication := TEMSClientAPI.TAuthentication.Default; TBackendAuthentication.Root: FEMSAPI.Authentication := TEMSClientAPI.TAuthentication.MasterSecret; TBackendAuthentication.Application: FEMSAPI.Authentication := TEMSClientAPI.TAuthentication.AppSecret; // TBackendAuthentication.User: // FKinveyAPI.Authentication := TEMSClientAPI.TAuthentication.UserName; TBackendAuthentication.Session: FEMSAPI.Authentication := TEMSClientAPI.TAuthentication.Session; TBackendAuthentication.None: FEMSAPI.Authentication := TEMSClientAPI.TAuthentication.None; TBackendAuthentication.User: raise EEMSProviderError.CreateFmt(sAuthenticationNotSupported, [ System.TypInfo.GetEnumName(TypeInfo(TBackendAuthentication), Integer(AAuthentication))]); else Assert(False); // Unexpected end; end; procedure TEMSServiceAPIAuth.SetDefaultAuthentication(ADefaultAuthentication : TBackendDefaultAuthentication); begin case ADefaultAuthentication of TBackendDefaultAuthentication.Root: FEMSAPI.DefaultAuthentication := TEMSClientAPI.TDefaultAuthentication. MasterSecret; TBackendDefaultAuthentication.Application: FEMSAPI.DefaultAuthentication := TEMSClientAPI.TDefaultAuthentication.AppSecret; // TBackendDefaultAuthentication.User: // FKinveyAPI.DefaultAuthentication := TEMSClientAPI.TDefaultAuthentication.UserName; TBackendDefaultAuthentication.Session: FEMSAPI.DefaultAuthentication := TEMSClientAPI.TDefaultAuthentication.Session; TBackendDefaultAuthentication.None: FEMSAPI.DefaultAuthentication := TEMSClientAPI.TDefaultAuthentication.None; TBackendDefaultAuthentication.User: raise EEMSProviderError.CreateFmt(sAuthenticationNotSupported, [ System.TypInfo.GetEnumName(TypeInfo(TBackendDefaultAuthentication), Integer(ADefaultAuthentication))]); else Assert(False); // Unexpected end; end; const sDisplayName = 'EMS'; { TCustomEMSConnectionInfo.TAndroidPush } procedure TCustomEMSConnectionInfo.TAndroidPush.AssignTo(AValue: TPersistent); begin if AValue is TAndroidPush then begin Self.FGCMAppID := TAndroidPush(AValue).FGCMAppID end else inherited; end; procedure TCustomEMSConnectionInfo.TAndroidPush.SetGCMAppID( const Value: string); begin if FGCMAppID <> Value then begin FGCMAppID := Value; FOwner.DoChanged; end; end; initialization TBackendProviders.Instance.Register(TCustomEMSProvider.ProviderID, sDisplayName); finalization TBackendProviders.Instance.UnRegister(TCustomEMSProvider.ProviderID); end.
{ Invokable implementation File for TSetExamState which implements ISetExamState } unit SetExamStateImpl; interface uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, SetExamStateIntf, Oracle; type { TSetExamState } TSetExamState = class(TInvokableClass, ISetExamState) public class var SendQueue: TOracleQueue; class var usn: string; class var pwd: string; function SetExamState(const pSetExamStateRequest: SetExamStateRequest): SetExamStateResponse; stdcall; end; implementation uses System.SysUtils; function TSetExamState.SetExamState(const pSetExamStateRequest: SetExamStateRequest): SetExamStateResponse; stdcall; var rCode: integer; rMsg: string; function FormatMsg(const ExceptionMessage: string): string; const maxErr = 2; exc: array[1..maxErr] of string = ('ORA-20000','ORA-20001'); var dove: integer; i: integer; begin result := ExceptionMessage; for i := 1 to maxErr do begin dove := Pos(exc[i],result); if dove>0 then begin result := Copy(result,dove+11,Length(result)-(dove+10)); dove := Pos(#10,result); if dove>0 then result := Copy(result,1,dove-1); break; end; end; end; begin Result := SetExamStateResponse.Create; if (pSetExamStateRequest.usn<>'hes') or (pSetExamStateRequest.pwd<>'4HesExState') then begin rCode := 500; rMsg := 'Nome utente o password errati'; end { else if (pSetExamStateRequest.appointment_id<>'123456') then begin rCode := 500; rMsg := format('Appuntamento %s non trovato',[pSetExamStateRequest.appointment_id]); end else if (pSetExamStateRequest.exam_type_id<>2) then begin rCode := 500; rMsg := format('Tipo esame %d non trovato',[pSetExamStateRequest.exam_type_id]); end } else if not (pSetExamStateRequest.exam_status in [1,2]) then begin rCode := 500; rMsg := format('Stato esame inviato non ammesso (%d)',[pSetExamStateRequest.exam_status]); end else begin rCode := 200; rMsg := ''; end; Result.res_code := rCode; Result.res_msg := rMsg; if (rCode=200) and (SendQueue<>nil) then begin // Create the message try SendQueue.Payload.SetAttr('appointment_id', pSetExamStateRequest.appointment_id); SendQueue.Payload.SetAttr('exam_id', pSetExamStateRequest.exam_id); SendQueue.Payload.SetAttr('exam_type_id', pSetExamStateRequest.exam_type_id); SendQueue.Payload.SetAttr('exam_status', pSetExamStateRequest.exam_status); SendQueue.Payload.SetAttr('exam_date', pSetExamStateRequest.exam_datetime.AsDateTime); // Enqueue the message SendQueue.Enqueue; // Commit the enqueue operation SendQueue.Session.Commit; except on E: Exception do begin Result.res_code := 500; Result.res_msg := FormatMsg(E.Message); // SendSession.RollBack; end; end; end; end; initialization { Invokable classes must be registered } InvRegistry.RegisterInvokableClass(TSetExamState); end.
unit uUsersOfTravel; interface uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd, System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes, System.Variants, FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr; type TUsersOfTravel = class(TCollectionItem) public Id: string; IdUser: string; IdTravel: string; State: string; Opinion: string; end; TUsersOfTravellist = class(TCollection) Procedure AddRecord(Id, IdUser, IdTravel, Opinion, State: string); Function ConnectToDb: TSQLConnection; procedure SaveUserOfTravel; procedure LoadUsersOfTravel; Procedure UpdateOrInsert(Item: TUsersOfTravel); end; implementation { TUsersOfTravellist } procedure TUsersOfTravellist.AddRecord(Id, IdUser, IdTravel, Opinion, State: string); Var Item: TUsersOfTravel; begin Item := TUsersOfTravel(self.Add); Item.Id := Id; Item.IdUser := IdUser; Item.IdTravel := IdTravel; Item.Opinion := Opinion; Item.State := State; end; function TUsersOfTravellist.ConnectToDb: TSQLConnection; var ASQLConnection: TSQLConnection; Path: string; begin ASQLConnection := TSQLConnection.Create(nil); ASQLConnection.ConnectionName := 'SQLITECONNECTION'; ASQLConnection.DriverName := 'Sqlite'; ASQLConnection.LoginPrompt := false; ASQLConnection.Params.Values['Host'] := 'localhost'; ASQLConnection.Params.Values['FailIfMissing'] := 'False'; ASQLConnection.Params.Values['ColumnMetaDataSupported'] := 'False'; Createdir(IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter('ExampleDb')); Path := IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter('ExampleDb') + 'ExampleDb.db'; ASQLConnection.Params.Values['Database'] := Path; ASQLConnection.Execute('CREATE TABLE if not exists UsersOfTravel(' + 'Id TEXT,' + 'IdUser TEXT,' + 'IdTravel TEXT,' + 'Opinion TEXT,' + 'State TEXT' + ');', nil); ASQLConnection.Open; result := ASQLConnection; end; procedure TUsersOfTravellist.LoadUsersOfTravel; var ASQLConnection: TSQLConnection; ResImage: TResourceStream; RS: TDataset; Item: TUsersOfTravel; begin ASQLConnection := ConnectToDb; try ASQLConnection.Execute ('select Id,IdUser,IdTravel, Opinion, State from UsersOfTravel', nil, RS); try while not RS.Eof do begin Item := TUsersOfTravel(self.Add); Item.Id := RS.FieldByName('Id').Value; Item.IdUser := RS.FieldByName('IdUser').Value; Item.IdTravel := RS.FieldByName('IdTravel').Value; Item.Opinion := RS.FieldByName('Opinion').Value; Item.State := RS.FieldByName('State').Value; RS.Next; end; finally freeandnil(RS); end; finally freeandnil(ASQLConnection); end; end; procedure TUsersOfTravellist.SaveUserOfTravel; var i: integer; DB: TSQLConnection; Params: TParams; query: string; begin query := 'INSERT INTO UsersOfTravel (Id,IdUser,IdTravel,Opinion,State) VALUES (:Id,:IdUser,:IdTravel,:Opinion,:State)'; DB := ConnectToDb; try for i := 0 to self.Count - 1 do begin Params := TParams.Create; Params.CreateParam(TFieldType.ftString, 'Id', ptInput); Params.ParamByName('Id').AsString := TUsersOfTravel(self.Items[i]).Id; Params.CreateParam(TFieldType.ftString, 'IdUser', ptInput); Params.ParamByName('IdUser').AsString := TUsersOfTravel(self.Items[i]).IdUser; Params.CreateParam(TFieldType.ftString, 'IdTravel', ptInput); Params.ParamByName('IdTravel').AsString := TUsersOfTravel(self.Items[i] ).IdTravel; Params.CreateParam(TFieldType.ftString, 'Opinion', ptInput); Params.ParamByName('Opinion').AsString := TUsersOfTravel(self.Items[i]).Opinion; Params.CreateParam(TFieldType.ftString, 'State', ptInput); Params.ParamByName('State').AsString := TUsersOfTravel(self.Items[i]).State; DB.Execute(query, Params); freeandnil(Params); end; finally freeandnil(DB); end; end; procedure TUsersOfTravellist.UpdateOrInsert(Item: TUsersOfTravel); const cInsertQuery = 'UPDATE UsersOfTravel SET `Id`= :Id,`IdTravel`= :IdTravel, `IdUser`= :IdUser,`Opinion` =:Opinion, `State`= :State WHERE IdUser="%s"'; var Image: TBitmap; query: String; querity: TSQLQuery; connect: TSQLConnection; Guid: TGUID; begin connect := ConnectToDb; querity := TSQLQuery.Create(nil); try querity.SQLConnection := connect; querity.SQL.Text := 'select IdUser from UsersOfTravel where IdUser = "' + Item.IdUser + '"'; querity.Open; if not querity.Eof then begin query := Format(cInsertQuery, [Item.IdUser]); querity.Params.CreateParam(TFieldType.ftString, 'Id', ptInput); querity.Params.ParamByName('Id').AsString := Item.Id; querity.Params.CreateParam(TFieldType.ftString, 'IdTravel', ptInput); querity.Params.ParamByName('IdTravel').AsString := Item.IdTravel; querity.Params.CreateParam(TFieldType.ftString, 'IdUser', ptInput); querity.Params.ParamByName('IdUser').AsString := Item.IdUser; querity.Params.CreateParam(TFieldType.ftString, 'Opinion', ptInput); querity.Params.ParamByName('Opinion').AsString := Item.Opinion; querity.Params.CreateParam(TFieldType.ftString, 'State', ptInput); querity.Params.ParamByName('State').AsString := Item.State; querity.SQL.Text := query; querity.ExecSQL(); end else begin query := 'INSERT INTO UsersOfTravel (Id,IdUser,IdTravel,Opinion,State) VALUES (:Id,:IdUser,:IdTravel,:Opinion,:State)'; querity.Params.CreateParam(TFieldType.ftString, 'Id', ptInput); querity.Params.ParamByName('Id').AsString := Item.Id; querity.Params.CreateParam(TFieldType.ftString, 'IdUser', ptInput); querity.Params.ParamByName('IdUser').AsString := Item.IdUser; querity.Params.CreateParam(TFieldType.ftString, 'IdTravel', ptInput); querity.Params.ParamByName('IdTravel').AsString := Item.IdTravel; querity.Params.CreateParam(TFieldType.ftString, 'Opinion', ptInput); querity.Params.ParamByName('Opinion').AsString := Item.Opinion; querity.Params.CreateParam(TFieldType.ftString, 'State', ptInput); querity.Params.ParamByName('State').AsString := Item.State; querity.SQL.Text := query; querity.ExecSQL(); end; finally freeandnil(querity); end; freeandnil(connect); end; end.
{ Oracle Deploy System ver.1.0 (ORDESY) by Volodymyr Sedler aka scribe 2016 Desc: wrap/deploy/save objects of oracle database. No warranty of using this program. Just Free. With bugs, suggestions please write to justscribe@yahoo.com On Github: github.com/justscribe/ORDESY Headers for read/write base types of delphi by functions (FileRead|FileWrite) } unit uFileRWTypes; interface uses SysUtils, Windows; // write procedure FileWriteString(const aHandle: integer; const aString: string); procedure FileWriteInteger(const aHandle: integer; const aInteger: integer); procedure FileWriteDateTime(const aHandle: integer; const aDateTime: TDateTime); procedure FileWriteBoolean(const aHandle: integer; const aBoolean: boolean); // read procedure FileReadString(const aHandle: integer; var aString: string); procedure FileReadInteger(const aHandle: integer; var aInteger: integer); procedure FileReadDateTime(const aHandle: integer; var aDateTime: TDateTime); procedure FileReadBoolean(const aHandle: integer; var aBoolean: boolean); implementation procedure FileReadBoolean(const aHandle: integer; var aBoolean: boolean); begin FileRead(aHandle, aBoolean, sizeof(aBoolean)); end; procedure FileReadDateTime(const aHandle: integer; var aDateTime: TDateTime); begin FileRead(aHandle, aDateTime, sizeof(aDateTime)); end; procedure FileReadInteger(const aHandle: integer; var aInteger: integer); begin FileRead(aHandle, aInteger, sizeof(aInteger)); end; procedure FileReadString(const aHandle: integer; var aString: string); var strSize: integer; begin FileRead(aHandle, strSize, sizeof(strSize)); SetLength(aString, strSize); FileRead(aHandle, aString[1], strSize * sizeof(char)); end; procedure FileWriteBoolean(const aHandle: integer; const aBoolean: boolean); begin FileWrite(aHandle, aBoolean, sizeof(aBoolean)); end; procedure FileWriteDateTime(const aHandle: integer; const aDateTime: TDateTime); begin FileWrite(aHandle, aDateTime, sizeof(aDateTime)); end; procedure FileWriteInteger(const aHandle, aInteger: integer); begin FileWrite(aHandle, aInteger, sizeof(aInteger)); end; procedure FileWriteString(const aHandle: integer; const aString: string); var strSize: integer; begin strSize:= length(aString); FileWrite(aHandle, strSize, sizeof(strSize)); FileWrite(aHandle, aString[1], strSize * sizeof(char)); end; end.
unit Model.Connection; interface uses System.SysUtils, System.Classes, Model.Base, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.Phys.SQLite, FireDAC.Comp.UI, Data.DB, FireDAC.Comp.Client, FireDAC.Comp.ScriptCommands, FireDAC.Stan.Util, FireDAC.Comp.Script, Vcl.AppEvnts, FireDAC.VCLUI.Wait; type TdtmdlConnection = class(TdtmdlBase) conConnection: TFDConnection; Cursor: TFDGUIxWaitCursor; Driver: TFDPhysSQLiteDriverLink; fdscrptScript: TFDScript; aplctnvntsExcept: TApplicationEvents; procedure aplctnvntsExceptException(Sender: TObject; E: Exception); procedure DataModuleCreate(Sender: TObject); private { Private declarations } public procedure CreateBaseScript; end; var dtmdlConnection: TdtmdlConnection; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TdtmdlConnection.aplctnvntsExceptException(Sender: TObject; E: Exception); begin inherited; InsertException(E); end; procedure TdtmdlConnection.CreateBaseScript; var I: Integer; begin try for I := 0 to Pred(fdscrptScript.SQLScripts.Count) do conConnection.ExecSQL(fdscrptScript.SQLScripts.Items[I].SQL.Text); except on E: Exception do begin InsertException(E); raise; end; end; end; procedure TdtmdlConnection.DataModuleCreate(Sender: TObject); begin inherited; conConnection.Params.Values['DataBase'] := ExtractFilePath(ParamStr(0)) + 'AutoPosto.s3db'; end; end.
unit fOptionsCombinations; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ORCtrls, OrFn, ComCtrls, fBase508Form, VA508AccessibilityManager; type TfrmOptionsCombinations = class(TfrmBase508Form) radAddByType: TRadioGroup; lblInfo: TMemo; lblAddby: TLabel; lblCombinations: TLabel; lstAddBy: TORComboBox; btnAdd: TButton; btnRemove: TButton; pnlBottom: TPanel; btnOK: TButton; btnCancel: TButton; bvlBottom: TBevel; lvwCombinations: TCaptionListView; procedure radAddByTypeClick(Sender: TObject); procedure lstAddByNeedData(Sender: TObject; const StartFrom: String; Direction, InsertAt: Integer); procedure FormCreate(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure lvwCombinationsColumnClick(Sender: TObject; Column: TListColumn); procedure lvwCombinationsCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure btnRemoveClick(Sender: TObject); procedure lstAddByChange(Sender: TObject); procedure lstAddByKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnOKClick(Sender: TObject); procedure lstAddByEnter(Sender: TObject); procedure lstAddByExit(Sender: TObject); procedure lvwCombinationsChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure FormShow(Sender: TObject); private { Private declarations } FsortCol: integer; FsortAscending: boolean; FDirty: boolean; function Duplicate(avalueien, asource: string): boolean; procedure LoadCombinations(alist: TStrings); public { Public declarations } end; var frmOptionsCombinations: TfrmOptionsCombinations; procedure DialogOptionsCombinations(topvalue, leftvalue, fontsize: integer; var actiontype: Integer); implementation uses rOptions, rCore; {$R *.DFM} type TCombination = class public IEN: string; Entry: string; Source: string; end; procedure DialogOptionsCombinations(topvalue, leftvalue, fontsize: integer; var actiontype: Integer); // create the form and make it modal, return an action var frmOptionsCombinations: TfrmOptionsCombinations; begin frmOptionsCombinations := TfrmOptionsCombinations.Create(Application); actiontype := 0; try with frmOptionsCombinations do begin if (topvalue < 0) or (leftvalue < 0) then Position := poScreenCenter else begin Position := poDesigned; Top := topvalue; Left := leftvalue; end; ResizeAnchoredFormToFont(frmOptionsCombinations); ShowModal; actiontype := btnOK.Tag; end; finally frmOptionsCombinations.Release; end; end; procedure TfrmOptionsCombinations.radAddByTypeClick(Sender: TObject); begin with lstAddBy do begin case radAddByType.ItemIndex of 0: begin ListItemsOnly := false; LongList := false; ListWardAll(lstAddBy.Items); MixedCaseList(lstAddBy.Items); lblAddby.Caption := 'Ward:'; end; 1: begin ListItemsOnly := true; LongList := true; InitLongList(''); lblAddby.Caption := 'Clinic:'; end; 2: begin ListItemsOnly := true; LongList := true; InitLongList(''); lblAddby.Caption := 'Provider:'; end; 3: begin ListItemsOnly := false; LongList := false; ListSpecialtyAll(lstAddBy.Items); lblAddby.Caption := 'Specialty:'; end; 4: begin ListItemsOnly := false; LongList := false; ListTeamAll(lstAddBy.Items); lblAddby.Caption := 'List:'; end; 5: begin // TDP - Added 5/27/2014 PCMM team mods ListItemsOnly := false; LongList := false; ListPcmmAll(lstAddBy.Items); lblAddby.Caption := 'PCMM:'; end; end; lstAddBy.Caption := lblAddby.Caption; ItemIndex := -1; Text := ''; btnAdd.Enabled := false; end; end; procedure TfrmOptionsCombinations.lstAddByNeedData(Sender: TObject; const StartFrom: String; Direction, InsertAt: Integer); begin with lstAddBy do begin case radAddByType.ItemIndex of 0: begin Pieces := '2'; end; 1: begin Pieces := '2'; ForDataUse(SubSetOfClinics(StartFrom, Direction)); end; 2: begin Pieces := '2,3'; ForDataUse(SubSetOfProviders(StartFrom, Direction)); end; 3: begin Pieces := '2'; end; 4: begin Pieces := '2'; end; end; end; end; procedure TfrmOptionsCombinations.FormCreate(Sender: TObject); begin radAddByType.ItemIndex := 0; radAddByTypeClick(self); FDirty := false; end; procedure TfrmOptionsCombinations.btnAddClick(Sender: TObject); var aListItem: TListItem; aCombination: TCombination; valueien, valuename, valuesource: string; begin valuesource := radAddByType.Items[radAddByType.ItemIndex]; if copy(valuesource, 1, 1) = '&' then valuesource := copy(valuesource, 2, length(valuesource) - 1); // TDP - Added 5/27/2014 to handle PCMM team addition if copy(valuesource, 3, 1) = '&' then valuesource := copy(valuesource, 1, 2) + copy(valuesource, 4, length(valuesource) - 1); { if radAddByType.ItemIndex = 2 then valuename := Piece(lstAddBy.DisplayText[lstAddBy.ItemIndex], '-', 1) else } //Removed per PTM 274 - should not peice by the "-" at all valuename := lstAddBy.DisplayText[lstAddBy.ItemIndex]; valueien := Piece(lstAddBy.Items[lstAddBy.ItemIndex], '^', 1); if Duplicate(valueien, valuesource) then exit; // check for duplicates aListItem := lvwCombinations.Items.Add; with aListItem do begin Caption := valuename; SubItems.Add(valuesource); end; aCombination := TCombination.Create; with aCombination do begin IEN := valueien; Entry := valuename; Source := valuesource; end; aListItem.SubItems.AddObject('combo object', aCombination); btnAdd.Enabled := false; FDirty := true; end; procedure TfrmOptionsCombinations.lvwCombinationsColumnClick( Sender: TObject; Column: TListColumn); begin if FsortCol = Column.Index then FsortAscending := not FsortAscending else FsortAscending := true; FsortCol := Column.Index; (Sender as TListView).AlphaSort; end; procedure TfrmOptionsCombinations.lvwCombinationsCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); begin if not(Sender is TListView) then exit; if FsortAscending then begin if FsortCol = 0 then Compare := CompareStr(Item1.Caption, Item2.Caption) else Compare := CompareStr(Item1.SubItems[FsortCol - 1], Item2.SubItems[FsortCol - 1]); end else begin if FsortCol = 0 then Compare := CompareStr(Item2.Caption, Item1.Caption) else Compare := CompareStr(Item2.SubItems[FsortCol - 1], Item1.SubItems[FsortCol - 1]); end; end; procedure TfrmOptionsCombinations.btnRemoveClick(Sender: TObject); var i: integer; begin with lvwCombinations do for i := Items.Count - 1 downto 0 do if Items[i].Selected then Items[i].Delete; btnRemove.Enabled := false; FDirty := true; end; procedure TfrmOptionsCombinations.lstAddByChange(Sender: TObject); var valueien, source: string; begin if lstAddBy.ItemIndex = -1 then btnAdd.Enabled := false else begin source := radAddByType.Items[radAddByType.ItemIndex]; if copy(source, 1, 1) = '&' then source := copy(source, 2, length(source) - 1); // TDP - Added 5/27/2014 to handle PCMM team addition if copy(source, 3, 1) = '&' then source := copy(source, 1, 2) + copy(source, 4, length(source) - 1); valueien := Piece(lstAddBy.Items[lstAddBy.ItemIndex], '^', 1); btnAdd.Enabled := not Duplicate(valueien, source); end; btnRemove.Enabled := false; end; function TfrmOptionsCombinations.Duplicate(avalueien, asource: string): boolean; var i: integer; aCombination :TCombination; begin result := false; with lvwCombinations do for i := 0 to Items.Count - 1 do if asource = Items[i].Subitems[0] then begin aCombination := TCombination(Items.Item[i].SubItems.Objects[1]); if aCombination.IEN = avalueien then begin Result := true; end; end; end; procedure TfrmOptionsCombinations.lstAddByKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = 13 then Perform(WM_NextDlgCtl, 0, 0); end; procedure TfrmOptionsCombinations.btnOKClick(Sender: TObject); var i: Integer; alist: TStringList; aCombination: TCombination; begin if FDirty then begin alist := TStringList.Create; try with lvwCombinations do for i := 0 to Items.Count - 1 do begin aCombination := TCombination(Items.Item[i].SubItems.Objects[1]); with aCombination do alist.Add(IEN + '^' + Source); end; rpcSetCombo(alist); finally alist.Free; end; end; end; procedure TfrmOptionsCombinations.lstAddByEnter(Sender: TObject); begin btnAdd.Default := true; end; procedure TfrmOptionsCombinations.lstAddByExit(Sender: TObject); begin btnAdd.Default := false; end; procedure TfrmOptionsCombinations.lvwCombinationsChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin btnRemove.Enabled := lvwCombinations.SelCount > 0; end; procedure TfrmOptionsCombinations.LoadCombinations(alist: TStrings); var i: integer; aListItem: TListItem; aCombination: TCombination; valueien, valuename, valuesource: string; begin for i := 0 to alist.Count - 1 do begin valuesource := Piece(alist[i], '^', 1); valuename := Piece(alist[i], '^', 2); valueien := Piece(alist[i], '^', 3); aListItem := lvwCombinations.Items.Add; with aListItem do begin Caption := valuename; SubItems.Add(valuesource); end; aCombination := TCombination.Create; with aCombination do begin IEN := valueien; Entry := valuename; Source := valuesource; end; aListItem.SubItems.AddObject('combo object', aCombination); end; end; procedure TfrmOptionsCombinations.FormShow(Sender: TObject); var aResults: TStringList; begin aResults := TStringList.Create; try rpcGetCombo(aResults); LoadCombinations(aResults); finally FreeAndNil(aResults); end; end; end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // {$POINTERMATH ON} unit RN_DetourObstacleAvoidance; interface uses Math, SysUtils; type PdtObstacleCircle = ^TdtObstacleCircle; TdtObstacleCircle = record p: array [0..2] of Single; ///< Position of the obstacle vel: array [0..2] of Single; ///< Velocity of the obstacle dvel: array [0..2] of Single; ///< Velocity of the obstacle rad: Single; ///< Radius of the obstacle dp, np: array [0..2] of Single; ///< Use for side selection during sampling. end; PdtObstacleSegment = ^TdtObstacleSegment; TdtObstacleSegment = record p, q: array [0..2] of Single; ///< End points of the obstacle segment touch: Boolean; end; TdtObstacleAvoidanceDebugData = class public constructor Create; destructor Destroy; override; function init(const maxSamples: Integer): Boolean; procedure reset(); procedure addSample(const vel: PSingle; const ssize, pen, vpen, vcpen, spen, tpen: Single); procedure normalizeSamples(); function getSampleCount(): Integer; function getSampleVelocity(i: Integer): PSingle; function getSampleSize(i: Integer): Single; function getSamplePenalty(i: Integer): Single; function getSampleDesiredVelocityPenalty(i: Integer): Single; function getSampleCurrentVelocityPenalty(i: Integer): Single; function getSamplePreferredSidePenalty(i: Integer): Single; function getSampleCollisionTimePenalty(i: Integer): Single; private m_nsamples: Integer; m_maxSamples: Integer; m_vel: PSingle; m_ssize: PSingle; m_pen: PSingle; m_vpen: PSingle; m_vcpen: PSingle; m_spen: PSingle; m_tpen: PSingle; end; function dtAllocObstacleAvoidanceDebugData(): TdtObstacleAvoidanceDebugData; procedure dtFreeObstacleAvoidanceDebugData(var ptr: TdtObstacleAvoidanceDebugData); const DT_MAX_PATTERN_DIVS = 32; ///< Max numver of adaptive divs. DT_MAX_PATTERN_RINGS = 4; ///< Max number of adaptive rings. type PdtObstacleAvoidanceParams = ^TdtObstacleAvoidanceParams; TdtObstacleAvoidanceParams = record velBias: Single; weightDesVel: Single; weightCurVel: Single; weightSide: Single; weightToi: Single; horizTime: Single; gridSize: Byte; ///< grid adaptiveDivs: Byte; ///< adaptive adaptiveRings: Byte; ///< adaptive adaptiveDepth: Byte; ///< adaptive end; TdtObstacleAvoidanceQuery = class public constructor Create; destructor Destroy; override; function init(const maxCircles, maxSegments: Integer): Boolean; procedure reset(); procedure addCircle(const pos: PSingle; const rad: Single; const vel, dvel: PSingle); procedure addSegment(const p, q: PSingle); function sampleVelocityGrid(const pos: PSingle; const rad, vmax: Single; const vel, dvel, nvel: PSingle; const params: PdtObstacleAvoidanceParams; debug: TdtObstacleAvoidanceDebugData = nil): Integer; function sampleVelocityAdaptive(const pos: PSingle; const rad, vmax: Single; const vel, dvel, nvel: PSingle; const params: PdtObstacleAvoidanceParams; debug: TdtObstacleAvoidanceDebugData = nil): Integer; function getObstacleCircleCount(): Integer; { return m_ncircles; } function getObstacleCircle(i: Integer): PdtObstacleCircle; { return &m_circles[i]; } function getObstacleSegmentCount(): Integer; { return m_nsegments; } function getObstacleSegment(i: Integer): PdtObstacleSegment; { return &m_segments[i]; } private procedure prepare(const pos, dvel: PSingle); function processSample(const vcand: PSingle; const cs: Single; const pos: PSingle; const rad: Single; const vel, dvel: PSingle; const minPenalty: Single; debug: TdtObstacleAvoidanceDebugData): Single; // Delphi: Unused ever? function insertCircle(const dist: Single): PdtObstacleCircle; // Delphi: Unused ever? function insertSegment(const dist: Single): PdtObstacleSegment; private m_params: TdtObstacleAvoidanceParams; m_invHorizTime: Single; m_vmax: Single; m_invVmax: Single; m_maxCircles: Integer; m_circles: PdtObstacleCircle; m_ncircles: Integer; m_maxSegments: Integer; m_segments: PdtObstacleSegment; m_nsegments: Integer; end; function dtAllocObstacleAvoidanceQuery(): TdtObstacleAvoidanceQuery; procedure dtFreeObstacleAvoidanceQuery(var ptr: TdtObstacleAvoidanceQuery); implementation uses RN_DetourCommon; function sweepCircleCircle(const c0: PSingle; const r0: Single; const v: PSingle; const c1: PSingle; const r1: Single; tmin, tmax: PSingle): Integer; const EPS = 0.0001; var s: array [0..2] of Single; r,c,a,b,d,rd: Single; begin dtVsub(@s[0],c1,c0); r := r0+r1; c := dtVdot2D(@s[0],@s[0]) - r*r; a := dtVdot2D(v,v); if (a < EPS) then Exit(0); // not moving // Overlap, calc time to exit. b := dtVdot2D(v,@s[0]); d := b*b - a*c; if (d < 0.0) then Exit(0); // no intersection. a := 1.0 / a; rd := Sqrt(d); tmin^ := (b - rd) * a; tmax^ := (b + rd) * a; Result := 1; end; function isectRaySeg(const ap, u, bp, bq: PSingle; t: PSingle): Integer; var v,w: array [0..2] of Single; d,s: Single; begin dtVsub(@v[0],bq,bp); dtVsub(@w[0],ap,bp); d := dtVperp2D(u,@v[0]); if (abs(d) < 0.000001) then Exit(0); d := 1.0/d; t^ := dtVperp2D(@v[0],@w[0]) * d; if (t^ < 0) or (t^ > 1) then Exit(0); s := dtVperp2D(u,@w[0]) * d; if (s < 0) or (s > 1) then Exit(0); Result := 1; end; function dtAllocObstacleAvoidanceDebugData(): TdtObstacleAvoidanceDebugData; begin Result := TdtObstacleAvoidanceDebugData.Create; end; procedure dtFreeObstacleAvoidanceDebugData(var ptr: TdtObstacleAvoidanceDebugData); begin FreeAndNil(ptr); end; constructor TdtObstacleAvoidanceDebugData.Create(); begin inherited; m_nsamples := 0; m_maxSamples := 0; m_vel := nil; m_ssize := nil; m_pen := nil; m_vpen := nil; m_vcpen := nil; m_spen := nil; m_tpen := nil; end; destructor TdtObstacleAvoidanceDebugData.Destroy; begin if m_vel <> nil then FreeMem(m_vel); if m_ssize <> nil then FreeMem(m_ssize); if m_pen <> nil then FreeMem(m_pen); if m_vpen <> nil then FreeMem(m_vpen); if m_vcpen <> nil then FreeMem(m_vcpen); if m_spen <> nil then FreeMem(m_spen); if m_tpen <> nil then FreeMem(m_tpen); inherited; end; function TdtObstacleAvoidanceDebugData.init(const maxSamples: Integer): Boolean; begin Assert(maxSamples <> 0); m_maxSamples := maxSamples; GetMem(m_vel, sizeof(Single)*3*m_maxSamples); GetMem(m_pen, sizeof(Single)*m_maxSamples); GetMem(m_ssize, sizeof(Single)*m_maxSamples); GetMem(m_vpen, sizeof(Single)*m_maxSamples); GetMem(m_vcpen, sizeof(Single)*m_maxSamples); GetMem(m_spen, sizeof(Single)*m_maxSamples); GetMem(m_tpen, sizeof(Single)*m_maxSamples); Result := true; end; procedure TdtObstacleAvoidanceDebugData.reset(); begin m_nsamples := 0; end; procedure TdtObstacleAvoidanceDebugData.addSample(const vel: PSingle; const ssize, pen, vpen, vcpen, spen, tpen: Single); begin if (m_nsamples >= m_maxSamples) then Exit; Assert(m_vel <> nil); Assert(m_ssize <> nil); Assert(m_pen <> nil); Assert(m_vpen <> nil); Assert(m_vcpen <> nil); Assert(m_spen <> nil); Assert(m_tpen <> nil); dtVcopy(@m_vel[m_nsamples*3], vel); m_ssize[m_nsamples] := ssize; m_pen[m_nsamples] := pen; m_vpen[m_nsamples] := vpen; m_vcpen[m_nsamples] := vcpen; m_spen[m_nsamples] := spen; m_tpen[m_nsamples] := tpen; Inc(m_nsamples); end; procedure normalizeArray(arr: PSingle; const n: Integer); var minPen, maxPen, penRange, s: Single; i: Integer; begin // Normalize penaly range. minPen := MaxSingle; maxPen := -MaxSingle; for i := 0 to n - 1 do begin minPen := dtMin(minPen, arr[i]); maxPen := dtMax(maxPen, arr[i]); end; penRange := maxPen-minPen; if penRange > 0.001 then s := 1.0 / penRange else s := 1; for i := 0 to n - 1 do arr[i] := dtClamp((arr[i]-minPen)*s, 0.0, 1.0); end; procedure TdtObstacleAvoidanceDebugData.normalizeSamples(); begin normalizeArray(m_pen, m_nsamples); normalizeArray(m_vpen, m_nsamples); normalizeArray(m_vcpen, m_nsamples); normalizeArray(m_spen, m_nsamples); normalizeArray(m_tpen, m_nsamples); end; function TdtObstacleAvoidanceDebugData.getSampleCount(): Integer; begin Result := m_nsamples; end; function TdtObstacleAvoidanceDebugData.getSampleVelocity(i: Integer): PSingle; begin Result := @m_vel[i*3]; end; function TdtObstacleAvoidanceDebugData.getSampleSize(i: Integer): Single; begin Result := m_ssize[i]; end; function TdtObstacleAvoidanceDebugData.getSamplePenalty(i: Integer): Single; begin Result := m_pen[i]; end; function TdtObstacleAvoidanceDebugData.getSampleDesiredVelocityPenalty(i: Integer): Single; begin Result := m_vpen[i]; end; function TdtObstacleAvoidanceDebugData.getSampleCurrentVelocityPenalty(i: Integer): Single; begin Result := m_vcpen[i]; end; function TdtObstacleAvoidanceDebugData.getSamplePreferredSidePenalty(i: Integer): Single; begin Result := m_spen[i]; end; function TdtObstacleAvoidanceDebugData.getSampleCollisionTimePenalty(i: Integer): Single; begin Result := m_tpen[i]; end; function dtAllocObstacleAvoidanceQuery(): TdtObstacleAvoidanceQuery; begin Result := TdtObstacleAvoidanceQuery.Create; end; procedure dtFreeObstacleAvoidanceQuery(var ptr: TdtObstacleAvoidanceQuery); begin FreeAndNil(ptr); end; constructor TdtObstacleAvoidanceQuery.Create(); begin inherited; m_maxCircles := 0; m_circles := nil; m_ncircles := 0; m_maxSegments := 0; m_segments := nil; m_nsegments := 0; end; destructor TdtObstacleAvoidanceQuery.Destroy; begin FreeMem(m_circles); FreeMem(m_segments); inherited; end; function TdtObstacleAvoidanceQuery.init(const maxCircles, maxSegments: Integer): Boolean; begin m_maxCircles := maxCircles; m_ncircles := 0; GetMem(m_circles, sizeof(TdtObstacleCircle)*m_maxCircles); FillChar(m_circles[0], sizeof(TdtObstacleCircle)*m_maxCircles, 0); m_maxSegments := maxSegments; m_nsegments := 0; GetMem(m_segments, sizeof(TdtObstacleSegment)*m_maxSegments); FillChar(m_segments[0], sizeof(TdtObstacleSegment)*m_maxSegments, 0); Result := true; end; procedure TdtObstacleAvoidanceQuery.reset(); begin m_ncircles := 0; m_nsegments := 0; end; procedure TdtObstacleAvoidanceQuery.addCircle(const pos: PSingle; const rad: Single; const vel, dvel: PSingle); var cir: PdtObstacleCircle; begin if (m_ncircles >= m_maxCircles) then Exit; cir := @m_circles[m_ncircles]; Inc(m_ncircles); dtVcopy(@cir.p, pos); cir.rad := rad; dtVcopy(@cir.vel[0], vel); dtVcopy(@cir.dvel[0], dvel); end; procedure TdtObstacleAvoidanceQuery.addSegment(const p, q: PSingle); var seg: PdtObstacleSegment; begin if (m_nsegments >= m_maxSegments) then Exit; seg := @m_segments[m_nsegments]; Inc(m_nsegments); dtVcopy(@seg.p, p); dtVcopy(@seg.q[0], q); end; procedure TdtObstacleAvoidanceQuery.prepare(const pos, dvel: PSingle); var i: Integer; cir: PdtObstacleCircle; pa,pb: PSingle; orig,dv: array [0..2] of Single; a,r,t: Single; seg: PdtObstacleSegment; begin // Prepare obstacles for i := 0 to m_ncircles - 1 do begin cir := @m_circles[i]; // Side pa := pos; pb := @cir.p; orig[0] := 0; orig[1] := 0; orig[2] := 0; dtVsub(@cir.dp[0],pb,pa); dtVnormalize(@cir.dp[0]); dtVsub(@dv[0], @cir.dvel[0], dvel); a := dtTriArea2D(@orig[0], @cir.dp[0], @dv[0]); if (a < 0.01) then begin cir.np[0] := -cir.dp[2]; cir.np[2] := cir.dp[0]; end else begin cir.np[0] := cir.dp[2]; cir.np[2] := -cir.dp[0]; end; end; for i := 0 to m_nsegments - 1 do begin seg := @m_segments[i]; // Precalc if the agent is really close to the segment. r := 0.01; seg.touch := dtDistancePtSegSqr2D(pos, @seg.p, @seg.q[0], @t) < Sqr(r); end; end; (* Calculate the collision penalty for a given velocity vector * * @param vcand sampled velocity * @param dvel desired velocity * @param minPenalty threshold penalty for early out *) function TdtObstacleAvoidanceQuery.processSample(const vcand: PSingle; const cs: Single; const pos: PSingle; const rad: Single; const vel, dvel: PSingle; const minPenalty: Single; debug: TdtObstacleAvoidanceDebugData): Single; const FLT_EPSILON = 1.19209290E-07; // decimal constant var vpen, vcpen, minPen, tmin, side: Single; tThresold: Double; nside,i: Integer; cir: PdtObstacleCircle; vab, sdir, snorm: array [0..2] of Single; htmin, htmax,spen, tpen, penalty: Single; seg: PdtObstacleSegment; begin // penalty for straying away from the desired and current velocities vpen := m_params.weightDesVel * (dtVdist2D(vcand, dvel) * m_invVmax); vcpen := m_params.weightCurVel * (dtVdist2D(vcand, vel) * m_invVmax); // find the threshold hit time to bail out based on the early out penalty // (see how the penalty is calculated below to understnad) minPen := minPenalty - vpen - vcpen; tThresold := (m_params.weightToi/minPen - 0.1) * m_params.horizTime; if (tThresold - m_params.horizTime > -FLT_EPSILON) then Exit(minPenalty); // already too much // Find min time of impact and exit amongst all obstacles. tmin := m_params.horizTime; side := 0; nside := 0; for i := 0 to m_ncircles - 1 do begin cir := @m_circles[i]; // RVO dtVscale(@vab[0], vcand, 2); dtVsub(@vab[0], @vab[0], vel); dtVsub(@vab[0], @vab[0], @cir.vel[0]); // Side side := side + dtClamp(dtMin(dtVdot2D(@cir.dp[0],@vab[0])*0.5+0.5, dtVdot2D(@cir.np[0],@vab[0])*2), 0.0, 1.0); Inc(nside); htmin := 0; htmax := 0; if (sweepCircleCircle(pos,rad, @vab[0], @cir.p,cir.rad, @htmin, @htmax) = 0) then continue; // Handle overlapping obstacles. if (htmin < 0.0) and (htmax > 0.0) then begin // Avoid more when overlapped. htmin := -htmin * 0.5; end; if (htmin >= 0.0) then begin // The closest obstacle is somewhere ahead of us, keep track of nearest obstacle. if (htmin < tmin) then begin tmin := htmin; if (tmin < tThresold) then Exit(minPenalty); end; end; end; for i := 0 to m_nsegments - 1 do begin seg := @m_segments[i]; htmin := 0; if (seg.touch) then begin // Special case when the agent is very close to the segment. dtVsub(@sdir[0], @seg.q[0], @seg.p[0]); snorm[0] := -sdir[2]; snorm[2] := sdir[0]; // If the velocity is pointing towards the segment, no collision. if (dtVdot2D(@snorm[0], vcand) < 0.0) then continue; // Else immediate collision. htmin := 0.0; end else begin if (isectRaySeg(pos, vcand, @seg.p[0], @seg.q[0], @htmin) = 0) then continue; end; // Avoid less when facing walls. htmin := htmin * 2.0; // The closest obstacle is somewhere ahead of us, keep track of nearest obstacle. if (htmin < tmin) then begin tmin := htmin; if (tmin < tThresold) then Exit(minPenalty); end; end; // Normalize side bias, to prevent it dominating too much. if (nside <> 0) then side := side / nside; spen := m_params.weightSide * side; tpen := m_params.weightToi * (1.0 / (0.1 + tmin*m_invHorizTime)); penalty := vpen + vcpen + spen + tpen; // Store different penalties for debug viewing if (debug <> nil) then debug.addSample(vcand, cs, penalty, vpen, vcpen, spen, tpen); Result := penalty; end; function TdtObstacleAvoidanceQuery.sampleVelocityGrid(const pos: PSingle; const rad, vmax: Single; const vel, dvel, nvel: PSingle; const params: PdtObstacleAvoidanceParams; debug: TdtObstacleAvoidanceDebugData = nil): Integer; var cvx,cvz,cs,half,minPenalty,penalty: Single; ns,y,x: Integer; vcand: array [0..2] of Single; begin prepare(pos, dvel); Move(params^, m_params, sizeof(TdtObstacleAvoidanceParams)); m_invHorizTime := 1.0 / m_params.horizTime; m_vmax := vmax; if vmax > 0 then m_invVmax := 1.0 / vmax else m_invVmax := MaxSingle; dtVset(nvel, 0,0,0); if (debug <> nil) then debug.reset(); cvx := dvel[0] * m_params.velBias; cvz := dvel[2] * m_params.velBias; cs := vmax * 2 * (1 - m_params.velBias) / (m_params.gridSize-1); half := (m_params.gridSize-1)*cs*0.5; minPenalty := MaxSingle; ns := 0; for y := 0 to m_params.gridSize - 1 do begin for x := 0 to m_params.gridSize - 1 do begin vcand[0] := cvx + x*cs - half; vcand[1] := 0; vcand[2] := cvz + y*cs - half; if (Sqr(vcand[0])+Sqr(vcand[2]) > Sqr(vmax+cs/2)) then continue; penalty := processSample(@vcand[0], cs, pos,rad,vel,dvel, minPenalty, debug); Inc(ns); if (penalty < minPenalty) then begin minPenalty := penalty; dtVcopy(nvel, @vcand[0]); end; end; end; Result := ns; end; // vector normalization that ignores the y-component. procedure dtNormalize2D(v: PSingle); var d: Single; begin d := Sqrt(v[0]*v[0]+v[2]*v[2]); if (d=0) then Exit; d := 1.0 / d; v[0] := v[0] * d; v[2] := v[2] * d; end; // vector normalization that ignores the y-component. procedure dtRorate2D(dest, v: PSingle; ang: Single); var c,s: Single; begin c := cos(ang); s := sin(ang); dest[0] := v[0]*c - v[2]*s; dest[2] := v[0]*s + v[2]*c; dest[1] := v[1]; end; function TdtObstacleAvoidanceQuery.sampleVelocityAdaptive(const pos: PSingle; const rad, vmax: Single; const vel, dvel, nvel: PSingle; const params: PdtObstacleAvoidanceParams; debug: TdtObstacleAvoidanceDebugData = nil): Integer; var pat: array [0..(DT_MAX_PATTERN_DIVS*DT_MAX_PATTERN_RINGS+1)*2-1] of Single; npat: Integer; ndivs, nrings, depth, nd, nr, nd2: Integer; da,ca,sa,r,cr,minPenalty,penalty: Single; ddir: array [0..5] of Single; j,i,k,ns: Integer; last1, last2: PSingle; res,bvel,vcand: array [0..2] of Single; begin prepare(pos, dvel); Move(params^, m_params, sizeof(TdtObstacleAvoidanceParams)); m_invHorizTime := 1.0 / m_params.horizTime; m_vmax := vmax; if vmax > 0 then m_invVmax := 1.0 / vmax else m_invVmax := MaxSingle; dtVset(nvel, 0,0,0); if (debug <> nil) then debug.reset(); // Build sampling pattern aligned to desired velocity. npat := 0; ndivs := m_params.adaptiveDivs; nrings := m_params.adaptiveRings; depth := m_params.adaptiveDepth; nd := dtClamp(ndivs, 1, DT_MAX_PATTERN_DIVS); nr := dtClamp(nrings, 1, DT_MAX_PATTERN_RINGS); nd2 := nd div 2; da := (1.0/nd) * PI*2; ca := cos(da); sa := sin(da); // desired direction dtVcopy(@ddir[0], dvel); dtNormalize2D(@ddir[0]); dtRorate2D(@ddir[3], @ddir[0], da*0.5); // rotated by da/2 // Always add sample at zero pat[npat*2+0] := 0; pat[npat*2+1] := 0; Inc(npat); for j := 0 to nr - 1 do begin r := (nr-j)/nr; pat[npat*2+0] := ddir[(j mod 2)*3] * r; pat[npat*2+1] := ddir[(j mod 2)*3+2] * r; last1 := @pat[npat*2]; last2 := last1; Inc(npat); i := 1; while (i < nd-1) do begin // get next point on the "right" (rotate CW) pat[npat*2+0] := last1[0]*ca + last1[1]*sa; pat[npat*2+1] := -last1[0]*sa + last1[1]*ca; // get next point on the "left" (rotate CCW) pat[npat*2+2] := last2[0]*ca - last2[1]*sa; pat[npat*2+3] := last2[0]*sa + last2[1]*ca; last1 := @pat[npat*2]; last2 := last1 + 2; Inc(npat, 2); Inc(i, 2); end; if ((nd and 1) = 0) then begin pat[npat*2+2] := last2[0]*ca - last2[1]*sa; pat[npat*2+3] := last2[0]*sa + last2[1]*ca; Inc(npat); end; end; // Start sampling. cr := vmax * (1.0 - m_params.velBias); dtVset(@res[0], dvel[0] * m_params.velBias, 0, dvel[2] * m_params.velBias); ns := 0; for k := 0 to depth - 1 do begin minPenalty := MaxSingle; dtVset(@bvel[0], 0,0,0); for i := 0 to npat - 1 do begin vcand[0] := res[0] + pat[i*2+0]*cr; vcand[1] := 0; vcand[2] := res[2] + pat[i*2+1]*cr; if (Sqr(vcand[0])+Sqr(vcand[2]) > Sqr(vmax+0.001)) then continue; penalty := processSample(@vcand[0],cr/10, pos,rad,vel,dvel, minPenalty, debug); Inc(ns); if (penalty < minPenalty) then begin minPenalty := penalty; dtVcopy(@bvel[0], @vcand[0]); end; end; dtVcopy(@res[0], @bvel[0]); cr := cr * 0.5; end; dtVcopy(nvel, @res[0]); Result := ns; end; function TdtObstacleAvoidanceQuery.getObstacleCircleCount(): Integer; begin Result := m_ncircles; end; function TdtObstacleAvoidanceQuery.getObstacleCircle(i: Integer): PdtObstacleCircle; begin Result := @m_circles[i]; end; function TdtObstacleAvoidanceQuery.getObstacleSegmentCount(): Integer; begin Result := m_nsegments; end; function TdtObstacleAvoidanceQuery.getObstacleSegment(i: Integer): PdtObstacleSegment; begin Result := @m_segments[i]; end; end.
unit InsertMember; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Mask, Vcl.DBCtrls, Vcl.ExtCtrls, Data.DB; type TInsertForm = class(TForm) InsertSource: TDataSource; LoginBack: TPanel; LoginCenter: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; editName: TDBEdit; editId: TDBEdit; editPw: TDBEdit; editPhone: TDBEdit; editMail: TDBEdit; Pnl_Insert: TPanel; Pnl_DupID: TPanel; procedure btnInsertClick(Sender: TObject); procedure DupIDClick(Sender: TObject); private { Private declarations } function DuplicatedUser: Boolean; public { Public declarations } end; var InsertForm: TInsertForm; implementation {$R *.dfm} uses DataAccessModule, Login, Main; procedure TInsertForm.btnInsertClick(Sender: TObject); begin if editName.Text = '' then begin ShowMessage('이름을 입력하세요.'); editName.SetFocus; Exit; end; if editId.Text = '' then begin ShowMessage('아이디를 입력하세요.'); editId.SetFocus; Exit; end; if editPw.Text = '' then begin ShowMessage('비밀번호를 입력하세요.'); editPw.SetFocus; Exit; end; if editPhone.Text = '' then begin ShowMessage('전화번호를 입력하세요.'); editPhone.SetFocus; Exit; end; DataAccess.qryUser.post; // DataAccess.qryUser.Refresh; if not DataAccess.qryUser.Eof then begin ShowMessage('회원가입을 축하드립니다. 로그인화면에서 다시 로그인 해주세요'); // Label6.Caption := 'welcome'; begin if not Assigned(LoginForm) then LoginForm := TLoginForm.Create(Self); LoginForm.Parent := MainForm.mainpanel; LoginForm.BorderStyle := bsNone; LoginForm.Align := alClient; LoginForm.Show; end; end; end; procedure TInsertForm.DupIDClick(Sender: TObject); begin DuplicatedUser; end; function TInsertForm.DuplicatedUser: Boolean; var ID: string; Seq: integer; begin // Seq := DataAccess.qryUser.FieldByName('USER_SEQ').AsInteger; // ID := DataAccess.qryUser.FieldByName('USER_ID').AsString; ID := editId.Text; if (ID = '') then Exit; if DataAccess.DuplicatedID(ID) then begin ShowMessage('이미 등록된 ID 입니다.'); end else begin ShowMessage('사용가능한 ID 입니다.'); editPw.enabled := true; editMail.enabled := true; editPhone.enabled := true; end; end; end.