text
stringlengths
14
6.51M
unit uFuns; interface uses Winapi.Windows, FMX.Forms, System.Classes, System.SysUtils, FMX.Dialogs, uFrmTabBase; /// <summary> /// 关闭类名为AClassName的窗口 /// </summary> /// <param name="AClassName">窗口类名</param> procedure ClosePage(AClassName: string = ''); /// <summary> /// 关闭除类名为AClassName和主窗口之外的所有的窗口 /// </summary> /// <param name="AClassName">窗口类名</param> procedure CloseOtherPages(AClassName: string = ''); /// <summary> /// 创建一个窗口 /// </summary> /// <param name="AOwner"></param> /// <param name="AFormName"></param> /// <param name="APageIndex"></param> procedure CreateForm(AOwner: TComponent; AFormName: string; AID: Integer); /// <summary> /// 创建一个窗口 /// </summary> function MsCreateForm(AOwner: TComponent; AFormName: string): TForm; /// <summary> /// 打印调试信息 /// </summary> /// <param name="AClassName"></param> function DebugInf(const Format: string; const Args: array of const): Boolean; implementation procedure CloseOtherPages(AClassName: string = ''); var i: Integer; vForm: TFrmTabBase; begin for I:=0 to Screen.FormCount-1 do begin vForm := TFrmTabBase(Screen.Forms[I]); if vForm.ID = 1000000 then //if UpperCase(vForm.ClassName) = UpperCase('TMainForm') then Continue; if (AClassName <> '') then begin if not (vForm.ClassNameIs(AClassName)) then Continue; end; vForm.Close; //FreeAndNil(vForm); //Break; end; end; procedure ClosePage(AClassName: string = ''); var i: Integer; vForm: TForm; begin if AClassName = '' then begin Exit; end; for I:=0 to Screen.FormCount-1 do begin vForm := TForm(Screen.Forms[I]); if not (vForm.ClassNameIs(AClassName)) then Continue; vForm.Close; //FreeAndNil(vForm); Break; end; end; procedure CreateForm(AOwner: TComponent; AFormName: string; AID: Integer); function GetFormByName(AFormName: string): TFrmTabBase; var i: Integer; begin Result := nil; for I:=0 to Screen.FormCount-1 do begin if not (Screen.Forms[I].ClassNameIs(AFormName)) then Continue; Result := TFrmTabBase(Screen.Forms[I]); Break; end; end; type TFormTabBaseClass = class of TFrmTabBase; var vForm: TFrmTabBase; sClassName, s: string; begin vForm := GetFormByName(AFormName); if vForm = nil then begin //创建 s := Copy(Trim(AFormName), 1, 1); if (s <> 'T') and (s <> 't') then sClassName := 'T' + Trim(AFormName) else sClassName := Trim(AFormName); if GetClass(sClassName)<>nil then vForm := TFormTabBaseClass(FindClass(sClassName)).Create(AOwner); end; if vForm = nil then begin {$IFDEF DEBUG} ShowMessage('没有找到类,可能类名不对'); {$ENDIF} Exit; end; //显示Form try vForm.ID := AID; vForm.PageIndex := AID mod 100; vForm.ShowModal; finally FreeAndNil(vForm); end; end; function MsCreateForm(AOwner: TComponent; AFormName: string): TForm; function GetFormByName(AFormName: string): TForm; var i: Integer; begin Result := nil; for I:=0 to Screen.FormCount-1 do begin if not (Screen.Forms[I].ClassNameIs(AFormName)) then Continue; Result := TForm(Screen.Forms[I]); Break; end; end; type TFormClass = class of TForm; var sClassName, s: string; begin Result := nil; try Result := GetFormByName(AFormName); if Result = nil then begin //创建 s := Copy(Trim(AFormName), 1, 1); if (s <> 'T') and (s <> 't') then sClassName := 'T' + Trim(AFormName) else sClassName := Trim(AFormName); if GetClass(sClassName)<>nil then Result := TFormClass(FindClass(sClassName)).Create(AOwner); end; except end; end; function DebugInf(const Format: string; const Args: array of const): Boolean; //{$IFDEF DEBUG} var sInfo: string; //{$ENDIF} begin Result := False; //{$IFDEF DEBUG} sInfo := System.SysUtils.Format(Format, Args, FormatSettings); OutputDebugString(PWideChar(sInfo)); //{$ENDIF} Result := True; end; end.
{$I DFS.INC} unit DFSStatusBarReg; interface uses {$IFDEF DFS_NO_DSGNINTF} DesignIntf, DesignEditors; {$ELSE} DesgnIntf; {$ENDIF} type TdfsStatusBarEditor = class(TDefaultEditor) protected {$IFDEF DFS_IPROPERTY} procedure RunPropertyEditor(const Prop: IProperty); {$ELSE} procedure RunPropertyEditor(Prop: TPropertyEditor); {$ENDIF} public procedure ExecuteVerb(Index : Integer); override; function GetVerb(Index : Integer): string; override; function GetVerbCount : Integer; override; procedure Edit; override; end; procedure Register; implementation uses Dialogs, Windows, DFSStatusBar, DFSAbout, Classes, SysUtils, TypInfo; procedure Register; begin RegisterComponents('DFS', [TdfsStatusBar]); RegisterPropertyEditor(TypeInfo(string), TdfsStatusBar, 'Version', TdfsVersionProperty); { We have to replace the panels editor that's registered for TStatusBar with our own because otherwise it would edit the TStatusBar.Panels property, which is of the type TStatusPanels. We don't want that because it doesn't know about our new stuff in TdfsStatusPanel. } RegisterComponentEditor(TdfsStatusBar, TdfsStatusBarEditor); end; { TdfsStatusBarEditor } procedure TdfsStatusBarEditor.Edit; var {$IFDEF DFS_DESIGNERSELECTIONS} Components: IDesignerSelections; {$ELSE} {$IFDEF DFS_COMPILER_5_UP} Components: TDesignerSelectionList; {$ELSE} Components: TComponentList; {$ENDIF} {$ENDIF} begin {$IFDEF DFS_DESIGNERSELECTIONS} Components := CreateSelectionList; {$ELSE} {$IFDEF DFS_COMPILER_5_UP} Components := TDesignerSelectionList.Create; {$ELSE} Components := TComponentList.Create; {$ENDIF} {$ENDIF} try Components.Add(Component); GetComponentProperties(Components, [tkClass], Designer, RunPropertyEditor); finally {$IFNDEF DFS_DESIGNERSELECTIONS} Components.Free; {$ENDIF} end; end; procedure TdfsStatusBarEditor.RunPropertyEditor( {$IFDEF DFS_IPROPERTY} const Prop: IProperty {$ELSE} Prop: TPropertyEditor {$ENDIF} ); begin if UpperCase(Prop.GetName) = 'PANELS' then Prop.Edit; end; procedure TdfsStatusBarEditor.ExecuteVerb(Index: Integer); begin if Index <> 0 then Exit; { We only have one verb, so exit if this ain't it } Edit; { Invoke the Edit function the same as if double click had happened } end; function TdfsStatusBarEditor.GetVerb(Index: Integer): string; begin Result := '&Panels Editor...'; { Menu item caption for context menu } end; function TdfsStatusBarEditor.GetVerbCount: Integer; begin Result := 1; // Just add one menu item. end; end.
unit MoveDestinationToRouteResponseUnit; interface uses REST.Json.Types, GenericParametersUnit; type TMoveDestinationToRouteResponse = class(TGenericParameters) private [JSONName('success')] FSuccess: boolean; [JSONName('error')] FError: String; public property Success: boolean read FSuccess write FSuccess; property Error: String read FError write FError; end; implementation end.
unit BaseOptimizationParametersProviderUnit; interface uses IOptimizationParametersProviderUnit, OptimizationParametersUnit, AddressUnit, RouteParametersUnit; type TBaseOptimizationParametersProvider = class abstract (TInterfacedObject, IOptimizationParametersProvider) protected procedure AddAddress(Address: TAddress; var AddressArray: TAddressesArray); function MakeAddresses(): TAddressesArray; virtual; abstract; function MakeRouteParameters(): TRouteParameters; virtual; abstract; /// <summary> /// After response some fields are changed from request. /// </summary> procedure CorrectForResponse(OptimizationParameters: TOptimizationParameters); virtual; abstract; public function OptimizationParameters: TOptimizationParameters; function OptimizationParametersForResponse: TOptimizationParameters; end; implementation { TBaseOptimizationParametersProvider } procedure TBaseOptimizationParametersProvider.AddAddress(Address: TAddress; var AddressArray: TAddressesArray); begin SetLength(AddressArray, Length(AddressArray) + 1); AddressArray[High(AddressArray)] := Address; end; function TBaseOptimizationParametersProvider.OptimizationParameters: TOptimizationParameters; var Address: TAddress; begin Result := TOptimizationParameters.Create; Result.Parameters := MakeRouteParameters; for Address in MakeAddresses do Result.AddAddress(Address); end; function TBaseOptimizationParametersProvider.OptimizationParametersForResponse: TOptimizationParameters; begin Result := OptimizationParameters; CorrectForResponse(Result); end; end.
{ Модуль компонента простого стрелочного индикатора c 3-мя зонами раскраски. } unit ICAnalogGauge; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs; type { Стиль отображения } TStyle = (LeftStyle, RightStyle, CenterStyle); { Опции отображения } TFaceOption = (ShowMargin, ShowCircles, ShowMainTicks, ShowSubTicks, ShowIndicatorMin, ShowIndicatorMid, ShowIndicatorMax, ShowValues, ShowCenter, ShowFrame, Show3D, ShowCaption); TFaceOptions = set of TFaceOption; TAntialiased = (aaNone, aaBiline, aaTriline, aaQuadral); { Компонента простого стрелочного индикатора c 3-мя зонами раскраски } TICAnalogGauge = class(TGraphicControl) private // Цвета элементов { Цвет зоны минимума } FMinColor: TColor; { Цвет средней зоны } FMidColor: TColor; { Цвет зоны максимума } FMaxColor: TColor; { Основной цвет контрола } FFaceColor: TColor; { Цвет шкалы } FTicksColor: TColor; { Цвет значений шкалы } FValueColor: TColor; { Цвет надписи } FCaptionColor: TColor; { Цвет стрелки } FArrowColor: TColor; FMarginColor: TColor; FCenterColor: TColor; FCircleColor: TColor; // Размеры элементов FCenterRadius: Integer; FCircleRadius: Integer; FScaleAngle: Integer; FMargin: Integer; FStyle: TStyle; FArrowWidth: Integer; FNumMainTicks: Integer; FLengthMainTicks: Integer; FLengthSubTicks: Integer; FFaceOptions: TFaceOptions; // Значения { Текщая позиция } FPosition: Double; { Диапазон значений } FScaleValue: Integer; { Граница минимальной зоны } FMinimum: Double; { Граница максимальной зоны } FMaximum: Double; { Надпись } FCaption: string; // event handlers FOverMax: TNotifyEvent; FOverMin: TNotifyEvent; // anti-aliasing mode FAntiAliased: TAntiAliased; // internal bitmaps FBackBitmap: TBitmap; FFaceBitmap: TBitmap; { Битмап для сглаживания движения стрелки } FAABitmap: TBitmap; // set properties {ecm} FLockRedraw: Integer; {/ecm} procedure SetMinColor(C: TColor); procedure SetMidColor(C: TColor); procedure SetMaxColor(C: TColor); procedure SetFaceColor(C: TColor); procedure SetTicksColor(C: TColor); procedure SetValueColor(C: TColor); procedure SetCaptionColor(C: TColor); procedure SetArrowColor(C: TColor); procedure SetMarginColor(C: TColor); procedure SetCenterColor(C: TColor); procedure SetCircleColor(C: TColor); procedure SetCenterRadius(I: Integer); procedure SetCircleRadius(I: Integer); procedure SetScaleAngle(I: Integer); procedure SetMargin(I: Integer); procedure SetStyle(S: TStyle); procedure SetArrowWidth(I: Integer); procedure SetNumMainTicks(I: Integer); procedure SetLengthMainTicks(I: Integer); procedure SetLengthSubTicks(I: Integer); procedure SetFaceOptions(O: TFaceOptions); procedure SetPosition(V: Double); procedure SetScaleValue(I: Integer); procedure SetMaximum(Value: Double); procedure SetMinimum(Value: Double); procedure SetCaption(S: string); procedure SetAntiAliased(V: TAntialiased); function GetAAMultipler: Integer; protected procedure DrawScale(Bitmap: TBitmap; K: Integer); procedure DrawArrow(Bitmap: TBitmap; K: Integer); procedure RedrawScale; procedure RedrawArrow; procedure FastAntiAliasPicture; procedure PaintGauge; procedure ReInitialize; public {ecm} procedure LockRedraw; procedure UnLockRedraw; {/ecm} procedure Init; virtual; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Paint; override; published property MinColor: TColor read FMinColor write SetMinColor; property MidColor: TColor read FMidColor write SetMidColor; property MaxColor: TColor read FMaxColor write SetMaxColor; property FaceColor: TColor read FFaceColor write SetFaceColor; property TicksColor: TColor read FTicksColor write SetTicksColor; property ValueColor: TColor read FValueColor write SetValueColor; property CaptionColor: TColor read FCaptionColor write SetCaptionColor; property ArrowColor: TColor read FArrowColor write SetArrowColor; property MarginColor: TColor read FMarginColor write SetMarginColor; property CenterColor: TColor read FCenterColor write SetCenterColor; property CircleColor: TColor read FCircleColor write SetCircleColor; property CenterRadius: Integer read FCenterRadius write SetCenterRadius; property CircleRadius: Integer read FCircleRadius write SetCircleRadius; property Angle: Integer read FScaleAngle write SetScaleAngle; property GaugeMargin: Integer read FMargin write SetMargin; property GaugeStyle: TStyle read FStyle write SetStyle; property ArrowWidth: Integer read FArrowWidth write SetArrowWidth; property NumberMainTicks: Integer read FNumMainTicks write SetNumMainTicks; property LengthMainTicks: Integer read FLengthMainTicks write SetLengthMainTicks; property LengthSubTicks: Integer read FLengthSubTicks write SetLengthSubTicks; property FaceOptions: TFaceOptions read FFaceOptions write SetFaceOptions; property GaugePosition: Double read FPosition write SetPosition; property Scale: Integer read FScaleValue write SetScaleValue; property IndMaximum: Double read FMaximum write SetMaximum; property IndMinimum: Double read FMinimum write SetMinimum; property GaugeCaption: string read FCaption write SetCaption; property AntiAliased: TAntialiased read FAntiAliased write SetAntiAliased; property OnOverMax: TNotifyEvent read FOverMax write FOverMax; property OnOverMin: TNotifyEvent read FOverMin write FOverMin; end; procedure Register; implementation uses Math, LCLType; procedure Register; begin {$I icanaloggauge_icon.lrs} RegisterComponents('IC Tools',[TICAnalogGauge]); end; constructor TICAnalogGauge.Create(AOwner: TComponent); begin inherited; FBackBitmap := TBitmap.Create; FFaceBitmap := TBitmap.Create; FAABitmap := TBitmap.Create; Init; end; destructor TICAnalogGauge.Destroy; begin if Assigned(FBackBitmap) then FBackBitmap.Free; if Assigned(FFaceBitmap) then FFaceBitmap.Free; if Assigned(FAABitmap) then FAABitmap.Free; inherited; end; procedure TICAnalogGauge.Init; begin inherited; FFaceColor := clForm; FTicksColor := clBlack; FValueColor := clBlack; FCaptionColor := clRed; FArrowColor := clBlack; FMarginColor := clSilver; FCenterColor := clWindow; FCircleColor := clBtnFace; FMinColor := clGreen; FMidColor := clLime; FMaxColor := clRed; FArrowWidth := 1; FPosition := 0; FMargin := 4; FStyle := CenterStyle; FScaleValue := 120; FMaximum := 100; FMinimum := 20; FScaleAngle := 100; FCircleRadius := 1; FCenterRadius := 5; FNumMainTicks := 12; FLengthMainTicks := 15; FLengthSubTicks := 8; FCaption := '---'; FFaceOptions := [ShowMargin, ShowMainTicks, ShowSubTicks, ShowIndicatorMin, SHowindicatormid,ShowIndicatorMax, ShowValues, ShowCenter, ShowFrame, ShowCaption]; FAntiAliased := aaNone; end; procedure TICAnalogGauge.Paint; begin inherited; ReInitialize; PaintGauge; end; procedure TICAnalogGauge.DrawScale(Bitmap: TBitmap; K: Integer); var I, J, X, Y, N, M, W, H: Integer; Max, Min: Double; A, C: Single; SI, CO, SI1, CO1:Extended; begin W := Bitmap.Width; H := Bitmap.Height; Max := FMaximum; Min := FMinimum; if FStyle in [LeftStyle, RightStyle] then begin W := Math.Min(W,H); H := Math.Min(W,H); end; N := FNumMainTicks * 5; M := FMargin * K; with Bitmap do begin // ***************************** Out Frame ************************** if ShowFrame in FFaceOptions then begin if Show3D in FFaceOptions then begin Canvas.Pen.Width := 2 * K; Canvas.Pen.Color := clBtnShadow; Canvas.MoveTo(W, 0); Canvas.LineTo(0, 0); Canvas.LineTo(0, H); Canvas.Pen.Color := clBtnHighlight; Canvas.LineTo(W, H); Canvas.LineTo(W, 0); end else begin Canvas.Pen.Width := K; Canvas.Pen.Color := clBtnText; Canvas.Rectangle(0, 0, W, H); end; end; //************************* Out Margins ************************** if ShowMargin in FFaceOptions then begin Canvas.Pen.Color := FMarginColor; Canvas.Pen.Width := K; Canvas.Rectangle(M, M, W - M, H - M); end; //**************************************************************** case fStyle of RightStyle: begin A := 0; C := W - M; X := W - M; Y := H - M; if FScaleAngle > 90 then FScaleAngle := 90; J := W - 2 * M; end; LeftStyle: begin A := 90; C := M; X := M; Y := H - M; if FScaleAngle > 90 then FScaleAngle := 90; J := W - 2 * M; end; else begin X := W div 2; A := (180 - FScaleAngle) / 2; C := W / 2; if FScaleAngle >= 180 then begin J := (W - 2 * M) div 2; Y := H div 2; end else begin J := Round(((W - 2 * M) / 2) / Cos(A * 2 * Pi / 360)); if J > H - 2 * M then J := H - 2 * M; Y := (H - J) div 2 + J; end; end; end;{case} //******************************** Out Caption ******************* if (ShowCaption in FFaceOptions) then begin Canvas.Font.Color := FCaptionColor; Canvas.TextOut(Round(C - J / 2 * Cos(A + FScaleAngle / 2) * 2 * Pi / 360) - Canvas.TextWidth(FCaption) div 2, Round(Y - J / 2 * Sin((A + FScaleAngle / 2) * 2 * Pi / 360)), FCaption); end; //********************************** Out MinMaxLines ************************************* Canvas.Pen.EndCap := pecFlat; //Square; Canvas.Pen.Width := 4 * K; if (ShowIndicatorMax in FFaceOptions) then begin Canvas.pen.color := FMaxColor; SinCos((A + FScaleAngle) * 2 * Pi / 360, Si, Co); SinCos((A + Max * FScaleAngle / FScaleValue) * 2 * Pi / 360, Si1, Co1); Canvas.Arc(X - J, Y - J, X + J, Y + J, Round(C - J * Co), Round(Y - J * Si), Round(C - J * Co1), Round(Y - J * Si1)) end; if (ShowIndicatorMid in FFaceOptions) and (FMinimum < FMaximum) then begin Canvas.Pen.Color := FMidColor; SinCos((A + Max * FScaleAngle / FScaleValue) * 2 * Pi / 360, Si, Co); SinCos((A + Min * FScaleAngle / FScaleValue) * 2 * Pi / 360, Si1, Co1); Canvas.Arc(X - J, Y - J, X + J, Y + J, Round(C - J * Co), Round(Y - J * Si), Round(C - J * Co1), Round(Y - J * Si1)) end; if (ShowIndicatorMin in FFaceOptions) then begin Canvas.Pen.Color := FMinColor; SinCos((A + Min * FScaleAngle / FScaleValue) * 2 * Pi / 360, Si, Co); SinCos(A * 2 * Pi / 360, Si1, Co1); Canvas.Arc(X - J, Y - J, X + J, Y + J, Round(C - J * Co), Round(Y - J * Si), Round(C - J * Co1), Round(Y - J * Si1)) end; Canvas.Font.Color := FValueColor; Canvas.Pen.Color := FTicksColor; Canvas.Pen.Width := K; //********************************** Out SubTicks ************************************* if ShowSubTicks in FFaceOptions then for I := 0 to N do begin SinCos((A + I * (FScaleAngle) / N) * 2 * Pi / 360, Si, Co); Canvas.MoveTo(Round(C - (J - FLengthSubTicks * K) * Co), Round(Y - (J - FLengthSubTicks * K) * Si)); Canvas.LineTo(Round(C - (J) * Co), Round(Y - (J) * Si)) end; //********************************** Out Main Ticks ************************************ for I := 0 to FNumMainTicks do begin if ShowMainTicks in FFaceOptions then begin SinCos((A + I * (FScaleAngle) / FNumMainTicks) * 2 * Pi / 360, Si, Co); Canvas.MoveTo(Round(C - (J - FLengthMainTicks * K) * Co), Round(Y - (J - FLengthMainTicks * K) * Si)); Canvas.LineTo(Round(C - (J) * Co), Round(Y - (J) * Si)); end; //************************************* Out Circles ************************************ if ShowCircles in FFaceOptions then begin Canvas.Brush.Color := FCircleColor; SinCos((A + I * (FScaleAngle) / FNumMainTicks) * 2 * Pi / 360, Si, Co); {ecm} Canvas.Ellipse(Round(C - (J * Co - FCircleRadius * K)), Round(Y - (J * Si - FCircleRadius * K)), Round(C - (J * Co + FCircleRadius * K)), Round(Y - (J * Si + FCircleRadius * K))); {/ecm} end; // ************************************* Out Values ************************************* if ShowValues in FFaceOptions then begin Canvas.Brush.Color := FFaceColor; Canvas.TextOut(Round(C - (J - FLengthMainTicks * K - 5 - I) * Cos((A + I * (FScaleAngle) / fNumMainTicks) * 2 * Pi / 360)) - Canvas.TextWidth(IntToStr(I * FScaleValue div FNumMainTicks))div 2, Round(Y - (J - FLengthMainTicks * K - 5) * Sin((A + I * (FScaleAngle) / FNumMainTicks) * 2 * Pi / 360)), IntToStr(I * FScaleValue div fNumMainTicks)); end; end; end; end; procedure TICAnalogGauge.DrawArrow(Bitmap: TBitmap; K: Integer); var J, X, Y, M, W, H, R: Integer; A, C: Single; Si, Co: Extended; begin M := FMargin * K; R := FCenterRadius * K; W := Bitmap.Width; H := Bitmap.Height; if FStyle in [LeftStyle, RightStyle] then begin W := Math.Min(W, H); H := Math.Min(W, H); end; with Bitmap do begin case FStyle of RightStyle: begin A := 0; C := W - M; X := W - M; Y := H - M; if FScaleAngle > 90 then FScaleAngle := 90; J := W - 2 * M; end; LeftStyle: begin A := 90; C := M; X := M; Y := H - M; if FScaleAngle > 90 then FScaleAngle := 90; J := W - 2 * M; end; else begin X := W div 2; A := (180 - FScaleAngle) / 2; C := W / 2; if FScaleAngle >= 180 then begin J := (W - 2 * M) div 2; Y := H div 2; end else begin J := Round(((W - 2 * M) / 2) / Cos(A * 2 * Pi / 360)); if J > H - 2 * M then J := H - 2 * M; Y := (H - J) div 2 + J; end; end; end;{case} Canvas.Pen.Width := FArrowWidth * K; Canvas.Pen.Color := FArrowColor; Canvas.MoveTo(X, Y); SinCos((A + FPosition * FScaleAngle / FScaleValue) * 2 * Pi / 360, Si, Co); Canvas.LineTo(Round(C - J * Co), Round(Y - J * Si)); //********************************* Out Center *************************************** if ShowCenter in FFaceOptions then begin Canvas.Brush.Color := FCenterColor; Canvas.Ellipse(X - R, Y - R, X + R, Y + R); end; end; end; procedure TICAnalogGauge.RedrawArrow; begin FFaceBitmap.Canvas.CopyRect(TRect.Create(0, 0, FBackBitmap.Width, FBackBitmap.Height), FBackBitmap.Canvas, TRect.Create(0, 0, FBackBitmap.Width, FBackBitmap.Height)); DrawArrow(FFaceBitmap, GetAAMultipler); if FAntiAliased <> aaNone then FastAntiAliasPicture; PaintGauge; end; procedure TICAnalogGauge.RedrawScale; begin {ecm} if FLockRedraw = 0 then {/ecm} begin FBackBitmap.Canvas.Brush.Color := FFaceColor; FBackBitmap.Canvas.Brush.Style := bsSolid; FBackBitmap.Canvas.FillRect(FBackBitmap.Canvas.ClipRect); DrawScale(FBackBitmap, GetAAMultipler); RedrawArrow; end; end; const MaxPixelCount = MaxInt div SizeOf(TRGBTriple); type PRGBArray = ^TRGBArray; TRGBArray = array[0..MaxPixelCount - 1] of TRGBTriple; procedure TICAnalogGauge.FastAntiAliasPicture; var x, y, cx, cy, cxi: Integer; totr, totg, totb: cardinal; Row1, Row2, Row3, Row4, DestRow: PRGBArray; i, K: Integer; begin // For each row if not Assigned(FFaceBitmap) then Exit; K := GetAAMultipler; Row2 := nil; Row3 := nil; Row4 := nil; for Y := 0 to FAABitmap.Height - 1 do begin // We compute samples of K x K pixels cy := y * K; // Get pointers to actual, previous and next rows in supersampled bitmap Row1 := FFaceBitmap.ScanLine[cy]; if Row1 = nil then Exit; if K > 1 then Row2 := FFaceBitmap.ScanLine[cy + 1]; if K > 2 then Row3 := FFaceBitmap.ScanLine[cy + 2]; if K > 3 then Row4 := FFaceBitmap.ScanLine[cy + 3]; // Get a pointer to destination row in output bitmap DestRow := FAABitmap.ScanLine[y]; // For each column... for x := 0 to FAABitmap.Width - 1 do begin // We compute samples of 3 x 3 pixels cx := x * K; // Initialize result color totr := 0; totg := 0; totb := 0; if K > 3 then begin for i := 0 to 3 do begin cxi := cx + i; totr := totr + Row1^[cxi].rgbtRed + Row2^[cxi].rgbtRed + Row3^[cxi].rgbtRed + Row4^[cxi].rgbtRed; totg := totg + Row1^[cxi].rgbtGreen + Row2^[cxi].rgbtGreen + Row3^[cxi].rgbtGreen + Row4^[cxi].rgbtGreen; totb := totb + Row1^[cxi].rgbtBlue + Row2^[cxi].rgbtBlue + Row3^[cxi].rgbtBlue + Row4^[cxi].rgbtBlue; end; DestRow^[x].rgbtRed := totr shr 4 ; //div 16; DestRow^[x].rgbtGreen := totg shr 4 ; //16; DestRow^[x].rgbtBlue := totb shr 4 ; //16; end else if K > 2 then begin for i := 0 to 2 do begin cxi := cx + i; totr := totr + Row1^[cxi].rgbtRed + Row2^[cxi].rgbtRed + Row3^[cxi].rgbtRed; totg := totg + Row1^[cxi].rgbtGreen + Row2^[cxi].rgbtGreen + Row3^[cxi].rgbtGreen; totb := totb + Row1^[cxi].rgbtBlue + Row2^[cxi].rgbtBlue + Row3^[cxi].rgbtBlue; end; DestRow^[x].rgbtRed := totr div 9; DestRow^[x].rgbtGreen := totg div 9; DestRow^[x].rgbtBlue := totb div 9; end else if K > 1 then begin for i := 0 to 1 do begin cxi := cx + i; totr := totr + Row1^[cxi].rgbtRed + Row2^[cxi].rgbtRed; totg := totg + Row1^[cxi].rgbtGreen + Row2^[cxi].rgbtGreen; totb := totb + Row1^[cxi].rgbtBlue + Row2^[cxi].rgbtBlue; end; DestRow^[x].rgbtRed := totr shr 2; DestRow^[x].rgbtGreen := totg shr 2; DestRow^[x].rgbtBlue := totb shr 2; end else begin DestRow^[x].rgbtRed := Row1^[cx].rgbtRed; DestRow^[x].rgbtGreen := Row1^[cx].rgbtGreen; DestRow^[x].rgbtBlue := Row1^[cx].rgbtBlue; end; end; end; end; procedure TICAnalogGauge.PaintGauge; begin if FAntiAliased = aaNone then Canvas.CopyRect(TRect.Create(0, 0, FFaceBitmap.Width, FFaceBitmap.Height), FFaceBitmap.Canvas, TRect.Create(0, 0, FFaceBitmap.Width, FFaceBitmap.Height)) else Canvas.CopyRect(TRect.Create(0, 0, FAABitmap.Width, FAABitmap.Height), FAABitmap.Canvas, TRect.Create(0, 0, FAABitmap.Width, FAABitmap.Height)); end; { ------------------------------------------------------------------------- } procedure TICAnalogGauge.SetMinColor(C: TColor); begin if C <> FMinColor then begin FMinColor := C; RedrawScale; end; end; procedure TICAnalogGauge.SetMidColor(C: TColor); begin if C <> FMidColor then begin FMidColor := C; RedrawScale; end; end; procedure TICAnalogGauge.SetMaxColor(C: TColor); begin if C <> FMaxColor then begin FMaxColor := C; RedrawScale; end; end; procedure TICAnalogGauge.SetFaceColor(C: TColor); begin if C <> FFaceColor then begin FFaceColor := C; RedrawScale; end; end; procedure TICAnalogGauge.SetTicksColor(C: TColor); begin if C <> FTicksColor then begin FTicksColor := C; RedrawScale; end; end; procedure TICAnalogGauge.SetValueColor(C: TColor); begin if C <> FValueColor then begin FValueColor := C; RedrawScale; end; end; procedure TICAnalogGauge.SetCaptionColor(C: TColor); begin if C <> FCaptionColor then begin FCaptionColor := C; RedrawScale; end; end; procedure TICAnalogGauge.SetArrowColor(C: TColor); begin if C <> FArrowColor then begin FArrowColor := C; RedrawArrow; end; end; procedure TICAnalogGauge.SetMarginColor(C: TColor); begin if C <> FMarginColor then begin FMarginColor := C; RedrawScale; end; end; procedure TICAnalogGauge.SetCenterColor(C: TColor); begin if C <> FCenterColor then begin FCenterColor := C; RedrawScale; end; end; procedure TICAnalogGauge.SetCircleColor(C: TColor); begin if C <> FCircleColor then begin FCircleColor := C; RedrawScale; end; end; procedure TICAnalogGauge.SetCenterRadius(I: Integer); begin if I <> FCenterRadius then begin FCenterRadius := I; RedrawScale; end; end; procedure TICAnalogGauge.SetCircleRadius(I: Integer); begin if I <> FCircleRadius then begin FCircleRadius := I; RedrawScale; end end; procedure TICAnalogGauge.SetScaleAngle(I: Integer); begin if I <> FScaleAngle then begin if (I > 10) and (I <= 360) then FScaleAngle := I; RedrawScale; end; end; procedure TICAnalogGauge.SetMargin(I: Integer); begin if I <> FMargin then begin FMargin := I; RedrawScale; end; end; procedure TICAnalogGauge.SetStyle(S: TStyle); begin if S <> FStyle then begin FStyle := S; RedrawScale; end; end; procedure TICAnalogGauge.SetArrowWidth(I: Integer); begin if I <> FArrowWidth then begin if I < 1 then FArrowWidth := 1 else if I > 5 then FArrowWidth := 5 else FArrowWidth := I; RedrawArrow; end end; procedure TICAnalogGauge.SetNumMainTicks(I: Integer); begin if I <> FNumMainTicks then begin FNumMainTicks := I; RedrawScale; end; end; procedure TICAnalogGauge.SetLengthMainTicks(I: Integer); begin if I <> FLengthMainTicks then begin FLengthMainTicks := I; RedrawScale; end; end; procedure TICAnalogGauge.SetLengthSubTicks(I: Integer); begin if I <> FLengthSubTicks then begin FLengthSubTicks := I; RedrawScale; end; end; procedure TICAnalogGauge.SetFaceOptions(O: TFaceOptions); begin if O <> FFaceOptions then begin FFaceOptions := O; RedrawScale; end; end; procedure TICAnalogGauge.SetPosition(V: Double); begin if V <> FPosition then begin FPosition := V; if (FPosition > FMaximum) and Assigned(FOverMax) then FOverMax(Self); if (FPosition < FMinimum) and Assigned(FOverMin) then FOverMin(Self); RedrawArrow; end end; procedure TICAnalogGauge.SetScaleValue(I: Integer); begin if I <> FScaleValue then begin if I > 1 then begin FScaleValue := I; if FMaximum >= FScaleValue then FMaximum := FScaleValue - 1; if FMinimum > FScaleValue - FMaximum then FMinimum := FScaleValue - FMaximum; end; RedrawScale; end; end; procedure TICAnalogGauge.SetMaximum(Value: Double); begin if Value <> FMaximum then begin if (Value > 0) and (Value < FScaleValue) then FMaximum := Value; RedrawScale; end; end; procedure TICAnalogGauge.SetMinimum(Value: Double); begin if Value <> FMinimum then begin if (Value > 0) and (Value < FScaleValue) then FMinimum := Value; RedrawScale; end end; procedure TICAnalogGauge.SetCaption(S: string); begin //TODO if S <> FCaption then begin Canvas.Font.Assign(Font); FCaption := S; RedrawScale; end end; procedure TICAnalogGauge.SetAntiAliased(V: TAntialiased); begin if V <> FAntiAliased then begin FAntiAliased := V; ReInitialize; end end; function TICAnalogGauge.GetAAMultipler: Integer; begin case FAntiAliased of aaBiline: Result := 2; aaTriline: Result := 3; aaQuadral: Result := 4; else Result := 1 end end; procedure TICAnalogGauge.ReInitialize; var K:integer; begin if Width < 30 then Width := 30; if Height < 30 then Height := 30; K := GetAAMultipler; if FAntiAliased = aaNone then K := 1; if Assigned(FFaceBitmap) then FFaceBitmap.Free; if Assigned(FBackBitmap) then FBackBitmap.Free; if Assigned(FAABitmap) then FAABitmap.Free; FBackBitmap := TBitmap.Create; FBackBitmap.SetSize(Width * K, Height * K); FFaceBitmap := TBitmap.Create; FFaceBitmap.SetSize(Width * K, Height * K); FAABitmap := TBitmap.Create; FAABitmap.SetSize(Width,Height); FBackBitmap.Canvas.Font.Assign(Font); FAABitmap.Canvas.Font.Assign(Font); FFaceBitmap.Canvas.Font.Assign(Font); FBackBitmap.Canvas.Font.Height := FAABitmap.Canvas.Font.Height * K; FBackBitmap.Canvas.Font.Quality := fqAntiAliased; RedrawScale; end; {ecm} procedure TICAnalogGauge.LockRedraw; begin Inc(FLockRedraw); end; procedure TICAnalogGauge.UnLockRedraw; begin if FLockRedraw > 0 then Dec(FLockRedraw); if FLockRedraw = 0 then RedrawScale; end; {/ecm} end.
unit DynMap; interface uses SysUtils, DynArr, System.Generics.Defaults; type EKeyNotFound = class(Exception); EMapCreationError = class(Exception); type TKeyValue<KeyType, ValueType> = record key: KeyType; value: ValueType; constructor from(const k: KeyType; const v: ValueType); property first: KeyType read key write key; property second: ValueType read value write value; end; // A map with keys of type KeyType and values of type ValueType. // Unoptimized, operations like insert, update, delete, access take O(n) time // (sequential scanning of keys). // Effective only for relatively small maps. type TDynMap<KeyType, ValueType> = record type Ptr = ^ValueType; public _keys: TDynArr<KeyType>; _values: TDynArr<ValueType>; // If assigned, keyCompare is used to compare map keys. // Otherwise, the default itemsEqual from DynArr is used. keyCompare: TFunc<KeyType, KeyType, Boolean>; // index of the given key, -1 if not found function indexOfKey(const k: KeyType): Integer; // set the value for the given key, add a new item if key not found procedure setVal(const k: KeyType; const v: ValueType); // set the value for a key via a pointer procedure setPtr(const k: KeyType; const p: Ptr); // get the value for a key, raises EKeyNotFound if no such key function getVal(const k: KeyType): ValueType; overload; // get the value for a key, return the fallBack if no such key function getVal(const k: KeyType; const fallBack: ValueType): ValueType; overload; // get the value for a key, return type default if no such key function getValDef(const k: KeyType): ValueType; // get the pointer to the value for a key (nil if not found in map) function getPtr(const k: KeyType): Ptr; // check if a key exists in the map function hasKey(const k: KeyType): Boolean; // the array of keys (actual, not a copy) property keys: TDynArr<KeyType> read _keys; // the array of values (actual, not a copy) property values: TDynArr<ValueType> read _values; // the value for a given key, returns type default if no such key property value[const k: KeyType]: ValueType read getValDef write setVal; default; // the pointer to the value for a given key, returns nil if no such key property ptrTo[const k: KeyType]: Ptr read getPtr write setPtr; // the value for a given key, EKeyNotFound if no such key property existingValues[const k: KeyType]: ValueType read getVal write setVal; // create a new map as a copy of the given map constructor from(const m: TDynMap<KeyType, ValueType>); overload; // create a new map, with the specified key-value pairs to start with constructor from(const kv: TDynArr<TKeyValue<KeyType, ValueType>>); overload; // create a new map with preallocated keys and values arrays constructor withSize(const size: Integer); // add a key-value pair to the map procedure add(const kv: TKeyValue<KeyType, ValueType>); // delete a key and its value procedure delete(const key: KeyType); // get the array of all key-value pairs for this map function enumerate(): TDynArr<TKeyValue<KeyType, ValueType>>; // merge another map into this map procedure merge(const m: TDynMap<KeyType, ValueType>); // clear the map procedure clear(); // get a sub-map for the specified set of keys function submap(keys: TDynArr<KeyType>): TDynMap<KeyType, ValueType>; // clone the map function clone(): TDynMap<KeyType, ValueType>; // is the map empty / non empty? function _isEmpty(): Boolean; property isEmpty: Boolean read _isEmpty; function _isNotEmpty(): Boolean; property isNotEmpty: Boolean read _isNotEmpty; // the "length" of the map, i.e. the number of keys function _length(): Integer; property length: Integer read _length; // create an empty map class function empty(): TDynMap<KeyType, ValueType>; static; end; TVariantList = array of Variant; TVariantLists = array of TVariantList; // A shortcut function to create TKeyValue<string, Variant>. function makeKV(const key: string; const value: Variant): TKeyValue<string, Variant>; overload; // Creates a string-variant pair from the const array. // The firs item of the array has to be convertible to a string. function makeKV(const data: TVariantList): TKeyValue<string, Variant>; overload; // Creates a string-variant map from the array of pairs. function makeSVMap(const data: TVariantLists): TDynMap<string, Variant>; // Creates a deep copy of the array of maps (clones each map individually). function cloneSVArrayMap( const src: TDynArr<TDynMap<string, Variant>> ): TDynArr<TDynMap<string, Variant>>; implementation { TDynMap<KeyType, ValueType> } procedure TDynMap<KeyType, ValueType>.add( const kv: TKeyValue<KeyType, ValueType>); begin self[kv.key] := kv.value; end; procedure TDynMap<KeyType, ValueType>.clear; begin self._keys.clear(); self._values.clear(); end; function TDynMap<KeyType, ValueType>.clone: TDynMap<KeyType, ValueType>; begin Result._keys := TDynArr<KeyType>.from(self._keys); Result._values := TDynArr<ValueType>.from(self._values); end; procedure TDynMap<KeyType, ValueType>.delete(const key: KeyType); begin var ki := indexOfKey(key); if ki >= 0 then begin _keys.delete(ki); _values.delete(ki); end; end; class function TDynMap<KeyType, ValueType>.empty: TDynMap<KeyType, ValueType>; begin Result._keys := TDynArr<KeyType>.empty(); Result._values := TDynArr<ValueType>.empty(); end; function TDynMap<KeyType, ValueType>.enumerate: TDynArr<TKeyValue<KeyType, ValueType>>; var i: Integer; begin Result := TDynArr<TKeyValue<KeyType, ValueType>>.create(keys.length); for i := 0 to keys.length - 1 do Result[i] := TKeyValue<KeyType, ValueType>.from(keys[i], values[i]); end; constructor TDynMap<KeyType, ValueType>.from( const m: TDynMap<KeyType, ValueType>); begin self._keys := TDynArr<KeyType>.from(m.keys); self._values := TDynArr<ValueType>.from(m.values); end; constructor TDynMap<KeyType, ValueType>.from( const kv: TDynArr<TKeyValue<KeyType, ValueType>>); var i: Integer; begin self._keys.length := kv.length; self._values.length := kv.length; for i := 0 to kv.length - 1 do begin self._keys[i] := kv[i].key; self._values[i] := kv[i].value; end; end; function TDynMap<KeyType, ValueType>.getVal(const k: KeyType): ValueType; var i: Integer; begin i := self.indexOfKey(k); if i >= 0 then Result := _values[i] else raise EKeyNotFound.Create('Key not found in the map.'); end; function TDynMap<KeyType, ValueType>.getPtr(const k: KeyType): Ptr; var i: Integer; begin i := self.indexOfKey(k); if i >= 0 then Result := @(_values[i]) else raise EKeyNotFound.Create('Key not found in the map.'); end; function TDynMap<KeyType, ValueType>.getVal(const k: KeyType; const fallBack: ValueType): ValueType; var i: Integer; begin i := self.indexOfKey(k); if i >= 0 then Result := _values[i] else Result := fallBack; end; function TDynMap<KeyType, ValueType>.getValDef(const k: KeyType): ValueType; begin Result := self.getVal(k, Default(ValueType)); end; function TDynMap<KeyType, ValueType>.hasKey(const k: KeyType): Boolean; begin Result := self.indexOfKey(k) >= 0; end; function TDynMap<KeyType, ValueType>.indexOfKey(const k: KeyType): Integer; var kc: TFunc<KeyType, KeyType, Boolean>; begin if Assigned(self.keyCompare) then begin kc := self.keyCompare; Result := keys.findIndex( function(key: KeyType): Boolean begin Result := kc(key, k); end ) end else Result := keys.indexOf(k); end; procedure TDynMap<KeyType, ValueType>.merge( const m: TDynMap<KeyType, ValueType>); var kv: TKeyValue<KeyType, ValueType>; begin for kv in m.enumerate.raw do setVal(kv.key, kv.value); end; procedure TDynMap<KeyType, ValueType>.setPtr(const k: KeyType; const p: Ptr); begin self.setVal(k, p^); end; procedure TDynMap<KeyType, ValueType>.setVal(const k: KeyType; const v: ValueType); var i: Integer; begin i := self.indexOfKey(k); if i >= 0 then _values[i] := v else begin _keys.append(k); _values.append(v); end; end; function TDynMap<KeyType, ValueType>.submap( keys: TDynArr<KeyType>): TDynMap<KeyType, ValueType>; var k: KeyType; begin for k in keys.raw do if self.hasKey(k) then Result[k] := self[k]; end; constructor TDynMap<KeyType, ValueType>.withSize(const size: Integer); begin self._keys := TDynArr<KeyType>.create(size); self._values := TDynArr<ValueType>.create(size); end; function TDynMap<KeyType, ValueType>._isEmpty: Boolean; begin Result := self._keys.isEmpty; end; function TDynMap<KeyType, ValueType>._isNotEmpty: Boolean; begin Result := self._keys.isNotEmpty; end; function TDynMap<KeyType, ValueType>._length: Integer; begin Result := self._keys.length; end; { TKeyValue<KeyType, ValueType> } constructor TKeyValue<KeyType, ValueType>.from(const k: KeyType; const v: ValueType); begin self.key := k; self.value := v; end; function makeKV(const key: string; const value: Variant): TKeyValue<string, Variant>; begin Result.key := key; Result.value := value; end; function makeKV(const data: TVariantList): TKeyValue<string, Variant>; begin if Length(data) <> 2 then raise EMapCreationError.CreateFmt( 'Cannot construct a map. %d args given, required 2.', [Length(data)]); Result.key := string(data[0]); Result.value := data[1]; end; function makeSVMap(const data: TVariantLists): TDynMap<string, Variant>; begin var l := Length(data); Result._keys := TDynArr<string>.create(l); Result._values := TDynArr<Variant>.create(l); for var i := Low(data) to High(data) do begin if Length(data[i]) <> 2 then raise EMapCreationError.CreateFmt( 'Cannot construct a map for item %d. %d values given, required 2', [i, Length(data[i])] ); Result._keys[i] := string(data[i][0]); Result._values[i] := data[i][1]; end; end; function cloneSVArrayMap( const src: TDynArr<TDynMap<string, Variant>> ): TDynArr<TDynMap<string, Variant>>; begin Result := TDynArr<TDynMap<string, Variant>>.create(src.length); for var i := 0 to src.lastIndex do Result[i] := src[i].clone(); end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, Spin; type TfrmPretDag = class(TForm) edtNaam: TEdit; sedOuderdom: TSpinEdit; lblNaam: TLabel; lblOuderdom: TLabel; lblKinders: TLabel; lblVolwasses: TLabel; lblVerwelkom: TLabel; btnVertoon: TButton; bmbClose: TBitBtn; bmbReset: TBitBtn; procedure btnVertoonClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure bmbResetClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmPretDag: TfrmPretDag; iKinders, iVolwasses : integer; implementation {$R *.dfm} procedure TfrmPretDag.btnVertoonClick(Sender: TObject); var sNaam, sVerwelkom :string; iOuderdom : integer; begin sNaam := edtNaam.Text; iOuderdom := sedOuderdom.Value; sVerwelkom := 'Welkom ' + sNaam + ' by die pretdag.'; if iOuderdom >= 13 then begin iVolwasses := iVolwasses + 1; lblVolwasses.Caption := 'Volwasses by die pret dag al :' + IntToStr(iVolwasses); end else begin iKinders := iKinders +1; lblKinders.Caption := 'Kinders by die pret dag al :' + IntToStr(iKinders); end; lblVerwelkom.Caption := sVerwelkom; edtNaam.Clear; sedOuderdom.Clear; edtNaam.SetFocus; end; procedure TfrmPretDag.FormActivate(Sender: TObject); begin edtNaam.SetFocus; sedOuderdom.Clear; end; procedure TfrmPretDag.bmbResetClick(Sender: TObject); begin edtNaam.clear; edtNaam.SetFocus; sedOuderdom.Clear; lblKinders.Caption := 'Kinders by die pret dag al :'; lblVolwasses.Caption := 'Volwasses by die pret dag al :'; end; end.
unit atBits; // Модуль: "w:\quality\test\garant6x\AdapterTest\CoreObjects\atBits.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatBits" MUID: (502563E400D8) interface uses l3IntfUses ; type TatBits = class(TObject) private f_Bits: Pointer; f_Size: Integer; private function GetBufSize(aBitsCount: Integer): Integer; virtual; protected procedure pm_SetSize(aValue: Integer); function pm_GetBits(anIndex: Integer): Boolean; virtual; procedure pm_SetBits(anIndex: Integer; aValue: Boolean); virtual; function GetBitFrom(const aStartIndex: Integer; const aForward: Boolean; const aSetBit: Boolean): Integer; virtual; public function GetLastSetBit: Integer; virtual; function GetRandomOpenBit: Integer; virtual; procedure Reset; virtual; procedure SaveToFile(const aFileName: AnsiString); virtual; procedure LoadFromFile(const aFileName: AnsiString); virtual; destructor Destroy; override; public property Size: Integer read f_Size write pm_SetSize; property Bits[anIndex: Integer]: Boolean read pm_GetBits write pm_SetBits; default; end;//TatBits implementation uses l3ImplUses , Windows , SysUtils //#UC START# *502563E400D8impl_uses* //#UC END# *502563E400D8impl_uses* ; const BITS_PER_INT = SizeOf(Integer)*8; procedure TatBits.pm_SetSize(aValue: Integer); //#UC START# *5025646900CB_502563E400D8set_var* var l_NewMem: Pointer; l_NewMemSize, l_OldMemSize: Integer; function Min(X, Y: Integer): Integer; begin Result := X; if X > Y then Result := Y; end; //#UC END# *5025646900CB_502563E400D8set_var* begin //#UC START# *5025646900CB_502563E400D8set_impl* if aValue <> Size then begin l_NewMemSize := GetBufSize(aValue); l_OldMemSize := GetBufSize(Size); if l_NewMemSize <> l_OldMemSize then begin l_NewMem := nil; if l_NewMemSize <> 0 then begin GetMem(l_NewMem, l_NewMemSize); FillChar(l_NewMem^, l_NewMemSize, 0); end; if l_OldMemSize <> 0 then begin if l_NewMem <> nil then Move(f_Bits^, l_NewMem^, Min(l_OldMemSize, l_NewMemSize)); FreeMem(f_Bits, l_OldMemSize); end; f_Bits := l_NewMem; end; f_Size := aValue; end; //#UC END# *5025646900CB_502563E400D8set_impl* end;//TatBits.pm_SetSize function TatBits.pm_GetBits(anIndex: Integer): Boolean; //#UC START# *502565320313_502563E400D8get_var* //#UC END# *502565320313_502563E400D8get_var* begin //#UC START# *502565320313_502563E400D8get_impl* asm MOV EAX, [Self] MOV EAX, [EAX].f_Bits MOV ECX, anIndex BT [EAX], ECX SBB EAX, EAX AND EAX, 1 MOV Result, AL end; //#UC END# *502565320313_502563E400D8get_impl* end;//TatBits.pm_GetBits procedure TatBits.pm_SetBits(anIndex: Integer; aValue: Boolean); //#UC START# *502565320313_502563E400D8set_var* //#UC END# *502565320313_502563E400D8set_var* begin //#UC START# *502565320313_502563E400D8set_impl* asm MOV ECX, anIndex MOV EDX, [Self] MOV EDX, [EDX].f_Bits MOV AL, aValue OR AL, AL JZ @@2 BTS [EDX], ECX JMP @@quit @@2: BTR [EDX], ECX @@quit: end; //#UC END# *502565320313_502563E400D8set_impl* end;//TatBits.pm_SetBits function TatBits.GetBitFrom(const aStartIndex: Integer; const aForward: Boolean; const aSetBit: Boolean): Integer; //#UC START# *5025659F0300_502563E400D8_var* var l_Start, l_LastOfBits : Pointer; l_InvertMask, l_LastBlockMask, l_FirstBlockMask : Longword; //#UC END# *5025659F0300_502563E400D8_var* begin //#UC START# *5025659F0300_502563E400D8_impl* Result := -1; l_Start := Pointer(Integer(f_Bits) + GetBufSize(aStartIndex+1) - SizeOf(Integer)); Assert(Integer(l_Start) mod SizeOf(Integer) = 0, 'Integer(l_Start) mod SizeOf(Integer) = 0'); // указатель должен быть кратен SizeOf(Int) l_LastOfBits := Pointer(Integer(f_Bits) + GetBufSize(Size) - SizeOf(Integer)); if aSetBit then l_InvertMask := 0 else l_InvertMask := $FFFFFFFF; l_LastBlockMask := ($FFFFFFFF shr (GetBufSize(Size) * BITS_PER_INT - Size)); if aForward then l_FirstBlockMask := $FFFFFFFF shl (aStartIndex AND $1F) else l_FirstBlockMask := ($FFFFFFFF shl ((aStartIndex AND $1F)+1)) XOR $FFFFFFFF; asm MOV EAX, [l_Start] // EAX содержит адрес с которого ищем MOV EDX, [EAX] XOR EDX, l_InvertMask // инвертируем для поиска сброшенных битов AND EDX, l_FirstBlockMask // из первого блока вырезаем биты младше стартового индекса MOV CL, aForward CMP CL, 0 JE @@backward_search // ищем нужный бит по увеличению индекса @@forward_search: MOV ECX, [l_LastOfBits] // ECX содержит границу буфера - конец CMP EAX, ECX JE @@forward_last_block // @@forward_cycle: BSF EDX, EDX JNE @@found CMP ECX, 0 JE @@quit ADD EAX, $04 // передвигаем указатель на 4 байта дальше MOV EDX, [EAX] XOR EDX, l_InvertMask // инвертируем для поиска сброшенных битов CMP EAX, ECX // достигли начала буфера? JNE @@forward_cycle @@forward_last_block: AND EDX, l_LastBlockMask // из последнего блока вырезаем биты старше чем размер MOV ECX, 0 // следующая проверка станет последней JMP @@forward_cycle // ищем нужный бит по уменьшению индекса @@backward_search: MOV ECX, [Self] MOV ECX, [ECX].f_Bits // ECX содержит границу - начало буфера CMP EAX, ECX JNE @@backward_cycle AND EDX, l_LastBlockMask // @@backward_cycle: BSR EDX, EDX JNE @@found CMP EAX, ECX JE @@quit SUB EAX, $04 // передвигаем указатель на 4 байта ближе MOV EDX, [EAX] XOR EDX, l_InvertMask JMP @@backward_cycle @@found: MOV ECX, [Self] MOV ECX, [ECX].f_Bits SUB EAX, ECX // разница между указателями в байтах IMUL EAX, $8 // 8 битов в байте ADD EDX, EAX // EDX содержит номер последнего установленного бита от начала буфера MOV Result, EDX @@quit: end; //#UC END# *5025659F0300_502563E400D8_impl* end;//TatBits.GetBitFrom function TatBits.GetBufSize(aBitsCount: Integer): Integer; //#UC START# *502565EE034B_502563E400D8_var* //#UC END# *502565EE034B_502563E400D8_var* begin //#UC START# *502565EE034B_502563E400D8_impl* Result := ((aBitsCount + BITS_PER_INT - 1) div BITS_PER_INT) * SizeOf(Integer); //#UC END# *502565EE034B_502563E400D8_impl* end;//TatBits.GetBufSize function TatBits.GetLastSetBit: Integer; //#UC START# *5025661502E8_502563E400D8_var* //#UC END# *5025661502E8_502563E400D8_var* begin //#UC START# *5025661502E8_502563E400D8_impl* Result := GetBitFrom(Size-1, false, true); //#UC END# *5025661502E8_502563E400D8_impl* end;//TatBits.GetLastSetBit function TatBits.GetRandomOpenBit: Integer; //#UC START# *5025662B0086_502563E400D8_var* var l_StartIndex : Integer; l_Direction : Boolean; //#UC END# *5025662B0086_502563E400D8_var* begin //#UC START# *5025662B0086_502563E400D8_impl* l_StartIndex := Random(Size); l_Direction := Random > 0.5; Result := GetBitFrom(l_StartIndex, l_Direction, false); if Result = -1 then Result := GetBitFrom(l_StartIndex, NOT l_Direction, false); //#UC END# *5025662B0086_502563E400D8_impl* end;//TatBits.GetRandomOpenBit procedure TatBits.Reset; //#UC START# *5025664301E6_502563E400D8_var* var l_Size : Integer; //#UC END# *5025664301E6_502563E400D8_var* begin //#UC START# *5025664301E6_502563E400D8_impl* l_Size := Size; Size := 0; Size := l_Size; //#UC END# *5025664301E6_502563E400D8_impl* end;//TatBits.Reset procedure TatBits.SaveToFile(const aFileName: AnsiString); //#UC START# *5025664D00CC_502563E400D8_var* var l_Handle : Windows.THandle; //#UC END# *5025664D00CC_502563E400D8_var* begin //#UC START# *5025664D00CC_502563E400D8_impl* l_Handle := CreateFile(PAnsiChar(aFileName), GENERIC_WRITE, FILE_SHARE_READ, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if l_Handle = INVALID_HANDLE_VALUE then Raise Exception.Create( SysErrorMessage(GetLastError) ); try FileSeek(l_Handle, 0, 0); FileWrite(l_Handle, f_Size, SizeOf(f_Size)); FileWrite(l_Handle, f_Bits^, GetBufSize(f_Size)); finally CloseHandle(l_Handle); end; //#UC END# *5025664D00CC_502563E400D8_impl* end;//TatBits.SaveToFile procedure TatBits.LoadFromFile(const aFileName: AnsiString); //#UC START# *50256663004A_502563E400D8_var* var l_Handle : Windows.THandle; l_Size : Integer; //#UC END# *50256663004A_502563E400D8_var* begin //#UC START# *50256663004A_502563E400D8_impl* l_Handle := CreateFile(PAnsiChar(aFileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if l_Handle = INVALID_HANDLE_VALUE then Raise Exception.Create( SysErrorMessage(GetLastError) ); try FileSeek(l_Handle, 0, 0); FileRead(l_Handle, l_Size, SizeOf(l_Size)); Size := l_Size; FileRead(l_Handle, f_Bits^, GetBufSize(Size)); finally CloseHandle(l_Handle); end; //#UC END# *50256663004A_502563E400D8_impl* end;//TatBits.LoadFromFile destructor TatBits.Destroy; //#UC START# *48077504027E_502563E400D8_var* //#UC END# *48077504027E_502563E400D8_var* begin //#UC START# *48077504027E_502563E400D8_impl* Size := 0; inherited; //#UC END# *48077504027E_502563E400D8_impl* end;//TatBits.Destroy end.
unit HGM.Autorun; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Registry; type TAutorun = class private FAppName, FAppCommand:string; function GetAutorunCurrentReg:Boolean; procedure SetAutorunCurrentReg(const Value:Boolean); function GetAutorunLocalReg: Boolean; procedure SetAutorunLocalReg(const Value: Boolean); public constructor Create(AppName, AppCommand:string); property AppName:string read FAppName write FAppName; property AppCommand:string read FAppCommand write FAppCommand; property AutorunCurrentReg:Boolean read GetAutorunCurrentReg write SetAutorunCurrentReg; property AutorunLocalReg:Boolean read GetAutorunLocalReg write SetAutorunLocalReg; end; implementation { TAutorun } constructor TAutorun.Create(AppName, AppCommand: string); begin FAppName:=AppName; FAppCommand:=AppCommand; end; function TAutorun.GetAutorunCurrentReg:Boolean; var Reg:TRegIniFile; begin Reg:=TRegIniFile.Create(KEY_READ); Reg.RootKey:=HKEY_CURRENT_USER; if Reg.OpenKeyReadOnly('Software\Microsoft\Windows\CurrentVersion\Run\') then begin Result:=Reg.ValueExists(FAppName); end else begin Reg.Free; raise Exception.Create('Ошибка при чтении данных из реестра'); end; Reg.Free; end; procedure TAutorun.SetAutorunCurrentReg(const Value:Boolean); var Reg:TRegIniFile; begin Reg:=TRegIniFile.Create(KEY_WRITE); Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion', True); Reg.WriteString('Run', FAppName, FAppCommand); Reg.Free; end; function TAutorun.GetAutorunLocalReg: Boolean; var Reg:TRegIniFile; begin Reg:=TRegIniFile.Create(KEY_READ); Reg.RootKey:=HKEY_LOCAL_MACHINE; if Reg.OpenKeyReadOnly('Software\Microsoft\Windows\CurrentVersion\Run\') then begin Result:=Reg.ValueExists(FAppName); end else begin Reg.Free; raise Exception.Create('Ошибка при чтении данных из реестра'); end; Reg.Free; end; procedure TAutorun.SetAutorunLocalReg(const Value: Boolean); var Reg:TRegIniFile; begin Reg:=TRegIniFile.Create(KEY_WRITE); Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion', True); Reg.WriteString('Run', FAppName, FAppCommand); Reg.Free; end; end.
PROGRAM HelloWorld(INPUT, OUTPUT); BEGIN WRITELN('Hello world') END.
unit tmvRecordOffsets; interface uses l3CacheableBase, tmvInterfaces ; type TtmvRecordOffsets = class(Tl3CacheableBase, ItmvRecordOffsets) private f_StartOffset: int64; f_EndOffset: int64; protected //ItmvRecordOffsets function pm_GetStartOffset: Int64; {-} function pm_GetEndOffset: Int64; {-} protected procedure cleanup; override; public constructor Create(aStart, aEnd: int64); reintroduce; {-} class function Make(aStart, aEnd: int64): ItmvRecordOffsets; {-} end;//TtmvRecordOffsets implementation uses l3Base ; { TtmvRecordOffsets } procedure TtmvRecordOffsets.cleanup; begin inherited; end; constructor TtmvRecordOffsets.Create(aStart, aEnd: int64); begin inherited Create; f_StartOffset := aStart; f_EndOffset := aEnd; end; class function TtmvRecordOffsets.Make(aStart, aEnd: int64): ItmvRecordOffsets; var l_Instance: TtmvRecordOffsets; begin l_Instance := TtmvRecordOffsets.Create(aStart, aEnd); try Result := l_Instance; finally l3Free(l_Instance); end; end; function TtmvRecordOffsets.pm_GetEndOffset: Int64; begin Result := f_EndOffset; end; function TtmvRecordOffsets.pm_GetStartOffset: Int64; begin Result := f_StartOffset; end; end.
/// <summary> /// This class contains a basic scene node, to which objects can be attached, and which serves as a node for the scene graph. /// All /// </summary> unit aeSceneNode; interface uses windows, types, System.Generics.Collections, aeSceneObject, aeTransform, aeMaths; type TaeSceneNodeType = (AE_SCENENODE_TYPE_NODE, AE_SCENENODE_TYPE_GEOMETRY, AE_SCENENODE_TYPE_LIGHT, AE_SCENENODE_TYPE_PRIMITIVESHAPE, AE_SCENENODE_TYPE_TERRAIN); type TaeSceneNode = class(TaeSceneObject) constructor Create(name: string); overload; constructor Create; overload; destructor Destroy; override; procedure AddChild(theChild: TaeSceneNode); function RemoveChild(theChild: TaeSceneNode): boolean; /// <remarks> /// Gets all child nodes. /// </remarks> function ListChildren: TList<TaeSceneNode>; overload; /// <remarks> /// Gets all child nodes of a certain type. /// </remarks> function ListChildren(childType: TaeSceneNodeType): TList<TaeSceneNode>; overload; procedure setParent(parent: TaeSceneNode); function getParent: TaeSceneNode; procedure RemoveFromParentNode; /// <remarks> /// Get the type of scene node. /// </remarks> function getType: TaeSceneNodeType; /// <remarks> /// Get world transformation (the sum of all transformations of all nodes before this and including this in tree) /// </remarks> function GetWorldTransformationMatrix: TaeMatrix44; procedure RecalculateWorldTransform; function IsWorldTransformDirty: boolean; procedure SetWorldTransformDirty(d: boolean); procedure SetNodeName(n: string); function GetNodeName: String; private // this transform matrix contains all changes done to this point in scene graph! _worldTransformMatrix: TaeMatrix44; _worldMatrixDirty: boolean; _parent: TaeSceneNode; _childNodes: TList<TaeSceneNode>; procedure SetSelfAndChildrenDirty; protected _NodeType: TaeSceneNodeType; _name: String; end; implementation { TaeNode } constructor TaeSceneNode.Create(name: string); begin inherited Create; self._NodeType := AE_SCENENODE_TYPE_NODE; self._name := name; self._childNodes := TList<TaeSceneNode>.Create; self._worldTransformMatrix.loadIdentity; self.SetLocalTransformDirty(false); self.SetDirtyCallback(self.SetSelfAndChildrenDirty); end; constructor TaeSceneNode.Create; begin inherited Create; self._NodeType := AE_SCENENODE_TYPE_NODE; self._worldTransformMatrix.loadIdentity; self._childNodes := TList<TaeSceneNode>.Create; self._worldTransformMatrix.loadIdentity; self.SetLocalTransformDirty(false); self.SetDirtyCallback(self.SetSelfAndChildrenDirty); end; // multiply current local transform with parent's world transform. procedure TaeSceneNode.RecalculateWorldTransform; var parentWorldMatrix, newMatrix: TaeMatrix44; begin // recalc our world matrix, using parent's world matrix and our local one. if (self.getParent <> nil) then begin // Recursively recalculate transforms until root node if (self.getParent.IsWorldTransformDirty()) or (self.getParent.IsLocalTransformDirty()) then self.getParent.RecalculateWorldTransform; parentWorldMatrix := self.getParent.GetWorldTransformationMatrix; self._worldTransformMatrix.loadIdentity; self._worldTransformMatrix := (parentWorldMatrix * self.GetLocalTransformMatrix()); self.SetWorldTransformDirty(false); end else // world matrix of root node is same as the local transform of world! self._worldTransformMatrix := self.GetLocalTransformMatrix(); end; function TaeSceneNode.RemoveChild(theChild: TaeSceneNode): boolean; var i: Integer; begin result := false; if (self._childNodes.Remove(theChild) > -1) then begin self._childNodes.Pack; result := true; end; end; procedure TaeSceneNode.RemoveFromParentNode; begin if (self._parent <> nil) then begin self._parent.RemoveChild(self); self._parent := nil; end; end; function TaeSceneNode.GetWorldTransformationMatrix: TaeMatrix44; var localTransform: TaeMatrix44; begin if (self.IsWorldTransformDirty()) or (self.IsLocalTransformDirty()) then begin self.RecalculateWorldTransform; end; result := self._worldTransformMatrix; end; function TaeSceneNode.IsWorldTransformDirty: boolean; begin result := self._worldMatrixDirty; end; procedure TaeSceneNode.SetNodeName(n: string); begin self._name := n; end; destructor TaeSceneNode.Destroy; begin // TODO : Free all children? Or do we need to have them do that on their own? self._childNodes.Free; self._parent := nil; inherited; end; function TaeSceneNode.GetNodeName: String; begin result := self._name; end; function TaeSceneNode.getParent: TaeSceneNode; begin result := self._parent; end; function TaeSceneNode.getType: TaeSceneNodeType; begin result := self._NodeType; end; function TaeSceneNode.ListChildren(childType: TaeSceneNodeType): TList<TaeSceneNode>; var i: Integer; begin result := self.ListChildren; for i := 0 to result.Count - 1 do if (result[i].getType <> childType) then result.Delete(i); end; procedure TaeSceneNode.AddChild(theChild: TaeSceneNode); begin if (theChild <> self) then begin theChild.setParent(self); self._childNodes.Add(theChild); end; end; function TaeSceneNode.ListChildren: TList<TaeSceneNode>; var i: Integer; tempRecursiveList: TList<TaeSceneNode>; e: Integer; begin // recursively list all children! result := TList<TaeSceneNode>.Create; if (self._childNodes.Count > 0) then begin // we have child nodes! for i := 0 to self._childNodes.Count - 1 do begin // for every child node, we first add it... result.Add(self._childNodes[i]); // ... and then, we add that node's children recursively! tempRecursiveList := self._childNodes[i].ListChildren; for e := 0 to tempRecursiveList.Count - 1 do result.Add(tempRecursiveList[e]); // now, we free the list. tempRecursiveList.Free; end; end; end; procedure TaeSceneNode.setParent(parent: TaeSceneNode); begin self._parent := parent; end; procedure TaeSceneNode.SetWorldTransformDirty(d: boolean); begin self._worldMatrixDirty := d; end; procedure TaeSceneNode.SetSelfAndChildrenDirty; var l: TList<TaeSceneNode>; i: Integer; begin self.SetWorldTransformDirty(true); self._localTransformDirty := true; l := self.ListChildren; for i := 0 to l.Count - 1 do begin l[i].SetWorldTransformDirty(true); l[i].SetLocalTransformDirty(true); end; l.Free; end; end.
unit csCommandsManager; interface {$Include l3XE.inc} uses csCommandsConst, IdGlobal, l3ObjectRefList, ActnList, Classes, CsDataPipe, ddAppConfigTypes, l3Base, csCommandsTypes, l3SimpleObjectRefList {$IfDef XE} , System.SyncObjs {$EndIf} ; type TcsCommandsManager = class(Tl3Base) private f_Commands: Tl3SimpleObjectRefList; f_CS: TCriticalSection; f_OnExecuteServerCommand: TNotifyEvent; function pm_GetCommands(Index: Integer): TcsCommand; function pm_GetCount: Integer; protected procedure Acquire; procedure Add(aCommand: TcsCommand); procedure Cleanup; override; procedure Leave; public constructor Create(aOwner: TObject); procedure ClearCommands; function CommandExists(aID: TcsCommands; out theCommand: TcsCommand): Boolean; overload; function CommandExists(aID: Integer; out theCommand: TcsCommand): Boolean; overload; property Commands[Index: Integer]: TcsCommand read pm_GetCommands; property Count: Integer read pm_GetCount; property OnExecuteServerCommand: TNotifyEvent read f_OnExecuteServerCommand write f_OnExecuteServerCommand; end; implementation uses SysUtils; constructor TcsCommandsManager.Create(aOwner: TObject); begin inherited; f_Commands:= Tl3SimpleObjectRefList.Make; f_CS:= TCriticalSection.Create; end; procedure TcsCommandsManager.Acquire; begin f_CS.Acquire; end; procedure TcsCommandsManager.Add(aCommand: TcsCommand); begin f_Commands.Add(aCommand); FreeAndNil(aCommand); end; procedure TcsCommandsManager.Cleanup; begin l3Free(f_Commands); l3Free(f_CS); inherited; end; procedure TcsCommandsManager.ClearCommands; begin f_Commands.Clear; end; function TcsCommandsManager.CommandExists(aID: TcsCommands; out theCommand: TcsCommand): Boolean; begin Result := CommandExists(Ord(aID), theCommand); end; function TcsCommandsManager.CommandExists(aID: Integer; out theCommand: TcsCommand): Boolean; var i: Integer; begin Result := False; theCommand:= nil; i:= 0; while not Result and (i <= f_Commands.Hi) do begin if TcsCommand(f_Commands.Items[i]).CommandID = aID then begin Result:= True; theCommand:= TcsCommand(f_Commands.Items[i]); end else Inc(i); end; end; procedure TcsCommandsManager.Leave; begin f_CS.Leave; end; function TcsCommandsManager.pm_GetCommands(Index: Integer): TcsCommand; begin Result := f_Commands[index] as TcsCommand; end; function TcsCommandsManager.pm_GetCount: Integer; begin Result := f_Commands.Count; end; end.
namespace Sugar.Collections; interface type HashSet<T> = public class mapped to {$IF COOPER}java.util.HashSet<T>{$ELSEIF ECHOES}System.Collections.Generic.HashSet<T>{$ELSEIF TOFFEE}Foundation.NSMutableSet{$ENDIF} public constructor; mapped to constructor(); constructor(&Set: HashSet<T>); method &Add(Item: T): Boolean; method Clear; mapped to {$IF COOPER OR ECHOES}Clear{$ELSE}removeAllObjects{$ENDIF}; method Contains(Item: T): Boolean; method &Remove(Item: T): Boolean; method ForEach(Action: Action<T>); method Intersect(&Set: HashSet<T>); method &Union(&Set: HashSet<T>); method IsSubsetOf(&Set: HashSet<T>): Boolean; method IsSupersetOf(&Set: HashSet<T>): Boolean; method SetEquals(&Set: HashSet<T>): Boolean; property Count: Integer read {$IF ECHOES OR TOFFEE}mapped.Count{$ELSE}mapped.size{$ENDIF}; {$IF TOFFEE} operator Implicit(aSet: NSSet<T>): HashSet<T>; {$ENDIF} end; HashsetHelpers = public class private public class method Foreach<T>(aSelf: HashSet<T>; aAction: Action<T>); class method IsSubsetOf<T>(aSelf, aSet: HashSet<T>): Boolean; end; implementation { HashSet } constructor HashSet<T>(&Set: HashSet<T>); begin {$IF COOPER} exit new java.util.HashSet<T>(&Set); {$ELSEIF ECHOES} exit new System.Collections.Generic.HashSet<T>(&Set); {$ELSEIF TOFFEE} var NewSet := new Foundation.NSMutableSet(); NewSet.setSet(&Set); exit NewSet; {$ENDIF} end; method HashSet<T>.&Add(Item: T): Boolean; begin {$IF COOPER OR ECHOES} exit mapped.Add(Item); {$ELSEIF TOFFEE} var lSize := mapped.count; mapped.addObject(NullHelper.ValueOf(Item)); exit lSize < mapped.count; {$ENDIF} end; method HashSet<T>.Contains(Item: T): Boolean; begin {$IF COOPER OR ECHOES} exit mapped.Contains(Item); {$ELSEIF TOFFEE} exit mapped.containsObject(NullHelper.ValueOf(Item)); {$ENDIF} end; method HashSet<T>.&Remove(Item: T): Boolean; begin {$IF COOPER OR ECHOES} exit mapped.Remove(Item); {$ELSEIF TOFFEE} var lSize := mapped.count; mapped.removeObject(NullHelper.ValueOf(Item)); exit lSize > mapped.count; {$ENDIF} end; method HashSet<T>.ForEach(Action: Action<T>); begin HashsetHelpers.Foreach(self, Action); end; method HashSet<T>.Intersect(&Set: HashSet<T>); begin {$IF COOPER} mapped.retainAll(&Set); {$ELSEIF ECHOES} mapped.IntersectWith(&Set); {$ELSEIF TOFFEE} mapped.intersectSet(&Set); {$ENDIF} end; method HashSet<T>.&Union(&Set: HashSet<T>); begin {$IF COOPER} mapped.addAll(&Set); {$ELSEIF ECHOES} mapped.UnionWith(&Set); {$ELSEIF TOFFEE} mapped.unionSet(&Set); {$ENDIF} end; method HashSet<T>.SetEquals(&Set: HashSet<T>): Boolean; begin {$IF COOPER} exit mapped.equals(&Set); {$ELSEIF ECHOES} exit mapped.SetEquals(&Set); {$ELSEIF TOFFEE} exit mapped.isEqualToSet(&Set); {$ENDIF} end; method HashSet<T>.IsSupersetOf(&Set: HashSet<T>): Boolean; begin exit HashsetHelpers.IsSubsetOf(&Set, self); end; method HashSet<T>.IsSubsetOf(&Set: HashSet<T>): Boolean; begin exit HashsetHelpers.IsSubsetOf(self, &Set); end; {$IF TOFFEE} operator HashSet<T>.Implicit(aSet: NSSet<T>): HashSet<T>; begin if aSet is NSMutableArray then result := HashSet<T>(aSet) else result := HashSet<T>(aSet:mutableCopy); end; {$ENDIF} { HashsetHelpers } class method HashsetHelpers.Foreach<T>(aSelf: HashSet<T>; aAction: Action<T>); begin for each el in aSelf do aAction(el); end; class method HashsetHelpers.IsSubsetOf<T>(aSelf, aSet: HashSet<T>): Boolean; begin if aSelf.Count = 0 then exit true; if aSelf.Count > aSet.Count then exit false; for each el in aSelf do if not aSet.Contains(el) then exit false; exit true; end; end.
unit ProgramSettings; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, IOUtils, printers,WinSpool, FFSUtils, FFSTypes; type TProgramSettings = class(Tcomponent) private FRegistryKey: string; FServerIP: string; FServerPort: string; FApplPrinters : array[1..3] of string; FLastCommandLine: string; procedure SetRegistryKey(const Value: string); procedure SetDirWork(const Value: string); procedure SetServerIP(const Value: string); procedure SetServerPort(const Value: string); function GetPrinters(Index: Integer): string; procedure SetPrinters(Index: Integer; const Value: string); function GetDirWork: string; { Private declarations } protected { Protected declarations } public { Public declarations } procedure SaveSettings(aRootKey: Cardinal = HKEY_CURRENT_USER); procedure ReadSettings; property ApplPrinters[Index: Integer]: string read GetPrinters write SetPrinters; property LastCommandLine:string read FLastCommandLine ; published { Published declarations } property RegistryKey:string read FRegistryKey write SetRegistryKey; property DirWork:string read GetDirWork write SetDirWork; property ServerIP: string read FServerIP write SetServerIP; property ServerPort: string read FServerPort write SetServerPort; end; TFFSDirectory = (drData, drReports, drToDo, drDone, drLtrAddOn, drUpdate, drExport, drUserRpts, drCacheReports, drCacheExport); TFFSDirSet = set of TFFSDirectory; function Dir(ADir:TFFSDirectory;DoRaise:boolean=true):string; function DirTemp:string; function DirExe:string; procedure MakeDirs(ASet:TFFSDirSet); procedure SetBaseDir(ABaseDir:string); procedure Register; implementation uses registry, filectrl; var FBaseDir:string; procedure Register; begin RegisterComponents('FFS Common', [TProgramSettings]); end; { TProgramSettings } function TProgramSettings.GetDirWork: string; begin result := FBaseDir; end; function TProgramSettings.GetPrinters(Index: Integer): string; begin result := FApplPrinters[Index]; end; procedure TProgramSettings.ReadSettings; var reg : TRegistry; x: integer; OkKey : boolean; begin reg := TRegistry.Create; try reg.RootKey := HKEY_CURRENT_USER; OkKey := reg.OpenKey(RegistryKey, false); if not OkKey then begin reg.RootKey := HKEY_LOCAL_MACHINE; OkKey := reg.OpenKey(RegistryKey, false); end; if OkKey then begin try DirWork := reg.ReadString('DataDirectory'); except DirWork := ''; end; try FServerIP := reg.ReadString('ServerIP'); except FServerIP := ''; end; try FServerPort := reg.ReadString('ServerPort'); except FServerPort := ''; end; for x := 1 to 3 do begin try FApplPrinters[x] := reg.ReadString('Printer' + InttoStr(x)); if empty(FApplPrinters[x]) or (not ValidPrinter(FApplPrinters[x])) then FApplPrinters[x] := FFSDEFAULTPRINTER; except FApplPrinters[x] := FFSDEFAULTPRINTER; end; end; try FLastCommandLine := reg.ReadString('LastCommandLine'); except FLastCommandLine := ''; end; reg.CloseKey; end else raise exception.create('No Such Key ' + RegistryKey ); finally reg.free; end; end; procedure TProgramSettings.SaveSettings(aRootKey: Cardinal = HKEY_CURRENT_USER); var reg : TRegistry; begin FLastCommandLine := strpas(CmdLine); reg := TRegistry.Create; try reg.RootKey := aRootKey; if reg.OpenKey(RegistryKey, true) then begin reg.WriteString('DataDirectory', DirWork); reg.WriteString('ServerIP',ServerIP); reg.WriteString('ServerPort',ServerPort); reg.WriteString('Printer1', ApplPrinters[1]); reg.WriteString('Printer2', ApplPrinters[2]); reg.WriteString('Printer3', ApplPrinters[3]); reg.WriteString('LastCommandLine', FLastCommandLine); reg.CloseKey; end; finally reg.free; end; end; procedure TProgramSettings.SetDirWork(const Value: string); begin if Value.IsEmpty then SetBaseDir(Value) else SetBaseDir(IncludeTrailingBackslash(Value)); end; procedure TProgramSettings.SetPrinters(Index: Integer; const Value: string); begin FApplPrinters[Index] := Value; end; procedure TProgramSettings.SetRegistryKey(const Value: string); begin FRegistryKey := Value; end; procedure TProgramSettings.SetServerIP(const Value: string); begin FServerIP := Value; end; procedure TProgramSettings.SetServerPort(const Value: string); begin FServerPort := Value; end; function Dirs(ADir:TFFSDirectory):string; begin result := ''; case ADir of drData : result := 'Data'; drReports : result := 'Reports'; drToDo : result := 'ToDo'; drDone : result := 'Done'; drLtrAddOn : result := 'LtrAddOn'; drUpdate : result := 'Update'; drExport : result := 'Export'; end; end; function DirTemp: string; begin Result := IncludeTrailingPathDelimiter(TPath.GetTempPath); end; function Dir(ADir:TFFSDirectory;DoRaise:boolean=true):string; var s : string; begin result := ''; s := IncludeTrailingBackslash(ExtractFileDir(Application.ExeName)); case ADir of {$ifdef THINVER} drReports : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drData : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drToDo : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drDone : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drUpdate : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drExport : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drLtrAddOn : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; {$else} drReports : result := FBaseDir + Dirs(ADir); drData : result := FBaseDir + Dirs(ADir); drToDo : result := FBaseDir + Dirs(ADir); drDone : result := FBaseDir + Dirs(ADir); drUpdate : result := FBaseDir + Dirs(ADir); drExport : result := FBaseDir + Dirs(ADir); drLtrAddOn : result := FBaseDir + Dirs(ADir); {$endif} end; result := IncludeTrailingBackslash(result); if (not DirectoryExists(result)) and (DoRaise) then raise Exception.Create(Format('Tickler: Directory (%s) does not exist',[result])); end; procedure MakeDirs(ASet:TFFSDirSet); var x : TFFSDirectory; s : string; begin if Aset = [] then begin // for x := drData to drUpdate do begin for x := drData to drUpdate do begin // any reason not to create them all? s := Dir(x,false); if not DirectoryExists(s) then try ForceDirectories(s); except end; end; end else begin for x := low(TFFSDirectory) to high(TFFSDirectory) do begin if x in ASet then begin s := Dir(x,false); if not DirectoryExists(s) then ForceDirectories(s); end; end; end; end; function DirExe:string; begin result := IncludeTrailingBackslash(ExtractFileDir(Application.ExeName)); end; procedure SetBaseDir(ABaseDir:string); begin FBaseDir := ABaseDir; end; initialization FBaseDir := ''; end.
{@html(<hr>) @abstract(Information provider class (known telemetry events, channels, etc.).) @author(František Milt <fmilt@seznam.cz>) @created(2013-10-07) @lastmod(2014-05-04) @bold(@NoAutoLink(TelemetryInfoProvider)) ©František Milt, all rights reserved. This unit contains TTelemetryInfoProvider class (see class declaration for details). Included files:@preformatted( .\Inc\TTelemetryInfoProvider.Prepare_Telemetry_1_0.pas Contains body of method TTelemetryInfoProvider.Prepare_Telemetry_1_0.) Last change: 2014-05-04 Change List:@unorderedList( @item(2013-10-07 - First stable version.) @item(2014-04-15 - Type of parameter @code(Name) in method TTelemetryInfoProvider.ChannelGetValueType changed to @code(TelemetryString).) @item(2014-04-18 - Result type of method TTelemetryInfoProvider.EventGetName changed to @code(TelemetryString).) @item(2014-04-27 - Added constructor mehod TTelemetryInfoProvider.CreateCurrent.) @item(2014-05-04 - Following callback functions were added:@unorderedList( @itemSpacing(Compact) @item(InfoProviderGetChannelIDFromName) @item(InfoProviderGetChannelNameFromID) @item(InfoProviderGetConfigIDFromName) @item(InfoProviderGetConfigNameFromID)))) ToDo:@unorderedList( @item(Add capability for loading information from file (text or ini).)) @html(<hr>)} unit TelemetryInfoProvider; interface {$INCLUDE '.\Telemetry_defs.inc'} uses TelemetryIDs, TelemetryLists, TelemetryVersionObjects, {$IFDEF Documentation} TelemetryCommon, {$ENDIF} {$IFDEF UseCondensedHeader} SCS_Telemetry_Condensed; {$ELSE} scssdk, scssdk_value, scssdk_telemetry, scssdk_telemetry_event, scssdk_telemetry_common_configs, scssdk_telemetry_common_channels, scssdk_telemetry_trailer_common_channels, scssdk_telemetry_truck_common_channels, scssdk_eut2, scssdk_telemetry_eut2; {$ENDIF} {==============================================================================} {------------------------------------------------------------------------------} { TTelemetryInfoProvider } {------------------------------------------------------------------------------} {==============================================================================} type { Used to distinguish which value type should method TTelemetryInfoProvider.ChannelGetValueType return for given channel. @value(cvtpPrimary Basic value type.) @value(cvtpSecondary Second used type (e.g. double for float types, u64 for u32, ...).) @value(cvtpTertiary Third type (e.g. euler for [f/d]placement).) } TChannelValueTypePriority = (cvtpPrimary, cvtpSecondary, cvtpTertiary); {==============================================================================} { TTelemetryInfoProvider // Class declaration } {==============================================================================} { @abstract(@NoAutoLink(TTelemetryInfoProvider) class provide lists of all known game events, channels and configurations along with some methods operating on them.) It can be created in two ways, user managed or automatically managed.@br When created as user managed (using no-paramater constructor), the object is created with empty lists and it is up to the user to fill them (use methods of individual lists to do so).@br When automatically managed (object is created using parametrized constructor), the telemetry and game versions are passed to the constructor and it checks whether they are supported or not. If they are, the lists are filled accordingly to them, if they are not supported, the constructor raises an exception.@br @member(fUserManaged Holds state indicationg whether current instance is user managed (when not, it is managed automatically).@br This field is set automatically in constructor(s).) @member(fKnownEvents See KnownEvents property.) @member(fKnownChannels See KnownChannels property.) @member(fKnownConfigs See KnownConfigs property.) @member(Prepare_Telemetry_1_0 Preparation for telemetry 1.0.) @member(Prepare_Game_eut2_1_0 Preparation for eut2 1.0.) @member(Prepare_Game_eut2_1_1 Preparation for eut2 1.1.) @member(Prepare_Game_eut2_1_2 Preparation for eut2 1.2.) @member(Prepare_Game_eut2_1_4 Preparation for eut2 1.4.) @member(Destroy Object destructor.@br Internal lists are automatically cleared in destructor, so it is unnecessary to @noAutoLink(clear) them explicitly.) @member(Clear When current instance is created as user managed, calling this procedure will clear all internal lists. When it is called on automatically managed object, it does nothing.) @member(EventGetName Returns internal (i.e. not defined by the API) name of passed event. @param Event Event whose name is requested. @returns(Name of given event or an empty string when no such event is known.)) @member(ChannelGetValueType Returns type of value for given channel and selected priority. @param Name Name of requested channel. @param TypePriority Priority of value type that should be returned. @returns(Type of value for selected channel and priority. When requested channel is not found, @code(SCS_VALUE_TYPE_INVALID) is returned.)) @member(KnownEvents List containing informations about known telemetry events.) @member(KnownChannels List containing informations about known telemetry channels.) @member(KnownConfigs List containing informations about known telemetry configs.) @member(UserManaged @True when current instance is user managed, @false when it is managed automatically.) } TTelemetryInfoProvider = class(TTelemetryVersionPrepareObject) private fUserManaged: Boolean; fKnownEvents: TKnownEventsList; fKnownChannels: TKnownChannelsList; fKnownConfigs: TKnownConfigsList; protected procedure Prepare_Telemetry_1_0; override; procedure Prepare_Game_eut2_1_0; override; procedure Prepare_Game_eut2_1_1; override; procedure Prepare_Game_eut2_1_2; override; procedure Prepare_Game_eut2_1_4; override; public { Basic object constructor.@br Call this no-parameter constructor when creating user managed info provider. Lists of known items are created empty. } constructor Create; overload; { Parameterized object constructor.@br Call this constructor when creating automatically managed info provider. Lists of known items are filled automatically in this constructor accordingly to passed telemetry and game versions.@br If passed telemetry/game versions are not supported then an exception is raised. @param TelemetryVersion Version of telemetry. @param GameID Game identifier. @param GameVersion Version of game. } constructor Create(TelemetryVersion: scs_u32_t; GameID: scs_string_t; GameVersion: scs_u32_t); overload; { Specialized object constructor.@br This constructor is designed to automatically fill lists with latest data available for passed game. It actually calls parametrized constructor with parameter @code(TelemetryVersion) set to value returned by function HighestSupportedTelemetryVersion, @code(GameID) set to passed game id and @code(GameVersion) set to value returned by function HighestSupportedGameVersion. @param GameID Game identifier. } constructor CreateCurrent(GameID: TelemetryString); virtual; destructor Destroy; override; procedure Clear; Function EventGetName(Event: scs_event_t): TelemetryString; virtual; Function ChannelGetValueType(const Name: TelemetryString; TypePriority: TChannelValueTypePriority = cvtpPrimary): scs_value_type_t; virtual; published property KnownEvents: TKnownEventsList read fKnownEvents; property KnownChannels: TKnownChannelsList read fKnownChannels; property KnownConfigs: TKnownConfigsList read fKnownConfigs; property UserManaged: Boolean read fUserManaged; end; {==============================================================================} { Unit Functions and procedures // Declaration } {==============================================================================} { @abstract(Function intended as callback for streaming functions, converting channel name to ID.) @code(UserData) passed to streaming function along with this callback must contain valid TTelemetryInfoProvider object. @param Name Channel name to be converted to ID. @param(TelemetryInfoProvider TTelemetryInfoProvider object that will be used for actual conversion.) @returns Channel ID obtained from passed name. } Function InfoProviderGetChannelIDFromName(const Name: TelemetryString; TelemetryInfoProvider: Pointer): TChannelID; { @abstract(Function intended as callback for streaming functions, converting channel ID to name.) @code(UserData) passed to streaming function along with this callback must contain valid TTelemetryInfoProvider object. @param ID Channel ID to be converted to name. @param(TelemetryInfoProvider TTelemetryInfoProvider object that will be used for actual conversion.) @returns Channel name obtained from passed ID. } Function InfoProviderGetChannelNameFromID(ID: TChannelID; TelemetryInfoProvider: Pointer): TelemetryString; { @abstract(Function intended as callback for streaming functions, converting config name to ID.) @code(UserData) passed to streaming function along with this callback must contain valid TTelemetryInfoProvider object. @param Name Config name to be converted to ID. @param(TelemetryInfoProvider TTelemetryInfoProvider object that will be used for actual conversion.) @returns Config ID obtained from passed name. } Function InfoProviderGetConfigIDFromName(const Name: TelemetryString; TelemetryInfoProvider: Pointer): TConfigID; { @abstract(Function intended as callback for streaming functions, converting ID to config name.) @code(UserData) passed to streaming function along with this callback must contain valid TTelemetryInfoProvider object. @param ID Config ID to be converted to name. @param(TelemetryInfoProvider TTelemetryInfoProvider object that will be used for actual conversion.) @returns Config name obtained from passed ID. } Function InfoProviderGetConfigNameFromID(ID: TConfigID; TelemetryInfoProvider: Pointer): TelemetryString; implementation uses SysUtils, TelemetryCommon; {==============================================================================} { Unit Functions and procedures // Implementation } {==============================================================================} Function InfoProviderGetChannelIDFromName(const Name: TelemetryString; TelemetryInfoProvider: Pointer): TChannelID; begin Result := TTelemetryInfoProvider(TelemetryInfoProvider).KnownChannels.ChannelNameToID(Name); end; //------------------------------------------------------------------------------ Function InfoProviderGetChannelNameFromID(ID: TChannelID; TelemetryInfoProvider: Pointer): TelemetryString; begin Result := TTelemetryInfoProvider(TelemetryInfoProvider).KnownChannels.ChannelIDToName(ID); end; //------------------------------------------------------------------------------ Function InfoProviderGetConfigIDFromName(const Name: TelemetryString; TelemetryInfoProvider: Pointer): TConfigID; begin Result := TTelemetryInfoProvider(TelemetryInfoProvider).KnownConfigs.ConfigNameToID(Name); end; //------------------------------------------------------------------------------ Function InfoProviderGetConfigNameFromID(ID: TConfigID; TelemetryInfoProvider: Pointer): TelemetryString; begin Result := TTelemetryInfoProvider(TelemetryInfoProvider).KnownConfigs.ConfigIDToName(ID); end; {==============================================================================} {------------------------------------------------------------------------------} { TTelemetryInfoProvider } {------------------------------------------------------------------------------} {==============================================================================} {==============================================================================} { TTelemetryInfoProvider // Class implementation } {==============================================================================} {------------------------------------------------------------------------------} { TTelemetryInfoProvider // Protected methods } {------------------------------------------------------------------------------} procedure TTelemetryInfoProvider.Prepare_Telemetry_1_0; begin inherited; // As content of this function is rather monstrous, it is, for the sake of // clarity, separated in its own file. {$INCLUDE '.\Inc\TTelemetryInfoProvider.Prepare_Telemetry_1_0.pas'} end; //------------------------------------------------------------------------------ procedure TTelemetryInfoProvider.Prepare_Game_eut2_1_0; begin inherited; fKnownChannels.Remove(SCS_TELEMETRY_TRUCK_CHANNEL_adblue); fKnownChannels.Remove(SCS_TELEMETRY_TRUCK_CHANNEL_adblue_warning); fKnownChannels.Remove(SCS_TELEMETRY_TRUCK_CHANNEL_adblue_average_consumption); end; //------------------------------------------------------------------------------ procedure TTelemetryInfoProvider.Prepare_Game_eut2_1_1; begin inherited; fKnownChannels.Insert(fKnownChannels.IndexOf(SCS_TELEMETRY_TRUCK_CHANNEL_brake_temperature), SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure_emergency, SCS_VALUE_TYPE_bool, SCS_VALUE_TYPE_invalid, SCS_VALUE_TYPE_invalid, False); fKnownConfigs.Insert(fKnownConfigs.IndexOf(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_oil_pressure_warning), SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_air_pressure_emergency, SCS_VALUE_TYPE_float, False); end; //------------------------------------------------------------------------------ procedure TTelemetryInfoProvider.Prepare_Game_eut2_1_2; begin inherited; fKnownChannels.Replace('truck.cabin.orientation', SCS_TELEMETRY_TRUCK_CHANNEL_cabin_offset, SCS_VALUE_TYPE_fplacement, SCS_VALUE_TYPE_dplacement, SCS_VALUE_TYPE_euler, False); end; //------------------------------------------------------------------------------ procedure TTelemetryInfoProvider.Prepare_Game_eut2_1_4; begin inherited; fKnownChannels.Insert(fKnownChannels.IndexOf(SCS_TELEMETRY_TRUCK_CHANNEL_light_parking), SCS_TELEMETRY_TRUCK_CHANNEL_light_lblinker, SCS_VALUE_TYPE_bool, SCS_VALUE_TYPE_invalid, SCS_VALUE_TYPE_invalid, False); fKnownChannels.Insert(fKnownChannels.IndexOf(SCS_TELEMETRY_TRUCK_CHANNEL_light_parking), SCS_TELEMETRY_TRUCK_CHANNEL_light_rblinker, SCS_VALUE_TYPE_bool, SCS_VALUE_TYPE_invalid, SCS_VALUE_TYPE_invalid, False); end; {------------------------------------------------------------------------------} { TTelemetryInfoProvider // Public methods } {------------------------------------------------------------------------------} constructor TTelemetryInfoProvider.Create; begin inherited Create; // User managed instance. fUserManaged := True; // Create lists. fKnownEvents := TKnownEventsList.Create; fKnownChannels := TKnownChannelsList.Create; fKnownConfigs := TKnownConfigsList.Create; end; constructor TTelemetryInfoProvider.Create(TelemetryVersion: scs_u32_t; GameID: scs_string_t; GameVersion: scs_u32_t); begin // Call basic constructor to initialize lists. Create; // Automatically managed instance. fUserManaged := False; // Prepare for required telemetry/game version, raise exception on unsupported // versions. If not PrepareForTelemetryVersion(TelemetryVersion) then raise Exception.Create('TTelemetryInfoProvider.Create(...): Telemetry version (' + SCSGetVersionAsString(TelemetryVersion) + ') is not supported'); If not PrepareForGameVersion('',APIStringToTelemetryString(GameID),GameVersion) then raise Exception.Create('TTelemetryInfoProvider.Create(...): Game version (' + TelemetryStringDecode(APIStringToTelemetryString(GameID)) + ' ' + SCSGetVersionAsString(GameVersion) + ') is not supported'); end; constructor TTelemetryInfoProvider.CreateCurrent(GameID: TelemetryString); begin Create(HighestSupportedTelemetryVersion,scs_string_t(GameID),HighestSupportedGameVersion(scs_string_t(GameID))); end; //------------------------------------------------------------------------------ destructor TTelemetryInfoProvider.Destroy; begin fKnownConfigs.Free; fKnownChannels.Free; fKnownEvents.Free; inherited; end; //------------------------------------------------------------------------------ procedure TTelemetryInfoProvider.Clear; begin If UserManaged then begin fKnownEvents.Clear; fKnownChannels.Clear; fKnownConfigs.Clear; end; end; //------------------------------------------------------------------------------ Function TTelemetryInfoProvider.EventGetName(Event: scs_event_t): TelemetryString; var Index: Integer; begin Index := fKnownEvents.IndexOf(Event); If Index >= 0 then Result := fKnownEvents[Index].Name else Result := ''; end; //------------------------------------------------------------------------------ Function TTelemetryInfoProvider.ChannelGetValueType(const Name: TelemetryString; TypePriority: TChannelValueTypePriority = cvtpPrimary): scs_value_type_t; var Index: Integer; begin Index := fKnownChannels.IndexOf(Name); If Index >= 0 then begin case TypePriority of cvtpPrimary: Result := fKnownChannels[Index].PrimaryType; cvtpSecondary: Result := fKnownChannels[Index].SecondaryType; cvtpTertiary: Result := fKnownChannels[Index].TertiaryType; else Result := SCS_VALUE_TYPE_invalid; end; end else Result := SCS_VALUE_TYPE_invalid; end; end.
unit fileutilwin; { Version 0.1 Copyright (C) 2018 by James O. Dreher License: https://opensource.org/licenses/MIT 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. } {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, LazFileUtils; function ChildPath(aPath: string): string; function ParentPath(aPath: string): string; function JoinPath(aDir, aFile: string): string; function CopyDirWin(sourceDir, targetDir: string; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): boolean; function CopyDirWinEC(sourceDir, targetDir: string; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): integer; function DelDirWin(targetDir: string; OnlyChildren: boolean=False): boolean; function MoveDirWin(sourceDir, targetDir: string): boolean; function CopyFileWin(sourceFile, targetFile: string; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): boolean; function CopyFilesWin(sourceDir, fileMask, targetDir: string; SearchSubDirs: boolean=true; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): boolean; function MoveFilesWin(sourceDir, fileMask, targetDir: string; SearchSubDirs: boolean=true; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): boolean; implementation function ChildPath(aPath: string): string; begin aPath:=ExpandFileName(ChompPathDelim(aPath)); Result:=Copy(aPath,aPath.LastIndexOf(DirectorySeparator)+2) end; function ParentPath(aPath: string): string; begin Result:=ExpandFileName(IncludeTrailingPathDelimiter(aPath) + '..'); end; function JoinPath(aDir, aFile: string): string; begin Result:=CleanAndExpandDirectory(aDir)+Trim(aFile); end; function CopyDirWin(sourceDir, targetDir: string; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): boolean; { copy directory tree, force directores, overwrite, and preserve attributes } { Result: 0=success, 1=sourceDir not exist, 2=err create targetDir, 3=err set attributes, 4=err copy dir, 5=error copy files } var sourceFile, targetFile: String; FileInfo: TSearchRec; begin Result:=false; sourceDir:=CleanAndExpandDirectory(sourceDir); targetDir:=CleanAndExpandDirectory(targetDir); if DirectoryExistsUTF8(sourceDir) then if (Flags=[cffOverwriteFile]) then DelDirWin(targetDir) else Exit; if not ForceDirectories(targetDir) then //will create empty dir Exit; if FindFirstUTF8(sourceDir+GetAllFilesMask,faAnyFile,FileInfo)=0 then begin repeat if (FileInfo.Name<>'.') and (FileInfo.Name<>'..') and (FileInfo.Name<>'') then begin sourceFile:=sourceDir+FileInfo.Name; targetFile:=targetDir+FileInfo.Name; if (FileInfo.Attr and faDirectory)>0 then begin if not CopyDirWin(sourceFile, targetFile, Flags, PreserveAttributes) then Exit; end else begin if not CopyFileWin(sourceFile, targetFile, Flags, PreserveAttributes) then Exit; end; end; until FindNextUTF8(FileInfo)<>0; end; { copy dir attributes - file attributes copied with CopyFileWin above } if PreserveAttributes then FileSetAttrUTF8(targetDir, FileGetAttrUTF8(sourceDir)); FindCloseUTF8(FileInfo); Exit(True); end; //CopyWinDirErr //CopyWinDirErrCheck //CopyWinDirErrCode //CopyWinDirEC //CopyWinDir //CopyWinDirErrChk function CopyDirWinEC(sourceDir, targetDir: string; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): integer; { copy directory tree, force directores, overwrite, and preserve attributes } { Result: 0=success, 1=sourceDir not exist, 2=err create targetDir, 3=err set attributes, 4=err copy dir, 5=error copy files } const { move to top to make global? do NOT move to fileutilwin.inc } ERR_SUCCESS=0; ERR_DIR_NOT_EXIST=1; ERR_CREATE_DIR=2; ERR_SET_ATTRIBUTES=3; ERR_COPY_DIR=4; ERR_COPY_FILE=5; var ErrCode: integer; FileInfo: TSearchRec; sourceFile, targetFile: String; begin sourceDir:=CleanAndExpandDirectory(sourceDir); targetDir:=CleanAndExpandDirectory(targetDir); { force overwrite, del dir } if DirectoryExistsUTF8(sourceDir) then if (Flags=[cffOverwriteFile]) then DelDirWin(targetDir) else Exit(ERR_DIR_NOT_EXIST); if not ForceDirectories(targetDir) then //will create empty dir Exit(ERR_CREATE_DIR); if FindFirstUTF8(sourceDir+GetAllFilesMask,faAnyFile,FileInfo)=0 then begin repeat if (FileInfo.Name<>'.') and (FileInfo.Name<>'..') and (FileInfo.Name<>'') then begin sourceFile:=sourceDir+FileInfo.Name; targetFile:=targetDir+FileInfo.Name; if (FileInfo.Attr and faDirectory)>0 then begin if CopyDirWinEC(sourceFile, targetFile, Flags, PreserveAttributes) >0 then Exit(ERR_COPY_DIR); end else begin if not CopyFileWin(sourceFile, targetFile, Flags, PreserveAttributes) then Exit(ERR_COPY_FILE); end; end; until FindNextUTF8(FileInfo)<>0; end; { copy dir attributes - file attributes copied with CopyFileWin above } if PreserveAttributes then FileSetAttrUTF8(targetDir, FileGetAttrUTF8(sourceDir)); FindCloseUTF8(FileInfo); Exit(ERR_SUCCESS); end; function CopyFileWin(sourceFile, targetFile: string; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): boolean; { copy a file and force dirs, Options: overwrite, preserve attributes } var attr, attrSource: integer; sourceDir, targetDir: string; sourceFileName, targetFileName: string; begin Result:=false; sourceFile:=CleanAndExpandFilename(sourceFile); targetFile:=CleanAndExpandFilename(targetFile); sourceFileName:=ExtractFileName(sourceFile); targetDir:=ExtractFileDir(targetFile); targetFile:=targetDir+DirectorySeparator+sourceFileName; if not ForceDirectories(targetDir) then exit; if PreserveAttributes then begin attrSource:=FileGetAttrUTF8(sourceFile); if (attrSource and faReadOnly)>0 then FileSetAttrUTF8(sourceFile, attrSource-faReadOnly) else if (attrSource and faHidden)>0 then FileSetAttrUTF8(sourceFile, attrSource-faHidden); end; if not FileUtil.CopyFile(sourceFile, targetFile, Flags) then exit; if PreserveAttributes then begin FileSetAttrUTF8(sourceFile, attrSource); FileSetAttrUTF8(targetFile, attrSource); end; Result:=true; end; function CopyFilesWin(sourceDir, fileMask, targetDir: string; SearchSubDirs: boolean=true; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): boolean; { copy files and force dirs, options: search sub dirs, overwrite, preserve attributes } var FileInfo: TSearchRec; sourceFile, targetFile: String; begin Result:=false; sourceDir:=CleanAndExpandDirectory(sourceDir); targetDir:=CleanAndExpandDirectory(targetDir); if FindFirstUTF8(sourceDir+fileMask,faAnyFile,FileInfo)=0 then begin repeat if (FileInfo.Name<>'.') and (FileInfo.Name<>'..') and (FileInfo.Name<>'') then begin { form source and target path } sourceFile:=sourceDir+FileInfo.Name; targetFile:=targetDir+FileInfo.Name; if (FileInfo.Attr and faDirectory)>0 then begin if SearchSubDirs then begin { create dir path - will copy empty dir } if not ForceDirectories(targetDir) then exit; if not CopyFilesWin(sourceFile, fileMask, targetFile) then exit; end; end else begin { if file is hidden or readonly then remove attributes } if (FileInfo.Attr and faReadOnly)>0 then FileSetAttrUTF8(targetFile, FileInfo.Attr-faReadOnly) else if (FileInfo.Attr and faHidden)>0 then FileSetAttrUTF8(targetFile, FileInfo.Attr-faHidden); { create dir if not exists and copy file with overwrite } if not ForceDirectories(targetDir) then exit; if not FileUtil.CopyFile(sourceFile, targetFile, Flags) then exit; { copy file attributes from source } if PreserveAttributes then FileSetAttrUTF8(targetFile, FileInfo.Attr); end; end; until FindNextUTF8(FileInfo)<>0; end; FindCloseUTF8(FileInfo); Result:=true; end; function DelDirWin(targetDir: string; OnlyChildren: boolean=False): boolean; { delete directory tree incl hidden and readonly files, OnlyChildren or parent dir } var FileInfo: TSearchRec; targetFile: String; begin targetDir:=CleanAndExpandDirectory(targetDir); Result:=true; if not DirectoryExistsUTF8(targetDir) then exit; Result:=false; if FindFirstUTF8(targetDir+GetAllFilesMask,faAnyFile,FileInfo)=0 then begin repeat if (FileInfo.Name<>'.') and (FileInfo.Name<>'..') and (FileInfo.Name<>'') then begin targetFile:=targetDir+FileInfo.Name; if (FileInfo.Attr and faDirectory)>0 then begin if not DelDirWin(targetFile, false) then exit; end else begin if (FileInfo.Attr and faReadOnly)>0 then FileSetAttrUTF8(targetFile, FileInfo.Attr-faReadOnly); if not DeleteFileUTF8(targetFile) then exit; end; end; until FindNextUTF8(FileInfo)<>0; end; FindCloseUTF8(FileInfo); if (not OnlyChildren) and (not RemoveDirUTF8(targetDir)) then exit; Result:=true; end; { TODO : TEST } function MoveDirWin(sourceDir, targetDir: string): boolean; { move directory tree, overwrite and preserve attributes } begin Result:=false; if CopyDirWinEC(sourceDir, targetDir) >0 then exit; if not DelDirWin(sourceDir, false) then exit; Result:=true; end; function MoveFilesWin(sourceDir, fileMask, targetDir: string; SearchSubDirs: boolean=true; Flags: TCopyFileFlags=[cffOverwriteFile]; PreserveAttributes: boolean=true): boolean; { move files and force dirs, options: search sub dirs, overwrite, preserve attributes } var FileInfo: TSearchRec; sourceFile, targetFile: String; begin Result:=false; sourceDir:=CleanAndExpandDirectory(sourceDir); targetDir:=CleanAndExpandDirectory(targetDir); if FindFirstUTF8(sourceDir+fileMask,faAnyFile,FileInfo)=0 then begin repeat if (FileInfo.Name<>'.') and (FileInfo.Name<>'..') and (FileInfo.Name<>'') then begin { form source and target path } sourceFile:=sourceDir+FileInfo.Name; targetFile:=targetDir+FileInfo.Name; if (FileInfo.Attr and faDirectory)>0 then begin if SearchSubDirs then begin { create dir path - will copy empty dir } if not ForceDirectories(targetDir) then exit; if not MoveFilesWin(sourceFile, fileMask, targetFile) then exit; end; end else begin { if file is hidden or readonly then remove attributes } if (FileInfo.Attr and faReadOnly)>0 then FileSetAttrUTF8(targetFile, FileInfo.Attr-faReadOnly) else if (FileInfo.Attr and faHidden)>0 then FileSetAttrUTF8(targetFile, FileInfo.Attr-faHidden); { create dir if not exists and copy file with overwrite } if not ForceDirectories(targetDir) then exit; if not FileUtil.CopyFile(sourceFile, targetFile, Flags) then exit; if not DeleteFileUTF8(sourceFile) then exit; { copy file attributes from source } if PreserveAttributes then FileSetAttrUTF8(targetFile, FileInfo.Attr); end; end; until FindNextUTF8(FileInfo)<>0; end; FindCloseUTF8(FileInfo); Result:=true; end; end.
unit fcShapeBtn; { // // Components : TfcShapeBtn // // Copyright (c) 1999 by Woll2Woll Software // Revision: History // 5/10/99 - PYW - Fixed Flat Style painting bug in High Color mode. // } interface {$i fcIfDef.pas} uses Windows, Messages, Classes, Controls, Forms, Graphics, StdCtrls, CommCtrl, Buttons, Dialogs, Math, Consts, SysUtils, fcCommon, fcText, fcButton, fcImgBtn, fcEvaluator, fcBitmap {$ifdef fcDelphi4up} ,ImgList, ActnList {$endif}; const DEFUNUSECOLOR = clRed; DEFUNUSECOLOR2 = clBlue; type TfcShapeOrientation = (soLeft, soRight, soUp, soDown); PfcPolyGonPoints = ^TFCPolyGonPoints; TfcPolyGonPoints = array[0..0] of TPoint; TfcButtonShape = (bsRoundRect, bsEllipse, bsTriangle, bsArrow, bsDiamond, bsRect, bsStar, bsTrapezoid, bsCustom); TfcCustomShapeBtn = class(TfcCustomImageBtn) private // Property Storage Variables FPointList: TStringList; FShape: TfcButtonShape; FOrientation: TfcShapeOrientation; FRoundRectBias: Integer; FRegionBitmap: TBitmap; // Propety Access Methods procedure SetShape(Value: TfcButtonShape); procedure SetOrientation(Value: TfcShapeOrientation); procedure SetPointList(Value: TStringList); procedure SetRoundRectBias(Value: Integer); function CorrectedColor: TColor; protected procedure WndProc(var Message: TMessage); override; function StoreRegionData: Boolean; override; function UnusableColor: TColor; procedure AssignTo(Dest: TPersistent); override; procedure Draw3dLines(Bitmap: TfcBitmap; PointList: array of TPoint; NumPoints: Integer; TransColor: TColor); procedure SetPointToOrientation(Points: PFCPolygonPoints; NumPoints: Integer; Orientation: TfcShapeOrientation; Size: TSize); function GetCustomPoints(var Points: PFCPolygonPoints; Size: TSize): Integer; function GetStarPoints(var Points: PFCPolygonPoints; Size: TSize): Integer; function GetPolygonPoints(var Points: PFCPolyGonPoints): Integer; // Overriden Methods function CreateRegion(DoImplementation: Boolean; Down: Boolean): HRgn; override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; function UseRegions: boolean; override; property RegionBitmap: TBitmap read FRegionBitmap write FRegionBitmap; public Patch: Variant; constructor Create(AOwner: TComponent); override; destructor Destroy; override; function IsMultipleRegions: Boolean; override; function RoundShape: Boolean; virtual; procedure GetDrawBitmap(DrawBitmap: TfcBitmap; ForRegion: Boolean; ShadeStyle: TfcShadeStyle; Down: Boolean); override; procedure SizeToDefault; override; property Orientation: TfcShapeOrientation read FOrientation write SetOrientation default soUp; property PointList: TStringList read FPointList write SetPointList; property RoundRectBias: Integer read FRoundRectBias write SetRoundRectBias default 0; property Shape: TfcButtonShape read FShape write SetShape default bsRect; end; TfcShapeBtn = class(TfcCustomShapeBtn) published {$ifdef fcDelphi4Up} property Action; property Anchors; property Constraints; {$endif} property AllowAllUp; property Cancel; property Caption; property Color; property Default; property DitherColor; property Down; property DragCursor; //3/31/99 - PYW - Exposed DragCursor, DragMode, DragKind properties. {$ifdef fcDelphi4Up} property DragKind; {$endif} property DragMode; property Font; property Enabled; property Glyph; property GroupIndex; property Kind; property Layout; property Margin; property ModalResult; property NumGlyphs; property Options; property Offsets; property Orientation; property ParentClipping; property ParentFont; property ParentShowHint; property PointList; property PopupMenu; property RoundRectBias; property ShadeColors; property ShadeStyle; property Shape; property ShowHint; {$ifdef fcDelphi4Up} property SmoothFont; {$endif} property Spacing; property Style; property TabOrder; property TabStop; property TextOptions; property Visible; property OnClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnSelChange; property OnStartDrag; end; implementation var GoodVideoDriverVar: Integer = -1; function GoodVideoDriver: Boolean; var TmpBm: TfcBitmap; TmpBitmap: TBitmap; begin if GoodVideoDriverVar = -1 then begin TmpBm := TfcBitmap.Create; TmpBm.LoadBlank(1, 1); TmpBm.Pixels[0, 0] := fcGetColor(RGB(192, 192, 192)); TmpBitmap := TBitmap.Create; TmpBitmap.Width := 1; TmpBitmap.Height := 1; TmpBitmap.Canvas.Draw(0, 0, TmpBm); with fcGetColor(TmpBitmap.Canvas.Pixels[0, 0]) do GoodVideoDriverVar := ord((r < 200) and (g < 200) and (b < 200)); TmpBitmap.Free; TmpBm.Free; end; result := GoodVideoDriverVar = 1; end; {$R-} procedure TfcCustomShapeBtn.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); exit; if (Button = mbLeft) and Enabled then begin if not Down then begin Down:=False; Invalidate; end; end; end; constructor TfcCustomShapeBtn.Create(AOwner: TComponent); begin inherited Create(AOwner); FPointList := TStringList.Create; FShape := bsRect; FOrientation := soUp; FRoundRectBias := 25; FRegionBitmap := TBitmap.Create; Color := clBtnFace; ShadeStyle := fbsHighlight; end; destructor TfcCustomShapeBtn.Destroy; begin FPointList.Free; FRegionBitmap.Free; inherited; end; procedure TfcCustomShapeBtn.SetOrientation(Value: TfcShapeOrientation); begin if FOrientation<> Value then begin FOrientation:= Value; Recreatewnd; end end; procedure TfcCustomShapeBtn.SetPointList(Value: TStringList); begin FPointList.Assign(Value); RecreateWnd; end; procedure TfcCustomShapeBtn.SetShape(Value: TfcButtonShape); begin if FShape <> Value then begin FShape := Value; Recreatewnd; // Ensures that the control's rectangle gets invalidated even in a transparent button group if (Parent <> nil) and fcIsClass(Parent.ClassType, 'TfcCustomButtonGroup') then fcParentInvalidate(Parent, True); end end; // Given a set of points will rotate the points to the given orientation. // Method assumes points passed in are oriented up procedure TfcCustomShapeBtn.SetPointToOrientation(Points: PFCPolygonPoints; NumPoints: Integer; Orientation: TfcShapeOrientation; Size: TSize); var i: Integer; RepeatInc, RepCount: Integer; begin RepCount := 0; case Orientation of soLeft: RepCount := 3; soRight: RepCount := 1; soUp: RepCount := 0; soDown: RepCount := 2; end; for RepeatInc := 1 to RepCount do for i := 0 to NumPoints - 1 do with Points[i] do Points[i] := Point(Size.cx - (y * Size.cx div Size.cy), (x * Size.cy div Size.cx)); end; procedure SetupPointList(var PointList: PfcPolygonPoints; NumPoints: Integer); begin PointList := AllocMem((NumPoints + 1) * SizeOf(TPoint)); FillChar(PointList^, (NumPoints + 1) * SizeOf(TPoint), 0); end; function GetNum(Num: Integer): Integer; begin result := Num; end; function TfcCustomShapeBtn.GetCustomPoints(var Points: PFCPolygonPoints; Size: TSize): Integer; var i: Integer; CurPoint, x, y: string; begin result := PointList.Count; if result <= 2 then begin result := 0; Exit; end; SetupPointList(Points, result); try for i := 0 to result - 1 do begin CurPoint := UpperCase(PointList[i]); if Pos(',', CurPoint) = 0 then raise EInvalidOperation.Create('Invalid Custom Points Format. X and Y ' + 'Coordinates must be separated by a comma and space.'); CurPoint := fcReplace(CurPoint, ',', ', '); CurPoint := fcReplace(CurPoint, ', ', ', '); CurPoint := fcReplace(CurPoint, 'WIDTH', InttoStr(Size.cx)); CurPoint := fcReplace(CurPoint, 'HEIGHT', InttoStr(Size.cy)); x := fcGetToken(CurPoint, ', ', 0); y := fcGetToken(CurPoint, ', ', 1); with Point(TfcEvaluator.Evaluate(x), TfcEvaluator.Evaluate(y)) do Points[i] := Point(x, y); end; except FreeMem(Points); Points := nil; FShape := bsRect; raise; end; end; function TfcCustomShapeBtn.GetStarPoints(var Points: PFCPolygonPoints; Size: TSize): Integer; var BottomOff: Integer; BaseTri, SideTri, HeightTri: Integer; Side: Integer; begin result := 10; SetupPointList(Points, result); Side := Trunc(Size.cy / Cos(DegToRad(18))); SideTri := Trunc(Side / (2 + 2 * Sin(DegToRad(18)))); BaseTri := Side - 2 * SideTri; HeightTri := Trunc(SideTri * Cos(DegToRad(18))); BottomOff := Trunc(Tan(DegToRad(18)) * Size.cy); Points[GetNum(0)] := Point(Size.cx div 2, 0); Points[GetNum(1)] := Point(Size.cx div 2 + BaseTri div 2, HeightTri); Points[GetNum(2)] := Point(Size.cx, Points[GetNum(1)].y); Points[GetNum(3)] := Point(Points[GetNum(1)].x + Trunc(Sin(DegToRad(18)) * BaseTri), Points[GetNum(1)].y + Trunc(Cos(DegToRad(18)) * BaseTri)); Points[GetNum(4)] := Point(Size.cx div 2 + BottomOff, Size.cy); Points[GetNum(5)] := Point(Size.cx div 2, Size.cy - Trunc(Sin(DegToRad(36)) * SideTri)); Points[GetNum(6)] := Point(Size.cx div 2 - BottomOff, Size.cy); Points[GetNum(7)] := Point(Size.cx - Points[GetNum(3)].x, Points[GetNum(3)].y); Points[GetNum(8)] := Point(0, Points[GetNum(2)].y); Points[GetNum(9)] := Point(Size.cx - Points[GetNum(1)].x, Points[GetNum(1)].y); end; function TfcCustomShapeBtn.GetPolygonPoints(var Points: PfcPolygonPoints): Integer; var Size: TSize; begin result := 0; Size := fcSize(Width - 1, Height - 1); case Shape of bsTriangle: begin result := 3; SetupPointList(Points, result); // Default Up, SetPointToOrientation adjusts for orientation Points[GetNum(0)] := Point(Size.cx div 2, 0); Points[GetNum(1)] := Point(Size.cx, Size.cy); Points[GetNum(2)] := Point(0, Size.cy); end; bsTrapezoid: begin result := 4; SetupPointList(Points, result); // Default Up, SetPointToOrientation adjusts for orientation Points[GetNum(0)] := Point(fcMin(Size.cy div 2, Size.cx div 2 div 2), 0); Points[GetNum(1)] := Point(Size.cx - fcMin(Size.cy div 2, Size.cx div 2 div 2), 0); Points[GetNum(2)] := Point(Size.cx, Size.cy); Points[GetNum(3)] := Point(0, Size.cy); end; bsArrow: begin result := 7; SetupPointList(Points, result); // Default Up, SetPointToOrientation adjusts for orientation Points[GetNum(0)] := Point(0, Size.cy div 3); Points[GetNum(1)] := Point(Size.cx div 2, 0); Points[GetNum(2)] := Point(Size.cx, Size.cy div 3); Points[GetNum(3)] := Point(Size.cx - Size.cx div 4, Size.cy div 3); Points[GetNum(4)] := Point(Size.cx - Size.cx div 4, Size.cy); Points[GetNum(5)] := Point(Size.cx div 4, Size.cy); Points[GetNum(6)] := Point(Size.cx div 4, Size.cy div 3); end; bsDiamond: begin result := 4; SetupPointList(Points, result); Points[GetNum(0)] := Point(Size.cx div 2, 0); Points[GetNum(1)] := Point(Size.cx, Size.cy div 2); Points[GetNum(2)] := Point(Size.cx div 2, Size.cy); Points[GetNum(3)] := Point(0, Size.cy div 2); end; bsRect: begin result := 4; SetupPointList(Points, result); Points[GetNum(0)] := Point(0, 0); Points[GetNum(1)] := Point(Size.cx, 0); Points[GetNum(2)] := Point(Size.cx, Size.cy); Points[GetNum(3)] := Point(0, Size.cy); end; bsStar: result := GetStarPoints(Points, Size); bsCustom: result := GetCustomPoints(Points, Size); end; if result > 0 then begin Points[result] := Points[0]; inc(result); SetPointToOrientation(Points, result, Orientation, Size); end; end; function TfcCustomShapeBtn.CreateRegion(DoImplementation: Boolean; Down: Boolean): HRgn; var DrawBitmap: TfcBitmap; begin result := inherited CreateRegion(False, Down); if not DoImplementation or (result <> 0) then Exit; DrawBitmap := TfcBitmap.Create; try GetDrawBitmap(DrawBitmap, True, ShadeStyle, Down); result := fcRegionFromBitmap(DrawBitmap, UnusableColor); finally SaveRegion(result, Down); DrawBitmap.Free; end; end; function TfcCustomShapeBtn.IsMultipleRegions: Boolean; begin result := False; end; function TfcCustomShapeBtn.StoreRegionData: Boolean; begin result := False; end; function TfcCustomShapeBtn.CorrectedColor: TColor; begin with fcGetColor(Color) do begin if not GoodVideoDriver then begin // 5/10/99 - PYW - Fixed Flat Style painting bug in High Color mode. if (r > 0) and (r mod 8 = 0) then dec(r); if (g > 0) and (g mod 8 = 0) then dec(g); if (b > 0) and (b mod 8 = 0) then dec(b); end; result := RGB(r, g, b); end; end; function TfcCustomShapeBtn.UnusableColor: TColor; begin if Color <> DEFUNUSECOLOR then result := DEFUNUSECOLOR else result := DEFUNUSECOLOR2; end; type TBooleanArray = array[0..0] of Boolean; PBooleanArray = ^TBooleanArray; procedure TfcCustomShapeBtn.AssignTo(Dest: TPersistent); begin if Dest is TfcCustomShapeBtn then with Dest as TfcCustomShapeBtn do begin Orientation := self.Orientation; PointList := self.PointList; RoundRectBias := self.RoundRectBias; Shape := self.Shape; end; inherited; end; procedure TfcCustomShapeBtn.Draw3dLines(Bitmap: TfcBitmap; PointList: array of TPoint; NumPoints: Integer; TransColor: TColor); function MidPoint(p1, p2: TPoint): TPoint; begin result := Point(p1.x + (p2.x - p1.x) div 2, p1.y + (p2.y - p1.y) div 2); end; var PolyRgn: HRGN; i: Integer; Difference: TSize; OutsideColor, InsideColor: TColor; Highlights: PBooleanArray; Offsets: PfcPolygonPoints; Focused: Integer; ACanvas: TCanvas; begin ACanvas := Bitmap.Canvas; if RoundShape then begin // fcOffsetBitmap(Bitmap, TransColor, Point(1, 1)); inherited Draw3dLines(Bitmap, Bitmap, TransColor, Down); // fcOffsetBitmap(Bitmap, TransColor, Point(-1, -1)); Exit; end; PolyRgn := CreatePolygonRgn(PointList, NumPoints, WINDING); if PolyRgn = 0 then Exit; Highlights := AllocMem(SizeOf(Boolean) * NumPoints); Offsets := AllocMem(SizeOf(TPoint) * NumPoints); try for i := 0 to NumPoints - 2 do begin Highlights[i] := False; Difference := fcSize(Abs(PointList[i + 1].x - PointList[i].x), Abs(PointList[i + 1].y - PointList[i].y)); with MidPoint(PointList[i], PointList[i + 1]) do if (Difference.cx > Difference.cy) then begin if PtInRegion(PolyRgn, x, y + 1) then begin Highlights[i] := True; Offsets[i] := Point(0, 1); end else Offsets[i] := Point(0, -1); end else begin if PtInRegion(PolyRgn, x + 1, y) then begin Highlights[i] := True; Offsets[i] := Point(1, 0); end else Offsets[i] := Point(-1, 0); end; if (Difference.cx = 0) then begin Offsets[i] := Point(Offsets[i].x, -1); if PtInRegion(PolyRgn, PointList[i].x, fcMax(PointList[i].y, PointList[i + 1].y) + 1) then Offsets[i].y := 1; end else if (Difference.cy = 0) then begin Offsets[i] := Point(-1, Offsets[i].y); if PtInRegion(PolyRgn, fcMax(PointList[i].x, PointList[i + 1].x), PointList[i].y) then Offsets[i].x := 1; end; end; if self.Focused or Default then Focused := 1 else Focused := 0; for i := 0 to NumPoints - 2 do begin if Highlights[i] xor Down then InsideColor := ColorToRGB(ShadeColors.Btn3dLight) else InsideColor := ColorToRGB(ShadeColors.BtnShadow); ACanvas.Pen.Color := InsideColor; ACanvas.PolyLine([ Point(PointList[i].x + Offsets[i].x * (1 + Focused), PointList[i].y + Offsets[i].y * (1 + Focused)), Point(PointList[i + 1].x + Offsets[i].x * (1 + Focused), PointList[i + 1].y + Offsets[i].y * (1 + Focused)) ]); end; for i := 0 to NumPoints - 2 do begin if Highlights[i] xor Down then OutsideColor := ColorToRGB(ShadeColors.BtnHighlight) else OutsideColor := ColorToRGB(ShadeColors.BtnBlack); ACanvas.Pen.Color := OutsideColor; ACanvas.Polyline([ Point(PointList[i].x + Offsets[i].x * Focused, PointList[i].y + Offsets[i].y * Focused), Point(PointList[i + 1].x + Offsets[i].x * Focused, PointList[i + 1].y + Offsets[i].y * Focused) ]); end; if self.Focused or Default then for i := 0 to NumPoints - 2 do begin ACanvas.Pen.Color := ShadeColors.BtnFocus; ACanvas.PolyLine([PointList[i], PointList[i + 1]]); end; finally DeleteObject(PolyRgn); FreeMem(Highlights); FreeMem(Offsets); end; end; function TfcCustomShapeBtn.RoundShape: Boolean; begin result := Shape in [bsRoundRect, bsEllipse]; end; procedure TfcCustomShapeBtn.GetDrawBitmap(DrawBitmap: TfcBitmap; ForRegion: Boolean; ShadeStyle: TfcShadeStyle; Down: Boolean); var PointList: PfcPolyGonPoints; NumPoints: Integer; // DitherBm: TBitmap; DoDraw3d: Boolean; OldBrush, ABrush: HBRUSH; begin DoDraw3d := True; case ShadeStyle of fbsFlat: DoDraw3d := (csDesigning in ComponentState) or MouseInControl(-1, -1, False) or Down; end; ABrush := 0; OldBrush := 0; DrawBitmap.SetSize(Width, Height); //3/16/99 - PYW - Raises canvas draw error when anchors cause width or height to be <=0 if (Width <=0) or (Height<=0) then exit; DrawBitmap.Canvas.Brush.Color := UnusableColor; DrawBitmap.Canvas.FillRect(Rect(0, 0, Width, Height)); DrawBitmap.Canvas.Brush.Color := CorrectedColor; if DoDraw3d then DrawBitmap.Canvas.Pen.Color := ColorToRGB(DitherColor) else DrawBitmap.Canvas.Pen.Color := DrawBitmap.Canvas.Brush.Color; if Down and (DitherColor <> clNone) and (GroupIndex <> 0) then begin ABrush := fcGetDitherBrush; SetBkColor(DrawBitmap.Canvas.Handle, ColorToRGB(DitherColor)); SetTextColor(DrawBitmap.Canvas.Handle, ColorToRGB(Color)); OldBrush := SelectObject(DrawBitmap.Canvas.Handle, ABrush); end; try PointList := nil; if RoundShape then begin DrawBitmap.Canvas.Pen.Color := CorrectedColor; case Shape of bsRoundRect: DrawBitmap.Canvas.RoundRect( 0, 0, Width - 1, Height - 1, RoundRectBias, RoundRectBias); bsEllipse: DrawBitmap.Canvas.Ellipse( 0, 0, Width - 1, Height - 1); end; if not ForRegion and DoDraw3d then { 5/2/99 - RSW - Support flat for RoundShape } Draw3dLines(DrawBitmap, [Point(0, 0)], 0, UnusableColor); end else begin NumPoints := GetPolygonPoints(PointList); if PointList <> nil then Polygon(DrawBitmap.Canvas.Handle, PointList^, NumPoints); if not ForRegion and DoDraw3d and (PointList <> nil) then Draw3dLines(DrawBitmap, Slice(PointList^, NumPoints), NumPoints, UnusableColor); end; if OldBrush <> 0 then SelectObject(DrawBitmap.Canvas.Handle, OldBrush); if ABrush <> 0 then DeleteObject(ABrush); finally if not RoundShape then FreeMem(PointList); end; end; procedure TfcCustomShapeBtn.SizeToDefault; begin if Width > Height then Height := Width else Width := Height; end; procedure TfcCustomShapeBtn.SetRoundRectBias(Value:Integer); begin if Value <> FRoundRectBias then begin FRoundRectBias := Value; RecreateWnd; end; end; function TfcCustomShapeBtn.UseRegions: boolean; begin result:= True; end; procedure TfcCustomShapeBtn.WndProc(var Message: TMessage); begin inherited; end; {$R+} end.
//////////////////////////////////////////////////////////////////////////////// // Trakce.pas: Interface to Trakce (e.g. XpressNET, LocoNET, Simulator). //////////////////////////////////////////////////////////////////////////////// { LICENSE: Copyright 2019-2020 Jan Horacek Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } { TTrakceIFace class allows its parent to load dll library with Trakce and simply use its functions. } unit Trakce; interface uses SysUtils, Classes, Windows, TrakceErrors, Generics.Collections; const // Highest-priority version last _TRK_API_SUPPORTED_VERSIONS : array[0..2] of Cardinal = ( $0001, $0100, $0101 // v0.1, v1.0, v1.1 ); _LOCO_DIR_FORWARD = false; _LOCO_DIR_BACKWARD = true; type TTrkLogLevel = ( llNo = 0, llErrors = 1, llWarnings = 2, llInfo = 3, llCommands = 4, llRawCommands = 5, llDebug = 6 ); TTrkStatus = ( tsUnknown = 0, tsOff = 1, tsOn = 2, tsProgramming = 3 ); TTrkLocoInfo = record addr: Word; direction: Boolean; step: Byte; maxSpeed: Byte; functions: Cardinal; class operator Equal(a, b: TTrkLocoInfo): Boolean; class operator NotEqual(a, b: TTrkLocoInfo): Boolean; end; TDllCommandCallbackFunc = procedure (Sender: TObject; Data: Pointer); stdcall; TDllCommandCallback = record callback: TDllCommandCallbackFunc; data: Pointer; end; TDllCb = TDllCommandCallback; TCommandCallbackFunc = procedure (Sender: TObject; Data: Pointer) of object; TCommandCallback = record callback: TCommandCallbackFunc; data: Pointer; other: ^TCommandCallback; end; TCb = TCommandCallback; PTCb = ^TCb; /////////////////////////////////////////////////////////////////////////// // Events called from library to TTrakceIFace: TTrkStdNotifyEvent = procedure (Sender: TObject; data: Pointer); stdcall; TTrkLogEvent = procedure (Sender: TObject; data: Pointer; logLevel: Integer; msg: PChar); stdcall; TTrkMsgEvent = procedure (Sender: TObject; msg: PChar); stdcall; TTrkStatusChangedEv = procedure (Sender: TObject; data: Pointer; trkStatus: Integer); stdcall; TTrkLocoEv = procedure (Sender: TObject; data: Pointer; addr: Word); stdcall; TDllLocoAcquiredCallback = procedure(Sender: TObject; LocoInfo: TTrkLocoInfo); stdcall; /////////////////////////////////////////////////////////////////////////// // Events called from TTrakceIFace to parent: TErrorEvent = procedure(Sender: TObject; errMsg: string) of object; TLogEvent = procedure (Sender: TObject; logLevel: TTrkLogLevel; msg: string) of object; TMsgEvent = procedure (Sender: TObject; msg: string) of object; TStatusChangedEv = procedure (Sender: TObject; trkStatus: TTrkStatus) of object; TLocoEv = procedure (Sender: TObject; addr: Word) of object; TLocoAcquiredCallback = procedure(Sender: TObject; LocoInfo: TTrkLocoInfo) of object; /////////////////////////////////////////////////////////////////////////// // Prototypes of functions called to library: TDllPGeneral = procedure(); stdcall; TDllFGeneral = function(): Integer; stdcall; TDllFCard = function(): Cardinal; stdcall; TDllBoolGetter = function(): Boolean; stdcall; TDllPCallback = procedure(ok: TDllCb; err: TDllCb); stdcall; TDllFileIOFunc = function(filename: PChar): Integer; stdcall; TDllApiVersionAsker = function(version: Cardinal): Boolean; stdcall; TDllApiVersionSetter = function(version: Cardinal): Integer; stdcall; TDllFSetTrackStatus = procedure(trkStatus: Cardinal; ok: TDllCb; err: TDllCb); stdcall; TDllFLocoAcquire = procedure(addr: Word; acquired: TDllLocoAcquiredCallback; err: TDllCb); stdcall; TDllFLocoRelease = procedure(addr: Word; ok: TDllCb); stdcall; TDllFLocoCallback = procedure(addr: Word; ok: TDllCb; err: TDllCb); stdcall; TDllFLocoSetSpeed = procedure(addr: Word; speed: Integer; direction: Boolean; ok: TDllCb; err: TDllCb); stdcall; TDllFLocoSetFunc = procedure(addr: Word; funcMask: Cardinal; funcState: Cardinal; ok: TDllCb; err: TDllCb); stdcall; TDllFPomWriteCv = procedure(addr: Word; cv: Word; value: Byte; ok: TDllCb; err: TDllCb); stdcall; TDllStdNotifyBind = procedure(event: TTrkStdNotifyEvent; data: Pointer); stdcall; TDllLogBind = procedure(event: TTrkLogEvent; data: Pointer); stdcall; TDllMsgBind = procedure(event: TTrkMsgEvent; data: Pointer); stdcall; TDllTrackStatusChangedBind = procedure(event: TTrkStatusChangedEv; data: Pointer); stdcall; TDllLocoEventBind = procedure(event: TTrkLocoEv; data: Pointer); stdcall; /////////////////////////////////////////////////////////////////////////// TTrakceIFace = class private const _Default_Cb : TCb = ( callback: nil; data: nil; ); private dllName: string; dllHandle: NativeUInt; mApiVersion: Cardinal; fOpening: Boolean; openErrors: string; // ------------------------------------------------------------------ // Functions called to library: // API dllFuncApiSupportsVersion : TDllApiVersionAsker; dllFuncApiSetVersion : TDllApiVersionSetter; dllFuncFeatures : TDllFCard; // load & save config dllFuncLoadConfig : TDllFileIOFunc; dllFuncSaveConfig : TDllFileIOFunc; // dialogs dllFuncShowConfigDialog : TDllPGeneral; // connect/disconnect dllFuncConnect : TDllFGeneral; dllFuncDisconnect : TDllFGeneral; dllFuncConnected : TDllBoolGetter; dllFuncTrackStatus : TDllFCard; dllFuncSetTrackStatus : TDllFSetTrackStatus; dllFuncLocoAcquire : TDllFLocoAcquire; dllFuncLocoRelease : TDllFLocoRelease; dllFuncEmergencyStop : TDllPCallback; dllFuncLocoEmergencyStop : TDllFLocoCallback; dllFuncLocoSetSpeed : TDllFLocoSetSpeed; dllFuncLocoSetFunc : TDllFLocoSetFunc; dllFuncPomWriteCv : TDllFPomWriteCv; // ------------------------------------------------------------------ // Events from TTrakceIFace eBeforeOpen : TNotifyEvent; eAfterOpen : TNotifyEvent; eBeforeClose : TNotifyEvent; eAfterClose : TNotifyEvent; eOnLog : TLogEvent; eOnOpenError : TMsgEvent; eOnTrackStatusChanged : TStatusChangedEv; eOnLocoStolen : TLocoEv; procedure Reset(); procedure PickApiVersion(); class function CallbackDll(const cb: TCb): TDllCb; class procedure CallbackDllReferOther(var dllCb: TDllCb; const other: TDllCb); class procedure CallbackDllReferEachOther(var first: TDllCb; var second: TDllCb); class procedure CallbacksDll(const ok: TCb; const err: TCb; var dllOk: TDllCb; var dllErr: TDllCb); public // list of unbound functions unbound: TList<string>; constructor Create(); destructor Destroy(); override; procedure LoadLib(path: string; configFn: string); procedure UnloadLib(); class function LogLevelToString(ll: TTrkLogLevel): string; //////////////////////////////////////////////////////////////////// // file I/O procedure LoadConfig(fn: string); procedure SaveConfig(fn: string); // dialogs procedure ShowConfigDialog(); function HasDialog(): Boolean; // device open/close procedure Connect(); procedure Disconnect(); function Connected(): Boolean; function ConnectedSafe(): Boolean; function TrackStatus(): TTrkStatus; function TrackStatusSafe(): TTrkStatus; procedure SetTrackStatus(status: TTrkStatus; ok: TCb; err: TCb); procedure EmergencyStop(); overload; procedure EmergencyStop(ok: TCb; err: TCb); overload; procedure LocoAcquire(addr: Word; callback: TLocoAcquiredCallback; err: TCb); procedure LocoRelease(addr: Word; ok: TCb); procedure LocoSetSpeed(addr: Word; speed: Integer; direction: Boolean; ok: TCb; err: TCb); procedure LocoSetFunc(addr: Word; funcMask: Cardinal; funcState: Cardinal; ok: TCb; err: TCb); procedure LocoSetSingleFunc(addr: Word; func: Integer; funcState: Cardinal; ok: TCb; err: TCb); procedure LocoEmergencyStop(addr: Word; ok: TCb; err: TCb); procedure PomWriteCv(addr: Word; cv: Word; value: Byte; ok: TCb; err: TCb); function apiVersionStr(): string; class function IsApiVersionSupport(version: Cardinal): Boolean; class function Callback(callback: TCommandCallbackFunc = nil; data: Pointer = nil): TCommandCallback; class procedure Callbacks(const ok: TCb; const err: TCb; var pOk: PTCb; var pErr: PTCb); property BeforeOpen: TNotifyEvent read eBeforeOpen write eBeforeOpen; property AfterOpen: TNotifyEvent read eAfterOpen write eAfterOpen; property BeforeClose: TNotifyEvent read eBeforeClose write eBeforeClose; property AfterClose: TNotifyEvent read eAfterClose write eAfterClose; property OnOpenError: TMsgEvent read eOnOpenError write eOnOpenError; property OnLog: TLogEvent read eOnLog write eOnLog; property OnTrackStatusChanged: TStatusChangedEv read eOnTrackStatusChanged write eOnTrackStatusChanged; property OnLocoStolen: TLocoEv read eOnLocoStolen write eOnLocoStolen; property Lib: string read dllName; property apiVersion: Cardinal read mApiVersion; property opening: Boolean read fOpening write fOpening; end; var acquiredCallbacks: TDictionary<Word, TLocoAcquiredCallback>; implementation //////////////////////////////////////////////////////////////////////////////// function GetLastOsError(_ErrCode: integer; out _Error: string; const _Format: string = ''): DWORD; overload; var s: string; begin Result := _ErrCode; if Result <> ERROR_SUCCESS then s := SysErrorMessage(Result) else s := ('unknown OS error'); if _Format <> '' then try _Error := Format(_Format, [Result, s]) except _Error := s; end else _Error := s; end; function GetLastOsError(out _Error: string; const _Format: string = ''): DWORD; overload; begin Result := GetLastOsError(GetLastError, _Error, _Format); end; //////////////////////////////////////////////////////////////////////////////// constructor TTrakceIFace.Create(); begin inherited; Self.unbound := TList<string>.Create(); Self.Reset(); end; destructor TTrakceIFace.Destroy(); begin if (Self.dllHandle <> 0) then Self.UnloadLib(); Self.unbound.Free(); inherited; end; //////////////////////////////////////////////////////////////////////////////// procedure TTrakceIFace.Reset(); begin Self.dllHandle := 0; Self.mApiVersion := _TRK_API_SUPPORTED_VERSIONS[High(_TRK_API_SUPPORTED_VERSIONS)]; Self.fOpening := false; dllFuncApiSupportsVersion := nil; dllFuncApiSetVersion := nil; dllFuncFeatures := nil; dllFuncLoadConfig := nil; dllFuncSaveConfig := nil; dllFuncShowConfigDialog := nil; dllFuncConnect := nil; dllFuncDisconnect := nil; dllFuncConnected := nil; dllFuncTrackStatus := nil; dllFuncSetTrackStatus := nil; dllFuncLocoAcquire := nil; dllFuncLocoRelease := nil; dllFuncEmergencyStop := nil; dllFuncLocoEmergencyStop := nil; dllFuncLocoSetSpeed := nil; dllFuncLocoSetFunc := nil; dllFuncPomWriteCv := nil; end; //////////////////////////////////////////////////////////////////////////////// // Events from dll library, these evetns must be declared as functions // (not as functions of objects) procedure dllBeforeOpen(Sender: TObject; data: Pointer); stdcall; begin try if (Assigned(TTrakceIFace(data).BeforeOpen)) then TTrakceIFace(data).BeforeOpen(TTrakceIFace(data)); except end; end; procedure dllAfterOpen(Sender: TObject; data: Pointer); stdcall; begin try TTrakceIFace(data).opening := false; if (Assigned(TTrakceIFace(data).AfterOpen)) then TTrakceIFace(data).AfterOpen(TTrakceIFace(data)); except end; end; procedure dllBeforeClose(Sender: TObject; data: Pointer); stdcall; begin try if (Assigned(TTrakceIFace(data).BeforeClose)) then TTrakceIFace(data).BeforeClose(TTrakceIFace(data)); except end; end; procedure dllAfterClose(Sender: TObject; data: Pointer); stdcall; begin try TTrakceIFace(data).opening := false; if (Assigned(TTrakceIFace(data).AfterClose)) then TTrakceIFace(data).AfterClose(TTrakceIFace(data)); except end; end; procedure dllOnLog(Sender: TObject; data: Pointer; logLevel: Integer; msg: PChar); stdcall; begin try if (Assigned(TTrakceIFace(data).OnLog)) then TTrakceIFace(data).OnLog(TTrakceIFace(data), TTrkLogLevel(logLevel), msg); except end; end; procedure dllOnOpenError(Sender: TObject; data: Pointer; msg: PChar); stdcall; begin try TTrakceIFace(data).opening := false; if (Assigned(TTrakceIFace(data).OnOpenError)) then TTrakceIFace(data).OnOpenError(TTrakceIFace(data), msg); except end; end; procedure dllOnTrackStatusChanged(Sender: TObject; data: Pointer; trkStatus: Integer); stdcall; begin try if (Assigned(TTrakceIFace(data).OnTrackStatusChanged)) then TTrakceIFace(data).OnTrackStatusChanged(TTrakceIFace(data), TTrkStatus(trkStatus)); except end; end; procedure dllOnLocoStolen(Sender: TObject; data: Pointer; addr: Word); stdcall; begin try if (Assigned(TTrakceIFace(data).OnLocoStolen)) then TTrakceIFace(data).OnLocoStolen(TTrakceIFace(data), addr); except end; end; procedure dllCallback(Sender: TObject; data: Pointer); stdcall; var pcb: ^TCb; cb: TCb; begin try pcb := data; cb := pcb^; if (cb.other <> nil) then FreeMem(cb.other); FreeMem(pcb); if (Assigned(cb.callback)) then cb.callback(Sender, cb.data); except end; end; procedure dllLocoAcquiredCallback(Sender: TObject; LocoInfo: TTrkLocoInfo); stdcall; var callback: TLocoAcquiredCallback; begin try if ((acquiredCallbacks.ContainsKey(LocoInfo.addr)) and (Assigned(acquiredCallbacks[LocoInfo.addr]))) then begin callback := acquiredCallbacks[LocoInfo.addr]; acquiredCallbacks.Remove(LocoInfo.addr); callback(Sender, LocoInfo); end; except end; end; //////////////////////////////////////////////////////////////////////////////// // Load dll library procedure TTrakceIFace.LoadLib(path: string; configFn: string); var dllFuncStdNotifyBind: TDllStdNotifyBind; dllFuncOnLogBind: TDllLogBind; dllFuncMsgBind: TDllMsgBind; dllFuncOnTrackStatusChanged: TDllTrackStatusChangedBind; dllLocoEventBind: TDllLocoEventBind; errorCode: dword; errorStr: string; begin Self.unbound.Clear(); if (dllHandle <> 0) then Self.UnloadLib(); dllName := path; dllHandle := LoadLibrary(PChar(dllName)); if (dllHandle = 0) then begin errorCode := GetLastOsError(errorStr); raise ETrkCannotLoadLib.Create('Cannot load library: error '+IntToStr(errorCode)+': '+errorStr+'!'); end; // library API version dllFuncApiSupportsVersion := TDllApiVersionAsker(GetProcAddress(dllHandle, 'apiSupportsVersion')); dllFuncApiSetVersion := TDllApiVersionSetter(GetProcAddress(dllHandle, 'apiSetVersion')); if ((not Assigned(dllFuncApiSupportsVersion)) or (not Assigned(dllFuncApiSetVersion))) then begin Self.UnloadLib(); raise ETrkUnsupportedApiVersion.Create('Library does not implement version getters!'); end; try Self.PickApiVersion(); // will pick right version or raise exception except Self.UnloadLib(); raise; end; // one of the supported versions is surely picked dllFuncLoadConfig := TDllFileIOFunc(GetProcAddress(dllHandle, 'loadConfig')); if (not Assigned(dllFuncLoadConfig)) then unbound.Add('loadConfig'); dllFuncSaveConfig := TDllFileIOFunc(GetProcAddress(dllHandle, 'saveConfig')); if (not Assigned(dllFuncSaveConfig)) then unbound.Add('saveConfig'); // dialogs dllFuncShowConfigDialog := TDllPGeneral(GetProcAddress(dllHandle, 'showConfigDialog')); // connect/disconnect dllFuncConnect := TDllFGeneral(GetProcAddress(dllHandle, 'connect')); if (not Assigned(dllFuncConnect)) then unbound.Add('connect'); dllFuncDisconnect := TDllFGeneral(GetProcAddress(dllHandle, 'disconnect')); if (not Assigned(dllFuncDisconnect)) then unbound.Add('disconnect'); dllFuncConnected := TDllBoolGetter(GetProcAddress(dllHandle, 'connected')); if (not Assigned(dllFuncConnected)) then unbound.Add('connected'); // track status getting & setting dllFuncTrackStatus := TDllFCard(GetProcAddress(dllHandle, 'trackStatus')); if (not Assigned(dllFuncTrackStatus)) then unbound.Add('trackStatus'); dllFuncSetTrackStatus := TDllFSetTrackStatus(GetProcAddress(dllHandle, 'setTrackStatus')); if (not Assigned(dllFuncSetTrackStatus)) then unbound.Add('setTrackStatus'); // loco acquire/release dllFuncLocoAcquire := TDllFLocoAcquire(GetProcAddress(dllHandle, 'locoAcquire')); if (not Assigned(dllFuncLocoAcquire)) then unbound.Add('locoAcquire'); dllFuncLocoRelease := TDllFLocoRelease(GetProcAddress(dllHandle, 'locoRelease')); if (not Assigned(dllFuncLocoRelease)) then unbound.Add('locoRelease'); // loco dllFuncEmergencyStop := TDllPCallback(GetProcAddress(dllHandle, 'emergencyStop')); if (not Assigned(dllFuncEmergencyStop)) then unbound.Add('emergencyStop'); dllFuncLocoEmergencyStop := TDllFLocoCallback(GetProcAddress(dllHandle, 'locoEmergencyStop')); if (not Assigned(dllFuncLocoEmergencyStop)) then unbound.Add('locoEmergencyStop'); dllFuncLocoSetSpeed := TDllFLocoSetSpeed(GetProcAddress(dllHandle, 'locoSetSpeed')); if (not Assigned(dllFuncLocoSetSpeed)) then unbound.Add('locoSetSpeed'); dllFuncLocoSetFunc := TDllFLocoSetFunc(GetProcAddress(dllHandle, 'locoSetFunc')); if (not Assigned(dllFuncLocoSetFunc)) then unbound.Add('locoSetFunc'); // pom dllFuncPomWriteCv := TDllFPomWriteCv(GetProcAddress(dllHandle, 'pomWriteCv')); if (not Assigned(dllFuncPomWriteCv)) then unbound.Add('pomWriteCv'); // events dllFuncStdNotifyBind := TDllStdNotifyBind(GetProcAddress(dllHandle, 'bindBeforeOpen')); if (Assigned(dllFuncStdNotifyBind)) then dllFuncStdNotifyBind(@dllBeforeOpen, self) else unbound.Add('bindBeforeOpen'); dllFuncStdNotifyBind := TDllStdNotifyBind(GetProcAddress(dllHandle, 'bindAfterOpen')); if (Assigned(dllFuncStdNotifyBind)) then dllFuncStdNotifyBind(@dllAfterOpen, self) else unbound.Add('bindAfterOpen'); dllFuncStdNotifyBind := TDllStdNotifyBind(GetProcAddress(dllHandle, 'bindBeforeClose')); if (Assigned(dllFuncStdNotifyBind)) then dllFuncStdNotifyBind(@dllBeforeClose, self) else unbound.Add('bindBeforeClose'); dllFuncStdNotifyBind := TDllStdNotifyBind(GetProcAddress(dllHandle, 'bindAfterClose')); if (Assigned(dllFuncStdNotifyBind)) then dllFuncStdNotifyBind(@dllAfterClose, self) else unbound.Add('bindAfterClose'); // other events dllFuncOnTrackStatusChanged := TDllTrackStatusChangedBind(GetProcAddress(dllHandle, 'bindOnTrackStatusChange')); if (Assigned(dllFuncOnTrackStatusChanged)) then dllFuncOnTrackStatusChanged(@dllOnTrackStatusChanged, self) else unbound.Add('bindOnTrackStatusChange'); dllFuncOnLogBind := TDllLogBind(GetProcAddress(dllHandle, 'bindOnLog')); if (Assigned(dllFuncOnLogBind)) then dllFuncOnLogBind(@dllOnLog, self) else unbound.Add('bindOnLog'); if (Self.apiVersion >= $0101) then begin dllFuncMsgBind := TDllMsgBind(GetProcAddress(dllHandle, 'bindOnOpenError')); if (Assigned(dllFuncMsgBind)) then dllFuncMsgBind(@dllOnOpenError, self) else unbound.Add('bindOnOpenError'); end; dllLocoEventBind := TDllLocoEventBind(GetProcAddress(dllHandle, 'bindOnLocoStolen')); if (Assigned(dllLocoEventBind)) then dllLocoEventBind(@dllOnLocoStolen, self) else unbound.Add('bindOnLocoStolen'); if (Assigned(dllFuncLoadConfig)) then Self.LoadConfig(configFn); end; procedure TTrakceIFace.UnloadLib(); begin if (Self.dllHandle = 0) then raise ETrkNoLibLoaded.Create('No library loaded, cannot unload!'); FreeLibrary(Self.dllHandle); Self.Reset(); end; //////////////////////////////////////////////////////////////////////////////// // Parent should call these methods: //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // file I/O procedure TTrakceIFace.LoadConfig(fn: string); var res: Integer; begin if (not Assigned(dllFuncLoadConfig)) then raise ETrkFuncNotAssigned.Create('loadConfig not assigned'); res := dllFuncLoadConfig(PChar(fn)); if (res = TRK_FILE_CANNOT_ACCESS) then raise ETrkCannotAccessFile.Create('Cannot read file '+fn+'!') else if (res = TRK_FILE_DEVICE_OPENED) then raise ETrkDeviceOpened.Create('Cannot reload config, device opened!') else if (res <> 0) then raise ETrkGeneralException.Create(); end; procedure TTrakceIFace.SaveConfig(fn: string); var res: Integer; begin if (not Assigned(dllFuncSaveConfig)) then raise ETrkFuncNotAssigned.Create('saveConfig not assigned'); res := dllFuncSaveConfig(PChar(fn)); if (res = TRK_FILE_CANNOT_ACCESS) then raise ETrkCannotAccessFile.Create('Cannot write to file '+fn+'!') else if (res <> 0) then raise ETrkGeneralException.Create(); end; //////////////////////////////////////////////////////////////////////////////// // dialogs: procedure TTrakceIFace.ShowConfigDialog(); begin if (Assigned(dllFuncShowConfigDialog)) then dllFuncShowConfigDialog() else raise ETrkFuncNotAssigned.Create('showConfigDialog not assigned'); end; function TTrakceIFace.HasDialog(): Boolean; begin Result := Assigned(Self.dllFuncShowConfigDialog); end; //////////////////////////////////////////////////////////////////////////////// // open/close: procedure TTrakceIFace.Connect(); var res: Integer; begin if (not Assigned(dllFuncConnect)) then raise ETrkFuncNotAssigned.Create('connect not assigned'); Self.opening := true; Self.openErrors := ''; res := dllFuncConnect(); if (res = TRK_ALREADY_OPENNED) then raise ETrkAlreadyOpened.Create('Device already opened!') else if (res = TRK_CANNOT_OPEN_PORT) then raise ETrkCannotOpenPort.Create('Cannot open this port!') else if (res <> 0) then raise ETrkGeneralException.Create(); end; procedure TTrakceIFace.Disconnect(); var res: Integer; begin if (not Assigned(dllFuncDisconnect)) then raise ETrkFuncNotAssigned.Create('disconnect not assigned'); res := dllFuncDisconnect(); if (res = TRK_NOT_OPENED) then raise ETrkNotOpened.Create('Device not opened!') else if (res <> 0) then raise ETrkGeneralException.Create(); end; function TTrakceIFace.Connected(): Boolean; begin if (not Assigned(dllFuncConnected)) then raise ETrkFuncNotAssigned.Create('connected not assigned') else Result := dllFuncConnected(); end; function TTrakceIFace.ConnectedSafe(): Boolean; begin if (not Assigned(dllFuncConnected)) then Result := false else Result := dllFuncConnected(); end; //////////////////////////////////////////////////////////////////////////////// function TTrakceIFace.TrackStatus(): TTrkStatus; begin if (not Self.ConnectedSafe()) then Exit(TTrkStatus.tsUnknown); if (Assigned(dllFuncTrackStatus)) then Result := TTrkStatus(dllFuncTrackStatus()) else raise ETrkFuncNotAssigned.Create('trackStatus not assigned'); end; function TTrakceIFace.TrackStatusSafe(): TTrkStatus; begin if (not Self.ConnectedSafe()) then Exit(TTrkStatus.tsUnknown); if (Assigned(dllFuncTrackStatus)) then Result := TTrkStatus(dllFuncTrackStatus()) else Result := TTrkStatus.tsUnknown; end; procedure TTrakceIFace.SetTrackStatus(status: TTrkStatus; ok: TCb; err: TCb); var dllOk, dllErr: TDllCb; begin if (not Assigned(dllFuncSetTrackStatus)) then raise ETrkFuncNotAssigned.Create('setTrackStatus not assigned'); CallbacksDll(ok, err, dllOk, dllErr); dllFuncSetTrackStatus(Integer(status), dllOk, dllErr); end; //////////////////////////////////////////////////////////////////////////////// procedure TTrakceIFace.EmergencyStop(ok: TCb; err: TCb); var dllOk, dllErr: TDllCb; begin if (not Assigned(dllFuncEmergencyStop)) then raise ETrkFuncNotAssigned.Create('emergencyStop not assigned'); CallbacksDll(ok, err, dllOk, dllErr); dllFuncEmergencyStop(dllOk, dllErr); end; procedure TTrakceIFace.EmergencyStop(); begin Self.EmergencyStop(Callback(), Callback()); end; //////////////////////////////////////////////////////////////////////////////// procedure TTrakceIFace.LocoAcquire(addr: Word; callback: TLocoAcquiredCallback; err: TCb); begin if (not Assigned(dllFuncLocoAcquire)) then raise ETrkFuncNotAssigned.Create('locoAcquire not assigned'); acquiredCallbacks.AddOrSetValue(addr, callback); dllFuncLocoAcquire(addr, dllLocoAcquiredCallback, CallbackDll(err)); end; procedure TTrakceIFace.LocoRelease(addr: Word; ok: TCb); begin if (not Assigned(dllFuncLocoRelease)) then raise ETrkFuncNotAssigned.Create('locoRelease not assigned'); dllFuncLocoRelease(addr, CallbackDll(ok)); end; //////////////////////////////////////////////////////////////////////////////// procedure TTrakceIFace.LocoEmergencyStop(addr: Word; ok: TCb; err: TCb); var dllOk, dllErr: TDllCb; begin if (not Assigned(dllFuncLocoEmergencyStop)) then raise ETrkFuncNotAssigned.Create('locoEmergencyStop not assigned'); CallbacksDll(ok, err, dllOk, dllErr); dllFuncLocoEmergencyStop(addr, dllOk, dllErr); end; procedure TTrakceIFace.LocoSetSpeed(addr: Word; speed: Integer; direction: Boolean; ok: TCb; err: TCb); var dllOk, dllErr: TDllCb; begin if (not Assigned(dllFuncLocoSetSpeed)) then raise ETrkFuncNotAssigned.Create('locoSetSpeed not assigned'); CallbacksDll(ok, err, dllOk, dllErr); dllFuncLocoSetSpeed(addr, speed, direction, dllOk, dllErr); end; procedure TTrakceIFace.LocoSetFunc(addr: Word; funcMask: Cardinal; funcState: Cardinal; ok: TCb; err: TCb); var dllOk, dllErr: TDllCb; begin if (not Assigned(dllFuncLocoSetFunc)) then raise ETrkFuncNotAssigned.Create('locoSetFunc not assigned'); CallbacksDll(ok, err, dllOk, dllErr); dllFuncLocoSetFunc(addr, funcMask, funcState, dllOk, dllErr); end; procedure TTrakceIFace.LocoSetSingleFunc(addr: Word; func: Integer; funcState: Cardinal; ok: TCb; err: TCb); var fMask: Cardinal; begin fMask := 1 shl func; Self.LocoSetFunc(addr, fMask, funcState, ok, err); end; //////////////////////////////////////////////////////////////////////////////// procedure TTrakceIFace.PomWriteCv(addr: Word; cv: Word; value: Byte; ok: TCb; err: TCb); var dllOk, dllErr: TDllCb; begin if (not Assigned(dllFuncPomWriteCv)) then raise ETrkFuncNotAssigned.Create('pomWriteCv not assigned'); CallbacksDll(ok, err, dllOk, dllErr); dllFuncPomWriteCv(addr, cv, value, dllOk, dllErr); end; //////////////////////////////////////////////////////////////////////////////// class function TTrakceIFace.IsApiVersionSupport(version: Cardinal): Boolean; var i: Integer; begin for i := Low(_TRK_API_SUPPORTED_VERSIONS) to High(_TRK_API_SUPPORTED_VERSIONS) do if (_TRK_API_SUPPORTED_VERSIONS[i] = version) then Exit(true); Result := false; end; //////////////////////////////////////////////////////////////////////////////// procedure TTrakceIFace.PickApiVersion(); var i: Integer; begin for i := High(_TRK_API_SUPPORTED_VERSIONS) downto Low(_TRK_API_SUPPORTED_VERSIONS) do begin if (Self.dllFuncApiSupportsVersion(_TRK_API_SUPPORTED_VERSIONS[i])) then begin Self.mApiVersion := _TRK_API_SUPPORTED_VERSIONS[i]; if (Self.dllFuncApiSetVersion(Self.mApiVersion) <> 0) then raise ETrkCannotLoadLib.Create('ApiSetVersion returned nonzero result!'); Exit(); end; end; raise ETrkUnsupportedApiVersion.Create('Library does not support any of the supported versions'); end; //////////////////////////////////////////////////////////////////////////////// class function TTrakceIFace.Callback(callback: TCommandCallbackFunc = nil; data: Pointer = nil): TCommandCallback; begin Result.callback := callback; Result.data := data; end; class procedure TTrakceIFace.Callbacks(const ok: TCb; const err: TCb; var pOk: PTCb; var pErr: PTCb); begin GetMem(pOk, sizeof(TCb)); GetMem(pErr, sizeof(TCb)); pOk^ := ok; pErr^ := err; pOk^.other := Pointer(pErr); pErr^.other := Pointer(pOk); end; //////////////////////////////////////////////////////////////////////////////// class function TTrakceIFace.LogLevelToString(ll: TTrkLogLevel): string; begin case (ll) of llNo: Result := 'No'; llErrors: Result := 'Err'; llWarnings: Result := 'Warn'; llInfo: Result := 'Info'; llCommands: Result := 'Cmd'; llRawCommands: Result := 'Raw'; llDebug: Result := 'Debug'; else Result := '?'; end; end; //////////////////////////////////////////////////////////////////////////////// class function TTrakceIFace.CallbackDll(const cb: TCb): TDllCb; var pcb: ^TCb; begin GetMem(pcb, sizeof(TCb)); pcb^.callback := cb.callback; pcb^.data := cb.data; pcb^.other := nil; Result.data := pcb; Result.callback := dllCallback; end; //////////////////////////////////////////////////////////////////////////////// class procedure TTrakceIFace.CallbackDllReferOther(var dllCb: TDllCb; const other: TDllCb); var pcb: ^TCb; begin pcb := dllCb.data; pcb^.other := other.data; end; class procedure TTrakceIFace.CallbackDllReferEachOther(var first: TDllCb; var second: TDllCb); begin TTrakceIFace.CallbackDllReferOther(first, second); TTrakceIFace.CallbackDllReferOther(second, first); end; class procedure TTrakceIFace.CallbacksDll(const ok: TCb; const err: TCb; var dllOk: TDllCb; var dllErr: TDllCb); begin dllOk := CallbackDll(ok); dllErr := CallbackDll(err); CallbackDllReferEachOther(dllOk, dllErr); end; //////////////////////////////////////////////////////////////////////////////// function TTrakceIFace.apiVersionStr(): string; begin Result := IntToStr((Self.apiVersion shr 8) and $FF) + '.' + IntToStr(Self.apiVersion and $FF); end; //////////////////////////////////////////////////////////////////////////////// class operator TTrkLocoInfo.Equal(a, b: TTrkLocoInfo): Boolean; begin Result := (a.addr = b.addr) and (a.direction = b.direction) and (a.step = b.step) and (a.maxSpeed = b.maxSpeed) and (a.functions = b.functions); end; class operator TTrkLocoInfo.NotEqual(a, b: TTrkLocoInfo): Boolean; begin Result := not (a = b); end; //////////////////////////////////////////////////////////////////////////////// initialization acquiredCallbacks := TDictionary<Word, TLocoAcquiredCallback>.Create(); finalization acquiredCallbacks.Free(); end.//unit
{$IfNDef DigitalSeparatorSupport_imp} // Модуль: "w:\common\components\gui\Garant\Everest\DigitalSeparatorSupport.imp.pas" // Стереотип: "Impurity" // Элемент модели: "DigitalSeparatorSupport" MUID: (4E5E029D03AD) // Имя типа: "_DigitalSeparatorSupport_" {$Define DigitalSeparatorSupport_imp} type TevCheckPointSeparator = ( ev_cpsNone {* ничего не делать (не ждать разделителя, не выливать) } , ev_cpsWait {* ждать разделителя. } , ev_cpsReady {* готовность к выливке } );//TevCheckPointSeparator _DigitalSeparatorSupport_ = class(_DigitalSeparatorSupport_Parent_) private f_WaitStyleD: TevCheckPointSeparator; f_DecimalOffset: Integer; private function HasDigitalSeparatorAlignment: Boolean; protected procedure ContinueCell; procedure CellStarted; {* Информируем о начале ячейки. } procedure CellFinished; {* Ячейка закончена. } procedure SetDigitalSeparatorParams(anAtomIndex: Integer; const aValue: Tk2Variant); function GetDigitalSeparatorOffset: Integer; end;//_DigitalSeparatorSupport_ {$Else DigitalSeparatorSupport_imp} {$IfNDef DigitalSeparatorSupport_imp_impl} {$Define DigitalSeparatorSupport_imp_impl} function _DigitalSeparatorSupport_.HasDigitalSeparatorAlignment: Boolean; //#UC START# *4E39244B0106_4E5E029D03AD_var* //#UC END# *4E39244B0106_4E5E029D03AD_var* begin //#UC START# *4E39244B0106_4E5E029D03AD_impl* Result := f_WaitStyleD = ev_cpsReady; //#UC END# *4E39244B0106_4E5E029D03AD_impl* end;//_DigitalSeparatorSupport_.HasDigitalSeparatorAlignment procedure _DigitalSeparatorSupport_.ContinueCell; //#UC START# *4E392479028C_4E5E029D03AD_var* //#UC END# *4E392479028C_4E5E029D03AD_var* begin //#UC START# *4E392479028C_4E5E029D03AD_impl* if f_WaitStyleD = ev_cpsReady then f_WaitStyleD := ev_cpsWait; //#UC END# *4E392479028C_4E5E029D03AD_impl* end;//_DigitalSeparatorSupport_.ContinueCell procedure _DigitalSeparatorSupport_.CellStarted; {* Информируем о начале ячейки. } //#UC START# *4E5E1C8D0090_4E5E029D03AD_var* //#UC END# *4E5E1C8D0090_4E5E029D03AD_var* begin //#UC START# *4E5E1C8D0090_4E5E029D03AD_impl* f_WaitStyleD := ev_cpsWait; //#UC END# *4E5E1C8D0090_4E5E029D03AD_impl* end;//_DigitalSeparatorSupport_.CellStarted procedure _DigitalSeparatorSupport_.CellFinished; {* Ячейка закончена. } //#UC START# *4E5E1CE40229_4E5E029D03AD_var* //#UC END# *4E5E1CE40229_4E5E029D03AD_var* begin //#UC START# *4E5E1CE40229_4E5E029D03AD_impl* f_WaitStyleD := ev_cpsNone; //#UC END# *4E5E1CE40229_4E5E029D03AD_impl* end;//_DigitalSeparatorSupport_.CellFinished procedure _DigitalSeparatorSupport_.SetDigitalSeparatorParams(anAtomIndex: Integer; const aValue: Tk2Variant); //#UC START# *4E5E22FB0348_4E5E029D03AD_var* //#UC END# *4E5E22FB0348_4E5E029D03AD_var* begin //#UC START# *4E5E22FB0348_4E5E029D03AD_impl* case anAtomIndex of k2_tiType: if (f_WaitStyleD = ev_cpsWait) and (aValue.AsInteger = Ord(l3_tssDecimal)) then f_WaitStyleD := ev_cpsReady else f_DecimalOffset := 0; k2_tiStart: f_DecimalOffset := aValue.AsInteger; end;//case anAtomIndex //#UC END# *4E5E22FB0348_4E5E029D03AD_impl* end;//_DigitalSeparatorSupport_.SetDigitalSeparatorParams function _DigitalSeparatorSupport_.GetDigitalSeparatorOffset: Integer; //#UC START# *4E5E26150131_4E5E029D03AD_var* //#UC END# *4E5E26150131_4E5E029D03AD_var* begin //#UC START# *4E5E26150131_4E5E029D03AD_impl* Result := f_DecimalOffset; //#UC END# *4E5E26150131_4E5E029D03AD_impl* end;//_DigitalSeparatorSupport_.GetDigitalSeparatorOffset {$EndIf DigitalSeparatorSupport_imp_impl} {$EndIf DigitalSeparatorSupport_imp}
unit afwTextControlPrim; // Модуль: "w:\common\components\gui\Garant\AFW\implementation\Visual\afwTextControlPrim.pas" // Стереотип: "GuiControl" // Элемент модели: "TafwTextControlPrim" MUID: (48BBD30803C5) {$Include w:\common\components\gui\Garant\AFW\afwDefine.inc} interface uses l3IntfUses , afwControl , afwInterfaces , l3Interfaces , Messages ; type TafwTextControlPrim = class(TafwControl) private f_CCaption: IafwCString; private procedure WMGetText(var Msg: TMessage); message WM_GetText; procedure WMGetTextLength(var Msg: TMessage); message WM_GetTextLength; procedure WMSetText(var Msg: TMessage); message WM_SetText; protected procedure pm_SetCCaption(const aValue: IafwCString); virtual; function pm_GetCaption: Tl3DString; procedure pm_SetCaption(aValue: Tl3DString); procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public property CCaption: IafwCString read f_CCaption write pm_SetCCaption; property Caption: Tl3DString read pm_GetCaption write pm_SetCaption; end;//TafwTextControlPrim implementation uses l3ImplUses , SysUtils , l3String , l3Base {$If NOT Defined(NoScripts)} , TtfwClassRef_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *48BBD30803C5impl_uses* //#UC END# *48BBD30803C5impl_uses* ; procedure TafwTextControlPrim.pm_SetCCaption(const aValue: IafwCString); //#UC START# *48BBF0D70131_48BBD30803C5set_var* //#UC END# *48BBF0D70131_48BBD30803C5set_var* begin //#UC START# *48BBF0D70131_48BBD30803C5set_impl* if not l3Same(f_CCaption, aValue) then begin f_CCaption := aValue; Perform(afw_CM_TEXTCHANGED, 0, 0); SendDockNotification(afw_CM_TEXTCHANGED, 0, Integer(aValue)); end;//not l3Same(f_CCaption, aValue) //#UC END# *48BBF0D70131_48BBD30803C5set_impl* end;//TafwTextControlPrim.pm_SetCCaption function TafwTextControlPrim.pm_GetCaption: Tl3DString; //#UC START# *48BBF34A018A_48BBD30803C5get_var* //#UC END# *48BBF34A018A_48BBD30803C5get_var* begin //#UC START# *48BBF34A018A_48BBD30803C5get_impl* Result := l3DStr(CCaption); //#UC END# *48BBF34A018A_48BBD30803C5get_impl* end;//TafwTextControlPrim.pm_GetCaption procedure TafwTextControlPrim.pm_SetCaption(aValue: Tl3DString); //#UC START# *48BBF34A018A_48BBD30803C5set_var* //#UC END# *48BBF34A018A_48BBD30803C5set_var* begin //#UC START# *48BBF34A018A_48BBD30803C5set_impl* CCaption := l3CStr(aValue); //#UC END# *48BBF34A018A_48BBD30803C5set_impl* end;//TafwTextControlPrim.pm_SetCaption procedure TafwTextControlPrim.WMGetText(var Msg: TMessage); //#UC START# *48BBE8CB00B3_48BBD30803C5_var* //#UC END# *48BBE8CB00B3_48BBD30803C5_var* begin //#UC START# *48BBE8CB00B3_48BBD30803C5_impl* with Msg do Result := StrLen(StrLCopy(PChar(LParam), PChar(l3Str(CCaption)), WParam - 1)); //#UC END# *48BBE8CB00B3_48BBD30803C5_impl* end;//TafwTextControlPrim.WMGetText procedure TafwTextControlPrim.WMGetTextLength(var Msg: TMessage); //#UC START# *48BBE8DD0385_48BBD30803C5_var* //#UC END# *48BBE8DD0385_48BBD30803C5_var* begin //#UC START# *48BBE8DD0385_48BBD30803C5_impl* Msg.Result := l3Len(CCaption); //#UC END# *48BBE8DD0385_48BBD30803C5_impl* end;//TafwTextControlPrim.WMGetTextLength procedure TafwTextControlPrim.WMSetText(var Msg: TMessage); //#UC START# *48BBE90600CF_48BBD30803C5_var* //#UC END# *48BBE90600CF_48BBD30803C5_var* begin //#UC START# *48BBE90600CF_48BBD30803C5_impl* if (Msg.lParam <> 0) then begin Msg.Result := Ord(true); CCaption := l3CStr(l3PCharLen(PChar(Msg.lParam))); end//Msg.lParam <> 0 else Msg.Result := Ord(false); //#UC END# *48BBE90600CF_48BBD30803C5_impl* end;//TafwTextControlPrim.WMSetText procedure TafwTextControlPrim.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_48BBD30803C5_var* //#UC END# *479731C50290_48BBD30803C5_var* begin //#UC START# *479731C50290_48BBD30803C5_impl* f_CCaption := nil; inherited; //#UC END# *479731C50290_48BBD30803C5_impl* end;//TafwTextControlPrim.Cleanup procedure TafwTextControlPrim.ClearFields; begin CCaption := nil; inherited; end;//TafwTextControlPrim.ClearFields initialization {$If NOT Defined(NoScripts)} TtfwClassRef.Register(TafwTextControlPrim); {* Регистрация TafwTextControlPrim } {$IfEnd} // NOT Defined(NoScripts) end.
unit RDOQueryServer; interface uses RDOInterfaces, RDOObjectServer, Logs; const tidConnRequestName = 'RDOCnntId'; type TRDOQueryServer = class( TInterfacedObject, IRDOQueryServer, IRDOLog ) public constructor Create( ObjectServer : TRDOObjectServer ); private fObjServer : TRDOObjectServer; fLogAgents : ILogAgents; fBusy : boolean; private // IRDOQueryServer function GetCommand( ObjectId : integer; QueryText : string; var ScanPos, ConnId : integer; var QueryStatus, RDOCallCnt : integer ) : string; function SetCommand( ObjectId : integer; QueryText : string; var ScanPos : integer; var QueryStatus, RDOCallCnt : integer ) : string; function CallCommand( ObjectId : integer; QueryText : string; var ScanPos : integer; var QueryStatus, RDOCallCnt : integer ) : string; function IdOfCommand( QueryText : string; var ScanPos : integer ) : string; private // IRDOLog function ExecQuery( const QueryText : string; ConnId : integer; var QueryStatus, RDOCallCnt : integer ) : string; procedure RegisterAgents( Agents : ILogAgents ); procedure ExecLogQuery(Query : string); function GetBusy : boolean; function GetStatus : integer; procedure SetBusy(value : boolean); public property Status : integer read GetStatus; private procedure LogMethod(Obj : TObject; Query : string); end; implementation uses Windows, SysUtils, RDOProtocol, RDOUtils, ErrorCodes, CompStringsParser; type TRDOCommand = ( cmSel, cmGet, cmSet, cmCall, cmIdOf, cmUnkCmd ); const RDOCommandNames : array [ TRDOCommand ] of string = ( SelObjCmd, GetPropCmd, SetPropCmd, CallMethCmd, IdOfCmd, '' ); function MapIdentToCommand( Ident : string ) : TRDOCommand; var CurCmd : TRDOCommand; LowCaseIdent : string; begin CurCmd := Low( CurCmd ); LowCaseIdent := LowerCase( Ident ); while ( CurCmd <> High( CurCmd ) ) and ( RDOCommandNames[ CurCmd ] <> LowCaseIdent ) do inc( CurCmd ); Result := CurCmd end; // TRDOQueryServer constructor TRDOQueryServer.Create( ObjectServer : TRDOObjectServer ); begin inherited Create; fObjServer := ObjectServer end; function TRDOQueryServer.ExecQuery; var CurToken : string; CurCmd : TRDOCommand; Error : boolean; QueryId : string; ScanPos : integer; QueryLen : integer; ObjectId : integer; ThreadPrio : integer; begin QueryStatus := 1; {1} // starting Error := false; ScanPos := 1; SkipSpaces( QueryText, ScanPos ); QueryId := ReadNumber( QueryText, ScanPos ); QueryLen := Length( QueryText ); SkipSpaces( QueryText, ScanPos ); CurToken := ReadIdent( QueryText, ScanPos ); ThreadPrio := UnknownPriority; if Length( CurToken ) = 1 then ThreadPrio := PriorityIdToPriority( CurToken[ 1 ] ); if ThreadPrio <> UnknownPriority then begin SetThreadPriority( GetCurrentThread, ThreadPrio ); SkipSpaces( QueryText, ScanPos ); CurToken := ReadIdent( QueryText, ScanPos ) end else SetThreadPriority( GetCurrentThread, THREAD_PRIORITY_HIGHEST ); // >> Priority changed by Cepero CurCmd := MapIdentToCommand( CurToken ); if CurCmd = cmSel then begin SkipSpaces( QueryText, ScanPos ); CurToken := ReadNumber( QueryText, ScanPos ); try ObjectId := StrToInt( CurToken ); except on EConvertError do begin Error := true; ObjectId := 0; Result := CreateErrorMessage( errMalformedQuery ); Logs.Log('Survival', DateTimeToStr(Now) + 'EConvertError in TRDOQueryServer.ExecQuery line (118)'); end else raise end; if not Error then begin Result := ''; try QueryStatus := 2; {2} repeat SkipSpaces( QueryText, ScanPos ); CurToken := ReadIdent( QueryText, ScanPos ); CurCmd := MapIdentToCommand( CurToken ); case CurCmd of cmGet: begin QueryStatus := 3; {3} Result := Result + GetCommand( ObjectId, QueryText, ScanPos, ConnId, QueryStatus, RDOCallCnt ); end; cmSet: begin QueryStatus := 4; {4} Result := Result + SetCommand( ObjectId, QueryText, ScanPos, QueryStatus, RDOCallCnt ); end; cmCall: begin QueryStatus := 5; {5} Result := Result + CallCommand( ObjectId, QueryText, ScanPos, QueryStatus, RDOCallCnt ) end; else begin Error := true; Result := CreateErrorMessage( errMalformedQuery ) end end; SkipSpaces( QueryText, ScanPos ); until EndOfStringText( ScanPos, QueryLen ) or ( QueryText[ ScanPos ] = QueryTerm ) or Error; QueryStatus := 6; {6} except Result := CreateErrorMessage( errMalformedQuery ); Logs.Log('Survival', DateTimeToStr(Now) + 'Malformed query in TRDOQueryServer.ExecQuery line (160) ' + QueryText); end end end else if CurCmd = cmIdOf then Result := IdOfCommand( QueryText, ScanPos ) else Result := CreateErrorMessage( errMalformedQuery ); if QueryId <> '' then Result := QueryId + Blank + Result + QueryTerm else Result := '' end; procedure TRDOQueryServer.RegisterAgents( Agents : ILogAgents ); begin fLogAgents := Agents; end; procedure TRDOQueryServer.ExecLogQuery(Query : string); var len : integer; p : integer; AgentId : string; ObjId : string; Agent : ILogAgent; Obj : TObject; aux1 : integer; aux2 : integer; begin try if fLogAgents <> nil then begin len := length(Query); p := 1; SkipSpaces(Query, p); AgentId := GetNextStringUpTo(Query, p, '#'); inc(p); ObjId := GetNextStringUpTo(Query, p, '#'); inc(p); Agent := fLogAgents.GetLogAgentById(AgentId); if Agent <> nil then begin Obj := Agent.GetObject(ObjId); if Obj <> nil then ExecQuery('0 sel ' + IntToStr(integer(Obj)) + copy(Query, p, len), 0, aux1, aux2); end; end; except //Logs.Log('Survival', DateTimeToStr(Now) + 'ExecLogQuery (213)'); end; end; function TRDOQueryServer.GetBusy : boolean; begin result := fBusy; end; function TRDOQueryServer.GetStatus : integer; begin result := 0; end; procedure TRDOQueryServer.SetBusy(value : boolean); begin fBusy := value; end; procedure TRDOQueryServer.LogMethod(Obj : TObject; Query : string); var aux : string; Agent : ILogAgent; begin try Agent := fLogAgents.GetLogAgentByClass(Obj.ClassType); if Agent <> nil then begin aux := Agent.GetId + '#' + Agent.GetLogId(Obj) + '# ' + Query; Agent.LogQuery(aux); end; except // >> end; end; function TRDOQueryServer.GetCommand( ObjectId : integer; QueryText : string; var ScanPos, ConnId : integer; var QueryStatus, RDOCallCnt : integer ) : string; var PropName : string; PropValue : variant; ErrorCode : integer; QueryLen : integer; PropValAsStr : string; IllegalVType : boolean; begin QueryStatus := 31; {31} Result := ''; QueryLen := Length( QueryText ); SkipSpaces( QueryText, ScanPos ); PropName := ReadIdent( QueryText, ScanPos ); if PropName = tidConnRequestName then begin PropValue := IntToStr(ConnId); ErrorCode := errNoError; end else PropValue := fObjServer.GetProperty( ObjectId, PropName, ErrorCode, QueryStatus, RDOCallCnt ); //##1 if ErrorCode <> errNoError then Result := CreateErrorMessage( ErrorCode ) + ' getting ' + PropName else begin PropValAsStr := GetStrFromVariant( PropValue, IllegalVType ); if not IllegalVType then Result := PropName + NameValueSep + LiteralDelim + PropValAsStr + LiteralDelim else Result := CreateErrorMessage( errIllegalPropValue ) + ' getting ' + PropName end; QueryStatus := 32; SkipSpaces( QueryText, ScanPos ); while not EndOfStringText( ScanPos, QueryLen ) and ( QueryText[ ScanPos ] = ParamDelim ) do begin inc( ScanPos ); SkipSpaces( QueryText, ScanPos ); QueryStatus := 33; PropName := ReadIdent( QueryText, ScanPos ); PropValue := fObjServer.GetProperty( ObjectId, PropName, ErrorCode, QueryStatus, RDOCallCnt ); QueryStatus := 34; if ErrorCode <> errNoError then Result := Result + ParamDelim + CreateErrorMessage( ErrorCode ) + ' getting ' + PropName else begin PropValAsStr := GetStrFromVariant( PropValue, IllegalVType ); if not IllegalVType then Result := Result + ParamDelim + PropName + NameValueSep + LiteralDelim + PropValAsStr + LiteralDelim else Result := Result + ParamDelim + CreateErrorMessage( ErrorCode ) + ' getting ' + PropName end; SkipSpaces( QueryText, ScanPos ) end; QueryStatus := 33; end; function TRDOQueryServer.SetCommand( ObjectId : integer; QueryText : string; var ScanPos : integer; var QueryStatus, RDOCallCnt : integer ) : string; var PropName : string; PropValAsStr : string; PropValue : variant; ErrorCode : integer; QueryLen : integer; SavePos : integer; begin QueryStatus := 41; Result := ''; QueryLen := Length( QueryText ); SkipSpaces( QueryText, ScanPos ); SavePos := ScanPos; PropName := ReadIdent( QueryText, ScanPos ); SkipSpaces( QueryText, ScanPos ); if (fLogAgents <> nil) and fLogAgents.LogableMethod(PropName) then LogMethod(TObject(ObjectId), 'set ' + copy(QueryText, SavePos, QueryLen - SavePos + 1)); if not EndOfStringText( ScanPos, QueryLen ) and ( QueryText[ ScanPos ] = NameValueSep ) then begin inc( ScanPos ); SkipSpaces( QueryText, ScanPos ); PropValAsStr := ReadLiteral( QueryText, ScanPos ); try PropValue := GetVariantFromStr( PropValAsStr ); fObjServer.SetProperty( ObjectId, PropName, PropValue, ErrorCode, QueryStatus, RDOCallCnt ); if ErrorCode <> errNoError then Result := CreateErrorMessage( ErrorCode ) + ' setting ' + PropName except Result := CreateErrorMessage( errIllegalPropValue ) + ' setting ' + PropName; Logs.Log('Survival', DateTimeToStr(Now) + 'Error in TRDOQueryServer.SetCommand (342)'); end; QueryStatus := 42; SkipSpaces( QueryText, ScanPos ); while not EndOfStringText( ScanPos, QueryLen ) and ( QueryText[ ScanPos ] = ParamDelim ) do begin inc( ScanPos ); SkipSpaces( QueryText, ScanPos ); PropName := ReadIdent( QueryText, ScanPos ); SkipSpaces( QueryText, ScanPos ); if not EndOfStringText( ScanPos, QueryLen ) and ( QueryText[ ScanPos ] = NameValueSep ) then begin inc( ScanPos ); SkipSpaces( QueryText, ScanPos ); PropValAsStr := ReadLiteral( QueryText, ScanPos ); try PropValue := GetVariantFromStr( PropValAsStr ); QueryStatus := 43; fObjServer.SetProperty( ObjectId, PropName, PropValue, ErrorCode, QueryStatus, RDOCallCnt ); QueryStatus := 44; if ErrorCode <> errNoError then if Result <> '' then Result := Result + ParamDelim + CreateErrorMessage( ErrorCode ) + ' setting ' + PropName else Result := CreateErrorMessage( ErrorCode ) + ' setting ' + PropName except if Result <> '' then Result := Result + ParamDelim + CreateErrorMessage( errIllegalPropValue ) + ' setting ' + PropName else Result := CreateErrorMessage( errIllegalPropValue ) + ' setting ' + PropName; Logs.Log('Survival', DateTimeToStr(Now) + 'Error in TRDOQueryServer.SetCommand (376)'); end; SkipSpaces( QueryText, ScanPos ) end else raise Exception.Create( '' ) end end else raise Exception.Create( '' ) end; function TRDOQueryServer.CallCommand( ObjectId : integer; QueryText : string; var ScanPos : integer; var QueryStatus, RDOCallCnt : integer ) : string; var MethodName : string; ParamValue : string; ResultType : string; ErrorCode : integer; ParamIdx : integer; Params : variant; Res : variant; Tmp : variant; IllegVType : boolean; VarAsStr : string; QueryLen : integer; BRefParIdx : integer; SavePos : integer; begin QueryStatus := 51; QueryLen := Length( QueryText ); SkipSpaces( QueryText, ScanPos ); SavePos := ScanPos; MethodName := ReadIdent( QueryText, ScanPos ); SkipSpaces( QueryText, ScanPos ); if (fLogAgents <> nil) and fLogAgents.LogableMethod(MethodName) then LogMethod(TObject(ObjectId), 'call ' + copy(QueryText, SavePos, QueryLen - ScanPos + 1)); ResultType := ReadLiteral( QueryText, ScanPos ); Res := UnAssigned; if ( Length( ResultType ) = 1 ) and ( ( ResultType[ 1 ] = VariantId ) or ( ResultType[ 1 ] = VoidId ) ) then begin if ResultType[ 1 ] = VariantId then TVarData( Res ).VType := varVariant; SkipSpaces( QueryText, ScanPos ); Params := UnAssigned; if not EndOfStringText( ScanPos, QueryLen ) then begin ParamValue := ReadLiteral( QueryText, ScanPos ); if ParamValue <> '' then begin ParamIdx := 1; Params := VarArrayCreate( [ 1, 1 ], varVariant ); Params[ ParamIdx ] := GetVariantFromStr( ParamValue ); if TVarData( Params[ ParamIdx ] ).VType = varVariant then begin TVarData( Tmp ).VType := varVariant; GetMem( TVarData( Tmp ).VPointer, SizeOf( variant ) ); Params[ ParamIdx ] := Tmp end; SkipSpaces( QueryText, ScanPos ); while not EndOfStringText( ScanPos, QueryLen ) and ( QueryText[ ScanPos ] = ParamDelim ) do begin inc( ScanPos ); SkipSpaces( QueryText, ScanPos ); if not EndOfStringText( ScanPos, QueryLen ) then begin SkipSpaces( QueryText, ScanPos ); ParamValue := ReadLiteral( QueryText, ScanPos ); inc( ParamIdx ); VarArrayRedim( Params, ParamIdx ); Params[ ParamIdx ] := GetVariantFromStr( ParamValue ); if TVarData( Params[ ParamIdx ] ).VType = varVariant then begin TVarData( Tmp ).VType := varVariant; GetMem( TVarData( Tmp ).VPointer, SizeOf( variant ) ); Params[ ParamIdx ] := Tmp end end else raise Exception.Create( '' ) end end end; QueryStatus := 52; fObjServer.CallMethod( ObjectId, MethodName, Params, Res, ErrorCode, QueryStatus, RDOCallCnt ); QueryStatus := 53; if ErrorCode = errNoError then begin if TVarData( Res ).VType <> varEmpty then begin VarAsStr := GetStrFromVariant( Res, IllegVType ); if not IllegVType then Result := ResultVarName + NameValueSep + LiteralDelim + VarAsStr + LiteralDelim else Result := CreateErrorMessage( errIllegalFunctionRes ) end else Result := ''; if TVarData( Params ).VType <> varEmpty then begin BRefParIdx := 1; for ParamIdx := 1 to VarArrayHighBound( Params, 1 ) do if VarType( Params[ ParamIdx ] ) and varTypeMask = varVariant then begin VarAsStr := GetStrFromVariant( PVariant( TVarData( Params[ ParamIdx ] ).VPointer )^, IllegVType ); FreeMem( TVarData( Params[ ParamIdx ] ).VPointer ); Result := Result + ByRefParName + IntToStr( BRefParIdx ) + NameValueSep + LiteralDelim + VarAsStr + LiteralDelim + Blank; inc( BRefParIdx ) end end end else Result := CreateErrorMessage( ErrorCode ); Params := NULL end else Result := CreateErrorMessage( errMalformedQuery ) end; function TRDOQueryServer.IdOfCommand( QueryText : string; var ScanPos : integer ) : string; var ObjectName : string; ObjectId : integer; ErrorCode : integer; QueryStatus : integer; begin SkipSpaces( QueryText, ScanPos ); ObjectName := ReadLiteral( QueryText, ScanPos ); ObjectId := fObjServer.GetIdOf( ObjectName, ErrorCode, QueryStatus ); if ErrorCode = errNoError then Result := ObjIdVarName + NameValueSep + LiteralDelim + IntToStr( ObjectId ) + LiteralDelim else Result := CreateErrorMessage( ErrorCode ) end; end.
unit fmuEJStatus; interface uses // VCL Windows, StdCtrls, Controls, Classes, Forms, Sysutils, ExtCtrls, Graphics, // This untPages, untUtil, untDriver; type { TfmEJStatus } TfmEJStatus = class(TPage) Memo: TMemo; btnGetEJCode1Status: TButton; btnGetEJCode2Status: TButton; btnEJVersion: TButton; btnGetEJSerialNumber: TButton; btnGetAll: TButton; procedure btnGetEJSerialNumberClick(Sender: TObject); procedure btnGetEJCode1StatusClick(Sender: TObject); procedure btnGetEJCode2StatusClick(Sender: TObject); procedure btnEJVersionClick(Sender: TObject); procedure btnGetAllClick(Sender: TObject); private procedure AddSeparator; procedure GetEKLZVersion; procedure GetEKLZCode1Status; procedure GetEKLZCode2Status; procedure GetEKLZSerialNumber; end; implementation {$R *.DFM} { TfmEJStatus } procedure TfmEJStatus.btnGetEJSerialNumberClick(Sender: TObject); begin EnableButtons(False); try Memo.Clear; Memo.Lines.Add(''); GetEKLZSerialNumber; AddSeparator; finally EnableButtons(True); end; end; procedure TfmEJStatus.btnGetEJCode1StatusClick(Sender: TObject); begin EnableButtons(False); try Memo.Clear; Memo.Lines.Add(''); GetEKLZCode1Status; AddSeparator; finally EnableButtons(True); end; end; procedure TfmEJStatus.btnGetEJCode2StatusClick(Sender: TObject); begin EnableButtons(False); try Memo.Clear; Memo.Lines.Add(''); GetEKLZCode2Status; AddSeparator; finally EnableButtons(True); end; end; procedure TfmEJStatus.btnEJVersionClick(Sender: TObject); begin EnableButtons(False); try Memo.Clear; Memo.Lines.Add(''); GetEKLZVersion; AddSeparator; finally EnableButtons(True); end; end; procedure TfmEJStatus.GetEKLZCode1Status; procedure EKLZFlagsToMemo; const DocType: array [0..3] of string = ('продажа', 'покупка', 'возврат продажи', 'возврат покупки'); BoolToStr: array [Boolean] of string = ('[нет]', '[да]'); var Flags: Integer; begin Flags := Driver.EKLZFlags; Memo.Lines.Add(' <T> Тип документа : ' + DocType[Flags and $3]); Memo.Lines.Add(' <I> Открыт архив : ' + BoolToStr[Flags and $4=$4]); Memo.Lines.Add(' <F> Выполнена активизация : ' + BoolToStr[Flags and $8=$8]); Memo.Lines.Add(' <W> Режим отчета : ' + BoolToStr[Flags and $10=$10]); Memo.Lines.Add(' <D> Открыт документ : ' + BoolToStr[Flags and $20=$20]); Memo.Lines.Add(' <S> Открыта смена : ' + BoolToStr[Flags and $40=$40]); Memo.Lines.Add(' <A> Ошибка устройства : ' + BoolToStr[Flags and $80=$80]); end; begin Check(Driver.GetEKLZCode1Report); AddSeparator; Memo.Lines.Add(' Дата : ' + DateToStr(Driver.LastKPKDate)); Memo.Lines.Add(' Время : ' + TimeToStr(Driver.LastKPKTime)); Memo.Lines.Add(' Итог : ' + CurrToStr(Driver.LastKPKDocumentResult)); Memo.Lines.Add(' Номер КПК : ' + IntToStr(Driver.LastKPKNumber)); Memo.Lines.Add(' Заводской номер ЭКЛЗ : ' + Driver.EKLZNumber); AddSeparator; Memo.Lines.Add(' Флаги (' + IntToStr(Driver.EKLZFlags)+')'); EKLZFlagsToMemo; // Прокручиваем Memo на начало Memo.SelStart := 0; Memo.SelLength := 0; end; procedure TfmEJStatus.GetEKLZCode2Status; begin Check(Driver.GetEKLZCode2Report); AddSeparator; Memo.Lines.Add(' Номер смены : ' + IntToStr(Driver.SessionNumber)); Memo.Lines.Add(' Продажа : ' + CurrToStr(Driver.Summ1)); Memo.Lines.Add(' Покупка : ' + CurrToStr(Driver.Summ2)); Memo.Lines.Add(' Возврат продаж : ' + CurrToStr(Driver.Summ3)); Memo.Lines.Add(' Возврат покупок : ' + CurrToStr(Driver.Summ4)); end; procedure TfmEJStatus.GetEKLZSerialNumber; begin Check(Driver.GetEKLZSerialNumber); AddSeparator; Memo.Lines.Add(' Заводской номер : ' + Driver.EKLZNumber); end; procedure TfmEJStatus.GetEKLZVersion; begin Check(Driver.GetEKLZVersion); AddSeparator; Memo.Lines.Add(' Версия : ' + Driver.EKLZVersion); end; procedure TfmEJStatus.btnGetAllClick(Sender: TObject); begin EnableButtons(False); try Memo.Clear; Memo.Lines.Add(''); GetEKLZCode1Status; GetEKLZCode2Status; GetEKLZVersion; GetEKLZSerialNumber; AddSeparator; // Прокручиваем Memo на начало Memo.SelStart := 0; Memo.SelLength := 0; finally EnableButtons(True); end; end; procedure TfmEJStatus.AddSeparator; begin Memo.Lines.Add(' ' + StringOfChar('-', 36)); end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2016 * } { * ------------------------------------------------------- * } { * documentation: RFC2104 * } { * ------------------------------------------------------- * } { *********************************************************** } unit tfHMAC; {$I TFL.inc} interface uses tfTypes, tfByteVectors; type PHMACAlg = ^THMACAlg; THMACAlg = record private const IPad = $36; OPad = $5C; private FVTable: Pointer; FRefCount: Integer; FHash: IHash; FKey: PByteVector; public class function Release(Inst: PHMACAlg): Integer; stdcall; static; class procedure Init(Inst: PHMACAlg; Key: Pointer; KeySize: Cardinal); {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class procedure Update(Inst: PHMACAlg; Data: Pointer; DataSize: Cardinal); {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class procedure Done(Inst: PHMACAlg; PDigest: Pointer); {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class procedure Burn(Inst: PHMACAlg); {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetDigestSize(Inst: PHMACAlg): Integer; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; // class function GetBlockSize(Inst: PHMACAlg): Integer; // {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function Duplicate(Inst: PHMACAlg; var DupInst: PHMACAlg): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function PBKDF2(Inst: PHMACAlg; Password: Pointer; PassLen: Cardinal; Salt: Pointer; SaltLen: Cardinal; Rounds, dkLen: Cardinal; var Key: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; end; function GetHMACAlgorithm(var Inst: PHMACAlg; const HashAlg: IHash): TF_RESULT; //function GetHMACAlgorithm(var Inst: PHMACAlg; HashAlg: IHashAlgorithm): TF_RESULT; implementation uses tfRecords; const HMACVTable: array[0..9] of Pointer = ( @TForgeInstance.QueryIntf, @TForgeInstance.Addref, @THMACAlg.Release, @THMACAlg.Init, @THMACAlg.Update, @THMACAlg.Done, @THMACAlg.Burn, @THMACAlg.GetDigestSize, // @THMACAlg.GetBlockSize, @THMACAlg.Duplicate, @THMACAlg.PBKDF2 ); function GetHMACAlgorithm(var Inst: PHMACAlg; const HashAlg: IHash): TF_RESULT; var P: PHMACAlg; BlockSize: Integer; begin BlockSize:= HashAlg.GetBlockSize; // protection against hashing algorithms which should not be used in HMAC if BlockSize = 0 then begin Result:= TF_E_INVALIDARG; Exit; end; try New(P); P^.FVTable:= @HMACVTable; P^.FRefCount:= 1; // interface assignment - refcount is incremented by the compiler P^.FHash:= HashAlg; // the bug is commented out - no need to increment refcount manually // HashAlg._AddRef; P^.FKey:= nil; Result:= ByteVectorAlloc(P^.FKey, BlockSize); if Result = TF_S_OK then begin if Inst <> nil then THMACAlg.Release(Inst); Inst:= P; end; except Result:= TF_E_OUTOFMEMORY; end; end; { THMACAlg } class function THMACAlg.Release(Inst: PHMACAlg): Integer; type TVTable = array[0..9] of Pointer; PVTable = ^TVTable; PPVTable = ^PVTable; TBurnProc = procedure(Inst: Pointer); {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} var BurnProc: Pointer; begin if Inst.FRefCount > 0 then begin Result:= tfDecrement(Inst.FRefCount); if Result = 0 then begin BurnProc:= PPVTable(Inst)^^[6]; // 6 is 'Burn' index TBurnProc(BurnProc)(Inst); if Inst.FHash <> nil then begin Inst.FHash._Release; end; if Inst.FKey <> nil then IBytes(Inst.FKey)._Release; FreeMem(Inst); end; end else Result:= Inst.FRefCount; end; class procedure THMACAlg.Init(Inst: PHMACAlg; Key: Pointer; KeySize: Cardinal); var BlockSize: Integer; I: Integer; InnerP: PByte; begin BlockSize:= Inst.FHash.GetBlockSize; // DigestSize:= Inst.FHash.GetDigestSize; FillChar(Inst.FKey.FData, BlockSize, 0); if Integer(KeySize) > BlockSize then begin Inst.FHash.Init; Inst.FHash.Update(Key, KeySize); Inst.FHash.Done(@Inst.FKey.FData); // KeySize:= DigestSize; end else begin Move(Key^, Inst.FKey.FData, KeySize); end; InnerP:= @Inst.FKey.FData; // OuterP:= @P^.FOuterKey.FData; // Move(InnerP^, OuterP^, BlockSize); for I:= 0 to BlockSize - 1 do begin InnerP^:= InnerP^ xor THMACAlg.IPad; // OuterP^:= OuterP^ xor OPad; Inc(InnerP); // Inc(OuterP); end; Inst.FHash.Init; Inst.FHash.Update(@Inst.FKey.FData, BlockSize); end; class procedure THMACAlg.Update(Inst: PHMACAlg; Data: Pointer; DataSize: Cardinal); begin Inst.FHash.Update(Data, DataSize); end; class procedure THMACAlg.Done(Inst: PHMACAlg; PDigest: Pointer); var BlockSize, DigestSize, I: Integer; P: PByte; begin BlockSize:= Inst.FHash.GetBlockSize; DigestSize:= Inst.FHash.GetDigestSize; Inst.FHash.Done(PDigest); Inst.FHash.Init; P:= @Inst.FKey.FData; for I:= 0 to BlockSize - 1 do begin P^:= P^ xor (IPad xor OPad); Inc(P); end; Inst.FHash.Update(@Inst.FKey.FData, BlockSize); Inst.FHash.Update(PDigest, DigestSize); Inst.FHash.Done(PDigest); end; class function THMACAlg.Duplicate(Inst: PHMACAlg; var DupInst: PHMACAlg): TF_RESULT; var P: PHMACAlg; // BlockSize, DigestSize: Integer; // I: Integer; // InnerP: PByte; begin try New(P); P^.FVTable:= @HMACVTable; P^.FRefCount:= 1; P^.FKey:= nil; Result:= TByteVector.CopyBytes(Inst.FKey, P^.FKey); if Result <> TF_S_OK then Exit; Inst.FHash.Duplicate(P^.FHash); if DupInst <> nil then THMACAlg.Release(DupInst); DupInst:= P; Result:= TF_S_OK; except Result:= TF_E_OUTOFMEMORY; end; end; { class function THMACAlg.GetBlockSize(Inst: PHMACAlg): Integer; begin Result:= 0; end; } class function THMACAlg.GetDigestSize(Inst: PHMACAlg): Integer; begin Result:= Inst.FHash.GetDigestSize; end; class procedure THMACAlg.Burn(Inst: PHMACAlg); begin FillChar(Inst.FKey.FData, Inst.FKey.FUsed, 0); Inst.FHash.Burn; end; const BigEndianOne = $01000000; function BigEndianInc(Value: UInt32): UInt32; inline; begin Result:= Value + BigEndianOne; if Result shr 24 = 0 then begin Result:= Result + $00010000; if Result shr 16 = 0 then begin Result:= Result + $00000100; if Result shr 8 = 0 then begin Result:= Result + $00000001; end; end; end; end; class function THMACAlg.PBKDF2(Inst: PHMACAlg; Password: Pointer; PassLen: Cardinal; Salt: Pointer; SaltLen, Rounds, dkLen: Cardinal; var Key: PByteVector): TF_RESULT; const MAX_DIGEST_SIZE = 128; // = 1024 bits var hLen: Cardinal; Digest: array[0 .. MAX_DIGEST_SIZE - 1] of Byte; Tmp: PByteVector; Count: UInt32; L, N, LRounds: Cardinal; PData, P1, P2: PByte; begin hLen:= Inst.FHash.GetDigestSize; if (hLen > MAX_DIGEST_SIZE) then begin Result:= TF_E_INVALIDARG; Exit; end; Tmp:= nil; Result:= ByteVectorAlloc(Tmp, dkLen); if Result <> TF_S_OK then Exit; FillChar(Tmp.FData, dkLen, 0); PData:= @Tmp.FData; N:= dkLen div hLen; Count:= BigEndianOne; while N > 0 do begin // process full hLen blocks LRounds:= Rounds; P1:= PData; if LRounds > 0 then begin Init(Inst, PassWord, PassLen); Update(Inst, Salt, SaltLen); Update(Inst, @Count, SizeOf(Count)); Done(Inst, @Digest); P2:= @Digest; L:= hLen shr 2; while L > 0 do begin PUInt32(P1)^:= PUInt32(P1)^ xor PUInt32(P2)^; Inc(PUInt32(P1)); Inc(PUInt32(P2)); Dec(L); end; L:= hLen and 3; while L > 0 do begin P1^:= P1^ xor P2^; Inc(P1); Inc(P2); Dec(L); end; Dec(LRounds); while LRounds > 0 do begin Init(Inst, PassWord, PassLen); Update(Inst, @Digest, hLen); Done(Inst, @Digest); P1:= PData; P2:= @Digest; L:= hLen shr 2; while L > 0 do begin PUInt32(P1)^:= PUInt32(P1)^ xor PUInt32(P2)^; Inc(PUInt32(P1)); Inc(PUInt32(P2)); Dec(L); end; L:= hLen and 3; while L > 0 do begin P1^:= P1^ xor P2^; Inc(P1); Inc(P2); Dec(L); end; Dec(LRounds); end; end; PData:= P1; Count:= BigEndianInc(Count); Dec(N); end; N:= dkLen mod hLen; if N > 0 then begin // process last incomplete block LRounds:= Rounds; if LRounds > 0 then begin Init(Inst, PassWord, PassLen); Update(Inst, Salt, SaltLen); Update(Inst, @Count, SizeOf(Count)); Done(Inst, @Digest); P1:= PData; P2:= @Digest; L:= N; while L > 0 do begin P1^:= P1^ xor P2^; Inc(P1); Inc(P2); Dec(L); end; Dec(LRounds); while LRounds > 0 do begin Init(Inst, PassWord, PassLen); Update(Inst, @Digest, hLen); Done(Inst, @Digest); P1:= PData; P2:= @Digest; L:= N; while L > 0 do begin P1^:= P1^ xor P2^; Inc(P1); Inc(P2); Dec(L); end; Dec(LRounds); end; end; end; tfFreeInstance(Key); //if Key <> nil then TtfRecord.Release(Key); Key:= Tmp; end; end.
unit DAO.CadastroEmpresa; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema, Model.CadastroEmpresa; type TCadastroEmpresaDAO = class private FConexao : TConexao; public constructor Create(); function GetID(): Integer; function Insert(aCadastros: TCadastroEmpresa): Boolean; function Update(aCadastros: TCadastroEmpresa): Boolean; function Delete(aCadastros: TCadastroEmpresa): Boolean; function EmpresaExiste(aCadastros: TCadastroEmpresa): Boolean; function Localizar(aParam: Array of variant): TFDQuery; end; const TABLENAME = 'cadastro_empresa'; implementation function TCadastroEmpresaDAO.Insert(aCadastros: TCadastroEmpresa): Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; aCadastros.ID := GetID(); sSQL := 'INSERT INTO ' + TABLENAME + '('+ 'ID_EMPRESA, NUM_CNPJ_MATRIZ, DES_TIPO_DOC, NOM_RAZAO_SOCIAL, NOM_FANTASIA, NUM_SUFRAMA, NUM_CRT, COD_CNAE, DOM_STATUS, ' + 'DES_LOG) ' + 'VALUES (' + ':pID_EMPRESA, :pNUM_CNPJ_MATRIZ, :pDES_TIPO_DOC, :pNOM_RAZAO_SOCIAL, :pNOM_FANTASIA, :pNUM_SUFRAMA, :pNUM_CRT, :pCOD_CNAE, ' + ':pDOM_STATUS, :pDES_LOG);'; FDQuery.ExecSQL(sSQL,[aCadastros.ID, aCadastros.CPFCNPJ, aCadastros.TipoDoc, aCadastros.Nome, aCadastros.Alias, aCadastros.SUFRAMA, aCadastros.CRT, aCadastros.CNAE, aCadastros.Status, aCadastros.Log]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroEmpresaDAO.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('WHERE ID_EMPRESA = :ID_EMPRESA'); FDQuery.ParamByName('ID_EMPRESA').AsInteger := aParam[1]; end; if aParam[0] = 'CNPJ' then begin FDQuery.SQL.Add('WHERE NUM_CNPJ_MATRIZ = :NUM_CNPJ_MATRIZ'); FDQuery.ParamByName('NUM_CNPJ_MATRIZ').AsString := aParam[1]; end; if aParam[0] = 'NOME' then begin FDQuery.SQL.Add('WHERE NOM_NOME_RAZAO LIKE :NOM_NOME_RAZAO'); FDQuery.ParamByName('NOM_NOME_RAZAO').AsString := aParam[1]; end; if aParam[0] = 'ALIAS' then begin FDQuery.SQL.Add('WHERE NOM_FANTASIA LIKE :NOM_FANTASIA'); FDQuery.ParamByName('NOM_FANTASIA').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open(); Result := FDQuery; end; function TCadastroEmpresaDAO.Update(aCadastros: TCadastroEmpresa): Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; sSQL := 'UPDATE ' + TABLENAME + ' SET ' + 'NUM_CNPJ_MATRIZ = :pNUM_CNPJ_MATRIZ, DES_TIPO_DOC = :pDES_TIPO_DOC, NOM_RAZAO_SOCIAL = :pNOM_RAZAO_SOCIAL, ' + 'NOM_FANTASIA = :pNOM_FANTASIA, NUM_SUFRAMA = :pNUM_SUFRAMA, NUM_CRT = :pNUM_CRT, COD_CNAE = :pCOD_CNAE, DOM_STATUS = :pDOM_STATUS, ' + 'DES_LOG = :pDES_LOG ' + 'WHERE ID_EMPRESA = :pID_EMPRESA;'; FDQuery.ExecSQL(sSQL,[aCadastros.CPFCNPJ, aCadastros.TipoDoc, aCadastros.Nome, aCadastros.Alias, aCadastros.SUFRAMA, aCadastros.CRT, aCadastros.CNAE, aCadastros.Status, aCadastros.Log, aCadastros.ID]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TCadastroEmpresaDAO.Create; begin FConexao := TConexao.Create; end; function TCadastroEmpresaDAO.Delete(aCadastros: TCadastroEmpresa): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where ID_EMPRESA = :pID_EMPRESA', [ACadastros.ID]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TCadastroEmpresaDAO.EmpresaExiste(aCadastros: TCadastroEmpresa): Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; sSQL := 'select * ' + TABLENAME + 'WHERE num_cnpj_matriz = :pnum_cnpj_matriz;'; FDQuery.ParamByName('pnum_cnpj_matriz').AsString := aCadastros.CPFCNPJ; FDQuery.Open; if FDQuery.IsEmpty then Exit; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroEmpresaDAO.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(ID_EMPRESA),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; end.
unit PE.Utils; interface // When writing padding use PADDINGX string instead of zeros. {$DEFINE WRITE_PADDING_STRING} uses System.Classes, System.SysUtils, PE.Common; function StreamRead(AStream: TStream; var Buf; Count: longint): boolean; inline; function StreamPeek(AStream: TStream; var Buf; Count: longint): boolean; inline; function StreamWrite(AStream: TStream; const Buf; Count: longint): boolean; inline; // Read 0-terminated 1-byte string. function StreamReadStringA(AStream: TStream; var S: string): boolean; // Read 0-terminated 2-byte string function StreamReadStringW(AStream: TStream; var S: string): boolean; // Write string and return number of bytes written. // If AlignAfter isn't 0 zero bytes will be written to align it up to AlignAfter value. function StreamWriteString(AStream: TStream; const S: string; Encoding: TEncoding; AlignAfter: integer = 0): uint32; // Write ANSI string and return number of bytes written. function StreamWriteStringA(AStream: TStream; const S: string; AlignAfter: integer = 0): uint32; const PATTERN_PADDINGX: array [0 .. 7] of AnsiChar = ('P', 'A', 'D', 'D', 'I', 'N', 'G', 'X'); // Write pattern to stream. If Pattern is nil or size of patter is 0 then // nulls are written (default). procedure WritePattern(AStream: TStream; Count: uint32; Pattern: Pointer = nil; PatternSize: integer = 0); function StreamSeek(AStream: TStream; Offset: TFileOffset): boolean; inline; function StreamSkip(AStream: TStream; Count: integer = 1): boolean; inline; // Seek from current position to keep alignment. function StreamSeekAlign(AStream: TStream; Align: integer): boolean; inline; // Try to seek Offset and insert padding if Offset < stream Size. procedure StreamSeekWithPadding(AStream: TStream; Offset: TFileOffset); function Min(const A, B: uint64): uint64; inline; overload; function Min(const A, B, C: uint64): uint64; inline; overload; function Max(const A, B: uint64): uint64; inline; function AlignUp(Value: uint64; Align: uint32): uint64; inline; function AlignDown(Value: uint64; Align: uint32): uint64; inline; function IsAlphaNumericString(const S: String): boolean; function CompareRVA(A, B: TRVA): integer; inline; function ReplaceSpecialSymobls(const source: string): string; implementation { Stream } function StreamRead(AStream: TStream; var Buf; Count: longint): boolean; begin Result := AStream.Read(Buf, Count) = Count; end; function StreamPeek(AStream: TStream; var Buf; Count: longint): boolean; inline; var Read: integer; begin Read := AStream.Read(Buf, Count); AStream.Seek(-Read, soFromCurrent); Result := Read = Count; end; function StreamWrite(AStream: TStream; const Buf; Count: longint): boolean; begin Result := AStream.Write(Buf, Count) = Count; end; function StreamReadStringA(AStream: TStream; var S: string): boolean; var C: byte; begin S := ''; while True do if AStream.Read(C, SizeOf(C)) <> SizeOf(C) then break else if (C = 0) then exit(True) else S := S + Char(C); exit(False); end; function StreamReadStringW(AStream: TStream; var S: string): boolean; var C: word; begin S := ''; while True do if AStream.Read(C, SizeOf(C)) <> SizeOf(C) then break else if (C = 0) then exit(True) else S := S + Char(C); exit(False); end; function StreamWriteString(AStream: TStream; const S: string; Encoding: TEncoding; AlignAfter: integer): uint32; var Bytes: TBytes; begin Bytes := Encoding.GetBytes(S); Result := AStream.Write(Bytes, Length(Bytes)); if AlignAfter <> 0 then begin // Number of bytes left to write to be aligned. AlignAfter := AlignAfter - (AStream.Size mod AlignAfter); WritePattern(AStream, AlignAfter, nil, 0); end; end; function StreamWriteStringA(AStream: TStream; const S: string; AlignAfter: integer): uint32; begin Result := StreamWriteString(AStream, S, TEncoding.ANSI, AlignAfter); end; procedure WritePattern(AStream: TStream; Count: uint32; Pattern: Pointer; PatternSize: integer); var p: pbyte; i: integer; begin if Count = 0 then exit; if Assigned(Pattern) and (PatternSize > 0) then begin p := GetMemory(Count); if PatternSize = 1 then FillChar(p^, Count, pbyte(Pattern)^) else begin for i := 0 to Count - 1 do p[i] := pbyte(Pattern)[i mod PatternSize]; end; end else begin p := AllocMem(Count); // filled with nulls end; try AStream.Write(p^, Count); finally FreeMem(p); end; end; function StreamSeek(AStream: TStream; Offset: TFileOffset): boolean; begin Result := AStream.Seek(Offset, TSeekOrigin.soBeginning) = Offset; end; function StreamSkip(AStream: TStream; Count: integer): boolean; inline; var Offset: TFileOffset; begin Offset := AStream.Position + Count; Result := AStream.Seek(Offset, TSeekOrigin.soBeginning) = Offset; end; function StreamSeekAlign(AStream: TStream; Align: integer): boolean; var m: integer; pos: TFileOffset; begin if Align in [0, 1] then exit(True); // don't need alignment pos := AStream.Position; m := pos mod Align; if m = 0 then exit(True); // already aligned inc(pos, Align - m); // next aligned position Result := AStream.Seek(pos, TSeekOrigin.soBeginning) = pos; end; procedure StreamSeekWithPadding(AStream: TStream; Offset: TFileOffset); begin if Offset <= AStream.Size then begin AStream.Seek(Offset, TSeekOrigin.soBeginning); exit; end; // Insert padding if need. AStream.Seek(AStream.Size, TSeekOrigin.soBeginning); WritePattern(AStream, Offset - AStream.Size, nil, 0); end; { Min / Max } function Min(const A, B: uint64): uint64; begin if A < B then exit(A) else exit(B); end; function Min(const A, B, C: uint64): uint64; begin Result := Min(Min(A, B), C); end; function Max(const A, B: uint64): uint64; begin if A > B then exit(A) else exit(B); end; { AlignUp } function AlignUp(Value: uint64; Align: uint32): uint64; var d, m: uint32; begin d := Value div Align; m := Value mod Align; if m = 0 then Result := Value else Result := (d + 1) * Align; end; function AlignDown(Value: uint64; Align: uint32): uint64; begin Result := (Value div Align) * Align; end; function IsAlphaNumericString(const S: String): boolean; const ALLOWED_CHARS = ['0' .. '9', 'A' .. 'Z', 'a' .. 'z']; var C: Char; begin for C in S do if not CharInSet(c, ALLOWED_CHARS) then exit(False); exit(True); end; function CompareRVA(A, B: TRVA): integer; begin if A > B then exit(1) else if A < B then exit(-1) else exit(0); end; function ReplaceSpecialSymobls(const source: string): string; begin Result := source. Replace(#10, '\n'). Replace(#13, '\r'); end; end.
unit ShutDown; interface type IShutDownTarget = interface function GetPriority : integer; procedure OnSuspend; procedure OnResume; procedure OnShutDown; end; procedure AttachTarget(const which : IShutDownTarget); procedure DetachTarget(const which : IShutDownTarget); function DoSuspend : integer; function DoResume : integer; procedure DoShutDown; implementation uses Classes; // Utils type TTargetList = class(TList) public destructor Destroy; override; public function Lock : integer; function Unlock : integer; protected function Add(const which : IShutDownTarget) : integer; function Remove(const which : IShutDownTarget) : integer; private fSorted : boolean; procedure Sort; procedure Suspend; procedure Resume; procedure Shutdown; end; var Targets : TTargetList = nil; function CompareTargets(Item1, Item2 : pointer) : integer; var Target1 : IShutDownTarget absolute Item1; Target2 : IShutDownTarget absolute Item2; begin Result := Target2.GetPriority - Target1.GetPriority; end; procedure FreeObject(var which); var aux : TObject; begin aux := TObject(which); TObject(which) := nil; aux.Free; end; // TTargetList destructor TTargetList.Destroy; begin ShutDown; inherited; end; function TTargetList.Lock : integer; begin Suspend; Result := 0; end; function TTargetList.Unlock : integer; begin Resume; Result := 0; end; function TTargetList.Add(const which : IShutDownTarget) : integer; begin which.OnSuspend; fSorted := (Count = 0); Result := inherited Add(pointer(which)); end; function TTargetList.Remove(const which : IShutDownTarget) : integer; var idx : integer; begin idx := IndexOf(pointer(which)); assert(idx <> -1); which.OnResume; Delete(idx); Result := idx; end; procedure TTargetList.Sort; begin if not fSorted then begin inherited Sort(CompareTargets); fSorted := true; end; end; procedure TTargetList.Suspend; var i : integer; begin Sort; for i := 0 to pred(Count) do try IShutDownTarget(List[i]).OnSuspend; except end; end; procedure TTargetList.Resume; var i : integer; begin Sort; for i := 0 to pred(Count) do try IShutDownTarget(List[i]).OnResume; except end; end; procedure TTargetList.Shutdown; var i : integer; begin Sort; for i := 0 to pred(Count) do try IShutDownTarget(List[i]).OnShutDown; except end; // <<>> finalize(IShutDownTarget(List[0]), Count); Clear; end; // Implementation procedure AttachTarget(const which : IShutDownTarget); begin if Targets = nil then Targets := TTargetList.Create; Targets.Add(which); end; procedure DetachTarget(const which : IShutDownTarget); begin if Targets <> nil // post-shutdown state then begin Targets.Remove(which); if Targets.Count = 0 then FreeObject(Targets); end; end; function DoSuspend : integer; begin if Targets <> nil then Result := Targets.Lock else Result := 0; end; function DoResume : integer; begin if Targets <> nil then Result := Targets.Unlock else Result := 0; end; procedure DoShutDown; begin FreeObject(Targets); end; initialization finalization DoShutDown; // Only to be sure end.
program OOStack; const MAX = 100; type IntArray = array [1..MAX] of integer; Stack = ^StackObj; StackObj = object private arr: ^IntArray; top: integer; cap: integer; public CONSTRUCTOR init(initCap : integer); DESTRUCTOR done; virtual; procedure push(e: integer); virtual; function pop : integer; virtual; function isEmpty : boolean; virtual; end; (*Stack*) DynArrStack = ^DynArrStackObj; DynArrStackObj = object(StackObj) constructor init(initCap : integer); procedure push(e : integer); virtual; function pop : integer; virtual; private procedure realloc; end; constructor StackObj.init(initCap : integer); begin if (initCap <= 0) or (initCap > MAX) then begin writeLn('Invalid capacity in constructor of stack!'); halt; end; top := 0; cap := initCap; getMem(arr, SIZEOF(integer) * cap); end; destructor StackObj.done; begin (* free all mememory! For Scotland *) freeMem(arr, sizeof(integer) * cap); end; procedure StackObj.Push(e: integer); begin if top < cap then begin inc(top); arr^[top] := e; end else begin writeLn('Stack is full'); halt; end; end; function StackObj.pop: integer; begin if isEmpty then begin writeLn('Stack is empty'); halt; end; pop := arr^[top]; dec(top); end; function StackObj.isEmpty: boolean; begin isEmpty := top = 0; end; (*****************************) (********** DynArrStack ******) (*****************************) constructor DynArrStackObj.init(initCap: integer); begin inherited init(initCap); cap := initCap; end; procedure DynArrStackObj.push(e: integer); begin if top = cap then begin realloc; end; inc(top); (*$R-*) arr^[top] := e; (*R+*) end; function DynArrStackObj.pop : integer; begin if isEmpty then begin writeLn('Stack is empty'); halt; end; (*R-*)pop := arr^[top];(*R+*) dec(top); end; procedure DynArrStackObj.realloc; var newArr : ^IntArray; i : integer; begin getMem(newArr, 2 * cap * SIZEOF(integer)); for i := 1 to top do begin (*R-*) newArr^[i] := arr^[i];(*R+*) end; freeMem(arr, cap * SIZEOF(integer)); arr := newArr; cap := 2*cap; end; var s: Stack; dynS : DynArrStack; i: integer; begin New(dynS, Init(10)); s := dyns; for i := 1 to 12 do begin s^.push(i); end; writeLn('IsEmpty:', s^.isEmpty); while not s^.isEmpty do begin writeLn(s^.pop); end; Dispose(s, Done); end.
unit atSemaphoreOperation; {* Обеспечивает выполнение вложенных операций одновременно не более чем заданному количеству клиентов } // Модуль: "w:\quality\test\garant6x\AdapterTest\Operations\atSemaphoreOperation.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatSemaphoreOperation" MUID: (4A4DF86D0208) interface uses l3IntfUses , atOperationBase ; type TatSemaphoreOperation = class(TatOperationBase) {* Обеспечивает выполнение вложенных операций одновременно не более чем заданному количеству клиентов } protected procedure ExecuteSelf; override; procedure InitParamList; override; procedure ExecuteChilds; override; end;//TatSemaphoreOperation implementation uses l3ImplUses , atFileBasedSemaphore , atLogger , SysUtils //#UC START# *4A4DF86D0208impl_uses* //#UC END# *4A4DF86D0208impl_uses* ; procedure TatSemaphoreOperation.ExecuteSelf; //#UC START# *48089F460352_4A4DF86D0208_var* var l_PathToFile : String; l_MaxEntered, l_Timeout : Integer; l_TFBS : TatFileBasedSemaphore; //#UC END# *48089F460352_4A4DF86D0208_var* begin //#UC START# *48089F460352_4A4DF86D0208_impl* inherited; l_PathToFile := Parameters['path_to_file'].AsStr; l_MaxEntered := Parameters['max_entered'].AsInt; l_Timeout := Parameters['timeout'].AsInt; // l_TFBS := TatFileBasedSemaphore.Create(l_PathToFile, l_MaxEntered); try Logger.Info('Ждем входа в секцию защищеную семафором'); if l_TFBS.Enter(l_Timeout) then begin Logger.Info('Вошли в секцию, защищеную семафором'); try inherited ExecuteChilds; finally l_TFBS.Leave(); Logger.Info('Покинули секцию, защищеную семафором'); end; end else Logger.Info('Не удалось войти в защищеную секцию в течение %d мс', [l_Timeout]); finally FreeAndNil(l_TFBS); end; //#UC END# *48089F460352_4A4DF86D0208_impl* end;//TatSemaphoreOperation.ExecuteSelf procedure TatSemaphoreOperation.InitParamList; //#UC START# *48089F3701B4_4A4DF86D0208_var* //#UC END# *48089F3701B4_4A4DF86D0208_var* begin //#UC START# *48089F3701B4_4A4DF86D0208_impl* inherited; with f_ParamList do begin Add( ParamType.Create('max_entered', 'Максимальное количество вошедших', '1') ); Add( ParamType.Create('timeout', 'Максимальное время ожидания', '-1') ); Add( ParamType.Create('path_to_file', 'Путь к файлу') ); end; //#UC END# *48089F3701B4_4A4DF86D0208_impl* end;//TatSemaphoreOperation.InitParamList procedure TatSemaphoreOperation.ExecuteChilds; //#UC START# *48089F660238_4A4DF86D0208_var* //#UC END# *48089F660238_4A4DF86D0208_var* begin //#UC START# *48089F660238_4A4DF86D0208_impl* // дети явно выполняются в ExecuteSelf //#UC END# *48089F660238_4A4DF86D0208_impl* end;//TatSemaphoreOperation.ExecuteChilds end.
unit OutputSearchHandlerViewer; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, PDTabControl, InfoBook, VisualControls, SHDocVw, CustomWebBrowser, VoyagerInterfaces, VoyagerServerInterfaces, ObjectInspectorInterfaces, StdCtrls, VisualClassesHandler, InternationalizerComponent, ComCtrls, FramedButton; const tidHandlerName_SupplyFinder = 'SupplyFinder'; type TOutputSearchViewer = class(TVisualControl) IECompPanel: TPanel; Panel1: TPanel; LeftLine: TShape; eCompany: TEdit; eTown: TEdit; Label1: TLabel; Label3: TLabel; cbExportWarehouses: TCheckBox; cbRegWarehouses: TCheckBox; cbTradeCenter: TCheckBox; cbFactories: TCheckBox; btnSearch: TFramedButton; Panel2: TPanel; lvResults: TListView; fbSelectALL: TFramedButton; fbClearAll: TFramedButton; fbBuyFrom: TFramedButton; btnClose: TFramedButton; eMaxLinks: TEdit; Label2: TLabel; InternationalizerComponent1: TInternationalizerComponent; procedure btnSearchClick(Sender: TObject); procedure fbSelectALLClick(Sender: TObject); procedure fbClearAllClick(Sender: TObject); procedure fbBuyFromClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure lvResultsDeletion(Sender: TObject; Item: TListItem); procedure lvResultsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lvResultsDblClick(Sender: TObject); procedure eMaxLinksKeyPress(Sender: TObject; var Key: Char); private fMasterURLHandler : IMasterURLHandler; fClientView : IClientView; fXPos : integer; fYPos : integer; fWorld : string; fFluid : string; public property MasterURLHandler : IMasterURLHandler read fMasterURLHandler write fMasterURLHandler; public procedure InitViewer(ClientView : IClientView; x, y : integer; world, fluid : string); private function GetLinkCoord(const text : string; var p : integer) : TPoint; procedure RenderResult(const text : string); public procedure RenderResults(const fluid, text : string); private function GetRoles : integer; public property Roles : integer read GetRoles; end; var OutputSearchViewer: TOutputSearchViewer; implementation uses CompStringsParser, SpecialChars, ServerCnxEvents, CacheCommon, Literals; {$R *.DFM} type TSupplierLinkInfo = class fX : integer; fY : integer; end; // TOutputSearchViewer procedure TOutputSearchViewer.InitViewer(ClientView : IClientView; x, y : integer; world, fluid : string); var keepResults : boolean; begin try keepResults := (fXPos = x) and (fYPos = y) and (fWorld = world) and (fFluid = fluid); fClientView := ClientView; fXPos := x; fYPos := y; fWorld := world; fFluid := fluid; cbExportWarehouses.Checked := true; cbRegWarehouses.Checked := true; cbTradeCenter.Checked := true; cbFactories.Checked := true; eCompany.Text := ''; eTown.Text := ''; if not keepResults then begin lvResults.Items.BeginUpdate; try lvResults.Items.Clear; finally lvResults.Items.EndUpdate; end; end; except end; end; function TOutputSearchViewer.GetLinkCoord(const text : string; var p : integer) : TPoint; var aux : string; begin FillChar(result, sizeof(result), 0); aux := CompStringsParser.GetNextStringUpTo(text, p, BackslashChar); if aux <> '' then begin result.x := StrToInt(aux); inc(p); aux := CompStringsParser.GetNextStringUpTo(text, p, BackslashChar); if aux <> '' then result.y := StrToInt(aux) else result.y := 0; end else result.x := 0; end; procedure TOutputSearchViewer.RenderResult(const text : string); var Item : TListItem; p : integer; aux : string; coord : TPoint; pt : PPoint; begin p := 1; coord := GetLinkCoord(text, p); inc(p); aux := CompStringsParser.GetNextStringUpTo(text, p, BackslashChar); if aux <> '' then begin Item := lvResults.Items.Add; Item.Caption := aux; new(pt); pt^ := coord; Item.Data := pt; inc(p); aux := CompStringsParser.GetNextStringUpTo(text, p, BackslashChar); while aux <> '' do begin Item.SubItems.Add(aux); aux := CompStringsParser.GetNextStringUpTo(text, p, BackslashChar); end; end; end; procedure TOutputSearchViewer.RenderResults(const fluid, text : string); var List : TStringList; i : integer; begin if fFluid = fluid then begin List := TStringList.Create; try List.Text := text; if List.Count = 0 then with lvResults.Items.Add do begin Caption := GetLiteral('Literal93'); Data := nil; end else for i := 0 to pred(List.Count) do RenderResult(List[i]); finally List.Free; end; end; end; procedure TOutputSearchViewer.btnSearchClick(Sender: TObject); var url : string; begin lvResults.Items.BeginUpdate; try lvResults.Items.Clear; finally lvResults.Items.EndUpdate; end; url := '?frame_Id=ObjectInspector' + '&Fluid=' + fFluid + '&Owner=' + eCompany.Text + '&Town=' + eTown.Text + '&Count=' + eMaxLinks.Text + '&Roles=' + IntToStr(Roles) + '&frame_Action=FINDSUPPLIERS'; fMasterURLHandler.HandleURL(url); end; procedure TOutputSearchViewer.fbSelectALLClick(Sender: TObject); var i : integer; begin lvResults.SetFocus; for i := 0 to pred(lvResults.Items.Count) do lvResults.Items[i].Selected := true; end; procedure TOutputSearchViewer.fbClearAllClick(Sender: TObject); var i : integer; begin for i := 0 to pred(lvResults.Items.Count) do lvResults.Items[i].Selected := false; end; procedure TOutputSearchViewer.fbBuyFromClick(Sender: TObject); var Item : TListItem; i : integer; pP : PPoint; aux : string; url : string; begin aux := ''; for i := 0 to pred(lvResults.Items.Count) do begin Item := lvResults.Items[i]; if Item.Selected then begin pP := PPoint(lvResults.Items[i].Data); if pP <> nil then aux := aux + IntToStr(pP.x) + ',' + IntToStr(pP.y) + ','; end; end; for i := pred(lvResults.Items.Count) to 0 do begin Item := lvResults.Items[i]; if Item.Selected then lvResults.Items.Delete(i); end; if aux <> '' then begin url := 'http://local.asp?frame_Id=ObjectInspector&Cnxs=' + aux + '&frame_Action=Connect'; fMasterURLHandler.HandleURL(url); end; end; procedure TOutputSearchViewer.btnCloseClick(Sender: TObject); var url : string; begin url := '?frame_Id=' + tidHandlerName_SupplyFinder + '&frame_Close=YES'; fMasterURLHandler.HandleURL(url); end; function TOutputSearchViewer.GetRoles : integer; var rl : TFacilityRoleSet; begin rl := []; if cbExportWarehouses.Checked then rl := rl + [rolCompExport]; // result := result or cbExportWarehouses.Tag; if cbRegWarehouses.Checked then rl := rl + [rolDistributer]; // result := result or cbRegWarehouses.Tag; if cbTradeCenter.Checked then rl := rl + [rolImporter]; // result := result or cbTradeCenter.Tag; if cbFactories.Checked then rl := rl + [rolProducer]; // result := result or cbFactories.Tag; result := byte(rl); end; procedure TOutputSearchViewer.lvResultsDeletion(Sender: TObject; Item: TListItem); begin try if Item.Data <> nil then dispose(Item.Data); finally Item.Data := nil; end; end; procedure TOutputSearchViewer.lvResultsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var i : integer; begin if Key = VK_DELETE then for i := pred(lvResults.Items.Count) downto 0 do if lvResults.Items[i].Selected then lvResults.Items.Delete(i); end; procedure TOutputSearchViewer.lvResultsDblClick(Sender: TObject); begin fbBuyFromClick(Sender); end; procedure TOutputSearchViewer.eMaxLinksKeyPress(Sender: TObject; var Key: Char); begin if not(key in ['0'..'9']) then Key := #0; end; end.
unit GetLocationHistoryFromTimeRangeUnit; interface uses SysUtils, BaseExampleUnit; type TGetLocationHistoryFromTimeRange = class(TBaseExample) public procedure Execute(RouteId: String; StartDate, EndDate: TDateTime); end; implementation uses TrackingHistoryUnit, TrackingHistoryResponseUnit; procedure TGetLocationHistoryFromTimeRange.Execute( RouteId: String; StartDate, EndDate: TDateTime); var ErrorString: String; Response: TTrackingHistoryResponse; HistoryStep: TTrackingHistory; LastPositionOnly: boolean; begin LastPositionOnly := False; Response := Route4MeManager.Tracking.GetLocationHistory( RouteId, StartDate, EndDate, LastPositionOnly, ErrorString); try WriteLn(''); if (Response <> nil) then begin WriteLn('GetLocationHistoryFromTimeRange executed successfully'); WriteLn(''); WriteLn(Format('Total location history steps: %d', [Length(Response.TrackingHistories)])); WriteLn(''); for HistoryStep in Response.TrackingHistories do begin WriteLn(Format('Speed: %f', [HistoryStep.Speed.Value])); WriteLn(Format('Longitude: %f', [HistoryStep.Longitude.Value])); WriteLn(Format('Latitude: %f', [HistoryStep.Latitude.Value])); WriteLn(Format('Time Stamp: %s', [HistoryStep.TimeStamp.Value])); WriteLn(''); end; end else WriteLn(Format('GetLocationHistoryFromTimeRange error: "%s"', [ErrorString])); finally FreeAndNil(Response); end; end; end.
PROGRAM ejercicio; CONST INI = 1; FIN = 7; TYPE TLista = ARRAY [INI..FIN] OF integer; VAR lista: TLista; aux: integer; PROCEDURE Inicializar (VAR v: TLista); VAR i: integer; BEGIN FOR i:= INI TO FIN DO v[i] := 0; END; PROCEDURE Mostrar (v: TLista); VAR i: integer; BEGIN FOR i:= INI TO FIN DO write (v[i], ' '); writeln; END; FUNCTION Verificar (v: TLista; n: integer): boolean; VAR i: integer; aux: boolean; BEGIN i := 0; {PRED (INI);} REPEAT i := SUCC (i); aux:= v[i] = n; UNTIL (aux {= TRUE}) OR (v[i] = 0) OR (i = FIN); Verificar := aux; END; PROCEDURE RellenarAutomatico (VAR v: TLista); VAR i, aux: integer; BEGIN i := INI; REPEAT aux := RANDOM (49) + 1; IF (NOT Verificar(v, aux)) THEN BEGIN v[i] := aux; i := SUCC (i); END; UNTIL (i = FIN+1); END; PROCEDURE RellenarManual (VAR v: TLista); VAR i, aux: integer; valido: boolean; BEGIN i := INI; REPEAT writeln ('Dame el numero ', i); readln (aux); valido := (aux > 0) AND (aux < 50); IF (valido) AND (NOT Verificar(v, aux)) THEN BEGIN v[i] := aux; i := SUCC (i); END; UNTIL (i = FIN+1); END; PROCEDURE Ordenar (VAR v: TLista); VAR i, j, aux: integer; BEGIN FOR i:= INI TO FIN - 1 DO FOR j := INI TO (FIN - i) DO IF (v[j] > v[j+1]) THEN BEGIN aux := v [j + 1]; v [j + 1] := v [j]; v [j] := aux; END; END; FUNCTION BusquedaBinaria (v: TLista; n: integer): boolean; VAR extremoInferior, extremoSuperior, centro: integer; aux: boolean; BEGIN extremoInferior := INI; extremoSuperior := FIN; aux := FALSE; WHILE (NOT aux) AND (extremoSuperior >= extremoInferior) DO BEGIN centro := (extremoSuperior + extremoInferior) DIV 2; IF v[centro] = n THEN aux := TRUE ELSE IF v[centro] < n THEN extremoInferior := SUCC(centro) ELSE extremoSuperior := PRED(centro); END; {WHILE} BusquedaBinaria := aux; END; {BusquedaBinaria} FUNCTION ContarAciertos (v, l : TLista): integer; VAR aux, i: integer; BEGIN aux := 0; FOR i:= INI TO FIN DO BEGIN IF Verificar (v, l [i]) THEN aux := SUCC(aux); END; ContarAciertos := aux; END; PROCEDURE CelebrarSorteo (VAR v: TLista); BEGIN RellenarAutomatico (v); Ordenar (v); END; PROCEDURE Menu; VAR apuesta, sorteo: TLista; opcion: char; BEGIN writeln ('Bienvenido a la loteria primitiva'); writeln ('Si desea hacer una apuesta manual, pulse 1, si desea hacerla aleatoria, pulse 2'); readln (opcion); CASE opcion OF '1': RellenarManual (apuesta); '2': RellenarAutomatico (apuesta) ELSE writeln ('Opcion no valida'); END; {CASE} Ordenar (apuesta); Mostrar (apuesta); CelebrarSorteo (sorteo); Mostrar (sorteo); Writeln (ContarAciertos(apuesta, sorteo)); END; BEGIN Randomize; Menu; readln; END.
unit Entidade.Tesouraria; interface uses SimpleAttributes; type TTB_TESOURARIA = class private FNRO_DOCUMENTO: integer; FVALOR: Double; FUSUARIO_INCLUSAO: string; FID_CENTRO_CUSTO: Integer; FDTA_MOVIMENTO: TDateTime; FDESCRICAO: string; FTIPO:string; FID_TIPO_LANCAMENTO: Integer; FSTATUS: string; FCOD_ENTRADA: integer; FSITUACAO: Integer; FID_FORNECEDOR: Integer; FCOD_TIPO_SAIDA: Integer; FCOD_CONGREGACAO: Integer; FID_FORMA_PAGAMENTO: Integer; FDTA_INCLUSAO: TDateTime; FID_TIPO_CULTO: Integer; procedure SetCOD_CONGREGACAO(const Value: Integer); procedure SetCOD_ENTRADA(const Value: integer); procedure SetCOD_TIPO_SAIDA(const Value: Integer); procedure SetDESCRICAO(const Value: string); procedure SetDTA_INCLUSAO(const Value: TDateTime); procedure SetDTA_MOVIMENTO(const Value: TDateTime); procedure SetID_CENTRO_CUSTO(const Value: Integer); procedure SetID_FORMA_PAGAMENTO(const Value: Integer); procedure SetID_FORNECEDOR(const Value: Integer); procedure SetID_TIPO_CULTO(const Value: Integer); procedure SetID_TIPO_LANCAMENTO(const Value: Integer); procedure SetNRO_DOCUMENTO(const Value: integer); procedure SetSITUACAO(const Value: Integer); procedure SetSTATUS(const Value: string); procedure SetUSUARIO_INCLUSAO(const Value: string); procedure SetVALOR(const Value: Double); procedure SetTIPO(const Value: string); published [PK,AutoInc] property COD_ENTRADA:integer read FCOD_ENTRADA write SetCOD_ENTRADA; property NRO_DOCUMENTO:integer read FNRO_DOCUMENTO write SetNRO_DOCUMENTO; property DTA_MOVIMENTO:TDateTime read FDTA_MOVIMENTO write SetDTA_MOVIMENTO; property DTA_INCLUSAO:TDateTime read FDTA_INCLUSAO write SetDTA_INCLUSAO; property USUARIO_INCLUSAO:string read FUSUARIO_INCLUSAO write SetUSUARIO_INCLUSAO; property DESCRICAO:string read FDESCRICAO write SetDESCRICAO; property VALOR:Double read FVALOR write SetVALOR; property STATUS:string read FSTATUS write SetSTATUS; property COD_CONGREGACAO:Integer read FCOD_CONGREGACAO write SetCOD_CONGREGACAO; property SITUACAO:Integer read FSITUACAO write SetSITUACAO; property COD_TIPO_SAIDA:Integer read FCOD_TIPO_SAIDA write SetCOD_TIPO_SAIDA; property ID_CENTRO_CUSTO:Integer read FID_CENTRO_CUSTO write SetID_CENTRO_CUSTO; property ID_TIPO_LANCAMENTO:Integer read FID_TIPO_LANCAMENTO write SetID_TIPO_LANCAMENTO; property ID_FORMA_PAGAMENTO:Integer read FID_FORMA_PAGAMENTO write SetID_FORMA_PAGAMENTO; property ID_FORNECEDOR:Integer read FID_FORNECEDOR write SetID_FORNECEDOR; property ID_TIPO_CULTO:Integer read FID_TIPO_CULTO write SetID_TIPO_CULTO; property TIPO:string read FTIPO write SetTIPO; end; implementation { TTESOURARIA } procedure TTB_TESOURARIA.SetCOD_CONGREGACAO(const Value: Integer); begin FCOD_CONGREGACAO := Value; end; procedure TTB_TESOURARIA.SetCOD_ENTRADA(const Value: integer); begin FCOD_ENTRADA := Value; end; procedure TTB_TESOURARIA.SetCOD_TIPO_SAIDA(const Value: Integer); begin FCOD_TIPO_SAIDA := Value; end; procedure TTB_TESOURARIA.SetDESCRICAO(const Value: string); begin FDESCRICAO := Value; end; procedure TTB_TESOURARIA.SetDTA_INCLUSAO(const Value: TDateTime); begin FDTA_INCLUSAO := Value; end; procedure TTB_TESOURARIA.SetDTA_MOVIMENTO(const Value: TDateTime); begin FDTA_MOVIMENTO := Value; end; procedure TTB_TESOURARIA.SetID_CENTRO_CUSTO(const Value: Integer); begin FID_CENTRO_CUSTO := Value; end; procedure TTB_TESOURARIA.SetID_FORMA_PAGAMENTO(const Value: Integer); begin FID_FORMA_PAGAMENTO := Value; end; procedure TTB_TESOURARIA.SetID_FORNECEDOR(const Value: Integer); begin FID_FORNECEDOR := Value; end; procedure TTB_TESOURARIA.SetID_TIPO_CULTO(const Value: Integer); begin FID_TIPO_CULTO := Value; end; procedure TTB_TESOURARIA.SetID_TIPO_LANCAMENTO(const Value: Integer); begin FID_TIPO_LANCAMENTO := Value; end; procedure TTB_TESOURARIA.SetNRO_DOCUMENTO(const Value: integer); begin FNRO_DOCUMENTO := Value; end; procedure TTB_TESOURARIA.SetSITUACAO(const Value: Integer); begin FSITUACAO := Value; end; procedure TTB_TESOURARIA.SetSTATUS(const Value: string); begin FSTATUS := Value; end; procedure TTB_TESOURARIA.SetTIPO(const Value: string); begin FTIPO:=Value; end; procedure TTB_TESOURARIA.SetUSUARIO_INCLUSAO(const Value: string); begin FUSUARIO_INCLUSAO := Value; end; procedure TTB_TESOURARIA.SetVALOR(const Value: Double); begin FVALOR := Value; end; end.
unit NurseAppMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Edit, FMX.ListBox, FMX.Layouts, FMX.StdCtrls, FMX.Controls.Presentation, FMX.TabControl, System.Bluetooth, System.Bluetooth.Components, SensorMonitorsU, System.JSON, Data.Bind.EngExt, Fmx.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.Components; type TForm23 = class(TForm) ToolBar1: TToolBar; Label1: TLabel; ListBox1: TListBox; PatientName: TListBoxItem; PatientHeartrate: TListBoxItem; PatientWeight: TListBoxItem; NameEdit: TComboBox; PatientEdit: TEdit; WeightEdit: TEdit; SpeedButton2: TSpeedButton; SpeedButton3: TSpeedButton; SaveData: TSpeedButton; SpeedButton6: TSpeedButton; TabControl1: TTabControl; GetData: TTabItem; StoredData: TTabItem; ToolBar2: TToolBar; StoredVitals: TLabel; ListBox2: TListBox; RecordedPatientVitals: TListBoxGroupHeader; StoredPatientName: TListBoxItem; StoredPatientHeartrate: TListBoxItem; StoredPatientWeight: TListBoxItem; lblNamePatient: TLabel; BindingsList1: TBindingsList; LinkFillControlToPropertyItemDataDetail: TLinkFillControlToProperty; procedure FormCreate(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure FormDestroy(Sender: TObject); // For update the UI procedure OnHearMonitorUpdateData(const AMeasurement : string; const ASensorLocation : String); procedure OnWeightMonitorUpdateData(const AWeight : double); procedure SpeedButton3Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure NameEditChange(Sender: TObject); procedure UpdateStoredPatientData(const AData : TJSONObject); function GetPatientDataToSave(const AUserId: string): TJSONObject; procedure OnSaveData(Sender : TObject); function ExistInComboBox(const AUserId : string): boolean; private { Private declarations } FHeartMonitor : THeartMonitor; FWeightMonitor : TWeightMonitor; procedure PushRegister; public { Public declarations } end; var Form23: TForm23; implementation uses NurseStationClientModuleU, System.PushNotification; type TDataPatient = class private FUserId: String; public constructor Create(const AUserId : String); property UserId : String read FUserId write FUserId; end; {$R *.fmx} function TForm23.ExistInComboBox(const AUserId: string): boolean; var I: Integer; AData : TDataPatient; begin Result := False; for I := 0 to NameEdit.Items.Count - 1 do begin AData := NameEdit.Items.Objects[I] as TDataPatient; if(AData.UserId.Equals(AUserId))then begin Result := True; break; end; end; end; procedure TForm23.FormCreate(Sender: TObject); var LDescription : String; LJsonMess : TJSONObject; lStatus : string; lUserId : string; begin FHeartMonitor := THeartMonitor.Create(); FHeartMonitor.OnUpdateData := OnHearMonitorUpdateData; FWeightMonitor := TWeightMonitor.Create(); FWeightMonitor.OnUpdateData := OnWeightMonitorUpdateData; NurseStationClientModule.OnPushReceived := procedure(AMessage : string; AExtras : TJSONObject) begin lJsonMess := TJSONObject.ParseJSONValue(AMessage) as TJSONObject; lStatus := lJsonMess.GetValue('status').Value; LUserId := LJsonMess.GetValue('message').Value; lDescription := NurseStationClientModule.GetDescription(LJsonMess.GetValue('message').Value); // Update the combobox via Push Message if not exist if(not ExistInComboBox(lUserId))then begin NameEdit.Items.AddObject(LDescription, TDataPatient.Create(lUserId)); end; // Update the label if(lStatus.Equals('NurseRoom'))then begin lblNamepatient.Text := LDescription + ' has entered the room'; end; end; end; procedure TForm23.FormDestroy(Sender: TObject); begin FHeartMonitor.Disconnect(); FreeAndNil(FHeartMonitor); FWeightMonitor.Disconnect(); FreeAndNil(FWeightMonitor); end; procedure TForm23.FormShow(Sender: TObject); begin // EMS Process NurseStationClientModule.Login('nurseuser', 'nursepass'); PushRegister(); end; function TForm23.GetPatientDataToSave(const AUserId: string): TJSONObject; begin Result := TJSONObject.Create(); Result.AddPair('id', AUserId); Result.AddPair('heart_rate', TJSONString.Create(PatientEdit.Text)); Result.AddPair('weight', TJSONString.Create(WeightEdit.Text)); end; procedure TForm23.NameEditChange(Sender: TObject); var AData : TDataPatient; begin if(NameEdit.Selected <> nil)then begin // Send Message Patient AData := TDataPatient(NameEdit.Items.Objects[NameEdit.Selected.Index]); NurseStationClientModule.SendMessagePatient(AData.UserId); // update the stored data UI UpdateStoredPatientData(NurseStationClientModule.GetPatientData(AData.UserId)); end; end; procedure TForm23.OnHearMonitorUpdateData(const AMeasurement, ASensorLocation: String); begin PatientEdit.Text := AMeasurement; end; procedure TForm23.OnSaveData(Sender: TObject); var AData : TJSONObject; begin if(NameEdit.Selected <> nil)then begin // Disabled the monitors FHeartMonitor.Disconnect(); FWeightMonitor.Disconnect(); try AData := GetPatientDataToSave((NameEdit.Selected.Data as TDataPatient).UserId); NurseStationClientModule.AddPatientData(AData); // Update the StoreData Tab UpdateStoredPatientData(AData); ShowMessage('The patient data saved'); except ShowMessage('Error save the data'); end; end else ShowMessage('You must choose a patient'); end; procedure TForm23.OnWeightMonitorUpdateData(const AWeight: double); begin WeightEdit.Text := Format('%8.2f pounds', [AWeight]); end; procedure TForm23.PushRegister; begin // Enable push if there are any push services if TPushServiceManager.Instance.Count > 0 then begin NurseStationClientModule.OnDeviceTokenReceived := procedure begin NurseStationClientModule.PushRegisterNurse(); end; if not NurseStationClientModule.PushEvents1.Active then try NurseStationClientModule.PushEvents1.Active := True; except // TODO end; end; end; procedure TForm23.SpeedButton2Click(Sender: TObject); begin if(NameEdit.Selected <> nil) then FHeartMonitor.Connect() else ShowMessage('You must choose a patient'); end; procedure TForm23.SpeedButton3Click(Sender: TObject); begin if(NameEdit.Selected <> nil) then FWeightMonitor.Connect() else ShowMessage('You must choose a patient'); end; procedure TForm23.UpdateStoredPatientData(const AData: TJSONObject); begin StoredPatientHeartrate.ItemData.Detail := AData.GetValue<string>('heart_rate'); StoredPatientWeight.ItemData.Detail := AData.GetValue<string>('weight'); end; { TDataPatient } constructor TDataPatient.Create(const AUserId: String); begin FUserId := AUserId; end; end.
unit ncsTrafficCounter; // Модуль: "w:\common\components\rtl\Garant\cs\ncsTrafficCounter.pas" // Стереотип: "UtilityPack" // Элемент модели: "ncsTrafficCounter" MUID: (57F3833101A7) {$Include w:\common\components\rtl\Garant\cs\CsDefine.inc} interface {$If NOT Defined(Nemesis)} uses l3IntfUses , l3StopWatch , l3ProtoObject ; type IncsTrafficCounter = interface ['{A75CEBEC-F0A7-4C0F-9464-84EDD9E2013E}'] function Get_BytesProcessed: Int64; function Get_ProcessingTime: TDateTime; procedure Reset; procedure DoProgress(aDelta: Int64); procedure AddWatch(const aWatch: Tl3StopWatch); property BytesProcessed: Int64 read Get_BytesProcessed; property ProcessingTime: TDateTime read Get_ProcessingTime; end;//IncsTrafficCounter TncsTrafficCounter = class(Tl3ProtoObject, IncsTrafficCounter) private f_Counter: Int64; f_Watch: Tl3StopWatch; protected function Get_BytesProcessed: Int64; procedure Reset; procedure DoProgress(aDelta: Int64); function Get_ProcessingTime: TDateTime; procedure AddWatch(const aWatch: Tl3StopWatch); public constructor Create; reintroduce; class function Make: IncsTrafficCounter; reintroduce; end;//TncsTrafficCounter {$IfEnd} // NOT Defined(Nemesis) implementation {$If NOT Defined(Nemesis)} uses l3ImplUses //#UC START# *57F3833101A7impl_uses* //#UC END# *57F3833101A7impl_uses* ; constructor TncsTrafficCounter.Create; //#UC START# *57F383A802EA_57F3830802F2_var* //#UC END# *57F383A802EA_57F3830802F2_var* begin //#UC START# *57F383A802EA_57F3830802F2_impl* inherited; f_Counter := 0; //#UC END# *57F383A802EA_57F3830802F2_impl* end;//TncsTrafficCounter.Create class function TncsTrafficCounter.Make: IncsTrafficCounter; var l_Inst : TncsTrafficCounter; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TncsTrafficCounter.Make function TncsTrafficCounter.Get_BytesProcessed: Int64; //#UC START# *57F382B203A9_57F3830802F2get_var* //#UC END# *57F382B203A9_57F3830802F2get_var* begin //#UC START# *57F382B203A9_57F3830802F2get_impl* Result := f_Counter; //#UC END# *57F382B203A9_57F3830802F2get_impl* end;//TncsTrafficCounter.Get_BytesProcessed procedure TncsTrafficCounter.Reset; //#UC START# *57F382CC017D_57F3830802F2_var* //#UC END# *57F382CC017D_57F3830802F2_var* begin //#UC START# *57F382CC017D_57F3830802F2_impl* f_Counter := 0; f_Watch.Reset; //#UC END# *57F382CC017D_57F3830802F2_impl* end;//TncsTrafficCounter.Reset procedure TncsTrafficCounter.DoProgress(aDelta: Int64); //#UC START# *57F382DC01D1_57F3830802F2_var* //#UC END# *57F382DC01D1_57F3830802F2_var* begin //#UC START# *57F382DC01D1_57F3830802F2_impl* Inc(f_Counter, aDelta); //#UC END# *57F382DC01D1_57F3830802F2_impl* end;//TncsTrafficCounter.DoProgress function TncsTrafficCounter.Get_ProcessingTime: TDateTime; //#UC START# *57FB5C8F0014_57F3830802F2get_var* //#UC END# *57FB5C8F0014_57F3830802F2get_var* begin //#UC START# *57FB5C8F0014_57F3830802F2get_impl* Result := f_Watch.Time; //#UC END# *57FB5C8F0014_57F3830802F2get_impl* end;//TncsTrafficCounter.Get_ProcessingTime procedure TncsTrafficCounter.AddWatch(const aWatch: Tl3StopWatch); //#UC START# *57FB5CB90232_57F3830802F2_var* //#UC END# *57FB5CB90232_57F3830802F2_var* begin //#UC START# *57FB5CB90232_57F3830802F2_impl* f_Watch.Add(aWatch); //#UC END# *57FB5CB90232_57F3830802F2_impl* end;//TncsTrafficCounter.AddWatch {$IfEnd} // NOT Defined(Nemesis) end.
unit IdNTLMv2; interface {$i IdCompilerDefines.inc} uses IdGlobal, IdStruct {$IFNDEF DOTNET}, IdCTypes, IdSSLOpenSSLHeaders{$ENDIF} ; type ProtocolArray = array [ 1.. 8] of AnsiChar; nonceArray = Array[ 1.. 8] of AnsiChar; const //These are from: // http://svn.xmpp.ru/repos/tkabber/trunk/tkabber/jabberlib/ntlm.tcl // and the code is under a BSD license IdNTLMSSP_NEGOTIATE_UNICODE = $00000001; //A - NTLMSSP_NEGOTIATE_UNICODE IdNTLM_NEGOTIATE_OEM = $00000002; //B - NTLM_NEGOTIATE_OEM IdNTLMSSP_REQUEST_TARGET = $00000004; //C - NTLMSSP_REQUEST_TARGET IdNTLM_Unknown1 = $00000008; //r9 - should be zero IdNTLMSSP_NEGOTIATE_SIGN = $00000010; //D - NTLMSSP_NEGOTIATE_SIGN IdNTLMSSP_NEGOTIATE_SEAL = $00000020; //E - NTLMSSP_NEGOTIATE_SEAL IdNTLMSSP_NEGOTIATE_DATAGRAM = $00000040; //F - NTLMSSP_NEGOTIATE_DATAGRAM IdNTLMSSP_NEGOTIATE_LM_KEY = $00000080; //G - NTLMSSP_NEGOTIATE_LM_KEY //mentioned in http://svn.xmpp.ru/repos/tkabber/trunk/tkabber/jabberlib/ntlm.tcl //and http://doc.ddart.net/msdn/header/include/ntlmsp.h.html from an old ntlmsp.h //header. MS now says that is unused so it should be zero. IdNTLMSSP_NEGOTIATE_NETWARE = $00000100; //r8 - should be zero IdNTLMSSP_NEGOTIATE_NTLM = $00000200; //H - NTLMSSP_NEGOTIATE_NTLM IdNTLMSSP_NEGOTIATE_NT_ONLY = $00000400; //I - NTLMSSP_NEGOTIATE_NT_ONLY IdNTLMSSP_ANONYMOUS = $00000800; //J - IdNTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED = $00001000; //K - NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED IdNTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED = $00002000; //L - NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED //mentioned in http://svn.xmpp.ru/repos/tkabber/trunk/tkabber/jabberlib/ntlm.tcl //and http://doc.ddart.net/msdn/header/include/ntlmsp.h.html from an old ntlmsp.h //header. MS now says that is unused so it should be zero. IdNTLMSSP_NEGOTIATE_LOCAL_CALL = $00004000; //r6 - should be zero IdNTLMSSP_NEGOTIATE_ALWAYS_SIGN = $00008000; //M - NTLMSSP_NEGOTIATE_ALWAYS_SIGN IdNTLMSSP_TARGET_TYPE_DOMAIN = $00010000; //N - NTLMSSP_TARGET_TYPE_DOMAIN IdNTLMSSP_TARGET_TYPE_SERVER = $00020000; //O - NTLMSSP_TARGET_TYPE_SERVER IdNTLMSSP_TARGET_TYPE_SHARE = $00040000; //P - NTLMSSP_TARGET_TYPE_SHARE IdNTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY = $00080000; //Q - NTLMSSP_NEGOTIATE_NTLM2 //was NTLMSSP_REQUEST_INIT_RESPONSE 0x100000 IdNTLMSSP_NEGOTIATE_IDENTIFY = $00100000; //R - NTLMSSP_NEGOTIATE_IDENTIFY IdNTLMSSP_REQUEST_ACCEPT_RESPONSE = $00200000; //r5 - should be zero //mentioned in http://doc.ddart.net/msdn/header/include/ntlmsp.h.html from an old ntlmsp.h //header. MS now says that is unused so it should be zero. IdIdNTLMSSP_REQUEST_NON_NT_SESSION_KEY = $00400000; //S - NTLMSSP_REQUEST_NON_NT_SESSION_KEY IdNTLMSSP_NEGOTIATE_TARGET_INFO = $00800000; //T - NTLMSSP_NEGOTIATE_TARGET_INFO IdNTLM_Unknown4 = $01000000; //r4 - should be zero IdNTLMSSP_NEGOTIATE_VERSION = $02000000; //U - NTLMSSP_NEGOTIATE_VERSION // 400000 IdNTLM_Unknown6 = $04000000; //r3 - should be zero IdNTLM_Unknown7 = $08000000; //r2 - should be zero IdNTLM_Unknown8 = $10000000; //r1 - should be zero IdNTLMSSP_NEGOTIATE_128 = $20000000; //V - NTLMSSP_NEGOTIATE_128 IdNTLMSSP_NEGOTIATE_KEY_EXCH = $40000000; //W - NTLMSSP_NEGOTIATE_KEY_EXCH IdNTLMSSP_NEGOTIATE_56 = $80000000; //X - NTLMSSP_NEGOTIATE_56 const //LC2 supports NTLMv2 only IdNTLM_TYPE1_FLAGS_LC2 = IdNTLMSSP_NEGOTIATE_UNICODE or IdNTLM_NEGOTIATE_OEM or IdNTLMSSP_REQUEST_TARGET or IdNTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY; IdNTLM_TYPE1_FLAGS = IdNTLMSSP_NEGOTIATE_UNICODE or IdNTLM_NEGOTIATE_OEM or IdNTLMSSP_REQUEST_TARGET or IdNTLMSSP_NEGOTIATE_NTLM or // IdNTLMSSP_NEGOTIATE_ALWAYS_SIGN or IdNTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY; IdNTLM_TYPE1_MARKER : LongWord = 1; IdNTLM_TYPE2_MARKER : LongWord = 2; IdNTLM_TYPE3_MARKER : LongWord = 3; IdNTLM_NTLMSSP_DES_KEY_LENGTH =7; IdNTLM_NTLMSSP_CHALLENGE_SIZE = 8; IdNTLM_LM_HASH_SIZE = 16; IdNTLM_LM_SESS_HASH_SIZE = 16; IdNTLM_LM_RESPONSE_SIZE = 24; IdNTLM_NTLMSSP_HASH_SIZE = 16; IdNTLM_NTLMSSP_RESPONSE_SIZE = 24; IdNTLM_NTLMSSP_V2_HASH_SIZE = 6; IdNTLM_NTLMSSP_V2_RESPONSE_SIZE = 16; IdNTLM_NONCE_LEN = 8; IdNTLM_TYPE2_TNAME_LEN_OFS = 12; IdNTLM_TYPE2_TNAME_OFFSET_OFS = 16; IdNTLM_TYPE2_FLAGS_OFS = 20; IdNTLM_TYPE2_NONCE_OFS = 24; IdNTLM_TYPE2_TINFO_LEN_OFS = 40; IdNTLM_TYPE2_TINFO_OFFSET_OFS = 44; IdNTLM_TYPE3_DOM_OFFSET = 64; //version info constants IdNTLM_WINDOWS_MAJOR_VERSION_5 = $05; IdNTLM_WINDOWS_MAJOR_VERSION_6 = $06; IdNTLM_WINDOWS_MINOR_VERSION_0 = $00; IdNTLM_WINDOWS_MINOR_VERSION_1 = $01; IdNTLM_WINDOWS_MINOR_VERSION_2 = $02; //original rel. build version of Vista //This isn't in the headers but I found easy enough. //It's provided because some NTLM servers might want ver info //from us. So we want to provide some dummy version and //Windows Vista is logical enough. IdNTLM_WINDOWS_BUILD_ORIG_VISTA = 6000; var IdNTLM_SSP_SIG : TIdBytes; UnixEpoch : TDateTime; {$DEFINE TESTSUITE} {$IFDEF TESTSUITE} procedure TestNTLM; {$ENDIF} function BuildType1Msg(const ADomain : String = ''; const AHost : String = ''; const ALMCompatibility : LongWord = 0) : TIdBytes; procedure ReadType2Msg(const AMsg : TIdBytes; var VFlags : LongWord; var VTargetName : TIdBytes; var VTargetInfo : TIdBytes; var VNonce : TIdBytes ); function BuildType3Msg(const ADomain, AHost, AUsername, APassword : String; const AFlags : LongWord; const AServerNonce : TIdBytes; const ATargetName, ATargetInfo : TIdBytes; const ALMCompatibility : LongWord = 0) : TIdBytes; { function BuildType1Message( ADomain, AHost: String; const AEncodeMsg : Boolean = True): String; procedure ReadType2Message(const AMsg : String; var VNonce : nonceArray; var Flags : LongWord); function BuildType3Message( ADomain, AHost, AUsername: TIdUnicodeString; APassword : String; AServerNonce : nonceArray): String; } function NTLMFunctionsLoaded : Boolean; procedure GetDomain(const AUserName : String; var VUserName, VDomain : String); function DumpFlags(const ABytes : TIdBytes): String; overload; function DumpFlags(const AFlags : LongWord): String; overload; function LoadRC4 : Boolean; function RC4FunctionsLoaded : Boolean; {$IFNDEF DOTNET} //const char *RC4_options(void); var GRC4_Options : function () : PAnsiChar; cdecl = nil; //void RC4_set_key(RC4_KEY *key, int len, const unsigned char *data); GRC4_set_key : procedure(key : PRC4_KEY; len : TIdC_INT; data : PAnsiChar); cdecl = nil; //void RC4(RC4_KEY *key, unsigned long len, const unsigned char *indata, // unsigned char *outdata); GRC4 : procedure (key : PRC4_KEY; len : TIdC_ULONG; indata, outdata : PAnsiChar) ; cdecl = nil; {$ENDIF} implementation uses SysUtils, {$IFDEF USE_VCL_POSIX} PosixTime, {$ENDIF} {$IFDEF DOTNET} Classes, System.Runtime.InteropServices, System.Runtime.InteropServices.ComTypes, System.Security.Cryptography, System.Text, {$ELSE} {$IFDEF FPC} DynLibs, // better add DynLibs only for fpc {$ENDIF} {$IFDEF WINDOWS} //Windows should really not be included but this protocol does use //some windows internals and is Windows-based. Windows, {$ENDIF} {$ENDIF} IdFIPS, IdGlobalProtocols, IdHash, IdHMACMD5, IdHashMessageDigest, IdCoderMIME; const {$IFDEF DOTNET} MAGIC : array [ 0.. 7] of byte = ( $4b, $47, $53, $21, $40, $23, $24, $25); {$ELSE} Magic: des_cblock = ( $4B, $47, $53, $21, $40, $23, $24, $25 ); Magic_const : array [0..7] of byte = ( $4b, $47, $53, $21, $40, $23, $24, $25 ); {$ENDIF} TYPE1_MARKER = 1; TYPE2_MARGER = 2; TYPE3_MARKER = 3; //const // NUL_USER_SESSION_KEY : TIdBytes[0..15] = ($00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00); {$IFNDEF DOTNET} type Pdes_key_schedule = ^des_key_schedule; {$IFNDEF WINDOWS} FILETIME = record dwLowDateTime : LongWord; dwHighDateTime : LongWord; end; {$ENDIF} {$ENDIF} function NulUserSessionKey : TIdBytes; begin SetLength(Result,16); FillChar(Result,16,0); end; //misc routines that might be helpful in some other places //=================== {$IFDEF DOTNET} function Int64ToFileTime(const AInt64 : Int64) : System.Runtime.InteropServices.ComTypes.FILETIME; var LBytes : TIdBytes; begin LBytes := BitConverter.GetBytes(AInt64); Result.dwLowDateTime := BitConverter.ToInt32(Lbytes, 0); Result.dwHighDateTime := BitConverter.ToInt32(Lbytes, 4); end; function UnixTimeToFileTime(const AUnixTime : LongWord) : System.Runtime.InteropServices.ComTypes.FILETIME; {$ELSE} { We do things this way because in Win64, FILETIME may not be a simple typecast of Int64. It might be a two dword record that's aligned on an 8-byte boundery. } {$UNDEF USE_FILETIME_TYPECAST} {$IFDEF WINCE} {$DEFINE USE_FILETIME_TYPECAST} {$ENDIF} {$IFDEF WIN32} {$DEFINE USE_FILETIME_TYPECAST} {$ENDIF} function UnixTimeToFileTime(const AUnixTime : LongWord) : FILETIME; var i : Int64; {$ENDIF} begin {$IFDEF DOTNET} Result := Int64ToFileTime((AUnixTime + 11644473600) * 10000000); {$ELSE} i := (AUnixTime + 11644473600) * 10000000; {$IFDEF USE_FILETIME_TYPECAST} Result := FILETIME(i); {$ELSE} Result.dwLowDateTime := i and $FFFFFFFF; Result.dwHighDateTime := i shr 32; {$ENDIF} {$ENDIF} end; function NowAsFileTime : FILETIME; {$IFDEF DOTNET} {$IFDEF USE_INLINE} inline; {$ENDIF} {$ENDIF} {$IFDEF UNIX} {$IFNDEF USE_VCL_POSIX} var TheTms: tms; {$ENDIF} {$ENDIF} begin {$IFDEF WINDOWS} {$IFDEF WINCE} // TODO {$ELSE} Windows.GetSystemTimeAsFileTime(Result); {$ENDIF} {$ENDIF} {$IFDEF UNIX} {$IFDEF USE_VCL_BASEUNIX} Result := UnixTimeToFileTime( fptimes (TheTms)); {$ENDIF} //Is the following correct? {$IFDEF KYLIXCOMPAT} Result := UnixTimeToFileTime(Times(TheTms)); {$ENDIF} {$IFDEF USE_VCL_POSIX} Result := UnixTimeToFileTime(PosixTime.time(nil)); {$ENDIF} {$ENDIF} {$IFDEF DOTNET} Result := Int64ToFileTime(DateTime.Now.ToFileTimeUtc); // Result := System.DateTime.Now.Ticks; {$ENDIF} end; function ConcateBytes(const A1, A2 : TIdBytes) : TIdBytes; begin Result := A1; IdGlobal.AppendBytes(Result,A2); end; procedure CharArrayToBytes(const AArray : Array of char; var VBytes : TIdBytes; const AIndex : Integer=0); var i, ll, lh : Integer; begin ll := Low( AArray); lh := High( AArray); for i := ll to lh do begin VBytes[i] := Ord( AArray[ i]); end; end; procedure BytesToCharArray(const ABytes : TIdBytes; var VArray : Array of char; const AIndex : Integer=0); var i, ll, lh : Integer; begin ll := Low( VArray); lh := High( Varray); for i := ll to lh do begin VArray[ i] := Char( Abytes[ (i - ll) + AIndex]); end; end; procedure BytesToByteArray(const ABytes : TIdBytes; var VArray : Array of byte; const AIndex : Integer=0); var i, ll, lh : Integer; begin ll := Low(VArray); lh := High(Varray); for i := ll to lh do begin VArray[i] := Abytes[ (i - ll) + AIndex]; end; end; procedure ByteArrayToBytes(const VArray : array of byte; const ABytes : TIdBytes; const AIndex : Integer=0); var i, ll, lh : Integer; begin ll := Low( VArray); lh := High( Varray); for i := ll to lh do begin Abytes[ (i - ll) + AIndex] := VArray[i]; end; end; //--------------------------- //end misc routines function DumpFlags(const ABytes : TIdBytes): String; {$IFDEF USE_INLINE}inline;{$ENDIF} begin Result := DumpFlags( LittleEndianToHost(BytesToLongWord(ABytes))); end; function DumpFlags(const AFlags : LongWord): String; {$IFDEF USE_INLINE}inline;{$ENDIF} begin Result := IntToHex(AFlags,8)+' -'; if AFlags and IdNTLMSSP_NEGOTIATE_UNICODE <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_UNICODE'; end; if AFlags and IdNTLM_NEGOTIATE_OEM <> 0 then begin Result := Result + ' IdNTLM_NEGOTIATE_OEM'; end; if AFlags and IdNTLMSSP_REQUEST_TARGET <> 0 then begin Result := Result + ' IdNTLMSSP_REQUEST_TARGET'; end; if AFlags and IdNTLM_Unknown1 <> 0 then begin Result := Result + ' IdNTLM_Unknown1'; end; if AFlags and IdNTLMSSP_NEGOTIATE_SIGN <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_SIGN'; end; if AFlags and IdNTLMSSP_NEGOTIATE_SEAL <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_SEAL'; end; if AFlags and IdNTLMSSP_NEGOTIATE_DATAGRAM <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_DATAGRAM'; end; if AFlags and IdNTLMSSP_NEGOTIATE_LM_KEY <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_LM_KEY'; end; if AFlags and IdNTLMSSP_NEGOTIATE_NETWARE <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_NETWARE'; end; if AFlags and IdNTLMSSP_NEGOTIATE_NTLM <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_NTLM'; end; if AFlags and IdNTLMSSP_NEGOTIATE_NT_ONLY <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_NT_ONLY'; end; if AFlags and IdNTLMSSP_ANONYMOUS <> 0 then begin Result := Result + ' IdNTLMSSP_ANONYMOUS'; end; if AFlags and IdNTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED'; end; if AFlags and IdNTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED'; end; if AFlags and IdNTLMSSP_NEGOTIATE_LOCAL_CALL <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_LOCAL_CALL'; end; if AFlags and IdNTLMSSP_NEGOTIATE_ALWAYS_SIGN <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_ALWAYS_SIGN'; end; if AFlags and IdNTLMSSP_TARGET_TYPE_DOMAIN <> 0 then begin Result := Result + ' IdNTLMSSP_TARGET_TYPE_DOMAIN'; end; if AFlags and IdNTLMSSP_TARGET_TYPE_SERVER <> 0 then begin Result := Result + ' IdNTLMSSP_TARGET_TYPE_SERVER'; end; if AFlags and IdNTLMSSP_TARGET_TYPE_SHARE <> 0 then begin Result := Result + ' IdNTLMSSP_TARGET_TYPE_SHARE'; end; if AFlags and IdNTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY'; end; if AFlags and IdNTLMSSP_NEGOTIATE_IDENTIFY <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_IDENTIFY'; end; if AFlags and IdNTLMSSP_REQUEST_ACCEPT_RESPONSE <> 0 then begin Result := Result + ' IdNTLMSSP_REQUEST_ACCEPT_RESPONSE'; end; if AFlags and IdIdNTLMSSP_REQUEST_NON_NT_SESSION_KEY <> 0 then begin Result := Result + ' IdIdNTLMSSP_REQUEST_NON_NT_SESSION_KEY'; end; if AFlags and IdNTLMSSP_NEGOTIATE_TARGET_INFO <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_TARGET_INFO'; end; if AFlags and IdNTLM_Unknown4 <> 0 then begin Result := Result + ' IdNTLM_Unknown4'; end; if AFlags and IdNTLMSSP_NEGOTIATE_VERSION <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_VERSION'; end; if AFlags and IdNTLM_Unknown8 <> 0 then begin Result := Result + ' IdNTLM_Unknown8'; end; if AFlags and IdNTLM_Unknown7 <> 0 then begin Result := Result + ' IdNTLM_Unknown7'; end; if AFlags and IdNTLM_Unknown8 <> 0 then begin Result := Result + ' IdNTLM_Unknown8'; end; if AFlags and IdNTLMSSP_NEGOTIATE_128 <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_128'; end; if AFlags and IdNTLMSSP_NEGOTIATE_KEY_EXCH <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_KEY_EXCH'; end; if AFlags and IdNTLMSSP_NEGOTIATE_56 <> 0 then begin Result := Result + ' IdNTLMSSP_NEGOTIATE_56'; end; end; {$IFDEF DOTNET} const DES_ODD_PARITY : array[ 0.. 255] of byte = ( 1, 1, 2, 2, 4, 4, 7, 7, 8, 8, 11, 11, 13, 13, 14, 14, 16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31, 32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47, 49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62, 64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79, 81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94, 97, 97, 98, 98, 100, 100, 103, 103, 104, 104, 107, 107, 109, 109, 110, 110, 112, 112, 115, 115, 117, 117, 118, 118, 121, 121, 122, 122, 124, 124, 127, 127, 128, 128, 131, 131, 133, 133, 134, 134, 137, 137, 138, 138, 140, 140, 143, 143, 145, 145, 146, 146, 148, 148, 151, 151, 152, 152, 155, 155, 157, 157, 158, 158, 161, 161, 162, 162, 164, 164, 167, 167, 168, 168, 171, 171, 173, 173, 174, 174, 176, 176, 179, 179, 181, 181, 182, 182, 185, 185, 186, 186, 188, 188, 191, 191, 193, 193, 194, 194, 196, 196, 199, 199, 200, 200, 203, 203, 205, 205, 206, 206, 208, 208, 211, 211, 213, 213, 214, 214, 217, 217, 218, 218, 220, 220, 223, 223, 224, 224, 227, 227, 229, 229, 230, 230, 233, 233, 234, 234, 236, 236, 239, 239, 241, 241, 242, 242, 244, 244, 247, 247, 248, 248, 251, 251, 253, 253, 254, 254); { IMPORTANT!!! In the NET framework, the DES API will not accept a weak key. Unfortunately, in NTLM's LM password, if a password is less than 8 charactors, the second key is weak. This is one flaw in that protocol. To workaround this, we use a precalculated key of zeros with the parity bit set and encrypt the MAGIC value with it. The Mono framework also does this. } const MAGIC_NUL_KEY : array [ 0.. 7] of byte = ($AA,$D3,$B4,$35,$B5,$14,$04,$EE); {barrowed from OpenSSL source-code - crypto/des/set_key.c 0.9.8g} { I barrowed it since it seems to work better than the NTLM sample code and because Microsoft.NET does not have this functionality when it really should have it. } procedure SetDesKeyOddParity(var VKey : TIdBytes); {$IFDEF USE_INLINE} inline; {$ENDIF} var i, l : Integer; begin l := Length( VKey); for i := 0 to l - 1 do begin VKey[ i] := DES_ODD_PARITY[ VKey[ i]]; end; end; {$ENDIF} procedure GetDomain(const AUserName : String; var VUserName, VDomain : String); {$IFDEF USE_INLINE} inline; {$ENDIF} var i : Integer; begin { Can be like this: DOMAIN\user domain.com\user user@DOMAIN } i := IndyPos('\', AUsername); if i > 0 then begin //was -1 VDomain := Copy( AUsername, 1, i - 1); VUserName := Copy( AUsername, i + 1, Length( AUserName)); end else begin i := IndyPos('@',AUsername); if i > 0 then //was -1 begin VUsername := Copy( AUsername, 1, i - 1); VDomain := Copy( AUsername, i + 1, Length( AUserName)); end else begin VDomain := ''; {do not localize} VUserName := AUserName; end; end; end; {$IFDEF DOTNET} function NTLMFunctionsLoaded : Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} begin Result := True; end; {$ELSE} function NTLMFunctionsLoaded : Boolean; begin Result := IdSSLOpenSSLHeaders.Load; if Result then begin Result := Assigned(des_set_odd_parity) and Assigned(DES_set_key) and Assigned(DES_ecb_encrypt); end; end; function LoadRC4 : Boolean; var h : Integer; begin Result := IdSSLOpenSSLHeaders.Load; if Result then begin h := IdSSLOpenSSLHeaders.GetCryptLibHandle; GRC4_Options := GetProcAddress(h,'RC4_options'); GRC4_set_key := GetProcAddress(h,'RC4_set_key'); GRC4 := GetProcAddress(h,'RC4'); end; Result := RC4FunctionsLoaded; end; function RC4FunctionsLoaded : Boolean; begin Result := Assigned(GRC4_Options) and Assigned(GRC4_set_key) and Assigned(GRC4); end; {$ENDIF} //* create NT hashed password */ function NTOWFv1(const APassword : String): TIdBytes; {$IFDEF USE_INLINE} inline; {$ENDIF} begin CheckMD4Permitted; with TIdHashMessageDigest4.Create do try Result := HashBytes(TIdTextEncoding.Unicode.GetBytes(APassword)); finally Free; end; end; {$IFNDEF DOTNET} {/* * turns a 56 bit key into the 64 bit, odd parity key and sets the key. * The key schedule ks is also set. */} procedure setup_des_key(key_56: des_cblock; Var ks: des_key_schedule); {$IFDEF USE_INLINE}inline;{$ENDIF} var key: des_cblock; begin key[0] := key_56[0]; key[1] := ((key_56[0] SHL 7) and $FF) or (key_56[1] SHR 1); key[2] := ((key_56[1] SHL 6) and $FF) or (key_56[2] SHR 2); key[3] := ((key_56[2] SHL 5) and $FF) or (key_56[3] SHR 3); key[4] := ((key_56[3] SHL 4) and $FF) or (key_56[4] SHR 4); key[5] := ((key_56[4] SHL 3) and $FF) or (key_56[5] SHR 5); key[6] := ((key_56[5] SHL 2) and $FF) or (key_56[6] SHR 6); key[7] := (key_56[6] SHL 1) and $FF; DES_set_odd_parity(@key); DES_set_key(@key, ks); end; //Returns 8 bytes in length procedure _DES(var Res : TIdBytes; const Akey, AData : array of byte; const AKeyIdx, ADataIdx, AResIdx : Integer); var Lks: des_key_schedule; begin setup_des_key(pdes_cblock(@Akey[AKeyIdx])^, Lks); DES_ecb_encrypt(@AData[ADataIdx], Pconst_DES_cblock(@Res[AResIdx]), Lks, DES_ENCRYPT); end; function LMOWFv1(const Passwd, User, UserDom : TIdBytes) : TIdBytes; // ConcatenationOf( DES( UpperCase( Passwd)[0..6],"KGS!@#$%"), // DES( UpperCase( Passwd)[7..13],"KGS!@#$%")) var LBuf : TIdBytes; begin SetLength(Result,16); SetLength(LBuf,14); FillBytes( LBuf, 14, 0); CopyTIdBytes(Passwd,0,LBuf, 0,14); _DES(Result,LBuf, Magic_const,0,0,0); _DES(Result,LBuf, Magic_const,7,0,8); end; {/* * takes a 21 byte array and treats it as 3 56-bit DES keys. The * 8 byte plaintext is encrypted with each key and the resulting 24 * bytes are stored in the results array. */} procedure DESL(const Akeys: TIdBytes; const AServerNonce: TIdBytes; out results: TIdBytes); //procedure DESL(keys: TIdBytes; AServerNonce: TIdBytes; results: TIdBytes); //procedure DESL(keys: TIdBytes; AServerNonce: TIdBytes; results: Pdes_key_schedule); var ks: des_key_schedule; begin SetLength(Results,24); setup_des_key(PDES_cblock(@Akeys[0])^, ks); DES_ecb_encrypt(@AServerNonce[0], Pconst_DES_cblock(results), ks, DES_ENCRYPT); setup_des_key(PDES_cblock(Integer(Akeys) + 7)^, ks); DES_ecb_encrypt(@AServerNonce[0], Pconst_DES_cblock(PtrUInt(results) + 8), ks, DES_ENCRYPT); setup_des_key(PDES_cblock(Integer(Akeys) + 14)^, ks); DES_ecb_encrypt(@AServerNonce[0], Pconst_DES_cblock(PtrUInt(results) + 16), ks, DES_ENCRYPT); end; //* setup LanManager password */ function SetupLMResponse(var vlmHash : TIdBytes; const APassword : String; AServerNonce : TIdBytes): TIdBytes; var lm_hpw : TIdBytes; lm_pw : TIdBytes; ks: des_key_schedule; begin SetLength( lm_hpw,21); FillBytes( lm_hpw, 14, 0); SetLength( lm_pw, 21); FillBytes( lm_pw, 14, 0); SetLength( vlmHash, 16); CopyTIdString( UpperCase( APassword), lm_pw, 0, 14); //* create LanManager hashed password */ setup_des_key(pdes_cblock(@lm_pw[0])^, ks); DES_ecb_encrypt(@magic, pconst_des_cblock(@lm_hpw[0]), ks, DES_ENCRYPT); setup_des_key(pdes_cblock(@lm_pw[7])^, ks); DES_ecb_encrypt(@magic, pconst_des_cblock(@lm_hpw[8]), ks, DES_ENCRYPT); CopyTIdBytes(lm_pw,0,vlmHash,0,16); // FillChar(lm_hpw[17], 5, 0); SetLength(Result,24); DESL(lm_hpw, AServerNonce, Result); // DESL(PDes_cblock(@lm_hpw[0]), AServerNonce, Pdes_key_schedule(@Result[0])); // end; //* create NT hashed password */ function CreateNTLMResponse(var vntlmhash : TIdBytes; const APassword : String; const nonce : TIdBytes): TIdBytes; var nt_pw : TIdBytes; nt_hpw : TIdBytes; //array [1..21] of Char; // nt_hpw128 : TIdBytes; begin CheckMD4Permitted; nt_pw := TIdTextEncoding.Unicode.GetBytes(APassword); with TIdHashMessageDigest4.Create do try vntlmhash := HashBytes(nt_pw); finally Free; end; SetLength( nt_hpw, 21); FillChar( nt_hpw[ 17], 5, 0); CopyTIdBytes( vntlmhash, 0, nt_hpw, 0, 16); // done in DESL SetLength( Result, 24); // DESL(pdes_cblock(@nt_hpw[0]), nonce, Pdes_key_schedule(@Result[0])); DESL(nt_hpw, nonce, Result); end; { function CreateNTLMResponse(const APassword : String; const nonce : TIdBytes): TIdBytes; var nt_pw : TIdBytes; nt_hpw : array [ 1.. 21] of AnsiChar; nt_hpw128 : TIdBytes; begin CheckMD4Permitted; SetLength(Result,24); nt_pw := TIdTextEncoding.Unicode.GetBytes(APassword); with TIdHashMessageDigest4.Create do try nt_hpw128 := HashBytes(nt_pw);//HashString( nt_pw); finally Free; end; Move( nt_hpw128[ 0], nt_hpw[ 1], 16); FillChar( nt_hpw[ 17], 5, 0); DESL(pdes_cblock( @nt_hpw[1]), nonce, Pdes_key_schedule( @Result[ 0])); end; } {$ELSE} procedure setup_des_key(const Akey_56: TIdBytes; out Key : TIdBytes; const AIndex : Integer = 0); {$IFDEF USE_INLINE}inline;{$ENDIF} begin SetLength( key, 8); key[0] := Akey_56[ AIndex]; key[1] := (( Akey_56[ AIndex] SHL 7) and $FF) or (Akey_56[ AIndex + 1] SHR 1); key[2] := (( Akey_56[ AIndex + 1] SHL 6) and $FF) or (Akey_56[ AIndex + 2] SHR 2); key[3] := (( Akey_56[ AIndex + 2] SHL 5) and $FF) or (Akey_56[ AIndex + 3] SHR 3); key[4] := (( Akey_56[ AIndex + 3] SHL 4) and $FF) or (Akey_56[ AIndex + 4] SHR 4); key[5] := (( Akey_56[ AIndex + 4] SHL 3) and $FF) or (Akey_56[ AIndex + 5] SHR 5); key[6] := (( Akey_56[ AIndex + 5] SHL 2) and $FF) or (Akey_56[ AIndex + 6] SHR 6); key[7] := ( AKey_56[ AIndex + 6] SHL 1) and $FF; SetDesKeyOddParity( Key); end; procedure DESL(const Akeys: TIdBytes; const AServerNonce: TIdBytes; out results: TIdBytes); var LKey : TIdBytes; LDes : System.Security.Cryptography.DES; LEnc : ICryptoTransform; begin SetLength( Results, 24); SetLength( LKey, 8); LDes := DESCryptoServiceProvider.Create; LDes.Mode := CipherMode.ECB; LDes.Padding := PaddingMode.None; setup_des_key( AKeys, LKey, 0); LDes.Key := LKey; LEnc := LDes.CreateEncryptor; LEnc.TransformBlock( AServerNonce, 0, 8, Results, 0); setup_des_key( AKeys, LKey, 7); LDes.Key := LKey; LEnc := LDes.CreateEncryptor; LEnc.TransformBlock( AServerNonce, 0, 8, Results, 8); setup_des_key(AKeys,LKey,14); LDes.Key := LKey; LEnc := LDes.CreateEncryptor; LEnc.TransformBlock( AServerNonce, 0, 8, Results, 16); end; function SetupLMResponse(const APassword : String; AServerNonce : TIdBytes): TIdBytes; var lm_hpw : TIdBytes; //array[1..21] of Char; lm_pw : TIdBytes; //array[1..21] of Char; LDes : System.Security.Cryptography.DES; LEnc : ICryptoTransform; LKey : TIdBytes; begin SetLength( lm_hpw,21); FillBytes( lm_hpw, 14, 0); SetLength( lm_pw, 21); FillBytes( lm_pw, 14, 0); CopyTIdString( UpperCase( APassword), lm_pw, 0, 14); LDes := DESCryptoServiceProvider.Create; LDes.Mode := CipherMode.ECB; LDes.Padding := PaddingMode.None; setup_des_key( lm_pw, LKey, 0); LDes.BlockSize := 64; LDes.Key := LKey; LEnc := LDes.CreateEncryptor; LEnc.TransformBlock( MAGIC, 0, 8, lm_hpw, 0); setup_des_key( lm_pw, LKey,7); if Length( APassword) > 7 then begin LDes.Key := LKey; LEnc := LDes.CreateEncryptor; LEnc.TransformBlock( MAGIC, 0, 8, lm_hpw, 8); end else begin CopyTIdBytes( MAGIC_NUL_KEY, 0, lm_hpw, 8, 8); end; DESL( lm_hpw, nonce, Result); end; function CreateNTLMResponse(const APassword : String; const nonce : TIdBytes): TIdBytes; var nt_pw : TIdBytes; nt_hpw : TIdBytes; //array [1..21] of Char; nt_hpw128 : TIdBytes; begin CheckMD4Permitted; nt_pw := System.Text.Encoding.Unicode.GetBytes( APassword); with TIdHashMessageDigest4.Create do try nt_hpw128 := HashString( nt_pw); finally Free; end; SetLength( nt_hpw, 21); FillBytes( nt_hpw, 21, 0); CopyTIdBytes( nt_hpw128, 0, nt_hpw, 0, 16); // done in DESL //SetLength( nt_resp, 24); DESL( nt_hpw,nonce, Result); end; {$ENDIF} procedure AddWord(var VBytes: TIdBytes; const AWord : Word); {$IFDEF USE_INLINE}inline;{$ENDIF} var LBytes : TIdBytes; begin SetLength(LBytes,SizeOf(AWord)); CopyTIdWord(HostToLittleEndian(AWord),LBytes,0); AppendBytes( VBytes,LBytes); end; procedure AddLongWord(var VBytes: TIdBytes; const ALongWord : LongWord); {$IFDEF USE_INLINE}inline;{$ENDIF} var LBytes : TIdBytes; begin SetLength(LBytes,SizeOf(ALongWord)); CopyTIdLongWord(HostToLittleEndian(ALongWord),LBytes,0); AppendBytes( VBytes,LBytes); end; procedure AddInt64(var VBytes: TIdBytes; const AInt64 : Int64); var LBytes : TIdBytes; begin SetLength(LBytes,SizeOf(AInt64)); {$IFDEF ENDIAN_LITTLE} IdGlobal.CopyTIdInt64(AInt64,LBytes,0); {$ELSE} //done this way since we need this in little endian byte-order CopyTIdLongWord(HostToLittleEndian(Lo( AInt64))); CopyTIdLongWord(HostToLittleEndian(Hi( AInt64))); {$ENDIF} AppendBytes( VBytes,LBytes); end; { IMPORTANT!!! I think the time feilds in the NTLM blob are really FILETIME records. MSDN says that a Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC). http://davenport.sourceforge.net/ntlm.html says that the time feild is Little-endian, 64-bit signed value representing the number of tenths of a microsecond since January 1, 1601. In other words, they are the same. We use FILETIME for the API so that we can easily obtain a the timestamp for the blob in Microsoft.NET as well as Delphi (the work on proper format is already done for us. } const NTLMv2_BLOB_Sig : array [0..3] of byte = ($01,$01,$00,$00); NTLMv2_BLOB_Res : array [0..3] of byte = ($00,$00,$00,$00); function IndyByteArrayLength(const ABuffer: array of byte; const ALength: Integer = -1; const AIndex: Integer = 0): Integer; var LAvailable: Integer; begin Assert(AIndex >= 0); LAvailable := IndyMax(Length(ABuffer)-AIndex, 0); if ALength < 0 then begin Result := LAvailable; end else begin Result := IndyMin(LAvailable, ALength); end; end; procedure AddByteArray(var VBytes : TIdBytes; const AToAdd : array of byte; const AIndex: Integer = 0); var LOldLen, LAddLen : Integer; begin LAddLen := IndyByteArrayLength(AToAdd, -1, AIndex); if LAddLen > 0 then begin LOldLen := Length(VBytes); SetLength(VBytes, LOldLen + LAddLen); CopyTIdByteArray(AToAdd, AIndex, VBytes, LOldLen, LAddLen); end; end; {$IFDEF DOTNET} function MakeBlob(const ANTLMTimeStamp : System.Runtime.InteropServices.ComTypes.FileTime; const ATargetInfo : TIdBytes;const cnonce : TIdBytes) : TIdBytes; {$ELSE} function MakeBlob(const ANTLMTimeStamp : FILETIME; const ATargetInfo : TIdBytes;const cnonce : TIdBytes) : TIdBytes; {$ENDIF} begin SetLength(Result,0); //blob signature - offset 0 // RespType - offset 0 // HiRespType - offset 1 // Reserved1 - offset 2 AddByteArray( Result, NTLMv2_BLOB_Sig); // reserved - offset 4 // Reserved2 - offset 4 AddByteArray( Result, NTLMv2_BLOB_Res); // time - offset 8 IdNTLMv2.AddLongWord(Result, ANTLMTimeStamp.dwLowDateTime ); IdNTLMv2.AddLongWord(Result, ANTLMTimeStamp.dwHighDateTime ); //client nonce (challange) // cnonce - offset 16 IdGlobal.AppendBytes(Result,cnonce); // reserved 3 // offset - offset 24 AddLongWord(Result,0); // AddByteArray( Result, NTLMv2_BLOB_Res); // targetinfo - offset 28 // av pairs - offset 28 IdGlobal.AppendBytes(Result,ATargetInfo); // unknown (0 works) AddByteArray( Result, NTLMv2_BLOB_Res); end; function InternalCreateNTLMv2Response(var Vntlm2hash : TIdBytes; const AUsername, ADomain, APassword : String; const ATargetInfo : TIdBytes; const ATimestamp : FILETIME; const cnonce, nonce : TIdBytes): TIdBytes; var LLmUserDom : TIdBytes; Blob : TIdBytes; begin LLmUserDom := TIdTextEncoding.Unicode.GetBytes(UpperCase(AUsername)); AppendBytes(LLmUserDom, TIdTextEncoding.Unicode.GetBytes(ADomain)); with TIdHMACMD5.Create do try Key := NTOWFv1(APassword); Vntlm2hash := HashValue(LLmUserDom); finally Free; end; Blob := MakeBlob(ATimestamp,ATargetInfo,cnonce); with TIdHMACMD5.Create do try Key := Vntlm2hash; Result := HashValue(ConcateBytes(nonce,Blob)); finally Free; end; AppendBytes(Result,Blob); end; function CreateNTLMv2Response(var Vntlm2hash : TIdBytes; const AUsername, ADomain, APassword : String; const TargetName, ATargetInfo : TIdBytes; const cnonce, nonce : TIdBytes): TIdBytes; begin Result := InternalCreateNTLMv2Response(Vntlm2hash, AUsername, ADomain, APassword, ATargetInfo, NowAsFileTime,cnonce, nonce); end; function LMUserSessionKey(const AHash : TIdBytes) : TIdBytes; {$IFDEF USE_INLINE} inline; {$ENDIF} // 1. The 16-byte LM hash (calculated previously) is truncated to 8 bytes. // 2. This is null-padded to 16 bytes. This value is the LM User Session Key. begin SetLength(Result,16); FillBytes(Result,16,0); CopyTIdBytes(AHash,0,Result,0,8); end; function UserNTLMv1SessionKey(const AHash : TIdBytes) : TIdBytes; {$IFDEF USE_INLINE} inline; {$ENDIF} begin CheckMD4Permitted; with TIdHashMessageDigest4.Create do try Result := HashBytes(AHash); finally Free; end; end; function UserLMv2SessionKey(const AHash : TIdBytes; const ABlob : TIdBytes; ACNonce : TIdBytes) : TIdBytes; {$IFDEF USE_INLINE} inline; {$ENDIF} var LBuf : TIdBytes; begin LBuf := ABlob; AppendBytes(LBuf,ACNonce); with TIdHMACMD5.Create do try Key := AHash; Result := HashValue(HashValue(LBuf)); finally Free; end; end; function UserNTLMv2SessionKey(const AHash : TIdBytes; const ABlob : TIdBytes; const AServerNonce : TIdBytes) : TIdBytes; {$IFDEF USE_INLINE} inline; {$ENDIF} //extremely similar to the above except that the nonce is used. begin Result := UserLMv2SessionKey(AHash,ABlob,AServerNonce); end; function UserNTLM2SessionSecSessionKey(const ANTLMv1SessionKey : TIdBytes; const AServerNonce : TIdBytes): TIdBytes; {$IFDEF USE_INLINE} inline; {$ENDIF} begin with TIdHMACMD5.Create do try Key := ANTLMv1SessionKey; Result := HashValue(AServerNonce); finally Free; end; end; function LanManagerSessionKey(const ALMHash : TIdBytes) : TIdBytes; var LKey : TIdBytes; ks : des_key_schedule; LHash8 : TIdBytes; begin LHash8 := ALMHash; SetLength(LHash8,8); SetLength(LKey,14); FillChar(LKey,14,$bd); CopyTIdBytes(LHash8,0,LKey,0,8); SetLength(Result,16); setup_des_key(pdes_cblock(@LKey[0])^, ks); DES_ecb_encrypt(@LHash8, pconst_des_cblock(@Result[0]), ks, DES_ENCRYPT); setup_des_key(pdes_cblock(@LKey[7])^, ks); DES_ecb_encrypt(@LHash8, pconst_des_cblock(@Result[8]), ks, DES_ENCRYPT); end; function SetupLMv2Response(var VntlmHash : TIdBytes; const AUsername, ADomain : String; const APassword : String; cnonce, AServerNonce : TIdBytes): TIdBytes; var LLmUserDom : TIdBytes; LChall : TIdBytes; begin LLmUserDom := TIdTextEncoding.Unicode.GetBytes(UpperCase(AUsername)); AppendBytes(LLmUserDom, TIdTextEncoding.Unicode.GetBytes(ADomain)); with TIdHMACMD5.Create do try Key := NTOWFv1(APassword); VntlmHash := HashValue(LLmUserDom); finally Free; end; LChall := AServerNonce; IdGlobal.AppendBytes(LChall,cnonce); with TIdHMACMD5.Create do try Key := vntlmhash; Result := HashValue(LChall); finally Free; end; AppendBytes(Result,cnonce); end; //function SetupLMResponse(const APassword : String; nonce : TIdBytes): TIdBytes; function CreateModNTLMv1Response(var Vntlmseshash : TIdBytes; const AUsername : String; const APassword : String; cnonce, nonce : TIdBytes; var LMFeild : TIdBytes): TIdBytes; var LChall, LTmp : TIdBytes; lntlmseshash : TIdBytes; LPassHash : TIdBytes; begin CheckMD5Permitted; //LM feild value for Type3 message SetLength(LMFeild,24); FillBytes( LMFeild,24, 0); IdGlobal.CopyTIdBytes(cnonce,0,LMFeild,0,8); // LChall := nonce; IdGlobal.AppendBytes(LChall,cnonce); with TIdHashMessageDigest5.Create do try Vntlmseshash := HashBytes(LChall); //we do this copy because we may need the value later. lntlmseshash := Vntlmseshash; finally Free; end; SetLength(lntlmseshash,8); SetLength(LPassHash,21); FillBytes( LPassHash,21, 0); LTmp := NTOWFv1(APassword); IdGlobal.CopyTIdBytes(LTmp,0,LPassHash,0,Length(LTmp)); {$IFNDEF DOTNET} SetLength(Result,24); DESL( LPassHash,lntlmseshash, Result); // DESL(PDes_cblock(@LPassHash[0]), lntlmseshash, Pdes_key_schedule(@Result[0])); {$ELSE} DESL( LPassHash,ntlmseshash, Result); {$ENDIF} end; //Todo: This does not match the results from //http://davenport.sourceforge.net/ntlm.html function TDateTimeToNTLMTime(const ADateTime : TDateTime):Int64; {$IFDEF USE_INLINE}inline;{$ENDIF} begin Result := DateTimeToUnix((ADateTime+11644473600)* 10000); end; function BuildType1Msg(const ADomain : String = ''; const AHost : String = ''; const ALMCompatibility : LongWord = 0) : TIdBytes; var LDomain, LWorkStation: TIdBytes; LDomLen, LWorkStationLen: Word; LFlags : LongWord; begin SetLength(Result,0); LDomain := TIdTextEncoding.Default.GetBytes(ADomain); //UpperCase(ADomain)); LWorkStation := TIdTextEncoding.Default.GetBytes(AHost); //UpperCase(AHost)); LFlags := IdNTLM_TYPE1_FLAGS_LC2; case ALMCompatibility of 0, 1 : LFlags := IdNTLM_TYPE1_FLAGS; end; LDomLen := Length(LDomain); if LDomLen > 0 then begin LFlags := LFlags or IdNTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED; end; LWorkStationLen := Length(LWorkStation); if LWorkStationLen > 0 then begin LFlags := LFlags or IdNTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED; end; //signature AppendBytes(Result,IdNTLM_SSP_SIG); //type AddLongWord(Result,IdNTLM_TYPE1_MARKER); //flags AddLongWord(Result,LFlags); //Supplied Domain security buffer // - length AddWord(Result,LDomLen); // - allocated space AddWord(Result,LDomLen); // - offset AddLongWord(Result,LWorkStationLen+$20); //Supplied Workstation security buffer (host) // - length AddWord(Result,LWorkStationLen); // - allocated space AddWord(Result,LWorkStationLen); // - offset if LWorkStationLen > 0 then begin AddLongWord(Result,$20); end else begin AddLongWord(Result,$08); end; // Supplied Workstation (host) if LWorkStationLen > 0 then begin AppendBytes(Result,LWorkStation,0,LWorkStationLen); end; // Supplied Domain if LDomLen > 0 then begin AppendBytes(Result,LDomain,0,LDomLen); end; end; procedure ReadType2Msg(const AMsg : TIdBytes; var VFlags : LongWord; var VTargetName : TIdBytes; var VTargetInfo : TIdBytes; var VNonce : TIdBytes ); var LLen : Word; LOfs : LongWord; begin //extract flags VFlags := LittleEndianToHost(BytesToLongWord(AMsg,IdNTLM_TYPE2_FLAGS_OFS)); //extract target name // - security buffer LLen := LittleEndianToHost( BytesToWord(AMsg,IdNTLM_TYPE2_TNAME_LEN_OFS)); LOfs := LittleEndianToHost( BytesToLongWord(AMsg,IdNTLM_TYPE2_TNAME_OFFSET_OFS)); // - the buffer itself SetLength(VTargetName,LLen); CopyTIdBytes(AMsg,LOfs,VTargetName,0,LLen); //extract targetinfo //Note that we should ignore TargetInfo if it is not required. if VFlags and IdNTLMSSP_NEGOTIATE_TARGET_INFO > 0 then begin // - security buffer LLen := LittleEndianToHost( BytesToWord(AMsg,IdNTLM_TYPE2_TINFO_LEN_OFS)); LOfs := LittleEndianToHost( BytesToLongWord(AMsg,IdNTLM_TYPE2_TINFO_OFFSET_OFS)); // - the buffer itself SetLength(VTargetInfo,LLen); CopyTIdBytes(AMsg,LOfs,VTargetInfo,0,LLen); end else begin SetLength(VTargetInfo,0); end; //extract nonce SetLength(VNonce,IdNTLM_NONCE_LEN); CopyTIdBytes(AMsg,IdNTLM_TYPE2_NONCE_OFS,VNonce,0,IdNTLM_NONCE_LEN); end; function CreateData(const ABytes : TIdBytes; const AOffset : LongWord; var VBuffer : TIdBytes) : LongWord; //returns the next buffer value //adds security value ptr to Vbuffer var LLen : Word; begin LLen := Length(ABytes); // - length AddWord(VBuffer,LLen); // - allocated space AddWord(VBuffer,LLen); // - offset AddLongWord(VBuffer,AOffset); Result := AOffset + Llen; end; function GenerateCNonce : TIdBytes; begin SetLength(Result,8); Randomize; Result[0] := Random(127)+1; Result[1] := Random(127)+1; Result[2] := Random(127)+1; Result[3] := Random(127)+1; Result[4] := Random(127)+1; Result[5] := Random(127)+1; Result[6] := Random(127)+1; Result[7] := Random(127)+1; end; const IdNTLM_IGNORE_TYPE_2_3_MASK = not (IdNTLMSSP_TARGET_TYPE_DOMAIN or IdNTLMSSP_TARGET_TYPE_SERVER or IdNTLMSSP_TARGET_TYPE_SHARE); function BuildType3Msg(const ADomain, AHost, AUsername, APassword : String; const AFlags : LongWord; const AServerNonce : TIdBytes; const ATargetName, ATargetInfo : TIdBytes; const ALMCompatibility : LongWord = 0) : TIdBytes; var LDom, LHost, LUser, LLMData, LNTLMData, LCNonce : TIdBytes; llmhash, lntlmhash : TIdBytes; ll_len, ln_len, ld_len, lh_len, lu_len : Word; ll_ofs, ln_ofs, ld_ofs, lh_ofs, lu_ofs : LongWord; LFlags : LongWord; begin LFlags := AFlags and IdNTLM_IGNORE_TYPE_2_3_MASK; if AFlags and IdNTLMSSP_REQUEST_TARGET > 0 then begin LFlags := LFlags or IdNTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED; end; if LFlags and IdNTLMSSP_NEGOTIATE_UNICODE <> 0 then begin if LFlags and IdNTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED > 0 then begin if Length(ATargetName) > 0 then begin LDom := ATargetName; end else begin LDom := TIdTextEncoding.Unicode.GetBytes(UpperCase(ADomain)); end; end; if LFlags and IdNTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED > 0 then begin LHost := TIdTextEncoding.Unicode.GetBytes(UpperCase(AHost)); end; LUser := TIdTextEncoding.Unicode.GetBytes(UpperCase(AUsername)); end else begin if LFlags and IdNTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED > 0 then begin LDom := ToBytes(UpperCase(ADomain)); end; if LFlags and IdNTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED > 0 then begin LHost := ToBytes(UpperCase(AHost)); end; LUser := ToBytes(UpperCase(AUsername)); end; if (ALMCompatibility < 3) and (AFlags and IdNTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY > 0) then begin LCNonce := GenerateCNonce; LNTLMData := CreateModNTLMv1Response(lntlmhash,AUserName,APassword,LCNonce,AServerNonce,LLMData); // LLMData := IdNTLMv2.SetupLMv2Response(AUsername,ADomain,APassword,LCNonce,AServerNonce); // LNTLMData := CreateNTLMv2Response(AUserName,ADomain,APassword,ATargetName,ATargetName, ATargetInfo,LCNonce); end else begin case ALMCompatibility of 0 : begin if AFlags and IdNTLMSSP_NEGOTIATE_NT_ONLY <> 0 then begin SetLength(LLMData,0); end else begin LLMData := SetupLMResponse(llmhash, APassword, AServerNonce); end; LNTLMData := CreateNTLMResponse(lntlmhash, APassword, AServerNonce); end; 1 : begin if AFlags and IdNTLMSSP_NEGOTIATE_NT_ONLY <> 0 then begin SetLength(LLMData,0); end else begin LLMData := SetupLMResponse(llmhash, APassword, AServerNonce); end; LNTLMData := CreateNTLMResponse(lntlmhash,APassword, AServerNonce); end; 2 : //Send NTLM response only begin LNTLMData := CreateNTLMResponse(lntlmhash,APassword, AServerNonce); if AFlags and IdNTLMSSP_NEGOTIATE_NT_ONLY <> 0 then begin SetLength(LLMData,0); end else begin LLMData := LNTLMData; // LLMData := SetupLMResponse(APassword, ANonce); end; end; 3,4,5 : //Send NTLMv2 response only begin // LFlags := LFlags and (not IdNTLMSSP_NEGOTIATE_NTLM); LCNonce := GenerateCNonce; LLMData := IdNTLMv2.SetupLMv2Response(llmhash,AUsername,ADomain,APassword,LCNonce,AServerNonce); LNTLMData := CreateNTLMv2Response(lntlmhash,AUserName,ADomain,APassword,ATargetName,ATargetInfo,LCNonce,AServerNonce); end; // LCNonce := GenerateCNonce; // LNTLMData := IdNTLMv2.CreateModNTLMv1Response(AUserName,APassword,LCNonce,ANonce,LLMData); end; end; //calculations for security buffer pointers //We do things this way because the security buffers are in a different order //than the data buffers themselves. In theory, you could change it but it's //not a good idea. ll_len := Length(LLMData); ln_len := Length(LNTLMData); ld_len := Length(LDom); lh_len := Length(LHost); lu_len := Length(LUser); LFlags := LFlags and (not IdNTLMSSP_NEGOTIATE_VERSION); ld_ofs := IdNTLM_TYPE3_DOM_OFFSET; { if LFlags and IdNTLMSSP_NEGOTIATE_VERSION <> 0 then begin ld_ofs := IdNTLM_TYPE3_DOM_OFFSET + 8; AppendByte(Result, IdNTLM_WINDOWS_MAJOR_VERSION_6); AppendByte(Result, IdNTLM_WINDOWS_MINOR_VERSION_0); AddWord(Result,IdNTLM_WINDOWS_BUILD_ORIG_VISTA); AddLongWord(Result,$F); end; } lu_ofs := ld_len + ld_ofs; lh_ofs := lu_len + lu_ofs; ll_ofs := lh_len + lh_ofs; ln_ofs := ll_len + ll_ofs; SetLength(Result,0); // 0 - signature AppendBytes(Result,IdNTLM_SSP_SIG); // 8 - type AddLongWord(Result,IdNTLM_TYPE3_MARKER); //12 - LM Response Security Buffer: // - length AddWord(Result,ll_len); // - allocated space AddWord(Result,ll_len); // - offset AddLongWord(Result,ll_ofs); //20 - NTLM Response Security Buffer: // - length AddWord(Result,ln_len); // - allocated space AddWord(Result,ln_len); // - offset AddLongWord(Result,ln_ofs); //28 - Domain Name Security Buffer: (target) // - length AddWord(Result,ld_len); // - allocated space AddWord(Result,ld_len); // - offset AddLongWord(Result,ld_ofs); //36 - User Name Security Buffer: // - length AddWord(Result,lu_len); // - allocated space AddWord(Result,lu_len); // - offset AddLongWord(Result,lu_ofs); //44 - Workstation Name (host) Security Buffer: // - length AddWord(Result,lh_len); // - allocated space AddWord(Result,lh_len); // - offset AddLongWord(Result,lh_ofs); //52 - Session Key Security Buffer: // - length AddWord(Result,0); // - allocated space AddWord(Result,0); // - offset AddLongWord(Result,ln_ofs+ln_len); //60 - Flags: //The flags feild is strictly optional. About the only time it matters is //with Datagram authentication. AddLongWord(Result,LFlags); if ld_len > 0 then begin //64 - Domain Name Data ("DOMAIN") AppendBytes(Result,LDom); end; if lu_len >0 then begin //User Name Data ("user") AppendBytes(Result,LUser); end; if lh_len > 0 then begin //Workstation Name Data (host) AppendBytes(Result,LHost); end; //LM Response Data AppendBytes(Result,LLMData); //NTLM Response Data AppendBytes(Result,LNTLMData); end; {$IFDEF TESTSUITE} const TEST_TARGETINFO : array [0..97] of byte = ( $02,$00,$0c,$00,$44,$00,$4f,$00, $4d,$00,$41,$00,$49,$00,$4e,$00, $01,$00,$0c,$00,$53,$00,$45,$00, $52,$00,$56,$00,$45,$00,$52,$00, $04,$00,$14,$00,$64,$00,$6f,$00, $6d,$00,$61,$00,$69,$00,$6e,$00, $2e,$00,$63,$00,$6f,$00,$6d,$00, $03,$00,$22,$00,$73,$00,$65,$00, $72,$00,$76,$00,$65,$00,$72,$00, $2e,$00,$64,$00,$6f,$00,$6d,$00, $61,$00,$69,$00,$6e,$00,$2e,$00, $63,$00,$6f,$00,$6d,$00,$00,$00, $00,$00); {function StrToHex(const AStr : AnsiString) : AnsiString; var i : Integer; begin Result := ''; for i := 1 to Length(AStr) do begin Result := Result + IntToHex(Ord(AStr[i]),2)+ ' '; end; end; } function BytesToHex(const ABytes : array of byte) : String; var i : Integer; begin for i := Low(ABytes) to High(ABytes) do begin Result := Result + IntToHex(ABytes[i],2)+ ' '; end; end; procedure DoDavePortTests; var LNonce,LCNonce, lmhash : TIdBytes; LMResp : TIdBytes; LTargetINfo : TIdBytes; Ltst : String; begin SetLength(LNonce,8); LNonce[0] := $01; LNonce[1] := $23; LNonce[2] := $45; LNonce[3] := $67; LNonce[4] := $89; LNonce[5] := $ab; LNonce[6] := $cd; LNonce[7] := $ef; SetLength(LCNonce,8); LCNonce[0] := $ff; LCNonce[1] := $ff; LCNonce[2] := $ff; LCNonce[3] := $00; LCNonce[4] := $11; LCNonce[5] := $22; LCNonce[6] := $33; LCNonce[7] := $44; SetLength(LTargetInfo,Length(TEST_TARGETINFO)); CopyTIdByteArray(TEST_TARGETINFO,0,LTargetInfo,0,Length(TEST_TARGETINFO)); if ToHex(SetupLMResponse(lmhash,'SecREt01',LNonce)) <> 'C337CD5CBD44FC9782A667AF6D427C6DE67C20C2D3E77C56' then begin DebugOutput(BytesToHex(LNonce)); raise Exception.Create('LM Response test failed'); end; if ToHex(CreateNTLMResponse(lmhash,'SecREt01',LNonce)) <> '25A98C1C31E81847466B29B2DF4680F39958FB8C213A9CC6' then begin raise Exception.Create('NTLM Response test failed'); end; if ToHex(CreateModNTLMv1Response(lmhash,'user','SecREt01',LCNonce,LNonce,LMResp)) <> '10D550832D12B2CCB79D5AD1F4EED3DF82ACA4C3681DD455' then begin raise Exception.Create ('NTLM2 Session Response failed'); end; if ToHex(LMResp) <> 'FFFFFF001122334400000000000000000000000000000000' then begin raise Exception.Create ('LM Response for NTLM2 reponse failed'); end; if ToHex(SetupLMv2Response(lmhash,'user','DOMAIN','SecREt01',LCNonce,LNonce)) <> 'D6E6152EA25D03B7C6BA6629C2D6AAF0FFFFFF0011223344' then begin raise Exception.Create ( 'LMv2 Response failed'); end; Ltst := ToHex(InternalCreateNTLMv2Response(lmhash,'user','DOMAIN','SecREt01',LTargetInfo,UnixTimeToFileTime(1055844000),LCNonce,LNonce )); if LTst <> 'CBABBCA713EB795D04C97ABC01EE4983'+ '01010000000000000090D336B734C301'+ 'FFFFFF00112233440000000002000C00' + '44004F004D00410049004E0001000C00' + '53004500520056004500520004001400' + '64006F006D00610069006E002E006300' + '6F006D00030022007300650072007600' + '650072002E0064006F006D0061006900' + '6E002E0063006F006D00000000000000' + '0000' then begin raise Exception.Create ('NTLMv2 Response failed' ); end; end; function ConstArray(const AArray : array of byte) : TIdBytes; var i : Integer; begin SetLength(Result,0); for i := Low(AArray) to High(AArray) do begin AppendByte(Result,AArray[i]); end; end; { Microsoft tests User 0000000: 55 00 73 00 65 00 72 00 U.s.e.r. 0000000: 55 00 53 00 45 00 52 00 U.S.E.R. 0000000: 55 73 65 72 User UserDom 0000000: 44 00 6f 00 6d 00 61 00 69 00 6e 00 D.o.m.a.i.n Password 0000000: 50 00 61 00 73 00 73 00 77 00 6f 00 72 00 64 00 P.a.s.s.w.o.r.d. 0000000: 50 41 53 53 57 4f 52 44 00 00 00 00 00 00 PASSWORD...... Server Name 00000000: 53 00 65 00 72 00 76 00 65 00 72 00 S.e.r.v.e.r. Workstation Name 0000000: 43 00 4f 00 4d 00 50 00 55 00 54 00 45 00 52 00 C.O.M.P.U.T.E.R. Random Session Key 0000000: 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 UUUUUUUUUUUUUUUU Time 0000000: 00 00 00 00 00 00 00 00 ........ Client Challange 0000000: aa aa aa aa aa aa aa aa ........ Server Challange 0000000: 01 23 45 67 89 ab cd ef .#Eg..&#x2550;. 4.2.2 NTLM v1 Authentication # NTLMSSP_NEGOTIATE_KEY_EXCH # NTLMSSP_NEGOTIATE_56 # NTLMSSP_NEGOTIATE_128 # NTLMSSP_NEGOTIATE_VERSION # NTLMSSP_TARGET_TYPE_SERVER # NTLMSSP_NEGOTIATE_ALWAYS_SIGN # NTLM NTLMSSP_NEGOTIATE_NTLM # NTLMSSP_NEGOTIATE_SEAL # NTLMSSP_NEGOTIATE_SIGN # NTLM_NEGOTIATE_OEM # NTLMSSP_NEGOTIATE_UNICOD NTLMv1 data flags 33 82 02 e2 } procedure DoMSTests; var LFlags : LongWord; begin LFlags := IdNTLMSSP_NEGOTIATE_KEY_EXCH or IdNTLMSSP_NEGOTIATE_56 or IdNTLMSSP_NEGOTIATE_128 or IdNTLMSSP_NEGOTIATE_VERSION or IdNTLMSSP_TARGET_TYPE_SERVER or IdNTLMSSP_NEGOTIATE_ALWAYS_SIGN or IdNTLMSSP_NEGOTIATE_NTLM or IdNTLMSSP_NEGOTIATE_SEAL or IdNTLMSSP_NEGOTIATE_SIGN or IdNTLM_NEGOTIATE_OEM or IdNTLMSSP_NEGOTIATE_UNICODE; if ToHex(ToBytes(LFlags))<>'338202E2' then begin raise Exception.Create('MS Tests failed - NTLMv1 data flags'); end; // if ToHex(NTOWFv1('Password') ) <> UpperCase('e52cac67419a9a224a3b108f3fa6cb6d') then if ToHex(LMOWFv1( IndyASCIIEncoding.GetBytes(Uppercase( 'Password')), IndyASCIIEncoding.GetBytes(Uppercase( 'User')), IndyASCIIEncoding.GetBytes(Uppercase( 'Domain')))) <> Uppercase('e52cac67419a9a224a3b108f3fa6cb6d') then begin raise Exception.Create('MS Tests failed - LMOWFv1'); end; end; procedure TestNTLM; begin // DoMSTests; DoDavePortTests; end; {$ENDIF} initialization SetLength(IdNTLM_SSP_SIG,8); IdNTLM_SSP_SIG[0] :=$4e; //N IdNTLM_SSP_SIG[1] :=$54; //T IdNTLM_SSP_SIG[2] :=$4c; //L IdNTLM_SSP_SIG[3] :=$4d; //M IdNTLM_SSP_SIG[4] :=$53; //S IdNTLM_SSP_SIG[5] :=$53; //S IdNTLM_SSP_SIG[6] :=$50; //P IdNTLM_SSP_SIG[7] :=$00; //#00 UnixEpoch := EncodeDate(1970, 1, 1); end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.HttpServer.Response Description : Http Server Response Author : Kike Pérez Version : 1.0 Created : 30/08/2019 Modified : 06/10/2019 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.HttpServer.Response; {$i QuickLib.inc} interface uses Classes, SysUtils, Quick.Value, Quick.Commons; type IHttpResponse = interface ['{3E90F34D-5F4D-41E5-89C5-CA9832C7405E}'] procedure SetStatusCode(const Value: Cardinal); procedure SetStatusText(const Value: string); function GetStatusCode: Cardinal; function GetStatusText: string; function GetHeaders: TPairList; procedure SetHeaders(const Value: TPairList); function GetContentStream: TStream; procedure SetContentStream(const Value: TStream); function GetContentText: string; procedure SetContentText(const Value: string); function GetContentType: string; procedure SetContentType(const Value: string); property Headers : TPairList read GetHeaders write SetHeaders; property StatusCode : Cardinal read GetStatusCode write SetStatusCode; property StatusText : string read GetStatusText write SetStatusText; property Content : TStream read GetContentStream write SetContentStream; property ContentText : string read GetContentText write SetContentText; property ContentType : string read GetContentType write SetContentType; end; {$M+} THttpResponse = class(TInterfacedObject,IHttpResponse) private fHeaders : TPairList; fStatusText: string; fStatusCode: Cardinal; fContentText : string; fContent : TStream; fContentType : string; procedure SetStatusCode(const Value: Cardinal); procedure SetStatusText(const Value: string); function GetStatusCode: Cardinal; function GetStatusText: string; function GetContentText: string; function GetContentStream: TStream; procedure SetContentText(const Value: string); procedure SetContentStream(const Value: TStream); function GetHeaders: TPairList; procedure SetHeaders(const Value: TPairList); function GetContentType: string; procedure SetContentType(const Value: string); public constructor Create; destructor Destroy; override; procedure ContentFromStream(const Value: TStream); published property Headers : TPairList read GetHeaders write SetHeaders; property StatusCode : Cardinal read GetStatusCode write SetStatusCode; property StatusText : string read GetStatusText write SetStatusText; property Content : TStream read GetContentStream write SetContentStream; property ContentText : string read GetContentText write SetContentText; property ContentType : string read GetContentType write SetContentType; end; {$M-} implementation { THttpResponse } constructor THttpResponse.Create; begin fContentText := ''; fContent := nil; fStatusCode := 200; fStatusText := ''; //add custom header to response fHeaders := TPairList.Create; fHeaders.Add('Server','QuickHttpServer'); end; destructor THttpResponse.Destroy; begin fHeaders.Free; if Assigned(fContent) and (fContent <> nil) then fContent.Free; inherited; end; function THttpResponse.GetContentStream: TStream; begin Result := fContent; end; function THttpResponse.GetContentText: string; begin Result := fContentText; end; function THttpResponse.GetContentType: string; begin Result := fContentType; end; function THttpResponse.GetHeaders: TPairList; begin Result := fHeaders; end; function THttpResponse.GetStatusCode: Cardinal; begin Result := fStatusCode; end; function THttpResponse.GetStatusText: string; begin Result := fStatusText; end; procedure THttpResponse.SetStatusCode(const Value: Cardinal); begin fStatusCode := Value; end; procedure THttpResponse.SetStatusText(const Value: string); begin fStatusText := Value; end; procedure THttpResponse.SetContentStream(const Value: TStream); begin fContent := Value; end; procedure THttpResponse.SetContentText(const Value: string); begin fContentText := Value; end; procedure THttpResponse.SetContentType(const Value: string); begin fContentType := Value; end; procedure THttpResponse.SetHeaders(const Value: TPairList); begin fHeaders := Value; end; procedure THttpResponse.ContentFromStream(const Value: TStream); begin if Value <> nil then begin if fContent = nil then fContent := TMemoryStream.Create; fContent.CopyFrom(Value,Value.Size); end else fContent := nil; end; end.
{ @abstract(@name contains the main form of Help Generator and a class for saving and restoring project settings.) @author(Richard B. Winston <rbwinst@usgs.gov>) @created(2004-11-28) @lastmod(2005-5-16) @name contains the main form of Help Generator. It also defines @link(THelpGeneratorProjectOptions) which is used to save project options to a file and restore them again. This file is made available by the U.S. Geological Survey (USGS) to be used in the public interest and the advancement of science. You may, without any fee or cost, use, copy, modify, or distribute this file, and any derivative works thereof, and its supporting documentation, subject to the following restrictions and understandings. If you distribute copies or modifications of this file and related material, make sure the recipients receive a copy of this notice and receive or can get a copy of the original distribution. If the software and (or) related material are modified and distributed, it must be made clear that the recipients do not have the original and are informed of the extent of the modifications. For example, modified files must include a prominent notice stating the modifications, author, and date. This restriction is necessary to guard against problems introduced in the software by others, reflecting negatively on the reputation of the USGS. This file is public property. You may charge fees for distribution, warranties, and services provided in connection with this file or derivative works thereof. The name USGS can be used in any advertising or publicity to endorse or promote any products or commercial entity using this software if specific written permission is obtained from the USGS. The user agrees to appropriately acknowledge the authors and the USGS in publications that result from the use of this file or in products that include this file in whole or in part. Because the software and related material is free (other than nominal materials and handling fees) and provided "as is", the authors, USGS, or the United States Government have made no warranty, expressed or implied, as to the accuracy or completeness and are not obligated to provide the user with any support, consulting, training or assistance of any kind with regard to the use, operation, and performance of this software nor to provide the user with any updates, revisions, new versions or "bug fixes". The user assumes all risk for any damages whatsoever resulting from loss of use, data, or profits arising in connection with the access, use, quality, or performance of this software. } unit frmHelpGeneratorCLX_Unit; interface uses {$IFDEF LINUX} Libc, {$ENDIF} {$IFDEF MSWINDOWS} Windows, ShellAPI, Qt, {$ENDIF} WebUtils, SysUtils, Types, Classes, Variants, QTypes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls, QMenus, QCheckLst, QButtons, QExtCtrls, PasDoc_Gen, PasDoc_GenHtml, PasDoc_Base, PasDoc_Types, PasDoc_Languages, PasDoc_GenHtmlHelp, PasDoc_GenLatex, CustomProjectOptions, QFileCtrls, ConsolProjectOptionsUnit; type // @abstract(TfrmHelpGenerator is the class of the main form of Help // Generator.) Its published fields are mainly components that are used to // save the project settings. TfrmHelpGenerator = class(TForm) // @name is the main workhorse of @classname. It analyzes the source // code and cooperates with @link(HtmlDocGenerator) // and @link(TexDocGenerator) to create the output. PasDoc1: TPasDoc; // @name generates HTML output. HtmlDocGenerator: THTMLDocGenerator; OpenDialog1: TOpenDialog; pcMain: TPageControl; tabGenerate: TTabSheet; // memoMessages displays compiler warnings. See also @link(seVerbosity); memoMessages: TMemo; tabOptions: TTabSheet; // @name controls whether of private, protected, public, published and // automated properties, methods, events, and fields will be included in // generated output. clbMethodVisibility: TCheckListBox; Label1: TLabel; // @name is used to set the language in which the web page will // be written. Of course, this only affects tha language for the text // generated by the program, not the comments about the program. comboLanguages: TComboBox; Label2: TLabel; tabSourceFiles: TTabSheet; // @name holds the complete paths of all the source files // in the project. memoFiles: TMemo; Panel3: TPanel; // Click @name to select one or more sorce files for the // project. btnBrowseSourceFiles: TButton; // @name has the path of the directory where the web files will // be created. edOutput: TEdit; Label3: TLabel; Panel1: TPanel; btnGenerate: TButton; tabIncludeDirectories: TTabSheet; // The lines in @name are the paths of the files that // may have include files that are part of the project. memoIncludeDirectories: TMemo; Panel2: TPanel; // Click @name to select a directory that may // have include directories. btnBrowseIncludeDirectory: TButton; // Click @name to select the directory in whick the // output files will be created. btnBrowseOutputDirectory: TButton; Label6: TLabel; // @name is used to set the name of the project. edProjectName: TEdit; SaveDialog1: TSaveDialog; OpenDialog2: TOpenDialog; MainMenu1: TMainMenu; miFile: TMenuItem; Open1: TMenuItem; Save1: TMenuItem; Exit1: TMenuItem; Panel4: TPanel; // @name controls the severity of the messages that are displayed. seVerbosity: TSpinEdit; Label7: TLabel; Panel5: TPanel; Label8: TLabel; Panel6: TPanel; Label9: TLabel; Panel7: TPanel; Label10: TLabel; // @name determines what sort of files will be created comboGenerateFormat: TComboBox; Label11: TLabel; New1: TMenuItem; // @name generates Latex output. TexDocGenerator: TTexDocGenerator; tabDefines: TTabSheet; memoDefines: TMemo; About1: TMenuItem; // @name generates HTML-help project output. HTMLHelpDocGenerator: THTMLHelpDocGenerator; edIntroduction: TEdit; Label13: TLabel; btnIntroduction: TButton; edConclusion: TEdit; Label14: TLabel; btnConclusion: TButton; odExtraFiles: TOpenDialog; tabMoreOptions: TTabSheet; cbUseGraphVizClasses: TCheckBox; cbUseGraphVizUses: TCheckBox; edGraphVizDotLocation: TEdit; btnGraphViz: TButton; Label15: TLabel; odDotLocation: TOpenDialog; memoHyphenatedWords: TMemo; Label16: TLabel; rgLineBreakQuality: TRadioGroup; Label4: TLabel; memoHeader: TMemo; memoFooter: TMemo; Label5: TLabel; Label17: TLabel; edTitle: TEdit; miHelp: TMenuItem; Help2: TMenuItem; Label18: TLabel; comboLatexGraphics: TComboBox; Label12: TLabel; edBrowser: TEdit; Button1: TButton; BrowserDialog: TOpenDialog; Label19: TLabel; procedure PasDoc1Warning(const MessageType: TMessageType; const AMessage: string; const AVerbosity: Cardinal); procedure btnBrowseSourceFilesClick(Sender: TObject); procedure clbMethodVisibilityClickCheck(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnGenerateClick(Sender: TObject); procedure comboLanguagesChange(Sender: TObject); procedure btnBrowseIncludeDirectoryClick(Sender: TObject); procedure btnBrowseOutputDirectoryClick(Sender: TObject); procedure Open1Click(Sender: TObject); procedure Save1Click(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure edProjectNameChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure New1Click(Sender: TObject); procedure comboGenerateFormatChange(Sender: TObject); procedure About1Click(Sender: TObject); procedure btnIntroductionClick(Sender: TObject); procedure btnConclusionClick(Sender: TObject); procedure btnGraphVizClick(Sender: TObject); procedure cbUseGraphVizClick(Sender: TObject); procedure edGraphVizDotLocationChange(Sender: TObject); procedure Help2Click(Sender: TObject); procedure pcMainChange(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure pcMainChanging(Sender: TObject; var AllowChange: Boolean); procedure pcMainPageChanging(Sender: TObject; NewPage: TTabSheet; var AllowChange: Boolean); procedure seVerbosityChanged(Sender: TObject; NewValue: Integer); procedure Button1Click(Sender: TObject); private // @name is @true when the user has changed the project settings. // Otherwise it is @false. Changed: boolean; DefaultDirectives: TStringList; procedure SaveChanges(var Action: TCloseAction); procedure SetDefaults; procedure SetEdVizGraphDotLocationColor; function SaveIt: boolean; procedure VisGraphMessage(const AMessage: string); { Private declarations } public { Public declarations } end; {@abstract(@classname is used to store and retrieve the settings of a project.) Each published property reads or writes a property of @link(frmHelpGenerator). It also inherits methods for running the TPasDoc component.} THelpGeneratorProjectOptions = class(TCustomHelpProjectOptions) protected function GetChanged: boolean; override; function GetConclusion: string; override; function GetDirectives: TSTrings; override; function GetFooter: TStrings; override; function GetGraphVizDotLocation: string; override; function GetHeader: TStrings; override; function GetHtmlDocGeneratorComponent: THtmlDocGenerator; override; function GetHTMLHelpDocGeneratorComponent: THTMLHelpDocGenerator; override; function GetHyphenatedWords: TStrings; override; function GetIncludeAutomated: boolean; override; function GetIncludeDirectories: TStrings; override; function GetIncludeImplicit: boolean; override; function GetIncludePrivate: boolean; override; function GetIncludeProtected: boolean; override; function GetIncludePublic: boolean; override; function GetIncludePublished: boolean; override; function GetIncludeStrictPrivate: boolean; override; function GetIncludeStrictProtected: boolean; override; function GetIntroduction: string; override; function GetLanguage: TLanguageID; override; function GetLatexGraphicsPackage: TLatexGraphicsPackage; override; function GetLineBreakQuality: TLineBreakQuality; override; function GetOutputDirectory: string; override; function GetOutputType: TOutputType; override; function GetPasDocComponent: TPasDoc; override; function GetProjectName: string; override; function GetSourceFiles: TStrings; override; function GetTexDocGeneratorComponent: TTexDocGenerator; override; function GetTitle: string; override; function GetUseGraphVizClasses: boolean; override; function GetUseGraphVizUses: boolean; override; function GetVerbosity: integer; override; procedure SetChanged(const Value: boolean); override; procedure SetConclusion(const Value: string); override; procedure SetDefaultActivePage; override; procedure SetDirectives(const Value: TSTrings); override; procedure SetFooter(const Value: TStrings); override; procedure SetGraphVizDotLocation(const Value: string); override; procedure SetHeader(const Value: TStrings); override; procedure SetHyphenatedWords(const Value: TStrings); override; procedure SetIncludeAutomated(const Value: boolean); override; procedure SetIncludeDirectories(const Value: TStrings); override; procedure SetIncludeImplicit(const Value: boolean); override; procedure SetIncludeStrictPrivate(const Value: boolean); override; procedure SetIncludePrivate(const Value: boolean); override; procedure SetIncludeStrictProtected(const Value: boolean); override; procedure SetIncludeProtected(const Value: boolean); override; procedure SetIncludePublic(const Value: boolean); override; procedure SetIncludePublished(const Value: boolean); override; procedure SetIntroduction(const Value: string); override; procedure SetLanguage(const Value: TLanguageID); override; procedure SetLatexGraphicsPackage(const Value: TLatexGraphicsPackage); override; procedure SetLineBreakQuality(const Value: TLineBreakQuality); override; procedure SetOutputDirectory(const Value: string); override; procedure SetOutputType(const Value: TOutputType); override; procedure SetProjectName(const Value: string); override; procedure SetSourceFiles(const Value: TStrings); override; procedure SetTitle(const Value: string); override; procedure SetUseGraphVizClasses(const Value: boolean); override; procedure SetUseGraphVizUses(const Value: boolean); override; procedure SetVerbosity(const Value: integer); override; end; // @name saves the location of the VizGraph dot program. T_CLX_Ini = class(TCustomIniFile) private FPasDocConsoleLocation: string; protected function GetGraphVizDotLocation: string; override; procedure SetGraphVizDotLocation(const Value: string); override; function GetBrowserLocation: string; override; procedure SetBrowserLocation(const Value: string); override; function GetPasDocConsoleLocation: string; override; procedure SetPasDocConsoleLocation(const Value: string); override; end; var // @name is the main form of Help Generator frmHelpGenerator: TfrmHelpGenerator; implementation {$R *.xfm} uses PasDoc_Items, frmAboutCLX_Unit; procedure TfrmHelpGenerator.PasDoc1Warning(const MessageType: TMessageType; const AMessage: string; const AVerbosity: Cardinal); begin memoMessages.Lines.Add(AMessage); Application.ProcessMessages; end; procedure TfrmHelpGenerator.VisGraphMessage(const AMessage: string); begin memoMessages.Lines.Add(AMessage); end; procedure TfrmHelpGenerator.btnBrowseSourceFilesClick(Sender: TObject); var Directory: string; FileIndex: integer; Files: TStringList; begin if OpenDialog1.Execute then begin Files := TStringList.Create; try if edOutput.Text = '' then begin edOutput.Text := ExtractFileDir(OpenDialog1.FileName); end; Files.Sorted := True; Files.Duplicates := dupIgnore; Files.AddStrings(memoFiles.Lines); Files.AddStrings(OpenDialog1.Files); memoFiles.Lines := Files; for FileIndex := 0 to OpenDialog1.Files.Count - 1 do begin Directory := ExtractFileDir(OpenDialog1.Files[FileIndex]); if memoIncludeDirectories.Lines.IndexOf(Directory) < 0 then begin memoIncludeDirectories.Lines.Add(Directory); end; end; finally Files.Free; end; end; end; procedure TfrmHelpGenerator.clbMethodVisibilityClickCheck(Sender: TObject); begin Changed := True; end; procedure TfrmHelpGenerator.SetDefaults; var ProjectOptions: THelpGeneratorProjectOptions; begin ProjectOptions := THelpGeneratorProjectOptions.Create(nil); try ProjectOptions.SetDefaults; finally ProjectOptions.Free; end; end; procedure TfrmHelpGenerator.FormCreate(Sender: TObject); var LanguageIndex: TLanguageID; begin { $IFDEF MSWINDOWS} ReadIniFile(T_CLX_Ini); { $ENDIF} {$IFDEF LINUX} odDotLocation.Filter := '(dot)|dot'; {$ENDIF} THelpGeneratorProjectOptions.DefaultDefines(memoDefines.Lines); comboLanguages.Items.Capacity := Ord(High(LanguageIndex)) - Ord(Low(TLanguageID)) + 1; for LanguageIndex := Low(TLanguageID) to High(LanguageIndex) do begin comboLanguages.Items.Add(LANGUAGE_ARRAY[LanguageIndex].Name); end; GetVisibilityNames(clbMethodVisibility.Items); Constraints.MinWidth := Width; Constraints.MinHeight := Height; DefaultDirectives := TStringList.Create; DefaultDirectives.Assign(memoDefines.Lines); SetDefaults; end; procedure TfrmHelpGenerator.comboLanguagesChange(Sender: TObject); begin Changed := True; end; procedure TfrmHelpGenerator.btnGenerateClick(Sender: TObject); var URL: string; BrowserPath: string; Settings: THelpGeneratorProjectOptions; begin {$IFDEF MSWINDOWS} if (cbUseGraphVizUses.Checked or cbUseGraphVizClasses.Checked) and not FileExists(edGraphVizDotLocation.Text) then begin if MessageDlg('The location of the VizGraph "dot" program was not' + ' found. Do you want to continue?', QDialogs.mtWarning, [mbYes, mbNo], 0) <> mrYes then begin Exit; end; end; {$ENDIF} Screen.Cursor := crHourGlass; btnGenerate.Enabled := False; miFile.Enabled := False; miHelp.Enabled := False; try memoMessages.Clear; Settings := THelpGeneratorProjectOptions.Create(nil); try Settings.RunPasDoc; Settings.RunVizGraph(VisGraphMessage); finally Settings.Free; end; if comboGenerateFormat.ItemIndex in [0, 1] then begin URL := FileToURL(PasDoc1.Generator.DestinationDirectory + 'index.html'); BrowserPath := edBrowser.Text; LaunchURL(BrowserPath, URL); end; finally Screen.Cursor := crDefault; btnGenerate.Enabled := True; miFile.Enabled := True; miHelp.Enabled := True; end; end; procedure TfrmHelpGenerator.btnBrowseIncludeDirectoryClick( Sender: TObject); var directory: WideString; begin // directory is an out variable so it doesn't need to be // specified before calling SelectDirectory. if SelectDirectory('Include directory', '', directory) then begin if memoIncludeDirectories.Lines.IndexOf(directory) < 0 then begin memoIncludeDirectories.Lines.Add(directory); end else begin MessageDlg('The directory you selected, (' + directory + ') is already included.', QDialogs.mtInformation, [mbOK], 0); end; end; end; procedure TfrmHelpGenerator.btnBrowseOutputDirectoryClick(Sender: TObject); var directory: WideString; begin // directory is an out variable so it doesn't need to be // specified before calling SelectDirectory. if SelectDirectory('Output directory', '', directory) then begin edOutput.Text := directory; Changed := True; end; end; procedure TfrmHelpGenerator.Open1Click(Sender: TObject); var Settings: THelpGeneratorProjectOptions; Action: TCloseAction; begin if Changed then begin Action := caFree; SaveChanges(Action); if Action = caNone then begin Exit; end; end; if OpenDialog2.Execute then begin SaveDialog1.FileName := OpenDialog2.FileName; Settings := THelpGeneratorProjectOptions.Create(nil); try Settings.ReadFromComponentFile(OpenDialog2.FileName); Caption := ExtractFileName(OpenDialog2.FileName) + ': Help Generator'; finally Settings.Free; end; Changed := False; end; end; function TfrmHelpGenerator.SaveIt: boolean; var Settings: THelpGeneratorProjectOptions; begin result := SaveDialog1.Execute; if result then begin Settings := THelpGeneratorProjectOptions.Create(nil); try Settings.SaveToComponentFile(SaveDialog1.FileName); finally Settings.Free; end; Changed := False; end; end; procedure TfrmHelpGenerator.Exit1Click(Sender: TObject); begin Close end; procedure TfrmHelpGenerator.edProjectNameChange(Sender: TObject); begin Changed := True; end; procedure TfrmHelpGenerator.SaveChanges(var Action: TCloseAction); var MessageResult: integer; begin if Changed then begin MessageResult := MessageDlg( 'Do you want to save the settings for this project?', QDialogs.mtInformation, [mbYes, mbNo, mbCancel], 0); case MessageResult of mrYes: begin if not SaveIt then begin Action := caNone; end; end; mrNo: begin // do nothing. end; else begin Action := caNone; end; end; end; end; procedure TfrmHelpGenerator.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveChanges(Action); if Action <> caNone then begin DefaultDirectives.Free; end; end; procedure TfrmHelpGenerator.New1Click(Sender: TObject); var Action: TCloseAction; begin Action := caHide; if Changed then begin SaveChanges(Action); if Action = caNone then Exit; end; SetDefaults; edProjectName.Text := ''; edTitle.Text := ''; edOutput.Text := ''; seVerbosity.Value := 2; comboGenerateFormat.ItemIndex := 0; memoFiles.Clear; memoIncludeDirectories.Clear; memoMessages.Clear; rgLineBreakQuality.ItemIndex := 0; memoDefines.Lines.Assign(DefaultDirectives); Changed := False; end; procedure TfrmHelpGenerator.seVerbosityChanged(Sender: TObject; NewValue: Integer); begin Changed := True; end; procedure TfrmHelpGenerator.btnIntroductionClick(Sender: TObject); begin if edIntroduction.Text <> '' then begin odExtraFiles.FileName := edIntroduction.Text; end; if odExtraFiles.Execute then begin edIntroduction.Text := odExtraFiles.FileName; Changed := True; end; end; procedure TfrmHelpGenerator.btnConclusionClick(Sender: TObject); begin if edConclusion.Text <> '' then begin odExtraFiles.FileName := edConclusion.Text; end; if odExtraFiles.Execute then begin edConclusion.Text := odExtraFiles.FileName; Changed := True; end; end; procedure TfrmHelpGenerator.cbUseGraphVizClick(Sender: TObject); begin Changed := True; edGraphVizDotLocation.Enabled := cbUseGraphVizUses.Checked or cbUseGraphVizClasses.Checked; btnGraphViz.Enabled := edGraphVizDotLocation.Enabled; SetEdVizGraphDotLocationColor; end; procedure TfrmHelpGenerator.btnGraphVizClick(Sender: TObject); begin if edGraphVizDotLocation.Text <> '' then begin odDotLocation.FileName := edGraphVizDotLocation.Text; end; if odDotLocation.Execute then begin edGraphVizDotLocation.Text := odDotLocation.FileName; Changed := True; SetEdVizGraphDotLocationColor; end; end; procedure TfrmHelpGenerator.pcMainPageChanging(Sender: TObject; NewPage: TTabSheet; var AllowChange: Boolean); begin HelpKeyword := NewPage.HelpKeyword; end; procedure TfrmHelpGenerator.About1Click(Sender: TObject); begin frmAbout.ShowModal; end; procedure TfrmHelpGenerator.Help2Click(Sender: TObject); begin Application.KeywordHelp(HelpKeyWord); end; procedure TfrmHelpGenerator.pcMainChanging(Sender: TObject; var AllowChange: Boolean); begin AllowChange := btnGenerate.Enabled; end; procedure TfrmHelpGenerator.comboGenerateFormatChange(Sender: TObject); begin Changed := True; memoHeader.Enabled := (comboGenerateFormat.ItemIndex in [0, 1]); memoFooter.Enabled := memoHeader.Enabled; if memoHeader.Enabled then begin memoHeader.Color := clBase; memoFooter.Color := clBase; end else begin memoHeader.Color := clButton; memoFooter.Color := clButton; end; rgLineBreakQuality.Enabled := (comboGenerateFormat.ItemIndex in [2, 3]); memoHyphenatedWords.Enabled := rgLineBreakQuality.Enabled; // This also sets the color of comboLatexGraphics comboLatexGraphics.Enabled := rgLineBreakQuality.Enabled; if memoHyphenatedWords.Enabled then begin memoHyphenatedWords.Color := clBase; end else begin memoHyphenatedWords.Color := clButton; end; end; procedure TfrmHelpGenerator.FormDestroy(Sender: TObject); begin { $IFDEF MSWINDOWS} WriteIniFile(T_CLX_Ini); { $ENDIF} end; procedure TfrmHelpGenerator.SetEdVizGraphDotLocationColor; begin if edGraphVizDotLocation.Enabled then begin if FileExists(edGraphVizDotLocation.Text) then begin edGraphVizDotLocation.Color := clBase; end else begin edGraphVizDotLocation.Color := clRed; end; end else begin edGraphVizDotLocation.Color := clBtnFace; end; end; procedure TfrmHelpGenerator.edGraphVizDotLocationChange(Sender: TObject); begin Changed := True; SetEdVizGraphDotLocationColor; end; procedure TfrmHelpGenerator.Save1Click(Sender: TObject); begin SaveIt; end; procedure TfrmHelpGenerator.pcMainChange(Sender: TObject); begin HelpKeyword := pcMain.ActivePage.HelpKeyword; end; { THelpGeneratorProjectOptions } function THelpGeneratorProjectOptions.GetChanged: boolean; begin result := frmHelpGenerator.Changed; end; function THelpGeneratorProjectOptions.GetConclusion: string; begin if csWriting in ComponentState then begin result := RelativeFileName(frmHelpGenerator.edConclusion.Text); end else begin result := frmHelpGenerator.edConclusion.Text; end; end; function THelpGeneratorProjectOptions.GetDirectives: TSTrings; begin result := frmHelpGenerator.memoDefines.Lines; end; function THelpGeneratorProjectOptions.GetFooter: TStrings; begin result := frmHelpGenerator.memoFooter.Lines; end; function THelpGeneratorProjectOptions.GetGraphVizDotLocation: string; begin result := frmHelpGenerator.edGraphVizDotLocation.Text; end; function THelpGeneratorProjectOptions.GetHeader: TStrings; begin result := frmHelpGenerator.memoFooter.Lines; end; function THelpGeneratorProjectOptions.GetHtmlDocGeneratorComponent: THtmlDocGenerator; begin result := frmHelpGenerator.HtmlDocGenerator; end; function THelpGeneratorProjectOptions.GetHTMLHelpDocGeneratorComponent: THTMLHelpDocGenerator; begin result := frmHelpGenerator.HTMLHelpDocGenerator; end; function THelpGeneratorProjectOptions.GetHyphenatedWords: TStrings; begin result := frmHelpGenerator.memoHyphenatedWords.Lines; end; function THelpGeneratorProjectOptions.GetIncludeAutomated: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kAutomated); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludeDirectories: TStrings; var Index: integer; begin if csWriting in ComponentState then begin FSourceFiles.Assign(frmHelpGenerator.memoIncludeDirectories.Lines); for Index := 0 to FSourceFiles.Count - 1 do begin FSourceFiles[Index] := RelativeFileName(FSourceFiles[Index]); end; result := FSourceFiles; end else begin result := frmHelpGenerator.memoIncludeDirectories.Lines; end; end; function THelpGeneratorProjectOptions.GetIncludeImplicit: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kImplicit); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludePrivate: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kPrivate); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludeProtected: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kProtected); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludePublic: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kPublic); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludePublished: boolean; begin result := frmHelpGenerator.clbMethodVisibility.Checked[0]; end; function THelpGeneratorProjectOptions.GetIncludeStrictPrivate: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kStrictPrivate); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludeStrictProtected: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kStrictProtected); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIntroduction: string; begin if csWriting in ComponentState then begin result := RelativeFileName(frmHelpGenerator.edIntroduction.Text); end else begin result := frmHelpGenerator.edIntroduction.Text; end; end; function THelpGeneratorProjectOptions.GetLanguage: TLanguageID; begin result := TLanguageID(frmHelpGenerator.comboLanguages.ItemIndex); end; function THelpGeneratorProjectOptions.GetLatexGraphicsPackage: TLatexGraphicsPackage; begin result := TLatexGraphicsPackage(frmHelpGenerator.comboLatexGraphics.ItemIndex); end; function THelpGeneratorProjectOptions.GetLineBreakQuality: TLineBreakQuality; begin result := TLineBreakQuality(frmHelpGenerator.rgLineBreakQuality.ItemIndex); end; function THelpGeneratorProjectOptions.GetOutputDirectory: string; begin if csWriting in ComponentState then begin result := RelativeFileName(frmHelpGenerator.edOutput.Text); end else begin result := frmHelpGenerator.edOutput.Text; end; end; function THelpGeneratorProjectOptions.GetOutputType: TOutputType; begin result := TOutputType(frmHelpGenerator.comboGenerateFormat.ItemIndex); end; function THelpGeneratorProjectOptions.GetPasDocComponent: TPasDoc; begin result := frmHelpGenerator.PasDoc1; end; function THelpGeneratorProjectOptions.GetProjectName: string; begin result := frmHelpGenerator.edProjectName.Text; end; function THelpGeneratorProjectOptions.GetSourceFiles: TStrings; var Index: integer; begin if csWriting in ComponentState then begin FSourceFiles.Assign(frmHelpGenerator.memoFiles.Lines); for Index := 0 to FSourceFiles.Count - 1 do begin FSourceFiles[Index] := RelativeFileName(FSourceFiles[Index]); end; result := FSourceFiles; end else begin result := frmHelpGenerator.memoFiles.Lines; end; end; function THelpGeneratorProjectOptions.GetTexDocGeneratorComponent: TTexDocGenerator; begin result := frmHelpGenerator.TexDocGenerator; end; function THelpGeneratorProjectOptions.GetTitle: string; begin result := frmHelpGenerator.edTitle.Text; end; function THelpGeneratorProjectOptions.GetUseGraphVizClasses: boolean; begin result := frmHelpGenerator.cbUseGraphVizClasses.Checked; end; function THelpGeneratorProjectOptions.GetUseGraphVizUses: boolean; begin result := frmHelpGenerator.cbUseGraphVizUses.Checked; end; function THelpGeneratorProjectOptions.GetVerbosity: integer; begin result := frmHelpGenerator.seVerbosity.Value; end; procedure THelpGeneratorProjectOptions.SetChanged(const Value: boolean); begin frmHelpGenerator.Changed := Value; end; procedure THelpGeneratorProjectOptions.SetConclusion(const Value: string); begin frmHelpGenerator.edConclusion.Text := Value; end; procedure THelpGeneratorProjectOptions.SetDefaultActivePage; begin frmHelpGenerator.pcMain.ActivePageIndex := 0; end; procedure THelpGeneratorProjectOptions.SetDirectives( const Value: TSTrings); begin frmHelpGenerator.memoDefines.Lines.Assign(Value); end; procedure THelpGeneratorProjectOptions.SetFooter(const Value: TStrings); begin frmHelpGenerator.memoFooter.Lines := Value; end; procedure THelpGeneratorProjectOptions.SetGraphVizDotLocation( const Value: string); begin if Value <> '' then begin frmHelpGenerator.edGraphVizDotLocation.Text := Value; end; end; procedure THelpGeneratorProjectOptions.SetHeader(const Value: TStrings); begin frmHelpGenerator.memoHeader.Lines := Value; end; procedure THelpGeneratorProjectOptions.SetHyphenatedWords( const Value: TStrings); begin frmHelpGenerator.memoHyphenatedWords.Lines := Value; end; procedure THelpGeneratorProjectOptions.SetIncludeAutomated( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kAutomated); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludeDirectories( const Value: TStrings); begin frmHelpGenerator.memoIncludeDirectories.Lines := Value; end; procedure THelpGeneratorProjectOptions.SetIncludeImplicit( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kImplicit); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludePrivate( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kPrivate); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludeProtected( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kProtected); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludePublic( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kPublic); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludePublished( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kPublished); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludeStrictPrivate( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kStrictPrivate); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludeStrictProtected( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kStrictProtected); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIntroduction( const Value: string); begin frmHelpGenerator.edIntroduction.Text := Value; end; procedure THelpGeneratorProjectOptions.SetLanguage( const Value: TLanguageID); begin frmHelpGenerator.comboLanguages.ItemIndex := Ord(Value); frmHelpGenerator.comboLanguagesChange(nil); end; procedure THelpGeneratorProjectOptions.SetLatexGraphicsPackage( const Value: TLatexGraphicsPackage); begin frmHelpGenerator.comboLatexGraphics.ItemIndex := Ord(Value); end; procedure THelpGeneratorProjectOptions.SetLineBreakQuality( const Value: TLineBreakQuality); begin frmHelpGenerator.rgLineBreakQuality.ItemIndex := Ord(Value); end; procedure THelpGeneratorProjectOptions.SetOutputDirectory( const Value: string); begin frmHelpGenerator.edOutput.Text := Value; end; procedure THelpGeneratorProjectOptions.SetOutputType(const Value: TOutputType); begin frmHelpGenerator.comboGenerateFormat.ItemIndex := Ord(Value); frmHelpGenerator.comboGenerateFormat.OnChange(nil); end; procedure THelpGeneratorProjectOptions.SetProjectName(const Value: string); begin frmHelpGenerator.edProjectName.Text := Value; end; procedure THelpGeneratorProjectOptions.SetSourceFiles( const Value: TStrings); begin frmHelpGenerator.memoFiles.Lines := Value; end; procedure THelpGeneratorProjectOptions.SetTitle(const Value: string); begin frmHelpGenerator.edTitle.Text := Value; end; procedure THelpGeneratorProjectOptions.SetUseGraphVizClasses( const Value: boolean); begin frmHelpGenerator.cbUseGraphVizClasses.Checked := Value; end; procedure THelpGeneratorProjectOptions.SetUseGraphVizUses( const Value: boolean); begin frmHelpGenerator.cbUseGraphVizUses.Checked := Value; end; procedure THelpGeneratorProjectOptions.SetVerbosity(const Value: integer); begin frmHelpGenerator.seVerbosity.Value := Value; end; { T_CLX_Ini } function T_CLX_Ini.GetBrowserLocation: string; begin result := frmHelpGenerator.edBrowser.Text; end; function T_CLX_Ini.GetGraphVizDotLocation: string; begin result := frmHelpGenerator.edGraphVizDotLocation.Text; end; function T_CLX_Ini.GetPasDocConsoleLocation: string; begin result := FPasDocConsoleLocation; end; procedure T_CLX_Ini.SetBrowserLocation(const Value: string); begin frmHelpGenerator.edBrowser.Text := Value; end; procedure T_CLX_Ini.SetGraphVizDotLocation(const Value: string); begin frmHelpGenerator.edGraphVizDotLocation.Text := Value; end; procedure TfrmHelpGenerator.Button1Click(Sender: TObject); begin if BrowserDialog.Execute then begin edBrowser.Text := BrowserDialog.FileName; end; end; procedure T_CLX_Ini.SetPasDocConsoleLocation(const Value: string); begin FPasDocConsoleLocation := Value; end; initialization Classes.RegisterClass(THelpGeneratorProjectOptions); Classes.RegisterClass(T_CLX_Ini); end.
PROGRAM SarahRevere(INPUT, OUTPUT); {Печать сообщения о том как идут британцы, в зависимости от ключа Look} PROCEDURE WriteAnswer(VAR Look: CHAR); BEGIN {WriteAnsw} IF Look = 'N' THEN WRITELN('Sarah didn''t say') ELSE WRITE('British are coming by '); IF Look = 'L' THEN WRITELN('land.'); IF Look = 'S' THEN WRITELN('sea.'); IF Look = 'A' THEN WRITELN('air.') END; {WriteAnsw} VAR Looking: CHAR; BEGIN {SarahRevere} IF NOT EOLN THEN READ(Looking); WriteAnswer(Looking) END. {SarahRevere}
unit Unbound.Main; interface uses Pengine.GLForm, Unbound.GameState; type TfrmMain = class(TGLForm) private FManager: TGameStateManager; public procedure Init; override; procedure Finalize; override; end; var frmMain: TfrmMain; implementation {$R *.dfm} uses Unbound.GameState.Loading, Unbound.GameState.MainMenu, Unbound.GameState.Playing; { TfrmMain } procedure TfrmMain.Init; begin FManager := TGameStateManager.Create(Game); FManager.Add<TGameStateLoading>; FManager.Add<TGameStateMainMenu>; FManager.Add<TGameStatePlaying>; FManager[TGameStatePlaying].Load; end; procedure TfrmMain.Finalize; begin FManager.Free; end; end.
unit clOcorrenciasJornal; interface uses clConexao, System.SysUtils, Vcl.Dialogs; type TOcorrenciasJornal = class(TObject) private FRoteiro: String; FEntregador: Integer; FAssinatura: String; FNome: String; FProduto: String; FOcorrencia: Integer; FReincidencia: String; FDescricao: String; FEndereco: String; FRetorno: String; FResultado: Integer; FOrigem: Integer; FObs: String; FStatus: Integer; FData: TDateTime; conexao: TConexao; FNumero: Integer; FLog: String; FProcessado: String; FValor: Double; FApuracao: String; FQtde: Integer; FDataDesconto: System.TDate; FImpressao: String; FAnexo: String; procedure SetRoteiro(val: String); procedure SetEntregador(val: Integer); procedure SetAssinatura(val: String); procedure SetNome(val: String); procedure SetProduto(val: String); procedure SetOcorrencia(val: Integer); procedure SetReincidencia(val: String); procedure SetDescricao(val: String); procedure SetEndereco(val: String); procedure SetRetorno(val: String); procedure SetResultado(val: Integer); procedure SetOrigem(val: Integer); procedure SetObs(val: String); procedure SetStatus(val: Integer); procedure SetData(val: TDateTime); procedure SetNumero(val: Integer); procedure SetLog(val: String); procedure SetProcessado(val: String); procedure SetValor(val: Double); procedure SetApuracao(val: String); procedure SetQtde(val: Integer); procedure SetDataDesconto(val: System.TDate); procedure SetImpressao(val: String); procedure SetAnexo(val: String); public property Roteiro: String read FRoteiro write SetRoteiro; property Entregador: Integer read FEntregador write SetEntregador; property Assinatura: String read FAssinatura write SetAssinatura; property Nome: String read FNome write SetNome; property Produto: String read FProduto write SetProduto; property Ocorrencia: Integer read FOcorrencia write SetOcorrencia; property Reincidencia: String read FReincidencia write SetReincidencia; property Descricao: String read FDescricao write SetDescricao; property Endereco: String read FEndereco write SetEndereco; property Retorno: String read FRetorno write SetRetorno; property Resultado: Integer read FResultado write SetResultado; property Origem: Integer read FOrigem write SetOrigem; property Obs: String read FObs write SetObs; property Status: Integer read FStatus write SetStatus; property Data: TDateTime read FData write SetData; property Numero: Integer read FNumero write SetNumero; property Log: String read FLog write SetLog; property Processado: String read FProcessado write SetProcessado; property Valor: Double read FValor write SetValor; property Apuracao: String read FApuracao write SetApuracao; property Qtde: Integer read FQtde write SetQtde; function Validar: Boolean; function Insert: Boolean; function Update: Boolean; function Delete(sFiltro: String): Boolean; function getObject(sId: String; sFiltro: String): Boolean; function getField(sCampo: String; sColuna: String): String; constructor Create; destructor Destroy; override; function Periodo(sData1: String; sData2: String; iTipo: Integer): Boolean; function Exist: Boolean; function LocalizaFinanceiro(sAssinatura: String; sData: String): Boolean; function Consolidado(sDataInicial: String; sDataFinal: String): Boolean; property DataDesconto: System.TDate read FDataDesconto write SetDataDesconto; property Impressao: String read FImpressao write SetImpressao; property Anexo: String read FAnexo write SetAnexo; end; const TABLENAME = 'JOR_OCORRENCIAS_JORNAL'; implementation uses uGlobais, udm; procedure TOcorrenciasJornal.SetRoteiro(val: String); begin FRoteiro := val; end; procedure TOcorrenciasJornal.SetEntregador(val: Integer); begin FEntregador := val; end; procedure TOcorrenciasJornal.SetAssinatura(val: String); begin FAssinatura := val; end; procedure TOcorrenciasJornal.SetNome(val: String); begin FNome := val; end; procedure TOcorrenciasJornal.SetProduto(val: String); begin FProduto := val; end; procedure TOcorrenciasJornal.SetOcorrencia(val: Integer); begin FOcorrencia := val; end; procedure TOcorrenciasJornal.SetReincidencia(val: String); begin FReincidencia := val; end; procedure TOcorrenciasJornal.SetDescricao(val: String); begin FDescricao := val; end; procedure TOcorrenciasJornal.SetEndereco(val: String); begin FEndereco := val; end; procedure TOcorrenciasJornal.SetRetorno(val: String); begin FRetorno := val; end; procedure TOcorrenciasJornal.SetResultado(val: Integer); begin FResultado := val; end; procedure TOcorrenciasJornal.SetOrigem(val: Integer); begin FOrigem := val; end; procedure TOcorrenciasJornal.SetObs(val: String); begin FObs := val; end; procedure TOcorrenciasJornal.SetStatus(val: Integer); begin FStatus := val; end; procedure TOcorrenciasJornal.SetData(val: TDateTime); begin FData := val; end; procedure TOcorrenciasJornal.SetNumero(val: Integer); begin FNumero := val; end; procedure TOcorrenciasJornal.SetLog(val: String); begin FLog := val; end; procedure TOcorrenciasJornal.SetProcessado(val: String); begin FProcessado := val; end; procedure TOcorrenciasJornal.SetValor(val: Double); begin FValor := val; end; procedure TOcorrenciasJornal.SetApuracao(val: String); begin FApuracao := val; end; procedure TOcorrenciasJornal.SetQtde(val: Integer); begin FQtde := val; end; procedure TOcorrenciasJornal.SetDataDesconto(val: System.TDate); begin FDataDesconto := val; end; procedure TOcorrenciasJornal.SetImpressao(val: String); begin FImpressao := Val; end; procedure TOcorrenciasJornal.SetAnexo(val: String); begin FAnexo := Val; end; function TOcorrenciasJornal.Validar: Boolean; begin try Result := False; if Self.Roteiro.IsEmpty then begin MessageDlg('Informe o Roteiro!',mtWarning,[mbOK],0); Exit; end; if Self.Assinatura.IsEmpty then begin MessageDlg('Informe o Código da Assinatura!',mtWarning,[mbOK],0); Exit; end; if Self.Nome.IsEmpty then begin MessageDlg('Informe o Nome do Assinante!',mtWarning,[mbOK],0); Exit; end; if Self.Produto.IsEmpty then begin MessageDlg('Informe o Produto!',mtWarning,[mbOK],0); Exit; end; if Self.Ocorrencia = 0 then begin MessageDlg('Informe a Ocorrência!',mtWarning,[mbOK],0); Exit; end; if Self.Reincidencia.IsEmpty then begin MessageDlg('Informe se há reincidência!',mtWarning,[mbOK],0); Exit; end; if Self.Data = 0 then begin MessageDlg('Informe a data!',mtWarning,[mbOK],0); Exit; end; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; constructor TOcorrenciasJornal.Create; begin inherited Create; conexao := TConexao.Create; end; destructor TOcorrenciasJornal.Destroy; begin conexao.Free; inherited Destroy; end; function TOcorrenciasJornal.Insert: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; if dm.qryCRUD.Active then begin dm.qryCRUD.Close; end; dm.qryCRUD.SQL.Clear; dm.qryCRUD.SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'DAT_OCORRENCIA, ' + 'COD_ASSINATURA, ' + 'NOM_ASSINANTE, ' + 'DES_ROTEIRO, ' + 'COD_ENTREGADOR, ' + 'COD_PRODUTO, ' + 'COD_OCORRENCIA, ' + 'DOM_REINCIDENTE, ' + 'DES_DESCRICAO, ' + 'DES_ENDERECO, ' + 'DES_RETORNO, ' + 'COD_RESULTADO, ' + 'COD_ORIGEM, ' + 'DES_OBS, ' + 'COD_STATUS, ' + 'DES_APURACAO, ' + 'DOM_PROCESSADO, ' + 'QTD_OCORRENCIAS, ' + 'VAL_OCORRENCIA, ' + 'DAT_DESCONTO, ' + 'DOM_IMPRESSAO, ' + 'DES_ANEXO,' + 'DES_LOG) ' + 'VALUES ' + '(:DATA, ' + ':ASSINATURA, ' + ':NOME, ' + ':ROTEIRO, ' + ':ENTREGADOR, ' + ':PRODUTO, ' + ':OCORRENCIA, ' + ':REINCIDENTE, ' + ':DESCRICAO, ' + ':ENDERECO, ' + ':RETORNO, ' + ':RESULTADO, ' + ':ORIGEM, ' + ':OBS, ' + ':STATUS, ' + ':APURACAO, ' + ':PROCESSADO, ' + ':QTDE, ' + ':VALOR, ' + ':DATADESCONTO, ' + ':IMPRESSAO, ' + ':ANEXO, ' + ':LOG);'; dm.qryCRUD.ParamByName('DATA').AsDate := Self.Data; dm.qryCRUD.ParamByName('ASSINATURA').AsString := Self.Assinatura; dm.qryCRUD.ParamByName('NOME').AsString := Self.Nome; dm.qryCRUD.ParamByName('ROTEIRO').AsString := Self.Roteiro; dm.qryCRUD.ParamByName('ENTREGADOR').AsInteger := Self.Entregador; dm.qryCRUD.ParamByName('PRODUTO').AsString := Self.Produto; dm.qryCRUD.ParamByName('OCORRENCIA').AsInteger := Self.Ocorrencia; dm.qryCRUD.ParamByName('REINCIDENTE').AsString := Self.Reincidencia; dm.qryCRUD.ParamByName('DESCRICAO').AsString := Self.Descricao; dm.qryCRUD.ParamByName('ENDERECO').AsString := Self.Endereco; dm.qryCRUD.ParamByName('RETORNO').AsString := Self.Retorno; dm.qryCRUD.ParamByName('RESULTADO').AsInteger := Self.Resultado; dm.qryCRUD.ParamByName('ORIGEM').AsInteger := Self.Origem; dm.qryCRUD.ParamByName('OBS').AsString := Self.Obs; dm.qryCRUD.ParamByName('STATUS').AsInteger := Self.Status; dm.qryCRUD.ParamByName('APURACAO').AsString := Self.Apuracao; dm.qryCRUD.ParamByName('PROCESSADO').AsString := Self.Processado; dm.qryCRUD.ParamByName('QTDE').AsInteger := Self.Qtde; dm.qryCRUD.ParamByName('VALOR').AsFloat := Self.Valor; dm.qryCRUD.ParamByName('DATADESCONTO').AsDate := Self.DataDesconto; dm.qryCRUD.ParamByName('IMPRESSAO').AsString := Self.Impressao; dm.qryCRUD.ParamByName('ANEXO').AsString := Self.Anexo; dm.qryCRUD.ParamByName('LOG').AsString := Self.Log; dm.ZConn.PingServer; dm.qryCRUD.ExecSQL; dm.qryCRUD.Close; dm.qryCRUD.SQL.Clear; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TOcorrenciasJornal.Update: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; if dm.qryCRUD.Active then begin dm.qryCRUD.Close; end; dm.qryCRUD.SQL.Clear; dm.qryCRUD.SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DAT_OCORRENCIA = :DATA, ' + 'COD_ASSINATURA = :ASSINATURA, ' + 'NOM_ASSINANTE = :NOME, ' + 'DES_ROTEIRO = :ROTEIRO, ' + 'COD_ENTREGADOR = :ENTREGADOR, ' + 'COD_PRODUTO = :PRODUTO, ' + 'COD_OCORRENCIA = :OCORRENCIA, ' + 'DOM_REINCIDENTE = :REINCIDENTE, ' + 'DES_DESCRICAO = :DESCRICAO, ' + 'DES_ENDERECO = :ENDERECO, ' + 'DES_RETORNO = :RETORNO, ' + 'COD_RESULTADO = :RESULTADO, ' + 'COD_ORIGEM = :ORIGEM, ' + 'DES_OBS = :OBS, ' + 'COD_STATUS = :STATUS, ' + 'DES_APURACAO = :APURACAO, ' + 'DOM_PROCESSADO = :PROCESSADO, ' + 'QTD_OCORRENCIAS = :QTDE, ' + 'VAL_OCORRENCIA = :VALOR, ' + 'DAT_DESCONTO = :DATADESCONTO, ' + 'DOM_IMPRESSAO = :IMPRESSAO, ' + 'DES_ANEXO = :ANEXO, ' + 'DES_LOG = :LOG ' + 'WHERE NUM_OCORRENCIA = :NUMERO;'; dm.qryCRUD.ParamByName('NUMERO').AsInteger := Self.Numero; dm.qryCRUD.ParamByName('DATA').AsDate := Self.Data; dm.qryCRUD.ParamByName('ASSINATURA').AsString := Self.Assinatura; dm.qryCRUD.ParamByName('NOME').AsString := Self.Nome; dm.qryCRUD.ParamByName('ROTEIRO').AsString := Self.Roteiro; dm.qryCRUD.ParamByName('ENTREGADOR').AsInteger := Self.Entregador; dm.qryCRUD.ParamByName('PRODUTO').AsString := Self.Produto; dm.qryCRUD.ParamByName('OCORRENCIA').AsInteger := Self.Ocorrencia; dm.qryCRUD.ParamByName('REINCIDENTE').AsString := Self.Reincidencia; dm.qryCRUD.ParamByName('DESCRICAO').AsString := Self.Descricao; dm.qryCRUD.ParamByName('ENDERECO').AsString := Self.Endereco; dm.qryCRUD.ParamByName('RETORNO').AsString := Self.Retorno; dm.qryCRUD.ParamByName('RESULTADO').AsInteger := Self.Resultado; dm.qryCRUD.ParamByName('ORIGEM').AsInteger := Self.Origem; dm.qryCRUD.ParamByName('OBS').AsString := Self.Obs; dm.qryCRUD.ParamByName('STATUS').AsInteger := Self.Status; dm.qryCRUD.ParamByName('APURACAO').AsString := Self.Apuracao; dm.qryCRUD.ParamByName('PROCESSADO').AsString := Self.Processado; dm.qryCRUD.ParamByName('QTDE').AsInteger := Self.Qtde; dm.qryCRUD.ParamByName('VALOR').AsFloat := Self.Valor; dm.qryCRUD.ParamByName('DATADESCONTO').AsDate := Self.DataDesconto; dm.qryCRUD.ParamByName('IMPRESSAO').AsString := Self.Impressao; dm.qryCRUD.ParamByName('ANEXO').AsString := Self.Anexo; dm.qryCRUD.ParamByName('LOG').AsString := Self.Log; dm.ZConn.PingServer; dm.qryCRUD.ExecSQL; dm.qryCRUD.Close; dm.qryCRUD.SQL.Clear; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TOcorrenciasJornal.Delete(sFiltro: String): Boolean; begin try Result := False; if sFiltro.IsEmpty then begin Exit; end; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Add('DELETE FROM ' + TABLENAME); if sFiltro = 'NUMERO' then begin dm.QryCRUD.SQL.Add('WHERE NUM_OCORRENCIA = :NUMERO'); dm.QryCRUD.ParamByName('NUMERO').AsInteger := Self.Numero; end else if sFiltro = 'ASSINATURA' then begin dm.QryCRUD.SQL.Add('WHERE COD_ASSINATURA = :ASSINATURA'); dm.QryCRUD.ParamByName('ASSINATURA').AsString := Self.Assinatura; end else if sFiltro = 'DATA' then begin dm.QryCRUD.SQL.Add('WHERE DAT_OCORRENCIA = :DATA'); dm.QryCRUD.ParamByName('DATA').AsDate := Self.Data; end else if sFiltro = 'DESCONTO' then begin dm.QryCRUD.SQL.Add('WHERE DAT_DESCONTO = :DATA'); dm.QryCRUD.ParamByName('DATA').AsDate := Self.DataDesconto; end else if sFiltro = 'ROTEIRO' then begin dm.QryCRUD.SQL.Add('WHERE DES_ROTEIRO = :ROTEIRO'); dm.QryCRUD.ParamByName('ROTEIRO').AsString := Self.Roteiro; end; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TOcorrenciasJornal.getObject(sId: String; sFiltro: String): Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME); if sFiltro = 'NUMERO' then begin dm.QryGetObject.SQL.Add('WHERE NUM_OCORRENCIA = :NUMERO'); dm.QryGetObject.ParamByName('NUMERO').AsInteger := StrToInt(sId); end else if sFiltro = 'ASSINATURA' then begin dm.QryGetObject.SQL.Add('WHERE COD_ASSINATURA = :ASSINATURA'); dm.QryGetObject.ParamByName('ASSINATURA').AsString := sId; end else if sFiltro = 'ROTEIRO' then begin dm.QryGetObject.SQL.Add('WHERE DES_ROTEIRO = :ROTEIRO'); dm.QryGetObject.ParamByName('ROTEIRO').AsString := sId; end else if sFiltro = 'ENDERECO' then begin dm.QryGetObject.SQL.Add('WHERE DES_LOGRADOURO LIKE :ENDERECO'); dm.QryGetObject.ParamByName('ENDERECO').AsString := '%' + sId + '%'; end else if sFiltro = 'CHAVE' then begin dm.QryGetObject.SQL.Add('WHERE COD_ASSINATURA = :ASSINATURA '); dm.QryGetObject.SQL.Add('AND COD_PRODUTO = :PRODUTO '); dm.QryGetObject.SQL.Add('AND DES_ROTEIRO = :ROTEIRO '); dm.QryGetObject.SQL.Add('AND COD_OCORRENCIA = :OCORRENCIA '); dm.QryGetObject.SQL.Add('AND DAT_OCORRENCIA = :DATA '); dm.QryGetObject.ParamByName('ASSINATURA').AsString := Self.Assinatura; dm.QryGetObject.ParamByName('PRODUTO').AsString := Self.Produto; dm.QryGetObject.ParamByName('ROTEIRO').AsString := Self.Roteiro; dm.QryGetObject.ParamByName('OCORRENCIA').AsInteger := Self.Ocorrencia; dm.QryGetObject.ParamByName('DATA').AsDateTime := Self.Data; end; dm.ZConn.PingServer; dm.QryGetObject.Open; if (not dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; Self.Numero := dm.QryGetObject.FieldByName('NUM_OCORRENCIA').AsInteger; Self.Data := dm.QryGetObject.FieldByName('DAT_OCORRENCIA').AsDateTime; Self.Assinatura := dm.QryGetObject.FieldByName('COD_ASSINATURA').AsString; Self.Nome := dm.QryGetObject.FieldByName('NOM_ASSINATURA').AsString; Self.Roteiro := dm.QryGetObject.FieldByName('DES_ROTEIRO').AsString; Self.Entregador := dm.QryGetObject.FieldByName('ENTREGADOR').AsInteger; Self.Produto := dm.QryGetObject.FieldByName('COD_PRODUTO').AsString; Self.Ocorrencia := dm.QryGetObject.FieldByName('COD_OCORRENCIA').AsInteger; Self.Reincidencia := dm.QryGetObject.FieldByName('DOM_REINCIDENTE').AsString; Self.Descricao := dm.QryGetObject.FieldByName('DES_DESCRICAO').AsString; Self.Endereco := dm.QryGetObject.FieldByName('DES_ENDERECO').AsString; Self.Retorno := dm.QryGetObject.FieldByName('DES_RETORNO').AsString; Self.Resultado := dm.QryGetObject.FieldByName('COD_RESULTADO').AsInteger; Self.Origem := dm.QryGetObject.FieldByName('COD_ORIGEM').AsInteger; Self.Obs := dm.QryGetObject.FieldByName('DES_OBS').AsString; Self.Status := dm.QryGetObject.FieldByName('COD_STATUS').AsInteger; Self.Apuracao := dm.QryGetObject.FieldByName('DES_APURACAO').AsString; Self.Processado := dm.QryGetObject.FieldByName('DOM_PROCESSADO').AsString; Self.Qtde := dm.QryGetObject.FieldByName('QTD_OCORRENCIAS').AsInteger; Self.Valor := dm.QryGetObject.FieldByName('VAL_OCORRENCIA').AsFloat; Self.DataDesconto := dm.QryGetObject.FieldByName('DAT_DESCONTO').AsDateTime; Self.Impressao := dm.QryGetObject.FieldByName('DOM_IMPRESSAO').AsString; Self.Anexo := dm.QryGetObject.FieldByName('DES_ANEXO').AsString; Self.Log := dm.QryGetObject.FieldByName('DES_LOG').AsString; Result := True; Exit; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TOcorrenciasJornal.getField(sCampo: String; sColuna: String): String; begin try Result := ''; if sCampo.IsEmpty then begin Exit; end; if sColuna.IsEmpty then begin Exit; end; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.qryFields.Close; dm.qryFields.SQL.Clear; dm.qryFields.SQL.Add('SELECT ' + sCampo + ' FROM ' + TABLENAME); if sColuna = 'CODIGO' then begin dm.qryFields.SQL.Add('WHERE NUM_OCORRENCIA = :NUMERO'); dm.qryFields.ParamByName('NUMERO').AsInteger := Self.Numero; end else if sColuna = 'ASSINATURA' then begin dm.qryFields.SQL.Add('WHERE COD_ASSINATURA = :ASSINATURA'); dm.qryFields.ParamByName('ASSINATURA').AsString := Self.Assinatura; end else if sColuna = 'ROTEIRO' then begin dm.qryFields.SQL.Add('WHERE DES_ROTEIRO = :ROTEIRO'); dm.qryFields.ParamByName('ROTEIRO').AsString := Self.Roteiro; end else if sColuna = 'NOME' then begin dm.qryFields.SQL.Add('WHERE NOM_ASSINANTE = :NOME'); dm.qryFields.ParamByName('NOME').AsString := Self.Nome; end; dm.ZConn.PingServer; dm.qryFields.Open; dm.qryFields.Open; if (not dm.qryFields.IsEmpty) then begin dm.qryFields.First; Result := dm.qryFields.FieldByName(sCampo).AsString; end; dm.qryFields.Close; dm.qryFields.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TOcorrenciasJornal.Periodo(sData1: String; sData2: String; iTipo: Integer): Boolean; begin Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.QryPesquisa.Close; dm.QryPesquisa.SQL.Clear; dm.QryPesquisa.SQL.Add('SELECT * FROM ' + TABLENAME); if iTipo = 4 then begin dm.QryPesquisa.SQL.Add('WHERE DAT_DESCONTO BETWEEN :DATA1 AND :DATA2 '); dm.QryPesquisa.SQL.Add('AND COD_STATUS = :STATUS'); dm.QryPesquisa.ParamByName('DATA1').AsDate := StrToDate(sData1); dm.QryPesquisa.ParamByName('DATA2').AsDate := StrToDate(sData2); dm.QryPesquisa.ParamByName('STATUS').AsInteger := iTipo; end else begin if (not sData1.IsEmpty) and (not sData2.IsEmpty) then begin dm.QryPesquisa.SQL.Add('WHERE DAT_OCORRENCIA BETWEEN :DATA1 AND :DATA2 '); dm.QryPesquisa.ParamByName('DATA1').AsDate := StrToDate(sData1); dm.QryPesquisa.ParamByName('DATA2').AsDate := StrToDate(sData2); if iTipo <> 5 then begin dm.QryPesquisa.SQL.Add('AND COD_STATUS = :STATUS'); dm.QryPesquisa.ParamByName('STATUS').AsInteger := iTipo; end; end else begin dm.QryPesquisa.SQL.Add('WHERE COD_STATUS = :STATUS '); dm.QryPesquisa.ParamByName('STATUS').AsInteger := iTipo; end; end; dm.ZConn.PingServer; dm.QryPesquisa.Open; if dm.QryPesquisa.IsEmpty then begin dm.QryPesquisa.Close; dm.QryPesquisa.SQL.Clear; Exit; end; dm.QryPesquisa.First; Result := True; end; function TOcorrenciasJornal.Exist: Boolean; begin Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.QryPesquisa.Close; dm.QryPesquisa.SQL.Clear; dm.QryPesquisa.SQL.Add('SELECT * FROM ' + TABLENAME + ' '); dm.QryPesquisa.SQL.Add('WHERE COD_ASSINATURA = :ASSINATURA '); dm.QryPesquisa.SQL.Add('AND COD_PRODUTO = :PRODUTO '); dm.QryPesquisa.SQL.Add('AND DES_ROTEIRO = :ROTEIRO '); dm.QryPesquisa.SQL.Add('AND COD_OCORRENCIA = :OCORRENCIA '); dm.QryPesquisa.SQL.Add('AND DAT_OCORRENCIA = :DATA '); dm.QryPesquisa.SQL.Add('AND COD_ENTREGADOR = :ENTREGADOR '); dm.QryPesquisa.ParamByName('ASSINATURA').AsString := Self.Assinatura; dm.QryPesquisa.ParamByName('PRODUTO').AsString := Self.Produto; dm.QryPesquisa.ParamByName('ROTEIRO').AsString := Self.Roteiro; dm.QryPesquisa.ParamByName('OCORRENCIA').AsInteger := Self.Ocorrencia; dm.QryPesquisa.ParamByName('DATA').AsDateTime := Self.Data; dm.QryPesquisa.ParamByName('ENTREGADOR').AsInteger := Self.Entregador; dm.ZConn.PingServer; dm.QryPesquisa.Open; if dm.QryPesquisa.IsEmpty then begin dm.QryPesquisa.Close; dm.QryPesquisa.SQL.Clear; Exit; end; Self.Numero := dm.qryPesquisa.FieldByName('NUM_OCORRENCIA').AsInteger; dm.QryPesquisa.Close; dm.QryPesquisa.SQL.Clear; Result := True; end; function TOcorrenciasJornal.LocalizaFinanceiro(sAssinatura: String; sData: String): Boolean; begin Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.QryPesquisa.Close; dm.QryPesquisa.SQL.Clear; dm.QryPesquisa.SQL.Add('SELECT * FROM ' + TABLENAME + ' '); dm.QryPesquisa.SQL.Add('WHERE COD_ASSINATURA LIKE :ASSINATURA AND DES_DESCRICAO LIKE :DATA'); dm.QryPesquisa.ParamByName('ASSINATURA').AsString := '%' + sAssinatura; dm.QryPesquisa.ParamByName('DATA').AsString := '%' + sData + '%'; dm.ZConn.PingServer; dm.QryPesquisa.Open; if dm.QryPesquisa.IsEmpty then begin dm.QryPesquisa.Close; dm.QryPesquisa.SQL.Clear; Exit; end; dm.QryPesquisa.First; Self.Numero := dm.qryPesquisa.FieldByName('NUM_OCORRENCIA').AsInteger; Self.Data := dm.qryPesquisa.FieldByName('DAT_OCORRENCIA').AsDateTime; Self.Assinatura := dm.qryPesquisa.FieldByName('COD_ASSINATURA').AsString; Self.Nome := dm.qryPesquisa.FieldByName('NOM_ASSINANTE').AsString; Self.Roteiro := dm.qryPesquisa.FieldByName('DES_ROTEIRO').AsString; Self.Entregador := dm.qryPesquisa.FieldByName('COD_ENTREGADOR').AsInteger; Self.Produto := dm.qryPesquisa.FieldByName('COD_PRODUTO').AsString; Self.Ocorrencia := dm.qryPesquisa.FieldByName('COD_OCORRENCIA').AsInteger; Self.Reincidencia := dm.qryPesquisa.FieldByName('DOM_REINCIDENTE').AsString; Self.Descricao := dm.qryPesquisa.FieldByName('DES_DESCRICAO').AsString; Self.Endereco := dm.qryPesquisa.FieldByName('DES_ENDERECO').AsString; Self.Retorno := dm.qryPesquisa.FieldByName('DES_RETORNO').AsString; Self.Resultado := dm.qryPesquisa.FieldByName('COD_RESULTADO').AsInteger; Self.Origem := dm.qryPesquisa.FieldByName('COD_ORIGEM').AsInteger; Self.Obs := dm.qryPesquisa.FieldByName('DES_OBS').AsString; Self.Status := dm.qryPesquisa.FieldByName('COD_STATUS').AsInteger; Self.Apuracao := dm.qryPesquisa.FieldByName('DES_APURACAO').AsString; Self.Processado := dm.qryPesquisa.FieldByName('DOM_PROCESSADO').AsString; Self.Qtde := dm.qryPesquisa.FieldByName('QTD_OCORRENCIAS').AsInteger; Self.Valor := dm.qryPesquisa.FieldByName('VAL_OCORRENCIA').AsFloat; Self.DataDesconto := dm.qryPesquisa.FieldByName('DAT_DESCONTO').AsDateTime; Self.Impressao := dm.qryPesquisa.FieldByName('DOM_IMPRESSAO').AsString; Self.Anexo := dm.qryPesquisa.FieldByName('DES_ANEXO').AsString; Self.Log := dm.qryPesquisa.FieldByName('DES_LOG').AsString; Result := True; end; function TOcorrenciasJornal.Consolidado(sDataInicial: String; sDataFinal: String): Boolean; var sSQL: string; begin Result := False; sSQL := 'SELECT A.DES_ROTEIRO, SUM(B.VAL_OCORRENCIA) AS VAL_OCORRENCIA ' + 'FROM JOR_ROTEIRO_ENTREGADOR AS A ' + 'LEFT JOIN JOR_OCORRENCIAS_JORNAL AS B ' + 'ON B.DES_ROTEIRO = A.COD_ROTEIRO_ANTIGO ' + 'WHERE B.DAT_DESCONTO BETWEEN :DATAINI AND :DATAFIM AND A.DOM_MOSTRAR = :MOSTRAR ' + 'GROUP BY A.DES_ROTEIRO'; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.qryCalculo.Close; dm.qryCalculo.SQL.Clear; dm.qryCalculo.SQL.Text := sSQL; dm.qryCalculo.ParamByName('DATAINI').AsDate := StrToDate(sDataInicial); dm.qryCalculo.ParamByName('DATAFIM').AsDate := StrToDate(sDataFinal); dm.qryCalculo.ParamByName('MOSTRAR').AsString := 'N'; dm.ZConn.PingServer; dm.qryCalculo.Open; if dm.qryCalculo.IsEmpty then begin dm.qryCalculo.Close; dm.qryCalculo.SQL.Clear; Exit; end; Result := True; end; end.
unit ActorTypes; interface uses StateEngine, DistributedStates, Classes; type TActorId = integer; TActorKind = integer; TViewerId = integer; type IActor = interface; IViewer = interface; IActor = interface function getId : TActorId; function getKind : TActorKind; end; IServerActor = interface( IActor ) function getStatePool : TServerStatePool; procedure Store( Stream : TStream ); function getContext : pointer; end; IClientActor = interface( IActor ) function getStatePool : TClientStatePool; procedure setStatePool( aStatePool : TClientStatePool ); procedure Inserted; procedure Deleted; procedure Load( Stream : TStream ); end; IViewer = interface function getId : TViewerId; function IsAwareOf( Actor : IServerActor ) : boolean; end; implementation end.
unit settings; interface uses Classes, SysUtils, IniFiles, Forms, Windows; const csIniDBConnectionSection = 'DBConnection'; csIniGlobalSection = 'Global'; {Section: DBConnection} csIniDBConnectionDBIP = 'DBIP'; csIniDBConnectionDBPath = 'DBPath'; csIniDBConnectionVendorLib = 'VendorLib'; {Section: Global} csIniGlobalStartInterval = 'StartInterval'; type TIniOptions = class(TObject) private {Section: DBConnection} FDBConnectionDBIP: string; FDBConnectionDBPath: string; FDBConnectionVendorLib: string; {Section: Global} FGlobalStartInterval: Integer; public procedure LoadSettings(Ini: TIniFile); procedure SaveSettings(Ini: TIniFile); procedure LoadFromFile(const FileName: string); procedure SaveToFile(const FileName: string); {Section: DBConnection} property DBConnectionDBIP: string read FDBConnectionDBIP write FDBConnectionDBIP; property DBConnectionDBPath: string read FDBConnectionDBPath write FDBConnectionDBPath; property DBConnectionVendorLib: string read FDBConnectionVendorLib write FDBConnectionVendorLib; {Section: Global} property GlobalStartInterval: Integer read FGlobalStartInterval write FGlobalStartInterval; end; var IniOptions: TIniOptions = nil; implementation procedure TIniOptions.LoadSettings(Ini: TIniFile); begin if Ini <> nil then begin {Section: DBConnection} FDBConnectionDBIP := Ini.ReadString(csIniDBConnectionSection, csIniDBConnectionDBIP, '127.0.0.1'); FDBConnectionDBPath := Ini.ReadString(csIniDBConnectionSection, csIniDBConnectionDBPath, 'C:\DB\SCADALOGGER.GDB'); FDBConnectionVendorLib := Ini.ReadString(csIniDBConnectionSection, csIniDBConnectionVendorLib, 'C:\Program Files (x86)\Firebird\Firebird_2_5\bin\fbclient.dll'); {Section: Global} FGlobalStartInterval := Ini.ReadInteger(csIniGlobalSection, csIniGlobalStartInterval, 60); end; end; procedure TIniOptions.SaveSettings(Ini: TIniFile); begin if Ini <> nil then begin {Section: DBConnection} Ini.WriteString(csIniDBConnectionSection, csIniDBConnectionDBIP, FDBConnectionDBIP); Ini.WriteString(csIniDBConnectionSection, csIniDBConnectionDBPath, FDBConnectionDBPath); Ini.WriteString(csIniDBConnectionSection, csIniDBConnectionVendorLib, FDBConnectionVendorLib); {Section: Global} Ini.WriteInteger(csIniGlobalSection, csIniGlobalStartInterval, FGlobalStartInterval); end; end; procedure TIniOptions.LoadFromFile(const FileName: string); var Ini: TIniFile; begin Ini := TIniFile.Create(FileName); try LoadSettings(Ini); finally Ini.Free; end; end; procedure TIniOptions.SaveToFile(const FileName: string); var Ini: TIniFile; begin Ini := TIniFile.Create(FileName); try SaveSettings(Ini); finally Ini.Free; end; end; initialization IniOptions := TIniOptions.Create; finalization IniOptions.Free; end.
program ejercicio12; const dimF = 22; //estasd son las versiones disponibles de android actualmente type dispositivo = record versionAndroid : Integer; tamPantalla : Real; RAM : Real; end; lista = ^nodo; nodo = record datos : dispositivo; sig : lista; end; vContado = array[1..dimF] of Integer; procedure inicializarVectorContador(var vc:vContado); var i: Integer; begin for i := 1 to dimF do begin vc[i]:=0; end; end; procedure insertarOrdenado(var l:lista; d:dispositivo); var nue,act,ant: lista; begin new(nue); nue^.datos:= d; act:=l; ant:=l; while (act <> nil) and (d.versionAndroid > act^.datos.versionAndroid) do begin ant:= act; act:= act^.sig; end; if (act = ant) then l:= nue else ant^.sig:=nue; nue^.sig:= act; end; procedure leerInfo(var d:dispositivo); begin with d do begin write('Ingrese la VERSION de android: '); readln(versionAndroid); write('Ingrese el tamano de pantalla: '); readln(tamPantalla); write('Ingrese la cantidad de memoria RAM: '); readln(RAM); writeln('----------------------------------'); end; end; procedure cargarLista(var l:lista); var d: dispositivo; begin leerInfo(d); while (d.versionAndroid <> 0) do begin insertarOrdenado(l,d); leerInfo(d); end; end; procedure imprimirLista(l:lista); begin while l <> nil do begin writeln('VERSIN ANDROID: ', l^.datos.versionAndroid); writeln('TAMANO DE PANTALLA : ', l^.datos.tamPantalla:2:2); writeln('TAMANO RAM: ', l^.datos.RAM:2:2); writeln('------------------------------'); l:= l^.sig; end; end; procedure imprimirVector(vc:vContado); var i: Integer; begin for i := 1 to dimF do begin writeln('La cantidad de dispotivos con la version ', i, ' tiene: ', vc[i]); end; end; function cumple(ram: Real; pantalla: Real): Boolean; begin cumple:= (ram > 3) and (pantalla <= 5); end; procedure procesarInfor(l:lista; var vc:vContado); var cont,ver: Integer; contDispositivo, sumaPantalla: Real; begin cont:= 0; contDispositivo:= 0; sumaPantalla:= 0; while (l <> nil) do begin contDispositivo:= contDispositivo + 1; sumaPantalla:= sumaPantalla + l^.datos.tamPantalla; ver:= l^.datos.versionAndroid; vc[ver]:= vc[ver] + 1; //inciso a if (cumple(l^.datos.RAM, l^.datos.tamPantalla)) then cont:= cont + 1; l:= l^.sig; end; imprimirVector(vc); writeln('La cantidad de dispositivo con mas de 3GB de memoria y pantalla de a lo sumo 5` ', cont ); writeln('El tamano promedio de las pantallas de todos los dispositivos es: ', sumaPantalla / contDispositivo); end; var l: lista; d: dispositivo; begin l:= nil; cargarLista(l); writeln(); imprimirLista(l); readln(); end.
unit CleanArch_EmbrConf.Core.Entity.Impl.ParkingLot; interface uses System.SysUtils, CleanArch_EmbrConf.Core.Entity.Interfaces; type TParkingLot = class(TInterfacedObject, iParkingLot) private FCode : String; FCapacity : Integer; FOpenHour : Integer; FCloseHour : Integer; FOccupiedSpaces : Integer; public constructor Create; destructor Destroy; override; class function New : iParkingLot; function Code(Value : String) : iParkingLot; overload; function Code : String; overload; function Capacity(Value : Integer) : iParkingLot; overload; function Capacity : Integer; overload; function OpenHour(Value : Integer) : iParkingLot; overload; function OpenHour : Integer; overload; function CloseHour(Value : Integer) : iParkingLot; overload; function CloseHour : Integer; overload; function OccupiedSpaces(Value : Integer) : iParkingLot; overload; function OccupiedSpaces : Integer; overload; function isOpen(Data : String) : Boolean; function isFull : Boolean; end; implementation function TParkingLot.Capacity(Value: Integer): iParkingLot; begin Result := Self; FCapacity := Value; end; function TParkingLot.Capacity: Integer; begin Result := FCapacity; end; function TParkingLot.CloseHour: Integer; begin Result := FCloseHour; end; function TParkingLot.CloseHour(Value: Integer): iParkingLot; begin Result := Self; FCloseHour := Value; end; function TParkingLot.Code: String; begin Result := FCode; end; function TParkingLot.Code(Value: String): iParkingLot; begin Result := Self; FCode := Value; end; constructor TParkingLot.Create; begin end; destructor TParkingLot.Destroy; begin inherited; end; function TParkingLot.isFull: Boolean; begin Result := not (FCapacity = FOccupiedSpaces); end; function TParkingLot.isOpen(Data : String) : Boolean; begin Result := not ((Trunc(StrToDateTime(Data)) >= FOpenHour) and (Trunc(StrToDateTime(Data)) <= FCloseHour)); end; class function TParkingLot.New : iParkingLot; begin Result := Self.Create; end; function TParkingLot.OccupiedSpaces(Value: Integer): iParkingLot; begin Result := Self; FOccupiedSpaces := Value; end; function TParkingLot.OccupiedSpaces: Integer; begin Result := FOccupiedSpaces; end; function TParkingLot.OpenHour: Integer; begin Result := FOpenHour; end; function TParkingLot.OpenHour(Value: Integer): iParkingLot; begin Result := Self; FOpenHour := Value; end; end.
unit uInstaller; interface uses ShellAPI, Windows, SysUtils, uDelphiInstallationCheck, Registry; type TRetProcedure = procedure(Desc: string) of object; TInstaller = class(TObject) private FCallBackProc: TRetProcedure; const BPL_FILENAME = 'RFindUnit.bpl'; DPK_FILENAME = 'RFindUnit.dpk'; RSVARS_FILENAME = 'rsvars.bat'; DCU32INT_EXE = 'dcu32int.exe'; var FDelphiBplOutPut, FDelphiBinPath, FCurPath, FOutPutDir, FDelphiDesc, FUserAppDirFindUnit, FDcu32IntPath: string; FReg, FRegPacks: string; procedure LoadPaths(DelphiDesc, DelphiPath: string); procedure CheckDelphiRunning; procedure CheckDpkExists; procedure RemoveCurCompiledBpl; procedure CompileProject; procedure RegisterBpl; procedure RemoveOldDelphiBpl; procedure InstallBpl; procedure InstallDcu32Int; public constructor Create(DelphiDesc, DelphiPath: string); destructor Destroy; override; procedure Install(CallBackProc: TRetProcedure); end; implementation uses TlHelp32; { TInstaller } function IsProcessRunning(const AExeFileName: string): Boolean; var Continuar: BOOL; SnapshotHandle: THandle; Entry: TProcessEntry32; begin Result := False; try SnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); Entry.dwSize := SizeOf(Entry); Continuar := Process32First(SnapshotHandle, Entry); while Integer(Continuar) <> 0 do begin if ((UpperCase(ExtractFileName(Entry.szExeFile)) = UpperCase(AExeFileName)) or (UpperCase(Entry.szExeFile) = UpperCase(AExeFileName))) then begin Result := True; end; Continuar := Process32Next(SnapshotHandle, Entry); end; CloseHandle(SnapshotHandle); except Result := False; end; end; procedure TInstaller.CheckDelphiRunning; begin FCallBackProc('Cheking if is there same Delphi instance running...'); if IsProcessRunning('bds.exe') then Raise Exception.Create('Close all you Delphi instances before install.'); end; procedure TInstaller.CheckDpkExists; begin FCallBackProc('Cheking if project file exist...'); if not FileExists(FCurPath + DPK_FILENAME) then raise Exception.Create('The system was not able to find: ' + FCurPath + DPK_FILENAME); end; procedure TInstaller.CompileProject; const GCC_CMDLINE = '/c call "%s" & dcc32 "%s" -LE"%s" & pause'; var GccCmd: WideString; I: Integer; begin FCallBackProc('Compiling project...'); GccCmd := Format(GCC_CMDLINE, [ FDelphiBinPath + RSVARS_FILENAME, FCurPath + DPK_FILENAME, ExcludeTrailingPathDelimiter(FOutPutDir)]); ShellExecute(0, nil, 'cmd.exe', PChar(GccCmd), nil, SW_HIDE); for I := 0 to 10 do begin if FileExists(FOutPutDir + BPL_FILENAME) then Exit; if I = 9 then raise Exception.Create('Could not compile file: ' + FOutPutDir + BPL_FILENAME); Sleep(1000); end; end; constructor TInstaller.Create(DelphiDesc, DelphiPath: string); begin FDelphiDesc := DelphiDesc; LoadPaths(DelphiDesc, DelphiPath); end; destructor TInstaller.Destroy; begin inherited; end; procedure TInstaller.Install(CallBackProc: TRetProcedure); begin FCallBackProc := CallBackProc; CheckDelphiRunning; CheckDpkExists; RemoveCurCompiledBpl; CompileProject; RegisterBpl; RemoveOldDelphiBpl; InstallBpl; InstallDcu32Int; end; procedure TInstaller.InstallBpl; var I: Integer; Return: Boolean; begin FCallBackProc('Installing new version...'); Return := Windows.CopyFile(PChar(FOutPutDir + BPL_FILENAME), PChar(FDelphiBplOutPut + BPL_FILENAME), True); if not Return then raise Exception.Create('Could not install: ' + FDelphiBplOutPut + BPL_FILENAME + '. ' + SysErrorMessage(GetLastError)); for I := 0 to 30 do begin if FileExists(FDelphiBplOutPut + BPL_FILENAME) then Exit; if I = 9 then raise Exception.Create('Could not install: ' + FDelphiBplOutPut + BPL_FILENAME); Sleep(500); end; end; procedure TInstaller.InstallDcu32Int; begin FCallBackProc('Installing Dcu32Int'); Windows.CopyFile(PChar(FDcu32IntPath + DCU32INT_EXE), PChar(FUserAppDirFindUnit + DCU32INT_EXE), True); end; procedure TInstaller.LoadPaths(DelphiDesc, DelphiPath: string); var DelphiInst: TDelphiInstallationCheck; DelphiVersion: TDelphiVersions; begin FDelphiBinPath := ExtractFilePath(DelphiPath); FCurPath := ExtractFilePath(ParamStr(0)); FDelphiBplOutPut := GetEnvironmentVariable('public') + '\Documents\RAD Studio\RFindUnit\' + DelphiDesc + '\bpl\'; FDcu32IntPath := FCurPath + '\Thirdy\Dcu32Int\'; FUserAppDirFindUnit := GetEnvironmentVariable('appdata') + '\DelphiFindUnit\'; FOutPutDir := FCurPath + 'Installer\build\' + FDelphiDesc + '\'; ForceDirectories(FUserAppDirFindUnit); ForceDirectories(FDelphiBplOutPut); ForceDirectories(FOutPutDir); DelphiInst := TDelphiInstallationCheck.Create; try DelphiVersion := DelphiInst.GetDelphiVersionByName(DelphiDesc); FReg := DelphiInst.GetDelphiRegPathFromVersion(DelphiVersion); FRegPacks := FReg + '\Known Packages'; finally DelphiInst.Free; end; end; procedure TInstaller.RegisterBpl; var Reg: TRegistry; begin FCallBackProc('Registering package...'); Reg := TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; Reg.OpenKey(FRegPacks, False); Reg.WriteString(FDelphiBplOutPut + BPL_FILENAME, 'RfUtils'); Reg.CloseKey; finally Reg.Free; end; end; procedure TInstaller.RemoveCurCompiledBpl; var I: Integer; begin FCallBackProc('Removing old bpl...'); for I := 0 to 10 do begin if not FileExists(FOutPutDir + BPL_FILENAME) then Exit; DeleteFile(FOutPutDir + BPL_FILENAME); if I = 9 then raise Exception.Create('Could not remote file: ' + FOutPutDir + BPL_FILENAME); Sleep(200); end; end; procedure TInstaller.RemoveOldDelphiBpl; var I: Integer; begin FCallBackProc('Uninstalling old version...'); for I := 0 to 10 do begin if not FileExists(FDelphiBplOutPut + BPL_FILENAME) then Exit; DeleteFile(FDelphiBplOutPut + BPL_FILENAME); if I = 9 then raise Exception.Create('Could not uninstall old version: ' + FDelphiBplOutPut + BPL_FILENAME); Sleep(200); end; end; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Description: TSysLogClient class encapsulate the client side of the SysLog protocol as described in RFC3164 and RFC5424 but UTF-8 encoding is not supported. Creation: September 2009 Version: 1.01 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 2009 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author 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. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. History: Feb 08, 2010 V1.01 F. Piette moved NILVALUE to SysLogDefs so that it can be used from client and server components. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsSysLogClient; {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$ALIGN 8} {$I OverbyteIcsDefs.inc} interface uses Windows, SysUtils, Classes, OverbyteIcsSysLogDefs, OverbyteIcsWSocket; type ESysLogClientException = class(Exception); TSysLogClient = class(TComponent) protected FUdpSocket : TWSocket; FServer : String; FPort : String; FLocalPort : String; FRawMessage : String; FPID : Integer; FFacility : TSysLogFacility; FSeverity : TSysLogSeverity; FText : String; FProcess : String; FHostName : String; FTimeStamp : TDateTime; FRFC5424 : Boolean; FMsgID : String; // RFC5424 only FStructData : String; // RFC5424 only public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Send; procedure RawSend(const ARawMessage: String); procedure Close; procedure BuildRawMessage; published property Server : String read FServer write FServer; property Port : String read FPort write FPort; property LocalPort : String read FLocalPort write FLocalPort; property RawMessage : String read FRawMessage write FRawMessage; property Process : String read FProcess write FProcess; property HostName : String read FHostName write FHostName; property Text : String read FText write FText; property Facility : TSysLogFacility read FFacility write FFacility; property Severity : TSysLogSeverity read FSeverity write FSeverity; property PID : Integer read FPID write FPID; property TimeStamp : TDateTime read FTimeStamp write FTimeStamp; property RFC5424 : Boolean read FRFC5424 write FRFC5424; property MsgID : String read FMsgID write FMsgID; property StructData : String read FStructData write FStructData; end; function TimeZoneBias : String; implementation const // The next constants are specific to RFC 5424 SYSLOGVER = 1; // Version BOM = #$EF#$BB#$BF; // Begin of UTF-8 string {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TSysLogClient.Create(AOwner: TComponent); begin inherited Create(AOwner); FUdpSocket := TWSocket.Create(Self); FPort := '514'; FLocalPort := ''; // Will be selected by OS FServer := '127.0.0.1'; FPid := -1; FFacility := SYSLOG_FACILITY_USER; FSeverity := SYSLOG_SEVERITY_NOTICE; FRFC5424 := TRUE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TSysLogClient.Destroy; begin FreeAndNil(FUdpSocket); inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TSysLogClient.BuildRawMessage; var Day, Month, Year : Word; Hour, Minute : Word; Second, MilliSec : Word; TS : TDateTime; DT : String; SMsgID : String; SStructData : String; begin if FPid = -1 then FPid := GetCurrentProcessID; if FProcess = '' then begin SetLength(FProcess, 256); SetLength(FProcess, GetModuleFileName(0, @FProcess[1], Length(FProcess))); FProcess := ExtractFileName(FProcess); FProcess := ChangeFileExt(FProcess, ''); end; if FHostName = '' then FHostName := String(LocalHostName); if FTimeStamp = 0 then TS := Now else TS := FTimeStamp; DecodeDate(TS, Year, Month, Day); DecodeTime(TS, Hour, Minute, Second, MilliSec); if FRFC5424 then begin DT := Format('%04.4d-%02.2d-%02.2dT%02.2d:%02.2d:%02.2d.%03.3d%s', [Year, Month, Day, Hour, Minute, Second, MilliSec, TimeZoneBias]); if FMsgID = '' then SMsgID := SYSLOG_NILVALUE else SMsgID := FMsgID; if FStructData = '' then SStructData := SYSLOG_NILVALUE else begin SStructData := FStructData; if (Length(SStructData) < 2) or (SStructData[1] <> '[') or (SStructData[Length(SStructData)] <> ']') then raise ESysLogClientException.Create( 'Structured data must be enclosed in ''[]'''); end; RawMessage := Format('<%d>%d %s %s %s %d %s %s %s', [Ord(FFacility) * 8 + Ord(FSeverity), SYSLOGVER, DT, FHostName, FProcess, FPID, SMsgID, SStructData, FText]); end else begin DT := Format('%s %2d %02.2d:%02.2d:%02.2d', [SysLogMonthNames[Month], Day, Hour, Minute, Second]); // <13>Sep 8 14:37:40 MyHostName MyProcess[1234]: This is my message text RawMessage := Format('<%d>%s %s %s[%d]: %s', [Ord(FFacility) * 8 + Ord(FSeverity), DT, FHostName, FProcess, FPID, FText]); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TSysLogClient.Send; begin BuildRawMessage; RawSend(FRawMessage); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TSysLogClient.RawSend(const ARawMessage : String); begin if FUdpSocket.State <> wsConnected then begin FUdpSocket.Proto := 'udp'; FUdpSocket.Addr := FServer; FUdpSocket.Port := FPort; if FLocalPort <> '' then FUdpSocket.LocalPort := FLocalPort; FUdpSocket.Connect; end; FUdpSocket.SendStr(ARawMessage); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TSysLogClient.Close; begin FUdpSocket.Close; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TimeZoneBias : String; const Time_Zone_ID_DayLight = 2; var TZI : tTimeZoneInformation; TZIResult : Integer; aBias : Integer; begin TZIResult := GetTimeZoneInformation(TZI); if TZIResult = -1 then Result := '-0000' else begin if TZIResult = Time_Zone_ID_DayLight then { 10/05/99 } aBias := TZI.Bias + TZI.DayLightBias else aBias := TZI.Bias + TZI.StandardBias; Result := Format('-%.2d:%.2d', [Abs(aBias) div 60, Abs(aBias) mod 60]); if aBias < 0 then Result[1] := '+'; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit f2FontLoad; interface uses d2dInterfaces; function f2LoadFont(const aFontName: string; aFromPack: Boolean = False): Id2dFont; implementation uses Classes, SysUtils, Windows, SHFolder, SimpleXML, d2dCore, d2dTypes, d2dFont, f2Types, f2FontGen; const c_DefaultSize = 19; c_DefaultGamma = 0.6; c_DefaultWeight = 0.4; c_DefaultBGColor = $626262; type Tf2DefFontRecord = record rName : string; rFontFileName: string; end; const c_DefaultFonts : array [1..10] of Tf2DefFontRecord = ((rName: 'serif'; rFontFileName: 'ptserif.ttf'), (rName: 'serif-bold'; rFontFileName: 'ptserifb.ttf'), (rName: 'serif-italic'; rFontFileName: 'ptserifi.ttf'), (rName: 'serif-italic-bold'; rFontFileName: 'ptserifbi.ttf'), (rName: 'serif-bold-italic'; rFontFileName: 'ptserifbi.ttf'), (rName: 'sans'; rFontFileName: 'ptsans.ttf'), (rName: 'sans-bold'; rFontFileName: 'ptsansb.ttf'), (rName: 'sans-italic'; rFontFileName: 'ptsansi.ttf'), (rName: 'sans-italic-bold'; rFontFileName: 'ptsansbi.ttf'), (rName: 'sans-bold-italic'; rFontFileName: 'ptsansbi.ttf')); function GetFontsFolder: string; const SHGFP_TYPE_CURRENT = 0; CSIDL_FONTS = $0014; var path: array [0..MAX_PATH] of char; begin if SUCCEEDED(SHGetFolderPath(0, CSIDL_FONTS, 0,SHGFP_TYPE_CURRENT,@path[0])) then Result := path else Result := ''; end; function DefaultSubstitudes(const aFN: string): string; var I: Integer; begin Result := aFN; for I := 1 to 10 do begin if AnsiSameText(aFN, c_DefaultFonts[I].rName) then begin Result := c_DefaultFonts[I].rFontFileName; Break; end; end; end; // fonts can be: // .fnt (HGE fonts), .bmf (Bitmap Fonts), .ttf (True Type fonts with params) // times.ttf[18,1.1,0.8,0xFF0000] function f2LoadFont(const aFontName: string; aFromPack: Boolean = False): Id2dFont; var l_Ext: string; l_Pos: Integer; l_Params: string; l_FN: string; l_MS: TMemoryStream; l_FMem: Pointer; l_FMemSize: Longword; l_FontGamma: Double; l_FontSize: Integer; l_FontWeight: Double; l_FontBGColor: Td2dColor; l_FromFontsFolder: Boolean; l_OneParam: string; l_XML: IXmlDocument; l_FG: TfgFont; function GetParam: Boolean; var l_Pos: Integer; begin Result := False; l_OneParam := ''; if l_Params = '' then Exit; l_Pos := Pos(',', l_Params); if l_Pos > 0 then begin l_OneParam := Trim(Copy(l_Params, 1, l_Pos-1)); Delete(l_Params, 1, l_Pos); end else begin l_OneParam := Trim(l_Params); l_Params := ''; end; Result := (l_OneParam <> ''); end; begin Result := nil; l_FMem := nil; l_FN := aFontName; l_Pos := Pos('[', l_FN); if l_Pos > 0 then begin l_Params := Trim(Copy(l_FN, l_Pos, MaxInt)); Delete(l_FN, l_Pos, MaxInt); l_FN := Trim(l_FN); end else l_Params := ''; l_FN := DefaultSubstitudes(l_FN); l_Ext := ExtractFileExt(l_FN); if AnsiSameText(l_Ext, '.fnt') then begin if gD2DE.Resource_Exists(l_FN, aFromPack) then Result := Td2dHGEFont.Create(l_FN, aFromPack); end else if AnsiSameText(l_Ext, '.bmf') then begin if gD2DE.Resource_Exists(l_FN, aFromPack) then Result := Td2dBMFont.Create(l_FN, aFromPack); end else if AnsiSameText(l_Ext, '.ttf') then begin l_FromFontsFolder := False; try l_FMem := gD2DE.Resource_Load(l_FN, @l_FMemSize, aFromPack, True); { if (l_FMem = nil) and (Pos('\', l_FN) = 0) and (Pos('/', l_FN) = 0) then begin l_FN := GetFontsFolder + '\' + l_FN; if FileExists(l_FN) then begin l_MS := TMemoryStream.Create; l_MS.LoadFromFile(l_FN); l_FMem := l_MS.Memory; l_FMemSize := l_MS.Size; l_FromFontsFolder := True; end; end; } if l_FMem <> nil then begin l_FontSize := c_DefaultSize; l_FontGamma := c_DefaultGamma; l_FontWeight := c_DefaultWeight; l_FontBGColor := c_DefaultBGColor; if l_Params <> '' then begin if l_Params[1] = '[' then begin Delete(l_Params, 1, 1); if l_Params[Length(l_Params)] = ']' then begin Delete(l_Params, Length(l_Params), 1); if GetParam then l_FontSize := StrToIntDef(l_OneParam, c_DefaultSize); if GetParam then l_FontGamma := StrToFloatDef(l_OneParam, c_DefaultGamma); if GetParam then l_FontWeight := StrToFloatDef(l_OneParam, c_DefaultWeight); if GetParam then l_FontBGColor := Hex2ColorDef(l_OneParam, c_DefaultBGColor); end; end; end; l_FG := TfgFont.Create; try l_FG.Build(''{l_FN}, l_FontSize, l_FMem, l_FMemSize, l_FontGamma, l_FontWeight, l_FontBGColor); l_XML := l_FG.GetXML; Result := Td2dBMFont.CreateFromXML(l_XML); finally FreeAndNil(l_FG); end; end; if Result <> nil then Result.ID := aFontName; finally if l_FromFontsFolder then FreeAndNil(l_MS) else gD2DE.Resource_Free(l_FMem); end; end; end; end.
unit _fmmain; {$mode objfpc}{$H+} interface uses Classes, ExtCtrls, Forms, SysUtils, report; type { TfmMain } TfmMain = class(TForm) TmReport: TTimer; procedure TmReportTimer(Sender: TObject); private public end; var fmMain: TfmMain; implementation {$R *.frm} function LoadConfigFromFile(Config: TStrings; FileName: string): Boolean; begin if not FileExists(FileName) then Exit(False); Config.LoadFromFile(FileName); if Length(Config.Values['Host']) = 0 then Exit(False); if Length(Config.Values['Username']) = 0 then Exit(False); if Length(Config.Values['Password']) = 0 then Exit(False); Config.Values['HistoryPath'] := ExtractFilePath(ParamStr(0)) + 'history\'; Result := True; end; { TfmMain } procedure TfmMain.TmReportTimer(Sender: TObject); var Timer: TTimer; Config: TStrings; begin if not (Sender is TTimer) then Exit; Timer := Sender as TTimer; if not Timer.Enabled then Exit; Timer.Enabled := False; try Config := TStringList.Create; try if not LoadConfigFromFile(Config, ChangeFileExt(ParamStr(0), '.config')) then Exit; Timer.Interval := StrToIntDef(Config.Values['Interval'], 600000); ReportDesktop(Config); finally Config.Free; end; finally Timer.Enabled := True; end; end; end.
unit MMO.Types; interface type TSessionId = UInt32; TPacketHeader = packed record Size: UInt32; end; const SizeOfTPacketHeader = SizeOf(TPacketHeader); implementation end.
unit CsDataPipePrim; // Модуль: "w:\common\components\rtl\Garant\cs\CsDataPipePrim.pas" // Стереотип: "SimpleClass" // Элемент модели: "TCsDataPipePrim" MUID: (538DC31F03A5) {$Include w:\common\components\rtl\Garant\cs\CsDefine.inc} interface {$If NOT Defined(Nemesis)} uses l3IntfUses , csIdIOHandlerAbstractAdapterPrim , CsCommon , csIdIOHandlerAbstractAdapter , IdIOHandler , Classes ; const c_MaxDataStringLength = 4 * 1024; c_NoMoreFiles = '<>'; type TCsDataPipePrim = class(TcsIdIOHandlerAbstractAdapterPrim) private f_ClientID: TCsClientId; f_IOHandler: TcsIdIOHandlerAbstractAdapter; {* Пока торчит наружу до перехода на постоянно живущее соединение (для подделки протокола) } protected procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aIOHandler: TcsIdIOHandlerAbstractAdapter); reintroduce; overload; constructor Create(aIOHandler: TIdIOHandler); reintroduce; overload; procedure WriteBufferFlush; override; function ReadChar: AnsiChar; override; function ReadCardinal: Cardinal; override; function ReadDateTime: TDateTime; override; function ReadLn: AnsiString; override; function ReadInt64: Int64; override; procedure ReadStream(aStream: TStream; aSize: Int64 = -1); override; function ReadInteger: Integer; override; function ReadSmallInt: SmallInt; override; procedure WriteLn(const aString: AnsiString); override; procedure WriteCardinal(aValue: Cardinal); override; procedure WriteInt64(aValue: Int64); override; procedure WriteStream(aStream: TStream; aByteCount: Int64 = 0); override; procedure WriteChar(aValue: AnsiChar); override; procedure WriteSmallInt(aValue: SmallInt); override; procedure WriteInteger(aValue: Integer); override; procedure WriteDateTime(aValue: TDateTime); override; function WaitForReadData(aTimeout: Integer): Boolean; override; procedure WriteLargeStr(const aString: AnsiString); override; function ReadLargeStr: AnsiString; override; function ReadStreamWithCRCCheck(aStream: TStream; CalcCRCFromBegin: Boolean = True; ReadOffset: Int64 = 0; ReadSize: Int64 = -1): Boolean; override; procedure WriteStreamWithCRCCheck(aStream: TStream; KeepPosition: Boolean = False); override; function ReadBoolean: Boolean; override; procedure WriteBoolean(aValue: Boolean); override; public property ClientID: TCsClientId read f_ClientID write f_ClientID; property IOHandler: TcsIdIOHandlerAbstractAdapter read f_IOHandler; {* Пока торчит наружу до перехода на постоянно живущее соединение (для подделки протокола) } end;//TCsDataPipePrim {$IfEnd} // NOT Defined(Nemesis) implementation {$If NOT Defined(Nemesis)} uses l3ImplUses , csIdIOHandlerAdapter , SysUtils , StrUtils //#UC START# *538DC31F03A5impl_uses* //#UC END# *538DC31F03A5impl_uses* ; constructor TCsDataPipePrim.Create(aIOHandler: TcsIdIOHandlerAbstractAdapter); //#UC START# *538DC49700E1_538DC31F03A5_var* //#UC END# *538DC49700E1_538DC31F03A5_var* begin //#UC START# *538DC49700E1_538DC31F03A5_impl* Assert(aIOHandler <> nil); inherited Create; aIOHandler.SetRefTo(f_IOHandler); //#UC END# *538DC49700E1_538DC31F03A5_impl* end;//TCsDataPipePrim.Create constructor TCsDataPipePrim.Create(aIOHandler: TIdIOHandler); //#UC START# *538DC4BB019F_538DC31F03A5_var* var l_IOHandler : TcsIdIOHandlerAdapter; //#UC END# *538DC4BB019F_538DC31F03A5_var* begin //#UC START# *538DC4BB019F_538DC31F03A5_impl* Assert(aIOHandler <> nil); l_IOHandler := TcsIdIOHandlerAdapter.Create(aIOHandler); try Create(l_IOHandler); finally FreeAndNil(l_IOHandler); end;//try..finally //#UC END# *538DC4BB019F_538DC31F03A5_impl* end;//TCsDataPipePrim.Create procedure TCsDataPipePrim.WriteBufferFlush; //#UC START# *538DB5C7002E_538DC31F03A5_var* //#UC END# *538DB5C7002E_538DC31F03A5_var* begin //#UC START# *538DB5C7002E_538DC31F03A5_impl* f_IOHandler.WriteBufferFlush; //#UC END# *538DB5C7002E_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteBufferFlush function TCsDataPipePrim.ReadChar: AnsiChar; //#UC START# *538DB5E90386_538DC31F03A5_var* //#UC END# *538DB5E90386_538DC31F03A5_var* begin //#UC START# *538DB5E90386_538DC31F03A5_impl* WriteBufferFlush; Result := f_IOHandler.ReadChar; //#UC END# *538DB5E90386_538DC31F03A5_impl* end;//TCsDataPipePrim.ReadChar function TCsDataPipePrim.ReadCardinal: Cardinal; //#UC START# *538DB61100CA_538DC31F03A5_var* //#UC END# *538DB61100CA_538DC31F03A5_var* begin //#UC START# *538DB61100CA_538DC31F03A5_impl* WriteBufferFlush; Result := f_IOHandler.ReadCardinal; //#UC END# *538DB61100CA_538DC31F03A5_impl* end;//TCsDataPipePrim.ReadCardinal function TCsDataPipePrim.ReadDateTime: TDateTime; //#UC START# *538DB62D02C7_538DC31F03A5_var* //#UC END# *538DB62D02C7_538DC31F03A5_var* begin //#UC START# *538DB62D02C7_538DC31F03A5_impl* WriteBufferFlush; Result := f_IOHandler.ReadDateTime; //#UC END# *538DB62D02C7_538DC31F03A5_impl* end;//TCsDataPipePrim.ReadDateTime function TCsDataPipePrim.ReadLn: AnsiString; //#UC START# *538DB6520024_538DC31F03A5_var* //#UC END# *538DB6520024_538DC31F03A5_var* begin //#UC START# *538DB6520024_538DC31F03A5_impl* WriteBufferFlush; Result := f_IOHandler.ReadLn; Result:= AnsiReplaceStr(Result, '#softbreak#', #10); Result:= AnsiReplaceStr(Result, '#hardbreak#', #13); //#UC END# *538DB6520024_538DC31F03A5_impl* end;//TCsDataPipePrim.ReadLn function TCsDataPipePrim.ReadInt64: Int64; //#UC START# *538DB66D02EB_538DC31F03A5_var* //#UC END# *538DB66D02EB_538DC31F03A5_var* begin //#UC START# *538DB66D02EB_538DC31F03A5_impl* WriteBufferFlush; Result := f_IOHandler.ReadInt64; //#UC END# *538DB66D02EB_538DC31F03A5_impl* end;//TCsDataPipePrim.ReadInt64 procedure TCsDataPipePrim.ReadStream(aStream: TStream; aSize: Int64 = -1); //#UC START# *538DB69000E7_538DC31F03A5_var* //#UC END# *538DB69000E7_538DC31F03A5_var* begin //#UC START# *538DB69000E7_538DC31F03A5_impl* WriteBufferFlush; f_IOHandler.ReadStream(aStream, aSize); aStream.Seek(0, soFromBeginning); //#UC END# *538DB69000E7_538DC31F03A5_impl* end;//TCsDataPipePrim.ReadStream function TCsDataPipePrim.ReadInteger: Integer; //#UC START# *538DB78C01B0_538DC31F03A5_var* //#UC END# *538DB78C01B0_538DC31F03A5_var* begin //#UC START# *538DB78C01B0_538DC31F03A5_impl* WriteBufferFlush; Result := f_IOHandler.ReadInteger; //#UC END# *538DB78C01B0_538DC31F03A5_impl* end;//TCsDataPipePrim.ReadInteger function TCsDataPipePrim.ReadSmallInt: SmallInt; //#UC START# *538DB7A4016D_538DC31F03A5_var* //#UC END# *538DB7A4016D_538DC31F03A5_var* begin //#UC START# *538DB7A4016D_538DC31F03A5_impl* WriteBufferFlush; Result := f_IOHandler.ReadSmallInt; //#UC END# *538DB7A4016D_538DC31F03A5_impl* end;//TCsDataPipePrim.ReadSmallInt procedure TCsDataPipePrim.WriteLn(const aString: AnsiString); //#UC START# *538DB7E00144_538DC31F03A5_var* (*const c_MaxDataStringLength = 4 * 1024;*) var l_Str: String; //#UC END# *538DB7E00144_538DC31F03A5_var* begin //#UC START# *538DB7E00144_538DC31F03A5_impl* Assert(Length(aString) <= c_MaxDataStringLength); l_Str := aString; l_Str:= AnsiReplaceStr(l_Str, #10, '#softbreak#'); l_Str:= AnsiReplaceStr(l_Str, #13, '#hardbreak#'); f_IOHandler.WriteLn(l_Str); //#UC END# *538DB7E00144_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteLn procedure TCsDataPipePrim.WriteCardinal(aValue: Cardinal); //#UC START# *538DB804015E_538DC31F03A5_var* //#UC END# *538DB804015E_538DC31F03A5_var* begin //#UC START# *538DB804015E_538DC31F03A5_impl* f_IOHandler.WriteCardinal(aValue); //#UC END# *538DB804015E_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteCardinal procedure TCsDataPipePrim.WriteInt64(aValue: Int64); //#UC START# *538DB83B021B_538DC31F03A5_var* //#UC END# *538DB83B021B_538DC31F03A5_var* begin //#UC START# *538DB83B021B_538DC31F03A5_impl* f_IOHandler.WriteInt64(aValue); //#UC END# *538DB83B021B_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteInt64 procedure TCsDataPipePrim.WriteStream(aStream: TStream; aByteCount: Int64 = 0); //#UC START# *538DB86700DB_538DC31F03A5_var* //#UC END# *538DB86700DB_538DC31F03A5_var* begin //#UC START# *538DB86700DB_538DC31F03A5_impl* f_IOHandler.WriteStream(aStream, aByteCount); //#UC END# *538DB86700DB_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteStream procedure TCsDataPipePrim.WriteChar(aValue: AnsiChar); //#UC START# *538DB8970317_538DC31F03A5_var* //#UC END# *538DB8970317_538DC31F03A5_var* begin //#UC START# *538DB8970317_538DC31F03A5_impl* f_IOHandler.WriteChar(aValue); //#UC END# *538DB8970317_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteChar procedure TCsDataPipePrim.WriteSmallInt(aValue: SmallInt); //#UC START# *538DB8BA00D1_538DC31F03A5_var* //#UC END# *538DB8BA00D1_538DC31F03A5_var* begin //#UC START# *538DB8BA00D1_538DC31F03A5_impl* f_IOHandler.WriteSmallInt(aValue); //#UC END# *538DB8BA00D1_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteSmallInt procedure TCsDataPipePrim.WriteInteger(aValue: Integer); //#UC START# *538DB8DF029E_538DC31F03A5_var* //#UC END# *538DB8DF029E_538DC31F03A5_var* begin //#UC START# *538DB8DF029E_538DC31F03A5_impl* f_IOHandler.WriteInteger(aValue); //#UC END# *538DB8DF029E_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteInteger procedure TCsDataPipePrim.WriteDateTime(aValue: TDateTime); //#UC START# *538DB9070097_538DC31F03A5_var* //#UC END# *538DB9070097_538DC31F03A5_var* begin //#UC START# *538DB9070097_538DC31F03A5_impl* f_IOHandler.WriteDateTime(aValue); //#UC END# *538DB9070097_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteDateTime function TCsDataPipePrim.WaitForReadData(aTimeout: Integer): Boolean; //#UC START# *54536C8F036B_538DC31F03A5_var* //#UC END# *54536C8F036B_538DC31F03A5_var* begin //#UC START# *54536C8F036B_538DC31F03A5_impl* Result := f_IOHandler.WaitForReadData(aTimeOut); //#UC END# *54536C8F036B_538DC31F03A5_impl* end;//TCsDataPipePrim.WaitForReadData procedure TCsDataPipePrim.WriteLargeStr(const aString: AnsiString); //#UC START# *54F5C07302CC_538DC31F03A5_var* //#UC END# *54F5C07302CC_538DC31F03A5_var* begin //#UC START# *54F5C07302CC_538DC31F03A5_impl* f_IOHandler.WriteLargeStr(aString); //#UC END# *54F5C07302CC_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteLargeStr function TCsDataPipePrim.ReadLargeStr: AnsiString; //#UC START# *54F5C09C0302_538DC31F03A5_var* //#UC END# *54F5C09C0302_538DC31F03A5_var* begin //#UC START# *54F5C09C0302_538DC31F03A5_impl* WriteBufferFlush; Result := f_IOHandler.ReadLargeStr; //#UC END# *54F5C09C0302_538DC31F03A5_impl* end;//TCsDataPipePrim.ReadLargeStr function TCsDataPipePrim.ReadStreamWithCRCCheck(aStream: TStream; CalcCRCFromBegin: Boolean = True; ReadOffset: Int64 = 0; ReadSize: Int64 = -1): Boolean; //#UC START# *580F367C0052_538DC31F03A5_var* //#UC END# *580F367C0052_538DC31F03A5_var* begin //#UC START# *580F367C0052_538DC31F03A5_impl* WriteBufferFlush; Result := f_IOHandler.ReadStreamWithCRCCheck(aStream, CalcCRCFromBegin, ReadOffset, ReadSize); //#UC END# *580F367C0052_538DC31F03A5_impl* end;//TCsDataPipePrim.ReadStreamWithCRCCheck procedure TCsDataPipePrim.WriteStreamWithCRCCheck(aStream: TStream; KeepPosition: Boolean = False); //#UC START# *580F36A802FA_538DC31F03A5_var* //#UC END# *580F36A802FA_538DC31F03A5_var* begin //#UC START# *580F36A802FA_538DC31F03A5_impl* f_IOHandler.WriteStreamWithCRCCheck(aStream); //#UC END# *580F36A802FA_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteStreamWithCRCCheck function TCsDataPipePrim.ReadBoolean: Boolean; //#UC START# *58172754028B_538DC31F03A5_var* //#UC END# *58172754028B_538DC31F03A5_var* begin //#UC START# *58172754028B_538DC31F03A5_impl* WriteBufferFlush; Result := f_IOHandler.ReadBoolean; //#UC END# *58172754028B_538DC31F03A5_impl* end;//TCsDataPipePrim.ReadBoolean procedure TCsDataPipePrim.WriteBoolean(aValue: Boolean); //#UC START# *581727750209_538DC31F03A5_var* //#UC END# *581727750209_538DC31F03A5_var* begin //#UC START# *581727750209_538DC31F03A5_impl* f_IOHandler.WriteBoolean(aValue); //#UC END# *581727750209_538DC31F03A5_impl* end;//TCsDataPipePrim.WriteBoolean procedure TCsDataPipePrim.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_538DC31F03A5_var* //#UC END# *479731C50290_538DC31F03A5_var* begin //#UC START# *479731C50290_538DC31F03A5_impl* FreeAndNil(f_IOHandler); inherited; //#UC END# *479731C50290_538DC31F03A5_impl* end;//TCsDataPipePrim.Cleanup {$IfEnd} // NOT Defined(Nemesis) end.
unit NOT_FINISHED_vtSaveDialog; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "VT$Core" // Модуль: "w:/common/components/gui/Garant/VT/NOT_FINISHED_vtSaveDialog.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::VT$Core::Dialogs::TvtSaveDialog // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Этот файл используется только для моделирования, а не для компиляции. ! {$Include ..\VT\vtDefine.inc} interface uses Dialogs ; type TvtSaveDialog = class(TSaveDialog) protected // protected methods function GetFileNameForAdjust: AnsiString; virtual; {* Получить имя файла для корректировки расширения } procedure FirstCorrectFileName; virtual; procedure SetAdjustedFileName(const aFileName: AnsiString); virtual; {* Установить откорректированное имя файла } end;//TvtSaveDialog implementation uses l3Base ; // start class TvtSaveDialog function TvtSaveDialog.GetFileNameForAdjust: AnsiString; //#UC START# *4DCAD2B2008F_4C37236E02A1_var* const c_BufferSize = 255; var l_FileName : array [0..c_BufferSize] of Char; //#UC END# *4DCAD2B2008F_4C37236E02A1_var* begin //#UC START# *4DCAD2B2008F_4C37236E02A1_impl* l3FillChar(l_FileName, SizeOf(l_FileName)); Windows.GetDlgItemText(DialogHandle, vtFileNameDlgCtlId(Handle), l_FileName, c_BufferSize); Result := StrPas(l_FileName); //#UC END# *4DCAD2B2008F_4C37236E02A1_impl* end;//TvtSaveDialog.GetFileNameForAdjust procedure TvtSaveDialog.FirstCorrectFileName; //#UC START# *4DCAD9560008_4C37236E02A1_var* //#UC END# *4DCAD9560008_4C37236E02A1_var* begin //#UC START# *4DCAD9560008_4C37236E02A1_impl* ChangeExtension; //#UC END# *4DCAD9560008_4C37236E02A1_impl* end;//TvtSaveDialog.FirstCorrectFileName procedure TvtSaveDialog.SetAdjustedFileName(const aFileName: AnsiString); //#UC START# *4DCBC96000E3_4C37236E02A1_var* //#UC END# *4DCBC96000E3_4C37236E02A1_var* begin //#UC START# *4DCBC96000E3_4C37236E02A1_impl* Windows.SetDlgItemText(DialogHandle, vtFileNameDlgCtlId(Handle), PAnsiChar(aFileName)); //#UC END# *4DCBC96000E3_4C37236E02A1_impl* end;//TvtSaveDialog.SetAdjustedFileName end.
unit LCLLogger; { Copyright (C) 2006 Luiz Américo Pereira Câmara pascalive@bol.com.br This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, MultiLog; type { TLCLLogger } TLCLLogger = class(TIntegratedLogger) private public procedure SendBitmap(const AText: String; ABitmap: TBitmap); //inline; procedure SendBitmap(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; ABitmap: TBitmap); procedure SendColor(const AText: String; AColor: TColor); //inline; procedure SendColor(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AColor: TColor); end; function ColorToStr(Color: TColor): String; implementation uses IntfGraphics, GraphType, FPimage, FPWriteBMP; function ColorToStr(Color: TColor): String; begin case Color of clBlack : Result:='clBlack'; clMaroon : Result:='clMaroon'; clGreen : Result:='clGreen'; clOlive : Result:='clOlive'; clNavy : Result:='clNavy'; clPurple : Result:='clPurple'; clTeal : Result:='clTeal'; clGray {clDkGray} : Result:='clGray/clDkGray'; clSilver {clLtGray} : Result:='clSilver/clLtGray'; clRed : Result:='clRed'; clLime : Result:='clLime'; clYellow : Result:='clYellow'; clBlue : Result:='clBlue'; clFuchsia : Result:='clFuchsia'; clAqua : Result:='clAqua'; clWhite : Result:='clWhite'; clCream : Result:='clCream'; clNone : Result:='clNone'; clDefault : Result:='clDefault'; clMoneyGreen : Result:='clMoneyGreen'; clSkyBlue : Result:='clSkyBlue'; clMedGray : Result:='clMedGray'; clScrollBar : Result:='clScrollBar'; clBackground : Result:='clBackground'; clActiveCaption : Result:='clActiveCaption'; clInactiveCaption : Result:='clInactiveCaption'; clMenu : Result:='clMenu'; clWindow : Result:='clWindow'; clWindowFrame : Result:='clWindowFrame'; clMenuText : Result:='clMenuText'; clWindowText : Result:='clWindowText'; clCaptionText : Result:='clCaptionText'; clActiveBorder : Result:='clActiveBorder'; clInactiveBorder : Result:='clInactiveBorder'; clAppWorkspace : Result:='clAppWorkspace'; clHighlight : Result:='clHighlight'; clHighlightText : Result:='clHighlightText'; clBtnFace : Result:='clBtnFace'; clBtnShadow : Result:='clBtnShadow'; clGrayText : Result:='clGrayText'; clBtnText : Result:='clBtnText'; clInactiveCaptionText : Result:='clInactiveCaptionText'; clBtnHighlight : Result:='clBtnHighlight'; cl3DDkShadow : Result:='cl3DDkShadow'; cl3DLight : Result:='cl3DLight'; clInfoText : Result:='clInfoText'; clInfoBk : Result:='clInfoBk'; clHotLight : Result:='clHotLight'; clGradientActiveCaption : Result:='clGradientActiveCaption'; clGradientInactiveCaption : Result:='clGradientInactiveCaption'; clForm : Result:='clForm'; { //todo find the conflicts clColorDesktop : Result:='clColorDesktop'; cl3DFace : Result:='cl3DFace'; cl3DShadow : Result:='cl3DShadow'; cl3DHiLight : Result:='cl3DHiLight'; clBtnHiLight : Result:='clBtnHiLight'; } else Result := 'Unknow Color'; end;//case Result := Result + ' ($' + IntToHex(Color, 6) + ')'; end; procedure SaveBitmapToStream(Bitmap: TBitmap; Stream: TStream); var IntfImg: TLazIntfImage; ImgWriter: TFPCustomImageWriter; RawImage: TRawImage; begin // adapted from LCL code IntfImg := nil; ImgWriter := nil; try IntfImg := TLazIntfImage.Create(0,0); IntfImg.LoadFromBitmap(Bitmap.Handle, Bitmap.MaskHandle); IntfImg.GetRawImage(RawImage); if RawImage.IsMasked(True) then ImgWriter := TLazWriterXPM.Create else begin ImgWriter := TFPWriterBMP.Create; TFPWriterBMP(ImgWriter).BitsPerPixel := IntfImg.DataDescription.Depth; end; IntfImg.SaveToStream(Stream, ImgWriter); Stream.Position := 0; finally IntfImg.Free; ImgWriter.Free; end; end; { TLCLLogger } procedure TLCLLogger.SendBitmap(const AText: String; ABitmap: TBitmap); begin SendBitmap(FilterDynamic_forWhatReasonsToLogActually,AText,ABitmap); end; procedure TLCLLogger.SendBitmap(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; ABitmap: TBitmap); var oStream: TStream; begin FilterDynamic_forWhatReasonsToLogActually:= FilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions if ABitmap <> nil then begin oStream:= TMemoryStream.Create; //use custom function to avoid bug in TBitmap.SaveToStream SaveBitmapToStream(ABitmap, oStream); end else oStream:= nil; //SendStream free oStream SendStream(methBitmap, AText, oStream); oStream.Free; end; procedure TLCLLogger.SendColor(const AText: String; AColor: TColor); begin SendColor(FilterDynamic_forWhatReasonsToLogActually, AText, AColor); end; procedure TLCLLogger.SendColor(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AColor: TColor); begin FilterDynamic_forWhatReasonsToLogActually:= FilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue, AText + ' = ' + ColorToStr(AColor),nil); end; end.
// SAX for Pascal, Simple API for XML Buffered Interfaces in Pascal. // Ver 1.1 July 4, 2003 // http://xml.defined.net/SAX (this will change!) // Based on http://www.saxproject.org/ // No warranty; no copyright -- use this as you will. unit BSAX; interface uses Classes, SysUtils, SAX; const {$IFDEF SAX_WIDESTRINGS} IID_IBufferedAttributes = '{B00262C6-2AEB-41B5-9D9F-0C952DDC382C}'; IID_IBufferedContentHandler = '{0B0C23E2-7C9C-483E-939C-C037D3C51392}'; IID_IBufferedDTDHandler = '{FC72C5C4-B218-41E6-B766-A5DE61BF700E}'; IID_IBufferedXMLReader = '{23F9C412-EDF7-4318-8A7F-621B9B586DE9}'; IID_IBufferedXMLFilter = '{2C93D9AC-8938-457D-9996-A52726A17FD6}'; {$ELSE} IID_IBufferedAttributes = '{4376FBEB-EB18-4509-8A7F-F8D5571D9A85}'; IID_IBufferedContentHandler = '{F5B17559-C64E-42AE-83F5-A9E0DB9300F7}'; IID_IBufferedDTDHandler = '{D99C7109-BAD8-4685-AB4B-439E4ABEC9F3}'; IID_IBufferedXMLReader = '{8810E2B8-0D20-4057-BBF5-841010B397AB}'; IID_IBufferedXMLFilter = '{DBFFB137-8706-46B5-BA25-2AFDCFDBAC14}'; {$ENDIF} type // Default Buffered Interfaces IBufferedAttributes = interface; IBufferedContentHandler = interface; IBufferedDTDHandler = interface; IBufferedXMLReader = interface; IBufferedXMLFilter = interface; // Default Vendor Class TBufferedSAXVendor = class; // Interface for a list of XML attributes. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This interface allows access to a list of attributes in // three different ways:</p> // // <ol> // <li>by attribute index;</li> // <li>by Namespace-qualified name; or</li> // <li>by qualified (prefixed) name.</li> // </ol> // // <p>The list will not contain attributes that were declared // #IMPLIED but not specified in the start tag. It will also not // contain attributes used as Namespace declarations (xmlns*) unless // the <code>http://xml.org/sax/features/namespace-prefixes</code> // feature is set to <var>true</var> (it is <var>false</var> by // default). // Because SAX2 conforms to the original "Namespaces in XML" // recommendation, it normally does not // give namespace declaration attributes a namespace URI.</p> // // <p>Some SAX2 parsers may support using an optional feature flag // (<code>http://xml.org/sax/features/xmlns-uris</code>) to request that // those attributes be given URIs, conforming to a later // backwards-incompatible revision of that recommendation. // (The attribute's "local name" will be the prefix, or the empty // string when defining a default element namespace.) // For portability, handler code should always resolve that conflict, // rather than requiring parsers that can change the setting of that // feature flag.</p> // // <p>If the namespace-prefixes feature (see above) is <var>false</var>, // access by qualified name may not be available; if the // <code>http://xml.org/sax/features/namespaces</code> // feature is <var>false</var>, access by Namespace-qualified names // may not be available.</p> // // <p>This interface replaces the now-deprecated SAX1 AttributeList // interface, which does not contain Namespace support. // In addition to Namespace support, it adds the <var>getIndex</var> // methods (below).</p> // // <p>The order of attributes in the list is unspecified, and will // vary from implementation to implementation.</p> // // <p>For reasons of generality and efficiency, strings that are returned // from the interface are declared as pointers (PSAXChar) and lengths. // This requires that the model use procedural out parameters rather // than functions as in the original interfaces.</p> // // @since SAX 2.0 // @see <a href="../BSAXExt/IBufferedDeclHandler.html#attributeDecl">IBufferedDeclHandler.attributeDecl</a> IBufferedAttributes = interface(IUnknown) [IID_IBufferedAttributes] // Return the number of attributes in the list. // // <p>Once you know the number of attributes, you can iterate // through the list.</p> // // @return The number of attributes in the list. // @see <a href="../BSAX/IBufferedAttributes.html#getURI.Integer.PSAXChar.Integer">IBufferedAttributes.getURI(Integer,PSAXChar,Integer)</a> // @see <a href="../BSAX/IBufferedAttributes.html#getLocalName.Integer.PSAXChar.Integer">IBufferedAttributes.getLocalName(Integer,PSAXChar,Integer)</a> // @see <a href="../BSAX/IBufferedAttributes.html#getQName.Integer.PSAXChar.Integer">IBufferedAttributes.getQName(Integer,PSAXChar,Integer)</a> // @see <a href="../BSAX/IBufferedAttributes.html#getType.Integer.PSAXChar.Integer">IBufferedAttributes.getType(Integer,PSAXChar,Integer)</a> // @see <a href="../BSAX/IBufferedAttributes.html#getValue.Integer.PSAXChar.Integer">IBufferedAttributes.getValue(Integer,PSAXChar,Integer)</a> function getLength() : Integer; // Look up an attribute's Namespace URI by index. // // @param index The attribute index (zero-based). // @param uri The Namespace URI, or the empty string if none // is available or if the index is out of range. // @param uriLength The length of the Namespace URI buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getLength">IBufferedAttributes.getLength</a> procedure getURI(index : Integer; out uri: PSAXChar; out uriLength: Integer); // Look up an attribute's local name by index. // // @param index The attribute index (zero-based). // @param localName The local name, or the empty string if Namespace // processing is not being performed or if the // index is out of range. // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getLength">IBufferedAttributes.getLength</a> procedure getLocalName(index : Integer; out localName: PSAXChar; out localNameLength: Integer); // Look up an attribute's XML 1.0 qualified name by index. // // @param index The attribute index (zero-based). // @param qName The XML 1.0 qualified name, or the empty string // if none is available or if the index is out of // range. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getLength">IBufferedAttributes.getLength</a> procedure getQName(index : Integer; out qName: PSAXChar; out qNameLength: Integer); // Look up an attribute's type by index. // // <p>The attribute type is one of the strings "CDATA", "ID", // "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", // or "NOTATION" (always in upper case).</p> // // <p>If the parser has not read a declaration for the attribute, // or if the parser does not report attribute types, then it must // return the value "CDATA" as stated in the XML 1.0 Recommendation // (clause 3.3.3, "Attribute-Value Normalization").</p> // // <p>For an enumerated attribute that is not a notation, the // parser will report the type as "NMTOKEN".</p> // // @param index The attribute index (zero-based). // @param attType The attribute's type as a string or an empty string if the // index is out of range. // @param attTypeLength The length of the attType buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getLength">IBufferedAttributes.getLength</a> procedure getType(index : Integer; out attType: PSAXChar; out attTypeLength: Integer); overload; // Look up an attribute's type by XML 1.0 local name and Namespace URI. // // <p>See <a href="../BSAX/IBufferedAttributes.html#getType.Integer.PSAXChar.Integer">getType(Integer, PSAXChar, Integer)</a> for a description // of the possible types.</p> // // @param uri The Namespace uri // @param uriLength The length of the uri Buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The XML 1.0 local name // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param uri The Namespace uri // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param attType The attribute's type as a string or an empty string if the // attribute is not in the list // @param attTypeLength The length of the attType buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. procedure getType(uri: PSAXChar; uriLength: Integer; localName: PSAXChar; localNameLength: Integer; out attType: PSAXChar; out attTypeLength: Integer); overload; // Look up an attribute's type by XML 1.0 qualified name. // // <p>See <a href="../BSAX/IBufferedAttributes.html#getType.Integer.PSAXChar.Integer">getType(Integer, PSAXChar, Integer)</a> // for a description of the possible types.</p> // // @param qName The XML 1.0 qualified name. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param attType The attribute type as a string, or an empty string if the // attribute is not in the list or if qualified names // are not available. // @param attTypeLength The length of the attType buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. procedure getType(qName: PSAXChar; qNameLength: Integer; out attType: PSAXChar; out attTypeLength: Integer); overload; // Look up an attribute's value by index. // // <p>If the attribute value is a list of tokens (IDREFS, // ENTITIES, or NMTOKENS), the tokens will be concatenated // into a single string with each token separated by a // single space.</p> // // @param index The attribute index (zero-based). // @param value The attribute's value as a string, or an empty string if the // index is out of range. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedAttributes.html#getLength">IBufferedAttributes.getLength</a> procedure getValue(index : Integer; out value: PSAXChar; out valueLength: Integer); overload; // Look up an attribute's value by Namespace name. // // <p>See <a href="../BSAX/IBufferedAttributes.html#getValue.Integer.PSAXChar.Integer)">getValue(Integer, PSAXChar, Integer)</a> // for a description of the possible values.</p> // // @param uri The Namespace URI, or the empty String if the // name has no Namespace URI. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The local name of the attribute. // @param localNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param value The attribute value as a string, or an empty string if the // attribute is not in the list. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. procedure getValue(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; out value: PSAXChar; out valueLength: Integer); overload; // Look up an attribute's value by XML 1.0 QName // // <p>See <a href="../BSAX/IBufferedAttributes.html#getValue.Integer.PSAXChar.Integer">getValue(Integer, PSAXChar, Integer)</a> // for a description of the possible values.</p> // // @param qName The qualified (prefixed) name. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param value The attribute value as a string, or an empty string if the // attribute is not in the list. // @param valueLength The length of the value buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. procedure getValue(qName : PSAXChar; qNameLength : Integer; out value: PSAXChar; out valueLength: Integer); overload; // Look up the index of an attribute by Namespace name. // // @param uri The Namespace URI, or the empty string if // the name has no Namespace URI. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The attribute's local name. // @param loclaNameLength The length of the localName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return The index of the attribute, or -1 if it does not // appear in the list. function getIndex(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer) : Integer; overload; // Look up the index of an attribute by XML 1.0 qualified name. // // @param qName The qualified (prefixed) name. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return The index of the attribute, or -1 if it does not // appear in the list. function getIndex(qName : PSAXChar; qNameLength : Integer) : Integer; overload; // Extension property to get the number of Attributes // // @return The number of attributes in the list. // @see <a href="../BSAX/IBufferedAttributes.html#getLength">IBufferedAttributes.getLength</a> property Length : Integer read getLength; end; // Receive notification of the logical content of a document. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This is the main interface that most SAX applications // implement: if the application needs to be informed of basic parsing // events, it implements this interface and registers an instance with // the SAX parser using the <a href="../BSAX/IBufferedXMLReader.html#setContentHandler">IBufferedXMLReader</a> // The parser uses the instance to report basic document-related events // like the start and end of elements and character data.</p> // // <p>The order of events in this interface is very important, and // mirrors the order of information in the document itself. For // example, all of an element's content (character data, processing // instructions, and/or subelements) will appear, in order, between // the startElement event and the corresponding endElement event.</p> // // <p>This interface is similar to the now-deprecated SAX 1.0 // DocumentHandler interface, but it adds support for Namespaces // and for reporting skipped entities (in non-validating XML // processors).</p> // // <p>For reasons of generality and efficiency, strings that are returned // from the interface are declared as pointers (PSAXChar) and lengths. // This requires that the model use procedural out parameters rather // than functions as in the original interfaces.</p> // // @since SAX 2.0 // @see <a href="../BSAX/IBufferedXMLReader.html">IBufferedXMLReader</a> // @see <a href="../BSAX/IBufferedDTDHandler.html">IBufferedDTDHandler</a> // @see <a href="../SAX/IErrorHandler.html">IErrorHandler</a> IBufferedContentHandler = interface(IUnknown) [IID_IBufferedContentHandler] // Receive an object for locating the origin of SAX document events. // // <p>SAX parsers are strongly encouraged (though not absolutely // required) to supply a locator: if it does so, it must supply // the locator to the application by invoking this method before // invoking any of the other methods in the ContentHandler // interface.</p> // // <p>The locator allows the application to determine the end // position of any document-related event, even if the parser is // not reporting an error. Typically, the application will // use this information for reporting its own errors (such as // character content that does not match an application's // business rules). The information returned by the locator // is probably not sufficient for use with a search engine.</p> // // <p>Note that the locator will return correct information only // during the invocation SAX event callbacks after // <a href="../BSAX/IBufferedContentHandler.html#startDocument">startDocument</a> returns and before // <a href="../BSAX/IBufferedContentHandler.html#endDocument">endDocument</a> is called. The // application should not attempt to use it at any other time.</p> // // @param locator An object that can return the location of // any SAX document event. // @see <a href="../BSAX/IBufferedLocator.html">IBufferedLocator</a> procedure setDocumentLocator(const locator: ILocator); // Receive notification of the beginning of a document. // // <p>The SAX parser will invoke this method only once, before any // other event callbacks (except for <a href="../BSAX/IBufferedContentHandler.html#setDocumentLocator">setDocumentLocator</a>).</p> // // @exception ESAXException Any SAX exception. // @see <a href="../BSAX/IBufferedContentHandler.html#endDocument">IBufferedContentHandler.endDocument</a> procedure startDocument(); // Receive notification of the end of a document. // // <p>The SAX parser will invoke this method only once, and it will // be the last method invoked during the parse. The parser shall // not invoke this method until it has either abandoned parsing // (because of an unrecoverable error) or reached the end of // input.</p> // // @exception ESAXException Any SAX exception. // @see <a href="../BSAX/IBufferedContentHandler.html#startDocument">IBufferedContentHandler.startDocument</a> procedure endDocument(); // Begin the scope of a prefix-URI Namespace mapping. // // <p>The information from this event is not necessary for // normal Namespace processing: the SAX XML reader will // automatically replace prefixes for element and attribute // names when the <code>http://xml.org/sax/features/namespaces</code> // feature is <var>true</var> (the default).</p> // // <p>There are cases, however, when applications need to // use prefixes in character data or in attribute values, // where they cannot safely be expanded automatically; the // start/endPrefixMapping event supplies the information // to the application to expand prefixes in those contexts // itself, if necessary.</p> // // <p>Note that start/endPrefixMapping events are not // guaranteed to be properly nested relative to each other: // all startPrefixMapping events will occur immediately before the // corresponding <a href="../BSAX/IBufferedContentHandler.html#startElement">startElement</a> event, // and all <a href="../BSAX/IBufferedContentHandler.html#endPrefixMapping">endPrefixMapping</a> // events will occur immediately after the corresponding // <a href="../BSAX/IBufferedContentHandler.html#endElement">endElement</a> event // but their order is not otherwise // guaranteed.</p> // // <p>There should never be start/endPrefixMapping events for the // "xml" prefix, since it is predeclared and immutable.</p> // // @param prefix The Namespace prefix being declared. // An empty string is used for the default element namespace, // which has no prefix. // @param prefixLength The length of the prefix buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param uri The Namespace URI the prefix is mapped to. // @param uriLength The length of the uri buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The client may throw // an exception during processing. // @see <a href="../BSAX/IBufferedContentHandler.html#endPrefixMapping">IBufferedContentHandler.endPrefixMapping</a> // @see <a href="../BSAX/IBufferedContentHandler.html#startElement">IBufferedContentHandler.startElement</a> procedure startPrefixMapping(prefix: PSAXChar; prefixLength: Integer; uri: PSAXChar; uriLength: Integer); // End the scope of a prefix-URI mapping. // // <p>See <a href="../BSAX/IBufferedContentHandler.html#startPrefixMapping">startPrefixMapping</a> for // details. These events will always occur immediately after the // corresponding <a href="../BSAX/IBufferedContentHandler.html#endElement">endElement</a> event, but the order of // <a href="../BSAX/IBufferedContentHandler.html#endPrefixMapping">endPrefixMapping</a> events is not otherwise // guaranteed.</p> // // @param prefix The prefix that was being mapped. // Use the empty string when a default mapping scope ends. // @param prefixLength The length of the prefix buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException The client may throw // an exception during processing. // @see <a href="../BSAX/IBufferedContentHandler.html#startPrefixMapping">IBufferedContentHandler.startPrefixMapping</a> // @see <a href="../BSAX/IBufferedContentHandler.html#endElement">IBufferedContentHandler.endElement</a> procedure endPrefixMapping(prefix: PSAXChar; prefixLength: Integer); // Receive notification of the beginning of an element. // // <p>The Parser will invoke this method at the beginning of every // element in the XML document; there will be a corresponding // <a href="../BSAX/IBufferedContentHandler.html#endElement">endElement</a> event for every startElement event // (even when the element is empty). All of the element's content will be // reported, in order, before the corresponding endElement // event.</p> // // <p>This event allows up to three name components for each // element:</p> // // <ol> // <li>the Namespace URI;</li> // <li>the local name; and</li> // <li>the qualified (prefixed) name.</li> // </ol> // // <p>Any or all of these may be provided, depending on the // values of the <var>http://xml.org/sax/features/namespaces</var> // and the <var>http://xml.org/sax/features/namespace-prefixes</var> // properties:</p> // // <ul> // <li>the Namespace URI and local name are required when // the namespaces property is <var>true</var> (the default), and are // optional when the namespaces property is <var>false</var> (if one is // specified, both must be);</li> // <li>the qualified name is required when the namespace-prefixes property // is <var>true</var>, and is optional when the namespace-prefixes property // is <var>false</var> (the default).</li> // </ul> // // <p>Note that the attribute list provided will contain only // attributes with explicit values (specified or defaulted): // #IMPLIED attributes will be omitted. The attribute list // will contain attributes used for Namespace declarations // (xmlns* attributes) only if the // <code>http://xml.org/sax/features/namespace-prefixes</code> // property is true (it is false by default, and support for a // true value is optional).</p> // // <p>Like <a href="../BSAX/IBufferedContentHandler.html#characters">characters</a>, attribute values may have // characters that need more than one <code>char</code> value.</p> // // @param uri The Namespace URI, or the empty string if the // element has no Namespace URI or if Namespace // processing is not being performed. // @param uriLength The length of the uri buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The local name (without prefix), or the // empty string if Namespace processing is not being // performed. // @param localNameLength The length of the localName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param qName The qualified name (with prefix), or the // empty string if qualified names are not available. // @param qNameLength The length of the qName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param atts The attributes attached to the element. If // there are no attributes, it shall be an empty // IBufferedAttributes object or nil. // @exception ESAXException Any SAX exception. // @see <a href="../BSAX/IBufferedContentHandler.html#endElement">IBufferedContentHandler.endElement</a> // @see <a href="../BSAX/IBufferedAttributes.html">IBufferedAttributes</a> procedure startElement(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer; const atts: IBufferedAttributes); // Receive notification of the end of an element. // // <p>The SAX parser will invoke this method at the end of every // element in the XML document; there will be a corresponding // <a href="../BSAX/IBufferedContentHandler.html#startElement">startElement</a> event for every endElement // event (even when the element is empty).</p> // // <p>For information on the names, see startElement.</p> // // @param uri The Namespace URI, or the empty string if the // element has no Namespace URI or if Namespace // processing is not being performed. // @param uriLength The length of the uri buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param localName The local name (without prefix), or the // empty string if Namespace processing is not being // performed. // @param localNameLength The length of the localName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param qName The qualified name (with prefix), or the // empty string if qualified names are not available. // @param qNameLength The length of the qName buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. procedure endElement(uri : PSAXChar; uriLength : Integer; localName : PSAXChar; localNameLength : Integer; qName : PSAXChar; qNameLength : Integer); // Receive notification of character data. // // <p>The Parser will call this method to report each chunk of // character data. SAX parsers may return all contiguous character // data in a single chunk, or they may split it into several // chunks; however, all of the characters in any single event // must come from the same external entity so that the Locator // provides useful information.</p> // // <p>The application must not attempt to read from the array // outside of the specified range.</p> // // <p>Individual characters may consist of more than one Java // <code>char</code> value. There are two important cases where this // happens, because characters can't be represented in just sixteen bits. // In one case, characters are represented in a <em>Surrogate Pair</em>, // using two special Unicode values. Such characters are in the so-called // "Astral Planes", with a code point above U+FFFF. A second case involves // composite characters, such as a base character combining with one or // more accent characters. </p> // // <p> Your code should not assume that algorithms using // <code>char</code>-at-a-time idioms will be working in character // units; in some cases they will split characters. This is relevant // wherever XML permits arbitrary characters, such as attribute values, // processing instruction data, and comments as well as in data reported // from this method. It's also generally relevant whenever Java code // manipulates internationalized text; the issue isn't unique to XML.</p> // // <p>Note that some parsers will report whitespace in element // content using the <a href="../BSAX/IBufferedContentHandler.html#ignorableWhitespace">ignorableWhitespace</a> // method rather than this one (validating parsers <em>must</em> // do so).</p> // // @param ch Pointer to the characters from the XML document. // @param chLength The length of the ch buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. // @see <a href="../BSAX/IBufferedContentHandler.html#ignorableWhitespace">IBufferedContentHandler.ignorableWhitespace</a> // @see <a href="../SAX/ILocator.html">ILocator</a> procedure characters(ch : PSAXChar; chLength : Integer); // Receive notification of ignorable whitespace in element content. // // <p>Validating Parsers must use this method to report each chunk // of whitespace in element content (see the W3C XML 1.0 recommendation, // section 2.10): non-validating parsers may also use this method // if they are capable of parsing and using content models.</p> // // <p>SAX parsers may return all contiguous whitespace in a single // chunk, or they may split it into several chunks; however, all of // the characters in any single event must come from the same // external entity, so that the Locator provides useful // information.</p> // // <p>The application must not attempt to read from the array // outside of the specified range.</p> // // @param ch Pointer to the characters from the XML document. // @param chLength The length of the ch buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. // @see <a href="../BSAX/IBufferedContentHandler.html#characters">IBufferedContentHandler.characters</a> procedure ignorableWhitespace(ch : PSAXChar; chLength : Integer); // Receive notification of a processing instruction. // // <p>The Parser will invoke this method once for each processing // instruction found: note that processing instructions may occur // before or after the main document element.</p> // // <p>A SAX parser must never report an XML declaration (XML 1.0, // section 2.8) or a text declaration (XML 1.0, section 4.3.1) // using this method.</p> // // <p>Like <a href="../BSAX/IBufferedContentHandler.html#characters">characters</a>, processing instruction // data may have characters that need more than one <code>char</code> // value. </p> // // @param target The processing instruction target. // @param targetLength The length of the target buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param data The processing instruction data, or the empty string // if none was supplied. The data does not include any // whitespace separating it from the target. // @param dataLength The length of the data buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. procedure processingInstruction(target : PSAXChar; targetLength : Integer; data : PSAXChar; dataLength : Integer); // Receive notification of a skipped entity. // This is not called for entity references within markup constructs // such as element start tags or markup declarations. (The XML // recommendation requires reporting skipped external entities. // SAX also reports internal entity expansion/non-expansion, except // within markup constructs.) // // <p>The Parser will invoke this method each time the entity is // skipped. Non-validating processors may skip entities if they // have not seen the declarations (because, for example, the // entity was declared in an external DTD subset). All processors // may skip external entities, depending on the values of the // <code>http://xml.org/sax/features/external-general-entities</code> // and the // <code>http://xml.org/sax/features/external-parameter-entities</code> // properties.</p> // // @param name The name of the skipped entity. If it is a // parameter entity, the name will begin with '%', and if // it is the external DTD subset, it will be the string // "[dtd]". // @param nameLength The length of the name buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. procedure skippedEntity(name : PSAXChar; nameLength : Integer); end; // Receive notification of basic DTD-related events. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>If a SAX application needs information about notations and // unparsed entities, then the application implements this // interface and registers an instance with the SAX parser using // the parser's setDTDHandler method. The parser uses the // instance to report notation and unparsed entity declarations to // the application.</p> // // <p>Note that this interface includes only those DTD events that // the XML recommendation <em>requires</em> processors to report: // notation and unparsed entity declarations.</p> // // <p>The SAX parser may report these events in any order, regardless // of the order in which the notations and unparsed entities were // declared; however, all DTD events must be reported after the // document handler's startDocument event, and before the first // startElement event. // If the <a href="../BSAXExt/IBufferedLexicalHandler.html">IBufferedLexicalHandler</a> is // used, these events must also be reported before the endDTD event.)</p> // // <p>It is up to the application to store the information for // future use (perhaps in a hash table or object tree). // If the application encounters attributes of type "NOTATION", // "ENTITY", or "ENTITIES", it can use the information that it // obtained through this interface to find the entity and/or // notation corresponding with the attribute value.</p> // // <p>For reasons of generality and efficiency, strings that are returned // from the interface are declared as pointers (PSAXChar) and lengths. // This requires that the model use procedural out parameters rather // than functions as in the original interfaces.</p> // // @since SAX 1.0 // @see <a href="../BSAX/IBufferedXMLReader.html#setDTDHandler">IBufferedXMLReader.setDTDHandler</a> IBufferedDTDHandler = interface(IUnknown) [IID_IBufferedDTDHandler] // Receive notification of a notation declaration event. // // <p>It is up to the application to record the notation for later // reference, if necessary; // notations may appear as attribute values and in unparsed entity // declarations, and are sometime used with processing instruction // target names.</p> // // <p>At least one of publicId and systemId must be non-empty. // If a system identifier is present, and it is a URL, the SAX // parser must resolve it fully before passing it to the // application through this event.</p> // // <p>There is no guarantee that the notation declaration will be // reported before any unparsed entities that use it.</p> // // @param name The notation name. // @param nameLength The length of the name buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param publicId The notation's public identifier, or empty if // none was given. // @param publicIdLength The length of the publicId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param systemId The notation's system identifier, or empty if // none was given. // @param systemIdLength The length of the systemId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @exception ESAXException Any SAX exception. // @see <a href="../BSAX/IBufferedDTDHandler.html#unparsedEntityDecl">IBufferedDTDHandler.unparsedEntityDecl</a> // @see <a href="../BSAX/IBufferedAttributes.html">IBufferedAttributes</a> procedure notationDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer); // Receive notification of an unparsed entity declaration event. // // <p>Note that the notation name corresponds to a notation // reported by the <a href="../BSAX/IBufferedDTDHandler.html#notationDecl">notationDecl</a> event. // It is up to the application to record the entity for later // reference, if necessary; // unparsed entities may appear as attribute values.</p> // // <p>If the system identifier is a URL, the parser must resolve it // fully before passing it to the application.</p> // // @exception ESAXException Any SAX exception. // @param name The unparsed entity's name. // @param nameLength The length of the name buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param publicId The entity's public identifier, or empty if none // was given. // @param publicIdLength The length of the publicId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param systemId The entity's system identifier. // @param systemIdLength The length of the systemId buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param notationName The name of the associated notation. // @param notationNameLength The length of the notationNameLength buffer. // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../BSAX/IBufferedDTDHandler.html#notationDecl">IBufferedDTDHandler.notationDecl</a> // @see <a href="../BSAX/IBufferedAttributes.html">IBufferedAttributes</a> procedure unparsedEntityDecl(name : PSAXChar; nameLength : Integer; publicId : PSAXChar; publicIdLength : Integer; systemId : PSAXChar; systemIdLength : Integer; notationName : PSAXChar; notationNameLength : Integer); end; // Interface for reading an XML document using callbacks. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>XMLReader is the interface that an XML parser's SAX2 driver must // implement. This interface allows an application to set and // query features and properties in the parser, to register // event handlers for document processing, and to initiate // a document parse.</p> // // <p>All SAX interfaces are assumed to be synchronous: the // <a href="../BSAX/IBufferedXMLReader.html#parse">parse</a> methods must not return until parsing // is complete, and readers must wait for an event-handler callback // to return before reporting the next event.</p> // // <p>This interface replaces the (now deprecated) SAX 1.0 <a href="../SAX/IParser.html">IParser</a> // interface. The XMLReader interface contains two important enhancements over the old Parser // interface (as well as some minor ones):</p> // // <ol> // <li>it adds a standard way to query and set features and // properties; and</li> // <li>it adds Namespace support, which is required for many // higher-level XML standards.</li> // </ol> // // <p>There are adapters available to convert a SAX1 Parser to // a SAX2 XMLReader and vice-versa.</p> // // <p>For reasons of generality and efficiency, strings that are returned // from the interface are declared as pointers (PSAXChar) and lengths. // This requires that the model use procedural out parameters rather // than functions as in the original interfaces.</p> // // @since SAX 2.0 // @see <a href="../BSAX/IBufferedXMLFilter.html">IBufferedXMLFilter</a> IBufferedXMLReader = interface(IBaseXMLReader) [IID_IBufferedXMLReader] // Allow an application to register a DTD event handler. // // <p>If the application does not register a DTD handler, all DTD // events reported by the SAX parser will be silently ignored.</p> // // <p>Applications may register a new or different handler in the // middle of a parse, and the SAX parser must begin using the new // handler immediately.</p> // // @param handler The DTD handler. // @see <a href="../BSAX/IBufferedXMLReader.html#getDTDHandler">IBufferedXMLReader.getDTDHandler</a> procedure setDTDHandler(const handler : IBufferedDTDHandler); // Return the current DTD handler. // // @return The current DTD handler, or null if none // has been registered. // @see <a href="../BSAX/IBufferedXMLReader.html#setDTDHandler">IBufferedXMLReader.setDTDHandler</a> function getDTDHandler() : IBufferedDTDHandler; // Allow an application to register a content event handler. // // <p>If the application does not register a content handler, all // content events reported by the SAX parser will be silently // ignored.</p> // // <p>Applications may register a new or different handler in the // middle of a parse, and the SAX parser must begin using the new // handler immediately.</p> // // @param handler The content handler. // @see <a href="../BSAX/IBufferedXMLReader.html#getContentHandler">IBufferedXMLReader.getContentHandler</a> procedure setContentHandler(const handler : IBufferedContentHandler); // Return the current content handler. // // @return The current content handler, or nil if none // has been registered. // @see <a href="../BSAX/IBufferedXMLReader.html#setContentHandler">IBufferedXMLReader.setContentHandler</a> function getContentHandler() : IBufferedContentHandler; // Extension property to get and set the ContentHandler // // @return The current content handler, or nil if none // has been registered. // @see <a href="../BSAX/IBufferedXMLReader.html#getContentHandler">IBufferedXMLReader.getContentHandler</a> // @see <a href="../BSAX/IBufferedXMLReader.html#setContentHandler">IBufferedXMLReader.setContentHandler</a> property ContentHandler: IBufferedContentHandler read getContentHandler write setContentHandler; // Extension property to get and set the DTDHandler // // @return The current DTD handler, or nil if none // has been registered. // @see <a href="../BSAX/IBufferedXMLReader.html#getDTDHandler">IBufferedXMLReader.getDTDHandler</a> // @see <a href="../BSAX/IBufferedXMLReader.html#setDTDHandler">IBufferedXMLReader.setDTDHandler</a> property DTDHandler: IBufferedDTDHandler read getDTDHandler write setDTDHandler; end; // Interface for an XML filter. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>An XML filter is like an XML reader, except that it obtains its // events from another XML reader rather than a primary source like // an XML document or database. Filters can modify a stream of // events as they pass on to the final application.</p> // // <p>The XMLFilterImpl helper class provides a convenient base // for creating SAX2 filters, by passing on all <a href="../SAX/IEntityResolver.html">IEntityResolver</a>, // <a href="../BSAX/IBufferedDTDHandler.html">IBufferedDTDHandler</a>, // <a href="../BSAX/IBufferedContentHandler.html">IBufferedContentHandler</a> and // <a href="../SAX/IErrorHandler.html">IErrorHandler</a> events automatically.</p> // // @since SAX 2.0 // @see <a href="../BSAXHelpers/TBufferedXMLFilterImpl.html">TBufferedXMLFilterImpl</a> IBufferedXMLFilter = interface(IBufferedXMLReader) [IID_IBufferedXMLFilter] // Set the parent reader. // // <p>This method allows the application to link the filter to // a parent reader (which may be another filter). The argument // may not be null.</p> // // @param parent The parent reader. procedure setParent(const parent : IBufferedXMLReader); // Get the parent reader. // // <p>This method allows the application to query the parent // reader (which may be another filter). It is generally a // bad idea to perform any operations on the parent reader // directly: they should all pass through this filter.</p> // // @return The parent filter, or nil if none has been set. function getParent() : IBufferedXMLReader; // Extension property to get and set the IBufferedXMLFilters's parent // // @return The parent reader. // @see <a href="../BSAX/IBufferedXMLFilter.html#getParent">IBufferedXMLFilter.getParent</a> // @see <a href="../BSAX/IBufferedXMLFilter.html#setParent">IBufferedXMLFilter.setParent</a> property Parent: IBufferedXMLReader read getParent write setParent; end; TBufferedSAXVendor = class(TSAXVendor) public function BufferedXMLReader: IBufferedXMLReader; virtual; abstract; end; implementation end.
{8. a.​ Realice un módulo que reciba un par de números (numA,numB) y retorne si numB es el doble de numA. b. Utilizando el módulo realizado en el inciso a., realice un programa que lea secuencias de pares de números hasta encontrar el par (0,0), e informe la cantidad total de pares de números leídos, y la cantidad de pares en las que numB es el doble de numA. Por ejemplo, si se lee la siguiente secuencia: (1,2) (3,4) (9,3) (7,14) (0,0) el programa debe informar los valores 4 (cantidad de pares leídos) y 2 (cantidad de pares en los que numB es el doble de numA). } program ejercicio8b; function doble(numA:Integer; numB:Integer): Boolean; var ok: Boolean; begin ok:= false; if (numB = numA * 2 ) then begin ok:=true; end; doble:= ok; end; var numA, numB,cantLeidos,cantEsDoble: Integer; begin cantLeidos:=0; cantEsDoble:=0; write('Ingrese el numeroA: '); readln(numA); write('Ingrese el numeroB: '); readln(numB); writeln('--------------------'); while (numA <> 0) or (numB <> 0) do begin cantLeidos:= cantLeidos + 1; if doble(numA, numB) then begin cantEsDoble:= cantEsDoble + 1; end; write('Ingrese el numeroA: '); readln(numA); write('Ingrese el numeroB: '); readln(numB); writeln('--------------------'); end; writeln('La cantidad de numeros totales de pares leidos son: ', cantLeidos) ; writeln('La cantidad de pares en las que numB es el doble de numA es: ', cantEsDoble); readln(); end.
unit nsOpenOrSaveInternetFileDialog_Form; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, nsDownloaderInterfaces, eeButton, vtButton, vtRadioButton, vtLabel, vcmEntityForm, vtCtrls; type TnsOpenOrSaveInternetFileDialog = class(TForm, InsDownloadParamsObserver) btnOpen: TvtButton; btnSave: TvtButton; btnCancel: TvtButton; lblPrompt: TvtLabel; lblFileNameCaption: TvtLabel; lblFileTypeCaption: TvtLabel; lblURLCaption: TvtLabel; lblFileName: TvtLabel; lblFileType: TvtLabel; lblURL: TvtLabel; imgFileTypeIcon: TvtImage; procedure btnOpenClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); private FParams: Pointer; FUpdatingParams: Boolean; procedure UpdateControls; protected procedure NotifyParamsChanged(const AParams: InsDownloadParams); function GetParams: InsDownloadParams; procedure SetParams(const AParams: InsDownloadParams); property Params: InsDownloadParams read GetParams write SetParams; public class function ChooseParams(const AParams: InsDownloadParams): Boolean; end; implementation uses StrUtils, vtSaveDialog; {$R *.dfm} { TOpenOrSaveInternetFileDialog } class function TnsOpenOrSaveInternetFileDialog.ChooseParams( const AParams: InsDownloadParams): Boolean; var l_Form: TnsOpenOrSaveInternetFileDialog; begin l_Form := Create(nil); try l_Form.Params := AParams; Result := (l_Form.ShowModal = mrOk); finally FreeAndNil(l_Form); end; end; procedure TnsOpenOrSaveInternetFileDialog.UpdateControls; function lp_GetRoot(const APath: string): string; var i: Integer; begin i := Pos('//', APath); if i>0 then i := PosEx('/', APath, i + 2) else i := Pos('/', APath); if (i = 0) then i := Length(APath); Result := Copy(APath, 1, i); end; begin lblFileName.Caption := Params.FileName; lblFileType.Caption := Params.FileTypeString; lblURL.Caption := lp_GetRoot(Params.URL); end; procedure TnsOpenOrSaveInternetFileDialog.NotifyParamsChanged(const AParams: InsDownloadParams); begin if (not FUpdatingParams) then UpdateControls; end; function TnsOpenOrSaveInternetFileDialog.GetParams: InsDownloadParams; begin Result := InsDownloadParams(FParams); end; procedure TnsOpenOrSaveInternetFileDialog.SetParams(const AParams: InsDownloadParams); begin if (FParams <> nil) then InsDownloadParams(FParams).Unsubscribe(Self); FParams := Pointer(AParams); if (FParams <> nil) then InsDownloadParams(FParams).Subscribe(Self); UpdateControls; end; procedure TnsOpenOrSaveInternetFileDialog.btnOpenClick(Sender: TObject); begin Params.FileAction := dfaOpen; ModalResult := mrOK; end; procedure TnsOpenOrSaveInternetFileDialog.btnSaveClick(Sender: TObject); var l_SaveDialog: TvtSaveDialog; l_FileExt: String; begin Params.FileAction := dfaSave; l_SaveDialog := TvtSaveDialog.Create(Self); try l_FileExt := ExtractFileExt(Params.FileName); l_SaveDialog.DefaultExt := l_FileExt; Delete(l_FileExt, 1, 1); l_SaveDialog.FileName := ExtractFileName(Params.FileName); l_SaveDialog.Filter := Format('%s|*.%s', [l_FileExt, l_FileExt]); if l_SaveDialog.Execute then begin Params.FileName := l_SaveDialog.FileName; ModalResult := mrOk; end else ModalResult := mrCancel; finally FreeAndNil(l_SaveDialog); end; end; end.
unit MFichas.Model.Usuario.TipoDeUsuario.Factory; interface uses MFichas.Model.Usuario.TipoDeUsuario.Interfaces, MFichas.Model.Usuario.Interfaces, MFichas.Model.Usuario.TipoDeUsuario.Caixa, MFichas.Model.Usuario.TipoDeUsuario.Fiscal, MFichas.Model.Usuario.TipoDeUsuario.Gerente; type TModelUsuarioTipoDeUsuarioFactory = class(TInterfacedObject, iModelUsuarioTipoDeUsuarioFactory) private constructor Create; public destructor Destroy; override; class function New: iModelUsuarioTipoDeUsuarioFactory; function Caixa(AParent: iModelUsuario) : iModelUsuarioMetodos; function Fiscal(AParent: iModelUsuario) : iModelUsuarioMetodos; function Gerente(AParent: iModelUsuario): iModelUsuarioMetodos; end; implementation { TModelUsuarioTipoDeUsuarioFactory } function TModelUsuarioTipoDeUsuarioFactory.Caixa( AParent: iModelUsuario): iModelUsuarioMetodos; begin Result := TModelUsuarioTipoDeUsuarioCaixa.New(AParent); end; constructor TModelUsuarioTipoDeUsuarioFactory.Create; begin end; destructor TModelUsuarioTipoDeUsuarioFactory.Destroy; begin inherited; end; function TModelUsuarioTipoDeUsuarioFactory.Fiscal( AParent: iModelUsuario): iModelUsuarioMetodos; begin Result := TModelUsuarioTipoDeUsuarioFiscal.New(AParent); end; function TModelUsuarioTipoDeUsuarioFactory.Gerente( AParent: iModelUsuario): iModelUsuarioMetodos; begin Result := TModelUsuarioTipoDeUsuarioGerente.New(AParent); end; class function TModelUsuarioTipoDeUsuarioFactory.New: iModelUsuarioTipoDeUsuarioFactory; begin Result := Self.Create; end; end.
unit kwVTControlsPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwVTControlsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "kwVTControlsPack" MUID: (4F6096D500C3) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , tfwGlobalKeyWord , DragData , tfwScriptingInterfaces , TypInfo , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4F6096D500C3impl_uses* //#UC END# *4F6096D500C3impl_uses* ; type TkwDDSupportGetState = {final} class(TtfwGlobalKeyWord) {* Слово скрипта DDSupport:GetState } private function DDSupport_GetState(const aCtx: TtfwContext): TDragDataState; {* Реализация слова скрипта DDSupport:GetState } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwDDSupportGetState function TkwDDSupportGetState.DDSupport_GetState(const aCtx: TtfwContext): TDragDataState; {* Реализация слова скрипта DDSupport:GetState } //#UC START# *552E449000E2_552E449000E2_Word_var* //#UC END# *552E449000E2_552E449000E2_Word_var* begin //#UC START# *552E449000E2_552E449000E2_Word_impl* Result := TDragDataSupport.Instance.DragState; //#UC END# *552E449000E2_552E449000E2_Word_impl* end;//TkwDDSupportGetState.DDSupport_GetState class function TkwDDSupportGetState.GetWordNameForRegister: AnsiString; begin Result := 'DDSupport:GetState'; end;//TkwDDSupportGetState.GetWordNameForRegister function TkwDDSupportGetState.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TDragDataState); end;//TkwDDSupportGetState.GetResultTypeInfo function TkwDDSupportGetState.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 0; end;//TkwDDSupportGetState.GetAllParamsCount function TkwDDSupportGetState.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([]); end;//TkwDDSupportGetState.ParamsTypes procedure TkwDDSupportGetState.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushInt(Ord(DDSupport_GetState(aCtx))); end;//TkwDDSupportGetState.DoDoIt initialization TkwDDSupportGetState.RegisterInEngine; {* Регистрация DDSupport_GetState } TtfwTypeRegistrator.RegisterType(TypeInfo(TDragDataState)); {* Регистрация типа TDragDataState } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit daScheme; // Модуль: "w:\common\components\rtl\Garant\DA\daScheme.pas" // Стереотип: "SimpleClass" // Элемент модели: "TdaScheme" MUID: (552D07EB03CB) {$Include w:\common\components\rtl\Garant\DA\daDefine.inc} interface uses l3IntfUses , l3ProtoObject , daInterfaces , daTypes , daTableDescription ; const da_TreeTableKinds = [da_ftSources, da_ftTypes, da_ftClasses, da_ftKeywords, da_ftBelongs, da_ftWarnings, da_ftCoSources, da_ftPrefixes, da_ftTerritories, da_ftNorms, da_ftAccessGroups, da_ftAnnoClasses, da_ftServiceInfo]; cStoredProcCount = 8; cDefaultSchemeName = 'archi'; type TFamilyDescriptions = array [TdaTables] of IdaTableDescription; TdaFillTableDescriptionProc = procedure(aTable: TdaTableDescription) of object; TdaScheme = class(Tl3ProtoObject) private f_Tables: TFamilyDescriptions; private procedure BuildMain; procedure BuildFamily; function MakeTableDescription(aKind: TdaTables; const aSQLName: AnsiString; const aDescription: AnsiString; aProc: TdaFillTableDescriptionProc; const aScheme: AnsiString = ''; aDublicate: Boolean = False; aFake: Boolean = False): IdaTableDescription; procedure FillMainAccess(aTable: TdaTableDescription); procedure FillMainPassword(aTable: TdaTableDescription); procedure FillMainUsers(aTable: TdaTableDescription); procedure FillMainGroups(aTable: TdaTableDescription); procedure FillMainGroupMembers(aTable: TdaTableDescription); procedure FillMainFamily(aTable: TdaTableDescription); procedure FillMainFree(aTable: TdaTableDescription); procedure FillMainJournal(aTable: TdaTableDescription); procedure FillControl(aTable: TdaTableDescription); procedure FillMainRegions(aTable: TdaTableDescription); procedure FillFamilyDocuments(aTable: TdaTableDescription); procedure FillFamilyHyperlinks(aTable: TdaTableDescription); procedure FillFamilySubs(aTable: TdaTableDescription); procedure FillFamilyFree(aTable: TdaTableDescription); procedure FillFamilySources(aTable: TdaTableDescription); procedure FillFamilyTypes(aTable: TdaTableDescription); procedure FillFamilyClasses(aTable: TdaTableDescription); procedure FillFamilyKeywords(aTable: TdaTableDescription); procedure FillFamilyBelongs(aTable: TdaTableDescription); procedure FillFamilyDateCodes(aTable: TdaTableDescription); procedure FillFamilyWarnings(aTable: TdaTableDescription); procedure FillFamilyCorrections(aTable: TdaTableDescription); procedure FillFamilyCoSources(aTable: TdaTableDescription); procedure FillFamilyPublishedIn(aTable: TdaTableDescription); procedure FillFamilyPrefixes(aTable: TdaTableDescription); procedure FillFamilyTerritories(aTable: TdaTableDescription); procedure FillFamilyNorms(aTable: TdaTableDescription); procedure FillFamilyExtClasses(aTable: TdaTableDescription); procedure FillFamilyAccessGroups(aTable: TdaTableDescription); procedure FillFamilyAnnoClasses(aTable: TdaTableDescription); procedure FillFamilyServiceInfo(aTable: TdaTableDescription); procedure FillFamilyDocSources(aTable: TdaTableDescription); procedure FillFamilyDocTypes(aTable: TdaTableDescription); procedure FillFamilyDocClasses(aTable: TdaTableDescription); procedure FillFamilyDocKeywords(aTable: TdaTableDescription); procedure FillFamilyDocBelongs(aTable: TdaTableDescription); procedure FillFamilyDocDateCodes(aTable: TdaTableDescription); procedure FillFamilyDocWarnings(aTable: TdaTableDescription); procedure FillFamilyDocCorrections(aTable: TdaTableDescription); procedure FillFamilyDocPublishedIn(aTable: TdaTableDescription); procedure FillFamilyDocPrefixes(aTable: TdaTableDescription); procedure FillFamilyDocTerritories(aTable: TdaTableDescription); procedure FillFamilyDocNorms(aTable: TdaTableDescription); procedure FillFamilyDocAccessGroups(aTable: TdaTableDescription); procedure FillFamilyDocAnnoClasses(aTable: TdaTableDescription); procedure FillFamilyDocServiceInfo(aTable: TdaTableDescription); procedure FillFamilyDoc2DocLink(aTable: TdaTableDescription); procedure FillFamilyPriority(aTable: TdaTableDescription); procedure FillFamilyRenum(aTable: TdaTableDescription); procedure FillFamilyDocStages(aTable: TdaTableDescription); procedure FillFamilyDocLog(aTable: TdaTableDescription); procedure FillFamilyDocActivity(aTable: TdaTableDescription); procedure FillFamilyDocAlarm(aTable: TdaTableDescription); procedure FillFamilyAutolinkDoc(aTable: TdaTableDescription); procedure FillFamilyAutolinkEdition(aTable: TdaTableDescription); protected procedure Cleanup; override; {* Функция очистки полей объекта. } public procedure BuildScheme; function CheckScheme(const aSchemeName: AnsiString): AnsiString; function Table(aTableKind: TdaTables): IdaTableDescription; function StoredProcName(anIndex: Integer): AnsiString; function StoredProcsCount: Integer; class function Instance: TdaScheme; {* Метод получения экземпляра синглетона TdaScheme } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TdaScheme implementation uses l3ImplUses , daSchemeConsts , SysUtils , daFieldDescription , l3Base //#UC START# *552D07EB03CBimpl_uses* //#UC END# *552D07EB03CBimpl_uses* ; var g_TdaScheme: TdaScheme = nil; {* Экземпляр синглетона TdaScheme } procedure TdaSchemeFree; {* Метод освобождения экземпляра синглетона TdaScheme } begin l3Free(g_TdaScheme); end;//TdaSchemeFree procedure TdaScheme.BuildScheme; //#UC START# *552D0A31006D_552D07EB03CB_var* var l_Idx : TdaTables; //#UC END# *552D0A31006D_552D07EB03CB_var* begin //#UC START# *552D0A31006D_552D07EB03CB_impl* BuildMain; BuildFamily; for l_Idx := Low(f_Tables) to High(f_Tables) do Assert(Assigned(f_Tables[l_Idx])); //#UC END# *552D0A31006D_552D07EB03CB_impl* end;//TdaScheme.BuildScheme procedure TdaScheme.BuildMain; //#UC START# *55364525020F_552D07EB03CB_var* //#UC END# *55364525020F_552D07EB03CB_var* begin //#UC START# *55364525020F_552D07EB03CB_impl* f_Tables[da_mtAccess] := MakeTableDescription(da_mtAccess, 'access_rights', 'Права доступа к документам', FillMainAccess); f_Tables[da_mtPassword] := MakeTableDescription(da_mtPassword, 'user_passwords', 'Пароли пользователей', FillMainPassword); f_Tables[da_mtUsers] := MakeTableDescription(da_mtUsers, 'users', 'Пользователи', FillMainUsers); f_Tables[da_mtGroups] := MakeTableDescription(da_mtGroups, 'user_groups', 'Группы (mtGUDt)', FillMainGroups); f_Tables[da_mtGroupMembers] := MakeTableDescription(da_mtGroupMembers, 'group_members', 'Члены группы (mtGULnk)', FillMainGroupMembers); f_Tables[da_mtFamily] := MakeTableDescription(da_mtFamily, 'mfamily', 'Семейства (не прижилось)', FillMainFamily); f_Tables[da_mtFree] := MakeTableDescription(da_mtFree, 'mfree', 'Список диапазонов для ID', FillMainFree); f_Tables[da_mtJournal] := MakeTableDescription(da_mtJournal, 'system_log', 'Журнал работы (mtBBLog)', FillMainJournal); f_Tables[da_mtControl] := MakeTableDescription(da_mtControl, 'mctrl', 'Флажок эксклюзивного доступа (mtCtrl)', FillControl); f_Tables[da_mtRegions] := MakeTableDescription(da_mtRegions, 'regions', 'Словарь регионов', FillMainRegions); //#UC END# *55364525020F_552D07EB03CB_impl* end;//TdaScheme.BuildMain procedure TdaScheme.BuildFamily; //#UC START# *5536453001FD_552D07EB03CB_var* //#UC END# *5536453001FD_552D07EB03CB_var* begin //#UC START# *5536453001FD_552D07EB03CB_impl* f_Tables[da_ftNone] := MakeTableDescription(da_ftNone, '', 'Фэйковая таблица', nil, '', False, True); f_Tables[da_ftDocuments] := MakeTableDescription(da_ftDocuments, 'documents', 'Документы (ftFile)', FillFamilyDocuments); f_Tables[da_ftHyperlinks] := MakeTableDescription(da_ftHyperlinks, 'hyperlinks', 'Гиперссылки (ftHLink)', FillFamilyHyperlinks); f_Tables[da_ftSubs] := MakeTableDescription(da_ftSubs, 'subs', 'Сабы (ftSub)', FillFamilySubs); f_Tables[da_ftFree] := MakeTableDescription(da_ftFree, 'free', 'Список диапазонов для ID', FillFamilyFree); f_Tables[da_ftSources] := MakeTableDescription(da_ftSources, 'sources', 'Словарь Исходящие органы (ftDt1)', FillFamilySources); f_Tables[da_ftTypes] := MakeTableDescription(da_ftTypes, 'types', 'Словарь Типы (ftDt2)', FillFamilyTypes); f_Tables[da_ftClasses] := MakeTableDescription(da_ftClasses, 'classes', 'Словарь Классы (ftDt3)', FillFamilyClasses); f_Tables[da_ftKeywords] := MakeTableDescription(da_ftKeywords, 'keywords', 'Словарь Ключевые слова (ftDt5)', FillFamilyKeyWords); f_Tables[da_ftBelongs] := MakeTableDescription(da_ftBelongs, 'belongs', 'Словарь Группы (ftDt6)', FillFamilyBelongs); f_Tables[da_ftDateCodes] := MakeTableDescription(da_ftDateCodes, 'date_codes', 'Словарь Номеров и Дат (ftDt7)', FillFamilyDateCodes); f_Tables[da_ftWarnings] := MakeTableDescription(da_ftWarnings, 'warnings', 'Словарь Предупреждений (ftDt8)', FillFamilyWarnings); f_Tables[da_ftCorrections] := MakeTableDescription(da_ftCorrections, 'corrects', 'Словарь Вычитка (ftDt9)', FillFamilyCorrections); f_Tables[da_ftCoSources] := MakeTableDescription(da_ftCoSources, 'issues', 'Словарь Изданий (ftDtA)', FillFamilyCoSources); f_Tables[da_ftPiblishedIn] := MakeTableDescription(da_ftPiblishedIn, 'published_issue', 'Словарь Источников опубликования (ftDtB)', FillFamilyPublishedIn); f_Tables[da_ftPrefixes] := MakeTableDescription(da_ftPrefixes, 'prefixes', 'Словарь Видов информации (ftDtC)', FillFamilyPrefixes); f_Tables[da_ftTerritories] := MakeTableDescription(da_ftTerritories, 'territories', 'Словарь Территорий (ftDtD)', FillFamilyTerritories); f_Tables[da_ftNorms] := MakeTableDescription(da_ftNorms, 'norms', 'Словарь Нормы права (ftDtE)', FillFamilyNorms); f_Tables[da_ftExtClasses] := MakeTableDescription(da_ftExtClasses, 'ext_classes', 'Дополнение Словаря Классов (ftDt3E)', FillFamilyExtClasses); f_Tables[da_ftAccessGroups] := MakeTableDescription(da_ftAccessGroups, 'access_groups', 'Словарь Группы доступа (ftDtF)', FillFamilyAccessGroups); f_Tables[da_ftAnnoClasses] := MakeTableDescription(da_ftAnnoClasses, 'anno_classes', 'Словарь Классы аннотаций (ftDtI)', FillFamilyAnnoClasses); f_Tables[da_ftServiceInfo] := MakeTableDescription(da_ftServiceInfo, 'service_info', 'Словарь Вид справочной информации (ftDtJ)', FillFamilyServiceInfo); f_Tables[da_ftDocSources] := MakeTableDescription(da_ftDocSources, 'doc_source', 'Исходящие органы документа (ftLnk1)', FillFamilyDocSources); f_Tables[da_ftDocTypes] := MakeTableDescription(da_ftDocTypes, 'doc_type', 'Типы документа (ftLnk2)', FillFamilyDocTypes); f_Tables[da_ftDocClasses] := MakeTableDescription(da_ftDocClasses, 'doc_class', 'Классы документа (ftLnk3)', FillFamilyDocClasses); f_Tables[da_ftDocKeywords] := MakeTableDescription(da_ftDocKeywords, 'doc_keyword', 'Ключевые слова документа (ftLnk5)', FillFamilyDocKeywords); f_Tables[da_ftDocBelongs] := MakeTableDescription(da_ftDocBelongs, 'doc_belong', 'Группы документа (ftLnk6)', FillFamilyDocBelongs); f_Tables[da_ftDocDateCodes] := MakeTableDescription(da_ftDocDateCodes, 'doc_data_code', 'Номера и даты документа (ftLnk7) - не нужен', FillFamilyDocDateCodes); f_Tables[da_ftDocWarnings] := MakeTableDescription(da_ftDocWarnings, 'doc_warning', 'Предупреждения документа (ftLnk8)', FillFamilyDocWarnings); f_Tables[da_ftDocCorrections] := MakeTableDescription(da_ftDocCorrections, 'doc_correction', 'Вычитка документа (ftLnk9) - не нужен', FillFamilyDocCorrections); f_Tables[da_ftDocPublishedIn] := MakeTableDescription(da_ftDocPublishedIn, 'doc_published_issue', 'Источники опубликования документа (ftLnkB)', FillFamilyDocPublishedIn); f_Tables[da_ftDocPrefixes] := MakeTableDescription(da_ftDocPrefixes, 'doc_prefix', 'Виды информации документа (ftLnkC)', FillFamilyDocPrefixes); f_Tables[da_ftDocTerritories] := MakeTableDescription(da_ftDocTerritories, 'doc_territory', 'Территория документа (ftLnkD)', FillFamilyDocTerritories); f_Tables[da_ftDocNorms] := MakeTableDescription(da_ftDocNorms, 'doc_norm', 'Нормы права документа (ftLnkE)', FillFamilyDocNorms); f_Tables[da_ftDocAccessGroups] := MakeTableDescription(da_ftDocAccessGroups, 'doc_access_group', 'Группы доступа документа (ftLnkF)', FillFamilyDocAccessGroups); f_Tables[da_ftDocAnnoClasses] := MakeTableDescription(da_ftDocAnnoClasses, 'doc_anno_class', 'Классы аннотации документа (ftLnkI)', FillFamilyDocAnnoClasses); f_Tables[da_ftDocServiceInfo] := MakeTableDescription(da_ftDocServiceInfo, 'doc_service_info', 'Вид справочной информации документа (ftLnkJ)', FillFamilyDocServiceInfo); f_Tables[da_ftDoc2DocLink] := MakeTableDescription(da_ftDoc2DocLink, 'doc_doc_link', 'Связи между документами (ftLnkK)', FillFamilyDoc2DocLink); f_Tables[da_ftPriority] := MakeTableDescription(da_ftPriority, 'priority', 'Словарь приоритетов (ftPriority)', FillFamilyPriority); f_Tables[da_ftRenum] := MakeTableDescription(da_ftRenum, 'renum', 'Соответствие внешних и внутренних номеров (ftRenum)', FillFamilyRenum); f_Tables[da_ftDocStages] := MakeTableDescription(da_ftDocStages, 'doc_stage', 'Этапы обработки документа (ftStage)', FillFamilyDocStages); f_Tables[da_ftDocLog] := MakeTableDescription(da_ftDocLog, 'doc_log', 'Журнал изменения документа (ftLog)', FillFamilyDocLog); f_Tables[da_ftDocActivity] := MakeTableDescription(da_ftDocActivity, 'doc_active', 'Интервалы действия документа (ftActiv)', FillFamilyDocActivity); f_Tables[da_ftDocAlarm] := MakeTableDescription(da_ftDocAlarm, 'doc_alarm', 'Служебные предупреждения к документу (ftAlarm)', FillFamilyDocAlarm); f_Tables[da_ftControl] := MakeTableDescription(da_ftControl, 'ctrl', 'Флажок эксклюзивного доступа (ftCtrl)', FillControl); f_Tables[da_ftDocumentsDub1] := MakeTableDescription(da_ftDocumentsDub1, 'documents', 'Дубликат таблицы документов - для связывания в запросах (ftFileDup1)', FillFamilyDocuments, '', True); f_Tables[da_ftDocumentsDub2] := MakeTableDescription(da_ftDocumentsDub2, 'documents', 'Дубликат таблицы документов - для связывания в запросах (ftFileDup2)', FillFamilyDocuments, '', True); f_Tables[da_ftAutolinkDocumentsLocal] := MakeTableDescription(da_ftAutolinkDocumentsLocal, 'autolink_doc_local', 'Автопростановщик - локальные документы', FillFamilyAutolinkDoc); f_Tables[da_ftAutolinkEditionsLocal] := MakeTableDescription(da_ftAutolinkEditionsLocal, 'autolink_editions_local', 'Автопростановщик - локальные редакции', FillFamilyAutolinkEdition); f_Tables[da_ftAutolinkDocumentsRemote] := MakeTableDescription(da_ftAutolinkDocumentsRemote, 'autolink_doc_remote', 'Автопростановщик - внешние документы', FillFamilyAutolinkDoc); f_Tables[da_ftAutolinkEditionsRemote] := MakeTableDescription(da_ftAutolinkEditionsRemote, 'autolink_editions_remote', 'Автопростановщик - внешние редакции', FillFamilyAutolinkEdition); //#UC END# *5536453001FD_552D07EB03CB_impl* end;//TdaScheme.BuildFamily function TdaScheme.MakeTableDescription(aKind: TdaTables; const aSQLName: AnsiString; const aDescription: AnsiString; aProc: TdaFillTableDescriptionProc; const aScheme: AnsiString = ''; aDublicate: Boolean = False; aFake: Boolean = False): IdaTableDescription; //#UC START# *5539EF2000FF_552D07EB03CB_var* var l_Table: TdaTableDescription; const cMap: array [TdaTables] of AnsiString = ( 'ACCESS','PASS','USERS','GUDT','GULNK', 'FAMILY','FREE','BB_LOG', 'CTRL', 'REGIONS', '---', // фиктивная таблица 'FILE','HLINK','SUB','FREE', 'DT#1','DT#2','DT#3','DT#5', 'DT#6','DT#7','DT#8','DT#9','DT#A', 'DT#B','DT#C','DT#D','DT#E','DT#3E', 'DT#F','DT#I','DT#J', 'LNK#1','LNK#2','LNK#3','LNK#5', 'LNK#6','LNK#7','LNK#8','LNK#9', 'LNK#B','LNK#C','LNK#D','LNK#E', 'LNK#F','LNK#I','LNK#J', 'LNK#K', 'PRIOR','RENUM','STAGE','LOG', 'ACTIV', 'ALARM', 'CTRL', 'FILE'{Dup1}, 'FILE'{Dup2}, 'ALINKML', 'ALINKVL', 'ALINKMR', 'ALINKVR' ); function lp_CalcFamily(aTable : TdaTables) : TdaFamilyID; begin case aTable of da_mtAccess..da_mtRegions: Result := MainTblsFamily; da_ftNone..da_ftAutolinkEditionsRemote: Result := CurrentFamily; else begin Result := CurrentFamily; Assert(False); end; end; end; //#UC END# *5539EF2000FF_552D07EB03CB_var* begin //#UC START# *5539EF2000FF_552D07EB03CB_impl* l_Table := TdaTableDescription.Create(aKind, aSQLName, aDescription, cMap[aKind], lp_CalcFamily(aKind), aScheme, aDublicate, aFake, aKind in da_TreeTableKinds); try Result := l_Table; if Assigned(aProc) then aProc(l_Table); if aKind in da_TreeTableKinds then begin l_Table.AddField(TdaFieldDescription.Make('Parentid', 'ID родителя', False, da_dtQWord)); l_Table.AddField(TdaFieldDescription.Make('Ordernum', 'Порядок сортировки', False, da_dtQWord)); end; finally FreeAndNil(l_Table); end; //#UC END# *5539EF2000FF_552D07EB03CB_impl* end;//TdaScheme.MakeTableDescription procedure TdaScheme.FillMainAccess(aTable: TdaTableDescription); //#UC START# *5539EFC3037B_552D07EB03CB_var* //#UC END# *5539EFC3037B_552D07EB03CB_var* begin //#UC START# *5539EFC3037B_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('User_Gr', 'ID группы пользователей', True, da_dtWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('FamilyID', 'ID семейства', True, da_dtWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Docum_Gr', 'ID группы доступа документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Mask', 'Маска прав', True, da_dtQWord)); //#UC END# *5539EFC3037B_552D07EB03CB_impl* end;//TdaScheme.FillMainAccess procedure TdaScheme.FillMainPassword(aTable: TdaTableDescription); //#UC START# *5539FF9001C0_552D07EB03CB_var* //#UC END# *5539FF9001C0_552D07EB03CB_var* begin //#UC START# *5539FF9001C0_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ShortName', 'Логин', True, da_dtChar, 15, True)); // aTable.AddField(TdaFieldDescription.Make('Password', 'Пароль', True, da_dtChar, 10)); aTable.AddField(TdaFieldDescription.Make('User_ID', 'ID Пользователя', True, da_dtQWord)); // AK //#UC END# *5539FF9001C0_552D07EB03CB_impl* end;//TdaScheme.FillMainPassword procedure TdaScheme.FillMainUsers(aTable: TdaTableDescription); //#UC START# *5539FFA400F0_552D07EB03CB_var* //#UC END# *5539FFA400F0_552D07EB03CB_var* begin //#UC START# *5539FFA400F0_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('id', 'ID Пользователя', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('user_name', 'ФИО', True, da_dtChar, 50)); aTable.AddField(TdaFieldDescription.Make('name_length', 'Длина ФИО', True, da_dtWord)); aTable.AddField(TdaFieldDescription.Make('active', 'Флаги (активность, админскость)', True, da_dtByte)); //#UC END# *5539FFA400F0_552D07EB03CB_impl* end;//TdaScheme.FillMainUsers procedure TdaScheme.FillMainGroups(aTable: TdaTableDescription); //#UC START# *5539FFBC0157_552D07EB03CB_var* //#UC END# *5539FFBC0157_552D07EB03CB_var* begin //#UC START# *5539FFBC0157_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('id', 'ID Группы', True, da_dtWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('group_name', 'Название', True, da_dtChar, 50)); aTable.AddField(TdaFieldDescription.Make('name_length', 'Длина названия', True, da_dtWord)); aTable.AddField(TdaFieldDescription.Make('import_priority', 'Приоритет импорта', True, da_dtInteger)); aTable.AddField(TdaFieldDescription.Make('export_priority', 'Приоритет экспорта', True, da_dtInteger)); //#UC END# *5539FFBC0157_552D07EB03CB_impl* end;//TdaScheme.FillMainGroups procedure TdaScheme.FillMainGroupMembers(aTable: TdaTableDescription); //#UC START# *5539FFDC022E_552D07EB03CB_var* //#UC END# *5539FFDC022E_552D07EB03CB_var* begin //#UC START# *5539FFDC022E_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('user_id', 'ID Пользователя', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('group_id', 'ID Группы', True, da_dtWord, 0, True)); // //#UC END# *5539FFDC022E_552D07EB03CB_impl* end;//TdaScheme.FillMainGroupMembers procedure TdaScheme.FillMainFamily(aTable: TdaTableDescription); //#UC START# *5539FFFB0143_552D07EB03CB_var* //#UC END# *5539FFFB0143_552D07EB03CB_var* begin //#UC START# *5539FFFB0143_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Семейства', True, da_dtWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('FamilyName', 'Название', True, da_dtChar, 50)); aTable.AddField(TdaFieldDescription.Make('Doc_Group', '???', True, da_dtWord)); aTable.AddField(TdaFieldDescription.Make('PathToTbl', 'Путь на диске (HT)', True, da_dtChar, 128)); aTable.AddField(TdaFieldDescription.Make('Attributes', '???', True, da_dtQWord)); //#UC END# *5539FFFB0143_552D07EB03CB_impl* end;//TdaScheme.FillMainFamily procedure TdaScheme.FillMainFree(aTable: TdaTableDescription); //#UC START# *553A000C0379_552D07EB03CB_var* //#UC END# *553A000C0379_552D07EB03CB_var* begin //#UC START# *553A000C0379_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('table_name', 'Код таблицы (HT)', True, da_dtChar, 8)); aTable.AddField(TdaFieldDescription.Make('start_num', 'Начало свободного диапазона', True, da_dtQWord)); aTable.AddField(TdaFieldDescription.Make('last_num', 'Конец диапазона', True, da_dtQWord)); //#UC END# *553A000C0379_552D07EB03CB_impl* end;//TdaScheme.FillMainFree procedure TdaScheme.FillMainJournal(aTable: TdaTableDescription); //#UC START# *553A0020004E_552D07EB03CB_var* //#UC END# *553A0020004E_552D07EB03CB_var* begin //#UC START# *553A0020004E_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('session_id', 'ID сессии', True, da_dtQWord)); // Формируется как уникальное число на клиенте с проверкой уникальности в таблице aTable.AddField(TdaFieldDescription.Make('operation_id', 'ID операции', True, da_dtWord)); // Хардкодед словарь см. TBBOperation aTable.AddField(TdaFieldDescription.Make('family_id', 'ID Семейства', True, da_dtWord)); // 0 = null aTable.AddField(TdaFieldDescription.Make('ext_id', 'ID чего-то', True, da_dtQWord)); // 0 = null Зависит от операции - или документ или пользователь aTable.AddField(TdaFieldDescription.Make('date', 'Дата', True, da_dtDate)); aTable.AddField(TdaFieldDescription.Make('time', 'Время', True, da_dtTime)); aTable.AddField(TdaFieldDescription.Make('additional', 'Доп. информация', True, da_dtQWord)); // 0 = null Зависит от операции - см. TBBOperation //#UC END# *553A0020004E_552D07EB03CB_impl* end;//TdaScheme.FillMainJournal procedure TdaScheme.FillControl(aTable: TdaTableDescription); //#UC START# *553A003200BF_552D07EB03CB_var* //#UC END# *553A003200BF_552D07EB03CB_var* begin //#UC START# *553A003200BF_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Attributes', '???', True, da_dtQWord, 0, True)); // //#UC END# *553A003200BF_552D07EB03CB_impl* end;//TdaScheme.FillControl procedure TdaScheme.FillMainRegions(aTable: TdaTableDescription); //#UC START# *553A00440110_552D07EB03CB_var* //#UC END# *553A00440110_552D07EB03CB_var* begin //#UC START# *553A00440110_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Региона', True, da_dtByte, 0, True)); aTable.AddField(TdaFieldDescription.Make('Name', 'Название', True, da_dtChar, 50)); //#UC END# *553A00440110_552D07EB03CB_impl* end;//TdaScheme.FillMainRegions procedure TdaScheme.FillFamilyDocuments(aTable: TdaTableDescription); //#UC START# *553DE6E1033B_552D07EB03CB_var* //#UC END# *553DE6E1033B_552D07EB03CB_var* begin //#UC START# *553DE6E1033B_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID документа', True, da_dtQWord, 0, True)); aTable.AddField(TdaFieldDescription.Make('ShortName', 'Кратное название', True, da_dtChar, 70)); aTable.AddField(TdaFieldDescription.Make('FullName', 'Полное название', True, da_dtChar, 1000)); aTable.AddField(TdaFieldDescription.Make('Status', 'Флаги статуса', True, da_dtWord)); // см. dstatXXX в dt_Const aTable.AddField(TdaFieldDescription.Make('Priority', 'Приоритет', True, da_dtWord)); // Денормализация от da_ftPriority в зависимости от Исходящих органов и Типов (береться минимальный) aTable.AddField(TdaFieldDescription.Make('SortDate', 'Дата для сортировки', True, da_dtDate)); // Денормализация от da_ftDocDateCodes (береться минимальный) aTable.AddField(TdaFieldDescription.Make('Typ', 'ID внутреннего типа', True, da_dtByte)); // Хардкодед словарь см. TDocType в dt_Types aTable.AddField(TdaFieldDescription.Make('Flag', 'ID пользовательского типа', True, da_dtByte)); // Хардкодед словарь см. TUserType в dt_Types aTable.AddField(TdaFieldDescription.Make('Related', 'ID справки к документу', True, da_dtQWord)); // Сам на себя aTable.AddField(TdaFieldDescription.Make('PaperUser', 'Хранитель твердой копии - умерло', True, da_dtWord)); // умерло!!! aTable.AddField(TdaFieldDescription.Make('PaperPlace', 'Место хранения твердой копии - умерло', True, da_dtChar, 100)); // умерло!!! aTable.AddField(TdaFieldDescription.Make('PriorFlag', 'Ручное изменение приоритета', True, da_dtBoolean)); aTable.AddField(TdaFieldDescription.Make('StageMask', '??? - умерло', True, da_dtWord)); // умерло aTable.AddField(TdaFieldDescription.Make('VerLink', 'ID предыдущую редакцию', True, da_dtQWord)); // Сам на себя aTable.AddField(TdaFieldDescription.Make('HasAnno', 'Есть ли аннотация', True, da_dtBoolean)); aTable.AddField(TdaFieldDescription.Make('Urgency', 'ID Срочности', True, da_dtByte)); // Совсем Хардкодед словарь см. cUrgencyCaption в dt_Doc aTable.AddField(TdaFieldDescription.Make('Comment', 'Комментарий', True, da_dtChar, 100)); //#UC END# *553DE6E1033B_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocuments procedure TdaScheme.FillFamilyHyperlinks(aTable: TdaTableDescription); //#UC START# *553DE7080233_552D07EB03CB_var* //#UC END# *553DE7080233_552D07EB03CB_var* begin //#UC START# *553DE7080233_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID гиперссылкой', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('SourDoc', 'ID документа с гиперссылкой', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('DestDoc', 'ID целевого документа', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSubs aTable.AddField(TdaFieldDescription.Make('DestSub', 'ID целевого саба', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSubs //#UC END# *553DE7080233_552D07EB03CB_impl* end;//TdaScheme.FillFamilyHyperlinks procedure TdaScheme.FillFamilySubs(aTable: TdaTableDescription); //#UC START# *553DE72B011F_552D07EB03CB_var* //#UC END# *553DE72B011F_552D07EB03CB_var* begin //#UC START# *553DE72B011F_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('DocID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('SubID', 'ID Саба', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('RealFlag', 'Ручное задание имени', True, da_dtBoolean)); aTable.AddField(TdaFieldDescription.Make('SubName', 'Название', True, da_dtChar, 800)); //#UC END# *553DE72B011F_552D07EB03CB_impl* end;//TdaScheme.FillFamilySubs procedure TdaScheme.FillFamilyFree(aTable: TdaTableDescription); //#UC START# *553DE749014E_552D07EB03CB_var* //#UC END# *553DE749014E_552D07EB03CB_var* begin //#UC START# *553DE749014E_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('table_name', 'Код таблицы (HT)', True, da_dtChar, 8)); aTable.AddField(TdaFieldDescription.Make('start_num', 'Начало свободного диапазона', True, da_dtQWord)); aTable.AddField(TdaFieldDescription.Make('last_num', 'Конец диапазона', True, da_dtQWord)); //#UC END# *553DE749014E_552D07EB03CB_impl* end;//TdaScheme.FillFamilyFree procedure TdaScheme.FillFamilySources(aTable: TdaTableDescription); //#UC START# *553DE77003DF_552D07EB03CB_var* //#UC END# *553DE77003DF_552D07EB03CB_var* begin //#UC START# *553DE77003DF_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Исходящего органа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 200)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 200)); aTable.AddField(TdaFieldDescription.Make('ShortName', 'Краткое занвание', True, da_dtChar, 70)); aTable.AddField(TdaFieldDescription.Make('Sinonims', 'Синонимы', True, da_dtChar, 800)); //#UC END# *553DE77003DF_552D07EB03CB_impl* end;//TdaScheme.FillFamilySources procedure TdaScheme.FillFamilyTypes(aTable: TdaTableDescription); //#UC START# *553DE7850036_552D07EB03CB_var* //#UC END# *553DE7850036_552D07EB03CB_var* begin //#UC START# *553DE7850036_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Типа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 200)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 200)); //#UC END# *553DE7850036_552D07EB03CB_impl* end;//TdaScheme.FillFamilyTypes procedure TdaScheme.FillFamilyClasses(aTable: TdaTableDescription); //#UC START# *553DE79F0210_552D07EB03CB_var* //#UC END# *553DE79F0210_552D07EB03CB_var* begin //#UC START# *553DE79F0210_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Класса', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 200)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 200)); //#UC END# *553DE79F0210_552D07EB03CB_impl* end;//TdaScheme.FillFamilyClasses procedure TdaScheme.FillFamilyKeywords(aTable: TdaTableDescription); //#UC START# *553DE7B101D5_552D07EB03CB_var* //#UC END# *553DE7B101D5_552D07EB03CB_var* begin //#UC START# *553DE7B101D5_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Ключевого слова', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 200)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 200)); //#UC END# *553DE7B101D5_552D07EB03CB_impl* end;//TdaScheme.FillFamilyKeywords procedure TdaScheme.FillFamilyBelongs(aTable: TdaTableDescription); //#UC START# *553DE7C8025D_552D07EB03CB_var* //#UC END# *553DE7C8025D_552D07EB03CB_var* begin //#UC START# *553DE7C8025D_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Группы', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 70)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 70)); aTable.AddField(TdaFieldDescription.Make('ShName', 'Краткое название', True, da_dtChar, 10)); //#UC END# *553DE7C8025D_552D07EB03CB_impl* end;//TdaScheme.FillFamilyBelongs procedure TdaScheme.FillFamilyDateCodes(aTable: TdaTableDescription); //#UC START# *553DE7E401C4_552D07EB03CB_var* //#UC END# *553DE7E401C4_552D07EB03CB_var* begin //#UC START# *553DE7E401C4_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Номера и даты', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Date', 'Дата', True, da_dtDate)); aTable.AddField(TdaFieldDescription.Make('No', 'Номер', True, da_dtChar, 50)); aTable.AddField(TdaFieldDescription.Make('Tip', 'ID типа Датономера', True, da_dtByte)); // Хардкодед словарь см. TDNType в dt_Types aTable.AddField(TdaFieldDescription.Make('LDocID', 'ID документа вносящего изменения', True, da_dtQWord)); // Часть ссылки на da_ftSub aTable.AddField(TdaFieldDescription.Make('LSubID', 'ID саба вносящего изменения', True, da_dtQWord)); // Часть ссылки на da_ftSub //#UC END# *553DE7E401C4_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDateCodes procedure TdaScheme.FillFamilyWarnings(aTable: TdaTableDescription); //#UC START# *553DE8070027_552D07EB03CB_var* //#UC END# *553DE8070027_552D07EB03CB_var* begin //#UC START# *553DE8070027_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Предупреждения', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 1000)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 1000)); //#UC END# *553DE8070027_552D07EB03CB_impl* end;//TdaScheme.FillFamilyWarnings procedure TdaScheme.FillFamilyCorrections(aTable: TdaTableDescription); //#UC START# *553DE8170107_552D07EB03CB_var* //#UC END# *553DE8170107_552D07EB03CB_var* begin //#UC START# *553DE8170107_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Вычитки', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Date', 'Дата вычитки', True, da_dtDate)); aTable.AddField(TdaFieldDescription.Make('Source', 'ID Источника опубликования связанного документа', True, da_dtQWord)); // !!! Допустимы только те источники опубликования, которые укзаны для документа !!! aTable.AddField(TdaFieldDescription.Make('Type', 'ID типа вычитки', True, da_dtByte)); // Совсем Хардкодед словарь (D_SrcChk) = 0 - Документ, 1 - Изменения aTable.AddField(TdaFieldDescription.Make('UserID', 'ID пользователя-корректора', True, da_dtQWord)); aTable.AddField(TdaFieldDescription.Make('Coment', 'Комментарий', True, da_dtChar, 70)); //#UC END# *553DE8170107_552D07EB03CB_impl* end;//TdaScheme.FillFamilyCorrections procedure TdaScheme.FillFamilyCoSources(aTable: TdaTableDescription); //#UC START# *553DE82E0028_552D07EB03CB_var* //#UC END# *553DE82E0028_552D07EB03CB_var* begin //#UC START# *553DE82E0028_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Издания', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 100)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 100)); aTable.AddField(TdaFieldDescription.Make('ShName', 'Краткое название', False, da_dtChar, 50)); aTable.AddField(TdaFieldDescription.Make('Private', 'Не отдавать пользователям', True, da_dtBoolean)); aTable.AddField(TdaFieldDescription.Make('NonPeriod', 'Не переодическое', True, da_dtBoolean)); //#UC END# *553DE82E0028_552D07EB03CB_impl* end;//TdaScheme.FillFamilyCoSources procedure TdaScheme.FillFamilyPublishedIn(aTable: TdaTableDescription); //#UC START# *553DE83D011A_552D07EB03CB_var* //#UC END# *553DE83D011A_552D07EB03CB_var* begin //#UC START# *553DE83D011A_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Источника опубликования', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Source', 'ID Издания', True, da_dtQWord)); // AK aTable.AddField(TdaFieldDescription.Make('StartDate', 'Начало периода', True, da_dtQWord)); // AK // ежемесячный журнал = 1.хх по 31.хх aTable.AddField(TdaFieldDescription.Make('EndDate', 'Конец периода', True, da_dtQWord)); // AK // ежедневный = xx.yy по xx.yy aTable.AddField(TdaFieldDescription.Make('Number', 'Номер', True, da_dtChar, 30)); // AK aTable.AddField(TdaFieldDescription.Make('Coment', 'Name', True, da_dtChar, 70)); //#UC END# *553DE83D011A_552D07EB03CB_impl* end;//TdaScheme.FillFamilyPublishedIn procedure TdaScheme.FillFamilyPrefixes(aTable: TdaTableDescription); //#UC START# *553DE862036A_552D07EB03CB_var* //#UC END# *553DE862036A_552D07EB03CB_var* begin //#UC START# *553DE862036A_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Вида информации', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 200)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 200)); //#UC END# *553DE862036A_552D07EB03CB_impl* end;//TdaScheme.FillFamilyPrefixes procedure TdaScheme.FillFamilyTerritories(aTable: TdaTableDescription); //#UC START# *553DE875037C_552D07EB03CB_var* //#UC END# *553DE875037C_552D07EB03CB_var* begin //#UC START# *553DE875037C_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Территории', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 200)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 200)); //#UC END# *553DE875037C_552D07EB03CB_impl* end;//TdaScheme.FillFamilyTerritories procedure TdaScheme.FillFamilyNorms(aTable: TdaTableDescription); //#UC START# *553DE88902FF_552D07EB03CB_var* //#UC END# *553DE88902FF_552D07EB03CB_var* begin //#UC START# *553DE88902FF_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Нормы права', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 200)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 200)); //#UC END# *553DE88902FF_552D07EB03CB_impl* end;//TdaScheme.FillFamilyNorms procedure TdaScheme.FillFamilyExtClasses(aTable: TdaTableDescription); //#UC START# *553DE89701FF_552D07EB03CB_var* //#UC END# *553DE89701FF_552D07EB03CB_var* begin //#UC START# *553DE89701FF_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('FirstID', 'ID класса', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('SecondID', 'ID суперкласса', True, da_dtQWord)); // // скорее FirstID подмножество SecondID, но не наоборот //#UC END# *553DE89701FF_552D07EB03CB_impl* end;//TdaScheme.FillFamilyExtClasses procedure TdaScheme.FillFamilyAccessGroups(aTable: TdaTableDescription); //#UC START# *553DE8C3038F_552D07EB03CB_var* //#UC END# *553DE8C3038F_552D07EB03CB_var* begin //#UC START# *553DE8C3038F_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Группы доступа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 70)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 70)); aTable.AddField(TdaFieldDescription.Make('ShName', 'Краткое название', True, da_dtChar, 10)); //#UC END# *553DE8C3038F_552D07EB03CB_impl* end;//TdaScheme.FillFamilyAccessGroups procedure TdaScheme.FillFamilyAnnoClasses(aTable: TdaTableDescription); //#UC START# *553DE8D60075_552D07EB03CB_var* //#UC END# *553DE8D60075_552D07EB03CB_var* begin //#UC START# *553DE8D60075_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Класса аннотаций', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 200)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 200)); //#UC END# *553DE8D60075_552D07EB03CB_impl* end;//TdaScheme.FillFamilyAnnoClasses procedure TdaScheme.FillFamilyServiceInfo(aTable: TdaTableDescription); //#UC START# *553DE8FE01AD_552D07EB03CB_var* //#UC END# *553DE8FE01AD_552D07EB03CB_var* begin //#UC START# *553DE8FE01AD_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ID', 'ID Вида справочной информации', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('NameR', 'Название', True, da_dtChar, 100)); aTable.AddField(TdaFieldDescription.Make('NameE', 'Name', True, da_dtChar, 100)); //#UC END# *553DE8FE01AD_552D07EB03CB_impl* end;//TdaScheme.FillFamilyServiceInfo procedure TdaScheme.FillFamilyDocSources(aTable: TdaTableDescription); //#UC START# *553F2E94021D_552D07EB03CB_var* //#UC END# *553F2E94021D_552D07EB03CB_var* begin //#UC START# *553F2E94021D_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Исходящего органа', True, da_dtQWord, 0, True)); // //#UC END# *553F2E94021D_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocSources procedure TdaScheme.FillFamilyDocTypes(aTable: TdaTableDescription); //#UC START# *553F2EE802EF_552D07EB03CB_var* //#UC END# *553F2EE802EF_552D07EB03CB_var* begin //#UC START# *553F2EE802EF_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSub aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Типа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Sub_ID', 'ID саба', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSub - НО Sub = 0 это весь документ и его НЕТ в da_ftSub!!! //#UC END# *553F2EE802EF_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocTypes procedure TdaScheme.FillFamilyDocClasses(aTable: TdaTableDescription); //#UC START# *553F2F0D0100_552D07EB03CB_var* //#UC END# *553F2F0D0100_552D07EB03CB_var* begin //#UC START# *553F2F0D0100_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSub aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Класса', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Sub_ID', 'ID саба', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSub - НО Sub = 0 это весь документ и его НЕТ в da_ftSub!!! //#UC END# *553F2F0D0100_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocClasses procedure TdaScheme.FillFamilyDocKeywords(aTable: TdaTableDescription); //#UC START# *553F2F34011F_552D07EB03CB_var* //#UC END# *553F2F34011F_552D07EB03CB_var* begin //#UC START# *553F2F34011F_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSub aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Ключевого слова', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Sub_ID', 'ID саба', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSub - НО Sub = 0 это весь документ и его НЕТ в da_ftSub!!! //#UC END# *553F2F34011F_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocKeywords procedure TdaScheme.FillFamilyDocBelongs(aTable: TdaTableDescription); //#UC START# *553F2F5E0169_552D07EB03CB_var* //#UC END# *553F2F5E0169_552D07EB03CB_var* begin //#UC START# *553F2F5E0169_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Группы', True, da_dtQWord, 0, True)); // //#UC END# *553F2F5E0169_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocBelongs procedure TdaScheme.FillFamilyDocDateCodes(aTable: TdaTableDescription); //#UC START# *553F2F8300A1_552D07EB03CB_var* //#UC END# *553F2F8300A1_552D07EB03CB_var* begin //#UC START# *553F2F8300A1_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Номеродаты', True, da_dtQWord, 0, True)); // //#UC END# *553F2F8300A1_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocDateCodes procedure TdaScheme.FillFamilyDocWarnings(aTable: TdaTableDescription); //#UC START# *553F2FA00207_552D07EB03CB_var* //#UC END# *553F2FA00207_552D07EB03CB_var* begin //#UC START# *553F2FA00207_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Предупраждения', True, da_dtQWord, 0, True)); // //#UC END# *553F2FA00207_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocWarnings procedure TdaScheme.FillFamilyDocCorrections(aTable: TdaTableDescription); //#UC START# *553F2FC40156_552D07EB03CB_var* //#UC END# *553F2FC40156_552D07EB03CB_var* begin //#UC START# *553F2FC40156_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Вычитки', True, da_dtQWord, 0, True)); // //#UC END# *553F2FC40156_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocCorrections procedure TdaScheme.FillFamilyDocPublishedIn(aTable: TdaTableDescription); //#UC START# *553F2FE300DC_552D07EB03CB_var* //#UC END# *553F2FE300DC_552D07EB03CB_var* begin //#UC START# *553F2FE300DC_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Источника опубликования', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Pages', 'Страницы', True, da_dtChar, 128)); aTable.AddField(TdaFieldDescription.Make('Coment', 'Комментарий', True, da_dtChar, 255)); aTable.AddField(TdaFieldDescription.Make('Flags', 'Флаги', True, da_dtByte)); // см pinfClone и пр. в dt_Const //#UC END# *553F2FE300DC_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocPublishedIn procedure TdaScheme.FillFamilyDocPrefixes(aTable: TdaTableDescription); //#UC START# *553F300C00A1_552D07EB03CB_var* //#UC END# *553F300C00A1_552D07EB03CB_var* begin //#UC START# *553F300C00A1_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSub aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Вида информации', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Sub_ID', 'ID саба', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSub - НО Sub = 0 это весь документ и его НЕТ в da_ftSub!!! //#UC END# *553F300C00A1_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocPrefixes procedure TdaScheme.FillFamilyDocTerritories(aTable: TdaTableDescription); //#UC START# *553F302E0091_552D07EB03CB_var* //#UC END# *553F302E0091_552D07EB03CB_var* begin //#UC START# *553F302E0091_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Территории', True, da_dtQWord, 0, True)); // //#UC END# *553F302E0091_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocTerritories procedure TdaScheme.FillFamilyDocNorms(aTable: TdaTableDescription); //#UC START# *553F304E00E0_552D07EB03CB_var* //#UC END# *553F304E00E0_552D07EB03CB_var* begin //#UC START# *553F304E00E0_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Нормы права', True, da_dtQWord, 0, True)); // //#UC END# *553F304E00E0_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocNorms procedure TdaScheme.FillFamilyDocAccessGroups(aTable: TdaTableDescription); //#UC START# *553F306E01DA_552D07EB03CB_var* //#UC END# *553F306E01DA_552D07EB03CB_var* begin //#UC START# *553F306E01DA_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Группы доступа', True, da_dtQWord, 0, True)); // //#UC END# *553F306E01DA_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocAccessGroups procedure TdaScheme.FillFamilyDocAnnoClasses(aTable: TdaTableDescription); //#UC START# *553F308901D3_552D07EB03CB_var* //#UC END# *553F308901D3_552D07EB03CB_var* begin //#UC START# *553F308901D3_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Класса аннотации', True, da_dtQWord, 0, True)); // //#UC END# *553F308901D3_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocAnnoClasses procedure TdaScheme.FillFamilyDocServiceInfo(aTable: TdaTableDescription); //#UC START# *553F30A901C5_552D07EB03CB_var* //#UC END# *553F30A901C5_552D07EB03CB_var* begin //#UC START# *553F30A901C5_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSub aTable.AddField(TdaFieldDescription.Make('Dict_ID', 'ID Вида справочной информации', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Sub_ID', 'ID саба', True, da_dtQWord, 0, True)); // // Часть ссылки на da_ftSub - НО Sub = 0 это весь документ и его НЕТ в da_ftSub!!! //#UC END# *553F30A901C5_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocServiceInfo procedure TdaScheme.FillFamilyDoc2DocLink(aTable: TdaTableDescription); //#UC START# *553F30C7024A_552D07EB03CB_var* //#UC END# *553F30C7024A_552D07EB03CB_var* begin //#UC START# *553F30C7024A_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Doc_ID', 'ID Документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('LinkType', 'ID типа связи', True, da_dtByte, 0, True)); // // совсем хардкодед словарь (D_Doc2DocLinkEdit) 0-документ изменен, 1-документ утратил силу aTable.AddField(TdaFieldDescription.Make('LinkDocID', 'ID документа связи', True, da_dtQWord, 0, True)); // //#UC END# *553F30C7024A_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDoc2DocLink procedure TdaScheme.FillFamilyPriority(aTable: TdaTableDescription); //#UC START# *553F30E70209_552D07EB03CB_var* //#UC END# *553F30E70209_552D07EB03CB_var* begin //#UC START# *553F30E70209_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('Sour_ID', 'ID Исходящего органа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Type_ID', 'ID Типа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Priority', 'Приоритет', True, da_dtWord, 0, True)); //#UC END# *553F30E70209_552D07EB03CB_impl* end;//TdaScheme.FillFamilyPriority procedure TdaScheme.FillFamilyRenum(aTable: TdaTableDescription); //#UC START# *553F310900AC_552D07EB03CB_var* //#UC END# *553F310900AC_552D07EB03CB_var* begin //#UC START# *553F310900AC_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('RealID', 'ID документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('ImportID', 'Внешнее ID документа', True, da_dtQWord)); // AK //#UC END# *553F310900AC_552D07EB03CB_impl* end;//TdaScheme.FillFamilyRenum procedure TdaScheme.FillFamilyDocStages(aTable: TdaTableDescription); //#UC START# *553F312A001C_552D07EB03CB_var* //#UC END# *553F312A001C_552D07EB03CB_var* begin //#UC START# *553F312A001C_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('DocID', 'ID документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Type', 'ID типа этапа', True, da_dtByte, 0, True)); // // см. TStageType в dt_Types aTable.AddField(TdaFieldDescription.Make('B_Date', 'Дата начала', True, da_dtDate)); aTable.AddField(TdaFieldDescription.Make('E_Date', 'Дата окончания', True, da_dtDate)); aTable.AddField(TdaFieldDescription.Make('UserID', 'ID Пользователя', True, da_dtQWord)); //#UC END# *553F312A001C_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocStages procedure TdaScheme.FillFamilyDocLog(aTable: TdaTableDescription); //#UC START# *553F315000CD_552D07EB03CB_var* //#UC END# *553F315000CD_552D07EB03CB_var* begin //#UC START# *553F315000CD_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('DocID', 'ID документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Action', 'ID действия', True, da_dtByte, 0, True)); // Хардкодед словарь см. TLogActionType в dt_Types aTable.AddField(TdaFieldDescription.Make('Date', 'Дата', True, da_dtDate, 0, True)); // aTable.AddField(TdaFieldDescription.Make('Time', 'Время', True, da_dtTime, 0, True)); // aTable.AddField(TdaFieldDescription.Make('ActionFlag', '', True, da_dtByte)); // Хардкодед словарь см. TLogActionFlags в dt_Types aTable.AddField(TdaFieldDescription.Make('Station', 'Станция HT', True, da_dtChar, 8)); aTable.AddField(TdaFieldDescription.Make('UserID', 'ID Пользователя', True, da_dtQWord)); //#UC END# *553F315000CD_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocLog procedure TdaScheme.FillFamilyDocActivity(aTable: TdaTableDescription); //#UC START# *553F316B01AC_552D07EB03CB_var* //#UC END# *553F316B01AC_552D07EB03CB_var* begin //#UC START# *553F316B01AC_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('DocID', 'ID документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('RecID', 'Порядковый номер', True, da_dtByte, 0, True)); // // Уникален в рамках DocID aTable.AddField(TdaFieldDescription.Make('Typ', 'ID типа', True, da_dtByte)); // Совсем хардкодед словарь 1-Период неуверенности, 0-иначе aTable.AddField(TdaFieldDescription.Make('Start', 'Дата начала (с)', True, da_dtDate)); aTable.AddField(TdaFieldDescription.Make('Finish', 'Дата окончания (по)', True, da_dtDate)); aTable.AddField(TdaFieldDescription.Make('Comment', 'Комментарий', True, da_dtChar, 1000)); //#UC END# *553F316B01AC_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocActivity procedure TdaScheme.FillFamilyDocAlarm(aTable: TdaTableDescription); //#UC START# *553F318A0380_552D07EB03CB_var* //#UC END# *553F318A0380_552D07EB03CB_var* begin //#UC START# *553F318A0380_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('DocID', 'ID документа', True, da_dtQWord, 0, True)); // aTable.AddField(TdaFieldDescription.Make('RecID', 'Порядковый номер', True, da_dtByte, 0, True)); // // Уникален в рамках DocID aTable.AddField(TdaFieldDescription.Make('Start', 'Дата', True, da_dtDate)); aTable.AddField(TdaFieldDescription.Make('Comment', 'Комментарий', True, da_dtChar, 1000)); //#UC END# *553F318A0380_552D07EB03CB_impl* end;//TdaScheme.FillFamilyDocAlarm function TdaScheme.CheckScheme(const aSchemeName: AnsiString): AnsiString; //#UC START# *56654FC70181_552D07EB03CB_var* //#UC END# *56654FC70181_552D07EB03CB_var* begin //#UC START# *56654FC70181_552D07EB03CB_impl* if Trim(aSchemeName) = '' then Result := cDefaultSchemeName else Result := Trim(aSchemeName); //#UC END# *56654FC70181_552D07EB03CB_impl* end;//TdaScheme.CheckScheme procedure TdaScheme.FillFamilyAutolinkDoc(aTable: TdaTableDescription); //#UC START# *569F44020026_552D07EB03CB_var* //#UC END# *569F44020026_552D07EB03CB_var* begin //#UC START# *569F44020026_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('ExtDocID', 'Внешний ID документа', True, da_dtQWord)); aTable.AddField(TdaFieldDescription.Make('IntDocID', 'Внутренний ID документа', True, da_dtQWord)); aTable.AddField(TdaFieldDescription.Make('DType', 'Тип документа', True, da_dtQWord)); aTable.AddField(TdaFieldDescription.Make('Source', 'Исходящий Орган', True, da_dtQWord)); aTable.AddField(TdaFieldDescription.Make('Date', 'Дата опубликования', True, da_dtDate)); aTable.AddField(TdaFieldDescription.Make('Num', 'Номер опубликования', False, da_dtChar, 50)); aTable.AddField(TdaFieldDescription.Make('LawCase', 'Номер судебного дела', False, da_dtChar, 50)); //#UC END# *569F44020026_552D07EB03CB_impl* end;//TdaScheme.FillFamilyAutolinkDoc procedure TdaScheme.FillFamilyAutolinkEdition(aTable: TdaTableDescription); //#UC START# *569F444D0185_552D07EB03CB_var* //#UC END# *569F444D0185_552D07EB03CB_var* begin //#UC START# *569F444D0185_552D07EB03CB_impl* aTable.AddField(TdaFieldDescription.Make('MDocID', 'Внешний ID документа', True, da_dtQWord)); aTable.AddField(TdaFieldDescription.Make('IntDocID', 'Внутренний ID редакции', True, da_dtQWord)); aTable.AddField(TdaFieldDescription.Make('ExtDocID', 'Внешний ID редакции', True, da_dtQWord)); aTable.AddField(TdaFieldDescription.Make('Start', 'Дата начала действия', True, da_dtDate)); aTable.AddField(TdaFieldDescription.Make('Finish', 'Дата окончания действия', True, da_dtDate)); //#UC END# *569F444D0185_552D07EB03CB_impl* end;//TdaScheme.FillFamilyAutolinkEdition function TdaScheme.Table(aTableKind: TdaTables): IdaTableDescription; //#UC START# *552FBDF700C9_552D07EB03CB_var* //#UC END# *552FBDF700C9_552D07EB03CB_var* begin //#UC START# *552FBDF700C9_552D07EB03CB_impl* Result := f_Tables[aTableKind]; //#UC END# *552FBDF700C9_552D07EB03CB_impl* end;//TdaScheme.Table function TdaScheme.StoredProcName(anIndex: Integer): AnsiString; //#UC START# *56A60A740072_552D07EB03CB_var* const cMap: array [0..cStoredProcCount - 1] of String = ( 'get_free_num', 'get_admin_free_num', 'delete_user_from_all_groups', 'register_admin_alloc_num', 'register_alloc_num', 'delete_all_users_from_group', 'change_password', 'update_user' ); //#UC END# *56A60A740072_552D07EB03CB_var* begin //#UC START# *56A60A740072_552D07EB03CB_impl* Assert((anIndex >= 0) and (anIndex < StoredProcsCount)); Result := cMap[anIndex]; //#UC END# *56A60A740072_552D07EB03CB_impl* end;//TdaScheme.StoredProcName function TdaScheme.StoredProcsCount: Integer; //#UC START# *56A60AA70045_552D07EB03CB_var* //#UC END# *56A60AA70045_552D07EB03CB_var* begin //#UC START# *56A60AA70045_552D07EB03CB_impl* Result := cStoredProcCount; //#UC END# *56A60AA70045_552D07EB03CB_impl* end;//TdaScheme.StoredProcsCount class function TdaScheme.Instance: TdaScheme; {* Метод получения экземпляра синглетона TdaScheme } begin if (g_TdaScheme = nil) then begin l3System.AddExitProc(TdaSchemeFree); g_TdaScheme := Create; end; Result := g_TdaScheme; end;//TdaScheme.Instance class function TdaScheme.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TdaScheme <> nil; end;//TdaScheme.Exists procedure TdaScheme.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_552D07EB03CB_var* var l_Idx : TdaTables; //#UC END# *479731C50290_552D07EB03CB_var* begin //#UC START# *479731C50290_552D07EB03CB_impl* for l_Idx := Low(f_Tables) to High(f_Tables) do f_Tables[l_Idx] := nil; inherited; //#UC END# *479731C50290_552D07EB03CB_impl* end;//TdaScheme.Cleanup end.
unit ncsProcessThread; // Модуль: "w:\common\components\rtl\Garant\cs\ncsProcessThread.pas" // Стереотип: "SimpleClass" // Элемент модели: "TncsProcessThread" MUID: (546061CE03DA) {$Include w:\common\components\rtl\Garant\cs\CsDefine.inc} interface {$If NOT Defined(Nemesis)} uses l3IntfUses , ncsTransporterThread , ncsReplyWaiter , ncsMessageInterfaces , ncsMessage , ncsMessageQueue ; type TncsProcessThread = class(TncsTransporterThread) private f_Transporter: Pointer; {* [weak] IncsTransporter } f_ReplyWaiter: TncsReplyWaiter; private procedure ProcessMessage(aMessage: TncsMessage); protected function pm_GetTransporter: IncsTransporter; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure DoExecute; override; {* основная процедура нити. Для перекрытия в потомках } public constructor Create(anQueue: TncsMessageQueue; const aTransporter: IncsTransporter; aWaiter: TncsReplyWaiter); reintroduce; protected property ReplyWaiter: TncsReplyWaiter read f_ReplyWaiter; public property Transporter: IncsTransporter read pm_GetTransporter; end;//TncsProcessThread {$IfEnd} // NOT Defined(Nemesis) implementation {$If NOT Defined(Nemesis)} uses l3ImplUses , SysUtils , l3Base , ncsMessageExecutorFactory , evdNcsTypes //#UC START# *546061CE03DAimpl_uses* //#UC END# *546061CE03DAimpl_uses* ; function TncsProcessThread.pm_GetTransporter: IncsTransporter; //#UC START# *5464BE030256_546061CE03DAget_var* //#UC END# *5464BE030256_546061CE03DAget_var* begin //#UC START# *5464BE030256_546061CE03DAget_impl* Result := IncsTransporter(f_Transporter); //#UC END# *5464BE030256_546061CE03DAget_impl* end;//TncsProcessThread.pm_GetTransporter procedure TncsProcessThread.ProcessMessage(aMessage: TncsMessage); //#UC START# *5460680D0277_546061CE03DA_var* var l_Executor: IncsExecutor; l_Transporter: IncsTransporter; l_FakeReply: TncsMessage; //#UC END# *5460680D0277_546061CE03DA_var* begin //#UC START# *5460680D0277_546061CE03DA_impl* l_Executor := TncsMessageExecutorFactory.Instance.MakeExecutor(aMessage); if Assigned(l_Executor) then begin l_Transporter := Transporter; try try l_Executor.Execute(TncsExecuteContext_C(aMessage, l_Transporter)) except on E: Exception do begin l3System.Msg2Log('Исключение при обработке сообщения %s', [aMessage.TaggedData.TagType.AsString]); l3System.Exception2Log(E); if aMessage.Kind = ncs_mkMessage then begin l_FakeReply := TncsInvalidMessage.Create; try l_FakeReply.Kind := ncs_mkReply; l_FakeReply.MessageID := aMessage.MessageID; l_Transporter.Send(l_FakeReply); finally FreeAndNil(l_FakeReply); end; end; raise; end; end; finally l_Transporter := nil; end; end else l3System.Msg2Log('Не удалось найти Executor для %s', [aMessage.TaggedData.TagType.AsString]); //#UC END# *5460680D0277_546061CE03DA_impl* end;//TncsProcessThread.ProcessMessage constructor TncsProcessThread.Create(anQueue: TncsMessageQueue; const aTransporter: IncsTransporter; aWaiter: TncsReplyWaiter); //#UC START# *5464BDC203B1_546061CE03DA_var* //#UC END# *5464BDC203B1_546061CE03DA_var* begin //#UC START# *5464BDC203B1_546061CE03DA_impl* inherited Create(anQueue); f_Transporter := Pointer(aTransporter); aWaiter.SetRefTo(f_ReplyWaiter); //#UC END# *5464BDC203B1_546061CE03DA_impl* end;//TncsProcessThread.Create procedure TncsProcessThread.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_546061CE03DA_var* //#UC END# *479731C50290_546061CE03DA_var* begin //#UC START# *479731C50290_546061CE03DA_impl* f_Transporter := nil; FreeAndNil(f_ReplyWaiter); inherited; //#UC END# *479731C50290_546061CE03DA_impl* end;//TncsProcessThread.Cleanup procedure TncsProcessThread.DoExecute; {* основная процедура нити. Для перекрытия в потомках } //#UC START# *4911B69E037D_546061CE03DA_var* var l_Message: TncsMessage; //#UC END# *4911B69E037D_546061CE03DA_var* begin //#UC START# *4911B69E037D_546061CE03DA_impl* l_Message := nil; while not TerminatedConnection do begin Queue.WaitForMessage; if TerminatedConnection then Exit; while Queue.ExtractMessage(l_Message) do try if TerminatedConnection then Exit; if l_Message.Kind = ncs_mkReply then f_ReplyWaiter.SubmitReply(l_Message) else ProcessMessage(l_Message); finally FreeAndNil(l_Message); end; end; //#UC END# *4911B69E037D_546061CE03DA_impl* end;//TncsProcessThread.DoExecute {$IfEnd} // NOT Defined(Nemesis) end.
// islip - IneQuation's Simple LOLCODE Interpreter in Pascal // Written by Leszek "IneQuation" Godlewski <leszgod081@student.polsl.pl> // Main interpreter executable program islip; // the console apptype is only supported on win32, gives warnings in Linux // since any app is a console one by default {$IFDEF WIN32} {$APPTYPE CONSOLE} {$ENDIF} uses SysUtils, {$IFNDEF WIN32} // only use crt in Linux crt, {$ENDIF} typedefs, // C-like types compiler, // language parser and bytecode compiler bytecode, // bytecode definitions interpreter, // bytecode interpreter variable; type // container for command line options islip_options = record script_fname : string; pseudoasm : boolean; end; var g_options : islip_options; g_script : cfile; g_compiler : islip_compiler; g_interpreter : islip_interpreter; // the raw instruction list and data to be fed to the interpreter g_bytecode : islip_bytecode; g_data : islip_data; // parse command line arguments, return false if the user's done something wrong function islip_parse_args : boolean; var i : int; begin // initialization islip_parse_args := false; with g_options do begin script_fname := ''; pseudoasm := false; end; if ParamCount < 1 then exit; i := 1; while i <= ParamCount do begin if ParamStr(i)[1] <> '-' then break; if length(ParamStr(i)) = 2 then case ParamStr(i)[2] of 'g': g_options.pseudoasm := true; else exit; end; inc(i); end; if i <> ParamCount then exit; g_options.script_fname := ParamStr(ParamCount); islip_parse_args := true; end; // print instructions procedure islip_print_help; begin writeln('islip - IneQuation''s Simple LOLCODE Interpreter in Pascal'); writeln('Written by Leszek "IneQuation" Godlewski ', '<leszgod081@student.polsl.pl>'); writeln('Usage: ', ParamStr(0), ' [OPTIONS] <SCRIPT FILE>'); writeln('Options:'); writeln(' -g Output pseudo-assembly code for debugging'); end; // open the script file, return false on failure function islip_file_open : boolean; begin islip_file_open := true; assign(g_script, g_options.script_fname); {$I-} reset(g_script); {$I+} if IOResult <> 0 then islip_file_open := false; end; // close the script file procedure islip_file_close; begin close(g_script); end; // output pseudo-assembly code procedure islip_asm_print; var i : integer; begin writeln('segment .data'); for i := 1 to length(g_data) do begin write(' 0x', IntToHex(i, 8), ' = '); if g_data[i].get_type = VT_STRING then write('"'); g_data[i].echo(false); if g_data[i].get_type = VT_STRING then write('"'); writeln; end; writeln; writeln('segment .text'); for i := 1 to length(g_bytecode) do begin case g_bytecode[i].inst of OP_STOP: writeln(' stop'); OP_PUSH: begin if g_bytecode[i].arg = ARG_NULL then writeln(' push NULL') else writeln(' push 0x', IntToHex(g_bytecode[i].arg, 8)); end; OP_POP: begin if g_bytecode[i].arg = ARG_NULL then writeln(' pop NULL') else writeln(' pop 0x', IntToHex(g_bytecode[i].arg, 8)); end; OP_ADD: writeln(' add'); OP_SUB: writeln(' sub'); OP_MUL: writeln(' mul'); OP_DIV: writeln(' div'); OP_MOD: writeln(' mod'); OP_MIN: writeln(' min'); OP_MAX: writeln(' max'); OP_AND: writeln(' and'); OP_OR: writeln(' or'); OP_XOR: writeln(' xor'); OP_EQ: writeln(' eq'); OP_NEQ: writeln(' neq'); OP_NEG: writeln(' neg'); OP_CONCAT: writeln(' concat'); OP_JMP: writeln(' jmp 0x', IntToHex(g_bytecode[i].arg, 8)); OP_CNDJMP: writeln(' cndjmp 0x', IntToHex(g_bytecode[i].arg, 8)); OP_PRINT: writeln(' print'); OP_READ: writeln(' read'); OP_CALL: writeln(' call 0x', IntToHex(g_bytecode[i].arg, 8)); end; end; end; // main routine begin if not islip_parse_args then begin islip_print_help; exit; end; if not islip_file_open then begin writeln('ERROR: Failed to read script file "', g_options.script_fname, '"'); exit; end; // compile the script g_compiler := islip_compiler.create(g_script); if not g_compiler.compile then begin // we rely on the compiler and the parser to print errors/warnings g_compiler.destroy; islip_file_close; exit; end; islip_file_close; // retrieve compilation products g_compiler.get_products(g_bytecode, g_data); g_compiler.destroy; // output pseudo-asm, if requested if g_options.pseudoasm then islip_asm_print else begin // run the bytecode g_interpreter := islip_interpreter.create(32, g_bytecode, g_data); g_interpreter.run; g_interpreter.destroy; end; // kthxbai! end.
unit QRQRBarcode; {$I QRDEFS.INC} interface uses Windows, quickrpt, DB, graphics, classes, controls, QRCtrls, qrDelphiZXingQRCode; type TQRQRBarcode = class(TQRPrintable) private FBCText : string; FBCEncoding : TQRCodeEncoding; FBCQuietzone : integer; protected procedure Paint; override; procedure Print(OfsX, OfsY : integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure GetExpandedHeight(var newheight : extended ); override; published property BarcodeText : string read FBCText write FBCText; property BarcodeEncoding : TQRCodeEncoding read FBCEncoding write FBCEncoding; property QuietZone: integer read FBCQuietzone write FBCQuietzone default 5; end; TQRQRDBBarcode = class(TQRQRBarcode) private FField : TField; FDataSet : TDataSet; FDataField : string; procedure SetDataField(const Value: string); procedure SetDataSet(Value: TDataSet); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Prepare; override; procedure UnPrepare; override; public procedure GetFieldString( var DataStr : string); override; property Field: TField read FField; published property DataField: string read FDataField write SetDataField; property DataSet: TDataSet read FDataSet write SetDataSet; property BarcodeEncoding; property QuietZone; end; implementation uses qrprntr, forms; procedure RenderQRBarcode( bcdata : string; bcenc : TQRCodeEncoding; qzone, targx, targy, targwidth, targheight : integer; bcanvas : TCanvas); var QRCode: TDelphiZXingQRCode; Row, Column, cellwidth : Integer; begin QRCode := TDelphiZXingQRCode.Create; try QRCode.Data := bcdata; QRCode.Encoding := bcenc; QRCode.QuietZone := qzone; bcanvas.Brush.Style := bsSolid; bcanvas.Brush.Color := clWhite; bcanvas.Pen.Color := clWhite; bcanvas.Rectangle(targx,targy, targx+targwidth, targy+targheight); bcanvas.Brush.Color := clBlack; bcanvas.Pen.Color := clBlack; if (qrcode.Columns < 1) or (qrcode.Rows<1) then exit; if targwidth < targheight then cellwidth := targwidth div qrcode.Columns else cellwidth := targheight div qrcode.Rows; if cellwidth < 2 then exit; for Row := 0 to QRCode.Rows - 1 do begin for Column := 0 to QRCode.Columns - 1 do begin if (QRCode.IsBlack[Row, Column]) then bcanvas.Rectangle( (cellwidth*column)+targx, (cellwidth*row)+targy, (cellwidth*column)+cellwidth+targx, (cellwidth*row)+cellwidth+targy); end; end; finally QRCode.Free; end; end; { TQRQRBarcode } constructor TQRQRBarcode.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csFramed, csOpaque]; Width := 105; Height := 105; FBCText := 'unset'; end; destructor TQRQRBarcode.Destroy; begin inherited Destroy; end; procedure TQRQRDBBarcode.Prepare; begin inherited Prepare; FBCText := ''; if assigned(FDataSet) then begin FField := DataSet.FindField(FDataField); FBCText := FField.AsString; end else FField := nil; end; // return value in screen pixels procedure TQRQRBarcode.GetExpandedHeight(var newheight : extended ); begin end; procedure TQRQRDBBarcode.GetFieldString( var DataStr : string); begin end; procedure TQRQRBarcode.Print(OfsX, OfsY : integer); var dest : TRect; expimg : TQRimage; expbmp : TBitmap; begin Dest.Top := QRPrinter.YPos(OfsY + Size.Top); Dest.Left := QRPrinter.XPos(OfsX + Size.Left); Dest.Right := QRPrinter.XPos(OfsX + Size.Width + Size.Left); Dest.Bottom := QRPrinter.YPos(OfsY + Size.Height + Size.Top); {$ifndef DXE} RenderQRBarcode( FBCText, FBCEncoding, FBCQuietzone,dest.Left,dest.Top,dest.Width, dest.height, QRPrinter.canvas); {$else} RenderQRBarcode( FBCText, FBCEncoding, FBCQuietzone,dest.Left,dest.Top,dest.right-dest.left, dest.bottom-dest.top, QRPrinter.canvas); {$endif} if ParentReport.exporting then begin expbmp := TBitmap.create; expbmp.width := width; expbmp.height := height; expimg := TQRImage.create(self); expimg.left := left; expimg.top := top; expimg.width := width; expimg.height := height; RenderQRBarcode( FBCText, FBCEncoding, FBCQuietzone,0,0,expbmp.Width, expbmp.height, expbmp.canvas); expimg.picture.Assign(expbmp); parentreport.ExportFilter.AcceptGraphic(dest.left,dest.top, expimg); expimg.free; expbmp.free; end; end; procedure TQRQRDBBarcode.UnPrepare; begin FField := nil; inherited UnPrepare; end; procedure TQRQRDBBarcode.SetDataSet(Value: TDataSet); begin FDataSet := Value; if Value <> nil then Value.FreeNotification(Self); end; procedure TQRQRDBBarcode.SetDataField(const Value: string); begin FDataField := Value; end; procedure TQRQRBarcode.Paint; begin Inherited Paint; if csDesigning in ComponentState then RenderQRBarcode( FBCText, FBCEncoding, FBCQuietzone,0,0,Width, height, inherited canvas); end; procedure TQRQRDBBarcode.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = DataSet) then DataSet := nil; end; end.
{@html(<hr>) @abstract(Unit providing constans with precalculated IDs a others stuff around IDs generally.) @author(František Milt <fmilt@seznam.cz>) @created(2014-04-15) @lastmod(2014-04-27) @bold(@NoAutoLink(TelemetryIDs)) ©František Milt, all rights reserved. This unit contains definitions of identification number types, set of constants containing full configuration names, constants with IDs for individual configs and channel, as well as function used to obtain those IDs. Last change: 2014-04-27 Change List:@unorderedList( @item(2014-04-15 - First stable version.) @item(2014-04-15 - Function GetItemID was moved to this unit.) @item(2014-04-18 - Constant cConfigFieldsSeparator was moved to this unit.)) @html(<hr>) Table of precomputed IDs for channels names.@br IDs are stored in constans whose identifiers corresponds to indetifiers of constants containing string value. For example, for name stored in constant @code(SCS_TELEMETRY_CHANNEL_local_scale), the ID is stored in constant SCS_TELEMETRY_CHANNEL_ID_local_scale. @table( @rowHead(@cell(Channel name constant identifier) @cell(String value) @cell(Precomputed ID (hexadecimal))) @row(@cell(@code(SCS_TELEMETRY_CHANNEL_local_scale)) @cell(@code(local.scale)) @cell(@code(33DE67E4))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_connected)) @cell(@code(trailer.connected)) @cell(@code(7007CCEE))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_world_placement)) @cell(@code(trailer.world.placement)) @cell(@code(3A729370))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_local_linear_velocity)) @cell(@code(trailer.velocity.linear)) @cell(@code(AE80C1D0))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_local_angular_velocity)) @cell(@code(trailer.velocity.angular)) @cell(@code(A2981BDF))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_local_linear_acceleration)) @cell(@code(trailer.acceleration.linear)) @cell(@code(99A57FA9))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_local_angular_acceleration)) @cell(@code(trailer.acceleration.angular)) @cell(@code(8B76F7F9))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_wear_chassis)) @cell(@code(trailer.wear.chassis)) @cell(@code(E071BE1A))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_susp_deflection)) @cell(@code(trailer.wheel.suspension.deflection)) @cell(@code(1E44DA91))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_on_ground)) @cell(@code(trailer.wheel.on_ground)) @cell(@code(9A68642F))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_substance)) @cell(@code(trailer.wheel.substance)) @cell(@code(1DFBFCF1))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_velocity)) @cell(@code(trailer.wheel.angular_velocity)) @cell(@code(C387243E))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_steering)) @cell(@code(trailer.wheel.steering)) @cell(@code(3B417600))) @row(@cell(@code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_rotation)) @cell(@code(trailer.wheel.rotation)) @cell(@code(EA941F6D))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_world_placement)) @cell(@code(truck.world.placement)) @cell(@code(6B48D06B))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_local_linear_velocity)) @cell(@code(truck.local.velocity.linear)) @cell(@code(5D9D7AB3))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_local_angular_velocity)) @cell(@code(truck.local.velocity.angular)) @cell(@code(76D03686))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_local_linear_acceleration)) @cell(@code(truck.local.acceleration.linear)) @cell(@code(A2E5F90F))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_local_angular_acceleration)) @cell(@code(truck.local.acceleration.angular)) @cell(@code(B4F8B1A2))) @row(@cell(@code(*SCS_TELEMETRY_TRUCK_CHANNEL_cabin_orientation)) @cell(@code(truck.cabin.orientation)) @cell(@code(36F3F15D))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_cabin_offset)) @cell(@code(truck.cabin.offset)) @cell(@code(303DEF2A))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_cabin_angular_velocity)) @cell(@code(truck.cabin.velocity.angular)) @cell(@code(10976F36))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_cabin_angular_acceleration)) @cell(@code(truck.cabin.acceleration.angular)) @cell(@code(D10EF7A8))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_head_offset)) @cell(@code(truck.head.offset)) @cell(@code(EEE287E8))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_speed)) @cell(@code(truck.speed)) @cell(@code(4E839148))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_engine_rpm)) @cell(@code(truck.engine.rpm)) @cell(@code(160E7B38))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_engine_gear)) @cell(@code(truck.engine.gear)) @cell(@code(9582C042))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_input_steering)) @cell(@code(truck.input.steering)) @cell(@code(DCFA7E3B))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_input_throttle)) @cell(@code(truck.input.throttle)) @cell(@code(CF8FC74B))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_input_brake)) @cell(@code(truck.input.brake)) @cell(@code(5EEDB702))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_input_clutch)) @cell(@code(truck.input.clutch)) @cell(@code(F5ECF339))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_effective_steering)) @cell(@code(truck.effective.steering)) @cell(@code(94181EAB))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_effective_throttle)) @cell(@code(truck.effective.throttle)) @cell(@code(876DA7DB))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_effective_brake)) @cell(@code(truck.effective.brake)) @cell(@code(47E5F7F0))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_effective_clutch)) @cell(@code(truck.effective.clutch)) @cell(@code(A6466849))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_cruise_control)) @cell(@code(truck.cruise_control)) @cell(@code(C31E2094))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_hshifter_slot)) @cell(@code(truck.hshifter.slot)) @cell(@code(36C98B9D))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_hshifter_selector)) @cell(@code(truck.hshifter.select)) @cell(@code(E4A50350))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_parking_brake)) @cell(@code(truck.brake.parking)) @cell(@code(5664B035))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_motor_brake)) @cell(@code(truck.brake.motor)) @cell(@code(8E0C8ABA))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_retarder_level)) @cell(@code(truck.brake.retarder)) @cell(@code(A8D6B016))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure)) @cell(@code(truck.brake.air.pressure)) @cell(@code(9384DD05))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure_warning)) @cell(@code(truck.brake.air.pressure.warning)) @cell(@code(C58F8B5A))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure_emergency)) @cell(@code(truck.brake.air.pressure.emergency)) @cell(@code(78FAD40D))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_brake_temperature)) @cell(@code(truck.brake.temperature)) @cell(@code(E1AE4E3F))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_fuel)) @cell(@code(truck.fuel.amount)) @cell(@code(C298DD2D))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_fuel_warning)) @cell(@code(truck.fuel.warning)) @cell(@code(9D0FD9A2))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_fuel_average_consumption)) @cell(@code(truck.fuel.consumption.average)) @cell(@code(013149D4))) @row(@cell(@code(**SCS_TELEMETRY_TRUCK_CHANNEL_adblue)) @cell(@code(truck.adblue)) @cell(@code(8D32829D))) @row(@cell(@code(**SCS_TELEMETRY_TRUCK_CHANNEL_adblue_warning)) @cell(@code(truck.adblue.warning)) @cell(@code(FF3464CB))) @row(@cell(@code(**SCS_TELEMETRY_TRUCK_CHANNEL_adblue_average_consumption)) @cell(@code(truck.adblue.consumption.average)) @cell(@code(C253FC24))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_oil_pressure)) @cell(@code(truck.oil.pressure)) @cell(@code(A368F9A6))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_oil_pressure_warning)) @cell(@code(truck.oil.pressure.warning)) @cell(@code(1A1815C5))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_oil_temperature)) @cell(@code(truck.oil.temperature)) @cell(@code(405A67E9))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_water_temperature)) @cell(@code(truck.water.temperature)) @cell(@code(B8B46564))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_water_temperature_warning)) @cell(@code(truck.water.temperature.warning)) @cell(@code(783F3300))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_battery_voltage)) @cell(@code(truck.battery.voltage)) @cell(@code(91BB0105))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_battery_voltage_warning)) @cell(@code(truck.battery.voltage.warning)) @cell(@code(26000473))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_electric_enabled)) @cell(@code(truck.electric.enabled)) @cell(@code(9D4D7843))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_engine_enabled)) @cell(@code(truck.engine.enabled)) @cell(@code(FACA0BF9))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_lblinker)) @cell(@code(truck.lblinker)) @cell(@code(A7B8351B))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_rblinker)) @cell(@code(truck.rblinker)) @cell(@code(CE891602))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_light_lblinker)) @cell(@code(truck.light.lblinker)) @cell(@code(ECC0AC62))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_light_rblinker)) @cell(@code(truck.light.rblinker)) @cell(@code(85F18F7B))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_light_parking)) @cell(@code(truck.light.parking)) @cell(@code(6931D205))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_light_low_beam)) @cell(@code(truck.light.beam.low)) @cell(@code(612D677D))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_light_high_beam)) @cell(@code(truck.light.beam.high)) @cell(@code(7E93DFB5))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_light_aux_front)) @cell(@code(truck.light.aux.front)) @cell(@code(D6464C43))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_light_aux_roof)) @cell(@code(truck.light.aux.roof)) @cell(@code(5ADBA32B))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_light_beacon)) @cell(@code(truck.light.beacon)) @cell(@code(990180CD))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_light_brake)) @cell(@code(truck.light.brake)) @cell(@code(E2790B7B))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_light_reverse)) @cell(@code(truck.light.reverse)) @cell(@code(71711168))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wipers)) @cell(@code(truck.wipers)) @cell(@code(EE7920A7))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_dashboard_backlight)) @cell(@code(truck.dashboard.backlight)) @cell(@code(91DA5D6D))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wear_engine)) @cell(@code(truck.wear.engine)) @cell(@code(D89A5F14))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wear_transmission)) @cell(@code(truck.wear.transmission)) @cell(@code(ABB45C97))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wear_cabin)) @cell(@code(truck.wear.cabin)) @cell(@code(49F699F6))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wear_chassis)) @cell(@code(truck.wear.chassis)) @cell(@code(BC2A6A7A))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wear_wheels)) @cell(@code(truck.wear.wheels)) @cell(@code(7C35EF18))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_odometer)) @cell(@code(truck.odometer)) @cell(@code(F988B0E0))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_susp_deflection)) @cell(@code(truck.wheel.suspension.deflection)) @cell(@code(369CAB49))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_on_ground)) @cell(@code(truck.wheel.on_ground)) @cell(@code(CB522734))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_substance)) @cell(@code(truck.wheel.substance)) @cell(@code(4CC1BFEA))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_velocit)) @cell(@code(truck.wheel.angular_velocity)) @cell(@code(B7B25C28))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_steering)) @cell(@code(truck.wheel.steering)) @cell(@code(DF025731))) @row(@cell(@code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_rotation)) @cell(@code(truck.wheel.rotation)) @cell(@code(0ED73E5C))) ) @code(*) - This constant does not actually exist (it was removed from telemetry SDK and replaced by @code(SCS_TELEMETRY_TRUCK_CHANNEL_cabin_offset) ).@br @code(**) - These channels does not work in current SDK.@br @br Table of precomputed IDs for configs names.@br IDs are stored in constans whose identifiers corresponds to indetifiers of constants containing string value. For example, for name stored in constant SCS_TELEMETRY_CONFIG_substances_ATTRIBUTE_id, the ID is stored in constant SCS_TELEMETRY_CONFIG_ID_substances_ATTRIBUTE_id. @table( @rowHead(@cell(Config name constant identifier) @cell(String value) @cell(Precomputed ID (hexadecimal))) @row(@cell(SCS_TELEMETRY_CONFIG_substances_ATTRIBUTE_id) @cell(@code(substances.id)) @cell(@code(A1E920F4))) @row(@cell(SCS_TELEMETRY_CONFIG_controls_ATTRIBUTE_shifter_type) @cell(@code(controls.shifter.type)) @cell(@code(37BA5313))) @row(@cell(SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_selector_count) @cell(@code(hshifter.selector.count)) @cell(@code(AA57ECAD))) @row(@cell(SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_slot_gear) @cell(@code(hshifter.slot.gear)) @cell(@code(601E49BB))) @row(@cell(SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_slot_handle_position) @cell(@code(hshifter.slot.handle.position)) @cell(@code(4C2725D0))) @row(@cell(SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_slot_selectors) @cell(@code(hshifter.slot.selectors)) @cell(@code(1705F155))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_brand_id) @cell(@code(truck.brand_id)) @cell(@code(CFEC235C))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_brand) @cell(@code(truck.brand)) @cell(@code(5DF796E6))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_id) @cell(@code(truck.id)) @cell(@code(93A67EA9))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_name) @cell(@code(truck.name)) @cell(@code(FF36A0AD))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_fuel_capacity) @cell(@code(truck.fuel.capacity)) @cell(@code(FFEA5570))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_fuel_warning_factor) @cell(@code(truck.fuel.warning.factor)) @cell(@code(766BF114))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_adblue_capacity) @cell(@code(truck.adblue.capacity)) @cell(@code(CBE6B731))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_air_pressure_warning) @cell(@code(truck.brake.air.pressure.warning)) @cell(@code(C58F8B5A))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_air_pressure_emergency) @cell(@code(truck.brake.air.pressure.emergency)) @cell(@code(78FAD40D))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_oil_pressure_warning) @cell(@code(truck.oil.pressure.warning)) @cell(@code(1A1815C5))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_water_temperature_warning) @cell(@code(truck.water.temperature.warning)) @cell(@code(783F3300))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_battery_voltage_warning) @cell(@code(truck.battery.voltage.warning)) @cell(@code(26000473))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_rpm_limit) @cell(@code(truck.rpm.limit)) @cell(@code(96F2B46D))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_forward_gear_count) @cell(@code(truck.gears.forward)) @cell(@code(620CEB70))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_reverse_gear_count) @cell(@code(truck.gears.reverse)) @cell(@code(2FEA55E1))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_retarder_step_count) @cell(@code(truck.retarder.steps)) @cell(@code(F8E36BF0))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_cabin_position) @cell(@code(truck.cabin.position)) @cell(@code(E37B50B2))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_head_position) @cell(@code(truck.head.position)) @cell(@code(59DED2CB))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_hook_position) @cell(@code(truck.hook.position)) @cell(@code(10944A21))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_count) @cell(@code(truck.wheels.count)) @cell(@code(D634DC01))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_position) @cell(@code(truck.wheel.position)) @cell(@code(61874258))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_steerable) @cell(@code(truck.wheel.steerable)) @cell(@code(91817077))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_simulated) @cell(@code(truck.wheel.simulated)) @cell(@code(27B8658F))) @row(@cell(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_radius) @cell(@code(truck.wheel.radius)) @cell(@code(60D54CB6))) @row(@cell(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_id) @cell(@code(trailer.id)) @cell(@code(E3F34E9A))) @row(@cell(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_cargo_accessory_id) @cell(@code(trailer.cargo.accessory.id)) @cell(@code(7E792A8A))) @row(@cell(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_hook_position) @cell(@code(trailer.hook.position)) @cell(@code(5D7A70AD))) @row(@cell(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_count) @cell(@code(trailer.wheels.count)) @cell(@code(8A6F0861))) @row(@cell(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_position) @cell(@code(trailer.wheel.position)) @cell(@code(85C46369))) @row(@cell(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_steerable) @cell(@code(trailer.wheel.steerable)) @cell(@code(C0BB336C))) @row(@cell(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_simulated) @cell(@code(trailer.wheel.simulated)) @cell(@code(76822694))) @row(@cell(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_radius) @cell(@code(trailer.wheel.radius)) @cell(@code(3C8E98D6))) ) @html(<hr>)} unit TelemetryIDs; interface {$INCLUDE '.\Telemetry_defs.inc'} uses CRC32, TelemetryCommon, {$IFDEF UseCondensedHeader} SCS_Telemetry_Condensed; {$ELSE} scssdk, scssdk_telemetry_common_configs, scssdk_telemetry_common_channels, scssdk_telemetry_trailer_common_channels, scssdk_telemetry_truck_common_channels; {$ENDIF} {==============================================================================} { Types and general constants } {==============================================================================} const // Character used as a separator for config + config_attribute conglomerate. cConfigFieldsSeparator = '.'; type // General item identificator. All other item identifiers are of this type. TItemID = TCRC32; // Pointer to a variable of type TItemID PItemID = ^TITemID; // Channel identificator obtained from its name. TChannelID = TItemID; // Pointer to a variable of type TChannelID. PChannelID = ^TChannelID; // Configuration identificator obtained from full config name. TConfigID = TItemID; // Pointer to a variable of type TConfigID. PConfigID = ^TConfigID; {==============================================================================} { Full config names } {==============================================================================} const // Full name of config attribute @code(id) in @code(substances) configuration. SCS_TELEMETRY_CONFIG_substances_ATTRIBUTE_id = TelemetryString(SCS_TELEMETRY_CONFIG_substances + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_id); // Full name of config attribute @code(shifter_type) in @code(controls) configuration. SCS_TELEMETRY_CONFIG_controls_ATTRIBUTE_shifter_type = TelemetryString(SCS_TELEMETRY_CONFIG_controls + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_shifter_type); // Full name of config attribute @code(selector_count) in @code(hshifter) configuration. SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_selector_count = TelemetryString(SCS_TELEMETRY_CONFIG_hshifter + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_selector_count); // Full name of config attribute @code(slot_gear) in @code(hshifter) configuration. SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_slot_gear = TelemetryString(SCS_TELEMETRY_CONFIG_hshifter + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_slot_gear); // Full name of config attribute @code(slot_handle_position) in @code(hshifter) configuration. SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_slot_handle_position = TelemetryString(SCS_TELEMETRY_CONFIG_hshifter + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_slot_handle_position); // Full name of config attribute @code(slot_selectors) in @code(hshifter) configuration. SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_slot_selectors = TelemetryString(SCS_TELEMETRY_CONFIG_hshifter + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_slot_selectors); // Full name of config attribute @code(brand_id) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_brand_id = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_brand_id); // Full name of config attribute @code(brand) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_brand = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_brand); // Full name of config attribute @code(id) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_id = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_id); // Full name of config attribute @code(name) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_name = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_name); // Full name of config attribute @code(fuel_capacity) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_fuel_capacity = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_fuel_capacity); // Full name of config attribute @code(fuel_warning_factor) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_fuel_warning_factor = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_fuel_warning_factor); // Full name of config attribute @code(adblue_capacity ) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_adblue_capacity = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_adblue_capacity); // Full name of config attribute @code(air_pressure_warning ) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_air_pressure_warning = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_air_pressure_warning); // Full name of config attribute @code(air_pressure_emergency) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_air_pressure_emergency = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_air_pressure_emergency); // Full name of config attribute @code(oil_pressure_warning) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_oil_pressure_warning = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_oil_pressure_warning); // Full name of config attribute @code(water_temperature_warning) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_water_temperature_warning = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_water_temperature_warning); // Full name of config attribute @code(battery_voltage_warning) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_battery_voltage_warning = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_battery_voltage_warning); // Full name of config attribute @code(rpm_limit) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_rpm_limit = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_rpm_limit); // Full name of config attribute @code(forward_gear_count) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_forward_gear_count = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_forward_gear_count); // Full name of config attribute @code(reverse_gear_count) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_reverse_gear_count = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_reverse_gear_count); // Full name of config attribute @code(retarder_step_count) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_retarder_step_count = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_retarder_step_count); // Full name of config attribute @code(cabin_position) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_cabin_position = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_cabin_position); // Full name of config attribute @code(head_position) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_head_position = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_head_position); // Full name of config attribute @code(hook_position) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_hook_position = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_hook_position); // Full name of config attribute @code(wheel_count) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_count = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_count); // Full name of config attribute @code(wheel_position) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_position = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_position); // Full name of config attribute @code(wheel_steerable) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_steerable = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_steerable); // Full name of config attribute @code(wheel_simulated) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_simulated = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_simulated); // Full name of config attribute @code(wheel_radius) in @code(truck) configuration. SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_radius = TelemetryString(SCS_TELEMETRY_CONFIG_truck + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_radius); // Full name of config attribute @code(id) in @code(trailer) configuration. SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_id = TelemetryString(SCS_TELEMETRY_CONFIG_trailer + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_id); // Full name of config attribute @code(cargo_accessory_id) in @code(trailer) configuration. SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_cargo_accessory_id = TelemetryString(SCS_TELEMETRY_CONFIG_trailer + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_cargo_accessory_id); // Full name of config attribute @code(hook_position) in @code(trailer) configuration. SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_hook_position = TelemetryString(SCS_TELEMETRY_CONFIG_trailer + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_hook_position); // Full name of config attribute @code(wheel_count) in @code(trailer) configuration. SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_count = TelemetryString(SCS_TELEMETRY_CONFIG_trailer + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_count); // Full name of config attribute @code(wheel_position) in @code(trailer) configuration. SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_position = TelemetryString(SCS_TELEMETRY_CONFIG_trailer + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_position); // Full name of config attribute @code(wheel_steerable) in @code(trailer) configuration. SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_steerable = TelemetryString(SCS_TELEMETRY_CONFIG_trailer + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_steerable); // Full name of config attribute @code(wheel_simulated) in @code(trailer) configuration. SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_simulated = TelemetryString(SCS_TELEMETRY_CONFIG_trailer + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_simulated); // Full name of config attribute @code(wheel_radius) in @code(trailer) configuration. SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_radius = TelemetryString(SCS_TELEMETRY_CONFIG_trailer + cConfigFieldsSeparator + SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_radius); {==============================================================================} { Config IDs } {==============================================================================} {$IFNDEF PrecomputedItemIDs} {$WRITEABLECONST ON} {$ENDIF} // Identification number for SCS_TELEMETRY_CONFIG_substances_ATTRIBUTE_id config. SCS_TELEMETRY_CONFIG_ID_substances_ATTRIBUTE_id: TConfigID = $A1E920F4; // Identification number for SCS_TELEMETRY_CONFIG_controls_ATTRIBUTE_shifter_type config. SCS_TELEMETRY_CONFIG_ID_controls_ATTRIBUTE_shifter_type: TConfigID = $37BA5313; // Identification number for SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_selector_count config. SCS_TELEMETRY_CONFIG_ID_hshifter_ATTRIBUTE_selector_count: TConfigID = $AA57ECAD; // Identification number for SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_slot_gear config. SCS_TELEMETRY_CONFIG_ID_hshifter_ATTRIBUTE_slot_gear: TConfigID = $601E49BB; // Identification number for SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_slot_handle_position config. SCS_TELEMETRY_CONFIG_ID_hshifter_ATTRIBUTE_slot_handle_position: TConfigID = $4C2725D0; // Identification number for SCS_TELEMETRY_CONFIG_shifter_ATTRIBUTE_slot_selectors config. SCS_TELEMETRY_CONFIG_ID_hshifter_ATTRIBUTE_slot_selectors: TConfigID = $1705F155; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_brand_id config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_brand_id: TConfigID = $CFEC235C; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_brand config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_brand: TConfigID = $5DF796E6; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_id config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_id: TConfigID = $93A67EA9; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_name config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_name: TConfigID = $FF36A0AD; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_fuel_capacity config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_fuel_capacity: TConfigID = $FFEA5570; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_fuel_warning_factor config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_fuel_warning_factor: TConfigID = $766BF114; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_adblue_capacity config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_adblue_capacity: TConfigID = $CBE6B731; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_air_pressure_warning config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_air_pressure_warning: TConfigID = $C58F8B5A; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_air_pressure_emergency config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_air_pressure_emergency: TConfigID = $78FAD40D; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_oil_pressure_warning config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_oil_pressure_warning: TConfigID = $1A1815C5; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_water_temperature_warning config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_water_temperature_warning: TConfigID = $783F3300; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_battery_voltage_warning config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_battery_voltage_warning: TConfigID = $26000473; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_rpm_limit config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_rpm_limit: TConfigID = $96F2B46D; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_forward_gear_count config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_forward_gear_count: TConfigID = $620CEB70; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_reverse_gear_count config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_reverse_gear_count: TConfigID = $2FEA55E1; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_retarder_step_count config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_retarder_step_count: TConfigID = $F8E36BF0; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_cabin_position config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_cabin_position: TConfigID = $E37B50B2; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_head_position config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_head_position: TConfigID = $59DED2CB; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_hook_position config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_hook_position: TConfigID = $10944A21; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_count config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_wheel_count: TConfigID = $D634DC01; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_position config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_wheel_position: TConfigID = $61874258; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_steerable config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_wheel_steerable: TConfigID = $91817077; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_simulated config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_wheel_simulated: TConfigID = $27B8658F; // Identification number for SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_radius config. SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_wheel_radius: TConfigID = $60D54CB6; // Identification number for SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_id config. SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_id: TConfigID = $E3F34E9A; // Identification number for SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_cargo_accessory_id config. SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_cargo_accessory_id: TConfigID = $7E792A8A; // Identification number for SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_hook_position config. SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_hook_position: TConfigID = $5D7A70AD; // Identification number for SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_count config. SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_wheel_count: TConfigID = $8A6F0861; // Identification number for SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_position config. SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_wheel_position: TConfigID = $85C46369; // Identification number for SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_steerable config. SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_wheel_steerable: TConfigID = $C0BB336C; // Identification number for SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_simulated config. SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_wheel_simulated: TConfigID = $76822694; // Identification number for SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_radius config. SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_wheel_radius: TConfigID = $3C8E98D6; {==============================================================================} { Channel IDs } {==============================================================================} // Identification number for @code(SCS_TELEMETRY_CHANNEL_local_scale) channel. SCS_TELEMETRY_CHANNEL_ID_local_scale: TChannelID = $33DE67E4; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_connected) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_connected: TChannelID = $7007CCEE; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_world_placement) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_world_placement: TChannelID = $3A729370; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_local_linear_velocity) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_local_linear_velocity: TChannelID = $AE80C1D0; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_local_angular_velocity) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_local_angular_velocity: TChannelID = $A2981BDF; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_local_linear_acceleration) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_local_linear_acceleration: TChannelID = $99A57FA9; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_local_angular_acceleration) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_local_angular_acceleration: TChannelID = $8B76F7F9; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_wear_chassis) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_wear_chassis: TChannelID = $E071BE1A; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_susp_deflection) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_susp_deflection: TChannelID = $1E44DA91; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_on_ground) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_on_ground: TChannelID = $9A68642F; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_substance) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_substance: TChannelID = $1DFBFCF1; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_velocity) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_velocity: TChannelID = $C387243E; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_steering) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_steering: TChannelID = $3B417600; // Identification number for @code(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_rotation) channel. SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_rotation: TChannelID = $EA941F6D; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_world_placement) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_world_placement: TChannelID = $6B48D06B; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_local_linear_velocity) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_local_linear_velocity: TChannelID = $5D9D7AB3; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_local_angular_velocity) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_local_angular_velocity: TChannelID = $76D03686; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_local_linear_acceleration) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_local_linear_acceleration: TChannelID = $A2E5F90F; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_local_angular_acceleration) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_local_angular_acceleration: TChannelID = $B4F8B1A2; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_cabin_orientation) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_cabin_orientation: TChannelID = $36F3F15D; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_cabin_offset) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_cabin_offset: TChannelID = $303DEF2A; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_cabin_angular_velocity) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_cabin_angular_velocity: TChannelID = $10976F36; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_cabin_angular_acceleration) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_cabin_angular_acceleration: TChannelID = $D10EF7A8; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_head_offset) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_head_offset: TChannelID = $EEE287E8; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_speed) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_speed: TChannelID = $4E839148; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_engine_rpm) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_engine_rpm: TChannelID = $160E7B38; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_engine_gear) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_engine_gear: TChannelID = $9582C042; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_input_steering) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_input_steering: TChannelID = $DCFA7E3B; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_input_throttle) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_input_throttle: TChannelID = $CF8FC74B; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_input_brake) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_input_brake: TChannelID = $5EEDB702; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_input_clutch) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_input_clutch: TChannelID = $F5ECF339; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_effective_steering) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_effective_steering: TChannelID = $94181EAB; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_effective_throttle) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_effective_throttle: TChannelID = $876DA7DB; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_effective_brake) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_effective_brake: TChannelID = $47E5F7F0; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_effective_clutch) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_effective_clutch: TChannelID = $A6466849; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_cruise_control) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_cruise_control: TChannelID = $C31E2094; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_hshifter_slot) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_hshifter_slot: TChannelID = $36C98B9D; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_hshifter_selector) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_hshifter_selector: TChannelID = $E4A50350; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_parking_brake) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_parking_brake: TChannelID = $5664B035; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_motor_brake) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_motor_brake: TChannelID = $8E0C8ABA; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_retarder_level) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_retarder_level: TChannelID = $A8D6B016; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_brake_air_pressure: TChannelID = $9384DD05; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure_warning) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_brake_air_pressure_warning: TChannelID = $C58F8B5A; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_brake_temperature) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_brake_temperature: TChannelID = $E1AE4E3F; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure_emergency) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_brake_air_pressure_emergency: TChannelID = $78FAD40D; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_fuel) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_fuel: TChannelID = $C298DD2D; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_fuel_warning) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_fuel_warning: TChannelID = $9D0FD9A2; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_fuel_average_consumption) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_fuel_average_consumption: TChannelID = $013149D4; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_adblue) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_adblue: TChannelID = $8D32829D; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_adblue_warning) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_adblue_warning: TChannelID = $FF3464CB; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_adblue_average_consumption) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_adblue_average_consumption: TChannelID = $C253FC24; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_oil_pressure) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_oil_pressure: TChannelID = $A368F9A6; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_oil_pressure_warning) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_oil_pressure_warning: TChannelID = $1A1815C5; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_oil_temperature) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_oil_temperature: TChannelID = $405A67E9; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_water_temperature) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_water_temperature: TChannelID = $B8B46564; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_water_temperature_warning) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_water_temperature_warning: TChannelID = $783F3300; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_battery_voltage) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_battery_voltage: TChannelID = $91BB0105; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_battery_voltage_warning) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_battery_voltage_warning: TChannelID = $26000473; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_electric_enabled) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_electric_enabled: TChannelID = $9D4D7843; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_engine_enabled) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_engine_enabled: TChannelID = $FACA0BF9; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_lblinker) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_lblinker: TChannelID = $A7B8351B; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_rblinker) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_rblinker: TChannelID = $CE891602; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_light_parking) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_parking: TChannelID = $6931D205; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_light_rblinker) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_rblinker: TChannelID = $85F18F7B; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_light_lblinker) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_lblinker: TChannelID = $ECC0AC62; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_light_low_beam) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_low_beam: TChannelID = $612D677D; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_light_high_beam) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_high_beam: TChannelID = $7E93DFB5; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_light_aux_front) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_aux_front: TChannelID = $D6464C43; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_light_aux_roof) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_aux_roof: TChannelID = $5ADBA32B; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_light_beacon) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_beacon: TChannelID = $990180CD; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_light_brake) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_brake: TChannelID = $E2790B7B; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_light_reverse) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_reverse: TChannelID = $71711168; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wipers) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wipers: TChannelID = $EE7920A7; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_dashboard_backlight) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_dashboard_backlight: TChannelID = $91DA5D6D; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wear_engine) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wear_engine: TChannelID = $D89A5F14; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wear_transmission) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wear_transmission: TChannelID = $ABB45C97; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wear_cabin) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wear_cabin: TChannelID = $49F699F6; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wear_chassis) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wear_chassis: TChannelID = $BC2A6A7A; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wear_wheels) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wear_wheels: TChannelID = $7C35EF18; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_odometer) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_odometer: TChannelID = $F988B0E0; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_susp_deflection) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_susp_deflection: TChannelID = $369CAB49; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_on_ground) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_on_ground: TChannelID = $CB522734; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_substance) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_substance: TChannelID = $4CC1BFEA; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_velocity) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_velocity: TChannelID = $B7B25C28; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_steering) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_steering: TChannelID = $DF025731; // Identification number for @code(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_rotation) channel. SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_rotation: TChannelID = $0ED73E5C; {$IFNDEF PrecomputedItemIDs} {$WRITEABLECONST OFF} {$ENDIF} {==============================================================================} { Unit Functions and procedures declarations } {==============================================================================} { @abstract(Function used to get identifier of passed item name.) At the moment, identifiers are implemented as CRC32 checksum of given item name (string). @param Item Item name. @returns Item identificator. } Function GetItemID(const Item: TelemetryString): TItemID; //------------------------------------------------------------------------------ { @abstract(Returns textual representation of item ID.) @param ID Item ID to be converted to text. @returns Textual representation of passed ID. } Function ItemIDToStr(ID: TItemID): String; //------------------------------------------------------------------------------ {$IFNDEF PrecomputedItemIDs} { @abstract(Procedure calculating identification numbers for channels and configs.) When you call this routine, it recalculates all ID constants. Use it only when you truly need this recalculation.@br It is called automatically in initialization section of this unit when neither of @code(PrecomputedItemIDs) and @code(ManualItemIDsCompute) switches is defined. } procedure InitializeItemsIDs; {$ENDIF} //------------------------------------------------------------------------------ { Returns full config name composed from config id and attribute name separated by cConfigFieldsSeparator. @param ConfigID ID of configuration. @param AttributeName Name of attribute. @returns Full config name. } Function ConfigMergeIDAndAttribute(const ConfigID, AttributeName: TelemetryString): TelemetryString; //------------------------------------------------------------------------------ { @abstract(Removes passed config id from full config name.) @bold(Note) - function does not control whether passed name truly starts with given config id. It simply removes number of characters corresponding to length of config id from the start of config name. @param ConfigName Name of config from which id should be removed. @param ConfigID Id that has be removed from passed config name. @returns Config name with removed id. } Function ConfigRemoveIDFromName(const ConfigName, ConfigID: TelemetryString): TelemetryString; implementation {==============================================================================} { Unit Functions and procedures implementation } {==============================================================================} Function GetItemID(const Item: TelemetryString): TItemID; begin Result := BufferCRC32(InitialCRC32,PUTF8Char(Item)^,Length(Item) * SizeOf(TUTF8Char)); end; //------------------------------------------------------------------------------ Function ItemIDToStr(ID: TItemID): String; begin Result := CRC32ToStr(ID); end; //------------------------------------------------------------------------------ {$IFNDEF PrecomputedItemIDs} procedure InitializeItemsIDs; begin //--- Configs IDs --- SCS_TELEMETRY_CONFIG_ID_substances_ATTRIBUTE_id := GetItemID(SCS_TELEMETRY_CONFIG_substances_ATTRIBUTE_id); SCS_TELEMETRY_CONFIG_ID_controls_ATTRIBUTE_shifter_type := GetItemID(SCS_TELEMETRY_CONFIG_controls_ATTRIBUTE_shifter_type); SCS_TELEMETRY_CONFIG_ID_hshifter_ATTRIBUTE_selector_count := GetItemID(SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_selector_count); SCS_TELEMETRY_CONFIG_ID_hshifter_ATTRIBUTE_slot_gear := GetItemID(SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_slot_gear); SCS_TELEMETRY_CONFIG_ID_hshifter_ATTRIBUTE_slot_handle_position := GetItemID(SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_slot_handle_position); SCS_TELEMETRY_CONFIG_ID_hshifter_ATTRIBUTE_slot_selectors := GetItemID(SCS_TELEMETRY_CONFIG_hshifter_ATTRIBUTE_slot_selectors); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_brand_id := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_brand_id); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_brand := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_brand); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_id := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_id); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_name := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_name); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_fuel_capacity := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_fuel_capacity); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_fuel_warning_factor := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_fuel_warning_factor); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_adblue_capacity := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_adblue_capacity); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_air_pressure_warning := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_air_pressure_warning); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_air_pressure_emergency := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_air_pressure_emergency); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_oil_pressure_warning := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_oil_pressure_warning); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_water_temperature_warning := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_water_temperature_warning); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_battery_voltage_warning := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_battery_voltage_warning); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_rpm_limit := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_rpm_limit); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_forward_gear_count := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_forward_gear_count); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_reverse_gear_count := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_reverse_gear_count); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_retarder_step_count := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_retarder_step_count); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_cabin_position := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_cabin_position); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_head_position := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_head_position); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_hook_position := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_hook_position); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_wheel_count := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_count); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_wheel_position := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_position); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_wheel_steerable := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_steerable); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_wheel_simulated := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_simulated); SCS_TELEMETRY_CONFIG_ID_truck_ATTRIBUTE_wheel_radius := GetItemID(SCS_TELEMETRY_CONFIG_truck_ATTRIBUTE_wheel_radius); SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_id := GetItemID(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_id); SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_cargo_accessory_id := GetItemID(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_cargo_accessory_id); SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_hook_position := GetItemID(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_hook_position); SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_wheel_count := GetItemID(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_count); SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_wheel_position := GetItemID(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_position); SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_wheel_steerable := GetItemID(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_steerable); SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_wheel_simulated := GetItemID(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_simulated); SCS_TELEMETRY_CONFIG_ID_trailer_ATTRIBUTE_wheel_radius := GetItemID(SCS_TELEMETRY_CONFIG_trailer_ATTRIBUTE_wheel_radius); //--- Channels IDs --- SCS_TELEMETRY_CHANNEL_ID_local_scale := GetItemID(SCS_TELEMETRY_CHANNEL_local_scale); SCS_TELEMETRY_TRAILER_CHANNEL_ID_connected := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_connected); SCS_TELEMETRY_TRAILER_CHANNEL_ID_world_placement := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_world_placement); SCS_TELEMETRY_TRAILER_CHANNEL_ID_local_linear_velocity := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_local_linear_velocity); SCS_TELEMETRY_TRAILER_CHANNEL_ID_local_angular_velocity := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_local_angular_velocity); SCS_TELEMETRY_TRAILER_CHANNEL_ID_local_linear_acceleration := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_local_linear_acceleration); SCS_TELEMETRY_TRAILER_CHANNEL_ID_local_angular_acceleration := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_local_angular_acceleration); SCS_TELEMETRY_TRAILER_CHANNEL_ID_wear_chassis := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_wear_chassis); SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_susp_deflection := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_susp_deflection); SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_on_ground := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_on_ground); SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_substance := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_substance); SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_velocity := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_velocity); SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_steering := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_steering); SCS_TELEMETRY_TRAILER_CHANNEL_ID_wheel_rotation := GetItemID(SCS_TELEMETRY_TRAILER_CHANNEL_wheel_rotation); SCS_TELEMETRY_TRUCK_CHANNEL_ID_world_placement := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_world_placement); SCS_TELEMETRY_TRUCK_CHANNEL_ID_local_linear_velocity := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_local_linear_velocity); SCS_TELEMETRY_TRUCK_CHANNEL_ID_local_angular_velocity := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_local_angular_velocity); SCS_TELEMETRY_TRUCK_CHANNEL_ID_local_linear_acceleration := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_local_linear_acceleration); SCS_TELEMETRY_TRUCK_CHANNEL_ID_local_angular_acceleration := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_local_angular_acceleration); SCS_TELEMETRY_TRUCK_CHANNEL_ID_cabin_orientation := GetItemID('truck.cabin.orientation'); SCS_TELEMETRY_TRUCK_CHANNEL_ID_cabin_offset := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_cabin_offset); SCS_TELEMETRY_TRUCK_CHANNEL_ID_cabin_angular_velocity := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_cabin_angular_velocity); SCS_TELEMETRY_TRUCK_CHANNEL_ID_cabin_angular_acceleration := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_cabin_angular_acceleration); SCS_TELEMETRY_TRUCK_CHANNEL_ID_head_offset := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_head_offset); SCS_TELEMETRY_TRUCK_CHANNEL_ID_speed := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_speed); SCS_TELEMETRY_TRUCK_CHANNEL_ID_engine_rpm := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_engine_rpm); SCS_TELEMETRY_TRUCK_CHANNEL_ID_engine_gear := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_engine_gear); SCS_TELEMETRY_TRUCK_CHANNEL_ID_input_steering := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_input_steering); SCS_TELEMETRY_TRUCK_CHANNEL_ID_input_throttle := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_input_throttle); SCS_TELEMETRY_TRUCK_CHANNEL_ID_input_brake := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_input_brake); SCS_TELEMETRY_TRUCK_CHANNEL_ID_input_clutch := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_input_clutch); SCS_TELEMETRY_TRUCK_CHANNEL_ID_effective_steering := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_effective_steering); SCS_TELEMETRY_TRUCK_CHANNEL_ID_effective_throttle := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_effective_throttle); SCS_TELEMETRY_TRUCK_CHANNEL_ID_effective_brake := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_effective_brake); SCS_TELEMETRY_TRUCK_CHANNEL_ID_effective_clutch := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_effective_clutch); SCS_TELEMETRY_TRUCK_CHANNEL_ID_cruise_control := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_cruise_control); SCS_TELEMETRY_TRUCK_CHANNEL_ID_hshifter_slot := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_hshifter_slot); SCS_TELEMETRY_TRUCK_CHANNEL_ID_hshifter_selector := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_hshifter_selector); SCS_TELEMETRY_TRUCK_CHANNEL_ID_parking_brake := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_parking_brake); SCS_TELEMETRY_TRUCK_CHANNEL_ID_motor_brake := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_motor_brake); SCS_TELEMETRY_TRUCK_CHANNEL_ID_retarder_level := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_retarder_level); SCS_TELEMETRY_TRUCK_CHANNEL_ID_brake_air_pressure := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure); SCS_TELEMETRY_TRUCK_CHANNEL_ID_brake_air_pressure_warning := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure_warning); SCS_TELEMETRY_TRUCK_CHANNEL_ID_brake_temperature := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_brake_temperature); SCS_TELEMETRY_TRUCK_CHANNEL_ID_brake_air_pressure_emergency := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure_emergency); SCS_TELEMETRY_TRUCK_CHANNEL_ID_fuel := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_fuel); SCS_TELEMETRY_TRUCK_CHANNEL_ID_fuel_warning := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_fuel_warning); SCS_TELEMETRY_TRUCK_CHANNEL_ID_fuel_average_consumption := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_fuel_average_consumption); SCS_TELEMETRY_TRUCK_CHANNEL_ID_adblue := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_adblue); SCS_TELEMETRY_TRUCK_CHANNEL_ID_adblue_warning := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_adblue_warning); SCS_TELEMETRY_TRUCK_CHANNEL_ID_adblue_average_consumption := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_adblue_average_consumption); SCS_TELEMETRY_TRUCK_CHANNEL_ID_oil_pressure := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_oil_pressure); SCS_TELEMETRY_TRUCK_CHANNEL_ID_oil_pressure_warning := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_oil_pressure_warning); SCS_TELEMETRY_TRUCK_CHANNEL_ID_oil_temperature := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_oil_temperature); SCS_TELEMETRY_TRUCK_CHANNEL_ID_water_temperature := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_water_temperature); SCS_TELEMETRY_TRUCK_CHANNEL_ID_water_temperature_warning := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_water_temperature_warning); SCS_TELEMETRY_TRUCK_CHANNEL_ID_battery_voltage := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_battery_voltage); SCS_TELEMETRY_TRUCK_CHANNEL_ID_battery_voltage_warning := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_battery_voltage_warning); SCS_TELEMETRY_TRUCK_CHANNEL_ID_electric_enabled := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_electric_enabled); SCS_TELEMETRY_TRUCK_CHANNEL_ID_engine_enabled := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_engine_enabled); SCS_TELEMETRY_TRUCK_CHANNEL_ID_lblinker := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_lblinker); SCS_TELEMETRY_TRUCK_CHANNEL_ID_rblinker := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_rblinker); SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_parking := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_light_parking); SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_rblinker := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_light_rblinker); SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_lblinker := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_light_lblinker); SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_low_beam := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_light_low_beam); SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_high_beam := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_light_high_beam); SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_aux_front := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_light_aux_front); SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_aux_roof := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_light_aux_roof); SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_beacon := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_light_beacon); SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_brake := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_light_brake); SCS_TELEMETRY_TRUCK_CHANNEL_ID_light_reverse := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_light_reverse); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wipers := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wipers); SCS_TELEMETRY_TRUCK_CHANNEL_ID_dashboard_backlight := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_dashboard_backlight); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wear_engine := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wear_engine); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wear_transmission := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wear_transmission); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wear_cabin := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wear_cabin); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wear_chassis := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wear_chassis); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wear_wheels := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wear_wheels); SCS_TELEMETRY_TRUCK_CHANNEL_ID_odometer := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_odometer); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_susp_deflection := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_susp_deflection); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_on_ground := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_on_ground); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_substance := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_substance); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_velocity := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_velocity); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_steering := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_steering); SCS_TELEMETRY_TRUCK_CHANNEL_ID_wheel_rotation := GetItemID(SCS_TELEMETRY_TRUCK_CHANNEL_wheel_rotation); end; {$ENDIF} //------------------------------------------------------------------------------ Function ConfigMergeIDAndAttribute(const ConfigID, AttributeName: TelemetryString): TelemetryString; begin Result := ConfigID + cConfigFieldsSeparator + AttributeName; end; //------------------------------------------------------------------------------ Function ConfigRemoveIDFromName(const ConfigName,ConfigID: TelemetryString): TelemetryString; begin Result := Copy(ConfigName,Length(ConfigID) + Length(cConfigFieldsSeparator) + 1, Length(ConfigName)); end; {==============================================================================} { Initialization section } {==============================================================================} {$IF not Defined(PrecomputedItemIDs) and not Defined(ManualItemIDsCompute)} initialization InitializeItemsIDs; {$IFEND} end.
unit RDOObjectProxy; interface uses Windows, Classes, SyncObjs, ComObj, ActiveX, {$IFDEF AutoServer} RDOClient_TLB, {$ENDIF} RDOInterfaces; type TRDOObjectProxy = {$IFDEF AutoServer} class( TAutoObject, IRDOObjectProxy ) {$ELSE} class( TInterfacedObject, IDispatch ) {$ENDIF} {$IFDEF AutoServer} public procedure Initialize; override; {$ELSE} public constructor Create; {$ENDIF} destructor Destroy; override; protected // IDispatch function GetIDsOfNames( const IID : TGUID; Names : Pointer; NameCount, LocaleID : Integer; DispIDs : Pointer) : HResult; {$IFDEF AutoServer } override; {$ENDIF} stdcall; {$IFNDEF AutoServer} function GetTypeInfo( Index, LocaleID : Integer; out TypeInfo ) : HResult; stdcall; function GetTypeInfoCount( out Count : Integer ) : HResult; stdcall; {$ENDIF} function Invoke( DispID : Integer; const IID : TGUID; LocaleID : Integer; Flags : Word; var Params; VarResult, ExcepInfo, ArgErr : Pointer ) : HResult; {$IFDEF AutoServer } override; {$ENDIF} stdcall; private fObjectId : integer; fRDOConnection : IRDOConnection; fTimeOut : integer; fWaitForAnswer : boolean; fPriority : integer; fErrorCode : integer; fDispIds : TStringList; fDispLock : TCriticalSection; private procedure Lock; procedure Unlock; function GetSingleThreaded : boolean; procedure SetSingleThreaded(value : boolean); function GetDispIndexOf(const name : string) : integer; function AddName(const name : string) : integer; function GetNameAt(index : integer) : string; private property SingleThreaded : boolean read GetSingleThreaded write SetSingleThreaded; end; implementation uses {$IFDEF AutoServer} ComServ, {$ENDIF} SysUtils, ErrorCodes, RDOMarshalers; const BindToName = 'bindto'; SetConnectionName = 'setconnection'; WaitForAnswerName = 'waitforanswer'; TimeOutName = 'timeout'; PriorityName = 'priority'; ErrorCodeName = 'errorcode'; OnStartPageName = 'onstartpage'; // Needed for ASP components only OnEndPageName = 'onendpage'; // Needed for ASP components only RemoteObjectName = 'remoteobjectid'; const BaseDispId = 1000; BindToDispId = BaseDispId + 1; SetConnectionDispId = BaseDispId + 2; WaitForAnswerDispId = BaseDispId + 3; TimeOutDispId = BaseDispId + 4; PriorityDispId = BaseDispId + 5; ErrorCodeDispId = BaseDispId + 6; OnStartPageDispId = BaseDispId + 7; OnEndPageDispId = BaseDispId + 8; RemoteObjectId = BaseDispId + 9; RemoteDispId = BaseDispId + 10; const noDispId = -1; const DefTimeOut = 60000; const DefPriority = THREAD_PRIORITY_NORMAL; type PInteger = ^integer; function MapQueryErrorToHResult( ErrorCode : integer ) : HResult; begin case ErrorCode of errNoError, errNoResult: Result := S_OK; errMalformedQuery: Result := E_UNEXPECTED; errIllegalObject: Result := DISP_E_BADCALLEE; errUnexistentProperty: Result := DISP_E_MEMBERNOTFOUND; errIllegalPropValue: Result := DISP_E_TYPEMISMATCH; errUnexistentMethod: Result := DISP_E_MEMBERNOTFOUND; errIllegalParamList: Result := DISP_E_BADVARTYPE; errIllegalPropType: Result := DISP_E_BADVARTYPE; else Result := E_FAIL end end; // TObjectProxy {$IFDEF AutoServer} procedure TRDOObjectProxy.Initialize; {$ELSE} constructor TRDOObjectProxy.Create; {$ENDIF} begin inherited; fDispLock := TCriticalSection.Create; fDispIds := TStringList.Create; fTimeOut := DefTimeOut; fPriority := DefPriority end; destructor TRDOObjectProxy.Destroy; begin fDispLock.Free; fDispIds.Free; inherited; end; function TRDOObjectProxy.GetIDsOfNames( const IID : TGUID; Names : Pointer; NameCount, LocaleID : Integer; DispIDs : Pointer ) : HResult; function MemberNameToDispId( MemberName : string ) : integer; const LocalMembers : array [ BindToDispId .. RemoteObjectId ] of string = ( BindToName, SetConnectionName, WaitForAnswerName, TimeOutName, PriorityName, ErrorCodeName, OnStartPageName, OnEndPageName, RemoteObjectName ); var MembNamLowerCase : string; begin result := BindToDispId; MembNamLowerCase := LowerCase(MemberName); while (result < RemoteDispId) and (LocalMembers[result] <> MembNamLowerCase) do inc(result); end; var MemberName : string; dspId : integer; begin {$IFDEF AutoServer} if not Succeeded( inherited GetIDsOfNames( IID, Names, NameCount, LocaleID, DispIDs ) ) then begin {$ENDIF} // Get prop/meth name MemberName := POLEStrList( Names )^[0]; // Get id of list dspId := GetDispIndexOf(MemberName); if dspId = noDispId then begin dspId := MemberNameToDispId(MemberName); if dspId >= RemoteDispId then dspId := AddName(MemberName); end; PInteger(DispIDs)^ := dspId; Result := NOERROR; {$IFDEF AutoServer} end else result := S_OK; {$ENDIF} end; {$IFNDEF AutoServer} function TRDOObjectProxy.GetTypeInfo( Index, LocaleID : Integer; out TypeInfo ) : HResult; begin pointer( TypeInfo ) := nil; Result := E_NOTIMPL end; function TRDOObjectProxy.GetTypeInfoCount( out Count : Integer ) : HResult; begin Count := 0; Result := NOERROR end; {$ENDIF} function TRDOObjectProxy.Invoke( DispID : Integer; const IID : TGUID; LocaleID : Integer; Flags : Word; var Params; VarResult, ExcepInfo, ArgErr : Pointer ) : HResult; var Parameters : TDispParams; ParamIdx : integer; RetValue : variant; VarParams : variant; Handled : boolean; ByRefParams : integer; MemberName : string; begin try {$IFDEF AutoServer} Result := inherited Invoke( DispId, IID, LocaleID, Flags, Params, VarResult, ExcepInfo, ArgErr ); if not Succeeded( Result ) and (DispId >= BaseDispId) then begin {$ENDIF} Parameters := TDispParams( Params ); Result := S_OK; // Adjust DispId if DispId >= RemoteDispId then begin MemberName := GetNameAt(DispId); DispId := RemoteDispId; end else MemberName := ''; case DispId of BindToDispId: if fRDOConnection <> nil then if Flags and DISPATCH_METHOD <> 0 then if Parameters.cArgs = 1 then begin if VarResult <> nil then PVariant( VarResult )^ := true; case Parameters.rgvarg[ 0 ].vt and VT_TYPEMASK of VT_INT: if Parameters.rgvarg[ 0 ].vt and VT_BYREF <> 0 then fObjectId := Parameters.rgvarg[ 0 ].pintVal^ else fObjectId := Parameters.rgvarg[ 0 ].intVal; VT_I4: if Parameters.rgvarg[ 0 ].vt and VT_BYREF <> 0 then fObjectId := Parameters.rgvarg[ 0 ].plVal^ else fObjectId := Parameters.rgvarg[ 0 ].lVal; VT_BSTR: begin if Parameters.rgvarg[ 0 ].vt and VT_BYREF <> 0 then fObjectId := MarshalObjIdGet( Parameters.rgvarg[ 0 ].pbstrVal^, fRDOConnection, fTimeOut, fPriority, fErrorCode ) else fObjectId := MarshalObjIdGet( Parameters.rgvarg[ 0 ].bstrVal, fRDOConnection, fTimeOut, fPriority, fErrorCode ); if VarResult <> nil then if fErrorCode <> errNoError then PVariant( VarResult )^ := false end else Result := DISP_E_TYPEMISMATCH end end else Result := DISP_E_BADPARAMCOUNT else Result := DISP_E_MEMBERNOTFOUND else if VarResult <> nil then PVariant( VarResult )^ := false; SetConnectionDispId: if Flags and DISPATCH_METHOD <> 0 then if Parameters.cArgs = 1 then begin if Parameters.rgvarg[ 0 ].vt and VT_TYPEMASK = VT_DISPATCH then if Parameters.rgvarg[ 0 ].vt and VT_BYREF <> 0 then try fRDOConnection := Parameters.rgvarg[ 0 ].pdispVal^ as IRDOConnection except Result := DISP_E_TYPEMISMATCH end else try fRDOConnection := IDispatch( Parameters.rgvarg[ 0 ].dispVal ) as IRDOConnection except Result := DISP_E_TYPEMISMATCH end else if Parameters.rgvarg[ 0 ].vt and VT_TYPEMASK = VT_UNKNOWN then if Parameters.rgvarg[ 0 ].vt and VT_BYREF <> 0 then try fRDOConnection := Parameters.rgvarg[ 0 ].punkVal^ as IRDOConnection except Result := DISP_E_TYPEMISMATCH end else try fRDOConnection := IUnknown( Parameters.rgvarg[ 0 ].unkVal ) as IRDOConnection except Result := DISP_E_TYPEMISMATCH end else if Parameters.rgvarg[ 0 ].vt and VT_TYPEMASK = VT_VARIANT then try fRDOConnection := IDispatch( Parameters.rgvarg[ 0 ].pvarVal^ ) as IRDOConnection except Result := DISP_E_TYPEMISMATCH end else Result := DISP_E_TYPEMISMATCH; if fRDOConnection <> nil then fTimeOut := fRDOConnection.TimeOut; end else Result := DISP_E_BADPARAMCOUNT else Result := DISP_E_MEMBERNOTFOUND; WaitForAnswerDispId .. ErrorCodeDispId, RemoteObjectId: if Flags and DISPATCH_PROPERTYGET <> 0 // reading the property then begin if Parameters.cArgs = 0 then if VarResult <> nil then case DispId of WaitForAnswerDispId: PVariant( VarResult )^ := fWaitForAnswer; TimeOutDispId: PVariant( VarResult )^ := fTimeOut; PriorityDispId: PVariant( VarResult )^ := fPriority; ErrorCodeDispId: PVariant( VarResult )^ := fErrorCode; RemoteObjectId: PVariant( VarResult )^ := fObjectId; end else Result := E_INVALIDARG else Result := DISP_E_BADPARAMCOUNT; end else if Flags and DISPATCH_METHOD <> 0 // method call then Result := DISP_E_MEMBERNOTFOUND else // setting the property, must make certain by checking a few other things if Parameters.cArgs = 1 then if ( Parameters.cNamedArgs = 1 ) and ( Parameters.rgdispidNamedArgs[ 0 ] = DISPID_PROPERTYPUT ) then case DispId of WaitForAnswerDispId: fWaitForAnswer := OleVariant( Parameters.rgvarg[ 0 ] ); TimeOutDispId: fTimeOut := OleVariant( Parameters.rgvarg[ 0 ] ); PriorityDispId: fPriority := OleVariant( Parameters.rgvarg[ 0 ] ); ErrorCodeDispId: fErrorCode := OleVariant( Parameters.rgvarg[ 0 ] ) end else Result := DISP_E_PARAMNOTOPTIONAL else Result := DISP_E_BADPARAMCOUNT; OnStartPageDispId, OnEndPageDispId: ; RemoteDispId: if fRDOConnection <> nil then begin Handled := false; if ( Flags and DISPATCH_PROPERTYGET <> 0 ) and ( Parameters.cArgs = 0 ) // property get or call to a method with no args then begin if VarResult <> nil then begin Handled := true; RetValue := MarshalPropertyGet( fObjectId, MemberName, fRDOConnection, fTimeOut, fPriority, fErrorCode ); Result := MapQueryErrorToHResult( fErrorCode ); if Result = S_OK then PVariant( VarResult )^ := RetValue; end else if Flags and DISPATCH_METHOD = 0 then begin Handled := true; Result := E_INVALIDARG end end; if not Handled then if Flags and DISPATCH_METHOD <> 0 // method call then if Parameters.cNamedArgs = 0 then begin ByRefParams := 0; if Parameters.cArgs <> 0 then begin VarParams := VarArrayCreate( [ 1, Parameters.cArgs ], varVariant ); for ParamIdx := 1 to Parameters.cArgs do begin VarParams[ ParamIdx ] := OleVariant( Parameters.rgvarg[ Parameters.cArgs - ParamIdx ] ); if TVarData( VarParams[ ParamIdx ] ).VType and varTypeMask = varVariant then inc( ByRefParams ) end end else VarParams := UnAssigned; if VarResult <> nil then TVarData( RetValue ).VType := varVariant else RetValue := UnAssigned; if fWaitForAnswer or ( VarResult <> nil ) or ( ByRefParams <> 0 ) then MarshalMethodCall( fObjectId, MemberName, VarParams, RetValue, fRDOConnection, fTimeOut, fPriority, fErrorCode ) else MarshalMethodCall( fObjectId, MemberName, VarParams, RetValue, fRDOConnection, 0, fPriority, fErrorCode ); for ParamIdx := 1 to Parameters.cArgs do if Parameters.rgvarg[ Parameters.cArgs - ParamIdx ].vt and varTypeMask = VT_VARIANT then Parameters.rgvarg[ Parameters.cArgs - ParamIdx ].pvarVal^ := VarParams[ ParamIdx ]; VarParams := NULL; Result := MapQueryErrorToHResult( fErrorCode ); if ( Result = S_OK ) and ( VarResult <> nil ) then PVariant( VarResult )^ := RetValue; end else Result := DISP_E_NONAMEDARGS else // property put but, must make certain by checking a few other things if Parameters.cArgs = 1 then if ( Parameters.cNamedArgs = 1 ) and ( Parameters.rgdispidNamedArgs[ 0 ] = DISPID_PROPERTYPUT ) then begin if fWaitForAnswer then MarshalPropertySet( fObjectId, MemberName, OleVariant( Parameters.rgvarg[ 0 ] ), fRDOConnection, fTimeOut, fPriority, fErrorCode ) else MarshalPropertySet( fObjectId, MemberName, OleVariant( Parameters.rgvarg[ 0 ] ), fRDOConnection, 0, fPriority, fErrorCode ); Result := MapQueryErrorToHResult( fErrorCode ) end else Result := DISP_E_PARAMNOTOPTIONAL else Result := DISP_E_BADPARAMCOUNT; end else Result := E_FAIL; end; {$IFDEF AutoServer} end; {$ENDIF} finally end; end; procedure TRDOObjectProxy.Lock; begin if fDispLock <> nil then fDispLock.Enter; end; procedure TRDOObjectProxy.Unlock; begin if fDispLock <> nil then fDispLock.Leave; end; function TRDOObjectProxy.GetSingleThreaded : boolean; begin result := fDispLock = nil; end; procedure TRDOObjectProxy.SetSingleThreaded(value : boolean); begin if value <> SingleThreaded then if not value then fDispLock := TCriticalSection.Create else begin fDispLock.Free; fDispLock := nil; end; end; function TRDOObjectProxy.GetDispIndexOf(const name : string) : integer; begin Lock; try result := fDispIds.IndexOf(name); if result <> -1 then result := result + RemoteDispId else result := noDispId; finally Unlock; end; end; function TRDOObjectProxy.AddName(const name : string) : integer; begin Lock; try result := fDispIds.Add(name) + RemoteDispId; finally Unlock; end; end; function TRDOObjectProxy.GetNameAt(index : integer) : string; begin Lock; try dec(index, RemoteDispId); if index < fDispIds.Count then result := fDispIds[index] else result := ''; finally Unlock; end; end; initialization { MembNameTLSIdx := TLSAlloc; if MembNameTLSIdx = $FFFFFFFF then raise Exception.Create( 'Unable to use thread local storage' ); } {$IFDEF AutoServer} TAutoObjectFactory.Create( ComServer, TRDOObjectProxy, Class_RDOObjectProxy, ciMultiInstance ) {$ENDIF} finalization { if MembNameTLSIdx <> $FFFFFFFF then TLSFree( MembNameTLSIdx ) } end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.42 2/1/05 12:36:36 AM RLebeau Removed CommandHandlersEnabled property, no longer used Rev 1.41 12/2/2004 9:26:42 PM JPMugaas Bug fix. Rev 1.40 2004.10.27 9:20:04 AM czhower For TIdStrings Rev 1.39 10/26/2004 8:42:58 PM JPMugaas Should be more portable with new references to TIdStrings and TIdStringList. Rev 1.38 6/21/04 10:07:14 PM RLebeau Updated .DoConnect() to make sure the connection is still connected before then sending the Greeting Rev 1.37 6/20/2004 12:01:44 AM DSiders Added "Do Not Localize" comments. Rev 1.36 6/16/04 12:37:06 PM RLebeau more compiler errors Rev 1.35 6/16/04 12:30:32 PM RLebeau compiler errors Rev 1.34 6/16/04 12:12:26 PM RLebeau Updated ExceptionReply, Greeting, HelpReply, MaxConnectionReply, and ReplyUnknownCommand properties to use getter methods that call virtual Create methods which descendants can override for class-specific initializations Rev 1.33 5/16/04 5:16:52 PM RLebeau Added setter methods to ExceptionReply, HelpReply, and ReplyTexts properties Rev 1.32 4/19/2004 5:39:58 PM BGooijen Added comment Rev 1.31 4/18/2004 11:58:44 PM BGooijen Wasn't thread safe Rev 1.30 3/3/2004 4:59:38 AM JPMugaas Updated for new properties. Rev 1.29 2004.03.01 5:12:24 PM czhower -Bug fix for shutdown of servers when connections still existed (AV) -Implicit HELP support in CMDserver -Several command handler bugs -Additional command handler functionality. Rev 1.28 2004.02.29 9:43:08 PM czhower Added ReadCommandLine. Rev 1.27 2004.02.29 8:17:18 PM czhower Minor cosmetic changes to code. Rev 1.26 2004.02.03 4:17:08 PM czhower For unit name changes. Rev 1.25 03/02/2004 01:49:22 CCostelloe Added DoReplyUnknownCommand to allow TIdIMAP4Server set a correct reply for unknown commands Rev 1.24 1/29/04 9:43:16 PM RLebeau Added setter methods to various TIdReply properties Rev 1.23 2004.01.20 10:03:22 PM czhower InitComponent Rev 1.22 1/5/2004 2:35:36 PM JPMugaas Removed of object in method declarations. Rev 1.21 1/5/04 10:12:58 AM RLebeau Fixed Typos in OnBeforeCommandHandler and OnAfterCommandHandler events Rev 1.20 1/4/04 8:45:34 PM RLebeau Added OnBeforeCommandHandler and OnAfterCommandHandler events Rev 1.19 1/1/2004 9:33:22 PM BGooijen the abstract class TIdReply was created sometimes, fixed that Rev 1.18 2003.10.18 9:33:26 PM czhower Boatload of bug fixes to command handlers. Rev 1.17 2003.10.18 8:03:58 PM czhower Defaults for codes Rev 1.16 8/31/2003 11:49:40 AM BGooijen removed FReplyClass, this was also in TIdTCPServer Rev 1.15 7/9/2003 10:55:24 PM BGooijen Restored all features Rev 1.14 7/9/2003 04:36:08 PM JPMugaas You now can override the TIdReply with your own type. This should illiminate some warnings about some serious issues. TIdReply is ONLY a base class with virtual methods. Rev 1.13 2003.07.08 2:26:02 PM czhower Sergio's update Rev 1.0 7/7/2003 7:06:44 PM SPerry Component that uses command handlers Rev 1.0 7/6/2003 4:47:32 PM SPerry Units that use Command handlers Adapted to IdCommandHandlers.pas SPerry Rev 1.7 4/4/2003 8:08:00 PM BGooijen moved some consts from tidtcpserver here Rev 1.6 3/23/2003 11:22:24 PM BGooijen Moved some code to HandleCommand Rev 1.5 3/22/2003 1:46:36 PM BGooijen Removed unused variables Rev 1.4 3/20/2003 12:18:30 PM BGooijen Moved ReplyExceptionCode from TIdTCPServer to TIdCmdTCPServer Rev 1.3 3/20/2003 12:14:18 PM BGooijen Re-enabled Server.ReplyException Rev 1.2 2/24/2003 07:21:50 PM JPMugaas Now compiles with new core code restructures. Rev 1.1 1/23/2003 11:06:10 AM BGooijen Rev 1.0 1/20/2003 12:48:40 PM BGooijen Tcpserver with command handlers, these were originally in TIdTcpServer, but are now moved here } unit IdCmdTCPServer; interface {$I IdCompilerDefines.inc} //Put FPC into Delphi mode uses Classes, IdCommandHandlers, IdContext, IdIOHandler, IdReply, IdTCPServer, SysUtils; type TIdCmdTCPServer = class; { Events } TIdCmdTCPServerAfterCommandHandlerEvent = procedure(ASender: TIdCmdTCPServer; AContext: TIdContext) of object; TIdCmdTCPServerBeforeCommandHandlerEvent = procedure(ASender: TIdCmdTCPServer; var AData: string; AContext: TIdContext) of object; TIdCmdTCPServer = class(TIdTCPServer) protected FCommandHandlers: TIdCommandHandlers; FCommandHandlersInitialized: Boolean; FExceptionReply: TIdReply; FHelpReply: TIdReply; FGreeting: TIdReply; FMaxConnectionReply: TIdReply; FOnAfterCommandHandler: TIdCmdTCPServerAfterCommandHandlerEvent; FOnBeforeCommandHandler: TIdCmdTCPServerBeforeCommandHandlerEvent; FReplyClass: TIdReplyClass; FReplyTexts: TIdReplies; FReplyUnknownCommand: TIdReply; // procedure CheckOkToBeActive; override; function CreateExceptionReply: TIdReply; virtual; function CreateGreeting: TIdReply; virtual; function CreateHelpReply: TIdReply; virtual; function CreateMaxConnectionReply: TIdReply; virtual; function CreateReplyUnknownCommand: TIdReply; virtual; procedure DoAfterCommandHandler(ASender: TIdCommandHandlers; AContext: TIdContext); procedure DoBeforeCommandHandler(ASender: TIdCommandHandlers; var AData: string; AContext: TIdContext); procedure DoConnect(AContext: TIdContext); override; function DoExecute(AContext: TIdContext): Boolean; override; procedure DoMaxConnectionsExceeded(AIOHandler: TIdIOHandler); override; // This is here to allow servers to override this functionality, such as IMAP4 server procedure DoReplyUnknownCommand(AContext: TIdContext; ALine: string); virtual; function GetExceptionReply: TIdReply; function GetGreeting: TIdReply; function GetHelpReply: TIdReply; function GetMaxConnectionReply: TIdReply; function GetRepliesClass: TIdRepliesClass; virtual; function GetReplyClass: TIdReplyClass; virtual; function GetReplyUnknownCommand: TIdReply; procedure InitializeCommandHandlers; virtual; procedure InitComponent; override; // This is used by command handlers as the only input. This can be overriden to filter, modify, // or preparse the input. function ReadCommandLine(AContext: TIdContext): string; virtual; procedure Startup; override; procedure SetCommandHandlers(AValue: TIdCommandHandlers); procedure SetExceptionReply(AValue: TIdReply); procedure SetGreeting(AValue: TIdReply); procedure SetHelpReply(AValue: TIdReply); procedure SetMaxConnectionReply(AValue: TIdReply); procedure SetReplyUnknownCommand(AValue: TIdReply); procedure SetReplyTexts(AValue: TIdReplies); public destructor Destroy; override; published property CommandHandlers: TIdCommandHandlers read FCommandHandlers write SetCommandHandlers; property ExceptionReply: TIdReply read GetExceptionReply write SetExceptionReply; property Greeting: TIdReply read GetGreeting write SetGreeting; property HelpReply: TIdReply read GetHelpReply write SetHelpReply; property MaxConnectionReply: TIdReply read GetMaxConnectionReply write SetMaxConnectionReply; property ReplyTexts: TIdReplies read FReplyTexts write SetReplyTexts; property ReplyUnknownCommand: TIdReply read GetReplyUnknownCommand write SetReplyUnknownCommand; // property OnAfterCommandHandler: TIdCmdTCPServerAfterCommandHandlerEvent read FOnAfterCommandHandler write FOnAfterCommandHandler; property OnBeforeCommandHandler: TIdCmdTCPServerBeforeCommandHandlerEvent read FOnBeforeCommandHandler write FOnBeforeCommandHandler; end; implementation uses IdGlobal, IdResourceStringsCore, IdReplyRFC; function TIdCmdTCPServer.GetReplyClass: TIdReplyClass; begin Result := TIdReplyRFC; end; function TIdCmdTCPServer.GetRepliesClass: TIdRepliesClass; begin Result := TIdRepliesRFC; end; destructor TIdCmdTCPServer.Destroy; begin inherited Destroy; FreeAndNil(FReplyUnknownCommand); FreeAndNil(FReplyTexts); FreeAndNil(FMaxConnectionReply); FreeAndNil(FHelpReply); FreeAndNil(FGreeting); FreeAndNil(FExceptionReply); FreeAndNil(FCommandHandlers); end; procedure TIdCmdTCPServer.DoAfterCommandHandler(ASender: TIdCommandHandlers; AContext: TIdContext); begin if Assigned(OnAfterCommandHandler) then begin OnAfterCommandHandler(Self, AContext); end; end; procedure TIdCmdTCPServer.DoBeforeCommandHandler(ASender: TIdCommandHandlers; var AData: string; AContext: TIdContext); begin if Assigned(OnBeforeCommandHandler) then begin OnBeforeCommandHandler(Self, AData, AContext); end; end; function TIdCmdTCPServer.DoExecute(AContext: TIdContext): Boolean; var LLine: string; begin if CommandHandlers.Count > 0 then begin Result := True; if AContext.Connection.Connected then begin LLine := ReadCommandLine(AContext); // OLX sends blank lines during reset groups (NNTP) and expects no response. // Not sure what the RFCs say about blank lines. // I telnetted to some newsservers, and they dont respond to blank lines. // This unit is core and not NNTP, but we should be consistent. if LLine <> '' then begin if not FCommandHandlers.HandleCommand(AContext, LLine) then begin DoReplyUnknownCommand(AContext, LLine); end; end; end; end else begin Result := inherited DoExecute(AContext); end; if Result and Assigned(AContext.Connection) then begin Result := AContext.Connection.Connected; end; // the return value is used to determine if the DoExecute needs to be called again by the thread end; procedure TIdCmdTCPServer.DoReplyUnknownCommand(AContext: TIdContext; ALine: string); var LReply: TIdReply; begin if CommandHandlers.PerformReplies then begin LReply := FReplyClass.CreateWithReplyTexts(nil, ReplyTexts); try LReply.Assign(ReplyUnknownCommand); LReply.Text.Add(ALine); AContext.Connection.IOHandler.Write(LReply.FormattedReply); finally FreeAndNil(LReply); end; end; end; procedure TIdCmdTCPServer.InitializeCommandHandlers; begin end; procedure TIdCmdTCPServer.DoConnect(AContext: TIdContext); var LGreeting: TIdReply; begin inherited DoConnect(AContext); // RLebeau - check the connection first in case the application // chose to disconnect the connection in the OnConnect event handler. if AContext.Connection.Connected then begin if Greeting.ReplyExists then begin ReplyTexts.UpdateText(Greeting); LGreeting := FReplyClass.Create(nil); try // SendGreeting calls TIdReply.GetFormattedReply LGreeting.Assign(Greeting); // and that changes the reply object, so we have to SendGreeting(AContext, LGreeting); // clone it to make it thread-safe finally FreeAndNil(LGreeting); end; end; end; end; procedure TIdCmdTCPServer.DoMaxConnectionsExceeded(AIOHandler: TIdIOHandler); begin inherited DoMaxConnectionsExceeded(AIOHandler); //Do not UpdateText here - in thread. Is done in constructor AIOHandler.Write(MaxConnectionReply.FormattedReply); end; procedure TIdCmdTCPServer.Startup; var i, j: Integer; LDescr: TStrings; LHelpList: TStringList; LHandler: TIdCommandHandler; begin inherited Startup; if not FCommandHandlersInitialized then begin // InitializeCommandHandlers must be called only at runtime, and only after streaming // has occured. This used to be in .Loaded and that worked for forms. It failed // for dynamically created instances and also for descendant classes. FCommandHandlersInitialized := True; InitializeCommandHandlers; if HelpReply.Code <> '' then begin with CommandHandlers.Add do begin Command := 'Help'; {do not localize} Description.Text := 'Displays commands that the servers supports.'; {do not localize} NormalReply.Assign(HelpReply); LHelpList := TStringList.Create; try for i := 0 to CommandHandlers.Count - 1 do begin LHandler := CommandHandlers.Items[i]; if LHandler.HelpVisible then begin LHelpList.AddObject(LHandler.Command+LHandler.HelpSuperScript, LHandler); end; end; LHelpList.Sort; for i := 0 to LHelpList.Count - 1 do begin Response.Add(LHelpList[i]); LDescr := TIdCommandHandler(LHelpList.Objects[i]).Description; for j := 0 to LDescr.Count - 1 do begin Response.Add(' ' + LDescr[j]); {do not localize} end; Response.Add(''); {do not localize} end; finally FreeAndNil(LHelpList); end; end; end; end; end; procedure TIdCmdTCPServer.SetCommandHandlers(AValue: TIdCommandHandlers); begin FCommandHandlers.Assign(AValue); end; function TIdCmdTCPServer.CreateExceptionReply: TIdReply; begin Result := FReplyClass.CreateWithReplyTexts(nil, ReplyTexts); Result.SetReply(500, 'Unknown Internal Error'); {do not localize} end; function TIdCmdTCPServer.GetExceptionReply: TIdReply; begin if FExceptionReply = nil then begin FExceptionReply := CreateExceptionReply; end; Result := FExceptionReply; end; procedure TIdCmdTCPServer.SetExceptionReply(AValue: TIdReply); begin ExceptionReply.Assign(AValue); end; function TIdCmdTCPServer.CreateGreeting: TIdReply; begin Result := FReplyClass.CreateWithReplyTexts(nil, ReplyTexts); Result.SetReply(200, 'Welcome'); {do not localize} end; function TIdCmdTCPServer.GetGreeting: TIdReply; begin if FGreeting = nil then begin FGreeting := CreateGreeting; end; Result := FGreeting; end; procedure TIdCmdTCPServer.SetGreeting(AValue: TIdReply); begin Greeting.Assign(AValue); end; function TIdCmdTCPServer.CreateHelpReply: TIdReply; begin Result := FReplyClass.CreateWithReplyTexts(nil, ReplyTexts); Result.SetReply(100, 'Help follows'); {do not localize} end; function TIdCmdTCPServer.GetHelpReply: TIdReply; begin if FHelpReply = nil then begin FHelpReply := CreateHelpReply; end; Result := FHelpReply; end; procedure TIdCmdTCPServer.SetHelpReply(AValue: TIdReply); begin HelpReply.Assign(AValue); end; function TIdCmdTCPServer.CreateMaxConnectionReply: TIdReply; begin Result := FReplyClass.CreateWithReplyTexts(nil, ReplyTexts); Result.SetReply(300, 'Too many connections. Try again later.'); {do not localize} end; function TIdCmdTCPServer.GetMaxConnectionReply: TIdReply; begin if FMaxConnectionReply = nil then begin FMaxConnectionReply := CreateMaxConnectionReply; end; Result := FMaxConnectionReply; end; procedure TIdCmdTCPServer.SetMaxConnectionReply(AValue: TIdReply); begin MaxConnectionReply.Assign(AValue); end; function TIdCmdTCPServer.CreateReplyUnknownCommand: TIdReply; begin Result := FReplyClass.CreateWithReplyTexts(nil, ReplyTexts); Result.SetReply(400, 'Unknown Command'); {do not localize} end; function TIdCmdTCPServer.GetReplyUnknownCommand: TIdReply; begin if FReplyUnknownCommand = nil then begin FReplyUnknownCommand := CreateReplyUnknownCommand; end; Result := FReplyUnknownCommand; end; procedure TIdCmdTCPServer.SetReplyUnknownCommand(AValue: TIdReply); begin ReplyUnknownCommand.Assign(AValue); end; procedure TIdCmdTCPServer.SetReplyTexts(AValue: TIdReplies); begin FReplyTexts.Assign(AValue); end; procedure TIdCmdTCPServer.InitComponent; begin inherited InitComponent; FReplyClass := GetReplyClass; // Before Command handlers as they need FReplyTexts, but after FReplyClass is set FReplyTexts := GetRepliesClass.Create(Self, FReplyClass); FCommandHandlers := TIdCommandHandlers.Create(Self, FReplyClass, ReplyTexts, ExceptionReply); FCommandHandlers.OnAfterCommandHandler := DoAfterCommandHandler; FCommandHandlers.OnBeforeCommandHandler := DoBeforeCommandHandler; end; function TIdCmdTCPServer.ReadCommandLine(AContext: TIdContext): string; begin Result := AContext.Connection.IOHandler.ReadLn; end; procedure TIdCmdTCPServer.CheckOkToBeActive; begin if (CommandHandlers.Count = 0) and FCommandHandlersInitialized then begin inherited CheckOkToBeActive; end; end; end.
{ File: CFNetwork/CFNetworkErrors.h Contains: CFNetwork error header Version: CFNetwork-219~1 Copyright: © 2006 by Apple Computer, Inc., all rights reserved } { Pascal Translation: Gale R Paeper, <gpaeper@empirenet.com>, 2008 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CFNetworkErrorss; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes, CFBase; {$ALIGN POWER} {GRP translation note: Double 's' unit name ending intentional to avoid GPC redeclaration error with 'CFNetworkErrors' type identifier.} { * kCFErrorDomainCFNetwork * * Discussion: * Error domain for all errors originating in CFNetwork. Error codes * may be interpreted using the list below. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFErrorDomainCFNetwork: CFStringRef; external name '_kCFErrorDomainCFNetwork'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFErrorDomainWinSock * * Discussion: * On Windows, errors originating from WinSock are represented using * this domain. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFErrorDomainWinSock: CFStringRef; external name '_kCFErrorDomainWinSock'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * CFNetworkErrors * * Discussion: * The list of all error codes returned under the error domain * kCFErrorDomainCFNetwork } type CFNetworkErrors = SInt32; const kCFHostErrorHostNotFound = 1; kCFHostErrorUnknown = 2; { Query the kCFGetAddrInfoFailureKey to get the value returned from getaddrinfo; lookup in netdb.h} { SOCKS errors; in all cases you may query kCFSOCKSStatusCodeKey to recover the status code returned by the server} kCFSOCKSErrorUnknownClientVersion = 100; kCFSOCKSErrorUnsupportedServerVersion = 101; { Query the kCFSOCKSVersionKey to find the version requested by the server} { SOCKS4-specific errors} kCFSOCKS4ErrorRequestFailed = 110; { request rejected or failed by the server} kCFSOCKS4ErrorIdentdFailed = 111; { request rejected because SOCKS server cannot connect to identd on the client} kCFSOCKS4ErrorIdConflict = 112; { request rejected because the client program and identd report different user-ids} kCFSOCKS4ErrorUnknownStatusCode = 113; { SOCKS5-specific errors} kCFSOCKS5ErrorBadState = 120; kCFSOCKS5ErrorBadResponseAddr = 121; kCFSOCKS5ErrorBadCredentials = 122; kCFSOCKS5ErrorUnsupportedNegotiationMethod = 123; { query kCFSOCKSNegotiationMethodKey to find the method requested} kCFSOCKS5ErrorNoAcceptableMethod = 124; { Errors originating from CFNetServices} kCFNetServiceErrorUnknown = -72000; kCFNetServiceErrorCollision = -72001; kCFNetServiceErrorNotFound = -72002; kCFNetServiceErrorInProgress = -72003; kCFNetServiceErrorBadArgument = -72004; kCFNetServiceErrorCancel = -72005; kCFNetServiceErrorInvalid = -72006; kCFNetServiceErrorTimeout = -72007; kCFNetServiceErrorDNSServiceFailure = -73000; { An error from DNS discovery; look at kCFDNSServiceFailureKey to get the error number and interpret using dns_sd.h} { FTP errors; query the kCFFTPStatusCodeKey to get the status code returned by the server} kCFFTPErrorUnexpectedStatusCode = 200; { HTTP errors} kCFErrorHTTPAuthenticationTypeUnsupported = 300; kCFErrorHTTPBadCredentials = 301; kCFErrorHTTPConnectionLost = 302; kCFErrorHTTPParseFailure = 303; kCFErrorHTTPRedirectionLoopDetected = 304; kCFErrorHTTPBadURL = 305; kCFErrorHTTPProxyConnectionFailure = 306; kCFErrorHTTPBadProxyCredentials = 307; { Keys used by CFNetwork to pass additional error information back to the user within CFError's userInfo dictionary } { * kCFGetAddrInfoFailureKey * * Discussion: * When an error of kCFHostErrorUnknown is returned, this key's * value is set to a CFNumber containing the raw error value * returned by getaddrinfo() * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFGetAddrInfoFailureKey: CFStringRef; external name '_kCFGetAddrInfoFailureKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFSOCKSStatusCodeKey * * Discussion: * When a SOCKS failure has occurred, this key's value is set to a * CFString containing the status value returned by the SOCKS server. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFSOCKSStatusCodeKey: CFStringRef; external name '_kCFSOCKSStatusCodeKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFSOCKSVersionKey * * Discussion: * When an error of kCFSOCKSErrorUnsupportedServerVersion is * returned, this key's value is set to a CFString containing the * version number requested by the server. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFSOCKSVersionKey: CFStringRef; external name '_kCFSOCKSVersionKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFSOCKSNegotiationMethodKey * * Discussion: * When an error of kCFSOCKS5ErrorUnsupportedNegotiationMethod is * returned, this key's value is set to a CFString containing the * negotiation method requested by the server. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFSOCKSNegotiationMethodKey: CFStringRef; external name '_kCFSOCKSNegotiationMethodKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFDNSServiceFailureKey * * Discussion: * When an error of kCFNetServicesErrorDNSServiceFailure is * returned, this key's value is set to a CFNumber containing the * value returned from DNS; interret it using the values dns_sd.h * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFDNSServiceFailureKey: CFStringRef; external name '_kCFDNSServiceFailureKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFFTPStatusCodeKey * * Discussion: * When an error of kCFFTPErrorUnexpectedStatusCode is returned, * this key's value is set to a CFString containing the status code * returned by the server * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFFTPStatusCodeKey: CFStringRef; external name '_kCFFTPStatusCodeKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) end.
unit atFilterHelper; // Модуль: "w:\quality\test\garant6x\AdapterTest\AdapterHelpers\atFilterHelper.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatFilterHelper" MUID: (503F84050182) interface uses l3IntfUses , DynamicTreeUnit ; type ContextFilterParams = record ContextPlace: TContextPlace; FindOrder: TFindOrder; SearchArea: TSearchArea; end;//ContextFilterParams TatContextFilter = class private f_TweakContextOnAssignment: Boolean; {* Изменяет контекст при присвоении в соответствии с настройками фильтра } f_Filter: IContextFilter; protected function pm_GetContext: AnsiString; procedure pm_SetContext(const aValue: AnsiString); function pm_GetArea: TSearchArea; virtual; procedure pm_SetArea(aValue: TSearchArea); virtual; function pm_GetOrder: TFindOrder; virtual; procedure pm_SetOrder(aValue: TFindOrder); virtual; function pm_GetPlace: TContextPlace; virtual; procedure pm_SetPlace(aValue: TContextPlace); virtual; public constructor Create(const aFilter: IContextFilter); reintroduce; overload; constructor Create; reintroduce; overload; public property Context: AnsiString read pm_GetContext write pm_SetContext; property TweakContextOnAssignment: Boolean read f_TweakContextOnAssignment write f_TweakContextOnAssignment; {* Изменяет контекст при присвоении в соответствии с настройками фильтра } property Filter: IContextFilter read f_Filter; property Area: TSearchArea read pm_GetArea write pm_SetArea; property Order: TFindOrder read pm_GetOrder write pm_SetOrder; property Place: TContextPlace read pm_GetPlace write pm_SetPlace; end;//TatContextFilter TatFilterHelper = class end;//TatFilterHelper const DEFAULT_CONTEXT_FILTER_PARAMS: ContextFilterParams = (ContextPlace: CP_ANY; FindOrder : FO_ANY; SearchArea : SA_ALL_LEVEL); implementation uses l3ImplUses , SysUtils , atStringHelper , atGblAdapterWorker , IOUnit //#UC START# *503F84050182impl_uses* //#UC END# *503F84050182impl_uses* ; function TatContextFilter.pm_GetContext: AnsiString; //#UC START# *5040D48103B0_5040D3EE02D5get_var* var l_Str : IString; //#UC END# *5040D48103B0_5040D3EE02D5get_var* begin //#UC START# *5040D48103B0_5040D3EE02D5get_impl* f_Filter.GetContext(l_Str); Result := TatStringHelper.AStr2DStr(l_Str); //#UC END# *5040D48103B0_5040D3EE02D5get_impl* end;//TatContextFilter.pm_GetContext procedure TatContextFilter.pm_SetContext(const aValue: AnsiString); //#UC START# *5040D48103B0_5040D3EE02D5set_var* var l_Context : String; //#UC END# *5040D48103B0_5040D3EE02D5set_var* begin //#UC START# *5040D48103B0_5040D3EE02D5set_impl* l_Context := aValue; if f_TweakContextOnAssignment then begin // преобразуем контекст в стиле TnsFilterableTreeStruct.MakeSearchStr l_Context := Trim(StringReplace(l_Context, '*', ' ', [rfReplaceAll])); l_Context := StringReplace(l_Context, ' ', ' ', [rfReplaceAll]); case Place of CP_BEGIN_OF_WORD : l_Context := '* ' + StringReplace(l_Context, ' ', '* ', [rfReplaceAll]) + '*'; CP_ANY : l_Context := '* *' + StringReplace(l_Context, ' ', '* *', [rfReplaceAll]) + '*'; CP_BEGIN_OF_PHRASE : l_Context := StringReplace(l_Context, ' ', '* ', [rfReplaceAll]) + '*'; end; end; f_Filter.SetContext( TatStringHelper.DStr2AStr(l_Context) ); //#UC END# *5040D48103B0_5040D3EE02D5set_impl* end;//TatContextFilter.pm_SetContext function TatContextFilter.pm_GetArea: TSearchArea; //#UC START# *5040D43501FA_5040D3EE02D5get_var* //#UC END# *5040D43501FA_5040D3EE02D5get_var* begin //#UC START# *5040D43501FA_5040D3EE02D5get_impl* Result := f_Filter.GetArea; //#UC END# *5040D43501FA_5040D3EE02D5get_impl* end;//TatContextFilter.pm_GetArea procedure TatContextFilter.pm_SetArea(aValue: TSearchArea); //#UC START# *5040D43501FA_5040D3EE02D5set_var* //#UC END# *5040D43501FA_5040D3EE02D5set_var* begin //#UC START# *5040D43501FA_5040D3EE02D5set_impl* f_Filter.SetArea(aValue); //#UC END# *5040D43501FA_5040D3EE02D5set_impl* end;//TatContextFilter.pm_SetArea function TatContextFilter.pm_GetOrder: TFindOrder; //#UC START# *5040D43E004C_5040D3EE02D5get_var* //#UC END# *5040D43E004C_5040D3EE02D5get_var* begin //#UC START# *5040D43E004C_5040D3EE02D5get_impl* Result := f_Filter.GetOrder; //#UC END# *5040D43E004C_5040D3EE02D5get_impl* end;//TatContextFilter.pm_GetOrder procedure TatContextFilter.pm_SetOrder(aValue: TFindOrder); //#UC START# *5040D43E004C_5040D3EE02D5set_var* //#UC END# *5040D43E004C_5040D3EE02D5set_var* begin //#UC START# *5040D43E004C_5040D3EE02D5set_impl* f_Filter.SetOrder(aValue); //#UC END# *5040D43E004C_5040D3EE02D5set_impl* end;//TatContextFilter.pm_SetOrder function TatContextFilter.pm_GetPlace: TContextPlace; //#UC START# *5040D44600D3_5040D3EE02D5get_var* //#UC END# *5040D44600D3_5040D3EE02D5get_var* begin //#UC START# *5040D44600D3_5040D3EE02D5get_impl* Result := f_Filter.GetPlace; //#UC END# *5040D44600D3_5040D3EE02D5get_impl* end;//TatContextFilter.pm_GetPlace procedure TatContextFilter.pm_SetPlace(aValue: TContextPlace); //#UC START# *5040D44600D3_5040D3EE02D5set_var* //#UC END# *5040D44600D3_5040D3EE02D5set_var* begin //#UC START# *5040D44600D3_5040D3EE02D5set_impl* f_Filter.SetPlace(aValue); //#UC END# *5040D44600D3_5040D3EE02D5set_impl* end;//TatContextFilter.pm_SetPlace constructor TatContextFilter.Create(const aFilter: IContextFilter); //#UC START# *5040D4A501C2_5040D3EE02D5_var* //#UC END# *5040D4A501C2_5040D3EE02D5_var* begin //#UC START# *5040D4A501C2_5040D3EE02D5_impl* f_Filter := aFilter; //#UC END# *5040D4A501C2_5040D3EE02D5_impl* end;//TatContextFilter.Create constructor TatContextFilter.Create; //#UC START# *5040D5BC01FF_5040D3EE02D5_var* //#UC END# *5040D5BC01FF_5040D3EE02D5_var* begin //#UC START# *5040D5BC01FF_5040D3EE02D5_impl* inherited; f_Filter := TatGblAdapterWorker.Instance.GblAdapterDll.MakeContextFilter; //#UC END# *5040D5BC01FF_5040D3EE02D5_impl* end;//TatContextFilter.Create end.
unit RESTRequest4D.Request; interface uses RESTRequest4D.Request.Intf, Data.DB, REST.Client, REST.Response.Adapter, RESTRequest4D.Request.Params.Intf, REST.Types, RESTRequest4D.Request.Body.Intf, RESTRequest4D.Request.Authentication.Intf, System.SysUtils, RESTRequest4D.Request.Headers.Intf, RESTRequest4D.Request.Response.Intf; type TRequest = class(TInterfacedObject, IRequest) private FBody: IRequestBody; FParams: IRequestParams; FResponse: IRequestResponse; FHeaders: IRequestHeaders; FAuthentication: IRequestAuthentication; FRESTRequest: TRESTRequest; FDataSetAdapter: TDataSet; FRESTResponse: TRESTResponse; FRESTClient: TRESTClient; FToken: string; procedure DoJoinComponents; procedure DoAfterExecute(Sender: TCustomRESTRequest); procedure ActiveCachedUpdates(const ADataSet: TDataSet; const AActive: Boolean = True); function GetAcceptEncoding: string; function SetAcceptEncoding(const AAcceptEncoding: string): IRequest; function GetAcceptCharset: string; function SetAcceptCharset(const AAcceptCharset: string): IRequest; function GetAccept: string; function SetAccept(const AAccept: string): IRequest; function SetDataSetAdapter(const ADataSet: TDataSet): IRequest; function SetBaseURL(const ABaseURL: string = ''): IRequest; function SetResource(const AResource: string = ''): IRequest; function SetResourceSuffix(const AResourceSuffix: string = ''): IRequest; function SetMethod(const AMethod: TRESTRequestMethod = rmGET): IRequest; function SetRaiseExceptionOn500(const ARaiseException: Boolean = True): IRequest; function SetToken(const AToken: string): IRequest; function GetRaiseExceptionOn500: Boolean; function GetFullRequestURL(const AIncludeParams: Boolean = True): string; function GetTimeout: Integer; function SetTimeout(const ATimeout: Integer): IRequest; function GetMethod: TRESTRequestMethod; function GetResourceSuffix: string; function GetResource: string; function GetBaseURL: string; function GetDataSetAdapter: TDataSet; function GetToken: string; function Execute: Integer; function Body: IRequestBody; function Headers: IRequestHeaders; function Response: IRequestResponse; function Params: IRequestParams; function Authentication: IRequestAuthentication; function ExecuteAsync(ACompletionHandler: TProc = nil; ASynchronized: Boolean = True; AFreeThread: Boolean = True; ACompletionHandlerWithError: TProc<TObject> = nil): TRESTExecutionThread; public constructor Create(const ABaseURL: string; const AToken: string = ''); overload; constructor Create(const AMethod: TRESTRequestMethod = rmGET; const ABaseURL: string = ''; const AToken: string = ''); overload; destructor Destroy; override; end; implementation uses RESTRequest4D.Request.Body, RESTRequest4D.Request.Params, RESTRequest4D.Request.Authentication, DataSet.Serialize, RESTRequest4D.Request.Headers, System.Generics.Collections, FireDAC.Comp.DataSet, FireDAC.Comp.Client, RESTRequest4D.Request.Response; { TRequest } procedure TRequest.ActiveCachedUpdates(const ADataSet: TDataSet; const AActive: Boolean = True); var LDataSet: TDataSet; LDataSetDetails: TList<TDataSet>; begin LDataSetDetails := TList<TDataSet>.Create; try if ADataSet is TFDMemTable then begin if not AActive then TFDMemTable(ADataSet).Close; TFDMemTable(ADataSet).CachedUpdates := AActive; if AActive and (not TFDMemTable(ADataSet).Active) and (TFDMemTable(ADataSet).FieldCount > 0) then TFDMemTable(ADataSet).Open; end; ADataSet.GetDetailDataSets(LDataSetDetails); for LDataSet in LDataSetDetails do ActiveCachedUpdates(LDataSet, AActive); finally LDataSetDetails.Free; end; end; function TRequest.Authentication: IRequestAuthentication; begin if not Assigned(FAuthentication) then FAuthentication := TRequestAuthentication.Create(FRESTClient); Result := FAuthentication; end; function TRequest.Body: IRequestBody; begin Result := FBody; end; constructor TRequest.Create(const ABaseURL, AToken: string); begin Create(rmGET, ABaseURL, AToken); end; constructor TRequest.Create(const AMethod: TRESTRequestMethod = rmGET; const ABaseURL: string = ''; const AToken: string = ''); begin FRESTResponse := TRESTResponse.Create(nil); FRESTClient := TRESTClient.Create(nil); FRESTRequest := TRESTRequest.Create(nil); FBody := TRequestBody.Create(FRESTRequest); FParams := TRequestParams.Create(FRESTRequest); FHeaders := TRequestHeaders.Create(FRESTRequest); FResponse := TRequestResponse.Create(FRESTResponse); FRESTRequest.OnAfterExecute := DoAfterExecute; DoJoinComponents; FRESTRequest.Method := AMethod; FRESTClient.RaiseExceptionOn500 := False; FRESTClient.BaseURL := ABaseURL; FToken := AToken; end; destructor TRequest.Destroy; begin FBody := nil; FAuthentication := nil; FParams := nil; FHeaders := nil; FreeAndNil(FRESTRequest); FreeAndNil(FRESTClient); FreeAndNil(FRESTResponse); inherited; end; procedure TRequest.DoAfterExecute(Sender: TCustomRESTRequest); begin if not Assigned(FDataSetAdapter) then Exit; ActiveCachedUpdates(FDataSetAdapter, False); FDataSetAdapter.LoadFromJSON(FRESTResponse.Content); ActiveCachedUpdates(FDataSetAdapter); end; procedure TRequest.DoJoinComponents; begin FRESTRequest.Client := FRESTClient; FRESTRequest.Response := FRESTResponse; end; function TRequest.Execute: Integer; begin if not FToken.Trim.IsEmpty then FHeaders.Add('Authorization', FToken, [poDoNotEncode]); FRESTRequest.Execute; Result := FRESTResponse.StatusCode; end; function TRequest.ExecuteAsync(ACompletionHandler: TProc; ASynchronized, AFreeThread: Boolean; ACompletionHandlerWithError: TProc<TObject>): TRESTExecutionThread; begin if not FToken.Trim.IsEmpty then FHeaders.Add('Authorization', FToken, [poDoNotEncode]); Result := FRESTRequest.ExecuteAsync(ACompletionHandler, ASynchronized, AFreeThread, ACompletionHandlerWithError); end; function TRequest.GetAccept: string; begin Result := FRESTRequest.Accept; end; function TRequest.GetAcceptCharset: string; begin Result := FRESTRequest.AcceptCharset; end; function TRequest.GetAcceptEncoding: string; begin Result := FRESTRequest.AcceptEncoding; end; function TRequest.GetBaseURL: string; begin Result := FRESTClient.BaseURL; end; function TRequest.GetDataSetAdapter: TDataSet; begin Result := FDataSetAdapter; end; function TRequest.GetFullRequestURL(const AIncludeParams: Boolean): string; begin Result := FRESTRequest.GetFullRequestURL(AIncludeParams); end; function TRequest.GetMethod: TRESTRequestMethod; begin Result := FRESTRequest.Method; end; function TRequest.GetRaiseExceptionOn500: Boolean; begin Result := FRESTClient.RaiseExceptionOn500; end; function TRequest.GetResource: string; begin Result := FRESTRequest.Resource; end; function TRequest.GetResourceSuffix: string; begin Result := FRESTRequest.ResourceSuffix; end; function TRequest.GetTimeout: Integer; begin Result := FRESTRequest.Timeout; end; function TRequest.GetToken: string; begin Result := FToken; end; function TRequest.Headers: IRequestHeaders; begin Result := FHeaders; end; function TRequest.Params: IRequestParams; begin Result := FParams; end; function TRequest.Response: IRequestResponse; begin Result := FResponse; end; function TRequest.SetAccept(const AAccept: string): IRequest; const REQUEST_DEFAULT_ACCEPT = CONTENTTYPE_APPLICATION_JSON + ', ' + CONTENTTYPE_TEXT_PLAIN + '; q=0.9, ' + CONTENTTYPE_TEXT_HTML + ';q=0.8,'; begin Result := Self; FRESTRequest.Accept := REQUEST_DEFAULT_ACCEPT; if not AAccept.Trim.IsEmpty then FRESTRequest.Accept := AAccept; end; function TRequest.SetAcceptCharset(const AAcceptCharset: string): IRequest; const REQUEST_DEFAULT_ACCEPT_CHARSET = 'utf-8, *;q=0.8'; begin Result := Self; FRESTRequest.AcceptCharset := REQUEST_DEFAULT_ACCEPT_CHARSET; if not AAcceptCharset.Trim.IsEmpty then FRESTRequest.AcceptCharset := AAcceptCharset; end; function TRequest.SetAcceptEncoding(const AAcceptEncoding: string): IRequest; begin Result := Self; FRESTRequest.AcceptEncoding := AAcceptEncoding; end; function TRequest.SetBaseURL(const ABaseURL: string = ''): IRequest; begin Result := Self; FRESTClient.BaseURL := ABaseURL; end; function TRequest.SetDataSetAdapter(const ADataSet: TDataSet): IRequest; begin Result := Self; FDataSetAdapter := ADataSet; end; function TRequest.SetMethod(const AMethod: TRESTRequestMethod): IRequest; begin Result := Self; FRESTRequest.Method := AMethod; if AMethod = TRESTRequestMethod.rmGET then Self.FBody.Clear; end; function TRequest.SetRaiseExceptionOn500(const ARaiseException: Boolean = True): IRequest; begin Result := Self; FRESTClient.RaiseExceptionOn500 := ARaiseException; end; function TRequest.SetResource(const AResource: string = ''): IRequest; begin Result := Self; FRESTRequest.Resource := AResource; end; function TRequest.SetResourceSuffix(const AResourceSuffix: string = ''): IRequest; begin Result := Self; FRESTRequest.ResourceSuffix := AResourceSuffix; end; function TRequest.SetTimeout(const ATimeout: Integer): IRequest; begin Result := Self; FRESTRequest.Timeout := ATimeout; end; function TRequest.SetToken(const AToken: string): IRequest; begin Result := Self; FToken := AToken; end; end.
unit u_DeforExpert; {$I delphiversions.inc} interface uses Windows, Messages, Controls, SysUtils, Classes, ToolsApi; procedure Register; implementation uses Menus, Dialogs, Forms, GX_CodeFormatterTypes, u_DelforTypesEx, u_DelforRegistry, GX_CodeFormatterDone, w_DelforAbout, GX_CodeFormatterConfig, GX_CodeFormatterBookmarks, GX_CodeFormatterBreakpoints, GX_CodeFormatterEngine, GX_CodeFormatterDefaultSettings, GX_CodeFormatterSettings; type TDelforExpert = class; TKeyboardNotifier = class(TNotifierObject, IOTAKeyboardBinding) private fWizard: TDelforExpert; fBindingIndex: Integer; fHotkey: TShortcutDesc; // IOTAKeyboardBinding function GetBindingType: TBindingType; function GetDisplayName: string; function GetName: string; procedure BindKeyboard(const BindingServices: IOTAKeyBindingServices); // registered Keyboard handling proc procedure KeyProc(const _Context: IOTAKeyContext; _KeyCode: TShortCut; var _BindingResult: TKeyBindingResult); procedure Unregister(_Idx: Integer); overload; public constructor Create(_Wizard: TDelforExpert; const _Shortcut: TShortcutDesc); destructor Destroy; override; procedure SetShortcut(_ShortCut: TShortCutDesc); procedure Unregister; overload; end; TDelforExpert = class(TNotifierObject, IOTAWizard) private FFormatter: TCodeFormatterEngine; FWizardSettings: TWizardSettings; // fNotifierIndex: Integer; fKeyboardNotifier: TKeyboardNotifier; function GetToolsMenu: TMenuItem; procedure FocusTopEditView; // IOTAWizard function GetIDString: string; function GetName: string; function GetState: TWizardState; procedure Execute; // IOTANotifier implemented by TNotifierObject // IOTAIdeNotifier // procedure AfterCompile(Succeeded: Boolean); // procedure BeforeCompile(const Project: IOTAProject; // var Cancel: Boolean); // procedure FileNotification(NotifyCode: TOTAFileNotification; // const FileName: string; var Cancel: Boolean); protected fSubMenu: TMenuItem; fDoneForm: TfmCodeFormatterDone; procedure FormatCurrent(_Sender: TObject); procedure Configure(_Sender: TObject); procedure About(_Sender: TObject); public constructor Create; destructor Destroy; override; end; { TDelforExpert } constructor TDelforExpert.Create; var ToolsMenu: TMenuItem; MenuItem: TMenuItem; Settings: TDefaultSettings; begin inherited Create; try FFormatter := TCodeFormatterEngine.Create; except on e: exception do begin FFormatter := nil; MessageDlg(Format('%s: %s', [e.ClassName, e.Message]), mtError, [mbOK], 0); Exit; end; end; try Settings := BorlandDefaults; TDelforRegistry.ReadSettings(Settings.Parser, Settings.Wizard); FFormatter.Settings.Settings := Settings.Parser; FWizardSettings := Settings.Wizard; except // ignore end; fDoneForm := TfmCodeFormatterDone.Create(nil); ToolsMenu := GetToolsMenu; if not Assigned(ToolsMenu) then begin MessageDlg('Something is very wrong: The IDE''s main menu has less than 3 items.'#13#10 + 'Wizard will not be installed.', mtError, [mbOK], 0); FFormatter.Free; FFormatter := nil; Exit; end; fSubmenu := TMenuItem.Create(nil); fSubMenu.Caption := 'Source Formatter'; fSubMenu.Name := 'mi_twmsExpertMain'; MenuItem := TMenuItem.Create(fSubMenu); MenuItem.Caption := 'Current &File'; MenuItem.Name := 'mi_twmsExpertCurrent'; MenuItem.OnClick := FormatCurrent; fSubMenu.Add(MenuItem); MenuItem := TMenuItem.Create(fSubMenu); MenuItem.Caption := '&Configure'; MenuItem.Name := 'mi_twmsExpertConfigure'; MenuItem.OnClick := Configure; fSubMenu.Add(MenuItem); MenuItem := TMenuItem.Create(fSubMenu); MenuItem.Caption := '&About'; MenuItem.Name := 'mi_twmsExpertAbpit'; MenuItem.OnClick := About; fSubMenu.Add(MenuItem); ToolsMenu.Insert(Settings.Wizard.ToolPosition, fSubMenu); // fNotifierIndex := (BorlandIdeServices as IOTAServices).AddNotifier(self); fKeyboardNotifier := TKeyboardNotifier.Create(self, Settings.Wizard.ShortCut); end; destructor TDelforExpert.Destroy; begin if Assigned(fKeyboardNotifier) then fKeyboardNotifier.Unregister; FFormatter.Free; FFormatter := nil; fDoneForm.Free; fSubMenu.Free; inherited; end; function TDelforExpert.GetToolsMenu: TMenuItem; var MainMenu: TMainMenu; begin MainMenu := (BorlandIdeServices as INTAServices).MainMenu; Result := MainMenu.Items.Find('&Tools'); if not Assigned(Result) then begin if MainMenu.Items.Count < 3 then begin Result := nil; Exit; end; Result := MainMenu.Items[MainMenu.Items.Count - 3]; end; end; procedure TDelforExpert.Configure(_Sender: TObject); var ToolsMenu: TMenuItem; Settings: TDefaultSettings; begin if not Assigned(FFormatter) then exit; Settings.Parser := FFormatter.Settings.Settings; Settings.Wizard := FWizardSettings; if TfmCodeFormatterConfig.Execute(Settings, false) = mrOk then begin FWizardSettings := Settings.Wizard; FFormatter.Settings.Settings := Settings.Parser; ToolsMenu := GetToolsMenu; if Assigned(ToolsMenu) and Assigned(fSubMenu) and Assigned(FFormatter) then begin ToolsMenu.Remove(fSubMenu); ToolsMenu.Insert(FWizardSettings.ToolPosition, fSubMenu); end; if Assigned(fKeyboardNotifier) then fKeyboardNotifier.Unregister; fKeyboardNotifier := TKeyboardNotifier.Create(Self, FWizardSettings.ShortCut); end; end; procedure TDelforExpert.About(_Sender: TObject); var frm: Tf_About; begin frm := Tf_About.Create(nil); try frm.ShowModal; finally frm.Free; end; end; procedure TDelforExpert.FormatCurrent(_Sender: TObject); var ModuleServices: IOTAModuleServices; Module: IOTAModule; Editor: IOTAEditor; SourceEditor: IOTASourceEditor; function ReadCurrentFile(out _Content: string): Boolean; const BUFFSIZE = 10000; var Reader: IOTAEditReader; Buffer: PChar; s: string; BytesRead: LongInt; Position: longint; begin Reader := SourceEditor.CreateReader; Result := Assigned(Reader); if not Result then Exit; _Content := ''; s := ''; GetMem(Buffer, BUFFSIZE); try Position := 0; repeat BytesRead := Reader.GetText(Position, Buffer, BUFFSIZE); SetString(s, Buffer, BytesRead); _Content := _Content + s; Position := Position + BytesRead; until BytesRead <> BUFFSIZE; finally FreeMem(Buffer); end; end; procedure ReplaceCurrentFile(const _Content: string); var Writer: IOTAEditWriter; begin Writer := SourceEditor.CreateUndoableWriter; if not Assigned(Writer) then Exit; Writer.DeleteTo(MaxLongint); Writer.Insert(PChar(_Content)); end; var Filename: string; FullText: string; ShowDone: Boolean; Bookmarks: TBookmarkHandler; Breakpoints: TBreakpointHandler; Extension: string; begin if not Assigned(FFormatter) then Exit; if Supports(BorlandIDEServices, IOTAModuleServices, ModuleServices) then begin Module := ModuleServices.CurrentModule; if not Assigned(Module) then Exit; {$IFDEF delphi6} Editor := Module.CurrentEditor; {$ELSE} Editor := Module.GetModuleFileEditor(0); {$ENDIF} if not Assigned(Editor) or not Supports(Editor, IOTASourceEditor, SourceEditor) then Exit; Filename := SourceEditor.FileName; Extension := LowerCase(ExtractFileExt(Filename)); if (Extension <> '.pas') and (Extension <> '.dpk') and (Extension <> '.dpr') and (Extension <> '.dpkw') then Exit; if not ReadCurrentFile(FullText) then Exit; Bookmarks := TBookmarkHandler.Create; try Breakpoints := TBreakpointHandler.Create; try Bookmarks.SaveBookmarks; Breakpoints.SaveBreakpoints; FFormatter.Settings.LoadCapFile(FWizardSettings.CapFileName); FFormatter.SetTextStr(PChar(FullText)); if FFormatter.Execute then begin if FFormatter.Settings.FillNewWords in [fmAddNewWord, fmAddUse, fmAddUseExcept] then FFormatter.Settings.SaveCapFile(FWizardSettings.CapFileName); if FullText = FFormatter.GetTextStr then Exit; // nothing has changed, so we don't change the buffer FullText := FFormatter.GetTextStr; ReplaceCurrentFile(FullText); if FWizardSettings.ShowDoneDialog then begin fDoneForm.ShowModal; ShowDone := not fDoneForm.chk_DontShowAgain.Checked; if Showdone <> FWizardSettings.ShowDoneDialog then begin FWizardSettings.ShowDoneDialog := ShowDone; TDelforRegistry.WriteShowDone(ShowDone); end; end; end; Breakpoints.RestoreBreakpoints; Bookmarks.RestoreBookmarks; finally Breakpoints.Free; end; finally Bookmarks.Free; end; FocusTopEditView; end; end; procedure TDelforExpert.FocusTopEditView; var EditorServices: IOTAEditorServices; EditWindow: INTAEditWindow; begin EditorServices := BorlandIDEServices as IOTAEditorServices; if Assigned(EditorServices) then if Assigned(EditorServices.TopView) then begin EditWindow := EditorServices.TopView as INTAEditWindow; if Assigned(EditWindow) then if Assigned(EditWindow.Form) then EditWindow.Form.SetFocus; end; end; function TDelforExpert.GetName: string; begin Result := 'dummzeuch.DelForExpert'; end; procedure TDelforExpert.Execute; begin end; function TDelforExpert.GetIDString: string; begin Result := GetName; end; function TDelforExpert.GetState: TWizardState; begin Result := [wsEnabled]; end; { TKeyboardNotifier } constructor TKeyboardNotifier.Create(_Wizard: TDelforExpert; const _Shortcut: TShortcutDesc); begin inherited Create; fWizard := _Wizard; fBindingIndex := -1; SetShortcut(_Shortcut); end; destructor TKeyboardNotifier.Destroy; begin Unregister; inherited; end; procedure TKeyboardNotifier.BindKeyboard(const BindingServices: IOTAKeyBindingServices); procedure RegisterHotkey(_Hotkey: array of TShortcut); begin BindingServices.AddKeyBinding(_Hotkey, KeyProc, nil, kfImplicitShift or kfImplicitModifier, '', ''); end; begin if fHotkey.Second <> #0 then RegisterHotkey([fHotkey.First, Ord(fHotkey.Second)]) else RegisterHotkey([fHotkey.First]); end; procedure TKeyboardNotifier.Unregister; var Idx: Integer; begin Idx := fBindingIndex; fBindingIndex := -1; if Idx <> -1 then Self.Unregister(Idx); end; procedure TKeyboardNotifier.Unregister(_Idx: Integer); begin (BorlandIDEServices as IOTAKeyboardServices).RemoveKeyboardBinding(_Idx); end; function TKeyboardNotifier.GetBindingType: TBindingType; begin Result := btPartial; end; procedure TKeyboardNotifier.KeyProc(const _Context: IOTAKeyContext; _KeyCode: TShortCut; var _BindingResult: TKeyBindingResult); begin fWizard.FormatCurrent(nil); _BindingResult := krHandled; end; function TKeyboardNotifier.GetDisplayName: string; begin Result := 'DelForExpert'; end; function TKeyboardNotifier.GetName: string; begin Result := fWizard.GetName; end; procedure TKeyboardNotifier.SetShortcut(_ShortCut: TShortCutDesc); var KeyboardServices: IOTAKeyboardServices; begin Unregister; fHotkey := _ShortCut; KeyboardServices := (BorlandIDEServices as IOTAKeyboardServices); fBindingIndex := KeyboardServices.AddKeyboardBinding(self); end; procedure Register; begin RegisterPackageWizard(TDelforExpert.Create); end; end.
unit uformlamwinosettingspaths; {$mode objfpc}{$H+} interface uses inifiles, Classes, SysUtils, FileUtil, LazFileUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Buttons, ExtCtrls, ComCtrls, LazIDEIntf {$IFDEF WINDOWS}, Registry {$ENDIF} ; type { TFormLamwinoSettingsPaths } TFormLamwinoSettingsPaths = class(TForm) BitBtnOK: TBitBtn; BitBtnCancel: TBitBtn; ComboBoxCOMPort: TComboBox; EditCodeTemplates: TEdit; EditPathToArduinoIDE: TEdit; Label1: TLabel; Label2: TLabel; LabelPathToArduinoIDE: TLabel; SelDirDlgPathToArduinoIDE: TSelectDirectoryDialog; SpBPathToArduinoIDE: TSpeedButton; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; StatusBar1: TStatusBar; procedure BitBtnOKClick(Sender: TObject); procedure BitBtnCancelClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormShow(Sender: TObject); procedure SpBPathToArduinoIDEClick(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); private { private declarations } FOk: boolean; public { public declarations } procedure LoadSettings(const fileName: string); procedure SaveSettings(const fileName: string); end; var FormLamwinoSettingsPaths: TFormLamwinoSettingsPaths; implementation {$R *.lfm} { TFormLamwinoSettingsPaths } procedure TFormLamwinoSettingsPaths.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin if FOk then Self.SaveSettings(LazarusIDE.GetPrimaryConfigPath + DirectorySeparator + 'AVRArduinoProject.ini' ); end; procedure TFormLamwinoSettingsPaths.FormShow(Sender: TObject); var strINI: TStringList; begin if not FileExists(LazarusIDE.GetPrimaryConfigPath + DirectorySeparator+ 'AVRArduinoProject.ini') then begin strINI:= TStringList.Create; strINI.SaveToFile(LazarusIDE.GetPrimaryConfigPath + DirectorySeparator+ 'AVRArduinoProject.ini'); strINI.Free; end; FOk:= False; Self.LoadSettings(LazarusIDE.GetPrimaryConfigPath + DirectorySeparator+ 'AVRArduinoProject.ini'); end; procedure TFormLamwinoSettingsPaths.FormActivate(Sender: TObject); begin EditPathToArduinoIDE.SetFocus; end; procedure TFormLamwinoSettingsPaths.BitBtnCancelClick(Sender: TObject); begin FOk:= False; Close; end; procedure TFormLamwinoSettingsPaths.BitBtnOKClick(Sender: TObject); begin FOk:= True; Close; end; procedure TFormLamwinoSettingsPaths.SpBPathToArduinoIDEClick(Sender: TObject); begin if SelDirDlgPathToArduinoIDE.Execute then begin EditPathToArduinoIDE.Text := SelDirDlgPathToArduinoIDE.FileName; end; end; //ref. http://forum.lazarus.freepascal.org/index.php?topic=14313.0 procedure TFormLamwinoSettingsPaths.SpeedButton1Click(Sender: TObject); var {$IFDEF WINDOWS} reg: TRegistry; l: TStringList; n: integer; {$ENDIF} res: string; begin //ShowMessage('Please, check if Arduino and PC are connecteds via USB!'); res:=''; ComboBoxCOMPort.Items.Clear; {$IFDEF WINDOWS} l:= TStringList.Create; reg:= TRegistry.Create; try {$IFNDEF VER100} reg.Access:= KEY_READ; {$ENDIF} reg.RootKey:= HKEY_LOCAL_MACHINE; reg.OpenKeyReadOnly('HARDWARE\DEVICEMAP\SERIALCOMM');//, false); reg.GetValueNames(l); for n:= 0 to l.Count - 1 do begin ComboBoxCOMPort.Items.Add(reg.ReadString(l[n])); end; finally reg.Free; l.Free; end; {$ENDIF} {$IFDEF LINUX} ShowMessage('Sorry... Not implemented yet...[LINUX]'); {$ENDIF} end; procedure TFormLamwinoSettingsPaths.SpeedButton2Click(Sender: TObject); begin if SelDirDlgPathToArduinoIDE.Execute then begin EditCodeTemplates.Text := SelDirDlgPathToArduinoIDE.FileName; end; end; procedure TFormLamwinoSettingsPaths.LoadSettings(const fileName: string); begin with TIniFile.Create(fileName) do try EditPathToArduinoIDE.Text := ReadString('NewProject','PathToArduinoIDE', ''); ComboBoxCOMPort.Text := ReadString('NewProject','COMPort', ''); EditCodeTemplates.Text:= ReadString('NewProject','PathToCodeTemplates', ''); finally Free; end; end; procedure TFormLamwinoSettingsPaths.SaveSettings(const fileName: string); begin with TInifile.Create(fileName) do try WriteString('NewProject', 'PathToArduinoIDE', EditPathToArduinoIDE.Text); WriteString('NewProject', 'COMPort', ComboBoxCOMPort.Text); WriteString('NewProject', 'PathToCodeTemplates', EditCodeTemplates.Text); finally Free; end; end; end.
unit GX_EditReader; {$I GX_CondDefine.inc} interface uses Classes, ToolsAPI; type TModuleMode = (mmModule, mmFile); type TEditReader = class(TObject) private FSourceInterfaceAllocated: Boolean; FModuleNotifier: IOTAModuleNotifier; FEditIntf: IOTASourceEditor; FEditRead: IOTAEditReader; FModIntf: IOTAModule; FNotifierIndex: Integer; Buf: PAnsiChar; FBufSize: Integer; FFileName: string; // FIsUTF8: Boolean; FMode: TModuleMode; SFile: TStream; procedure AllocateFileData; function GetLineCount: Integer; procedure SetBufSize(New: Integer); procedure InternalGotoLine(Line: Integer; Offset: Boolean); function ReadTextFromStream(Stream: TMemoryStream): string; protected procedure SetFileName(const Value: string); procedure ReleaseModuleNotifier; procedure SaveToStreamFromPos(Stream: TStream); procedure SaveToStreamToPos(Stream: TStream); procedure SaveToStream(Stream: TStream); public constructor Create(const FileName: string); destructor Destroy; override; procedure FreeFileData; procedure Reset; procedure GotoLine(L: Integer); procedure GotoOffsetLine(L: Integer); procedure ShowSource; procedure ShowForm; function GetText: string; function GetTextFromPos: string; function GetTextToPos: string; ///<summary> /// Returns the cursor position as offset into the editor buffer, /// that is into a possibly UTF-8 encoded buffer without expanding tabs </summary> function GetCurrentBufferPos: Integer; ///<symmary> /// Returns the cursor position in charcacter coordinates, that is without expanding tabs </summary> function GetCurrentCharPos: TOTACharPos; property BufSize: Integer read FBufSize write SetBufSize; property FileName: string read FFileName write SetFileName; property LineCount: Integer read GetLineCount; property Mode: TModuleMode read FMode; // property IsUTF8: Boolean read FIsUTF8; end; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} SysUtils, {$IFDEF GX_VER250_up} AnsiStrings, {$ENDIF GX_VER250_up} GX_GenericUtils, GX_OtaUtils, GX_IdeUtils, Math; type TModuleFreeNotifier = class(TNotifierObject, IOTAModuleNotifier) private FOwner: TEditReader; public constructor Create(Owner: TEditReader); destructor Destroy; override; procedure ModuleRenamed(const NewName: string); function CheckOverwrite: Boolean; end; { TModuleFreeNotifier } function TModuleFreeNotifier.CheckOverwrite: Boolean; begin Result := True; end; constructor TModuleFreeNotifier.Create(Owner: TEditReader); begin inherited Create; FOwner := Owner; end; destructor TModuleFreeNotifier.Destroy; begin Assert(FOwner <> nil); FOwner.FreeFileData; FOwner.FModuleNotifier := nil; inherited; end; procedure TModuleFreeNotifier.ModuleRenamed(const NewName: string); begin // We might want to handle this and change the stored file name end; resourcestring SNoEditReader = 'FEditRead: No editor reader interface (you have found a bug!)'; constructor TEditReader.Create(const FileName: string); begin inherited Create; FBufSize := 32760; // Large buffers are faster, but too large causes crashes FNotifierIndex := InvalidNotifierIndex; FMode := mmModule; if FileName <> '' then SetFileName(FileName); end; // Use the FreeFileData to release the references // to the internal editor buffer or the external // file on disk in order not to block the file // or track the editor (which may disappear) for // possibly extended periods of time. // // Calls to edit reader will always (re-)allocate // references again by calling the "AllocateFileData" // method, so calling "FreeFileData" essentially comes // for free, only reducing the length a reference // is held to an entity. procedure TEditReader.FreeFileData; begin FreeAndNil(SFile); FEditRead := nil; FEditIntf := nil; ReleaseModuleNotifier; FModIntf := nil; FSourceInterfaceAllocated := False; end; destructor TEditReader.Destroy; begin FreeFileData; {$IFDEF GX_VER250_up}AnsiStrings.{$ENDIF}StrDispose(Buf); Buf := nil; inherited Destroy; end; procedure TEditReader.AllocateFileData; resourcestring SFileDoesNotExist = 'File %s does not exist'; SNoEditorInterface = 'FEditRead: No editor interface'; SNoModuleNotifier = 'TEditReader: Could not get module notifier'; procedure AllocateFromDisk; var UnicodeBOM: Integer; Bytes: Integer; FileStream: TFileStream; begin if not FileExists(FFileName) then raise Exception.CreateFmt(SFileDoesNotExist, [FFileName]); FMode := mmFile; FileStream := TFileStream.Create(FFileName, fmOpenRead or fmShareDenyWrite); try Bytes := FileStream.Read(UnicodeBOM, 3); // This does not support other encodings such as UCS-2, UCS-4, etc. // but according to a poll I did on Google+, nobody uses these anyway. // So we just support ANSI and UTF-8 and hope for the best. // -- 2015-06-10 twm if (Bytes = 3) and ((UnicodeBOM and $00FFFFFF) = $00BFBBEF) then // FIsUTF8 := true else FileStream.Seek(0, soFromBeginning); SFile := TMemoryStream.Create; SFile.CopyFrom(FileStream, FileStream.Size - FileStream.Position); finally FileStream.Free; end; end; begin if FSourceInterfaceAllocated then Exit; if BorlandIDEServices = nil then begin AllocateFromDisk; Exit; end; // Get module interface Assert(FModIntf = nil); FModIntf := GxOtaGetModule(FFileName); if FModIntf = nil then begin {$IFOPT D+} SendDebug('EditReader: Module not open in the IDE - opening "' + FFilename + '" from disk'); {$ENDIF} AllocateFromDisk; end else begin FMode := mmModule; {$IFOPT D+} SendDebug('EditReader: Got module for ' + FFileName); {$ENDIF} // FIsUTF8 := RunningDelphi8OrGreater; // Delphi 8+ convert all edit buffers to UTF-8 // Allocate notifier for module Assert(FModuleNotifier = nil); FModuleNotifier := TModuleFreeNotifier.Create(Self); {$IFOPT D+} SendDebug('EditReader: Got FModuleNotifier'); {$ENDIF} if FModuleNotifier = nil then begin FModIntf := nil; raise Exception.Create(SNoModuleNotifier); end; FNotifierIndex := FModIntf.AddNotifier(FModuleNotifier); // Get Editor Interface Assert(FEditIntf = nil); FEditIntf := GxOtaGetSourceEditorFromModule(FModIntf, FFileName); {$IFOPT D+} SendDebug('EditReader: Got FEditIntf for module'); {$ENDIF} if FEditIntf = nil then begin ReleaseModuleNotifier; FModIntf := nil; if FileExists(FFileName) then AllocateFromDisk else raise Exception.Create(SNoEditorInterface); // Should we call FreeFileData? Exit; end; // Get Reader interface } Assert(FEditRead = nil); FEditRead := FEditIntf.CreateReader; if FEditRead = nil then begin ReleaseModuleNotifier; FModIntf := nil; FEditIntf := nil; raise Exception.Create(SNoEditReader); end; end; FSourceInterfaceAllocated := True; end; procedure TEditReader.SetFileName(const Value: string); begin if SameText(Value, FFileName) then Exit; FreeFileData; // Assigning an empty string clears allocation. if Value = '' then Exit; FFileName := Value; Reset; end; procedure TEditReader.SetBufSize(New: Integer); begin if (Buf = nil) and (New <> FBufSize) then FBufSize := New; // 32K is the max we can read from an edit reader at once Assert(FBufSize <= 1024 * 32); end; procedure TEditReader.ShowSource; begin AllocateFileData; Assert(Assigned(FEditIntf)); if FMode = mmModule then begin if RunningDelphi8OrGreater then begin // This prevents .aspx editor flickering in Delphi 2005+ if (GxOtaGetTopMostEditBufferFileName <> FFileName) then FEditIntf.Show; end else FEditIntf.Show; end; end; procedure TEditReader.ShowForm; begin AllocateFileData; Assert(Assigned(FModIntf)); if FMode = mmModule then GxOtaShowFormForModule(FModIntf); end; procedure TEditReader.GotoLine(L: Integer); begin InternalGotoLine(L, False); end; procedure TEditReader.GotoOffsetLine(L: Integer); begin InternalGotoLine(L, True); end; procedure TEditReader.InternalGotoLine(Line: Integer; Offset: Boolean); var EditView: IOTAEditView; EditPos: TOTAEditPos; S: Integer; ViewCount: Integer; begin AllocateFileData; //{$IFOPT D+} SendDebug('LineCount ' + IntToStr(LineCount)); {$ENDIF} if Line > LineCount then Exit; if Line < 1 then Line := 1; Assert(FModIntf <> nil); ShowSource; Assert(FEditIntf <> nil); ViewCount := FEditIntf.EditViewCount; if ViewCount < 1 then Exit; EditView := FEditIntf.EditViews[0]; if EditView <> nil then begin EditPos.Col := 1; EditPos.Line := Line; if Offset then begin EditView.CursorPos := EditPos; S := Line - (EditView.ViewSize.cy div 2); if S < 1 then S := 1; EditPos.Line := S; EditView.TopPos := EditPos; end else begin EditView.TopPos := EditPos; EditView.CursorPos := EditPos; ShowSource; end; EditView.Paint; end; end; function TEditReader.GetLineCount: Integer; begin if FMode = mmModule then begin AllocateFileData; Assert(FEditIntf <> nil); Result := FEditIntf.GetLinesInBuffer; end else Result := -1; end; function TEditReader.ReadTextFromStream(Stream: TMemoryStream): string; var Buffer: IDEEditBufferString; begin SetLength(Buffer, Stream.Size); Stream.Position := 0; Stream.ReadBuffer(Buffer[1], Stream.Size); // In theory we could rely on UTF-8 having a BOM, meaning that // every file not containing a BOM is ANSI. Unfortunately this // turns out to be unreliable, so we assume everything to be // UTF-8, try to convert it to ANSI. // There are four possible cases: // 1) If it is ANSI and does not contain any high ASCII charactes the // conversion will do nothing // 2) If it is UTF-8, the conversion will work fine // 3) If it is ANSI with high ASCII charactes, the conversion will fail // and return an empty string. In this case we take the string as is. // 4) If it is neither valid UTF-8 nor ANSI, the conversion will fail // and return an empty string. In this case we still take the string // as is and hope for the best. // If this is a non-unicode version of Delphi, all files should be ANSI anyway // UTF8ToUnicodeString does nothing. // -- 2015-06-14 twm Result := UTF8ToUnicodeString(Buffer); if (Result = '') and (Buffer <> '') then begin Result := String(Buffer); end; end; function TEditReader.GetText: string; var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try SaveToStream(Stream); Result := ReadTextFromStream(Stream); finally Stream.Free; end; end; function TEditReader.GetTextFromPos: string; var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try SaveToStreamFromPos(Stream); Result := ReadTextFromStream(Stream); finally Stream.Free; end; end; function TEditReader.GetTextToPos: string; var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try SaveToStreamToPos(Stream); Result := ReadTextFromStream(Stream); finally Stream.Free; end; end; procedure TEditReader.Reset; begin if FMode = mmFile then begin // We do not need to allocate file data // in order to set the stream position if SFile <> nil then SFile.Position := 0; end; end; procedure TEditReader.SaveToStream(Stream: TStream); var Pos: Integer; Size: Integer; const TheEnd: Char = #0; // Leave typed constant as is - needed for streaming code begin Assert(Stream <> nil); Reset; AllocateFileData; if Mode = mmFile then begin Assert(SFile <> nil); SFile.Position := 0; Stream.CopyFrom(SFile, SFile.Size); end else begin Pos := 0; if Buf = nil then Buf := AnsiStrAlloc(BufSize + 1); if FEditRead = nil then raise Exception.Create(SNoEditReader); // Delphi 5+ sometimes returns -1 here, for an unknown reason Size := FEditRead.GetText(Pos, Buf, BufSize); if Size = -1 then begin FreeFileData; AllocateFileData; Size := FEditRead.GetText(Pos, Buf, BufSize); end; if Size > 0 then begin Pos := Pos + Size; while Size = BufSize do begin Stream.Write(Buf^, Size); Size := FEditRead.GetText(Pos, Buf, BufSize); Pos := Pos + Size; end; Stream.Write(Buf^, Size); end; end; Stream.Write(TheEnd, 1); end; function TEditReader.GetCurrentBufferPos: Integer; var EditorPos: TOTAEditPos; CharPos: TOTACharPos; EditView: IOTAEditView; begin AllocateFileData; Assert(FEditIntf <> nil); Result := -1; Assert(FEditIntf.EditViewCount > 0); EditView := FEditIntf.EditViews[0]; if EditView <> nil then begin EditorPos := EditView.CursorPos; EditView.ConvertPos(True, EditorPos, CharPos); Result := EditView.CharPosToPos(CharPos); end; end; function TEditReader.GetCurrentCharPos: TOTACharPos; var EditorPos: TOTAEditPos; EditView: IOTAEditView; begin AllocateFileData; Assert(FEditIntf <> nil); Result.CharIndex := -1; Result.Line := -1; Assert(FEditIntf.EditViewCount > 0); EditView := FEditIntf.EditViews[0]; if EditView <> nil then begin EditorPos := EditView.CursorPos; EditView.ConvertPos(True, EditorPos, Result); end; end; procedure TEditReader.SaveToStreamFromPos(Stream: TStream); var Pos: Integer; Size: Integer; begin AllocateFileData; Reset; if Mode = mmFile then begin Assert(SFile <> nil); SFile.Position := 0; Stream.CopyFrom(SFile, SFile.Size); end else begin Pos := GetCurrentBufferPos; if Buf = nil then Buf := AnsiStrAlloc(BufSize); if FEditRead = nil then raise Exception.Create(SNoEditReader); Size := FEditRead.GetText(Pos, Buf, BufSize); if Size > 0 then begin Pos := Pos + Size; while Size = BufSize do begin Stream.Write(Buf^, Size); Size := FEditRead.GetText(Pos, Buf, BufSize); Pos := Pos + Size; end; Stream.Write(Buf^, Size); end; end; end; // The character at the current position is not written to the stream procedure TEditReader.SaveToStreamToPos(Stream: TStream); var Pos, AfterPos: Integer; ToReadSize, Size: Integer; NullChar: Char; begin AllocateFileData; Reset; if Mode = mmFile then begin Assert(SFile <> nil); SFile.Position := 0; Stream.CopyFrom(SFile, SFile.Size); end else begin AfterPos := GetCurrentBufferPos; Pos := 0; if Buf = nil then Buf := AnsiStrAlloc(BufSize); if FEditRead = nil then raise Exception.Create(SNoEditReader); ToReadSize := Min(BufSize, AfterPos - Pos); Size := FEditRead.GetText(Pos, Buf, ToReadSize); if Size > 0 then begin Pos := Pos + Size; while Size = BufSize do begin Stream.Write(Buf^, Size); ToReadSize := Min(BufSize, AfterPos - Pos); Size := FEditRead.GetText(Pos, Buf, ToReadSize); Pos := Pos + Size; end; Stream.Write(Buf^, Size); end; end; NullChar := #0; Stream.Write(NullChar, SizeOf(NullChar)); end; procedure TEditReader.ReleaseModuleNotifier; begin if FNotifierIndex <> InvalidNotifierIndex then FModIntf.RemoveNotifier(FNotifierIndex); FNotifierIndex := InvalidNotifierIndex; FModuleNotifier := nil; end; end.
unit Station; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ObjectID; type TStation = object(TObjWithID) Private name:string; SWayNum:integer; x:integer; y:integer; isvisited:boolean; Coefficient:integer; Public Procedure SetName(s:string); Function GetName:string; Procedure SetXCoord(i:integer); Function GetXCoord:integer; Procedure SetYCoord(i:integer); Function GetYCoord:integer; Procedure AddSWay; Function NumSWays:integer; // Testing Procedure SetVisited(b:boolean); Function GetVisited:boolean; Function CheckSWays:boolean; Procedure SetCoefficient(i:integer); Function GetCoefficient:integer; Public Constructor Create; Destructor Done; end; implementation Procedure TStation.SetName(s:string); Begin Name:=s; end; Function TStation.GetName:string; begin GetName:=name; end; Procedure TStation.SetXCoord(i:integer); begin x:=i; end; Function TStation.GetXCoord:integer; begin GetXCoord:=x; end; Procedure TStation.SetYCoord(i:integer); begin y:=i; end; Function TStation.GetYCoord:integer; begin GetYCoord:=y; end; Procedure TStation.AddSWay; begin SWayNum:=SWayNum+1; end; Function TStation.NumSWays:integer; // FOR TEST. TESTING begin NumSWays:=SWayNum; end; Function TStation.CheckSWays:boolean; begin CheckSWays:=true; if SWayNum>=2 then CheckSWays:=false; end; Procedure TStation.SetVisited(b:boolean); begin isVisited:=b; end; Function TStation.GetVisited:boolean; begin GetVisited:=isVisited; end; Procedure TStation.SetCoefficient(i:integer); begin Coefficient:=i; end; Function TStation.GetCoefficient:integer; begin GetCoefficient:=Coefficient; end; Constructor TStation.Create; begin Name:=''; SWayNum:=0; x:=0; y:=0; Coefficient:=32767; end; Destructor TStation.Done; begin end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clMultiDC; interface {$I clVer.inc} {$IFDEF DELPHIXE2} {$WARN SYMBOL_PLATFORM OFF} {$ENDIF} uses {$IFNDEF DELPHIXE2} Classes, Windows, {$ELSE} System.Classes, Winapi.Windows, System.Types, {$ENDIF} clWinInet, clDC, clDCUtils, clUtils, clInternetConnection, clHttpRequest, clCryptApi, clCertificate, clSspiTls, clFtpUtils, clHttpUtils, clUriUtils, clWUtils, clResourceState; type TclInternetItem = class; TclOnMultiStatusChanged = procedure (Sender: TObject; Item: TclInternetItem; Status: TclProcessStatus) of object; TclOnMultiDataItemProceed = procedure (Sender: TObject; Item: TclInternetItem; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer) of object; TclOnMultiError = procedure (Sender: TObject; Item: TclInternetItem; const Error: string; ErrorCode: Integer) of object; TclOnMultiGetResourceInfo = procedure (Sender: TObject; Item: TclInternetItem; ResourceInfo: TclResourceInfo) of object; TclOnMultiURLParsing = procedure (Sender: TObject; Item: TclInternetItem; var URLComponents: TURLComponents) of object; TclOnMultiNotifyEvent = procedure (Sender: TObject; Item: TclInternetItem) of object; TclOnMultiGetCertificate = procedure (Sender: TObject; Item: TclInternetItem; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean) of object; TclCustomInternetControl = class; TclInternetItem = class(TCollectionItem) private FDataStream: TStream; FSelfDataStream: TStream; FThreaderList: TList; FPassword: string; FUserName: string; FURL: string; FLastStatus: TclProcessStatus; FPriority: TclProcessPriority; FResourceInfo: TclResourceInfo; FErrors: TclErrorList; FCertificateFlags: TclCertificateVerifyFlags; FThreadCount: Integer; FResourceState: TclResourceStateList; FKeepConnection: Boolean; FSelfConnection: TclInternetConnection; FData: Pointer; FHttpRequest: TclHttpRequest; FUseHttpRequest: Boolean; FHttpResponseHeader: TStrings; FPort: Integer; FIsCommit: Boolean; procedure DoOnResourceStateChanged(Sender: TObject); procedure DoOnURLParsing(Sender: TObject; var URLComponents: TURLComponents); procedure DoOnGetResourceInfo(Sender: TObject; AResourceInfo: TclResourceInfo); procedure DoOnDataItemProceed(Sender: TObject; AResourceInfo: TclResourceInfo; BytesProceed: Int64; CurrentData: PclChar; CurrentDataSize: Integer); procedure DoOnError(Sender: TObject; const Error: string; ErrorCode: Integer); procedure DoOnStatusChanged(Sender: TObject; Status: TclProcessStatus); procedure DoOnTerminate(Sender: TObject); procedure DoOnGetCertificate(Sender: TObject; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); procedure ClearInfo; procedure ClearDataStream; procedure ClearThreaderList; procedure SetDataStream(const Value: TStream); function GetInternalDataStream: TStream; function GetIsBusy: Boolean; procedure Wait; procedure RemoveThreader(Index: Integer); procedure SetMaxConnectionsOption; procedure SetThreadCount(const Value: Integer); function GetConnection: TclInternetConnection; function FindFirstFailedItem(APrevThreader: TclCustomThreader): TclResourceStateItem; procedure ReTryFailedItem(AStateItem: TclResourceStateItem; AURLParser: TclUrlParser); procedure SetHttpRequest(const Value: TclHttpRequest); function GetResourceConnections(Index: Integer): TclInternetConnection; function GetResourceConnectionCount: Integer; procedure AssignThreader(AThreader: TclCustomThreader); protected FLocalFile: string; procedure InternalSetHttpRequest(const Value: TclHttpRequest); function IsSharedConnection: Boolean; function FindStateItem(AThreader: TclCustomThreader): TclResourceStateItem; procedure DoError(const Error: string; ErrorCode: Integer); function GetBatchSize: Integer; function GetDefaultChar: Char; procedure ClearResourceState; function AddThreader(AStateItem: TclResourceStateItem; AIsGetResourceInfo: Boolean): TclCustomThreader; function CanProcess: Boolean; virtual; function CheckSizeValid(ASize: Int64): Boolean; procedure AssignThreaderEvents(AThreader: TclCustomThreader); virtual; procedure AssignThreaderParams(AThreader: TclCustomThreader); virtual; function GetControl: TclCustomInternetControl; virtual; abstract; function GetDataStream: TStream; virtual; abstract; function CreateThreader(ADataStream: TStream; AIsGetResourceInfo: Boolean): TclCustomThreader; virtual; abstract; procedure InternalStart(AIsGetResourceInfo: Boolean); virtual; procedure SetLocalFile(const Value: string); virtual; procedure SetPassword(const Value: string); virtual; procedure SetURL(const Value: string); virtual; procedure SetUserName(const Value: string); virtual; procedure SetPort(const Value: Integer); virtual; procedure ThreaderTerminated(AThreader: TclCustomThreader); virtual; procedure ProcessCompleted(AThreader: TclCustomThreader); virtual; procedure LastStatusChanged(Status: TclProcessStatus); virtual; procedure DoGetResourceInfo(AResourceInfo: TclResourceInfo); virtual; procedure ControlChanged; virtual; procedure SetInternalDataStream(const ADataStream: TStream); procedure CommitWork; virtual; procedure DoCreate; virtual; procedure DoDestroy; virtual; procedure SetUseHttpRequest(const Value: Boolean); virtual; property IsCommit: Boolean read FIsCommit; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Start(IsAsynch: Boolean); function GetResourceInfo(IsAsynch: Boolean): TclResourceInfo; procedure Stop; procedure CloseConnection; procedure DeleteRemoteFile; function GetThreader(Index: Integer): TclCustomThreader; property DataStream: TStream read GetInternalDataStream write SetDataStream; property IsBusy: Boolean read GetIsBusy; property Control: TclCustomInternetControl read GetControl; property Errors: TclErrorList read FErrors; property ResourceInfo: TclResourceInfo read FResourceInfo; property ResourceState: TclResourceStateList read FResourceState; property ResourceConnections[Index: Integer]: TclInternetConnection read GetResourceConnections; property ResourceConnectionCount: Integer read GetResourceConnectionCount; property Data: Pointer read FData write FData; published property ThreadCount: Integer read FThreadCount write SetThreadCount default DefaultThreadCount; property KeepConnection: Boolean read FKeepConnection write FKeepConnection default False; property URL: string read FURL write SetURL; property LocalFile: string read FLocalFile write SetLocalFile; property UserName: string read FUserName write SetUserName; property Password: string read FPassword write SetPassword; property Port: Integer read FPort write SetPort default 0; property Priority: TclProcessPriority read FPriority write FPriority default ppNormal; property CertificateFlags: TclCertificateVerifyFlags read FCertificateFlags write FCertificateFlags default []; property HttpRequest: TclHttpRequest read FHttpRequest write SetHttpRequest; property HttpResponseHeader: TStrings read FHttpResponseHeader; property UseHttpRequest: Boolean read FUseHttpRequest write SetUseHttpRequest default False; end; TclInternetItemClass = class of TclInternetItem; TclControlNotifier = class private FControl: TclCustomInternetControl; protected procedure DoResourceStateChanged(Item: TclInternetItem); virtual; procedure DoStatusChanged(Item: TclInternetItem; Status: TclProcessStatus); virtual; procedure DoDataItemProceed(Item: TclInternetItem; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer); virtual; procedure DoItemDeleted(Item: TclInternetItem); virtual; public constructor Create(AControl: TclCustomInternetControl); destructor Destroy; override; end; TclCustomInternetControl = class(TComponent) private FIsBusyCount: Integer; FTryCount: Integer; FBatchSize: Integer; FTimeOut: Integer; FOnIsBusyChanged: TNotifyEvent; FMinResourceSize: Int64; FMaxResourceSize: Int64; FProxyBypass: TStrings; FInternetAgent: string; FDefaultChar: Char; FPassiveFTPMode: Boolean; FNotifierList: TList; FReconnectAfter: Integer; FConnection: TclInternetConnection; FDoNotGetResourceInfo: Boolean; FFtpProxySettings: TclFtpProxySettings; FHttpProxySettings: TclHttpProxySettings; FUseInternetErrorDialog: Boolean; procedure SetBatchSize(const Value: Integer); procedure SetTryCount(const Value: Integer); procedure SetTimeOut(const Value: Integer); procedure SetReconnectAfter(const Value: Integer); function GetIsBusy: Boolean; procedure SetMaxResourceSize(const Value: Int64); procedure SetMinResourceSize(const Value: Int64); procedure SetDefaultChar(const Value: Char); function GetControlNotifier(Index: Integer): TclControlNotifier; procedure RegisterControlNotifier(ANotifier: TclControlNotifier); procedure UnregisterControlNotifier(ANotifier: TclControlNotifier); procedure SetConnection(const Value: TclInternetConnection); procedure SetFtpProxySettings(const Value: TclFtpProxySettings); procedure SetHttpProxySettings(const Value: TclHttpProxySettings); procedure SetProxyBypass(const Value: TStrings); protected procedure BeginIsBusy; procedure EndIsBusy; procedure DoStopItem(Item: TclInternetItem); virtual; procedure DoItemCreated(Item: TclInternetItem); virtual; procedure DoItemDeleted(Item: TclInternetItem); virtual; function CanProcess(Item: TclInternetItem): Boolean; virtual; procedure StartNextItem(APrevItem: TclInternetItem); virtual; function CanStartItem(Item: TclInternetItem; AIsGetResourceInfo, IsAsynch: Boolean): Boolean; virtual; procedure NotifyInternetItems(AComponent: TComponent); virtual; abstract; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Loaded; override; procedure IsBusyChanged; dynamic; procedure Changed(Item: TclInternetItem); dynamic; procedure DoResourceStateChanged(Item: TclInternetItem); dynamic; procedure DoGetCertificate(Item: TclInternetItem; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); dynamic; procedure DoURLParsing(Item: TclInternetItem; var URLComponents: TURLComponents); dynamic; procedure DoGetResourceInfo(Item: TclInternetItem; AResourceInfo: TclResourceInfo); dynamic; procedure DoStatusChanged(Item: TclInternetItem; Status: TclProcessStatus); dynamic; procedure DoDataItemProceed(Item: TclInternetItem; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer); dynamic; procedure DoError(Item: TclInternetItem; const Error: string; ErrorCode: Integer); dynamic; procedure DoProcessCompleted(Item: TclInternetItem); dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property IsBusy: Boolean read GetIsBusy; procedure ReadRegistry(const APath: string); virtual; procedure WriteRegistry(const APath: string); virtual; procedure GetFtpDirList(const ADir, AUser, APassword: string; AList: TStrings; ADetails: Boolean); class procedure SetCookie(const AURL, AName, AValue: string); class function GetCookie(const AURL, AName: string): string; class procedure GetAllCookies(const AURL: string; AList: TStrings); class procedure FlushIESession; class procedure EnumIECacheEntries(AList: TStrings); class procedure GetIECacheEntryHeader(const AUrl: string; AList: TStrings); class procedure GetIECacheFile(const AUrl: string; AStream: TStream); published property TryCount: Integer read FTryCount write SetTryCount default DefaultTryCount; property BatchSize: Integer read FBatchSize write SetBatchSize default DefaultBatchSize; property TimeOut: Integer read FTimeOut write SetTimeOut default DefaultTimeOut; property ReconnectAfter: Integer read FReconnectAfter write SetReconnectAfter default DefaultTimeOut; property MinResourceSize: Int64 read FMinResourceSize write SetMinResourceSize default 0; property MaxResourceSize: Int64 read FMaxResourceSize write SetMaxResourceSize default 0; property HttpProxySettings: TclHttpProxySettings read FHttpProxySettings write SetHttpProxySettings; property FtpProxySettings: TclFtpProxySettings read FFtpProxySettings write SetFtpProxySettings; property ProxyBypass: TStrings read FProxyBypass write SetProxyBypass; property InternetAgent: string read FInternetAgent write FInternetAgent; property DefaultChar: Char read FDefaultChar write SetDefaultChar default DefaultPreviewChar; property PassiveFTPMode: Boolean read FPassiveFTPMode write FPassiveFTPMode default False; property Connection: TclInternetConnection read FConnection write SetConnection; property DoNotGetResourceInfo: Boolean read FDoNotGetResourceInfo write FDoNotGetResourceInfo default False; property UseInternetErrorDialog: Boolean read FUseInternetErrorDialog write FUseInternetErrorDialog default False; property OnIsBusyChanged: TNotifyEvent read FOnIsBusyChanged write FOnIsBusyChanged; end; TclMultiInternetControl = class(TclCustomInternetControl) private FDelayedItems: TList; FMaxStartedItems: Integer; FStartedItemCount: Integer; FOnDataItemProceed: TclOnMultiDataItemProceed; FOnError: TclOnMultiError; FOnGetResourceInfo: TclOnMultiGetResourceInfo; FOnChanged: TclOnMultiNotifyEvent; FOnStatusChanged: TclOnMultiStatusChanged; FOnUrlParsing: TclOnMultiURLParsing; FOnGetCertificate: TclOnMultiGetCertificate; FOnProcessCompleted: TclOnMultiNotifyEvent; FOnItemDeleted: TclOnMultiNotifyEvent; FOnItemCreated: TclOnMultiNotifyEvent; procedure SetMaxStartedItems(const Value: Integer); procedure DeleteDelayedInfo(Item: TclInternetItem); protected procedure InternalStop(Item: TclInternetItem); virtual; procedure NotifyInternetItems(AComponent: TComponent); override; procedure Changed(Item: TclInternetItem); override; procedure DoGetCertificate(Item: TclInternetItem; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); override; procedure DoURLParsing(Item: TclInternetItem; var URLComponents: TURLComponents); override; procedure DoGetResourceInfo(Item: TclInternetItem; AResourceInfo: TclResourceInfo); override; procedure DoStatusChanged(Item: TclInternetItem; Status: TclProcessStatus); override; procedure DoDataItemProceed(Item: TclInternetItem; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer); override; procedure DoError(Item: TclInternetItem; const Error: string; ErrorCode: Integer); override; procedure DoProcessCompleted(Item: TclInternetItem); override; procedure DoStopItem(Item: TclInternetItem); override; procedure DoItemCreated(Item: TclInternetItem); override; procedure DoItemDeleted(Item: TclInternetItem); override; procedure StartNextItem(APrevItem: TclInternetItem); override; function CanStartItem(Item: TclInternetItem; AIsGetResourceInfo, IsAsynch: Boolean): Boolean; override; function GetInternetItems(Index: Integer): TclInternetItem; virtual; abstract; function GetInternetItemsCount: Integer; virtual; abstract; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetResourceInfo(Item: TclInternetItem = nil; IsAsynch: Boolean = True): TclResourceInfo; procedure Start(Item: TclInternetItem = nil; IsAsynch: Boolean = True); procedure Stop(Item: TclInternetItem = nil); published property MaxStartedItems: Integer read FMaxStartedItems write SetMaxStartedItems default 5; property OnStatusChanged: TclOnMultiStatusChanged read FOnStatusChanged write FOnStatusChanged; property OnGetResourceInfo: TclOnMultiGetResourceInfo read FOnGetResourceInfo write FOnGetResourceInfo; property OnDataItemProceed: TclOnMultiDataItemProceed read FOnDataItemProceed write FOnDataItemProceed; property OnError: TclOnMultiError read FOnError write FOnError; property OnUrlParsing: TclOnMultiURLParsing read FOnUrlParsing write FOnUrlParsing; property OnChanged: TclOnMultiNotifyEvent read FOnChanged write FOnChanged; property OnGetCertificate: TclOnMultiGetCertificate read FOnGetCertificate write FOnGetCertificate; property OnProcessCompleted: TclOnMultiNotifyEvent read FOnProcessCompleted write FOnProcessCompleted; property OnItemCreated: TclOnMultiNotifyEvent read FOnItemCreated write FOnItemCreated; property OnItemDeleted: TclOnMultiNotifyEvent read FOnItemDeleted write FOnItemDeleted; end; const cProcessPriorities: array[TclProcessPriority] of TThreadPriority = (tpLower, tpNormal, tpHigher); implementation uses {$IFNDEF DELPHIXE2} Registry{$IFDEF DEMO}, Forms{$ENDIF}, SysUtils{$IFDEF LOGGER}, clLogger{$ENDIF}; {$ELSE} System.Win.Registry{$IFDEF DEMO}, Vcl.Forms{$ENDIF}, System.SysUtils{$IFDEF LOGGER}, clLogger{$ENDIF}; {$ENDIF} type TclThreaderHolder = class public FThreader: TclCustomThreader; FStateItem: TclResourceStateItem; end; TclInternetItemInfo = class public FItem: TclInternetItem; FIsGetResourceInfo: Boolean; end; { TclInternetItem } procedure TclInternetItem.Assign(Source: TPersistent); var Item: TclInternetItem; begin if (Source is TclInternetItem) then begin Item := (Source as TclInternetItem); DataStream := Item.DataStream; FThreadCount := Item.ThreadCount; FKeepConnection := Item.KeepConnection; FURL := Item.URL; FUserName := Item.UserName; FLocalFile := Item.LocalFile; FPassword := Item.Password; FPriority := Item.Priority; FCertificateFlags := Item.CertificateFlags; FUseHttpRequest := Item.UseHttpRequest; FData := Item.Data; HttpRequest := Item.HttpRequest; ControlChanged(); end else begin inherited Assign(Source); end; end; procedure TclInternetItem.AssignThreaderEvents(AThreader: TclCustomThreader); begin AThreader.OnGetResourceInfo := DoOnGetResourceInfo; AThreader.OnStatusChanged := DoOnStatusChanged; AThreader.OnError := DoOnError; AThreader.OnTerminate := DoOnTerminate; AThreader.OnUrlParsing := DoOnURLParsing; AThreader.OnDataItemProceed := DoOnDataItemProceed; AThreader.OnGetCertificate := DoOnGetCertificate; end; procedure TclInternetItem.AssignThreaderParams(AThreader: TclCustomThreader); begin if (HttpRequest <> nil) then begin AThreader.RequestHeader := HttpRequest.HeaderSource; end; AThreader.Priority := cProcessPriorities[FPriority]; AThreader.BatchSize := Control.BatchSize; AThreader.TryCount := Control.TryCount; AThreader.TimeOut := Control.TimeOut; AThreader.ReconnectAfter := Control.ReconnectAfter; AThreader.FreeOnTerminate := True; AThreader.CertificateFlags := FCertificateFlags; AThreader.UseInternetErrorDialog := Control.UseInternetErrorDialog; AThreader.HttpProxySettings := Control.HttpProxySettings; AThreader.FtpProxySettings := Control.FtpProxySettings; AThreader.ProxyBypass := StringReplace(Trim(Control.ProxyBypass.Text), #13#10, #32, [rfReplaceAll]); AThreader.InternetAgent := Control.InternetAgent; AThreader.PassiveFTPMode := Control.PassiveFTPMode; AThreader.KeepConnection := KeepConnection; AThreader.DoNotGetResourceInfo := Control.DoNotGetResourceInfo; if IsSharedConnection() then begin AThreader.Connection := GetConnection(); end; end; procedure TclInternetItem.AssignThreader(AThreader: TclCustomThreader); begin AssignThreaderEvents(AThreader); AssignThreaderParams(AThreader); end; function TclInternetItem.IsSharedConnection: Boolean; begin Result := ((Control <> nil) and (Control.Connection <> nil)) or KeepConnection; end; function TclInternetItem.GetConnection(): TclInternetConnection; begin if (Control <> nil) and (Control.Connection <> nil) then begin Result := Control.Connection; FreeAndNil(FSelfConnection); end else begin if (FSelfConnection = nil) then begin FSelfConnection := TclInternetConnection.Create(nil); end; Result := FSelfConnection; end; end; procedure TclInternetItem.ClearInfo(); begin FreeAndNil(FResourceInfo); end; constructor TclInternetItem.Create(Collection: TCollection); begin inherited Create(Collection); DoCreate(); Control.DoItemCreated(Self); end; destructor TclInternetItem.Destroy; begin if IsBusy then begin Stop(); Wait(); end; Control.DoItemDeleted(Self); DoDestroy(); inherited Destroy(); end; procedure TclInternetItem.ClearThreaderList(); begin while (FThreaderList.Count > 0) do begin RemoveThreader(0); end; end; procedure TclInternetItem.Wait(); begin while (FThreaderList.Count > 0) do begin GetThreader(0).Wait(); end; end; procedure TclInternetItem.DoOnDataItemProceed(Sender: TObject; AResourceInfo: TclResourceInfo; BytesProceed: Int64; CurrentData: PclChar; CurrentDataSize: Integer); var StateItem: TclResourceStateItem; begin StateItem := FindStateItem(Sender as TclCustomThreader); ResourceState.UpdateProceed(StateItem, BytesProceed - StateItem.ResourcePos); Control.DoDataItemProceed(Self, AResourceInfo, StateItem, CurrentData, CurrentDataSize); end; procedure TclInternetItem.DoError(const Error: string; ErrorCode: Integer); begin FErrors.AddError(Error, ErrorCode); Control.DoError(Self, Error, ErrorCode); end; procedure TclInternetItem.DoOnError(Sender: TObject; const Error: string; ErrorCode: Integer); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'DoOnError');{$ENDIF} DoError(Error, ErrorCode); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'DoOnError'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'DoOnError', E); raise; end; end;{$ENDIF} end; procedure TclInternetItem.DoOnGetResourceInfo(Sender: TObject; AResourceInfo: TclResourceInfo); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'DoOnGetResourceInfo');{$ENDIF} DoGetResourceInfo(AResourceInfo); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'DoOnGetResourceInfo'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'DoOnGetResourceInfo', E); raise; end; end;{$ENDIF} end; procedure TclInternetItem.DoOnStatusChanged(Sender: TObject; Status: TclProcessStatus); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'DoOnStatusChanged');{$ENDIF} ResourceState.UpdateStatus(FindStateItem(Sender as TclCustomThreader), Status); LastStatusChanged(ResourceState.LastStatus); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'DoOnStatusChanged: %d', nil, [Integer(Status)]); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'DoOnStatusChanged: %d', E, [Integer(Status)]); raise; end; end;{$ENDIF} end; procedure TclInternetItem.DoGetResourceInfo(AResourceInfo: TclResourceInfo); begin ClearInfo(); if (AResourceInfo <> nil) then begin FResourceInfo := TclResourceInfo.Create(); FResourceInfo.Assign(AResourceInfo); end; Control.DoGetResourceInfo(Self, FResourceInfo); end; function TclInternetItem.GetThreader(Index: Integer): TclCustomThreader; begin Result := TclThreaderHolder(FThreaderList[Index]).FThreader; end; procedure TclInternetItem.RemoveThreader(Index: Integer); begin TclThreaderHolder(FThreaderList[Index]).Free(); FThreaderList.Delete(Index); end; procedure TclInternetItem.ThreaderTerminated(AThreader: TclCustomThreader); var i: Integer; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'ThreaderTerminated');{$ENDIF} if (AThreader.Status <> psFailed) and (ResourceState.LastStatus <> psTerminated) then begin ReTryFailedItem(FindFirstFailedItem(AThreader), AThreader.URLParser); end; for i := 0 to FThreaderList.Count - 1 do begin if (GetThreader(i) = AThreader) then begin RemoveThreader(i); Break; end; end; if (FThreaderList.Count = 0) then begin ProcessCompleted(AThreader); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'ThreaderTerminated'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'ThreaderTerminated', E); raise; end; end;{$ENDIF} end; procedure TclInternetItem.ReTryFailedItem(AStateItem: TclResourceStateItem; AURLParser: TclUrlParser); var Threader: TclCustomThreader; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'ReTryFailedItem');{$ENDIF} if (AStateItem = nil) then Exit; Threader := AddThreader(AStateItem, False); Threader.ResourceInfo := ResourceInfo; Threader.URLParser := AURLParser; Threader.Perform(); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'ReTryFailedItem'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'ReTryFailedItem', E); raise; end; end;{$ENDIF} end; function TclInternetItem.FindFirstFailedItem(APrevThreader: TclCustomThreader): TclResourceStateItem; var i: Integer; PrevStateItem: TclResourceStateItem; begin PrevStateItem := FindStateItem(APrevThreader); if (PrevStateItem <> nil) then begin for i := 0 to ResourceState.Count - 1 do begin Result := ResourceState[i]; if ((PrevStateItem <> Result) and (Result.Status = psFailed)) then begin Exit; end; end; end; Result := nil; end; procedure TclInternetItem.DoOnTerminate(Sender: TObject); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'DoOnTerminate');{$ENDIF} ThreaderTerminated(Sender as TclCustomThreader); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'DoOnTerminate'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'DoOnTerminate', E); raise; end; end;{$ENDIF} end; procedure TclInternetItem.DoOnURLParsing(Sender: TObject; var URLComponents: TURLComponents); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'DoOnURLParsing');{$ENDIF} if (UserName <> '') then begin ZeroMemory(URLComponents.lpszUserName + 0, INTERNET_MAX_USER_NAME_LENGTH); CopyMemory(URLComponents.lpszUserName + 0, PclChar(GetTclString(FUserName)), Length(FUserName)); URLComponents.dwUserNameLength := Length(FUserName); end; if (Password <> '') then begin ZeroMemory(URLComponents.lpszPassword + 0, INTERNET_MAX_USER_NAME_LENGTH); CopyMemory(URLComponents.lpszPassword + 0, PclChar(GetTclString(FPassword)), Length(FPassword)); URLComponents.dwPasswordLength := Length(FPassword); end; if (Port <> 0) then begin URLComponents.nPort := Word(Port); end; Control.DoURLParsing(Self, URLComponents); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'DoOnURLParsing'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'DoOnURLParsing', E); raise; end; end;{$ENDIF} end; function TclInternetItem.GetIsBusy: Boolean; begin Result := (FThreaderList.Count > 0); end; function TclInternetItem.GetResourceInfo(IsAsynch: Boolean): TclResourceInfo; begin Result := nil; if (FResourceInfo = nil) and (not IsBusy) then begin if Control.CanStartItem(Self, True, IsAsynch) then begin InternalStart(True); end; if not IsAsynch then begin Wait(); Result := FResourceInfo; end; end else begin Result := FResourceInfo; if not IsBusy then begin Control.DoGetResourceInfo(Self, FResourceInfo); end; end; end; procedure TclInternetItem.SetLocalFile(const Value: string); begin if (FLocalFile = Value) then Exit; FLocalFile := Value; ControlChanged(); end; procedure TclInternetItem.SetPassword(const Value: string); begin if (FPassword = Value) then Exit; FPassword := Value; ControlChanged(); end; procedure TclInternetItem.SetURL(const Value: string); var Parser: TclUrlParser; begin if (FURL = Value) then Exit; FURL := Value; if (csLoading in Control.ComponentState) then Exit; Parser := TclUrlParser.Create(); try if (Parser.Parse(FURL) <> '') then begin UserName := Parser.UserName; Password := Parser.Password; end; finally Parser.Free(); end; ControlChanged(); end; procedure TclInternetItem.SetUserName(const Value: string); begin if (FUserName = Value) then Exit; FUserName := Value; ControlChanged(); end; procedure TclInternetItem.SetMaxConnectionsOption(); procedure SetIntOption(AOption, AValue: DWORD); var val, valsize: DWORD; begin val := 0; valsize := SizeOf(val); InternetQueryOption(nil, AOption, @val, valsize); if (val < AValue) then begin val := AValue; valsize := SizeOf(val); InternetSetOption(nil, AOption, @val, valsize); end; end; begin SetIntOption(INTERNET_OPTION_MAX_CONNS_PER_SERVER, MaxThreadCount); SetIntOption(INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER, MaxThreadCount); end; procedure TclInternetItem.InternalStart(AIsGetResourceInfo: Boolean); var StateItem: TclResourceStateItem; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'InternalStart: %s', nil, [URL]);{$ENDIF} SetMaxConnectionsOption(); FLastStatus := psUnknown; ClearInfo(); FHttpResponseHeader.Clear(); FErrors.Clear(); ResourceState.InitStatistic(); if AIsGetResourceInfo or CanProcess() then begin Control.BeginIsBusy(); if (ResourceState.Count > 0) then begin StateItem := ResourceState[0]; end else begin StateItem := nil; end; AddThreader(StateItem, AIsGetResourceInfo).Perform(); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'InternalStart'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'InternalStart', E); raise; end; end;{$ENDIF} end; function TclInternetItem.AddThreader(AStateItem: TclResourceStateItem; AIsGetResourceInfo: Boolean): TclCustomThreader; var Holder: TclThreaderHolder; Stream: TStream; begin if not AIsGetResourceInfo then begin Stream := GetDataStream(); end else begin Stream := nil; end; Result := CreateThreader(Stream, AIsGetResourceInfo); Holder := TclThreaderHolder.Create(); FThreaderList.Add(Holder); Holder.FThreader := Result; Holder.FStateItem := AStateItem; AssignThreader(Result); if (AStateItem <> nil) then begin Result.ResourcePos := AStateItem.ResourcePos + AStateItem.BytesProceed; if (AStateItem.BytesToProceed > 0) then begin Result.BytesToProceed := AStateItem.BytesToProceed - AStateItem.BytesProceed; end; end; end; procedure TclInternetItem.Start(IsAsynch: Boolean); begin if IsBusy then begin raise EclInternetError.Create(cOperationIsInProgress, -1); end; if Control.CanStartItem(Self, False, IsAsynch) then begin InternalStart(False); end; if not IsAsynch then begin Wait(); end; end; procedure TclInternetItem.Stop; var i: Integer; begin Control.DoStopItem(Self); if IsBusy then begin for i := 0 to FThreaderList.Count - 1 do begin GetThreader(i).Stop(); end; end; end; procedure TclInternetItem.ProcessCompleted(AThreader: TclCustomThreader); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'ProcessCompleted');{$ENDIF} HttpResponseHeader.Assign(AThreader.ResponseHeader); FIsCommit := True; try CommitWork(); finally FIsCommit := False; end; Control.StartNextItem(Self); Control.EndIsBusy(); Control.DoProcessCompleted(Self); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'ProcessCompleted'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'ProcessCompleted', E); raise; end; end;{$ENDIF} end; procedure TclInternetItem.CommitWork; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'CommitWork');{$ENDIF} ClearDataStream(); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'CommitWork'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'CommitWork', E); raise; end; end;{$ENDIF} end; procedure TclInternetItem.LastStatusChanged(Status: TclProcessStatus); begin if (FLastStatus <> Status) then begin FLastStatus := Status; Control.DoStatusChanged(Self, FLastStatus); end; end; procedure TclInternetItem.DoOnGetCertificate(Sender: TObject; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); begin Control.DoGetCertificate(Self, ACertificate, AExtraCerts, Handled); end; procedure TclInternetItem.ClearDataStream(); begin FSelfDataStream.Free(); FSelfDataStream := nil; end; function TclInternetItem.CheckSizeValid(ASize: Int64): Boolean; begin Result := True; Result := Result and ((Control.MinResourceSize = 0) or (ASize >= Control.MinResourceSize)); Result := Result and ((Control.MaxResourceSize = 0) or (ASize <= Control.MaxResourceSize)); end; function TclInternetItem.CanProcess: Boolean; begin Result := Control.CanProcess(Self); end; procedure TclInternetItem.ClearResourceState(); var i: Integer; begin ResourceState.Clear(); for i := 0 to FThreaderList.Count - 1 do begin TclThreaderHolder(FThreaderList[i]).FStateItem := nil; end; end; procedure TclInternetItem.SetInternalDataStream(const ADataStream: TStream); begin if (DataStream = nil) then begin ClearDataStream(); FSelfDataStream := ADataStream; end; end; procedure TclInternetItem.SetDataStream(const Value: TStream); begin if (DataStream <> Value) then begin ClearDataStream(); FDataStream := Value; end; end; function TclInternetItem.GetInternalDataStream: TStream; begin if (FDataStream <> nil) then begin Result := FDataStream; end else begin Result := FSelfDataStream; end; end; function TclInternetItem.FindStateItem(AThreader: TclCustomThreader): TclResourceStateItem; var i: Integer; begin for i := 0 to FThreaderList.Count - 1 do begin if (GetThreader(i) = AThreader) then begin Result := TclThreaderHolder(FThreaderList[i]).FStateItem; Exit; end; end; Result := nil; end; procedure TclInternetItem.ControlChanged(); begin if not (csLoading in Control.ComponentState) then begin if not IsBusy then begin ClearInfo(); ClearResourceState(); CloseConnection(); end; Control.Changed(Self); end; end; procedure TclInternetItem.CloseConnection; begin if (IsSharedConnection()) then begin GetConnection().Close(); end; end; function TclInternetItem.GetDefaultChar: Char; begin Result := Control.DefaultChar; end; function TclInternetItem.GetBatchSize: Integer; begin Result := Control.BatchSize; end; procedure TclInternetItem.DoOnResourceStateChanged(Sender: TObject); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'DoOnResourceStateChanged');{$ENDIF} Control.DoResourceStateChanged(Self); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'DoOnResourceStateChanged'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'DoOnResourceStateChanged', E); raise; end; end;{$ENDIF} end; procedure TclInternetItem.SetThreadCount(const Value: Integer); begin if (Value > 0) and (Value <= MaxThreadCount) then begin FThreadCount := Value; end; end; procedure TclInternetItem.DoCreate; begin FHttpResponseHeader := TStringList.Create(); FErrors := TclErrorList.Create(); FThreaderList := TList.Create(); FResourceState := TclResourceStateList.Create(); FResourceState.OnChanged := DoOnResourceStateChanged; FResourceInfo := nil; FPriority := ppNormal; FLastStatus := psUnknown; FThreadCount := 1; end; procedure TclInternetItem.DoDestroy; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'DoDestroy');{$ENDIF} FreeAndNil(FSelfConnection); ClearDataStream(); ClearInfo(); FResourceState.Free(); ClearThreaderList(); FThreaderList.Free(); FErrors.Free(); FHttpResponseHeader.Free(); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'DoDestroy'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'DoDestroy', E); raise; end; end;{$ENDIF} end; procedure TclInternetItem.SetHttpRequest(const Value: TclHttpRequest); begin if (FHttpRequest = Value) then Exit; if (FHttpRequest <> nil) then begin FHttpRequest.RemoveFreeNotification(Control); end; FHttpRequest := Value; if (FHttpRequest <> nil) then begin FHttpRequest.FreeNotification(Control); end; ControlChanged(); end; procedure TclInternetItem.InternalSetHttpRequest(const Value: TclHttpRequest); begin FHttpRequest := Value; end; function TclInternetItem.GetResourceConnections(Index: Integer): TclInternetConnection; begin Result := GetThreader(Index).Connection; end; function TclInternetItem.GetResourceConnectionCount: Integer; begin Result := FThreaderList.Count; end; procedure TclInternetItem.SetPort(const Value: Integer); begin if (FPort = Value) then Exit; FPort := Value; ControlChanged(); end; procedure TclInternetItem.DeleteRemoteFile; var threader: TclDeleteThreader; begin threader := TclDeleteThreader.Create(URL); try AssignThreaderParams(threader); threader.FreeOnTerminate := False; threader.OnUrlParsing := DoOnURLParsing; threader.OnGetCertificate := DoOnGetCertificate; threader.Perform(); threader.Wait(); if (threader.Status <> psSuccess) then begin raise EclInternetError.Create(threader.LastError, threader.LastErrorCode); end; finally threader.Free(); end; end; procedure TclInternetItem.SetUseHttpRequest(const Value: Boolean); begin FUseHttpRequest := Value; end; { TclCustomInternetControl } procedure TclCustomInternetControl.BeginIsBusy; begin Inc(FIsBusyCount); if (FIsBusyCount = 1) then begin IsBusyChanged(); end; end; constructor TclCustomInternetControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FProxyBypass := TStringList.Create(); FFtpProxySettings := TclFtpProxySettings.Create(); FHttpProxySettings := TclHttpProxySettings.Create(); FNotifierList := TList.Create(); FTryCount := DefaultTryCount; FBatchSize := DefaultBatchSize; FTimeOut := DefaultTimeOut; FReconnectAfter := DefaultTimeOut; FMinResourceSize := 0; FMaxResourceSize := 0; FInternetAgent := DefaultInternetAgent; FDefaultChar := DefaultPreviewChar; FDoNotGetResourceInfo := False; FUseInternetErrorDialog := False; end; procedure TclCustomInternetControl.EndIsBusy; var Allow: Boolean; begin Allow := (FIsBusyCount = 1); Dec(FIsBusyCount); if (FIsBusyCount < 0) then begin FIsBusyCount := 0; end; if Allow then begin IsBusyChanged(); end; end; class procedure TclCustomInternetControl.EnumIECacheEntries(AList: TStrings); var info: ^TInternetCacheEntryInfo; size: DWORD; hCache: THandle; begin info := nil; hCache := 0; try size := 0; GetMem(info, size); repeat hCache := FindFirstUrlCacheEntry(nil, info^, size); if (hCache = 0) then begin if (GetLastError() <> ERROR_INSUFFICIENT_BUFFER) then begin raise EclInternetError.CreateByLastError(); end; end else begin Break; end; FreeMem(info); GetMem(info, size); until False; if (hCache <> 0) then begin AList.Add(string(info^.lpszSourceUrlName)); end; repeat if not FindNextUrlCacheEntry(hCache, info^, size) then begin if (GetLastError() = ERROR_INSUFFICIENT_BUFFER) then begin FreeMem(info); GetMem(info, size); end else if (GetLastError() = ERROR_NO_MORE_ITEMS) then begin Break; end else begin raise EclInternetError.CreateByLastError(); end; end else begin AList.Add(string(info^.lpszSourceUrlName)); end; until False; finally FreeMem(info); if (hCache <> 0) then begin FindCloseUrlCache(hCache); end; end; end; class procedure TclCustomInternetControl.FlushIESession; begin InternetSetOption(nil, INTERNET_OPTION_END_BROWSER_SESSION, nil, 0); end; class procedure TclCustomInternetControl.GetIECacheEntryHeader(const AUrl: string; AList: TStrings); var info: ^TInternetCacheEntryInfo; size: DWORD; begin size := 0; info := nil; if not GetUrlCacheEntryInfo(PclChar(GetTclString(AUrl)), info^, size) and (GetLastError() <> ERROR_INSUFFICIENT_BUFFER) then begin raise EclInternetError.CreateByLastError(); end; GetMem(info, size); try if not GetUrlCacheEntryInfo(PclChar(GetTclString(AUrl)), info^, size) then begin raise EclInternetError.CreateByLastError(); end; if info.dwHeaderInfoSize > 0 then begin AList.Text := string(system.Copy(PclChar(info.lpHeaderInfo), 1, info.dwHeaderInfoSize)); end; finally FreeMem(info); end; end; class procedure TclCustomInternetControl.GetIECacheFile(const AUrl: string; AStream: TStream); const batchSize = 8192; var info: ^TInternetCacheEntryInfo; bytesRead, size: DWORD; hStream: THandle; buf: PclChar; begin size := 0; info := nil; hStream := RetrieveUrlCacheEntryStream(PclChar(GetTclString(AUrl)), info^, size, False, 0); if (hStream = 0) and (GetLastError() <> ERROR_INSUFFICIENT_BUFFER) then begin raise EclInternetError.CreateByLastError(); end; GetMem(buf, batchSize); GetMem(info, size); try hStream := RetrieveUrlCacheEntryStream(PclChar(GetTclString(AUrl)), info^, size, False, 0); if (hStream = 0) then begin raise EclInternetError.CreateByLastError(); end; bytesRead := 0; while (bytesRead < info.dwSizeLow) do begin size := info.dwSizeLow; if (size > batchSize) then begin size := batchSize; end; if not ReadUrlCacheEntryStream(hStream, bytesRead, buf, size, 0) then begin raise EclInternetError.CreateByLastError(); end; AStream.Write(buf^, size); bytesRead := bytesRead + size; end; finally if (hStream <> 0) then begin UnlockUrlCacheEntryStream(hStream, 0); end; FreeMem(info); FreeMem(buf); end; end; function TclCustomInternetControl.GetIsBusy: Boolean; begin Result := (FIsBusyCount > 0); end; procedure TclCustomInternetControl.IsBusyChanged; begin if Assigned(FOnIsBusyChanged) then begin FOnIsBusyChanged(Self); end; end; procedure TclCustomInternetControl.ReadRegistry(const APath: string); var size: Integer; reg: TRegistry; stream: TMemoryStream; begin reg := TRegistry.Create(); try if (reg.OpenKey(APath, False)) and reg.ValueExists(cDataValueName) then begin size := reg.GetDataSize(cDataValueName); if (size > 0) then begin stream := TMemoryStream.Create(); try stream.Size := size; reg.ReadBinaryData(cDataValueName, stream.Memory^, size); try stream.ReadComponent(Self); except end; finally stream.Free(); end; end; reg.CloseKey(); end; finally reg.Free(); end; end; procedure TclCustomInternetControl.WriteRegistry(const APath: string); var reg: TRegistry; stream: TMemoryStream; begin reg := TRegistry.Create(); try if (reg.OpenKey(APath, True)) then begin stream := TMemoryStream.Create(); try stream.WriteComponent(Self); reg.WriteBinaryData(cDataValueName, stream.Memory^, stream.Size); finally stream.Free(); end; reg.CloseKey(); end; finally reg.Free(); end; end; procedure TclCustomInternetControl.SetBatchSize(const Value: Integer); begin if (FBatchSize <> Value) and (Value > 0) then begin FBatchSize := Value; end; end; procedure TclCustomInternetControl.SetTimeOut(const Value: Integer); begin if (FTimeOut <> Value) and (Value > 0) then begin FTimeOut := Value; end; end; procedure TclCustomInternetControl.SetTryCount(const Value: Integer); begin if (FTryCount <> Value) and (Value > 0) then begin FTryCount := Value; end; end; procedure TclCustomInternetControl.SetMaxResourceSize(const Value: Int64); begin if (Value > -1) then begin FMaxResourceSize := Value; end; end; procedure TclCustomInternetControl.SetMinResourceSize(const Value: Int64); begin if (Value > -1) then begin FMinResourceSize := Value; end; end; procedure TclCustomInternetControl.SetDefaultChar(const Value: Char); begin if (FDefaultChar <> Value) and (Value > #31) then begin FDefaultChar := Value; end; end; procedure TclCustomInternetControl.Loaded; begin inherited Loaded(); Changed(nil); end; destructor TclCustomInternetControl.Destroy; begin FNotifierList.Free(); FHttpProxySettings.Free(); FFtpProxySettings.Free(); FProxyBypass.Free(); inherited Destroy(); end; procedure TclCustomInternetControl.DoDataItemProceed(Item: TclInternetItem; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer); var i: Integer; begin for i := 0 to FNotifierList.Count - 1 do begin GetControlNotifier(i).DoDataItemProceed(Item, ResourceInfo, AStateItem, CurrentData, CurrentDataSize); end; end; procedure TclCustomInternetControl.DoError(Item: TclInternetItem; const Error: string; ErrorCode: Integer); begin end; procedure TclCustomInternetControl.DoGetCertificate(Item: TclInternetItem; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); begin end; procedure TclCustomInternetControl.DoGetResourceInfo(Item: TclInternetItem; AResourceInfo: TclResourceInfo); begin end; procedure TclCustomInternetControl.DoStatusChanged(Item: TclInternetItem; Status: TclProcessStatus); var i: Integer; begin for i := 0 to FNotifierList.Count - 1 do begin GetControlNotifier(i).DoStatusChanged(Item, Status); end; end; function TclCustomInternetControl.GetControlNotifier(Index: Integer): TclControlNotifier; begin Result := TclControlNotifier(FNotifierList[Index]); end; procedure TclCustomInternetControl.RegisterControlNotifier(ANotifier: TclControlNotifier); begin FNotifierList.Add(ANotifier); end; procedure TclCustomInternetControl.UnregisterControlNotifier(ANotifier: TclControlNotifier); begin FNotifierList.Remove(ANotifier); end; procedure TclCustomInternetControl.DoItemCreated(Item: TclInternetItem); begin end; procedure TclCustomInternetControl.DoItemDeleted(Item: TclInternetItem); var i: Integer; begin for i := 0 to FNotifierList.Count - 1 do begin GetControlNotifier(i).DoItemDeleted(Item); end; end; procedure TclCustomInternetControl.DoProcessCompleted(Item: TclInternetItem); begin end; procedure TclCustomInternetControl.DoResourceStateChanged(Item: TclInternetItem); var i: Integer; begin for i := 0 to FNotifierList.Count - 1 do begin GetControlNotifier(i).DoResourceStateChanged(Item); end; end; procedure TclCustomInternetControl.SetReconnectAfter(const Value: Integer); begin if (FReconnectAfter <> Value) and (Value > 0) then begin FReconnectAfter := Value; end; end; procedure TclCustomInternetControl.SetConnection(const Value: TclInternetConnection); begin if (FConnection <> Value) then begin if (FConnection <> nil) then begin FConnection.RemoveFreeNotification(Self); end; FConnection := Value; if (FConnection <> nil) then begin FConnection.FreeNotification(Self); end; end; end; procedure TclCustomInternetControl.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation <> opRemove) then Exit; if (AComponent = FConnection) then begin FConnection := nil; end; if not (csDestroying in ComponentState) then begin NotifyInternetItems(AComponent); end; end; class function TclCustomInternetControl.GetCookie(const AURL, AName: string): string; var List: TStrings; begin List := TStringList.Create(); try GetAllCookies(AURL, List); Result := List.Values[AName]; finally List.Free(); end; end; class procedure TclCustomInternetControl.SetCookie(const AURL, AName, AValue: string); begin if not InternetSetCookie(PclChar(GetTclString(AURL)), PclChar(GetTclString(AName)), PclChar(GetTclString(AValue))) then begin raise EclInternetError.CreateByLastError(); end; end; class procedure TclCustomInternetControl.GetAllCookies(const AURL: string; AList: TStrings); procedure AddTextStr_(AList: TStrings; const Value: TclString); var P, Start: PclChar; S: TclString; begin AList.BeginUpdate(); try P := PclChar(Value); if P <> nil then while P^ <> #0 do begin Start := P; while not (P^ in [#0, #32, #59]) do Inc(P); SetString(S, Start, P - Start); AList.Add(string(S)); if P^ = #59 then Inc(P); if P^ = #32 then Inc(P); end; finally AList.EndUpdate(); end; end; var buf: PclChar; size: DWORD; begin size := 0; if not InternetGetCookie(PclChar(GetTclString(AURL)), nil, nil, size) then begin raise EclInternetError.CreateByLastError(); end; GetMem(buf, size); try if not InternetGetCookie(PclChar(GetTclString(AURL)), nil, buf, size) then begin raise EclInternetError.CreateByLastError(); end; AddTextStr_(AList, GetTclString(buf)); finally FreeMem(buf); end; end; function TclCustomInternetControl.CanStartItem(Item: TclInternetItem; AIsGetResourceInfo, IsAsynch: Boolean): Boolean; begin Result := True; end; procedure TclCustomInternetControl.Changed(Item: TclInternetItem); begin end; procedure TclCustomInternetControl.StartNextItem(APrevItem: TclInternetItem); begin end; procedure TclCustomInternetControl.DoStopItem(Item: TclInternetItem); begin end; procedure TclCustomInternetControl.DoURLParsing(Item: TclInternetItem; var URLComponents: TURLComponents); begin end; function TclCustomInternetControl.CanProcess(Item: TclInternetItem): Boolean; begin Result := True; end; procedure TclCustomInternetControl.GetFtpDirList(const ADir, AUser, APassword: string; AList: TStrings; ADetails: Boolean); function GetMsDosFileInfo(AFindFileData: TWin32FindData): string; var info: TclFtpFileInfo; begin info := TclFtpFileInfo.Create(); try info.FileName := AFindFileData.cFileName; info.Size := AFindFileData.nFileSizeLow; info.IsDirectory := ((AFindFileData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) > 0); info.ModifiedDate := ConvertFileTimeToDateTime(AFindFileData.ftLastWriteTime); Result := info.Build(lsMsDos); finally info.Free(); end; end; const AccessTypes: array[Boolean] of DWORD = (INTERNET_OPEN_TYPE_PRECONFIG, INTERNET_OPEN_TYPE_PROXY); var URLParser: TclUrlParser; OpenAction: TclInternetOpenAction; ConnectAction: TclConnectAction; FindFirstFileAction: TclFtpFindFirstFileAction; WaitEngine: TclInternetConnection; FindFileData: TWin32FindData; usr, psw, proxy: string; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); {$ENDIF} end; {$ENDIF} AList.Clear(); URLParser := nil; WaitEngine := nil; OpenAction := nil; ConnectAction := nil; FindFirstFileAction := nil; try URLParser := TclUrlParser.Create(); if (URLParser.Parse(ADir) = '') then Exit; WaitEngine := TclInternetConnection.Create(nil); proxy := GetProxyItem('ftp', FtpProxySettings.Server, FtpProxySettings.Port); OpenAction := TclInternetOpenAction.Create(WaitEngine, InternetAgent, AccessTypes[(proxy <> '')], proxy, StringReplace(Trim(ProxyBypass.Text), #13#10, #32, [rfReplaceAll]), INTERNET_FLAG_DONT_CACHE); OpenAction.FireAction(-1); usr := AUser; if (usr = '') then begin usr := URLParser.UserName; end; psw := APassword; if (psw = '') then begin psw := URLParser.Password; end; ConnectAction := TclConnectAction.Create(WaitEngine, OpenAction.hResource, URLParser.Host, INTERNET_DEFAULT_FTP_PORT, usr, psw, INTERNET_SERVICE_FTP, 0); ConnectAction.FireAction(TimeOut); FindFirstFileAction := TclFtpFindFirstFileAction.Create(WaitEngine, ConnectAction.Internet, ConnectAction.hResource, URLParser.Urlpath, INTERNET_FLAG_RELOAD); FindFirstFileAction.FireAction(TimeOut); FindFileData := FindFirstFileAction.lpFindFileData; repeat if ADetails then begin AList.Add(GetMsDosFileInfo(FindFileData)); end else begin AList.Add(FindFileData.cFileName); end; until (not InternetFindNextFile(FindFirstFileAction.hResource, @FindFileData)); finally FindFirstFileAction.Free(); ConnectAction.Free(); OpenAction.Free(); WaitEngine.Free(); URLParser.Free(); end; end; procedure TclCustomInternetControl.SetFtpProxySettings(const Value: TclFtpProxySettings); begin FFtpProxySettings.Assign(Value); end; procedure TclCustomInternetControl.SetHttpProxySettings(const Value: TclHttpProxySettings); begin FHttpProxySettings.Assign(Value); end; procedure TclCustomInternetControl.SetProxyBypass(const Value: TStrings); begin FProxyBypass.Assign(Value); end; { TclMultiInternetControl } procedure TclMultiInternetControl.Changed(Item: TclInternetItem); begin if Assigned(FOnChanged) then begin FOnChanged(Self, Item); end; end; procedure TclMultiInternetControl.DoDataItemProceed(Item: TclInternetItem; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer); begin if Assigned(FOnDataItemProceed) then begin FOnDataItemProceed(Self, Item, ResourceInfo, AStateItem, CurrentData, CurrentDataSize); end; inherited DoDataItemProceed(Item, ResourceInfo, AStateItem, CurrentData, CurrentDataSize); end; procedure TclMultiInternetControl.DoError(Item: TclInternetItem; const Error: string; ErrorCode: Integer); begin if Assigned(FOnError) then begin FOnError(Self, Item, Error, ErrorCode); end; end; procedure TclMultiInternetControl.DoGetCertificate(Item: TclInternetItem; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); begin if Assigned(FOnGetCertificate) then begin FOnGetCertificate(Self, Item, ACertificate, AExtraCerts, Handled); end; end; procedure TclMultiInternetControl.DoGetResourceInfo(Item: TclInternetItem; AResourceInfo: TclResourceInfo); begin if Assigned(FOnGetResourceInfo) then begin FOnGetResourceInfo(Self, Item, AResourceInfo); end; end; procedure TclMultiInternetControl.DoStatusChanged(Item: TclInternetItem; Status: TclProcessStatus); begin if Assigned(FOnStatusChanged) then begin FOnStatusChanged(Self, Item, Status); end; inherited DoStatusChanged(Item, Status); end; procedure TclMultiInternetControl.DoURLParsing(Item: TclInternetItem; var URLComponents: TURLComponents); begin if Assigned(FOnUrlParsing) then begin FOnUrlParsing(Self, Item, URLComponents); end; end; function TclMultiInternetControl.GetResourceInfo(Item: TclInternetItem; IsAsynch: Boolean): TclResourceInfo; var i: Integer; begin if (Item <> nil) then begin Result := Item.GetResourceInfo(IsAsynch); end else begin Result := nil; for i := 0 to GetInternetItemsCount() - 1 do begin GetInternetItems(i).GetResourceInfo(IsAsynch); end; end; end; procedure TclMultiInternetControl.Start(Item: TclInternetItem; IsAsynch: Boolean); var i: Integer; begin if (Item <> nil) then begin Item.Start(IsAsynch); end else begin for i := 0 to GetInternetItemsCount() - 1 do begin GetInternetItems(i).Start(IsAsynch); end; end; end; procedure TclMultiInternetControl.Stop(Item: TclInternetItem); begin InternalStop(Item); end; procedure TclMultiInternetControl.DoProcessCompleted(Item: TclInternetItem); begin if Assigned(FOnProcessCompleted) then begin FOnProcessCompleted(Self, Item); end; end; procedure TclMultiInternetControl.NotifyInternetItems(AComponent: TComponent); var i: Integer; begin for i := 0 to GetInternetItemsCount() - 1 do begin if (GetInternetItems(i).HttpRequest = AComponent) then begin GetInternetItems(i).InternalSetHttpRequest(nil); end; end; end; procedure TclMultiInternetControl.SetMaxStartedItems(const Value: Integer); begin if (Value > -1) then begin FMaxStartedItems := Value; end; end; constructor TclMultiInternetControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FDelayedItems := TList.Create(); FMaxStartedItems := 5; end; function TclMultiInternetControl.CanStartItem(Item: TclInternetItem; AIsGetResourceInfo, IsAsynch: Boolean): Boolean; var info: TclInternetItemInfo; begin Result := (not IsAsynch) or (FMaxStartedItems = 0) or (FStartedItemCount < FMaxStartedItems); if Result then begin Inc(FStartedItemCount); end else begin info := TclInternetItemInfo.Create(); FDelayedItems.Add(info); info.FItem := Item; info.FIsGetResourceInfo := AIsGetResourceInfo; end; end; procedure TclMultiInternetControl.StartNextItem(APrevItem: TclInternetItem); var info: TclInternetItemInfo; begin if (FStartedItemCount > 0) then begin Dec(FStartedItemCount); end; if (FDelayedItems.Count > 0) then begin info := TclInternetItemInfo(FDelayedItems[0]); try FDelayedItems.Delete(0); info.FItem.InternalStart(info.FIsGetResourceInfo); Inc(FStartedItemCount); finally info.Free(); end; end; end; destructor TclMultiInternetControl.Destroy; var i: Integer; begin for i := 0 to FDelayedItems.Count - 1 do begin TObject(FDelayedItems[i]).Free(); end; FDelayedItems.Free(); inherited Destroy(); end; procedure TclMultiInternetControl.DeleteDelayedInfo(Item: TclInternetItem); var i: Integer; info: TclInternetItemInfo; begin for i := 0 to FDelayedItems.Count - 1 do begin info := TclInternetItemInfo(FDelayedItems[i]); if (info.FItem = Item) then begin info.Free(); FDelayedItems.Delete(i); Break; end; end; end; procedure TclMultiInternetControl.DoItemCreated(Item: TclInternetItem); begin inherited DoItemCreated(Item); if Assigned(OnItemCreated) then begin OnItemCreated(Self, Item); end; end; procedure TclMultiInternetControl.DoItemDeleted(Item: TclInternetItem); begin inherited DoItemDeleted(Item); DeleteDelayedInfo(Item); if Assigned(OnItemDeleted) then begin OnItemDeleted(Self, Item); end; end; procedure TclMultiInternetControl.DoStopItem(Item: TclInternetItem); begin DeleteDelayedInfo(Item); end; procedure TclMultiInternetControl.InternalStop(Item: TclInternetItem); var i: Integer; begin if (Item <> nil) then begin Item.Stop(); end else begin for i := 0 to GetInternetItemsCount() - 1 do begin GetInternetItems(i).Stop(); end; end; end; { TclControlNotifier } constructor TclControlNotifier.Create(AControl: TclCustomInternetControl); begin inherited Create(); FControl := AControl; Assert(FControl <> nil); FControl.RegisterControlNotifier(Self); end; destructor TclControlNotifier.Destroy(); begin FControl.UnregisterControlNotifier(Self); inherited Destroy(); end; procedure TclControlNotifier.DoDataItemProceed(Item: TclInternetItem; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer); begin end; procedure TclControlNotifier.DoItemDeleted(Item: TclInternetItem); begin end; procedure TclControlNotifier.DoResourceStateChanged(Item: TclInternetItem); begin end; procedure TclControlNotifier.DoStatusChanged(Item: TclInternetItem; Status: TclProcessStatus); begin end; end.
unit uLembreteDAO; interface uses uBaseDAO, uLembrete, FireDAC.Comp.Client, System.Generics.Collections, System.SysUtils; type TLembreteDAO = class(TBaseDAO) private FListaLembrete: TObjectList<TLembrete>; procedure PreencherColecao(Ds: TFDQuery); public constructor Create; destructor Destroy; function Inserir(pLembrete: TLembrete): Boolean; function Deletar(pLembrete: TLembrete): Boolean; function Alterar(pLembrete: TLembrete): Boolean; function ListarPorTitulo(pConteudo: string): TObjectList<TLembrete>; end; implementation { TLembreteDAO } constructor TLembreteDAO.Create; begin inherited; FListaLembrete := TObjectList<TLembrete>.Create; end; destructor TLembreteDAO.Destroy; begin Try inherited; if Assigned(FListaLembrete) then FreeAndNil(FListaLembrete); except on e: exception do raise exception.Create(e.Message); End; end; function TLembreteDAO.Inserir(pLembrete: TLembrete): Boolean; var SQL: string; begin SQL := 'INSERT INTO lembretes(idlembrete, titulo, descricao, datahora) values (' + 'default' + ',' + QuotedStr(pLembrete.titulo) + ',' + QuotedStr(pLembrete.descricao) + ',' + QuotedStr(FormatDateTime('dd,MM,yyyy', pLembrete.data)) + QuotedStr(formatDateTime('HH:mm', pLembrete.hora)) + ')'; Result := ExecutarComando(SQL) > 0 end; function TLembreteDAO.Alterar(pLembrete: TLembrete): Boolean; var SQL: string; begin SQL := 'UPDATE lembretes set titulo = ' + QuotedStr(pLembrete.titulo) + ', descricao = ' + QuotedStr(pLembrete.descricao) + ', datahora = ' + QuotedStr(FormatDateTime('yyyy,mm,dd', pLembrete.data)) + QuotedStr(FormatDateTime('HH:mm', pLembrete.hora)) + ' WHERE idlembrete = ' + IntToStr(pLembrete.IDLembrete); Result := ExecutarComando(SQL) > 0; end; function TLembreteDAO.Deletar(pLembrete: TLembrete): Boolean; var SQL: String; begin SQL := 'DELETE FROM Lembretes L where L.idlembrete = ' + IntToStr(pLembrete.IDLembrete); Result := ExecutarComando(SQL) > 0; end; function TLembreteDAO.ListarPorTitulo(pConteudo: string) : TObjectList<TLembrete>; var SQL: string; begin Result := Nil; SQL := 'SELECT F.idlembrete, F.titulo, F.descricao, ' + ' F.datahora FROM lembretes F'; if pConteudo = '' then begin SQL := SQL + ' WHERE F.datahora >= ' + QuotedStr(FormatDateTime('yyyy-mm-dd', Now)); end else begin SQL := SQL + ' WHERE F.titulo LIKE ' + QuotedStr('%' + pConteudo + '%'); end; SQL := SQL + ' ORDER BY F.datahora '; FQuery := RetornarDataSet(SQL); if not(FQuery.IsEmpty) then begin PreencherColecao(FQuery); Result := FListaLembrete; end; end; procedure TLembreteDAO.PreencherColecao(Ds: TFDQuery); var I: integer; begin I := 0; FListaLembrete.Clear; while not Ds.eof do begin FListaLembrete.Add(TLembrete.Create); FListaLembrete[I].IDLembrete := Ds.FieldByName('idlembrete').AsInteger; FListaLembrete[I].titulo := Ds.FieldByName('titulo').AsString; FListaLembrete[I].descricao := Ds.FieldByName('descricao').AsString; FListaLembrete[I].data := Ds.FieldByName('datahora').AsDateTime; Ds.Next; I := I + 1; end; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { { Rev 1.8 10/26/2004 8:12:30 PM JPMugaas { Now uses TIdStrings and TIdStringList for portability. } { Rev 1.7 6/11/2004 8:28:56 AM DSiders Added "Do not Localize" comments. } { { Rev 1.6 5/14/2004 12:14:50 PM BGooijen { Fix for weird dotnet bug when querying the local binding } { { Rev 1.5 4/18/04 2:45:54 PM RLebeau { Conversion support for Int64 values } { { Rev 1.4 2004.03.07 11:45:26 AM czhower { Flushbuffer fix + other minor ones found } { { Rev 1.3 3/6/2004 5:16:30 PM JPMugaas { Bug 67 fixes. Do not write to const values. } { { Rev 1.2 2/10/2004 7:33:26 PM JPMugaas { I had to move the wrapper exception here for DotNET stack because Borland's { update 1 does not permit unlisted units from being put into a package. That { now would report an error and I didn't want to move IdExceptionCore into the { System package. } { { Rev 1.1 2/4/2004 8:48:30 AM JPMugaas { Should compile. } { { Rev 1.0 2004.02.03 3:14:46 PM czhower { Move and updates } { { Rev 1.32 2/1/2004 6:10:54 PM JPMugaas { GetSockOpt. } { { Rev 1.31 2/1/2004 3:28:32 AM JPMugaas { Changed WSGetLocalAddress to GetLocalAddress and moved into IdStack since { that will work the same in the DotNET as elsewhere. This is required to { reenable IPWatch. } { { Rev 1.30 1/31/2004 1:12:54 PM JPMugaas { Minor stack changes required as DotNET does support getting all IP addresses { just like the other stacks. } { { Rev 1.29 2004.01.22 2:46:52 PM czhower { Warning fixed. } { { Rev 1.28 12/4/2003 3:14:54 PM BGooijen { Added HostByAddress } { { Rev 1.27 1/3/2004 12:22:14 AM BGooijen { Added function SupportsIPv6 } { { Rev 1.26 1/2/2004 4:24:08 PM BGooijen { This time both IPv4 and IPv6 work } { { Rev 1.25 02/01/2004 15:58:00 HHariri { fix for bind } { { Rev 1.24 12/31/2003 9:52:00 PM BGooijen { Added IPv6 support } { { Rev 1.23 10/28/2003 10:12:36 PM BGooijen { DotNet } { { Rev 1.22 10/26/2003 10:31:16 PM BGooijen { oops, checked in debug version <g>, this is the right one } { { Rev 1.21 10/26/2003 5:04:26 PM BGooijen { UDP Server and Client } { { Rev 1.20 10/21/2003 11:03:50 PM BGooijen { More SendTo, ReceiveFrom } { { Rev 1.19 10/21/2003 9:24:32 PM BGooijen { Started on SendTo, ReceiveFrom } { { Rev 1.18 10/19/2003 5:21:30 PM BGooijen { SetSocketOption } { { Rev 1.17 10/11/2003 4:16:40 PM BGooijen { Compiles again } { { Rev 1.16 10/5/2003 9:55:28 PM BGooijen { TIdTCPServer works on D7 and DotNet now } { { Rev 1.15 10/5/2003 3:10:42 PM BGooijen { forgot to clone the Sockets list in some Select methods, + added Listen and { Accept } { { Rev 1.14 10/5/2003 1:52:14 AM BGooijen { Added typecasts with network ordering calls, there are required for some { reason } { { Rev 1.13 10/4/2003 10:39:38 PM BGooijen { Renamed WSXXX functions in implementation section too } { { Rev 1.12 04/10/2003 22:32:00 HHariri { moving of WSNXXX method to IdStack and renaming of the DotNet ones } { { Rev 1.11 04/10/2003 21:28:42 HHariri { Netowkr ordering functions } { { Rev 1.10 10/3/2003 11:02:02 PM BGooijen { fixed calls to Socket.Select } { { Rev 1.9 10/3/2003 11:39:38 PM GGrieve { more work } { { Rev 1.8 10/3/2003 12:09:32 AM BGooijen { DotNet } { { Rev 1.7 10/2/2003 8:23:52 PM BGooijen { .net } { { Rev 1.6 10/2/2003 8:08:52 PM BGooijen { .Connect works not in .net } { { Rev 1.5 10/2/2003 7:31:20 PM BGooijen { .net } { { Rev 1.4 10/2/2003 6:12:36 PM GGrieve { work in progress (hardly started) } { { Rev 1.3 2003.10.01 9:11:24 PM czhower { .Net } { { Rev 1.2 2003.10.01 5:05:18 PM czhower { .Net } { { Rev 1.1 2003.10.01 1:12:40 AM czhower { .Net } { { Rev 1.0 2003.09.30 10:35:40 AM czhower { Initial Checkin } unit IdStackDotNet; interface uses IdGlobal, IdStack, IdStackConsts, IdObjs, System.Collections; type TIdSocketListDotNet = class(TIdSocketList) protected Sockets:ArrayList; function GetItem(AIndex: Integer): TIdStackSocketHandle; override; public constructor Create; override; destructor Destroy; override; procedure Add(AHandle: TIdStackSocketHandle); override; procedure Remove(AHandle: TIdStackSocketHandle); override; function Count: Integer; override; procedure Clear; override; function Clone: TIdSocketList; override; function Contains(AHandle: TIdStackSocketHandle): boolean; override; class function Select(AReadList: TIdSocketList; AWriteList: TIdSocketList; AExceptList: TIdSocketList; const ATimeout: Integer = IdTimeoutInfinite): Boolean; override; function SelectRead(const ATimeout: Integer = IdTimeoutInfinite): Boolean; override; function SelectReadList(var VSocketList: TIdSocketList; const ATimeout: Integer = IdTimeoutInfinite): Boolean; override; end; TIdStackDotNet = class(TIdStack) protected function ReadHostName: string; override; function HostByName(const AHostName: string; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string; override; function GetLocalAddress: string; override; function GetLocalAddresses: TIdStrings; override; procedure PopulateLocalAddresses; override; //internal IP Mutlicasting membership stuff procedure MembershipSockOpt(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP : String; const ASockOpt : TIdSocketOption; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); public procedure Bind(ASocket: TIdStackSocketHandle; const AIP: string; const APort: Integer; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure Connect(const ASocket: TIdStackSocketHandle; const AIP: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure Disconnect(ASocket: TIdStackSocketHandle); override; procedure GetPeerName(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: Integer); override; procedure GetSocketName(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: TIdPort); override; function NewSocketHandle(const ASocketType:TIdSocketType; const AProtocol: TIdSocketProtocol; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION; const AOverlapped: Boolean = False) : TIdStackSocketHandle; override; // Result: // > 0: Number of bytes received // 0: Connection closed gracefully // Will raise exceptions in other cases function Receive(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes) : Integer; override; function Send( ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; AOffset: Integer = 0; ASize: Integer = -1 ): Integer; override; function IOControl(const s: TIdStackSocketHandle; const cmd: cardinal; var arg: cardinal ): Integer; override; function ReceiveFrom(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes; var VIP: string; var VPort: Integer; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION ): Integer; override; function ReceiveMsg(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes; APkt : TIdPacketInfo; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): Cardinal; override; function SendTo(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; const AOffset: Integer; const AIP: string; const APort: integer; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION ): Integer; override; function HostToNetwork(AValue: Word): Word; override; function NetworkToHost(AValue: Word): Word; override; function HostToNetwork(AValue: LongWord): LongWord; override; function NetworkToHost(AValue: LongWord): LongWord; override; function HostToNetwork(AValue: Int64): Int64; override; function NetworkToHost(AValue: Int64): Int64; override; function HostByAddress(const AAddress: string; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string; override; procedure Listen(ASocket: TIdStackSocketHandle; ABackLog: Integer);override; function Accept(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: Integer; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION ):TIdStackSocketHandle; override; procedure GetSocketOption(ASocket: TIdStackSocketHandle; ALevel: TIdSocketOptionLevel; AOptName: TIdSocketOption; out AOptVal: Integer); override; procedure SetSocketOption(ASocket: TIdStackSocketHandle; ALevel:TIdSocketOptionLevel; AOptName: TIdSocketOption; AOptVal: Integer); overload;override; function SupportsIPv6:boolean; override; //multicast stuff Kudzu permitted me to add here. procedure SetMulticastTTL(AHandle: TIdStackSocketHandle; const AValue : Byte; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure SetLoopBack(AHandle: TIdStackSocketHandle; const AValue: Boolean; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure DropMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP : String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure AddMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP : String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure WriteChecksum(s : TIdStackSocketHandle; var VBuffer : TIdBytes; const AOffset : Integer; const AIP : String; const APort : Integer; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; end; implementation uses IdException, System.Net, System.Net.Sockets; const IdIPFamily : array[TIdIPVersion] of AddressFamily = (AddressFamily.InterNetwork, AddressFamily.InterNetworkV6 ); { TIdStackDotNet } function BuildException(AException : System.Exception) : Exception; var LSocketError : System.Net.Sockets.SocketException; begin if AException is System.Net.Sockets.SocketException then begin LSocketError := AException as System.Net.Sockets.SocketException; result := EIdSocketError.createError(LSocketError.ErrorCode, LSocketError.Message) end else begin result := EIdWrapperException.create(AException.Message, AException); end; end; procedure TIdStackDotNet.Bind(ASocket: TIdStackSocketHandle; const AIP: string; const APort: Integer; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var LEndPoint : IPEndPoint; LIP:String; begin try LIP := AIP; if LIP='' then begin if (AIPVersion=Id_IPv4) then begin LIP := '0.0.0.0'; {do not localize} end else if (AIPVersion=Id_IPv6) then begin LIP := '::'; {do not localize} end; end; LEndPoint := IPEndPoint.Create(IPAddress.Parse(LIP), APort); ASocket.Bind(LEndPoint); except on e:exception do begin raise BuildException(e); end; end; end; procedure TIdStackDotNet.Connect(const ASocket: TIdStackSocketHandle; const AIP: string; const APort: TIdPort;const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var LEndPoint : IPEndPoint; begin try LEndPoint := IPEndPoint.Create(IPAddress.Parse(AIP), APort); ASocket.Connect(LEndPoint); except on e:exception do begin raise BuildException(e); end; end; end; procedure TIdStackDotNet.Disconnect(ASocket: TIdStackSocketHandle); begin try ASocket.Close; except on e:exception do begin raise BuildException(e); end; end; end; procedure TIdStackDotNet.Listen(ASocket: TIdStackSocketHandle; ABackLog: Integer); begin try ASocket.Listen(ABackLog); except on e:exception do begin raise BuildException(e); end; end; end; function TIdStackDotNet.Accept(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: Integer; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION ):TIdStackSocketHandle; begin try result := ASocket.Accept(); except on e:exception do begin raise BuildException(e); end; end; end; procedure TIdStackDotNet.GetPeerName(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: Integer); var LEndPoint : EndPoint; begin try LEndPoint := ASocket.remoteEndPoint; VIP := (LEndPoint as IPEndPoint).Address.ToString; VPort := (LEndPoint as IPEndPoint).Port; except on e:exception do begin raise BuildException(e); end; end; end; procedure TIdStackDotNet.GetSocketName(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: TIdPort); var LEndPoint : EndPoint; begin try if ASocket.Connected or (VIP<>'') then begin LEndPoint := ASocket.localEndPoint; VIP := (LEndPoint as IPEndPoint).Address.ToString; VPort := (LEndPoint as IPEndPoint).Port; end; except on e:exception do begin raise BuildException(e); end; end; end; function TIdStackDotNet.HostByName(const AHostName: string; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string; var LIP:array of IPAddress; a:integer; begin try LIP := Dns.Resolve(AHostName).AddressList; for a:=low(LIP) to high(LIP) do begin if LIP[a].AddressFamily=IdIPFamily[AIPVersion] then begin result := LIP[a].toString; exit; end; end; raise System.Net.Sockets.SocketException.Create(11001); except on e:exception do begin raise BuildException(e); end; end; end; function TIdStackDotNet.HostByAddress(const AAddress: string; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string; begin try result := Dns.GetHostByAddress(AAddress).HostName; except on e:exception do begin raise BuildException(e); end; end; end; function TIdStackDotNet.NewSocketHandle(const ASocketType:TIdSocketType; const AProtocol: TIdSocketProtocol; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION; const AOverlapped: Boolean = false): TIdStackSocketHandle; begin try case AIPVersion of Id_IPv4: result := Socket.Create(AddressFamily.InterNetwork, ASocketType, AProtocol); Id_IPv6: result := Socket.Create(AddressFamily.InterNetworkV6, ASocketType, AProtocol); else raise EIdException.Create('Invalid socket type'); {do not localize} end; except on E: Exception do begin raise BuildException(E); end; end; end; function TIdStackDotNet.ReadHostName: string; begin try result := System.Net.DNS.GetHostName; except on e:exception do begin raise BuildException(e); end; end; end; function TIdStackDotNet.Receive(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes): Integer; begin try result := ASocket.Receive(VBuffer,length(VBuffer),SocketFlags.None); except on e:exception do begin raise BuildException(e); end; end; end; function TIdStackDotNet.Send( ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; AOffset: Integer = 0; ASize: Integer = -1 ): Integer; begin if ASize = -1 then begin ASize := Length(ABuffer) - AOffset; end; try Result := ASocket.Send(ABuffer, AOffset, ASize, SocketFlags.None); except on E: Exception do begin raise BuildException(E); end; end; end; function TIdStackDotNet.ReceiveFrom(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes; var VIP: string; var VPort: Integer; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): Integer; var LEndPoint : EndPoint; begin Result := 0; // to make the compiler happy LEndPoint := IPEndPoint.Create(IPAddress.Any, 0); try try Result := ASocket.ReceiveFrom(VBuffer,SocketFlags.None,LEndPoint); except on e:exception do begin raise BuildException(e); end; end; VIP := IPEndPoint(LEndPoint).Address.ToString; VPort := IPEndPoint(LEndPoint).Port; finally LEndPoint.free; end; end; function TIdStackDotNet.SendTo(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; const AOffset: Integer; const AIP: string; const APort: integer; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION ): Integer; var LEndPoint : EndPoint; begin Result := 0; // to make the compiler happy LEndPoint := IPEndPoint.Create(IPAddress.Parse(AIP), APort); try try Result := ASocket.SendTo(ABuffer,SocketFlags.None,LEndPoint); except on e:exception do begin raise BuildException(e); end; end; finally LEndPoint.free; end; end; ////////////////////////////////////////////////////////////// constructor TIdSocketListDotNet.Create; begin inherited Create; Sockets:=ArrayList.Create; end; destructor TIdSocketListDotNet.Destroy; begin Sockets.free; inherited Destroy; end; procedure TIdSocketListDotNet.Add(AHandle: TIdStackSocketHandle); begin Sockets.Add(AHandle); end; procedure TIdSocketListDotNet.Clear; begin Sockets.Clear; end; function TIdSocketListDotNet.Contains(AHandle: TIdStackSocketHandle): Boolean; begin result:=Sockets.Contains(AHandle); end; function TIdSocketListDotNet.Count: Integer; begin result:=Sockets.Count; end; function TIdSocketListDotNet.GetItem(AIndex: Integer): TIdStackSocketHandle; begin result:=(Sockets.Item[AIndex]) as TIdStackSocketHandle; end; procedure TIdSocketListDotNet.Remove(AHandle: TIdStackSocketHandle); begin Sockets.Remove(AHandle); end; function TIdSocketListDotNet.SelectRead(const ATimeout: Integer): Boolean; var LTempSockets:ArrayList; begin try // DotNet updates this object on return, so we need to copy it each time we need it LTempSockets:=ArrayList(Sockets.Clone); try if ATimeout=IdTimeoutInfinite then begin Socket.Select(LTempSockets,nil,nil,MaxLongint); end else begin Socket.Select(LTempSockets,nil,nil,ATimeout*1000); end; result := LTempSockets.Count > 0; finally LTempSockets.free; end; except on e:exception do begin raise BuildException(e); end; end; end; function TIdSocketListDotNet.SelectReadList(var VSocketList: TIdSocketList; const ATimeout: Integer): Boolean; var LTempSockets:ArrayList; begin try // DotNet updates this object on return, so we need to copy it each time we need it LTempSockets:=ArrayList(Sockets.Clone); try if ATimeout=IdTimeoutInfinite then begin Socket.Select(LTempSockets,nil,nil,MaxLongint); end else begin Socket.Select(LTempSockets,nil,nil,ATimeout*1000); end; result := LTempSockets.Count > 0; finally LTempSockets.free; end; except on e:exception do begin raise BuildException(e); end; end; end; class function TIdSocketListDotNet.Select(AReadList, AWriteList, AExceptList: TIdSocketList; const ATimeout: Integer): Boolean; begin try if ATimeout=IdTimeoutInfinite then begin Socket.Select( TIdSocketListDotNet(AReadList).Sockets, TIdSocketListDotNet(AWriteList).Sockets, TIdSocketListDotNet(AExceptList).Sockets,MaxLongint); end else begin Socket.Select( TIdSocketListDotNet(AReadList).Sockets, TIdSocketListDotNet(AWriteList).Sockets, TIdSocketListDotNet(AExceptList).Sockets,ATimeout*1000); end; result:= (TIdSocketListDotNet(AReadList).Sockets.Count>0) or (TIdSocketListDotNet(AWriteList).Sockets.Count>0) or (TIdSocketListDotNet(AExceptList).Sockets.Count>0); except on e:ArgumentNullException do begin result:=false; end; on e:exception do begin raise BuildException(e); end; end; end; function TIdSocketListDotNet.Clone: TIdSocketList; begin Result:=TIdSocketListDotNet.Create; //BGO: TODO: make prettier TIdSocketListDotNet(Result).Sockets.Free; TIdSocketListDotNet(Result).Sockets:=ArrayList(Sockets.Clone); end; function TIdStackDotNet.HostToNetwork(AValue: Word): Word; begin Result := Word(IPAddress.HostToNetworkOrder(SmallInt(AValue))); end; function TIdStackDotNet.HostToNetwork(AValue: LongWord): LongWord; begin Result := LongWord(IPAddress.HostToNetworkOrder(integer(AValue))); end; function TIdStackDotNet.HostToNetwork(AValue: Int64): Int64; begin Result := IPAddress.HostToNetworkOrder(AValue); end; function TIdStackDotNet.NetworkToHost(AValue: Word): Word; begin Result := Word(IPAddress.NetworkToHostOrder(SmallInt(AValue))); end; function TIdStackDotNet.NetworkToHost(AValue: LongWord): LongWord; begin Result := LongWord(IPAddress.NetworkToHostOrder(integer(AValue))); end; function TIdStackDotNet.NetworkToHost(AValue: Int64): Int64; begin Result := IPAddress.NetworkToHostOrder(AValue); end; procedure TIdStackDotNet.GetSocketOption(ASocket: TIdStackSocketHandle; ALevel: TIdSocketOptionLevel; AOptName: TIdSocketOption; out AOptVal: Integer); var L : System.Object; begin L := ASocket.GetSocketOption(ALevel,AoptName); AOptVal := Integer(L); end; procedure TIdStackDotNet.SetSocketOption(ASocket: TIdStackSocketHandle; ALevel:TIdSocketOptionLevel; AOptName: TIdSocketOption; AOptVal: Integer); begin ASocket.SetSocketOption(ALevel, AOptName, AOptVal); end; function TIdStackDotNet.SupportsIPv6:boolean; begin result := Socket.SupportsIPv6; end; function TIdStackDotNet.GetLocalAddresses: TIdStrings; begin if FLocalAddresses = nil then begin FLocalAddresses := TIdStringList.Create; end; PopulateLocalAddresses; Result := FLocalAddresses; end; procedure TIdStackDotNet.PopulateLocalAddresses; var LAddr : IPAddress; LHost : IPHostEntry; i : Integer; begin FLocalAddresses.Clear; LAddr := IPAddress.Any; LHost := DNS.GetHostByAddress(LAddr); if Length(LHost.AddressList)>0 then begin for i := Low(LHost.AddressList) to High(LHost.AddressList) do begin FLocalAddresses.Add(LHost.AddressList[i].ToString); end; end; end; function TIdStackDotNet.GetLocalAddress: string; begin Result := LocalAddresses[0]; end; procedure TIdStackDotNet.SetLoopBack(AHandle: TIdStackSocketHandle; const AValue: Boolean; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var LVal : Integer; begin //necessary because SetSocketOption only accepts an integer //see: http://groups-beta.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/6a35c6d9052cfc2b/f01fea11f9a24508?q=SetSocketOption+DotNET&rnum=2&hl=en#f01fea11f9a24508 if AValue then begin LVal := 1; end else begin LVal := 0; end; AHandle.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback , LVal); end; procedure TIdStackDotNet.DropMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP: String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin MembershipSockOpt(AHandle,AGroupIP,ALocalIP,SocketOptionName.DropMembership ); end; procedure TIdStackDotNet.AddMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP: String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin MembershipSockOpt(AHandle,AGroupIP,ALocalIP,SocketOptionName.AddMembership); end; procedure TIdStackDotNet.SetMulticastTTL(AHandle: TIdStackSocketHandle; const AValue: Byte; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin if AIPVersion=Id_IPv4 then begin AHandle.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive,AValue); end else begin AHandle.SetSocketOption(SocketOptionLevel.IPv6 , SocketOptionName.MulticastTimeToLive,AValue); end; end; procedure TIdStackDotNet.MembershipSockOpt(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP: String; const ASockOpt: TIdSocketOption; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var LM4 : MulticastOption; LM6 : IPv6MulticastOption; LGroupIP, LLocalIP : System.Net.IPAddress; begin LGroupIP := IPAddress.Parse(AGroupIP); if LGroupIP.AddressFamily = AddressFamily.InterNetworkV6 then begin LM6 := IPv6MulticastOption.Create(LGroupIP); AHandle.SetSocketOption(SocketOptionLevel.IPv6 , SocketOptionName.AddMembership , LM6); end else begin if ALocalIP.Length =0 then begin LM4 := System.Net.Sockets.MulticastOption.Create(LGroupIP); end else begin LLocalIP := IPAddress.Parse(ALocalIP); LM4 := System.Net.Sockets.MulticastOption.Create(LGroupIP,LLocalIP); end; AHandle.SetSocketOption(SocketOptionLevel.IP, ASockOpt, LM4); end; end; function TIdStackDotNet.ReceiveMsg(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes; APkt: TIdPacketInfo; const AIPVersion: TIdIPVersion): Cardinal; var LIP : String; LPort : Integer; begin Result := ReceiveFrom(ASocket,VBuffer,LIP,LPort,AIPVersion); APkt.SourceIP := LIP; APkt.SourcePort := LPort; end; procedure TIdStackDotNet.WriteChecksum(s: TIdStackSocketHandle; var VBuffer: TIdBytes; const AOffset: Integer; const AIP: String; const APort: Integer; const AIPVersion: TIdIPVersion); begin if AIPVersion = Id_IPv4 then begin CopyTIdWord(CalcCheckSum(VBuffer),VBuffer,AOffset); end else begin {This is a todo because to do a checksum for ICMPv6, you need to obtain the address for the IP the packet will come from (querry the network interfaces). You then have to make a IPv6 pseudo header. About the only other alternative is to have the kernal (or DotNET Framework generate the checksum but we don't have an API for it. I'm not sure if we have an API for it at all. Even if we did, would it be worth doing when you consider that Microsoft's NET Framework 1.1 does not support ICMPv5 in its enumerations. } Todo; end; end; function TIdStackDotNet.IOControl(const s: TIdStackSocketHandle; const cmd: cardinal; var arg: cardinal): Integer; var LTmp : TIdBytes; begin LTmp := ToBytes(arg); s.IOControl(cmd, ToBytes(arg), LTmp); arg := BytesToCardinal(LTmp); Result := 0; end; initialization GSocketListClass := TIdSocketListDotNet; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DropSource, StdCtrls, Menus; type TDummy = class (TControl) public property Caption; property OnMouseDown; //TMouseEvent read FOnMouseDown write FOnMouseDown; property OnMouseMove; //TMouseMoveEvent read FOnMouseMove write FOnMouseMove; end; TForm1 = class(TForm) DropTextSource1: TDropTextSource; Label1: TLabel; Button1: TButton; PopupMenu1: TPopupMenu; AddLabel1: TMenuItem; procedure dsMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure dsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure AddLabel1Click(Sender: TObject); procedure FormDestroy(Sender: TObject); private DragPoint : TPoint; FNbrOfAddedLabels : integer; //For label naming purpose procedure AssignEvents; procedure createLabel(Caption_ : string); procedure LoadFromfile; procedure SaveToFile; function GetInifilename() : string; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses inifiles; {$R *.DFM} procedure TForm1.dsMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin //Start drag after moviing 10 pixels if (DragPoint.X = -1) or ((Shift <> [ssLeft]) and (Shift <> [ssRight])) or ((abs(DragPoint.X - X) <10) and (abs(DragPoint.Y - Y) <10)) then exit; if Sender is TControl then begin DropTextSource1.Text :=TDummy(Sender).Caption; end else begin exit; end; //Start the dragdrop... //Note: DropFileSource1.DragTypes = [dtCopy] DropTextSource1.execute; end; procedure TForm1.dsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin DragPoint := Point(X,Y); if Button = mbright then begin if sender is TLabel then TLabel(Sender).Caption := InputBox('Update','Enter a new value:',TLabel(Sender).Caption); end; end; procedure TForm1.Button1Click(Sender: TObject); begin Close; end; procedure TForm1.FormCreate(Sender: TObject); begin FNbrOfAddedLabels := 1; Caption := Application.Title; AssignEvents(); LoadFromfile; end; procedure TForm1.AssignEvents(); var i : integer; MouseDown : TMouseEvent; MouseMove : TMouseMoveEvent; begin MouseDown := dsMouseDown; MouseMove := dsMouseMove; for i := 0 to ControlCount -1 do begin if Controls[i] is TControl then begin TDummy(Controls[i]).OnMouseDown := MouseDown; TDummy(Controls[i]).OnMouseMove := MouseMove; end; end; end; procedure TForm1.AddLabel1Click(Sender: TObject); begin CreateLabel('null'); end; procedure TForm1.createLabel(Caption_ : string); var O : TLabel; const constOffset = 16; begin Inc(FNbrOfAddedLabels); O := TLabel.Create(Self); O.Parent := self; O.Name := 'Label' + IntToStr(FNbrOfAddedLabels); O.Left := Label1.Left; O.Top := Label1.Top + constOffset * (FNbrOfAddedLabels -1); Height := Height + constOffset; O.Visible := True; O.Caption := Caption_; AssignEvents(); end; procedure TForm1.LoadFromfile(); var f : TIniFile; i : integer; lst : TStrings; s : string; begin lst := nil; f := nil; try lst := TStringList.Create; f := TIniFile.Create(GetInifilename); f.ReadSection('Data',lst); for i := 0 to lst.Count - 1 do begin s := f.ReadString('Data',lst[i],'null'); if lst[i] = 'Label1' then Label1.Caption := s else createLabel(s); end; finally f.Free; lst.Free; end; end; function TForm1.GetInifilename() : string; begin Result := ChangeFileExt(paramstr(0),'.ini'); end; procedure TForm1.SaveToFile(); var f : TIniFile; i : integer; begin f :=nil; try f := TIniFile.Create(GetInifilename); for i := 0 to ControlCount -1 do begin if Controls[i] is TLabel then begin f.WriteString('Data',TLabel(Controls[i]).Name,TLabel(Controls[i]).Caption); end; end; finally f.Free; end; end; procedure TForm1.FormDestroy(Sender: TObject); begin SaveToFile; end; end.
unit AddressesOrderInfoUnit; interface uses REST.Json.Types, SysUtils, JSONNullableAttributeUnit, HttpQueryMemberAttributeUnit, GenericParametersUnit; type TAddressInfo = class(TGenericParameters) private [JSONName('route_destination_id')] FDestinationId: integer; [JSONName('sequence_no')] FSequenceNo: integer; [JSONName('is_depot')] FIsDepot: boolean; public property DestinationId: integer read FDestinationId write FDestinationId; property SequenceNo: integer read FSequenceNo write FSequenceNo; property IsDepot: boolean read FIsDepot write FIsDepot; end; TAddressesOrderInfo = class(TGenericParameters) private [JSONMarshalled(False)] [HttpQueryMember('route_id')] FRouteId: String; [JSONName('addresses')] FAddresses: TArray<TAddressInfo>; public constructor Create(RouteId: String); reintroduce; destructor Destroy; override; procedure AddAddress(Address: TAddressInfo); property RouteId: String read FRouteId write FRouteId; property Addresses: TArray<TAddressInfo> read FAddresses; end; implementation { TAddressesOrderInfo } procedure TAddressesOrderInfo.AddAddress(Address: TAddressInfo); begin SetLength(FAddresses, Length(FAddresses) + 1); FAddresses[High(FAddresses)] := Address; end; constructor TAddressesOrderInfo.Create(RouteId: String); begin inherited Create; FRouteId := RouteId; SetLength(FAddresses, 0); end; destructor TAddressesOrderInfo.Destroy; var i: integer; begin for i := Length(FAddresses) - 1 downto 0 do FreeAndNil(FAddresses[i]); inherited; end; end.
namespace Sugar.Test; interface uses Sugar, RemObjects.Elements.EUnit; type UserSettingsTest = public class (Test) var Data: UserSettings := UserSettings.Default; public method TearDown; override; method ReadString; method ReadInteger; method ReadBoolean; method ReadDouble; method WriteString; method WriteInteger; method WriteBoolean; method WriteDouble; method Clear; method &Remove; method Keys; method &Default; end; implementation method UserSettingsTest.TearDown; begin Data.Clear; Data.Save; end; method UserSettingsTest.ReadString; begin Data.Write("String", "One"); var Actual := Data.Read("String", nil); Assert.IsNotNil(Actual); Assert.AreEqual(Actual, "One"); Assert.AreEqual(Data.Read("StringX", "Default"), "Default"); Data.Clear; Assert.AreEqual(Data.Read("String", "Default"), "Default"); Assert.Throws(->Data.Read(nil, "Default")); end; method UserSettingsTest.ReadInteger; begin Data.Write("Integer", 42); var Actual := Data.Read("Integer", -1); Assert.AreEqual(Actual, 42); Assert.AreEqual(Data.Read("IntegerX", -1), -1); Data.Clear; Assert.AreEqual(Data.Read("Integer", -1), -1); Assert.Throws(->Data.Read(nil, 1)); end; method UserSettingsTest.ReadBoolean; begin Data.Write("Boolean", true); Assert.IsTrue(Data.Read("Boolean", false)); Assert.IsTrue(Data.Read("BooleanX", true)); Data.Clear; Assert.IsFalse(Data.Read("Boolean", false)); Assert.Throws(->Data.Read(nil, true)); end; method UserSettingsTest.ReadDouble; begin Data.Write("Double", 4.2); var Actual := Data.Read("Double", -1.0); Assert.AreEqual(Actual, 4.2); Assert.AreEqual(Data.Read("DoubleX", -1), -1); Data.Clear; Assert.AreEqual(Data.Read("Double", -1), -1); Assert.Throws(->Data.Read(nil, 1.1)); end; method UserSettingsTest.WriteString; begin Assert.AreEqual(length(Data.Keys), 0); Data.Write("String", "One"); Assert.AreEqual(length(Data.Keys), 1); Assert.AreEqual(Data.Read("String", nil), "One"); Data.Write("String", "Two"); //override Assert.AreEqual(length(Data.Keys), 1); Assert.AreEqual(Data.Read("String", nil), "Two"); Assert.Throws(->Data.Write(nil, "One")); end; method UserSettingsTest.WriteInteger; begin Assert.AreEqual(length(Data.Keys), 0); Data.Write("Integer", 42); Assert.AreEqual(length(Data.Keys), 1); Assert.AreEqual(Data.Read("Integer", -1), 42); Data.Write("Integer", 5); Assert.AreEqual(length(Data.Keys), 1); Assert.AreEqual(Data.Read("Integer", -1), 5); Assert.Throws(->Data.Write(nil, 1)); end; method UserSettingsTest.WriteBoolean; begin Assert.AreEqual(length(Data.Keys), 0); Data.Write("Boolean", true); Assert.AreEqual(length(Data.Keys), 1); Assert.IsTrue(Data.Read("Boolean", false)); Data.Write("Boolean", false); Assert.AreEqual(length(Data.Keys), 1); Assert.IsFalse(Data.Read("Boolean", true)); Assert.Throws(->Data.Write(nil, true)); end; method UserSettingsTest.WriteDouble; begin Assert.AreEqual(length(Data.Keys), 0); Data.Write("Double", 4.2); Assert.AreEqual(length(Data.Keys), 1); Assert.AreEqual(Data.Read("Double", -1.0), 4.2); Data.Write("Double", 5.5); Assert.AreEqual(length(Data.Keys), 1); Assert.AreEqual(Data.Read("Double", -1.0), 5.5); Assert.Throws(->Data.Write(nil, 1.0)); end; method UserSettingsTest.Clear; begin Assert.AreEqual(length(Data.Keys), 0); Data.Write("Boolean", true); Assert.AreEqual(length(Data.Keys), 1); Data.Clear; Assert.AreEqual(length(Data.Keys), 0); end; method UserSettingsTest.&Remove; begin Assert.AreEqual(length(Data.Keys), 0); Data.Write("String", "One"); Assert.AreEqual(length(Data.Keys), 1); Data.Remove("String"); Assert.AreEqual(length(Data.Keys), 0); Data.Remove("A"); Assert.Throws(->Data.Remove(nil)); end; method UserSettingsTest.Keys; begin var Expected := new Sugar.Collections.List<String>; Expected.Add("String"); Expected.Add("Integer"); Expected.Add("Double"); Data.Write("String", ""); Data.Write("Integer", 0); Data.Write("Double", 2.2); var Actual := Data.Keys; Assert.AreEqual(length(Actual), 3); for i: Integer := 0 to length(Actual) - 1 do Assert.IsTrue(Expected.Contains(Actual[i])); end; method UserSettingsTest.&Default; begin Assert.IsNotNil(UserSettings.Default); Assert.AreEqual(length(UserSettings.Default.Keys), 0); Assert.AreEqual(length(Data.Keys), 0); UserSettings.Default.Write("Boolean", true); Assert.AreEqual(length(UserSettings.Default.Keys), 1); Assert.AreEqual(length(Data.Keys), 1); end; end.
// Save/load macro templates from an XML file // Original Author: Piotr Likus unit GX_MacroFile; interface uses Classes; type TTemplateInsertPos = (tipCursorPos, tipUnitStart, tipLineStart, tipLineEnd); const DefaultInsertPos = tipCursorPos; EmptyShortCut = 0; type TTemplateList = class; // Stores all information about single macro template TMacroObject = class private FText: string; // code of macro FDesc: string; // description FPubUnits: TStringList; // list of public units FPrivUnits: TStringList; // list of private units FInsertPos: TTemplateInsertPos; // position of insert FShortCut: TShortCut; FName: string; procedure SetPrivUnits(const Value: TStringList); procedure SetPubUnits(const Value: TStringList); public constructor Create(const AName: string); destructor Destroy; override; procedure Assign(ASource: TMacroObject); property Name: string read FName write FName; property Desc: string read FDesc write FDesc; property Text: string read FText write FText; property PrivUnits: TStringList read FPrivUnits write SetPrivUnits; property PubUnits: TStringList read FPubUnits write SetPubUnits; property InsertPos: TTemplateInsertPos read FInsertPos write FInsertPos default DefaultInsertPos; property ShortCut: TShortCut read FShortCut write FShortCut default EmptyShortCut; end; TTemplateList = class(TList) protected function GetTemplate(Index: Integer): TMacroObject; public procedure Clear; override; destructor Destroy; override; function CreateTemplate(const AName: string): TMacroObject; procedure Remove(ATemplate: TMacroObject); property Templates[Index: Integer]: TMacroObject read GetTemplate; default; end; // Saves/loads templates from an XML file TMacroFile = class private FTemplateList: TTemplateList; FFileName: string; function GetMacroItem(Index: Integer): TMacroObject; function GetMacroCount: Integer; public constructor Create(const AFileName: string = ''); destructor Destroy; override; procedure Clear; procedure LoadFromFile; procedure SaveToFile(const AFilename: string); function AddMacro(AMacroObject: TMacroObject): TMacroObject; procedure RemoveMacro(AMacroObject: TMacroObject); function IndexOf(const AObjectName: string): Integer; property MacroCount: Integer read GetMacroCount; property MacroItems[Index: Integer]: TMacroObject read GetMacroItem; default; property FileName: string read FFileName write FFileName; end; function InsertPosToText(Pos: TTemplateInsertPos): string; implementation uses SysUtils, OmniXML, GX_XmlUtils, GX_GenericUtils; const // XML storage tag tag names TagPrivUnits = 'PrivUnits'; // property name for Private units TagPubUnits = 'PubUnits'; // property name for Public units TagDesc = 'Desc'; // property name for Description TagName = 'Name'; // property name for Name TagInsertPos = 'InsertPos'; // property name for Insert position TagShortCut = 'Shortcut'; // property name for ShortCut TagTemplates = 'Templates'; // list of templates TagTemplate = 'Template'; // single template { TMacroObject } procedure TMacroObject.Assign(ASource: TMacroObject); begin FName := ASource.Name; FDesc := ASource.Desc; FText := ASource.Text; FPrivUnits.Assign(ASource.PrivUnits); FPubUnits.Assign(ASource.PubUnits); FInsertPos := ASource.InsertPos; FShortCut := ASource.ShortCut; end; constructor TMacroObject.Create(const AName: string); begin inherited Create; FName := AName; FPrivUnits := TStringList.Create; FPubUnits := TStringList.Create; FInsertPos := tipCursorPos; end; destructor TMacroObject.Destroy; begin FreeAndNil(FPrivUnits); FreeAndNil(FPubUnits); inherited; end; procedure TMacroObject.SetPrivUnits(const Value: TStringList); begin FPrivUnits.Assign(Value); end; procedure TMacroObject.SetPubUnits(const Value: TStringList); begin FPubUnits.Assign(Value); end; { TMacroFile } constructor TMacroFile.Create(const AFileName: string); begin inherited Create; FTemplateList := TTemplateList.Create; FFileName := AFileName; end; destructor TMacroFile.Destroy; begin FreeAndNil(FTemplateList); inherited; end; function TMacroFile.AddMacro(AMacroObject: TMacroObject): TMacroObject; begin Result := FTemplateList.CreateTemplate(AMacroObject.Name); Result.Assign(AMacroObject); end; procedure TMacroFile.Clear; begin inherited; FTemplateList.Clear; end; function TMacroFile.GetMacroItem(Index: Integer): TMacroObject; begin Result := TMacroObject(FTemplateList[Index]); end; function TMacroFile.IndexOf(const AObjectName: string): Integer; var i: Integer; begin Result := -1; for i := 0 to FTemplateList.Count - 1 do if AnsiCompareText(MacroItems[i].Name, AObjectName) = 0 then begin Result := i; Break; end; end; procedure TMacroFile.RemoveMacro(AMacroObject: TMacroObject); begin FTemplateList.Remove(AMacroObject); end; procedure TMacroFile.LoadFromFile; function GetOptionalProp(AMap: IXMLNamedNodeMap; APropName: string; ADefaultValue: string = ''): string; var PropAttr: IXMLNode; begin PropAttr := AMap.GetNamedItem(APropName); if Assigned(PropAttr) then Result := PropAttr.NodeValue else Result := ADefaultValue; end; var Doc: IXMLDocument; i: Integer; MacroObject: TMacroObject; Nodes: IXMLNodeList; TmplName, TmplDesc, TmplText, TmplPrivUnits, TmplPubUnits, TmplInsertPos: string; TmplShortCut: string; PropMap: IXMLNamedNodeMap; PropNode: IXMLNode; Macro: IXMLNode; begin FTemplateList.Clear; if not FileExists(FFileName) then Exit; Doc := CreateXMLDoc; Doc.Load(FileName); Nodes := Doc.DocumentElement.SelectNodes(TagTemplate); for i := 0 to Nodes.Length - 1 do begin Macro := Nodes.Item[i]; PropMap := Macro.Attributes; PropNode := PropMap.GetNamedItem(TagName); if not Assigned(PropNode) then Exit; TmplName := PropNode.NodeValue; PropNode := PropMap.GetNamedItem(TagDesc); if not Assigned(PropNode) then Exit; TmplDesc := PropNode.NodeValue; TmplText := GetCDataSectionTextOrNodeText(Macro); TmplPrivUnits := GetOptionalProp(PropMap, TagPrivUnits); TmplPubUnits := GetOptionalProp(PropMap, TagPubUnits); TmplInsertPos := GetOptionalProp(PropMap, TagInsertPos, IntToStr(Ord(DefaultInsertPos))); TmplShortCut := GetOptionalProp(PropMap, TagShortCut, IntToStr(EmptyShortCut)); MacroObject := FTemplateList.CreateTemplate(TmplName); MacroObject.Desc := TmplDesc; MacroObject.Text := TmplText; MacroObject.PrivUnits.CommaText := TmplPrivUnits; MacroObject.PubUnits.CommaText := TmplPubUnits; MacroObject.InsertPos := TTemplateInsertPos(StrToIntDef(TmplInsertPos, Ord(DefaultInsertPos))); MacroObject.ShortCut := StrToIntDef(TmplShortCut, EmptyShortCut); end; end; procedure TMacroFile.SaveToFile(const AFilename: string); var Doc: IXMLDocument; Root: IXMLElement; i: Integer; MacroObject: TMacroObject; MacroItem: IXMLElement; TextNode: IXMLCDATASection; begin Doc := CreateXMLDoc; AddXMLHeader(Doc); Root := Doc.CreateElement(TagTemplates); Doc.AppendChild(Root); for i := 0 to FTemplateList.Count - 1 do begin MacroItem := Doc.CreateElement(TagTemplate); MacroObject := FTemplateList[i]; MacroItem.SetAttribute(TagName, MacroObject.Name); MacroItem.SetAttribute(TagDesc, MacroObject.Desc); if MacroObject.PrivUnits.Count > 0 then MacroItem.SetAttribute(TagPrivUnits, MacroObject.PrivUnits.CommaText); if MacroObject.PubUnits.Count > 0 then MacroItem.SetAttribute(TagPubUnits, MacroObject.PubUnits.CommaText); if MacroObject.InsertPos <> DefaultInsertPos then MacroItem.SetAttribute(TagInsertPos, IntToStr(Ord(MacroObject.InsertPos))); if MacroObject.ShortCut <> EmptyShortCut then MacroItem.SetAttribute(TagShortCut, IntToStr(MacroObject.ShortCut)); TextNode := Doc.CreateCDATASection(EscapeCDataText(MacroObject.Text)); MacroItem.AppendChild(TextNode); Root.AppendChild(MacroItem); end; if PrepareDirectoryForWriting(ExtractFileDir(AFilename)) then Doc.Save(AFileName, ofFlat); end; function TMacroFile.GetMacroCount: Integer; begin Result := FTemplateList.Count; end; { TTemplateList } destructor TTemplateList.Destroy; begin Clear; inherited; end; procedure TTemplateList.Clear; var Obj: TObject; begin while Count > 0 do begin Obj := Self[Count - 1]; Delete(Count - 1); FreeAndNil(Obj); end; end; function TTemplateList.GetTemplate(Index: Integer): TMacroObject; begin Result := TMacroObject(inherited Items[Index]); end; function TTemplateList.CreateTemplate(const AName: string): TMacroObject; begin Result := TMacroObject.Create(AName); Add(Result); end; procedure TTemplateList.Remove(ATemplate: TMacroObject); begin inherited Remove(ATemplate); FreeAndNil(ATemplate); end; function InsertPosToText(Pos: TTemplateInsertPos): string; begin Result := 'Unknown'; case Pos of tipCursorPos: Result := 'Cursor'; tipUnitStart: Result := 'File'; tipLineStart: Result := 'Line'; tipLineEnd: Result := 'LineEnd'; end; end; end.
unit atNamedMutex; {* Обертка вокруг виндового мьютекса } // Модуль: "w:\quality\test\garant6x\AdapterTest\CoreObjects\atNamedMutex.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatNamedMutex" MUID: (491D8DFA00BB) interface uses l3IntfUses , l3_Base , Windows ; type TatNamedMutex = class(Tl3_Base) {* Обертка вокруг виндового мьютекса } private f_MutexHandle: THandle; protected procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aName: AnsiString); reintroduce; function Acquire(aTimeOut: LongWord = INFINITE): Boolean; virtual; procedure Release; virtual; end;//TatNamedMutex implementation uses l3ImplUses , SysUtils //#UC START# *491D8DFA00BBimpl_uses* //#UC END# *491D8DFA00BBimpl_uses* ; constructor TatNamedMutex.Create(const aName: AnsiString); //#UC START# *491D94ED015F_491D8DFA00BB_var* //#UC END# *491D94ED015F_491D8DFA00BB_var* begin //#UC START# *491D94ED015F_491D8DFA00BB_impl* inherited Create; f_MutexHandle := CreateMutex(nil, false, PAnsiChar('{7273D3A2-313D-44DE-9D04-A3A90137271A}_' + aName)); if (f_MutexHandle = 0) then Raise Exception.Create('Не могу создать мьютекс!'); //#UC END# *491D94ED015F_491D8DFA00BB_impl* end;//TatNamedMutex.Create function TatNamedMutex.Acquire(aTimeOut: LongWord = INFINITE): Boolean; //#UC START# *491D955302A3_491D8DFA00BB_var* //#UC END# *491D955302A3_491D8DFA00BB_var* begin //#UC START# *491D955302A3_491D8DFA00BB_impl* Result := (WaitForSingleObject(f_MutexHandle, aTimeOut) = WAIT_OBJECT_0); //#UC END# *491D955302A3_491D8DFA00BB_impl* end;//TatNamedMutex.Acquire procedure TatNamedMutex.Release; //#UC START# *491D959F0347_491D8DFA00BB_var* //#UC END# *491D959F0347_491D8DFA00BB_var* begin //#UC START# *491D959F0347_491D8DFA00BB_impl* ReleaseMutex(f_MutexHandle); //#UC END# *491D959F0347_491D8DFA00BB_impl* end;//TatNamedMutex.Release procedure TatNamedMutex.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_491D8DFA00BB_var* //#UC END# *479731C50290_491D8DFA00BB_var* begin //#UC START# *479731C50290_491D8DFA00BB_impl* CloseHandle(f_MutexHandle); inherited; //#UC END# *479731C50290_491D8DFA00BB_impl* end;//TatNamedMutex.Cleanup end.
{$MODE OBJFPC} program Task; const InputFile = 'PAPERS.INP'; OutputFile = 'PAPERS.OUT'; modulo = Round(1E9 + 7); var fi, fo: TextFile; n, k, a, i: Integer; function Inverse(a: Integer): Integer; var m, r, q, xa, xm, xr: Integer; begin m := modulo; xa := 1; xm := 0; while m <> 0 do begin q := a div m; xr := xa - q * xm; xa := xm; xm := xr; r := a mod m; a := m; m := r; end; Result := (xa + modulo) mod modulo; end; function C(k, n: Integer): Int64; var i: Integer; begin Result := 1; for i := 2 to k do Result := Result * i mod modulo; Result := Inverse(Result); for i := n downto n - k + 1 do Result := Result * i mod modulo; end; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); try ReadLn(fi, n, k); for i := 1 to k do begin Read(fi, a); n := n - a + 1; if n < 0 then n := -1; end; if k > n then WriteLn(fo, 0) else WriteLn(fo, C(k - 1, n - 1)); finally CloseFile(fi); CloseFile(fo); end; end.
unit uFBFormReplicacao; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait, Vcl.StdCtrls, Data.DB, FireDAC.Comp.Client, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Buttons, FireDAC.Phys.FBDef, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.Phys.IBDef, FireDAC.Comp.UI, FireDAC.Phys.IB, FireDAC.Phys.SQLite, FireDAC.Phys.IBBase, FireDAC.Phys.FB, FireDAC.Comp.ScriptCommands, FireDAC.Stan.Util, FireDAC.Comp.Script; const CR = #13; type TFDReplicacao = class private FConn:TFDConnection; procedure CreateRepl_Table; procedure ExecSql(texto: string); function CreateGidPublisher(tab: string): boolean; function CriarGID(tab:string):boolean; function existsColumn(tab, coluna: string): boolean; public procedure LerColunas(aConn:TFDConnection; aTabela:string; aItems:TStrings); procedure LerTabelas(aConn:TFDConnection;aItems:TStrings) ; procedure CriarPublisher(aConn:TFDConnection; aTabela:string); procedure CriarSubscriptor(aConn:TFDConnection; aTabela:string); end; TForm41 = class(TForm) FConnOrigem: TFDConnection; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; TabSheet3: TTabSheet; Label1: TLabel; ComboBox1: TComboBox; Panel1: TPanel; Panel2: TPanel; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; FDManager1: TFDManager; SpeedButton3: TSpeedButton; Label2: TLabel; ComboBox2: TComboBox; FDPhysFBDriverLink1: TFDPhysFBDriverLink; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; FDPhysIBDriverLink1: TFDPhysIBDriverLink; FDGUIxWaitCursor1: TFDGUIxWaitCursor; ListBox1: TListBox; SpeedButton4: TSpeedButton; SpeedButton5: TSpeedButton; Label3: TLabel; ComboBox3: TComboBox; SpeedButton6: TSpeedButton; Label4: TLabel; ComboBox4: TComboBox; SpeedButton7: TSpeedButton; ListBox2: TListBox; FConnDestino: TFDConnection; SpeedButton8: TSpeedButton; procedure FormCreate(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); procedure SpeedButton4Click(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure SpeedButton5Click(Sender: TObject); procedure SpeedButton6Click(Sender: TObject); procedure SpeedButton7Click(Sender: TObject); procedure SpeedButton8Click(Sender: TObject); private { Private declarations } FReplicacao:TFDReplicacao; public { Public declarations } procedure moveTab(const value:integer); end; var Form41: TForm41; implementation {$R *.dfm} procedure TForm41.FormCreate(Sender: TObject); var it:IFDStanConnectionDef; i:integer; begin FReplicacao:=TFDReplicacao.create; ComboBox1.Items.Clear; for i:=0 to FDManager1.ConnectionDefs.Count-1 do begin it := FDManager1.ConnectionDefs.Items[i]; if it.Params.values['DriverID'] = 'FB' then begin ComboBox1.Items.Add(it.Name); comboBox3.Items.Add(it.Name); end; end; comboBox1.ItemIndex := 0; ComboBox3.ItemIndex := 0; PageControl1.ActivePageIndex := 0; end; procedure TForm41.FormDestroy(Sender: TObject); begin FReplicacao.Free; end; procedure TForm41.moveTab(const value: integer); var r:integer; begin r := PageControl1.ActivePageIndex + value; if r>=PageControl1.PageCount then r := PageControl1.PageCount -1; if r<0 then r := 0; PageControl1.ActivePageIndex := r; end; procedure TFDReplicacao.LerTabelas(aConn:TFDConnection;aItems:TStrings) ; var lst: TStringList; begin AItems.Clear; lst := TStringList.Create; try AConn.GetTableNames('', '', '', lst); AItems.Assign(lst); finally lst.Free; end; end; procedure TFDReplicacao.CreateRepl_Table; begin ExecSQL('create table Repl_Itens ' + '( tabela varchar(128), ' + ' gid varchar(38), ' + ' tipo char(1), ' + ' data date, id numeric(15,0) ' + ');'); ExecSQL('alter table Repl_Itens add Session_id numeric(15,0);'); ExecSQL('create index repl_itensID on repl_itens(id); '); ExecSQL('create index repl_itensData on repl_itens(data); '); ExecSQL('create index repl_itensgid on repl_itens(gid); '); ExecSQL('create index repl_itenstabela on repl_itens(tabela); '); ExecSQL('CREATE SEQUENCE REPL_ITENS_GEN_ID;'); ExecSQL( 'CREATE OR ALTER TRIGGER REPL_ITENS_ID FOR REPL_ITENS ' + CR + 'ACTIVE BEFORE INSERT POSITION 0 ' + CR + 'AS ' + CR + 'begin /* Replicacao Storeware */ ' + CR + ' new.id = gen_id(REPL_ITENS_GEN_ID,1); ' + CR + ' new.data = cast(''now'' as date); ' + CR + 'end '); end; function TFDReplicacao.existsColumn(tab, coluna: string): boolean; var lst:TStringList; begin lst:=TStringList.create; try FConn.GetFieldNames('','',tab,'',lst); result := lst.IndexOf(uppercase(coluna))>=0; finally lst.free; end; end; function TFDReplicacao.CreateGidPublisher(tab: string): boolean; begin result := false; tab := uppercase(tab); if not existsColumn(tab, 'GID') then begin ExecSQL('alter table ' + tab + ' add GID varchar(38);'); ExecSQL('create index ' + tab + 'GID on ' + tab + '(gid); '); end; ExecSQL( 'CREATE OR ALTER TRIGGER REPL_' + tab + '_REG FOR ' + tab + ' ' + CR + 'ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0 ' + CR + 'AS ' + CR + 'begin ' + CR + ' /* Replicacao Storeware */ ' + CR + ' if (coalesce(rdb$get_context(''USER_TRANSACTION'', ''Modulo''),''BD'')<>''PDVSYNC'') then ' + CR + ' begin ' + CR + ' in autonomous transaction do ' + CR + ' begin ' + CR + ' if (inserting) then ' + CR + ' insert into repl_itens ( tabela,gid,tipo) ' + CR + ' values(' + QuotedStr(tab) + ',new.gid,''I''); ' + CR + ' if (updating) then ' + CR + ' insert into repl_itens ( tabela,gid,tipo) ' + CR + ' values(' + QuotedStr(tab) + ',new.gid,''U''); ' + CR + ' if (deleting) then ' + CR + ' insert into repl_itens ( tabela,gid,tipo) ' + CR + ' values(' + QuotedStr(tab) + ',old.gid,''D''); ' + CR + ' end ' + CR + ' end ' + CR + 'end ');//+ result := true; end; function TFDReplicacao.CriarGID(tab: string): boolean; begin if not existsColumn(tab, 'GID') then begin ExecSQL('alter table ' + tab + ' add GID varchar(38);'); ExecSQL('create index ' + tab + 'GID on ' + tab + '(gid); '); end; end; procedure TFDReplicacao.CriarPublisher(aConn: TFDConnection; aTabela: string); begin FConn := aConn; CreateRepl_Table; // criar a tabela de controle de eventos CreateGidPublisher(aTabela); end; procedure TFDReplicacao.CriarSubscriptor(aConn: TFDConnection; aTabela: string); begin FConn := aConn; CriarGID(aTabela); end; procedure TFDReplicacao.ExecSql(texto:string); var scp:TFDScript; txt:TStringList; begin txt:=TStringList.create; try txt.Text := texto; scp:=TFDScript.Create(nil); try scp.Connection := FConn; scp.ExecuteScript(txt); finally scp.Free; end; finally txt.Free; end; end; procedure TFDReplicacao.LerColunas(aConn:TFDConnection; aTabela:string; aItems:TStrings); var lst: TStringList; begin if aTabela <> '' then begin lst := TStringList.create; try aConn.GetFieldNames('', '', aTabela, '', lst); AItems.Assign(lst); finally lst.Free; end; end; end; procedure TForm41.SpeedButton1Click(Sender: TObject); begin moveTab(1); end; procedure TForm41.SpeedButton2Click(Sender: TObject); begin moveTab(-1); end; procedure TForm41.SpeedButton3Click(Sender: TObject); begin FConnOrigem.ConnectionDefName := comboBox1.Text; FReplicacao.LerTabelas(FConnOrigem,ComboBox2.Items); ComboBox2.Enabled := true; ComboBox2.ItemIndex := 0; end; procedure TForm41.SpeedButton4Click(Sender: TObject); begin FReplicacao.LerColunas(FConnOrigem,ComboBox2.Text,ListBox1.Items); ComboBox4.Text := ComboBox2.Text; end; procedure TForm41.SpeedButton5Click(Sender: TObject); begin // gerar if ComboBox2.text<>'' then FReplicacao.CriarPublisher(FConnOrigem,ComboBox2.text); end; procedure TForm41.SpeedButton6Click(Sender: TObject); begin FConnDestino.ConnectionDefName := comboBox3.Text; FReplicacao.LerTabelas(FConnDestino,ComboBox4.Items); ComboBox4.Enabled := false; end; procedure TForm41.SpeedButton7Click(Sender: TObject); begin FReplicacao.LerColunas(FConnDestino,ComboBox4.Text,ListBox2.Items); end; procedure TForm41.SpeedButton8Click(Sender: TObject); begin if ComboBox1.Text = ComboBox3.text then raise exception.Create('O banco de origem e destino não podem ser o mesmo'); if ComboBox4.text<>'' then FReplicacao.CriarSubscriptor(FConnDestino,ComboBox4.text); end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls; type { TForm1 } TForm1 = class(TForm) ButtonFind: TButton; ButtonDir: TButton; EditDirs: TEdit; EditMasks: TEdit; Label1: TLabel; Label2: TLabel; ListBox1: TListBox; Panel1: TPanel; SelectDirectoryDialog1: TSelectDirectoryDialog; procedure ButtonFindClick(Sender: TObject); procedure ButtonDirClick(Sender: TObject); private public end; var Form1: TForm1; implementation uses FileUtil; {$R *.lfm} { TForm1 } procedure TForm1.ButtonFindClick(Sender: TObject); var L: TStringList; begin ListBox1.Items.Clear; L:= TStringList.Create; try FindAllFiles(L, EditDirs.text, EditMasks.Text); ListBox1.Items.Assign(L); finally L.Free; end; end; procedure TForm1.ButtonDirClick(Sender: TObject); begin with SelectDirectoryDialog1 do if Execute then EditDirs.Text:= FileName; end; end.
unit RegUtils; // Copyright (c) 1998 Jorge Romero Gomez, Merchise interface uses Windows, SysUtils, Classes; // Use this for a centralizing access to your registry settings // Whenever you need the registry path for your application, call AppRegistryPath // You will need to include a string resource with this ID in your executable, signaling // the needed path, as in: 'Software\MyCompany\MyApp\Current Version\' const idAppRegistryPath = 54321; function AppRegistryPath : string; // Registry access goodies type PRegistryKey = ^TRegistryKey; TRegistryKey = array[0..MAX_PATH] of char; function GetReadableKey( Key : HKEY; const Path : string ) : HKEY; function GetWritableKey( Key : HKEY; const Path : string ) : HKEY; function CreateWritableKey( Key : HKEY; const Path : string ) : HKEY; function GetRegValue( const Key : HKEY; const Path : string ) : string; procedure SetRegValue( Key : HKEY; const Path : string; const Value : string ); // CLASSES_ROOT: function GetExtensionClassKey( const Extension, ClassName : string; var ExtKey : HKEY ) : boolean; // Register executable so we can later run it without specifying a path procedure RegisterExecutable; // Also register a path for it (like in MS-DOS). Use it if you don't store your DLLs neither // in WINDOWS\SYSTEM nor your own folder (let's say you do it in \Program Files\MyApp\System) procedure RegisterExecutablePath( const Path : string ); // Registry goodies procedure SaveStringsToRegKey( Strings : TStrings; Key : HKEY; const Path : string ); function LoadStringsFromRegKey( Strings : TStrings; Key : HKEY; const Path : string ) : TStrings; var fAppRegistryPath : string; implementation procedure SaveStringsToRegKey( Strings : TStrings; Key : HKEY; const Path : string ); var i : integer; ListKey : HKEY; begin RegDeleteKey( Key, pchar( Path ) ); ListKey := CreateWritableKey( Key, Path ); try with Strings do for i := 0 to Count - 1 do SetRegValue( ListKey, IntToStr( i ), Strings[i] ); finally RegCloseKey( ListKey ); end; end; function LoadStringsFromRegKey( Strings : TStrings; Key : HKEY; const Path : string ) : TStrings; var i : integer; ListKey : HKEY; ValueType : longint; NameSize : longint; Name : array[0..MAX_PATH] of char; begin Result := Strings; with Result do begin Clear; ListKey := GetReadableKey( Key, Path ); try if ListKey <> 0 then begin i := 0; NameSize := sizeof( Name ); while ( RegEnumValue( ListKey, i, Name, NameSize, nil, @ValueType, nil, nil ) = NO_ERROR ) do begin inc( i ); if ValueType = REG_SZ then try Add( GetRegValue( ListKey, Name ) ); except end; NameSize := sizeof( Name ); end; end; finally RegCloseKey( ListKey ); end; end; end; function AppRegistryPath : string; begin Result := fAppRegistryPath; assert( ( Result <> '' ), 'You have not included the string resource for AppRegistryPath!! (' + IntToStr( idAppRegistryPath ) + ' = ''Software\MyCompany\MyApp\Current Version\'')' ); assert( ( Result[length( Result )] = '\' ), 'You must terminate the AppRegistryPath string resource with a backslash (as in ''Software\MyCompany\MyApp\Current Version\'')' ); end; procedure RegisterExecutablePath( const Path : string ); const keyAppPaths = 'Software\Microsoft\Windows\Current Version\App Paths\'; var ExeName : string; PathKey : HKEY; begin ExeName := LowerCase( ExtractFilename( ParamStr( 0 ) ) ); PathKey := GetWritableKey( HKEY_LOCAL_MACHINE, keyAppPaths + ExeName ); SetRegValue( PathKey, '', ParamStr( 0 ) ); if Path <> '' then SetRegValue( PathKey, 'Path', Path ); end; procedure RegisterExecutable; begin RegisterExecutablePath( '' ); end; function GetReadableKey( Key : HKEY; const Path : string ) : HKEY; begin if RegOpenKeyEx( Key, pchar( Path ), 0, KEY_EXECUTE, Result ) <> ERROR_SUCCESS then Result := 0; end; function CreateWritableKey( Key : HKEY; const Path : string ) : HKEY; begin if RegCreateKeyEx( Key, pchar( Path ), 0, nil, REG_OPTION_NON_VOLATILE, KEY_WRITE or KEY_EXECUTE, nil, Result, nil ) <> ERROR_SUCCESS then Result := 0; end; function GetWritableKey( Key : HKEY; const Path : string ) : HKEY; begin if RegOpenKeyEx( Key, pchar( Path ), 0, KEY_WRITE or KEY_EXECUTE, Result ) <> ERROR_SUCCESS then Result := 0; end; function GetRegValue( const Key : HKEY; const Path : string ) : string; var KeySize : longint; KeyType : longint; begin KeySize := 0; if RegQueryValueEx( Key, pchar( Path ), nil, nil, nil, @KeySize ) = ERROR_SUCCESS then begin if KeySize <= 1 then Result := '' else begin SetLength( Result, KeySize - 1 ); RegQueryValueEx( Key, pchar( Path ), nil, @KeyType, pbyte( pchar(Result) ), @KeySize ); end; end else Result := ''; end; procedure SetRegValue( Key : HKEY; const Path : string; const Value : string ); begin RegSetValueEx( Key, pchar( Path ), 0, REG_SZ, pchar( Value ), length( Value ) + 1 ); end; // CLASSES_ROOT: function GetExtensionClassKey( const Extension, ClassName : string; var ExtKey : HKEY ) : boolean; begin Result := ( ( ClassName <> '' ) and ( RegOpenKey( HKEY_CLASSES_ROOT, pchar( ClassName ), ExtKey ) = ERROR_SUCCESS ) ) or ( RegOpenKey( HKEY_CLASSES_ROOT, pchar( Extension ), ExtKey ) = ERROR_SUCCESS ) end; initialization fAppRegistryPath := LoadStr( idAppRegistryPath ); end.
{14. Realizar una solución ​modularizada para el ejercicio 5 de la práctica 2 que plantea lo siguiente: ​Realizar un programa que lea información de 200 productos de un supermercado. De cada producto se lee código y precio (cada código es un número entre 1 y 200). Informar en pantalla: - Los códigos de los dos productos más baratos. - La cantidad de productos de más de 16 pesos con código par. ​ } program ejercicio4; const Df = 5; //200 type rangoCodigo = 1..200; procedure masBaratos(precio: Real; codigo: rangoCodigo; var min1:Real; var min2: Real; var codmin1: Integer; var codmin2:Integer); begin if precio <= min1 then begin min2:= min1; codmin2:= codmin1; min1:= precio; codmin1:= codigo; end else if precio <= min2 then begin min2:= precio; codmin2:= codigo; end; end; var codigo: rangoCodigo; precio,min1, min2: Real; codmin1, codmin2, i, cont: Integer; begin min1:=9999; min2:=9999; codmin1:=0; codmin2:=0; cont:= 0; for i := 1 to Df do begin write('Ingrse el CODIGO DEL PRODUCTO: '); readln(codigo); write('Ingrese el PRECIO DEL PRODUCTO: '); readln(precio); writeln('------------------------------'); masBaratos(precio, codigo, min1, min2, codmin1, codmin2); if (precio > 16) and ((codigo mod 2) = 0) then cont:= cont + 1; end; writeln('Los codigos de los dos productos mas baratos son: ', codmin1, ' y ', codmin2); readln(); end.
object fmAutoTodoDone: TfmAutoTodoDone Left = 341 Top = 244 BorderIcons = [] BorderStyle = bsDialog Caption = 'Comment Empty Code Blocks' ClientHeight = 80 ClientWidth = 359 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poScreenCenter DesignSize = ( 359 80) PixelsPerInch = 96 TextHeight = 13 object lblMesssage: TLabel Left = 8 Top = 16 Width = 270 Height = 13 Caption = '%d comments have been inserted in empty code blocks.' end object btnOK: TButton Left = 278 Top = 47 Width = 75 Height = 25 Anchors = [akRight, akBottom] Cancel = True Caption = 'OK' Default = True ModalResult = 1 TabOrder = 0 end object chkDontShowAgain: TCheckBox Left = 8 Top = 55 Width = 263 Height = 17 Anchors = [akLeft, akRight, akBottom] Caption = 'Do not show this message again' TabOrder = 1 end end
unit aeIndexBuffer; interface uses windows, classes, types, dglOpenGL, aeLoggingManager; type TaeIndexBuffer = class private // opengl buffer ID for this data _gpuBufferID: Cardinal; _data: Array of Word; _index: Cardinal; _critsect: TRTLCriticalSection; public constructor Create; destructor Destroy; override; /// <summary> /// Preallocate memory!. /// </summary> procedure PreallocateIndices(nIndices: Cardinal); /// <summary> /// Add a index range to the array. index_count is the number of indices (2 byte chunks). /// </summary> procedure AddIndexRange(i0: pWord; index_count: integer); /// <summary> /// Add a single vertex to the array. /// </summary> procedure AddIndex(i0: Word); /// <summary> /// Clear the index array. /// </summary> procedure Clear; /// <summary> /// Returns true if buffer is empty. /// </summary> function Empty: boolean; /// <summary> /// Reduces the capacity to the actual length. Cuts of excess space that is not used. /// </summary> procedure Pack; /// <summary> /// Returns number of indices in this buffer. /// </summary> function Count: Cardinal; /// <summary> /// Gets the OpenGL Buffer ID. /// </summary> function GetOpenGLBufferID: Cardinal; /// <summary> /// Uploads data to GPU as index data. /// </summary> function UploadToGPU: boolean; /// <summary> /// Deletes data on GPU. /// </summary> function RemoveFromGPU: boolean; /// <summary> /// Returns pointer to start of index array. /// </summary> function GetIndexData: Pointer; /// <summary> /// Returns certain index of index array. /// </summary> function GetIndex(indx: Cardinal): Word; /// <summary> /// Locks this buffer for other threads. /// </summary> procedure Lock; /// <summary> /// Unlocks this buffer for other threads. /// </summary> procedure Unlock; end; implementation { TaeIndexBuffer } procedure TaeIndexBuffer.AddIndex(i0: Word); begin self._data[_index] := i0; inc(_index); end; procedure TaeIndexBuffer.AddIndexRange(i0: pWord; index_count: integer); begin CopyMemory(@self._data[self._index], i0, index_count * 2); inc(self._index, index_count); end; procedure TaeIndexBuffer.Clear; begin self._index := 0; SetLength(self._data, 0); Finalize(self._data); self._data := nil; end; function TaeIndexBuffer.Count: Cardinal; begin Result := self._index; end; constructor TaeIndexBuffer.Create; begin InitializeCriticalSection(self._critsect); self.Clear; self._gpuBufferID := 0; end; destructor TaeIndexBuffer.Destroy; begin self.Clear; self.RemoveFromGPU; DeleteCriticalSection(self._critsect); inherited; end; function TaeIndexBuffer.Empty: boolean; begin Result := self._index = 0; end; function TaeIndexBuffer.GetIndex(indx: Cardinal): Word; begin Result := self._data[indx]; end; function TaeIndexBuffer.GetIndexData: Pointer; begin Result := @self._data[0]; end; function TaeIndexBuffer.GetOpenGLBufferID: Cardinal; begin Result := self._gpuBufferID; end; procedure TaeIndexBuffer.Lock; begin EnterCriticalSection(self._critsect); end; procedure TaeIndexBuffer.Pack; begin SetLength(self._data, self._index); end; procedure TaeIndexBuffer.PreallocateIndices(nIndices: Cardinal); begin SetLength(self._data, nIndices); end; function TaeIndexBuffer.RemoveFromGPU: boolean; begin if (self._gpuBufferID > 0) then begin glDeleteBuffers(1, @self._gpuBufferID); self._gpuBufferID := 0; Result := true; end else begin AE_LOGGING.AddEntry('TaeIndexBuffer.RemoveFromGPU() : Attempt to delete a non-existing buffer! Ignored.', AE_LOG_MESSAGE_ENTRY_TYPE_NOTICE); Result := false; end; end; procedure TaeIndexBuffer.Unlock; begin LeaveCriticalSection(self._critsect); end; function TaeIndexBuffer.UploadToGPU: boolean; begin // if buffer object is still 0, we need to create one first! if (self._gpuBufferID = 0) then begin // create a buffer object glGenBuffers(1, @self._gpuBufferID); // mark buffer as active glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._gpuBufferID); // upload data glBufferData(GL_ELEMENT_ARRAY_BUFFER, self._index * 2, @self._data[0], GL_STATIC_DRAW); Result := true; end else begin AE_LOGGING.AddEntry('TaeIndexBuffer.UploadToGPU() : Attempt to overwrite existing buffer with a new one!', AE_LOG_MESSAGE_ENTRY_TYPE_ERROR); Result := false; end; end; end.
unit Bird.Socket.Connection; interface uses IdContext, Bird.Socket.Consts, Bird.Socket.Helpers, System.JSON, System.Generics.Collections, System.SysUtils; type TBirdSocketConnection = class private FIdContext: TIdContext; public constructor Create(const AIdContext: TIdContext); function WaitMessage: string; function IPAdress: string; function Id: Integer; function CheckForDataOnSource(const ATimeOut: Integer): Boolean; function Connected: Boolean; function IsEquals(const AIdContext: TIdContext): Boolean; procedure Send(const AMessage: string); overload; procedure Send(const ACode: Integer; const AMessage: string); overload; procedure Send(const ACode: Integer; const AMessage: string; const AValues: array of const); overload; procedure Send(const AJSONObject: TJSONObject; const AOwns: Boolean = True); overload; procedure SendFile(const AFile: string); overload; end; TBirds = class private FListLocked: Boolean; FItems: TList<TBirdSocketConnection>; public constructor Create; property Items: TList<TBirdSocketConnection> read FItems write FItems; function LockList: TList<TBirdSocketConnection>; function Last: TBirdSocketConnection; procedure Add(const ABird: TBirdSocketConnection); procedure Remove(const ABird: TBirdSocketConnection); procedure UnLockList; destructor Destroy; override; end; implementation function TBirdSocketConnection.CheckForDataOnSource(const ATimeOut: Integer): Boolean; begin if (not Assigned(FIdContext)) or (not Assigned(FIdContext.Connection)) or (not Assigned(FIdContext.Connection.IOHandler)) then Exit(False); Result := FIdContext.Connection.IOHandler.CheckForDataOnSource(ATimeOut); end; function TBirdSocketConnection.Connected: Boolean; begin if (not Assigned(FIdContext)) or (not Assigned(FIdContext.Connection)) then Exit(False); Result := FIdContext.Connection.Connected; end; constructor TBirdSocketConnection.Create(const AIdContext: TIdContext); begin FIdContext := AIdContext; end; function TBirdSocketConnection.IsEquals(const AIdContext: TIdContext): Boolean; begin if (not Assigned(FIdContext)) then Exit(False); Result := (FIdContext = AIdContext); end; procedure TBirdSocketConnection.Send(const AMessage: string); begin if Assigned(FIdContext) and Assigned(FIdContext.Connection) and Assigned(FIdContext.Connection.IOHandler) then FIdContext.Connection.IOHandler.Send(AMessage); end; procedure TBirdSocketConnection.Send(const ACode: Integer; const AMessage: string); begin if Assigned(FIdContext) and Assigned(FIdContext.Connection) and Assigned(FIdContext.Connection.IOHandler) then FIdContext.Connection.IOHandler.Send(ACode, AMessage); end; procedure TBirdSocketConnection.Send(const ACode: Integer; const AMessage: string; const AValues: array of const); begin if Assigned(FIdContext) and Assigned(FIdContext.Connection) and Assigned(FIdContext.Connection.IOHandler) then FIdContext.Connection.IOHandler.Send(ACode, AMessage, AValues); end; function TBirdSocketConnection.ID: Integer; begin Result := Integer(@FIdContext); end; function TBirdSocketConnection.IPAdress: string; begin if (not Assigned(FIdContext)) or (not Assigned(FIdContext.Connection)) or (not Assigned(FIdContext.Connection.Socket)) or (not Assigned(FIdContext.Connection.Socket.Binding)) then Exit(EmptyStr); Result := FIdContext.Connection.Socket.Binding.PeerIP; end; procedure TBirdSocketConnection.Send(const AJSONObject: TJSONObject; const AOwns: Boolean); begin if Assigned(FIdContext) and Assigned(FIdContext.Connection) and Assigned(FIdContext.Connection.IOHandler) then FIdContext.Connection.IOHandler.Send(AJSONObject, AOwns); end; procedure TBirdSocketConnection.SendFile(const AFile: string); begin if Assigned(FIdContext) and Assigned(FIdContext.Connection) and Assigned(FIdContext.Connection.IOHandler) then FIdContext.Connection.IOHandler.SendFile(AFile); end; function TBirdSocketConnection.WaitMessage: string; begin if (not Assigned(FIdContext)) or (not Assigned(FIdContext.Connection)) or (not Assigned(FIdContext.Connection.IOHandler)) then Exit(EmptyStr); FIdContext.Connection.IOHandler.CheckForDataOnSource(TIMEOUT_DATA_ON_SOURCE); Result := FIdContext.Connection.IOHandler.ReadString; end; procedure TBirds.Add(const ABird: TBirdSocketConnection); begin LockList.Add(ABird); UnLockList; end; constructor TBirds.Create; begin FItems := TList<TBirdSocketConnection>.Create; end; destructor TBirds.Destroy; begin FItems.Free; inherited; end; function TBirds.Last: TBirdSocketConnection; begin Result := LockList.Last; UnLockList; end; function TBirds.LockList: TList<TBirdSocketConnection>; begin while FListLocked do begin Sleep(100); Continue; end; FListLocked := True; Result := FItems; end; procedure TBirds.Remove(const ABird: TBirdSocketConnection); begin LockList; FItems.Remove(ABird); UnLockList; end; procedure TBirds.UnLockList; begin FListLocked := False; end; end.
unit urlEncodeDecode; { URL Encoder/Decoder based on Rosetta Code challenge for encoding/decoding https://rosettacode.org/wiki/URL_decoding https://rosettacode.org/wiki/URL_encoding Author - Marcus Fernstrom License - Apache 2.0 Version - 0.1 } {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs, strutils; function urlDecode(data: String):AnsiString; function urlEncode(data: string):AnsiString; implementation function urlDecode(data: String): AnsiString; var ch: Char; pos, skip: Integer; begin pos := 0; skip := 0; Result := ''; for ch in data do begin if skip = 0 then begin if (ch = '%') and (pos < data.length -2) then begin skip := 2; Result := Result + AnsiChar(Hex2Dec('$' + data[pos+2] + data[pos+3])); end else begin Result := Result + ch; end; end else begin skip := skip - 1; end; pos := pos +1; end; end; function urlEncode(data: string): AnsiString; var ch: AnsiChar; begin Result := ''; for ch in data do begin if ((Ord(ch) < 65) or (Ord(ch) > 90)) and ((Ord(ch) < 97) or (Ord(ch) > 122)) then begin Result := Result + '%' + IntToHex(Ord(ch), 2); end else Result := Result + ch; end; end; end.
unit dcNumEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, dcEdit; type TdcNumEdit = class(TdcEdit) private FEditMask: string; procedure SetEditMask(const Value: string); { Private declarations } protected { Protected declarations } public { Public declarations } constructor create(AOwner:TComponent);override; published { Published declarations } property EditMask:string read FEditMask write SetEditMask; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Data Entry', [TdcNumEdit]); end; { TdcNumEdit } constructor TdcNumEdit.create(AOwner: TComponent); begin inherited create(AOwner); end; procedure TdcNumEdit.SetEditMask(const Value: string); begin FEditMask := Value; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Math, Buttons; type TfrmDaagInkm = class(TForm) lblInkomste: TLabel; gbpAantekentyd: TGroupBox; edtUurAan: TEdit; edtMinAan: TEdit; lblUurAan: TLabel; lblMinAan: TLabel; gbpAftekentyd: TGroupBox; lblUurAf: TLabel; lblMinAf: TLabel; edtUurAf: TEdit; edtMinAf: TEdit; btnBereken: TButton; brnReset_Waardes: TButton; lblHvlKliente: TLabel; lblInkmVDDag: TLabel; lblGemidInkmPSes: TLabel; lblKlientTyd: TLabel; lblKosteVSes: TLabel; btnResetAles: TButton; bmbClose: TBitBtn; procedure btnBerekenClick(Sender: TObject); procedure brnReset_WaardesClick(Sender: TObject); procedure btnResetAlesClick(Sender: TObject); procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmDaagInkm: TfrmDaagInkm; sHvlKlient, sInkmVDag, sGemidInkmPSes, sKlientTyd, sKosteVSes : string; iKliente, iInkVDag, iGemidInkPSes : integer; implementation {$R *.dfm} procedure TfrmDaagInkm.btnBerekenClick(Sender: TObject); var iUurAan, iMinAan, iUurAf, iMinAf, iKostePUur, iUurTyd, iMinTyd, iTyd, iKosteVSes, iGemidInkmPSes : integer; begin iKostePUur := 25; iUurAan := StrToInt(edtUurAan.Text); iMinAan := StrToInt(edtMinAan.Text); iUurAf := StrToInt(edtUurAf.Text); iMinAf := StrToInt(edtMinAf.Text); Inc(iKliente); iUurAan := iUurAan*60; iUurAf := iUurAf*60; iTyd := iUurAf - iUurAan + iMinAf - iMinAan; iUurTyd := iTyd div 60; iMinTyd := iTyd mod 60; iKosteVSes := ceil(iTyd/60); iKosteVSes := iKosteVSes * iKostePUur; iInkVDag := iInkVDag + iKosteVSes; iGemidInkmPSes := ceil(iInkVDag/iKliente); sHvlKlient := 'Hoveelheid kliente: ' + IntToStr(iKliente); lblHvlKliente.Caption := sHvlKlient ; sInkmVDag := 'Inkomste vir die dag: R' + IntToStr(iInkVDag); lblInkmVDDag.Caption := sInkmVDag; sGemidInkmPSes := 'Gemiddelde inkomste per sessie: R' + IntToStr(iGemidInkmPSes); //hoor MNR lblGemidInkmPSes.Caption := sGemidInkmPSes; sKlientTyd := 'Hierdie klient was besig vir: ' + IntToStr(iUurTyd) + ' ure en ' + IntToStr(iMinTyd) + ' minute.'; lblKlientTyd.caption := sKlientTyd ; sKosteVSes := 'Koste van sessie: R' + IntToStr(iKosteVSes); lblKosteVSes.Caption := sKosteVSes; edtUurAan.clear; edtMinAan.clear; edtUurAf.clear; edtMinAf.clear; edtUurAan.SetFocus ; end; procedure TfrmDaagInkm.brnReset_WaardesClick(Sender: TObject); begin edtUurAan.clear; edtMinAan.clear; edtUurAf.clear; edtMinAf.clear; edtUurAan.SetFocus ; sKlientTyd := 'Hierdie klient was besig vir:'; lblKlientTyd.caption := sKlientTyd ; sKosteVSes := 'Koste van sessie:'; lblKosteVSes.Caption := sKosteVSes; end; procedure TfrmDaagInkm.btnResetAlesClick(Sender: TObject); begin edtUurAan.clear; edtMinAan.clear; edtUurAf.clear; edtMinAf.clear; edtUurAan.SetFocus ; sHvlKlient := 'Hoveelheid kliente:'; lblHvlKliente.Caption := sHvlKlient ; sInkmVDag := 'Inkomste vir die dag:'; lblInkmVDDag.Caption := sInkmVDag; sGemidInkmPSes := 'Gemiddelde inkomste per sessie:'; //hoor MNR lblGemidInkmPSes.Caption := sGemidInkmPSes; sKlientTyd := 'Hierdie klient was besig vir:'; lblKlientTyd.caption := sKlientTyd ; sKosteVSes := 'Koste van sessie:'; lblKosteVSes.Caption := sKosteVSes; end; procedure TfrmDaagInkm.FormActivate(Sender: TObject); begin edtUurAan.setfocus; end; end.
(* * 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 Initial Developer of this code is John Hansen. * Portions created by John Hansen are Copyright (C) 2009 John Hansen. * All Rights Reserved. * *) unit uNXTClasses; {$B-} interface uses Classes, Contnrs, SysUtils, uNXTConstants, uPreprocess, uNBCCommon; type TCompilerStatusChangeEvent = procedure(Sender : TObject; const StatusMsg : string; const bDone : boolean) of object; NXTInstruction = record Encoding : TOpCode; CCType : Byte; Arity : Byte; Name : string; end; type TAsmLineType = (altBeginDS, altEndDS, altBeginClump, altEndClump, altCode, altVarDecl, altTypeDecl, altBeginStruct, altEndStruct, altBeginSub, altEndSub, altCodeDepends, altInvalid); TAsmLineTypes = set of TAsmLineType; TMainAsmState = (masDataSegment, masCodeSegment, masClump, masClumpSub, masStruct, masDSClump, masStructDSClump, masDSClumpSub, masStructDSClumpSub, masBlockComment); PRXEHeader = ^RXEHeader; RXEHeader = record FormatString : array[0..13] of Char; // add null terminator at end Skip : Byte; // second 0 Version : Byte; DSCount : Word; DSSize : Word; DSStaticSize : Word; DSDefaultsSize : Word; DynDSDefaultsOffset : Word; DynDSDefaultsSize : Word; MemMgrHead : Word; MemMgrTail : Word; DVArrayOffset : Word; ClumpCount : Word; CodespaceCount : Word; end; DSTocEntry = record TypeDesc : Byte; Flags : Byte; DataDesc: Word; Size : Word; RefCount: Word; end; DSTocEntries = array of DSTocEntry; // dynamic array DopeVector = record offset : Word; elemsize : Word; count : Word; backptr : Word; link : Word; end; DopeVectors = array of DopeVector; // dynamic array ClumpRecord = record FireCount : Byte; DependentCount : Byte; CodeStart : Word; end; ClumpRecords = array of ClumpRecord; // dynamic array TSTTFuncType = function(const stype : string; bUseCase : Boolean = false) : TDSType; const BytesPerType : array[TDSType] of Byte = (4, 1, 1, 2, 2, 4, 4, 2, 4, 4, 4); NOT_AN_ELEMENT = $FFFF; type TDSBase = class; TDSData = class; TDataspaceEntry = class(TCollectionItem) private fThreadNames : TStrings; fDataType: TDSType; fIdentifier: string; fDefValue: Cardinal; fAddress: Word; fSubEntries: TDSBase; fArrayValues: TObjectList; fDSID: integer; fArrayMember: boolean; fRefCount : integer; fTypeName: string; function GetValue(idx: integer): Cardinal; function GetArrayInit: string; procedure SetSubEntries(const Value: TDSBase); function GetDataTypeAsString: string; function GetFullPathIdentifier: string; function GetDSBase: TDSBase; procedure SetArrayMember(const Value: boolean); procedure SetIdentifier(const Value: string); function GetInUse: boolean; function GetRefCount: integer; function GetClusterInit: string; function GetInitializationString: string; function GetArrayBaseType: TDSType; function GetIsArray: boolean; protected procedure AssignTo(Dest: TPersistent); override; procedure SaveToDynamicDefaults(aDS : TDSData; const cnt, doffset : integer); public constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure SaveToStream(aStream : TStream); procedure SaveToStrings(aStrings : TStrings; bDefine : boolean = false; bInCluster : boolean = false); procedure LoadFromStream(aStream : TStream); procedure AddValue(aValue : Cardinal); function AddValuesFromString(Calc : TNBCExpParser; sargs : string) : TDSType; function ValueCount : Word; function ArrayElementSize(bPad : boolean = true) : Word; function ElementSize(bPad : boolean = true) : Word; procedure IncRefCount; procedure DecRefCount; procedure AddThread(const aThreadName : string); function ThreadCount : integer; property DSBase : TDSBase read GetDSBase; property DSID : integer read fDSID write fDSID; property Identifier : string read fIdentifier write SetIdentifier; property TypeName : string read fTypeName write fTypeName; property DataType : TDSType read fDataType write fDataType; property DataTypeAsString : string read GetDataTypeAsString; property DefaultValue : Cardinal read fDefValue write fDefValue; property Address : Word read fAddress write fAddress; property SubEntries : TDSBase read fSubEntries write SetSubEntries; // used to store array types and cluster structure property Values[idx : integer] : Cardinal read GetValue; // used to store array default values property FullPathIdentifier : string read GetFullPathIdentifier; property InitializationString : string read GetInitializationString; property ArrayMember : boolean read fArrayMember write SetArrayMember; property BaseDataType : TDSType read GetArrayBaseType; property IsArray : boolean read GetIsArray; property InUse : boolean read GetInUse; property RefCount : integer read GetRefCount; end; TDSData = class private fDSStaticSize : integer; public TOC : DSTocEntries; TOCNames : array of string; StaticDefaults : array of byte; DynamicDefaults : array of byte; DopeVecs : DopeVectors; Head : Word; Tail : Word; constructor Create; function DynDSDefaultsOffset : Word; function DynDSDefaultsSize : Word; function DSCount : Word; function DSStaticSize : Word; function DVArrayOffset : Word; procedure SaveToStream(aStream : TStream); procedure SaveToSymbolTable(aStrings : TStrings); end; TDSBaseSortCompare = function(List: TDSBase; Index1, Index2: Integer): Integer; EDuplicateDataspaceEntry = class(Exception) public constructor Create(DE : TDataspaceEntry); end; // TDataspaceEntry = class; TDSBase = class(TCollection) private fParent: TPersistent; procedure ExchangeItems(Index1, Index2: Integer); function GetRoot: TDataspaceEntry; protected fEntryIndex : TStringList; function GetItem(Index: Integer): TDataspaceEntry; procedure SetItem(Index: Integer; Value: TDataspaceEntry); procedure AssignTo(Dest : TPersistent); override; procedure QuickSort(L, R: Integer; SCompare: TDSBaseSortCompare); function ResolveNestedArrayAddress(DS : TDSData; DV : DopeVector) : TDataspaceEntry; public constructor Create; virtual; destructor Destroy; override; function Add: TDataspaceEntry; function Insert(Index: Integer): TDataspaceEntry; function IndexOfName(const name : string) : integer; function FullPathName(DE : TDataspaceEntry) : string; function FindEntryByAddress(Addr : Word) : TDataspaceEntry; virtual; function FindEntryByFullName(const path : string) : TDataspaceEntry; virtual; function FindEntryByName(name : string) : TDataspaceEntry; virtual; procedure Sort; virtual; procedure CheckEntry(DE : TDataspaceEntry); property Items[Index: Integer]: TDataspaceEntry read GetItem write SetItem; default; property Parent : TPersistent read fParent write fParent; property Root : TDataspaceEntry read GetRoot; end; TDataDefs = class(TDSBase); TDataspace = class(TDSBase) private function GetCaseSensitive: boolean; procedure SetCaseSensitive(const Value: boolean); protected fVectors : DopeVectors; fMMTail: Word; fMMHead: Word; fDSIndexMap : TStringList; fDSList : TObjectList; function GetVector(index: Integer): DopeVector; protected procedure LoadArrayValuesFromDynamicData(DS : TDSData); function FinalizeDataspace(DS : TDSBase; addr : Word) : Word; procedure ProcessDopeVectors(aDS : TDSData; addr : Word); procedure ProcessArray(DE : TDataspaceEntry; aDS : TDSData; var doffset : integer); public constructor Create; override; destructor Destroy; override; procedure Compact; procedure SaveToStream(aStream : TStream); procedure SaveToStrings(aStrings : TStrings); procedure LoadFromStream(aStream : TStream); procedure LoadFromDSData(aDS : TDSData); procedure SaveToDSData(aDS : TDSData); function IndexOfEntryByAddress(Addr : Word) : Integer; function FindEntryByFullName(const path : string) : TDataspaceEntry; override; function FindEntryAndAddReference(const path : string) : TDataspaceEntry; procedure RemoveReferenceIfPresent(const path : string); procedure AddReference(DE : TDataspaceEntry); procedure RemoveReference(DE : TDataspaceEntry); function DataspaceIndex(const ident : string) : Integer; property Vectors[index : Integer] : DopeVector read GetVector; property MMHead : Word read fMMHead write fMMHead; property MMTail : Word read fMMTail write fMMTail; property CaseSensitive : boolean read GetCaseSensitive write SetCaseSensitive; end; ClumpDepArray = array of Byte; TClumpData = class public CRecs : ClumpRecords; ClumpDeps : ClumpDepArray; procedure SaveToStream(aStream : TStream); end; TRXEHeader = class public Head : RXEHeader; end; CodeArray = array of Word; TCodeSpaceAry = class public Code : CodeArray; function CodespaceCount : Word; procedure SaveToStream(aStream : TStream); end; TAsmArgument = class(TCollectionItem) private fValue: string; fDSID: integer; procedure SetValue(const Value: string); public property Value : string read fValue write SetValue; function IsQuoted(delim : char) : boolean; property DSID : integer read fDSID; function Evaluate(Calc : TNBCExpParser) : Extended; end; TOnNameToDSID = procedure(const aName : string; var aId : integer) of object; TAsmArguments = class(TCollection) private function GetItem(Index: Integer): TAsmArgument; procedure SetItem(Index: Integer; const Value: TAsmArgument); function GetAsString: string; protected procedure AssignTo(Dest: TPersistent); override; public constructor Create; function Add: TAsmArgument; function Insert(Index: Integer): TAsmArgument; property Items[Index: Integer]: TAsmArgument read GetItem write SetItem; default; property AsString : string read GetAsString; end; TClumpCode = class; TClump = class; TCodeSpace = class; TRXEProgram = class; TAsmLine = class(TCollectionItem) private fMacroExpansion: boolean; function GetAsString: string; procedure SetAsString(const Value: string); function GetClump: TClump; function GetCodeSpace: TCodeSpace; function GetPC: word; function GetOptimizable: boolean; protected fComment: string; fLabel: string; fArgs: TAsmArguments; fOpCode: TOpcode; fLineNum: integer; // fPC: word; fInstrSize : integer; fStartAddress : integer; fCode : CodeArray; fArity : Byte; fCC : Byte; fsop : ShortInt; fIsSpecial : boolean; fSpecialStr : string; procedure SetArgs(const Value: TAsmArguments); function GetClumpCode: TClumpCode; function CanBeShortOpEncoded : boolean; procedure FinalizeASMInstrSize; procedure FinalizeCode; procedure FinalizeArgs(bResolveDSIDs : Boolean); procedure FixupFinClump; function IsLabel(const name : string; var aID : integer) : boolean; procedure HandleNameToDSID(const name : string; var aId : integer); procedure RemoveVariableReference(const arg : string; const idx : integer); procedure RemoveVariableReferences; function FirmwareVersion : word; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure AddArgs(sargs : string); function InstructionSize : integer; procedure SaveToCode(var Store : CodeArray); property LineLabel : string read fLabel write fLabel; property Command : TOpcode read fOpCode write fOpCode; property Args : TAsmArguments read fArgs write SetArgs; property Comment : string read fComment write fComment; property LineNum : integer read fLineNum write fLineNum; property ProgramCounter : word read GetPC; property IsPartOfMacroExpansion : boolean read fMacroExpansion; property IsSpecial : boolean read fIsSpecial; // property ProgramCounter : word read fPC write fPC; property ClumpCode : TClumpCode read GetClumpCode; property Clump : TClump read GetClump; property CodeSpace : TCodeSpace read GetCodeSpace; property StartAddress : integer read fStartAddress; property AsString : string read GetAsString write SetAsString; property Optimizable : boolean read GetOptimizable; end; TClumpCode = class(TCollection) private fOnNameToDSID: TOnNameToDSID; fClump : TClump; protected function GetItem(Index: Integer): TAsmLine; procedure SetItem(Index: Integer; const Value: TAsmLine); procedure HandleNameToDSID(const aName : string; var aId : integer); procedure FixupFinalization; public constructor Create(aClump : TClump); destructor Destroy; override; function Add: TAsmLine; property Items[Index: Integer]: TAsmLine read GetItem write SetItem; default; property Clump : TClump read fClump; property OnNameToDSID : TOnNameToDSID read fOnNameToDSID write fOnNameToDSID; end; TClump = class(TCollectionItem) private fName: string; fClumpCode: TClumpCode; fIsSub: boolean; fDatasize : integer; fCode : CodeArray; fFilename: string; fLastLine: integer; function GetUpstream(aIndex: integer): string; function GetCodeSpace: TCodeSpace; function GetDataSize: Word; function GetStartAddress: Word; function GetDownstream(aIndex: integer): string; function GetDownCount: Byte; function GetUpCount: integer; function GetFireCount: Word; function GetCaseSensitive: boolean; function GetInUse: boolean; procedure RemoveOrNOPLine(AL, ALNext: TAsmLine; const idx: integer); function GetCallerCount: Byte; function GetIsMultithreaded: boolean; protected fLabelMap : TStringList; fUpstream : TStringList; fDownstream : TStringList; fCallers : TStringList; fRefCount : integer; procedure FinalizeClump; procedure HandleNameToDSID(const aname : string; var aId : integer); procedure RemoveReferences; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure Optimize(const level : Integer); procedure OptimizeMutexes; procedure RemoveUnusedLabels; procedure AddClumpDependencies(const opcode, args : string); procedure AddDependant(const clumpName : string); procedure AddAncestor(const clumpName : string); procedure AddCaller(const clumpName : string); procedure AddLabel(const lbl : string; Line : TAsmLine); function IndexOfLabel(const lbl : string) : integer; function AsmLineFromLabelIndex(const idx : integer) : TAsmLine; procedure IncRefCount; procedure DecRefCount; procedure SaveToCode(var Store : CodeArray); procedure SaveDependencies(var Store : ClumpDepArray); property CodeSpace : TCodeSpace read GetCodeSpace; property StartAddress : Word read GetStartAddress; property FireCount : Word read GetFireCount; property DataSize : Word read GetDataSize; property Name : string read fName write fName; property UpstreamClumps[aIndex : integer] : string read GetUpstream; property UpstreamCount : integer read GetUpCount; property DownstreamClumps[aIndex : integer] : string read GetDownstream; property DownstreamCount : Byte read GetDownCount; property CallerCount : Byte read GetCallerCount; property ClumpCode : TClumpCode read fClumpCode; property IsSubroutine : boolean read fIsSub write fIsSub; property CaseSensitive : boolean read GetCaseSensitive; property InUse : boolean read GetInUse; property Filename : string read fFilename write fFilename; property LastLine : integer read fLastLine write fLastLine; property IsMultithreaded : boolean read GetIsMultithreaded; end; TCodeSpace = class(TCollection) private fNXTInstructions : array of NXTInstruction; fOnNameToDSID: TOnNameToDSID; fCalc: TNBCExpParser; fCaseSensitive : Boolean; fDS: TDataspace; fFirmwareVersion: word; function GetCaseSensitive: boolean; procedure SetCaseSensitive(const Value: boolean); procedure BuildReferences; procedure InitializeInstructions; function IndexOfOpcode(op: TOpCode): integer; function OpcodeToStr(const op : TOpCode) : string; procedure SetFirmwareVersion(const Value: word); protected fRXEProg : TRXEProgram; fInitName: string; fAddresses : TObjectList; fFireCounts : TObjectList; fMultiThreadedClumps : TStrings; function GetItem(aIndex: Integer): TClump; procedure SetItem(aIndex: Integer; const aValue: TClump); function GetAddress(aIndex: Integer): Word; function GetFireCount(aIndex: integer): Byte; procedure FinalizeDependencies; procedure FinalizeAddressesAndFireCounts; procedure HandleNameToDSID(const aName : string; var aId : integer); function GetNXTInstruction(const idx : integer) : NXTInstruction; procedure RemoveUnusedLabels; public constructor Create(rp : TRXEProgram; ds : TDataspace); destructor Destroy; override; function Add: TClump; procedure Compact; procedure Optimize(const level : Integer); procedure OptimizeMutexes; procedure SaveToCodeData(aCD : TClumpData; aCode : TCodeSpaceAry); procedure SaveToSymbolTable(aStrings : TStrings); procedure SaveToStrings(aStrings : TStrings); function IndexOf(const aName : string) : integer; procedure AddReferenceIfPresent(aClump : TClump; const aName : string); procedure RemoveReferenceIfPresent(const aName : string); procedure MultiThread(const aName : string); property Items[aIndex: Integer]: TClump read GetItem write SetItem; default; property StartingAddresses[aIndex: Integer] : Word read GetAddress; property FireCounts[aIndex : integer] : Byte read GetFireCount; property InitialClumpName : string read fInitName write fInitName; property Calc : TNBCExpParser read fCalc write fCalc; property OnNameToDSID : TOnNameToDSID read fOnNameToDSID write fOnNameToDSID; property CaseSensitive : boolean read GetCaseSensitive write SetCaseSensitive; property Dataspace : TDataspace read fDS; property FirmwareVersion : word read fFirmwareVersion write SetFirmwareVersion; property RXEProgram : TRXEProgram read fRXEProg; end; TAsmArgType = (aatVariable, aatVarNoConst, aatVarOrNull, aatConstant, aatClumpID, aatLabelID, aatCluster, aatString, aatStringNoConst, aatArray, aatScalar, aatScalarNoConst, aatScalarOrNull, aatMutex, aatTypeName); TOnNBCCompilerMessage = procedure(const msg : string; var stop : boolean) of object; TRXEProgram = class(TPersistent) private fNXTInstructions : array of NXTInstruction; fOnCompMSg: TOnNBCCompilerMessage; fCalc: TNBCExpParser; fCaseSensitive: boolean; fStandardDefines: boolean; fExtraDefines: boolean; fCompVersion: byte; fIncDirs: TStrings; fCompilerOutput : TStrings; fSymbolTable : TStrings; fOptimizeLevel: integer; fReturnRequired: boolean; fDefines: TStrings; fWarningsOff: boolean; fEnhancedFirmware: boolean; fIgnoreSystemFile: boolean; fMaxErrors: word; fFirmwareVersion: word; fOnCompilerStatusChange: TCompilerStatusChangeEvent; fMaxPreProcDepth: word; procedure SetCaseSensitive(const Value: boolean); procedure SetStandardDefines(const Value: boolean); procedure SetExtraDefines(const Value: boolean); procedure SetCompVersion(const Value: byte); procedure SetIncDirs(const Value: TStrings); function GetSymbolTable: TStrings; function GetCurrentFile(bFullPath: boolean): string; function GetCurrentPath: string; procedure SetCurrentFile(const Value: string); procedure CreateReturnerClump(const basename: string); procedure CreateSpawnerClump(const basename: string); procedure SetDefines(const Value: TStrings); procedure LoadSystemFile(S: TStream); procedure SetLineCounter(const Value: integer); procedure SetFirmwareVersion(const Value: word); function IndexOfOpcode(op: TOpCode): integer; procedure InitializeInstructions; procedure ChunkLine(const state: TMainAsmState; namedTypes: TMapList; line: string; bUseCase: boolean; var lbl, opcode, args: string; var lineType: TAsmLineType; var bIgnoreDups: boolean); function DetermineLineType(const state: TMainAsmState; namedTypes: TMapList; op: string; bUseCase: boolean): TAsmLineType; function StrToOpcode(const op: string; bUseCase: boolean = False): TOpCode; function OpcodeToStr(const op: TOpCode): string; protected fDSData : TDSData; fClumpData : TClumpData; fCode : TCodeSpaceAry; fMainStateLast : TMainAsmState; fMainStateCurrent : TMainAsmState; fCurrentFile : string; fCurrentPath : string; fLineCounter : integer; fDD : TDataDefs; fDS : TDataspace; fCS : TCodeSpace; fHeader : RXEHeader; fNamedTypes : TMapList; fConstStrMap : TMapList; fCurrentClump : TClump; fCurrentStruct : TDataspaceEntry; fMsgs : TStrings; fBadProgram : boolean; fProgErrorCount : integer; fClumpUsesWait : boolean; fClumpUsesSign : boolean; fClumpUsesShift : boolean; fAbsCount : integer; fSignCount : integer; fShiftCount : integer; fVarI : integer; fVarJ : integer; fClumpName : string; fSkipCount : integer; fProductVersion : string; fSpawnedThreads : TStrings; fIgnoreDupDefs : boolean; fSpecialFunctions : TObjectList; fIgnoreLines : boolean; procedure DoCompilerStatusChange(const Status : string; const bDone : boolean = False); function GetVersion: byte; procedure SetVersion(const Value: byte); function GetFormat: string; procedure SetFormat(const Value: string); function GetClumpCount: Word; function GetCodespaceCount: Word; function GetDSCount: Word; function GetDSDefaultsSize: Word; function GetDSSize: Word; function GetDVArrayOffset: Word; function GetDynDSDefaultsOffset: Word; function GetDynDSDefaultsSize: Word; function GetMemMgrHead: Word; function GetMemMgrTail: Word; function GetNXTInstruction(const idx : integer) : NXTInstruction; procedure ReportProblem(const lineNo : integer; const fName, line, msg : string; err : boolean); procedure ProcessASMLine(aStrings : TStrings; var idx : integer); function ReplaceSpecialStringCharacters(const line : string) : string; procedure HandleConstantExpressions(AL : TAsmLine); procedure ProcessSpecialFunctions(AL : TAsmLine); procedure HandlePseudoOpcodes(AL : TAsmLine; op : TOpCode{; const args : string}); procedure UpdateHeader; procedure CheckArgs(AL : TAsmLine); procedure DoCompilerCheck(AL : TAsmLine; bIfCheck : boolean); procedure DoCompilerCheckType(AL : TAsmLine); procedure ValidateLabels(aClump : TClump); procedure HandleNameToDSID(const aName : string; var aId : integer); procedure CreateObjects; procedure FreeObjects; procedure InitializeHeader; procedure LoadSpecialFunctions; procedure HandleCalcParserError(Sender: TObject; E: Exception); procedure CreateWaitClump(const basename : string); procedure DefineWaitArgs(const basename : string); procedure DefineShiftArgs(const basename : string); function ReplaceTokens(const line : string) : string; procedure FixupComparisonCodes(Arg : TAsmArgument); procedure DefineVar(aVarName : string; dt :TDSType); procedure RegisterThreadForSpawning(aThreadName : string); procedure ProcessSpawnedThreads; procedure OutputUnusedItemWarnings; procedure CheckMainThread; procedure HandleSpecialFunctionSizeOf(Arg : TAsmArgument; const left, right, name : string); procedure HandleSpecialFunctionIsConst(Arg : TAsmArgument; const left, right, name : string); procedure HandleSpecialFunctionValueOf(Arg : TAsmArgument; const left, right, name : string); procedure HandleSpecialFunctionTypeOf(Arg : TAsmArgument; const left, right, name : string); procedure HandlePreprocStatusChange(Sender : TObject; const StatusMsg : string); property LineCounter : integer read fLineCounter write SetLineCounter; public constructor Create; destructor Destroy; override; procedure Clear; function Parse(aStream : TStream) : string; overload; function Parse(aStrings : TStrings) : string; overload; procedure LoadFromStream(aStream : TStream); function SaveToStream(aStream : TStream) : boolean; function SaveToFile(const filename : string) : boolean; procedure SaveToStrings(aStrings : TStrings); property Calc : TNBCExpParser read fCalc; property IncludeDirs : TStrings read fIncDirs write SetIncDirs; // header properties property FormatString : string read GetFormat write SetFormat; property Version : byte read GetVersion write SetVersion; property DSCount : Word read GetDSCount; property DSSize : Word read GetDSSize; property DSDefaultsSize : Word read GetDSDefaultsSize; property DynDSDefaultsOffset : Word read GetDynDSDefaultsOffset; property DynDSDefaultsSize : Word read GetDynDSDefaultsSize; property MemMgrHead : Word read GetMemMgrHead; property MemMgrTail : Word read GetMemMgrTail; property DVArrayOffset : Word read GetDVArrayOffset; property ClumpCount : Word read GetClumpCount; property CodespaceCount : Word read GetCodespaceCount; // dataspace definitions property property DataDefinitions : TDataDefs read fDD; // dataspace property property Dataspace : TDataspace read fDS; // codespace property property Codespace : TCodeSpace read fCS; property CompilerMessages : TStrings read fMsgs; property SymbolTable : TStrings read GetSymbolTable; property CompilerOutput : TStrings read fCompilerOutput; property CaseSensitive : boolean read fCaseSensitive write SetCaseSensitive; property CurrentFile : string read fCurrentFile write SetCurrentFile; property StandardDefines : boolean read fStandardDefines write SetStandardDefines; property ExtraDefines : boolean read fExtraDefines write SetExtraDefines; property CompilerVersion : byte read fCompVersion write SetCompVersion; property ReturnRequiredInSubroutine : boolean read fReturnRequired write fReturnRequired; property OptimizeLevel : integer read fOptimizeLevel write fOptimizeLevel; property Defines : TStrings read fDefines write SetDefines; property WarningsOff : boolean read fWarningsOff write fWarningsOff; property EnhancedFirmware : boolean read fEnhancedFirmware write fEnhancedFirmware; property FirmwareVersion : word read fFirmwareVersion write SetFirmwareVersion; property IgnoreSystemFile : boolean read fIgnoreSystemFile write fIgnoreSystemFile; property MaxErrors : word read fMaxErrors write fMaxErrors; property MaxPreprocessorDepth : word read fMaxPreProcDepth write fMaxPreProcDepth; property OnCompilerMessage : TOnNBCCompilerMessage read fOnCompMSg write fOnCompMsg; property OnCompilerStatusChange : TCompilerStatusChangeEvent read fOnCompilerStatusChange write fOnCompilerStatusChange; end; TRXEDumper = class private fNXTInstructions : array of NXTInstruction; fOnlyDumpCode: boolean; fFirmwareVersion: word; function TOCNameFromArg(DS : TDSData; const argValue: word): string; procedure SetFirmwareVersion(const Value: word); procedure InitializeInstructions; function IndexOfOpcode(op: TOpCode): integer; protected fHeader : TRXEHeader; fDSData : TDSData; fClumpData : TClumpData; fCode : TCodeSpaceAry; fFilename : string; fAddrList : TStringList; fFixups : TStringList; fTmpDataspace : TDataspace; function GetAddressLine(const str : string) : string; procedure FixupLabelStrings(aStrings : TStrings; const addr, line : integer); procedure OutputByteCodePhaseOne(aStrings : TStrings); procedure OutputDataspace(aStrings: TStrings); procedure OutputBytecode(aStrings: TStrings); procedure OutputClumpBeginEndIfNeeded(CD : TClumpData; const addr : integer; aStrings : TStrings); function ProcessInstructionArg(DS : TDSData; const addr : integer; const op : TOpCode; const argIdx : integer; const argValue : word) : string; function ProcessInstruction(DS : TDSData; CS : TCodeSpaceAry; const addr: integer; aStrings : TStrings): integer; procedure DumpRXEHeader(aStrings : TStrings); procedure DumpRXEDataSpace(aStrings : TStrings); procedure DumpRXEClumpRecords(aStrings : TStrings); procedure DumpRXECodeSpace(aStrings : TStrings); procedure FinalizeRXE; procedure InitializeRXE; function GetNXTInstruction(const idx : integer) : NXTInstruction; public { Public declarations } constructor Create; destructor Destroy; override; procedure LoadFromFile(const aFilename : string); procedure LoadFromStream(aStream : TStream); procedure SaveToFile(const aFilename : string); procedure SaveToStream(aStream : TStream); procedure DumpRXE(aStrings : TStrings); procedure Decompile(aStrings : TStrings); property Filename : string read fFilename write fFilename; property OnlyDumpCode : boolean read fOnlyDumpCode write fOnlyDumpCode; property FirmwareVersion : word read fFirmwareVersion write SetFirmwareVersion; end; const RXEHeaderText = 'FormatString = %0:s'#13#10 + 'Version = %1:d'#13#10 + 'DSCount = %2:d (0x%2:x)'#13#10 + 'DSSize = %3:d (0x%3:x)'#13#10 + 'DSStaticSize = %4:d (0x%4:x)'#13#10 + 'DSDefaultsSize = %5:d (0x%5:x)'#13#10 + 'DynDSDefaultsOffset = %6:d (0x%6:x)'#13#10 + 'DynDSDefaultsSize = %7:d (0x%7:x)'#13#10 + 'MemMgrHead = %8:d (0x%8:x)'#13#10 + 'MemMgrTail = %9:d (0x%9:x)'#13#10 + 'DVArrayOffset = %10:d (0x%10:x)'#13#10 + 'ClumpCount = %11:d (0x%11:x)'#13#10 + 'CodespaceCount = %12:d (0x%12:x)'; const STR_USES = 'precedes'; type TNXTInstructions = array of NXTInstruction; var NXTInstructions : array of NXTInstruction; const StandardOpcodeCount1x = 54; EnhancedOpcodeCount1x = 27; PseudoOpcodeCount1x = 39; NXTInstructionsCount1x = StandardOpcodeCount1x+EnhancedOpcodeCount1x+PseudoOpcodeCount1x; NXTInstructions1x : array[0..NXTInstructionsCount1x-1] of NXTInstruction = ( ( Encoding: OP_ADD ; CCType: 0; Arity: 3; Name: 'add'; ), ( Encoding: OP_SUB ; CCType: 0; Arity: 3; Name: 'sub'; ), ( Encoding: OP_NEG ; CCType: 0; Arity: 2; Name: 'neg'; ), ( Encoding: OP_MUL ; CCType: 0; Arity: 3; Name: 'mul'; ), ( Encoding: OP_DIV ; CCType: 0; Arity: 3; Name: 'div'; ), ( Encoding: OP_MOD ; CCType: 0; Arity: 3; Name: 'mod'; ), ( Encoding: OP_AND ; CCType: 0; Arity: 3; Name: 'and'; ), ( Encoding: OP_OR ; CCType: 0; Arity: 3; Name: 'or'; ), ( Encoding: OP_XOR ; CCType: 0; Arity: 3; Name: 'xor'; ), ( Encoding: OP_NOT ; CCType: 0; Arity: 2; Name: 'not'; ), ( Encoding: OP_CMNT ; CCType: 0; Arity: 2; Name: 'cmnt'; ), ( Encoding: OP_LSL ; CCType: 0; Arity: 3; Name: 'lsl'; ), ( Encoding: OP_LSR ; CCType: 0; Arity: 3; Name: 'lsr'; ), ( Encoding: OP_ASL ; CCType: 0; Arity: 3; Name: 'asl'; ), ( Encoding: OP_ASR ; CCType: 0; Arity: 3; Name: 'asr'; ), ( Encoding: OP_ROTL ; CCType: 0; Arity: 3; Name: 'rotl'; ), ( Encoding: OP_ROTR ; CCType: 0; Arity: 3; Name: 'rotr'; ), ( Encoding: OP_CMP ; CCType: 2; Arity: 3; Name: 'cmp'; ), ( Encoding: OP_TST ; CCType: 1; Arity: 2; Name: 'tst'; ), ( Encoding: OP_CMPSET ; CCType: 2; Arity: 4; Name: 'cmpset'; ), ( Encoding: OP_TSTSET ; CCType: 1; Arity: 3; Name: 'tstset'; ), ( Encoding: OP_INDEX ; CCType: 0; Arity: 3; Name: 'index'; ), ( Encoding: OP_REPLACE ; CCType: 0; Arity: 4; Name: 'replace'; ), ( Encoding: OP_ARRSIZE ; CCType: 0; Arity: 2; Name: 'arrsize'; ), ( Encoding: OP_ARRBUILD ; CCType: 0; Arity: 6; Name: 'arrbuild'; ), ( Encoding: OP_ARRSUBSET ; CCType: 0; Arity: 4; Name: 'arrsubset'; ), ( Encoding: OP_ARRINIT ; CCType: 0; Arity: 3; Name: 'arrinit'; ), ( Encoding: OP_MOV ; CCType: 0; Arity: 2; Name: 'mov'; ), ( Encoding: OP_SET ; CCType: 0; Arity: 2; Name: 'set'; ), ( Encoding: OP_FLATTEN ; CCType: 0; Arity: 2; Name: 'flatten'; ), ( Encoding: OP_UNFLATTEN ; CCType: 0; Arity: 4; Name: 'unflatten'; ), ( Encoding: OP_NUMTOSTRING ; CCType: 0; Arity: 2; Name: 'numtostr'; ), ( Encoding: OP_STRINGTONUM ; CCType: 0; Arity: 5; Name: 'strtonum'; ), ( Encoding: OP_STRCAT ; CCType: 0; Arity: 6; Name: 'strcat'; ), ( Encoding: OP_STRSUBSET ; CCType: 0; Arity: 4; Name: 'strsubset'; ), ( Encoding: OP_STRTOBYTEARR ; CCType: 0; Arity: 2; Name: 'strtoarr'; ), ( Encoding: OP_BYTEARRTOSTR ; CCType: 0; Arity: 2; Name: 'arrtostr'; ), ( Encoding: OP_JMP ; CCType: 0; Arity: 1; Name: 'jmp'; ), ( Encoding: OP_BRCMP ; CCType: 2; Arity: 3; Name: 'brcmp'; ), ( Encoding: OP_BRTST ; CCType: 1; Arity: 2; Name: 'brtst'; ), ( Encoding: OP_SYSCALL ; CCType: 0; Arity: 2; Name: 'syscall'; ), ( Encoding: OP_STOP ; CCType: 0; Arity: 1; Name: 'stop'; ), ( Encoding: OP_FINCLUMP ; CCType: 0; Arity: 2; Name: 'exit'; ), ( Encoding: OP_FINCLUMPIMMED ; CCType: 0; Arity: 1; Name: 'exitto'; ), ( Encoding: OP_ACQUIRE ; CCType: 0; Arity: 1; Name: 'acquire'; ), ( Encoding: OP_RELEASE ; CCType: 0; Arity: 1; Name: 'release'; ), ( Encoding: OP_SUBCALL ; CCType: 0; Arity: 2; Name: 'subcall'; ), ( Encoding: OP_SUBRET ; CCType: 0; Arity: 1; Name: 'subret'; ), ( Encoding: OP_SETIN ; CCType: 0; Arity: 3; Name: 'setin'; ), ( Encoding: OP_SETOUT ; CCType: 0; Arity: 6; Name: 'setout'; ), ( Encoding: OP_GETIN ; CCType: 0; Arity: 3; Name: 'getin'; ), ( Encoding: OP_GETOUT ; CCType: 0; Arity: 3; Name: 'getout'; ), ( Encoding: OP_WAIT ; CCType: 0; Arity: 1; Name: 'wait'; ), ( Encoding: OP_GETTICK ; CCType: 0; Arity: 1; Name: 'gettick'; ), // enhanced firmware opcodes ( Encoding: OPS_WAITV ; CCType: 0; Arity: 1; Name: 'waitv'; ), ( Encoding: OPS_ABS ; CCType: 0; Arity: 2; Name: 'abs'; ), ( Encoding: OPS_SIGN ; CCType: 0; Arity: 2; Name: 'sign'; ), ( Encoding: OPS_STOPCLUMP ; CCType: 0; Arity: 1; Name: 'stopthread'; ), ( Encoding: OPS_START ; CCType: 0; Arity: 1; Name: 'start'; ), ( Encoding: OPS_PRIORITY ; CCType: 0; Arity: 2; Name: 'priority'; ), ( Encoding: OPS_FMTNUM ; CCType: 0; Arity: 3; Name: 'fmtnum'; ), ( Encoding: OPS_ARROP ; CCType: 0; Arity: 5; Name: 'arrop'; ), ( Encoding: OPS_ACOS ; CCType: 0; Arity: 2; Name: 'acos'; ), ( Encoding: OPS_ASIN ; CCType: 0; Arity: 2; Name: 'asin'; ), ( Encoding: OPS_ATAN ; CCType: 0; Arity: 2; Name: 'atan'; ), ( Encoding: OPS_CEIL ; CCType: 0; Arity: 2; Name: 'ceil'; ), ( Encoding: OPS_EXP ; CCType: 0; Arity: 2; Name: 'exp'; ), ( Encoding: OPS_FABS ; CCType: 0; Arity: 2; Name: 'fabs'; ), ( Encoding: OPS_FLOOR ; CCType: 0; Arity: 2; Name: 'floor'; ), ( Encoding: OPS_SQRT ; CCType: 0; Arity: 2; Name: 'sqrt'; ), ( Encoding: OPS_TAN ; CCType: 0; Arity: 2; Name: 'tan'; ), ( Encoding: OPS_TANH ; CCType: 0; Arity: 2; Name: 'tanh'; ), ( Encoding: OPS_COS ; CCType: 0; Arity: 2; Name: 'cos'; ), ( Encoding: OPS_COSH ; CCType: 0; Arity: 2; Name: 'cosh'; ), ( Encoding: OPS_LOG ; CCType: 0; Arity: 2; Name: 'log'; ), ( Encoding: OPS_LOG10 ; CCType: 0; Arity: 2; Name: 'log10'; ), ( Encoding: OPS_SIN ; CCType: 0; Arity: 2; Name: 'sin'; ), ( Encoding: OPS_SINH ; CCType: 0; Arity: 2; Name: 'sinh'; ), ( Encoding: OPS_ATAN2 ; CCType: 0; Arity: 3; Name: 'atan2'; ), ( Encoding: OPS_FMOD ; CCType: 0; Arity: 3; Name: 'fmod'; ), ( Encoding: OPS_POW ; CCType: 0; Arity: 3; Name: 'pow'; ), // pseudo-opcodes ( Encoding: OPS_THREAD ; CCType: 0; Arity: 0; Name: 'thread'; ), ( Encoding: OPS_ENDT ; CCType: 0; Arity: 0; Name: 'endt'; ), ( Encoding: OPS_SUBROUTINE ; CCType: 0; Arity: 0; Name: 'subroutine'; ), ( Encoding: OPS_REQUIRES ; CCType: 0; Arity: 0; Name: 'follows'; ), ( Encoding: OPS_USES ; CCType: 0; Arity: 0; Name: STR_USES; ), ( Encoding: OPS_SEGMENT ; CCType: 0; Arity: 0; Name: 'segment'; ), ( Encoding: OPS_ENDS ; CCType: 0; Arity: 0; Name: 'ends'; ), ( Encoding: OPS_TYPEDEF ; CCType: 0; Arity: 0; Name: 'typedef'; ), ( Encoding: OPS_STRUCT ; CCType: 0; Arity: 0; Name: 'struct'; ), ( Encoding: OPS_DB ; CCType: 0; Arity: 0; Name: 'db'; ), ( Encoding: OPS_BYTE ; CCType: 0; Arity: 0; Name: 'byte'; ), ( Encoding: OPS_SBYTE ; CCType: 0; Arity: 0; Name: 'sbyte'; ), ( Encoding: OPS_UBYTE ; CCType: 0; Arity: 0; Name: 'ubyte'; ), ( Encoding: OPS_DW ; CCType: 0; Arity: 0; Name: 'dw'; ), ( Encoding: OPS_WORD ; CCType: 0; Arity: 0; Name: 'word'; ), ( Encoding: OPS_SWORD ; CCType: 0; Arity: 0; Name: 'sword'; ), ( Encoding: OPS_UWORD ; CCType: 0; Arity: 0; Name: 'uword'; ), ( Encoding: OPS_DD ; CCType: 0; Arity: 0; Name: 'dd'; ), ( Encoding: OPS_DWORD ; CCType: 0; Arity: 0; Name: 'dword'; ), ( Encoding: OPS_SDWORD ; CCType: 0; Arity: 0; Name: 'sdword'; ), ( Encoding: OPS_UDWORD ; CCType: 0; Arity: 0; Name: 'udword'; ), ( Encoding: OPS_LONG ; CCType: 0; Arity: 0; Name: 'long'; ), ( Encoding: OPS_SLONG ; CCType: 0; Arity: 0; Name: 'slong'; ), ( Encoding: OPS_ULONG ; CCType: 0; Arity: 0; Name: 'ulong'; ), ( Encoding: OPS_VOID ; CCType: 0; Arity: 0; Name: 'void'; ), ( Encoding: OPS_MUTEX ; CCType: 0; Arity: 0; Name: 'mutex'; ), ( Encoding: OPS_FLOAT ; CCType: 0; Arity: 0; Name: 'float'; ), ( Encoding: OPS_CALL ; CCType: 0; Arity: 1; Name: 'call'; ), ( Encoding: OPS_RETURN ; CCType: 0; Arity: 0; Name: 'return'; ), ( Encoding: OPS_STRINDEX ; CCType: 0; Arity: 3; Name: 'strindex'; ), ( Encoding: OPS_STRREPLACE ; CCType: 0; Arity: 4; Name: 'strreplace'; ), ( Encoding: OPS_SHL ; CCType: 0; Arity: 3; Name: 'shl'; ), ( Encoding: OPS_SHR ; CCType: 0; Arity: 3; Name: 'shr'; ), ( Encoding: OPS_STRLEN ; CCType: 0; Arity: 2; Name: 'strlen'; ), ( Encoding: OPS_COMPCHK ; CCType: 0; Arity: 3; Name: 'compchk'; ), ( Encoding: OPS_COMPIF ; CCType: 0; Arity: 3; Name: 'compif'; ), ( Encoding: OPS_COMPELSE ; CCType: 0; Arity: 0; Name: 'compelse'; ), ( Encoding: OPS_COMPEND ; CCType: 0; Arity: 0; Name: 'compend'; ), ( Encoding: OPS_COMPCHKTYPE ; CCType: 0; Arity: 2; Name: 'compchktype'; ) ); StandardOpcodeCount2x = 56; EnhancedOpcodeCount2x = 38; PseudoOpcodeCount2x = 39; NXTInstructionsCount2x = StandardOpcodeCount2x+EnhancedOpcodeCount2x+PseudoOpcodeCount2x; NXTInstructions2x : array[0..NXTInstructionsCount2x-1] of NXTInstruction = ( ( Encoding: OP_ADD ; CCType: 0; Arity: 3; Name: 'add'; ), ( Encoding: OP_SUB ; CCType: 0; Arity: 3; Name: 'sub'; ), ( Encoding: OP_NEG ; CCType: 0; Arity: 2; Name: 'neg'; ), ( Encoding: OP_MUL ; CCType: 0; Arity: 3; Name: 'mul'; ), ( Encoding: OP_DIV ; CCType: 0; Arity: 3; Name: 'div'; ), ( Encoding: OP_MOD ; CCType: 0; Arity: 3; Name: 'mod'; ), ( Encoding: OP_AND ; CCType: 0; Arity: 3; Name: 'and'; ), ( Encoding: OP_OR ; CCType: 0; Arity: 3; Name: 'or'; ), ( Encoding: OP_XOR ; CCType: 0; Arity: 3; Name: 'xor'; ), ( Encoding: OP_NOT ; CCType: 0; Arity: 2; Name: 'not'; ), ( Encoding: OP_CMNT ; CCType: 0; Arity: 2; Name: 'cmnt'; ), ( Encoding: OP_LSL ; CCType: 0; Arity: 3; Name: 'lsl'; ), ( Encoding: OP_LSR ; CCType: 0; Arity: 3; Name: 'lsr'; ), ( Encoding: OP_ASL ; CCType: 0; Arity: 3; Name: 'asl'; ), ( Encoding: OP_ASR ; CCType: 0; Arity: 3; Name: 'asr'; ), ( Encoding: OP_ROTL ; CCType: 0; Arity: 3; Name: 'rotl'; ), ( Encoding: OP_ROTR ; CCType: 0; Arity: 3; Name: 'rotr'; ), ( Encoding: OP_CMP ; CCType: 2; Arity: 3; Name: 'cmp'; ), ( Encoding: OP_TST ; CCType: 1; Arity: 2; Name: 'tst'; ), ( Encoding: OP_CMPSET ; CCType: 2; Arity: 4; Name: 'cmpset'; ), ( Encoding: OP_TSTSET ; CCType: 1; Arity: 3; Name: 'tstset'; ), ( Encoding: OP_INDEX ; CCType: 0; Arity: 3; Name: 'index'; ), ( Encoding: OP_REPLACE ; CCType: 0; Arity: 4; Name: 'replace'; ), ( Encoding: OP_ARRSIZE ; CCType: 0; Arity: 2; Name: 'arrsize'; ), ( Encoding: OP_ARRBUILD ; CCType: 0; Arity: 6; Name: 'arrbuild'; ), ( Encoding: OP_ARRSUBSET ; CCType: 0; Arity: 4; Name: 'arrsubset'; ), ( Encoding: OP_ARRINIT ; CCType: 0; Arity: 3; Name: 'arrinit'; ), ( Encoding: OP_MOV ; CCType: 0; Arity: 2; Name: 'mov'; ), ( Encoding: OP_SET ; CCType: 0; Arity: 2; Name: 'set'; ), ( Encoding: OP_FLATTEN ; CCType: 0; Arity: 2; Name: 'flatten'; ), ( Encoding: OP_UNFLATTEN ; CCType: 0; Arity: 4; Name: 'unflatten'; ), ( Encoding: OP_NUMTOSTRING ; CCType: 0; Arity: 2; Name: 'numtostr'; ), ( Encoding: OP_STRINGTONUM ; CCType: 0; Arity: 5; Name: 'strtonum'; ), ( Encoding: OP_STRCAT ; CCType: 0; Arity: 6; Name: 'strcat'; ), ( Encoding: OP_STRSUBSET ; CCType: 0; Arity: 4; Name: 'strsubset'; ), ( Encoding: OP_STRTOBYTEARR ; CCType: 0; Arity: 2; Name: 'strtoarr'; ), ( Encoding: OP_BYTEARRTOSTR ; CCType: 0; Arity: 2; Name: 'arrtostr'; ), ( Encoding: OP_JMP ; CCType: 0; Arity: 1; Name: 'jmp'; ), ( Encoding: OP_BRCMP ; CCType: 2; Arity: 3; Name: 'brcmp'; ), ( Encoding: OP_BRTST ; CCType: 1; Arity: 2; Name: 'brtst'; ), ( Encoding: OP_SYSCALL ; CCType: 0; Arity: 2; Name: 'syscall'; ), ( Encoding: OP_STOP ; CCType: 0; Arity: 1; Name: 'stop'; ), ( Encoding: OP_FINCLUMP ; CCType: 0; Arity: 2; Name: 'exit'; ), ( Encoding: OP_FINCLUMPIMMED ; CCType: 0; Arity: 1; Name: 'exitto'; ), ( Encoding: OP_ACQUIRE ; CCType: 0; Arity: 1; Name: 'acquire'; ), ( Encoding: OP_RELEASE ; CCType: 0; Arity: 1; Name: 'release'; ), ( Encoding: OP_SUBCALL ; CCType: 0; Arity: 2; Name: 'subcall'; ), ( Encoding: OP_SUBRET ; CCType: 0; Arity: 1; Name: 'subret'; ), ( Encoding: OP_SETIN ; CCType: 0; Arity: 3; Name: 'setin'; ), ( Encoding: OP_SETOUT ; CCType: 0; Arity: 6; Name: 'setout'; ), ( Encoding: OP_GETIN ; CCType: 0; Arity: 3; Name: 'getin'; ), ( Encoding: OP_GETOUT ; CCType: 0; Arity: 3; Name: 'getout'; ), ( Encoding: OP_WAIT ; CCType: 0; Arity: 2; Name: 'wait2'; ), ( Encoding: OP_GETTICK ; CCType: 0; Arity: 1; Name: 'gettick'; ), ( Encoding: OP_SQRT_2 ; CCType: 0; Arity: 2; Name: 'sqrt'; ), ( Encoding: OP_ABS_2 ; CCType: 0; Arity: 2; Name: 'abs'; ), // enhanced firmware opcodes ( Encoding: OPS_WAITI_2 ; CCType: 0; Arity: 1; Name: 'wait'; ), ( Encoding: OPS_WAITV_2 ; CCType: 0; Arity: 1; Name: 'waitv'; ), ( Encoding: OPS_SIGN_2 ; CCType: 0; Arity: 2; Name: 'sign'; ), ( Encoding: OPS_STOPCLUMP_2 ; CCType: 0; Arity: 1; Name: 'stopthread'; ), ( Encoding: OPS_START_2 ; CCType: 0; Arity: 1; Name: 'start'; ), ( Encoding: OPS_PRIORITY_2 ; CCType: 0; Arity: 2; Name: 'priority'; ), ( Encoding: OPS_FMTNUM_2 ; CCType: 0; Arity: 3; Name: 'fmtnum'; ), ( Encoding: OPS_ARROP_2 ; CCType: 0; Arity: 5; Name: 'arrop'; ), ( Encoding: OPS_ACOS_2 ; CCType: 0; Arity: 2; Name: 'acos'; ), ( Encoding: OPS_ASIN_2 ; CCType: 0; Arity: 2; Name: 'asin'; ), ( Encoding: OPS_ATAN_2 ; CCType: 0; Arity: 2; Name: 'atan'; ), ( Encoding: OPS_CEIL_2 ; CCType: 0; Arity: 2; Name: 'ceil'; ), ( Encoding: OPS_EXP_2 ; CCType: 0; Arity: 2; Name: 'exp'; ), ( Encoding: OPS_FLOOR_2 ; CCType: 0; Arity: 2; Name: 'floor'; ), ( Encoding: OPS_TAN_2 ; CCType: 0; Arity: 2; Name: 'tan'; ), ( Encoding: OPS_TANH_2 ; CCType: 0; Arity: 2; Name: 'tanh'; ), ( Encoding: OPS_COS_2 ; CCType: 0; Arity: 2; Name: 'cos'; ), ( Encoding: OPS_COSH_2 ; CCType: 0; Arity: 2; Name: 'cosh'; ), ( Encoding: OPS_LOG_2 ; CCType: 0; Arity: 2; Name: 'log'; ), ( Encoding: OPS_LOG10_2 ; CCType: 0; Arity: 2; Name: 'log10'; ), ( Encoding: OPS_SIN_2 ; CCType: 0; Arity: 2; Name: 'sin'; ), ( Encoding: OPS_SINH_2 ; CCType: 0; Arity: 2; Name: 'sinh'; ), ( Encoding: OPS_TRUNC_2 ; CCType: 0; Arity: 2; Name: 'trunc'; ), ( Encoding: OPS_FRAC_2 ; CCType: 0; Arity: 2; Name: 'frac'; ), ( Encoding: OPS_ATAN2_2 ; CCType: 0; Arity: 3; Name: 'atan2'; ), ( Encoding: OPS_POW_2 ; CCType: 0; Arity: 3; Name: 'pow'; ), ( Encoding: OPS_MULDIV_2 ; CCType: 0; Arity: 4; Name: 'muldiv'; ), ( Encoding: OPS_ACOSD_2 ; CCType: 0; Arity: 2; Name: 'acosd'; ), ( Encoding: OPS_ASIND_2 ; CCType: 0; Arity: 2; Name: 'asind'; ), ( Encoding: OPS_ATAND_2 ; CCType: 0; Arity: 2; Name: 'atand'; ), ( Encoding: OPS_TAND_2 ; CCType: 0; Arity: 2; Name: 'tand'; ), ( Encoding: OPS_TANHD_2 ; CCType: 0; Arity: 2; Name: 'tanhd'; ), ( Encoding: OPS_COSD_2 ; CCType: 0; Arity: 2; Name: 'cosd'; ), ( Encoding: OPS_COSHD_2 ; CCType: 0; Arity: 2; Name: 'coshd'; ), ( Encoding: OPS_SIND_2 ; CCType: 0; Arity: 2; Name: 'sind'; ), ( Encoding: OPS_SINHD_2 ; CCType: 0; Arity: 2; Name: 'sinhd'; ), ( Encoding: OPS_ATAN2D_2 ; CCType: 0; Arity: 3; Name: 'atan2d'; ), ( Encoding: OPS_ADDROF ; CCType: 0; Arity: 3; Name: 'addrof'; ), // pseudo-opcodes ( Encoding: OPS_THREAD ; CCType: 0; Arity: 0; Name: 'thread'; ), ( Encoding: OPS_ENDT ; CCType: 0; Arity: 0; Name: 'endt'; ), ( Encoding: OPS_SUBROUTINE ; CCType: 0; Arity: 0; Name: 'subroutine'; ), ( Encoding: OPS_REQUIRES ; CCType: 0; Arity: 0; Name: 'follows'; ), ( Encoding: OPS_USES ; CCType: 0; Arity: 0; Name: STR_USES; ), ( Encoding: OPS_SEGMENT ; CCType: 0; Arity: 0; Name: 'segment'; ), ( Encoding: OPS_ENDS ; CCType: 0; Arity: 0; Name: 'ends'; ), ( Encoding: OPS_TYPEDEF ; CCType: 0; Arity: 0; Name: 'typedef'; ), ( Encoding: OPS_STRUCT ; CCType: 0; Arity: 0; Name: 'struct'; ), ( Encoding: OPS_DB ; CCType: 0; Arity: 0; Name: 'db'; ), ( Encoding: OPS_BYTE ; CCType: 0; Arity: 0; Name: 'byte'; ), ( Encoding: OPS_SBYTE ; CCType: 0; Arity: 0; Name: 'sbyte'; ), ( Encoding: OPS_UBYTE ; CCType: 0; Arity: 0; Name: 'ubyte'; ), ( Encoding: OPS_DW ; CCType: 0; Arity: 0; Name: 'dw'; ), ( Encoding: OPS_WORD ; CCType: 0; Arity: 0; Name: 'word'; ), ( Encoding: OPS_SWORD ; CCType: 0; Arity: 0; Name: 'sword'; ), ( Encoding: OPS_UWORD ; CCType: 0; Arity: 0; Name: 'uword'; ), ( Encoding: OPS_DD ; CCType: 0; Arity: 0; Name: 'dd'; ), ( Encoding: OPS_DWORD ; CCType: 0; Arity: 0; Name: 'dword'; ), ( Encoding: OPS_SDWORD ; CCType: 0; Arity: 0; Name: 'sdword'; ), ( Encoding: OPS_UDWORD ; CCType: 0; Arity: 0; Name: 'udword'; ), ( Encoding: OPS_LONG ; CCType: 0; Arity: 0; Name: 'long'; ), ( Encoding: OPS_SLONG ; CCType: 0; Arity: 0; Name: 'slong'; ), ( Encoding: OPS_ULONG ; CCType: 0; Arity: 0; Name: 'ulong'; ), ( Encoding: OPS_VOID ; CCType: 0; Arity: 0; Name: 'void'; ), ( Encoding: OPS_MUTEX ; CCType: 0; Arity: 0; Name: 'mutex'; ), ( Encoding: OPS_FLOAT ; CCType: 0; Arity: 0; Name: 'float'; ), ( Encoding: OPS_CALL ; CCType: 0; Arity: 1; Name: 'call'; ), ( Encoding: OPS_RETURN ; CCType: 0; Arity: 0; Name: 'return'; ), ( Encoding: OPS_STRINDEX ; CCType: 0; Arity: 3; Name: 'strindex'; ), ( Encoding: OPS_STRREPLACE ; CCType: 0; Arity: 4; Name: 'strreplace'; ), ( Encoding: OPS_SHL ; CCType: 0; Arity: 3; Name: 'shl'; ), ( Encoding: OPS_SHR ; CCType: 0; Arity: 3; Name: 'shr'; ), ( Encoding: OPS_STRLEN ; CCType: 0; Arity: 2; Name: 'strlen'; ), ( Encoding: OPS_COMPCHK ; CCType: 0; Arity: 3; Name: 'compchk'; ), ( Encoding: OPS_COMPIF ; CCType: 0; Arity: 3; Name: 'compif'; ), ( Encoding: OPS_COMPELSE ; CCType: 0; Arity: 0; Name: 'compelse'; ), ( Encoding: OPS_COMPEND ; CCType: 0; Arity: 0; Name: 'compend'; ), ( Encoding: OPS_COMPCHKTYPE ; CCType: 0; Arity: 2; Name: 'compchktype'; ) ); type ShortOpEncoding = record Encoding : Byte; LongEncoding : TOpCode; GCName : String; ShortOp : String; end; const ShortOpEncodingsCount = 4; ShortOpEncodings : array[0..ShortOpEncodingsCount-1] of ShortOpEncoding = ( ( Encoding: 0; LongEncoding: OP_MOV ; GCName: 'MOV' ; ShortOp: 'OP_MOV'; ), ( Encoding: 1; LongEncoding: OP_ACQUIRE; GCName: 'ACQUIRE'; ShortOp: 'OP_ACQUIRE'; ), ( Encoding: 2; LongEncoding: OP_RELEASE; GCName: 'RELEASE'; ShortOp: 'OP_RELEASE'; ), ( Encoding: 3; LongEncoding: OP_SUBCALL; GCName: 'SUBCALL'; ShortOp: 'OP_SUBCALL'; ) ); const TC_VOID = 0; TC_UBYTE = 1; TC_SBYTE = 2; TC_UWORD = 3; TC_SWORD = 4; TC_ULONG = 5; TC_SLONG = 6; TC_ARRAY = 7; TC_CLUSTER = 8; TC_MUTEX = 9; TC_FLOAT = 10; const SHOP_MASK = $08; // b00001000 INST_MASK = $F0; // b11110000 CC_MASK = $07; // b00000111 function TypeToStr(const TypeDesc : byte) : string; overload; function TypeToStr(const aType : TDSType) : string; overload; function StrToType(const stype : string; bUseCase : Boolean = false) : TDSType; function GenerateTOCName(const TypeDesc : byte; const idx : Int64; const fmt : string = '%s%4.4x') : string; function ShortOpEncoded(const b : byte) : boolean; function CompareCodeToStr(const cc : byte) : string; function ShortOpToLongOp(const op : byte) : TOpCode; function GenericIDToStr(genIDs : array of IDRec; const ID : integer) : string; function SysCallMethodIDToStr(const fver : word; const ID : integer) : string; function InputFieldIDToStr(const ID : integer) : string; function OutputFieldIDToStr(const ID : integer) : string; procedure LoadRXEHeader(H : TRXEHeader; aStream : TStream); procedure LoadRXEDataSpace(H : TRXEHeader; DS : TDSData; aStream : TStream); procedure LoadRXEClumpRecords(H : TRXEHeader; CD : TClumpData; aStream : TStream); procedure LoadRXECodeSpace(H : TRXEHeader; CS : TCodeSpaceAry; aStream : TStream); function GetArgDataType(val : Extended): TDSType; function ExpectedArgType(const firmVer : word; const op : TOpCode; const argIdx: integer): TAsmArgType; function ProcessCluster(aDS : TDSData; Item : TDataspaceEntry; idx : Integer; var staticIndex : Integer) : integer; function GetTypeHint(DSpace : TDataspace; const aLine: TASMLine; const idx : integer; bEnhanced : boolean): TDSType; function CreateConstantVar(DSpace : TDataspace; val : Extended; bIncCount : boolean; aTypeHint : TDSType = dsVoid) : string; procedure InstantiateCluster(DD : TDataDefs; DE: TDataspaceEntry; const clustername: string); procedure HandleVarDecl(DD : TDataDefs; NT : TMapList; bCaseSensitive : boolean; DSE : TDataspaceEntry; albl, aopcode : string; sttFunc : TSTTFuncType); implementation uses StrUtils, Math, uNBCLexer, uCommonUtils, uVersionInfo, uLocalizedStrings, {$IFDEF FAST_MM}FastStrings, {$ENDIF} NBCCommonData, NXTDefsData; const CLUMP_FMT = 't%3.3d'; DWORD_LEN = 4; SubroutineReturnAddressType = dsUByte; type TCardinalObject = class protected fValue : Cardinal; public constructor Create(aValue : Cardinal); property Value : Cardinal read fValue; end; TIntegerObject = class protected fValue : Integer; public constructor Create(aValue : Integer); property Value : Integer read fValue; end; TSpecialFunctionExecute = procedure(Arg : TAsmArgument; const left, right, name : string) of object; TSpecialFunction = class private fFunc: string; fExecute: TSpecialFunctionExecute; public property Func : string read fFunc write fFunc; property Execute : TSpecialFunctionExecute read fExecute write fExecute; end; function RoundToByteSize(addr : Word; size : byte) : Word; var x : Word; begin x := Word(addr mod size); if x <> 0 then Result := Word(addr + size - x) else Result := addr; end; function QuotedString(const sargs : string) : boolean; var p1, len, L1, p2, L2 : integer; begin len := Length(sargs); p1 := Pos('''', sargs); p2 := Pos('"', sargs); L1 := LastDelimiter('''', sargs); L2 := LastDelimiter('"', sargs); Result := ((p1 = 1) and (L1 = len)) or ((p2 = 1) and (L2 = len)); end; function StripExtraQuotes(str : string) : string; var tmp : string; begin Result := str; while true do begin if QuotedString(Result) then begin tmp := Result; System.Delete(tmp, 1, 1); System.Delete(tmp, Length(tmp), 1); if QuotedString(tmp) then begin // we have a string with a duplicate set of quotation marks Result := tmp; end else break; end else break; end; end; function Replace(const str : string; const src, rep : string) : string; begin {$IFDEF FAST_MM} Result := FastReplace(str, src, rep, True); {$ELSE} Result := StringReplace(str, src, rep, [rfReplaceAll]); {$ENDIF} end; function IndexOfIOMapID(iomapID : integer) : integer; var i : integer; begin Result := -1; for i := Low(IOMapFieldIDs) to High(IOMapFieldIDs) do begin if IOMapFieldIDs[i].ID = iomapID then begin Result := i; Break; end; end; end; function IndexOfIOMapName(const aName : string) : integer; var i : integer; begin Result := -1; for i := Low(IOMapFieldIDs) to High(IOMapFieldIDs) do begin if IOMapFieldIDs[i].Name = aName then begin Result := i; Break; end; end; end; function LongOpToShortOp(op : TOpCode) : ShortInt; var i : integer; SOE : ShortOpEncoding; begin Result := -1; for i := Low(ShortOpEncodings) to High(ShortOpEncodings) do begin SOE := ShortOpEncodings[i]; if SOE.LongEncoding = op then begin Result := SOE.Encoding; Break; end; end; end; function TypeToStr(const aType : TDSType) : string; begin Result := TypeToStr(Byte(Ord(aType))); end; const NXTTypes : array[0..17] of NXTInstruction = ( ( Encoding: OPS_DB ; CCType: 0; Arity: 0; Name: 'db'; ), ( Encoding: OPS_BYTE ; CCType: 0; Arity: 0; Name: 'byte'; ), ( Encoding: OPS_SBYTE ; CCType: 0; Arity: 0; Name: 'sbyte'; ), ( Encoding: OPS_UBYTE ; CCType: 0; Arity: 0; Name: 'ubyte'; ), ( Encoding: OPS_DW ; CCType: 0; Arity: 0; Name: 'dw'; ), ( Encoding: OPS_WORD ; CCType: 0; Arity: 0; Name: 'word'; ), ( Encoding: OPS_SWORD ; CCType: 0; Arity: 0; Name: 'sword'; ), ( Encoding: OPS_UWORD ; CCType: 0; Arity: 0; Name: 'uword'; ), ( Encoding: OPS_DD ; CCType: 0; Arity: 0; Name: 'dd'; ), ( Encoding: OPS_DWORD ; CCType: 0; Arity: 0; Name: 'dword'; ), ( Encoding: OPS_SDWORD ; CCType: 0; Arity: 0; Name: 'sdword'; ), ( Encoding: OPS_UDWORD ; CCType: 0; Arity: 0; Name: 'udword'; ), ( Encoding: OPS_LONG ; CCType: 0; Arity: 0; Name: 'long'; ), ( Encoding: OPS_SLONG ; CCType: 0; Arity: 0; Name: 'slong'; ), ( Encoding: OPS_ULONG ; CCType: 0; Arity: 0; Name: 'ulong'; ), ( Encoding: OPS_VOID ; CCType: 0; Arity: 0; Name: 'void'; ), ( Encoding: OPS_MUTEX ; CCType: 0; Arity: 0; Name: 'mutex'; ), ( Encoding: OPS_FLOAT ; CCType: 0; Arity: 0; Name: 'float'; ) ); function StrToType(const stype : string; bUseCase : Boolean = false) : TDSType; var op : TOpCode; i : integer; tmpName : string; begin op := OPS_INVALID; for i := Low(NXTTypes) to High(NXTTypes) do begin if bUseCase then tmpName := stype else tmpName := AnsiLowerCase(stype); if NXTTypes[i].Name = tmpName then begin op := NXTTypes[i].Encoding; break; end; end; case op of OPS_DB, OPS_BYTE, OPS_UBYTE : Result := dsUByte; OPS_SBYTE : Result := dsSByte; OPS_DW, OPS_WORD, OPS_UWORD : Result := dsUWord; OPS_SWORD : Result := dsSWord; OPS_DD, OPS_DWORD, OPS_UDWORD, OPS_LONG, OPS_ULONG : Result := dsULong; OPS_SDWORD, OPS_SLONG : Result := dsSLong; OPS_MUTEX : Result := dsMutex; OPS_FLOAT : Result := dsFloat; else Result := dsVoid; end; end; function ValToStr(const aType : TDSType; aVal : Cardinal) : string; begin if aVal = 0 then Result := '' // don't output question marks needlessly else case aType of dsVoid : Result := ''; dsUByte : Result := Format('%u', [Byte(aVal)]); dsSByte : Result := Format('%d', [Shortint(aVal)]); dsUWord : Result := Format('%u', [Word(aVal)]); dsSWord : Result := Format('%d', [Smallint(aVal)]); dsULong : Result := Format('%u', [aVal]); dsSLong : Result := Format('%d', [Integer(aVal)]); dsMutex : Result := Format('%u', [aVal]); dsArray : Result := ''; dsCluster : Result := ''; dsFloat : Result := NBCFloatToStr(CardinalToSingle(aVal)); else Result := '???'; end; end; function TypeToStr(const TypeDesc : byte) : string; begin case TypeDesc of TC_VOID : Result := 'void'; TC_UBYTE : Result := 'byte'; TC_SBYTE : Result := 'sbyte'; TC_UWORD : Result := 'word'; TC_SWORD : Result := 'sword'; TC_ULONG : Result := 'dword'; TC_SLONG : Result := 'sdword'; TC_ARRAY : Result := 'array'; TC_CLUSTER : Result := 'struct'; TC_MUTEX : Result := 'mutex'; TC_FLOAT : Result := 'float'; else Result := '????'; end; end; function GenerateTOCName(const TypeDesc : byte; const idx : Int64; const fmt : string) : string; var prefix : string; begin case TypeDesc of TC_VOID : prefix := 'v'; TC_UBYTE : prefix := 'ub'; TC_SBYTE : prefix := 'sb'; TC_UWORD : prefix := 'uw'; TC_SWORD : prefix := 'sw'; TC_ULONG : prefix := 'ul'; TC_SLONG : prefix := 'sl'; TC_ARRAY : prefix := 'a'; TC_CLUSTER : prefix := 'c'; TC_MUTEX : prefix := 'm'; TC_FLOAT : prefix := 'f'; else prefix := '?'; end; Result := Format(fmt, [prefix, idx]); end; function ShortOpEncoded(const b : byte) : boolean; begin Result := (SHOP_MASK and b) = SHOP_MASK; end; function CompareCodeToStr(const cc : byte) : string; var i : integer; begin Result := '??'; for i := Low(CCEncodings) to High(CCEncodings) do begin if CCEncodings[i].Encoding = cc then begin Result := CCEncodings[i].Mode; break; end; end; end; function ValidCompareCode(const cc : byte) : boolean; begin Result := CompareCodeToStr(cc) <> '??'; end; function ShortOpToLongOp(const op : byte) : TOpCode; var i : integer; begin Result := TOpCode(op); for i := Low(ShortOpEncodings) to High(ShortOpEncodings) do begin if ShortOpEncodings[i].Encoding = op then begin Result := ShortOpEncodings[i].LongEncoding; break; end; end; end; function TRXEProgram.StrToOpcode(const op : string; bUseCase : boolean) : TOpCode; var i : integer; tmpName : string; begin Result := OPS_INVALID; for i := Low(fNXTInstructions) to High(fNXTInstructions) do begin if bUseCase then tmpName := op else tmpName := AnsiLowerCase(op); if fNXTInstructions[i].Name = tmpName then begin Result := fNXTInstructions[i].Encoding; break; end; end; end; function TRXEProgram.OpcodeToStr(const op : TOpCode) : string; var i : integer; begin if op <> OPS_INVALID then Result := Format('bad op (%d)', [Ord(op)]) else Result := ''; for i := Low(fNXTInstructions) to High(fNXTInstructions) do begin if fNXTInstructions[i].Encoding = op then begin Result := fNXTInstructions[i].Name; break; end; end; end; function GenericIDToStr(genIDs : array of IDRec; const ID : integer) : string; var i : integer; begin Result := Format('%d', [ID]); for i := Low(genIDs) to High(genIDs) do begin if genIDs[i].ID = ID then begin Result := genIDs[i].Name; break; end; end; end; function SysCallMethodIDToStr(const fver : word; const ID : integer) : string; begin if fver > MAX_FW_VER1X then Result := GenericIDToStr(SysCallMethodIDs2x, ID) else Result := GenericIDToStr(SysCallMethodIDs1x, ID); end; function InputFieldIDToStr(const ID : integer) : string; begin Result := GenericIDToStr(InputFieldIDs, ID); end; function OutputFieldIDToStr(const ID : integer) : string; begin Result := GenericIDToStr(OutputFieldIDs, ID); end; function LineTypeToStr(lt : TAsmLineType) : string; begin case lt of altBeginDS : Result := 'Begin Datasegment'; altEndDS : Result := 'End Datasegment'; altBeginClump : Result := 'Begin thread'; altEndClump : Result := 'End Thread'; altCode : Result := 'Code'; altVarDecl : Result := 'Variable Declaration'; altTypeDecl : Result := 'Type Declaration'; altBeginStruct : Result := 'Begin Structure'; altEndStruct : Result := 'End Structure'; altBeginSub : Result := 'Begin Subroutine'; altEndSub : Result := 'End Subroutine'; altCodeDepends : Result := 'Thread Relationships'; altInvalid : Result := 'Invalid'; else Result := 'Unknown Line Type'; end; end; function LineTypesToStr(lts : TAsmLineTypes) : string; var i : TAsmLineType; begin Result := '['; for i := Low(TAsmLineType) to High(TAsmLinetype) do begin if i in lts then Result := Result + LineTypeToStr(i) + ', '; end; if Pos(',', Result) <> 0 then Delete(Result, Length(Result)-1, 2); // remove trailing comma + space Result := Result + ']'; end; function AsmStateToStr(asmState : TMainAsmState) : string; begin case asmState of masDataSegment, masDSClump, masDSClumpSub : Result := 'Data Segment'; masCodeSegment : Result := 'Code Segment'; masClump : Result := 'Thread'; masClumpSub : Result := 'Subroutine'; masStruct, masStructDSClump, masStructDSClumpSub : Result := 'Struct Definition'; masBlockComment : Result := 'Block Comment'; else Result := 'Unknown'; end; end; function SizeOfDSTocEntry : Integer; begin Result := SizeOf(Byte)+SizeOf(Byte)+SizeOf(Word); end; procedure LoadRXEClumpRecords(H : TRXEHeader; CD : TClumpData; aStream: TStream); var i, start, stop, depCount : integer; begin if H.Head.Version <> 0 then begin start := SizeOf(RXEHeader)+(SizeOfDSTocEntry*H.Head.DSCount)+H.Head.DSDefaultsSize; // pad if start is an odd number if (start mod 2) <> 0 then inc(start); stop := Integer(aStream.Size-(2*H.Head.CodespaceCount)); aStream.Seek(start, soFromBeginning); SetLength(CD.CRecs, H.Head.ClumpCount); for i := 0 to H.Head.ClumpCount - 1 do begin aStream.Read(CD.CRecs[i].FireCount, 1); aStream.Read(CD.CRecs[i].DependentCount, 1); ReadWordFromStream(aStream, CD.CRecs[i].CodeStart); end; // now read the packed clump dependency list which is an array of byte // the number of bytes to read is stop-start-(4*ClumpCount). depCount := stop-start-(H.Head.ClumpCount*SizeOf(ClumpRecord)); if depCount > 0 then begin aStream.Seek(start+(H.Head.ClumpCount*SizeOf(ClumpRecord)), soFromBeginning); SetLength(CD.ClumpDeps, depCount); i := 0; while i < depCount do begin aStream.Read(CD.ClumpDeps[i], SizeOf(Byte)); inc(i); end; end; end; end; procedure TRXEDumper.DumpRXEClumpRecords(aStrings: TStrings); var i, j, k : integer; tmpStr : string; begin aStrings.Add('ClumpRecords'); aStrings.Add('----------------'); if fHeader.Head.Version <> 0 then begin aStrings.Add(Format('%d record(s) (Fire Cnt, Dependent Cnt, Code Start)', [fHeader.Head.ClumpCount])); for i := 0 to fHeader.Head.ClumpCount - 1 do begin with fClumpData.CRecs[i] do aStrings.Add(Format(CLUMP_FMT+': %2.2x %2.2x %4.4x', [i, FireCount, DependentCount, CodeStart])); end; // now output dependencies by clump k := 0; for i := 0 to Length(fClumpData.CRecs) - 1 do begin if fClumpData.CRecs[i].DependentCount > 0 then begin tmpStr := Format(CLUMP_FMT+' dependencies: ', [i]); for j := 0 to fClumpData.CRecs[i].DependentCount - 1 do begin tmpStr := tmpStr + Format(CLUMP_FMT+' ', [fClumpData.ClumpDeps[k]]); inc(k); end; aStrings.Add(tmpStr); end; end; end; aStrings.Add('----------------'); end; function TRXEDumper.TOCNameFromArg(DS : TDSData; const argValue : word) : string; var DE : TDataspaceEntry; i : integer; begin if (fTmpDataspace.Count > 0) and (argValue < Length(DS.TOCNames)) then begin DE := fTmpDataspace.FindEntryByName(DS.TOCNames[argValue]); if Assigned(DE) then Result := DE.FullPathIdentifier else begin Result := DS.TOCNames[argValue]; end; end else if argValue < Length(DS.TOCNames) then Result := DS.TOCNames[argValue] else begin // maybe an IO Map address??? i := IndexOfIOMapID(argValue); if i <> -1 then Result := IOMapFieldIDs[i].Name else Result := Format(HEX_FMT, [argValue]); end; end; function TRXEDumper.ProcessInstructionArg(DS : TDSData; const addr : integer; const op : TOpCode; const argIdx: integer; const argValue: word): string; var offset : SmallInt; begin // this routine uses special handling for certain opcodes case op of OP_ADD, OP_SUB, OP_NEG, OP_MUL, OP_DIV, OP_MOD, OP_AND, OP_OR, OP_XOR, OP_NOT, OP_CMNT, OP_LSL, OP_LSR, OP_ASL, OP_ASR, OP_ROTL, OP_ROTR, OP_CMP, OP_TST, OP_CMPSET, OP_TSTSET, OP_MOV, OP_ARRSIZE, OP_ARRBUILD, OP_FLATTEN, OP_UNFLATTEN, OP_NUMTOSTRING, OP_STRCAT, OP_STRTOBYTEARR, OP_BYTEARRTOSTR, OP_ACQUIRE, OP_RELEASE, OP_SUBRET, OP_GETTICK : begin Result := TOCNameFromArg(DS, argValue); end; OP_STOP, OP_ARRINIT, OP_INDEX, OP_REPLACE, OP_ARRSUBSET, OP_STRSUBSET, OP_STRINGTONUM : begin if argValue = NOT_AN_ELEMENT then Result := STR_NA else Result := TOCNameFromArg(DS, argValue); end; OP_SET : begin if argIdx > 0 then Result := Format(HEX_FMT, [argValue]) else Result := TOCNameFromArg(DS, argValue); end; OP_SUBCALL : begin if argIdx = 0 then Result := Format(CLUMP_FMT, [argValue]) else Result := TOCNameFromArg(DS, argValue); end; OP_FINCLUMP : begin Result := Format('%d', [SmallInt(argValue)]); end; OP_FINCLUMPIMMED : begin Result := Format(CLUMP_FMT, [SmallInt(argValue)]); end; OP_JMP, OP_BRCMP, OP_BRTST : begin if argIdx = 0 then begin // the first argument is an offset and could be forward or reverse offset := SmallInt(argValue); // Instead of outputting the offset value we want to output a label // specifying the line to jump to Result := Format('lbl%4.4x', [addr+offset]); // we also need to store this address for post processing of the // output fFixups.Add(Format('%d', [addr+offset])); end else Result := TOCNameFromArg(DS, argValue); end; OP_SYSCALL : begin if argIdx = 0 then Result := SysCallMethodIDToStr(FirmwareVersion, argValue) else Result := TOCNameFromArg(DS, argValue); end; OP_SETIN, OP_GETIN : begin if argIdx = 2 then Result := InputFieldIDToStr(argValue) else Result := TOCNameFromArg(DS, argValue); end; OP_SETOUT : begin if (argIdx mod 2) = 1 then Result := OutputFieldIDToStr(argValue) else Result := TOCNameFromArg(DS, argValue); end; OP_GETOUT : begin if argIdx = 2 then Result := OutputFieldIDToStr(argValue) else Result := TOCNameFromArg(DS, argValue); end; OP_WAIT : begin if FirmwareVersion > MAX_FW_VER1X then begin if argValue = NOT_AN_ELEMENT then Result := STR_NA else Result := TOCNameFromArg(DS, argValue); end else Result := Format(HEX_FMT, [argValue]); end; OPS_WAITI_2 : begin Result := Format(HEX_FMT, [argValue]); end; OPS_ADDROF : begin if argIdx = 2 then Result := Format(HEX_FMT, [argValue]) else Result := TOCNameFromArg(DS, argValue); end; OPS_WAITV, OPS_ABS, {OP_SQRT_2, OP_ABS_2, }OPS_SIGN, OPS_FMTNUM, OPS_ACOS, OPS_ASIN, OPS_ATAN, OPS_CEIL, OPS_EXP, OPS_FABS, OPS_FLOOR, OPS_SQRT, OPS_TAN, OPS_TANH, OPS_COS, OPS_COSH, OPS_LOG, OPS_LOG10, OPS_SIN, OPS_SINH, OPS_ATAN2, OPS_FMOD, OPS_POW, OPS_WAITV_2, OPS_SIGN_2, OPS_FMTNUM_2, OPS_ACOS_2, OPS_ASIN_2, OPS_ATAN_2, OPS_CEIL_2, OPS_EXP_2, OPS_FLOOR_2, OPS_TAN_2, OPS_TANH_2, OPS_COS_2, OPS_COSH_2, OPS_LOG_2, OPS_LOG10_2, OPS_SIN_2, OPS_SINH_2, OPS_TRUNC_2, OPS_FRAC_2, OPS_ATAN2_2, OPS_POW_2, OPS_MULDIV_2, OPS_ACOSD_2, OPS_ASIND_2, OPS_ATAND_2, OPS_TAND_2, OPS_TANHD_2, OPS_COSD_2, OPS_COSHD_2, OPS_SIND_2, OPS_SINHD_2, OPS_ATAN2D_2 : begin Result := TOCNameFromArg(DS, argValue); end; OPS_PRIORITY, OPS_PRIORITY_2 : begin if argValue = NOT_AN_ELEMENT then Result := STR_NA else Result := Format(HEX_FMT, [argValue]); end; OPS_ARROP, OPS_ARROP_2 : begin if argValue = NOT_AN_ELEMENT then Result := STR_NA else if argIdx = 0 then Result := Format(HEX_FMT, [argValue]) else Result := TOCNameFromArg(DS, argValue); end; else Result := Format(HEX_FMT, [argValue]); end; end; function TRXEDumper.ProcessInstruction(DS : TDSData; CS : TCodeSpaceAry; const addr : integer; aStrings : TStrings) : integer; var B1, B2, cc, sarg : byte; op : TOpCode; rarg : Shortint; instsize, x, opIdx : integer; NI : NXTInstruction; bShortEncoded, bNotFirst : boolean; tmpStr, TabStr : string; line : integer; begin // initialize variables and begin processing the current instruction TabStr := #9; tmpStr := ''; Result := addr; B1 := Lo(CS.Code[Result]); // xxxxxxxx B2 := Hi(CS.Code[Result]); // iiiifsss instsize := Byte((INST_MASK and B2) shr 4); bShortEncoded := ShortOpEncoded(B2); if bShortEncoded then begin op := ShortOpToLongOp(CC_MASK and B2); cc := 0; sarg := B1; end else begin op := TOpCode(B1); cc := (CC_MASK and B2); sarg := 0; end; // begin to generate the output string bNotFirst := False; opIdx := IndexOfOpcode(op); if opIdx = -1 then raise Exception.CreateFmt(sInvalidOpcode, [Ord(op)]); NI := GetNXTInstruction(opIdx); tmpStr := tmpStr + #9 + NI.Name; inc(Result); // move to next word in array dec(instsize, 2); if NI.CCType <> 0 then begin tmpStr := tmpStr + #9 + CompareCodeToStr(cc); bNotFirst := True; end; if bShortEncoded and (instsize = 0) then begin tmpStr := tmpStr + IfThen(bNotFirst, ', ', #9) + TOCNameFromArg(DS, sarg); bNotFirst := True; end; if instsize > 0 then tmpStr := tmpStr + IfThen(bNotFirst, ', ', TabStr); // we need special handling for 3 opcodes if ((op = OP_STRCAT) or (op = OP_ARRBUILD) or (op = OP_SETOUT)) and (instsize > 0) then begin // handle the extra argument stuff instsize := CS.Code[Result]; dec(instsize, 4); // subtract out the instruction and the instsize arg inc(Result); end; x := 0; while instsize > 0 do begin if bShortEncoded and (x = 0) then begin // special handling if there are multiple arguments and the first // argument was short-op encoded (as a relative offset from // from the second argument) rarg := ShortInt(sarg); tmpStr := tmpStr + ProcessInstructionArg(DS, addr, op, x, Word(CS.Code[Result]+rarg)) + ', '; inc(x); continue; end; // these should be arguments to the opcode we found above tmpStr := tmpStr + ProcessInstructionArg(DS, addr, op, x, CS.code[Result]); inc(x); inc(Result); dec(instsize, 2); if instsize > 0 then tmpStr := tmpStr + ', '; end; line := aStrings.Add(tmpStr); fAddrList.Add(Format('%d=%d', [addr, line])); end; procedure LoadRXECodeSpace(H : TRXEHeader; CS : TCodeSpaceAry; aStream: TStream); var i : integer; begin if H.Head.Version <> 0 then begin aStream.Seek(Integer(aStream.Size-(2*H.Head.CodespaceCount)), soFromBeginning); i := 0; SetLength(CS.Code, H.Head.CodespaceCount); while i < H.Head.CodespaceCount do begin ReadWordFromStream(aStream, CS.Code[i]); inc(i); end; end; end; procedure TRXEDumper.FixupLabelStrings(aStrings: TStrings; const addr, line: integer); var str : string; begin str := Format('lbl%4.4x:', [addr]) + aStrings[line]; aStrings[line] := str; end; function TRXEDumper.GetAddressLine(const str: string): string; begin Result := fAddrList.Values[str]; end; procedure TRXEDumper.OutputByteCodePhaseOne(aStrings: TStrings); var i : integer; begin // format code for output i := 0; while i < Length(fCode.Code) do begin // if we are at the start of a clump we should end the previous clump // (if there is one) and start the new clump. OutputClumpBeginEndIfNeeded(fClumpData, i, aStrings); // now process the current instruction i := ProcessInstruction(fDSData, fCode, i, aStrings); end; aStrings.Add(#9'endt'); // end the last clump end; procedure TRXEDumper.OutputBytecode(aStrings: TStrings); var i, line, addr : integer; str : string; tmpSL : TStringList; begin aStrings.Add('; -------------- program code --------------'); tmpSL := TStringList.Create; try OutputBytecodePhaseOne(tmpSL); // we need to fixup the labels for jumps for i := 0 to fFixups.Count - 1 do begin str := fFixups[i]; addr := StrToIntDef(str, -1); line := StrToIntDef(GetAddressLine(str), -1); if (addr <> -1) and (line <> -1) then begin FixupLabelStrings(tmpSL, addr, line); end; end; aStrings.AddStrings(tmpSL); finally tmpSL.Free; end; end; procedure TRXEDumper.DumpRXECodeSpace(aStrings: TStrings); begin if fHeader.Head.Version <> 0 then begin OutputDataspace(aStrings); OutputBytecode(aStrings); end; end; procedure LoadDVA(dvCount : integer; DS : TDSData; aStream: TStream); var i : integer; begin // now read the Dope Vectors (10 bytes each) i := 0; SetLength(DS.DopeVecs, dvCount); // SetLength(DS.DopeVecs, (H.Head.DynDSDefaultsSize - (H.Head.DVArrayOffset-H.Head.DSStaticSize)) div 10); while i < Length(DS.DopeVecs) do begin with DS.DopeVecs[i] do begin ReadWordFromStream(aStream, offset); ReadWordFromStream(aStream, elemsize); ReadWordFromStream(aStream, count); ReadWordFromStream(aStream, backptr); ReadWordFromStream(aStream, link); end; inc(i); end; end; procedure LoadDynamicDefaultData(dsCount : integer; DS : TDSData; aStream: TStream); var i : integer; B : Byte; begin i := 0; SetLength(DS.DynamicDefaults, dsCount); while i < dsCount do begin aStream.Read(B, SizeOf(Byte)); DS.DynamicDefaults[i] := B; inc(i); end; end; procedure LoadRXEDataSpace(H : TRXEHeader; DS : TDSData; aStream: TStream); var i, dvCount, offset, dsLen : integer; B : Byte; begin if H.Head.Version <> 0 then begin dvCount := 1; // always have 1 Dope Vector in the DVA // dataspace contains DSCount 4 byte structures (the TOC) // followed by the static and dynamic defaults aStream.Seek(SizeOf(RXEHeader), soFromBeginning); SetLength(DS.TOC, H.Head.DSCount); SetLength(DS.TOCNames, H.Head.DSCount); for i := 0 to H.Head.DSCount - 1 do begin aStream.Read(B, 1); DS.TOC[i].TypeDesc := B; aStream.Read(DS.TOC[i].Flags, 1); ReadWordFromStream(aStream, DS.TOC[i].DataDesc); DS.TOCNames[i] := GenerateTOCName(DS.TOC[i].TypeDesc, i); if B = TC_ARRAY then inc(dvCount); end; // static bytes are next offset := SizeOf(RXEHeader)+(SizeOfDSTocEntry*H.Head.DSCount); aStream.Seek(offset, soFromBeginning); i := 0; B := 0; SetLength(DS.StaticDefaults, H.Head.DynDSDefaultsOffset); while i < H.Head.DynDSDefaultsOffset do begin aStream.Read(B, SizeOf(Byte)); DS.StaticDefaults[i] := B; inc(i); end; // now we can read the dynamic default data // aStream.Seek(offset+H.Head.DynDSDefaultsOffset, soFromBeginning); // this should not be necessary // how many bytes of array default data are there to read? dsLen := H.Head.DynDSDefaultsSize-(dvCount*SizeOf(DopeVector)); // figure out whether the Dope Vector Array comes before or after the // dynamic defaults that aren't part of the Dope Vector Array if H.Head.DVArrayOffset = H.Head.DSStaticSize then begin // DVA comes first LoadDVA(dvCount, DS, aStream); // we just read dvCount*10 bytes. If the DVA comes first then we need // to read 0 or 2 padding bytes depending on whether dvCount is even or odd // so that the actual array data is guaranteed to start on an address that // is a multiple of 4. if (dvCount mod 2) = 1 then begin aStream.Read(B, 1); aStream.Read(B, 1); dec(dsLen, 2); end; LoadDynamicDefaultData(dsLen, DS, aStream); end else begin LoadDynamicDefaultData(dsLen, DS, aStream); LoadDVA(dvCount, DS, aStream); end; // set the dataspace memory manager indexes from the header DS.Head := H.Head.MemMgrHead; DS.Tail := H.Head.MemMgrTail; end; end; procedure TRXEDumper.OutputDataspace(aStrings: TStrings); begin fTmpDataspace.LoadFromDSData(self.fDSData); aStrings.Add('; -------------- variable declarations --------------'); fTmpDataspace.SaveToStrings(aStrings); end; procedure TRXEDumper.DumpRXEDataSpace(aStrings: TStrings); var i : integer; tmpStr : string; begin aStrings.Add('DataSpace'); aStrings.Add('----------------'); // dataspace contains DSCount 4 byte structures (the TOC) // followed by the static and dynamic defaults aStrings.Add('DSTOC'); for i := 0 to Length(fDSData.TOC) - 1 do begin with fDSData do aStrings.Add(Format('%8s: %2.2x %2.2x %4.4x', [TOCNames[i], TOC[i].TypeDesc, TOC[i].Flags, TOC[i].DataDesc])); end; // static bytes are next i := 0; tmpStr := ''; aStrings.Add('Static DS Defaults'); while i < Length(fDSData.StaticDefaults) do begin tmpStr := tmpStr + Format('%2.2x ', [fDSData.StaticDefaults[i]]); inc(i); if i mod 16 = 0 then begin aStrings.Add(tmpStr); tmpStr := ''; end; end; if tmpStr <> '' then aStrings.Add(tmpStr); // now we can dump the dynamic default data i := 0; tmpStr := ''; aStrings.Add('Dynamic DS Defaults'); while i < Length(fDSData.DynamicDefaults) do begin tmpStr := tmpStr + Format('%2.2x ', [fDSData.DynamicDefaults[i]]); inc(i); if i mod 16 = 0 then begin aStrings.Add(tmpStr); tmpStr := ''; end; end; if tmpStr <> '' then aStrings.Add(tmpStr); // now output the Dope Vectors (10 bytes each) i := 0; aStrings.Add('Dope Vectors (offset, elem size, count, back ptr, link)'); while i < Length(fDSData.DopeVecs) do begin tmpStr := ''; with fDSData do begin tmpStr := tmpStr + Format('%2.2x %2.2x ', [Hi(DopeVecs[i].offset), Lo(DopeVecs[i].offset)]); tmpStr := tmpStr + Format('%2.2x %2.2x ', [Hi(DopeVecs[i].elemsize), Lo(DopeVecs[i].elemsize)]); tmpStr := tmpStr + Format('%2.2x %2.2x ', [Hi(DopeVecs[i].count), Lo(DopeVecs[i].count)]); tmpStr := tmpStr + Format('%2.2x %2.2x ', [Hi(DopeVecs[i].backptr), Lo(DopeVecs[i].backptr)]); tmpStr := tmpStr + Format('%2.2x %2.2x', [Hi(DopeVecs[i].link), Lo(DopeVecs[i].link)]); end; aStrings.Add(tmpStr); inc(i); end; aStrings.Add('----------------'); end; procedure LoadRXEHeader(H : TRXEHeader; aStream: TStream); begin aStream.Seek(0, soFromBeginning); with H.Head do begin aStream.Read(FormatString, 14); aStream.Read(Skip, 1); aStream.Read(Version, 1); ReadWordFromStream(aStream, DSCount); ReadWordFromStream(aStream, DSSize); ReadWordFromStream(aStream, DSStaticSize); ReadWordFromStream(aStream, DSDefaultsSize); ReadWordFromStream(aStream, DynDSDefaultsOffset); ReadWordFromStream(aStream, DynDSDefaultsSize); ReadWordFromStream(aStream, MemMgrHead); ReadWordFromStream(aStream, MemMgrTail); ReadWordFromStream(aStream, DVArrayOffset); ReadWordFromStream(aStream, ClumpCount); ReadWordFromStream(aStream, CodespaceCount); end; end; procedure TRXEDumper.DumpRXEHeader(aStrings: TStrings); begin aStrings.Add('Header'); aStrings.Add('----------------'); with fHeader.Head do aStrings.Text := aStrings.Text + Format(RXEHeaderText, [FormatString, Version, DSCount, DSSize, DSStaticSize, DSDefaultsSize, DynDSDefaultsOffset, DynDSDefaultsSize, MemMgrHead, MemMgrTail, DVArrayOffset, ClumpCount, CodespaceCount]); aStrings.Add('----------------'); end; procedure TRXEDumper.OutputClumpBeginEndIfNeeded(CD : TClumpData; const addr: integer; aStrings: TStrings); var i, j, depOffset : integer; tmpStr : string; begin // if we are at the start of a clump we should end the previous clump // (if there is one) and start the new clump. depOffset := 0; for i := 0 to Length(CD.CRecs) - 1 do begin if CD.CRecs[i].CodeStart = addr then begin if i > 0 then begin // output the end of the previous clump aStrings.Add(#9'endt'); aStrings.Add(';-----------------------------------'); end; // output the beginning of the new clump aStrings.Add(Format(#9'thread '+CLUMP_FMT, [i])); // while we are at the start of a clump we should also // output our dependency information if CD.CRecs[i].DependentCount > 0 then begin tmpStr := #9 + STR_USES + #9; for j := 0 to CD.CRecs[i].DependentCount - 1 do begin tmpStr := tmpStr + Format(CLUMP_FMT+', ', [fClumpData.ClumpDeps[depOffset+j]]); end; Delete(tmpStr, Length(tmpStr)-1, 2); // remove the last ', ' sequence. aStrings.Add(tmpStr); end; end; inc(depOffset, CD.CRecs[i].DependentCount); end; end; constructor TRXEDumper.Create; begin inherited; fHeader := TRXEHeader.Create; fDSData := TDSData.Create; fClumpData := TClumpData.Create; fCode := TCodeSpaceAry.Create; fAddrList := TStringList.Create; fAddrList.Sorted := True; fAddrList.Duplicates := dupIgnore; fFixups := TStringList.Create; fFixups.Sorted := True; fFixups.Duplicates := dupIgnore; fTmpDataspace := TDataspace.Create; fHeader.Head.DSCount := 0; fOnlyDumpCode := False; FirmwareVersion := 0; end; destructor TRXEDumper.Destroy; begin FreeAndNil(fHeader); FreeAndNil(fDSData); FreeAndNil(fClumpData); FreeAndNil(fCode); FreeAndNil(fAddrList); FreeAndNil(fFixups); FreeAndNil(fTmpDataspace); inherited; end; procedure TRXEDumper.DumpRXE(aStrings : TStrings); var SL : TStringList; begin aStrings.Clear; aStrings.BeginUpdate; try SL := TStringList.Create; try if not OnlyDumpCode then begin SL.Add('/*'); SL.Add(ExtractFileName(Filename)); DumpRXEHeader(SL); DumpRXEDataSpace(SL); DumpRXEClumpRecords(SL); SL.Add('*/'); end; DumpRXECodeSpace(SL); // copy from temporary string list into the provided TStrings class aStrings.AddStrings(SL); finally SL.Free; end; finally aStrings.EndUpdate; end; end; procedure TRXEDumper.Decompile(aStrings: TStrings); begin aStrings.Clear; aStrings.BeginUpdate; try aStrings.Add('; '+ExtractFileName(Filename)); DumpRXECodeSpace(aStrings); finally aStrings.EndUpdate; end; end; procedure TRXEDumper.LoadFromFile(const aFilename : string); var MS : TMemoryStream; begin Filename := aFilename; MS := TMemoryStream.Create; try MS.LoadFromFile(aFilename); LoadFromStream(MS); finally FreeAndNil(MS); end; end; procedure TRXEDumper.LoadFromStream(aStream: TStream); begin aStream.Position := 0; LoadRXEHeader(fHeader, aStream); if FirmwareVersion = 0 then begin // only set the firmware version based on the file contents if // it has not been explicitly set to a non-zero value externally if fHeader.Head.Version > 5 then FirmwareVersion := MIN_FW_VER2X else FirmwareVersion := MAX_FW_VER1X; end; LoadRXEDataSpace(fHeader, fDSData, aStream); LoadRXEClumpRecords(fHeader, fClumpData, aStream); LoadRXECodeSpace(fHeader, fCode, aStream); InitializeRXE; end; procedure TRXEDumper.SaveToFile(const aFilename: string); var MS : TMemoryStream; begin MS := TMemoryStream.Create; try SaveToStream(MS); MS.SaveToFile(aFilename); finally MS.Free; end; end; procedure WriteHeaderToStream(aStream: TStream; Head : RXEHeader); begin with Head do begin aStream.Write(FormatString, 14); aStream.Write(Skip, 1); aStream.Write(Version, 1); WriteWordToStream(aStream, DSCount); WriteWordToStream(aStream, DSSize); WriteWordToStream(aStream, DSStaticSize); WriteWordToStream(aStream, DSDefaultsSize); WriteWordToStream(aStream, DynDSDefaultsOffset); WriteWordToStream(aStream, DynDSDefaultsSize); WriteWordToStream(aStream, MemMgrHead); WriteWordToStream(aStream, MemMgrTail); WriteWordToStream(aStream, DVArrayOffset); WriteWordToStream(aStream, ClumpCount); WriteWordToStream(aStream, CodespaceCount); end; end; procedure TRXEDumper.SaveToStream(aStream: TStream); begin FinalizeRXE; // write the header WriteHeaderToStream(aStream, fHeader.Head); fDSData.SaveToStream(aStream); // write the clump records fClumpData.SaveToStream(aStream); // write the codespace fCode.SaveToStream(aStream); end; procedure TRXEDumper.FinalizeRXE; begin // prepare all the dynamic arrays from the class structure end; procedure TRXEDumper.InitializeRXE; begin // process dynamic arrays and build the class // representation of the code end; function TRXEDumper.GetNXTInstruction(const idx: integer): NXTInstruction; begin Result := fNXTInstructions[idx]; end; procedure TRXEDumper.SetFirmwareVersion(const Value: word); begin fFirmwareVersion := Value; InitializeInstructions; end; procedure TRXEDumper.InitializeInstructions; var i : integer; begin if fFirmwareVersion > MAX_FW_VER1X then begin SetLength(fNXTInstructions, NXTInstructionsCount2x); for i := 0 to NXTInstructionsCount2x - 1 do begin fNXTInstructions[i] := NXTInstructions2x[i]; end; end else begin SetLength(fNXTInstructions, NXTInstructionsCount1x); for i := 0 to NXTInstructionsCount1x - 1 do begin fNXTInstructions[i] := NXTInstructions1x[i]; end; end; end; function TRXEDumper.IndexOfOpcode(op : TOpCode) : integer; var i : integer; begin Result := -1; for i := Low(fNXTInstructions) to High(fNXTInstructions) do begin if fNXTInstructions[i].Encoding = op then begin Result := i; Break; end; end; end; { TDSBase } function TDSBase.Add: TDataspaceEntry; begin Result := TDataspaceEntry(inherited Add); end; procedure TDSBase.AssignTo(Dest: TPersistent); var i : integer; begin if Dest is TDSBase then begin TDSBase(Dest).Clear; for i := 0 to Self.Count - 1 do begin TDSBase(Dest).Add.Assign(Self[i]); end; end else inherited; end; function TDSBase.GetItem(Index: Integer): TDataspaceEntry; begin Result := TDataspaceEntry(inherited GetItem(Index)); end; function TDSBase.FindEntryByFullName(const path : string): TDataspaceEntry; var i, p : integer; tmp : string; DE : TDataspaceEntry; begin i := fEntryIndex.IndexOf(path); if i <> -1 then Result := TDataspaceEntry(fEntryIndex.Objects[i]) else begin Result := nil; for i := 0 to Self.Count - 1 do begin DE := Items[i]; if DE.Identifier = path then begin Result := DE; Break; end else begin p := Pos(DE.Identifier + '.', path); if p = 1 then // 2009-05-12 JCH: was p > 0 begin tmp := Copy(path, p+Length(DE.Identifier)+1, MaxInt); Result := DE.SubEntries.FindEntryByFullName(tmp); if Result <> nil then Break; end; end; end; end; end; function TDSBase.IndexOfName(const name : string): integer; var DE : TDataspaceEntry; begin DE := FindEntryByFullName(name); if Assigned(DE) then Result := DE.Index else Result := -1; end; function TDSBase.Insert(Index: Integer): TDataspaceEntry; begin result := TDataspaceEntry(inherited Insert(Index)); end; procedure TDSBase.ExchangeItems(Index1, Index2: Integer); var Temp1, Temp2: Integer; de1, de2 : TDataspaceEntry; begin de1 := Items[Index1]; de2 := Items[Index2]; Temp1 := de1.Index; Temp2 := de2.Index; BeginUpdate; try de1.Index := Temp2; de2.Index := Temp1; finally EndUpdate; end; end; procedure TDSBase.QuickSort(L, R: Integer; SCompare: TDSBaseSortCompare); var I, J, P: Integer; begin repeat I := L; J := R; P := (L + R) shr 1; repeat while SCompare(Self, I, P) < 0 do Inc(I); while SCompare(Self, J, P) > 0 do Dec(J); if I <= J then begin ExchangeItems(I, J); if P = I then P := J else if P = J then P := I; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(L, J, SCompare); L := I; until I >= R; end; procedure TDSBase.SetItem(Index: Integer; Value: TDataspaceEntry); begin inherited SetItem(Index, Value); end; function GetBytesPerType(dt : TDSType) : integer; begin if dt = dsCluster then Result := -10 else if dt = dsArray then Result := -20 else Result := BytesPerType[dt]; end; function IsScalarType(dt : TDSType) : boolean; begin Result := not (dt in [dsArray, dsCluster]); end; function DSBaseCompareSizes(List: TDSBase; Index1, Index2: Integer): Integer; var de1, de2 : TDataspaceEntry; b1, b2 : Integer; // dt1, dt2 : TDSType; // bScalar1, bScalar2 : boolean; begin { -1 if the item identified by Index1 comes before the item identified by Index2 0 if the two are equivalent 1 if the item with Index1 comes after the item identified by Index2. } de1 := List.Items[Index1]; de2 := List.Items[Index2]; b1 := GetBytesPerType(de1.DataType); b2 := GetBytesPerType(de2.DataType); if b1 > b2 then // larger sizes of scalar types come first Result := -1 else if b1 = b2 then Result := 0 else Result := 1; (* { We want to sort the dataspace so that 1. all scalar types come before aggregate types. 2. scalar types are ordered by size with 4 byte types before 2 byte types before 1 byte types 3. All structs come before arrays 4. arrays are last TDSType = (dsVoid, dsUByte, dsSByte, dsUWord, dsSWord, dsULong, dsSLong, dsArray, dsCluster, dsMutex, dsFloat); } dt1 := de1.DataType; dt2 := de2.DataType; bScalar1 := IsScalarType(dt1); bScalar2 := IsScalarType(dt2); if bScalar1 and bScalar2 then begin b1 := GetBytesPerType(dt1); b2 := GetBytesPerType(dt2); if b1 > b2 then // larger sizes of scalar types come first Result := -1 else if b1 = b2 then Result := 0 else Result := 1; end else if bScalar1 then begin // 1 is scalar but 2 is not Result := -1; end else if bScalar2 then begin // 2 is scalar but 1 is not Result := 1; end else begin // neither one is scalar if dt1 < dt2 then Result := 1 else if dt1 = dt2 then Result := 0 else Result := -1; end; *) end; procedure TDSBase.Sort; begin if Count = 0 then Exit; QuickSort(0, Count - 1, @DSBaseCompareSizes); end; constructor TDSBase.Create; begin inherited Create(TDataspaceEntry); fEntryIndex := TStringList.Create; fEntryIndex.CaseSensitive := True; fEntryIndex.Sorted := True; fParent := nil; end; function TDSBase.FullPathName(DE: TDataspaceEntry): string; begin if Parent <> nil then Result := TDataspaceEntry(Parent).FullPathIdentifier + '.' + DE.Identifier else Result := DE.Identifier; end; function TDSBase.FindEntryByAddress(Addr: Word): TDataspaceEntry; var i : integer; begin Result := nil; for i := 0 to Count - 1 do begin if Items[i].DataType = dsCluster then begin Result := Items[i].SubEntries.FindEntryByAddress(Addr); if assigned(Result) then Break; end else if Items[i].Address = Addr then begin Result := Items[i]; Break; end; end; end; function TDSBase.FindEntryByName(name: string): TDataspaceEntry; var i : integer; begin // find the first entry with a matching name (could be duplicates). Result := nil; for i := 0 to Self.Count - 1 do begin if Items[i].Identifier = name then begin Result := Items[i]; Break; end else begin Result := Items[i].SubEntries.FindEntryByName(name); if Result <> nil then Break; end; end; end; procedure TDSBase.CheckEntry(DE: TDataspaceEntry); var X : TDataspaceEntry; begin // identifier must be valid if not IsValidIdent(DE.Identifier) then raise Exception.CreateFmt(sInvalidVarDecl, [DE.Identifier]); // make sure entry is unique X := FindEntryByFullName(DE.FullPathIdentifier); if (X <> nil) and (X <> DE) then raise EDuplicateDataspaceEntry.Create(DE); end; function EqualDopeVectors(DV1, DV2 : DopeVector) : boolean; begin Result := (DV1.offset = DV2.offset) and (DV1.elemsize = DV2.elemsize) and (DV1.count = DV2.count) and (DV1.backptr = DV2.backptr) and (DV1.link = DV2.link); end; function TDSBase.ResolveNestedArrayAddress(DS: TDSData; DV: DopeVector): TDataspaceEntry; var i, addr : integer; begin addr := -1; // find the index of the DV in DS.DopeVectors and look at // the item just before it to get the Dataspace entry address for i := Low(DS.DopeVecs) to High(DS.DopeVecs) do begin if EqualDopeVectors(DS.DopeVecs[i], DV) and (i > Low(DS.DopeVecs)) then begin // found the item addr := DS.DopeVecs[i-1].backptr; Break; end; end; Result := FindEntryByAddress(Word(addr)); end; function TDSBase.GetRoot: TDataspaceEntry; begin Result := nil; if Assigned(Parent) then Result := TDataspaceEntry(Parent).DSBase.Root; if not Assigned(Result) then Result := TDataspaceEntry(Parent); end; destructor TDSBase.Destroy; begin FreeAndNil(fEntryIndex); inherited; end; { TDataspace } constructor TDataspace.Create; begin inherited; fDSIndexMap := TStringList.Create; fDSIndexMap.CaseSensitive := True; fDSIndexMap.Sorted := True; // an unsorted list of all dataspace entries regardless of their nesting level fDSList := TObjectList.Create; end; destructor TDataspace.Destroy; begin FreeAndNil(fDSIndexMap); FreeAndNil(fDSList); inherited; end; function TDataspace.FinalizeDataspace(DS : TDSBase; addr : Word) : Word; var i : integer; DE : TDataspaceEntry; currAddress : Word; begin // run through the dataspace and set the Address property for each entry and // build a map for the dataspace indices currAddress := addr; for i := 0 to DS.Count - 1 do begin DE := DS.Items[i]; fDSIndexMap.AddObject(DE.FullPathIdentifier, DE); fDSList.Add(DE); DE.DSID := fDSList.Count - 1; if DE.DataType = dsCluster then begin DE.Address := Word(DE.SubEntries.Count); currAddress := FinalizeDataspace(DE.SubEntries, RoundToBytesize(currAddress, BytesPerType[dsCluster])); end else if DE.DataType = dsArray then begin DE.Address := RoundToBytesize(currAddress, BytesPerType[dsArray]); FinalizeDataspace(DE.SubEntries, 0); currAddress := Word(DE.Address + BytesPerType[DE.DataType]); end else begin DE.Address := RoundToBytesize(currAddress, BytesPerType[DE.DataType]); currAddress := Word(DE.Address + BytesPerType[DE.DataType]); end; end; Result := currAddress; end; function TDataspace.DataspaceIndex(const ident: string): Integer; var DE : TDataspaceEntry; begin if fDSIndexMap.Count = 0 then FinalizeDataspace(Self, 0); Result := fDSIndexMap.IndexOf(ident); if Result <> -1 then begin DE := TDataspaceEntry(fDSIndexMap.Objects[Result]); Result := DE.DSID; end; end; function TDataspace.GetVector(index: Integer): DopeVector; begin Result := fVectors[index]; end; function TDataspace.IndexOfEntryByAddress(Addr: Word): Integer; var DE : TDataspaceEntry; begin DE := FindEntryByAddress(Addr); if Assigned(DE) then Result := DE.Index else Result := -1; end; function AddArrayItem(aDS : TDSData; Item : TDataspaceEntry; idx : Integer; var staticIndex : Integer) : integer; var Sub : TDataspaceEntry; begin // when this function is called idx is pointing one past the array item Result := idx; // the next entry contains the datatype (which, unfortunately, could be an array) Sub := Item.SubEntries.Add; Sub.Identifier := aDS.TOCNames[Result]; Sub.DataType := TDSType(aDS.TOC[Result].TypeDesc); Sub.DSID := Result; Sub.DefaultValue := 0; Sub.ArrayMember := True; if Sub.DataType = dsArray then begin inc(Result); Result := AddArrayItem(aDS, Sub, Result, staticIndex); end else if Sub.DataType = dsCluster then Result := ProcessCluster(aDS, Sub, Result, staticIndex) else inc(Result); end; procedure GetStaticDefaults(X: TDataspaceEntry; aDS: TDSData; var staticIndex: integer); var val : Cardinal; begin // read the static bytes and convert to default value case BytesPerType[X.DataType] of 1 : val := BytesToCardinal(aDS.StaticDefaults[staticIndex]); 2 : val := BytesToCardinal(aDS.StaticDefaults[staticIndex], aDS.StaticDefaults[staticIndex+1]); 4 : val := BytesToCardinal(aDS.StaticDefaults[staticIndex], aDS.StaticDefaults[staticIndex+1], aDS.StaticDefaults[staticIndex+2], aDS.StaticDefaults[staticIndex+3]); else val := 0; end; X.DefaultValue := val; // increment the static index inc(staticIndex, BytesPerType[X.DataType]); end; function ProcessCluster(aDS : TDSData; Item : TDataspaceEntry; idx : Integer; var staticIndex : Integer) : integer; var n, j : integer; member : TDataspaceEntry; DSE : DSTocEntry; begin Result := idx; inc(Result); n := aDS.TOC[idx].DataDesc; // number of elements in this cluster j := 1; while j <= n do begin // the next entry contains the datatype member := Item.SubEntries.Add; DSE := aDS.TOC[Result]; member.Identifier := aDS.TOCNames[Result]; member.DataType := TDSType(DSE.TypeDesc); member.DSID := Result; member.DefaultValue := 0; member.ArrayMember := Item.ArrayMember; case member.DataType of dsArray : begin inc(Result); // move past the array element to its child // read an extra item member.Address := DSE.DataDesc; // data description is the address Result := AddArrayItem(aDS, member, Result, staticIndex); // if this array is a root level array (i.e., not an ArrayMember) then // get the DVAIndex from the static dataspace if (DSE.Flags = 0) and not Item.ArrayMember then begin GetStaticDefaults(member, aDS, staticIndex); end; end; dsCluster : begin member.Address := DSE.DataDesc; // data description is the number of elements Result := ProcessCluster(aDS, member, Result, staticIndex); end; else inc(Result); member.Address := DSE.DataDesc; // data description is the address if (DSE.Flags = 0) and not Item.ArrayMember then begin GetStaticDefaults(member, aDS, staticIndex); end; end; inc(j); end; end; const INVALID_LINK = $FFFF; NESTED_ARRAY_BACKPTR = $FFFE; procedure TDataspace.LoadArrayValuesFromDynamicData(DS: TDSData); var idx, dp : integer; actualbytes, i, paddedbytes : Word; DV : DopeVector; X : TDataspaceEntry; function ProcessElement(aArray : TDataspaceEntry; DE : TDataspaceEntry; k : word) : word; var b1, b2, b3, b4 : byte; j : integer; begin Result := k; case DE.DataType of dsUByte, dsSByte : begin b1 := DS.DynamicDefaults[dp+k]; if DV.count > 0 then aArray.AddValue(BytesToCardinal(b1)); end; dsUWord, dsSWord : begin b1 := DS.DynamicDefaults[dp+k]; b2 := DS.DynamicDefaults[dp+k+1]; if DV.count > 0 then aArray.AddValue(BytesToCardinal(b1, b2)); end; dsULong, dsSLong : begin b1 := DS.DynamicDefaults[dp+k]; b2 := DS.DynamicDefaults[dp+k+1]; b3 := DS.DynamicDefaults[dp+k+2]; b4 := DS.DynamicDefaults[dp+k+3]; if DV.count > 0 then aArray.AddValue(BytesToCardinal(b1, b2, b3, b4)); end; else if DE.DataType = dsCluster then // an array of cluster begin for j := 0 to DE.SubEntries.Count - 1 do begin k := RoundToByteSize(k, BytesPerType[DE.SubEntries[j].DataType]); k := ProcessElement(DE, DE.SubEntries[j], k); end; end else if DE.DataType = dsArray then // an array of array begin ProcessElement(DE, DE.SubEntries[0], k); end; end; if DE.DataType = dsArray then inc(Result, DV.elemsize) else inc(Result, DE.ElementSize); end; begin dp := 0; idx := 0; while idx < Length(DS.DopeVecs) do begin DV := DS.DopeVecs[idx]; if (DV.backptr <> INVALID_LINK){ and ((DV.count > 0) or (DV.elemsize > 4))} then begin if DV.backptr = NESTED_ARRAY_BACKPTR then begin inc(dp, 4); end else begin X := FindEntryByAddress(DV.backptr); // if X is not assigned it is because this is a nested array if not Assigned(X) then X := ResolveNestedArrayAddress(DS, DV); if (X <> nil) and (X.DataType = dsArray) and ((DV.count > 0) or (X.SubEntries[0].DataType = dsCluster) or // array of cluster or array of array (X.SubEntries[0].DataType = dsArray)) then begin // process the default data for this element // the number of bytes to read from the dynamic defaults array is // (DV.Count * DV.Size) + (4 - ((DV.Count * DV.Size) mod 4)) if DV.count > 0 then actualbytes := Word(DV.count * DV.elemsize) else actualbytes := DV.elemsize; paddedbytes := RoundToByteSize(actualbytes, DWORD_LEN); // read from the current dynamic defaults pointer (dp) i := 0; while i < actualbytes do begin i := ProcessElement(X, X.SubEntries[0], i); end; inc(dp, paddedbytes); end; end; end; inc(idx); end; end; procedure TDataspace.LoadFromDSData(aDS: TDSData); var i : integer; staticIndex : integer; DSE : DSTocEntry; X : TDataspaceEntry; begin Clear; fDSIndexMap.Clear; fDSList.Clear; i := 0; staticIndex := 0; fMMHead := aDS.Head; fMMTail := aDS.Tail; while i < Length(aDS.TOC) do begin DSE := aDS.TOC[i]; X := Self.Add; X.Identifier := aDS.TOCNames[i]; X.DataType := TDSType(DSE.TypeDesc); X.DSID := i; X.DefaultValue := 0; case X.DataType of dsArray : begin inc(i); X.Address := DSE.DataDesc; // data description is the address i := AddArrayItem(aDS, X, i, staticIndex); // root-level arrays have DV index in static dataspace GetStaticDefaults(X, aDS, staticIndex); end; dsCluster : begin // the data descriptor is the number of items in the cluster // we need to process clusters recursively since a cluster // can contain another cluster X.Address := DSE.DataDesc; i := ProcessCluster(aDS, X, i, staticIndex); end; else // all other datatypes are simple scalars X.Address := DSE.DataDesc; // data description is the address // a flags value of 0 for a scalar type means it has a static default value if DSE.Flags = 0 then begin GetStaticDefaults(X, aDS, staticIndex); end; inc(i); end; end; // process dynamic data using dopevectors LoadArrayValuesFromDynamicData(aDS); end; procedure TDataspace.LoadFromStream(aStream: TStream); begin fDSIndexMap.Clear; fDSList.Clear; // TODO: implement TDataspace.LoadFromStream aStream.Position := 0; end; procedure TDataspace.SaveToDSData(aDS: TDSData); var i, j, offset, doffset : integer; cnt, maxAddress, DVAIndex : Word; pTE : ^DSTocEntry; DE : TDataspaceEntry; begin fDSList.Clear; fDSIndexMap.Clear; FinalizeDataspace(self, 0); aDS.Head := 0; aDS.Tail := 0; // add the first dope vector which contains the number of dope vectors // if the dope vector array is empty SetLength(aDS.DopeVecs, 1); with aDS.DopeVecs[0] do begin offset := 0; elemsize := 10; // the size of each dope vector count := 1; // start at 1 backptr := $FFFF; // invalid pointer end; // fill the table of contents maxAddress := 0; doffset := 0; offset := 0; DVAIndex := 1; SetLength(aDS.TOC, fDSList.Count); SetLength(aDS.TOCNames, fDSList.Count); for i := 0 to fDSList.Count - 1 do begin pTE := @(aDS.TOC[i]); DE := TDataspaceEntry(fDSList[i]); aDS.TOCNames[i] := DE.GetFullPathIdentifier; if DE.DataType = dsMutex then DE.DefaultValue := $FFFFFFFF; pTE^.TypeDesc := Byte(Ord(DE.DataType)); if (DE.DefaultValue = 0) and not (DE.DataType in [dsArray, dsCluster]) and not DE.ArrayMember then pTE^.Flags := 1 else pTE^.Flags := 0; pTE^.DataDesc := DE.Address; // these next two fields are only used when outputting the symbol table pTE^.RefCount := Word(DE.RefCount); pTE^.Size := DE.ElementSize; // keep track of the maximum dataspace address if DE.Address >= maxAddress then maxAddress := Word(DE.Address+BytesPerType[DE.DataType]); // generate the static defaults data if (DE.DefaultValue <> 0) and (DE.DataType <> dsArray) then begin // add bytes to static data cnt := BytesPerType[DE.DataType]; SetLength(aDS.StaticDefaults, offset+cnt); for j := 0 to cnt - 1 do begin aDS.StaticDefaults[offset+j] := GetByte(DE.DefaultValue, j); end; inc(offset, cnt); end else if (DE.DataType = dsArray) then begin if not DE.ArrayMember then begin // top-level arrays output DVA index in static data SetLength(aDS.StaticDefaults, offset+BytesPerType[dsArray]); aDS.StaticDefaults[offset] := Lo(Word(DVAIndex)); aDS.StaticDefaults[offset+1] := Hi(Word(DVAIndex)); inc(offset, 2); end; DE.DefaultValue := DVAIndex; inc(DVAIndex); // all arrays get a DVA and we increment the index accordingly end; // generate the dynamic defaults data and dope vectors if (DE.DataType = dsArray) then begin ProcessArray(DE, aDS, doffset); end; end; // now process the dope vectors array and set the offset and link values ProcessDopeVectors(aDS, maxAddress); end; procedure TDataspace.SaveToStream(aStream: TStream); var DS : TDSData; begin DS := TDSData.Create; try SaveToDSData(DS); DS.SaveToStream(aStream); finally DS.Free; end; end; procedure TDataspace.SaveToStrings(aStrings: TStrings); var i : integer; begin aStrings.BeginUpdate; try aStrings.Add('dseg'#9'segment'); // output all unique definitions first aStrings.Add(';------- definitions -------'); for i := 0 to Count - 1 do Items[i].SaveToStrings(aStrings, true); //now output declarations aStrings.Add(';------- declarations -------'); for i := 0 to Count - 1 do Items[i].SaveToStrings(aStrings); aStrings.Add('dseg'#9'ends'); finally aStrings.EndUpdate; end; end; function TDataspace.FindEntryByFullName(const path: string): TDataspaceEntry; var i : integer; begin if fDSIndexMap.Count <> 0 then begin i := fDSIndexMap.IndexOf(path); if i <> -1 then Result := TDataspaceEntry(fDSIndexMap.Objects[i]) else Result := nil; end else Result := inherited FindEntryByFullName(path); end; procedure TDataspace.ProcessDopeVectors(aDS: TDSData; addr: Word); var i, idxEmpty, idxFull : integer; pDV : ^DopeVector; delta : Word; begin // make sure starting address is a 4 byte boundary addr := RoundToByteSize(addr, DWORD_LEN); idxEmpty := 0; idxFull := aDS.Head; for i := 1 to Length(aDS.DopeVecs) - 1 do begin pDV := @(aDS.DopeVecs[i]); if pDV^.count = 0 then begin pDV^.offset := $FFFF; // store the greatest index with an offset of $FFFF as the tail if i > aDS.Tail then aDS.Tail := Word(i); // handle special case of empty arrays of struct or empty nested arrays if pDV^.link <> 0 then begin // increment maxAddress delta := pDV^.elemsize; delta := RoundToByteSize(delta, DWORD_LEN); inc(addr, delta); end; // set link pointer pDV := @(aDS.DopeVecs[idxEmpty]); pDV^.link := Word(i); idxEmpty := i; end else begin pDV^.offset := addr; // if the last element in the array is not empty then link it back to the // first empty element (always 0) // increment maxAddress delta := Word(pDV^.count * pDV^.elemsize); delta := RoundToByteSize(delta, DWORD_LEN); inc(addr, delta); if pDV^.backptr = 0 then begin // a nested array pDV^.backptr := addr; end; // set link pointer if i = idxFull then begin // special case where there is only one non-empty array pDV := @(aDS.DopeVecs[i]); pDV^.link := Word(0); end else begin pDV := @(aDS.DopeVecs[idxFull]); pDV^.link := Word(i); idxFull := i; end; end; end; // link the last Full item back to zero (the first empty item) // unless the last full item is item 0 if idxFull <> 0 then begin pDV := @(aDS.DopeVecs[idxFull]); pDV^.link := 0; end; pDV := @(aDS.DopeVecs[Length(aDS.DopeVecs)-1]); if pDV^.count > 0 then pDV^.link := 0; aDS.DopeVecs[0].offset := RoundToBytesize(addr, DWORD_LEN); aDS.DopeVecs[aDS.Tail].link := $FFFF; end; function TDataspace.GetCaseSensitive: boolean; begin Result := fDSIndexMap.CaseSensitive; end; procedure TDataspace.SetCaseSensitive(const Value: boolean); begin fDSIndexMap.CaseSensitive := Value; end; procedure TDataspace.Compact; var i : integer; begin // this routine removes dataspace entries (root level) // which are not in use. for i := Count - 1 downto 0 do begin if not Items[i].InUse then Delete(i); end; end; function TDataspace.FindEntryAndAddReference(const path: string): TDataspaceEntry; begin Result := FindEntryByFullName(path); if Assigned(Result) then begin AddReference(Result); end; end; procedure TDataspace.RemoveReferenceIfPresent(const path: string); var DE : TDataspaceEntry; begin DE := FindEntryByFullName(path); if Assigned(DE) then RemoveReference(DE); end; procedure TDataspace.ProcessArray(DE: TDataspaceEntry; aDS: TDSData; var doffset : integer); var j, k, bytesWritten : integer; idx, cnt : Word; pDV : ^DopeVector; val : Cardinal; Sub : TDataspaceEntry; begin // 1. Create a new DopeVector entry in our DopeVectorArray idx := Word(Length(aDS.DopeVecs)); // create a dope vector entry for this array SetLength(aDS.DopeVecs, idx+1); pDV := @(aDS.DopeVecs[idx]); // 2. Increment our dope vector count inc(aDS.DopeVecs[0].count); // offset and link values will be calculated after we have finished // 3. Fill in DopeVector values common to all three types of arrays pDV^.elemsize := DE.ArrayElementSize; // NOTE: the backptr value is unused in the 1.03 firmware { TODO: I need to add code here to handle arrays of arrays which output a different backptr value. } if DE.ArrayMember then pDV^.backptr := NESTED_ARRAY_BACKPTR else pDV^.backptr := DE.Address; // the DS address of the array // 4. Fill in the DopeVector values based on array type (array of struct, // array of array, or array of scalar) // 5. Write dynamic default values to the dataspace (by array type) Sub := DE.SubEntries[0]; if (Sub.DataType = dsArray) or DE.ArrayMember then begin // array of array or array of struct or scalar that is itself an array member if DE.ArrayMember and (Sub.DataType <> dsArray) then pDV^.count := 1 else pDV^.count := 0; // an array containing an array always has count of 0 ??? if DE.ArrayMember then k := 2 // nested arrays output DVAIndex ??? else k := 1; // the top level element of a nested array seems to write just one byte (padded) cnt := RoundToByteSize(Word(k), DWORD_LEN); SetLength(aDS.DynamicDefaults, doffset+cnt); pDV^.link := 2; // write to dynamic data bytesWritten := k; if DE.ArrayMember then begin aDS.DynamicDefaults[doffset+0] := GetByte(DE.DefaultValue, 0); aDS.DynamicDefaults[doffset+1] := GetByte(DE.DefaultValue, 1); end else begin aDS.DynamicDefaults[doffset+0] := 1; end; // now write the pad bytes for j := 0 to cnt - bytesWritten - 1 do aDS.DynamicDefaults[doffset+bytesWritten+j] := $FF; end else if Sub.DataType = dsCluster {and not an array member} then begin // array of struct pDV^.count := Word(Sub.ValueCount div Sub.SubEntries.Count); // even if there are not initialization values for an array of struct // we will write out dynamic data for the array anyway if pDV^.count = 0 then cnt := pDV^.elemsize else cnt := Word(pDV^.count * pDV^.elemsize); cnt := RoundToByteSize(cnt, DWORD_LEN); SetLength(aDS.DynamicDefaults, doffset+cnt); // set a flag so that I can tell whether this is an array of struct // or a nested array or an array of scalar pDV^.link := 1; // write to dynamic data // clusters store the initialization data one level down // and it is organized by cluster member DE.SaveToDynamicDefaults(aDS, cnt, doffset); end else begin // non-nested array of scalars pDV^.count := DE.ValueCount; cnt := Word(pDV^.count * pDV^.elemsize); cnt := RoundToByteSize(cnt, DWORD_LEN); SetLength(aDS.DynamicDefaults, doffset+cnt); pDV^.link := 0; // write to dynamic data bytesWritten := 0; for j := 0 to pDV^.count - 1 do begin val := DE.Values[j]; for k := 0 to pDV^.elemsize - 1 do begin aDS.DynamicDefaults[doffset+(j*pDV^.elemsize)+k] := GetByte(val, k); inc(bytesWritten); end; end; // now write the pad bytes for j := 0 to cnt - bytesWritten - 1 do aDS.DynamicDefaults[doffset+bytesWritten+j] := $FF; end; // 6. Update the Memory Manager Head pointer (if needed) // Point the head at this entry if it a) hasn't been set yet and // b) this entry has a count > 0 if (aDS.Head = 0) and (pDV^.count > 0) then aDS.Head := idx; // the index of this entry in the array // 7. Finally, increment the dynamic default data offset pointer inc(doffset, cnt); end; procedure TDataspace.AddReference(DE: TDataspaceEntry); begin // if this item has a parent then incref at the parent level if DE.DSBase.Root <> nil then DE.DSBase.Root.IncRefCount else DE.IncRefCount; end; procedure TDataspace.RemoveReference(DE: TDataspaceEntry); begin if DE.DSBase.Root <> nil then DE.DSBase.Root.DecRefCount else DE.DecRefCount; end; { TDataspaceEntry } procedure TDataspaceEntry.AddValue(aValue: Cardinal); begin fArrayValues.Add(TCardinalObject.Create(aValue)); end; function StripArrayAndStructDelimiters(const str : string) : string; begin Result := Trim(Replace(Replace(Replace(Replace(str, '{', ''), '}', ''), '[', ''), ']', '')); // if the string either starts or ends with a comma then delete it. if Pos(',', Result) = 1 then System.Delete(Result, 1, 1); if LastDelimiter(',', Result) = Length(Result) then System.Delete(Result, Length(Result), 1); Result := Trim(Result); end; function ValueAsCardinal(aValue : Extended; aDST : TDSType = dsVoid) : Cardinal; var iVal : Int64; sVal : Single; begin iVal := Trunc(aValue); if (iVal = aValue) and (aDST <> dsFloat) then Result := Cardinal(iVal) else begin sVal := aValue; Result := SingleToCardinal(sVal); end; end; function CalcDSType(aDSType : TDSType; aValue : Extended) : TDSType; var oldBPT, newBPT : byte; begin Result := GetArgDataType(aValue); if Result <> aDSType then begin oldBPT := BytesPerType[aDSType]; newBPT := BytesPerType[Result]; if oldBPT >= newBPT then begin // we will return the old type since it is >= new type if (Result in [dsSByte, dsSWord, dsSLong]) and (aDSType in [dsUByte, dsUWord, dsULong]) then begin // if new type is signed but old is unsigned then switch to equivalent signed type Result := TDSType(Ord(aDSType)+1); // signed is always unsigned+1 end else begin // in all other cases (old signed, new unsigned or both same) // just return old type Result := aDSType; end; end; end; end; function TDataspaceEntry.AddValuesFromString(Calc : TNBCExpParser; sargs: string) : TDSType; var i : integer; SL : TStringList; x : Byte; fVal : Extended; begin Result := dsUByte; // default value type is unsigned byte sargs := Trim(sargs); // sargs is a comma-separated list of values // it could also be a ? or a {} pair if (sargs = '') or (sargs = '?') or (sargs = '{}') then Exit; SL := TStringList.Create; try // is sargs a quoted string? if QuotedString(sargs) then begin sargs := Copy(sargs, 2, Length(sargs)-2); // remove quotes at both ends for i := 1 to Length(sargs) do begin x := Ord(sargs[i]); case x of 3 : AddValue(9); // tab 4 : AddValue(10); // lf 5 : AddValue(13); // cr 6 : AddValue(Ord('\')); 7 : AddValue(Ord('''')); 8 : AddValue(Ord('"')); else AddValue(x); end; end; // add a null terminator AddValue(0); end else begin sargs := StripArrayAndStructDelimiters(sargs); SL.CommaText := sargs; if DataType = dsCluster then begin // initialize cluster members if Self.ArrayMember then begin for i := 0 to SL.Count - 1 do begin Calc.Expression := SL[i]; fVal := Calc.Value; AddValue(ValueAsCardinal(fVal)); Result := CalcDSType(Result, fVal); end; end else begin for i := 0 to Self.SubEntries.Count - 1 do begin if i < SL.Count then begin Calc.Expression := SL[i]; fVal := Calc.Value; SubEntries[i].DefaultValue := ValueAsCardinal(fVal, SubEntries[i].DataType); Result := CalcDSType(dsUByte, fVal); end; end; end; end else if DataType = dsArray then begin // initialize array // first check whether this is an array of scalars or an array // of structs or array of array if Self.SubEntries[0].DataType in [dsCluster, dsArray] then SubEntries[0].AddValuesFromString(Calc, sargs) else begin for i := 0 to SL.Count - 1 do begin Calc.Expression := SL[i]; fVal := Calc.Value; AddValue(ValueAsCardinal(fVal, Self.SubEntries[0].DataType)); Result := CalcDSType(Result, fVal); end; end; end else begin // initialize scalar types // if there is only one value then used DefaultValue rather // than AddValue Calc.Expression := SL[0]; fVal := Calc.Value; DefaultValue := ValueAsCardinal(fVal, DataType); Result := CalcDSType(dsUByte, fVal); end; end; finally SL.Free; end; end; function TDataspaceEntry.ElementSize(bPad : boolean) : Word; var i, bpt, padBytes : integer; DE : TDataspaceEntry; begin Result := 0; if DataType in [dsVoid..dsSLong, dsMutex, dsFloat] then begin Result := Word(BytesPerType[DataType]); end else begin // handle special cases (arrays of clusters and arrays of arrays) if DataType = dsCluster then begin // calculate the padded size of a cluster for i := 0 to SubEntries.Count - 1 do begin DE := SubEntries[i]; bpt := DE.ElementSize(bPad); // 2006-10-02 JCH recursively calculate the element size // this fixes a problem with the size of arrays containing nested aggregate types if bPad then begin padBytes := bpt - (Result mod bpt); if padBytes < bpt then begin Result := Word(Result + padBytes); end; end; Result := Word(Result + bpt); end; if bPad then Result := RoundToBytesize(Result, DWORD_LEN); end else if DataType = dsArray then begin // TODO: check validity of array of array element size calculation // Result := ArrayElementSize + 4; Result := 4; end else Result := 4; end; end; function TDataspaceEntry.ArrayElementSize(bPad : boolean) : Word; begin Result := 0; if DataType <> dsArray then Exit; if SubEntries[0].DataType = dsArray then Result := 2 else Result := SubEntries[0].ElementSize(bPad); end; procedure TDataspaceEntry.AssignTo(Dest: TPersistent); var i : integer; begin if Dest is TDataspaceEntry then begin TDataspaceEntry(Dest).Identifier := Self.Identifier; TDataspaceEntry(Dest).DataType := Self.DataType; TDataspaceEntry(Dest).DefaultValue := Self.DefaultValue; TDataspaceEntry(Dest).ArrayMember := Self.ArrayMember; TDataspaceEntry(Dest).SubEntries := Self.SubEntries; TDataspaceEntry(Dest).fArrayValues.Clear; for i := 0 to Self.ValueCount - 1 do TDataspaceEntry(Dest).AddValue(Self.Values[i]); end else inherited; end; constructor TDataspaceEntry.Create(ACollection: TCollection); begin inherited; fThreadNames := TStringList.Create; TStringList(fThreadNames).Sorted := True; TStringList(fThreadNames).Duplicates := dupIgnore; fSubEntries := TDSBase.Create; fSubEntries.Parent := Self; fArrayValues := TObjectList.Create; fArrayMember := False; fRefCount := 0; end; destructor TDataspaceEntry.Destroy; begin FreeAndNil(fThreadNames); FreeAndNil(fArrayValues); FreeAndNil(fSubEntries); inherited; end; function TDataspaceEntry.GetInitializationString: string; begin if DataType = dsArray then Result := GetArrayInit else if DataType = dsCluster then Result := GetClusterInit else Result := ValToStr(DataType, DefaultValue); end; function TDataspaceEntry.GetArrayInit: string; var i : integer; bIsString : boolean; Sub : TDataspaceEntry; x : Char; begin Result := ''; if DataType <> dsArray then Exit; // no output if this isn't an array if Self.ArrayMember then Exit; Sub := SubEntries[0]; if Sub.DataType = dsCluster then begin // the values are each considered to be the values of cluster members // so group the values using {} around N elements based on the // cluster definition for i := 0 to Sub.ValueCount - 1 do begin if (i mod Sub.SubEntries.Count) = 0 then begin if Length(Result) > 0 then Delete(Result, Length(Result)-1, MaxInt); if i > 0 then Result := Result + '}, {' else Result := Result + '{'; end; Result := Result + '0x' + IntToHex(Sub.Values[i], 1) + ', '; end; Delete(Result, Length(Result)-1, MaxInt); if Length(Result) > 0 then Result := Result + '}'; end else if Sub.DataType = dsArray then begin Result := Sub.InitializationString; // ???? if Trim(Result) <> '' then Result := '['+Result+']'; end else begin // an array of scalars bIsString := False; if (ValueCount > 1) and (Values[ValueCount - 1] = 0) and (Sub.DataType in [dsUByte, dsSByte]) then begin // at least 2 items and the last one is zero and it is an array of byte // Maybe this is a string??? bIsString := True; for i := 0 to ValueCount - 2 do // skip the 0 at the end begin // check that all values are in the alphanumeric ASCII range if not (Values[i] in [9, 10, 13, 32..126]) then // if (Values[i] < 32) or (Values[i] > 126) then begin bIsString := False; break; end; end; end; if bIsString then begin Result := ''''; for i := 0 to ValueCount - 2 do // skip null begin x := Chr(Values[i]); case x of '"', '''', '\' : Result := Result + '\' + x; #9 : Result := Result + '\t'; #10 : Result := Result + '\n'; #13 : Result := Result + '\r'; else Result := Result + x; end; end; Result := Result + ''''; end else begin for i := 0 to ValueCount - 1 do begin Result := Result + '0x' + IntToHex(Values[i], 1) + ', '; end; Delete(Result, Length(Result)-1, MaxInt); end; end; end; function TDataspaceEntry.GetClusterInit: string; var i : integer; Sub : TDataspaceEntry; begin Result := ''; if DataType <> dsCluster then Exit; // no output if this isn't a cluster for i := 0 to SubEntries.Count - 1 do begin Sub := SubEntries[i]; if Result = '' then Result := Sub.InitializationString else Result := Result + ', ' + Sub.InitializationString; end; if Result <> '' then Result := '{' + Result + '}'; end; function TDataspaceEntry.GetDataTypeAsString: string; begin if DataType = dsCluster then Result := Identifier + '_def' else if DataType = dsArray then begin if SubEntries[0].DataType = dsCluster then Result := SubEntries[0].Identifier + '_def[]' else if SubEntries[0].DataType = dsArray then Result := SubEntries[0].DataTypeAsString + '[]' else Result := TypeToStr(SubEntries[0].DataType) + '[]'; end else Result := TypeToStr(DataType); end; function TDataspaceEntry.GetDSBase: TDSBase; begin Result := TDSBase(Collection); end; function TDataspaceEntry.GetFullPathIdentifier: string; begin // ask my collection what my full path identifier is Result := DSBase.FullPathName(self); end; function TDataspaceEntry.GetValue(idx: integer): Cardinal; begin Result := TCardinalObject(fArrayValues[idx]).Value; end; procedure TDataspaceEntry.LoadFromStream(aStream: TStream); var X : DSTOCEntry; begin X.TypeDesc := 0; X.Flags := 0; X.DataDesc := 0; aStream.Read(X.TypeDesc, 1); aStream.Read(X.Flags, 1); ReadWordFromStream(aStream, X.DataDesc); // copy DSTOCEntry values to collection item X.TypeDesc := Byte(Ord(Self.DataType)); end; procedure TDataspaceEntry.SaveToStream(aStream: TStream); var X : DSTOCEntry; begin // copy collection item values to DSTOCEntry X.TypeDesc := Byte(Ord(DataType)); if DefaultValue <> 0 then X.Flags := 0 else X.Flags := 1; case DataType of dsCluster : X.DataDesc := Word(SubEntries.Count); else X.DataDesc := Address; end; aStream.Write(X.TypeDesc, 1); aStream.Write(X.Flags, 1); WriteWordToStream(aStream, X.DataDesc); end; function Replicate(const str : string; const times : integer) : string; var i : integer; begin Result := ''; for i := 0 to times - 1 do Result := Result + str; end; procedure TDataspaceEntry.SaveToStrings(aStrings: TStrings; bDefine, bInCluster : boolean); var tmpStr : string; i : integer; begin // write self and subentries to strings if bDefine then begin for i := 0 to SubEntries.Count - 1 do SubEntries[i].SaveToStrings(aStrings, True); end; case DataType of dsArray : begin // arrays should have only one sub entry if SubEntries.Count > 0 then begin // if the array type is a structure then define it first and then output // the array declaration tmpStr := Format('%s'#9'%s', [Identifier, DataTypeAsString]); if not bInCluster then tmpStr := tmpStr + Format(#9'%s', [InitializationString]); if not bDefine or bInCluster then aStrings.Add(tmpStr); end; end; dsCluster : begin // definitions are only needed for items which are clusters if bDefine then begin if DataType = dsCluster then begin // only output a definition if this item is the first of its type tmpStr := Format('%s_def'#9'%s', [Identifier, 'struct']); aStrings.Add(tmpStr); for i := 0 to SubEntries.Count - 1 do SubEntries[i].SaveToStrings(aStrings, False, True); tmpStr := Format('%s_def'#9'%s', [Identifier, 'ends']); aStrings.Add(tmpStr); end; end else begin tmpStr := Format('%s'#9'%s'#9'%s', [Identifier, DataTypeAsString, InitializationString]); aStrings.Add(tmpStr); end; end; dsVoid, dsMutex : begin tmpStr := Format('%s'#9'%s', [Identifier, DataTypeAsString]); if not bDefine or bInCluster then aStrings.Add(tmpStr); end; else // scalars & floats tmpStr := Format('%s'#9'%s', [Identifier, DataTypeAsString]); if not {bDefine}bInCluster then tmpStr := tmpStr + Format(#9'%s', [InitializationString]); if not bDefine or bInCluster then aStrings.Add(tmpStr); end; end; procedure TDataspaceEntry.SetArrayMember(const Value: boolean); var i : integer; begin fArrayMember := Value; // iterate through all sub entries for i := 0 to SubEntries.Count - 1 do SubEntries[i].ArrayMember := Value; end; procedure TDataspaceEntry.SetIdentifier(const Value: string); begin fIdentifier := Value; DSBase.fEntryIndex.AddObject(Self.FullPathIdentifier, Self); DSBase.CheckEntry(self); end; procedure TDataspaceEntry.SetSubEntries(const Value: TDSBase); begin fSubEntries.Assign(Value); end; function TDataspaceEntry.ValueCount: Word; begin Result := Word(fArrayValues.Count); end; procedure TDataspaceEntry.SaveToDynamicDefaults(aDS: TDSData; const cnt, doffset: integer); var elemsize : integer; X : TDataspaceEntry; procedure DoSaveToDynDefaults; var idx, vc : integer; val : Cardinal; j, bytesWritten : word; bpt : Byte; i, k : integer; begin if X.ValueCount = 0 then vc := X.SubEntries.Count else vc := X.ValueCount; // we need to write a total of cnt bytes to aDS.DynamicDefaults at // offset == doffset // the values come from SubEntries[0].Values[n] bytesWritten := 0; j := 0; for i := 0 to vc - 1 do begin if X.ValueCount = 0 then val := 0 else val := X.Values[i]; idx := i mod X.SubEntries.Count; // calculate the field index bpt := BytesPerType[X.SubEntries[idx].DataType]; if (idx = 0) and (i <> 0) then begin // we have wrapped around to another element in the array // pad to full structure size. // j must be within 0..elemsize-1 j := Word((elemsize - (j mod elemsize)) mod elemsize); for k := 0 to j - 1 do aDS.DynamicDefaults[doffset+bytesWritten+k] := $FF; inc(bytesWritten, j); j := bytesWritten; end; // are we at the right boundary for the next (current) struct field? j := RoundToBytesize(j, bpt); if j > bytesWritten then for k := 0 to j - bytesWritten - 1 do aDS.DynamicDefaults[doffset+bytesWritten+k] := $FF; bytesWritten := j; // now we are ready to output this field's value for k := 0 to bpt - 1 do begin aDS.DynamicDefaults[doffset+j+k] := GetByte(val, k); inc(bytesWritten); end; j := bytesWritten; end; // if we haven't written the full cnt bytes out then pad. for k := 0 to cnt - bytesWritten - 1 do aDS.DynamicDefaults[doffset+bytesWritten+k] := $FF; end; begin // this routine is for saving array of struct or array of arrays to dynamic data if DataType <> dsArray then Exit; if SubEntries.Count <> 1 then Exit; elemsize := ArrayElementSize; X := SubEntries[0]; if X.DataType in [dsCluster, dsArray] then begin DoSaveToDynDefaults; end; end; function TDataspaceEntry.GetInUse: boolean; var i : integer; begin Result := fRefCount > 0; if not Result and (DataType = dsCluster) then begin for i := 0 to SubEntries.Count - 1 do begin Result := SubEntries[i].InUse; if Result then Break; end; end; end; function TDataspaceEntry.GetRefCount: integer; begin Result := fRefCount; end; procedure TDataspaceEntry.IncRefCount; var i : integer; begin inc(fRefCount); // check sub entries if this entry is a cluster if DataType = dsCluster then begin for i := 0 to SubEntries.Count - 1 do begin SubEntries[i].IncRefCount; end; end; end; procedure TDataspaceEntry.DecRefCount; var i : integer; begin dec(fRefCount); if DataType = dsCluster then begin for i := 0 to SubEntries.Count - 1 do begin SubEntries[i].DecRefCount; end; end; end; function TDataspaceEntry.GetArrayBaseType: TDSType; begin Result := DataType; if IsArray then Result := SubEntries[0].BaseDataType; end; function TDataspaceEntry.GetIsArray: boolean; begin Result := DataType = dsArray; end; procedure TDataspaceEntry.AddThread(const aThreadName: string); begin fThreadNames.Add(aThreadName); end; function TDataspaceEntry.ThreadCount: integer; begin Result := fThreadNames.Count; end; { TRXEProgram } constructor TRXEProgram.Create; begin inherited; fMaxPreprocDepth := 10; fMaxErrors := 0; fIgnoreSystemFile := False; fEnhancedFirmware := False; fWarningsOff := False; fReturnRequired := False; fCaseSensitive := True; fStandardDefines := True; fExtraDefines := True; fCompVersion := 5; fProductVersion := GetProductVersion; CreateObjects; InitializeHeader; FirmwareVersion := 128; // 1.28 NXT 2.0 firmware end; destructor TRXEProgram.Destroy; begin FreeObjects; inherited; end; procedure TRXEProgram.LoadFromStream(aStream: TStream); begin // TODO: implement loadfromstream aStream.Position := 0; end; function TRXEProgram.SaveToFile(const filename: string) : boolean; var MS : TMemoryStream; begin MS := TMemoryStream.Create; try Result := SaveToStream(MS); MS.SaveToFile(filename); finally MS.Free; end; end; function TRXEProgram.SaveToStream(aStream: TStream) : boolean; begin Result := False; if fBadProgram then begin fMsgs.Add(Format(sProgramError, [fProgErrorCount])); end else begin DoCompilerStatusChange(sNBCFinalizeDepends); // make sure our dependencies are finalized Codespace.FinalizeDependencies; // possibly optimize if Optimize level > 0 if OptimizeLevel >= 1 then begin DoCompilerStatusChange(Format(sNBCOptimizeLevel, [OptimizeLevel])); DoCompilerStatusChange(sNBCBuildRefs); // build references if we are optimizing Codespace.BuildReferences; DoCompilerStatusChange(sNBCOptMutexes); // optimize mutexes Codespace.OptimizeMutexes; DoCompilerStatusChange(sNBCCompactCode); // compact the codespace before codespace optimizations Codespace.Compact; DoCompilerStatusChange(sNBCRemoveLabels); // also get rid of extra labels Codespace.RemoveUnusedLabels; // 2009-03-18 JCH: I have restored the level 2 optimizations // As defects are revealed they will be fixed Some optimizations // will be only performed at levels higher than 2 so I now pass the // level into the optimization function itself. if OptimizeLevel >= 2 then begin DoCompilerStatusChange(sNBCRunCodeOpts); Codespace.Optimize(OptimizeLevel); DoCompilerStatusChange(sNBCCompactAfterOpt); // after optimizations we should re-compact the codespace Codespace.Compact; end; // after optimizing and compacting the codespace we remove // unused variables from the dataspace DoCompilerStatusChange(sNBCCompactData); Dataspace.Compact; end else begin // level zero (no optimizations) DoCompilerStatusChange(sNBCRemoveLabels); // also get rid of extra labels Codespace.RemoveUnusedLabels; // after optimizing and compacting the codespace we remove // unused variables from the dataspace DoCompilerStatusChange(sNBCCompactData); Dataspace.Compact; end; if not WarningsOff then OutputUnusedItemWarnings; DoCompilerStatusChange(sNBCSortDataspace); // sort the dataspace Dataspace.Sort; DoCompilerStatusChange(sNBCGenerateRawDS); // write the dataspace to DSData Dataspace.SaveToDSData(fDSData); DoCompilerStatusChange(sNBCFillCodeArrays); // fill the clumprecords and codespace array Codespace.SaveToCodeData(fClumpData, fCode); DoCompilerStatusChange(sNBCUpdateHeader); // having done that I can now update the header UpdateHeader; // and write everything to the stream aStream.Position := 0; DoCompilerStatusChange(sNBCWriteHeader); WriteHeaderToStream(aStream, fHeader); DoCompilerStatusChange(sNBCWriteDataspace); fDSData.SaveToStream(aStream); DoCompilerStatusChange(sNBCWriteClumpData); fClumpData.SaveToStream(aStream); DoCompilerStatusChange(sNBCWriteCodespace); fCode.SaveToStream(aStream); Result := not fBadProgram; if Result then begin DoCompilerStatusChange(sNBCWriteOptSource); // replace the original "compiler output" with the optimized version SaveToStrings(CompilerOutput); end; end; DoCompilerStatusChange(sNBCFinished, True); end; function TRXEProgram.GetVersion: byte; begin Result := fHeader.Version; end; procedure TRXEProgram.SetVersion(const Value: byte); begin fHeader.Version := Value; end; function TRXEProgram.GetFormat: string; begin Result := fHeader.FormatString; end; procedure TRXEProgram.SetFormat(const Value: string); var i : integer; begin for i := 0 to 12 do fHeader.FormatString[i] := Value[i]; fHeader.FormatString[13] := #0; end; function TRXEProgram.GetClumpCount: Word; begin Result := fHeader.ClumpCount; end; function TRXEProgram.GetCodespaceCount: Word; begin Result := fHeader.CodespaceCount; end; function TRXEProgram.GetDSCount: Word; begin Result := fHeader.DSCount; end; function TRXEProgram.GetDSDefaultsSize: Word; begin Result := fHeader.DSDefaultsSize; end; function TRXEProgram.GetDSSize: Word; begin Result := fHeader.DSSize; end; function TRXEProgram.GetDVArrayOffset: Word; begin Result := fHeader.DVArrayOffset; end; function TRXEProgram.GetDynDSDefaultsOffset: Word; begin Result := fHeader.DynDSDefaultsOffset; end; function TRXEProgram.GetDynDSDefaultsSize: Word; begin Result := fHeader.DynDSDefaultsSize; end; function TRXEProgram.GetMemMgrHead: Word; begin Result := fHeader.MemMgrHead; end; function TRXEProgram.GetMemMgrTail: Word; begin Result := fHeader.MemMgrTail; end; function TRXEProgram.Parse(aStream: TStream) : string; var S : TStrings; begin S := TStringList.Create; try S.LoadFromStream(aStream); Result := Parse(S); finally S.Free; end; end; procedure TRXEProgram.LoadSystemFile(S : TStream); var tmp : string; begin // load fMS with the contents of NBCCommon.h followed by NXTDefs.h tmp := '#line 0 "NXTDefs.h"'#13#10; S.Write(PChar(tmp)^, Length(tmp)); S.Write(nbc_common_data, High(nbc_common_data)+1); S.Write(nxt_defs_data, High(nxt_defs_data)+1); tmp := '#reset'#13#10; S.Write(PChar(tmp)^, Length(tmp)); end; function TRXEProgram.Parse(aStrings: TStrings) : string; var i, idx : integer; P : TLangPreprocessor; S : TMemoryStream; tmpFile, tmpMsg : string; begin DoCompilerStatusChange(sNBCCompBegin); DoCompilerStatusChange(Format(sCompileTargets, [FirmwareVersion, BoolToString(EnhancedFirmware)])); Result := ''; try if not IgnoreSystemFile then begin S := TMemoryStream.Create; try DoCompilerStatusChange(sNBCLoadSystemFiles); LoadSystemFile(S); aStrings.SaveToStream(S); S.Position := 0; aStrings.LoadFromStream(S); finally S.Free; end; end; fBadProgram := False; fProgErrorCount := 0; LineCounter := 0; fAbsCount := 0; fSignCount := 0; fShiftCount := 0; fMainStateLast := masCodeSegment; // used only when we enter a block comment fMainStateCurrent := masCodeSegment; // default state P := TLangPreprocessor.Create(TNBCLexer, ExtractFilePath(ParamStr(0)), lnNBC, MaxPreprocessorDepth); try P.OnPreprocessorStatusChange := HandlePreprocStatusChange; P.Defines.AddDefines(Defines); if EnhancedFirmware then P.Defines.Define('__ENHANCED_FIRMWARE'); P.Defines.AddEntry('__FIRMWARE_VERSION', IntToStr(FirmwareVersion)); P.AddIncludeDirs(IncludeDirs); if not IgnoreSystemFile then begin P.SkipIncludeFile('NBCCommon.h'); P.SkipIncludeFile('NXTDefs.h'); end; DoCompilerStatusChange(sNBCPreprocess); // Preprocess returns a list of files from #download statements Result := P.Preprocess(GetCurrentFile(true), aStrings); for i := 0 to P.Warnings.Count - 1 do begin tmpMsg := P.Warnings.ValueFromIndex[i]; idx := Pos('|', tmpMsg); tmpFile := Copy(tmpMsg, 1, idx-1); Delete(tmpMsg, 1, idx); ReportProblem(StrToIntDef(P.Warnings.Names[i], 0), tmpFile, '', tmpMsg, false); end; finally P.Free; end; // aStrings.SaveToFile('preproc.txt'); DoCompilerStatusChange(sNBCCompilingSource); i := 0; while i < aStrings.Count do begin if fSkipCount = 0 then LineCounter := LineCounter + 1; ProcessASMLine(aStrings, i); inc(i); if fSkipCount > 0 then Dec(fSkipCount); end; DoCompilerStatusChange(sNBCCompFinished); CheckMainThread; if not fBadProgram then fBadProgram := Codespace.Count = 0; if not fBadProgram then fCompilerOutput.Assign(aStrings); except on E : EAbort do begin fBadProgram := True; // end processing file due to Abort in ReportProblem end; on E : EPreprocessorException do begin fBadProgram := True; ReportProblem(E.LineNo, GetCurrentFile(true), sException, E.Message, true); end; on E : Exception do begin fBadProgram := True; ReportProblem(LineCounter, GetCurrentFile(true), sException, E.Message, true); end; end; end; function GetValidLineTypes(const state : TMainAsmState) : TAsmLineTypes; begin case state of masClump : Result := [altEndClump, altBeginDS, altCode, altCodeDepends]; masClumpSub : Result := [altEndSub, altBeginDS, altCode]; masCodeSegment : Result := [altBeginClump, altBeginDS, altBeginSub]; masStruct : Result := [altEndStruct, altVarDecl]; masDSClump : Result := [altEndDS, altVarDecl, altTypeDecl, altBeginStruct]; masStructDSClump : Result := [altEndStruct, altVarDecl]; masDSClumpSub : Result := [altEndDS, altVarDecl, altTypeDecl, altBeginStruct]; masStructDSClumpSub : Result := [altEndStruct, altVarDecl]; else // masDataSegment Result := [altEndDS, altVarDecl, altTypeDecl, altBeginStruct]; end; end; function CommasToSpaces(const line : string) : string; var i, len : integer; bInString : boolean; ch : Char; begin i := Pos('''', line); // is there a string initializer on this line? if i > 0 then begin // if there is a string on this line then process a character at a time bInString := False; Result := ''; len := Length(line); for i := 1 to len do begin ch := line[i]; if (ch = ',') and not bInString then ch := ' ' // else if (not bInString and (ch = '''')) or // (bInString and (ch = '''') and // ((i = len) or (line[i+1] <> ''''))) then else if ch = '''' then bInString := not bInString; Result := Result + ch; end; end else Result := Replace(line, ',', ' '); end; function TRXEProgram.DetermineLineType(const state : TMainAsmState; namedTypes: TMapList; op : string; bUseCase : boolean) : TAsmLineType; begin // special handling for [] at end of opcode op := Replace(op, '[]', ''); case StrToOpcode(op, bUseCase) of OP_ADD..OP_GETTICK : Result := altCode; OPS_WAITV..OPS_POW : Result := altCode; // pseudo opcodes // OPS_SQRT_2..OPS_ABS_2 : Result := altCode; // standard 1.26+ opcodes (included in OPS_WAITV..OPS_POW due to overlap) OPS_WAITI_2..OPS_ADDROF : Result := altCode; // enhanced 1.26+ opcodes OPS_SEGMENT : Result := altBeginDS; OPS_ENDS : if state in [masStruct, masStructDSClump, masStructDSClumpSub] then Result := altEndStruct else if state = masClumpSub then Result := altEndSub else Result := altEndDS; OPS_TYPEDEF : Result := altTypeDecl; OPS_THREAD : Result := altBeginClump; OPS_ENDT : Result := altEndClump; OPS_SUBROUTINE : Result := altBeginSub; OPS_STRUCT : Result := altBeginStruct; OPS_REQUIRES, OPS_USES : Result := altCodeDepends; OPS_DB..OPS_FLOAT : Result := altVarDecl; OPS_CALL..OPS_COMPCHKTYPE : Result := altCode; // pseudo opcodes else // if the opcode isn't known perhaps it is a typedef if state in [masDataSegment, masStruct, masDSClump, masStructDSClump, masDSClumpSub, masStructDSClumpSub] then begin if namedTypes.IndexOf(op) <> -1 then Result := altVarDecl else Result := altInvalid; end else Result := altInvalid; end; end; procedure TrimComments(var line : string; p : integer; const sub : string); var k, j, x : integer; tmp : string; begin // before we decide to trim these comment we need to know whether they are // embedded in a string or not. tmp := line; while (p > 0) do begin k := Pos('''', tmp); j := 0; if k < p then begin // hmmm, is there another single quote? tmp := Copy(tmp, k+1, MaxInt); j := Pos('''', tmp); tmp := Copy(tmp, j+1, MaxInt); j := j + k; end; if not ((p > k) and (p < j)) then begin Delete(line, p, MaxInt); // trim off any trailing comment line := TrimRight(line); // trim off any trailing whitespace tmp := line; p := 0; end else p := j; x := Pos(sub, tmp); if x > 0 then inc(p, x-1) else p := 0; end; end; function NBCExtractStrings(str : string; values : TStrings) : integer; var s, p : integer; begin // between 0 and 3 entries in values when I'm done values.Clear; str := Replace(str, #9, ' '); s := Pos(' ', str); p := Pos(',', str); while (s > 0) and (s < p) do begin if values.Count > 1 then Break; values.Add(Copy(str, 1, s-1)); System.Delete(str, 1, s); str := Trim(str); s := Pos(' ', str); p := Pos(',', str); end; if str <> '' then values.Add(str); Result := values.Count; end; procedure TRXEProgram.ChunkLine(const state : TMainAsmState; namedTypes: TMapList; line : string; bUseCase : boolean; var lbl, opcode, args : string; var lineType : TAsmLineType; var bIgnoreDups : boolean); var i : integer; tmp : string; values : TStringList; begin bIgnoreDups := True; lbl := ''; opcode := ''; args := ''; lineType := altInvalid; // break apart the line into its constituent parts // whitespace at the beginning and end of the line has already been trimmed. // if the first word in the line is an opcode (of any kind) then // the label is blank and everything after the opcode is the args // if the first word is NOT an opcode then we assume it is a label // and we check the second word for whether it is an opcode or not // if it is not then the line is invalid. If it is then everything after // the second word is the args i := Pos(';', line); if i <> 0 then TrimComments(line, i, ';'); i := Pos('//', line); if i <> 0 then TrimComments(line, i, '//'); values := TStringList.Create; try line := CommasToSpaces(line); i := JCHExtractStrings([' ', #9], [], PChar(line), values); if i = 1 then begin if StrToOpcode(values[0], bUseCase) = OPS_INVALID then begin // if there is only one item in the line and it isn't an opcode // then it should be a label // with an required trailing ':'. If the colon is missing then // the line is invalid i := Pos(':', line); if i = Length(line) then begin lbl := Copy(line, 1, i-1); lineType := altCode; end; end else begin // it could be an endt or ends opcode to end the current thread/subroutine lbl := ''; opcode := values[0]; lineType := DetermineLineType(state, namedTypes, opcode, bUseCase); end; end else if (i > 1) and (i < 3) then begin // special case is the dseg segment and dseg ends lines tmp := values[0]; if tmp = 'dseg' then begin lbl := tmp; opcode := values[1]; bIgnoreDups := (values.Count = 3) and (values[2] = '1'); if opcode = OpcodeToStr(OPS_SEGMENT) then lineType := altBeginDS else if opcode = OpcodeToStr(OPS_ENDS) then lineType := altEndDS; end else begin // if the first item is a known opcode then assume no label // exists in this line if StrToOpcode(values[0], bUseCase) = OPS_INVALID then begin // label + opcode and no args lbl := values[0]; opcode := values[1]; end else begin // no label - just opcode and args lbl := ''; opcode := values[0]; values.Delete(0); args := Trim(values.CommaText); end; lineType := DetermineLineType(state, namedTypes, opcode, bUseCase); end; end else begin // i >= 3 // if the first item is a known opcode then assume no label // exists in this line if StrToOpcode(values[0]) = OPS_INVALID then begin lbl := values[0]; opcode := values[1]; values.Delete(0); values.Delete(0); end else begin lbl := ''; opcode := values[0]; values.Delete(0); end; if values.Count = 1 then args := Trim(values[0]) else args := Trim(values.CommaText); lineType := DetermineLineType(state, namedTypes, opcode, bUseCase); end; finally values.Free; end; end; procedure InstantiateCluster(DD : TDataDefs; DE: TDataspaceEntry; const clustername: string); var idx : integer; Def : TDataspaceEntry; begin DE.TypeName := clustername; // find an entry in the datadefs collection with clustername idx := DD.IndexOfName(clustername); if idx <> -1 then begin Def := DD[idx]; DE.SubEntries := Def.SubEntries; end; end; procedure HandleVarDecl(DD : TDataDefs; NT : TMapList; bCaseSensitive : boolean; DSE : TDataspaceEntry; albl, aopcode : string; sttFunc : TSTTFuncType); var stype : string; idx, p, len : integer; Sub : TDataspaceEntry; begin DSE.Identifier := albl; stype := aopcode; p := Pos('[]', stype); len := Length(stype); // calculate the named type index without [] if there are any if p > 0 then begin Delete(aopcode, len-1, 2); // assumes that [] are last two characters stype := aopcode; end; idx := NT.IndexOf(stype); if idx <> -1 then stype := NT.MapValue[idx]; if (p > 0) then begin // this is an array type DSE.DataType := dsArray; DSE.TypeName := stype; Sub := DSE.SubEntries.Add; Sub.Identifier := DSE.Identifier + '_type'; // could be an array of structs (yuck!) if (idx <> -1) and (aopcode = stype) then begin // must be a struct type Sub.DataType := dsCluster; InstantiateCluster(DD, Sub, stype); end else begin HandleVarDecl(DD, NT, bCaseSensitive, Sub, Sub.Identifier, aopcode, sttFunc); end; Sub.DefaultValue := 0; Sub.ArrayMember := True; end else if (idx <> -1) and (aopcode = stype) then begin DSE.DataType := dsCluster; InstantiateCluster(DD, DSE, stype); end else begin // a simple type DSE.DataType := sttFunc(stype, bCaseSensitive); end; end; procedure TRXEProgram.ProcessASMLine(aStrings: TStrings; var idx : integer); var i, endBCPos, cPos, len, oldIdx : integer; lbl, opcode, args, errMsg, tmpFile, tmpLine, line, varName : string; lineType : TASMLineType; ValidLineTypes : TASMLineTypes; DE : TDataspaceEntry; AL : TAsmLine; inBlockComment : boolean; theOp : TOpCode; begin try lineType := altInvalid; args := ''; opcode := ''; lbl := ''; line := aStrings[idx]; oldIdx := idx; // check for and handle the case where the line ends with \ indicating that // the line continues on the next line. len := Length(line); if len > 0 then begin while (line[len] = '\') and (idx < aStrings.Count - 1) do begin System.Delete(line, len, 1); // delete the '\' inc(idx); line := line + aStrings[idx]; len := Length(line); aStrings[idx] := ''; // clear the current line end; if line[len] = '\' then System.Delete(line, len, 1); end; line := ReplaceTokens(Trim(line)); aStrings[oldIdx] := line; // do nothing if line is blank or a comment if (line = '') or (Pos(';', line) = 1) or (Pos('//', line) = 1) then Exit; line := ReplaceSpecialStringCharacters(line); i := Pos('#line ', line); if i = 1 then begin // this is a special preprocessor line tmpLine := line; Delete(line, 1, 6); i := Pos(' ', line); LineCounter := StrToIntDef(Copy(line, 1, i - 1), LineCounter); Delete(line, 1, i); tmpFile := Replace(line, '"', ''); tmpFile := Replace(tmpFile, '''', ''); CurrentFile := tmpFile; if fMainStateCurrent in [masClump, masClumpSub] then begin // add code to the current clump AL := fCurrentClump.ClumpCode.Add; AL.AsString := tmpLine; AL.LineNum := LineCounter; end; end else if Pos('#download', line) = 1 then begin // ignore #download lines // if we are in a clump then add a special asm line for the #download // otherwise just skip it. if fMainStateCurrent in [masClump, masClumpSub] then begin // add code to the current clump AL := fCurrentClump.ClumpCode.Add; AL.AsString := line; AL.LineNum := LineCounter; end; end else if Pos('#reset', line) = 1 then begin tmpLine := line; LineCounter := 1; if fMainStateCurrent in [masClump, masClumpSub] then begin // add code to the current clump AL := fCurrentClump.ClumpCode.Add; AL.AsString := tmpLine; AL.LineNum := LineCounter; end; end else if Pos('#pragma ', line) = 1 then begin // this is a special preprocessor line // if we are in a clump then add a special asm line for the #pragma // otherwise just skip it. if fMainStateCurrent in [masClump, masClumpSub] then begin // add code to the current clump AL := fCurrentClump.ClumpCode.Add; AL.AsString := line; AL.LineNum := LineCounter; if Pos('safecalling', line) > 0 then CodeSpace.Multithread(fCurrentClump.Name); end; // is this a special #pragma macro line? if Pos('macro', line) = 9 then begin System.Delete(line, 1, 14); fSkipCount := StrToIntDef(line, 0)+1; end; end else begin // check for the possibility that we are starting or ending a block comment on this line // nesting block comments is not supported and will result in compiler errors i := Pos('/*', line); endBCPos := Pos('*/', line); if (endBCPos = 0) or ((fMainStateCurrent <> masBlockComment) and (endBCPos = 0)) then inBlockComment := i > 0 else if endBCPos <> 0 then inBlockComment := i > endBCPos+1 else inBlockComment := False; if (endBCPos > 0) and (fMainStateCurrent = masBlockComment) then begin // remove everything from line up to end block comment Delete(line, 1, endBCPos+1); // revert to previous state fMainStateCurrent := fMainStateLast; end; if inBlockComment then begin Delete(line, i, MaxInt); // delete to end of line end else if (i > 0) and (endBCPos > i+1) then begin // just remove the block comment portion of the line Delete(line, i, endBCPos-i+2); // we don't want a block comment remove to result in a valid // identifier or function Insert(' ', line, i); end; // if we were already in a block comment before starting this line // and we still are in a block comment after the above processing // then we can skip the rest of this routine if fMainStateCurrent = masBlockComment then Exit; // double check for a blank line since we have manipulated it if Trim(line) <> '' then begin // go ahead and process this line as normal // chunk the line into its consituent parts ChunkLine(fMainStateCurrent, fNamedTypes, line, CaseSensitive, lbl, opcode, args, lineType, fIgnoreDupDefs); // what state are we in? ValidLineTypes := GetValidLineTypes(fMainStateCurrent); if lineType in ValidLineTypes then begin case fMainStateCurrent of masClump, masClumpSub : begin // 1. end of clump/sub // 2. start of datasegment // 3. code if (lineType = altEndClump) or (lineType = altEndSub) then begin fIgnoreLines := False; fCurrentClump.LastLine := LineCounter; fMainStateCurrent := masCodeSegment; // at the end of the current clump we can validate labels ValidateLabels(fCurrentClump); if ReturnRequiredInSubroutine and (lineType = altEndSub) then begin // the last line of a subroutine must be a return!!! if (fCurrentClump.ClumpCode.Count > 0) then begin AL := fCurrentClump.ClumpCode[fCurrentClump.ClumpCode.Count-1]; if AL.Command <> OP_SUBRET then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sNoReturnAtEndOfSub, true); end else ReportProblem(LineCounter, GetCurrentFile(true), line, sNoReturnAtEndOfSub, true); end; ProcessSpawnedThreads; // if we have just ended a clump we may need to create a new // one if the clump uses the wait opcode. if fClumpUsesWait then CreateWaitClump(fCurrentClump.Name); fClumpName := ''; end else if lineType = altBeginDS then begin if fMainStateCurrent = masClump then fMainStateCurrent := masDSClump else fMainStateCurrent := masDSClumpSub; end else if lineType = altCode then begin // add code to the current clump AL := fCurrentClump.ClumpCode.Add; cPos := Pos(':', lbl); if cPos > 0 then System.Delete(lbl, cPos, MaxInt); lbl := Trim(lbl); if lbl <> '' then begin AL.LineLabel := lbl; if fCurrentClump.IndexOfLabel(lbl) = -1 then fCurrentClump.AddLabel(lbl, AL) else begin errMsg := Format(sDuplicateLabel, [lbl]); ReportProblem(LineCounter, GetCurrentFile(true), line, errMsg, true); end; end; AL.LineNum := LineCounter; theOp := StrToOpcode(opcode, CaseSensitive); AL.Command := theOp; AL.AddArgs(args); HandleConstantExpressions(AL); if not fIgnoreLines then CheckArgs(AL); HandlePseudoOpcodes(AL, theOp{, args}); if fIgnoreLines then AL.Command := OPS_INVALID; end else if (lineType = altCodeDepends) then begin if not fIgnoreLines then fCurrentClump.AddClumpDependencies(opcode, args); end; end; masCodeSegment : begin // 1. start of clump/sub // 2. start of datasegment if lineType = altBeginDS then fMainStateCurrent := masDataSegment else begin if lineType = altBeginSub then fMainStateCurrent := masClumpSub else fMainStateCurrent := masClump; // starting a clump so define one fClumpUsesWait := False; fClumpUsesSign := False; fClumpUsesShift := False; fIgnoreLines := False; fVarI := 0; // each clump starts with I and J reset to 0. fVarJ := 0; fCurrentClump := CodeSpace.Add; fCurrentClump.Name := args; fClumpName := fCurrentClump.Name; fCurrentClump.IsSubroutine := fMainStateCurrent = masClumpSub; fCurrentClump.Filename := GetCurrentFile(true); if fCurrentClump.IsSubroutine then begin varName := Format('__%s_return', [fCurrentClump.Name]); // subroutines each have their own unsigned byte variable in // the dataspace to store the return address DefineVar(varName, SubroutineReturnAddressType); end; end; end; masStruct, masStructDSClump, masStructDSClumpSub : begin // we are inside a structure definition // the only valid line type are: // 1. end of structure definition // 2. variable declaration if lineType = altEndStruct then begin if fMainStateCurrent = masStructDSClump then fMainStateCurrent := masDSClump else if fMainStateCurrent = masStructDSClumpSub then fMainStateCurrent := masDSClumpSub else fMainStateCurrent := masDataSegment end else if lineType = altVarDecl then begin // add a member to the current structure definition DE := fCurrentStruct.SubEntries.Add; HandleVarDecl(DataDefinitions, fNamedTypes, CaseSensitive, DE, lbl, opcode, @StrToType); // the args value is an initializer DE.AddValuesFromString(Calc, args); end; end; masDatasegment, masDSClump, masDSClumpSub : begin // 1. end of datasegment // 2. variable declaration // 3. type declaration // 4. start of struct definition if lineType = altEndDS then begin if fMainStateCurrent = masDataSegment then fMainStateCurrent := masCodeSegment else if fMainStateCurrent = masDSClumpSub then fMainStateCurrent := masClumpSub else fMainStateCurrent := masClump; end else if lineType = altVarDecl then begin // add a variable declaration to the dataspace DE := Dataspace.Add; HandleVarDecl(DataDefinitions, fNamedTypes, CaseSensitive, DE, lbl, opcode, @StrToType); // the args value is an initializer if args <> '' then args := StripExtraQuotes(args); DE.AddValuesFromString(Calc, args); end else if lineType = altTypeDecl then begin // add a named type alias if fNamedTypes.IndexOf(lbl) = -1 then fNamedTypes.AddEntry(lbl, args) else raise Exception.CreateFmt(sDuplicateType, [lbl]); end else if lineType = altBeginStruct then begin if fMainStateCurrent = masDataSegment then fMainStateCurrent := masStruct else if fMainStateCurrent = masDSClumpSub then fMainStateCurrent := masStructDSClumpSub else fMainStateCurrent := masStructDSClump; // add a named type alias if fNamedTypes.IndexOf(lbl) = -1 then fNamedTypes.AddEntry(lbl, lbl) else raise Exception.CreateFmt(sDuplicateType, [lbl]); // create a new structure definition fCurrentStruct := DataDefinitions.Add; fCurrentStruct.Identifier := lbl; end; end; end; end else begin if not fIgnoreLines then begin // tell the user what type of line was found and // what the current state is if lineType = altInvalid then errMsg := sInvalidStatement else errMsg := Format(sInvalidLine, [LineTypeToStr(lineType), ASMStateToStr(fMainStateCurrent)]); ReportProblem(LineCounter, GetCurrentFile(true), line, errMsg, true); end; end; end; // now handle the fact that we may have stated a block comment on this line if inBlockComment then begin fMainStateLast := fMainStateCurrent; fMainStateCurrent := masBlockComment; end; end; except on E : Exception do begin ReportProblem(LineCounter, GetCurrentFile(true), line, E.Message, true); end; end; end; procedure TRXEProgram.ReportProblem(const lineNo: integer; const fName, line, msg: string; err : boolean); var tmp, tmp1, tmp2, tmp3, tmp4 : string; stop : boolean; begin // exit without doing anything if this is not an error and warnings are off if WarningsOff and not err then Exit; if lineNo = -1 then begin tmp := msg; fMsgs.Add(tmp); end else begin if err then tmp1 := Format('# Error: %s', [msg]) else tmp1 := Format('# Warning: %s', [msg]); fMsgs.Add(tmp1); tmp2 := Format('File "%s" ; line %d', [fName, lineNo]); fMsgs.Add(tmp2); tmp3 := Format('# %s', [line]); fMsgs.Add(tmp3); tmp4 := '#----------------------------------------------------------'; fMsgs.Add(tmp4); tmp := tmp1+#13#10+tmp2+#13#10+tmp3+#13#10+tmp4; end; fBadProgram := err; if err then inc(fProgErrorCount); stop := (MaxErrors > 0) and (fProgErrorCount >= MaxErrors); if assigned(fOnCompMsg) then fOnCompMsg(tmp, stop); if stop then Abort; end; function ExpectedArgType(const firmVer : word; const op : TOpCode; const argIdx: integer): TAsmArgType; begin case op of OP_ADD, OP_SUB, OP_NEG, OP_MUL, OP_DIV, OP_MOD, OP_AND, OP_OR, OP_XOR, OP_NOT, OP_CMNT, OP_LSL, OP_LSR, OP_ASL, OP_ASR, OP_ROTL, OP_ROTR, OP_MOV, OPS_ACOS, OPS_ASIN, OPS_ATAN, OPS_CEIL, OPS_EXP, OPS_FABS, OPS_FLOOR, OPS_SQRT, OPS_TAN, OPS_TANH, OPS_COS, OPS_COSH, OPS_LOG, OPS_LOG10, OPS_SIN, OPS_SINH, OPS_ATAN2, OPS_FMOD, OPS_POW, OPS_ACOS_2, OPS_ASIN_2, OPS_ATAN_2, OPS_CEIL_2, OPS_EXP_2, OPS_FLOOR_2, OPS_TAN_2, OPS_TANH_2, OPS_COS_2, OPS_COSH_2, OPS_LOG_2, OPS_LOG10_2, OPS_SIN_2, OPS_SINH_2, OPS_TRUNC_2, OPS_FRAC_2, OPS_ATAN2_2, OPS_POW_2, OPS_MULDIV_2, OPS_ACOSD_2, OPS_ASIND_2, OPS_ATAND_2, OPS_COSD_2, OPS_COSHD_2, OPS_TAND_2, OPS_TANHD_2, OPS_SIND_2, OPS_SINHD_2, OPS_ATAN2D_2 : begin if argIdx > 0 then Result := aatVariable else Result := aatVarNoConst; end; OP_ARRBUILD : begin if argIdx > 0 then Result := aatVariable else Result := aatArray; end; OP_FLATTEN : begin if argIdx > 0 then Result := aatVariable else // 0 Result := aatStringNoConst; end; OP_STRCAT : begin if argIdx > 0 then Result := aatString else Result := aatStringNoConst; end; OP_NUMTOSTRING : begin if argIdx > 0 then Result := aatScalar else // 0 Result := aatStringNoConst; end; OP_ARRSIZE : begin if argIdx = 1 then Result := aatArray else // 0 Result := aatScalarNoConst; end; OP_UNFLATTEN : begin if argIdx > 2 then Result := aatVariable else if argIdx = 2 then Result := aatString else if argIdx = 1 then Result := aatScalarNoConst else // 0 Result := aatVarNoConst; end; OP_INDEX : begin if argIdx > 2 then Result := aatVariable else if argIdx = 2 then Result := aatScalarOrNull else if argIdx = 1 then Result := aatArray else // 0 Result := aatVarNoConst; end; OP_REPLACE : begin if argIdx = 2 then Result := aatScalarOrNull else if argIdx > 2 then Result := aatVariable else // 0 or 1 Result := aatArray; end; OP_CMP, OP_TST, OP_CMPSET, OP_TSTSET : begin if argIdx = 0 then Result := aatConstant else if argIdx > 1 then Result := aatVariable else Result := aatVarNoConst; end; OP_STRTOBYTEARR : begin if argIdx = 0 then Result := aatArray else // 1 Result := aatString; end; OP_BYTEARRTOSTR : begin if argIdx = 1 then Result := aatArray else // 0 Result := aatStringNoConst; end; OP_ACQUIRE, OP_RELEASE : begin Result := aatMutex; end; OP_SUBRET : begin Result := aatScalarNoConst; end; OP_GETTICK : begin Result := aatScalarNoConst; end; OP_STOP : begin Result := aatScalarorNull; end; OP_ARRSUBSET : begin if argIdx >= 2 then Result := aatScalarOrNull else Result := aatArray; end; OPS_ARROP, OPS_ARROP_2 : begin if argIdx = 0 then Result := aatConstant else if argIdx = 1 then Result := aatVarNoConst else if argIdx >= 3 then Result := aatScalarOrNull else Result := aatArray; end; OP_STRSUBSET : begin if argIdx >= 2 then Result := aatScalarOrNull else if argIdx = 1 then Result := aatString else // 0 Result := aatStringNoConst; end; OP_SET : begin if argIdx > 0 then Result := aatConstant else Result := aatScalarNoConst; end; OP_SUBCALL : begin if argIdx = 0 then Result := aatClumpID else Result := aatScalarNoConst; end; OP_FINCLUMP : begin Result := aatConstant; end; OP_FINCLUMPIMMED : begin Result := aatClumpID; end; OP_JMP : begin Result := aatLabelID; end; OP_BRCMP, OP_BRTST : begin if argIdx = 0 then Result := aatConstant else if argIdx = 1 then Result := aatLabelID else Result := aatVariable; end; OP_SYSCALL : begin if argIdx = 0 then Result := aatConstant else Result := aatCluster; end; OP_SETIN, OP_GETIN : begin if argIdx = 2 then Result := aatConstant else if (op = OP_GETIN) and (argIdx = 0) then Result := aatScalarNoConst else Result := aatScalar; end; OP_SETOUT : begin if argIdx = 0 then Result := aatVariable // could be a scalar or an array else if (argIdx mod 2) = 1 then Result := aatConstant else // argIdx > 0 and even Result := aatScalar; end; OP_GETOUT : begin if argIdx = 2 then Result := aatConstant else if argIdx = 1 then Result := aatScalar else Result := aatScalarNoConst; end; OP_ARRINIT : begin if argIdx = 2 then Result := aatScalarOrNull else if argIdx = 1 then Result := aatVariable else // arg 0 Result := aatArray; end; OP_STRINGTONUM : begin if argIdx >= 3 then Result := aatScalarOrNull else if argIdx = 2 then Result := aatString else // 0 or 1 Result := aatScalarNoConst; end; OP_WAIT : begin if firmVer > MAX_FW_VER1X then begin Result := aatScalarOrNull; end else Result := aatConstant; end; OPS_WAITV{, OP_SQRT_2} : begin if firmVer > MAX_FW_VER1X then begin // OPS_WAITV == OP_SQRT_2 in 2.x firmware if argIdx > 0 then Result := aatVariable else Result := aatVarNoConst; end else Result := aatScalar; end; OPS_WAITV_2 : begin Result := aatScalar; end; OPS_CALL : begin Result := aatClumpID; end; OPS_ABS{, OP_ABS_2}, OPS_SIGN, OPS_SIGN_2 : begin if argIdx = 1 then Result := aatScalar else // 0 Result := aatScalarNoConst; end; OPS_SHL, OPS_SHR : begin if argIdx >= 1 then Result := aatScalar else // 0 Result := aatScalarNoConst; end; OPS_STRINDEX : begin if argIdx > 2 then Result := aatVariable else if argIdx = 2 then Result := aatScalarOrNull else if argIdx = 1 then Result := aatString else // 0 Result := aatVarNoConst; end; OPS_STRREPLACE : begin if argIdx = 2 then Result := aatScalarOrNull else if argIdx > 2 then Result := aatVariable else // 0 or 1 Result := aatString; end; OPS_STRLEN : begin if argIdx = 1 then Result := aatString else // 0 Result := aatScalarNoConst; end; OPS_COMPCHK : begin if argIdx > 2 then Result := aatString else Result := aatConstant; end; OPS_COMPIF : begin Result := aatConstant; end; OPS_COMPCHKTYPE : begin if argIdx = 0 then Result := aatVariable else Result := aatTypeName; end; OPS_START, OPS_START_2 : begin Result := aatClumpID; end; OPS_STOPCLUMP, OPS_STOPCLUMP_2 : begin Result := aatClumpID; end; OPS_PRIORITY, OPS_PRIORITY_2 : begin if argIdx = 0 then Result := aatClumpID else Result := aatConstant; end; OPS_FMTNUM, OPS_FMTNUM_2 : begin if argIdx > 1 then Result := aatScalar else if argIdx = 1 then Result := aatString else // 0 Result := aatStringNoConst; end; OPS_ADDROF : begin if argIdx = 1 then Result := aatVariable else if argIdx = 2 then Result := aatConstant else Result := aatVarNoConst; end; else Result := aatConstant; end; end; procedure TRXEProgram.HandleConstantExpressions(AL: TAsmLine); var expected : TAsmArgType; i, j, delta : integer; // n : integer; arg : TAsmArgument; val : Extended; iVal : Int64; tmpName, tmpValue : string; DE, Sub : TDataspaceEntry; bValidCC : boolean; // newLine : TAsmLine; tmpType : TDSType; begin // if this line requires a reference to a temporary scalar variable // then define a constant variable reference and use it whereever this value // needs to be used // The new asm line calls the "set" opcode setting the temporary variable // to the constant value. // check all the arguments for this line to see if their argument type // matches the expected argument type. If it does then do nothing. // if it doesn't and the expected type allows for a temporary then create one // and adjust the argument appropriately. // n := 0; ProcessSpecialFunctions(AL); if AL.Command in [OP_CMP, OP_TST, OP_CMPSET, OP_TSTSET, OP_BRCMP, OP_BRTST] then begin if AL.Args.Count > 0 then begin FixupComparisonCodes(AL.Args[0]); arg := AL.Args[0]; bValidCC := False; Calc.SilentExpression := arg.Value; if not Calc.ParserError then begin iVal := Trunc(Calc.Value); bValidCC := ValidCompareCode(Byte(iVal)); if bValidCC then arg.Value := IntToStr(iVal); end; if Calc.ParserError or not bValidCC then begin ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidCompareCode, [arg.Value]), true); arg.Value := '-1'; // set to a valid numeric string constant end; end; // skip the comparison argument delta := 1; end else delta := 0; for i := delta to AL.Args.Count - 1 do begin // the optional 4th argument of the compchk opcode is a special case if (AL.Command = OPS_COMPCHK) and (i = 3) then Continue; expected := ExpectedArgType(FirmwareVersion, AL.Command, i); arg := AL.Args[i]; if expected in [aatVariable, aatVarOrNull, aatArray, aatString, aatScalar, aatScalarOrNull] then begin // look at the argument and see if it is of the variable type // if not then create temporary. j := Dataspace.IndexOfName(arg.Value); if j = -1 then begin // the current argument is not a known variable and it is supposed to be one // argument could also be a constant expression which needs to be evaluated. // but first we need to rule out the possibility that the argument is a // IO Map address macro j := IndexOfIOMapName(arg.Value); if j = -1 then begin // is it a string? if (arg.IsQuoted('''') or arg.IsQuoted('"')) and not (expected in [aatScalar, aatScalarOrNull]) then begin // maintain a map between string constants and variable names tmpValue := StripQuotes(arg.Value); j := fConstStrMap.IndexOf(tmpValue); if j = -1 then begin tmpName := Format('__constStr%4.4d', [fConstStrMap.Count]); fConstStrMap.AddEntry(tmpValue, tmpName); DE := DataSpace.Add; // this is an array type DE.Identifier := tmpName; DE.DataType := dsArray; Sub := DE.SubEntries.Add; Sub.Identifier := DE.Identifier + '_type'; Sub.DataType := dsUByte; // the args value is an initializer DE.AddValuesFromString(Calc, arg.Value); end else tmpName := fConstStrMap.MapValue[j]; // we have a temporary called 'tmpName' in the dataspace // so switch our line to use it instead arg.Value := tmpName; end else if (IsDelimiter('{', arg.Value, 1) and IsDelimiter('}', arg.Value, Length(arg.Value))) and not (expected in [aatScalar, aatScalarOrNull]) then begin // maintain a map between constants and variable names tmpValue := StripQuotes(arg.Value); // removes '{' and '}' j := fConstStrMap.IndexOf(tmpValue); if j = -1 then begin tmpName := Format('__constStr%4.4d', [fConstStrMap.Count]); fConstStrMap.AddEntry(tmpValue, tmpName); DE := DataSpace.Add; // this is an array type DE.Identifier := tmpName; DE.DataType := dsArray; Sub := DE.SubEntries.Add; Sub.Identifier := DE.Identifier + '_type'; // constant array type defaults to signed long Sub.DataType := dsSLong; // the args value is an initializer tmpType := DE.AddValuesFromString(Calc, arg.Value); Sub.DataType := tmpType; end else tmpName := fConstStrMap.MapValue[j]; // we have a temporary called 'tmpName' in the dataspace // so switch our line to use it instead arg.Value := tmpName; end else begin // now we can assume the arg is supposed to be a constant expression val := arg.Evaluate(Calc); iVal := Trunc(val); // one more check with respect to IOMap Addresses. j := IndexOfIOMapID(Integer(iVal)); if ((expected in [aatVarOrNull, aatScalarOrNull]) and (iVal = NOT_AN_ELEMENT)) or (j <> -1) then begin // we have an IO Map address as a constant expression arg.Value := IntToStr(iVal); end else begin // definitely not an IO Map Address // what type should this temporary be? tmpName := CreateConstantVar(DataSpace, val, False, GetTypeHint(DataSpace, AL, i, EnhancedFirmware)); // we have a temporary called 'tmpName' in the dataspace // so switch our line to use it instead arg.Value := tmpName; end; end; end; end; end else if expected = aatConstant then begin Calc.SilentExpression := arg.Value; if Calc.ParserError then begin if not fIgnoreLines then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sBadConstExpression, [arg.Value]), true); arg.Value := '-1'; // set to a valid numeric string end else arg.Value := NBCFloatToStr(Calc.Value); // arg.Value := IntToStr(Trunc(Calc.Value)); end; end; end; function GetArgDataType(val : Extended): TDSType; var iVal : Int64; begin iVal := Trunc(val); if iVal = val then begin val := iVal; // see if this works. if not then figure out the // type based on the size of the value if (val >= Low(ShortInt)) and (val <= High(ShortInt)) then Result := dsSByte else if (val >= Low(SmallInt)) and (val <= High(SmallInt)) then Result := dsSWord else if (val >= Low(Integer)) and (val <= High(Integer)) then Result := dsSLong else if (val > High(Cardinal)) or (val < Low(Integer)) then Result := dsFloat else Result := dsULong; end else Result := dsFloat; // else if ((val >= 0) and (val <= High(Byte)) then // Result := dsUByte // else if ((val >= 0) and (val <= High(Word)) then // Result := dsUWord end; procedure TRXEProgram.UpdateHeader; begin fHeader.DSCount := fDSData.DSCount; fHeader.DSStaticSize := fDSData.DSStaticSize; fHeader.DynDSDefaultsOffset := fDSData.DynDSDefaultsOffset; fHeader.DynDSDefaultsSize := fDSData.DynDSDefaultsSize; fHeader.DVArrayOffset := fDSData.DVArrayOffset; fHeader.ClumpCount := Word(Codespace.Count); fHeader.CodespaceCount := fCode.CodespaceCount; fHeader.MemMgrHead := fDSData.Head; fHeader.MemMgrTail := fDSData.Tail; fHeader.DSDefaultsSize := Word(fHeader.DynDSDefaultsOffset + fHeader.DynDSDefaultsSize); fHeader.DSSize := Word(fHeader.DSStaticSize + fHeader.DynDSDefaultsSize); end; procedure TRXEProgram.CheckArgs(AL: TAsmLine); var arg : string; NI : NXTInstruction; i : integer; val : integer; argType : TAsmArgType; de, de2 : TDataspaceEntry; begin if AL.Command <> OPS_INVALID then begin i := IndexOfOpcode(AL.Command); if i = -1 then begin ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidOpcode, [OpcodeToStr(Al.Command)]), true); end else begin NI := GetNXTInstruction(i); case AL.Command of OP_CMP, OP_TST, OP_CMPSET, OP_TSTSET, OP_BRCMP, OP_BRTST : begin if AL.Args.Count <> NI.Arity+1 then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidNumArgs, [NI.Arity+1, AL.Args.Count]), true); end; OP_FINCLUMP : begin // can have 2 or zero arguments if (AL.Args.Count <> NI.Arity) and (AL.Args.Count <> 0) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidNumArgs, [NI.Arity, AL.Args.Count]), true); end; OP_ARRBUILD, OP_STRCAT : begin // must have at least 2 arguments if (AL.Args.Count < 2) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidNumArgsVar, [2, AL.Args.Count]), true); end; OP_SETOUT : begin // must have at least 3 arguments if (AL.Args.Count < 3) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidNumArgsVar, [3, AL.Args.Count]), true) else if (AL.Args.Count mod 2) = 0 then begin // total number of args must be odd ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sInvalidNumArgsOdd, true); end; end; OP_DIV : begin // if second argument is signed and third is unsigned then // bad things might happen if AL.Args.Count = NI.Arity then begin de := Dataspace.FindEntryByFullName(AL.Args[1].Value); de2 := Dataspace.FindEntryByFullName(AL.Args[2].Value); if Assigned(de) and Assigned(de2) then begin if (de.DataType in [dsSByte, dsSWord, dsSLong]) and (de2.DataType in [dsUByte, dsUWord, dsULong]) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sUnsafeDivision, false); end else begin if not Assigned(de) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidVarArg, [AL.Args[1].Value]), true) else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidVarArg, [AL.Args[2].Value]), true); end; end; end; OP_SET : begin // must have 2 arguments if AL.Args.Count <> NI.Arity then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidNumArgs, [NI.Arity, AL.Args.Count]), true); // the first argument must not be anything other than an integer datatype de := Dataspace.FindEntryByFullName(AL.Args[0].Value); if Assigned(de) then begin if de.DataType = dsFloat then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sInvalidSetStatement, true); end else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidVarArg, [AL.Args[0].Value]), true); // second argument must be a constant within the range of UWORD // or SWORD arg := AL.Args[1].Value; // should be a number Calc.SilentExpression := arg; if Calc.ParserError then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sBadConstExpression, [arg]), true) else begin // make sure it is in range val := Integer(Trunc(Calc.Value)); if (val < Low(SmallInt)) or (val > High(Word)) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sConstOutOfRange, [val, Low(SmallInt), High(Word)]), true) end; end; OPS_COMPCHK : begin // can have 3 or 4 arguments if (AL.Args.Count <> NI.Arity) and (AL.Args.Count <> NI.Arity+1) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidNumArgs, [NI.Arity, AL.Args.Count]), true); end; else // case if (NI.Arity < 6) and (AL.Args.Count <> NI.Arity) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidNumArgs, [NI.Arity, AL.Args.Count]), true); end; for i := 0 to AL.Args.Count - 1 do begin // the optional 4th argument of the compchk opcode is a special case if (AL.Command = OPS_COMPCHK) and (i = 3) then Continue; arg := AL.Args[i].Value; argType := ExpectedArgType(FirmwareVersion, Al.Command, i); case argType of aatVariable, aatVarNoConst, aatVarOrNull, aatScalar, aatScalarNoConst, aatScalarOrNull : begin // arg must be in list of known variables de := Dataspace.FindEntryAndAddReference(arg); if (de = nil) and (IndexOfIOMapName(arg) = -1) then begin Calc.SilentExpression := arg; val := Integer(Trunc(Calc.Value)); if IndexOfIOMapID(val) = -1 then begin if (not (argType in [aatVarOrNull, aatScalarOrNull])) or ((val <> NOT_AN_ELEMENT) and (val <> -1)) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidVarArg, [arg]), true); end; end else if Assigned(de) and (argType in [aatScalar, aatScalarNoConst, aatScalarOrNull]) then begin // a known variable name but is it a scalar if de.DataType in [dsVoid, dsArray, dsCluster, dsMutex] then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidScalarArg, [arg]), true); end; end; aatArray : begin de := Dataspace.FindEntryAndAddReference(arg); if (de = nil) or (de.DataType <> dsArray) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidArrayArg, [arg]), true); end; aatString, aatStringNoConst : begin // arg must be in list of known variables de := Dataspace.FindEntryAndAddReference(arg); if (de = nil) or (de.DataType <> dsArray) or not (de.SubEntries[0].DataType in [dsUByte, dsSByte]) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidStringArg, [arg]), true); end; aatConstant : begin // if it is a constant then I should be able to evaluate it Calc.SilentExpression := arg; if Calc.ParserError then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sBadConstExpression, [arg]), true); end; aatLabelID : begin // Labels are checked elsewhere (ValidateLabels) end; aatClumpID : begin // can't check clumpIDs yet since it could be not yet defined // but we can at least require them to be valid identifiers if not IsValidIdent(arg) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidClumpArg, [arg]), true); end; aatCluster : begin de := Dataspace.FindEntryAndAddReference(arg); if (de = nil) or (de.DataType <> dsCluster) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidClusterArg, [arg]), true); end; aatMutex : begin de := Dataspace.FindEntryAndAddReference(arg); // we want to keep a list of all the threads that reference a // mutex in order to help us correctly optimize them later on. if Assigned(de) and (de.DataType = dsMutex) then begin de.AddThread(fClumpName); end else // if (de = nil) or (de.DataType <> dsMutex) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidMutexArg, [arg]), true); end; end; end; end; end; end; procedure TRXEProgram.HandleNameToDSID(const aName: string; var aId: integer); begin aId := Dataspace.DataspaceIndex(aName); end; procedure TRXEProgram.CreateObjects; begin fCalc := TNBCExpParser.Create(nil); fCalc.CaseSensitive := fCaseSensitive; fCalc.OnParserError := HandleCalcParserError; fCalc.StandardDefines := fStandardDefines; fCalc.ExtraDefines := fExtraDefines; fDD := TDataDefs.Create; fDS := TDataspace.Create; fDS.CaseSensitive := fCaseSensitive; fCS := TCodeSpace.Create(self, fDS); fCS.CaseSensitive := fCaseSensitive; fCS.OnNameToDSID := HandleNameToDSID; fDSData := TDSData.Create; fClumpData := TClumpData.Create; fCode := TCodeSpaceAry.Create; fNamedTypes := TMapList.Create; fNamedTypes.CaseSensitive := fCaseSensitive; fNamedTypes.Duplicates := dupError; fConstStrMap := TMapList.Create; fMsgs := TStringList.Create; fCS.Calc := fCalc; fIncDirs := TStringList.Create; fCompilerOutput := TStringList.Create; fSymbolTable := TStringList.Create; fDefines := TStringList.Create; fSpawnedThreads := TStringList.Create; TStringList(fSpawnedThreads).CaseSensitive := True; TStringList(fSpawnedThreads).Duplicates := dupIgnore; fSpecialFunctions := TObjectList.Create; LoadSpecialFunctions; fVarI := 0; fVarJ := 0; fOptimizeLevel := 0; end; procedure TRXEProgram.FreeObjects; begin fConstStrMap.Clear; fNamedTypes.Clear; FreeAndNil(fDD); FreeAndNil(fDS); FreeAndNil(fCS); FreeAndNil(fNamedTypes); FreeAndNil(fConstStrMap); FreeAndNil(fDSData); FreeAndNil(fClumpData); FreeAndNil(fCode); FreeAndNil(fMsgs); FreeAndNil(fCalc); FreeAndNil(fIncDirs); FreeAndNil(fCompilerOutput); FreeAndNil(fSymbolTable); FreeAndNil(fDefines); FreeAndNil(fSpawnedThreads); FreeAndNil(fSpecialFunctions); end; procedure TRXEProgram.Clear; begin FreeObjects; CreateObjects; InitializeHeader; end; procedure TRXEProgram.InitializeHeader; begin fHeader.FormatString := 'MindstormsNXT'; fHeader.Version := CompilerVersion; fHeader.DSCount := 0; fHeader.DSSize := 0; fHeader.DSStaticSize := 0; fHeader.DSDefaultsSize := 0; fHeader.DynDSDefaultsOffset := 0; fHeader.DynDSDefaultsSize := 0; fHeader.MemMgrHead := 0; fHeader.MemMgrTail := 0; fHeader.ClumpCount := 0; fHeader.CodespaceCount := 0; end; procedure TRXEProgram.HandleCalcParserError(Sender: TObject; E: Exception); begin if Assigned(Sender) and not fIgnoreLines then ReportProblem(LineCounter, GetCurrentFile(true), '', E.Message, True); end; procedure TRXEProgram.SetCaseSensitive(const Value: boolean); begin fCaseSensitive := Value; fCalc.CaseSensitive := Value; fNamedTypes.CaseSensitive := Value; fDS.CaseSensitive := fCaseSensitive; fCS.CaseSensitive := fCaseSensitive; end; procedure TRXEProgram.SetStandardDefines(const Value: boolean); begin fCalc.StandardDefines := Value; fStandardDefines := Value; end; procedure TRXEProgram.SetExtraDefines(const Value: boolean); begin fCalc.ExtraDefines := Value; fExtraDefines := Value; end; procedure TRXEProgram.SetCompVersion(const Value: byte); begin fCompVersion := Value; fHeader.Version := Value; end; procedure TRXEProgram.ValidateLabels(aClump: TClump); var arg : string; i, j : integer; argType : TAsmArgType; AL : TAsmLine; begin for j := 0 to aCLump.ClumpCode.Count - 1 do begin AL := aClump.ClumpCode[j]; if AL.Command <> OPS_INVALID then begin for i := 0 to AL.Args.Count - 1 do begin arg := AL.Args[i].Value; argType := ExpectedArgType(FirmwareVersion, Al.Command, i); case argType of aatLabelID : begin // check labels if (aClump.IndexOfLabel(arg) = -1) or not IsValidIdent(arg) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidLabelArg, [arg]), true); end; end; end; end; end; end; procedure TRXEProgram.SetIncDirs(const Value: TStrings); begin fIncDirs.Assign(Value); end; function TRXEProgram.GetSymbolTable: TStrings; begin Result := fSymbolTable; Result.Clear; Result.BeginUpdate; try fDSData.SaveToSymbolTable(Result); Codespace.SaveToSymbolTable(Result); finally Result.EndUpdate; end; end; procedure TRXEProgram.CreateWaitClump(const basename: string); var C : TClump; AL : TAsmLine; begin C := CodeSpace.Add; C.Name := Format('__%s_wait', [basename]); C.Filename := GetCurrentFile(true); AL := C.ClumpCode.Add; AL.Command := OP_GETTICK; AL.AddArgs(Format('%s_now', [C.Name])); AL := C.ClumpCode.Add; AL.Command := OP_ADD; AL.AddArgs(Format('%0:s_then, %0:s_now, %0:s_ms', [C.Name])); AL := C.ClumpCode.Add; AL.LineLabel := Format('%sing', [C.Name]); C.AddLabel(AL.LineLabel, AL); AL.Command := OP_GETTICK; AL.AddArgs(Format('%s_now', [C.Name])); AL := C.ClumpCode.Add; AL.Command := OP_BRCMP; AL.AddArgs(Format('LT, %0:sing, %0:s_now, %0:s_then', [C.Name])); AL := C.ClumpCode.Add; AL.Command := OP_SUBRET; AL.AddArgs(Format('%s_return', [C.Name])); end; procedure TRXEProgram.CreateSpawnerClump(const basename: string); var C : TClump; AL : TAsmLine; begin C := CodeSpace.Add; C.Name := Format('__%s_Spawner', [basename]); C.Filename := GetCurrentFile(true); C.AddClumpDependencies('precedes', Format('%0:s, __%0:s_Returner', [basename])); // exit AL := C.ClumpCode.Add; AL.Command := OP_FINCLUMP; end; procedure TRXEProgram.CreateReturnerClump(const basename: string); var C : TClump; AL : TAsmLine; begin C := CodeSpace.Add; C.Name := Format('__%s_Returner', [basename]); C.Filename := GetCurrentFile(true); // subret __x_Spawner_return AL := C.ClumpCode.Add; AL.Command := OP_SUBRET; AL.AddArgs(Format('__%s_Spawner_return', [basename])); end; procedure TRXEProgram.DefineWaitArgs(const basename: string); var DE : TDataspaceEntry; idstr : string; begin idstr := Format('__%s_wait_', [basename]); DE := Dataspace.Add; DE.DataType := SubroutineReturnAddressType; DE.Identifier := idstr + 'return'; // refcount is 1+caller DE.IncRefCount; DE := Dataspace.Add; DE.DataType := dsUWord; DE.Identifier := idstr + 'ms'; // refcount is 1+caller DE.IncRefCount; DE := Dataspace.Add; DE.DataType := dsULong; DE.Identifier := idstr + 'now'; // refcount is 3 DE.IncRefCount; DE.IncRefCount; DE.IncRefCount; DE := Dataspace.Add; DE.DataType := dsULong; DE.Identifier := idstr + 'then'; // refcount is 2 DE.IncRefCount; DE.IncRefCount; end; procedure TRXEProgram.HandlePseudoOpcodes(AL: TAsmLine; op: TOpCode{; const args: string}); var Arg : TAsmArgument; a1, a2, a3, a4, a5, c1, c2 : string; de1, de2, de3, de4, de5 : TDataspaceEntry; tmpLine, shiftConst : integer; begin tmpLine := AL.LineNum; case op of OP_WAIT, OPS_WAITV, OPS_WAITI_2, OPS_WAITV_2 : begin // 2.x firmwares support wait and OPS_WAITV == OP_SQRT_2 if (FirmwareVersion > MAX_FW_VER1X) then begin if op in [OP_WAIT, OP_SQRT_2{, OPS_WAITV}] then Exit; if not EnhancedFirmware then begin // opcode is either OPS_WAITI_2 or OPS_WAITV_2 // convert it to OP_WAIT with 2 args if op = OPS_WAITI_2 then begin //AL == waiti 12345 c1 := CreateConstantVar(DataSpace, StrToIntDef(AL.Args[0].Value, 0), True); Arg := AL.Args[0]; Arg.Value := c1; end; Arg := AL.Args.Insert(0); Arg.Value := STR_NA; AL.Command := OP_WAIT; end; end else begin if not EnhancedFirmware then begin // convert OPS_WAITV // if this is a wait opcode we replace it with two lines of code if not fClumpUsesWait then DefineWaitArgs(fCurrentClump.Name); fClumpUsesWait := True; if op = OP_WAIT then AL.Command := OP_SET else AL.Command := OP_MOV; Arg := AL.Args.Insert(0); Arg.Value := Format('__%s_wait_ms', [fCurrentClump.Name]); Dataspace.FindEntryAndAddReference(Arg.Value); // inc refcount AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_SUBCALL; AL.LineNum := tmpLine; Arg := AL.Args.Add; Arg.Value := Format('__%s_wait', [fCurrentClump.Name]); Arg := AL.Args.Add; Arg.Value := Format('__%0:s_wait_return', [fCurrentClump.Name]); Dataspace.FindEntryAndAddReference(Arg.Value); // inc refcount end; end; end; OPS_STRINDEX : begin // just replace opcode AL.Command := OP_INDEX; end; OPS_STRREPLACE : begin // just replace opcode AL.Command := OP_REPLACE; end; OPS_COMPCHK : begin AL.Command := OPS_INVALID; // make this line a no-op DoCompilerCheck(AL, False); end; OPS_COMPCHKTYPE : begin AL.Command := OPS_INVALID; // make this line a no-op DoCompilerCheckType(AL); end; OPS_COMPIF : begin AL.Command := OPS_INVALID; // make this line a no-op DoCompilerCheck(AL, True); end; OPS_COMPELSE : begin AL.Command := OPS_INVALID; // make this line a no-op fIgnoreLines := not fIgnoreLines; end; OPS_COMPEND : begin AL.Command := OPS_INVALID; // make this line a no-op fIgnoreLines := False; end; OPS_STRLEN : begin if AL.Args.Count = 2 then begin c1 := CreateConstantVar(DataSpace, 1, True); a1 := AL.Args[0].Value; de1 := Dataspace.FindEntryByFullName(a1); AL.Command := OP_ARRSIZE; // sub AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_SUB; AL.LineNum := tmpLine; AL.AddArgs(Format('%0:s, %0:s, %s', [a1, c1])); if Assigned(de1) then begin de1.IncRefCount; de1.IncRefCount; end else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidVarArg, [AL.Args[0].Value]), true); end; end; OPS_START, OPS_START_2 : begin if AL.Args.Count < 1 then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sInvalidStatement, true) else begin a1 := AL.Args[0].Value; // base thread name if not EnhancedFirmware then begin // replace start with subcall and automatic return address variable. AL.Command := OP_SUBCALL; AL.Args[0].Value := Format('__%s_Spawner', [a1]); Arg := AL.Args.Add; Arg.Value := Format('%s_return', [AL.Args[0].Value]); DefineVar(Arg.Value, SubroutineReturnAddressType); RegisterThreadForSpawning(a1); end; // need to mark clumps as multi-threaded CodeSpace.Multithread(fCurrentClump.Name); CodeSpace.Multithread(a1); end; end; OPS_STOPCLUMP, OPS_PRIORITY, OPS_FMTNUM, OPS_STOPCLUMP_2, OPS_PRIORITY_2, OPS_FMTNUM_2 : begin if not EnhancedFirmware then begin // replace with no-op if not running enhanced firmware and report error ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidOpcode, [OpcodeToStr(Al.Command)]), true); AL.Command := OPS_INVALID; end; end; OPS_CALL : begin // subcall with automatic return address variable. AL.Command := OP_SUBCALL; Arg := AL.Args.Add; Arg.Value := Format('__%s_return', [AL.Args[0].Value]); if not fIgnoreLines then DefineVar(Arg.Value, SubroutineReturnAddressType); end; OPS_RETURN : begin // first make sure it only is present in a subroutine if not fCurrentClump.IsSubroutine then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sReturnNotInSub, true); // subret with automatic return address variable AL.Command := OP_SUBRET; Arg := AL.Args.Add; Arg.Value := Format('__%s_return', [fCurrentClump.Name]); if not fIgnoreLines then DefineVar(Arg.Value, SubroutineReturnAddressType); end; OPS_ABS{, OP_ABS_2} : begin // 2.x standard firmware supports ABS opcode if FirmwareVersion > MAX_FW_VER1X then Exit; if not EnhancedFirmware then begin if AL.Args.Count = 2 then begin a1 := AL.Args[0].Value; a2 := AL.Args[1].Value; de1 := Dataspace.FindEntryByFullName(a1); de2 := Dataspace.FindEntryByFullName(a2); AL.Command := OP_MOV; AL.Args.Clear; AL.AddArgs(Format('%s, %s', [a1, a2])); AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_BRTST; AL.LineNum := tmpLine; AL.AddArgs(Format('GTEQ, __abs_%d, %s', [fAbsCount, a2])); AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_NEG; AL.LineNum := tmpLine; AL.AddArgs(Format('%s, %s', [a1, a2])); AL := fCurrentClump.ClumpCode.Add; AL.Command := OPS_INVALID; // OPS_MOV; AL.LineNum := tmpLine; AL.LineLabel := Format('__abs_%d', [fAbsCount]); fCurrentClump.AddLabel(AL.LineLabel, AL); inc(fAbsCount); if Assigned(de1) and Assigned(de2) then begin de1.IncRefCount; de2.IncRefCount; de2.IncRefCount; end else begin if not Assigned(de1) then ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidVarArg, [a1]), true) else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidVarArg, [a2]), true); end; end else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sInvalidStatement, true); end; end; OPS_SIGN, OPS_SIGN_2 : begin if not EnhancedFirmware then begin if AL.Args.Count = 2 then begin a1 := AL.Args[0].Value; a2 := AL.Args[1].Value; de2 := Dataspace.FindEntryByFullName(a2); a3 := Format('__%s_sign_tmp', [fCurrentClump.Name]); if not fClumpUsesSign then begin with Dataspace.Add do begin DataType := dsSByte; // only needs to store -1, 0, or 1 Identifier := a3; end; end; de3 := Dataspace.FindEntryByFullName(a3); fClumpUsesSign := True; AL.Command := OP_SET; AL.Args.Clear; AL.AddArgs(Format('%s, 0', [a3])); de3.IncRefCount; AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_BRTST; AL.LineNum := tmpLine; AL.AddArgs(Format('EQ, __sign_%d, %s', [fSignCount, a2])); AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_SET; AL.LineNum := tmpLine; AL.AddArgs(Format('%s, -1', [a3])); de3.IncRefCount; AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_BRTST; AL.LineNum := tmpLine; AL.AddArgs(Format('LT, __sign_%d, %s', [fSignCount, a2])); AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_SET; AL.LineNum := tmpLine; AL.AddArgs(Format('%s, 1', [a3])); de3.IncRefCount; AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_MOV; AL.LineNum := tmpLine; AL.LineLabel := Format('__sign_%d', [fSignCount]); AL.AddArgs(Format('%s, %s', [a1, a3])); de3.IncRefCount; fCurrentClump.AddLabel(AL.LineLabel, AL); inc(fSignCount); if Assigned(de2) then de2.IncRefCount else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidVarArg, [a2]), true); end else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sInvalidStatement, true); end; end; OPS_SHL, OPS_SHR : begin if AL.Args.Count = 3 then begin a1 := AL.Args[0].Value; a2 := AL.Args[1].Value; a3 := AL.Args[2].Value; // is this argument a constant??? if Pos('__constVal', a3) = 1 then begin // if the argument is a constant then generate a single mul or div // shLR a1, a2, a3 // first get the constant value de3 := Dataspace.FindEntryByFullName(a3); if Assigned(de3) then begin de3.DecRefCount; // this constant is used 1 less time than it used to be shiftConst := Integer(de3.DefaultValue); end else begin ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sInvalidVarArg, [a3]), true); shiftConst := 0; end; if shiftConst >= 0 then begin if shiftConst = 0 then AL.Command := OPS_INVALID else if AL.Command = OPS_SHL then AL.Command := OP_MUL else AL.Command := OP_DIV; shiftConst := Trunc(Power(2,shiftConst)); c1 := CreateConstantVar(DataSpace, shiftConst, True); AL.Args.Clear; AL.AddArgs(Format('%s, %s, %s', [a1, a2, c1])); end else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sNoNegShifts, true); end else begin if not EnhancedFirmware then begin // what about shifting by a variable containing a negative value??? c1 := CreateConstantVar(DataSpace, 1, True); c2 := CreateConstantVar(DataSpace, 2, True); if not fClumpUsesShift then DefineShiftArgs(fCurrentClump.Name); fClumpUsesShift := True; a4 := Format('__%s_shift_cnt', [fCurrentClump.Name]); a5 := Format('__%s_shift_tmp', [fCurrentClump.Name]); de1 := Dataspace.FindEntryByFullName(a1); de4 := Dataspace.FindEntryByFullName(a4); de5 := Dataspace.FindEntryByFullName(a5); if assigned(de1) and assigned(de4) and assigned(de5) then begin // shLR a1, a2, a3 // mov __shift_cnt, a3 AL.Command := OP_MOV; AL.Args.Clear; AL.AddArgs(Format('%s, %s', [a4, a3])); de4.IncRefCount; // mov __shift_tmp, a2 AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_MOV; AL.LineNum := tmpLine; AL.AddArgs(Format('%s, %s', [a5, a2])); de5.IncRefCount; // label: brtst LTEQ, __shiftdone_NN, __shift_cnt AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_BRTST; AL.LineNum := tmpLine; AL.AddArgs(Format('LTEQ, __shiftdone_%d, %s', [fShiftCount, a4])); AL.LineLabel := Format('__shiftstart_%d', [fShiftCount]); fCurrentClump.AddLabel(AL.LineLabel, AL); de4.IncRefCount; // mul/div __shift_tmp, __shift_tmp, 2 AL := fCurrentClump.ClumpCode.Add; if op = OPS_SHR then AL.Command := OP_DIV else AL.Command := OP_MUL; AL.LineNum := tmpLine; AL.AddArgs(Format('%0:s, %0:s, %s', [a5, c2])); de5.IncRefCount; de5.IncRefCount; // sub __shift_cnt, __shift_cnt, 1 AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_SUB; AL.LineNum := tmpLine; AL.AddArgs(Format('%0:s, %0:s, %s', [a4, c1])); de4.IncRefCount; de4.IncRefCount; // jmp __shiftstart_NNN AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_JMP; AL.LineNum := tmpLine; AL.AddArgs(Format('__shiftstart_%d', [fShiftCount])); // label __shiftdone_NNN AL := fCurrentClump.ClumpCode.Add; AL.Command := OPS_INVALID; AL.LineNum := tmpLine; AL.LineLabel := Format('__shiftdone_%d', [fShiftCount]); fCurrentClump.AddLabel(AL.LineLabel, AL); // mov a1, __shift_tmp AL := fCurrentClump.ClumpCode.Add; AL.Command := OP_MOV; AL.LineNum := tmpLine; AL.AddArgs(Format('%s, %s', [a1, a5])); de1.IncRefCount; de5.IncRefCount; inc(fShiftCount); end else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sInvalidStatement, true); end else begin if op = OPS_SHL then AL.Command := OP_ASL else AL.Command := OP_ASR; end; end; end else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sInvalidStatement, true); end; end; end; function TRXEProgram.ReplaceTokens(const line: string): string; var p : integer; begin Result := line; // line is already trimmed if Length(Result) = 0 then Exit; // Result := Replace(Result, '##', ''); if Length(Result) = 0 then Exit; if Pos('__ResetI__', Result) > 0 then begin Result := Replace(Result, '__ResetI__', ''); fVarI := 0; end; if Length(Result) = 0 then Exit; p := Pos('__IncI__', Result); while p > 0 do begin inc(fVarI); System.Delete(Result, p, 8); p := Pos('__IncI__', Result); end; if Length(Result) = 0 then Exit; p := Pos('__DecI__', Result); while p > 0 do begin dec(fVarI); System.Delete(Result, p, 8); p := Pos('__DecI__', Result); end; if Length(Result) = 0 then Exit; if Pos('__ResetJ__', Result) > 0 then begin Result := Replace(Result, '__ResetJ__', ''); fVarJ := 0; end; if Length(Result) = 0 then Exit; p := Pos('__IncJ__', Result); while p > 0 do begin inc(fVarJ); System.Delete(Result, p, 8); p := Pos('__IncJ__', Result); end; if Length(Result) = 0 then Exit; p := Pos('__DecJ__', Result); while p > 0 do begin dec(fVarJ); System.Delete(Result, p, 8); p := Pos('__DecJ__', Result); end; if Length(Result) = 0 then Exit; Result := Replace(Result, '__I__', IntToStr(fVarI)); Result := Replace(Result, '__J__', IntToStr(fVarJ)); Result := Replace(Result, '__THREADNAME__', fClumpName); Result := Replace(Result, '__LINE__', IntToStr(LineCounter)); Result := Replace(Result, '__FILE__', GetCurrentFile(false)); Result := Replace(Result, '__VER__', fProductVersion); end; function TRXEProgram.GetCurrentFile(bFullPath: boolean): string; begin Result := fCurrentFile; if bFullPath and (GetCurrentPath <> '') then Result := IncludeTrailingPathDelimiter(GetCurrentPath) + Result; end; function TRXEProgram.GetCurrentPath: string; begin Result := fCurrentPath; end; procedure TRXEProgram.SetCurrentFile(const Value: string); begin if fCurrentPath + fCurrentFile <> Value then begin fCurrentFile := ExtractFilename(Value); fCurrentPath := ExtractFilePath(Value); // DoCompilerStatusChange(Format(sCurrentFile, [Value])); end; end; procedure TRXEProgram.FixupComparisonCodes(Arg: TAsmArgument); var val : string; begin val := Arg.Value; if val = '<' then Arg.Value := '0' else if val = '>' then Arg.Value := '1' else if val = '<=' then Arg.Value := '2' else if val = '>=' then Arg.Value := '3' else if val = '==' then Arg.Value := '4' else if val = '!=' then Arg.Value := '5' else if val = '<>' then Arg.Value := '5'; end; procedure TRXEProgram.ProcessSpecialFunctions(AL: TAsmLine); var i, j, p : integer; Arg : TAsmArgument; name, leftstr, rightstr : string; SF : TSpecialFunction; begin for i := 0 to AL.Args.Count - 1 do begin Arg := AL.Args[i]; for j := 0 to fSpecialFunctions.Count - 1 do begin SF := TSpecialFunction(fSpecialFunctions[j]); p := Pos(SF.Func, Arg.Value); while p > 0 do begin name := Arg.Value; leftstr := Copy(name, 1, p-1); // everything before the first "sizeof(" System.Delete(name, 1, p+Length(SF.Func)-1); p := Pos(')', name); rightstr := Copy(name, p+1, MaxInt); // everything after the first ")" System.Delete(name, p, MaxInt); SF.Execute(Arg, leftstr, rightstr, name); p := Pos(SF.Func, Arg.Value); end; end; end; end; procedure TRXEProgram.DefineShiftArgs(const basename: string); var DE : TDataspaceEntry; begin DE := Dataspace.Add; DE.DataType := dsSByte; DE.Identifier := Format('__%s_shift_cnt', [basename]); DE := Dataspace.Add; DE.DataType := dsSLong; DE.Identifier := Format('__%s_shift_tmp', [basename]); end; procedure TRXEProgram.DoCompilerCheck(AL: TAsmLine; bIfCheck : boolean); var i1, i2, i3 : integer; bCheckOkay : boolean; errMsg : string; begin if fIgnoreLines then Exit; bCheckOkay := False; if AL.Args.Count >= 3 then begin i2 := StrToIntDef(AL.Args[0].Value, OPCC1_EQ); i1 := StrToIntDef(AL.Args[1].Value, 0); i3 := StrToIntDef(AL.Args[2].Value, 0); case i2 of OPCC1_LT : bCheckOkay := i1 < i3; OPCC1_GT : bCheckOkay := i1 > i3; OPCC1_LTEQ : bCheckOkay := i1 <= i3; OPCC1_GTEQ : bCheckOkay := i1 >= i3; OPCC1_EQ : bCheckOkay := i1 = i3; OPCC1_NEQ : bCheckOkay := i1 <> i3; end; if not bCheckOkay then begin if bIfCheck then fIgnoreLines := True else begin if AL.Args.Count > 3 then errMsg := AL.Args[3].Value else errMsg := Format(sCompCheckFailed, [i1, CCToStr(i2), i3]); ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, errMsg, true); end; end else if bIfCheck then fIgnoreLines := False; end else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sInvalidCompCheck, true); end; procedure TRXEProgram.DefineVar(aVarName: string; dt :TDSType); var DE : TDataspaceEntry; begin DE := Dataspace.FindEntryByFullName(aVarName); if not Assigned(DE) then begin DE := Dataspace.Add; DE.DataType := dt; DE.Identifier := aVarName; end; DE.IncRefCount; end; procedure TRXEProgram.RegisterThreadForSpawning(aThreadName: string); begin fSpawnedThreads.Add(aThreadName); end; procedure TRXEProgram.ProcessSpawnedThreads; var i : integer; t, spawner : string; begin for i := 0 to fSpawnedThreads.Count - 1 do begin t := fSpawnedThreads[i]; spawner := Format('__%s_Spawner', [t]); if Codespace.IndexOf(spawner) = -1 then begin // need to create Spawner and Returner threads CreateReturnerClump(t); CreateSpawnerClump(t); end; end; fSpawnedThreads.Clear; end; procedure TRXEProgram.OutputUnusedItemWarnings; var i : integer; de : TDataspaceEntry; begin for i := DataSpace.Count - 1 downto 0 do begin de := DataSpace.Items[i]; if not de.InUse then ReportProblem(0, GetCurrentFile(true), '', Format(sUnusedVar, [de.FullPathIdentifier]), false); end; end; procedure TRXEProgram.SetDefines(const Value: TStrings); begin fDefines.Assign(Value); end; procedure TRXEProgram.LoadSpecialFunctions; var SF : TSpecialFunction; begin // sizeof SF := TSpecialFunction.Create; fSpecialFunctions.Add(SF); SF.Func := 'sizeof('; SF.Execute := HandleSpecialFunctionSizeOf; // isconst SF := TSpecialFunction.Create; fSpecialFunctions.Add(SF); SF.Func := 'isconst('; SF.Execute := HandleSpecialFunctionIsConst; // valueof SF := TSpecialFunction.Create; fSpecialFunctions.Add(SF); SF.Func := 'valueof('; SF.Execute := HandleSpecialFunctionValueOf; // typeof SF := TSpecialFunction.Create; fSpecialFunctions.Add(SF); SF.Func := 'typeof('; SF.Execute := HandleSpecialFunctionTypeOf; end; procedure TRXEProgram.HandleSpecialFunctionSizeOf(Arg: TAsmArgument; const left, right, name: string); var de1 : TDataspaceEntry; dt : TDSType; begin // is name a constant value? Calc.SilentExpression := name; if Calc.ParserError then begin de1 := Dataspace.FindEntryByFullName(name); if Assigned(de1) then Arg.Value := left + IntToStr(de1.ElementSize(False)) + right else begin Arg.Value := left + '0' + right; ReportProblem(LineCounter, GetCurrentFile(true), '', Format(sInvalidVarArg, [name]), true); end end else begin dt := GetArgDataType(Calc.Value); Arg.Value := left + IntToStr(BytesPerType[dt]) + right; end; end; procedure TRXEProgram.HandleSpecialFunctionIsConst(Arg: TAsmArgument; const left, right, name: string); begin // is name a constant value (i.e., can it be evaluated)? Calc.SilentExpression := name; if Calc.ParserError then begin Arg.Value := left + '0' + right; end else begin Arg.Value := left + '1' + right; end; end; procedure TRXEProgram.HandleSpecialFunctionValueOf(Arg: TAsmArgument; const left, right, name: string); begin // is name a constant value? Calc.SilentExpression := name; if Calc.ParserError then begin Arg.Value := left + '0' + right; ReportProblem(LineCounter, GetCurrentFile(true), '', Format(sBadConstExpression, [name]), true); end else begin Arg.Value := left + NBCFloatToStr(Calc.Value) + right; end; end; procedure TRXEProgram.HandleSpecialFunctionTypeOf(Arg: TAsmArgument; const left, right, name: string); var de1 : TDataspaceEntry; dt : TDSType; begin // is name a constant value? Calc.SilentExpression := name; if Calc.ParserError then begin de1 := Dataspace.FindEntryByFullName(name); if Assigned(de1) then Arg.Value := left + IntToStr(Ord(de1.DataType)) + right else begin Arg.Value := left + '0' + right; ReportProblem(LineCounter, GetCurrentFile(true), '', Format(sInvalidVarArg, [name]), true); end end else begin dt := GetArgDataType(Calc.Value); Arg.Value := left + IntToStr(Ord(dt)) + right; end; end; procedure TRXEProgram.DoCompilerCheckType(AL: TAsmLine); var s1, s2, s3 : string; bCheckOkay : boolean; de : TDataspaceEntry; begin if fIgnoreLines then Exit; if AL.Args.Count = 2 then begin de := Dataspace.FindEntryByFullName(AL.Args[0].Value); if Assigned(de) then begin s1 := AL.Args[1].Value; s2 := de.TypeName; s3 := de.GetDataTypeAsString; bCheckOkay := (s1 = s2) or (s1 = s3); if not bCheckOkay then begin ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, Format(sCompCheckTypFailed, [AL.Args[0].Value, s1]), true); end; end else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sInvalidCompCheckTyp, true); end else ReportProblem(AL.LineNum, GetCurrentFile(true), AL.AsString, sInvalidCompCheckTyp, true); end; procedure TRXEProgram.SetLineCounter(const Value: integer); begin fLineCounter := Value; end; function TRXEProgram.GetNXTInstruction(const idx: integer): NXTInstruction; begin Result := fNXTInstructions[idx]; end; procedure TRXEProgram.SetFirmwareVersion(const Value: word); begin fFirmwareVersion := Value; CodeSpace.FirmwareVersion := Value; if fFirmwareVersion > MAX_FW_VER1X then CompilerVersion := 6 else CompilerVersion := 5; InitializeInstructions; end; function TRXEProgram.IndexOfOpcode(op : TOpCode) : integer; var i : integer; begin Result := -1; for i := Low(fNXTInstructions) to High(fNXTInstructions) do begin if fNXTInstructions[i].Encoding = op then begin Result := i; Break; end; end; end; procedure TRXEProgram.InitializeInstructions; var i : integer; begin if fFirmwareVersion > MAX_FW_VER1X then begin SetLength(fNXTInstructions, NXTInstructionsCount2x); for i := 0 to NXTInstructionsCount2x - 1 do begin fNXTInstructions[i] := NXTInstructions2x[i]; end; end else begin SetLength(fNXTInstructions, NXTInstructionsCount1x); for i := 0 to NXTInstructionsCount1x - 1 do begin fNXTInstructions[i] := NXTInstructions1x[i]; end; end; end; procedure TRXEProgram.CheckMainThread; var i : integer; X : TClump; begin i := Codespace.IndexOf(Codespace.InitialClumpName); if i = -1 then begin i := Codespace.IndexOf('t000'); if i > -1 then begin X := Codespace.Items[i]; X.Index := 0; end else ReportProblem(LineCounter, GetCurrentFile(true), '', sMainUndefined, false); end; end; procedure TRXEProgram.SaveToStrings(aStrings: TStrings); begin // write source code to aStrings aStrings.Clear; DataSpace.SaveToStrings(aStrings); Codespace.SaveToStrings(aStrings); end; procedure TRXEProgram.DoCompilerStatusChange(const Status: string; const bDone : boolean); begin if Assigned(fOnCompilerStatusChange) then fOnCompilerStatusChange(Self, Status, bDone); end; function TRXEProgram.ReplaceSpecialStringCharacters(const line: string): string; begin Result := line; if Pos('#', line) = 1 then Exit; // replace \\ with #06 Result := Replace(Result, '\\', #06); // replace \" with #08 Result := Replace(Result, '\"', #08); // replace \' with #07 Result := Replace(Result, '\''', #07); // replace \t with #03 Result := Replace(Result, '\t', #03); // replace \n with #04 Result := Replace(Result, '\n', #04); // replace \r with #05 Result := Replace(Result, '\r', #05); // replace " with ' Result := Replace(Result, '"', ''''); end; procedure TRXEProgram.HandlePreprocStatusChange(Sender: TObject; const StatusMsg: string); begin DoCompilerStatusChange(StatusMsg); end; { TAsmLine } procedure TAsmLine.AddArgs(sargs: string); var i : integer; SL : TStringList; Arg : TAsmArgument; tmp : string; begin // args is a comma-separated list of opcode arguments if Trim(sargs) = '' then Exit; SL := TStringList.Create; try // arguments can be delimited by single quotes, double quotes, or braces. // In any of those cases the entire contents of // the delimited item is a single argument if Pos('{', sargs) <> 0 then begin while sargs <> '' do begin // is the start of the next argument a delimiter? if IsDelimiter('{"''', sargs, 1) then begin tmp := Copy(sargs, 1, 1);//'{'; if tmp = '{' then begin System.Delete(sargs, 1, 1); // remove the delimiter i := Pos('}', sargs); if i = 0 then begin tmp := tmp + Copy(sargs, 1, MaxInt) + '}'; end else tmp := tmp + Copy(sargs, 1, i); System.Delete(sargs, 1, i); end else begin // the argument string starts with " or ' // let's just try adding the rest using CommaText. UGLY KLUDGE!!!! SL.CommaText := sargs; for i := 0 to SL.Count - 1 do begin Arg := Args.Add; Arg.Value := Trim(SL[i]); end; sargs := ''; break; end; end else begin i := Pos(',', sargs); if i = 0 then tmp := sargs else tmp := Copy(sargs, 1, i-1); System.Delete(sargs, 1, Length(tmp)); end; sargs := Trim(sargs); // remove comma between this arg and next if there is one if Pos(',', sargs) = 1 then begin System.Delete(sargs, 1, 1); sargs := Trim(sargs); end; Arg := Args.Add; Arg.Value := Trim(tmp); end; end else begin SL.CommaText := sargs; for i := 0 to SL.Count - 1 do begin Arg := Args.Add; Arg.Value := Trim(SL[i]); end; end; finally SL.Free; end; end; constructor TAsmLine.Create(ACollection: TCollection); begin inherited; fOpCode := OPS_INVALID; fInstrSize := -1; fMacroExpansion := False; fIsSpecial := False; fArgs := TAsmArguments.Create; end; function TAsmLine.InstructionSize: integer; begin if fInstrSize = -1 then FinalizeASMInstrSize; Result := fInstrSize; end; destructor TAsmLine.Destroy; begin FreeAndNil(fArgs); inherited; end; function TAsmLine.GetClumpCode: TClumpCode; begin Result := TClumpCode(Collection); end; procedure TAsmLine.SetArgs(const Value: TAsmArguments); begin fArgs.Assign(Value); end; function TAsmLine.CanBeShortOpEncoded: boolean; var rarg : ShortInt; w : word; tmpInt : integer; begin Result := False; fsop := LongOpToShortOp(Command); if fsop <> -1 then begin case Args.Count of 1 : begin { If the arg array has only 1 item and when the U16 value is converted to an I8 the two are equal then short ops are allowed and the relative arg output is the I8 value. } rarg := ShortInt(Args[0].DSID); w := Word(Args[0].DSID); Result := w = Word(rarg); end; 2 : begin { If there are two args in the array then take (arg 0 - arg 1), convert to I8, add arg 1, compare arg 0 to the result. If equal the short op is allowed. relative arg output is the I8 difference between arg 0 and arg 1. } tmpInt := (Args[0].DSID - Args[1].DSID); rarg := ShortInt(tmpInt); tmpInt := Args[1].DSID + rarg; Result := Args[0].DSID = tmpInt; end; else Result := False; end; end; end; procedure TAsmLine.FinalizeASMInstrSize; var idx : integer; NI : NXTInstruction; begin FinalizeArgs(False); fInstrSize := 0; fArity := 0; fCC := 0; if Command = OPS_INVALID then Exit; idx := CodeSpace.IndexOfOpcode(Command); if idx <> -1 then begin NI := CodeSpace.GetNXTInstruction(idx); fArity := NI.Arity; fCC := NI.CCType; if fArity = 6 then begin // opcodes with an arity of 6 have to be handled in a special manner fInstrSize := (2+Args.Count)*2; end else begin fInstrSize := (fArity + 1) * 2; if CanBeShortOpEncoded then Dec(fInstrSize, 2); end; end; end; procedure TAsmLine.HandleNameToDSID(const name: string; var aId: integer); var i : integer; begin // check whether the name matches an IO Map macro name i := IndexOfIOMapName(name); if i <> -1 then aId := IOMapFieldIDs[i].ID else ClumpCode.HandleNameToDSID(name, aId); end; procedure TAsmLine.SaveToCode(var Store: CodeArray); var i, len, start : integer; begin if Length(fCode) = 0 then FinalizeCode; len := Length(fCode); start := Length(Store); // copy data from our local array to the passed in array SetLength(Store, start + len); for i := 0 to len - 1 do begin Store[start+i] := fCode[i]; end; end; procedure TAsmLine.FinalizeCode; var i, argidx, isize : integer; b1, b2, cc : byte; rarg : ShortInt; bShort : boolean; arg0, arg1 : word; begin FinalizeArgs(True); SetLength(fCode, fInstrSize div 2); bShort := CanBeShortOpEncoded; argidx := 0; isize := (farity+1)*2; if bShort then dec(isize, 2); for i := 0 to Length(fCode) - 1 do begin if (i = 0) and bShort then begin // first word short //iiiifsss xxxxxxxx b2 := (Byte(isize shl 4) and INST_MASK) or SHOP_MASK or (Byte(fsop) and CC_MASK); if farity = 1 then begin b1 := Byte(Args[argidx].DSID); // low byte // eat the first argument inc(argidx); fCode[i] := Word((Word(b1) and $FF) + (Word(b2) shl 8)); end else begin arg0 := Word(Args[argidx].DSID); // eat the first argument inc(argidx); // peek at the second argument as well and calculate a temporary word // for the next slot in fCode arg1 := Word(Args[argidx].DSID); // the low byte in the first slot is a relative argument rarg := ShortInt(arg0 - arg1); fCode[i] := Word((Word(rarg) and $FF) + (Word(b2) shl 8)); end; end else if i = 0 then begin // first word long b1 := Byte(Ord(Command)); // low byte b2 := (Byte(isize shl 4) and INST_MASK); if fCC <> 0 then begin // first argument should be comparison code cc := Byte(Args[argidx].DSID); inc(argidx); b2 := b2 or (cc and CC_MASK); end; fCode[i] := Word((Word(b1) and $FF) + (Word(b2) shl 8)); end else begin // special handling for opcodes with arity = 6 if (fArity = 6) and (i = 1) then begin fCode[i] := Word(fInstrSize); end else begin // all other words (regardless of encoding type) fCode[i] := Word(Args[argidx].DSID); inc(argidx); end; end; end; end; procedure TAsmLine.FinalizeArgs(bResolveDSIDs : Boolean); var i, dsid, x, fsop : integer; Arg : TAsmArgument; argType : TAsmArgType; begin if Command = OPS_INVALID then Exit; if (Command = OP_FINCLUMP) and (Args.Count <> 2) then begin FixupFinClump; end else begin // commands which can be short op encoded need to have their arguments // finalized regardless of the bResolveDSIDs value fsop := LongOpToShortOp(Command); if (fsop <> -1) or bResolveDSIDs then begin for i := 0 to Args.Count - 1 do begin Arg := Args[i]; x := 0; Val(Arg.Value, dsid, x); // Val was interpreting variables such as 'xd' and 'xcb' as hexadecimal // numbers. By checking also whether Arg.Value is a valid identifier // we can correctly resolve the variable (2006-05-04 JCH) if (x <> 0) or IsValidIdent(Arg.Value) then begin // some opcodes have clump IDs as their arguments. Those need // special handling. if ((Command in [OP_SUBCALL, OPS_CALL, OPS_PRIORITY, OPS_PRIORITY_2]) and (i = 0)) or (Command in [OP_FINCLUMPIMMED, OPS_START, OPS_STOPCLUMP, OPS_START_2, OPS_STOPCLUMP_2]) then begin // try to lookup the clump # from the clump name dsid := CodeSpace.IndexOf(Arg.Value); end else begin // argument is not a valid integer (in string form) // could this argument be a label? argType := ExpectedArgType(FirmwareVersion, Self.Command, i); if argType = aatLabelID then begin if IsLabel(Arg.Value, dsid) then begin // id is start address of line containing label // we need to calculate positive or negative offset dsid := dsid - StartAddress; end else HandleNameToDSID(Arg.Value, dsid); end else HandleNameToDSID(Arg.Value, dsid); end; end; // if we have a dsid of -1 then try to resolve it one last time as // a constant expression if dsid = -1 then dsid := Integer(Trunc(Arg.Evaluate(CodeSpace.Calc))); Arg.fDSID := dsid; end; end; end; end; function TAsmLine.IsLabel(const name: string; var aID : integer): boolean; var i : integer; AL : TAsmLine; begin aID := 0; i := Clump.IndexOfLabel(name); Result := i <> -1; if Result then begin AL := Clump.AsmLineFromLabelIndex(i); aID := AL.StartAddress; end; end; function TAsmLine.GetAsString: string; begin if fIsSpecial then Result := fSpecialStr else begin Result := LineLabel; if Result <> '' then Result := Result + ':'; if Command <> OPS_INVALID then begin Result := Result + #9; Result := Result + CodeSpace.OpcodeToStr(Command) + ' ' + Args.AsString; end; end; end; function TAsmLine.GetClump: TClump; begin Result := ClumpCode.Clump; end; function TAsmLine.GetCodeSpace: TCodeSpace; begin Result := Clump.CodeSpace; end; procedure TAsmLine.FixupFinClump; var A1, A2 : TAsmArgument; begin Args.Clear; A1 := Args.Add; A2 := Args.Add; // automatically generate the correct arguments and DSID values if Clump.DownstreamCount > 0 then A1.fDSID := 0 else A1.fDSID := -1; A2.fDSID := Clump.DownstreamCount - 1; A1.Value := IntToStr(A1.DSID); A2.Value := IntToStr(A2.DSID); end; procedure TAsmLine.RemoveVariableReferences; var i : integer; begin for i := 0 to Args.Count - 1 do begin RemoveVariableReference(Args[i].Value, i); end; end; procedure TAsmLine.RemoveVariableReference(const arg: string; const idx : integer); var argType : TAsmArgType; begin argType := ExpectedArgType(FirmwareVersion, Command, idx); case argType of aatVariable, aatVarNoConst, aatVarOrNull, aatScalar, aatScalarNoConst, aatScalarOrNull, aatMutex, aatCluster, aatArray, aatString, aatStringNoConst : begin CodeSpace.Dataspace.RemoveReferenceIfPresent(arg); end; aatClumpID : begin CodeSpace.RemoveReferenceIfPresent(arg); end; end; end; function TAsmLine.GetPC: word; begin Result := Word(StartAddress); end; procedure TAsmLine.SetAsString(const Value: string); begin fIsSpecial := True; Command := OPS_INVALID; fSpecialStr := Value; end; function TAsmLine.FirmwareVersion: word; begin Result := CodeSpace.FirmwareVersion; end; function TAsmLine.GetOptimizable: boolean; var op : TOpCode; begin Result := False; op := Command; if (op in [OP_ADD..OP_ROTR]) or (op in [OP_GETIN, OP_GETOUT, OP_GETTICK]) or (op in [OP_INDEX..OP_BYTEARRTOSTR]) or ((FirmwareVersion > MAX_FW_VER1X) and (op in [OP_SQRT_2, OP_ABS_2, OPS_SIGN_2, OPS_FMTNUM_2, OPS_ACOS_2..OPS_ADDROF])) or ((FirmwareVersion <= MAX_FW_VER1X) and (op in [OPS_ABS, OPS_SIGN, OPS_FMTNUM, OPS_ACOS..OPS_POW])) then begin Result := True; end; end; { TAsmArguments } function TAsmArguments.Add: TAsmArgument; begin Result := TAsmArgument(inherited Add); end; procedure TAsmArguments.AssignTo(Dest: TPersistent); var i : integer; arg : TAsmArgument; begin if Dest is TAsmArguments then begin TAsmArguments(Dest).Clear; for i := 0 to Self.Count - 1 do begin arg := TAsmArguments(Dest).Add; arg.Value := Self[i].Value; end; end else inherited; end; constructor TAsmArguments.Create; begin inherited Create(TAsmArgument); end; function TAsmArguments.GetAsString: string; var i : integer; begin Result := ''; for i := 0 to Count - 1 do Result := Result + Items[i].Value + ', '; if Count > 0 then System.Delete(Result, Length(Result)-1, 2); end; function TAsmArguments.GetItem(Index: Integer): TAsmArgument; begin Result := TAsmArgument(inherited GetItem(Index)); end; function TAsmArguments.Insert(Index: Integer): TAsmArgument; begin Result := TAsmArgument(inherited Insert(Index)); end; procedure TAsmArguments.SetItem(Index: Integer; const Value: TAsmArgument); begin inherited SetItem(Index, Value); end; { TCodeSpace } function TCodeSpace.Add: TClump; begin Result := TClump(inherited Add); end; procedure TCodeSpace.BuildReferences; var i, j : integer; C : TClump; AL : TAsmLine; begin // build references for i := 0 to Count - 1 do begin C := Items[i]; if i = 0 then C.IncRefCount; // the first clump is required for j := 0 to C.ClumpCode.Count - 1 do begin AL := C.ClumpCode.Items[j]; if AL.Command in [OP_SUBCALL, OPS_CALL, OP_FINCLUMPIMMED, OPS_START, OPS_STOPCLUMP, OPS_PRIORITY, OPS_START_2, OPS_STOPCLUMP_2, OPS_PRIORITY_2] then begin // a clump name argument if AL.Args.Count > 0 then AddReferenceIfPresent(C, AL.Args[0].Value); end; end; // downstream clumps for j := 0 to C.DownstreamCount - 1 do begin AddReferenceIfPresent(C, C.DownstreamClumps[j]); end; end; end; procedure TCodeSpace.Compact; var bDone : boolean; i : integer; C : TClump; begin // remove any unused clumps from the codespace bDone := False; while not bDone do begin bDone := True; // never check clump 0 since it is the main clump for i := 1 to Count - 1 do begin C := Items[i]; if not C.InUse then begin // remove this clump from the codespace C.RemoveReferences; Delete(i); bDone := False; break; end; end; end; end; constructor TCodeSpace.Create(rp : TRXEProgram; ds : TDataspace); begin inherited Create(TClump); fRXEProg := rp; fDS := ds; fInitName := 'main'; fAddresses := TObjectList.Create; fFireCounts := TObjectList.Create; fMultiThreadedClumps := TStringList.Create; TStringList(fMultiThreadedClumps).CaseSensitive := True; TStringList(fMultiThreadedClumps).Duplicates := dupIgnore; FirmwareVersion := 128; end; destructor TCodeSpace.Destroy; begin FreeAndNil(fAddresses); FreeAndNil(fFireCounts); FreeAndNil(fMultiThreadedClumps); inherited; end; procedure TCodeSpace.FinalizeDependencies; var i, j, idx : integer; X : TClump; cName : string; begin // if there is a clump called main make it the first clump i := IndexOf(InitialClumpName); if i <> -1 then begin X := Items[i]; X.Index := 0; end; // update dependencies for i := 0 to Count - 1 do begin X := Items[i]; for j := 0 to X.UpstreamCount - 1 do begin // add myself to each (thread in my upstream list)'s downstream list cName := X.UpstreamClumps[j]; idx := IndexOf(cName); if idx <> -1 then Items[idx].AddDependant(X.Name); end; for j := 0 to X.DownstreamCount - 1 do begin // add myself to each (thread in my downstream list)'s upstream list cName := X.DownstreamClumps[j]; idx := IndexOf(cName); if idx <> -1 then Items[idx].AddAncestor(X.Name); end; end; end; function TCodeSpace.GetAddress(aIndex: Integer): Word; begin if fAddresses.Count <> Count then FinalizeAddressesAndFireCounts; Result := Word(TIntegerObject(fAddresses[aIndex]).Value); end; function TCodeSpace.GetCaseSensitive: boolean; begin Result := fCaseSensitive; end; function TCodeSpace.GetFireCount(aIndex: integer): Byte; begin if fFireCounts.Count <> Count then FinalizeAddressesAndFireCounts; Result := Byte(TIntegerObject(fFireCounts[aIndex]).Value); end; function TCodeSpace.GetItem(aIndex: Integer): TClump; begin Result := TClump(inherited GetItem(aIndex)); end; procedure TCodeSpace.HandleNameToDSID(const aName: string; var aId: integer); begin aId := 0; if Assigned(fOnNameToDSID) then fOnNameToDSID(aName, aId); end; function TCodeSpace.IndexOf(const aName: string): integer; var i : integer; begin Result := -1; for i := 0 to Count - 1 do begin if Items[i].Name = aName then begin Result := i; Break; end; end; end; procedure TCodeSpace.AddReferenceIfPresent(aClump : TClump; const aName: string); var i : integer; C : TClump; begin i := IndexOf(aName); if i <> -1 then begin C := Items[i]; C.IncRefCount; if C.IsSubroutine then C.AddCaller(aClump.Name); end; end; procedure TCodeSpace.RemoveReferenceIfPresent(const aName: string); var i : integer; begin i := IndexOf(aName); if i <> -1 then Items[i].DecRefCount; end; procedure TCodeSpace.SaveToCodeData(aCD: TClumpData; aCode : TCodeSpaceAry); var pX : ^ClumpRecord; C : TClump; i : integer; begin if (fAddresses.Count <> Count) or (fFireCounts.Count <> Count) then FinalizeAddressesAndFireCounts; SetLength(aCD.ClumpDeps, 0); // start with an empty array SetLength(aCode.Code, 0); SetLength(aCD.CRecs, Count); for i := 0 to Count - 1 do begin pX := @(aCD.CRecs[i]); C := Items[i]; pX^.FireCount := FireCounts[i]; pX^.DependentCount := C.DownstreamCount; pX^.CodeStart := StartingAddresses[i]; C.SaveDependencies(aCD.ClumpDeps); C.SaveToCode(aCode.Code); end; end; procedure TCodeSpace.SetCaseSensitive(const Value: boolean); var i : integer; begin fCaseSensitive := Value; for i := 0 to Count - 1 do begin Items[i].fLabelMap.CaseSensitive := Value; Items[i].fUpstream.CaseSensitive := Value; Items[i].fDownstream.CaseSensitive := Value; end; end; procedure TCodeSpace.SetItem(aIndex: Integer; const aValue: TClump); begin inherited SetItem(aIndex, aValue); end; procedure TCodeSpace.FinalizeAddressesAndFireCounts; var i : integer; X : TClump; addr : integer; begin // calculate addresses for all the clumps addr := 0; fAddresses.Clear; fFireCounts.Clear; for i := 0 to Count - 1 do begin X := Items[i]; fAddresses.Add(TIntegerObject.Create(addr)); inc(addr, X.DataSize); fFireCounts.Add(TIntegerObject.Create(X.FireCount)); end; end; procedure TCodeSpace.Optimize(const level : Integer); var i : integer; C : TClump; begin // level 2 optimizations are buggy so don't do them. // have each clump optimize itself for i := 0 to Count - 1 do begin C := Items[i]; // skip clumps starting with '__' under the assumption that // they are API-level (hand optimized) clumps if Pos('__', C.Name) = 1 then Continue; RXEProgram.DoCompilerStatusChange(Format(sNBCOptClump, [C.Name])); C.Optimize(level); end; end; procedure TCodeSpace.OptimizeMutexes; var i : integer; begin // have each clump optimize itself for i := 0 to Count - 1 do Items[i].OptimizeMutexes; end; procedure TCodeSpace.SaveToSymbolTable(aStrings: TStrings); var i, j : integer; C : TClump; AL : TAsmLine; begin aStrings.Add('#SOURCES'); aStrings.Add('Clump'#9'Line'#9'PC'#9'Source'); for i := 0 to Count - 1 do begin C := Items[i]; for j := 0 to C.ClumpCode.Count - 1 do begin AL := C.ClumpCode.Items[j]; if not AL.IsPartOfMacroExpansion and ((AL.Command <> OPS_INVALID) or (AL.IsSpecial)) then aStrings.Add(Format('%d'#9'%d'#9'%d'#9'%s', [i, AL.LineNum, AL.ProgramCounter, AL.AsString])); end; end; aStrings.Add('#CLUMPS'); aStrings.Add('Clump'#9'Name'#9'Offset'#9'File'); for i := 0 to Count - 1 do begin C := Items[i]; aStrings.Add(Format('%d'#9'%s'#9'%d'#9'%s', [i, C.Name, C.StartAddress, C.Filename])); end; end; procedure TCodeSpace.MultiThread(const aName: string); begin fMultiThreadedClumps.Add(aName); end; function TCodeSpace.GetNXTInstruction(const idx: integer): NXTInstruction; begin Result := fNXTInstructions[idx]; end; procedure TCodeSpace.InitializeInstructions; var i : integer; begin if fFirmwareVersion > MAX_FW_VER1X then begin SetLength(fNXTInstructions, NXTInstructionsCount2x); for i := 0 to NXTInstructionsCount2x - 1 do begin fNXTInstructions[i] := NXTInstructions2x[i]; end; end else begin SetLength(fNXTInstructions, NXTInstructionsCount1x); for i := 0 to NXTInstructionsCount1x - 1 do begin fNXTInstructions[i] := NXTInstructions1x[i]; end; end; end; function TCodeSpace.IndexOfOpcode(op: TOpCode): integer; var i : integer; begin Result := -1; for i := Low(fNXTInstructions) to High(fNXTInstructions) do begin if fNXTInstructions[i].Encoding = op then begin Result := i; Break; end; end; end; procedure TCodeSpace.SetFirmwareVersion(const Value: word); begin fFirmwareVersion := Value; InitializeInstructions; end; function TCodeSpace.OpcodeToStr(const op: TOpCode): string; var i : integer; begin if op <> OPS_INVALID then Result := Format('bad op (%d)', [Ord(op)]) else Result := ''; for i := Low(fNXTInstructions) to High(fNXTInstructions) do begin if fNXTInstructions[i].Encoding = op then begin Result := fNXTInstructions[i].Name; break; end; end; end; procedure TCodeSpace.RemoveUnusedLabels; var i : integer; begin // now remove any labels that are not targets of a branch/jump for i := 0 to Count - 1 do Items[i].RemoveUnusedLabels; end; procedure TCodeSpace.SaveToStrings(aStrings: TStrings); var i, j : integer; C : TClump; AL : TAsmLine; tmpStr : string; begin aStrings.Add(';------- code -------'); for i := 0 to Count - 1 do begin C := Items[i]; if C.IsSubroutine then aStrings.Add('subroutine ' + C.Name) else aStrings.Add('thread ' + C.Name); for j := 0 to C.ClumpCode.Count - 1 do begin AL := C.ClumpCode.Items[j]; // skip blank lines tmpStr := AL.AsString; if Trim(tmpStr) <> '' then aStrings.Add(tmpStr); end; if C.IsSubroutine then aStrings.Add('ends') else aStrings.Add('endt'); aStrings.Add(';------------------------'); end; end; { TClump } procedure TClump.AddClumpDependencies(const opcode, args: string); var tmpSL : TStringList; i : integer; begin // clumps with no downstream dependencies finalize -1, -1 // clumps with downstream dependencies finalize and conditionally schedule // all their downstream dependants with 0..N where N is the number of // dependants - 1. tmpSL := TStringList.Create; try tmpSL.CommaText := args; if opcode = CodeSpace.OpcodeToStr(OPS_REQUIRES) then begin // upstream clumps fUpstream.AddStrings(tmpSL); end else if opcode = CodeSpace.OpcodeToStr(OPS_USES) then begin // downstream clumps // fDownstream.AddStrings(tmpSL); // this seems to do the same as the for loop does for i := 0 to tmpSL.Count - 1 do AddDependant(tmpSL[i]); end; finally tmpSL.Free; end; end; constructor TClump.Create(ACollection: TCollection); begin inherited; fDatasize := -1; fIsSub := False; fRefCount := 0; fLabelMap := TStringList.Create; fLabelMap.CaseSensitive := CodeSpace.CaseSensitive; fLabelMap.Sorted := True; fUpstream := TStringList.Create; fUpstream.CaseSensitive := CodeSpace.CaseSensitive; fUpstream.Sorted := False; // do not sort dependencies fUpstream.Duplicates := dupIgnore; fDownstream := TStringList.Create; fDownstream.CaseSensitive := CodeSpace.CaseSensitive; fDownstream.Sorted := False; // do not sort dependencies fDownstream.Duplicates := dupIgnore; fClumpCode := TClumpCode.Create(Self); fClumpCode.OnNameToDSID := HandleNameToDSID; fCallers := TStringList.Create; fCallers.CaseSensitive := CodeSpace.CaseSensitive; fCallers.Sorted := True; fCallers.Duplicates := dupIgnore; end; destructor TClump.Destroy; begin FreeAndNil(fLabelMap); FreeAndNil(fUpstream); FreeAndNil(fDownstream); FreeAndNil(fClumpCode); FreeAndNil(fCallers); inherited; end; function TClump.GetUpstream(aIndex: integer): string; begin Result := fUpstream[aIndex]; end; function TClump.GetCodeSpace: TCodeSpace; begin Result := TCodeSpace(Collection); end; function TClump.GetDataSize: Word; begin // calculate the datasize from the code contained in this clump if fDatasize = -1 then FinalizeClump; Result := Word(fDatasize); end; function TClump.GetStartAddress: Word; begin // the starting address of a clump is determined by the codespace Result := CodeSpace.StartingAddresses[Self.Index]; end; function TClump.GetDownstream(aIndex: integer): string; begin Result := fDownstream[aIndex]; end; function TClump.GetDownCount: Byte; begin Result := Byte(fDownstream.Count); end; function TClump.GetUpCount: integer; begin Result := fUpstream.Count; end; procedure TClump.FinalizeClump; var i : integer; AL : TAsmLine; begin fDataSize := 0; // no code to start with ClumpCode.FixupFinalization; for i := 0 to ClumpCode.Count - 1 do begin AL := ClumpCode[i]; AL.fStartAddress := fDataSize; inc(fDataSize, AL.InstructionSize div 2); end; // save code for i := 0 to ClumpCode.Count - 1 do begin AL := ClumpCode[i]; AL.SaveToCode(fCode); end; end; procedure TClump.SaveToCode(var Store: CodeArray); var i, len, start : integer; begin if Length(fCode) = 0 then FinalizeClump; len := Length(fCode); start := Length(Store); // copy data from our local array to the passed in array SetLength(Store, start + len); for i := 0 to len - 1 do begin Store[start+i] := fCode[i]; end; end; procedure TClump.SaveDependencies(var Store: ClumpDepArray); var len, i : integer; begin len := Length(Store); SetLength(Store, len+DownstreamCount); for i := 0 to DownstreamCount - 1 do begin Store[len+i] := Byte(CodeSpace.IndexOf(DownstreamClumps[i])); end; end; procedure TClump.HandleNameToDSID(const aname: string; var aId: integer); begin CodeSpace.HandleNameToDSID(aname, aId); end; function TClump.GetFireCount: Word; var i, j : integer; cnt : Word; C : TClump; begin if Self.Index = 0 then Result := 0 else begin Result := 1; // how many times am I listed in other clumps downstream clumps list? cnt := 0; for i := 0 to CodeSpace.Count - 1 do begin C := CodeSpace[i]; if C.Index = Self.Index then Continue; for j := 0 to C.DownstreamCount - 1 do begin if C.DownstreamClumps[j] = Self.Name then begin inc(cnt); break; end; end; end; if cnt > 0 then Result := cnt; end; end; procedure TClump.AddDependant(const clumpName: string); begin if fDownstream.IndexOf(clumpName) = -1 then fDownstream.Add(clumpName); end; procedure TClump.AddAncestor(const clumpName: string); begin if fUpstream.IndexOf(clumpName) = -1 then fUpstream.Add(clumpName); end; procedure TClump.AddCaller(const clumpName: string); begin fCallers.Add(clumpName); // duplicates are ignored end; function TClump.GetCaseSensitive: boolean; begin Result := CodeSpace.CaseSensitive; end; procedure TClump.AddLabel(const lbl: string; Line : TAsmLine); begin fLabelMap.AddObject(lbl, Line); end; function TClump.IndexOfLabel(const lbl: string): integer; begin Result := fLabelMap.IndexOf(lbl); end; function TClump.AsmLineFromLabelIndex(const idx: integer): TAsmLine; begin Result := TAsmLine(fLabelMap.Objects[idx]); end; function TClump.GetInUse: boolean; begin Result := fRefCount > 0; end; procedure TClump.RemoveReferences; var i : integer; begin // remove references in code for i := 0 to ClumpCode.Count - 1 do begin ClumpCode.Items[i].RemoveVariableReferences; end; // remove downstream dependency references for i := 0 to DownstreamCount - 1 do begin CodeSpace.RemoveReferenceIfPresent(DownstreamClumps[i]); end; // if this clump is a subroutine remove // the return address variable as well if Self.IsSubroutine then CodeSpace.Dataspace.RemoveReferenceIfPresent(Format('__%s_return', [Name])); end; procedure TClump.DecRefCount; begin dec(fRefCount); end; procedure TClump.IncRefCount; begin inc(fRefCount); end; function IsStackOrReg(const str : string) : boolean; begin Result := (Pos('__D0', str) = 1) or (Pos('__signed_stack_', str) = 1) or (Pos('__unsigned_stack_', str) = 1) or (Pos('__float_stack_', str) = 1) or (Pos('__DU0', str) = 1) or (Pos('__DF0', str) = 1); end; procedure TClump.RemoveOrNOPLine(AL, ALNext : TAsmLine; const idx : integer); begin if AL.LineLabel = '' then begin ClumpCode.Delete(idx); end else if Assigned(ALNext) and (ALNext.LineLabel = '') then begin ALNext.LineLabel := AL.LineLabel; ClumpCode.Delete(idx); end else begin AL.Command := OPS_INVALID; AL.Args.Clear; end; end; function GetTypeHint(DSpace : TDataspace; const aLine: TASMLine; const idx : integer; bEnhanced : boolean): TDSType; var DE : TDataspaceEntry; begin Result := dsVoid; case aLine.Command of OP_ARRINIT : begin if (idx = 1) and not bEnhanced then begin // the first argument is always an array. We need the base type DE := DSpace.FindEntryByFullName(aLine.Args[0].Value); if Assigned(DE) then Result := DE.BaseDataType; end; end; else Result := dsVoid; end; end; function CreateConstantVar(DSpace : TDataspace; val : Extended; bIncCount : boolean; aTypeHint : TDSType) : string; var datatype : TDSType; DE : TDataspaceEntry; // iVal : Int64; sVal : Single; begin if aTypeHint <> dsVoid then datatype := aTypeHint else datatype := GetArgDataType(val); // iVal := Trunc(val*1000000); // scale by 6 decimal places // Result := GenerateTOCName(Byte(Ord(datatype)), Int64(abs(iVal)), '%1:d'); Result := Replace(NBCFloatToStr(abs(val)), '.', 'P'); if datatype = dsFloat then Result := 'f' + Result; // distinguish between float constants and integer constants if val < 0 then Result := '__constValNeg' + Result else Result := '__constVal' + Result; // is this temporary already in the dataspace? DE := DSpace.FindEntryByFullName(Result); if not Assigned(DE) then begin // we need to add it DE := DSpace.Add; DE.Identifier := Result; DE.DataType := datatype; // DE.DefaultValue := ValueAsCardinal(val, datatype); if datatype = dsFloat then begin sVal := val; DE.DefaultValue := SingleToCardinal(sVal); end else DE.DefaultValue := Cardinal(Trunc(val)); end; if Assigned(DE) and bIncCount then DE.IncRefCount; end; procedure ConvertToSetOrMov(DS : TDataspace; var AL : TAsmLine; iVal : Double; var arg1 : string); var tmp : string; DE : TDataspaceEntry; begin if (iVal < Low(SmallInt)) or (iVal > High(Word)) or (Trunc(iVal) <> iVal) then begin // we need to use mov AL.Command := OP_MOV; // the type of the output variable determines whether we should truncate this value or not tmp := AL.Args[0].Value; DE := DS.FindEntryByFullName(tmp); if Assigned(DE) then begin if DE.DataType <> dsFloat then iVal := Trunc(iVal); end; arg1 := CreateConstantVar(DS, iVal, True); end else begin // no need to use mov - we can use set instead AL.Command := OP_SET; arg1 := IntToStr(Trunc(iVal)); end; end; function GetArgValue(EP : TNBCExpParser; arg1 : string; var val : Double) : boolean; var bIsNeg : boolean; bIsFloat : boolean; begin if Pos('__constVal', arg1) = 1 then begin Result := True; // remove __constVal or __constValNeg bIsNeg := Pos('__constValNeg', arg1) = 1; if bIsNeg then System.Delete(arg1, 1, 13) else System.Delete(arg1, 1, 10); bIsFloat := (Pos('f', arg1) > 0) or (Pos('P', arg1) > 0); if bIsFloat then begin arg1 := Replace(Replace(arg1, 'f', ''), 'P', '.'); val := NBCStrToFloatDef(arg1, 0); end else val := StrToIntDef(arg1, 0); if bIsNeg then val := val * -1; end else begin EP.SilentExpression := arg1; Result := not EP.ParserError; if Result then val := EP.Value else val := 0; end; end; function CountArgUsage(AL : TAsmLine; const arg : string) : integer; var i : integer; begin Result := 0; for i := 0 to AL.Args.Count - 1 do begin if AL.Args[i].Value = arg then inc(Result); end; end; procedure TClump.Optimize(const level : Integer); var i, offset : integer; iVal : Double; AL, ALNext, tmpAL : TAsmLine; arg1, arg2, arg3, tmp : string; bDone, bArg1Numeric, bArg2Numeric, bCanOptimize : boolean; Arg1Val, Arg2Val : Double; DE : TDataspaceEntry; bEnhanced : boolean; function CheckReferenceCount : boolean; var cnt : integer; begin Result := True; arg1 := AL.Args[0].Value; // check the output (dest) argument cnt := CountArgUsage(AL, arg1); DE := CodeSpace.Dataspace.FindEntryByFullName(arg1); if Assigned(DE) then begin // simple case - refcount is less than this line's usage if DE.RefCount <= cnt then begin // setting a variable to a value and never referencing it again // set|mov X, whatever // nop (or delete line) // remove the references AL.RemoveVariableReferences; RemoveOrNOPLine(AL, nil, i); Result := False; end; end; end; begin bEnhanced := CodeSpace.RXEProgram.EnhancedFirmware; bDone := False; while not bDone do begin bDone := True; // assume we are done for i := 0 to ClumpCode.Count - 1 do begin AL := ClumpCode.Items[i]; // any line of this form: op reg/stack, rest // followed by this line mov anything, reg/stack // where reg/stack1 == reg/stack2 // can be replaced by one line of this form: // op anything, rest // nop if AL.Optimizable then begin // first check reference count of output variable if not CheckReferenceCount then begin bDone := False; Break; end; arg1 := AL.Args[0].Value; if IsStackOrReg(arg1) then begin // maybe we can do an optimization // find the next line (which may not be i+1) that is not (NOP or labeled) offset := 1; while (i < ClumpCode.Count - offset) do begin tmpAL := ClumpCode.Items[i+offset]; if (tmpAL.Command <> OPS_INVALID) or (tmpAL.LineLabel <> '') then Break; inc(offset); end; // every line between Items[i] and Items[i+offset] are NOP lines without labels. if i < (ClumpCode.Count - offset) then begin ALNext := ClumpCode.Items[i+offset]; // now check other cases // bricxcc-Bugs-1669679 - make sure the next line // cannot be jumped to from elsewhere. If it does then the // "previous" line may actually be skipped so we cannot // do any optimization if (ALNext.LineLabel = '') and (ALNext.Command = OP_MOV) and (ALNext.Args[1].Value = arg1) then begin bCanOptimize := True; if not bEnhanced then begin if AL.Command in [OP_GETTICK, OP_NOT, OP_ARRSIZE, OP_GETOUT, OP_CMP, OP_WAIT] then begin DE := CodeSpace.Dataspace.FindEntryByFullName(ALNext.Args[0].Value); if Assigned(DE) then bCanOptimize := (DE.DataType <> dsFloat) else bCanOptimize := False; end else if AL.Command = OP_STRINGTONUM then begin DE := CodeSpace.Dataspace.FindEntryByFullName(ALNext.Args[1].Value); if Assigned(DE) then bCanOptimize := (DE.DataType <> dsFloat) else bCanOptimize := False; end; end else if AL.Command = OP_SET then begin // need to also check the type of the next line's output arg DE := CodeSpace.Dataspace.FindEntryByFullName(ALNext.Args[0].Value); if Assigned(DE) then bCanOptimize := DE.DataType <> dsFloat else bCanOptimize := False; end; if bCanOptimize then begin AL.RemoveVariableReference(arg1, 0); AL.Args[0].Value := ALNext.Args[0].Value; // switch output arg (no ref count changes) ALNext.RemoveVariableReference(arg1, 1); ALNext.Command := OPS_INVALID; // no-op next line ALNext.Args.Clear; bDone := False; Break; end; end; end; end; end; case AL.Command of OP_SET, OP_MOV : begin // this is a set or mov line // first check reference count of output variable if not CheckReferenceCount then begin bDone := False; Break; end; if AL.Args[0].Value = AL.Args[1].Value then begin // set|mov X, X <-- replace with nop or delete AL.RemoveVariableReferences; RemoveOrNOPLine(AL, nil, i); bDone := False; Break; end; arg1 := AL.Args[0].Value; // find the next line (which may not be i+1) that is not (NOP or labeled) offset := 1; while (i < ClumpCode.Count - offset) do begin tmpAL := ClumpCode.Items[i+offset]; if (tmpAL.Command <> OPS_INVALID) or (tmpAL.LineLabel <> '') then begin // is it safe to ignore this line? If it is a set or a mov for // different variables then yes (at higher optimization levels) ... // (this is not always safe AKA buggy) if not ((tmpAL.Command in [OP_SET, OP_MOV]) and (tmpAL.LineLabel = '') and (arg1 <> tmpAL.Args[0].Value) and (arg1 <> tmpAL.Args[1].Value) and (level >= 4)) then Break; end; inc(offset); end; // every line between Items[i] and Items[i+offset] are NOP lines without labels. // OR lines that have nothing whatsoever to do with the output variable in // Items[i] if i < (ClumpCode.Count - offset) then begin ALNext := ClumpCode.Items[i+offset]; // now check other cases // bricxcc-Bugs-1669679 - make sure the next line // cannot be jumped to from elsewhere. If it does then the // "previous" line may actually be skipped so we cannot // do any optimization if ALNext.LineLabel = '' then begin case ALNext.Command of OP_SET, OP_MOV : begin if ALNext.Args[0].Value = AL.Args[0].Value then begin // set|mov X, whatever // set|mov X, whatever <-- replace these two lines with // nop (or delete line) // set|mov X, whatever AL.RemoveVariableReferences; RemoveOrNOPLine(AL, ALNext, i); bDone := False; Break; end else begin arg1 := AL.Args[0].Value; arg2 := ALNext.Args[1].Value; if (arg1 = arg2) then begin // set|mov __D0,whatever (__D0 or __stack_nnn) // mov X,__D0 <-- replace these two lines with // nop (if arg1 and arg2 are stack or register variables) // mov X,whatever if AL.Command = OP_SET then tmp := CreateConstantVar(CodeSpace.Dataspace, StrToIntDef(AL.Args[1].Value, 0), True) else begin tmp := AL.Args[1].Value; CodeSpace.Dataspace.FindEntryAndAddReference(tmp); end; ALNext.Command := OP_MOV; ALNext.Args[1].Value := tmp; { ALNext.Command := AL.Command; ALNext.Args[1].Value := AL.Args[1].Value; } ALNext.RemoveVariableReference(arg2, 1); if IsStackOrReg(arg1) then begin // remove second reference to _D0 AL.RemoveVariableReferences; // AL.RemoveVariableReference(arg1, 0); RemoveOrNOPLine(AL, ALNext, i); end; bDone := False; Break; end; end; end; OPS_WAITV, OPS_WAITV_2 : begin // these two opcodes are only present if EnhancedFirmware is true arg1 := AL.Args[0].Value; arg2 := ALNext.Args[0].Value; if (arg1 = arg2) then begin // set|mov __D0,whatever (__D0 or __stack_nnn) // waitv __D0 <-- replace these two lines with // nop (if arg1 and arg2 are stack or register variables) // waitv|wait whatever ALNext.Args[0].Value := AL.Args[1].Value; ALNext.RemoveVariableReference(arg2, 0); if AL.Command = OP_SET then begin if CodeSpace.FirmwareVersion > MAX_FW_VER1X then ALNext.Command := OPS_WAITI_2 else ALNext.Command := OP_WAIT; end; CodeSpace.Dataspace.FindEntryAndAddReference(ALNext.Args[0].Value); if IsStackOrReg(arg1) then begin // remove second reference to _D0 AL.RemoveVariableReferences; // AL.RemoveVariableReference(arg1, 0); RemoveOrNOPLine(AL, ALNext, i); end; bDone := False; Break; end; end; OP_ADD, OP_SUB, OP_MUL, OP_DIV, OP_MOD, OP_AND, OP_OR, OP_XOR, OP_LSL, OP_LSR, OP_ASL, OP_ASR : begin arg1 := AL.Args[0].Value; arg2 := ALNext.Args[2].Value; arg3 := ALNext.Args[1].Value; if (arg1 = arg2) or (arg1 = arg3) then begin // set|mov __D0,X // arithop A, B, __D0 <-- replace these two lines with // nop // arithop A, B, X if AL.Command = OP_SET then tmp := CreateConstantVar(CodeSpace.Dataspace, StrToIntDef(AL.Args[1].Value, 0), True) else begin // increment the reference count of this variable tmp := AL.Args[1].Value; CodeSpace.Dataspace.FindEntryAndAddReference(tmp); end; if (arg1 = arg2) then begin ALNext.Args[2].Value := tmp; ALNext.RemoveVariableReference(arg2, 2); end else begin // arg1=arg3 (aka ALNext.Args[1].Value) ALNext.Args[1].Value := tmp; ALNext.RemoveVariableReference(arg3, 1); end; if IsStackOrReg(arg1) then begin // remove second reference to _D0 AL.RemoveVariableReferences; // AL.RemoveVariableReference(arg1, 0); RemoveOrNOPLine(AL, ALNext, i); end; bDone := False; Break; end; end; OP_NEG, OP_NOT : begin arg1 := AL.Args[0].Value; arg2 := ALNext.Args[1].Value; if arg1 = arg2 then begin // set|mov __D0,X // neg|not A, __D0 <-- replace these two lines with // nop // neg|not A, X if AL.Command = OP_SET then tmp := CreateConstantVar(CodeSpace.Dataspace, StrToIntDef(AL.Args[1].Value, 0), True) else begin tmp := AL.Args[1].Value; CodeSpace.Dataspace.FindEntryAndAddReference(tmp); end; ALNext.Args[1].Value := tmp; ALNext.RemoveVariableReference(arg2, 1); if IsStackOrReg(arg1) then begin // remove second reference to _D0 AL.RemoveVariableReference(arg1, 0); RemoveOrNOPLine(AL, ALNext, i); end; bDone := False; Break; end; end; else // nothing end; end; end; end; OP_ADD, OP_SUB, OP_MUL, OP_DIV, OP_MOD, OP_AND, OP_OR, OP_XOR, OP_ASL, OP_ASR : begin // first check reference count of output variable if not CheckReferenceCount then begin bDone := False; Break; end; if level >= 3 then begin // process argument 1 // is it a constant variable (i.e., aname == _constVal...) arg1 := AL.Args[1].Value; Arg1Val := 0; bArg1Numeric := GetArgValue(CodeSpace.Calc, arg1, Arg1Val); // now process argument 2 arg2 := AL.Args[2].Value; Arg2Val := 0; bArg2Numeric := GetArgValue(CodeSpace.Calc, arg2, Arg2Val); // ready to process if bArg1Numeric and bArg2Numeric then begin if (AL.Command in [OP_ADD, OP_SUB, OP_MUL, OP_DIV]) or ((Trunc(Arg1Val) = Arg1Val) and (Trunc(Arg2Val) = Arg2Val)) then begin // both arguments are numeric AL.RemoveVariableReference(arg1, 1); AL.RemoveVariableReference(arg2, 2); case AL.Command of OP_ADD : iVal := Arg1Val + Arg2Val; OP_SUB : iVal := Arg1Val - Arg2Val; OP_MUL : iVal := Arg1Val * Arg2Val; OP_DIV : iVal := Arg1Val / Arg2Val; OP_MOD : iVal := Trunc(Arg1Val) mod Trunc(Arg2Val); OP_AND : iVal := integer(Trunc(Arg1Val) and Trunc(Arg2Val)); OP_OR : iVal := integer(Trunc(Arg1Val) or Trunc(Arg2Val)); OP_XOR : iVal := integer(Trunc(Arg1Val) xor Trunc(Arg2Val)); OP_ASL : iVal := integer(Trunc(Arg1Val) shl Trunc(Arg2Val)); OP_ASR : iVal := integer(Trunc(Arg1Val) shr Trunc(Arg2Val)); else iVal := 0; end; // arithop X, N1, N2 <-- replace this line with // set|mov X, N (where N = N1 arithop N2) ConvertToSetOrMov(CodeSpace.Dataspace, AL, iVal, arg1); AL.Args.Delete(2); AL.Args[1].Value := arg1; bDone := False; Break; end; end; end; end; OP_NEG, OP_NOT : begin // first check reference count of output variable if not CheckReferenceCount then begin bDone := False; Break; end; if level >= 3 then begin // process argument 1 // is it a constant variable (i.e., aname == _constVal...) arg1 := AL.Args[1].Value; bArg1Numeric := GetArgValue(CodeSpace.Calc, arg1, Arg1Val); // ready to process if bArg1Numeric and ((AL.Command = OP_NEG) or (Trunc(Arg1Val) = Arg1Val)) then begin // the argument is numeric AL.RemoveVariableReference(arg1, 1); case AL.Command of OP_NEG : iVal := Arg1Val * -1; OP_NOT : iVal := integer(not boolean(Trunc(Arg1Val))); else iVal := 0; end; // neg|not X, N1 <-- replace this line with // set|mov X, N (where N = neg|not N1 ) ConvertToSetOrMov(CodeSpace.Dataspace, AL, iVal, arg1); AL.Args[1].Value := arg1; bDone := False; Break; end; end; end; OP_JMP, OP_BRCMP, OP_BRTST : begin // if this line is a some kind of jump statement and the destination is the very next line that // is not a no-op then it can be optimized. if AL.Command = OP_JMP then begin arg1 := AL.Args[0].Value; // first argument is label end else // if AL.Command in [OP_BRCMP, OP_BRTST] then begin arg1 := AL.Args[1].Value; // second argument is label end; // find the next line (which may not be i+1) that is not (NOP or labeled) offset := 1; while (i < ClumpCode.Count - offset) do begin tmpAL := ClumpCode.Items[i+offset]; if (tmpAL.Command <> OPS_INVALID) or (tmpAL.LineLabel <> '') then Break; inc(offset); end; // every line between Items[i] and Items[i+offset] are NOP lines without labels. if i < (ClumpCode.Count - offset) then begin ALNext := ClumpCode.Items[i+offset]; // if the next line has a label == to arg1 then we can delete the current line if ALNext.LineLabel = arg1 then begin AL.RemoveVariableReferences; RemoveOrNOPLine(AL, ALNext, i); RemoveUnusedLabels; bDone := False; Break; end; end; end; else // nothing end; end; end; end; procedure TClump.OptimizeMutexes; var i : integer; AL : TAsmLine; de : TDataspaceEntry; function AllCallersHaveZeroAncestors : boolean; var j, idx : integer; C : TClump; begin Result := True; for j := 0 to CallerCount - 1 do begin idx := CodeSpace.IndexOf(fCallers[j]); if idx <> -1 then begin C := CodeSpace[idx]; if C.UpstreamCount > 0 then begin Result := False; Break; end; end; end; end; begin if (UpstreamCount = 0) and ((CallerCount <= 1) or AllCallersHaveZeroAncestors) and (not IsMultithreaded) then for i := 0 to ClumpCode.Count - 1 do begin AL := ClumpCode.Items[i]; if AL.Command in [OP_ACQUIRE, OP_RELEASE] then begin de := self.CodeSpace.Dataspace.FindEntryByName(Al.Args[0].Value); if Assigned(de) and (de.DataType = dsMutex) and (de.ThreadCount <= 1) then begin AL.RemoveVariableReferences; AL.Command := OPS_INVALID; // no-op AL.Args.Clear; end; end; end; end; function TClump.GetCallerCount: Byte; begin Result := Byte(fCallers.Count); end; function TClump.GetIsMultithreaded: boolean; begin Result := Codespace.fMultiThreadedClumps.IndexOf(Self.Name) <> -1; end; procedure TClump.RemoveUnusedLabels; var i : integer; AL : TAsmLine; SL : TStringList; begin // first gather a list of jump targets in this clump SL := TStringList.Create; try SL.Sorted := True; SL.Duplicates := dupIgnore; for i := 0 to ClumpCode.Count - 1 do begin AL := ClumpCode.Items[i]; if AL.Command = OP_JMP then begin SL.Add(AL.Args[0].Value); // first argument is label end else if AL.Command in [OP_BRCMP, OP_BRTST] then begin SL.Add(AL.Args[1].Value); // second argument is label end; end; for i := 0 to ClumpCode.Count - 1 do begin AL := ClumpCode.Items[i]; if SL.IndexOf(AL.LineLabel) = -1 then AL.LineLabel := ''; end; finally SL.Free; end; end; { TClumpCode } function TClumpCode.Add: TAsmLine; begin Result := TAsmLine(inherited Add); end; constructor TClumpCode.Create(aClump : TClump); begin inherited Create(TAsmLine); fClump := aClump; end; destructor TClumpCode.Destroy; begin inherited; end; procedure TClumpCode.FixupFinalization; var i : integer; AL : TAsmLine; bDone : boolean; begin // if this clump does not contain exit, exitto or subret calls anywhere // or if the last line has an invalid opcode (empty line with label) // then add exit at the very end bDone := False; for i := 0 to Count - 1 do begin AL := Items[i]; if AL.Command in [OP_FINCLUMP, OP_FINCLUMPIMMED, OP_SUBRET] then begin bDone := True; Break; end; end; if not bDone or ((Count > 0) and (Items[Count - 1].Command = OPS_INVALID)) then begin // need to add fthread to end of clump code AL := Add; AL.LineNum := Clump.LastLine; if Clump.IsSubroutine then begin AL.Command := OP_SUBRET; AL.AddArgs(Format('__%s_return', [Clump.Name])); end else AL.Command := OP_FINCLUMP; end; end; function TClumpCode.GetItem(Index: Integer): TAsmLine; begin Result := TAsmLine(inherited GetItem(Index)); end; procedure TClumpCode.HandleNameToDSID(const aName: string; var aId: integer); begin aId := 0; if Assigned(fOnNameToDSID) then fOnNameToDSID(aName, aId); end; procedure TClumpCode.SetItem(Index: Integer; const Value: TAsmLine); begin inherited SetItem(Index, Value); end; { TAsmArgument } function TAsmArgument.Evaluate(Calc: TNBCExpParser): Extended; begin Calc.Expression := Value; Result := Calc.Value; end; function TAsmArgument.IsQuoted(delim : char): boolean; begin // the argument is a quoted if it starts and ends with // the specified delimiter. Result := (IsDelimiter(delim, Value, 1) and IsDelimiter(delim, Value, Length(Value))); end; procedure TAsmArgument.SetValue(const Value: string); begin fDSID := -1; fValue := Value; end; { TDSData } constructor TDSData.Create; begin fDSStaticSize := -1; end; function TDSData.DSCount: Word; begin Result := Word(Length(TOC)); end; function TDSData.DSStaticSize: Word; var i : integer; X : DSTocEntry; begin if fDSStaticSize = -1 then begin // the maximum address in toc + the size in bytes fDSStaticSize := 0; for i := 0 to Length(TOC) - 1 do begin X := TOC[i]; if X.DataDesc >= fDSStaticSize then begin fDSStaticSize := LongInt(X.DataDesc) + LongInt(BytesPerType[TDSType(X.TypeDesc)]); end; end; fDSStaticSize := Integer(RoundToByteSize(Word(fDSStaticSize), DWORD_LEN)); end; Result := Word(fDSStaticSize); end; function TDSData.DVArrayOffset: Word; begin Result := DopeVecs[0].offset; end; function TDSData.DynDSDefaultsOffset: Word; begin Result := Word(Length(StaticDefaults)); end; function TDSData.DynDSDefaultsSize: Word; begin Result := Word((DVArrayOffset - DSStaticSize) + (Length(DopeVecs)*SizeOf(DopeVector))); end; procedure TDSData.SaveToStream(aStream: TStream); var i, len, sBytes : integer; B : Byte; begin // dataspace table of contents for i := 0 to Length(TOC) - 1 do begin with TOC[i] do begin aStream.Write(TypeDesc, 1); aStream.Write(Flags, 1); WriteWordToStream(aStream, DataDesc); end; end; // static default data sBytes := DynDSDefaultsOffset; i := 0; len := Length(StaticDefaults); while i < sBytes do begin if i < len then B := StaticDefaults[i] else B := $FF; aStream.Write(B, SizeOf(Byte)); inc(i); end; // dynamic default data for i := 0 to Length(DynamicDefaults) - 1 do aStream.Write(DynamicDefaults[i], SizeOf(Byte)); // dope vectors for i := 0 to Length(DopeVecs) - 1 do begin with DopeVecs[i] do begin WriteWordToStream(aStream, offset); WriteWordToStream(aStream, elemsize); WriteWordToStream(aStream, count); WriteWordToStream(aStream, backptr); WriteWordToStream(aStream, link); end; end; // pad to even boundary at the end of the dataspace if needed if (sBytes mod 2) > 0 then begin B := $FF; aStream.Write(B, SizeOf(Byte)); end; end; procedure TDSData.SaveToSymbolTable(aStrings: TStrings); var i : integer; X : DSTOCEntry; begin aStrings.Add('#SYMBOLS'); aStrings.Add('Index'#9'Identifier'#9'Type'#9'Flag'#9'Data'#9'Size'#9'RefCount'); for i := 0 to DSCount - 1 do begin X := TOC[i]; aStrings.Add(Format('%d'#9'%s'#9'%d'#9'%d'#9'%d'#9'%d'#9'%d', [i, TOCNames[i], X.TypeDesc, X.Flags, X.DataDesc, X.Size, X.RefCount])); end; end; { TCodeSpaceAry } function TCodeSpaceAry.CodespaceCount: Word; begin Result := Word(Length(Code)); end; procedure TCodeSpaceAry.SaveToStream(aStream: TStream); var i : integer; begin // output code array for i := 0 to Length(Code) - 1 do begin WriteWordToStream(aStream, Code[i]); end; end; { TClumpData } procedure TClumpData.SaveToStream(aStream: TStream); var i : integer; B : byte; begin // clump records for i := 0 to Length(CRecs) - 1 do begin aStream.Write(CRecs[i].FireCount, 1); aStream.Write(CRecs[i].DependentCount, 1); WriteWordToStream(aStream, CRecs[i].CodeStart); end; // clump dependencies for i := 0 to Length(ClumpDeps) - 1 do begin aStream.Write(ClumpDeps[i], SizeOf(Byte)); end; if Length(ClumpDeps) mod 2 <> 0 then begin B := $FF; aStream.Write(B, 1); end; end; { TCardinalObject } constructor TCardinalObject.Create(aValue: Cardinal); begin fValue := aValue; end; { TIntegerObject } constructor TIntegerObject.Create(aValue: Integer); begin fValue := aValue; end; { EDuplicateDataspaceEntry } constructor EDuplicateDataspaceEntry.Create(DE : TDataspaceEntry); begin inherited Create(Format(sDuplicateDSEntry, [DE.FullPathIdentifier])); end; end.
unit K278136024; {* [RequestLink:278136024] } // Модуль: "w:\common\components\rtl\Garant\Daily\K278136024.pas" // Стереотип: "TestCase" // Элемент модели: "K278136024" MUID: (4E396B1F03D0) // Имя типа: "TK278136024" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , WikiToEVDWriterTest ; type TK278136024 = class(TWikiToEVDWriterTest) {* [RequestLink:278136024] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK278136024 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *4E396B1F03D0impl_uses* //#UC END# *4E396B1F03D0impl_uses* ; function TK278136024.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.7 Lulin'; end;//TK278136024.GetFolder function TK278136024.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '4E396B1F03D0'; end;//TK278136024.GetModelElementGUID initialization TestFramework.RegisterTest(TK278136024.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
(*--------------------------------------------------------------------------------*) (* Übung 4 ; Memory Addressing Function (MAF) for one and two-dimensional arrays *) (* Entwickler: Neuhold Michael *) (* Datum: 07.11.2018 *) (*--------------------------------------------------------------------------------*) PROGRAM OpenArray; CONST lower = 1; upper = 10; l1 = 1; u1 = 3; l2 = 1; u2 = 4; FUNCTION MAF1(startAdr: LONGINT; i, elementTypeSize: INTEGER): LONGINT; BEGIN (* IF (i < lower) OR (i > upper) THEN ... problem *) MAF1 := startAdr + (i - lower) * elementTypeSize; END; FUNCTION MAF2(startAdr: LONGINT; i, j, elementTypeSize: INTEGER): LONGINT; BEGIN (* IF (i < 11) OR (i > u1) OR (j < 12) OR (j > u2) THEN ... problem *) MAF2 := startAdr + (i - 11) * ((u2-l2+1) * elementTypeSize) + (j - 12) * elementTypeSize; (* full lines in matrix // dest. line to index *) END; VAR a: ARRAY[lower..upper] OF INTEGER; m: ARRAY[l1..u1, l2..u2] OF REAL; BEGIN WriteLn('Memory Addressing Function'); WriteLn('one dim'); (* find address of 3rd element in a *) WriteLn('start address of a is: ', LONGINT(@a)); WriteLn('address of 3rd elem in a is: ', MAF1(LONGINT(@a), 3, SizeOf(INTEGER))); // @ steht für die Adresse! WriteLn('two dim'); WriteLn('start address of a is: ', LONGINT(@m)); WriteLn('address of 3rd elem in a is: ', MAF2(LONGINT(@m), 3, 3, SizeOf(REAL))); // @ steht für die Adresse! END.
{ Subroutine SST_R_SYN_INT (SYM_P) * * Create new integer variable in the current scope. SYM_P will be returned * pointing to the symbol descriptor for the new variable. } module sst_r_syn_int; define sst_r_syn_int; %include 'sst_r_syn.ins.pas'; procedure sst_r_syn_int ( {make new interger variable} out sym_p: sst_symbol_p_t); {pointer to symbol descriptor of new var} val_param; var name: string_var32_t; {name of new variable} token: string_var16_t; {scratch token for number conversion} stat: sys_err_t; begin name.max := sizeof(name.str); {init local var strings} token.max := sizeof(token.str); string_vstring (name, 'i', 1); {set static part of variable name} string_f_int (token, seq_int); {make sequence number string} seq_int := seq_int + 1; {update sequence number to use next time} string_append (name, token); {add sequence number to variable name} sst_symbol_new_name (name, sym_p, stat); sys_error_abort (stat, '', '', nil, 0); sym_p^.symtype := sst_symtype_var_k; sym_p^.flags := [sst_symflag_def_k]; sym_p^.var_dtype_p := sym_int_p^.dtype_dtype_p; sym_p^.var_val_p := nil; sym_p^.var_arg_p := nil; sym_p^.var_proc_p := nil; sym_p^.var_com_p := nil; sym_p^.var_next_p := nil; end;
unit BaiduMapAPI.PoiSearchService.iOS; //author:Xubzhlin //Email:371889755@qq.com //百度地图API Poi搜索服务 单元 //官方链接:http://lbsyun.baidu.com/ //TiOSBaiduMapPoiSearchService 百度地图 iOS Poi搜索服务 interface uses System.Classes, System.Types, Macapi.ObjectiveC, Macapi.Helpers, iOSapi.Foundation, iOSapi.BaiduMapAPI_Search, iOSapi.BaiduMapAPI_Base, BaiduMapAPI.Search.CommTypes, BaiduMapAPI.PoiSearchService, FMX.Maps; type TiOSBaiduMapPoiSearchService = class; TBMKPoiSearchDelegate = class(TOCLocal, BMKPoiSearchDelegate) private [Weak] FPoiSearchService: TiOSBaiduMapPoiSearchService; function BMKPoiInfoToPoiInfo(Info:BMKPoiInfo):TPoiInfo; function BMKPoiAddressInfoToPoiAddrInfo(Info:BMKPoiAddressInfo):TPoiAddrInfo; function BMKCityListInfoToCityInfo(Info:BMKCityListInfo):TCityInfo; function BMKPoiIndoorInfoToPoiIndoorInfo(Info:BMKPoiIndoorInfo):TPoiIndoorInfo; public procedure onGetPoiResult(searcher: BMKPoiSearch; result: BMKPoiResult; errorCode: BMKSearchErrorCode); cdecl; procedure onGetPoiDetailResult(searcher: BMKPoiSearch; result: BMKPoiDetailResult; errorCode: BMKSearchErrorCode); cdecl; procedure onGetPoiIndoorResult(searcher: BMKPoiSearch; result: BMKPoiIndoorResult; errorCode: BMKSearchErrorCode); cdecl; constructor Create(PoiSearchService: TiOSBaiduMapPoiSearchService); end; TiOSBaiduMapPoiSearchService = class(TBaiduMapPoiSearchService) private FPoiSearch: BMKPoiSearch; FDelegate: TBMKPoiSearchDelegate; function DoBoundSearch(Option: TPoiBoundSearchOption): Boolean; function DoCitySearch(Option: TPoiCitySearchOption): Boolean; function DoNearbySearch(Option: TPoiNearbySearchOption): Boolean; protected function DoPoiSearch(Option: TPoiSearchrOption): Boolean; override; function DoSearchPoiDetail(Uid: string): Boolean; override; public constructor Create; destructor Destroy; override; end; implementation function CreatePoiType(AType:integer):TPoiType; begin //0:普通点 1:公交站 2:公交线路 3:地铁站 4:地铁线路 case AType of 0:Result:=TPoiType.POINT; 1:Result:=TPoiType.BUS_STATION; 2:Result:=TPoiType.BUS_LINE; 3:Result:=TPoiType.SUBWAY_STATION; 4:Result:=TPoiType.SUBWAY_LINE; end; end; { TBMKPoiSearchDelegate } function TBMKPoiSearchDelegate.BMKCityListInfoToCityInfo( Info: BMKCityListInfo): TCityInfo; begin Result.city:=NSStrToStr(Info.city); Result.num:=Info.num; end; function TBMKPoiSearchDelegate.BMKPoiAddressInfoToPoiAddrInfo( Info: BMKPoiAddressInfo): TPoiAddrInfo; begin Result.address:=NSStrToStr(Info.address); Result.location:=TMapCoordinate.Create(Info.pt.latitude, Info.pt.longitude); Result.name:=NSStrToStr(Info.name); end; function TBMKPoiSearchDelegate.BMKPoiIndoorInfoToPoiIndoorInfo( Info: BMKPoiIndoorInfo): TPoiIndoorInfo; begin Result.address:=NSStrToStr(Info.address); Result.bid:=NSStrToStr(Info.indoorId); Result.floor:=NSStrToStr(Info.floor); Result.name:=NSStrToStr(Info.name); Result.phone:=NSStrToStr(Info.phone); Result.price:=Info.price; Result.latLng:=TMapCoordinate.Create(Info.pt.latitude, Info.pt.longitude); Result.starLevel:=Info.starLevel; Result.isGroup:=Info.grouponFlag; Result.isTakeOut:=Info.takeoutFlag; Result.isWaited:=Info.waitedFlag; Result.uid:=NSStrToStr(Info.uid); Result.tag:=NSStrToStr(Info.tag); Result.isGroup:=Info.grouponNum<>-1; Result.groupNum:=Info.grouponNum; end; function TBMKPoiSearchDelegate.BMKPoiInfoToPoiInfo(Info: BMKPoiInfo): TPoiInfo; begin Result.name:=NSStrToStr(Info.name); Result.uid:=NSStrToStr(Info.uid); Result.address:=NSStrToStr(Info.address); Result.city:=NSStrToStr(Info.city); Result.phoneNum:=NSStrToStr(Info.phone); Result.postCode:=NSStrToStr(Info.postCode); Result.&type:=CreatePoiType(Info.epoitype); Result.location:=TMapCoordinate.Create(Info.pt.latitude, Info.pt.longitude); Result.isPano:=Info.panoFlag; end; constructor TBMKPoiSearchDelegate.Create( PoiSearchService: TiOSBaiduMapPoiSearchService); begin inherited Create; FPoiSearchService := PoiSearchService; end; procedure TBMKPoiSearchDelegate.onGetPoiDetailResult(searcher: BMKPoiSearch; result: BMKPoiDetailResult; errorCode: BMKSearchErrorCode); var DetailResult:TPoiDetailResult; begin if FPoiSearchService<>nil then begin DetailResult:=TPoiDetailResult.Create; DetailResult.error:=CreateErrorNo(errorCode); if DetailResult.error = TSearchResult_ErrorNo.NO_ERROR then begin DetailResult.name:=NSStrToStr(result.name); DetailResult.location:=TMapCoordinate.Create(result.pt.latitude, result.pt.longitude); DetailResult.address:=NSStrToStr(result.address); DetailResult.telephone:=NSStrToStr(result.phone); DetailResult.uid:=NSStrToStr(result.uid); DetailResult.tag:=NSStrToStr(result.tag); DetailResult.detailUrl:=NSStrToStr(result.DetailUrl); DetailResult.&type:= NSStrToStr(result.&type); DetailResult.price:=result.price; DetailResult.overallRating:=result.overallRating; DetailResult.tasteRating:=result.tasteRating; DetailResult.serviceRating:=result.serviceRating; DetailResult.environmentRating:=result.environmentRating; DetailResult.facilityRating:=result.facilityRating; DetailResult.hygieneRating:=result.hygieneRating; DetailResult.technologyRating:=result.technologyRating; DetailResult.imageNum:=result.imageNum; DetailResult.grouponNum:=result.grouponNum; DetailResult.commentNum:=result.commentNum; DetailResult.favoriteNum:=result.favoriteNum; DetailResult.checkinNum:=result.checkInNum; DetailResult.shopHours:=NSStrToStr(result.shopHours); end; FPoiSearchService.GetPoiDetailResult(DetailResult); end; end; procedure TBMKPoiSearchDelegate.onGetPoiIndoorResult(searcher: BMKPoiSearch; result: BMKPoiIndoorResult; errorCode: BMKSearchErrorCode); var PoiIndoorResult:TPoiIndoorResult; i:Integer; PoiIndoorInfo:BMKPoiIndoorInfo; List:NSArray; begin if FPoiSearchService <> nil then begin PoiIndoorResult:=TPoiIndoorResult.Create; PoiIndoorResult.error:=CreateErrorNo(errorCode); if PoiIndoorResult.error = TSearchResult_ErrorNo.NO_ERROR then begin List:=result.poiIndoorInfoList; for i := 0 to List.count - 1 do begin PoiIndoorInfo:=TBMKPoiIndoorInfo.Wrap(List.objectAtIndex(i)); PoiIndoorResult.PoiIndoorsInfo.Add(BMKPoiIndoorInfoToPoiIndoorInfo(PoiIndoorInfo)); end; PoiIndoorResult.CurrentPageNum:=result.pageIndex; PoiIndoorResult.CurrentPageCapacity:=result.currPoiNum; PoiIndoorResult.TotalPoiNum:=result.totalPoiNum; end; FPoiSearchService.GetPoiIndoorResult(PoiIndoorResult); end; end; procedure TBMKPoiSearchDelegate.onGetPoiResult(searcher: BMKPoiSearch; result: BMKPoiResult; errorCode: BMKSearchErrorCode); var PoiResult:TPoiResult; List:NSArray; i: Integer; PoiInfo:BMKPoiInfo; AddrInfo:BMKPoiAddressInfo; CityInfo:BMKCityListInfo ; begin if FPoiSearchService<>nil then begin PoiResult:=TPoiResult.Create; PoiResult.error:=CreateErrorNo(errorCode); case PoiResult.error of TSearchResult_ErrorNo.NO_ERROR: begin List:=result.poiInfoList; for i := 0 to List.count -1 do begin PoiInfo := TBMKPoiInfo.Wrap(List.objectAtIndex(i)); PoiResult.PoisInfo.Add(BMKPoiInfoToPoiInfo(PoiInfo)); end; if result.isHavePoiAddressInfoList then begin List:=result.poiAddressInfoList; for i := 0 to List.count-1 do begin AddrInfo:=TBMKPoiAddressInfo.Wrap(List.objectAtIndex(i)); PoiResult.PoiAddrsInfo.Add(BMKPoiAddressInfoToPoiAddrInfo(AddrInfo)); end; end; PoiResult.CurrentPageCapacity:=result.currPoiNum; PoiResult.CurrentPageNum:=result.pageIndex; PoiResult.TotalPageNum:=result.pageNum; PoiResult.TotalPoiNum:=result.totalPoiNum; PoiResult.isHasAddrInfo:=result.isHavePoiAddressInfoList; end; TSearchResult_ErrorNo.AMBIGUOUS_KEYWORD: begin List:=result.cityList; for i := 0 to List.count - 1 do begin CityInfo:=TBMKCityListInfo.Wrap(List.objectAtIndex(i)); PoiResult.CitysInfo.Add(BMKCityListInfoToCityInfo(CityInfo)); end; end; end; FPoiSearchService.GetPoiResult(PoiResult); end; end; { TiOSBaiduMapPoiSearchService } constructor TiOSBaiduMapPoiSearchService.Create; begin inherited Create; FPoiSearch := TBMKPoiSearch.Create; FDelegate := TBMKPoiSearchDelegate.Create(Self); FPoiSearch.setDelegate(FDelegate.GetObjectID); end; destructor TiOSBaiduMapPoiSearchService.Destroy; begin FPoiSearch:=nil; FDelegate.Free; inherited; end; function TiOSBaiduMapPoiSearchService.DoBoundSearch( Option: TPoiBoundSearchOption): Boolean; var SearchOption:BMKBoundSearchOption; begin SearchOption:=TBMKBoundSearchOption.Create; SearchOption.SetpageIndex(Option.PageNum); SearchOption.SetpageCapacity(Option.PageCapacity); SearchOption.setKeyword(StrToNSStr(Option.Keyword)); SearchOption.setLeftBottom(CLLocationCoordinate2D(Option.NorthEast)); SearchOption.setRightTop(CLLocationCoordinate2D(Option.SouthWest)); Result := FPoiSearch.poiSearchInbounds(SearchOption); end; function TiOSBaiduMapPoiSearchService.DoCitySearch( Option: TPoiCitySearchOption): Boolean; var SearchOption:BMKCitySearchOption; begin SearchOption:=TBMKCitySearchOption.Create; SearchOption.SetpageIndex(Option.PageNum); SearchOption.SetpageCapacity(Option.PageCapacity); SearchOption.setKeyword(StrToNSStr(Option.Keyword)); SearchOption.setCity(StrToNSStr(Option.City)); SearchOption.setRequestPoiAddressInfoList(Option.IsReturnAddr); Result := FPoiSearch.poiSearchInCity(SearchOption); end; function TiOSBaiduMapPoiSearchService.DoNearbySearch( Option: TPoiNearbySearchOption): Boolean; var SearchOption:BMKNearbySearchOption; begin SearchOption:=TBMKNearbySearchOption.Create; SearchOption.SetpageIndex(Option.PageNum); SearchOption.SetpageCapacity(Option.PageCapacity); SearchOption.setKeyword(StrToNSStr(Option.Keyword)); SearchOption.setLocation(CLLocationCoordinate2D(Option.Location)); SearchOption.setSortType(ord(Option.sortType)); SearchOption.setRadius(Option.radius); Result := FPoiSearch.poiSearchNearBy(SearchOption); end; function TiOSBaiduMapPoiSearchService.DoPoiSearch( Option: TPoiSearchrOption): Boolean; begin if Option is TPoiBoundSearchOption then begin Result := DoBoundSearch(TPoiBoundSearchOption(Option)); end else if Option is TPoiCitySearchOption then begin Result := DoCitySearch(TPoiCitySearchOption(Option)); end else if Option is TPoiNearbySearchOption then begin Result := DoNearbySearch(TPoiNearbySearchOption(Option)); end; end; function TiOSBaiduMapPoiSearchService.DoSearchPoiDetail(Uid: string): Boolean; var SearchOption: BMKPoiDetailSearchOption; begin SearchOption := TBMKPoiDetailSearchOption.Create; SearchOption.setPoiUid(StrToNSStr(Uid)); Result := FPoiSearch.poiDetailSearch(SearchOption); end; end.
{ Subroutine SST_VAR_FUNCNAME (V) * * Modify the variable descriptor V to represent a function's main symbol * instead of its return value. Nothing is done if the variable descriptor * does not already represent a function's return value "variable". } module sst_VAR_FUNCNAME; define sst_var_funcname; %include 'sst2.ins.pas'; procedure sst_var_funcname ( {change var from func return val to func name} in out v: sst_var_t); {variable descriptor to convert} begin if v.vtype <> sst_vtype_var_k then return; {not referencing a variable ?} if v.mod1.next_p <> nil then return; {compound name reference ?} if {symbol not a variable ?} v.mod1.top_sym_p^.symtype <> sst_symtype_var_k then return; if {symbol not a function return value ?} (v.mod1.top_sym_p^.var_proc_p = nil) or (v.mod1.top_sym_p^.var_arg_p <> nil) then return; { * Symbol does represent the return value "variable" of a function. } v.mod1.top_sym_p := {point to function definition symbol} v.mod1.top_sym_p^.var_proc_p^.sym_p; v.dtype_p := {var data type is data type returned by func} v.mod1.top_sym_p^.proc.dtype_func_p; v.rwflag := [sst_rwflag_read_k]; {function value is read-only} v.vtype := sst_vtype_rout_k; {var descriptor now represents a routine} v.rout_proc_p := {point to routine template descriptor} addr(v.mod1.top_sym_p^.proc); end;
unit utils_zs_login; interface uses windows, Graphics, Sysutils, define_zsprocess; function FindZSLoginWnd(AZsProcess: PZsProcess; AWndLogin: PZsWndLogin): Boolean; procedure ClickLoginButton(AWndLogin: PZsWndLogin); function CheckZSLoginWndUIElement(ALoginWnd: PZsWndLogin): Boolean; function InputUserLoginInfo(AZsProcess: PZsProcess; AWndLogin: PZsWndLogin; APassword: Integer): Boolean; function AutoLogin(AZsProcess: PZsProcess; AWndLogin: PZsWndLogin; APassword: Integer): Boolean; function EnsureAppLoginStatus(AZsProcess: PZsProcess; AMainWnd: PZsWndMain): Boolean; implementation uses UtilsWindows, utils_findwnd, utils_zsprocess, utils_zs_dialog, utils_zs_main, utils_zs_login_verifycode; function FuncCheckLoginWnd(AWnd: HWND; AFind: PZsExWindowEnumFind): Boolean; var tmpChildWnd: HWND; begin Result := true; tmpChildWnd := Windows.GetWindow(AWnd, GW_CHILD); if 0 = tmpChildWnd then begin Result := false; end; end; function FindZSLoginWnd(AZsProcess: PZsProcess; AWndLogin: PZsWndLogin): Boolean; var tmpFind: TZsExWindowEnumFind; //tmpWndLogin: TZsWndLogin; begin FillChar(tmpFind, SizeOf(tmpFind), 0); tmpFind.NeedWinCount := 1; tmpFind.WndClassKey := '#32770'; tmpFind.WndCaptionKey := '招商证券智远理财服务平台'; tmpFind.CheckWndFunc := FuncCheckLoginWnd; Windows.EnumWindows(@ZsEnumFindDesktopWindowProc, Integer(@tmpFind)); Result := tmpFind.FindCount > 0; if Result then begin if nil <> AWndLogin then begin AWndLogin.Core.WindowHandle := tmpFind.FindWindow[0]; end; end; end; type PTraverse_LoginWindow = ^TTraverse_LoginWindow; TTraverse_LoginWindow = record LoginWindow: PZsWndLogin; end; procedure TraverseCheckChildWindowA(AWnd: HWND; ATraverseWindow: PTraverse_LoginWindow); var tmpChildWnd: HWND; tmpStr: string; tmpCtrlId: integer; tmpRect: TRect; tmpIsHandled: Boolean; begin tmpChildWnd := Windows.GetWindow(AWnd, GW_CHILD); while 0 <> tmpChildWnd do begin tmpStr := GetWndClassName(tmpChildWnd); tmpIsHandled := False; tmpCtrlId := Windows.GetDlgCtrlID(tmpChildWnd); if SameText('SafeEdit', tmpStr) then begin if tmpCtrlId = $ED then begin tmpIsHandled := true; ATraverseWindow.LoginWindow.WndVerifyCodeEdit := tmpChildWnd; Windows.GetWindowRect(ATraverseWindow.LoginWindow.WndVerifyCodeEdit, tmpRect); if 0 < tmpRect.Left then begin end; end; end; if not tmpIsHandled then begin if SameText('Edit', tmpStr) then begin if tmpCtrlId = $EC then begin tmpIsHandled := true; ATraverseWindow.LoginWindow.WndPasswordEdit := tmpChildWnd; end; if tmpCtrlId = $3E9 then begin tmpIsHandled := true; ATraverseWindow.LoginWindow.WndAccountEdit := tmpChildWnd; end; end; end; if not tmpIsHandled then begin if tmpCtrlId = 1 then begin tmpIsHandled := true; ATraverseWindow.LoginWindow.WndLoginButton := tmpChildWnd; end; end; if not tmpIsHandled then begin end; TraverseCheckChildWindowA(tmpChildWnd, ATraverseWindow); tmpChildWnd := Windows.GetWindow(tmpChildWnd, GW_HWNDNEXT); end; end; function CheckZSLoginWndUIElement(ALoginWnd: PZsWndLogin): Boolean; var tmpTraverse_Window: TTraverse_LoginWindow; begin Result := false; if nil = ALoginWnd then exit; if IsWindow(ALoginWnd.WndVerifyCodeEdit) then begin exit; end; FillChar(tmpTraverse_Window, SizeOf(tmpTraverse_Window), 0); tmpTraverse_Window.LoginWindow := ALoginWnd; TraverseCheckChildWindowA(ALoginWnd.Core.WindowHandle, @tmpTraverse_Window); Result := IsWindow(ALoginWnd.WndVerifyCodeEdit); end; procedure InputLoginAccount(AWndLogin: PZsWndLogin; Account: AnsiString); var tmpAccount: AnsiString; i: integer; tmpKeyCode: Byte; begin if nil = AWndLogin then exit; if '' = Account then exit; if IsWindow(AWndLogin.WndAccountEdit) then begin ForceBringFrontWindow(AWndLogin.WndAccountEdit); for i := 1 to 10 do begin SimulateKeyPress(VK_BACK, 20); SimulateKeyPress(VK_DELETE, 20); end; tmpAccount := UpperCase(Account); for i := 1 to Length(tmpAccount) do begin tmpKeyCode := Byte(tmpAccount[i]); SimulateKeyPress(tmpKeyCode, 20); end; SimulateKeyPress(VK_RETURN, 20); SimulateKeyPress(VK_TAB, 20); end; end; procedure InputLoginPassword(AZsProcess: PZsProcess; AWndLogin: PZsWndLogin; APassword: AnsiString); procedure DoInputPassword; var tmpKeyCode: Byte; i: integer; tmpPassword: AnsiString; begin for i := 1 to 8 do begin Windows.keybd_event(VK_BACK, MapVirtualKey(VK_BACK, 0), 0, 0) ;//#a键位码是86 SleepWait(10); Windows.keybd_event(VK_BACK, MapVirtualKey(VK_BACK, 0), KEYEVENTF_KEYUP, 0); SleepWait(10); SleepWait(10); Windows.keybd_event(VK_DELETE, MapVirtualKey(VK_DELETE, 0), 0, 0) ;//#a键位码是86 SleepWait(10); Windows.keybd_event(VK_DELETE, MapVirtualKey(VK_DELETE, 0), KEYEVENTF_KEYUP, 0); SleepWait(10); SleepWait(10); end; tmpPassword := UpperCase(APassword); for i := 1 to Length(tmpPassword) do begin tmpKeyCode := Byte(tmpPassword[i]); Windows.keybd_event(tmpKeyCode, MapVirtualKey(tmpKeyCode, 0), 0, 0) ;//#a键位码是86 SleepWait(10); Windows.keybd_event(tmpKeyCode, MapVirtualKey(tmpKeyCode, 0), KEYEVENTF_KEYUP, 0); SleepWait(10); SleepWait(10); end; Windows.keybd_event(VK_RETURN, MapVirtualKey(VK_RETURN, 0), 0, 0) ;//#a键位码是86 SleepWait(10); Windows.keybd_event(VK_RETURN, MapVirtualKey(VK_RETURN, 0), KEYEVENTF_KEYUP, 0); SleepWait(10); SleepWait(10); Windows.keybd_event(VK_TAB, MapVirtualKey(VK_TAB, 0), 0, 0) ;//#a键位码是86 SleepWait(10); Windows.keybd_event(VK_TAB, MapVirtualKey(VK_TAB, 0), KEYEVENTF_KEYUP, 0); SleepWait(10); SleepWait(10); end; var i: integer; processid: DWORD; tmpRect: TRect; begin if nil = AWndLogin then exit; if '' = APassword then exit; if IsWindow(AWndLogin.WndPasswordEdit) then begin GetWindowThreadProcessId(AWndLogin.WndPasswordEdit, processid); if 0 <> processid then begin if AttachThreadInput(processid, GetCurrentThreadId(), TRUE) then begin try for i := 0 to 1 do begin if Windows.GetFocus <> AWndLogin.WndPasswordEdit then begin SetFocus(AWndLogin.WndPasswordEdit); end; SleepWait(10); end; if Windows.GetFocus <> AWndLogin.WndPasswordEdit then begin SleepWait(10); exit; end; DoInputPassword; finally AttachThreadInput(processid, GetCurrentThreadId(), FALSE); end; end else begin GetWindowRect(AWndLogin.WndPasswordEdit, tmpRect); Windows.SetCursorPos((tmpRect.Left + tmpRect.Right) div 2, (tmpRect.Top + tmpRect.Bottom) div 2); SleepWait(20); Windows.mouse_event(MOUSEEVENTF_LEFTDOWN or MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); SleepWait(300); CloseZsDialog(AZsProcess, @AWndLogin.Core); DoInputPassword; end; end; end; end; procedure InputLoginVerifyCode(AWndLogin: PZsWndLogin; AVerifyCode: AnsiString); var tmpVerifyCode: AnsiString; tmpKeyCode: Byte; i: integer; begin if nil = AWndLogin then exit; if '' = AVerifyCode then exit; if IsWindow(AWndLogin.WndVerifyCodeEdit) then begin ForceBringFrontWindow(AWndLogin.WndVerifyCodeEdit); for i := 1 to 4 do begin SimulateKeyPress(VK_BACK, 20); SimulateKeyPress(VK_DELETE, 20); end; tmpVerifyCode := UpperCase(AVerifyCode); for i := 1 to Length(tmpVerifyCode) do begin tmpKeyCode := Byte(tmpVerifyCode[i]); SimulateKeyPress(tmpKeyCode, 20); end; end; end; function getLoginVerifyCodeBmp(AWndLogin: PZsWndLogin; ALeft, ATop, AWidth, AHeight: integer): Graphics.TBitmap; const CAPTUREBLT = $40000000; var tmpWnd: HWND; tmpForegroundWnd: HWND; tmpProcessID: DWORD; tmpWinRect: TRect; tmpMemDC: HDC; tmpDC: HDC; tmpMemBmp: HBITMAP; tmpOldBmp: HBITMAP; begin Result := nil; tmpWnd := AWndLogin.Core.WindowHandle; if IsWindow(tmpWnd) and IsWindowVisible(tmpWnd) then begin tmpForegroundWnd := GetForegroundWindow; GetWindowThreadProcessId(tmpForegroundWnd, tmpProcessID); AttachThreadInput(tmpProcessID, GetCurrentThreadId(), TRUE); if Windows.GetForegroundWindow <> tmpWnd then SetForegroundWindow(tmpWnd); if Windows.GetFocus <> tmpWnd then SetFocus(tmpWnd); AttachThreadInput(tmpProcessID, GetCurrentThreadId(), FALSE); ForceBringFrontWindow(tmpWnd); Windows.GetWindowRect(tmpWnd, tmpWinRect); Result := Graphics.TBitmap.Create; Result.PixelFormat := pf32bit; //tmpVerifyCodeBmp.Width := tmpWinRect.Right - tmpWinRect.Left; //tmpVerifyCodeBmp.Height := tmpWinRect.Bottom - tmpWinRect.Top; Result.Width := AWidth; //52; Result.Height := AHeight; //21; //tmpDC := Windows.GetDC(tmpWnd); tmpDC := Windows.GetDC(0); try tmpMemDC := Windows.CreateCompatibleDC(tmpDC); tmpMemBmp := Windows.CreateCompatibleBitmap(tmpDC, Result.Width, Result.Height); tmpOldBmp := Windows.SelectObject(tmpMemDC, tmpMemBmp); try Windows.BitBlt(tmpMemDC, 0, 0, //tmpWinRect.Top, //Windows.BitBlt(tmpVerifyCodeBmp.Canvas.Handle, 0, 0, Result.Width, Result.Height, tmpDC, tmpWinRect.Left + ALeft, //0, tmpWinRect.Top + ATop, //0, SRCCOPY or CAPTUREBLT); Windows.BitBlt(Result.Canvas.Handle, 0, 0, //Windows.BitBlt(tmpVerifyCodeBmp.Canvas.Handle, 0, 0, Result.Width, Result.Height, tmpMemDC, 0, 0, SRCCOPY); finally Windows.SelectObject(tmpMemDC, tmpOldBmp); Windows.DeleteDC(tmpMemDC); Windows.DeleteObject(tmpMemBmp); end; finally Windows.ReleaseDC(tmpWnd, tmpDC); end; end; end; function getLoginVerifyCode(AWndLogin: PZsWndLogin): AnsiString; var tmpVerifyCodeBmp: Graphics.TBitmap; begin Result := ''; tmpVerifyCodeBmp := getLoginVerifyCodeBmp(AWndLogin, 447, 241, 52, 21); if nil = tmpVerifyCodeBmp then exit; try Result := GetVerifyCode(tmpVerifyCodeBmp); finally tmpVerifyCodeBmp.Free; end; end; procedure ClickLoginButton(AWndLogin: PZsWndLogin); var tmpRect: TRect; begin if IsWindow(AWndLogin.WndLoginButton) then begin GetWindowRect(AWndLogin.WndLoginButton, tmpRect); Windows.SetCursorPos(tmpRect.Left + 10, tmpRect.Top + 10); Windows.mouse_event(MOUSEEVENTF_LEFTDOWN or MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); SleepWait(20); end; end; function InputUserLoginInfo(AZsProcess: PZsProcess; AWndLogin: PZsWndLogin; APassword: Integer): Boolean; var i: integer; tmpAnsi: AnsiString; begin Result := false; if nil = AWndLogin then exit; for i := 1 to 5 do begin if CheckZSLoginWndUIElement(AWndLogin) then Break; Sleep(100); end; if not IsWindow(AWndLogin.WndAccountEdit) then exit; for i := 1 to 2 do begin ForceBringFrontWindow(AWndLogin.Core.WindowHandle); SleepWait(50); end; CloseZsDialog(AZsProcess, @AWndLogin.Core); if IsWindowEnabled(AWndLogin.WndAccountEdit) then begin //=========================== InputLoginAccount(AWndLogin, inttostr(AZsProcess.LoginAccountId)); SleepWait(200); //=========================== tmpAnsi := getLoginVerifyCode(AWndLogin); if '' <> tmpAnsi then begin InputLoginVerifyCode(AWndLogin, tmpAnsi); end; SleepWait(200); //=========================== tmpAnsi := inttostr(APassword); tmpAnsi := Copy('000000', 1, 6 - length(tmpAnsi)) + tmpAnsi; InputLoginPassword(AZsProcess, AWndLogin, tmpAnsi); SleepWait(200); //=========================== Result := True; end; end; function AutoLogin(AZsProcess: PZsProcess; AWndLogin: PZsWndLogin; APassword: Integer): Boolean; begin Result := InputUserLoginInfo(AZsProcess, AWndLogin, APassword); if Result then begin ClickLoginButton(AWndLogin); end; end; //function InputUserLoginInfo(AZsProcess: PZsProcess; ALoginWnd: PZsWndLogin): Boolean; //begin // Result := AutoLogin(AZsProcess, ALoginWnd, 1808175166, 12177); //end; procedure DoLoginInMainWnd(AZsProcess: PZsProcess; AMainWnd: PZsWndMain); forward; function EnsureAppLoginStatus(AZsProcess: PZsProcess; AMainWnd: PZsWndMain): Boolean; var tmpLoginWnd: TZsWndLogin; tmpCounter: integer; tmpIsLoginMode: integer; i: integer; begin Result := false; if nil = AMainWnd then begin exit; end; if (0 = AZsProcess.Process.Core.ProcessId) then begin LaunchZSProgram(AZsProcess); end else begin if not IsWindow(AMainWnd.Core.WindowHandle) then begin if FindZSMainWnd(AZsProcess, AMainWnd) then begin TraverseCheckMainChildWindowA(AMainWnd.Core.WindowHandle, AMainWnd); end; end; Result := IsWindow(AMainWnd.WndFunctionTree); if Result then begin exit; end; end; tmpCounter := 0; tmpIsLoginMode := 0; SleepWait(200); FillChar(tmpLoginWnd, SizeOf(tmpLoginWnd), 0); FindZSLoginWnd(AZsProcess, @tmpLoginWnd); while not IsWindow(AMainWnd.Core.WindowHandle) do begin if 0 = tmpLoginWnd.Core.WindowHandle then begin FindZSLoginWnd(AZsProcess, @tmpLoginWnd); tmpCounter := tmpCounter + 1; if 0 = tmpLoginWnd.Core.WindowHandle then begin SleepWait(10); if 1000 < tmpCounter then Break; Continue; end; end; if not IsWindow(tmpLoginWnd.WndAccountEdit) then begin CheckZSLoginWndUIElement(@tmpLoginWnd); end; if IsWindow(tmpLoginWnd.WndAccountEdit) then begin if IsWindowEnabled(tmpLoginWnd.WndAccountEdit) then begin tmpIsLoginMode := 1; //InputUserLoginInfo(AZsProcess, @tmpLoginWnd); AutoLogin(AZsProcess, @tmpLoginWnd, 12177); end else begin tmpIsLoginMode := 2; if IsWindow(tmpLoginWnd.WndLoginButton) then begin ForceBringFrontWindow(tmpLoginWnd.Core.WindowHandle); SleepWait(100); ClickLoginButton(@tmpLoginWnd); SleepWait(100); end; end; end; FindZSMainWnd(AZsProcess, AMainWnd); SleepWait(10); tmpCounter := tmpCounter + 1; if 1000 < tmpCounter then Break; end; case tmpIsLoginMode of 0: begin if IsWindow(AMainWnd.Core.WindowHandle) then begin ForceBringFrontWindow(AMainWnd.Core.WindowHandle); Sleep(100); i := 0; while CloseZsDialog(AZsProcess, @tmpLoginWnd.Core) do begin Sleep(100); Inc(i); if 10 < i then Break; end; DoLoginInMainWnd(AZsProcess, AMainWnd); end; end; 1: begin end; 2: begin // 等待主窗体出现 关闭对话框 SleepWait(1000); i := 0; while CloseZsDialog(AZsProcess, 0) do begin Sleep(100); Inc(i); if 10 < i then Break; end; DoLoginInMainWnd(AZsProcess, AMainWnd); end; end; Result := IsWindow(AMainWnd.WndFunctionTree); end; procedure DoLoginInMainWnd(AZsProcess: PZsProcess; AMainWnd: PZsWndMain); var tmpLoginWnd: TZsWndLogin; i: integer; begin if not IsWindow(AMainWnd.WndMenuOrderButton) then begin TraverseCheckMainChildWindowA(AMainWnd.Core.WindowHandle, AMainWnd); end; if IsWindow(AMainWnd.WndMenuOrderButton) then begin // 点击 交易 Menu 菜单 ClickButtonWnd(AMainWnd.WndMenuOrderButton); Sleep(100); FillChar(tmpLoginWnd, SizeOf(tmpLoginWnd), 0); for i := 1 to 20 do begin FindZSLoginWnd(AZsProcess, @tmpLoginWnd); if IsWindow(tmpLoginWnd.Core.WindowHandle) then Break; Sleep(100); end; //InputUserLoginInfo(AZsProcess, @tmpLoginWnd); AutoLogin(AZsProcess, @tmpLoginWnd, 12177); Sleep(100); for i := 1 to 20 do begin if IsWindow(AMainWnd.WndFunctionTree) then begin Break; end else begin if IsWindow(AMainWnd.Core.WindowHandle) then begin TraverseCheckMainChildWindowA(AMainWnd.Core.WindowHandle, AMainWnd); end; end; SleepWait(100); end; SleepWait(1000); i := 0; while CloseZsDialog(AZsProcess, 0) do begin Sleep(100); Inc(i); if 10 < i then Break; end; end; end; end.
unit HotelUnit; interface //hotel record type hotel = record name : string; id : integer; distance : integer; //Distanz zum nächsten Hotel end; type HotelFileType = File of hotel; type HotelArrayType = array of Hotel; function loadHotelsFromeFile(path : string) : HotelArrayType; procedure saveHotelsToFile(path : string; var ar : HotelArrayType); procedure showHotelListe(var ar : HotelArrayType); function getHotelFrom(var ar : HotelArrayType) : integer; implementation function loadHotelsFromeFile(path : string) : HotelArrayType; var hotelArray : HotelArrayType; var hotelFile : HotelFileType; begin assign(hotelFile, path); reset(hotelFile); setLength(hotelArray, 1); while not eof(hotelFile) do begin read(hotelFile, hotelArray[Length(hotelArray) - 1]); setLength(hotelArray, Length(hotelArray) + 1); end; setLength(HotelArray, Length(hotelArray) - 1); close(hotelFile); loadHotelsFromeFile := hotelArray; end; procedure saveHotelsToFile(path : string; var ar : HotelArrayType); var i : integer; var hotelFile : HotelFileType; begin assign(hotelFile, path); rewrite(hotelFile); for i := low(ar) to high(ar) do write(hotelFile, ar[i]); close(hotelFile); end; procedure showHotelListe(var ar : HotelArrayType); var i : integer; begin for i := low(ar) to high(ar) do write('--', ar[i].name, '[', i, ']', '--', ar[i].distance, 'km'); writeln(); end; function getHotelFrom(var ar : HotelArrayType):integer; var correct : boolean; index, i : integer; input : string; begin correct := false; repeat readln(input); for i := 0 to 4 do begin if (ar[i].name = input) then begin index := i; correct := true; end; end; if (correct = false) then begin writeln('Hotel nicht gefunden'); getHotelFrom := -1; end; until (correct); getHotelFrom := index; end; end.
unit vtGrids; {$I vtDefine.inc } interface uses Messages, Windows, SysUtils, Classes, Graphics, Menus, Controls, Forms, StdCtrls, Mask, Grids; Type TGetCellEvent = procedure (Sender: TObject; ACol, ARow: Longint; var Value: PChar) of object; TSetCellEvent = procedure (Sender: TObject; ACol, ARow: Longint; Value: PChar) of object; TvtCustomStringGrid = class(TCustomGrid) private fRenumCol : array of integer; //procedure DisableEditUpdate; //procedure EnableEditUpdate; //procedure Update(ACol, ARow: Integer); reintroduce; //procedure SetUpdateState(Updating: Boolean); //FOnColumnMoved: TMovedEvent; FOnDrawCell: TDrawCellEvent; //FOnGetEditMask: TGetEditEvent; FOnGetCellText: TGetCellEvent; FOnSetCellText: TSetCellEvent; //FOnRowMoved: TMovedEvent; //FOnSelectCell: TSelectCellEvent; //FOnSetEditText: TSetEditEvent; //FOnTopLeftChanged: TNotifyEvent; procedure SizeChanged(OldColCount, OldRowCount: Longint); override; protected procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override; procedure ColumnMoved(FromIndex, ToIndex: Longint); override; procedure RowMoved(FromIndex, ToIndex: Longint); override; function GetEditMask(ACol, ARow: Longint): string; override; function GetCellText(ACol, ARow: Longint): PChar; procedure SetCellText(ACol, ARow: Longint; Value: PChar); function GetEditText(ACol, ARow: Longint): string; override; procedure SetEditText(ACol, ARow: Longint; const Value: string); override; function SelectCell(ACol, ARow: Longint): Boolean; override; procedure TopLeftChanged; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; //function CellRect(ACol, ARow: Longint): TRect; procedure MouseToCell(X, Y: Integer; var ACol, ARow: Longint); end; TvtStringGrid = class(TvtCustomStringGrid) public property Canvas; property Col; property ColWidths; property EditorMode; property GridHeight; property GridWidth; property LeftCol; property Selection; property Row; property RowHeights; property TabStops; property TopRow; published //property OnColumnMoved: TMovedEvent read FOnColumnMoved write FOnColumnMoved; property OnDrawCell: TDrawCellEvent read FOnDrawCell write FOnDrawCell; //property OnGetEditMask: TGetEditEvent read FOnGetEditMask write FOnGetEditMask; property OnGetCellText: TGetCellEvent read FOnGetCellText write FOnGetCellText; property OnSetCellText: TSetCellEvent read FOnSetCellText write FOnSetCellText; //property OnRowMoved: TMovedEvent read FOnRowMoved write FOnRowMoved; //property OnSelectCell: TSelectCellEvent read FOnSelectCell write FOnSelectCell; //property OnTopLeftChanged: TNotifyEvent read FOnTopLeftChanged write FOnTopLeftChanged; property Align; property Anchors; property BiDiMode; property BorderStyle; property Color; property ColCount; property Constraints; property Ctl3D; property DefaultColWidth; property DefaultRowHeight; property DefaultDrawing; property DragCursor; property DragKind; property DragMode; property Enabled; property FixedColor; property FixedCols; property RowCount; property FixedRows; property Font; property GridLineWidth; property Options; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ScrollBars; property ShowHint; property TabOrder; property TabStop; property Visible; property VisibleColCount; property VisibleRowCount; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheelDown; property OnMouseWheelUp; property OnStartDock; property OnStartDrag; end; implementation {TvtCustomStringGrid} constructor TvtCustomStringGrid.Create(AOwner: TComponent); begin inherited Create(AOwner); SizeChanged(ColCount, RowCount); end; destructor TvtCustomStringGrid.Destroy; begin inherited Destroy; end; procedure TvtCustomStringGrid.MouseToCell(X, Y: Integer; var ACol, ARow: Longint); var Coord: TGridCoord; begin Coord := MouseCoord(X, Y); ACol := Coord.X; ARow := Coord.Y; end; procedure TvtCustomStringGrid.SizeChanged(OldColCount, OldRowCount: Longint); var I : Integer; begin If (High(fRenumCol) = Pred(ColCount)) then Exit; If ColCount > 0 then begin SetLength(fRenumCol, ColCount); For I := 0 to Pred(ColCount) do fRenumCol[I] := I; end else fRenumCol := nil; end; procedure TvtCustomStringGrid.ColumnMoved(FromIndex, ToIndex: Longint); var lSave : Integer; begin lSave := fRenumCol[FromIndex]; fRenumCol[FromIndex] := fRenumCol[ToIndex]; fRenumCol[ToIndex] := lSave; end; procedure TvtCustomStringGrid.RowMoved(FromIndex, ToIndex: Longint); begin //if Assigned(FOnRowMoved) then FOnRowMoved(Self, FromIndex, ToIndex); end; function TvtCustomStringGrid.GetEditMask(ACol, ARow: Longint): string; begin Result := ''; //if Assigned(FOnGetEditMask) then FOnGetEditMask(Self, ACol, ARow, Result); end; function TvtCustomStringGrid.GetCellText(ACol, ARow: Longint): PChar; begin Result := ''; if Assigned(FOnGetCellText) then FOnGetCellText(Self, fRenumCol[ACol], ARow, Result); end; procedure TvtCustomStringGrid.SetCellText(ACol, ARow: Longint; Value: PChar); begin if Assigned(FOnSetCellText) then FOnSetCellText(Self, ACol, ARow, Value); end; function TvtCustomStringGrid.GetEditText(ACol, ARow: Longint): string; begin Result := StrPas(GetCellText(ACol, ARow)); end; procedure TvtCustomStringGrid.SetEditText(ACol, ARow: Longint; const Value: string); begin SetCellText(ACol, ARow, PChar(Value)); end; {begin DisableEditUpdate; try if Value <> Cells[ACol, ARow] then Cells[ACol, ARow] := Value; finally EnableEditUpdate; end; inherited SetEditText(ACol, ARow, Value); end; } function TvtCustomStringGrid.SelectCell(ACol, ARow: Longint): Boolean; begin Result := True; //if Assigned(FOnSelectCell) then FOnSelectCell(Self, ACol, ARow, Result); end; procedure TvtCustomStringGrid.DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); var Hold: Integer; begin If DefaultDrawing then Canvas.TextRect(ARect, ARect.Left+2, ARect.Top+2, StrPas(GetCellText(ACol, ARow))) else begin if Assigned(FOnDrawCell) then begin if UseRightToLeftAlignment then begin ARect.Left := ClientWidth - ARect.Left; ARect.Right := ClientWidth - ARect.Right; Hold := ARect.Left; ARect.Left := ARect.Right; ARect.Right := Hold; //ChangeGridOrientation(False); end; FOnDrawCell(Self, ACol, ARow, ARect, AState); //if UseRightToLeftAlignment then ChangeGridOrientation(True); end; end; end; procedure TvtCustomStringGrid.TopLeftChanged; begin inherited TopLeftChanged; //if Assigned(FOnTopLeftChanged) then FOnTopLeftChanged(Self); end; {procedure TvtCustomStringGrid.DisableEditUpdate; begin Inc(FEditUpdate); end; procedure TvtCustomStringGrid.EnableEditUpdate; begin Dec(FEditUpdate); end; } {procedure TvtCustomStringGrid.SetUpdateState(Updating: Boolean); begin FUpdating := Updating; if not Updating and FNeedsUpdating then begin InvalidateGrid; FNeedsUpdating := False; end; end; procedure TvtCustomStringGrid.Update(ACol, ARow: Integer); begin if not FUpdating then InvalidateCell(ACol, ARow) else FNeedsUpdating := True; if (ACol = Col) and (ARow = Row) and (FEditUpdate = 0) then InvalidateEditor; end; } end.