text
stringlengths
14
6.51M
unit BankAccount; interface uses Bank; type TBankAccount = class(TObject) private FBank: TBank; FAccountNo: string; FCardNo: string; FCardExpiry: TDate; public property Bank: TBank read FBank write FBank; property AccountNo: string read FAccountNo write FAccountNo; property CardNo: string read FCardNo write FCardNo; property CardExpiry: TDate read FCardExpiry write FCardExpiry; constructor Create; overload; constructor Create(const bk: TBank; const acctNo, cardNo: string; const cardExp: TDate); overload; end; var bnkAcct: TBankAccount; implementation constructor TBankAccount.Create; begin inherited; end; constructor TBankAccount.Create(const bk: TBank; const acctNo, cardNo: string; const cardExp: TDate); begin FBank := bk; FAccountNo := acctNo; FCardNo := cardNo; FCardExpiry := cardExp; end; end.
{********************************************} { TeeChart Pro Charting Library } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {********************************************} unit TeeTransposeTool; {$I TeeDefs.inc} interface uses {$IFDEF CLR} Classes, StdCtrls, Forms, {$ELSE} {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, {$ENDIF} {$ENDIF} TeEngine, TeeSurfa, TeCanvas; type TGridTransposeTool=class(TTeeCustomTool) private FSeries : TCustom3DGridSeries; protected class Function GetEditorClass:String; override; public class Function Description:String; override; procedure Transpose; published property Active; property Series:TCustom3DGridSeries read FSeries write FSeries; end; TGridTransposeToolEdit = class(TForm) Label1: TLabel; CBSeries: TComboFlat; BTranspose: TButton; procedure CBSeriesChange(Sender: TObject); procedure BTransposeClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } Tool : TGridTransposeTool; public { Public declarations } end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} uses Chart, TeeProCo; { TGridTransposeTool } class function TGridTransposeTool.Description: String; begin result:=TeeMsg_GridTranspose; end; class function TGridTransposeTool.GetEditorClass: String; begin result:='TGridTransposeToolEdit'; { the editor dialog class name } end; procedure TGridTransposeTool.Transpose; var t : Integer; tmp : TCustom3DGridSeries; begin if Active and Assigned(FSeries) then begin tmp:=TCustom3DGridSeries.Create(nil); try with FSeries do for t:=0 to Count-1 do tmp.AddXYZ(ZValues.Value[t],YValues.Value[t],XValues.Value[t]); FSeries.AssignValues(tmp); finally tmp.Free; end; end; end; { register both the tool and the tool editor dialog form } procedure TGridTransposeToolEdit.CBSeriesChange(Sender: TObject); begin with CBSeries do Tool.Series:=TCustom3DGridSeries(Items.Objects[ItemIndex]); BTranspose.Enabled:=True; end; procedure TGridTransposeToolEdit.BTransposeClick(Sender: TObject); begin Tool.Transpose; end; procedure TGridTransposeToolEdit.FormShow(Sender: TObject); var tmp : TChartSeriesList; t : Integer; begin {$IFNDEF CLR} Tool:=TGridTransposeTool(Tag); {$ENDIF} if Assigned(Tool) and Assigned(Tool.ParentChart) then begin tmp:=Tool.ParentChart.SeriesList; with CBSeries do begin Items.Clear; for t:=0 to tmp.Count-1 do if tmp[t] is TCustom3DGridSeries then Items.AddObject(SeriesTitleOrName(tmp[t]),tmp[t]); ItemIndex:=Items.IndexOfObject(Tool.Series); BTranspose.Enabled:=ItemIndex<>-1; end; end; end; initialization RegisterClass(TGridTransposeToolEdit); RegisterTeeTools([TGridTransposeTool]); finalization { un-register the tool } UnRegisterTeeTools([TGridTransposeTool]); end.
unit func_ccreg_set24; interface implementation type TEnum24 = (_a00,_a01,_a02,_a03,_a04,_a05,_a06,_a07,_a08,_a09,_a10,_a11,_a12,_a13,_a14,_a15,_a16,_a17,_a18,_a19,_a20,_a21,_a22,_a23); TSet24 = packed set of TEnum24; function F(a: TSet24): TSet24; external 'CAT' name 'func_ccreg_set24'; var a, r: TSet24; procedure Test; begin a := [_a01]; r := F(a); Assert(a = r); end; initialization Test(); finalization end.
unit uGMV_DLLCommon; { ================================================================================ * * Application: Vitals * Revision: $Revision: 1 $ $Modtime: 1/16/09 2:17p $ * Developer: dddddddddomain.user@domain.ext * Site: Hines OIFO * * Description: Common DLL handling functions. * * Notes: * ================================================================================ * $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSUTILS/uGMV_DLLCommon.pas $ * * $History: uGMV_DLLCommon.pas $ * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 8/12/09 Time: 8:29a * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSUTILS * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 3/09/09 Time: 3:39p * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSUTILS * * ***************** Version 2 ***************** * User: Zzzzzzandria Date: 1/20/09 Time: 3:42p * Updated in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSUTILS * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 1/13/09 Time: 1:26p * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSUTILS * * ***************** Version 2 ***************** * User: Zzzzzzandria Date: 7/17/07 Time: 2:30p * Updated in $/Vitals GUI 2007/Vitals-5-0-18/VITALSUTILS * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/14/07 Time: 10:30a * Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSUTILS * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/16/06 Time: 5:44p * Created in $/Vitals/VITALS-5-0-18/VitalsUtils * GUI v. 5.0.18 updates the default vital type IENs with the local * values. * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/16/06 Time: 5:33p * Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsUtils * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 1/25/06 Time: 8:57a * Created in $/Vitals/Vitals 5.0.3/DLL-Common * 060125 test * ================================================================================ } interface uses Forms,Windows,Dialogs; procedure FindModule(const aLibrary: String; const aModule:String;var H:THandle;var P: Pointer); function RunDLLDialog(aLibrary,aFunction:String): Integer; implementation // Note: Don't forget to free memory if H is not 0! procedure FindModule(const aLibrary: String; const aModule:String;var H:THandle;var P: Pointer); var DLLHandle: THandle; begin P := nil; try DLLHandle := LoadLibrary(PChar(aLibrary)); if DLLHandle <> 0 then begin H := DLLHandle; P := nil; P := GetProcAddress(DLLHandle,PChar(aModule)); {$IFNDEF USEVSMONITOR} if not Assigned(P) then ShowMessage('Error: Failure loaging function <'+aModule+'>'); end else ShowMessage('Error: Failure loaging library <'+PChar(aLibrary)+'>'); {$ELSE} end {$ENDIF} except H := 0; P := nil; end; end; function RunDLLDialog(aLibrary,aFunction:String): Integer; type TFuncSign = function:Integer; var FuncSign : TFuncSign; DLLHandle : THandle; P: Pointer; i: Integer; begin i := -1; FindModule(aLibrary,aFunction,DLLHandle,P); if Assigned(P) then begin @FuncSign := P; i := FuncSign; end; @FuncSign := nil; FreeLibrary(DLLHandle); Result := i; end; end.
unit ORRadioCheck; interface uses Windows, Classes, SysUtils, ComCtrls, ExtCtrls, StdCtrls, Controls, Graphics, Messages, ORStaticText; const OR_DEFAULT_SPACING = 3; DEFAULT_ICON_SIZE = 17; // default size DEFAULT_MAX_WIDTH = 0; type TORRadioCheck = class(TPanel) private fCheck: TCheckbox; fRadio: TRadioButton; fSingleLine: boolean; fFocusOnBox: boolean; fGrayedToChecked: boolean; fAllowAllUnchecked: boolean; fAssociate: TControl; fSpacing: integer; fUseRadioStyle: boolean; fPreDelimiter: TSysCharSet; fPostDelimiter: TSysCharSet; IconSize: integer; FontHeight: integer; fLines: TStrings; // property holder for Lines fDisplayed: TStringList; fTransparent: boolean; // property holder for Transparent fVerticalSpace: integer; // property holder for VerticalSpace Resizing: boolean; // flag stating the control is resizing Painting: boolean; FirstTime: boolean; // flag stating the control needs initialization fWordWrap: boolean; fMaxWidth: integer; fWrapByChar: boolean; fPauseResize: boolean; ResizeRequested: boolean; LargestPixelWidth: longint; fClicksDisabled: Boolean; FStringData: string; function GetGroupIndex: integer; procedure SetAssociate(const Value: TControl); procedure SetGroupIndex(const Value: integer); procedure SetUseRadioStyle(const Value: boolean); procedure SetSpacing(const Value: integer); function GetSingleLine: boolean; procedure TextToCanvas(y: integer; s: string); procedure SetMaxWidth(const Value: integer); procedure SetWrapByChar(const Value: boolean); procedure SyncAllowAllUnchecked; procedure SetPostDelimiter(const Value: TSysCharSet); procedure SetPreDelimiter(const Value: TSysCharSet); function GetChecked: boolean; procedure SetChecked(const Value: boolean); function GetText: string; function GetLine(const idx: integer): string; procedure SetLine(const idx: integer; const Value: string); function GetCount: integer; function BoxWidth: integer; procedure SetFocusOnBox(const Value: boolean); function GetState: TCheckBoxState; procedure SetState(const Value: TCheckBoxState); function GetCaption: string; procedure SetCaption(const Value: string); protected procedure DoEnter; override; // fires when the control is entered; used for displaying the focus status procedure DoExit; override; // fires when the control is exited; used for displaying the focus status procedure SetName(const Value: TComponentName); override; // Sets the text in the control when the name is changed procedure SetAllowAllUnchecked(const Value: boolean); procedure UpdateAssociate; procedure Paint; override; procedure Resize; override; procedure RefreshParts; procedure SetLines(const Value: TStrings); // write accessor for Lines procedure SetText(const Value: string); // write accessor for Text procedure SetVerticalSpace(const Value: integer); // write accessor for VerticalSpace procedure SetTransparent(const Value: boolean); // write accessor for Transparent procedure SetWordWrap(const Value: boolean); function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override; function LargestTextWidth: longint; property ClicksDisabled: Boolean read FClicksDisabled write FClicksDisabled; public property Caption: string read GetCaption write SetCaption; property Displayed: TStringList read fDisplayed; constructor Create(AOwner: TComponent); override; // constructor destructor Destroy; override; // destructor procedure PauseResize; procedure ResumeResize; property SingleLine: boolean read GetSingleLine; property PreDelimiters: TSysCharSet read fPreDelimiter write SetPreDelimiter; property PostDelimiters: TSysCharSet read fPostDelimiter write SetPostDelimiter; property Checkbox: TCheckbox read fCheck write fCheck; property RadioButton: TRadioButton read fRadio write fRadio; property DockManager; property Line[const idx: integer]: string read GetLine write SetLine; // user-formatted text; CRLF delimited property StringData: string read FStringData write FStringData; published property AutoSize; property AllowAllUnchecked: boolean read FAllowAllUnchecked write SetAllowAllUnchecked default True; property Associate: TControl read FAssociate write SetAssociate; property GroupIndex: integer read GetGroupIndex write SetGroupIndex default 0; property Spacing: integer read fSpacing write SetSpacing default OR_DEFAULT_SPACING; property UseRadioStyle: boolean read fUseRadioStyle write SetUseRadioStyle default False; property Checked: boolean read GetChecked write SetChecked; property Text: string read GetText write SetText; property Lines: TStrings read fLines write SetLines; property Transparent: boolean read fTransparent write SetTransparent default True; // determines if the background is transparent property VerticalSpace: integer read fVerticalSpace write SetVerticalSpace default DEFAULT_ICON_SIZE; // number of vertical pixel spaces between items when using multi-line property WordWrap: boolean read fWordWrap write SetWordWrap default False; property MaxWidth: integer read fMaxWidth write SetMaxWidth default DEFAULT_MAX_WIDTH; property WrapByChar: boolean read fWrapByChar write SetWrapByChar default False; property Count: integer read GetCount; property FocusOnBox: boolean read FFocusOnBox write SetFocusOnBox default false; property State: TCheckBoxState read GetState write SetState; end; implementation uses ORFn, Math, System.UITypes; { TORRadioCheck } function TORRadioCheck.BoxWidth: integer; begin Result := Max(fCheck.Width, fRadio.Width); end; function TORRadioCheck.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; begin Result := True; if HandleAllocated and (Align <> alClient) and (not (csDesigning in ComponentState) or (ControlCount > 0)) then begin NewWidth := Max(fRadio.Width, fCheck.Width) + fSpacing + LargestTextWidth + Margins.Left + Margins.Right; NewHeight := Max(fDisplayed.Count * FontHeight, fCheck.Height) + Margins.Top + Margins.Bottom + (fVerticalSpace * fLines.Count); end; end; constructor TORRadioCheck.Create(AOwner: TComponent); begin inherited; IconSize := DEFAULT_ICON_SIZE; // default size BevelInner := bvNone; BevelOuter := bvNone; ShowCaption := False; ParentFont := True; // initialize objects fLines := TStringList.Create; fDisplayed := TStringList.Create; // set internal property values fMaxWidth := DEFAULT_MAX_WIDTH; fTransparent := True; fVerticalSpace := OR_DEFAULT_SPACING; fWordWrap := False; Caption := ''; fWrapByChar := False; fPauseResize := False; ResizeRequested := False; // set flags Resizing := False; Painting := False; FirstTime := True; // set inherited property values BevelInner := bvNone; BevelOuter := bvNone; Alignment := taLeftJustify; fSpacing := OR_DEFAULT_SPACING; Height := IconSize + Margins.Top + Margins.Bottom; Width := IconSize + Margins.Left + Margins.Right + fSpacing; FontHeight := FontHeightInPixels(Font); fCheck := TCheckbox.Create(Self); fCheck.Parent := Self; fCheck.Left := 0; fCheck.Top := 0; fCheck.Caption := ''; fCheck.Width := fCheck.Height; IconSize := fCheck.Height; fCheck.ParentFont := True; fCheck.Visible := True; fCheck.OnClick := Self.OnClick; fRadio := TRadioButton.Create(Self); fRadio.Parent := Self; fRadio.Left := 0; fRadio.Top := 0; fRadio.Width := fRadio.Height; fRadio.Caption := ''; fRadio.Visible := False; fRadio.ParentFont := True; fRadio.OnClick := Self.OnClick; UseRadioStyle := False; fSingleLine := True; fFocusOnBox := False; fGrayedToChecked := True; fAllowAllUnchecked := True; fAssociate := nil; end; destructor TORRadioCheck.Destroy; begin // free up objects if assigned(fLines) then fLines.Free; if assigned(fDisplayed) then fDisplayed.Free; inherited; end; procedure TORRadioCheck.DoEnter; begin Paint; inherited; end; procedure TORRadioCheck.DoExit; begin Paint; inherited; end; function TORRadioCheck.GetCaption: string; begin Result := GetText; end; function TORRadioCheck.GetChecked: boolean; begin Result := fCheck.Checked; end; function TORRadioCheck.GetCount: integer; begin Result := fLines.Count; end; function TORRadioCheck.GetGroupIndex: integer; begin Result := fRadio.Tag; end; function TORRadioCheck.GetLine(const idx: integer): string; begin if (idx >= 0) and (idx < Count) then Result := fLines[idx] else raise exception.Create('line index out of bounds (' + IntToStr(idx) + ')'); end; function TORRadioCheck.GetSingleLine: boolean; begin Result := (fLines.Count = 1); // assumption: this may need to be < 2 end; function TORRadioCheck.GetState: TCheckBoxState; begin Result := fCheck.State; end; function TORRadioCheck.GetText: string; begin Result := fLines.Text; end; function TORRadioCheck.LargestTextWidth: longint; var i: integer; begin Result := 0; for i := 0 to (fLines.Count - 1) do begin if Trim(fLines[i]) <> '' then begin Result := Max(FontWidthInPixels(Font, fLines[i]), Result); end; end; end; procedure TORRadioCheck.Paint; var r: TRect; // rectangle used to draw the border i: integer; // loops OldPenColor, // saves the former pen color while drawing the border OldBrushColor: TColor; // saves the former brush color while drawing the border OldPenStyle: TPenStyle; // saves the former pen style while drawing the border OldBrushStyle: TBrushStyle; // saves the former brush style while drawing the border begin if assigned(Canvas) then begin if not Painting then begin Painting := True; try FontHeight := FontHeightInPixels(Font); fCheck.Visible := (not fUseRadioStyle); fRadio.Visible := fUseRadioStyle; if fUseRadioStyle then begin fCheck.Width := 0; fRadio.Width := IconSize; end else begin fCheck.Width := IconSize; fRadio.Width := 0; end; fCheck.Top := Max(fCheck.Height, FontHeight) - fCheck.Height + Margins.Top; fRadio.Top := fCheck.Top; {------------------} { Draw the outline } {------------------} OldBrushColor := Canvas.Brush.Color; OldBrushStyle := Canvas.Brush.Style; OldPenColor := Canvas.Pen.Color; // save old settings OldPenStyle := Canvas.Pen.Style; try Canvas.Font.Assign(Font); // make sure using the correct font to draw with Canvas.Pen.Width := 1; if Transparent then begin Canvas.Brush.Style := bsClear; Canvas.Brush.Color := clNone; end else begin Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := Color; end; Canvas.Brush.Color := clNone; Canvas.Brush.Style := bsClear; if Focused then begin // focused control uses dotted line in font color Canvas.Pen.Style := psDot; Canvas.Pen.Color := Font.Color; end else begin // normal drawing just draws a rectangle that overwrites previous rectangles Canvas.Pen.Style := psSolid; Canvas.Pen.Color := Color; end; r := Rect(0, 0, Width, Height); if Transparent then begin Canvas.TextFlags := 0; Canvas.FrameRect(r); end else begin Canvas.TextFlags := ETO_OPAQUE; Canvas.Rectangle(r); // draw the rectangle end; {---------------} { Draw the text } {---------------} // write out the strings after determining if they are wrapped for i := 0 to (fDisplayed.Count - 1) do begin // loop through lines, determine if they need wrapped TextToCanvas(Margins.Top + (i * (FontHeight + VerticalSpace)), fDisplayed[i]); end; finally Canvas.Brush.Color := OldBrushColor; Canvas.Brush.Style := OldBrushStyle; Canvas.Pen.Color := OldPenColor; Canvas.Pen.Style := OldPenStyle; end; finally Painting := False; end; end; end; end; procedure TORRadioCheck.PauseResize; begin fPauseResize := True; end; procedure TORRadioCheck.RefreshParts; begin fCheck.Repaint; fRadio.Repaint; Invalidate; end; procedure TORRadioCheck.Resize; var i: integer; sl: TStringList; WorkWidth: integer; begin inherited; FontHeight := FontHeightInPixels(Font); if fPauseResize then begin ResizeRequested := True; end else begin if not Resizing then begin Resizing := True; try fDisplayed.Clear; LargestPixelWidth := FindFontMetrics(Font).tmMaxCharWidth; if fWordWrap then begin // word handling is Word Wrap if (fMaxWidth > 0) then begin WorkWidth := Min(LargestTextWidth, fMaxWidth); end else begin WorkWidth := Width - fSpacing - BoxWidth; end; for i := 0 to (fLines.Count - 1) do begin if fWrapByChar and (fMaxWidth > 0) then sl := WrapTextByChar(fLines[i], fMaxWidth, Canvas, PreSeparatorChars, PostSeparatorChars) else sl := WrapTextByPixels(fLines[i], WorkWidth, Canvas, PreSeparatorChars, PostSeparatorChars); fDisplayed.AddStrings(sl); end; end else begin // no word wrapping fDisplayed.Text := fLines.Text; end; Invalidate; finally Resizing := False; end; end; end; end; procedure TORRadioCheck.ResumeResize; begin fPauseResize := False; if ResizeRequested then Resize; end; procedure TORRadioCheck.SetAllowAllUnchecked(const Value: boolean); begin FAllowAllUnchecked := Value; SyncAllowAllUnchecked; end; procedure TORRadioCheck.SetAssociate(const Value: TControl); begin if (FAssociate <> Value) then begin if (assigned(FAssociate)) then FAssociate.RemoveFreeNotification(Self); FAssociate := Value; if (assigned(FAssociate)) then begin FAssociate.FreeNotification(Self); UpdateAssociate; end; end; end; procedure TORRadioCheck.UpdateAssociate; procedure EnableCtrl(Ctrl: TControl; DoCtrl: boolean); var i: integer; DoIt: boolean; begin if DoCtrl then Ctrl.Enabled := Checked; // added (csAcceptsControls in Ctrl.ControlStyle) below to prevent disabling of // child sub controls, like the TBitBtn in the TORComboBox. If the combo box is // already disabled, we don't want to disable the button as well - when we do, we // lose the disabled glyph that is stored on that button for the combo box. if (Ctrl is TWinControl) and (csAcceptsControls in Ctrl.ControlStyle) then begin for i := 0 to TWinControl(Ctrl).ControlCount - 1 do begin if DoCtrl then DoIt := TRUE else DoIt := (TWinControl(Ctrl).Controls[i] is TWinControl); if DoIt then EnableCtrl(TWinControl(Ctrl).Controls[i], TRUE); end; end; end; begin if (assigned(FAssociate)) then EnableCtrl(FAssociate, FALSE); end; procedure TORRadioCheck.SetCaption(const Value: string); begin SetText(Value); end; procedure TORRadioCheck.SetChecked(const Value: boolean); begin if (Value <> fCheck.Checked) or (Value <> fRadio.Checked) then begin fCheck.Checked := Value; fRadio.Checked := Value; end; invalidate; end; procedure TORRadioCheck.SetFocusOnBox(const Value: boolean); begin fFocusOnBox := Value; invalidate; end; procedure TORRadioCheck.SetGroupIndex(const Value: integer); begin fRadio.Tag := Value; end; procedure TORRadioCheck.SetLine(const idx: integer; const Value: string); begin if (idx >= 0) and (idx < Count) then begin if fLines[idx] <> Value then begin fLines[idx] := Value; Resize; end; end else raise exception.Create('line index out of bounds (' + IntToStr(idx) + ')'); end; procedure TORRadioCheck.SetLines(const Value: TStrings); begin if (Value.Text <> fLines.Text) then begin fLines.Text := Value.Text; Resize; end; end; procedure TORRadioCheck.SetMaxWidth(const Value: integer); begin if (fMaxWidth <> Value) then begin fMaxWidth := Value; Resize; end; end; procedure TORRadioCheck.SetName(const Value: TComponentName); begin inherited; if (Name <> Value) then begin inherited SetName(Value); fLines.Text := Name; end; end; procedure TORRadioCheck.SetPostDelimiter(const Value: TSysCharSet); begin fPostDelimiter := Value; end; procedure TORRadioCheck.SetPreDelimiter(const Value: TSysCharSet); begin fPreDelimiter := Value; end; procedure TORRadioCheck.SetUseRadioStyle(const Value: boolean); begin if (Value <> fUseRadioStyle) then begin fUseRadioStyle := Value; end; Repaint; end; procedure TORRadioCheck.SetVerticalSpace(const Value: integer); begin if (fVerticalSpace <> Value) then begin fVerticalSpace := Value; Invalidate; end; end; procedure TORRadioCheck.SetSpacing(const Value: integer); begin fSpacing := Value; Invalidate; end; procedure TORRadioCheck.SetState(const Value: TCheckBoxState); begin fCheck.State := Value; fRadio.Checked := fCheck.Checked; end; procedure TORRadioCheck.SetText(const Value: string); begin fLines.Text := Value; Resize; end; procedure TORRadioCheck.SetTransparent(const Value: boolean); begin if (fTransparent <> Value) then begin fTransparent := Value; if Value then ControlStyle := ControlStyle - [csOpaque] else ControlStyle := ControlStyle + [csOpaque]; end; Invalidate; end; procedure TORRadioCheck.SetWordWrap(const Value: boolean); begin if (fWordWrap <> Value) then begin fWordWrap := Value; end; Resize; end; procedure TORRadioCheck.SetWrapByChar(const Value: boolean); begin fWrapByChar := Value; Resize; end; procedure TORRadioCheck.SyncAllowAllUnchecked; var i: integer; cb: TORRadioCheck; begin if (assigned(Parent) and (GroupIndex <> 0)) then begin for i := 0 to Parent.ControlCount - 1 do begin if (Parent.Controls[i] is TORRadioCheck) then begin cb := TORRadioCheck(Parent.Controls[i]); if ((cb <> Self) and (cb.GroupIndex = GroupIndex)) then cb.FAllowAllUnchecked := FAllowAllUnchecked; end; end; end; end; procedure TORRadioCheck.TextToCanvas(y: integer; s: string); begin if assigned(Canvas) then begin case Alignment of // x position based on alignment property of control taLeftJustify: Canvas.TextOut(IconSize + fSpacing + Margins.Left, y, s); taRightJustify: Canvas.TextOut(IconSize + fSpacing + (Width - Margins.Right - Canvas.TextWidth(s)), y, s); taCenter: Canvas.TextOut(IconSize + fSpacing + ((Width div 2) - Margins.Right - (Canvas.TextWidth(s) div 2)), y, s); end; end; end; end.
unit ncaFrmEditFunc; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxLabel, PngImage, ExtCtrls, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, Menus, StdCtrls, cxButtons, ImgList, ncMyImage, ncaFrmCliPesq2, System.ImageList; type TFrmEditFunc = class(TForm) panPri: TLMDSimplePanel; lbNome: TcxLabel; imgs: TcxImageList; Img: TMyImage; procedure FormCreate(Sender: TObject); procedure lbNomeClick(Sender: TObject); procedure ImgClick(Sender: TObject); private FUsername: String; FNome: String; FPodeAlterar: Boolean; procedure SetUsername(const Value: String); procedure SetNome(const Value: String); public procedure Pesquisa(const aMostraMsg: Boolean = False); procedure Update; property PodeAlterar: Boolean read FPodeAlterar write FPodeAlterar; { Private declarations } property Username: String read FUsername write SetUsername; property Nome: String read FNome write SetNome; end; var FrmEditFunc: TFrmEditFunc; implementation uses ncaDM, ncaFrmFuncPesq, ncIDRecursos, ncaStrings; {$R *.dfm} resourcestring rsSelecioneUsuario = 'Selecione um usuário'; { TFrmEditContato } procedure TFrmEditFunc.FormCreate(Sender: TObject); begin FUsername := ''; FNome := ''; FPodeAlterar := True; end; procedure TFrmEditFunc.ImgClick(Sender: TObject); begin Pesquisa; end; procedure TFrmEditFunc.lbNomeClick(Sender: TObject); begin Pesquisa; lbNome.Invalidate; lbNome.Update; end; procedure TFrmEditFunc.Pesquisa(const aMostraMsg: Boolean = False); var F: TFrmFuncPesq; begin if (FUsername>'') and (not PodeAlterar) then begin ShowMessage(rsSemPermissaoAlterar); Exit; end; F := gFuncPesqList.GetFrm; try if F.Pesquisar(FUsername, FNome, aMostraMsg) then Update; finally gFuncPesqList.ReleaseFrm(F); end; end; procedure TFrmEditFunc.SetUsername(const Value: String); begin FUsername := Value; with Dados do if Value='' then FNome := '' else if mtUsuario.Locate('Username', FUsername, []) then FNome := mtUsuarioNome.Value; Update; end; procedure TFrmEditFunc.Update; begin if FUsername>'' then begin lbNome.Caption := FNome; if FNome='' then lbNome.Caption := FUsername; end else lbNome.Caption := rsSelecioneUsuario; lbNome.Caption := lbNome.Caption + ' (F6)'; end; procedure TFrmEditFunc.SetNome(const Value: String); begin FNome := Value; Update; end; end.
unit RegFIBPlusEditors; interface {$I ..\FIBPlus.inc} uses Windows,Classes, {$IFDEF D_XE2} Vcl.StdCtrls,Vcl.Forms,Vcl.ExtCtrls,Vcl.Dialogs, {$ELSE} StdCtrls,Forms,ExtCtrls,Dialogs, {$ENDIF} SysUtils,pFIBInterfaces, TypInfo, FIBDatabase, {$IFDEF D6+} DesignEditors,DesignIntf, Variants//,Types {$else} DsgnIntf {$ENDIF} ; type TiBeforeProposalCall=procedure(const ProposalName:string) of object; IFIBSQLTextEditor= interface ['{59B98703-4324-43AA-A656-5842806E35B2}'] function GetReadOnly:boolean; procedure SetReadOnly(Value:boolean); function GetLines:TStrings; procedure SetLines(Value: TStrings); function GetSelStart: Integer; procedure SetSelStart(Value: Integer); function GetSelLength: Integer; procedure SetSelLength(Value: Integer); function GetCaretX:integer; function GetCaretY:integer; procedure iSetCaretPos(X,Y:integer); procedure ScreenPosToTextPos(const ScrX,ScrY:Integer; var DestX,DestY:Integer ); // для драг дропа procedure ISetProposalItems(ts1,ts2:TStrings); procedure SaveProposals(const aName:string); procedure ApplyProposal(const aName:string); procedure AddToCurrentProposal(ts,ts1:TStrings); procedure AddProposal(const aName:string); procedure ClearProposal; function GetBeforePropCall:TiBeforeProposalCall; procedure SetBeforePropCall(Event:TiBeforeProposalCall); function GetPosInText:Integer; procedure SelectAll; function GetModified: Boolean; procedure SetModified(Value: Boolean); procedure SetFocus; property SelLength: Integer read GetSelLength write SetSelLength; property SelStart: Integer read GetSelStart write SetSelStart; property ReadOnly:boolean read GetReadOnly write SetReadOnly; property Lines: TStrings read GetLines write SetLines; property CaretX:integer read GetCaretX; property CaretY:integer read GetCaretY; property DoBeforeProposalCall: TiBeforeProposalCall read GetBeforePropCall write SetBeforePropCall; property PosInText:integer read GetPosInText; end; { TODO 1 : Тулзы подключить. Проверить на компиляцию под Д6 перенести под Д2009 } procedure RegisterFIBSQLTextEditor(Editor:TClass); function GetSQLTextEditor:TClass; procedure Register; implementation uses pFIBComponentEditors, {$ifndef internal} fib_aspr_api, Fibmodule5, Fibmodule6, FibHash2, Fibhash3, fibAthlInstanceCounter, fibCheckSingleLicenseClass, fib_hard, {$endif} ToolsAPI, RegSynEditAlt {, FIBSplash}; var vSQLTextEditorClass:TClass; var LicensedTo: string; k: AnsiString; type TFIBSQLMemo=class(TMemo,IFIBSQLTextEditor) private function GetReadOnly:boolean; procedure SetReadOnly(Value:boolean); function GetLines:TStrings; function GetCaretX:integer; function GetCaretY:integer; function GetModified: Boolean; procedure SetModified(Value: Boolean); procedure iSetCaretPos(X,Y:integer); procedure ISetProposalItems(ts1,ts2:TStrings); procedure SaveProposals(const aName:string); procedure ApplyProposal(const aName:string); procedure AddToCurrentProposal(ts,ts1:TStrings); procedure AddProposal(const aName:string); procedure ClearProposal; function GetBeforePropCall:TiBeforeProposalCall; procedure SetBeforePropCall(Event:TiBeforeProposalCall); function GetPosInText:Integer; procedure ScreenPosToTextPos(const ScrX,ScrY:Integer; var DestX,DestY:Integer ); // для драг дропа public constructor Create(AOwner:TComponent);override; end; procedure RegisterFIBSQLTextEditor(Editor:TClass); begin if Assigned(Editor) then vSQLTextEditorClass:=Editor else vSQLTextEditorClass:=TFIBSQLMemo end; function GetSQLTextEditor:TClass; begin if Assigned(vSQLTextEditorClass) then Result:=vSQLTextEditorClass else Result:=TFIBSQLMemo end; {$ifndef internal} type TMenuIOTAFibPlus = class(TNotifierObject, IOTAWIzard, IOTAMenuWizard) public function GetMenuText: string; function GetIDString: string; function GetName: string; function GetState: TWizardState; procedure Execute; end; TIDEIOTAFibPlus = class(TNotifierObject, IOTANotifier, IOTAIDENotifier, IOTAIDENotifier50) public // IOTAIDENotifier procedure FileNotification(NotifyCode: TOTAFileNotification; const FileName: string; var Cancel: Boolean); procedure BeforeCompile(const Project: IOTAProject; var Cancel: Boolean); overload; procedure AfterCompile(Succeeded: Boolean); overload; // IOTAIDENotifier50 procedure BeforeCompile(const Project: IOTAProject; IsCodeInsight: Boolean; var Cancel: Boolean); overload; procedure AfterCompile(Succeeded: Boolean; IsCodeInsight: Boolean); overload; end; type TDemoTimer = class end; var DemoTimer: TDemoTimer; var CheckLicense: TCheckLicense; NotifierIndex: Integer; {$endif} type IFIBClassesExporter = interface ['{AFC7CF1A-EAA5-4584-B47D-BDAD337B4EEC}'] function iGetStringer:IFIBStringer; function iGetMetaExtractor:IFIBMetaDataExtractor; end; procedure Register; procedure RegisterEditors; var DatabaseClass:TClass; QueryClass:TClass; DatasetClass:TClass; DeltaReceiver:TClass; TransactionClass:TClass; pi:PPropInfo; auClass:TClass; expCl:IFIBClassesExporter; begin Supports(FIBClassesExporter,IFIBClassesExporter,expCl); try expCl.iGetStringer; // AV если триал пытаются использовать с не триалом //database Properties DatabaseClass:=expDatabaseClass; TransactionClass:=expTransactionClass; QueryClass:=expQueryClass; DatasetClass:=expDatasetClass; DeltaReceiver:=expDeltaReceiverClass; RegisterPropertyEditor(TypeInfo(string), DatabaseClass, 'AliasName', TFIBAliasEdit); RegisterPropertyEditor(TypeInfo(string), DatabaseClass, 'DBName', TFileNameProperty); RegisterPropertyEditor(TypeInfo(string), DatabaseClass, 'LibraryName', TFileNameProperty); RegisterPropertyEditor(TypeInfo(TNotifyEvent),DatabaseClass, 'OnConnect', nil ); pi:=GetPropInfo(DatabaseClass,'OnLogin'); if pi<>nil then RegisterPropertyEditor(pi.PropType^,DatabaseClass, 'OnLogin', nil ); RegisterComponentEditor(TComponentClass(DatabaseClass), TpFIBDatabaseEditor); RegisterComponentEditor(TComponentClass(TransactionClass), TpFIBTransactionEditor); RegisterComponentEditor(TComponentClass(QueryClass), TpFIBQueryEditor); RegisterComponentEditor(TComponentClass(DataSetClass), TFIBGenSQlEd); pi:=GetPropInfo(QueryClass,'Conditions'); RegisterPropertyEditor(pi.PropType^,nil,'Conditions',TFIBConditionsEditor); pi:=GetPropInfo(DatasetClass,'Options'); RegisterPropertyEditor(pi.PropType^, nil, 'Options', TpFIBDataSetOptionsEditor); pi:=GetPropInfo(DatasetClass,'PrepareOptions'); RegisterPropertyEditor(pi.PropType^, nil, 'PrepareOptions', TpFIBDataSetOptionsEditor); pi:=GetPropInfo(DatasetClass,'AutoUpdateOptions'); RegisterPropertyEditor(pi.PropType^, DatasetClass, 'AutoUpdateOptions', TpFIBAutoUpdateOptionsEditor); auClass:=GetTypeData(Pi^.PropType^).ClassType; RegisterPropertyEditor(TypeInfo(TStrings), auClass, 'ParamsToFieldsLinks', TEdParamToFields ); RegisterPropertyEditor(TypeInfo(string), auClass, 'GeneratorName', TGeneratorNameEdit ); RegisterPropertyEditor(TypeInfo(string), auClass, 'KeyFields', TKeyFieldNameEdit ); RegisterPropertyEditor(TypeInfo(string), auClass, 'UpdateTableName', TTableNameEdit ); RegisterPropertyEditor(TypeInfo(integer), DatasetClass, 'DataSet_ID', TDataSet_ID_Edit ); RegisterPropertyEditor(TypeInfo(TStrings),DatasetClass,'SelectSQL',nil); RegisterPropertyEditor(TypeInfo(TStrings),DatasetClass,'InsertSQL',nil); RegisterPropertyEditor(TypeInfo(TStrings),DatasetClass,'UpdateSQL',nil); RegisterPropertyEditor(TypeInfo(TStrings),DatasetClass,'DeleteSQL',nil); RegisterPropertyEditor(TypeInfo(TStrings),DatasetClass,'RefreshSQL',nil); RegisterPropertyEditor(TypeInfo(boolean),DatasetClass,'WaitEndMasterScroll',nil); pi:=GetPropInfo(DatasetClass,'SQLs'); RegisterPropertyEditor(TypeInfo(TStrings),GetTypeData(Pi^.PropType^).ClassType,'',TFIBSQLsProperty); RegisterPropertyEditor(pi.PropType^,DatasetClass,'',TFIBSQLsProperties); RegisterPropertyEditor(TypeInfo(string), QueryClass, 'StoredProcName', TpFIBStoredProcProperty ); RegisterPropertyEditor(TypeInfo(TStrings), QueryClass, 'SQL', TpFIBSQLPropEdit ); RegisterPropertyEditor(TypeInfo(string),TransactionClass, 'UserKindTransaction', TFIBTrKindEdit ); pi:=GetPropInfo(DatabaseClass,'GeneratorsCache'); auClass:=GetTypeData(Pi^.PropType^).ClassType; RegisterPropertyEditor(TypeInfo(TOwnedCollection),auClass, 'GeneratorList', TpFIBGeneratorsProperty ); RegisterPropertyEditor(TypeInfo(string),auClass, 'CacheFileName', TFileNameProperty ); { RegisterPropertyEditor(TypeInfo(TOwnedCollection),TGeneratorsCache, 'Generators', TpFIBGeneratorsProperty ); { RegisterPropertyEditor(TypeInfo(TCollection), TCustomDBGridEh, 'Columns', TDBGridEhColumnsProperty); } RegisterPropertyEditor(TypeInfo(TStrings), TransactionClass, 'TRParams', TpFIBTRParamsEditor ); if Assigned(expServicesClass) then RegisterPropertyEditor(TypeInfo(string), expServicesClass, 'LibraryName', TFileNameProperty); RegisterPropertyEditor(TypeInfo(string), DeltaReceiver, 'TableName', TTableNameEditDR ); RegisterComponentEditor(TComponentClass(DeltaReceiver), TpFIBDeltaReceiverEditor); {$IFDEF D6+} RegisterPropertiesInCategory('Transactions',['*Transaction*'] ); {$ENDIF} except end; end; begin // RegisterSplashScreen; {$ifdef internal} // RegisterFIBUtils; RegisterEditors; {$else} {$I include\aspr_crypt_begin1.inc} // trial // MessageBox(0, 'trial', '', mb_ok); RegisterEditors; DemoTimer := TDemoTimer.Create; {$I include\aspr_crypt_end1.inc} {$I include\aspr_crypt_begin2.inc} // single user // MessageBox(0, 'single', '', mb_ok); RegisterFIBUtils; RegisterEditors; CheckLicense := TCheckLicense.Create(k); NotifierIndex := (BorlandIDEServices as IOTAServices).AddNotifier(TIDEIOTAFibPlus.Create); {$I include\aspr_crypt_end2.inc} {$I include\aspr_crypt_begin3.inc} // multi user // MessageBox(0, 'multi', '', mb_ok); RegisterFIBUtils; RegisterEditors; {$I include\aspr_crypt_end3.inc} RegisterPackageWizard(TMenuIOTAFibPlus.create as IOTAWizard); {$endif} end; { TFIBSQLMemo } constructor TFIBSQLMemo.Create(AOwner: TComponent); begin inherited; ScrollBars:=ssBoth; end; function TFIBSQLMemo.GetCaretX: integer; begin Result:=CaretPos.X end; function TFIBSQLMemo.GetCaretY: integer; begin Result:=CaretPos.Y end; function TFIBSQLMemo.GetLines: TStrings; begin Result:=Lines end; function TFIBSQLMemo.GetModified: Boolean; begin Result:=Modified end; function TFIBSQLMemo.GetReadOnly: boolean; begin Result:=ReadOnly end; procedure TFIBSQLMemo.ScreenPosToTextPos(const ScrX,ScrY:Integer; var DestX,DestY:Integer ); // для драг дропа begin DestX:=-1 end; procedure TFIBSQLMemo.iSetCaretPos(X,Y:integer); begin end; procedure TFIBSQLMemo.SetModified(Value: Boolean); begin Modified:=Value end; procedure TFIBSQLMemo.SetReadOnly(Value: boolean); begin inherited ReadOnly:=Value end; {$ifndef internal} procedure RegisterModule; const RegKey = 'Devrace\FibPlus\7.2'; var Crypt: TDev_class8; //Tea Crypt2: TDev_class10; //Ice tempkey: HKey; keyClass: array[0..256] of AnsiChar; KeySize: DWord; work, Hardware: AnsiString; I: Integer; info, username, key: Ansistring; t: AnsiChar; begin DemoTimer := nil; CheckLicense := nil; NotifierIndex := -MAXWORD; LicensedTo := 'Craked version'; Crypt := TDev_class8.Create(nil); Crypt2 := TDev_class10.Create(nil); try if RegOpenKeyEx(HKEY_CURRENT_USER, 'Software\' + RegKey, 0, KEY_QUERY_VALUE, tempkey) = ERROR_SUCCESS then begin KeySize := 256; RegQueryInfoKeyA(tempkey, keyClass, @KeySize, nil, nil, nil, nil, nil, nil, nil, nil, nil); RegCloseKey(TempKey); Hardware := GetHardID; Hardware := Hardware + StringOfChar('\', Length(RegKey) - Length(Hardware)); work := ''; for I := 1 to Length(RegKey) do work := work + AnsiChar(Byte(Ord(Hardware[i]) + Ord(RegKey[i]))); crypt.InitStr(work, TDev_hash2); //MD5 info := crypt.WorkDSt(keyclass); username := Copy(info, 1, Pos(#1, Info) - 1); LicensedTo := username; key := copy(info, Pos(#1, Info) + 1, Length(info)); k := key; crypt2.InitStr(username, TDev_hash3); //RipeMD-128 key := key + '=='; key := Crypt2.WorkDSt(key); t := key[1]; key[1] := key[30]; key[30] := t; t := key[3]; key[3] := key[32]; key[32] := t; t := key[6]; key[6] := key[35]; key[35] := t; t := key[8]; key[8] := key[37]; key[37] := t; t := key[10]; key[10] := key[39]; key[39] := t; t := key[12]; key[12] := key[41]; key[41] := t; t := key[14]; key[14] := key[43]; key[43] := t; // MessageBoxa(0, PAnsiChar(key), PAnsiChar(username), mb_ok) ; CheckKeyAndDecrypt(PAnsiChar(key), PAnsiChar(username), False); ; // k := key; end; finally Crypt.Burn; Crypt.Free; Crypt2.Burn; Crypt2.Free; end; end; {$endif} {$ifndef internal} { TMenuIOTACleverFilter } procedure TMenuIOTAFibPlus.Execute; var Msg: string; begin {$I include\userpolybuffer.inc} Msg := 'FibPlus version 7.2.'#13#10'Copyright (c) Devrace Ltd, S.A.'#13#10; if Assigned(DemoTimer) then Msg := Msg + 'Trial version' else Msg := Msg + 'Registered on ' + LicensedTo; if Assigned(CheckLicense) then Msg := Msg + #13#10'Running instance: ' + IntToStr(CheckLicense.InstanceCount); if BorlandIDEServices <> nil then MessageDlg(Msg, mtInformation, [mbOk], 0{$IFDEF D10+}, mbOK{$ENDIF}); end; function TMenuIOTAFibPlus.GetIDString: string; begin Result := 'Devrace.FibPlus'; end; function TMenuIOTAFibPlus.GetMenuText: string; begin Result := 'About Devrace FibPlus'; end; function TMenuIOTAFibPlus.GetName: string; begin Result := 'AboutDevraceFibPlus'; end; function TMenuIOTAFibPlus.GetState: TWizardState; begin Result := [wsEnabled]; end; { TIDEIOTACleverFilter } procedure TIDEIOTAFibPlus.AfterCompile(Succeeded: Boolean); begin end; procedure TIDEIOTAFibPlus.AfterCompile(Succeeded, IsCodeInsight: Boolean); begin end; procedure TIDEIOTAFibPlus.BeforeCompile(const Project: IOTAProject; IsCodeInsight: Boolean; var Cancel: Boolean); begin {$I include\userpolybuffer.inc} Cancel := not (Assigned(CheckLicense) and CheckLicense.IsValid); if Cancel then (BorlandIDEServices as IOTAMessageServices).AddTitleMessage('The compilation of the project has been stopped because of the violation of the license agreement: the current registration key is being used on multiple computers simultaneously.'); end; procedure TIDEIOTAFibPlus.BeforeCompile(const Project: IOTAProject; var Cancel: Boolean); begin {$I include\userpolybuffer.inc} Cancel := not (Assigned(CheckLicense) and CheckLicense.IsValid); if Cancel then (BorlandIDEServices as IOTAMessageServices).AddTitleMessage('The compilation of the project has been stopped because of the violation of the license agreement: the current registration key is being used on multiple computers simultaneously.'); end; procedure TIDEIOTAFibPlus.FileNotification( NotifyCode: TOTAFileNotification; const FileName: string; var Cancel: Boolean); begin {$I include\userpolybuffer.inc} Cancel := not (Assigned(CheckLicense) and CheckLicense.IsValid); if Cancel then (BorlandIDEServices as IOTAMessageServices).AddTitleMessage('The compilation of the project has been stopped because of the violation of the license agreement: the current registration key is being used on multiple computers simultaneously.'); end; procedure CleanupModule; begin {$I include\userpolybuffer.inc} if Assigned(DemoTimer) then FreeAndNil(DemoTimer); if Assigned(CheckLicense) then FreeAndNil(CheckLicense); if NotifierIndex <> -MAXWORD then (BorlandIDEServices as IOTAServices).RemoveNotifier(NotifierIndex); end; {$endif} procedure TFIBSQLMemo.ISetProposalItems(ts1, ts2: TStrings); begin end; procedure TFIBSQLMemo.AddProposal(const aName: string); begin end; procedure TFIBSQLMemo.AddToCurrentProposal(ts, ts1: TStrings); begin end; procedure TFIBSQLMemo.ApplyProposal(const aName: string); begin end; procedure TFIBSQLMemo.ClearProposal; begin end; procedure TFIBSQLMemo.SaveProposals(const aName: string); begin end; function TFIBSQLMemo.GetBeforePropCall: TiBeforeProposalCall; begin Result:=nil end; procedure TFIBSQLMemo.SetBeforePropCall(Event: TiBeforeProposalCall); begin end; function TFIBSQLMemo.GetPosInText: Integer; begin end; initialization {$ifndef internal} RegisterModule; {$endif} // RegisterFIBSQLTextEditor(TFIBSQLMemo) // AppHandleException:=Application.HandleException; finalization {$ifndef internal} CleanupModule; {$endif} end.
unit mGMV_SystemParameters; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, // TRPCB, StdCtrls, CheckLst, ExtCtrls // , u_Common ; type TfraSystemParameters = class(TFrame) Panel1: TPanel; pnlBottom: TPanel; Label1: TLabel; Label3: TLabel; clbxVersions: TCheckListBox; pnlMain: TPanel; Label2: TLabel; edtWebLink: TEdit; cbxAllowUserTemplates: TCheckBox; pnlHeader: TPanel; procedure pnlMainResize(Sender: TObject); private { Private declarations } public // procedure LoadParameters(Broker: TRPCBroker); // procedure SaveParameters(Broker: TRPCBroker); procedure LoadParameters; procedure SaveParameters; { Public declarations } end; implementation uses uGMV_Const //, fROR_PCall , uGMV_Engine, uGMV_Common; {$R *.DFM} //procedure TfraSystemParameters.LoadParameters(Broker: TRPCBroker); procedure TfraSystemParameters.LoadParameters; var lstVersions: TStringList; sWebLink: string; sUserTemplates: string; i: integer; begin clbxVersions.Items.Clear; // lstVersions := TStringList.Create; try // CallRemoteProc(Broker, RPC_PARAMETER, ['GETLST', 'SYS', 'GMV GUI VERSION'], nil,[rpcSilent,rpcNoResChk], lstVersions); lstVersions := getGUIVersionList; // CallRemoteProc(Broker, RPC_PARAMETER, ['GETPAR', 'SYS', 'GMV WEBLINK'], nil); // sWebLink := Broker.Results[0]; sWebLink := getWebLinkAddress; // CallRemoteProc(Broker, RPC_PARAMETER, ['GETPAR', 'SYS', 'GMV ALLOW USER TEMPLATES'], nil); // sUserTemplates := Broker.Results[0]; sUserTemplates := getSystemParameterByName('GMV ALLOW USER TEMPLATES'); cbxAllowUserTemplates.Checked := (Pos('Y', sUserTemplates) > 0); edtWebLink.Text := sWebLink; for i := 1 to lstVersions.Count - 1 do clbxVersions.Checked[clbxVersions.Items.Add(Piece(lstVersions[i], '^', 1))] := (Pos('Y', Piece(lstVersions[i], '^', 2)) > 0); finally FreeAndNil(lstVersions); end; end; //procedure TfraSystemParameters.SaveParameters(Broker: TRPCBroker); procedure TfraSystemParameters.SaveParameters; var i: integer; begin for i := 0 to clbxVersions.Items.Count - 1 do // if clbxVersions.Checked[i] then // CallRemoteProc(Broker, RPC_PARAMETER, ['SETPAR', 'SYS', 'GMV GUI VERSION', clbxVersions.Items[i], '1'], nil) // else // CallRemoteProc(Broker, RPC_PARAMETER, ['SETPAR', 'SYS', 'GMV GUI VERSION', clbxVersions.Items[i], '0'], nil); if clbxVersions.Checked[i] then setSystemParameter('GMV GUI VERSION', clbxVersions.Items[i], '1') else setSystemParameter('GMV GUI VERSION', clbxVersions.Items[i], '0'); // if cbxAllowUserTemplates.Checked then // CallRemoteProc(Broker, RPC_PARAMETER, ['SETPAR', 'SYS', 'GMV ALLOW USER TEMPLATES', '1', '1'], nil) // else // CallRemoteProc(Broker, RPC_PARAMETER, ['SETPAR', 'SYS', 'GMV ALLOW USER TEMPLATES', '1', '0'], nil); if cbxAllowUserTemplates.Checked then setSystemParameter('GMV ALLOW USER TEMPLATES', '1', '1') else setSystemParameter('GMV ALLOW USER TEMPLATES', '1', '0'); // CallRemoteProc(Broker, RPC_PARAMETER, ['SETPAR', 'SYS', 'GMV WEBLINK', '1', edtWebLink.Text], nil); setSystemParameter('GMV WEBLINK', '1', edtWebLink.Text); end; procedure TfraSystemParameters.pnlMainResize(Sender: TObject); begin edtWebLink.Width := pnlMain.Width - (edtWebLink.Left * 2); end; end.
unit UShapes; {$mode objfpc}{$H+} interface uses Classes, Graphics, UViewPort, UGeometry, math, LCLIntf, LCLType, sysutils, UBaseShape; type { TFill } TBrushColor = type TColor; TFill = class abstract(TShape) private FBrushColor: TBrushColor; FBrushStyle: TBrushStyle; procedure SetPoints(AValue: TStrings); override; public constructor Create; override; procedure Draw(ACanvas: TCanvas); override; procedure DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); override; procedure SetPoint(APoint: TPoint); override; published property BrushColor: TBrushColor read FBrushColor write FBrushColor; property BrushStyle: TBrushStyle read FBrushStyle write FBrushStyle; end; { TPolyline } TPolyline = class(TShape) public function PointInShape(APoint: TPoint): Boolean; override; function RectInShape(ARect: TRect): Boolean; override; procedure Draw(ACanvas: TCanvas); override; procedure DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); override; procedure AddPoint(APoint: TPoint); end; { TLine } TLine = class(TShape) private procedure SetPoints(AValue: TStrings); override; public function PointInShape(APoint: TPoint): Boolean; override; function RectInShape(ARect: TRect): Boolean; override; procedure Draw(ACanvas: TCanvas); override; procedure DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); override; procedure SetPoint(APoint: TPoint); override; end; { TRectangle } TRectangle = class(TFill) public function PointInShape(APoint: TPoint): Boolean; override; function RectInShape(ARect: TRect): Boolean; override; procedure Draw(ACanvas: TCanvas); override; procedure DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); override; end; { TEllipse } TEllipse = class(TFill) public function PointInShape(APoint: TPoint): Boolean; override; function RectInShape(ARect: TRect): Boolean; override; procedure Draw(ACanvas: TCanvas); override; procedure DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); override; end; { TRoundRect } TRadius = type Integer; TRoundRect = class(TFill) private FRadiusX: Integer; FRadiusY: Integer; public function PointInShape(APoint: TPoint): Boolean; override; function RectInShape(ARect: TRect): Boolean; override; procedure Draw(ACanvas: TCanvas); override; procedure DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); override; published property RadiusX: TRadius read FRadiusX write FRadiusX; property RadiusY: TRadius read FRadiusY write FRadiusY; end; implementation { TFill } constructor TFill.Create; begin inherited Create; FBrushColor := clWhite; FBrushStyle := bsSolid; end; procedure TFill.Draw(ACanvas: TCanvas); begin inherited Draw(ACanvas); ACanvas.Brush.Color := FBrushColor; ACanvas.Brush.Style := FBrushStyle; end; procedure TFill.DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); begin inherited DrawExport(ACanvas, TopLeft, Scale); ACanvas.Brush.Color := FBrushColor; ACanvas.Brush.Style := FBrushStyle; end; procedure TFill.SetPoint(APoint: TPoint); begin inherited SetPoint(APoint); SetLength(FPoints, 2); FPoints[1] := VP.ScreenToWorld(APoint); end; procedure TFill.SetPoints(AValue: TStrings); begin inherited SetPoints(AValue); if not InRange(Length(FPoints), 2, 2) then raise Exception.Create('Invalid number of points'); end; { TPolyline } function TPolyline.PointInShape(APoint: TPoint): Boolean; var i: integer; begin //I don't know how to do this with regions, so I wrote it myself for i := 0 to High(FPoints) - 1 do begin Result := CircleSegmentIntersection( VP.WorldToScreen(FPoints[i]), VP.WorldToScreen(FPoints[i+1]), APoint, Round(FPenWidth * VP.Scale / 2 + 5)); if Result then Exit; end; end; function TPolyline.RectInShape(ARect: TRect): Boolean; var i: integer; begin //I don't know how to do this with regions, so I wrote it myself for i := 0 to High(FPoints) - 1 do begin Result := Intersection(ARect, VP.WorldToScreen(FPoints[i]), VP.WorldToScreen(FPoints[i+1])); if Result then Exit; end; end; procedure TPolyline.Draw(ACanvas: TCanvas); begin inherited; ACanvas.Polyline(VP.WorldToScreen(FPoints)); end; procedure TPolyline.DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); var p: TPoints; i: Integer; begin inherited DrawExport(ACanvas, TopLeft, Scale); SetLength(p, Length(FPoints)); for i := 0 to High(FPoints) do p[i] := Point((FPoints[i] - TopLeft) * Scale); ACanvas.Polyline(p); end; procedure TPolyline.AddPoint(APoint: TPoint); begin SetLength(FPoints, Length(FPoints) + 1); FPoints[High(FPoints)] := VP.ScreenToWorld(APoint); FRect.Left := Min(FRect.Left, FPoints[High(FPoints)].X); FRect.Right := Max(FRect.Right, FPoints[High(FPoints)].X); FRect.Top := Min(FRect.Top, FPoints[High(FPoints)].Y); FRect.Bottom := Max(FRect.Bottom, FPoints[High(FPoints)].Y); end; { TLine } function TLine.PointInShape(APoint: TPoint): Boolean; begin //I don't know how to do this with regions, so I wrote it myself Result := CircleSegmentIntersection( VP.WorldToScreen(FPoints[0]), VP.WorldToScreen(FPoints[1]), APoint, Round(FPenWidth * VP.Scale / 2 + 5)); end; function TLine.RectInShape(ARect: TRect): Boolean; begin //I don't know how to do this with regions, so I wrote it myself Result := Intersection(ARect, VP.WorldToScreen(FPoints[0]), VP.WorldToScreen(FPoints[1])); end; procedure TLine.Draw(ACanvas: TCanvas); begin inherited; ACanvas.Line(VP.WorldToScreen(FPoints[0]), VP.WorldToScreen(FPoints[1])); end; procedure TLine.DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); var p: TPoints; i: Integer; begin inherited DrawExport(ACanvas, TopLeft, Scale); SetLength(p, Length(FPoints)); for i := 0 to High(FPoints) do p[i] := Point((FPoints[i] - TopLeft) * Scale); ACanvas.Line(p[0], p[1]); end; procedure TLine.SetPoint(APoint: TPoint); begin inherited SetPoint(APoint); SetLength(FPoints, 2); FPoints[1] := VP.ScreenToWorld(APoint); end; procedure TLine.SetPoints(AValue: TStrings); begin inherited SetPoints(AValue); if not InRange(Length(FPoints), 2, 2) then raise Exception.Create('Invalid number of points'); end; { TRectangle } function TRectangle.PointInShape(APoint: TPoint): Boolean; var r: HRGN; begin r := CreateRectRgnIndirect(VP.WorldToScreen(FRect)); Result := PtInRegion(r, APoint.X, APoint.Y); DeleteObject(r); end; function TRectangle.RectInShape(ARect: TRect): Boolean; var r: HRGN; begin r := CreateRectRgnIndirect(VP.WorldToScreen(FRect)); Result := RectInRegion(r, ARect); DeleteObject(r); end; procedure TRectangle.Draw(ACanvas: TCanvas); begin inherited; ACanvas.Rectangle(VP.WorldToScreen(UGeometry.FloatRect(FPoints[0], FPoints[1]))); end; procedure TRectangle.DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); var p: TPoints; i: Integer; begin inherited DrawExport(ACanvas, TopLeft, Scale); SetLength(p, Length(FPoints)); for i := 0 to High(FPoints) do p[i] := Point((FPoints[i] - TopLeft) * Scale); ACanvas.Rectangle(UGeometry.Rect(p[0], p[1])); end; { TEllipse } function TEllipse.PointInShape(APoint: TPoint): Boolean; var r: HRGN; begin r := CreateEllipticRgnIndirect(VP.WorldToScreen(FRect)); Result := PtInRegion(r, APoint.X, APoint.Y); DeleteObject(r); end; function TEllipse.RectInShape(ARect: TRect): Boolean; var r: HRGN; begin r := CreateEllipticRgnIndirect(VP.WorldToScreen(FRect)); Result := RectInRegion(r, ARect); DeleteObject(r); end; procedure TEllipse.Draw(ACanvas: TCanvas); begin inherited; ACanvas.Ellipse(VP.WorldToScreen(UGeometry.FloatRect(FPoints[0], FPoints[1]))); end; procedure TEllipse.DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); var p: TPoints; i: Integer; begin inherited DrawExport(ACanvas, TopLeft, Scale); SetLength(p, Length(FPoints)); for i := 0 to High(FPoints) do p[i] := Point((FPoints[i] - TopLeft) * Scale); ACanvas.Ellipse(UGeometry.Rect(p[0], p[1])); end; { TRoundRect } function TRoundRect.PointInShape(APoint: TPoint): Boolean; var r: HRGN; begin r := CreateRoundRectRgn( VP.WorldToScreen(FPoints[0]).X, VP.WorldToScreen(FPoints[0]).Y, VP.WorldToScreen(FPoints[1]).X, VP.WorldToScreen(FPoints[1]).Y, Round(FRadiusX * VP.Scale), Round(FRadiusY * VP.Scale)); Result := PtInRegion(r, APoint.X, APoint.Y); DeleteObject(r); end; function TRoundRect.RectInShape(ARect: TRect): Boolean; var r: HRGN; begin r := CreateRoundRectRgn( VP.WorldToScreen(FPoints[0]).X, VP.WorldToScreen(FPoints[0]).Y, VP.WorldToScreen(FPoints[1]).X, VP.WorldToScreen(FPoints[1]).Y, Round(FRadiusX * VP.Scale), Round(FRadiusY * VP.Scale)); Result := RectInRegion(r, ARect); DeleteObject(r); end; procedure TRoundRect.Draw(ACanvas: TCanvas); begin inherited; ACanvas.RoundRect(VP.WorldToScreen(UGeometry.FloatRect(FPoints[0], FPoints[1])), Round(FRadiusX * VP.Scale), Round(FRadiusY * VP.Scale)); end; procedure TRoundRect.DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); var p: TPoints; i: Integer; begin inherited DrawExport(ACanvas, TopLeft, Scale); SetLength(p, Length(FPoints)); for i := 0 to High(FPoints) do p[i] := Point((FPoints[i] - TopLeft) * Scale); ACanvas.RoundRect(UGeometry.Rect(p[0], p[1]), FRadiusX, FRadiusY); end; initialization RegisterClass(TPolyline); RegisterClass(TLine); RegisterClass(TRectangle); RegisterClass(TRoundRect); RegisterClass(TEllipse); end.
{**********************************************} { TCustomBoxSeries } { TBoxSeries } { THorizBoxSeries } { } { Copyright (c) 2000-2004 by } { Marjan Slatinek and David Berneda } {**********************************************} unit TeeBoxPlot; {$I TeeDefs.inc} interface Uses {$IFDEF CLR} Classes, Graphics, {$ELSE} {$IFNDEF LINUX} Windows, {$ENDIF} Classes, SysUtils, {$IFDEF CLX} QGraphics, {$ELSE} Graphics, {$ENDIF} {$ENDIF} Chart, Series, TeEngine, TeCanvas; type TCustomBoxSeries=class(TPointSeries) private FExtrOut : TSeriesPointer; FMedianPen : TChartPen; FMildOut : TSeriesPointer; FPosition : Double; FWhiskerLength : Double; FWhiskerPen : TChartPen; IVertical : Boolean; FUseCustomValues: boolean; FMedian: double; FQuartile1: double; FQuartile3: double; FInnerFence1: double; FInnerFence3: double; FOuterFence1: double; FOuterFence3: double; FAdjacentPoint1: integer; FAdjacentPoint3: integer; Function GetBox:TSeriesPointer; procedure SetExtrOut(Value: TSeriesPointer); procedure SetMedianPen(Value: TChartPen); procedure SetMildOut(Value: TSeriesPointer); procedure SetPosition(Const Value: Double); procedure SetWhiskerLength(Const Value: Double); procedure SetWhiskerPen(Value: TChartPen); procedure SetUseCustomValues(const Value: boolean); procedure SetMedian(const Value: double); procedure SetQuartile1(const Value: double); procedure SetQuartile3(const Value: double); procedure SetInnerFence1(const Value: double); procedure SetInnerFence3(const Value: double); procedure SetOuterFence1(const Value: double); procedure SetOuterFence3(const Value: double); procedure SetAdjacentPoint1(const Value: integer); procedure SetAdjacentPoint3(const Value: integer); protected procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); override; procedure DoBeforeDrawValues; override; procedure DrawAllValues; override; procedure DrawMark( ValueIndex:Integer; Const St:String; APosition:TSeriesMarkPosition); override; procedure DrawValue(ValueIndex: Integer); override; class Function GetEditorClass:String; override; function GetSampleValues: TChartValueList; virtual; procedure PrepareForGallery(IsEnabled:Boolean); override; procedure SetParentChart(Const Value: TCustomAxisPanel); override; procedure SetSampleValues(Value: TChartValueList); virtual; public Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; Procedure Assign(Source:TPersistent); override; property Box:TSeriesPointer read GetBox; { MS : Added to support custom values } property Median: double read FMedian write SetMedian; property Quartile1: double read FQuartile1 write SetQuartile1; property Quartile3: double read FQuartile3 write SetQuartile3; property InnerFence1: double read FInnerFence1 write SetInnerFence1; property InnerFence3: double read FInnerFence3 write SetInnerFence3; property OuterFence1: double read FOuterFence1 write SetOuterFence1; property OuterFence3: double read FOuterFence3 write SetOuterFence3; property AdjacentPoint1 : integer read FAdjacentPoint1 write SetAdjacentPoint1; property AdjacentPoint3 : integer read FAdjacentPoint3 write SetAdjacentPoint3; published property ExtrOut : TSeriesPointer read FExtrOut write SetExtrOut; property MedianPen : TChartPen read FMedianPen write SetMedianPen; property MildOut : TSeriesPointer read FMildOut write SetMildOut; property Position : Double read FPosition write SetPosition; property SampleValues : TChartValueList read GetSampleValues write SetSampleValues; property WhiskerLength : Double read FWhiskerLength write SetWhiskerLength; property WhiskerPen : TChartPen read FWhiskerPen write SetWhiskerPen; property UseCustomValues : boolean read FUseCustomValues write SetUseCustomValues default false; end; { Vertical Box Series } TBoxSeries=class(TCustomBoxSeries) public Function MaxXValue:Double; override; Function MinXValue:Double; override; end; { Horizontal Box Series } THorizBoxSeries=class(TCustomBoxSeries) public Constructor Create(AOwner:TComponent); override; Function MaxYValue:Double; override; Function MinYValue:Double; override; end; implementation Uses {$IFDEF CLR} SysUtils, {$ENDIF} TeeProCo; { TCustomBoxSeries } Constructor TCustomBoxSeries.Create(AOwner: TComponent); begin inherited; AllowSinglePoint:=False; CalcVisiblePoints:=False; XValues.Name:=''; YValues.Name:='Samples'; { <- do not translate } Marks.Visible:=False; Marks.Callout.Length:=0; FUseCustomValues := false; { MS : added to support custom values } FWhiskerLength:=1.5; FMildOut:=TSeriesPointer.Create(Self); FMildOut.Style:=psCircle; FExtrOut:=TSeriesPointer.Create(Self); FExtrOut.Style:=psStar; With Pointer do begin Draw3D:=False; Pen.Width:=1; VertSize:=15; HorizSize:=15; Brush.Color:=clWhite; end; FWhiskerPen:=CreateChartPen; FMedianPen:=CreateChartPen; FMedianPen.Width:=1; FMedianPen.Style:=psDot; IVertical:=True; end; Destructor TCustomBoxSeries.Destroy; begin FMedianPen.Free; FWhiskerPen.Free; FreeAndNil(FExtrOut); FreeAndNil(FMildOut); inherited; end; procedure TCustomBoxSeries.SetWhiskerLength(Const Value: Double); begin SetDoubleProperty(FWhiskerLength,Value); end; function TCustomBoxSeries.GetSampleValues; begin result:=MandatoryValueList; end; procedure TCustomBoxSeries.SetSampleValues(Value: TChartValueList); begin if IVertical then YValues:=Value else XValues:=Value; end; procedure TCustomBoxSeries.SetPosition(Const Value: Double); begin SetDoubleProperty(FPosition,Value); end; procedure TCustomBoxSeries.SetWhiskerPen(Value: TChartPen); begin FWhiskerPen.Assign(Value); end; procedure TCustomBoxSeries.SetMedianPen(Value: TChartPen); begin FMedianPen.Assign(Value); end; procedure TCustomBoxSeries.SetMildOut(Value: TSeriesPointer); begin FMildOut.Assign(Value); end; procedure TCustomBoxSeries.SetExtrOut(Value: TSeriesPointer); begin FExtrOut.Assign(Value); end; procedure TCustomBoxSeries.DoBeforeDrawValues; { 5.02 - new calculation algorithm } var N : Integer; i : Integer; FIqr : Double; FMed : Integer; InvN : Double; { Calculate 1st and 3rd quartile } function Percentile(Const P: double): double; var QQ, OldQQ, U : Double; begin i := 0; QQ := 0.0; OldQQ := 0.0; while QQ < P do begin OldQQ := QQ; QQ := (0.5+i)*InvN; Inc(i); end; U := (P-OldQQ)/(QQ-OldQQ); Result := SampleValues[i-2] + (SampleValues[i-1]-SampleValues[i-2])*U; end; begin inherited; { if custom values are used, or there are no points, skip the recalculation } if (Not FUseCustomValues) and (SampleValues.Count>0) then begin N:=SampleValues.Count; InvN := 1.0/N; { calculate median } FMed := N div 2; if Odd(N) then FMedian := SampleValues[FMed] else FMedian := 0.5* (SampleValues[FMed-1] + SampleValues[FMed]); { calculate Q1 and Q3 } FQuartile1 := Percentile(0.25); FQuartile3 := Percentile(0.75); { calculate IQR } FIqr:=FQuartile3-FQuartile1; FInnerFence1:=FQuartile1-FWhiskerLength*FIqr; FInnerFence3:=FQuartile3+FWhiskerLength*FIqr; { find adjacent points } for i := 0 to N-1 do if FInnerFence1<=SampleValues.Value[i] then Break; FAdjacentPoint1:=i; for i := FMed to N-1 do if FInnerFence3<=SampleValues.Value[i] then Break; FAdjacentPoint3 := i-1; { calculate outer fences } FOuterFence1:=FQuartile1-2*FWhiskerLength*FIqr; FOuterFence3:=FQuartile3+2*FWhiskerLength*FIqr; end; end; procedure TCustomBoxSeries.DrawMark(ValueIndex: Integer; const St: String; APosition: TSeriesMarkPosition); begin with APosition do if IVertical then begin ArrowTo.X:=CalcXPosValue(FPosition); ArrowFrom.X:=ArrowTo.X; LeftTop.X:=ArrowTo.X - (Width div 2); end else begin ArrowTo.Y:=CalcYPosValue(FPosition); ArrowFrom.Y:=ArrowTo.Y; LeftTop.Y:=ArrowTo.Y - (Height div 2); end; inherited; end; procedure TCustomBoxSeries.DrawValue(ValueIndex:Integer); var tmpColor : TColor; tmpVal : Double; tmp : TSeriesPointer; begin tmpVal:=SampleValues.Value[ValueIndex]; { inside inner fences - no point } if (tmpVal>=FInnerFence1) and (tmpVal<=FInnerFence3) then tmp:=nil { mild outlined points } else if ((tmpVal>=FInnerFence3) and (tmpVal<=FOuterFence3)) or ((tmpVal<=FInnerFence1) and (tmpVal>=FOuterFence1)) then tmp:=FMildOut else { extreme outlined points } tmp:=FExtrOut; if Assigned(tmp) then with tmp do if Visible then begin tmpColor:=ValueColor[ValueIndex]; PrepareCanvas(ParentChart.Canvas,tmpColor); if IVertical then Draw(CalcXPosValue(FPosition),CalcYPos(ValueIndex),tmpColor,Style) else Draw(CalcXPos(ValueIndex),CalcYPosValue(FPosition),tmpColor,Style) end; end; procedure TCustomBoxSeries.AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); var t : Integer; n : Integer; begin t:=ParentChart.SeriesCount+1; n:=t*(3+RandomValue(10)); Add(-n); for t:=2 to NumValues-2 do Add(n*t/NumValues); Add(2*n); end; procedure TCustomBoxSeries.PrepareForGallery(IsEnabled:Boolean); var t : Integer; begin inherited; { by default display 2 series} for t:=0 to ParentChart.SeriesCount-1 do if ParentChart.Series[t] is TCustomBoxSeries then with TCustomBoxSeries(ParentChart.Series[t]) do begin FPosition:=t+1; Pointer.HorizSize:=12; MildOut.HorizSize:=3; ExtrOut.VertSize:=3; FillSampleValues(10*(t+1)); end; end; procedure TCustomBoxSeries.DrawAllValues; Var tmp : Integer; tmp1 : Integer; tmpZ : Integer; Function CalcPos(Const Value:Double):Integer; begin if IVertical then result:=CalcYPosValue(Value) else result:=CalcXPosValue(Value); end; Procedure DrawWhisker(AIndex,Pos:Integer); var tmp2 : Integer; begin tmp2:=CalcPos(SampleValues.Value[AIndex]); With ParentChart,Canvas do if View3D then begin if IVertical then begin VertLine3D(tmp1,Pos,tmp2,tmpZ); HorizLine3D(tmp1-tmp,tmp1+tmp,tmp2,tmpZ); end else begin HorizLine3D(Pos,tmp2,tmp1,tmpZ); VertLine3D(tmp2,tmp1-tmp,tmp1+tmp,tmpZ); end; end else if IVertical then begin DoVertLine(tmp1,Pos,tmp2); DoHorizLine(tmp1-tmp,tmp1+tmp,tmp2); end else begin DoHorizLine(Pos,tmp2,tmp1); DoVertLine(tmp2,tmp1-tmp,tmp1+tmp); end; end; var AL,AT,AR,AB, tmpH,tmpV, tmpA1,tmpA2 : Integer; begin inherited; if IVertical then begin tmp:=Pointer.HorizSize; // 6.0 AL:=CalcXPosValue(FPosition)-tmp; AR:=CalcXPosValue(FPosition)+tmp; AT:=CalcYPosValue(FQuartile3); AB:=CalcYPosValue(FQuartile1); tmpA1:=AB; tmpA2:=AT; end else begin tmp:=Pointer.HorizSize; // 6.0 AT:=CalcYPosValue(FPosition)-tmp; AB:=CalcYPosValue(FPosition)+tmp; AR:=CalcXPosValue(FQuartile3); AL:=CalcXPosValue(FQuartile1); tmpA1:=AL; tmpA2:=AR; end; if GetHorizAxis.Inverted then SwapInteger(AL,AR); if GetVertAxis.Inverted then SwapInteger(AT,AB); With ParentChart,Canvas do begin with Pointer do (* box *) if Visible then begin PrepareCanvas(ParentChart.Canvas,Color);; if IVertical then begin tmpV:=(AB-AT) div 2; DrawPointer(Canvas,View3D,AL+tmp-1,AT+tmpV,HorizSize-1,tmpV-1,Brush.Color,Style); end else begin tmpH:=(AR-AL) div 2; DrawPointer(Canvas,View3D,AL+tmpH,AT+tmp-1,tmpH-1,VertSize-1,Brush.Color,Style); end; end; (* median *) if FMedianPen.Visible then begin AssignVisiblePen(FMedianPen); Brush.Style:=bsClear; tmpV:=CalcPos(FMedian); if IVertical then if View3D then HorizLine3D(AL,AR,tmpV,StartZ) else DoHorizLine(AL,AR,tmpV) else if View3D then VertLine3D(tmpV,AT,AB,StartZ) else DoVertLine(tmpV,AT,AB); end; (* whiskers *) if FWhiskerPen.Visible then begin if Pointer.Visible and Pointer.Draw3D then tmpZ:=MiddleZ else tmpZ:=StartZ; AssignVisiblePen(FWhiskerPen); if IVertical then tmp1:=(AL+AR) div 2 else tmp1:=(AT+AB) div 2; DrawWhisker(FAdjacentPoint1,tmpA1); DrawWhisker(FAdjacentPoint3,tmpA2); end; end; end; procedure TCustomBoxSeries.SetParentChart(const Value: TCustomAxisPanel); begin inherited; if not (csDestroying in ComponentState) then begin if Assigned(FExtrOut) then FExtrOut.ParentChart:=Value; if Assigned(FMildOut) then FMildOut.ParentChart:=Value; end; end; class function TCustomBoxSeries.GetEditorClass: String; begin result:='TBoxSeriesEditor'; end; function TCustomBoxSeries.GetBox: TSeriesPointer; begin result:=Pointer; end; procedure TCustomBoxSeries.Assign(Source: TPersistent); begin if Source is TCustomBoxSeries then With TCustomBoxSeries(Source) do begin Self.ExtrOut :=ExtrOut; Self.MedianPen :=MedianPen; Self.MildOut :=MildOut; Self.FPosition :=Position; Self.FWhiskerLength :=FWhiskerLength; Self.WhiskerPen :=WhiskerPen; Self.FUseCustomValues := FUseCustomValues; end; inherited; end; procedure TCustomBoxSeries.SetUseCustomValues(const Value: boolean); begin FUseCustomValues := Value; end; procedure TCustomBoxSeries.SetMedian(const Value: double); begin FMedian := Value; end; procedure TCustomBoxSeries.SetQuartile1(const Value: double); begin FQuartile1 := Value; end; procedure TCustomBoxSeries.SetQuartile3(const Value: double); begin FQuartile3 := Value; end; procedure TCustomBoxSeries.SetInnerFence1(const Value: double); begin FInnerFence1 := Value; end; procedure TCustomBoxSeries.SetInnerFence3(const Value: double); begin FInnerFence3 := Value; end; procedure TCustomBoxSeries.SetOuterFence1(const Value: double); begin FOuterFence1 := Value; end; procedure TCustomBoxSeries.SetOuterFence3(const Value: double); begin FOuterFence3 := Value; end; procedure TCustomBoxSeries.SetAdjacentPoint1(const Value: integer); begin FAdjacentPoint1 := Value; end; procedure TCustomBoxSeries.SetAdjacentPoint3(const Value: integer); begin FAdjacentPoint3 := Value; end; { TBoxSeries } function TBoxSeries.MaxXValue: Double; begin result:=FPosition; end; function TBoxSeries.MinXValue: Double; begin result:=FPosition; end; { THorizBoxSeries} Constructor THorizBoxSeries.Create(AOwner:TComponent); begin inherited; SetHorizontal; IVertical:=False; end; function THorizBoxSeries.MaxYValue: Double; begin result:=FPosition; end; function THorizBoxSeries.MinYValue: Double; begin result:=FPosition; end; initialization RegisterTeeSeries(TBoxSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryBoxPlot, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryStats,2); RegisterTeeSeries(THorizBoxSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryHorizBoxPlot, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryStats,2); finalization UnRegisterTeeSeries([TBoxSeries,THorizBoxSeries]); end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC SQL script engine standard commands } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} {$HPPEMIT LINKUNIT} unit FireDAC.Comp.ScriptCommands; interface {-------------------------------------------------------------------------------} implementation uses System.SysUtils, System.Classes, Data.DB, Data.FmtBCD, System.Variants, FireDAC.Stan.Intf, FireDAC.Stan.Param, FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Error, FireDAC.Stan.Option, FireDAC.Stan.Async, FireDAC.DatS, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Comp.Client, FireDAC.Comp.Script, FireDAC.Comp.BatchMove, FireDAC.Comp.BatchMove.Text, FireDAC.Comp.BatchMove.SQL; type TFDSQLScriptCommand = class; TFDPLSQLScriptCommand = class; TFDRunScriptCommand = class; TFDAcceptScriptCommand = class; TFDConnectScriptCommand = class; TFDDefineScriptCommand = class; TFDDisconnectScriptCommand = class; TFDExecuteScriptCommand = class; TFDExitScriptCommand = class; TFDHostScriptCommand = class; TFDShowTextScriptCommand = class; TFDPauseScriptCommand = class; TFDPromptScriptCommand = class; TFDPrintScriptCommand = class; TFDSetScriptCommand = class; TFDSpoolScriptCommand = class; TFDUndefineScriptCommand = class; TFDVariableScriptCommand = class; TFDHelpScriptCommand = class; TFDRemarkScriptCommand = class; TFDCopyScriptCommand = class; TFDDelimiterScriptCommand = class; TFDIBCreateDBScriptCommand = class; TFDIBDropDBScriptCommand = class; TFDSQLScriptCommand = class(TFDScriptCommand) private FSQL: String; FIsPLSQL: Boolean; procedure DumpParams; procedure DumpTableHeader(ATable: TFDDatSTable; var ALinesPrinted: Integer); function DumpValue(const AValue: Variant; AColumn: TFDDatSColumn): String; procedure DumpTableRows(ATable: TFDDatSTable; var ALinesPrinted: Integer); procedure DumpServerOutput; function PadVal(AColumn: TFDDatSColumn; const AVal: String; APadChar: Char = ' '): String; procedure DumpMacros; function DumpVarBytes(const AVal: Variant): String; procedure LoadBlobFileParams(AParams: TFDParams); public {$IFDEF FireDAC_MONITOR} function Dump: String; override; {$ENDIF} function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; property SQL: String read FSQL; end; TFDPLSQLScriptCommand = class(TFDSQLScriptCommand) public constructor Create(AParser: TFDScriptParser; AEngine: TFDScript); override; {$IFDEF FireDAC_MONITOR} function Dump: String; override; {$ENDIF} end; TFDRunScriptCommand = class(TFDScriptCommand) private FFileName: String; FArguments: TStrings; FUseParentPath: Boolean; procedure InternalExecute(ARealExecute: Boolean); public constructor Create(AParser: TFDScriptParser; AEngine: TFDScript); override; destructor Destroy; override; {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; procedure Validate(); override; property FileName: String read FFileName; property Arguments: TStrings read FArguments; property UseParentPath: Boolean read FUseParentPath; end; TFDAcceptScriptCommand = class(TFDScriptCommand) private FVariable: String; FDataType: TFieldType; FFmt: String; FDef: String; FPrompt: String; FHide: Boolean; public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; property Variable: String read FVariable; property DataType: TFieldType read FDataType; property Fmt: String read FFmt; property Def: String read FDef; property Prompt: String read FPrompt; property Hide: Boolean read FHide; end; TFDConnectScriptCommand = class(TFDScriptCommand) private FConnectString: String; public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; property ConnectString: String read FConnectString; end; TFDDefineScriptCommand = class(TFDScriptCommand) private FMode: Integer; FName: String; FSValue: String; public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; // -1 - show defs, 0 - show def, 1 - set def property Mode: Integer read FMode; property Name: String read FName; property Value: String read FSValue; end; TFDDisconnectScriptCommand = class(TFDScriptCommand) public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; procedure Execute(); override; end; TFDExecuteScriptCommand = class(TFDSQLScriptCommand) private FBlock: String; public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; property Block: String read FBlock; end; TFDExitScriptCommandAction = (eaNone, eaCommit, eaRollback); TFDExitScriptCommand = class(TFDScriptCommand) private FAction: TFDExitScriptCommandAction; public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; procedure Validate(); override; property Action: TFDExitScriptCommandAction read FAction; end; TFDHostScriptCommand = class(TFDScriptCommand) private FCommand: String; public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; property Command: String read FCommand; end; TFDShowTextScriptCommand = class(TFDScriptCommand) private FText: String; public property Text: String read FText; end; TFDPauseScriptCommand = class(TFDShowTextScriptCommand) public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; end; TFDPromptScriptCommand = class(TFDShowTextScriptCommand) public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; end; TFDPrintScriptCommand = class(TFDScriptCommand) private FVars: TStrings; public constructor Create(AParser: TFDScriptParser; AEngine: TFDScript); override; destructor Destroy; override; {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; property Vars: TStrings read FVars; end; TFDSetScriptCommandKind = (skNone, skArraySize, skAutoCommit, skAutoPrint, skBlobFile, skCharacterSet, skClientLib, skCmdSep, skDropNonexistObj, skDefine, skEcho, skEncoding, skFeedback, skHeading, skLineSize, skLong, skParamArraySize, skPageSize, skScan, skServerOutput, skSQLDialect, skTermout, skTiming, skBreakOnError, skIgnoreError, skTrimConsole, skTrimSpool, skVerify); TFDSetScriptCommandItem = class(TObject) private FSetKind: TFDSetScriptCommandKind; FIValue: Integer; FSValue: String; FEchoCommands: TFDScriptEchoCommands; end; TFDSetScriptCommandItems = array of TFDSetScriptCommandItem; TFDSetScriptCommand = class(TFDScriptCommand) private FItems: TFDSetScriptCommandItems; public constructor Create(AParser: TFDScriptParser; AEngine: TFDScript); override; destructor Destroy; override; function AddItem(ASetKind: TFDSetScriptCommandKind; AIValue: Integer = 0; ASValue: String = ''; AEchoCommands: TFDScriptEchoCommands = ecNone): TFDSetScriptCommandItem; {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; procedure Validate(); override; property Items: TFDSetScriptCommandItems read FItems; end; TFDSpoolScriptCommand = class(TFDScriptCommand) private FMode: Integer; FFileName: String; FAppend: Boolean; public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; // -1 - off, 0 - show, 1 - file property Mode: Integer read FMode; property Append: Boolean read FAppend; property FileName: String read FFileName; end; TFDUndefineScriptCommand = class(TFDScriptCommand) private FVars: TStrings; public constructor Create(AParser: TFDScriptParser; AEngine: TFDScript); override; destructor Destroy; override; {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; property Vars: TStrings read FVars; end; TFDVariableScriptCommand = class(TFDScriptCommand) private FMode: Integer; FVariable: String; FDataType: TFieldType; FSize: Integer; FTableSize: Integer; FParamType: TParamType; FValue: String; public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; // -1 - show vars, 0 - show var, 1 - def var property Mode: Integer read FMode; property Variable: String read FVariable; property DataType: TFieldType read FDataType; property Size: Integer read FSize; property TableSize: Integer read FTableSize; property ParamType: TParamType read FParamType; property Value: String read FValue; end; TFDHelpScriptCommand = class(TFDScriptCommand) public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; procedure Execute(); override; end; TFDRemarkScriptCommand = class(TFDScriptCommand) private FText: String; public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; property Text: String read FText; end; TFDCopyScriptCommand = class(TFDScriptCommand) private FBatchMove: TFDBatchMove; FSrcConnection: TFDConnection; FDestConnection: TFDConnection; FSrcConnStr: String; FDestConnStr: String; FConfigFile: String; FConfigParams: String; FLogToSpool: Boolean; procedure DumpServerOutput; public constructor Create(AParser: TFDScriptParser; AEngine: TFDScript); override; destructor Destroy; override; {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; procedure AbortJob(const AWait: Boolean); override; end; TFDDelimiterScriptCommand = class(TFDScriptCommand) private FCmdSep: String; public {$IFDEF FireDAC_MONITOR} function Dump(): String; override; {$ENDIF} class function Help(): String; override; class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; procedure Validate(); override; property CmdSep: String read FCmdSep; end; TFDIBCreateDBScriptCommand = class(TFDScriptCommand) private FDB, FUser, FPwd, FPageSize, FCharset: String; public {$IFDEF FireDAC_MONITOR} function Dump: String; override; {$ENDIF} class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; property DB: String read FDB; property User: String read FUser; property Pwd: String read FPwd; property PageSize: String read FPageSize; property Charset: String read FCharset; end; TFDIBDropDBScriptCommand = class(TFDScriptCommand) public {$IFDEF FireDAC_MONITOR} function Dump: String; override; {$ENDIF} class procedure Keywords(AKwds: TStrings); override; function Parse(const AKwd: String): Boolean; override; procedure Execute(); override; end; {-------------------------------------------------------------------------------} { TFDSQLScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDSQLScriptCommand.Dump: String; begin Result := '<SQL> [' + FSQL + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} function TFDSQLScriptCommand.Parse(const AKwd: String): Boolean; begin FSQL := AKwd; Result := True; end; {-------------------------------------------------------------------------------} function TFDSQLScriptCommand.DumpVarBytes(const AVal: Variant): String; var iLen, i, iText: Integer; b: Byte; sChar: String; begin if not VarIsArray(AVal) then begin Result := VarToStr(AVal); Exit; end; iText := 1; iLen := VarArrayHighBound(AVal, 1); i := 0; SetLength(Result, (iLen + 1) * 4); while i <= iLen do begin b := AVal[i]; if (b < Ord(' ')) and not ((b = 13) or (b = 10) or (b = 9)) then begin sChar := '#' + IntToStr(b); Move(sChar[1], Result[iText], Length(sChar) * SizeOf(Char)); Inc(iText, Length(sChar)); end else begin Result[iText] := Char(b); Inc(iText); end; Inc(i); end; SetLength(Result, iText - 1); end; {-------------------------------------------------------------------------------} function TFDSQLScriptCommand.PadVal(AColumn: TFDDatSColumn; const AVal: String; APadChar: Char): String; var iDispWidth: Integer; begin if AColumn.DataType in [dtAnsiString, dtWideString, dtByteString, dtBlob, dtMemo, dtWideMemo, dtXML, dtHBlob, dtHMemo, dtWideHMemo, dtHBFile] then iDispWidth := Engine.ScriptOptions.MaxStringWidth else iDispWidth := AColumn.DisplayWidth; if iDispWidth < Length(AColumn.Caption) then iDispWidth := Length(AColumn.Caption); if Length(AVal) > iDispWidth then Result := Copy(AVal, 1, iDispWidth - 4) + ' ...' else Result := AVal; if AColumn.DataType in [dtAnsiString, dtWideString, dtByteString, dtBlob, dtMemo, dtWideMemo, dtXML, dtHBlob, dtHMemo, dtWideHMemo, dtHBFile] then Result := Result + StringOfChar(APadChar, iDispWidth - Length(Result)) else Result := StringOfChar(APadChar, iDispWidth - Length(Result)) + Result; end; {-------------------------------------------------------------------------------} procedure TFDSQLScriptCommand.DumpParams; var oCol: TFDDatSColumn; i: Integer; oPar: TFDParam; eDataType: TFDDataType; iSize: LongWord; iPrec: Integer; iScale: Integer; eAttrs: TFDDataAttributes; begin oCol := TFDDatSColumn.Create; try for i := 0 to EngineIntf.CommandIntf.Params.Count - 1 do begin oPar := EngineIntf.CommandIntf.Params[i]; EngineIntf.CommandIntf.Options.FormatOptions.FieldDef2ColumnDef( oPar.DataType, oPar.Size, oPar.Precision, oPar.NumericScale, eDataType, iSize, iPrec, iScale, eAttrs); oCol.Caption := oPar.Name; oCol.DataType := eDataType; oCol.Size := iSize; oCol.Precision := iPrec; oCol.Scale := iScale; oCol.Attributes := eAttrs; EngineIntf.ConPut(oPar.DisplayName + ':' + DumpValue(oPar.Value, oCol), soParam); end; finally FDFree(oCol); end; end; {-------------------------------------------------------------------------------} procedure TFDSQLScriptCommand.DumpTableHeader(ATable: TFDDatSTable; var ALinesPrinted: Integer); var c: Integer; s: String; begin s := ''; for c := 0 to ATable.Columns.Count - 1 do begin if c > 0 then s := s + ' '; s := s + PadVal(ATable.Columns[c], ATable.Columns[c].Name); end; EngineIntf.ConPut(s, soData); Inc(ALinesPrinted); s := ''; for c := 0 to ATable.Columns.Count - 1 do begin if c > 0 then s := s + ' '; s := s + PadVal(ATable.Columns[c], '', '-'); end; EngineIntf.ConPut(s, soData); Inc(ALinesPrinted); end; {-------------------------------------------------------------------------------} function TFDSQLScriptCommand.DumpValue(const AValue: Variant; AColumn: TFDDatSColumn): String; var dt: TDateTime; begin if AColumn.DataType in [dtByteString, dtBlob, dtHBlob, dtHBFile] then Result := PadVal(AColumn, DumpVarBytes(AValue)) else if AColumn.DataType <> dtTime then Result := PadVal(AColumn, VarToStr(AValue)) else begin dt := VarAsType(AValue, varDate); // Delphi does not support negative time value if dt < 0 then Result := PadVal(AColumn, '-' + TimeToStr(dt)) else Result := PadVal(AColumn, TimeToStr(dt)); end; end; {-------------------------------------------------------------------------------} procedure TFDSQLScriptCommand.DumpTableRows(ATable: TFDDatSTable; var ALinesPrinted: Integer); var i: Integer; c: Integer; s: String; oCol: TFDDatSColumn; oRow: TFDDatSRow; begin for i := 0 to ATable.Rows.Count - 1 do begin if (ALinesPrinted = 0) and Engine.ScriptOptions.ColumnHeadings and (Engine.ScriptOptions.PageSize > 0) then DumpTableHeader(ATable, ALinesPrinted); s := ''; for c := 0 to ATable.Columns.Count - 1 do begin oCol := ATable.Columns[c]; oRow := ATable.Rows[i]; if c > 0 then s := s + ' '; s := s + DumpValue(oRow.GetData(c), oCol); end; EngineIntf.ConPut(s, soData); Inc(ALinesPrinted); if ALinesPrinted >= Engine.ScriptOptions.PageSize - 1 then begin EngineIntf.ConPut('', soSeparator); ALinesPrinted := 0; end; end; end; {-------------------------------------------------------------------------------} procedure TFDSQLScriptCommand.DumpServerOutput; var i: Integer; begin if not (EngineIntf.ConnectionIntf.Options.ResourceOptions as TFDTopResourceOptions).ServerOutput or (EngineIntf.ConnectionIntf.Messages = nil) or (EngineIntf.ConnectionIntf.Messages.ErrorCount = 0) then Exit; for i := 0 to EngineIntf.ConnectionIntf.Messages.ErrorCount - 1 do EngineIntf.ConPut(EngineIntf.ConnectionIntf.Messages[i].Message, soServerOutput); EngineIntf.ConPut('', soSeparator); end; {-------------------------------------------------------------------------------} procedure TFDSQLScriptCommand.DumpMacros; var oSrc, oDest: TFDStringList; i: Integer; begin oSrc := TFDStringList.Create; oDest := TFDStringList.Create; try oSrc.Text := AdjustLineBreaks(FSQL, tlbsCRLF); oDest.Text := AdjustLineBreaks(EngineIntf.CommandIntf.SQLText, tlbsCRLF); for i := 0 to oSrc.Count - 1 do if oSrc[i] <> oDest[i] then begin EngineIntf.ConPut(Format('old %d:%s', [i + 1, oSrc[i]]), soMacro); EngineIntf.ConPut(Format('new %d:%s', [i + 1, oDest[i]]), soMacro); end; finally FDFree(oSrc); FDFree(oDest); end; end; {-------------------------------------------------------------------------------} procedure TFDSQLScriptCommand.LoadBlobFileParams(AParams: TFDParams); var i: Integer; s: String; oStr: TStream; iPos, iLen: LongWord; oText: TFDTextFile; pData: Pointer; begin for i := 0 to AParams.Count - 1 do begin s := AParams[i].Name; if (Length(s) = 18) and FDInSet(s[1], ['h', 'H']) and (s[10] = '_') then begin iPos := StrToInt('$' + Copy(s, 2, 8)); iLen := StrToInt('$' + Copy(s, 11, 8)); oText := nil; EngineIntf.GetText(Engine.ScriptOptions.BlobFile, smRead, oText); try oStr := oText.Stream; oStr.Position := iPos; pData := AParams[i].SetBlobRawData(iLen, nil, 0); if iLen > 0 then oStr.ReadBuffer(pData^, iLen); finally EngineIntf.ReleaseText(Engine.ScriptOptions.BlobFile, smRead, oText); end; end; end; end; {-------------------------------------------------------------------------------} procedure TFDSQLScriptCommand.Execute(); var iRows: LongWord; iLinesPrinted: Integer; dwStartTime: LongWord; dwExecTime: LongWord; lOpen: Boolean; sFeedback: String; eCmdKind: TFDPhysCommandKind; lWasRowset: Boolean; oExc: EFDException; oCmd: IFDPhysCommand; oFtch: TFDFetchOptions; oRes: TFDResourceOptions; begin EngineIntf.CheckCommand; EngineIntf.CheckStartTransaction; oCmd := EngineIntf.CommandIntf; oCmd.Disconnect; oFtch := oCmd.Options.FetchOptions; oFtch.AutoClose := False; oFtch.AutoFetchAll := afAll; oFtch.Items := oFtch.Items - [fiMeta]; oRes := oCmd.Options.ResourceOptions; if oRes.CmdExecMode = amAsync then oRes.CmdExecMode := amBlocking; oRes.DirectExecute := True; oRes.MacroCreate := False; oRes.MacroExpand := Engine.ScriptOptions.MacroExpand; oRes.Persistent := False; lOpen := Engine.ScriptOptions.ParamArraySize = 1; lWasRowset := False; dwExecTime := 0; dwStartTime := TThread.GetTickCount(); eCmdKind := skUnknown; try try try oCmd.CommandText := FSQL; oCmd.Params.AssignValues(Engine.Params); if Engine.ScriptOptions.BlobFile <> '' then LoadBlobFileParams(oCmd.Params); oCmd.Prepare; eCmdKind := oCmd.CommandKind; if Engine.ScriptOptions.Verify then DumpMacros; while oCmd.State <> csInactive do begin if lOpen then begin iRows := 0; iLinesPrinted := 0; oCmd.Open; if oCmd.State <> csOpen then Break; lWasRowset := True; oCmd.Define(EngineIntf.Table, mmReset); repeat EngineIntf.ConLockUpdate; try EngineIntf.Table.Clear; oCmd.Fetch(EngineIntf.Table, False); Inc(iRows, EngineIntf.Table.Rows.Count); DumpTableRows(EngineIntf.Table, iLinesPrinted); finally EngineIntf.ConUnlockUpdate; end; until EngineIntf.Table.Rows.Count = 0; if iLinesPrinted > 0 then EngineIntf.ConPut('', soSeparator); if Engine.ScriptOptions.FeedbackCommands then if iRows = 0 then EngineIntf.ConPut('no rows selected.', soCommand) else if iRows = 1 then EngineIntf.ConPut('1 row selected.', soCommand) else EngineIntf.ConPut(IntToStr(iRows) + ' rows selected.', soCommand); end else oCmd.Execute(Engine.ScriptOptions.ParamArraySize, 0); oCmd.NextRecordSet := True; oCmd.Close; lOpen := True; end; Engine.Params.AssignValues(oCmd.Params, [ptOutput .. ptResult]); finally dwExecTime := TThread.GetTickCount() - dwStartTime; if Engine.ScriptOptions.RaisePLSQLErrors and (EngineIntf.ConnectionIntf.Messages <> nil) and // ORA-24344: Compiled with errors (EngineIntf.ConnectionIntf.Messages[0].ErrorCode = 24344) then begin oExc := nil; EngineIntf.ConnectionIntf.Messages.Duplicate(oExc); raise oExc; end; if (EngineIntf.ConnectionIntf <> nil) and (EngineIntf.ConnectionIntf.Options.ResourceOptions as TFDTopResourceOptions).ServerOutput then DumpServerOutput; end; finally EngineIntf.Table.Reset; oCmd.AbortJob(True); oCmd.NextRecordSet := False; oCmd.Disconnect; end; except on E: EFDDBEngineException do begin if (E.Kind = ekObjNotExists) and Engine.ScriptOptions.DropNonexistObj and ((eCmdKind = skUnknown) and (oCmd.CommandKind = skDrop) or (eCmdKind = skDrop)) then begin if Engine.ScriptOptions.FeedbackCommands then if E[0].ObjName <> '' then EngineIntf.ConPut('[' + E[0].ObjName + '] does not exists.', soCommand) else EngineIntf.ConPut('Object does not exists. ', soCommand); end else raise; end; end; EngineIntf.CheckCommit(False); if Engine.ScriptOptions.FeedbackCommands then begin sFeedback := ''; if not lWasRowset then if oCmd.RowsAffectedReal and not (eCmdKind in [skCreate, skAlter, skDrop, skStartTransaction, skCommit, skRollback, skSet, skSetSchema]) then if oCmd.RowsAffected = 0 then sFeedback := 'no rows processed' else if oCmd.RowsAffected = 1 then sFeedback := '1 row processed' else sFeedback := IntToStr(oCmd.RowsAffected) + ' rows processed' else sFeedback := 'Ok'; if Engine.ScriptOptions.Timing then begin if sFeedback <> '' then sFeedback := sFeedback + ' '; sFeedback := sFeedback + Format('[%.2d:%.2d:%.2d.%.3d]', [ (dwExecTime div 3600000) mod 60, (dwExecTime div 60000) mod 60, (dwExecTime div 1000) mod 60, dwExecTime mod 1000]); end; if sFeedback <> '' then begin sFeedback := sFeedback + '.'; EngineIntf.ConPut(sFeedback, soCommand); end; end; if Engine.ScriptOptions.AutoPrintParams then DumpParams; // EngineIntf.ConPut(''); end; {-------------------------------------------------------------------------------} { TFDPLSQLScriptCommand } {-------------------------------------------------------------------------------} constructor TFDPLSQLScriptCommand.Create(AParser: TFDScriptParser; AEngine: TFDScript); begin inherited Create(AParser, AEngine); FIsPLSQL := True; end; {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDPLSQLScriptCommand.Dump: String; begin Result := '<PL/SQL> [' + FSQL + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} { TFDRunScriptCommand } {-------------------------------------------------------------------------------} constructor TFDRunScriptCommand.Create(AParser: TFDScriptParser; AEngine: TFDScript); begin inherited Create(AParser, AEngine); FArguments := TFDStringList.Create; end; {-------------------------------------------------------------------------------} destructor TFDRunScriptCommand.Destroy; begin FDFreeAndNil(FArguments); inherited Destroy; end; {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDRunScriptCommand.Dump(): String; var i: Integer; begin if not FUseParentPath then Result := '<@> [' + FFileName + ']' else Result := '<@@> [' + FFileName + ']'; for i := 0 to FArguments.Count - 1 do Result := Result + ' [' + FArguments[i] + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDRunScriptCommand.Help(): String; begin Result := '(@ | @@ | START | INput) <script> <arguments> - starts execution of specified script'; end; {-------------------------------------------------------------------------------} class procedure TFDRunScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('@'); AKwds.Add('@@'); AKwds.Add('START'); AKwds.Add('INput'); end; {-------------------------------------------------------------------------------} function TFDRunScriptCommand.Parse(const AKwd: String): Boolean; var s: String; begin if not Parser.WasBeginningOfLine then begin Result := False; Exit; end; FUseParentPath := True; if Parser.Ch = '@' then Parser.GetChar else FUseParentPath := False; FFileName := Parser.GetString(); while True do begin s := Parser.GetString(); if s = '' then Break; FArguments.Add(s); end; Result := True; end; {-------------------------------------------------------------------------------} procedure TFDRunScriptCommand.InternalExecute(ARealExecute: Boolean); var oParser: TFDScriptParser; oArgs: TFDStringList; oText: TFDTextFile; sFileName: String; begin if (ExtractFilePath(FFileName) = '') and FUseParentPath then sFileName := ExtractFilePath(Parser.FileName) + FFileName else sFileName := FFileName; sFileName := EngineIntf.ExpandString(sFileName); oText := nil; oArgs := nil; EngineIntf.GetText(sFileName, smRead, oText); if oText <> nil then try oParser := TFDScriptParser.Create(sFileName, Self, oText, Engine.ScriptOptions); try if Arguments.Count > 0 then begin oArgs := TFDStringList.Create; oArgs.SetStrings(Engine.Arguments); Engine.Arguments.SetStrings(Arguments); end; oParser.TotalSize := Parser.TotalSize; if ARealExecute then EngineIntf.ExecuteAll(oParser) else EngineIntf.ValidateAll(oParser); finally if oArgs <> nil then begin Engine.Arguments.SetStrings(oArgs); FDFree(oArgs); end; Parser.TotalSize := oParser.TotalSize; FDFree(oParser); end; finally EngineIntf.ReleaseText(sFileName, smRead, oText); end; end; {-------------------------------------------------------------------------------} procedure TFDRunScriptCommand.Execute(); begin InternalExecute(True); end; {-------------------------------------------------------------------------------} procedure TFDRunScriptCommand.Validate(); begin InternalExecute(False); end; {-------------------------------------------------------------------------------} { TFDAcceptScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDAcceptScriptCommand.Dump(): String; begin Result := '<accept> [var="' + Variable + '", dt=' + FieldTypeNames[DataType]; if Fmt <> '' then Result := Result + ', fmt="' + Fmt + '"'; if Def <> '' then Result := Result + ', def="' + Def + '"'; if Prompt <> '' then Result := Result + ', pr="' + Prompt + '"'; if Hide then Result := Result + ', hide'; Result := Result + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDAcceptScriptCommand.Help(): String; begin Result := 'ACCept <var> (NUMber|CHAR|DATE) [FORmat <fmt>] [DEFault <def>]'#13#10 + ' [PROmpt ''<prompt>'' | NOPRompt] [HIDE] - asks user to enter a variable value'; end; {-------------------------------------------------------------------------------} class procedure TFDAcceptScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('ACCept'); end; {-------------------------------------------------------------------------------} function TFDAcceptScriptCommand.Parse(const AKwd: String): Boolean; var ucS: String; begin FVariable := Parser.GetIdentifier; if Variable = '' then FDException(Engine, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrAccMustSpecVar, []); FDataType := ftUnknown; while True do begin ucS := Parser.GetUCWord; if ucS = '' then Break; if FDKeywordMatch(ucS, 'NUMBER', 3) then FDataType := ftFmtBCD else if FDKeywordMatch(ucS, 'CHAR', 4) then FDataType := ftString else if FDKeywordMatch(ucS, 'DATE', 4) then FDataType := ftDateTime else if FDKeywordMatch(ucS, 'FORMAT', 3) then FFmt := Parser.GetString else if FDKeywordMatch(ucS, 'DEFAULT', 3) then FDef := Parser.GetString else if FDKeywordMatch(ucS, 'PROMPT', 3) then FPrompt := Parser.GetString else if FDKeywordMatch(ucS, 'NOPROMPT', 4) then FPrompt := '' else if FDKeywordMatch(ucS, 'HIDE', 4) then FHide := True; end; Result := True; end; {-------------------------------------------------------------------------------} procedure TFDAcceptScriptCommand.Execute(); var oPar: TFDParam; sVal: String; rBcd: TBcd; rFS: TFormatSettings; begin oPar := Engine.Params.ParamByName(EngineIntf.ExpandString(Variable)); sVal := oPar.AsString; if sVal = '' then sVal := Def; EngineIntf.ConGet(EngineIntf.ExpandString(Prompt), sVal); sVal := EngineIntf.ExpandString(sVal); if DataType <> ftUnknown then begin oPar.Clear(); oPar.DataType := DataType; end; case oPar.DataType of ftFmtBCD: begin FDStr2BCD(PChar(sVal), Length(sVal), rBcd, FormatSettings.DecimalSeparator); oPar.AsFmtBCD := rBcd; end; ftFloat: oPar.AsFloat := FDStr2Float(sVal, FormatSettings.DecimalSeparator); ftString: oPar.AsString := sVal; ftDateTime: if Fmt = '' then oPar.AsDateTime := StrToDateTime(sVal) else begin rFS := TFormatSettings.Create; rFS.ShortDateFormat := EngineIntf.ExpandString(Fmt); oPar.AsDateTime := StrToDateTime(sVal, rFS); end; else ASSERT(False); end; end; {-------------------------------------------------------------------------------} { TFDConnectScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDConnectScriptCommand.Dump: String; begin Result := '<connect> [' + FConnectString + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDConnectScriptCommand.Help(): String; begin Result := 'CONnect <FireDAC connection string> - connects to the specified DBMS'; end; {-------------------------------------------------------------------------------} class procedure TFDConnectScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('CONnect'); end; {-------------------------------------------------------------------------------} function TFDConnectScriptCommand.Parse(const AKwd: String): Boolean; begin FConnectString := Parser.GetLine(); Result := True; end; {-------------------------------------------------------------------------------} procedure TFDConnectScriptCommand.Execute(); var oMAIntf: IFDMoniAdapter; sName: String; vValue: Variant; eKind: TFDMoniAdapterItemKind; i: Integer; begin EngineIntf.CloseConnection; try EngineIntf.OpenConnection(EngineIntf.ExpandString(ConnectString)); except on E: Exception do EngineIntf.ConPut(E.Message, soError); end; if (EngineIntf.ConnectionIntf <> nil) and (EngineIntf.ConnectionIntf.State = csConnected) then begin EngineIntf.ConPut('Connected to', soConnect); EngineIntf.UpdateCommandSeparator; if Engine.ScriptOptions.FeedbackCommands then begin oMAIntf := EngineIntf.ConnectionIntf as IFDMoniAdapter; for i := 0 to oMAIntf.ItemCount - 1 do begin oMAIntf.GetItem(i, sName, vValue, eKind); if eKind = ikSessionInfo then EngineIntf.ConPut(sName + ' = ' + VarToStr(vValue), soConnect); end; end; end else EngineIntf.ConPut('Not logged on', soConnect); end; {-------------------------------------------------------------------------------} { TFDDefineScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDDefineScriptCommand.Dump: String; begin Result := '<define> ['; case FMode of -1: Result := Result + 'show all'; 0: Result := Result + 'show def="' + FName + '"'; 1: Result := Result + 'set def="' + FName + '", val="' + FSValue + '"'; end; Result := Result + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDDefineScriptCommand.Help(): String; begin Result := 'DEFine [<name> | <name>=<value>] - prints all, the specified or sets the specified macro value'; end; {-------------------------------------------------------------------------------} class procedure TFDDefineScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('DEFine'); end; {-------------------------------------------------------------------------------} function TFDDefineScriptCommand.Parse(const AKwd: String): Boolean; begin FName := Parser.GetIdentifier(); if FName = '' then FMode := -1 else begin Parser.SkipWS; if Parser.Ch = '=' then begin FMode := 1; Parser.GetChar; FSValue := Parser.GetString(); if FSValue = '' then FDException(Engine, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrDefReqValue, []); end else begin FMode := 0; Parser.UnGetChar; end; end; Result := True; end; {-------------------------------------------------------------------------------} procedure TFDDefineScriptCommand.Execute(); var i: Integer; oMac: TFDMacro; begin case FMode of -1: for i := 0 to Engine.Macros.Count - 1 do EngineIntf.ConPut('DEFINE ' + Engine.Macros[i].Name + ' = ' + Engine.Macros[i].AsRaw, soMacro); 0: begin oMac := Engine.Macros.FindMacro(EngineIntf.ExpandString(Name)); if oMac = nil then EngineIntf.ConPut('Symbol ' + Name + ' is UNDEFINED', soMacro) else EngineIntf.ConPut('DEFINE ' + oMac.Name + ' = ' + oMac.AsRaw, soMacro); end; 1: begin oMac := Engine.Macros.FindMacro(EngineIntf.ExpandString(Name)); if oMac = nil then begin oMac := TFDMacro(Engine.Macros.Add); oMac.Name := EngineIntf.ExpandString(Name); end; oMac.AsRaw := EngineIntf.ExpandString(Value); end; end; end; {-------------------------------------------------------------------------------} { TFDDisconnectScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDDisconnectScriptCommand.Dump: String; begin Result := '<disconnect>'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDDisconnectScriptCommand.Help(): String; begin Result := 'DISconnect - disconnects from the DBMS'; end; {-------------------------------------------------------------------------------} class procedure TFDDisconnectScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('DISconnect'); end; {-------------------------------------------------------------------------------} procedure TFDDisconnectScriptCommand.Execute(); begin EngineIntf.CloseConnection; EngineIntf.ConPut('Not logged on', soConnect); end; {-------------------------------------------------------------------------------} { TFDExecuteScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDExecuteScriptCommand.Dump: String; begin Result := '<execute> [' + FBlock + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDExecuteScriptCommand.Help(): String; begin Result := '(EXECute | CALL) <procedure> - executes the specified stored procedure'; end; {-------------------------------------------------------------------------------} class procedure TFDExecuteScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('EXECute'); AKwds.Add('CALL'); end; {-------------------------------------------------------------------------------} function TFDExecuteScriptCommand.Parse(const AKwd: String): Boolean; begin // Ignore ADS EXECUTE PROCEDURE, FB EXECUTE BLOCK, PgSQL and MSSQL EXECUTE if FDKeywordMatch(AKwd, 'EXECUTE', 4) and (EngineIntf.RDBMSKind in [TFDRDBMSKinds.Advantage, TFDRDBMSKinds.Firebird, TFDRDBMSKinds.PostgreSQL, TFDRDBMSKinds.MSSQL, TFDRDBMSKinds.Informix]) then Result := False // Ignore NexusDB, DB2 and MySQL CALL else if FDKeywordMatch(AKwd, 'CALL', 4) and (EngineIntf.RDBMSKind in [TFDRDBMSKinds.NexusDB, TFDRDBMSKinds.DB2, TFDRDBMSKinds.MySQL]) then Result := False else begin FBlock := Parser.GetLine(); Result := True; end; end; {-------------------------------------------------------------------------------} procedure TFDExecuteScriptCommand.Execute(); var oGen: IFDPhysCommandGenerator; begin EngineIntf.CheckCommand; EngineIntf.ConnectionIntf.CreateCommandGenerator(oGen, nil); FSQL := oGen.GenerateCall(FBlock); inherited Execute(); end; {-------------------------------------------------------------------------------} { TFDExitScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDExitScriptCommand.Dump(): String; begin case FAction of eaCommit: Result := '<commit, exit>'; eaRollback: Result := '<rollback, exit>'; eaNone: Result := '<exit>'; end; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDExitScriptCommand.Help(): String; begin Result := 'EXIT - stops script execution and commit changes'#13#10 + 'QUIT - stops script execution and rollback changes'#13#10 + 'STOP - stops script execution'; end; {-------------------------------------------------------------------------------} class procedure TFDExitScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('EXIT'); AKwds.Add('QUIT'); AKwds.Add('STOP'); end; {-------------------------------------------------------------------------------} function TFDExitScriptCommand.Parse(const AKwd: String): Boolean; begin if FDKeywordMatch(AKwd, 'EXIT', 4) then FAction := eaCommit else if FDKeywordMatch(AKwd, 'QUIT', 4) then FAction := eaRollback else FAction := eaNone; Result := True; end; {-------------------------------------------------------------------------------} procedure TFDExitScriptCommand.Execute(); begin if EngineIntf.ConnectionIntf <> nil then case FAction of eaCommit: while EngineIntf.ConnectionIntf.Transaction.Active do EngineIntf.ConnectionIntf.Transaction.Commit; eaRollback: while EngineIntf.ConnectionIntf.Transaction.Active do EngineIntf.ConnectionIntf.Transaction.Rollback; end; Engine.Finished := True; end; {-------------------------------------------------------------------------------} procedure TFDExitScriptCommand.Validate; begin Engine.Finished := True; end; {-------------------------------------------------------------------------------} { TFDHostScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDHostScriptCommand.Dump(): String; begin Result := '<host> [' + Command + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDHostScriptCommand.Help(): String; begin Result := '(HOst | !! | SHELL) <command> - executes host command'; end; {-------------------------------------------------------------------------------} class procedure TFDHostScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('HOst'); AKwds.Add('SHELL'); AKwds.Add('!!'); end; {-------------------------------------------------------------------------------} function TFDHostScriptCommand.Parse(const AKwd: String): Boolean; begin FCommand := Parser.GetLine(); Result := True; end; {-------------------------------------------------------------------------------} procedure TFDHostScriptCommand.Execute(); begin EngineIntf.ExecuteHostCommand(EngineIntf.ExpandString(Command)); end; {-------------------------------------------------------------------------------} { TFDPauseScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDPauseScriptCommand.Dump(): String; begin Result := '<pause> [' + Text + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDPauseScriptCommand.Help(): String; begin Result := 'PAUse <prompt> - pauses script execution'; end; {-------------------------------------------------------------------------------} class procedure TFDPauseScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('PAUse'); end; {-------------------------------------------------------------------------------} function TFDPauseScriptCommand.Parse(const AKwd: String): Boolean; begin FText := Parser.GetLine(); Result := True; end; {-------------------------------------------------------------------------------} procedure TFDPauseScriptCommand.Execute(); begin EngineIntf.ConPause(EngineIntf.ExpandString(Text)); end; {-------------------------------------------------------------------------------} { TFDPromptScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDPromptScriptCommand.Dump(): String; begin Result := '<prompt> [' + Text + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDPromptScriptCommand.Help(): String; begin Result := 'PROmpt <prompt> - prints specified text'; end; {-------------------------------------------------------------------------------} class procedure TFDPromptScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('PROmpt'); end; {-------------------------------------------------------------------------------} function TFDPromptScriptCommand.Parse(const AKwd: String): Boolean; begin FText := Parser.GetLine(); Result := True; end; {-------------------------------------------------------------------------------} procedure TFDPromptScriptCommand.Execute(); begin EngineIntf.ConPut(EngineIntf.ExpandString(Text), soUserOutput); end; {-------------------------------------------------------------------------------} { TFDPrintScriptCommand } {-------------------------------------------------------------------------------} constructor TFDPrintScriptCommand.Create(AParser: TFDScriptParser; AEngine: TFDScript); begin inherited Create(AParser, AEngine); FVars := TFDStringList.Create; end; {-------------------------------------------------------------------------------} destructor TFDPrintScriptCommand.Destroy; begin FDFreeAndNil(FVars); inherited Destroy; end; {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDPrintScriptCommand.Dump(): String; var i: Integer; begin Result := '<print> ['; for i := 0 to Vars.Count - 1 do begin if i > 0 then Result := Result + ', '; Result := Result + IntToStr(i) + '="' + Vars[i] + '"'; end; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDPrintScriptCommand.Help(): String; begin Result := 'PRInt <var 1> [..., <varN>] - prints value of the specified variables'; end; {-------------------------------------------------------------------------------} class procedure TFDPrintScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('PRInt'); end; {-------------------------------------------------------------------------------} function TFDPrintScriptCommand.Parse(const AKwd: String): Boolean; begin Result := not ((EngineIntf.RDBMSKind = TFDRDBMSKinds.MSSQL) and (UpperCase(AKwd) = 'PRINT')); if Result then Vars.AddStrings(Parser.GetLine().Split([',', ' ', #9], TStringSplitOptions.ExcludeEmpty)); end; {-------------------------------------------------------------------------------} procedure TFDPrintScriptCommand.Execute(); var i, j, iWidth: Integer; oPar: TFDParam; lAlignRight: Boolean; function PadStr(const AStr: String; AWidth: Integer; ARight: Boolean): String; begin if ARight then Result := Copy(StringOfChar(' ', AWidth - Length(AStr)) + AStr, 1, AWidth) else Result := Copy(AStr + StringOfChar(' ', AWidth - Length(AStr)), 1, AWidth); end; begin for i := 0 to Vars.Count - 1 do try oPar := Engine.Params.ParamByName(EngineIntf.ExpandString(Vars[i])); iWidth := 20; lAlignRight := False; case oPar.DataType of ftFmtBCD, ftBCD, ftCurrency, ftFloat, ftInteger, ftSmallint, ftWord, ftAutoInc, ftLargeint: begin if oPar.Precision > 0 then iWidth := oPar.Precision; lAlignRight := True; end; ftWideString, ftString: if oPar.Size > 0 then iWidth := oPar.Size; end; EngineIntf.ConPut(PadStr(oPar.Name, iWidth, lAlignRight), soParam); EngineIntf.ConPut(StringOfChar('-', iWidth), soParam); EngineIntf.ConPut(PadStr(oPar.AsString, iWidth, lAlignRight), soParam); if oPar.ArraySize > 1 then for j := 1 to oPar.ArraySize - 1 do EngineIntf.ConPut(Format(' [%d]: %s', [j, PadStr(oPar.AsStrings[j], iWidth, lAlignRight)]), soParam); EngineIntf.ConPut('', soSeparator); except on E: Exception do EngineIntf.ConPut(E.Message, soError); end; end; {-------------------------------------------------------------------------------} { TFDSetScriptCommand } {-------------------------------------------------------------------------------} constructor TFDSetScriptCommand.Create(AParser: TFDScriptParser; AEngine: TFDScript); begin inherited Create(AParser, AEngine); end; {-------------------------------------------------------------------------------} destructor TFDSetScriptCommand.Destroy; var i: Integer; begin for i := 0 to Length(FItems) - 1 do FDFree(FItems[i]); inherited Destroy; end; {-------------------------------------------------------------------------------} function TFDSetScriptCommand.AddItem(ASetKind: TFDSetScriptCommandKind; AIValue: Integer; ASValue: String; AEchoCommands: TFDScriptEchoCommands): TFDSetScriptCommandItem; begin SetLength(FItems, Length(FItems) + 1); Result := TFDSetScriptCommandItem.Create; FItems[Length(FItems) - 1] := Result; Result.FSetKind := ASetKind; Result.FIValue := AIValue; Result.FSValue := ASValue; Result.FEchoCommands := AEchoCommands; end; {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDSetScriptCommand.Dump(): String; var s: String; i: Integer; oItem: TFDSetScriptCommandItem; begin Result := '<set> ['; s := ''; for i := 0 to Length(FItems) - 1 do begin if i > 0 then s := s + ', '; oItem := FItems[i]; case oItem.FSetKind of skNone: ; skArraySize: s := s + 'arraysize=' + IntToStr(oItem.FIValue); skAutoCommit: s := s + 'autocommit=' + IntToStr(oItem.FIValue); skAutoPrint: s := s + 'autoprint=' + IntToStr(oItem.FIValue); skBlobFile: s := s + 'blobfile=' + oItem.FSValue; skCharacterSet: s := s + 'characterset=' + oItem.FSValue; skClientLib: s := s + 'clientlib=' + oItem.FSValue; skCmdSep: s := s + 'cmdsep=' + oItem.FSValue; skDefine: s := s + 'define=' + IntToStr(oItem.FIValue); skEcho: s := s + 'echo=' + IntToStr(oItem.FIValue); skEncoding: s := s + 'encoding=' + IntToStr(oItem.FIValue); skFeedback: s := s + 'feedback=' + IntToStr(oItem.FIValue); skHeading: s := s + 'heading=' + IntToStr(oItem.FIValue); skLineSize: s := s + 'linesize=' + IntToStr(oItem.FIValue); skLong: s := s + 'long=' + IntToStr(oItem.FIValue); skParamArraySize: s := s + 'paramarraysize=' + IntToStr(oItem.FIValue); skPageSize: s := s + 'pagesize=' + IntToStr(oItem.FIValue); skScan: s := s + 'scan=' + IntToStr(oItem.FIValue); skServerOutput: s := s + 'serveroutput=' + IntToStr(oItem.FIValue); skSQLDialect: s := s + 'sqldialect=' + IntToStr(oItem.FIValue); skTermout: s := s + 'termout=' + IntToStr(oItem.FIValue); skTiming: s := s + 'timing=' + IntToStr(oItem.FIValue); skBreakOnError: s := s + 'breakonerror=' + IntToStr(oItem.FIValue); skIgnoreError: s := s + 'ignoreerror=' + IntToStr(oItem.FIValue); skTrimConsole: s := s + 'trimconsole=' + IntToStr(oItem.FIValue); skTrimSpool: s := s + 'trimspool=' + IntToStr(oItem.FIValue); skVerify: s := s + 'verify=' + IntToStr(oItem.FIValue); end; end; Result := Result + s + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDSetScriptCommand.Help(): String; // show begin Result := 'SET - sets script execution mode'#13#10 + ' ARRAY <value> - specifies the rowset size'#13#10 + ' AUTOcommit OFF|ON|<value> - set auto commit off, on or to commit each N commands'#13#10+ ' AUTOPrint OFF|ON - show variable values after command execution'#13#10 + ' BREAK OFF|ON - stop script execution on error'#13#10 + ' (CHARACTERset | NAMES) <value> - specifies client character set'#13#10 + ' CLIENTlib <value> - specifies driver CLI library'#13#10 + ' (CMDSeparator | TERMinator) <value> - specifies commands separator. TERM is for IB/FB only'#13#10 + ' (DEFine | SCAN) OFF|ON - controls macros expansion'#13#10 + ' DROPnonexistent ON|OFF - allow to drop non existent objects'#13#10 + ' ECHO OFF|(ON [SQL|ALL] [TRIM 50|<value>]) - shows command text before it execution with optional trimming'#13#10 + ' ENCoding ANSI | UTF8 | UTF16 - sets text file encoding'#13#10 + ' (FEEDback|COUNT) 6|<value>|OFF|ON - show feedback after command execution'#13#10 + ' HEAding OFF|ON - show column names for dataset'#13#10 + ' LINESize 0|<value> - set line width'#13#10 + ' (WIDTH|LONG) 80|<value> - show specified amount of characters for character or binary values'#13#10 + ' PAGESize 24|<value> - set the page size when printing dataset'#13#10 + ' PARAMARRAY 1|<value> - specifies the size of parameters array'#13#10 + ' SERVEROUTPUT OFF|(ON [SIZE <value>]) - show server output after command execution'#13#10 + ' SQL DIALECT <value> - specifies the SQL dialect. For IB/FB connection only'#13#10 + ' (TERMout|CONsole) OFF|ON - output command execution result to console'#13#10 + ' TIMing OFF|ON - show command executin time'#13#10 + ' TRIMout OFF|ON - trim spaces from strings at console output'#13#10 + ' TRIMSpool ON|OFF - trim spaces from strings at spool output'#13#10 + ' VERify OFF|ON - show SQL command before execution with substituted macros'; end; {-------------------------------------------------------------------------------} class procedure TFDSetScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('SET'); end; {-------------------------------------------------------------------------------} function TFDSetScriptCommand.Parse(const AKwd: String): Boolean; var ucS, s: String; iLastBmk: Integer; oItem: TFDSetScriptCommandItem; lEQREquired: Boolean; begin while True do begin ucS := Parser.GetUCWord; if ucS = '' then Break; Parser.SkipWS; iLastBmk := Parser.GetBookmark; lEQREquired := False; if Parser.Ch = ':' then begin Parser.GetChar; lEQREquired := True; end; if Parser.Ch = '=' then Parser.GetChar else if lEQREquired then Parser.SetBookmark(iLastBmk); if FDKeywordMatch(ucS, 'ARRAY', 5) then // n AddItem(skArraySize, Parser.GetNumber(15)) else if FDKeywordMatch(ucS, 'AUTOCOMMIT', 4) then // OFF(-1) | ON(1) | n AddItem(skAutoCommit, Parser.GetNumber(1)) else if FDKeywordMatch(ucS, 'AUTOPRINT', 5) then // OFF(-1) | ON(1) AddItem(skAutoPrint, Parser.GetOnOff) else if FDKeywordMatch(ucS, 'BLOBFILE', 8) then // file name AddItem(skBlobFile, 0, Parser.GetString(True)) else if FDKeywordMatch(ucS, 'CHARACTERSET', 9) or FDKeywordMatch(ucS, 'NAMES', 5) then // charset AddItem(skCharacterSet, 0, Parser.GetString(True)) else if FDKeywordMatch(ucS, 'CLIENTLIB', 6) then // clientlib AddItem(skClientLib, 0, Parser.GetString(True)) else if FDKeywordMatch(ucS, 'CMDSEPARATOR', 4) or FDKeywordMatch(ucS, 'TERMINATOR', 4) and (EngineIntf.RDBMSKind in [TFDRDBMSKinds.Interbase, TFDRDBMSKinds.Firebird]) then begin // ';' | c | OFF(-1) | ON(ord(';')) s := Parser.GetString(True); if UpperCase(s) = 'OFF' then s := #255 else if UpperCase(s) = 'ON' then s := '' else if s = '' then s := Parser.ScriptOptions.CommandSeparator; AddItem(skCmdSep, 0, s) end else if FDKeywordMatch(ucS, 'DEFINE', 3) or FDKeywordMatch(ucS, 'SCAN', 4) then // SQL*Plus: '&' | c | OFF(-1) | ON(ord('&')) // FireDAC: OFF(-1) | ON(1) AddItem(skDefine, Parser.GetOnOff) else if FDKeywordMatch(ucS, 'DROPNONEXISTENT', 4) then // OFF(-1) | ON(1) AddItem(skDropNonexistObj, Parser.GetOnOff) else if FDKeywordMatch(ucS, 'ECHO', 4) then begin // OFF(-1) | ON(1) [SQL|ALL] [TRIM <size>] oItem := AddItem(skEcho, Parser.GetOnOff); if oItem.FIValue = 1 then begin oItem.FEchoCommands := ecAll; oItem.FIValue := 50; while True do begin iLastBmk := Parser.GetBookmark; ucS := Parser.GetUCWord; if ucS = 'SQL' then oItem.FEchoCommands := ecSQL else if ucS = 'ALL' then oItem.FEchoCommands := ecAll else if ucS = 'TRIM' then oItem.FIValue := Parser.GetNumber else begin Parser.SetBookmark(iLastBmk); Break; end; end; end else oItem.FEchoCommands := ecNone; end else if FDKeywordMatch(ucS, 'ENCODING', 3) then begin oItem := AddItem(skEncoding); ucS := Parser.GetUCWord; if FDKeyWordMatch(ucS, 'UTF8', 4) then oItem.FIValue := Integer(ecUTF8) else if FDKeyWordMatch(ucS, 'UTF16', 5) then oItem.FIValue := Integer(ecUTF16) else oItem.FIValue := Integer(ecANSI); end else if FDKeywordMatch(ucS, 'FEEDBACK', 4) or FDKeywordMatch(ucS, 'COUNT', 5) then // 6 | n | OFF(-1) | ON(6) AddItem(skFeedback, Parser.GetNumber(6)) else if FDKeywordMatch(ucS, 'HEADING', 3) then // OFF(-1) | ON(1) AddItem(skHeading, Parser.GetOnOff) else if FDKeywordMatch(ucS, 'LINESIZE', 5) then // 0 | n AddItem(skLineSize, Parser.GetNumber(0)) else if FDKeywordMatch(ucS, 'LONG', 4) or FDKeywordMatch(ucS, 'WIDTH', 5) then // 80 | n AddItem(skLong, Parser.GetNumber(80)) else if FDKeywordMatch(ucS, 'PARAMARRAY', 10) then // n AddItem(skParamArraySize, Parser.GetNumber(1)) else if FDKeywordMatch(ucS, 'PAGESIZE', 5) then // n AddItem(skPageSize, Parser.GetNumber(24)) else if FDKeywordMatch(ucS, 'SERVEROUTPUT', 9) then begin // [OFF | ON] [SIZE n] oItem := AddItem(skServerOutput, Parser.GetOnOff); iLastBmk := Parser.GetBookmark; ucS := Parser.GetUCWord; if FDKeywordMatch(ucS, 'SIZE', 4) then oItem.FIValue := Parser.GetNumber else begin oItem.FIValue := 1024; Parser.SetBookmark(iLastBmk); end; end else if FDKeywordMatch(ucS, 'SQL', 3) then begin // DIALECT n oItem := AddItem(skSQLDialect); iLastBmk := Parser.GetBookmark; ucS := Parser.GetUCWord; if ucS = 'DIALECT' then oItem.FIValue := Parser.GetNumber(3) else begin oItem.FIValue := 3; Parser.SetBookmark(iLastBmk); end; end else if FDKeywordMatch(ucS, 'TERMOUT', 4) or FDKeywordMatch(ucS, 'CONSOLE', 3) then // OFF(-1) | ON(1) AddItem(skTermout, Parser.GetOnOff) else if FDKeywordMatch(ucS, 'TIMING', 3) then // OFF(-1) | ON(1) AddItem(skTiming, Parser.GetOnOff) else if FDKeywordMatch(ucS, 'BREAK', 5) then // OFF(-1) | ON(1) AddItem(skBreakOnError, Parser.GetOnOff) else if FDKeywordMatch(ucS, 'IGNORE', 6) then // OFF(-1) | ON(1) AddItem(skIgnoreError, Parser.GetOnOff) else if FDKeywordMatch(ucS, 'TRIMOUT', 4) then // OFF(-1) | ON(1) AddItem(skTrimConsole, Parser.GetOnOff) else if FDKeywordMatch(ucS, 'TRIMSPOOL', 5) then // OFF(-1) | ON(1) AddItem(skTrimSpool, Parser.GetOnOff) else if FDKeywordMatch(ucS, 'VERIFY', 3) then // OFF(-1) | ON(1) AddItem(skVerify, Parser.GetOnOff) // ******************************************************** // ******** just ignore next SET's ************************ else if FDKeywordMatch(ucS, 'NUMWIDTH', 3) then // n Parser.GetNumber else if FDKeywordMatch(ucS, 'TAB', 3) then // OFF(-1) | ON(1) Parser.GetOnOff; end; Result := Length(FItems) > 0; end; {-------------------------------------------------------------------------------} procedure TFDSetScriptCommand.Execute(); var i: Integer; oItem: TFDSetScriptCommandItem; oRes: TFDTopResourceOptions; begin for i := 0 to Length(FItems) - 1 do begin oItem := FItems[i]; case oItem.FSetKind of skArraySize: begin EngineIntf.CheckCommand; EngineIntf.CommandIntf.Options.FetchOptions.RowsetSize := oItem.FIValue; end; skAutoCommit: begin if EngineIntf.ConnectionIntf = nil then Engine.Connection.TxOptions.AutoCommit := (oItem.FIValue >= 1) else begin EngineIntf.CheckCommand; EngineIntf.CheckCommit(True); EngineIntf.ConnectionIntf.Transaction.Options.AutoCommit := (oItem.FIValue >= 1); end; if oItem.FIValue >= 1 then Engine.ScriptOptions.CommitEachNCommands := oItem.FIValue else Engine.ScriptOptions.CommitEachNCommands := 0; Engine.ProcessedAfterCommit := 0; end; skAutoPrint: Engine.ScriptOptions.AutoPrintParams := (oItem.FIValue = 1); skBlobFile: Engine.ScriptOptions.BlobFile := oItem.FSValue; skCharacterSet: Engine.ScriptOptions.CharacterSet := oItem.FSValue; skClientLib: Engine.ScriptOptions.ClientLib := oItem.FSValue; skCmdSep: begin Parser.ScriptOptions.CommandSeparator := oItem.FSValue; EngineIntf.UpdateCommandSeparator; end; skDropNonexistObj: Engine.ScriptOptions.DropNonexistObj := (oItem.FIValue = 1); skEcho: begin Engine.ScriptOptions.EchoCommandTrim := 0; Engine.ScriptOptions.EchoCommands := oItem.FEchoCommands; if oItem.FEchoCommands <> ecNone then Engine.ScriptOptions.EchoCommandTrim := oItem.FIValue; end; skEncoding: Engine.ScriptOptions.FileEncoding := TFDEncoding(oItem.FIValue); skFeedback: Engine.ScriptOptions.FeedbackCommands := (oItem.FIValue > 0); skHeading: Engine.ScriptOptions.ColumnHeadings := (oItem.FIValue > 0); skLineSize: Engine.ScriptOptions.LineSize := oItem.FIValue; skLong: Engine.ScriptOptions.MaxStringWidth := oItem.FIValue; skParamArraySize: begin Engine.ScriptOptions.ParamArraySize := oItem.FIValue; Engine.Params.ArraySize := oItem.FIValue; end; skPageSize: Engine.ScriptOptions.PageSize := oItem.FIValue; skDefine, skScan: Engine.ScriptOptions.MacroExpand := (oItem.FIValue > 0); skServerOutput: begin EngineIntf.CheckCommand; oRes := EngineIntf.ConnectionIntf.Options.ResourceOptions as TFDTopResourceOptions; if oItem.FIValue > 1 then oRes.ServerOutputSize := oItem.FIValue; oRes.ServerOutput := (oItem.FIValue > 0); end; skSQLDialect: Engine.ScriptOptions.SQLDialect := oItem.FIValue; skTermout: Engine.ScriptOptions.ConsoleOutput := (oItem.FIValue > 0); skTiming: Engine.ScriptOptions.Timing := (oItem.FIValue > 0); skBreakOnError: Engine.ScriptOptions.BreakOnError := (oItem.FIValue > 0); skIgnoreError: Engine.ScriptOptions.IgnoreError := (oItem.FIValue > 0); skTrimConsole: Engine.ScriptOptions.TrimConsole := (oItem.FIValue > 0); skTrimSpool: Engine.ScriptOptions.TrimSpool := (oItem.FIValue > 0); skVerify: Engine.ScriptOptions.Verify := (oItem.FIValue > 0); else ASSERT(False); end; end; end; {-------------------------------------------------------------------------------} procedure TFDSetScriptCommand.Validate(); var i: Integer; oItem: TFDSetScriptCommandItem; begin for i := 0 to Length(FItems) - 1 do begin oItem := FItems[i]; case oItem.FSetKind of skCmdSep: begin Parser.ScriptOptions.CommandSeparator := oItem.FSValue; EngineIntf.UpdateCommandSeparator; end; skEncoding: Engine.ScriptOptions.FileEncoding := TFDEncoding(oItem.FIValue); skBreakOnError: Engine.ScriptOptions.BreakOnError := (oItem.FIValue > 0); skIgnoreError: Engine.ScriptOptions.IgnoreError := (oItem.FIValue > 0); end; end; end; {-------------------------------------------------------------------------------} { TFDSpoolScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDSpoolScriptCommand.Dump: String; begin Result := '<spool> ['; case FMode of -1: Result := Result + 'off'; 0: Result := Result + 'show'; 1: begin Result := Result + 'on fl="' + FileName + '"'; if Append then Result := Result + ', append'; end; end; Result := Result + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDSpoolScriptCommand.Help(): String; begin Result := '(SPOol | OUTput) [OFF|[APPend] <spool name>] - turns spooling off, print it status'#13#10 + ' or redirect it to the name'; end; {-------------------------------------------------------------------------------} class procedure TFDSpoolScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('SPOol'); AKwds.Add('OUTput'); end; {-------------------------------------------------------------------------------} function TFDSpoolScriptCommand.Parse(const AKwd: String): Boolean; var iLastBmk: Integer; ucS: string; begin iLastBmk := Parser.GetBookmark; ucS := Parser.GetUCWord; if ucS = 'OFF' then FMode := -1 else if ucS = '' then FMode := 0 else begin FMode := 1; FAppend := FDKeyWordMatch(ucS, 'APPEND', 3); if not FAppend then Parser.SetBookmark(iLastBmk); FFileName := Parser.GetLine(); if FFileName = '' then FMode := -1; end; Result := True; end; {-------------------------------------------------------------------------------} procedure TFDSpoolScriptCommand.Execute(); begin case FMode of -1: begin Engine.ScriptOptions.SpoolOutput := smNone; EngineIntf.UpdateSpool; end; 0: if Engine.ScriptOptions.SpoolOutput <> smNone then EngineIntf.ConPut('currently spooling to ' + Engine.ScriptOptions.SpoolFileName, soInfo) else EngineIntf.ConPut('not spooling currently', soInfo); 1: begin if FAppend then Engine.ScriptOptions.SpoolOutput := smOnAppend else Engine.ScriptOptions.SpoolOutput := smOnReset; Engine.ScriptOptions.SpoolFileName := EngineIntf.ExpandString(FileName); EngineIntf.UpdateSpool; end; end; end; {-------------------------------------------------------------------------------} { TFDUndefineScriptCommand } {-------------------------------------------------------------------------------} constructor TFDUndefineScriptCommand.Create(AParser: TFDScriptParser; AEngine: TFDScript); begin inherited Create(AParser, AEngine); FVars := TFDStringList.Create; end; {-------------------------------------------------------------------------------} destructor TFDUndefineScriptCommand.Destroy; begin FDFreeAndNil(FVars); inherited Destroy; end; {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDUndefineScriptCommand.Dump(): String; var i: Integer; begin Result := '<undefine> ['; for i := 0 to FVars.Count - 1 do begin if i > 0 then Result := Result + ', '; Result := Result + IntToStr(i) + '="' + FVars[i] + '"'; end; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDUndefineScriptCommand.Help(): String; begin Result := 'UNDEFine <var1> [..., <varN>] - undefines specified macros'; end; {-------------------------------------------------------------------------------} class procedure TFDUndefineScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('UNDEFine'); end; {-------------------------------------------------------------------------------} function TFDUndefineScriptCommand.Parse(const AKwd: String): Boolean; begin Vars.AddStrings(Parser.GetLine().Split([',', ' ', #9], TStringSplitOptions.ExcludeEmpty)); Result := True; end; {-------------------------------------------------------------------------------} procedure TFDUndefineScriptCommand.Execute(); var i: Integer; oMac: TFDMacro; begin for i := 0 to Vars.Count - 1 do begin oMac := Engine.Macros.FindMacro(EngineIntf.ExpandString(Vars[i])); if oMac <> nil then FDFree(oMac); end; end; {-------------------------------------------------------------------------------} { TFDVariableScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDVariableScriptCommand.Dump(): String; begin Result := '<variable> ['; case FMode of -1: Result := Result + 'show all'; 0: Result := Result + 'show var="' + Variable + '"'; 1: Result := Result + 'set var="' + Variable + '", dt=' + FieldTypeNames[DataType] + ', sz=' + IntToStr(Size) + ', tabsz=' + IntToStr(TableSize) + ', partp=' + InttoStr(Integer(ParamType)) + ', val=' + FValue; end; Result := Result + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDVariableScriptCommand.Help(): String; begin Result := 'VARiable [<name> (NUMber|CHAR|NCHAR) [(<size>)]] [TABle <size>]'#13#10 + ' [IN|OUT|INOUT] [=<value>] - prints all variables or defines variable'; end; {-------------------------------------------------------------------------------} class procedure TFDVariableScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('VARiable'); end; {-------------------------------------------------------------------------------} function TFDVariableScriptCommand.Parse(const AKwd: String): Boolean; var ucS: String; begin FVariable := Parser.GetIdentifier(); if FVariable = '' then // print all FMode := -1 else begin ucS := Parser.GetUCWord; if ucS = '' then begin // print var FMode := 0; Parser.UnGetChar; end else begin // declare var FMode := 1; while ucS <> '' do begin if FDKeyWordMatch(ucS, 'NUMBER', 3) then FDataType := ftFmtBCD else if FDKeyWordMatch(ucS, 'CHAR', 4) or FDKeyWordMatch(ucS, 'NCHAR', 5) or FDKeyWordMatch(ucS, 'VARCHAR2', 7) or FDKeyWordMatch(ucS, 'NVARCHAR2', 8) then begin if ucS[1] = 'N' then FDataType := ftWideString else FDataType := ftString; FSize := -1; Parser.SkipWS; if Parser.Ch = '(' then begin Parser.GetChar; FSize := Parser.GetNumber; Parser.SkipWS; if Parser.Ch <> ')' then FDException(Engine, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrVarMissedCloseBrace, []); Parser.GetChar; end; end else if FDKeyWordMatch(ucS, 'TABLE', 3) then FTableSize := Parser.GetNumber else if FDKeyWordMatch(ucS, 'INPUT', 2) then FParamType := ptInput else if FDKeyWordMatch(ucS, 'OUTPUT', 3) then FParamType := ptOutput else if FDKeyWordMatch(ucS, 'INOUT', 3) then FParamType := ptInputOutput else FDException(Engine, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrVarUnsupType, []); ucS := Parser.GetUCWord; end; if Parser.Ch = '=' then begin Parser.GetChar; Parser.SkipWS; FValue := Parser.GetString(); end; end; end; Result := True; end; {-------------------------------------------------------------------------------} procedure TFDVariableScriptCommand.Execute(); var i: Integer; sVar: String; oPar: TFDParam; procedure PrintPar(APar: TFDParam); var s: String; begin EngineIntf.ConPut('variable ' + APar.Name, soParam); case APar.DataType of ftFmtBCD, ftFloat: s := 'NUMBER'; ftString: s := 'CHAR(' + IntToStr(APar.Size) + ')'; ftWideString: s := 'NCHAR(' + IntToStr(APar.Size) + ')'; else s := FieldTypeNames[APar.DataType]; end; EngineIntf.ConPut('datatype ' + s, soParam); if APar.ParamType <> ptUnknown then begin case APar.ParamType of ptInput: s := 'INPUT'; ptOutput: s := 'OUTPUT'; ptInputOutput: s := 'INOUT'; end; EngineIntf.ConPut('direction ' + s, soParam); end; if APar.ArraySize <> 1 then EngineIntf.ConPut('array size' + IntToStr(APar.ArraySize), soParam); end; begin case FMode of -1: for i := 0 to Engine.Params.Count - 1 do begin if i > 0 then EngineIntf.ConPut('', soSeparator); PrintPar(Engine.Params[i]); end; 0: PrintPar(Engine.Params.ParamByName(EngineIntf.ExpandString(Variable))); 1: begin sVar := EngineIntf.ExpandString(Self.Variable); oPar := Engine.Params.FindParam(sVar); if oPar = nil then begin oPar := Engine.Params.Add; oPar.Name := sVar; end; if (oPar.DataType = ftUnknown) or (DataType <> ftUnknown) then oPar.DataType := DataType; if (ParamType = ptUnknown) and (EngineIntf.RDBMSKind = TFDRDBMSKinds.Oracle) then FParamType := ptInputOutput; if (oPar.ParamType = ptUnknown) or (ParamType <> ptUnknown) then oPar.ParamType := ParamType; if (oPar.Size = 0) or (Size <> 0) then oPar.Size := Size; if TableSize <> 0 then begin oPar.ArrayType := atTable; oPar.ArraySize := TableSize; end else oPar.ArraySize := Engine.ScriptOptions.ParamArraySize; if FValue <> '' then if CompareText(FValue, 'null') = 0 then oPar.Clear() else oPar.Value := FValue; end; end; end; {-------------------------------------------------------------------------------} { TFDHelpScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDHelpScriptCommand.Dump(): String; begin Result := '<help>'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDHelpScriptCommand.Help(): String; begin Result := 'HELP - shows help for all registered commands'; end; {-------------------------------------------------------------------------------} class procedure TFDHelpScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('HELP'); AKwds.Add('?'); end; {-------------------------------------------------------------------------------} procedure TFDHelpScriptCommand.Execute(); var i: Integer; oReg: TFDScriptCommandRegistry; begin oReg := FDScriptCommandRegistry(); for i := 0 to oReg.Count - 1 do EngineIntf.ConPut(oReg.Commands[i].Help(), soInfo); end; {-------------------------------------------------------------------------------} { TFDRemarkScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDRemarkScriptCommand.Dump(): String; begin Result := '<remark> [' + FText + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDRemarkScriptCommand.Help(): String; begin Result := 'REMark <text> - adds comment to the script'; end; {-------------------------------------------------------------------------------} class procedure TFDRemarkScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('REMark'); end; {-------------------------------------------------------------------------------} function TFDRemarkScriptCommand.Parse(const AKwd: String): Boolean; begin FText := Parser.GetLine; Result := True; end; {-------------------------------------------------------------------------------} { TFDCopyScriptCommand } {-------------------------------------------------------------------------------} constructor TFDCopyScriptCommand.Create(AParser: TFDScriptParser; AEngine: TFDScript); begin inherited Create(AParser, AEngine); FBatchMove := TFDBatchMove.Create(nil); FBatchMove.Options := [poIdentityInsert]; FSrcConnection := TFDConnection.Create(nil); FDestConnection := TFDConnection.Create(nil); end; {-------------------------------------------------------------------------------} destructor TFDCopyScriptCommand.Destroy; begin FDFreeAndNil(FBatchMove); FDFreeAndNil(FSrcConnection); FDFreeAndNil(FDestConnection); inherited Destroy; end; {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDCopyScriptCommand.Dump: String; begin Result := ''; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDCopyScriptCommand.Help: String; begin Result := 'COPY FROM (FILE ''<file>'' | TABle ''<table name>'' [CONnect ''<connection>''])'#13#10 + ' TO (FILE ''<file>'' | TABle ''<table name>'' [CONnect ''<connection>''])'#13#10 + ' [TRUNCate | CLEar | ALWAYSinsert | APPend | UPDate | APPENDUPDate | DELete]'#13#10 + ' [LOG (OFF | (SPOol|OUTput) | ([APPend] <log file name>)]'#13#10 + ' [USING FILE ''config file'' | PARAMS ''<definition>''] - move data between databases or text files'; end; {-------------------------------------------------------------------------------} class procedure TFDCopyScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('COPY'); end; {-------------------------------------------------------------------------------} function TFDCopyScriptCommand.Parse(const AKwd: String): Boolean; var iPrevBmk, iPrevBmk2: Integer; ucS: String; begin // Source ucS := Parser.GetUCWord; if ucS <> 'FROM' then Parser.InvalidSyntax; ucS := Parser.GetUCWord; if ucS = 'FILE' then begin FBatchMove.Reader := TFDBatchMoveTextReader.Create(FBatchMove); TFDBatchMoveTextReader(FBatchMove.Reader).FileName := Parser.GetString(); end else if FDKeyWordMatch(ucS, 'TABLE', 3) then begin FBatchMove.Reader := TFDBatchMoveSQLReader.Create(FBatchMove); TFDBatchMoveSQLReader(FBatchMove.Reader).TableName := Parser.GetString(); iPrevBmk := Parser.GetBookmark; ucS := Parser.GetUCWord; if FDKeyWordMatch(ucS, 'CONNECT', 3) then begin TFDBatchMoveSQLReader(FBatchMove.Reader).Connection := FSrcConnection; FSrcConnStr := Parser.GetString(); end else Parser.SetBookmark(iPrevBmk); end; // Destination ucS := Parser.GetUCWord; if ucS <> 'TO' then Parser.InvalidSyntax; ucS := Parser.GetUCWord; if ucS = 'FILE' then begin FBatchMove.Writer := TFDBatchMoveTextWriter.Create(FBatchMove); TFDBatchMoveTextWriter(FBatchMove.Writer).FileName := Parser.GetString(); end else if FDKeyWordMatch(ucS, 'TABLE', 3) then begin FBatchMove.Writer := TFDBatchMoveSQLWriter.Create(FBatchMove); TFDBatchMoveSQLWriter(FBatchMove.Writer).TableName := Parser.GetString(); iPrevBmk := Parser.GetBookmark; ucS := Parser.GetUCWord; if FDKeyWordMatch(ucS, 'CONNECT', 3) then begin TFDBatchMoveSQLWriter(FBatchMove.Writer).Connection := FDestConnection; FDestConnStr := Parser.GetString(); end else Parser.SetBookmark(iPrevBmk); end; // Mode iPrevBmk := Parser.GetBookmark; ucS := Parser.GetUCWord; if FDKeyWordMatch(ucS, 'CLEAR', 3) then begin FBatchMove.Options := FBatchMove.Options + [poClearDest]; FBatchMove.Mode := dmAlwaysInsert; end else if FDKeyWordMatch(ucS, 'TRUNCATE', 5) then begin FBatchMove.Options := FBatchMove.Options + [poClearDest, poClearDestNoUndo]; FBatchMove.Mode := dmAlwaysInsert; end else if FDKeyWordMatch(ucS, 'ALWAYSINSERT', 6) then FBatchMove.Mode := dmAlwaysInsert else if FDKeyWordMatch(ucS, 'APPEND', 3) then FBatchMove.Mode := dmAppend else if FDKeyWordMatch(ucS, 'UPDATE', 3) then FBatchMove.Mode := dmUpdate else if FDKeyWordMatch(ucS, 'APPENDUPDATE', 9) then FBatchMove.Mode := dmAppendUpdate else if FDKeyWordMatch(ucS, 'DELETE', 3) then FBatchMove.Mode := dmDelete else begin FBatchMove.Options := FBatchMove.Options + [poClearDest, poClearDestNoUndo]; FBatchMove.Mode := dmAlwaysInsert; Parser.SetBookmark(iPrevBmk); end; // Log file iPrevBmk := Parser.GetBookmark; ucS := Parser.GetUCWord; if ucS = 'LOG' then begin iPrevBmk2 := Parser.GetBookmark; ucS := Parser.GetUCWord; if ucS = 'OFF' then FBatchMove.LogFileAction := laNone else if FDKeyWordMatch(ucS, 'SPOOL', 3) or FDKeyWordMatch(ucS, 'OUTPUT', 3) then begin FBatchMove.LogFileAction := laAppend; FLogToSpool := True; end else begin if FDKeyWordMatch(ucS, 'APPEND', 3) then FBatchMove.LogFileAction := laAppend else begin FBatchMove.LogFileAction := laCreate; Parser.SetBookmark(iPrevBmk2); end; FBatchMove.LogFileName := Parser.GetString(); end; end else begin FBatchMove.LogFileAction := laNone; Parser.SetBookmark(iPrevBmk); end; // Config file iPrevBmk := Parser.GetBookmark; ucS := Parser.GetUCWord; if ucS = 'USING' then begin ucS := Parser.GetUCWord; if ucS = 'FILE' then FConfigFile := Parser.GetString() else if ucS = 'PARAMS' then FConfigParams := Parser.GetString() else Parser.InvalidSyntax; end else Parser.SetBookmark(iPrevBmk); Result := True; end; {-------------------------------------------------------------------------------} procedure TFDCopyScriptCommand.DumpServerOutput; var i: Integer; begin if not (EngineIntf.ConnectionIntf.Options.ResourceOptions as TFDTopResourceOptions).ServerOutput or (EngineIntf.ConnectionIntf.Messages = nil) or (EngineIntf.ConnectionIntf.Messages.ErrorCount = 0) then Exit; for i := 0 to EngineIntf.ConnectionIntf.Messages.ErrorCount - 1 do EngineIntf.ConPut(EngineIntf.ConnectionIntf.Messages[i].Message, soServerOutput); EngineIntf.ConPut('', soSeparator); end; {-------------------------------------------------------------------------------} procedure TFDCopyScriptCommand.Execute; var oStr: TStream; sFeedback: String; dwStartTime: LongWord; dwExecTime: LongWord; procedure SetupSQLDriver(ADriver: TFDBatchMoveSQLDriver; AConnection: TFDConnection; const AConnStr: String); begin if ADriver.Connection = nil then begin ADriver.Connection := Engine.Connection; ADriver.Transaction := Engine.Transaction; end; ADriver.TableName := EngineIntf.ExpandString(Trim(ADriver.TableName)); if AConnStr <> '' then begin AConnection.Close; AConnection.ResultConnectionDef.Params.Clear; AConnection.ResultConnectionDef.ParseString(EngineIntf.ExpandString(AConnStr)); AConnection.LoginPrompt := False; AConnection.Close; end; end; procedure SetupTextDriver(ADriver: TFDBatchMoveTextDriver; AReader: Boolean); var s: String; oDef: TFDTextDataDef; function DefineFileName(const ADir, AFile, AExt: String): String; begin Result := AFile; if (ExtractFilePath(Result) = '') and (ADir <> '') then Result := FDNormPath(ADir) + Result; if (ExtractFileExt(Result) = '') and (AExt <> '') then Result := Result + '.' + AExt; Result := EngineIntf.ExpandString(Result); end; begin s := EngineIntf.ExpandString(ADriver.FileName); if AReader then begin if not FileExists(s) then begin s := DefineFileName(Engine.ScriptOptions.DefaultDataPath, s, 'csv'); if not FileExists(s) then s := DefineFileName(Engine.ScriptOptions.DefaultDataPath, s, 'txt'); end; end else s := DefineFileName(Engine.ScriptOptions.DefaultDataPath, s, 'txt'); ADriver.FileName := s; oDef := ADriver.DataDef; oDef.RecordFormat := rfSemicolonDoubleQuote; oDef.WithFieldNames := True; oDef.FormatSettings.DecimalSeparator := '.'; oDef.FormatSettings.DateSeparator := '-'; oDef.FormatSettings.TimeSeparator := ':'; oDef.FormatSettings.ShortDateFormat := 'yyyy/mm/dd'; oDef.FormatSettings.ShortTimeFormat := 'hh:mm:ss'; end; begin if FBatchMove.Reader is TFDBatchMoveSQLDriver then SetupSQLDriver(TFDBatchMoveSQLDriver(FBatchMove.Reader), FSrcConnection, FSrcConnStr) else if FBatchMove.Reader is TFDBatchMoveTextDriver then SetupTextDriver(TFDBatchMoveTextDriver(FBatchMove.Reader), True); if FBatchMove.Writer is TFDBatchMoveSQLDriver then SetupSQLDriver(TFDBatchMoveSQLDriver(FBatchMove.Writer), FDestConnection, FDestConnStr) else if FBatchMove.Writer is TFDBatchMoveTextDriver then SetupTextDriver(TFDBatchMoveTextDriver(FBatchMove.Writer), False); if FConfigFile <> '' then begin oStr := TBufferedFileStream.Create(EngineIntf.ExpandString(FConfigFile), fmOpenRead or fmShareDenyWrite); try oStr.ReadComponent(FBatchMove); finally FDFree(oStr); end; end else if FConfigParams <> '' then begin oStr := TStringStream.Create(EngineIntf.ExpandString(FConfigParams)); try oStr.ReadComponent(FBatchMove); finally FDFree(oStr); end; end; if Engine.ScriptOptions.CommitEachNCommands > 0 then FBatchMove.CommitCount := Engine.ScriptOptions.CommitEachNCommands else FBatchMove.CommitCount := 100; if Engine.ScriptOptions.BreakOnError then FBatchMove.MaxErrors := 0 else FBatchMove.MaxErrors := -1; FBatchMove.LogFileName := EngineIntf.ExpandString(FBatchMove.LogFileName); if FLogToSpool then if Engine.ScriptOptions.SpoolOutput <> smNone then begin FBatchMove.LogFileName := EngineIntf.ExpandString(Engine.LastSpoolFileName); Engine.ScriptOptions.SpoolOutput := smOnAppend; EngineIntf.CloseSpool; end else FBatchMove.LogFileAction := laNone; if Engine.ScriptOptions.FeedbackCommands then begin sFeedback := ''; case FBatchMove.Mode of dmAlwaysInsert: sFeedback := 'Insert data into'; dmAppend: sFeedback := 'Append data into'; dmUpdate: sFeedback := 'Update data in'; dmAppendUpdate: sFeedback := 'Append or update data in'; dmDelete: sFeedback := 'Delete data in'; end; if FBatchMove.Writer is TFDBatchMoveTextDriver then sFeedback := sFeedback + ' file ' + TFDBatchMoveTextDriver(FBatchMove.Writer).FileName else if FBatchMove.Writer is TFDBatchMoveSQLDriver then sFeedback := sFeedback + ' table ' + TFDBatchMoveSQLDriver(FBatchMove.Writer).ActualTableName; sFeedback := sFeedback + ' from '; if FBatchMove.Reader is TFDBatchMoveTextDriver then sFeedback := sFeedback + ' file ' + TFDBatchMoveTextDriver(FBatchMove.Reader).FileName else if FBatchMove.Reader is TFDBatchMoveSQLDriver then sFeedback := sFeedback + ' table ' + TFDBatchMoveSQLDriver(FBatchMove.Reader).ActualTableName; sFeedback := sFeedback + ' ...'; EngineIntf.ConPut(sFeedback, soCommand); end; try dwStartTime := TThread.GetTickCount(); FBatchMove.Execute; dwExecTime := TThread.GetTickCount() - dwStartTime; finally if (EngineIntf.ConnectionIntf.Options.ResourceOptions as TFDTopResourceOptions).ServerOutput then DumpServerOutput; if FLogToSpool then if Engine.ScriptOptions.SpoolOutput <> smNone then EngineIntf.UpdateSpool; end; if Engine.ScriptOptions.FeedbackCommands then begin sFeedback := Format('Rows read: %d. Rows written: %d (inserted: %d, updated: %d, deleted: %d)'#13#10, [FBatchMove.ReadCount, FBatchMove.WriteCount, FBatchMove.InsertCount, FBatchMove.UpdateCount, FBatchMove.DeleteCount]); if FBatchMove.ErrorCount = 0 then sFeedback := sFeedback + 'Ok' else sFeedback := sFeedback + Format('Errors: %d', [FBatchMove.ErrorCount]); if Engine.ScriptOptions.Timing then sFeedback := sFeedback + Format(' [%.2d:%.2d:%.2d.%.3d]', [ (dwExecTime div 3600000) mod 60, (dwExecTime div 60000) mod 60, (dwExecTime div 1000) mod 60, dwExecTime mod 1000]); sFeedback := sFeedback + '.'; EngineIntf.ConPut(sFeedback, soCommand); end; end; {-------------------------------------------------------------------------------} procedure TFDCopyScriptCommand.AbortJob(const AWait: Boolean); begin FBatchMove.AbortJob; end; {-------------------------------------------------------------------------------} { TFDDelimiterScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDDelimiterScriptCommand.Dump: String; begin Result := '<delimiter> [' + FCmdSep + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class function TFDDelimiterScriptCommand.Help: String; begin Result := 'DELIMiter <text> - sets script command delimiter'; end; {-------------------------------------------------------------------------------} class procedure TFDDelimiterScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('DELIMiter') end; {-------------------------------------------------------------------------------} function TFDDelimiterScriptCommand.Parse(const AKwd: String): Boolean; begin FCmdSep := Parser.GetStringInFull; Result := True; end; {-------------------------------------------------------------------------------} procedure TFDDelimiterScriptCommand.Execute(); begin Parser.ScriptOptions.CommandSeparator := FCmdSep; EngineIntf.UpdateCommandSeparator; end; {-------------------------------------------------------------------------------} procedure TFDDelimiterScriptCommand.Validate(); begin Execute(); end; {-------------------------------------------------------------------------------} { TFDIBCreateDBScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDIBCreateDBScriptCommand.Dump: String; begin Result := '<create IB database> [' + FDB + ']'; end; {$ENDIF} {-------------------------------------------------------------------------------} class procedure TFDIBCreateDBScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('CREATE DATABASE'); end; {-------------------------------------------------------------------------------} function TFDIBCreateDBScriptCommand.Parse(const AKwd: String): Boolean; var ucS: String; begin if not (EngineIntf.RDBMSKind in [TFDRDBMSKinds.Interbase, TFDRDBMSKinds.Firebird]) then begin Result := False; Exit; end; Result := True; FDB := Parser.GetString(True); while True do begin Parser.SkipWSLF; ucS := Parser.GetUCWord; if ucS = '' then Break; if FDKeywordMatch(ucS, 'USER', 4) then FUser := Parser.GetString(True) else if FDKeywordMatch(ucS, 'PASSWORD', 8) then FPwd := Parser.GetString(True) else if FDKeywordMatch(ucS, 'PAGE_SIZE', 9) then FPageSize := Parser.GetString(True) else if FDKeywordMatch(ucS, 'DEFAULT', 7) then begin ucS := Parser.GetUCWord; if ucS = 'CHARACTER' then begin ucS := Parser.GetUCWord; if ucS = 'SET' then FCharset := Parser.GetString(True); end; end end; end; {-------------------------------------------------------------------------------} procedure TFDIBCreateDBScriptCommand.Execute; var oDef: IFDStanConnectionDef; begin Engine.Connection.Close; oDef := Engine.Connection.ResultConnectionDef; oDef.AsString[S_FD_ConnParam_IB_OpenMode] := 'Create'; oDef.Params.Database := EngineIntf.ExpandString(FDB); oDef.Params.UserName := EngineIntf.ExpandString(FUser); oDef.Params.Password := EngineIntf.ExpandString(FPwd); oDef.AsString[S_FD_ConnParam_IB_PageSize] := EngineIntf.ExpandString(FPageSize); EngineIntf.OpenConnection(''); EngineIntf.ConPut('Database created', soCommand); end; {-------------------------------------------------------------------------------} { TFDIBDropDBScriptCommand } {-------------------------------------------------------------------------------} {$IFDEF FireDAC_MONITOR} function TFDIBDropDBScriptCommand.Dump: String; begin Result := '<drop IB database>'; end; {$ENDIF} {-------------------------------------------------------------------------------} class procedure TFDIBDropDBScriptCommand.Keywords(AKwds: TStrings); begin AKwds.Add('DROP DATABASE'); end; {-------------------------------------------------------------------------------} function TFDIBDropDBScriptCommand.Parse(const AKwd: String): Boolean; begin Result := EngineIntf.RDBMSKind in [TFDRDBMSKinds.Interbase, TFDRDBMSKinds.Firebird]; end; {-------------------------------------------------------------------------------} procedure TFDIBDropDBScriptCommand.Execute; var prevChanging: TNotifyEvent; oDef: IFDStanConnectionDef; begin oDef := Engine.Connection.ResultConnectionDef; prevChanging := oDef.OnChanging; oDef.OnChanging := nil; try oDef.AsYesNo[S_FD_ConnParam_IB_DropDatabase] := True; Engine.Connection.Close; finally oDef.AsYesNo[S_FD_ConnParam_IB_DropDatabase] := False; oDef.OnChanging := prevChanging; end; EngineIntf.ConPut('Database droped', soCommand); end; {-------------------------------------------------------------------------------} initialization FDScriptCommandRegistry().DefaultSQLCommandClass := TFDSQLScriptCommand; FDScriptCommandRegistry().DefaultPLSQLCommandClass := TFDPLSQLScriptCommand; FDScriptCommandRegistry().AddCommand(TFDRunScriptCommand); FDScriptCommandRegistry().AddCommand(TFDAcceptScriptCommand); FDScriptCommandRegistry().AddCommand(TFDConnectScriptCommand); FDScriptCommandRegistry().AddCommand(TFDCopyScriptCommand); FDScriptCommandRegistry().AddCommand(TFDDefineScriptCommand); FDScriptCommandRegistry().AddCommand(TFDDelimiterScriptCommand); FDScriptCommandRegistry().AddCommand(TFDDisconnectScriptCommand); FDScriptCommandRegistry().AddCommand(TFDExecuteScriptCommand); FDScriptCommandRegistry().AddCommand(TFDExitScriptCommand); FDScriptCommandRegistry().AddCommand(TFDHelpScriptCommand); FDScriptCommandRegistry().AddCommand(TFDHostScriptCommand); FDScriptCommandRegistry().AddCommand(TFDPauseScriptCommand); FDScriptCommandRegistry().AddCommand(TFDPromptScriptCommand); FDScriptCommandRegistry().AddCommand(TFDPrintScriptCommand); FDScriptCommandRegistry().AddCommand(TFDRemarkScriptCommand); FDScriptCommandRegistry().AddCommand(TFDSetScriptCommand); FDScriptCommandRegistry().AddCommand(TFDSpoolScriptCommand); FDScriptCommandRegistry().AddCommand(TFDUndefineScriptCommand); FDScriptCommandRegistry().AddCommand(TFDVariableScriptCommand); FDScriptCommandRegistry().AddCommand(TFDIBCreateDBScriptCommand); FDScriptCommandRegistry().AddCommand(TFDIBDropDBScriptCommand); end.
unit Support.Transcend; interface uses SysUtils, Support, Device.SMART.List; type TTranscendNSTSupport = class sealed(TNSTSupport) private InterpretingSMARTValueList: TSMARTValueList; function GetSemiSupport: TSupportStatus; function GetTotalWrite: TTotalWrite; function IsProductOfTranscend: Boolean; function Is220S: Boolean; public function GetSupportStatus: TSupportStatus; override; function GetSMARTInterpreted(SMARTValueList: TSMARTValueList): TSMARTInterpreted; override; end; implementation { TTranscendNSTSupport } function TTranscendNSTSupport.Is220S: Boolean; begin result := (Pos('TS', Identify.Model) > 0) and (Pos('GSSD220S', Identify.Model) > 0); end; function TTranscendNSTSupport.IsProductOfTranscend: Boolean; begin result := Is220S; end; function TTranscendNSTSupport.GetSemiSupport: TSupportStatus; begin result.Supported := Supported; result.FirmwareUpdate := false; result.TotalWriteType := TTotalWriteType.WriteSupportedAsValue; end; function TTranscendNSTSupport.GetSupportStatus: TSupportStatus; begin result.Supported := NotSupported; if IsProductOfTranscend then result := GetSemiSupport; end; function TTranscendNSTSupport.GetTotalWrite: TTotalWrite; const TranscendUnit = 32; IDOfHostWrite = $F1; var RAWValue: UInt64; begin result.InValue.TrueHostWriteFalseNANDWrite := true; RAWValue := InterpretingSMARTValueList.GetRAWByID(IDOfHostWrite); result.InValue.ValueInMiB := RAWValue * TranscendUnit; end; function TTranscendNSTSupport.GetSMARTInterpreted( SMARTValueList: TSMARTValueList): TSMARTInterpreted; const IDOfReadError = 1; IDOfReplacedSector = 5; ReplacedSectorThreshold = 50; EraseErrorThreshold = 10; begin InterpretingSMARTValueList := SMARTValueList; result.TotalWrite := GetTotalWrite; result.UsedHour := 0; result.ReadEraseError.TrueReadErrorFalseEraseError := true; result.ReadEraseError.Value := InterpretingSMARTValueList.GetRAWByID(IDOfReadError); result.SMARTAlert.ReadEraseError := result.ReadEraseError.Value >= EraseErrorThreshold; result.ReplacedSectors := InterpretingSMARTValueList.GetRAWByID(IDOfReplacedSector); result.SMARTAlert.ReplacedSector := result.ReplacedSectors >= ReplacedSectorThreshold; end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX_Objects3D; {$I FMX_Defines.inc} interface uses Classes, Types, UITypes, FMX_Types, FMX_Objects, FMX_Types3D, FMX_Video; {$SCOPEDENUMS ON} type { TGrid3D } TGrid3D = class(TControl3D) private FLineColor: TAlphaColor; FFrequency: Single; FMarks: Single; procedure SetLineColor(const Value: TAlphaColor); function GetLineColor: TAlphaColor; procedure SetFrequency(const Value: Single); procedure SetMarks(const Value: Single); protected procedure SetDepth(const Value: Single); override; procedure Render; override; public constructor Create(AOwner: TComponent); override; function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override; published property Marks: Single read FMarks write SetMarks; property Frequency: Single read FFrequency write SetFrequency; property LineColor: TAlphaColor read GetLineColor write SetLineColor; end; { TShape3D } TShape3D = class(TControl3D) private FMaterial: TMaterial; procedure SetMaterial(const Value: TMaterial); protected procedure MaterialChanged(Sender: TObject); procedure Apply; override; procedure UnApply; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Material: TMaterial read FMaterial write SetMaterial; end; { TStrokeCube } TStrokeCube = class(TShape3D) protected procedure Render; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override; end; { TCustomMesh } TCustomMesh = class(TShape3D) private FData: TMeshData; procedure SetData(const Value: TMeshData); protected procedure DoMeshChanged(Sender: TObject); procedure Render; override; property Data: TMeshData read FData write SetData; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override; end; { TCube } TCube = class(TCustomMesh) private FSubdivisionsWidth: Integer; FSubdivisionsDepth: Integer; FSubdivisionsHeight: Integer; procedure SetSubdivisionsDepth(const Value: Integer); procedure SetSubdivisionsHeight(const Value: Integer); procedure SetSubdivisionsWidth(const Value: Integer); protected procedure RebuildMesh; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override; published property SubdivisionsDepth: Integer read FSubdivisionsDepth write SetSubdivisionsDepth default 8; property SubdivisionsHeight: Integer read FSubdivisionsHeight write SetSubdivisionsHeight default 8; property SubdivisionsWidth: Integer read FSubdivisionsWidth write SetSubdivisionsWidth default 8; end; { TPlane } TPlane = class(TCustomMesh) private FSubdivisionsWidth: Integer; FSubdivisionsHeight: Integer; procedure SetSubdivisionsHeight(const Value: Integer); procedure SetSubdivisionsWidth(const Value: Integer); protected procedure SetDepth(const Value: Single); override; procedure RebuildMesh; public constructor Create(AOwner: TComponent); override; function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override; published property SubdivisionsHeight: Integer read FSubdivisionsHeight write SetSubdivisionsHeight default 16; property SubdivisionsWidth: Integer read FSubdivisionsWidth write SetSubdivisionsWidth default 16; end; { TDisk } TDisk = class(TCustomMesh) private FSubdivisionsAxes: Integer; FSubdivisionsCap: Integer; procedure SetSubdivisionsAxes(const Value: Integer); procedure SetSubdivisionsCap(const Value: Integer); protected procedure SetHeight(const Value: Single); override; procedure RebuildMesh; public constructor Create(AOwner: TComponent); override; function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override; published property SubdivisionsAxes: Integer read FSubdivisionsAxes write SetSubdivisionsAxes default 16; property SubdivisionsCap: Integer read FSubdivisionsCap write SetSubdivisionsCap default 1; end; { TMesh } TMesh = class(TCustomMesh) protected procedure Render; override; published property Data; end; { TSphere } TSphere = class(TCustomMesh) private FSubdivisionsAxes: Integer; FSubdivisionsHeight: Integer; procedure SetSubdivisionsAxes(const Value: Integer); procedure SetSubdivisionsHeight(const Value: Integer); protected procedure RebuildMesh; public constructor Create(AOwner: TComponent); override; function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override; published property SubdivisionsAxes: Integer read FSubdivisionsAxes write SetSubdivisionsAxes default 16; property SubdivisionsHeight: Integer read FSubdivisionsHeight write SetSubdivisionsHeight default 12; end; { TCylinder } TCylinder = class(TCustomMesh) private FSubdivisionsAxes: Integer; FSubdivisionsCap: Integer; FSubdivisionsHeight: Integer; procedure SetSubdivisionsAxes(const Value: Integer); procedure SetSubdivisionsCap(const Value: Integer); procedure SetSubdivisionsHeight(const Value: Integer); protected procedure RebuildMesh; public constructor Create(AOwner: TComponent); override; published property SubdivisionsAxes: Integer read FSubdivisionsAxes write SetSubdivisionsAxes default 12; property SubdivisionsCap: Integer read FSubdivisionsCap write SetSubdivisionsCap default 1; property SubdivisionsHeight: Integer read FSubdivisionsHeight write SetSubdivisionsHeight default 1; end; { TRoundCube } TRoundCube = class(TCustomMesh) public constructor Create(AOwner: TComponent); override; end; { TCone } TCone = class(TCustomMesh) private FSubdivisionsAxes: Integer; FSubdivisionsCap: Integer; FSubdivisionsHeight: Integer; procedure SetSubdivisionsAxes(const Value: Integer); procedure SetSubdivisionsCap(const Value: Integer); procedure SetSubdivisionsHeight(const Value: Integer); protected procedure RebuildMesh; public constructor Create(AOwner: TComponent); override; published property SubdivisionsAxes: Integer read FSubdivisionsAxes write SetSubdivisionsAxes default 12; property SubdivisionsCap: Integer read FSubdivisionsCap write SetSubdivisionsCap default 1; property SubdivisionsHeight: Integer read FSubdivisionsHeight write SetSubdivisionsHeight default 1; end; { Pseudo 3D Objects } TExtrudedShapeSide = (esFront, esBack, esShaft); TExtrudedShapeSides = set of TExtrudedShapeSide; { TExtrudedShape3D } TExtrudedShape3D = class(TShape3D) private FFlatness: Single; FSides: TExtrudedShapeSides; FMaterialShaft: TMaterial; FMaterialBack: TMaterial; procedure SetFlatness(const Value: Single); procedure SetSides(const Value: TExtrudedShapeSides); procedure SetMaterialBack(const Value: TMaterial); procedure SetMaterialShaft(const Value: TMaterial); protected procedure Apply; override; procedure Render; override; procedure ShapeMouseMove(Shift: TShiftState; X, Y: Single); virtual; procedure ShapeMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); virtual; procedure ShapeMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); virtual; procedure MouseMove3D(Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); override; procedure MouseDown3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); override; procedure MouseUp3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override; published property Flatness: Single read FFlatness write SetFlatness; property Sides: TExtrudedShapeSides read FSides write SetSides; property MaterialBack: TMaterial read FMaterialBack write SetMaterialBack; property MaterialShaft: TMaterial read FMaterialShaft write SetMaterialShaft; end; { TRectangle3D } TRectangle3D = class(TExtrudedShape3D) private FYRadius: Single; FXRadius: Single; FCorners: TCorners; FCornerType: TCornerType; procedure SetXRadius(const Value: Single); procedure SetYRadius(const Value: Single); function IsCornersStored: Boolean; procedure SetCorners(const Value: TCorners); procedure SetCornerType(const Value: TCornerType); protected procedure Render; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property XRadius: Single read FXRadius write SetXRadius; property YRadius: Single read FYRadius write SetYRadius; property Corners: TCorners read FCorners write SetCorners stored IsCornersStored; property CornerType: TCornerType read FCornerType write SetCornerType; end; { TEllipse3D } TEllipse3D = class(TExtrudedShape3D) protected procedure Render; override; end; { TText3D } TText3D = class(TExtrudedShape3D) private FFont: TFont; FText: WideString; FWordWrap: Boolean; FStretch: Boolean; FVertTextAlign: TTextAlign; FHorzTextAlign: TTextAlign; procedure SetFont(const Value: TFont); procedure SetText(const Value: WideString); procedure SetHorzTextAlign(const Value: TTextAlign); procedure SetStretch(const Value: Boolean); procedure SetVertTextAlign(const Value: TTextAlign); procedure SetWordWrap(const Value: Boolean); protected procedure FontChanged(Sender: TObject); procedure Render; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetTextBounds: TRectF; function GetPathBounds: TRectF; function GetPathLength: Single; published property Font: TFont read FFont write SetFont; property HorzTextAlign: TTextAlign read FHorzTextAlign write SetHorzTextAlign default TTextAlign.taCenter; property VertTextAlign: TTextAlign read FVertTextAlign write SetVertTextAlign default TTextAlign.taCenter; property Text: WideString read FText write SetText; property Stretch: Boolean read FStretch write SetStretch default False; property WordWrap: Boolean read FWordWrap write SetWordWrap default True; end; { TPath3D } TPath3D = class(TExtrudedShape3D) private FPath: TPathData; FWrapMode: TPathWrapMode; procedure SetPath(const Value: TPathData); procedure SetWrapMode(const Value: TPathWrapMode); protected procedure PathChanged(Sender: TObject); procedure Render; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Path: TPathData read FPath write SetPath; property WrapMode: TPathWrapMode read FWrapMode write SetWrapMode default TPathWrapMode.pwStretch; end; { Designer } TSelectionPointKind = (spMove, spRotation); { TSelectionPoint3D } TSelectionPoint3D = class(TControl3D) private FOnTrack: TNotifyEvent; FOnChange: TNotifyEvent; FPressed: Boolean; FOldRayPos, FOldRayDir: TVector3D; FWorkPlane: TPosition3D; FKind: TSelectionPointKind; FAngle: Single; procedure SetWorkPlane(const Value: TPosition3D); protected procedure Render; override; procedure MouseDown3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); override; procedure MouseMove3D(Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); override; procedure MouseUp3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); override; procedure DoMouseEnter; override; procedure DoMouseLeave; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override; property Pressed: Boolean read FPressed; property Angle: Single read FAngle; published property Kind: TSelectionPointKind read FKind write FKind default TSelectionPointKind.spMove; property WorkPlane: TPosition3D read FWorkPlane write SetWorkPlane; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnTrack: TNotifyEvent read FOnTrack write FOnTrack; end; { TModel3D } TMeshDynArray = array of TMesh; TMeshCollection = TMeshDynArray; TModel3D = class(TDummy) private FMeshCollection: TMeshCollection; protected procedure DefineProperties(Filer: TFiler); override; procedure ReadModel(Stream: TStream); procedure WriteModel(Stream: TStream); procedure UpdateMeshCollection; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; virtual; function LoadFromFile(const AFileName: WideString): Boolean; virtual; published property MeshCollection: TMeshCollection read FMeshCollection; end; implementation uses UIConsts, Math, FMX_Import; type THackMaterial = class(TMaterial); { TGrid3D } constructor TGrid3D.Create(AOwner: TComponent); begin inherited; FFrequency := 1; FMarks := 4; FLineColor := $50505050; Depth := 0.001; end; procedure TGrid3D.Render; var X, Y: Single; begin inherited; Context.SetContextState(TContextState.csLightOff); Context.SetTextureUnit(0, nil); X := 0; Y := 0; while X < Width / 2 do begin if (frac(X) = 0) and (frac(X / Marks) = 0) then Context.SetColor(TMaterialColor.mcDiffuse, MakeColor(FLineColor and $FFFFFF or $A0000000, AbsoluteOpacity)) else Context.SetColor(TMaterialColor.mcDiffuse, MakeColor(FLineColor, AbsoluteOpacity)); Context.DrawLine(Vector3D(X, -Height / 2, 0), Vector3D(X, Height / 2, 0), AbsoluteOpacity); Context.DrawLine(Vector3D(-X, -Height / 2, 0), Vector3D(-X, Height / 2, 0), AbsoluteOpacity); X := X + FFrequency; end; while Y < Height / 2 do begin if (frac(Y) = 0) and (frac(Y / Marks) = 0) then Context.SetColor(TMaterialColor.mcDiffuse, MakeColor(FLineColor and $FFFFFF or $A0000000, AbsoluteOpacity)) else Context.SetColor(TMaterialColor.mcDiffuse, MakeColor(FLineColor, AbsoluteOpacity)); Context.DrawLine(Vector3D(-Width / 2, Y, 0), Vector3D(Width / 2, Y, 0), AbsoluteOpacity); Context.DrawLine(Vector3D(-Width / 2, -Y, 0), Vector3D(Width / 2, -Y, 0), AbsoluteOpacity); Y := Y + FFrequency; end; end; function TGrid3D.GetLineColor: TAlphaColor; begin Result := FLineColor; //AlphaColorToString(FLineColor) end; procedure TGrid3D.SetLineColor(const Value: TAlphaColor); //var // NewColor: TAlphaColor; begin // NewColor := StringToAlphaColor(Value); if Value <> FLineColor then FLineColor := Value; end; procedure TGrid3D.SetFrequency(const Value: Single); begin if FFrequency <> Value then begin FFrequency := Value; if FFrequency <= 0 then FFrequency := 0.01; Repaint; end; end; function TGrid3D.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; var IPoint: TVector3D; begin if RayCastPlaneIntersect(RayPos, RayDir, Vector3D(0,0,0), Vector3D(0, 0, -1), IPoint) and (Abs(IPoint.X) < Width / 2) and (Abs(IPoint.Y) < Height / 2) then begin Result := True; Intersection := LocalToAbsoluteVector(IPoint); end else Result := False; end; procedure TGrid3D.SetDepth(const Value: Single); begin inherited SetDepth(0.001); end; procedure TGrid3D.SetMarks(const Value: Single); begin if FMarks <> Value then begin FMarks := Value; Repaint; end; end; { TShape3D } constructor TShape3D.Create(AOwner: TComponent); begin inherited; FMaterial := TMaterial.Create; FMaterial.OnChanged := MaterialChanged; end; destructor TShape3D.Destroy; begin FMaterial.Free; inherited; end; procedure TShape3D.Apply; begin inherited; Context.SetMaterial(FMaterial); end; procedure TShape3D.UnApply; begin inherited; end; procedure TShape3D.MaterialChanged(Sender: TObject); begin Repaint; end; procedure TShape3D.SetMaterial(const Value: TMaterial); begin FMaterial.Assign(Value); end; { TStrokeCube } constructor TStrokeCube.Create(AOwner: TComponent); begin inherited; Material.Lighting := False; end; destructor TStrokeCube.Destroy; begin inherited; end; procedure TStrokeCube.Render; begin inherited; Context.DrawCube(Vector3D(0, 0, 0), Vector3D(Width, Height, Depth), AbsoluteOpacity); end; function TStrokeCube.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; begin Result := inherited; end; { TCustomMesh } constructor TCustomMesh.Create(AOwner: TComponent); begin inherited; FData := TMeshData.Create; FData.OnChanged := DoMeshChanged; end; destructor TCustomMesh.Destroy; begin FData.Free; inherited; end; function TCustomMesh.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; begin if FData.RayCastIntersect(Width, Height, Depth, RayPos, RayDir, Intersection) then begin Intersection := LocalToAbsoluteVector(Intersection); Result := True; end else if csDesigning in ComponentState then Result := inherited else Result := False; end; procedure TCustomMesh.Render; begin Context.SetMatrix(Matrix3DMultiply(CreateScaleMatrix3D(Vector3D(Width, Height, Depth)), AbsoluteMatrix)); Context.DrawTrianglesList(FData.VertexBuffer, FData.IndexBuffer, AbsoluteOpacity); end; procedure TCustomMesh.SetData(const Value: TMeshData); begin FData.Assign(Value); end; procedure TCustomMesh.DoMeshChanged(Sender: TObject); begin Repaint; end; { TPlane } constructor TPlane.Create(AOwner: TComponent); begin inherited; Depth := 0.001; FSubdivisionsWidth := 16; FSubdivisionsHeight := 16; RebuildMesh; end; procedure TPlane.RebuildMesh; var X, Y: Integer; begin FData.VertexBuffer.Length := (FSubdivisionsWidth + 1) * (FSubdivisionsHeight + 1); for Y := 0 to FSubdivisionsHeight do for X := 0 to FSubdivisionsWidth do begin FData.VertexBuffer.Vertices[X + (Y * (FSubdivisionsWidth + 1))] := Point3D(-0.5 + (X / FSubdivisionsWidth), 0.5 - (Y / FSubdivisionsHeight), 0); FData.VertexBuffer.Normals[X + (Y * (FSubdivisionsWidth + 1))] := Point3D(0, 0, -1); FData.VertexBuffer.TexCoord0[X + (Y * (FSubdivisionsWidth + 1))] := PointF(X / FSubdivisionsWidth, Y / FSubdivisionsHeight); end; FData.IndexBuffer.Length := FSubdivisionsWidth * FSubdivisionsHeight * 6; for Y := 0 to FSubdivisionsHeight - 1 do for X := 0 to FSubdivisionsWidth - 1 do begin FData.IndexBuffer[(X + (Y * (FSubdivisionsWidth + 0))) * 6 + 0] := X + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[(X + (Y * (FSubdivisionsWidth + 0))) * 6 + 2] := X + 1 + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[(X + (Y * (FSubdivisionsWidth + 0))) * 6 + 1] := X + ((Y + 1) * (FSubdivisionsWidth + 1)); FData.IndexBuffer[(X + (Y * (FSubdivisionsWidth + 0))) * 6 + 3] := X + ((Y + 1) * (FSubdivisionsWidth + 1)); FData.IndexBuffer[(X + (Y * (FSubdivisionsWidth + 0))) * 6 + 5] := X + 1 + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[(X + (Y * (FSubdivisionsWidth + 0))) * 6 + 4] := X + 1 + ((Y + 1) * (FSubdivisionsWidth + 1)); end; end; function TPlane.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; var IPoint: TVector3D; begin if RayCastPlaneIntersect(RayPos, RayDir, Vector3D(0,0,0), Vector3D(0, 0, -1), IPoint) and (Abs(IPoint.X) < Width / 2) and (Abs(IPoint.Y) < Height / 2) then begin Result := True; Intersection := LocalToAbsoluteVector(IPoint); end else Result := False; end; procedure TPlane.SetDepth(const Value: Single); begin inherited SetDepth(0.001); end; procedure TPlane.SetSubdivisionsHeight(const Value: Integer); begin if FSubdivisionsHeight <> Value then begin FSubdivisionsHeight := Value; if FSubdivisionsHeight < 1 then FSubdivisionsHeight := 1; RebuildMesh; end; end; procedure TPlane.SetSubdivisionsWidth(const Value: Integer); begin if FSubdivisionsWidth <> Value then begin FSubdivisionsWidth := Value; if FSubdivisionsWidth < 1 then FSubdivisionsWidth := 1; RebuildMesh; end; end; { TDisk } constructor TDisk.Create(AOwner: TComponent); begin inherited; Height := 0.001; FSubdivisionsAxes := 16; FSubdivisionsCap := 1; RebuildMesh; end; function TDisk.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; var IPoint: TVector3D; begin if RayCastPlaneIntersect(RayPos, RayDir, Vector3D(0,0,0), Vector3D(0, -1, 0), IPoint) and (Width > 0) and (Depth > 0) and (Sqr(IPoint.X / (Width / 2)) + Sqr(IPoint.Z / (Depth / 2)) <= 1) then begin Result := True; Intersection := LocalToAbsoluteVector(IPoint); end else Result := False; end; procedure TDisk.RebuildMesh; var A, H, AA, HH: Integer; Theta, Phi: Single; DTheta, DPhi: Single; PhiSin, PhiCos: Extended; IdxCount: Integer; VerticesWidth: Integer; begin VerticesWidth := (FSubdivisionsAxes + 1); FData.VertexBuffer.Length := (FSubdivisionsCap) * VerticesWidth + 1; FData.IndexBuffer.Length := (FSubdivisionsCap - 1) * FSubdivisionsAxes * 6 + (FSubdivisionsAxes * 3); DPhi := DegToRad(360) / FSubdivisionsAxes; IdxCount := 0; // fill indices FData.VertexBuffer.Vertices[FData.VertexBuffer.Length - 1] := Point3D(0, 0, 0); FData.VertexBuffer.TexCoord0[FData.VertexBuffer.Length - 1] := PointF(0.5, 0.5); FData.VertexBuffer.Normals[FData.VertexBuffer.Length - 1] := Point3D(0, -1, 0); for H := 0 to FSubdivisionsCap - 1 do begin Phi := 0; for A := 0 to FSubdivisionsAxes - 1 do begin SinCos(Phi, PhiSin, PhiCos); FData.VertexBuffer.Vertices[A + (H * VerticesWidth)] := Point3D(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap), 0, PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap)); FData.VertexBuffer.TexCoord0[A + (H * VerticesWidth)] := PointF(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5, 1 - (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5)); FData.VertexBuffer.Normals[A + (H * VerticesWidth)] := Point3D(0, -1, 0); if A = 0 then begin FData.VertexBuffer.Vertices[FSubdivisionsAxes + (H * VerticesWidth)] := Point3D(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap), 0, PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap)); FData.VertexBuffer.TexCoord0[FSubdivisionsAxes + (H * VerticesWidth)] := PointF(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5, 1 - (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5)); FData.VertexBuffer.Normals[FSubdivisionsAxes + (H * VerticesWidth)] := Point3D(0, -1, 0); end; AA := A + 1; HH := H - 1; if H = 0 then begin FData.IndexBuffer.Indices[IdxCount + 0] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 1] := FData.VertexBuffer.Length - 1; FData.IndexBuffer.Indices[IdxCount + 2] := AA + (H * VerticesWidth); IdxCount := IdxCount + 3; end else begin FData.IndexBuffer.Indices[IdxCount + 0] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := AA + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 1] := A + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 3] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 5] := AA + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 4] := AA + (HH * VerticesWidth); IdxCount := IdxCount + 6; end; Phi := Phi + DPhi; end; end; end; procedure TDisk.SetHeight(const Value: Single); begin inherited SetHeight(0.001); end; procedure TDisk.SetSubdivisionsAxes(const Value: Integer); begin if FSubdivisionsAxes <> Value then begin FSubdivisionsAxes := Value; if FSubdivisionsAxes < 3 then FSubdivisionsAxes := 3; RebuildMesh; end; end; procedure TDisk.SetSubdivisionsCap(const Value: Integer); begin if FSubdivisionsCap <> Value then begin FSubdivisionsCap := Value; if FSubdivisionsCap < 1 then FSubdivisionsCap := 1; RebuildMesh; end; end; { TCube } constructor TCube.Create(AOwner: TComponent); begin inherited; FSubdivisionsDepth := 8; FSubdivisionsHeight := 8; FSubdivisionsWidth := 8; RebuildMesh; end; destructor TCube.Destroy; begin inherited; end; procedure TCube.RebuildMesh; var X, Y: Integer; Face: Integer; FaceVertexLength: Integer; FaceIndexLength: Integer; VertexOffset: Integer; IndexOffset: Integer; begin FData.VertexBuffer.Length := (FSubdivisionsWidth + 1) * (FSubdivisionsHeight + 1) * 2 + (FSubdivisionsDepth + 1) * (FSubdivisionsWidth + 1) * 2 + (FSubdivisionsDepth + 1) * (FSubdivisionsHeight + 1) * 2; FData.IndexBuffer.Length := (FSubdivisionsWidth) * (FSubdivisionsHeight) * 6 * 2 + (FSubdivisionsDepth) * (FSubdivisionsWidth) * 6 * 2 + (FSubdivisionsDepth) * (FSubdivisionsHeight) * 6 * 2; VertexOffset := 0; IndexOffset := 0; FaceVertexLength := (FSubdivisionsWidth + 1) * (FSubdivisionsHeight + 1); FaceIndexLength := FSubdivisionsWidth * FSubdivisionsHeight * 6; for Face := 0 to 1 do begin for Y := 0 to FSubdivisionsHeight do for X := 0 to FSubdivisionsWidth do begin if not Odd(Face) then begin FData.VertexBuffer.Vertices[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := Point3D(-0.5 + (X / FSubdivisionsWidth), -0.5 + (Y / FSubdivisionsHeight), -0.5); FData.VertexBuffer.Normals[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := Point3D(0, 0, -1); FData.VertexBuffer.TexCoord0[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := PointF(X / FSubdivisionsWidth, Y / FSubdivisionsHeight); end else begin FData.VertexBuffer.Vertices[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := Point3D(-0.5 + (X / FSubdivisionsWidth), -0.5 + (Y / FSubdivisionsHeight), 0.5); FData.VertexBuffer.Normals[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := Point3D(0, 0, 1); FData.VertexBuffer.TexCoord0[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := PointF(1 - X / FSubdivisionsWidth, Y / FSubdivisionsHeight); end; end; for Y := 0 to FSubdivisionsHeight - 1 do for X := 0 to FSubdivisionsWidth - 1 do begin if Odd(Face) then begin FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 0] := VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 2] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 1] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 3] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 5] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 4] := VertexOffset + (Face * FaceVertexLength) + X + 1 + ((Y + 1) * (FSubdivisionsWidth + 1)); end else begin FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 0] := VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 1] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 2] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 3] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 4] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 5] := VertexOffset + (Face * FaceVertexLength) + X + 1 + ((Y + 1) * (FSubdivisionsWidth + 1)); end; end; end; VertexOffset := VertexOffset + FaceVertexLength * 2; IndexOffset := IndexOffset + FaceIndexLength * 2; FaceVertexLength := (FSubdivisionsDepth + 1) * (FSubdivisionsWidth + 1); FaceIndexLength := FSubdivisionsDepth * FSubdivisionsWidth * 6; for Face := 0 to 1 do begin for Y := 0 to FSubdivisionsDepth do for X := 0 to FSubdivisionsWidth do begin if Odd(Face) then begin FData.VertexBuffer.Vertices[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := Point3D(-0.5 + (X / FSubdivisionsWidth), -0.5, -0.5 + (Y / FSubdivisionsDepth)); FData.VertexBuffer.Normals[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := Point3D(0, -1, 0); FData.VertexBuffer.TexCoord0[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := PointF(X / FSubdivisionsWidth, 1 - Y / FSubdivisionsDepth); end else begin FData.VertexBuffer.Vertices[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := Point3D(-0.5 + (X / FSubdivisionsWidth), 0.5, -0.5 + (Y / FSubdivisionsDepth)); FData.VertexBuffer.Normals[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := Point3D(0, 1, 0); FData.VertexBuffer.TexCoord0[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1))] := PointF(X / FSubdivisionsWidth, Y / FSubdivisionsDepth); end; end; for Y := 0 to FSubdivisionsDepth - 1 do for X := 0 to FSubdivisionsWidth - 1 do begin if Odd(Face) then begin FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 0] := VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 2] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 1] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 3] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 5] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 4] := VertexOffset + (Face * FaceVertexLength) + X + 1 + ((Y + 1) * (FSubdivisionsWidth + 1)); end else begin FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 0] := VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 1] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 2] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 3] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 4] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsWidth + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsWidth + 0))) * 6 + 5] := VertexOffset + (Face * FaceVertexLength) + X + 1 + ((Y + 1) * (FSubdivisionsWidth + 1)); end; end; end; VertexOffset := VertexOffset + FaceVertexLength * 2; IndexOffset := IndexOffset + FaceIndexLength * 2; FaceVertexLength := (FSubdivisionsDepth + 1) * (FSubdivisionsHeight + 1); FaceIndexLength := FSubdivisionsDepth * FSubdivisionsHeight * 6; for Face := 0 to 1 do begin for Y := 0 to FSubdivisionsDepth do for X := 0 to FSubdivisionsHeight do begin if Odd(Face) then begin FData.VertexBuffer.Vertices[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsHeight + 1))] := Point3D(-0.5, -0.5 + (X / FSubdivisionsHeight), -0.5 + (Y / FSubdivisionsDepth)); FData.VertexBuffer.Normals[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsHeight + 1))] := Point3D(-1, 0, 0); FData.VertexBuffer.TexCoord0[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsHeight + 1))] := PointF(1 - Y / FSubdivisionsDepth, X / FSubdivisionsHeight); end else begin FData.VertexBuffer.Vertices[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsHeight + 1))] := Point3D(0.5, -0.5 + (X / FSubdivisionsHeight), -0.5 + (Y / FSubdivisionsDepth)); FData.VertexBuffer.Normals[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsHeight + 1))] := Point3D(1, 0, 0); FData.VertexBuffer.TexCoord0[VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsHeight + 1))] := PointF(Y / FSubdivisionsDepth, X / FSubdivisionsHeight); end; end; for Y := 0 to FSubdivisionsDepth - 1 do for X := 0 to FSubdivisionsHeight - 1 do begin if not Odd(Face) then begin FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 0] := VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsHeight + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 2] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsHeight + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 1] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsHeight + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 3] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsHeight + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 5] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsHeight + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 4] := VertexOffset + (Face * FaceVertexLength) + X + 1 + ((Y + 1) * (FSubdivisionsHeight + 1)); end else begin FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 0] := VertexOffset + (Face * FaceVertexLength) + X + (Y * (FSubdivisionsHeight + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 1] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsHeight + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 2] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsHeight + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 3] := VertexOffset + (Face * FaceVertexLength) + X + ((Y + 1) * (FSubdivisionsHeight + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 4] := VertexOffset + (Face * FaceVertexLength) + X + 1 + (Y * (FSubdivisionsHeight + 1)); FData.IndexBuffer[IndexOffset + (Face * FaceIndexLength) + (X + (Y * (FSubdivisionsHeight + 0))) * 6 + 5] := VertexOffset + (Face * FaceVertexLength) + X + 1 + ((Y + 1) * (FSubdivisionsHeight + 1)); end; end; end; end; function TCube.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; var INear, IFar: TVector3D; begin // Calling inherited will search through the MeshData for intersection. This is // wasted effort for such a simple shape. Result := RayCastCuboidIntersect(RayPos, RayDir, Vector3D(0,0,0), Width, Height, Depth, INear, IFar) > 0; if Result then Intersection := LocalToAbsoluteVector(INear); end; procedure TCube.SetSubdivisionsDepth(const Value: Integer); begin if FSubdivisionsDepth <> Value then begin FSubdivisionsDepth := Value; if FSubdivisionsDepth < 1 then FSubdivisionsDepth := 1; RebuildMesh; end; end; procedure TCube.SetSubdivisionsHeight(const Value: Integer); begin if FSubdivisionsHeight <> Value then begin FSubdivisionsHeight := Value; if FSubdivisionsHeight < 1 then FSubdivisionsHeight := 1; RebuildMesh; end; end; procedure TCube.SetSubdivisionsWidth(const Value: Integer); begin if FSubdivisionsWidth <> Value then begin FSubdivisionsWidth := Value; if FSubdivisionsWidth < 1 then FSubdivisionsWidth := 1; RebuildMesh; end; end; { TSphere } constructor TSphere.Create(AOwner: TComponent); begin inherited; FSubdivisionsAxes := 16; FSubdivisionsHeight := 12; RebuildMesh; end; procedure TSphere.RebuildMesh; var A, H, AA, HH: Integer; Theta, Phi: Single; DTheta, DPhi: Single; {$IFDEF FPC} ThetaSin, ThetaCos: Extended; PhiSin, PhiCos: Extended; {$ELSE} ThetaSin, ThetaCos: Extended; PhiSin, PhiCos: Extended; {$ENDIF} IdxCount: Integer; VerticesWidth: Integer; N, N1, N2: TPoint3D; begin VerticesWidth := (FSubdivisionsAxes + 1); FData.VertexBuffer.Length := (FSubdivisionsHeight + 1) * VerticesWidth - 1; FData.IndexBuffer.Length := (FSubdivisionsHeight - 2) * FSubdivisionsAxes * 6 + (FSubdivisionsAxes * 3) + (FSubdivisionsAxes * 3); DTheta := DegToRad(180) / FSubdivisionsHeight; DPhi := DegToRad(360) / FSubdivisionsAxes; IdxCount := 0; // fill indices Theta := -DegToRad(90); for H := 0 to FSubdivisionsHeight - 1 do begin Phi := 0; for A := 0 to FSubdivisionsAxes - 1 do begin SinCos(Theta, ThetaSin, ThetaCos); SinCos(Phi, PhiSin, PhiCos); FData.VertexBuffer.Vertices[A + (H * VerticesWidth)] := Point3D(ThetaCos * PhiCos * 0.5, ThetaSin * 0.5, ThetaCos * PhiSin * 0.5); FData.VertexBuffer.TexCoord0[A + (H * VerticesWidth)] := PointF(A / FSubdivisionsAxes, H / FSubdivisionsHeight); if A = 0 then begin FData.VertexBuffer.Vertices[FSubdivisionsAxes + (H * VerticesWidth)] := Point3D(ThetaCos * PhiCos * 0.5, ThetaSin * 0.5, ThetaCos * PhiSin * 0.5); FData.VertexBuffer.TexCoord0[FSubdivisionsAxes + (H * VerticesWidth)] := PointF(1, H / FSubdivisionsHeight); end; AA := A + 1; HH := H + 1; if H = 0 then begin FData.VertexBuffer.TexCoord0[A + (H * VerticesWidth)] := PointF((A + 0.5) / FSubdivisionsAxes, 0); FData.IndexBuffer.Indices[IdxCount + 0] := A; FData.IndexBuffer.Indices[IdxCount + 1] := AA + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := A + (HH * VerticesWidth); IdxCount := IdxCount + 3; end else if H = FSubdivisionsHeight - 1 then begin FData.VertexBuffer.Vertices[A + (FSubdivisionsHeight * VerticesWidth)] := Point3D(0, 0.5, 0); FData.VertexBuffer.TexCoord0[A + (FSubdivisionsHeight * VerticesWidth)] := PointF((A + 0.5) / FSubdivisionsAxes, 1); FData.IndexBuffer.Indices[IdxCount + 0] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 1] := AA + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := A + (HH * VerticesWidth); IdxCount := IdxCount + 3; end else begin FData.IndexBuffer.Indices[IdxCount + 0] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 1] := AA + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := A + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 3] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 4] := AA + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 5] := AA + (HH * VerticesWidth); IdxCount := IdxCount + 6; end; Phi := Phi + DPhi; end; Theta := Theta + DTheta; end; FData.CalcNormals; // merge normals at the top for A := 0 to FSubdivisionsAxes - 1 do FData.VertexBuffer.Normals[A] := Point3D(0, -1, 0); // merge normals at the bottom for A := 0 to FSubdivisionsAxes - 1 do FData.VertexBuffer.Normals[A + (FSubdivisionsHeight * VerticesWidth)] := Point3D(0, 1, 0); // merge normals in split for H := 1 to FSubdivisionsHeight - 1 do begin N1 := FData.VertexBuffer.Normals[0 + (H * VerticesWidth)]; N2 := FData.VertexBuffer.Normals[FSubdivisionsAxes + (H * VerticesWidth)]; N.X := (N1.X + N2.X) / 2; N.Y := (N1.Y + N2.Y) / 2; N.Z := (N1.Z + N2.Z) / 2; N := Point3D(Vector3DNormalize(Vector3D(N))); FData.VertexBuffer.Normals[0 + (H * VerticesWidth)] := N; FData.VertexBuffer.Normals[FSubdivisionsAxes + (H * VerticesWidth)] := N; end; end; function TSphere.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; var INear, IFar: TVector3D; begin // Calling inherited will search through the MeshData for intersection. This is // wasted effort for such a simple shape. Result := RayCastEllipsoidIntersect(RayPos, RayDir, Vector3D(0,0,0), Width/2, Height/2, Depth/2, INear, IFar) > 0; if Result then Intersection := LocalToAbsoluteVector(INear); end; procedure TSphere.SetSubdivisionsAxes(const Value: Integer); begin if FSubdivisionsAxes <> Value then begin FSubdivisionsAxes := Value; if FSubdivisionsAxes < 3 then FSubdivisionsAxes := 3; if FSubdivisionsAxes > 50 then FSubdivisionsAxes := 50; RebuildMesh; end; end; procedure TSphere.SetSubdivisionsHeight(const Value: Integer); begin if FSubdivisionsHeight <> Value then begin FSubdivisionsHeight := Value; if FSubdivisionsHeight < 2 then FSubdivisionsHeight := 2; if FSubdivisionsHeight > 50 then FSubdivisionsHeight := 50; RebuildMesh; end; end; { TCylinder } constructor TCylinder.Create(AOwner: TComponent); begin inherited; FSubdivisionsAxes := 12; FSubdivisionsCap := 2; FSubdivisionsHeight := 1; RebuildMesh; end; procedure TCylinder.RebuildMesh; var A, H, AA, HH: Integer; Theta, Phi: Single; S, DTheta, DPhi: Single; PhiSin, PhiCos: Extended; IdxCount: Integer; Offset, VerticesWidth: Integer; N, N1, N2: TPoint3D; begin VerticesWidth := (FSubdivisionsAxes + 1); FData.VertexBuffer.Length := (FSubdivisionsCap * VerticesWidth + 1) * 2 + ((FSubdivisionsHeight + 1) * VerticesWidth); FData.IndexBuffer.Length := ((FSubdivisionsCap - 1) * FSubdivisionsAxes * 6 + (FSubdivisionsAxes * 3)) * 2 + FSubdivisionsHeight * FSubdivisionsAxes * 6; DPhi := DegToRad(360) / FSubdivisionsAxes; IdxCount := 0; // bottom and top FData.VertexBuffer.Vertices[FData.VertexBuffer.Length - 1] := Point3D(0, 0.5, 0); FData.VertexBuffer.TexCoord0[FData.VertexBuffer.Length - 1] := PointF(0.5, 0.5); FData.VertexBuffer.Normals[FData.VertexBuffer.Length - 1] := Point3D(0, 1, 0); FData.VertexBuffer.Vertices[FData.VertexBuffer.Length - 2] := Point3D(0, -0.5, 0); FData.VertexBuffer.TexCoord0[FData.VertexBuffer.Length - 2] := PointF(0.5, 0.5); FData.VertexBuffer.Normals[FData.VertexBuffer.Length - 2] := Point3D(0, -1, 0); Offset := VerticesWidth * FSubdivisionsCap; for H := 0 to FSubdivisionsCap - 1 do begin Phi := 0; for A := 0 to FSubdivisionsAxes - 1 do begin SinCos(Phi, PhiSin, PhiCos); // bottom FData.VertexBuffer.Vertices[A + (H * VerticesWidth)] := Point3D(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap), 0.5, (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap))); FData.VertexBuffer.TexCoord0[A + (H * VerticesWidth)] := PointF(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5, 1 - (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5)); if A = 0 then begin FData.VertexBuffer.Vertices[FSubdivisionsAxes + (H * VerticesWidth)] := Point3D(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap), 0.5, (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap))); FData.VertexBuffer.TexCoord0[FSubdivisionsAxes + (H * VerticesWidth)] := PointF(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5, 1 - (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5)); end; AA := A + 1; HH := H - 1; if H = 0 then begin FData.IndexBuffer.Indices[IdxCount + 0] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := FData.VertexBuffer.Length - 1; FData.IndexBuffer.Indices[IdxCount + 1] := AA + (H * VerticesWidth); IdxCount := IdxCount + 3; end else begin FData.IndexBuffer.Indices[IdxCount + 0] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 1] := AA + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := A + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 3] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 4] := AA + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 5] := AA + (HH * VerticesWidth); IdxCount := IdxCount + 6; end; // top FData.VertexBuffer.Vertices[Offset + A + (H * VerticesWidth)] := Point3D(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap), -0.5, (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap))); FData.VertexBuffer.TexCoord0[Offset + A + (H * VerticesWidth)] := PointF(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5, 1 - (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5)); if A = 0 then begin FData.VertexBuffer.Vertices[Offset + FSubdivisionsAxes + (H * VerticesWidth)] := Point3D(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap), -0.5, (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap))); FData.VertexBuffer.TexCoord0[Offset + FSubdivisionsAxes + (H * VerticesWidth)] := PointF(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5, 1 - (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5)); end; if H = 0 then begin FData.IndexBuffer.Indices[IdxCount + 0] := Offset + A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 1] := FData.VertexBuffer.Length - 2; FData.IndexBuffer.Indices[IdxCount + 2] := Offset + AA + (H * VerticesWidth); IdxCount := IdxCount + 3; end else begin FData.IndexBuffer.Indices[IdxCount + 0] := Offset + A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := Offset + AA + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 1] := Offset + A + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 3] := Offset + A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 5] := Offset + AA + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 4] := Offset + AA + (HH * VerticesWidth); IdxCount := IdxCount + 6; end; Phi := Phi + DPhi; end; end; // sides Phi := 0; Offset := Offset + VerticesWidth * FSubdivisionsCap; for H := 0 to FSubdivisionsHeight - 1 do for A := 0 to FSubdivisionsAxes - 1 do begin SinCos(Phi, PhiSin, PhiCos); S := 1 - (H / FSubdivisionsHeight); FData.VertexBuffer.Vertices[Offset + A + (H * VerticesWidth)] := Point3D(PhiCos * 0.5 * S, 0.5 - (1 - S), PhiSin * 0.5 * S); FData.VertexBuffer.TexCoord0[Offset + A + (H * VerticesWidth)] := PointF(A / FSubdivisionsAxes, S); if H = 0 then begin FData.VertexBuffer.Vertices[Offset + A + (FSubdivisionsHeight * VerticesWidth)] := Point3D(PhiCos * 0.5 * S, -0.5, PhiSin * 0.5 * S); FData.VertexBuffer.TexCoord0[Offset + A + (FSubdivisionsHeight * VerticesWidth)] := PointF(A / FSubdivisionsAxes, 0); end; if A = 0 then begin FData.VertexBuffer.Vertices[Offset + FSubdivisionsAxes + (H * VerticesWidth)] := FData.VertexBuffer.Vertices[Offset + (H * VerticesWidth)]; FData.VertexBuffer.TexCoord0[Offset + FSubdivisionsAxes + (H * VerticesWidth)] := PointF(1, S); if H = 0 then begin FData.VertexBuffer.Vertices[Offset + FSubdivisionsAxes + (FSubdivisionsHeight * VerticesWidth)] := Point3D(PhiCos * 0.5 * S, -0.5, PhiSin * 0.5 * S); FData.VertexBuffer.TexCoord0[Offset + FSubdivisionsAxes + (FSubdivisionsHeight * VerticesWidth)] := PointF(1, 0); end; end; AA := A + 1; HH := H + 1; FData.IndexBuffer.Indices[IdxCount + 0] := Offset + A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := Offset + AA + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 1] := Offset + A + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 3] := Offset + A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 5] := Offset + AA + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 4] := Offset + AA + (HH * VerticesWidth); IdxCount := IdxCount + 6; Phi := Phi + DPhi; end; FData.CalcNormals; // smooth split for H := 0 to FSubdivisionsHeight do begin N1 := FData.VertexBuffer.Normals[Offset + 0 + (H * VerticesWidth)]; N2 := FData.VertexBuffer.Normals[Offset + FSubdivisionsAxes + (H * VerticesWidth)]; N.X := (N1.X + N2.X) / 2; N.Y := (N1.Y + N2.Y) / 2; N.Z := (N1.Z + N2.Z) / 2; N := Point3D(Vector3DNormalize(Vector3D(N))); FData.VertexBuffer.Normals[Offset + 0 + (H * VerticesWidth)] := N; FData.VertexBuffer.Normals[Offset + FSubdivisionsAxes + (H * VerticesWidth)] := N; end; end; procedure TCylinder.SetSubdivisionsAxes(const Value: Integer); begin if FSubdivisionsAxes <> Value then begin FSubdivisionsAxes := Value; if FSubdivisionsAxes < 3 then FSubdivisionsAxes := 3; RebuildMesh; end; end; procedure TCylinder.SetSubdivisionsCap(const Value: Integer); begin if FSubdivisionsCap <> Value then begin FSubdivisionsCap := Value; if FSubdivisionsCap < 1 then FSubdivisionsCap := 1; RebuildMesh; end; end; procedure TCylinder.SetSubdivisionsHeight(const Value: Integer); begin if FSubdivisionsHeight <> Value then begin FSubdivisionsHeight := Value; if FSubdivisionsHeight < 1 then FSubdivisionsHeight := 1; RebuildMesh; end; end; { TRoundCube } const RoundCubeVertices: array [0 .. 201] of TMeshVertex = ((X: - 0.42; Y: 0.42; z: 0.5; nx: - 0.0184349; ny: 0.00943183; nz: 1.5144; tu: 0.08; tv: 0.08;), (X: 0.42; Y: 0.42; z: 0.5; nx: 0.00943183; ny: 0.0184349; nz: 0.8088; tu: 0.92; tv: 0.08;), (X: - 0.42; Y: - 0.42; z: 0.5; nx: - 0.00943183; ny: - 0.0184349; nz: 0.8088; tu: 0.08; tv: 0.92; ), (X: 0.42; Y: - 0.42; z: 0.5; nx: 0.0184349; ny: - 0.00943183; nz: 1.5144; tu: 0.92; tv: 0.92; ), (X: - 0.42; Y: 0.46; z: 0.489282; nx: - 0.000486155; ny: 0.0444174; nz: 0.0941968; tu: 0.08; tv: 0.04; ), (X: - 0.44; Y: 0.454641; z: 0.489282; nx: - 0.00154256; ny: 0.0021282; nz: 0.00378564; tu: 0.06; tv: 0.045359; ), (X: - 0.454641; Y: 0.44; z: 0.489282; nx: - 0.00239999; ny: 0.00107179; nz: 0.00378564; tu: 0.045359; tv: 0.0599999;), (X: - 0.46; Y: 0.42; z: 0.489282; nx: - 0.0589968; ny: 0.000214357; nz: 0.0841794; tu: 0.04; tv: 0.08;), (X: - 0.46; Y: - 0.42; z: 0.489282; nx: - 0.0444174; ny: - 0.000486152; nz: 0.0941968; tu: 0.04; tv: 0.92;), (X: - 0.454641; Y: - 0.44; z: 0.489282; nx: - 0.0021282; ny: - 0.00154256; nz: 0.00378564; tu: 0.045359; tv: 0.94;), (X: - 0.44; Y: - 0.454641; z: 0.489282; nx: - 0.0010718; ny: - 0.0024; nz: 0.00378564; tu: 0.06; tv: 0.954641;), (X: - 0.42; Y: - 0.46; z: 0.489282; nx: - 0.00021436; ny: - 0.0589968; nz: 0.0841795; tu: 0.08; tv: 0.96;), (X: 0.42; Y: - 0.46; z: 0.489282; nx: 0.000486156; ny: - 0.0444174; nz: 0.0941969; tu: 0.92; tv: 0.96; ), (X: 0.44; Y: - 0.454641; z: 0.489282; nx: 0.00154256; ny: - 0.0021282; nz: 0.00378564; tu: 0.94; tv: 0.954641; ), (X: 0.454641; Y: - 0.44; z: 0.489282; nx: 0.0024; ny: - 0.0010718; nz: 0.00378564; tu: 0.954641; tv: 0.94; ), (X: 0.46; Y: - 0.42; z: 0.489282; nx: 0.0589968; ny: - 0.000214359; nz: 0.0841795; tu: 0.96; tv: 0.92; ), (X: 0.46; Y: 0.42; z: 0.489282; nx: 0.0444174; ny: 0.000486156; nz: 0.0941969; tu: 0.96; tv: 0.08; ), (X: 0.454641; Y: 0.44; z: 0.489282; nx: 0.0021282; ny: 0.00154256; nz: 0.00378564; tu: 0.954641; tv: 0.06; ), (X: 0.44; Y: 0.454641; z: 0.489282; nx: 0.00107179; ny: 0.0024; nz: 0.00378564; tu: 0.94; tv: 0.045359; ), (X: 0.42; Y: 0.46; z: 0.489282; nx: 0.000214357; ny: 0.0589968; nz: 0.0841794; tu: 0.92; tv: 0.04; ), (X: - 0.42; Y: 0.489282; z: 0.46; nx: - 0.00107179; ny: 0.0867937; nz: 0.0600113; tu: 0.08; tv: 0.010718; ), (X: - 0.454641; Y: 0.48; z: 0.46; nx: - 0.0037282; ny: 0.00591384; nz: 0.00378564; tu: 0.045359; tv: 0.02; ), (X: - 0.48; Y: 0.454641; z: 0.46; nx: - 0.00618564; ny: 0.00325743; nz: 0.00378564; tu: 0.02; tv: 0.045359; ), (X: - 0.489282; Y: 0.42; z: 0.46; nx: - 0.0947825; ny: 0.000799995; nz: 0.0445744; tu: 0.010718; tv: 0.08; ), (X: - 0.489282; Y: - 0.42; z: 0.46; nx: - 0.0867937; ny: - 0.00107179; nz: 0.0600113; tu: 0.010718; tv: 0.92; ), (X: - 0.48; Y: - 0.454641; z: 0.46; nx: - 0.00591384; ny: - 0.0037282; nz: 0.00378564; tu: 0.02; tv: 0.954641; ), (X: - 0.454641; Y: - 0.48; z: 0.46; nx: - 0.00325744; ny: - 0.00618564; nz: 0.00378564; tu: 0.045359; tv: 0.98; ), (X: - 0.42; Y: - 0.489282; z: 0.46; nx: - 0.000800001; ny: - 0.0947825; nz: 0.0445743; tu: 0.08; tv: 0.989282; ), (X: 0.42; Y: - 0.489282; z: 0.46; nx: 0.0010718; ny: - 0.0867937; nz: 0.0600112; tu: 0.92; tv: 0.989282; ), (X: 0.454641; Y: - 0.48; z: 0.46; nx: 0.0037282; ny: - 0.00591384; nz: 0.00378564; tu: 0.954641; tv: 0.98; ), (X: 0.48; Y: - 0.454641; z: 0.46; nx: 0.00618564; ny: - 0.00325743; nz: 0.00378564; tu: 0.98; tv: 0.954641; ), (X: 0.489282; Y: - 0.42; z: 0.46; nx: 0.0947825; ny: - 0.000800001; nz: 0.0445743; tu: 0.989282; tv: 0.92; ), (X: 0.489282; Y: 0.42; z: 0.46; nx: 0.0867937; ny: 0.0010718; nz: 0.0600112; tu: 0.989282; tv: 0.08; ), (X: 0.48; Y: 0.454641; z: 0.46; nx: 0.00591384; ny: 0.0037282; nz: 0.00378564; tu: 0.98; tv: 0.045359; ), (X: 0.454641; Y: 0.48; z: 0.46; nx: 0.00325743; ny: 0.00618564; nz: 0.00378564; tu: 0.954641; tv: 0.02; ), (X: 0.42; Y: 0.489282; z: 0.46; nx: 0.000799995; ny: 0.0947825; nz: 0.0445744; tu: 0.92; tv: 0.010718; ), (X: - 0.42; Y: 0.5; z: 0.42; nx: - 0.00042872; ny: 0.0688001; nz: 0.0184349; tu: 0.08; tv: 0; ), (X: - 0.46; Y: 0.489282; z: 0.42; nx: - 0.00197128; ny: 0.00415692; nz: 0.00122871; tu: 0.04; tv: 0.010718; ), (X: - 0.489282; Y: 0.46; z: 0.42; nx: - 0.00378564; ny: 0.00261436; nz: 0.00122871; tu: 0.010718; tv: 0.04; ), (X: - 0.5; Y: 0.42; z: 0.42; nx: - 0.0365857; ny: 0.0008; nz: 0.00980311; tu: 0; tv: 0.08; ), (X: - 0.5; Y: - 0.42; z: 0.42; nx: - 0.0688001; ny: - 0.00042872; nz: 0.0184349; tu: 0; tv: 0.92; ), (X: - 0.489282; Y: - 0.46; z: 0.42; nx: - 0.00415693; ny: - 0.00197128; nz: 0.00122872; tu: 0.010718; tv: 0.96; ), (X: - 0.46; Y: - 0.489282; z: 0.42; nx: - 0.00261436; ny: - 0.00378564; nz: 0.00122872; tu: 0.04; tv: 0.989282; ), (X: - 0.42; Y: - 0.5; z: 0.42; nx: - 0.0008; ny: - 0.0365857; nz: 0.00980306; tu: 0.08; tv: 1; ), (X: 0.42; Y: - 0.5; z: 0.42; nx: 0.000428717; ny: - 0.0688001; nz: 0.0184348; tu: 0.92; tv: 1; ), (X: 0.46; Y: - 0.489282; z: 0.42; nx: 0.00197128; ny: - 0.00415692; nz: 0.00122872; tu: 0.96; tv: 0.989282; ), (X: 0.489282; Y: - 0.46; z: 0.42; nx: 0.00378564; ny: - 0.00261436; nz: 0.00122872; tu: 0.989282; tv: 0.96; ), (X: 0.5; Y: - 0.42; z: 0.42; nx: 0.0365857; ny: - 0.0008; nz: 0.00980306; tu: 1; tv: 0.92; ), (X: 0.5; Y: 0.42; z: 0.42; nx: 0.0688; ny: 0.000428717; nz: 0.0184348; tu: 1; tv: 0.08; ), (X: 0.489282; Y: 0.46; z: 0.42; nx: 0.00415692; ny: 0.00197128; nz: 0.00122872; tu: 0.989282; tv: 0.04; ), (X: 0.46; Y: 0.489282; z: 0.42; nx: 0.00261436; ny: 0.00378564; nz: 0.00122872; tu: 0.96; tv: 0.010718; ), (X: 0.42; Y: 0.5; z: 0.42; nx: 0.0008; ny: 0.0365857; nz: 0.00980311; tu: 0.92; tv: 0; ), (X: - 0.42; Y: 0.5; z: - 0.42; nx: - 0.00900311; ny: 0.0336; nz: 0; tu: 0; tv: 1; ), (X: - 0.46; Y: 0.489282; z: - 0.42; nx: - 0.0426031; ny: 0.0917968; nz: 0; tu: 0.00991422; tv: 1; ), (X: - 0.489282; Y: 0.46; z: - 0.42; nx: - 0.0827938; ny: 0.0581969; nz: 0; tu: 0.0198284; tv: 1; ), (X: - 0.5; Y: 0.42; z: - 0.42; nx: - 0.7728; ny: 0.0180062; nz: 0; tu: 0.0297427; tv: 1; ), (X: - 0.5; Y: - 0.42; z: - 0.42; nx: - 1.4448; ny: - 0.00900311; nz: 0; tu: 0.230847; tv: 1; ), (X: - 0.489282; Y: - 0.46; z: - 0.42; nx: - 0.0917969; ny: - 0.0426031; nz: 0; tu: 0.240761; tv: 1; ), (X: - 0.46; Y: - 0.489282; z: - 0.42; nx: - 0.0581969; ny: - 0.0827938; nz: 0; tu: 0.250676; tv: 1; ), (X: - 0.42; Y: - 0.5; z: - 0.42; nx: - 0.0180061; ny: - 0.7728; nz: 0; tu: 0.26059; tv: 1; ), (X: 0.42; Y: - 0.5; z: - 0.42; nx: 0.00900306; ny: - 1.4448; nz: 0; tu: 0.461694; tv: 1; ), (X: 0.46; Y: - 0.489282; z: - 0.42; nx: 0.042603; ny: - 0.0917969; nz: 0; tu: 0.471609; tv: 1; ), (X: 0.489282; Y: - 0.46; z: - 0.42; nx: 0.0827938; ny: - 0.0581969; nz: 0; tu: 0.481523; tv: 1; ), (X: 0.5; Y: - 0.42; z: - 0.42; nx: 0.7728; ny: - 0.0180061; nz: 0; tu: 0.491437; tv: 1; ), (X: 0.5; Y: 0.42; z: - 0.42; nx: 1.4448; ny: 0.00900306; nz: 0; tu: 0.692542; tv: 1; ), (X: 0.489282; Y: 0.46; z: - 0.42; nx: 0.0917968; ny: 0.042603; nz: 0; tu: 0.702456; tv: 1; ), (X: 0.46; Y: 0.489282; z: - 0.42; nx: 0.0581969; ny: 0.0827938; nz: 0; tu: 0.71237; tv: 1; ), (X: 0.42; Y: 0.5; z: - 0.42; nx: 0.0180062; ny: 0.7728; nz: 0; tu: 0.722284; tv: 1; ), (X: - 0.42; Y: 0.489282; z: - 0.46; nx: - 0.000799998; ny: 0.0947825; nz: - 0.0445744; tu: 0.08; tv: 0.989282; ), (X: - 0.454641; Y: 0.48; z: - 0.46; nx: - 0.00325744; ny: 0.00618564; nz: - 0.00378564; tu: 0.045359; tv: 0.98; ), (X: - 0.48; Y: 0.454641; z: - 0.46; nx: - 0.00591384; ny: 0.0037282; nz: - 0.00378563; tu: 0.02; tv: 0.954641; ), (X: - 0.489282; Y: 0.42; z: - 0.46; nx: - 0.0867938; ny: 0.00107179; nz: - 0.0600113; tu: 0.010718; tv: 0.92; ), (X: - 0.489282; Y: - 0.42; z: - 0.46; nx: - 0.0947825; ny: - 0.000799996; nz: - 0.0445744; tu: 0.010718; tv: 0.08;), (X: - 0.48; Y: - 0.454641; z: - 0.46; nx: - 0.00618564; ny: - 0.00325744; nz: - 0.00378564; tu: 0.02; tv: 0.045359;), (X: - 0.454641; Y: - 0.48; z: - 0.46; nx: - 0.0037282; ny: - 0.00591384; nz: - 0.00378564; tu: 0.045359; tv: 0.02;), (X: - 0.42; Y: - 0.489282; z: - 0.46; nx: - 0.0010718; ny: - 0.0867938; nz: - 0.0600112; tu: 0.08; tv: 0.010718;), (X: 0.42; Y: - 0.489282; z: - 0.46; nx: 0.000800002; ny: - 0.0947825; nz: - 0.0445743; tu: 0.92; tv: 0.010718;), (X: 0.454641; Y: - 0.48; z: - 0.46; nx: 0.00325744; ny: - 0.00618564; nz: - 0.00378564; tu: 0.954641; tv: 0.02;), (X: 0.48; Y: - 0.454641; z: - 0.46; nx: 0.00591384; ny: - 0.0037282; nz: - 0.00378564; tu: 0.98; tv: 0.045359;), (X: 0.489282; Y: - 0.42; z: - 0.46; nx: 0.0867938; ny: - 0.0010718; nz: - 0.0600112; tu: 0.989282; tv: 0.08;), (X: 0.489282; Y: 0.42; z: - 0.46; nx: 0.0947825; ny: 0.000800001; nz: - 0.0445743; tu: 0.989282; tv: 0.92;), (X: 0.48; Y: 0.454641; z: - 0.46; nx: 0.00618564; ny: 0.00325744; nz: - 0.00378564; tu: 0.98; tv: 0.954641;), (X: 0.454641; Y: 0.48; z: - 0.46; nx: 0.0037282; ny: 0.00591384; nz: - 0.00378564; tu: 0.954641; tv: 0.98;), (X: 0.42; Y: 0.489282; z: - 0.46; nx: 0.00107179; ny: 0.0867938; nz: - 0.0600113; tu: 0.92; tv: 0.989282;), (X: - 0.42; Y: 0.46; z: - 0.489282; nx: - 0.00021436; ny: 0.0589969; nz: - 0.0841794; tu: 0.08; tv: 0.96;), (X: - 0.44; Y: 0.454641; z: - 0.489282; nx: - 0.00107179; ny: 0.0024; nz: - 0.00378564; tu: 0.06; tv: 0.954641;), (X: - 0.454641; Y: 0.44; z: - 0.489282; nx: - 0.0021282; ny: 0.00154256; nz: - 0.00378564; tu: 0.045359; tv: 0.94;), (X: - 0.46; Y: 0.42; z: - 0.489282; nx: - 0.0444174; ny: 0.000486153; nz: - 0.0941968; tu: 0.04; tv: 0.92;), (X: - 0.46; Y: - 0.42; z: - 0.489282; nx: - 0.0589969; ny: - 0.000214357; nz: - 0.0841794; tu: 0.04; tv: 0.08;), (X: - 0.454641; Y: - 0.44; z: - 0.489282; nx: - 0.0024; ny: - 0.00107179; nz: - 0.00378564; tu: 0.045359; tv: 0.06;), (X: - 0.44; Y: - 0.454641; z: - 0.489282; nx: - 0.00154256; ny: - 0.0021282; nz: - 0.00378564; tu: 0.06; tv: 0.045359;), (X: - 0.42; Y: - 0.46; z: - 0.489282; nx: - 0.000486157; ny: - 0.0444174; nz: - 0.0941969; tu: 0.08; tv: 0.04;), (X: 0.42; Y: - 0.46; z: - 0.489282; nx: 0.00021436; ny: - 0.0589969; nz: - 0.0841795; tu: 0.92; tv: 0.04;), (X: 0.44; Y: - 0.454641; z: - 0.489282; nx: 0.0010718; ny: - 0.0024; nz: - 0.00378564; tu: 0.94; tv: 0.045359;), (X: 0.454641; Y: - 0.44; z: - 0.489282; nx: 0.0021282; ny: - 0.00154256; nz: - 0.00378564; tu: 0.954641; tv: 0.06;), (X: 0.46; Y: - 0.42; z: - 0.489282; nx: 0.0444174; ny: - 0.000486157; nz: - 0.0941969; tu: 0.96; tv: 0.08;), (X: 0.46; Y: 0.42; z: - 0.489282; nx: 0.0589969; ny: 0.000214359; nz: - 0.0841795; tu: 0.96; tv: 0.92;), (X: 0.454641; Y: 0.44; z: - 0.489282; nx: 0.0024; ny: 0.0010718; nz: - 0.00378564; tu: 0.954641; tv: 0.94;), (X: 0.44; Y: 0.454641; z: - 0.489282; nx: 0.00154256; ny: 0.0021282; nz: - 0.00378564; tu: 0.94; tv: 0.954641;), (X: 0.42; Y: 0.46; z: - 0.489282; nx: 0.000486153; ny: 0.0444174; nz: - 0.0941968; tu: 0.92; tv: 0.96;), (X: 0.42; Y: - 0.42; z: - 0.5; nx: 0.0094318; ny: - 0.0184349; nz: - 0.8088; tu: 0.92; tv: 0.08;), (X: - 0.42; Y: - 0.42; z: - 0.5; nx: - 0.0184349; ny: - 0.0094318; nz: - 1.5144; tu: 0.08; tv: 0.08;), (X: 0.42; Y: 0.42; z: - 0.5; nx: 0.0184349; ny: 0.0094318; nz: - 1.5144; tu: 0.92; tv: 0.92; ), (X: - 0.42; Y: 0.42; z: - 0.5; nx: - 0.0094318; ny: 0.0184349; nz: - 0.8088; tu: 0.08; tv: 0.92; ), (X: - 0.42; Y: 0.5; z: 0.42; nx: - 0.00900311; ny: 0.0336; nz: 0; tu: 0; tv: 0; ), (X: - 0.42; Y: 0.5; z: 0.42; nx: - 0.00900311; ny: 0.0336; nz: 0; tu: 0; tv: 0; ), (X: - 0.46; Y: 0.489282; z: 0.42; nx: - 0.00900311; ny: 0.0336; nz: 0; tu: 0.00991422; tv: 0; ), (X: - 0.46; Y: 0.489282; z: 0.42; nx: - 0.0245969; ny: 0.0245969; nz: 0; tu: 0.00991422; tv: 0; ), (X: - 0.46; Y: 0.489282; z: 0.42; nx: - 0.0245969; ny: 0.0245969; nz: 0; tu: 0.00991422; tv: 0; ), (X: - 0.489282; Y: 0.46; z: 0.42; nx: - 0.0245969; ny: 0.0245969; nz: 0; tu: 0.0198284; tv: 0; ), (X: - 0.489282; Y: 0.46; z: 0.42; nx: - 0.0336; ny: 0.00900311; nz: 0; tu: 0.0198284; tv: 0; ), (X: - 0.489282; Y: 0.46; z: 0.42; nx: - 0.0336; ny: 0.00900311; nz: 0; tu: 0.0198284; tv: 0; ), (X: - 0.5; Y: 0.42; z: 0.42; nx: - 0.0336; ny: 0.00900311; nz: 0; tu: 0.0297427; tv: 0; ), (X: - 0.5; Y: 0.42; z: 0.42; nx: - 0.7056; ny: 0; nz: 0; tu: 0.0297427; tv: 0; ), (X: - 0.5; Y: 0.42; z: 0.42; nx: - 0.7056; ny: 0; nz: 0; tu: 0.0297427; tv: 0; ), (X: - 0.5; Y: - 0.42; z: 0.42; nx: - 0.7056; ny: 0; nz: 0; tu: 0.230847; tv: 0; ), (X: - 0.5; Y: - 0.42; z: 0.42; nx: - 0.0336; ny: - 0.00900311; nz: 0; tu: 0.230847; tv: 0; ), (X: - 0.5; Y: - 0.42; z: 0.42; nx: - 0.0336; ny: - 0.00900311; nz: 0; tu: 0.230847; tv: 0; ), (X: - 0.489282; Y: - 0.46; z: 0.42; nx: - 0.0336; ny: - 0.00900311; nz: 0; tu: 0.240761; tv: 0; ), (X: - 0.489282; Y: - 0.46; z: 0.42; nx: - 0.0245969; ny: - 0.0245969; nz: 0; tu: 0.240761; tv: 0; ), (X: - 0.489282; Y: - 0.46; z: 0.42; nx: - 0.0245969; ny: - 0.0245969; nz: 0; tu: 0.240761; tv: 0; ), (X: - 0.46; Y: - 0.489282; z: 0.42; nx: - 0.0245969; ny: - 0.0245969; nz: 0; tu: 0.250676; tv: 0; ), (X: - 0.46; Y: - 0.489282; z: 0.42; nx: - 0.00900306; ny: - 0.0336; nz: 0; tu: 0.250676; tv: 0; ), (X: - 0.46; Y: - 0.489282; z: 0.42; nx: - 0.00900306; ny: - 0.0336; nz: 0; tu: 0.250676; tv: 0; ), (X: - 0.42; Y: - 0.5; z: 0.42; nx: - 0.00900306; ny: - 0.0336; nz: 0; tu: 0.26059; tv: 0; ), (X: - 0.42; Y: - 0.5; z: 0.42; nx: 0; ny: - 0.7056; nz: 0; tu: 0.26059; tv: 0; ), (X: - 0.42; Y: - 0.5; z: 0.42; nx: 0; ny: - 0.7056; nz: 0; tu: 0.26059; tv: 0; ), (X: 0.42; Y: - 0.5; z: 0.42; nx: 0; ny: - 0.7056; nz: 0; tu: 0.461694; tv: 0; ), (X: 0.42; Y: - 0.5; z: 0.42; nx: 0.00900306; ny: - 0.0336; nz: 0; tu: 0.461694; tv: 0; ), (X: 0.42; Y: - 0.5; z: 0.42; nx: 0.00900306; ny: - 0.0336; nz: 0; tu: 0.461694; tv: 0; ), (X: 0.46; Y: - 0.489282; z: 0.42; nx: 0.00900306; ny: - 0.0336; nz: 0; tu: 0.471609; tv: 0; ), (X: 0.46; Y: - 0.489282; z: 0.42; nx: 0.0245969; ny: - 0.0245969; nz: 0; tu: 0.471609; tv: 0; ), (X: 0.46; Y: - 0.489282; z: 0.42; nx: 0.0245969; ny: - 0.0245969; nz: 0; tu: 0.471609; tv: 0; ), (X: 0.489282; Y: - 0.46; z: 0.42; nx: 0.0245969; ny: - 0.0245969; nz: 0; tu: 0.481523; tv: 0; ), (X: 0.489282; Y: - 0.46; z: 0.42; nx: 0.0336; ny: - 0.00900306; nz: 0; tu: 0.481523; tv: 0; ), (X: 0.489282; Y: - 0.46; z: 0.42; nx: 0.0336; ny: - 0.00900306; nz: 0; tu: 0.481523; tv: 0; ), (X: 0.5; Y: - 0.42; z: 0.42; nx: 0.0336; ny: - 0.00900306; nz: 0; tu: 0.491437; tv: 0; ), (X: 0.5; Y: - 0.42; z: 0.42; nx: 0.7056; ny: 0; nz: 0; tu: 0.491437; tv: 0; ), (X: 0.5; Y: - 0.42; z: 0.42; nx: 0.7056; ny: 0; nz: 0; tu: 0.491437; tv: 0; ), (X: 0.5; Y: 0.42; z: 0.42; nx: 0.7056; ny: 0; nz: 0; tu: 0.692542; tv: 0; ), (X: 0.5; Y: 0.42; z: 0.42; nx: 0.0336; ny: 0.00900306; nz: 0; tu: 0.692542; tv: 0; ), (X: 0.5; Y: 0.42; z: 0.42; nx: 0.0336; ny: 0.00900306; nz: 0; tu: 0.692542; tv: 0; ), (X: 0.489282; Y: 0.46; z: 0.42; nx: 0.0336; ny: 0.00900306; nz: 0; tu: 0.702456; tv: 0; ), (X: 0.489282; Y: 0.46; z: 0.42; nx: 0.0245969; ny: 0.0245969; nz: 0; tu: 0.702456; tv: 0; ), (X: 0.489282; Y: 0.46; z: 0.42; nx: 0.0245969; ny: 0.0245969; nz: 0; tu: 0.702456; tv: 0; ), (X: 0.46; Y: 0.489282; z: 0.42; nx: 0.0245969; ny: 0.0245969; nz: 0; tu: 0.71237; tv: 0; ), (X: 0.46; Y: 0.489282; z: 0.42; nx: 0.00900311; ny: 0.0336; nz: 0; tu: 0.71237; tv: 0; ), (X: 0.46; Y: 0.489282; z: 0.42; nx: 0.00900311; ny: 0.0336; nz: 0; tu: 0.71237; tv: 0; ), (X: 0.42; Y: 0.5; z: 0.42; nx: 0.00900311; ny: 0.0336; nz: 0; tu: 0.722284; tv: 0; ), (X: 0.42; Y: 0.5; z: 0.42; nx: 0; ny: 0.7056; nz: 0; tu: 0.722284; tv: 0; ), (X: - 0.42; Y: 0.5; z: - 0.42; nx: 0; ny: 0.7056; nz: 0; tu: 1; tv: 1; ), (X: 0.42; Y: 0.5; z: 0.42; nx: 0; ny: 0.7056; nz: 0; tu: 0.722284; tv: 0; ), (X: - 0.42; Y: 0.5; z: - 0.42; nx: 0; ny: 0.7056; nz: 0; tu: 1; tv: 1; ), (X: - 0.42; Y: 0.5; z: 0.42; nx: 0; ny: 0.7056; nz: 0; tu: 1; tv: 0; ), (X: - 0.42; Y: 0.5; z: - 0.42; nx: - 0.00037128; ny: 0.00138564; nz: - 0.000371282; tu: 0.08; tv: 1; ), (X: - 0.42; Y: 0.5; z: - 0.42; nx: - 0.00042872; ny: 0.0016; nz: - 0.000428716; tu: 0.08; tv: 1; ), (X: - 0.46; Y: 0.489282; z: - 0.42; nx: - 0.00042872; ny: 0.0016; nz: - 0.000428716; tu: 0.04; tv: 0.989282; ), (X: - 0.46; Y: 0.489282; z: - 0.42; nx: - 0.00101436; ny: 0.00101436; nz: - 0.000371279; tu: 0.04; tv: 0.989282; ), (X: - 0.46; Y: 0.489282; z: - 0.42; nx: - 0.00117128; ny: 0.00117128; nz: - 0.000428718; tu: 0.04; tv: 0.989282; ), (X: - 0.489282; Y: 0.46; z: - 0.42; nx: - 0.00117128; ny: 0.00117128; nz: - 0.000428718; tu: 0.010718; tv: 0.96; ), (X: - 0.489282; Y: 0.46; z: - 0.42; nx: - 0.00138564; ny: 0.00037128; nz: - 0.000371279; tu: 0.010718; tv: 0.96; ), (X: - 0.489282; Y: 0.46; z: - 0.42; nx: - 0.0016; ny: 0.000428719; nz: - 0.000428719; tu: 0.010718; tv: 0.96; ), (X: - 0.5; Y: 0.42; z: - 0.42; nx: - 0.0016; ny: 0.000428719; nz: - 0.000428719; tu: 0; tv: 0.92; ), (X: - 0.5; Y: 0.42; z: - 0.42; nx: - 0.0336; ny: 0; nz: - 0.00900311; tu: 0; tv: 0.92; ), (X: - 0.5; Y: 0.42; z: - 0.42; nx: - 0.0336; ny: 0; nz: - 0.00900311; tu: 0; tv: 0.92; ), (X: - 0.5; Y: - 0.42; z: - 0.42; nx: - 0.0336; ny: 0; nz: - 0.00900311; tu: 0; tv: 0.08; ), (X: - 0.5; Y: - 0.42; z: - 0.42; nx: - 0.00138564; ny: - 0.00037128; nz: - 0.000371282; tu: 0; tv: 0.08; ), (X: - 0.5; Y: - 0.42; z: - 0.42; nx: - 0.0016; ny: - 0.00042872; nz: - 0.000428718; tu: 0; tv: 0.08; ), (X: - 0.489282; Y: - 0.46; z: - 0.42; nx: - 0.0016; ny: - 0.00042872; nz: - 0.000428718; tu: 0.010718; tv: 0.04; ), (X: - 0.489282; Y: - 0.46; z: - 0.42; nx: - 0.00101436; ny: - 0.00101436; nz: - 0.00037128; tu: 0.010718; tv: 0.04;), (X: - 0.489282; Y: - 0.46; z: - 0.42; nx: - 0.00117128; ny: - 0.00117128; nz: - 0.000428718; tu: 0.010718; tv: 0.04;), (X: - 0.46; Y: - 0.489282; z: - 0.42; nx: - 0.00117128; ny: - 0.00117128; nz: - 0.000428718; tu: 0.04; tv: 0.010718;), (X: - 0.46; Y: - 0.489282; z: - 0.42; nx: - 0.000371282; ny: - 0.00138564; nz: - 0.000371282; tu: 0.04; tv: 0.010718;), (X: - 0.46; Y: - 0.489282; z: - 0.42; nx: - 0.000428717; ny: - 0.0016; nz: - 0.000428717; tu: 0.04; tv: 0.010718; ), (X: - 0.42; Y: - 0.5; z: - 0.42; nx: - 0.000428717; ny: - 0.0016; nz: - 0.000428717; tu: 0.08; tv: 0; ), (X: - 0.42; Y: - 0.5; z: - 0.42; nx: 0; ny: - 0.0336; nz: - 0.00900306; tu: 0.08; tv: 0; ), (X: - 0.42; Y: - 0.5; z: - 0.42; nx: 0; ny: - 0.0336; nz: - 0.00900306; tu: 0.08; tv: 0; ), (X: 0.42; Y: - 0.5; z: - 0.42; nx: 0; ny: - 0.0336; nz: - 0.00900306; tu: 0.92; tv: 0; ), (X: 0.42; Y: - 0.5; z: - 0.42; nx: 0.000371282; ny: - 0.00138564; nz: - 0.00037128; tu: 0.92; tv: 0; ), (X: 0.42; Y: - 0.5; z: - 0.42; nx: 0.000428717; ny: - 0.0016; nz: - 0.000428719; tu: 0.92; tv: 0; ), (X: 0.46; Y: - 0.489282; z: - 0.42; nx: 0.000428717; ny: - 0.0016; nz: - 0.000428719; tu: 0.96; tv: 0.010718; ), (X: 0.46; Y: - 0.489282; z: - 0.42; nx: 0.00101436; ny: - 0.00101436; nz: - 0.000371281; tu: 0.96; tv: 0.010718; ), (X: 0.46; Y: - 0.489282; z: - 0.42; nx: 0.00117128; ny: - 0.00117128; nz: - 0.00042872; tu: 0.96; tv: 0.010718; ), (X: 0.489282; Y: - 0.46; z: - 0.42; nx: 0.00117128; ny: - 0.00117128; nz: - 0.00042872; tu: 0.989282; tv: 0.04; ), (X: 0.489282; Y: - 0.46; z: - 0.42; nx: 0.00138564; ny: - 0.000371282; nz: - 0.000371282; tu: 0.989282; tv: 0.04; ), (X: 0.489282; Y: - 0.46; z: - 0.42; nx: 0.0016; ny: - 0.000428717; nz: - 0.000428717; tu: 0.989282; tv: 0.04; ), (X: 0.5; Y: - 0.42; z: - 0.42; nx: 0.0016; ny: - 0.000428717; nz: - 0.000428717; tu: 1; tv: 0.08; ), (X: 0.5; Y: - 0.42; z: - 0.42; nx: 0.0336; ny: 0; nz: - 0.00900306; tu: 1; tv: 0.08; ), (X: 0.5; Y: - 0.42; z: - 0.42; nx: 0.0336; ny: 0; nz: - 0.00900306; tu: 1; tv: 0.08; ), (X: 0.5; Y: 0.42; z: - 0.42; nx: 0.0336; ny: 0; nz: - 0.00900306; tu: 1; tv: 0.92; ), (X: 0.5; Y: 0.42; z: - 0.42; nx: 0.00138564; ny: 0.000371282; nz: - 0.00037128; tu: 1; tv: 0.92; ), (X: 0.5; Y: 0.42; z: - 0.42; nx: 0.0016; ny: 0.000428717; nz: - 0.000428718; tu: 1; tv: 0.92; ), (X: 0.489282; Y: 0.46; z: - 0.42; nx: 0.0016; ny: 0.000428717; nz: - 0.000428718; tu: 0.989282; tv: 0.96; ), (X: 0.489282; Y: 0.46; z: - 0.42; nx: 0.00101436; ny: 0.00101436; nz: - 0.00037128; tu: 0.989282; tv: 0.96; ), (X: 0.489282; Y: 0.46; z: - 0.42; nx: 0.00117128; ny: 0.00117128; nz: - 0.000428717; tu: 0.989282; tv: 0.96; ), (X: 0.46; Y: 0.489282; z: - 0.42; nx: 0.00117128; ny: 0.00117128; nz: - 0.000428717; tu: 0.96; tv: 0.989282; ), (X: 0.46; Y: 0.489282; z: - 0.42; nx: 0.00037128; ny: 0.00138564; nz: - 0.00037128; tu: 0.96; tv: 0.989282; ), (X: 0.46; Y: 0.489282; z: - 0.42; nx: 0.000428719; ny: 0.0016; nz: - 0.00042872; tu: 0.96; tv: 0.989282; ), (X: 0.42; Y: 0.5; z: - 0.42; nx: 0.000428719; ny: 0.0016; nz: - 0.00042872; tu: 0.92; tv: 1; ), (X: 0.42; Y: 0.5; z: - 0.42; nx: 0; ny: 0.0336; nz: - 0.00900311; tu: 0.92; tv: 1; ), (X: 0.42; Y: 0.5; z: - 0.42; nx: 0; ny: 0.0336; nz: - 0.00900311; tu: 0.92; tv: 1; ), (X: - 0.42; Y: 0.5; z: - 0.42; nx: 0; ny: 0.0336; nz: - 0.00900311; tu: 0.08; tv: 1;)); RoundCubeIndices: array [0 .. 611] of Word = (0, 3, 2, 0, 1, 3, 0, 5, 4, 0, 6, 5, 0, 7, 6, 0, 8, 7, 0, 2, 8, 2, 9, 8, 2, 10, 9, 2, 11, 10, 2, 12, 11, 2, 3, 12, 3, 13, 12, 3, 14, 13, 3, 15, 14, 3, 16, 15, 3, 1, 16, 1, 17, 16, 1, 18, 17, 1, 19, 18, 1, 4, 19, 1, 0, 4, 4, 21, 20, 4, 5, 21, 5, 22, 21, 5, 6, 22, 6, 23, 22, 6, 7, 23, 7, 24, 23, 7, 8, 24, 8, 25, 24, 8, 9, 25, 9, 26, 25, 9, 10, 26, 10, 27, 26, 10, 11, 27, 11, 28, 27, 11, 12, 28, 12, 29, 28, 12, 13, 29, 13, 30, 29, 13, 14, 30, 14, 31, 30, 14, 15, 31, 15, 32, 31, 15, 16, 32, 16, 33, 32, 16, 17, 33, 17, 34, 33, 17, 18, 34, 18, 35, 34, 18, 19, 35, 19, 20, 35, 19, 4, 20, 20, 37, 36, 20, 21, 37, 21, 38, 37, 21, 22, 38, 22, 39, 38, 22, 23, 39, 23, 40, 39, 23, 24, 40, 24, 41, 40, 24, 25, 41, 25, 42, 41, 25, 26, 42, 26, 43, 42, 26, 27, 43, 27, 44, 43, 27, 28, 44, 28, 45, 44, 28, 29, 45, 29, 46, 45, 29, 30, 46, 30, 47, 46, 30, 31, 47, 31, 48, 47, 31, 32, 48, 32, 49, 48, 32, 33, 49, 33, 50, 49, 33, 34, 50, 34, 51, 50, 34, 35, 51, 35, 36, 51, 35, 20, 36, 104, 53, 52, 105, 106, 53, 107, 54, 53, 108, 109, 54, 110, 55, 54, 111, 112, 55, 113, 56, 55, 114, 115, 56, 116, 57, 56, 117, 118, 57, 119, 58, 57, 120, 121, 58, 122, 59, 58, 123, 124, 59, 125, 60, 59, 126, 127, 60, 128, 61, 60, 129, 130, 61, 131, 62, 61, 132, 133, 62, 134, 63, 62, 135, 136, 63, 137, 64, 63, 138, 139, 64, 140, 65, 64, 141, 142, 65, 143, 66, 65, 144, 145, 66, 146, 67, 66, 147, 148, 67, 149, 150, 67, 151, 153, 152, 154, 69, 68, 155, 156, 69, 157, 70, 69, 158, 159, 70, 160, 71, 70, 161, 162, 71, 163, 72, 71, 164, 165, 72, 166, 73, 72, 167, 168, 73, 169, 74, 73, 170, 171, 74, 172, 75, 74, 173, 174, 75, 175, 76, 75, 176, 177, 76, 178, 77, 76, 179, 180, 77, 181, 78, 77, 182, 183, 78, 184, 79, 78, 185, 186, 79, 187, 80, 79, 188, 189, 80, 190, 81, 80, 191, 192, 81, 193, 82, 81, 194, 195, 82, 196, 83, 82, 197, 198, 83, 199, 68, 83, 200, 201, 68, 68, 85, 84, 68, 69, 85, 69, 86, 85, 69, 70, 86, 70, 87, 86, 70, 71, 87, 71, 88, 87, 71, 72, 88, 72, 89, 88, 72, 73, 89, 73, 90, 89, 73, 74, 90, 74, 91, 90, 74, 75, 91, 75, 92, 91, 75, 76, 92, 76, 93, 92, 76, 77, 93, 77, 94, 93, 77, 78, 94, 78, 95, 94, 78, 79, 95, 79, 96, 95, 79, 80, 96, 80, 97, 96, 80, 81, 97, 81, 98, 97, 81, 82, 98, 82, 99, 98, 82, 83, 99, 83, 84, 99, 83, 68, 84, 84, 85, 103, 85, 86, 103, 86, 87, 103, 87, 101, 103, 87, 88, 101, 88, 89, 101, 89, 90, 101, 90, 91, 101, 91, 100, 101, 91, 92, 100, 92, 93, 100, 93, 94, 100, 94, 95, 100, 95, 102, 100, 95, 96, 102, 96, 97, 102, 97, 98, 102, 98, 99, 102, 99, 103, 102, 99, 84, 103, 102, 101, 100, 102, 103, 101); constructor TRoundCube.Create(AOwner: TComponent); begin inherited; Data.AssignFromMeshVertex(RoundCubeVertices, RoundCubeIndices); end; { TCone } constructor TCone.Create(AOwner: TComponent); begin inherited; FSubdivisionsAxes := 12; FSubdivisionsCap := 1; FSubdivisionsHeight := 1; RebuildMesh; end; procedure TCone.RebuildMesh; var A, H, AA, HH: Integer; Theta, Phi: Single; S, DTheta, DPhi: Single; PhiSin, PhiCos: Extended; IdxCount: Integer; Offset, VerticesWidth: Integer; N, N1, N2: TPoint3D; begin VerticesWidth := (FSubdivisionsAxes + 1); FData.VertexBuffer.Length := (FSubdivisionsCap) * VerticesWidth + ((FSubdivisionsHeight + 1) * VerticesWidth) + 1; FData.IndexBuffer.Length := (FSubdivisionsCap - 1) * FSubdivisionsAxes * 6 + (FSubdivisionsAxes * 3) + (FSubdivisionsHeight - 1) * FSubdivisionsAxes * 6 + (FSubdivisionsAxes * 3); DPhi := DegToRad(360) / FSubdivisionsAxes; IdxCount := 0; // bottom center FData.VertexBuffer.Vertices[FData.VertexBuffer.Length - 1] := Point3D(0, 0.5, 0); FData.VertexBuffer.TexCoord0[FData.VertexBuffer.Length - 1] := PointF(0.5, 0.5); FData.VertexBuffer.Normals[FData.VertexBuffer.Length - 1] := Point3D(0, 1, 0); // bottom for H := 0 to FSubdivisionsCap - 1 do begin Phi := 0; for A := 0 to FSubdivisionsAxes - 1 do begin SinCos(Phi, PhiSin, PhiCos); FData.VertexBuffer.Vertices[A + (H * VerticesWidth)] := Point3D(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap), 0.5, (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap))); FData.VertexBuffer.TexCoord0[A + (H * VerticesWidth)] := PointF(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5, (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5)); if A = 0 then begin FData.VertexBuffer.Vertices[FSubdivisionsAxes + (H * VerticesWidth)] := Point3D(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap), 0.5, (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap))); FData.VertexBuffer.TexCoord0[FSubdivisionsAxes + (H * VerticesWidth)] := PointF(PhiCos * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5, (PhiSin * 0.5 * ((H + 1) / FSubdivisionsCap) + 0.5)); end; AA := A + 1; HH := H - 1; if H = 0 then begin FData.IndexBuffer.Indices[IdxCount + 0] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := FData.VertexBuffer.Length - 1; FData.IndexBuffer.Indices[IdxCount + 1] := AA + (H * VerticesWidth); IdxCount := IdxCount + 3; end else begin FData.IndexBuffer.Indices[IdxCount + 0] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 1] := AA + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := A + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 3] := A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 4] := AA + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 5] := AA + (HH * VerticesWidth); IdxCount := IdxCount + 6; end; Phi := Phi + DPhi; end; end; // sides Phi := 0; Offset := VerticesWidth * FSubdivisionsCap; for H := 0 to FSubdivisionsHeight - 1 do for A := 0 to FSubdivisionsAxes - 1 do begin SinCos(Phi, PhiSin, PhiCos); S := 1 - (H / FSubdivisionsHeight); FData.VertexBuffer.Vertices[Offset + A + (H * VerticesWidth)] := Point3D(PhiCos * 0.5 * S, 0.5 - (1 - S), PhiSin * 0.5 * S); FData.VertexBuffer.TexCoord0[Offset + A + (H * VerticesWidth)] := PointF(A / FSubdivisionsAxes, S); if H = 0 then begin FData.VertexBuffer.Vertices[Offset + A + (FSubdivisionsHeight * VerticesWidth)] := Point3D(0, -0.5, 0); FData.VertexBuffer.TexCoord0[Offset + A + (FSubdivisionsHeight * VerticesWidth)] := PointF(A / FSubdivisionsAxes, 0); end; if A = 0 then begin FData.VertexBuffer.Vertices[Offset + FSubdivisionsAxes + (H * VerticesWidth)] := FData.VertexBuffer.Vertices[Offset + (H * VerticesWidth)]; FData.VertexBuffer.TexCoord0[Offset + FSubdivisionsAxes + (H * VerticesWidth)] := PointF(1, S); if H = 0 then begin FData.VertexBuffer.Vertices[Offset + FSubdivisionsAxes + (FSubdivisionsHeight * VerticesWidth)] := Point3D(0, -0.5, 0); FData.VertexBuffer.TexCoord0[Offset + FSubdivisionsAxes + (FSubdivisionsHeight * VerticesWidth)] := PointF(1, 0); end; end; AA := A + 1; HH := H + 1; if H = FSubdivisionsHeight - 1 then begin FData.IndexBuffer.Indices[IdxCount + 0] := Offset + A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 1] := Offset + A + (FSubdivisionsHeight * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := Offset + AA + (H * VerticesWidth); IdxCount := IdxCount + 3; end else begin FData.IndexBuffer.Indices[IdxCount + 0] := Offset + A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 2] := Offset + AA + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 1] := Offset + A + (HH * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 3] := Offset + A + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 5] := Offset + AA + (H * VerticesWidth); FData.IndexBuffer.Indices[IdxCount + 4] := Offset + AA + (HH * VerticesWidth); IdxCount := IdxCount + 6; end; Phi := Phi + DPhi; end; FData.CalcNormals; // smooth split for H := 0 to FSubdivisionsHeight - 2 do begin N1 := FData.VertexBuffer.Normals[Offset + 0 + (H * VerticesWidth)]; N2 := FData.VertexBuffer.Normals[Offset + FSubdivisionsAxes + (H * VerticesWidth)]; N.X := (N1.X + N2.X) / 2; N.Y := (N1.Y + N2.Y) / 2; N.Z := (N1.Z + N2.Z) / 2; N := Point3D(Vector3DNormalize(Vector3D(N))); FData.VertexBuffer.Normals[Offset + 0 + (H * VerticesWidth)] := N; FData.VertexBuffer.Normals[Offset + FSubdivisionsAxes + (H * VerticesWidth)] := N; end; end; procedure TCone.SetSubdivisionsAxes(const Value: Integer); begin if FSubdivisionsAxes <> Value then begin FSubdivisionsAxes := Value; if FSubdivisionsAxes < 3 then FSubdivisionsAxes := 3; RebuildMesh; end; end; procedure TCone.SetSubdivisionsCap(const Value: Integer); begin if FSubdivisionsCap <> Value then begin FSubdivisionsCap := Value; if FSubdivisionsCap < 3 then FSubdivisionsCap := 3; RebuildMesh; end; end; procedure TCone.SetSubdivisionsHeight(const Value: Integer); begin if FSubdivisionsHeight <> Value then begin FSubdivisionsHeight := Value; if FSubdivisionsHeight < 1 then FSubdivisionsHeight := 1; RebuildMesh; end; end; { TMesh } procedure TMesh.Render; begin Context.FillMesh(Vector3D(0, 0, 0), Vector3D(Width, Height, Depth), FData, AbsoluteOpacity); end; { TExtrudedShape3D } constructor TExtrudedShape3D.Create(AOwner: TComponent); begin inherited; FMaterialBack := TMaterial.Create; FMaterialBack.Assign(FMaterial); FMaterialBack.OnChanged := MaterialChanged; FMaterialShaft := TMaterial.Create; FMaterialShaft.Assign(FMaterial); FMaterialShaft.OnChanged := MaterialChanged; FFlatness := 1; FSides := [TExtrudedShapeSide.esFront, TExtrudedShapeSide.esBack, TExtrudedShapeSide.esShaft]; Width := 4; Height := 4; Depth := 1; end; destructor TExtrudedShape3D.Destroy; begin FMaterialBack.Free; FMaterialShaft.Free; inherited; end; procedure TExtrudedShape3D.Apply; var M: TMatrix3D; begin inherited; M := IdentityMatrix3D; M.m41 := -Width / 2; M.m42 := -Height / 2; Context.SetMatrix(Matrix3DMultiply(M, AbsoluteMatrix)); end; procedure TExtrudedShape3D.Render; begin end; function TExtrudedShape3D.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; begin Result := inherited; end; procedure TExtrudedShape3D.MouseMove3D(Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); var p3, rPos, rDir: TVector3D; begin inherited; if RayCastIntersect(RayPos, RayDir, p3) then begin p3 := AbsoluteToLocalVector(p3); X := (((p3.X + (Width / 2)) / Width) * Width); Y := (((-p3.z + (Depth / 2)) / Depth) * Depth); end else Exit; ShapeMouseMove(Shift, X, Y); end; procedure TExtrudedShape3D.MouseDown3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); var p3, rPos, rDir: TVector3D; begin inherited; if RayCastIntersect(RayPos, RayDir, p3) then begin p3 := AbsoluteToLocalVector(p3); X := (((p3.X + (Width / 2)) / Width) * Width); Y := (((-p3.z + (Depth / 2)) / Depth) * Depth); end else Exit; ShapeMouseDown(Button, Shift, X, Y); end; procedure TExtrudedShape3D.MouseUp3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); var p3, rPos, rDir: TVector3D; begin inherited; if RayCastIntersect(RayPos, RayDir, p3) then begin p3 := AbsoluteToLocalVector(p3); X := (((p3.X + (Width / 2)) / Width) * Width); Y := (((-p3.z + (Depth / 2)) / Depth) * Depth); end; ShapeMouseUp(Button, Shift, X, Y); end; procedure TExtrudedShape3D.ShapeMouseMove(Shift: TShiftState; X, Y: Single); begin end; procedure TExtrudedShape3D.ShapeMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin end; procedure TExtrudedShape3D.ShapeMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin end; procedure TExtrudedShape3D.SetFlatness(const Value: Single); begin if FFlatness <> Value then begin FFlatness := Value; if FFlatness < 0.05 then FFlatness := 0.05; Repaint; end; end; procedure TExtrudedShape3D.SetSides(const Value: TExtrudedShapeSides); begin if FSides <> Value then begin FSides := Value; Repaint; end; end; procedure TExtrudedShape3D.SetMaterialBack(const Value: TMaterial); begin FMaterialBack.Assign(Value); end; procedure TExtrudedShape3D.SetMaterialShaft(const Value: TMaterial); begin FMaterialShaft.Assign(Value); end; { TRectangle3D } constructor TRectangle3D.Create(AOwner: TComponent); begin inherited; FCorners := AllCorners; end; destructor TRectangle3D.Destroy; begin inherited; end; function TRectangle3D.IsCornersStored: Boolean; begin Result := FCorners <> AllCorners; end; procedure TRectangle3D.Render; var S: TPointF; VP: TPolygon; r: TRectF; Path: TPathData; begin inherited; Path := TPathData.Create; Path.AddRectangle(RectF(0, 0, Width, Height), XRadius, YRadius, FCorners, FCornerType); S := Path.FlattenToPolygon(VP, FFlatness); if (S.X > 0) and (S.Y > 0) then begin r := RectF(0, 0, S.X, S.Y); { front } if TExtrudedShapeSide.esFront in FSides then begin Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, True, False); end; { back } if TExtrudedShapeSide.esBack in FSides then begin Context.SetMaterial(FMaterialBack); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, True, False, False); end; { shaft } if TExtrudedShapeSide.esShaft in FSides then begin Context.SetMaterial(FMaterialShaft); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, False, True); end; end; Path.Free; end; procedure TRectangle3D.SetCorners(const Value: TCorners); begin if FCorners <> Value then begin FCorners := Value; Repaint; end; end; procedure TRectangle3D.SetCornerType(const Value: TCornerType); begin if FCornerType <> Value then begin FCornerType := Value; Repaint; end; end; procedure TRectangle3D.SetXRadius(const Value: Single); begin if FXRadius <> Value then begin FXRadius := Value; Repaint; end; end; procedure TRectangle3D.SetYRadius(const Value: Single); begin if FYRadius <> Value then begin FYRadius := Value; Repaint; end; end; { TEllipse3D } procedure TEllipse3D.Render; var S: TPointF; VP: TPolygon; r: TRectF; Path: TPathData; begin inherited; Path := TPathData.Create; r := RectF(0, 0, Width, Height); Path.AddEllipse(r); S := Path.FlattenToPolygon(VP, FFlatness); if (S.X > 0) and (S.Y > 0) then begin r := RectF(0, 0, S.X, S.Y); { front } if TExtrudedShapeSide.esFront in FSides then begin Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, True, False); end; { back } if TExtrudedShapeSide.esBack in FSides then begin Context.SetMaterial(FMaterialBack); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, True, False, False); end; { left } if TExtrudedShapeSide.esShaft in FSides then begin Context.SetMaterial(FMaterialShaft); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, False, True); end; end; Path.Free; end; { TText3D } constructor TText3D.Create(AOwner: TComponent); begin inherited; FFont := TFont.Create; FFont.OnChanged := FontChanged; FFlatness := 1; Depth := 0.3; Width := 3; Height := 2; ZWrite := True; WordWrap := True; end; destructor TText3D.Destroy; begin FFont.Free; inherited; end; procedure TText3D.Render; var r: TRectF; W, H: Single; Path: TPathData; VP: TPolygon; B: TPointF; i: Integer; Factor: Single; begin inherited; if Text <> '' then begin if GetMeasureBitmap.Canvas.BeginScene then try if Projection = TProjection.pjCamera then Factor := 10 else Factor := 1; GetMeasureBitmap.Canvas.Font.Family := Font.Family; GetMeasureBitmap.Canvas.Font.Style := Font.Style; GetMeasureBitmap.Canvas.Font.Size := Font.Size * Factor; Path := TPathData.Create; if Stretch then begin r := RectF(0, 0, Width * Factor, Height * Factor); if GetMeasureBitmap.Canvas.TextToPath(Path, r, Text, WordWrap, HorzTextAlign, VertTextAlign) then begin B := Path.FlattenToPolygon(VP, FFlatness); if (B.X > 0) and (B.Y > 0) then begin { front } if TExtrudedShapeSide.esFront in FSides then begin Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r) / Factor, RectHeight(r) / Factor, Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, True, False); end; { back } if TExtrudedShapeSide.esBack in FSides then begin Context.SetMaterial(FMaterialBack); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r) / Factor, RectHeight(r) / Factor, Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, True, False, False); end; { left } if TExtrudedShapeSide.esShaft in FSides then begin Context.SetMaterial(FMaterialShaft); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r) / Factor, RectHeight(r) / Factor, Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, False, True); end; end; end; end else begin r := RectF(0, 0, Width * Factor, Height * Factor); if GetMeasureBitmap.Canvas.TextToPath(Path, r, Text, WordWrap, HorzTextAlign, VertTextAlign) then begin if not WordWrap then begin r := RectF(0, 0, Width * Factor, Height * Factor); GetMeasureBitmap.Canvas.MeasureText(r, Text, WordWrap, [], HorzTextAlign, VertTextAlign); case HorzTextAlign of TTextAlign.taCenter: r := RectF(0, 0, Width * Factor, RectHeight(r)); TTextAlign.taLeading: r := RectF(0, 0, Width * Factor, RectHeight(r)); TTextAlign.taTrailing: r := RectF(Width * Factor - RectWidth(r), 0, Width * Factor, RectHeight(r)); end; r := UnionRect(r, RectF(0, 0, Width * Factor, Height * Factor)); end else begin GetMeasureBitmap.Canvas.MeasureText(r, Text, WordWrap, [], HorzTextAlign, VertTextAlign); r := UnionRect(r, RectF(0, 0, Width * Factor, Height * Factor)); end; B := Path.FlattenToPolygon(VP, FFlatness); if (B.X > 0) and (B.Y > 0) then begin { front } if TExtrudedShapeSide.esFront in FSides then begin Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r) / Factor, RectHeight(r) / Factor, Depth), r, VP, AbsoluteOpacity, False, True, False); end; { back } if TExtrudedShapeSide.esBack in FSides then begin Context.SetMaterial(FMaterialBack); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r) / Factor, RectHeight(r) / Factor, Depth), r, VP, AbsoluteOpacity, True, False, False); end; { left } if TExtrudedShapeSide.esShaft in FSides then begin Context.SetMaterial(FMaterialShaft); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r) / Factor, RectHeight(r) / Factor, Depth), r, VP, AbsoluteOpacity, False, False, True); end; end; end; end; finally GetMeasureBitmap.Canvas.EndScene; end; Path.Free; end; if (csDesigning in ComponentState) and not Locked then begin Context.SetColor(TMaterialColor.mcDiffuse, $8060A799); Context.DrawCube(Vector3D(Width / 2, Height / 2, 0), Vector3D(Width, Height, Depth), AbsoluteOpacity); end; end; function TText3D.GetPathBounds: TRectF; var r: TRectF; W, H: Single; Bmp: TBitmap; Path: TPathData; VP: TPolygon; B: TPointF; i: Integer; begin Result := RectF(0, 0, Width, Height); if Text <> '' then begin Bmp := TBitmap.Create(1, 1); Bmp.Canvas.Font.Family := Font.Family; Bmp.Canvas.Font.Style := Font.Style; Bmp.Canvas.Font.Size := Font.Size; Path := TPathData.Create; if Stretch then r := RectF(0, 0, Width * 10, Height * 10) else begin r := RectF(0, 0, Width * 10, Height * 10); if Bmp.Canvas.TextToPath(Path, r, Text, WordWrap, HorzTextAlign, VertTextAlign) then begin Result := Path.GetBounds; end; end; Path.Free; Bmp.Free; Result := RectF(Result.Left / 10, Result.Top / 10, Result.Right / 10, Result.Bottom / 10); end; end; function TText3D.GetTextBounds: TRectF; var r: TRectF; W, H: Single; B: TBitmap; i: Integer; begin Result := RectF(0, 0, 0, 0); if Text <> '' then begin B := TBitmap.Create(1, 1); try B.Canvas.Font.Family := Font.Family; B.Canvas.Font.Style := Font.Style; B.Canvas.Font.Size := Font.Size; if Stretch then r := RectF(0, 0, Width, Height) else begin r := RectF(0, 0, Width * 10, Height * 10); B.Canvas.MeasureText(r, Text, WordWrap, [], TTextAlign.taLeading, TTextAlign.taLeading); Result := RectF(0, 0, r.Right / 10, r.Bottom / 10); end; finally B.Free; end; end; end; function TText3D.GetPathLength: Single; var r: TRectF; W, H: Single; Bmp: TBitmap; Path: TPathData; Points: TPolygon; i: Integer; len: Single; begin Result := 0; if Text <> '' then begin Bmp := TBitmap.Create(1, 1); try Bmp.Canvas.Font.Family := Font.Family; Bmp.Canvas.Font.Style := Font.Style; Bmp.Canvas.Font.Size := Font.Size; Path := TPathData.Create; try if Stretch then begin r := RectF(0, 0, Width * 10, Height * 10); Bmp.Canvas.TextToPath(Path, r, Text, WordWrap, HorzTextAlign, VertTextAlign); end else begin r := RectF(0, 0, Width * 10, Height * 10); Bmp.Canvas.MeasureText(r, Text, WordWrap, [], TTextAlign.taLeading, VertTextAlign); Bmp.Canvas.TextToPath(Path, r, Text, WordWrap, HorzTextAlign, VertTextAlign); end; Path.FlattenToPolygon(Points, FFlatness); finally Path.Free; end; finally Bmp.Free; end; for i := 0 to High(Points) do begin if (Points[i].X >= $FFFF) and (Points[i].Y >= $FFFF) then continue; with Points[i] do begin if (i > 0) then begin if Points[i - 1].X >= $FFFF then begin Result := Result + VectorLength(Vector(X - Points[i - 2].X, Y - Points[i - 2].Y)); end else begin Result := Result + VectorLength(Vector(X - Points[i - 1].X, Y - Points[i - 1].Y)); end; end; end; end; Result := Result / 10; end; end; procedure TText3D.FontChanged(Sender: TObject); begin Repaint; end; procedure TText3D.SetFont(const Value: TFont); begin FFont.Assign(Value); end; procedure TText3D.SetText(const Value: WideString); begin if FText <> Value then begin FText := Value; Repaint; end; end; procedure TText3D.SetHorzTextAlign(const Value: TTextAlign); begin if FHorzTextAlign <> Value then begin FHorzTextAlign := Value; Repaint; end; end; procedure TText3D.SetStretch(const Value: Boolean); begin if FStretch <> Value then begin FStretch := Value; Repaint; end; end; procedure TText3D.SetVertTextAlign(const Value: TTextAlign); begin if FVertTextAlign <> Value then begin FVertTextAlign := Value; Repaint; end; end; procedure TText3D.SetWordWrap(const Value: Boolean); begin if FWordWrap <> Value then begin FWordWrap := Value; end; end; { TPath3D } constructor TPath3D.Create(AOwner: TComponent); begin inherited; FPath := TPathData.Create; FPath.OnChanged := PathChanged; FFlatness := 2; FWrapMode := TPathWrapMode.pwStretch; end; destructor TPath3D.Destroy; begin FPath.Free; inherited; end; procedure TPath3D.Render; var S: TPointF; VP: TPolygon; r: TRectF; i, j: Integer; begin inherited; if not FPath.IsEmpty then begin case FWrapMode of TPathWrapMode.pwOriginal: begin S := FPath.FlattenToPolygon(VP, FFlatness); if (S.X > 0) and (S.Y > 0) then begin r := RectF(0, 0, S.X, S.Y); { front } if TExtrudedShapeSide.esFront in FSides then begin Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, True, False); end; { back } if TExtrudedShapeSide.esBack in FSides then begin Context.SetMaterial(FMaterialBack); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, True, False, False); end; { left } if TExtrudedShapeSide.esShaft in FSides then begin Context.SetMaterial(FMaterialShaft); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, False, True); end; end; end; TPathWrapMode.pwFit: begin S := FPath.FlattenToPolygon(VP, FFlatness); if (S.X > 0) and (S.Y > 0) then begin r := RectF(0, 0, S.X, S.Y); FitRect(r, RectF(0, 0, Width, Height)); { front } if TExtrudedShapeSide.esFront in FSides then begin Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, True, False); end; { back } if TExtrudedShapeSide.esBack in FSides then begin Context.SetMaterial(FMaterialBack); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, True, False, False); end; { left } if TExtrudedShapeSide.esShaft in FSides then begin Context.SetMaterial(FMaterialShaft); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, False, True); end; end; end; TPathWrapMode.pwStretch: begin S := FPath.FlattenToPolygon(VP, FFlatness); if (S.X > 0) and (S.Y > 0) then begin r := RectF(0, 0, Width, Height); { front } if TExtrudedShapeSide.esFront in FSides then begin Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, True, False); end; { back } if TExtrudedShapeSide.esBack in FSides then begin Context.SetMaterial(FMaterialBack); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, True, False, False); end; { left } if TExtrudedShapeSide.esShaft in FSides then begin Context.SetMaterial(FMaterialShaft); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, False, True); end; end; end; TPathWrapMode.pwTile: begin S := FPath.FlattenToPolygon(VP, FFlatness); if (S.X > 0) and (S.Y > 0) then begin r := RectF(0, 0, S.X, S.Y); for i := 0 to round(Width / RectWidth(r)) do for j := 0 to round(Height / RectHeight(r)) do begin r := RectF(0, 0, S.X, S.Y); OffsetRect(r, i * (RectWidth(r)), j * (RectHeight(r))); { front } if TExtrudedShapeSide.esFront in FSides then begin Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, True, False); end; { back } if TExtrudedShapeSide.esBack in FSides then begin Context.SetMaterial(FMaterialBack); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, True, False, False); end; { left } if TExtrudedShapeSide.esShaft in FSides then begin Context.SetMaterial(FMaterialShaft); Context.FillPolygon(Vector3D(Width / 2, Height / 2, 0), Vector3D(RectWidth(r), RectHeight(r), Depth), RectF(0, 0, 0, 0), VP, AbsoluteOpacity, False, False, True); end; end; end; end; end; end; if (csDesigning in ComponentState) and not Locked then begin Context.SetColor(TMaterialColor.mcDiffuse, $8060A799); Context.DrawCube(Vector3D(Width / 2, Height / 2, 0), Vector3D(Width, Height, Depth), AbsoluteOpacity); end; end; procedure TPath3D.PathChanged(Sender: TObject); begin Repaint; end; procedure TPath3D.SetPath(const Value: TPathData); begin FPath.Assign(Value); end; procedure TPath3D.SetWrapMode(const Value: TPathWrapMode); begin if FWrapMode <> Value then begin FWrapMode := Value; Repaint; end; end; { TSelectionPoint3D } constructor TSelectionPoint3D.Create(AOwner: TComponent); begin inherited; FWorkPlane := TPosition3D.Create(Point3D(0, 1, 0)); AutoCapture := True; end; destructor TSelectionPoint3D.Destroy; begin FWorkPlane.Free; inherited; end; procedure TSelectionPoint3D.DoMouseEnter; begin inherited; Repaint; end; procedure TSelectionPoint3D.MouseDown3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); begin inherited; if Button = TMouseButton.mbLeft then begin FPressed := True; FOldRayPos := RayPos; FOldRayDir := RayDir; FOldRayPos := LocalToAbsoluteVector(RayPos); FOldRayDir := Vector3DNormalize(LocalToAbsoluteVector(RayDir)); FAngle := 0; end; end; procedure TSelectionPoint3D.MouseMove3D(Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); var V, V1, V2, M: TVector3D; r: TMatrix3D; begin inherited; if FPressed then begin RayPos := LocalToAbsoluteVector(RayPos); RayDir := Vector3DNormalize(LocalToAbsoluteVector(RayDir)); // plane space V := FWorkPlane.Vector; V.W := 0; V := LocalToAbsoluteVector(V); if not RayCastPlaneIntersect(FOldRayPos, FOldRayDir, AbsolutePosition, V, V1) then Exit; if not RayCastPlaneIntersect(RayPos, RayDir, AbsolutePosition, V, V2) then Exit; // convert to parent space if (Parent <> nil) and (Parent is TControl3D) then begin V1 := TControl3D(Parent).AbsoluteToLocalVector(V1); V2 := TControl3D(Parent).AbsoluteToLocalVector(V2); end; case Kind of TSelectionPointKind.spMove: begin // calc move vector M := Vector3DSubtract(V2, V1); // move Position.Vector := Vector3DAdd(Position.Vector, M); end; TSelectionPointKind.spRotation: begin // calc angle if (FWorkPlane.X = 0) and (FWorkPlane.Y = 1) and (FWorkPlane.z = 0) then begin V1 := Vector3D(1, 0, 0); V := Vector3D(Vector3DLength(Position.Vector), 0, 0); if Vector3DCrossProduct(V1, V2).Y < 0 then FAngle := ArcCos(Vector3DAngleCosine(V1, V2)) else FAngle := -ArcCos(Vector3DAngleCosine(V1, V2)); end else if (FWorkPlane.X = 0) and (FWorkPlane.Y = 0) and (FWorkPlane.z = 1) then begin V1 := Vector3D(1, 0, 0); V := Vector3D(Vector3DLength(Position.Vector), 0, 0); if Vector3DCrossProduct(V1, V2).z < 0 then FAngle := ArcCos(Vector3DAngleCosine(V1, V2)) else FAngle := -ArcCos(Vector3DAngleCosine(V1, V2)); end else if (FWorkPlane.X = 1) and (FWorkPlane.Y = 0) and (FWorkPlane.z = 0) then begin V1 := Vector3D(0, 1, 0); V := Vector3D(Vector3DLength(Position.Vector), 0, 0); if Vector3DCrossProduct(V1, V2).X < 0 then FAngle := ArcCos(Vector3DAngleCosine(V1, V2)) else FAngle := -ArcCos(Vector3DAngleCosine(V1, V2)); end; V := Vector3D(Vector3DLength(Position.Vector), 0, 0); RotateVector(V, FWorkPlane.Vector, FAngle); FAngle := RadToDeg(FAngle); // move Position.Vector := V; end; end; if Assigned(FOnTrack) then FOnTrack(Self); // FOldRayPos := RayPos; FOldRayDir := RayDir; end; end; procedure TSelectionPoint3D.MouseUp3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); begin inherited; if FPressed then begin if Assigned(FOnChange) then FOnChange(Self); FPressed := False; Repaint; end; end; procedure TSelectionPoint3D.DoMouseLeave; begin inherited; Repaint; end; procedure TSelectionPoint3D.Render; begin Context.SetContextState(TContextState.csTexDisable); Context.SetContextState(TContextState.csLightOff); if IsMouseOver then Context.SetColor(TMaterialColor.mcDiffuse, TAlphaColors.Red) else Context.SetColor(TMaterialColor.mcDiffuse, TAlphaColors.Blue); Context.FillCube(Vector3D(0, 0, 0), Vector3D(Width, Height, Depth), AbsoluteOpacity); Context.SetColor(TMaterialColor.mcDiffuse, TAlphaColors.White); Context.DrawCube(Vector3D(0, 0, 0), Vector3D(Width, Height, Depth), AbsoluteOpacity); end; function TSelectionPoint3D.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; begin Result := inherited; end; procedure TSelectionPoint3D.SetWorkPlane(const Value: TPosition3D); begin FWorkPlane.Assign(Value); end; { TModel3D } procedure TModel3D.Clear; var i: Integer; begin if not (csDestroying in ComponentState) then for i := 0 to High(FMeshCollection) do begin RemoveObject(FMeshCollection[i]); FMeshCollection[i].Free; end; FMeshCollection := nil; end; constructor TModel3D.Create(AOwner: TComponent); begin inherited; end; procedure TModel3D.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineBinaryProperty('Data', ReadModel, WriteModel, True); end; destructor TModel3D.Destroy; begin Clear; inherited; end; function TModel3D.LoadFromFile(const AFileName: WideString): Boolean; var I: Integer; begin Clear; Result := TModelImportServices.LoadFromFile(AFileName, FMeshCollection, Self); UpdateMeshCollection; end; procedure TModel3D.ReadModel(Stream: TStream); procedure Read(AStream: TStream); var i, l: Integer; LLength: Word; begin Clear; AStream.ReadBuffer(LLength, 2); SetLength(FMeshCollection, LLength); for i := 0 to LLength - 1 do begin FMeshCollection[i] := TMesh.Create(Self); AStream.ReadComponent(FMeshCollection[i]); FMeshCollection[i].Stored := False; end; end; begin Read(Stream); UpdateMeshCollection; end; procedure TModel3D.UpdateMeshCollection; var I: Integer; begin for i := 0 to High(FMeshCollection) do begin FMeshCollection[I].HitTest := False; FMeshCollection[I].Lock; AddObject(FMeshCollection[I]); end; end; procedure TModel3D.WriteModel(Stream: TStream); procedure Write(AStream: TStream); var i, l: Integer; LLength: Word; begin LLength := Length(FMeshCollection); AStream.WriteBuffer(LLength, 2); for i := 0 to LLength - 1 do begin AStream.WriteComponent(FMeshCollection[i]); end; end; begin Write(Stream); end; initialization RegisterFmxClasses([TPlane, TDisk, TCube, TMesh, TSphere, TCylinder, TRoundCube, TCone, TGrid3D, TStrokeCube, TText3D, TPath3D, TRectangle3D, TEllipse3D, TSelectionPoint3D, TShape3D, TExtrudedShape3D, TModel3D]); end.
PROGRAM FibonacciRI; USES IntStack; CONST MAX = 21; TYPE IntArray = ARRAY[0..MAX] of INTEGER; CONST FIBONACCI: IntArray=(0, 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946); FUNCTION Fib(n: INTEGER): INTEGER; BEGIN IF n = 0 THEN Fib := 0 ELSE IF n = 1 THEN Fib := 1 ELSE Fib := Fib(n - 1) + Fib(n - 2) END; FUNCTION Fib1(n: INTEGER): INTEGER; VAR f1, f2: INTEGER; BEGIN IF n = 0 THEN Fib1 := 0 ELSE IF n = 1 THEN Fib1 := 1 ELSE BEGIN f1 := Fib1(n - 1); f2 := Fib1(n - 2); Fib1 := f1 + f2; END END; FUNCTION Fib2(n: INTEGER): INTEGER; VAR state, result: INTEGER; f1, f2: INTEGER; BEGIN state := 1; while (state<>0) DO BEGIN IF state = 1 THEN BEGIN IF n = 0 THEN BEGIN result := 0; state := 0; END ELSE IF n = 1 THEN BEGIN result := 1; state := 0 END ELSE BEGIN result := Fib2(n - 1); state := 2; END END ELSE IF state = 2 THEN BEGIN f1 := result; result := Fib2(n-2); state := 3; END ELSE IF state = 3 THEN BEGIN f2 := result; result := f1 + f2; state := 0; END END; Fib2 := result; END; FUNCTION Fib3(n: INTEGER): INTEGER; VAR state, result:INTEGER; f1, f2:INTEGER; BEGIN InitStack; state := 1; while (state <> 0) DO BEGIN IF state = 1 THEN BEGIN IF n = 0 THEN BEGIN result := 0; state := 0; END ELSE IF n = 1 THEN BEGIN result := 1; state := 0 END ELSE BEGIN Push(n); Push(2); n := n - 1; state := 1; END END ELSE IF state = 2 THEN BEGIN Pop(n); f1 := result; Push(n); Push(f1); Push(3); n := n - 2; state := 1; END ELSE IF state = 3 THEN BEGIN Pop(f1); Pop(n); f2 := result; result := f1 + f2; state := 0; END; IF (state = 0) and not Empty THEN BEGIN Pop(state); END; END; Fib3 := result; END; VAR i, result:INTEGER; BEGIN FOR i := 0 to MAX DO BEGIN result := Fib3(i); Write('Fib(',i,')=',result); IF (result <> FIBONACCI[i]) THEN Write('ERROR Fib(',i,')=',FIBONACCI[i]); WriteLn; END; END.
unit BowlingInt; // unit containing the interfaces and data structures for the app interface uses Generics.Collections; // apparently this version of Delphi doesn't have spring.collections type // Represents the state the frame is in at any given time TBowlFrameType = (frameIncomplete, // frame with incomplete information frameOpen, // frame with no spares or strikes frameSpare, // frame with scores totalling 10 in 2 throws frameStrike); // frame with a 10 score for the first throw // Frame structure allowing access to a single frame IBowlFrame = interface ['{642BCAEE-5189-495C-9334-76C12225B149}'] function BowlFrameType(WhichFrame: integer): TBowlFrameType; // returns the type of frame: incomplete or final state procedure LinkNextFrame(NextFrame: IBowlFrame = nil); // register (link) new frames with their previous ones function NextFrame: IBowlFrame; // used to access the next frame in the series for scoring purposes function SecondNextFrame: IBowlFrame; // used to access two frames in the series for scoring purposes (2 strikes in a row) function CurrentScore(WhichFrame: integer): integer; // return the current score of the frame, dependent on which position the frame is in function AddRoll(ARoll: integer): boolean; // add a roll to the next available position in the frame, or return false; ARoll should be between 0 and 10; function GetRoll(AnIdx: integer): integer; // return the roll (index should be 1..3) property Roll[idx: integer]: integer read GetRoll; // property for retrieving the roll value (idx should be 1..3) end; // List containing the ten frames, last element in the list is the current frame being populated TBowlLine = TList<IBowlFrame>; // Interface used to manage the game from the users perspective IGame = interface ['{A7E5EF17-F469-49E6-9C88-C8CD2C118781}'] procedure Start; // initializes the data, erasing old score data procedure Roll(ARoll: integer); // only way to get a thrown ball score into the system, expected to be entered in sequential order function GetScoreByFrame: TBowlLine; // retrieves the scoring structure for the ScoreByFrame property property ScoreByFrame: TBowlLine read GetScoreByFrame; // read only property to get the scoring structure function TotalScore: integer; // returns the total score of all the entered ball throws up to the currently entered one end; implementation end.
(***********************************************************) (* xPLRFX *) (* part of Digital Home Server project *) (* http://www.digitalhomeserver.net *) (* info@digitalhomeserver.net *) (***********************************************************) unit uxPLRFX_0x58; interface Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uxPLRFXMessages; procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); implementation Uses SysUtils; (* Type $58 - Date/Time sensors Buffer[0] = packetlength = $0D; Buffer[1] = packettype Buffer[2] = subtype Buffer[3] = seqnbr Buffer[4] = id1 Buffer[5] = id2 Buffer[6] = yy Buffer[7] = mm Buffer[8] = dd Buffer[9] = dow Buffer[10] = hr Buffer[11] = min Buffer[12] = sec Buffer[13] = battery_level:4/rssi:4 xPL Schema datetime.basic { datetime=<date and time as yyyymmddhhmmss> date=<date as yyyymmdd> time=<time as hhmmss> } sensor.basic { device=dt1 0x<hex sensor id> type=battery current=0-100 } *) const // Type DATETIME = $58; // Subtype DT1 = $01; var SubTypeArray : array[1..1] of TRFXSubTypeRec = ((SubType : DT1; SubTypeString : 'dt1')); procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); var DeviceID : String; SubType : Byte; BatteryLevel : Integer; Year, Month, Day : String; Hour, Minute, Second : String; DateString, TimeString : String; xPLMessage : TxPLMessage; begin SubType := Buffer[2]; DeviceID := GetSubTypeString(SubType,SubTypeArray)+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2); // Convert the date Year := '20'+IntToStr(Buffer[6]); Month := IntToStr(Buffer[7]); if Buffer[7] < 10 then Month := '0'+Month; Day := IntToStr(Buffer[8]); if Buffer[8] < 10 then Day := '0'+Day; Hour := IntToStr(Buffer[10]); if Buffer[10] < 10 then Hour := '0'+Hour; Minute := IntToStr(Buffer[11]); if Buffer[11] < 10 then Minute := '0'+Minute; Second := IntToSTr(Buffer[12]); if Buffer[12] < 0 then Second := '0'+Second; DateString := Year+Month+Day; TimeString := Hour+Minute+Second; if (Buffer[13] and $0F) = 0 then // zero out rssi BatteryLevel := 0 else BatteryLevel := 100; // Create sensor.basic messages xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('datetime='+DateString+TimeString); xPLMessage.Body.AddKeyValue('date='+DateString); xPLMessage.Body.AddKeyValue('time='+TimeString); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+IntToStr(BatteryLevel)); xPLMessage.Body.AddKeyValue('type=battery'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: Types3DS<p> Implements the standard Teapot, build from evaluators.<p> <b>History : </b><font size=-1><ul> <li>06/04/08 - DaStr - Fixed sizes of some array pointer types. Now $R- is not required for units that use them. <li>30/03/07 - DaStr - Added $I GLScene.inc <li>20/07/00 - Egg - Fixed array declarations (non null range to allow bound checks), Renamed "TIntegerList" to "TIntegerArray" </ul></font> } // This unit contains all of the data types used by the core routines. Most of these are only used // with the internal database, created when a file is loaded. // // Last change - 03. October 1999 // // (c) Copyright 1999, Dipl. Ing. Mike Lischke (public@lischke-online.de) unit Types3DS; {$ALIGN ON} {$MINENUMSIZE 4} interface {$I GLScene.inc} uses System.Classes; // for TStringList //---------------- commonly used structures ---------------------------------- type TDumpLevel = (dlTerseDump, dlMediumDump, dlMaximumDump); PChar3DS = PAnsiChar; String3DS = AnsiString; String64 = string[64]; PWordList = ^TWordList; TWordList = array[0..MaxInt div (2*SizeOf(Word))] of Word; PIntegerArray = ^TIntegerArray; TIntegerArray = array[0..MaxInt div (2*SizeOf(Integer))] of Integer; PCardinalArray = ^TCardinalArray; TCardinalArray = array[0..MaxInt div (2*SizeOf(Cardinal))] of Cardinal; PSingleList = ^TSingleList; TSingleList = array[0..MaxInt div (2*SizeOf(Single))] of Single; PPoint3DS = ^TPoint3DS; // 3D point structure TPoint3DS = record X, Y, Z : Single; end; PPointList = ^TPointList; TPointList = array[0..MaxInt div (2*SizeOf(TPoint3DS))] of TPoint3DS; PFColor3DS = ^TFColor3DS; // RGB Color components TFColor3DS = record R, G, B: Single; end; PFColorList = ^TFColorList; TFColorList = array[0..MaxInt div (2*SizeOf(TFColor3DS))] of TFColor3DS; PFace3DS = ^TFace3DS; // Face List element TFace3DS = packed record case Boolean of True: (V1, V2, V3, Flag: Word); False: (FaceRec: array[0..3] of Word); end; PFaceList = ^TFaceList; TFaceList = array[0..MaxInt div (2*SizeOf(TFace3DS))] of TFace3DS; PTexVert3DS = ^TTexVert3DS; // Texture assignment coordinate TTexVert3DS = record U, V: Single; end; PTexVertList = ^TTexVertList; TTexVertList = array[0..MaxInt div (2*SizeOf(TTexVert3DS))] of TTexVert3DS; PTrackHeader3DS = ^TTrackHeader3DS; // Global track settings TTrackHeader3DS = record Flags: Word; nu1, nu2, KeyCount: Integer; // Number of keys in the track end; PKeyHeader3DS = ^TKeyHeader3DS; // Animation key settings TKeyHeader3DS = record Time: Integer; // Key's frame position RFlags: Word; // Spline terms used flag Tension: Single; // Flagged with $01 Continuity: Single; // Flagged with $02 Bias: Single; // Flagged with $04 EaseTo: Single; // Flagged with $08 EaseFrom: Single; // Flagged with $10 end; PKeyHeaderList = ^TKeyHeaderList; TKeyHeaderList = array[0..MaxInt div (2*SizeOf(TKeyHeader3DS))] of TKeyHeader3DS; PKFRotKey3DS = ^TKFRotKey3DS; // Rotation key TKFRotKey3DS = record Angle: Single; // Angle of Rotation X, Y, Z: Single; // Rotation axis vector end; PKFRotKeyList = ^TKFRotKeyList; TKFRotKeyList = array[0..MaxInt div (2*SizeOf(TKFRotKey3DS))] of TKFRotKey3DS; PKFMorphKey3DS = ^TKFMorphKey3DS; // Object Morph key TKFMorphKey3DS = String; // Name of Target Morph object PKFMorphKeyList = ^TKFMorphKeyList; TKFMorphKeyList = array[0..MaxInt div (2*SizeOf(TKFMorphKey3DS))] of TKFMorphKey3DS; PChunk3DS = ^TChunk3DS; // internal database representation of file information PChunkListEntry3DS = ^TChunkListEntry3DS; // cross reference between Name and Chunk TChunkListEntry3DS = record NameStr: String; // chunk name list Chunk: PChunk3DS; // corresponding pos end; PChunkList = ^TChunkList; TChunkList = array[0..MaxInt div (2*SizeOf(TChunkListEntry3DS))] of TChunkListEntry3DS; PChunkList3DS = ^TChunkList3DS; // list of cross references TChunkList3DS = record Count: Integer; // number of entries in List List: PChunkList; // contents of List end; { replaced by a TStringList PNameList = ^TNameList; TNameList = array[0..0] of String; PNameList3DS = ^TNameList3DS; // list of database object names TNameList3DS = record Count : Integer; // how many entries are in list Spaces : Integer; // how much space for entries Names : PNameList; // to access pointers end;} // Database type settings TDBType3DS = (dbUnknown, // database has not been created yet dbMeshFile, // 3D Studio .3DS file dbProjectFile, // 3D Studio .PRJ file dbMaterialFile // 3D Studio .MLI file ); PNodeList = ^TNodeList; TNodeList = record ID: SmallInt; Tag: Word; Name, InstStr: String; ParentID: SmallInt; Next: PNodeList; end; PDatabase3DS = ^TDatabase3DS; // file database TDatabase3DS = record TopChunk: PChunk3DS; // Top chunk in the file ObjListDirty, // If True, than ObjList needs to be recreated MatListDirty, NodeListDirty: Boolean; ObjList, // Quick Cross references between names and database chunks MatList, NodeList: PChunkList3DS; end; TViewType3DS = (vtNoView3DS, vtTopView3DS, vtBottomView3DS, vtLeftView3DS, vtRightView3DS, vtFrontView3DS, vtBackView3DS, vtUserView3DS, vtCameraView3DS, vtSpotlightView3DS); PViewSize3DS = ^TViewSize3DS; TViewSize3DS = record XPos, YPos, Width, Height: Word; end; POrthoView3DS = ^TOrthoView3DS; // Used to describe Top, Bottom, left, right, front and back views TOrthoView3DS = record Center: TPoint3DS; // Center of orthogonal View Zoom: Single; // View Zoom factor end; PUserView3DS = ^TUserView3DS; TUserView3DS = record // Used to describe User views Center: TPoint3DS; // Center of User View Zoom: Single; // View Zoom factor HorAng: Single; // Horizontal Angle of View VerAng: Single; // Vertical Angle of View end; PViewport3DS = ^TViewport3DS; // Viewport structure details the kind of View in a viewport TViewport3DS = record AType: TViewType3DS; // top, bottom, left, right, front, back, user and camera, spot Size: TViewSize3DS; // size of the viewport Ortho: TOrthoView3DS; // used for top, bottom, left, right, front, and back views User: TUserView3DS; // Used for User views CameraStr: String; // used for camera views end; TShadowStyle3DS = (ssUseShadowMap, ssUseRayTraceShadow); PShadowSets3DS = ^TShadowSets3DS; // global Shadow settings TShadowSets3DS = record AType: TShadowStyle3DS; // either UseShadowMaps or UseRayTraceShadows Bias: Single; // Shadow Bias factor. RayBias: Single; // Shadow ray Bias factor, Used in R3 MapSize: Smallint; // Shadow Map Size Filter: Single; // Shadow Filter end; PMeshSet3DS = ^TMeshSet3DS; TMeshSet3DS = record MasterScale: Single; // master mesh Scale factor Shadow: TShadowSets3DS; // Global Shadow settings AmbientLight: TFColor3DS; // Ambient light Color OConsts: TPoint3DS; // default object constructing axis end; TAtmosphereType3DS = (atNoAtmo, // no active atmospherics atUseFog, // Fog atmospheric atUseLayerFog, // layer Fog atmospheric atUseDistanceCue // distance cue atmospheric ); TLayerFogFalloff3DS = (lfNoFall, // no FallOff lfTopFall, // FallOff to the Top lfBottomFall // FallOff to the Bottom ); PFogSettings3DS = ^TFogSettings3DS; // Fog atmosphere parameters TFogSettings3DS = record NearPlane: Single; // near radius of Fog effect NearDensity: Single; // near Fog Density FarPlane: Single; // far radius of Fog effect FarDensity: Single; // far Fog Density FogColor: TFColor3DS; // Color of Fog effect FogBgnd: Boolean; // "Fog background" Flag end; PLayerFogSettings3DS = ^TLayerFogSettings3DS; // layered Fog atmosphere parameters TLayerFogSettings3DS = record ZMin: Single; // lower bounds of Fog ZMax: Single; // upper bounds of Fog Density: Single; // Fog Density FogColor: TFColor3DS; // Fog Color FallOff: TLayerFogFalloff3DS; // FallOff style FogBgnd: Boolean; // "Fog background" Flag end; PDCueSettings3DS = ^TDCueSettings3DS; // distance cue atmosphere parameters TDCueSettings3DS = record NearPlane: Single; // near radius of effect NearDim: Single; // near dimming factor FarPlane: Single; // far radius of effect FarDim: Single; // far dimming factor DCueBgnd: Boolean; // effect the background Flag end; PAtmosphere3DS = ^TAtmosphere3DS; TAtmosphere3DS = record Fog: TFogSettings3DS; // Fog atmosphere settings LayerFog: TLayerFogSettings3DS; // layered Fog atmosphere parameters DCue: TDCueSettings3DS; // distance cue atmosphere parameters ActiveAtmo: TAtmosphereType3DS; // the active atmospheric end; // enumerate list of possible backgrounds used in file TBackgroundType3DS = (btNoBgnd, btUseSolidBgnd, btUseVGradientBgnd, btUseBitmapBgnd); PBitmapBgnd3DS = ^TBitmapBgnd3DS; TBitmapBgnd3DS = AnsiString; // Name of background Bitmap TSolidBgnd3DS = TFColor3DS; // Color of Solid background PVGradientBgnd3DS = ^TVGradientBgnd3DS; TVGradientBgnd3DS = record GradPercent: Single; // placement of Mid Color band, Ranges from 0-1 Top: TFColor3DS; // color of Top band Mid: TFColor3DS; // color of Mid background band Bottom: TFColor3DS; // color of Bottom band end; PBackground3DS = ^TBackground3DS; TBackground3DS = record Bitmap: TBitmapBgnd3DS; Solid: TSolidBgnd3DS; VGradient: TVGradientBgnd3DS; BgndUsed: TBackgroundType3DS; // background in effect end; // used for shading field in TMaterial3DS structure TShadeType3DS = (stWire, stFlat, stGouraud, stPhong, stMetal); // used for tiling field in TBitmap3DS structure TTileType3DS = (ttTile, ttDecal, ttBoth); TFilterType3DS = (ftPyramidal, ftSummedArea); TTintType3DS = (ttRGB, ttAlpha, ttRGBLumaTint, ttAlphaTint, ttRGBTint); // used by AddMaterial3DS PACubic3DS = ^TACubic3DS; TACubic3DS = record FirstFrame: Boolean; // True for First Frame Only Flat: Boolean; // True for Flat Mirror reflection Size: Integer; // Map resolution nthFrame: Integer; // Map update period end; // Cubic reflection Map defintion PBitmap3DS = ^TBitmap3DS; TBitmap3DS = record NameStr: AnsiString; // Bitmap file name Percent: Single; // Strength percentage Tiling: TTileType3DS; // Tile/Decal/Both IgnoreAlpha: Boolean; Filter: TFilterType3DS; // Pyramidal/Summed Area Blur: Single; Mirror: Boolean; Negative: Boolean; UScale: Single; VScale: Single; UOffset: Single; VOffset: Single; Rotation: Single; Source: TTintType3DS; // RGB/RGB Luma Tint/Alpha Tint/RGB Tint Tint1: TFColor3DS; Tint2: TFColor3DS; RedTint: TFColor3DS; GreenTint: TFColor3DS; BlueTint: TFColor3DS; DataSize: Integer; // Size of procedural Data Data: Pointer; // Procedural Data end; // Bit Map definition // Structure to all Map settings PMapSet3DS = ^TMapSet3DS; TMapSet3DS = record Map: TBitmap3DS; // The Map settings Mask: TBitmap3DS; // The Mask settings end; TRMapSet3DS = record Map: TBitmap3DS; // The Map settings UseAuto: Boolean; // True if automatic reflections are being used AutoMap: TACubic3DS; // Automatic reflection definitions Mask: TBitmap3DS; // The Mask settings end; PMaterial3DS = ^TMaterial3DS; TMaterial3DS = record NameStr: AnsiString; // Name Ambient: TFColor3DS; // Ambient Light Color Diffuse: TFColor3DS; // Diffuse Light Color Specular: TFColor3DS; // Specular Light Color Shininess: Single; // Shininess factor ShinStrength: Single; // Shininess strength Blur: Single; // Blur factor Transparency: Single; // Trasparency factor TransFallOff: Single; // Falloff factor SelfIllumPct: Single; // Self illumination percentage WireSize: Single; // Width of wireframe Shading: TShadeType3DS; // Shading type UseBlur: Boolean; // Blurring Flag UseFall: Boolean; // Transparency FallOff Flag TwoSided: Boolean; // Two sided material Flag SelFillum: Boolean; // Self illumination Flag Additive: Boolean; // Additive Transparency Flag UseWire: Boolean; // Use wireframe rendering UseWireAbs: Boolean; // Wire Size is in units, not pixels. FaceMap: Boolean; // Face mapping switch Soften: Boolean; // Soften switch Texture: TMapSet3DS; // Texture Map settings Texture2: TMapSet3DS; // Second Texture Map settings Opacity: TMapSet3DS; // Opacity Map settings Bump: TMapSet3DS; // Bump Map settings SpecMap: TMapSet3DS; // Specularity Map settings ShinMap: TMapSet3DS; // Shininess Map settings IllumMap: TMapSet3DS; // Self illumination Map settings Reflect: TRMapSet3DS; // Reflection Map settings end; // Mesh definition PMeshMatrix = ^TMeshMatrix; TMeshMatrix = array[0..11] of Single; // Texture Map icon placement PMapInfo3DS = ^TMapInfo3DS; TMapInfo3DS = record MapType: Word; // icon type TileX: Single; // tiling TileY: Single; CenX: Single; // position of center CenY: Single; CenZ: Single; Scale: Single; // icon scaling factor Matrix: TMeshMatrix; // orientation matrix PW: Single; // planar icon width PH: Single; // planar icon height CH: Single; // cylinder icon height end; // Material assignments by face PObjMat3DS = ^TObjMat3DS; TObjMat3DS = record NameStr: AnsiString; // material name NFaces: Word; // number of faces using material FaceIndex: PWordList; // list of faces using material end; PObjMatList = ^TObjMatList; TObjMatList = array[0..MaxInt div (2*SizeOf(TObjMat3DS))] of TObjMat3DS; // Mesh object definition PMesh3DS = ^TMesh3DS; TMesh3DS = record NameStr: AnsiString; // object name IsHidden: Boolean; // hidden object flag IsvisLofter: Boolean; // lofter visibility flag IsMatte: Boolean; // matte object flag IsNoCast: Boolean; // doesn't cast shadows flag IsFast: Boolean; // fast display flag IsNorcvShad: boolean; // doesn't recieve shadows IsFrozen: Boolean; // frozen object flag NVertices: Word; // vertice count VertexArray: PPointList; // list of vertices NVFlags: Word; // number of vertex flags VFlagArray: PWordList; // list of vertex flags NTextVerts: Word; // number of texture vertices TextArray: PTexVertList; // list of texture coordinates UseMapInfo: Boolean; // for use of mapping icon information Map: TMapInfo3DS; // mapping icon info LocMatrix: TMeshMatrix; // object orientation matrix NFaces: Word; // face count FaceArray: PFaceList; // list of faces SmoothArray: PCardinalArray; // smoothing group assignment list UseBoxMap: Boolean; // used to indicate the use of box mapping BoxMapStr: array[0..5] of String; // material names used in boxmapping MeshColor: Byte; // UI color assigned to the mesh NMats: Word; // assigned materials count MatArray: PObjMatList; // material assignment list UseProc: Boolean; // use animated stand-in flag ProcSize: Integer; // size of animated stand-in data ProcNameStr: String; // name of animated stand-in procedure ProcData: Pointer; // animated stand-in data end; // Spotlight projection cone shape TConeStyle3DS = (csCircular, csRectangular); // Spotlight shadow settings PSpotShadow3DS = ^TSpotShadow3DS; TSpotShadow3DS = record Cast: Boolean; // True if spotlight casts shadows AType: TShadowStyle3DS; // UseShadow or UseRayTrace Local: Boolean; // True if local shadow settings are being used Bias: Single; // shadow bias Filter: Single; // shadow filter MapSize: Word; // shadow map size RayBias: Single; // Ray tracing shadow bias end; // Cone visibility settings PSpotCone3DS = ^TSpotCone3DS; TSpotCone3DS = record AType: TConeStyle3DS; // Circular or rectangular light cone Show: Boolean; // True if cone is visible Overshoot: Boolean; // True if cone overshoot is on end; // spotlight projectio Bitmap PSpotProjector3DS = ^TSpotProjector3DS; TSpotProjector3DS = record Use: Boolean; // True if using projector BitmapStr: String; // name of projector bitmap end; // spotlight settings PSpotLight3DS = ^TSpotLight3DS; TSpotLight3DS = record Target: TPoint3DS; // Spotlight Target Hotspot: Single; // Hotspot Angle FallOff: Single; // Hotspot FallOff Roll: Single; // Roll Angle Aspect: Single; // Aspect ratio Shadows: TSpotShadow3DS; Cone: TSpotCone3DS; Projector: TSpotProjector3DS; end; // Light Attenuation settings PLiteAttenuate3DS = ^TLiteAttenuate3DS; TLiteAttenuate3DS = record IsOn: Boolean; // True if Light Attenuation is on Inner: Single; // Inner range of Attenuation Outer: Single; // Outer range of Attenuation end; // omni and spotlight settings PLight3DS = ^TLight3DS; TLight3DS = record NameStr: AnsiString; // light name Pos: TPoint3DS; // light position Color: TFColor3DS; // light color Multiplier: Single; // light intensity multiplier DLOff: Boolean; // True if light is off Attenuation: TLiteAttenuate3DS; Exclude: TStringList; Spot: PSpotLight3DS; // if not nil then struct is a spotlight, else omni end; // Camera atomosphere Ranges PCamRanges3DS = ^TCamRanges3DS; TCamRanges3DS = record CamNear: Single; // Nearest effect radius CamFar: Single; // Farthest effect radius end; PCamera3DS = ^TCamera3DS; TCamera3DS = record NameStr: AnsiString; Position: TPoint3DS; Target: TPoint3DS; Roll: Single; FOV: Single; ShowCone: Boolean; Ranges: TCamRanges3DS; end; PKFKeyInfo3DS = ^TKFKeyInfo3DS; TKFKeyInfo3DS = record Length: Integer; CurFrame: Integer; end; PKFSegment3DS = ^TKFSegment3DS; TKFSegment3DS = record Use: Boolean; SegBegin: Integer; SegEnd: Integer; end; PKFSets3DS = ^TKFSets3DS; TKFSets3DS = record Anim: TKFKeyInfo3DS; Seg: TKFSegment3DS; end; PKFCamera3DS = ^TKFCamera3DS; TKFCamera3DS = record NameStr: AnsiString; // Name of Camera object ParentStr: AnsiString; // Name of Parent object Flags1: Word; // Flags field from node header -fixup later Flags2: Word; // Flags2 field from node header -fixup later NPKeys: Integer; // Number of Camera Position keys NPFlag: Word; // Loop control Flag for Camera Position keys PKeys: PKeyHeaderList; // Spline values for Camera Position keys Pos: PPointList; // Camera Position keys NFKeys: Integer; // Number of Camera FOV keys NFFlag: Word; // Loop control Flag for Camera FOV keys FKeys: PKeyHeaderList; // Spline values for Camera FOV keys FOV: PSingleList; // Camera FOV keys NRKeys: Integer; // Number of Camera Roll keys NRFlag: Word; // Loop control Flag for Camera Roll keys RKeys: PKeyHeaderList; // Spline values for Camera Roll keys Roll: PSingleList; // Camera Roll keys TParentStr: String; // Index of Parent object for Target NTKeys: Integer; // Number of Target Position keys NTFlag: Word; // Loop control Flag for Target Position keys TKeys: PKeyHeaderList; // Spline values for Target Position keys TPos: PPointList; // Target Position keys TFlags1: Word; // Flags field from Target node header TFlags2: Word; // Flags field from Target node header end; // Ambient Light animation PKFAmbient3DS = ^TKFAmbient3DS; TKFAmbient3DS = record Flags1: Word; // Flags field from node header -fixup later Flags2: Word; // Flags2 field from node header -fixup later NCKeys: Integer; // Number of Color keys NCFlag: Word; // Loop control Flag for Color keys CKeys: PKeyHeaderList; // Spline values for Position keys Color: PFColorList; // Color keys end; // used by ObjectMotion3DS PKFMesh3DS = ^TKFMesh3DS; TKFMesh3DS = record NameStr: AnsiString; // Name of mesh ParentStr: AnsiString; // Name of Parent object Flags1: Word; // Flags field from node header Flags2: Word; // Flags2 field from node header Pivot: TPoint3DS; // Object Pivot point InstanceStr: AnsiString; // Object Instance Name BoundMin: TPoint3DS; // Minimum bounding box point for dummy objects BoundMax: TPoint3DS; // Maximum bounding box point for dummy objects NPKeys: Integer; // Number of Position keys NPFlag: Smallint; // Loop control Flag for Position keys PKeys: PKeyHeaderList; // Spline values for Position keys Pos: PPointList; // Mesh Position keys NRKeys: Integer; // Number of Rotation keys NRFlag: Smallint; // Loop control Flag for Rotation keys RKeys: PKeyHeaderList; // Spline values for Rotation keys Rot: PKFRotKeyList; // Rotation keys NSKeys: Integer; // Number of scaling keys NSFlag: Smallint; // Loop control Flag for scaling keys SKeys: PKeyHeaderList; // Spline values for scaling Scale: PPointList; // Mesh scaling keys NMKeys: Integer; // Number of Morph keys NMFlag: Smallint; // Loop control Flag for Morph keys MKeys: PKeyHeaderList; // Spline values for Morph keys Morph: PKFMorphKeyList; // Morph keys NHKeys: Integer; // Number of hide keys NHFlag: Smallint; // Loop control Flag for hide keys HKeys: PKeyHeaderList; // Spline values for hide keys MSAngle: Single; // Morph smoothing group Angle end; // used by OmnilightMotion3DS PKFOmni3DS = ^TKFOmni3DS; TKFOmni3DS = record Name: AnsiString; // Name of the Light object node Parent: AnsiString; // Name of the Parent object Flags1: Word; // Flags field from node header -fixup later Flags2: Word; // Flags2 field from node header -fixup later NPKeys: Integer; // Number of Position keys NPFlag: Word; // Loop control Flag for Position keys PKeys: PKeyHeaderList; // Spline values for Position keys Pos: PPointList; // Position keys NCKeys: Integer; // Number of Color keys NCFlag: Word; // Loop control Flag for Color keys CKeys: PKeyHeaderList; // Spline values for Position keys Color: PFColorList; // Color keys end; PKFSpot3DS = ^TKFSpot3DS; TKFSpot3DS = record Name: AnsiString; // Name of Camera object Parent: AnsiString; // Parent Name Flags1: Word; // Flags field from node header -fixup later Flags2: Word; // Flags2 field from node header -fixup later {$ifdef broken} visible: Smallint; // Flags to control visibility {$endif} NPKeys: Integer; // Number of Light Position keys NPFlag: Word; // Loop control Flag for Position keys PKeys: PKeyHeaderList; // Spline values for Light Position keys Pos: PPointList; // Light Position keys NCKeys: Integer; // Number of Color keys NCFlag: Word; // Loop control Flag Color keys CKeys: PKeyHeaderList; // Spline values for Color keys Color: PFColorList; // Color keys NHKeys: Integer; // Number of Hotspot Angle keys NHFlag: Word; // Loop control Flag for Hotspot Angle keys HKeys: PKeyHeaderList; // Spline values for Hotspot Angle keys Hot: PSingleList; // Hotspot Angle keys NFKeys: Integer; // Number of FallOff Angle keys NFFlag: Word; // Loop control Flag for FallOff Angle keys FKeys: PKeyHeaderList; // Spline values for FallOff Angle keys Fall: PSingleList; // FallOff Angle keys NRKeys: Integer; // Number of Light Roll keys NRFlag: Word; // Loop control Flag for Light Roll keys RKeys: PKeyHeaderList; // Spline values for Light Roll keys Roll: PSingleList; // Light Roll keys TParent: AnsiString; // Name of Target's Parent object NTKeys: Integer; // Number of Target Position keys NTFlag: Word; // Loop control Flag for Target Position keys TKeys: PKeyHeaderList; // Spline values for Target Position keys TPos: PPointList; // Target Position keys TFlags1: Word; // Flags field from Target node header TFlags2: Word; // Flags field from Target node header end; PXDataRaw3DS = ^TXDataRaw3DS; TXDataRaw3DS = record Size: Integer; Data: Pointer; end; TTargetType3DS = (ttLightTarget,ttCameraTarget); PM3dVersion = ^TM3dVersion; TM3dVersion = Cardinal; // inner datatypes not followed by a '3DS' to show they are locally used // (mostly as a part of another chunk or while collecting specific data) PColorF = ^TColorF; TColorF = record Red, Green, Blue: Single; end; PLinColorF = ^TLinColorF; TLinColorF = TColorF; PColor24 = ^TColor24; TColor24 = record Red, Green, Blue: Byte; end; PLinColor24 = ^TLinColor24; TLinColor24 = TColor24; PMatMapRCol = ^TMatMapRCol; TMatMapRCol = TLinColor24; PMatMapGCol = ^TMatMapGCol; TMatMapGCol = TMatMapRCol; PMatMapBCol = ^TMatMapBCol; TMatMapBCol = TMatMapGCol; PMatMapCol1 = ^TMatMapCol1; TMatMapCol1 = TMatMapBCol; PMatMapCol2 = ^TMatMapCol2; TMatMapCol2 = TMatMapCol1; PIntPercentage = ^TIntPercentage; TIntPercentage = SmallInt; PMatBumpPercent = ^TMatBumpPercent; TMatBumpPercent = TIntPercentage; PFloatPercentage = ^TFloatPercentage; TFloatPercentage = Single; PMatMapname = PChar3DS; PMeshVersion = ^TMeshVersion; TMeshVersion = Integer; PMasterScale = ^TMasterScale; TMasterScale = Single; PLoShadowBias = ^TLoShadowBias; TLoShadowBias = Single; PHiShadowBias = ^THiShadowBias; THiShadowBias = TLoShadowBias; PRayBias = ^TRayBias; TRayBias = THiShadowBias; PShadowMapSize = ^TShadowMapSize; TShadowMapSize = SmallInt; PShadowSamples = ^TShadowSamples; TShadowSamples = SmallInt; PShadowRange = ^TShadowRange; TShadowRange = Integer; PShadowFilter = ^TShadowFilter; TShadowFilter = Single; POConsts = ^TOConsts; TOConsts = TPoint3DS; PBitMapName = PChar3DS; PVGradient = ^TVGradient; TVGradient = Single; PFog = ^TFog; TFog = record NearPlaneDist: Single; NearPlaneDensity: Single; FarPlaneDist: Single; FarPlaneDensity: Single; end; PLayerFog = ^TLayerFog; TLayerFog = record ZMin: Single; ZMax: Single; Density: Single; AType: Cardinal; end; PDistanceCue = ^TDistanceCue; TDistanceCue = record NearPlaneDist: Single; NearPlaneDimming: Single; FarPlaneDist: Single; FarPlaneDimming: Single; end; PViewStandard = ^TViewStandard; TViewStandard = record ViewTargetCoord: TPoint3DS; ViewWidth: Single; end; PViewUser = ^TViewUser; TViewUser = record ViewTargetCoord: TPoint3DS; ViewWidth: Single; XYViewangle: Single; YZViewangle: Single; BankAngle: Single; end; PViewCamera = PChar3DS; PMatName = PChar3DS; PMatShading = ^TMatShading; TMatShading = SmallInt; PMatAcubic = ^TMatAcubic; TMatAcubic = record ShadeLevel: Byte; Antialias: Byte; Flags: SmallInt; MapSize: Cardinal; FrameInterval: Cardinal; end; PIpasData = ^TIpasData; TIpasData = record Size: Integer; Data: Pointer; end; PMatWireSize = ^TMatWireSize; TMatWireSize = Single; PMatMapTiling = ^TMatMapTiling; TMatMapTiling = Word; PMatMapTexblur = ^TMatMapTexblur; TMatMapTexblur = Single; PMatMapUScale = ^TMatMapUScale; TMatMapUScale = Single; PMatMapVScale = ^TMatMapVScale; TMatMapVScale = TMatMapUScale; PMatMapUOffset = ^TMatMapUOffset; TMatMapUOffset = Single; PMatMapVOffset = ^TMatMapVOffset; TMatMapVOffset = TMatMapUOffset; PMatMapAng = ^TMatMapAng; TMatMapAng = Single; PNamedObject = PChar3DS; PPointArray = ^TPointArray; TPointArray = record Vertices: Word; PointList: PPointList; end; PPointFlagArray = ^TPointFlagArray; TPointFlagArray = record Flags: Word; FlagList: PWordList; end; PFaceArray = ^TFaceArray; TFaceArray = record Faces: Word; FaceList: PFaceList; end; PMshMatGroup = ^TMshMatGroup; TMshMatGroup = record MatNameStr: AnsiString; Faces: Word; FaceList: PWordList; end; PMshBoxmap = ^TMshBoxmap; TMshBoxmap = array[0..5] of AnsiString; PSmoothGroup = ^TSmoothGroup; TSmoothGroup = record Groups: Word; GroupList: PCardinalArray; end; PTexVerts = ^TTexVerts; TTexVerts = record NumCoords: Word; TextVertList: PTexVertList; end; PMeshColor = ^TMeshColor; TMeshColor = Byte; PMeshTextureInfo = ^TMeshTextureInfo; TMeshTextureInfo = record MapType: Word; XTiling: Single; YTiling: Single; IconPos: TPoint3DS; IconScaling: Single; XMatrix: TMeshMatrix; IconWidth: Single; IconHeight: Single; CylIconHeight: Single; end; PProcName = PChar3DS; PNDirectLight = ^TNDirectLight; TNDirectLight = TPoint3DS; PDlExclude = PChar3DS; PDlSpotlight = ^TDlSpotlight; TDlSpotlight = record SpotLightTarg: TPoint3DS; HotspotAngle: Single; FalloffAngle: Single; end; PDlOuterRange = ^TDlOuterRange; TDlOuterRange = Single; PDlInnerRange = ^TDlInnerRange; TDlInnerRange = TDlOuterRange; PDlMultiplier = ^TDlMultiplier; TDlMultiplier = Single; PDlSpotRoll = ^TDlSpotRoll; TDlSpotRoll = Single; PDlSpotAspect = ^TDlSpotAspect; TDlSpotAspect = Single; PDlSpotProjector = PChar3DS; PDlRayBias = ^TDlRayBias; TDlRayBias = Single; PDlLocalShadow2 = ^TDlLocalShadow2; TDlLocalShadow2 = record LocalShadowBias: Single; LocalShadowFilter: Single; LocalShadowMapSize: SmallInt end; PNCamera = ^TNCamera; TNCamera = record CameraPos: TPoint3DS; TargetPos: TPoint3DS; CameraBank: Single; CameraFocalLength: Single; end; PCamRanges = ^TCamRanges; TCamRanges = record NearPlane: Single; FarPlane: Single; end; PViewportLayout = ^TViewportLayout; TViewportLayout = record Form: SmallInt; // 0 = single window // 1 = 2 split verticle // 2 = 2 split horizontal // 3 = 4 equal squares // 4 = 2 squares left & 1 rect right // 5 = 1 rect at Top & 2 sqr on bot // 6 = 1 rect left & 2 sqr right // 7 = 2 sqr Top & 1 rect bot // 8 = 3 split vertical // 9 = 2 split horiz // 10 = 3 sqr left and 1 rect right // 11 = 1 rect left & 3 sqr. right // Form becomes 0 during swap and its preswapped value is stored in the SwapPort field Top: SmallInt; // Active window index of 0 to 5 Ready: SmallInt; WState: SmallInt; // 0 if no swap window, 1 if in swaped "w" state. During a swap, the old 0 window gets stored as the 4 window SwapWS: SmallInt; SwapPort: SmallInt; // The preswapped value from the Form field SwapCur: SmallInt; // The window index that was swapped end; PViewportSize = ^TViewportSize; TViewportSize = record // Values given for 1024x768 resolution XPos: Word; // 0 YPos: Word; // 14 Width: Word; // 895 Height: Word; // 725 end; PViewportData = ^TViewportData; TViewportData = record Flags: Word; AxisLockout: Word; WinXPos: Word; WinYPos: Word; WinWidth: Word; WinHeight: Word; View: Word; // 0 = No View // 1 = Top View // 2 = Bottom View // 3 = Left View // 4 = Right View // 5 = Front View // 6 = Back View // 7 = User View // 18 = Spotlight View // 65535 = Camera View ZoomFactor: Single; Center: TPoint3DS; HorizAng: Single; VertAng: Single; CamNameStr: AnsiString; end; PViewportData3 = ^TViewportData3; TViewportData3 = TViewportData; PKFHdr = ^TKFHdr; TKFHdr = record Revision: SmallInt; Filename: String; AnimLength: Integer; end; PKFId = ^TKFId; TKFId = SmallInt; PKFSeg = ^TKFSeg; TKFSeg = record First: Integer; Last: Integer; end; PKFCurtime = ^TKFCurtime; TKFCurtime = Integer; PNodeHdr = ^TNodeHdr; TNodeHdr = record ObjNameStr: String; Flags1: Word; Flags2: Word; ParentIndex: SmallInt; end; PPivot = ^TPivot; TPivot = TPoint3DS; PInstanceName = PChar3DS; PMorphSmooth = ^TMorphSmooth; TMorphSmooth = Single; PBoundBox = ^TBoundBox; TBoundBox = record Min: TPoint3DS; Max: TPoint3DS; end; PPosTrackTag = ^TPosTrackTag; TPosTrackTag = record TrackHdr: TTrackHeader3DS; KeyHdrList: PKeyHeaderList; PositionList: PPointList; end; PColTrackTag = ^TColTrackTag; TColTrackTag = record TrackHdr: TTrackHeader3DS; KeyHdrList: PKeyHeaderList; ColorList: PFColorList; end; PRotTrackTag = ^TRotTrackTag; TRotTrackTag = record TrackHdr: TTrackHeader3DS; KeyHdrList: PKeyHeaderList; RotationList: PKFRotKeyList; end; PScaleTrackTag = ^TScaleTrackTag; TScaleTrackTag = record TrackHdr: TTrackHeader3DS; KeyHdrList: PKeyHeaderList; ScaleList: PPointList; end; PMorphTrackTag = ^TMorphTrackTag; TMorphTrackTag = record TrackHdr: TTrackHeader3DS; KeyHdrList: PKeyHeaderList; MorphList: PKFMorphKeyList; end; PHideTrackTag = ^THideTrackTag; THideTrackTag = record TrackHdr: TTrackHeader3DS; KeyHdrList: PKeyHeaderList; end; PFovTrackTag = ^TFovTrackTag; TFovTrackTag = record TrackHdr: TTrackHeader3DS; KeyHdrList: PKeyHeaderList; FOVAngleList: PSingleList; end; PRollTrackTag = ^TRollTrackTag; TRollTrackTag = record TrackHdr: TTrackHeader3DS; KeyHdrList: PKeyHeaderList; RollAngleList: PSingleList; end; PHotTrackTag = ^THotTrackTag; THotTrackTag = record TrackHdr: TTrackHeader3DS; KeyHdrList: PKeyHeaderList; HotspotAngleList: PSingleList; end; PFallTrackTag = ^TFallTrackTag; TFallTrackTag = record TrackHdr: TTrackHeader3DS; KeyHdrList: PKeyHeaderList; FalloffAngleList: PSingleList; end; PXDataEntry = ^TXDataEntry; TXDataEntry = record Size: Integer; Data: Pointer; end; PXDataAppName = PChar3DS; PXDataString = PChar3DS; PXDataFloat = ^TXDataFloat; TXDataFloat = Single; PXDataDouble = ^TXDataDouble; TXDataDouble = Double; PXDataShort = ^TXDataShort; TXDataShort = SmallInt; PXDataLong = ^TXDataLong; TXDataLong = Integer; PXDataVoid = ^TXDataVoid; TXDataVoid = Pointer; TReleaseLevel = (rlRelease1, rlRelease2, rlRelease3, rlReleaseNotKnown); // to avoid zillion type casts, we use this variant record for // chunk data, effectively this defines the same pointer differently // for different chunk types // this is only possible because all types are just pointers TChunkData = record case Integer of 0 : (ColorF: PColorF); 1 : (LinColorF: PLinColorF); 2 : (Color24: PColor24); 3 : (LinColor24: PLinColor24); 4 : (IntPercentage: PIntPercentage); 5 : (FloatPercentage: PFloatPercentage); 6 : (MatMapname: PMatMapname); 7 : (M3dVersion: PM3dVersion); 8 : (MeshVersion: PMeshVersion); 9 : (MasterScale: PMasterScale); 10 : (LoShadowBias: PLoShadowBias); 11 : (ShadowFilter: PShadowFilter); 12 : (ShadowRange: PShadowRange); 13 : (HiShadowBias: PHiShadowBias); 14 : (RayBias: PRayBias); 15 : (ShadowMapSize: PShadowMapSize); 16 : (ShadowSamples: PShadowSamples); 17 : (OConsts: POConsts); 18 : (BitMapName: PBitMapName); 19 : (VGradient: PVGradient); 20 : (Fog: PFog); 21 : (LayerFog: PLayerFog); 22 : (DistanceCue: PDistanceCue); 23 : (ViewStandard: PViewStandard); 24 : (ViewUser: PViewUser); 25 : (ViewCamera: PViewCamera); 26 : (MatName: PMatName); 27 : (MatShading: PMatShading); 28 : (MatAcubic: PMatAcubic); 29 : (IpasData: PIpasData); 30 : (MatWireSize: PMatWireSize); 31 : (MatMapTiling: PMatMapTiling); 32 : (MatMapTexblur: PMatMapTexblur); 33 : (MatMapUScale: PMatMapUScale); 34 : (MatMapVScale: PMatMapVScale); 35 : (MatMapUOffset: PMatMapUOffset); 36 : (MatMapVOffset: PMatMapVOffset); 37 : (MatMapAng: PMatMapAng); 38 : (MatMapCol1: PMatMapCol1); 39 : (MatMapCol2: PMatMapCol2); 40 : (MatMapRCol: PMatMapRCol); 41 : (MatMapGCol: PMatMapGCol); 42 : (MatMapBCol: PMatMapBCol); 43 : (MatBumpPercent: PMatBumpPercent); 44 : (NamedObject: PNamedObject); 45 : (PointArray: PPointArray); 46 : (PointFlagArray: PPointFlagArray); 47 : (FaceArray: PFaceArray); 48 : (MshMatGroup: PMshMatGroup); 49 : (MshBoxmap: PMshBoxmap); 50 : (SmoothGroup: PSmoothGroup); 51 : (TexVerts: PTexVerts); 52 : (MeshMatrix: PMeshMatrix); 53 : (MeshColor: PMeshColor); 54 : (MeshTextureInfo: PMeshTextureInfo); 55 : (ProcName: PProcName); 56 : (NDirectLight: PNDirectLight); 57 : (DlExclude: PDlExclude); 58 : (DlInnerRange: PDlInnerRange); 59 : (DlOuterRange: PDlOuterRange); 60 : (DlMultiplier: PDlMultiplier); 61 : (DlSpotlight: PDlSpotlight); 62 : (DlLocalShadow2: PDlLocalShadow2); 63 : (DlSpotRoll: PDlSpotRoll); 64 : (DlSpotAspect: PDlSpotAspect); 65 : (DlSpotProjector: PDlSpotProjector); 66 : (DlRayBias: PDlRayBias); 67 : (NCamera: PNCamera); 68 : (CamRanges: PCamRanges); 69 : (ViewportLayout: PViewportLayout); 70 : (ViewportSize: PViewportSize); 71 : (ViewportData: PViewportData); 72 : (XDataEntry: PXDataEntry); 73 : (XDataAppName: PXDataAppName); 74 : (XDataString: PXDataString); 75 : (KFHdr: PKFHdr); 76 : (KFSeg: PKFSeg); 77 : (KFCurtime: PKFCurtime); 78 : (KFId: PKFId); 79 : (NodeHdr: PNodeHdr); 80 : (Pivot: PPivot); 81 : (InstanceName: PInstanceName); 82 : (MorphSmooth: PMorphSmooth); 83 : (BoundBox: PBoundBox); 84 : (PosTrackTag: PPosTrackTag); 85 : (ColTrackTag: PColTrackTag); 86 : (RotTrackTag: PRotTrackTag); 87 : (ScaleTrackTag: PScaleTrackTag); 88 : (MorphTrackTag: PMorphTrackTag); 89 : (FovTrackTag: PFovTrackTag); 90 : (RollTrackTag: PRollTrackTag); 91 : (HotTrackTag: PHotTrackTag); 92 : (FallTrackTag: PFallTrackTag); 93 : (HideTrackTag: PHideTrackTag); 99 : (Dummy: Pointer); end; // finally the chunk definition TChunk3DS = record Tag: Word; // Type of Chunk Size: Cardinal; // Number of bytes used by Chunk Position: Cardinal; // Offset in Source file Data: TChunkData; // Memory copy of file Data Sibling: PChunk3DS; // Next Chunk in database Children: PChunk3DS; // Chunks contained within this Chunk end; //--------------------------------------------------------------------------------------------------------------------- implementation //--------------------------------------------------------------------------------------------------------------------- end.
unit osUrl; interface uses SysUtils; function UrlDecode(url: string): string; implementation function UrlDecode(url: string): string; var i: integer; decodedUrl: string; begin decodedUrl := ''; i := 1; while (i<=(length(url))) do begin if url[i]='%' then begin decodedUrl := decodedUrl + char(StrToInt('$'+url[i+1]+url[i+2])); i := i + 2; end else decodedUrl := decodedUrl + url[i]; i := i+1; end; result := decodedUrl; end; end.
unit CustomerSelect; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids, DBGridEh, DB, ComCtrls, ToolWin; type TCustomerSelectForm = class(TForm) Panel1: TPanel; CancelButton: TButton; OKButton: TButton; DBGridEh1: TDBGridEh; ToolBar1: TToolBar; ToolButton1: TToolButton; InsertButton: TToolButton; EditButton: TToolButton; DeleteButton: TToolButton; ToolButton2: TToolButton; Edit1: TEdit; CheckBox1: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CancelButtonClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure InsertButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure DBGridEh1DblClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var CustomerSelectForm: TCustomerSelectForm; implementation uses StoreDM, CustomerItem; var CloseStatus : Boolean; {$R *.dfm} procedure TCustomerSelectForm.FormCreate(Sender: TObject); begin with StoreDataModule.CustomerSelectQuery do begin Close; SQL.Clear; SQL.Add('SELECT "Customers"."CustomerID", "Customers"."CustomerName", "Customers"."PriceID", "Customers"."DelayPay"'); SQL.Add('FROM "Customers"'); SQL.Add('WHERE ("Customers"."CustomerID" <> :MainFirm AND "Customers"."CustomerID" > 0)'); SQL.Add(''); SQL.Add('ORDER BY "Customers"."CustomerName"');{} Open; end; Caption := 'Выбери меня, выбери меня...'; end; procedure TCustomerSelectForm.FormClose(Sender: TObject; var Action: TCloseAction); begin with StoreDataModule.CustomerSelectQuery do begin if CustomerSelectForm.ModalResult = mrOk then begin CurCustomerID := FieldByName('CustomerID').Value; CurCustomerName := FieldByName('CustomerName').Value; if FieldByName('Debt').IsNull then CurDebt := 0 else CurDebt := FieldByName('Debt').Value; if FieldByName('PriceID').IsNull then CurPriceID := MainPrice // Если у Клиента нет "Типа Цен", то проставляем "Тип Цены" по-умолчанию else CurPriceID := FieldByName('PriceID').Value; if FieldByName('DelayPay').IsNull then CurrentDelayPay := 0 // Если у Клиента нет "Отсрочки платежа", то проставляем "Ноль" else CurrentDelayPay := FieldByName('DelayPay').Value; end; Close; SQL.Clear; SQL.Add('SELECT "Customers"."CustomerID", "Customers"."CustomerName", "Customers"."PriceID", "Customers"."DelayPay"'); SQL.Add('FROM "Customers"'); SQL.Add('WHERE ("Customers"."CustomerID" <> :MainFirm AND "Customers"."CustomerID" > 0)'); SQL.Add(''); SQL.Add('ORDER BY "Customers"."CustomerName"');{} end; StoreDataModule.DebtQuery.Close; end; procedure TCustomerSelectForm.CancelButtonClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TCustomerSelectForm.OKButtonClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TCustomerSelectForm.CheckBox1Click(Sender: TObject); begin with StoreDataModule.CustomerSelectQuery do begin Close; if CheckBox1.Checked then begin SQL.Strings[1] := 'FROM "Customers", "Balance"'; SQL.Strings[2] := 'WHERE ("Customers"."CustomerID" <> :MainFirm AND "Customers"."CustomerID" > 0) AND ("Customers"."CustomerID" = "Balance"."CustomerID") AND ("Balance"."FirmID" = :MainFirm AND "Balance"."Debt" <> 0)'; end else begin SQL.Strings[1] := 'FROM "Customers"'; SQL.Strings[2] := 'WHERE ("Customers"."CustomerID" <> :MainFirm AND "Customers"."CustomerID" > 0)'; end; Open; end end; procedure TCustomerSelectForm.Edit1Change(Sender: TObject); var Find : String; begin Find := AnsiUpperCase(Edit1.Text); with StoreDataModule.CustomerSelectQuery do begin Close; SQL.Strings[3] := ' AND (UPPER("Customers"."CustomerName") LIKE ''%' + Find + '%'')'; Open; end; end; procedure TCustomerSelectForm.InsertButtonClick(Sender: TObject); begin if StoreDataModule.CustomerDataSet.Active = False then begin CloseStatus := True; StoreDataModule.CustomerDataSet.Open; end; StoreDataModule.CustomerDataSet.Append; CustomerItemForm := TCustomerItemForm.Create(Self); CustomerItemForm.ShowModal; if CustomerItemForm.ModalResult = mrOK then begin StoreDataModule.CustomerSelectQuery.Close; StoreDataModule.DebtQuery.Close; StoreDataModule.CustomerSelectQuery.Open; end; if CloseStatus = True then begin StoreDataModule.CustomerDataSet.Close; CloseStatus := False; end; end; procedure TCustomerSelectForm.EditButtonClick(Sender: TObject); begin if StoreDataModule.CustomerDataSet.Active = False then begin CloseStatus := True; StoreDataModule.CustomerDataSet.Open; end; StoreDataModule.CustomerDataSet.Edit; StoreDataModule.CustomerDataSet.Locate('CustomerID', StoreDataModule.CustomerSelectQuery['CustomerID'], []); CustomerItemForm := TCustomerItemForm.Create(Self); CustomerItemForm.ShowModal; if CustomerItemForm.ModalResult = mrOK then begin StoreDataModule.CustomerSelectQuery.Close; StoreDataModule.DebtQuery.Close; StoreDataModule.CustomerSelectQuery.Open; end; if CloseStatus = True then begin StoreDataModule.CustomerDataSet.Close; CloseStatus := False; end; end; procedure TCustomerSelectForm.DeleteButtonClick(Sender: TObject); var CustomerStr : String; begin if StoreDataModule.CustomerDataSet.Active = False then begin CloseStatus := True; StoreDataModule.CustomerDataSet.Open; end; StoreDataModule.CustomerDataSet.Locate('CustomerID', StoreDataModule.CustomerSelectQuery['CustomerID'], []); CustomerStr := StoreDataModule.CustomerDataSet.FieldByName('CustomerName').AsString; if Application.MessageBox(PChar('Вы действительно хотите удалить запись"' + CustomerStr + '"?'), 'Удаление записи', mb_YesNo + mb_IconQuestion + mb_DefButton2) = idYes then try StoreDataModule.CustomerDataSet.Delete; except Application.MessageBox(PChar('Запись "' + CustomerStr + '" удалять нельзя.'), 'Ошибка удаления', mb_IconStop); end; if CloseStatus = True then begin StoreDataModule.CustomerDataSet.Close; CloseStatus := False; end; StoreDataModule.CustomerSelectQuery.Close; StoreDataModule.CustomerSelectQuery.Open; end; procedure TCustomerSelectForm.DBGridEh1DblClick(Sender: TObject); begin OKButton.Click; end; procedure TCustomerSelectForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN : OKButton.Click; VK_F2 : InsertButton.Click; VK_F3 : EditButton.Click; VK_F8 : DeleteButton.Click; VK_F4 : Edit1.SetFocus; end; end; end.
unit Ntapi.nttmapi; {$MINENUMSIZE 4} interface uses Winapi.WinNt, Ntapi.ntdef; const // Transaction manager // WinNt.21983 TRANSACTIONMANAGER_QUERY_INFORMATION = $0001; TRANSACTIONMANAGER_SET_INFORMATION = $0002; TRANSACTIONMANAGER_RECOVER = $0004; TRANSACTIONMANAGER_RENAME = $0008; TRANSACTIONMANAGER_CREATE_RM = $0010; TRANSACTIONMANAGER_BIND_TRANSACTION = $0020; TRANSACTIONMANAGER_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED or $3F; TmTmAccessMapping: array [0..5] of TFlagName = ( (Value: TRANSACTIONMANAGER_QUERY_INFORMATION; Name: 'Query information'), (Value: TRANSACTIONMANAGER_SET_INFORMATION; Name: 'Set information'), (Value: TRANSACTIONMANAGER_RECOVER; Name: 'Recover'), (Value: TRANSACTIONMANAGER_RENAME; Name: 'Rename'), (Value: TRANSACTIONMANAGER_CREATE_RM; Name: 'Create resource manager'), (Value: TRANSACTIONMANAGER_BIND_TRANSACTION; Name: 'Bind transaction') ); TmTmAccessType: TAccessMaskType = ( TypeName: 'transaction manager'; FullAccess: TRANSACTIONMANAGER_ALL_ACCESS; Count: Length(TmTmAccessMapping); Mapping: PFlagNameRefs(@TmTmAccessMapping); ); // Transaction // WinNt.22018 TRANSACTION_QUERY_INFORMATION = $0001; TRANSACTION_SET_INFORMATION = $0002; TRANSACTION_ENLIST = $0004; TRANSACTION_COMMIT = $0008; TRANSACTION_ROLLBACK = $0010; TRANSACTION_PROPAGATE = $0020; TRANSACTION_RIGHT_RESERVED1 = $0040; TRANSACTION_ALL_ACCESS = STANDARD_RIGHTS_ALL or $7F; TmTxAccessMapping: array [0..5] of TFlagName = ( (Value: TRANSACTION_QUERY_INFORMATION; Name: 'Query information'), (Value: TRANSACTION_SET_INFORMATION; Name: 'Set information'), (Value: TRANSACTION_ENLIST; Name: 'Enlist'), (Value: TRANSACTION_COMMIT; Name: 'Commit'), (Value: TRANSACTION_ROLLBACK; Name: 'Rollback'), (Value: TRANSACTION_PROPAGATE; Name: 'Propagate') ); TmTxAccessType: TAccessMaskType = ( TypeName: 'transaction'; FullAccess: TRANSACTION_ALL_ACCESS; Count: Length(TmTxAccessMapping); Mapping: PFlagNameRefs(@TmTxAccessMapping); ); // ktmtypes.180 MAX_TRANSACTION_DESCRIPTION_LENGTH = 64; // Resource manager // WinNt.22067 RESOURCEMANAGER_QUERY_INFORMATION = $0001; RESOURCEMANAGER_SET_INFORMATION = $0002; RESOURCEMANAGER_RECOVER = $0004; RESOURCEMANAGER_ENLIST = $0008; RESOURCEMANAGER_GET_NOTIFICATION = $0010; RESOURCEMANAGER_REGISTER_PROTOCOL = $0020; RESOURCEMANAGER_COMPLETE_PROPAGATION = $0040; RESOURCEMANAGER_ALL_ACCESS = STANDARD_RIGHTS_ALL or $7F; TmRmAccessMapping: array [0..6] of TFlagName = ( (Value: RESOURCEMANAGER_QUERY_INFORMATION; Name: 'Query information'), (Value: RESOURCEMANAGER_SET_INFORMATION; Name: 'Set information'), (Value: RESOURCEMANAGER_RECOVER; Name: 'Recover'), (Value: RESOURCEMANAGER_ENLIST; Name: 'Enlist'), (Value: RESOURCEMANAGER_GET_NOTIFICATION; Name: 'Get notification'), (Value: RESOURCEMANAGER_REGISTER_PROTOCOL; Name: 'Register protocol'), (Value: RESOURCEMANAGER_COMPLETE_PROPAGATION; Name: 'Complete propagation') ); TmRmAccessType: TAccessMaskType = ( TypeName: 'resource manager'; FullAccess: RESOURCEMANAGER_ALL_ACCESS; Count: Length(TmRmAccessMapping); Mapping: PFlagNameRefs(@TmRmAccessMapping); ); // Enlistment // WinNt.22067 ENLISTMENT_QUERY_INFORMATION = $0001; ENLISTMENT_SET_INFORMATION = $0002; ENLISTMENT_RECOVER = $0004; ENLISTMENT_SUBORDINATE_RIGHTS = $0008; ENLISTMENT_SUPERIOR_RIGHTS = $0010; ENLISTMENT_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED or $1F; TmEnAccessMapping: array [0..4] of TFlagName = ( (Value: ENLISTMENT_QUERY_INFORMATION; Name: 'Query information'), (Value: ENLISTMENT_SET_INFORMATION; Name: 'Set information'), (Value: ENLISTMENT_RECOVER; Name: 'Recover'), (Value: ENLISTMENT_SUBORDINATE_RIGHTS; Name: 'Subordinate rights'), (Value: ENLISTMENT_SUPERIOR_RIGHTS; Name: 'Superior rights') ); TmEnAccessType: TAccessMaskType = ( TypeName: 'enlistment'; FullAccess: ENLISTMENT_ALL_ACCESS; Count: Length(TmEnAccessMapping); Mapping: PFlagNameRefs(@TmEnAccessMapping); ); type // wdm.15389 TKtmObjectType = ( KtmObjectTransaction = 0, KtmObjectTransactionManager = 1, KtmObjectResourceManager = 2, KtmObjectEnlistment = 3, KtmObjectInvalid = 4 ); // wdm.15407 TKtmObjectCursor = record LastQuery: TGuid; ObjectIdCount: Integer; ObjectIds: array [ANYSIZE_ARRAY] of TGuid; end; PKtmObjectCursor = ^TKtmObjectCursor; TTransactionInformationClass = ( TransactionBasicInformation = 0, // q: TTrasactionBasicInformation TransactionPropertiesInformation = 1, // q, s: TTransactionPropertiesInformation TransactionEnlistmentInformation = 2, // q: TTransactionEnlistmentsInformation TransactionSuperiorEnlistmentInformation = 3 // q: TTransactionEnlistmentPair ); TTransactionOutcome = ( TransactionOutcomeReserved = 0, TransactionOutcomeUndetermined = 1, TransactionOutcomeCommitted = 2, TransactionOutcomeAborted = 3 ); TTransactionState = ( TransactionStateReserved = 0, TransactionStateNormal = 1, TransactionStateIndoubt = 2, TransactionStateCommittedNotify = 3 ); TTransactionBasicInformation = record TransactionId: TGuid; State: TTransactionState; Outcome: TTransactionOutcome; end; PTransactionBasicInformation = ^TTransactionBasicInformation; TTransactionPropertiesInformation = record IsolationLevel: Cardinal; IsolationFlags: Cardinal; Timeout: TLargeInteger; Outcome: TTransactionOutcome; DescriptionLength: Cardinal; Description: array [ANYSIZE_ARRAY] of WideChar; end; PTransactionPropertiesInformation = ^TTransactionPropertiesInformation; TTransactionEnlistmentPair = record EnlistmentId: TGuid; ResourceManagerId: TGuid; end; PTransactionEnlistmentPair = ^TTransactionEnlistmentPair; TTransactionEnlistmentsInformation = record NumberOfEnlistments: Cardinal; EnlistmentPair: array [ANYSIZE_ARRAY] of TTransactionEnlistmentPair; end; PTransactionEnlistmentsInformation = ^TTransactionEnlistmentsInformation; function NtEnumerateTransactionObject(RootObjectHandle: THandle; QueryType: TKtmObjectType; ObjectCursor: PKtmObjectCursor; ObjectCursorLength: Cardinal; out ReturnLength: Cardinal): NTSTATUS; stdcall; external ntdll; function NtCreateTransaction(out TransactionHandle: THandle; DesiredAccess: TAccessMask; ObjectAttributes: PObjectAttributes; Uow: PGuid; TmHandle: THandle; CreateOptions: Cardinal; IsolationLevel: Cardinal; IsolationFlags: Cardinal; Timeout: PLargeInteger; Description: PUNICODE_STRING): NTSTATUS; stdcall; external ntdll; function NtOpenTransaction(out TransactionHandle: THandle; DesiredAccess: TAccessMask; const ObjectAttributes: TObjectAttributes; Uow: PGuid; TmHandle: THandle): NTSTATUS; stdcall; external ntdll; function NtQueryInformationTransaction(TransactionHandle: THandle; TransactionInformationClass: TTransactionInformationClass; TransactionInformation: Pointer; TransactionInformationLength: Cardinal; ReturnLength: PCardinal): NTSTATUS; stdcall; external ntdll; function NtSetInformationTransaction(TransactionHandle: THandle; TransactionInformationClass: TTransactionInformationClass; TransactionInformation: Pointer; TransactionInformationLength: Cardinal): NTSTATUS; stdcall; external ntdll; function NtCommitTransaction(TransactionHandle: THandle; Wait: Boolean): NTSTATUS; stdcall; external ntdll; function NtRollbackTransaction(TransactionHandle: THandle; Wait: Boolean): NTSTATUS; stdcall; external ntdll; implementation end.
Unit morphmath; Interface Uses Windows; Type PVector3D = ^Vector3D; Vector3D=Packed Object X:Single; Y:Single; Z:Single; Function Equals(Const B:Vector3D):Boolean; Function Dot(Const B:Vector3D):Single; Procedure Add(Const B:Vector3D); Procedure Subtract(Const B:Vector3D); Procedure Scale(Const S:Single); Procedure Multiply(Const B:Vector3D); Function Get(Index:Integer):Single; Procedure SetValue(Index:Integer; Value:Single); // Normalizes the vector Procedure Normalize; Function Length:Single; Function LengthSquared:Single; Function Distance(Const B:Vector3D):Single; Function Distance2D(Const B:Vector3D):Single; Procedure Rotate(Const Axis:Vector3D; Const Angle:Single); End; Const // Vector constants VectorZero: Vector3D = (X:0.0; Y:0.0; Z:0.0); VectorOne: Vector3D = (X:1.0; Y:1.0; Z:1.0); VectorUp: Vector3D = (X:0.0; Y:1.0; Z:0.0); Type PVector2D=^Vector2D; Vector2D=Packed Object X,Y:Single; Function Equals(Const B:Vector2D):Boolean; Procedure Rotate(Const Angle:Single); Overload; Procedure Rotate(Const Angle:Single; Const Center:Vector2D); Overload; Procedure Add(Const B:Vector2D); Procedure Subtract(Const B:Vector2D); Procedure Scale(Const S:Single);Overload; Procedure Scale(Const B:Vector2D);Overload; Procedure Project(Const V:Vector2D); Procedure Normalize; Function Length:Single; Function Distance(Const B:Vector2D):Single; Function Dot(B:Vector2D):Single; End; type PMatrix = ^Matrix; Matrix=Packed Object V:Array [0..15] Of Single; //Function GetAngles:Vector3D; procedure postMultiply(mat:Matrix); procedure Copy(mat:Matrix); Function Transform(P:Vector3D):Vector3D; Function inverseTranslateVect(var P:Vector3D):Vector3D; Function inverseRotateVect(var P:Vector3D):Vector3D; Function TranslateVect(var P:Vector3D):Vector3D; Function RotateVect(var P:Vector3D):Vector3D; Function TransformNormal(P:Vector3D):Vector3D; procedure setTranslation(x,y,z:single); Procedure Orthonormalize; Function Get(I,J:Integer):Single; procedure SetData(I, J: Integer;d:single); Function GetTranslation:Vector3D; End; Matrix3x3=Packed Object m:Array [0..8] Of Single; function MulVec(v:Vector3D):Vector3D; End; PMatrixArray=^MatrixArray; MatrixArray=Array[0..255] Of Matrix; Const MatrixIdentity:Matrix= (V:(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)); Matrix3xIdentity:Matrix3x3= (m: (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)); Type PQuaternion = ^Quaternion; Quaternion=Packed Object X:Single; Y:Single; Z:Single; W:Single; Function Equals(Const B:Quaternion):Boolean; Procedure Transform(Const M:Matrix); // Returns a normalized quaternion Procedure Normalize; function Inverse():quaternion; Procedure Add(Const B:Quaternion); Procedure Subtract(Const B:Quaternion); Function Length:Single; End; Vector4D = Quaternion; Color4F = Vector4D; Const QuaternionOne:Vector4D=(X:1.0; Y:1.0; Z:1.0; W:1.0); QuaternionZero:Vector4D=(X:0.0; Y:0.0; Z:0.0; W:1.0); // Returns a rotation matrix Function MatrixRotation(Const Rotation:Vector3D):Matrix; Overload; Function MatrixRotation(Const X,Y,Z:Single):Matrix; Overload; Function MatrixRotation(Const Axis:Vector3D; Const Angle:Single):Matrix; Overload; // Returns a translation matrix Function MatrixTranslation(Const Translation:Vector3D):Matrix;Overload; Function MatrixTranslation(Const X,Y,Z:Single):Matrix;Overload; Function MatrixTransform(Const Position,Rotation,Scale:Vector3D):Matrix; Function MatrixOrientation(Const Position,Direction,Up,Scale:Vector3D):Matrix; Function MatrixLerp(Const A,B:Matrix; Const S:Single):Matrix; // Inverts a matrix Function MatrixInverse(A:Matrix):Matrix; Function MatrixScale(Const Scale:Vector3D):Matrix;Overload; Function MatrixScale(Const X,Y,Z:Single):Matrix;Overload; // Returns a reflection matrix Function MatrixMirror(Const Source,Normal:Vector3D):Matrix; Function MatrixTranspose(Const Source:Matrix):Matrix; // Multiplys two matrices Function MatrixMultiply4x3(Const A,B:Matrix):Matrix; Function MatrixMultiply4x4(Const A,B:Matrix):Matrix; Function MatrixPerspective(FOV, AspectRatio, zNear, zFar:Single):Matrix; Function MatrixLookAt(Eye, LookAt, Roll:Vector3D):Matrix; Function MatrixOrtho(left, right, bottom, top, nearVal, farVal:Single):Matrix; Function MatrixIsometric(X,Y, Height:Single):Matrix; // Vector functions Function VectorCreate(Const X,Y,Z:Single):Vector3D; Function VectorUniform(Const N:Single):Vector3D; Function VectorMax(Const A,B:Vector3D):Vector3D; Function VectorMin(Const A,B:Vector3D):Vector3D; Function VectorAdd(Const A,B:Vector3D):Vector3D; Function VectorSubtract(Const A,B:Vector3D):Vector3D; Function VectorMultiply(Const A,B:Vector3D):Vector3D; Function VectorCross(Const A,B:Vector3D):Vector3D; // Returns the dot product between two vectors Function VectorDot(Const A,B:Vector3D):Single; // Scales a vector by S Function VectorScale(Const A:Vector3D; S:Single):Vector3D; // Reflect two vectors Function VectorReflect(Const Source,Normal:Vector3D):Vector3D; Function VectorInterpolate(Const A,B:Vector3D; Const S:Single):Vector3D; // Halve arc between unit vectors v0 and v1. Function VectorBisect(Const A,B:Vector3D):Vector3D; // Returns a triangle normal Function TriangleNormal(Const V0,V1,V2:Vector3D):Vector3D; // Quad functions Function GetTriangleHeight(H0,H1,H2:Single; X,Y:Single; Normal:PVector3D=Nil):Single; Function QuaternionCreate(Const X,Y,Z,W:Single):Quaternion;Overload; Function QuaternionCreate(Const V:Vector3D):Quaternion;Overload; Function QuaternionCreate(Const pMatrix:Matrix):Quaternion;Overload; // Creates a quaterion with specified rotation Function QuaternionRotation(Const Rotation:Vector3D):Quaternion; // Returns a matrix representing the quaternion Function QuaternionMatrix(Const q:Quaternion):Matrix; Function QuaternionToMatrix(Pos:Vector3D;q:Quaternion):Matrix; Function QuaternionRotationMatrix(Const q:Quaternion):Matrix3x3; // Slerps two quaternions Function QuaternionSlerp(A,B:Quaternion; Const T:Single):Quaternion; function RotationYawPitchRollTo(yaw:Single; pitch:Single; roll:Single):Quaternion; // Returns the conjugate of a quaternion Function QuaternionConjugate(Const Q:Quaternion):Quaternion; // Multiplies two quaternions Function QuaternionMultiply( Ql,Qr:Quaternion):Quaternion; Function QuaternionAdd(Const A,B:Quaternion):Quaternion; Function QuaternionScale(Const Q:Quaternion; Const Scale:Single):Quaternion; Function QuaternionFromBallPoints(Const arcFrom,arcTo:Vector3D):Quaternion; Procedure QuaternionToBallPoints(Var Q:Quaternion; arcFrom,arcTo:Vector3D); Function QuaternionFromAxisAngle(Const Axis:Vector3D; Const Angle:Single):Quaternion; Function QuaternionToEuler(Const Q:Quaternion):Vector3D; function makeTransform( position:Vector3d; scale:Vector3d; orientation:Quaternion):Matrix; Function VectorCreate2D(Const X,Y:Single):Vector2D; Function VectorCross2D(Const A,B:Vector2D):Single; Function VectorAdd2D(Const A,B:Vector2D):Vector2D; Function VectorSubtract2D(Const A,B:Vector2D):Vector2D; Const Epsilon = 0.00001; Rad = 0.017453292519; // Pi/180 Deg = 57.29577951308; // 180/Pi RAND_MAX = Pred(MAXINT); INV_RAND_MAX = 1.0 / (RAND_MAX + 1); Function FloatMax(Const A,B:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Function FloatMin(Const A,B:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Function RandomFloat:Single; Overload; Function RandomFloat(Const min,max:Single):Single; Overload; Function RealMod(Const n,d: Single): Single; Function SmoothStep(A,B,X:Single):Single; Function NearestPowerOfTwo(P:Cardinal):Cardinal; Function LinearInterpolate(a,b, mu:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Function CubicInterpolate(y0, y1, y2, y3, mu:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Function CatmullRomInterpolate(y0, y1, y2, y3, mu:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Function QuadraticBezierCurve(y0, y1, y2, mu:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Function CubicBezierCurve(y0, y1, y2, y3, mu:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Function InvSqrt(X:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Function Pow(X, Y:Single):Single; Implementation Uses Math; Function RealMod(Const n,d: Single): Single; Var i: integer; Begin i := trunc(n / d); result := n - d * i; End; Function IntPower(X:Single; I: Integer): Single; var Y: Integer; begin Y := Abs(I); Result := 1.0; While Y > 0 do Begin While Not Odd(Y) do Begin Y := Y Shr 1; X := X * X; End; Dec(Y); Result := Result * X; End; if I < 0.0 Then Result := 1.0 / Result; End; Function Pow(X, Y:Single):Single; Begin If Y = 0.0 Then Result := 1.0 Else if (X = 0.0) and (Y > 0.0) Then Result := 0.0 Else if (Frac(Y) = 0.0) and (Abs(Y) <= MaxInt) then Result := IntPower(X, Integer(Trunc(Y))) Else Result := Exp(Y * Ln(X)) End; Function NearestPowerOfTwo(P:Cardinal):Cardinal; Var I,N:Cardinal; Begin Result := 0; For I:=14 DownTo 2 Do Begin N:=(1 Shl I); If N<P Then Break Else Result:=N; End; End; Function LinearInterpolate(a,b, mu:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := (B * Mu) + A * (1.0 - Mu); End; Function CubicInterpolate(y0, y1, y2, y3, mu:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Var a0,a1,a2,a3,mu2:Single; Begin mu2 := Sqr(mu); a0 := y3 - y2 - y0 + y1; a1 := y0 - y1 - a0; a2 := y2 - y0; a3 := y1; Result := (a0 * mu * mu2) + (a1 * mu2) + (a2 * mu) + a3; End; Function CatmullRomInterpolate(y0, y1, y2, y3, mu:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Var a0,a1,a2,a3,mu2:Single; Begin mu2 := Sqr(mu); a0 := (-0.5 * y0) + (1.5 * y1) - (1.5 * y2) + (0.5 * y3); a1 := y0 - (2.5 * y1) + (2.0 * y2) - (0.5 * y3); a2 := (-0.5 * y0) + (0.5 * y2); a3 := y1; Result := (a0 * mu * mu2) + (a1 * mu2) + (a2 * mu) + a3; End; Function QuadraticBezierCurve(y0, y1, y2, mu:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := Sqr(1-mu) * y0 + 2 * (1-mu) * y1 + Sqr(mu) * y2; End; Function CubicBezierCurve(y0, y1, y2, y3, mu:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := (1-mu) * Sqr(1-mu) * y0 + 3 * Sqr(1-mu) * y1 + 3 * (1-mu) * Sqr(mu) * y2 + Sqr(mu) * mu * y3; End; Function FloatMax(Const A,B:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Begin If A>B Then Result:=A Else Result:=B; End; Function FloatMin(Const A,B:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Begin If A<B Then Result:=A Else Result:=B; End; Function RandomFloat:Single; Overload; Begin Result := System.Random(RAND_MAX) * INV_RAND_MAX; End; Function RandomFloat(Const min,max:Single):Single; Overload; Begin Result := Min + ((max - min) * (System.Random(RAND_MAX) * INV_RAND_MAX)); End; Function SmoothStep(A, B, X:Single):Single; Begin If (x < a) Then Result := 0.0 Else If (x >= b) Then Result := 1.0 Else Begin x := (x-a) / (b-a); Result := (x*x) * (3-2*x); End; End; {$OVERFLOWCHECKS OFF} Function InvSqrt(X:Single):Single; {$IFDEF FPC} Inline;{$ENDIF} Var I:Cardinal; xhalf:Single; Begin xhalf := 0.5*x; i := PCardinal(@x)^; // get bits for floating value i := $5f3759df - (i Shr 1); // give initial guess y0 x := PSingle(@i)^; // convert bits back to float x := X * (1.5 - xhalf*x*x); // newton step, repeating this step x := X * (1.5 - xhalf*x*x); // increases accuracy Result := X; End; Function MatrixIsometric(X,Y, Height:Single):Matrix; Begin //http://toxicdump.org/blog/view/7/Haunted-Mansion-DevBlog-_02---Oblique-vs-Isometric-perspective-and-perfect-depth-sorting //http://www.xnaresources.com/default.asp?page=Tutorial:TileEngineSeries:4 //http://www.gamedev.net/topic/226797-isometric-camera-problems/ //glRotatef(30.0, 1,0,0); //glRotatef(-45.0, 0,1,0); //glTranslatef(-x, -m_cameraheight, -z); End; Function MatrixTranspose(Const Source:Matrix):Matrix; Begin Result.V[0] := Source.V[0]; Result.V[1] := Source.V[4]; Result.V[2] := Source.V[8]; Result.V[3] := Source.V[12]; Result.V[4] := Source.V[1]; Result.V[5] := Source.V[5]; Result.V[6] := Source.V[9]; Result.V[7] := Source.V[13]; Result.V[8] := Source.V[2]; Result.V[9] := Source.V[6]; Result.V[10] := Source.V[10]; Result.V[11] := Source.V[14]; Result.V[12] := Source.V[3]; Result.V[13] := Source.V[7]; Result.V[14] := Source.V[11]; Result.V[15] := Source.V[15]; End; Function MatrixOrtho(left, right, bottom, top, nearVal, farVal:Single):Matrix; Var Tx, Ty, Tz:Single; Begin TX := -(Right + Left)/(Right - Left); TY := -(Top + Bottom)/(Top - Bottom); TZ := -(farVal + nearVal)/(farVal - nearVal); Result.V[0] := 2 / (Right - Left); Result.V[1] := 0; Result.V[2] := 0; Result.V[3] := 0; Result.V[4] := 0; Result.V[5] := 2 / (Top - Bottom); Result.V[6] := 0; Result.V[7] := 0; Result.V[8] := 0; Result.V[9] := 0; Result.V[10] := -2 / (farVal - nearVal); Result.V[11] := 0; Result.V[12] := tx; Result.V[13] := ty; Result.V[14] := tz; Result.V[15] := 1.0; // + 0.375 End; //TESTME Function Matrix.Get(I, J: Integer): Single; Begin Result := V[J*4+I]; End; procedure Matrix.SetData(I, J: Integer;d:single); Begin V[J*4+I]:=d; End; procedure Matrix.setTranslation(x,y,z:single); begin V[12] := X; V[13] := Y; V[14] := Z; end; procedure Matrix.Copy(mat:Matrix); var i : integer; begin for i := 0 to 15 do v[i] := mat.v[i]; end; Function Matrix.GetTranslation:Vector3D; Begin Result.X := V[12]; Result.Y := V[13]; Result.Z := V[14]; End; Procedure Matrix.Orthonormalize; Var x,y,z:Vector3D; Begin // It probably should be going 11, 12, 13 for x x := VectorCreate(V[0], V[1], V[2]); // And 21, 22, 23 for y. x := VectorCreate(V[4], V[5], V[6]); x.Normalize(); z := VectorCross(x, y); z.Normalize; y := VectorCross(z, x); y.Normalize; V[0] := x.X; V[1] := y.X; V[2] := z.X; V[4] := x.Y; V[5] := y.Y; V[6] := z.Y; V[8] := x.Z; V[9] := y.Z; V[10] := z.Z; End; Function Matrix.inverseTranslateVect(var P:Vector3D):Vector3D; begin p.X := P.X- V[12]; p.Y := P.Y- V[13]; p.Z := P.Z- V[14]; result:=p; end; Function Matrix.inverseRotateVect(var P:Vector3D):Vector3D; begin p.x := p.x*v[0]+p.y*v[1]+p.z*v[2]; p.y := p.x*v[4]+p.y*v[5]+p.z*v[6]; p.z := p.x*v[8]+p.y*v[9]+p.z*v[10]; Result:=p; end; Function Matrix.TranslateVect(var P:Vector3D):Vector3D; begin p.X := P.X+ V[12]; p.Y := P.Y+ V[13]; p.Z := P.Z+ V[14]; result:=p; end; Function Matrix.RotateVect(var P:Vector3D):Vector3D; begin p.x := p.x*v[0]+p.y*v[4]+p.z*v[8]; p.y := p.x*v[1]+p.y*v[5]+p.z*v[9]; p.z := p.x*v[2]+p.y*v[6]+p.z*v[10]; Result:=p; end; function Matrix3x3.MulVec(v:Vector3D):Vector3D; begin Result.x:=m[0] * v.x + m[3] * v.y + m[6] * v.z; Result.y:=m[1] * v.x + m[4] * v.y + m[7] * v.z; Result.z:=m[2] * v.x + m[5] * v.y + m[8] * v.z; end; Function Matrix.Transform(P:Vector3D):Vector3D; Begin Result.X := P.X*V[0] + P.Y*V[4] + P.Z*V[8] + V[12]; Result.Y := P.X*V[1] + P.Y*V[5] + P.Z*V[9] + V[13]; Result.Z := P.X*V[2] + P.Y*V[6] + P.Z*V[10] + V[14]; End; procedure Matrix.postMultiply(mat:Matrix); var newMat :Matrix; begin newmat.v[0] := v[0]*mat.v[0] + v[4]*mat.v[1] + v[8]*mat.v[2]; newmat.v[1] := v[1]*mat.v[0] + v[5]*mat.v[1] + v[9]*mat.v[2]; newmat.v[2] := v[2]*mat.v[0] + v[6]*mat.v[1] + v[10]*mat.v[2]; newmat.v[3] := 0; newmat.v[4] := v[0]*mat.v[4] + v[4]*mat.v[5] + v[8]*mat.v[6]; newmat.v[5] := v[1]*mat.v[4] + v[5]*mat.v[5] + v[9]*mat.v[6]; newmat.v[6] := v[2]*mat.v[4] + v[6]*mat.v[5] + v[10]*mat.v[6]; newmat.v[7] := 0; newmat.v[8] := v[0]*mat.v[8] + v[4]*mat.v[9] + v[8]*mat.v[10]; newmat.v[9] := v[1]*mat.v[8] + v[5]*mat.v[9] + v[9]*mat.v[10]; newmat.v[10] := v[2]*mat.v[8] + v[6]*mat.v[9] + v[10]*mat.v[10]; newmat.v[11] := 0; newmat.v[12] := v[0]*mat.v[12] + v[4]*mat.v[13] + v[8]*mat.v[14] + v[12]; newmat.v[13] := v[1]*mat.v[12] + v[5]*mat.v[13] + v[9]*mat.v[14] + v[13]; newmat.v[14] := v[2]*mat.v[12] + v[6]*mat.v[13] + v[10]*mat.v[14] + v[14]; newmat.v[15] := 1; Copy(newMat); end; Function Matrix.TransformNormal(P:Vector3D):Vector3D; Begin Result.X := P.X*V[0] + P.Y*V[4] + P.Z*V[8]; Result.Y := P.X*V[1] + P.Y*V[5] + P.Z*V[9]; Result.Z := P.X*V[2] + P.Y*V[6] + P.Z*V[10]; End; Function MatrixTransform(Const Position,Rotation,Scale:Vector3D):Matrix; Var CosRx,CosRy,CosRz:Single; SinRx,SinRy,SinRz:Single; Begin CosRx := Cos(Rotation.x); //Used 6x CosRy := Cos(Rotation.y); //Used 4x CosRz := Cos(Rotation.z); //Used 4x SinRx := Sin(Rotation.x); //Used 5x SinRy := Sin(Rotation.y); //Used 5x SinRz := Sin(Rotation.z); //Used 5x Result.V[0] := CosRy*CosRz*Scale.x; Result.V[1] := CosRy*SinRz*Scale.x; Result.V[2] := -SinRy*Scale.x; Result.V[3] := 0.0; Result.V[4] := (CosRz*SinRx*SinRy*Scale.y) - (CosRx*SinRz*Scale.y); Result.V[5] := (CosRx*CosRz*Scale.y) + (SinRx*SinRy*SinRz*Scale.y); Result.V[6] := CosRy*SinRx*Scale.y; Result.V[7] := 0.0; Result.V[8] := (CosRx*CosRz*SinRy*Scale.z) + (SinRx*SinRz*Scale.z); Result.V[9] := (-CosRz*SinRx*Scale.z) + (CosRx*SinRy*SinRz*Scale.z); Result.V[10] := CosRx*CosRy*Scale.z; Result.V[11] := 0.0; Result.V[12] := Position.x; Result.V[13] := Position.y; Result.V[14] := Position.z; Result.V[15] := 1.0; End; Function MatrixOrientation(Const Position,Direction,Up,Scale:Vector3D):Matrix; Var TX,TZ:Vector3D; Begin TZ := VectorCross(Direction, Up); TZ.Normalize; TX := VectorCross(Up, TZ); TX.Normalize; Result.V[0] := TX.X * Scale.X; Result.V[1] := TX.Y * Scale.X; Result.V[2] := TX.Z * Scale.X; Result.V[3] := 0.0; Result.V[4] := Up.X * Scale.y; Result.V[5] := Up.Y * Scale.y; Result.V[6] := Up.Z * Scale.Y; Result.V[7] := 0.0; Result.V[8] := TZ.X * Scale.Z; Result.V[9] := TZ.Y * Scale.Z; Result.V[10] := TZ.Z * Scale.Z; Result.V[11] := 0.0; Result.V[12] := Position.x; Result.V[13] := Position.y; Result.V[14] := Position.z; Result.V[15] := 1.0; End; Function MatrixRotation(Const Axis:Vector3D; Const Angle:Single):Matrix; Var C,S,T:Single; X,Y,Z:Single; Begin C := Cos(Angle); S := Sin(Angle); T := 1-C; X := Axis.X; Y := Axis.Y; Z := Axis.Z; Result.V[0] := T * Sqr(X) + C; Result.V[1] := (T * X * Y) - (s *Z); Result.V[2] := (T * X * Z) + (s * Y); Result.V[3] := 0.0; Result.V[4] := (t * X * Y) + (s * Z); Result.V[5] := (t * Y * Y)+ C; Result.V[6] := (T * Y * Z) - (S * X); Result.V[7] := 0.0; Result.V[8] := (T * X * Z) - (S * Y); Result.V[9] := (T * Y * Z) + (S * X); Result.V[10] := (T * Z * Z) + C; Result.V[11] := 0.0; Result.V[12] := 0.0; Result.V[13] := 0.0; Result.V[14] := 0.0; Result.V[15] := 1.0; End; Function MatrixRotation(Const Rotation:Vector3D):Matrix; Begin Result := MatrixRotation(Rotation.X, Rotation.Y, Rotation.Z); End; Function MatrixRotation(Const X,Y,Z:Single):Matrix; Var Cr,Sr,Cp,Sp,Cy,Sy,Srsp,Crsp:Single; Begin cr := Cos(X); sr := Sin(X); cp := Cos(Y); sp := Sin(Y); cy := Cos(Z); sy := Sin(Z); Result.V[0] := cp * cy; Result.V[1] := cp * sy; Result.V[2] := -sp; If Result.V[2] = -0 Then Result.V[2] := 0; Result.V[3] := 0.0; srsp := sr * sp; crsp := cr * sp; Result.V[4] := (srsp * cy) - (cr * sy); Result.V[5] := (srsp * sy) + (cr * cy); Result.V[6] := (sr * cp); Result.V[7] := 0.0; Result.V[8] := (crsp * cy) + (sr * sy); Result.V[9] := (crsp * sy) - (sr * cy); Result.V[10] := (cr * cp); Result.V[11] := 0.0; Result.V[12] := 0.0; Result.V[13] := 0.0; Result.V[14] := 0.0; Result.V[15] := 1.0; End; Function MatrixTranslation(Const Translation:Vector3D):Matrix; Begin Result := MatrixTranslation(Translation.X,Translation.Y,Translation.Z); End; Function MatrixTranslation(Const X,Y,Z:Single):Matrix; Begin Result.V[0] := 1.0; Result.V[1] := 0.0; Result.V[2] := 0.0; Result.V[3] := 0.0; Result.V[4] := 0.0; Result.V[5] := 1.0; Result.V[6] := 0.0; Result.V[7] := 0.0; Result.V[8] := 0.0; Result.V[9] := 0.0; Result.V[10] := 1.0; Result.V[11] := 0.0; Result.V[12] := X; Result.V[13] := Y; Result.V[14] := Z; Result.V[15] := 1.0; End; Function MatrixScale(Const Scale:Vector3D):Matrix; Begin Result := MatrixScale(Scale.X,Scale.Y,Scale.Z); End; Function MatrixScale(Const X,Y,Z:Single):Matrix; Begin Result.V[0] := X; Result.V[1] := 0.0; Result.V[2] := 0.0; Result.V[3] := 0.0; Result.V[4] := 0.0; Result.V[5] := Y; Result.V[6] := 0.0; Result.V[7] := 0.0; Result.V[8] := 0.0; Result.V[9] := 0.0; Result.V[10] := Z; Result.V[11] := 0.0; Result.V[12] := 0.0; Result.V[13] := 0.0; Result.V[14] := 0.0; Result.V[15] := 1.0; End; Function MatrixPerspective(FOV, aspectRatio, znear, zfar:Single):Matrix; Var left, right, bottom, top:Single; ymax, xmax:Single; temp, temp2, temp3, temp4:Single; Begin ymax := znear * Tan(FOV * 0.5 * Rad); xmax := ymax * aspectRatio; left := -xmax; right := xmax; bottom := -ymax; top := ymax; temp := znear * 2.0; temp2 := (xmax * 2.0); temp3 := (top - bottom); temp4 := 1.0 / (zfar - znear); Result.V[0] := temp / temp2; Result.V[1] := 0.0; Result.V[2] := 0.0; Result.V[3] := 0.0; Result.V[4] := 0.0; Result.V[5] := temp / temp3; Result.V[6] := 0.0; Result.V[7] := 0.0; Result.V[8] := (right + left) / temp2; Result.V[9] := (top + bottom) / temp3; Result.V[10] := (-zfar - znear) * temp4; Result.V[11] := -1.0; Result.V[12] := 0.0; Result.V[13] := 0.0; Result.V[14] := (-temp * zfar) * temp4; Result.V[15] := 0.0; End; Function MatrixLookAt(Eye, LookAt, Roll:Vector3D):Matrix; Var xaxis, yaxis, zaxis:Vector3D; Begin zaxis := VectorSubtract(Eye, lookAt); zaxis.Normalize(); xaxis := VectorCross(Roll, zaxis); xaxis.Normalize(); yaxis := VectorCross(zaxis, xaxis); Result.V[0] := xaxis.x; Result.V[1] := yaxis.x; Result.V[2] := zaxis.x; Result.V[3] := 0.0; Result.V[4] := xaxis.y; Result.V[5] := yaxis.y; Result.V[6] := zaxis.y; Result.V[7] := 0.0; Result.V[8] := xaxis.z; Result.V[9] := yaxis.z; Result.V[10] := zaxis.z; Result.V[11] := 0.0; Result.V[12] := -xaxis.dot(eye); Result.V[13] := -yaxis.dot(eye); Result.V[14] := -zaxis.dot(eye); Result.V[15] := 1.0; End; Function MatrixMirror(Const Source,Normal:Vector3D):Matrix; Var Dot:Single; Begin Dot := VectorDot(Source,Normal); Result.V[0] := 1.0 - (2.0 *Normal.X * Normal.X); Result.V[1] := - (2.0 * Normal.Y * Normal.X); Result.V[2] := - (2.0 * Normal.Z * Normal.X); Result.V[3] := 0.0; Result.V[4] := - (2.0 * Normal.X * Normal.Y); Result.V[5] := 1.0 - (2.0 * Normal.Y * Normal.Y); Result.V[6] := - (2.0 * Normal.Z * Normal.Y); Result.V[7] := 0.0; Result.V[8] := - (2.0 * Normal.X * Normal.Z); Result.V[9] := - (2.0 * Normal.Y * Normal.Z); Result.V[10] := 1.0 - (2.0 * Normal.Z * Normal.Z); Result.V[11] := 0.0; Result.V[12]:= 2.0 * Dot * Normal.X; Result.V[13]:= 2.0 * Dot * Normal.Y; Result.V[14]:= 2.0 * Dot * Normal.Z; Result.V[15]:= 1.0; End; Function MatrixGetTranslation(Const A:Matrix):Vector3D; Begin Result.X := A.V[12]; Result.Y := A.V[13]; Result.Z := A.V[14]; End; Function MatrixGetScale(Const A:Matrix):Vector3D; Begin Result.X := A.V[0]; Result.Y := A.V[5]; Result.Z := A.V[10]; End; // 4x4 matrix inverse using Gauss-Jordan algorithm with row pivoting // originally written by Nathan Reed, now released into the public domain. Function MatrixInverse(A:Matrix):Matrix; Var I:Integer; a0, a1, a2, a3, a4, a5: Single; b0, b1, b2, b3, b4, b5: Single; Det, invDet:Single; Begin a0 := A.V[ 0] * A.V[ 5] - A.V[ 1] *A.V[ 4]; a1 := A.V[ 0] * A.V[ 6] - A.V[ 2] *A.V[ 4]; a2 := A.V[ 0] * A.V[ 7] - A.V[ 3] *A.V[ 4]; a3 := A.V[ 1] * A.V[ 6] - A.V[ 2] *A.V[ 5]; a4 := A.V[ 1] * A.V[ 7] - A.V[ 3] *A.V[ 5]; a5 := A.V[ 2] * A.V[ 7] - A.V[ 3] *A.V[ 6]; b0 := A.V[ 8] * A.V[13] - A.V[ 9] *A.V[12]; b1 := A.V[ 8] * A.V[14] - A.V[10] *A.V[12]; b2 := A.V[ 8] * A.V[15] - A.V[11] *A.V[12]; b3 := A.V[ 9] * A.V[14] - A.V[10] *A.V[13]; b4 := A.V[ 9] * A.V[15] - A.V[11] *A.V[13]; b5 := A.V[10] * A.V[15] - A.V[11] *A.V[14]; Det := a0*b5 - a1*b4 + a2*b3 + a3*b2 - a4*b1 + a5*b0; If (Abs(Det) > Epsilon) Then Begin Result.V[ 0] := + A.V[ 5]*b5 - A.V[ 6]*b4 + A.V[ 7]*b3; Result.V[ 4] := - A.V[ 4]*b5 + A.V[ 6]*b2 - A.V[ 7]*b1; Result.V[ 8] := + A.V[ 4]*b4 - A.V[ 5]*b2 + A.V[ 7]*b0; Result.V[12] := - A.V[ 4]*b3 + A.V[ 5]*b1 - A.V[ 6]*b0; Result.V[ 1] := - A.V[ 1]*b5 + A.V[ 2]*b4 - A.V[ 3]*b3; Result.V[ 5] := + A.V[ 0]*b5 - A.V[ 2]*b2 + A.V[ 3]*b1; Result.V[ 9] := - A.V[ 0]*b4 + A.V[ 1]*b2 - A.V[ 3]*b0; Result.V[13] := + A.V[ 0]*b3 - A.V[ 1]*b1 + A.V[ 2]*b0; Result.V[ 2] := + A.V[13]*a5 - A.V[14]*a4 + A.V[15]*a3; Result.V[ 6] := - A.V[12]*a5 + A.V[14]*a2 - A.V[15]*a1; Result.V[10] := + A.V[12]*a4 - A.V[13]*a2 + A.V[15]*a0; Result.V[14] := - A.V[12]*a3 + A.V[13]*a1 - A.V[14]*a0; Result.V[ 3] := - A.V[ 9]*a5 + A.V[10]*a4 - A.V[11]*a3; Result.V[ 7] := + A.V[ 8]*a5 - A.V[10]*a2 + A.V[11]*a1; Result.V[11] := - A.V[ 8]*a4 + A.V[ 9]*a2 - A.V[11]*a0; Result.V[15] := + A.V[ 8]*a3 - A.V[ 9]*a1 + A.V[10]*a0; invDet := 1.0 / Det; For I:=0 To 15 Do Result.V[ I] := Result.V[ I] * invDet; End Else FillChar(Result, SizeOf(Result), 0); End; Function MatrixLerp(Const A,B:Matrix; Const S:Single):Matrix; Var I:Integer; Begin For I:=0 To 15 Do Result.V[I] := A.V[I] * S + B.V[I] * (1.0 - S); End; Function MatrixMultiply4x4(Const A,B:Matrix):Matrix; Begin Result.V[0] := A.V[0]*B.V[0] + A.V[4]*B.V[1] + A.V[8]*B.V[2] + A.V[12]*B.V[3]; Result.V[1] := A.V[1]*B.V[0] + A.V[5]*B.V[1] + A.V[9]*B.V[2] + A.V[13]*B.V[3]; Result.V[2] := A.V[2]*B.V[0] + A.V[6]*B.V[1] + A.V[10]*B.V[2] + A.V[14]*B.V[3]; Result.V[3] := A.V[3]*B.V[0] + A.V[7]*B.V[1] + A.V[11]*B.V[2] + A.V[15]*B.V[3]; Result.V[4] := A.V[0]*B.V[4] + A.V[4]*B.V[5] + A.V[8]*B.V[6] + A.V[12]*B.V[7]; Result.V[5] := A.V[1]*B.V[4] + A.V[5]*B.V[5] + A.V[9]*B.V[6] + A.V[13]*B.V[7]; Result.V[6] := A.V[2]*B.V[4] + A.V[6]*B.V[5] + A.V[10]*B.V[6] + A.V[14]*B.V[7]; Result.V[7] := A.V[3]*B.V[4] + A.V[7]*B.V[5] + A.V[11]*B.V[6] + A.V[15]*B.V[7]; Result.V[8] := A.V[0]*B.V[8] + A.V[4]*B.V[9] + A.V[8]*B.V[10] + A.V[12]*B.V[11]; Result.V[9] := A.V[1]*B.V[8] + A.V[5]*B.V[9] + A.V[9]*B.V[10] + A.V[13]*B.V[11]; Result.V[10] := A.V[2]*B.V[8] + A.V[6]*B.V[9] + A.V[10]*B.V[10] + A.V[14]*B.V[11]; Result.V[11] := A.V[3]*B.V[8] + A.V[7]*B.V[9] + A.V[11]*B.V[10] + A.V[15]*B.V[11]; Result.V[12] := A.V[0]*B.V[12] + A.V[4]*B.V[13] + A.V[8]*B.V[14] + A.V[12]*B.V[15]; Result.V[13] := A.V[1]*B.V[12] + A.V[5]*B.V[13] + A.V[9]*B.V[14] + A.V[13]*B.V[15]; Result.V[14] := A.V[2]*B.V[12] + A.V[6]*B.V[13] + A.V[10]*B.V[14] + A.V[14]*B.V[15]; Result.V[15] := A.V[3]*B.V[12] + A.V[7]*B.V[13] + A.V[11]*B.V[14] + A.V[15]*B.V[15]; End; Function MatrixMultiply4x3(Const A,B:Matrix):Matrix; Begin Result.V[0] := A.V[0]*B.V[0] + A.V[4]*B.V[1] + A.V[8]*B.V[2]; Result.V[1] := A.V[1]*B.V[0] + A.V[5]*B.V[1] + A.V[9]*B.V[2]; Result.V[2] := A.V[2]*B.V[0] + A.V[6]*B.V[1] + A.V[10]*B.V[2]; Result.V[3] := 0.0; Result.V[4] := A.V[0]*B.V[4] + A.V[4]*B.V[5] + A.V[8]*B.V[6]; Result.V[5] := A.V[1]*B.V[4] + A.V[5]*B.V[5] + A.V[9]*B.V[6]; Result.V[6] := A.V[2]*B.V[4] + A.V[6]*B.V[5] + A.V[10]*B.V[6]; Result.V[7] := 0.0; Result.V[8] := A.V[0]*B.V[8] + A.V[4]*B.V[9] + A.V[8]*B.V[10]; Result.V[9] := A.V[1]*B.V[8] + A.V[5]*B.V[9] + A.V[9]*B.V[10]; Result.V[10] := A.V[2]*B.V[8] + A.V[6]*B.V[9] + A.V[10]*B.V[10]; Result.V[11] := 0.0; Result.V[12] := A.V[0]*B.V[12] + A.V[4]*B.V[13] + A.V[8]*B.V[14] + A.V[12]; Result.V[13] := A.V[1]*B.V[12] + A.V[5]*B.V[13] + A.V[9]*B.V[14] + A.V[13]; Result.V[14] := A.V[2]*B.V[12] + A.V[6]*B.V[13] + A.V[10]*B.V[14] + A.V[14]; Result.V[15] := 1.0; End; Function Vector3D.Get(Index:Integer):Single; Begin Case Index Of 0: Result := X; 1: Result := Y; 2: Result := Z; End; End; Procedure Vector3D.SetValue(Index:Integer; Value:Single); Begin Case Index Of 0: X := Value; 1: Y := Value; 2: Z := Value; End; End; Function VectorCreate(Const X,Y,Z:Single):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Begin Result.X := X; Result.Y := Y; Result.Z := Z; End; Function VectorUniform(Const N:Single):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Begin Result.X := N; Result.Y := N; Result.Z := N; End; Function Vector3D.Equals(Const B:Vector3D):Boolean; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := (Self.X=B.X) And (Self.Y=B.Y) And(Self.Z=B.Z); End; Function VectorMax(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Begin If A.X>B.X Then Result.X:=A.X Else Result.X:=B.X; If A.Y>B.Y Then Result.Y:=A.Y Else Result.Y:=B.Y; If A.Z>B.Z Then Result.Z:=A.Z Else Result.Z:=B.Z; End; Function VectorMin(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Begin If A.X<B.X Then Result.X:=A.X Else Result.X:=B.X; If A.Y<B.Y Then Result.Y:=A.Y Else Result.Y:=B.Y; If A.Z<B.Z Then Result.Z:=A.Z Else Result.Z:=B.Z; End; Procedure Vector3D.Rotate(Const Axis:Vector3D; Const Angle:Single); {$IFDEF FPC} Inline;{$ENDIF} Var SX,SY,SZ:Single; C,S:Single; Begin C := Cos(angle); S := Sin(angle); SX := X; SY := Y; SZ := Z; X := (Axis.x*Axis.x*(1-c) + c) * Sx + (Axis.x*Axis.y*(1-c) - Axis.z*s) * Sy + (Axis.x*Axis.z*(1-c) + Axis.y*s) * Sz; Y := (Axis.y*Axis.x*(1-c) + Axis.z*s) * Sx + (Axis.y*Axis.y*(1-c) + c) * Sy + (Axis.y*Axis.z*(1-c) - Axis.x*s) * Sz; Z := (Axis.x*Axis.z*(1-c) - Axis.y*s) * Sx + (Axis.y*Axis.z*(1-c) + Axis.x*s) * Sy + (Axis.z*Axis.z*(1-c) + c) * Sz; End; {Function VectorDotRotate(Const Source:Vector3D; Const Matrix:LMatrix):Vector3D; Begin Result.x:=VectorDot(Source,MatrixGetRow(Matrix,0)); Result.y:=VectorDot(Source,MatrixGetRow(Matrix,1)); Result.z:=VectorDot(Source,MatrixGetRow(Matrix,2)); End; } Procedure Vector3D.Add(Const B:Vector3D); {$IFDEF FPC} Inline; {$ENDIF} Begin X := X + B.X; Y := Y + B.Y; Z := Z + B.Z; End; Procedure Vector3D.Subtract(Const B:Vector3D); {$IFDEF FPC} Inline;{$ENDIF} Begin X := X - B.X; Y := Y - B.Y; Z := Z - B.Z; End; Procedure Vector3D.Scale(Const S:Single); {$IFDEF FPC} Inline;{$ENDIF} Begin X := X * S; Y := Y * S; Z := Z * S; End; Procedure Vector3D.Multiply(Const B:Vector3D); {$IFDEF FPC} Inline;{$ENDIF} Begin X := X * B.X; Y := Y * B.Y; Z := Z * B.Z; End; Function Vector3D.Dot(Const B:Vector3D):Single; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := (X*B.X)+(Y*B.Y)+(Z*B.Z); End; Function VectorDot(Const A,B:Vector3D):Single; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := (A.X*B.X)+(A.Y*B.Y)+(A.Z*B.Z); End; // R = 2 * ( N dot V ) * V - V // R = V - 2 * ( N dot V ) * V Function VectorReflect(Const Source,Normal:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Var N:Single; Begin N := VectorDot(Normal,Source) * 2; Result := VectorScale(Source, N); Result := VectorSubtract(Source,Result); End; Function VectorCross(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Begin With Result Do Begin X := A.Y*B.Z - A.Z*B.Y; Y := A.Z*B.X - A.X*B.Z; Z := A.X*B.Y - A.Y*B.X; End; End; Function VectorSubtract(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Begin With Result Do Begin X:=A.X-B.X; Y:=A.Y-B.Y; Z:=A.Z-B.Z; End; End; Function VectorScale(Const A:Vector3D; S:Single):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Begin With Result Do Begin X := A.X* S; Y := A.Y* S; Z := A.Z* S; End; End; Function VectorAdd(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Begin With Result Do Begin X:=(A.X+B.X); Y:=(A.Y+B.Y); Z:=(A.Z+B.Z); End; End; Function VectorMultiply(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Begin With Result Do Begin X:=(A.X*B.X); Y:=(A.Y*B.Y); Z:=(A.Z*B.Z); End; End; Function VectorInterpolate(Const A,B:Vector3D; Const S:Single):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Begin With Result Do Begin X := (A.X*S)+(B.X*(1-S)); Y := (A.Y*S)+(B.Y*(1-S)); Z := (A.Z*S)+(B.Z*(1-S)); End; End; Function VectorBisect(Const A,B:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Var Len:Single; Begin Result := VectorAdd(A,B); Len := Result.Length; If (Len<Epsilon) Then Result := VectorZero Else Result := VectorScale(Result, 1.0 / Len); End; Function VectorNullify(Const A:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Begin If Abs(A.X)<Epsilon Then Result.X:=0 Else Result.X:=A.X; If Abs(A.Y)<Epsilon Then Result.Y:=0 Else Result.Y:=A.Y; If Abs(A.Z)<Epsilon Then Result.Z:=0 Else Result.Z:=A.Z; End; {$IFDEF SSE} {$IFDEF BENCHMARK} Procedure Vector3D.NormalizeSSE; {$ELSE} Procedure Vector3D.Normalize; {$IFDEF FPC} Inline;{$ENDIF} {$ENDIF} Asm movss xmm0, [eax+8] // read (z) shufps xmm0, xmm0, 0h // broadcast length movlps xmm0, [eax] // read(x,y) movaps xmm2, xmm0 // store a copy of the vector mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y), sqr(z)) movaps xmm1, xmm0 shufps xmm1, xmm1, 55h // xmm1 = (sqr(y), sqr(y), sqr(y)) addps xmm1, xmm0 // add both shufps xmm0, xmm0, 0AAh // xmm1 = (sqr(z), sqr(z), sqr(z)) addps xmm0, xmm1 // sum all shufps xmm0, xmm0, 0h // broadcast length xorps xmm1, xmm1 ucomiss xmm0, xmm1 // check for zero length je @@END rsqrtps xmm0, xmm0 // get reciprocal of length of vector mulps xmm2, xmm0 // normalize movlps [eax], xmm2 // store X and Y shufps xmm2, xmm2, 0AAh // xmm1 = (sqr(z), sqr(z), sqr(z)) movss [eax+8], xmm2 // store Z @@END: End; {$IFDEF BENCHMARK} Function Vector3D.LengthSSE:Single; {$ELSE} Function Vector3D.Length:Single; {$IFDEF FPC} Inline;{$ENDIF} {$ENDIF} Asm movss xmm0, [eax+8] // read (z) shufps xmm0, xmm0, 0h movlps xmm0, [eax] // read(x,y) mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y), sqr(z)) movaps xmm1, xmm0 shufps xmm1, xmm1, 55h // xmm1 = (sqr(y), sqr(y), sqr(y)) addps xmm1, xmm0 // add both shufps xmm0, xmm0, 0AAh // xmm1 = (sqr(z), sqr(z), sqr(z)) addps xmm0, xmm1 // sum all sqrtss xmm0, xmm0 // and finally, sqrt movss result, xmm0 End; {$IFDEF BENCHMARK} Function Vector3D.DistanceSSE(Const B:Vector3D):Single; {$ELSE} Function Vector3D.Distance(Const B:Vector3D):Single; {$IFDEF FPC} Inline;{$ENDIF} {$ENDIF} Asm movss xmm0, [eax+8] // read (z) shufps xmm0, xmm0, 0h movlps xmm0, [eax] // read(x,y) movss xmm1, [edx+8] // read (b.z) shufps xmm1, xmm1, 0h movlps xmm1, [edx] // read(b.x,b.y) subps xmm0, xmm1 mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y), sqr(z)) movaps xmm1, xmm0 shufps xmm1, xmm1, 55h // xmm1 = (sqr(y), sqr(y), sqr(y)) addps xmm1, xmm0 // add both shufps xmm0, xmm0, 0AAh // xmm1 = (sqr(z), sqr(z), sqr(z)) addps xmm0, xmm1 // sum all sqrtss xmm0, xmm0 // and finally, sqrt movss result, xmm0 End; {$ENDIF} {$IFDEF BENCHMARK} {$UNDEF SSE} {$ENDIF} {$IFNDEF SSE} Procedure Vector3D.Normalize; {$IFDEF FPC} Inline;{$ENDIF} Var K:Single; Begin K := Sqr(X) + Sqr(Y) + Sqr(Z); {If (K<=SingleOne) Then Exit;} K := InvSqrt(K); X := X * K; Y := Y * K; Z := Z * K; End; Function Vector3D.Length:Single; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z)); End; Function Vector3D.LengthSquared:Single; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := Sqr(X) + Sqr(Y) + Sqr(Z); End; Function Vector3D.Distance(Const B:Vector3D):Single; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := Sqrt(Sqr(Self.X-B.X) + Sqr(Self.Y-B.Y) + Sqr(Self.Z-B.Z)); End; {$ENDIF} Function Vector3D.Distance2D(Const B:Vector3D):Single; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := Sqrt(Sqr(Self.X-B.X)+Sqr(Self.Z-B.Z)); End; Function TriangleNormal(Const V0,V1,V2:Vector3D):Vector3D; {$IFDEF FPC} Inline;{$ENDIF} Var A,B:Vector3D; Begin A := VectorSubtract(V1,V0); B := VectorSubtract(V2,V0); Result := VectorCross(A,B); Result.Normalize; End; Function TriangleHeightNormal(Const V0,V1,V2:Single):Vector3D; Begin Result:=TriangleNormal(VectorCreate(0.0, V0, 0.0), VectorCreate(1.0, V1, 0.0), VectorCreate(0.0, V2, 1.0)); End; Function GetTriangleHeight(H0,H1,H2:Single; X,Y:Single; Normal:PVector3D=Nil):Single; Var D:Single; FloorNormal:Vector3D; Begin FloorNormal := TriangleHeightNormal(H0, H1, H2); D := - (FloorNormal.Y * H0); Result := - ((FloorNormal.X * X) + (FloorNormal.Z * Y) + D) / FloorNormal.Y; If Assigned(Normal) Then Normal^ := FloorNormal; End; function makeTransform( position:Vector3d; scale:Vector3d; orientation:Quaternion):Matrix; var rot3x3 :Matrix3x3; begin rot3x3:=QuaternionRotationMatrix(orientation); // Set up final matrix with scale, rotation and translation result.v[0] := scale.x * rot3x3.m[0]; result.v[4] := scale.y * rot3x3.m[3]; result.v[8] := scale.z * rot3x3.m[6]; result.v[12] := position.x; result.v[1] := scale.x * rot3x3.m[1]; result.v[5] := scale.y * rot3x3.m[4]; result.v[9] := scale.z * rot3x3.m[7]; result.v[13] := position.y; result.v[2] := scale.x * rot3x3.m[2]; result.v[6] := scale.y * rot3x3.m[5]; result.v[10] := scale.z * rot3x3.m[8]; result.v[14] := position.z; // No projection term result.v[3] := 0; result.v[7] := 0; result.v[11] := 0; result.v[15] := 1; end; Function QuaternionCreate(Const X,Y,Z,W:Single):Quaternion; Begin Result.X := X; Result.Y := Y; Result.Z := Z; Result.W := W; End; { * <code>fromAngles</code> builds a Quaternion from the Euler rotation * angles (x,y,z) aka (pitch, yaw, rall)). Note that we are applying in order: (y, z, x) aka (yaw, roll, pitch) but * we've ordered them in x, y, and z for convenience. * @see <a href="http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm">http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm</a> * * @param xAngle * the Euler pitch of rotation (in radians). (aka Attitude, often rot * around x) * @param yAngle * the Euler yaw of rotation (in radians). (aka Heading, often * rot around y) * @param zAngle * the Euler roll of rotation (in radians). (aka Bank, often * rot around z) */ } Function QuaternionCreate(Const V:Vector3D):Quaternion; var cosYXcosZ,sinYXsinZ,cosYXsinZ,sinYXcosZ,angle,sinY, sinZ, sinX, cosY, cosZ, cosX:single; Begin angle := v.z * 0.5; sinZ := sin(angle); cosZ := cos(angle); angle := v.y * 0.5; sinY := sin(angle); cosY := cos(angle); angle := v.x * 0.5; sinX := sin(angle); cosX := cos(angle); // variables used to reduce multiplication calls. cosYXcosZ := cosY * cosZ; sinYXsinZ := sinY * sinZ; cosYXsinZ := cosY * sinZ; sinYXcosZ := sinY * cosZ; result.w := (cosYXcosZ * cosX - sinYXsinZ * sinX); result.x := (cosYXcosZ * sinX + sinYXsinZ * cosX); result.y := (sinYXcosZ * cosX + cosYXsinZ * sinX); result.z := (cosYXsinZ * cosX - sinYXcosZ * sinX); // result.Normalize(); End; Function Quaternion.Length:Single; Begin Result := Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z) + Sqr(W)); End; Function Quaternion.Inverse:Quaternion; var inverseNorm,norm:Single; Begin norm := self.w * self.w + self.x * self.x + self.y * self.y + self.z * self.z; if( norm > 0.0 )then begin inverseNorm := 1.0 / norm; Result:=QuaternionCreate( self.w * inverseNorm, -self.x * inverseNorm, -self.y * inverseNorm, -self.z * inverseNorm ); end else result:= QuaternionZero; End; Function Quaternion.Equals(Const B:Quaternion):Boolean; Begin Result := (Self.X=B.X) And (Self.Y=B.Y) And(Self.Z=B.Z) And(Self.W=B.W); End; Function QuaternionRotation(Const Rotation:Vector3D):Quaternion; Var cos_z_2, cos_y_2, cos_x_2:Single; sin_z_2, sin_y_2, sin_x_2:Single; Begin cos_z_2 := Cos(0.5 * Rotation.Z); cos_y_2 := Cos(0.5 * Rotation.y); cos_x_2 := Cos(0.5 * Rotation.x); sin_z_2 := Sin(0.5 * Rotation.z); sin_y_2 := Sin(0.5 * Rotation.y); sin_x_2 := Sin(0.5 * Rotation.x); // and now compute quaternion Result.W := cos_z_2*cos_y_2*cos_x_2 + sin_z_2*sin_y_2*sin_x_2; Result.X := cos_z_2*cos_y_2*sin_x_2 - sin_z_2*sin_y_2*cos_x_2; Result.Y := cos_z_2*sin_y_2*cos_x_2 + sin_z_2*cos_y_2*sin_x_2; Result.Z := sin_z_2*cos_y_2*cos_x_2 - cos_z_2*sin_y_2*sin_x_2; Result.Normalize; End; function RotationYawPitchRollTo(yaw:Single; pitch:Single; roll:Single):Quaternion; var halfRoll,halfPitch,halfYaw,sinroll,cosroll,sinPitch,cospitch,sinyaw,cosyaw:Single; begin halfRoll := roll * 0.5; halfPitch := pitch * 0.5; halfYaw := yaw * 0.5; sinRoll := sin(halfRoll); cosRoll := cos(halfRoll); sinPitch := sin(halfPitch); cosPitch := cos(halfPitch); sinYaw := sin(halfYaw); cosYaw := cos(halfYaw); result.x := (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll); result.y := (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll); result.z := (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll); result.w := (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll); end; Function QuaternionCreate(Const pMatrix:Matrix):Quaternion; var scale,diagonal:Single; q:Quaternion; begin diagonal := pMatrix.v[0] + pMatrix.v[5] + pMatrix.v[10] + 1; scale := 0.0; q:= QuaternionCreate(0, 0, 0, 1); if(diagonal > 0.00000001) then begin // Calculate the scale of the diagonal scale := (sqrt(diagonal ) * 2); // Calculate the x, y, x and w of the quaternion through the respective equation q.x := ( pMatrix.v[9] - pMatrix.v[6] ) / scale; q.y := ( pMatrix.v[2] - pMatrix.v[8] ) / scale; q.z := ( pMatrix.v[4] - pMatrix.v[1] ) / scale; q.w := 0.25 * scale; end else begin // If the first element of the diagonal is the greatest value if (( pMatrix.v[0] > pMatrix.v[5]) and (pMatrix.v[0] > pMatrix.v[10] )) then begin // Find the scale according to the first element, and double that value scale := sqrt( 1.0 + pMatrix.v[0] - pMatrix.v[5] - pMatrix.v[10] ) * 2.0; // Calculate the x, y, x and w of the quaternion through the respective equation q.x := 0.25 * scale; q.y := (pMatrix.v[4] + pMatrix.v[1] ) / scale; q.z := (pMatrix.v[2] + pMatrix.v[8] ) / scale; q.w := (pMatrix.v[9] - pMatrix.v[6] ) / scale; end // Else if the second element of the diagonal is the greatest value else if ( pMatrix.v[5] > pMatrix.v[10] ) then begin // Find the scale according to the second element, and double that value scale := sqrt( 1.0 + pMatrix.v[5] - pMatrix.v[0] - pMatrix.v[10] ) * 2.0; // Calculate the x, y, x and w of the quaternion through the respective equation q.x := (pMatrix.v[4] + pMatrix.v[1] ) / scale; q.y := 0.25 * scale; q.z := (pMatrix.v[9] + pMatrix.v[6] ) / scale; q.w := (pMatrix.v[2] - pMatrix.v[8] ) / scale; end // Else the third element of the diagonal is the greatest value else begin // Find the scale according to the third element, and double that value scale := sqrt( 1.0 + pMatrix.v[10] - pMatrix.v[0] - pMatrix.v[5] ) * 2.0; // Calculate the x, y, x and w of the quaternion through the respective equation q.x := (pMatrix.v[2] + pMatrix.v[8] ) / scale; q.y := (pMatrix.v[9] + pMatrix.v[6] ) / scale; q.z := 0.25 * scale; q.w := (pMatrix.v[4] - pMatrix.v[1] ) / scale; end; end; Result:= q; end; Function QuaternionRotationMatrix(Const q:Quaternion):Matrix3x3; var xx,yy,zz,xy,zw,zx,yw,yz,xw:Single; begin xx := q.x * q.x; yy := q.y * q.y; zz := q.z * q.z; xy := q.x * q.y; zw := q.z * q.w; zx := q.z * q.x; yw := q.y * q.w; yz := q.y * q.z; xw := q.x * q.w; result.m[0] := 1.0 - (2.0 * (yy + zz)); result.m[1] := 2.0 * (xy + zw); result.m[2] := 2.0 * (zx - yw); result.m[3] := 2.0 * (xy - zw); result.m[4] := 1.0 - (2.0 * (zz + xx)); result.m[5] := 2.0 * (yz + xw); result.m[6] := 2.0 * (zx + yw); result.m[7] := 2.0 * (yz - xw); result.m[8] := 1.0 - (2.0 * (yy + xx)); end; Function QuaternionToMatrix(Pos:Vector3D;q:Quaternion):Matrix; Begin Q.Normalize; Result.V[0]:= 1.0 - 2.0*Q.Y*Q.Y -2.0 *Q.Z*Q.Z; Result.V[1]:= 2.0 * Q.X*Q.Y + 2.0 * Q.W*Q.Z; Result.V[2]:= 2.0 * Q.X*Q.Z - 2.0 * Q.W*Q.Y; Result.V[3] := 0; Result.V[4]:= 2.0 * Q.X*Q.Y - 2.0 * Q.W*Q.Z; Result.V[5]:= 1.0 - 2.0 * Q.X*Q.X - 2.0 * Q.Z*Q.Z; Result.V[6]:= 2.0 * Q.Y*Q.Z + 2.0 * Q.W*Q.X; Result.V[7] := 0; Result.V[8] := 2.0 * Q.X*Q.Z + 2.0 * Q.W*Q.Y; Result.V[9] := 2.0 * Q.Y*Q.Z - 2.0 * Q.W*Q.X; Result.V[10] := 1.0 - 2.0 * Q.X*Q.X - 2.0 * Q.Y*Q.Y; Result.V[11] := 0; Result.V[12] :=pos.x; Result.V[13] :=pos.y; Result.V[14] :=pos.z; Result.V[15] := 1.0; End; Function QuaternionMatrix(Const q:Quaternion):Matrix; Begin Q.Normalize; Result.V[0]:= 1.0 - 2.0*Q.Y*Q.Y -2.0 *Q.Z*Q.Z; Result.V[1]:= 2.0 * Q.X*Q.Y + 2.0 * Q.W*Q.Z; Result.V[2]:= 2.0 * Q.X*Q.Z - 2.0 * Q.W*Q.Y; Result.V[3] := 0; Result.V[4]:= 2.0 * Q.X*Q.Y - 2.0 * Q.W*Q.Z; Result.V[5]:= 1.0 - 2.0 * Q.X*Q.X - 2.0 * Q.Z*Q.Z; Result.V[6]:= 2.0 * Q.Y*Q.Z + 2.0 * Q.W*Q.X; Result.V[7] := 0; Result.V[8] := 2.0 * Q.X*Q.Z + 2.0 * Q.W*Q.Y; Result.V[9] := 2.0 * Q.Y*Q.Z - 2.0 * Q.W*Q.X; Result.V[10] := 1.0 - 2.0 * Q.X*Q.X - 2.0 * Q.Y*Q.Y; Result.V[11] := 0; Result.V[12] := 0.0; Result.V[13] := 0.0; Result.V[14] := 0.0; Result.V[15] := 1.0; End; Function QuaternionMultiply( Ql,Qr:Quaternion):Quaternion; Begin Result.W := qL.W * qR.W - qL.X * qR.X - qL.Y * qR.Y - qL.Z * qR.Z; Result.X := qL.W * qR.X + qL.X * qR.W + qL.Y * qR.Z - qL.Z * qR.Y; Result.Y := qL.W * qR.Y + qL.Y * qR.W + qL.Z * qR.X - qL.X * qR.Z; Result.Z := qL.W * qR.Z + qL.Z * qR.W + qL.X * qR.Y - qL.Y * qR.X; End; Procedure Quaternion.Normalize; Var Len:Single; Begin Len := Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z) + Sqr(W)); If (Len<=0) Then Exit; Len := 1.0 / Len; X := X * Len; Y := Y * Len; Z := Z * Len; W := W * Len; End; Function QuaternionSlerp(A,B:Quaternion; Const T:Single):Quaternion; Var Theta, Sine, Beta, Alpha:Single; Cosine:Single; Begin Cosine := a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w; Cosine := Abs(Cosine); If ((1-cosine)>Epsilon) Then Begin Theta := ArcCos(cosine); Sine := Sin(theta); Beta := Sin((1-t)*theta) / sine; Alpha := Sin(t*theta) / sine; End Else Begin Beta := (1.0 - T); Alpha := T; End; Result.X := A.X * Beta + B.X * Alpha; Result.Y := A.Y * Beta + B.Y * Alpha; Result.Z := A.Z * Beta + B.Z * Alpha; Result.W := A.W * Beta + B.W * Alpha; End; Procedure Quaternion.Add(Const B:Quaternion); Begin X := X + B.X; Y := Y + B.Y; Z := Z + B.Z; // W := W + B.W; End; Procedure Quaternion.Subtract(Const B:Quaternion); Begin X := X - B.X; Y := Y - B.Y; Z := Z - B.Z; // W := W - B.W; End; Function QuaternionAdd(Const A,B:Quaternion):Quaternion; Begin With Result Do Begin X := A.X + B.X; Y := A.Y + B.Y; Z := A.Z + B.Z; W := A.W + B.W; End; End; Function QuaternionScale(Const Q:Quaternion; Const Scale:Single):Quaternion; Begin With Result Do Begin X := Q.X * Scale; Y := Q.Y * Scale; Z := Q.Z * Scale; W := Q.W * Scale; End; End; Function QuaternionFromBallPoints(Const arcFrom,arcTo:Vector3D):Quaternion; Begin Result.X := arcFrom.Y * arcTo.Z - arcFrom.Z * arcTo.Y; Result.Y := arcFrom.Z * arcTo.X - arcFrom.X * arcTo.Z; Result.Z := arcFrom.X * arcTo.Y - arcFrom.Y * arcTo.X; Result.W := arcFrom.X * arcTo.X + arcFrom.Y * arcTo.Y + arcFrom.Z * arcTo.Z; End; Procedure QuaternionToBallPoints(Var Q:Quaternion; arcFrom,arcTo:Vector3D); Var S:Single; Begin S := Sqrt(Sqr(Q.X) + Sqr(Q.Y)); If s=0 Then arcFrom:=VectorCreate(0.0, 1.0, 0.0) Else arcFrom:=VectorCreate(-Q.Y/S, Q.X/S, 0.0); arcTo.X := (Q.W * arcFrom.X) - (Q.Z * arcFrom.Y); arcTo.Y := (Q.W * arcFrom.Y) + (Q.Z * arcFrom.X); arcTo.Z := (Q.X * arcFrom.Y) - (Q.Y * arcFrom.X); If Q.W<0.0 Then arcFrom := VectorCreate(-arcFrom.X, -arcFrom.Y, 0.0); End; Function QuaternionConjugate(Const Q:Quaternion):Quaternion; Begin Result.X := -Q.X; Result.Y := -Q.Y; Result.Z := -Q.Z; Result.W := Q.W; End; Function VectorCreate4D(Const X,Y,Z,W:Single):Quaternion; Begin Result.X := X; Result.Y := Y; Result.Z := Z; Result.W := W; End; Procedure Quaternion.Transform(Const M:Matrix); Var QX,QY,QZ,QW:Single; Begin QX := X; QY := Y; QZ := Z; QW := W; X := QX*M.V[0] + QY*M.V[4] + QZ*M.V[8] + QW*M.V[12]; Y := QX*M.V[1] + QY*M.V[5] + QZ*M.V[9] + QW*M.V[13]; Z := QX*M.V[2] + QY*M.V[6] + QZ*M.V[10] + QW*M.V[14]; W := QX*M.V[3] + QY*M.V[7] + QZ*M.V[11] + QW*M.V[15]; End; //! converts from a normalized axis - angle pair rotation to a quaternion Function QuaternionFromAxisAngle(Const Axis:Vector3D; Const Angle:Single):Quaternion; Var S:Single; Begin S := Sin(Angle/2); Result.X := Axis.X * S; Result.Y := Axis.Y * S; Result.Z := Axis.Z * S; Result.W := Cos(angle/2); End; Function sgn (a : real) : real; Begin if (a < 0) then sgn := -1 else sgn := 1; End; Function atan2 (y, x : Extended) : Extended; Begin if x > 0 then result := arctan (y/x) else if x < 0 then result := arctan (y/x) + pi else result := pi/2 * sgn (y); End; Function QuaternionToEuler(Const Q:Quaternion):Vector3D; Var sqw, sqx, sqy, sqz:Single; Begin { Result.X := Atan2(2 * q.Y * q.W - 2 * q.X * q.Z, 1 - 2* Pow(q.Y, 2) - 2*Pow(q.Z, 2) ); Result.Y := Arcsin(2*q.X*q.Y + 2*q.Z*q.W); Result.Z := Atan2(2*q.X*q.W-2*q.Y*q.Z, 1 - 2*Pow(q.X, 2) - 2*Pow(q.Z, 2) ); If (q.X*q.Y + q.Z*q.W = 0.5) Then Begin Result.X := (2 * Atan2(q.X,q.W)); Result.Z := 0; End Else If (q.X*q.Y + q.Z*q.W = -0.5) Then Begin Result.X := (-2 * Atan2(q.X, q.W)); Result.Z := 0; End;} sqx := Sqr(Q.X); sqy := Sqr(Q.Y); sqz := Sqr(Q.Z); {if (homogenous) Then euler.x = atan2f(2.f * (v.x*v.y + v.z*s), sqx - sqy - sqz + sqw); euler.y = asinf(-2.f * (v.x*v.z - v.y*s)); euler.z = atan2f(2.f * (v.y*v.z + v.x*s), -sqx - sqy + sqz + sqw); End Else } Result.x := atan2(2 * (Q.z*Q.y + Q.x*Q.W), 1 - 2*(sqx + sqy)); Result.y := arcsin(-2 * (Q.x*Q.z - Q.y*Q.W)); Result.z := atan2(2 * (Q.x*Q.y + Q.z*Q.W), 1 - 2*(sqy + sqz)); End; Function VectorCreate2D(Const X,Y:Single):Vector2D; {$IFDEF FPC} Inline;{$ENDIF} Begin Result.X := X; Result.Y := Y; End; Function VectorCross2D(Const A,B:Vector2D):Single; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := (A.X * B.Y) - (A.Y * B.X); End; Function Vector2D.Equals(Const B:Vector2D):Boolean; {$IFDEF FPC} Inline;{$ENDIF} Begin Result := (Self.X = B.X) And (Self.Y = B.Y); End; Function VectorAdd2D(Const A,B:Vector2D):Vector2D; Begin Result.X := A.X + B.X; Result.Y := A.Y + B.Y; End; Function VectorSubtract2D(Const A,B:Vector2D):Vector2D; Begin Result.X := A.X - B.X; Result.Y := A.Y - B.Y; End; Procedure Vector2D.Project(Const V:Vector2D); Var thisDotV:Single; Begin thisDotV := Self.Dot(V); Self.X := V.X * thisDotV; Self.Y := V.Y * thisDotV; End; Procedure Vector2D.Rotate(Const Angle:Single; Const Center:Vector2D); {$IFDEF FPC} Inline;{$ENDIF} Begin Self.Subtract(Center); Self.Rotate(Angle); Self.Add(Center); End; Procedure Vector2D.Rotate(Const Angle:Single); {$IFDEF FPC} Inline;{$ENDIF} Var SX,SY:Single; Sine,Cosine:Single; Begin SX := Self.X; SY := Self.Y; Sine := Sin(Angle); Cosine := Cos(Angle); X := (Sx * Cosine) - (Sy * Sine); Y := (Sx * Sine) + (Sy * Cosine); End; Procedure Vector2D.Add(Const B:Vector2D); {$IFDEF FPC} Inline;{$ENDIF} Begin X := X + B.X; Y := Y + B.Y; End; {Procedure Vector2D.AddSSE(Const B:Vector2D); Asm movlps xmm0, [self] // xmm0 = (x,y) movlps xmm1, [edx] // xmm1 = (b.x,b.y) addps xmm0, xmm1 movlps [self], xmm0 // store result End; } Procedure Vector2D.Subtract(Const B:Vector2D); {$IFDEF FPC} Inline;{$ENDIF} Begin X := X - B.X; Y := Y - B.Y; End; Procedure Vector2D.Scale(Const S:Single); {$IFDEF FPC} Inline;{$ENDIF} Begin X := X * S; Y := Y * S; End; Procedure Vector2D.Scale(Const B:Vector2D); {$IFDEF FPC} Inline;{$ENDIF} Begin X := X * B.X; Y := Y * B.Y; End; {$IFDEF SSE} {$IFDEF BENCHMARK} Function Vector2D.LengthSSE:Single;Register; {$ELSE} Function Vector2D.Length:Single;Register; {$ENDIF} Asm movlps xmm0, [eax] // xmm0 = (x,y) mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y)) movaps xmm1, xmm0 shufps xmm1, xmm1, 85 // xmm1 = (sqr(y), sqr(y)) addps xmm0, xmm1 // add both sqrtss xmm0, xmm0 // and finally, sqrt} movss result, xmm0 End; {$IFDEF BENCHMARK} Function Vector2D.DistanceSSE(Const B:Vector2D):Single;Register; {$ELSE} Function Vector2D.Distance(Const B:Vector2D):Single;Register; {$ENDIF} Asm movlps xmm0, [eax] // xmm0 = (x,y) movlps xmm1, [edx] // xmm0 = (b.x,b.y) subps xmm0, xmm1 mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y)) movaps xmm1, xmm0 shufps xmm1, xmm1, 55h // xmm1 = (sqr(y), sqr(y)) addps xmm0, xmm1 // add both sqrtss xmm1, xmm0 // and finally, sqrt movss result, xmm1 End; {$ENDIF} {$IFDEF BENCHMARK} {$UNDEF SSE} {$ENDIF} {$IFNDEF SSE} Function Vector2D.Length:Single; Begin Result := Sqrt(Sqr(X)+Sqr(Y)); End; Function Vector2D.Distance(Const B:Vector2D):Single; Begin Result := Sqrt(Sqr(Self.X-B.X)+Sqr(Self.Y-B.Y)); End; {$ENDIF} Procedure Vector2D.Normalize; Var K:Single; Begin K := Length; If (K<=1.0) Then Exit; X := X / K; Y := Y / K; End; Function Vector2D.Dot(B:Vector2D):Single; Begin Result := (Self.X * B.X) + (Self.Y * B.Y); End; End.
unit FilterRoutines; interface procedure DoConvert (const inputfile, outputfile: string; flag: Char); procedure ConvUpper; procedure ConvCapitalize; procedure ConvSymbols; implementation uses SysUtils; var FileIn, FileOut: TextFile; FileLength: LongInt; procedure DoConvert (const inputfile, outputfile: string; flag: Char); var F: file of Byte; begin // compute the input file length AssignFile (F, inputfile); Reset (F); FileLength := FileSize (F); CloseFile (F); // open the text files AssignFile (FileIn, inputfile); Reset (FileIn); AssignFile (FileOut, outputfile); Rewrite (FileOut); // conversion...} // check the input flag case Flag of 'U': ConvUpper; 'C': ConvCapitalize; 'R': ConvSymbols; end; // close the files CloseFile (FileOut); CloseFile (FileIn); end; procedure ConvUpper; var Ch: Char; Position: LongInt; begin Position := 0; while not Eof (FileIn) do begin Read (FileIn, Ch); Ch := UpCase (Ch); Write (FileOut, Ch); Inc (Position); end; end; function LowCase (C: Char): Char; begin if C in ['A'..'Z'] then LowCase := Chr (Ord (C) - Ord ('A') + Ord ('a')) else LowCase := C; end; procedure ConvCapitalize; var Ch: Char; Period: Boolean; Position: LongInt; begin Period := True; Position := 0; while not Eof (FileIn) do begin Read (FileIn, Ch); case Ch of 'A'..'Z': if Period then begin Write (FileOut, Ch); Period := False; end else begin Ch := LowCase (Ch); Write (FileOut, Ch); Period := False; end; 'a'..'z': if Period then begin Ch := UpCase (ch); Write (FileOut, Ch); Period := False; end else begin Write (FileOut, Ch); Period := False; end; '.', '?', '!': begin Period := True; Write (FileOut, Ch); end; else Write (FileOut, Ch); end; // case Inc (Position); end; // while end; procedure ConvSymbols; var Ch: Char; Position: LongInt; begin Position := 0; while not Eof (FileIn) do begin Read (FileIn, Ch); if Ch < Chr (127) then Write (FileOut, Ch); Inc (Position); end; end; end.
(** This module contains a class / interface for managing a response file for collecting the files from the IDE project for zipping into an archive. @Author David Hoyle @Version 1.0 @Date 13 Jan 2018 **) Unit ITHelper.ResponseFile; Interface {$INCLUDE 'CompilerDefinitions.inc'} Uses ToolsAPI, Classes, ITHelper.Interfaces; Type (** A class which implements tjhe ITHResponseFile interface for creating and managing a zip response file. **) TITHResponseFile = Class(TInterfacedObject, IITHResponseFile) Strict Private FProject : IOTAProject; FGlobalOps : IITHGlobalOptions; FProjectOps : IITHProjectOptions; FResponseFile : TStringList; FFileName : String; FMsgMgr : IITHMessageManager; Strict Protected // IITHResponseFile Function GetFileName : String; // General Methods Procedure BuildTargetFileName(Const strBasePath: String); Procedure CheckResponseFileAgainExclusions; Procedure CheckResponseFilesForIncludeAndRes(Const strProject, strBasePath: String); Function IsProject(Const strExtType: String): Boolean; Function ProjectOptions(Const strOptions: Array Of String): String; Procedure AddAdditionalZipFilesToResponseFile(Const strBasePath: String); Procedure AddProjectFilesToResponseFile(Const strBasePath: String); Function AddToList(Const strBasePath, strModuleName: String): Boolean; Procedure BuildResponseFile(Const strBasePath, strProject, strZIPName: String); Function CheckResExts(Const slResExts: TStringList; Const strFileName: String): Boolean; Procedure CheckSourceForInclude(Const strFileName, strInclude : String; Const slIncludeFiles: TStringList); Function FileList : String; Public Constructor Create(Const Project: IOTAProject; Const GlobalOps : IITHGlobalOptions; Const ProjectOps: IITHProjectOptions; Const MessageManager : IITHMessageManager); Destructor Destroy; Override; End; Implementation Uses {$IFDEF CODESITE} CodeSiteLogging, {$ENDIF} SysUtils, ITHelper.TestingHelperUtils, ITHelper.ProcessingForm, ITHelper.CommonFunctions, ITHelper.Types, System.StrUtils, ITHelper.PascalParsing, System.Variants; (** This method adds additional files list for the zip process to the responce file. @precon INIFile must be a valid instance of a TMemIniFile class and slRepsonse must be a valid instance of a TStringList. @postcon Adds additional files list for the zip process to the responce file. @param strBasePath as a String as a constant **) Procedure TITHResponseFile.AddAdditionalZipFilesToResponseFile(Const strBasePath: String); Var slWildcards: TStringList; iModule: Integer; Begin slWildcards := FProjectOps.AddZipFiles; For iModule := 0 To slWildcards.Count - 1 Do AddToList(strBasePath, ExpandMacro(slWildcards[iModule], FProject.FileName)); End; (** This method adds project files to the response file for zipping. @precon slRepsonse file must be a valid instance of a TStringList. Project must be a valid instance of a IOTAProject interface. @postcon Adds project files to the response file for zipping. @param strBasePath as a String as a constant **) Procedure TITHResponseFile.AddProjectFilesToResponseFile(Const strBasePath: String); Var iModule: Integer; ModuleInfo: IOTAModuleInfo; iFile: Integer; slFiles : TStringList; Begin slFiles := TStringList.Create; Try // 160 and above (Delphi 8) FProject.GetCompleteFileList(slFiles); For iFile := 0 To slFiles.Count - 1 Do AddToList(strBasePath, slFiles[iFile]); // Manually For iModule := 0 To FProject.GetModuleCount - 1 Do Begin ModuleInfo := FProject.GetModule(iModule); AddToList(strBasePath, ModuleInfo.FileName); ModuleInfo.GetAdditionalFiles(slFiles); For iFile := 0 To slFiles.Count - 1 Do AddToList(strBasePath, slFiles[iFile]); End; FProject.GetAssociatedFilesFromModule(slFiles); For iFile := 0 To FProject.ModuleFileCount - 1 Do AddToList(strBasePath, FProject.ModuleFileEditors[iFile].FileName); Finally slFiles.Free; End; End; (** This procedure adds the module name to the list of zip files after changing it to a relative path. If the file already exists in the list true is returned else false. @precon None. @postcon Adds the module name to the list of zip files after changing it to a relative path. If the file already exists in the list true is returned else false. @param strBasePath as a String as a constant @param strModuleName as a String as a constant @return a Boolean **) Function TITHResponseFile.AddToList(Const strBasePath, strModuleName: String): Boolean; Const strModelSupportPath = '\modelsupport_'; Var iIndex: Integer; strNewModuleName: String; Begin Result := False; If Pos(strModelSupportPath, Lowercase(strModuleName)) = 0 Then Begin strNewModuleName := strModuleName; If DGHPathRelativePathTo(strBasePath, strNewModuleName) Then Begin If strNewModuleName <> '' Then Begin Result := FResponseFile.Find(strNewModuleName, iIndex); FResponseFile.Add(strNewModuleName); End; End; End; End; (** This method adds files to the response file starting with project files and then project modules. @precon INIFile and slReponse should be valid instances. @postcon Adds files to the response file starting with project files and then project modules. @param strBasePath as a String as a constant @param strProject as a String as a constant @param strZIPName as a String as a constant **) Procedure TITHResponseFile.BuildResponseFile(Const strBasePath, strProject, strZIPName: String); ResourceString strBuildingFilelistFor = 'Building Filelist for %s...'; strCheckingFilelistForResources = 'Checking Filelist for Resources...'; Const //: @debug strRESExt = '.res'; strCFGExt = '.cfg'; strResponseFileExt = '.response'; Begin TfrmITHProcessing.ShowProcessing(Format(strBuildingFilelistFor, [ExtractFileName(strProject)])); //: @debug AddToList(strBasePath, FProject.FileName); //: @debug AddToList(strBasePath, ChangeFileExt(FProject.FileName, strRESExt)); AddToList(strBasePath, ChangeFileExt(FProject.FileName, strCFGExt)); BuildTargetFileName(strBasePath); AddProjectFilesToResponseFile(strBasePath); TfrmITHProcessing.ShowProcessing(strCheckingFilelistForResources); CheckResponseFilesForIncludeAndRes(strProject, strBasePath); AddAdditionalZipFilesToResponseFile(strBasePath); FFileName := ChangeFileExt(strZIPName, strResponseFileExt); CheckResponseFileAgainExclusions; Try FResponseFile.SaveToFile(FFileName); Except On E: EWriteError Do FMsgMgr.AddMsg(Format(E.Message + '(%s)', [strProject]), fnHeader, ithfFailure); End; End; (** This method builds the target file name from scratch using project options. @precon slResponse must be a valid instance of a TStringList and Project must be a valid instance of a IOTAProject interface. @postcon Builds the target file name from scratch using project options. @note This will not handle project options in INC files. @param strBasePath as a String as a constant **) Procedure TITHResponseFile.BuildTargetFileName(Const strBasePath: String); Const iExtLen = 3; strDPKExt = '*.dpk'; strBPLExt = '.bpl'; strDPRExt = '*.dpr'; strEXEExt = '.exe'; strLibraryPattern = '*library*%s*;*'; strDLLExt = '.dll'; strOutputDirOpName = 'OutputDir'; strPkgDllDirOpName = 'PkgDllDir'; strDllPrefixOpName = 'DllPrefix'; strSOPrefixOpName = 'SOPrefix'; strDllSuffixOpName = 'DllSuffix'; strSOSuffixOpName = 'SOSuffix'; strDllVersionOpName = 'DllVersion'; strSOVersionOpName = 'SOVersion'; strDPRExtChange = '.dpr'; Var strExt: String; i: Integer; strTargetName: String; sl: TStringList; iStart: Integer; iEnd: Integer; Begin //: @todo UPdate!!!!! If IsProject(strDPKExt) Then strExt := strBPLExt Else If IsProject(strDPRExt) Then Begin strExt := strEXEExt; sl := TStringList.Create; Try sl.LoadFromFile(ChangeFileExt(FProject.FileName, strDPRExtChange)); For i := 0 To sl.Count - 1 Do Begin If Like(Format(strLibraryPattern, [ChangeFileExt(ExtractFileName(FProject.FileName), '')]), sl[i]) Then strExt := strDLLExt; If Like('{$e *}*', sl[i]) Or Like('{$e'#9'*}*', sl[i]) Then // Search for alternate extension Begin iStart := Pos('{$e', Lowercase(sl[i])); iEnd := Pos('}', sl[i]); If (iStart > 0) And (iEnd > 0) And (iStart < iEnd) Then strExt := '.' + Trim(Copy(sl[i], iStart + iExtLen, iEnd - iStart - iExtLen)); End; End; Finally sl.Free; End; End; //: @todo Check that this code works in XE2 and above properly. strTargetName := ExtractFilePath(FProject.FileName) + ProjectOptions([strOutputDirOpName, strPkgDllDirOpName]) + ProjectOptions([strDllPrefixOpName, strSOPrefixOpName]) + ExtractFileName(ChangeFileExt(FProject.FileName, '')) + ProjectOptions([strDllSuffixOpName, strSOSuffixOpName]) + strExt + '.' + ProjectOptions([strDllVersionOpName, strSOVersionOpName]); strTargetName := ExpandFileName(strTargetName); AddToList(strBasePath, strTargetName); End; (** This method checks whether the extension of the given file exists in the semi-colon separated list of extension to be excluded resource warnings. If it does then it returns false. @precon None. @postcon Checks whether the extension of the given file exists in the semi-colon separated list of extension to be excluded resource warnings. If it does then it returns false. @param slResExts as a TStringList as a constant @param strFileName as a String as a constant @return a Boolean **) Function TITHResponseFile.CheckResExts(Const slResExts: TStringList; Const strFileName: String): Boolean; Var iExt: Integer; Begin Result := True; For iExt := 0 To slResExts.Count - 1 Do Result := Result And Not Like(slResExts[iExt], strFileName); End; (** This method processes the response file information removing any items that make the wildcard (LIKE) exclusions. @precon None. @postcon Processes the response file information removing any items that make the wildcard (LIKE) exclusions. **) Procedure TITHResponseFile.CheckResponseFileAgainExclusions; Var i, j: Integer; sl: TStringList; Begin sl := TStringList.Create; Try sl.Text := FProjectOps.ExcPatterns; For j := 0 To sl.Count - 1 Do For i := FResponseFile.Count - 1 DownTo 0 Do If Like(sl[j], FResponseFile[i]) Then Begin FResponseFile.Delete(i); Break; End; Finally sl.Free; End; End; (** This method searches the list of files in the response file for INCLUDE statements where additional INC and RC/RES files are requested. @precon Project must be a valid instance of a IOTAProject interface, slResponse must be a valid instance of a TStringList and INIFile must be a valid instance of a TMemINIFile class. @postcon Searches the list of files in the response file for INCLUDE statements where additional INC and RC/RES files are requested. @param strProject as a String as a Constant @param strBasePath as a String as a constant **) Procedure TITHResponseFile.CheckResponseFilesForIncludeAndRes(Const strProject, strBasePath: String); Const strINCLUDEPattern = '{$INCLUDE'; strRESOURCEPattern = '{$RESOURCE'; ResourceString strNotReferencedInProject = '%s is not referenced in the project (%s).'; strNotReferencedInProjectRes = '%s is not referenced in the project (%s). Consider using an RC ' + 'file and the form {$R resfile.res rcfile.rc}.'; Var strFileName: String; slIncludeFiles: TStringList; strExts: String; iModule: Integer; iExt: Integer; slResExts: TStringList; i: Integer; astrResExts: TDGHArrayOfString; Begin // Check Source files (*.pas) for INCLUDE & RES files. For iModule := 0 To FProject.GetModuleCount - 1 Do Begin strFileName := FProject.GetModule(iModule).FileName; TfrmITHProcessing.ProcessFileName(ExtractFileName(strFileName)); slIncludeFiles := TStringList.Create; Try CheckSourceForInclude(FProject.GetModule(iModule).FileName, '{$I', slIncludeFiles); CheckSourceForInclude(FProject.GetModule(iModule).FileName, strINCLUDEPattern, slIncludeFiles); For i := 0 To slIncludeFiles.Count - 1 Do If Not AddToList(strBasePath, slIncludeFiles[i]) Then FMsgMgr.AddMsg(Format(strNotReferencedInProject, [slIncludeFiles[i], strProject]), fnTools, ithfWarning); slIncludeFiles.Clear; CheckSourceForInclude(FProject.GetModule(iModule).FileName, '{$R', slIncludeFiles); CheckSourceForInclude(FProject.GetModule(iModule).FileName, strRESOURCEPattern, slIncludeFiles); slResExts := TStringList.Create; Try strExts := FProjectOps.ResExtExc; astrResExts := DGHSplit(strExts, ';'); For iExt := Low(astrResExts) To High(astrResExts) Do Begin If (astrResExts[iExt] <> '') And (astrResExts[iExt][1] = '.') Then astrResExts[iExt] := '*' + astrResExts[iExt]; slResExts.Add(astrResExts[iExt]); End; For i := 0 To slIncludeFiles.Count - 1 Do If Not AddToList(strBasePath, slIncludeFiles[i]) Then If CheckResExts(slResExts, slIncludeFiles[i]) Then FMsgMgr.AddMsg(Format(strNotReferencedInProjectRes, [slIncludeFiles[i], strProject]), fnTools, ithfWarning); Finally slResExts.Free; End; Finally slIncludeFiles.Free; End; End; End; (** This method searches for include / res files in source code and extracts the file name and adds it to the list of files to be included in the zip response. @precon slResponse must be a valid instance. @postcon Searches for include / res files in source code and extracts the file name and adds it to the list of files to be included in the zip response. @param strFileName as a String as a constant @param strInclude as a String as a constant @param slIncludeFiles as a TStringList as a constant **) Procedure TITHResponseFile.CheckSourceForInclude(Const strFileName, strInclude : String; Const slIncludeFiles: TStringList); (** This function returns the positions of the closing brace before the end of the line containing iOffset or the line end. If the brace is found a positive offset is returned else if the line end is found a negative offset is returned. @precon None. @postcon Returns the positions of the closing brace before the end of the line containing iOffset or the line end. If the brace is found a positive offset is returned else if the line end is found a negative offset is returned. @param strText as a String as a constant @param iOffset as an Integer as a constant @return an Integer **) Function FindClosingBrace(Const strText: String; Const iOffset: Integer): Integer; Var i: Integer; Begin Result := 0; For i := iOffset To Length(strText) Do {$IFNDEF D2009} If strText[i] In ['}', #13, #10] Then {$ELSE} If CharInSet(strText[i], ['}', #13, #10]) Then {$ENDIF} Begin If strText[i] = '}' Then Result := i Else Result := -i; Exit; End; End; //ResourceString // strExceptionPrefix = 'ITHelper: '; Var sl: TStringList; iOffset: Integer; iEnd: Integer; strIncFile: String; iPos: Integer; slTokens: TStringList; Begin sl := TStringList.Create; Try If FileExists(strFileName) Then Begin //Try sl.LoadFromFile(strFileName); iOffset := 1; While iOffset > 0 Do Begin iOffset := PosEx(strInclude, sl.Text, iOffset); If iOffset > 0 Then Begin Inc(iOffset, Length(strInclude)); {$IFNDEF D2009} If sl.Text[iOffset] In [#32, #9] Then {$ELSE} If CharInSet(sl.Text[iOffset], [#32, #9]) Then {$ENDIF} Begin iEnd := FindClosingBrace(sl.Text, iOffset); If iEnd > iOffset Then Begin slTokens := Tokenize(Copy(sl.Text, iOffset, iEnd - iOffset)); Try If slTokens.Count > 0 Then Begin strIncFile := slTokens[0]; iPos := Pos('*', strIncFile); While iPos > 0 Do Begin strIncFile := Copy(strIncFile, 1, iPos - 1) + ChangeFileExt(ExtractFileName(strFileName), '') + Copy(strIncFile, iPos + 1, Length(strIncFile)); iPos := Pos('*', strIncFile); End; strIncFile := StringReplace(strIncFile, '''', '', [rfReplaceAll]); If ExtractFilePath(strIncFile) = '' Then strIncFile := ExtractFilePath(strFileName) + strIncFile; strIncFile := ExpandFileName(strIncFile); If FileExists(strIncFile) Then slIncludeFiles.Add(strIncFile); End; Finally slTokens.Free; End; iOffset := iEnd + 1; End Else iOffset := Abs(iEnd) + 1; End; End; End; //Except // On E: Exception Do // FMsgMgr.AddMsg(strExceptionPrefix + E.Message, fnHeader, ithfFailure); //End; End; Finally sl.Free; End; End; (** A constructor for the TITHResponseFile class. @precon None. @postcon Stores interface references for later use and creates a string list for the response file. @param Project as an IOTAProject as a constant @param GlobalOps as an IITHGlobalOptions as a constant @param ProjectOps as an IITHProjectOptions as a constant @param MessageManager as an IITHMessageManager as a constant **) Constructor TITHResponseFile.Create(Const Project: IOTAProject; Const GlobalOps : IITHGlobalOptions; Const ProjectOps: IITHProjectOptions; Const MessageManager : IITHMessageManager); Begin FProject := Project; FGlobalOps := GlobalOps; FProjectOps := ProjectOps; FMsgMgr := MessageManager; FResponseFile := TStringList.Create; FResponseFile.Duplicates := dupIgnore; FResponseFile.Sorted := True; End; (** A destructor for the TITHResponseFile class. @precon None. @postcon Deletes the response file if found and then frees the memory used by the string list. **) Destructor TITHResponseFile.Destroy; Begin If FileExists(FFileName) Then DeleteFile(FFileName); FResponseFile.Free; Inherited Destroy; End; (** This method expands the list of files to include as a space separated list of double quoted files. @precon slResponseFile must be a valid instance of a string list. @postcon Returns a list of files to include as a space separated list of double quoted files. @return a String **) Function TITHResponseFile.FileList : String; Var i: Integer; Begin Result := ''; For i := 0 To FResponseFile.Count - 1 Do Result := Result + Format('"%s" ', [FResponseFile[i]]); End; (** This is a getter method for the FileName property. @precon None. @postcon Returns the filename of the response file. @return a String **) Function TITHResponseFile.GetFileName: String; Begin Result := FFileName; End; (** This method searches the projects module files in search of the given file extension pattern. @precon Project must be a valid instance of a IOTAProject interface. @postcon Returns return if the file extension pattern was found in the module files. @param strExtType as a String as a constant @return a Boolean **) Function TITHResponseFile.IsProject(Const strExtType: String): Boolean; Var i: Integer; Begin Result := Like(strExtType, FProject.FileName); For i := 0 To FProject.ModuleFileCount - 1 Do Result := Result Or Like(strExtType, FProject.ModuleFileEditors[i].FileName); End; (** This method returns the first non-null occurance of the list of project option values. @precon Project must be a valid instance of a IOTAProject interface. @postcon Returns the first non-null occurance of the list of project option values. @param strOptions as an Array Of String as a constant @return a String **) Function TITHResponseFile.ProjectOptions(Const strOptions: Array Of String): String; Var i: Integer; varValue: Variant; Begin Result := ''; For i := Low(strOptions) To High(strOptions) Do Begin varValue := FProject.ProjectOptions.Values[strOptions[i]]; If VarType(varValue) And varString > 0 Then Result := varValue; If Result <> '' Then Break; End; End; End.
unit UnMensagemView; interface uses // VCL Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ImgList, System.ImageList, // JEDI JvExControls, JvButton, JvTransparentButton; type TMensagemView = class(TForm) pnlDesktop: TPanel; pnlTitle: TPanel; btnFechar: TJvTransparentButton; pnlCaption: TPanel; lblMensagem: TLabel; pnlFooter: TPanel; btnSim: TPanel; btnNao: TPanel; Imagem: TImage; Imagens: TImageList; procedure btnFecharClick(Sender: TObject); procedure btnSimClick(Sender: TObject); procedure btnNaoClick(Sender: TObject); protected function ShowModalDimmed(Form: TForm; Centered: Boolean = true): TModalResult; public function ExibirConfirmacao: Integer; function ExibirMensagem: Integer; function ExibirMensagemDeErro: Integer; function Legenda(const Legenda: string): TMensagemView; function LegendaBotaoNao(const LegendaBotaoNao: string): TMensagemView; function LegendaBotaoSim(const LegendaBotaoSim: string): TMensagemView; function Mensagem(const Mensagem: string): TMensagemView; end; implementation {$R *.dfm} { TMensagemView } function TMensagemView.ExibirMensagem: Integer; begin Result := Self.ShowModalDimmed(Self, True); end; function TMensagemView.Legenda(const Legenda: string): TMensagemView; begin Self.pnlCaption.Caption := Legenda; Result := Self; end; function TMensagemView.Mensagem(const Mensagem: string): TMensagemView; begin Self.lblMensagem.Caption := Mensagem; Result := Self; end; function TMensagemView.ShowModalDimmed(Form: TForm; Centered: Boolean = true): TModalResult; var Back: TForm; begin Back := TForm.Create(nil); try Back.Position := poDesigned; Back.BorderStyle := bsNone; Back.AlphaBlend := true; Back.AlphaBlendValue := 192; Back.Color := clBlack; Back.SetBounds(0, 0, Screen.Width, Screen.Height); Back.Show; if Centered then begin Form.Left := (Back.ClientWidth - Form.Width) div 2; Form.Top := (Back.ClientHeight - Form.Height) div 2; end; Result := Form.ShowModal; finally Back.Free; end; end; procedure TMensagemView.btnFecharClick(Sender: TObject); begin Self.ModalResult := mrCancel; end; function TMensagemView.LegendaBotaoNao( const LegendaBotaoNao: string): TMensagemView; begin Self.btnNao.Caption := LegendaBotaoNao; Result := Self; end; function TMensagemView.LegendaBotaoSim( const LegendaBotaoSim: string): TMensagemView; begin Self.btnSim.Caption := LegendaBotaoSim; Result := Self; end; function TMensagemView.ExibirConfirmacao: Integer; begin Self.Imagem.Picture.Bitmap := nil; Self.Imagens.GetBitmap(1, Self.Imagem.Picture.Bitmap); Self.Imagem.Visible := True; Self.btnSim.Visible := True; Self.btnNao.Visible := True; Result := Self.ShowModalDimmed(Self, True); end; function TMensagemView.ExibirMensagemDeErro: Integer; begin Self.Imagem.Picture.Bitmap := nil;; Self.Imagens.GetBitmap(0, Self.Imagem.Picture.Bitmap); Self.Imagem.Visible := True; Result := Self.ShowModalDimmed(Self, True); end; procedure TMensagemView.btnSimClick(Sender: TObject); begin Self.ModalResult := mrOk; end; procedure TMensagemView.btnNaoClick(Sender: TObject); begin Self.ModalResult := mrCancel; end; end.
{ @html(<b>) Data Server Components @html(</b>) - Copyright (c) Danijel Tkalcec @html(<br><br>) This unit implements a set of Server-side Data components. @Link(TRtcDataServer) implements a wrapper for all Request/Response based server-side connection components. By linking one or more @Link(TRtcDataServerLink) components, which are linked to one or more @Link(TRtcDataProvider) components, you add functionality to your server for specific Request handlers. @html(<br>) @Link(TRtcHttpServer) implements a HTTP-based TCP/IP server connection with uses a HTTP connection provider, so you can compile your DataProvider/ServerModule/Function components into a stand-alone HTTP server executable. } unit rtcDataSrv; {$INCLUDE rtcDefs.inc} interface // When "UseGUIDs" is defined, CoCreateGUID() API function is used to create Session IDs. {.$DEFINE UseGUIDs} uses rtcTrashcan, Classes, {$IFDEF useGUIDs} Windows, ComObj, ActiveX, {$ENDIF} rtcLog, rtcInfo, rtcConn, rtcThrPool; var { Default Session Live Time (in seconds). @html(<br><br>) Before a session defines its KeepAliveTime, the session will live for RTC_SESSION_TIMEOUT seconds after each call. } RTC_SESSION_TIMEOUT:integer=60; {$IFNDEF UseGUIDs} const // @exclude RTC_SESSIONID_LENGTH=28; {$ENDIF} type { @abstract(Components used in DataServer to implement server's functionality) } TRtcServerComponent=class(TRtcComponent) protected // @exclude function GetOrder: integer; virtual; abstract; end; // @exclude TRtcServerComponentList = class private FList:TList; public constructor Create; destructor Destroy; override; procedure Add(Value:TRtcServerComponent); procedure Remove(Value:TRtcServerComponent); procedure RemoveAll; function Count:integer; function Get(index:integer):TRtcServerComponent; end; TRtcAbsDataServerLink = class; // @exclude TRtcDataServerLinkList = class(TRtcServerComponentList) public function GetLink(index:integer):TRtcAbsDataServerLink; end; { @abstract(Server Session information) } TRtcServerSession=class(TRtcSession) private FLastUsed, FExpireTime:TDateTime; FFinalExpire:TDateTime; FKeepAlive:integer; protected // @exclude class function Find(const _ID:string; const _PeerAddr,_ForwardedFor:string):TRtcServerSession; // @exclude class function Have(const _ID:string; const _PeerAddr,_ForwardedFor:string):boolean; // @exclude class function Open(_LockType:TRtcSessionLockType; const _PeerAddr,_ForwardedFor:string):TRtcServerSession; // @exclude class function CloseID(const _ID:string; const _PeerAddr,_ForwardedFor:string; _Event:TRtcSimpleEvent):boolean; // @exclude procedure SetFinalExpire(const _Value:TDateTime); // @exclude procedure SetKeepAlive(const _Value:integer); // @exclude procedure LockSessionID; // @exclude procedure UnlockSession(_Event:TRtcSimpleEvent); // @exclude procedure UnLock(_Event:TRtcSimpleEvent); // @exclude function DenyAccess(const _PeerAddr,_ForwardedFor:string):boolean; public // Close session: This is same as setting "FinalExpire" to "Now". procedure Close; // Session Last used (updated after each FindSession call) property LastUsed:TDateTime read FLastUsed; // Number of seconds this session will be kept alive after each usage (renew "ExpireTime"). property KeepAlive:integer read FKeepAlive write SetKeepAlive; { Time when Session will Expire. It is auto-maintained, using the LiveTime and FinalExpire values. } property ExpireTime:TDateTime read FExpireTime; // If not zero, defines the Time and Date when this session will Expire for good. property FinalExpire:TDateTime read FFinalExpire write SetFinalExpire; end; { @Abstract(Universal Data Server Connection component) By using methods provided by this DataProvider component, you ensure that your code will be compatible with different connection providers, which makes it possible to write your code once and use it to compile it for different servers. @html(<br>) By using methods, events and properties available from TRtcDataServer, you can easily respond to requests by sending an appropriate result which will be readable by the connected client, be it a standard Web Browser or any application written by using the @Link(TRtcDataClient) connection component. @Link(TRtcDataServer) also makes sure that you receive requests one by one and get the chance to answer them one-by-one, even if the client side sends all the requests at once (as one big request list), so you can relax and process all incomming requests, without worrying about overlapping your responses for different requests. @html(<br><br>) Component which calls 'Accept' will gain complete control over the connection, until a complete response is sent out (or connection is closed). After the response is done, DataServer again takes over and waits for the next request, then the process repeats itself, until all requests have been processed or the connection has been closed. Properties to check first: @html(<br>) @Link(TRtcConnection.ServerAddr) - Local Address to bind the server to (leave empty for ALL) @html(<br>) @Link(TRtcConnection.ServerPort) - Port to listen on and wait for connections @html(<br><br>) Methods to check first: @html(<br>) @Link(TRtcServer.Listen) - Start server @html(<br>) @Link(TRtcDataServer.Accept), @Link(TRtcDataServer.Request), @Link(TRtcConnection.Read) - Read and Accept client Request @html(<br>) @Link(TRtcDataServer.WriteHeader), @Link(TRtcConnection.Write) - Write result to client @html(<br>) @Link(TRtcConnection.Disconnect) - Disconnect client @html(<br>) @Link(TRtcServer.StopListen) - Stop server @html(<br><br>) Events to check first: @html(<br>) @Link(TRtcServer.OnListenStart) - Server started @html(<br>) @Link(TRtcConnection.OnConnecting) - new Client connecting @html(<br>) @Link(TRtcDataServer.OnRequestNotAccepted) - Request has been received but not accepted by any DataProvider component. @html(<br>) @Link(TRtcConnection.OnDataSent) - Data sent to client (buffer now empty) @html(<br>) @Link(TRtcConnection.OnDisconnecting) - one Client disconnecting @html(<br>) @Link(TRtcServer.OnListenStop) - Server stopped @html(<br><br>) Check @Link(TRtcServer) and @Link(TRtcConnection) for more info. } TRtcDataServer = class(TRtcServer) private FOnRequestAccepted:TRtcNotifyEvent; FOnRequestNotAccepted:TRtcNotifyEvent; FOnResponseDone:TRtcNotifyEvent; FOnSessionOpen:TRtcNotifyEvent; FOnSessionClose:TRtcNotifyEvent; FSession:TRtcServerSession; FActiveLink:TRtcAbsDataServerLink; FDataServerLinks:TRtcDataServerLinkList; FDataServerLinks_Owner:boolean; FMyRequest, FRequest:TRtcServerRequest; FMyResponse, FResponse:TRtcServerResponse; protected // @exclude procedure CopyFrom(Dup: TRtcServer); override; // @exclude procedure AddDataServerLink(Value:TRtcAbsDataServerLink); // @exclude procedure RemoveDataServerLink(Value:TRtcAbsDataServerLink); // @exclude procedure RemoveAllDataServerLinks; // @exclude procedure CallSessionOpen; // @exclude procedure CallSessionClose(Sender:TObject); // @exclude procedure CallListenStart; override; // @exclude procedure CallListenStop; override; // @exclude procedure CallDataReceived; override; // @exclude procedure CallDataOut; override; // @exclude procedure CallDataIn; override; // @exclude procedure CallDataSent; override; // @exclude procedure CallReadyToSend; override; // @exclude procedure CallDisconnect; override; // @exclude procedure CallLastWrite; override; // @exclude procedure SetRequest(const Value: TRtcServerRequest); virtual; // @exclude procedure SetResponse(const Value: TRtcServerResponse); virtual; { @exclude } procedure InitSession; { **************************************************** } { NEW METHODS TO BE IMPLEMENTED BY THE CONNECTION COMPONENT } public { Flush all buffered data. @html(<br>) When using 'Write' without calling 'WriteHeader' before, all data prepared by calling 'Write' will be buffered until your event returns to its caller (automatically upon your event completion) or when you first call 'Flush'. Flush will check if Response.ContentLength is set and if not, will set the content length to the number of bytes buffered. @html(<br>) Flush does nothing if WriteHeader was called for this response. @exclude} procedure Flush; virtual; abstract; // You can call WriteHeader to send the Response header out. procedure WriteHeader(SendNow:boolean=True); overload; virtual; abstract; { You can call WriteHeader with empty 'HeaderText' parameter to tell the component that you do not want any HTTP header to be sent. } procedure WriteHeader(const HeaderText: string; SendNow:boolean=True); overload; virtual; abstract; { **************************************************** } // @exclude constructor Create(AOwner: TComponent); override; // @exclude destructor Destroy; override; // @exclude class function New:TRtcDataServer; // @exclude procedure CallRequestAccepted; virtual; // @exclude procedure CallRequestNotAccepted; virtual; // @exclude procedure CallResponseDone; virtual; { Used by DataServerLink components to tell DataServer that they are currently checking the request. Only needs to be called from OnCheckRequest, before the Request has been accepted. Once the request is accepted, ActiveDataServerLink will be used to process all future Data-related events, until the request has been processed or connection closed. @exclude } procedure SetActiveLink(Link:TRtcAbsDataServerLink); { Request handler has to call Accept before it starts processing the request, so that all further events remain mapped to the active event handlers and don't switch before a reply has been sent. } procedure Accept; { Find an existing Session with this ID. If Session with this ID does not exist, or session has expired or session is currently locked, returns FALSE. Otherwise, prepares the Session variable for use and returns TRUE. } function FindSession(const ID:string):boolean; { If there is a session with this ID, returns TRUE, even if that session is locked. } function HaveSession(const ID:string):boolean; { If you do not need the Session anymore and do not want to keep the session locked until request completes, you can release the Session Lock by calling "UnLockSession". After this call, you will no longer have access to the Session object, until you lock it again using FindSession. } procedure UnLockSession; { Create a new Session, with a new and unique Session ID. } procedure OpenSession(LockType:TRtcSessionLockType=sesFwdLock); { If there is a session with this ID, returns TRUE and closes the session. } function CloseSession(const ID:string):boolean; { Total number of open Sessions } function TotalSessionsCount:cardinal; { Total number of Sessions currently locked. A session is locked after a call to FindSession() and unlocked after the Event is done executing. } function TotalSessionsLocked:cardinal; { Total number of Sessions currently unlocked. A session is locked after a call to FindSession() and unlocked after the Event is done executing. } function TotalSessionsUnlocked:cardinal; { Current Request's Session info. @html(<br>) Before you can access the Session for the Request, you have to find the appropriate Session by using the FindSession function or create a new session by calling the OpenSession method. } property Session:TRtcServerSession read FSession; { Access to current request information. Use Request property to read the request information received. Here is all the info that was available in request header. To read request's body, use the Read function. } property Request:TRtcServerRequest read FRequest write SetRequest; { Access to current response information. Use Response property to prepare the response header. Here you can set all header variables and parameters. If there is no content body to send out (only header), you will at least have to call 'WriteHeader', or 'Write' without parameters once. } property Response:TRtcServerResponse read FResponse write SetResponse; published { Called after a new request has been accepted. You can use this event handler to create a DataTunel and assign it to Tunel, in case the request has to be tunelled. } property OnRequestAccepted:TRtcNotifyEvent read FOnRequestAccepted write FOnRequestAccepted; { Called after a new request has been received, but NOT ACCEPTED. You can use this event handler to respond to requests with no DataProvider. } property OnRequestNotAccepted:TRtcNotifyEvent read FOnRequestNotAccepted write FOnRequestNotAccepted; { Called after a processed response was Done sending data out. } property OnResponseDone:TRtcNotifyEvent read FOnResponseDone write FOnResponseDone; { Called after a new session has been opened. You can use the Session property from this event to get session ID. } property OnSessionOpen:TRtcNotifyEvent read FOnSessionOpen write FOnSessionOpen; { Called before an old session has been closed. You can use the Session property from this event to get Session ID. } property OnSessionClose:TRtcNotifyEvent read FOnSessionClose write FOnSessionClose; { This event will be triggered every time a chunk of your data prepared for sending has just been sent out. To know exactly how much of it is on the way, use the @Link(TRtcConnection.DataOut) property. @html(<br><br>) NOTE: Even though data has been sent out, it doesn't mean that the other side already received it. It could also be that connection will break before this package reaches the other end. } property OnDataOut; { This event will be triggered every time a chunk of data has just come in (received). To know exactly how much of it has just arrived, use the @Link(TRtcConnection.DataIn) property. } property OnDataIn; end; TRtcDataServerLink=class; { @abstract(DataServer Link wrapper) } TRtcAbsDataServerLink=class(TRtcServerComponent) private FServer: TRtcDataServer; FLink: TRtcDataServerLink; FOrder: integer; protected // @exclude function CheckLink(Value:TRtcAbsDataServerLink):boolean; virtual; // @exclude procedure RemoveLink(Value:TRtcAbsDataServerLink); virtual; // @exclude procedure RemoveServer(Value:TRtcDataServer); virtual; // @exclude function GetServer: TRtcDataServer; virtual; // @exclude procedure SetServer(const Value: TRtcDataServer); virtual; // @exclude function GetLink: TRtcDataServerLink; virtual; // @exclude procedure SetLink(const Value: TRtcDataServerLink); virtual; // @exclude function GetOrder: integer; override; // @exclude procedure SetOrder(const Value: integer); virtual; // @exclude procedure Call_SessionOpen(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_SessionClose(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_ListenStart(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_ListenStop(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_CheckRequest(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_RequestAccepted(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_ResponseDone(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_DataReceived(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_DataOut(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_DataIn(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_DataSent(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_ReadyToSend(Sender:TRtcConnection); virtual; abstract; // @exclude procedure Call_Disconnect(Sender:TRtcConnection); virtual; abstract; public // @exclude constructor Create(AOwner:TComponent); override; // @exclude destructor Destroy; override; published { You can link your components (one or more) to a DataServerLink component by assigning your @Link(TRtcDataServerLink) component to this Link property. Doing this, you only have to set the Server property for the master DataServerLink component and don't need to do it for every single DataSource component. } property Link:TRtcDataServerLink read GetLink write SetLink; { You can also link your components (one or more) directly to your DataServer connection component by assigning your @Link(TRtcDataServer) connection component to this Server property. This is useful if you have some complex functionality implemented in a single DataSource/DataServerLink component and don't need to drag the component through another DataServerLink component to get to your DataServer. } property Server:TRtcDataServer read GetServer write SetServer; { This is the Order in which the components will be asked to process a request. The smaller this Order number, the sooner a component will be asked to process a request, compared to other components connected to the DataServer at the same level. Since we could have more levels (more DataServerLink components connected to each other), Order only defines the priority at the same level. @html(<br><br>) For example, if DataSourceA has Order=50 and DataServerLinkB has Order=60, when both components are assigned to the same parent DataServerLink or directly to the DataServer, DataSourceA will receive requests for checking before any component assigned to DataServerLinkB, no matter which Order the components assigned to DataServerLinkB have. This is because the Order property only defines the order in the list of components assigned to the same parent component (DataServerLink or DataSource). @html(<br><br>) To make this simpler, just think of this Order as you would of TabOrder in a Form, where DataServer is the Form, DataServerLink are the Panels and DataSource are edit controls. TabOrder is defined for each control inside its parent (TEdit inside TPanel, child TPanel inside parent TPanel or master TPanel directly on the TForm). @html(<br><br>) Order is especially important for components which could handle same requests, like the PHP source handler and File source handler. If FileSource handler would have lower order number than the PHPSource handler, then the PHP soruce handler would never be executed, because all PHP files would be simply sent out in their source code form by the File Source handler. This is why the File Source handler has to have order number bigger that the PHPSource handler and (preferably) be connected to the same component (DataServerLink or DataServer). } property CheckOrder:integer read GetOrder write SetOrder default 0; end; { @abstract(DataServer Link, used to group Data Providers) You can use TRtcDataServerLink components to group several related @Link(TRtcDataProvider) components. Simply set this component as the Link property for all your RtcDataSource components, so that you don't have to set the Server property for every single TRtcDataProvider component separately. This is useful especially when the component is used in a datamodule or a form without dataserver and you need to link all the components to a DataServer which is on another datamodule or form. @html(<br><br>) Check @Link(TRtcAbsDataServerLink) for more info. } TRtcDataServerLink=class(TRtcAbsDataServerLink) private FOnListenStart:TRtcNotifyEvent; FOnListenStop:TRtcNotifyEvent; FOnRequestAccepted:TRtcNotifyEvent; FOnResponseDone:TRtcNotifyEvent; FOnDisconnect:TRtcNotifyEvent; FOnSessionOpen:TRtcNotifyEvent; FOnSessionClose:TRtcNotifyEvent; protected // @exclude FDataServerLinks:TRtcDataServerLinkList; { Other Call_ methods are not implemented here, since only CheckRequest event will be called on the Link, while all the other events are being called directly on the AbsDataServerLink component which implements them (for example, TRtcDataProvider). @exclude } procedure Call_CheckRequest(Sender:TRtcConnection); override; // @exclude procedure Call_DataReceived(Sender:TRtcConnection); override; // @exclude procedure Call_DataOut(Sender:TRtcConnection); override; // @exclude procedure Call_DataIn(Sender:TRtcConnection); override; // @exclude procedure Call_DataSent(Sender:TRtcConnection); override; // @exclude procedure Call_ReadyToSend(Sender:TRtcConnection); override; // @exclude procedure AddChildLink(Value:TRtcAbsDataServerLink); // @exclude procedure RemoveChildLink(Value:TRtcAbsDataServerLink); // @exclude procedure RemoveAllChildLinks; public // @exclude constructor Create(AOwner:TComponent); override; // @exclude destructor Destroy; override; { ListenStart and ListenStop methods are used for component initialization on server start and deinitialization on server stop. @exclude } procedure Call_ListenStart(Sender:TRtcConnection); override; // @exclude procedure Call_ListenStop(Sender:TRtcConnection); override; { Accepted can be used to prepare the Request after it has been accepted. @exclude } procedure Call_RequestAccepted(Sender:TRtcConnection); override; { ResponseDone can be used to complete thingsprepared with RequestAccepted. @exclude } procedure Call_ResponseDone(Sender:TRtcConnection); override; { Disconnect can be used for request deinitialization. @exclude } procedure Call_Disconnect(Sender:TRtcConnection); override; { New Session Open. @exclude } procedure Call_SessionOpen(Sender:TRtcConnection); override; { Existing Session Closing. @exclude } procedure Call_SessionClose(Sender:TRtcConnection); override; published { Event to be triggered when the Server starts listening on the connection. You can use this event for component initialization. } property OnListenStart:TRtcNotifyEvent read FOnListenStart write FOnListenStart; { Event to be triggered when the Server stops listening on the connection. You can use this event for component deinitialization. } property OnListenStop:TRtcNotifyEvent read FOnListenStop write FOnListenStop; { Event to be triggered when a child DataProvider component accepts the Request. You can use this event for request initialization. For example, you could create a DataTunel and assign it to Tunel, to have reuqest data tunneled. } property OnRequestAccepted:TRtcNotifyEvent read FOnRequestAccepted write FOnRequestAccepted; { Event to be triggered when a response to server has been sent (Response.Done) } property OnResponseDone:TRtcNotifyEvent read FOnResponseDone write FOnResponseDone; { Event to be triggered when connection gets lost after a request was accepted. You can use this event for component deinitialization. } property OnDisconnect:TRtcNotifyEvent read FOnDisconnect write FOnDisconnect; { Event to be triggered after new Session was opened. } property OnSessionOpen:TRtcNotifyEvent read FOnSessionOpen write FOnSessionOpen; { Event to be triggered before existing Session closes. } property OnSessionClose:TRtcNotifyEvent read FOnSessionClose write FOnSessionClose; end; { @abstract(DualDataServerLink, used to link Data Providers to two Servers) You can use TRtcDualDataServerLink components to link several related @Link(TRtcDataProvider) components to two Servers (for example, HTTP and HTTPS). Simply set this component as the Link property for all your RtcDataSource components, then set both Servers as this components "Server" and "Server2", or "Link" and "Link2" properties. You can also combine multiple DualDataServerLink components if you want your code running with more Servers. @html(<br><br>) Check @Link(TRtcAbsDataServerLink) for more info. } TRtcDualDataServerLink=class(TRtcDataServerLink) private FServer2: TRtcDataServer; FLink2: TRtcDataServerLink; protected // @exclude function CheckLink(Value:TRtcAbsDataServerLink):boolean; override; // @exclude procedure RemoveLink(Value:TRtcAbsDataServerLink); override; // @exclude procedure RemoveServer(Value:TRtcDataServer); override; // @exclude function GetServer2: TRtcDataServer; virtual; // @exclude procedure SetServer2(const Value: TRtcDataServer); virtual; // @exclude function GetLink2: TRtcDataServerLink; virtual; // @exclude procedure SetLink2(const Value: TRtcDataServerLink); virtual; // @exclude procedure SetServer(const Value: TRtcDataServer); override; // @exclude procedure SetLink(const Value: TRtcDataServerLink); override; protected // @exclude procedure SetOrder(const Value: integer); override; public // @exclude constructor Create(AOwner:TComponent); override; // @exclude destructor Destroy; override; // @exclude procedure Call_RequestAccepted(Sender: TRtcConnection); override; // @exclude procedure Call_ResponseDone(Sender: TRtcConnection); override; // @exclude procedure Call_Disconnect(Sender:TRtcConnection); override; published { You can link your components (one or more) to a DataServerLink component by assigning your @Link(TRtcDataServerLink) component to this Link property. Doing this, you only have to set the Server property for the master DataServerLink component and don't need to do it for every single DataSource component. } property Link2:TRtcDataServerLink read GetLink2 write SetLink2; { You can also link your components (one or more) directly to your DataServer connection component by assigning your @Link(TRtcDataServer) connection component to this Server property. This is useful if you have some complex functionality implemented in a single DataSource/DataServerLink component and don't need to drag the component through another DataServerLink component to get to your DataServer. } property Server2:TRtcDataServer read GetServer2 write SetServer2; end; { @abstract(Data Provider, used to implement events for processing Requests from DataServer) You can use TRtcDataProvider components to implement event handlers for different requests and combine them to compile a Server which can handle any request implemented in those handlers. @html(<br><br>) By implementing events specified by this component, then assigning your @Link(TRtcDataServer) connection component to this component's @Link(TRtcAbsDataServerLink.Server) property, or @Link(TRtcDataServerLink) (which also has to be somewhere connected to the DataServer connection component) to this component's @Link(TRtcAbsDataServerLink.Link) property, you can simply integrate diferent request handlers into your DataServer. For example, a File source (to send files from disk) and a PHP source (to read php files from disk, process them by PHP parser and send the resulting page out). @html(<br><br>) Check @Link(TRtcAbsDataServerLink) for more info. } TRtcDataProvider=class(TRtcAbsDataServerLink) protected // @exclude FOnListenStart: TRtcNotifyEvent; // @exclude FOnListenStop: TRtcNotifyEvent; // @exclude FOnDisconnect: TRtcNotifyEvent; // @exclude FOnCheckRequest: TRtcNotifyEvent; // @exclude FOnDataReceived: TRtcNotifyEvent; // @exclude FOnReadyToSend: TRtcNotifyEvent; // @exclude FOnDataOut: TRtcNotifyEvent; // @exclude FOnDataIn: TRtcNotifyEvent; // @exclude FOnDataSent: TRtcNotifyEvent; // @exclude FOnSessionOpen: TRtcNotifyEvent; // @exclude FOnSessionClose: TRtcNotifyEvent; // @exclude procedure Call_RequestAccepted(Sender:TRtcConnection); override; // @exclude procedure Call_ResponseDone(Sender:TRtcConnection); override; // @exclude procedure Call_ListenStart(Sender:TRtcConnection); override; // @exclude procedure Call_ListenStop(Sender:TRtcConnection); override; // @exclude procedure Call_CheckRequest(Sender:TRtcConnection); override; // @exclude procedure Call_DataReceived(Sender:TRtcConnection); override; // @exclude procedure Call_DataOut(Sender:TRtcConnection); override; // @exclude procedure Call_DataIn(Sender:TRtcConnection); override; // @exclude procedure Call_DataSent(Sender:TRtcConnection); override; // @exclude procedure Call_ReadyToSend(Sender:TRtcConnection); override; // @exclude procedure Call_Disconnect(Sender:TRtcConnection); override; // @exclude procedure Call_SessionOpen(Sender:TRtcConnection); override; // @exclude procedure Call_SessionClose(Sender:TRtcConnection); override; public // @exclude constructor Create(AOwner:TComponent); override; // @exclude destructor Destroy; override; published { This event will be mapped as @Link(TRtcServer.OnListenStart) event to the assigned Server component and called AFTER the Server's OnListenStart event, for all components. This event can be used to initialize the component after server starts listening. } property OnListenStart:TRtcNotifyEvent read FOnListenStart write FOnListenStart; { This event will be mapped as @Link(TRtcServer.OnListenStop) event to the assigned Server component and called BEFORE the Server's OnListenStop event, for all components. This event can be used to de-initialize the component before server stops listening. } property OnListenStop:TRtcNotifyEvent read FOnListenStop write FOnListenStop; { This event will be called after new session has been opened. } property OnSessionOpen:TRtcNotifyEvent read FOnSessionOpen write FOnSessionOpen; { This event will be called before existing session is about to close. } property OnSessionClose:TRtcNotifyEvent read FOnSessionClose write FOnSessionClose; { This event will be called when a new Request comes from a client and its headers have been read (but not content body). What this event has to do is to check the request information available, without reading the request body (!do not call 'Read' here) and decide wether it wants to process this request or not. If it wants to process the request, it just has to accept it here. The processing has to be done from other events defined for this DataProvider. @html(<br><br>) To accept the request as its own (and so be able to respond to the client), DataPrivder has to call "Accept" from it's 'OnCheckRequest' event handler. DataProvider has to be able to recognize the Request as it's own, simply by checking the Request property of the Sender (as TRtcDataServer), without reading the request body (content part). @html(<br><br>) Example of one OnCheckRequest and OnDataReceived events implementation: @longcode(# procedure TWebServer.TimeSourceCheckRequest(Sender: TRtcConnection); begin with TRtcDataServer(Sender) do if UpperCase(Request.FileName)='/TIME' then Accept; // Accept the request. // After accepting the request, all your other events will be mapped // to the connection, so you will have complete control over the // received data and the art of your response. end; procedure TWebServer.TimeSourceDataReceived(Sender: TRtcConnection); begin // If the request body is small or of no special interest to you, // You can simply respond to the request after it has been completely loaded. with TRtcDataServer(Sender) do if Request.Complete then Write(FormatDateTime('dddd, dd.mm.yyyy. hh:nn:ss',Now)); end; #) This simple implementation is a complete implementation for a HTML page that shows current date and time on the server when user asks for "/TIME". To see what the above example does, click here: http://www.realthinclient.com/time @html(<br><br>) If your component doesn't Accept the request when it first receives it in its CheckRequest event, the same request will be passed to the next component in the list, until one component accepts the request. If the request was not accepted after all CheckRequest events from all components assigned to the Server were passed, then Server's OnRequestNotAccepted event will be called. If a component accepts a request, all furure events regarding this request will be mapped to the component which accepted the request. @html(<br><br>) This means that CheckRequest is the only event which will be called for all DataProvider components, until a component is found which wants to process the request (the one that Accepts the request). All other request-related events (all but OnListenStart and OnListenStop) will ONLY be called by the event handlers defined by the component which accepted the request. } property OnCheckRequest:TRtcNotifyEvent read FOnCheckRequest write FOnCheckRequest; { This event will be mapped as TRtcConnection.OnDataReceived event to the assigned Server component and called for all DataReceived events for the accepted request. This means that, after you have accepted a request from your component's CheckRequest event handler, all Server's OnDataReceived events will be only mapped to your component's OnDataReceived event. No other component, including the DataServer, will receive those events. } property OnDataReceived:TRtcNotifyEvent read FOnDataReceived write FOnDataReceived; { This event will be mapped as @Link(TRtcConnection.OnDataOut) event to the assigned Server component and called for all DataOut events for the accepted request. After you have accepted a request from your component's CheckRequest event handler, all Server's OnDataOut events will be mapped to your component's OnDataOut event. No other component, except for the DataServer, will receive those events. @html(<br><br>) You can use this event to count how many bytes have been written out. } property OnDataOut:TRtcNotifyEvent read FOnDataOut write FOnDataOut; { This event will be mapped as @Link(TRtcConnection.OnDataIn) event to the assigned Server component and called for all DataIn events for the accepted request. After you have accepted a request from your component's CheckRequest event handler, all Server's OnDataIn events will be mapped to your component's OnDataIn event. No other component, except for the DataServer, will receive those events. You can use this event to count how many bytes have been read in. } property OnDataIn:TRtcNotifyEvent read FOnDataIn write FOnDataIn; { This event will be mapped as @Link(TRtcConnection.OnDataSent) event to the assigned Server component and called for all DataSent events for the accepted request. This means that, after you have accepted a request from your component's CheckRequest event handler, all Server's OnDataSent events will be only mapped to your component's OnDataSent event. No other component, including the DataServer, will receive those events. } property OnDataSent:TRtcNotifyEvent read FOnDataSent write FOnDataSent; { This event will be mapped as @Link(TRtcConnection.OnReadyToSend) event to the assigned Server component and called for all ReadyToSend events for the accepted request. This means that, after you have accepted a request from your component's CheckRequest event handler, all Server's OnReadyToSend events will be only mapped to your component's OnReadyToSend event. No other component, including the DataServer, will receive those events, until you process the request completely. } property OnReadyToSend:TRtcNotifyEvent read FOnReadyToSend write FOnReadyToSend; { This event will be mapped as @Link(TRtcConnection.OnDisconnect) event to the assigned Server component and called if your connection gets closed while you are still processing the request you accepted. This means that, after you have accepted a request from your component's CheckRequest event handler, if connection closes before your complete result has been sent out to the client, your component will be the only one to receive this OnDisconnect event. No other component, including the DataServer, will receive the Disconnect event if your component did not finish processing the request and sending the resulting data. @html(<br><br>) If you want to react to clients connecting and disconnecting to your Data Server regardless of those event mappings, use the OnConnecting and OnDisconnecting events instead of OnConnect/OnDisconnect. } property OnDisconnect:TRtcNotifyEvent read FOnDisconnect write FOnDisconnect; end; implementation uses memStrObjList, SysUtils, rtcSyncObjs; var SessCS:TRtcCritSec; SessExpList:tStrObjList; // Unlocked Sessions, sorted by Expiring date+time, PeerAddr & Session ID SessUnLockList:tStrObjList; // UnLocked Sessions, sorted by Session ID SessLockList:tStrObjList; // Locked Sessions, sorted by Session ID procedure InitSessions; begin SessCS:=TRtcCritSec.Create; SessExpList:=tStrObjList.Create(128); SessUnLockList:=tStrObjList.Create(128); SessLockList:=tStrObjList.Create(128); end; function GetTotalSessCount:cardinal; begin SessCS.Enter; try if assigned(SessUnLockList) then Result:=SessUnLockList.Count else Result:=0; if assigned(SessLockList) then Result:=Result+SessLockList.Count; finally SessCS.Leave; end; end; function GetTotalLockSessCount:cardinal; begin SessCS.Enter; try if assigned(SessLockList) then Result:=SessLockList.Count else Result:=0; finally SessCS.Leave; end; end; function GetTotalUnlockSessCount:cardinal; begin SessCS.Enter; try if assigned(SessUnLockList) then Result:=SessUnLockList.Count else Result:=0; finally SessCS.Leave; end; end; procedure DoneSessions; var o:TObject; id:string; begin SessCS.Enter; try if assigned(SessUnLockList) then begin id:=SessUnLockList.search_min(o); while id<>'' do begin o.Free; SessUnLockList.remove(id); id:=SessUnLockList.search_min(o); end; SessUnLockList.Free; SessUnLockList:=nil; end; if assigned(SessLockList) then begin id:=SessLockList.search_min(o); while id<>'' do begin o.Free; SessLockList.remove(id); id:=SessLockList.search_min(o); end; SessLockList.Free; SessLockList:=nil; end; if assigned(SessExpList) then begin SessExpList.Free; SessExpList:=nil; end; finally SessCS.Leave; end; Garbage(SessCS); end; {$IFDEF UseGUIDs} function NewSessionID:string; var GUID: TGUID; function GuidToStr:string; begin SetLength(Result, 32); StrLFmt(PChar(Result), 32,'%.8x%.4x%.4x%.2x%.2x%.2x%.2x%.2x%.2x%.2x%.2x', // do not localize [GUID.D1, GUID.D2, GUID.D3, GUID.D4[0], GUID.D4[1], GUID.D4[2], GUID.D4[3], GUID.D4[4], GUID.D4[5], GUID.D4[6], GUID.D4[7]]); end; begin if CoCreateGuid(GUID) = S_OK then Result := GUIDToStr else Result := ''; end; {$ELSE} function NewSessionID(const OldID:string; const PeerAddr:string):string; var tmp:string; function PeerAddrToSessionID:string; const code:array[0..15] of char = ('a','A','b','B','c','C','d','D','e','E','f','F','g','G','h','H'); var ip,loc:integer; myIP:byte; st:array[1..4] of string; begin Result:=''; for ip:=1 to 4 do st[ip]:=''; // Sort out numbers from the IP address ip:=1; loc:=1; while length(PeerAddr)>=loc do begin if PeerAddr[loc] in ['0'..'9'] then st[ip]:=st[ip]+PeerAddr[loc] else if PeerAddr[loc]='.' then Inc(ip); Inc(loc); end; // Convert IP numbers to Hex string for ip:=1 to 4 do begin if st[ip]<>'' then begin myIP:=StrToIntDef(st[ip],0); Result := Result + code[myIP shr 4 and $F]+ code[myIP and $F]; end else Result:=Result+code[0]+code[0]; end; // Add 10 random letters/numbers for loc:=1 to 10 do begin ip:=random(10+26+26); if ip<10 then Result:=Result+char(Ord('0')+ip) else if ip<36 then Result:=Result+char(Ord('A')+ip-10) else Result:=Result+char(Ord('a')+ip-36) end; end; procedure IncID(var ID:string); var loc:integer; ok:boolean; begin ok:=False; loc:=length(ID); while loc>0 do begin if ID[loc]='9' then begin ID[loc]:='A'; ok:=True; Break; end else if ID[loc]='Z' then begin ID[loc]:='a'; ok:=True; Break; end else if ID[loc]='z' then ID[loc]:='0' // carry 1 forward else begin ID[loc]:=Char(Ord(ID[loc])+1); ok:=True; Break; end; Dec(Loc); end; if not ok then ID:='1'+ID; end; begin if OldID='' then Result:='1'+PeerAddrToSessionID else begin Result:=PeerAddrToSessionID; tmp:=Copy(OldID,1,length(OldID)-length(Result)); IncID(tmp); Result:=tmp+Result; end; end; {$ENDIF} function SessionTimeToStr(v:TDateTime):String; var y,m,d,hh,mm,ss,ms:word; p:integer; str:string; len:word; begin Result:='00000000000000000'; DecodeDate(v, y,m,d); DecodeTime(v, hh,mm,ss,ms); p:=1; str:=IntToStr(y); len:=length(str); Inc(p,4-len); Move(str[1],Result[p],len); Inc(p,len); str:=IntToStr(m); len:=length(str); Inc(p,2-len); Move(str[1],Result[p],len); Inc(p,len); str:=IntToStr(d); len:=length(str); Inc(p,2-len); Move(str[1],Result[p],len); Inc(p,len); str:=IntToStr(hh); len:=length(str); Inc(p,2-len); Move(str[1],Result[p],len); Inc(p,len); str:=IntToStr(mm); len:=length(str); Inc(p,2-len); Move(str[1],Result[p],len); Inc(p,len); str:=IntToStr(ss); len:=length(str); Inc(p,2-len); Move(str[1],Result[p],len); Inc(p,len); str:=IntToStr(ms); len:=length(str); Inc(p,3-len); Move(str[1],Result[p],len); end; {function SessionTimeToStr(DT:TDateTime):string; begin Result:=FormatDateTime('yyyymmddhhnnss',DT); end;} { Find Session by SessionID and Lock the Session: - remove from UnLocked and Expiring list - add to Locked list } function FindSession(const ID,PeerAddr,ForwardedFor: string):TRtcServerSession; var id2:string; o:TObject; begin if ID='' then Result:=nil else begin SessCS.Enter; try if assigned(SessUnLockList) then begin id2:=ID; {$IFNDEF UseGUIDs} // Set ID to desired length, so it will be sorted as a numeric value. while length(id2)<RTC_SESSIONID_LENGTH do id2:=' '+id2; {$ENDIF} // Find Session with Session ID o:=SessUnLockList.search(id2); if o<>nil then begin Result:=TRtcServerSession(o); // Check if we have the right to access this session if Result.DenyAccess(PeerAddr,ForwardedFor) then Result:=nil else begin // Remove from UnLocked list SessUnLockList.remove(id2); // Add to Locked list SessLockList.insert(id2,Result); // Remove from Expiring list SessExpList.remove(SessionTimeToStr(Result.ExpireTime)+Result.ID); end; end else Result:=nil; end else Result:=nil; finally SessCS.Leave; end; end; end; { Check if Session with SessionID exists } function HaveSession(const ID,PeerAddr,ForwardedFor: string):boolean; var id2:string; o:TObject; sess:TRtcServerSession; begin if ID='' then Result:=false else begin SessCS.Enter; try if assigned(SessUnLockList) then begin id2:=ID; {$IFNDEF UseGUIDs} // Set ID to desired length, so it will be sorted as a numeric value. while length(id2)<RTC_SESSIONID_LENGTH do id2:=' '+id2; {$ENDIF} // Find Session with Session ID inside unlocked sessions list o:=SessUnLockList.search(id2); if o<>nil then begin sess:=TRtcServerSession(o); // Check if we have the right to access this session Result:=not sess.DenyAccess(PeerAddr,ForwardedFor); end else begin // Find Session with Session ID inside Locked Sessions list o:=SessLockList.search(id2); if o<>nil then begin sess:=TRtcServerSession(o); // Check if we have the right to access this session Result:=not sess.DenyAccess(PeerAddr,ForwardedFor); end else Result:=False; end; end else Result:=False; finally SessCS.Leave; end; end; end; { Find Session by SessionID and Close the Session } function CloseSessionID(const ID,PeerAddr,ForwardedFor: string; _Event:TRtcSimpleEvent):boolean; var id2:string; o:TObject; sess:TRtcServerSession; begin if ID='' then Result:=false else begin SessCS.Enter; try if assigned(SessUnLockList) then begin id2:=ID; {$IFNDEF UseGUIDs} // Set ID to desired length, so it will be sorted as a numeric value. while length(id2)<RTC_SESSIONID_LENGTH do id2:=' '+id2; {$ENDIF} // Find Session with Session ID inside unlocked sessions list o:=SessUnLockList.search(id2); if o<>nil then begin sess:=TRtcServerSession(o); // Check if we have the right to access this session if sess.DenyAccess(PeerAddr,ForwardedFor) then Result:=False else begin // Remove from UnLocked list SessUnLockList.remove(id2); // Remove from Expiring list SessExpList.remove(SessionTimeToStr(sess.ExpireTime)+sess.ID); // Call SessionClose event. if assigned(_Event) then _Event(sess); // Free session object sess.Free; Result:=True; end; end else begin // Find Session with Session ID inside Locked Sessions list o:=SessLockList.search(id2); if o<>nil then begin sess:=TRtcServerSession(o); // Check if we have the right to access this session if sess.DenyAccess(PeerAddr,ForwardedFor) then Result:=False else begin sess.FinalExpire:=Now; Result:=True; end; end else Result:=False; end; end else Result:=False; finally SessCS.Leave; end; end; end; { TRtcDataServer } class function TRtcDataServer.New: TRtcDataServer; begin Result:=Create(nil); end; constructor TRtcDataServer.Create(AOwner: TComponent); begin inherited Create(AOwner); FMyRequest:=TRtcServerRequest.Create; FMyResponse:=TRtcServerResponse.Create; FRequest:=FMyRequest; FResponse:=FMyResponse; FActiveLink:=nil; FDataServerLinks:=nil; FDataServerLinks_Owner:=False; FSession:=nil; end; destructor TRtcDataServer.Destroy; begin if FDataServerLinks_Owner and assigned(FDataServerLinks) then begin RemoveAllDataServerLinks; FDataServerLinks_Owner:=False; FDataServerLinks.Free; FDataServerLinks:=nil; end; InitSession; FActiveLink:=nil; FMyRequest.Free; FRequest:=nil; FMyResponse.Free; FResponse:=nil; inherited; end; procedure TRtcDataServer.CopyFrom(Dup: TRtcServer); begin inherited CopyFrom(Dup); FActiveLink:=nil; InitSession; OnRequestAccepted:=TRtcDataServer(Dup).OnRequestAccepted; OnRequestNotAccepted:=TRtcDataServer(Dup).OnRequestNotAccepted; OnResponseDone:=TRtcDataServer(Dup).OnResponseDone; OnSessionOpen:=TRtcDataServer(Dup).OnSessionOpen; OnSessionClose:=TRtcDataServer(Dup).OnSessionClose; if assigned(FDataServerLinks) and FDataServerLinks_Owner then begin FDataServerLinks.Free; FDataServerLinks:=nil; end; FDataServerLinks_Owner:=False; FDataServerLinks:=TRtcDataServer(Dup).FDataServerLinks; end; procedure TRtcDataServer.CallListenStart; var idx:integer; FMyLink:TRtcAbsDataServerLink; begin inherited; FActiveLink:=nil; InitSession; if assigned(FDataServerLinks) then for idx:=0 to FDataServerLinks.Count-1 do begin FMyLink:=FDataServerLinks.GetLink(idx); FMyLink.Call_ListenStart(self); end; end; procedure TRtcDataServer.CallListenStop; var idx:integer; FMyLink:TRtcAbsDataServerLink; begin if assigned(FDataServerLinks) then for idx:=0 to FDataServerLinks.Count-1 do begin FMyLink:=FDataServerLinks.GetLink(idx); FMyLink.Call_ListenStop(self); end; inherited; end; { DataServer.OnDataReceived event will be called only if there is no DataServerLink component to accept the request. } procedure TRtcDataServer.CallDataReceived; var idx:integer; FMyLink:TRtcAbsDataServerLink; begin if Request.Accepted then begin if assigned(FActiveLink) then FActiveLink.Call_DataReceived(self) else CallRequestNotAccepted; Flush; end else begin FActiveLink:=nil; InitSession; if assigned(FDataServerLinks) then for idx:=0 to FDataServerLinks.Count-1 do begin FMyLink:=FDataServerLinks.GetLink(idx); FMyLink.Call_CheckRequest(self); if Request.Accepted or not Request.Active then Break; end; if Request.Active then if not Request.Accepted then begin InitSession; FActiveLink:=nil; CallRequestNotAccepted; Flush; end else if not Response.Sent then begin if assigned(FActiveLink) then FActiveLink.Call_DataReceived(self) else CallRequestNotAccepted; Flush; end; end; end; { DataServer.OnDataOut event will be called only if the request was not accepted by any DataServerLink component (DataServer is probably sending the response). } procedure TRtcDataServer.CallDataOut; begin if assigned(FActiveLink) then FActiveLink.Call_DataOut(self); inherited; Flush; end; { DataServer.OnDataIn event will be called only if the request was not accepted by any DataServerLink component (DataServer is probably receiving a request). } procedure TRtcDataServer.CallDataIn; begin if assigned(FActiveLink) then FActiveLink.Call_DataIn(self); inherited; end; { DataServer.OnDataSent event will be called only if the request was not accepted by any DataServerLink component (DataServer is probably sending the response). } procedure TRtcDataServer.CallDataSent; begin if assigned(FActiveLink) then FActiveLink.Call_DataSent(self) else inherited; Flush; // Moved here from CallDataSent !!!! if Response.Done then begin CallResponseDone; Request.Accepted:=False; Request.Active:=False; FActiveLink:=nil; InitSession; end; end; { DataServer.OnReadyToSend event will be called if: 1. DataServer.OnDataSent event was just triggered, which means that DataServer is processing a request, or 2. Response just sent out for the last Request being processed. } procedure TRtcDataServer.CallReadyToSend; begin if assigned(FActiveLink) then FActiveLink.Call_ReadyToSend(self) else inherited; Flush; end; { DataServer.OnDisconnect event will ONLY be called if DataServer was the one processing a request when conncetion got lost. This event means that data sent out was most likely not delivered. DataServer.OnDisconnect event will NOT be called if the request was not accepted. To catch all connect and disconnect events for DataServer, use OnClientConnect and onClientDisconnect. } procedure TRtcDataServer.CallDisconnect; begin if Request.Accepted then begin if assigned(FActiveLink) then FActiveLink.Call_Disconnect(self); end; inherited; // call DataServer's OnDisconnect event FActiveLink:=nil; InitSession; end; procedure TRtcDataServer.AddDataServerLink(Value: TRtcAbsDataServerLink); begin if not assigned(FDataServerLinks) then begin FDataServerLinks:=TRtcDataServerLinkList.Create; FDataServerLinks_Owner:=True; end; FDataServerLinks.Add(Value); end; procedure TRtcDataServer.RemoveDataServerLink(Value: TRtcAbsDataServerLink); begin if assigned(FDataServerLinks) then FDataServerLinks.Remove(Value); end; procedure TRtcDataServer.RemoveAllDataServerLinks; var Link:TRtcAbsDataServerLink; begin if FDataServerLinks_Owner then if assigned(FDataServerLinks) then while FDataServerLinks.Count>0 do begin Link:=TRtcAbsDataServerLink(FDataServerLinks.Get(0)); Link.RemoveServer(self); end; end; procedure TRtcDataServer.SetActiveLink(Link: TRtcAbsDataServerLink); begin FActiveLink:=Link; end; { TRtcDataServer } procedure TRtcDataServer.Accept; begin if not Request.Accepted then begin Request.Accepted:=True; CallRequestAccepted; Flush; end; end; procedure TRtcDataServer.CallRequestAccepted; begin if assigned(FActiveLink) then FActiveLink.Call_RequestAccepted(self); if assigned(FOnRequestAccepted) then FOnRequestAccepted(self); end; procedure TRtcDataServer.CallResponseDone; begin if assigned(FActiveLink) then FActiveLink.Call_ResponseDone(self); if assigned(FOnResponseDone) then FOnResponseDone(self); end; procedure TRtcDataServer.CallRequestNotAccepted; begin if assigned(FOnRequestNotAccepted) then FOnRequestNotAccepted(self) else Disconnect; end; procedure TRtcDataServer.InitSession; begin if assigned(FSession) then begin {$IFDEF FPC} FSession.UnLock(@CallSessionClose); {$ELSE} FSession.UnLock(CallSessionClose); {$ENDIF} FSession:=nil; end; end; function TRtcDataServer.HaveSession(const ID: string): boolean; begin Result:=TRtcServerSession.Have(ID,PeerAddr,Request.ForwardedFor); end; function TRtcDataServer.CloseSession(const ID: string): boolean; begin {$IFDEF FPC} Result:=TRtcServerSession.CloseID(ID,PeerAddr,Request.ForwardedFor,@CallSessionClose); {$ELSE} Result:=TRtcServerSession.CloseID(ID,PeerAddr,Request.ForwardedFor,CallSessionClose); {$ENDIF} end; function TRtcDataServer.FindSession(const ID: string): boolean; begin InitSession; FSession:=TRtcServerSession.Find(ID,PeerAddr,Request.ForwardedFor); Result:=assigned(FSession); end; procedure TRtcDataServer.OpenSession(LockType:TRtcSessionLockType); begin InitSession; FSession:=TRtcServerSession.Open(LockType,PeerAddr,Request.ForwardedFor); if assigned(FSession) then CallSessionOpen; end; procedure TRtcDataServer.CallSessionClose(Sender: TObject); var idx:integer; FMyLink:TRtcAbsDataServerLink; FOldSess:TRtcServerSession; begin FOldSess:=FSession; EnterEvent; try FSession:=TRtcServerSession(Sender); if assigned(FDataServerLinks) then for idx:=0 to FDataServerLinks.Count-1 do begin FMyLink:=FDataServerLinks.GetLink(idx); FMyLink.Call_SessionClose(self); end; if assigned(FOnSessionClose) then FOnSessionClose(self); finally FSession:=FOldSess; LeaveEvent; end; end; procedure TRtcDataServer.CallSessionOpen; var idx:integer; FMyLink:TRtcAbsDataServerLink; begin EnterEvent; try if assigned(FOnSessionOpen) then FOnSessionOpen(self); if assigned(FDataServerLinks) then for idx:=0 to FDataServerLinks.Count-1 do begin FMyLink:=FDataServerLinks.GetLink(idx); FMyLink.Call_SessionOpen(self); end; finally LeaveEvent; end; end; procedure TRtcDataServer.SetRequest(const Value: TRtcServerRequest); begin FRequest := Value; end; procedure TRtcDataServer.SetResponse(const Value: TRtcServerResponse); begin FResponse := Value; end; procedure TRtcDataServer.CallLastWrite; begin inherited; InitSession; end; function TRtcDataServer.TotalSessionsCount: cardinal; begin Result:=GetTotalSessCount; end; function TRtcDataServer.TotalSessionsLocked: cardinal; begin Result:=GetTotalLockSessCount; end; function TRtcDataServer.TotalSessionsUnlocked: cardinal; begin Result:=GetTotalUnlockSessCount; end; procedure TRtcDataServer.UnLockSession; begin InitSession; end; { TRtcServerComponentList } constructor TRtcServerComponentList.Create; begin inherited; FList:=TList.Create; end; destructor TRtcServerComponentList.Destroy; begin FList.Free; inherited; end; procedure TRtcServerComponentList.Add(Value: TRtcServerComponent); var idx:integer; begin idx:=FList.IndexOf(Value); if idx>=0 then FList.Delete(idx); idx:=0; while idx<FList.Count do if Get(idx).GetOrder>=Value.GetOrder then Break // insert here! else Inc(idx); FList.Insert(idx, Value); end; function TRtcServerComponentList.Count: integer; begin Result:=FList.Count; end; procedure TRtcServerComponentList.Remove(Value: TRtcServerComponent); var idx:integer; begin idx:=FList.IndexOf(Value); if idx>=0 then FList.Delete(idx); end; procedure TRtcServerComponentList.RemoveAll; begin FList.Clear; end; function TRtcServerComponentList.Get(index:integer): TRtcServerComponent; begin if (index>=0) and (index<FList.Count) then Result:=TRtcServerComponent(FList.Items[index]) else Result:=nil; end; { TRtcDataServerLinkList } function TRtcDataServerLinkList.GetLink(index:integer): TRtcAbsDataServerLink; begin if (index>=0) and (index<Count) then Result:=TRtcAbsDataServerLink(Get(index)) else Result:=nil; end; { TRtcAbsDataServerLink } constructor TRtcAbsDataServerLink.Create(AOwner: TComponent); begin inherited Create(AOwner); FServer:=nil; FLink:=nil; FOrder:=0; end; destructor TRtcAbsDataServerLink.Destroy; begin Server:=nil; // remove from DataServer Link:=nil; // remove from parent DataServerLink inherited; end; procedure TRtcAbsDataServerLink.SetLink(const Value: TRtcDataServerLink); begin if Value<>FLink then begin if assigned(FLink) then begin FLink.RemoveChildLink(self); FLink:=nil; end; if assigned(Value) then begin Server:=nil; // can not be maped to DataServer and to DataServerLink at the same time. // Check for circular reference before assigning! if Value=self then raise Exception.Create('Circular DataServerLink reference!'); if Value.CheckLink(self) then raise Exception.Create('Circular DataServerLink reference!'); if CheckLink(Value) then raise Exception.Create('Circular DataServerLink reference!'); FLink:=Value; FLink.AddChildLink(self); end; end; end; function TRtcAbsDataServerLink.GetLink: TRtcDataServerLink; begin Result:=FLink; end; procedure TRtcAbsDataServerLink.SetServer(const Value: TRtcDataServer); begin if Value<>FServer then begin if assigned(FServer) then begin FServer.RemoveDataServerLink(self); FServer:=nil; end; if assigned(Value) then begin Link:=nil; // can not be linked to DataServerLink and DataServer at the same time. FServer:=Value; FServer.AddDataServerLink(self); end; end; end; function TRtcAbsDataServerLink.GetServer: TRtcDataServer; begin Result:=FServer; end; procedure TRtcAbsDataServerLink.SetOrder(const Value: integer); begin if Value<>FOrder then begin FOrder:=Value; // Update order if assigned(FLink) then FLink.AddChildLink(self) else if assigned(FServer) then FServer.AddDataServerLink(self); end; end; function TRtcAbsDataServerLink.GetOrder: integer; begin Result:=FOrder; end; procedure TRtcAbsDataServerLink.RemoveLink(Value: TRtcAbsDataServerLink); begin if Value=FLink then Link:=nil; end; procedure TRtcAbsDataServerLink.RemoveServer(Value: TRtcDataServer); begin if Value=FServer then Server:=nil; end; function TRtcAbsDataServerLink.CheckLink(Value: TRtcAbsDataServerLink):boolean; begin if Value=FLink then Result:=True else if assigned(FLink) then Result:=FLink.CheckLink(Value) else Result:=False; end; { TRtcDataServerLink } constructor TRtcDataServerLink.Create(AOwner: TComponent); begin inherited Create(AOwner); FDataServerLinks:=TRtcDataServerLinkList.Create; end; destructor TRtcDataServerLink.Destroy; begin RemoveAllChildLinks; FDataServerLinks.Free; FDataServerLinks:=nil; inherited; end; procedure TRtcDataServerLink.AddChildLink(Value: TRtcAbsDataServerLink); begin FDataServerLinks.Add(Value); end; procedure TRtcDataServerLink.RemoveChildLink(Value: TRtcAbsDataServerLink); begin FDataServerLinks.Remove(Value); end; procedure TRtcDataServerLink.RemoveAllChildLinks; var _Link:TRtcAbsDataServerLink; begin while FDataServerLinks.Count>0 do begin _Link:=TRtcAbsDataServerLink(FDataServerLinks.Get(0)); _Link.RemoveLink(self); end; end; procedure TRtcDataServerLink.Call_CheckRequest(Sender:TRtcConnection); var idx:integer; FMyLink:TRtcAbsDataServerLink; begin for idx:=0 to FDataServerLinks.Count-1 do begin FMyLink:=FDataServerLinks.GetLink(idx); FMyLink.Call_CheckRequest(Sender); if TRtcDataServer(Sender).Request.Accepted or not TRtcDataServer(Sender).Request.Active then Exit; end; end; procedure TRtcDataServerLink.Call_ListenStart(Sender: TRtcConnection); var idx:integer; FMyLink:TRtcAbsDataServerLink; begin if assigned(FOnListenStart) then FOnListenStart(Sender); for idx:=0 to FDataServerLinks.Count-1 do begin FMyLink:=FDataServerLinks.GetLink(idx); FMyLink.Call_ListenStart(Sender); end; end; procedure TRtcDataServerLink.Call_ListenStop(Sender: TRtcConnection); var idx:integer; FMyLink:TRtcAbsDataServerLink; begin for idx:=0 to FDataServerLinks.Count-1 do begin FMyLink:=FDataServerLinks.GetLink(idx); FMyLink.Call_ListenStop(Sender); end; if assigned(FOnListenStop) then FOnListenStop(Sender); end; procedure TRtcDataServerLink.Call_RequestAccepted(Sender: TRtcConnection); begin if assigned(FOnRequestAccepted) then FOnRequestAccepted(Sender); if assigned(Link) then Link.Call_RequestAccepted(Sender); end; procedure TRtcDataServerLink.Call_ResponseDone(Sender: TRtcConnection); begin if assigned(FOnResponseDone) then FOnResponseDone(Sender); if assigned(Link) then Link.Call_ResponseDone(Sender); end; procedure TRtcDataServerLink.Call_Disconnect(Sender:TRtcConnection); begin if assigned(FOnDisconnect) then FOnDisconnect(Sender); if assigned(Link) then Link.Call_Disconnect(Sender); end; procedure TRtcDataServerLink.Call_DataReceived(Sender:TRtcConnection); begin // left empty end; procedure TRtcDataServerLink.Call_DataOut(Sender:TRtcConnection); begin // left empty end; procedure TRtcDataServerLink.Call_DataIn(Sender:TRtcConnection); begin // left empty end; procedure TRtcDataServerLink.Call_DataSent(Sender:TRtcConnection); begin // left empty end; procedure TRtcDataServerLink.Call_ReadyToSend(Sender:TRtcConnection); begin // left empty end; procedure TRtcDataServerLink.Call_SessionClose(Sender: TRtcConnection); var idx:integer; FMyLink:TRtcAbsDataServerLink; begin for idx:=0 to FDataServerLinks.Count-1 do begin FMyLink:=FDataServerLinks.GetLink(idx); FMyLink.Call_SessionClose(Sender); end; if assigned(FOnSessionClose) then FOnSessionClose(Sender); end; procedure TRtcDataServerLink.Call_SessionOpen(Sender: TRtcConnection); var idx:integer; FMyLink:TRtcAbsDataServerLink; begin if assigned(FOnSessionOpen) then FOnSessionOpen(Sender); for idx:=0 to FDataServerLinks.Count-1 do begin FMyLink:=FDataServerLinks.GetLink(idx); FMyLink.Call_SessionOpen(Sender); end; end; { TRtcDualDataServerLink } constructor TRtcDualDataServerLink.Create(AOwner: TComponent); begin inherited; FServer2:=nil; FLink2:=nil; end; destructor TRtcDualDataServerLink.Destroy; begin Server2:=nil; Link2:=nil; inherited; end; function TRtcDualDataServerLink.GetServer2: TRtcDataServer; begin Result:=FServer2; end; function TRtcDualDataServerLink.GetLink2: TRtcDataServerLink; begin Result:=FLink2; end; procedure TRtcDualDataServerLink.SetServer2(const Value: TRtcDataServer); begin if Value<>FServer2 then begin if assigned(FServer) and (FServer=Value) then Server:=nil; if assigned(FServer2) then begin FServer2.RemoveDataServerLink(self); FServer2:=nil; end; if assigned(Value) then begin Link2:=nil; FServer2:=Value; FServer2.AddDataServerLink(self); end; end; end; procedure TRtcDualDataServerLink.SetLink2(const Value: TRtcDataServerLink); begin if Value<>FLink2 then begin if assigned(FLink) and (FLink=Value) then Link:=nil; if assigned(FLink2) then begin FLink2.RemoveChildLink(self); FLink2:=nil; end; if assigned(Value) then begin Server2:=nil; // can not be maped to Server2 and to Link2 at the same time. // Check for circular reference before assigning! if Value=self then raise Exception.Create('Circular DataServerLink reference!'); if Value.CheckLink(self) then raise Exception.Create('Circular DataServerLink reference!'); if CheckLink(Value) then raise Exception.Create('Circular DataServerLink reference!'); FLink2:=Value; FLink2.AddChildLink(self); end; end; end; procedure TRtcDualDataServerLink.SetServer(const Value: TRtcDataServer); begin if Value<>FServer then begin if assigned(FServer2) and (FServer2=Value) then Server2:=nil; inherited SetServer(Value); end; end; procedure TRtcDualDataServerLink.SetLink(const Value: TRtcDataServerLink); begin if Value<>FLink then begin if assigned(FLink2) and (FLink2=Value) then Link2:=nil; inherited SetLink(Value); end; end; procedure TRtcDualDataServerLink.SetOrder(const Value: integer); begin if Value<>FOrder then begin FOrder:=Value; // Update order if assigned(FLink2) then FLink2.AddChildLink(self) else if assigned(FServer2) then FServer2.AddDataServerLink(self); if assigned(FLink) then FLink.AddChildLink(self) else if assigned(FServer) then FServer.AddDataServerLink(self); end; end; procedure TRtcDualDataServerLink.RemoveLink(Value: TRtcAbsDataServerLink); begin inherited RemoveLink(Value); if Value=FLink2 then Link2:=nil; end; function TRtcDualDataServerLink.CheckLink(Value: TRtcAbsDataServerLink):boolean; begin Result:=inherited CheckLink(Value); if not Result then if Value=FLink2 then Result:=True else if assigned(FLink2) then Result:=FLink2.CheckLink(Value) else Result:=False; end; procedure TRtcDualDataServerLink.RemoveServer(Value: TRtcDataServer); begin inherited RemoveServer(Value); if Value=FServer2 then Server2:=nil; end; procedure TRtcDualDataServerLink.Call_RequestAccepted(Sender: TRtcConnection); begin inherited Call_RequestAccepted(Sender); if assigned(Link2) then Link2.Call_RequestAccepted(Sender); end; procedure TRtcDualDataServerLink.Call_ResponseDone(Sender: TRtcConnection); begin inherited Call_ResponseDone(Sender); if assigned(Link2) then Link2.Call_ResponseDone(Sender); end; procedure TRtcDualDataServerLink.Call_Disconnect(Sender:TRtcConnection); begin inherited Call_Disconnect(Sender); if assigned(Link2) then Link2.Call_Disconnect(Sender); end; { TRtcDataProvider } constructor TRtcDataProvider.Create(AOwner: TComponent); begin inherited Create(AOwner); FOnDisconnect:=nil; FOnCheckRequest:=nil; FOnDataReceived:=nil; FOnReadyToSend:=nil; FOnDataOut:=nil; FOnDataIn:=nil; FOnDataSent:=nil; end; destructor TRtcDataProvider.Destroy; begin FOnDisconnect:=nil; FOnCheckRequest:=nil; FOnDataReceived:=nil; FOnReadyToSend:=nil; FOnDataOut:=nil; FOnDataIn:=nil; FOnDataSent:=nil; inherited; end; procedure TRtcDataProvider.Call_CheckRequest(Sender:TRtcConnection); begin if assigned(OnCheckRequest) then begin TRtcDataServer(Sender).SetActiveLink(self); OnCheckRequest(Sender); end; end; procedure TRtcDataProvider.Call_DataReceived(Sender:TRtcConnection); begin if assigned(OnDataReceived) then OnDataReceived(Sender); end; procedure TRtcDataProvider.Call_DataOut(Sender:TRtcConnection); begin if assigned(OnDataOut) then OnDataOut(Sender); end; procedure TRtcDataProvider.Call_DataIn(Sender:TRtcConnection); begin if assigned(OnDataIn) then OnDataIn(Sender); end; procedure TRtcDataProvider.Call_DataSent(Sender:TRtcConnection); begin if assigned(OnDataSent) then OnDataSent(Sender); end; procedure TRtcDataProvider.Call_ReadyToSend(Sender:TRtcConnection); begin if assigned(OnReadyToSend) then OnReadyToSend(Sender); end; procedure TRtcDataProvider.Call_ListenStart(Sender:TRtcConnection); begin if assigned(OnListenStart) then OnListenStart(Sender); end; procedure TRtcDataProvider.Call_ListenStop(Sender:TRtcConnection); begin if assigned(OnListenStop) then OnListenStop(Sender); end; procedure TRtcDataProvider.Call_RequestAccepted(Sender: TRtcConnection); begin if assigned(Link) then Link.Call_RequestAccepted(Sender); end; procedure TRtcDataProvider.Call_ResponseDone(Sender: TRtcConnection); begin if assigned(Link) then Link.Call_ResponseDone(Sender); end; procedure TRtcDataProvider.Call_Disconnect(Sender:TRtcConnection); begin if assigned(OnDisconnect) then OnDisconnect(Sender); if assigned(Link) then Link.Call_Disconnect(Sender); end; procedure TRtcDataProvider.Call_SessionOpen(Sender: TRtcConnection); begin if assigned(OnSessionOpen) then OnSessionOpen(Sender); end; procedure TRtcDataProvider.Call_SessionClose(Sender: TRtcConnection); begin if assigned(OnSessionClose) then OnSessionClose(Sender); end; { TRtcServerSession } class function TRtcServerSession.Find(const _ID,_PeerAddr,_ForwardedFor: string): TRtcServerSession; begin Result:=FindSession(_ID,_PeerAddr,_ForwardedFor); end; class function TRtcServerSession.Have(const _ID,_PeerAddr,_ForwardedFor: string): boolean; begin Result:=HaveSession(_ID,_PeerAddr,_ForwardedFor); end; class function TRtcServerSession.CloseID(const _ID,_PeerAddr,_ForwardedFor: string; _Event:TRtcSimpleEvent): boolean; begin Result:=CloseSessionID(_ID,_PeerAddr,_ForwardedFor,_Event); end; { Define Session ID and Lock the Session } procedure TRtcServerSession.LockSessionID; {$IFNDEF UseGUIDs} var id1,id2:string; o:TObject; {$ENDIF} begin SessCS.Enter; try if assigned(SessLockList) then begin {$IFDEF UseGUIDs} FID:=NewSessionID; // Add Session to Locked list SessLockList.insert(FID, self); {$ELSE} // Find max. session ID in use if SessLockList.search_max(o)<>'' then id1:=TRtcServerSession(o).ID else id1:=''; if SessUnlockList.search_max(o)<>'' then id2:=TRtcServerSession(o).ID else id2:=''; if id2>id1 then id1:=id2; // Define new session ID id2:=NewSessionID(id1, PeerAddr); FID:=id2; // Set ID to desired length, so it will be sorted as a numeric value. while length(id2)<RTC_SESSIONID_LENGTH do // 10 for SessionID + 8 for PeerAddr + 10 random id2:=' '+id2; // Add Session to Locked list SessLockList.insert(id2, self); {$ENDIF} end; finally SessCS.Leave; end; end; class function TRtcServerSession.Open(_LockType:TRtcSessionLockType; const _PeerAddr,_ForwardedFor: string): TRtcServerSession; begin // Create a new Session object Result:=TRtcServerSession.Create; Result.FLockType:=_LockType; Result.FPeerAddr:=_PeerAddr; Result.FForwardedFor:=_ForwardedFor; Result.FCreated:=Now; Result.FLastUsed:=Result.FCreated; // Define Session ID and Lock the Session object Result.LockSessionID; if Result.ID='' then begin Result.Free; raise Exception.Create('Unable to initialize session'); end; end; function TRtcServerSession.DenyAccess(const _PeerAddr, _ForwardedFor: string): boolean; begin if LockType=sesNoLock then Result:=False else if (LockType=sesFwdLock) and (ForwardedFor='') and // "X-FORWARDED-FOR" was NOT set by creator - check for IP (PeerAddr<>_PeerAddr) then Result:=True else if (LockType in [sesFwdLock, sesIPFwdLock]) and (ForwardedFor<>'') and // "X-FORWARDED-FOR" was set by creator - use value set (ForwardedFor<>_ForwardedFor) then Result:=True else if (LockType in [sesIPLock, sesIPFwdLock]) and (PeerAddr<>_PeerAddr) then Result:=True else Result:=False; end; { UnLock Session and remove all sessions that have expired: - remove from Locked list - add to UnLocked and Expiring list } procedure TRtcServerSession.UnLockSession(_Event:TRtcSimpleEvent); var id2,ex:string; o:TObject; begin if not assigned(SessCS) then Exit; SessCS.Enter; try if assigned(SessUnLockList) then begin // Check if there are Sessions that have expired but are still in our session list ex:=SessExpList.search_min(o); while (ex<>'') and (TRtcServerSession(o).ExpireTime<=Now) do begin // Remove from Expiring list SessExpList.remove(ex); // Set ID to desired length, so it will be sorted as a numeric value. id2:=TRtcServerSession(o).ID; {$IFNDEF UseGUIDs} while length(id2)<RTC_SESSIONID_LENGTH do id2:=' '+id2; {$ENDIF} // Remove from UnLocked list SessUnLockList.remove(id2); if assigned(_Event) then _Event(o); // Free the Session object o.Free; ex:=SessExpList.search_min(o); end; id2:=FID; {$IFNDEF UseGUIDs} // Set ID to desired length, so it will be sorted as a numeric value. while length(id2)<RTC_SESSIONID_LENGTH do id2:=' '+id2; {$ENDIF} // Remove from Locked list SessLockList.remove(id2); // Free if expired, add to expiring list if not. if ExpireTime<=Now then begin if assigned(_Event) then _Event(self); Free; end else begin // Add to UnLocked list SessUnLockList.insert(id2, self); // Add to Expiring list SessExpList.insert(SessionTimeToStr(ExpireTime)+ID, self); end; end; finally SessCS.Leave; end; end; procedure TRtcServerSession.UnLock(_Event:TRtcSimpleEvent); begin FLastUsed:=Now; // First update ExpireTime with LiveTime if FKeepAlive=0 then FExpireTime:=Now + RTC_SESSION_TIMEOUT/24/60/60 else FExpireTime:=Now + FKeepAlive/24/60/60; // Check if session has to expire (FinalExpire value defined) if FFinalExpire<>0 then if FExpireTime>FFinalExpire then FExpireTime:=FFinalExpire; UnLockSession(_Event); end; procedure TRtcServerSession.SetKeepAlive(const _Value: integer); begin FKeepAlive:=_Value; end; procedure TRtcServerSession.SetFinalExpire(const _Value: TDateTime); begin FFinalExpire:=_Value; end; procedure TRtcServerSession.Close; begin FFinalExpire:=Now; end; initialization Randomize; InitSessions; finalization DoneSessions; end.
unit fOrdersRelease; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ORFn, ORCtrls, ExtCtrls, UBACore, UBAGlobals, VA508AccessibilityManager; type TfrmReleaseOrders = class(TfrmAutoSz) Panel1: TPanel; lstOrders: TCaptionListBox; Label1: TLabel; Panel2: TPanel; grpRelease: TGroupBox; radVerbal: TRadioButton; radPhone: TRadioButton; radPolicy: TRadioButton; cmdOK: TButton; cmdCancel: TButton; procedure FormCreate(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); procedure lstOrdersDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure lstOrdersMeasureItem(Control: TWinControl; Index: Integer; var AHeight: Integer); procedure Panel1Resize(Sender: TObject); private FOrderList: TList; FNature: Char; FSigSts: Char; OKPressed: Boolean; ESCode: string; end; function ExecuteReleaseOrders(SelectedList: TList): Boolean; implementation {$R *.DFM} uses Hash, rCore, rOrders, uConst, fSignItem, fOrdersPrint, uCore, uOrders, fRptBox, fFrame, fClinicWardMeds, rODLab, System.UITypes; const TX_SAVERR1 = 'The error, '; TX_SAVERR2 = ', occurred while trying to save:' + CRLF + CRLF; TC_SAVERR = 'Error Saving Order'; TX_ES_REQ = 'Enter your electronic signature to release these orders.'; TC_ES_REQ = 'Electronic Signature'; TX_NO_REL = CRLF + CRLF + '- cannot be released to the service(s).' + CRLF + CRLF + 'Reason: '; TC_NO_REL = 'Unable to Release Orders'; function ExecuteReleaseOrders(SelectedList: TList): Boolean; var frmReleaseOrders: TfrmReleaseOrders; i, PrintLoc: Integer; SignList: TStringList; OrderText: string; AnOrder: TOrder; AList: TStringList; function FindOrderText(const AnID: string): string; var i: Integer; begin Result := ''; with SelectedList do for i := 0 to Count - 1 do with TOrder(Items[i]) do if ID = AnID then begin Result := Text; Break; end; end; function SignNotRequired: Boolean; var i: Integer; begin Result := True; with SelectedList do for i := 0 to Pred(Count) do begin with TOrder(Items[i]) do if Signature <> OSS_NOT_REQUIRE then Result := False; end; end; begin Result := False; PrintLoc := 0; if SelectedList.Count = 0 then Exit; frmReleaseOrders := TfrmReleaseOrders.Create(Application); try ResizeFormToFont(TForm(frmReleaseOrders)); frmReleaseOrders.FOrderList := SelectedList; with SelectedList do for i := 0 to Count - 1 do frmReleaseOrders.lstOrders.Items.Add(TOrder(Items[i]).Text); if SignNotRequired then frmReleaseOrders.grpRelease.Visible := False; frmReleaseOrders.ShowModal; if frmReleaseOrders.OKPressed then begin Result := True; SignList := TStringList.Create; try with SelectedList, frmReleaseOrders do for i := 0 to Count - 1 do begin AnOrder := TOrder(Items[i]); SignList.Add(AnOrder.ID + U + FSigSts + U + RS_RELEASE + U + FNature); end; StatusText('Sending Orders to Service(s)...'); if SignList.Count > 0 then SendOrders(SignList, frmReleaseOrders.ESCode); if (not frmFrame.TimedOut) then begin if IsValidIMOLoc(uCore.TempEncounterLoc,Patient.DFN) then frmClinicWardMeds.ClinicOrWardLocation(SignList, uCore.TempEncounterLoc,uCore.TempEncounterLocName, PrintLoc) else if (IsValidIMOLoc(Encounter.Location,Patient.DFN)) and ((frmClinicWardMeds.rpcIsPatientOnWard(patient.DFN)) and (Patient.Inpatient = false)) then frmClinicWardMeds.ClinicOrWardLocation(SignList, Encounter.Location,Encounter.LocationName, PrintLoc); end; uCore.TempEncounterLoc := 0; uCore.TempEncounterLocName := ''; //hds7591 Clinic/Ward movement. //CQ #15813 Modired code to look for error string mentioned in CQ and change strings to conts - JCS with SignList do if Count > 0 then for i := 0 to Count - 1 do begin if Pos('E', Piece(SignList[i], U, 2)) > 0 then begin OrderText := FindOrderText(Piece(SignList[i], U, 1)); if Piece(SignList[i],U,4) = TX_SAVERR_PHARM_ORD_NUM_SEARCH_STRING then InfoBox(TX_SAVERR1 + Piece(SignList[i], U, 4) + TX_SAVERR2 + OrderText + CRLF + CRLF + TX_SAVERR_PHARM_ORD_NUM, TC_SAVERR, MB_OK) else if Piece(SignList[i],U,4) = TX_SAVERR_IMAGING_PROC_SEARCH_STRING then InfoBox(TX_SAVERR1 + Piece(SignList[i], U, 4) + TX_SAVERR2 + OrderText + CRLF + CRLF + TX_SAVERR_IMAGING_PROC, TC_SAVERR, MB_OK) else InfoBox(TX_SAVERR1 + Piece(SignList[i], U, 4) + TX_SAVERR2 + OrderText, TC_SAVERR, MB_OK); end; if Pos('R', Piece(SignList[i], U, 2)) > 0 then NotifyOtherApps(NAE_ORDER, 'RL' + U + Piece(SignList[i], U, 1)); end; StatusText(''); // CQ 10226, PSI-05-048 - advise of auto-change from LC to WC on lab orders AList := TStringList.Create; try CheckForChangeFromLCtoWCOnRelease(AList, Encounter.Location, SignList); if AList.Text <> '' then ReportBox(AList, 'Changed Orders', TRUE); finally AList.Free; end; PrintOrdersOnSignRelease(SignList, frmReleaseOrders.FNature, PrintLoc); // SetupOrdersPrint(SignList, DeviceInfo, frmReleaseOrders.FNature, False, PrintIt); //*KCM* // if PrintIt then PrintOrdersOnReview(SignList, DeviceInfo); //*KCM* finally SignList.Free; end; {BillingAware} // HDS6435 // HDS00005143 - if cidc master sw is on and BANurseConsultOrders.Count > 0 then // save those orders with selected DX enteries. Resulting in dx populated for provider. if rpcGetBAMasterSwStatus then begin if BANurseConsultOrders.Count > 0 then begin rpcSaveNurseConsultOrder(BANurseConsultOrders); BANurseConsultOrders.Clear; end; end; {BillingAware} // HDS6435 end; {if frmReleaseOrders.OKPressed} finally frmReleaseOrders.Release; with SelectedList do for i := 0 to Count - 1 do UnlockOrder(TOrder(Items[i]).ID); end; end; procedure TfrmReleaseOrders.FormCreate(Sender: TObject); begin inherited; OKPressed := False; ESCode := ''; if Encounter.Provider = User.DUZ then begin FNature := NO_POLICY; radPolicy.Checked := True; end else begin FNature := NO_VERBAL; radVerbal.Checked := True; end; FSigSts := SS_UNSIGNED; end; procedure TfrmReleaseOrders.cmdOKClick(Sender: TObject); var i: Integer; AnErrMsg: string; AnOrder: TOrder; begin inherited; // set up nature, signature status if radPhone.Checked then FNature := NO_PHONE else if radPolicy.Checked then FNature := NO_POLICY else FNature := NO_VERBAL; FSigSts := SS_UNSIGNED; if not grpRelease.Visible then begin FNature := NO_PROVIDER; FSigSts := SS_NOTREQD; end; if FNature = NO_POLICY then FSigSts := SS_ESIGNED; // validate release of the orders with this nature of order StatusText('Validating Release...'); AnErrMsg := ''; with FOrderList do for i := 0 to Count - 1 do begin AnOrder := TOrder(Items[i]); ValidateOrderActionNature(AnOrder.ID, OA_RELEASE, FNature, AnErrMsg); if Length(AnErrMsg) > 0 then begin if IsInvalidActionWarning(AnOrder.Text, AnOrder.ID) then Break; InfoBox(AnOrder.Text + TX_NO_REL + AnErrMsg, TC_NO_REL, MB_OK); Break; end; end; StatusText(''); if Length(AnErrMsg) > 0 then Exit; // get the signature code for releasing the orders if grpRelease.Visible then begin SignatureForItem(Font.Size, TX_ES_REQ, TC_ES_REQ, ESCode); if ESCode = '' then Exit; end; OKPressed := True; Close; end; procedure TfrmReleaseOrders.cmdCancelClick(Sender: TObject); begin inherited; Close; end; procedure TfrmReleaseOrders.lstOrdersDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var x: string; ARect: TRect; SaveColor: TColor; begin inherited; with lstOrders do begin ARect := Rect; ARect.Left := ARect.Left + 2; Canvas.FillRect(ARect); Canvas.Pen.Color := Get508CompliantColor(clSilver); SaveColor := Canvas.Brush.Color; Canvas.MoveTo(ARect.Left, ARect.Bottom - 1); Canvas.LineTo(ARect.Right, ARect.Bottom - 1); if Index < Items.Count then begin x := FilteredString(Items[Index]); DrawText(Canvas.Handle, PChar(x), Length(x), ARect, DT_LEFT or DT_NOPREFIX or DT_WORDBREAK); Canvas.Brush.Color := SaveColor; ARect.Right := ARect.Right + 4; end; end; end; procedure TfrmReleaseOrders.lstOrdersMeasureItem(Control: TWinControl; Index: Integer; var AHeight: Integer); var x: string; ARect: TRect; begin inherited; with lstOrders do if Index < Items.Count then begin ARect := ItemRect(Index); Canvas.FillRect(ARect); x := FilteredString(Items[Index]); AHeight := WrappedTextHeightByFont(Canvas, Font, x, ARect); if AHeight < 13 then AHeight := 15; end; end; procedure TfrmReleaseOrders.Panel1Resize(Sender: TObject); begin inherited; lstOrders.Invalidate; end; end.
unit MD.DAO.Client; interface uses MD.Model.Classes, System.Generics.Collections, System.SysUtils; type TDAOClient = class private function CopyClient(AClient: TClient): TClient; public procedure insert(Client: TClient); procedure update(Client: TClient); procedure delete(Id: Integer); function listAll: TObjectList<TClient>; function find(Id: Integer): TClient; constructor create; end; var Clients: TObjectList<TClient>; procedure initialDb; implementation procedure initialDb; var i: Integer; begin for i := 1 to 10 do begin Clients.Add(TClient.Create); Clients.Last.id := i; Clients.Last.name := 'Client ' + i.ToString; Clients.Last.lastName := 'LastName ' + i.ToString; Clients.Last.phone := Format('%6.9d',[i]);; end; end; { TDAOClient } function TDAOClient.CopyClient(AClient: TClient): TClient; begin result := TClient.Create; try Result.id := AClient.id; result.name := AClient.name; result.lastName := AClient.lastName; result.phone := AClient.phone; except Result.Free; raise; end; end; constructor TDAOClient.create; begin end; procedure TDAOClient.delete(Id: Integer); var i : Integer; begin for i := 0 to Pred(Clients.Count) do begin if Clients[i].id = Id then begin Clients.Delete(i); Exit; end; end; raise Exception.CreateFmt('Client %s not found.', [Id.ToString]); end; function TDAOClient.find(Id: Integer): TClient; var i: Integer; begin result := nil; for i := 0 to Pred(Clients.Count) do begin if Clients[i].id = id then begin result := TClient.Create; Result.id := Clients[i].id; result.name := Clients[i].name; Result.lastName := Clients[i].lastName; Result.phone := Clients[i].phone; end; end; end; procedure TDAOClient.insert(Client: TClient); var auxClient: TClient; begin auxClient := CopyClient(Client); try auxClient.id := Clients.Last.id + 1; Clients.Add(auxClient); Client.id := auxClient.id; except auxClient.Free; end; end; function TDAOClient.listAll: TObjectList<TClient>; begin result := Clients; end; procedure TDAOClient.update(Client: TClient); var i : Integer; begin for i := 0 to Pred(Clients.Count) do begin if Clients[i].id = Client.id then begin Clients[i].name := Client.name; Clients[i].lastName := Client.lastName; Clients[i].phone := Client.phone; Exit; end; end; raise Exception.CreateFmt('Client %s not found.', [Client.id]); end; initialization Clients := TObjectList<TClient>.create; initialDb; finalization Clients.Free; end.
unit IdException; interface uses SysUtils; type EIdException = class(Exception); TClassIdException = class of EIdException; EIdAlreadyConnected = class(EIdException); EIdSilentException = class(EIdException); EIdInvalidServiceName = class(EIdException); EIdProtocolReplyError = class(EIdException) protected FReplyErrorCode: Integer; public constructor CreateError(const anErrCode: Integer; const asReplyMessage: string); reintroduce; virtual; property ReplyErrorCode: Integer read FReplyErrorCode; end; EIdDnsResolverError = class(EIdException); EIdInvalidSocket = class(EIdException); EIdSocketError = class(EIdException) private FLastError: Integer; public constructor CreateError(const anErr: Integer; const asMsg: string); virtual; property LastError: Integer read FLastError; end; EIdConnClosedGracefully = class(EIdSilentException); EIdResponseError = class(EIdException); EIdClosedSocket = class(EIdException); EIdTFTPException = class(EIdException); EIdTFTPFileNotFound = class(EIdTFTPException); EIdTFTPAccessViolation = class(EIdTFTPException); EIdTFTPAllocationExceeded = class(EIdTFTPException); EIdTFTPIllegalOperation = class(EIdTFTPException); EIdTFTPUnknownTransferID = class(EIdTFTPException); EIdTFTPFileAlreadyExists = class(EIdTFTPException); EIdTFTPNoSuchUser = class(EIdTFTPException); EIdTFTPOptionNegotiationFailed = class(EIdTFTPException); // RFC 1782 EIdIcmpException = class(EIdException); EIdSetSizeExceeded = class(EIdException); implementation constructor EIdProtocolReplyError.CreateError(const anErrCode: Integer; const asReplyMessage: string); begin inherited Create(asReplyMessage); FReplyErrorCode := anErrCode; end; constructor EIdSocketError.CreateError(const anErr: Integer; const asMsg: string); begin FLastError := anErr; inherited Create(asMsg); end; end.
uses Classes, SysUtils; {procedure TestStringList;} var Dictionary: TStringList; name: String; answer: String; begin Dictionary := TStringList.Create; { add coubtry} Dictionary.AddPair('Россия', 'Москва'); Dictionary.AddPair('Беларусь', 'Минск'); Dictionary.AddPair('Ливия', 'Триполи'); Dictionary.AddPair('Абхазия', 'Сухум'); Dictionary.AddPair('Австралия', 'Камберра'); Dictionary.AddPair('Австрия', 'Вена'); Dictionary.AddPair('Азербайджан', 'Баку'); Dictionary.AddPair('Албания', 'Тирана'); Dictionary.AddPair('Алжир', 'Алжир'); Dictionary.AddPair('Ангола', 'Луанда'); Dictionary.AddPair('Андорра', 'Андорра-ла-Велья'); Dictionary.AddPair('Антигуана и Барбуда', 'Сент-Джонс'); Dictionary.AddPair('Аргентина', 'Буэнос-Айрес'); Dictionary.AddPair('Армения', 'Ереван'); Dictionary.AddPair('Аруба', 'Ораньестад'); Dictionary.AddPair('Афганистан', 'Кабул'); Dictionary.AddPair('Багамы', 'Нассау'); Dictionary.AddPair('Бангландеш', 'Дака'); Dictionary.AddPair('Барбадос', 'Бриджтаун'); Dictionary.AddPair('Бахрейн', 'Манама'); Dictionary.AddPair('Белиз', 'Бельмопан'); Dictionary.AddPair('Бельгия', 'Брюссель'); Dictionary.AddPair('Бенин', 'Порто-Ново, Котону'); Dictionary.AddPair('Бермудские острова', 'Гамильтон'); Dictionary.AddPair('Болгария', 'София'); Dictionary.AddPair('Боливия', 'Сукре'); Dictionary.AddPair('Босния и Герцеговина', 'Сараево'); Dictionary.AddPair('Ботсвана', 'Габороне'); Dictionary.AddPair('Бразилия', 'Бразилиа'); Dictionary.AddPair('Бруней', 'Бандар-Сери-Бегаван'); Dictionary.AddPair('Буркина Фасо', 'Уагадугу'); Dictionary.AddPair('Бурунди', 'Бужумбура'); Dictionary.AddPair('Бутан', 'Тхимпху'); Dictionary.AddPair('Вануату', 'порт-Вила'); Dictionary.AddPair('Ватикан', 'Ватикан'); Dictionary.AddPair('Великобритания', 'Лондон'); Dictionary.AddPair('венгрия', 'Будапешт'); Dictionary.AddPair('Венесуэла', 'Каракас'); Dictionary.AddPair('Вьетнам', 'Ханой'); Dictionary.AddPair('Габон', 'Либревиль'); Dictionary.AddPair('Гавайские острова', 'Гонолулу'); Dictionary.AddPair('Гайана', 'Джорджтаун'); Dictionary.AddPair('Гаити', 'Порт-о-Пренс'); Dictionary.AddPair('Гамбия', 'Банжул'); Dictionary.AddPair('Гана', 'Аккра'); Dictionary.AddPair('Гваделупа', 'Бас-Тер'); Dictionary.AddPair('Гватемала', 'Гватемала'); Dictionary.AddPair('Гвинея', 'Конакри'); Dictionary.AddPair('Гвинея-Бисау', 'Бисау'); Dictionary.AddPair('Германия', 'Берлин'); Dictionary.AddPair('Гондурас', 'Тегусигальпа'); Dictionary.AddPair('Гонконг', 'Гонконг'); Dictionary.AddPair('Гренада', 'Сент-Джорджес'); Dictionary.AddPair('Греция', 'Афины'); Dictionary.AddPair('Грузия', 'Тбилиси'); Dictionary.AddPair('Дания', 'Копенгаген'); Dictionary.AddPair('Джибути', 'Джибути'); Dictionary.AddPair('Доминика', 'Розо'); Dictionary.AddPair('Доминикана', 'Санто-Доминго'); Dictionary.AddPair('Египет', 'Каир'); Dictionary.AddPair('Замбия', 'Лусака'); Dictionary.AddPair('Зимбабве', 'Хараре'); Dictionary.AddPair('Израиль', 'Иерусалим'); Dictionary.AddPair('Индия', 'Нью-Дели'); Dictionary.AddPair('Индонезия', 'Джакарта'); Dictionary.AddPair('Иордания', 'Амман'); Dictionary.AddPair('Ирак', 'Багдад'); Dictionary.AddPair('Иран', 'Тегеран'); Dictionary.AddPair('Ирландия', 'Дублин'); Dictionary.AddPair('Исландия', 'Рейкьявик'); Dictionary.AddPair('Испания', 'Мадрид'); Dictionary.AddPair('Италия', 'Рим'); Dictionary.AddPair('Йемен', 'Сана'); Dictionary.AddPair('Кабо-Верде', 'Прая'); Dictionary.AddPair('Казахстан', 'Нур-Султан'); Dictionary.AddPair('Каймановы острова', 'Джорджтаун'); Dictionary.AddPair('Камбоджа', 'Пномпень'); Dictionary.AddPair('Камерун', 'Яунде'); Dictionary.AddPair('Канада', 'Оттава'); Dictionary.AddPair('Канарские острова', 'Испания'); Dictionary.AddPair('Катар', 'Доха'); Dictionary.AddPair('Кения', 'Найроби'); Dictionary.AddPair('Кипр', 'Никосия'); Dictionary.AddPair('Киргизия', 'Бишкек'); Dictionary.AddPair('Кирибати', 'Южная Тарава'); Dictionary.AddPair('Китай', 'Пекин'); Dictionary.AddPair('Колумбия', 'Санта-Фе-Де-Богота'); Dictionary.AddPair('Коморы', 'Морони'); Dictionary.AddPair('Конго', 'Браззавиль'); Dictionary.AddPair('Конго-Киншаса', 'Киншаса'); Dictionary.AddPair('Коста-Рика', 'Сан-Хосе'); Dictionary.AddPair('Кот-д,Ивуар', 'Ямусурко'); Dictionary.AddPair('Куба', 'Гавана'); Dictionary.AddPair('Лаос', 'Вьентьян'); Dictionary.AddPair('Латвия', 'Рига'); Dictionary.AddPair('Лесото', 'Масеру'); Dictionary.AddPair('Либерия', 'Монровия'); Dictionary.AddPair('Ливан', 'Бейрут'); Dictionary.AddPair('Литва', 'Вильнюс'); Dictionary.AddPair('Лихтенштейн', 'Вадуц'); Dictionary.AddPair('Люксембург', 'Люксембург'); Dictionary.AddPair('Маврикий', 'Порт-Луи'); Dictionary.AddPair('Мавритания', 'Нуакшот'); Dictionary.AddPair('Мадагаскар', 'Антананариву'); Dictionary.AddPair('Македония', 'Скопье'); Dictionary.AddPair('Малави', 'Лилонгве'); Dictionary.AddPair('Малайзия', 'куала-Лумпур'); Dictionary.AddPair('Мали', 'Бамако'); Dictionary.AddPair('Мальдивы', 'Мале'); Dictionary.AddPair('Мальта', 'Валлетта'); Dictionary.AddPair('Марокко', 'Рабат'); Dictionary.AddPair('Мартиника', 'Фор-де-Франс'); Dictionary.AddPair('Маршалловы острова', 'Маджуро'); Dictionary.AddPair('Мексика', 'Мехико'); Dictionary.AddPair('Мозамбик', 'Мапуту'); Dictionary.AddPair('Молдова', 'Кишинев'); Dictionary.AddPair('Монако', 'Монако'); Dictionary.AddPair('Монголия', 'Улан-Батор'); Dictionary.AddPair('Мьянма', 'Нейпьидо'); Dictionary.AddPair('Намибия', 'Виндхук'); Dictionary.AddPair('Науру', 'Ярен'); Dictionary.AddPair('Непал', 'Катманду'); Dictionary.AddPair('Нигер', 'Ниамей'); Dictionary.AddPair('Нигерия', 'Абуджа'); Dictionary.AddPair('Нидерланды', 'Амстердам'); Dictionary.AddPair('Никарагуа', 'Манагуа'); Dictionary.AddPair('Новая Зеландия', 'Велингтон'); Dictionary.AddPair('Норвегия', 'Осло'); Dictionary.AddPair('ОАЭ', 'Абу-Даби'); Dictionary.AddPair('Оман', 'Маскат'); Dictionary.AddPair('Остров Святой Елены', 'Джеймстаун'); Dictionary.AddPair('Пакистан', 'Исламабад'); Dictionary.AddPair('Палау', 'Нгерулдум'); Dictionary.AddPair('Панама', 'Памана'); Dictionary.AddPair('Папуа-Новая Гвинея', 'Порт-Морсби'); Dictionary.AddPair('Парагвай', 'Асунсьон'); Dictionary.AddPair('Перу', 'Лима'); Dictionary.AddPair('Польша', 'Варшава'); Dictionary.AddPair('Португалия', 'Лиссабон'); Dictionary.AddPair('Пуэрто-Рико', 'Сан-Хуан'); Dictionary.AddPair('Реюньон', 'Сен-Дени'); Dictionary.AddPair('Руанда', 'Кигали'); Dictionary.AddPair('Румыния', 'Бухарест'); Dictionary.AddPair('Сальвадор', 'Сан-Сальвадор'); Dictionary.AddPair('Самоа', 'Апиа'); Dictionary.AddPair('Сан-Марино', 'Сан-Марино'); Dictionary.AddPair('Сан-Томе', 'Сан-Томе'); Dictionary.AddPair('Саудовская Аравия', 'Эр-Рияд'); Dictionary.AddPair('Свазиленд', 'Мбабане, Лобамба'); Dictionary.AddPair('Северная Корея', 'Пхеньян'); Dictionary.AddPair('Северная Македония', 'Скопье'); Dictionary.AddPair('Сейшелы', 'Виктория'); Dictionary.AddPair('Сенегал', 'Дакар'); Dictionary.AddPair('Сен-Мартен', 'Мариго'); Dictionary.AddPair('Сент-Винсент и Гренадины', 'Кингстаун'); Dictionary.AddPair('Сент-Китс', 'Бастер'); Dictionary.AddPair('Сент-Люсия', 'Кастри'); Dictionary.AddPair('Сербия', 'Белград'); Dictionary.AddPair('Сингапур', 'Сингапур'); Dictionary.AddPair('Сирия', 'Дамаск'); Dictionary.AddPair('Словакия', 'Братислава'); Dictionary.AddPair('Словения', 'Любляна'); Dictionary.AddPair('Соломоновы острова', 'Хониара'); Dictionary.AddPair('Сомали', 'Могадишо'); Dictionary.AddPair('Судан', 'Хартум'); Dictionary.AddPair('Суринам', 'Парамарибо'); Dictionary.AddPair('США', 'Вашингтон'); Dictionary.AddPair('Сьерра-Леоне', 'Фритаун'); Dictionary.AddPair('Таджикистан', 'Душанбе'); Dictionary.AddPair('Тайвань', 'Тайбэй'); Dictionary.AddPair('Тайланд', 'Бангкок'); Dictionary.AddPair('Танзания', 'Додома'); Dictionary.AddPair('Того', 'Ломе'); Dictionary.AddPair('Тонга', 'Нукуалофа'); Dictionary.AddPair('Тринидад', 'Порт-оф-Спейн'); Dictionary.AddPair('Тувалу', 'Фунафути'); Dictionary.AddPair('Тунис', 'Тунис'); Dictionary.AddPair('Туркменистан', 'Ашхадаб'); Dictionary.AddPair('Турция', 'Анкара'); Dictionary.AddPair('Уганда', 'Кампала'); Dictionary.AddPair('Узбекистан', 'Ташкент'); Dictionary.AddPair('Украина', 'Киев'); Dictionary.AddPair('Уоллис', 'Мата-Уту'); Dictionary.AddPair('Уругвай', 'Монтевидео'); Dictionary.AddPair('Фиджи', 'Сува'); Dictionary.AddPair('Филиппины', 'Манила'); Dictionary.AddPair('Финляндия', 'Хельсинки'); Dictionary.AddPair('Франция', 'Париж'); Dictionary.AddPair('Французская Гвиана', 'Кайенна'); Dictionary.AddPair('Хорватия', 'Загреб'); Dictionary.AddPair('Центрально-африканская республика', 'Банги'); Dictionary.AddPair('Чад', 'Нджамена'); Dictionary.AddPair('Черногория', 'Подгорница'); Dictionary.AddPair('Чехия', 'Прага'); Dictionary.AddPair('Чили', 'Сантьяго'); Dictionary.AddPair('Швейцария', 'Берн'); Dictionary.AddPair('Швеция', 'Стокгольм'); Dictionary.AddPair('Шри-Ланка', 'Шри-Джаяварденепура-Котте'); Dictionary.AddPair('Эквадор', 'Кито'); Dictionary.AddPair('Экваториальная Гвинея', 'Малабо'); Dictionary.AddPair('Эритрея', 'Асмэра'); Dictionary.AddPair('Эстония', 'Таллин'); Dictionary.AddPair('Эфиопия', 'Аддис-Абеба'); Dictionary.AddPair('ЮАР', 'Кейптаун Претория'); Dictionary.AddPair('Южная Корея', 'Сеул'); Dictionary.AddPair('Ямайка', 'Кингстон'); Dictionary.AddPair('Япония', 'Токио'); {input country} Writeln('Введите название страны: '); Readln(name); answer := Dictionary.Values[name]; Writeln('Столица страны '+ name + ': ' + answer); end.
unit Stats.PedsDatabaseIO; interface uses Stats.Constant, System.Diagnostics,System.TimeSpan, Stats.IO.Base; type TDatabasePedRW = class(TDatabaseReaderWriter) strict private strict protected function GetTraceType(): TTraceType; override; protected procedure Write(paData: TTraceDataObj); override; procedure Read(var paData: TTraceDataObj); override; end; TDatabasePedPositionRW = class(TDatabaseReaderWriter) strict protected function GetDatabaseType(): TDatabaseType; override; function GetTraceType(): TTraceType; override; protected procedure Write(paData: TTraceDataObj); override; procedure Read(var paData: TTraceDataObj); override; end; TDatabasePedEventsRW = class(TDatabaseReaderWriter) strict protected function GetTraceType(): TTraceType; override; protected procedure Write(paData: TTraceDataObj); override; procedure Read(var paData: TTraceDataObj); override; end; TDatabasePedStartEndRW = class(TDatabaseReaderWriter) strict protected function GetTraceType(): TTraceType; override; protected procedure Read(var paData: TTraceDataObj); override; end; TDatabasePedModelRW = class(TDatabaseReaderWriter) strict protected function GetTraceType(): TTraceType; override; protected procedure Write(paData: TTraceDataObj); override; procedure Read(var paData: TTraceDataObj); override; end; TDatabasePedTraceRW = class(TDatabaseReaderWriter) strict protected function GetTraceType(): TTraceType; override; protected procedure Write(paData: TTraceDataObj); override; procedure Read(var paData: TTraceDataObj); override; end; TDatabasePedMacroGrapRW = class(TDatabaseReaderWriter) strict protected function GetTraceType(): TTraceType; override; protected procedure Write(paData: TTraceDataObj); override; procedure Read(var paData: TTraceDataObj); override; end; TDatabasePedElevator = class(TDatabaseReaderWriter) strict protected function GetTraceType(): TTraceType; override; protected procedure Write(paData: TTraceDataObj); override; procedure Read(var paData: TTraceDataObj); override; end; procedure MakeLog(paFileName: string; paElapsed: Integer); implementation uses System.Classes, System.SysUtils, FireDAC.Comp.Client, oTracesManager, Stats.PedsTraceData, Stats.DBConnectionhandler, Data.DB; procedure MakeLog(paFileName: string; paElapsed: Integer); var logFile: TextFile; fileName: string; begin fileName := GetCurrentDir + PathDelim + paFileName; AssignFile(logFile, fileName); if FileExists(fileName) then Append(logFile) else Rewrite(logFile); writeln(logFile,paElapsed); CloseFile(logFile); end; { TDatabasePedPositionRW } function TDatabasePedPositionRW.GetDatabaseType: TDatabaseType; begin Result := dbPostgre; end; function TDatabasePedPositionRW.GetTraceType: TTraceType; begin Result := ttPedPositions; end; procedure TDatabasePedPositionRW.Read(var paData: TTraceDataObj); var qry: TFDQuery; // pri inej stope iny record readCount: integer; dataObj: TPedPositionTraceData; // pri inej stope ina trieda sqlText: string; begin inherited; dataObj := TPedPositionTraceData(paData); sqlText := 'SELECT PS.SIMTIME,PS.PEDID,PS.POSX,PS.POSY,PS.POSZ,PS.ROTATION,PS.ZONEID from pedposition ps where ps.modelid = '+ IntToStr(ActualModelID) +' and ps.traceid = '+ IntToStr(ActualTraceID) +' and ps.replicationnumber = '+ IntToStr(ActualRepNumber) +';'; if(ReadFromDatabase(sqlText,qry,readCount))then begin qry.First; while (not qry.Eof) do begin dataObj.SimTime := qry.Fields[0].AsExtended; dataObj.EntityID := qry.Fields[1].AsInteger; dataObj.X := qry.Fields[2].AsSingle; dataObj.Y := qry.Fields[3].AsSingle; dataObj.Z := qry.Fields[4].AsSingle; dataObj.Rotation := qry.Fields[5].AsSingle; dataObj.ZONEID := qry.Fields[6].AsInteger; if (not ProcessData(paData)) then Exit(); qry.Next; end; end; qry := nil; end; procedure TDatabasePedPositionRW.Write(paData: TTraceDataObj); var dataObj: TPedPositionTraceData; begin inherited; dataObj := TPedPositionTraceData(paData); aParam[0] := ActualModelID; aParam[1] := ActualTraceID; aParam[2] := ActualRepNumber; aParam[3] := dataObj.EntityID; aParam[4] := dataObj.SimTime; aParam[5] := dataObj.X; aParam[6] := dataObj.Y; aParam[7] := dataObj.Z; aParam[8] := dataObj.Rotation; aParam[9] := dataObj.ZoneID; WriteToDatabase(GetTraceType, aParam); end; { TDatabasePedEventsRW } function TDatabasePedEventsRW.GetTraceType: TTraceType; begin Result := ttPedEvents; end; procedure TDatabasePedEventsRW.Read(var paData: TTraceDataObj); var qry: TFDQuery; // pri inej stope iny record readCount: integer; dataObj: TPedEventsTraceData; // pri inej stope ina trieda sqlText: string; begin inherited; dataObj := TPedEventsTraceData(paData); sqlText := ' SELECT E.ENTITYID,E.PEDID,E.SIMTIME,E.EVENTYPE from pedevents e where e.modelid = '+ IntToStr(ActualModelID) +' and e.traceid = '+ IntToStr(ActualTraceID) +' and e.replicationnumber = '+ IntToStr(ActualRepNumber) +';'; if(ReadFromDatabase(sqlText,qry,readCount))then begin qry.First; while (not qry.Eof) do begin dataObj.EntityID := qry.Fields[0].AsInteger; dataObj.PedID := qry.Fields[1].AsInteger; dataObj.SimTime := qry.Fields[2].AsDateTime; case qry.Fields[3].AsInteger of 0: dataObj.EventType := etPedBORN; 1: dataObj.EventType := etPedDEATH; 2: dataObj.EventType := etSTART_WAITING; 3: dataObj.EventType := etSTOP_WAITING; end; if (not ProcessData(paData)) then Exit(); qry.Next; end; end; qry := nil; end; procedure TDatabasePedEventsRW.Write(paData: TTraceDataObj); var dataObj: TPedEventsTraceData; begin inherited; dataObj := TPedEventsTraceData(paData); aParam[0] := ActualModelID; aParam[1] := ActualTraceID; aParam[2] := ActualRepNumber; aParam[3] := dataObj.PedID; aParam[4] := dataObj.EntityID; aParam[5] := dataObj.SimTime; aParam[6] := Ord(dataObj.EventType); WriteToDatabase(GetTraceType, aParam); end; { TDatabasePedRW } function TDatabasePedRW.GetTraceType: TTraceType; begin Result := ttPed; end; procedure TDatabasePedRW.Read(var paData: TTraceDataObj); var qry: TFDQuery; // pri inej stope iny record readCount: integer; dataObj: TPedTraceData; // pri inej stope ina trieda pedCountID: Variant; checkPedCountID: boolean; sqlText: string; begin inherited; dataObj := TPedTraceData(paData); checkPedCountID := Filter.GetValue(coPedCountID, pedCountID); if not checkPedCountID then sqlText := 'select count(*) from simentity p where p.modelid ='+ IntToStr(ActualModelID) +' and p.traceid ='+ IntToStr(ActualTraceID) +' and p.replicationnumber ='+ IntToStr(ActualRepNumber) +' and entityID >0;' else sqlText := 'select p.entityID,p.EntityPath from simentity p where p.modelid = '+ IntToStr(ActualModelID) +' and p.traceid = '+ IntToStr(ActualTraceID) +' and p.replicationnumber = '+ IntToStr(ActualRepNumber) +' and entityID >0;'; if(ReadFromDatabase(sqlText,qry,readCount))then begin qry.First; while (not qry.Eof) do begin if not checkPedCountID then dataObj.PedCount := qry.Fields[0].AsInteger else begin dataObj.PedID := qry.Fields[0].AsInteger; dataObj.PedPathID := qry.Fields[1].AsInteger; end; if (not ProcessData(paData)) then Exit(); qry.Next; end; end; qry := nil; end; procedure TDatabasePedRW.Write(paData: TTraceDataObj); var dataObj: TPedTraceData; begin inherited; dataObj := TPedTraceData(paData); aParam[0] := ActualModelID; aParam[1] := ActualTraceID; aParam[2] := ActualRepNumber; aParam[3] := dataObj.PedID; aParam[4] := dataObj.PedPathID; WriteToDatabase(ttPed, aParam); end; { TDatabasePedBornDeathRW } function TDatabasePedStartEndRW.GetTraceType: TTraceType; begin Result := ttPedStartEnd; end; procedure TDatabasePedStartEndRW.Read(var paData: TTraceDataObj); var qry: TFDQuery; // pri inej stope iny record readCount: integer; dataObj: TPedStartEndTraceData; // pri inej stope ina trieda EventStartID: Variant; EventEndID: Variant; eventend,eventstart: Integer; sqlText: String; begin inherited; dataObj := TPedStartEndTraceData(paData); Filter.GetValue(coPedStartEvent, EventStartID); Filter.GetValue(coPedEndEvent, EventEndID); eventstart := EventStartID; eventend := EventEndID; sqlText := 'select n.pedid, n.entityid,n.simtime, n2.entityid, n2.simtime from (select pedid,entityid,simtime,eventype from pedevents where eventype = '+IntToStr(eventstart)+ ' and modelid = '+ IntToStr(ActualModelID) +' and traceid = '+ IntToStr(ActualTraceID) +' and replicationnumber = '+ IntToStr(ActualRepNumber) +' ) as n left join (select pedid,entityid,simtime,eventype from pedevents where eventype = '+ IntToStr(eventend)+' and modelid = '+ IntToStr(ActualModelID) +' and traceid = '+ IntToStr(ActualTraceID) +' and replicationnumber = '+ IntToStr(ActualRepNumber) +' ) as n2 on(n.pedid = n2.pedid);'; // pouzitie filtra - v kazdej stope moze byt iny, mozu sa kontrolovat // rozne veci, kontrola moze byt aj na zoznam povolenych, alebo nepovolenych hodnot if(ReadFromDatabase(sqlText, qry,readCount))then begin qry.First; while (not qry.Eof) do begin if( not qry.Fields[0].IsNull)then dataObj.PedID := qry.Fields[0].AsInteger; if( not qry.Fields[1].IsNull)then dataObj.StartID := qry.Fields[1].AsInteger; if( not qry.Fields[2].IsNull)then dataObj.StartTime := qry.Fields[2].AsDateTime; if( not qry.Fields[3].IsNull)then dataObj.EndID := qry.Fields[3].AsInteger else dataObj.EndID := Integer.MinValue; if( not qry.Fields[4].IsNull)then dataObj.EndTime := qry.Fields[4].AsDateTime else dataObj.EndTime := Double.MinValue; if( dataObj.EndTime <> Double.MinValue )then dataObj.Time := TimeToStr((Round(dataObj.EndTime * SecsPerDay) - Round(dataObj.StartTime * SecsPerDay))/SecsPerDay) else dataObj.Time := ''; if (not ProcessData(paData)) then Exit(); qry.Next; end; end; qry:= nil; end; { TDatabasePedModelRW } function TDatabasePedModelRW.GetTraceType: TTraceType; begin Result := ttPedModel; end; procedure TDatabasePedModelRW.Read(var paData: TTraceDataObj); begin inherited; end; procedure TDatabasePedModelRW.Write(paData: TTraceDataObj); var dataObj: TPedModelTraceData; begin inherited; dataObj := TPedModelTraceData(paData); aParam[0] := dataObj.ModelID; aParam[1] := dataObj.ModelName; WriteToDatabase(GetTraceType, aParam); end; { TDatabasePedTraceRW } function TDatabasePedTraceRW.GetTraceType: TTraceType; begin Result := ttPedTrace; end; procedure TDatabasePedTraceRW.Read(var paData: TTraceDataObj); begin inherited; end; procedure TDatabasePedTraceRW.Write(paData: TTraceDataObj); var dataObj: TPedTraceTraceData; begin inherited; dataObj := TPedTraceTraceData(paData); aParam[0] := dataObj.TraceID; aParam[1] := dataObj.TraceName; WriteToDatabase(GetTraceType, aParam); end; { TDatabasePedMacroGrapRW } function TDatabasePedMacroGrapRW.GetTraceType: TTraceType; begin Result := ttPedMacroGraph; end; procedure TDatabasePedMacroGrapRW.Read(var paData: TTraceDataObj); var qry: TFDQuery; readCount: integer; dataObj: TPedMacroGraphTraceData; // pri inej stope ina trieda sqlText: string; begin inherited; dataObj := TPedMacroGraphTraceData(paData); sqlText := 'SELECT m.EdgeID, m.SimTime, m.Density from macrograph m where m.modelid = '+ IntToStr(ActualModelID) +' and m.traceid = '+ IntToStr(ActualTraceID) +' and m.replicationnumber = '+ IntToStr(ActualRepNumber) +';'; if(ReadFromDatabase(sqlText,qry,readCount))then begin qry.First; while (not qry.Eof) do begin dataObj.EdgeID := qry.Fields[0].AsInteger; dataObj.SimTime := qry.Fields[1].AsExtended; dataObj.Density := qry.Fields[2].AsExtended; if (not ProcessData(paData)) then Exit(); qry.Next; end; end; qry := nil; end; procedure TDatabasePedMacroGrapRW.Write(paData: TTraceDataObj); var dataObj: TPedMacroGraphTraceData; begin inherited; dataObj := TPedMacroGraphTraceData(paData); aParam[0] := dataObj.EdgeID; aParam[1] := dataObj.SimTime; aParam[2] := dataObj.Density; WriteToDatabase(GetTraceType, aParam); end; { TDatabasePedElevator } function TDatabasePedElevator.GetTraceType: TTraceType; begin Result := ttPedElevator; end; procedure TDatabasePedElevator.Read(var paData: TTraceDataObj); var qry: TFDQuery; readCount: integer; dataObj: TPedElevatorTraceData; // pri inej stope ina trieda sqlText: string; begin inherited; dataObj := TPedElevatorTraceData(paData); sqlText := 'SELECT e.elevatorID, e.EventType, e.LevelID, e.Simtime from pedelevator e where e.modelid = '+ IntToStr(ActualModelID) +' and e.traceid = '+ IntToStr(ActualTraceID) +' and e.replicationnumber = '+ IntToStr(ActualRepNumber) +';'; if(ReadFromDatabase(sqlText,qry,readCount))then begin qry.First; while (not qry.Eof) do begin dataObj.ElevatorID := qry.Fields[0].AsInteger; dataObj.EventType := TStatElevatorEvent(qry.Fields[1].AsInteger); dataObj.LevelID := qry.Fields[2].AsInteger; dataObj.SimTime := qry.Fields[3].AsExtended; if (not ProcessData(paData)) then Exit(); qry.Next; end; end; qry := nil; end; procedure TDatabasePedElevator.Write(paData: TTraceDataObj); var dataObj: TPedElevatorTraceData; begin inherited; dataObj := TPedElevatorTraceData(paData); aParam[0] := dataObj.ElevatorID; aParam[1] := dataObj.EventType; aParam[2] := dataObj.LevelID; aParam[3] := dataObj.SimTime; WriteToDatabase(GetTraceType, aParam); end; end.
{ GS1 interface library for FPC and Lazarus Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru 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. } unit crpt_vvod_import_fts; {$mode objfpc}{$H+} interface uses Classes, SysUtils, xmlobject, AbstractSerializationObjects; type TProduct_Date = TDate; { TProduct } TProduct = class(TXmlSerializationObject) private Fki: string; procedure Setki(AValue: string); protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; public destructor Destroy; override; published property ki:string read Fki write Setki; end; TProducts = specialize GXMLSerializationObjectList<TProduct>; { TProductList } TProductList = class(TXmlSerializationObject) private FProducts: TProducts; protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; public destructor Destroy; override; published property Products:TProducts read FProducts; end; { TVvod_import_fts } TVvod_import_fts = class(TXmlSerializationObject) private Fdeclaration_date: TProduct_Date; Fdeclaration_number: string; FProductList: TProductList; Ftrade_participant_inn: string; FVersion: Integer; procedure Setdeclaration_date(AValue: TProduct_Date); procedure Setdeclaration_number(AValue: string); procedure Settrade_participant_inn(AValue: string); procedure SetVersion(AValue: Integer); protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; function RootNodeName:string; override; public constructor Create; destructor Destroy; override; published property Version:Integer read FVersion write SetVersion; property trade_participant_inn:string read Ftrade_participant_inn write Settrade_participant_inn; property declaration_number:string read Fdeclaration_number write Setdeclaration_number; property declaration_date:TProduct_Date read Fdeclaration_date write Setdeclaration_date; property ProductList:TProductList read FProductList; end; implementation { TProductList } procedure TProductList.InternalRegisterPropertys; begin inherited InternalRegisterPropertys; RegisterProperty('Products', 'product', [], '', -1, -1); end; procedure TProductList.InternalInitChilds; begin inherited InternalInitChilds; FProducts:=TProducts.Create; end; destructor TProductList.Destroy; begin FreeAndNil(FProducts); inherited Destroy; end; { TProduct } procedure TProduct.Setki(AValue: string); begin if Fki=AValue then Exit; Fki:=AValue; ModifiedProperty('ki'); end; procedure TProduct.InternalRegisterPropertys; var P: TPropertyDef; begin inherited InternalRegisterPropertys; P:=RegisterProperty('ki', 'ki', [xsaSimpleObject], '', -1, -1); end; procedure TProduct.InternalInitChilds; begin inherited InternalInitChilds; end; destructor TProduct.Destroy; begin inherited Destroy; end; { TVvod_import_fts } procedure TVvod_import_fts.Setdeclaration_date(AValue: TProduct_Date); begin if Fdeclaration_date=AValue then Exit; Fdeclaration_date:=AValue; ModifiedProperty('declaration_date'); end; procedure TVvod_import_fts.Setdeclaration_number(AValue: string); begin if Fdeclaration_number=AValue then Exit; Fdeclaration_number:=AValue; ModifiedProperty('declaration_number'); end; procedure TVvod_import_fts.Settrade_participant_inn(AValue: string); begin if Ftrade_participant_inn=AValue then Exit; Ftrade_participant_inn:=AValue; ModifiedProperty('trade_participant_inn'); end; procedure TVvod_import_fts.SetVersion(AValue: Integer); begin if FVersion=AValue then Exit; FVersion:=AValue; ModifiedProperty('Version'); end; procedure TVvod_import_fts.InternalRegisterPropertys; var P: TPropertyDef; begin inherited InternalRegisterPropertys; P:=RegisterProperty('trade_participant_inn', 'trade_participant_inn', [xsaSimpleObject], '', -1, -1); P:=RegisterProperty('declaration_number', 'declaration_number', [xsaSimpleObject], '', -1, -1); P:=RegisterProperty('declaration_date', 'declaration_date', [xsaSimpleObject], '', -1, -1); P:=RegisterProperty('Version', 'version', [], '', -1, -1); P.DefaultValue:='1'; P:=RegisterProperty('ProductList', 'products_list', [], '', -1, -1); end; procedure TVvod_import_fts.InternalInitChilds; begin inherited InternalInitChilds; FProductList:=TProductList.Create; end; function TVvod_import_fts.RootNodeName: string; begin Result:='vvod_import_fts'; end; constructor TVvod_import_fts.Create; begin inherited Create; Version:=1; end; destructor TVvod_import_fts.Destroy; begin FreeAndNil(FProductList); inherited Destroy; end; end.
unit UserSessionUnit; { This is a DataModule where you can add components or declare fields that are specific to ONE user. Instead of creating global variables, it is better to use this datamodule. You can then access the it using UserSession. } interface uses IWUserSessionBase, SysUtils, Classes, 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.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.UI, FireDAC.Comp.Client, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, IdHashMessageDigest; type TIWUserSession = class(TIWUserSessionBase) ConexaoBD: TFDConnection; FDQQuery: TFDQuery; FDGUIxWaitCursor1: TFDGUIxWaitCursor; FDPhysMySQLDriverLink1: TFDPhysMySQLDriverLink; private { Private declarations } public { Public declarations } glbUsuario, glbNomeUsuario, glbEmailUsuario, glbTipoUsuario, glbNomeEstabelecimento, glbApelidoEstabelecimento : String; glbIdEstabelecimento : Integer; function MD5(const texto:string):string; end; implementation {$R *.dfm} function TIWUserSession.MD5(const texto:string):string; var idmd5 : TIdHashMessageDigest5; begin idmd5 := TIdHashMessageDigest5.Create; try result := idmd5.HashStringAsHex(texto); finally idmd5.Free; end; end; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 16384,0,0} { by Behdad Esfahbod Algorithmic Problems Book April '2000 Problem 84 O(N3) Minumum Cut Method FordFulkerson Alg. } program ProjectOnTwoProcessors; const MaxN = 100; MaxD = 100; var N : Integer; G : array [1 .. MaxN + 2, 1 .. MaxN + 2] of Integer; F : array [1 .. MaxN + 2, 1 .. MaxN + 2] of Integer; Mark : array [1 .. MaxN + 2] of Boolean; Fl : Boolean; P : Longint; I, J : Integer; procedure ReadInput; begin Assign(Input, 'input.txt'); Reset(Input); Readln(Input, N); for I := 1 to N do begin Readln(G[N + 1, I], G[N + 2, I]); G[I, N + 1] := G[N + 1, I]; G[I, N + 2] := G[N + 2, I]; end; for I := 2 to N do begin for J := 1 to I - 1 do begin Read(G[I, J]); G[J, I] := G[I, J]; end; Readln; end; Close(Input); end; procedure WriteOutput; begin Assign(Output, 'output.txt'); Rewrite(Output); Writeln(P); for I := 1 to N do Writeln(2 - Byte(Mark[I])); Close(Output); end; function Min (A, B : Integer) : Integer; begin if A <= B then Min := A else Min := B; end; function Dfs (V, E : Integer) : Integer; var I, Eps : Integer; begin if V = N + 1 then begin Dfs := E; Exit; end; Mark[V] := True; for I := N + 1 downto 1 do if not Mark[I] and (F[V, I] < G[V, I]) then begin Eps := Dfs(I, Min(E, G[V, I] - F[V, I])); if Eps > 0 then begin Inc(F[V, I], Eps); F[I, V] := - F[V, I]; Dfs := Eps; Exit; end; end; Dfs := 0; end; procedure MinCut; begin while Dfs(N + 2, MaxInt) <> 0 do FillChar(Mark, SizeOf(Mark), 0); for I := 1 to N + 2 do for J := 1 to I - 1 do if Mark[I] xor Mark[J] then Inc(P, G[I, J]); end; begin ReadInput; MinCut; WriteOutput; end.
unit EQ2008_Function; interface Const EQ2008_Dll = 'EQ2008_Dll.dll'; //颜色常量 RED = $0000FF; GREEN = $00FF00; YELLOW = $00FFFF; //返回值常量 EQ_FALSE = 0; EQ_TRUE = 1; Type User_FontSet = Packed Record //字体设置 strFontName: String; //字体的名称 iFontSize: Longword ; //字体的大小 bFontBold: Longword; //字体是否加粗 bFontItaic: Longword; //字体是否是斜体 bFontUnderline: Longword; //字体是否带下划线 colorFont: Longword; //字体的颜色 iAlignStyle: Longword; //对齐方式 //0- 左对齐 //1-居中 //2-右对齐 iVAlignerStyle: Longword; //上下对齐方式 //0-顶对齐 //1-上下居中 //2-底对齐 iRowSpace: Longword; //行间距 End; PUser_FontSet = ^User_FontSet; User_PartInfo = Packed Record //字体设置 iX: Longword; //窗口的起点X iY: Longword; //窗口的起点Y iWidth: Longword; //窗体的宽度 iHeight: Longword; //窗体的高度 iFrameMode: Longword; //边框的样式 FrameColor: Longword; //边框颜色 End ; PUser_PartInfo = ^User_PartInfo; User_MoveSet = Packed Record iActionType: Longword; //节目变换方式 iActionSpeed: Longword; //节目的播放速度 bClear: Longword; //是否需要清除背景 iHoldTime: Longword; //在屏幕上停留的时间 iClearSpeed: Longword; //清除显示屏的速度 iClearActionType: Longword; //节目清除的变换方式 iFrameTime: Longword; End ; PUser_MoveSet = ^User_MoveSet; //“计时窗口” User_Timer = Packed Record PartInfo: User_PartInfo; //分区信息 BkColor: Longword; //背景颜色 FontInfo: User_FontSet; //字体设置 ReachTimeYear: Longword; //到达年 ReachTimeMonth: Longword; //到达月 ReachTimeDay: Longword; //到达日 ReachTimeHour: Longword; //到达时 ReachTimeMinute: Longword; //到达分 ReachTimeSecond: Longword; //到达秒 bDay: Longword; //是否显示天 0-不显示 1-显示 bHour: Longword; //是否显示小时 bMin: Longword; //是否显示分钟 bSec: Longword; //是否显示秒 bMulOrSingleLine: Longword; //单行还是多行 chTitle: String; //添加显示文字 End; PUser_Timer = ^User_Timer; //“温度窗口” User_Temperature = Packed Record PartInfo: User_PartInfo; //分区信息 BkColor: Longword; //背景颜色 FontInfo: User_FontSet; //字体设置 chTitle: String; //标题 iDisplayType: Longword; //显示格式:0-度 1-C End ; PUser_Temperature = ^User_Temperature; //“日期时间窗口” User_DateTime = Packed Record PartInfo: User_PartInfo; //分区信息 BkColor: Longword; //背景颜色 FontInfo: User_FontSet; //字体设置 iDisplayType: Longword; //显示风格 chTitle: String; //添加显示文字 bYearDisType: Longword; //年份位数0 -4;1-2位 bMulOrSingleLine: Longword; //单行还是多行 bYear: Longword; bMouth: Longword; bDay: Longword; bWeek: Longword; bHour: Longword; bMin: Longword; bSec: Longword; End; PUser_DateTime = ^User_DateTime; //“图文框” User_Bmp = Packed Record PartInfo: User_PartInfo; //分区信息 End; PUser_Bmp = ^User_Bmp; //“单行文本框” User_SingleText = Packed Record chContent: String; //显示内容 PartInfo: User_PartInfo; //分区信息 BkColor: Longword; //背景颜色 FontInfo: User_FontSet ; //字体设置 MoveSet: User_MoveSet; //动作方式设置 End; PUser_SingleText = ^User_SingleText; //“文本框” User_Text = Packed Record chContent: String; //显示内容 PartInfo: User_PartInfo ; //分区信息 BkColor: Longword; //背景颜色 FontInfo: User_FontSet ; //字体设置 MoveSet: User_MoveSet; //动作方式设置 End; PUser_Text = ^User_Text; //“RTF文件” User_RTF = Packed Record strFileName: String; //显示内容 PartInfo: User_PartInfo ; //分区信息 MoveSet: User_MoveSet; //动作方式设置 End; PUser_RTF = ^User_RTF; //1、节目编辑函数组 //添加节目 Function User_AddProgram (CardNum: Longword;bWaitToEnd: Boolean;iPlayTime: Longword): Longword; Stdcall; External EQ2008_Dll; //添加图文区 Function User_AddBmpZone (CardNum: Longword;pBmp: PUser_Bmp; iProgramIndex: Longword): Longword ; Stdcall; External EQ2008_Dll; Function User_AddBmp (CardNum: Longword;iBmpPartNum: Longword; hBitmap: Longword;pMoveSet: PUser_MoveSet; iProgramIndex: Longword): Longword; Stdcall; External EQ2008_Dll; //添加时间区 Function User_AddTime (CardNum: Longword; pDateTime: PUser_DateTime;iProgramIndex: Longword): Longword; Stdcall; External EQ2008_Dll; //添加倒计时区 Function User_AddTimeCount (CardNum: Longword;pTimeCount: PUser_Timer; iProgramIndex: Longword): Longword; Stdcall; External EQ2008_Dll; //添加温度区 Function User_AddTemperature (CardNum: Longword;pTemperature: PUser_Temperature;iProgramIndex: Longword): Longword ; Stdcall; External EQ2008_Dll; //添加文本区 Function User_AddText (CardNum: Longword;pText: PUser_Text; iProgramIndex: Longword): Longword; Stdcall; External EQ2008_Dll; //添加文本区 Function User_AddRTF (CardNum: Longword;pRTF: PUser_RTF; iProgramIndex: Longword): Longword; Stdcall; External EQ2008_Dll; //添加单行文本区 Function User_AddSingleText (CardNum: Longword; pSingleText: PUser_SingleText; iProgramIndex: Longword): Longword; Stdcall; External EQ2008_Dll; //删除所有节目 Function User_DelAllProgram (CardNum: Longword): Boolean; Stdcall; External EQ2008_Dll; //发送节目 Function User_SendToScreen (CardNum: Longword): Boolean ; Stdcall; External EQ2008_Dll; //2、实时更新数据函数组 //实时发送数据建立连接 Function User_RealtimeConnect(CardNum: Longword): Boolean ; Stdcall; External EQ2008_Dll; //实时发送图片句柄 Function User_RealtimeSendData(CardNum: Longword; x: Longword; y: Longword; iWidth: Longword; iHeight: Longword; hBitmap: Longword): Boolean ; Stdcall; External EQ2008_Dll; //实时发送图片文件 Function User_RealtimeSendBmpData(CardNum: Longword; x: Longword; y: Longword; iWidth: Longword; iHeight: Longword; strFileName:String): Boolean ; Stdcall; External EQ2008_Dll; //实时发送文本 Function User_RealtimeSendText(CardNum: Longword;x: Longword; y: Longword; iWidth: Longword; iHeight: Longword; strText: String; pFontInfo:PUser_FontSet): Boolean ; Stdcall; External EQ2008_Dll; //实时发送断开连接 Function User_RealtimeDisConnect(CardNum: Longword): Boolean ; Stdcall; External EQ2008_Dll; //实时发送清屏 Function User_RealtimeScreenClear(CardNum: Longword): Boolean ; Stdcall; External EQ2008_Dll; //3、显示屏控制函数组 //开屏 Function User_OpenScreen(CardNum: Longword): Boolean ; Stdcall; External EQ2008_Dll; //关屏 Function User_CloseScreen(CardNum: Longword): Boolean ; Stdcall; External EQ2008_Dll; //校正时间 Function User_AdjustTime(CardNum: Longword): Boolean ; Stdcall; External EQ2008_Dll; //亮度调节 Function User_SetScreenLight(CardNum: Longword; iLightDegreen: Longword): Boolean ; Stdcall; External EQ2008_Dll; //重新加载配置文件INI Function User_ReloadIniFile(strEQ2008_Dll_Set_Path: string): Boolean ; Stdcall; External EQ2008_Dll; implementation end.
unit dlg_ProrataNewExemptionUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Mask, Db, DBTables, Wwtable, wwdblook; type Tdlg_ProrataNewExemption = class(TForm) gb_ProrataYear: TGroupBox; Label5: TLabel; Label6: TLabel; ed_RollYear: TEdit; gb_OtherInformation: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; OKButton: TBitBtn; CancelButton: TBitBtn; cb_ExemptionCode: TwwDBLookupCombo; tb_ExemptionCodes: TwwTable; cb_HomesteadCode: TComboBox; ed_CountyAmount: TEdit; ed_MunicipalAmount: TEdit; ed_SchoolAmount: TEdit; Label7: TLabel; procedure OKButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ed_RollYearExit(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } EditMode, RollYear, ExemptionCode, HomesteadCode : String; CountyAmount, MunicipalAmount, SchoolAmount : LongInt; end; implementation {$R *.DFM} uses DataAccessUnit, GlblCnst, Utilitys, WinUtils; {=========================================================================} Procedure Tdlg_ProrataNewExemption.FormShow(Sender: TObject); begin _OpenTable(tb_ExemptionCodes, ExemptionCodesTableName, '', '', ThisYear, []); If _Compare(EditMode, emEdit, coEqual) then begin Caption := 'Edit the prorated exemption.'; ed_RollYear.Text := RollYear; MakeNonDataAwareEditReadOnly(ed_RollYear, False, ''); cb_ExemptionCode.SetFocus; _Locate(tb_ExemptionCodes, [ExemptionCode], '', []); cb_ExemptionCode.Text := ExemptionCode; cb_HomesteadCode.ItemIndex := cb_HomesteadCode.Items.IndexOf(HomesteadCode); ed_CountyAmount.Text := IntToStr(CountyAmount); ed_MunicipalAmount.Text := IntToStr(MunicipalAmount); ed_SchoolAmount.Text := IntToStr(SchoolAmount); end; {If _Compare(EditMode, emEdit, coEqual)} end; {FormShow} {=========================================================================} Procedure Tdlg_ProrataNewExemption.FormKeyPress( Sender: TObject; var Key: Char); begin If (Key = #13) then begin Perform(WM_NextDlgCtl, 0, 0); Key := #0; end; {If (Key = #13)} end; {FormKeyPress} {=========================================================================} Procedure Tdlg_ProrataNewExemption.ed_RollYearExit(Sender: TObject); begin cb_ExemptionCode.SetFocus; end; {ed_RollYearExit} {=========================================================================} Procedure Tdlg_ProrataNewExemption.OKButtonClick(Sender: TObject); begin RollYear := ed_RollYear.Text; ExemptionCode := cb_ExemptionCode.Text; HomesteadCode := cb_HomesteadCode.Text; try CountyAmount := StrToInt(ed_CountyAmount.Text); except CountyAmount := 0; end; try MunicipalAmount := StrToInt(ed_MunicipalAmount.Text); except MunicipalAmount := 0; end; try SchoolAmount := StrToInt(ed_SchoolAmount.Text); except SchoolAmount := 0; end; ModalResult := mrOK; end; {OKButtonClick} {================================================================} Procedure Tdlg_ProrataNewExemption.FormClose( Sender: TObject; var Action: TCloseAction); begin _CloseTablesForForm(Self); Action := caFree; end; end.
unit BCEditor.Utils; interface uses Winapi.Windows, System.Math, System.Classes, Vcl.Graphics, System.UITypes, BCEditor.Consts, BCEditor.Types; function CharWidthTable(AChar: Char): SmallInt; function GetBestTabConvertProc(TabWidth: Integer): TBCEditorTabConvertProc; function GetLeadingExpandedLength(const AStr: string; ATabWidth: Integer; ABorder: Integer = 0): Integer; function GetTextSize(AHandle: HDC; AText: PChar; ACount: Integer): TSize; function MessageDialog(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons): Integer; function MinMax(Value, MinValue, MaxValue: Integer): Integer; function RoundCorrect(Value: Real): LongInt; function TextExtent(ACanvas: TCanvas; const Text: string): TSize; function TextWidth(ACanvas: TCanvas; const Text: string): Integer; function TextHeight(ACanvas: TCanvas; const Text: string): Integer; procedure ClearList(var List: TList); procedure FreeList(var List: TList); procedure TextOut(ACanvas: TCanvas; X, Y: Integer; const Text: string); procedure TextRect(ACanvas: TCanvas; Rect: TRect; x, Y: Integer; const Text: string); implementation uses Vcl.Forms, Vcl.Dialogs, System.SysUtils, Vcl.Clipbrd; procedure FreeList(var List: TList); begin ClearList(List); if Assigned(List) then begin List.Free; List := nil; end; end; procedure ClearList(var List: TList); var i: Integer; begin if not Assigned(List) then Exit; for i := 0 to List.Count - 1 do if Assigned(List[i]) then begin TObject(List[i]).Free; List[i] := nil; end; List.Clear; end; function MessageDialog(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons): Integer; begin with CreateMessageDialog(Msg, DlgType, Buttons) do try HelpContext := 0; HelpFile := ''; Position := poMainFormCenter; Result := ShowModal; finally Free; end; end; function MinMax(Value, MinValue, MaxValue: Integer): Integer; begin Value := Min(Value, MaxValue); Result := Max(Value, MinValue); end; function GetHasTabs(Line: PChar; var CharsBefore: Integer): Boolean; begin Result := False; CharsBefore := 0; if Assigned(Line) then begin while Line^ <> BCEDITOR_NONE_CHAR do begin if Line^ = BCEDITOR_TAB_CHAR then Exit(True); Inc(CharsBefore); Inc(Line); end; end end; function ConvertTabs1(const Line: string; TabWidth: Integer; var HasTabs: Boolean): string; //var // pDest: PChar; // nBeforeTab: Integer; begin { Result := Line; // increment reference count only if GetHasTabs(Pointer(Line), nBeforeTab) then begin HasTabs := True; pDest := @Result[nBeforeTab + 1]; // this will make a copy of Line // We have at least one tab in the string, and the tab width is 1. // pDest points to the first tab char. We overwrite all tabs with spaces. repeat if (pDest^ = BCEDITOR_TAB_CHAR) then pDest^ := ' '; Inc(pDest); until (pDest^ = BCEDITOR_NONE_CHAR); end else HasTabs := False; } end; function ConvertTabs2n(const Line: string; TabWidth: Integer; var HasTabs: Boolean): string; var i, DestLen, TabCount, TabMask: Integer; pSrc, pDest: PChar; begin Result := Line; // increment reference count only if GetHasTabs(Pointer(Line), DestLen) then begin HasTabs := True; pSrc := @Line[1 + DestLen]; // We have at least one tab in the string, and the tab width equals 2^n. // pSrc points to the first tab char in Line. We get the number of tabs // and the length of the expanded string now. TabCount := 0; TabMask := (TabWidth - 1) xor $7FFFFFFF; repeat if pSrc^ = BCEDITOR_TAB_CHAR then begin DestLen := (DestLen + TabWidth) and TabMask; Inc(TabCount); end else Inc(DestLen); Inc(pSrc); until (pSrc^ = BCEDITOR_NONE_CHAR); // Set the length of the expanded string. SetLength(Result, DestLen); DestLen := 0; pSrc := PChar(Line); pDest := PChar(Result); // We use another TabMask here to get the difference to 2^n. TabMask := TabWidth - 1; repeat if pSrc^ = BCEDITOR_TAB_CHAR then begin i := TabWidth - (DestLen and TabMask); Inc(DestLen, i); // This is used for both drawing and other stuff and is meant to be BCEDITOR_TAB_CHAR and not BCEDITOR_SPACE_CHAR repeat pDest^ := BCEDITOR_TAB_CHAR; Inc(pDest); Dec(i); until (i = 0); Dec(TabCount); if TabCount = 0 then begin repeat Inc(pSrc); pDest^ := pSrc^; Inc(pDest); until (pSrc^ = BCEDITOR_NONE_CHAR); Exit; end; end else begin pDest^ := pSrc^; Inc(pDest); Inc(DestLen); end; Inc(pSrc); until (pSrc^ = BCEDITOR_NONE_CHAR); end else HasTabs := False; end; function ConvertTabs(const Line: string; TabWidth: Integer; var HasTabs: Boolean): string; var pSrc{, pDest}: PChar; begin HasTabs := False; Result := ''; pSrc := PChar(Line); while pSrc^ <> BCEDITOR_NONE_CHAR do begin if pSrc^ = BCEDITOR_TAB_CHAR then begin HasTabs := True; Result := Result + StringOfChar(BCEDITOR_SPACE_CHAR, TabWidth); end else Result := Result + pSrc^; Inc(pSrc); end; {Result := Line; // increment reference count only if GetHasTabs(Pointer(Line), DestLen) then begin HasTabs := True; pSrc := @Line[1 + DestLen]; // We have at least one tab in the string, and the tab width is greater // than 1. pSrc points to the first tab char in Line. We get the number // of tabs and the length of the expanded string now. TabCount := 0; repeat if pSrc^ = BCEDITOR_TAB_CHAR then begin DestLen := DestLen + TabWidth - DestLen mod TabWidth; Inc(TabCount); end else Inc(DestLen); Inc(pSrc); until (pSrc^ = BCEDITOR_NONE_CHAR); // Set the length of the expanded string. SetLength(Result, DestLen); DestLen := 0; pSrc := PChar(Line); pDest := PChar(Result); repeat if pSrc^ = BCEDITOR_TAB_CHAR then begin i := TabWidth - (DestLen mod TabWidth); Inc(DestLen, i); repeat pDest^ := BCEDITOR_TAB_CHAR; Inc(pDest); Dec(i); until (i = 0); Dec(TabCount); if TabCount = 0 then begin repeat Inc(pSrc); pDest^ := pSrc^; Inc(pDest); until (pSrc^ = BCEDITOR_NONE_CHAR); Exit; end; end else begin pDest^ := pSrc^; Inc(pDest); Inc(DestLen); end; Inc(pSrc); until (pSrc^ = BCEDITOR_NONE_CHAR); end else HasTabs := False; } end; function IsPowerOfTwo(TabWidth: Integer): Boolean; var nW: Integer; begin nW := 2; repeat if (nW >= TabWidth) then Break; Inc(nW, nW); until (nW >= $10000); // we don't want 64 kByte spaces... Result := (nW = TabWidth); end; function GetBestTabConvertProc(TabWidth: Integer): TBCEditorTabConvertProc; begin {if (TabWidth < 2) then Result := TBCEditorTabConvertProc(@ConvertTabs1) else if IsPowerOfTwo(TabWidth) then Result := TBCEditorTabConvertProc(@ConvertTabs2n) else } Result := TBCEditorTabConvertProc(@ConvertTabs); end; function GetLeadingExpandedLength(const AStr: string; ATabWidth: Integer; ABorder: Integer = 0): Integer; var iRun: PChar; Len: Integer; begin Result := 0; iRun := PChar(AStr); if ABorder > 0 then Len := Min(PInteger(iRun - 2)^, ABorder) else Len := PInteger(iRun - 2)^; while Len > 0 do begin if iRun^ = BCEDITOR_TAB_CHAR then Inc(Result, ATabWidth - (Result mod ATabWidth)) else if iRun^ = BCEDITOR_SPACE_CHAR then Inc(Result) else Exit; Inc(iRun); Dec(Len); end; end; { Full-width ranges: U-16 U-8 U-16 U-8 1100 e1 84 80 .. 115F e1 85 9f 2329 e2 8c a9 .. 232A e2 8c aa 2E80 e2 ba 80 .. 303E e3 80 be 3041 e3 81 81 .. 33FF e3 8f bf 3400 e3 90 80 .. 4DB5 e4 b6 b5 4E00 e4 b8 80 .. 9FC3 e9 bf 83 A000 ea 80 80 .. A4C6 ea 93 86 AC00 ea b0 80 .. D7A3 ed 9e a3 F900 ef a4 80 .. FAD9 ef ab 99 FE10 ef b8 90 .. FE19 ef b8 99 FE30 ef b8 b0 .. FE6B ef b9 ab FF01 ef bc 81 .. FF60 ef bd a0 FFE0 ef bf a0 .. FFE6 ef bf a6 20000 f0 a0 80 80 .. 2FFFD f0 af bf bd 30000 f0 b0 80 80 .. 3FFFD f0 bf bf bd Actually, they are incomplete. One can easily find character out of this range which is actually full-width but doesn't fall in any of ranges above. Also, there are characters even wider than full-width, which take 3 or even 4 regular spaces in text } function CharWidthTable(AChar: Char): SmallInt; begin Result := 1; if (AChar >= #$1100) and (AChar <= #$115F) then Result := 2 else if (AChar >= #$2329) and (AChar <= #$232A) then Result := 2 else if (AChar >= #$2E80) and (AChar <= #$303E) then Result := 2 else if (AChar >= #$3041) and (AChar <= #$33FF) then Result := 2 else if (AChar >= #$3400) and (AChar <= #$4DB5) then Result := 2 else if (AChar >= #$4E00) and (AChar <= #$9FC3) then Result := 2 else if (AChar >= #$A000) and (AChar <= #$A4C6) then Result := 2 else if (AChar >= #$AC00) and (AChar <= #$D7A3) then Result := 2 else if (AChar >= #$F900) and (AChar <= #$FAD9) then Result := 2 else if (AChar >= #$FE10) and (AChar <= #$FE19) then Result := 2 else if (AChar >= #$FE30) and (AChar <= #$FE6B) then Result := 2 else if (AChar >= #$FF01) and (AChar <= #$FF60) then Result := 2 else if (AChar >= #$FFE0) and (AChar <= #$FFE6) then Result := 2; end; function GetTextSize(AHandle: HDC; AText: PChar; ACount: Integer): TSize; begin Result.cx := 0; Result.cy := 0; GetTextExtentPoint32W(AHandle, AText, ACount, Result); end; type TAccessCanvas = class(TCanvas) end; function TextExtent(ACanvas: TCanvas; const Text: string): TSize; begin with TAccessCanvas(ACanvas) do begin RequiredState([csHandleValid, csFontValid]); Result := GetTextSize(Handle, PChar(Text), Length(Text)); end; end; function TextWidth(ACanvas: TCanvas; const Text: string): Integer; begin Result := TextExtent(ACanvas, Text).cx; end; function TextHeight(ACanvas: TCanvas; const Text: string): Integer; begin Result := TextExtent(ACanvas, Text).cy; end; procedure TextOut(ACanvas: TCanvas; x, Y: Integer; const Text: string); begin with TAccessCanvas(ACanvas) do begin Changing; RequiredState([csHandleValid, csFontValid, csBrushValid]); if CanvasOrientation = coRightToLeft then Inc(x, BCEditor.Utils.TextWidth(ACanvas, Text) + 1); Winapi.Windows.ExtTextOutW(Handle, x, Y, TextFlags, nil, PChar(Text), Length(Text), nil); MoveTo(x + BCEditor.Utils.TextWidth(ACanvas, Text), Y); Changed; end; end; procedure TextRect(ACanvas: TCanvas; Rect: TRect; X, Y: Integer; const Text: string); var Options: Longint; begin with TAccessCanvas(ACanvas) do begin Changing; RequiredState([csHandleValid, csFontValid, csBrushValid]); Options := ETO_CLIPPED or TextFlags; if Brush.Style <> bsClear then Options := Options or ETO_OPAQUE; if ((TextFlags and ETO_RTLREADING) <> 0) and (CanvasOrientation = coRightToLeft) then Inc(X, BCEditor.Utils.TextWidth(ACanvas, Text) + 1); Winapi.Windows.ExtTextOutW(Handle, X, Y, Options, @Rect, PChar(Text), Length(Text), nil); Changed; end; end; function RoundCorrect(Value: Real): LongInt; begin Result:= Trunc(Value); if Frac(Value) >= 0.5 then Result := Result + 1; end; end.
unit Mail_Queue; interface uses Classes, SyncObjs, IdSMTP, IdMessage, IdComponent, IdCoderHeader, SIP_RingList; type TMailQueue=class(TThread) private SMTP:TIdSMTP; Mail:TIdMessage; MailList:TThreadList; Event:TEvent; From:String; FSIPApp:TObject; procedure MailInitializeISO(var VTransferHeader: TTransfer; var VHeaderEncoding: Char; var VCharSet: string); procedure SMTPStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: String); procedure Send(Email,Body, Subject:String); procedure Reconnect; protected procedure Execute;override; public constructor Create(SMTPHost,SMTPPort,SMTPUser,SMTPPassword,SMTPFrom:String;App:TObject); destructor Destroy;override; procedure Add(const Name,Email,Body,Subject:String;Address:TSIPAddress;QueueID:Cardinal); end; implementation uses SysUtils, Logger, Windows, SIP_Monitor, SIP_App, SIP_QueueManager; { TMailQueue } procedure TMailQueue.SMTPStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: String); var S:String; begin case AStatus of hsResolving:S:='resolving '+AStatusText; hsConnecting:S:='connecting '+AStatusText; hsConnected:S:='connected '+AStatusText; hsDisconnecting:S:='disconnecting '+AStatusText; hsDisconnected:S:='disconnected '+AStatusText; hsStatusText:S:=AStatusText; end; if Log<>nil then Log.Debug(S); end; type TMail=class(TObject) EMail:String; Body:String; Subject:String; Name:String; Address:TSIPAddress; QueueID:Cardinal; end; procedure TMailQueue.Add(const Name, Email, Body, Subject: String;Address:TSIPAddress;QueueID:Cardinal); var S:TMail; begin S:=TMail.Create; S.Name:=Name; S.Email:=Email; S.Body:=Body; S.Subject:=Subject; S.Address:=Address; S.QueueID:=QueueID; TSIPApp(FSIPApp).SIPQueueManager.StartMail(Address,QueueID); MailList.Add(S); Event.SetEvent; end; constructor TMailQueue.Create; begin FSIPApp:=App; SMTP:=TidSMTP.Create(nil); SMTP.MailAgent:='asos'; SMTP.OnStatus:=SMTPStatus; SMTP.Host :=SMTPHost; SMTP.Port :=StrToIntDef(SMTPPort,25); SMTP.UserName:=SMTPUser; SMTP.Password:=SMTPPassword; Mail:=TIdMessage.Create(nil); Mail.Encoding:=mePlainText; Mail.ConvertPreamble:=True; Mail.OnInitializeISO := MailInitializeISO; From:=SMTPFrom; Event:=TEvent.Create(nil,True,False,'',False); MailList:=TThreadList.Create; inherited Create(False); end; destructor TMailQueue.Destroy; begin Terminate; Event.SetEvent; inherited; FreeAndNil(Mail); FreeAndNil(SMTP); end; procedure TMailQueue.Execute; var S:TMail; L:TList; begin while not Terminated do begin L:=MailList.LockList; S:=nil; try SIPMonitor.Count_Mail:=L.Count; if L.Count>0 then begin S:=L[0]; L.Delete(0); end; if (L.Count<=0) then Event.ResetEvent; finally MailList.UnlockList; end; if S<>nil then begin try try //s.Address.Status:='изпращане на EMail'; Send(s.EMail,s.Body,s.Subject); s.Address.AddReport('Успешно изпратен EMail('+S.Name+') към '+s.EMail); TSIPApp(FSIPApp).SIPQueueManager.Succeed(s.Address,s.QueueID,pkMail); except on E:Exception do begin s.Address.AddReport('Неуспешно изпращане на EMail('+S.Name+') към '+s.EMail+' : '+E.Message); TSIPApp(FSIPApp).SIPQueueManager.Fail(s.Address,s.QueueID,pkMail); if Log<>nil then Log.Error('Грешка при изпращане към "'+s.EMail+'" на EMail "'+s.Body+'" : '+E.Message); end; end; finally FreeAndNil(S); end; end else Reconnect; if not Terminated then Event.WaitFor(15000); end; end; procedure TMailQueue.MailInitializeISO(var VTransferHeader: TTransfer; var VHeaderEncoding: Char; var VCharSet: string); begin VCharSet:='windows-1251'; end; procedure TMailQueue.Reconnect; begin if SMTP.Host='' then Exit; try try SMTP.Connect; SIPMonitor.Status_Mail:=GetTick64; finally SMTP.Disconnect; end; except end; end; procedure TMailQueue.Send(Email, Body, Subject: String); begin if SMTP.Host='' then begin Log.Error('Липсва настройка на SMTP Host. Не е изпратено съобщение до '+EMail); raise Exception.Create('липсва настройка SMTP Host'); end; Mail.Clear; Mail.Charset:='windows-1251'; Mail.AddHeader('X-Generator: asos'); Mail.From.Address:=From; Mail.Recipients.EmailAddresses:=Email; Mail.Subject:=Subject; Mail.Body.Text:=Body; if SMTP.Connected then SMTP.Disconnect; SMTP.Connect; try SIPMonitor.Status_Mail:=GetTick64; SMTP.Send(Mail); finally if SMTP.Connected then SMTP.Disconnect; end; end; end.
unit uGMV_Engine; { ================================================================================ * * Application: Vitals * Revision: $Revision: 1 $ $Modtime: 5/05/09 1:44p $ * Developer: andrey.andriyevskiy@va.gov * Site: Hines OIFO * * Description: This unit isolates VistA RPC * * Notes: * ================================================================================ * $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSUTILS/uGMV_Engine.pas $ * * $ History: uGMV_Engine.pas $ * * 2007-07-12,16,17 zzzzzzandria * Parameter verification * Formatting of the source code } interface uses {$IFDEF REDIRECTOR} uHEVDR_PCall {$ELSE} fROR_PCall {$ENDIF} , Classes , SysUtils ; function getStationInfo: string; function getEXEInfo(anEXEName: string): string; function getDLLInfo(anEXEName: string): string; function getALLPatientData(aPatient, aFrom, aTo: string): TStringList; // Date and Time function getCurrentDateTime: string; // uGMV_DateTime function convertMDate(aValue: string): string; // uGMVMDateTime function getServerWDateTime: TDateTime; function getServerWDelay: TDateTime; function getServerWDateTimeString: string; function getUserParameter: string; // uGMV_User function getUserSignOnInfo: TStringList; function getUserSettings(aName: string): string; function setUserSettings(aName, aValue: string): string; function getUserDUZString: string; // System parameters function getSystemParameterByName(aName: string): string; // fGMV_Manager function getWebLinkAddress: string; // Qualifiers function getVitalQualifierList(aVital: string): TStringList; // fGMV_Qualifiers function getQualifiers(aVital, aCategory: string): TStringList; // uGMV_QualifyBox function getCategoryQualifiers(aVital: string): TStringList; // mGMV_EditTemplate function addQualifier(aVitalID, aCategoryID, aQualifierID: string): string; function delQualifier(aVitalID, aCategoryID, aQualifierID: string): string; function addNewQualifier(aName: string): string; function validateQualifierName(aFDD, aIEN, aField, aName: string): string; function setQualifierName(aFDD, aIEN, aField, aName: string): string; //Patients {$IFNDEF DLL} function getPatientList(aTarget: string): TStringList; {$ENDIF} // Files and Fields function getFileEntries(aFile: string): TStringList; // uGMV_FileEntry function getFileField(aFile, aField, anIEN: string): string; // Vitals function getVitalsIDList: TStringList; function getVitalTypeIEN(aVital: string): string; // fGMV_SupO2 function getVitalCategoryIEN(aCategory: string): string; function getTemplateList: TStringList; // fGMV_InputTemp function addVM(aValue: string): string; function getPatientInfo(aPatient: string): TStringList; function getPatientHeader(aPatient: string): TStringList; //procedure logPatientAccess(aPatient:String);// fGMV_PtSelect function logPatientAccess(aPatient: string): string; function getNursingUnitPatients(aUnit: string): TStringList; // mGMV_PtLookup function getWardPatients(aWard: string): TStringList; function getTeamPatients(aTeam: string): TStringList; function getClinicPatients(aClinic, aDate: string): TStringList; function getLookupEntries(aFile, aTarget: string): TStringList; // mGMV_Lookup function newTemplate(aCategory, aName, aValue: string): string; procedure setTemplate(anID, aName, aValue: string); function renameTemplate(anID, aName, aNewName: string): string; function getTemplateValue(anID, aName: string): string; function setDefaultTemplate(anID, aName: string): string; function getDefaultTemplateByID(anID: string): string; function getDefaultTemplateList: TStringList; function getTemplateListByID(anID: string): TStringList; function createUserTemplateByName(aName: string): string; function deleteUserTemplate(aName: string): string; function deleteTemplate(aCategory, aName: string): string; function createContext(aContext: string): Boolean; // uGMV_User function EngineReady: Boolean; function getLatestVitalsByDFN(aDFN: string; aSilent: Boolean): TStringList; function getHospitalLocationByID(anID: string): string; function getWardLocations(anOption: string = ''): TStringList; function getRoomBedByWard(aWard: string): TStringList; function getProcedureResult(aProc, aParam: string): string; function getGMVRecord(aParam: string): TStringList; function setGMVErrorRecord(aParam: string): TStringList; function getPatientINQInfo(aINQ, aDFN: string): TStringList; // ????? function getPatientAllergies(aDFN: string): TStringList; //// Manager /////////////////////////////////////////////////////////////////// // // Manager calls are not used in the DLL // so we will include them in this module later some time... // function printQualifierTable(aX, aY: string): string; function getGUIVersionList: TStringList; function setSystemParameter(aName, aValue, anOption: string): string; function getVitalHiLo(aVitalType: string): string; function setVitalHiLo(aVitalType, aValue: string): string; function getDeviceList(aTarget, aMargin: string; Direction: Integer = 1): string; function getLocationsByName(aTarget: string): string; function getLocationsByAppt(aDFN, aFrom, aTo, aFlag: string): string; function getLocationsByAdmit(aDFN: string): string; //function getClinicsByName(aStartFrom,aCount,aDirection:String):String; function getClinicFileEntriesByName(aStartFrom, aCount, aDirection: string): TStringList; // zzzzzzandria 060810 function getClosestReading(aDFN, aDate, aType, aDirection: string): String; var ServerDelay: TDateTime; CheckBrokerFlag: Boolean; implementation uses Dialogs, uGMV_Common , uGMV_Const , fGMV_RPCLog , uGMV_FileEntry, uGMV_VersionInfo, uGMV_RPC_Names, uGMV_Log ; //////////////////////////////////////////////////////////////////////////////// function CallRPC(RemoteProcedure: string; Parameters: array of string; MultList: TStringList = nil; RPCMode: TRPCMode = []; RetList: TStrings = nil): Boolean; var anItem: TRPCEventItem; aStart, aStop: TDateTime; aList: TStrings; iLimit: Integer; i: integer; SL: TStringList; begin aStart := Now; Result := CallRemoteProc(RPCBroker, RemoteProcedure, Parameters, MultList, RPCMode, RetList); aStop := Now; if RetList = nil then aList := RPCBroker.Results else aList := RetList; anItem := getRPCEventItem(aStart, aStop, RemoteProcedure, Parameters, MultList, RPCMode, aList ); SL := TStringList.Create; for i := Low(parameters) to High(Parameters) do SL.Add(Parameters[i]); Inc(RPCCount); RPCLog.InsertObject(0, Format('%10.10d ', [RPCCount]) + FormatDateTime('hh:mm:ss.zzz', aStart) + ' ' + RemoteProcedure + ' (' + SL.CommaText + ')' // zzzzzzandria 060724 , anItem); SL.Free; iLimit := 300; if assigned(frmGMV_RPCLog) then iLimit := StrToIntDef(frmGMV_RPCLog.ComboBox1.Text, iLimit); while RPCLog.Count > iLimit do begin if RPCLog.Objects[RPCLog.Count - 1] <> nil then TRPCEventItem(RPCLog.Objects[RPCLog.Count - 1]).Free; RPCLog.Delete(RPCLog.Count - 1); end; if assigned(frmGMV_RPCLog) then begin frmGMV_RPCLog.lbLog.Items.Assign(RPCLog); frmGMV_RPCLog.lbLog.ItemIndex := 0; frmGMV_RPCLog.lbLogClick(nil); end; end; //////////////////////////////////////////////////////////////////////////////// function getRPCResultStringList(aProcedure: string; ParamLST: array of string; RPCMode: TRPCMode = []): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(aProcedure, ParamLST, nil, RPCMode, SL); Result := SL; end; function getRPCResultString(aProcedure: string; ParamLST: array of string; RPCMode: TRPCMode = []): string; var SL: TStringList; begin try SL := getRPCResultStringList(aProcedure, ParamLST, RPCMode); Result := SL.Text; except Result := '-1^Error'; end; end; //////////////////////////////////////////////////////////////////////////////// // The next RPC is used to retrieve Patient information. // It is used only once in module fGMV_PtInfo (see line 51). // By default aINQ is equal to RPC_PATIENTINFO = 'ORWPT PTINQ'; // the user settings could overwrite the default value. //////////////////////////////////////////////////////////////////////////////// function getPatientINQInfo(aINQ, aDFN: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(aINQ, [aDFN], nil, [rpcSilent, rpcNoResChk], SL); Result := SL; end; (* function getProcedureResultList(aProc,aParam:String):TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(aProc, [aParam], nil,[rpcNoResChk,rpcSilent],SL); Result := SL; end; *) function getGMVRecord(aParam: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_GMV_RECORD, [aParam], nil, [rpcNoResChk, rpcSilent], SL); Result := SL; end; function setGMVErrorRecord(aParam: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_GMV_MARK_ERROR, [aParam], nil, [rpcNoResChk, rpcSilent], SL); Result := SL; end; //============================================================================== function getGUIVersionList: TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_PARAMETER, ['GETLST', 'SYS', 'GMV GUI VERSION'], nil, [rpcSilent, rpcNoResChk], SL); Result := SL; end; function getEXEInfo(anEXEName: string): string; begin CallRPC(RPC_PARAMETER, ['GETPAR', 'SYS', 'GMV GUI VERSION', anExeName], nil); Result := RPCBroker.Results[0]; end; function getDLLInfo(anEXEName: string): string; begin CallRPC(RPC_DLL_VERSION, [anExeName], nil); Result := RPCBroker.Results[0]; end; function getALLPatientData(aPatient, aFrom, aTo: string): TStringList; var i: Integer; SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_PATIENT_VITALS_ALL, [aPatient + '^' + aFrom + '^' + aTo + '^0'], nil, []); if RPCBroker.Results.Count > 4 then for i := RPCBroker.Results.Count - 1 downto 4 do SL.Add(RPCBroker.Results[i]); Result := SL; end; function getCurrentDateTime: string; begin // TEST FOR PARAMETERS // Formally the next RPC does not require parameters. // But without parameters it generates error in some environments // if CallRPC(RPC_CurrentTime, [], nil,[rpcSilent,rpcNoResChk]) then if CallRPC(RPC_CurrentTime, ['1'], nil, [rpcSilent, rpcNoResChk]) then // dummy parameter Result := RPCBroker.Results[0] else Result := ''; end; function convertMDate(aValue: string): string; begin if CallRPC(RPC_DATE_CONVERT, [aValue], nil, []) and (RPCBroker.Results.Count > 0) then Result := Piece(RPCBroker.Results[0], '^', 1) else Result := ''; end; function getStationInfo: string; var s: string; begin s := ''; if CallRPC(RPC_PATIENT_SELECT, ['CCOW'], nil, []) then s := RPCBroker.Results[0]; Result := s; end; function getPatientList(aTarget: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_PATIENT_SELECT, ['PTLKUP', '', aTarget], nil, [rpcSilent, rpcNoResChk], SL); Result := SL; end; function logPatientAccess(aPatient: string): string; begin Result := ''; // 060929 zzzzzzandria LOGSECURITY or LOGSEC ? // CallRPC(RPC_PATIENT_SELECT, ['LOGSEC', aPatient, 'RPCCALL^Clinical Procedure GUI v1'], CallRPC(RPC_PATIENT_SELECT, ['LOGSEC', aPatient, RPC_CREATECONTEXT + '^' + CurrentExeNameAndVersion], nil, [rpcSilent, rpcNoResChk]); // 2008-03-10 zzzzzzandria LOGSECURITY was used before fix // CallRPC(RPC_PATIENT_SELECT, ['LOGSECURITY', aPatient, 'RPCCALL^Clinical Procedure GUI v1'], // nil, [rpcSilent, rpcNoResChk]); Result := RPCBroker.Results[0] end; function getPatientInfo(aPatient: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_PATIENT_SELECT, ['SELECT', aPatient], nil, [rpcSilent, rpcNoresChk], SL); Result := SL; end; function getPatientHeader(aPatient: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_PATIENT_SELECT, ['PTHDR', aPatient], nil, [rpcSilent, rpcNoresChk], SL); Result := SL; end; function getServerWDateTime: TDateTime; begin try Result := FMDateTimeToWindowsDateTime(StrToFloat(getCurrentDateTime)); except on E: Exception do Result := 0; end; end; function getServerWDateTimeString: string; begin try Result := FormatDateTime(GMV_DateTimeFormat, FMDateTimeToWindowsDateTime(StrToFloat(getCurrentDateTime))); except on E: Exception do Result := ''; end; end; function getServerWDelay: TDateTime; begin Result := getServerWDateTime - Now; end; //////////////////////////////////////////////////////////////////////////////// // System Parameters //////////////////////////////////////////////////////////////////////////////// function getSystemParameterByName(aName: string): string; // fGMV_Manager begin if CallRPC(RPC_PARAMETER, ['GETPAR', 'SYS', aName], nil, [rpcSilent, rpcNoResChk]) then Result := RPCBroker.Results[0] else Result := ''; end; function getWebLinkAddress: string; begin Result := getSystemParameterByName('GMV WEBLINK'); end; function setSystemParameter(aName, aValue, anOption: string): string; begin CallRPC(RPC_PARAMETER, ['SETPAR', 'SYS', aName, aValue, anOption], nil, []); Result := RPCBroker.Results[0]; end; function getUserParameter: string; // uGMV_User begin if CallRPC(RPC_PARAMETER, ['GETPAR', 'SYS', 'GMV ALLOW USER TEMPLATES'], nil, [], nil) then Result := RPCBroker.Results[0] else Result := ''; end; function getUserSignOnInfo: TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_USER, ['SIGNON', ''], nil, [rpcSilent, rpcNoResChk], SL); Result := SL; end; function getUserDUZString: string; var SL: TStringList; begin SL := getUserSignOnInfo; if SL.Count > 0 then Result := SL[0] else Result := ''; SL.Free; end; function getUserSettings(aName: string): string; begin (* .. ABNORMALBGCOLOR 15 ABNORMALBOLD OFF ABNORMALQUALIFIERS OFF ABNORMALTEXTCOLOR 9 CLINIC_INDEX -1 CPRSMetricStyle VitalsMetricStyle CloseInputWindowAfterSave DoNotCloseInputWindow ConversionWarningStatus ON DefaultTemplate 114;DIC(4.2,|WARD GRAPH OPTIONS VISIBLE 1 GRAPHCOLOR -2147483643 GRAPHOPTIONS ON GRAPHOPTIONS-1 OFF GRAPHOPTIONS-2 OFF GRAPHOPTIONS-3 ON GRAPHOPTIONS-4 ON GRAPH_INDEX 8 GRIDSIZE 314 GridDateRange 15 LastVitalsListHeight 144 NORMALBGCOLOR 15 NORMALBOLD OFF NORMALQUALIFIERS OFF NORMALTEXTCOLOR 0 OneUnavailableBox ManyUnavailableBoxes ParamTreeWidth 165 RefuseStatus ON SELECTOR_TAB 4 SearchDelay 1.0 ShowLastVitals NoLatestVitals ShowTemplates NoTemplates TEAM_INDEX -1 TfrmGMV_InputLite 1024;768;360;0;640;480;0 UNIT_INDEX -1 UnavailableStatus ON VIEW-HEIGHT 519 VIEW-LEFT 363 VIEW-TOP 7 VIEW-WIDTH 640 VitalsLite 1024;768;361;34;640;480;0 WARD_INDEX -1 *) try if CallRPC(RPC_USER, ['GETPAR', aName], nil, [rpcSilent, rpcNoResChk]) then Result := RPCBroker.Results[0] else Result := ''; except on E: Exception do Result := ''; end; end; function setUserSettings(aName, aValue: string): string; begin if CallRPC(RPC_USER, ['SETPAR', aName + '^' + aValue], nil, [rpcSilent, rpcNoResChk]) then Result := RPCBroker.Results[0] else Result := '-1^Unknown Error'; end; function getVitalQualifierList(aVital: string): TStringList; var SL: TStringList; begin // ? SL := TStringList.Create; CallRPC(RPC_VITALS_QUALIFIERS, [aVital], nil, [rpcSilent, rpcNoResChk], SL); Result := SL end; function getQualifiers(aVital, aCategory: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_MANAGER, ['GETQUAL', aVital + ';' + aCategory], nil, [], SL); Result := SL; end; function getCategoryQualifiers(aVital: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_MANAGER, ['GETCATS', aVital], nil, [rpcSilent, rpcNoResChk], SL); Result := SL; end; function getFileEntries(aFile: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_MANAGER, ['GETLIST', aFile], nil, [], SL); Result := SL; end; function getFileField(aFile, aField, anIEN: string): string; begin if CallRPC(RPC_MANAGER, ['GETDATA', aFile + '^' + anIEN + '^' + aField], nil, [rpcSilent, rpcNoResChk], nil) then Result := RPCBroker.Results[0] else Result := ''; end; function getLookupEntries(aFile, aTarget: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_MANAGER, ['LOOKUP', aFile + '^' + aTarget], nil, [rpcSilent, rpcNoResChk], SL); Result := SL; end; function getVitalsIDList: TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_MANAGER, ['VT', ''], nil, [rpcNoResChk], SL); Result := SL; end; function getVitalTypeIEN(aVital: string): string; begin // ? if CallRPC(RPC_VITAL_TYPE_IEN, [aVital], nil, [rpcSilent, rpcNoResChk], nil) then Result := RPCBroker.Results[0] else Result := ''; end; function getVitalCategoryIEN(aCategory: string): string; begin if CallRPC(RPC_VITAL_CATEGORY_IEN, [aCategory], nil, [], nil) then Result := RPCBroker.Results[0] else Result := ''; end; function getTemplateList: TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_MANAGER, ['GETTEMP'], nil, [rpcSilent, rpcNoresChk], SL); Result := SL; end; function addVM(aValue: string): string; begin if CallRPC(RPC_VITAL_ADD_VALUE, [aValue], nil, [rpcSilent, rpcNoresChk]) then Result := '' else Result := RPCBroker.Results.Text; end; function getNursingUnitPatients(aUnit: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_NUR_UNIT_PATIENTS, [aUnit], nil, [rpcNoResChk, rpcSilent], SL); Result := SL; end; function getWardPatients(aWard: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_WARD_PATIENTS, [aWard], nil, [rpcNoResChk, rpcSilent], SL); Result := SL; end; function getTeamPatients(aTeam: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_TEAM_PATIENTS, [aTeam], nil, [rpcNoResChk, rpcSilent], SL); Result := SL; end; function getClinicPatients(aClinic, aDate: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_CLINIC_PATIENTS, [aClinic, aDate], nil, [rpcNoResChk, rpcSilent], SL); Result := SL; end; //============================================================================== function newTemplate(aCategory, aName, aValue: string): string; begin CallRPC(RPC_MANAGER, ['NEWTEMP', aCategory + '^' + aName + '^' + aValue], nil, []); Result := RPCBroker.Results[0] end; procedure setTemplate(anID, aName, aValue: string); begin CallRPC(RPC_MANAGER, ['SETTEMP', anID + '^' + aName + '^' + aValue], nil, []); end; function renameTemplate(anID, aName, aNewName: string): string; begin CallRPC(RPC_MANAGER, ['RENTEMP', anID + '^' + aName + '^' + aNewname], nil, [rpcNoResChk, rpcSilent]); //zzzzzzandria 051229 Result := RPCBroker.Results[0]; end; function getTemplateValue(anID, aName: string): string; begin try if CallRPC(RPC_MANAGER, ['GETTEMP', anID + '^' + aName], nil, []) then Result := RPCBroker.Results[1] else Result := ''; except Result := ''; end; end; function setDefaultTemplate(anID, aName: string): string; begin if CallRPC(RPC_MANAGER, ['SETDEF', anID + '^' + aName], nil, []) then Result := RPCBroker.Results[0] else Result := '-1'; end; function getDefaultTemplateByID(anID: string): string; begin try if CallRPC(RPC_MANAGER, ['GETDEF', anID], nil, []) then Result := RPCBroker.Results[0] else Result := '-1'; except Result := '-1'; end; end; function getDefaultTemplateList: TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_MANAGER, ['GETDEF'], nil, [rpcNoResChk, rpcSilent], SL); Result := SL; end; function getTemplateListByID(anID: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; if anID <> '' then CallRPC(RPC_MANAGER, ['GETTEMP', anID], nil, [], SL) else CallRPC(RPC_MANAGER, ['GETTEMP'], nil, [], SL); Result := SL; end; function createUserTemplateByName(aName: string): string; begin try if CallRPC(RPC_MANAGER, ['NEWTEMP', 'USR^' + aName + '^No Description'], nil, [rpcNoResChk]) then Result := RPCBroker.Results[0] else Result := '-1'; except Result := '-1'; end; end; function deleteTemplate(aCategory, aName: string): string; begin try if CallRPC(RPC_MANAGER, ['DELTEMP', aCategory + '^' + aName], nil, []) then Result := RPCBroker.Results[0] else Result := '-1^Unknown Error'; except Result := '-1^Unknown Error'; end; end; function deleteUserTemplate(aName: string): string; begin Result := deleteTemplate('USR', aName); end; //////////////////////////////////////////////////////////////////////////////// function createContext(aContext: string): Boolean; begin Result := RPCBroker.CreateContext(aContext); end; function EngineReady: Boolean; begin Result := Assigned(RPCBroker); end; function getLatestVitalsByDFN(aDFN: string; aSilent: Boolean): TStringList; var SL: TStringList; begin SL := TStringList.Create; try if aSilent then CallRPC(RPC_PATIENT_LATEST_VITALS, [aDFN], nil, [rpcNoResChk, rpcSilent], SL) else CallRPC(RPC_PATIENT_LATEST_VITALS, [aDFN], nil, [], SL); except end; Result := SL; end; function getHospitalLocationByID(anID: string): string; begin // zzzzzzandria 2007-07-17 ----------------------------------------------- Begin Result := ''; if trim(anID) = '' then Exit; // zzzzzzandria 2007-07-17 ----------------------------------------------- End try if CallRPC(RPC_PATIENT_SELECT, ['HOSPLOC', anID], nil, [rpcNoResChk, rpcSilent]) then Result := RPCBroker.Results[0] else Result := ''; except Result := ''; end; end; function getWardLocations(anOption: string = ''): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_WARD_LOCATION, [anOption], nil, [], SL); Result := SL; end; function getRoomBedByWard(aWard: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_ROOM_BED, [aWard], nil, [], SL); Result := SL; end; function getProcedureResult(aProc, aParam: string): string; begin try if CallRPC(aProc, [aParam], nil, [rpcNoResChk, rpcSilent]) then Result := RPCBroker.Results[0] else Result := 'Procedure ' + aProc + '(' + aParam + ') Failed'; except Result := 'Procedure ' + aProc + '(' + aParam + ') Failed'; end; end; function getPatientAllergies(aDFN: string): TStringList; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_PATIENT_ALLERGIES, [aDFN], nil, [], SL); Result := SL; end; //////////////////////////////////////////////////////////////////////////////// function printQualifierTable(aX, aY: string): string; begin CallRPC(RPC_QUALIFIER_TABLE, ['^^^^' + aX + '^^' + aY], nil); Result := RPCBroker.Results[0] end; function addQualifier(aVitalID, aCategoryID, aQualifierID: string): string; begin CallRPC(RPC_MANAGER, ['ADDQUAL', aVitalID + ';' + aCategoryID + ';' + aQualifierID], nil); Result := RPCBroker.Results[0] end; function delQualifier(aVitalID, aCategoryID, aQualifierID: string): string; begin CallRPC(RPC_MANAGER, ['DELQUAL', aVitalID + ';' + aCategoryID + ';' + aQualifierID], nil); Result := RPCBroker.Results[0] end; function AddNewQualifier(aName: string): string; begin CallRPC(RPC_MANAGER, ['NEWQUAL', aName], nil); Result := RPCBroker.Results[0] end; function validateQualifierName(aFDD, aIEN, aField, aName: string): string; begin CallRPC(RPC_MANAGER, ['VALID', aFDD + '^' + aIEN + '^' + aField + '^' + aName], nil, []); Result := RPCBroker.Results[0]; end; function setQualifierName(aFDD, aIEN, aField, aName: string): string; begin CallRPC(RPC_MANAGER, ['SETDATA', aFDD + '^' + aIEN + '^' + aField + '^' + aName], nil, []); Result := RPCBroker.Results[0]; end; function getVitalHiLo(aVitalType: string): string; begin if aVitalType = '6.2' then // 6.2 - min CVP value could be below 0 CallRPC(RPC_MANAGER, ['GETHILO', aVitalType], nil, [rpcSilent]) else CallRPC(RPC_MANAGER, ['GETHILO', aVitalType], nil, []); Result := RPCBroker.Results[0]; end; function setVitalHiLo(aVitalType, aValue: string): string; begin CallRPC(RPC_MANAGER, ['SETHILO', aVitalType + '^' + aValue], nil, []); Result := RPCBroker.Results[0]; end; function getDeviceList(aTarget, aMargin: string; Direction: Integer = 1): string; begin CallRPC(RPC_CHECK_DEVICE, [aTarget, IntToStr(Direction), aMargin], nil, [rpcNoResChk, rpcSilent]); Result := RPCBroker.Results.Text; end; function getLocationsByName(aTarget: string): string; var SL: TStringList; begin SL := TStringList.Create; CallRPC(RPC_LOCATION_SELECT, ['NAME', aTarget], nil, [rpcNoResChk, rpcSilent], SL); Result := SL.Text; SL.Free; end; function getLocationsByAppt(aDFN, aFrom, aTo, aFlag: string): string; begin // zzzzzzandria 2007-07-16 ----------------------------------------------- Begin Result := ''; if trim(aDFN) = '' then Exit; // zzzzzzandria 2007-07-16 ----------------------------------------------- End CallRPC(RPC_LOCATION_SELECT, ['APPT', aDFN + '^' + aFrom + '^' + aTo + '^' + aFlag], nil, [rpcNoResChk, rpcSilent]); Result := RPCBroker.Results.Text; end; function getLocationsByAdmit(aDFN: string): string; begin Result := ''; if trim(aDFN) = '' then Exit; CallRPC(RPC_LOCATION_SELECT, ['ADMIT', aDFN], nil, [rpcNoResChk, rpcSilent]); Result := RPCBroker.Results.Text; end; function getClinicsByName(aStartFrom, aCount, aDirection: string): string; begin CallRPC(RPC_LOCATION_SELECT, ['CLINIC', aStartFrom + '^' + aCount + '^' + aDirection], nil, [rpcNoResChk, rpcSilent]); Result := RPCBroker.Results.Text; end; function getClinicFileEntriesByName(aStartFrom, aCount, aDirection: string): TStringList; var SL: TStringList; i: Integer; fe: TGMV_FileEntry; begin CallRPC(RPC_LOCATION_SELECT, ['CLINIC', aStartFrom + '^' + aCount + '^' + aDirection], nil, [rpcNoResChk, rpcSilent]); if copy(RPCBroker.Results.Text, 1, 1) = '-' then begin Result := nil; Exit; end; SL := TStringList.Create; for i := 1 to RPCBroker.Results.Count - 1 do begin fe := TGMV_FileEntry.CreateFromRPC(RPCBroker.Results[i]); // SL.AddObject(fe.CaptionConverted, fe); // zzzzzzandria 2008-04-17 SL.AddObject(fe.Caption, fe); end; Result := SL; end; function getClosestReading(aDFN, aDate, aType, aDirection: string): String; begin Result := ''; if trim(aDFN) = '' then Exit; CallRPC(RPC_CLOSEST_READING, [aDFN, aDate,aType,aDirection], nil, [rpcNoResChk, rpcSilent]); Result := RPCBroker.Results.Text; end; initialization CheckBrokerFlag := False; end.
unit delphi_intf_1; interface type IUnknown = interface procedure QueryInterface(const IID: TGUID; out Intf); stdcall; function _AddRef: Int32; stdcall; function _Release: Int32; stdcall; end external 'SYS'; IMyIntf = interface(IUnknown) function GetInt: Int32; procedure SetInt(V: Int32); end external 'SYS'; function GetIntf: IMyIntf; external 'SYS'; implementation var G: Int32; procedure Test; var I: IMyIntf; begin I := GetIntf(); I.SetInt(12); G := I.GetInt(); end; initialization Test(); finalization Assert(G = 12); end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995-2002 Borland Software Corporation } { } {*******************************************************} unit ActnColorMaps; interface uses Classes, Graphics, ActnMan; type { TStandardColorMap } TStandardColorMap = class(TCustomActionBarColorMap) protected procedure SetColor(const Value: TColor); override; public procedure UpdateColors; override; published // HighlightColor and UnusedColor should stream before Color property HighlightColor; property UnusedColor; property BtnFrameColor default clBtnFace; property BtnSelectedColor default clBtnFace; property BtnSelectedFont default clWindowText; property Color default clBtnFace; property DisabledFontColor default clGrayText; property DisabledFontShadow default clBtnHighlight; property FontColor default clWindowText; property HotColor default clDefault; property HotFontColor default clDefault; property MenuColor default clBtnFace; property FrameTopLeftInner default clBtnHighlight; property FrameTopLeftOuter default clBtnFace; property FrameBottomRightInner default clBtnShadow; property FrameBottomRightOuter default clBlack; property DisabledColor default clDefault; property SelectedColor default clMenuHighlight; property SelectedFontColor default clHighlightText; property ShadowColor default clBtnShadow; property OnColorChange; end; { TXPColorMap } TXPColorMap = class(TCustomActionBarColorMap) public procedure UpdateColors; override; published property ShadowColor default cl3DDkShadow; property Color default clBtnFace; property DisabledColor default clGray; property DisabledFontColor default clGrayText; property DisabledFontShadow default clBtnHighlight; property FontColor default clWindowText; property HighlightColor; property HotColor default clDefault; property HotFontColor default clDefault; property MenuColor default clWindow; property FrameTopLeftInner default clWhite; property FrameTopLeftOuter default $007A868A; property FrameBottomRightInner default clWhite; property FrameBottomRightOuter default $007A868A; property BtnFrameColor default $00C66931; property BtnSelectedColor default clWhite; property SelectedColor default $00EFD3C6; property SelectedFontColor default clBlack; property UnusedColor; property OnColorChange; end; { TTwilightColorMap } TTwilightColorMap = class(TCustomActionBarColorMap) public procedure UpdateColors; override; published property Color default clBlack; property DisabledFontColor default clGrayText; property DisabledFontShadow default clBlack; property FontColor default clWhite; property HighlightColor; property HotColor default clDefault; property HotFontColor default clWhite; property FrameTopLeftInner default clBlack; property FrameTopLeftOuter default cl3DDkShadow; property FrameBottomRightInner default clBlack; property FrameBottomRightOuter default cl3DDkShadow; property BtnFrameColor default cl3DDkShadow; property BtnSelectedColor default cl3DDkShadow; property MenuColor default clBlack; property DisabledColor default clDefault; property SelectedColor default cl3dDkShadow; property SelectedFontColor default clBlack; property ShadowColor default clBlack; property UnusedColor default clBlack; property OnColorChange; end; implementation uses GraphUtil; { TStandardColorMap } procedure TStandardColorMap.SetColor(const Value: TColor); begin if Value <> Color then begin HighlightColor := GetHighlightColor(Value); UnusedColor := GetHighlightColor(Value, 10); end; inherited; end; procedure TStandardColorMap.UpdateColors; begin inherited; BtnFrameColor := clBtnFace; BtnSelectedColor := clBtnFace; BtnSelectedFont := clWindowText; Color := clBtnFace; MenuColor := clBtnFace; DisabledFontColor := clGrayText; DisabledFontShadow := clBtnHighlight; DisabledColor := clDefault; FontColor := clWindowText; FrameTopLeftInner := clBtnHighlight; FrameTopLeftOuter := clBtnFace; FrameBottomRightInner := clBtnShadow; FrameBottomRightOuter := clBlack; HighlightColor := GetHighlightColor(Color); HotColor := clDefault; HotFontColor := clDefault; SelectedColor := clHighlight; SelectedFontColor := clHighlightText; ShadowColor := clBtnShadow; UnusedColor := GetHighlightColor(Color, 18); end; { TXPColorMap } procedure TXPColorMap.UpdateColors; begin inherited; Color := clBtnFace; MenuColor := clWindow; BtnFrameColor := $00C66931; BtnSelectedColor := clBtnFace; DisabledFontColor := clGrayText; DisabledFontShadow := clBtnHighlight; DisabledColor := clGray; FontColor := clWindowText; FrameTopLeftInner := clWhite; FrameTopLeftOuter := $007A868A; FrameBottomRightInner := clWhite; FrameBottomRightOuter := $007A868A; HighlightColor := GetHighLightColor(clBtnFace, 15); HotColor := clDefault; HotFontColor := clDefault; SelectedColor := $00EFD3C6; SelectedFontColor := clBlack; ShadowColor := cl3DDkShadow; UnusedColor := GetHighLightColor(clBtnFace, 15); end; { TTwilightColorMap } procedure TTwilightColorMap.UpdateColors; begin inherited; Color := clBlack; MenuColor := clBlack; DisabledFontColor := clGrayText; DisabledFontShadow := clBlack; DisabledColor := cl3DDkShadow; FontColor := clWhite; FrameTopLeftInner := clBlack; FrameTopLeftOuter := cl3DDkShadow; FrameBottomRightInner := clBlack; FrameBottomRightOuter := cl3DDkShadow; HighlightColor := clBlack; HotColor := clDefault; HotFontColor := clWhite; BtnSelectedColor := cl3DDkShadow; SelectedColor := cl3DDkShadow; SelectedFontColor := clBlack; ShadowColor := clBlack; UnusedColor := clBlack; end; end.
unit uMainForm; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Imaging.Jpeg, // GLScene GLScene, GLVectorFileObjects, GLObjects, GLTexture, GLVectorLists, GLCadencer, GLWin32Viewer, GLSimpleNavigation, GLPostEffects, GLCrossPlatform, GLMeshUtils, GLVectorGeometry, GLMaterial, GLCoordinates, GLBaseClasses, GLRenderContextInfo, GLUtils, GLFileMD2 // TGA, // GLFileObj, // GLFile3DS, // GLFileSMD, ; type TMainForm = class(TForm) GLScene1: TGLScene; GLCamera1: TGLCamera; GLMaterialLibrary1: TGLMaterialLibrary; GLCadencer1: TGLCadencer; GLActor1: TGLActor; Label1: TLabel; GLLightSource1: TGLLightSource; Panel1: TPanel; GLSceneViewer1: TGLSceneViewer; ComboBox1: TComboBox; GLPostEffect1: TGLPostEffect; Label2: TLabel; GLSimpleNavigation1: TGLSimpleNavigation; procedure GLCadencer1Progress(Sender: TObject; const DeltaTime, newTime: Double); procedure FormCreate(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure GLPostEffect1CustomEffect(Sender: TObject; var rci: TRenderContextInfo; var Buffer: TGLPostEffectBuffer); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.GLCadencer1Progress(Sender: TObject; const DeltaTime, newTime: Double); begin GLSceneViewer1.Invalidate; end; procedure TMainForm.FormCreate(Sender: TObject); begin SetGLSceneMediaDir; // GLMaterialLibrary1.TexturePaths := MediaPath; GLActor1.LoadFromFile('waste.md2'); GLActor1.Material.Texture.Image.LoadFromFile('waste.jpg'); GLActor1.Material.Texture.Enabled := True; GLActor1.SwitchToAnimation(GLActor1.Animations[0]); GLActor1.AnimationMode := aamLoop; GLActor1.ObjectStyle := GLActor1.ObjectStyle + [osDirectDraw]; GLActor1.Reference := aarMorph; end; procedure TMainForm.ComboBox1Change(Sender: TObject); begin case ComboBox1.ItemIndex of 0: GLPostEffect1.Preset := pepNone; 1: GLPostEffect1.Preset := pepGray; 2: GLPostEffect1.Preset := pepNegative; 3: GLPostEffect1.Preset := pepDistort; 4: GLPostEffect1.Preset := pepNoise; 5: GLPostEffect1.Preset := pepNightVision; 6: GLPostEffect1.Preset := pepBlur; 7: GLPostEffect1.Preset := pepCustom; end; end; {$R-} // Turn off range checking. procedure TMainForm.GLPostEffect1CustomEffect(Sender: TObject; var rci: TRenderContextInfo; var Buffer: TGLPostEffectBuffer); var I: Longword; begin for I := 0 to High(Buffer) do begin Buffer[I].r := Round(Buffer[I + 5].r * 2); Buffer[I].g := Round(Buffer[I].g * 1.5); Buffer[I].b := Round(Buffer[I + 5].b * 1.5); end; end; {$R+} end.
unit UMainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ActnList, Menus, ImgList, PlatformDefaultStyleActnCtrls, ActnMan, ActnCtrls, ComCtrls, ToolWin, ActnMenus, StdActns, ExtActns, ExtCtrls, RpCon, RpConDS, RpRave, RpDefine, RpBase, RpSystem; type TMainForm = class(TForm) ActionMainMenuBar1: TActionMainMenuBar; StatusBar1: TStatusBar; CoolBar1: TCoolBar; ActionToolBar1: TActionToolBar; ActionToolBar2: TActionToolBar; ImageList: TImageList; Timer1: TTimer; RvSystem1: TRvSystem; RvProject1: TRvProject; ItemRvDataSetConnection: TRvDataSetConnection; ActionManager: TActionManager; SearchAction: TAction; RegAction: TAction; FileExit1: TFileExit; CascadeAction: TAction; TileAction: TAction; ArrangeIconsAction: TAction; MinimizeAllAction: TAction; DefaultAction: TAction; AboutAction: TAction; CloseAction: TAction; AllCloseAction: TAction; ReportAction: TAction; procedure SearchActionExecute(Sender: TObject); procedure RegActionExecute(Sender: TObject); procedure CascadeActionExecute(Sender: TObject); procedure TileActionExecute(Sender: TObject); procedure ArrangeIconsActionExecute(Sender: TObject); procedure MinimizeAllActionExecute(Sender: TObject); procedure DefaultActionExecute(Sender: TObject); procedure AboutActionExecute(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure CloseActionExecute(Sender: TObject); procedure AllCloseActionExecute(Sender: TObject); procedure ReportActionExecute(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation uses USearchForm, URegForm, ABOUT, UAppStoreDM; {$R *.dfm} procedure TMainForm.AboutActionExecute(Sender: TObject); begin AboutBox := TAboutBox.Create(application); AboutBox.Show; end; procedure TMainForm.AllCloseActionExecute(Sender: TObject); var I: Integer; begin for I := MDIChildCount - 1 downto 0 do MDIChildren[I].Close; end; procedure TMainForm.ArrangeIconsActionExecute(Sender: TObject); begin ArrangeIcons; end; procedure TMainForm.CascadeActionExecute(Sender: TObject); begin Cascade; end; procedure TMainForm.CloseActionExecute(Sender: TObject); begin if ActiveMDIChild <> nil then ActiveMDIChild.Close; end; procedure TMainForm.DefaultActionExecute(Sender: TObject); var I: Integer; begin for I := MDIChildCount - 1 downto 0 do begin MDIChildren[I].WindowState := wsNormal; MDIChildren[I].Height := 600; MDIChildren[I].Width := 760; MDIChildren[I].left := 0; MDIChildren[I].top := 0; end; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TMainForm.FormShow(Sender: TObject); begin Height := 768; Width := 1024; Timer1.Enabled := true; StatusBar1.panels[0].text := '앱 스토어 관리 프로그램 Ver 1.0.0'; application.ProcessMessages; end; procedure TMainForm.MinimizeAllActionExecute(Sender: TObject); var I: Integer; begin for I := MDIChildCount - 1 downto 0 do MDIChildren[I].WindowState := wsMinimized; end; procedure TMainForm.RegActionExecute(Sender: TObject); begin RegForm := TRegForm.Create(Application); RegForm.Show; end; procedure TMainForm.ReportActionExecute(Sender: TObject); begin RvProject1.ExecuteReport('ItemReport'); end; procedure TMainForm.SearchActionExecute(Sender: TObject); begin SearchForm := TSearchForm.Create(Application); SearchForm.Show; end; procedure TMainForm.TileActionExecute(Sender: TObject); begin Tile; end; procedure TMainForm.Timer1Timer(Sender: TObject); begin StatusBar1.panels[2].text := formatdatetime('yyyy-mm-dd hh:nn:ss', now) + ' '; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 2010-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Androidapi.Consts; interface resourcestring SJNIRTTINotAvailable = 'RTTI for type %s was not found. Perhaps missing {$M+}?'; SJNIClassNotFound = 'Java class %s could not be found'; SJNIType = '%s is not a valid Java type'; SInternalBindingError = 'Internal error creating binding for ''%s'''; SBadJNIClass = '''%s'' must be an interface derived from IJavaClass'; SBadJNIInstance = '''%s'' must be an interface derived from IJavaInstance'; SErrorCreatingJNIObject = 'Unable to create Java object for instance of ''%s'''; SJNIInvokeError = 'Fatal error invoking interface'; SInvalidJNIType = 'The type ''%s'' is not supported with jni interoperability'; SJNINoInterface = 'No implemented interface found in ''%s'''; SJNIMethodNotFound = 'Invoke error: method ''%s'' not found'; SJNIUnknownMethod = 'Invoke error: method not found'; SJNIInvalidSetter = 'Method ''%s'' is not a valid property setter'; SJNIInvalidGetter = 'Method ''%s'' is not a valid property getter'; // In-App Billing messages SUnknown = 'Unknown'; SOk = 'OK'; SUserCanceled = 'User Canceled'; SBillingUnavailable = 'Billing Unavailable'; SItemUnavailable = 'Item unavailable'; SDeveloperError = 'Developer Error'; SError = 'Error'; SItemAlreadyOwned = 'Item Already Owned'; SItemNotOwned = 'Item not owned'; SRemoteExceptionOccurred = 'Remote exception during initialization'; SBadResponse = 'Bad response received'; SVerificationFailed = 'Purchase signature verification failed'; SSendIntentFailed = 'Send intent failed'; SUnknownPurchaseResponse = 'Unknown purchase response'; SMissingToken = 'Missing token'; SUnknownError = 'Unknown error'; SSubscriptionsNotavailable = 'Subscriptions not available'; SInvalidConsumption = 'Invalid consumption attempt'; SIABUnavailable = 'Billing service unavailable on device.'; SIABv3NotFound = 'Error checking for billing v3 support.'; SSuccess = 'Success'; SPurchaseDataParse = 'Failed to parse purchase data.'; SNullReturn = 'IAB returned null purchaseData or dataSignature'; SNullInResultData = 'Null data in IAB result'; SSignatureFailureFmt = 'Signature verification failed for sku %s'; SBuyFailure = 'Unable to buy item'; SPurchaseProblem = 'Problem purchashing item.'; SSetupOK = 'Setup successful.'; SConsumeOKFmt = 'Successful consume of sku %s'; SInventoryRefreshOK = 'Inventory refresh successful.'; SNoSubscriptions = 'Subscriptions are not available.'; sSetupException = 'RemoteException while setting up in-app billing.'; SConsumeErrorFmt = 'Remote exception while consuming. PurchaseInfo: %s'; SIABNotSetUpErrorFmt = 'IAB helper is not set up. Can''t perform operation: %s'; SCantConsumeThoseErrorFmt = 'Items of type ''%s'' can''t be consumed.'; SSkuTokenMissingErrorFmt = 'PurchaseInfo is missing token for sku: %s %s'; SIntentSendError = 'Failed to send intent.'; SBadIntentResponseCodeType = 'Unexpected type for intent response code: %s'; SBadBundleResponseCodeType = 'Unexpected type for bundle response code: %s'; SAsyncInProgressError = 'Can''t start async operation (%s) because another async operation(%s) is in progress.'; SSkuConsumptionErrorFmt = 'Error consuming sku %s'; SPurchaseFlowError = 'Remote exception while starting purchase flow'; SInventoryRefreshRemoteError = 'Remote exception while refreshing inventory.'; SInventoryJSONError = 'Error parsing JSON response while refreshing inventory.'; SInventoryRefreshOwnedItemsError = 'Error refreshing inventory (querying owned items).'; SInventoryRefreshItemPricesError = 'Error refreshing inventory (querying prices of items).'; SInventoryRefreshOwnedSubsError = 'Error refreshing inventory (querying owned subscriptions).'; SInventoryRefreshSubsPricesError = 'Error refreshing inventory (querying prices of subscriptions).'; implementation end.
{$I SBDemo.inc} unit DemoForm; interface uses {$IFNDEF MSWINDOWS} Types, {$ENDIF} SysUtils, Classes, Windows, Forms, Messages, Controls, StdCtrls, Graphics, ImgList, ComCtrls, Dialogs, ExtCtrls, Tabs, Menus, DBCtrls, Buttons, {$IFNDEF VER130} Variants, {$ENDIF} DemoBase, DemoFrame {$IFDEF XPMAN}, UxTheme{$ENDIF} {$IFDEF USE_SYNEDIT}, SynMemo, SynEdit, SynEditHighlighter, SynHighlighterPas{$ENDIF} ; type TDemoForm = class(TForm) MainPanel: TPanel; Shape1: TShape; pnTopLabel: TPanel; Panel2: TPanel; pnSource: TPanel; Panel6: TPanel; Panel3: TPanel; sbOpenDemoDir: TSpeedButton; pnDemo: TPanel; sbDemo: TSpeedButton; pnShowSource: TPanel; lbTitle: TLabel; Panel1: TPanel; btRandom: TSpeedButton; procedure FormCreate(Sender: TObject); virtual; procedure sbOpenDemoDirClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure sbDemoClick(Sender: TObject); procedure btRandomClick(Sender: TObject); protected Demos: TDemos; FRandomized: boolean; //Product customization function ApplicationTitle: string; virtual; abstract; //This function should return DAC product specific title procedure RegisterDemos; virtual; abstract; //This procedure should regiter DAC product specific demos //XP manifest function GetIsXPMan: boolean; {$IFDEF XPMAN} procedure ReplaceFlatStyle(Control: TWinControl; Flat: boolean); {$ENDIF} //Demo selection procedure InitializeDemoFrame(Frame: TDemoFrame; DemoType: TDemoType); virtual; procedure UpdateDemo; public {$IFDEF USE_SYNEDIT} SourceBrowser: TSynMemo; {$ELSE} SourceBrowser: TMemo; {$ENDIF} function ProductColor: TColor; virtual; abstract; //This function should return DAC product specific color procedure Randomize; property Randomized: boolean read FRandomized; end; implementation {$IFNDEF FPC} {$R *.dfm} {$ENDIF} {$IFDEF XPMAN} {$R WindowsXP.res} {$ENDIF} uses RandomForm, ScBridge; procedure TDemoForm.FormCreate(Sender: TObject); begin Demos := TDemos.Create; RegisterDemos; {$IFDEF XPMAN} if GetIsXPMan then begin ReplaceFlatStyle(Self, False); pnTopLabel.Color := ProductColor; end; {$ENDIF} {$IFDEF USE_SYNEDIT} SourceBrowser := TSynMemo.Create(pnSource); SourceBrowser.Highlighter := TSynPasSyn.Create(SourceBrowser); SourceBrowser.Options := [eoAltSetsColumnMode, eoAutoIndent, eoAutoSizeMaxScrollWidth, eoDisableScrollArrows, eoDragDropEditing, eoDropFiles, eoEnhanceEndKey, eoGroupUndo, eoHideShowScrollbars, eoKeepCaretX, eoShowScrollHint, eoSmartTabDelete, eoSmartTabs, eoTabIndent, eoTabsToSpaces]; with SourceBrowser.Gutter do begin Visible := True; AutoSize := True; DigitCount := 3; LeftOffset := 0; RightOffset := 0; ShowLineNumbers := True; Width := 1; end; {$ELSE} SourceBrowser := TMemo.Create(pnSource); SourceBrowser.ScrollBars := ssVertical; SourceBrowser.Font.Name := 'Courier New'; SourceBrowser.Font.Size := 10; {$ENDIF} with SourceBrowser do begin Parent := pnSource; Align := alClient; ReadOnly := True; end; Resize; UpdateDemo; end; procedure TDemoForm.FormDestroy(Sender: TObject); begin Demos.Free; end; //Sizing constraints function TDemoForm.GetIsXPMan: boolean; begin Result := {$IFDEF XPMAN}UseThemes; {$ELSE} False;{$ENDIF} end; {$IFDEF XPMAN} procedure TDemoForm.ReplaceFlatStyle(Control: TWinControl; Flat: boolean); var i: integer; begin for i := 0 to Control.ControlCount - 1 do if Control.Controls[i] is TSpeedButton then TSpeedButton(Control.Controls[i]).Flat := Flat else if Control.Controls[i] is TDBNavigator then TDBNavigator(Control.Controls[i]).Flat := Flat else if Control.Controls[i] is TWinControl then begin if Control.Controls[i] is TPanel then begin TPanel(Control.Controls[i]).ParentBackground := False; if Control.Controls[i].Tag <> 0 then TPanel(Control.Controls[i]).Color := ProductColor else TPanel(Control.Controls[i]).Color := clBtnFace; end; ReplaceFlatStyle(TWinControl(Control.Controls[i]), Flat); end; end; {$ENDIF} //Demo Change procedure TDemoForm.InitializeDemoFrame(Frame: TDemoFrame; DemoType: TDemoType); begin Frame.Parent := pnDemo; Frame.Initialize; {$IFDEF XPMAN} if GetIsXPMan then ReplaceFlatStyle(Frame, False); {$ENDIF} end; procedure TDemoForm.UpdateDemo; begin // for i := 1 to StatusBar.Panels.Count - 1 do // StatusBar.Panels[i].Text := ''; with Demos.SelectDemo(1) do begin InitializeDemoFrame(Frame, DemoType); LoadDemoCode(SourceBrowser.Lines); //Load demo sources if DemoType = dtCategory then begin pnSource.Visible := False; pnDemo.Visible := True; sbDemo.Enabled := False; end else begin sbDemo.Enabled := True; if sbDemo.Down then begin pnSource.Visible := True; pnDemo.Visible := False; end; end; Self.Caption := ApplicationTitle + ' - ' + Hint; Application.Title := Self.Caption; end; // StatusBar.Repaint; end; procedure TDemoForm.sbOpenDemoDirClick(Sender: TObject); begin Demos.SelectedDemo.OpenDemoFolder; end; procedure TDemoForm.sbDemoClick(Sender: TObject); begin with sbDemo do if Down then begin pnSource.Visible := True; pnDemo.Visible := False; Caption := 'Show demo' end else begin pnSource.Visible := False; pnDemo.Visible := True; Caption := 'Show source' end; end; procedure TDemoForm.Randomize; begin fmRandom := TfmRandom.Create(Self); try if fmRandom.ShowModal = mrOk then begin Random.Randomize(fmRandom.Data); FRandomized := True; end; finally fmRandom.Free; end; end; procedure TDemoForm.btRandomClick(Sender: TObject); begin Self.Randomize; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Buttons; type { TfrmMarkUp } TfrmMarkUp = class(TForm) bmbReset: TBitBtn; edtWholesale: TEdit; gpbWholesale: TGroupBox; gpbSelling: TGroupBox; gpbMarkUp: TGroupBox; lblSelling: TLabel; spdFifteen: TSpeedButton; spdTwenty: TSpeedButton; spdTwentyFive: TSpeedButton; procedure bmbResetClick(Sender: TObject); procedure gpbWholesaleClick(Sender: TObject); procedure spdFifteenClick(Sender: TObject); procedure spdTwentyClick(Sender: TObject); procedure spdTwentyFiveClick(Sender: TObject); private { private declarations } procedure SellingPrice(Input: TEdit; Markup: double; Output: TLabel); public { public declarations } end; var frmMarkUp: TfrmMarkUp; implementation {$R *.lfm} { TfrmMarkUp } procedure TfrmMarkUp.SellingPrice(Input: TEdit; Markup: double; Output: TLabel); var Wholesale, Selling: double; begin Wholesale:=StrToFloat(Input.Text); Selling:=Wholesale+Markup*Wholesale; Output.Caption:=FloatToStrF(Selling, ffCurrency, 15, 2); end; procedure TfrmMarkUp.gpbWholesaleClick(Sender: TObject); begin end; procedure TfrmMarkUp.bmbResetClick(Sender: TObject); var i: integer; begin edtWholesale.Clear; lblSelling.Caption:=''; edtWholesale.SetFocus; for i:=0 to (gpbMarkUp.ControlCount - 1) do TSpeedButton(gpbMarkUp.Controls[i]).Down:=False; end; procedure TfrmMarkUp.spdFifteenClick(Sender: TObject); var SellStr: string; begin SellingPrice(edtWholesale, 0.15, lblSelling); end; procedure TfrmMarkUp.spdTwentyClick(Sender: TObject); var SellStr: string; begin SellingPrice(edtWholesale, 0.20, lblSelling); end; procedure TfrmMarkUp.spdTwentyFiveClick(Sender: TObject); var SellStr: string; begin SellingPrice(edtWholesale, 0.25, lblSelling); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995,2001 Borland Software Corporation } { } {*******************************************************} unit ListActns; interface uses Classes, Controls, ActnList, ImgList; type TListControlItems = class; TListControlItem = class(TCollectionItem) private FListControlItems: TListControlItems; protected FCaption: String; FData: Pointer; FImageIndex: TImageIndex; procedure Changed; function GetDisplayName: String; override; procedure SetCaption(const Value: String); virtual; procedure SetData(const Value: Pointer); virtual; procedure SetImageIndex(const Value: TImageIndex); virtual; public constructor Create(Collection: TCollection); override; procedure Assign(Source: TPersistent); override; property Data: Pointer read FData write SetData; published property Caption: String read FCaption write SetCaption; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex default -1; end; TListItemsSortType = (stNone, stData, stText, stBoth); TListCompareEvent = function(List: TListControlItems; Item1, Item2: TListControlItem): Integer of object; TListItemsCompare = function(List: TListControlItems; Index1, Index2: Integer): Integer; TListControlItems = class(TOwnedCollection) private FCaseSensitive: Boolean; FSortType: TListItemsSortType; FOnCompare: TListCompareEvent; procedure ExchangeItems(Index1, Index2: Integer); function GetListItem(const Index: Integer): TListControlItem; procedure QuickSort(L, R: Integer; SCompare: TListItemsCompare); procedure SetSortType(const Value: TListItemsSortType); protected function CompareItems(I1, I2: TListControlItem): Integer; virtual; public function Add: TListControlItem; procedure Sort; procedure CustomSort(Compare: TListItemsCompare); property Items[const Index: Integer]: TListControlItem read GetListItem; default; published property CaseSensitive: Boolean read FCaseSensitive write FCaseSensitive; property SortType: TListItemsSortType read FSortType write SetSortType; property OnCompare: TListCompareEvent read FOnCompare write FOnCompare; end; { TCustomListAction } TCustomListAction = class; TGetItemCountEvent = procedure(Sender: TCustomListAction; var Count: Integer) of object; TItemSelectedEvent = procedure(Sender: TCustomListAction; Control: TControl) of object; TCustomListAction = class(TCustomAction) private FActive: Boolean; FActivated: Boolean; FImages: TCustomImageList; FInUpdate: Boolean; FLoadedImages: TCustomImageList; FLoading: Boolean; FOnGetItemCount: TGetItemCountEvent; FOnItemSelected: TItemSelectedEvent; FItemIndex: Integer; procedure SetActive(const Value: Boolean); procedure SetImages(const Value: TCustomImageList); procedure SetItemIndex(const Value: Integer); protected function GetCount: Integer; virtual; function GetString(Index: Integer): String; virtual; procedure Loaded; override; procedure SetString(Index: Integer; const Value: String); virtual; property Images: TCustomImageList read FImages write SetImages; property ItemIndex: Integer read FItemIndex write SetItemIndex; property Loading: Boolean read FLoading; property OnGetItemCount: TGetItemCountEvent read FOnGetItemCount write FOnGetItemCount; property OnItemSelected: TItemSelectedEvent read FOnItemSelected write FOnItemSelected; public constructor Create(AOwner: TComponent); override; procedure ExecuteTarget(Target: TObject); override; function HandlesTarget(Target: TObject): Boolean; override; property Active: Boolean read FActive write SetActive default True; property Count: Integer read GetCount; property Strings[Index: Integer]: String read GetString write SetString; default; end; { TVirtualListAction } TGetVirtualItemEvent = procedure(Sender: TCustomListAction; const Index: Integer; var Value: String; var ImageIndex: Integer; var Data: Pointer) of object; TVirtualListAction = class(TCustomListAction) private FOnGetItem: TGetVirtualItemEvent; protected function GetItem(const Index: Integer; var Value: String; var ImageIndex: Integer; var Data: Pointer): Boolean; public property Count; published property Active; property Caption; property Enabled; property HelpContext; property Hint; property Images; property ItemIndex default -1; property ShortCut; property SecondaryShortCuts; property Visible; property OnGetItem: TGetVirtualItemEvent read FOnGetItem write FOnGetItem; property OnGetItemCount; property OnItemSelected; property OnHint; end; { TStaticListAction } TStaticListAction = class; TGetItemEvent = procedure(Sender: TCustomListAction; const Index: Integer; var Item: TListControlItem) of object; TStaticListItems = class(TListControlItems) private FStaticListAction: TStaticListAction; protected procedure Notify(Item: TCollectionItem; Action: TCollectionNotification); override; procedure Update(Item: TCollectionItem); override; end; TListControlItemClass = class of TListControlItem; TStaticListAction = class(TCustomListAction) private FListItems: TStaticListItems; FOnGetItem: TGetItemEvent; procedure SetListitems(const Value: TStaticListItems); protected function GetItemClass: TListControlItemClass; virtual; function GetCount: Integer; override; function GetItem(const Index: Integer; AnItem: TListControlItem): Boolean; function GetString(Index: Integer): String; override; procedure SetString(Index: Integer; const Value: String); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Count; published property Active; property Caption; property Enabled; property HelpContext; property Hint; property Images; property ItemIndex default -1; property Items: TStaticListItems read FListItems write SetListitems; property ShortCut; property SecondaryShortCuts; property Visible; property OnGetItem: TGetItemEvent read FOnGetItem write FOnGetItem; property OnItemSelected; property OnHint; property OnUpdate; end; { TListActionLink } TListActionLink = class(TWinControlActionLink) protected function IsActiveLinked: Boolean; virtual; procedure SetActive(const Value: Boolean); virtual; function IsImagesLinked: Boolean; virtual; procedure SetAction(Value: TBasicAction); override; procedure SetImages(Value: TCustomImageList); virtual; procedure SetItemIndex(const Value: Integer); virtual; procedure AddItem(AnItem: TListControlItem); overload; virtual; procedure AddItem(ACaption: String; AImageIndex: Integer; DataPtr: Pointer); overload; virtual; procedure RefreshControl; end; implementation uses SysUtils, ComCtrls; { TListControlItem } procedure TListControlItem.Assign(Source: TPersistent); begin if Source is TListControlItem then begin if Assigned(Collection) then Collection.BeginUpdate; try Caption := TListControlItem(Source).Caption; ImageIndex := TListControlItem(Source).ImageIndex; Data := TListControlItem(Source).Data; finally if Assigned(Collection) then Collection.EndUpdate; end; end; end; procedure TListControlItem.Changed; begin if Assigned(FListControlItems) then FListControlItems.Update(Self); end; constructor TListControlItem.Create(Collection: TCollection); begin inherited Create(Collection); FImageIndex := -1; end; function TListControlItem.GetDisplayName: String; begin if Length(Caption) > 0 then Result := Caption else Result := inherited GetDisplayName; end; procedure TListControlItem.SetCaption(const Value: String); begin FCaption := Value; Changed; end; procedure TListControlItem.SetData(const Value: Pointer); begin FData := Value; Changed; end; procedure TListControlItem.SetImageIndex(const Value: TImageIndex); begin FImageIndex := Value; Changed; end; { TListControlItems } function ListItemsCompare(List: TListControlItems; Index1, Index2: Integer): Integer; begin Result := List.CompareItems(List.Items[Index1], List.Items[Index2]); end; function TListControlItems.Add: TListControlItem; begin Result := TListControlItem(inherited Add); Result.FListControlItems := Self; end; procedure TListControlItems.CustomSort(Compare: TListItemsCompare); begin if (SortType <> stNone) and (Count > 1) then QuickSort(0, Count - 1, Compare); end; function TListControlItems.CompareItems(I1, I2: TListControlItem): Integer; begin if Assigned(OnCompare) then Result := OnCompare(Self, I1, I2) else if CaseSensitive then Result := AnsiCompareStr(I1.Caption, I2.Caption) else Result := AnsiCompareText(I1.Caption, I2.Caption); end; procedure TListControlItems.ExchangeItems(Index1, Index2: Integer); var Item1, Item2: TListControlItem; I1, I2: Integer; begin Item1 := Items[Index1]; Item2 := Items[Index2]; I1 := Items[Index1].Index; I2 := Items[Index2].Index; Item1.Index := I2; Item2.Index := I1; end; procedure TListControlItems.QuickSort(L, R: Integer; SCompare: TListItemsCompare); 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; function TListControlItems.GetListItem( const Index: Integer): TListControlItem; begin Result := TListControlItem(GetItem(Index)); end; procedure TListControlItems.SetSortType(const Value: TListItemsSortType); begin if FSortType <> Value then begin FSortType := Value; if Value <> stNone then CustomSort(ListItemsCompare); end; end; procedure TListControlItems.Sort; begin CustomSort(ListItemsCompare); end; { TCustomListAction } constructor TCustomListAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FItemIndex := -1; DisableIfNoHandler := False; Enabled := True; Active := True; end; procedure TCustomListAction.ExecuteTarget(Target: TObject); var I: Integer; begin if FInUpdate then exit; FInUpdate := True; try if Target is TCustomListControl then for I := 0 to FClients.Count - 1 do if (TListActionLink(FClients[I]).FClient <> Target) and (TBasicActionLink(FClients[I]) is TListActionLink) then with Target as TCustomListControl do TListActionLink(FClients[I]).SetItemIndex(ItemIndex); if Assigned(FOnItemSelected) then FOnItemSelected(Self, Target as TControl); finally FInUpdate := False; end; end; function TCustomListAction.GetCount: Integer; begin Result := -1; if Assigned(FOnGetItemCount) then FOnGetItemCount(Self, Result); end; function TCustomListAction.GetString(Index: Integer): String; begin Result := ''; end; function TCustomListAction.HandlesTarget(Target: TObject): Boolean; begin Result := True; end; procedure TCustomListAction.Loaded; begin inherited Loaded; if FActivated then SetActive(FActivated); if Assigned(FLoadedImages) then SetImages(FLoadedImages); end; procedure TCustomListAction.SetActive(const Value: Boolean); var I: Integer; begin if Value and (csLoading in ComponentState) then begin FActivated := Value; exit; end; if FActive <> Value then begin FActive := Value; for I := 0 to FClients.Count - 1 do if TBasicActionLink(FClients[I]) is TListActionLink then begin FLoading := True; try TListActionLink(FClients[I]).SetActive(Value); finally FLoading := False; end; end; Change; if FItemIndex <> -1 then SetItemIndex(FItemIndex); end; end; procedure TCustomListAction.SetImages(const Value: TCustomImageList); var I: Integer; begin if Assigned(Value) and (csLoading in ComponentState) then begin FLoadedImages := Value; exit; end; if FImages <> Value then begin FImages := Value; for I := 0 to FClients.Count - 1 do if TBasicActionLink(FClients[I]) is TListActionLink then TListActionLink(FClients[I]).SetImages(Value); end; end; procedure TCustomListAction.SetItemIndex(const Value: Integer); var I: Integer; begin if not Active then exit; for I := 0 to FClients.Count - 1 do if TBasicActionLink(FClients[I]) is TListActionLink then TListActionLink(FClients[I]).SetItemIndex(Value); FItemIndex := Value; end; procedure TCustomListAction.SetString(Index: Integer; const Value: String); begin end; { TVirtualListAction } function TVirtualListAction.GetItem(const Index: Integer; var Value: String; var ImageIndex: Integer; var Data: Pointer): Boolean; begin Result := False; if Count <= 0 then exit; Result := Assigned(FOnGetItem); if Result then FOnGetItem(Self, Index, Value, ImageIndex, Data); end; { TStaticListItems } type TWinControlActionLinkType = class(TWinControlActionLink); TCustomListViewClass = class(TCustomListView); procedure TStaticListItems.Notify(Item: TCollectionItem; Action: TCollectionNotification); var I: Integer; begin case Action of cnAdded: begin if not Assigned(FStaticListAction) or not FStaticListAction.Active then exit; for I := 0 to FStaticListAction.FClients.Count - 1 do with TWinControlActionLinkType(FStaticListAction.FClients[I]) do begin if FClient is TCustomComboBoxEx then with FClient as TCustomComboBoxEx do with ItemsEx.Add do begin Caption := TListControlItem(Item). Caption; ImageIndex := TListControlItem(Item).ImageIndex; Data := TListControlItem(Item).Data; end else if FClient is TCustomListView then with TCustomListViewClass(FClient).Items.Add do begin Caption := TListControlItem(Item).Caption; ImageIndex := TListControlItem(Item).ImageIndex; Data := TListControlItem(Item).Data; end; end; end; cnDeleting: begin if not Assigned(FStaticListAction) or not FStaticListAction.Active then exit; for I := 0 to FStaticListAction.FClients.Count - 1 do with TWinControlActionLinkType(FStaticListAction.FClients[I]) do begin if FClient is TCustomComboBoxEx then TCustomComboBoxEx(FClient).Items.Delete(Item.Index) else if FClient is TCustomListView then TCustomListViewClass(FClient).Items.Delete(Item.Index); end; end; end; end; procedure TStaticListItems.Update(Item: TCollectionItem); var I: Integer; begin inherited Update(Item); if not Assigned(FStaticListAction) or not Assigned(Item) or not FStaticListAction.Active or FStaticListAction.Loading then exit; for I := 0 to FStaticListAction.FClients.Count - 1 do with TWinControlActionLinkType(FStaticListAction.FClients[I]) do begin if FClient is TCustomComboBoxEx then with FClient as TCustomComboBoxEx do with ItemsEx[Item.Index] do begin Caption := TListControlItem(Item). Caption; ImageIndex := TListControlItem(Item).ImageIndex; Data := TListControlItem(Item).Data; end else if FClient is TCustomListView then with TCustomListViewClass(FClient).Items[Item.Index] do begin Caption := TListControlItem(Item).Caption; ImageIndex := TListControlItem(Item).ImageIndex; Data := TListControlItem(Item).Data; end; end; end; { TStaticListAction } constructor TStaticListAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FListItems := TStaticListItems.Create(Self, GetItemClass); FListItems.FStaticListAction := Self; end; destructor TStaticListAction.Destroy; begin FreeAndNil(FListItems); inherited Destroy; end; function TStaticListAction.GetCount: Integer; begin Result := FListItems.Count; end; function TStaticListAction.GetItem(const Index: Integer; AnItem: TListControlItem): Boolean; begin Result := (Index >= 0) and (Index < FListItems.Count); if not Result then exit; AnItem.Assign(FListItems[Index]); if Assigned(FOnGetItem) then FOnGetItem(Self, Index, AnItem); end; function TStaticListAction.GetItemClass: TListControlItemClass; begin Result := TListControlItem; end; function TStaticListAction.GetString(Index: Integer): String; begin Result := Items[Index].Caption; end; procedure TStaticListAction.SetListitems(const Value: TStaticListItems); begin FListItems.Assign(Value); end; procedure TStaticListAction.SetString(Index: Integer; const Value: String); begin Items[Index].Caption := Value; end; { TListActionLink } function TListActionLink.IsActiveLinked: Boolean; begin Result := Action is TCustomListAction; end; function TListActionLink.IsImagesLinked: Boolean; begin Result := Action is TCustomListAction and Assigned(TCustomListAction(Action).FImages); end; procedure TListActionLink.SetAction(Value: TBasicAction); begin inherited SetAction(Value); if FClient is TCustomListControl then if FAction is TCustomListAction then if TCustomListAction(FAction).Active then RefreshControl; end; procedure TListActionLink.SetActive(const Value: Boolean); begin if not Value then begin if (FClient is TCustomListControl) then TCustomListControl(FClient).Clear; exit; end; if Value and (FAction is TCustomListAction) and not TCustomListAction(FAction).Active then exit; if Action is TCustomListAction then RefreshControl; end; procedure TListActionLink.SetImages(Value: TCustomImageList); begin end; procedure TListActionLink.RefreshControl; var I: Integer; ACaption: String; AImageIndex: Integer; DataPtr: Pointer; begin if not (Action is TCustomListAction) then exit; if FClient is TCustomListControl then TCustomListControl(FClient).Clear; if Action is TStaticListAction then begin with Action as TStaticListAction do for I := 0 to Count - 1 do if GetItem(I, Items[I]) then AddItem(Items[I]); end else if Action is TVirtualListAction then for I := 0 to TCustomListAction(Action).Count - 1 do with Action as TVirtualListAction do if GetItem(I, ACaption, AImageIndex, DataPtr) then AddItem(ACaption, AImageIndex, DataPtr); end; procedure TListActionLink.AddItem(AnItem: TListControlItem); begin end; procedure TListActionLink.AddItem(ACaption: String; AImageIndex: Integer; DataPtr: Pointer); begin end; procedure TListActionLink.SetItemIndex(const Value: Integer); begin if FClient is TCustomListControl then with FClient as TCustomListControl do ItemIndex := Value; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { COM Web server application components } { } { Copyright (c) 1997-2001 Borland Software Corp } { } {*******************************************************} unit SockHTTP; interface uses Classes, HTTPApp, WebReq, SysUtils, SockRequestInterpreter; type // Interface to access information about the web request ISockWebRequestAccess = interface(IUnknown) ['{E72A0846-8C34-11D3-AAF7-A0AC2E78CD57}'] function GetFieldByName(const Name: string): string; function ReadClient(var Buffer: string; Count: Integer): Integer; function TranslateURI(const Value: string): string; function WriteClient(const Buffer: string): Integer; function GetStringVariable(Index: Integer): string; function WriteHeaders(StatusCode: Integer; StatusText: string; Headers: string): Boolean; function UsingStub: Boolean; function ReadString(var Buffer: string; Count: Integer): Integer; end; TSockWebRequest = class(TWebRequest) private FIntf: ISockWebRequestAccess; function UsingStub: Boolean; protected function GetStringVariable(Index: Integer): string; override; function GetDateVariable(Index: Integer): TDateTime; override; function GetIntegerVariable(Index: Integer): Integer; override; function GetInternalPathInfo: string; override; public constructor Create(AIntf: ISockWebRequestAccess); function GetFieldByName(const Name: string): string; override; function ReadClient(var Buffer; Count: Integer): Integer; override; function ReadString(Count: Integer): string; override; function TranslateURI(const URI: string): string; override; function WriteClient(var Buffer; Count: Integer): Integer; override; function WriteString(const AString: string): Boolean; override; function WriteHeaders(StatusCode: Integer; const StatusString, Headers: string): Boolean; override; end; TSockWebResponse = class(TWebResponse) private FStatusCode: Integer; FStringVariables: array[0..MAX_STRINGS - 1] of string; FIntegerVariables: array[0..MAX_INTEGERS - 1] of Integer; FDateVariables: array[0..MAX_DATETIMES - 1] of TDateTime; FContent: string; FSent: Boolean; protected function GetContent: string; override; function GetDateVariable(Index: Integer): TDateTime; override; function GetIntegerVariable(Index: Integer): Integer; override; function GetLogMessage: string; override; function GetStatusCode: Integer; override; function GetStringVariable(Index: Integer): string; override; procedure SetContent(const Value: string); override; procedure SetDateVariable(Index: Integer; const Value: TDateTime); override; procedure SetIntegerVariable(Index: Integer; Value: Integer); override; procedure SetLogMessage(const Value: string); override; procedure SetStatusCode(Value: Integer); override; procedure SetStringVariable(Index: Integer; const Value: string); override; public constructor Create(HTTPRequest: TWebRequest); procedure SendResponse; override; procedure SendRedirect(const URI: string); override; procedure SendStream(AStream: TStream); override; function Sent: Boolean; override; end; TSockWebRequestHandler = class(TWebRequestHandler) private function NewRequest(AIntf: ISockWebRequestAccess): TSockWebRequest; function NewResponse(SockWebRequest: TSockWebRequest): TSockWebResponse; procedure HandleServerException(E: Exception; AIntf: ISockWebRequestAccess); procedure HandleException(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Run(AIntf: ISockWebRequestAccess); end; implementation uses BrkrConst, Variants; { TSockWebRequest } constructor TSockWebRequest.Create(AIntf: ISockWebRequestAccess); begin FIntf := AIntf; inherited Create; end; function TSockWebRequest.GetFieldByName(const Name: string): string; begin Result := FIntf.GetFieldByName(Name); end; function VariantArrayToString(const V: OleVariant): string; var P: Pointer; Size: Integer; begin Result := ''; if VarIsArray(V) and (VarType(V) and varTypeMask = varByte) then begin Size := VarArrayHighBound(V, 1) - VarArrayLowBound(V, 1) + 1; if Size > 0 then begin SetLength(Result, Size); P := VarArrayLock(V); try Move(P^, Result[1], Size); finally VarArrayUnlock(V); end; end; end; end; function TSockWebRequest.GetStringVariable(Index: Integer): string; begin Result := FIntf.GetStringVariable(Index); end; function TSockWebRequest.GetDateVariable(Index: Integer): TDateTime; var Value: string; begin Value := GetStringVariable(Index); if Value <> '' then Result := ParseDate(Value) else Result := -1; end; function TSockWebRequest.GetIntegerVariable(Index: Integer): Integer; var Value: string; begin Value := GetStringVariable(Index); Result := StrToIntDef(Value, -1) end; function TSockWebRequest.ReadClient(var Buffer; Count: Integer): Integer; var V: string; begin Result := FIntf.ReadClient(V, Count); Move(V[1], Buffer, Result); end; function TSockWebRequest.ReadString(Count: Integer): string; begin FIntf.ReadString(Result, Count); end; function TSockWebRequest.TranslateURI(const URI: string): string; begin end; function TSockWebRequest.WriteClient(var Buffer; Count: Integer): Integer; var S: string; begin SetString(S, PChar(@Buffer), Count); Result := FIntf.WriteClient(S); end; function TSockWebRequest.WriteString(const AString: string): Boolean; begin if AString <> '' then Result := FIntf.WriteClient(AString) = Length(AString) else Result := False; end; function TSockWebRequest.WriteHeaders(StatusCode: Integer; const StatusString, Headers: string): Boolean; begin Result := FIntf.WriteHeaders(StatusCode, StatusString, Headers); end; { TCGIResponse } constructor TSockWebResponse.Create(HTTPRequest: TWebRequest); begin inherited Create(HTTPRequest); if FHTTPRequest.ProtocolVersion = '' then Version := '1.0'; {do not localize} StatusCode := 200; LastModified := -1; Expires := -1; Date := -1; ContentType := 'text/html'; {do not localize} end; function TSockWebResponse.GetContent: string; begin Result := FContent; end; function TSockWebResponse.GetDateVariable(Index: Integer): TDateTime; begin if (Index >= 0) and (Index < 3) then Result := FDateVariables[Index] else Result := -1; end; function TSockWebResponse.GetIntegerVariable(Index: Integer): Integer; begin if (Index >= 0) and (Index < 2) then Result := FIntegerVariables[Index] else Result := -1; end; function TSockWebResponse.GetLogMessage: string; begin // Result := TCGIRequest(HTTPRequest).ECB.lpszLogData; end; function TSockWebResponse.GetStatusCode: Integer; begin Result := FStatusCode; end; function TSockWebResponse.GetStringVariable(Index: Integer): string; begin if (Index >= 0) and (Index < 12) then Result := FStringVariables[Index]; end; function TSockWebResponse.Sent: Boolean; begin Result := FSent; end; procedure TSockWebResponse.SetContent(const Value: string); begin FContent := Value; if ContentStream = nil then ContentLength := Length(FContent); end; procedure TSockWebResponse.SetDateVariable(Index: Integer; const Value: TDateTime); begin if (Index >= Low(FDateVariables)) and (Index <= High(FDateVariables)) then if Value <> FDateVariables[Index] then FDateVariables[Index] := Value; end; procedure TSockWebResponse.SetIntegerVariable(Index: Integer; Value: Integer); begin if (Index >= Low(FIntegerVariables)) and (Index <= High(FIntegerVariables)) then if Value <> FDateVariables[Index] then FIntegerVariables[Index] := Value; end; procedure TSockWebResponse.SetLogMessage(const Value: string); begin // StrPLCopy(TCGIRequest(HTTPRequest).ECB.lpszLogData, Value, HSE_LOG_BUFFER_LEN); end; procedure TSockWebResponse.SetStatusCode(Value: Integer); begin if FStatusCode <> Value then begin FStatusCode := Value; ReasonString := StatusString(Value); end; end; procedure TSockWebResponse.SetStringVariable(Index: Integer; const Value: string); begin if (Index >= Low(FStringVariables)) and (Index <= High(FStringVariables)) then FStringVariables[Index] := Value; end; procedure TSockWebResponse.SendResponse; var StatusString: string; Headers: string; I: Integer; procedure AddHeaderItem(const Item, FormatStr: string); begin if Item <> '' then Headers := Headers + Format(FormatStr, [Item]); end; begin if HTTPRequest.ProtocolVersion <> '' then begin if (ReasonString <> '') and (StatusCode > 0) then StatusString := Format('%d %s', [StatusCode, ReasonString]) {do not localize} else StatusString := '200 OK'; {do not localize} AddHeaderItem(Location, 'Location: %s'#13#10); {do not localize} AddHeaderItem(Allow, 'Allow: %s'#13#10); {do not localize} for I := 0 to Cookies.Count - 1 do AddHeaderItem(Cookies[I].HeaderValue, 'Set-Cookie: %s'#13#10); {do not localize} AddHeaderItem(DerivedFrom, 'Derived-From: %s'#13#10); {do not localize} if Expires > 0 then Format(FormatDateTime('"Expires: "' + sDateFormat + ' "GMT"'#13#10, Expires), {do not localize} [DayOfWeekStr(Expires), MonthStr(Expires)]); if LastModified > 0 then Format(FormatDateTime('"Last-Modified: "' + sDateFormat + ' "GMT"'#13#10, {do not localize} LastModified), [DayOfWeekStr(LastModified), MonthStr(LastModified)]); AddHeaderItem(Title, 'Title: %s'#13#10); {do not localize} AddHeaderItem(FormatAuthenticate, 'WWW-Authenticate: %s'#13#10); {do not localize} AddCustomHeaders(Headers); AddHeaderItem(ContentVersion, 'Content-Version: %s'#13#10); {do not localize} AddHeaderItem(ContentEncoding, 'Content-Encoding: %s'#13#10); {do not localize} AddHeaderItem(ContentType, 'Content-Type: %s'#13#10); if (Content <> '') or (ContentStream <> nil) then AddHeaderItem(IntToStr(ContentLength), 'Content-Length: %s'#13#10); {do not localize} Headers := Headers + 'Content:'#13#10#13#10; {do not localize} HTTPRequest.WriteHeaders(StatusCode, StatusString, Headers); end; if ContentStream = nil then HTTPRequest.WriteString(Content) else if ContentStream <> nil then begin SendStream(ContentStream); ContentStream := nil; // Drop the stream end; FSent := True; end; procedure TSockWebResponse.SendRedirect(const URI: string); begin Location := URI; StatusCode := 302; ContentType := 'text/html'; {do not localize} Content := Format(sDocumentMoved, [URI]); SendResponse; end; procedure TSockWebResponse.SendStream(AStream: TStream); var Buffer: array[0..8191] of Byte; BytesToSend: Integer; begin while AStream.Position < AStream.Size do begin BytesToSend := AStream.Read(Buffer, SizeOf(Buffer)); FHTTPRequest.WriteClient(Buffer, BytesToSend); end; end; { TSockWebRequestHandler } procedure TSockWebRequestHandler.HandleServerException(E: Exception; AIntf: ISockWebRequestAccess); var ResultText, ResultHeaders, StatusString: string; begin ResultText := Format(sInternalServerError, [E.ClassName, E.Message]); StatusString := Format('500 %s', [E.Message]); {do not localize} ResultHeaders := Format( 'Status: 500'#13#10+ //Not resourced 'Content-Type: text/html'#13#10 + //Not resourced 'Content-Length: %d'#13#10 + //Not resourced 'Content:'#13#10#13#10, [Length(ResultText)]); //Not resourced AIntf.WriteHeaders(500, StatusString, ResultHeaders); AIntf.WriteClient(WideString(ResultText)); { Socket web modules don't have a way to mark as sent } // ARequest.Sent; end; function TSockWebRequestHandler.NewRequest(AIntf: ISockWebRequestAccess): TSockWebRequest; begin Result := TSockWebRequest.Create(AIntf); end; procedure TSockWebRequestHandler.Run( AIntf: ISockWebRequestAccess); var HTTPRequest: TSockWebRequest; HTTPResponse: TSockWebResponse; begin try HTTPRequest := NewRequest(AIntf); try HTTPResponse := NewResponse(HTTPRequest); try HandleRequest(HTTPRequest, HTTPResponse); finally HTTPResponse.Free; end; finally HTTPRequest.Free; end; except HandleServerException(Exception(ExceptObject), AIntf); end; end; function TSockWebRequestHandler.NewResponse(SockWebRequest: TSockWebRequest): TSockWebResponse; begin Result := TSockWebResponse.Create(SockWebRequest) end; function TSockWebRequest.GetInternalPathInfo: string; var P: Integer; begin if UsingStub then begin Result := PathInfo; Assert(Length(Result) > 0, 'Unexpected length'); Assert(Result[1] = '/', 'Unexpected value'); Delete(Result, 1, 1); // Remove first section of path. This is a reference // to the progid. P := Pos('/', Result); {do not localize} if P > 0 then Delete(Result, 1, P-1) else Result := '/'; end else Result := inherited GetInternalPathInfo; end; function TSockWebRequest.UsingStub: Boolean; begin Result := FIntf.UsingStub; end; constructor TSockWebRequestHandler.Create(AOwner: TComponent); begin inherited; Classes.ApplicationHandleException := HandleException; end; destructor TSockWebRequestHandler.Destroy; begin Classes.ApplicationHandleException := nil; inherited; end; procedure TSockWebRequestHandler.HandleException(Sender: TObject); var Handled: Boolean; Intf: IWebExceptionHandler; begin Handled := False; if (ExceptObject is Exception) and not (ExceptObject is EAbort) and Supports(Sender, IWebExceptionHandler, Intf) then Intf.HandleException(Exception(ExceptObject), Handled); if not Handled then SysUtils.ShowException(ExceptObject, ExceptAddr); end; end.
{**********************************************} { TErrorSeries } { TErrorBarSeries (derived from TBarSeries) } { } { Copyright (c) 1995-2004 by David Berneda } {**********************************************} unit ErrorBar; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, Types, {$ELSE} Graphics, {$ENDIF} {$IFDEF CLR} Types, {$ENDIF} TeEngine, Series, TeCanvas; type TErrorSeriesStyle=( essLeft,essRight,essLeftRight, essTop,essBottom,essTopBottom); TErrorWidthUnits=(ewuPercent,ewuPixels); TCustomErrorSeries=class(TBarSeries) private { Private declarations } FErrorPen : TChartPen; FErrorStyle : TErrorSeriesStyle; FErrorValues : TChartValueList; FErrorWidth : Integer; FErrorWidthUnits : TErrorWidthUnits; { internal } IDrawBar : Boolean; Function GetErrorValue(Index:Integer):Double; Procedure PrepareErrorPen(ValueIndex:Integer); Procedure SetErrorStyle(Value:TErrorSeriesStyle); Procedure SetErrorValue(Index:Integer; Const Value:Double); Procedure SetErrorValues(Value:TChartValueList); Procedure SetErrorWidthUnits(Value:TErrorWidthUnits); Procedure SetErrorWidth(Value:Integer); procedure SetErrorPen(const Value: TChartPen); protected { Protected declarations } Procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); override; Procedure CalcHorizMargins(Var LeftMargin,RightMargin:Integer); override; Procedure CalcVerticalMargins(Var TopMargin,BottomMargin:Integer); override; Procedure DrawError(X,Y,AWidth,AHeight:Integer; Draw3D:Boolean); Procedure DrawLegendShape(ValueIndex:Integer; Const Rect:TRect); override; class Function GetEditorClass:String; override; Procedure PrepareForGallery(IsEnabled:Boolean); override; Procedure PrepareLegendCanvas( ValueIndex:Integer; Var BackColor:TColor; Var BrushStyle:TBrushStyle); override; Procedure SetSeriesColor(AColor:TColor); override; class Function SubGalleryStack:Boolean; override; { 5.01 } public { Public declarations } Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; Function AddErrorBar(Const AX,AY,AError:Double; Const AXLabel:String=''; AColor:TColor=clTeeColor):Integer; Procedure Assign(Source:TPersistent); override; Procedure DrawBar(BarIndex,StartPos,EndPos:Integer); override; Function MinYValue:Double; override; Function MaxYValue:Double; override; property ErrorValue[Index:Integer]:Double read GetErrorValue write SetErrorValue; { To be published declarations } property ErrorPen:TChartPen read FErrorPen write SetErrorPen; property ErrorStyle:TErrorSeriesStyle read FErrorStyle write SetErrorStyle default essTopBottom; property ErrorValues:TChartValueList read FErrorValues write SetErrorValues; property ErrorWidth:Integer read FErrorWidth write SetErrorWidth default 100; property ErrorWidthUnits:TErrorWidthUnits read FErrorWidthUnits write SetErrorWidthUnits default ewuPercent; end; TErrorSeries=class(TCustomErrorSeries) public published property ErrorPen; property ErrorStyle; property ErrorValues; property ErrorWidth; property ErrorWidthUnits; end; TErrorBarSeries=class(TCustomErrorSeries) protected Procedure PrepareForGallery(IsEnabled:Boolean); override; public Constructor Create(AOwner:TComponent); override; published property ErrorPen; property ErrorValues; property ErrorWidth; property ErrorWidthUnits; end; THighLowSeries=class(TChartSeries) private FHighPen : TChartPen; FLow : TChartValueList; FLowPen : TChartPen; OldX : Integer; OldY0 : Integer; OldY1 : Integer; FLowBrush: TChartBrush; FTransparency: TTeeTransparency; function GetHigh: TChartValueList; procedure SetHigh(const Value: TChartValueList); procedure SetHighPen(const Value: TChartPen); procedure SetLow(const Value: TChartValueList); procedure SetLowPen(const Value: TChartPen); function GetHighBrush: TChartBrush; procedure SetHighBrush(const Value: TChartBrush); procedure SetLowBrush(const Value: TChartBrush); procedure SetTransparency(const Value: TTeeTransparency); protected Procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); override; class Procedure CreateSubGallery(AddSubChart:TChartSubGalleryProc); override; Procedure DrawValue(ValueIndex:Integer); override; class Function GetEditorClass:String; override; class Procedure SetSubGallery(ASeries:TChartSeries; Index:Integer); override; public Constructor Create(AOwner: TComponent); override; destructor Destroy; override; Procedure Assign(Source:TPersistent); override; Function AddHighLow(Const AX,AHigh,ALow:Double; Const AXLabel:String=''; AColor:TColor=clTeeColor):Integer; function Clicked(x, y: Integer): Integer; override; // 6.0 Function IsValidSourceOf(Value:TChartSeries):Boolean; override; Function MaxYValue:Double; override; Function MinYValue:Double; override; published property HighBrush:TChartBrush read GetHighBrush write SetHighBrush; property HighPen:TChartPen read FHighPen write SetHighPen; property HighValues:TChartValueList read GetHigh write SetHigh; property LowBrush:TChartBrush read FLowBrush write SetLowBrush; property LowPen:TChartPen read FLowPen write SetLowPen; property LowValues:TChartValueList read FLow write SetLow; property Pen; property Transparency:TTeeTransparency read FTransparency write SetTransparency default 0; property Active; property ColorEachPoint; property ColorSource; property Cursor; property Depth; property HorizAxis; property Marks; property ParentChart; { datasource below parentchart } property DataSource; property PercentFormat; property SeriesColor; property ShowInLegend; property Title; property ValueFormat; property VertAxis; property XLabelsSource; property XValues; { 5.01 } { events } property AfterDrawValues; property BeforeDrawValues; property OnAfterAdd; property OnBeforeAdd; property OnClearValues; property OnClick; property OnDblClick; property OnGetMarkText; property OnMouseEnter; property OnMouseLeave; end; implementation Uses {$IFDEF CLR} {$ELSE} Math, {$ENDIF} Chart, TeeProcs, TeeProCo, TeeConst; { TCustomErrorSeries } Constructor TCustomErrorSeries.Create(AOwner: TComponent); Begin inherited; IDrawBar:=False; FErrorPen:=CreateChartPen; FErrorValues:=TChartValueList.Create(Self,TeeMsg_ValuesStdError); { <-- Std Error storage } FErrorStyle:=essTopBottom; FErrorWidth:=100; FErrorWidthUnits:=ewuPercent; Marks.Hide; end; Destructor TCustomErrorSeries.Destroy; begin FErrorPen.Free; inherited; end; Procedure TCustomErrorSeries.CalcHorizMargins(Var LeftMargin,RightMargin:Integer); begin inherited; if (FErrorStyle=essLeft) or (FErrorStyle=essLeftRight) then LeftMargin :=Math.Max(LeftMargin, ErrorPen.Width); if (FErrorStyle=essRight) or (FErrorStyle=essLeftRight) then RightMargin :=Math.Max(RightMargin, ErrorPen.Width); end; Procedure TCustomErrorSeries.CalcVerticalMargins(Var TopMargin,BottomMargin:Integer); begin inherited; if (FErrorStyle=essTop) or (FErrorStyle=essTopBottom) then TopMargin :=Math.Max(TopMargin, ErrorPen.Width); if (FErrorStyle=essBottom) or (FErrorStyle=essTopBottom) then BottomMargin :=Math.Max(BottomMargin, ErrorPen.Width); end; Procedure TCustomErrorSeries.SetErrorPen(Const Value:TChartPen); Begin FErrorPen.Assign(Value); if not IDrawBar then SeriesColor:=FErrorPen.Color; End; Procedure TCustomErrorSeries.PrepareErrorPen(ValueIndex:Integer); begin With ParentChart.Canvas do begin if (ValueIndex<>TeeAllValues) and (not IDrawBar) then AssignVisiblePenColor(ErrorPen,ValueColor[ValueIndex]) else AssignVisiblePen(ErrorPen); BackMode:=cbmTransparent; end; end; Procedure TCustomErrorSeries.SetErrorWidth(Value:Integer); Begin SetIntegerProperty(FErrorWidth,Value); End; Procedure TCustomErrorSeries.DrawError(X,Y,AWidth,AHeight:Integer; Draw3D:Boolean); Procedure DrawHoriz(XPos:Integer); begin With ParentChart.Canvas do begin if Draw3D then begin HorizLine3D(X,XPos,Y,MiddleZ); VertLine3D(XPos,(Y-AWidth div 2),Y+(AWidth div 2),MiddleZ); { 5.01 } end else begin DoHorizLine(X,XPos,Y); DoVertLine(XPos,(Y-AWidth div 2),Y+(AWidth div 2)); { 5.01 } end; end; end; Procedure DrawVert(YPos:Integer); begin With ParentChart.Canvas do begin if Draw3D then begin VertLine3D(X,Y,YPos,MiddleZ); HorizLine3D(X-(AWidth div 2),X+(AWidth div 2),YPos,MiddleZ); end else begin DoVertLine(X,Y,YPos); DoHorizLine(X-(AWidth div 2),X+(AWidth div 2),YPos); end; end; end; begin Case FErrorStyle of essLeft : DrawHoriz(X-AHeight); { 5.01 } essRight : DrawHoriz(X+AHeight); essLeftRight: begin DrawHoriz(X-AHeight); DrawHoriz(X+AHeight); end; essTop : DrawVert(Y-AHeight); essBottom : DrawVert(Y+AHeight); essTopBottom: begin DrawVert(Y-AHeight); DrawVert(Y+AHeight); end; end; end; Procedure TCustomErrorSeries.DrawBar(BarIndex,StartPos,EndPos:Integer); Var tmp : Integer; tmpWidth : Integer; tmpBarWidth : Integer; tmpError : Double; tmpHeight : Integer; Begin if IDrawBar then inherited; if ErrorPen.Visible then Begin tmpError:=FErrorValues.Value[BarIndex]; if tmpError<>0 then Begin tmpBarWidth:=BarBounds.Right-BarBounds.Left; if FErrorWidth=0 then tmpWidth:=tmpBarWidth else if FErrorWidthUnits=ewuPercent then tmpWidth:=Round(1.0*FErrorWidth*tmpBarWidth*0.01) else tmpWidth:=FErrorWidth; tmp:=CalcYPosValue(YValues.Value[BarIndex]); { MS : simplified and allows vertical/horizontal style 5.01 } Case FErrorStyle of essLeft, essRight, essLeftRight : tmpHeight:=GetHorizAxis.CalcSizeValue(Abs(tmpError)); else tmpHeight:=GetVertAxis.CalcSizeValue(Abs(tmpError)); end; if IDrawBar and (YValues.Value[BarIndex]<YOrigin) then tmpHeight:=-tmpHeight; PrepareErrorPen(BarIndex); DrawError((BarBounds.Right+BarBounds.Left) div 2,tmp, tmpWidth,tmpHeight,ParentChart.View3D); end; end; End; Procedure TCustomErrorSeries.SetErrorWidthUnits(Value:TErrorWidthUnits); Begin if FErrorWidthUnits<>Value then Begin FErrorWidthUnits:=Value; Repaint; end; end; Procedure TCustomErrorSeries.SetErrorStyle(Value:TErrorSeriesStyle); begin if FErrorStyle<>Value then begin FErrorStyle:=Value; Repaint; end; end; Procedure TCustomErrorSeries.SetErrorValues(Value:TChartValueList); Begin SetChartValueList(FErrorValues,Value); { standard method } End; Function TCustomErrorSeries.AddErrorBar( Const AX,AY,AError:Double; Const AXLabel:String; AColor:TColor):Integer; Begin FErrorValues.TempValue:=AError; result:=AddXY(AX,AY,AXLabel,AColor); End; Procedure TCustomErrorSeries.AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); Var t : Integer; s : TSeriesRandomBounds; Begin s:=RandomBounds(NumValues); with s do for t:=1 to NumValues do Begin AddErrorBar( tmpX, RandomValue(Round(DifY)), DifY/(20+RandomValue(4))); tmpX:=tmpX+StepX; end; end; Function TCustomErrorSeries.MaxYValue:Double; Var t : Integer; tmp : Double; tmpErr : Double; Begin if IDrawBar then result:=inherited MaxYValue else result:=0; for t:=0 to Count-1 do if IDrawBar then Begin tmpErr:=FErrorValues.Value[t]; tmp:=YValues.Value[t]; if tmp<0 then tmp:=tmp-tmpErr else tmp:=tmp+tmpErr; if tmp>result then result:=tmp; end else begin tmp:=YValues.Value[t]+FErrorValues.Value[t]; if t=0 then result:=tmp else result:=Math.Max(result,tmp); end; End; Function TCustomErrorSeries.MinYValue:Double; Var t : Integer; tmp : Double; tmpErr : Double; Begin if IDrawBar then result:=inherited MinYValue else result:=0; for t:=0 to Count-1 do if IDrawBar then Begin tmpErr:=FErrorValues.Value[t]; tmp:=YValues.Value[t]; if tmp<0 then tmp:=tmp-tmpErr else tmp:=tmp+tmpErr; if tmp<result then result:=tmp; end else begin tmp:=YValues.Value[t]-FErrorValues.Value[t]; if t=0 then result:=tmp else result:=Math.Min(result,tmp); end; End; Function TCustomErrorSeries.GetErrorValue(Index:Integer):Double; Begin result:=FErrorValues.Value[Index]; End; Procedure TCustomErrorSeries.SetErrorValue(Index:Integer; Const Value:Double); Begin FErrorValues.Value[Index]:=Value; End; class Function TCustomErrorSeries.GetEditorClass:String; Begin result:='TErrorSeriesEditor'; end; Procedure TCustomErrorSeries.Assign(Source:TPersistent); begin if Source is TCustomErrorSeries then With TCustomErrorSeries(Source) do begin Self.ErrorPen :=FErrorPen; // 7.0 fix Self.FErrorStyle :=FErrorStyle; Self.FErrorWidth :=FErrorWidth; Self.FErrorWidthUnits:=FErrorWidthUnits; end; inherited; end; Procedure TCustomErrorSeries.PrepareForGallery(IsEnabled:Boolean); Const Colors:Array[Boolean] of TColor=(clSilver,clBlue); ErrorColors:Array[Boolean] of TColor=(clWhite,clRed); begin inherited; ErrorPen.Color:=ErrorColors[IsEnabled]; SeriesColor:=Colors[IsEnabled]; end; Procedure TCustomErrorSeries.SetSeriesColor(AColor:TColor); begin inherited; if not IDrawBar then ErrorPen.Color:=AColor; end; Procedure TCustomErrorSeries.DrawLegendShape(ValueIndex:Integer; Const Rect:TRect); begin With Rect do DrawError( (Left+Right) div 2,(Top+Bottom) div 2, Right-Left,((Bottom-Top) div 2)-1,False); end; class Function TCustomErrorSeries.SubGalleryStack:Boolean; begin result:=False; { 5.01 } { Do not show stacked styles at sub-gallery } end; procedure TCustomErrorSeries.PrepareLegendCanvas(ValueIndex: Integer; var BackColor: TColor; var BrushStyle: TBrushStyle); begin PrepareErrorPen(ValueIndex); end; { TErrorBarSeries } Constructor TErrorBarSeries.Create(AOwner: TComponent); Begin inherited; IDrawBar:=True; FErrorStyle:=essTop; end; Procedure TErrorBarSeries.PrepareForGallery(IsEnabled:Boolean); begin ErrorPen.Width:=2; inherited; end; { THighLowSeries } Constructor THighLowSeries.Create(AOwner: TComponent); begin inherited; CalcVisiblePoints:=False; Pen.Color:=clTeeColor; FLow:=TChartValueList.Create(Self,TeeMsg_ValuesLow); FHighPen:=CreateChartPen; FLowPen:=CreateChartPen; FLowBrush:=TChartBrush.Create(CanvasChanged); LowBrush.Style:=bsClear; HighBrush.Style:=bsClear; end; Destructor THighLowSeries.Destroy; begin FHighPen.Free; FLowPen.Free; FLowBrush.Free; inherited; end; function THighLowSeries.AddHighLow(const AX, AHigh, ALow: Double; Const AXLabel:String=''; AColor:TColor=clTeeColor): Integer; begin FLow.TempValue:=ALow; result:=AddXY(AX,AHigh); end; procedure THighLowSeries.Assign(Source: TPersistent); begin if Source is THighLowSeries then With THighLowSeries(Source) do begin Self.HighPen :=HighPen; Self.LowPen :=LowPen; Self.LowBrush:=LowBrush; Self.FTransparency:=FTransparency; end; inherited; end; function THighLowSeries.Clicked(x, y: Integer): Integer; var t : Integer; X0 : Integer; P : TPoint; PS : TFourPoints; begin result:=TeeNoPointClicked; if (FirstValueIndex<>-1) and (LastValueIndex<>-1) then // 7.0 begin P:=TeePoint(x,y); for t:=FirstValueIndex to LastValueIndex do begin X0:=CalcXPos(t); PS[2]:=ParentChart.Canvas.Calculate3DPosition(X0,CalcYPosValue(FLow.Value[t]),MiddleZ); PS[3]:=ParentChart.Canvas.Calculate3DPosition(X0,CalcYPos(t),MiddleZ); if (t<>FirstValueIndex) and PointInPolygon(P,PS) then begin result:=t; break; end; PS[0]:=PS[3]; PS[1]:=PS[2]; end; end; end; procedure THighLowSeries.DrawValue(ValueIndex: Integer); Var X : Integer; View3D : Boolean; Procedure DrawLine(APen:TChartPen; BeginY,EndY:Integer); begin if APen.Visible then With ParentChart.Canvas do begin AssignVisiblePen(APen); if View3D then LineWithZ(OldX,BeginY,X,EndY,MiddleZ) else Line(OldX,BeginY,X,EndY); end; end; procedure DrawValueLine(AColor:TColor); var tmp : TColor; begin tmp:=Pen.Color; if tmp=clTeeColor then tmp:=AColor; with ParentChart.Canvas do begin AssignVisiblePenColor(Self.Pen,tmp); if View3D then VertLine3D(OldX,OldY0,OldY1,MiddleZ) else DoVertLine(OldX,OldY0,OldY1); end; end; var Y0 : Integer; Y1 : Integer; tmpBrush : TChartBrush; tmpColor : TColor; IPoints : TFourPoints; P : TFourPoints; tmpBlend : TTeeBlend; tmpFirst : Integer; begin // calculate coordinates x:=CalcXPos(ValueIndex); y0:=CalcYPos(ValueIndex); y1:=CalcYPosValue(FLow.Value[ValueIndex]); tmpFirst:=FirstDisplayedIndex; if ValueIndex<>tmpFirst then begin tmpColor:=ValueColor[ValueIndex-1]; View3D:=ParentChart.View3D; if (not IsNull(ValueIndex)) and (not IsNull(ValueIndex-1)) then // 7.0 begin // Determine brush to use (high or low) if LowValues.Value[ValueIndex]<HighValues.Value[ValueIndex] then tmpBrush:=HighBrush else tmpBrush:=LowBrush; // set brush if tmpBrush.Style<>bsClear then begin P[0].X:=OldX; P[0].Y:=OldY0; P[1].X:=OldX; P[1].Y:=OldY1; P[2].X:=X; P[2].Y:=Y1; P[3].X:=X; P[3].Y:=Y0; with ParentChart.Canvas do begin if Transparency>0 then begin IPoints[0]:=Calculate3DPosition(P[0],MiddleZ); IPoints[1]:=Calculate3DPosition(P[1],MiddleZ); IPoints[2]:=Calculate3DPosition(P[2],MiddleZ); IPoints[3]:=Calculate3DPosition(P[3],MiddleZ); tmpBlend:=BeginBlending(RectFromPolygon(IPoints,4),Transparency); end else tmpBlend:=nil; AssignBrush(tmpBrush,tmpColor); Pen.Style:=psClear; // no pen to draw polygon // draw plane if View3D then PlaneWithZ(P,MiddleZ) else Polygon(P); if Transparency>0 then EndBlending(tmpBlend); end; end; // draw lines DrawLine(HighPen,OldY0,Y0); DrawLine(LowPen,OldY1,Y1); end; // draw vertical lines if Pen.Visible and (not IsNull(ValueIndex-1)) then // 7.0 begin DrawValueLine(tmpColor); if DrawValuesForward then tmpFirst:=LastValueIndex else tmpFirst:=FirstValueIndex; if ValueIndex=tmpFirst then begin OldX:=X; OldY0:=Y0; OldY1:=Y1; DrawValueLine(ValueColor[ValueIndex]); end; end; end; OldX:=X; OldY0:=Y0; OldY1:=Y1; end; function THighLowSeries.GetHigh: TChartValueList; begin result:=YValues; end; procedure THighLowSeries.SetHigh(const Value: TChartValueList); begin SetChartValueList(YValues,Value); end; procedure THighLowSeries.SetLow(const Value: TChartValueList); begin FLow.Assign(Value); end; Function THighLowSeries.IsValidSourceOf(Value:TChartSeries):Boolean; begin result:=Value is THighLowSeries; end; Function THighLowSeries.MaxYValue:Double; Begin result:=Math.Max(inherited MaxYValue,FLow.MaxValue); End; Function THighLowSeries.MinYValue:Double; Begin result:=Math.Min(inherited MinYValue,FLow.MinValue); End; procedure THighLowSeries.SetHighPen(const Value: TChartPen); begin FHighPen.Assign(Value); end; procedure THighLowSeries.SetLowPen(const Value: TChartPen); begin FLowPen.Assign(Value); end; class function THighLowSeries.GetEditorClass: String; begin result:='THighLowEditor'; end; function THighLowSeries.GetHighBrush: TChartBrush; begin result:=Brush; end; procedure THighLowSeries.SetHighBrush(const Value: TChartBrush); begin Brush:=Value; end; procedure THighLowSeries.SetLowBrush(const Value: TChartBrush); begin FLowBrush.Assign(Value); end; procedure THighLowSeries.AddSampleValues(NumValues: Integer; OnlyMandatory:Boolean=False); Var t : Integer; tmp : Double; s : TSeriesRandomBounds; Begin s:=RandomBounds(NumValues); with s do begin tmp:=RandomValue(Round(DifY)); for t:=1 to NumValues do Begin tmp:=tmp+RandomValue(Round(DifY/5.0))-(DifY/10.0); AddHighLow(tmpX,{ X } tmp, { High } tmp-RandomValue(Round(DifY/5.0))); { Low } tmpX:=tmpX+StepX; end; end; end; class procedure THighLowSeries.CreateSubGallery( AddSubChart: TChartSubGalleryProc); begin inherited; AddSubChart(TeeMsg_Filled); AddSubChart(TeeMsg_NoLines); AddSubChart(TeeMsg_NoHigh); AddSubChart(TeeMsg_NoLow); end; class procedure THighLowSeries.SetSubGallery(ASeries: TChartSeries; Index: Integer); begin With THighLowSeries(ASeries) do Case Index of 1: Brush.Style:=bsSolid; 2: Pen.Hide; 3: HighPen.Hide; 4: LowPen.Hide; else inherited; end; end; procedure THighLowSeries.SetTransparency(const Value: TTeeTransparency); begin if FTransparency<>Value then begin FTransparency:=Value; Repaint; end; end; initialization RegisterTeeSeries(TErrorBarSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryErrorBar, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryStats,1); RegisterTeeSeries(TErrorSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryError, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryStats,1); RegisterTeeSeries(THighLowSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryHighLow, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryStats,1); finalization UnRegisterTeeSeries( [TErrorBarSeries,TErrorSeries,THighLowSeries]); end.
{ Module of relatively small GUI library utility routines. } module gui_util; define gui_string_wrap; %include 'gui2.ins.pas'; { ************************************************************************* * * Subroutine GUI_STRING_WRAP (STR, WIDE, LIST) * * Wrap the string STR into multiple lines as needed to not exceed the * width limit WIDE. The current RENDlib text control parameters are used * to determine the text size. * * All resulting wrapped text, if any, is inserted as new lines immediately * following the current position in LIST. The position will be left at * the last line added, or at the original position if nothing was added. * * Some STR characters have special meaning: * * LINE FEED (10) - Unconditionally start a new line. * * The SIZE field of LIST is trashed. } procedure gui_string_wrap ( {wrap string into multiple lines} in str: univ string_var_arg_t; {input string} in wide: real; {width to wrap to, uses curr RENDlib tparms} in out list: string_list_t); {insert at current string position} val_param; var p: string_index_t; {STR parse index} tk: string_var8192_t; {token parsed from STR} ostr: string_var8192_t; {one line wrapped string buffer} spacew: real; {width of one space character} ow: real; {current width of string in OSTR} aw: real; {additional width if token added to OSTR} bv, up, ll: vect_2d_t; {text string size and position parameters} nspace: sys_int_machine_t; {number of spaces needed before new token} label loop_token, new_line, add_token, leave; begin tk.max := size_char(tk.str); {init local var strings} ostr.max := size_char(ostr.str); rend_set.enter_rend^; {push one level into graphics mode} p := 1; {init input string parse index} rend_get.txbox_txdraw^ ( {measure the size of the blank character} ' ', 1, {string and string length} bv, up, ll); {returned string metrics} spacew := bv.x; {save width of space character} ostr.len := 0; {init accumulated output line to empty} ow := 0.0; {init width of text in OSTR} loop_token: {back here to get each new input string token} tk.len := 0; {init parsed token to empty} while (p <= str.len) and then (str.str[p] = ' ') {skip over leading blanks} do p := p + 1; if p > str.len then goto leave; {input string exhausted ?} if str.str[p] = chr(10) then begin {LINE FEED, start a new line ?} p := p + 1; {use up this special character} goto new_line; {close the current line} end; while (p <= str.len) and then (str.str[p] <> ' ') do begin {loop until blank char} if str.str[p] = chr(10) then begin {LINE FEED special case ?} exit; {token ends before this special character} end; string_append1 (tk, str.str[p]); {append this char to parsed token} p := p + 1; {advance to next input string character} end; {back to process this new input string char} if tk.len <= 0 then goto leave; {got no token, hit end of string ?} { * The next input string token is in TK. This token is treated as being * indivisible. } rend_get.txbox_txdraw^ ( {measure the size of this token} tk.str, tk.len, {string and string length} bv, up, ll); {returned string metrics} aw := bv.x; {init additional width to raw token width} nspace := 0; {init spaces needed before new token} if ostr.len <= 0 then goto add_token; {always add token to empty output string} case ostr.str[ostr.len] of {what is last character of previous token ?} '.', '?', '!': nspace := 2; {extra space after these sentence end chars} otherwise nspace := 1; {normal single space} end; aw := aw + nspace * spacew; {additional width if token added to OSTR} if ow + aw <= wide then goto add_token; {this token still fits onto output string} { * The current token can't be added to the output string because that would * make it too wide. } new_line: list.size := ostr.len; {set length for any new lines} string_list_line_add (list); {create new line and make it current} string_copy (ostr, list.str_p^); {copy this line into strings list} ostr.len := 0; {reset output line to empty} ow := 0.0; nspace := 0; {add no padding before token on new line} if tk.len <= 0 then goto loop_token; {no token to start new line with ?} aw := bv.x; {update token width without padding} { * The current token is to be added to the end of the accumulated output line. } add_token: string_appendn (ostr, ' ', nspace); {add spaces before new token} string_append (ostr, tk); {append the new token} ow := ow + aw; {update current width of output string} goto loop_token; leave: {common exit point} if ostr.len > 0 then begin {unwritten output fragment exists ?} list.size := ostr.len; {set length for any new lines} string_list_line_add (list); {create new line and make it current} string_copy (ostr, list.str_p^); {copy this line into strings list} end; rend_set.exit_rend^; {pop one level out of graphics mode} end;
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit BindOutputConvertersFormU; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ActnList, Data.Bind.Components, System.Generics.Collections, System.Bindings.Outputs, DesignIntf, System.Actions; type TBindOutputConvertersForm = class(TForm) HelpBtn: TButton; OKBtn: TButton; CancelBtn: TButton; ActionList1: TActionList; AcceptAction: TAction; ListView1: TListView; CheckBoxSelectAll: TCheckBox; ActionSelectAll: TAction; procedure HelpBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure DataBindingListCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure DataBindingListDblClick(Sender: TObject); procedure AcceptActionUpdate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ListView1Click(Sender: TObject); procedure ListView1Change(Sender: TObject; Item: TListItem; Change: TItemChange); procedure actnSelectAllUpdate(Sender: TObject); procedure actSelectAllExecute(Sender: TObject); procedure ListView1InfoTip(Sender: TObject; Item: TListItem; var InfoTip: string); private FSortColumn: Integer; FDictionary: TDictionary<Pointer, TConverterDescription>; FBindArtifacts: TBindArtifacts; FArtifactDictionary: TDictionary<string, TBindArtifactItem>; FModified: Boolean; FUpdateAllChecked: Boolean; FAllChecked: Boolean; FAllUnchecked: Boolean; FChecking: Boolean; FDesignerIntf: IDesigner; function AddArtifact(AArtifact: TConverterDescription): TListItem; procedure AddArtifacts(AUpdateColumns: Boolean); function GetRegKey: string; procedure SetBindArtifacts(const Value: TBindArtifacts); procedure Modified; procedure CheckAllItems(ACheck: Boolean); procedure UpdateAllChecked; function GetAllChecked: Boolean; function GetAllUnChecked: Boolean; procedure SelectAllItems; procedure LoadSizes; procedure SaveSizes; procedure SetDesigner(const Value: IDesigner); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ApplyChanges; property BindArtifacts: TBindArtifacts read FBindArtifacts write SetBindArtifacts; property DesignerIntf: IDesigner read FDesignerIntf write SetDesigner; end; implementation {$R *.dfm} uses DsnConst, System.Win.Registry; procedure TBindOutputConvertersForm.HelpBtnClick(Sender: TObject); begin Application.HelpContext(HelpContext); end; procedure TBindOutputConvertersForm.ListView1Change(Sender: TObject; Item: TListItem; Change: TItemChange); begin // if Change = ctState then begin FUpdateAllChecked := True; Modified; end; end; procedure TBindOutputConvertersForm.ListView1Click(Sender: TObject); begin // end; procedure TBindOutputConvertersForm.ListView1InfoTip(Sender: TObject; Item: TListItem; var InfoTip: string); var LConverter: TConverterDescription; begin if Item <> nil then begin if not FDictionary.ContainsKey(Item.Data) then begin Assert(False); end; LConverter := FDictionary[Item.Data]; if LConverter.Description <> '' then InfoTip := LConverter.Description else InfoTip := LConverter.DisplayName; end; end; procedure TBindOutputConvertersForm.Modified; begin FModified := True; end; function TBindOutputConvertersForm.AddArtifact(AArtifact: TConverterDescription): TListItem; function FrameworkName(AFrameworkClass: TPersistentClass): string; begin if (AFrameworkClass = nil) or TComponent.InheritsFrom(AFrameworkClass) then Result := '' else begin if TControl.InheritsFrom(AFrameworkClass) then Result := 'VCL' // Do not localize else Result := 'FMX' // Do not localize end; end; var LItem: TListItem; LCaption: string; I: Integer; LBindArtifactItem: TBindArtifactItem; LHaveItem: Boolean; begin LItem := ListView1.Items.Add; with LItem do begin LHaveItem := FArtifactDictionary.TryGetValue(AArtifact.ID, LBindArtifactItem); Caption := AArtifact.ID; for I := 1 to ListView1.Columns.Count - 1 do begin case I of 1: LCaption := AArtifact.UnitName; 2: LCaption := FrameworkName(AArtifact.FrameWorkClass); else LCaption := ''; end; LItem.SubItems.Add(LCaption); end; if LHaveItem then LItem.Checked := LBindArtifactItem.State = TBindArtifactState.eaInclude else LItem.Checked := AArtifact.DefaultEnabled; end; Result := LItem; end; procedure TBindOutputConvertersForm.AddArtifacts(AUpdateColumns: Boolean); var LConverter: TConverterDescription; LCounter: Integer; LItem: TListItem; LKeys: TList<string>; begin LCounter := 0; LKeys := TList<string>.Create; try ListView1.Items.BeginUpdate; try ListView1.Items.Clear; FDictionary.Clear; for LConverter in TValueRefConverterFactory.GetConverterDescriptions do begin // Converters with the same ID are considered part of the same set (e.g.; FloatToStr ID is for extended and single converters) if not LKeys.Contains(LConverter.ID) then begin LItem := AddArtifact(LConverter); LItem.Data := Pointer(LCounter); FDictionary.Add(LItem.Data, LConverter); Inc(LCounter); LKeys.Add(LConverter.ID); end; end; finally ListView1.Items.EndUpdate; FUpdateAllChecked := True; end; finally LKeys.Free; end; end; procedure TBindOutputConvertersForm.ApplyChanges; var LListItem: TListItem; LConverter: TConverterDescription; LBindArtifact: TBindArtifactItem; LHaveItems: Boolean; LChecked: Boolean; begin for LListItem in ListView1.Items do begin if not FDictionary.ContainsKey(LListItem.Data) then begin Assert(False); continue; end; LConverter := FDictionary[LListItem.Data]; LChecked := LListItem.Checked; LHaveItems := FArtifactDictionary.TryGetValue(LConverter.ID, LBindArtifact); if (not LHaveItems) then begin if LChecked <> LConverter.DefaultEnabled then begin LBindArtifact := TBindArtifactItem(FBindArtifacts.Add); LBindArtifact.ID := LConverter.ID; if LChecked then LBindArtifact.State := TBindArtifactState.eaInclude else LBindArtifact.State := TBindArtifactState.eaExclude end; end else begin if LChecked then begin if LConverter.DefaultEnabled then begin //if this is defaultEnabled, remove the item instead of marking the state FBindArtifacts.Delete(LBindArtifact.Index); FArtifactDictionary.Remove(LConverter.ID); end else LBindArtifact.State := TBindArtifactState.eaInclude end else LBindArtifact.State := TBindArtifactState.eaExclude end; end; end; constructor TBindOutputConvertersForm.Create(AOwner: TComponent); begin inherited; FDictionary := TDictionary<Pointer, TConverterDescription>.Create; FArtifactDictionary := TDictionary<string, TBindArtifactItem>.Create; end; const sWidth = 'Width'; sHeight = 'Height'; procedure TBindOutputConvertersForm.LoadSizes; var LIndex: Integer; LSubKey: string; begin LSubKey := TBindOutputConvertersForm.ClassName; with TRegIniFile.Create(GetRegKey) do try Width := ReadInteger(LSubKey, sWidth, Width); Height := ReadInteger(LSubKey, sHeight, Height); for LIndex := 0 to ListView1.Columns.Count - 1 do with ListView1.Columns.Items[LIndex] do Width := ReadInteger(LSubKey, sWidth+IntToStr(LIndex), Width); finally Free; end; end; procedure TBindOutputConvertersForm.SaveSizes; var LIndex: Integer; LSubKey: string; begin LSubKey := TBindOutputConvertersForm.ClassName; with TRegIniFile.Create(GetRegKey) do try EraseSection(LSubKey); WriteInteger(LSubKey, sWidth, Width); WriteInteger(LSubKey, sHeight, Height); for LIndex := 0 to ListView1.Columns.Count - 1 do with ListView1.Columns.Items[LIndex] do WriteInteger(LSubKey, sWidth+IntToStr(LIndex), Width); finally Free; end; end; function TBindOutputConvertersForm.GetRegKey: string; begin Result := DesignerIntf.GetBaseRegKey + '\' + sIniEditorsName + '\Output Converter Editor'; end; procedure TBindOutputConvertersForm.SetBindArtifacts( const Value: TBindArtifacts); var LItem: TCollectionItem; LBindArtifactItem: TBindArtifactItem; begin FBindArtifacts := Value; FArtifactDictionary.Clear; if FBindArtifacts <> nil then for LItem in FBindArtifacts do begin LBindArtifactItem := TBindArtifactItem(LItem); FArtifactDictionary.Add(LBindArtifactItem.ID, LBindArtifactItem); end; ListView1.Clear; AddArtifacts(True); FUpdateAllChecked := True; end; procedure TBindOutputConvertersForm.SetDesigner(const Value: IDesigner); begin FDesignerIntf := Value; if FDesignerIntf <> nil then LoadSizes; end; procedure TBindOutputConvertersForm.FormShow(Sender: TObject); begin ListView1.SetFocus; end; procedure TBindOutputConvertersForm.DataBindingListCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); begin if Abs(FSortColumn) = 1 then Compare := FSortColumn * AnsiCompareText(Item1.Caption, Item2.Caption) else Compare := FSortColumn * AnsiCompareText(Item1.SubItems[0], Item2.SubItems[0]); end; procedure TBindOutputConvertersForm.DataBindingListDblClick(Sender: TObject); begin // if OKBtn.Enabled then OKBtn.Click; end; destructor TBindOutputConvertersForm.Destroy; begin FDictionary.Free; FArtifactDictionary.Free; inherited; end; procedure TBindOutputConvertersForm.AcceptActionUpdate(Sender: TObject); begin AcceptAction.Enabled := FModified; end; procedure TBindOutputConvertersForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if DesignerIntf <> nil then SaveSizes; end; procedure TBindOutputConvertersForm.UpdateAllChecked; var I: Integer; begin if FUpdateAllChecked then begin FUpdateAllChecked := False; FAllChecked := True; FAllUnchecked := True; for I := 0 to ListView1.Items.Count - 1 do begin if not ListView1.Items[I].Checked then FAllChecked := False else FAllUnchecked := False end; if FAllChecked and FAllUnchecked then FAllChecked := False; end; end; procedure TBindOutputConvertersForm.CheckAllItems(ACheck: Boolean); var I: Integer; begin for I := 0 to ListView1.Items.Count - 1 do begin ListView1.Items[I].Checked := ACheck; end; end; function TBindOutputConvertersForm.GetAllChecked: Boolean; begin UpdateAllChecked; Result := FAllChecked; end; function TBindOutputConvertersForm.GetAllUnChecked: Boolean; begin UpdateAllChecked; Result := FAllUnChecked; end; procedure TBindOutputConvertersForm.actnSelectAllUpdate(Sender: TObject); begin if FChecking then Exit; FChecking := True; try if GetAllChecked then CheckBoxSelectAll.State := TCheckBoxState.cbChecked else if GetAllUnchecked then CheckBoxSelectAll.State := TCheckBoxState.cbUnchecked else CheckBoxSelectAll.State := TCheckBoxState.cbGrayed; finally FChecking := False; end; end; procedure TBindOutputConvertersForm.actSelectAllExecute(Sender: TObject); begin SelectAllItems; end; procedure TBindOutputConvertersForm.SelectAllItems; begin if FChecking then Exit; if GetAllChecked then //CheckAll(TCheckState.csUnCheckedNormal) CheckAllItems(False) else if GetAllUnchecked then //CheckAll(TCheckState.csCheckedNormal) CheckAllItems(True) else //CheckAll(TCheckState.csUnCheckedNormal); CheckAllItems(False); end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2015-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit EMSHosting.ExtensionsServices; {$HPPEMIT LINKUNIT} interface function AddService(const Handler: IUnknown): Integer; procedure RemoveService(Index: Integer); implementation uses System.SysUtils, System.Generics.Collections, System.Classes, EMS.Services, EMS.ResourceTypes, EMSHosting.Utility, System.JSON, EMS.ResourceApi, EMSHosting.ResourceManager, EMSHosting.Consts, EMSHosting.Endpoints; var OTAExtensions: IInterfaceList; type TEMSExtensionServices = class(TInterfacedObject, IInterface, IEMSServices, IEMSEndPointSegmentsService) public { IInterface } function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; { IEMSServices } function SupportsService(const Service: TGUID): Boolean; function GetService(const Service: TGUID): IInterface; overload; function TryGetService(const Service: TGUID; out Svc): Boolean; overload; { IEMSEndPointSegmentsService } procedure ExtractSegments(const AString: string; const AList: TEMSEndPointSegmentList); function CountSegments(const AValue: string): Integer; end; procedure CreateServices; begin if EMSServices = nil then EMSServices := TEMSExtensionServices.Create; end; function AddToList(const List: IInterfaceList; Item: IUnknown): Integer; var I: Integer; begin for I := 0 to List.Count - 1 do if List[I] = nil then begin List[I] := Item; Result := I; Exit; end; Result := List.Add(Item); end; function AddService(const Handler: IUnknown): Integer; begin if OTAExtensions = nil then OTAExtensions := TInterfaceList.Create; Result := AddToList(OTAExtensions, Handler); end; procedure RemoveService(Index: Integer); begin if OTAExtensions <> nil then OTAExtensions[Index] := nil; end; function TEMSExtensionServices.GetService(const Service: TGUID): IInterface; begin if not Supports(Self, Service, Result) then Result := nil; end; function TEMSExtensionServices.CountSegments(const AValue: string): Integer; var LTemp: TStrings; begin if AValue.StartsWith('/') then LTemp := ParseURLPath(AValue.Substring(1)) else LTemp := ParseURLPath(AValue); try Result := LTemp.Count; finally LTemp.Free; end; end; procedure TEMSExtensionServices.ExtractSegments(const AString: string; const AList: TEMSEndPointSegmentList); var LName: string; LStrings: TStrings; S: string; begin if AString.StartsWith('/') then LStrings := ParseURLPath(AString.Substring(1)) else LStrings := ParseURLPath(AString); try for S in LStrings do begin if S = '/' then TEMSEndPointSegmentSlash.Create(AList) else if S = '*' then TEMSEndPointSegmentWildcard.Create(AList) else if S.StartsWith('{') then begin if S.EndsWith('}') then LName := S.Substring(1, S.Length - 2) else if S.EndsWith('}/') then LName := S.Substring(1, S.Length - 3) else if S.EndsWith('/') then LName := S.Substring(1, S.Length-2) else LName := S.Substring(1, S.Length-1); TEMSEndPointSegmentParameter.Create(AList, LName); end else TEMSEndPointSegmentConstant.Create(AList, S); end; finally LStrings.Free; end; end; function TEMSExtensionServices.TryGetService(const Service: TGUID; out Svc): Boolean; begin Result := Supports(Self, Service, Svc); end; function TEMSExtensionServices.SupportsService(const Service: TGUID): Boolean; begin Result := Supports(Self, Service); end; function TEMSExtensionServices.QueryInterface(const IID: TGUID; out Obj): HResult; var I: Integer; Item: IUnknown; begin try if GetInterface(IID, Obj) then begin Result := S_OK; Exit; end else if OTAExtensions <> nil then for I := 0 to OTAExtensions.Count - 1 do begin Item := OTAExtensions[I]; if Item <> nil then begin Result := Item.QueryInterface(IID, Obj); Item := nil; if Result = S_OK then Exit; end; end; except // in case something horribly bogus is passed in Obj, fail silently and return failure // this is fairly easy to do when talking to the OTA from C++ end; Result := E_NOINTERFACE; end; initialization CreateServices; finalization EMSServices := nil; end.
unit MD5.Version; interface uses System.SysUtils, System.StrUtils, Windows; type /// <summary> /// This structure describes a file version /// </summary> TVersion = record Version: String; CompanyName: String; ProgramName: String; Comments: String; end; /// <summary> /// Retrieve a version from the executable file /// </summary> procedure GetVersion(var Version: TVersion); implementation procedure GetVersion(var Version: TVersion); var Dummy: Cardinal; Buffer: Pointer; Size: Cardinal; // PInfo: Pointer; PFix: PVsFixedFileInfo; PTransl: PWordArray; // S: String; begin Version.Version := ''; Version.CompanyName := ''; Version.ProgramName := ''; Version.Comments := ''; // Узнаем номер версии Size := GetFileVersionInfoSize(PChar(ParamStr(0)), Dummy); if Size > 0 then begin GetMem(Buffer, Size); if GetFileVersionInfo(PChar(ParamStr(0)), 0, Size, Buffer) then begin // Запрос версии if VerQueryValue(Buffer, '\', Pointer(PFix), Size) then begin S := IfThen((PFix^.dwFileFlags AND VS_FF_PRERELEASE) <> 0, 'b', ''); Version.Version := Format('%d.%d.%d/%d%s', [HiWord(PFix^.dwFileVersionMS), LoWord(PFix^.dwFileVersionMS), HiWord(PFix^.dwFileVersionLS), LoWord(PFix^.dwFileVersionLS), S]); end; if VerQueryValue(Buffer, '\VarFileInfo\Translation', Pointer(PTransl), Size) then begin S := '\StringFileInfo\' + IntToHex(PTransl^[0], 4) + IntToHex(PTransl^[1], 4); if VerQueryValue(Buffer, PChar(S + '\ProductName'), PInfo, Size) then Version.ProgramName := PChar(PInfo); if VerQueryValue(Buffer, PChar(S + '\CompanyName'), PInfo, Size) then Version.CompanyName := PChar(PInfo); if VerQueryValue(Buffer, PChar(S + '\Comments'), PInfo, Size) then Version.Comments := PChar(PInfo); end; end; FreeMem(Buffer); end; end; end.
unit JEDECQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap; type TJEDECW = class(TDSWrap) private FJEDEC: TFieldWrap; FID: TFieldWrap; public constructor Create(AOwner: TComponent); override; function LocateOrAppend(const AJedec: string): Boolean; property JEDEC: TFieldWrap read FJEDEC; property ID: TFieldWrap read FID; end; TQueryJEDEC = class(TQueryBase) private FW: TJEDECW; { Private declarations } public constructor Create(AOwner: TComponent); override; property W: TJEDECW read FW; { Public declarations } end; implementation {$R *.dfm} constructor TQueryJEDEC.Create(AOwner: TComponent); begin inherited; FW := TJEDECW.Create(FDQuery); end; constructor TJEDECW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FJEDEC := TFieldWrap.Create(Self, 'JEDEC'); end; function TJEDECW.LocateOrAppend(const AJedec: string): Boolean; begin Assert(not AJedec.IsEmpty); Result := JEDEC.Locate( AJedec, [lxoCaseInsensitive] ); if Result then Exit; TryAppend; JEDEC.F.AsString := AJedec; TryPost; end; end.
unit SIP_App; interface uses SIP_Status,Classes,SIP_QueueManager,Contnrs, SMS_Queue, Mail_Queue, Event_RS232; type TSIPApp = class (TObject) public SIPStatus:TSIPStatus; SIPQueueManager:TSIPQueueManager; SIPChannels:TObjectList; SMSQueue:TSMSQueue; MailQueue:TMailQueue; EventRS232:TEventRS232; constructor Create(ChannelCount,ComPort,Bits,Baud,StopBits:Integer;Parity:String;RSPort:Integer;Signal:TSignalProc;SMTPHost,SMTPPort,SMTPUser,SMTPPass,SMTPFrom:String); procedure Stop(EventID:Integer); destructor Destroy;override; end; implementation uses SysUtils, SIP_Call; { TSIPApp } constructor TSIPApp.Create; var I:Integer; begin SIPStatus:=TSIPStatus.Create(ChannelCount); SIPQueueManager:=TSIPQueueManager.Create(Self,ChannelCount+1); SMSQueue:=TSMSQueue.Create(ComPort,Bits,Baud,StopBits,Parity,Self); MailQueue:=TMailQueue.Create(SMTPHost,SMTPPort,SMTPUser,SMTPPass,SMTPFrom,Self); SIPChannels:=TObjectList.Create; SIPChannels.OwnsObjects:=True; for I := 1 to ChannelCount do SIPChannels.Add(TSIPCall.Create(Self,I)); EventRS232:=TEventRS232.Create(RSPort,Signal); end; destructor TSIPApp.Destroy; begin SIPQueueManager.Close; FreeAndNil(EventRS232); FreeAndNil(SIPChannels); FreeAndNil(MailQueue); FreeAndNil(SMSQueue); FreeAndNil(SIPQueueManager); FreeAndNil(SIPStatus); inherited; end; procedure TSIPApp.Stop(EventID: Integer); var I: Integer; begin SIPQueueManager.Stop(EventID); for I := 0 to SIPChannels.Count - 1 do TSIPCall(SIPChannels[I]).StopEvent(EventID); end; end.
unit Unit4; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdActns, ActnList, LangManCtrls, ComCtrls, LangManSys, LangManComp, TeeProcs, TeEngine, Chart, StdCtrls, ExtCtrls, Menus, ToolWin, ImgList, LangManCore, System.Actions; type TMainForm = class(TForm) ActionList1: TActionList; FileOpen1: TFileOpen; FileSaveAs1: TFileSaveAs; FileExit1: TFileExit; MainMenu1: TMainMenu; File1: TMenuItem; Language1: TMenuItem; Open1: TMenuItem; SaveAs1: TMenuItem; Exit1: TMenuItem; StatusBar: TStatusBar; LangManEngine: TLangManEngine; LangManClient: TLangManClient; DesignedLexicon: TDesignedLexicon; Pages: TPageControl; BasicsTab: TTabSheet; GridPanel1: TGridPanel; Label1: TLabel; ComboBox1: TComboBox; Button1: TButton; LangFlagsCombo1: TLangFlagsCombo; ValuedLabel1: TValuedLabel; ValuedLabel2: TValuedLabel; Chart1: TChart; RichTab: TTabSheet; Memo1: TMemo; Rich: TLangManRichEdit; ReportBtn: TButton; GDBtn: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ReportBtnClick(Sender: TObject); procedure GDBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; Memo: TLangManStrings; implementation {$R *.dfm} const BOLD_RED = 0; HEADING = 1; NOTE = 2; procedure TMainForm.ReportBtnClick(Sender: TObject); begin // Generate DEMO Report to TLangManRichEdit Rich.WriteLn(DesignedLexicon.Link[2], HEADING); Rich.WriteLn(''); // OR Rich.NextLine Rich.Write(DesignedLexicon.Link[3] + ' '); Rich.Writeln(DateToStr(Date), BOLD_RED); Rich.NextLine; // OR Rich.Writeln('') Rich.WriteLn(DesignedLexicon.Link[4] + ' (' + Rich.Format(DesignedLexicon.Link[5], NOTE) + ')'); Rich.NextLine; // Generate DEMO Report to TMemo via TLangManStrings Memo.Add(DesignedLexicon.Link[2]); Memo.Add(''); Memo.Add(DesignedLexicon.Link[3] + ' ' + DateToStr(Date)); Memo.Add(''); Memo.Add(DesignedLexicon.Link[4] + ' (' + DesignedLexicon.Link[5] + ')'); Memo.Add(''); // GDBtn.Visible := true; end; procedure TMainForm.FormCreate(Sender: TObject); begin // LangMan for Memo1 Memo := TLangManStrings.Create(Memo1.Lines, DesignedLexicon); // Rich: TLangManRichEdit - define styles Rich.SetStyle([fsBold], 0, clRed); // BOLD_RED Rich.SetStyle([fsBold, fsItalic, fsUnderLine], 12, clBlue); // HEADING Rich.SetStyle([fsItalic]); // NOTE end; procedure TMainForm.FormDestroy(Sender: TObject); begin Memo.Free; end; procedure TMainForm.GDBtnClick(Sender: TObject); begin Rich.SetStyle([fsBold], 0, clGreen,'',DEFAULT_CHARSET,fpDefault, BOLD_RED); // OR (same effect:) // Rich.GetStyles[BOLD_RED].Color := clGreen; // Rich.Translate; end; end.
(* **************************************************************** *) (* Copyright (C) 1999-2010, Jon Gentle, All right reserved. *) (* **************************************************************** *) (* This program is free software; you can redistribute it under the *) (* terms of the Artistic License, as specified in the LICENSE file. *) (* **************************************************************** *) unit error; interface type TError = class constructor create(own: TObject); procedure err(s: string); procedure status(s: string); procedure stream(s: string); procedure newNode(s: string); procedure addNode(s: string); procedure popNode(s: string); procedure compile(s: string); procedure assemble(s: string); procedure link(s: string); private owner: TObject; end; implementation uses Draak, classes; constructor TError.create(own: TObject); begin if own.ClassType <> TDraak then raise EComponentError.Create('Invalid Class type:' + own.ClassName + '. Expected TDraak'); owner := own; end; procedure TError.err(s: string); begin if not assigned(owner) then exit; if Assigned(TDraak(owner).onError) then TDraak(owner).onError(self, s); end; procedure TError.status(s: string); begin if not assigned(owner) then exit; if Assigned(TDraak(owner).onStatus) then TDraak(owner).onStatus(self, s); end; procedure TError.stream(s: string); begin if not assigned(owner) then exit; if Assigned(TDraak(owner).onStream) then TDraak(owner).onStream(self, s); end; procedure TError.newNode(s: string); begin if not assigned(owner) then exit; if Assigned(TDraak(owner).onNodeCreate) then TDraak(owner).onNodeCreate(self, s); end; procedure TError.addNode(s: string); begin if not assigned(owner) then exit; if Assigned(TDraak(owner).onNodeChild) then TDraak(owner).onNodeChild(self, s); end; procedure TError.popNode(s: string); begin if not assigned(owner) then exit; if Assigned(TDraak(owner).onNodePop) then TDraak(owner).onNodePop(self, s); end; procedure TError.compile(s: string); begin if not assigned(owner) then exit; if Assigned(TDraak(owner).onCompile) then TDraak(owner).onCompile(self, s); end; procedure TError.assemble(s: string); begin if not assigned(owner) then exit; if Assigned(TDraak(owner).onAssemble) then TDraak(owner).onAssemble(self, s); end; procedure TError.link(s: string); begin if not assigned(owner) then exit; if Assigned(TDraak(owner).onLink) then TDraak(owner).onLink(self, s); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Web services description language (WSDL) } { generation from RTTI } { } { Copyright (c) 2001 Borland Software Corporation } { } {*******************************************************} unit WebServExp; interface uses SysUtils, Classes, Variants, ActiveX, IntfInfo, TypInfo, XMLIntf, XMLDoc, xmldom, XmlSchema, WSDLIntf, WSDLBind, XMLSchemaTags; type ArgumentType = (argIn, argOut, argInOut, argReturn); TSchemaType = record TypeName: WideString; NameSpace: WideString; TypeInfo: PTypeinfo; NSPrefix: WideString; XSGenerated: Boolean; end; TSchemaTypeArray = array of TSchemaType; TWebServExp = class private Definition: IDefinition; ComplexTypeList: TStringList; bHasComplexTypes: Boolean; FServiceAddress: WideString; FNameSpace: WideString; FBindingType: TBindingType; FWSDLElements: TWSDLElements; FImportNames: TWideStrings; FImportLocation: TWideStrings; FArrayAsComplexContent: Boolean; SchemaArray: TSchemaTypeArray; procedure GenerateWSDL(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument; PortNames, Locations: array of WideString); procedure GenerateNestedArraySchema(RootNode: IXMLSchemaDoc; ComplexType: IXMLComplexTypeDef; const ObjectTypeInfo: PTypeinfo; var Dimension: Integer; Namespace: WideString); procedure AddImports(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument); procedure AddTypes(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument); procedure AddMessages(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument); procedure AddPortTypes(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument); procedure AddBinding(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument); procedure AddServices(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument; PortNames: array of WideString; Locations: array of WideString); function GetXMLSchemaType(const ParamTypeInfo: PTypeInfo): string; function IsComplexType(const ParamType: TTypeKind ):Boolean; procedure SetBindingType(const Value: TBindingType); procedure SetServiceAddress(const Value: WideString); function GetImportNamespace(const Index: Integer): WideString; procedure SetImportNamespace(const Index: Integer; const Value: WideString); function GetImportLocation(const Index: Integer): WideString; procedure SetImportLocation(const Index: Integer; const Value: WideString); procedure SetArrayType(const Value: Boolean); function GetPrefixForURI(RootNode: IXMLSchemaDoc; URI: WideString): WideString; overload; function GetPrefixForURI(Def: IDefinition; URI: WideString): WideString; overload; function GetPrefixForTypeInfo(const ObjectTypeInfo: PTypeinfo): WideString; overload; function AddNamespaceURI(RootNode: IXMLNode; URI: WideString): WideString; function GetNodeNameForURI(RootNode: IXMLSchemaDoc; URI: WideString): WideString; procedure GenerateArraySchema(RootNode: IXMLSchemaDoc; const ObjectTypeInfo: PTypeinfo; Namespace: WideString); procedure GenerateEnumSchema(RootNode: IXMLSchemaDoc; const ObjectTypeInfo: PTypeinfo; Namespace: WideString); procedure GenerateClassSchema(RootNode: IXMLSchemaDoc; const ObjectTypeInfo, ParentInfo: PTypeinfo; Namespace: WideString); procedure GenerateDerivedClassSchema(RootNode: IXMLSchemaDoc; const ParentTypeInfo: PTypeinfo; Namespace: WideString); procedure GetAllSchemaTypes(const IntfMD: TIntfMetaData); procedure GetSchemaTypes(const ObjectTypeInfo, ParentInfo: PTypeinfo); function FindSchema(const ObjectTypeInfo: PTypeinfo; const TnsURI: string): Boolean; procedure GetClassSchema(const ObjectTypeInfo, ParentInfo: PTypeinfo); procedure GetDerivedClassSchema(const ParentTypeInfo: PTypeinfo); function IsSchemaGenerated(const ObjectTypeInfo: PTypeinfo; const TnsURI: WideString): Boolean; procedure GetArraySchema(const ObjectTypeInfo: PTypeinfo); public constructor Create; destructor Destroy; override; procedure GetWSDLForInterface(const IntfTypeInfo: Pointer; WSDLDoc: IWSDLDocument; PortNames, Locations: array of WideString); procedure GenerateXMLSchema(RootNode: IXMLSchemaDoc; const ObjectTypeInfo, ParentInfo: PTypeinfo; Namespace: WideString); property ImportNames [const Index: Integer]: WideString read GetImportNamespace write SetImportNamespace; property ImportLocations[const Index: Integer]: WideString read GetImportLocation write SetImportLocation; published property ArrayAsComplexContent: Boolean read FArrayAsComplexContent write SetArrayType; property BindingType: TBindingType read FBindingType write SetBindingType; property ServiceAddress: WideString read FServiceAddress write SetServiceAddress; property WSDLElements: TWSDLElements read FWSDLElements write FWSDLElements default [weServiceIntf]; end; implementation uses InvokeRegistry, SOAPConst; { WebServExp Implementation } constructor TWebServExp.Create; begin ComplexTypeList := TStringList.Create; FWSDLElements := [weServiceIntf]; FImportNames := TWideStrings.Create; FImportLocation := TWideStrings.Create; FArrayAsComplexContent := True; end; destructor TWebServExp.Destroy; begin ComplexTypeList.Free; FImportNames.Free; FImportLocation.Free; inherited Destroy; end; procedure TWebServExp.SetArrayType(const Value: Boolean); begin FArrayAsComplexContent := Value; end; procedure TWebServExp.SetBindingType(const Value: TBindingType); begin FBindingType := Value; end; procedure TWebServExp.SetServiceAddress(const Value: WideString); begin FServiceAddress := Value; end; function TWebServExp.GetImportNamespace(const Index: Integer): WideString; begin if FImportNames.Count > Index then Result := FImportNames.Strings[Index] else Result := ''; end; function TWebServExp.GetImportLocation(const Index: Integer): WideString; begin if FImportLocation.Count > Index then Result := FImportLocation.Strings[Index] else Result := ''; end; procedure TWebServExp.SetImportNamespace(const Index: Integer; const Value: WideString); begin FImportNames.Insert(Index, Value); end; procedure TWebServExp.SetImportLocation(const Index: Integer; const Value: WideString); begin FImportLocation.Insert(Index, Value); end; procedure TWebServExp.GetWSDLForInterface(const IntfTypeInfo: Pointer; WSDLDoc: IWSDLDocument; PortNames, Locations: array of WideString); var IntfMD: TIntfMetaData; begin bHasComplexTypes := False; GetIntfMetaData(IntfTypeInfo, IntfMD); GenerateWSDL(IntfMD, WSDLDoc, PortNames, Locations); end; procedure TWebServExp.GenerateWSDL(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument; PortNames, Locations: array of WideString); var //Definition: IDefinition; Encoding: WideString; begin if IntfMD.Name <> '' then begin //Add WSDL:Definitions and its attributes Definition := WSDLDoc.Definition; Definition.Attributes[Sname] := IntfMD.Name+SService; Definition.Attributes[Stns] := tns; //Definition.Attributes['xmlns:xsd'] := Xsdns; //Need to auto generate Namespace prefix Definition.Attributes['xmlns:soap'] := Soapns; Definition.Attributes['xmlns:soapenc'] := SSoap11EncodingS5; //Add Encoding if WSDLDoc.Encoding = '' then begin Encoding := InvRegistry.GetWSDLEncoding(IntfMD.Info, '', IntfMD.Name); if Encoding <> '' then WSDLDoc.Encoding := Encoding else WSDLDoc.Encoding := 'utf-8'; end; //Set the Namespace prefix (WSDLDoc as IXMLDocumentAccess).DocumentObject.NSPrefixBase := SNsPrefix; //Add WSDL Types if (WeTypes in FWSDLElements) or (WeServiceIntf in FWSDLElements) then AddTypes(IntfMD, WSDLDoc); //Add Imports if (WeImport in FWSDLElements) or (WeServiceImpl in FWSDLElements) then if (FImportNames.Count = FImportLocation.Count) then AddImports(IntfMD, WSDLDoc); //Add WSDL Message and its parts if ((weMessage in FWSDLElements) or (weServiceIntf in FWSDLElements) ) then AddMessages(IntfMD, WSDLDoc); //Add WSDL PortType and its Operations if ((wePortType in FWSDLElements) or (weServiceIntf in FWSDLElements) ) then AddPortTypes(IntfMD, WSDLDoc); //Add WSDL Binding for operations if (WeBinding in FWSDLElements) or (weServiceIntf in FWSDLElements) then AddBinding(IntfMD, WSDLDoc); //Add WSDL Service and its port if (WeService in FWSDLElements) or (WeServiceImpl in FWSDLElements) then AddServices(IntfMD, WSDLDoc, PortNames, Locations); end; end; procedure TWebServExp.AddImports(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument); var Imports: IImports; Index: Integer; begin Imports := WSDLDoc.Definition.Imports; for Index := 0 to FImportNames.Count -1 do Imports.Add(FImportNames.Strings[Index], FImportLocation.Strings[Index]); end; procedure TWebServExp.AddMessages(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument); var IntfMethArray: TIntfMethEntryArray; ParamArray: TIntfParamEntryArray; Methods, Params, NoOfMethods, NoOfParams: Integer; ParamType: string; Messages: IMessages; NewMessage: IMessage; Parts: IParts; MethodExtName, ParamExtName: WideString; begin IntfMethArray := nil; ParamArray := nil; IntfMethArray := IntfMD.MDA; NoOfMethods := Length(IntfMethArray); //Add WSDL Message and its parts Messages := WSDLDoc.Definition.Messages; for Methods := 0 to NoOfMethods -1 do begin ParamArray := IntfMD.MDA[Methods].Params; NoOfParams := Length(ParamArray); //Add InOut parts MethodExtName := InvRegistry.GetMethExternalName(IntfMD.Info, IntfMD.MDA[Methods].Name); NewMessage := Messages.Add(MethodExtName + SRequest); Parts := NewMessage.Parts; for Params := 0 to NoOfParams -2 do begin if not (pfOut in ParamArray[Params].Flags) then begin ParamType := GetXMLSchemaType(ParamArray[Params].Info); ParamExtName := InvRegistry.GetParamExternalName(IntfMD.Info, MethodExtName, ParamArray[Params].Name); Parts.Add(ParamExtName,'',ParamType); end; end; //Add Out parts NewMessage := Messages.Add(MethodExtName + SResponse); Parts := NewMessage.Parts; for Params := 0 to NoOfParams -2 do begin if ( (pfOut in ParamArray[Params].Flags) or (pfVar in ParamArray[Params].Flags) ) then begin ParamType := GetXMLSchemaType(ParamArray[Params].Info); ParamExtName := InvRegistry.GetParamExternalName(IntfMD.Info, MethodExtName, ParamArray[Params].Name); Parts.Add(ParamExtName,'',ParamType); end; end; //For Functions creat a response if IntfMD.MDA[Methods].ResultInfo <> nil then begin ParamType := GetXMLSchemaType(IntfMD.MDA[Methods].ResultInfo); Parts.Add(SReturn,'',ParamType); end; end; end; procedure TWebServExp.AddPortTypes(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument); var IntfMethArray: TIntfMethEntryArray; ParamArray: TIntfParamEntryArray; Methods, Params, NoOfMethods, NoOfParams: Integer; PortTypes: IPortTypes; PortType: IPortType; Operations: IOperations; PortExtName, MethodExtName: WideString; HasOut: Boolean; begin //Add WSDL PortType and its Operations IntfMethArray := nil; ParamArray := nil; IntfMethArray := IntfMD.MDA; NoOfMethods := Length(IntfMethArray); PortTypes := WSDLDoc.Definition.PortTypes; PortExtName := InvRegistry.GetInterfaceExternalName(IntfMD.Info,'',IntfMD.Name); PortType := PortTypes.Add(PortExtName); for Methods := 0 to NoOfMethods -1 do begin Operations := PortType.Operations; HasOut := False; ParamArray := IntfMD.MDA[Methods].Params; NoOfParams := Length(ParamArray); for Params := 0 to NoOfParams -2 do begin if ((pfOut in ParamArray[Params].Flags) or (pfVar in ParamArray[Params].Flags)) then HasOut := True; end; if ( (IntfMD.MDA[Methods].ResultInfo <> nil) or HasOut ) then begin MethodExtName := InvRegistry.GetMethExternalName(IntfMD.Info, IntfMD.MDA[Methods].Name); Operations.Add(MethodExtName, MethodExtName+ SRequest, '', MethodExtName+ SResponse); end else begin MethodExtName := InvRegistry.GetMethExternalName(IntfMD.Info, IntfMD.MDA[Methods].Name); Operations.Add(MethodExtName,MethodExtName+ SRequest, '', ''); end; end; end; procedure TWebServExp.AddBinding(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument); var IntfMethArray: TIntfMethEntryArray; Methods, NoOfMethods: Integer; Bindings: IBindings; Binding: IBinding; BindOperations: IBindingOperations; NewBindOperation: IBindingOperation; NewNode, SoapBodyNode: IXMLNode; PortExtName, MethodExtName: WideString; begin //Add WSDL Binding and its Operations IntfMethArray := nil; IntfMethArray := IntfMD.MDA; NoOfMethods := Length(IntfMethArray); Bindings := WSDLDoc.Definition.Bindings; PortExtName := InvRegistry.GetInterfaceExternalName(IntfMD.Info,'',IntfMD.Name); Binding := Bindings.Add(PortExtName+SBinding,PortExtName); //Add Binding specific elements if FBindingType = btSoap then begin //Add soap:binding NewNode := Binding.AddChild(SWSDLSoapBinding); NewNode.Attributes[SStyle] := 'rpc'; NewNode.Attributes[STransport] := SSoapHTTPTransport; end; for Methods := 0 to NoOfMethods -1 do begin BindOperations := Binding.BindingOperations; MethodExtName := InvRegistry.GetMethExternalName(IntfMD.Info, IntfMD.MDA[Methods].Name); NewBindOperation := BindOperations.Add(MethodExtName); if FBindingType = btSoap then begin //Add soap:operation NewNode := NewBindOperation.AddChild(SWSDLSoapOperation); NewNode.Attributes[SSoapAction] := InvRegistry.GetNamespaceByGUID(IntfMD.IID) + '#' + MethodExtName; //NewNode.Attributes[SStyle] := 'rpc'; end; //Add input/output NewNode := NewBindOperation.AddChild(SInput); if FBindingType = btSoap then begin SoapBodyNode := NewNode.AddChild(SWSDLSoapBody); //SoapBodyNode.Attributes[SParts] := ''; SoapBodyNode.Attributes[SUse] := SSoapBodyUseEncoded; SoapBodyNode.Attributes[SEncodingStyle] := SSoap11EncodingS5; SoapBodyNode.Attributes[SNameSpace] := InvRegistry.GetNamespaceByGUID(IntfMD.IID); if IntfMD.MDA[Methods].ResultInfo <> nil then begin NewNode := NewBindOperation.AddChild(SOutput); SoapBodyNode := NewNode.AddChild(SWSDLSoapBody); //SoapBodyNode.Attributes[SParts] := ''; SoapBodyNode.Attributes[SUse] := SSoapBodyUseEncoded; SoapBodyNode.Attributes[SEncodingStyle] := SSoap11EncodingS5; SoapBodyNode.Attributes[SNameSpace] := InvRegistry.GetNamespaceByGUID(IntfMD.IID); end; end; //Add soap:body //Add soap:Header //Add soap:Fault end; end; procedure TWebServExp.AddServices(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument; PortNames: array of WideString; Locations: array of WideString); var Services: IServices; NewService: IService; NewPort: IPort; NewNode: IXMLNode; I: Integer; PortExtName: WideString; begin Services := WSDLDoc.Definition.Services; PortExtName := InvRegistry.GetInterfaceExternalName(IntfMD.Info,'',IntfMD.Name); NewService := Services.Add(PortExtName + SService); for I := 0 to Length(Locations) - 1 do begin NewPort := NewService.Ports.Add(PortNames[I], PortExtName+SBinding); NewNode := NewPort.AddChild(SWSDLSoapAddress); NewNode.Attributes[SLocation] := Locations[I]; end; end; procedure TWebServExp.AddTypes(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument); var NewNode: IXMLNode; Xsd: IXMLSchemaDoc; Index, Count: Integer; UniqueURI: TWideStrings; begin //Collect all schema types to be generated GetAllSchemaTypes(IntfMD); if Length(SchemaArray) > 0 then begin UniqueURI := TWideStrings.Create; try //Get Unique URI's and namespace prefix for Index := 0 to Length(SchemaArray) -1 do begin if ( UniqueURI.IndexOf(SchemaArray[Index].NameSpace)= -1 ) then UniqueURI.Add(SchemaArray[Index].NameSpace); SchemaArray[Index].NSPrefix := GetPrefixForURI(Definition, SchemaArray[Index].NameSpace); end; NewNode := WSDLDoc.Definition.AddChild(STypes); //Add seperate schema nodes for each unique URI for Count := 0 to UniqueURI.Count -1 do begin Xsd := NewXmlSchema; Xsd.SchemaDef.Attributes[STns] := UniqueURI.Strings[Count]; for Index := 0 to Length(SchemaArray) -1 do GenerateXMLSchema(Xsd, SchemaArray[Index].TypeInfo, nil, UniqueURI.Strings[Count]); NewNode.ChildNodes.Add(Xsd.DocumentElement.CloneNode(True)); end; finally UniqueURI.Free; end; end; end; // Consider TOrdType and TFloatType subtypes of tkInteger and tkFloat... // share with TypeTrans.pas ?? function TWebServExp.GetXMLSchemaType(const ParamTypeInfo: PTypeInfo ):string; var TypeName, URI, Prefix: WideString; begin Prefix := ''; case ParamTypeInfo^.Kind of tkClass, tkDynArray, tkEnumeration, tkSet: begin URI := SXMLSchemaURI_2000_10; RemTypeRegistry.TypeInfoToXSD(ParamTypeInfo, URI , TypeName); if TypeName = '' then begin URI := SXMLSchemaURI_1999; RemTypeRegistry.TypeInfoToXSD(ParamTypeInfo, URI , TypeName); end; if ((URI <> SXMLSchemaURI_2000_10) and (URI <> SXMLSchemaURI_1999) and (URI <> SXMLSchemaURI_2001)) then begin Prefix := GetPrefixForTypeInfo(ParamTypeInfo); if Prefix <> '' then //Result := FNameSpace + ParamTypeInfo^.Name; Result := Prefix + ':' + ParamTypeInfo^.Name else Result := ParamTypeInfo^.Name; end else begin //Always get the prefix for 2001 XMLSchema URI := SXMLSchemaURI_2001; Prefix := GetPrefixForURI(Definition, URI); if Prefix <> '' then Result := Prefix + ':' + TypeName else Result := TypeName; end; bHasComplexTypes := True; end; tkVariant: begin //Always get the prefix for 2001 XMLSchema URI := SXMLSchemaURI_2001; Prefix := GetPrefixForURI(Definition, URI); if Prefix <> '' then Result := Prefix + ':' + SAnySimpleType else Result := SAnySimpleType; end else //Scalar types URI := SXMLSchemaURI_2000_10; RemTypeRegistry.TypeInfoToXSD(ParamTypeInfo, URI , TypeName); if TypeName = '' then begin URI := SXMLSchemaURI_1999; RemTypeRegistry.TypeInfoToXSD(ParamTypeInfo, URI , TypeName); end; //Always get the prefix for 2001 XMLSchema URI := SXMLSchemaURI_2001; if TypeName <> '' then begin Prefix := GetPrefixForURI(Definition, URI); if Prefix <> '' then Result := Prefix + ':' + TypeName else Result := TypeName; end else Result := SUnknown; end; end; function TWebServExp.IsComplexType(const ParamType: TTypeKind ):Boolean; begin case ParamType of tkClass, tkDynArray, tkEnumeration, tkSet: Result := True; else Result := False; end; end; function TWebServExp.GetPrefixForURI(Def: IDefinition; URI: WideString): WideString; var NameSpaceNode: IXMLNode; begin Result := ''; if Definition <> nil then begin NamespaceNode := Def.FindNamespaceDecl(URI); if NamespaceNode <> nil then begin Result := NamespaceNode.LocalName; exit; end; Result := AddNamespaceURI(Def as IXMLNode, URI); end; end; function TWebServExp.GetPrefixForURI(RootNode: IXMLSchemaDoc; URI: WideString): WideString; var NameSpaceNode: IXMLNode; begin Result := ''; //Check if the XMLSchema root has it NamespaceNode := RootNode.SchemaDef.FindNamespaceDecl(URI); if NamespaceNode <> nil then begin Result := NamespaceNode.LocalName; exit; end else begin //Check if its a WSDL and if the root has it if Definition <> nil then begin NamespaceNode := Definition.FindNamespaceDecl(URI); if NamespaceNode <> nil then begin Result := NamespaceNode.LocalName; exit; end else Result := AddNamespaceURI(Definition as IXMLNode, URI); end else Result := AddNamespaceURI(RootNode.SchemaDef as IXMLNode, URI); end; end; function TWebServExp.AddNamespaceURI(RootNode: IXMLNode; URI: WideString): WideString; begin Result := RootNode.OwnerDocument.GeneratePrefix(RootNode); RootNode.DeclareNamespace(Result, URI); end; function TWebServExp.GetNodeNameForURI(RootNode: IXMLSchemaDoc; URI: WideString): WideString; var NameSpaceNode: IXMLNode; begin Result := ''; //Check if the XMLSchema root has it NamespaceNode := RootNode.SchemaDef.FindNamespaceDecl(URI); if NamespaceNode <> nil then begin Result := NamespaceNode.NodeName; exit; end else begin //Check if its a WSDL and if the root has it if Definition <> nil then begin NamespaceNode := Definition.FindNamespaceDecl(URI); if NamespaceNode <> nil then Result := NamespaceNode.NodeName; end; end; end; procedure TWebServExp.GenerateDerivedClassSchema(RootNode: IXMLSchemaDoc; const ParentTypeInfo: PTypeinfo; Namespace:WideString); var Count, Index: Integer; RegEntry: TRemRegEntry; begin Count := RemClassRegistry.GetURICount; for Index := 0 to Count -1 do begin RegEntry := RemClassRegistry.GetURIMap(Index); if RegEntry.ClassType <> nil then begin if RegEntry.ClassType.InheritsFrom(GetTypeData(ParentTypeInfo).ClassType) and (RegEntry.ClassType <> GetTypeData(ParentTypeInfo).ClassType) then begin GenerateXMLSchema(RootNode, RegEntry.Info, ParentTypeInfo, Namespace); end; end; end; end; procedure GetPropInfosInternal(TypeInfo: PTypeInfo; PropList: PPropList); assembler; asm { -> EAX Pointer to type info } { EDX Pointer to prop list } { <- nothing } PUSH EBX PUSH ESI PUSH EDI XOR ECX,ECX MOV ESI,EAX MOV CL,[EAX].TTypeInfo.Name.Byte[0] MOV EDI,EDX XOR EAX,EAX MOVZX ECX,[ESI].TTypeInfo.Name[ECX+1].TTypeData.PropCount REP STOSD @outerLoop: MOV CL,[ESI].TTypeInfo.Name.Byte[0] LEA ESI,[ESI].TTypeInfo.Name[ECX+1] MOV CL,[ESI].TTypeData.UnitName.Byte[0] MOVZX EAX,[ESI].TTypeData.UnitName[ECX+1].TPropData.PropCount TEST EAX,EAX JE @parent LEA EDI,[ESI].TTypeData.UnitName[ECX+1].TPropData.PropList @innerLoop: MOVZX EBX,[EDI].TPropInfo.NameIndex MOV CL,[EDI].TPropInfo.Name.Byte[0] CMP dword ptr [EDX+EBX*4],0 JNE @alreadySet MOV [EDX+EBX*4],EDI @alreadySet: LEA EDI,[EDI].TPropInfo.Name[ECX+1] DEC EAX JNE @innerLoop @parent: @exit: POP EDI POP ESI POP EBX end; function GetPropListInternal(TypeInfo: PTypeInfo; out PropList: PPropList): Integer; begin Result := GetTypeData(TypeInfo)^.PropCount; if Result > 0 then begin GetMem(PropList, Result * SizeOf(Pointer)); FillChar(PropList^, Result * SizeOf(Pointer), 0); GetPropInfosInternal(TypeInfo, PropList); end; end; procedure TWebServExp.GenerateClassSchema(RootNode: IXMLSchemaDoc; const ObjectTypeInfo, ParentInfo: PTypeinfo; Namespace: WideString); var Size, Props: integer; PropList: PPropList; ComplexType: IXMLComplexTypeDef; ElementType: IXMLElementDef; ParamType: string; BaseName, Pre: WideString; begin Size := GetPropListInternal(ObjectTypeInfo, PropList); if Size > 0 then begin try if ParentInfo <> nil then begin Pre := GetPrefixForTypeInfo(ParentInfo); if Pre <> '' then BaseName := Pre + ':' + ParentInfo.Name else BaseName := ParentInfo.Name; ComplexType := RootNode.SchemaDef.ComplexTypes.Add(ObjectTypeInfo.Name, BaseName) end else ComplexType := RootNode.SchemaDef.ComplexTypes.Add(ObjectTypeInfo.Name); for Props := 0 to Size -1 do begin if PropList[Props] <> nil then begin ParamType := GetXMLSchemaType(PropList[Props].PropType^); ElementType := ComplexType.ElementDefs.Add(PropList[Props].Name, ParamType); if IsComplexType(PropList[Props].PropType^.Kind) then GenerateXMLSchema(RootNode, PropList[Props].PropType^, nil, Namespace); end; end; finally FreeMem(PropList); end; end; //Size > 0 end; procedure TWebServExp.GenerateEnumSchema(RootNode: IXMLSchemaDoc; const ObjectTypeInfo: PTypeinfo; Namespace: WideString); var SimpleType: IXMLSimpleTypeDef; TypeData: PTypeData; Index: Integer; Value: string; begin TypeData := GetTypeData(ObjectTypeInfo); if TypeData <> nil then begin SimpleType := RootNode.SchemaDef.SimpleTypes.Add(ObjectTypeInfo.Name, 'string'); for Index := 0 to TypeData.MaxValue do begin Value := GetEnumName(ObjectTypeInfo, Index ); SimpleType.Enumerations.Add(Value); end; end; end; procedure TWebServExp.GenerateArraySchema(RootNode: IXMLSchemaDoc; const ObjectTypeInfo: PTypeinfo; Namespace: WideString); var ComplexType: IXMLComplexTypeDef; ElementType: IXMLElementDef; ElementTypeInfo: PTypeinfo; I, Dimensions: integer; ParamType, ArrayElementName: string; ArrayType: string; Prefix, SoapEncPrefix: WideString; AttrDef: IXMLAttributeDef; DimString, ArrayName, TempName: string; begin if FArrayAsComplexContent then begin ElementTypeInfo := GetDynArrayNextInfo2(ObjectTypeInfo, ArrayName); Dimensions := 1; while (ElementTypeInfo <> nil) and (ElementTypeInfo.Kind = tkDynArray ) and (ElementTypeInfo.Name[1] = '.') do begin Inc(Dimensions); ElementTypeInfo := GetDynArrayNextInfo2(ElementTypeInfo, TempName); end; if (ElementTypeInfo = nil) or (ElementTypeInfo.Name[1] = '.') then GetDynArrayElTypeInfo(ObjectTypeInfo, ElementTypeInfo, Dimensions); { if (ElementTypeInfo.Kind = tkDynArray) and (ArrayName <> '') and (ArrayName[1] <> '.') then GenerateArraySchema(RootNode, ElementTypeInfo, Namespace); if (ElementTypeInfo.Kind = tkClass) or (ElementTypeInfo.Kind = tkEnumeration) then GenerateXMLSchema(RootNode, ElementTypeInfo, nil, Namespace); } ParamType := GetXMLSchemaType(ElementTypeInfo); ArrayType := SArrayOf + ParamType; //Get Soap Encoding prefix SoapEncPrefix := GetPrefixForURI(RootNode, SSoap11EncodingS5); ComplexType := RootNode.SchemaDef.ComplexTypes.Add(ObjectTypeInfo.Name, SoapEncPrefix + ':' + SSoapEncodingArray, dmComplexRestriction); AttrDef:= ComplexType.AttributeDefs.Add(SoapEncPrefix + ':'+ SArrayType); //Get WSDL URI prefix Prefix := GetNodeNameForURI(RootNode, Wsdlns); for I := 0 to Dimensions -1 do DimString := DimString + '[]'; AttrDef.Attributes['n1'+':'+SArrayType] := ParamType + DimString; AttrDef.Attributes[Prefix+':'+'n1'] := Wsdlns; end else begin GetDynArrayElTypeInfo(ObjectTypeInfo, ElementTypeInfo, Dimensions); ParamType := GetXMLSchemaType(ElementTypeInfo); ArrayType := SArrayOf + ParamType; ElementType := RootNode.SchemaDef.ElementDefs.Add(ObjectTypeInfo.Name, True, SSoapArray); ComplexType := ElementType.DataType as IXMLComplexTypeDef; ComplexType.Attributes[SName] := ArrayType; if Dimensions > 1 then GenerateNestedArraySchema(RootNode, ComplexType, ElementTypeInfo, Dimensions, Namespace) else begin ArrayElementName := 'Dimension' + IntToStr(Dimensions); ParamType := GetXMLSchemaType(ElementTypeInfo); ElementType := ComplexType.ElementDefs.Add(ArrayElementName, ParamType); ElementType.Attributes[SMaxOccurs] := SUnbounded; if IsComplexType(ElementTypeInfo.Kind) then GenerateXMLSchema(RootNode, ElementTypeInfo, nil, Namespace); end; end; end; procedure TWebServExp.GenerateNestedArraySchema(RootNode: IXMLSchemaDoc; ComplexType: IXMLComplexTypeDef; const ObjectTypeInfo: PTypeinfo; var Dimension: Integer; Namespace: WideString); var ParamType: string; ArrayElementName: String; ElementType: IXMLElementDef; NestedType: IXMLComplexTypeDef; begin while Dimension <> 0 do begin if Dimension > 1 then begin ArrayElementName := 'Dimension' + IntToStr(Dimension); ElementType := ComplexType.ElementDefs.Add(ArrayElementName, True); ElementType.Attributes[SMaxOccurs] := SUnbounded; NestedType := ElementType.DataType as IXMLComplexTypeDef; Dimension := Dimension -1; GenerateNestedArraySchema(RootNode, NestedType, ObjectTypeInfo, Dimension, Namespace); end else begin ArrayElementName := 'Dimension' + IntToStr(Dimension); ParamType := GetXMLSchemaType(ObjectTypeInfo); ElementType := ComplexType.ElementDefs.Add(ArrayElementName, ParamType); ElementType.Attributes[SMaxOccurs] := SUnbounded; Dimension := Dimension -1; if IsComplexType(ObjectTypeInfo.Kind) then GenerateXMLSchema(RootNode, ObjectTypeInfo, nil, Namespace); end; end; //while end; procedure TWebServExp.GenerateXMLSchema(RootNode: IXMLSchemaDoc; const ObjectTypeInfo, ParentInfo: PTypeinfo; Namespace: WideString); var TempURI, TempName: WideString; AncInfo: PTypeInfo; begin if IsComplexType(ObjectTypeInfo.Kind) then begin if (not IsSchemaGenerated(ObjectTypeInfo, Namespace)) then begin case ObjectTypeInfo.Kind of tkDynArray: GenerateArraySchema(RootNode,ObjectTypeInfo, NameSpace); tkEnumeration: GenerateEnumSchema(RootNode,ObjectTypeInfo, NameSpace); tkClass: begin if (ParentInfo = nil) and ( (GetTypeData(ObjectTypeInfo).ParentInfo)^ <> nil) then begin AncInfo := (GetTypeData(ObjectTypeInfo).ParentInfo)^; if (AncInfo <> nil) and not RemTypeRegistry.TypeInfoToXSD(AncInfo, TempURI , TempName) then AncInfo := nil; if (AncInfo <> nil) and (GetTypeData(AncInfo).ClassType = TRemotable) then AncInfo := nil; end else AncInfo := ParentInfo; GenerateClassSchema(RootNode,ObjectTypeInfo, AncInfo, Namespace); //Generate XML Schema for registered derived classes GenerateDerivedClassSchema(RootNode, ObjectTypeInfo, Namespace); end; end; end; end; end; procedure TWebServExp.GetAllSchemaTypes(const IntfMD: TIntfMetaData); var Methods, Params, NoOfMethods, NoOfParams: Integer; IntfMethArray: TIntfMethEntryArray; ParamArray: TIntfParamEntryArray; begin IntfMethArray := nil; ParamArray := nil; IntfMethArray := IntfMD.MDA; NoOfMethods := Length(IntfMethArray); for Methods := 0 to NoOfMethods -1 do begin ParamArray := IntfMD.MDA[Methods].Params; NoOfParams := Length(ParamArray); for Params := 0 to NoOfParams -2 do begin if IsComplexType(ParamArray[Params].Info.Kind) then GetSchemaTypes(ParamArray[Params].Info, nil); end; //For Function return type if IntfMD.MDA[Methods].ResultInfo <> nil then begin //If the return type is an object if IsComplexType(IntfMD.MDA[Methods].ResultInfo.Kind) then GetSchemaTypes(IntfMD.MDA[Methods].ResultInfo, nil); end; end; end; procedure TWebServExp.GetDerivedClassSchema(const ParentTypeInfo: PTypeinfo); var Count, Index: Integer; RegEntry: TRemRegEntry; begin Count := RemClassRegistry.GetURICount; for Index := 0 to Count -1 do begin RegEntry := RemClassRegistry.GetURIMap(Index); if RegEntry.ClassType <> nil then begin if RegEntry.ClassType.InheritsFrom(GetTypeData(ParentTypeInfo).ClassType) then GetSchemaTypes(RegEntry.Info, ParentTypeInfo); end; end; end; function TWebServExp.FindSchema(const ObjectTypeInfo: PTypeinfo; const TnsURI: string): Boolean; var Index: Integer; begin Result := False; //Do not register Empty TnsURI or tkSet or any predefined type from XMLSchema if ((TnsURI = '') or (ObjectTypeInfo.Kind = tkSet) or (TnsURI = SXMLSchemaURI_1999) or (TnsURI = SXMLSchemaURI_2000_10) or (TnsURI = SXMLSchemaURI_2001)) then begin Result := True; Exit; end; for Index := 0 to Length(SchemaArray) -1 do begin if SchemaArray[Index].TypeInfo = ObjectTypeInfo then begin Result := True; Exit; end; end; //Add new type Index := Length(SchemaArray); SetLength(SchemaArray, Index+1); SchemaArray[Index].TypeName := ObjectTypeInfo.Name; SchemaArray[Index].NameSpace := TnsURI; SchemaArray[Index].TypeInfo := ObjectTypeInfo; SchemaArray[Index].XSGenerated := False; end; function TWebServExp.IsSchemaGenerated(const ObjectTypeInfo: PTypeinfo; const TnsURI: WideString): Boolean; var Index: Integer; begin Result := True; for Index := 0 to Length(SchemaArray) -1 do begin if ((SchemaArray[Index].TypeInfo = ObjectTypeInfo) and (SchemaArray[Index].NameSpace = TnsURI) ) then begin if SchemaArray[Index].XSGenerated = False then begin Result := False; SchemaArray[Index].XSGenerated := True; end else Result := True; Exit; end; end; end; function TWebServExp.GetPrefixForTypeInfo(const ObjectTypeInfo: PTypeinfo): WideString; var Index: Integer; begin Result := ''; for Index := 0 to Length(SchemaArray) -1 do begin if (SchemaArray[Index].TypeInfo = ObjectTypeInfo) then begin Result := SchemaArray[Index].NSPrefix; exit; end; end; end; procedure TWebServExp.GetSchemaTypes(const ObjectTypeInfo, ParentInfo: PTypeinfo); var URI, Name: WideString; IsScalar: Boolean; begin if IsComplexType(ObjectTypeInfo.Kind) then begin RemClassRegistry.InfoToURI(ObjectTypeInfo, URI, Name, IsScalar); //Add to the SchemaArray to keep track of what complex type has //already been encountered if (not FindSchema(ObjectTypeInfo, URI)) then begin case ObjectTypeInfo.Kind of tkDynArray: GetArraySchema(ObjectTypeInfo); //tkEnumeration: GenerateEnumSchema(RootNode,ObjectTypeInfo); tkClass: begin GetClassSchema(ObjectTypeInfo, ParentInfo); //Get all the registered derived classes GetDerivedClassSchema(ObjectTypeInfo); end; end; end; end; end; procedure TWebServExp.GetClassSchema(const ObjectTypeInfo, ParentInfo: PTypeinfo); var Size, Props: integer; PropList: PPropList; begin Size := GetPropList(ObjectTypeInfo, [tkUnknown..tkDynArray], nil); if Size > 0 then begin PropList := AllocMem(sizeof(TPropInfo) * Size); try Size := GetPropList(ObjectTypeInfo, PropList); for Props := 0 to Size -1 do begin if IsComplexType(PropList[Props].PropType^.Kind) then GetSchemaTypes(PropList[Props].PropType^, nil); end; finally FreeMem(PropList); end; end; //Size > 0 end; procedure TWebServExp.GetArraySchema(const ObjectTypeInfo: PTypeinfo); var ElementTypeInfo: PTypeInfo; Dimensions: Integer; ArrayName, TempName: String; begin ElementTypeInfo := GetDynArrayNextInfo2(ObjectTypeInfo, ArrayName); Dimensions := 1; while (ElementTypeInfo <> nil) and (ElementTypeInfo.Kind = tkDynArray ) and (ElementTypeInfo.Name[1] = '.') do begin Inc(Dimensions); ElementTypeInfo := GetDynArrayNextInfo2(ElementTypeInfo, TempName); end; if (ElementTypeInfo = nil) or (ElementTypeInfo.Name[1] = '.') then GetDynArrayElTypeInfo(ObjectTypeInfo, ElementTypeInfo, Dimensions); if (ElementTypeInfo.Kind = tkDynArray) and (ArrayName <> '') and (ArrayName[1] <> '.') then GetSchemaTypes(ElementTypeInfo, nil); if (ElementTypeInfo.Kind = tkClass) or (ElementTypeInfo.Kind = tkEnumeration) then GetSchemaTypes(ElementTypeInfo, nil); { GetDynArrayElTypeInfo(ObjectTypeInfo, ElementTypeInfo, Dim); if ElementTypeInfo <> nil then GetSchemaTypes(ElementTypeInfo, nil); } end; initialization finalization end.
unit main1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,system.Types, Vcl.Buttons, Vcl.Grids, ComObj ; type //===========================================CLASS CHARGE Charge = class private _q : real; _pos : TPoint; _checked : boolean; _color : TColor; public constructor New(q : real; pos: TPoint); end; //===========================================CLASS SPACE Space = class private _charges : array of Charge; _cntCharges : integer; public _canvas : TCanvas; constructor New(canvas : TCanvas; gridPeriod : integer); procedure AddCharge(position:tpoint;chargeq:real); procedure RemoveCharge(numbercharge:integer); procedure MoveCharge(numbercharge:integer); procedure Draw(linenumber:array of integer;DropOut:integer); procedure DrawGrid(gridperiod:integer); procedure redraw; procedure scopedraw(point1:tpoint;color:tcolor); procedure opilki; function colour(eint:real):tcolor; end; //==================================================== TfMain = class(TForm) pbMain: TPaintBox; btndelete: TBitBtn; Panel1: TPanel; labelededit1: TLabeledEdit; Label3: TLabel; Button1: TButton; StringGrid1: TStringGrid; exitbtn: TBitBtn; btnaccept: TBitBtn; BitBtn1: TBitBtn; Panel2: TPanel; Label1: TLabel; TrackBar1: TTrackBar; Label2: TLabel; savebutton: TBitBtn; loadbutton: TBitBtn; statbtn: TButton; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Button2: TButton; RadioButton1: TRadioButton; RadioButton2: TRadioButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure pbMainPaint(Sender: TObject); procedure pbMainClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure statbtnClick(Sender: TObject); procedure btndeleteClick(Sender: TObject); procedure exitbtnClick(Sender: TObject); procedure btnacceptClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); function foolproof(labele1:tlabelededit):real; procedure savebuttonClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure labelededit1Change(Sender: TObject); procedure pbMainDblClick(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button2KeyPress(Sender: TObject; var Key: Char); procedure exitbtnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); { Private declarations } public { Public declarations } end; var excel:variant; fMain: TfMain; chargeq:real; MySpace : Space; gridperiod:integer ; pt:tpoint; point0,point1:tpoint; implementation {$R *.dfm} uses Unit2; constructor Charge.New(q: real; pos: TPoint); begin self._q := q; self._pos := pos; if(q<0)then self._color := clBlue else self._color := clRed; end; procedure TfMain.BitBtn1Click(Sender: TObject); begin panel1.Visible:=false; myspace.scopedraw(point1,clwhite); pbmain.Canvas.Pen.Color:=clblack; pbmain.canvas.pen.Width:=1; myspace.DrawGrid(20); myspace.redraw; end; procedure TfMain.btnacceptClick(Sender: TObject); begin chargeq:=FOOLPROOF(LABELEDEDIT1); myspace.addcharge(pOINt1,chargeq); panel1.Visible:=false; pbmain.canvas.Pen.Color:=clwhite; pbmain.canvas.pen.Width:=5; myspace.scopedraw(point1,clwhite); myspace.redraw; myspace.DrawGrid(20); statbtn.click; end; procedure TfMain.btnClearClick(Sender: TObject); var numbercharge:integer; begin myspace.RemoveCharge(numbercharge); end; procedure TfMain.btndeleteClick(Sender: TObject); begin setlength(myspace._charges,0); myspace._cntCharges:=0; pbmain.Canvas.Rectangle(0,0,pbmain.Width,pbmain.Height); pbmain.Canvas.FloodFill(pbmain.width,pbmain.height,clwhite,fsborder); pbmain.Canvas.Pen.Width:=1; pbmain.Canvas.Pen.Color:=clblack; myspace.DrawGrid(20); statbtn.Click; end; procedure TfMain.Button1Click(Sender: TObject); var stuff:array of integer ; i:integer; begin setlength(stuff,100); for i := 0 to 99 do stuff[i]:=trackbar1.Position; if radiobutton2.Checked=true then myspace.Draw(stuff,10); if radiobutton1.Checked=true then myspace.opilki; end; procedure TfMain.Button2Click(Sender: TObject); begin panel2.visible:=false; bitbtn1.Click; end; procedure TfMain.Button2KeyPress(Sender: TObject; var Key: Char); begin if key=#27 then button2.Click; end; procedure TfMain.Button3Click(Sender: TObject); begin myspace.opilki end; procedure TfMain.exitbtnClick(Sender: TObject); begin fmain.Close; form2.show; end; procedure TfMain.exitbtnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (panel1.Visible=false) and (panel2.Visible=false) then begin pbmain.Canvas.pen.color:=clwhite; pbmain.Canvas.pen.width:=1; pbmain.Canvas.rectangle(point1.X-5,point1.Y-5,point1.X+5,point1.Y+5); pbmain.Canvas.Pen.Style:=pssolid; pbmain.Canvas.pen.Color:=clsilver; pbmain.Canvas.MoveTo(point1.X-5,point1.Y); pbmain.Canvas.lineTo(point1.X+5,point1.Y); pbmain.Canvas.MoveTo(point1.X,point1.Y-5); pbmain.Canvas.lineTo(point1.X,point1.Y+5); pbmain.Canvas.pen.width:=1; if (key=vk_right) and (point1.X<=pbmain.Width) then point1.x:=point1.x+20; //wasd controls if (key=vk_down)and (point1.Y<=pbmain.Height) then point1.y:=point1.y+20; if (key=vk_left) and (point1.x>=0) then point1.x:=point1.x-20; if (key=vk_up)and (point1.y>=0) then point1.y:=point1.y-20; pbmain.Canvas.pen.Color:=clred; pbmain.Canvas.rectangle(point1.X-5,point1.Y-5,point1.X+5,point1.Y+5); end; end; function TfMain.foolproof(labele1: tlabelededit): real; VAR isOk:boolean; i: Integer; begin try result:=strtofloat(labele1.Text) except panel2.visible:=true; end; end; procedure TfMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin { try Excel.Quit; except end; CanClose:=True; Excel:=Unassigned; } end; procedure TfMain.FormCreate(Sender: TObject); begin MySpace := Space.New(pbMain.Canvas,10); point1:=point(0,0) end; procedure TfMain.FormKeyPress(Sender: TObject; var Key: Char); var i:integer;//simple counter z:integer;//what charge to delete; begin if panel2.Visible=true then begin if key=#27 then button2.Click; end else begin if PANEL1.Visible=TRUE then begin if (key=#101) and (trackbar1.Position<25) then begin trackbar1.SetFocus; trackbar1.Position:=trackbar1.position+1; labelededit1.SetFocus; end; if (key=#113) and (trackbar1.Position>5) then begin trackbar1.SetFocus; trackbar1.Position:=trackbar1.position-1 ; labelededit1.SetFocus; end; if key=#27 then bitbtn1.Click; if key=#13 then btnaccept.Click; end else begin pbmain.Canvas.pen.color:=clwhite; pbmain.Canvas.pen.width:=1; pbmain.Canvas.rectangle(point1.X-5,point1.Y-5,point1.X+5,point1.Y+5); pbmain.Canvas.Pen.Style:=pssolid; pbmain.Canvas.pen.Color:=clsilver; pbmain.Canvas.MoveTo(point1.X-5,point1.Y); pbmain.Canvas.lineTo(point1.X+5,point1.Y); pbmain.Canvas.MoveTo(point1.X,point1.Y-5); pbmain.Canvas.lineTo(point1.X,point1.Y+5); pbmain.Canvas.pen.width:=1; if (key=#100) and (point1.X<=pbmain.Width) then point1.x:=point1.x+20; //wasd controls if (key=#115)and (point1.Y<=pbmain.Height) then point1.y:=point1.y+20; if (key=#97) and (point1.x>=0) then point1.x:=point1.x-20; if (key=#119)and (point1.y>=0) then point1.y:=point1.y-20; //---- functional hotkeys if Key=#13 then button1.Click; if key=#27 then exitbtn.Click; if key=#127 then btndelete.Click; if (key=#09) and (radiobutton1.Checked=true) then radiobutton2.Checked:=true ; if (key=#09) and (radiobutton2.Checked=true) then radiobutton1.Checked:=true ; if key=#08 then //deleting charges begin for i := 0 to myspace._cntCharges-1 do begin if (myspace._charges[i]._pos=point1) and ( myspace._cntCharges>=1) then z:=i; end; myspace.RemoveCharge(z); statbtn.click; end; pbmain.Canvas.pen.Color:=clred; pbmain.Canvas.rectangle(point1.X-5,point1.Y-5,point1.X+5,point1.Y+5); if key=#32 then begin myspace.DrawGrid(20); panel1.Left:=point1.X-40; panel1.top:=point1.y+40; panel1.Visible:=true; myspace.redraw; myspace.scopedraw(point1,clred); labelededit1.SetFocus; END; end; end; end; procedure TfMain.labelededit1Change(Sender: TObject); begin //if (labelededit1.text[length(labelededit1.Text)-1]='e') or (labelededit1.text[length(labelededit1.Text)-1]='q') then labelededit1.text[length(labelededit1.Text)]:='' end; procedure TfMain.pbMainClick(Sender: TObject); begin if PANEL1.Visible=TRUE then ELSE BEGIN //deleting mistakes of youth(key usage rectangle) pbmain.Canvas.pen.color:=clwhite; pbmain.Canvas.pen.width:=1; pbmain.Canvas.rectangle(point1.X-5,point1.Y-5,point1.X+5,point1.Y+5); pbmain.Canvas.Pen.Style:=pssolid; pbmain.Canvas.pen.Color:=clsilver; pbmain.Canvas.MoveTo(point1.X-5,point1.Y); pbmain.Canvas.lineTo(point1.X+5,point1.Y); pbmain.Canvas.MoveTo(point1.X,point1.Y-5); pbmain.Canvas.lineTo(point1.X,point1.Y+5); pbmain.Canvas.pen.width:=1; //---------------------- myspace.DrawGrid(20); getcursorpos(pt) ; point0:=screentoclient(pt) ; point1:=point(round(point0.X/20)*20,round(point0.y/20)*20 ) ; //setting point of charge //showing panel panel1.Left:=point1.X-40; panel1.top:=point1.y+40; panel1.Visible:=true; myspace.redraw; myspace.scopedraw(point1,clred); END; end; procedure TfMain.pbMainDblClick(Sender: TObject); var z,i:integer; pos:tpoint; begin getcursorpos(pos); pos:=screentoclient(pos); pos:=point(round(pos.X/20)*20,round(pos.Y/20)*20); for i := 0 to myspace._cntCharges-1 do begin if (myspace._charges[i]._pos=pos) and (myspace._cntCharges>=1) then z:=i; end; myspace.RemoveCharge(z); statbtn.click; end; procedure TfMain.pbMainPaint(Sender: TObject); begin pbmain.Canvas.Pen.Width:=1; pbmain.Canvas.Pen.Color:=clblack; myspace.DrawGrid(20); end; procedure TfMain.savebuttonClick(Sender: TObject); var i,j:integer;//counters begin { Excel:=CreateOleObject('Excel.Application'); Excel.Application.WorkBooks.Add('таблица.xls'); Excel.DisplayAlerts:=False; with StringGrid1 do for i:=1 to RowCount-1 do for j:=1 to ColCount-1 do Cells[j, i]:=Excel.WorkSheets.Item['Лист1'].Cells[i, j]; Excel.ActiveWorkbook.SaveAs('Имя_Файла'); } end; procedure TfMain.statbtnClick(Sender: TObject); var i: Integer; begin //if stringgrid1.Visible=false then stringgrid1.Visible:=true else stringgrid1.Visible:=false ; stringgrid1.rowcount:= myspace._cntCharges+1; for i := 0 to myspace._cntCharges-1 do begin stringgrid1.Cells[0,0]:='№ '; stringgrid1.Cells[1,0]:='Заряд'; stringgrid1.Cells[2,0]:=' (X)' ; stringgrid1.Cells[3,0]:=' (Y)' ; if myspace._charges[i]._q<>0 then begin stringgrid1.Cells[1,i+1]:=floattostr(myspace._charges[i]._q ); stringgrid1.Cells[2,i+1]:=inttostr(myspace._charges[i]._pos.X) ; stringgrid1.Cells[3,i+1]:=inttostr(myspace._charges[i]._pos.y); stringgrid1.Cells[0,i+1]:=inttostr(i+1); end; end; end; procedure Space.AddCharge(position:tpoint;chargeq:real); var chargepos:tpoint; begin chargepos:=position; SETLENGTH(self._charges,(self._CNTCHARGES+1)); self._charges[self._cntcharges]:=charge.New(chargeq,point(round(chargepos.x/20)*20,round(chargepos.y/20)*20)) ; self._canvas.Pen.Width:=3; self._canvas.Pen.Color:=self._charges[self._cntCharges]._color; self._canvas.Create.Ellipse((round(chargepos.X/20)*20+10),(round(chargepos.Y/20)*20+10),round(chargepos.X/20)*20-10,round(chargepos.Y/20)*20-10); self._cntcharges:=self._cntcharges+1; self._canvas.Pen.Width:=1; self._canvas.pen.Color:=clblack ; end; function Space.colour(eint:real): tcolor; var i:integer; a,b,k:real; scalar:real; red,green,blue,z1:byte; emax:real; begin k:=7.3; emax:=-100000; for i := 0 to self._cntCharges-1 do begin if (self._charges[i]._q/169)>emax then emax:=(self._charges[i]._q/169); end; b:=ln(abs(eint/emax))/k; if b<-2.5 then b:=-2.5 ; b:=b*abs(eint)/eint+2.5; z1:=round((b-trunc(b))*255); if (b<1) and (b>0) then begin red:=255; green:=z1; blue:=0; end; if (b<2) and (b>1) then begin red:=255-z1; green:=255; blue:=0; end; if (b>2) and (b<3) then begin red:=0; green:=255; blue:=z1; end; if (b<3) and (b<4) then begin red:=0; green:=255-z1; blue:=255; end; if (b<5) and (b>4)then begin red:=0 ; green:=0 ; blue:=255; end; result:=rgb(red,green,blue) end; procedure Space.Draw(linenumber:array of integer;dropout:integer); var ex,ey,e,eint,x,y,r,cosa,sina,angle:real; counter,counter1,counter2,curve:integer; //0-charge,1-line,2-influence linecolor:tcolor; begin for counter := 0 to self._cntcharges-1 do //cycle which cycles through charges begin for counter1 :=0 to linenumber[counter] do //through different angles of start begin curve:=0; //crutch for length angle:=(counter1/linenumber[counter])*2*pi; x:=self._charges[counter]._pos.X+dropout*cos(angle); y:=self._charges[counter]._pos.y+dropout*sin(angle); while (x<self._canvas.ClipRect.Width)and (y<self._canvas.ClipRect.Height) and (x>0) and (y>0) and (curve<20000) do begin ex:=0 ; ey:=0 ; eint:=0; for counter2 := 0 to self._cntcharges-1 do //through oharges influence begin r:=sqrt(sqr(self._charges[counter2]._pos.x-x)+sqr(self._charges[counter2]._pos.y-y)); if r<>0 then cosa:=(x-self._charges[counter2]._pos.x )/r ; if r<>0 then sina:=(y-self._charges[counter2]._pos.y )/r ; if (r<>0) and (self._charges[counter]._q>0) then e:=self._charges[counter2]._q/sqr(r) else e:=-1*self._charges[counter2]._q/sqr(r) ; ex:=ex+(e)*cosa; ey:=ey+(e)*sina; end; eint:=sqrt(sqr(ex)+sqr(ey)); //summary if eint<>0 then x:=x+ex/eint; if eint<>0 then y:=y+ey/eint; // if eint<>0 then linecolor:=rgb(255,0,round(255*abs(ex/eint))); linecolor:=clblack; self._canvas.Pixels[round(x),round(y)]:=linecolor; self._canvas.Pixels[round(x)+1,round(y)]:=linecolor; curve:=curve+1; end; end; end; end; procedure Space.RemoveCharge(numbercharge:integer); var chargepos:tpoint; r:integer; begin self._canvas.pen.width:=3; self._canvas.pen.color:=clwhite; self._canvas.Ellipse(self._charges[numbercharge]._pos.X-10,self._charges[numbercharge]._pos.y-10,self._charges[numbercharge]._pos.X+10,self._charges[numbercharge]._pos.y+10); self._cntcharges:=self._cntcharges-1; self._charges[numbercharge]._q:=0; setlength(self._charges,self._cntCharges); self._canvas.pen.width:=3; for r := numbercharge to self._cntCharges-2 do begin self._charges[r]:=self._charges[r+1]; end; myspace.DrawGrid(20); end; procedure Space.scopedraw(point1: tpoint;color:tcolor); begin self._canvas.pen.Width:=5; self._Canvas.Pen.Color:=color; self._Canvas.MoveTo(point1.X+10,point1.Y+10); self._Canvas.lineTo(point1.X+40,point1.Y+40); self._Canvas.MoveTo(point1.X-10,point1.Y+10); self._Canvas.lineTo(point1.X-40,point1.Y+40); self._Canvas.MoveTo(point1.X,point1.Y-15); self._Canvas.lineTo(point1.X,point1.Y-40); self._Canvas.Pen.Color:=clblack; self._canvas.pen.Width:=1; end; PROCEDURE space.DrawGrid(gridperiod: Integer); var i,z:integer; begin i:=0; z:=0; self._canvas.pen.width:=1; while i<=self._canvas.ClipRect.Width do begin self._canvas.pen.Color:=clSILVER; self._canvas.MoveTo(i,0); self._canvas.LineTo(i,self._canvas.ClipRect.Height); i:=i+gridperiod; end; while z<=self._canvas.ClipRect.Width do begin self._canvas.pen.Color:=clSILVER; self._canvas.MoveTo(0,z); self._canvas.LineTo(self._canvas.ClipRect.Width,z); z:=z+gridperiod; end; end; procedure Space.MoveCharge(numbercharge: integer); begin end; constructor Space.New(canvas: TCanvas; gridPeriod: integer); begin self._canvas:=canvas; self._cntCharges:=0 ; end; procedure Space.opilki; var scalar,a,b,ex,ey,e,emax,emin,eint,x,y,r,cosa,sina,angle:real; i,counter,counter1,counter2,curve:integer; //0-charge,1-line,2-influence linecolor:tcolor; begin for counter := 0 to self._cntcharges-1 do //cycle which cycles through charges begin for counter1 :=0 to 100 do //through different angles of start begin curve:=0; //crutch for length angle:=(counter1/100)*2*pi; x:=self._charges[counter]._pos.X+10*cos(angle); y:=self._charges[counter]._pos.y+10*sin(angle); while (x<self._canvas.ClipRect.Width)and (y<self._canvas.ClipRect.Height) and (x>0) and (y>0) and (curve<20000) do begin ex:=0 ; ey:=0 ; eint:=0; for counter2 := 0 to self._cntcharges-1 do //through oharges influence begin r:=sqrt(sqr(self._charges[counter2]._pos.x-x)+sqr(self._charges[counter2]._pos.y-y)); if r<>0 then cosa:=(x-self._charges[counter2]._pos.x )/r ; if r<>0 then sina:=(y-self._charges[counter2]._pos.y )/r ; if (r<>0) and (self._charges[counter]._q>0) then e:=self._charges[counter2]._q/sqr(r) else e:=-1*self._charges[counter2]._q/sqr(r) ; ex:=ex+(e)*cosa; ey:=ey+(e)*sina; end; eint:=(sqr(ex)+sqr(ey)); //summary if eint<>0 then x:=x+4*ex/eint; if eint<>0 then y:=y+4*ey/eint; linecolor:=myspace.colour(eint); self._canvas.Pixels[round(x),round(y)]:=linecolor; curve:=curve+1; end; end; end; end; procedure Space.redraw; var i:integer; begin for i := 0 to self._cntCharges-1 do begin self._canvas.Pen.Width:=3; self._canvas.Pen.Color:=self._charges[i]._color; self._canvas.Ellipse(self._charges[i]._pos.X+10,self._charges[i]._pos.y+10,self._charges[i]._pos.X-10,self._charges[i]._pos.y-10); self._canvas.Pen.Width:=1; end; end; end.
unit uQueryCommandHandler; interface uses uCommandHandler, uTokenizer, dmConnection; type TQueryCommandHandler = class(TCommandHandler) function HandleCommand(const AConnection: TConnectionData; const ATarget: string; const ATokenizer: TTokenizer): string; override; end; implementation uses SysUtils; { TQueryCommandHandler } function TQueryCommandHandler.HandleCommand(const AConnection: TConnectionData; const ATarget: string; const ATokenizer: TTokenizer): string; var Target, Line: string; begin if not ATokenizer.HasMoreTokens then Exit; Target := ATokenizer.NextToken; Line := ATokenizer.NextToken; while ATokenizer.HasMoreTokens do Line := Line + ' ' + ATokenizer.NextToken; AConnection.Query(Target, Line); end; initialization TCommandHandlerFactory.GetInstance.RegisterClass('/query', TQueryCommandHandler); TCommandHandlerFactory.GetInstance.RegisterClass('/q', TQueryCommandHandler); end.
unit FIToolkit.Reports.Parser.Exceptions; interface uses FIToolkit.Commons.Exceptions; type EReportsParserException = class abstract (ECustomException); { FixInsight XML output parser exceptions } EFixInsightXMLParseError = class (EReportsParserException); implementation uses FIToolkit.Reports.Parser.Consts; initialization RegisterExceptionMessage(EFixInsightXMLParseError, RSFixInsightXMLParseError); end.
unit Xml.Internal.ParserUtilsWin32; // ParserUtilsWin32 3.0.4 -- Win32 version // Delphi 4 to 2009 and Kylix 3 Implementation // February 2009 // // // LICENSE // // The contents of this file are subject to the Mozilla Public License Version // 1.1 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // "http://www.mozilla.org/MPL/" // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for // the specific language governing rights and limitations under the License. // // The Original Code is "ParserUtilsWin32.pas". // // The Initial Developer of the Original Code is Dieter Köhler (Heidelberg, // Germany, "http://www.philo.de/"). Portions created by the Initial Developer // are Copyright (C) 2003-2009 Dieter Köhler. All Rights Reserved. // // Alternatively, the contents of this file may be used under the terms of the // GNU General Public License Version 2 or later (the "GPL"), in which case the // provisions of the GPL are applicable instead of those above. If you wish to // allow use of your version of this file only under the terms of the GPL, and // not to allow others to use your version of this file under the terms of the // MPL, indicate your decision by deleting the provisions above and replace them // with the notice and other provisions required by the GPL. If you do not delete // the provisions above, a recipient may use your version of this file under the // terms of any one of the MPL or the GPL. // HISTORY // 2009-02-23 3.0.4 TUtilsCustomAutodetectInputStream and TUtilsUCS4Reader // modified. // Encoding detection functions removed. // Other small revisions. // 2008-09-28 3.0.3 EncodingToWideStr and WideStrToEncoding function added. // Other small revisions. // 2008-07-07 3.0.2 EncodingToStr and StrToEncoding function added. // 2007-12-03 3.0.1 Made .NET compliant. // 2006-09-24 3.0.0 Completely refactored. // 2004-09-25 2.0.2 TUtilsUCS4Reader.Create modified, DefaultCodecClass added. // 2004-08-08 2.0.1 TUtilsNoRefCount moved to separate unit. // 2004-06-01 2.0.0 Completely refactored. // 2004-01-04 1.0.2 Small revisions. // 2003-11-16 1.0.1 Small revisions. // 2003-08-03 1.0.0 interface uses Xml.Internal.CodecUtilsWin32, System.Classes, System.SysUtils; function ConvertToUTF16(const SourceEncoding: string; const S: AnsiString): WideString; function ConvertFromUTF16(const TargetEncoding: string; const S: WideString): AnsiString; type EParserUtilsException = class(Exception); type TUtilsCustomInputStream = class private FStream: TStream; FBuffer: PAnsiChar; FInitialStreamPosition: Int64; FPosition: Int64; FRemaining: Int64; FBufSize: Integer; protected function GetPosition: Int64; virtual; function Read(var Buf; const Count: Longint): Boolean; virtual; procedure SetPosition(Value: Int64); virtual; property BufSize: Integer read FBufSize; property InitialStreamPosition: Int64 read FInitialStreamPosition; property Position: Int64 read GetPosition write SetPosition; public constructor Create(const Stream: TStream; const BufSize: Integer); destructor Destroy; override; procedure FlushBuffer; virtual; end; TUtilsCustomOutputStream = class private FStream: TStream; FBuffer: PAnsiChar; FInitialStreamPosition: Int64; FPosition: Int64; FBufSize: Integer; protected function GetPosition: Int64; virtual; procedure SetPosition(Value: Int64); virtual; procedure Write(const Buf; const Count: Longint); virtual; property BufSize: Integer read FBufSize; property InitialStreamPosition: Int64 read FInitialStreamPosition; property Position: Int64 read GetPosition write SetPosition; public constructor Create(const Stream: TStream; const BufSize: Integer); destructor Destroy; override; procedure FlushBuffer; virtual; end; TUtilsCustomAutodetectInputStream = class(TUtilsCustomInputStream) private FByteOrderMarkSize: Cardinal; FCodec: TUnicodeCodec; procedure Reset; protected function GetPosition: Int64; override; procedure SetPosition(Value: Int64); override; property ByteOrderMarkSize: Cardinal read FByteOrderMarkSize; public constructor Create(const Stream: TStream; const BufSize: Integer; const ExpectedEncoding, DefaultEncoding: string); destructor Destroy; override; property BufSize; property Codec: TUnicodeCodec read FCodec; end; TUtilsAutodetectInputStream = class(TUtilsCustomAutodetectInputStream) protected procedure ChangeEncoding(const AEncoding: string); function GetHasByteOrderMark: Boolean; virtual; public property Position; property HasByteOrderMark: Boolean read GetHasByteOrderMark; end; TUtilsUCS4CharData = record ByteCount: Int64; CharCount: Int64; CharsInLine: Int64; CodePoint: UCS4Char; Line: Int64; Size: Cardinal; TabsInLine: Int64; end; TUtilsUCS4Reader = class private FCodec: TUnicodeCodec; FCurrentUCS4Char: TUtilsUCS4CharData; FInternalInputStream: TUtilsAutodetectInputStream; FInitialUCS4CharData: TUtilsUCS4CharData; FNextUCS4Char: TUtilsUCS4CharData; FPreviousUCS4Char: TUtilsUCS4CharData; FResetPosition: Int64; function GetBof: Boolean; function GetBufSize: Integer; function GetEof: Boolean; function GetHasByteOrderMark: Boolean; function GetPosition: Int64; function GetReadLFOption: TCodecReadLFOption; procedure SetReadLFOption(const Value: TCodecReadLFOption); procedure UpdateLocator(var UCS4CharData: TUtilsUCS4CharData); protected function GetCodec: TUnicodeCodec; virtual; function GetDefaultEncoding: string; virtual; procedure ReadEventHandler(Sender: TObject; var Buf; Count: Longint; var Ok: Boolean); virtual; procedure SetEncoding(const Value: string); procedure SetResetPosition(const Value: Int64); virtual; property Codec: TUnicodeCodec read GetCodec; property DefaultEncoding: string read GetDefaultEncoding; property InternalInputStream: TUtilsAutodetectInputStream read FInternalInputStream; property InitialUCS4CharData: TUtilsUCS4CharData read FInitialUCS4CharData write FInitialUCS4CharData; property Position: Int64 read GetPosition; property ReadLFOption: TCodecReadLFOption read GetReadLFOption write SetReadLFOption default lrNormalize; property ResetPosition: Int64 read FResetPosition write SetResetPosition; public constructor Create(const Stream: TStream; const ABufSize: Integer; const AEncoding: string; const InitialByteCount, InitialCharCount, InitialCharsInLine, InitialTabsInLine, InitialLine: Int64); destructor Destroy; override; function Match(Ucs2Str: WideString): Boolean; virtual; procedure Next; virtual; procedure Reset; virtual; function SkipNext(Ucs2Str: WideString): Integer; virtual; property Bof: Boolean read GetBof; property BufSize: Integer read GetBufSize; property CurrentCharInfo: TUtilsUCS4CharData read FCurrentUCS4Char; property Eof: Boolean read GetEof; property HasByteOrderMark: Boolean read GetHasByteOrderMark; property NextCharInfo: TUtilsUCS4CharData read FNextUCS4Char; property PreviousCharInfo: TUtilsUCS4CharData read FPreviousUCS4Char; end; TUtilsLineBreakOpt = ( lbCRLF, lbCR, lbLF, lbNone); TUtilsCustomTranscoder = class private FInputCodec: TUnicodeCodec; FInputEncoding: string; FLineBreakOpt: TUtilsLineBreakOpt; FOutputCodec: TUnicodeCodec; FOutputEncoding: string; FOnProgress: TNotifyEvent; procedure SetInputEncoding(const Value: string); procedure SetLineBreakOpt(const Value: TUtilsLineBreakOpt); procedure SetOutputEncoding(const Value: string); procedure UpdateLineBreakOpt; protected FBusy: Boolean; procedure CodecReadEventHandler(Sender: TObject; var Buf; Count: Longint; var Ok: Boolean); virtual; procedure CodecWriteEventHandler(Sender: TObject; const Buf; Count: Longint); virtual; procedure DoProgress; virtual; property Busy: Boolean read FBusy; property InputCodec: TUnicodeCodec read FInputCodec; property InputEncoding: string read FInputEncoding write SetInputEncoding; property LineBreakOpt: TUtilsLineBreakOpt read FLineBreakOpt write SetLineBreakOpt default lbNone; property OutputCodec: TUnicodeCodec read FOutputCodec; property OutputEncoding: string read FOutputEncoding write SetOutputEncoding; property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; public constructor Create; destructor Destroy; override; procedure Transcode; virtual; end; TUtilsStandardTranscoder = class(TUtilsCustomTranscoder) private FOnRead: TCodecReadEvent; FOnWrite: TCodecWriteEvent; protected procedure CodecReadEventHandler(Sender: TObject; var Buf; Count: Longint; var Ok: Boolean); override; procedure CodecWriteEventHandler(Sender: TObject; const Buf; Count: Longint); override; public property Busy; property InputEncoding; property LineBreakOpt; property OutputEncoding; property OnProgress; property OnRead: TCodecReadEvent read FOnRead write FOnRead; property OnWrite: TCodecWriteEvent read FOnWrite write FOnWrite; end; TUtilsStreamTranscoder = class(TUtilsCustomTranscoder) private FReader: TUtilsCustomInputStream; FWriter: TUtilsCustomOutputStream; protected procedure CodecReadEventHandler(Sender: TObject; var Buf; Count: Longint; var Ok: Boolean); override; procedure CodecWriteEventHandler(Sender: TObject; const Buf; Count: Longint); override; public constructor Create(const InputStream, OutputStream: TStream; const BufSize: Integer); destructor Destroy; override; property Busy; property InputEncoding; property LineBreakOpt; property OutputEncoding; property OnProgress; end; resourcestring SByteOrderMarkMismatch = 'Specified input encoding does not match byte order mark.'; SDefaultEncodingNotSpecified = 'Default Encoding not specified.'; SEncodingNotSupported = 'Character encoding scheme not supported.'; SInputEncodingNotSpecified = 'Input Encoding not specified.'; SOutputEncodingNotSpecified = 'Output Encoding not specified.'; SStreamNotSpecified = 'Stream not specified.'; implementation { Helper Functions } function ConvertToUTF16(const SourceEncoding: string; const S: AnsiString): WideString; var C : TUnicodeCodec; begin C := TEncodingRepository.CreateCodecByAlias(SourceEncoding); if not Assigned(C) then raise EConvertError.Create(SEncodingNotSupported); try try C.DecodeStr(PAnsiChar(S), Length(S), Result); except on E: EUnicodeCodecException do raise EConvertError.Create(E.Message); end; finally C.Free; end; end; function ConvertFromUTF16(const TargetEncoding: string; const S: WideString): AnsiString; var C : TUnicodeCodec; I : Integer; begin C := TEncodingRepository.CreateCodecByAlias(TargetEncoding); if not Assigned(C) then raise EConvertError.Create(SEncodingNotSupported); try try Result := C.Encode(Pointer(S), Length(S), I); except on E: EUnicodeCodecException do raise EConvertError.Create(E.Message); end; finally C.Free; end; end; { TUtilsCustomInputStream } // TUtilsCustomInputStream was provided by Robert Marquardt. // Modifications in TdomCustomReader.Read() by Dieter Köhler. constructor TUtilsCustomInputStream.Create(const Stream: TStream; const BufSize: Integer); begin FBuffer := nil; // Remark: If an exception occurs, the destructor is automatically called. FStream := nil; // Therefore, we need to initialize critical objects with nil first. if not Assigned(Stream) then raise EParserUtilsException.Create(SStreamNotSpecified); inherited Create; if Assigned(Stream) then FInitialStreamPosition := Stream.Position else FInitialStreamPosition := 0; FStream := Stream; FBufSize := BufSize; FPosition := 0; FRemaining := 0; GetMem(FBuffer, BufSize); end; destructor TUtilsCustomInputStream.Destroy; begin if Assigned(FStream) then FlushBuffer; FreeMem(FBuffer); inherited; end; procedure TUtilsCustomInputStream.FlushBuffer; begin FStream.Position := FStream.Position - FRemaining; FRemaining := 0; FPosition := 0; end; function TUtilsCustomInputStream.GetPosition: Int64; begin Result := FStream.Position - FRemaining - FInitialStreamPosition; end; function TUtilsCustomInputStream.Read(var Buf; const Count: Longint): Boolean; var S, D: PAnsiChar; I: Integer; begin Result := True; if Count <= FRemaining then begin S := FBuffer + FPosition; D := @Buf; for I := Pred(Count) downto 0 do D[I] := S[I]; Inc(FPosition, Count); Dec(FRemaining, Count); Exit; end else FlushBuffer; if Count > FBufSize then begin if FStream.Read(Buf, Count) = 0 then Result := False; Exit; end; if FRemaining = 0 then begin FRemaining := FStream.Read(FBuffer^, FBufSize); if FRemaining = 0 then begin Result := False; Exit; end; FPosition := 0; end; S := FBuffer + FPosition; D := @Buf; for I := Pred(Count) downto 0 do D[I] := S[I]; Inc(FPosition, Count); Dec(FRemaining, Count); end; procedure TUtilsCustomInputStream.SetPosition(Value: Int64); begin FStream.Position := Value + FInitialStreamPosition; FRemaining := 0; FPosition := 0; end; { TUtilsCustomOutputStream } // TUtilsCustomOutputStream was provided by Robert Marquardt constructor TUtilsCustomOutputStream.Create(const Stream: TStream; const BufSize: Integer); begin FBuffer := nil; // Remark: If an exception occurs, the destructor is automatically called. FStream := nil; // Therefore, we need to initialize critical objects with nil first. if not Assigned(Stream) then raise EParserUtilsException.Create(SStreamNotSpecified); inherited Create; if Assigned(Stream) then FInitialStreamPosition := Stream.Position else FInitialStreamPosition := 0; FStream := Stream; GetMem(FBuffer, BufSize); FPosition := 0; FBufSize := BufSize; end; destructor TUtilsCustomOutputStream.Destroy; begin if Assigned(FStream) then FlushBuffer; FreeMem(FBuffer); inherited; end; procedure TUtilsCustomOutputStream.FlushBuffer; begin FStream.Write(FBuffer[0], FPosition); FPosition := 0; end; function TUtilsCustomOutputStream.GetPosition: Int64; begin Result := FStream.Position + FPosition - FInitialStreamPosition; end; procedure TUtilsCustomOutputStream.SetPosition(Value: Int64); begin FlushBuffer; FStream.Position := Value + FInitialStreamPosition; end; procedure TUtilsCustomOutputStream.Write(const Buf; const Count: Longint); var S, D: PAnsiChar; I: Integer; begin if FPosition + Count <= FBufSize then begin S := @Buf; D := FBuffer + FPosition; for I := Pred(Count) downto 0 do D[I] := S[I]; Inc(FPosition, Count); Exit; end else FlushBuffer; if Count > FBufSize then FStream.Write(Buf, Count) else begin S := @Buf; D := FBuffer + FPosition; for I := Pred(Count) downto 0 do D[I] := S[I]; Inc(FPosition, Count); end; end; { TUtilsCustomAutodetectInputStream } constructor TUtilsCustomAutodetectInputStream.Create(const Stream: TStream; const BufSize: Integer; const ExpectedEncoding, DefaultEncoding: string); var BOMCodec: TUnicodeCodec; DefaultCodec: TUnicodeCodec; ExpectedCodec: TUnicodeCodec; begin FCodec := nil; // Remark: If an exception occurs, the destructor is // automatically called. Therefore, we need to // initialize critical objects with nil before // we call the constructor of the base class. inherited Create(Stream, BufSize); FByteOrderMarkSize := 0; BOMCodec := TEncodingRepository.CreateCodecForStream(Stream); try if Assigned(BOMCodec) then begin if BOMCodec.HasAlias(ExpectedEncoding) then begin FByteOrderMarkSize := Length(BOMCodec.GetPreamble); FCodec := BOMCodec; end else if TUTF16BECodec.HasAlias(ExpectedEncoding) then begin if BOMCodec is TUTF16LECodec then raise EConvertError.Create(SByteOrderMarkMismatch); FCodec := TUTF16BECodec.Create; end else if TUTF16LECodec.HasAlias(ExpectedEncoding) then begin if BOMCodec is TUTF16BECodec then raise EConvertError.Create(SByteOrderMarkMismatch); FCodec := TUTF16LECodec.Create; end else if TUCS2LECodec.HasAlias(ExpectedEncoding) then begin // The alias for UCS-2 ("ISO-10646-UCS-2") does not allow to distinguish // between Little Endian and Big Endian UCS-2. Therefore we need to // have a look at the byte order mark, if any. if BOMCodec is TUTF16LECodec then begin FByteOrderMarkSize := Length(BOMCodec.GetPreamble); FCodec := TUCS2LECodec.Create; end else if BOMCodec is TUTF16BECodec then begin FByteOrderMarkSize := Length(BOMCodec.GetPreamble); FCodec := TUCS2BECodec.Create; end else FCodec := TUCS2LECodec.Create; end else if TUCS4LECodec.HasAlias(ExpectedEncoding) then begin // The alias for UCS-4 ("ISO-10646-UCS-4") does not allow to distinguish // between Little Endian and Big Endian UCS-5. Therefore we need to // have a look at the byte order mark, if any. if BOMCodec is TUCS4LECodec then begin FByteOrderMarkSize := Length(BOMCodec.GetPreamble); FCodec := TUCS4LECodec.Create; end else if BOMCodec is TUCS4BECodec then begin FByteOrderMarkSize := Length(BOMCodec.GetPreamble); FCodec := TUCS4BECodec.Create; end else if BOMCodec is TUCS4_2143Codec then begin FByteOrderMarkSize := Length(BOMCodec.GetPreamble); FCodec := TUCS4_2143Codec.Create; end else if BOMCodec is TUCS4_3412Codec then begin FByteOrderMarkSize := Length(BOMCodec.GetPreamble); FCodec := TUCS4_3412Codec.Create; end else FCodec := TUCS4LECodec.Create; end else begin ExpectedCodec := TEncodingRepository.CreateCodecByAlias(ExpectedEncoding); if Assigned(ExpectedCodec) then begin FCodec := ExpectedCodec; end else begin FByteOrderMarkSize := Length(BOMCodec.GetPreamble); FCodec := BOMCodec; end; end; end else begin ExpectedCodec := TEncodingRepository.CreateCodecByAlias(ExpectedEncoding); if Assigned(ExpectedCodec) then begin FCodec := ExpectedCodec; end else begin DefaultCodec := TEncodingRepository.CreateCodecByAlias(DefaultEncoding); if Assigned(DefaultCodec) then begin FCodec := DefaultCodec; end else raise EConvertError.Create(SDefaultEncodingNotSpecified); end; end; finally try Reset; finally if FCodec <> BOMCodec then BOMCodec.Free; end; end; end; destructor TUtilsCustomAutodetectInputStream.Destroy; begin FCodec.Free; inherited; end; function TUtilsCustomAutodetectInputStream.GetPosition: Int64; begin Result := inherited GetPosition - ByteOrderMarkSize; end; procedure TUtilsCustomAutodetectInputStream.Reset; begin Position := 0; end; procedure TUtilsCustomAutodetectInputStream.SetPosition(Value: Int64); begin inherited SetPosition(Value + ByteOrderMarkSize); end; { TUtilsAutodetectInputStream } procedure TUtilsAutodetectInputStream.ChangeEncoding(const AEncoding: string); var NewCodec: TUnicodeCodec; begin NewCodec := TEncodingRepository.CreateCodecByAlias(AEncoding); if not Assigned(NewCodec) then raise EParserUtilsException.Create(SEncodingNotSupported); NewCodec.ErrorAction := FCodec.ErrorAction; NewCodec.DecodeReplaceChar := FCodec.DecodeReplaceChar; NewCodec.ReadLFOption := FCodec.ReadLFOption; NewCodec.WriteLFOption := FCodec.WriteLFOption; NewCodec.OnRead := FCodec.OnRead; NewCodec.OnWrite := FCodec.OnWrite; FCodec.Free; FCodec := NewCodec; end; function TUtilsAutodetectInputStream.GetHasByteOrderMark: Boolean; begin Result := ByteOrderMarkSize <> 0; end; { TUtilsUCS4Reader } constructor TUtilsUCS4Reader.Create(const Stream: TStream; const ABufSize: Integer; const AEncoding: string; const InitialByteCount, InitialCharCount, InitialCharsInLine, InitialTabsInLine, InitialLine: Int64); // Creation fails if the source stream's first character (if any) cannot be // converted from the specified encoding to a UCS4 code point, because the // call to FCodec.ReadUCS4Char() in the Reset procedure raises an EConvertError // exception. begin inherited Create; FCodec := nil; // Remark: If an exception occurs, the destructor is automatically called. FInternalInputStream := nil; // Therefore, we need to initialize critical objects with nil first. with FInitialUCS4CharData do begin ByteCount := InitialByteCount; CharCount := InitialCharCount; CharsInLine := InitialCharsInLine; CodePoint := $98; // START OF STRING Line := InitialLine; Size := 0; TabsInLine := InitialTabsInLine; end; FResetPosition := 0; FInternalInputStream := TUtilsAutodetectInputStream.Create(Stream, ABufSize, AEncoding, DefaultEncoding); FInternalInputStream.Codec.ReadLFOption := lrNormalize; FInternalInputStream.Codec.OnRead := ReadEventHandler; Reset; end; destructor TUtilsUCS4Reader.Destroy; begin FCodec.Free; FInternalInputStream.Free; inherited; end; function TUtilsUCS4Reader.GetBof: Boolean; begin Result := CurrentCharInfo.CodePoint = $98; // START OF STRING end; function TUtilsUCS4Reader.GetBufSize: Integer; begin Result := InternalInputStream.BufSize; end; function TUtilsUCS4Reader.GetCodec: TUnicodeCodec; begin Result := InternalInputStream.Codec; end; function TUtilsUCS4Reader.GetDefaultEncoding: string; begin Result := 'UTF-8'; end; function TUtilsUCS4Reader.GetEof: Boolean; begin Result := CurrentCharInfo.CodePoint = $9C; // STRING TERMINATOR end; function TUtilsUCS4Reader.GetHasByteOrderMark: Boolean; begin Result := InternalInputStream.HasByteOrderMark; end; function TUtilsUCS4Reader.GetPosition: Int64; begin Result := InternalInputStream.Position; end; function TUtilsUCS4Reader.GetReadLFOption: TCodecReadLFOption; begin Result := Codec.ReadLFOption; end; function TUtilsUCS4Reader.Match(Ucs2Str: WideString): Boolean; // Raises an EConvertError exception via the call to Next(), if the next // character of the source stream cannot be converted (according to the // source's character encoding scheme) to a UCS4 code point. const STRING_TERMINATOR = $9C; var I: Integer; begin for I := 1 to Length(Ucs2Str) do begin Next; if CurrentCharInfo.CodePoint <> Ord(Ucs2Str[I]) then begin Result := False; Exit; // Missmatch found. end; end; Result := True; end; procedure TUtilsUCS4Reader.Next; // Raises an EConvertError exception via the call to FCodec.ReadUCS4Char(), // if the next character of the source stream cannot be converted (according // to the source's character encoding scheme) to a UCS4 code point. const STRING_TERMINATOR = $9C; var TempNextCP: UCS4Char; TempSize: Integer; begin if FCurrentUCS4Char.CodePoint = STRING_TERMINATOR then Exit; if FNextUCS4Char.CodePoint = STRING_TERMINATOR then begin FPreviousUCS4Char := FCurrentUCS4Char; FCurrentUCS4Char := FNextUCS4Char; Exit; end; Codec.ReadUCS4Char(TempNextCP, TempSize); // We use a temporary code point, so that the properties of TUtilsUCS4Reader // remain unchanged if FCodec.ReadUCS4Char() raises an exception. FPreviousUCS4Char := FCurrentUCS4Char; FCurrentUCS4Char := FNextUCS4Char; with FNextUCS4Char do begin Inc(CharCount, 1); CodePoint := TempNextCP; Inc(ByteCount, TempSize); Size := TempSize; end; UpdateLocator(FNextUCS4Char); end; procedure TUtilsUCS4Reader.ReadEventHandler(Sender: TObject; var Buf; Count: Longint; var Ok: Boolean); begin Ok := InternalInputStream.Read(Buf, Count); end; procedure TUtilsUCS4Reader.Reset; var TempNextCP: UCS4Char; TempSize: Integer; begin InternalInputStream.Position := ResetPosition; FPreviousUCS4Char := InitialUCS4CharData; FCurrentUCS4Char := InitialUCS4CharData; FNextUCS4Char := InitialUCS4CharData; Codec.ReadUCS4Char(TempNextCP, TempSize); with FNextUCS4Char do begin Inc(CharCount); CodePoint := TempNextCP; Inc(ByteCount, TempSize); Size := TempSize; end; UpdateLocator(FNextUCS4Char); end; procedure TUtilsUCS4Reader.SetEncoding(const Value: string); begin InternalInputStream.ChangeEncoding(Value) end; procedure TUtilsUCS4Reader.SetReadLFOption( const Value: TCodecReadLFOption); begin Codec.ReadLFOption := Value; end; procedure TUtilsUCS4Reader.SetResetPosition(const Value: Int64); begin FResetPosition := Value; end; function TUtilsUCS4Reader.SkipNext(Ucs2Str: WideString): Integer; // Raises an EConvertError exception via the call to Next(), if the next // character of the source stream cannot be converted (according to the // source's character encoding scheme) to a UCS4 code point. const STRING_TERMINATOR = $9C; var I: Integer; begin Result := 0; Next; if CurrentCharInfo.CodePoint = STRING_TERMINATOR then Exit; for I := 1 to Length(Ucs2Str) do if CurrentCharInfo.CodePoint = Ord(Ucs2Str[I]) then begin Result := SkipNext(Ucs2Str); Inc(Result); Exit; end; end; procedure TUtilsUCS4Reader.UpdateLocator(var UCS4CharData: TUtilsUCS4CharData); begin with UCS4CharData do case CodePoint of $A: begin // LF Inc(Line); CharsInLine := 0; TabsInLine := 0; end; $9: begin // TAB Inc(CharsInLine); Inc(TabsInLine); end; else Inc(CharsInLine); end; end; { TUtilsCustomTranscoder } procedure TUtilsCustomTranscoder.CodecReadEventHandler(Sender: TObject; var Buf; Count: Integer; var Ok: Boolean); begin Ok := False; // By default return False; end; procedure TUtilsCustomTranscoder.CodecWriteEventHandler(Sender: TObject; const Buf; Count: Integer); begin // By default do nothing. end; constructor TUtilsCustomTranscoder.Create; begin inherited; FBusy := False; FLineBreakOpt := lbNone; UpdateLineBreakOpt; end; destructor TUtilsCustomTranscoder.Destroy; begin FInputCodec.Free; FOutputCodec.Free; inherited Destroy; end; procedure TUtilsCustomTranscoder.DoProgress; begin if Assigned(FOnProgress) then FOnProgress(Self); end; procedure TUtilsCustomTranscoder.SetInputEncoding(const Value: string); var NewCodec: TUnicodeCodec; begin if Value = '' then begin FInputEncoding := ''; FInputCodec.Free; FInputCodec := nil; end else begin NewCodec := TEncodingRepository.CreateCodecByAlias(Value); if Assigned(NewCodec) then begin FInputCodec.Free; FInputCodec := NewCodec; FInputCodec.OnRead := CodecReadEventHandler; FInputEncoding := Value; UpdateLineBreakOpt; end else raise EParserUtilsException.Create(SEncodingNotSupported); end; {if value = '' else ...} end; procedure TUtilsCustomTranscoder.SetLineBreakOpt(const Value: TUtilsLineBreakOpt); begin if (FLineBreakOpt <> Value) and not FBusy then begin FLineBreakOpt := Value; UpdateLineBreakOpt; end; end; procedure TUtilsCustomTranscoder.SetOutputEncoding(const Value: string); var NewCodec: TUnicodeCodec; begin if Value = '' then begin FOutputEncoding := ''; FOutputCodec.Free; FOutputCodec := nil; end else begin NewCodec := TEncodingRepository.CreateCodecByAlias(Value); if Assigned(NewCodec) then begin FOutputCodec.Free; FOutputCodec := NewCodec; FOutputCodec.OnWrite := CodecWriteEventHandler; FOutputEncoding := Value; UpdateLineBreakOpt; end else raise EParserUtilsException.Create(SEncodingNotSupported); end; {if value = '' else ...} end; procedure TUtilsCustomTranscoder.Transcode; var C: UCS4Char; ByteCount: Integer; // Dummy begin if not Assigned(FInputCodec) then raise EParserUtilsException.Create(SInputEncodingNotSpecified); if not Assigned(FOutputCodec) then raise EParserUtilsException.Create(SOutputEncodingNotSpecified); FBusy := True; try while True do begin FInputCodec.ReadUCS4Char(C, ByteCount); if C = $9C then Exit; // $9C = STRING TERMINATOR FOutputCodec.WriteUCS4Char(C, ByteCount); DoProgress; end; finally FBusy := False; end; end; procedure TUtilsCustomTranscoder.UpdateLineBreakOpt; begin case FLineBreakOpt of lbCRLF: begin if Assigned(FInputCodec) then FInputCodec.ReadLFOption := lrNormalize; if Assigned(FOutputCodec) then FOutputCodec.WriteLFOption := lwCRLF; end; lbCR: begin if Assigned(FInputCodec) then FInputCodec.ReadLFOption := lrNormalize; if Assigned(FOutputCodec) then FOutputCodec.WriteLFOption := lwCR; end; lbLF: begin if Assigned(FInputCodec) then FInputCodec.ReadLFOption := lrNormalize; if Assigned(FOutputCodec) then FOutputCodec.WriteLFOption := lwLF; end; lbNone: begin if Assigned(FInputCodec) then FInputCodec.ReadLFOption := lrPass; if Assigned(FOutputCodec) then FOutputCodec.WriteLFOption := lwLF; end; end; end; { TUtilsStandardTranscoder } procedure TUtilsStandardTranscoder.CodecReadEventHandler(Sender: TObject; var Buf; Count: Integer; var Ok: Boolean); begin if Assigned(FOnRead) then FOnRead(Self, Buf, Count, Ok) else inherited; end; procedure TUtilsStandardTranscoder.CodecWriteEventHandler(Sender: TObject; const Buf; Count: Integer); begin if Assigned(FOnWrite) then FOnWrite(Self, Buf, Count); end; { TUtilsStreamTranscoder } procedure TUtilsStreamTranscoder.CodecReadEventHandler(Sender: TObject; var Buf; Count: Integer; var Ok: Boolean); begin Ok := FReader.Read(Buf, Count); end; procedure TUtilsStreamTranscoder.CodecWriteEventHandler(Sender: TObject; const Buf; Count: Integer); begin FWriter.Write(Buf, Count); end; constructor TUtilsStreamTranscoder.Create(const InputStream, OutputStream: TStream; const BufSize: Integer); begin inherited Create; FReader := TUtilsCustomInputStream.Create(InputStream, BufSize); FWriter := TUtilsCustomOutputStream.Create(OutputStream, BufSize); end; destructor TUtilsStreamTranscoder.Destroy; begin FReader.Free; FWriter.Free; inherited; end; end.
unit uFrmGrid; interface uses Windows, Forms, uFrmRoot, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, dxSkinsdxBarPainter, cxClasses, dxBar, ExtCtrls, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, Classes, Controls, cxGrid, DBClient, ImgList, ActnList; type TFrmGrid = class(TFrmRoot) grdbtblvwData: TcxGridDBTableView; grdlvlData: TcxGridLevel; grdData: TcxGrid; pnlTop: TPanel; dxbrmngr1: TdxBarManager; dxbrMenu: TdxBar; CdsData: TClientDataSet; DsData: TDataSource; btnNew: TdxBarButton; btnEdit: TdxBarButton; btnDelete: TdxBarButton; btnFilter: TdxBarButton; btnPreview: TdxBarButton; btnPrint: TdxBarButton; dxbrpmn1: TdxBarPopupMenu; actlst1: TActionList; actNew: TAction; actEdit: TAction; actDelete: TAction; actFilter: TAction; actExp: TAction; actImp: TAction; actPreview: TAction; actPrint: TAction; btnShowGroup: TdxBarButton; btnShowFilter: TdxBarButton; actShowGroup: TAction; actShowFilter: TAction; BtnRefresh: TdxBarButton; BtnExport: TdxBarButton; actRefresh: TAction; BtnAutoWidth: TdxBarButton; BtnAutoHeight: TdxBarButton; actAutoWidth: TAction; actAutoHeight: TAction; procedure actlst1Update(Action: TBasicAction; var Handled: Boolean); procedure actShowGroupExecute(Sender: TObject); procedure actShowFilterExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure actAutoWidthExecute(Sender: TObject); procedure actAutoHeightExecute(Sender: TObject); private procedure SetDataRowHeight(AutoHeight: Boolean = False); public { Public declarations } end; var FrmGrid: TFrmGrid; implementation uses UDmImage; {$R *.dfm} procedure TFrmGrid.actShowGroupExecute(Sender: TObject); begin grdbtblvwData.OptionsView.GroupByBox := not grdbtblvwData.OptionsView.GroupByBox; end; procedure TFrmGrid.actAutoHeightExecute(Sender: TObject); begin inherited; grdbtblvwData.OptionsView.CellAutoHeight := not grdbtblvwData.OptionsView.CellAutoHeight; SetDataRowHeight(grdbtblvwData.OptionsView.CellAutoHeight); end; procedure TFrmGrid.actAutoWidthExecute(Sender: TObject); begin inherited; grdbtblvwData.OptionsView.ColumnAutoWidth := not grdbtblvwData.OptionsView.ColumnAutoWidth; end; procedure TFrmGrid.actlst1Update(Action: TBasicAction; var Handled: Boolean); var lHasData: Boolean; begin inherited; actNew.Enabled := cdsData.Active; lHasData := cdsData.Active and not cdsData.IsEmpty; actEdit.Enabled := lHasData; actDelete.Enabled := lHasData; actExp.Enabled := lHasData; end; procedure TFrmGrid.actShowFilterExecute(Sender: TObject); begin grdbtblvwData.OptionsCustomize.ColumnFiltering := not grdbtblvwData.OptionsCustomize.ColumnFiltering; end; procedure TFrmGrid.FormCreate(Sender: TObject); begin inherited; actShowGroup.Checked := grdbtblvwData.OptionsView.GroupByBox; actShowFilter.Checked := grdbtblvwData.OptionsCustomize.ColumnFiltering; actAutoWidth.Checked := grdbtblvwData.OptionsView.ColumnAutoWidth; actAutoHeight.Checked := grdbtblvwData.OptionsView.CellAutoHeight; SetDataRowHeight(actAutoHeight.Checked); end; procedure TFrmGrid.SetDataRowHeight(AutoHeight: Boolean); begin if AutoHeight then grdbtblvwData.OptionsView.DataRowHeight := 0 else grdbtblvwData.OptionsView.DataRowHeight := 24; end; end.
// NOT Ported CDI unit SMARTSupport.NVMe.Intel; interface uses SysUtils, BufferInterpreter, Device.SMART.List, SMARTSupport, Support; type TIntelNVMeSMARTSupport = class(TSMARTSupport) private function ModelHasIntelString(const Model: String): Boolean; function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite; public function IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; override; function GetTypeName: String; override; function IsSSD: Boolean; override; function IsInsufficientSMART: Boolean; override; function GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; override; function IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; override; protected function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer; override; end; implementation { TIntelNVMeSMARTSupport } function TIntelNVMeSMARTSupport.GetTypeName: String; begin result := 'SmartNvme'; end; function TIntelNVMeSMARTSupport.IsInsufficientSMART: Boolean; begin result := false; end; function TIntelNVMeSMARTSupport.IsSSD: Boolean; begin result := true; end; function TIntelNVMeSMARTSupport.IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; begin result := (IdentifyDevice.StorageInterface = TStorageInterface.NVMe) and (ModelHasIntelString(IdentifyDevice.Model)); end; function TIntelNVMeSMARTSupport.ModelHasIntelString(const Model: String): Boolean; var ModelInUpperCase: String; begin ModelInUpperCase := UpperCase(Model); result := FindAtFirst('INTEL', ModelInUpperCase); end; function TIntelNVMeSMARTSupport.ErrorCheckedGetLife( const SMARTList: TSMARTValueList): Integer; begin result := SMARTList[SMARTList.GetIndexByID(3)].RAW; end; function TIntelNVMeSMARTSupport.IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; const WriteID = $05; begin try SMARTList.GetIndexByID(WriteID); result := true; except result := false; end; end; function TIntelNVMeSMARTSupport.GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; const ReadError = true; EraseError = false; UsedHourID = $0C; ThisErrorType = EraseError; ErrorID = $0E; ReplacedSectorsID = $00; CriticalErrorID = $01; begin FillChar(result, SizeOf(result), 0); result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID); result.ReadEraseError.TrueReadErrorFalseEraseError := ThisErrorType; result.ReadEraseError.Value := SMARTList.ExceptionFreeGetRAWByID(ErrorID); result.TotalWrite := GetTotalWrite(SMARTList); result.SMARTAlert.CriticalError := SMARTList.GetRAWByID(CriticalErrorID) > 0; end; function TIntelNVMeSMARTSupport.GetTotalWrite( const SMARTList: TSMARTValueList): TTotalWrite; function LBAToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shr 1; end; function GBToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shl 10; end; const HostWrite = true; NANDWrite = false; WriteID = $05; begin result.InValue.TrueHostWriteFalseNANDWrite := HostWrite; result.InValue.ValueInMiB := LBAToMB(SMARTList.ExceptionFreeGetRAWByID(WriteID)); end; end.
unit ComponentsSearchGroupUnit2; interface uses BaseComponentsGroupUnit2, NotifyEvents, System.Classes, ComponentsSearchQuery, FamilySearchQuery, SearchComponentOrFamilyQuery; type TComponentsSearchGroup2 = class(TBaseComponentsGroup2) private FOnOpenCategory: TNotifyEventsEx; FqComponentsSearch: TQueryComponentsSearch; FqFamilySearch: TQueryFamilySearch; function GetqComponentsSearch: TQueryComponentsSearch; function GetqFamilySearch: TQueryFamilySearch; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ApplyUpdates: Boolean; override; procedure ClearSearchResult; procedure OpenCategory; procedure Search(ALike: Boolean); property qComponentsSearch: TQueryComponentsSearch read GetqComponentsSearch; property qFamilySearch: TQueryFamilySearch read GetqFamilySearch; property OnOpenCategory: TNotifyEventsEx read FOnOpenCategory; end; implementation uses SearchInterfaceUnit, System.SysUtils; constructor TComponentsSearchGroup2.Create(AOwner: TComponent); begin inherited Create(AOwner); // Сначала будем открывать компоненты, чтобы при открытии семейства знать сколько у него компонент // Компоненты и семейства не связаны как главный-подчинённый главным для них является категория QList.Add(qComponentsSearch); QList.Add(qFamilySearch); FOnOpenCategory := TNotifyEventsEx.Create(Self); end; destructor TComponentsSearchGroup2.Destroy; begin FreeAndNil(FOnOpenCategory); inherited; end; function TComponentsSearchGroup2.ApplyUpdates: Boolean; begin // Если находимся в режиме отображения найденных записей if qFamilySearch.FamilySearchW.Mode = RecordsMode then begin Result := Inherited; end else Result := True; end; procedure TComponentsSearchGroup2.ClearSearchResult; begin qComponentsSearch.ClearSearchResult; qFamilySearch.ClearSearchResult; end; function TComponentsSearchGroup2.GetqComponentsSearch: TQueryComponentsSearch; begin if FqComponentsSearch = nil then FqComponentsSearch := TQueryComponentsSearch.Create(Self); Result := FqComponentsSearch; end; function TComponentsSearchGroup2.GetqFamilySearch: TQueryFamilySearch; begin if FqFamilySearch = nil then FqFamilySearch := TQueryFamilySearch.Create(Self); Result := FqFamilySearch; end; procedure TComponentsSearchGroup2.OpenCategory; begin FOnOpenCategory.CallEventHandlers(Self); end; procedure TComponentsSearchGroup2.Search(ALike: Boolean); var AValues: TArray<String>; begin qFamilySearch.W.TryPost; // Получаем список значений по которым будем осуществлять поиск AValues := qFamilySearch.W.Value.AllValues(',').ToUpper.Split([',']); if Length(AValues) = 0 then Exit; qComponentsSearch.SearchByValue(AValues, ALike); qFamilySearch.SearchByValue(AValues, ALike); end; end.
UNIT Astar; {$MODE Delphi} INTERFACE USES LinkedList, Map, MapObject; TYPE TPathNode = CLASS PUBLIC x, y : INTEGER; prev : TPathNode; CONSTRUCTOR create(_x, _y, destx, desty : INTEGER; _prev : TPathNode); OVERLOAD; CONSTRUCTOR create(_x, _y : INTEGER); OVERLOAD; FUNCTION getG() : INTEGER; FUNCTION getH() : INTEGER; FUNCTION getF() : INTEGER; PRIVATE g : INTEGER; f : INTEGER; END; FUNCTION heuristic(x1, y1, x2, y2 : INTEGER) : INTEGER; PROCEDURE pushPathNode(VAR openNodes, closedNodes, forbiddenNodes : TLinkedList; node : TPathNode); PROCEDURE findPath(startx, starty, destx, desty : INTEGER; map : TMap; o : TMapObject; VAR forbiddenNodes, result : TLinkedList); IMPLEMENTATION CONSTRUCTOR TPathNode.create(_x, _y, destx, desty : INTEGER; _prev : TPathNode); BEGIN x := _x; y := _y; prev := _prev; IF prev <> NIL THEN g := prev.getG()+1 ELSE g := 0; f := g + heuristic(x, y, destx, desty); END; CONSTRUCTOR TPathNode.create(_x, _y : INTEGER); BEGIN x := _x; y := _y; END; FUNCTION TPathNode.getG() : INTEGER; BEGIN getG := g; END; FUNCTION TPathNode.getH() : INTEGER; BEGIN getH := f - g; END; FUNCTION TPathNode.getF() : INTEGER; BEGIN getF := f; END; FUNCTION heuristic(x1, y1, x2, y2 : INTEGER) : INTEGER; //manhattan h BEGIN heuristic := ABS(x1-x2) + ABS(y1-y2); END; PROCEDURE pushPathNode(VAR openNodes, closedNodes, forbiddenNodes : TLinkedList; node : TPathNode); VAR ptr : TLinkedNode; BEGIN ptr := NIL; WHILE closedNodes.iterate(ptr) DO IF (TPathNode(ptr.getObject()).x = node.x) AND (TPathNode(ptr.getObject()).y = node.y) THEN BREAK; IF ptr = NIL THEN WHILE forbiddenNodes.iterate(ptr) DO IF (TPathNode(ptr.getObject()).x = node.x) AND (TPathNode(ptr.getObject()).y = node.y) THEN BREAK; IF ptr <> NIL THEN node.Destroy() ELSE BEGIN WHILE openNodes.iterate(ptr) DO BEGIN IF (TPathNode(ptr.getObject()).x = node.x) AND (TPathNode(ptr.getObject()).y = node.y) THEN BEGIN IF TPathNode(ptr.getObject()).getF() > node.getF() THEN BEGIN openNodes.release(ptr).destroy(); ptr := NIL; END; BREAK; END; END; IF ptr = NIL THEN BEGIN WHILE openNodes.iterate(ptr) DO IF TPathNode(ptr.getObject()).getF() > node.getF() THEN BREAK; IF ptr <> NIL THEN openNodes.insert(ptr.getPrev(), node) ELSE openNodes.insertBack(node); END; END; END; PROCEDURE findPath(startx, starty, destx, desty : INTEGER; map : TMap; o : TMapObject; VAR forbiddenNodes, result : TLinkedList); VAR openNodes, closedNodes : TLinkedList; VAR ptr : TLinkedNode; VAR currentNode, last : TPathNode; VAR currentX, currentY : INTEGER; BEGIN openNodes := TLinkedList.create(); closedNodes := TLinkedList.create(); ptr := NIL; IF NOT o.blocksMovement(map.getTile(destx, desty)) THEN BEGIN openNodes.insertFront(TPathNode.create(startx, starty, destx, desty, NIL)); WHILE NOT openNodes.isEmpty() DO BEGIN currentNode := TPathNode(openNodes.release(openNodes.getFirst())); currentX := currentNode.x; currentY := currentNode.y; IF (currentX = destx) AND (currentY = desty) THEN BEGIN last := currentNode; WHILE last <> NIL DO BEGIN result.insertFront(TPathNode.create(last.x, last.y)); last := last.prev; END; BREAK; END; closedNodes.insertBack(currentNode); IF NOT o.blocksMovement(map.getTile(currentX-1, currentY)) AND (currentX>0) THEN pushPathNode(openNodes, closedNodes, forbiddenNodes, TPathNode.create(currentX-1, currentY, destx, desty, currentNode)); IF NOT o.blocksMovement(map.getTile(currentX+1, currentY)) AND (currentX<map.getWidth()) THEN pushPathNode(openNodes, closedNodes, forbiddenNodes, TPathNode.create(currentX+1, currentY, destx, desty, currentNode)); IF NOT o.blocksMovement(map.getTile(currentX, currentY-1)) AND (currentY>0) THEN pushPathNode(openNodes, closedNodes, forbiddenNodes, TPathNode.create(currentX, currentY-1, destx, desty, currentNode)); IF NOT o.blocksMovement(map.getTile(currentX, currentY+1)) AND (currentY<map.getHeight()) THEN pushPathNode(openNodes, closedNodes, forbiddenNodes, TPathNode.create(currentX, currentY+1, destx, desty, currentNode)); END; END; openNodes.destroy(); closedNodes.destroy(); END; END.
unit MD5.Utils; interface uses System.SysUtils, System.DateUtils, Windows; const DATE_FORMAT = 'dd"/"mm"/"yyyy'; TIME_FORMAT = 'hh":"nn":"ss'; DATE_TIME_FORMAT = DATE_FORMAT + ' ' + TIME_FORMAT; /// <summary>Преобразовать байт в строковое представление</summary> function ByteToHex(B: Byte): String; /// <summary>Аналог функции FormatNumberHelper</summary> /// <remarks><see cref="FormatNumberHelper"/></remarks> function FormatNumber(N: UInt64): String; /// <summary>Convert number into string, with split by group of 3 chars</summary> /// <param name="N">N, number to convert to string</param> /// <returns>true, if convert is succesfull. false otherwise</returns> function FormatNumberHelper(N: UInt64): String; /// <summary>Проверить, пуста ли строка</summary> /// <param name="S">Проверяемая строка</param> /// <returns>true, если строка содержит только пробелы и символы табуляции, /// false в ином случае</returns> function StringIsEmpty(const S: String): Boolean; /// <summary> /// Вычисляем процент числа N1 от N2. Процент будет вычислен /// по формуле N1*100/N2. При этом, чтобы избежать переполнения, /// числа N1 и N2 делятся на 2 (SHR 1), пока оба они не станут /// меньше System.MaxInt ($7fffffff). /// </summary> /// <remarks> /// Если N1 > N2, функция вернет 100. /// </remarks> function Percent(N1, N2: UInt64): Integer; /// <summary> /// Преобразовать процент параметра N1 от N2 (используется функция Percent) /// в строковое представление. Слева дополняется пробелами до 3-х символов. /// </summary> function FormatPercent(N1, N2: UInt64): String; /// <summary> /// Вернуть текущую дату в строковом формате. /// Формат задается константой DATE_FORMAT. /// </summary> function CurrentDate: String; /// <summary> /// Вернуть текущее время в строковом формате. /// Формат задается константой TIME_FORMAT. /// </summary> function CurrentTime: String; /// <summary> /// Вернуть текущую дату и время в строковом формате. /// Формат задается константой DATE_TIME_FORMAT. /// </summary> function CurrentDateTime: String; /// <summary> /// Функция заменяет завершающие пробелы на символ '•', означающий, что в конце имени файла присутствуют пробелы /// </summary> /// <param name="S"> /// Строка с именем файла /// </param> /// <returns> /// Возвращает строку, у которой завершающие пробелы заменены на символ '•' /// </returns> function ShowTrailingSpaces(const S: String): String; type /// <summary> /// Структура предназначена для хранения дней, часов, минут, секунд, мс. /// </summary> TDayHourMinSec = record Day, Hour, Min, Second, Ms: Cardinal; procedure AssignFromMs(Ms: Cardinal); end; /// <summary>Класс, помогающий проверить, прошло ли X миллисекунд с момента последней проверки</summary> TTimer = class private StartTime: Cardinal; CheckTime: Cardinal; public constructor Create; /// <summary>Проверить, прошло ли указанное количество миллисекунд</summary> /// <param name="Delta">Количество миллисекунд</param> /// <returns>Возвращает TRUE, если с момента последней проверки прошло Delta миллисекунд. FALSE - в другом случае</returns> function CheckInterval(Delta: Cardinal): Boolean; /// <summary>Возвращает количество миллисекунд, прошедших с момента создания объекта</summary> function Passed: Cardinal; end; // /// <summary> /// Hold the value into class (for reference by pointer). /// </summary> TBoxing<T> = class private FValue: T; public constructor Create(Value: T); end; /// <summary> /// Сформировать UInt64 из двух половинок, Lo и Hi. /// </summary> function MakeUInt64(Lo, Hi: Cardinal): UInt64; inline; IMPLEMENTATION function MakeUInt64(Lo, Hi: Cardinal): UInt64; begin Int64Rec(Result).Lo := Lo; Int64Rec(Result).Hi := Hi; end; function TTimer.CheckInterval(Delta: Cardinal): Boolean; var Temp: Cardinal; begin Temp := GetTickCount; if (Temp - CheckTime) >= Delta then begin CheckTime := Temp; Exit(TRUE); end; Exit(FALSE); end; constructor TTimer.Create; begin inherited; StartTime := GetTickCount; CheckTime := StartTime; end; function TTimer.Passed: Cardinal; begin Exit(GetTickCount - StartTime); end; function ByteToHex(B: Byte): String; const Hexdigits: array[0..15] of Char = ('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'); begin Result := Hexdigits[B SHR 4] + Hexdigits[B AND $F]; end; function FormatNumber(N: UInt64): String; begin Result := FormatNumberHelper(N); end; // Вернуть TRUE, если в строке S только пробелы, или строка пустая function StringIsEmpty(const S: String): Boolean; var Ch: Char; begin for Ch in S do begin if NOT ((Ch = ' ') OR (Ch = #9)) then Exit(FALSE); end; Result := TRUE; end; function Percent(N1, N2: UInt64): Integer; begin if N1 > N2 then Exit(100); // Приводим числа к разрядности типа Integer (32 bits) while (N1 > $7fffffff) OR (N2 > $7fffffff) do begin N1 := N1 SHR 1; N2 := N2 SHR 1; end; Result := Windows.MulDiv(N1, 100, N2) end; function FormatPercent(N1, N2: UInt64): String; begin Result := IntToStr(Percent(N1, N2)).PadLeft(3) + '%'; end; { DONE : Создать объект, TTimer, который запоминает время своего создания. Чтобы в конце можно было вычислить время работы программы. Также, он должен отвечать на вопрос: с момента последней проверки прошло X миллисекунд? } function CurrentDate: String; var D: TDateTime; begin D := Today; DateTimeToString(Result, DATE_FORMAT, D); end; function CurrentTime: String; var T: TDateTime; begin T := Time; DateTimeToString(Result, TIME_FORMAT, T); end; function CurrentDateTime: String; begin DateTimeToString(Result, DATE_TIME_FORMAT, Now); end; function ShowTrailingSpaces(const S: String): String; var Index: Integer; begin Result := S; for Index := High(Result) downto Low(Result) do begin if Result[Index]=' ' then begin Result[Index] := '•'; end else Break; end; end; function FormatNumberHelper(N: UInt64): String; var Index, Group: Integer; Buffer: array[0..79] of Char; begin Index := High(Buffer)+1; Dec(Index); Buffer[Index] := #0; Group := 3; repeat Dec(Index); Buffer[Index] := Char((N MOD 10) + Ord('0')); N := N DIV 10; if N = 0 then Break; Dec(Group); if Group = 0 then begin Dec(Index); Buffer[Index] := '`'; Group := 3; end; until FALSE; Result := PChar(@Buffer[Index]); end; { TDayHourMinSec } procedure TDayHourMinSec.AssignFromMs(Ms: Cardinal); const SEC_DIVISOR = 1000; MIN_DIVISOR = SEC_DIVISOR*60; HRS_DIVISOR = MIN_DIVISOR*60; DAY_DIVISOR = HRS_DIVISOR*24; var T: Cardinal; begin Self.Day := Ms DIV DAY_DIVISOR; T := Ms MOD DAY_DIVISOR; // Self.Hour := T DIV HRS_DIVISOR; T := T MOD HRS_DIVISOR; // Self.Min := T DIV MIN_DIVISOR; T := T MOD MIN_DIVISOR; // Self.Second := T DIV SEC_DIVISOR; T := T MOD SEC_DIVISOR; // Self.Ms := T; end; { TBoxing<T> } constructor TBoxing<T>.Create(Value: T); begin FValue := Value; end; end.
unit uProgress; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, acProgressBar, ExtCtrls, StdCtrls, sLabel, Vcl.Imaging.GIFImg, sButton, acImage, sSkinManager; type TFProgressWnd = class(TForm) lblLoading: TsLabel; ImgLoading: TsImage; procedure FormCreate(Sender: TObject); private { Private declarations } m_Form: TForm; m_bViewCancel : Boolean; procedure Init( AParent: TForm; bViewCancel: Boolean); procedure FadeIn; procedure FadeOut; public { Public declarations } end; procedure ProgressBegin( AParent: TForm; bPossibleCancel: Boolean = False); procedure ProgressText( s : string ); procedure ProgressEnd; var gIsLoading : Boolean = True; FProgressWnd : TFProgressWnd = nil; implementation uses System.Types; {$R *.dfm} procedure ProgressBegin( AParent: TForm; bPossibleCancel : Boolean = False); begin if not gIsLoading then Exit; FProgressWnd.Init( AParent, bPossibleCancel); if AParent.Showing then FProgressWnd.Show; FProgressWnd.FadeIn; end; procedure ProgressText( s : string ); begin if FProgressWnd = nil then Exit; FProgressWnd.lblLoading.Caption := s; end; procedure ProgressEnd; begin if not gIsLoading then Exit; if FProgressWnd = nil then Exit; FProgressWnd.FadeOut; FProgressWnd.Hide; end; { TProgressWnd } procedure TFProgressWnd.FormCreate(Sender: TObject); begin ( imgLoading.Picture.Graphic as TGIFImage ).Animate := True; end; procedure TFProgressWnd.Init(AParent: TForm; bViewCancel: Boolean); var pt: TPoint; begin m_Form := AParent; m_bViewCancel := bViewCancel; pt := m_Form.ClientToScreen( Point( 0, 0 ) ); Self.Top := pt.Y; Self.Left := pt.X; // ��Ų ������ ����â �� �ʺ�, ���̰� ��߳� if AParent.HostDockSite = nil then begin Self.Height := m_Form.Height - 37; Self.Width := m_Form.Width - 15; end else begin Self.Height := m_Form.Height; Self.Width := m_Form.Width; end; end; procedure TFProgressWnd.FadeIn; begin repeat Self.AlphaBlendValue := Self.AlphaBlendValue + 10; Sleep(10); Application.ProcessMessages; until ( Self.AlphaBlendValue >= 200 ); end; procedure TFProgressWnd.FadeOut; begin repeat Self.AlphaBlendValue := Self.AlphaBlendValue - 10; Sleep(10); Application.ProcessMessages; until ( Self.AlphaBlendValue <= 10 ); end; end.
unit Rx.Observable.Take; interface uses Rx, Rx.Subjects; type TTake<T> = class(TPublishSubject<T>) strict private FCounter: Integer; FLimit: Integer; FSubscription: ISubscription; public constructor Create(Source: IObservable<T>; Limit: Integer); procedure OnNext(const Data: T); override; end; TSkip<T> = class(TPublishSubject<T>) strict private FCounter: Integer; public constructor Create(Source: IObservable<T>; Limit: Integer); procedure OnNext(const Data: T); override; end; TTakeLast<T> = class(TAsyncSubject<T>) strict private FLimit: Integer; public constructor Create(Source: IObservable<T>; Limit: Integer); procedure OnNext(const Data: T); override; end; implementation { TTake<T> } constructor TTake<T>.Create(Source: IObservable<T>; Limit: Integer); begin inherited Create; FSubscription := Merge(Source); FLimit := Limit end; procedure TTake<T>.OnNext(const Data: T); var RaiseMethod: Boolean; begin if not FSubscription.IsUnsubscribed then begin Lock; Inc(FCounter); RaiseMethod := FCounter <= FLimit; if not RaiseMethod then begin FSubscription.Unsubscribe; end; Unlock; if RaiseMethod then inherited OnNext(Data) else OnCompleted; end end; { TSkip<T> } constructor TSkip<T>.Create(Source: IObservable<T>; Limit: Integer); begin inherited Create; Merge(Source); FCounter := Limit end; procedure TSkip<T>.OnNext(const Data: T); var RaiseMethod: Boolean; begin Lock; RaiseMethod := FCounter <= 0; if not RaiseMethod then Dec(FCounter); Unlock; if RaiseMethod then inherited OnNext(Data); end; { TTakeLast<T> } constructor TTakeLast<T>.Create(Source: IObservable<T>; Limit: Integer); begin inherited Create; Merge(Source); FLimit := Limit end; procedure TTakeLast<T>.OnNext(const Data: T); begin Lock; try if Cache.Count >= FLimit then Cache.DeleteRange(0, Cache.Count - FLimit + 1); inherited OnNext(Data); finally Unlock; end; end; end.
unit PieReg; interface uses Windows, Classes, Graphics, Forms, Controls, Pies, Buttons, DsgnIntf, DsgnWnds, StdCtrls, ComCtrls; type TAngleEditorDlg = class(TForm) EAngleLabel: TLabel; OKButton: TButton; CancelButton: TButton; SAngleLabel: TLabel; STrackBar: TTrackBar; ETrackBar: TTrackBar; procedure CancelClick(Sender: TObject); procedure STrackBarChange(Sender: TObject); procedure ETrackBarChange(Sender: TObject); private FOrigStart, FOrigEnd: Integer; FAngles: TAngles; procedure SetStartAngle(Value: Integer); procedure SetEndAngle(Value: Integer); procedure SetAngles(Value: TAngles); public property EditorAngles: TAngles read FAngles write SetAngles; end; TAnglesProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { Component editor - brings up angle editor when double clicking on Angles property } TPieEditor = class(TDefaultEditor) protected procedure EditProperty(PropertyEditor: TPropertyEditor; var Continue, FreeEditor: Boolean); override; public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; procedure Register; implementation uses SysUtils; {$R *.DFM} { TAngleEditorDlg } procedure TAngleEditorDlg.STrackBarChange(Sender: TObject); begin SetStartAngle(STrackBar.Position); end; procedure TAngleEditorDlg.ETrackBarChange(Sender: TObject); begin SetEndAngle(ETrackBar.Position); end; procedure TAngleEditorDlg.SetStartAngle(Value: Integer); begin STrackBar.Position := Value; SAngleLabel.Caption := 'StartAngle = '+ IntToStr(Value); FAngles.StartAngle := Value; end; procedure TAngleEditorDlg.SetEndAngle(Value: Integer); begin ETrackBar.Position := Value; EAngleLabel.Caption := 'EndAngle = '+ IntToStr(Value); FAngles.EndAngle := Value; end; procedure TAngleEditorDlg.SetAngles(Value: TAngles); begin FAngles := Value; FOrigStart := Value.StartAngle; FOrigEnd := Value.EndAngle; SetStartAngle(Value.StartAngle); SetEndAngle(Value.EndAngle); end; procedure TAngleEditorDlg.CancelClick(Sender: TObject); begin SetStartAngle(FOrigStart); SetEndAngle(FOrigEnd); end; { TAnglesProperty } procedure TAnglesProperty.Edit; var Angles: TAngles; AngleEditor: TAngleEditorDlg; begin Angles := TAngles(GetOrdValue); AngleEditor := TAngleEditorDlg.Create(Application); try AngleEditor.EditorAngles := Angles; AngleEditor.ShowModal; finally AngleEditor.Free; end; end; function TAnglesProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paSubProperties]; end; {TPieEditor} procedure TPieEditor.EditProperty(PropertyEditor: TPropertyEditor; var Continue, FreeEditor: Boolean); var PropName: string; begin PropName := PropertyEditor.GetName; if (CompareText(PropName, 'ANGLES') = 0) then begin PropertyEditor.Edit; Continue := False; end; end; function TPieEditor.GetVerbCount: Integer; begin Result := 1; end; function TPieEditor.GetVerb(Index: Integer): string; begin if Index = 0 then Result := 'Edit Angles' else Result := ''; end; procedure TPieEditor.ExecuteVerb(Index: Integer); begin if Index = 0 then Edit; end; procedure Register; begin RegisterComponents('Samples',[TPie]); RegisterComponentEditor(TPie, TPieEditor); RegisterPropertyEditor(TypeInfo(TAngles), nil, '', TAnglesProperty); end; end.
unit U_AddMdyMeter; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, U_MyFunction; type TF_AddMdyMeter = class(TForm) lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; lbl4: TLabel; lbl5: TLabel; lbl6: TLabel; lbl7: TLabel; lbl8: TLabel; lbl9: TLabel; lbl10: TLabel; lbl11: TLabel; lbl12: TLabel; btn_ok: TBitBtn; btn_cancel: TBitBtn; edt_meterSn: TEdit; edt_meterAddr: TEdit; cbb_speed: TComboBox; cbb_port: TComboBox; cbb_protocol: TComboBox; edt_pwd: TEdit; cbb_tariff: TComboBox; cbb_int: TComboBox; cbb_dec: TComboBox; edt_coll: TEdit; cbb_largeClass: TComboBox; cbb_smallClass: TComboBox; procedure FormCreate(Sender: TObject); procedure btn_cancelClick(Sender: TObject); private { Private declarations } public { Public declarations } m_editFlag:Integer; end; var F_AddMdyMeter: TF_AddMdyMeter; implementation {$R *.dfm} uses U_MeterFile; procedure TF_AddMdyMeter.FormCreate(Sender: TObject); begin cbb_speed.Items.AddObject('默认', TObject(0)); cbb_speed.Items.AddObject('600', TObject(1)); cbb_speed.Items.AddObject('1200', TObject(2)); cbb_speed.Items.AddObject('2400', TObject(3)); cbb_speed.Items.AddObject('4800', TObject(4)); cbb_speed.Items.AddObject('7200', TObject(5)); cbb_speed.Items.AddObject('9600', TObject(6)); cbb_speed.Items.AddObject('19200', TObject(7)); cbb_port.Items.AddObject('交采', TObject(1)); cbb_port.Items.AddObject('485', TObject(2)); cbb_port.Items.AddObject('载波', TObject(31)); cbb_protocol.Items.AddObject('DL/T 645-1997', TObject(1)); cbb_protocol.Items.AddObject('DL/T 645-2007', TObject(30)); cbb_protocol.Items.AddObject('交流采样装置通信协议', TObject(2)); cbb_protocol.Items.AddObject('串行接口连接窄带低压载波通信模块', TObject(31)); cbb_tariff.Items.AddObject('单费率', TObject(1)); cbb_tariff.Items.AddObject('二费率', TObject(2)); cbb_tariff.Items.AddObject('三费率', TObject(3)); cbb_tariff.Items.AddObject('四费率', TObject(4)); cbb_int.Items.AddObject('4位', TObject(0)); cbb_int.Items.AddObject('5位', TObject(1)); cbb_int.Items.AddObject('6位', TObject(2)); cbb_int.Items.AddObject('7位', TObject(3)); cbb_dec.Items.AddObject('1位', TObject(0)); cbb_dec.Items.AddObject('2位', TObject(1)); cbb_dec.Items.AddObject('3位', TObject(2)); cbb_dec.Items.AddObject('4位', TObject(3)); cbb_largeClass.Items.AddObject('默认', TObject(0)); cbb_largeClass.Items.AddObject('大型专变用户(A类)', TObject(1)); cbb_largeClass.Items.AddObject('中小型专变用户(B类)', TObject(2)); cbb_largeClass.Items.AddObject('三相一般工商业用户(C类)', TObject(3)); cbb_largeClass.Items.AddObject('单相一般工商业用户(D类)', TObject(4)); cbb_largeClass.Items.AddObject('居民用户(E类)', TObject(5)); cbb_largeClass.Items.AddObject('公用配变考核计量点(F类)', TObject(6)); cbb_smallClass.Items.AddObject('默认', TObject(0)); cbb_smallClass.Items.AddObject('单相智能电能表用户', TObject(1)); cbb_smallClass.Items.AddObject('三相智能电能表用户', TObject(2)); end; procedure TF_AddMdyMeter.btn_cancelClick(Sender: TObject); begin Close; end; end.
unit FactoryConversor; interface uses InterfaceConversor, System.SysUtils, Data.DB, Datasnap.DBClient, JSONToDataSet, XMlToDataSet, CSVToDataSet; type TFactoryConversor = class public function ConverterArquivo(Arquivo: string; ClientDataSet: TClientDataSet): TConversor; end; EValidationError = class(Exception); implementation { TFactoryConversor } function TFactoryConversor.ConverterArquivo(Arquivo: string; ClientDataSet: TClientDataSet): TConversor; var FileExit: String; begin FileExit := ExtractFileExt(Arquivo); if FileExit = '.json' then Result := TJSONToDataSet.Create(Arquivo, ClientDataSet) else if FileExit = '.xml' then Result := TXMLToDataSet.Create(Arquivo, ClientDataSet) else if FileExit = '.csv' then Result := TCSVToDataSet.Create(Arquivo, ClientDataSet) else begin raise EvalidationError.Create('Arquivo invalido'); Result := nil; end; end; end.
 {$IFDEF FPC} {$MODE Delphi} {$ENDIF} //------------------------------------------------------------------------------------------------- unit OptType; interface uses Classes, DataTypes; const er_opt_MaxFunEval = 1; // превышено максимальное число вычислений функции er_Opt_InitVal = 2; // ќшибка инициализации алгоритма оптимизации er_opt_Eps = 3; // ќшибка оптимизаци по сходимости type // Функция присвоения выходов модели оптимизации SetOutsFunc = procedure(X, FX : PExtArr; var ner : NativeInt) of object; // Функция получения качества GetQualFunc = procedure(X, FX : PExtArr; var ner : NativeInt) of object; // Функция возврата результата от алгоритма оптимизации OutOptFunc = procedure(X, FX: PExtArr; N, M, NFE : integer; var stepout : integer) of object; // Функция сравнения результатов CompQualFunc = procedure(X, Y, FX, FY : PExtArr; N : integer; M : integer; var IC : integer) of object; // Базовый класс метода оптимизации TOptMethod = class public SETOUTS: SetOutsFunc; GETQUAL: GetQualFunc; OUT2: OutOptFunc; COMPQUAL: CompQualFunc; procedure InitMem(N,M: integer);virtual;abstract; procedure LeaveMem;virtual;abstract; procedure ExecuteStep(X,FX:PExtArr; N:integer; M:integer; DX: PExtArr; DXfinal:PExtArr; NFEMAX: integer; MinParam,MaxParam: PExtArr; var NER: NativeInt; var StopOpt: integer; var otp_step_position: integer );virtual;abstract; function RestartLoad(Stream: TStream;Count: integer;const TimeShift:double):boolean;virtual; procedure RestartSave(Stream: TStream);virtual; destructor Destroy;override; end; //############################################################################## implementation //############################################################################## destructor TOptMethod.Destroy; begin LeaveMem; inherited; end; //------------------------------------------------------------------------------------------------- function TOptMethod.RestartLoad(Stream: TStream;Count: integer;const TimeShift:double):boolean; begin Result:=True; end; //------------------------------------------------------------------------------------------------- procedure TOptMethod.RestartSave(Stream: TStream); begin end; //------------------------------------------------------------------------------------------------- end.
unit js_lexer; interface uses fw_utils,fw_vm_types,fw_system_types; type TJs_OnComment=function (src,tpos,pos:pchar;data:pointer):boolean; TJs_Lexer=class private CommentHandlers:pointer; CommentData:pointer; function LexError(s:string):boolean; // Genera un error lexico function pos_matches(p:pchar;k:cardinal):boolean; procedure lex_accept(k:cardinal); inline; function CheckInternal:boolean; public src:pchar; // Texto fuente spos,tpos,pos:pchar; // Posicion inicial del lexer, de inicio de token y del cursor error:string; // Error que se ha producido prevtoken,token,hash:cardinal; // Token anterior,Token Actual, hash del mismo y longitud constructor Create; destructor Destroy; override; procedure registerCommentHandler(f:TJs_OnComment;data:pointer); procedure CheckCommentHandlers; function Lex:boolean; // Avanza el lexer function lex_gtg(que:cardinal):integer; // Lex GetTestGet function lex_gt(que:cardinal):integer; // Lex GetTest function lex_tg(que:cardinal):integer; // Lex TestGet function lex_tge(que1,que2:cardinal):integer; // Lex TestGetExpect function lex_ge(que:cardinal):boolean; // Lex GetExpect function lex_eg(que:cardinal):boolean; // Lex ExpectGet function lex_N_eg(que:cardinal):boolean; // Lex NONE or EXPECTGET function lex_geg(que:cardinal):boolean; // Lex GetExpectGet function lex_gge(que:cardinal):boolean; // Lex GetGetExpect function lex_eeg(k1,k2:cardinal):boolean; // Lex ExpectExpectGet function lex_ee(k1,k2:cardinal):boolean; // Lex ExpectExpect function lex_gee(k1,k2:cardinal):boolean; // Lex GetExpectExpect function lex_gege(k1,k2:cardinal):boolean; // Lex GetExpectGetExpect function lex_token:string; // El token procedure SetSource(s:pchar); // Crea el lexer function CalcXY(p1:pchar):string; function lex_RegExpression:boolean; end; implementation uses js_tokens; constructor TJs_Lexer.Create; begin inherited Create; CommentHandlers:=l_create(SizeOf(POINTER),0); CommentData:=l_create(SizeOf(POINTER),0); end; destructor TJs_Lexer.Destroy; begin l_free(CommentHandlers); l_free(CommentData); inherited Destroy; end; procedure TJS_Lexer.registerCommentHandler(f:TJs_OnComment;data:pointer); begin if assigned(f) then begin l_push(CommentHandlers,@f);l_push(CommentData,data);end; end; procedure TJS_Lexer.CheckCommentHandlers; var i:longint; f:TJs_OnComment; begin i:=l_count(CommentHandlers); while (i>0) do begin i:=i-1;f:=l_get(CommentHandlers,i);if f(src,tpos,pos,l_get(CommentData,i)) then i:=0;end; end; procedure TJS_Lexer.SetSource(s:pchar); begin inherited Create; src:=s;pos:=src;error:=''; token:=jst_None;prevtoken:=token; //OnComment:=LexComment; end; procedure TJS_Lexer.lex_accept(k:cardinal); begin inc(pos);token:=k; end; function TJS_Lexer.pos_matches(p:pchar;k:cardinal):boolean; var k1:pchar; begin k1:=pos;result:=k>0; while result and (k>0) do begin result:=p^=k1^;k:=k-1;inc(p);inc(k1);end; end; function TJS_Lexer.Lex:boolean; begin if token=jst_Error then begin result:=false;exit;end; prevtoken:=token;result:=true;token:=jst_None;spos:=pos; // Nos saltamos los espacios y comentarios repeat while (pos^<>#0) and (pos^<=' ') do inc(pos); if pos_matches('//',2) then begin inc(pos,2);tpos:=pos; while (pos^<>#13) and (pos^<>#0) do inc(pos); CheckCommentHandlers;spos:=pos; end; if pos_matches('#$',2) then begin inc(pos,2);tpos:=pos; while (pos^<>'#') and (pos^<>#0) do inc(pos); if pos^='#' then inc(pos); CheckCommentHandlers;spos:=pos; end; if pos_matches('/*',2) then begin inc(pos,2);tpos:=pos; repeat inc(pos) until pos_matches('*/',2) or (pos^=#0); if pos^='*' then inc(pos,2) else begin result:=LexError('Unexpected END');exit;end; CheckCommentHandlers;spos:=pos; end; until (pos^=#0) or (pos^>' '); // Si tenemos el final salimos if pos^=#0 then begin token:=jst_Eof;exit;end; // Guardamos en que posicion estamos tpos:=pos; // Hacemos segun pos^ case pos^ of '{': lex_accept(jst_Begin); '}': lex_accept(jst_End); '(': lex_accept(jst_OpenPar); ')': lex_accept(jst_ClosePar); ':': lex_accept(jst_2Puntos); '[': lex_accept(jst_OpenB); ']': lex_accept(jst_CloseB); ',': lex_accept(jst_Comma); ';': lex_accept(jst_PComma); '~': lex_accept(jst_bNot); '.': lex_accept(jst_Dot); '?': lex_accept(jst_CondIf); '&': begin lex_accept(jst_bAnd); case pos^ of '&': lex_accept(jst_And); '=': lex_accept(jst_AsgnAnd);end;end; '|': begin lex_accept(jst_bOr); case pos^ of '|': lex_accept(jst_Or); '=': lex_accept(jst_AsgnOr);end;end; '+': begin lex_accept(jst_Add); case pos^ of '+': lex_accept(jst_PostInc); '=': lex_accept(jst_AsgnAdd);end;end; '-': begin lex_accept(jst_Minus); case pos^ of '-': lex_accept(jst_PostDec); '=': lex_accept(jst_AsgnMinus);end;end; '^': begin lex_accept(jst_bXOr); if pos^='=' then lex_accept(jst_AsgnXor);end; '*': begin lex_accept(jst_Times); if pos^='=' then lex_accept(jst_AsgnTimes);end; '/': begin lex_accept(jst_div); if pos^='=' then lex_accept(jst_AsgnDiv);end; '%': begin lex_accept(jst_Mod); if pos^='=' then lex_accept(jst_AsgnMod);end; '<': begin lex_accept(jst_Less); case pos^ of '<': begin lex_accept(jst_shiftl);if pos^='=' then lex_accept(jst_AsgnLeft);end; '=': lex_accept(jst_LessEq); end; end; '>': begin lex_accept(jst_big); case pos^ of '>': begin lex_accept(jst_shiftr); case pos^ of '=': lex_accept(jst_AsgnRight); '>': begin lex_accept(jst_shiftrz);if pos^='=' then lex_accept(jst_AsgnZRight);end; end; end; '=': lex_accept(jst_BigEq); end; end; '!': begin lex_accept(jst_Not); begin if pos^='=' then lex_accept(jst_Diff); if pos^='=' then lex_accept(jst_strictDif);end;end; '=': begin lex_accept(jst_Assign);begin if pos^='=' then lex_accept(jst_Equals);if pos^='=' then lex_accept(jst_strictEq);end;end; #39: begin token:=jst_PChar;inc(pos);end; #34: begin token:=jst_PChar2;inc(pos);end; '#': begin token:=jst_Internal;inc(pos);end; '0'..'9': begin token:=jst_Integer;inc(pos);end; 'A'..'Z','$','a'..'z','_': begin token:=jst_Ident;inc(pos);end; else begin tpos:=pos;result:=LexError('Illegal character');end; end; if token=jst_Error then exit; case token of jst_PChar: begin while ((pos^>=' ') or (pos^=#9)) and (pos^<>#39) do inc(pos);if pos^<>#39 then result:=LexError('Unterminated string ') else inc(pos);end; jst_PChar2: begin token:=jst_PChar;while ((pos^>=' ') or (pos^=#9)) and (pos^<>#34) do inc(pos);if pos^<>#34 then result:=LexError('Unterminated string ') else inc(pos);end; jst_Integer: begin while (pos^ in ['0'..'9']) do inc(pos);if (pos^='.') and ((pos+1)^ in ['0'..'9']) then begin token:=jst_Float;inc(pos);while (pos^ in ['0'..'9']) do inc(pos);end;end; jst_Dot: if (pos)^ in ['0'..'9'] then begin token:=jst_float;inc(pos);while (pos^ in ['0'..'9']) do inc(pos);end; jst_Ident: begin while (pos^ in ['A'..'Z','a'..'z','_','0'..'9']) do inc(pos);hash:=s_hash(lex_token);token:=js_keyword(hash);end; jst_Internal: result:=CheckInternal; end; end; function TJS_Lexer.CheckInternal:boolean; var p1:pchar; s:string; begin p1:=pos; while (pos^ in ['A'..'Z','a'..'z','_','0'..'9']) do inc(pos); s:=copy(p1,1,pos-p1); if s='....INTERNALCOMAND.' then begin token:=0;result:=true;exit;;end; token:=jst_Error; result:=LexError('Unknown Internal token: '+s); end; // Las funciones __Test__ Dan: 0 Si FALLO 1: SI -1: No function TJS_Lexer.lex_gtg(que:cardinal):integer; begin result:=0; if lex then begin if token<>que then result:=-1 else if lex then result:=1; end; end; function TJS_Lexer.lex_geg(que:cardinal):boolean; begin result:=lex;if not result then exit; result:=token=que; if result then result:=lex else LexError('Expected geg '+js_token2str(que)+' and have '); end; function TJS_Lexer.lex_gge(que:cardinal):boolean; // Lex GetGetExpect begin result:=lex and lex; if result then result:=token=que; end; // Entramos con / inicial function TJS_Lexer.lex_RegExpression:boolean; begin tpos:=pos;repeat inc(pos);until (pos^<' ') or (pos^='/'); if pos^<>'/' then begin result:=LexError('Unterminated Regular Expression');exit;end; result:=true; inc(pos); if pos^ in ['a'..'z','A'..'Z'] then inc(pos); end; function TJS_Lexer.lex_N_eg(que:cardinal):boolean; // Lex NONE or EXPECT then GET begin result:=que=jst_None; if not result then result:=lex_eg(que); end; function TJS_Lexer.lex_eg(que:cardinal):boolean; begin result:=token=que; if result then result:=lex else LexError('Expected eg '+js_token2str(que)+' and have '); end; function TJS_Lexer.lex_gege(k1,k2:cardinal):boolean; // Lex GetExpectGetExpect begin result:=lex_geg(k1); if result then result:=token=k2; end; function TJS_Lexer.lex_eeg(k1,k2:cardinal):boolean; // Lex ExpectExpectGet begin result:=token=k1; if result then begin result:=lex_ge(k2);if result then result:=lex;end else LexError('Expected eeg '+js_token2str(k1)+' and have '); end; function TJS_Lexer.lex_ee(k1,k2:cardinal):boolean; // Lex ExpectExpectGet begin result:=token=k1; if result then result:=lex_ge(k2) else LexError('Expected ee '+js_token2str(k1)+' and have '); end; function TJS_Lexer.lex_gee(k1,k2:cardinal):boolean; // Lex GetExpectExpect begin result:=lex_ge(k1);if result then result:=lex_ge(k2); end; function TJS_Lexer.lex_ge(que:cardinal):boolean; begin result:=lex;if not result then exit; result:=token=que;if not result then LexError('Expected ge '+js_token2str(que)+' and have ') end; // Las funciones __Test__ Dan: 0 Si FALLO 1: SI -1: No function TJS_Lexer.lex_tg(que:cardinal):integer; begin if token<>que then result:=-1 else if lex then result:=1 else result:=0; end; function TJS_Lexer.lex_tge(que1,que2:cardinal):integer; // Lex TestGetExpect begin if token<>que1 then result:=-1 else begin result:=0;if lex then if token=que2 then result:=1;end; end; function TJS_Lexer.lex_token: string; begin if token<>jst_PChar then result:=copy(tpos,1,pos-tpos) else result:=copy(tpos,2,pos-tpos-2); end; function TJS_Lexer.lex_gt(que:cardinal):integer; begin if not lex then result:=0 else if token=que then result:=1 else result:=-1; end; function TJS_Lexer.LexError(s:string):boolean; begin result:=false; if error='' then begin error:='Lex error: '+s+' ('+js_token2str(token)+') '+lex_token; error:=error+CalcXY(tpos); end; token:=jst_Error; end; function TJS_Lexer.CalcXY(p1:pchar):string; var p:pchar; posx,posy:cardinal; begin posy:=1;p:=p1; while (p^>=' ') and (p<>src) do dec(p); posx:=p1-p;if p=src then posx:=posx+1; p:=p1; while (p<>src) do begin if p^=#10 then posy:=posy+1;dec(p);end; result:=' in position '+s_i2s(posx)+','+s_i2s(posy); end; end.
unit OwnerProgressionDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBTables, StdCtrls, Buttons, ComCtrls, ExtCtrls, MemoDialog; type TSalesOwnerProgressionForm = class(TForm) SalesTable: TTable; AuditNameAddressTable: TTable; Panel1: TPanel; ProgressionOfOwnersLabel: TLabel; Panel2: TPanel; OwnerProgressionListView: TListView; pnlHistoryOfOwners: TPanel; lbHistoryOfOwnersHeader: TLabel; Panel4: TPanel; lstHistoryOfOwners: TListView; tbHistoryOfOwners: TTable; Panel3: TPanel; btnAddHistoryOfOwnersEntry: TBitBtn; MemoDialogBox: TMemoDialogBox; procedure btnAddHistoryOfOwnersEntryClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } sDeedBook, sDeedPage, sDeedDate, sSwisSBLKey : String; Procedure LoadHistoryOfOwnersGrid; Procedure InitializeForm(_SwisSBLKey : String; _DeedBook : String; _DeedPage : String; _DeedDate : String); end; var SalesOwnerProgressionForm: TSalesOwnerProgressionForm; implementation {$R *.DFM} uses GlblCnst, WinUtils, GlblVars, PASUtils, PASTypes, Utilitys, DataAccessUnit; {=====================================================================} Procedure TSalesOwnerProgressionForm.LoadHistoryOfOwnersGrid; begin lbHistoryOfOwnersHeader.Caption := 'History of owners for ' + ConvertSwisSBLToDashDot(sSwisSBLKey); tbHistoryOfOwners.TableName := 'PHistoryOfOwners'; tbHistoryOfOwners.Open; _SetRange(tbHistoryOfOwners, [sSwisSBLKey, '1/1/1900', 0], [sSwisSBLKey, '1/1/3000', 0], '', []); ClearListView(lstHistoryOfOwners); FillInListView(lstHistoryOfOwners, tbHistoryOfOwners, ['DeedBook', 'DeedPage', 'DeedDate', 'SequenceNumber', 'Comment'], False, True); end; {LoadHistoryOfOwnersGrid} {=====================================================================} Procedure TSalesOwnerProgressionForm.InitializeForm(_SwisSBLKey : String; _DeedBook : String; _DeedPage : String; _DeedDate : String); var NewNameAddrArray, OldNameAddrArray : NameAddrArray; ListItem : TListItem; I : Integer; begin sSwisSBLKey := _SwisSBLKey; sDeedBook := _DeedBook; sDeedPage := _DeedPage; sDeedDate := _DeedDate; ProgressionOfOwnersLabel.Caption := 'Progression of owners for ' + ConvertSwisSBLToDashDot(sSwisSBLKey); OpenTablesForForm(Self, ThisYear); SetRangeOld(AuditNameAddressTable, ['SwisSBLKey', 'Date', 'Time'], [sSwisSBLKey, '1/1/1900', ''], [sSwisSBLKey, '1/1/3000', '']); with AuditNameAddressTable do begin Last; while not BOF do begin FillInNameAddrArray(FieldByName('OldName1').Text, FieldByName('OldName2').Text, FieldByName('OldAddress1').Text, FieldByName('OldAddress2').Text, FieldByName('OldStreet').Text, FieldByName('OldCity').Text, FieldByName('OldState').Text, FieldByName('OldZip').Text, FieldByName('OldZipPlus4').Text, True, False, OldNameAddrArray); FillInNameAddrArray(FieldByName('NewName1').Text, FieldByName('NewName2').Text, FieldByName('NewAddress1').Text, FieldByName('NewAddress2').Text, FieldByName('NewStreet').Text, FieldByName('NewCity').Text, FieldByName('NewState').Text, FieldByName('NewZip').Text, FieldByName('NewZipPlus4').Text, True, False, NewNameAddrArray); with OwnerProgressionListView do ListItem := Items.Insert(Items.Count); ListItem.Caption := FieldByName('Date').Text; ListItem.SubItems.Add(FormatDateTime(TimeFormat, FieldByName('Time').AsDateTime)); ListItem.SubItems.Add(OldNameAddrArray[1]); ListItem.SubItems.Add(NewNameAddrArray[1]); ListItem.SubItems.Add(FieldByName('User').Text); For I := 2 to 6 do If ((Deblank(OldNameAddrArray[I]) <> '') or (Deblank(NewNameAddrArray[I]) <> '')) then begin with OwnerProgressionListView do ListItem := Items.Insert(Items.Count); ListItem.SubItems.Add(''); ListItem.SubItems.Add(OldNameAddrArray[I]); ListItem.SubItems.Add(NewNameAddrArray[I]); end; {If ((Deblank(OldNameAddrArray[I]) <> '') or ...} {Insert a blank line.} with OwnerProgressionListView do Items.Insert(Items.Count); Prior; end; {while not BOF do} end; {with AuditNameAddressTable do} If glblShowHistoryOfOwners then LoadHistoryOfOwnersGrid else begin pnlHistoryOfOwners.Visible := False; {FXX07062010-1(2.26.1.4)[I7277]: Incorrect height.} Height := 347; end; end; {InitializeForm} {========================================================================} Procedure TSalesOwnerProgressionForm.btnAddHistoryOfOwnersEntryClick(Sender: TObject); var I : Integer; begin MemoDialogBox.MemoCaption := lbHistoryOfOwnersHeader.Caption; If MemoDialogBox.Execute then begin For I := 0 to (MemoDialogBox.MemoLines.Count - 1) do with tbHistoryOfOwners do try Insert; FieldByName('SwisSBLKey').AsString := sSwisSBLKey; FieldByName('SequenceNumber').AsInteger := I + 1; FieldByName('DeedBook').AsString := sDeedBook; FieldByName('DeedPage').AsString := sDeedPage; FieldByName('DeedDate').AsString := sDeedDate; TMemoField(FieldByName('Comment')).AsString := MemoDialogBox.MemoLines[I]; Post; except end; LoadHistoryOfOwnersGrid; end; {If MemoDialogBox.Execute} end; {btnAddHistoryOfOwnersEntryClick} {=======================================================================} Procedure TSalesOwnerProgressionForm.FormClose( Sender: TObject; var Action: TCloseAction); begin _CloseTablesForForm(Self); end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFileGTS<p> GTS (GNU Triangulated Surface) vector file format implementation.<p> <b>History :</b><font size=-1><ul> <li>16/10/08 - UweR - Compatibility fix for Delphi 2009 <li>31/03/07 - DaStr - Added $I GLScene.inc <li>05/06/03 - SG - Separated from GLVectorFileObjects.pas </ul></font> } unit GLFileGTS; interface {$I GLScene.inc} uses System.Classes, GLVectorFileObjects, GLApplicationFileIO; type // TGLGTSVectorFile // {: The GTS vector file (GNU Triangulated Surface library).<p> It is a simple text format, with indexed vertices. The first line contains the number of vertices, the number of edges and the number of faces separated by spaces.<br> Following lines contain the x/y/z coordinates of vertices, then the edges (two indices) and the faces (three indices).<br> http://gts.sourceforge.net/ } TGLGTSVectorFile = class(TVectorFile) public { Public Declarations } class function Capabilities : TDataFileCapabilities; override; procedure LoadFromStream(aStream : TStream); override; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses {$IFDEF Unicode} Sysutils, {$ENDIF} GLUtils; // ------------------ // ------------------ TGLGTSVectorFile ------------------ // ------------------ // Capabilities // class function TGLGTSVectorFile.Capabilities : TDataFileCapabilities; begin Result:=[dfcRead]; end; // LoadFromStream // procedure TGLGTSVectorFile.LoadFromStream(aStream : TStream); var i, nv, ne, nf, k, ei : Integer; sl : TStringList; mesh : TMeshObject; fg : TFGVertexIndexList; vertIndices : array [0..5] of Integer; pEdge, pTri, p : PChar; begin sl:=TStringList.Create; try sl.LoadFromStream(aStream{$IFDEF Unicode}, TEncoding.ASCII{$ENDIF}); mesh:=TMeshObject.CreateOwned(Owner.MeshObjects); mesh.Mode:=momFaceGroups; if sl.Count>0 then begin p:=PChar(sl[0]); nv:=ParseInteger(p); ne:=ParseInteger(p); nf:=ParseInteger(p); if (nv or nf or ne)=0 then Exit; for i:=1 to nv do begin p:=PChar(sl[i]); mesh.Vertices.Add(ParseFloat(p), ParseFloat(p), ParseFloat(p)); end; fg:=TFGVertexIndexList.CreateOwned(mesh.FaceGroups); for i:=1+nv+ne to nv+ne+nf do begin pTri:=PChar(sl[i]); for k:=0 to 2 do begin ei:=ParseInteger(pTri); pEdge:=PChar(sl[nv+ei]); vertIndices[k*2+0]:=ParseInteger(pEdge); vertIndices[k*2+1]:=ParseInteger(pEdge); end; if (vertIndices[0]=vertIndices[2]) or (vertIndices[0]=vertIndices[3]) then fg.VertexIndices.Add(vertIndices[0]-1) else fg.VertexIndices.Add(vertIndices[1]-1); if (vertIndices[2]=vertIndices[4]) or (vertIndices[2]=vertIndices[5]) then fg.VertexIndices.Add(vertIndices[2]-1) else fg.VertexIndices.Add(vertIndices[3]-1); if (vertIndices[4]=vertIndices[0]) or (vertIndices[4]=vertIndices[1]) then fg.VertexIndices.Add(vertIndices[4]-1) else fg.VertexIndices.Add(vertIndices[5]-1); end; mesh.BuildNormals(fg.VertexIndices, momTriangles); end; finally sl.Free; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterVectorFileFormat('gts', 'GNU Triangulated Surface', TGLGTSVectorFile); end.
unit uMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Gauges, ExtCtrls, uChangeName; type TFrmMain = class(TForm) Panel2: TPanel; Panel1: TPanel; Panel3: TPanel; Panel4: TPanel; EdMaxHpNPCs1: TEdit; LbNPC1: TLabel; EdMaxHpNPCs2: TEdit; LbNPC2: TLabel; EdMaxHpNPCs3: TEdit; LbNPC3: TLabel; EdMaxHpNPCs4: TEdit; LbNPC4: TLabel; EdMaxHpNPCs5: TEdit; LbNPC5: TLabel; EdMaxHpNPCs6: TEdit; LbNPC6: TLabel; EdMaxHpNPCs7: TEdit; LbNPC7: TLabel; EdMaxHpNPCs8: TEdit; LbNPC8: TLabel; EdMaxHpNPCs9: TEdit; LbNPC9: TLabel; EdMaxHpNPCs10: TEdit; LbNPC10: TLabel; EdMaxHpNPCs11: TEdit; LbNPC11: TLabel; EdMaxHpNPCs12: TEdit; LbNPC12: TLabel; EdMaxHpNPCs13: TEdit; LbNPC13: TLabel; EdMaxHpNPCs14: TEdit; LbNPC14: TLabel; EdHpAtuNPCs1: TEdit; EdHpAtuNPCs2: TEdit; EdHpAtuNPCs3: TEdit; EdHpAtuNPCs4: TEdit; EdHpAtuNPCs5: TEdit; EdHpAtuNPCs6: TEdit; EdHpAtuNPCs7: TEdit; EdHpAtuNPCs8: TEdit; EdHpAtuNPCs9: TEdit; EdHpAtuNPCs10: TEdit; EdHpAtuNPCs11: TEdit; EdHpAtuNPCs12: TEdit; EdHpAtuNPCs13: TEdit; EdHpAtuNPCs14: TEdit; lbHPAtualNPC: TLabel; lbHPMaxNPC: TLabel; LbPlayer1: TLabel; EdMaxHPPlayer1: TEdit; EdHPPlayer1: TEdit; LbPlayer2: TLabel; EdMaxHPPlayer2: TEdit; EdHPPlayer2: TEdit; LbPlayer3: TLabel; EdMaxHPPlayer3: TEdit; EdHPPlayer3: TEdit; LbPlayer4: TLabel; EdMaxHPPlayer4: TEdit; EdHPPlayer4: TEdit; LbPlayer5: TLabel; EdMaxHPPlayer5: TEdit; EdHPPlayer5: TEdit; LbPlayer6: TLabel; EdMaxHPPlayer6: TEdit; EdHPPlayer6: TEdit; lbHpMaxPlayer: TLabel; lbHpAtualPlayer: TLabel; GgPlayer1: TGauge; GgPlayer2: TGauge; GgPlayer3: TGauge; GgPlayer4: TGauge; GgPlayer5: TGauge; GgPlayer6: TGauge; GgNPC6: TGauge; GgNPC1: TGauge; GgNPC2: TGauge; GgNPC3: TGauge; GgNPC4: TGauge; GgNPC5: TGauge; GgNPC12: TGauge; GgNPC7: TGauge; GgNPC8: TGauge; GgNPC9: TGauge; GgNPC10: TGauge; GgNPC11: TGauge; GgNPC13: TGauge; GgNPC14: TGauge; EdQtdPlayers: TEdit; LbQtdPlayers: TLabel; LbQtdNPCs: TLabel; EdQtdNPCs: TEdit; BtnShowPlayers: TButton; BtnShowNPCs: TButton; BtnAltNumPlay: TButton; BtnAltNumNPCs: TButton; BtnAtualizarNPCs: TButton; BtnGravarPlayer: TButton; BtnGravarNPCs: TButton; BtnAtualizarPlayer: TButton; Label1: TLabel; Button1: TButton; Procedure LblClick (sender: TObject); procedure FormCreate(Sender: TObject); procedure BtnShowPlayersClick(Sender: TObject); procedure BtnAltNumPlayClick(Sender: TObject); procedure BtnShowNPCsClick(Sender: TObject); procedure BtnAltNumNPCsClick(Sender: TObject); procedure BtnGravarPlayerClick(Sender: TObject); procedure BtnGravarNPCsClick(Sender: TObject); procedure BtnAtualizarPlayerClick(Sender: TObject); procedure BtnAtualizarNPCsClick(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } procedure AtribuirPlayers; procedure AtribuirNPCs; procedure MostrarPlayers; procedure EsconderPlayers; procedure MostrarNPCs; procedure EsconderNPCs; procedure ClearShowPlayers; procedure ClearShowNPCs; public { Public declarations } end; var FrmMain: TFrmMain; vLbPlayers: array [0..5] of TLabel; vEdMaxHPPlayers: array [0..5] of TEdit; vEdHPPlayers: array [0..5] of TEdit; vGgPlayers: array [0..5] of TGauge; vLbNPCs: array [0..13] of TLabel; vEdMaxHPNPCs: array [0..13] of TEdit; vEdHPNPCs: array [0..13] of TEdit; vGgNPCs: array [0..13] of TGauge; fQtdPlayers: Integer; fQtdNPCs: Integer; implementation uses uFichaCompleta; {$R *.dfm} { TForm1 } { TFrmMain } procedure TFrmMain.LblClick(sender: TObject); begin FrmChangeName.ShowModal; TLabel(sender).Caption := uChangeName.vName; end; procedure TFrmMain.FormCreate(Sender: TObject); begin AtribuirPlayers; AtribuirNPCs; end; procedure TFrmMain.AtribuirNPCs; begin vLbNPCs[0] := LbNPC1; vEdMaxHPNPCs[0] := EdMaxHpNPCs1; vEdHPNPCs[0] := EdHpAtuNPCs1; vGgNPCs[0] := GgNPC1; vLbNPCs[1] := LbNPC2; vEdMaxHPNPCs[1] := EdMaxHpNPCs2; vEdHPNPCs[1] := EdHpAtuNPCs2; vGgNPCs[1] := GgNPC2; vLbNPCs[2] := LbNPC3; vEdMaxHPNPCs[2] := EdMaxHpNPCs3; vEdHPNPCs[2] := EdHpAtuNPCs3; vGgNPCs[2] := GgNPC3; vLbNPCs[3] := LbNPC4; vEdMaxHPNPCs[3] := EdMaxHpNPCs4; vEdHPNPCs[3] := EdHpAtuNPCs4; vGgNPCs[3] := GgNPC4; vLbNPCs[4] := LbNPC5; vEdMaxHPNPCs[4] := EdMaxHpNPCs5; vEdHPNPCs[4] := EdHpAtuNPCs5; vGgNPCs[4] := GgNPC5; vLbNPCs[5] := LbNPC6; vEdMaxHPNPCs[5] := EdMaxHpNPCs6; vEdHPNPCs[5] := EdHpAtuNPCs6; vGgNPCs[5] := GgNPC6; vLbNPCs[6] := LbNPC7; vEdMaxHPNPCs[6] := EdMaxHpNPCs7; vEdHPNPCs[6] := EdHpAtuNPCs7; vGgNPCs[6] := GgNPC7; vLbNPCs[7] := LbNPC8; vEdMaxHPNPCs[7] := EdMaxHpNPCs8; vEdHPNPCs[7] := EdHpAtuNPCs8; vGgNPCs[7] := GgNPC8; vLbNPCs[8] := LbNPC9; vEdMaxHPNPCs[8] := EdMaxHpNPCs9; vEdHPNPCs[8] := EdHpAtuNPCs9; vGgNPCs[8] := GgNPC9; vLbNPCs[9] := LbNPC10; vEdMaxHPNPCs[9] := EdMaxHpNPCs10; vEdHPNPCs[9] := EdHpAtuNPCs10; vGgNPCs[9] := GgNPC10; vLbNPCs[10] := LbNPC11; vEdMaxHPNPCs[10] := EdMaxHpNPCs11; vEdHPNPCs[10] := EdHpAtuNPCs11; vGgNPCs[10] := GgNPC11; vLbNPCs[11] := LbNPC12; vEdMaxHPNPCs[11] := EdMaxHpNPCs12; vEdHPNPCs[11] := EdHpAtuNPCs12; vGgNPCs[11] := GgNPC12; vLbNPCs[12] := LbNPC13; vEdMaxHPNPCs[12] := EdMaxHpNPCs13; vEdHPNPCs[12] := EdHpAtuNPCs13; vGgNPCs[12] := GgNPC13; vLbNPCs[13] := LbNPC14; vEdMaxHPNPCs[13] := EdMaxHpNPCs14; vEdHPNPCs[13] := EdHpAtuNPCs14; vGgNPCs[13] := GgNPC14; end; procedure TFrmMain.AtribuirPlayers; begin vLbPlayers[0] := LbPlayer1; vEdMaxHPPlayers[0] := EdMaxHPPlayer1; vEdHPPlayers[0] := EdHPPlayer1; vGgPlayers[0] := GgPlayer1; vLbPlayers[1] := LbPlayer2; vEdMaxHPPlayers[1] := EdMaxHPPlayer2; vEdHPPlayers[1] := EdHPPlayer2; vGgPlayers[1] := GgPlayer2; vLbPlayers[2] := LbPlayer3; vEdMaxHPPlayers[2] := EdMaxHPPlayer3; vEdHPPlayers[2] := EdHPPlayer3; vGgPlayers[2] := GgPlayer3; vLbPlayers[3] := LbPlayer4; vEdMaxHPPlayers[3] := EdMaxHPPlayer4; vEdHPPlayers[3] := EdHPPlayer4; vGgPlayers[3] := GgPlayer4; vLbPlayers[4] := LbPlayer5; vEdMaxHPPlayers[4] := EdMaxHPPlayer5; vEdHPPlayers[4] := EdHPPlayer5; vGgPlayers[4] := GgPlayer5; vLbPlayers[5] := LbPlayer6; vEdMaxHPPlayers[5] := EdMaxHPPlayer6; vEdHPPlayers[5] := EdHPPlayer6; vGgPlayers[5] := GgPlayer6; end; procedure TFrmMain.BtnShowPlayersClick(Sender: TObject); // Funcionando 100% begin fQtdPlayers := 0; try fQtdPlayers := StrToInt(EdQtdPlayers.text); except on EConvertError do begin ClearShowPlayers; Abort; end; end; if (fQtdPlayers > 6) or (fQtdPlayers <= 0) then begin ClearShowPlayers; Abort; end; MostrarPlayers; BtnGravarPlayer.Visible := True; BtnAltNumPlay.Visible := True; BtnShowPlayers.Visible := False; EdQtdPlayers.Enabled := False; lbHpMaxPlayer.Visible := True; lbHpAtualPlayer.Visible := True; end; procedure TFrmMain.BtnAltNumPlayClick(Sender: TObject); // Funcionando 100% begin BtnShowPlayers.Visible := True; EdQtdPlayers.Enabled := True; BtnAltNumPlay.Visible := False; BtnAtualizarPlayer.Visible := False; BtnGravarPlayer.Visible := False; EsconderPlayers; end; procedure TFrmMain.BtnShowNPCsClick(Sender: TObject); // funcionando 100% begin fQtdNPCs := 0; // Validações... try fQtdNPCs := StrToInt(EdQtdNPCs.text); except on EConvertError do begin ClearShowNPCs; Abort; end; end; if (fQtdNPCs > 14) or (fQtdNPCs <= 0) then begin ClearShowNPCs; Abort; end; MostrarNpcs; BtnGravarNPCs.Visible := True; BtnAltNumNPCs.Visible := True; BtnShowNPCs.Visible := False; EdQtdNPCs.Enabled := False; lbHPMaxNPC.Visible := True; lbHPAtualNPC.Visible := True; end; procedure TFrmMain.BtnAltNumNPCsClick(Sender: TObject); // funcionando 100% begin BtnShowNPCs.Visible := True; EdQtdNPCs.Enabled := True; BtnAltNumNPCs.Visible := False; BtnAtualizarNPCs.Visible := False; BtnGravarNPCs.Visible := False; EsconderNPCs; end; procedure TFrmMain.BtnGravarPlayerClick(Sender: TObject); // funcionando 100% var i: Integer; begin if BtnGravarPlayer.Caption = 'Gravar' then begin for i := 0 to fQtdPlayers -1 do begin vEdMaxHPPlayers[i].Enabled := False; try vGgPlayers[i].MaxValue := StrToInt(vEdMaxHPPlayers[i].Text); if (vGgPlayers[i].Progress = 0) then vGgPlayers[i].Progress := vGgPlayers[i].MaxValue else BtnAtualizarPlayerClick(nil); except vEdMaxHPPlayers[i].Enabled := True; exit; end; end; BtnAtualizarPlayer.Visible := True; BtnGravarPlayer.Caption := 'Alterar'; end else begin for i := 0 to fQtdPlayers -1 do begin vEdMaxHPPlayers[i].Enabled := True; end; BtnAtualizarPlayer.Visible := False; BtnGravarPlayer.Caption := 'Gravar'; end; end; procedure TFrmMain.BtnGravarNPCsClick(Sender: TObject); // Funcionando 100% var i: Integer; begin if BtnGravarNPCs.Caption = 'Gravar' then begin for i := 0 to fQtdNPCs -1 do begin vEdMaxHPNPCs[i].Enabled := False; try vGgNPCs[i].MaxValue := StrToInt(vEdMaxHPNPCs[i].Text); if (vGgNPCs[i].Progress = 0) then vGgNPCs[i].Progress := vGgNPCs[i].MaxValue else BtnAtualizarNPCsClick(nil); except vEdMaxHPNPCs[i].Enabled := True; exit; end; end; BtnAtualizarNPCs.Visible := True; BtnGravarNPCs.Caption := 'Alterar'; end else begin for i := 0 to fQtdNPCs -1 do begin vEdMaxHPNPCs[i].Enabled := True; end; BtnAtualizarNPCs.Visible := False; BtnGravarNPCs.Caption := 'Gravar'; end; end; procedure TFrmMain.BtnAtualizarPlayerClick(Sender: TObject); // funcionando 80% ---> Gauge.Progress não marca o valor correto em alguns casos. Verificar! var i: Integer; xVal: Extended; xValStr: String; begin for i := 0 to fQtdPlayers -1 do begin xVal := ((StrToInt(vEdHPPlayers[i].Text) * 100) / (StrToInt(vEdMaxHPPlayers[i].Text))); xValStr := FloatToStr(xVal); vGgPlayers[i].Progress := 0; vGgPlayers[i].Progress := StrToInt(xValStr); end; end; procedure TFrmMain.EsconderPlayers; // Funcionando 100% var i: integer; begin for i := 0 to 5 do begin vLbPlayers[i].Visible := false; vEdMaxHPPlayers[i].Visible := false; vEdHPPlayers[i].Visible := false; vGgPlayers[i].Visible := false; end; lbHpMaxPlayer.Visible := False; lbHpAtualPlayer.Visible := False; EdQtdPlayers.SetFocus; EdQtdPlayers.Clear; end; procedure TFrmMain.MostrarPlayers; // funcionando 100% var i: integer; begin for i := 0 to fQtdPlayers -1 do begin vLbPlayers[i].Visible := true; vEdMaxHPPlayers[i].Visible := true; vEdHPPlayers[i].Visible := true; vGgPlayers[i].Visible := true; end; end; procedure TFrmMain.EsconderNPCs; // funcionando 100% var i: integer; begin for i := 0 to 13 do begin vLbNPCs[i].Visible := false; vEdMaxHPNPCs[i].Visible := false; vEdHPNPCs[i].Visible := false; vGgNPCs[i].Visible := false; end; lbHPMaxNPC.Visible := False; lbHPAtualNPC.Visible := False; EdQtdNPCs.SetFocus; EdQtdNPCs.Clear; end; procedure TFrmMain.MostrarNPCs; // funcionando 100% var i: integer; begin for i := 0 to fQtdNPCs -1 do begin vLbNPCs[i].Visible := true; vEdMaxHPNPCs[i].Visible := true; vEdHPNPCs[i].Visible := true; vGgNPCs[i].Visible := true; end; end; procedure TFrmMain.ClearShowPlayers; // funcionando 100% begin ShowMessage('Digite apenas valores de 1 a 6'); EdQtdPlayers.SetFocus; EdQtdPlayers.Clear; end; procedure TFrmMain.ClearShowNPCs; // funcionando 100% begin ShowMessage('Digite apenas valores de 1 a 14'); EdQtdNPCs.SetFocus; EdQtdNPCs.Clear; end; procedure TFrmMain.BtnAtualizarNPCsClick(Sender: TObject); var i: Integer; xVal: Extended; xValStr: String; begin for i := 0 to fQtdNPCs -1 do begin xVal := ((StrToInt(vEdHPNPCs[i].Text) * 100) / (StrToInt(vEdMaxHPNPCs[i].Text))); xValStr := FloatToStr(xVal); vGgNPCs[i].Progress := 0; vGgNPCs[i].Progress := StrToInt(xValStr); end; end; procedure TFrmMain.Button1Click(Sender: TObject); begin FrmFichaCompl.ShowModal; end; end.
unit uMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Threading, System.SyncObjs, System.NetEncoding, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.DialogService, FMX.Dialogs, FMX.Layouts, FMX.TreeView, FMX.Edit, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, FMX.Menus, FMX.Controls.Presentation, FMX.Objects, System.Actions, FMX.ActnList, FMX.ConstrainedForm, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.Memo.Types, Pkg.Json.Mapper, uUpdate, uUpdateForm, DTO.GitHUB.Release; const JsonValidatorUrl = 'http://jsonlint.com'; type TMainForm = class(TConstrainedForm) Memo1: TMemo; StyleBook1: TStyleBook; StatusBar1: TStatusBar; Label1: TLabel; MainPopupMenu: TPopupMenu; MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; Panel2: TPanel; Splitter1: TSplitter; Label4: TLabel; MemoPopupMenu: TPopupMenu; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; MenuItem8: TMenuItem; Panel3: TPanel; btnVisualize: TButton; btnOnlineJsonValidator: TButton; btnExit: TButton; Panel4: TPanel; Label5: TLabel; Edit2: TEdit; btnGenerateUnit: TButton; Panel1: TPanel; TreeView: TTreeView; Label3: TLabel; Button1: TButton; Label2: TLabel; Edit1: TEdit; ActionList1: TActionList; actPrettyPrintJSON: TAction; actValidateJSON: TAction; MenuItem4: TMenuItem; actRenameProperty: TAction; Splitter2: TSplitter; ListView1: TListView; actFMXDemo: TAction; Button3: TButton; procedure btnVisualizeClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure PreviewUnitClick(Sender: TObject); procedure MainPopupMenuPopup(Sender: TObject); procedure TreeViewDblClick(Sender: TObject); procedure MenuItem5Click(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure Label1Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure TreeViewKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure Panel1Resize(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure actPrettyPrintJSONExecute(Sender: TObject); procedure actValidateJSONExecute(Sender: TObject); procedure actRenamePropertyExecute(Sender: TObject); procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean); procedure btnExitClick(Sender: TObject); procedure ListView1Change(Sender: TObject); procedure ActDemoExecute(Sender: TObject); private { Private declarations } FJsonMapper: TPkgJsonMapper; FCheckVersionResponse: TRelease; FChanged: Boolean; // 0: Active // 1: Terminating // >=2: Terminated FApplicationStatus: Integer; FUpdateCheckEvent: TEvent; procedure VisualizeClass; procedure PrepareMenu; procedure DisableGuiElements; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} uses System.IoUtils, System.Json, uSaveUnitForm, Pkg.Json.Visualizer, Pkg.Json.DTO, Pkg.Json.StubField, Pkg.Json.DemoGenerator, Pkg.Json.Utils; const DemoDataRoot = '../../../Demo Data/'; procedure TMainForm.btnExitClick(Sender: TObject); begin Close; end; procedure TMainForm.btnVisualizeClick(Sender: TObject); begin if FChanged then TDialogService.MessageDialog('You made changes to the structure. Do you want to load original class?', TMsgDlgType.mtWarning, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], TMsgDlgBtn.mbYes, 0, procedure(const AResult: TModalResult) begin if AResult = mrYes then VisualizeClass; end) else VisualizeClass; end; procedure TMainForm.DisableGuiElements; begin Edit2.Enabled := false; Memo1.Enabled := false; TreeView.Enabled := false; TreeView.PopupMenu := nil; btnExit.Enabled := false; btnVisualize.Enabled := false; btnGenerateUnit.Enabled := false; end; procedure TMainForm.Edit1Change(Sender: TObject); begin Edit2.Text := Edit1.Text + 'U'; end; procedure TMainForm.PreviewUnitClick(Sender: TObject); begin if TreeView.Count = 0 then VisualizeClass; FJsonMapper.DestinationClassName := Edit1.Text; FJsonMapper.DestinationUnitName := Edit2.Text; FJsonMapper.Parse(Memo1.Lines.Text); with TSaveUnitForm.Create(nil) do try FileName := FJsonMapper.DestinationUnitName + '.pas'; Json := FJsonMapper.GenerateUnit; ShowModal; finally free; end; end; procedure TMainForm.ActionList1Update(Action: TBasicAction; var Handled: Boolean); var StubContainerField: TStubContainerField; begin actRenameProperty.Enabled := false; Panel1.Visible := TreeView.Count > 0; if TreeView.Selected = nil then exit; if TreeView.Selected = TreeView.Items[0] then exit; if not(TreeView.Selected.TagObject is TStubField) then exit; if TreeView.Selected.TagObject is TStubContainerField then StubContainerField := TStubField(TreeView.Selected.TagObject) as TStubContainerField else StubContainerField := nil; actRenameProperty.Enabled := (StubContainerField = nil); // and (StubContainerField.FieldType = jtObject); end; procedure TMainForm.actPrettyPrintJSONExecute(Sender: TObject); begin Memo1.Text := TJsonDTO.PrettyPrintJSON(Memo1.Text); end; procedure TMainForm.actRenamePropertyExecute(Sender: TObject); var StubField: TStubField; begin if TreeView.Selected.TagObject is TStubContainerField then exit; StubField := TStubField(TreeView.Selected.TagObject); TDialogService.InputQuery('Rename Property ' + StubField.Name, ['Enter new Property name'], [StubField.Name], procedure(const AResult: TModalResult; const AValues: array of string) var s: string; begin s := AValues[0]; if (s <> '') and (s.ToLower <> StubField.Name.ToLower) then begin FChanged := True; StubField.Name := s; JsonVisualizer.Visualize(TreeView, 'TreeViewItem1Style1', FJsonMapper); end; end); end; procedure TMainForm.actValidateJSONExecute(Sender: TObject); begin ShellExecute(JsonValidatorUrl); end; procedure TMainForm.ActDemoExecute(Sender: TObject); var Destination: string; begin if not SelectDirectory('Select a directory', Destination, Destination) then exit; with TDemoGenerator.Create do try DestinationClassName := Edit1.Text; DestinationUnitName := Edit2.Text; DestinationDirectory := Destination; DestinationFrameWork := TDestinationFrameWork.dfBoth; Json := Memo1.Text; Execute; finally free; end; TDialogService.MessageDialog('Demo project sucessfull genereted. Do you want to open the destination folder?', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], TMsgDlgBtn.mbYes, 0, procedure(const AResult: TModalResult) begin if AResult <> mrYes then exit; ShellExecute(Destination); end) end; procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if FUpdateCheckEvent.WaitFor(0) = wrSignaled then CanClose := True else begin CanClose := false; case FApplicationStatus of 0: begin TInterlocked.Increment(FApplicationStatus); DisableGuiElements; Label1.Text := 'Terminating application, please wait...'; // We start a termination task. // This way the main thread will not freeze TTask.Run( procedure begin FUpdateCheckEvent.WaitFor(); // Indicate next stage TInterlocked.Increment(FApplicationStatus); // We enqueue the handler TThread.Queue(nil, procedure begin Close; end); end); end; 1: ; else CanClose := True; end; end; end; procedure TMainForm.FormCreate(Sender: TObject); var FileName: String; begin FApplicationStatus := 0; FUpdateCheckEvent := TEvent.Create(nil, True, false, ''); Constraints.MinWidth := 1024; Constraints.MinHeight := 560; Caption := 'JsonToDelphiClass - ' + FloatToJson(ProgramVersion) + ' | By Jens Borrisholt'; FJsonMapper := TPkgJsonMapper.Create; Label1.Text := 'Checking for update...'; CheckForUpdate( procedure(aRelease: TRelease; aErrorMessage: string) begin FCheckVersionResponse := aRelease; if (aRelease = nil) and (aErrorMessage = '') then begin Label1.StyleLookup := 'LabelGreenStyle'; Label1.Text := 'Your version ' + FloatToJson(uUpdate.ProgramVersion) + ' is up to date! For more information about JsonToDelphiClass click here!'; (Label1.FindStyleResource('text') as TText).OnClick := Label1Click; end else if aErrorMessage = '' then begin Label1.StyleLookup := 'LabelLinkStyle'; Label1.Text := 'Version ' + aRelease.Tag_Name + ' is available! Click here to download!'; (Label1.FindStyleResource('text') as TText).OnClick := Label1Click; Label1.HitTest := True; end else begin Label1.StyleLookup := 'LabelErrorStyle'; Label1.Text := 'Error checking for new version: ' + aErrorMessage; end; FUpdateCheckEvent.SetEvent; end); ListView1.BeginUpdate; try for FileName in TDirectory.GetFiles(DemoDataRoot, '*.json') do ListView1.Items.Add.Text := TPath.GetFileName(FileName); finally ListView1.EndUpdate; end; TTask.Run( procedure begin Sleep(50); TThread.Queue(nil, procedure begin if ListView1.Items.Count > 0 then begin ListView1.ItemIndex := 0; ListView1.OnChange(nil); end; end); end); end; procedure TMainForm.FormDestroy(Sender: TObject); begin FreeAndNil(FUpdateCheckEvent); FreeAndNil(FJsonMapper); FreeAndNil(FCheckVersionResponse); end; procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = 27 then Close; end; procedure TMainForm.Label1Click(Sender: TObject); begin if FCheckVersionResponse = nil then ShellExecute(ProgramUrl) else with TUpdateForm.Create(nil) do try NewRelease := FCheckVersionResponse; ShowModal; finally free; end; end; procedure TMainForm.ListView1Change(Sender: TObject); var Item: TListViewItem; begin TreeView.Clear; Item := ListView1.Selected as TListViewItem; if Item = nil then begin Memo1.Lines.Clear; exit; end; with TStringList.Create do try LoadFromFile(DemoDataRoot + Item.Text); Memo1.Lines.Text := TJsonDTO.PrettyPrintJSON(Text); finally free; end; end; procedure TMainForm.MenuItem5Click(Sender: TObject); var StubField: TStubField; begin if TreeView.Selected.TagObject is TStubContainerField then exit; StubField := TStubField(TreeView.Selected.TagObject); TDialogService.InputQuery('Rename Class ' + StubField.Name, ['Enter new Property name'], [StubField.Name], procedure(const AResult: TModalResult; const AValues: array of string) var s: string; begin s := AValues[0]; if (s <> '') and (s.ToLower <> StubField.Name.ToLower) then begin FChanged := True; StubField.Name := s; JsonVisualizer.Visualize(TreeView, 'TreeViewItem1Style1', FJsonMapper); end; end); end; procedure TMainForm.Panel1Resize(Sender: TObject); begin if Panel1.Width < 200 then Panel1.Width := 200 else if Panel1.Width > (MainForm.Width - 20) div 2 then Panel1.Width := (MainForm.Width - 20) div 2; end; procedure TMainForm.MainPopupMenuPopup(Sender: TObject); var Item: TTreeViewItem; Point: TPointF; begin MainPopupMenu.Items[0].Text := '---'; Point := TreeView.AbsoluteToLocal(ScreenToClient(MainPopupMenu.PopupPoint)); Item := TreeView.ItemByPoint(Point.X, Point.Y); if Item <> nil then Item.Select; PrepareMenu; end; procedure TMainForm.PrepareMenu; var StubField: TStubField; begin if TreeView.Selected = nil then exit; MainPopupMenu.Items[0].Text := TreeView.Selected.Text; exit; if TreeView.Selected <> TreeView.Items[0] then begin StubField := TreeView.Selected.TagObject as TStubField; MainPopupMenu.Items[2].Enabled := True; MainPopupMenu.Items[2].TagObject := StubField; if (StubField is TStubContainerField) and ((StubField as TStubContainerField).ContainedType = TJsonType.jtObject) then begin MainPopupMenu.Items[3].Enabled := True; MainPopupMenu.Items[3].TagObject := (StubField as TStubContainerField).FieldClass; end; end else begin MainPopupMenu.Items[3].Enabled := True; MainPopupMenu.Items[3].TagObject := TreeView.Selected.TagObject; end; end; procedure TMainForm.TreeViewDblClick(Sender: TObject); begin if TreeView.Selected <> nil then TreeView.Selected.IsExpanded := not TreeView.Selected.IsExpanded; end; procedure TMainForm.TreeViewKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if ((KeyChar = #0) and (Key = 113)) and (TreeView.Selected <> nil) then begin PrepareMenu; if TreeView.Selected = TreeView.Items[0] then MenuItem5Click(MenuItem5) else actRenameProperty.Execute; end; end; procedure TMainForm.VisualizeClass; begin FChanged := false; FJsonMapper.DestinationUnitName := Edit1.Text; FJsonMapper.Parse(Memo1.Text); JsonVisualizer.Visualize(TreeView, 'TreeViewItem1Style1', FJsonMapper); Panel1.Width := Panel1.Width + 1; Panel1.Width := Panel1.Width - 1; end; end.
unit ORSystem; {$O-} {$WARN SYMBOL_PLATFORM OFF} interface uses Windows; const CPRS_ROOT_KEY = HKEY_LOCAL_MACHINE; CPRS_USER_KEY = HKEY_CURRENT_USER; CPRS_SOFTWARE = 'Software\Vista\CPRS'; CPRS_REG_AUTO = 'AutoUpdate'; CPRS_REG_GOLD = 'GoldCopyPath'; CPRS_REG_ONLY = 'LimitUpdate'; CPRS_REG_ASK = 'AskFirst'; CPRS_REG_LAST = 'LastUpdate-'; CPRS_USER_LAST = 'Software\Vista\CPRS\LastUpdate'; CPRS_LAST_DATE = 'Software\Vista\CPRS\DateUpdated'; function ClientVersion(const AFileName: string): string; function CompareVersion(const A, B: string): Integer; procedure CopyFileDate(const Source, Dest: string); procedure CopyLastWriteTime(const Source, Dest: string); procedure Delay(i: Integer); function FullToFilePart(const AFileName: string): string; function FullToPathPart(const AFileName: string): string; function IsWin95Style: Boolean; function ParamIndex(const AName: string): Integer; function ParamSearch(const AName: string): string; function QuotedExeName: string; function RegKeyExists(ARoot: HKEY; const AKey: string): Boolean; function RegReadInt(const AName: string): Integer; function RegReadStr(const AName: string): string; function RegReadBool(const AName: string): Boolean; procedure RegWriteInt(const AName: string; AValue: Integer); procedure RegWriteStr(const AName, AValue: string); procedure RegWriteBool(const AName: string; AValue: Boolean); function UserRegReadDateTime(const AKey, AName: string): TDateTime; procedure UserRegWriteDateTime(const AKey, AName: string; AValue: TDateTime); function UserRegReadInt(const AKey, AName: string): Integer; procedure UserRegWriteInt(const AKey, AName: string; AValue: Integer); procedure RunProgram(const AppName: string); function BorlandDLLVersionOK: boolean; implementation uses SysUtils, Classes, Forms, Registry, ORFn; const CREATE_KEY = True; // cause key to be created if it's not in the registry function FileLastWrite(const FileName: string): LARGE_INTEGER; var AHandle: THandle; FindData: TWin32FindData; begin Result.QuadPart := 0; AHandle := FindFirstFile(PChar(FileName), FindData); if AHandle <> INVALID_HANDLE_VALUE then begin Windows.FindClose(AHandle); Result.LowPart := FindData.ftLastWriteTime.dwLowDateTime; Result.HighPart := FindData.ftLastWriteTime.dwHighDateTime; end; end; function ClientVersion(const AFileName: string): string; var ASize, AHandle: DWORD; Buf: string; FileInfoPtr: Pointer; //PVSFixedFileInfo; begin Result := ''; ASize:=GetFileVersionInfoSize(PChar(AFileName), AHandle); if ASize > 0 then begin SetLength(Buf, ASize); GetFileVersionInfo(PChar(AFileName), AHandle, ASize, Pointer(Buf)); VerQueryValue(Pointer(Buf), '\', FileInfoPtr, ASize); with TVSFixedFileInfo(FileInfoPtr^) do Result := IntToStr(HIWORD(dwFileVersionMS)) + '.' + IntToStr(LOWORD(dwFileVersionMS)) + '.' + IntToStr(HIWORD(dwFileVersionLS)) + '.' + IntToStr(LOWORD(dwFileVersionLS)); end; end; function CompareVersion(const A, B: string): Integer; var NumA, NumB: Integer; begin NumA := (StrToInt(Piece(A, '.', 1)) * 16777216) + (StrToInt(Piece(A, '.', 2)) * 65536) + (StrToInt(Piece(A, '.', 3)) * 256) + StrToInt(Piece(A, '.', 4)); NumB := (StrToInt(Piece(B, '.', 1)) * 16777216) + (StrToInt(Piece(B, '.', 2)) * 65536) + (StrToInt(Piece(B, '.', 3)) * 256) + StrToInt(Piece(B, '.', 4)); Result := NumA - NumB; end; procedure CopyFileDate(const Source, Dest: string); { from TI2972 } var SourceHand, DestHand: Integer; begin SourceHand := FileOpen(Source, fmOutput); { open source file } DestHand := FileOpen(Dest, fmInput); { open dest file } FileSetDate(DestHand, FileGetDate(SourceHand)); { get/set date } FileClose(SourceHand); { close source file } FileClose(DestHand); { close dest file } end; procedure CopyLastWriteTime(const Source, Dest: string); var HandleSrc, HandleDest: Integer; LastWriteTime: TFileTime; begin HandleSrc := FileOpen(Source, fmOpenRead or fmShareDenyNone); HandleDest := FileOpen(Dest, fmOpenWrite); if (HandleSrc > 0) and (HandleDest > 0) then begin if GetFileTime(THandle(HandleSrc), nil, nil, @LastWriteTime) = TRUE then SetFileTime(THandle(HandleDest), nil, nil, @LastWriteTime); FileClose(HandleSrc); FileClose(HandleDest); end; end; procedure Delay(i: Integer); const AMilliSecond = 0.000000011574; var Start: TDateTime; begin Start := Now; while Now < (Start + (i * AMilliSecond)) do Application.ProcessMessages; end; procedure FileCopy(const FromFileName, ToFileName: string); var FromFile, ToFile: file; NumRead, NumWritten: Integer; Buf: array[1..16384] of Char; begin AssignFile(FromFile, FromFileName); // Input file Reset(FromFile, 1); // Record size = 1 AssignFile(ToFile, ToFileName); // Output file Rewrite(ToFile, 1); // Record size = 1 repeat BlockRead(FromFile, Buf, SizeOf(Buf), NumRead); BlockWrite(ToFile, Buf, NumRead, NumWritten); until (NumRead = 0) or (NumWritten <> NumRead); CloseFile(FromFile); CloseFile(ToFile); end; procedure FileCopyWithDate(const FromFileName, ToFileName: string); var FileHandle, ADate: Integer; begin FileCopy(FromFileName, ToFileName); FileHandle := FileOpen(FromFileName, fmOpenRead or fmShareDenyNone); ADate := FileGetDate(FileHandle); FileClose(FileHandle); if ADate < 0 then Exit; FileHandle := FileOpen(ToFileName, fmOpenWrite or fmShareDenyNone); if FileHandle > 0 then FileSetDate(FileHandle, ADate); FileClose(FileHandle); end; procedure CopyFileWithDate(const FromFileName, ToFileName: string); var FileHandle, ADate: Integer; begin if CopyFile(PChar(FromFileName), PChar(ToFileName), False) then begin FileHandle := FileOpen(FromFileName, fmOpenRead or fmShareDenyNone); ADate := FileGetDate(FileHandle); FileClose(FileHandle); if ADate < 0 then Exit; FileHandle := FileOpen(ToFileName, fmOpenWrite or fmShareDenyNone); if FileHandle > 0 then FileSetDate(FileHandle, ADate); FileClose(FileHandle); end; end; function FullToFilePart(const AFileName: string): string; var DirBuf: string; FilePart: PChar; NameLen: DWORD; begin Result := ''; SetString(DirBuf, nil, 255); NameLen := GetFullPathName(PChar(AFileName), 255, PChar(DirBuf), FilePart); if NameLen > 0 then Result := FilePart; end; function FullToPathPart(const AFileName: string): string; var DirBuf: string; FilePart: PChar; NameLen: Cardinal; begin Result := ''; SetString(DirBuf, nil, 255); NameLen := GetFullPathName(PChar(AFileName), 255, PChar(DirBuf), FilePart); if NameLen > 0 then Result := Copy(DirBuf, 1, NameLen - StrLen(FilePart)); end; function IsWin95Style: Boolean; begin Result := Lo(GetVersion) >= 4; // True = Win95 interface, otherwise old interface end; function ParamIndex(const AName: string): Integer; var i: Integer; x: string; begin Result := 0; for i := 1 to ParamCount do begin x := UpperCase(ParamStr(i)); x := Piece(x, '=', 1); if x = Uppercase(AName) then begin Result := i; Break; end; end; {for i} end; function ParamSearch(const AName: string): string; var i: Integer; x: string; begin Result := ''; for i := 1 to ParamCount do begin x := UpperCase(ParamStr(i)); x := Copy(x, 1, Pos('=', x) - 1); if x = Uppercase(AName) then begin Result := UpperCase(Copy(ParamStr(i), Length(x) + 2, Length(ParamStr(i)))); Break; end; end; {for i} end; function QuotedExeName: string; var i: Integer; begin Result := '"' + ParamStr(0) + '"'; for i := 1 to ParamCount do Result := Result + ' ' + ParamStr(i); end; function RegReadInt(const AName: string): Integer; var Registry: TRegistry; begin Result := 0; Registry := TRegistry.Create; try Registry.RootKey := CPRS_ROOT_KEY; if Registry.OpenKeyReadOnly(CPRS_SOFTWARE) and Registry.ValueExists(AName) then Result := Registry.ReadInteger(AName); Registry.CloseKey; finally Registry.Free; end; end; function RegReadStr(const AName: string): string; var Registry: TRegistry; begin Result := ''; Registry := TRegistry.Create; try Registry.RootKey := CPRS_ROOT_KEY; if Registry.OpenKeyReadOnly(CPRS_SOFTWARE) and Registry.ValueExists(AName) then Result := Registry.ReadString(AName); Registry.CloseKey; finally Registry.Free; end; end; function RegReadBool(const AName: string): Boolean; var Registry: TRegistry; begin Result := False; Registry := TRegistry.Create; try Registry.RootKey := CPRS_ROOT_KEY; if Registry.OpenKeyReadOnly(CPRS_SOFTWARE) and Registry.ValueExists(AName) then Result := Registry.ReadBool(AName); Registry.CloseKey; finally Registry.Free; end; end; procedure RegWriteInt(const AName: string; AValue: Integer); var Registry: TRegistry; begin Registry := TRegistry.Create; try Registry.RootKey := CPRS_ROOT_KEY; if Registry.OpenKey(CPRS_SOFTWARE, CREATE_KEY) then Registry.WriteInteger(AName, AValue); Registry.CloseKey; finally Registry.Free; end; end; procedure RegWriteStr(const AName, AValue: string); var Registry: TRegistry; begin Registry := TRegistry.Create; try Registry.RootKey := CPRS_ROOT_KEY; if Registry.OpenKey(CPRS_SOFTWARE, CREATE_KEY) then Registry.WriteString(AName, AValue); Registry.CloseKey; finally Registry.Free; end; end; procedure RegWriteBool(const AName: string; AValue: Boolean); var Registry: TRegistry; begin Registry := TRegistry.Create; try Registry.RootKey := CPRS_ROOT_KEY; if Registry.OpenKey(CPRS_SOFTWARE, CREATE_KEY) then Registry.WriteBool(AName, AValue); Registry.CloseKey; finally Registry.Free; end; end; function RegKeyExists(ARoot: HKEY; const AKey: string): Boolean; var Registry: TRegistry; begin Result := False; Registry := TRegistry.Create; try Registry.RootKey := ARoot; //Result := Registry.KeyExists(AKey); {this tries to open key with full access} if Registry.OpenKeyReadOnly(AKey) and (Registry.CurrentKey <> 0) then Result := True; Registry.CloseKey; finally Registry.Free; end; end; function UserRegReadDateTime(const AKey, AName: string): TDateTime; var Registry: TRegistry; begin Result := 0; Registry := TRegistry.Create; try Registry.RootKey := CPRS_USER_KEY; if Registry.OpenKey(AKey, CREATE_KEY) and Registry.ValueExists(AName) then try Result := Registry.ReadDateTime(AName); except on ERegistryException do Result := 0; end; Registry.CloseKey; finally Registry.Free; end; end; procedure UserRegWriteDateTime(const AKey, AName: string; AValue: TDateTime); var Registry: TRegistry; begin Registry := TRegistry.Create; try Registry.RootKey := CPRS_USER_KEY; if Registry.OpenKey(AKey, CREATE_KEY) then Registry.WriteDateTime(AName, AValue); Registry.CloseKey; finally Registry.Free; end; end; function UserRegReadInt(const AKey, AName: string): Integer; var Registry: TRegistry; begin Result := 0; Registry := TRegistry.Create; try Registry.RootKey := CPRS_USER_KEY; if Registry.OpenKey(AKey, CREATE_KEY) and Registry.ValueExists(AName) then Result := Registry.ReadInteger(AName); Registry.CloseKey; finally Registry.Free; end; end; procedure UserRegWriteInt(const AKey, AName: string; AValue: Integer); var Registry: TRegistry; begin Registry := TRegistry.Create; try Registry.RootKey := CPRS_USER_KEY; if Registry.OpenKey(AKey, CREATE_KEY) then Registry.WriteInteger(AName, AValue); Registry.CloseKey; finally Registry.Free; end; end; procedure RunProgram(const AppName: string); var StartInfo: TStartupInfo; ProcInfo: TProcessInformation; begin FillChar(StartInfo, SizeOf(StartInfo), 0); StartInfo.CB := SizeOf(StartInfo); CreateProcess(nil, PChar(AppName), nil, nil, False, DETACHED_PROCESS or NORMAL_PRIORITY_CLASS, nil, nil, StartInfo, ProcInfo); end; function BorlandDLLVersionOK: boolean; const DLL_CURRENT_VERSION = 10; TC_DLL_ERR = 'ERROR - BORLNDMM.DLL'; TX_NO_RUN = 'This version of CPRS is unable to run because' + CRLF; TX_NO_DLL = 'no copy of BORLNDMM.DLL can be found' + CRLF + 'in your workstation''s current PATH.'; TX_OLD_DLL1 = 'the copy of BORLNDMM.DLL located at:' + CRLF + CRLF; TX_OLD_DLL2 = CRLF + CRLF + 'is out of date (Version '; TX_CALL_IRM = CRLF + CRLF +'Please contact IRM for assistance.'; var DLLHandle: HMODULE; DLLNamePath: array[0..261] of Char; DLLVersion: string; begin Result := TRUE; DLLHandle := GetModuleHandle('BORLNDMM.DLL'); if DLLHandle <=0 then begin InfoBox(TX_NO_RUN + TX_NO_DLL + TX_CALL_IRM, TC_DLL_ERR, MB_ICONERROR or MB_OK); Result := FALSE; Exit; end; Windows.GetModuleFileName(DLLHandle, DLLNamePath, 261); DLLVersion := ClientVersion(DLLNamePath); if StrToIntDef(Piece(DLLVersion, '.', 1), 0) < DLL_CURRENT_VERSION then begin InfoBox(TX_NO_RUN + TX_OLD_DLL1 + ' ' + DLLNamePath + TX_OLD_DLL2 + DLLVersion + ')' + TX_CALL_IRM, TC_DLL_ERR, MB_ICONERROR or MB_OK); Result := false; end; end; end.
unit array_dynamic_3; interface implementation type TIntArray = array of int32; function ConcatArray(const A1, A2: TIntArray): TIntArray; begin SetLength(Result, Length(A1) + Length(A2)); end; var A, B, R: TIntArray; procedure Test; begin SetLength(A, 5); SetLength(B, 10); R := ConcatArray(A, B); end; initialization Test(); finalization Assert(Length(R) = 15); end.
unit stacks; interface const BoardSize = 8; type TCell = (cQueen, cUnderAttack, cFree); TBoard = array[1..BoardSize,1..BoardSize] of TCell; pStack=^TStack; TStack = record x: byte; board: TBoard; next:pStack; end; procedure CreateStack(var top:pStack); procedure PushStack(var top: pStack; x: byte; board: TBoard); procedure PopStack(var top: pStack; var x: byte; var board: TBoard); //function StackElements(var top: pStack): integer; implementation procedure CreateStack(var top: pStack); {создание пустого стека} begin top:=nil; end; procedure PushStack(var top: pStack; x: byte; board: TBoard); {добавление элемента в верх стека} var temp: pStack; begin new(temp); {выделяем память для нового элемента} temp^.x:=x; {присваиваем элементу информацию} temp^.board:=board; temp^.next:=top; {"ставим" новый элемент в верх стека} top:=temp; {сохраняем стек с новым элементом} end; procedure PopStack(var top: pStack; var x: byte; var board: TBoard); {изъятие элемента из вершины стека} var temp: pStack; begin if top<>nil then {если стек не пуст, то} begin temp:=top^.next; {сохраняем стек, начиная со второго элемента} x:=top^.x; {считываем информацию} board:=top^.board; dispose(top); {очищаем память от первого элемента} top:=temp; {записываем новый стек в top} end; end; end.
unit Branch; interface type TBranch = class private FCode: string; FName: string; public property Code: string read FCode write FCode; property Name: string read FName write FName; end; implementation end.
unit MainFormU; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, DBCtrls, Grids, DBGrids, StdCtrls, Mask, ActnList, Db, DBTables, StdActns, Menus, ImgList, DBClient; type TViews = (vwCustomersList, vwCustomerForm, vwOrdersList, vwOrderForm, vwItemsList); TMainForm = class(TForm) ActionList1: TActionList; ConnectAction: TAction; ViewOrdersListAction: TAction; ViewItemsListAction: TAction; ViewCustomerFormAction: TAction; ViewOrderFormAction: TAction; MainMenu1: TMainMenu; File1: TMenuItem; View1: TMenuItem; CustomerForm1: TMenuItem; OrderForm1: TMenuItem; OrdersList1: TMenuItem; ItemsList1: TMenuItem; Edit1: TMenuItem; CopyAction: TEditCopy; CutAction: TEditCut; PasteAction: TEditPaste; Cut1: TMenuItem; Copy1: TMenuItem; Paste1: TMenuItem; Search1: TMenuItem; GotoCustomer1: TMenuItem; ExitAction: TAction; Exit1: TMenuItem; PackBriefcaseAction: TAction; PackBriefcase1: TMenuItem; Server1: TMenuItem; Connect1: TMenuItem; ViewAvailableCustomersAction: TAction; ViewCustomersListAction: TAction; CustomersList1: TMenuItem; ApplyChanges1: TMenuItem; CancelChanges1: TMenuItem; ImageList1: TImageList; N1: TMenuItem; N2: TMenuItem; AvailableCustomers1: TMenuItem; CustomerEdits1: TMenuItem; Panel9: TPanel; Panel1: TPanel; Splitter1: TSplitter; Panel3: TPanel; DBText1: TDBText; Panel6: TPanel; Panel2: TPanel; Splitter2: TSplitter; Panel4: TPanel; DBText2: TDBText; Panel7: TPanel; Panel5: TPanel; DBText3: TDBText; Panel8: TPanel; Panel10: TPanel; DBText4: TDBText; Panel11: TPanel; Splitter3: TSplitter; ViewStatusLogAction: TAction; procedure FormCreate(Sender: TObject); procedure ConnectActionExecute(Sender: TObject); procedure ShowViewActionExecute(Sender: TObject); procedure ShowViewActionUpdate(Sender: TObject); procedure ExitActionExecute(Sender: TObject); procedure PackBriefcaseActionExecute(Sender: TObject); procedure ViewStatusLogActionExecute(Sender: TObject); procedure ViewStatusLogActionUpdate(Sender: TObject); private { Private declarations } procedure PackBriefcaseDialog; protected procedure Connect(AEmpNo: Integer); virtual; abstract; function ConnectDialog: Boolean; virtual; abstract; public { Public declarations } end; var MainForm: TMainForm; implementation uses ClientDataModuleU, OrdersListViewU, ItemsListViewU, CustomerFormViewU, OrderFormViewU, BaseViewU, AppActionsU, CustomerListViewU, PackBriefFormU, PageControlFormU; {$R *.DFM} var Views: array[TViews] of TBaseView = (nil, nil, nil, nil, nil); procedure TMainForm.FormCreate(Sender: TObject); function GetCmdLineArg(const Switch: string): string; const SwitchChars = ['-', '/']; var I: Integer; S: string; begin I := 1; while I <= ParamCount do begin S := ParamStr(I); if (SwitchChars = []) or (S[1] in SwitchChars) then if (AnsiCompareText(Copy(S, 2, Maxint), Switch) = 0) then begin Inc(I); if I <= ParamCount then begin Result := ParamStr(I); Exit; end; end; Inc(I); end; Result := ''; end; var SEmpNo: string; V: TViews; begin SEmpNo := GetCmdLineArg('E'); if SEmpNo <> '' then begin Connect(StrToInt(SEmpNo)); end else if not ConnectDialog then begin Application.ShowMainForm := False; Application.Terminate; Exit; end; ViewOrdersListAction.Tag := Integer(vwOrdersList); ViewOrderFormAction.Tag := Integer(vwOrderForm); ViewCustomerFormAction.Tag := Integer(vwCustomerForm); ViewItemsListAction.Tag := Integer(vwItemsList); ViewCustomersListAction.Tag := Integer(vwCustomersList); Views[vwOrdersList] := TOrdersListView.Create(Self); Views[vwOrderForm] := TOrderFormView.Create(Self); Views[vwItemsList] := TItemsListView.Create(Self); Views[vwCustomerForm] := TCustomerFormView.Create(Self); Views[vwCustomersList] := TCustomersListView.Create(Self); with TPageControlForm.Create(Self) do begin ManualDock(Panel9, nil, alTop); for V := Low(TViews) to High(TViews) do begin if V <> vwCustomersList then begin Views[V].ManualDock(ViewPageControl, nil, alTop); Views[V].Visible := True; end; end; ViewPageControl.ActivePage := ViewPageControl.Pages[0]; end; end; procedure TMainForm.ConnectActionExecute(Sender: TObject); begin ConnectDialog; end; procedure TMainForm.ShowViewActionExecute(Sender: TObject); var View: TBaseView; Action: TAction; begin if Sender is TWinControl then Sender := TWinControl(Sender).Action else if Sender is TMenuItem then Sender := TMenuItem(Sender).Action; Action := Sender as TAction; View := Views[TViews(Action.Tag)]; Action.Checked := not Action.Checked; View.Visible := Action.Checked; end; procedure TMainForm.ShowViewActionUpdate(Sender: TObject); var View: TBaseView; Action: TAction; begin Action := Sender as TAction; View := Views[TViews(Action.Tag)]; Action.Checked := View.Visible; end; procedure TMainForm.ExitActionExecute(Sender: TObject); begin Application.Terminate; end; procedure TMainForm.PackBriefcaseDialog; begin with TPackBriefForm.Create(Self) do try ShowModal; finally Free; end; end; procedure TMainForm.PackBriefcaseActionExecute(Sender: TObject); begin ClientDataModule.CustomerTreeDataSet.CheckBrowseMode; PackBriefcaseDialog; end; procedure TMainForm.ViewStatusLogActionExecute(Sender: TObject); begin with ClientDataModule.CustomerTreeDataSet do begin if StatusFilter = [] then StatusFilter := [usModified, usInserted, usDeleted] else StatusFilter := []; end; end; procedure TMainForm.ViewStatusLogActionUpdate(Sender: TObject); begin with ClientDataModule.CustomerTreeDataSet do ViewStatusLogAction.Checked := StatusFilter <> []; end; end.
program Domik; uses graphABC; const W = 1000; H = 800; winColor = clWhite; RAD = 180 / pi; { function Hypotenuse(leg1, leg2: integer): integer; { @Return hypotenuse length }{ begin Hypotenuse := round(sqrt(sqr(leg1) + sqr(leg2))); // Pythagorean theorem end; } procedure Brush ( color: System.Drawing.Color; style: System.Drawing.Drawing2D.DashStyle; width: integer ); { Sets brush options } begin SetPenColor(color); SetPenStyle(style); SetPenWidth(width); end; procedure Triangle ( apexX, apexY, alfa, // the main angle side, //a negative side value reverses the direction of the triangle. width: integer; firstColor, secondColor: System.Drawing.Color ); { Draws an isosceles triangle based on the side length and the main angle } begin var angle := alfa / 2 / RAD; // a half of the main angle expressed in RAD { The angle and the hypotenuse are known, you need to find the legs } var TrgX := round(side * sin(angle)); var TrgY := round(side * cos(angle)); Brush(firstColor, psSolid, width); Line(apexX, apexY, (apexX - TrgX), (apexY - TrgY)); Line(apexX, apexY, (apexX + TrgX), (apexY - TrgY)); Line((apexX - TrgX), (apexY - TrgY), (apexX + TrgX), (apexY - TrgY)); FloodFill(apexX, (apexY - (TrgY div 2)), secondColor); end; procedure Pine ( pineX, pineY, height, alfa: integer; // the angle of the pine twigs firstColor, // the trunk color secondColor: System.Drawing.Color // the twigs color ); { Draws primitive pine based on height and alfa parameters. The principle is to draw a pine tree from top to bottom, dividing the height into several SECTIONS: 1. the top triangle 2. the medium triangle 3. the large triangle 4. the trunk } begin var twig: array [0..3] of integer; var trunk := round(height * 0.2); twig[0] := 0; // distance between the top and the current twig apex twig[1] := round(height * 0.2); twig[2] := round(height * 0.3); twig[3] := round(height * 0.3); for var i := 1 to 3 do begin Triangle ( pineX, (pineY - height + twig[0]), // from top to bottom (alfa - 10 + i * 10), // the main angle increases by 10 per iteration { the leg and the angle (in degrees) are known, you need to find the hypotenuse } -round(twig[i] / cos((alfa - 10 + i * 10) / 2 / RAD)), 3, clBlack, secondColor ); twig[0] := twig[0] + twig[i]; // increases by previous twig height end; Brush(firstColor, psSolid, 5); Line(pineX, pineY, pineX, (pineY - trunk)); end; procedure Cottage ( Cx, Cy, height, alfa: integer; // the angle of the roof incline (>=90 deg) firstColor, // Basement color secondColor, // Roof color thirdColor, // Outline color fourthColor: System.Drawing.Color // Light color ); { ... } begin { main doughts } var xC1, xC2, yC, oneThird: integer; xC1 := Cx - height div 2; xC2 := Cx + height div 2; yC := Cy - height; oneThird := round(height / 3); { Draws basement } Brush(thirdColor, psSolid, 1); Rectangle(xC1, Cy, xC2, yC); FloodFill(Cx, (Cy - height div 2), firstColor); { Draws roof } Triangle ( Cx, (Cy - 3 * height div 2), // roofs height alfa, -round((height div 2) / cos(alfa / 2 / RAD)), // roofs incline 1, thirdColor, secondColor ); { Draws door } Brush(thirdColor, psSolid, 1); Rectangle ( (xC1 + round(oneThird * 2)), // right X + two-thirds of height Cy, xC2, (yC + oneThird) // top Y + one-third of height ); FloodFill((xC2 - oneThird div 2), (Cy - height div 2), thirdColor); { Draws window } Brush(thirdColor, psSolid, 1); Rectangle ( { window side is equal to one-third of basement side } (xC1 + oneThird - oneThird div 2), (Cy - oneThird), (xC1 + oneThird + oneThird div 2), (yC + oneThird) ); FloodFill ( (xC1 + oneThird), (Cy - oneThird - oneThird div 2), fourthColor ); Brush(thirdColor, psSolid, 3); Line // horizontal rod ( (xC1 + oneThird - oneThird div 2), (Cy - oneThird - oneThird div 2), (xC1 + oneThird + oneThird div 2), (Cy - oneThird - oneThird div 2) ); Line //vertical rod ( (xC1 + oneThird), (Cy - oneThird), (xC1 + oneThird), (Cy - oneThird - oneThird div 2) ); end; begin SetWindowSize(W, H); ClearWindow(winColor); Pine((W div 5), (H - H div 8), (H div 2), 70, clBrown, clGreen); Cottage ( (W div 2), (H div 2), (H div 3), 115, clTeal, clMaroon, clBrown, clYellow ); Cottage((W - W div 3), H, (H div 4), 115, clTeal, clMaroon, clBrown, clYellow); end.
Unit Utils; Interface Uses Windows; Function SymbolicLinkExists(ALinkName:WideString):Boolean; Procedure WinErrorMessage(AMsg:WideString; AErrorCode:Cardinal); Function GetDiskDriveLetters(ADiskNumber:Cardinal):WideString; Implementation Uses SysUtils; Const SYMBOLIC_LINK_QUERY = $1; OBJ_CASE_INSENSITIVE = $40; Type UNICODE_STRING = Record Lenth : Word; MaximumLength : Word; Buffer : PWideChar; end; PUNICODE_STRING = ^UNICODE_STRING; OBJECT_ATTRIBUTES = Record Length : Cardinal; RootDirectory : THandle; ObjectName : PUNICODE_STRING; Attributes : Cardinal; SecurityDescriptor : Pointer; SecurityQualityOfService : Pointer; end; POBJECT_ATTRIBUTES = ^OBJECT_ATTRIBUTES; _DISK_EXTENT = Record DiskNumber : Cardinal; StartingOffset : LARGE_INTEGER; ExtentLength : LARGE_INTEGER; end; DISK_EXTENT = _DISK_EXTENT; PDISK_EXTENT = ^DISK_EXTENT; _VOLUME_DISK_EXTENTS = Record NumberOfDiskExtents : Cardinal; Extents : Array [0..0] Of DISK_EXTENT; end; VOLUME_DISK_EXTENTS = _VOLUME_DISK_EXTENTS; PVOLUME_DISK_EXTENTS = ^VOLUME_DISK_EXTENTS; Function NtOpenSymbolicLinkObject(Var LinkHandle:THandle; DesiredAccess:Cardinal; Var ObjectAttributes:OBJECT_ATTRIBUTES):Cardinal; StdCall; External 'ntdll.dll'; Function NtClose(ObjectHandle:THandle):Cardinal; StdCall; External 'ntdll.dll'; Procedure RtlInitUnicodeString(Var UnicodeString:UNICODE_STRING; WStr:PWideChar); StdCall; External 'ntdll.dll'; Procedure WinErrorMessage(AMsg:WideString; AErrorCode:Cardinal); Var msg : WideString; begin msg := Format('%s'#13#10'Error code: %u'#13#10'Error message: %s', [AMsg, AErrorCode, SysErrorMessage(AErrorCode)]); MessageBoxW(0, PWideChar(msg), 'Error', MB_OK Or MB_ICONERROR); end; Function SymbolicLinkExists(ALinkName:WideString):Boolean; Var smHandle : THandle; uName : UNICODE_STRING; oa : OBJECT_ATTRIBUTES; status : Cardinal; begin RtlInitUnicodeString(uName, PWideChar(ALinkName)); oa.Length := SizeOf(oa); oa.RootDirectory := 0; oa.ObjectName := @uName; oa.Attributes := OBJ_CASE_INSENSITIVE; oa.SecurityDescriptor := Nil; oa.SecurityQualityOfService := Nil; status := NtOpenSymbolicLinkObject(smHandle, SYMBOLIC_LINK_QUERY, oa); Result := (status < $80000000); If Result Then NtClose(smHandle); end; Function GetDiskDriveLetters(ADiskNumber:Cardinal):WideString; Var I : Integer; driveHandle : THandle; driveLetter : WideChar; drivePath : WideString; err : cardinal; returnedLength : Cardinal; Extents : PVOLUME_DISK_EXTENTS; ExtentsLen : Cardinal; begin Result := ''; For driveLetter := 'A' To 'Z' Do begin drivePath := '\\.\' + driveLetter + ':'; driveHandle := CreateFIleW(PWideChar(drivePath), FILE_READ_ATTRIBUTES, FILE_SHARE_READ Or FILE_SHARE_WRITE, Nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); If driveHandle <> INVALID_HANDLE_VALUE Then begin ExtentsLen := 64; Repeat Extents := HeapAlloc(GetProcessHeap, 0, ExtentsLen); If Assigned(Extents) Then begin err := ERROR_SUCCESS; If Not DeviceIoControl(driveHandle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, Nil, 0, Extents, ExtentsLen, returnedLength, Nil) Then begin err := GetLastError; HeapFree(GetProcessHeap, 0, Extents); Inc(ExtentsLen, ExtentsLen); end; end Else err := ERROR_NOT_ENOUGH_MEMORY; Until err <> ERROR_INSUFFICIENT_BUFFER; If err = ERROR_SUCCESS Then begin For I := 0 To Extents.NumberOfDiskExtents - 1 Do begin If Extents.Extents[I].DiskNumber = ADiskNumber Then Result := Result + driveLetter + ' '; end; HeapFree(GetProcessHeap, 0, Extents); end; CloseHandle(driveHandle); end; end; If Result <> '' Then Delete(Result, Length(Result), 1); end; End.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {*******************************************************} { Windows specific property editors } {*******************************************************} unit VCLEditors; interface uses Winapi.Messages, System.Types, System.UITypes, System.Classes, System.Actions, Winapi.Windows, Vcl.Graphics, Vcl.Menus, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.Dialogs, DesignIntf, DesignEditors, DesignMenus, Vcl.ActnList, Vcl.ComCtrls; const CM_FORMMODIFIED = CM_BASE + 100; { Property Editors } type { ICustomPropertyDrawing Implementing this interface allows a property editor to take over the object inspector's drawing of the name and the value. If paFullWidthName is returned by IProperty.GetAttributes then only PropDrawName will be called. Default implementation of both these methods are provided in DefaultPropertyDrawName and DefaultPropertyDrawValue in this unit. } ICustomPropertyDrawing = interface ['{E1A50419-1288-4B26-9EFA-6608A35F0824}'] procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); end; { ICustomPropertyDrawing80 Use this interface in addition to the above interface to control the region in which the custom painting occurs. This allows only part of the value or the name to be custom painted. It also allows the embedded edit control to to be moved in order to paint next to it. When PropDrawxxxRect is called, return the rectangle in which custom painting is to be done. If the rect that is returned is empty, then no custom painting will take place for that item. For PropDrawValueRect, if you do return a smaller rectangle than the one given, then when this item is selected, the embedded edit control will be placed in the remaining rect, so be sure to leave enough room so the user can effectively type in the edit control. Returning the same rectangle as was passed in, will cause the edit control to revert to the previous behaviour of the edit control covering the entire value area and PropDrawValue must paint then entire rect.} ICustomPropertyDrawing80 = interface(ICustomPropertyDrawing) ['{73100176-DF0B-4900-AA52-4E67D7D04895}'] function PropDrawNameRect(const ARect: TRect): TRect; function PropDrawValueRect(const ARect: TRect): TRect; end; { ICustomPropertyMessage Implement this interface in order for the given property to handle mouse and other messages (such as CMHintShow). If the implementor handles the message, set Handled to true before returning to the caller. If Handled returns true the default processing is *not* done. } ICustomPropertyMessage = interface ['{60E3EB3A-23DD-459C-8936-0607A27D11A8}'] procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); procedure MouseMove(Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); procedure HintShow(var HintInfo: THintInfo; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); end; { ICustomPropertyDrawing Implementing this interface allows a property editor to take over the drawing of the drop down list box displayed by the property editor. This is only meaningful to implement if the property editor returns paValueList from IProperty.GetAttributes. The Value parameter is the result of IProperty.GetValue. The implementations ListMeasureWidth and ListMeasureHeight can be left blank since the var parameter is filled in to reasonable defaults by the object inspector. A default implementation of ListDrawValue is supplied in the DefaultPropertyListDrawValue procedure included in this unit } ICustomPropertyListDrawing = interface ['{BE2B8CF7-DDCA-4D4B-BE26-2396B969F8E0}'] procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); procedure ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); end; { TFontNameProperty Editor for the TFont.FontName property. Displays a drop-down list of all the fonts known by Winapi.Windows. The following global variable will make this property editor actually show examples of each of the fonts in the drop down list. We would have enabled this by default but it takes too many cycles on slower machines or those with a lot of fonts. Enable it at your own risk. ;-} var FontNamePropertyDisplayFontNames: Boolean = False; type TFontNameProperty = class(TStringProperty, ICustomPropertyListDrawing) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; // ICustomPropertyListDrawing procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); procedure ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); end; { TFontCharsetProperty Editor for the TFont.Charset property. Displays a drop-down list of the character-set by Winapi.Windows.} TFontCharsetProperty = class(TIntegerProperty) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; { TImeNameProperty Editor for the TImeName property. Displays a drop-down list of all the IME names known by Winapi.Windows.} TImeNameProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; { TColorProperty Property editor for the TColor type. Displays the color as a clXXX value if one exists, otherwise displays the value as hex. Also allows the clXXX value to be picked from a list. } TColorProperty = class(TIntegerProperty, ICustomPropertyDrawing, ICustomPropertyListDrawing, ICustomPropertyDrawing80) protected function PaintColorBox(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean): TRect; public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; { ICustomPropertyListDrawing } procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); procedure ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); { ICustomPropertyDrawing } procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); { ICustomPropertyDrawing80 } function PropDrawNameRect(const ARect: TRect): TRect; function PropDrawValueRect(const ARect: TRect): TRect; end; { TBrushStyleProperty Property editor for TBrush's Style. Simply provides for custom render. } TBrushStyleProperty = class(TEnumProperty, ICustomPropertyDrawing, ICustomPropertyListDrawing) public { ICustomPropertyListDrawing } procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); procedure ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); { ICustomPropertyDrawing } procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); end; { TPenStyleProperty Property editor for TPen's Style. Simply provides for custom render. } TPenStyleProperty = class(TEnumProperty, ICustomPropertyDrawing, ICustomPropertyListDrawing) public procedure GetValues(Proc: TGetStrProc); override; { ICustomPropertyListDrawing } procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); procedure ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); { ICustomPropertyDrawing } procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); end; { TCursorProperty Property editor for the TCursor type. Displays the cursor as a clXXX value if one exists, otherwise displays the value as hex. Also allows the clXXX value to be picked from a list. } TCursorProperty = class(TIntegerProperty, ICustomPropertyListDrawing) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; { ICustomPropertyListDrawing } procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); procedure ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); end; { TFontProperty Property editor for the Font property. Brings up the font dialog as well as allowing the properties of the object to be edited. } TFontProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { TModalResultProperty } TModalResultProperty = class(TIntegerProperty) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; { TShortCutProperty Property editor the ShortCut property. Allows both typing in a short cut value or picking a short-cut value from a list. } TShortCutProperty = class(TOrdinalProperty) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; TFileNameProperty = class(TStringProperty) protected procedure GetDialogOptions(Dialog: TOpenDialog); virtual; public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { TMPFilenameProperty Property editor for the TMediaPlayer. Displays an File Open Dialog for the name of the media file.} TMPFilenameProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { TTabOrderProperty Property editor for the TabOrder property. Prevents the property from being displayed when more than one component is selected. } TTabOrderProperty = class(TIntegerProperty) public function GetAttributes: TPropertyAttributes; override; end; { TCaptionProperty Property editor for the Caption and Text properties. Updates the value of the property for each change instead on when the property is approved. } TCaptionProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; end; function GetDisplayValue(const Prop: IProperty): string; { Spacing the Spacing parameter is used to specify the space between center-divider of the OI and the property value. } procedure DefaultPropertyDrawName(Prop: TPropertyEditor; Canvas: TCanvas; const Rect: TRect; Spacing : Integer = 0); procedure DefaultPropertyDrawValue(Prop: TPropertyEditor; Canvas: TCanvas; const Rect: TRect; Spacing : Integer = 0); procedure DefaultPropertyListDrawValue(const Value: string; Canvas: TCanvas; const Rect: TRect; Selected: Boolean; Spacing : Integer = 0); overload; procedure DefaultPropertyListDrawValue(const Value: WideString; Canvas: TCanvas; const Rect: TRect; Selected: Boolean; Spacing : Integer = 0); overload; { TBooleanProperty Property editor for boolean properties. Uses a checkbox to display the state of boolean properties and allows easier access to toggling them. } type TBooleanProperty = class(TEnumProperty, ICustomPropertyDrawing, ICustomPropertyDrawing80, ICustomPropertyMessage) protected function CBRect(const ItemRect: TRect) : TRect; public // ICustomPropertyDrawing procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); // ICustomPropertyDrawing80 function PropDrawNameRect(const ARect: TRect): TRect; function PropDrawValueRect(const ARect: TRect): TRect; // ICustomPropertyMessage procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); procedure MouseMove(Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); procedure HintShow(var HintInfo: THintInfo; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); end; { TSetProperty Override functionality of DesignEditors.TSetProperty to provide checkboxes for each set element similar to the Boolean property above } TSetProperty = class(DesignEditors.TSetProperty) public procedure GetProperties(Proc: TGetPropProc); override; end; TSetElementProperty = class(DesignEditors.TSetElementProperty, ICustomPropertyDrawing, ICustomPropertyDrawing80, ICustomPropertyMessage) private FBit : TBit; protected function CBRect(const ItemRect: TRect) : TRect; public // ICustomPropertyDrawing procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); // ICustomPropertyDrawing80 function PropDrawNameRect(const ARect: TRect): TRect; function PropDrawValueRect(const ARect: TRect): TRect; // ICustomPropertyMessage procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); procedure MouseMove(Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); procedure HintShow(var HintInfo: THintInfo; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); public constructor Create(Parent: TPropertyEditor; AElement: Integer); reintroduce; end; { TDateProperty Property editor for date portion of TDateTime type. } TDateProperty = class(DesignEditors.TDateProperty, IProperty80) private FControl : TMonthCalendar; FHost: IPropertyHost; FIgnoreDblClick: Boolean; public destructor Destroy; override; function GetAttributes: TPropertyAttributes; override; procedure Edit(const Host: IPropertyHost; DblClick: Boolean); reintroduce; overload; procedure CalendarDblClick(Sender: TObject); procedure CalendarKeyPress(Sender: TObject; var Key: Char); end; //{ TActionListView } // // TNewActionEvent = procedure(Sender: TObject; const Category: string; // ActionClass: TContainedActionClass; ActionList: TCustomActionList) of object; // TSelectActionEvent = procedure(Sender: TObject; Action: TContainedAction) of object; // TActionListView = class(TCustomListView) // private const // FDefItemHeight = 17; // private // FActionList: TCustomActionList; // FDesigner: IDesigner; // FImageList: TImageList; // FNewActnPopupMenu: TPopupMenu; // FNewStdActnPopupMenu: TPopupMenu; // FStdActionList: TStrings; // FTempStringList: TStrings; // FOnNewAction: TNewActionEvent; // FOnSelectAction: TSelectActionEvent; // procedure AddStdAction(const Category: string; // ActionClass: TBasicActionClass; Info: Pointer); // procedure AddTempString(const S: string); // function CreateMenuItem(const Caption: string; // Event: TNotifyEvent; CustomData: Pointer): TMenuItem; // procedure DoNewActionClick(Sender: TObject); // procedure DoNewStdActionClick(Sender: TObject); // procedure RebuildListView; // procedure RebuildPopupMenus; // procedure SetDesigner(const Value: IDesigner); // procedure ShowPopupMenu(Item: TListItem; PopupMenu: TPopupMenu); // protected // procedure CreateWnd; override; // function CustomDrawItem(Item: TListItem; State: TCustomDrawState; // Stage: TCustomDrawStage): Boolean; override; // function IsCustomDrawn(Target: TCustomDrawTarget; Stage: TCustomDrawStage): Boolean; override; // procedure KeyDown(var Key: Word; Shift: TShiftState); override; // public // constructor Create(AOwner: TComponent); override; // destructor Destroy; override; // procedure Click; override; // property Designer: IDesigner read FDesigner write SetDesigner; // property OnNewAction: TNewActionEvent read FOnNewAction write FOnNewAction; // property OnSelectAction: TSelectActionEvent read FOnSelectAction write FOnSelectAction; // end; // //{ TActionProperty } // // TActionProperty = class(TComponentProperty, IProperty80) // private // FActionListView: TActionListView; // FHost: IPropertyHost; // procedure CreateNewAction(Sender: TObject; const Category: string; // ActionClass: TContainedActionClass; ActionList: TCustomActionList); // procedure SelectAction(Sender: TObject; Action: TContainedAction); // public // destructor Destroy; override; // // IProperty80 // procedure Edit(const Host: IPropertyHost; DblClick: Boolean); reintroduce; overload; // function GetAttributes: TPropertyAttributes; override; // end; type { ISelectionMessage } { If a selection editor implements this interface the form designer will ensure all windows message are first sent through this interface before handling them when the selection editor for the corresponding class is selected. IsSelectionMessage - Filter for all messages processed by the designer when this the implementing selection editor is active. Return True if the message is handled by the selection editor which causes the designer to ignore the message (as well as preventing the control from seeing the message) or False, allowing the designer to process the message normally. Sender the control that received the original message. Message the message sent by windows to the control. } ISelectionMessage = interface ['{58274878-BB87-406A-9220-904105C9E112}'] function IsSelectionMessage(Sender: TControl; var Message: TMessage): Boolean; end; ISelectionMessageList = interface ['{C1360368-0099-4A7C-A4A8-7650503BA0C6}'] function Get(Index: Integer): ISelectionMessage; function GetCount: Integer; property Count: Integer read GetCount; property Items[Index: Integer]: ISelectionMessage read Get; default; end; function SelectionMessageListOf(const SelectionEditorList: ISelectionEditorList): ISelectionMessageList; { Custom Module Types } type { ICustomDesignForm Allows a custom module to create a different form for use by the designer as the base form. CreateDesignForm - Create a descendent of TCustomForm for use by the designer as the instance to design } ICustomDesignForm = interface ['{787195AF-C234-49DC-881B-221B69C0137A}'] procedure CreateDesignerForm(const Designer: IDesigner; Root: TComponent; out DesignForm: TCustomForm; out ComponentContainer: TWinControl); deprecated; end; ICustomDesignForm80 = interface ['{525A1DF8-5EF3-4B98-8EE3-4567910A7EA1}'] procedure CreateDesignerForm(const Designer: IDesigner; Root: TComponent; out DesignForm: IHostForm; out ComponentContainer: TWinControl); end; TControlGuidelines = class(TComponentGuidelines) private FClientDelta: TRect; FBoundsRect: TRect; protected procedure CalcClientDelta(Force: Boolean = True); function CalcHorzPos(APos: Integer): Integer; override; function CalcVertPos(APos: Integer): Integer; override; function GetCount: Integer; override; function GetDesignerGuideType(Index: Integer): TDesignerGuideType; override; function GetDesignerGuideOffset(Index: Integer): Integer; override; function GetCtl3D: Boolean; virtual; public procedure Initialize(AComponent: TComponent; AContainer: TComponent); override; class function GetTextBaseline(AControl: TControl; Align: TTextLayout): Integer; static; end; TWinControlGuidelines = class(TControlGuidelines) private FCountDelta: Integer; protected function GetControlPadding: TPadding; virtual; function GetCount: Integer; override; function GetDesignerGuideType(Index: Integer): TDesignerGuideType; override; function GetDesignerGuideOffset(Index: Integer): Integer; override; public procedure Initialize(AComponent: TComponent; AContainer: TComponent); override; end; TCustomFormGuidelines = class(TWinControlGuidelines) private FCustomPadding: TPadding; protected function GetControlPadding: TPadding; override; public destructor Destroy; override; end; { Clipboard utility functions } const cfDelphiComponents = 'Delphi Components'; cfDelphiComponent = 'Delphi Component'; var CF_COMPONENTS: Word; CF_COMPONENT: Word; procedure CopyStreamToClipboard(S: TMemoryStream); function GetClipboardStream: TMemoryStream; { EditAction utility functions } function EditActionFor(AEditControl: TCustomEdit; Action: TEditAction): Boolean; function GetEditStateFor(AEditControl: TCustomEdit): TEditState; { Registry Information } var BaseRegistryKey: string = ''; { Spacing Information } var PropertyDrawingOffset: Integer = 8; //{ Action Registration } // //type // // TNotifyActionListChange = procedure; // //var // NotifyActionListChange: TNotifyActionListChange = nil; // //procedure RegActions(const ACategory: string; // const AClasses: array of TBasicActionClass; AResource: TComponentClass); //procedure UnRegActions(const Classes: array of TBasicActionClass); //procedure EnumActions(Proc: TEnumActionProc; Info: Pointer); //function CreateAction(AOwner: TComponent; ActionClass: TBasicActionClass): TBasicAction; procedure DrawCheckbox(ACanvas: TCanvas; ARect : TRect; ASelected, AEnabled, AAllEqual, AValue: Boolean); implementation uses Vcl.Consts, System.RTLConsts, System.SysUtils, System.Math, System.Win.Registry, System.TypInfo, Vcl.Clipbrd, Vcl.ImgList, Winapi.CommCtrl, Vcl.Themes, System.Generics.Collections, DsnConst, Winapi.UxTheme, Vcl.GraphUtil, DesignConst, ComponentDesigner, BrandingAPI; //{ Registry Information } // //type // // TBasicActionRecord = record // ActionClass: TBasicActionClass; // GroupId: Integer; // end; // // TActionClassArray = array of TBasicActionRecord; // // TActionClassesEntry = record // Category: string; // Actions: TActionClassArray; // Resource: TComponentClass; // end; // // TActionClassesArray = array of TActionClassesEntry; // // TActionResourceCache = class // private // type // TResourceCache = TDictionary<TComponentClass, TComponent>; // class var FCache: TResourceCache; // public // class constructor Create; // class destructor Destroy; // class procedure Add(ComponentClass: TComponentClass; Instance: TComponent); // class procedure Clear; // class function GetInstance(ComponentClass: TComponentClass): TComponent; // class procedure Remove(ComponentClass: TComponentClass); // end; // //var // DesignersList: TList = nil; // ActionClasses: TActionClassesArray = nil; //{ Action Registration } // //type // THackAction = class(TCustomAction); // //procedure RegActions(const ACategory: string; // const AClasses: array of TBasicActionClass; AResource: TComponentClass); //var // CategoryIndex, Len, I, J, NewClassCount: Integer; // NewClasses: array of TBasicActionClass; // Skip: Boolean; // S: string; // lClasses: array of TContainedActionClass; // //begin // for I := Low(AClasses) to High(AClasses) do // if (AClasses[I] <> nil) and (AClasses[I].InheritsFrom(TContainedAction)) then // begin // SetLength(lClasses, Length(lClasses) + 1); // lClasses[Length(lClasses) - 1] := TContainedActionClass(AClasses[I]); // end; // RegisteredActions.RegisterActions(ACategory, lClasses, AResource); // // // Remove resource from cache if it's there // if TActionResourceCache.GetInstance(AResource) <> nil then // TActionResourceCache.Remove(AResource); // // { Determine whether we're adding a new category, or adding to an existing one } // CategoryIndex := -1; // for I := Low(ActionClasses) to High(ActionClasses) do // if CompareText(ActionClasses[I].Category, ACategory) = 0 then // begin // CategoryIndex := I; // Break; // end; // // { Adding a new category } // if CategoryIndex = -1 then // begin // CategoryIndex := Length(ActionClasses); // SetLength(ActionClasses, CategoryIndex + 1); // end; // // with ActionClasses[CategoryIndex] do // begin // SetLength(NewClasses, Length(AClasses)); // { Remove duplicate classes } // NewClassCount := 0; // for I := Low(AClasses) to High(AClasses) do // begin // Skip := False; // for J := Low(Actions) to High(Actions) do // if AClasses[I] = Actions[J].ActionClass then // begin // Skip := True; // Break; // end; // if not Skip then // begin // NewClasses[Low(NewClasses) + NewClassCount] := AClasses[I]; // Inc(NewClassCount); // end; // end; // // { Pack NewClasses } // SetLength(NewClasses, NewClassCount); // // SetString(S, PChar(ACategory), Length(ACategory)); // Category := S; // Resource := AResource; // Len := Length(Actions); // SetLength(Actions, Len + Length(NewClasses)); // for I := Low(NewClasses) to High(NewClasses) do // begin // RegisterNoIcon([NewClasses[I]]); // System.Classes.RegisterClass(NewClasses[I]); // with Actions[Len + I] do // begin // ActionClass := NewClasses[I]; // GroupId := CurrentGroup; // end; // end; // end; // { Notify all available designers of new TAction class } // if (DesignersList <> nil) and Assigned(NotifyActionListChange) then // NotifyActionListChange; //end; // //procedure UnRegActions(const Classes: array of TBasicActionClass);//! far; //var // I, J, K: Integer; // LActionClass: TBasicActionClass; // lClasses: array of TContainedActionClass; // //begin // for I := Low(Classes) to High(Classes) do // if (Classes[I] <> nil) and (Classes[I].InheritsFrom(TContainedAction)) then // begin // SetLength(lClasses, Length(lClasses) + 1); // lClasses[Length(lClasses) - 1] := TContainedActionClass(Classes[I]); // end; // RegisteredActions.UnregisterActions(lClasses); // // // Clear the resource cache // TActionResourceCache.Clear; // // for I := Low(Classes) to High(Classes) do // begin // LActionClass := Classes[I]; // for J := Low(ActionClasses) to High(ActionClasses) do // for K := Low(ActionClasses[J].Actions) to High(ActionClasses[J].Actions) do // with ActionClasses[J].Actions[K] do // if LActionClass = ActionClass then // begin // ActionClass := nil; // GroupId := -1; // end; // end; // if Assigned(NotifyActionListChange) then // NotifyActionListChange; //end; // //procedure UnregisterActionGroup(AGroupId: Integer); //var // I, J: Integer; //begin // for I := Low(ActionClasses) to High(ActionClasses) do // for J := Low(ActionClasses[I].Actions) to High(ActionClasses[I].Actions) do // with ActionClasses[I].Actions[J] do // if GroupId = AGroupId then // begin // ActionClass := nil; // GroupId := -1; // end; // if Assigned(NotifyActionListChange) then // NotifyActionListChange; //end; // //procedure EnumActions(Proc: TEnumActionProc; Info: Pointer); //var // I, J, Count: Integer; // ActionClass: TBasicActionClass; //begin // if ActionClasses <> nil then // for I := Low(ActionClasses) to High(ActionClasses) do // begin // Count := 0; // for J := Low(ActionClasses[I].Actions) to High(ActionClasses[I].Actions) do // begin // ActionClass := ActionClasses[I].Actions[J].ActionClass; // if ActionClass = nil then // Continue; // Proc(ActionClasses[I].Category, ActionClass, Info); // Inc(Count); // end; // if Count = 0 then // SetLength(ActionClasses[I].Actions, 0); // end; //end; // //function CreateAction(AOwner: TComponent; ActionClass: TBasicActionClass): TBasicAction; //var // I, J: Integer; // Res: TComponentClass; // Instance: TComponent; // Action: TBasicAction; // // function FindComponentByClass(AOwner: TComponent; const AClassName: string): TComponent; // var // I: Integer; // begin // if (AClassName <> '') and (AOwner.ComponentCount > 0) then // for I := 0 to AOwner.ComponentCount - 1 do // begin // Result := AOwner.Components[I]; // if CompareText(Result.ClassName, AClassName) = 0 then Exit; // end; // Result := nil; // end; // // procedure CreateMaskedBmp(ImageList: TCustomImageList; ImageIndex: Integer; // var Image, Mask: Vcl.Graphics.TBitmap); // begin // Image := Vcl.Graphics.TBitmap.Create; // Mask := Vcl.Graphics.TBitmap.Create; // try // with Image do // begin // Height := ImageList.Height; // Width := ImageList.Width; // end; // with Mask do // begin // Monochrome := True; // Height := ImageList.Height; // Width := ImageList.Width; // end; // ImageList_Draw(ImageList.Handle, ImageIndex, Image.Canvas.Handle, 0, 0, ILD_NORMAL); // ImageList_Draw(ImageList.Handle, ImageIndex, Mask.Canvas.Handle, 0, 0, ILD_MASK); ////! Result.MaskHandle := Mask.ReleaseHandle; // except // Image.Free; // Mask.Free; // Image := nil; // Mask := nil; // raise; // end; // end; // //begin // Result := ActionClass.Create(AOwner); // { Attempt to find the first action with the same class Type as ActionClass in // the Resource component's resource stream, and use its property values as // our defaults. } // Res := nil; // for I := Low(ActionClasses) to High(ActionClasses) do // with ActionClasses[I] do // for J := Low(Actions) to High(Actions) do // if Actions[J].ActionClass = ActionClass then // begin // Res := Resource; // Break; // end; // if Res <> nil then // begin // // Look for this resource in the cache // Instance := TActionResourceCache.GetInstance(Res); // if Instance = nil then // begin // // Not found, create it and add it // Instance := Res.Create(nil); // TActionResourceCache.Add(Res, Instance); // end; // // Action := FindComponentByClass(Instance, ActionClass.ClassName) as TBasicAction; // if Action <> nil then // begin // with Action as TCustomAction do // begin // TCustomAction(Result).Caption := Caption; // TCustomAction(Result).Checked := Checked; // TCustomAction(Result).Enabled := Enabled; // TCustomAction(Result).HelpContext := HelpContext; // TCustomAction(Result).Hint := Hint; // TCustomAction(Result).ImageIndex := ImageIndex; // TCustomAction(Result).ShortCut := ShortCut; // TCustomAction(Result).Visible := Visible; // if (ImageIndex > -1) and (ActionList <> nil) and // (ActionList.Images <> nil) then // begin // THackAction(Result).FImage.Free; // THackAction(Result).FMask.Free; // CreateMaskedBmp(ActionList.Images, ImageIndex, // Vcl.Graphics.TBitmap(THackAction(Result).FImage), // Vcl.Graphics.TBitmap(THackAction(Result).FMask)); // end; // end; // end; // end; //end; const { context ids for the Font editor and the Color Editor, etc. } hcDFontEditor = 25000; hcDColorEditor = 25010; hcDMediaPlayerOpen = 25020; function GetDisplayValue(const Prop: IProperty): string; begin Result := ''; if Assigned(Prop) and Prop.AllEqual then Result := Prop.GetValue; end; procedure DefaultPropertyDrawName(Prop: TPropertyEditor; Canvas: TCanvas; const Rect: TRect; Spacing : Integer = 0); begin Canvas.TextRect(Rect, Rect.Left + 2 + Spacing, Rect.Top + 1, Prop.GetName); end; procedure DefaultPropertyDrawValue(Prop: TPropertyEditor; Canvas: TCanvas; const Rect: TRect; Spacing : Integer = 0); begin Canvas.TextRect(Rect, Rect.Left + 1 + Spacing, Rect.Top + 1, Prop.GetVisualValue); end; procedure DefaultPropertyListDrawValue(const Value: string; Canvas: TCanvas; const Rect: TRect; Selected: Boolean; Spacing : Integer = 0); begin Canvas.TextRect(Rect, Rect.Left + 1 + Spacing, Rect.Top + 1, Value); end; // Copy from IDEWideGraphics type TCanvasClass = Class(TCanvas); function TextExtentW(Canvas: TCanvas; const Text: Widestring): TSize; begin with TCanvasClass(Canvas) do begin Changing; RequiredState([csHandleValid, csFontValid]); Result.cX := 0; Result.cY := 0; Winapi.Windows.GetTextExtentPoint32W(Handle, PWideChar(Text), Length(Text), Result); Changed; end; end; function TextWidthW(Canvas: TCanvas; const Text: Widestring): Integer; inline; begin Result := TextExtentW(Canvas, Text).cX; end; procedure TextRectW(Canvas: TCanvas; Rect: TRect; X, Y: Integer; const Text: WideString); var Options: Longint; begin with TCanvasClass(Canvas) do begin Changing; RequiredState([csHandleValid, csFontValid, csBrushValid]); Options := ETO_CLIPPED or TextFlags; if Brush.Style <> bsClear then Options := Options or ETO_OPAQUE; if ((TextFlags and ETO_RTLREADING) <> 0) and (CanvasOrientation = coRightToLeft) then Inc(X, TextWidthW(Canvas, Text) + 1); Winapi.Windows.ExtTextOutW(Handle, X, Y, Options, @Rect, PWideChar(Text), Length(Text), nil); Changed; end; end; procedure DefaultPropertyListDrawValue(const Value: WideString; Canvas: TCanvas; const Rect: TRect; Selected: Boolean; Spacing : Integer = 0); begin TextRectW(Canvas, Rect, Rect.Left + 1 + Spacing, Rect.Top + 1, Value); end; { TFontNameProperty } { Owner draw code has been commented out, see the interface section's for info. } function TFontNameProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList, paRevertable]; end; procedure TFontNameProperty.GetValues(Proc: TGetStrProc); var I: Integer; begin for I := 0 to Screen.Fonts.Count - 1 do Proc(Screen.Fonts[I]); end; procedure TFontNameProperty.ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); var OldFontName: string; begin if FontNamePropertyDisplayFontNames then with ACanvas do begin // save off things OldFontName := Font.Name; // set things up and do work Font.Name := Value; TextRect(ARect, ARect.Left + 2 + PropertyDrawingOffset, ARect.Top + 1, Value); // restore things Font.Name := OldFontName; end else DefaultPropertyListDrawValue(Value, ACanvas, ARect, ASelected, PropertyDrawingOffset); end; procedure TFontNameProperty.ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); var OldFontName: string; begin if FontNamePropertyDisplayFontNames then with ACanvas do begin // save off things OldFontName := Font.Name; // set things up and do work Font.Name := Value; AHeight := TextHeight(Value) + 2; // restore things Font.Name := OldFontName; end; end; procedure TFontNameProperty.ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); var OldFontName: string; begin if FontNamePropertyDisplayFontNames then with ACanvas do begin // save off things OldFontName := Font.Name; // set things up and do work Font.Name := Value; AWidth := TextWidth(Value) + 4; // restore things Font.Name := OldFontName; end; end; { TFontCharsetProperty } function TFontCharsetProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paSortList, paValueList]; end; function TFontCharsetProperty.GetValue: string; begin if not CharsetToIdent(TFontCharset(GetOrdValue), Result) then FmtStr(Result, '%d', [GetOrdValue]); end; procedure TFontCharsetProperty.GetValues(Proc: TGetStrProc); begin GetCharsetValues(Proc); end; procedure TFontCharsetProperty.SetValue(const Value: string); var NewValue: Longint; begin if IdentToCharset(Value, NewValue) then SetOrdValue(NewValue) else inherited SetValue(Value); end; { TImeNameProperty } function TImeNameProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList, paSortList, paMultiSelect]; end; procedure TImeNameProperty.GetValues(Proc: TGetStrProc); var I: Integer; begin for I := 0 to Screen.Imes.Count - 1 do Proc(Screen.Imes[I]); end; { TFileNameProperty } procedure TFileNameProperty.GetDialogOptions(Dialog: TOpenDialog); begin Dialog.Filter := SAllFiles; Dialog.Options := Dialog.Options + [ofFileMustExist]; end; procedure TFileNameProperty.Edit; var OpenDialog: TOpenDialog; begin OpenDialog := TOpenDialog.Create(nil); try GetDialogOptions(OpenDialog); if OpenDialog.Execute then SetValue(OpenDialog.FileName); finally OpenDialog.Free; end; end; function TFileNameProperty.GetAttributes: TPropertyAttributes; begin Result := [paRevertable, paDialog, paMultiSelect]; end; { TMPFilenameProperty } procedure TMPFilenameProperty.Edit; var MPFileOpen: TOpenDialog; begin MPFileOpen := TOpenDialog.Create(Application); MPFileOpen.Filename := GetValue; MPFileOpen.Filter := SMPOpenFilter; MPFileOpen.HelpContext := hcDMediaPlayerOpen; MPFileOpen.Options := MPFileOpen.Options + [ofShowHelp, ofPathMustExist, ofFileMustExist]; try if MPFileOpen.Execute then SetValue(string(MPFileOpen.Filename)); finally MPFileOpen.Free; end; end; function TMPFilenameProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paRevertable]; end; { TColorProperty } procedure TColorProperty.Edit; var ColorDialog: TColorDialog; IniFile: TRegIniFile; procedure GetCustomColors; begin if BaseRegistryKey = '' then Exit; IniFile := TRegIniFile.Create(BaseRegistryKey); try IniFile.ReadSectionValues(SCustomColors, ColorDialog.CustomColors); except { Ignore errors reading values } end; end; procedure SaveCustomColors; var I, P: Integer; S: string; begin if IniFile <> nil then with ColorDialog do for I := 0 to CustomColors.Count - 1 do begin S := CustomColors.Strings[I]; P := Pos('=', S); if P <> 0 then begin S := Copy(S, 1, P - 1); IniFile.WriteString(SCustomColors, S, CustomColors.Values[S]); end; end; end; begin IniFile := nil; ColorDialog := TColorDialog.Create(Application); try GetCustomColors; ColorDialog.Color := GetOrdValue; ColorDialog.HelpContext := hcDColorEditor; ColorDialog.Options := [cdShowHelp]; if ColorDialog.Execute then SetOrdValue(ColorDialog.Color); SaveCustomColors; finally IniFile.Free; ColorDialog.Free; end; end; function TColorProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paDialog, paValueList, paRevertable]; end; function TColorProperty.GetValue: string; begin Result := ColorToString(TColor(GetOrdValue)); end; procedure TColorProperty.GetValues(Proc: TGetStrProc); begin GetColorValues(Proc); end; procedure TColorProperty.PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); begin if GetVisualValue <> '' then PaintColorBox(GetVisualValue, ACanvas, ARect, ASelected) // ListDrawValue(GetVisualValue, ACanvas, ARect, True{ASelected}) else DefaultPropertyDrawValue(Self, ACanvas, ARect); end; procedure TColorProperty.ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); var ValueRect: TRect; begin ValueRect := PaintColorBox(Value, ACanvas, Rect(ARect.Left + PropertyDrawingOffset, ARect.Top, ARect.Right, ARect.Bottom), ASelected); DefaultPropertyListDrawValue(Value, ACanvas, ValueRect, ASelected); end; procedure TColorProperty.ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); begin AWidth := AWidth + ACanvas.TextHeight('M') {* 2}; end; procedure TColorProperty.SetValue(const Value: string); var NewValue: Longint; begin if IdentToColor(Value, NewValue) then SetOrdValue(NewValue) else inherited SetValue(Value); end; procedure TColorProperty.ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); begin // No implemenation necessary end; procedure TColorProperty.PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); begin DefaultPropertyDrawName(Self, ACanvas, ARect); end; function TColorProperty.PropDrawNameRect(const ARect: TRect): TRect; begin Result := ARect; end; function TColorProperty.PropDrawValueRect(const ARect: TRect): TRect; begin Result := Rect(ARect.Left, ARect.Top, (ARect.Bottom - ARect.Top) + ARect.Left, ARect.Bottom); end; function TColorProperty.PaintColorBox(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean): TRect; function ColorToBorderColor(AColor: TColor): TColor; type TColorQuad = record Red, Green, Blue, Alpha: Byte; end; begin if (TColorQuad(AColor).Red > 192) or (TColorQuad(AColor).Green > 192) or (TColorQuad(AColor).Blue > 192) then Result := clBlack else if ASelected then Result := clWhite else Result := AColor; end; var Right: Integer; OldPenColor, OldBrushColor: TColor; begin Right := (ARect.Bottom - ARect.Top) {* 2} + ARect.Left; with ACanvas do begin // save off things OldPenColor := Pen.Color; OldBrushColor := Brush.Color; // frame things Pen.Color := Brush.Color; Rectangle(ARect.Left, ARect.Top, Right, ARect.Bottom); // set things up and do the work Brush.Color := StringToColor(Value); Pen.Color := ColorToBorderColor(ColorToRGB(Brush.Color)); Rectangle(ARect.Left + 1, ARect.Top + 1, Right - 1, ARect.Bottom - 1); // restore the things we twiddled with Brush.Color := OldBrushColor; Pen.Color := OldPenColor; Result := Rect(Right, ARect.Top, ARect.Right, ARect.Bottom); { DefaultPropertyListDrawValue(Value, ACanvas, Rect(Right, ARect.Top, ARect.Right, ARect.Bottom), ASelected);} end; end; { TBrushStyleProperty } procedure TBrushStyleProperty.PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); begin if GetVisualValue <> '' then ListDrawValue(GetVisualValue, ACanvas, ARect, ASelected) else DefaultPropertyDrawValue(Self, ACanvas, ARect); end; procedure TBrushStyleProperty.ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); var Right: Integer; OldPenColor, OldBrushColor: TColor; OldBrushStyle: TBrushStyle; begin Right := (ARect.Bottom - ARect.Top) {* 2} + ARect.Left; with ACanvas do begin // save off things OldPenColor := Pen.Color; OldBrushColor := Brush.Color; OldBrushStyle := Brush.Style; // frame things Pen.Color := Brush.Color; Brush.Color := clWindow; Rectangle(ARect.Left, ARect.Top, Right, ARect.Bottom); // set things up Pen.Color := clWindowText; Brush.Style := TBrushStyle(GetEnumValue(GetPropInfo^.PropType^, Value)); // bsClear hack if Brush.Style = bsClear then begin Brush.Color := clWindow; Brush.Style := bsSolid; end else Brush.Color := clWindowText; // ok on with the show Rectangle(ARect.Left + 1, ARect.Top + 1, Right - 1, ARect.Bottom - 1); // restore the things we twiddled with Brush.Color := OldBrushColor; Brush.Style := OldBrushStyle; Pen.Color := OldPenColor; DefaultPropertyListDrawValue(Value, ACanvas, Rect(Right, ARect.Top, ARect.Right, ARect.Bottom), ASelected); end; end; procedure TBrushStyleProperty.ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); begin AWidth := AWidth + ACanvas.TextHeight('A') {* 2}; end; procedure TBrushStyleProperty.ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); begin // No implementation necessary end; procedure TBrushStyleProperty.PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); begin DefaultPropertyDrawName(Self, ACanvas, ARect); end; { TPenStyleProperty } procedure TPenStyleProperty.GetValues(Proc: TGetStrProc); var LStyle: TPenStyle; EnumType: PTypeInfo; begin EnumType := GetPropType; for LStyle := Low(TPenStyle) to High(TPenStyle) do if (LStyle <> psUserStyle) and (LStyle <> psAlternate) then Proc(GetEnumName(EnumType, Integer(LStyle))); end; procedure TPenStyleProperty.PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); begin if GetVisualValue <> '' then ListDrawValue(GetVisualValue, ACanvas, ARect, ASelected) else DefaultPropertyDrawValue(Self, ACanvas, ARect); end; procedure TPenStyleProperty.ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); var Right, Top: Integer; OldPenColor, OldBrushColor: TColor; OldPenStyle: TPenStyle; begin Right := (ARect.Bottom - ARect.Top) * 2 + ARect.Left; Top := (ARect.Bottom - ARect.Top) div 2 + ARect.Top; with ACanvas do begin // save off things OldPenColor := Pen.Color; OldBrushColor := Brush.Color; OldPenStyle := Pen.Style; // frame things Pen.Color := Brush.Color; Rectangle(ARect.Left, ARect.Top, Right, ARect.Bottom); // white out the background Pen.Color := clWindowText; Brush.Color := clWindow; Rectangle(ARect.Left + 1, ARect.Top + 1, Right - 1, ARect.Bottom - 1); // set thing up and do work Pen.Color := clWindowText; Pen.Style := TPenStyle(GetEnumValue(GetPropInfo^.PropType^, Value)); MoveTo(ARect.Left + 1, Top); LineTo(Right - 1, Top); MoveTo(ARect.Left + 1, Top + 1); LineTo(Right - 1, Top + 1); // restore the things we twiddled with Brush.Color := OldBrushColor; Pen.Style := OldPenStyle; Pen.Color := OldPenColor; DefaultPropertyListDrawValue(Value, ACanvas, Rect(Right, ARect.Top, ARect.Right, ARect.Bottom), ASelected); end; end; procedure TPenStyleProperty.ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); begin AWidth := AWidth + ACanvas.TextHeight('X') * 2; end; procedure TPenStyleProperty.ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); begin // No implementation necessary end; procedure TPenStyleProperty.PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); begin DefaultPropertyDrawName(Self, ACanvas, ARect); end; { TCursorProperty } function TCursorProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList, paRevertable]; end; function TCursorProperty.GetValue: string; begin Result := CursorToString(TCursor(GetOrdValue)); end; procedure TCursorProperty.GetValues(Proc: TGetStrProc); begin GetCursorValues(Proc); end; procedure TCursorProperty.SetValue(const Value: string); var NewValue: Longint; begin if IdentToCursor(Value, NewValue) then SetOrdValue(NewValue) else inherited SetValue(Value); end; procedure TCursorProperty.ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); var Right: Integer; CursorIndex: Integer; CursorHandle: THandle; begin Right := ARect.Left + GetSystemMetrics(SM_CXCURSOR) + 4; with ACanvas do begin if not IdentToCursor(Value, CursorIndex) then CursorIndex := StrToInt(Value); ACanvas.FillRect(ARect); CursorHandle := Screen.Cursors[CursorIndex]; if CursorHandle <> 0 then DrawIconEx(ACanvas.Handle, ARect.Left + 2 + PropertyDrawingOffset, ARect.Top + 2, CursorHandle, 0, 0, 0, 0, DI_NORMAL or DI_DEFAULTSIZE); DefaultPropertyListDrawValue(Value, ACanvas, Rect(Right, ARect.Top, ARect.Right, ARect.Bottom), ASelected, PropertyDrawingOffset); end; end; procedure TCursorProperty.ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); begin AWidth := AWidth + GetSystemMetrics(SM_CXCURSOR) + 4; end; procedure TCursorProperty.ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); begin AHeight := Max(ACanvas.TextHeight('Wg'), GetSystemMetrics(SM_CYCURSOR) + 4); end; { TFontProperty } procedure TFontProperty.Edit; var FontDialog: TFontDialog; begin FontDialog := TFontDialog.Create(Application); try FontDialog.Font := TFont(GetOrdValue); FontDialog.HelpContext := hcDFontEditor; FontDialog.Options := FontDialog.Options + [fdShowHelp, fdForceFontExist]; if FontDialog.Execute then SetOrdValue(Longint(FontDialog.Font)); finally FontDialog.Free; end; end; function TFontProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paSubProperties, paDialog, paReadOnly]; end; { TModalResultProperty } const ModalResults: array[mrNone..mrYesToAll] of string = ( 'mrNone', 'mrOk', 'mrCancel', 'mrAbort', 'mrRetry', 'mrIgnore', 'mrYes', 'mrNo', 'mrClose', 'mrHelp', 'mrTryAgain', 'mrContinue', 'mrAll', 'mrNoToAll', 'mrYesToAll'); function TModalResultProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paRevertable]; end; function TModalResultProperty.GetValue: string; var CurValue: Longint; begin CurValue := GetOrdValue; case CurValue of Low(ModalResults)..High(ModalResults): Result := ModalResults[CurValue]; else Result := IntToStr(CurValue); end; end; procedure TModalResultProperty.GetValues(Proc: TGetStrProc); var I: Integer; begin for I := Low(ModalResults) to High(ModalResults) do Proc(ModalResults[I]); end; procedure TModalResultProperty.SetValue(const Value: string); var I: Integer; begin if Value = '' then begin SetOrdValue(0); Exit; end; for I := Low(ModalResults) to High(ModalResults) do if CompareText(ModalResults[I], Value) = 0 then begin SetOrdValue(I); Exit; end; inherited SetValue(Value); end; { TShortCutProperty } const ShortCuts: array[0..108] of TShortCut = ( scNone, Byte('A') or scCtrl, Byte('B') or scCtrl, Byte('C') or scCtrl, Byte('D') or scCtrl, Byte('E') or scCtrl, Byte('F') or scCtrl, Byte('G') or scCtrl, Byte('H') or scCtrl, Byte('I') or scCtrl, Byte('J') or scCtrl, Byte('K') or scCtrl, Byte('L') or scCtrl, Byte('M') or scCtrl, Byte('N') or scCtrl, Byte('O') or scCtrl, Byte('P') or scCtrl, Byte('Q') or scCtrl, Byte('R') or scCtrl, Byte('S') or scCtrl, Byte('T') or scCtrl, Byte('U') or scCtrl, Byte('V') or scCtrl, Byte('W') or scCtrl, Byte('X') or scCtrl, Byte('Y') or scCtrl, Byte('Z') or scCtrl, Byte('A') or scCtrl or scAlt, Byte('B') or scCtrl or scAlt, Byte('C') or scCtrl or scAlt, Byte('D') or scCtrl or scAlt, Byte('E') or scCtrl or scAlt, Byte('F') or scCtrl or scAlt, Byte('G') or scCtrl or scAlt, Byte('H') or scCtrl or scAlt, Byte('I') or scCtrl or scAlt, Byte('J') or scCtrl or scAlt, Byte('K') or scCtrl or scAlt, Byte('L') or scCtrl or scAlt, Byte('M') or scCtrl or scAlt, Byte('N') or scCtrl or scAlt, Byte('O') or scCtrl or scAlt, Byte('P') or scCtrl or scAlt, Byte('Q') or scCtrl or scAlt, Byte('R') or scCtrl or scAlt, Byte('S') or scCtrl or scAlt, Byte('T') or scCtrl or scAlt, Byte('U') or scCtrl or scAlt, Byte('V') or scCtrl or scAlt, Byte('W') or scCtrl or scAlt, Byte('X') or scCtrl or scAlt, Byte('Y') or scCtrl or scAlt, Byte('Z') or scCtrl or scAlt, VK_F1, VK_F2, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10, VK_F11, VK_F12, VK_F1 or scCtrl, VK_F2 or scCtrl, VK_F3 or scCtrl, VK_F4 or scCtrl, VK_F5 or scCtrl, VK_F6 or scCtrl, VK_F7 or scCtrl, VK_F8 or scCtrl, VK_F9 or scCtrl, VK_F10 or scCtrl, VK_F11 or scCtrl, VK_F12 or scCtrl, VK_F1 or scShift, VK_F2 or scShift, VK_F3 or scShift, VK_F4 or scShift, VK_F5 or scShift, VK_F6 or scShift, VK_F7 or scShift, VK_F8 or scShift, VK_F9 or scShift, VK_F10 or scShift, VK_F11 or scShift, VK_F12 or scShift, VK_F1 or scShift or scCtrl, VK_F2 or scShift or scCtrl, VK_F3 or scShift or scCtrl, VK_F4 or scShift or scCtrl, VK_F5 or scShift or scCtrl, VK_F6 or scShift or scCtrl, VK_F7 or scShift or scCtrl, VK_F8 or scShift or scCtrl, VK_F9 or scShift or scCtrl, VK_F10 or scShift or scCtrl, VK_F11 or scShift or scCtrl, VK_F12 or scShift or scCtrl, VK_INSERT, VK_INSERT or scShift, VK_INSERT or scCtrl, VK_DELETE, VK_DELETE or scShift, VK_DELETE or scCtrl, VK_BACK or scAlt, VK_BACK or scShift or scAlt); function TShortCutProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paRevertable]; end; function TShortCutProperty.GetValue: string; var CurValue: TShortCut; begin CurValue := GetOrdValue; if CurValue = scNone then Result := srNone else Result := ShortCutToText(CurValue); end; procedure TShortCutProperty.GetValues(Proc: TGetStrProc); var I: Integer; begin Proc(srNone); for I := 1 to High(ShortCuts) do Proc(ShortCutToText(ShortCuts[I])); end; procedure TShortCutProperty.SetValue(const Value: string); var NewValue: TShortCut; begin NewValue := 0; if (Value <> '') and (AnsiCompareText(Value, srNone) <> 0) then begin NewValue := TextToShortCut(Value); if NewValue = 0 then raise EDesignPropertyError.CreateRes(@SInvalidPropertyValue); end; SetOrdValue(NewValue); end; { TTabOrderProperty } function TTabOrderProperty.GetAttributes: TPropertyAttributes; begin Result := []; end; { TCaptionProperty } function TCaptionProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paAutoUpdate, paRevertable]; end; { TBooleanProperty } procedure DrawCheckbox(ACanvas: TCanvas; ARect : TRect; ASelected, AEnabled, AAllEqual, AValue: Boolean); const ThemeStyles : array[TCheckBoxState] of array[Boolean] of TThemedButton = (( tbCheckBoxUncheckedDisabled, tbCheckBoxUnCheckedNormal ),( tbCheckBoxCheckedDisabled, tbCheckBoxCheckedNormal ),( tbCheckBoxMixedDisabled, tbCheckBoxMixedNormal )); UnThemedStyles : array[TCheckBoxState] of array[Boolean] of Cardinal = (( DFCS_BUTTONCHECK or DFCS_INACTIVE, DFCS_BUTTONCHECK ),( DFCS_CHECKED or DFCS_INACTIVE, DFCS_CHECKED ),( DFCS_BUTTON3STATE or DFCS_INACTIVE, DFCS_BUTTON3STATE )); var State: TCheckBoxState; LStyle: TCustomStyleServices; SaveIndex: Integer; begin if AAllEqual = false then State := cbGrayed else if AValue then State := cbChecked else State := cbUnchecked; if (ThemeProperties <> nil) then LStyle := ThemeProperties.StyleServices else LStyle := StyleServices; if LStyle.Enabled then begin SaveIndex := SaveDC(ACanvas.Handle); try LStyle.DrawElement(ACanvas.Handle, LStyle.GetElementDetails(ThemeStyles[State][AEnabled]), ARect); finally RestoreDC(ACanvas.Handle, SaveIndex); end; end else DrawFrameControl(ACanvas.Handle, ARect, DFC_BUTTON, UnThemedStyles[State][AEnabled]); end; function TBooleanProperty.CBRect(const ItemRect: TRect): TRect; const cBorder = 4; var X, W : Integer; begin X := ItemRect.Right + cBorder; W := ItemRect.Bottom - ItemRect.Top - cBorder; Result := Rect(X, ItemRect.Top, X + W, ItemRect.Bottom); end; procedure TBooleanProperty.PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); begin VCLEditors.DefaultPropertyDrawName(Self, ACanvas, ARect); end; function TBooleanProperty.PropDrawNameRect(const ARect: TRect): TRect; begin Result := ARect; end; procedure TBooleanProperty.PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); begin DrawCheckbox(ACanvas, ARect, ASelected, not (paReadOnly in GetAttributes), AllEqual, Boolean(GetOrdValue())); end; function TBooleanProperty.PropDrawValueRect(const ARect: TRect): TRect; begin Result := Rect(ARect.Left, ARect.Top, (ARect.Bottom - ARect.Top) + ARect.Left, ARect.Bottom); end; procedure TBooleanProperty.HintShow(var HintInfo: THintInfo; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); begin Handled := False; end; procedure TBooleanProperty.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); begin Handled := False; end; procedure TBooleanProperty.MouseMove(Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); begin Handled := False; end; procedure TBooleanProperty.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); begin Handled := False; if (paReadOnly in GetAttributes) or InNameRect then Exit; if PtInRect(CBRect(ItemRect), Point(X, Y)) then begin SetOrdValue(1-GetOrdValue()); Handled := True; end; end; { TSetProperty } procedure TSetProperty.GetProperties(Proc: TGetPropProc); var I: Integer; E: IProperty; begin with GetTypeData(GetTypeData(GetPropType)^.CompType^)^ do for I := MinValue to MaxValue do begin { Fix addref problems by referencing it here } E := TSetElementProperty.Create(Self, I); Proc(E); E := nil; end; end; function SetPropMapper(Obj: TPersistent; PropInfo: PPropInfo): TPropertyEditorClass; begin Result := nil; if PropInfo.PropType^.Kind = tkSet then Result := TSetProperty; end; { TSetElementProperty } function TSetElementProperty.CBRect(const ItemRect: TRect): TRect; begin Result := Rect(ItemRect.Right + 2, ItemRect.Top, itemrect.Right + Itemrect.Bottom - ItemRect.Top + 2, ItemRect.Bottom); end; constructor TSetElementProperty.Create(Parent: TPropertyEditor; AElement: Integer); var MinValue: integer; begin inherited; MinValue := GetTypeData(GetTypeData(GetPropType).CompType^).MinValue; FBit := AElement - MinValue; end; procedure TSetElementProperty.PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); begin VCLEditors.DefaultPropertyDrawName(Self, ACanvas, ARect); end; function TSetElementProperty.PropDrawNameRect(const ARect: TRect): TRect; begin Result := ARect; end; procedure TSetElementProperty.PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); var S: TIntegerSet; begin Integer(S) := GetOrdValue; DrawCheckbox(ACanvas, ARect, ASelected, not (paReadOnly in GetAttributes), AllEqual, FBit in S); end; function TSetElementProperty.PropDrawValueRect(const ARect: TRect): TRect; begin Result := Rect(ARect.Left, ARect.Top, (ARect.Bottom - ARect.Top) + ARect.Left, ARect.Bottom); end; procedure TSetElementProperty.HintShow(var HintInfo: THintInfo; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); begin Handled := False; end; procedure TSetElementProperty.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); begin Handled := False; end; procedure TSetElementProperty.MouseMove(Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); begin Handled := False; end; procedure TSetElementProperty.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer; InNameRect: Boolean; const ItemRect: TRect; var Handled: Boolean); var S: TIntegerSet; begin Handled := False; if paReadOnly in GetAttributes then Exit; if PtInRect(CBRect(ItemRect), Point(x,y)) then begin Integer(S) := GetOrdValue; if FBit in S then Exclude(S, FBit) else Include(S, FBit); SetOrdValue(Integer(S)); Handled := True; end; end; { TDateProperty } destructor TDateProperty.Destroy; begin if FControl <> nil then FControl.Free; inherited; end; function TDateProperty.GetAttributes: TPropertyAttributes; begin Result := inherited + [paCustomDropDown]; end; procedure TDateProperty.Edit(const Host: IPropertyHost; DblClick: Boolean); var R : TRect; Val : Single; begin if FControl = nil then FControl := TMonthCalendar.Create(nil); Fcontrol.OnKeyPress := CalendarKeyPress; FControl.OnDblClick := CalendarDblClick; fcontrol.Align := alNone; FControl.Visible := False; FControl.ParentWindow := GetDesktopWindow; MonthCal_GetMinReqRect(fcontrol.Handle, R); fcontrol.ParentWindow := 0; FControl.Visible := True; FControl.Width := R.Right; FControl.Height := R.Bottom; Val := GetFloatValue; if Val = 0 then FControl.Date := Now else FControl.Date := Val; Fcontrol.Update; FHost := Host; Host.DropDownControl(FControl); end; procedure TDateProperty.CalendarDblClick(Sender: TObject); begin if not FIgnoreDblClick then SetFloatValue(TMonthCalendar(Sender).Date); end; procedure TDateProperty.CalendarKeyPress(Sender: TObject; var Key: Char); begin case key of #27: FHost.CloseDropDown; #13: SetFloatValue(FControl.Date); end; end; { Clipboard routines } procedure CopyStreamToClipboard(S: TMemoryStream); var T: TMemoryStream; I: TValueType; V: Integer; procedure CopyToClipboard(Format: Word; S: TMemoryStream); var Handle: THandle; Mem: Pointer; begin Handle := GlobalAlloc(GMEM_MOVEABLE, S.Size); Mem := GlobalLock(Handle); Move(S.Memory^, Mem^, S.Size); GlobalUnlock(Handle); Clipboard.SetAsHandle(Format, Handle); end; begin Clipboard.Open; try CopyToClipboard(CF_COMPONENTS, S); S.Position := 0; T := TMemoryStream.Create; try repeat S.Read(I, SizeOf(I)); S.Seek(-SizeOf(I), 1); if I = vaNull then Break; ObjectBinaryToText(S, T); until False; V := 0; T.Write(V, 1); CopyToClipboard(CF_TEXT, T); finally T.Free; end; finally Clipboard.Close; end; end; function GetClipboardStream: TMemoryStream; var S, T: TMemoryStream; Handle: THandle; Mem: Pointer; Format: Word; V: TValueType; function AnotherObject(S: TStream): Boolean; var Buffer: array[0..255] of AnsiChar; Position: Integer; begin Position := S.Position; Buffer[S.Read(Buffer, SizeOf(Buffer))-1] := #0; S.Position := Position; Result := PossibleStream(string(Buffer)); end; begin Result := TMemoryStream.Create; try if Clipboard.HasFormat(CF_COMPONENTS) then Format := CF_COMPONENTS else Format := CF_TEXT; Clipboard.Open; try Handle := Clipboard.GetAsHandle(Format); Mem := GlobalLock(Handle); try Result.Write(Mem^, GlobalSize(Handle)); finally GlobalUnlock(Handle); end; finally Clipboard.Close; end; Result.Position := 0; if Format = CF_TEXT then begin S := TMemoryStream.Create; try while AnotherObject(Result) do ObjectTextToBinary(Result, S); V := vaNull; S.Write(V, SizeOf(V)); T := Result; Result := nil; T.Free; except S.Free; raise; end; Result := S; Result.Position := 0; end; except Result.Free; raise; end; end; type TSelectionMessageList = class(TInterfacedObject, ISelectionMessageList) private FList: IInterfaceList; protected procedure Add(AEditor: ISelectionMessage); public constructor Create; function Get(Index: Integer): ISelectionMessage; function GetCount: Integer; property Count: Integer read GetCount; property Items[Index: Integer]: ISelectionMessage read Get; default; end; { TSelectionMessageList } procedure TSelectionMessageList.Add(AEditor: ISelectionMessage); begin FList.Add(AEditor); end; constructor TSelectionMessageList.Create; begin inherited; FList := TInterfaceList.Create; end; function TSelectionMessageList.Get(Index: Integer): ISelectionMessage; begin Result := FList[Index] as ISelectionMessage; end; function TSelectionMessageList.GetCount: Integer; begin Result := FList.Count; end; function SelectionMessageListOf(const SelectionEditorList: ISelectionEditorList): ISelectionMessageList; var SelectionMessage: ISelectionMessage; I: Integer; R: TSelectionMessageList; begin R := TSelectionMessageList.Create; for I := 0 to SelectionEditorList.Count - 1 do if Supports(SelectionEditorList[I], ISelectionMessage, SelectionMessage) then R.Add(SelectionMessage); Result := R; end; { EditAction utility functions } function EditActionFor(AEditControl: TCustomEdit; Action: TEditAction): Boolean; begin Result := True; case Action of eaUndo: AEditControl.Undo; eaCut: AEditControl.CutToClipboard; eaCopy: AEditControl.CopyToClipboard; eaDelete: AEditControl.ClearSelection; eaPaste: AEditControl.PasteFromClipboard; eaSelectAll: AEditControl.SelectAll; else Result := False; end; end; function GetEditStateFor(AEditControl: TCustomEdit): TEditState; begin Result := []; if AEditControl.CanUndo then Include(Result, esCanUndo); if AEditControl.SelLength > 0 then begin Include(Result, esCanCut); Include(Result, esCanCopy); Include(Result, esCanDelete); end; if Clipboard.HasFormat(CF_TEXT) then Include(Result, esCanPaste); if AEditControl.SelLength < Length(AEditControl.Text) then Include(Result, esCanSelectAll); end; { TControlGuidelines } function TControlGuidelines.CalcVertPos(APos: Integer): Integer; var LParent: TWinControl; LPoint: TPoint; begin if Component <> Container then begin LParent := TControl(Component).Parent; LPoint := Point(0, TControl(Component).Top); LPoint := LParent.ClientToScreen(LPoint); LPoint := TControl(Container).ScreenToClient(LPoint); Result := LPoint.Y + APos; end else Result := TControl(Component).Top + APos; end; procedure TControlGuidelines.CalcClientDelta(Force: Boolean = True); var Control: TControl; ClientRect, BoundsRect: TRect; Origin: TPoint; begin if Component = Container then begin Control := TControl(Component); BoundsRect := Control.BoundsRect; if Force or not EqualRect(BoundsRect, FBoundsRect) then begin FBoundsRect := BoundsRect; ClientRect := Control.ClientRect; Origin := Control.ClientOrigin; OffsetRect(ClientRect, Origin.X, Origin.Y); if Control.Parent <> nil then begin BoundsRect.TopLeft := Control.Parent.ClientToScreen(BoundsRect.TopLeft); BoundsRect.BottomRight := Control.Parent.ClientToScreen(BoundsRect.BottomRight); end; FClientDelta.Top := Control.Top + (ClientRect.Top - BoundsRect.Top); FClientDelta.Left := Control.Left + (ClientRect.Left - BoundsRect.Left); FClientDelta.BottomRight := FClientDelta.TopLeft; end; end; end; function TControlGuidelines.CalcHorzPos(APos: Integer): Integer; var LParent: TWinControl; LPoint: TPoint; begin if Component <> Container then begin LParent := TControl(Component).Parent; LPoint := Point(TControl(Component).Left, 0); LPoint := LParent.ClientToScreen(LPoint); LPoint := TControl(Container).ScreenToClient(LPoint); Result := LPoint.X + APos; end else Result := TControl(Component).Left + APos; end; function TControlGuidelines.GetCount: Integer; begin Result := 8; end; function TControlGuidelines.GetCtl3D: Boolean; begin if IsPublishedProp(Component, 'Ctl3D') then // do not localize Result := GetOrdProp(Component, 'Ctl3D') <> 0 // do not localize else Result := True; end; function TControlGuidelines.GetDesignerGuideOffset(Index: Integer): Integer; var Control: TControl; begin Control := TControl(Component); CalcClientDelta(False); case Index of 0: Result := -FClientDelta.Left; 1: Result := -FClientDelta.Top; 2: Result := Control.Width - 1 - FClientDelta.Right; 3: Result := Control.Height - 1 - FClientDelta.Bottom; 4: Result := -Control.Margins.Left - FClientDelta.Left; 5: Result := -Control.Margins.Top - FClientDelta.Top; 6: Result := (Control.Width - FClientDelta.Right) + Control.Margins.Right; 7: Result := (Control.Height - FClientDelta.Bottom) + Control.Margins.Bottom; else Result := 0; TList.Error(SListIndexError, Index); end; end; function TControlGuidelines.GetDesignerGuideType(Index: Integer): TDesignerGuideType; const DesignTypes: array[0..7] of TDesignerGuideType = (gtAlignLeft, gtAlignTop, gtAlignRight, gtAlignBottom, gtMarginLeft, gtMarginTop, gtMarginRight, gtMarginBottom); begin if (Index >= 0) and (Index < GetCount) then Result := DesignTypes[Index] else begin Result := gtAlignLeft; TList.Error(SListIndexError, Index); end; end; type TOpenControl = class(TControl); class function TControlGuidelines.GetTextBaseline(AControl: TControl; Align: TTextLayout): Integer; var Canvas: TControlCanvas; tm: TTextMetric; ClientRect: TRect; Ascent, Height: Integer; begin Canvas := TControlCanvas.Create; try ClientRect := AControl.ClientRect; Canvas.Control := AControl; Canvas.Font := TOpenControl(AControl).Font; GetTextMetrics(Canvas.Handle, tm); Ascent := tm.tmAscent + 1; Height := tm.tmHeight; case Align of tlTop: Result := ClientRect.Top + Ascent; tlCenter: Result := (ClientRect.Top + (ClientRect.Bottom - Height) div 2) + Ascent; tlBottom: Result := (ClientRect.Bottom - Height) + Ascent; else Result := 0; end; finally Canvas.Free; end; end; procedure TControlGuidelines.Initialize(AComponent, AContainer: TComponent); begin inherited Initialize(AComponent, AContainer); CalcClientDelta; end; { TWinControlGuidelines } function TWinControlGuidelines.GetControlPadding: TPadding; begin Result := TWinControl(Component).Padding; end; function TWinControlGuidelines.GetCount: Integer; begin Result := inherited GetCount; Inc(Result, FCountDelta); end; function TWinControlGuidelines.GetDesignerGuideOffset(Index: Integer): Integer; var Control: TWinControl; LRect: TRect; LPos: TPoint; LPadding: TPadding; begin Control := TWinControl(Component); if (FCountDelta > 0) and (Index > 7) and (Index < 12) then begin LRect := Control.ClientRect; LPos := Control.BoundsRect.TopLeft; LPadding := GetControlPadding; if (Component <> Container) and (Control.Parent <> nil) then begin MapWindowPoints(Control.Handle, TWinControl(Container).Handle, LRect, 2); MapWindowPoints(Control.Parent.Handle, TWinControl(Container).Handle, LPos, 1); end; case Index of 8: Result := LRect.Left + LPadding.Left - LPos.X; 9: Result := LRect.Top + LPadding.Top - LPos.Y; 10: Result := LRect.Right - LPadding.Right - LPos.X; 11: Result := LRect.Bottom - LPadding.Bottom - LPos.Y; else Result := 0; end; end else Result := inherited GetDesignerGuideOffset(Index); end; // Since these guide lines are *internal* to the control, we need to reverse their meanings // so that they will match correctly. function TWinControlGuidelines.GetDesignerGuideType(Index: Integer): TDesignerGuideType; begin if (FCountDelta > 0) and (Index > 7) and (Index < 12) then case Index of 8: Result := gtPaddingLeft; 9: Result := gtPaddingTop; 10: Result := gtPaddingRight; 11: Result := gtPaddingBottom; else Result := gtPaddingLeft; end else Result := inherited GetDesignerGuideType(Index); end; procedure TWinControlGuidelines.Initialize(AComponent, AContainer: TComponent); begin inherited Initialize(AComponent, AContainer); if (csAcceptsControls in TWinControl(AComponent).ControlStyle) or (AComponent is TCustomFrame) then FCountDelta := 4; end; { TCustomFormGuidelindes } function TCustomFormGuidelines.GetControlPadding: TPadding; var Form: TWinControl; begin Form := TWinControl(Component); if (Form.Padding.Left = 0) and (Form.Padding.Top = 0) and (Form.Padding.Right = 0) and (Form.Padding.Bottom = 0) then begin if FCustomPadding = nil then begin FCustomPadding := TPadding.Create(Form); FCustomPadding.SetBounds(5, 5, 5, 5); end; Result := FCustomPadding; Exit; end; Result := Form.Padding; end; destructor TCustomFormGuidelines.Destroy; begin FCustomPadding.Free; inherited; end; //{ TActionResourceCache } // //class constructor TActionResourceCache.Create; //begin // FCache := TResourceCache.Create; //end; // //class destructor TActionResourceCache.Destroy; //begin // Clear; // Free stored items // FreeAndNil(FCache); //end; // //class procedure TActionResourceCache.Add(ComponentClass: TComponentClass; Instance: TComponent); //begin // FCache.Add(ComponentClass, Instance); //end; // //class procedure TActionResourceCache.Clear; //var // P: TPair<TComponentClass, TComponent>; //begin // for P in FCache do // if P.Value <> nil then // P.Value.Free; // FCache.Clear; //end; // //class function TActionResourceCache.GetInstance(ComponentClass: TComponentClass): TComponent; //begin // if FCache.ContainsKey(ComponentClass) then // Result := FCache.Items[ComponentClass] // else // Result := nil; //end; // //class procedure TActionResourceCache.Remove(ComponentClass: TComponentClass); //begin // if FCache.ContainsKey(ComponentClass) then // begin // if FCache.Items[ComponentClass] <> nil then // FCache.Items[ComponentClass].Free; // FCache.Remove(ComponentClass); // end; //end; // //{ TActionListView } // //constructor TActionListView.Create(AOwner: TComponent); //begin // inherited; // FImageList := TImageList.Create(nil); // FNewActnPopupMenu := TPopupMenu.Create(nil); // FNewStdActnPopupMenu := TPopupMenu.Create(nil); // FTempStringList := TStringList.Create; // BorderStyle := bsNone; // Columns.Add; // Height := FDefItemHeight; // ReadOnly := True; // RowSelect := True; // ShowColumnHeaders := False; // SmallImages := FImageList; // ViewStyle := vsReport; // Width := 200; //end; // //destructor TActionListView.Destroy; //begin // FreeAndNil(FImageList); // FreeAndNil(FNewActnPopupMenu); // FreeAndNil(FNewStdActnPopupMenu); // FreeAndnil(FTempStringList); // inherited; //end; // //procedure TActionListView.AddStdAction(const Category: string; // ActionClass: TBasicActionClass; Info: Pointer); //var // I: Integer; // LCategory: string; // List: TList<TBasicActionClass>; //begin // if Category <> '' then // LCategory := Category // else // LCategory := SActionCategoryNone; // // I := FStdActionList.IndexOf(LCategory); // if I = -1 then // begin // List := TList<TBasicActionClass>.Create; // List.Add(ActionClass); // FStdActionList.AddObject(LCategory, List); // end // else // begin // List := TList<TBasicActionClass>(FStdActionList.Objects[I]); // List.Add(ActionClass); // end; //end; // //procedure TActionListView.AddTempString(const S: string); //begin // FTempStringList.Add(S); //end; // //procedure TActionListView.Click; //var // P: TPoint; // Item: TListItem; //begin // GetCursorPos(P); // P := ScreenToClient(P); // Item := GetItemAt(P.X, P.Y); // // if Item <> nil then // begin // if Item.Index <= 1 then // begin // if (Item.Index = 0) and (FNewActnPopupMenu.Items.Count = 0) then // begin // if Assigned(FOnNewAction) then // FOnNewAction(Self, '', TAction, FActionList); // end // else // begin // if Item.Index = 0 then // ShowPopupMenu(Item, FNewActnPopupMenu) // else // ShowPopupMenu(Item, FNewStdActnPopupMenu); // end; // end // else // if (Item.Index <> 2) and Assigned(FOnSelectAction) then // FOnSelectAction(Self, TCustomAction(Item.Data)); // end // else // if Assigned(FOnSelectAction) then // FOnSelectAction(Self, nil); //end; // //function TActionListView.CreateMenuItem(const Caption: string; // Event: TNotifyEvent; CustomData: Pointer): TMenuItem; //begin // Result := NewItem(Caption, 0, False, True, Event, 0, ''); // Result.Tag := Integer(CustomData); //end; // //procedure TActionListView.CreateWnd; //begin // inherited; // if Designer.Root <> nil then // RebuildListView; //end; // //function TActionListView.CustomDrawItem(Item: TListItem; // State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; //var // LRect: TRect; //begin // Result := True; // Canvas.Brush.Style := bsClear; // LRect := Item.DisplayRect(drLabel); // // case Stage of // cdPrePaint: // // Draw separator // if Item.Index = 2 then // begin // Canvas.Pen.Color := clSilver; // Canvas.MoveTo(LRect.Left, LRect.Top + (LRect.Bottom - LRect.Top) div 2); // Canvas.LineTo(LRect.Right - LRect.Left, LRect.Top + (LRect.Bottom - LRect.Top) div 2); // Result := False; // Prevent default drawing of highlight bar // end; // cdPostPaint: // // Draw arrow for New Action and New Standard Action items // if ((Item.Index <= 1) and (FNewStdActnPopupMenu.Items.Count > 1)) and // (((Item.Index = 0) and (FNewActnPopupMenu.Items.Count > 1)) or // ((Item.Index = 1) and (FNewStdActnPopupMenu.Items.Count > 1))) then // begin // LRect.Left := LRect.Right - 20; // if ThemeServices.ThemesEnabled and (Win32MajorVersion >= 6) then // DrawThemeBackground(ThemeServices.Theme[teMenu], Canvas.Handle, // MENU_POPUPSUBMENU, MSM_NORMAL, LRect, nil) // else // DrawArrow(Canvas, sdRight, Point(LRect.Right - 15, // LRect.Top + ((LRect.Bottom - LRect.Top - 8) div 2)), 4); // end; // end; //end; // //procedure TActionListView.DoNewActionClick(Sender: TObject); //begin // if Assigned(FOnNewAction) and (Sender is TMenuItem) then // FOnNewAction(Self, '', TAction, TCustomActionList(TMenuItem(Sender).Tag)); //end; // //procedure TActionListView.DoNewStdActionClick(Sender: TObject); //begin // if Assigned(FOnNewAction) and (Sender is TMenuItem) then // FOnNewAction(Self, '', TContainedActionClass(TMenuItem(Sender).Tag), // TCustomActionList(TMenuItem(Sender).Parent.Tag)); //end; // //function TActionListView.IsCustomDrawn(Target: TCustomDrawTarget; // Stage: TCustomDrawStage): Boolean; //begin // Result := (Stage = cdPrePaint) or (Stage = cdPostPaint); //end; // //procedure TActionListView.KeyDown(var Key: Word; Shift: TShiftState); //begin // case Key of // VK_RETURN: // if Assigned(FOnSelectAction) and (Selected <> nil) then // begin // if (Selected.Index = 0) and (FActionList <> nil) and Assigned(FOnNewAction) then // FOnNewAction(Self, '', TAction, FActionList) // else if Selected.Index = 0 then // ShowPopupMenu(Selected, FNewActnPopupMenu) // else if Selected.Index = 1 then // ShowPopupMenu(Selected, FNewStdActnPopupMenu) // else if Selected.Index <> 2 then // FOnSelectAction(Self, TCustomAction(Selected.Data)); // end; // VK_RIGHT: // if Selected <> nil then // begin // if Selected.Index = 0 then // ShowPopupMenu(Selected, FNewActnPopupMenu) // else // ShowPopupMenu(Selected, FNewStdActnPopupMenu); // end; // else // inherited; // end; //end; // //procedure TActionListView.RebuildListView; //var // LRect: TRect; // LIcon: TIcon; // ListItem: TListItem; // LAction: TCustomAction; // I, LWidth, MinWidth: Integer; //begin // // Add actions to listview // if FNewStdActnPopupMenu.Items.Count > 0 then // begin // Items.BeginUpdate; // try // Items.Clear; // FImageList.Clear; // // // Set initial max width // MinWidth := Max(Width, Canvas.TextWidth(SCreateNewStdAction) + 25); // // // Find all actions // FTempStringList.Clear; // Designer.GetComponentNames(GetTypeData(TypeInfo(TCustomAction)), AddTempString); // for I := 0 to FTempStringList.Count - 1 do // begin // LAction := TCustomAction(Designer.GetComponent(FTempStringList[I])); // ListItem := Items.Add; // ListItem.Caption := FTempStringList[I]; // ListItem.Data := LAction; // ListItem.ImageIndex := -1; // LWidth := Canvas.TextWidth(ListItem.Caption); // if (LWidth + 40) > MinWidth then // MinWidth := LWidth + 40; // // if (LAction.ImageIndex <> -1) and (LAction.ActionList <> nil) and // (LAction.ActionList.Images <> nil) then // begin // LIcon := TIcon.Create; // try // LAction.ActionList.Images.GetIcon(LAction.ImageIndex, LIcon); // ListItem.ImageIndex := FImageList.AddIcon(LIcon); // finally // LIcon.Free; // end; // end; // end; // // // Sort list items before adding "special" items // CustomSort(nil, 0); // // // Add "New Action" item // ListItem := Items.Insert(0); // ListItem.Caption := SCreateNewAction; // ListItem.ImageIndex := -1; // // // Add "New Standard Action" item // ListItem := Items.Insert(1); // ListItem.Caption := SCreateNewStdAction; // ListItem.ImageIndex := -1; // // // Add dummy item for divider line // if Items.Count > 2 then // begin // ListItem := Items.Insert(2); // ListItem.ImageIndex := -1; // end; // // finally // Items.EndUpdate; // end; // // // Set Height to fit 14 items // LWidth := 0; // if Items.Count > 14 then // begin // I := 14; // LWidth := GetSystemMetrics(SM_CXVSCROLL); // end // else // I := Items.Count; // LRect := Items[0].DisplayRect(drBounds); // Height := LRect.Bottom * I; // // // Set width to widest + space for icon and gutters (20 pixels each side) // Width := MinWidth + LWidth + FImageList.Width; // Columns[0].Width := Width - LWidth; // end // else // Height := FDefItemHeight; //end; // //procedure TActionListView.RebuildPopupMenus; //var // LName: string; // J, I, K: Integer; // MenuItem, SubItem: TMenuItem; // LActionList: TCustomActionList; // LActionLists: TList<TCustomActionList>; // ActionClassList: TList<TBasicActionClass>; //begin // SmallImages := nil; // MenuItem := nil; // // // Build popup menus // FNewActnPopupMenu.Items.Clear; // FNewStdActnPopupMenu.Items.Clear; // FStdActionList := TStringList.Create; // try // // Gather list of registered action classes // if Assigned(EnumRegisteredActionsProc) then // EnumRegisteredActions(AddStdAction, nil); // // LActionLists := TList<TCustomActionList>.Create; // try // // Build list of ActionLists // FTempStringList.Clear; // Designer.GetComponentNames(GetTypeData(TypeInfo(TCustomActionList)), AddTempString); // for I := 0 to FTempStringList.Count - 1 do // LActionLists.Add(TCustomActionList(Designer.GetComponent(FTempStringList[I]))); // // // If there's just one, save it in FActionList // if LActionLists.Count = 1 then // FActionList := LActionLists[0] // else // FActionList := nil; // // // Build popupmenus for actionlists and standard actions // for LActionList in LActionLists do // begin // // Build a popup menu for each ActionList // if LActionList.Images <> nil then // SmallImages := FImageList; // // // If more than 1 actionlist, add a popupmenu to select // // where the create the action // if LActionLists.Count > 1 then // begin // if LActionList.Owner = Designer.Root then // LName := LActionList.Name // else // LName := LActionList.Owner.Name + DotSep + LActionList.Name; // // MenuItem := CreateMenuItem(LName, DoNewActionClick, LActionList); // FNewActnPopupMenu.Items.Add(MenuItem); // MenuItem := CreateMenuItem(LName, nil, nil); // FNewStdActnPopupMenu.Items.Add(MenuItem); // end; // // // For standard actions popup, add each standard action category // for J := 0 to FStdActionList.Count - 1 do // begin // SubItem := CreateMenuItem(FStdActionList[J], nil, LActionList); // if LActionLists.Count > 1 then // MenuItem.Add(SubItem) // else // FNewStdActnPopupMenu.Items.Add(SubItem); // // // For each category, add each registered action class // ActionClassList := TList<TBasicActionClass>(FStdActionList.Objects[J]); // for K := 0 to ActionClassList.Count - 1 do // SubItem.Add(CreateMenuItem(ActionClassList[K].ClassName, DoNewStdActionClick, ActionClassList[K])); // end; // end; // finally // LActionLists.Free; // end; // // // Free lists of registered action classes // for I := 0 to FStdActionList.Count - 1 do // FStdActionList.Objects[I].Free; // finally // FreeAndNil(FStdActionList); // end; //end; // //procedure TActionListView.SetDesigner(const Value: IDesigner); //begin // if Value <> FDesigner then // begin // FDesigner := Value; // // // Set initial height based on default item height // FTempStringList.Clear; // Designer.GetComponentNames(GetTypeData(TypeInfo(TCustomAction)), AddTempString); // if FTempStringList.Count > 0 then // Height := (Min(FTempStringList.Count, 11) + 3) * FDefItemHeight // else // Height := FDefItemHeight; // // // Rebuild popup menus and listview // RebuildPopupMenus; // if HandleAllocated then // RebuildListView; // end; //end; // //procedure TActionListView.ShowPopupMenu(Item: TListItem; PopupMenu: TPopupMenu); //var // P: TPoint; // LRect: TRect; //begin // LRect := Item.DisplayRect(drBounds); // P := Item.Owner.Owner.ClientToScreen(Point(LRect.Right, LRect.Top)); // PopupMenu.Tag := Integer(Item.Data); // PopupMenu.Popup(P.X, P.Y); //end; // //{ TActionProperty } // //destructor TActionProperty.Destroy; //begin // if FActionListView <> nil then // FreeAndNil(FActionListView); // inherited; //end; // //procedure TActionProperty.CreateNewAction(Sender: TObject; const Category: string; // ActionClass: TContainedActionClass; ActionList: TCustomActionList); //var // LRoot: IRoot; // LCategory: string; // Image, Mask: TBitmap; // NewAction: TContainedAction; //begin // LCategory := Category; // if AnsiCompareText(LCategory, SActionCategoryNone) = 0 then // LCategory := ''; // // // Create new action // NewAction := CreateAction(ActionList.Owner, ActionClass) as TContainedAction; // try // if ActionList.Owner = Designer.Root then // NewAction.Name := Designer.UniqueName(ActionClass.ClassName) // else // begin // LRoot := ActiveDesigner.FindRoot(ActionList.Owner); // if LRoot <> nil then // NewAction.Name := LRoot.GetDesigner.UniqueName(ActionClass.ClassName) // else // raise Exception.CreateResFmt(@SUnableToFindComponent, [ActionList.Owner.Name]); // end; // NewAction.Category := LCategory; // NewAction.ActionList := ActionList; // // if ActionList.Images <> nil then // begin // // Use BeginUpdate to prevent the ImageList's ChangeLink from causing the // // Object Inspector to refresh, freeing the property editor in the process // ActionList.Images.BeginUpdate; // try // // Copy image if available // if (NewAction is TCustomAction) and (THackAction(NewAction).FImage <> nil) and // (ActionList.Images.Height = 16) and (ActionList.Images.Width = 16) then // begin // Image := TBitmap.Create; // try // Mask := TBitmap.Create; // try // Image.SetSize(16, 16); // Mask.SetSize(16, 16); // // Image.Canvas.Draw(0, 0, TBitmap(THackAction(NewAction).FImage)); // Mask.Canvas.Draw(0, 0, TBitmap(THackAction(NewAction).FMask)); // // Image.PixelFormat := pf8bit; // Mask.PixelFormat := pf8bit; // // THackAction(NewAction).FImage.Free; // THackAction(NewAction).FMask.Free; // THackAction(NewAction).FImage := nil; // THackAction(NewAction).FMask := nil; // THackAction(NewAction).ImageIndex := ActionList.Images.Add(Image, Mask); // finally // Mask.Free; // end; // finally // Image.Free; // end; // end; // // // Update property // SelectAction(Sender, NewAction); // finally // ActionList.Images.EndUpdate; // end; // end // else // // Update property // SelectAction(Sender, NewAction); // except // NewAction.Free; // raise; // end; //end; // //procedure TActionProperty.SelectAction(Sender: TObject; Action: TContainedAction); //begin // FHost.CloseDropDown; // if Action <> nil then // SetValue(Action.Owner.Name + DotSep + Action.Name) // else // SetValue(''); //end; // //procedure TActionProperty.Edit(const Host: IPropertyHost; DblClick: Boolean); //var // LHost20: IPropertyHost20; //begin // FHost := Host; // if FActionListView <> nil then // FActionListView.Free; // // FActionListView := TActionListView.Create(nil); // if Supports(FHost, IPropertyHost20, LHost20) then // FActionListView.Width := LHost20.GetDropDownWidth; // FActionListView.OnNewAction := CreateNewAction; // FActionListView.OnSelectAction := SelectAction; // FActionListView.Designer := Designer; // FActionListView.Visible := True; // FHost.DropDownControl(FActionListView); //end; // //function TActionProperty.GetAttributes: TPropertyAttributes; //begin // Result := inherited + [paCustomDropDown, paVolatileSubProperties] - [paValueList, paSortList]; //end; initialization CF_COMPONENTS := RegisterClipboardFormat(cfDelphiComponents); CF_COMPONENT := RegisterClipboardFormat(cfDelphiComponent); // NotifyGroupChange(UnregisterActionGroup); finalization // UnNotifyGroupChange(UnregisterActionGroup); end.
unit OS.Partition.Lock; interface uses OSFile.IoControl, OSFile.Handle, OS.Handle; type TPartitionLock = class(TIoControlFile) public constructor Create(const FileToGetAccess: String); override; procedure Lock; procedure Unlock; function GetHandle: THandle; protected function GetMinimumPrivilege: TCreateFileDesiredAccess; override; end; implementation { TPartitionLock } constructor TPartitionLock.Create(const FileToGetAccess: String); begin inherited Create(FileToGetAccess); CreateHandle(FileToGetAccess, DesiredReadWrite); end; function TPartitionLock.GetHandle: THandle; begin result := GetFileHandle; end; function TPartitionLock.GetMinimumPrivilege: TCreateFileDesiredAccess; begin result := TCreateFileDesiredAccess.DesiredReadWrite; end; procedure TPartitionLock.Lock; begin IoControl(TIoControlCode.LockVolume, NullOSBuffer); end; procedure TPartitionLock.Unlock; begin IoControl(TIoControlCode.UnlockVolume, NullOSBuffer); end; end.
unit QlpConverters; {$I ..\Include\QRCodeGenLib.inc} interface uses SysUtils, QlpGuard, QlpQRCodeGenLibTypes; resourcestring SEncodingInstanceNil = 'Encoding instance cannot be nil'; type TConverters = class sealed(TObject) strict private {$IF DEFINED(VCL_OR_LCL)} /// <summary> /// Convert a Delphi/Lazarus <c>TColor</c> to <c>HTML</c> Color code in /// Hex <c>.</c> /// </summary> /// <param name="AColor"> /// the <c>TColor</c> to convert /// </param> /// <returns> /// returns a string containing the <c>HTML</c> Color code representation /// of the <c>TColor</c> parameter in Hex /// </returns> class function TColorToHTMLColorHex(const AColor: TQRCodeGenLibColor) : String; inline; class function HTMLColorHexToTColor(const AHTMLHexColor: String) : TQRCodeGenLibColor; inline; {$ELSEIF DEFINED(FMX)} /// <summary> /// Convert a Delphi FireMonkey <c>TAlphaColor</c> to <c>HTML</c> Color code in /// Hex <c>.</c> /// </summary> /// <param name="AColor"> /// the <c>TAlphaColor</c> to convert /// </param> /// <returns> /// returns a string containing the <c>HTML</c> Color code representation /// of the <c>TAlphaColor</c> parameter in Hex /// </returns> class function TAlphaColorToHTMLColorHex(const AColor: TQRCodeGenLibColor) : String; inline; class function HTMLColorHexToTAlphaColor(const AHTMLHexColor: String) : TQRCodeGenLibColor; inline; {$ELSEIF DEFINED(FCL)} /// <summary> /// Convert an FPC <c>TFPColor</c> to <c>HTML</c> Color code in /// Hex <c>.</c> /// </summary> /// <param name="AColor"> /// the <c>TFPColor</c> to convert /// </param> /// <returns> /// returns a string containing the <c>HTML</c> Color code representation /// of the <c>TColor</c> parameter in Hex /// </returns> class function TFPColorToHTMLColorHex(const AColor: TQRCodeGenLibColor) : String; inline; class function HTMLColorHexToTFPColor(const AHTMLHexColor: String) : TQRCodeGenLibColor; inline; {$IFEND VCL_OR_LCL} public {$IFDEF VCL_OR_LCL} class function GetRValue(Argb: UInt32): Byte; static; inline; class function GetGValue(Argb: UInt32): Byte; static; inline; class function GetBValue(Argb: UInt32): Byte; static; inline; class function RGB(Ar, Ag, Ab: Byte): TQRCodeGenLibColor; static; inline; {$ENDIF VCL_OR_LCL} class function ConvertStringToBytes(const AInput: String; const AEncoding: TEncoding): TQRCodeGenLibByteArray; static; class function ConvertBytesToString(const AInput: TQRCodeGenLibByteArray; const AEncoding: TEncoding): String; static; class function QRCodeGenLibColorToHTMLHexColor(const AColor : TQRCodeGenLibColor): String; inline; class function HTMLHexColorToQRCodeGenLibColor(const AHTMLHexColor: String) : TQRCodeGenLibColor; inline; end; implementation { TConverters } class function TConverters.ConvertStringToBytes(const AInput: String; const AEncoding: TEncoding): TQRCodeGenLibByteArray; begin TGuard.RequireNotNull(AEncoding, SEncodingInstanceNil); {$IFDEF FPC} result := AEncoding.GetBytes(UnicodeString(AInput)); {$ELSE} result := AEncoding.GetBytes(AInput); {$ENDIF FPC} end; class function TConverters.ConvertBytesToString(const AInput : TQRCodeGenLibByteArray; const AEncoding: TEncoding): String; begin TGuard.RequireNotNull(AEncoding, SEncodingInstanceNil); {$IFDEF FPC} result := String(AEncoding.GetString(AInput)); {$ELSE} result := AEncoding.GetString(AInput); {$ENDIF FPC} end; {$IF DEFINED(VCL_OR_LCL)} class function TConverters.GetRValue(Argb: UInt32): Byte; begin result := Byte(Argb); end; class function TConverters.GetGValue(Argb: UInt32): Byte; begin result := Byte(Argb shr 8); end; class function TConverters.GetBValue(Argb: UInt32): Byte; begin result := Byte(Argb shr 16); end; class function TConverters.RGB(Ar, Ag, Ab: Byte): TQRCodeGenLibColor; begin result := (Ar or (Ag shl 8) or (Ab shl 16)); end; class function TConverters.TColorToHTMLColorHex(const AColor : TQRCodeGenLibColor): String; begin result := Format('%.2x%.2x%.2x', [GetRValue(QRCodeGenLibColorToRGB(AColor)), GetGValue(QRCodeGenLibColorToRGB(AColor)), GetBValue(QRCodeGenLibColorToRGB(AColor))]); end; class function TConverters.HTMLColorHexToTColor(const AHTMLHexColor: String) : TQRCodeGenLibColor; var R, G, B: Byte; begin {$IFDEF DEBUG} System.Assert(System.Length(AHTMLHexColor) = 6); {$ENDIF DEBUG} R := StrToInt('$' + System.Copy(AHTMLHexColor, 1, 2)); G := StrToInt('$' + System.Copy(AHTMLHexColor, 3, 2)); B := StrToInt('$' + System.Copy(AHTMLHexColor, 5, 2)); result := TQRCodeGenLibColor(RGB(R, G, B)); end; {$ELSEIF DEFINED(FMX)} class function TConverters.TAlphaColorToHTMLColorHex(const AColor : TQRCodeGenLibColor): String; begin result := Format('%.2x%.2x%.2x', [TQRCodeGenLibAlphaColorRec(AColor).R, TQRCodeGenLibAlphaColorRec(AColor).G, TQRCodeGenLibAlphaColorRec(AColor).B]); end; class function TConverters.HTMLColorHexToTAlphaColor(const AHTMLHexColor : String): TQRCodeGenLibColor; var R, G, B: Byte; rec: TQRCodeGenLibAlphaColorRec; begin {$IFDEF DEBUG} System.Assert(System.Length(AHTMLHexColor) = 6); {$ENDIF DEBUG} R := StrToInt('$' + System.Copy(AHTMLHexColor, 1, 2)); G := StrToInt('$' + System.Copy(AHTMLHexColor, 3, 2)); B := StrToInt('$' + System.Copy(AHTMLHexColor, 5, 2)); rec.A := $FF; // for transparency rec.R := R; rec.G := G; rec.B := B; result := rec.Color; end; {$ELSEIF DEFINED(FCL)} class function TConverters.TFPColorToHTMLColorHex(const AColor : TQRCodeGenLibColor): String; begin result := Format('%.2x%.2x%.2x', [AColor.Red shr 8, AColor.Green shr 8, AColor.Blue shr 8]); end; class function TConverters.HTMLColorHexToTFPColor(const AHTMLHexColor: String) : TQRCodeGenLibColor; var R, G, B: Byte; begin {$IFDEF DEBUG} System.Assert(System.Length(AHTMLHexColor) = 6); {$ENDIF DEBUG} R := StrToInt('$' + System.Copy(AHTMLHexColor, 1, 2)); G := StrToInt('$' + System.Copy(AHTMLHexColor, 3, 2)); B := StrToInt('$' + System.Copy(AHTMLHexColor, 5, 2)); result.Alpha := $FFFF; // for transparency result.Red := (R shl 8) + R; result.Green := (G shl 8) + G; result.Blue := (B shl 8) + B; end; {$IFEND VCL_OR_LCL} class function TConverters.QRCodeGenLibColorToHTMLHexColor (const AColor: TQRCodeGenLibColor): String; begin {$IF DEFINED(VCL_OR_LCL)} result := TConverters.TColorToHTMLColorHex(AColor); {$ELSEIF DEFINED(FMX)} result := TConverters.TAlphaColorToHTMLColorHex(AColor); {$ELSEIF DEFINED(FCL)} result := TConverters.TFPColorToHTMLColorHex(AColor); {$IFEND VCL_OR_LCL} end; class function TConverters.HTMLHexColorToQRCodeGenLibColor(const AHTMLHexColor : String): TQRCodeGenLibColor; begin {$IF DEFINED(VCL_OR_LCL)} result := TConverters.HTMLColorHexToTColor(AHTMLHexColor); {$ELSEIF DEFINED(FMX)} result := TConverters.HTMLColorHexToTAlphaColor(AHTMLHexColor); {$ELSEIF DEFINED(FCL)} result := TConverters.HTMLColorHexToTFPColor(AHTMLHexColor); {$IFEND VCL_OR_LCL} end; end.
unit eSocial.Models.DAO.Factory; interface uses eSocial.Models.DAO.Interfaces, eSocial.Models.DAO.Competencia, eSocial.Models.DAO.Operacao, eSocial.Models.DAO.Configuracao, eSocial.Models.Entities.Competencia, eSocial.Models.Entities.Operacao, eSocial.Models.Entities.Configuracao; type TModelDAOFactory = class strict private class var _instance : TModelDAOFactory; private FCompetencia : iModelDAOEntity<TCompetencia>; FOperacao : iModelDAOEntity<TOperacao>; FConfiguracao : iModelDAOEntity<TConfiguracao>; protected constructor Create; public destructor Destroy; override; class function GetInstance : TModelDAOFactory; function Competencia : iModelDAOEntity<TCompetencia>; function Operacao : iModelDAOEntity<TOperacao>; function Configuracao : iModelDAOEntity<TConfiguracao>; end; var _ModelDAOFactory : TModelDAOFactory; implementation { TModelDAOFactory } constructor TModelDAOFactory.Create; begin ; end; destructor TModelDAOFactory.Destroy; begin inherited; end; function TModelDAOFactory.Configuracao: iModelDAOEntity<TConfiguracao>; begin if not Assigned(FConfiguracao) then FConfiguracao := TModelDAOConfiguracao.New; Result := FConfiguracao; end; class function TModelDAOFactory.GetInstance: TModelDAOFactory; begin if not Assigned(_instance) then _instance := TModelDAOFactory.Create; Result := _instance; end; function TModelDAOFactory.Operacao: iModelDAOEntity<TOperacao>; begin if not Assigned(FOperacao) then FOperacao := TModelDAOOperacao.New; Result := FOperacao; end; function TModelDAOFactory.Competencia: iModelDAOEntity<TCompetencia>; begin if not Assigned(FCompetencia) then FCompetencia := TModelDAOCompetencia.New; Result := FCompetencia; end; initialization _ModelDAOFactory := TModelDAOFactory.GetInstance; finalization _ModelDAOFactory.DisposeOf; end.
unit U.Methods; interface uses System.Bindings.EvalProtocol; procedure RegisterCurrencyCleanMethodOnFactory; implementation uses System.Bindings.Methods, System.Bindings.Helper, System.Character, System.SysUtils; procedure RegisterCurrencyCleanMethodOnFactory; var LMethodDescription: TMethodDescription; LInvokable: IInvokable; begin TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create(MakeInvokable( function(Args: TArray<IValue>): IValue var StrValue, StrResult: String; CurrChar: Char; begin StrValue := Args[0].GetValue.AsString; for CurrChar in StrValue do if CurrChar.IsDigit or (CurrChar = ',') then StrResult := StrResult + CurrChar; Result := TValueWrapper.Create(StrToFloat(StrResult)); end), 'CurrencyClean', // Method identifier 'CurrencyClean', // Method name 'Utilities', // Unit name where the method is defined True, // Enabled 'Clean currency value from EUR symbol and other chars', // Long method description (Hint) nil // Method's platform (TComponent=VCL; TFMXComponent=FMX; nil=both) ) ); end; initialization RegisterCurrencyCleanMethodOnFactory; end.
unit constexpr_3; interface implementation function AddMul2Neg(a, b, c: Int32): Int32; pure; begin Result := - (a + b) * c; end; var G: Int32; procedure Test; begin G := AddMul2Neg(2, 3, 3); end; initialization Test(); finalization Assert(G = -15); end.
unit IdVCard; interface uses Classes, IdBaseComponent, IdGlobal; type TIdVCardEmbeddedObject = class(TPersistent) protected FObjectType: string; FObjectURL: string; FBase64Encoded: Boolean; FEmbeddedData: TStrings; procedure SetEmbeddedData(const Value: TStrings); public constructor Create; destructor Destroy; override; published property ObjectType: string read FObjectType write FObjectType; property ObjectURL: string read FObjectURL write FObjectURL; property Base64Encoded: Boolean read FBase64Encoded write FBase64Encoded; property EmbeddedData: TStrings read FEmbeddedData write SetEmbeddedData; end; TIdVCardBusinessInfo = class(TPersistent) protected FTitle: string; FRole: string; FOrganization: string; FDivisions: TStrings; procedure SetDivisions(Value: TStrings); public constructor Create; destructor Destroy; override; published property Organization: string read FOrganization write FOrganization; property Divisions: TStrings read FDivisions write SetDivisions; property Title: string read FTitle write FTitle; property Role: string read FRole write FRole; end; TIdVCardGeog = class(TPersistent) protected FLatitude: Real; FLongitude: Real; FTimeZoneStr: string; published property Latitude: Real read FLatitude write FLatitude; property Longitude: Real read FLongitude write FLongitude; property TimeZoneStr: string read FTimeZoneStr write FTimeZoneStr; end; TIdPhoneAttributes = set of (tpaHome, tpaVoiceMessaging, tpaWork, tpaPreferred, tpaVoice, tpaFax, paCellular, tpaVideo, tpaBBS, tpaModem, tpaCar, tpaISDN, tpaPCS, tpaPager); TIdCardPhoneNumber = class(TCollectionItem) protected FPhoneAttributes: TIdPhoneAttributes; FNumber: string; public procedure Assign(Source: TPersistent); override; published property PhoneAttributes: TIdPhoneAttributes read FPhoneAttributes write FPhoneAttributes; property Number: string read FNumber write FNumber; end; TIdVCardTelephones = class(TOwnedCollection) protected function GetItem(Index: Integer): TIdCardPhoneNumber; procedure SetItem(Index: Integer; const Value: TIdCardPhoneNumber); public constructor Create(AOwner: TPersistent); reintroduce; function Add: TIdCardPhoneNumber; property Items[Index: Integer]: TIdCardPhoneNumber read GetItem write SetItem; default; end; TIdCardAddressAttributes = set of (tatHome, tatDomestic, tatInternational, tatPostal, tatParcel, tatWork, tatPreferred); TIdCardAddressItem = class(TCollectionItem) protected FAddressAttributes: TIdCardAddressAttributes; FPOBox: string; FExtendedAddress: string; FStreetAddress: string; FLocality: string; FRegion: string; FPostalCode: string; FNation: string; public procedure Assign(Source: TPersistent); override; published property AddressAttributes: TIdCardAddressAttributes read FAddressAttributes write FAddressAttributes; property POBox: string read FPOBox write FPOBox; property ExtendedAddress: string read FExtendedAddress write FExtendedAddress; property StreetAddress: string read FStreetAddress write FStreetAddress; property Locality: string read FLocality write FLocality; property Region: string read FRegion write FRegion; property PostalCode: string read FPostalCode write FPostalCode; property Nation: string read FNation write FNation; end; TIdVCardAddresses = class(TOwnedCollection) protected function GetItem(Index: Integer): TIdCardAddressItem; procedure SetItem(Index: Integer; const Value: TIdCardAddressItem); public constructor Create(AOwner: TPersistent); reintroduce; function Add: TIdCardAddressItem; property Items[Index: Integer]: TIdCardAddressItem read GetItem write SetItem; default; end; TIdVCardMailingLabelItem = class(TCollectionItem) private FAddressAttributes: TIdCardAddressAttributes; FMailingLabel: TStrings; procedure SetMailingLabel(Value: TStrings); public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property AddressAttributes: TIdCardAddressAttributes read FAddressAttributes write FAddressAttributes; property MailingLabel: TStrings read FMailingLabel write SetMailingLabel; end; TIdVCardMailingLabels = class(TOwnedCollection) protected function GetItem(Index: Integer): TIdVCardMailingLabelItem; procedure SetItem(Index: Integer; const Value: TIdVCardMailingLabelItem); public constructor Create(AOwner: TPersistent); reintroduce; function Add: TIdVCardMailingLabelItem; property Items[Index: Integer]: TIdVCardMailingLabelItem read GetItem write SetItem; default; end; TIdVCardEMailType = (ematAOL, ematAppleLink, ematATT, ematCIS, emateWorld, ematInternet, ematIBMMail, ematMCIMail, ematPowerShare, ematProdigy, ematTelex, ematX400); TIdVCardEMailItem = class(TCollectionItem) protected FEMailType: TIdVCardEMailType; FPreferred: Boolean; FAddress: string; public constructor Create(Collection: TCollection); override; procedure Assign(Source: TPersistent); override; published property EMailType: TIdVCardEMailType read FEMailType write FEMailType; property Preferred: Boolean read FPreferred write FPreferred; property Address: string read FAddress write FAddress; end; TIdVCardEMailAddresses = class(TOwnedCollection) protected function GetItem(Index: Integer): TIdVCardEMailItem; procedure SetItem(Index: Integer; const Value: TIdVCardEMailItem); public constructor Create(AOwner: TPersistent); reintroduce; function Add: TIdVCardEMailItem; property Items[Index: Integer]: TIdVCardEMailItem read GetItem write SetItem; default; end; TIdVCardName = class(TPersistent) protected FFirstName: string; FSurName: string; FOtherNames: TStrings; FPrefix: string; FSuffix: string; FFormattedName: string; FSortName: string; FNickNames: TStrings; procedure SetOtherNames(Value: TStrings); procedure SetNickNames(Value: TStrings); public constructor Create; destructor Destroy; override; published property FirstName: string read FFirstName write FFirstName; property SurName: string read FSurName write FSurName; property OtherNames: TStrings read FOtherNames write SetOtherNames; property FormattedName: string read FFormattedName write FFormattedName; property Prefix: string read FPrefix write FPrefix; property Suffix: string read FSuffix write FSuffix; property SortName: string read FSortName write FSortName; property NickNames: TStrings read FNickNames write SetNickNames; end; TIdVCard = class(TIdBaseComponent) private protected FComments: TStrings; FCatagories: TStrings; FBusinessInfo: TIdVCardBusinessInfo; FGeography: TIdVCardGeog; FFullName: TIdVCardName; FRawForm: TStrings; FURLs: TStrings; FEMailProgram: string; FEMailAddresses: TIdVCardEMailAddresses; FAddresses: TIdVCardAddresses; FMailingLabels: TIdVCardMailingLabels; FTelephones: TIdVCardTelephones; FVCardVersion: Real; FProductID: string; FUniqueID: string; FClassification: string; FLastRevised: TDateTime; FBirthDay: TDateTime; FPhoto: TIdVCardEmbeddedObject; FLogo: TIdVCardEmbeddedObject; FSound: TIdVCardEmbeddedObject; FKey: TIdVCardEmbeddedObject; procedure SetComments(Value: TStrings); procedure SetCatagories(Value: TStrings); procedure SetURLs(Value: TStrings); procedure SetVariablesAfterRead; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ReadFromTStrings(s: TStrings); property RawForm: TStrings read FRawForm; published property VCardVersion: Real read FVCardVersion; property URLs: TStrings read FURLs write SetURLs; property ProductID: string read FProductID write FProductID; property UniqueID: string read FUniqueID write FUniqueID; property Classification: string read FClassification write FClassification; property BirthDay: TDateTime read FBirthDay write FBirthDay; property FullName: TIdVCardName read FFullName write FFullName; property EMailProgram: string read FEMailProgram write FEMailProgram; property EMailAddresses: TIdVCardEMailAddresses read FEMailAddresses; property Telephones: TIdVCardTelephones read FTelephones; property BusinessInfo: TIdVCardBusinessInfo read FBusinessInfo; property Catagories: TStrings read FCatagories write SetCatagories; property Addresses: TIdVCardAddresses read FAddresses; property MailingLabels: TIdVCardMailingLabels read FMailingLabels; property Comments: TStrings read FComments write SetComments; property Photo: TIdVCardEmbeddedObject read FPhoto; property Logo: TIdVCardEmbeddedObject read FLogo; property Sound: TIdVCardEmbeddedObject read FSound; property Key: TIdVCardEmbeddedObject read FKey; end; implementation uses IdCoderText, SysUtils; const VCardProperties: array[1..28] of string = ( 'FN', 'N', 'NICKNAME', 'PHOTO', 'BDAY', 'ADR', 'LABEL', 'TEL', 'EMAIL', 'MAILER', 'TZ', 'GEO', 'TITLE', 'ROLE', 'LOGO', 'AGENT', 'ORG', 'CATEGORIES', 'NOTE', 'PRODID', 'REV', 'SORT-STRING', 'SOUND', 'URL', 'UID', 'VERSION', 'CLASS', 'KEY'); { These constants are for testing the VCard for E-Mail types. Don't alter these } const EMailTypePropertyParameter: array[1..12] of string = ('AOL', 'APPLELINK', 'ATTMAIL', 'CIS', 'EWORLD', 'INTERNET', 'IBMMAIL', 'MCIMAIL', 'POWERSHARE', 'PRODIGY', 'TLX', 'X400'); procedure AddValueToStrings(strs: TStrings; Value: string); begin if (Length(Value) <> 0) then begin strs.Add(Value); end; end; procedure ParseDelinatorToTStrings(strs: TStrings; str: string; deliniator: Char = ','); begin while (str <> '') do begin AddValueToStrings(strs, Fetch(str, deliniator)); end; end; function ParseDateTimeStamp(DateString: string): TDateTime; var Year, Day, Month: Integer; Hour, Minute, Second: Integer; begin Year := StrToInt(Copy(DateString, 1, 4)); Month := StrToInt(Copy(DateString, 5, 2)); Day := StrToInt(Copy(DateString, 7, 2)); if (Length(DateString) > 14) then begin Hour := StrToInt(Copy(DateString, 10, 2)); Minute := StrToInt(Copy(DateString, 12, 2)); Second := StrToInt(Copy(DateString, 14, 2)); end else begin Hour := 0; Minute := 0; Second := 0; end; Result := EncodeDate(Year, Month, Day) + EncodeTime(Hour, Minute, Second, 0); end; function GetAttributesAndValue(data: string; var value: string): TStringList; var Buff, Buff2: string; begin Result := TStringList.Create; Result.Sorted := False; if Pos(':', Data) <> 0 then begin Buff := idGlobal.Fetch(Data, ':'); StringReplace(Buff, ',', ';', [rfReplaceAll]); while (Buff <> '') do begin Buff2 := IdGlobal.Fetch(Buff, ';'); if (Length(Buff2) > 0) then begin Result.Add(UpperCase(Buff2)); end; end; end; Value := Data; end; procedure ParseOrg(OrgObj: TIdVCardBusinessInfo; OrgStr: string); begin OrgObj.Organization := Fetch(OrgStr); ParseDelinatorToTStrings(OrgObj.Divisions, OrgStr, ';'); end; procedure ParseGeography(Geog: TIdVCardGeog; GeogStr: string); begin Geog.Latitude := StrToFloat(Fetch(GeogStr, ';')); Geog.Longitude := StrToFloat(Fetch(GeogStr, ';')); end; procedure ParseTelephone(PhoneObj: TIdCardPhoneNumber; PhoneStr: string); var Value: string; idx: Integer; Attribs: TStringList; const TelephoneTypePropertyParameter: array[0..13] of string = ('HOME', 'MSG', 'WORK', 'PREF', 'VOICE', 'FAX', 'CELL', 'VIDEO', 'BBS', 'MODEM', 'CAR', 'ISDN', 'PCS', 'PAGER'); begin attribs := GetAttributesAndValue(PhoneStr, Value); try idx := 0; while idx < Attribs.Count do begin case idGlobal.PosInStrArray(attribs[idx], TelephoneTypePropertyParameter) of 0: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaHome]; 1: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaVoiceMessaging]; 2: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaWork]; 3: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaPreferred]; 4: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaVoice]; 5: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaFax]; 6: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [paCellular]; 7: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaVideo]; 8: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaBBS]; 9: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaModem]; 10: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaCar]; 11: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaISDN]; 12: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaPCS]; 13: PhoneObj.PhoneAttributes := PhoneObj.PhoneAttributes + [tpaPager]; end; inc(idx); end; if (Attribs.Count = 0) then begin PhoneObj.PhoneAttributes := [tpaVoice]; end; PhoneObj.Number := Value; finally FreeAndNil(attribs); end; end; procedure ParseAddress(AddressObj: TIdCardAddressItem; AddressStr: string); var Value: string; Attribs: TStringList; idx: Integer; const AttribsArray: array[0..6] of string = ('HOME', 'DOM', 'INTL', 'POSTAL', 'PARCEL', 'WORK', 'PREF'); begin Attribs := GetAttributesAndValue(AddressStr, Value); try idx := 0; while idx < Attribs.Count do begin case idGlobal.PosInStrArray(attribs[idx], AttribsArray) of 0: AddressObj.AddressAttributes := AddressObj.AddressAttributes + [tatHome]; 1: AddressObj.AddressAttributes := AddressObj.AddressAttributes + [tatDomestic]; 2: AddressObj.AddressAttributes := AddressObj.AddressAttributes + [tatInternational]; 3: AddressObj.AddressAttributes := AddressObj.AddressAttributes + [tatPostal]; 4: AddressObj.AddressAttributes := AddressObj.AddressAttributes + [tatParcel]; 5: AddressObj.AddressAttributes := AddressObj.AddressAttributes + [tatWork]; 6: AddressObj.AddressAttributes := AddressObj.AddressAttributes + [tatPreferred]; end; inc(idx); end; if (Attribs.Count = 0) then begin AddressObj.AddressAttributes := [tatInternational, tatPostal, tatParcel, tatWork]; end; AddressObj.POBox := idGlobal.Fetch(Value, ';'); AddressObj.ExtendedAddress := idGlobal.Fetch(Value, ';'); AddressObj.StreetAddress := idGlobal.Fetch(Value, ';'); AddressObj.Locality := idGlobal.Fetch(Value, ';'); AddressObj.Region := idGlobal.Fetch(Value, ';'); AddressObj.PostalCode := idGlobal.Fetch(Value, ';'); AddressObj.Nation := idGlobal.Fetch(Value, ';'); finally FreeAndNil(Attribs); end; end; procedure ParseMailingLabel(LabelObj: TIdVCardMailingLabelItem; LabelStr: string); var Value: string; Attribs: TStringList; idx: Integer; const AttribsArray: array[0..6] of string = ('HOME', 'DOM', 'INTL', 'POSTAL', 'PARCEL', 'WORK', 'PREF'); begin Attribs := GetAttributesAndValue(LabelStr, Value); try idx := 0; while idx < Attribs.Count do begin case idGlobal.PosInStrArray(attribs[idx], AttribsArray) of 0: LabelObj.AddressAttributes := LabelObj.AddressAttributes + [tatHome]; 1: LabelObj.AddressAttributes := LabelObj.AddressAttributes + [tatDomestic]; 2: LabelObj.AddressAttributes := LabelObj.AddressAttributes + [tatInternational]; 3: LabelObj.AddressAttributes := LabelObj.AddressAttributes + [tatPostal]; 4: LabelObj.AddressAttributes := LabelObj.AddressAttributes + [tatParcel]; 5: LabelObj.AddressAttributes := LabelObj.AddressAttributes + [tatWork]; 6: LabelObj.AddressAttributes := LabelObj.AddressAttributes + [tatPreferred]; end; inc(idx); end; if Attribs.Count = 0 then begin LabelObj.AddressAttributes := [tatInternational, tatPostal, tatParcel, tatWork]; end; LabelObj.MailingLabel.Add(Value); finally FreeAndNil(Attribs); end; end; procedure ParseName(NameObj: TIdVCardName; NameStr: string); var OtherNames: string; begin NameObj.SurName := Fetch(NameStr, ';'); NameObj.FirstName := Fetch(NameStr, ';'); OtherNames := Fetch(NameStr, ';'); NameObj.Prefix := Fetch(NameStr, ';'); NameObj.Suffix := Fetch(NameStr, ';'); OtherNames := StringReplace(OtherNames, ' ', ',', [rfReplaceAll]); ParseDelinatorToTStrings(NameObj.OtherNames, OtherNames); end; procedure ParseEMailAddress(EMailObj: TIdVCardEMailItem; EMailStr: string); var Value: string; Attribs: TStringList; idx: Integer; ps: Integer; begin Attribs := GetAttributesAndValue(EMailStr, Value); try EMailObj.Address := Value; EMailObj.Preferred := (attribs.IndexOf('PREF') <> -1); idx := 0; ps := -1; while (idx < Attribs.Count) and (ps = -1) do begin ps := PosInStrArray(Attribs[idx], EMailTypePropertyParameter); case ps of 0: EMailObj.EMailType := ematAOL; 1: EMailObj.EMailType := ematAppleLink; 2: EMailObj.EMailType := ematATT; 3: EMailObj.EMailType := ematCIS; 4: EMailObj.EMailType := emateWorld; 5: EMailObj.EMailType := ematInternet; 6: EMailObj.EMailType := ematIBMMail; 7: EMailObj.EMailType := ematMCIMail; 8: EMailObj.EMailType := ematPowerShare; 9: EMailObj.EMailType := ematProdigy; 10: EMailObj.EMailType := ematTelex; 11: EMailObj.EMailType := ematX400; end; inc(idx); end; finally FreeAndNil(Attribs); end; end; constructor TIdVCard.Create(AOwner: TComponent); begin inherited; FPhoto := TIdVCardEmbeddedObject.Create; FLogo := TIdVCardEmbeddedObject.Create; FSound := TIdVCardEmbeddedObject.Create; FKey := TIdVCardEmbeddedObject.Create; FComments := TStringList.Create; FCatagories := TStringList.Create; FBusinessInfo := TIdVCardBusinessInfo.Create; FGeography := TIdVCardGeog.Create; FFullName := TIdVCardName.Create; FRawForm := TStringList.Create; FEMailAddresses := TIdVCardEMailAddresses.Create(Self); FAddresses := TIdVCardAddresses.Create(Self); FTelephones := TIdVCardTelephones.Create(Self); FURLs := TStringList.Create; FMailingLabels := TIdVCardMailingLabels.Create(Self); end; destructor TIdVCard.Destroy; begin FreeAndNil(FKey); FreeAndNil(FPhoto); FreeAndNil(FLogo); FreeAndNil(FSound); FreeAndNil(FComments); FreeAndNil(FMailingLabels); FreeAndNil(FCatagories); FreeAndNil(FBusinessInfo); FreeAndNil(FGeography); FreeAndNil(FURLs); FreeAndNil(FTelephones); FreeAndNil(FAddresses); FreeAndNil(FEMailAddresses); FreeAndNil(FFullName); FreeAndNil(FRawForm); inherited; end; procedure TIdVCard.ReadFromTStrings(s: TStrings); var idx, embedded: Integer; begin FRawForm.Clear; idx := 0; embedded := 0; while (idx < s.Count) and (Trim(UpperCase(s[idx])) <> 'BEGIN:VCARD') do begin Inc(idx); end; while (idx < s.Count) do begin if Length(s[idx]) > 0 then begin if UpperCase(Trim(s[idx])) <> 'END:VCARD' then begin if embedded <> 0 then begin Dec(embedded); end; end else if UpperCase(Trim(s[idx])) <> 'BEGIN:VCARD' then begin Inc(embedded); end; FRawForm.Add(s[idx]); end; Inc(idx); end; if (idx < s.Count) and (Length(s[idx]) > 0) then FRawForm.Add(s[idx]); SetVariablesAfterRead; end; procedure TIdVCard.SetCatagories(Value: TStrings); begin FCatagories.Assign(Value); end; procedure TIdVCard.SetComments(Value: TStrings); begin FComments.Assign(Value); end; procedure TIdVCard.SetURLs(Value: TStrings); begin FURLs.Assign(Value); end; procedure TIdVCard.SetVariablesAfterRead; var idx: Integer; OrigLine: string; Line: string; Attribs: string; Data: string; Test: string; Colon: Integer; SColon: Integer; ColonFind: Integer; QPCoder: TIdQuotedPrintableDecoder; function UnfoldLines: string; begin Result := ''; Inc(idx); while (idx < FRawForm.Count) and ((Length(FRawForm[idx]) > 0) and (FRawForm[idx][1] = ' ') or (FRawForm[idx][1] = #9)) do begin Result := Result + Trim(FRawForm[idx]); inc(idx); end; Dec(idx); end; procedure ProcessAgent; begin end; procedure ParseEmbeddedObject(EmObj: TIdVCardEmbeddedObject; StLn: string); var Value: string; Attribs: TStringList; idx2: Integer; begin attribs := GetAttributesAndValue(StLn, Value); try idx2 := 0; while (idx2 < attribs.Count) do begin if ((Attribs[idx2] = 'ENCODING=BASE64') or (Attribs[idx2] = 'BASE64')) then begin emObj.Base64Encoded := True; end else begin if not ((Attribs[idx2] = 'VALUE=URI') or (Attribs[idx2] = 'VALUE=URL') or (Attribs[idx2] = 'URI') or (Attribs[idx2] = 'URL')) then begin emObj.ObjectType := Attribs[idx2]; end; end; Inc(idx2); end; if (Attribs.IndexOf('VALUE=URI') > -1) or (Attribs.IndexOf('VALUE=URL') > -1) or (Attribs.IndexOf('URI') > -1) or (Attribs.IndexOf('URL') > -1) then begin emObj.ObjectURL := Value + UnfoldLines; end else begin AddValueToStrings(EmObj.EmbeddedData, Value); Inc(idx); while (idx < FRawForm.Count) and ((Length(FRawForm[idx]) > 0) and (FRawForm[idx][1] = ' ') or (FRawForm[idx][1] = #9)) do begin AddValueToStrings(EmObj.EmbeddedData, Trim(FRawForm[idx2])); inc(idx); end; Dec(idx); end; finally FreeAndNil(Attribs); end; end; begin QPCoder := TIdQuotedPrintableDecoder.Create(Self); try QPCoder.AddCRLF := False; QPCoder.UseEvent := False; QPCoder.IgnoreNotification := True; idx := 0; while idx < FRawForm.Count do begin Line := FRawForm[idx]; Colon := Pos(':', Line); Attribs := Copy(Line, 1, Colon - 1); if Pos('QUOTED-PRINTABLE', UpperCase(Attribs)) > 0 then begin OrigLine := Line; Data := Copy(Line, Colon + 1, Length(Line)); Inc(idx); ColonFind := Pos(':', FRawForm[idx]); while ColonFind = 0 do begin Data := Data + CR + LF + TrimLeft(FRawForm[idx]); Inc(idx); if idx <> FRawForm.Count then begin ColonFind := Pos(':', FRawForm[idx]); end else ColonFind := 1; end; Dec(idx); Test := QPCoder.CodeString(Data); Data := ''; while Test <> '' do begin Fetch(Test, ';'); Data := Data + Test; Test := QPCoder.GetCodedData; end; Test := QPCoder.CompletedInput; while Test <> '' do begin Fetch(Test, ';'); Data := Data + Test; Test := QPCoder.GetCodedData; end; QPCoder.Reset; ColonFind := Pos(';', Attribs); Line := ''; while ColonFind <> 0 do begin Test := Copy(Attribs, 1, ColonFind); if Pos('QUOTED-PRINTABLE', Test) = 0 then begin Line := Line + Test; end; Attribs := Copy(Attribs, ColonFind + 1, Length(Attribs)); ColonFind := Pos(';', Attribs); end; if Length(Attribs) <> 0 then begin if Pos('QUOTED-PRINTABLE', Attribs) = 0 then begin Line := Line + Attribs; end; end; ColonFind := Length(Line); if ColonFind > 0 then begin if Line[ColonFind] = ';' then begin Line := Copy(Line, 1, ColonFind - 1); end; end; Line := Line + ':' + Data; end; Colon := Pos(':', Line); SColon := Pos(';', Line); if (Colon < SColon) or (SColon = 0) then begin Line := StringReplace(Line, ':', ';', []); end; Test := UpperCase(Fetch(Line, ';')); case PosInStrArray(Test, VCardProperties) of 0: FFullName.FormattedName := Line + UnfoldLines; 1: ParseName(FFullName, Line + UnfoldLines); 2: ParseDelinatorToTStrings(FFullName.NickNames, Line + UnfoldLines); 3: ParseEmbeddedObject(FPhoto, Line); 4: FBirthDay := ParseDateTimeStamp(Line + UnfoldLines); 5: ParseAddress(FAddresses.Add, Line + UnfoldLines); 6: ParseMailingLabel(FMailingLabels.Add, Line + UnfoldLines); 7: ParseTelephone(FTelephones.Add, Line + UnfoldLines); 8: ParseEMailAddress(FEMailAddresses.Add, Line + UnfoldLines); 9: FEMailProgram := Line + UnfoldLines; 10: FGeography.TimeZoneStr := Line + UnfoldLines; 11: ParseGeography(FGeography, Line + UnfoldLines); 12: FBusinessInfo.Title := Line + UnfoldLines; 13: FBusinessInfo.Role := Line + UnfoldLines; 14: ParseEmbeddedObject(FLogo, Line); 15: ProcessAgent; 16: ParseOrg(FBusinessInfo, Line + UnfoldLines); 17: ParseDelinatorToTStrings(FCatagories, Line + UnfoldLines); 18: FComments.Add(Line + UnfoldLines); 19: FProductID := Line + UnfoldLines; 20: FLastRevised := ParseDateTimeStamp(Line + UnfoldLines); 21: FFullName.SortName := Line + UnfoldLines; 22: ParseEmbeddedObject(FSound, Line); 23: AddValueToStrings(FURLs, Line + UnfoldLines); 24: FUniqueID := Line + UnfoldLines; 25: FVCardVersion := StrToFloat(Line + UnfoldLines); 26: FClassification := Line + UnfoldLines; 27: ParseEmbeddedObject(FKey, Line); end; inc(idx); end; finally QPCoder.Free; end; end; function TIdVCardEMailAddresses.Add: TIdVCardEMailItem; begin Result := TIdVCardEMailItem(inherited Add); end; constructor TIdVCardEMailAddresses.Create(AOwner: TPersistent); begin inherited Create(AOwner, TIdVCardEMailItem); end; function TIdVCardEMailAddresses.GetItem(Index: Integer): TIdVCardEMailItem; begin Result := TIdVCardEMailItem(inherited Items[Index]); end; procedure TIdVCardEMailAddresses.SetItem(Index: Integer; const Value: TIdVCardEMailItem); begin inherited SetItem(Index, Value); end; procedure TIdVCardEMailItem.Assign(Source: TPersistent); var EMail: TIdVCardEMailItem; begin if ClassType <> Source.ClassType then begin inherited end else begin EMail := TIdVCardEMailItem(Source); EMailType := EMail.EMailType; Preferred := EMail.Preferred; Address := EMail.Address; end; end; constructor TIdVCardEMailItem.Create(Collection: TCollection); begin inherited; FEMailType := ematInternet; end; function TIdVCardAddresses.Add: TIdCardAddressItem; begin Result := TIdCardAddressItem(inherited Add); end; constructor TIdVCardAddresses.Create(AOwner: TPersistent); begin inherited Create(AOwner, TIdCardAddressItem); end; function TIdVCardAddresses.GetItem(Index: Integer): TIdCardAddressItem; begin Result := TIdCardAddressItem(inherited Items[Index]); end; procedure TIdVCardAddresses.SetItem(Index: Integer; const Value: TIdCardAddressItem); begin inherited SetItem(Index, Value); end; function TIdVCardTelephones.Add: TIdCardPhoneNumber; begin Result := TIdCardPhoneNumber(inherited Add); end; constructor TIdVCardTelephones.Create(AOwner: TPersistent); begin inherited Create(AOwner, TIdCardPhoneNumber); end; function TIdVCardTelephones.GetItem(Index: Integer): TIdCardPhoneNumber; begin Result := TIdCardPhoneNumber(inherited Items[Index]); end; procedure TIdVCardTelephones.SetItem(Index: Integer; const Value: TIdCardPhoneNumber); begin inherited SetItem(Index, Value); end; constructor TIdVCardName.Create; begin inherited; FOtherNames := TStringList.Create; FNickNames := TStringList.Create; end; destructor TIdVCardName.Destroy; begin FreeAndNil(FNickNames); FreeAndNil(FOtherNames); inherited; end; procedure TIdVCardName.SetNickNames(Value: TStrings); begin FNickNames.Assign(Value); end; procedure TIdVCardName.SetOtherNames(Value: TStrings); begin FOtherNames.Assign(Value); end; constructor TIdVCardBusinessInfo.Create; begin inherited; FDivisions := TStringList.Create; end; destructor TIdVCardBusinessInfo.Destroy; begin FreeAndNil(FDivisions); inherited; end; procedure TIdVCardBusinessInfo.SetDivisions(Value: TStrings); begin FDivisions.Assign(Value); end; procedure TIdVCardMailingLabelItem.Assign(Source: TPersistent); var lbl: TIdVCardMailingLabelItem; begin if ClassType <> Source.ClassType then begin inherited end else begin lbl := TIdVCardMailingLabelItem(Source); AddressAttributes := lbl.AddressAttributes; MailingLabel.Assign(lbl.MailingLabel); end; end; constructor TIdVCardMailingLabelItem.Create(Collection: TCollection); begin inherited; FMailingLabel := TStringList.Create; end; destructor TIdVCardMailingLabelItem.Destroy; begin FreeAndNil(FMailingLabel); inherited; end; procedure TIdVCardMailingLabelItem.SetMailingLabel(Value: TStrings); begin FMailingLabel.Assign(Value); end; function TIdVCardMailingLabels.Add: TIdVCardMailingLabelItem; begin Result := TIdVCardMailingLabelItem(inherited Add); end; constructor TIdVCardMailingLabels.Create(AOwner: TPersistent); begin inherited Create(AOwner, TIdVCardMailingLabelItem); end; function TIdVCardMailingLabels.GetItem( Index: Integer): TIdVCardMailingLabelItem; begin Result := TIdVCardMailingLabelItem(inherited GetItem(Index)); end; procedure TIdVCardMailingLabels.SetItem(Index: Integer; const Value: TIdVCardMailingLabelItem); begin inherited SetItem(Index, Value); end; constructor TIdVCardEmbeddedObject.Create; begin inherited; FEmbeddedData := TStringList.Create; end; destructor TIdVCardEmbeddedObject.Destroy; begin FreeAndNil(FEmbeddedData); inherited; end; procedure TIdVCardEmbeddedObject.SetEmbeddedData(const Value: TStrings); begin FEmbeddedData.Assign(Value); end; procedure TIdCardPhoneNumber.Assign(Source: TPersistent); var Phone: TIdCardPhoneNumber; begin if ClassType <> Source.ClassType then begin inherited; end else begin Phone := TIdCardPhoneNumber(Source); PhoneAttributes := Phone.PhoneAttributes; Number := Phone.Number; end; end; procedure TIdCardAddressItem.Assign(Source: TPersistent); var Addr: TIdCardAddressItem; begin if ClassType <> Source.ClassType then begin inherited; end else begin Addr := TIdCardAddressItem(Source); AddressAttributes := Addr.AddressAttributes; POBox := Addr.POBox; ExtendedAddress := Addr.ExtendedAddress; StreetAddress := Addr.StreetAddress; Locality := Addr.Locality; Region := Addr.Region; PostalCode := Addr.PostalCode; Nation := Addr.Nation; end; end; end.
unit fGMV_AddEditQualifier; { ================================================================================ * * Application: Vitals * Revision: $Revision: 1 $ $Modtime: 3/02/09 12:04p $ * Developer: doma.user@domain.ext * Site: Hines OIFO * * Description: Form to add/edit qualifiers * * Notes: * ================================================================================ * $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/APP-VITALSMANAGER/fGMV_AddEditQualifier.pas $ * * $History: fGMV_AddEditQualifier.pas $ * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 8/12/09 Time: 8:29a * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/APP-VITALSMANAGER * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 3/09/09 Time: 3:38p * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/APP-VITALSMANAGER * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 1/13/09 Time: 1:26p * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/APP-VITALSMANAGER * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/11/07 Time: 3:12p * Created in $/Vitals GUI 2007/Vitals-5-0-18/APP-VITALSMANAGER * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/16/06 Time: 5:40p * Created in $/Vitals/VITALS-5-0-18/APP-VitalsManager * GUI v. 5.0.18 updates the default vital type IENs with the local * values. * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/16/06 Time: 5:30p * Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/APP-VitalsManager * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/24/05 Time: 4:56p * Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsManager-503 * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 4/16/04 Time: 4:21p * Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSMANAGER-503 * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 1/26/04 Time: 1:09p * Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, Delphi7)/V5031-D7/VitalsManager * * ***************** Version 7 ***************** * User: Zzzzzzandria Date: 11/04/02 Time: 9:15a * Updated in $/Vitals GUI Version 5.0/Vitals Manager * Version 5.0.0.0 * * ***************** Version 6 ***************** * User: Zzzzzzandria Date: 8/23/02 Time: 5:04p * Updated in $/Vitals GUI Version 5.0/Vitals Manager * * ***************** Version 5 ***************** * User: Zzzzzzandria Date: 7/18/02 Time: 5:56p * Updated in $/Vitals GUI Version 5.0/Vitals Manager * 1. Qualifier name case are the same as in Database * 2. Qualifier List for the category selected is updated after editing * the qualifier description * 3. Categories are kept in ListView and supplied with a hint if not * enough window space * 4. Tree view could not be stretched more then 300 pixels or shrunken * less then 150 * * ***************** Version 4 ***************** * User: Zzzzzzandria Date: 7/09/02 Time: 5:00p * Updated in $/Vitals GUI Version 5.0/Vitals Manager * * ***************** Version 3 ***************** * User: Zzzzzzandria Date: 6/13/02 Time: 5:14p * Updated in $/Vitals GUI Version 5.0/Vitals Manager * * ***************** Version 2 ***************** * User: Zzzzzzpetitd Date: 6/06/02 Time: 11:10a * Updated in $/Vitals GUI Version 5.0/Vitals Manager * Roll-up to 5.0.0.27 * * ***************** Version 1 ***************** * User: Zzzzzzpetitd Date: 4/04/02 Time: 3:39p * Created in $/Vitals GUI Version 5.0/Vitals Manager * * * ================================================================================ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, uGMV_Common, Buttons, ExtCtrls, uGMV_FileEntry; type TfrmGMV_AddEditQualifier = class(TForm) edtName: TEdit; edtAbbv: TEdit; Label1: TLabel; Label2: TLabel; Panel1: TPanel; btnCancel: TButton; btnOK: TButton; btnApply: TButton; procedure edtNameChange(Sender: TObject); procedure edtNameExit(Sender: TObject); procedure edtAbbvExit(Sender: TObject); procedure edtAbbvEnter(Sender: TObject); procedure edtAbbvChange(Sender: TObject); procedure edtNameEnter(Sender: TObject); procedure btnApplyClick(Sender: TObject); procedure edtNameKeyPress(Sender: TObject; var Key: Char); procedure btnOKClick(Sender: TObject); private FDD: string; FIENS: string; FQualifierRec: TGMV_FileEntry; FChangeMade: Boolean; { Private declarations } public { Public declarations } end; var frmGMV_AddEditQualifier: TfrmGMV_AddEditQualifier; function NewQualifier: TGMV_FileEntry; procedure EditQualifier(Qualifier: TGMV_FileEntry); implementation uses uGMV_Const , uGMV_Engine, system.UITypes ; {$R *.DFM} function NewQualifier: TGMV_FileEntry; var s, aNewQualifier: string; begin Result := nil; if InputQuery('New Qualifier', 'Qualifier Name (2-50 char):', aNewQualifier) then if aNewQualifier <> '' then begin s := addNewQualifier(aNewQualifier); if piece(s, '^', 1) = '-1' then begin MessageDlg('Unable to create qualifier'+#13+piece(s, '^', 2), mtError, [mbok], 0); end else begin Result := TGMV_FileEntry.CreateFromRPC(s); GMVQuals.Entries.AddObject(Result.Caption, Result); EditQualifier({Broker, }Result); end; end; end; procedure EditQualifier({Broker: TRPCBroker; }Qualifier: TGMV_FileEntry); begin with TfrmGMV_AddEditQualifier.Create(Application) do try FQualifierRec := Qualifier; FDD := Qualifier.DDNumber; FIENS := Qualifier.IENS; edtName.Text := Qualifier.FieldData('.01'); edtAbbv.Text := Qualifier.FieldData('.02'); ShowModal; finally free; end; end; procedure TfrmGMV_AddEditQualifier.edtNameEnter(Sender: TObject); begin FChangeMade := False; btnApply.Enabled := False;//AAN 06/12/02 end; procedure TfrmGMV_AddEditQualifier.edtNameKeyPress(Sender: TObject; var Key: Char); begin //AAN 07/18/2002 if Key in ['a'..'z'] then //AAN 07/18/2002 Dec(Key, 32); end; procedure TfrmGMV_AddEditQualifier.edtNameChange(Sender: TObject); begin FChangeMade := True; btnApply.Enabled := True;//AAN 06/12/02 end; procedure TfrmGMV_AddEditQualifier.edtNameExit(Sender: TObject); var s: String; begin if FChangeMade then begin s := validateQualifierName(FDD,FIENS,'.01',edtName.text); if piece(s, '^', 1) = '-1' then begin MessageDlg(piece(s, '^', 2), mtError, [mbOK], 0); edtName.Text := FQualifierRec.FieldData('.01'); edtName.SetFocus; end; FChangeMade := False; btnApply.Enabled := False;//AAN 06/12/02 end; end; procedure TfrmGMV_AddEditQualifier.edtAbbvEnter(Sender: TObject); begin FChangeMade := False; btnApply.Enabled := False;//AAN 06/12/02 end; procedure TfrmGMV_AddEditQualifier.edtAbbvChange(Sender: TObject); begin FChangeMade := True; btnApply.Enabled := True;//AAN 06/12/02 end; procedure TfrmGMV_AddEditQualifier.edtAbbvExit(Sender: TObject); var s: String; begin if FChangeMade then begin s := validateQualifierName(FDD,FIENS,'.02',edtAbbv.text); if piece(s, '^', 1) = '-1' then begin MessageDlg(piece(s, '^', 2), mtError, [mbOK], 0); edtAbbv.Text := FQualifierRec.FieldData('.02'); edtAbbv.SetFocus; end; FChangeMade := False; btnApply.Enabled := False;//AAN 06/12/02 end; end; procedure TfrmGMV_AddEditQualifier.btnApplyClick(Sender: TObject); var i: Integer; begin i := GMVQuals.Entries.IndexOfObject(FQualifierRec);// AAN 08/22/2002 setQualifierName(FDD,FIENS,'.01',edtName.text); setQualifierName(FDD,FIENS,'.02',edtAbbv.text); FQualifierRec.Caption := FQualifierRec.FieldData('.01'); try GMVQuals.Entries[i] := FQualifierRec.Caption; except end; btnApply.Enabled := False;//AAN 06/12/02 end; procedure TfrmGMV_AddEditQualifier.btnOKClick(Sender: TObject); begin btnApplyClick(Sender); end; end.
unit uNPCFrame; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TNPCFrame = class(TFrame) pnlBackground: TPanel; lblName: TLabel; lblFunction: TLabel; lblLocation: TLabel; mmoDescr: TMemo; private { Private declarations } public { Public declarations } end; type TNPC = record name: string; desc: string; location: string; func: string; end; implementation {$R *.dfm} end.
unit UNewCorrectPacking; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UFrameSave, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, Vcl.StdCtrls, Vcl.Mask, sMaskEdit, sCustomComboEdit, sCurrEdit, cxGroupBox, dxSkinDevExpressStyle, dxSkinXmas2008Blue; type TFNewCorrectPacking = class(TForm) FrameSave1: TFrameSave; GroupPrice: TcxGroupBox; lbl2: TLabel; edtЗнакЦены: TComboBox; lbl3: TLabel; edtЦенаКоррект: TsCalcEdit; cxGroupBox1: TcxGroupBox; Label2: TLabel; Label3: TLabel; edtВесДействие: TComboBox; edtВесЗначение: TsCalcEdit; procedure FormShow(Sender: TObject); procedure FrameSave1btnSaveClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FNewCorrectPacking: TFNewCorrectPacking; implementation {$R *.dfm} procedure TFNewCorrectPacking.FormShow(Sender: TObject); begin edtЦенаКоррект.SetFocus; end; procedure TFNewCorrectPacking.FrameSave1btnSaveClick(Sender: TObject); begin FrameSave1.btnSaveClick(Sender); Close; end; end.
unit testhqrndunit; interface uses Math, Sysutils, Ap, hqrnd; procedure CalculateMV(const X : TReal1DArray; N : AlglibInteger; var Mean : Double; var MeanS : Double; var StdDev : Double; var StdDevS : Double); function TestHQRND(Silent : Boolean):Boolean; function testhqrndunit_test_silent():Boolean; function testhqrndunit_test():Boolean; implementation procedure UnsetState(var State : HQRNDState);forward; procedure CalculateMV(const X : TReal1DArray; N : AlglibInteger; var Mean : Double; var MeanS : Double; var StdDev : Double; var StdDevS : Double); var I : AlglibInteger; V : Double; V1 : Double; V2 : Double; Variance : Double; begin Mean := 0; MeanS := 1; StdDev := 0; StdDevS := 1; Variance := 0; if N<=1 then begin Exit; end; // // Mean // I:=0; while I<=N-1 do begin Mean := Mean+X[I]; Inc(I); end; Mean := Mean/N; // // Variance (using corrected two-pass algorithm) // if N<>1 then begin V1 := 0; I:=0; while I<=N-1 do begin V1 := V1+AP_Sqr(X[I]-Mean); Inc(I); end; V2 := 0; I:=0; while I<=N-1 do begin V2 := V2+(X[I]-Mean); Inc(I); end; V2 := AP_Sqr(V2)/N; Variance := (V1-V2)/(N-1); if AP_FP_Less(Variance,0) then begin Variance := 0; end; StdDev := Sqrt(Variance); end; // // Errors // MeanS := StdDev/Sqrt(N); StdDevS := StdDev*Sqrt(2)/Sqrt(N-1); end; function TestHQRND(Silent : Boolean):Boolean; var WasErrors : Boolean; SampleSize : AlglibInteger; SigmaThreshold : Double; PassCount : AlglibInteger; N : AlglibInteger; I : AlglibInteger; Pass : AlglibInteger; S1 : AlglibInteger; S2 : AlglibInteger; I1 : AlglibInteger; I2 : AlglibInteger; R1 : Double; R2 : Double; X : TReal1DArray; Mean : Double; MeanS : Double; StdDev : Double; StdDevS : Double; Lambda : Double; SeedErrors : Boolean; URErrors : Boolean; URSigmaErr : Double; UIErrors : Boolean; UISigmaErr : Double; NormErrors : Boolean; NormSigmaErr : Double; ExpErrors : Boolean; ExpSigmaErr : Double; State : HQRNDState; begin WasErrors := False; SigmaThreshold := 7; SampleSize := 100000; PassCount := 50; SetLength(X, SampleSize-1+1); // // Test seed errors // SeedErrors := False; Pass:=1; while Pass<=PassCount do begin S1 := 1+RandomInteger(32000); S2 := 1+RandomInteger(32000); UnsetState(State); HQRNDSeed(S1, S2, State); I1 := HQRNDUniformI(100, State); UnsetState(State); HQRNDSeed(S1, S2, State); I2 := HQRNDUniformI(100, State); SeedErrors := SeedErrors or (I1<>I2); UnsetState(State); HQRNDSeed(S1, S2, State); R1 := HQRNDUniformR(State); UnsetState(State); HQRNDSeed(S1, S2, State); R2 := HQRNDUniformR(State); SeedErrors := SeedErrors or AP_FP_Neq(R1,R2); Inc(Pass); end; // // Test HQRNDRandomize() and real uniform generator // UnsetState(State); HQRNDRandomize(State); URErrors := False; URSigmaErr := 0; I:=0; while I<=SampleSize-1 do begin X[I] := HQRNDUniformR(State); Inc(I); end; I:=0; while I<=SampleSize-1 do begin URErrors := URErrors or AP_FP_Less_Eq(X[I],0) or AP_FP_Greater_Eq(X[I],1); Inc(I); end; CalculateMV(X, SampleSize, Mean, MeanS, StdDev, StdDevS); if AP_FP_Neq(MeanS,0) then begin URSigmaErr := Max(URSigmaErr, AbsReal((Mean-0.5)/MeanS)); end else begin URErrors := True; end; if AP_FP_Neq(StdDevS,0) then begin URSigmaErr := Max(URSigmaErr, AbsReal((StdDev-Sqrt(AP_Double(1)/12))/StdDevS)); end else begin URErrors := True; end; URErrors := URErrors or AP_FP_Greater(URSigmaErr,SigmaThreshold); // // Test HQRNDRandomize() and integer uniform // UnsetState(State); HQRNDRandomize(State); UIErrors := False; UISigmaErr := 0; N:=2; while N<=10 do begin I:=0; while I<=SampleSize-1 do begin X[I] := HQRNDUniformI(N, State); Inc(I); end; I:=0; while I<=SampleSize-1 do begin UIErrors := UIErrors or AP_FP_Less(X[I],0) or AP_FP_Greater_Eq(X[I],N); Inc(I); end; CalculateMV(X, SampleSize, Mean, MeanS, StdDev, StdDevS); if AP_FP_Neq(MeanS,0) then begin UISigmaErr := Max(UISigmaErr, AbsReal((Mean-0.5*(N-1))/MeanS)); end else begin UIErrors := True; end; if AP_FP_Neq(StdDevS,0) then begin UISigmaErr := Max(UISigmaErr, AbsReal((StdDev-Sqrt((AP_Sqr(N)-1)/12))/StdDevS)); end else begin UIErrors := True; end; Inc(N); end; UIErrors := UIErrors or AP_FP_Greater(UISigmaErr,SigmaThreshold); // // Special 'close-to-limit' test on uniformity of integers // (straightforward implementation like 'RND mod N' will return // non-uniform numbers for N=2/3*LIMIT) // UnsetState(State); HQRNDRandomize(State); UIErrors := False; UISigmaErr := 0; N := Round(2.0/3.0*2147483563.0); I:=0; while I<=SampleSize-1 do begin X[I] := HQRNDUniformI(N, State); Inc(I); end; I:=0; while I<=SampleSize-1 do begin UIErrors := UIErrors or AP_FP_Less(X[I],0) or AP_FP_Greater_Eq(X[I],N); Inc(I); end; CalculateMV(X, SampleSize, Mean, MeanS, StdDev, StdDevS); if AP_FP_Neq(MeanS,0) then begin UISigmaErr := Max(UISigmaErr, AbsReal((Mean-0.5*(N-1))/MeanS)); end else begin UIErrors := True; end; if AP_FP_Neq(StdDevS,0) then begin UISigmaErr := Max(UISigmaErr, AbsReal((StdDev-Sqrt((AP_Sqr(N)-1)/12))/StdDevS)); end else begin UIErrors := True; end; UIErrors := UIErrors or AP_FP_Greater(UISigmaErr,SigmaThreshold); // // Test normal // UnsetState(State); HQRNDRandomize(State); NormErrors := False; NormSigmaErr := 0; I := 0; while I<SampleSize do begin HQRNDNormal2(State, R1, R2); X[I] := R1; if I+1<SampleSize then begin X[I+1] := R2; end; I := I+2; end; CalculateMV(X, SampleSize, Mean, MeanS, StdDev, StdDevS); if AP_FP_Neq(MeanS,0) then begin NormSigmaErr := Max(NormSigmaErr, AbsReal((Mean-0)/MeanS)); end else begin NormErrors := True; end; if AP_FP_Neq(StdDevS,0) then begin NormSigmaErr := Max(NormSigmaErr, AbsReal((StdDev-1)/StdDevS)); end else begin NormErrors := True; end; NormErrors := NormErrors or AP_FP_Greater(NormSigmaErr,SigmaThreshold); // // Test exponential // UnsetState(State); HQRNDRandomize(State); ExpErrors := False; ExpSigmaErr := 0; Lambda := 2+5*RandomReal; I:=0; while I<=SampleSize-1 do begin X[I] := HQRNDExponential(Lambda, State); Inc(I); end; I:=0; while I<=SampleSize-1 do begin UIErrors := UIErrors or AP_FP_Less(X[I],0); Inc(I); end; CalculateMV(X, SampleSize, Mean, MeanS, StdDev, StdDevS); if AP_FP_Neq(MeanS,0) then begin ExpSigmaErr := Max(ExpSigmaErr, AbsReal((Mean-1.0/Lambda)/MeanS)); end else begin ExpErrors := True; end; if AP_FP_Neq(StdDevS,0) then begin ExpSigmaErr := Max(ExpSigmaErr, AbsReal((StdDev-1.0/Lambda)/StdDevS)); end else begin ExpErrors := True; end; ExpErrors := ExpErrors or AP_FP_Greater(ExpSigmaErr,SigmaThreshold); // // Final report // WasErrors := SeedErrors or URErrors or UIErrors or NormErrors or ExpErrors; if not Silent then begin Write(Format('RNG TEST'#13#10'',[])); Write(Format('SEED TEST: ',[])); if not SeedErrors then begin Write(Format('OK'#13#10'',[])); end else begin Write(Format('FAILED'#13#10'',[])); end; Write(Format('UNIFORM CONTINUOUS: ',[])); if not URErrors then begin Write(Format('OK'#13#10'',[])); end else begin Write(Format('FAILED'#13#10'',[])); end; Write(Format('UNIFORM INTEGER: ',[])); if not UIErrors then begin Write(Format('OK'#13#10'',[])); end else begin Write(Format('FAILED'#13#10'',[])); end; Write(Format('NORMAL: ',[])); if not NormErrors then begin Write(Format('OK'#13#10'',[])); end else begin Write(Format('FAILED'#13#10'',[])); end; Write(Format('EXPONENTIAL: ',[])); if not ExpErrors then begin Write(Format('OK'#13#10'',[])); end else begin Write(Format('FAILED'#13#10'',[])); end; if WasErrors then begin Write(Format('TEST SUMMARY: FAILED'#13#10'',[])); end else begin Write(Format('TEST SUMMARY: PASSED'#13#10'',[])); end; Write(Format(''#13#10''#13#10'',[])); end; Result := not WasErrors; end; (************************************************************************* Unsets HQRNDState structure *************************************************************************) procedure UnsetState(var State : HQRNDState); begin State.S1 := 0; State.S2 := 0; State.V := 0; State.MagicV := 0; end; (************************************************************************* Silent unit test *************************************************************************) function testhqrndunit_test_silent():Boolean; begin Result := TestHQRND(True); end; (************************************************************************* Unit test *************************************************************************) function testhqrndunit_test():Boolean; begin Result := TestHQRND(False); end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs, uROClient, uROClientIntf, uROServer, uROBinMessage, uROIndyTCPServer; type TICBCService = class(TService) ROMessage: TROBinMessage; ROServer: TROIndyTCPServer; procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); procedure ServicePause(Sender: TService; var Paused: Boolean); procedure ServiceContinue(Sender: TService; var Continued: Boolean); procedure ServiceCreate(Sender: TObject); procedure ServiceDestroy(Sender: TObject); private { Private declarations } public function GetServiceController: TServiceController; override; { Public declarations } end; var ICBCService: TICBCService; implementation uses u_Func; {$R *.dfm} procedure ServiceController(CtrlCode: DWord); stdcall; begin ICBCService.Controller(CtrlCode); end; function TICBCService.GetServiceController: TServiceController; begin Result := ServiceController; end; procedure TICBCService.ServiceStart(Sender: TService; var Started: Boolean); begin RoServer.Active := true; end; procedure TICBCService.ServiceStop(Sender: TService; var Stopped: Boolean); begin RoServer.Active := false; end; procedure TICBCService.ServicePause(Sender: TService; var Paused: Boolean); begin RoServer.Active := false; end; procedure TICBCService.ServiceContinue(Sender: TService; var Continued: Boolean); begin RoServer.Active := true; end; procedure TICBCService.ServiceCreate(Sender: TObject); begin LoadCfg(); RoServer.Port:=U_SvrPort; U_ICBCCtl := TICBCCtlAPI.Create(self); end; procedure TICBCService.ServiceDestroy(Sender: TObject); begin U_ICBCCtl.Free; end; end.
unit CpuUnit; interface uses Windows, SysUtils; // Call CollectCPUData to refresh information about CPU usage procedure CollectCPUData; // Call it to obtain the number of CPU's in the system function GetCPUCount: integer; // Call it to obtain the % of usage for given CPU function GetCPUUsage(Index: integer): double; // For Win9x only: call it to stop CPU usage monitoring and free system resources procedure ReleaseCPUData; implementation type PInt64 = ^TInt64; TInt64 = int64; type TPERF_DATA_BLOCK = record Signature: array[0..4 - 1] of WCHAR; LittleEndian: DWORD; Version: DWORD; Revision: DWORD; TotalByteLength: DWORD; HeaderLength: DWORD; NumObjectTypes: DWORD; DefaultObject: longint; SystemTime: TSystemTime; Reserved: DWORD; PerfTime: TInt64; PerfFreq: TInt64; PerfTime100nSec: TInt64; SystemNameLength: DWORD; SystemNameOffset: DWORD; end; PPERF_DATA_BLOCK = ^TPERF_DATA_BLOCK; TPERF_OBJECT_TYPE = record TotalByteLength: DWORD; DefinitionLength: DWORD; HeaderLength: DWORD; ObjectNameTitleIndex: DWORD; ObjectNameTitle: LPWSTR; ObjectHelpTitleIndex: DWORD; ObjectHelpTitle: LPWSTR; DetailLevel: DWORD; NumCounters: DWORD; DefaultCounter: longint; NumInstances: longint; CodePage: DWORD; PerfTime: TInt64; PerfFreq: TInt64; end; PPERF_OBJECT_TYPE = ^TPERF_OBJECT_TYPE; type TPERF_COUNTER_DEFINITION = record ByteLength: DWORD; CounterNameTitleIndex: DWORD; CounterNameTitle: LPWSTR; CounterHelpTitleIndex: DWORD; CounterHelpTitle: LPWSTR; DefaultScale: longint; DetailLevel: DWORD; CounterType: DWORD; CounterSize: DWORD; CounterOffset: DWORD; end; PPERF_COUNTER_DEFINITION = ^TPERF_COUNTER_DEFINITION; TPERF_COUNTER_BLOCK = record ByteLength: DWORD; end; PPERF_COUNTER_BLOCK = ^TPERF_COUNTER_BLOCK; TPERF_INSTANCE_DEFINITION = record ByteLength: DWORD; ParentObjectTitleIndex: DWORD; ParentObjectInstance: DWORD; UniqueID: longint; NameOffset: DWORD; NameLength: DWORD; end; PPERF_INSTANCE_DEFINITION = ^TPERF_INSTANCE_DEFINITION; type TInt64F = TInt64; type FInt64 = TInt64F; Int64D = TInt64; //------------------------------------------------------------------------------ const Processor_IDX_Str = '238'; Processor_IDX = 238; CPUUsageIDX = 6; type AInt64F = array[0..$FFFF] of TInt64F; PAInt64F = ^AInt64F; var _PerfData: PPERF_DATA_BLOCK; _BufferSize: integer; _POT: PPERF_OBJECT_TYPE; _PCD: PPerf_Counter_Definition; _ProcessorsCount: integer; _Counters: PAInt64F; _PrevCounters: PAInt64F; _SysTime: TInt64F; _PrevSysTime: TInt64F; _IsWinNT: boolean; _W9xCollecting: boolean; _W9xCpuUsage: DWORD; _W9xCpuKey: HKEY; //------------------------------------------------------------------------------ function GetCPUCount: integer; begin if _IsWinNT then begin if _ProcessorsCount < 0 then CollectCPUData; Result := _ProcessorsCount; end else begin Result := 1; end; end; //------------------------------------------------------------------------------ procedure ReleaseCPUData; var H: HKEY; R: DWORD; dwDataSize, dwType: DWORD; begin if _IsWinNT then exit; if not _W9xCollecting then exit; _W9xCollecting := False; RegCloseKey(_W9xCpuKey); R := RegOpenKeyEx(HKEY_DYN_DATA, 'PerfStats\StopStat', 0, KEY_ALL_ACCESS, H); if R <> ERROR_SUCCESS then exit; dwDataSize := sizeof(DWORD); RegQueryValueEx(H, 'KERNEL\CPUUsage', nil, @dwType, PBYTE(@_W9xCpuUsage), @dwDataSize); RegCloseKey(H); end; //------------------------------------------------------------------------------ function GetCPUUsage(Index: integer): double; begin if _IsWinNT then begin if _ProcessorsCount < 0 then CollectCPUData; if (Index >= _ProcessorsCount) or (Index < 0) then raise Exception.Create('CPU Ë÷Òý³¬³ö·¶Î§'); if _PrevSysTime = _SysTime then Result := 0 else Result := 1 - (_Counters[index] - _PrevCounters[index]) / (_SysTime - _PrevSysTime); end else begin if Index <> 0 then raise Exception.Create('CPU Ë÷Òý³¬³ö·¶Î§'); if not _W9xCollecting then CollectCPUData; Result := _W9xCpuUsage / 100; end; end; var VI: TOSVERSIONINFO; //------------------------------------------------------------------------------ procedure CollectCPUData; var BS: integer; i: integer; _PCB_Instance: PPERF_COUNTER_BLOCK; _PID_Instance: PPERF_INSTANCE_DEFINITION; ST: TFileTime; H: HKEY; R: DWORD; dwDataSize, dwType: DWORD; begin if _IsWinNT then begin BS := _BufferSize; while RegQueryValueEx(HKEY_PERFORMANCE_DATA, Processor_IDX_Str, nil, nil, PByte(_PerfData), @BS) = ERROR_MORE_DATA do begin // Get a buffer that is big enough. Inc(_BufferSize, $1000); BS := _BufferSize; ReallocMem(_PerfData, _BufferSize); end; // Locate the performance object _POT := PPERF_OBJECT_TYPE(DWORD(_PerfData) + _PerfData.HeaderLength); for i := 1 to _PerfData.NumObjectTypes do begin if _POT.ObjectNameTitleIndex = Processor_IDX then Break; _POT := PPERF_OBJECT_TYPE(DWORD(_POT) + _POT.TotalByteLength); end; // Check for success if _POT.ObjectNameTitleIndex <> Processor_IDX then raise Exception.Create( 'Unable to locate the "Processor" performance object'); if _ProcessorsCount < 0 then begin _ProcessorsCount := _POT.NumInstances; GetMem(_Counters, _ProcessorsCount * SizeOf(TInt64)); GetMem(_PrevCounters, _ProcessorsCount * SizeOf(TInt64)); end; // Locate the "% CPU usage" counter definition _PCD := PPERF_Counter_DEFINITION(DWORD(_POT) + _POT.HeaderLength); for i := 1 to _POT.NumCounters do begin if _PCD.CounterNameTitleIndex = CPUUsageIDX then break; _PCD := PPERF_COUNTER_DEFINITION(DWORD(_PCD) + _PCD.ByteLength); end; // Check for success if _PCD.CounterNameTitleIndex <> CPUUsageIDX then raise Exception.Create( 'Unable to locate the "% of CPU usage" performance counter'); // Collecting coutners _PID_Instance := PPERF_INSTANCE_DEFINITION(DWORD(_POT) + _POT.DefinitionLength); for i := 0 to _ProcessorsCount - 1 do begin _PCB_Instance := PPERF_COUNTER_BLOCK(DWORD(_PID_Instance) + _PID_Instance.ByteLength); _PrevCounters[i] := _Counters[i]; _Counters[i] := FInt64(PInt64(DWORD(_PCB_Instance) + _PCD.CounterOffset)^); _PID_Instance := PPERF_INSTANCE_DEFINITION(DWORD(_PCB_Instance) + _PCB_Instance.ByteLength); end; _PrevSysTime := _SysTime; SystemTimeToFileTime(_PerfData.SystemTime, ST); _SysTime := FInt64(TInt64(ST)); end else begin if not _W9xCollecting then begin R := RegOpenKeyEx(HKEY_DYN_DATA, 'PerfStats\StartStat', 0, KEY_ALL_ACCESS, H); if R <> ERROR_SUCCESS then raise Exception.Create('Unable to start performance monitoring'); dwDataSize := sizeof(DWORD); RegQueryValueEx(H, 'KERNEL\CPUUsage', nil, @dwType, PBYTE(@_W9xCpuUsage), @dwDataSize); RegCloseKey(H); R := RegOpenKeyEx(HKEY_DYN_DATA, 'PerfStats\StatData', 0, KEY_READ, _W9xCpuKey); if R <> ERROR_SUCCESS then raise Exception.Create('Unable to read performance data'); _W9xCollecting := True; end; dwDataSize := sizeof(DWORD); RegQueryValueEx(_W9xCpuKey, 'KERNEL\CPUUsage', nil, @dwType, PBYTE(@_W9xCpuUsage), @dwDataSize); end; end; initialization _ProcessorsCount := -1; _BufferSize := $2000; _PerfData := AllocMem(_BufferSize); VI.dwOSVersionInfoSize := SizeOf(VI); if not GetVersionEx(VI) then raise Exception.Create('Can''t get the Windows version'); _IsWinNT := VI.dwPlatformId = VER_PLATFORM_WIN32_NT; finalization ReleaseCPUData; FreeMem(_PerfData); end.
{ *************************************************************************** } { } { Kylix and Delphi Cross-Platform Visual Component Library } { } { Copyright (c) 1995, 2001 Borland Software Corporation } { } { *************************************************************************** } unit FMTBcd; interface uses SysUtils, Variants; const MaxStringDigits = 100; _NoDecimal = -255; _DefaultDecimals = 10; { From DB.pas } MaxFMTBcdFractionSize = 64; // max supported by Midas MaxFMTBcdDigits = 32; // max supported by Midas DefaultFMTBcdScale = 6; MaxBcdPrecision = 18; MaxBcdScale = 4; type PBcd = ^TBcd; TBcd = packed record Precision: Byte; { 1..64 } SignSpecialPlaces: Byte; { Sign:1, Special:1, Places:6 } Fraction: packed array [0..31] of Byte; { BCD Nibbles, 00..99 per Byte, high Nibble 1st } end; { Exception classes } EBcdException = class(Exception); EBcdOverflowException = class(EBcdException); { Utility functions for TBcd access } function BcdPrecision(const Bcd: TBcd): Word; function BcdScale(const Bcd: TBcd): Word; function IsBcdNegative(const Bcd: TBcd): Boolean; { Bcd Arithmetic} procedure BcdAdd(const bcdIn1, bcdIn2: TBcd; var bcdOut: TBcd); procedure BcdSubtract(const bcdIn1, bcdIn2: TBcd; var bcdOut: TBcd); // Returns True if successful, False if Int Digits needed to be truncated function NormalizeBcd(const InBcd: TBcd; var OutBcd: TBcd; const Prec, Scale: Word): Boolean; procedure BcdMultiply(const bcdIn1, bcdIn2: TBcd; var bcdOut: TBcd); overload; procedure BcdMultiply(const bcdIn: TBcd; const DoubleIn: Double; var bcdOut: TBcd); overload; procedure BcdMultiply(const bcdIn: TBcd; const StringIn: string; var bcdOut: TBcd); overload; procedure BcdMultiply(StringIn1, StringIn2: string; var bcdOut: TBcd); overload; procedure BcdDivide(Dividend, Divisor: string; var bcdOut: TBcd); overload; procedure BcdDivide(const Dividend, Divisor: TBcd; var bcdOut: TBcd); overload; procedure BcdDivide(const Dividend: TBcd; const Divisor: Double; var bcdOut: TBcd); overload; procedure BcdDivide(const Dividend: TBcd; const Divisor: string; var bcdOut: TBcd); overload; { TBcd variant creation utils } procedure VarFMTBcdCreate(var ADest: Variant; const ABcd: TBcd); overload; function VarFMTBcdCreate: Variant; overload; function VarFMTBcdCreate(const AValue: string; Precision, Scale: Word): Variant; overload; function VarFMTBcdCreate(const AValue: Double; Precision: Word = 18; Scale: Word = 4): Variant; overload; function VarFMTBcdCreate(const ABcd: TBcd): Variant; overload; function VarIsFMTBcd(const AValue: Variant): Boolean; overload; function VarFMTBcd: TVarType; // convert String/Double/Integer to BCD struct function StrToBcd(const AValue: string): TBcd; function TryStrToBcd(const AValue: string; var Bcd: TBcd): Boolean; function DoubleToBcd(const AValue: Double): TBcd; overload; procedure DoubleToBcd(const AValue: Double; var bcd: TBcd); overload; function IntegerToBcd(const AValue: Integer): TBcd; function VarToBcd(const AValue: Variant): TBcd; { From DB.pas } function CurrToBCD(const Curr: Currency; var BCD: TBcd; Precision: Integer = 32; Decimals: Integer = 4): Boolean; // Convert Bcd struct to string/Double/Integer function BcdToStr(const Bcd: TBcd): string; overload; function BcdToDouble(const Bcd: TBcd): Double; function BcdToInteger(const Bcd: TBcd; Truncate: Boolean = False): Integer; { From DB.pas } function BCDToCurr(const BCD: TBcd; var Curr: Currency): Boolean; // Formatting Bcd as string function BcdToStrF(const Bcd: TBcd; Format: TFloatFormat; const Precision, Digits: Integer): string; function FormatBcd(const Format: string; Bcd: TBcd): string; function BcdCompare(const bcd1, bcd2: TBcd): Integer; const NullBcd: TBcd = (Precision: 0; SignSpecialPlaces: 0; Fraction: (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)); implementation uses VarUtils, SysConst, DBConsts, TypInfo, Math, Classes; type { TFMTBcdVariantType } TFMTBcdVariantType = class(TPublishableVariantType) protected function LeftPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; override; function RightPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; override; function GetInstance(const V: TVarData): TObject; override; public procedure Clear(var V: TVarData); override; procedure Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); override; procedure Cast(var Dest: TVarData; const Source: TVarData); override; procedure CastTo(var Dest: TVarData; const Source: TVarData; const VarType: TVarType); override; procedure BinaryOp(var Left: TVarData; const Right: TVarData; const Operator: TVarOp); override; procedure Compare(const Left, Right: TVarData; var Relationship: TVarCompareResult); override; end; var { FMTBcd that the complex variant points to } FMTBcdVariantType: TFMTBcdVariantType = nil; type { TFMTBcdData } TFMTBcdData = class(TPersistent) private FBcd: TBcd; function GetAsCurrency: Currency; function GetAsDouble: Double; function GetAsInteger: Integer; function GetAsString: string; function GetAsSmallInt: SmallInt; procedure SetAsCurrency(const Value: Currency); procedure SetAsDouble(const Value: Double); procedure SetAsInteger(const Value: Integer); procedure SetAsSmallInt(const Value: SmallInt); procedure SetAsString(const Value: string); public // The many ways to create a variant constructor Create(const AValue: Integer); overload; constructor Create(const AValue: Double; Precision, Scale: Word); overload; constructor Create(const AValue: Currency); overload; constructor Create(const AText: string; Precision, Scale: Word); overload; constructor Create(const ABcd: TBcd); overload; constructor Create(const ASource: TFMTBcdData); overload; // Access to the private bits property Bcd: TBcd read FBcd write FBcd; // Non-destructive operations function Compare(const Value: TFMTBcdData): TVarCompareResult; // Destructive operations procedure DoAdd(const Value: TBcd); overload; procedure DoAdd(const AFMTBcd: TFMTBcdData); overload; procedure DoSubtract(const Value: TBcd); overload; procedure DoSubtract(const AFMTBcd: TFMTBcdData); overload; procedure DoMultiply(const ABcdData: TFMTBcdData); overload; procedure DoDivide(const ABcdData: TFMTBcdData); overload; published // Conversion property AsCurrency: Currency read GetAsCurrency write SetAsCurrency; property AsDouble: Double read GetAsDouble write SetAsDouble; property AsInteger: Integer read GetAsInteger write SetAsInteger; property AsSmallInt: SmallInt read GetAsSmallInt write SetAsSmallInt; property AsString: string read GetAsString write SetAsString; end; { Helper record that helps crack open TFMTBcdObject } TFMTBcdVarData = packed record VType: TVarType; Reserved1, Reserved2, Reserved3: Word; VBcd: TFMTBcdData; Reserved4: LongWord; end; procedure BcdErrorFmt(const Message, BcdAsString: string); begin raise EBcdException.Create(Format(Message, [BcdAsString])); end; procedure BcdError(const Message: string); begin raise EBcdException.Create(Message); end; procedure OverflowError(const Message: string); begin raise EBcdOverflowException.Create(Message); end; { TFMTBcdData } procedure TFMTBcdData.DoAdd(const Value: TBcd); var NewBcd: TBcd; begin BcdAdd(Self.Bcd, Value, NewBcd); Self.Bcd := NewBcd; end; procedure TFMTBcdData.DoAdd(const AFMTBcd: TFMTBcdData); begin DoAdd(AFMTBcd.Bcd); end; procedure TFMTBcdData.DoSubtract(const Value: TBcd); var NewBcd: TBcd; begin BcdSubtract(Self.Bcd, Value, NewBcd); Self.Bcd := NewBcd; end; procedure TFMTBcdData.DoSubtract(const AFMTBcd: TFMTBcdData); begin DoSubtract(AFMTBcd.Bcd); end; procedure TFMTBcdData.DoMultiply(const ABcdData: TFMTBcdData); var ABcd: TBcd; begin BcdMultiply(Self.Bcd, ABcdData.Bcd, ABcd); Self.Bcd := ABcd; end; procedure TFMTBcdData.DoDivide(const ABcdData: TFMTBcdData); var ABcd: TBcd; begin ABcd.signSpecialPlaces := Byte(Max((ABcdData.FBcd.signSpecialPlaces and 63), (Self.FBcd.signSpecialPlaces and 63))); BcdDivide(Self.Bcd, ABcdData.Bcd, ABcd); Self.Bcd := ABcd; end; function TFMTBcdData.Compare(const Value: TFMTBcdData): TVarCompareResult; begin Result := TVarCompareResult(BcdCompare(Self.FBcd, Value.FBcd)+1); end; function TFMTBcdData.GetAsString: string; begin Result := BcdToStr(Self.FBcd); end; function TFMTBcdData.GetAsDouble: Double; begin Result := StrToFloat(BcdToStr(Self.FBcd)); end; function TFMTBcdData.GetAsInteger: Integer; begin Result := StrToInt(BcdToStr(Self.FBcd)); end; function TFMTBcdData.GetAsSmallInt: SmallInt; begin Result := SmallInt(GetAsInteger); end; function TFMTBcdData.GetAsCurrency: Currency; begin BCDToCurr(Self.FBcd, Result); end; procedure TFMTBcdData.SetAsString(const Value: string); begin FBcd := StrToBcd(Value); end; procedure TFMTBcdData.SetAsDouble(const Value: Double); begin FBcd := StrToBcd(FloatToStr(Value)); end; procedure TFMTBcdData.SetAsInteger(const Value: Integer); begin FBcd := StrToBcd(IntToStr(Value)); end; procedure TFMTBcdData.SetAsSmallInt(const Value: SmallInt); begin SetAsInteger(Integer(Value)); end; procedure TFMTBcdData.SetAsCurrency(const Value: Currency); begin CurrToBcd(Value, FBcd); end; constructor TFMTBcdData.Create(const ABcd: TBcd); begin inherited Create; Move(ABcd, FBcd, SizeOf(TBcd)); end; constructor TFMTBcdData.Create(const AValue: Integer); begin Create(IntegerToBcd(AValue)); end; constructor TFMTBcdData.Create(const AValue: Double; Precision, Scale: Word); var ABcd, OutBcd: TBcd; begin ABcd := StrToBcd(FloatToStr(AValue)); if not NormalizeBcd(ABcd, OutBcd, Precision, Scale) then OverflowError(SBcdOverflow); Create(OutBcd); end; constructor TFMTBcdData.Create(const AValue: Currency); var OutBcd: TBcd; begin CurrToBcd(AValue, OutBcd); Create(OutBcd); end; constructor TFMTBcdData.Create(const AText: string; Precision, Scale: Word); var ABcd, OutBcd: TBcd; begin ABcd := StrToBcd(AText); if not NormalizeBcd(ABcd,OutBcd,Precision,Scale) then OverflowError(SBcdOverflow); Create(OutBcd); end; constructor TFMTBcdData.Create(const ASource: TFMTBcdData); begin Create(aSource.Bcd); end; { TFMTBcdVariantType } procedure TFMTBcdVariantType.Clear(var V: TVarData); begin V.VType := varEmpty; FreeAndNil(TFMTBcdVarData(V).VBcd); end; procedure TFMTBcdVariantType.Cast(var Dest: TVarData; const Source: TVarData); const cBooleanArray: array [Boolean] of Integer = (0, -1); var vTemp: TVarData; begin VarDataInit(vTemp); VarDataCopyNoInd(vTemp, Source); try {$RANGECHECKS ON} case vTemp.VType of varSmallInt: TFMTBcdVarData(Dest).VBcd := TFMTBcdData.Create(vTemp.VSmallInt); varInteger: TFMTBcdVarData(Dest).VBcd := TFMTBcdData.Create(vTemp.VInteger); varSingle: TFMTBcdVarData(Dest).VBcd := TFMTBcdData.Create; varDouble: TFMTBcdVarData(Dest).VBcd := TFMTBcdData.Create(vTemp.VDouble, 32, 8); varCurrency: TFMTBcdVarData(Dest).VBcd := TFMTBcdData.Create(vTemp.VCurrency); varOleStr: TFMTBcdVarData(Dest).VBcd := TFMTBcdData.Create(vTemp.VOleStr, 32, 8); varString: TFMTBcdVarData(Dest).VBcd := TFMTBcdData.Create(string(vTemp.VString^), 32, 8); varNull: TFMTBcdVarData(Dest).VBcd := TFMTBcdData.Create(NullBcd); else RaiseCastError; end; {$RANGECHECKS OFF} finally VarDataClear(vTemp); end; Dest.VType := VarType; end; procedure TFMTBcdVariantType.CastTo(var Dest: TVarData; const Source: TVarData; const VarType: TVarType); var vTemp: TVarData; begin VarDataInit(vTemp); VarDataCopyNoInd(vTemp, Source); try {$RANGECHECKS ON} case VarType of varSmallInt: Dest.VSmallInt := SmallInt(BcdToInteger(TFMTBcdVarData(vTemp).VBcd.Bcd)); varInteger: Dest.VInteger := BcdToInteger(TFMTBcdVarData(vTemp).VBcd.Bcd); varSingle: Dest.VSingle := BcdToDouble(TFMTBcdVarData(vTemp).VBcd.Bcd); varDouble: Dest.VDouble := BcdToDouble(TFMTBcdVarData(vTemp).VBcd.Bcd); varCurrency: Dest.VCurrency := BcdToDouble(TFMTBcdVarData(vTemp).VBcd.Bcd); varOleStr: Dest.VOleStr := StringToOleStr(TFMTBcdVarData(vTemp).VBcd.AsString); varString: string(Dest.VString) := TFMTBcdVarData(vTemp).VBcd.AsString; else RaiseCastError; end; {$RANGECHECKS OFF} finally VarDataClear(vTemp); end; Dest.VType := VarType; end; procedure TFMTBcdVariantType.Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); begin if Indirect and VarDataIsByRef(Source) then VarDataCopyNoInd(Dest, Source) else with TFMTBcdVarData(Dest) do begin VType := VarType; VBcd := TFMTBcdData.Create(TFMTBcdVarData(Source).VBcd); end; end; procedure TFMTBcdVariantType.BinaryOp(var Left: TVarData; const Right: TVarData; const Operator: TVarOp); begin case Operator of opAdd: TFMTBcdVarData(Left).VBcd.DoAdd(TFMTBcdVarData(Right).VBcd); opSubtract: TFMTBcdVarData(Left).VBcd.DoSubtract(TFMTBcdVarData(Right).VBcd); opMultiply: TFMTBcdVarData(Left).VBcd.DoMultiply(TFMTBcdVarData(Right).VBcd); opDivide: TFMTBcdVarData(Left).VBcd.DoDivide(TFMTBcdVarData(Right).VBcd); else RaiseInvalidOp; end; end; function TFMTBcdVariantType.GetInstance(const V: TVarData): TObject; begin Result := TFMTBcdVarData(V).VBcd; end; procedure TFMTBcdVariantType.Compare(const Left, Right: TVarData; var Relationship: TVarCompareResult); begin Relationship := TFMTBcdVarData(Left).VBcd.Compare(TFMTBcdVarData(Right).VBcd); end; function TFMTBcdVariantType.LeftPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; begin RequiredVarType := VarType; // fine but convert it to FMTBcd case V.VType of varNull, varSmallInt, varInteger, varSingle, varDouble, varCurrency, varOleStr, varBoolean, varByte, varString: Result := True; else Result := False; end; if V.VType = VarType then Result := True; end; function TFMTBcdVariantType.RightPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; begin RequiredVarType := VarType; // fine but convert it to FMTBcd case V.VType of varNull, varSmallInt, varInteger, varSingle, varDouble, varCurrency, varOleStr, varBoolean, varByte, varString: Result := True; else Result := False; end; if V.VType = VarType then Result := True; end; { FMTBcd variant create utils } function VarFMTBcdCreate(const AValue: string; Precision, Scale: Word): Variant; overload; begin VarClear(Result); TFMTBcdVarData(Result).VType := FMTBcdVariantType.VarType; TFMTBcdVarData(Result).VBcd := TFMTBcdData.Create(AValue, Precision, Scale); end; function VarFMTBcdCreate(const AValue: Double; Precision, Scale: Word): Variant; overload; begin VarClear(Result); TFMTBcdVarData(Result).VType := FMTBcdVariantType.VarType; TFMTBcdVarData(Result).VBcd := TFMTBcdData.Create(AValue, Precision, Scale); end; (*function VarFMTBcdCreate(const AValue: Integer; Precision: Word = 10; Scale: Word = 0): Variant; overload; begin VarClear(Result); TFMTBcdVarData(Result).VType := FMTBcdVariantType.VarType; TFMTBcdVarData(Result).VBcd := TFMTBcdData.Create(AValue); end;*) procedure VarFMTBcdCreate(var ADest: Variant; const ABcd: TBcd); overload; begin VarClear(ADest); TFMTBcdVarData(ADest).VType := FMTBcdVariantType.VarType; TFMTBcdVarData(ADest).VBcd := TFMTBcdData.Create(ABcd); end; function VarFMTBcdCreate: Variant; overload; begin VarFMTBcdCreate(Result, NullBcd); end; function VarFMTBcdCreate(const ABcd: TBcd): Variant; begin VarFMTBcdCreate(Result, ABcd); end; function VarIsFMTBcd(const AValue: Variant): Boolean; begin Result := (TVarData(AValue).VType = FMTBcdVariantType.VarType); end; function VarFMTBcd: TVarType; begin Result := FMTBcdVariantType.VarType; end; function StrToBcd(const AValue: string): TBcd; var Success: Boolean; begin Success := TryStrToBcd(AValue, Result); if not Success then BcdErrorFmt(SInvalidBcdValue, AValue); end; procedure DoubleToBcd(const AValue: Double; var bcd: TBcd); overload; begin bcd := StrToBcd(FloatToStr(AValue)); end; function DoubleToBcd(const AValue: Double): TBcd; overload; begin DoubleToBcd(AValue, Result); end; function VarToBcd(const AValue: Variant): TBcd; begin if VarType(AValue) = FMTBcdVariantType.VarType then Result := TFMTBcdVarData(AValue).VBcd.FBcd else Result := TFMTBcdVarData(VarFmtBcdCreate(AValue)).VBcd.FBcd; end; function IntegerToBcd( const AValue: Integer): TBcd; begin Result := StrToBcd(IntToStr(AValue)); end; function BcdToDouble(const Bcd: TBcd): Double; begin Result := StrToFloat(BcdToStr(Bcd)); end; function BcdToInteger(const Bcd: TBcd; Truncate: Boolean = False): Integer; var ABcd: TBcd; begin if (Truncate) and (BcdScale(Bcd) > 0 ) then NormalizeBcd(Bcd,ABcd,Bcd.Precision,0) else ABcd := Bcd; Result := StrToInt(BcdToStr(ABcd)); end; { utility routines } function RoundAt(const Value: string; Position: SmallInt): string; var P, PP: PChar; DecPos: SmallInt; Dot : Char; begin Dot := DecimalSeparator; DecPos := Pos(Dot, Value); // if Value[1] = '-' then Inc(DecPos); if DecPos = 0 then DecPos := Length(Value) else Inc(Position, DecPos); if (Position < (Length(Value) -1)) and (DecPos < Position) then begin PP := PChar(Value) + ((Position -1)); P := PP+1; if Byte(P^) >= 53 then // if '5' or more PP^ := Char(Byte(PP^)+1); while (Position > 0) and ((Byte(PP^) > 57) or (PP^ = Dot)) do // if greater than '9' then begin if PP^ <> Dot then PP^ := '0'; Dec(Position); Dec(PP); if PP^ <> Dot then PP^ := Char(Byte(PP^)+1); end; if Byte(PP^) > 57 then begin PP^ := '0'; Result := '1' + Copy(Value,1,Position -1); end else Result := Copy(Value,1,Position); end else Result := Value; end; function LeftTrim(const Value: string): string; begin Result := Value; while (Length(Result) > 1) and (Result[1] = '0') do Result := Copy(Result, 2, Length(Result) -1); end; function CompareDigits(S1, S2: string): Integer; begin S1 := LeftTrim(S1); if Length(S1) > Length(S2) then Result := 1 else if Length(S2) > Length(S1) then Result := -1 else Result := CompareStr(S1, S2); end; procedure GetValueAndMultiplyOrder(A, B: string; var V, M: string; LA, LB: Integer; var Wid, Len, DecPos: Integer); var DecimalPosA, DecimalPosB: Integer; Dot : Char; begin Dot := DecimalSeparator; DecPos := 0; if CompareDigits(A,B) > 1 then begin V := A; M := B; Wid := LA; Len := LB; end else begin M := A; V := B; Wid := LB; Len := LA; end; // to get rid of GetDecimalPosition DecimalPosA := Pos(Dot, V); DecimalPosB := Pos(Dot, M); if (DecimalPosA = 0) and (DecimalPosB = 0) then DecPos := _NoDecimal else begin if DecimalPosA > 0 then begin V := StringReplace(V, Dot, '', []); DecPos := Wid - DecimalPosA; Dec(Wid); end; if DecimalPosB > 0 then begin M := StringReplace(M, Dot,'',[]); DecPos := DecPos + (Len - DecimalPosB); Dec(Len); end; end; end; function AddChars(V, M: Char; var R: Byte): string; var Value: Byte; begin Value := Byte((Byte(V)-48) + (Byte(M)-48) + R); if Value > 9 then begin Result := Char((Value - 10) + 48); R := Byte(1); end else begin Result := Char(Value + 48); R := Byte(0); end; if Result = '' then Result := '0'; end; function SubtractChars(V, M: Char; var R: Byte): string; var Value: Byte; begin Value := Byte((Byte(V)-48) - ((Byte(M)-48) + R)); if Value > 9 then // Byte is unsigned: values will be between 246-255 begin Result := Char((Value + 10) + 48); R := Byte(1); end else begin Result := Char(Value + 48); R := Byte(0); end; end; function AddStrings(const V, M: string): string; var Digit: string; pV, pM: PChar; // pointer to string A, string B; LenV, LenM, MaxDigits, I, DigitV, DigitM: Integer; R: Byte; // Remainder CV, CM: Char; // char from string A, string B begin if (V = '') or (V = '0') then begin Result := M; Exit; end; if (M = '') or (M = '0') then begin Result := V; Exit; end; R := 0; pV := PChar(V); pM := PChar(M); LenV := Length(V); LenM := Length(M); MaxDigits := Max(LenV, LenM); Result := ''; for I := 1 to MaxDigits do begin DigitV := LenV - I; DigitM := LenM - I; if I <= LenV then CV := pV[DigitV] else CV := '0'; if I <= LenM then CM := pM[DigitM] else CM := '0'; Digit := AddChars(CV, CM, R); Result := Digit + Result; end; if R > 0 then Result := '1' + Result; end; function SubtractStrings(const Value, Minus: string): string; var Digit, V, M: string; pV, pM: PChar; // pointer to string A, string B; LenV, LenM, MaxDigits, I, DigitV, DigitM: Integer; R: Byte; // Remainder CV, CM: Char; // char from string A, string B begin if CompareDigits(Value, Minus) >= 0 then begin V := Value; M := Minus; Result := ''; end else begin M := Value; V := Minus; Result := '-'; end; if (V = '') or (M = '') then begin if V = '' then Result := '-' + M else Result := V; end; if (V = '0') or (M = '0') then begin if M = '0' then Result := V else if V = '0' then Result := '0' else Result := M; Exit; end; R := 0; pV := PChar(V); pM := PChar(M); LenV := Length(V); LenM := Length(M); MaxDigits := Max(LenV, LenM); Result := ''; for I := 1 to MaxDigits do begin DigitV := LenV - I; DigitM := LenM - I; if I <= LenV then CV := pV[DigitV] else CV := '0'; if I <= LenM then CM := pM[DigitM] else CM := '0'; Digit := SubtractChars(CV, CM, R); Result := Digit + Result; end; if Result = '' then Result := '0'; end; function _ShortMultiply(const A, B: string): string; var DecPos,W,L,I: Integer; S, SS, Times: LongWord; pMultiplier: PChar; Value, Multiplier: string; Dot : Char; begin Dot := DecimalSeparator; GetValueAndMultiplyOrder(A, B, Value, Multiplier, Length(A), Length(B), W, L, DecPos); PMultiplier := PChar(Multiplier); Times := 1; S := 0; for I := L - 1 downto 0 do begin SS := LongWord(LongWord((Byte(PMultiplier[I])-Byte(48))) * LongWord(StrToInt(Value)) * Times); S := SS + S; Times := Times * 10; end; Result := IntToStr(S); if DecPos <> _NoDecimal then begin I := Length(Result) - DecPos; if I = 0 then Result := '0' + Dot + Result else if I > 0 then Result := Copy(Result,1, I) + Dot + Copy(Result,I+1,DecPos) else if I < 0 then Result := Dot + StringOfChar('0', -I) + Result; end; end; function StringMultiplyByByte(const Value: string; B: Byte): string; pascal; var L : SmallInt; PValue, PResult: PChar; begin L := Length(Value); PValue := PChar(Value) + (L - 1); // point to end of input string SetLength(Result, L + 1); // allocate, perhaps 1 more byte than needed. PResult := PChar(Result) + L; asm PUSH ECX PUSH EDI PUSH ESI PUSH EBX MOV BH,10 // divisor to get both digits MOV EDI,PResult MOV ESI,PValue MOV CX,L // Store # of digits in Value to CX MOV DX,0 // DX holds remainder, which comes from AH @@1: CMP CX,0 // any more digits: JE @@2 MOV AL,[ESI] // move digit to AL SUB ESI,1 // decrement pointer SUB AL,'0' // convert from char digit to # MUL B // multiply by B: result goes to AX ADD AX,DX // Add Remainder from DL MOV DX,0 // set remainder back to 0 DIV BH // Divide by 10; result goes to AL, remainder to AH MOV DL,AL // move remainder to DL (DH will always 0 here) ADD AH,'0' // convert from # to char digit MOV [EDI],AH // move digit to Result SUB EDI,1 // decrement output pointer SUB CX,1 JMP @@1 @@2: ADD DL,'0' // move '0' or remainder to last MOV [EDI],DL // digit of Result @@3: POP EBX POP ESI POP EDI POP ECX end; if Result[1] = '0' then Result := Copy(Result, 2, Length(Result) -1 ); end; function _LongMultiply(const A, B: string): string; const MaxSmall = 9; var DecPos, W, L, I: Integer; Times, S, SS: string; pMultiplier: PChar; Value, Multiplier: string; T1, T2: Integer; Dot : Char; begin Dot := DecimalSeparator; GetValueAndMultiplyOrder(A, B, Value, Multiplier, Length(A), Length(B), W, L, DecPos); T1 := Length(Value); T2 := Length(Multiplier); pMultiplier := PChar(Multiplier); Times := ''; for I := L-1 downto 0 do begin if W < MaxSmall then SS := IntToStr(LongWord((Byte(PMultiplier[I])-48) * StrToInt(Value))) + Times else SS := StringMultiplyByByte(Value,Byte(PMultiplier[I])-48) + Times; S := AddStrings(SS,S); Times := Times + '0'; end; Result := S; while Result[1] = '0' do Result := Copy(Result, 2, Length(Result) -1); if DecPos <> _NoDecimal then begin I := Length(Result) - DecPos; if I = 0 then Result := '0' + Dot + Result else if I > 0 then Result := Copy(Result,1, I) + Dot + Copy(Result,I+1,DecPos) else if I < 0 then Result := Dot + StringOfChar('0', -I) + Result; if T1 + T2 > 1024 then Result := '' end; end; // Go through 2 strings and determine if total length > MaxDigits function CanUseShort(A, B: PChar; MaxDigits: ShortInt): Boolean; pascal; var Dot: Char; begin Dot := DecimalSeparator; asm PUSH EAX PUSH EBX PUSH ECX PUSH EDX PUSH EDI MOV EDI,A MOV Result,False MOV CL,0 // Flag for A/B MOV CH,0 // Total Digit counter MOV AH,MaxDigits // Max Integer Digits MOV DL,0 // Flag for first char MOV DH,0 // Values of first chars @@1: MOV AL,[EDI] ADD EDI,1 CMP DL,0 // if first char JNE @@2 // then ADD DH,AL // save value to DH MOV DL,1 @@2: CMP AL,0 JE @@3 CMP AL,Dot // if '.' don't count JE @@1 ADD CH,1 JMP @@1 @@3: CMP CL,0 JNE @@4 MOV CL,1 MOV DL,0 MOV EDI,B JMP @@1 @@4: CMP DH,107 JA @@5 ADD AH,1 @@5: CMP CH,AH JA @@6 // if CH > then AH (Max), then Result stays False MOV Result,True // otherwise, it's true. @@6: POP EDI POP EDX POP ECX POP EBX POP EAX end; end; // Return True if S evaluates to 0 function BlankArgument(const S: string): Boolean; var I: Integer; begin Result := True; for I := 1 to Length(S) do if not (S[I] in ['0', '.']) then begin Result := False; break; end; end; function _Multiply(const A, B: string): string; begin if BlankArgument(A) and BlankArgument(B) then Result := '0' else if CanUseShort(PChar(A), PChar(B), 9) then Result := _ShortMultiply(A,B) else Result := _LongMultiply(A,B); end; function NextDigit(const V, D: string; var R: string): string; begin R := V; Result := '0'; while CompareDigits(R, D) >= 0 do begin Result := IntToStr(StrToInt(Result) + 1); R := LeftTrim(SubtractStrings(R, D)); end; end; function AdjustDecimalPosition(const Value: string; DecPos: SmallInt): string; var Dot : Char; begin Dot := DecimalSeparator; Result := Value; while Result[1] = '0' do Result := Copy(Result, 2, length(Result) -1); if DecPos = 0 then Result := '0.' + Result else if DecPos > 0 then Result := '0' + Dot + StringOfChar('0', DecPos) + Result else // DecPos < 0 then begin if -DecPos >= Length(Result) then Result := Result + StringOfChar('0', (-DecPos)-Length(Result)) else if -DecPos < Length(Result) then begin Result := Copy(Result, 1, -DecPos) + Dot + Copy(Result, (-DecPos)+1, Length(Result)); end; end; end; function ValueOverOne(D: string): string; var R: string; V: string; AddZeros, DecimalPos: SmallInt; Dot : Char; begin Dot := DecimalSeparator; DecimalPos := Pos(Dot, D); if DecimalPos > 0 then begin Result := '10'; Dec(DecimalPos,2); // 1/.2 = 5.0; 1/2.2 = .45; if PChar(D)[0]= Dot then begin D := Copy(D, 2, Length(D) -1); while PChar(D)[0] = '0' do begin Result := Result + '0'; // copy back later D := Copy(D, 2, Length(D) -1); Dec(DecimalPos); end; end else D := StringReplace(D, Dot, '', []); end else begin DecimalPos := Length(D) -1; Result := '1'; end; if (D ='1') or (D = '1' + StringOfChar('0', Length(D) -1)) then Result := AdjustDecimalPosition(Result, DecimalPos -1) else begin V := '1'; R := V; AddZeros := Length(V) -1; // for divisor of 12345, add 4 zeros V := V + StringOfChar('0', AddZeros); if CompareDigits(V,D) < 0 then // if still ess add 1 V := V + '0'; Result := ''; while (R <> '0') and (Length(Result) < (MaxFMTBcdFractionSize + AddZeros)) do begin Result := Result + NextDigit(V, D, R); V := R + '0'; end; Result := AdjustDecimalPosition(Result, DecimalPos); end; end; function _LongDivide(A, B: string): string; var Negative: Boolean; begin // save pos/minus info and remove '-' Negative := (PChar(A)[0] <> PChar(B)[0]) and ((PChar(A)[0] = '-') or (PChar(A)[0] = '-')); if PChar(A)[0] = '-' then A := Copy(A, 2, Length(A)-1); if PChar(B)[0] = '-' then B := Copy(B, 2, Length(B)-1); while PChar(A)[0] = '0' do A := Copy(A, 2, Length(A)-1); while PChar(B)[0] = '0' do B := Copy(B, 2, Length(B)-1); Result := ValueOverOne(B); Result := _Multiply(A, Result); if Negative then Result := '-' + Result; end; function _Divide(const A, B: string): string; begin if BlankArgument(A) and BlankArgument(B) then begin if (A = '') or (A = '0') then Result := '0' else BcdError(SDivByZero); end else if B = '1' then Result := A else if B = '-1' then Result := '-' + A else if CompareStr(A,B) = 0 then Result := '1' else Result := _LongDivide(A,B); end; procedure _GetRemainder; asm ADD DL,DH // Add remainder CMP DL,10 // if over 10 JB @@1 MOV DH,1 // then remainder of 1 SUB DL,10 // and subtract 10 from value JMP @@2 @@1: MOV DH,0 // otherwise remainder of 0 @@2: end; procedure _GetSubRemainder; asm SUB DL,DH // Subtract remainder CMP DL,10 // if less than 0 JBE @@1 // MOV DH,1 // then remainder of 1 ADD DL,10 // and ADD 10 to value JMP @@2 @@1: MOV DH,0 // otherwise remainder of 0 @@2: end; procedure _CopyBytes; asm @@1: CMP CL,0 // set # of bytes to copy JBE @@2 // so just LODSB // copy all bytes SUB CL,1 STOSB // from in to out CMP CL,0 JE @@2 JMP @@1 @@2: end; procedure _CopyOddFractions; asm @@1: CMP CL,CH // splitting nibbles: JAE @@4 MOV AH,DL // DL contains last nibble ADD CL,1 CMP CL,CH JNE @@2 MOV AL,0 JMP @@3 @@2: LODSB MOV DL,AL // save off nibble SHR AL,4 // get 1st Nibble of new byte @@3: AND AH,15 // get 2nd Nibble of saved byte SHL AH,4 // make 2nd Nibble of saved 1st Nibble of new OR AH,AL // make 1st Nibble of new 2nd Nibble of new MOV AL,AH STOSB ADD CL,1 JMP @@1 @@4: end; procedure _CopyRestBlank; asm @@1: CMP CL,1 JBE @@2 MOV AL,0 STOSB SUB CL,2 JMP @@1 @@2: end; procedure NormalizeFractions(const pIn: PChar; InPrec, InScale, OutPrec, outScale: ShortInt; pOut: PChar); pascal; asm // setup PUSH ESI PUSH EDI PUSH EBX PUSH ECX PUSH EDX MOV EDI,pOut MOV ESI,pIn MOV CL,OutPrec MOV CH,OutScale CMP CL,InPrec JA @@6 // if OutPrec > InPrec ... CMP CL,InPrec JE @@4 // if OutPrec = InPrec, move to CheckScale MOV AH,InPrec SUB AH,OutPrec MOV CL,InPrec // Case where Output precision is less than input: cut it down @@0: CMP AH,0 JE @@9 LODSB CMP AL,0 JE @@1 MOV [EDI],AL ADD EDI,1 @@1: SUB AH,1 CMP AH,0 JE @@2 SUB AH,1 SUB CL,2 JMP @@0 @@2: MOV DL,AL // save byte to DL: splitting required CMP CH,InScale // CH contains OutScale JBE @@3 MOV CH,InScale // # of digits to store = @@3: ADD CH,OutPrec // Min(InScale,OutScale) + OutPrec MOV CL,0 // nothing stored yet CALL _CopyOddFractions; MOV CL,OutScale CMP CL,InScale JBE @@12 SUB CL,InScale CALL _CopyRestBlank; JMP @@12 @@4: ADD CL,InScale // case where outputsize = input size, so just copy bytes @@5: CALL _CopyBytes // Otherwise, copy only Prec bytes CMP CH,InScale JE @@12 MOV CL,CH CALL _CopyRestBlank JMP @@12 // case where additional blank nibbles to prefixed to Fractions @@6: SUB CL,InPrec @@7: CMP CL,0 JE @@9 SUB CL,1 CMP CL,0 JE @@8 MOV AL,0 // add two blank nibbles STOSB SUB CL,1 JMP @@7 @@8: LODSB MOV DL,AL // save copy of input byte SHR AL,4 // get first nibble OR AL,0 STOSB MOV AL,DL MOV AH,InPrec MOV OutPrec,AH MOV CL,1 // 1 nibble stored already JMP @@2 // even # of fractions to copy @@9: MOV CH,OutScale // CL must be set to scale values to be copies. MOV CL,InPrec CMP CH,InScale JAE @@10 ADD CL,CH JMP @@11 @@10: ADD CL,InScale @@11: CALL _CopyBytes MOV CL,OutPrec CMP CL,InPrec JBE @@12 SUB CL,InPrec CALL _CopyRestBlank; @@12: POP EDX POP ECX POP EBX POP EDI POP ESI end; procedure StrToFraction(pTo: PChar; pFrom: PChar; count: SmallInt); pascal; var Dot: Char; begin Dot := DecimalSeparator; asm // From bytes to nibbles, both left aligned PUSH ESI PUSH EDI PUSH EBX MOV ESI,pFrom // move pFrom to ESI MOV EDI,pTo // move pTo to EDI XOR ECX,ECX // set ECX to 0 MOV CX,count // store count in CX MOV DL,0 // Flag: when to store CLD @@1: LODSB // moves [ESI] into al CMP AL,Dot JE @@4 SUB AL,'0' CMP DL,0 JNE @@2 SHL AL,4 MOV AH,AL JMP @@3 @@2: OR AL,AH // takes AH and ors in AL STOSB // always moves AL into [EDI] @@3: NOT dl // flip all bits @@4: LOOP @@1 // decrements cx and checks if it's 0 CMP DL,0 // are any bytes left unstored? JE @@5 MOV AL,AH // if so, move to al STOSB // and store to [EDI] @@5: POP EBX POP EDI POP ESI end; end; function InvalidBcdString(PValue: PChar): Boolean; var Dot, Comma: Char; P: PChar; begin Dot := DecimalSeparator; Comma := ThousandSeparator; P := PValue; Result := False; while P^ <> #0 do begin if not (P^ in ['0'..'9', '-', Dot, Comma]) then begin Result := True; break; end; Inc(P); end; end; function TryStrToBcd(const AValue: string; var Bcd: TBcd): Boolean; const spaceChars: set of Char = [ ' ', #6, #10, #13, #14]; digits: set of Char = ['0'..'9']; var Neg: Boolean; NumDigits, DecimalPos: Word; pTmp, pSource: PChar; Dot : Char; begin Dot := DecimalSeparator; if InvalidBcdString(PChar(AValue)) then begin Result := False; exit; end; if (AValue = '0') or (AValue = '') then begin Result := True; Bcd.Precision := 8; Bcd.SignSpecialPlaces := 2; pSource := PChar(@Bcd.Fraction); FillChar(PSource^, SizeOf(Bcd.Fraction), 0); Exit end; Result := True; Neg := False; DecimalPos := Pos(Dot, AValue); pSource := pCHAR(AValue); { Strip leading whitespace } while (pSource^ in spaceChars) or (pSource^ = '0') do begin Inc(pSource); if DecimalPos > 0 then Dec(DecimalPos); end; { Strip trailing whitespace } pTmp := @pSource[ StrLen( pSource ) -1 ]; while pTmp^ in spaceChars do begin pTmp^ := #0; Dec(pTmp); end; { Is the number negative? } if pSource^ = '-' then begin Neg := TRUE; if DecimalPos > 0 then Dec(DecimalPos); end; if (pSource^ = '-') or (pSource^ ='+') then Inc(pSource); { Clear structure } pTmp := pCHAR(@Bcd.Fraction); FillChar(pTmp^, SizeOf(Bcd.Fraction), 0); if (pSource[0] = '0') then begin Inc(PSource); // '0.' scenario if DecimalPos > 0 then Dec(DecimalPos); end; NumDigits := StrLen(pSource); if (NumDigits > MaxFMTBcdFractionSize) then begin if (DecimalPos > 0) and (DecimalPos <= MaxFMTBcdFractionSize) then NumDigits := MaxFMTBcdFractionSize // truncate to 64 else begin Bcd.Precision := NumDigits; Exit; end; end; if NumDigits > 0 then StrToFraction(pTmp, pSource, SmallInt(NumDigits)) else begin Bcd.Precision := 10; Bcd.SignSpecialPlaces := 2; end; if DecimalPos > 0 then begin Bcd.Precision := Byte(NumDigits-1); if Neg then Bcd.SignSpecialPlaces := ( 1 shl 7 ) + (BYTE(NumDigits - DecimalPos)) else Bcd.SignSpecialPlaces := ( 0 shl 7 ) + (BYTE(NumDigits - DecimalPos)); end else begin Bcd.Precision := Byte(NumDigits); if Neg then Bcd.SignSpecialPlaces := (1 shl 7) else Bcd.SignSpecialPlaces := (0 shl 7); end; end; function SignificantIntDigits(const pIn: PChar; Digits: Word): Word; pascal; asm PUSH ESI PUSH EBX MOV ESI, pIn MOV CX,Digits // start with all digits CLD @@1: CMP CX,0 // if 0, JE @@3 // then end LODSB // load pIn BYTE into AL and CMP AL,0 // if 0 JNE @@2 SUB CX,1 // then subtract 1 from CX CMP CX,0 // make sure it's not 0 JE @@3 SUB CX,1 // subtract 1 again and JMP @@1 // start again @@2: SHR AL,4 // check last nibble CMP AL,0 // if 0, then JNE @@3 SUB CX,1 // subtract 1 more from CX @@3: MOV Result,CX // Result is CX POP EBX POP ESI end; procedure SubtractNormalizedFractions(const pIn1, pIn2, pOut: PChar; Digits: SmallInt); pascal; var OddFlag: SmallInt; begin asm PUSH ESI PUSH EDI PUSH EBX PUSH ECX PUSH EDX MOV OddFlag,0 // Flag for odd # of Digits MOV CX,Digits MOV DH,0 // Remainder MOV EDI,pOut MOV EBX,pIn1 MOV ESI,pIn2 @@0: CMP CX,2 JBE @@2 ADD EDI,1 ADD ESI,1 ADD EBX,1 SUB CX,1 CMP CX,2 JNE @@1 MOV OddFlag,1 // there are odd # of digits JMP @@2 @@1: SUB CX,1 JMP @@0 @@2: MOV CX,Digits @@3: CMP CX,0 // at end? JE @@5 CMP OddFlag,1 JNE @@12 MOV AH,0 MOV OddFlag,0 JMP @@13 @@12: MOV AL,[ESI] MOV AH,[EBX] AND AL,15 // get last nibble AND AH,15 // values MOV DL,AH SUB DL,AL // SUBTRACT [ESI] FROM [EBX] CALL _GetSubRemainder // get remainder and MOV AH,DL // store in AH SUB CX,1 CMP CX,0 JE @@4 @@13: MOV AL,[ESI] // AH now has last values added MOV DL,[EBX] // so now get SHR AL,4 // first SHR DL,4 // values SUB DL,AL // into DL CALL _GetSubRemainder SHL DL,4 OR DL,AH MOV [EDI],DL SUB EDI,1 SUB ESI,1 SUB EBX,1 SUB CX,1 JMP @@3 @@4: MOV DL,0 // if end is reached on odd nibble OR DL,AH // OR with 0 and flush MOV [EDI],DL @@5: POP EDX POP ECX POP EBX POP EDI POP ESI end; end; procedure AddNormalizedFractions(const pIn1, pIn2, pOut: PChar; Digits: SmallInt); pascal; var OddFlag: SmallInt; begin asm PUSH ESI PUSH EDI PUSH EBX PUSH ECX PUSH EDX MOV CX,Digits MOV DH,0 // Remainder MOV EDI,pOut MOV EBX,pIn1 MOV ESI,pIn2 MOV OddFlag,0 @@0: CMP CX,2 JBE @@2 ADD EDI,1 ADD ESI,1 ADD EBX,1 SUB CX,1 CMP CX,2 JNE @@1 MOV OddFlag,1 JMP @@2 @@1: SUB CX,1 JMP @@0 @@2: MOV CX,Digits @@3: CMP CX,0 // at end? JE @@5 CMP OddFlag,1 JNE @@12 MOV AH,0 MOV OddFlag,0 JMP @@13 @@12: MOV AL,[ESI] MOV AH,[EBX] AND AL,15 // get last nibble AND AH,15 // values MOV DL,AH ADD DL,AL // Add 2 values CALL _GetRemainder // get remainder and MOV AH,DL // store in AH SUB CX,1 CMP CX,0 JE @@4 @@13: MOV AL,[ESI] // AH now has last values added MOV DL,[EBX] // so now get SHR AL,4 // first SHR DL,4 // values ADD DL,AL // into DL CALL _GetRemainder SHL DL,4 OR DL,AH MOV [EDI],DL SUB EDI,1 SUB ESI,1 SUB EBX,1 SUB CX,1 JMP @@3 @@4: MOV DL,0 // if end is reached on odd nibble OR DL,AH // OR with 0 and flush MOV [EDI],DL @@5: POP EDX POP ECX POP EBX POP EDI POP ESI end; end; // compare where both FRACTIONs have same # of Nibbles function CompareNormalizedFractions(const pIn1, pIn2: PChar; Digits1, Digits2: SmallInt): Integer; pascal; asm PUSH ESI PUSH EDI PUSH EBX MOV CX,Digits1 MOV EDI,pIn2 MOV ESI,pIn1 MOV Result,0 // initialize Result to 0 CLD @@1: LODSB // strip leading 0's from input1 CMP AL,0 JNE @@2 SUB CX,2 JMP @@1 @@2: MOV AH,[EDI] // strip leading 0's from input1 INC EDI CMP AH,0 JE @@2 JMP @@4 @@3: CMP CX,0 JE @@9 // no more digits LODSB // load [ESI] into AL MOV AH,[EDI] // load [EDI] into AH INC EDI // advance EDI @@4: CMP AL,ah // start by comparing 2 nibbles at once JNE @@5 SUB CX,1 CMP CX,0 JE @@9 SUB CX,1 JMP @@3 @@5: MOV BL,AH // don't appear to match: MOV AH,AL // put first nibble of SHR AH,4 // input1 into AH, and first nibble MOV BH,BL // of input2 into bh, SHR BH,4 // and them CMP BH,AH // JNE @@6 // CMP CX,0 // make sure we didn't end on odd-nibble JE @@9 MOV AH,AL // it's the 2nd nibble that's different MOV BH,BL // so move 2nd nibble AND AH,15 // for input1 and input2 AND BH,15 // into AH and BH @@6: CMP BH,AH // we know they're not the same JA @@8 @@7: MOV Result,1 // input1 > input2 JMP @@9 @@8: MOV Result,-1 // input2 > input1 @@9: POP EBX POP EDI POP ESI end; function ReverseNegative(SignSpecialPlaces: Byte): Byte; begin if (SignSpecialPlaces and (1 shl 7)) <> 0 then Result := (SignSpecialPlaces and 63) else Result := (SignSpecialPlaces and 63) or (1 shl 7); end; function NormalizeBcd(const InBcd: TBcd; var OutBcd: TBcd; const Prec, Scale: Word): Boolean; var PIn, POut: PChar; DecDigits: SmallInt; Negative : Boolean; begin Result := True; if (Word(InBcd.Precision) = Prec) and (Word(InBcd.SignSpecialPlaces and 63) = Scale) then OutBcd := InBcd else begin Negative := InBcd.SignSpecialPlaces and (1 shl 7) <> 0; DecDigits := InBcd.SignSpecialPlaces and 63; OutBcd.Precision := Prec; OutBcd.SignSpecialPlaces := Scale; PIn := PChar(@InBcd.Fraction); POut := PChar(@OutBcd.Fraction); FillChar(POut^, SizeOf(OutBcd.Fraction), 0); if (Prec < Word(InBcd.Precision)) and (SignificantIntDigits(pIn, Word(InBcd.Precision)) > Prec) then Result := False else begin // Precision is IntegerDigits, Scale is Decimal Digits NormalizeFractions(PIn, SmallInt(InBcd.Precision - DecDigits), DecDigits, Prec-(Scale and 63), Scale and 63, pOut); if Negative and (OutBcd.SignSpecialPlaces and (1 shl 7) = 0) then OutBcd.SignSpecialPlaces := ReverseNegative(OutBcd.SignSpecialPlaces); end; end; end; procedure NormalizeBcdPair(const bcdIn1, bcdIn2: TBcd; var bcdOut1, bcdOut2: TBcd; ExtraDigits: Word = 0 ); var Prec, Scale1, Scale2, Excess: Word; IntDigitsUsed, Req, ReqDecDigits: Word; begin Req := Max( bcdIn1.Precision - (bcdIn1.SignSpecialPlaces and 63), bcdIn2.Precision - (bcdIn2.SignSpecialPlaces and 63)); ReqDecDigits := Max( (bcdIn1.SignSpecialPlaces and 63), (bcdIn2.SignSpecialPlaces and 63)); Prec := ExtraDigits + Req + ReqDecDigits; if Prec > MaxFMTBcdFractionSize then begin Excess := Prec - (MAXFMTBcdFractionSize div 2); Prec := (MAXFMTBcdFractionSize div 2); IntDigitsUsed := ExtraDigits + Max(SignificantIntDigits(PChar(@BcdIn1.Fraction), SmallInt(BcdIn1.Precision - (BcdIn1.SignSpecialPlaces and 63))), SignificantIntDigits(PChar(@BcdIn2.Fraction), SmallInt(BcdIn2.Precision - (BcdIn2.SignSpecialPlaces and 63)))); if Excess > ((MAXFMTBcdFractionSize div 2) + IntDigitsUsed) then ReqDecDigits := Max(0, ReqDecDigits-Excess); end; if (bcdIn1.SignSpecialPlaces and (1 shl 7)) <> 0 then Scale1 := Word((ReqDecDigits and 63) or Word(1 shl 7)) else Scale1 := ReqDecDigits; if (bcdIn2.SignSpecialPlaces and (1 shl 7)) <> 0 then Scale2 := Word((ReqDecDigits and 63) or Word(1 shl 7)) else Scale2 := ReqDecDigits; NormalizeBcd(bcdIn1, bcdOut1, Prec, Scale1); NormalizeBcd(bcdIn2, bcdOut2, Prec, Scale2); end; function BcdCompare(const Bcd1, Bcd2: TBcd): Integer; var TempBcd1, TempBcd2: TBcd; PBcd1, PBcd2: PChar; Digits1,Digits2: ShortInt; Negative: Boolean; begin if (Bcd1.SignSpecialPlaces and (1 shl 7)) <> (Bcd2.SignSpecialPlaces and (1 shl 7)) then begin // if Negative setting doesn't match. if (Bcd1.SignSpecialPlaces and (1 shl 7)) <> 0 then Result := -1 else Result := 1; end else begin // both Negative or both Positive Negative := (Bcd1.SignSpecialPlaces and (1 shl 7)) <> 0; pBcd1 := pCHAR(@Bcd1.Fraction); // move to fractions pBcd2 := pCHAR(@Bcd2.Fraction); // move to fractions Digits1 := SignificantIntDigits(pBcd1, SmallInt(Bcd1.Precision - (Bcd1.SignSpecialPlaces and 63))); Digits2 := SignificantIntDigits(pBcd2, SmallInt(Bcd2.Precision - (Bcd2.SignSpecialPlaces and 63))); if Digits1 <> Digits2 then begin if Digits1 > Digits2 then Result := 1 else Result := -1; end else begin NormalizeBcdPair(Bcd1, Bcd2, TempBcd1, TempBcd2); pBcd1 := pCHAR(@TempBcd1.Fraction); // move to fractions pBcd2 := pCHAR(@TempBcd2.Fraction); // move to fractions Result := CompareNormalizedFractions(pBcd1, pBcd2, Bcd1.Precision, Bcd2.Precision); end; if Negative then Result := -Result; end; end; procedure BcdSubtract(const bcdIn1, bcdIn2: TBcd; var bcdOut: TBcd); var newBcd2: TBcd; begin newBcd2 := bcdIn2; newBcd2.SignSpecialPlaces := ReverseNegative(newBcd2.SignSpecialPlaces); BcdAdd(bcdIn1, newBcd2, bcdOut); end; procedure BcdMultiply(StringIn1, StringIn2: string; var bcdOut: TBcd); overload; var Output: string; NegCount: Integer; begin NegCount := 0; if PChar(StringIn1)[0] = '-' then begin Inc(NegCount); StringIn1 := Copy(StringIn1, 2, Length(StringIn1)-1); end; if PChar(StringIn2)[0] = '-' then begin Inc(NegCount); StringIn2 := Copy(StringIn2, 2, Length(StringIn2)-1); end; Output := _Multiply(StringIn1, StringIn2); bcdOut := StrToBcd(Output); if (NegCount mod 2) <> 0 then bcdOut.SignSpecialPlaces := (bcdOut.SignSpecialPlaces and 63) or (1 shl 7); end; procedure BcdMultiply(const bcdIn1, bcdIn2: TBcd; var bcdOut: TBcd); begin BcdMultiply(BcdToStr(bcdIn1), BcdToStr(bcdIn2), bcdOut); end; procedure BcdMultiply(const bcdIn: TBcd; const DoubleIn: Double; var bcdOut: TBcd); begin BcdMultiply(BcdToStr(bcdIn), FloatToStr(DoubleIn), bcdOut); end; procedure BcdMultiply(const bcdIn: TBcd; const StringIn: string; var bcdOut: TBcd); begin BcdMultiply(BcdToStr(bcdIn), StringIn, bcdOut); end; procedure BcdDivide(Dividend, Divisor: string; var bcdOut: TBcd); overload; var Output: string; NegCount: Integer; MaxDecimals: Byte; begin NegCount := 0; MaxDecimals := bcdOut.signSpecialPlaces and 63; if MaxDecimals = 0 then MaxDecimals := _DefaultDecimals; if PChar(Dividend)[0] = '-' then begin Inc(NegCount); Dividend := Copy(Dividend, 2, Length(Dividend)-1); end; if PChar(Divisor)[0] = '-' then begin Inc(NegCount); Divisor := Copy(Divisor, 2, Length(Divisor)-1); end; Output := RoundAt(_Divide(Dividend, Divisor), MaxDecimals); bcdOut := StrToBcd(Output); if (NegCount mod 2) <> 0 then bcdOut.SignSpecialPlaces := (bcdOut.SignSpecialPlaces and 63) or (1 shl 7); end; procedure BcdDivide(const Dividend, Divisor: TBcd; var bcdOut: TBcd); begin BcdDivide(BcdToStr(Dividend), BcdToStr(Divisor), bcdOut); end; procedure BcdDivide(const Dividend: TBcd; const Divisor: Double; var bcdOut: TBcd); begin BcdDivide(BcdToStr(Dividend), FloatToStr(Divisor), bcdOut); end; procedure BcdDivide(const Dividend: TBcd; const Divisor: string; var bcdOut: TBcd); begin BcdDivide(BcdToStr(Dividend), Divisor, bcdOut); end; procedure BcdAdd(const bcdIn1, bcdIn2: TBcd; var bcdOut: TBcd); var bcd1, bcd2: TBcd; pIn1, pIn2, pOut: PChar; Prec, Scale: Word; Neg1, Neg2: Boolean; Digits1, Digits2: Integer; begin NormalizeBcdPair(bcdIn1, bcdIn2, bcd1, bcd2, 1); Prec := bcd1.Precision; Scale := bcd1.SignSpecialPlaces; Neg1 := (BcdIn1.SignSpecialPlaces and (1 shl 7)) <> 0; Neg2 := (BcdIn2.SignSpecialPlaces and (1 shl 7)) <> 0; bcdOut.Precision := Prec; if (Neg1 = Neg2) or ((bcd1.SignSpecialPlaces and 63) >= (bcd2.SignSpecialPlaces and 63)) then bcdOut.SignSpecialPlaces := Scale else bcdOut.SignSpecialPlaces := ReverseNegative(Scale); pIn1 := PChar(@bcd1.Fraction); pIn2 := PChar(@bcd2.Fraction); pOut := PChar(@bcdOut.Fraction); FillChar(pOut^, SizeOf(bcdOut.Fraction), 0); if Neg1 = Neg2 then AddNormalizedFractions(pIn1, pIn2, pOut, prec) else begin Digits1 := SignificantIntDigits(pIn1, Prec); Digits2 := SignificantIntDigits(pIn2, Prec); if Digits1 > Digits2 then SubtractNormalizedFractions(pIn1,pIn2,pOut, Prec) else if Digits2 > Digits1 then begin SubtractNormalizedFractions(pIn2,pIn1,pOut,prec); bcdOut.SignSpecialPlaces := ReverseNegative(bcdOut.SignSpecialPlaces); end else if CompareNormalizedFractions(pIn1,pIn2,prec,prec) >= 0 then SubtractNormalizedFractions(pIn1,pIn2,pOut, prec) else begin SubtractNormalizedFractions(pIn2,pIn1,pOut,prec); bcdOut.SignSpecialPlaces := ReverseNegative(bcdOut.SignSpecialPlaces); end; end; end; function FractionToStr(const pIn: PChar; count: SmallInt; DecPosition: ShortInt; Negative: Boolean): string; var NibblesIn, BytesIn, DigitsOut: Integer; P, POut: PChar; Dot: Char; procedure AddOneChar(Value: Char); begin P[0] := Value; Inc(P); Inc(DigitsOut); end; procedure AddDigit(Value: Char); begin if (DecPosition > 0) and (NibblesIn = DecPosition) then begin if DigitsOut = 0 then AddOneChar('0'); AddOneChar(Dot); end; if (Value > #0) or (DigitsOut > 0) then AddOneChar(Char(Integer(Value)+48)); Inc(NibblesIn); end; begin POut := AllocMem(Count + 3); // count + negative/decimal/zero try Dot := DecimalSeparator; P := POut; DigitsOut := 0; BytesIn := 0; NibblesIn := 0; while NibblesIn < Count do begin AddDigit(Char(Integer(pIn[BytesIn]) SHR 4)); if NibblesIn < Count then AddDigit(Char(Integer(pIn[BytesIn]) AND 15)); Inc(BytesIn); end; while (DecPosition > 0) and (NibblesIn > DecPosition) and (DigitsOut > 1) do begin if POut[DigitsOut-1] = '0' then begin Dec(DigitsOut); POut[DigitsOut] := #0; end else break; end; if POut[DigitsOut-1] = Dot then Dec(DigitsOut); POut[DigitsOut] := #0; SetString(Result, POut, DigitsOut); finally FreeMem(POut, Count + 2); end; if Result = '' then Result := '0' else if Negative then Result := '-' + Result; end; function BcdToStr(const Bcd: TBcd): string; var NumDigits: Integer; pStart: PChar; DecPos: SmallInt; Negative: Boolean; begin if (Bcd.Precision = 0) or (Bcd.Precision > MaxFMTBcdFractionSize) then OverFlowError(SBcdOverFlow) else begin Negative := Bcd.SignSpecialPlaces and (1 shl 7) <> 0; NumDigits := Bcd.Precision; pStart := pCHAR(@Bcd.Fraction); // move to fractions // use lower 6 bits of iSignSpecialPlaces. if (Bcd.SignSpecialPlaces and 63) > 0 then begin DecPos := ShortInt(NumDigits - (Bcd.SignSpecialPlaces and 63)); end else DecPos := NumDigits + 1; // out of range Result := FractionToStr(pStart, NumDigits, DecPos, Negative); if Result[1] in ['0', '-'] then if (Result = '-0') or (Result = '0.0') or (Result = '-0.0') then Result := '0'; end; end; function BcdPrecision(const Bcd: TBcd): Word; begin Result := Bcd.Precision - BcdScale(Bcd); end; function BcdScale(const Bcd: TBcd): Word; begin Result := (Bcd.SignSpecialPlaces and 63); end; function IsBcdNegative(const Bcd: TBcd): Boolean; begin Result := (Bcd.SignSpecialPlaces and (1 shl 7)) <> 0; end; function IsBcdZero(const Bcd: TBcd): Boolean; var P: PChar; I, Scale: Integer; begin Result := True; P := PChar(@Bcd.Fraction); I := 0; Scale := BcdScale(Bcd); while Result and (I < Scale div 2) do begin if Byte(P^) <> 0 then Result := False; Inc(P); Inc(I); end; { if odd nibble, check it } if Result and (Scale mod 2 > 0) then if (Byte(P^) SHR 4) > 0 then Result := False; end; function CurrToBCD(const Curr: Currency; var BCD: TBcd; Precision: Integer = 32; Decimals: Integer = 4): Boolean; const Power10: array[0..3] of Single = (10000, 1000, 100, 10); var Digits: array[0..63] of Byte; asm PUSH EBX PUSH ESI PUSH EDI MOV ESI,EAX XCHG ECX,EDX MOV [ESI].TBcd.Precision,CL MOV [ESI].TBcd.SignSpecialPlaces,DL @@1: SUB EDX,4 JE @@3 JA @@2 FILD Curr FDIV Power10.Single[EDX*4+16] FISTP Curr JMP @@3 @@2: DEC ECX MOV Digits.Byte[ECX],0 DEC EDX JNE @@2 @@3: MOV EAX,Curr.Integer[0] MOV EBX,Curr.Integer[4] OR EBX,EBX JNS @@4 NEG EBX NEG EAX SBB EBX,0 OR [ESI].TBcd.SignSpecialPlaces,80H @@4: MOV EDI,10 @@5: MOV EDX,EAX OR EDX,EBX JE @@7 XOR EDX,EDX OR EBX,EBX JE @@6 XCHG EAX,EBX DIV EDI XCHG EAX,EBX @@6: DIV EDI @@7: MOV Digits.Byte[ECX-1],DL DEC ECX JNE @@5 OR EAX,EBX MOV AL,0 JNE @@9 MOV CL,[ESI].TBcd.Precision INC ECX SHR ECX,1 @@8: MOV AX,Digits.Word[ECX*2-2] SHL AL,4 OR AL,AH MOV [ESI].TBcd.Fraction.Byte[ECX-1],AL DEC ECX JNE @@8 MOV AL,1 @@9: POP EDI POP ESI POP EBX end; function BCDToCurr(const BCD: TBcd; var Curr: Currency): Boolean; const FConst10: Single = 10; CWNear: Word = $133F; var CtrlWord: Word; Temp: Integer; Digits: array[0..63] of Byte; asm PUSH EBX PUSH EDI PUSH ESI XOR EBX,EBX MOV EDI,EAX MOV ESI,EDX MOV AL,0 MOVZX EDX,[EDI].TBcd.Precision OR EDX,EDX JE @@8 LEA ECX,[EDX+1] SHR ECX,1 @@1: MOV AL,[EDI].TBcd.Fraction.Byte[ECX-1] MOV AH,AL SHR AL,4 AND AH,0FH MOV Digits.Word[ECX*2-2],AX DEC ECX JNE @@1 XOR EAX,EAX @@2: MOV AL,Digits.Byte[ECX] OR AL,AL JNE @@3 INC ECX CMP ECX,EDX JNE @@2 FLDZ JMP @@7 @@3: MOV Temp,EAX FILD Temp @@4: INC ECX CMP ECX,EDX JE @@5 FMUL [EBX].FConst10 MOV AL,Digits.Byte[ECX] MOV Temp,EAX FIADD Temp JMP @@4 @@5: MOV AL,[EDI].TBcd.SignSpecialPlaces OR AL,AL JNS @@6 FCHS @@6: AND EAX,3FH SUB EAX,4 NEG EAX CALL FPower10 @@7: FSTCW CtrlWord FLDCW [EBX].CWNear FISTP [ESI].Currency FSTSW AX NOT AL AND AL,1 FCLEX FLDCW CtrlWord FWAIT @@8: POP ESI POP EDI POP EBX end; procedure CopyByte(var Buffer: array of Char; const Byte: Char; var Pos: Integer); begin Buffer[Pos] := Byte; Inc(Pos); end; { ffGeneral - General number format. The value is converted to the shortest possible decimal string using fixed format. Trailing zeros are removed from the resulting string, and a decimal point appears only if necessary. The resulting string uses fixed point format if the number of digits to the left of the decimal point in the value is less than or equal to the specified precision. Otherwise an exception is thrown } function BcdGeneralFormat(const Bcd: TBcd; const Precision, Digits: Integer): string; begin Result := BcdToStr(Bcd); end; { ffExponent - Scientific format. Not supported for FMTBcd -- Bcd is by definition fixed format } function BcdScientificFormat(const Bcd: TBcd; const Precision, Digits: Integer): string; begin BcdError(SInvalidFormatType); end; { ffFixed - Fixed point format. The value is converted to a string of the form "-ddd.ddd...". The resulting string starts with a minus sign if the number is negative, and at least one digit always precedes the decimal point. The number of digits after the decimal point is given by the Digits parameter--it must be between 0 and 18. If the value has more decimal values than permitted by Digits, it is truncated. If the number of digits to the left of the decimal point is greater than the specified precision, an exception is thrown ffNumber - Number format. The ffNumber format corresponds to the ffFixed format, except that the resulting string contains thousand separators. } function BcdFixedOrNumberFormat(const Start: string; Format: TFloatFormat; const Precision, Digits: Integer): string; var P: PChar; AddCommaDigits, DecDigits, BufPos: Integer; Buffer: array[0..255] of Char; Comma, Dot: Char; begin BufPos := 0; Dot := DecimalSeparator; Comma := ThousandSeparator; Result := Start; P := PChar(Result); DecDigits := -1; if Format = ffNumber then begin AddCommaDigits := Pos(Dot, Result); if AddCommaDigits > 0 then Dec(AddCommaDigits) else AddCommaDigits := Length(Result); end else AddCommaDigits := 0; if P^ = '-' then begin CopyByte(Buffer, P^, BufPos); Inc(P); if AddCommaDigits > 0 then Dec(AddCommaDigits); end; while P^ <> #0 do begin CopyByte(Buffer, P^, BufPos); if P^ = Dot then DecDigits := 0 else if DecDigits > -1 then Inc(DecDigits); Inc(P); if AddCommaDigits > 3 then begin Dec(AddCommaDigits); if (AddCommaDigits mod 3 = 0) then CopyByte(Buffer, Comma, BufPos); end; end; if DecDigits = -1 then begin if Digits > 0 then CopyByte(Buffer, Dot, BufPos); DecDigits := 0; end; while DecDigits < Digits do begin CopyByte(Buffer, '0', BufPos); Inc(DecDigits); end; if Buffer[BufPos -1] = Dot then Dec(BufPos); Buffer[BufPos] := #0; SetString(Result, Buffer, BufPos); Result := RoundAt( Result, Digits); end; { ffCurrency - Currency format. The value is converted to a string that represents a currency amount. The conversion is controlled by the CurrencyString, CurrencyFormat, NegCurrFormat, ThousandSeparator, and DecimalSeparator global variables The number of digits after the decimal point is given by the Digits parameter--it must be between 0 and 18. } { 0 = '$1', 1 = '1$', 2 = '$ 1', 3 = '1 $' } function AddCurrencySymbol(const Value, CurrSymbol: string; const CurrFormat: Byte): string; begin case CurrFormat of 0: Result := Format('%s%s', [CurrSymbol, Value]); 1: Result := Format('%s%s', [Value, CurrSymbol]); 2: Result := Format('%s %s', [CurrSymbol, Value]); 3: Result := Format('%s %s', [Value, CurrSymbol]); end; end; { 0 = '($1)' 4 = '(1$)' 8 = '-1 $' 12 = '$ -1' 1 = '-$1' 5 = '-1$' 9 = '-$ 1' 13 = '1- $' 2 = '$-1' 6 = '1-$' 10 = '1 $-' 14 = '($ 1)' 3 = '$1-' 7 = '1$-' 11 = '$ 1-' 15 = '(1 $)' } function AddNegCurrencySymbol(const Value, CurrSymbol: string; const CurrFormat: Byte): string; begin case CurrFormat of 0: Result := Format('(%s%s)', [CurrSymbol, Value]); 1: Result := Format('-%s%s', [CurrSymbol, Value]); 2: Result := Format('%s-%s', [CurrSymbol, Value]); 3: Result := Format('%s%s-', [CurrSymbol, Value]); 4: Result := Format('(%s%s)', [Value, CurrSymbol]); 5: Result := Format('-%s%s', [Value, CurrSymbol]); 6: Result := Format('%s-%s', [Value, CurrSymbol]); 7: Result := Format('%s%s-', [Value, CurrSymbol]); 8: Result := Format('-%s %s', [Value, CurrSymbol]); 9: Result := Format('-%s %s', [CurrSymbol, Value]); 10: Result := Format('%s %s-', [Value, CurrSymbol]); 11: Result := Format('%s %s-', [CurrSymbol, Value]); 12: Result := Format('%s %s', [CurrSymbol, Value]); 13: Result := Format('%s -%s', [Value, CurrSymbol]); 14: Result := Format('(%s- %s)', [CurrSymbol, Value]); 15: Result := Format('(%s %s)', [Value, CurrSymbol]); end; end; function BcdCurrencyFormat(const Bcd: TBcd; const Start: string; const Precision, Digits: Integer): string; var CurrSymbol: string; CurrFormat: Byte; NegFormat: Byte; begin CurrSymbol := CurrencyString; CurrFormat := CurrencyFormat; NegFormat := NegCurrFormat; Result := BcdFixedOrNumberFormat(Start, ffNumber, Precision, Digits); if IsBcdNegative(Bcd) then Result := AddNegCurrencySymbol(String(PChar(Result)+1), CurrSymbol, NegFormat) else Result := AddCurrencySymbol(Result, CurrSymbol, CurrFormat); end; function BcdToStrF(const Bcd: TBcd; Format: TFloatFormat; const Precision, Digits: Integer): string; begin Result := BcdGeneralFormat(Bcd, Precision, Digits); case Format of ffExponent: Result := BcdScientificFormat(Bcd, Precision, Digits); ffCurrency: Result := BcdCurrencyFormat(Bcd, Result, Precision, Digits); ffFixed, ffNumber: Result := BcdFixedOrNumberFormat(Result, Format, Precision, Digits); end; end; function ExtractMoneySymbol( var CurrencyPos: Integer; var HoldFormat: String): string; var TempPos: Integer; begin TempPos := CurrencyPos; Result := '$'; while (CurrencyPos > 0) and (HoldFormat[CurrencyPos-1] = ' ') do begin Dec(CurrencyPos); Result := ' ' + Result; end; while (TempPos < Length(HoldFormat)) and (HoldFormat[TempPos+1] = ' ') do begin Inc(TempPos); Result := Result + ' '; end; HoldFormat := StringReplace(HoldFormat, Result, '', []); Result := StringReplace(Result, '$', CurrencyString, []); end; procedure CalcPrecisionAndDigits( const HoldFormat: string; var Precision, Digits, ReqIntDigits: Integer); begin if Digits > 0 then begin ReqIntDigits := Digits -1; Precision := Length(HoldFormat) -1; Digits := Length(HoldFormat) - Digits; end else begin Precision := Length(HoldFormat); ReqIntDigits := Precision; Digits := 0; end; end; function PadInputString(var InputString: string; var Precision: Integer; const ReqIntDigits: Integer): Boolean; var DecSep: Char; IntDigits, PadCount: Integer; begin Result := True; DecSep := DecimalSeparator; IntDigits := Pos(DecSep, InputString); if IntDigits = 0 then IntDigits := Length(InputString) else Dec(IntDigits); PadCount := ReqIntDigits - IntDigits; if PadCount > 0 then begin InputString := '1' + StringOfChar('0', PadCount -1) + InputString; Inc(Precision); end else Result := False; end; procedure AddCurrency(var Output: string; const CurrencyPos: Integer; const MoneySymbol: string); begin if CurrencyPos = 1 then Output := MoneySymbol + Output else if CurrencyPos >= Length(Output) then Output := Output + MoneySymbol else Output := Copy(Output, 1, CurrencyPos -1 ) + MoneySymbol + Copy(Output, CurrencyPos, Length(Output)); end; type TLiteralInfo = class private FValue: string; FPosition: Integer; public property Value: string read FValue write FValue; property Position: Integer read FPosition write FPosition; constructor Create(Val: string; Pos: Integer); end; constructor TLiteralInfo.Create; begin FValue := Val; FPosition := Pos; end; procedure ExtractLiterals(LiteralList: TList; var HoldFormat: string); const FormatChars = ['#', '0', ',', '.']; LiteralMarkers = [#39, '"']; var P, PStart: PChar; I, Pos, LiteralPos: Integer; LiteralString: string; InLiteral: Boolean; begin InLiteral := False; P := PChar(HoldFormat); LiteralPos := 0; Pos := 0; LiteralString := ''; while P^ <> #0 do begin if P^ in LiteralMarkers then InLiteral := not InLiteral else if not (P^ in FormatChars) then begin LiteralPos := Pos; PStart := P; while ((InLiteral) or not (P^ in FormatChars)) do begin Inc(P); Inc(Pos); if (P^ in LiteralMarkers) or (P^ = #0) then begin InLiteral := False; break; end; end; SetString(LiteralString, PStart, P-PStart); end; if (not InLiteral) and (LiteralString <> '') then begin LiteralList.Add(TLiteralInfo.Create(LiteralString, LiteralPos)); LiteralString := ''; end; if P^ <> #0 then Inc(P); Inc(Pos); end; for I := 0 to LiteralList.Count -1 do HoldFormat := StringReplace(HoldFormat, TLiteralInfo(LiteralList.Items[I]).Value, '', []); end; procedure AddLiterals(LiteralList: TList; var Output: string; const Format: string); var I, Add: Integer; Pos: Integer; begin Add := (Length(Output)+1) - Length(Format); if Add < 0 then Add := 0; for I := 0 to LiteralList.Count -1 do begin Pos := TLiteralInfo(LiteralList.Items[I]).Position; if Pos = 0 then Output := TLiteralInfo(LiteralList.Items[I]).Value + Output else if (Pos + Add) < Length(Output) then begin Inc(Pos, Add); Output := Copy(Output, 1, Pos -1 ) + TLiteralInfo(LiteralList.Items[I]).Value + Copy(Output, Pos, length(Output) - (Pos -1)); end else Output := Output + TLiteralInfo(LiteralList.Items[I]).Value; TLiteralInfo(LiteralList.Items[I]).Free; end; end; function FormatOneBcd(const Format: string; Bcd: TBcd): string; const Dot: Char = '.'; var Precision, Digits, ReqDigits: Integer; TempPos, CurrencyPos: Integer; MoneySymbol: string; FFormat: TFloatFormat; LeftPadZeros, RightPadZeros, UseCommas: Boolean; Neg, HoldFormat: string; LiteralList: TList; begin Neg := ''; LiteralList := TList.Create; try HoldFormat := Format; CurrencyPos := Pos('$', Format); if CurrencyPos > 0 then MoneySymbol := ExtractMoneySymbol(CurrencyPos, HoldFormat); ExtractLiterals(LiteralList,HoldFormat); UseCommas := (Pos(',', HoldFormat) > 0); if UseCommas then HoldFormat := StringReplace(HoldFormat, ',', '', []); Digits := Pos(Dot, HoldFormat); CalcPrecisionAndDigits(HoldFormat, Precision, Digits, ReqDigits); TempPos := Pos('0', HoldFormat); LeftPadZeros := (TempPos > 0) and (TempPos < ReqDigits); TempPos := Pos('0', Copy(HoldFormat, ReqDigits, Digits + 1)); RightPadZeros := TempPos > 0; if UseCommas then FFormat := ffNumber else if RightPadZeros or (Digits < BcdScale(Bcd)) then FFormat := ffFixed else FFormat := ffGeneral; Result := BcdGeneralFormat(Bcd, Precision, Digits); if IsBcdNegative(Bcd) then begin Neg := '-'; Result := StringReplace(Result, Neg, '', []); Inc(CurrencyPos); end; if LeftPadZeros then LeftPadZeros := PadInputString(Result, Precision, ReqDigits); if FFormat <> ffGeneral then Result := BcdFixedOrNumberFormat(Result, FFormat, Precision, Digits); if LeftPadZeros then Result := Neg + '0' + Copy(Result, 2, Length(Result) -1) else Result := Neg + Result; if MoneySymbol <> '' then AddCurrency(Result, CurrencyPos, MoneySymbol); AddLiterals(LiteralList, Result, HoldFormat); finally LiteralList.Free; end; end; type TFormatSection = (sectionPositive, sectionNegative, sectionZero); function GetFormat(const Format: string; Section: TFormatSection): string; const Separator: Char = ';'; LiteralMarkers = [#39, '"']; var InLiteral: Boolean; P, PThisSection: PChar; SectionCount: Integer; begin if Pos(Separator,Format) = 0 then Result := Format else begin PThisSection := PChar(Format); P := PThisSection; InLiteral := False; SectionCount := 0; while P^ <> #0 do begin if P^ in LiteralMarkers then InLiteral := not InLiteral else begin if (P^ = Separator) and (not InLiteral) then begin if Integer(Section) = SectionCount then break else begin Inc(SectionCount); end; end; end; Inc(P); end; SetString(Result, PThisSection, P-PThisSection); end; end; function FormatBcd(const Format: string; Bcd: TBcd): string; begin if IsBcdNegative(Bcd) then Result := FormatOneBcd(GetFormat(Format, sectionNegative), Bcd) else if IsBcdZero(Bcd) then Result := FormatOneBcd(GetFormat(Format, sectionZero), Bcd) else Result := FormatOneBcd(GetFormat(Format, sectionPositive), Bcd); end; initialization FMTBcdVariantType := TFMTBcdVariantType.Create; finalization FreeAndNil(FMTBcdVariantType); end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2019 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit RSConsole.DlgPushDataU; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Rtti, System.Bindings.Outputs, FMX.Bind.Editors, Data.Bind.EngExt, FMX.Bind.DBEngExt, IPPeerClient, REST.Backend.PushTypes, REST.Backend.MetaTypes, System.JSON, Data.Bind.Components, Data.Bind.ObjectScope, REST.Backend.BindSource, REST.Backend.ServiceComponents, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, FMX.Layouts, FMX.Memo, FMX.ScrollBox; type TDlgPushData = class(TForm) EditMessage: TEdit; LabelMessage: TLabel; LinkControlToFieldMessage: TLinkControlToField; BindingsList1: TBindingsList; EditAPSBadge: TEdit; LabelAPSBadge: TLabel; LinkControlToFieldAPSBadge: TLinkControlToField; EditAPSSound: TEdit; LabelAPSSound: TLabel; LinkControlToFieldAPSSound: TLinkControlToField; EditGCMTitle: TEdit; LabelGCMTitle: TLabel; LinkControlToFieldGCMTitle: TLinkControlToField; GroupBoxAPNS: TGroupBox; GroupBoxGCM: TGroupBox; BackendPush1: TBackendPush; ButtonOK: TButton; ButtonCancel: TButton; EditGCMMessage: TEdit; Label1: TLabel; LinkControlToField2: TLinkControlToField; Edit1: TEdit; LinkControlToField3: TLinkControlToField; Label2: TLabel; Layout1: TLayout; Layout2: TLayout; private FJSONData: TJSONObject; function GetJSONData: TJSONObject; procedure SetJSONData(const Value: TJSONObject); { Private declarations } public destructor Destroy; override; { Public declarations } property JSONData: TJSONObject read GetJSONData write SetJSONData; end; var DlgPushData: TDlgPushData; implementation {$R *.fmx} { TDlgPushData } destructor TDlgPushData.Destroy; begin FJSONData.Free; inherited; end; function TDlgPushData.GetJSONData: TJSONObject; begin if FJSONData = nil then FJSONData := TJSONObject.Create; if BackendPush1.Message <> '' then FJSONData.AddPair('message', BackendPush1.Message); BackendPush1.APS.Save(FJSONData, 'aps'); BackendPush1.GCM.Save(FJSONData, 'gcm'); Result := FJSONData; end; procedure TDlgPushData.SetJSONData(const Value: TJSONObject); var LMessage: string; begin BackendPush1.APS.Load(Value, 'aps'); BackendPush1.GCM.Load(Value, 'gcm'); if Value.TryGetValue<string>('message', LMessage) then BackendPush1.Message := LMessage; // LPushData.Extras.Load(Value, 'extras'); // BackendPush end; end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.DAO.Database Description : DAO Database Author : Kike Pérez Version : 1.2 Created : 22/06/2018 Modified : 14/04/2020 This file is part of QuickDAO: https://github.com/exilon/QuickDAO *************************************************************************** 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.DAO.Database; {$i QuickDAO.inc} interface uses SysUtils, Classes, Rtti, TypInfo, {$IFDEF FPC} rttiutils, fpjson, jsonparser, strUtils, //jsonreader, //fpjsonrtti, Quick.Json.fpc.Compatibility, {$ELSE} {$IFDEF DELPHIXE7_UP} System.Json, {$ENDIF} {$ENDIF} Quick.Json.Serializer, Quick.DAO, Quick.DAO.Factory.QueryGenerator; type IDBConnectionSettings = interface ['{B4AE214B-432F-409C-8A15-AEEEE39CBAB5}'] function GetProvider : TDBProvider; function GetServer : string; function GetDatabase : string; function GetUserName : string; function GetPassword : string; property Provider : TDBProvider read GetProvider; property Server : string read GetServer; property Database : string read GetDatabase; property UserName : string read GetUserName; property Password : string read GetPassword; function IsCustomConnectionString : Boolean; procedure FromConnectionString(aDBProviderID : Integer; const aConnectionString: string); function GetCustomConnectionString : string; end; TDBConnectionSettings = class(TInterfacedObject,IDBConnectionSettings) private fDBProvider : TDBProvider; fServer : string; fDatabase : string; fUserName : string; fPassword : string; fCustomConnectionString : string; fIsCustomConnectionString : Boolean; function GetProvider : TDBProvider; virtual; function GetServer : string; function GetDatabase : string; function GetUserName : string; function GetPassword : string; public constructor Create; property Provider : TDBProvider read GetProvider write fDBProvider; property Server : string read fServer write fServer; property Database : string read fDatabase write fDatabase; property UserName : string read fUserName write fUserName; property Password : string read fPassword write fPassword; function IsCustomConnectionString : Boolean; procedure FromConnectionString(aDBProviderID : Integer; const aConnectionString: string); function GetCustomConnectionString : string; function Clone : TDBConnectionSettings; end; TDAODataBase = class private fDBConnection : TDBConnectionSettings; fOwnsConnection : Boolean; fQueryGenerator : IDAOQueryGenerator; fModels : TDAOModels; fIndexes : TDAOIndexes; protected property OwnsConnection : Boolean read fOwnsConnection write fOwnsConnection; function CreateConnectionString : string; virtual; abstract; procedure ExecuteSQLQuery(const aQueryText : string); virtual; abstract; procedure OpenSQLQuery(const aQueryText: string); virtual; abstract; function ExistsTable(aModel : TDAOModel) : Boolean; virtual; abstract; function CreateTable(const aModel : TDAOModel): Boolean; virtual; function ExistsColumn(aModel: TDAOModel; const aFieldName: string): Boolean; virtual; abstract; procedure AddColumnToTable(aModel : TDAOModel; aField : TDAOField); virtual; procedure CreateTables; virtual; procedure SetPrimaryKey(aModel : TDAOModel); virtual; procedure CreateIndexes; virtual; procedure CreateIndex(aModel : TDAOModel; aIndex : TDAOIndex); virtual; public constructor Create; virtual; destructor Destroy; override; function QueryGenerator : IDAOQueryGenerator; property Connection : TDBConnectionSettings read fDBConnection write fDBConnection; property Models : TDAOModels read fModels write fModels; property Indexes : TDAOIndexes read fIndexes write fIndexes; function CreateQuery(aModel : TDAOModel) : IDAOQuery<TDAORecord>; virtual; abstract; function GetTableNames : TArray<string>; virtual; abstract; function GetFieldNames(const aTableName : string) : TArray<string>; virtual; abstract; function Connect : Boolean; virtual; procedure Disconnect; virtual; abstract; function IsConnected : Boolean; virtual; abstract; function AddOrUpdate(aDAORecord : TDAORecord) : Boolean; virtual; function Add(aDAORecord : TDAORecord) : Boolean; virtual; function Update(aDAORecord : TDAORecord) : Boolean; virtual; function Delete(aDAORecord : TDAORecord) : Boolean; overload; virtual; function Clone : TDAODatabase; virtual; abstract; end; implementation { TDAODataBase } constructor TDAODataBase.Create; begin fDBConnection := TDBConnectionSettings.Create; fOwnsConnection := True; fModels := TDAOModels.Create; fIndexes := TDAOIndexes.Create; end; destructor TDAODataBase.Destroy; begin fDBConnection.Free; fModels.Free; fIndexes.Free; inherited; end; procedure TDAODataBase.CreateIndexes; var daoindex : TDAOIndex; daomodel : TDAOModel; begin for daoindex in Indexes.List do begin if (Models.List.TryGetValue(daoindex.Table,daomodel)) and (daomodel.HasPrimaryKey) then CreateIndex(daomodel,daoindex); end; end; procedure TDAODataBase.CreateTables; var daomodel : TDAOModel; field : TDAOField; begin for daomodel in Models.List.Values do begin if not ExistsTable(daomodel) then CreateTable(daomodel) else begin //add new fields for field in daomodel.Fields do begin if not ExistsColumn(daomodel,field.Name) then AddColumnToTable(daomodel,field); end; end; SetPrimaryKey(daomodel); end; end; function TDAODataBase.CreateTable(const aModel : TDAOModel): Boolean; begin try ExecuteSQLQuery(QueryGenerator.CreateTable(aModel)); Result := True; except on E : Exception do raise EDAOCreationError.CreateFmt('Error creating table "%s" : %s!',[aModel.TableName,e.Message]) end; end; function TDAODataBase.Connect: Boolean; begin Result := False; fQueryGenerator := TDAOQueryGeneratorFactory.Create(fDBConnection.Provider); end; procedure TDAODataBase.AddColumnToTable(aModel : TDAOModel; aField : TDAOField); begin try ExecuteSQLQuery(QueryGenerator.AddColumn(aModel,aField)); except on E : Exception do raise EDAOCreationError.CreateFmt('Error creating table "%s" fields',[aModel.TableName]); end; end; procedure TDAODataBase.SetPrimaryKey(aModel : TDAOModel); var query : string; begin try query := QueryGenerator.SetPrimaryKey(aModel); if not query.IsEmpty then ExecuteSQLQuery(query); except on E : Exception do raise EDAOCreationError.Create('Error modifying primary key field'); end; if (fDBConnection.Provider = daoSQLite) and (aModel.HasPrimaryKey) then Indexes.Add(aModel.Table,[aModel.PrimaryKey.Name],TDAOIndexOrder.orAscending); end; procedure TDAODataBase.CreateIndex(aModel : TDAOModel; aIndex : TDAOIndex); var query : string; begin try query := QueryGenerator.CreateIndex(aModel,aIndex); if query.IsEmpty then Exit; ExecuteSQLQuery(query); except on E : Exception do raise EDAOCreationError.CreateFmt('Error creating index "%s" on table "%s"',[aIndex.FieldNames[0],aModel.TableName]); end; end; function TDAODataBase.Add(aDAORecord : TDAORecord) : Boolean; begin Result := CreateQuery(fModels.Get(aDAORecord)).Add(aDAORecord); end; function TDAODataBase.AddOrUpdate(aDAORecord : TDAORecord) : Boolean; begin Result := CreateQuery(fModels.Get(aDAORecord)).AddOrUpdate(aDAORecord); end; function TDAODataBase.Delete(aDAORecord : TDAORecord) : Boolean; begin Result := CreateQuery(fModels.Get(aDAORecord)).Delete(aDAORecord); end; function TDAODataBase.Update(aDAORecord : TDAORecord) : Boolean; begin Result := CreateQuery(fModels.Get(aDAORecord)).Update(aDAORecord); end; function TDAODataBase.QueryGenerator: IDAOQueryGenerator; begin Result := fQueryGenerator; end; { TDBConnectionSettings } function TDBConnectionSettings.Clone: TDBConnectionSettings; begin Result := TDBConnectionSettings.Create; Result.Provider := fDBProvider; Result.Server := fServer; Result.Database := fDatabase; Result.UserName := fUserName; Result.Password := fPassword; Result.fIsCustomConnectionString := fIsCustomConnectionString; Result.fCustomConnectionString := fCustomConnectionString; end; constructor TDBConnectionSettings.Create; begin fCustomConnectionString := ''; fIsCustomConnectionString := False; end; procedure TDBConnectionSettings.FromConnectionString(aDBProviderID : Integer; const aConnectionString: string); begin if aConnectionString.IsEmpty then fIsCustomConnectionString := False else begin fCustomConnectionString := aConnectionString; fIsCustomConnectionString := True; end; //get provider from connectionstring if aDBProviderID <> 0 then fDBProvider := TDBProvider(aDBProviderID) else begin if fCustomConnectionString.ToUpper.Contains('DRIVERID=SQLITE') then fDBProvider := TDBProvider.daoSQLite; end; end; function TDBConnectionSettings.GetCustomConnectionString: string; begin Result := fCustomConnectionString; end; function TDBConnectionSettings.GetDatabase: string; begin Result := fDatabase; end; function TDBConnectionSettings.GetProvider: TDBProvider; begin Result := fDBProvider; end; function TDBConnectionSettings.GetServer: string; begin Result := fServer; end; function TDBConnectionSettings.GetUserName: string; begin Result := fUserName; end; function TDBConnectionSettings.IsCustomConnectionString: Boolean; begin Result := fIsCustomConnectionString; end; function TDBConnectionSettings.GetPassword: string; begin Result := fPassword; end; end.