text
stringlengths
14
6.51M
unit htPicture; interface uses SysUtils, Classes, Graphics, htPersistBase, htTypes; type ThtCustomPicture = class(ThtPersistBase) private FFilename: string; FPictureValid: Boolean; FPicture: TPicture; FUrl: string; protected function GetGraphic: TGraphic; function GetPicture: TPicture; function GetUrl: string; procedure SetFilename(const Value: string); procedure SetPicture(const Value: TPicture); procedure ValidatePicture; public constructor Create; destructor Destroy; override; function HasGraphic: Boolean; procedure Assign(Source: TPersistent); override; property Filename: string read FFilename write SetFilename; property Picture: TPicture read GetPicture write SetPicture; property Graphic: TGraphic read GetGraphic; property Url: string read GetUrl write FUrl; end; // ThtPicture = class(ThtCustomPicture) published property Filename; end; implementation uses htUtils; { ThtCustomPicture } constructor ThtCustomPicture.Create; begin FPicture := TPicture.Create; end; destructor ThtCustomPicture.Destroy; begin FPicture.Free; inherited; end; procedure ThtCustomPicture.Assign(Source: TPersistent); begin if not (Source is ThtCustomPicture) then inherited else with ThtCustomPicture(Source) do Self.Filename := Filename; end; procedure ThtCustomPicture.SetFilename(const Value: string); begin if Url = htForwardSlashes(Filename) then Url := htForwardSlashes(Value); FFilename := Value; FPictureValid := false; Change; end; function ThtCustomPicture.GetPicture: TPicture; begin ValidatePicture; Result := FPicture; end; procedure ThtCustomPicture.SetPicture(const Value: TPicture); begin FPicture.Assign(Value); end; procedure ThtCustomPicture.ValidatePicture; begin if not FPictureValid then try FPictureValid := true; if FileExists(Filename) then FPicture.LoadFromFile(Filename); except end; end; function ThtCustomPicture.GetGraphic: TGraphic; begin Result := Picture.Graphic; end; function ThtCustomPicture.HasGraphic: Boolean; begin Result := (Graphic <> nil) and not (Graphic.Empty); end; function ThtCustomPicture.GetUrl: string; begin if FUrl <> '' then Result := FUrl else Result := htForwardSlashes(FFilename); end; end.
unit Geometry1; interface {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses sysutils,math,util1,listG,NcDef2; type TRPoint=record x,y:float; end; TpolyR=array of TRPoint; { On considère des polygones convexes orientés dans le sens des aiguilles d'une montre } function segment(const A,B:TRpoint):TpolyR; function PtInside(M:TRpoint;poly:TpolyR):boolean; function PolyRinter(poly1,poly2:TpolyR):TpolyR; function PolyRArea(poly:TpolyR):float; procedure testGeom; function PointInSector(xa,ya,xb,yb,Dtheta,xm,ym:float):boolean; function fonctionPointInSector(xa,ya,xb,yb,Dtheta,xm,ym:float):boolean;pascal; function SegAngle(xa,ya,xb,yb:float):float; function fonctionSegAngle(xa,ya,xb,yb:float):float;pascal; implementation function Rpoint(x,y:float):TRpoint; begin result.x:=x; result.y:=y; end; function segment(const A,B:TRpoint):TpolyR; begin setLength(result,2); result[0]:=A; result[1]:=B; end; function poly5R(p1,p2,p3,p4:TRpoint):TpolyR; begin setLength(result,5); result[0]:=p1; result[1]:=p2; result[2]:=p3; result[3]:=p4; result[4]:=p1; end; { Indique si le point M est à droite du segment AB Renvoie une valeur positive si M est à droite zéro si M est sur la droite AB une valeur négative si M est à gauche } function PtRight(M:TRpoint; AB:TpolyR):float; begin result:=(M.x-AB[0].x)*(AB[1].y-AB[0].y) - (M.y-AB[0].y)*(AB[1].x-AB[0].x); end; {Indique si le point est strictement intérieur au polygone } {Indique si le point est strictement intérieur au polygone Deuxième méthode } function PtInside(M:TRpoint;poly:TpolyR):boolean; var n,i:integer; xc:float; function coupe(var p1,p2:TRPoint):boolean; begin if p1.y=p2.y then coupe:=(m.y=p1.y) else if p1.x=p2.x then coupe:=(m.x<=p1.x) and ( (m.y>=p1.y) and (m.y<=p2.y) or (m.y>=p2.y) and (m.y<=p1.y) ) else begin xc:=p1.x+(p2.x-p1.x)*(m.y-p1.y)/(p2.y-p1.y); coupe:=(xc>=m.x) and ( (p1.x<=xc) and (xc<=p2.x) or (p2.x<=xc) and (xc<=p1.x) ); end; end; begin n:=0; for i:=0 to high(poly)-1 do if coupe(poly[i],poly[i+1]) then inc(n); result:=(n and 1<>0); end; function SegInterSeg(A,B,C,D:TRpoint;var M:TRpoint):boolean; const eps=1E-30; var k1,k2:float; begin result:=false; if (a.y=b.y) and (c.y=d.y) then exit; if a.y=b.y then begin m.y:=a.y; k2:=(d.x-c.x)/(d.y-c.y); m.x:=c.x+k2*(m.y-c.y); end else if c.y=d.y then begin m.y:=c.y; k1:=(b.x-a.x)/(b.y-a.y); m.x:=a.x+k1*(m.y-a.y); end else begin k1:=(b.x-a.x)/(b.y-a.y); k2:=(d.x-c.x)/(d.y-c.y); if k1=k2 then exit; m.y:=(c.x-a.x+k1*a.y-k2*c.y)/(k1-k2); m.x:=a.x+k1*(m.y-a.y); end; result:=((m.x-a.x)*(m.x-b.x)<=eps) and ((m.y-a.y)*(m.y-b.y)<=eps) and ((m.x-c.x)*(m.x-d.x)<=eps) and ((m.y-c.y)*(m.y-d.y)<=eps) ; end; var R:TlistG; bary:TRpoint; function compare(item1,item2:pointer):integer; var w:float; begin w:=PtRight(TRpoint(item1^), segment(bary, TRpoint(item2^))); if w>0 then result:=1 else if w<0 then result:=-1 else result:=0; end; function PolyRinter(poly1,poly2:TpolyR):TpolyR; var i,j:integer; IP,A,B:TRpoint; begin R:=TlistG.create(sizeof(TRpoint)); for i:=0 to high(poly1)-1 do for j:=0 to high(poly2)-1 do if SegInterSeg(poly1[i],poly1[i+1],poly2[j],poly2[j+1],IP) then R.add(@IP); for i:=0 to high(poly1)-1 do if PtInside(poly1[i],poly2) then R.add(@poly1[i]); for i:=0 to high(poly2)-1 do if PtInside(poly2[i],poly1) then R.add(@poly2[i]); setLength(result,0); if R.count=0 then exit; bary.x:=0; bary.y:=0; for i:=0 to R.Count-1 do begin bary.x:=bary.x+TRpoint(R[i]^).x; bary.y:=bary.y+TRpoint(R[i]^).y; end; bary.x:=bary.x/R.Count; bary.y:=bary.y/R.Count; R.Sort(compare); if R.count>0 then begin setLength(result,R.Count+1); for i:=0 to R.Count-1 do result[i]:=TRpoint(R[i]^); result[R.count]:=TRpoint(R[0]^); end; end; function PolyRArea(poly:TpolyR):float; var i:integer; begin result:=0; for i:=0 to high(poly)-1 do result:=result+(poly[i+1].x-poly[i].x)*(poly[i+1].y+poly[i].y)/2; result:=abs(result); end; function SegAngle(xa,ya,xb,yb:float):float; var sint,cost:float; aa:float; begin aa:=sqrt(sqr(xa-xb)+sqr(ya-yb)); if (aa<>0) then begin sint:=(yb-ya)/aa; cost:=(xb-xa)/aa; result:=arcsin(sint); if cost<0 then if sint>0 then result:=pi-result else result:=-pi-result; end else result:=0; end; function fonctionSegAngle(xa,ya,xb,yb:float):float; begin result:=SegAngle(xa,ya,xb,yb); end; { Le segment AB et l'angle Dtheta définissent un secteur d'origine A et d'axe de symétrie AB. L'angle au sommet est Dtheta . } function PointInSector(xa,ya,xb,yb,Dtheta,xm,ym:float):boolean; var thetaSec,thetaM:float; Diff1,Diff2,Diff3:float; begin if (xa=xm) and (ya=ym) then begin result:=true; { Le point M est à l'origine du secteur } exit; end; thetaSec:=SegAngle(xa,ya,xb,yb); thetaM:=SegAngle(xa,ya,xm,ym); Diff1:=abs(thetaSec-thetaM); Diff2:=abs(thetaSec-thetaM-2*pi); Diff3:=abs(thetaSec-thetaM+2*pi); if Diff2<Diff1 then Diff1:=Diff2; if Diff3<Diff1 then Diff1:=Diff3; result:=(Diff1<Dtheta/2); end; function fonctionPointInSector(xa,ya,xb,yb,Dtheta,xm,ym:float):boolean; begin if (xa=xb) and (ya=yb) then sortieErreur('Bad sector'); result:=PointInSector(xa,ya,xb,yb,Dtheta,xm,ym); end; procedure testGeom; var M:TRpoint; poly1,poly2:TpolyR; begin M:=Rpoint(-0.2,-1.7); poly1:=poly5R(Rpoint(1,-1),Rpoint(-1,-1),Rpoint(-1,1),Rpoint(1,1)); poly2:=poly5R(Rpoint(1,-10),Rpoint(-1,-10),Rpoint(-1,0),Rpoint(1,0)); messageCentral(Bstr(PtInside(M,poly1))); end; end.
{------------------------------------------------------------------------------} { 单元名称: DWinCtl.pas } { } { 单元作者: 未知 修改作者: 清清 } { 创建日期: 未知 } { } { 功能介绍: 控件实现单元 } { 修改: 增加DTEDIT控件 } { 20080623: 增加BUTTON Moveed属性. 功能:当鼠标移动到控件上,此函数为TRUE } {------------------------------------------------------------------------------} unit DWinCtl; interface uses Windows, Classes, Graphics, Controls, DXDraws, Grids, Wil, Clipbrd; type TClickSound = (csNone, csStone, csGlass, csNorm); TDControl = class; TOnDirectPaint = procedure(Sender: TObject; dsurface: TDirectDrawSurface) of object; TOnKeyPress = procedure(Sender: TObject; var Key: Char) of object; TOnKeyDown = procedure(Sender: TObject; var Key: word; Shift: TShiftState) of object; TOnMouseMove = procedure(Sender: TObject; Shift: TShiftState; X, Y: integer) of object; TOnMouseDown = procedure(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer) of object; TOnMouseUp = procedure(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer) of object; TOnClick = procedure(Sender: TObject) of object; TOnClickEx = procedure(Sender: TObject; X, Y: integer) of object; TOnInRealArea = procedure(Sender: TObject; X, Y: integer; var IsRealArea: Boolean) of object; TOnGridSelect = procedure(Sender: TObject; ACol, ARow: integer; Shift: TShiftState) of object; TOnGridPaint = procedure(Sender: TObject; ACol, ARow: integer; Rect: TRect; State: TGridDrawState; dsurface: TDirectDrawSurface) of object; TOnClickSound = procedure(Sender: TObject; Clicksound: TClickSound) of object; TDControl = class (TCustomControl) private FCaption: string; //0x1F0 FDParent: TDControl; //0x1F4 FEnableFocus: Boolean; //0x1F8 FOnDirectPaint: TOnDirectPaint; //0x1FC FOnKeyPress: TOnKeyPress; //0x200 FOnKeyDown: TOnKeyDown; //0x204 FOnMouseMove: TOnMouseMove; //0x208 FOnMouseDown: TOnMouseDown; //0x20C FOnMouseUp: TOnMouseUp; //0x210 FOnDblClick: TNotifyEvent; //0x214 FOnClick: TOnClickEx; //0x218 FOnInRealArea: TOnInRealArea; //0x21C FOnBackgroundClick: TOnClick; //0x220 procedure SetCaption (str: string); protected FVisible: Boolean; public Background: Boolean; //0x24D DControls: TList; //0x250 //FaceSurface: TDirectDrawSurface; WLib: TWMImages; //0x254 FaceIndex: integer; //0x258 WantReturn: Boolean; //Background老锭, Click狼 荤侩 咯何.. constructor Create (AOwner: TComponent); override; destructor Destroy; override; procedure Paint; override; procedure Loaded; override; function SurfaceX (x: integer): integer; function SurfaceY (y: integer): integer; function LocalX (x: integer): integer; function LocalY (y: integer): integer; procedure AddChild (dcon: TDControl); procedure ChangeChildOrder (dcon: TDControl); function InRange (x, y: integer): Boolean; function KeyPress (var Key: Char): Boolean; dynamic; function KeyDown (var Key: Word; Shift: TShiftState): Boolean; dynamic; function MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; dynamic; function MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; dynamic; function MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; dynamic; function DblClick (X, Y: integer): Boolean; dynamic; function Click (X, Y: integer): Boolean; dynamic; function CanFocusMsg: Boolean; function Focused: Boolean; procedure SetImgIndex (Lib: TWMImages; index: integer); procedure DirectPaint (dsurface: TDirectDrawSurface); dynamic; published property OnDirectPaint: TOnDirectPaint read FOnDirectPaint write FOnDirectPaint; property OnKeyPress: TOnKeyPress read FOnKeyPress write FOnKeyPress; property OnKeyDown: TOnKeyDown read FOnKeyDown write FOnKeyDown; property OnMouseMove: TOnMouseMove read FOnMouseMove write FOnMouseMove; property OnMouseDown: TOnMouseDown read FOnMouseDown write FOnMouseDown; property OnMouseUp: TOnMouseUp read FOnMouseUp write FOnMouseUp; property OnDblClick: TNotifyEvent read FOnDblClick write FOnDblClick; property OnClick: TOnClickEx read FOnClick write FOnClick; property OnInRealArea: TOnInRealArea read FOnInRealArea write FOnInRealArea; property OnBackgroundClick: TOnClick read FOnBackgroundClick write FOnBackgroundClick; property Caption: string read FCaption write SetCaption; property DParent: TDControl read FDParent write FDParent; property Visible: Boolean read FVisible write FVisible; property EnableFocus: Boolean read FEnableFocus write FEnableFocus; property Color; property Font; property Hint; property ShowHint; property Align; end; TDButton = class (TDControl) private FClickSound: TClickSound; FOnClick: TOnClickEx; FOnClickSound: TOnClickSound; public Downed: Boolean; Moveed: Boolean; //20080624 constructor Create (AOwner: TComponent); override; function MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; published property ClickCount: TClickSound read FClickSound write FClickSound; property OnClick: TOnClickEx read FOnClick write FOnClick; property OnClickSound: TOnClickSound read FOnClickSound write FOnClickSound; end; TDGrid = class (TDControl) private FColCount, FRowCount: integer; FColWidth, FRowHeight: integer; FViewTopLine: integer; SelectCell: TPoint; DownPos: TPoint; FOnGridSelect: TOnGridSelect; FOnGridMouseMove: TOnGridSelect; FOnGridPaint: TOnGridPaint; function GetColRow (x, y: integer; var acol, arow: integer): Boolean; public CX, CY: integer; Col, Row: integer; constructor Create (AOwner: TComponent); override; function MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; function Click (X, Y: integer): Boolean; override; procedure DirectPaint (dsurface: TDirectDrawSurface); override; published property ColCount: integer read FColCount write FColCount; property RowCount: integer read FRowCount write FRowCount; property ColWidth: integer read FColWidth write FColWidth; property RowHeight: integer read FRowHeight write FRowHeight; property ViewTopLine: integer read FViewTopLine write FViewTopLine; property OnGridSelect: TOnGridSelect read FOnGridSelect write FOnGridSelect; property OnGridMouseMove: TOnGridSelect read FOnGridMouseMove write FOnGridMouseMove; property OnGridPaint: TOnGridPaint read FOnGridPaint write FOnGridPaint; end; TDWindow = class (TDButton) private FFloating: Boolean; SpotX, SpotY: integer; protected procedure SetVisible (flag: Boolean); public DialogResult: TModalResult; constructor Create (AOwner: TComponent); override; function MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; procedure Show; function ShowModal: integer; published property Visible: Boolean read FVisible write SetVisible; property Floating: Boolean read FFloating write FFloating; end; TDWinManager = class (TComponent) private public DWinList: TList; //list of TDControl; constructor Create (AOwner: TComponent); override; destructor Destroy; override; procedure AddDControl (dcon: TDControl; visible: Boolean); procedure DelDControl (dcon: TDControl); procedure ClearAll; function KeyPress (var Key: Char): Boolean; function KeyDown (var Key: Word; Shift: TShiftState): Boolean; function MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; function MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; function MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; function DblClick (X, Y: integer): Boolean; function Click (X, Y: integer): Boolean; procedure DirectPaint (dsurface: TDirectDrawSurface); end; TDEdit = class(TDControl) private FText: Widestring; FOnChange:TNotifyEvent; FFont:TFont; F3D:boolean; FColor:TColor; FTransparent:boolean; FMaxLength: Integer; XDif:integer; FSelCol:TColor; CursorTime:integer; InputStr:string; KeyByteCount: Byte; boDoubleByte: Boolean; SelStart:integer; SelStop:integer; procedure DoMove; //光标闪烁 procedure DelSelText; function CopySelText():string; procedure SetText (str: Widestring); procedure SetMaxLength(const Value: Integer); protected DrawFocused:boolean; DrawEnabled:boolean; DrawHovered:boolean; CursorVisible:boolean; BlinkSpeed:integer; Hovered:boolean; function KeyDown (var Key: Word; Shift: TShiftState): Boolean; override; function KeyPress (var Key: Char): Boolean; override; function MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; function GetSelCount:integer; public Moveed: Boolean; //20080624 procedure SetFocus(); property SelCount:integer read GetSelCount; function MouseToSelPos(AX:integer):integer; procedure DirectPaint (dsurface: TDirectDrawSurface); override; procedure Update;override; constructor Create (AOwner: TComponent); override; destructor Destroy; override; published property OnChange:TNotifyEvent read FOnChange write FOnChange; property Text: Widestring read FText write SetText; property MaxLength: Integer read FMaxLength write SetMaxLength; property Font:TFont read FFont write FFont; property Ctrl3D:boolean read F3D write F3D; property Color:TColor read FColor write FColor; property SelectionColor:TColor read FSelCol write FSelCol; property Transparent:boolean read FTransparent write FTransparent; end; TDCheckBox = class (TDControl) private FClickSound: TClickSound; FOnClick: TOnClickEx; FOnClickSound: TOnClickSound; FChecked: Boolean; procedure SetChecked(Value: Boolean); function GetChecked: Boolean; public Moveed: Boolean; //20080624 constructor Create (AOwner: TComponent); override; function MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; override; //procedure DirectPaint (dsurface: TDirectDrawSurface); override; function MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; published property ClickCount: TClickSound read FClickSound write FClickSound; property Checked: Boolean read GetChecked write SetChecked; property OnClick: TOnClickEx read FOnClick write FOnClick; property OnClickSound: TOnClickSound read FOnClickSound write FOnClickSound; end; procedure Register; procedure SetDFocus (dcon: TDControl); procedure ReleaseDFocus; procedure SetDCapture (dcon: TDControl); procedure ReleaseDCapture; var MouseCaptureControl: TDControl; //mouse message FocusedControl: TDControl; //Key message MainWinHandle: integer; ModalDWindow: TDControl; implementation procedure Register; begin RegisterComponents('MirGame', [TDWinManager, TDControl, TDButton, TDGrid, TDWindow, TDEdit, TDCheckBox]); end; procedure SetDFocus (dcon: TDControl); begin FocusedControl := dcon; end; procedure ReleaseDFocus; begin FocusedControl := nil; end; procedure SetDCapture (dcon: TDControl); begin SetCapture (MainWinHandle); MouseCaptureControl := dcon; end; procedure ReleaseDCapture; begin ReleaseCapture; MouseCaptureControl := nil; end; {----------------------------- TDControl -------------------------------} constructor TDControl.Create (AOwner: TComponent); begin inherited Create (AOwner); DParent := nil; inherited Visible := FALSE; FEnableFocus := FALSE; Background := FALSE; FOnDirectPaint := nil; FOnKeyPress := nil; FOnKeyDown := nil; FOnMouseMove := nil; FOnMouseDown := nil; FOnMouseUp := nil; FOnInRealArea := nil; DControls := TList.Create; FDParent := nil; Width := 80; Height:= 24; FCaption := ''; FVisible := TRUE; //FaceSurface := nil; WLib := nil; FaceIndex := 0; end; destructor TDControl.Destroy; begin DControls.Free; inherited Destroy; end; function TDControl.Focused: Boolean; //20080624 begin if FocusedControl = Self then Result := True else Result := False; end; procedure TDControl.SetCaption (str: string); begin FCaption := str; if csDesigning in ComponentState then begin Refresh; end; end; procedure TDControl.Paint; begin if csDesigning in ComponentState then begin if self is TDWindow then begin with Canvas do begin Pen.Color := clBlack; MoveTo (0, 0); LineTo (Width-1, 0); LineTo (Width-1, Height-1); LineTo (0, Height-1); LineTo (0, 0); LineTo (Width-1, Height-1); MoveTo (Width-1, 0); LineTo (0, Height-1); TextOut ((Width-TextWidth(Caption)) div 2, (Height-TextHeight(Caption)) div 2, Caption); end; end else begin with Canvas do begin Pen.Color := clBlack; MoveTo (0, 0); LineTo (Width-1, 0); LineTo (Width-1, Height-1); LineTo (0, Height-1); LineTo (0, 0); TextOut ((Width-TextWidth(Caption)) div 2, (Height-TextHeight(Caption)) div 2, Caption); end; end; end; end; procedure TDControl.Loaded; var i: integer; dcon: TDControl; begin if not (csDesigning in ComponentState) then begin if Parent <> nil then if TControl(Parent).ComponentCount > 0 then //20080629 for i:=0 to TControl(Parent).ComponentCount-1 do begin if TControl(Parent).Components[i] is TDControl then begin dcon := TDControl(TControl(Parent).Components[i]); if dcon.DParent = self then begin AddChild (dcon); end; end; end; end; end; //瘤开 谅钎甫 傈眉 谅钎肺 官厕 function TDControl.SurfaceX (x: integer): integer; var d: TDControl; begin d := self; while TRUE do begin if d.DParent = nil then break; x := x + d.DParent.Left; d := d.DParent; end; Result := x; end; function TDControl.SurfaceY (y: integer): integer; var d: TDControl; begin d := self; while TRUE do begin if d.DParent = nil then break; y := y + d.DParent.Top; d := d.DParent; end; Result := y; end; //傈眉谅钎甫 按眉狼 谅钎肺 官厕 function TDControl.LocalX (x: integer): integer; var d: TDControl; begin d := self; while TRUE do begin if d.DParent = nil then break; x := x - d.DParent.Left; d := d.DParent; end; Result := x; end; function TDControl.LocalY (y: integer): integer; var d: TDControl; begin d := self; while TRUE do begin if d.DParent = nil then break; y := y - d.DParent.Top; d := d.DParent; end; Result := y; end; procedure TDControl.AddChild (dcon: TDControl); begin DControls.Add (Pointer (dcon)); end; procedure TDControl.ChangeChildOrder (dcon: TDControl); var i: integer; begin if not (dcon is TDWindow) then exit; //if TDWindow(dcon).Floating then begin //20081024修改 if DControls.Count > 0 then //20080629 for i:=0 to DControls.Count-1 do begin if dcon = DControls[i] then begin DControls.Delete (i); break; end; end; DControls.Add (dcon); //end; end; function TDControl.InRange (x, y: integer): Boolean; var inrange: Boolean; d: TDirectDrawSurface; begin if (x >= Left) and (x < Left+Width) and (y >= Top) and (y < Top+Height) then begin inrange := TRUE; if Assigned (FOnInRealArea) then FOnInRealArea(self, x-Left, y-Top, inrange) else if WLib <> nil then begin d := WLib.Images[FaceIndex]; if d <> nil then if d.Pixels[x-Left, y-Top] <= 0 then inrange := FALSE; end; Result := inrange; end else Result := FALSE; end; function TDControl.KeyPress (var Key: Char): Boolean; var i: integer; begin Result := FALSE; if Background then exit; if DControls.Count > 0 then //20080629 for i:=DControls.Count-1 downto 0 do if TDControl(DControls[i]).Visible then if TDControl(DControls[i]).KeyPress(Key) then begin Result := TRUE; exit; end; if (FocusedControl=self) then begin if Assigned (FOnKeyPress) then FOnKeyPress (self, Key); Result := TRUE; end; end; function TDControl.KeyDown (var Key: Word; Shift: TShiftState): Boolean; var i: integer; begin Result := FALSE; if Background then exit; if DControls.Count > 0 then //20080629 for i:=DControls.Count-1 downto 0 do if TDControl(DControls[i]).Visible then if TDControl(DControls[i]).KeyDown(Key, Shift) then begin Result := TRUE; exit; end; if (FocusedControl=self) then begin if Assigned (FOnKeyDown) then FOnKeyDown (self, Key, Shift); Result := TRUE; end; end; function TDControl.CanFocusMsg: Boolean; begin if (MouseCaptureControl = nil) or ((MouseCaptureControl <> nil) and ((MouseCaptureControl=self) or (MouseCaptureControl=DParent))) then Result := TRUE else Result := FALSE; end; function TDControl.MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; var i: integer; begin Result := FALSE; if DControls.Count > 0 then //20080629 for i:=DControls.Count-1 downto 0 do if TDControl(DControls[i]).Visible then if TDControl(DControls[i]).MouseMove(Shift, X-Left, Y-Top) then begin Result := TRUE; exit; end; if (MouseCaptureControl <> nil) then begin //MouseCapture 捞搁 磊脚捞 快急 if (MouseCaptureControl = self) then begin if Assigned (FOnMouseMove) then FOnMouseMove (self, Shift, X, Y); Result := TRUE; end; exit; end; if Background then exit; if InRange (X, Y) then begin if Assigned (FOnMouseMove) then FOnMouseMove (self, Shift, X, Y); Result := TRUE; end; end; function TDControl.MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; var i: integer; begin Result := FALSE; //showmessage('11'); if DControls.Count > 0 then //20080629 for i:=DControls.Count-1 downto 0 do if TDControl(DControls[i]).Visible then if TDControl(DControls[i]).MouseDown(Button, Shift, X-Left, Y-Top) then begin //showmessage('22'); Result := TRUE; exit; end; if Background then begin if Assigned (FOnBackgroundClick) then begin WantReturn := FALSE; FOnBackgroundClick (self); if WantReturn then Result := TRUE; end; ReleaseDFocus; exit; end; if CanFocusMsg then begin if InRange (X, Y) or (MouseCaptureControl = self) then begin if Assigned (FOnMouseDown) then FOnMouseDown (self, Button, Shift, X, Y); if EnableFocus then SetDFocus (self); //else ReleaseDFocus; Result := TRUE; end; end; end; function TDControl.MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; var i: integer; begin Result := FALSE; if DControls.Count > 0 then //20080629 for i:=DControls.Count-1 downto 0 do if TDControl(DControls[i]).Visible then if TDControl(DControls[i]).MouseUp(Button, Shift, X-Left, Y-Top) then begin Result := TRUE; exit; end; if (MouseCaptureControl <> nil) then begin //MouseCapture 捞搁 磊脚捞 快急 if (MouseCaptureControl = self) then begin if Assigned (FOnMouseUp) then FOnMouseUp (self, Button, Shift, X, Y); Result := TRUE; end; exit; end; if Background then exit; if InRange (X, Y) then begin if Assigned (FOnMouseUp) then FOnMouseUp (self, Button, Shift, X, Y); Result := TRUE; end; end; function TDControl.DblClick (X, Y: integer): Boolean; var i: integer; begin Result := FALSE; if (MouseCaptureControl <> nil) then begin //MouseCapture 捞搁 磊脚捞 快急 if (MouseCaptureControl = self) then begin if Assigned (FOnDblClick) then FOnDblClick (self); Result := TRUE; end; exit; end; if DControls.Count > 0 then //20080629 for i:=DControls.Count-1 downto 0 do if TDControl(DControls[i]).Visible then if TDControl(DControls[i]).DblClick(X-Left, Y-Top) then begin Result := TRUE; exit; end; if Background then exit; if InRange (X, Y) then begin if Assigned (FOnDblClick) then FOnDblClick (self); Result := TRUE; end; end; function TDControl.Click (X, Y: integer): Boolean; var i: integer; begin Result := FALSE; if (MouseCaptureControl <> nil) then begin //MouseCapture 捞搁 磊脚捞 快急 if (MouseCaptureControl = self) then begin if Assigned (FOnClick) then FOnClick (self, X, Y); Result := TRUE; end; exit; end; if DControls.Count > 0 then //20080629 for i:=DControls.Count-1 downto 0 do if TDControl(DControls[i]).Visible then if TDControl(DControls[i]).Click(X-Left, Y-Top) then begin Result := TRUE; exit; end; if Background then exit; if InRange (X, Y) then begin if Assigned (FOnClick) then FOnClick (self, X, Y); Result := TRUE; end; end; procedure TDControl.SetImgIndex (Lib: TWMImages; index: integer); var d: TDirectDrawSurface; begin //FaceSurface := dsurface; if Lib <> nil then begin d := Lib.Images[index]; WLib := Lib; FaceIndex := index; if d <> nil then begin Width := d.Width; Height := d.Height; end; end; end; procedure TDControl.DirectPaint (dsurface: TDirectDrawSurface); var i: integer; d: TDirectDrawSurface; begin if Assigned (FOnDirectPaint) then FOnDirectPaint (self, dsurface) else if WLib <> nil then begin d := WLib.Images[FaceIndex]; if d <> nil then dsurface.Draw (SurfaceX(Left), SurfaceY(Top), d.ClientRect, d, TRUE); end; if DControls.Count > 0 then //20080629 for i:=0 to DControls.Count-1 do if TDControl(DControls[i]).Visible then TDControl(DControls[i]).DirectPaint (dsurface); end; {--------------------- TDButton --------------------------} constructor TDButton.Create (AOwner: TComponent); begin inherited Create (AOwner); Downed := FALSE; Moveed := False; FOnClick := nil; FEnableFocus := TRUE; FClickSound := csNone; end; function TDButton.MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; begin Result := inherited MouseMove (Shift, X, Y); Moveed := Result; if (not Background) and (not Result) then begin Result := inherited MouseMove (Shift, X, Y); if MouseCaptureControl = self then if InRange (X, Y) then Downed := TRUE else Downed := FALSE; end; end; function TDButton.MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin Result := FALSE; if inherited MouseDown (Button, Shift, X, Y) then begin if (not Background) and (MouseCaptureControl=nil) then begin Downed := TRUE; SetDCapture (self); end; Result := TRUE; end; end; function TDButton.MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin Result := FALSE; if inherited MouseUp (Button, Shift, X, Y) then begin ReleaseDCapture; if not Background then begin if InRange (X, Y) then begin if Assigned (FOnClickSound) then FOnClickSound(self, FClickSound); if Assigned (FOnClick) then FOnClick(self, X, Y); end; end; Downed := FALSE; Result := TRUE; exit; end else begin ReleaseDCapture; Downed := FALSE; end; end; {------------------------- TDGrid --------------------------} constructor TDGrid.Create (AOwner: TComponent); begin inherited Create (AOwner); FColCount := 8; FRowCount := 5; FColWidth := 36; FRowHeight:= 32; FOnGridSelect := nil; FOnGridMouseMove := nil; FOnGridPaint := nil; end; function TDGrid.GetColRow (x, y: integer; var acol, arow: integer): Boolean; begin Result := FALSE; if InRange (x, y) then begin acol := (x-Left) div FColWidth; arow := (y-Top) div FRowHeight; Result := TRUE; end; end; function TDGrid.MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; var acol, arow: integer; begin Result := FALSE; if mbLeft = Button then begin if GetColRow (X, Y, acol, arow) then begin SelectCell.X := acol; SelectCell.Y := arow; DownPos.X := X; DownPos.Y := Y; SetDCapture (self); Result := TRUE; end; end; end; function TDGrid.MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; var acol, arow: integer; begin Result := FALSE; if InRange (X, Y) then begin if GetColRow (X, Y, acol, arow) then begin if Assigned (FOnGridMouseMove) then FOnGridMouseMove (self, acol, arow, Shift); end; Result := TRUE; end; end; function TDGrid.MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; var acol, arow: integer; begin Result := FALSE; if mbLeft = Button then begin if GetColRow (X, Y, acol, arow) then begin if (SelectCell.X = acol) and (SelectCell.Y = arow) then begin Col := acol; Row := arow; if Assigned (FOnGridSelect) then FOnGridSelect (self, acol, arow, Shift); end; Result := TRUE; end; ReleaseDCapture; end; end; function TDGrid.Click (X, Y: integer): Boolean; {var acol, arow: integer; } begin Result := FALSE; { if GetColRow (X, Y, acol, arow) then begin if Assigned (FOnGridSelect) then FOnGridSelect (self, acol, arow, []); Result := TRUE; end; } end; procedure TDGrid.DirectPaint (dsurface: TDirectDrawSurface); var i, j: integer; rc: TRect; begin if Assigned (FOnGridPaint) then if FRowCount > 0 then //20080629 for i:=0 to FRowCount-1 do for j:=0 to FColCount-1 do begin rc := Rect (Left + j*FColWidth, Top + i*FRowHeight, Left+j*(FColWidth+1)-1, Top+i*(FRowHeight+1)-1); if (SelectCell.Y = i) and (SelectCell.X = j) then FOnGridPaint (self, j, i, rc, [gdSelected], dsurface) else FOnGridPaint (self, j, i, rc, [], dsurface); end; end; {--------------------- TDWindown --------------------------} constructor TDWindow.Create (AOwner: TComponent); begin inherited Create (AOwner); FFloating := FALSE; FEnableFocus := TRUE; Width := 120; Height := 120; end; procedure TDWindow.SetVisible (flag: Boolean); begin FVisible := flag; if Floating then begin if DParent <> nil then DParent.ChangeChildOrder (self); end; end; function TDWindow.MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; //var // al, at: integer; begin Result := inherited MouseMove (Shift, X, Y); if Result and FFloating and (MouseCaptureControl=self) then begin if (SpotX <> X) or (SpotY <> Y) then begin Left := Left + (X - SpotX); Top := Top + (Y - SpotY); //if al+Width < WINLEFT then al := WINLEFT - Width; //if al > WINRIGHT then al := WINRIGHT; //if at+Height < WINTOP then at := WINTOP - Height; //if at+Height > BOTTOMEDGE then at := BOTTOMEDGE-Height; //Left := al; //Top := at; SpotX := X; SpotY := Y; end; end; end; function TDWindow.MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin Result := inherited MouseDown (Button, Shift, X, Y); if Result then begin //if Floating then begin //20081024修改 if DParent <> nil then DParent.ChangeChildOrder (self); //end; SpotX := X; SpotY := Y; end; end; function TDWindow.MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin Result := inherited MouseUp (Button, Shift, X, Y); end; procedure TDWindow.Show; begin Visible := TRUE; if Floating then begin if DParent <> nil then DParent.ChangeChildOrder (self); end; if EnableFocus then SetDFocus (self); end; function TDWindow.ShowModal: integer; begin Result:=0;//Jacky Visible := TRUE; ModalDWindow := self; if EnableFocus then SetDFocus (self); end; {--------------------- TDWinManager --------------------------} constructor TDWinManager.Create (AOwner: TComponent); begin inherited Create (AOwner); DWinList := TList.Create; MouseCaptureControl := nil; FocusedControl := nil; end; destructor TDWinManager.Destroy; begin DWinList.Free; inherited Destroy; end; procedure TDWinManager.ClearAll; begin DWinList.Clear; end; procedure TDWinManager.AddDControl (dcon: TDControl; visible: Boolean); begin dcon.Visible := visible; DWinList.Add (dcon); end; procedure TDWinManager.DelDControl (dcon: TDControl); var i: integer; begin if DWinList.Count > 0 then //20080629 for i:=0 to DWinList.Count-1 do if DWinList[i] = dcon then begin DWinList.Delete (i); break; end; end; function TDWinManager.KeyPress (var Key: Char): Boolean; begin Result := FALSE; if ModalDWindow <> nil then begin if ModalDWindow.Visible then begin with ModalDWindow do Result := KeyPress (Key); exit; end else ModalDWindow := nil; Key := #0; //ModalDWindow啊 KeyDown阑 芭摹搁辑 Visible=false肺 函窍搁辑 //KeyPress甫 促矫芭媚辑 ModalDwindow=nil捞 等促. end; if FocusedControl <> nil then begin if FocusedControl.Visible then begin Result := FocusedControl.KeyPress (Key); end else ReleaseDFocus; end; {for i:=0 to DWinList.Count-1 do begin if TDControl(DWinList[i]).Visible then begin if TDControl(DWinList[i]).KeyPress (Key) then begin Result := TRUE; break; end; end; end; } end; function TDWinManager.KeyDown (var Key: Word; Shift: TShiftState): Boolean; begin Result := FALSE; if ModalDWindow <> nil then begin if ModalDWindow.Visible then begin with ModalDWindow do Result := KeyDown (Key, Shift); exit; end else MOdalDWindow := nil; end; if FocusedControl <> nil then begin if FocusedControl.Visible then Result := FocusedControl.KeyDown (Key, Shift) else ReleaseDFocus; end; {for i:=0 to DWinList.Count-1 do begin if TDControl(DWinList[i]).Visible then begin if TDControl(DWinList[i]).KeyDown (Key, Shift) then begin Result := TRUE; break; end; end; end; } end; function TDWinManager.MouseMove (Shift: TShiftState; X, Y: Integer): Boolean; var i: integer; begin Result := FALSE; if ModalDWindow <> nil then begin if ModalDWindow.Visible then begin with ModalDWindow do MouseMove (Shift, LocalX(X), LocalY(Y)); Result := TRUE; exit; end else MOdalDWindow := nil; end; if MouseCaptureControl <> nil then begin with MouseCaptureControl do Result := MouseMove (Shift, LocalX(X), LocalY(Y)); end else if DWinList.Count > 0 then //20080629 for i:=0 to DWinList.Count-1 do begin if TDControl(DWinList[i]).Visible then begin if TDControl(DWinList[i]).MouseMove (Shift, X, Y) then begin Result := TRUE; break; end; end; end; end; function TDWinManager.MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; var i: integer; begin Result := FALSE; if ModalDWindow <> nil then begin if ModalDWindow.Visible then begin with ModalDWindow do MouseDown (Button, Shift, LocalX(X), LocalY(Y)); Result := TRUE; exit; end else ModalDWindow := nil; end; if MouseCaptureControl <> nil then begin with MouseCaptureControl do Result := MouseDown (Button, Shift, LocalX(X), LocalY(Y)); end else if DWinList.Count > 0 then //20080629 for i:=0 to DWinList.Count-1 do begin if TDControl(DWinList[i]).Visible then begin if TDControl(DWinList[i]).MouseDown (Button, Shift, X, Y) then begin Result := TRUE; break; end; end; end; end; function TDWinManager.MouseUp (Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; var i: integer; begin Result := TRUE; if ModalDWindow <> nil then begin if ModalDWindow.Visible then begin with ModalDWindow do Result := MouseUp (Button, Shift, LocalX(X), LocalY(Y)); exit; end else ModalDWindow := nil; end; if MouseCaptureControl <> nil then begin with MouseCaptureControl do Result := MouseUp (Button, Shift, LocalX(X), LocalY(Y)); end else if DWinList.Count > 0 then //20080629 for i:=0 to DWinList.Count-1 do begin if TDControl(DWinList[i]).Visible then begin if TDControl(DWinList[i]).MouseUp (Button, Shift, X, Y) then begin Result := TRUE; break; end; end; end; end; function TDWinManager.DblClick (X, Y: integer): Boolean; var i: integer; begin Result := TRUE; if ModalDWindow <> nil then begin if ModalDWindow.Visible then begin with ModalDWindow do Result := DblClick (LocalX(X), LocalY(Y)); exit; end else ModalDWindow := nil; end; if MouseCaptureControl <> nil then begin with MouseCaptureControl do Result := DblClick (LocalX(X), LocalY(Y)); end else if DWinList.Count > 0 then //20080629 for i:=0 to DWinList.Count-1 do begin if TDControl(DWinList[i]).Visible then begin if TDControl(DWinList[i]).DblClick (X, Y) then begin Result := TRUE; break; end; end; end; end; function TDWinManager.Click (X, Y: integer): Boolean; var i: integer; begin Result := TRUE; if ModalDWindow <> nil then begin if ModalDWindow.Visible then begin with ModalDWindow do Result := Click (LocalX(X), LocalY(Y)); exit; end else ModalDWindow := nil; end; if MouseCaptureControl <> nil then begin with MouseCaptureControl do Result := Click (LocalX(X), LocalY(Y)); end else if DWinList.Count > 0 then //20080629 for i:=0 to DWinList.Count-1 do begin if TDControl(DWinList[i]).Visible then begin if TDControl(DWinList[i]).Click (X, Y) then begin Result := TRUE; break; end; end; end; end; procedure TDWinManager.DirectPaint (dsurface: TDirectDrawSurface); var i: integer; begin if DWinList.Count > 0 then //20080629 for i:=0 to DWinList.Count-1 do begin if TDControl(DWinList[i]).Visible then begin TDControl(DWinList[i]).DirectPaint (dsurface); end; end; if ModalDWindow <> nil then begin if ModalDWindow.Visible then with ModalDWindow do DirectPaint (dsurface); end; end; { TDEdit } constructor TDEdit.Create(AOwner: TComponent); begin inherited Create (AOwner); //组件创建 //F3D := true; FColor := clWhite; //字体颜色 Width := 30; //宽度 Height := 19; //高度 //Cursor := crIBeam; //光标 BorderWidth := 2; //边框宽度 Font := TFont.Create; //字体创建 //FCanGetFocus := true; Moveed := False; BlinkSpeed := 20; //光标闪烁 FSelCol := clHotLight; //选择颜色 FText:= ''; KeyByteCount := 0; FMaxLength := 0; //FEnableFocus := True; //是否有焦点 end; //删除文字 procedure TDEdit.DelSelText; var s:integer; begin s := selStart; if SelStart > SelStop then s := SelStop; Delete(FText,S+1,SelCount); SelStart := s; SelStop := s; end; function TDEdit.CopySelText():string; var s:Integer; begin Result := ''; s := SelStart; if SelStart > SelStop then s := SelStop; Result := Copy(FText,S+1,SelCount); end; //画的方法 procedure TDEdit.DirectPaint(dsurface: TDirectDrawSurface); var SelStartX:integer; SelStopX:integer; Ypos:integer; begin with dsurface.Canvas do begin if not FTransparent then begin Brush.Color := FColor;//FSelCol; FillRect(Rect(SurfaceX(Left), //左边 SurfaceY(Top), //上边 SurfaceX(Left)+Width, //右边 SurfaceY(Top)+Height));//下边 end; inherited DirectPaint(dsurface); //if DesignMode then exit; // Lock; if assigned(Font) then Canvas.Font.Assign(Font); SelStartX := TextWidth(copy(FText,1,SelStart)); SelStopX := TextWidth(copy(FText,1,SelStop)); YPos := ((Height) - TextHeight(FText)) div 2; XDif := 0; if SelStopX > Width-5 then begin XDif := SelStopX-Width+TextWidth('W')*2; end; {rgn := Windows.CreateRectRgnIndirect(rect(BoundsRect.Left+BorderWidth,BoundsRect.Top+BorderWidth, BoundsRect.Right-BorderWidth,BoundsRect.Bottom-BorderWidth)); Windows.SelectClipRgn(Canvas.Handle,rgn); } {*********此函数为选择了某字符而变色*******} //showmessage(inttostr(SurfaceX(Left))); //Canvas.FillRect(rect(X+SelStartX+1-XDif,Y+borderwidth+1,X+SelStopX+1-XDif,Y+Self.Height-BorderWidth)); if (SelCount > 0) and (FocusedControl = Self) then begin Brush.Color := FSelCol;//FSelCol; FillRect(Rect(SurfaceX(Left)+SelStartX+1-XDif, //左边 SurfaceY(Top)+TextHeight('H') div 2 -2, //上边 SurfaceX(Left)+SelStopX+1-XDif, //右边 SurfaceY(Top)+Height-TextHeight('H') div 2 + 3));//下边 end; Brush.Style := bsClear; {******************************************} //输出Capiton内容 Font.Color := FFont.Color; TextRect(rect(SurfaceX(Left),SurfaceY(Top),SurfaceX(Left)+Width,SurfaceY(Top)+Height), SurfaceX(Left)+BorderWidth-XDif, SurfaceY(Top)+YPos + 1,FText); //TextOut(SurfaceX(Left)+BorderWidth-XDif,SurfaceY(Top)+YPos,FText); //Windows.DeleteObject(rgn); Release; DoMove; if (FocusedControl=self) and (cursorvisible) then if cursorvisible then //光标是否可见 闪烁用的这个 begin //画光标 pen.Color := clWhite; //左 //上 //右 Rectangle(SurfaceX(Left)+SelStopX+BorderWidth-XDif,SurfaceY(Top)+TextHeight('H') div 2 -2,SurfaceX(Left)+SelStopX-XDif+BorderWidth+2,SurfaceY(Top)+Height-TextHeight('H') div 2+3); end; // UnLock; Release; end; end; //光标闪烁函数 procedure TDEdit.DoMove; begin CursorTime := CursorTime + 1; If CursorTime > BlinkSpeed then begin CursorVisible := not CursorVisible; CursorTime := 0; end; end; //得到选择数量 function TDEdit.GetSelCount: integer; begin result := abs(SelStop-SelStart); end; //最大输入数量 procedure TDEdit.SetMaxLength(const Value: Integer); begin FMaxLength := Value; if (FMaxLength > 0) and (Length(string(FText)) > FMaxLength) then begin FText := Copy(FText, 1, FMaxLength); if (SelStart > Length(string(FText))) then SelStart := Length(string(FText)); end; end; function TDEdit.KeyDown(var Key: Word; Shift: TShiftState): Boolean; var Clipboard: TClipboard; AddTx: string; begin //if not FVisible then ReleaseDFocus; if not FVisible or not DParent.FVisible then Exit; Result := inherited KeyDown(Key, Shift); //处理按键 主程序不执行了按键效果 if (Result) and (not Background) then begin //Result := inherited KeyDown(Key, Shift); CursorVisible := true; CursorTime := 0; if key = VK_BACK then begin if SelCount = 0 then begin Delete(FText,SelStart,1); SelStart := SelStart-1; SelStop := SelStart; end else begin DelSelText; end; if (Assigned(FOnChange)) then FOnChange(Self); end; if key = VK_DELETE then begin if SelCount = 0 then begin Delete(FText,SelStart+1,1); end else DelSelText; if (Assigned(FOnChange)) then FOnChange(Self); end; if key = VK_LEFT then begin if ssShift in Shift then begin SelStop := SelStop-1; end else begin if SelStop < SelStart then begin SelStart := SelStop; end else begin if SelStop > SelStart then begin SelStart := SelStop; end else begin SelStart := SelStart-1; SelStop := SelStart; end; end; end; end; if key = VK_HOME then begin if ssShift in Shift then begin SelStop := 0; end else begin SelStart := 0; SelStop := 0; end; end; if key = VK_END then begin if ssShift in Shift then begin SelStop := Length(FText); end else begin SelStart := Length(FText); SelStop := Length(FText); end; end; if key = VK_RIGHT then begin if ssShift in Shift then begin SelStop := SelStop+1; end else begin if SelStop < SelStart then begin SelStart := SelStop; end else begin if SelStop > SelStart then begin SelStart := SelStop; end else begin SelStart := SelStart+1; SelStop := SelStart; end; end; end; end; if (Key = Byte('V')) and (ssCtrl in Shift) then begin //粘贴代码 Clipboard := TClipboard.Create(); AddTx := Clipboard.AsText; Insert(AddTx, FText, SelStart + 1); Inc(SelStart, Length(AddTx)); if (FMaxLength > 0) and (Length(FText) > FMaxLength) then begin FText := Copy(FText, 1, FMaxLength); if (SelStart > Length(FText)) then SelStart := Length(FText); end; SelStop := SelStart; Clipboard.Free(); if (Assigned(FOnChange)) then FOnChange(Self); end; if (Key = Byte('C')) and (ssCtrl in Shift) then begin //复制 Clipboard := TClipboard.Create(); Clipboard.AsText := CopySelText(); //Showmessage(CopySelText); Clipboard.Free(); end; if SelStart < 0 then SelStart := 0; if SelStart > Length(FText) then SelStart := Length(FText); if SelStop < 0 then SelStop := 0; if SelStop > Length(FText) then SelStop := Length(FText); end; end; function TDEdit.KeyPress(var Key: Char): Boolean; begin if not FVisible or not DParent.FVisible then Exit; if (inherited KeyPress(Key)) and (not Background) then begin Result := inherited KeyPress(Key); //处理按键 主程序不执行了按键效果 if (ord(key) > 31) and ((ord(key) < 127) or (ord(key) > 159)) then begin if SelCount > 0 then DelSelText; {if (FMaxLength > 0) and (Length(string(FText)) > FMaxLength) then begin FText := Copy(FText, 1, FMaxLength); if (SelStop > Length(string(FText))) then SelStop := Length(string(FText)); end; } //--------------By huasoft------------------------------------------------------- if ((FMaxLength < 1) or (Length(string(FText)) < FMaxLength)) then begin if IsDBCSLeadByte(Ord(Key)) or boDoubleByte then //判断是否是汉字 begin boDoubleByte :=true; Inc(KeyByteCount); //字节数 InputStr:=InputStr+ Key; end; if not boDoubleByte then begin if SelStart >= Length(FText) then begin FText := FText + Key; end else begin Insert(Key,FText,SelStart+1); end; Inc(SelStart); end else begin if KeyByteCount >= 2 then begin //字节数为2则为汉字 if SelStart >= Length(FText) then begin FText := FText + InputStr; end else begin Insert(InputStr,FText,SelStart+1); end; boDoubleByte := False; KeyByteCount := 0; InputStr := ''; Inc(SelStart); end; end; //SelStart := SelStart+1; SelStop := SelStart; end; if (Assigned(FOnChange)) then FOnChange(Self); end; end; end; //先试这个 我给你看 //这个是鼠标移动事件 就这地方有问题 function TDEdit.MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; begin if not FVisible or not DParent.FVisible then Exit; //if ssLeft in Shift then begin Result := inherited MouseMove (Shift, X, Y); Moveed := Result; if ssLeft in Shift then begin if (not Background){ and (not Result)} then begin Result := inherited MouseMove (Shift, X, Y); if MouseCaptureControl = self then begin {if InRange (X, Y) then} SelStop := MouseToSelPos(x-left); //else Downed := FALSE; end; end; end; end; //这个是鼠标按下的事件 没问题 function TDEdit.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin { Result := FALSE; if inherited MouseDown (Button, Shift, X, Y) then begin //如果是控件本身 if mbLeft = Button then if not Background then begin SelStart := MouseToSelPos(x-left); SelStop := SelStart; SetDCapture (self); Result := True; end; end; } if not FVisible or not DParent.FVisible then Exit; Result := FALSE; if inherited MouseDown (Button, Shift, X, Y) then begin if (not Background) and (MouseCaptureControl=nil) then begin SelStart := MouseToSelPos(x-left); SelStop := SelStart; SetDCapture (self); end; Result := TRUE; end; end; function TDEdit.MouseToSelPos(AX: integer): integer; var I:integer; AX1: Integer; begin Result := length(FText); AX1 := AX-Borderwidth+XDif -3; if length(FText) <= 0 then begin //2080629 Exit; end; for i := 0 to length(FText) do begin if Canvas.TextWidth(copy(FText,1,I)) >= AX1 then begin Result := I; break; end; end; end; procedure TDEdit.Update; begin inherited; end; function TDEdit.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin Result := FALSE; if inherited MouseUp (Button, Shift, X, Y) then begin ReleaseDCapture; if not Background then begin if InRange (X, Y) then begin if Assigned (FOnClick) then FOnClick(self, X, Y); end; end; Result := TRUE; exit; end else begin ReleaseDCapture; end; end; procedure TDEdit.SetText (str: Widestring); begin FText := str; if csDesigning in ComponentState then begin Refresh; end; end; procedure TDEdit.SetFocus; begin SetDFocus (self); end; destructor TDEdit.Destroy; begin Font.Free; inherited; end; { TDCheckBox } constructor TDCheckBox.Create(AOwner: TComponent); begin inherited Create (AOwner); Moveed := False; FChecked := False; FOnClick := nil; FEnableFocus := TRUE; FClickSound := csNone; end; {procedure TDCheckBox.DirectPaint(dsurface: TDirectDrawSurface); begin end; } function TDCheckBox.GetChecked: Boolean; begin Result := FChecked; end; procedure TDCheckBox.SetChecked(Value: Boolean); begin if FChecked <> Value then FChecked := Value; end; function TDCheckBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin Result := FALSE; if inherited MouseDown (Button, Shift, X, Y) then begin if (not Background) and (MouseCaptureControl=nil) then begin SetDCapture (self); end; Result := TRUE; end; end; function TDCheckBox.MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; begin Result := inherited MouseMove (Shift, X, Y); Moveed := Result; if (not Background) and (not Result) then Result := inherited MouseMove (Shift, X, Y); end; function TDCheckBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin Result := FALSE; if inherited MouseUp (Button, Shift, X, Y) then begin ReleaseDCapture; if not Background then begin if InRange (X, Y) then begin if Button = mbLeft then begin SetChecked(not FChecked); if Assigned (FOnClickSound) then FOnClickSound(self, FClickSound); if Assigned (FOnClick) then FOnClick(self, X, Y); end; end; end; Result := TRUE; exit; end else begin ReleaseDCapture; end; end; end.
{: Explosion FX Demo (Matheus, matheus@tilt.net)<p> This project demonstrates the use of TGLBExplosionFx. Nothing out of ordinary as one can see. Load the mesh, load the default settings, click "on" to initiate the demo, "reset" to reset :)<p> The information of the mesh is cached on the cache variable, that is restored every time the demo is reseted. The MaxSteps property defines the max number of frames the explosion will be rendered. Speed is the scalar speed each face is issued in the rendering<p> } unit Unit1; interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, GLScene, GLVectorFileObjects, GLLCLViewer, GLCadencer, GLExplosionFx, GLFile3DS, ExtCtrls, GLCrossPlatform, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) viewer: TGLSceneViewer; GLScene1: TGLScene; Camera1: TGLCamera; GLLightSource1: TGLLightSource; mesh: TGLFreeForm; GLCadencer1: TGLCadencer; Panel1: TPanel; CheckOn: TCheckBox; Button1: TButton; StepBar: TProgressBar; Label2: TLabel; MaxStepsBar: TTrackBar; Label1: TLabel; Label3: TLabel; SpeedBar: TTrackBar; procedure FormCreate(Sender: TObject); procedure CheckOnClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure viewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); procedure viewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); procedure SpeedBarChange(Sender: TObject); procedure MaxStepsBarChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; vx, vy: integer; Cache: TMeshObjectList; implementation {$R *.lfm} uses GLUtils; procedure TForm1.FormCreate(Sender: TObject); var exp: TGLBExplosionFx; begin SetGLSceneMediaDir(); //load mesh mesh.LoadFromFile('mushroom.3ds'); //cache information cache := TMeshObjectList.Create; cache.Assign(mesh.MeshObjects); //default settings exp := TGLBExplosionFx(mesh.effects.items[0]); exp.MaxSteps := 0; exp.Speed := 0.1; end; procedure TForm1.CheckOnClick(Sender: TObject); begin //turn on/off TGLBExplosionFx(mesh.Effects.items[0]).Enabled := checkon.Checked; end; procedure TForm1.Button1Click(Sender: TObject); begin //reset simulation TGLBExplosionFx(mesh.effects.items[0]).Reset; checkon.Checked := False; //restore the mesh mesh.MeshObjects.Assign(Cache); mesh.StructureChanged; end; procedure TForm1.viewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); begin if shift <> [ssLeft] then exit; camera1.MoveAroundTarget(y - vy, x - vx); vx := x; vy := y; end; procedure TForm1.viewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); begin vx := x; vy := y; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); begin viewer.Invalidate; StepBar.Position := TGLBExplosionFx(mesh.Effects.items[0]).Step; end; procedure TForm1.SpeedBarChange(Sender: TObject); begin TGLBExplosionFx(mesh.Effects.items[0]).Speed := speedBar.Position / 10; end; procedure TForm1.MaxStepsBarChange(Sender: TObject); begin TGLBExplosionFx(mesh.Effects.items[0]).MaxSteps := MaxStepsBar.Position; stepBar.Max := MaxStepsBar.Position; end; end.
unit eaterSanitize; interface uses SysUtils, jsonDoc, MSXML2_TLB; procedure SanitizeInit; function SanitizeTrim(const x:WideString):WideString; procedure SanitizePostID(var id:string); function SanitizeTitle(const title:WideString):WideString; procedure SanitizeContentType(var rt:WideString); procedure SanitizeUnicode(var rw:WideString); procedure SanitizeStartImg(var content:WideString); procedure SanitizeWPImgData(var content:WideString); procedure SanitizeFoafImg(var content:WideString); function EncodeNonHTMLContent(const title:WideString):WideString; function DisplayShortURL(const URL:string):string; function FindPrefixAndCrop(var data:WideString;const pattern:WideString):boolean; function FindMatch(const data:WideString;const pattern:WideString):WideString; function FixUndeclNSPrefix(doc:DOMDocument60;var FeedData:WideString):boolean; function FixNBSP(doc:DOMDocument60;var FeedData:WideString):boolean; procedure SanitizeYoutubeURL(var URL:string); procedure PerformReplace(data:IJSONDocument;var subject:WideString); implementation uses VBScript_RegExp_55_TLB, Variants, eaterUtils; var rh0,rh1,rh2,rh3,rh4,rh5,rh6,rh7,rhUTM,rhCID,rhLFs,rhTrim, rhStartImg,rhImgData,rhImgFoaf:RegExp; procedure SanitizeInit; begin rh0:=CoRegExp.Create; rh0.Pattern:='[\u0000-\u001F]'; rh0.Global:=true; rh1:=CoRegExp.Create; rh1.Pattern:='&'; rh1.Global:=true; rh2:=CoRegExp.Create; rh2.Pattern:='<'; rh2.Global:=true; rh3:=CoRegExp.Create; rh3.Pattern:='>'; rh3.Global:=true; rh4:=CoRegExp.Create; rh4.Pattern:='"'; rh4.Global:=true; rh5:=CoRegExp.Create; rh5.Pattern:='&amp;([a-z]+?);'; rh5.Global:=true; rh6:=CoRegExp.Create; rh6.Pattern:='&lt;(i|b|u|s|em|strong|sub|sup)&gt;(.*?)&lt;/\1&gt;'; rh6.Global:=true; rh6.IgnoreCase:=true; rh7:=CoRegExp.Create; rh7.Pattern:='&amp;(#x?[0-9a-f]+?|[0-9]+?);'; rh7.Global:=true; rh7.IgnoreCase:=true; rhUTM:=CoRegExp.Create; rhUTM.Pattern:='\?utm_[^\?]+?$'; rhCID:=CoRegExp.Create; rhCID.Pattern:='\?cid=public-rss_\d{8}$'; rhLFs:=CoRegExp.Create; rhLFs.Pattern:='(\x0D?\x0A)+'; rhLFs.Global:=true; rhTrim:=CoRegExp.Create; rhTrim.Pattern:='^\s*(.*?)\s*$'; rhStartImg:=CoRegExp.Create; rhStartImg.Pattern:='^\s*?(<(div|p)[^>]*?>\s*?)?(<img[^>]*?>)\s*(?!<br)'; rhStartImg.IgnoreCase:=true; rhImgData:=nil;//see SanitizeWPImgData rhImgFoaf:=nil;//see SanitizeFoafImg end; function SanitizeTrim(const x:WideString):WideString; begin Result:=rhTrim.Replace(x,'$1'); end; procedure SanitizePostID(var id:string); begin //strip '?utm_'... query string if rhUTM.Test(id) then id:=rhUTM.Replace(id,''); if rhCID.Test(id) then id:=rhCID.Replace(id,''); end; function SanitizeTitle(const title:WideString):WideString; begin Result:= rh7.Replace( rh6.Replace( rh5.Replace( rh4.Replace( rh3.Replace( rh2.Replace( rh1.Replace( rh0.Replace( title ,' ')//rh0 ,'&amp;')//rh1 ,'&lt;')//rh2 ,'&gt;')//rh3 ,'&quot;')//rh4 ,'&$1;')//rh5 ,'<$1>$2</$1>')//rh6 ,'&$1;')//rh7 ; if Length(Result)<5 then Result:=Result+'&nbsp;&nbsp;&nbsp;'; end; procedure SanitizeContentType(var rt:WideString); var i:integer; begin if rt<>'' then begin i:=1; while (i<=Length(rt)) and (rt[i]<>';') do inc(i); if i<=Length(rt) then while (i>0) and (rt[i]<=' ') do dec(i); if (i<=Length(rt)) then SetLength(rt,i-1); end; end; procedure SanitizeUnicode(var rw:WideString); var i:integer; begin for i:=1 to Length(rw) do case word(rw[i]) of 0..8,11,12,14..31:rw[i]:=#9; 9,10,13:;//leave as-is else ;//leave as-is end; end; procedure SanitizeStartImg(var content:WideString); begin if rhStartImg.Test(content) then content:=rhStartImg.Replace(content,'$1$3<br />'); end; procedure SanitizeWPImgData(var content:WideString); begin if rhImgData=nil then begin rhImgData:=CoRegExp.Create; rhImgData.Pattern:='<img(\s+?)data-(srcset="[^"]*?"\s+?)data-(src="[^"]+?")'; //TODO: negative lookaround: no src/srcset="" rhImgData.Global:=true; end; content:=rhImgData.Replace(content,'<img$1$2$3'); end; procedure SanitizeFoafImg(var content:WideString); begin if rhImgFoaf=nil then begin rhImgFoaf:=CoRegExp.Create; rhImgFoaf.Pattern:='<noscript class="adaptive-image"[^>]*?>(<img typeof="foaf:Image"[^>]*?>)</noscript>'; rhImgFoaf.Global:=true; end; content:=rhImgFoaf.Replace(content,'$1'); end; function EncodeNonHTMLContent(const title:WideString):WideString; begin Result:= rhLFs.Replace( rh3.Replace( rh2.Replace( rh1.Replace( title ,'&amp;')//rh1 ,'&lt;')//rh2 ,'&gt;')//rh3 ,'<br />')//rhLFs ; end; function DisplayShortURL(const URL:string):string; var s:string; i,j:integer; begin s:=URL; i:=1; //ship https?:// while (i<=Length(s)) and (s[i]<>'/') do inc(i); inc(i); if (i<=Length(s)) and (s[i]='/') then inc(i); if Copy(s,i,4)='www.' then inc(i,4); j:=i; while (j<=Length(s)) and (s[j]<>'/') do inc(j); inc(j); while (j<=Length(s)) and (s[j]<>'/') and (s[j]<>'?') do inc(j); Result:=Copy(s,i,j-i); end; function FindPrefixAndCrop(var data:WideString;const pattern:WideString):boolean; var r:RegExp; m:MatchCollection; mm:Match; l:integer; begin r:=CoRegExp.Create; r.Global:=false; r.IgnoreCase:=false;//? r.Pattern:=pattern;//??!! m:=r.Execute(data) as MatchCollection; if m.Count=0 then Result:=false else begin mm:=m.Item[0] as Match; l:=mm.FirstIndex+mm.Length; data:=Copy(data,1+l,Length(data)-l); Result:=true; end; end; function FindMatch(const data:WideString;const pattern:WideString):WideString; var r:RegExp; m:MatchCollection; sm:SubMatches; begin r:=CoRegExp.Create; r.Global:=false; r.IgnoreCase:=false;//? r.Pattern:=pattern; m:=r.Execute(data) as MatchCollection; if m.Count=0 then Result:='' else begin sm:=(m.Item[0] as Match).SubMatches as SubMatches; if sm.Count=0 then Result:='' else Result:=VarToStr(sm.Item[0]); end; end; function FixUndeclNSPrefix(doc:DOMDocument60;var FeedData:WideString):boolean; var re:RegExp; s:string; begin re:=CoRegExp.Create; re.Pattern:='Reference to undeclared namespace prefix: ''([^'']+?)''.\r\n'; if re.Test(doc.parseError.reason) then begin s:=(((re.Execute(doc.parseError.reason) as MatchCollection).Item[0] as Match).SubMatches as SubMatches).Item[0]; re.Pattern:='<('+s+':\S+?)[^>]*?[\u0000-\uFFFF]*?</\1>'; re.Global:=true; FeedData:=re.Replace(FeedData,''); Result:=doc.loadXML(FeedData); end else Result:=false; end; function FixNBSP(doc:DOMDocument60;var FeedData:WideString):boolean; var re:RegExp; begin re:=CoRegExp.Create; re.Pattern:='&nbsp;'; re.Global:=true; //rw:=re.Replace(rw,'&amp;nbsp;'); FeedData:=re.Replace(FeedData,#$00A0); Result:=doc.loadXML(FeedData); end; procedure SanitizeYoutubeURL(var URL:string); const YoutubePrefix0='https://www.youtube.com/@'; YoutubePrefix1='https://www.youtube.com/channel/'; YoutubePrefix2='https://www.youtube.com/feeds/videos.xml?channel_id='; YoutubePrefix3='https://www.youtube.com/feeds/videos.xml?user='; var d:ServerXMLHTTP60; r:RegExp; m:MatchCollection; mm:Match; s:string; begin if StartsWith(URL,YoutubePrefix0) then begin d:=CoServerXMLHTTP60.Create; d.open('GET',URL,false,EmptyParam,EmptyParam); d.setRequestHeader('User-Agent','FeedEater/1.1'); d.setRequestHeader('Cookie','CONSENT=YES+EN.us+V9+BX'); d.send(EmptyParam); //assert d.status=200 r:=CoRegExp.Create; r.Pattern:='<meta property="og:url" content="https://www.youtube.com/channel/([^"]+?)">'; m:=r.Execute(d.responseText) as MatchCollection; if m.Count=0 then raise Exception.Create('YouTube: unable to get channel ID from channel name'); mm:=m.Item[0] as Match; URL:=YoutubePrefix2+(mm.SubMatches as SubMatches).Item[0]; end else if StartsWithX(URL,YoutubePrefix1,s) then URL:=YoutubePrefix2+s else begin r:=CoRegExp.Create; r.Pattern:='^https://www.youtube.com/([^/@]+)$'; m:=r.Execute(URL) as MatchCollection; if m.Count=1 then begin mm:=m.Item[0] as Match; URL:=YoutubePrefix3+(mm.SubMatches as SubMatches).Item[0]; end; end; end; procedure PerformReplace(data:IJSONDocument;var subject:WideString); var re,re1:RegExp; sub:IJSONDocument; base,p:WideString; i,j,k,l:integer; mc:MatchCollection; m:Match; sm:SubMatches; begin re:=CoRegExp.Create; re.Pattern:=data['x']; if not(VarIsNull(data['g'])) then re.Global:=boolean(data['g']); if not(VarIsNull(data['m'])) then re.Multiline:=boolean(data['m']); if not(VarIsNull(data['i'])) then re.IgnoreCase:=boolean(data['i']); sub:=JSON(data['p']); if sub=nil then subject:=re.Replace(subject,data['s']) else begin mc:=re.Execute(subject) as MatchCollection; if mc.Count<>0 then begin base:=subject; re1:=CoRegExp.Create; re1.Pattern:=sub['x']; if not(VarIsNull(sub['g'])) then re1.Global:=boolean(sub['g']); if not(VarIsNull(sub['m'])) then re1.Multiline:=boolean(sub['m']); if not(VarIsNull(sub['i'])) then re1.IgnoreCase:=boolean(sub['i']); j:=0; subject:=''; for i:=0 to mc.Count-1 do begin m:=mc.Item[i] as Match; subject:=subject+Copy(base,j+1,m.FirstIndex-j); //assert m.Value=Copy(base,m.FirstIndex+1,m.Length) if VarIsNull(sub['n']) then subject:=subject+re1.Replace(m.Value,sub['s']) else begin sm:=(m.SubMatches as SubMatches); j:=m.FirstIndex; //for k:=0 to sm.Count-1 do k:=sub['n']-1; begin //////??????? sm.Index? Pos(sm[k],m.Value)? l:=m.FirstIndex; p:=sm[k]; if p='' then j:=l+1//?? else begin while (l<=Length(base)) and (Copy(base,l,Length(p))<>p) do inc(l); subject:=subject+Copy(base,j+1,l-j-1); subject:=subject+re1.Replace(p,sub['s']); j:=l+Length(p); end; end; subject:=subject+Copy(base,j,m.FirstIndex+m.Length-j+1); end; j:=m.FirstIndex+m.Length; end; subject:=subject+Copy(base,j+1,Length(base)-j); end; end; end; end.
{ @abstract Implements font and character set routines. } unit NtFontUtils; {$I NtVer.inc} interface uses Vcl.Graphics; type { @abstract Record that stores information about charset. } TNtCharsetInfo = record CharSet: TFontCharset; CodePage: Integer; end; { @abstract Static class that contains font routines. } TNtFontUtils = class public { Get charset information. @param langId Language or locale id. @return Charset information. } class function GetCharSetInfo(langId: Integer): TNtCharsetInfo; { Get the active font charset. @return Font charset. } class function GetActiveFontCharset: TFontCharset; end; implementation uses Windows, NtBase, NtLocalization; type TLocaleFontSignature = packed record fsUsb: array[0..3] of DWord; fsCsbDefault: array[0..1] of DWord; fsCsbSupported: array[0..1] of DWord; end; class function TNtFontUtils.GetCharSetInfo(langId: Integer): TNtCharsetInfo; const CHARSETSETS: array[0..31] of TNtCharsetInfo = ( (charSet: ANSI_CHARSET; codePage: 1252), (charSet: EASTEUROPE_CHARSET; codePage: 1250), (charSet: RUSSIAN_CHARSET; codePage: 1251), (charSet: GREEK_CHARSET; codePage: 1253), (charSet: TURKISH_CHARSET; codePage: 1254), (charSet: HEBREW_CHARSET; codePage: 1255), (charSet: ARABIC_CHARSET; codePage: 1256), (charSet: BALTIC_CHARSET; codePage: 1257), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: THAI_CHARSET; codePage: 874), (charSet: SHIFTJIS_CHARSET; codePage: 932), (charSet: GB2312_CHARSET; codePage: 936), (charSet: HANGEUL_CHARSET; codePage: 949), (charSet: CHINESEBIG5_CHARSET; codePage: 950), (charSet: JOHAB_CHARSET; codePage: 1361), (charSet: VIETNAMESE_CHARSET; codePage: 1258), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0), (charSet: 0; codePage: 0) ); var f: DWord; i: Integer; lfs: TLocaleFontSignature; begin if GetLocaleInfo(langId, LOCALE_FONTSIGNATURE, PChar(@lfs), Sizeof(lfs)) <> 0 then begin f := 1; for i := Low(CHARSETSETS) to High(CHARSETSETS) do begin if (f and lfs.fsCsbDefault[0]) <> 0 then begin Result := CHARSETSETS[i]; Exit; end; f := f shl 1; end; end; Result := CHARSETSETS[0]; end; class function TNtFontUtils.GetActiveFontCharset: TFontCharset; begin Result := GetCharSetInfo(TNtLocale.ExtensionToLocale(LoadedResourceLocale)).charSet; end; end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * 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 TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* FXSRVR0.PAS 4.06 *} {*********************************************************} {**********************Description************************} { FxSrvr is an example project for the TApdFaxServer and TApdFaxServerManager components. The controls on the form are separated in different GroupBoxes so the components properties are kept together. The controls are described below: Status ListBox: Contains status information and notification tags. TApdFaxServerManger: Directory to monitor: The directory name where the TApdFaxServerManager will look for outbound fax jobs Paused: If checked, the TApdFaxServerManager will not provide a fax job when the TApdFaxServer queries for fax jobs TApdFaxServer: StationID: Contains the StationID property value FaxClass: determines which FaxClass to use Modem init string: contains any special init commands required by your modem Dial prefix: contains any prefix required for dialing from this modem Destination directory: the directory where received faxes will be saved Enhanced fonts: outbound faxe headers and text cover pages will use these fonts Monitor for incoming faxes: if checked, ApdFaxServer will automatically receive incoming faxes Print on receive: if checked, received faxes will be printed using the attached TApdFaxPrinter Query every XXX seconds: enter 0 to disable querying the TApdFaxServerManager for new outbound fax jobs. Enter non-0 number and the TApdFaxServerManager will be queried for new jobs on the given interval. Device selection: The label will show which device is being used to fax The Select Device button enabled you to select which device to use. Select the device by name to use TAPI, or by COMx to go direct to the port. Hint properties of all editable controls contains the component and property that the control relates to. To use, select the device to be used (with the 'Select device' button), enter the appropriate ApdFaxServer properties and 'Check' the Monitor for incoming faxes checkbox. You will get OnFaxServerStatus entries in the list box while waiting for faxes. When faxes are received, they will be saved in the directory entered in the Destination directory control. To schedule and send faxes, use the FaxClient example project to create fax jobs and submit them for queing. } {**********************************************************} unit FxSrvr0; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, AdFaxSrv, AdFax, AdTapi, OoMisc, AdPort, AdFaxPrn, AdFPStat, AdFStat, AdExcept, AdSelCom, AdTSel; type TfrmFxSrv0 = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; edtMonitorDir: TEdit; cbxPaused: TCheckBox; GroupBox2: TGroupBox; Label2: TLabel; edtStationID: TEdit; rgpFaxClass: TRadioGroup; Label3: TLabel; edtDialPrefix: TEdit; Label4: TLabel; edtModemInit: TEdit; Label5: TLabel; edtQueryInterval: TEdit; Label6: TLabel; Label7: TLabel; edtDestinationDir: TEdit; cbxEnhFonts: TCheckBox; btnHeaderFont: TButton; btnCoverFont: TButton; cbxMonitor: TCheckBox; lbxStatus: TListBox; Label8: TLabel; cbxPrintOnReceive: TCheckBox; btnPrintSetup: TButton; GroupBox3: TGroupBox; lblDeviceName: TLabel; btnSelectDevice: TButton; GroupBox4: TGroupBox; btnClose: TButton; ApdComPort1: TApdComPort; FontDialog1: TFontDialog; ApdFaxServer1: TApdFaxServer; ApdFaxStatus1: TApdFaxStatus; ApdFaxLog1: TApdFaxLog; ApdFaxServerManager1: TApdFaxServerManager; ApdFaxPrinter1: TApdFaxPrinter; ApdFaxPrinterStatus1: TApdFaxPrinterStatus; ApdTapiDevice1: TApdTapiDevice; procedure rgpFaxClassClick(Sender: TObject); procedure edtStationIDExit(Sender: TObject); procedure edtDialPrefixExit(Sender: TObject); procedure edtModemInitExit(Sender: TObject); procedure edtQueryIntervalExit(Sender: TObject); procedure edtDestinationDirExit(Sender: TObject); procedure btnHeaderFontClick(Sender: TObject); procedure btnCoverFontClick(Sender: TObject); procedure cbxEnhFontsClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ApdFaxServer1FaxServerAccept(CP: TObject; var Accept: Boolean); procedure ApdFaxServer1FaxServerFatalError(CP: TObject; FaxMode: TFaxServerMode; ErrorCode, HangupCode: Integer); procedure ApdFaxServer1FaxServerFinish(CP: TObject; FaxMode: TFaxServerMode; ErrorCode: Integer); procedure ApdFaxServer1FaxServerLog(CP: TObject; LogCode: TFaxLogCode; ServerCode: TFaxServerLogCode); procedure ApdFaxServer1FaxServerPortOpenClose(CP: TObject; Opening: Boolean); procedure ApdFaxServer1FaxServerStatus(CP: TObject; FaxMode: TFaxServerMode; First, Last: Boolean; Status: Word); procedure btnPrintSetupClick(Sender: TObject); procedure cbxPrintOnReceiveClick(Sender: TObject); procedure btnSelectDeviceClick(Sender: TObject); procedure cbxMonitorClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure cbxPausedClick(Sender: TObject); procedure edtMonitorDirExit(Sender: TObject); procedure ApdFaxServerManager1Queried(Mgr: TApdFaxServerManager; QueryFrom: TApdCustomFaxServer; const JobToSend: String); private { Private declarations } procedure Add(const S: String); public { Public declarations } end; var frmFxSrv0: TfrmFxSrv0; implementation {$R *.DFM} procedure TfrmFxSrv0.rgpFaxClassClick(Sender: TObject); begin ApdFaxServer1.FaxClass := TFaxClass(rgpFaxClass.ItemIndex+1); end; procedure TfrmFxSrv0.edtStationIDExit(Sender: TObject); begin ApdFaxServer1.StationID := edtStationID.Text; end; procedure TfrmFxSrv0.edtDialPrefixExit(Sender: TObject); begin ApdFaxServer1.DialPrefix := edtDialPrefix.Text; end; procedure TfrmFxSrv0.edtModemInitExit(Sender: TObject); begin ApdFaxServer1.ModemInit := edtModemInit.Text; end; procedure TfrmFxSrv0.edtQueryIntervalExit(Sender: TObject); begin ApdFaxServer1.SendQueryInterval := StrToIntDef(edtQueryInterval.Text, ApdFaxServer1.SendQueryInterval); edtQueryInterval.Text := IntToStr(ApdFaxServer1.SendQueryInterval); end; procedure TfrmFxSrv0.edtDestinationDirExit(Sender: TObject); begin ApdFaxServer1.DestinationDir := edtDestinationDir.Text; edtDestinationDir.Text := ApdFaxServer1.DestinationDir; end; procedure TfrmFxSrv0.btnHeaderFontClick(Sender: TObject); begin FontDialog1.Font := ApdFaxServer1.EnhHeaderFont; if FontDialog1.Execute then ApdFaxServer1.EnhHeaderFont := FontDialog1.Font; end; procedure TfrmFxSrv0.btnCoverFontClick(Sender: TObject); begin FontDialog1.Font := ApdFaxServer1.EnhFont; if FontDialog1.Execute then ApdFaxServer1.EnhFont := FontDialog1.Font; end; procedure TfrmFxSrv0.cbxEnhFontsClick(Sender: TObject); begin ApdFaxServer1.EnhTextEnabled := cbxEnhFonts.Checked; end; procedure TfrmFxSrv0.FormCreate(Sender: TObject); begin { set up initial values in controls } edtMonitorDir.Text := ApdFaxServerManager1.MonitorDir; cbxPaused.Checked := ApdFaxServerManager1.Paused; edtStationID.Text := ApdFaxServer1.StationID; if ApdFaxServer1.FaxClass = fcUnknown then ApdFaxServer1.FaxClass := fcDetect; rgpFaxClass.ItemIndex := Ord(ApdFaxServer1.FaxClass) - 1; edtModemInit.Text := ApdFaxServer1.ModemInit; edtDialPrefix.Text := ApdFaxServer1.DialPrefix; edtDestinationDir.Text := ApdFaxServer1.DestinationDir; cbxEnhFonts.Checked := ApdFaxServer1.EnhTextEnabled; cbxMonitor.Checked := ApdFaxServer1.Monitoring; cbxPrintOnReceive.Checked := ApdFaxServer1.PrintOnReceive; edtQueryInterval.Text := IntToStr(ApdFaxServer1.SendQueryInterval); if ApdComPort1.TapiMode = tmOn then begin if ApdTapiDevice1.SelectedDevice <> '' then lblDeviceName.Caption := 'Using TAPI device: ' + ApdTapiDevice1.SelectedDevice else lblDeviceName.Caption := 'Using TAPI device: <no device selected>'; end else lblDeviceName.Caption := 'Using modem on ' + ComName(ApdComPort1.ComNumber); end; procedure TfrmFxSrv0.Add(const S: String); begin if Assigned(lbxStatus) then begin lbxStatus.Items.Add(IntToStr(GetTickCount) + ': ' + S); if lbxStatus.Items.Count > 1 then lbxStatus.ItemIndex := lbxStatus.Items.Count - 1; end; end; procedure TfrmFxSrv0.ApdFaxServer1FaxServerAccept(CP: TObject; var Accept: Boolean); begin Add('Accepting fax from: ' + ApdFaxServer1.RemoteID); end; procedure TfrmFxSrv0.ApdFaxServer1FaxServerFatalError(CP: TObject; FaxMode: TFaxServerMode; ErrorCode, HangupCode: Integer); var S: String; begin if FaxMode = fsmSend then S := 'sending' else S := 'receiving'; Add('Fatal error occured while ' + S); Add(' ErrorCode = (' + IntToStr(ErrorCode) + ') ' + ErrorMsg(ErrorCode)); Add(' HangupCode= ' + IntToStr(HangupCode)); end; procedure TfrmFxSrv0.ApdFaxServer1FaxServerFinish(CP: TObject; FaxMode: TFaxServerMode; ErrorCode: Integer); var S: String; begin if FaxMode = fsmSend then S := 'sent' else S := 'received'; if ErrorCode = ecOK then S := S + ' successfully' else S := S + ' with an error code of (' + IntToStr(ErrorCode) + ') ' + ErrorMsg(ErrorCode); Add('Fax ' + S); if (FaxMode = fsmReceive) and (ErrorCode = ecOK) then Add('Fax saved to ' + ApdFaxServer1.FaxFile); end; procedure TfrmFxSrv0.ApdFaxServer1FaxServerLog(CP: TObject; LogCode: TFaxLogCode; ServerCode: TFaxServerLogCode); var S: String; begin if TLogFaxCode(LogCode) = lfaxNone then case ServerCode of fslPollingEnabled : S := 'Polling enabled every ' + IntToStr(ApdFaxServer1.SendQueryInterval) + ' seconds'; fslPollingDisabled : S := 'Polling disabled'; fslMonitoringEnabled : S := 'Monitoring for incoming faxes'; fslMonitoringDisabled : S := 'Monitoring disabled'; else S := ''; end else case TLogFaxCode(LogCode) of lfaxTransmitStart : S := 'Transmit start'; lfaxTransmitOk : S := 'Transmit OK'; lfaxTransmitFail : S := 'Transmit failed'; lfaxReceiveStart : S := 'Receive start'; lfaxReceiveOk : S := 'Receive OK'; lfaxReceiveSkip : S := 'Receive skipped'; lfaxReceiveFail : S := 'Receive failed'; else S := ''; end; Add('Fax log: ' + S); end; procedure TfrmFxSrv0.ApdFaxServer1FaxServerPortOpenClose(CP: TObject; Opening: Boolean); begin if Opening then Add('Port is opened') else Add('Port is closed'); end; procedure TfrmFxSrv0.ApdFaxServer1FaxServerStatus(CP: TObject; FaxMode: TFaxServerMode; First, Last: Boolean; Status: Word); var S: String; begin if FaxMode = fsmSend then S := 'Send' else S := 'Receive'; Add('Fax status (' + S + '): ' + ApdFaxServer1.StatusMsg(Status)); end; procedure TfrmFxSrv0.btnPrintSetupClick(Sender: TObject); begin ApdFaxPrinter1.PrintSetup; end; procedure TfrmFxSrv0.cbxPrintOnReceiveClick(Sender: TObject); begin ApdFaxServer1.PrintOnReceive := cbxPrintOnReceive.Checked; end; procedure TfrmFxSrv0.btnSelectDeviceClick(Sender: TObject); begin {$IFDEF Win32} with TDeviceSelectionForm.Create(Self) do begin try ShowTapiDevices := True; ShowPorts := True; EnumAllPorts; if ShowModal = mrOK then begin if Copy(DeviceName, 1, 13) = 'Direct to COM' then begin ApdComPort1.TapiMode := tmOff; ApdComPort1.ComNumber := ComNumber; end else begin ApdTapiDevice1.SelectedDevice := DeviceName; ApdComPort1.TapiMode := tmOn; end; end; finally Free; end; end; {$ELSE} with TComSelectForm.Create(Self) do begin try ShowModal; ApdComPort1.TapiMode := tmOff; ApdComPort1.ComNumber := SelectedComNum; finally Free; end; end; {$ENDIF} if ApdComPort1.TapiMode = tmOn then begin if ApdTapiDevice1.SelectedDevice <> '' then lblDeviceName.Caption := 'Using TAPI device: ' + ApdTapiDevice1.SelectedDevice else lblDeviceName.Caption := 'Using TAPI device: <no device selected>'; end else lblDeviceName.Caption := 'Using modem on ' + ComName(ApdComPort1.ComNumber); end; procedure TfrmFxSrv0.cbxMonitorClick(Sender: TObject); begin ApdFaxServer1.Monitoring := cbxMonitor.Checked; end; procedure TfrmFxSrv0.btnCloseClick(Sender: TObject); begin Close; end; procedure TfrmFxSrv0.cbxPausedClick(Sender: TObject); begin ApdFaxServerManager1.Paused := cbxPaused.Checked; end; procedure TfrmFxSrv0.edtMonitorDirExit(Sender: TObject); begin ApdFaxServerManager1.MonitorDir := edtMonitorDir.Text; end; procedure TfrmFxSrv0.ApdFaxServerManager1Queried(Mgr: TApdFaxServerManager; QueryFrom: TApdCustomFaxServer; const JobToSend: String); begin Add('Queried by : ' + QueryFrom.Name + ': ' + JobToSend); end; end.
unit uClassicMultiplier; {$I ..\Include\IntXLib.inc} interface uses uMultiplierBase, uDigitHelper; type /// <summary> /// Multiplies using "classic" algorithm. /// </summary> TClassicMultiplier = class sealed(TMultiplierBase) public /// <summary> /// Multiplies two big integers using pointers. /// </summary> /// <param name="digitsPtr1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="digitsPtr2">Second big integer digits.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsResPtr">Resulting big integer digits.</param> /// <returns>Resulting big integer length.</returns> function Multiply(digitsPtr1: PCardinal; length1: UInt32; digitsPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal) : UInt32; override; end; implementation function TClassicMultiplier.Multiply(digitsPtr1: PCardinal; length1: UInt32; digitsPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal): UInt32; var c: UInt64; lengthTemp, newLength: UInt32; ptrTemp, digitsPtr1End, digitsPtr2End, ptr1, ptrRes: PCardinal; begin // External cycle must be always smaller if (length1 < length2) then begin // First must be bigger - swap lengthTemp := length1; length1 := length2; length2 := lengthTemp; ptrTemp := digitsPtr1; digitsPtr1 := digitsPtr2; digitsPtr2 := ptrTemp; end; // Prepare end pointers digitsPtr1End := digitsPtr1 + length1; digitsPtr2End := digitsPtr2 + length2; // We must always clear first "length1" digits in result TDigitHelper.SetBlockDigits(digitsResPtr, length1, UInt32(0)); // Perform digits multiplication ptrRes := Nil; while digitsPtr2 < (digitsPtr2End) do begin // Check for zero (sometimes may help). There is no sense to make this check in internal cycle - // it would give performance gain only here if (digitsPtr2^ = 0) then begin Inc(digitsPtr2); Inc(digitsResPtr); continue; end; c := 0; ptr1 := digitsPtr1; ptrRes := digitsResPtr; while (ptr1) < (digitsPtr1End) do begin c := c + UInt64(digitsPtr2^) * ptr1^ + ptrRes^; (ptrRes)^ := UInt32(c); c := c shr 32; Inc(ptr1); Inc(ptrRes); end; (ptrRes)^ := UInt32(c); Inc(digitsPtr2); Inc(digitsResPtr); end; newLength := length1 + length2; if ((newLength > 0) and ((ptrRes = Nil) or (ptrRes^ = 0))) then begin Dec(newLength); end; result := newLength; end; end.
unit ListaItens; interface uses Classes, Produto, Dialogs; Type TListaItens = class private { private declarations } FListaItens : TList; protected { protected declarations } public constructor Create; procedure Adicionar(pItem: TProduto); procedure Remover(Index: Integer); function Count: Integer; function GetProduto(i:integer): TProduto; published { published declarations } end; implementation { TListaItens } constructor TListaItens.Create; begin inherited Create; FListaItens := TList.Create; end; procedure TListaItens.Adicionar(pItem: TProduto); begin FListaItens.Add(pItem); end; function TListaItens.Count: Integer; begin Result := FListaItens.Count; end; procedure TListaItens.Remover(Index: Integer); begin if Index < Count then FListaItens.Delete(Index) else ShowMessage('Item não encontrado!'); end; function TListaItens.GetProduto(i: integer): TProduto; begin GetProduto := TProduto(FListaItens.Items[i]); end; end.
//****************************************************************************** // Проект "ГорВодоКанал" (bs) // Файл типов // Перчак А.Л. // создан 18/01/2010 // последние изменения Перчак А.Л. 18/01/2010 //****************************************************************************** unit uCommon_Types; interface uses Classes, IBase, Forms, Types, RxMemDS; type TSelectMode = (SingleSelect, MultiSelect); type TActionMode = (View, Edit); Type TbsSimpleParams = class public Owner: TComponent; Db_Handle: TISC_DB_HANDLE; Formstyle: TFormStyle; WaitPakageOwner : TForm; SMode : TSelectMode; AMode : TActionMode; ID_SESSION: Int64; Type_Report:Integer; Sql_Master,Sql_Detail,Report_Name:String; FieldView,NotFieldView,FieldNameReport:Variant; LastIgnor:Integer; Date_beg,Date_end:TDateTime; ID_User : Int64; User_Name: string; ID_Locate : int64; ID_Locate_1 : int64; ID_Locate_2 : int64; DontShowGroups : boolean; DontShowFacs : boolean; ID_PRICE: Int64; is_admin: boolean; //признак админа is_debug : boolean; //признак редактирования отчета id_system : Byte; //запуск системы end; type TbsParamsToPakage = record ID_DOG_ROOT : int64; ID_DOG : int64; ID_STUD : int64; ID_RATE_ACCOUNT : int64; ID_DOC : int64; FIO : String; Num_Doc : String; Note : String; DATE_DOG : TDateTime; Summa : Currency; IsWithSumma : Boolean; DissDownAllContract : boolean; Is_collect : byte; IsUpload : Boolean; // признак переоформления договора Is_Admin : Boolean; //Признак админестратора end; type TbsSimpleParamsEx = class(TbsSimpleParams) public bsParamsToPakage : TbsParamsToPakage; ReturnMode : string; // Single, Multy // для рапортов TypeDoc : byte; // 1-отчисление, 2-восстановление TR_Handle: TISC_TR_HANDLE; end; type TbsAccessResult = record ID_User:integer; Name_user:string; User_Id_Card:integer; User_Fio:string; DB_Handle : TISC_DB_HANDLE; Password: string; is_admin : Boolean; id_system : Byte; //запуск какой системы end; type TbsAcademicYear = record Date_Beg: TDateTime; Date_End: TDateTime; end; type TCurrentConnect = record Db_Handle: TISC_DB_HANDLE; PLanguageIndex: byte; end; type TDissInfo = record flag : Integer; TR_Handle: TISC_TR_HANDLE; Date_Diss: TDateTime; end; type TbsExAcademicYear = array of TbsAcademicYear; type TFinanceSource = record isEmpty : boolean; ID_SMETA : int64; ID_RAZDEL : int64; ID_STAT : int64; ID_KEKV : int64; PERCENT : Currency; TEXT_SMETA :string; TEXT_RAZDEL :string; TEXT_STAT :string; TEXT_KEKV :string; CODE_SMETA :string; CODE_RAZDEL :string; CODE_STAT :string; CODE_KEKV :string; end; type TbsSourceStudInf = record ID_FAC : int64; ID_SPEC : int64; end; type TbsSourceStudInfParams = class(TbsSimpleParams) public bsSourceStudInf : TbsSourceStudInf; end; type TbsCalcIn = record Owner : TComponent; DB_Handle : TISC_DB_HANDLE; ID_STUD : int64; BEG_CHECK : TDateTime; END_CHECK : TDateTime; CNUPLSUM : Currency; end; type TbsCalcOut = record CNDATEOPL : TDateTime; bs_SNEED : Currency; bs_SNEEDL : Currency; ID_SESSION : int64; end; type TbsPayIn = record Owner : TComponent; DB_Handle : TISC_DB_HANDLE; ID_STUD : int64; BEG_CHECK : TDateTime; END_CHECK : TDateTime; DATE_PROV_CHECK : byte; IS_DOC_GEN : byte; IS_PROV_GEN : byte; IS_SMET_GEN : byte; NOFPROV : byte; DIGNORDOCID : int64; end; type TbsPayOut = record SUMMA_ALL : Currency; CNUPLSUM : Currency; CNSUMDOC : Currency; CNINSOST :Currency; ID_SESSION : int64; end; type TbsAnnulContractIn = record Owner : TComponent; DB_Handle : TISC_DB_HANDLE; ID_DOG_ROOT : int64; ID_DOG : int64; ID_STUD : int64; DATE_DISS : TDateTime; ID_TYPE_DISS : int64; ORDER_DATE : TDateTime; ORDER_NUM : String; COMMENT : String; IS_COLLECT : integer; // ID_DOG_DISS_IN : int64; end; type TbsParamsToAddContract = record // идентификаторы ID_DOG_STATUS : int64; // статус ID_DEPARTMENT : int64; // факультет (подразделение) ID_SPEC : int64; // специальность ID_GROUP : int64; // группа ID_FORM_STUD : int64; // форма обучения ID_KAT_STUD : int64; // категория обучения ID_NATIONAL : int64; // гражданство KURS : Integer; // курс DATE_BEG : TDateTime; // Дата начала обучения DATE_END : TDateTime; // Дата конца обучения ID_MAN : int64; // ? end; type TbsSimpleParamsAbiturient = class(TbsSimpleParams) public WorkMode : string; // 'simple', 'extra' ActionMode : string; // 'add', 'edit' bsParamsToAddContract : TbsParamsToAddContract; bsParamsToPakage :TbsParamsToPakage; end; Type TbsView = class public ViewRX : TRxMemoryData; end; type TbsShortCut = record //горячие клавиши View : TShortCut; //Просмотр Edit : TShortCut; //Редактирование Add : TShortCut; //Добавить Del : TShortCut; //Удлить Print : TShortCut; //Печатать Block : TShortCut; //Блокировать Close : TShortCut; //Закрыть Work : TShortCut; //Отработать Done : TShortCut; //Выполнить UnDone : TShortCut; //Расформировать Rejection : TShortCut; //Отклонить Sign : TShortCut; //Подписать Configure : TShortCut; //Сконфигурировать UnSign : TShortCut; //Снять подпись Change : TShortCut; //Изменить Choice : TShortCut; //Выбрать Search : TShortCut; //Искать StepUp : TShortCut; //Шаг вперед StepDown : TShortCut; //Шаг назад Clear : TShortCut; //Очистить Refresh : TShortCut; //Обновить end; implementation end.
unit Arabic; interface uses Classes, SysUtils, XmlObjModel, Dialogs; type TAraAlphaName = String[16]; TAraAlphaId = { 00-04 } (aaUnknown, aaAlif, aaBaa, aaTaa, aaSaa, { 05-09 } aaJeem, aaHaa, aaKhaa, aaDaal, aaDhaal, { 10-14 } aaRaa, aaZaa, aaSeen, aaSheen, aaSaud, { 15-19 } aaDhaud, aaTau, aaZau, aaAain, aaGhain, { 20-24 } aaFaa, aaQaaf, aaKaaf, aaLaam, aaMeem, { 25-29 } aaNoon, aaHa, aaWaw, aaYaa, aaHamza, { 30-31 } aaAlifMud, aaThaaMarbutah, aaLamAlif); const FirstArabicLetter : TAraAlphaId = aaAlif; LastArabicLetter : TAraAlphaId = aaYaa; AraAlphaNames : array [TAraAlphaId] of TAraAlphaName = { 00-04 } ('', 'alif', 'baa', 'taa', 'saa', { 05-09 } 'jeem', 'haa', 'khaa', 'daal', 'dhaal', { 10-14 } 'raa', 'zaa', 'seen', 'sheen', 'saud', { 15-19 } 'dhaud', 'tau', 'zau', 'aain', 'ghain', { 20-24 } 'faa', 'qaaf', 'kaaf', 'laam', 'meem', { 25-29 } 'noon', 'ha', 'waw', 'yaa', 'hamza', { 30-31 } 'alifmud', 'thaamarbutah', 'lamalif'); type TAraLetterContext = (lcIsolated, lcInitial, lcMedial, lcFinal); TAraCharMapItem = record AlphaId : TAraAlphaId; AlphaName : TAraAlphaName; ConnectToLeft : Boolean; ConnectToRight : Boolean; ContextChars : array[TAraLetterContext] of Byte; end; PAraCharMap = ^TAraCharMap; PAraKeyboardMap = ^TAraKeyboardMap; TAraCharMap = array[TAraAlphaId] of TAraCharMapItem; TAraKeyboardMap = array[Char] of TAraAlphaId; EArabicEncodingInvalidName = Exception; EArabicEncodingParseError = Exception; TArabicEncodings = class(TObject) protected FActiveCharMapName : String; // name of character map in use FActiveKeyboardMapName : String; // name keyboard map in use FActiveCharMap : PAraCharMap; // actual map in use FActiveKeyboardMap : PAraKeyboardMap; // actual map in use FCharMaps : TStringList; // key is encoding type, value is PAraCharMap FKeyboardMaps : TStringList; // key is map name, value is PAraKeyboardMap FFontEncodings : TStringList; // key is the font name, value is the encoding name (FCharMap) FEncodingFonts : TStringList; // key is the encoding name, value is a TStringList of font names FDefaultFonts : TStringList; // key is the encoding name, value is the name of the default font FActiveEncDefaultFont : String; // the default font of the active encoding procedure Clear; function GetActiveCharMapFonts : TStringList; function GetFontEncoding(AFontName : String) : String; procedure SetActiveCharMapName(AName : String); procedure SetActiveKeyboardMapName(AName : String); public constructor Create; virtual; destructor Destroy; override; procedure LoadFromAML(const ARootElem : TXmlElement); function ToArabic(const AText : String) : String; function GetLetterFontChar(const AAraAlphaNum : Byte; const AShape : TAraLetterContext) : Char; property ActiveCharMapName : String read FActiveCharMapName write SetActiveCharMapName; property ActiveKeyboardMapName : String read FActiveKeyboardMapName write SetActiveKeyboardMapName; property AvailableFonts : TStringList read GetActiveCharMapFonts; property FontEncoding[Index : String] : String read GetFontEncoding; property ActiveCharMap : PAraCharMap read FActiveCharMap; property ActiveKeyboardMap : PAraKeyboardMap read FActiveKeyboardMap; property CharMaps : TStringList read FCharMaps; property KeyboardMaps : TStringList read FKeyboardMaps; property FontEncodings : TStringList read FFontEncodings; property EncodingFonts : TStringList read FEncodingFonts; property DefaultFontName : String read FActiveEncDefaultFont; end; function AraAlphaNameToId(const AName : String) : TAraAlphaId; implementation uses StStrS; function AraAlphaNameToId(const AName : String) : TAraAlphaId; var L : TAraAlphaId; begin Result := aaUnknown; for L := Low(TAraAlphaId) to High(TAraAlphaId) do begin if CompareText(AraAlphaNames[L], AName) = 0 then begin Result := L; Exit; end; end; end; constructor TArabicEncodings.Create; begin inherited Create; FCharMaps := TStringList.Create; FCharMaps.Sorted := True; FCharMaps.Duplicates := dupError; FKeyboardMaps := TStringList.Create; FKeyboardMaps.Sorted := True; FKeyboardMaps.Duplicates := dupError; FFontEncodings := TStringList.Create; FDefaultFonts := TStringList.Create; FEncodingFonts := TStringList.Create; FEncodingFonts.Sorted := True; FEncodingFonts.Duplicates := dupError; end; destructor TArabicEncodings.Destroy; begin Clear; FCharMaps.Free; FKeyboardMaps.Free; FEncodingFonts.Free; FFontEncodings.Free; FDefaultFonts.Free; inherited Destroy; end; procedure TArabicEncodings.Clear; var I : Integer; begin FActiveCharMapName := ''; FActiveKeyboardMapName := ''; FActiveCharMap := Nil; FActiveKeyboardMap := Nil; if (FCharMaps <> Nil) and (FCharMaps.Count > 0) then begin for I := 0 to FCharMaps.Count-1 do Dispose(Pointer(FCharMaps.Objects[I])); FCharMaps.Clear; end; if (FKeyboardMaps <> Nil) and (FKeyboardMaps.Count > 0) then begin for I := 0 to FKeyboardMaps.Count-1 do Dispose(Pointer(FKeyboardMaps.Objects[I])); FKeyboardMaps.Clear; end; if (FEncodingFonts <> Nil) and (FEncodingFonts.Count > 0) then begin for I := 0 to FEncodingFonts.Count-1 do FEncodingFonts.Objects[I].Free; FEncodingFonts.Clear; end; FFontEncodings.Clear; FDefaultFonts.Clear; end; function TArabicEncodings.GetActiveCharMapFonts : TStringList; var I : Integer; begin Result := Nil; if FEncodingFonts.Find(FActiveCharMapName, I) then Result := TStringList(FEncodingFonts.Objects[I]); end; function TArabicEncodings.GetFontEncoding(AFontName : String) : String; begin Result := FFontEncodings.Values[AFontName]; end; procedure TArabicEncodings.SetActiveCharMapName(AName : String); var I : Integer; Fonts : TStringList; begin FActiveCharMapName := AName; if FCharMaps.Find(AName, I) then begin FActiveCharMap := PAraCharMap(FCharMaps.Objects[I]); Fonts := AvailableFonts; FActiveEncDefaultFont := FDefaultFonts.Values[AName]; if (FActiveEncDefaultFont = '') and (Fonts.Count > 0) then FActiveEncDefaultFont := Fonts[0]; end else begin FActiveCharMap := Nil; raise EArabicEncodingInvalidName.CreateFmt('Invalid char map name %s', [AName]); end; end; procedure TArabicEncodings.SetActiveKeyboardMapName(AName : String); var I : Integer; begin FActiveKeyboardMapName := AName; if FKeyboardMaps.Find(AName, I) then FActiveKeyboardMap := PAraKeyboardMap(FKeyboardMaps.Objects[I]) else begin FActiveKeyboardMap := Nil; raise EArabicEncodingInvalidName.CreateFmt('Invalid keyboard map name %s', [AName]); end; end; procedure TArabicEncodings.LoadFromAML(const ARootElem : TXmlElement); var T, C, ListIdx : Integer; TypeNode, ItemNode : TXmlNode; TypeElem, ItemElem : TXmlElement; AraCharMap : PAraCharMap; AraKeyMap : PAraKeyboardMap; ChStr : ShortString; Letter : TAraAlphaId; FontNamesList : TStringList; FontName, EncodingName : ShortString; DefFont : Boolean; begin Clear; if ARootElem.ChildNodes.Length <= 0 then Exit; for T := 0 to ARootElem.ChildNodes.Length-1 do begin TypeNode := ARootElem.ChildNodes.Item(T) as TXmlNode; if (TypeNode.NodeType = ELEMENT_NODE) then begin TypeElem := TypeNode as TXmlElement; if TypeElem.NodeName = 'charmap' then begin EncodingName := TypeElem.GetAttribute('encoding'); New(AraCharMap); FillChar(AraCharMap^, SizeOf(AraCharMap^), 0); try FCharMaps.AddObject(EncodingName, TObject(AraCharMap)); except ShowMessage('Duplicate encoding format found: ' + EncodingName); continue; end; for C := 0 to TypeElem.ChildNodes.Length-1 do begin ItemNode := TypeElem.ChildNodes.Item(C) as TXmlNode; if ItemNode.NodeType = ELEMENT_NODE then begin ItemElem := ItemNode as TXmlElement; if ItemElem.NodeName = 'font' then begin FontName := ItemElem.GetAttribute('name'); DefFont := ItemElem.GetAttribute('default') = 'yes'; if DefFont then FDefaultFonts.Values[EncodingName] := FontName; FFontEncodings.Values[FontName] := EncodingName; if not FEncodingFonts.Find(EncodingName, ListIdx) then begin FontNamesList := TStringList.Create; FontNamesList.Sorted := True; FontNamesList.Duplicates := dupIgnore; FEncodingFonts.AddObject(EncodingName, FontNamesList); end else FontNamesList := FEncodingFonts.Objects[ListIdx] as TStringList; FontNamesList.Add(FontName) end else if ItemElem.NodeName = 'context' then begin Letter := AraAlphaNameToId(ItemElem.GetAttribute('letter')); if Letter = aaUnknown then begin Clear; raise EArabicEncodingParseError.CreateFmt('Unknown arabic letter %s', [ItemElem.GetAttribute('letter')]); end; with AraCharMap[Letter] do begin AlphaId := Letter; AlphaName := AraAlphaNames[Letter]; ConnectToLeft := ItemElem.GetAttribute('connectleft') <> 'no'; ConnectToRight := ItemElem.GetAttribute('connectright') <> 'no'; try ContextChars[lcIsolated] := StrToInt(ItemElem.GetAttribute('isolated')); ContextChars[lcInitial] := StrToInt(ItemElem.GetAttribute('initial')); ContextChars[lcMedial] := StrToInt(ItemElem.GetAttribute('medial')); ContextChars[lcFinal] := StrToInt(ItemElem.GetAttribute('final')); except Clear; raise EArabicEncodingParseError.CreateFmt('Invalid context format (number expected) for %s', [AlphaName]); end; end; end; end; end; end else if TypeElem.NodeName = 'keymap' then begin New(AraKeyMap); FillChar(AraKeyMap^, SizeOf(AraKeyMap^), 0); try FKeyboardMaps.AddObject(TypeElem.GetAttribute('name'), TObject(AraKeyMap)); except ShowMessage('Duplicate keyboard map found: %s' + TypeElem.GetAttribute('encoding')); continue; end; for C := 0 to TypeElem.ChildNodes.Length-1 do begin ItemNode := TypeElem.ChildNodes.Item(C) as TXmlNode; if ItemNode.NodeType = ELEMENT_NODE then begin ItemElem := ItemNode as TXmlElement; if ItemElem.NodeName = 'key' then begin ChStr := ItemElem.GetAttribute('char'); if Length(ChStr) <> 1 then begin Clear; raise EArabicEncodingParseError.CreateFmt('Single character expected for key map %s', [ChStr]); end; AraKeyMap^[ChStr[1]] := AraAlphaNameToId(ItemElem.GetAttribute('letter')); if AraKeyMap^[ChStr[1]] = aaUnknown then begin Clear; raise EArabicEncodingParseError.CreateFmt('Key map %s letter not found', [ChStr]); end; end; end; end; end; end; end; if FCharMaps.Count > 0 then SetActiveCharMapName(FCharMaps[0]); if FKeyboardMaps.Count > 0 then SetActiveKeyboardMapName(FKeyboardMaps[0]); end; function TArabicEncodings.GetLetterFontChar(const AAraAlphaNum : Byte; const AShape : TAraLetterContext) : Char; begin if FActiveCharMap = Nil then Result := Char(0) else begin if AAraAlphaNum <= Byte(Ord(High(TAraAlphaId))) then Result := Char(FActiveCharMap^[TAraAlphaId(AAraAlphaNum)].ContextChars[AShape]) else Result := Char(AAraAlphaNum); end; end; function TArabicEncodings.ToArabic(const AText : String) : String; const WordDelims = ' '; var I, AW, ArabicWords, First, Last : Integer; ArabicWord, TranslatedWord : String; AraLetter, PrevLetter : TAraAlphaId; LetterForm : TAraLetterContext; begin Result := ''; if AText = '' then Exit; if FActiveKeyboardMap = Nil then begin Result := 'No active keyboard map '+FActiveKeyboardMapName; Exit; end; if FActiveCharMap = Nil then begin Result := 'No active character map '+FActiveCharMapName; Exit; end; ArabicWords := WordCountS(AText, WordDelims); PrevLetter := aaUnknown; for AW := 1 to ArabicWords do begin if AW > 1 then Result := Result + ' '; ArabicWord := ExtractWordS(AW, AText, WordDelims); First := Length(ArabicWord); Last := 1; TranslatedWord := ''; for I := First downto Last do begin AraLetter := FActiveKeyboardMap^[ArabicWord[I]]; if (First = Last) then LetterForm := lcIsolated else if I = First then LetterForm := lcInitial else begin if FActiveCharMap^[PrevLetter].ConnectToRight then begin if I = Last then LetterForm := lcFinal else LetterForm := lcMedial; end else begin if I = Last then LetterForm := lcIsolated else LetterForm := lcInitial; end; end; if ArabicWord[I] in ['0'..'9'] then TranslatedWord := ArabicWord[I] + TranslatedWord else TranslatedWord := Char(FActiveCharMap^[AraLetter].ContextChars[LetterForm]) + TranslatedWord; PrevLetter := AraLetter; end; Result := Result + TranslatedWord; end; end; end.
{..............................................................................} { Converts bitmap image into PCB regions, addaped from 'Scan Pixel Algorithm' } { Version 1.3 script by Paul D. Fincato (fincato@infinet.com) } { } { Copyright (c) 2006 by Altium Limited } {..............................................................................} {..............................................................................} Var FPixelSize : TCoord; FBaseX : TCoord; FBaseY : TCoord; CanChangeScale : Boolean; Board : IPCB_Board; {......................................................................................................................} {......................................................................................................................} Procedure SetState_ControlsEnable(Enabled : Boolean); Begin ConverterForm.XEdit.Enabled := Enabled; ConverterForm.YEdit.Enabled := Enabled; ConverterForm.ComboBoxLayers.Enabled := Enabled; ConverterForm.CreateComponentRadioButton.Enabled := Enabled; ConverterForm.CreateFreeRadioButton.Enabled := Enabled; DoUnionRadioButton.Enabled := Enabled; DontUnionRadioButton.Enabled := Enabled; ConverterForm.NegativeCheckBox.Enabled := Enabled; ConverterForm.FlipHorCheckBox.Enabled := Enabled; ConverterForm.FlipVertCheckBox.Enabled := Enabled; ConverterForm.PixelSizeEdit.Enabled := Enabled; ConverterForm.HeightEdit.Enabled := Enabled; ConverterForm.WidthEdit.Enabled := Enabled; ConverterForm.ConvertButton.Enabled := Enabled; ConverterForm.SelectButton.Enabled := Enabled; End; {......................................................................................................................} {......................................................................................................................} Procedure RunConverterScript; Begin If PCBServer = Nil Then Client.StartServer('PCB'); If PCBServer.GetCurrentPCBBoard = Nil Then CreateNewDocumentFromDocumentKind('PCB'); Board := PCBServer.GetCurrentPCBBoard; SetupComboBoxFromLayer(ConverterForm.ComboBoxLayers, Board); // Set the default layer to Top layer. ConverterForm.ComboBoxLayers.ItemIndex := 0; CanChangeScale := False; SetState_ControlsEnable(False); ConverterForm.ShowModal; End; {......................................................................................................................} {......................................................................................................................} Procedure SetState_EditControls(Edit : TEdit); Begin If Edit = Nil Then Begin SetState_EditControls(PixelSizeEdit); SetState_EditControls(WidthEdit); SetState_EditControls(HeightEdit); SetState_EditControls(XEdit); SetState_EditControls(YEdit); End; If Edit = PixelSizeEdit Then PixelSizeEdit.Text := CoordUnitToString(FPixelSize, eImperial) Else If Edit = WidthEdit Then Begin If Image1.Picture <> Nil Then WidthEdit.Text := CoordUnitToString(Abs(Image1.Picture.Width * FPixelSize), eImperial); End Else If Edit = HeightEdit Then Begin If Image1.Picture <> Nil Then HeightEdit.Text := CoordUnitToString(Abs(Image1.Picture.Height * FPixelSize), eImperial); End Else If Edit = XEdit Then XEdit.Text := CoordUnitToString(FBaseX, eImperial) Else If Edit = YEdit Then YEdit.Text := CoordUnitToString(FBaseY, eImperial); End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.XEditChange(Sender : TObject); Var DummyUnit : TUnit; Begin StringToCoordUnit(XEdit.Text, FBaseX, DummyUnit); End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.YEditChange(Sender : TObject); Var DummyUnit : TUnit; Begin StringToCoordUnit(YEdit.Text, FBaseY, DummyUnit); End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.WidthEditChange(Sender : TObject); Var DummyUnit : TUnit; NewWidth : TCoord; Begin If Not CanChangeScale Then Exit; CanChangeScale := False; StringToCoordUnit(WidthEdit.Text, NewWidth, DummyUnit); If Image1.Picture.Width <> Nil Then FPixelSize := NewWidth / Image1.Picture.Width; SetState_EditControls(HeightEdit); SetState_EditControls(PixelSizeEdit); CanChangeScale := True; End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.HeightEditChange(Sender : TObject); Var DummyUnit : TUnit; NewHeight : TCoord; Begin If Not CanChangeScale Then Exit; CanChangeScale := False; StringToCoordUnit(HeightEdit.Text, NewHeight, DummyUnit); If Image1.Picture.Height <> Nil Then FPixelSize := NewHeight / Image1.Picture.Height; SetState_EditControls(WidthEdit); SetState_EditControls(PixelSizeEdit); CanChangeScale := True; End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.PixelSizeEditChange(Sender : TObject); Var DummyUnit : TUnit; Begin If Not CanChangeScale Then Exit; CanChangeScale := False; StringToCoordUnit(PixelSizeEdit.Text, FPixelSize, DummyUnit); SetState_EditControls(WidthEdit); SetState_EditControls(HeightEdit); CanChangeScale := True; End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.LoadButtonClick(Sender: TObject); Begin If OpenPictureDialog1.Execute then Begin XPProgressBar1.Position := 0; XStatusBar1.SimpleText := ' Loading...'; XStatusBar1.Update; Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName); SetState_ControlsEnable(True); ConvertButton.Enabled := True; LoadButton.Enabled := True; XStatusBar1.SimpleText := ' Ready...'; XStatusBar1.Update; ImageSizeLabel.Caption := IntToStr(Image1.Picture.Width) + 'x' + IntToStr(Image1.Picture.Height); CanChangeScale := True; FPixelSize := MilsToCoord(1); FBaseX := MilsToCoord(1000); FBaseY := MilsToCoord(1000); SetState_EditControls(Nil); End; End; {......................................................................................................................} {......................................................................................................................} Procedure CreateFreeRegionsFromImage(AImage : TImage; Board : IPCB_Board; Layer : TLayer); Begin If Board = Nil Then Exit; PCBServer.PreProcess; If DoUnionRadioButton.Checked Then CreateRegionsFromPicture_Union(AImage, Layer, Board, XPProgressBar1, XStatusBar1) Else CreateRegionsFromPicture_NoUnion(AImage, Layer, Board, XPProgressBar1, XStatusBar1); PCBServer.PostProcess; End; {......................................................................................................................} {......................................................................................................................} Procedure CreateComponentFromImage(AImage : TImage; Board : IPCB_Board; Layer : TLayer); Var I : Integer; Component : IPCB_Component; Begin If Board = Nil Then Exit; PCBServer.PreProcess; Component := PCBServer.PCBObjectFactory(eComponentObject, eNoDimension, eCreate_Default); Component.X := FBaseX; Component.Y := FBaseY; Component.NameOn := False; If DoUnionRadioButton.Checked Then CreateRegionsFromPicture_Union(AImage, Layer, Component, XPProgressBar1, XStatusBar1) Else CreateRegionsFromPicture_NoUnion(AImage, Layer, Component, XPProgressBar1, XStatusBar1); Board.AddPCBObject(Component); PCBServer.PostProcess; End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.ConvertButtonClick(Sender: TObject); Var Layer : TLayer; OldCursor : TCursor; OldDoOnlineDRC : Boolean; Begin OldCursor := Screen.Cursor; Screen.Cursor := crHourGlass; OldDoOnlineDRC := PCBServer.SystemOptions.DoOnlineDRC; PCBServer.SystemOptions.DoOnlineDRC := False; XStatusBar1.SimpleText := 'Registering Regions...'; XStatusBar1.Update; SetState_Negative(NegativeCheckBox.Checked); SetState_DoFlipH(FlipHorCheckBox.Checked); SetState_DoFlipV(FlipVertCheckBox.Checked); Layer := String2Layer(ComboBoxLayers.Items[ComboBoxLayers.ItemIndex]); Board.LayerIsDisplayed[Layer] := True; If CreateComponentRadioButton.Checked Then CreateComponentFromImage(Image1, Board, Layer) Else CreateFreeRegionsFromImage(Image1, Board, Layer); Screen.Cursor := OldCursor; PCBServer.SystemOptions.DoOnlineDRC := OldDoOnlineDRC; XStatusBar1.SimpleText := ' Done...'; XStatusBar1.Update; XPProgressBar1.Position := 0; XPProgressBar1.Update; Board.GraphicallyInvalidate; Board.GraphicalView_ZoomOnRect(FBaseX, FBaseY, FBaseX + FPixelSize * Image1.Picture.Width, FBaseY + FPixelSize * Image1.Picture.Height); Close; End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.ExitButtonClick(Sender: TObject); Begin Close; End; {......................................................................................................................} {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.SelectButtonClick(Sender: TObject); Var X, Y : TCoord; begin Self.Hide; If Board.ChooseLocation(x, y, 'Choose Insertion Location') Then Begin FBaseX := X; FBaseY := Y; SetState_EditControls(XEdit); SetState_EditControls(YEdit); End; Self.Show; End; {......................................................................................................................}
unit umfmMakeSampleKey; interface uses Windows, Messages, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, uTPLb_MemoryStreamPool, uTPLb_Signatory, uTPLb_Codec, uTPLb_BaseNonVisualComponent, uTPLb_CryptographicLibrary, uTPLb_Hash; type TmfmMakeSampleKey = class(TForm) btnGenRSA: TButton; memoOutput: TMemo; btnGenAES256: TButton; btnAbort: TButton; lblCountPrimalityTests: TLabel; lblCountPrimalityTestsValue: TLabel; lblKeySize: TLabel; edtKeySize: TEdit; CryptographicLibrary1: TCryptographicLibrary; Codec1: TCodec; btnGenCompRSAKeys: TButton; Hash1: THash; Signatory1: TSignatory; procedure btnGenRSAClick(Sender: TObject); procedure btnGenAES256Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnAbortClick(Sender: TObject); procedure btnGenCompRSAKeysClick(Sender: TObject); function Codec1Progress(Sender: TObject; CountBytesProcessed: Int64): Boolean; private FPool: IMemoryStreamPool; FNumbersTested: integer; FwasAborted: boolean; FisGeneratingKeys: boolean; procedure GenRSA_Progress( Sender: TObject; BitsProcessed, TotalBits: int64; var doAbort: boolean); procedure GenRSA_TPrimalityTestNotice( CountPrimalityTests: integer); procedure Put( const Line: string); procedure PutFmt( const Line: string; const Args: array of const); procedure SetNumbersTested( Value: integer); public property PrimalityTestCount: integer read FNumbersTested write SetNumbersTested; end; var mfmMakeSampleKey: TmfmMakeSampleKey; implementation uses SysUtils, uTPLb_RSA_Primitives, uTPLb_HugeCardinalUtils, uTPLb_HugeCardinal, uTPLb_StreamUtils, uTPLb_AES, uTPLb_HashDsc, uTPLb_BlockCipher, uTPLb_StreamCipher, uTPLb_Random, uTPLb_Asymetric, uTPLb_Constants, StrUtils; {$R *.dfm} const MinBits = 256; MaxBits = 4096; procedure TmfmMakeSampleKey.FormCreate( Sender: TObject); begin FPool := NewPool; FwasAborted := False; FNumbersTested := 0; memoOutput.Clear; FisGeneratingKeys := False end; procedure TmfmMakeSampleKey.FormDestroy( Sender: TObject); begin FPool := nil end; procedure TmfmMakeSampleKey.btnGenRSAClick( Sender: TObject); var RequiredBitLengthOfN: integer; N, e, d, Totient: THugeCardinal; S: TDateTime; LocalNumbersTested: integer; LocalWasAborted: boolean; Secs: integer; Tmp: TStream; Code: integer; p, q, dp, dq, qinv: THugeCardinal; // For use with CRT. procedure ReportHugeCardinal( const Label1: string; Value: THugeCardinal); var B64: ansistring; begin Tmp.Size := 0; Value.StreamOut( LittleEndien, Tmp, (Value.BitLength + 7) div 8); B64 := Stream_to_Base64( Tmp); PutFmt( '%s (little-endien; base64) = "%s";', [Label1, B64]); Put( '') end; begin FwasAborted := False; LocalWasAborted := False; FNumbersTested := 0; LocalNumbersTested := 0; btnAbort.Enabled := True; Val( edtKeySize.Text, RequiredBitLengthOfN, Code); if (edtKeySize.Text='') or (Code <> 0) or (RequiredBitLengthOfN < MinBits) or (RequiredBitLengthOfN > MaxBits) then begin PutFmt( 'Key size ("%s") invalid or out of range.', [edtKeySize.Text]); PutFmt( 'Correct range is %d bits to %d bits.', [MinBits, MaxBits]); exit end; Tmp := FPool.NewMemoryStream( 0); try PutFmt( 'Now generating an RSA-%d key pair', [RequiredBitLengthOfN]); S := Now; Compute_RSA_Fundamentals_2Factors( RequiredBitLengthOfN, StandardExponent, N, e, d, Totient, p, q, dp, dq, qinv, GenRSA_Progress, GenRSA_TPrimalityTestNotice, 5, FPool, LocalNumbersTested, LocalWasAborted); if LocalWasAborted then Put( 'Generation aborted by user.') else begin Put( 'Generation completed.'); Secs := Round( (Now - S) * SecsPerDay); PutFmt( 'Generation took %ds.', [Secs]); PutFmt( '%d primality tests were conducted to reach this goal,', [LocalNumbersTested]); PutFmt( 'at a rate of %.1f tests per second.', [LocalNumbersTested / Secs]); Put( ''); PutFmt( 'n has %d bits.', [N.BitLength]); PutFmt( 'e has %d bits.', [e.BitLength]); PutFmt( 'd has %d bits.', [d.BitLength]); ReportHugeCardinal( 'n', n); ReportHugeCardinal( 'e', e); PutFmt( 'e (decimal) = %d', [StandardExponent]); Put( ''); ReportHugeCardinal( 'd', d); Put( '') end; finally Tmp.Free; btnAbort.Enabled := False; N.Free; e.Free; d.Free; Totient.Free; p.Free; q.Free; dp.Free; dq.Free; qinv.Free; end end; function RsaEncString( const PublicKey: ansistring; const SrcString : String): ansistring; var Codec : TCodec; wasAborted: boolean; KeyPair: TAsymetricKeyPair; KeyAsStream : TMemoryStream; Key: TSymetricKey; lib : TCryptographicLibrary; begin result := ''; Codec := TCodec.Create(Nil); lib := TCryptographicLibrary.Create(Nil); try //0. Reset Codec.Reset; Codec.CryptoLibrary := lib; Codec.ChainModeId := ECB_ProgId; //1. Set the cipher to RSA encryption. Codec.StreamCipherId := RSA_ProgId; //2. Load our pre-fabricated public key. KeyAsStream := TMemoryStream.Create; try Base64_to_stream(PublicKey, KeyAsStream); KeyAsStream.Position := 0; Codec.AsymetricKeySizeInBits := 512; Key := Codec.Asymetric_Engine.CreateFromStream(KeyAsStream, [partPublic]); //3. Now set the key. Codec.InitFromKey(Key); finally KeyAsStream.Free; end; Codec.EncryptString( SrcString, result); finally lib.Free; Codec.Free; end; end; function RsaDecString(const PrivateKey, SrcString : AnsiString): string; var Codec : TCodec; wasAborted: boolean; KeyPair: TAsymetricKeyPair; KeyAsStream : TMemoryStream; Key: TSymetricKey; lib : TCryptographicLibrary; begin result := ''; Codec := TCodec.Create(Nil); lib := TCryptographicLibrary.Create(Nil); try //0. Reset Codec.Reset; Codec.CryptoLibrary := lib; Codec.ChainModeId := ECB_ProgId; //1. Set the cipher to RSA encryption. Codec.StreamCipherId := RSA_ProgId; //2. Load our pre-fabricated private key. KeyAsStream := TMemoryStream.Create; try Base64_to_stream(PrivateKey, KeyAsStream); KeyAsStream.Position := 0; Codec.AsymetricKeySizeInBits := 512; Key := Codec.Asymetric_Engine.CreateFromStream(KeyAsStream, [partPrivate]); //3. Now set the key. Codec.InitFromKey(Key); finally KeyAsStream.Free; end; Codec.DecryptString( result, SrcString); finally lib.Free; Codec.Free; end; end; procedure TmfmMakeSampleKey.btnGenCompRSAKeysClick( Sender: TObject); var Mem: TStream; RequiredBitLengthOfN, Code: integer; PublicKey, PrivateKey: ansistring; Plaintext, Reconstruct: string; Ciphertext: ansistring; Ok: boolean; begin FisGeneratingKeys := True; Mem := TMemoryStream.Create; try Val( edtKeySize.Text, RequiredBitLengthOfN, Code); if (edtKeySize.Text='') or (Code <> 0) then begin Put( ''); exit; end; if RequiredBitLengthOfN < MinBits then RequiredBitLengthOfN := MinBits; if RequiredBitLengthOfN > MaxBits then RequiredBitLengthOfN := MaxBits; PutFmt( 'Generating two key pairs of size %d.', [RequiredBitLengthOfN]); Signatory1.Codec.AsymetricKeySizeInBits := RequiredBitLengthOfN; Signatory1.GenerateKeys; Signatory1.StoreKeysToStream( Mem, [partPublic]); PublicKey := Stream_to_Base64( Mem); PutFmt( 'Public key = "%s"', [PublicKey]); Mem.Size := 0; Signatory1.StoreKeysToStream( Mem, [partPrivate]); PrivateKey := Stream_to_Base64( Mem); PutFmt( 'Private key = "%s"', [PrivateKey]); finally FisGeneratingKeys := False; Mem.Free end; Put( 'Now performing a general inversion test (self-test)...'); try Plaintext := 'Your lip''s are smoother than vasoline.'; Ciphertext := RsaEncString( PublicKey, Plaintext); Reconstruct := RsaDecString( PrivateKey, Ciphertext); Ok := Reconstruct = Plaintext; except Ok := False end; PutFmt( 'Self-test result = %s', [IfThen( Ok, 'Pass', 'Fail')]) end; function TmfmMakeSampleKey.Codec1Progress( Sender: TObject; CountBytesProcessed: Int64): Boolean; begin result := True; if FisGeneratingKeys then GenRSA_TPrimalityTestNotice( Codec1.FGenerateAsymetricKeyPairProgress_CountPrimalityTests) end; procedure TmfmMakeSampleKey.GenRSA_Progress( Sender: TObject; BitsProcessed, TotalBits: int64; var doAbort: boolean); begin Application.ProcessMessages; doAbort := FwasAborted end; procedure TmfmMakeSampleKey.GenRSA_TPrimalityTestNotice( CountPrimalityTests: integer); begin Application.ProcessMessages; PrimalityTestCount := CountPrimalityTests end; procedure TmfmMakeSampleKey.Put(const Line: string); begin memoOutput.Lines.Add( Line) end; procedure TmfmMakeSampleKey.PutFmt( const Line: string; const Args: array of const); begin Put( Format( Line, Args)) end; procedure TmfmMakeSampleKey.SetNumbersTested( Value: integer); begin FNumbersTested := Value; lblCountPrimalityTestsValue.Caption := Format( '%d', [FNumbersTested]) end; procedure TmfmMakeSampleKey.btnAbortClick( Sender: TObject); begin FwasAborted := True; (Sender as TButton).Enabled := False end; procedure TmfmMakeSampleKey.btnGenAES256Click( Sender: TObject); var AES: IBlockCipher; KeyStream: TMemoryStream; Tmp: TStream; Key: TSymetricKey; KeySize: integer; begin KeyStream := nil; Tmp := nil; Key := nil; KeySize := 256; AES := TAES.Create( KeySize) as IBlockCipher; try KeyStream := FPool.NewMemoryStream( AES.KeySize div 8); RandomFillStream( KeyStream); KeyStream.Position := 0; Key := AES.GenerateKey( KeyStream); Tmp := FPool.NewMemoryStream( 0); Key.SaveToStream( Tmp); PutFmt( 'AES-%d key (base64) = "%s";', [KeySize, Stream_to_Base64( Tmp)]); finally Tmp.Free; Key.Free; KeyStream.Free end end; end.
unit UnitFMPreview; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UnitMain, Menus, ExtCtrls; type TFormFMPreview = class(TForm) Image1: TImage; PopupMenu1: TPopupMenu; Salvar1: TMenuItem; SaveDialog1: TSaveDialog; procedure FormShow(Sender: TObject); procedure Salvar1Click(Sender: TObject); procedure PopupMenu1Popup(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormFMPreview: TFormFMPreview; implementation uses UnitStrings, Jpeg; {$R *.dfm} procedure TFormFMPreview.PopupMenu1Popup(Sender: TObject); begin Salvar1.Enabled := Image1.Picture <> nil; end; procedure TFormFMPreview.FormShow(Sender: TObject); begin Salvar1.Caption := Traduzidos[387]; SaveDialog1.Title := Traduzidos[387]; end; procedure TFormFMPreview.Salvar1Click(Sender: TObject); var b: TBitmap; j: TJpegImage; begin if SaveDialog1.Execute = False then Exit; try b := TBitmap.Create; b.Assign(Image1.Picture); j := TJpegImage.Create; j.Assign(b); j.SaveToFile(SaveDialog1.FileName); finally j.Free; b.Free; end; end; end.
unit uUserBook; interface uses classes, controls, ADODB, DB, cxGrid, uAccessGrid, uFrameGrid, uBASE_BookForm, uFrameUserTable, cxPC, uAccess, uFrameUserData, uParams, uCommonUtils; type TUserBookItem = class; TUserBook = class; TUserBookItem = class(TCollectionItem) private FAccess: TAccessGrid; FObjectID: integer; FObjectName: string; FFrameGrid: TFrameGrid; FTabSheet: TcxTabSheet; FOwnerFrame: TFrameUserTable; FObjectAlias: string; FParentItem: TUserBookItem; FBaseTableName: string; FIsObject: boolean; FParentItemScrolledID: integer; FCanAddRecord: boolean; procedure SetObjectID(const Value: integer); function GetPrimaryKeyValue: variant; function GetIsChild: boolean; protected procedure ReadObjectName; virtual; procedure ReadBaseTableName; virtual; function PKName: string; virtual; public property ParentItem: TUserBookItem read FParentItem write FParentItem; property ParentItemScrolledID: integer read FParentItemScrolledID; property PrimaryKeyValue: variant read GetPrimaryKeyValue; property ObjectID: integer read FObjectID write SetObjectID; property ObjectName: string read FObjectName; property ObjectAlias: string read FObjectAlias; property IsChild: boolean read GetIsChild; property BaseTableName: string read FBaseTableName; property CanAddRecord: boolean read FCanAddRecord; property IsObject: boolean read FIsObject; property OwnerFrame: TFrameUserTable read FOwnerFrame; property TabSheet: TcxTabSheet read FTabSheet; property FrameGrid: TFrameGrid read FFrameGrid write FFrameGrid; property Access: TAccessGrid read FAccess; procedure RefreshData; virtual; constructor Create(Collection: TCollection); override; destructor Destroy; override; end; TUserBookSubListChildCollection = class(TCollection) private function GetItems(Index: integer): TUserBookItem; public property Items[Index: integer]: TUserBookItem read GetItems; default; function Add(OwnerFrame: TFrameUserTable): TUserBookItem; end; TUserBookSubListItem = class(TUserBookItem) private FChilds: TUserBookSubListChildCollection; FIgnoreDataRefresh: boolean; FMainUserBook: TUserBook; FIgnoreRefreshChilds: boolean; FIsObjectLink: boolean; FObjectLinkMainFrameGrid: TFrameGrid; FObjectLink: TUserBook; FAccessBook: TAccessBook; function GetIgnoreDataRefresh: boolean; public property Childs: TUserBookSubListChildCollection read FChilds; property IsObjectLink: boolean read FIsObjectLink write FIsObjectLink; property ObjectLink: TUserBook read FObjectLink write FObjectLink; property ObjectLinkMainFrameGrid: TFrameGrid read FObjectLinkMainFrameGrid write FObjectLinkMainFrameGrid; property IgnoreDataRefresh: boolean read GetIgnoreDataRefresh write FIgnoreDataRefresh; property MainUserBook: TUserBook read FMainUserBook; property AccessBook: TAccessBook read FAccessBook; property IgnoreRefreshChilds: boolean read FIgnoreRefreshChilds write FIgnoreRefreshChilds; procedure RefreshChilds; virtual; constructor Create(Collection: TCollection); override; destructor Destroy; override; end; TUserBookSubListCollection = class(TCollection) private function GetItems(Index: integer): TUserBookSubListItem; public property Items[Index: integer]: TUserBookSubListItem read GetItems; default; function Add(BookForm: TBASE_BookForm): TUserBookSubListItem; end; TUserBook = class private FItems: TUserBookSubListCollection; FObjectID: integer; FOwnerForm: TBASE_BookForm; FAccessManager: TAccessBook; FIsCardView: boolean; FPropsFormClass: TClass; FRealBook: TUserBookItem; FExtendedParams: TParamCollection; FItemsCreated: boolean; FEmptyOpen: boolean; function GetFieldValue(field: string): variant; function GetPrimaryKeyValue: variant; procedure SetPrimaryKeyValue(const Value: variant); function GetSelector: boolean; procedure SetSelector(const Value: boolean); procedure SetOwnerForm(const Value: TBASE_BookForm); protected SuspendedRestoreKey: variant; SuspendedIsNewRecord: boolean; public CopyFrom: TCopyFromObjectRecord; property Items: TUserBookSubListCollection read FItems; property ObjectID: integer read FObjectID write FObjectID; property OwnerForm: TBASE_BookForm read FOwnerForm write SetOwnerForm; property RealBook: TUserBookItem read FRealBook write FRealBook; property ExtendedParams: TParamCollection read FExtendedParams; property ItemsCreated: boolean read FItemsCreated; property IsCardView: boolean read FIsCardView write FIsCardView; property PrimaryKeyValue: variant read GetPrimaryKeyValue write SetPrimaryKeyValue; property FieldValue[field: string]: variant read GetFieldValue; property AccessManager: TAccessBook read FAccessManager write FAccessManager; property PropsFormClass: TClass read FPropsFormClass write FPropsFormClass; property Selector: boolean read GetSelector write SetSelector; property EmptyOpen: boolean read FEmptyOpen write FEmptyOpen; procedure CreateItems(RestoreKey: variant; IsNewRecord: boolean); virtual; procedure Show; function ShowModal(RestoreKey: variant; AIsCardView: boolean; AIsNewRecord: boolean; UEPrimaryKey: integer = -1): TModalResult; virtual; procedure ShowOnControl(ParentControl: TWinControl); procedure ContinueCreate; virtual; constructor Create; virtual; destructor Destroy; override; end; implementation uses Forms, SysUtils, variants, GlobalVars, uAttributes, uBASE_ObjectPropsForm, Dialogs; { TUserBookItem } constructor TUserBookItem.Create(Collection: TCollection); begin inherited; FAccess:=TAccessGrid.Create; FParentItemScrolledID:=-1; end; destructor TUserBookItem.Destroy; begin Access.Free; inherited; end; function TUserBookItem.GetIsChild: boolean; begin result:=Assigned(ParentItem); end; function TUserBookItem.GetPrimaryKeyValue: variant; begin if FrameGrid.dsCh.Active then result:=FrameGrid.CurRecPKValue else if FrameGrid.Query.Active then result:=FrameGrid.Query.Fields[0].Value else result:=null; end; function TUserBookItem.PKName: string; begin result:=FrameGrid.dsCh.Fields[0].FieldName; end; procedure TUserBookItem.ReadBaseTableName; var v: variant; begin v:=ExecSQLExpr(format('select dbo.f_КодГлавногоВладельца(%d)', [ObjectID])); if VarIsNull(v) then FBaseTableName:=ObjectName else FBaseTableName:=ExecSQLExpr(format('sp_GetObjectName @ObjectID = %d', [integer(v)])); end; procedure TUserBookItem.ReadObjectName; begin FObjectName:=ExecSQLExpr(format('sp_GetObjectName @ObjectID = %d', [ObjectID])); FObjectAlias:=ExecSQLExpr(format('sp_GetObjectName @ObjectID = %d, @NeedAlias = 1', [ObjectID])); FIsObject:=ExecSQLExpr(format('sp_GetIsObject @ObjectID = %d', [ObjectID])) = 1; self.FCanAddRecord:=ExecSQLExpr(format('select МожноДобавлятьЗаписи from sys_Объект where код_Объект=%d', [ObjectID])); // ыуда TabSheet.Caption:=ObjectAlias+' '; end; procedure TUserBookItem.RefreshData; var id: variant; sql: string; p1, p2: pointer; qry: TAdoQuery; IsObjLink: boolean; book: TUserBookSubListItem; begin IsObjLink:=(FrameGrid.OwnerBook is TUserBookSubListItem) and ( FrameGrid.OwnerBook as TUserBookSubListItem).IsObjectLink; if (not IsChild) and (not IsObjLink) then begin id:=FrameGrid.CurRecPKValue; FrameGrid.dsCh.Close; FrameGrid.dsCh.Open; FrameGrid.Query.Close; FrameGrid.LocateByIDCh(id); end else begin FrameGrid.dsCh.Close; if not VarIsNull(ParentItem.PrimaryKeyValue) then begin IsObjLink:=(FrameGrid.OwnerBook is TUserBookSubListItem) and (FrameGrid.OwnerBook as TUserBookSubListItem).IsObjectLink; if not IsObjLink then begin sql:=format('select * from [в_%s] where [%s] = %d', [ObjectName, FrameGrid.dsCh.Fields[2].FieldName, integer(ParentItem.PrimaryKeyValue)]); FrameGrid.Query.SQL.Text:=sql; if not FrameGrid.Prepared then FrameGrid.Prepared:=true; FrameGrid.dsCh.Close; FrameGrid.dsCh.Open; FrameGrid.Query.Close; end else begin book:=FrameGrid.OwnerBook as TUserBookSubListItem; if FrameGrid.ShowExtendedProps then sql:=format('select * from [в_%s] inner join [в_учетная единица_для_объединения] on вк_Свойства = [Учетная единица.код_Учетная единица] where [вк_ОбъектРодитель] = %d and [вк_ЗаписьОбъектРодитель] = %d', [ObjectName, ParentItem.ObjectID, integer(ParentItem.PrimaryKeyValue)]) else sql:=format('select * from [в_%s] where [вк_ОбъектРодитель] = %d and [' + 'вк_ЗаписьОбъектРодитель] = %d', [ObjectName, ParentItem.ObjectID, integer(ParentItem.PrimaryKeyValue)]); if Assigned(book.AccessBook) then if book.AccessBook.Suspended then book.AccessBook.ShowOnControl(nil, true); FrameGrid.Query.SQL.Text:=sql; if not FrameGrid.Prepared then FrameGrid.Prepared:=true; FrameGrid.dsCh.Close; FrameGrid.dsCh.Open; FrameGrid.Query.Close; end; self.FParentItemScrolledID:=ParentItem.PrimaryKeyValue; end; end; end; procedure TUserBookItem.SetObjectID(const Value: integer); begin FObjectID:=Value; ReadObjectName; ReadBaseTableName; Access.ObjectID:=Value; end; { TUserBookSubListChildCollection } function TUserBookSubListChildCollection.Add(OwnerFrame: TFrameUserTable): TUserBookItem; begin result:=TUserBookItem(inherited Add); result.FTabSheet:=OwnerFrame.AddChildSheet; result.FFrameGrid:=TFrameGrid.Create(result.TabSheet); result.FrameGrid.Parent:=result.TabSheet; result.FrameGrid.Align:=alClient; result.FrameGrid.OwnerBook:=result; result.TabSheet.Tag:=integer(result); end; function TUserBookSubListChildCollection.GetItems(Index: integer): TUserBookItem; begin result:= TUserBookItem(inherited Items[Index]); end; { TUserBookSubListCollection } function TUserBookSubListCollection.Add(BookForm: TBASE_BookForm): TUserBookSubListItem; begin result:=TUserBookSubListItem(inherited Add); result.FOwnerFrame:=BookForm.FrameUserData.AddSubListFrame; result.FTabSheet:=result.OwnerFrame.Parent as TcxTabSheet; result.FFrameGrid:=TFrameGrid.Create(result.OwnerFrame); result.FrameGrid.Parent:=result.OwnerFrame; result.FrameGrid.Align:=alClient; result.FrameGrid.OwnerBook:=result; result.TabSheet.Caption:=result.ObjectName; result.TabSheet.Tag:=integer(result); end; function TUserBookSubListCollection.GetItems(Index: integer): TUserBookSubListItem; begin result:= TUserBookSubListItem(inherited Items[Index]); end; { TUserBookSubListItem } constructor TUserBookSubListItem.Create(Collection: TCollection); begin inherited; FIgnoreRefreshChilds:=true; IsObjectLink:=false; FChilds:=TUserBookSubListChildCollection.Create(TUserBookItem); end; destructor TUserBookSubListItem.Destroy; begin FChilds.Free; inherited; end; function TUserBookSubListItem.GetIgnoreDataRefresh: boolean; begin if Assigned(ParentItem) then result:=(ParentItem as TUserBookSubListItem).IgnoreDataRefresh else result:=FIgnoreDataRefresh; end; procedure TUserBookSubListItem.RefreshChilds; var i: integer; begin if IgnoreRefreshChilds then exit; for i:=0 to Childs.Count-1 do Childs[i].RefreshData; end; { TUserBook } procedure TUserBook.ContinueCreate; begin CreateItems(SuspendedRestoreKey, SuspendedIsNewRecord); if not self.Items[0].FrameGrid.Prepared then self.Items[0].FrameGrid.Prepared:=true; Items[0].FrameGrid.BarManagerGridToolMainBar.Visible:=not IsCardView; OwnerForm.FrameUserData.pcData.HideTabs:=Items.Count=1; if SuspendedIsNewRecord then Items[0].FrameGrid.Query.Insert; end; constructor TUserBook.Create; begin inherited Create; PropsFormClass:=TBASE_BookForm; FRealBook:=nil; FItemsCreated:=false; FExtendedParams:=TParamCollection.Create(TParamItem); FEmptyOpen:=false; FOwnerForm:=nil; end; procedure TUserBook.CreateItems(RestoreKey: variant; IsNewRecord: boolean); var i, n, index, cindex: integer; Tables: TTables; a: TAccessBook; begin Tables:=TTables.Create; try Tables.CreateTables(ObjectID); Items.Add(OwnerForm); Items[0].OwnerFrame.ChildVisible:=false; Items[0].IgnoreDataRefresh:=true; Items[0].FMainUserBook:=self; Items[0].ObjectID:=ObjectID; Items[0].IsObjectLink:=false; if self.IsCardView then Items[0].FrameGrid.IsCardView:=true; Items[0].FrameGrid.CardViewPrimaryKey:=RestoreKey; Items[0].FrameGrid.ExtendedParams.CopyFrom(ExtendedParams); Items[0].FrameGrid.EmptyOpen:=EmptyOpen; Items[0].FrameGrid.PrepareData(true, VarIsNullMy(RestoreKey)); OwnerForm.Caption:=Items[0].ObjectAlias; OwnerForm.ObjectID:=ObjectID; // Items[0].FrameGrid.RestoryGrid(ObjectID); if not IsNewRecord then for i:=0 to Tables.Tables[0].Count-1 do begin if Tables.Tables[0].Attr[i].AttrType=atSubList then begin Items.Add(OwnerForm); index:=Items.Count-1; Items[index].FParentItem:=Items[0]; Items[index].ObjectID:=Tables.Tables[0].Attr[i].ID; Items[index].FrameGrid.PrepareData(); // Items[index].FrameGrid.RestoryGrid(Items[index].ObjectID); for n:=0 to Tables.Tables[0].Attr[i].Count-1 do begin if Tables.Tables[0].Attr[i].Attr[n].AttrType = atSubList then begin Items[index].Childs.Add(Items[index].OwnerFrame); cindex:=Items[index].Childs.Count-1; Items[index].Childs[cindex].FParentItem:=Items[index]; Items[index].Childs[cindex].ObjectID:=Tables.Tables[0].Attr[i].Attr[n].ID; Items[index].Childs[cindex].FrameGrid.PrepareData(); // Items[index].Childs[cindex].FrameGrid.RestoryGrid(Items[index].Childs[cindex].ObjectID); end end; if Items[index].Childs.Count=0 then Items[index].OwnerFrame.ChildVisible:=false; end; if Tables.Tables[0].Attr[i].AttrType=atObjectLink then begin Items.Add(OwnerForm); index:=Items.Count-1; Items[index].FParentItem:=Items[0]; Items[index].ObjectID:=Tables.Tables[0].Attr[i].L1; Items[index].OwnerFrame.ChildVisible:=false; Items[index].IsObjectLink:=true; // Items[index].t a:=TAccessBook.Create; a.ObjectID:=Tables.Tables[0].Attr[i].L1; a.PropsFormClass:=TBASE_ObjectPropsForm; a.WillBeChild:=true; a.Suspended:=true; a.Suspended_OwnerFrame:=Items[index].OwnerFrame; a.Suspended_IsObjectLink:=true; a.Suspended_ParentItem:=Items[0]; a.Suspended_Item:=Items[index]; Items[index].FAccessBook:=a; { a.ShowOnControl(Items[index].OwnerFrame); (a.UserBook as TUserBook).Items[0].IsObjectLink:=true; (a.UserBook as TUserBook).Items[0].FParentItem:=Items[0]; Items[index].ObjectLinkMainFrameGrid:=(a.UserBook as TUserBook).Items[0].FrameGrid;} Items[index].ObjectLink:=(a.UserBook as TUserBook); end; end; Items[0].IgnoreDataRefresh:=false; if not VarIsNullMy(RestoreKey) then PrimaryKeyValue:=RestoreKey; FItemsCreated:=true; finally Tables.Free; end; end; destructor TUserBook.Destroy; begin FExtendedParams.Free; AccessManager.UserBook:=nil; if Assigned(FOwnerForm) then FOwnerForm.Free; Items.Free; inherited; end; function TUserBook.GetFieldValue(field: string): variant; begin // result:=Items[0].FrameGrid.Query[field]; result:=Items[0].FrameGrid.CurRecItemValue(field); end; function TUserBook.GetPrimaryKeyValue: variant; begin result:=Items[0].PrimaryKeyValue; end; function TUserBook.GetSelector: boolean; begin result:=OwnerForm.Selector; end; procedure TUserBook.SetOwnerForm(const Value: TBASE_BookForm); begin FOwnerForm:=Value; if not Assigned(Value) then begin Free; end; end; procedure TUserBook.SetPrimaryKeyValue(const Value: variant); begin with Items[0].FrameGrid do ViewCh.DataController.FocusedRecordIndex:=dsCh.Locate(dsCh.KeyFields, Value, []); end; procedure TUserBook.SetSelector(const Value: boolean); begin self.OwnerForm.Selector:=Value; end; function TUserBook.ShowModal(RestoreKey: variant; AIsCardView: boolean; AIsNewRecord: boolean; UEPrimaryKey: integer = -1): TModalResult; var Instance: TComponent; ParentPropsID: integer; tb, te: TDateTime; begin tb:=now; Instance:=TComponent(PropsFormClass.NewInstance); Instance.Create(Application.MainForm); OwnerForm:=Instance as TBase_BookForm; OwnerForm.Book:=self; FItems:=TUserBookSubListCollection.Create(TUserBookSubListItem); IsCardView:=AIsCardView; if IsCardView then OwnerForm.ReadOnly:=true; SuspendedRestoreKey:=RestoreKey; SuspendedIsNewRecord:=AIsNewRecord; if not (OwnerForm is TBase_ObjectPropsForm) then begin CreateItems(RestoreKey, AIsNewRecord); if not self.Items[0].FrameGrid.Prepared then self.Items[0].FrameGrid.Prepared:=true; Items[0].FrameGrid.BarManagerGridToolMainBar.Visible:=not IsCardView; if AIsNewRecord then Items[0].FrameGrid.Query.Insert; end; if (OwnerForm is TBase_ObjectPropsForm) then begin (OwnerForm as TBase_ObjectPropsForm).UEPrimaryKey:=UEPrimaryKey; (OwnerForm as TBase_ObjectPropsForm).Caption:=ExecSQLExpr('select Псевдоним from sys_Объект where код_Объект = '+IntToStr(ObjectID)); (OwnerForm as TBase_ObjectPropsForm).CopyFrom.EnableCopy:=CopyFrom.EnableCopy; (OwnerForm as TBase_ObjectPropsForm).CopyFrom.ObjectID:=CopyFrom.ObjectID; (OwnerForm as TBase_ObjectPropsForm).CopyFrom.RecordID:=CopyFrom.RecordID; (OwnerForm as TBase_ObjectPropsForm).CopyFrom.UEID:=CopyFrom.UEID; end; OwnerForm.FrameUserData.pcData.HideTabs:=Items.Count=1; OwnerForm.Selector:=true; OwnerForm.Position:=poMainFormCenter; OwnerForm.BorderIcons:=[biSystemMenu, biMaximize]; OwnerForm.PropertyForm:=AIsCardView; if (OwnerForm is TBASE_ObjectPropsForm) and Assigned(RealBook) then if Assigned(RealBook.ParentItem) then begin ParentPropsID:=RealBook.ParentItem.FrameGrid.CurRecItemValue('вк_Свойства'); (OwnerForm as TBASE_ObjectPropsForm).ParentItemPropertyID:=ParentPropsID; end; te:=now; if ParamStr(1)='a' then ShowMessage(FormatDateTime('ss:zzz', te-tb)); result:=OwnerForm.ShowModal; end; procedure TUserBook.Show; begin if Assigned(OwnerForm) then OwnerForm.Show else begin OwnerForm:=TBase_BookForm.Create(nil); OwnerForm.Book:=self; FItems:=TUserBookSubListCollection.Create(TUserBookSubListItem); CreateItems(null, false); if not self.Items[0].FrameGrid.Prepared then self.Items[0].FrameGrid.Prepared:=true; OwnerForm.FrameUserData.pcData.HideTabs:=Items.Count=1; OwnerForm.Selector:=false; OwnerForm.FormStyle:=fsMDIChild; end end; //20-08-2009 //перенес строку OwnerForm.FrameUserData.Parent:=ParentControl; в самый конец procedure TUserBook.ShowOnControl(ParentControl: TWinControl); var book: TUserBookItem; begin OwnerForm:=TBase_BookForm.Create(nil); OwnerForm.Book:=self; FItems:=TUserBookSubListCollection.Create(TUserBookSubListItem); OwnerForm.FrameUserData.pcData.HideTabs:=Items.Count=1; CreateItems(null, false); if not self.Items[0].FrameGrid.Prepared then self.Items[0].FrameGrid.Prepared:=true; OwnerForm.Selector:=false; OwnerForm.FrameUserData.Parent:=ParentControl; self.Items[0].FrameGrid.RestoryGrid; end; //^^^20-08-2009 end.
{*************************** 界面控件与存储过程参数字段配置 为了减少对界面控件的值的获取和赋值 mx 2015-04-28 ****************************} unit uDBComConfig; interface uses Windows, Classes, Db, DBClient, SysUtils, Controls, cxGrid, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGraphics, uParamObject, cxButtons, ExtCtrls, Mask, cxTextEdit, cxMaskEdit, cxButtonEdit, cxDropDownEdit, ComCtrls, cxStyles, cxCustomData, cxFilter, uBaseInfoDef, uModelFunIntf, cxData, cxDataStorage, cxDBData, cxGridLevel, cxClasses, cxMemo, cxCalendar, Forms, uDefCom; const EXPPlusInt = '[1-9]\d*|0'; //正整数(允许0)的正则表达式 EXPInt = '(0|-?[1-9]\d*)'; //整数 EXPFloat = '(-?\d+)(\.\d+)'; //浮点数 type //记录一个界面控件和对应参数等信息 PDBComItem = ^TDBComItem; TDBComItem = record Component: TControl; //绑定的控件 SetDBName: string; //赋值时的字段 GetDBName: string; //取值时的字段 BasicType: TBasicType;//是否是基本信息字段 ShowFields: string;//显示基本信息哪个字段 TypeId: string;//基本信息赋值取值用此字段 EditType: TColField;//输入的类型 end; TDBComArray = array of PDBComItem; //管理和控制一个界面里面的控件对应的数据库参数 TFormDBComItem = class(TObject) private FOwnerFrom: TForm; FModelFun: IModelFun; FDBComList: TDBComArray; FOnSelectBasic: TSelectBasicinfoEvent; //弹出TC类选择框 procedure TCButtonClick(Sender: TObject; AButtonIndex: Integer);//基本信息类型,点击按钮弹出TC框 procedure EdtKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);//基本信息类型,回车弹出TC框 protected public constructor Create(AOwner: TForm); destructor Destroy; override; procedure GetDataFormParam(AParam: TParamObject); //从TParamObject中取值 procedure SetDataToParam(AParam: TParamObject); //给ParamObject赋值 function AddItem(AControl: TControl; ASetDBNane: string; AGetDBName: string; AEditType: TColField = cfString): PDBComItem; overload; //通过已有的控件添加一个数据项 function AddItem(AControl: TControl; ADBName: string): PDBComItem; overload; function AddItem(AControl: TControl; ASetDBName, AGetDBName, AFieldsList: string; ABasicType: TBasicType): PDBComItem; overload; procedure ClearItemData; procedure SetBasicItemValue(AControl: TControl; ASelectBasicData: TSelectBasicData);//给绑定了基本信息的控件赋值 function GetItemValue(AControl: TControl): Variant;//回去控件的值 procedure SetReadOnly(AControl: TControl; AReadOnly: Boolean = True);//设置是否只读 published property DBComList: TDBComArray read FDBComList; property OnSelectBasic: TSelectBasicinfoEvent read FOnSelectBasic write FOnSelectBasic; end; implementation uses uSysSvc, uOtherIntf, cxCheckBox, Graphics, Messages, uPubFun; { TFormDBComItem } function TFormDBComItem.AddItem(AControl: TControl; ASetDBNane, AGetDBName: string; AEditType: TColField = cfString): PDBComItem; var aLen: Integer; aItem: PDBComItem; aEdt: TcxButtonEdit; begin aItem := New(PDBComItem); aItem.Component := AControl; aItem.SetDBName := ASetDBNane; aItem.GetDBName := AGetDBName; aItem.BasicType := btNo; aItem.EditType := AEditType; if AControl is TcxButtonEdit then begin aEdt := TcxButtonEdit(AControl); aEdt.OnKeyDown := EdtKeyDown; aEdt.Properties.MaskKind := emkRegExprEx; case AEditType of cfInt: aEdt.Properties.EditMask := EXPInt; cfPlusInt: aEdt.Properties.EditMask := EXPPlusInt; cfFloat: aEdt.Properties.EditMask := EXPFloat; else end; end else if AControl is TcxDateEdit then begin TcxDateEdit(AControl).OnKeyDown := EdtKeyDown; end; aLen := Length(FDBComList) + 1; SetLength(FDBComList, aLen); FDBComList[aLen - 1] := aItem; Result := aItem; end; function TFormDBComItem.AddItem(AControl: TControl; ADBName: string): PDBComItem; begin Result := AddItem(AControl, ADBName, ADBName); end; function TFormDBComItem.AddItem(AControl: TControl; ASetDBName, AGetDBName, AFieldsList: string; ABasicType: TBasicType): PDBComItem; var aDBComItem: PDBComItem; begin aDBComItem := AddItem(AControl, ASetDBName, AGetDBName); aDBComItem.BasicType := ABasicType; aDBComItem.ShowFields := AFieldsList; Result := aDBComItem; if AControl is TcxButtonEdit then begin TcxButtonEdit(AControl).Properties.OnButtonClick := TCButtonClick; end else begin raise(SysService as IExManagement).CreateSysEx('控件[' + AControl.ClassName + ']不是TcxButtonEdit类型控件,不支持基本信息弹出框!'); end; end; procedure TFormDBComItem.EdtKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin if Sender is TcxButtonEdit then TCButtonClick(Sender, 0); FOwnerFrom.Perform(WM_NEXTDLGCTL, 0, 0); //焦点跳转到下一个控件 // FOwnerFrom.SelectNext(ActiveControl, True, True); // TWinControl(FOwnerFrom).SelectNext(TcxButtonEdit(Sender), True, False); end; end; procedure TFormDBComItem.ClearItemData; var i: Integer; aItem: PDBComItem; begin inherited; for i := 0 to Length(Self.DBComList) - 1 do begin aItem := Self.DBComList[i]; if aItem.Component is TcxButtonEdit then begin TcxButtonEdit(aItem.Component).Text := ''; if not IsSaveToLocal(aItem.BasicType) then begin TcxButtonEdit(aItem.Component).Properties.Buttons.Clear; end; end else if aItem.Component is TcxComboBox then begin if TcxComboBox(aItem.Component).Properties.Items.Count > 0 then TcxComboBox(aItem.Component).ItemIndex := 0 else TcxComboBox(aItem.Component).ItemIndex := -1; end else if aItem.Component is TcxCheckBox then begin TcxCheckBox(aItem.Component).Checked := False; end else if aItem.Component is TcxMemo then begin TcxMemo(aItem.Component).Text := ''; end else if aItem.Component is TcxDateEdit then begin TcxDateEdit(aItem.Component).Text := FormatdateTime('YYYY-MM-DD', Now); end else begin raise(SysService as IExManagement).CreateSysEx('绑定未知类型的控件[' + aItem.Component.ClassName + '],请设置清空数据方式!'); end; end; end; constructor TFormDBComItem.Create(AOwner: TForm); begin SetLength(FDBComList, 0); FOwnerFrom := AOwner; FModelFun := SysService as IModelFun; end; destructor TFormDBComItem.Destroy; var i: Integer; begin for i := 0 to Length(FDBComList) - 1 do begin Dispose(FDBComList[i]); end; SetLength(FDBComList, 0); inherited; end; procedure TFormDBComItem.GetDataFormParam(AParam: TParamObject); var i: Integer; aItem: PDBComItem; aValue: string; begin inherited; for i := 0 to Length(Self.DBComList) - 1 do begin aItem := Self.DBComList[i]; if aItem.Component is TcxButtonEdit then begin aValue := AParam.AsString(aItem.GetDBName); if IsSaveToLocal(aItem.BasicType) and (not StringEmpty(aValue)) then begin aItem.TypeId := aValue; aValue := FModelFun.GetLocalValue(aItem.BasicType, aItem.ShowFields, aValue); end; TcxButtonEdit(aItem.Component).Text := aValue; end else if aItem.Component is TcxComboBox then begin TcxComboBox(aItem.Component).ItemIndex := AParam.AsInteger(aItem.GetDBName); end else if aItem.Component is TcxCheckBox then begin TcxCheckBox(aItem.Component).Checked := AParam.AsInteger(aItem.GetDBName) = 1; end else if aItem.Component is TcxMemo then begin TcxMemo(aItem.Component).Text := AParam.AsString(aItem.GetDBName); end else if aItem.Component is TcxDateEdit then begin TcxDateEdit(aItem.Component).Text := AParam.AsString(aItem.GetDBName); end else begin raise(SysService as IExManagement).CreateSysEx('绑定未知类型的控件[' + aItem.Component.ClassName + '],请设置赋值方式!'); end; end; end; function TFormDBComItem.GetItemValue(AControl: TControl): Variant; var i: Integer; aItem: PDBComItem; aValue: string; aFindCon: Boolean; begin inherited; Result := ''; aFindCon := False; for i := 0 to Length(Self.DBComList) - 1 do begin aItem := Self.DBComList[i]; if aItem.Component = AControl then begin aFindCon := True; if aItem.Component is TcxButtonEdit then begin aValue := Trim(TcxButtonEdit(aItem.Component).Text); if IsSaveToLocal(aItem.BasicType) then begin aValue := aItem.TypeId; end; Result := aValue; end else if aItem.Component is TcxComboBox then begin Result := TcxComboBox(aItem.Component).ItemIndex; end else if aItem.Component is TcxCheckBox then begin if TcxCheckBox(aItem.Component).Checked then Result := 1 else Result := 0; end else if aItem.Component is TcxMemo then begin Result := Trim(TcxButtonEdit(aItem.Component).Text) end else if aItem.Component is TcxDateEdit then begin Result := Trim(TcxDateEdit(aItem.Component).Text); end else begin raise(SysService as IExManagement).CreateSysEx('绑定未知类型的控件[' + aItem.Component.ClassName + '],请设置取值方式!'); end; Break; end; end; if not aFindCon then begin FModelFun.ShowMsgBox('没有发现绑定的控件!','提示') end; end; procedure TFormDBComItem.SetBasicItemValue(AControl: TControl; ASelectBasicData: TSelectBasicData); var i, aReturnCount: Integer; aItem: PDBComItem; begin for i := 0 to Length(FDBComList) - 1 do begin aItem := FDBComList[i]; if aItem.Component = AControl then begin TcxButtonEdit(aItem.Component).Text := ASelectBasicData.FullName; aItem.TypeId := ASelectBasicData.TypeId; Break; end; end; end; procedure TFormDBComItem.SetDataToParam(AParam: TParamObject); var i: Integer; aItem: PDBComItem; aValue: string; begin inherited; for i := 0 to Length(Self.DBComList) - 1 do begin aItem := Self.DBComList[i]; AParam.Add('@' + aItem.SetDBName, GetItemValue(aItem.Component)); end; end; procedure TFormDBComItem.TCButtonClick(Sender: TObject; AButtonIndex: Integer); var i, aReturnCount: Integer; aBasicType: TBasicType; aSelectParam: TSelectBasicParam; aSelectOptions: TSelectBasicOptions; aReturnArray: TSelectBasicDatas; aItem: PDBComItem; begin for i := 0 to Length(FDBComList) - 1 do begin aItem := FDBComList[i]; if aItem.Component is TcxButtonEdit then begin if IsSaveToLocal(aItem.BasicType) then begin if aItem.Component = Sender then begin if TcxButtonEdit(aItem.Component).Properties.ReadOnly then Exit; OnSelectBasic(aItem.Component, aItem.BasicType, aSelectParam, aSelectOptions, aReturnArray, aReturnCount); if aReturnCount >= 1 then begin SetBasicItemValue(aItem.Component, aReturnArray[0]); end; Break; end; end; end; end; end; procedure TFormDBComItem.SetReadOnly(AControl: TControl; AReadOnly: Boolean); var i: Integer; aItem: PDBComItem; aValue: string; begin inherited; for i := 0 to Length(Self.DBComList) - 1 do begin aItem := DBComList[i]; if Assigned(AControl) then begin if AControl <> aItem.Component then Continue; end; if aItem.Component is TcxButtonEdit then begin TcxButtonEdit(aItem.Component).Properties.ReadOnly := AReadOnly; end else if aItem.Component is TcxComboBox then begin TcxComboBox(aItem.Component).Properties.ReadOnly := AReadOnly; end else if aItem.Component is TcxCheckBox then begin TcxCheckBox(aItem.Component).Properties.ReadOnly := AReadOnly; end else if aItem.Component is TcxMemo then begin TcxButtonEdit(aItem.Component).Properties.ReadOnly := AReadOnly; end else if aItem.Component is TcxDateEdit then begin TcxDateEdit(aItem.Component).Properties.ReadOnly := AReadOnly; end else begin raise(SysService as IExManagement).CreateSysEx('绑定未知类型的控件[' + aItem.Component.ClassName + ']!'); end; end; end; initialization finalization end.
{ Autor: Vinícius Lopes de Melo Data: 17/06/2014 Link: https://github.com/viniciuslopesmelo/Aplicacao-Delphi } unit untFrmPrincipal; interface uses untDMPrincipal, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TFormPrincipal = class(TForm) pnlProjeto: TPanel; btnGravarDados: TButton; edtQtdeRegistros: TLabeledEdit; btnEmitirRelatorioDados: TButton; btnExcluirTodosDados: TButton; lblCaminhoBancoDados: TLabel; lblAguarde: TLabel; btnInformacoes: TButton; procedure FormShow(Sender: TObject); procedure btnGravarDadosClick(Sender: TObject); procedure btnEmitirRelatorioDadosClick(Sender: TObject); procedure btnExcluirTodosDadosClick(Sender: TObject); procedure btnInformacoesClick(Sender: TObject); protected bProibidoExecutar: Boolean; end; var FormPrincipal: TFormPrincipal; implementation {$R *.dfm} { TFormProjeto } procedure TFormPrincipal.FormShow(Sender: TObject); begin lblAguarde.Caption := ''; if (FileExists('C:\BANCODADOS.fdb')) then begin lblCaminhoBancoDados.Caption := 'Caminho da Base de Dados: C:\BANCODADOS.fdb'; bProibidoExecutar := False; DMPrincipal.atualizarConexaoAplicativo; end else begin DMPrincipal.imprimirMensagem('O arquivo de base de dados não existe em "C:\BANCODADOS.fdb".', 'Aviso'); lblCaminhoBancoDados.Caption := 'O arquivo de base de dados não existe em "C:\BANCODADOS.fdb".'; bProibidoExecutar := True; end; end; procedure TFormPrincipal.btnEmitirRelatorioDadosClick(Sender: TObject); begin if (not bProibidoExecutar) then begin if (not DMPrincipal.pesquisarVendas) then DMPrincipal.imprimirMensagem('Não há registros para serem emitidos.', 'Informação') else begin lblAguarde.Caption := 'Aguarde... Emitindo relatório de dados.'; Self.Refresh; Sleep(2000); DMPrincipal.emitirRelatorio; lblAguarde.Caption := ''; end; end else begin DMPrincipal.imprimirMensagem('O arquivo de base de dados não existe em "C:\BANCODADOS.fdb".', 'Aviso'); lblCaminhoBancoDados.Caption := 'O arquivo de base de dados não existe em "C:\BANCODADOS.fdb".'; bProibidoExecutar := True; end; end; procedure TFormPrincipal.btnExcluirTodosDadosClick(Sender: TObject); var cursorSalvo : TCursor; iQtdeRegistrosExcluidos : Integer; begin if (not bProibidoExecutar) then begin if (not DMPrincipal.pesquisarPrimeiraVenda) then DMPrincipal.imprimirMensagem('Não há registros para excluir.', 'Informação') else if (DMPrincipal.imprimirMensagem('Deseja excluir todos os Registros?', 'Pergunta')) then begin cursorSalvo := Screen.Cursor; Screen.Cursor := crHourGlass; try lblAguarde.Caption := 'Aguarde... Excluindo dados.'; Self.Enabled := False; Self.Refresh; iQtdeRegistrosExcluidos := DMPrincipal.excluirTodosRegistros; if (iQtdeRegistrosExcluidos > 0) then DMPrincipal.imprimirMensagem('Exclusão realizada com sucesso.' + sLineBreak + IntToStr(iQtdeRegistrosExcluidos) + ' registros foram excluídos.', 'Informação'); Self.Enabled := True; Self.Refresh; if (edtQtdeRegistros.CanFocus) then edtQtdeRegistros.SetFocus; finally Screen.Cursor := cursorSalvo; Self.Enabled := True; Self.Refresh; lblAguarde.Caption := ''; end; end; end else begin DMPrincipal.imprimirMensagem('O arquivo de base de dados não existe em "C:\BANCODADOS.fdb".', 'Aviso'); lblCaminhoBancoDados.Caption := 'O arquivo de base de dados não existe em "C:\BANCODADOS.fdb".'; bProibidoExecutar := True; end; end; procedure TFormPrincipal.btnGravarDadosClick(Sender: TObject); var cursorSalvo : TCursor; iQtdeRegistros : Integer; begin if (not bProibidoExecutar) then begin cursorSalvo := Screen.Cursor; Screen.Cursor := crHourGlass; try iQtdeRegistros := StrToIntDef(edtQtdeRegistros.Text, 0); if (iQtdeRegistros = 0) then begin DMPrincipal.imprimirMensagem('A Qtde de Registros dever ser maior que 0.', 'Aviso'); if (edtQtdeRegistros.CanFocus) then edtQtdeRegistros.SetFocus; end else if (iQtdeRegistros > 100000) then begin if (DMPrincipal.imprimirMensagem('Gravar mais de 100.000 registros de uma só vez ' + sLineBreak + 'poderá causar lentidão na aplicação.' + sLineBreak + sLineBreak + 'Gostaria de continuar mesmo assim?', 'Pergunta')) then begin lblAguarde.Caption := 'Aguarde... Gravando dados.'; Self.Enabled := False; Self.Refresh; if (DMPrincipal.gravarRegistros(iQtdeRegistros)) then DMPrincipal.imprimirMensagem('Gravação realizada com sucesso.', 'Informação'); Self.Enabled := True; Self.Refresh; if (edtQtdeRegistros.CanFocus) then edtQtdeRegistros.SetFocus; end; end else begin lblAguarde.Caption := 'Aguarde... Gravando dados.'; Self.Enabled := False; Self.Refresh; if (DMPrincipal.gravarRegistros(iQtdeRegistros)) then DMPrincipal.imprimirMensagem('Gravação realizada com sucesso.', 'Informação'); Self.Enabled := True; Self.Refresh; if (edtQtdeRegistros.CanFocus) then edtQtdeRegistros.SetFocus; end; finally Screen.Cursor := cursorSalvo; Self.Enabled := True; Self.Refresh; lblAguarde.Caption := ''; end; end else begin DMPrincipal.imprimirMensagem('O arquivo de base de dados não existe em "C:\BANCODADOS.fdb".', 'Aviso'); lblCaminhoBancoDados.Caption := 'O arquivo de base de dados não existe em "C:\BANCODADOS.fdb".'; bProibidoExecutar := True; end; end; procedure TFormPrincipal.btnInformacoesClick(Sender: TObject); begin DMPrincipal.imprimirMensagem('Link do projeto: https://github.com/viniciuslopesmelo/Aplicacao-Delphi', 'Informação'); end; end.
unit AST.Delphi.Parser; interface uses AST.Pascal.Parser, AST.Lexer, AST.Classes, AST.Parser.Messages, AST.Delphi.Operators, AST.Delphi.Errors, AST.Lexer.Delphi, AST.Delphi.DataTypes, AST.Delphi.Classes, AST.Parser.Utils, AST.Parser.Contexts, AST.Delphi.Contexts, AST.Parser.Options, AST.Parser.ProcessStatuses, AST.Intf, AST.Pascal.ConstCalculator, AST.Delphi.Options, AST.Delphi.Project, AST.Delphi.Intf, System.Generics.Collections; // System.Generics.Defaults, // System.Internal.GenericsHlpr // system // GETMEM.INC // system.Classes // Winapi.ActiveX // system.Rtti // System.JSON // system.Types // system.TypInfo // system.UITypes // sysutils // sysinit // Windows // AnsiStrings // Character type {anonymous types cache} TDeclCache = class private fRanges: TList<TIDRangeType>; fSets: TList<TIDSet>; //Arrays: TList<TIDSet>; public constructor Create; destructor Destroy; override; procedure Add(Decl: TIDRangeType); overload; procedure Add(Decl: TIDSet); overload; function FindRange(BaseType: TIDType; LoBound, HiBound: TIDExpression): TIDRangeType; function FindSet(BaseType: TIDType): TIDSet; end; TASTDelphiUnit = class(TPascalUnit, IASTDelphiUnit) type TVarModifyPlace = (vmpAssignment, vmpPassArgument); var fRCPathCount: UInt32; // кол-во проходов increfcount/decrefcount для деклараций fInitProcExplicit: Boolean; // определена ли явно секция init fFinalProcExplicit: Boolean; // определена ли явно секция final fInitProc: TIDProcedure; fFinalProc: TIDProcedure; fSystemExplicitUse: Boolean; fCondStack: TSimpleStack<Boolean>; fPackage: IASTDelphiProject; fDefines: TDefines; fOptions: TDelphiOptions; fIncludeFilesStack: TSimpleStack<string>; fUnitSContext: TSContext; fCCalc: TExpressionCalculator; fErrors: TASTDelphiErrors; fSysDecls: PDelphiSystemDeclarations; fCache: TDeclCache; fForwardPtrTypes: TList<TIDPointer>; property Sys: PDelphiSystemDeclarations read fSysDecls; procedure CheckLeftOperand(const Status: TRPNStatus); class procedure CheckAndCallFuncImplicit(const EContext: TEContext); overload; static; class function CheckAndCallFuncImplicit(const SContext: TSContext; Expr: TIDExpression; out WasCall: Boolean): TIDExpression; overload; static; class function CheckAndCallFuncImplicit(const EContext: TEContext; Expr: TIDExpression): TIDExpression; overload; static; function CreateAnonymousConstant(Scope: TScope; var EContext: TEContext; const ID: TIdentifier; IdentifierType: TIdentifierType): TIDExpression; procedure InitEContext(out EContext: TEContext; const SContext: TSContext; EPosition: TExpessionPosition); overload; inline; procedure AddType(const Decl: TIDType); class function CheckExplicit(const SContext: TSContext; const Source, Destination: TIDType; out ExplicitOp: TIDDeclaration): Boolean; overload; static; class function MatchExplicit(const SContext: TSContext; const Source: TIDExpression; Destination: TIDType; out Explicit: TIDDeclaration): TIDExpression; overload; static; //class function MatchArrayImplicitToRecord(const SContext: TSContext; Source: TIDExpression; Destination: TIDStructure): TIDExpression; static; function Lexer_MatchSemicolonAndNext(Scope: TScope; ActualToken: TTokenID): TTokenID; //======================================================================================================== function ProcSpec_Inline(Scope: TScope; var Flags: TProcFlags): TTokenID; function ProcSpec_Export(Scope: TScope; var Flags: TProcFlags): TTokenID; function ProcSpec_Forward(Scope: TScope; var Flags: TProcFlags): TTokenID; function ProcSpec_External(Scope: TScope; out ImportLib, ImportName: TIDDeclaration; var Flags: TProcFlags): TTokenID; function ProcSpec_Overload(Scope: TScope; var Flags: TProcFlags): TTokenID; function ProcSpec_Virtual(Scope: TScope; Struct: TIDStructure; var Flags: TProcFlags): TTokenID; function ProcSpec_Dynamic(Scope: TScope; Struct: TIDStructure; var Flags: TProcFlags): TTokenID; function ProcSpec_Abstract(Scope: TScope; Struct: TIDStructure; var Flags: TProcFlags): TTokenID; function ProcSpec_Override(Scope: TScope; Struct: TIDStructure; var Flags: TProcFlags): TTokenID; function ProcSpec_Final(Scope: TScope; Struct: TIDStructure; var Flags: TProcFlags): TTokenID; function ProcSpec_Reintroduce(Scope: TScope; var Flags: TProcFlags): TTokenID; function ProcSpec_Static(Scope: TScope; var Flags: TProcFlags; var ProcType: TProcType): TTokenID; function ProcSpec_FastCall(Scope: TScope; var CallConvention: TCallConvention): TTokenID; function ProcSpec_StdCall(Scope: TScope; var CallConvention: TCallConvention): TTokenID; function ProcSpec_CDecl(Scope: TScope; var CallConvention: TCallConvention): TTokenID; function SpecializeGenericProc(CallExpr: TIDCallExpression; const CallArgs: TIDExpressions): TASTDelphiProc; function SpecializeGenericType(GenericType: TIDType; const ID: TIdentifier; const SpecializeArgs: TIDExpressions): TIDType; function InstantiateGenericType(AScope: TScope; AGenericType: TIDType; const SpecializeArgs: TIDExpressions): TIDType; function GetWeakRefType(Scope: TScope; SourceDataType: TIDType): TIDWeekRef; function CreateAnonymousConstTuple(Scope: TScope; ElementDataType: TIDType): TIDExpression; function GetCurrentParsedFileName(OnlyFileName: Boolean): string; class function CreateRangeType(Scope: TScope; LoBound, HiBound: Integer): TIDRangeType; static; class procedure AddSelfParameter(Params: TScope; Struct: TIDStructure; ClassMethod: Boolean); static; inline; function AddResultParameter(Params: TScope; DataType: TIDType): TIDVariable; procedure CheckCorrectEndCondStatemet(var Token: TTokenID); public property Package: IASTDelphiProject read fPackage; property Options: TDelphiOptions read fOptions; property ERRORS: TASTDelphiErrors read fErrors; class function GetTMPVar(const SContext: TSContext; DataType: TIDType): TIDVariable; overload; static; class function GetTMPVar(const EContext: TEContext; DataType: TIDType): TIDVariable; overload; static; class function GetTMPRef(const SContext: TSContext; DataType: TIDType): TIDVariable; static; class function GetTMPVarExpr(const SContext: TSContext; DataType: TIDType; const TextPos: TTextPosition): TIDExpression; overload; inline; static; class function GetTMPVarExpr(const EContext: TEContext; DataType: TIDType; const TextPos: TTextPosition): TIDExpression; overload; inline; static; class function GetTMPRefExpr(const SContext: TSContext; DataType: TIDType): TIDExpression; overload; inline; static; class function GetTMPRefExpr(const SContext: TSContext; DataType: TIDType; const TextPos: TTextPosition): TIDExpression; overload; inline; static; class function GetStaticTMPVar(DataType: TIDType; VarFlags: TVariableFlags = []): TIDVariable; static; protected function GetSource: string; override; function GetErrors: TASTDelphiErrors; function GetSystemDeclarations: PDelphiSystemDeclarations; virtual; procedure CheckLabelExpression(const Expr: TIDExpression); overload; procedure CheckLabelExpression(const Decl: TIDDeclaration); overload; function Process_operators(var EContext: TEContext; OpID: TOperatorID): TIDExpression; function Process_CALL(var EContext: TEContext): TIDExpression; function Process_CALL_direct(const SContext: TSContext; PExpr: TIDCallExpression; CallArguments: TIDExpressions): TIDExpression; function process_CALL_constructor(const SContext: TSContext; CallExpression: TIDCallExpression; const CallArguments: TIDExpressions): TIDExpression; procedure Process_operator_Assign(var EContext: TEContext); function Process_operator_neg(var EContext: TEContext): TIDExpression; function Process_operator_not(var EContext: TEContext): TIDExpression; function Process_operator_Addr(var EContext: TEContext): TIDExpression; function Process_operator_Deref(var EContext: TEContext): TIDExpression; function Process_operator_In(var EContext: TEContext; const Left, Right: TIDExpression): TIDExpression; function Process_operator_Is(var EContext: TEContext): TIDExpression; function Process_operator_As(var EContext: TEContext): TIDExpression; function Process_operator_Period(var EContext: TEContext): TIDExpression; function Process_operator_dot(var EContext: TEContext): TIDExpression; function MatchImplicitOrNil(const SContext: TSContext; Source: TIDExpression; Dest: TIDType): TIDExpression; function MatchArrayImplicit(const SContext: TSContext; Source: TIDExpression; DstArray: TIDArray): TIDExpression; function MatchRecordImplicit(const SContext: TSContext; Source: TIDExpression; DstRecord: TIDRecord): TIDExpression; function MatchBinarOperator(const SContext: TSContext; Op: TOperatorID; var Left, Right: TIDExpression): TIDDeclaration; function MatchBinarOperatorWithImplicit(const SContext: TSContext; Op: TOperatorID; var Left, Right: TIDexpression): TIDDeclaration; function FindBinaryOperator(const SContext: TSContext; OpID: TOperatorID; var Left, Right: TIDExpression): TIDDeclaration; class function MatchUnarOperator(Op: TOperatorID; Right: TIDType): TIDType; overload; static; inline; class function MatchUnarOperator(const SContext: TSContext; Op: TOperatorID; Source: TIDExpression): TIDExpression; overload; static; function DoMatchBinarOperator(const SContext: TSContext; OpID: TOperatorID; var Left, Right: TIDExpression): TIDDeclaration; procedure MatchProc(const SContext: TSContext; CallExpr: TIDExpression; const ProcParams: TIDParamArray; var CallArgs: TIDExpressions); function FindImplicitFormBinarOperators(const Operators: TBinaryOperatorsArray; const Left, Right: TIDType; out LLeftImplicitCast: TIDDeclaration; out LRightrImplicitCast: TIDDeclaration; out BetterFactor: Integer): TIDDeclaration; function MatchBinarOperatorWithTuple(const SContext: TSContext; Op: TOperatorID; var CArray: TIDExpression; const SecondArg: TIDExpression): TIDDeclaration; procedure Progress(StatusClass: TASTProcessStatusClass); override; public function MatchImplicit3(const SContext: TSContext; Source: TIDExpression; Dest: TIDType; AAbortIfError: Boolean = True): TIDExpression; class function MatchOperatorIn(const SContext: TSContext; const Left, Right: TIDExpression): TIDDeclaration; static; class function CheckConstDynArrayImplicit(const SContext: TSContext; Source: TIDExpression; Destination: TIDType): TIDType; static; class function MatchDynArrayImplicit(Source: TIDExpression; Destination: TIDType): TIDType; static; function MatchOverloadProc(const SContext: TSContext; Item: TIDExpression; const CallArgs: TIDExpressions; CallArgsCount: Integer): TIDProcedure; class function MatchImplicitClassOf(Source: TIDExpression; Destination: TIDClassOf): TIDDeclaration; static; class function MatchProcedureTypes(Src: TIDProcType; Dst: TIDProcType): TIDType; static; procedure MatchPropSetter(Prop: TIDProperty; Setter: TIDExpression; const PropParams: TIDParamArray); procedure MatchPropGetter(Prop: TIDProperty; Getter: TIDProcedure; const PropParams: TIDParamArray); procedure SetProcGenericArgs(CallExpr: TIDCallExpression; Args: TIDExpressions); class function MatchImplicit(Source, Destination: TIDType): TIDDeclaration; static; inline; procedure CheckVarParamConformity(Param: TIDVariable; Arg: TIDExpression); function IsConstValueInRange(Value: TIDExpression; RangeExpr: TIDRangeConstant): Boolean; function IsConstRangesIntersect(const Left, Right: TIDRangeConstant): Boolean; function IsConstEqual(const Left, Right: TIDExpression): Boolean; procedure CheckIntfSectionMissing(Scope: TScope); inline; procedure CheckImplicitTypes(Src, Dst: TIDType; Position: TTextPosition); inline; procedure CheckEmptyExpression(Expression: TIDExpression); inline; procedure CheckArrayExpression(Expression: TIDExpression); inline; procedure CheckIncompletedProcs(ProcSpace: PProcSpace); virtual; procedure CheckIncompletedIntfProcs(ClassType: TIDClass); procedure StaticCheckBounds(ConstValue: TIDConstant; Decl: TIDDeclaration; DimNumber: Integer); procedure CheckIncompleteFwdTypes; procedure CheckEndOfFile(Token: TTokenID); procedure CheckProcedureType(DeclType: TIDType); inline; procedure CheckStingType(DataType: TIDType); inline; class procedure CheckDestructorSignature(const DProc: TIDProcedure); static; class procedure CheckStaticRecordConstructorSign(const CProc: TIDProcedure); static; procedure CheckConstValueOverflow(Src: TIDExpression; DstDataType: TIDType); class procedure CheckStringExpression(Expression: TIDExpression); static; inline; procedure CheckConstExpression(Expression: TIDExpression); inline; procedure CheckIntExpression(Expression: TIDExpression); inline; procedure CheckOrdinalExpression(Expression: TIDExpression); inline; procedure CheckOrdinalType(DataType: TIDType); inline; class procedure CheckNumericExpression(Expression: TIDExpression); static; inline; procedure CheckBooleanExpression(Expression: TIDExpression); inline; procedure CheckVarExpression(Expression: TIDExpression; VarModifyPlace: TVarModifyPlace); class procedure CheckPointerType(Expression: TIDExpression); static; inline; class procedure CheckReferenceType(Expression: TIDExpression); static; inline; class procedure CheckRecordType(Expression: TIDExpression); static; inline; class procedure CheckStructType(Expression: TIDExpression); overload; static; inline; class procedure CheckStructType(Decl: TIDType); overload; static; inline; class procedure CheckExprHasMembers(Expression: TIDExpression); static; procedure CheckType(Expression: TIDExpression); inline; procedure CheckClassType(Expression: TIDExpression); inline; procedure CheckExceptionType(Decl: TIDDeclaration); procedure CheckClassExpression(Expression: TIDExpression); inline; class procedure CheckSetType(Expression: TIDExpression); static; inline; procedure CheckClassOrIntfType(Expression: TIDExpression); overload; procedure CheckClassOrClassOfOrIntfType(Expression: TIDExpression); overload; procedure CheckClassOrIntfType(DataType: TIDType; const TextPosition: TTextPosition); overload; class procedure CheckInterfaceType(Expression: TIDExpression); static; inline; class procedure CheckIncompleteType(Fields: TScope); static; class procedure CheckAccessMember(SContext: PSContext; Decl: TIDDeclaration; const ID: TIdentifier); class procedure CheckIntConstInRange(const Expr: TIDExpression; HiBount, LowBound: Int64); static; procedure InsertToScope(Scope: TScope; Item: TIDDeclaration); overload; inline; procedure InsertToScope(Scope: TScope; const ID: string; Declaration: TIDDeclaration); overload; inline; ////////////////////////////////////////////////////////////////////////////////////////////////////// /// Lexer helper functions procedure Lexer_ReadToken(Scope: TScope; const Token: TTokenID); inline; procedure Lexer_ReadSemicolon(Scope: TScope); inline; procedure Lexer_MatchIdentifier(const ActualToken: TTokenID); inline; procedure Lexer_MatchToken(const ActualToken, ExpectedToken: TTokenID); inline; procedure Lexer_MatchCurToken(const ExpectedToken: TTokenID); inline; procedure Lexer_MatchSemicolon(const ActualToken: TTokenID); inline; procedure Lexer_ReadCurrIdentifier(var Identifier: TIdentifier); inline; procedure Lexer_ReadTokenAsID(var Identifier: TIdentifier); procedure Lexer_ReadNextIdentifier(Scope: TScope; var Identifier: TIdentifier); inline; procedure Lexer_ReadNextIFDEFLiteral(Scope: TScope; var Identifier: TIdentifier); inline; procedure Lexer_MatchParamNameIdentifier(ActualToken: TTokenID); inline; function Lexer_CurTokenID: TTokenID; inline; function Lexer_AmbiguousId: TTokenID; inline; function Lexer_ReadSemicolonAndToken(Scope: TScope): TTokenID; inline; function Lexer_NextToken(Scope: TScope): TTokenID; overload; inline; function Lexer_Position: TTextPosition; inline; function Lexer_PrevPosition: TTextPosition; inline; function Lexer_IdentifireType: TIdentifierType; inline; function Lexer_TokenLexem(const TokenID: TTokenID): string; inline; function Lexer_Line: Integer; inline; function Lexer_SkipBlock(StopToken: TTokenID): TTokenID; function Lexer_SkipTo(Scope: TScope; StopToken: TTokenID): TTokenID; function Lexer_NotEof: boolean; inline; function Lexer_IsCurrentIdentifier: boolean; inline; function Lexer_IsCurrentToken(TokenID: TTokenID): boolean; inline; function ReadNewOrExistingID(Scope: TScope; out ID: TIDentifier; out Decl: TIDDeclaration): TTokenID; procedure PutMessage(Message: TCompilerMessage); overload; procedure PutMessage(MessageType: TCompilerMessageType; const MessageText: string); overload; procedure PutMessage(MessageType: TCompilerMessageType; const MessageText: string; const SourcePosition: TTextPosition); overload; procedure Error(const Message: string; const Params: array of const; const TextPosition: TTextPosition); procedure Warning(const Message: string; const Params: array of const; const TextPosition: TTextPosition); procedure Hint(const Message: string; const Params: array of const; const TextPosition: TTextPosition); overload; procedure Hint(const Message: string; const Params: array of const); overload; function FindID(Scope: TScope; const ID: TIdentifier): TIDDeclaration; overload; inline; function FindIDNoAbort(Scope: TScope; const ID: TIdentifier): TIDDeclaration; overload; inline; function FindIDNoAbort(Scope: TScope; const ID: string): TIDDeclaration; overload; inline; class function StrictMatchProcSingnatures(const SrcParams, DstParams: TIDParamArray; const SrcResultType, DstResultType: TIDType): Boolean; class function StrictMatchProc(const Src, Dst: TIDProcedure): Boolean; public function GetFirstFunc: TASTDeclaration; override; function GetFirstVar: TASTDeclaration; override; function GetFirstType: TASTDeclaration; override; function GetFirstConst: TASTDeclaration; override; class function CheckImplicit(const SContext: TSContext; Source: TIDExpression; Dest: TIDType; AResolveCalls: Boolean = False): TIDDeclaration; class function ConstDynArrayToSet(const SContext: TSContext; const CDynArray: TIDExpression; TargetSetType: TIDSet): TIDExpression; static; class function MatchSetImplicit(const SContext: TSContext; Source: TIDExpression; Destination: TIDSet): TIDExpression; static; function ParseUnitName(Scope: TScope; out ID: TIdentifier): TTokenID; procedure ParseUnitDecl(Scope: TScope); function ParseUsesSection(Scope: TScope): TTokenID; //======================================================================================================================= /// Парсинг типов procedure ParseEnumType(Scope: TScope; Decl: TIDEnum); procedure ParseRangeType(Scope: TScope; Expr: TIDExpression; const ID: TIdentifier; out Decl: TIDRangeType); function ParseImportStatement(Scope: TScope; out ImportLib, ImportName: TIDDeclaration): TTokenID; function ParseStaticArrayType(Scope: TScope; Decl: TIDArray): TTokenID; function ParseSetType(Scope: TScope; Decl: TIDSet): TTokenID; function ParsePointerType(Scope: TScope; const ID: TIdentifier; out Decl: TIDPointer): TTokenID; function ParseProcType(Scope: TScope; const ID: TIdentifier; GDescriptor: PGenericDescriptor; out Decl: TIDProcType): TTokenID; function ParseRecordType(Scope: TScope; Decl: TIDRecord): TTokenID; function ParseCaseRecord(Scope: TScope; Decl: TIDRecord): TTokenID; function ParseClassAncestorType(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; ClassDecl: TIDClass): TTokenID; function ParseClassType(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TIDClass): TTokenID; function ParseTypeMember(Scope: TScope; Struct: TIDStructure): TTokenID; function ParseClassOfType(Scope: TScope; const ID: TIdentifier; out Decl: TIDClassOf): TTokenID; function ParseInterfaceType(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TIDInterface): TTokenID; function ParseIntfGUID(Scope: TScope; Decl: TIDInterface): TTokenID; //======================================================================================================================= function ParseTypeRecord(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TIDType): TTokenID; function ParseTypeArray(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TIDType): TTokenID; function ParseTypeHelper(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TDlphHelper): TTokenID; // функция парсинга анонимного типа function ParseTypeDecl(Scope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TIDType): TTokenID; function ParseTypeDeclOther(Scope: TScope; const ID: TIdentifier; out Decl: TIDType): TTokenID; // функция парсинга именованного типа function ParseNamedTypeDecl(Scope: TScope): TTokenID; // функция парсинга указания типа (имени существующего или анонимного типа) function ParseTypeSpec(Scope: TScope; out DataType: TIDType): TTokenID; function ParseGenericTypeSpec(Scope: TScope; const ID: TIdentifier; out DataType: TIDType): TTokenID; virtual; function ParseGenericsHeader(Scope: TScope; out Args: TIDTypeArray): TTokenID; function ParseGenericsConstraint(Scope: TScope; out AConstraint: TGenericConstraint; out AConstraintType: TIDType): TTokenID; function ParseGenericsArgs(Scope: TScope; const SContext: TSContext; out Args: TIDExpressions): TTokenID; function ParseStatements(Scope: TScope; const SContext: TSContext; IsBlock: Boolean): TTokenID; overload; function GetPtrReferenceType(Decl: TIDPointer): TIDType; procedure CheckForwardPtrDeclarations; function ParseExpression(Scope: TScope; const SContext: TSContext; var EContext: TEContext; out ASTE: TASTExpression): TTokenID; overload; function ParseConstExpression(Scope: TScope; out Expr: TIDExpression; EPosition: TExpessionPosition): TTokenID; function ParseMemberCall(Scope: TScope; var EContext: TEContext; const ASTE: TASTExpression): TTokenID; function ParseMember(Scope: TScope; var EContext: TEContext; const ASTE: TASTExpression): TTokenID; function ParseIdentifier(Scope, SearchScope: TScope; out Expression: TIDExpression; var EContext: TEContext; const PrevExpr: TIDExpression; const ASTE: TASTExpression): TTokenID; function ParseArrayMember(Scope: TScope; var EContext: TEContext; ASTE: TASTExpression): TTokenID; function ParsePropertyMember(var PMContext: TPMContext; Scope: TScope; Prop: TIDProperty; out Expression: TIDExpression; var EContext: TEContext; const PrevExpr: TIDExpression): TTokenID; function ParseIndexedPropertyArgs(Scope: TScope; out ArgumentsCount: Integer; var EContext: TEContext): TTokenID; function InferTypeByVector(Scope: TScope; Vector: TIDExpressions): TIDType; procedure ParseVector(Scope: TScope; var EContext: TEContext); function ParseEntryCall(Scope: TScope; CallExpr: TIDCallExpression; const EContext: TEContext; const ASTE: TASTExpression): TTokenID; function ParseBuiltinCall(Scope: TScope; CallExpr: TIDExpression; var EContext: TEContext): TTokenID; function ParseExplicitCast(Scope: TScope; const SContext: TSContext; var DstExpression: TIDExpression): TTokenID; function ParseProcedure(Scope: TScope; ProcType: TProcType; Struct: TIDStructure = nil): TTokenID; function ParseGlobalProc(Scope: TScope; ProcType: TProcType; const ID: TIdentifier; ProcScope: TProcScope): TTokenID; function ParseNestedProc(Scope: TScope; ProcType: TProcType; const ID: TIdentifier; ProcScope: TProcScope): TTokenID; function ParseProcName(Scope: TScope; ProcType: TProcType; out Name: TIdentifier; var Struct: TIDStructure; out ProcScope: TProcScope; out GenericParams: TIDTypeArray): TTokenID; function ParseProcBody(Proc: TASTDelphiProc): TTokenID; function ParseGenericProcRepeatedly(Scope: TScope; GenericProc, Proc: TASTDelphiProc; Struct: TIDStructure): TTokenID; function ParseOperator(Scope: TScope; Struct: TIDStructure): TTokenID; function ParseGenericMember(const PMContext: TPMContext; const SContext: TSContext; StrictSearch: Boolean; out Decl: TIDDeclaration; out WithExpression: TIDExpression): TTokenID; function ParseIfThenStatement(Scope: TScope; const SContext: TSContext): TTokenID; function ParseWhileStatement(Scope: TScope; const SContext: TSContext): TTokenID; function ParseRepeatStatement(Scope: TScope; const SContext: TSContext): TTokenID; function ParseWithStatement(Scope: TScope; const SContext: TSContext): TTokenID; function ParseForStatement(Scope: TScope; const SContext: TSContext): TTokenID; function ParseForInStatement(Scope: TScope; const SContext: TSContext; LoopVar: TIDExpression): TTokenID; function ParseCaseStatement(Scope: TScope; const SContext: TSContext): TTokenID; // function ParseBreakStatement(Scope: TScope; const SContext: TSContext): TTokenID; // function ParseContinueStatement(Scope: TScope; const SContext: TSContext): TTokenID; function ParseInheritedStatement(Scope: TScope; const EContext: TEContext): TTokenID; function ParseImmVarStatement(Scope: TScope; const SContext: TSContext): TTokenID; function ParseTrySection(Scope: TScope; const SContext: TSContext): TTokenID; function ParseExceptOnSection(Scope: TScope; KW: TASTKWTryBlock; const SContext: TSContext): TTokenID; function ParseRaiseStatement(Scope: TScope; const SContext: TSContext): TTokenID; function ParseLabelSection(Scope: TScope): TTokenID; function ParseGoToStatement(Scope: TScope; const SContext: TSContext): TTokenID; function ParseASMStatement(Scope: TScope; const SContext: TSContext): TTokenID; function ParseProperty(Scope: TScope; Struct: TIDStructure): TTokenID; function ParseVarDefaultValue(Scope: TScope; DataType: TIDType; out DefaultValue: TIDExpression): TTokenID; function ParseVarStaticArrayDefaultValue(Scope: TScope; ArrType: TIDArray; out DefaultValue: TIDExpression): TTokenID; function ParseVarRecordDefaultValue(Scope: TScope; Struct: TIDStructure; out DefaultValue: TIDExpression): TTokenID; function ParseRecordInitValue(Scope: TRecordInitScope; var FirstField: TIDExpression): TTokenID; function ParseConstSection(Scope: TScope): TTokenID; function ParseVarSection(Scope: TScope; Visibility: TVisibility; IsWeak: Boolean = False): TTokenID; function ParseFieldsSection(Scope: TScope; Visibility: TVisibility; Struct: TIDStructure; IsClass: Boolean): TTokenID; function ParseFieldsInCaseRecord(Scope: TScope; Visibility: TVisibility; Struct: TIDStructure): TTokenID; function ParseParameters(EntryScope: TScope; ParamsScope: TParamsScope): TTokenID; function ParseAnonymousProc(Scope: TScope; var EContext: TEContext; const SContext: TSContext; ProcType: TTokenID): TTokenID; function ParseInitSection: TTokenID; function ParseFinalSection: TTokenID; function ParsePlatform(Scope: TScope): TTokenID; function ParseUnknownID(Scope: TScope; const PrevExpr: TIDExpression; ID: TIdentifier; out Decl: TIDDeclaration): TTokenID; function ParseDeprecated(Scope: TScope; out DeprecatedExpr: TIDExpression): TTokenID; function CheckAndMakeClosure(const SContext: TSContext; const ProcDecl: TIDProcedure): TIDClosure; function EmitCreateClosure(const SContext: TSContext; Closure: TIDClosure): TIDExpression; function CheckAndParseDeprecated(Scope: TScope; CurrToken: TTokenID): TTokenID; function ParseAttribute(Scope: TScope): TTokenID; function CheckAndParseAttribute(Scope: TScope): TTokenID; function CheckAndParseProcTypeCallConv(Scope: TScope; Token: TTokenID; TypeDecl: TIDType): TTokenID; function ParseAsmSpecifier: TTokenID; property InitProc: TIDProcedure read FInitProc; property FinalProc: TIDProcedure read FFinalProc; /// condition compilation function ParseCondStatements(Scope: TScope; Token: TTokenID): TTokenID; function ParseCondInclude(Scope: TScope): TTokenID; function ParseCondIfDef(Scope: TScope): Boolean; function ParseCondHint(Scope: TScope): TTokenID; function ParseCondWarn(Scope: TScope): TTokenID; function ParseCondError(Scope: TScope): TTokenID; function ParseCondMessage(Scope: TScope): TTokenID; function Defined(const Name: string): Boolean; function ParseCondIf(Scope: TScope; out ExpressionResult: TCondIFValue): TTokenID; function ParseCondOptSet(Scope: TScope): TTokenID; procedure ParseCondDefine(Scope: TScope; add_define: Boolean); function ParseCondOptions(Scope: TScope): TTokenID; procedure EnumIntfDeclarations(const Proc: TEnumASTDeclProc); override; procedure EnumAllDeclarations(const Proc: TEnumASTDeclProc); override; procedure PostCompileChecks; property Source: string read GetSource; function Compile(ACompileIntfOnly: Boolean; RunPostCompile: Boolean = True): TCompilerResult; override; function CompileIntfOnly: TCompilerResult; override; function CompileSource(Scope: TScope; const FileName: string; const Source: string): ICompilerMessages; constructor Create(const Project: IASTProject; const FileName: string; const Source: string = ''); override; destructor Destroy; override; end; function GetUnit(const SContext: PSContext): TASTDelphiUnit; overload; function GetUnit(const EContext: TEContext): TASTDelphiUnit; overload; function GetBoolResultExpr(const SContext: TSContext): TIDBoolResultExpression; function ScopeToVarList(Scope: TScope; SkipFirstCount: Integer): TIDParamArray; function IntConstExpression(const SContext: TSContext; const Value: Int64): TIDExpression; inline; function StrConstExpression(const SContext: TSContext; const Value: string): TIDExpression; inline; implementation uses System.Math, System.Types, System.StrUtils, System.SysUtils, System.Classes, AST.Parser.Errors, AST.Delphi.System, AST.Delphi.SysOperators; type TSContextHelper = record helper for TSContext private function GetSysUnit: TSYSTEMUnit; function GetErrors: TASTDelphiErrors; public property SysUnit: TSYSTEMUnit read GetSysUnit; property ERRORS: TASTDelphiErrors read GetErrors; end; function GetUnit(const SContext: PSContext): TASTDelphiUnit; begin Result := SContext.Module as TASTDelphiUnit; end; function GetUnit(const EContext: TEContext): TASTDelphiUnit; begin Result := EContext.SContext.Module as TASTDelphiUnit; end; function GetBoolResultExpr(const SContext: TSContext): TIDBoolResultExpression; var Decl: TIDVariable; begin Decl := TASTDelphiUnit.GetTMPVar(SContext, SContext.SysUnit._Boolean); Result := TIDBoolResultExpression.Create(Decl); end; function IntConstExpression(const SContext: TSContext; const Value: Int64): TIDExpression; var DataType: TIDType; begin DataType := SContext.SysUnit.DataTypes[GetValueDataType(Value)]; Result := TIDExpression.Create(TIDIntConstant.CreateWithoutScope(DataType, Value)); end; function StrConstExpression(const SContext: TSContext; const Value: string): TIDExpression; inline; var Decl: TIDStringConstant; begin Decl := TIDStringConstant.CreateAsAnonymous(nil, SContext.SysUnit._UnicodeString, Value); Result := TIDExpression.Create(Decl); end; { TASTDelphiUnit } function TASTDelphiUnit.ParseSetType(Scope: TScope; Decl: TIDSet): TTokenID; var ID: TIdentifier; Base: TIDType; Expression: TIDExpression; begin Lexer_MatchToken(Lexer_NextToken(Scope), token_of); Result := Lexer_NextToken(Scope); Result := ParseTypeDecl(Scope, nil, TIdentifier.Empty, Base); CheckOrdinalType(Base); Decl.BaseType := TIDOrdinal(Base); Decl.BaseType.OverloadBinarOperator2(opIn, Decl, Sys._Boolean); end; function TASTDelphiUnit.ParseStatements(Scope: TScope; const SContext: TSContext; IsBlock: Boolean): TTokenID; var LEContext: TEContext; NewScope: TScope; AST: TASTItem; begin // ASTE.AddDeclItem(Expr.Declaration, Expr.TextPosition); Result := Lexer_CurTokenID; while True do begin case Result of {BEGIN} token_begin: begin Lexer_NextToken(Scope); NewScope := TScope.Create(stLocal, Scope); Result := ParseStatements(NewScope, SContext, True); Lexer_MatchToken(Result, token_end); Result := Lexer_NextToken(Scope); if not IsBlock then Exit; continue; end; {END} token_end: begin exit; end; {UNTIL} token_until: Break; {IF} token_if: Result := ParseIfThenStatement(Scope, SContext); {WHILE} token_while: Result := ParseWhileStatement(Scope, SContext); {REPEAT} token_repeat: Result := ParseRepeatStatement(Scope, SContext); {WITH} token_with: Result := ParseWithStatement(Scope, SContext); {FOR} token_for: Result := ParseForStatement(Scope, SContext); {CASE} token_case: Result := ParseCaseStatement(Scope, SContext); {GOTO} token_goto: Result := ParseGoTOStatement(Scope, SContext); {ASM} token_asm: Result := ParseASMStatement(Scope, SContext); {INHERITED} token_inherited: begin InitEContext({out} LEContext, SContext, ExprLValue); Result := ParseInheritedStatement(Scope, LEContext); end; {TRY} token_try: Result := ParseTrySection(Scope, SContext); {EXCEPT/FINALLY} token_except, token_finally: begin if not SContext.IsTryBlock then ERRORS.TRY_KEYWORD_MISSED; Exit; end; {RAISE} token_raise: Result := ParseRaiseStatement(Scope, SContext); {BREAK} // token_break: Result := ParseBreakStatement(Scope, SContext); {CONTINUE} // token_continue: Result := ParseContinueStatement(Scope, SContext); {;} token_semicolon:; {VAR} token_var: Result := ParseImmVarStatement(Scope, SContext); {@} token_address: begin Result := Lexer_NextToken(Scope); Continue; end; {IDENTIFIER, OPEN ROUND} token_identifier, token_id_or_keyword, token_openround: begin InitEContext({out} LEContext, SContext, ExprLValue); begin var ASTEDst, ASTESrc: TASTExpression; Result := ParseExpression(Scope, SContext, LEContext, ASTEDst); if Result = token_assign then begin var REContext: TEContext; InitEContext(REContext, SContext, ExprRValue); Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, REContext, ASTESrc); LEContext.RPNPushExpression(REContext.Result); LEContext.RPNPushOperator(opAssignment); LEContext.RPNFinish(); var Op := SContext.Add(TASTOpAssign) as TASTOpAssign; Op.Dst := ASTEDst; Op.Src := ASTESrc; end else if Result = token_colon then begin var LExpr := LEContext.Result; CheckLabelExpression(LExpr); var KW := SContext.Add(TASTKWLabel) as TASTKWLabel; KW.LabelDecl := LExpr.Declaration; Result := Lexer_NextToken(Scope); Continue; end else SContext.AddItem(ASTEDst); //CheckAndCallFuncImplicit(LEContext); //CheckUnusedExprResult(LEContext); end; end; token_initialization, token_finalization: Break; token_eof: Exit; else if IsBlock then ERRORS.EXPECTED_KEYWORD_OR_ID; end; if IsBlock then Result := Lexer_MatchSemicolonAndNext(Scope, Result) else Exit; end; end; function TASTDelphiUnit.ParseStaticArrayType(Scope: TScope; Decl: TIDArray): TTokenID; procedure CheckExpression(Expr: TIDExpression); begin CheckEmptyExpression(Expr); if not ((Expr.ItemType = itConst) or ((Expr.ItemType = itType) and (TIDType(Expr.Declaration).IsOrdinal))) then ERRORS.ORDINAL_CONST_OR_TYPE_REQURED; end; var Expr: TIDExpression; Bound: TIDOrdinal; DataType: TIDType; begin // todo сделать парсинг многомерного массива вида array of array of ... while True do begin // нижняя граница/тип/размер Lexer_NextToken(Scope); Result := ParseConstExpression(Scope, Expr, ExprNested); CheckExpression(Expr); if Expr.ItemType = itType then Bound := TIDOrdinal(Expr.Declaration) else Bound := Expr.AsRangeConst.DataType as TIDRangeType; Decl.AddBound(Bound); if Result = token_coma then begin continue; end; Break; end; Lexer_MatchToken(Result, token_closeblock); Result := Lexer_NextToken(Scope); Lexer_MatchToken(Result, token_of); Result := ParseTypeSpec(Scope, DataType); Decl.ElementDataType := DataType; end; function TASTDelphiUnit.ParseTrySection(Scope: TScope; const SContext: TSContext): TTokenID; var KW: TASTKWTryBlock; NewContext: TSContext; ExceptItem: TASTKWTryExceptItem; begin KW := SContext.Add(TASTKWTryBlock) as TASTKWTryBlock; NewContext := SContext.MakeChild(Scope, KW.Body); // запоминаем предыдущий TryBlock Lexer_NextToken(Scope); Result := ParseStatements(Scope, NewContext, True); case Result of {parse EXCEPT section} token_except: begin Result := Lexer_NextToken(Scope); if Result <> token_on then begin ExceptItem := KW.AddExceptBlock(nil); NewContext := SContext.MakeChild(Scope, ExceptItem.Body); Result := ParseStatements(Scope, NewContext, True); end else begin while Result = token_on do Result := ParseExceptOnSection(Scope, KW, SContext); end; Lexer_MatchToken(Result, token_end); Result := Lexer_NextToken(Scope); end; {parse FINALLY section} token_finally: begin Lexer_NextToken(Scope); KW.FinallyBody := TASTBlock.Create(KW); NewContext := SContext.MakeChild(Scope, KW.FinallyBody); Result := ParseStatements(Scope, NewContext, True); Lexer_MatchToken(Result, token_end); Result := Lexer_NextToken(Scope); end; else AbortWork(sExceptOrFinallySectionWasMissed, Lexer_Position); end; end; function TASTDelphiUnit.ParseTypeArray(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TIDType): TTokenID; var TypeScope: TScope; DataType: TIDType; begin if Assigned(GDescriptor) then TypeScope := GDescriptor.Scope else if Assigned(GenericScope) then TypeScope := GenericScope else TypeScope := Scope; Result := Lexer_NextToken(Scope); if Result = token_openblock then begin {static array} Decl := TIDStaticArray.Create(Scope, ID); Decl.GenericDescriptor := GDescriptor; if ID.Name <> '' then begin if Assigned(GDescriptor) then InsertToScope(Scope, GDescriptor.SearchName, Decl) else InsertToScope(Scope, Decl); end; Result := ParseStaticArrayType(TypeScope, TIDArray(Decl)); end else begin {dynamic array} Lexer_MatchToken(Result, token_of); Decl := TIDDynArray.Create(Scope, ID); Decl.GenericDescriptor := GDescriptor; if ID.Name <> '' then begin if Assigned(GDescriptor) then InsertToScope(Scope, GDescriptor.SearchName, Decl) else InsertToScope(Scope, Decl); end; Result := ParseTypeSpec(TypeScope, DataType); // case: array of const if (DataType = nil) and (Result = token_const) then begin DataType := TSYSTEMUnit(SysUnit).SystemDeclarations._TVarRec; if not Assigned(DataType) then AbortWorkInternal('System.TVarRec is not defined', Lexer_Position); Result := Lexer_NextToken(Scope); end; TIDDynArray(Decl).ElementDataType := DataType; end; end; function TASTDelphiUnit.ParseTypeDecl(Scope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TIDType): TTokenID; var IsPacked: Boolean; IsAnonimous: Boolean; begin Result := Lexer_CurTokenID; // является ли тип анонимным IsAnonimous := (ID.Name = ''); // является ли тип упакованным if Result <> token_packed then IsPacked := False else begin IsPacked := True; Result := Lexer_NextToken(Scope); end; case Result of ///////////////////////////////////////////////////////////////////////// // type of ///////////////////////////////////////////////////////////////////////// token_type: begin Lexer_NextToken(Scope); var ResExpr: TIDExpression; Result := ParseConstExpression(Scope, ResExpr, ExprRValue); if ResExpr.ItemType = itType then begin Decl := TIDAliasType.CreateAlias(Scope, ID, ResExpr.AsType); InsertToScope(Scope, Decl); end; Exit; end; ///////////////////////////////////////////////////////////////////////// // pointer type ///////////////////////////////////////////////////////////////////////// token_caret: Result := ParsePointerType(Scope, ID, TIDPointer(Decl)); ///////////////////////////////////////////////////////////////////////// // array type ///////////////////////////////////////////////////////////////////////// token_array: Result := ParseTypeArray(Scope, nil, GDescriptor, ID, Decl); ///////////////////////////////////////////////////////////////////////// // procedural type ///////////////////////////////////////////////////////////////////////// token_id_or_keyword: if Lexer_AmbiguousId = token_reference then Result := ParseProcType(Scope, ID, GDescriptor, TIDProcType(Decl)); token_procedure, token_function: Result := ParseProcType(Scope, ID, GDescriptor, TIDProcType(Decl)); ///////////////////////////////////////////////////////////////////////// // set ///////////////////////////////////////////////////////////////////////// token_set: begin Decl := TIDSet.Create(Scope, ID); if not IsAnonimous then InsertToScope(Scope, Decl); Result := ParseSetType(Scope, TIDSet(Decl)); end; ///////////////////////////////////////////////////////////////////////// // enum ///////////////////////////////////////////////////////////////////////// token_openround: begin Decl := TIDEnum.Create(Scope, ID); if not IsAnonimous then InsertToScope(Scope, Decl) else {если это анонимная декларация типа для параметра, то добавляем его в более высокий scope} if Assigned(Scope.Parent) and (Scope.ScopeClass = scProc) then Scope := Scope.Parent; ParseEnumType(Scope, TIDEnum(Decl)); Result := Lexer_NextToken(Scope); end; ///////////////////////////////////////////////////////////////////////// // record ///////////////////////////////////////////////////////////////////////// token_record: Result := ParseTypeRecord(Scope, nil, GDescriptor, ID, Decl); ///////////////////////////////////////////////////////////////////////// // class ///////////////////////////////////////////////////////////////////////// token_class: begin Result := Lexer_NextToken(Scope); if Result = token_of then Result := ParseClassOfType(Scope, ID, TIDClassOf(Decl)) else begin if IsAnonimous then AbortWork(sClassTypeCannotBeAnonimous, Lexer.PrevPosition); Result := ParseClassType(Scope, nil, GDescriptor, ID, TIDClass(Decl)); end; end; ///////////////////////////////////////////////////////////////////////// // interface ///////////////////////////////////////////////////////////////////////// token_interface: Result := ParseInterfaceType(Scope, nil, GDescriptor, ID, TIDInterface(Decl)); ///////////////////////////////////////////////////////////////////////// // other ///////////////////////////////////////////////////////////////////////// else Result := ParseTypeDeclOther(Scope, ID, Decl); end; if Assigned(Decl) then begin Decl.IsPacked := IsPacked; AddType(Decl); end; Result := CheckAndParseDeprecated(Scope, Result); end; function TASTDelphiUnit.ParseTypeDeclOther(Scope: TScope; const ID: TIdentifier; out Decl: TIDType): TTokenID; var IsAnonimous: Boolean; Expr: TIDExpression; begin IsAnonimous := (ID.Name = ''); Result := Lexer_CurTokenID; case Result of token_minus, token_plus: begin Result := ParseConstExpression(Scope, Expr, ExprRValue); ParseRangeType(Scope, Expr, ID, TIDRangeType(Decl)); if not IsAnonimous then InsertToScope(Scope, Decl); end; token_identifier: begin Result := ParseConstExpression(Scope, Expr, ExprType); {alias type} if Expr.ItemType = itType then begin Decl := TIDAliasType.CreateAlias(Scope, ID, Expr.AsType); end else {range type} begin ParseRangeType(Scope, Expr, ID, TIDRangeType(Decl)); end; if not IsAnonimous then InsertToScope(Scope, Decl); end; else Decl := nil; end; end; function TASTDelphiUnit.ParseTypeHelper(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TDlphHelper): TTokenID; var TargetID: TIdentifier; TargetDecl: TIDType; Visibility: TVisibility; begin Lexer_ReadToken(Scope, token_for); Lexer_ReadNextIdentifier(Scope, TargetID); TargetDecl := TIDType(FindID(Scope, TargetID)); if TargetDecl.ItemType <> itType then ERRORS.TYPE_REQUIRED(Lexer_PrevPosition); Decl := TDlphHelper.Create(Scope, ID); Decl.Target := TargetDecl; if Assigned(TargetDecl.Helper) then Warning('Helper for %s was reassigned from %s to %s', [TargetDecl.Name, TargetDecl.Helper.Name, ID.Name], ID.TextPosition); TargetDecl.Helper := Decl; if ID.Name <> '' then begin if Assigned(GDescriptor) then InsertToScope(Scope, GDescriptor.SearchName, Decl) else InsertToScope(Scope, Decl); end; Result := Lexer_NextToken(Scope); while True do begin case Result of token_class: begin Result := Lexer_NextToken(scope); case Result of token_procedure: Result := ParseProcedure(Decl.StaticMembers, ptClassProc, Decl); token_function: Result := ParseProcedure(Decl.StaticMembers, ptClassFunc, Decl); token_operator: Result := ParseOperator(Decl.StaticMembers, Decl); token_property: Result := ParseProperty(Decl.StaticMembers, Decl); else AbortWork('PROCEDURE, FUNCTION and PROPERIES are allowed in helpers only', Lexer_Position); end; end; token_procedure: Result := ParseProcedure(Decl.Members, ptProc, Decl); token_function: Result := ParseProcedure(Decl.Members, ptFunc, Decl); token_property: Result := ParseProperty(Decl.Members, Decl); token_public: begin Visibility := vPublic; Result := Lexer_NextToken(Scope); end; token_private: begin Visibility := vPrivate; Result := Lexer_NextToken(Scope); end; token_strict: begin Result := Lexer_NextToken(Scope); case Result of token_private: Visibility := vStrictPrivate; token_protected: Visibility := vStrictProtected; else ERRORS.EXPECTED_TOKEN(token_private, Result); end; Result := Lexer_NextToken(Scope); end; token_const: Result := ParseConstSection(Decl.StaticMembers); token_type: Result := ParseNamedTypeDecl(Decl.StaticMembers); token_end: break; else AbortWork('PROCEDURE, FUNCTION and PROPERIES are allowed in helpers only', Lexer_Position); end; end; Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseTypeMember(Scope: TScope; Struct: TIDStructure): TTokenID; begin Result := Lexer_NextToken(Scope); case Result of token_procedure: Result := ParseProcedure(Struct.StaticMembers, ptClassProc, Struct); token_function: Result := ParseProcedure(Struct.StaticMembers, ptClassFunc, Struct); token_property: Result := ParseProperty(Struct.StaticMembers, Struct); token_constructor: Result := ParseProcedure(Struct.StaticMembers, ptClassConstructor, Struct); token_destructor: Result := ParseProcedure(Struct.StaticMembers, ptClassDestructor, Struct); token_var: begin Lexer_NextToken(Scope); Result := ParseFieldsSection(Struct.StaticMembers, vLocal, Struct, True); end else ERRORS.PROC_OR_PROP_OR_VAR_REQUIRED; end; end; function TASTDelphiUnit.ParseTypeRecord(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TIDType): TTokenID; {var TypeScope: TScope;} begin {if Assigned(GDescriptor) then TypeScope := GDescriptor.Scope else TypeScope := Scope;} Result := Lexer_NextToken(Scope); if Result = token_helper then begin Result := ParseTypeHelper(Scope, GenericScope, GDescriptor, ID, TDlphHelper(Decl)); Exit; end; // try to find forward declaration first (for system types) var FForwardDecl := FindIDNoAbort(Scope, ID); if Assigned(FForwardDecl) and (FForwardDecl is TIDRecord) and TIDType(FForwardDecl).NeedForward then Decl := TIDRecord(FForwardDecl) else begin Decl := TIDRecord.Create(Scope, ID); Decl.GenericDescriptor := GDescriptor; if Assigned(GenericScope) then TIDRecord(Decl).Members.AddScope(GenericScope); if ID.Name <> '' then begin if Assigned(GDescriptor) then InsertToScope(Scope, GDescriptor.SearchName, Decl) else InsertToScope(Scope, Decl); end; end; Result := ParseRecordType(Scope, TIDRecord(Decl)); end; function TASTDelphiUnit.ParseTypeSpec(Scope: TScope; out DataType: TIDType): TTokenID; var Decl: TIDDeclaration; SearchScope: TScope; begin Result := Lexer_NextToken(Scope); if Result = token_identifier then begin SearchScope := nil; while True do begin var ID: TIdentifier; Lexer_ReadCurrIdentifier(ID); Result := Lexer_NextToken(Scope); {если это специализация обобщенного типа} if Result = token_less then begin Result := ParseGenericTypeSpec(Scope, ID, {out} DataType); Exit; end; if SearchScope = nil then Decl := FindIDNoAbort(Scope, ID) else Decl := SearchScope.FindMembers(ID.Name); if not Assigned(Decl) then ERRORS.UNDECLARED_ID(ID); // workaround for a case when param or field can be named as type if Decl.ItemType = itVar then begin var OuterDecl := FindIDNoAbort(Scope.Parent, ID); if Assigned(OuterDecl) then Decl := OuterDecl; end; case Decl.ItemType of itType: begin DataType := TIDType(Decl).ActualDataType; if Result = token_dot then begin if not (DataType is TIDStructure) then ERRORS.STRUCT_TYPE_REQUIRED(Lexer_PrevPosition); SearchScope := TIDStructure(DataType).Members; Lexer_NextToken(Scope); continue; end else if Result = token_openblock then begin CheckStingType(DataType); Lexer_NextToken(Scope); var Expr: TIDExpression := nil; Result := ParseConstExpression(Scope, Expr, ExprNested); Lexer_MatchToken(Result, token_closeblock); DataType := Sys._ShortString; Result := Lexer_NextToken(Scope); end; Exit; end; itAlias: begin Decl := Decl.Original; if Decl.ItemType = itType then begin DataType := Decl as TIDType; if Result = token_dot then begin if not (DataType is TIDStructure) then ERRORS.STRUCT_TYPE_REQUIRED(Lexer_PrevPosition); SearchScope := TIDStructure(DataType).Members; Lexer_NextToken(Scope); continue; end; Exit; end; end; itUnit: begin SearchScope := TIDUnit(Decl).Members; Lexer_NextToken(Scope); continue; end; else ERRORS.INVALID_TYPE_DECLARATION(ID); end; Exit; end; Exit; end else if Result = token_const then begin // case: array of const DataType := nil; Exit; end; Result := ParseTypeDecl(Scope, nil, TIdentifier.Empty, DataType); if not Assigned(DataType) then ERRORS.INVALID_TYPE_DECLARATION; end; procedure TASTDelphiUnit.ParseUnitDecl(Scope: TScope); var Decl: TIDUnit; Token: TTokenID; begin Lexer_ReadToken(Scope, token_Unit); Token := ParseUnitName(Scope, fUnitName); Lexer_MatchSemicolon(Token); Decl := TIDUnit.Create(Scope, Self); // add itself to the intf scope InsertToScope(Scope, Decl); end; function TASTDelphiUnit.ParseUnitName(Scope: TScope; out ID: TIdentifier): TTokenID; var UName: string; begin Result := Lexer_NextToken(Scope); while True do begin Lexer_MatchIdentifier(Result); UName := AddStringSegment(UName, Lexer.OriginalToken, '.'); Result := Lexer_NextToken(Scope); if Result <> token_dot then break; Result := Lexer_NextToken(Scope); end; Package.GetStringConstant(UName); ID := Identifier(UName, Lexer_PrevPosition); end; procedure StopCompile(CompileSuccess: Boolean); begin raise ECompilerStop.Create(CompileSuccess); end; function TASTDelphiUnit.ParseUsesSection(Scope: TScope): TTokenID; var Token: TTokenID; ID: TIdentifier; LUnit: TPascalUnit; Idx: Integer; begin while True do begin Token := ParseUnitName(Scope, {out} ID); // check recursive using if ID.Name = Self.FUnitName.Name then ERRORS.UNIT_RECURSIVELY_USES_ITSELF(ID); // find the unit file LUnit := Package.UsesUnit(ID.Name, nil) as TPascalUnit; if not Assigned(LUnit) then ERRORS.UNIT_NOT_FOUND(ID); // check unique using if IntfImportedUnits.Find(ID.Name, {var} Idx) or ImplImportedUnits.Find(ID.Name, {var} Idx) then begin //if (LUnit <> SYSUnit) or FSystemExplicitUse then ERRORS.ID_REDECLARATED(ID); end; // compile if not compiled yet if LUnit.Compiled = CompileNone then begin var AResult := LUnit.Compile({ACompileIntfOnly:} True); if (AResult <> CompileSuccess) and Package.StopCompileIfError then StopCompile({CompileSuccess:} False); end; if Scope = IntfScope then IntfImportedUnits.AddObject(ID.Name, LUnit) else if Scope = ImplScope then ImplImportedUnits.AddObject(ID.Name, LUnit) else AbortWorkInternal('Wrong scope'); case Token of token_coma: continue; token_semicolon: break; else ERRORS.SEMICOLON_EXPECTED; end; end; Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseEntryCall(Scope: TScope; CallExpr: TIDCallExpression; const EContext: TEContext; const ASTE: TASTExpression): TTokenID; var ArgumentsCount: Integer; Expr: TIDExpression; InnerEContext: TEContext; ASTExpr: TASTExpression; //ASTCall: TASTOpCallProc; begin //ASTCall := ASTE.AddOperation<TASTOpCallProc>; //ASTCall.Proc := CallExpr.Declaration; ArgumentsCount := 0; InitEContext(InnerEContext, EContext.SContext, ExprNested); {цикл парсинга аргументов} while true do begin Result := Lexer_NextToken(Scope); if Result = token_closeround then begin Result := Lexer_NextToken(Scope); Break; end; Result := ParseExpression(Scope, EContext.SContext, InnerEContext, ASTExpr); //ASTCall.AddArg(ASTExpr); Expr := InnerEContext.Result; if Assigned(Expr) then begin {if Expr.DataType = Sys._Boolean then begin if (Expr.ItemType = itVar) and Expr.IsAnonymous then Bool_CompleteImmediateExpression(InnerEContext, Expr); end;} EContext.RPNPushExpression(Expr); end else begin // Добавляем пустой Expression для значения по умолчанию EContext.RPNPushExpression(nil); end; Inc(ArgumentsCount); case Result of token_coma: begin InnerEContext.Reset; continue; end; token_closeround: begin Result := Lexer_NextToken(Scope); Break; end; else ERRORS.INCOMPLETE_STATEMENT('call'); end; end; TIDCallExpression(CallExpr).ArgumentsCount := ArgumentsCount; EContext.RPNPushExpression(CallExpr); EContext.RPNPushOperator(opCall); end; procedure TASTDelphiUnit.ParseEnumType(Scope: TScope; Decl: TIDEnum); var ID: TIdentifier; Token: TTokenID; Item: TIDIntConstant; Expr: TIDExpression; LB, HB, LCValue: Int64; begin LCValue := 0; LB := MaxInt64; HB := MinInt64; Decl.Items := TScope.Create(stLocal, Scope); Token := Lexer_NextToken(Scope); while True do begin Lexer_MatchIdentifier(Token); Lexer_ReadCurrIdentifier(ID); Item := TIDIntConstant.Create(Decl.Items, ID); Item.DataType := Decl; InsertToScope(Decl.Items, Item); if not Options.SCOPEDENUMS then InsertToScope(Scope, Item); Token := Lexer_NextToken(Scope); if Token = token_equal then begin Lexer_NextToken(Scope); Token := ParseConstExpression(Scope, Expr, ExprNested); CheckEmptyExpression(Expr); CheckConstExpression(Expr); LCValue := TIDIntConstant(Expr.Declaration).Value; end; Item.Value := LCValue; LB := Min(LB, LCValue); HB := Max(HB, LCValue); case Token of token_coma: begin Token := Lexer_NextToken(Scope); Inc(LCValue); Continue; end; token_closeround: begin Decl.LowBound := LB; Decl.HighBound := HB; Break; end; else AbortWork(sComaOrCloseRoundExpected, Lexer_PrevPosition); end; end; end; function TASTDelphiUnit.ParseBuiltinCall(Scope: TScope; CallExpr: TIDExpression; var EContext: TEContext): TTokenID; var LBuiltin: TIDBuiltInFunction; ArgsCount: Integer; Expr: TIDExpression; InnerEContext: TEContext; MacroID: TBuiltInFunctionID; SContext: TSContext; MacroParams: TIDParamArray; MParam: TIDVariable; i: Integer; ParamsBeginPos: Integer; ParamsBeginRow: Integer; ParamsText: string; Ctx: TSysFunctionContext; ASTExpr: TASTExpression; begin ArgsCount := 0; Result := Lexer_CurTokenID; SContext := EContext.SContext; LBuiltin := TIDBuiltInFunction(CallExpr.Declaration); // парсинг аргументов if Result = token_openround then begin ParamsBeginPos := Lexer.SourcePosition; ParamsBeginRow := Lexer.LinePosition.Row; InitEContext(InnerEContext, EContext.SContext, ExprNested); while True do begin Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, InnerEContext, ASTExpr); Expr := InnerEContext.Result; if Assigned(Expr) then begin {if Expr.DataType = Sys._Boolean then begin if (Expr.ItemType = itVar) and Expr.IsAnonymous then Bool_CompleteImmediateExpression(InnerEContext, Expr); end;} Inc(ArgsCount); EContext.RPNPushExpression(Expr); end else begin // Добавляем пустой Expression для значения по умолчанию if LBuiltin.ParamsCount > 0 then EContext.RPNPushExpression(nil); end; case Result of token_coma: begin InnerEContext.Reset; continue; end; token_closeround: begin ParamsText := Copy(Lexer.Source, ParamsBeginPos, Lexer.SourcePosition - ParamsBeginPos - 1); Result := Lexer_NextToken(Scope); Break; end; else ERRORS.INCOMPLETE_STATEMENT('call 2'); end; end; end else begin ParamsBeginRow := 0; end; if LBuiltin.FunctionID = bf_sysrtfunction then begin {set default param values} MacroParams := LBuiltin.ExplicitParams; for i := 0 to LBuiltin.ParamsCount - 1 do begin MParam := MacroParams[i]; if Assigned(MParam.DefaultValue) and (ArgsCount < LBuiltin.ParamsCount) then begin Inc(ArgsCount); EContext.RPNPushExpression(MParam.DefaultValue); end; end; {check args count} if LBuiltin.ParamsCount >= 0 then begin if ArgsCount > LBuiltin.ParamsCount then ERRORS.TOO_MANY_ACTUAL_PARAMS(CallExpr, LBuiltin.ParamsCount, ArgsCount) else if ArgsCount < LBuiltin.ParamsCount then ERRORS.NOT_ENOUGH_ACTUAL_PARAMS(CallExpr); end; end; Ctx.UN := Self; Ctx.Scope := Scope; Ctx.ParamsStr := ParamsText; Ctx.EContext := @EContext; Ctx.SContext := @SContext; Ctx.ArgsCount := ArgsCount; Ctx.ERRORS := ERRORS; MacroID := LBuiltin.FunctionID; case MacroID of bf_sysrtfunction: Expr := TIDSysRuntimeFunction(LBuiltin).Process(EContext); bf_sysctfunction: Expr := TIDSysCompileFunction(LBuiltin).Process(Ctx); else ERRORS.FEATURE_NOT_SUPPORTED; Expr := nil; end; if Assigned(Expr) then begin Expr.TextPosition := CallExpr.TextPosition; EContext.RPNPushExpression(Expr); end; end; function TASTDelphiUnit.ReadNewOrExistingID(Scope: TScope; out ID: TIDentifier; out Decl: TIDDeclaration): TTokenID; var SearchScope: TScope; FullID: string; PrevFoundUnitDeclID: string; UnitDecl: TIDUnit; begin Decl := nil; SearchScope := nil; while True do begin // read first ID Result := Lexer_NextToken(Scope); if (Result = token_identifier) or (Result = token_id_or_keyword) then begin Lexer_ReadCurrIdentifier(ID); if FullID = '' then FullID := ID.Name else FullID := FullID + '.' + ID.Name; // read next token, assuming "." Result := Lexer_NextToken(Scope); // search a declaration if SearchScope = nil then Decl := FindIDNoAbort(Scope, FullID) else Decl := SearchScope.FindMembers(FullID); if Result = token_dot then begin if Assigned(Decl) then begin case Decl.ItemType of itType: begin CheckStructType(TIDType(Decl)); SearchScope := TIDStructure(Decl).Members; FullID := ''; end; itUnit: begin SearchScope := TIDUnit(Decl).Members; PrevFoundUnitDeclID := FullID; FullID := ''; end; end; end else if PrevFoundUnitDeclID <> '' then begin FullID := PrevFoundUnitDeclID + '.' + FullID; Decl := FindIDNoAbort(Scope, FullID); if Assigned(Decl) and (Decl.ItemType = itUnit) then begin SearchScope := TIDUnit(Decl).Members; PrevFoundUnitDeclID := FullID; FullID := ''; end; end; Continue; end; end; if not Assigned(Decl) and (Pos('.', FullID) > 0) then ERRORS.UNDECLARED_ID(FullID, Lexer_Position); Exit; end; end; function TASTDelphiUnit.ParseExceptOnSection(Scope: TScope; KW: TASTKWTryBlock; const SContext: TSContext): TTokenID; var ID, VarID, TypeID: TIdentifier; Decl, VarDecl, TypeDecl: TIDDeclaration; VarExpr: TASTExpression; NewScope: TScope; Item: TASTExpBlockItem; NewSContext: TSContext; begin // try to parse... Result := ReadNewOrExistingID(Scope, {out} ID, {out} Decl); if Result = token_colon then begin NewScope := TScope.Create(stLocal, Scope); VarDecl := TIDVariable.Create(NewScope, ID); VarExpr := TASTExpression.Create(nil); VarExpr.AddDeclItem(VarDecl, Lexer_Position); InsertToScope(NewScope, VarDecl); Result := ReadNewOrExistingID(Scope, {out} TypeID, {out} TypeDecl); CheckExceptionType(TypeDecl); VarDecl.DataType := TypeDecl as TIDType; end else begin VarExpr := nil; // todo: CheckExceptionType(Decl); end; Lexer_MatchToken(Result, token_do); Item := KW.AddExceptBlock(VarExpr); NewSContext := SContext.MakeChild(Scope, Item.Body); Lexer_NextToken(Scope); Result := ParseStatements(NewScope, NewSContext, False); Lexer_MatchSemicolon(Result); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseWhileStatement(Scope: TScope; const SContext: TSContext): TTokenID; var Expression: TIDExpression; EContext: TEContext; BodySContext: TSContext; ASTExpr: TASTExpression; KW: TASTKWWhile; begin KW := SContext.Add(TASTKWWhile) as TASTKWWhile; // loop expression InitEContext(EContext, SContext, ExprRValue); Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, EContext, ASTExpr); KW.Expression := ASTExpr; Expression := EContext.Result; CheckEmptyExpression(Expression); if CheckImplicit(SContext, Expression, Sys._Boolean, {AResolveCalls:} True) = nil then CheckBooleanExpression(Expression); BodySContext := SContext.MakeChild(Scope, KW.Body); // loop body Lexer_MatchToken(Result, token_do); Result := Lexer_NextToken(Scope); if Result <> token_semicolon then Result := ParseStatements(Scope, BodySContext, False); end; function TASTDelphiUnit.ParseWithStatement(Scope: TScope; const SContext: TSContext): TTokenID; var Decl: TIDDeclaration; EContext: TEContext; Expression, Expr: TIDExpression; WNextScope: TWithScope; WPrevScope: TScope; BodySContext: TSContext; ASTExpr: TASTExpression; KW: TASTKWWith; begin WPrevScope := Scope; WNextScope := nil; KW := SContext.Add(TASTKWWith) as TASTKWWith; BodySContext := SContext.MakeChild(Scope, KW.Body); while True do begin Result := Lexer_NextToken(Scope); InitEContext(EContext, SContext, ExprRValue); Lexer_MatchToken(Result, token_identifier); Result := ParseExpression(Scope, SContext, EContext, ASTExpr); KW.AddExpression(ASTExpr); Expression := EContext.Result; CheckExprHasMembers(Expression); Decl := Expression.Declaration; // проверка на повторное выражение/одинаковый тип while Assigned(WNextScope) and (WNextScope.ScopeType = stWithScope) do begin Expr := WNextScope.Expression; if Expr.Declaration = Decl then AbortWork('Duplicate expression', Lexer_PrevPosition); if Expr.DataType = Decl.DataType then AbortWork('Duplicate expressions types', Lexer_PrevPosition); WNextScope := TWithScope(WNextScope.OuterScope); end; // создаем специальный "WITH Scope" WNextScope := TWithScope.Create(Scope, Expression); Scope.AddScope(WNextScope); WNextScope.OuterScope := WPrevScope; WNextScope.InnerScope := TIDStructure(Expression.DataType).Members; case Result of token_coma: begin WPrevScope := WNextScope; Continue; end; token_do: begin Lexer_NextToken(Scope); Result := ParseStatements(WNextScope, BodySContext, False); Break; end; else begin Lexer_MatchToken(Result, token_do); end; end; end; end; procedure TASTDelphiUnit.PostCompileChecks; begin for var AIndex := 0 to fForwardPtrTypes.Count - 1 do begin var APtrType := fForwardPtrTypes[AIndex]; // abort if reference type is not found GetPtrReferenceType(APtrType); end; end; function TASTDelphiUnit.Process_CALL(var EContext: TEContext): TIDExpression; var PIndex, AIndex, ArgsCount, ParamsCount: Integer; PExpr: TIDCallExpression; UserArguments, CallArguments: TIDExpressions; ProcParams: TIDParamArray; Decl: TIDDeclaration; ResVar: TIDVariable; ProcDecl: TIDProcedure; ProcResult: TIDType; Param: TIDVariable; AExpr, NewExpr: TIDExpression; SContext: PSContext; begin SContext := @EContext.SContext; // читаем декларацию функции PExpr := TIDCallExpression(EContext.RPNPopExpression()); {вычитка явно указанных аргументов функции} ArgsCount := PExpr.ArgumentsCount; SetLength(UserArguments, ArgsCount); for AIndex := ArgsCount - 1 downto 0 do UserArguments[AIndex] := EContext.RPNPopExpression(); ProcDecl := nil; Decl := PExpr.Declaration; {прямой вызов} if Decl.ItemType = itProcedure then begin ProcDecl := TIDProcedure(Decl); if Assigned(ProcDecl.GenericDescriptor) and not Assigned(SContext.Proc.GenericDescriptor) and not IsGenericTypeThisStruct(SContext.Scope, ProcDecl.Struct) then begin ProcDecl := SpecializeGenericProc(PExpr, UserArguments); ProcParams := ProcDecl.ExplicitParams; PExpr.Declaration := ProcDecl; end; {поиск подходящей декларации} if Assigned(ProcDecl.PrevOverload) then begin ProcDecl := MatchOverloadProc(EContext.SContext, PExpr, UserArguments, ArgsCount); ProcParams := ProcDecl.ExplicitParams; PExpr.Declaration := ProcDecl; end else begin ProcParams := ProcDecl.ExplicitParams; MatchProc(EContext.SContext, PExpr, ProcParams, UserArguments); end; ProcResult := ProcDecl.ResultType; end else {вызов через переменную процедурного типа} if PExpr.DataTypeID = dtProcType then begin Decl := PExpr.DataType; ProcParams := TIDProcType(Decl).Params; ProcResult := TIDProcType(Decl).ResultType; MatchProc(EContext.SContext, PExpr, ProcParams, UserArguments); end else begin AbortWorkInternal(sProcOrProcVarRequired, Lexer_Position); ProcResult := nil; end; ParamsCount := Length(ProcParams); {если все аргументы явно указаны} if ParamsCount = ArgsCount then begin for AIndex := 0 to ParamsCount - 1 do begin Param := ProcParams[AIndex]; AExpr := UserArguments[AIndex]; {если аргумент константый дин. массив то делаем доп. проверку} //if AExpr.Declaration is TIDDynArrayConstant then // AExpr := CheckConstDynArray(SContext, Param.DataType, AExpr); {проверка диаппазона для константных аргументов} if AExpr.IsConstant then CheckConstValueOverflow(AExpr, Param.DataType); {подбираем implicit оператор} AExpr := MatchImplicit3(SContext^, AExpr, Param.DataType); {если параметр - constref и аргумент - константа, то создаем временную переменную} //if (VarConstRef in Param.Flags) and (AExpr.ItemType = itConst) then // AExpr := GenConstToVar(SContext, AExpr, Param.DataType); {если параметр - метод, получаем ссылку на него} if (AExpr.ItemType = itProcedure) and (not TIDProcType(AExpr.DataType).IsStatic) then begin NewExpr := GetTMPVarExpr(SContext^, AExpr.DataType, AExpr.TextPosition); AExpr := NewExpr; end; UserArguments[AIndex] := AExpr; end; CallArguments := UserArguments; end else {если некоторые аргументы опущены} begin AIndex := 0; PIndex := 0; SetLength(CallArguments, ParamsCount); while (PIndex < ParamsCount) do begin Param := ProcParams[PIndex]; if AIndex < ArgsCount then begin AExpr := UserArguments[AIndex]; Inc(AIndex); end else AExpr := nil; {подстановка аргуметов по умолчанию} if Assigned(AExpr) then CallArguments[PIndex] := AExpr else begin AExpr := Param.DefaultValue; if not Assigned(AExpr) then ERRORS.NOT_ENOUGH_ACTUAL_PARAMS(PExpr); CallArguments[PIndex] := AExpr; end; {если аргумент константый дин. массив то делаем доп. проверку} //if AExpr.Declaration is TIDDynArrayConstant then // AExpr := CheckConstDynArray(SContext, Param.DataType, AExpr); // нужно ли???? {проверка диаппазона для константных аргументов} if AExpr.IsConstant then CheckConstValueOverflow(AExpr, Param.DataType); {подбираем implicit оператор} AExpr := MatchImplicit3(SContext^, AExpr, Param.DataType); {если параметр - constref и аргумент - константа, то создаем временную переменную} //if (VarConstRef in Param.Flags) and (AExpr.ItemType = itConst) then // AExpr := GenConstToVar(SContext, AExpr, Param.DataType); {если параметр - метод, получаем ссылку на него} if (AExpr.ItemType = itProcedure) and (not TIDProcType(AExpr.DataType).IsStatic) then begin NewExpr := GetTMPVarExpr(SContext^, AExpr.DataType, AExpr.TextPosition); AExpr := NewExpr; end; CallArguments[PIndex] := AExpr; Inc(PIndex); {если параметр передается по ссылке, проверяем что аргумент можно менять} if Param.VarReference then begin CheckVarExpression(AExpr, vmpPassArgument); {проверка на строгость соответствия типов} if Param.DataType.ActualDataType <> AExpr.DataType.ActualDataType then ERRORS.REF_PARAM_MUST_BE_IDENTICAL(AExpr); end; end; end; {конструирование обьекта} if (Assigned(ProcDecl) and (pfConstructor in ProcDecl.Flags)) then begin Result := process_CALL_constructor(EContext.SContext, PExpr, CallArguments); Exit; end; {результат функции} if Assigned(ProcResult) then begin ResVar := GetTMPVar(SContext^, ProcResult); ResVar.IncludeFlags([VarTmpResOwner]); Result := TIDExpression.Create(ResVar, PExpr.TextPosition); end else Result := nil; {если вызов был коссвенным, инлайн невозможен} Decl := PExpr.Declaration; if Decl.ItemType = itVar then begin {если переменная - поле класа, получаем ссылку на поле} // Exit; end; {INLINE подстановка (пока только если инлайн процедура готова)} if (pfInline in ProcDecl.Flags) and (ProcDecl.IsCompleted) and (ProcDecl <> SContext.Proc) then begin // todo: end else begin // todo: end; end; function TASTDelphiUnit.Process_CALL_direct(const SContext: TSContext; PExpr: TIDCallExpression; CallArguments: TIDExpressions): TIDExpression; var AIndex, ArgsCount: Integer; ProcDecl: TIDProcedure; ProcParams: TIDParamArray; ResVar: TIDVariable; ProcResult: TIDType; Param: TIDVariable; AExpr: TIDExpression; begin ArgsCount := Length(CallArguments); ProcDecl := PExpr.AsProcedure; ProcParams := ProcDecl.ExplicitParams; if Assigned(ProcDecl.GenericDescriptor) then begin ProcDecl := SpecializeGenericProc(PExpr, CallArguments); ProcParams := ProcDecl.ExplicitParams; PExpr.Declaration := ProcDecl; end; if Length(ProcParams) < ArgsCount then AbortWorkInternal('Ivalid proc call: %s', [PExpr.Text], PExpr.TextPosition); {если все аргументы явно указаны} for AIndex := 0 to ArgsCount - 1 do begin Param := ProcParams[AIndex]; AExpr := CallArguments[AIndex]; {если аргумент константый дин. массив то делаем доп. проверку} // if AExpr.Declaration is TIDDynArrayConstant then // AExpr := CheckConstDynArray(SContext, Param.DataType, AExpr); {проверка диаппазона для константных аргументов} if AExpr.IsConstant then CheckConstValueOverflow(AExpr, Param.DataType); {подбираем и если надо вызываем implicit оператор} AExpr := MatchImplicit3(SContext, AExpr, Param.DataType); {если параметр - constref и аргумент - константа, то создаем временную переменную} // if (VarConstRef in Param.Flags) and (AExpr.ItemType = itConst) then // AExpr := GenConstToVar(AExpr, Param.DataType); CallArguments[AIndex] := AExpr; // if Param.Reference then // CheckVarExpression(AExpr, vmpPassArgument); end; {результат функции} ProcResult := ProcDecl.ResultType; if Assigned(ProcResult) then begin ResVar := GetTMPVar(SContext, ProcResult); ResVar.IncludeFlags([VarTmpResOwner]); Result := TIDExpression.Create(ResVar, PExpr.TextPosition); end else Result := nil; end; function TASTDelphiUnit.process_CALL_constructor(const SContext: TSContext; CallExpression: TIDCallExpression; const CallArguments: TIDExpressions): TIDExpression; var Proc: TIDProcedure; ResVar: TIDVariable; begin Proc := CallExpression.AsProcedure; ResVar := GetTMPVar(SContext, Proc.Struct); Result := TIDExpression.Create(ResVar, CallExpression.TextPosition); end; function GetOperatorInstance(Op: TOperatorID; Left, Right: TIDExpression): TIDExpression; var LDT, RDT: TIDType; Decl: TIDDeclaration; begin LDT := Left.DataType.ActualDataType; RDT := Right.DataType.ActualDataType; // поиск оператора (у левого операнда) Decl := LDT.BinarOperator(Op, RDT); if Assigned(Decl) then Exit(Left); // поиск оператора (у правого операнда) Decl := RDT.BinarOperatorFor(Op, LDT); if Assigned(Decl) then Exit(Right); Result := nil end; function TASTDelphiUnit.Defined(const Name: string): Boolean; begin // поиск в локальном списке модуля Result := FDefines.IndexOf(Name) > -1; // поиск в пакете if not Result then Result := FPackage.Defines.IndexOf(Name) > -1; end; destructor TASTDelphiUnit.Destroy; begin fForwardPtrTypes.Free; fCache.Free; fDefines.Free; fOptions.Free; fErrors.Free; inherited; end; function TASTDelphiUnit.DoMatchBinarOperator(const SContext: TSContext; OpID: TOperatorID; var Left, Right: TIDExpression): TIDDeclaration; begin if OpID in [opShiftLeft, opShiftRight] then Result := MatchBinarOperator(SContext, OpID, Left, Left) else Result := MatchBinarOperator(SContext, OpID, Left, Right); if not Assigned(Result) then Result := MatchBinarOperatorWithImplicit(SContext, OpID, Left, Right); end; function TASTDelphiUnit.EmitCreateClosure(const SContext: TSContext; Closure: TIDClosure): TIDExpression; begin end; function TASTDelphiUnit.MatchBinarOperatorWithTuple(const SContext: TSContext; Op: TOperatorID; var CArray: TIDExpression; const SecondArg: TIDExpression): TIDDeclaration; var DataType: TIDType; begin Result := nil; DataType := SecondArg.DataType; if DataType.DataTypeID = dtSet then begin CArray := MatchSetImplicit(SContext, CArray, DataType as TIDSet); Result := Sys._Boolean; // tmp надо проверять оператор end; end; class function TASTDelphiUnit.CheckConstDynArrayImplicit(const SContext: TSContext; Source: TIDExpression; Destination: TIDType): TIDType; var i, ArrayLen: Integer; SConst: TIDDynArrayConstant; SExpr: TIDExpression; DstElementDataType: TIDType; ImplicitCast: TIDDeclaration; SrcArrayElement: TIDType; begin SConst := TIDDynArrayConstant(Source.Declaration); ArrayLen := Length(SConst.Value); // exit if this is just empty array "[]" if ArrayLen = 0 then Exit(Destination); case Destination.DataTypeID of dtSet: begin DstElementDataType := TIDSet(Destination).BaseType; end; dtOpenArray: begin if TIDArray(Destination).IsOpenArrayOfConst then Exit(Destination); DstElementDataType := TIDDynArray(Destination).ElementDataType; end; dtDynArray: begin DstElementDataType := TIDDynArray(Destination).ElementDataType; end; else Exit(nil); end; // проверка каждого элемента for i := 0 to ArrayLen - 1 do begin SExpr := SConst.Value[i]; ImplicitCast := CheckImplicit(SContext, SExpr, DstElementDataType, {AResolveCalls:} True); if not Assigned(ImplicitCast) then Exit(nil); end; Result := Destination; end; class function TASTDelphiUnit.MatchDynArrayImplicit(Source: TIDExpression; Destination: TIDType): TIDType; var SrcDataType: TIDArray; begin if (Destination.DataTypeID in [dtDynArray, dtOpenArray]) and (Source.DataTypeID = Destination.DataTypeID) then begin SrcDataType := TIDArray(Source.DataType); if SrcDataType.ElementDataType.ActualDataType = TIDArray(Destination).ElementDataType.ActualDataType then Exit(Destination); end; Result := nil; end; function TASTDelphiUnit.FindBinaryOperator(const SContext: TSContext; OpID: TOperatorID; var Left, Right: TIDExpression): TIDDeclaration; var WasCall: Boolean; begin Result := DoMatchBinarOperator(SContext, OpID, Left, Right); if not Assigned(Result) then begin // if there is no operator found, let's assume that the left operand can be a function... Left := CheckAndCallFuncImplicit(SContext, Left, WasCall); if WasCall then Result := DoMatchBinarOperator(SContext, OpID, Left, Right); if not Assigned(Result) then begin // if there is no operator found, let's assume that the right operand can be a function... Right := CheckAndCallFuncImplicit(SContext, Right, WasCall); if WasCall then Result := FindBinaryOperator(SContext, OpID, Left, Right); end; if not Assigned(Result) then ERRORS.NO_OVERLOAD_OPERATOR_FOR_TYPES(OpID, Left, Right); end; end; function GetImplicitFactor(ASrcType, ADestType: TIDType): Integer; begin if (ASrcType = ADestType) then Result := MaxInt8 else ImplicitFactor2(ASrcType.DataTypeID, ADestType.DataTypeID); end; function TASTDelphiUnit.FindImplicitFormBinarOperators(const Operators: TBinaryOperatorsArray; const Left, Right: TIDType; out LLeftImplicitCast: TIDDeclaration; out LRightrImplicitCast: TIDDeclaration; out BetterFactor: Integer): TIDDeclaration; begin Result := nil; var LBetterFactor := 0; for var AIndex := 0 to Length(Operators) - 1 do begin var LItemPtr := PBinaryOperator(@Operators[AIndex]); LLeftImplicitCast := MatchImplicit({Source:} Left, {Destination:} LItemPtr.Left); LRightrImplicitCast := MatchImplicit({Source:} Right, {Destination:} LItemPtr.Right); if Assigned(LLeftImplicitCast) and Assigned(LRightrImplicitCast) then begin var LLeftImplicitFactor := GetImplicitFactor(Left, LItemPtr.Left); var LRightImplicitFactor := GetImplicitFactor(Right, LItemPtr.Right); var LMinCommonFactor := Min(LLeftImplicitFactor, LRightImplicitFactor); if LMinCommonFactor > LBetterFactor then begin BetterFactor := LBetterFactor; Result := LItemPtr.OpDecl; end; end; end; end; function TASTDelphiUnit.Process_operators(var EContext: TEContext; OpID: TOperatorID): TIDExpression; var Left, Right: TIDExpression; Op: TIDDeclaration; TmpVar: TIDVariable; begin Result := nil; case OpID of opAssignment: Process_operator_Assign(EContext); opNegative: Result := Process_operator_neg(EContext); opNot: Result := Process_operator_not(EContext); opPositive: Result := EContext.RPNPopExpression; opDereference: Result := Process_operator_Deref(EContext); opCall: Result := Process_CALL(EContext); opPeriod: Result := Process_operator_Period(EContext); opAddr: Result := Process_operator_Addr(EContext); opIs: Result := Process_operator_Is(EContext); opAs: Result := Process_operator_As(EContext); else begin // Читаем первый операнд Right := EContext.RPNPopExpression(); // Читаем второй операнд Left := EContext.RPNPopExpression(); Op := FindBinaryOperator(EContext.SContext, OpID, Left, Right); // если аргументы - константы, производим константные вычисления if Left.IsConstant and Right.IsConstant then begin Result := fCCalc.ProcessConstOperation(Left, Right, OpID); Exit; end else begin if Op is TSysOpBinary then begin Result := TSysOpBinary(Op).Match(EContext.SContext, Left, Right); if Result = nil then ERRORS.NO_OVERLOAD_OPERATOR_FOR_TYPES(OpID, Left, Right); end else begin TmpVar := GetTMPVar(EContext, TIDType(Op)); Result := TIDExpression.Create(TmpVar, Left.TextPosition); end; end; if Op.ItemType = itType then begin case OpID of opAdd: begin // если результат строка или дин. массив - помечаем переменную if Result.DataTypeID in [dtDynArray, dtString, dtAnsiString] then Result.AsVariable.IncludeFlags([VarTmpResOwner]); end; opSubtract: ;//ILWrite(SContext, TIL.IL_Sub(Result, Left, Right)); opMultiply: ;//ILWrite(SContext, TIL.IL_Mul(Result, Left, Right)); opDivide: ;//ILWrite(SContext, TIL.IL_Div(Result, Left, Right)); opIntDiv: ;//ILWrite(SContext, TIL.IL_IntDiv(Result, Left, Right)); opModDiv: ;//ILWrite(SContext, TIL.IL_ModDiv(Result, Left, Right)); opEqual, opNotEqual, opLess, opLessOrEqual, opGreater, opGreaterOrEqual: begin Result := AST.Delphi.Classes.GetBoolResultExpr(Result); //ILWrite(SContext, TIL.IL_Cmp(Left, Right)); {освобожадем временные переменные} //ReleaseExpression(SContext, Left); //ReleaseExpression(SContext, Right); //ILWrite(SContext, TIL.IL_JmpNext(Left.Line, cNone, nil)); //Bool_AddExprNode(EContext, SContext.ILLast, TILCondition(Ord(OpID) - Ord(opEqual) + 1)); Exit; end; opIn: Result := Process_operator_In(EContext, Left, Right); opAnd, opOr, opXor, opShiftLeft, opShiftRight: begin if (OpID in [opAnd, opOr]) and (TmpVar.DataType = Sys._Boolean) then begin // логические операции Result := AST.Delphi.Classes.GetBoolResultExpr(Result); //Process_operator_logical_AND_OR(EContext, OpID, Left, Right, Result); end; end; else ERRORS.UNSUPPORTED_OPERATOR(OpID); end; end else if Op.ItemType = itProcedure then begin // вызов перегруженного бинарного оператора Result := TIDCallExpression.Create(Op); Result.TextPosition := Left.TextPosition; TIDCallExpression(Result).ArgumentsCount := 2; TIDCallExpression(Result).Instance := GetOperatorInstance(OpID, Left, Right); Result := Process_CALL_direct(EContext.SContext, TIDCallExpression(Result), TIDExpressions.Create(Left, Right)); end; end; end; end; function TASTDelphiUnit.Process_operator_Addr(var EContext: TEContext): TIDExpression; var Expr: TIDExpression; TmpDecl: TIDVariable; DataType: TIDType; begin Expr := EContext.RPNPopExpression(); DataType := Expr.DataType.DefaultReference; if DataType = nil then begin DataType := Expr.DataType.GetDefaultReference(ImplScope); AddType(DataType); end; if Expr.IsConstant and (Expr.DataTypeID in [dtString, dtAnsiString]) then begin // resourcestring -> PResStringRec support var LConst := TIDPointerConstant.CreateAsAnonymous(IntfScope, Sys._ResStringRecord, Expr.AsConst); Result := TIDExpression.Create(LConst, Expr.TextPosition); end else if Expr.IsTMPVar and Expr.AsVariable.Reference then begin Result := GetTMPVarExpr(EContext.SContext, DataType, Expr.TextPosition); Result.AsVariable.Absolute := Expr.AsVariable; end else begin TmpDecl := GetTMPVar(EContext.SContext, DataType); Result := TIDExpression.Create(TmpDecl, Expr.TextPosition); end; end; function TASTDelphiUnit.Process_operator_As(var EContext: TEContext): TIDExpression; var Src, Dst: TIDExpression; begin Dst := EContext.RPNPopExpression(); Src := EContext.RPNPopExpression(); CheckClassOrIntfType(Src.DataType, Src.TextPosition); CheckClassOrClassOfOrIntfType(Dst); Result := GetTMPVarExpr(EContext, Dst.AsType, Dst.TextPosition); end; procedure TASTDelphiUnit.Process_operator_Assign(var EContext: TEContext); function IsSameRef(const Dst, Src: TIDExpression): Boolean; begin if Src.ItemType = itVar then Result := Dst.AsVariable.Reference = Src.AsVariable.Reference else Result := False; end; begin var Source := EContext.RPNPopExpression; var Dest := EContext.RPNPopExpression; {check Implicit} var NewSrc := MatchImplicit3(EContext.SContext, Source, Dest.DataType, {AAbortIfError:} False); if not Assigned(NewSrc) then begin // a case when the current function name is used as the result variable var LCurrentProc := EContext.SContext.Proc; if (Dest.Declaration = LCurrentProc) and Assigned(LCurrentProc.ResultType) then begin MatchImplicit3(EContext.SContext, Source, LCurrentProc.ResultType); end else ERRORS.INCOMPATIBLE_TYPES(Source, Dest); end else CheckVarExpression(Dest, vmpAssignment); end; function TASTDelphiUnit.Process_operator_Deref(var EContext: TEContext): TIDExpression; var Src: TIDExpression; PtrType: TIDPointer; RefType: TIDType; AWasCall: Boolean; begin Src := EContext.RPNPopExpression(); Src := CheckAndCallFuncImplicit(EContext, Src); CheckPointerType(Src); PtrType := Src.DataType as TIDPointer; RefType := GetPtrReferenceType(PtrType); if not Assigned(RefType) then RefType := Sys._Untyped; Result := GetTMPVarExpr(EContext, RefType, Src.TextPosition); end; function TASTDelphiUnit.Process_operator_dot(var EContext: TEContext): TIDExpression; begin end; function TASTDelphiUnit.Process_operator_In(var EContext: TEContext; const Left, Right: TIDExpression): TIDExpression; begin Result := TIDExpression.Create(GetTMPVar(EContext, Sys._Boolean)); end; function TASTDelphiUnit.Process_operator_Is(var EContext: TEContext): TIDExpression; var Src, Dst: TIDExpression; begin Dst := EContext.RPNPopExpression(); Src := EContext.RPNPopExpression(); Src := CheckAndCallFuncImplicit(EContext, Src); CheckClassOrIntfType(Src.DataType, Src.TextPosition); CheckClassOrClassOfOrIntfType(Dst); Result := GetTMPVarExpr(EContext, Sys._Boolean, Dst.TextPosition); end; function TASTDelphiUnit.Process_operator_neg(var EContext: TEContext): TIDExpression; var Right: TIDExpression; OperatorItem: TIDExpression; begin // Читаем операнд Right := EContext.RPNPopExpression(); OperatorItem := MatchUnarOperator(EContext.SContext, opNegative, Right); if not Assigned(OperatorItem) then ERRORS.NO_OVERLOAD_OPERATOR_FOR_TYPES(opNegative, Right); if Right.ItemType = itConst then Result := fCCalc.ProcessConstOperation(Right, Right, opNegative) else begin Result := GetTMPVarExpr(EContext, OperatorItem.DataType, Right.TextPosition); end; end; function TASTDelphiUnit.Process_operator_not(var EContext: TEContext): TIDExpression; var Right, OperatorItem: TIDExpression; DataType: TIDType; begin // Читаем операнд Right := EContext.RPNPopExpression(); OperatorItem := MatchUnarOperator(EContext.SContext, opNot, Right); if not Assigned(OperatorItem) then ERRORS.NO_OVERLOAD_OPERATOR_FOR_TYPES(opNot, Right); if Right.ItemType = itConst then Result := fCCalc.ProcessConstOperation(Right, Right, opNot) else begin var WasCall := False; Right := CheckAndCallFuncImplicit(EContext.SContext, Right, WasCall); // если это просто выражение (not Bool_Value) if (Right.DataTypeID = dtBoolean) then begin var TmpVar := GetTMPVar(EContext, Sys._Boolean); Result := TIDBoolResultExpression.Create(TmpVar, Lexer_Position); end else Result:= GetTMPVarExpr(EContext, Right.DataType, Lexer_Position); end; end; function TASTDelphiUnit.Process_operator_Period(var EContext: TEContext): TIDExpression; var ValueType: TIDDeclaration; RangeType: TIDRangeType; Decl: TIDDeclaration; LB, HB: TIDExpression; SRValue: TSubRangeRecord; begin HB := EContext.RPNPopExpression(); LB := EContext.RPNPopExpression(); CheckEmptyExpression(LB); CheckEmptyExpression(HB); CheckConstExpression(LB); CheckConstExpression(HB); CheckOrdinalExpression(LB); CheckOrdinalExpression(HB); ValueType := MatchImplicit(LB.DataType, HB.DataType); if not Assigned(ValueType) then AbortWork(sTypesMustBeIdentical, HB.TextPosition); // search in the cache first RangeType := fCache.FindRange(ValueType as TIDType, LB, HB); if not Assigned(RangeType) then begin RangeType := TIDRangeType.CreateAsAnonymous(IntfScope); RangeType.BaseType := ValueType as TIDOrdinal; RangeType.LoDecl := LB.AsConst; RangeType.HiDecl := HB.AsConst; fCache.Add(RangeType); AddType(RangeType); end; if LB.IsConstant and HB.IsConstant then begin if TIDConstant(LB.Declaration).CompareTo(TIDConstant(HB.Declaration)) > 0 then AbortWork(sLowerBoundExceedsHigherBound, HB.TextPosition); end; SRValue.LBExpression := LB; SRValue.HBExpression := HB; Decl := TIDRangeConstant.CreateAsAnonymous(IntfScope, RangeType, SRValue); Result := TIDExpression.Create(Decl, HB.TextPosition); end; procedure TASTDelphiUnit.CheckIncompletedProcs(ProcSpace: PProcSpace); begin // inherited; end; procedure TASTDelphiUnit.CheckLabelExpression(const Expr: TIDExpression); begin if Expr.ItemType <> itLabel then AbortWork('LABEL required', Expr.TextPosition); end; procedure TASTDelphiUnit.CheckLabelExpression(const Decl: TIDDeclaration); begin if Decl.ItemType <> itLabel then AbortWork('LABEL required', Lexer_Position); end; function TASTDelphiUnit.Compile(ACompileIntfOnly: Boolean; RunPostCompile: Boolean): TCompilerResult; var Token: TTokenID; Scope: TScope; begin try if UnitState = UnitNotCompiled then begin fTotalLinesParsed := 0; Progress(TASTStatusParseBegin); Result := inherited Compile(RunPostCompile); fSysDecls := TSYSTEMUnit(SysUnit).SystemDeclarations; fCCalc := TExpressionCalculator.Create(Self); Package.DoBeforeCompileUnit(Self); Messages.Clear; FRCPathCount := 1; Lexer.First; Scope := IntfScope; ParseUnitDecl(Scope); end else if UnitState = UnitIntfCompiled then begin Scope := ImplScope; end else AbortWorkInternal('Invalid unit state'); Token := Lexer_NextToken(Scope); while true do begin case Token of token_type: begin CheckIntfSectionMissing(Scope); Token := ParseNamedTypeDecl(Scope); end; token_asm: begin CheckIntfSectionMissing(Scope); Token := ParseAsmSpecifier(); case Token of token_function: Token := ParseProcedure(Scope, ptFunc); token_procedure: Token := ParseProcedure(Scope, ptProc); else ERRORS.FEATURE_NOT_SUPPORTED; end; end; token_uses: Token := ParseUsesSection(Scope); token_function: begin CheckIntfSectionMissing(Scope); Token := ParseProcedure(Scope, ptFunc); end; token_procedure: begin CheckIntfSectionMissing(Scope); Token := ParseProcedure(Scope, ptProc); end; token_constructor: begin CheckIntfSectionMissing(Scope); Token := ParseProcedure(Scope, ptConstructor); end; token_destructor: begin CheckIntfSectionMissing(Scope); Token := ParseProcedure(Scope, ptDestructor); end; token_const: begin CheckIntfSectionMissing(Scope); Token := ParseConstSection(Scope); end; token_resourcestring: begin CheckIntfSectionMissing(Scope); // todo: parse resourcestring Token := ParseConstSection(Scope); end; token_class: begin CheckIntfSectionMissing(Scope); Token := Lexer_NextToken(Scope); case Token of token_function: Token := ParseProcedure(Scope, ptClassFunc); token_procedure: Token := ParseProcedure(Scope, ptClassProc); token_constructor: Token := ParseProcedure(Scope, ptClassConstructor); token_destructor: Token := ParseProcedure(Scope, ptClassDestructor); token_operator: Token := ParseOperator(Scope, nil); else ERRORS.FEATURE_NOT_SUPPORTED(Lexer_TokenLexem(Token)); end; end; // token_weak: begin // CheckIntfSectionMissing(Scope); // Lexer_NextToken(Scope); // Token := ParseVarSection(Scope, vLocal, True); // end; token_var: begin CheckIntfSectionMissing(Scope); Lexer_NextToken(Scope); Token := ParseVarSection(Scope, vLocal, False); end; token_threadvar: begin CheckIntfSectionMissing(Scope); Lexer_NextToken(Scope); Token := ParseVarSection(Scope, vLocal, False); end; token_exports: begin // todo: Token := Lexer_SkipTo(Scope, token_semicolon); Token := Lexer_NextToken(Scope); end; token_interface: begin Scope := IntfScope; Token := Lexer_NextToken(Scope); end; token_implementation: begin CheckIntfSectionMissing(Scope); fUnitState := UnitIntfCompiled; if ACompileIntfOnly then begin Package.DoFinishCompileUnit(Self, {AIntfOnly:} True); Progress(TASTStatusParseIntfSucess); Result := CompileSuccess; Exit; end; Scope := ImplScope; Token := Lexer_NextToken(Scope); end; token_end: begin Lexer_MatchToken(Lexer_NextToken(Scope), token_dot); Token := Lexer_NextToken(Scope); if Token <> token_eof then ERRORS.HINT_TEXT_AFTER_END; Break; end; token_initialization: Token := ParseInitSection; token_finalization: Token := ParseFinalSection; token_eof: Break; else if Token >= token_cond_define then begin Token := ParseCondStatements(Scope, Token); continue; end; ERRORS.KEYWORD_EXPECTED; end; end; PostCompileChecks; fUnitState := UnitAllCompiled; Result := CompileSuccess; FCompiled := Result; Progress(TASTStatusParseSuccess); Package.DoFinishCompileUnit(Self, {AIntfOnly:} False); except on e: ECompilerStop do Exit(); on e: ECompilerSkip do Exit(CompileSkip); on e: ECompilerAbort do begin PutMessage(ECompilerAbort(e).CompilerMessage^); Progress(TASTStatusParseFail); Result := CompileFail; end; on e: Exception do begin PutMessage(cmtInteranlError, e.Message, Lexer_Position); Progress(TASTStatusParseFail); Result := CompileFail; end; end; end; function TASTDelphiUnit.CompileIntfOnly: TCompilerResult; begin Result := Compile({ACompileIntfOnly:} True); end; function TASTDelphiUnit.CompileSource(Scope: TScope; const FileName: string; const Source: string): ICompilerMessages; var ParserState: TParserPosition; ParserSource: string; Token: TTokenID; begin Result := Messages; Lexer.SaveState(ParserState); ParserSource := Lexer.Source; fIncludeFilesStack.Push(FileName); try try Lexer.Source := Source; Lexer.First; Token := Lexer_NextToken(Scope); while true do begin case Token of token_type: begin CheckIntfSectionMissing(Scope); Token := ParseNamedTypeDecl(Scope); end; token_uses: Token := ParseUsesSection(Scope); token_function: begin CheckIntfSectionMissing(Scope); Token := ParseProcedure(Scope, ptFunc); end; token_procedure: begin CheckIntfSectionMissing(Scope); Token := ParseProcedure(Scope, ptProc); end; //token_namespace: Token := ParseNameSpace(Scope); token_constructor: begin CheckIntfSectionMissing(Scope); Token := ParseProcedure(Scope, ptConstructor); end; token_destructor: begin CheckIntfSectionMissing(Scope); Token := ParseProcedure(Scope, ptDestructor); end; token_operator: begin CheckIntfSectionMissing(Scope); Token := ParseOperator(Scope, nil); end; token_const: begin CheckIntfSectionMissing(Scope); Token := ParseConstSection(Scope); end; token_class: begin CheckIntfSectionMissing(Scope); Token := Lexer_NextToken(Scope); case Token of token_function: Token := ParseProcedure(Scope, ptClassFunc); token_procedure: Token := ParseProcedure(Scope, ptClassProc); token_constructor: Token := ParseProcedure(Scope, ptClassConstructor); token_destructor: Token := ParseProcedure(Scope, ptClassDestructor); else ERRORS.FEATURE_NOT_SUPPORTED; end; end; token_weak: begin CheckIntfSectionMissing(Scope); Lexer_NextToken(Scope); Token := ParseVarSection(Scope, vLocal, True); end; token_var: begin CheckIntfSectionMissing(Scope); Lexer_NextToken(Scope); Token := ParseVarSection(Scope, vLocal, False); end; token_interface: begin Scope := IntfScope; Token := Lexer_NextToken(Scope); end; token_implementation: begin CheckIntfSectionMissing(Scope); Scope := ImplScope; Token := Lexer_NextToken(Scope); end; token_end: begin Lexer_MatchToken(Lexer_NextToken(Scope), token_dot); Token := Lexer_NextToken(Scope); if Token <> token_eof then ERRORS.HINT_TEXT_AFTER_END; Break; end; token_initialization: Token := ParseInitSection; token_finalization: Token := ParseFinalSection; token_eof: Break; else if Token >= token_cond_define then begin Token := ParseCondStatements(Scope, Token); continue; end; ERRORS.KEYWORD_EXPECTED; end; end; except on e: ECompilerAbort do PutMessage(ECompilerAbort(e).CompilerMessage^); on e: Exception do PutMessage(cmtInteranlError, e.Message, Lexer_Position); end; finally Lexer.Source := ParserSource; Lexer.LoadState(ParserState); fIncludeFilesStack.Pop; end; end; class function TASTDelphiUnit.ConstDynArrayToSet(const SContext: TSContext; const CDynArray: TIDExpression; TargetSetType: TIDSet): TIDExpression; var i: Integer; CArray: TIDDynArrayConstant; SExpr: TIDExpression; ImplicitCast: TIDDeclaration; ItemType: TIDType; ItemValue, SetValue: Int64; begin SetValue := 0; CArray := CDynArray.AsDynArrayConst; ItemType := TargetSetType.BaseType; Assert(CArray.ArrayLength <= 64); for i := 0 to CArray.ArrayLength - 1 do begin SExpr := CArray.Value[i]; ImplicitCast := CheckImplicit(SContext, SExpr, ItemType); if not Assigned(ImplicitCast) then SContext.ERRORS.INCOMPATIBLE_TYPES(SExpr, ItemType); ItemValue := SExpr.AsIntConst.Value; SetValue := SetValue or (1 shl ItemValue); end; Result := IntConstExpression(SContext, SetValue); Result.TextPosition := CDynArray.TextPosition; end; class function TASTDelphiUnit.MatchSetImplicit(const SContext: TSContext; Source: TIDExpression; Destination: TIDSet): TIDExpression; var i: Integer; CArray: TIDDynArrayConstant; SExpr: TIDExpression; ImplicitCast: TIDDeclaration; EnumDecl: TIDType; ItemValue, SetValue: Int64; begin SetValue := 0; EnumDecl := Destination.BaseType; CArray := Source.AsDynArrayConst; for i := 0 to CArray.ArrayLength - 1 do begin SExpr := CArray.Value[i]; ImplicitCast := CheckImplicit(SContext, SExpr, EnumDecl); if not Assigned(ImplicitCast) then SContext.ERRORS.INCOMPATIBLE_TYPES(SExpr, EnumDecl); ItemValue := SExpr.AsIntConst.Value; SetValue := SetValue or (1 shl ItemValue); end; var Scope := TASTDelphiUnit(SContext.Module).ImplScope; Result := TIDExpression.Create(TIDIntConstant.CreateAsAnonymous(Scope, SContext.SysUnit._Int32, SetValue), Source.TextPosition); end; function TASTDelphiUnit.GetCurrentParsedFileName(OnlyFileName: Boolean): string; begin if fIncludeFilesStack.Count > 0 then Result := fIncludeFilesStack.Top else Result := FileName; if OnlyFileName then Result := ExtractFileName(Result); end; function TASTDelphiUnit.GetErrors: TASTDelphiErrors; begin Result := fErrors; end; function TASTDelphiUnit.GetFirstConst: TASTDeclaration; begin Result := nil; end; function TASTDelphiUnit.GetFirstFunc: TASTDeclaration; begin Result := ProcSpace.First; end; function TASTDelphiUnit.GetFirstType: TASTDeclaration; begin Result := TypeSpace.First; end; function TASTDelphiUnit.GetFirstVar: TASTDeclaration; begin Result := VarSpace.First; end; procedure TASTDelphiUnit.EnumAllDeclarations(const Proc: TEnumASTDeclProc); var Decl: TIDDeclaration; begin {константы} Decl := ConstSpace.First; while Assigned(Decl) do begin Proc(Self, Decl); Decl := Decl.NextItem; end; {глобальные переменные} Decl := VarSpace.First; while Assigned(Decl) do begin Proc(Self, Decl); Decl := Decl.NextItem; end; {типы} Decl := TypeSpace.First; while Assigned(Decl) do begin Proc(Self, Decl); Decl := Decl.NextItem; end; {процедуры} Decl := ProcSpace.First; while Assigned(Decl) do begin Proc(Self, Decl); Decl := Decl.NextItem; end; end; procedure TASTDelphiUnit.EnumIntfDeclarations(const Proc: TEnumASTDeclProc); var Decl: TIDDeclaration; begin {константы} Decl := ConstSpace.First; while Assigned(Decl) do begin if Decl.Scope = IntfScope then Proc(Self, Decl); Decl := Decl.NextItem; end; {глобальные переменные} Decl := VarSpace.First; while Assigned(Decl) do begin if Decl.Scope = IntfScope then Proc(Self, Decl); Decl := Decl.NextItem; end; {типы} Decl := TypeSpace.First; while Assigned(Decl) do begin if Decl.Scope = IntfScope then Proc(Self, Decl); Decl := Decl.NextItem; end; {процедуры} Decl := ProcSpace.First; while Assigned(Decl) do begin if Decl.Scope = IntfScope then Proc(Self, Decl); Decl := Decl.NextItem; end; end; class function TASTDelphiUnit.GetTMPVar(const EContext: TEContext; DataType: TIDType): TIDVariable; begin Result := TIDProcedure(EContext.Proc).GetTMPVar(DataType); end; function TASTDelphiUnit.GetSource: string; begin Result := Lexer.Source; end; class function TASTDelphiUnit.GetStaticTMPVar(DataType: TIDType; VarFlags: TVariableFlags): TIDVariable; begin Result := TIDVariable.CreateAsTemporary(nil, DataType); Result.IncludeFlags(VarFlags); end; function TASTDelphiUnit.GetSystemDeclarations: PDelphiSystemDeclarations; begin Result := fSysDecls; end; class function TASTDelphiUnit.GetTMPVar(const SContext: TSContext; DataType: TIDType): TIDVariable; begin if Assigned(SContext.Proc) then Result := SContext.Proc.GetTMPVar(DataType) else Result := GetStaticTMPVar(DataType); end; class function TASTDelphiUnit.GetTMPVarExpr(const EContext: TEContext; DataType: TIDType; const TextPos: TTextPosition): TIDExpression; begin Result := TIDExpression.Create(GetTMPVar(EContext, DataType), TextPos); end; class function TASTDelphiUnit.GetTMPVarExpr(const SContext: TSContext; DataType: TIDType; const TextPos: TTextPosition): TIDExpression; begin Result := TIDExpression.Create(GetTMPVar(SContext, DataType), TextPos); end; class function TASTDelphiUnit.GetTMPRef(const SContext: TSContext; DataType: TIDType): TIDVariable; begin Result := SContext.Proc.GetTMPRef(DataType); end; class function TASTDelphiUnit.GetTMPRefExpr(const SContext: TSContext; DataType: TIDType; const TextPos: TTextPosition): TIDExpression; begin Result := TIDExpression.Create(GetTMPRef(SContext, DataType)); Result.TextPosition := TextPos; end; class function TASTDelphiUnit.GetTMPRefExpr(const SContext: TSContext; DataType: TIDType): TIDExpression; begin Result := TIDExpression.Create(GetTMPRef(SContext, DataType)); end; procedure TASTDelphiUnit.InitEContext(out EContext: TEContext; const SContext: TSContext; EPosition: TExpessionPosition); begin EContext.Initialize(SContext, Process_operators); EContext.EPosition := EPosition; end; function TASTDelphiUnit.IsConstEqual(const Left, Right: TIDExpression): Boolean; var RExpr: TIDExpression; begin RExpr := fCCalc.ProcessConstOperation(Left, Right, opEqual); Result := TIDBooleanConstant(RExpr.Declaration).Value; end; function TASTDelphiUnit.IsConstRangesIntersect(const Left, Right: TIDRangeConstant): Boolean; var Expr, LeftLB, LeftHB, RightLB, RightHB: TIDExpression; begin LeftLB := Left.Value.LBExpression; LeftHB := Left.Value.HBExpression; RightLB := Right.Value.LBExpression; RightHB := Right.Value.HBExpression; Expr := fCCalc.ProcessConstOperation(LeftLB, RightLB, opLess); // если Left.Low < Right.Low if TIDBooleanConstant(Expr.Declaration).Value then begin Expr := fCCalc.ProcessConstOperation(LeftHB, RightLB, opGreaterOrEqual); Result := TIDBooleanConstant(Expr.Declaration).Value; end else begin Expr := fCCalc.ProcessConstOperation(RightHB, LeftLB, opGreaterOrEqual); Result := TIDBooleanConstant(Expr.Declaration).Value; end; end; function TASTDelphiUnit.IsConstValueInRange(Value: TIDExpression; RangeExpr: TIDRangeConstant): Boolean; var Expr: TIDExpression; begin Expr := fCCalc.ProcessConstOperation(Value, RangeExpr.Value.LBExpression, opLess); if TIDBooleanConstant(Expr.Declaration).Value then Exit(False); Expr := fCCalc.ProcessConstOperation(Value, RangeExpr.Value.HBExpression, opLessOrEqual); Result := TIDBooleanConstant(Expr.Declaration).Value; end; procedure TASTDelphiUnit.InsertToScope(Scope: TScope; Item: TIDDeclaration); begin if not Scope.InsertID(Item) then ERRORS.ID_REDECLARATED(Item); end; procedure TASTDelphiUnit.InsertToScope(Scope: TScope; const ID: string; Declaration: TIDDeclaration); begin if Assigned(Scope.InsertNode(ID, Declaration)) then ERRORS.ID_REDECLARATED(Declaration); end; {parser methods} procedure TASTDelphiUnit.Lexer_ReadTokenAsID(var Identifier: TIdentifier); begin with Lexer do begin if TokenCanBeID(TTokenID(CurrentTokenID)) then begin Identifier.Name := TokenLexem(TTokenID(CurrentTokenID)); Identifier.TextPosition := Position; end else ERRORS.IDENTIFIER_EXPECTED(TTokenID(CurrentTokenID)); end; end; procedure TASTDelphiUnit.Lexer_ReadNextIdentifier(Scope: TScope; var Identifier: TIdentifier); var Token: TTokenID; begin Token := Lexer_NextToken(Scope); if Token = token_Identifier then Lexer.GetIdentifier(Identifier) else Lexer_ReadTokenAsID(Identifier); end; procedure TASTDelphiUnit.CheckCorrectEndCondStatemet(var Token: TTokenID); var Found: Boolean; begin Found := False; while (Token < token_cond_define) and (Token <> token_eof) and (Token <> token_closefigure) do begin if not Found then begin Warning('Invalid chars in conditional statement: %s', [Lexer_TokenLexem(Token)], Lexer_Position); Found := True; end; Token := Lexer.NextToken; end; end; procedure TASTDelphiUnit.Lexer_ReadNextIFDEFLiteral(Scope: TScope; var Identifier: TIdentifier); var Token: TTokenID; begin Lexer_ReadNextIdentifier(Scope, Identifier); Token := Lexer.NextToken; CheckCorrectEndCondStatemet(Token); Lexer_MatchToken(Token, token_closefigure); end; procedure TASTDelphiUnit.Lexer_ReadSemicolon(Scope: TScope); begin if Lexer_NextToken(Scope) <> token_semicolon then ERRORS.SEMICOLON_EXPECTED; end; function TASTDelphiUnit.Lexer_ReadSemicolonAndToken(Scope: TScope): TTokenID; begin Result := Lexer_NextToken(Scope); if Result = token_semicolon then Result := Lexer_NextToken(Scope); end; procedure TASTDelphiUnit.Lexer_ReadToken(Scope: TScope; const Token: TTokenID); var curToken: TTokenID; begin curToken := Lexer_NextToken(Scope); if curToken <> Token then ERRORS.EXPECTED_TOKEN(Token, curToken); end; procedure TASTDelphiUnit.Lexer_MatchToken(const ActualToken, ExpectedToken: TTokenID); begin if ActualToken <> ExpectedToken then ERRORS.EXPECTED_TOKEN(ExpectedToken, ActualToken); end; procedure TASTDelphiUnit.Lexer_MatchCurToken(const ExpectedToken: TTokenID); begin if Lexer_CurTokenID <> ExpectedToken then ERRORS.EXPECTED_TOKEN(ExpectedToken, Lexer_CurTokenID); end; procedure TASTDelphiUnit.Lexer_MatchIdentifier(const ActualToken: TTokenID); begin if ActualToken <> token_Identifier then if not Lexer.TokenCanBeID(ActualToken) then ERRORS.IDENTIFIER_EXPECTED(ActualToken); end; procedure TASTDelphiUnit.Lexer_MatchParamNameIdentifier(ActualToken: TTokenID); begin if ActualToken <> token_Identifier then ERRORS.PARAM_NAME_ID_EXPECTED(ActualToken); end; procedure TASTDelphiUnit.Lexer_MatchSemicolon(const ActualToken: TTokenID); begin if ActualToken <> token_semicolon then ERRORS.SEMICOLON_EXPECTED; end; procedure TASTDelphiUnit.Lexer_ReadCurrIdentifier(var Identifier: TIdentifier); begin if Lexer_CurTokenID = token_identifier then Lexer.GetIdentifier(Identifier) else Lexer.GetTokenAsIdentifier(Identifier); end; function TASTDelphiUnit.Lexer_NextToken(Scope: TScope): TTokenID; begin Result := TTokenID(Lexer.NextToken); if Result >= token_cond_define then Result := ParseCondStatements(Scope, Result); end; function TASTDelphiUnit.Lexer_AmbiguousId: TTokenID; begin Result := TTokenID(Lexer.AmbiguousTokenID); end; function TASTDelphiUnit.Lexer_CurTokenID: TTokenID; begin Result := TTokenID(Lexer.CurrentTokenID); end; function TASTDelphiUnit.Lexer_Position: TTextPosition; begin Result := Lexer.Position; end; function TASTDelphiUnit.Lexer_PrevPosition: TTextPosition; begin Result := Lexer.PrevPosition; end; function TASTDelphiUnit.Lexer_IdentifireType: TIdentifierType; begin Result := Lexer.IdentifireType; end; function TASTDelphiUnit.Lexer_IsCurrentIdentifier: boolean; begin Result := Lexer.IdentifireType = itIdentifier; end; function TASTDelphiUnit.Lexer_IsCurrentToken(TokenID: TTokenID): boolean; begin Result := Lexer.AmbiguousTokenId = Ord(TokenID); end; function TASTDelphiUnit.Lexer_NotEOF: boolean; begin Result := Lexer_CurTokenID <> token_eof; end; function TASTDelphiUnit.Lexer_Line: Integer; begin Result := Lexer.Position.Row; end; function TASTDelphiUnit.Lexer_TokenLexem(const TokenID: TTokenID): string; begin Result := Lexer.TokenLexem(TokenID); end; function TASTDelphiUnit.Lexer_SkipBlock(StopToken: TTokenID): TTokenID; var ECnt: Integer; begin ECnt := 0; while True do begin Result := Lexer.NextToken; case Result of token_begin, token_try, token_case: Inc(ECnt); token_end: begin if (StopToken = token_end) and (ECnt = 0) then Exit; Dec(ECnt); if (StopToken = token_end) and (ECnt = 0) then Exit; end; token_eof: Exit(token_eof); end; end; end; function TASTDelphiUnit.Lexer_SkipTo(Scope: TScope; StopToken: TTokenID): TTokenID; begin while true do begin Result := Lexer_NextToken(Scope); if (Result = StopToken) or (Result = token_eof) then Exit; end; end; procedure TASTDelphiUnit.PutMessage(MessageType: TCompilerMessageType; const MessageText: string); var SourcePosition: TTextPosition; Msg: TCompilerMessage; begin SourcePosition.Row := -1; SourcePosition.Col := -1; Msg := TCompilerMessage.Create(Self, MessageType, MessageText, SourcePosition); Msg.UnitName := _ID.Name; Messages.Add(Msg); fPackage.PutMessage(Msg); end; procedure TASTDelphiUnit.PutMessage(MessageType: TCompilerMessageType; const MessageText: string; const SourcePosition: TTextPosition); var Msg: TCompilerMessage; begin Msg := TCompilerMessage.Create(Self, MessageType, MessageText, SourcePosition); Msg.UnitName := GetCurrentParsedFileName(True); Messages.Add(Msg); fPackage.PutMessage(Msg); end; procedure TASTDelphiUnit.PutMessage(Message: TCompilerMessage); begin Message.UnitName := Self.Name; if Message.Row <=0 then begin Message.Row := Lexer_Position.Row; Message.Col := Lexer_Position.Col; end; Messages.Add(Message); fPackage.PutMessage(Message); end; procedure TASTDelphiUnit.Error(const Message: string; const Params: array of const; const TextPosition: TTextPosition); begin PutMessage(cmtError, Format(Message, Params), TextPosition); end; procedure TASTDelphiUnit.Warning(const Message: string; const Params: array of const; const TextPosition: TTextPosition); begin PutMessage(cmtWarning, Format(Message, Params), TextPosition); end; procedure TASTDelphiUnit.Hint(const Message: string; const Params: array of const; const TextPosition: TTextPosition); begin PutMessage(cmtHint, Format(Message, Params), TextPosition); end; procedure TASTDelphiUnit.Hint(const Message: string; const Params: array of const); begin PutMessage(cmtHint, Format(Message, Params)); end; function TASTDelphiUnit.FindID(Scope: TScope; const ID: TIdentifier{; out Expression: TIDExpression}): TIDDeclaration; var i: Integer; IDName: string; begin IDName := ID.Name; Result := Scope.FindIDRecurcive(IDName); if not Assigned(Result) then ERRORS.UNDECLARED_ID(ID); end; function TASTDelphiUnit.FindIDNoAbort(Scope: TScope; const ID: string): TIDDeclaration; begin Result := Scope.FindIDRecurcive(ID); end; function TASTDelphiUnit.FindIDNoAbort(Scope: TScope; const ID: TIdentifier): TIDDeclaration; begin Result := Scope.FindIDRecurcive(ID.Name); end; procedure TASTDelphiUnit.AddType(const Decl: TIDType); begin if not (Decl is TIDAliasType) and not Decl.IsPooled then begin TypeSpace.Add(Decl); Decl.IsPooled := True; end; end; class function TASTDelphiUnit.MatchImplicit(Source, Destination: TIDType): TIDDeclaration; begin Source := Source.ActualDataType; Destination := Destination.ActualDataType; if Source = Destination then Exit(Destination); // ищем явно определенный implicit у источника Result := Source.GetImplicitOperatorTo(Destination); if Assigned(Result) then Exit; // ищем явно определенный implicit у приемника Result := Destination.GetImplicitOperatorFrom(Source); if Assigned(Result) then Exit; // если не нашли точных имплиситов, ищем подходящий (у источника) Result := Source.FindImplicitOperatorTo(Destination); if Assigned(Result) then Exit; // если не нашли точных имплиситов, ищем подходящий (у приемника) Result := Destination.FindImplicitOperatorFrom(Source); if Assigned(Result) then Exit; if (Destination.DataTypeID = dtGeneric) or (Source.DataTypeID = dtGeneric) then Exit(Source); // нужна еще проверка на констрейты end; function TASTDelphiUnit.MatchImplicit3(const SContext: TSContext; Source: TIDExpression; Dest: TIDType; AAbortIfError: Boolean = True): TIDExpression; var WasCall: Boolean; begin Result := MatchImplicitOrNil(SContext, Source, Dest); if Assigned(Result) then Exit; WasCall := False; Source := CheckAndCallFuncImplicit(SContext, Source, {out} WasCall); if WasCall then begin Result := MatchImplicitOrNil(SContext, Source, Dest); if Assigned(Result) then Exit; end; if AAbortIfError then ERRORS.INCOMPATIBLE_TYPES(Source, Dest); end; class function TASTDelphiUnit.MatchImplicitClassOf(Source: TIDExpression; Destination: TIDClassOf): TIDDeclaration; var SrcDecl: TIDDeclaration; DstDecl: TIDClass; begin SrcDecl := Source.Declaration; DstDecl := TIDClass(Destination.ReferenceType); // если источник - тип if SrcDecl.ItemType = itType then begin if SrcDecl is TIDStructure then begin if (SrcDecl = DstDecl) or TIDStructure(SrcDecl).IsInheritsForm(DstDecl) then Exit(Destination); end else AbortWork(sCLASSTypeRequired, Source.TextPosition); end else // если источник - переменная if SrcDecl.ItemType = itVar then begin if SrcDecl.DataType.DataTypeID = dtClassOf then begin SrcDecl := TIDClassOf(SrcDecl.DataType).ReferenceType; if (SrcDecl = DstDecl) or TIDClass(SrcDecl).IsInheritsForm(DstDecl) then Exit(Destination); end; end; Result := nil; end; function TASTDelphiUnit.MatchArrayImplicit(const SContext: TSContext; Source: TIDExpression; DstArray: TIDArray): TIDExpression; function CreateAnonymousDynArrayType(ElementDataType: TIDType): TIDArray; begin Result := TIDDynArray.CreateAsAnonymous(ImplScope); Result.ElementDataType := ElementDataType; AddType(Result); end; var i, ACnt: Integer; CArray: TIDDynArrayConstant; SExpr: TIDExpression; DstElementDT: TIDType; BoundType: TIDOrdinal; NeedCallImplicits: Boolean; ImplicitCast: TIDDeclaration; TmpArrayType: TIDArray; Expr: TIDExpression; EContext: TEContext; SrcArray: TIDArray; begin Result := nil; SrcArray := Source.DataType as TIDArray; // skip any checks if the parameter is open array of const if DstArray.IsOpenArrayOfConst then Exit(Source); if Source.Declaration is TIDDynArrayConstant then begin CArray := Source.AsArrayConst; DstElementDT := DstArray.ElementDataType; // проверка каждого элемента NeedCallImplicits := False; ACnt := CArray.ArrayLength; for i := 0 to ACnt - 1 do begin SExpr := CArray.Value[i]; ImplicitCast := CheckImplicit(SContext, SExpr, DstElementDT); if not Assigned(ImplicitCast) then ERRORS.INCOMPATIBLE_TYPES(SExpr, DstElementDT); if ImplicitCast.ItemType = itProcedure then NeedCallImplicits := True; end; {если тип вектора не совподает с типом приемника, подгоняем тип под нужный} if TIDArray(CArray.DataType).ElementDataType <> DstElementDT then CArray.DataType := CreateAnonymousDynArrayType(DstElementDT); // если типы массивов требуют вызовов пользовательских операторов implicit // то создаем временный статический массив, и для каждого элемента вызываем пользовательский implicit if NeedCallImplicits then begin if DstArray.DataTypeID = dtOpenArray then begin // для открытых массивов создаем анонимный тип - статический массив TmpArrayType := TIDArray.CreateAnonymousStatic1Dim(ImplScope, DstElementDT, ACnt, BoundType); AddType(BoundType); AddType(TmpArrayType); Result := GetTMPVarExpr(SContext, TmpArrayType, Lexer_Position); end else begin // для динамических массивов просто выделяем память Result := GetTMPVarExpr(SContext, DstArray, Lexer_Position); //ILWrite(SContext, TIL.IL_DAlloc(Result, IntConstExpression(ACnt))); end; for i := 0 to ACnt - 1 do begin SExpr := CArray.Value[i]; InitEContext(EContext, SContext, ExprNested); Expr := TIDMultiExpression.CreateAnonymous(DstElementDT, [Result, IntConstExpression(SContext, i)]); EContext.RPNPushExpression(Expr); EContext.RPNPushExpression(SExpr); Process_operator_Assign(EContext); end; end else Result := Source; end else begin // приведение динамических массивов if (SrcArray.DataTypeID = DstArray.DataTypeID) and (SrcArray.DimensionsCount = DstArray.DimensionsCount) then begin for i := 0 to SrcArray.DimensionsCount - 1 do begin // todo: добавить глубокую проверку типов (range/enum/...) if SrcArray.Dimensions[i].ActualDataType <> DstArray.Dimensions[i].ActualDataType then Exit(nil); end; if SrcArray.ElementDataType.ActualDataType <> DstArray.ElementDataType.ActualDataType then Exit(nil); Result := Source; end; end; end; function TASTDelphiUnit.MatchRecordImplicit(const SContext: TSContext; Source: TIDExpression; DstRecord: TIDRecord): TIDExpression; var SrcRecord: TIDRecord; i: Integer; SrcFld, DstFld: TIDVariable; begin SrcRecord := Source.DataType as TIDRecord; if SrcRecord.FieldsCount <> DstRecord.FieldsCount then Exit(nil); SrcFld := SrcRecord.Fields.First; DstFld := DstRecord.Fields.First; for i := 0 to SrcRecord.FieldsCount - 1 do begin if SrcFld.DataType.ActualDataType <> DstFld.DataType.ActualDataType then Exit(nil); SrcFld := TIDVariable(SrcFld.NextItem); DstFld := TIDVariable(DstFld.NextItem); end; Result := Source; end; class function TASTDelphiUnit.MatchUnarOperator(Op: TOperatorID; Right: TIDType): TIDType; begin Right := Right.ActualDataType; Result := Right.UnarOperator(Op, Right); if Assigned(Result) then Exit; if (Right.DataTypeID = dtGeneric) then Exit(Right); end; class function TASTDelphiUnit.MatchUnarOperator(const SContext: TSContext; Op: TOperatorID; Source: TIDExpression): TIDExpression; var OpDecl: TIDType; WasCall: Boolean; begin OpDecl := MatchUnarOperator(Op, Source.DataType.ActualDataType); if Assigned(OpDecl) then Exit(Source); Source := CheckAndCallFuncImplicit(SContext, Source, WasCall); if WasCall then begin OpDecl := MatchUnarOperator(Op, Source.DataType.ActualDataType); if Assigned(OpDecl) then Exit(Source); end; end; function TASTDelphiUnit.MatchImplicitOrNil(const SContext: TSContext; Source: TIDExpression; Dest: TIDType): TIDExpression; var SDataType: TIDType; Decl: TIDDeclaration; SrcDTID, DstDTID: TDataTypeID; begin {$IFDEF DEBUG} Result := nil; if not Assigned(Source.DataType) then AbortWorkInternal('Source data type is not assigned', Lexer_Position); {$ENDIF} SDataType := Source.DataType.ActualDataType; Dest := Dest.ActualDataType; if SDataType = Dest then Exit(Source); SrcDTID := SDataType.DataTypeID; DstDTID := Dest.DataTypeID; // ищем явно определенный implicit у источника Decl := SDataType.GetImplicitOperatorTo(Dest); if Decl is TSysTypeCast then begin Result := TSysTypeCast(Decl).Match(SContext, Source, Dest); if Assigned(Result) then Exit(Result); Decl := nil; end; if not Assigned(Decl) then begin // ищем явно определенный implicit у приемника Decl := Dest.GetImplicitOperatorFrom(SDataType); if not Assigned(Decl) then begin // если не нашли точных имплиситов, ищем подходящий (у источника) Decl := SDataType.FindImplicitOperatorTo(Dest); if not Assigned(Decl) then begin // если не нашли точных имплиситов, ищем подходящий (у приемника) Decl := Dest.FindImplicitOperatorFrom(SDataType); if not Assigned(Decl) then begin { если классы и интерфейс } if (SrcDTID = dtClass) and (DstDTID = dtInterface) then begin if TIDClass(Source.DataType).FindInterface(TIDInterface(Dest)) then Exit(Source) else ERRORS.CLASS_NOT_IMPLEMENT_INTF(Source, Dest); end; { есди приемник - class of } if DstDTID = dtClassOf then Decl := MatchImplicitClassOf(Source, TIDClassOf(Dest)); {дин. массив как набор} if (DstDTID = dtSet) and (SDataType is TIDDynArray) then begin Result := MatchSetImplicit(SContext, Source, TIDSet(Dest)); Exit; end else if (SrcDTID = dtProcType) and (DstDTID = dtProcType) then Decl := MatchProcedureTypes(TIDProcType(SDataType), TIDProcType(Dest)) else if SDataType is TIDArray then begin if Dest is TIDArray then Result := MatchArrayImplicit(SContext, Source, TIDArray(Dest)) else // if DstDTID = dtRecord then // Result := MatchArrayImplicitToRecord(SContext, Source, TIDStructure(Dest)) // else Result := nil; Exit; end; if (SrcDTID = dtRecord) and (DstDTID = dtRecord) then begin Result := MatchRecordImplicit(SContext, Source, TIDRecord(Dest)); Exit; end; {если generic} if (SrcDTID = dtGeneric) or (DstDTID = dtGeneric) then Exit(Source); // нужна еще проверка на констрейты end; end; end else if Decl is TSysTypeCast then begin Result := TSysTypeCast(Decl).Match(SContext, Source, Dest); if Assigned(Result) then Exit; end; end; if Source.ClassType = TIDDrefExpression then begin Result := GetTMPVarExpr(SContext, Source.DataType, Lexer_Position); Exit; end; if Assigned(SDataType.SysImplicitToAny) then begin Decl := TSysOpImplicit(SDataType.SysImplicitToAny).Check(SContext, Source, Dest); if Assigned(Decl) then Exit(Source); Decl := nil; end; if not Assigned(Decl) then begin if Assigned(Dest.SysExplicitFromAny) then begin Decl := TSysOpImplicit(Dest.SysExplicitFromAny).Check(SContext, Source, Dest); if Assigned(Decl) then Exit(Source); end; Exit(nil); end; if Decl.ItemType = itType then Exit(Source); Result := nil; end; procedure TASTDelphiUnit.MatchProc(const SContext: TSContext; CallExpr: TIDExpression; const ProcParams: TIDParamArray; var CallArgs: TIDExpressions); var i, ArgIdx, pc: Integer; Param: TIDVariable; Arg: TIDExpression; Implicit: TIDDeclaration; CallArgsCount: Integer; begin pc := Length(ProcParams); CallArgsCount := Length(CallArgs); if CallArgsCount > pc then ERRORS.TOO_MANY_ACTUAL_PARAMS(CallArgs[pc], pc, CallArgsCount); ArgIdx := 0; for i := 0 to pc - 1 do begin Param := ProcParams[i]; if VarHiddenParam in Param.Flags then Continue; // пропускаем скрытые параметры if (ArgIdx < CallArgsCount) then begin Arg := CallArgs[ArgIdx]; Inc(ArgIdx); if Assigned(Arg) then begin if (Arg.ItemType = itVar) and (Arg.DataType = Sys._Void) then begin if VarOut in Param.Flags then Arg.AsVariable.DataType := Param.DataType else ERRORS.INPLACEVAR_ALLOWED_ONLY_FOR_OUT_PARAMS(Arg.AsVariable); end; Implicit := CheckImplicit(SContext, Arg, Param.DataType, {AResolveCalls:} True); if Assigned(Implicit) then begin if Param.VarReference then begin CheckVarExpression(Arg, vmpPassArgument); {проверка на строгость соответствия типов} if Param.DataType.ActualDataType <> Arg.DataType.ActualDataType then CheckVarParamConformity(Param, Arg); end; continue; end; ERRORS.INCOMPATIBLE_TYPES(Arg, Param.DataType); end else if not Assigned(Param.DefaultValue) then ERRORS.NOT_ENOUGH_ACTUAL_PARAMS(CallExpr); end; end; end; class function TASTDelphiUnit.MatchProcedureTypes(Src, Dst: TIDProcType): TIDType; begin if StrictMatchProcSingnatures(Src.Params, Dst.Params, Src.ResultType, Dst.ResultType) then Result := Dst else Result := nil; end; function GetProcDeclSring(const Params: TIDParamArray; ResultType: TIDtype): string; var sProcParams, sProcParamName: string; begin if Assigned(ResultType) then Result := 'function' else Result := 'procedure'; for var LParam in Params do begin sProcParamName := LParam.DisplayName + ': ' + LParam.DataType.DisplayName; sProcParams := AddStringSegment(sProcParams, sProcParamName, '; '); end; if sProcParams <> '' then Result := Result + '(' + sProcParams + ')'; if Assigned(ResultType) then Result := Result + ': ' + ResultType.DisplayName; end; procedure TASTDelphiUnit.MatchPropGetter(Prop: TIDProperty; Getter: TIDProcedure; const PropParams: TIDParamArray); begin var LParamCount := Length(PropParams); if Getter.ParamsCount <> LParamCount then ERRORS.GETTER_MUST_BE_SUCH(Getter, GetProcDeclSring(PropParams, Prop.DataType)); for var LParamIndex := 0 to LParamCount - 1 do begin var LGetterParam := Getter.ExplicitParams[LParamIndex]; var LPropertyParam := PropParams[LParamIndex]; if MatchImplicit(LPropertyParam.DataType, LGetterParam.DataType) = nil then ERRORS.GETTER_MUST_BE_SUCH(Getter, GetProcDeclSring(PropParams, Prop.DataType)); end; end; procedure TASTDelphiUnit.MatchPropSetter(Prop: TIDProperty; Setter: TIDExpression; const PropParams: TIDParamArray); var Proc: TIDProcedure; LSetterParam, LPropertryParam: TIDParam; begin var LParamCount := Length(PropParams); // due to possible overloaded setters (getter can't be overloaded), serach for the proper setter Proc := Setter.AsProcedure; while Assigned(Proc) do begin if not Assigned(Proc.ResultType) and (Proc.ParamsCount = (LParamCount + 1)) then begin var IsMatch := True; // match indexed params first for var LParamIndex := 0 to LParamCount - 1 do begin LSetterParam := Proc.ExplicitParams[LParamIndex]; LPropertryParam := PropParams[LParamIndex]; if MatchImplicit(LPropertryParam.DataType, LSetterParam.DataType) = nil then begin IsMatch := False; Break; end; end; if IsMatch then begin // match property setter value param LSetterParam := Proc.ExplicitParams[LParamCount]; if MatchImplicit(LSetterParam.DataType, Prop.DataType) <> nil then Exit; end; end; Proc := Proc.PrevOverload; end; if not Assigned(Proc) then ERRORS.SETTER_MUST_BE_SUCH(GetProcDeclSring(PropParams, nil), Setter.TextPosition); end; function TASTDelphiUnit.MatchBinarOperator(const SContext: TSContext; Op: TOperatorID; var Left, Right: TIDExpression): TIDDeclaration; var LeftDT, RightDT: TIDType; L2RImplicit, R2LImplicit: TIDDeclaration; begin LeftDT := Left.DataType.ActualDataType; RightDT := Right.DataType.ActualDataType; // поиск оператора (у левого операнда) Result := LeftDT.BinarOperator(Op, RightDT); if Assigned(Result) then Exit; // поиск оператора (у правого операнда) Result := RightDT.BinarOperatorFor(Op, LeftDT); if Assigned(Result) then Exit; Result := LeftDT.SysBinayOperator[Op]; if Assigned(Result) then Exit; Result := RightDT.SysBinayOperator[Op]; if Assigned(Result) then Exit; if (LeftDT.DataTypeID = dtGeneric) then Exit(LeftDT); if RightDT.DataTypeID = dtGeneric then Exit(RightDT); if (Op = opIn) and (Right.Declaration.ClassType = TIDRangeConstant) then begin Result := MatchOperatorIn(SContext, Left, Right); Exit; end; if (LeftDT.DataTypeID = dtClass) and (RightDT.DataTypeID = dtClass) then begin if TIDClass(LeftDT).IsInheritsForm(TIDClass(RightDT)) then Exit(Sys._Boolean); if TIDClass(RightDT).IsInheritsForm(TIDClass(LeftDT)) then Exit(Sys._Boolean); end; // если ненайдено напрямую - ищем через неявное привидение L2RImplicit := CheckImplicit(SContext, Left, RightDT); R2LImplicit := CheckImplicit(SContext, Right, LeftDT); if L2RImplicit is TIDType then begin Result := TIDType(L2RImplicit).BinarOperator(Op, RightDT); if Assigned(Result) then begin Left := MatchImplicit3(SContext, Left, RightDT); Exit; end; end; if R2LImplicit is TIDType then begin Result := TIDType(R2LImplicit).BinarOperator(Op, LeftDT); if Assigned(Result) then begin Right := MatchImplicit3(SContext, Right, LeftDT); Exit; end; end; if Assigned(L2RImplicit) then begin Result := RightDT.BinarOperator(Op, L2RImplicit.DataType); if Assigned(Result) then begin Left := MatchImplicit3(SContext, Left, RightDT); Exit; end; end; if Assigned(R2LImplicit) then begin Result := LeftDT.BinarOperator(Op, R2LImplicit.DataType); if Assigned(Result) then begin Right := MatchImplicit3(SContext, Right, LeftDT); Exit; end; end; Result := nil; end; class function TASTDelphiUnit.MatchOperatorIn(const SContext: TSContext; const Left, Right: TIDExpression): TIDDeclaration; var RangeConst: TIDRangeConstant; DataType: TIDType; begin RangeConst := Right.Declaration as TIDRangeConstant; DataType := RangeConst.Value.LBExpression.DataType; Result := CheckImplicit(SContext, Left, DataType); if Assigned(Result) then begin DataType := RangeConst.Value.HBExpression.DataType; Result := CheckImplicit(SContext, Left, DataType); end; // пока без проверки на пользовательские операторы end; function TASTDelphiUnit.MatchOverloadProc(const SContext: TSContext; Item: TIDExpression; const CallArgs: TIDExpressions; CallArgsCount: Integer): TIDProcedure; procedure AbortWithAmbiguousOverload(AmbiguousCnt: Integer; AmbiguousRate: Integer); var Str, Args: string; ProcItem: PASTProcMatchItem; begin for var i := 0 to AmbiguousCnt - 1 do begin ProcItem := Addr(fProcMatches[i]); if ProcItem.TotalRate = AmbiguousRate then Str := Str + #13#10' ' + ProcItem.Decl.Module.Name + '.' + ProcItem.Decl.DisplayName; end; for var i := 0 to CallArgsCount - 1 do Args := AddStringSegment(Args, CallArgs[i].DataType.DisplayName, ', '); Str := Str + #13#10' Arguments: (' + Args + ')'; // just warning, to not block parsing process // todo: AST parser doesn't have ability to resolve an ambiguous // in case argument array [..] of Char and params (1. PAnsiChar, 2. untyped ref) // Warning(sAmbiguousOverloadedCallFmt, [Str], Item.TextPosition); end; const cRateFactor = 1000000; // multiplication factor for total rate calculdation var i, MatchedCount: Integer; // Кол-во деклараций имеющих одинаковый максимальный коэффициент ParamDataType, // Тип формального параметра процедуры ArgDataType : TIDType; // Тип передаваемого аргумента Param: TIDVariable; ImplicitCast: TIDDeclaration; Declaration: TIDProcedure; SrcDataTypeID, DstDataTypeID: TDataTypeID; curProcMatchItem: PASTProcMatchItem; cutArgMatchItem: PASTArgMatchInfo; curLevel: TASTArgMatchLevel; curRate: TASTArgMatchRate; begin Result := nil; MatchedCount := 0; Declaration := TIDProcedure(Item.Declaration); repeat if (Declaration.ParamsCount = 0) and (CallArgsCount = 0) then Exit(Declaration); // check and grow if MatchedCount >= Length(fProcMatches) then SetLength(fProcMatches, MatchedCount + 4); curProcMatchItem := Addr(fProcMatches[MatchedCount]); if CallArgsCount <= Declaration.ParamsCount then begin for i := 0 to Declaration.ParamsCount - 1 do begin Param := Declaration.ExplicitParams[i]; // if cur arg presents if (i < CallArgsCount) and Assigned(CallArgs[i]) then begin ParamDataType := Param.DataType.ActualDataType; ArgDataType := CallArgs[i].DataType.ActualDataType; curRate := 0; curLevel := MatchNone; // сравнение типов формального параметра и аргумента (пока не учитываются модификаторы const, var... etc) if ParamDataType.DataTypeID = dtGeneric then curLevel := TASTArgMatchLevel.MatchGeneric else if ParamDataType = ArgDataType then curLevel := TASTArgMatchLevel.MatchStrict else begin // find implicit type cast ImplicitCast := CheckImplicit(SContext, CallArgs[i], ParamDataType, {AResolveCalls:} True); if Assigned(ImplicitCast) then begin SrcDataTypeID := ArgDataType.DataTypeID; DstDataTypeID := ParamDataType.DataTypeID; if SrcDataTypeID = DstDataTypeID then begin curLevel := TASTArgMatchLevel.MatchImplicit; curRate := 10; end else begin var dataLoss: Boolean; curRate := GetImplicitRate(SrcDataTypeID, DstDataTypeID, {out} dataLoss); // todo if dataLoss then curLevel := TASTArgMatchLevel.MatchImplicitAndDataLoss else curLevel := TASTArgMatchLevel.MatchImplicit; end; end; // if any arg doesn't match - skip this declaration if curLevel = MatchNone then Break; end; end else begin // if the arg is missed and the param has a default value if VarHasDefault in param.Flags then curLevel := TASTArgMatchLevel.MatchStrict else begin // if not, skip this declaration curLevel := MatchNone; Break; end; end; // check and grow if i >= Length(curProcMatchItem.ArgsInfo) then SetLength(curProcMatchItem.ArgsInfo, i + 4); // store argument's match info into cache cutArgMatchItem := @curProcMatchItem.ArgsInfo[i]; cutArgMatchItem.Level := curLevel; cutArgMatchItem.Rate := curRate; end; end else begin // skip this declaration due to params length doesn't match Declaration := Declaration.PrevOverload; Continue; end; if curLevel <> MatchNone then begin curProcMatchItem.Decl := Declaration; Inc(MatchedCount); end; // take next declaration Declaration := Declaration.PrevOverload; until Declaration = nil; Declaration := nil; if MatchedCount > 0 then begin // calculating total rates for each match for i := 0 to MatchedCount - 1 do begin var TotalRate: Integer := 0; curProcMatchItem := Addr(fProcMatches[i]); for var j := 0 to CallArgsCount - 1 do begin cutArgMatchItem := Addr(curProcMatchItem.ArgsInfo[j]); TotalRate := TotalRate + Ord(cutArgMatchItem.Level)*cRateFactor + cutArgMatchItem.Rate * 100000; end; curProcMatchItem.TotalRate := TotalRate; end; // finding the most matched or ambiguous var MaxRate := 0; var AmbiguousRate: Integer := 0; for i := 0 to MatchedCount - 1 do begin curProcMatchItem := Addr(fProcMatches[i]); if curProcMatchItem.TotalRate > MaxRate then begin MaxRate := curProcMatchItem.TotalRate; Result := curProcMatchItem.Decl; AmbiguousRate := 0; end else if curProcMatchItem.TotalRate = MaxRate then begin AmbiguousRate := curProcMatchItem.TotalRate; end; end; if AmbiguousRate > 0 then AbortWithAmbiguousOverload(MatchedCount, AmbiguousRate); end else ERRORS.NO_OVERLOAD(Item, CallArgs) end; function TASTDelphiUnit.MatchBinarOperatorWithImplicit(const SContext: TSContext; Op: TOperatorID; var Left, Right: TIDexpression): TIDDeclaration; var LeftDT, RightDT: TIDType; Operators: TBinaryOperatorsArray; LeftImplicit, RightImplicit, LeftBinarOp, RightBinarOp: TIDDeclaration; LeftImplicitFactor, RightImplicitFactor: Integer; begin LeftImplicitFactor := 0; RightImplicitFactor := 0; LeftDT := Left.DataType.ActualDataType; RightDT := Right.DataType.ActualDataType; Operators := LeftDT.BinarOperators[Op]; if Assigned(Operators) then LeftBinarOp := FindImplicitFormBinarOperators(Operators, LeftDT, RightDT, {out} LeftImplicit, {out} RightImplicit, {out} LeftImplicitFactor) else LeftBinarOp := nil; Operators := RightDT.BinarOperators[Op]; if Assigned(Operators) then RightBinarOp := FindImplicitFormBinarOperators(Operators, LeftDT, RightDT, {out} LeftImplicit, {out} RightImplicit, {out} RightImplicitFactor) else RightBinarOp := nil; if not Assigned(LeftBinarOp) and not Assigned(RightBinarOp) then Exit(nil); if LeftImplicitFactor >= RightImplicitFactor then begin Result := LeftBinarOp; //Right := WriteImplicitCast(LeftImplicit, Right); end else begin Result := RightBinarOp; //Left := WriteImplicitCast(RightImplicit, Left); end; end; class function TASTDelphiUnit.CheckExplicit(const Scontext: TSContext; const Source, Destination: TIDType; out ExplicitOp: TIDDeclaration): Boolean; var SrcDataType: TIDType; DstDataType: TIDType; begin ExplicitOp := nil; SrcDataType := Source.ActualDataType; DstDataType := Destination.ActualDataType; if SrcDataType = DstDataType then Exit(True); if (SrcDataType.DataTypeID = dtClass) and (DstDataType.DataTypeID = dtClass) then Exit(True); ExplicitOp := SrcDataType.GetExplicitOperatorTo(DstDataType); if Assigned(ExplicitOp) then begin if ExplicitOp is TSysTypeCast then begin if TSysTypeCast(ExplicitOp).Check(SContext, SrcDataType, DstDataType) then Exit(True); end else Exit(True); end; ExplicitOp := DstDataType.GetExplicitOperatorFrom(SrcDataType); if Assigned(ExplicitOp) then begin if ExplicitOp is TSysTypeCast then begin if TSysTypeCast(ExplicitOp).Check(SContext, SrcDataType, DstDataType) then Exit(True); end else Exit(True); end; Result := False; end; class procedure TASTDelphiUnit.CheckExprHasMembers(Expression: TIDExpression); begin if not (Expression.DataType is TIDStructure) and not Assigned(Expression.DataType.Helper) then AbortWork('Expression has no members', Expression.TextPosition); end; procedure TASTDelphiUnit.CheckForwardPtrDeclarations; begin // search and assign reference type for forward pointer types // for searching use current scope only for var AIndex := fForwardPtrTypes.Count - 1 downto 0 do begin var APtrDecl := fForwardPtrTypes[AIndex]; var ARefDecl := APtrDecl.Scope.FindID(APtrDecl.ForwardID.Name); if Assigned(ARefDecl) then begin if ARefDecl.ItemType <> itType then AbortWork(sTypeIdExpectedButFoundFmt, [APtrDecl.ForwardID.Name], APtrDecl.ForwardID.TextPosition); APtrDecl.ReferenceType := TIDType(ARefDecl); fForwardPtrTypes.Delete(AIndex); end; end; end; class function TASTDelphiUnit.MatchExplicit(const SContext: TSContext; const Source: TIDExpression; Destination: TIDType; out Explicit: TIDDeclaration): TIDExpression; var SrcDataType: TIDType; DstDataType: TIDType; begin SrcDataType := Source.DataType.ActualDataType; DstDataType := Destination.ActualDataType; if CheckExplicit(SContext, SrcDataType, DstDataType, Explicit) then Result := TIDCastExpression.Create(Source, DstDataType) else begin Result := nil; var WasCall := False; var NewSource := CheckAndCallFuncImplicit(Scontext, Source, WasCall); if WasCall then begin SrcDataType := NewSource.DataType.ActualDataType; Result := TIDCastExpression.Create(NewSource, DstDataType); end; end; end; class procedure TASTDelphiUnit.CheckAndCallFuncImplicit(const EContext: TEContext); var Expr, Res: TIDExpression; begin Expr := EContext.Result; if Assigned(Expr) and (Expr.DataTypeID = dtProcType) and Assigned(Expr.AsProcedure.ResultType) then begin // todo: generate a call expression Res := GetTMPVarExpr(EContext, Expr.AsProcedure.ResultType, Expr.TextPosition); EContext.RPNPushExpression(Res); end; end; function TASTDelphiUnit.AddResultParameter(Params: TScope; DataType: TIDType): TIDVariable; var Decl: TIDDeclaration; begin Result := TIDVariable.CreateAsAnonymous(Params); Decl := Params.FindID('Result'); if Assigned(Decl) then Result.Name := '$Result' // just a flag that Result was redeclared, should be cheched later else Result.Name := 'Result'; Result.Flags := [VarParameter, VarOut, VarHiddenParam, VarResult]; Result.DataType := DataType; Result.TextPosition := Lexer_Position; Params.InsertID(Result); Params.VarSpace.InsertFirst(Result); end; class procedure TASTDelphiUnit.AddSelfParameter(Params: TScope; Struct: TIDStructure; ClassMethod: Boolean); var SelfParam: TIDVariable; DataType: TIDType; begin if Struct is TDlphHelper then DataType := TDlphHelper(Struct).Target else DataType := Struct; if ClassMethod and (DataType is TIDClass) then DataType := TIDClass(DataType).ClassOfType; // if Struct.DataTypeID = dtRecord then // SelfParam := TIDVariable.Create(Params, Identifier('Self'), DataType, [VarParameter, VarSelf, VarInOut, VarHiddenParam]) // else SelfParam := TIDVariable.Create(Params, Identifier('Self'), DataType, [VarParameter, VarSelf, VarHiddenParam]); Params.AddVariable(SelfParam); end; class function TASTDelphiUnit.CheckAndCallFuncImplicit(const SContext: TSContext; Expr: TIDExpression; out WasCall: Boolean): TIDExpression; begin WasCall := False; if Expr.ItemType = itProcedure then begin var LProc := Expr.AsProcedure; var LResultType := LProc.ResultType; if Assigned(LResultType) or (pfConstructor in LProc.Flags) then begin WasCall := True; if (pfConstructor in LProc.Flags) then LResultType := (Expr as TIDCallExpression).Instance.AsType; Result := GetTMPVarExpr(SContext, LResultType, Expr.TextPosition); end else Result := Expr; end else begin if Expr.DataTypeID = dtProcType then begin var LProcType := TIDProcType(Expr.DataType); if Assigned(LProcType.ResultType) then begin WasCall := True; Result := GetTMPVarExpr(SContext, LProcType.ResultType, Expr.TextPosition); end else Result := Expr; end else Result := Expr; end; end; class function TASTDelphiUnit.CheckAndCallFuncImplicit(const EContext: TEContext; Expr: TIDExpression): TIDExpression; begin if (Expr.DataTypeID = dtProcType) and Assigned(TIDProcType(Expr.DataType).ResultType) then begin // todo: generate func call Result := GetTMPVarExpr(EContext, TIDProcType(Expr.DataType).ResultType, Expr.TextPosition); end else Result := Expr; end; function TASTDelphiUnit.CheckAndMakeClosure(const SContext: TSContext; const ProcDecl: TIDProcedure): TIDClosure; begin // todo: recognize using out context and create an anonymous class Result := nil; end; function TASTDelphiUnit.CheckAndParseAttribute(Scope: TScope): TTokenID; begin // todo: complete the attributes parsing Result := Lexer_CurTokenID; if Result = token_openblock then Result := ParseAttribute(Scope); end; function TASTDelphiUnit.CheckAndParseDeprecated(Scope: TScope; CurrToken: TTokenID): TTokenID; var MessageExpr: TIDExpression; begin Result := CurrToken; if CurrToken = token_deprecated then begin Result := Lexer_NextToken(Scope); if Result = token_identifier then begin Result := ParseConstExpression(Scope, MessageExpr, TExpessionPosition.ExprRValue); CheckStringExpression(MessageExpr); end; end; end; function TASTDelphiUnit.CheckAndParseProcTypeCallConv(Scope: TScope; Token: TTokenID; TypeDecl: TIDType): TTokenID; begin if Token = token_semicolon then Result := Lexer_NextToken(Scope) else Result := Token; case Result of token_stdcall: begin TIDProcType(TypeDecl).CallConv := ConvStdCall; Result := Lexer_NextToken(Scope); if Result = token_semicolon then Result := Lexer_NextToken(Scope); end; token_fastcall: begin TIDProcType(TypeDecl).CallConv := ConvFastCall; Result := Lexer_NextToken(Scope); if Result = token_semicolon then Result := Lexer_NextToken(Scope); end; token_cdecl: begin TIDProcType(TypeDecl).CallConv := ConvCDecl; Result := Lexer_NextToken(Scope); if Result = token_semicolon then Result := Lexer_NextToken(Scope); end; end; end; class function TASTDelphiUnit.CheckImplicit(const SContext: TSContext; Source: TIDExpression; Dest: TIDType; AResolveCalls: Boolean): TIDDeclaration; var SDataType: TIDType; SrcDTID, DstDTID: TDataTypeID; begin SDataType := Source.DataType.ActualDataType; Dest := Dest.ActualDataType; if SDataType = Dest then Exit(Dest); // ищем явно определенный implicit у источника Result := SDataType.GetImplicitOperatorTo(Dest); if Result is TSysTypeCast then Result := TSysTypeCast(Result).Check(SContext, Source, Dest); if Assigned(Result) then Exit; // ищем явно определенный implicit у приемника Result := Dest.GetImplicitOperatorFrom(SDataType); if Result is TSysTypeCast then Result := TSysTypeCast(Result).Check(SContext, Source, Dest); if Assigned(Result) then Exit; // если не нашли точных имплиситов, ищем подходящий (у источника) Result := SDataType.FindImplicitOperatorTo(Dest); if Result is TSysTypeCast then Result := TSysTypeCast(Result).Check(SContext, Source, Dest); if Assigned(Result) then Exit; // если не нашли точных имплиситов, ищем подходящий (у приемника) Result := Dest.FindImplicitOperatorFrom(SDataType); if Result is TSysTypeCast then Result := TSysTypeCast(Result).Check(SContext, Source, Dest); if Assigned(Result) then Exit; SrcDTID := Source.DataTypeID; DstDTID := Dest.DataTypeID; // есди приемник - class of if DstDTID = dtClassOf then begin Result := MatchImplicitClassOf(Source, TIDClassOf(Dest)); if Assigned(Result) then Exit; end; if (SrcDTID = dtPointer) and (DstDTID = dtPointer) then begin if (TIDPointer(SDataType).ReferenceType = nil) and (TIDPointer(Dest).ReferenceType = nil) then Exit(Source.DataType); // it needs to check !!! if not Assigned(TIDPointer(SDataType).ReferenceType) or not Assigned(TIDPointer(Dest).ReferenceType) then Exit(Source.DataType); if TIDPointer(SDataType).ReferenceType.ActualDataType = TIDPointer(Dest).ReferenceType.ActualDataType then Exit(Source.DataType); end; if (SrcDTID = dtProcType) and (DstDTID = dtProcType) then Result := MatchProcedureTypes(TIDProcType(SDataType), TIDProcType(Dest)) else if (Source.Declaration.ItemType = itConst) and (SrcDTID = dtDynArray) then Result := CheckConstDynArrayImplicit(SContext, Source, Dest) else begin Result := MatchDynArrayImplicit(Source, Dest); end; if (DstDTID = dtGeneric) or (SrcDTID = dtGeneric) then begin // todo: constrains Exit(Source.Declaration); end; if AResolveCalls then begin if Source.ItemType = itProcedure then begin if Assigned(Source.AsProcedure.ResultType) then begin var AResultExpr := TIDExpression.Create(SContext.Proc.GetTMPVar(Source.AsProcedure.ResultType), Source.TextPosition); Exit(CheckImplicit(SContext, AResultExpr, Dest)); end; end; if (Source.ItemType = itVar) and (Source.DataTypeID = dtProcType) then begin var AResultType := TIDProcType(Source.DataType).ResultType; if Assigned(AResultType) then begin var AResultExpr := TIDExpression.Create(SContext.Proc.GetTMPVar(AResultType), Source.TextPosition); Exit(CheckImplicit(SContext, AResultExpr, Dest)); end; end; end; end; function TASTDelphiUnit.ParseAnonymousProc(Scope: TScope; var EContext: TEContext; const SContext: TSContext; ProcType: TTokenID): TTokenID; var ProcScope: TProcScope; GenericsArgs: TIDTypeArray; ResultType: TIDType; ProcDecl: TASTDelphiProc; VarSpace: TVarSpace; Closure: TIDClosure; Expr: TIDExpression; begin VarSpace.Initialize; ProcScope := TProcScope.CreateInDecl(Scope, nil, @VarSpace, nil); // создаем Result переменную (тип будет определен позже) Result := Lexer_NextToken(Scope); // если generic if Result = token_less then Result := ParseGenericsHeader(ProcScope, {out} GenericsArgs); // парсим параметры if Result = token_openround then begin ParseParameters(ProcScope, ProcScope.ParamsScope); Result := Lexer_NextToken(Scope); // move to "token_colon" end; if ProcType = token_function then begin Lexer_MatchToken(Result, token_colon); // парсим тип возвращаемого значения Result := ParseTypeSpec(ProcScope, {out} ResultType); AddResultParameter(ProcScope, ResultType); end else ResultType := nil; Lexer_MatchToken(Result, token_begin); ProcDecl := TASTDelphiProc.CreateAsAnonymous(ImplScope); ProcDecl.VarSpace := VarSpace; ProcDecl.ParamsScope := ProcScope; ProcDecl.EntryScope := ProcScope; ProcDecl.ResultType := ResultType; ProcDecl.CreateProcedureTypeIfNeed(Scope); ProcScope.Proc := ProcDecl; ProcDecl.ExplicitParams := ProcScope.ExplicitParams; {парсим тело анонимной процедуры} Result := ParseProcBody(ProcDecl); Closure := CheckAndMakeClosure(SContext, ProcDecl); if Assigned(Closure) then begin {если это замыкание, меняем анонимную процедуру на метод замыкания} ProcDecl.Struct := Closure; ProcDecl.MakeSelfParam; ProcDecl.Name := 'Run'; Expr := EmitCreateClosure(SContext, Closure); end else begin ImplScope.AddAnonymousProcedure(ProcDecl); Expr := TIDExpression.Create(ProcDecl, Lexer_PrevPosition); end; EContext.RPNPushExpression(Expr); end; function TASTDelphiUnit.ParseArrayMember(Scope: TScope; var EContext: TEContext; ASTE: TASTExpression): TTokenID; var ArrExpr: TIDExpression; ArrDecl: TIDDeclaration; IdxCount: Integer; // кол-во индексов указанных при обращении к массиву Expr: TIDExpression; InnerEContext: TEContext; DimensionsCount: Integer; DeclType: TIDType; DataType: TIDType; begin ArrExpr := EContext.RPNPopExpression(); ArrDecl := ArrExpr.Declaration; DeclType := ArrExpr.DataType; if DeclType.DataTypeID = dtPointer then begin var ARefType := GetPtrReferenceType(TIDPointer(DeclType)); // auto-dereference for static array pointer (doesn't depend on POINTERMATH state) if ARefType.DataTypeID = dtStaticArray then begin DimensionsCount := TIDArray(ARefType).DimensionsCount; DataType := TIDArray(ARefType).ElementDataType; end else // Delphi always treats System.PByte as POINTERMATH enabled type if Options.POINTERMATH or (ARefType.DataTypeID in [dtUInt8]) then begin DimensionsCount := 1; DataType := ARefType; end else ERRORS.ARRAY_TYPE_REQUIRED(ArrExpr.Declaration.ID, Lexer_PrevPosition); end else if DeclType.DataTypeID in [dtPAnsiChar, dtPWideChar] then begin var ARefType := GetPtrReferenceType(TIDPointer(DeclType)); DimensionsCount := 1; DataType := ARefType; end else if (ArrDecl.ItemType <> itProperty) and (DeclType is TIDArray) then begin DimensionsCount := TIDArray(DeclType).DimensionsCount; DataType := TIDArray(DeclType).ElementDataType; end else if (ArrDecl.ItemType = itProperty) and (TIDProperty(ArrDecl).Params.Count > 0) then begin DimensionsCount := TIDProperty(ArrDecl).ParamsCount; DataType := TIDProperty(ArrDecl).DataType; end else if (DeclType is TIDStructure) and Assigned(TIDStructure(DeclType).DefaultProperty) then begin ArrDecl := TIDStructure(DeclType).DefaultProperty; DimensionsCount := TIDProperty(ArrDecl).ParamsCount; DataType := TIDProperty(ArrDecl).DataType; Expr := TIDExpression.Create(ArrDecl); end else if (ArrDecl.ItemType = itType) and (TIDType(ArrDecl).DataTypeID in [dtString, dtAnsiString]) then begin // string with length restriction (ShortString) Lexer_NextToken(Scope); Result := ParseConstExpression(Scope, Expr, ExprNested); Lexer_MatchToken(Result, token_closeblock); Result := Lexer_NextToken(Scope); // todo: create new string type and add size restriction Expr := TIDExpression.Create(ArrDecl, ArrExpr.TextPosition); EContext.RPNPushExpression(Expr); Exit; end else begin ERRORS.ARRAY_TYPE_REQUIRED(ArrDecl.ID, ArrExpr.TextPosition); DimensionsCount := 0; end; var Op: TASTOpArrayAccess := ASTE.AddOperation<TASTOpArrayAccess>; IdxCount := 0; InitEContext(InnerEContext, EContext.SContext, ExprNested); var Indexes: TIDExpressions := []; while True do begin Lexer_NextToken(Scope); var ASTExpr: TASTExpression := nil; Result := ParseExpression(Scope, EContext.SContext, InnerEContext, ASTExpr); Op.AddIndex(ASTExpr); Expr := InnerEContext.Result; CheckEmptyExpression(Expr); Indexes := Indexes + [Expr]; {if Assigned(InnerEContext.LastBoolNode) then Bool_CompleteImmediateExpression(InnerEContext, Expr);} if Expr.Declaration.ItemType = itConst then // статическая проверка на границы массива StaticCheckBounds(Expr.AsConst, ArrDecl, IdxCount) else begin // динамическая проверка на границы массива {if UseCheckBound then EmitDynCheckBound(EContext.SContext, Decl, Expr);} end; //PMContext.Add(Expr); Inc(IdxCount); if Result = token_coma then begin InnerEContext.Reset; Continue; end; Lexer_MatchToken(Result, token_closeblock); Result := Lexer_NextToken(Scope); Break; end; if IdxCount <> DimensionsCount then ERRORS.NEED_SPECIFY_NINDEXES(ArrDecl); var ATmpVar := GetTMPVar(EContext, DataType); var AExpr := TIDArrayExpression.Create(ATmpVar, ArrExpr.TextPosition); AExpr.DataType := DataType; AExpr.Indexes := Indexes; EContext.RPNPushExpression(AExpr); end; function TASTDelphiUnit.ParseAsmSpecifier: TTokenID; begin end; function TASTDelphiUnit.ParseASMStatement(Scope: TScope; const SContext: TSContext): TTokenID; var KW: TASTKWAsm; begin KW := SContext.Add(TASTKWAsm) as TASTKWAsm; while (Result <> token_end) do begin // skip all to end if KW.Next <> nil then; Result := Lexer_NextToken(Scope); end; Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseAttribute(Scope: TScope): TTokenID; begin Result := Lexer_CurTokenID; while (Result <> token_closeblock) and (Result <> token_eof) do begin Result := Lexer_NextToken(Scope); end; Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseProperty(Scope: TScope; Struct: TIDStructure): TTokenID; var ID: TIdentifier; Prop: TIDProperty; PropDataType: TIDType; Proc: TIDProcedure; Expr: TIDExpression; EContext: TEContext; DataType: TIDType; IndexedPropParams: TIDParamArray; VarSpace: TVarSpace; SContext: TSContext; ASTE: TASTExpression; begin Lexer_ReadNextIdentifier(Scope, ID); Prop := TIDProperty.Create(Scope, ID); Scope.AddProperty(Prop); Result := Lexer_NextToken(Scope); if Result = token_openblock then begin // indexed propery VarSpace.Initialize; var LParamsScope := TParamsScope.Create(stLocal, Scope); Prop.Params := LParamsScope; Result := ParseParameters(Scope, LParamsScope); IndexedPropParams := LParamsScope.ExplicitParams; Lexer_MatchToken(Result, token_closeblock); Result := Lexer_NextToken(Scope); end; // property type Lexer_MatchToken(Result, token_colon); Result := ParseTypeSpec(Scope, PropDataType); Prop.DataType := PropDataType; SContext := fUnitSContext; // getter if Result = token_read then begin InitEContext(EContext, SContext, ExprRValue); Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, EContext, ASTE); Expr := EContext.Result; if Expr.ItemType = itProcedure then begin Proc := Expr.AsProcedure; DataType := Proc.ResultType; if not Assigned(DataType) then AbortWork(sFieldConstOrFuncRequiredForGetter, Expr.TextPosition); if Assigned(IndexedPropParams) then MatchPropGetter(Prop, Proc, IndexedPropParams); end else DataType := Expr.DataType; CheckImplicitTypes(DataType, PropDataType, Expr.TextPosition); Prop.Getter := Expr.Declaration; end; // setter if Result = token_write then begin InitEContext(EContext, SContext, ExprRValue); Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, EContext, ASTE); Expr := EContext.Result; case Expr.ItemType of itConst: AbortWork(sFieldOrProcRequiredForSetter, Expr.TextPosition); itProcedure: MatchPropSetter(Prop, Expr, IndexedPropParams); end; Prop.Setter := Expr.Declaration; end; Lexer_MatchToken(Result, token_semicolon); Result := Lexer_NextToken(Scope); // default propery (note: default is ambiguous keyword) if Lexer_IsCurrentToken(token_default) then begin if Prop.ParamsCount = 0 then ERRORS.DEFAULT_PROP_MUST_BE_ARRAY_PROP; if not Assigned(Struct.DefaultProperty) then Struct.DefaultProperty := Prop else ERRORS.DEFAULT_PROP_ALREADY_EXIST(Struct.DefaultProperty); Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; end; {function TASTDelphiUnit.ParseBreakStatement(Scope: TScope; const SContext: TSContext): TTokenID; begin if not SContext.IsLoopBody then if not SContext.IsLoopBody then AbortWork(sBreakOrContinueAreAllowedOnlyInALoops, Lexer_Position); SContext.Add(TASTKWBreak); Result := Lexer_NextToken(Scope); end;} procedure TASTDelphiUnit.ParseCondDefine(Scope: TScope; add_define: Boolean); var ID: TIdentifier; idx: Integer; begin Lexer_ReadNextIFDEFLiteral(Scope, ID); idx := FDefines.IndexOf(ID.Name); if add_define then begin if idx = -1 then FDefines.Add(ID.Name); end else begin if idx > -1 then FDefines.Delete(idx); end; end; function TASTDelphiUnit.ParseCondError(Scope: TScope): TTokenID; var ID: TIdentifier; begin Lexer_ReadNextIdentifier(Scope, ID); AbortWork(ID.Name, ID.TextPosition); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseCondHint(Scope: TScope): TTokenID; var ID: TIdentifier; begin Lexer_ReadNextIdentifier(Scope, ID); PutMessage(cmtHint, ID.Name, ID.TextPosition); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseCondIf(Scope: TScope; out ExpressionResult: TCondIFValue): TTokenID; var Expr: TIDExpression; CondScope: TConditionalScope; begin CondScope := TConditionalScope.Create(TScopeType.stLocal, Scope); Lexer.NextToken; Result := ParseConstExpression(CondScope, Expr, ExprRValue); if Expr.DataTypeID <> dtGeneric then begin CheckBooleanExpression(Expr); ExpressionResult := TCondIFValue(Expr.AsBoolConst.Value); end else ExpressionResult := condIFUnknown; end; function TASTDelphiUnit.ParseCondInclude(Scope: TScope): TTokenID; var FileName: string; Pos: TParserPosition; Stream: TStringStream; begin while True do begin Result := TTokenID(Lexer.NextToken); if Result = token_closefigure then break; if Result = token_identifier then FileName := FileName + Lexer.OriginalToken else FileName := FileName + '.'; // tmp end; Stream := TStringStream.Create; try Stream.LoadFromFile(ExtractFilePath(Self.FileName) + FileName); var Messages := CompileSource(Scope, FileName, Stream.DataString); if Messages.HasErrors then AbortWork('The included file: ' + FileName + ' has errors', Lexer_Position); finally Stream.Free; end; end; function TASTDelphiUnit.ParseCondIfDef(Scope: TScope): Boolean; var ID: TIdentifier; begin Lexer_ReadNextIFDEFLiteral(Scope, ID); Result := Defined(ID.Name); end; function TASTDelphiUnit.ParseCondMessage(Scope: TScope): TTokenID; var ID: TIdentifier; MsgType: string; begin Lexer_ReadNextIdentifier(Scope, ID); MsgType := UpperCase(ID.Name); Lexer_ReadNextIdentifier(Scope, ID); if MsgType = 'ERROR' then PutMessage(TCompilerMessageType.cmtWarning, 'message error: ' + ID.Name, ID.TextPosition); // todo: Result := Lexer.NextToken; end; function TASTDelphiUnit.ParseCondOptions(Scope: TScope): TTokenID; function SkipToEnd: TTokenID; begin repeat Result := Lexer.NextToken; until Result = token_closefigure; Result := Lexer.NextToken; end; var OptID: TIdentifier; Opt: TOption; ErrorMsg: string; begin while True do begin Lexer.ReadNextIdentifier(OptID); Opt := Options.FindOption(OptID.Name); if not Assigned(Opt) then begin Warning('Unknown compiler directive: %s', [OptID.Name], OptID.TextPosition); Exit(SkipToEnd()); end; case Opt.ArgsCount of 1: begin Result := Lexer.NextToken; var Value: string; if Result = token_identifier then Value := Lexer.OriginalToken else Value := Lexer_TokenLexem(Result); TValueOption(Opt).SetValue(Value, ErrorMsg); end; // todo: end; if ErrorMsg <> '' then AbortWork(OptID.Name + ' option arguments Error: ' + ErrorMsg, Lexer_Position); Result := Lexer.NextToken; if Result = token_coma then Continue; break; end; Lexer_MatchToken(Result, token_closefigure); Result := Lexer.NextToken; end; function TASTDelphiUnit.ParseCondOptSet(Scope: TScope): TTokenID; var ID: TIdentifier; Expr: TIDExpression; begin Lexer_ReadNextIdentifier(Scope, ID); if not Options.Exist(ID.Name) then ERRORS.UNKNOWN_OPTION(ID); Lexer_ReadToken(Scope, token_equal); Lexer.NextToken; Result := ParseConstExpression(Scope, Expr, ExprRValue); Lexer_MatchSemicolon(Result); CheckEmptyExpression(Expr); Options.OptSet(ID.Name, Expr.AsConst.AsVariant); Result := Lexer.NextToken; end; function TASTDelphiUnit.ParseCondStatements(Scope: TScope; Token: TTokenID): TTokenID; function SkipToElseOrEnd(SkipToEnd: Boolean): TTokenID; var ifcnt: Integer; begin ifcnt := 0; while True do begin Result := Lexer.NextToken; case Result of token_cond_if, token_cond_ifdef, token_cond_ifopt, token_cond_ifndef: Inc(ifcnt); // считаем вложенные конструкции token_cond_else: begin if SkipToEnd then continue; if ifcnt = 0 then Exit; end; token_cond_else_if: begin if ifcnt = 0 then Exit; end; token_cond_end: begin if ifcnt = 0 then Exit; Dec(ifcnt); end; token_eof: ERRORS.END_OF_FILE; end; end; end; var ExprResult: TCondIFValue; CondResult: Boolean; begin Result := Token; while true do begin case Result of ////////////////////////////////////////// // {$define ...} token_cond_define: begin ParseCondDefine(Scope, True); Result := Lexer_NextToken(Scope); end; ////////////////////////////////////////// // {$else ...} token_cond_else: begin // skip all comment tokens repeat Result := Lexer.NextToken; until (Result = token_eof) or (Result = token_closefigure); if fCondStack.Top then Result := SkipToElseOrEnd(False); end; ////////////////////////////////////////// // {$elseif (condition)} token_cond_else_if: begin if fCondStack.Top then Result := SkipToElseOrEnd(True) else begin Result := ParseCondIf(Scope, ExprResult); fCondStack.Top := (ExprResult = condIfTrue); case ExprResult of condIFFalse: Result := SkipToElseOrEnd(False); condIfTrue:; condIFUnknown: Result := SkipToElseOrEnd(True); end; end; end; ////////////////////////////////////////// // {$endif ...} token_cond_end: begin fCondStack.Pop; repeat Result := Lexer.NextToken; until (Result = token_eof) or (Result = token_closefigure); Result := Lexer.NextToken; end; ////////////////////////////////////////// // {$include ...} token_cond_include: Result := ParseCondInclude(Scope); ////////////////////////////////////////// // {$undefine ...} token_cond_undefine: begin ParseCondDefine(Scope, False); Result := Lexer.NextToken; Lexer_MatchToken(Result, token_closefigure); Result := Lexer_NextToken(Scope); end; ////////////////////////////////////////// // {$ifdef ...} token_cond_ifdef: begin CondResult := ParseCondIfDef(Scope); fCondStack.Push(CondResult); if not CondResult then Result := SkipToElseOrEnd(False) else Result := Lexer.NextToken; end; ////////////////////////////////////////// // {$ifndef ...} token_cond_ifndef: begin CondResult := ParseCondIfDef(Scope); fCondStack.Push(not CondResult); if CondResult then Result := SkipToElseOrEnd(False) else Result := Lexer.NextToken; end; ////////////////////////////////////////// // {$if ...} token_cond_if: begin Result := ParseCondIf(Scope, ExprResult); fCondStack.Push(ExprResult = condIfTrue); case ExprResult of condIFFalse: Result := SkipToElseOrEnd(False); condIFUnknown: Result := SkipToElseOrEnd(True); end; CheckCorrectEndCondStatemet(Result); end; ////////////////////////////////////////// // {$ifopt ...} token_cond_ifopt: begin // todo: complete the options check repeat Result := Lexer.NextToken; until (Result = token_eof) or (Result = token_closefigure); fCondStack.Push(False); Result := SkipToElseOrEnd(False); end; ////////////////////////////////////////// // {$message ...} token_cond_message: Result := ParseCondMessage(Scope); ////////////////////////////////////////// // {$<option> ...} token_cond_any: Result := ParseCondOptions(Scope); else ERRORS.FEATURE_NOT_SUPPORTED; Result := token_unknown; end; if Result = token_closefigure then Result := Lexer.NextToken; if Result < token_cond_define then Break; end; end; function TASTDelphiUnit.ParseCondWarn(Scope: TScope): TTokenID; var ID: TIdentifier; begin Lexer_ReadNextIdentifier(Scope, ID); PutMessage(cmtWarning, ID.Name, ID.TextPosition); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseConstExpression(Scope: TScope; out Expr: TIDExpression; EPosition: TExpessionPosition): TTokenID; var EContext: TEContext; ASTE: TASTExpression; begin InitEContext(EContext, fUnitSContext, EPosition); Result := ParseExpression(Scope, fUnitSContext, EContext, ASTE); CheckEndOfFile(Result); Expr := EContext.Result; if not Assigned(Expr) then Exit; if (Expr.ItemType <> itType) and (Expr.DataTypeID <> dtGeneric) then CheckConstExpression(Expr); end; function TASTDelphiUnit.ParseConstSection(Scope: TScope): TTokenID; var i, c: Integer; DataType: TIDType; LConst: TIDConstant; Expr: TIDExpression; Names: TIdentifiersPool; begin c := 0; Names := TIdentifiersPool.Create(2); Lexer_MatchIdentifier(Lexer_NextToken(Scope)); repeat Names.Add; Lexer_ReadCurrIdentifier(Names.Items[c]); // read name Result := Lexer_NextToken(Scope); if Result = token_Coma then begin Inc(c); Result := Lexer_NextToken(Scope); Lexer_MatchIdentifier(Result); Continue; end; if Result = token_colon then Result := ParseTypeSpec(Scope, DataType) else DataType := nil; // = Lexer_MatchToken(Result, token_equal); if Assigned(DataType) then begin Result := ParseVarDefaultValue(Scope, DataType, Expr); if Expr.IsAnonymous then begin Expr.Declaration.DataType := DataType; Expr.AsConst.ExplicitDataType := DataType; end; end else begin // читаем значение константы Lexer_NextToken(Scope); Result := ParseConstExpression(Scope, {out} Expr, ExprRValue); CheckEmptyExpression(Expr); end; CheckConstExpression(Expr); var LConstClass := GetConstantClassByDataType(Expr.DataTypeID); // AddConstant(Expr.AsConst); if Lexer_IsCurrentToken(token_platform) then Result := ParsePlatform(Scope); Result := CheckAndParseDeprecated(Scope, Result); Lexer_MatchToken(Result, token_semicolon); for i := 0 to c do begin LConst := LConstClass.Create(Scope, Names.Items[i]) as TIDConstant; LConst.DataType := Expr.DataType; LConst.AssignValue(Expr.AsConst); InsertToScope(Scope, LConst); AddConstant(LConst); end; c := 0; Result := Lexer_NextToken(Scope); until (not Lexer_IsCurrentIdentifier); end; {function TASTDelphiUnit.ParseContinueStatement(Scope: TScope; const SContext: TSContext): TTokenID; begin if not SContext.IsLoopBody then AbortWork(sBreakOrContinueAreAllowedOnlyInALoops, Lexer_Position); SContext.Add(TASTKWContinue); Result := Lexer_NextToken(Scope); end;} function TASTDelphiUnit.ParseDeprecated(Scope: TScope; out DeprecatedExpr: TIDExpression): TTokenID; begin Result := Lexer_NextToken(Scope); if Result = token_identifier then begin Result := ParseConstExpression(Scope, DeprecatedExpr, TExpessionPosition.ExprRValue); CheckStringExpression(DeprecatedExpr); end else DeprecatedExpr := TIDExpression.Create(Sys._DeprecatedDefaultStr, Lexer_Position); end; function TASTDelphiUnit.ParseCaseRecord(Scope: TScope; Decl: TIDRecord): TTokenID; var Expr: TIDExpression; CaseVarSpace: PVarSpace; CaseTypeDecl: TIDDeclaration; ID: TIdentifier; begin Lexer_ReadNextIdentifier(Scope, ID); CaseTypeDecl := FindIDNoAbort(Scope, ID); if not Assigned(CaseTypeDecl) then begin Result := Lexer_NextToken(Scope); Lexer_MatchToken(Result, token_colon); Result := Lexer_NextToken(Scope); end; Result := ParseConstExpression(Scope, Expr, ExprNested); Lexer_MatchToken(Result, token_of); Result := Lexer_NextToken(Scope); while Result <> token_eof do begin // parse case lable const expression: (example: ... 1, 2: ... Result := ParseConstExpression(Scope, {out} Expr, ExprLValue); if Result = token_coma then begin Result := Lexer_NextToken(Scope); // just parse all lables for now // todo: labels should be validated Continue; end; // parse ":" & "(" Lexer_MatchToken(Result, token_colon); Lexer_ReadToken(Scope, token_openround); CaseVarSpace := Decl.AddCase(); Result := Lexer_NextToken(Scope); // todo: var space must be redesigned Scope.VarSpace := CaseVarSpace; // parse fields first if (Result = token_identifier) or (Result = token_id_or_keyword) then begin Result := ParseFieldsInCaseRecord(Scope, vPublic, Decl); end; // parse nested case then if Result = token_case then begin Result := ParseCaseRecord(Scope, Decl); Lexer_MatchToken(Result, token_closeround); end; // parse close round at the end if Result = token_closeround then begin Result := Lexer_NextToken(Scope); if Result = token_semicolon then Result := Lexer_NextToken(Scope); case Result of token_minus, token_identifier, token_id_or_keyword: Continue; token_closeround, token_end: Exit; else ERRORS.IDENTIFIER_EXPECTED(Result); end; end else ERRORS.EXPECTED_TOKEN(token_closeround); end; end; function TASTDelphiUnit.ParseCaseStatement(Scope: TScope; const SContext: TSContext): TTokenID; type TMatchItem = record Expression: TIDExpression; end; PMatchItem = ^TMatchItem; var MatchItems: array of TMatchItem; MatchItem: PMatchItem; procedure CheckUniqueMIExpression(Cur: TIDExpression); var i: Integer; Prev: TIDExpression; IsDuplicate: Boolean; begin IsDuplicate := False; for i := 0 to Length(MatchItems) - 2 do begin Prev := MatchItems[i].Expression; if Prev.IsConstant and Cur.IsConstant then begin if Prev.DataTypeID = dtRange then begin if Cur.DataTypeID <> dtRange then IsDuplicate := IsConstValueInRange(Cur, TIDRangeConstant(Prev.Declaration)) else IsDuplicate := IsConstRangesIntersect(TIDRangeConstant(Cur.Declaration), TIDRangeConstant(Prev.Declaration)) end else if Cur.DataTypeID = dtRange then begin IsDuplicate := IsConstValueInRange(Prev, TIDRangeConstant(Cur.Declaration)); end else IsDuplicate := IsConstEqual(Prev, Cur); end else if (not Prev.IsAnonymous) and (not Cur.IsAnonymous) then begin IsDuplicate := (Prev.Declaration = Cur.Declaration); end; if IsDuplicate then AbortWork(sDuplicateMatchExpression, Cur.TextPosition); end; end; var EContext: TEContext; CaseExpr, ItemExpr: TIDExpression; TotalMICount, ItemsCount: Integer; ElsePresent: Boolean; SEConst: Boolean; MISContext: TSContext; NeedWriteIL, NeedCMPCode: Boolean; Implicit: TIDDeclaration; ASTExpr: TASTExpression; KW: TASTKWCase; CaseItem: TASTExpBlockItem; begin KW := SContext.Add(TASTKWCase) as TASTKWCase; // NeedCMPCode := False; // CASE выражение InitEContext(EContext, SContext, ExprRValue); Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, EContext, ASTExpr); KW.Expression := ASTExpr; CaseExpr := EContext.RPNPopExpression(); CheckEmptyExpression(CaseExpr); var WasCall := False; CaseExpr := CheckAndCallFuncImplicit(SContext, CaseExpr, WasCall); {if Assigned(EContext.LastBoolNode) then Bool_CompleteImmediateExpression(EContext, SExpression);} SEConst := CaseExpr.IsConstant; Lexer_MatchToken(Result, token_of); ItemsCount := 0; TotalMICount := 0; NeedWriteIL := True; ElsePresent := False; Result := Lexer_NextToken(Scope); while Result <> token_end do begin InitEContext(EContext, SContext, ExprRValue); if Result <> token_else then begin while True do begin //CFBBegin(SContext, CFB_CASE_ENTRY); Result := ParseExpression(Scope, SContext, EContext, ASTExpr); CaseItem := KW.AddItem(ASTExpr); MISContext := SContext.MakeChild(Scope, CaseItem.Body); ItemExpr := EContext.RPNPopExpression(); CheckEmptyExpression(ItemExpr); // проверка на совпадение типа if ItemExpr.DataTypeID = dtRange then Implicit := CheckImplicit(SContext, CaseExpr, TIDRangeType(ItemExpr.DataType).BaseType) else Implicit := CheckImplicit(SContext, ItemExpr, CaseExpr.DataType); if not Assigned(Implicit) then if not Assigned(Implicit) then AbortWork(sMatchExprTypeMustBeIdenticalToCaseExprFmt, [ItemExpr.DataTypeName, CaseExpr.DataTypeName], ItemExpr.TextPosition); // проверяем на константу if ItemExpr.IsConstant and SEConst then begin // если данное выражение истенно, то для остальных генерировать IL код не нужно if ((ItemExpr.DataTypeID = dtRange) and IsConstValueInRange(CaseExpr, TIDRangeConstant(ItemExpr.Declaration))) or IsConstEqual(CaseExpr, ItemExpr) then begin NeedWriteIL := False; end else NeedWriteIL := True; NeedCMPCode := False; end else begin //MISContext.WriteIL := NeedWriteIL; NeedCMPCode := NeedWriteIL; if NeedCMPCode then begin SetLength(MatchItems, ItemsCount + 1); MatchItem := @MatchItems[ItemsCount]; MatchItem.Expression := ItemExpr; // код проверки условия {if DExpression.DataTypeID <> dtRange then begin end else Process_operator_In(EContext, SExpression, DExpression);} Inc(ItemsCount); end; end; CheckUniqueMIExpression(ItemExpr); {if Assigned(EContext.LastBoolNode) and Assigned(EContext.LastBoolNode.PrevNode) then Bool_AddExprNode(EContext, ntOr);} // если была запятая, парсим следующее выражение if Result <> token_coma then break; Lexer_NextToken(Scope); end; // двоеточие Lexer_MatchToken(Result, token_colon); Lexer_NextToken(Scope); // корректируем переходы //Bool_CompleteExpression(EContext.LastBoolNode, JMPToEnd); // парсим код секции Result := ParseStatements(Scope, MISContext, False); Lexer_MatchToken(Result, token_semicolon); Result := Lexer_NextToken(Scope); Inc(TotalMICount); end else begin // ELSE секция MISContext := SContext.MakeChild(Scope, KW.ElseBody); Lexer_NextToken(Scope); Result := ParseStatements(Scope, MISContext, True); Lexer_MatchToken(Result, token_end); Result := Lexer_NextToken(Scope); ElsePresent := True; Inc(TotalMICount); Break; end; end; // проверяем есть ли хоть одна секция(включая ELSE) в кейсе if TotalMICount = 0 then AbortWork(sCaseStmtRequireAtLeastOneMatchExpr, Lexer_PrevPosition); // если небыло ELSE секции, парсим END; if not ElsePresent then begin Lexer_MatchToken(Result, token_end); Result := Lexer_NextToken(Scope); end; end; function TASTDelphiUnit.ParseClassAncestorType(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; ClassDecl: TIDClass): TTokenID; var Expr: TIDExpression; Decl: TIDType; i: Integer; begin i := 0; // if this is a generic class - use generic description scope if Assigned(GDescriptor) then Scope := GDescriptor.Scope; while True do begin Lexer_NextToken(Scope); Result := ParseConstExpression(Scope, Expr, ExprNested); if Assigned(Expr) then begin CheckClassOrIntfType(Expr); Decl := Expr.AsType; // проверка на зацикливание на себя if Decl = ClassDecl then AbortWork(sRecurciveTypeLinkIsNotAllowed, Expr.TextPosition); end else begin ERRORS.CLASS_OR_INTF_TYPE_REQUIRED(Lexer_PrevPosition); Decl := nil; end; if (Decl.DataTypeID = dtClass) then begin if i = 0 then ClassDecl.Ancestor := TIDClass(Decl) else AbortWork('Multiple inheritance is not supported', Expr.TextPosition); end else begin if ClassDecl.FindInterface(TIDInterface(Decl)) then ERRORS.INTF_ALREADY_IMPLEMENTED(Expr); ClassDecl.AddInterface(TIDInterface(Decl)); end; inc(i); if Result = token_coma then continue; break; end; Lexer_MatchToken(Result, token_closeround); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseClassOfType(Scope: TScope; const ID: TIdentifier; out Decl: TIDClassOf): TTokenID; var RefType: TIDClass; Expr: TIDExpression; begin Lexer_NextToken(Scope); Result := ParseConstExpression(Scope, Expr, ExprRValue); CheckClassType(Expr); RefType := TIDClass(Expr.Declaration); Decl := TIDClassOf.Create(Scope, ID); Decl.ReferenceType := RefType; InsertToScope(Scope, Decl); end; function TASTDelphiUnit.ParseClassType(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TIDClass): TTokenID; var Visibility: TVisibility; //Ancestor: TIDClass; FwdDecl: TIDDeclaration; begin Visibility := vPublic; FwdDecl := Scope.FindID(ID.Name); if not Assigned(FwdDecl) then begin Decl := TIDClass.Create(Scope, ID); if Assigned(GenericScope) then Decl.Members.AddScope(GenericScope); Decl.GenericDescriptor := GDescriptor; if not Assigned(GDescriptor) then InsertToScope(Scope, Decl) else InsertToScope(Scope, GDescriptor.SearchName, Decl); end else begin if (FwdDecl.ItemType = itType) and (TIDType(FwdDecl).DataTypeID = dtClass) and TIDType(FwdDecl).NeedForward then Decl := FwdDecl as TIDClass else ERRORS.ID_REDECLARATED(FwdDecl); end; if (Self = SYSUnit) and (ID.Name = 'TObject') then Sys._TObject := Decl; Result := Lexer_CurTokenID; if Result = token_abstract then begin // class is abstract Result := Lexer_NextToken(Scope); end else if Result = token_sealed then begin // class is sealed Result := Lexer_NextToken(Scope); end; if Result = token_openround then begin Result := ParseClassAncestorType(Scope, GenericScope, GDescriptor, Decl); end else begin if Self <> SYSUnit then Decl.Ancestor := Sys._TObject; end; // если найден символ ; - то это forward-декларация if Result = token_semicolon then begin if Decl.NeedForward then ERRORS.ID_REDECLARATED(ID); Decl.NeedForward := True; Exit; end; if Result = token_abstract then begin Result := Lexer_NextToken(Scope); end; while True do begin case Result of token_openblock: Result := ParseAttribute(Scope); token_class: Result := ParseTypeMember(Scope, Decl); token_procedure: Result := ParseProcedure(Decl.Members, ptProc, Decl); token_function: Result := ParseProcedure(Decl.Members, ptFunc, Decl); token_property: Result := ParseProperty(Decl.Members, Decl); token_constructor: Result := ParseProcedure(Decl.Members, ptConstructor, Decl); token_destructor: begin Result := ParseProcedure(Decl.Members, ptDestructor, Decl); end; token_var: begin Lexer_NextToken(Scope); Result := ParseFieldsSection(Decl.Members, Visibility, Decl, False); end; token_const: Result := ParseConstSection(Decl.StaticMembers); token_type: Result := ParseNamedTypeDecl(Decl.StaticMembers); token_public, token_published: begin Visibility := vPublic; Result := Lexer_NextToken(Scope); end; token_private: begin Visibility := vPrivate; Result := Lexer_NextToken(Scope); end; token_protected: begin Visibility := vProtected; Result := Lexer_NextToken(Scope); end; token_strict: begin Result := Lexer_NextToken(Scope); case Result of token_private: Visibility := vStrictPrivate; token_protected: Visibility := vStrictProtected; else ERRORS.EXPECTED_TOKEN(token_private, Result); end; Result := Lexer_NextToken(Scope); end; token_identifier: begin Result := ParseFieldsSection(Decl.Members, Visibility, Decl, False); end else break; end; end; CheckIncompleteType(Decl.Members); Decl.StructFlags := Decl.StructFlags + [StructCompleted]; Lexer_MatchToken(Result, token_end); Result := Lexer_NextToken(Scope); end; procedure TASTDelphiUnit.CheckLeftOperand(const Status: TRPNStatus); begin if Status <> rpOperand then ERRORS.EXPRESSION_EXPECTED; end; function TASTDelphiUnit.ParseExplicitCast(Scope: TScope; const SContext: TSContext; var DstExpression: TIDExpression): TTokenID; var EContext: TEContext; SrcExpr: TIDExpression; ResExpr: TIDExpression; OperatorDecl: TIDDeclaration; CallExpr: TIDCallExpression; TargetType: TIDType; ASTE: TASTExpression; begin InitEContext(EContext, SContext, ExprNested); Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, EContext, ASTE); SrcExpr := EContext.RPNPopExpression(); if Result <> token_closeround then ERRORS.INCOMPLETE_STATEMENT('explicit cast'); TargetType := DstExpression.AsType; ResExpr := MatchExplicit(SContext, SrcExpr, TargetType, OperatorDecl); Result := Lexer_NextToken(Scope); if Assigned(ResExpr) then begin DstExpression := ResExpr; Exit; end; if Assigned(OperatorDecl) then begin if OperatorDecl.ItemType = itType then begin if (SrcExpr.ItemType = itConst) and (SrcExpr.IsAnonymous) then begin TIDConstant(SrcExpr.Declaration).ExplicitDataType := OperatorDecl as TIDType; DstExpression := TIDExpression.Create(SrcExpr.Declaration); end else DstExpression := TIDCastExpression.Create(SrcExpr.Declaration, TIDType(DstExpression.Declaration), DstExpression.TextPosition); end else if OperatorDecl.ItemType = itProcedure then begin // вызываем explicit-оператор CallExpr := TIDCallExpression.Create(OperatorDecl, DstExpression.TextPosition); CallExpr.ArgumentsCount := 1; DstExpression := Process_CALL_direct(SContext, CallExpr, TIDExpressions.Create(SrcExpr)); end else if OperatorDecl.ItemType = itSysOperator then begin ResExpr := TSysTypeCast(OperatorDecl).Match(SContext, SrcExpr, TargetType); if not Assigned(ResExpr) then ERRORS.INVALID_EXPLICIT_TYPECAST(SrcExpr, TargetType); end; end else ERRORS.INVALID_EXPLICIT_TYPECAST(SrcExpr, TargetType); end; function TASTDelphiUnit.ParseExpression(Scope: TScope; const SContext: TSContext; var EContext: TEContext; out ASTE: TASTExpression): TTokenID; var ID: TIdentifier; Status: TRPNStatus; Expr: TIDExpression; RoundCount: Integer; RecordInitResultExpr: TIDExpression; begin Expr := nil; Status := rprOk; RoundCount := 0; RecordInitResultExpr := nil; Result := Lexer_CurTokenID; ASTE := TASTExpression.Create(nil); while True do begin case Result of token_eof: Break; token_openround: begin if Status = rpOperand then begin Result := ParseMemberCall(Scope, EContext, ASTE); Status := rpOperand; continue; end else begin Inc(RoundCount); EContext.RPNPushOpenRaund; ASTE.AddSubItem(TASTOpOpenRound); Status := rprOk; end; end; token_closeround: begin Dec(RoundCount); if RoundCount < 0 then begin if EContext.EPosition <> ExprLValue then Break; ERRORS.UNNECESSARY_CLOSED_ROUND; end; ASTE.AddSubItem(TASTOpCloseRound); EContext.RPNPushCloseRaund(); Status := rpOperand; end; token_openblock: begin if Status = rpOperand then begin Result := ParseArrayMember(Scope, EContext, ASTE); continue; end else ParseVector(Scope, EContext); Status := rpOperand; end; token_closeblock: begin if EContext.EPosition = ExprNested then Break else ERRORS.UNNECESSARY_CLOSED_BLOCK; end; token_plus: begin if Status = rpOperand then Status := EContext.RPNPushOperator(opAdd) else Status := EContext.RPNPushOperator(opPositive); ASTE.AddSubItem(TASTOpPlus); end; token_minus: begin if Status = rpOperand then Status := EContext.RPNPushOperator(opSubtract) else Status := EContext.RPNPushOperator(opNegative); ASTE.AddSubItem(TASTOpMinus); end; token_equal: begin if EContext.EPosition = ExprType then break; CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opEqual); ASTE.AddSubItem(TASTOpEqual); end; token_colon: begin // for now just skip if EContext.EPosition <> ExprNested then break; // todo: add parsiong args for Str() like: Val:X:Y Status := rpOperation; end; token_notequal: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opNotEqual); ASTE.AddSubItem(TASTOpNotEqual); end; token_less: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opLess); ASTE.AddSubItem(TASTOpLess); end; token_lessorequal: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opLessOrEqual); ASTE.AddSubItem(TASTOpLessEqual); end; token_above: begin if EContext.EPosition = ExprNestedGeneric then Break; CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opGreater); ASTE.AddSubItem(TASTOpGrater); end; token_aboveorequal: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opGreaterOrEqual); ASTE.AddSubItem(TASTOpGraterEqual); end; token_asterisk: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opMultiply); ASTE.AddSubItem(TASTOpMul); end; token_in: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opIn); end; token_slash: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opDivide); ASTE.AddSubItem(TASTOpDiv); end; token_div: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opIntDiv); ASTE.AddSubItem(TASTOpIntDiv); end; token_mod: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opModDiv); ASTE.AddSubItem(TASTOpMod); end; token_period: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opPeriod); end; token_address: begin Status := EContext.RPNPushOperator(opAddr); end; token_caret: begin // call the Process_operator_Deref directly Expr := Process_operator_Deref(EContext); EContext.RPNPushExpression(Expr); Status := rpOperand; end; token_and: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opAnd); end; token_or: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opOr); end; token_xor: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opXor); end; token_not: begin Status := EContext.RPNPushOperator(opNot); end; token_shl: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opShiftLeft); ASTE.AddSubItem(TASTOpShl); end; token_shr: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opShiftRight); ASTE.AddSubItem(TASTOpShr); end; token_is: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opIs); ASTE.AddSubItem(TASTOpCastCheck); end; token_as: begin CheckLeftOperand(Status); Status := EContext.RPNPushOperator(opAs); ASTE.AddSubItem(TASTOpDynCast); end; token_procedure, token_function: begin if Status = rpOperand then break; Result := ParseAnonymousProc(Scope, EContext, SContext, Result); Status := rpOperand; continue; end; token_inherited: begin //CheckLeftOperand(Status); Result := ParseInheritedStatement(Scope, EContext); Status := rpOperand; continue; end; token_dot: begin Result := ParseMember(Scope, EContext, ASTE); Status := rpOperand; continue; end; token_identifier, token_id_or_keyword: begin // есил встретился подряд воторой идентификатор, то выходим if Status = rpOperand then Break; if Lexer_IdentifireType = itIdentifier then begin Expr := nil; Result := ParseIdentifier(Scope, nil, Expr, EContext, nil, ASTE); // если результат = nil значит это был вызов функции и все // необходимые параметры погружены в стек, поэтому идем дальше if not Assigned(Expr) then begin Status := rpOperand; continue; end; // the record default value init if (Result = token_colon) and (Scope is TRecordInitScope) then begin if not Assigned(RecordInitResultExpr) then begin var Decl := TIDRecordConstant.CreateAsAnonymous(Scope, TRecordInitScope(Scope).Struct, nil); //Decl.DataType := TRecordInitScope(Scope).Struct; RecordInitResultExpr := TIDExpression.Create(Decl, Expr.TextPosition); EContext.RPNPushExpression(RecordInitResultExpr); end; Result := ParseRecordInitValue(TRecordInitScope(Scope), Expr); Continue; end; end else begin {анонимная константа} Lexer_ReadCurrIdentifier(ID); Expr := CreateAnonymousConstant(Scope, EContext, ID, Lexer_IdentifireType); Result := Lexer_NextToken(Scope); ASTE.AddDeclItem(Expr.Declaration, Expr.TextPosition); end; EContext.RPNPushExpression(Expr); Status := rpOperand; Continue; end; else Break; end; Result := Lexer_NextToken(Scope); end; if (EContext.EPosition <> ExprNested) and (Status <> rpOperand) and NeedRValue(EContext.RPNLastOp) then ERRORS.EXPRESSION_EXPECTED; if Assigned(Expr) and (Expr is TUnknownIDExpression) then ERRORS.UNDECLARED_ID(TUnknownIDExpression(Expr).ID); EContext.RPNFinish(); end; constructor TASTDelphiUnit.Create(const Project: IASTProject; const FileName: string; const Source: string); var Scope: TProcScope; begin inherited Create(Project, FileName, Source); fDefines := TDefines.Create(); fPackage := Project as IASTDelphiProject; fUnitSContext := TSContext.Create(Self, IntfScope); fErrors := TASTDelphiErrors.Create(Lexer); fCache := TDeclCache.Create; fForwardPtrTypes := TList<TIDPointer>.Create; // FParser := TDelphiLexer.Create(Source); // FMessages := TCompilerMessages.Create; // //FVisibility := vPublic; // FIntfScope := TScope.Create(stGlobal, @FVarSpace, @FProcSpace, nil, Self); // {$IFDEF DEBUG}FIntfScope.Name := 'unit_intf_scope';{$ENDIF} // FImplScope := TImplementationScope.Create(FIntfScope, nil); // {$IFDEF DEBUG}FImplScope.Name := 'unit_impl_scope';{$ENDIF} // FIntfImportedUnits := TUnitList.Create; // FImplImportedUnits := TUnitList.Create; // //FBENodesPool := TBENodesPool.Create(16); // if Assigned(SYSUnit) then // begin // FTypeSpace.Initialize(Sys.SystemTypesCount); // // добовляем system в uses // FIntfImportedUnits.AddObject('system', SYSUnit); // end; FOptions := TDelphiOptions.Create(Package.Options); fCondStack := TSimpleStack<Boolean>.Create(0); fCondStack.OnPopError := procedure begin ERRORS.INVALID_COND_DIRECTIVE end; FInitProc := TASTDelphiProc.CreateAsSystem(ImplScope, '$initialization'); TASTDelphiProc(FInitProc).Body := TASTBlock.Create(FInitProc); FFinalProc := TASTDelphiProc.CreateAsSystem(ImplScope, '$finalization'); TASTDelphiProc(FFinalProc).Body := TASTBlock.Create(FFinalProc); end; function TASTDelphiUnit.CreateAnonymousConstant(Scope: TScope; var EContext: TEContext; const ID: TIdentifier; IdentifierType: TIdentifierType): TIDExpression; var i: Integer; IntValue: Int64; UInt64Value: UInt64; Int32Value: Int32; FltValue: Extended; DataType: TIDType; Value: string; CItem: TIDConstant; Chars: TStringDynArray; begin Value := ID.Name; case IdentifierType of itChar: CItem := TIDCharConstant.CreateAsAnonymous(Scope, Sys._WideChar, Value[1]); itString: begin // если чарсет метаданных равен ASCII, все строковые константы // удовлетворающе набору ASCII, создаются по умолчанию с типом AnsiString if (Package.RTTICharset = RTTICharsetASCII) and IsAnsiString(Value) then DataType := Sys._AnsiString else DataType := Sys._UnicodeString; CItem := TIDStringConstant.CreateAsAnonymous(Scope, DataType, Value); end; itInteger: begin if Value[1] = '#' then begin Value := Copy(Value, 2, Length(Value) - 1); if TryStrToInt(Value, Int32Value) then CItem := TIDCharConstant.CreateAsAnonymous(Scope, Sys._WideChar, Char(Int32Value)) else AbortWorkInternal('int convert error', Lexer_Position); end else begin if not TryStrToInt64(Value, IntValue) then begin if (EContext.RPNLastOperator = TOperatorID.opNegative) then begin // хак для обработки MinInt64 !!! if TryStrToInt64('-' + Value, IntValue) then EContext.RPNEraiseTopOperator else AbortWork('Invalid decimal value: %s', [Value], Lexer_Position); end else if TryStrToUInt64(Value, UInt64Value) then begin IntValue := Int64(UInt64Value); end else AbortWork('Invalid decimal value: %s', [Value], Lexer_Position); end; DataType := Sys.DataTypes[GetValueDataType(IntValue)]; CItem := TIDIntConstant.CreateAsAnonymous(Scope, DataType, IntValue); end; end; itFloat: begin FltValue := StrToFloat(Value); DataType := Sys.DataTypes[GetValueDataType(FltValue)]; CItem := TIDFloatConstant.CreateAsAnonymous(Scope, DataType, FltValue); end; itHextNumber: begin try IntValue := HexToInt64(Value); except ERRORS.INVALID_HEX_CONSTANT; IntValue := 0; end; DataType := Sys.DataTypes[GetValueDataType(IntValue)]; CItem := TIDIntConstant.CreateAsAnonymous(Scope, DataType, IntValue); end; itBinNumber: begin try IntValue := BinStringToInt64(Value); except ERRORS.INVALID_BIN_CONSTANT; IntValue := 0; end; DataType := Sys.DataTypes[GetValueDataType(IntValue)]; CItem := TIDIntConstant.CreateAsAnonymous(Scope, DataType, IntValue); end; itCharCodes: begin Chars := SplitString(ID.Name, '#'); if Chars[0] = '' then Delete(Chars, 0, 1); // this is a string if Length(Chars) > 1 then begin SetLength(Value, Length(Chars)); for i := 0 to Length(Chars) - 1 do Value[Low(string) + i] := Char(StrToInt(Chars[i])); // если чарсет метаданных равен ASCII, все строковые константы // удовлетворающе набору ASCII, создаются по умолчанию с типом AnsiString if (Package.RTTICharset = RTTICharsetASCII) and IsAnsiString(Value) then DataType := Sys._AnsiString else DataType := Sys._UnicodeString; CItem := TIDStringConstant.CreateAsAnonymous(Scope, DataType, Value); end else // this is a char CItem := TIDCharConstant.CreateAsAnonymous(Scope, Sys._WideChar, Char(StrToInt(Chars[0]))); end; else ERRORS.INTERNAL; CItem := nil; end; Result := TIDExpression.Create(CItem, ID.TextPosition); end; function TASTDelphiUnit.ParseForInStatement(Scope: TScope; const SContext: TSContext; LoopVar: TIDExpression): TTokenID; var EContext: TEContext; LExpr: TIDExpression; LoopArrayDT: TIDType; ASTExpr: TASTExpression; KW: TASTKWForIn; BodySContext: TSContext; AWasCall: Boolean; begin ASTExpr := TASTExpression.Create(nil); ASTExpr.AddDeclItem(LoopVar.Declaration, LoopVar.TextPosition); KW := SContext.Add(TASTKWForIn) as TASTKWForIn; KW.VarExpr := ASTExpr; // парсим выражение-коллекцию InitEContext(EContext, SContext, ExprRValue); Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, EContext, ASTExpr); KW.ListExpr := ASTExpr; LExpr := EContext.Result; LExpr := CheckAndCallFuncImplicit(SContext, LExpr, {out} AWasCall); // expression is array: if (LExpr.DataType is TIDArray) then begin LoopArrayDT := (LExpr.DataType as TIDArray).ElementDataType; if Assigned(LoopVar.DataType) then begin // match loop var type to the array element type if MatchImplicit(LoopVar.DataType, LoopArrayDT) = nil then ERRORS.INCOMPATIBLE_TYPES(LoopVar, LoopArrayDT); end else begin LoopVar.Declaration.DataType := LoopArrayDT; end; end else // expression has enumerator: if LExpr.DataType is TIDStructure then begin var LStruct := TIDStructure(LExpr.DataType); var LCurrentProp: TIDProperty; if LStruct.GetEnumeratorSupported({out} LCurrentProp) then begin // to do: check enumerator if Assigned(LoopVar.DataType) then begin // match loop var type to the enumerator element type if MatchImplicit(LoopVar.DataType, LCurrentProp.DataType) = nil then ERRORS.INCOMPATIBLE_TYPES(LoopVar, LCurrentProp.DataType); end else begin LoopVar.Declaration.DataType := LCurrentProp.DataType; end; end else ERRORS.ARRAY_EXPRESSION_REQUIRED(LExpr); end else ERRORS.ARRAY_EXPRESSION_REQUIRED(LExpr); Lexer_MatchToken(Result, token_do); Lexer_NextToken(Scope); BodySContext := SContext.MakeChild(Scope, KW.Body); Result := ParseStatements(Scope, BodySContext, False); end; type TILCondition = (cNone, cEqual, cNotEqual, cGreater, cGreaterOrEqual, cLess, cLessOrEqual, cZero, cNonZero); function TASTDelphiUnit.ParseForStatement(Scope: TScope; const SContext: TSContext): TTokenID; var EContext: TEContext; BodySContext: TSContext; ID: TIdentifier; LoopVar: TIDDeclaration; LExpr, StartExpr, StopExpr: TIDExpression; NewScope: TScope; KW: TASTKWFor; JMPCondition: TILCondition; ASTExpr: TASTExpression; WriteIL: Boolean; begin // цикловая переменная Result := Lexer_NextToken(Scope); if Result = token_var then begin Lexer_ReadNextIdentifier(Scope, ID); NewScope := TScope.Create(stLocal, Scope); LoopVar := TIDVariable.Create(NewScope, ID); NewScope.AddVariable(TIDVariable(LoopVar)); Scope := NewScope; end else begin Lexer_ReadCurrIdentifier(ID); LoopVar := FindID(Scope, ID); end; InitEContext(EContext, SContext, ExprRValue); // заталкиваем в стек левое выражение LExpr := TIDExpression.Create(LoopVar, ID.TextPosition); EContext.RPNPushExpression(LExpr); Result := Lexer_NextToken(Scope); {если это цикл for ... in ...} if Result = token_in then begin Result := ParseForInStatement(Scope, SContext, LExpr); Exit; end; KW := SContext.Add(TASTKWFor) as TASTKWFor; BodySContext := SContext.MakeChild(Scope, KW.Body); Lexer_MatchToken(Result, token_assign); if LoopVar.DataType = nil then LoopVar.DataType := Sys._Int32 else if (LoopVar.ItemType <> itVar) or not (LoopVar.DataType.IsOrdinal) then AbortWork(sForLoopIndexVarsMastBeSimpleIntVar, Lexer_Position); // начальное значение Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, EContext, ASTExpr); KW.ExprInit := ASTExpr; StartExpr := EContext.Result; CheckEmptyExpression(StartExpr); // пишем инструкцию присваениея начального значения EContext.RPNPushOperator(opAssignment); EContext.RPNFinish(); // устанавливаем флаг цикловой переменной with TIDVariable(LoopVar) do Flags := Flags + [VarLoopIndex]; // to/downto keyword case Result of token_to: JMPCondition := cGreater; token_downto: JMPCondition := cLess; else begin AbortWork(sKeywordToOrDowntoExpected, Lexer_PrevPosition); JMPCondition := cNone; end; end; // конечное значение InitEContext(EContext, SContext, ExprRValue); Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, EContext, ASTExpr); KW.ExprTo := ASTExpr; StopExpr := EContext.Result; CheckEmptyExpression(StopExpr); // если для вычисления конечного выражения использовалась временная переменная // помечаем ее как постоянно используемую в блоке FOR цикла if StopExpr.IsTMPVar then StopExpr.AsVariable.IncludeFlags([VarLoopIndex]); // проверка на константы if (StartExpr.ItemType = itConst) and (StopExpr.ItemType = itConst) then begin WriteIL := ((JMPCondition = cGreater) and (StartExpr.AsIntConst.Value <= StopExpr.AsIntConst.Value)) or ((JMPCondition = cLess) and (StartExpr.AsIntConst.Value >= StopExpr.AsIntConst.Value)); if not WriteIL then Warning(sForOrWhileLoopExecutesZeroTimes, [], StartExpr.TextPosition); end; // тело цикла Lexer_MatchToken(Result, token_do); Result := Lexer_NextToken(Scope); if Result <> token_semicolon then Result := ParseStatements(Scope, BodySContext, False); // сбрасываем флаг цикловой переменной with TIDVariable(LoopVar) do Flags := Flags - [VarLoopIndex]; end; function TASTDelphiUnit.ParseGenericsArgs(Scope: TScope; const SContext: TSContext; out Args: TIDExpressions): TTokenID; var EContext: TEContext; Expr: TIDExpression; ArgsCount: Integer; ASTE: TASTExpression; begin ArgsCount := 0; while true do begin InitEContext(EContext, SContext, ExprNestedGeneric); Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, EContext, ASTE); Expr := EContext.Result; if Assigned(Expr) then begin {if Expr.DataType = Sys._Boolean then begin if (Expr.ItemType = itVar) and Expr.IsAnonymous then Bool_CompleteImmediateExpression(EContext, Expr); end;} end else ERRORS.EXPRESSION_EXPECTED; Inc(ArgsCount); SetLength(Args, ArgsCount); Args[ArgsCount - 1] := EContext.RPNPopExpression(); case Result of token_coma: begin continue; end; token_above: begin Result := Lexer_NextToken(Scope); Break; end; else ERRORS.INCOMPLETE_STATEMENT('generics args'); end; end; end; function TASTDelphiUnit.ParseGenericsConstraint(Scope: TScope; out AConstraint: TGenericConstraint; out AConstraintType: TIDType): TTokenID; begin AConstraint := gsNone; AConstraintType := nil; Result := Lexer_NextToken(Scope); while true do begin case Result of token_class: begin case AConstraint of gsNone: AConstraint := gsClass; gsConstructor: AConstraint := gsClassAndConstructor; else ERRORS.GENERIC_INVALID_CONSTRAINT(Result); end; AConstraintType := TSYSTEMUnit(SysUnit)._TObject; end; token_constructor: begin case AConstraint of gsNone: AConstraint := gsConstructor; gsClass: AConstraint := gsClassAndConstructor; else ERRORS.GENERIC_INVALID_CONSTRAINT(Result); end; AConstraintType := TSYSTEMUnit(SysUnit)._TObject; end; token_record: begin if AConstraint = gsNone then begin AConstraint := gsRecord; Exit; end else ERRORS.GENERIC_INVALID_CONSTRAINT(Result); end; token_identifier, token_id_or_keyword: begin if AConstraint = gsNone then begin var AID: TIdentifier; Lexer_ReadCurrIdentifier(AID); var ADeclaration := FindID(Scope, AID); if (ADeclaration.ItemType = itType) and (TIDType(ADeclaration).DataTypeID in [dtClass, dtInterface]) then begin AConstraintType := TIDType(ADeclaration); AConstraint := gsType; Exit; end; end; ERRORS.GENERIC_INVALID_CONSTRAINT(Result); end; token_above: begin if AConstraint = gsNone then ERRORS.GENERIC_INVALID_CONSTRAINT(Result); Exit; end; else ERRORS.GENERIC_INVALID_CONSTRAINT(Result); end; Result := Lexer_NextToken(Scope); end; end; function TASTDelphiUnit.ParseGenericsHeader(Scope: TScope; out Args: TIDTypeArray): TTokenID; var ID: TIdentifier; ParamsCount, ParamsInGroupCount, ComaCount: Integer; ParamDecl: TIDGenericParam; begin ComaCount := 0; ParamsCount := 0; ParamsInGroupCount := 0; while True do begin Result := Lexer_NextToken(Scope); case Result of token_identifier: begin Lexer_ReadCurrIdentifier(ID); ParamDecl := TIDGenericParam.Create(Scope, ID); InsertToScope(Scope, ParamDecl); Inc(ParamsCount); Inc(ParamsInGroupCount); SetLength(Args, ParamsCount); Args[ParamsCount - 1] := ParamDecl; end; token_colon: begin if ParamsInGroupCount = 0 then ERRORS.IDENTIFIER_EXPECTED(); // parse generic constraint var AConstraint: TGenericConstraint; var AConstraintType: TIDType; Result := ParseGenericsConstraint(Scope, {out} AConstraint, {out} AConstraintType); // set constraint to all params in the group (like in <A, B, C: class>) for var AIndex := ParamsInGroupCount - 1 downto 0 do begin ParamDecl := TIDGenericParam(Args[ParamsInGroupCount - ParamsCount]); ParamDecl.Constraint := AConstraint; ParamDecl.ConstraintType := AConstraintType; end; if Result = token_above then Break; ParamsInGroupCount := 0; end; token_coma: begin if ComaCount >= ParamsCount then ERRORS.IDENTIFIER_EXPECTED(); Inc(ComaCount); end; token_above: begin if ParamsCount = 0 then AbortWork(sNoOneTypeParamsWasFound, Lexer_PrevPosition); if ComaCount >= ParamsCount then ERRORS.IDENTIFIER_EXPECTED(); Break; end; else ERRORS.IDENTIFIER_EXPECTED(); end; end; Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseGenericTypeSpec(Scope: TScope; const ID: TIdentifier; out DataType: TIDType): TTokenID; var GenericArgs: TIDExpressions; SearchName: string; begin Result := ParseGenericsArgs(Scope, fUnitSContext, GenericArgs); SearchName := format('%s<%d>', [ID.Name, Length(GenericArgs)]); var LGenericType := TIDType(FindIDNoAbort(Scope, SearchName)); if Assigned(LGenericType) then begin if not LGenericType.GenericDeclInProgress and not IsGenericTypeThisStruct(Scope, LGenericType) then begin // new call: DataType := InstantiateGenericType(Scope, LGenericType, GenericArgs); //DataType := SpecializeGenericType(DataType, ID, GenericArgs); end; end else ERRORS.UNDECLARED_ID(ID {todo: generic params}); end; function TASTDelphiUnit.ParseGoToStatement(Scope: TScope; const SContext: TSContext): TTokenID; var ID: TIdentifier; LDecl: TIDDeclaration; KW: TASTKWGoTo; begin Lexer_ReadNextIdentifier(Scope, ID); LDecl := FindID(Scope, ID); CheckLabelExpression(LDecl); KW := SContext.Add(TASTKWGoTo) as TASTKWGoTo; KW.LabelDecl := LDecl; Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseIfThenStatement(Scope: TScope; const SContext: TSContext): TTokenID; var Expression: TIDExpression; EContext: TEContext; ThenSContext: TSContext; ElseSContext: TSContext; NewScope: TScope; KW: TASTKWIF; CondExpr: TASTExpression; begin KW := SContext.Add(TASTKWIF) as TASTKWIF; InitEContext(EContext, SContext, ExprRValue); Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, EContext, CondExpr); KW.Expression := CondExpr; CheckAndCallFuncImplicit(EContext); Expression := EContext.Result; CheckEmptyExpression(Expression); CheckBooleanExpression(Expression); {then section} Lexer_MatchToken(Result, token_then); Result := Lexer_NextToken(Scope); if Result <> token_semicolon then begin {оптимизация, не создаем лишний scope, если внутри он создастся всеравно} if Result <> token_begin then NewScope := TScope.Create(stLocal, Scope) else NewScope := Scope; ThenSContext := SContext.MakeChild(Scope, KW.ThenBody); Result := ParseStatements(NewScope, ThenSContext, False); end; { else section} if Result = token_else then begin Result := Lexer_NextToken(Scope); {оптимизация, не создаем лишний scope, если внутри он создастся всеравно} if Result <> token_begin then NewScope := TScope.Create(stLocal, Scope) else NewScope := Scope; KW.ElseBody := TASTKWIF.TASTKWIfElseBlock.Create(KW); ElseSContext := SContext.MakeChild(Scope, KW.ElseBody); Result := ParseStatements(NewScope, ElseSContext, False); end; end; function TASTDelphiUnit.ParseImmVarStatement(Scope: TScope; const SContext: TSContext): TTokenID; var i, c: Integer; DataType: TIDType; Expr: TIDExpression; Variable: TIDVariable; Names: TIdentifiersPool; EContext: TEContext; Vars: array of TIDVariable; KW: TASTKWInlineVarDecl; begin c := 0; Names := TIdentifiersPool.Create(1); Result := Lexer_NextToken(Scope); KW := SContext.Add(TASTKWInlineVarDecl) as TASTKWInlineVarDecl; while True do begin Lexer_MatchIdentifier(Result); Names.Add; Lexer_ReadCurrIdentifier(Names.Items[c]); Result := Lexer_NextToken(Scope); if Result = token_Coma then begin Inc(c); Result := Lexer_NextToken(Scope); Continue; end; // parse a type if declared if Result = token_colon then Result := ParseTypeSpec(Scope, DataType) else DataType := nil; SetLength(Vars, c + 1); for i := 0 to c do begin Variable := TIDVariable.Create(Scope, Names.Items[i]); Variable.DataType := DataType; Variable.Visibility := vLocal; Variable.DefaultValue := nil; Variable.Absolute := nil; Scope.AddVariable(Variable); Vars[i] := Variable; KW.AddDecl(Variable); end; // parse a default value if declared if Result = token_assign then begin InitEContext(EContext, SContext, ExprRValue); var ADefaultValueExpr := TIDExpression.Create(Variable, Variable.TextPosition); EContext.RPNPushExpression(ADefaultValueExpr); Lexer_NextToken(Scope); var ASTExpr: TASTExpression := nil; Result := ParseExpression(Scope, SContext, EContext, {out} ASTExpr); KW.Expression := ASTExpr; if not Assigned(DataType) then begin DataType := EContext.Result.DataType; if DataType = Sys._Untyped then ERRORS.COULD_NOT_INFER_VAR_TYPE_FROM_UNTYPED(EContext.Result); for i := 0 to c do Vars[i].DataType := DataType end; EContext.RPNPushOperator(opAssignment); EContext.RPNFinish; end; Lexer_MatchSemicolon(Result); Break; end; end; function TASTDelphiUnit.ParseImportStatement(Scope: TScope; out ImportLib, ImportName: TIDDeclaration): TTokenID; var LibExpr, NameExpr: TIDExpression; begin // читаем имя библиотеки Lexer_NextToken(Scope); Result := ParseConstExpression(Scope, LibExpr, ExprRValue); if Assigned(LibExpr) then begin CheckStringExpression(LibExpr); ImportLib := LibExpr.Declaration; if (Result = token_identifier) and (Lexer_AmbiguousId = token_name) then begin // читаем имя декларации Lexer_NextToken(Scope); Result := ParseConstExpression(Scope, NameExpr, ExprRValue); CheckEmptyExpression(NameExpr); CheckStringExpression(NameExpr); ImportName := NameExpr.Declaration; end else ImportName := nil; end; // else todo: // delayed if Result = token_delayed then Result := Lexer_NextToken(Scope); Lexer_MatchSemicolon(Result); end; function TASTDelphiUnit.ParseLabelSection(Scope: TScope): TTokenID; var ID: TIdentifier; Decl: TASTDelphiLabel; begin while True do begin Lexer_ReadNextIdentifier(Scope, ID); Decl := TASTDelphiLabel.Create(Scope, ID); InsertToScope(Scope, Decl); Result := Lexer_NextToken(Scope); if Result = token_coma then continue; break; end; Lexer_MatchSemicolon(Result); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseParameters(EntryScope: TScope; ParamsScope: TParamsScope): TTokenID; type PIDItem = ^TIDItem; TIDItem = record ID: TIdentifier; Param: TIDVariable; NextItem: PIDItem; end; var DataType: TIDType; Param: TIDVariable; VarFlags: TVariableFlags; DefaultExpr: TIDExpression; IDItem: TIDItem; CurItem: PIDItem; NextItem: PIDItem; begin CurItem := Addr(IDItem); CurItem.Param := nil; CurItem.NextItem := nil; // process param's specifiers (var, out, const) first while True do begin Result := Lexer_NextToken(EntryScope); if (Result = token_closeround) or (Result = token_closeblock) then Exit; VarFlags := [VarParameter]; // todo: process attributes like [constref] if Result = token_openblock then Result := ParseAttribute(EntryScope); case Result of token_const: begin Include(VarFlags, VarConst); Result := Lexer_NextToken(EntryScope); end; token_var: begin Include(VarFlags, VarInOut); Result := Lexer_NextToken(EntryScope); end; token_identifier: begin if Lexer_AmbiguousId = token_out then begin Include(VarFlags, VarOut); Result := Lexer_NextToken(EntryScope); end; end; end; if Result = token_openblock then Result := ParseAttribute(EntryScope); Lexer_MatchIdentifier(Result); while True do begin // read param name Lexer_ReadCurrIdentifier(CurItem.ID); Result := Lexer_NextToken(EntryScope); if Result = token_coma then begin Result := Lexer_NextToken(EntryScope); Lexer_MatchParamNameIdentifier(Result); // one more param with the same datatype New(NextItem); CurItem.NextItem := NextItem; CurItem := NextItem; CurItem.Param := nil; CurItem.NextItem := nil; Continue; end; if Result = token_colon then begin // parse param type Result := ParseTypeSpec(EntryScope, DataType); // open array case if DataType.IsAnonymous and (DataType.DataTypeID = dtDynArray) then DataType.DataTypeID := dtOpenArray; // parse default value if Result = token_equal then begin Lexer_NextToken(EntryScope); Result := ParseConstExpression(EntryScope, DefaultExpr, ExprNested) end else DefaultExpr := nil; end else begin // if type is not specified then it is untyped reference if (VarConst in VarFlags) or (VarInOut in VarFlags) or (VarOut in VarFlags) or (VarConstRef in VarFlags) then begin DataType := Sys._UntypedReference; end else ERRORS.PARAM_TYPE_REQUIRED; end; NextItem := addr(IDItem); while Assigned(NextItem) do begin if not Assigned(NextItem.Param) then begin Param := TIDParameter.Create(EntryScope, NextItem.ID, DataType, VarFlags); Param.DefaultValue := DefaultExpr; NextItem.Param := Param; end; NextItem := NextItem.NextItem; end; Break; end; if Result = token_semicolon then begin New(NextItem); CurItem.NextItem := NextItem; CurItem := NextItem; CurItem.Param := nil; CurItem.NextItem := nil; continue; end; // insert params to proc scope NextItem := addr(IDItem); while Assigned(NextItem) do begin Param := NextItem.Param; ParamsScope.AddExplicitParam(Param); NextItem := NextItem.NextItem; end; // disposing items memory CurItem := Addr(IDItem); CurItem := CurItem.NextItem; while Assigned(CurItem) do begin NextItem := CurItem; CurItem := CurItem.NextItem; Dispose(NextItem); end; Exit; end; end; function TASTDelphiUnit.ParsePlatform(Scope: TScope): TTokenID; begin Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.GetPtrReferenceType(Decl: TIDPointer): TIDType; begin Result := Decl.ReferenceType; // if the type has been declared as forward, find the reference type // for searching use all parent scopes if not Assigned(Result) and Decl.NeedForward then begin var TypeDecl := FindID(Decl.Scope, Decl.ForwardID); if TypeDecl.ItemType <> itType then AbortWork(sTypeIdExpectedButFoundFmt, [Decl.ForwardID.Name], Decl.ForwardID.TextPosition); Decl.ReferenceType := TIDType(TypeDecl); Result := TIDType(TypeDecl); end; end; function TASTDelphiUnit.ParsePointerType(Scope: TScope; const ID: TIdentifier; out Decl: TIDPointer): TTokenID; var TmpID: TIdentifier; DataType: TIDType; begin Lexer_ReadNextIdentifier(Scope, TmpID); DataType := TIDType(FindIDNoAbort(Scope, TmpID)); // use the target type if it has been declared in the same unit if Assigned(DataType) and (DataType.Scope.DeclUnit = Self) then begin if DataType.ItemType <> itType then AbortWork(sTypeIdExpectedButFoundFmt, [TmpID.Name], Lexer.Position); if ID.Name = '' then begin Decl := DataType.GetDefaultReference(Scope) as TIDPointer; {признак, что этот анонимный тип является ссылкой на структуру которая еще не закончена} if (Decl.ReferenceType is TIDStructure) and (Scope.ScopeType = stStruct) and (Decl.ReferenceType = TStructScope(Scope).Struct) then Decl.NeedForward := True; end else begin Decl := TIDPointer.Create(Scope, ID); Decl.ReferenceType := DataType; InsertToScope(Scope, Decl); end; end else begin // if not, postpone it to first using Decl := TIDPointer.Create(Scope, ID); Decl.ForwardID := TmpID; Decl.NeedForward := True; fForwardPtrTypes.Add(Decl); if ID.Name <> '' then InsertToScope(Scope, Decl); end; Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseProcBody(Proc: TASTDelphiProc): TTokenID; var Scope: TScope; SContext: TSContext; begin Scope := Proc.EntryScope; Result := Lexer_CurTokenID; while true do begin case Result of token_eof: Exit; token_var: begin Lexer_NextToken(Scope); Result := ParseVarSection(Scope, vLocal, False); end; token_weak: begin Lexer_NextToken(Scope); Result := ParseVarSection(Scope, vLocal, True); end; token_label: Result := ParseLabelSection(Scope); token_const: Result := ParseConstSection(Scope); token_type: Result := ParseNamedTypeDecl(Scope); token_procedure: Result := ParseProcedure(Scope, ptProc); token_function: Result := ParseProcedure(Scope, ptFunc); token_identifier: ERRORS.KEYWORD_EXPECTED; token_asm: begin // skip the asm...end block Lexer_SkipBlock(token_end); Result := Lexer_NextToken(Scope); Exit; end; token_begin: begin Proc.FirstBodyLine := Lexer_Line; Proc.Body := TASTBlock.Create(Proc); //SContext.Initialize; //SContext.IL := TIL(Proc.IL); SContext := TSContext.Create(Self, Scope, Proc, Proc.Body); //CheckInitVariables(@SContext, nil, @Proc.VarSpace); Lexer_NextToken(Scope); Result := ParseStatements(Scope, SContext, True); Lexer_MatchToken(Result, token_end); Result := Lexer_NextToken(Scope); Proc.LastBodyLine := Lexer_Line; // геренация кода процедуры завершено Proc.Flags := Proc.Flags + [pfCompleted]; //BENodesPool.Clear; Exit; end; else ERRORS.BEGIN_KEYWORD_EXPECTED; end; end; end; procedure CopyExplicitParams(SrcScope, DstScope: TProcScope); begin var Node := SrcScope.First; while Assigned(Node) do begin if TIDVariable(Node.Data).IsExplicit then DstScope.InsertNode(Node.Key, Node.Data); Node := SrcScope.Next(Node); end; end; function SearchInstanceMethodDecl(Struct: TIDStructure; const ID: TIdentifier; out ForwardDeclNode: TIDList.PAVLNode): TASTDelphiProc; begin Result := nil; ForwardDeclNode := Struct.Members.Find(ID.Name); if not Assigned(ForwardDeclNode) then begin // second, search the decl including ancestors Result := Struct.Members.FindMembers(ID.Name) as TASTDelphiProc; // third, if this is a helper, search the decl in the helper's target if not Assigned(Result) and (Struct is TDlphHelper) and (TDlphHelper(Struct).Target is TIDStructure) then ForwardDeclNode := TIDStructure(TDlphHelper(Struct).Target).Members.Find(ID.Name); end; end; function SearchClassMethodDecl(Struct: TIDStructure; const ID: TIdentifier; out ForwardDeclNode: TIDList.PAVLNode): TASTDelphiProc; begin Result := nil; ForwardDeclNode := Struct.StaticMembers.Find(ID.Name); if not Assigned(ForwardDeclNode) then begin // second, search the decl including ancestors Result := Struct.StaticMembers.FindMembers(ID.Name) as TASTDelphiProc; // third, if this is a helper, search the decl in the helper's target if not Assigned(Result) and (Struct is TDlphHelper) and (TDlphHelper(Struct).Target is TIDStructure) then ForwardDeclNode := TIDStructure(TDlphHelper(Struct).Target).StaticMembers.Find(ID.Name); end; end; function TASTDelphiUnit.ParseProcedure(Scope: TScope; ProcType: TProcType; Struct: TIDStructure): TTokenID; type TFwdDeclState = (dsNew, dsDifferent, dsSame); var ID: TIdentifier; ProcScope: TProcScope; ResultType: TIDType; VarSpace: TVarSpace; GenericsParams: TIDTypeArray; Proc, ForwardDecl: TASTDelphiProc; ForwardDeclNode: TIDList.PAVLNode; FwdDeclState: TFwdDeclState; SRCProcPos: TParserPosition; CallConv: TCallConvention; ProcFlags: TProcFlags; ForwardScope: TScope; ImportLib, ImportName: TIDDeclaration; begin ForwardScope := Scope; Result := ParseProcName(Scope, ProcType, {out} ID, {var} Struct, {out} ProcScope, {out} GenericsParams); if not Assigned(Struct) then begin if Scope.ScopeClass <> scProc then Result := ParseGlobalProc(Scope, ProcType, ID, ProcScope) else Result := ParseNestedProc(Scope, ProcType, ID, ProcScope); Exit; end; VarSpace.Initialize; ProcScope.VarSpace := addr(VarSpace); if ProcType in [ptFunc, ptProc, ptClassFunc, ptClassProc, ptConstructor, ptDestructor] then AddSelfParameter(ProcScope, Struct, (ProcType = ptClassProc) or (ProcType = ptClassFunc)); Lexer.SaveState(SRCProcPos); // parse parameters if Result = token_openround then begin ParseParameters(ProcScope, ProcScope.ParamsScope); Result := Lexer_NextToken(Scope); end; // parse result type if ProcType <= ptStaticFunc then begin Lexer_MatchToken(Result, token_colon); Result := ParseTypeSpec(ProcScope, ResultType); AddResultParameter(ProcScope, ResultType); end else ResultType := nil; if Result = token_semicolon then Result := Lexer_NextToken(Scope) else if not (Result in [token_overload, token_stdcall, token_cdecl]) then ERRORS.SEMICOLON_EXPECTED; case ProcType of ptClassFunc, ptClassProc: ProcFlags := [pfClass]; ptStaticFunc, ptStaticProc: ProcFlags := [pfStatic]; ptConstructor: begin if (Struct.DataTypeID = dtRecord) and (ProcScope.ExplicitParamsCount = 0) then ERRORS.PARAMETERLESS_CTOR_NOT_ALLOWED_ON_RECORD(Lexer_PrevPosition); ProcFlags := [pfConstructor]; end; ptDestructor: ProcFlags := [pfDestructor]; else ProcFlags := []; end; CallConv := TCallConvention.ConvNative; // parse proc specifiers while True do begin case Result of token_forward: Result := ProcSpec_Forward(Scope, ProcFlags); token_export: Result := ProcSpec_Export(Scope, ProcFlags); token_inline: Result := ProcSpec_Inline(Scope, ProcFlags); token_external: Result := ProcSpec_External(Scope, ImportLib, ImportName, ProcFlags); token_overload: Result := ProcSpec_Overload(Scope, ProcFlags); token_virtual: Result := ProcSpec_Virtual(Scope, Struct, ProcFlags); token_dynamic: Result := ProcSpec_Dynamic(Scope, Struct, ProcFlags); token_abstract: Result := ProcSpec_Abstract(Scope, Struct, ProcFlags); token_override: Result := ProcSpec_Override(Scope, Struct, ProcFlags); token_final: Result := ProcSpec_Final(Scope, Struct, ProcFlags); token_reintroduce: Result := ProcSpec_Reintroduce(Scope, ProcFlags); token_static: Result := ProcSpec_Static(Scope, ProcFlags, ProcType); token_stdcall: Result := ProcSpec_StdCall(Scope, CallConv); token_fastcall: Result := ProcSpec_FastCall(Scope, CallConv); token_cdecl: Result := ProcSpec_CDecl(Scope, CallConv); token_varargs: begin Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; token_deprecated: begin Result := CheckAndParseDeprecated(Scope, token_deprecated); Result := Lexer_NextToken(Scope); end; token_id_or_keyword: begin if Lexer_AmbiguousId = token_platform then begin Result := ParsePlatform(Scope); Result := Lexer_NextToken(Scope); end; end; else break; end; end; ForwardDecl := nil; ForwardDeclNode := nil; // search the procedure forward declaration // first, search the decl in the current members only if ProcType = ptClassConstructor then ForwardDecl := Struct.ClassConstructor as TASTDelphiProc else if ProcType = ptClassDestructor then ForwardDecl := Struct.ClassDestructor as TASTDelphiProc else if IsClassProc(ProcType) then ForwardDecl := SearchClassMethodDecl(Struct, ID, {out} ForwardDeclNode) else ForwardDecl := SearchInstanceMethodDecl(Struct, ID, {out} ForwardDeclNode); if not Assigned(ForwardDecl) and not Assigned(ForwardDeclNode) and (Scope.ScopeClass = scImplementation) then ERRORS.METHOD_NOT_DECLARED_IN_CLASS(ID, Struct); if Assigned(ForwardDeclNode) and not Assigned(ForwardDecl) then ForwardDecl := TASTDelphiProc(ForwardDeclNode.Data); Proc := nil; FwdDeclState := dsDifferent; {if found forward declaration, process overload} if Assigned(ForwardDecl) then begin // ошибка если перекрыли идентификатор другого типа: if ForwardDecl.ItemType <> itProcedure then ERRORS.ID_REDECLARATED(ID); // The case when proc impl doesn't have params at all insted of decl if (Scope.ScopeClass = scImplementation) and (ProcScope.ExplicitParamsCount = 0) and (ForwardDecl.PrevOverload = nil) then begin FwdDeclState := dsSame; Proc := ForwardDecl; ProcScope.CopyFrom(ForwardDecl.ParamsScope); end else begin // search overload var Decl := ForwardDecl; while True do begin if Decl.SameDeclaration(ProcScope.ExplicitParams) then begin if Decl.Scope = Scope then begin FwdDeclState := dsSame; if not (pfForward in Decl.Flags) or (pfCompleted in Decl.Flags) then ERRORS.ID_REDECLARATED(ID); Proc := Decl; end else if (Decl.Scope.ScopeClass = scInterface) and (Scope.ScopeClass = scImplementation) then begin Proc := Decl; FwdDeclState := dsSame; end else FwdDeclState := dsNew; Break; end; if not Assigned(Decl.PrevOverload) then Break; Decl := TASTDelphiProc(Decl.PrevOverload); end; end; end else FwdDeclState := dsNew; {create a new declaration} if not Assigned(Proc) then begin Proc := TASTDelphiProc.Create(Scope, ID); // если это generic-процедура или это generic-метод if Assigned(GenericsParams) then Proc.CreateGenericDescriptor(GenericsParams, SRCProcPos) else if Assigned(Struct.GenericDescriptor) then Proc.CreateGenericDescriptor(Struct.GenericDescriptor.GenericParams, SRCProcPos); // Для Scope будут переопределены VarSpace и ProcSpace Proc.ParamsScope := ProcScope; Proc.EntryScope := ProcScope; Proc.VarSpace := VarSpace; Proc.ResultType := ResultType; ProcScope.Proc := Proc; if Scope.ScopeClass = scInterface then Proc.Flags := Proc.Flags + [pfForward]; Proc.ExplicitParams := ProcScope.ExplicitParams; // добовляем новую декларацию в структуру или глобольный список или к списку перегруженных процедур if not Assigned(ForwardDecl) then begin Proc.Struct := Struct; case ProcType of ptConstructor: begin // constructor should be added to both scopes (instance and static) Scope.AddProcedure(Proc); Struct.StaticMembers.InsertID(Proc); end; ptClassConstructor: begin // class constructor doesn't need to be added to the scope if Assigned(Struct.ClassConstructor) then ERRORS.CLASS_CONSTRUCTOR_ALREADY_EXIST(Proc); Struct.ClassConstructor := Proc; end; ptClassDestructor: begin // class destructor doesn't need to be added to the scope if Assigned(Struct.ClassDestructor) then ERRORS.CLASS_DESTRUCTOR_ALREADY_EXIST(Proc); Struct.ClassDestructor := Proc; end; else Scope.AddProcedure(Proc); end; end else begin // доавляем в список следующую перегруженную процедуру Proc.PrevOverload := ForwardDecl; // override the declaration if the scope the same if (ForwardDecl.Scope = Scope) then ForwardDeclNode.Data := Proc else if not Scope.InsertID(Proc) then ERRORS.ID_REDECLARATED(Proc); //special case for constructors, we need to place overloaded contructor in the static scope as well if ProcType = ptConstructor then begin SearchClassMethodDecl(Struct, ID, {out} ForwardDeclNode); if Assigned(ForwardDeclNode) then ForwardDeclNode.Data := Proc else Struct.StaticMembers.InsertID(Proc); end; if IsClassProc(ProcType) then Struct.StaticMembers.ProcSpace.Add(Proc) else Struct.Members.ProcSpace.Add(Proc); Proc.Struct := Struct; end; end else begin if Assigned(Proc.GenericDescriptor) then Proc.GenericDescriptor.ImplSRCPosition := SRCProcPos; end; CallConv := ConvNative; Proc.Flags := Proc.Flags + ProcFlags; Proc.CallConvention := CallConv; // check overload/override if Scope.ScopeClass = scInterface then begin if pfOverride in ProcFlags then begin if not Proc.IsClassMethod then Proc.InheritedProc := Struct.FindVirtualInstanceProcInAncestor(Proc) else Proc.InheritedProc := Struct.FindVirtualClassProcInAncestor(Proc); if not Assigned(Proc.InheritedProc) then begin if not Proc.IsClassMethod then Proc.InheritedProc := Struct.FindVirtualInstanceProcInAncestor(Proc) else Proc.InheritedProc := Struct.FindVirtualClassProcInAncestor(Proc); ERRORS.NO_METHOD_IN_BASE_CLASS(Proc); end; end; if Assigned(ForwardDecl) and (Struct = ForwardDecl.Struct) and not ((pfOveload in ForwardDecl.Flags) or (pfOveload in ProcFlags)) and not Assigned(Proc.InheritedProc) then ERRORS.OVERLOADED_MUST_BE_MARKED(ID); end; if (Scope.ScopeClass <> scInterface) and not (pfImport in ProcFlags) and not (pfForward in ProcFlags) then begin // имена парметров реализации процедуры могут отличатся от ее определения // копируем накопленный VarSpace в процедуру Proc.VarSpace := VarSpace; ProcScope.ProcSpace := Proc.ProcSpace; // use initial EntryScope (declared parameters) // just set Implementation scope as outer scope for the Entry Proc.EntryScope.OuterScope := ProcScope.OuterScope; if (FwdDeclState = dsDifferent) and not (pfOveload in ProcFlags) then begin if Proc.IsCompleted then ERRORS.OVERLOADED_MUST_BE_MARKED(ID) else ERRORS.DECL_DIFF_WITH_PREV_DECL(ID, ForwardDecl.DisplayName, Proc.DisplayName); end; Result := ParseProcBody(Proc); if Result = token_eof then Exit; if Result <> token_semicolon then ERRORS.SEMICOLON_EXPECTED; Result := Lexer_NextToken(Scope); end; if (ProcType = ptDestructor) and (Struct.DataTypeID = dtClass) then CheckDestructorSignature(Proc); end; function TASTDelphiUnit.ParseGlobalProc(Scope: TScope; ProcType: TProcType; const ID: TIdentifier; ProcScope: TProcScope): TTokenID; type TFwdDeclState = (dsNew, dsDifferent, dsSame); var ResultType: TIDType; VarSpace: TVarSpace; Proc, ForwardDecl: TASTDelphiProc; ForwardDeclNode: TIDList.PAVLNode; FwdDeclState: TFwdDeclState; CallConv: TCallConvention; ProcFlags: TProcFlags; ImportLib, ImportName: TIDDeclaration; begin VarSpace.Initialize; ProcScope.VarSpace := addr(VarSpace); Result := Lexer_CurTokenID; // parse parameters if Result = token_openround then begin ParseParameters(ProcScope, ProcScope.ParamsScope); Result := Lexer_NextToken(Scope); end; // parse return type if ProcType = ptFunc then begin if Result <> token_semicolon then begin Lexer_MatchToken(Result, token_colon); Result := ParseTypeSpec(ProcScope, ResultType); AddResultParameter(ProcScope, ResultType); end else ResultType := nil; end else ResultType := nil; if Result = token_semicolon then Result := Lexer_NextToken(Scope) else if not (Result in [token_overload, token_stdcall, token_cdecl]) then ERRORS.SEMICOLON_EXPECTED; ProcFlags := []; // parse proc specifiers while True do begin case Result of token_forward: Result := ProcSpec_Forward(Scope, ProcFlags); token_export: Result := ProcSpec_Export(Scope, ProcFlags); token_inline: Result := ProcSpec_Inline(Scope, ProcFlags); token_external: Result := ProcSpec_External(Scope, ImportLib, ImportName, ProcFlags); token_overload: Result := ProcSpec_Overload(Scope, ProcFlags); token_stdcall: Result := ProcSpec_StdCall(Scope, CallConv); token_fastcall: Result := ProcSpec_FastCall(Scope, CallConv); token_cdecl: Result := ProcSpec_CDecl(Scope, CallConv); token_varargs: begin Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; token_deprecated: begin Result := CheckAndParseDeprecated(Scope, token_deprecated); Result := Lexer_NextToken(Scope); end; token_id_or_keyword: begin if Lexer_AmbiguousId = token_platform then begin Result := ParsePlatform(Scope); Result := Lexer_NextToken(Scope); end; end; else break; end; end; ForwardDecl := nil; ForwardDeclNode := nil; {search the procedure forward declaration} // first, search the declaration in the current scope only ForwardDeclNode := Scope.Find(ID.Name); // second, search the declaration in the interface section scope if not Assigned(ForwardDeclNode) and (Scope = ImplScope) then ForwardDeclNode := IntfScope.Find(ID.Name); // third, search in the uses units if not Assigned(ForwardDeclNode) then begin if Scope = ImplScope then begin var LDecl := ImplScope.FindIDRecurcive(ID.Name); if LDecl is TASTDelphiProc then ForwardDecl := TASTDelphiProc(LDecl); end else begin var LDecl := IntfScope.FindIDRecurcive(ID.Name); if LDecl is TASTDelphiProc then ForwardDecl := TASTDelphiProc(LDecl); end; end; if Assigned(ForwardDeclNode) and not Assigned(ForwardDecl) then ForwardDecl := TASTDelphiProc(ForwardDeclNode.Data); Proc := nil; FwdDeclState := dsDifferent; {если найдена ранее обьявленная декларация, проверяем соответствие} if Assigned(ForwardDecl) then begin if (Scope.ScopeClass = scInterface) and (ForwardDecl.Scope.DeclUnit = Self) then begin if not (pfOveload in ForwardDecl.Flags) then ERRORS.OVERLOADED_MUST_BE_MARKED(ForwardDecl.ID) else if not (pfOveload in ProcFlags) then ERRORS.OVERLOADED_MUST_BE_MARKED(ID); end; // ошибка если перекрыли идентификатор другого типа: if ForwardDecl.ItemType <> itProcedure then ERRORS.ID_REDECLARATED(ID); // The case when proc impl doesn't have params at all insted of decl if (Scope.ScopeClass = scImplementation) and (ProcScope.ExplicitParamsCount = 0) and (ForwardDecl.PrevOverload = nil) then begin FwdDeclState := dsSame; Proc := ForwardDecl; ProcScope.CopyFrom(ForwardDecl.ParamsScope); end else begin // search overload var Decl := ForwardDecl; while True do begin if Decl.SameDeclaration(ProcScope.ExplicitParams) then begin FwdDeclState := dsSame; if (Decl.Scope = Scope) then begin if Scope.ScopeClass = scInterface then ERRORS.ID_REDECLARATED(ID); end; Proc := Decl; Break; end; if not Assigned(Decl.PrevOverload) then Break; Decl := TASTDelphiProc(Decl.PrevOverload); end; end; end else FwdDeclState := dsNew; {create a new declaration} if not Assigned(Proc) then begin Proc := TASTDelphiProc.Create(Scope, ID); // Для Scope будут переопределены VarSpace и ProcSpace Proc.ParamsScope := ProcScope; Proc.VarSpace := VarSpace; Proc.ResultType := ResultType; ProcScope.Proc := Proc; if Scope.ScopeClass = scInterface then Proc.Flags := Proc.Flags + [pfForward]; Proc.ExplicitParams := ProcScope.ExplicitParams; // добовляем новую декларацию в структуру или глобольный список или к списку перегруженных процедур if not Assigned(ForwardDecl) then begin Scope.AddProcedure(Proc); end else begin // доавляем в список следующую перегруженную процедуру if pfOveload in ProcFlags then Proc.PrevOverload := ForwardDecl; // override the declaration if the scope the same if (ForwardDecl.Scope = Scope) then ForwardDeclNode.Data := Proc else Scope.InsertID(Proc); Scope.ProcSpace.Add(Proc); end; end; CallConv := ConvNative; Proc.Flags := Proc.Flags + ProcFlags; Proc.CallConvention := CallConv; if (Scope.ScopeClass <> scInterface) and not (pfImport in ProcFlags) and not (pfForward in ProcFlags) then begin // имена парметров реализации процедуры могут отличатся от ее определения // копируем накопленный VarSpace в процедуру Proc.VarSpace := VarSpace; ProcScope.ProcSpace := Proc.ProcSpace; Proc.EntryScope := ProcScope; if Assigned(ForwardDecl) and (ForwardDecl.Scope = Scope) and (FwdDeclState = dsDifferent) and not (pfOveload in ProcFlags) then begin if ForwardDecl.IsCompleted then ERRORS.OVERLOADED_MUST_BE_MARKED(ID) else ERRORS.DECL_DIFF_WITH_PREV_DECL(ID, ForwardDecl.DisplayName, Proc.DisplayName); end; // parse proc body Result := ParseProcBody(Proc); if Result = token_eof then Exit; if Result <> token_semicolon then ERRORS.SEMICOLON_EXPECTED; Result := Lexer_NextToken(Scope); end; end; function TASTDelphiUnit.ParseNestedProc(Scope: TScope; ProcType: TProcType; const ID: TIdentifier; ProcScope: TProcScope): TTokenID; type TFwdDeclState = (dsNew, dsDifferent, dsSame); var ResultType: TIDType; VarSpace: TVarSpace; Proc, ForwardDecl: TASTDelphiProc; ForwardDeclNode: TIDList.PAVLNode; FwdDeclState: TFwdDeclState; CallConv: TCallConvention; ProcFlags: TProcFlags; begin VarSpace.Initialize; ProcScope.VarSpace := addr(VarSpace); Result := Lexer_CurTokenID; // parse parameters if Result = token_openround then begin ParseParameters(ProcScope, ProcScope.ParamsScope); Result := Lexer_NextToken(Scope); end; // parse return type if ProcType = ptFunc then begin if Result <> token_semicolon then begin Lexer_MatchToken(Result, token_colon); Result := ParseTypeSpec(ProcScope, ResultType); AddResultParameter(ProcScope, ResultType); end else ResultType := nil; end else ResultType := nil; if Result = token_semicolon then Result := Lexer_NextToken(Scope) else if not (Result in [token_overload, token_stdcall, token_cdecl]) then ERRORS.SEMICOLON_EXPECTED; ProcFlags := []; // parse proc specifiers while True do begin case Result of token_forward: Result := ProcSpec_Forward(Scope, ProcFlags); token_inline: Result := ProcSpec_Inline(Scope, ProcFlags); token_overload: Result := ProcSpec_Overload(Scope, ProcFlags); token_stdcall: Result := ProcSpec_StdCall(Scope, CallConv); token_fastcall: Result := ProcSpec_FastCall(Scope, CallConv); token_cdecl: Result := ProcSpec_CDecl(Scope, CallConv); token_varargs: begin Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; token_deprecated: begin Result := CheckAndParseDeprecated(Scope, token_deprecated); Result := Lexer_NextToken(Scope); end; token_id_or_keyword: begin if Lexer_AmbiguousId = token_platform then begin Result := ParsePlatform(Scope); Result := Lexer_NextToken(Scope); end; end; else break; end; end; ForwardDecl := nil; ForwardDeclNode := nil; {search the procedure forward declaration} // first, search the declaration in the current scope only ForwardDeclNode := Scope.Find(ID.Name); // second, search the declaration in the interface section scope if not Assigned(ForwardDeclNode) and (Scope = ImplScope) then ForwardDeclNode := IntfScope.Find(ID.Name); // third, search in the uses units if not Assigned(ForwardDeclNode) then begin if Scope = ImplScope then begin var LDecl := ImplScope.FindIDRecurcive(ID.Name); if LDecl is TASTDelphiProc then ForwardDecl := TASTDelphiProc(LDecl); end else begin var LDecl := IntfScope.FindIDRecurcive(ID.Name); if LDecl is TASTDelphiProc then ForwardDecl := TASTDelphiProc(LDecl); end; end; if Assigned(ForwardDeclNode) and not Assigned(ForwardDecl) then ForwardDecl := TASTDelphiProc(ForwardDeclNode.Data); Proc := nil; FwdDeclState := dsDifferent; {если найдена ранее обьявленная декларация, проверяем соответствие} if Assigned(ForwardDecl) then begin if (Scope.ScopeClass = scInterface) and (ForwardDecl.Scope.DeclUnit = Self) then begin if not (pfOveload in ForwardDecl.Flags) then ERRORS.OVERLOADED_MUST_BE_MARKED(ForwardDecl.ID) else if not (pfOveload in ProcFlags) then ERRORS.OVERLOADED_MUST_BE_MARKED(ID); end; // ошибка если перекрыли идентификатор другого типа: if ForwardDecl.ItemType <> itProcedure then ERRORS.ID_REDECLARATED(ID); // The case when proc impl doesn't have params at all insted of decl if (ProcScope.ExplicitParamsCount = 0) and (ForwardDecl.PrevOverload = nil) and (ForwardDecl.Scope = Scope) then begin FwdDeclState := dsSame; Proc := ForwardDecl; ProcScope.CopyFrom(ForwardDecl.ParamsScope); end else if (pfOveload in ForwardDecl.Flags) then begin // search overload var Decl := ForwardDecl; while True do begin if Decl.SameDeclaration(ProcScope.ExplicitParams) then begin FwdDeclState := dsSame; if ((Decl.Scope = Scope) and not (pfForward in Decl.Flags)) or ((pfCompleted in Decl.Flags) and (ForwardDecl.Scope.DeclUnit = Self)) then ERRORS.ID_REDECLARATED(ID); Proc := Decl; Break; end; if not Assigned(Decl.PrevOverload) then Break; Decl := TASTDelphiProc(Decl.PrevOverload); end; end else FwdDeclState := dsNew; end else FwdDeclState := dsNew; {create a new declaration} if not Assigned(Proc) then begin Proc := TASTDelphiProc.Create(Scope, ID); // Для Scope будут переопределены VarSpace и ProcSpace Proc.ParamsScope := ProcScope; Proc.VarSpace := VarSpace; Proc.ResultType := ResultType; ProcScope.Proc := Proc; if Scope.ScopeClass = scInterface then Proc.Flags := Proc.Flags + [pfForward]; Proc.ExplicitParams := ProcScope.ExplicitParams; // добовляем новую декларацию в структуру или глобольный список или к списку перегруженных процедур if not Assigned(ForwardDecl) then begin Scope.AddProcedure(Proc); end else begin // доавляем в список следующую перегруженную процедуру if pfOveload in ProcFlags then Proc.PrevOverload := ForwardDecl; // override the declaration if the scope the same if (ForwardDecl.Scope = Scope) then ForwardDeclNode.Data := Proc else Scope.InsertID(Proc); Scope.ProcSpace.Add(Proc); end; end; CallConv := ConvNative; Proc.Flags := Proc.Flags + ProcFlags; Proc.CallConvention := CallConv; if (Scope.ScopeClass <> scInterface) and not (pfImport in ProcFlags) and not (pfForward in ProcFlags) then begin // имена парметров реализации процедуры могут отличатся от ее определения // копируем накопленный VarSpace в процедуру Proc.VarSpace := VarSpace; ProcScope.ProcSpace := Proc.ProcSpace; Proc.EntryScope := ProcScope; if Assigned(ForwardDecl) and (ForwardDecl.Scope = Scope) and (FwdDeclState = dsDifferent) and not (pfOveload in ProcFlags) then begin if ForwardDecl.IsCompleted then ERRORS.OVERLOADED_MUST_BE_MARKED(ID) else ERRORS.DECL_DIFF_WITH_PREV_DECL(ID, ForwardDecl.DisplayName, Proc.DisplayName); end; // parse proc body Result := ParseProcBody(Proc); if Result = token_eof then Exit; if Result <> token_semicolon then ERRORS.SEMICOLON_EXPECTED; Result := Lexer_NextToken(Scope); end; end; function TASTDelphiUnit.ParseProcName(Scope: TScope; ProcType: TProcType; out Name: TIdentifier; var Struct: TIDStructure; out ProcScope: TProcScope; out GenericParams: TIDTypeArray): TTokenID; function GetStructScope(AStruct: TIDStructure; AProcType: TProcType): TScope; begin if AProcType = ptOperator then Result := Struct.Operators else if IsClassProc(ProcType) then Result := Struct.StaticMembers else Result := Struct.Members; end; var Decl: TIDDeclaration; SearchName: string; SearchScope: TScope; begin ProcScope := nil; SearchScope := Scope; while True do begin Lexer_ReadNextIdentifier(Scope, Name); Result := Lexer_NextToken(Scope); if Result = token_less then begin if Assigned(Struct) or Scope.InheritsFrom(TMethodScope) then ProcScope := TMethodScope.CreateInDecl(Scope, GetStructScope(Struct, ProcType), nil) else ProcScope := TProcScope.CreateInDecl(Scope, nil, nil, nil); Result := ParseGenericsHeader(ProcScope, GenericParams); SearchName := Format('%s<%d>', [Name.Name, Length(GenericParams)]); end else SearchName := Name.Name; if Result = token_dot then begin Decl := SearchScope.FindID(SearchName); if not Assigned(Decl) then ERRORS.UNDECLARED_ID(Name, GenericParams); if Decl is TIDStructure then begin Struct := TIDStructure(Decl); SearchScope := Struct.StaticMembers; {т.к это имплементация обобщенного метода, то очищаем дупликатные обобщенные параметры} if Assigned(ProcScope) then begin ProcScope.OuterScope := Scope; ProcScope.Parent := GetStructScope(Struct, ProcType); ProcScope.Clear; end; end else ERRORS.STRUCT_TYPE_REQUIRED(Name.TextPosition); continue; end; if not Assigned(ProcScope) then begin if Assigned(Struct) then ProcScope := TMethodScope.CreateInDecl(Scope, GetStructScope(Struct, ProcType), nil) else ProcScope := TProcScope.CreateInDecl(Scope, nil, nil, nil); end; Exit; end; end; function TASTDelphiUnit.ParseProcType(Scope: TScope; const ID: TIdentifier; GDescriptor: PGenericDescriptor; out Decl: TIDProcType): TTokenID; var ParentScope: TScope; VarSpace: TVarSpace; ResultType: TIDType; ProcClass: TProcTypeClass; IsFunction: Boolean; begin ProcClass := procStatic; Result := Lexer_AmbiguousId; if Result = token_reference then begin ProcClass := procReference; Lexer_ReadToken(Scope, token_to); Result := Lexer_NextToken(Scope); end; case Result of token_procedure: IsFunction := False; token_function: IsFunction := True; else AbortWork('PROCEDURE or FUNCTION required', Lexer_Position); end; Decl := TIDProcType.Create(Scope, ID); Decl.GenericDescriptor := GDescriptor; Result := Lexer_NextToken(Scope); if Assigned(GDescriptor) then ParentScope := GDescriptor.Scope else ParentScope := Scope; // parsing params if Result = token_openround then begin VarSpace.Initialize; var LParamsScope := TParamsScope.Create(stLocal, ParentScope); ParseParameters(ParentScope, LParamsScope); Result := Lexer_NextToken(Scope); Decl.Params := LParamsScope.ExplicitParams; end; // parsing result if this is function if IsFunction then begin Lexer_MatchToken(Result, token_colon); Result := ParseTypeSpec(ParentScope, ResultType); Decl.ResultType := ResultType; end; // parsing of object if Result = token_of then begin Lexer_ReadToken(Scope, token_object); Result := Lexer_NextToken(Scope); ProcClass := procMethod; end; Decl.ProcClass := ProcClass; if ID.Name <> '' then if Assigned(GDescriptor) then InsertToScope(Scope, GDescriptor.SearchName, Decl) else InsertToScope(Scope, Decl); end; function TASTDelphiUnit.ParseGenericProcRepeatedly(Scope: TScope; GenericProc, Proc: TASTDelphiProc; Struct: TIDStructure): TTokenID; {type TFwdDeclState = (dsNew, dsDifferent, dsSame);} var ProcScope: TProcScope; ResultType: TIDType; RetVar: TIDVariable; VarSpace: TVarSpace; CurParserPos: TParserPosition; ProcFlags: TProcFlags; GD: PGenericDescriptor; ImportLib, ImportName: TIDDeclaration; begin GD := GenericProc.GenericDescriptor; if not Assigned(GD) then GD := Struct.GenericDescriptor; if not Assigned(GD) then Assert(Assigned(GD)); {перемещаем парсер на исходный код generic-процедуры} Lexer.SaveState(CurParserPos); Lexer.LoadState(GD.ImplSRCPosition); Result := Lexer_CurTokenID; VarSpace.Initialize; if Assigned(Struct) then ProcScope := TMethodScope.CreateInDecl(Scope, Struct.Members, Proc, @VarSpace, nil) else ProcScope := TProcScope.CreateInDecl(Scope, Proc, @VarSpace, nil); // создаем Result переменную (пока без имени) и добовляем ее в VarSpace чтобы зарезервировать индекс if Assigned(GenericProc.ResultType) then RetVar := AddResultParameter(ProcScope, nil) else RetVar := nil; if Assigned(Struct) then AddSelfParameter(ProcScope, Struct, False); // парсим параметры if Result = token_openround then begin ParseParameters(ProcScope, ProcScope.ParamsScope); Result := Lexer_NextToken(Scope); // move to "token_colon" end; // парсим тип возвращаемого значения ResultType := nil; if Assigned(GenericProc.ResultType) then begin Lexer_MatchToken(Result, token_colon); Result := ParseTypeSpec(ProcScope, {out} ResultType); RetVar.DataType := ResultType; RetVar.TextPosition := Lexer_Position; Proc.ResultType := ResultType; end; Lexer_MatchToken(Result, token_semicolon); if not Assigned(Struct) then begin // Для Scope будут переопределены VarSpace и ProcSpace Proc.ParamsScope := ProcScope; Proc.VarSpace := VarSpace; Proc.ResultType := ResultType; Proc.ExplicitParams := ProcScope.ExplicitParams; ImplScope.AddProcedure(Proc); // добовляем новую декларацию в структуру или глобольный список end; ProcFlags := []; Result := Lexer_NextToken(Scope); while True do begin case Result of token_forward: Result := ProcSpec_Forward(Scope, ProcFlags); token_export: Result := ProcSpec_Export(Scope, ProcFlags); token_inline: Result := ProcSpec_Inline(Scope, ProcFlags); token_external: Result := ProcSpec_External(Scope, ImportLib, ImportName, ProcFlags); token_overload: Result := ProcSpec_Overload(Scope, ProcFlags); token_procedure, token_function, token_const, token_type, token_var, token_begin: begin // т.к синтаксис проверен ранее, флаги процедуры нет необходимости проверять // имена парметров реализации процедуры могут отличатся от ее определения // копируем накопленный VarSpace в процедуру Proc.VarSpace := ProcScope.VarSpace^; // Для Scope будут переопределены VarSpace и ProcSpace Proc.EntryScope := ProcScope; Result := ParseProcBody(Proc); Lexer_MatchSemicolon(Result); Result := Lexer_NextToken(Scope); Break; end; token_identifier: ERRORS.KEYWORD_EXPECTED; else Break; end; end; Lexer.LoadState(CurParserPos); end; function TASTDelphiUnit.ParseOperator(Scope: TScope; Struct: TIDStructure): TTokenID; type TFwdDeclState = (dsNew, dsDifferent, dsSame); var ID: TIdentifier; ProcScope: TProcScope; ResultType: TIDType; VarSpace: TVarSpace; GenericsParams: TIDTypeArray; Proc, ForwardDecl: TASTDelphiProc; FwdDeclState: TFwdDeclState; SRCProcPos: TParserPosition; OperatorID: TOperatorID; ParamCount: Integer; ProcFlags: TProcFlags; ImportLib, ImportName: TIDDeclaration; begin Result := ParseProcName(Scope, ptOperator, {out} ID, {var} Struct, {out} ProcScope, {out} GenericsParams); OperatorID := GetOperatorID(ID.Name); if OperatorID = opNone then AbortWork(sUnknownOperatorFmt, [ID.Name], ID.TextPosition); if not Assigned(Struct) then ERRORS.OPERATOR_MUST_BE_DECLARED_IN_STRUCT(ID.TextPosition); VarSpace.Initialize; ProcScope.VarSpace := @VarSpace; // если generic Lexer.SaveState(SRCProcPos); // парсим параметры Lexer_MatchToken(Result, token_openround); ParseParameters(ProcScope, ProcScope.ParamsScope); Result := Lexer_NextToken(Scope); // проверка на кол-во необходимых параметров ParamCount := IfThen(OperatorID < OpIn, 1, 2); if ParamCount <> ProcScope.ExplicitParamsCount then AbortWork(sOperatorNeedNCountOfParameters, [ID.Name, ParamCount], ID.TextPosition); // парсим тип возвращаемого значения Lexer_MatchToken(Result, token_colon); Result := ParseTypeSpec(ProcScope, ResultType); // создаем Result переменную AddResultParameter(ProcScope, ResultType); Lexer_MatchToken(Result, token_semicolon); // ищем ранее обьявленную декларацию с таким же именем ForwardDecl := TASTDelphiProc(Struct.Operators.FindID(ID.Name)); Proc := nil; FwdDeclState := dsDifferent; {если найдена ранее обьявленная декларация, проверяем соответствие} if Assigned(ForwardDecl) then begin // ошибка если перекрыли идентификатор другого типа: if ForwardDecl.ItemType <> itProcedure then ERRORS.ID_REDECLARATED(ID); // ищем подходящую декларацию в списке перегруженных: while True do begin if ForwardDecl.SameDeclaration(ProcScope.ExplicitParams) then begin // нашли подходящую декларацию FwdDeclState := dsSame; if ForwardDecl.IsCompleted then begin //if ForwardDecl.SameDeclaration(Parameters) then ERRORS.ID_REDECLARATED(ID); end; Proc := ForwardDecl; Break; end; // не нашли подходящую декларацию, создаем новую // проверку дерективы overload оставим на потом if not Assigned(ForwardDecl.PrevOverload) then begin Break; end; ForwardDecl := ForwardDecl.PrevOverload as TASTDelphiProc; end; end else FwdDeclState := dsNew; ProcFlags := [pfOperator]; {создаем новую декларацию} if not Assigned(Proc) then begin Proc := TIDOperator.Create(Struct.Operators, ID, OperatorID); if Assigned(GenericsParams) then Proc.CreateGenericDescriptor(GenericsParams, SRCProcPos); // Для Scope будут переопределены VarSpace и ProcSpace Proc.ParamsScope := ProcScope; Proc.VarSpace := ProcScope.VarSpace^; Proc.ResultType := ResultType; Proc.ExplicitParams := ProcScope.ExplicitParams; Proc.Struct := Struct; // добовляем новую декларацию в структуру или глобольный список или к списку перегруженных процедур if not Assigned(ForwardDecl) then begin Struct.Operators.AddProcedure(Proc); end else begin ForwardDecl.PrevOverload := Proc; Struct.Operators.ProcSpace.Add(Proc); end; case OperatorID of opImplicit: begin if ResultType = Struct then Struct.OverloadImplicitFrom(Proc.ExplicitParams[0].DataType, Proc) else Struct.OverloadImplicitTo(ResultType, Proc); end; opExplicit: begin if ResultType = Struct then Struct.OverloadExplicitFrom(Proc.ExplicitParams[0].DataType, Proc) else Struct.OverloadExplicitTo(ResultType, Proc); end; else if OperatorID < opIn then Struct.OverloadUnarOperator(OperatorID, Proc) else Struct.OverloadBinarOperator(OperatorID, TIDOperator(Proc)); end; end else begin if Assigned(Proc.GenericDescriptor) then Proc.GenericDescriptor.ImplSRCPosition := SRCProcPos; end; Result := Lexer_NextToken(Scope); while True do begin case Result of token_forward: Result := ProcSpec_Forward(Scope, ProcFlags); token_export: Result := ProcSpec_Export(Scope, ProcFlags); token_inline: Result := ProcSpec_Inline(Scope, ProcFlags); token_external: Result := ProcSpec_External(Scope, ImportLib, ImportName, ProcFlags); token_overload: Result := ProcSpec_Overload(Scope, ProcFlags); else if (Scope.ScopeClass = scInterface) or (pfImport in ProcFlags) then begin Proc.Flags := ProcFlags; Break; end; // имена парметров реализации процедуры могут отличатся от ее определения // копируем накопленный VarSpace в процедуру Proc.VarSpace := ProcScope.VarSpace^; // Для Scope будут переопределены VarSpace и ProcSpace Proc.EntryScope := ProcScope; if (FwdDeclState = dsDifferent) then begin if not Proc.IsCompleted then ERRORS.DECL_DIFF_WITH_PREV_DECL(ID, ForwardDecl.DisplayName, Proc.DisplayName); end; Result := ParseProcBody(Proc); Lexer_MatchSemicolon(Result); Result := Lexer_NextToken(Scope); Break; end; //token_identifier: AbortWork(sKeywordExpected, Lexer_Position); {else if Scope.ScopeClass <> scInterface then ERRORS.PROC_NEED_BODY; Break;} end; end; function TASTDelphiUnit.ParseRaiseStatement(Scope: TScope; const SContext: TSContext): TTokenID; var EExcept, EAtAddr: TIDExpression; EContext: TEContext; ASTExpr: TASTExpression; KW: TASTKWRaise; begin Lexer_NextToken(Scope); InitEContext(EContext, SContext, ExprRValue); Result := ParseExpression(Scope, SContext, EContext, ASTExpr); EExcept := EContext.Result; if Assigned(EExcept) then CheckClassExpression(EExcept); if Lexer_AmbiguousId = token_at then begin Lexer_NextToken(Scope); InitEContext(EContext, SContext, ExprRValue); Result := ParseExpression(Scope, SContext, EContext, ASTExpr); EAtAddr := EContext.Result; if Assigned(EExcept) then CheckPointerType(EAtAddr); end; KW := SContext.Add(TASTKWRaise) as TASTKWRaise; KW.Expression := ASTExpr; end; procedure TASTDelphiUnit.ParseRangeType(Scope: TScope; Expr: TIDExpression; const ID: TIdentifier; out Decl: TIDRangeType); var LB, HB: Int64; CRange: TIDRangeConstant; BoundExpr: TIDExpression; RDataTypeID: TDataTypeID; RDataType: TIDType; begin CRange := TIDRangeConstant(Expr.Declaration); if (CRange.ItemType <> itConst) and (not (CRange is TIDRangeConstant)) then AbortWork(sConstRangeRequired, Lexer_Position); BoundExpr := CRange.Value.LBExpression; CheckConstExpression(BoundExpr); LB := TIDConstant(BoundExpr.Declaration).AsInt64; BoundExpr := CRange.Value.HBExpression; CheckConstExpression(BoundExpr); HB := TIDConstant(BoundExpr.Declaration).AsInt64; RDataTypeID := GetValueDataType(HB - LB); RDataType := Sys.DataTypes[RDataTypeID]; Decl := TIDRangeType.Create(Scope, ID); Decl.LoDecl := CRange.Value.LBExpression.AsConst; Decl.HiDecl := CRange.Value.HBExpression.AsConst; Decl.LowBound := LB; Decl.HighBound := HB; Decl.OverloadImplicitFrom(RDataType); end; function TASTDelphiUnit.ParseRecordInitValue(Scope: TRecordInitScope; var FirstField: TIDExpression): TTokenID; var FldValue: TIDExpression; begin Lexer_NextToken(Scope); Result := ParseConstExpression(Scope, FldValue, ExprRValue); if Result = token_semicolon then Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseRecordType(Scope: TScope; Decl: TIDRecord): TTokenID; var Visibility: TVisibility; begin Visibility := vPublic; Result := Lexer_CurTokenID; while True do begin case Result of token_openblock: Result := ParseAttribute(Scope); token_case: Result := ParseCaseRecord(Decl.Members, Decl); token_class: begin Result := Lexer_NextToken(scope); case Result of token_procedure: Result := ParseProcedure(Decl.StaticMembers, ptClassProc, Decl); token_function: Result := ParseProcedure(Decl.StaticMembers, ptClassFunc, Decl); token_operator: Result := ParseOperator(Decl.Operators, Decl); token_property: Result := ParseProperty(Decl.StaticMembers, Decl); token_constructor: Result := ParseProcedure(Decl.StaticMembers, ptClassConstructor, Decl); token_destructor: Result := ParseProcedure(Decl.StaticMembers, ptClassDestructor, Decl); token_var: begin Lexer_NextToken(Scope); Result := ParseFieldsSection(Decl.StaticMembers, Visibility, Decl, True); end; else AbortWork('Class members can be: PROCEDURE, FUNCTION, OPERATOR, CONSTRUCTOR, DESTRUCTOR, PROPERTY, VAR', Lexer_Position); end; end; token_procedure: Result := ParseProcedure(Decl.Members, ptProc, Decl); token_function: Result := ParseProcedure(Decl.Members, ptFunc, Decl); token_constructor: Result := ParseProcedure(Decl.Members, ptConstructor, Decl); token_destructor: Result := ParseProcedure(Decl.Members, ptDestructor, Decl); token_property: Result := ParseProperty(Decl.Members, Decl); token_public: begin Visibility := vPublic; Result := Lexer_NextToken(Scope); end; token_private: begin Visibility := vPrivate; Result := Lexer_NextToken(Scope); end; token_strict: begin Result := Lexer_NextToken(Scope); case Result of token_private: Visibility := vStrictPrivate; token_protected: Visibility := vStrictProtected; else ERRORS.EXPECTED_TOKEN(token_private, Result); end; Result := Lexer_NextToken(Scope); end; token_var: begin Lexer_NextToken(Scope); Result := ParseFieldsSection(Decl.Members, Visibility, Decl, False); end; token_const: Result := ParseConstSection(Decl.StaticMembers); token_type: Result := ParseNamedTypeDecl(Decl.StaticMembers); // необходимо оптимизировать парсинг ключевых слов как идентификаторов token_identifier, token_name: Result := ParseFieldsSection(Decl.Members, Visibility, Decl, False); else break; end; end; CheckIncompleteType(Decl.Members); Decl.StructFlags := Decl.StructFlags + [StructCompleted]; Lexer_MatchToken(Result, token_end); Result := Lexer_NextToken(Scope); // check for align keyword if Lexer_AmbiguousId = token_aling then begin Lexer_NextToken(Scope); var AlignValueExpr: TIDExpression; Result := ParseConstExpression(Scope, {out} AlignValueExpr, ExprRValue); end; if Lexer_IsCurrentToken(token_platform) then Result := ParsePlatform(Scope); Result := CheckAndParseDeprecated(Scope, Result); end; function FindGenericInstance(const GenericInstances: TGenericInstanceList; const SpecializeArgs: TIDExpressions): TIDDeclaration; var i, ac, ai: Integer; Item: ^TGenericInstance; SrcArg, DstArg: TIDExpression; SrcType, DstType: TIDType; begin for i := 0 to Length(GenericInstances) - 1 do begin Item := addr(GenericInstances[i]); ac := Length(SpecializeArgs); if ac <> Length(Item.Args) then AbortWorkInternal('Wrong length generics arguments'); for ai := 0 to ac - 1 do begin DstArg := Item.Args[ai]; SrcArg := SpecializeArgs[ai]; // тут упрощенная проверка: SrcType := SrcArg.AsType.ActualDataType; DstType := DstArg.AsType.ActualDataType; if SrcType <> DstType then begin if (SrcType.DataTypeID = dtGeneric) and (DstType.DataTypeID = dtGeneric) then continue; Item := nil; break; end; end; if Assigned(Item) then Exit(Item.Instance); end; Result := nil; end; procedure TASTDelphiUnit.SetProcGenericArgs(CallExpr: TIDCallExpression; Args: TIDExpressions); var Proc: TIDProcedure; ArgsCount, ParamsCount: Integer; GDescriptor: PGenericDescriptor; begin Proc := CallExpr.AsProcedure; GDescriptor := Proc.GenericDescriptor; if not Assigned(GDescriptor) then AbortWork(sProcHasNoGenericParams, [Proc.ProcTypeName, Proc.DisplayName], CallExpr.TextPosition); ParamsCount := Length(GDescriptor.GenericParams); ArgsCount := Length(Args); if ParamsCount > ArgsCount then AbortWork(sProcRequiresExplicitTypeArgumentFmt, [Proc.ProcTypeName, Proc.DisplayName], CallExpr.TextPosition); if ParamsCount < ArgsCount then AbortWork(sTooManyActualTypeParameters, CallExpr.TextPosition); CallExpr.GenericArgs := Args; end; function TASTDelphiUnit.SpecializeGenericProc(CallExpr: TIDCallExpression; const CallArgs: TIDExpressions): TASTDelphiProc; var i, ai, ac, pc: Integer; SrcArg: TIDExpression; SpecializeArgs: TIDExpressions; Proc: TASTDelphiProc; GDescriptor: PGenericDescriptor; Scope: TScope; Param: TIDDeclaration; ProcName: string; begin Proc := CallExpr.AsProcedure as TASTDelphiProc; GDescriptor := Proc.GenericDescriptor; {подготавливаем списко обобщенных аргументов} SpecializeArgs := CallExpr.GenericArgs; if Length(SpecializeArgs) = 0 then begin ac := Length(GDescriptor.GenericParams); pc := Length(Proc.ExplicitParams); if pc <> ac then AbortWork(sProcRequiresExplicitTypeArgumentFmt, [CallExpr.AsProcedure.ProcTypeName, CallExpr.DisplayName], CallExpr.TextPosition); ai := 0; SetLength(SpecializeArgs, ac); for i := 0 to pc - 1 do begin Param := Proc.ExplicitParams[i]; if Param.DataTypeID = dtGeneric then begin if CallExpr.ArgumentsCount > i then SrcArg := CallArgs[i] else SrcArg := TIDVariable(Param).DefaultValue; SpecializeArgs[ai] := TIDExpression.Create(SrcArg.DataType, SrcArg.TextPosition); Inc(ai); end; end; end; Result := TASTDelphiProc(FindGenericInstance(GDescriptor.GenericInstances, SpecializeArgs)); if Assigned(Result) then Exit; Scope := TScope.Create(Proc.Scope.ScopeType, Proc.EntryScope); {$IFDEF DEBUG}Scope.Name := Proc.DisplayName + '.generic_alias_scope';{$ENDIF} Proc.EntryScope.AddScope(Scope); {формируем уникальное название процедуры} for i := 0 to Length(SpecializeArgs) - 1 do begin SrcArg := SpecializeArgs[i]; ProcName := AddStringSegment(ProcName, SrcArg.DisplayName, ', '); Param := TIDAlias.CreateAlias(Scope, GDescriptor.GenericParams[i].ID, SrcArg.Declaration); Scope.InsertID(Param); end; ProcName := Proc.Name + '<' + ProcName + '>'; Result := TASTDelphiProc.Create(Proc.Scope, Identifier(ProcName, Proc.ID.TextPosition)); {добовляем специализацию в пул } GDescriptor.AddGenericInstance(Result, SpecializeArgs); try ParseGenericProcRepeatedly(Scope, Proc, Result, Proc.Struct); except on e: ECompilerAbort do begin PutMessage(cmtError, Format(IfThen(Assigned(CallExpr.AsProcedure.ResultType), sGenericFuncInstanceErrorFmt, sGenericProcInstanceErrorFmt), [ProcName]), CallExpr.TextPosition); raise; end; end; end; function TASTDelphiUnit.InstantiateGenericType(AScope: TScope; AGenericType: TIDType; const SpecializeArgs: TIDExpressions): TIDType; var GDescriptor: PGenericDescriptor; LContext: TGenericInstantiateContext; begin GDescriptor := AGenericType.GenericDescriptor; {find in the pool first} Result := TIDType(FindGenericInstance(GDescriptor.GenericInstances, SpecializeArgs)); if Assigned(Result) then Exit; LContext.SrcDecl := AGenericType; LContext.DstScope := AScope; var AStrSufix := ''; var AArgsCount := Length(SpecializeArgs); SetLength(LContext.Arguments, AArgsCount); for var AIndex := 0 to AArgsCount - 1 do begin var AArgType := SpecializeArgs[AIndex].AsType; LContext.Arguments[AIndex].GParam := GDescriptor.GenericParams[AIndex] as TIDGenericParam; LContext.Arguments[AIndex].GArg := AArgType; AStrSufix := AddStringSegment(AStrSufix, AArgType.Name, ','); end; LContext.DstID.Name := AGenericType.Name + '<' + AStrSufix + '>'; LContext.DstID.TextPosition := Lexer_Position; Result := AGenericType.InstantiateGeneric(LContext); end; function TASTDelphiUnit.SpecializeGenericType(GenericType: TIDType; const ID: TIdentifier; const SpecializeArgs: TIDExpressions): TIDType; var i: Integer; GAScope: TScope; // специальный скоуп для алиасов-параметров параметрического типа Param: TIDAlias; NewID: TIdentifier; TypeName: string; SrcArg: TIDExpression; ParserPos: TParserPosition; GDescriptor: PGenericDescriptor; GProc, SProc: TASTDelphiProc; GMethods, SMethods: PProcSpace; begin GDescriptor := GenericType.GenericDescriptor; {поиск подходящей специализации в пуле} Result := TIDType(FindGenericInstance(GDescriptor.GenericInstances, SpecializeArgs)); if Assigned(Result) then Exit; GAScope := TScope.Create(GenericType.Scope.ScopeType, GenericType.Scope); {формируем название типа} for i := 0 to Length(SpecializeArgs) - 1 do begin SrcArg := SpecializeArgs[i]; TypeName := AddStringSegment(TypeName, SrcArg.DisplayName, ', '); Param := TIDAlias.CreateAlias(GAScope, GDescriptor.GenericParams[i].ID, SrcArg.Declaration); GAScope.InsertID(Param); end; NewID.Name := GenericType.Name + '<' + TypeName + '>'; NewID.TextPosition := ID.TextPosition; {$IFDEF DEBUG}GAScope.Name := NewID.Name + '.generic_alias_scope';{$ENDIF} Lexer.SaveState(ParserPos); Lexer.LoadState(GDescriptor.ImplSRCPosition); Lexer_NextToken(GAScope); GenericType.GenericDeclInProgress := True; try {парсим заново generic-тип} ParseTypeDecl(GAScope, nil, NewID, {out} Result); if not Assigned(Result) then AbortWorkInternal('Generic parsing error'); except on E: ECompilerAbort do begin Lexer.LoadState(ParserPos); // show the original place of the error PutMessage(cmtError, 'Generic specialization error: ' + NewID.Name, Lexer_Position); raise; end; on E: Exception do begin Lexer.LoadState(ParserPos); AbortWorkInternal(E.Message, Lexer_Position); end; end; {если есть методы, пытаемся их перекомпилировать} if GenericType.InheritsFrom(TIDStructure) then begin GMethods := TIDStructure(GenericType).Methods; SMethods := TIDStructure(Result).Methods; GProc := GMethods.First as TASTDelphiProc; SProc := SMethods.First as TASTDelphiProc; while Assigned(GProc) do begin if GProc.IsCompleted and Assigned(GProc.GenericDescriptor) then ParseGenericProcRepeatedly(ImplScope, GProc, SProc, TIDStructure(Result)) else SProc.GenericPrototype := GProc; GProc := TASTDelphiProc(GProc.NextItem); SProc := TASTDelphiProc(SProc.NextItem); end end; GenericType.GenericDeclInProgress := False; Lexer.LoadState(ParserPos); {добовляем специализацию в пул} GDescriptor.AddGenericInstance(Result, SpecializeArgs); end; procedure TASTDelphiUnit.StaticCheckBounds(ConstValue: TIDConstant; Decl: TIDDeclaration; DimNumber: Integer); var DeclType: TIDType; Dim: TIDOrdinal; begin if Decl.ItemType <> itProperty then begin DeclType := Decl.DataType; if DeclType.DataTypeID = dtPointer then DeclType := TIDPointer(DeclType).ReferenceType; if DeclType is TIDArray then with TIDArray(DeclType) do begin if DimNumber >= DimensionsCount then AbortWork(sNeedSpecifyNIndexesFmt, [Decl.DisplayName, DisplayName, DimensionsCount], Lexer.PrevPosition); Dim := Dimensions[DimNumber]; if (ConstValue.AsInt64 < Dim.LowBound) or (ConstValue.AsInt64 > Dim.HighBound) then AbortWork(sConstExprOutOfRangeFmt, [ConstValue.AsInt64, Dim.LowBound, Dim.HighBound], Lexer.PrevPosition); end; end; end; class function TASTDelphiUnit.StrictMatchProc(const Src, Dst: TIDProcedure): Boolean; begin Result := StrictMatchProcSingnatures(Src.ExplicitParams, Dst.ExplicitParams, Src.ResultType, Dst.ResultType); end; class function TASTDelphiUnit.StrictMatchProcSingnatures(const SrcParams, DstParams: TIDParamArray; const SrcResultType, DstResultType: TIDType): Boolean; var i: Integer; SParamsCount, DParamsCount: Integer; SParamType, DParamType: TIDType; begin // проверяем на соответсвтие возвращаемый результат (если есть) if SrcResultType <> DstResultType then Exit(False); if Assigned(DstResultType) and Assigned(DstResultType) then begin if SrcResultType.ActualDataType <> DstResultType.ActualDataType then Exit(False); end; SParamsCount := Length(SrcParams); DParamsCount := Length(DstParams); // проверяем на соответсвтие кол-во параметров if SParamsCount <> DParamsCount then Exit(False); // проверяем на соответсвтие типов параметров for i := 0 to SParamsCount - 1 do begin SParamType := SrcParams[i].DataType.ActualDataType; DParamType := DstParams[i].DataType.ActualDataType; if SParamType <> DParamType then Exit(False); end; Result := True; end; function TASTDelphiUnit.ParseRepeatStatement(Scope: TScope; const SContext: TSContext): TTokenID; var Expression: TIDExpression; EContext: TEContext; BodySContext: TSContext; KW: TASTKWRepeat; ASTExpr: TASTExpression; begin KW := SContext.Add(TASTKWRepeat) as TASTKWRepeat; BodySContext := SContext.MakeChild(Scope, KW.Body); Lexer_NextToken(Scope); // тело цикла Result := ParseStatements(Scope, BodySContext, True); Lexer_MatchToken(Result, token_until); // выражение цикла InitEContext(EContext, SContext, ExprRValue); Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext, EContext, ASTExpr); KW.Expression := ASTExpr; Expression := EContext.Result; CheckEmptyExpression(Expression); CheckBooleanExpression(Expression); end; function TASTDelphiUnit.Lexer_MatchSemicolonAndNext(Scope: TScope; ActualToken: TTokenID): TTokenID; begin if ActualToken = token_semicolon then Result := Lexer_NextToken(Scope) else if ActualToken <> token_end then begin ERRORS.SEMICOLON_EXPECTED; Result := token_unknown; end else Result := ActualToken end; function TASTDelphiUnit.ProcSpec_Inline(Scope: TScope; var Flags: TProcFlags): TTokenID; begin if pfImport in Flags then ERRORS.IMPORT_FUNCTION_CANNOT_BE_INLINE; if pfInline in Flags then ERRORS.DUPLICATE_SPECIFICATION(PS_INLINE); Include(Flags, pfInline); Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_Export(Scope: TScope; var Flags: TProcFlags): TTokenID; var ExportID: TIdentifier; begin if pfExport in Flags then ERRORS.DUPLICATE_SPECIFICATION(PS_EXPORT); Include(Flags, pfExport); {if Scope.ScopeClass <> scInterface then ERRORS.EXPORT_ALLOWS_ONLY_IN_INTF_SECTION;} Result := Lexer_NextToken(Scope); if Result = token_identifier then begin Lexer_ReadCurrIdentifier(ExportID); Result := Lexer_NextToken(Scope); end; //else // ExportID := Proc.ID; // Proc.Export := Package.GetStringConstant(ExportID.Name); Lexer_MatchToken(Result, token_semicolon); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_Forward(Scope: TScope; var Flags: TProcFlags): TTokenID; begin if (pfForward in Flags) or (pfImport in Flags) then ERRORS.DUPLICATE_SPECIFICATION(PS_FORWARD); Include(Flags, pfForward); Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_External(Scope: TScope; out ImportLib, ImportName: TIDDeclaration; var Flags: TProcFlags): TTokenID; begin if pfImport in Flags then ERRORS.DUPLICATE_SPECIFICATION(PS_IMPORT); Include(Flags, pfImport); ParseImportStatement(Scope, ImportLib, ImportName); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_Overload(Scope: TScope; var Flags: TProcFlags): TTokenID; begin if pfOveload in Flags then ERRORS.DUPLICATE_SPECIFICATION(PS_OVELOAD); Include(Flags, pfOveload); Result := Lexer_ReadSemicolonAndToken(Scope); end; function TASTDelphiUnit.ProcSpec_Reintroduce(Scope: TScope; var Flags: TProcFlags): TTokenID; begin if pfReintroduce in Flags then ERRORS.DUPLICATE_SPECIFICATION(PS_REINTRODUCE); Include(Flags, pfReintroduce); Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_Virtual(Scope: TScope; Struct: TIDStructure; var Flags: TProcFlags): TTokenID; begin if pfVirtual in Flags then ERRORS.DUPLICATE_SPECIFICATION(PS_VIRTUAL); Include(Flags, pfVirtual); if not Assigned(Struct) then ERRORS.VIRTUAL_ALLOWED_ONLY_IN_CLASSES; //Proc.VirtualIndex := Proc.Struct.GetLastVirtualIndex + 1; Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_Dynamic(Scope: TScope; Struct: TIDStructure; var Flags: TProcFlags): TTokenID; begin if pfVirtual in Flags then ERRORS.DUPLICATE_SPECIFICATION(PS_VIRTUAL); Include(Flags, pfVirtual); if not Assigned(Struct) then ERRORS.VIRTUAL_ALLOWED_ONLY_IN_CLASSES; //Proc.VirtualIndex := Proc.Struct.GetLastVirtualIndex + 1; Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; procedure TASTDelphiUnit.Progress(StatusClass: TASTProcessStatusClass); begin fTotalLinesParsed := Lexer_Line; inherited; end; function TASTDelphiUnit.ProcSpec_Abstract(Scope: TScope; Struct: TIDStructure; var Flags: TProcFlags): TTokenID; begin if pfAbstract in Flags then ERRORS.DUPLICATE_SPECIFICATION(PS_ABSTRACT); Include(Flags, pfAbstract); if not Assigned(Struct) then ERRORS.VIRTUAL_ALLOWED_ONLY_IN_CLASSES; Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_Override(Scope: TScope; Struct: TIDStructure; var Flags: TProcFlags): TTokenID; begin if pfOverride in Flags then ERRORS.DUPLICATE_SPECIFICATION(PS_OVERRIDE); if not Assigned(Struct) then ERRORS.STRUCT_TYPE_REQUIRED(Lexer_Position); Include(Flags, pfOverride); Include(Flags, pfVirtual); Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_Final(Scope: TScope; Struct: TIDStructure; var Flags: TProcFlags): TTokenID; var PrevProc: TIDProcedure; begin if pfFinal in Flags then ERRORS.DUPLICATE_SPECIFICATION(PS_FINAL); if not Assigned(Struct) then ERRORS.STRUCT_TYPE_REQUIRED(Lexer_Position); Include(Flags, pfFinal); Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_Static(Scope: TScope; var Flags: TProcFlags; var ProcType: TProcType): TTokenID; begin if pfStatic in Flags then ERRORS.DUPLICATE_SPECIFICATION(PS_STATIC); Include(Flags, pfStatic); Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_StdCall(Scope: TScope; var CallConvention: TCallConvention): TTokenID; begin if CallConvention = ConvStdCall then ERRORS.DUPLICATE_SPECIFICATION(PS_STDCALL); CallConvention := ConvStdCall; Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_FastCall(Scope: TScope; var CallConvention: TCallConvention): TTokenID; begin if CallConvention = ConvFastCall then ERRORS.DUPLICATE_SPECIFICATION(PS_FASTCALL); CallConvention := ConvFastCall; Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ProcSpec_CDecl(Scope: TScope; var CallConvention: TCallConvention): TTokenID; begin if CallConvention = ConvCDecl then ERRORS.DUPLICATE_SPECIFICATION(PS_CDECL); CallConvention := ConvCDecl; Lexer_ReadSemicolon(Scope); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseGenericMember(const PMContext: TPMContext; const SContext: TSContext; StrictSearch: Boolean; out Decl: TIDDeclaration; out WithExpression: TIDExpression): TTokenID; var Scope: TScope; GenericArgs: TIDExpressions; ExprName: string; begin Scope := PMContext.ItemScope; Result := ParseGenericsArgs(Scope, SContext, GenericArgs); ExprName := format('%s<%d>', [PMContext.ID.Name, Length(GenericArgs)]); if not StrictSearch then Decl := FindIDNoAbort(Scope, ExprName) else Decl := Scope.FindMembers(ExprName); if not Assigned(Decl) then ERRORS.UNDECLARED_ID(ExprName, Lexer_PrevPosition); if Decl.ItemType = itType then Decl := SpecializeGenericType(TIDType(Decl), PMContext.ID, GenericArgs) else ERRORS.FEATURE_NOT_SUPPORTED; end; function TASTDelphiUnit.ParseUnknownID(Scope: TScope; const PrevExpr: TIDExpression; ID: TIdentifier; out Decl: TIDDeclaration): TTokenID; var PrevDecl: TIDUnit; FullID, NextID: TIdentifier; begin if Assigned(PrevExpr) and (PrevExpr.ItemType = itUnit) then FullID := PrevExpr.Declaration.ID; Result := Lexer_CurTokenID; while True do begin FullID := TIdentifier.Combine(FullID, ID); Decl := FindIDNoAbort(Scope, FullID); if Assigned(Decl) then Exit; if Result = token_dot then begin Lexer_ReadNextIdentifier(Scope, ID); Result := Lexer_NextToken(Scope); continue; end; break; end; ERRORS.UNDECLARED_ID(ID); end; function TASTDelphiUnit.ParseIdentifier(Scope, SearchScope: TScope; out Expression: TIDExpression; var EContext: TEContext; const PrevExpr: TIDExpression; const ASTE: TASTExpression): TTokenID; var Decl: TIDDeclaration; Indexes: TIDExpressions; i: Integer; Expr, NExpr: TIDExpression; GenericArgs: TIDExpressions; PMContext: TPMContext; WasProperty, StrictSearch: Boolean; begin WasProperty := False; PMContext.Init; PMContext.ItemScope := Scope; Lexer_ReadCurrIdentifier(PMContext.ID); Expr := nil; // todo: with if not Assigned(SearchScope) then Decl := FindIDNoAbort(Scope, PMContext.ID) else begin Decl := SearchScope.FindMembers(PMContext.ID.Name); end; StrictSearch := Assigned(SearchScope); Result := Lexer_NextToken(Scope); if not Assigned(Decl) then begin if Result = token_less then Result := ParseGenericMember(PMContext, EContext.SContext, StrictSearch, Decl, Expr); if PMContext.ItemScope is TConditionalScope then begin Decl := TIDStringConstant.CreateAsAnonymous(PMContext.ItemScope, Sys._UnicodeString, PMContext.ID.Name); end; if not Assigned(Decl) then Result := ParseUnknownID(Scope, PrevExpr, PMContext.ID, Decl); end; // если Scope порожден конструкцией WITH // то добавляем в выражение первым элементом if Assigned(Expr) then begin if Expr.ExpressionType = etDeclaration then begin PMContext.Add(Expr); end else begin Indexes := TIDMultiExpression(Expr).Items; for i := 0 to Length(Indexes) - 1 do PMContext.Add(Indexes[i]); end; end; {проверяем на псевдоним} if Decl.ItemType = itAlias then Decl := TIDAlias(Decl).Original; {проверяем на доступ к члену типа} //if Assigned(EContext.SContext) then // CheckAccessMember(SContext, Decl, PMContext.ID); case Decl.ItemType of {процедура/функция} itProcedure: begin var LCallExpr := TIDCallExpression.Create(Decl, PMContext.ID.TextPosition); LCallExpr.Instance := PrevExpr; Expression := LCallExpr; // если есть открытая угловая скобка, - значит generic-вызов if (Result = token_less) and TIDProcedure(Decl).IsGeneric then begin Result := ParseGenericsArgs(Scope, EContext.SContext, GenericArgs); SetProcGenericArgs(LCallExpr, GenericArgs); end; // если есть открытая скобка, - значит вызов if Result = token_openround then begin Result := ParseEntryCall(Scope, LCallExpr, EContext, ASTE); // если это метод, подставляем self из пула if PMContext.Count > 0 then begin if PMContext.Count > 1 then begin Expr := nil; Assert(false); end else Expr := PMContext.Last; if (Expr.Declaration is TIDField) and (PMContext.Count = 1) then begin NExpr := GetTMPRefExpr(EContext.SContext, Expr.DataType); NExpr.TextPosition := Expr.TextPosition; Expr := NExpr; end; LCallExpr.Instance := Expr; end else if (Decl.ItemType = itProcedure) and Assigned(TIDProcedure(Decl).Struct) and (TIDProcedure(Decl).Struct = EContext.SContext.Proc.Struct) then begin // если это собственный метод, добавляем self из списка параметров LCallExpr.Instance := TIDExpression.Create(EContext.SContext.Proc.SelfParam); end; // process call operator Expression := EContext.RPNPopOperator(); end else begin // иначе создаем процедурный тип, если он отсутствовал TIDProcedure(Decl).CreateProcedureTypeIfNeed(Scope); PMContext.DataType := TIDProcedure(Decl).DataType; AddType(TIDProcedure(Decl).DataType); end; end; {built-in} itMacroFunction: begin var LBuiltinExpr := TIDExpression.Create(Decl, PMContext.ID.TextPosition); Result := ParseBuiltinCall(Scope, LBuiltinExpr, EContext); end; {variable} itVar: begin // если есть открытая скобка, - значит вызов if Result = token_openround then begin if Decl.DataTypeID <> dtProcType then ERRORS.PROC_OR_PROCVAR_REQUIRED(PMContext.ID); Expression := TIDCallExpression.Create(Decl, PMContext.ID.TextPosition); Result := ParseEntryCall(Scope, TIDCallExpression(Expression), EContext, ASTE); Expression := nil; end else Expression := TIDExpression.Create(Decl, PMContext.ID.TextPosition); end; {const/unit/label} itConst, itUnit, itLabel: begin Expression := TIDExpression.Create(Decl, PMContext.ID.TextPosition); PMContext.DataType := Decl.DataType; end; {property} itProperty: begin WasProperty := True; Result := ParsePropertyMember(PMContext, Scope, TIDProperty(Decl), Expression, EContext, PrevExpr); // заменяем декларацию if Assigned(Expression) then begin Decl := Expression.Declaration; // если геттер/сеттер - поле, то снимаем флаг "свойства" if Decl.ItemType = itVar then WasProperty := False; end; PMContext.DataType := Decl.DataType; end; {type} itType: begin {generic param} if Result = token_less then Result := ParseGenericTypeSpec(Scope, Decl.ID, TIdType(Decl)); Expression := TIDExpression.Create(Decl, PMContext.ID.TextPosition); {explicit typecase} if Result = token_openround then Result := ParseExplicitCast(Scope, EContext.SContext, Expression); PMContext.DataType := Decl.DataType; end; else ERRORS.FEATURE_NOT_SUPPORTED; end; if Assigned(Expression) then ASTE.AddDeclItem(Expression.Declaration, Expression.TextPosition); end; function TASTDelphiUnit.ParseMember(Scope: TScope; var EContext: TEContext; const ASTE: TASTExpression): TTokenID; var Left, Right: TIDExpression; Decl: TIDDeclaration; SearchScope: TScope; DataType: TIDType; begin Left := EContext.RPNPopExpression(); Decl := Left.Declaration; // todo: system fail if decl is not assigned SearchScope := nil; case Decl.ItemType of itUnit: begin // if this is the full name of THIS unit, let's search in implementation first if Decl.ID.Name = Self._ID.Name then SearchScope := ImplScope else SearchScope := TIDNameSpace(Decl).Members end; itType: begin if Decl.ClassType = TIDAliasType then Decl := TIDAliasType(Decl).Original; if Assigned(TIDType(Decl).Helper) then SearchScope := TIDType(Decl).Helper.StaticMembers else if Decl is TIDStructure then SearchScope := TIDStructure(Decl).StaticMembers else if Decl.ClassType = TIDEnum then SearchScope := TIDEnum(Decl).Items else if Decl.ClassType = TIDDynArray then SearchScope := TIDDynArray(Decl).GetHelperScope; if Decl.ClassType = TIDGenericParam then begin SearchScope := (TIDGenericParam(Decl).ConstraintType as TIDStructure).StaticMembers; end; end; itProcedure, itVar, itConst: begin if Decl.ItemType = itProcedure then DataType := TIDProcedure(Decl).ResultType.ActualDataType else DataType := Left.DataType.ActualDataType; if DataType.ClassType = TIDAliasType then DataType := TIDAliasType(DataType).Original; while DataType.DataTypeID in [dtPointer, dtClassOf] do DataType := GetPtrReferenceType(TIDPointer(DataType)).ActualDataType; if (DataType.DataTypeID = dtGeneric) and Assigned(TIDGenericParam(DataType).ConstraintType) then DataType := TIDGenericParam(DataType).ConstraintType; if Assigned(DataType.Helper) then // todo: join helper scope and decl's scope together SearchScope := DataType.Helper.Members else if DataType is TIDStructure then SearchScope := TIDStructure(DataType).Members else if Decl.ClassType = TIDEnum then SearchScope := TIDEnum(Decl).Items end; else AbortWorkInternal('Unsuported decl type: %d', [Ord(Decl.ItemType)]) end; if not Assigned(SearchScope) then begin ERRORS.IDENTIFIER_HAS_NO_MEMBERS(Decl); Exit; end; ASTE.AddOperation<TASTOpMemberAccess>; Lexer_NextToken(Scope); Result := ParseIdentifier(Scope, SearchScope, Right, EContext, Left, ASTE); if Assigned(Right) then EContext.RPNPushExpression(Right); end; function TASTDelphiUnit.ParseMemberCall(Scope: TScope; var EContext: TEContext; const ASTE: TASTExpression): TTokenID; var Expr: TIDExpression; CallExpr: TIDCallExpression; begin Expr := EContext.RPNPopExpression(); if Expr.ItemType = itProcedure then CallExpr := TIDCallExpression.Create(Expr.Declaration, Expr.TextPosition) else if (Expr.ItemType = itVar) and (Expr.DataType is TIDProcType) then begin CallExpr := TIDCastedCallExpression.Create(Expr.Declaration, Expr.TextPosition); TIDCastedCallExpression(CallExpr).DataType := Expr.DataType; end else begin ERRORS.FEATURE_NOT_SUPPORTED; CallExpr := nil; Result := token_unknown; end; Result := ParseEntryCall(Scope, CallExpr, EContext, ASTE); (*// если это метод, подставляем self из пула if PMContext.Count > 0 then begin if PMContext.Count > 1 then Expr := ProcessMemberExpression({SContext}nil, WasProperty, PMContext) else Expr := PMContext.Last; if (Expr.Declaration is TIDField) and (PMContext.Count = 1) then begin NExpr := GetTMPRefExpr(SContext, Expr.DataType); NExpr.TextPosition := Expr.TextPosition; Expr := NExpr; end; TIDCallExpression(Expression).Instance := Expr; end else if (Decl.ItemType = itProcedure) and Assigned(TIDProcedure(Decl).Struct) and (TIDProcedure(Decl).Struct = SContext.Proc.Struct) then begin // если это собственный метод, добавляем self из списка параметров TIDCallExpression(Expression).Instance := TIDExpression.Create(SContext.Proc.SelfParam); end;*) end; function TASTDelphiUnit.ParseNamedTypeDecl(Scope: TScope): TTokenID; var ID: TIdentifier; Decl: TIDType; GenericParams: TIDTypeArray; ParserPos: TParserPosition; GDescriptor: PGenericDescriptor; begin Lexer_NextToken(Scope); repeat CheckAndParseAttribute(Scope); Lexer_ReadCurrIdentifier(ID); Result := Lexer_NextToken(Scope); {if there is "<" - read generic params} if Result = token_less then begin GDescriptor := TGenericDescriptor.Create(Scope); Result := ParseGenericsHeader(GDescriptor.Scope, {out} GenericParams); GDescriptor.GenericParams := GenericParams; GDescriptor.SearchName := format('%s<%d>', [ID.Name, Length(GenericParams)]); end else GDescriptor := nil; Lexer_MatchToken(Result, token_equal); if Assigned(GDescriptor) then begin Lexer.SaveState(ParserPos); GDescriptor.IntfSRCPosition := ParserPos; end; Lexer_NextToken(Scope); Result := ParseTypeDecl(Scope, GDescriptor, ID, Decl); if not Assigned(Decl) then ERRORS.INVALID_TYPE_DECLARATION(ID); CheckForwardPtrDeclarations; // check and parse procedural type call convention Result := CheckAndParseProcTypeCallConv(Scope, Result, Decl); until (Result <> token_identifier) and (Result <> token_openblock); end; function TASTDelphiUnit.ParseIndexedPropertyArgs(Scope: TScope; out ArgumentsCount: Integer; var EContext: TEContext): TTokenID; var Expr: TIDExpression; InnerEContext: TEContext; SContext: PSContext; ASTExpr: TASTExpression; begin ArgumentsCount := 0; SContext := addr(EContext.SContext); InitEContext(InnerEContext, SContext^, ExprNested); {цикл парсинга аргументов} while true do begin Lexer_NextToken(Scope); Result := ParseExpression(Scope, SContext^, InnerEContext, ASTExpr); Expr := InnerEContext.Result; if Assigned(Expr) then begin if Expr.DataType = Sys._Boolean then begin {if (Expr.ItemType = itVar) and Expr.IsAnonymous then Bool_CompleteImmediateExpression(InnerEContext, Expr);} end; EContext.RPNPushExpression(Expr); end else begin // Добавляем пустой Expression для значения по умолчанию EContext.RPNPushExpression(nil); end; Inc(ArgumentsCount); case Result of token_coma: begin InnerEContext.Reset; continue; end; token_closeblock: begin Result := Lexer_NextToken(Scope); Break; end; else ERRORS.INCOMPLETE_STATEMENT('indexed args'); end; end; end; function TASTDelphiUnit.ParseInheritedStatement(Scope: TScope; const EContext: TEContext): TTokenID; var Proc, InheritedProc: TIDProcedure; CallExpr: TIDCallExpression; CallArgs: TIDExpressions; i, ArgsCnt: Integer; ResultExpr: TIDExpression; Decl: TIDDeclaration; Ancestor: TIDStructure; ID: TIdentifier; KW: TASTKWInheritedCall; begin Proc := EContext.SContext.Proc; KW := EContext.SContext.Add(TASTKWInheritedCall) as TASTKWInheritedCall; InheritedProc := nil; Result := Lexer_NextToken(Scope); if Result = token_identifier then begin {если после inherited идет полное описание вызова метода} Ancestor := Proc.Struct.Ancestor; while Assigned(Ancestor) do begin Lexer_ReadCurrIdentifier(ID); Decl := FindID(Ancestor.Members, ID); if not Assigned(Decl) then ERRORS.UNDECLARED_ID(ID); case Decl.ItemType of itProcedure: begin InheritedProc := Decl as TIDProcedure; Result := Lexer_NextToken(Scope); ArgsCnt := Length(CallArgs); if Result = token_openround then begin CallExpr := TIDCallExpression.Create(InheritedProc, Lexer_Line); CallExpr.Instance := TIDExpression.Create(Proc.SelfParameter); CallExpr.ArgumentsCount := ArgsCnt; Result := ParseEntryCall(Scope, CallExpr, EContext, nil {tmp!!!}); end; Break; end; else ERRORS.PROC_OR_TYPE_REQUIRED(ID); Exit; end; Break; end; end else begin {если после inherited ничего больше нет, заполняем аргументы параметрами (если есть)} ArgsCnt := Length(Proc.ExplicitParams); SetLength(CallArgs, ArgsCnt); for i := 0 to ArgsCnt - 1 do CallArgs[i] := TIDExpression.Create(Proc.ExplicitParams[i]); if (pfConstructor in Proc.Flags) or (pfClass in Proc.Flags) then InheritedProc := Proc.Struct.FindVirtualClassProcInAncestor(Proc) else InheritedProc := Proc.Struct.FindVirtualInstanceProcInAncestor(Proc); if not Assigned(InheritedProc) and not (pfConstructor in Proc.Flags) then ERRORS.NO_METHOD_IN_BASE_CLASS(Proc); end; // if inherited was found, generate call expression if Assigned(InheritedProc) then begin CallExpr := TIDCallExpression.Create(InheritedProc, Lexer_Line); CallExpr.Instance := TIDExpression.Create(Proc.SelfParameter); CallExpr.ArgumentsCount := ArgsCnt; ResultExpr := Process_CALL_direct(EContext.SContext, CallExpr, CallArgs); if Assigned(ResultExpr) then EContext.RPNPushExpression(ResultExpr); end; end; function TASTDelphiUnit.ParseInitSection: TTokenID; var SContext: TSContext; begin if FInitProcExplicit then ERRORS.INIT_SECTION_ALREADY_DEFINED; FInitProcExplicit := True; SContext := TSContext.Create(Self, ImplScope, InitProc as TASTDelphiProc, TASTDelphiProc(InitProc).Body); Lexer_NextToken(InitProc.Scope); InitProc.FirstBodyLine := Lexer_Line; Result := ParseStatements(InitProc.Scope, SContext, True); InitProc.LastBodyLine := Lexer_Line; end; function TASTDelphiUnit.ParseInterfaceType(Scope, GenericScope: TScope; GDescriptor: PGenericDescriptor; const ID: TIdentifier; out Decl: TIDInterface): TTokenID; var FwdDecl: TIDDeclaration; Expr: TIDExpression; SearchName: string; begin if not Assigned(GDescriptor) then SearchName := ID.Name else SearchName := GDescriptor.SearchName; FwdDecl := Scope.FindID(SearchName); if not Assigned(FwdDecl) then begin Decl := TIDInterface.Create(Scope, ID); if Assigned(GenericScope) then Decl.Members.AddScope(GenericScope); Decl.GenericDescriptor := GDescriptor; if not Assigned(GDescriptor) then InsertToScope(Scope, Decl) else InsertToScope(Scope, GDescriptor.SearchName, Decl); //InsertToScope(Scope, Decl); end else begin if (FwdDecl.ItemType = itType) and (TIDType(FwdDecl).DataTypeID = dtInterface) and TIDType(FwdDecl).NeedForward then Decl := FwdDecl as TIDInterface else begin ERRORS.ID_REDECLARATED(FwdDecl); end; end; Result := Lexer_NextToken(Scope); if Result = token_openround then begin Lexer_NextToken(Scope); Result := ParseConstExpression(Scope, Expr, ExprNested); CheckInterfaceType(Expr); var Ancestor := Expr.AsType.ActualDataType; if Ancestor = Decl then AbortWork(sRecurciveTypeLinkIsNotAllowed, Expr.TextPosition); Lexer_MatchToken(Result, token_closeround); Decl.Ancestor := Ancestor as TIDInterface; Result := Lexer_NextToken(Scope); end; // если найден символ ; - то это forward-декларация if Result = token_semicolon then begin if Decl.NeedForward then ERRORS.ID_REDECLARATED(ID); Decl.NeedForward := True; Exit; end; if Result = token_openblock then Result := ParseIntfGUID(Scope, Decl); while True do begin case Result of token_openblock: Result := ParseAttribute(Scope); token_procedure: Result := ParseProcedure(Decl.Members, ptProc, Decl); token_function: Result := ParseProcedure(Decl.Members, ptFunc, Decl); token_property: Result := ParseProperty(Decl.Members, Decl); else break; end; end; CheckIncompleteType(Decl.Members); Decl.StructFlags := Decl.StructFlags + [StructCompleted]; Lexer_MatchToken(Result, token_end); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseIntfGUID(Scope: TScope; Decl: TIDInterface): TTokenID; var UID: TIDExpression; GUID: TGUID; begin Lexer_NextToken(Scope); if Lexer_IdentifireType = itString then begin Result := ParseConstExpression(Scope, UID, ExprNested); CheckEmptyExpression(UID); CheckStringExpression(UID); try GUID := StringToGUID(UID.AsStrConst.Value); except AbortWork('Invalid GUID', Lexer_Position); end; Decl.GUID := GUID; Lexer_MatchToken(Result, token_closeblock); Result := Lexer_NextToken(Scope); end else Result := ParseAttribute(Scope); end; function TASTDelphiUnit.ParseFinalSection: TTokenID; var SContext: TSContext; begin if fFinalProcExplicit then ERRORS.FINAL_SECTION_ALREADY_DEFINED; FFinalProcExplicit := True; SContext := TSContext.Create(Self, ImplScope, FinalProc as TASTDelphiProc, TASTDelphiProc(FinalProc).Body); Lexer_NextToken(FinalProc.Scope); FinalProc.FirstBodyLine := Lexer_Line; Result := ParseStatements(FinalProc.Scope, SContext, True); FinalProc.LastBodyLine := Lexer_Line; end; function TASTDelphiUnit.ParseVarDefaultValue(Scope: TScope; DataType: TIDType; out DefaultValue: TIDExpression): TTokenID; var SContext: TSContext; EContext: TEContext; ASTE: TASTExpression; begin case DataType.DataTypeID of dtStaticArray: Result := ParseVarStaticArrayDefaultValue(Scope, DataType as TIDArray, DefaultValue); dtRecord: begin Result := Lexer_NextToken(Scope); if (DataType.Module = SYSUnit) and (DataType.Name = 'TGUID') and (Result <> token_openround) then begin Result := ParseConstExpression(Scope, DefaultValue, ExprRValue); end else Result := ParseVarRecordDefaultValue(Scope, DataType as TIDStructure, DefaultValue); end else SContext := fUnitSContext; Result := Lexer_NextToken(Scope); if Scope.ScopeType = stLocal then Result := ParseConstExpression(Scope, DefaultValue, ExprRValue) else begin InitEContext(EContext, SContext, ExprRValue); Result := ParseExpression(Scope, SContext, EContext, ASTE); DefaultValue := EContext.Result; end; CheckEmptyExpression(DefaultValue); if CheckImplicit(SContext, DefaultValue, DataType) = nil then ERRORS.INCOMPATIBLE_TYPES(DefaultValue, DataType); DefaultValue := MatchImplicit3(SContext, DefaultValue, DataType); if DefaultValue.IsAnonymous then DefaultValue.Declaration.DataType := DataType; // подгоняем фактичиский тип константы под необходимый end; end; function TASTDelphiUnit.ParseFieldsInCaseRecord(Scope: TScope; Visibility: TVisibility; Struct: TIDStructure): TTokenID; var i, c: Integer; DataType: TIDType; Field: TIDVariable; Names: TIdentifiersPool; VarFlags: TVariableFlags; begin c := 0; Names := TIdentifiersPool.Create(2); while True do begin VarFlags := []; Result := CheckAndParseAttribute(Scope); Lexer_MatchIdentifier(Result); Names.Add; Lexer_ReadCurrIdentifier(Names.Items[c]); Result := Lexer_NextToken(Scope); if Result = token_Coma then begin Inc(c); Lexer_NextToken(Scope); Continue; end; Lexer_MatchToken(Result, token_colon); // парсим тип Result := ParseTypeSpec(Scope, DataType); for i := 0 to c do begin Field := TIDField.Create(Struct, Names.Items[i]); Field.DataType := DataType; Field.Visibility := Visibility; Field.DefaultValue := nil; Field.Flags := Field.Flags + VarFlags; Scope.AddVariable(Field); end; if Result = token_semicolon then begin Result := Lexer_NextToken(Scope); if Lexer.TokenCanBeID(Result) then begin c := 0; Continue; end; end; Break; end; end; function TASTDelphiUnit.ParseVarRecordDefaultValue(Scope: TScope; Struct: TIDStructure; out DefaultValue: TIDExpression): TTokenID; var i: Integer; ID: TIdentifier; Expr: TIDExpression; Decl: TIDDeclaration; Field: TIDField; Expressions: TIDRecordConstantFields; begin i := 0; Lexer_MatchCurToken(token_openround); SetLength(Expressions, Struct.FieldsCount); Lexer_NextToken(Scope); while True do begin Lexer_ReadCurrIdentifier(ID); Lexer_ReadToken(Scope, token_colon); Field := Struct.FindField(ID.Name); if not Assigned(Field) then ERRORS.UNDECLARED_ID(ID); if Field.DataType.DataTypeID = dtStaticArray then Result := ParseVarStaticArrayDefaultValue(Scope, TIDArray(Field.DataType), Expr) else begin Result := Lexer_NextToken(Scope); Result := ParseConstExpression(Scope, Expr, ExprRValue); end; Expressions[i].Field := Field; Expressions[i].Value := Expr; Inc(i); if Result = token_semicolon then begin Field := TIDField(Field.NextItem); Result := Lexer_NextToken(Scope); if Result = token_identifier then Continue; end; Break; end; // create anonymous record constant Decl := TIDRecordConstant.CreateAsAnonymous(Scope, Struct, Expressions); DefaultValue := TIDExpression.Create(Decl, Lexer_Position); Lexer_MatchToken(Result, token_closeround); Result := Lexer_NextToken(Scope); end; function TASTDelphiUnit.ParseVarSection(Scope: TScope; Visibility: TVisibility; IsWeak: Boolean): TTokenID; var i, c: Integer; DataType: TIDType; DefaultValue: TIDExpression; DeclAbsolute: TIDDeclaration; ID: TIdentifier; Variable: TIDVariable; Names: TIdentifiersPool; VarFlags: TVariableFlags; DeprecatedText: TIDExpression; begin c := 0; Names := TIdentifiersPool.Create(2); while True do begin VarFlags := []; Result := CheckAndParseAttribute(Scope); Lexer_MatchIdentifier(Result); Names.Add; Lexer_ReadCurrIdentifier(Names.Items[c]); Result := Lexer_NextToken(Scope); if Result = token_Coma then begin Inc(c); Lexer_NextToken(Scope); Continue; end; Lexer_MatchToken(Result, token_colon); // парсим тип Result := ParseTypeSpec(Scope, {out} DataType); DeclAbsolute := nil; DefaultValue := nil; // platform declaration if Lexer_IsCurrentToken(token_platform) then Result := ParsePlatform(Scope); // check and parse procedural type call convention Result := CheckAndParseProcTypeCallConv(Scope, Result, DataType); case Result of // значение по умолчанию token_equal: Result := ParseVarDefaultValue(Scope, DataType, {out} DefaultValue); // absolute token_absolute: begin Lexer_ReadNextIdentifier(Scope, ID); DeclAbsolute := Scope.FindID(ID.Name); if not Assigned(DeclAbsolute) then ERRORS.UNDECLARED_ID(ID); if DeclAbsolute.ItemType <> itVar then AbortWork(sVariableRequired, Lexer_Position); Result := Lexer_NextToken(Scope); end; end; // deprecated if Result = token_deprecated then Result := ParseDeprecated(Scope, DeprecatedText); for i := 0 to c do begin Variable := TIDVariable.Create(Scope, Names.Items[i]); // если это слабая ссылка - получаем соответствующий тип if IsWeak then DataType := GetWeakRefType(Scope, DataType); Variable.DataType := DataType; Variable.Visibility := Visibility; Variable.DefaultValue := DefaultValue; Variable.Absolute := TIDVariable(DeclAbsolute); Variable.Flags := Variable.Flags + VarFlags; // if isRef then // Field.Flags := Field.Flags + [VarNotNull]; Scope.AddVariable(Variable); end; if Result = token_semicolon then Result := Lexer_NextToken(Scope); if Result <> token_identifier then Exit; c := 0; end; end; function TASTDelphiUnit.ParseFieldsSection(Scope: TScope; Visibility: TVisibility; Struct: TIDStructure; IsClass: Boolean): TTokenID; var i, c: Integer; DataType: TIDType; Field: TIDVariable; Names: TIdentifiersPool; VarFlags: TVariableFlags; DeprecatedText: TIDExpression; begin c := 0; Names := TIdentifiersPool.Create(2); while True do begin VarFlags := []; Result := CheckAndParseAttribute(Scope); Lexer_MatchIdentifier(Result); Names.Add; Lexer_ReadCurrIdentifier(Names.Items[c]); Result := Lexer_NextToken(Scope); if Result = token_Coma then begin Inc(c); Lexer_NextToken(Scope); Continue; end; Lexer_MatchToken(Result, token_colon); // парсим тип Result := ParseTypeSpec(Scope, DataType); // platform declaration if Lexer_IsCurrentToken(token_platform) then Result := ParsePlatform(Scope); // deprecated if Result = token_deprecated then Result := ParseDeprecated(Scope, DeprecatedText); // check and parse procedural type call convention Result := CheckAndParseProcTypeCallConv(Scope, Result, DataType); for i := 0 to c do begin Field := TIDField.Create(Struct, Names.Items[i]); // // если это слабая ссылка - получаем соответствующий тип // if IsWeak then // DataType := GetWeakRefType(Scope, DataType); Field.DataType := DataType; Field.Visibility := Visibility; Field.DefaultValue := nil; Field.Flags := Field.Flags + VarFlags; Scope.AddVariable(Field); end; if Result <> token_identifier then Exit; c := 0; end; end; function TASTDelphiUnit.ParseVarStaticArrayDefaultValue(Scope: TScope; ArrType: TIDArray; out DefaultValue: TIDExpression): TTokenID; type TDimensionsArray = array of Integer; function DoParse(ArrType: TIDArray; const Dimensions: TDimensionsArray; DimIndex: Integer; const CArray: TIDDynArrayConstant): TTokenID; var i, c: Integer; Expr: TIDExpression; NewScope: TScope; DimensionsCount: Integer; begin Result := Lexer_NextToken(Scope); // first element initializer if Result = token_identifier then begin Result := ParseConstExpression(Scope, Expr, ExprRValue); Exit; // todo: end; if ArrType.ElementDataType.DataTypeID = dtRecord then begin NewScope := TRecordInitScope.Create(stGlobal, Scope); TRecordInitScope(NewScope).Struct := TIDStructure(ArrType.ElementDataType); NewScope.AddScope(TIDStructure(ArrType.ElementDataType).Members); end else NewScope := Scope; DimensionsCount := Length(Dimensions); Lexer_MatchToken(Result, token_openround); c := Dimensions[DimIndex] - 1; for i := 0 to c do begin if DimensionsCount > (DimIndex + 1) then Result := DoParse(ArrType, Dimensions, DimIndex + 1, CArray) else begin Lexer_NextToken(Scope); Result := ParseConstExpression(NewScope, Expr, ExprNested); CheckEmptyExpression(Expr); if CheckImplicit(fUnitSContext, Expr, CArray.ElementType) = nil then ERRORS.INCOMPATIBLE_TYPES(Expr, CArray.ElementType); Expr.Declaration.DataType := CArray.ElementType; CArray.AddItem(Expr); end; if i < c then Lexer_MatchToken(Result, token_coma); end; Lexer_MatchToken(Result, token_closeround); Result := Lexer_NextToken(Scope); end; function GetTotalDimensionsCount(ArrayType: TIDArray; out ElementType: TIDType): TDimensionsArray; begin SetLength(Result, ArrayType.DimensionsCount); for var i := 0 to ArrayType.DimensionsCount - 1 do Result[i] := ArrayType.Dimensions[i].ElementsCount; ElementType := ArrayType.ElementDataType; if ArrayType.ElementDataType.DataTypeID = dtStaticArray then Result := Result + GetTotalDimensionsCount(TIDArray(ArrayType.ElementDataType), ElementType); end; var ElementType: TIDType; Dimensions: TDimensionsArray; begin Dimensions := GetTotalDimensionsCount(ArrType, ElementType); DefaultValue := CreateAnonymousConstTuple(Scope, ElementType); Result := DoParse(ArrType, Dimensions, 0, DefaultValue.AsDynArrayConst); end; function TASTDelphiUnit.InferTypeByVector(Scope: TScope; Vector: TIDExpressions): TIDType; function MaxType(Type1, Type2: TIDType): TIDType; begin if Type1 = Type2 then Exit(Type1); if (Type1 = Sys._Variant) or (Type2 = Sys._Variant) then Exit(Sys._Variant); if (Type1.DataTypeID = dtRange) then Exit(Type1); if (Type2.DataTypeID = dtRange) then Exit(Type2); var AImplicit := Type2.GetImplicitOperatorTo(Type1); if Assigned(AImplicit) then begin if Type1.DataSize >= Type2.DataSize then Result := Type1 else Result := Type2; end else Result := Sys._Variant; end; begin if Length(Vector) = 0 then Exit(Sys._Void); var IsSet := False; var ItemType: TIDType := nil; for var AIndex := 0 to Length(Vector) - 1 do begin var Expr := Vector[AIndex]; IsSet := IsSet or Expr.IsRangeConst or (Expr.DataTypeID = dtEnum); if AIndex > 0 then ItemType := MaxType(ItemType, Expr.DataType) else ItemType := Expr.DataType; end; if not Assigned(ItemType) then ERRORS.COULD_NOT_INFER_DYNAMIC_ARRAY_TYPE(Vector); if IsSet then begin // create or find in the cache anonymous set type var ASetBaseType: TIDOrdinal; if ItemType.DataTypeID = dtRange then ASetBaseType := (ItemType as TIDRangeType).BaseType else ASetBaseType := (ItemType as TIDEnum); // search in the cache first var SetType := fCache.FindSet(ASetBaseType); if not Assigned(SetType) then begin SetType := TIDSet.CreateAsAnonymous(Scope, ASetBaseType); // add to types pool AddType(SetType); fCache.Add(SetType); end; Result := SetType; end else begin // create anonymous array type var ArrType := TIDDynArray.CreateAsAnonymous(Scope); ArrType.ElementDataType := ItemType; // add to types pool AddType(ArrType); Result := ArrType; end; end; procedure TASTDelphiUnit.ParseVector(Scope: TScope; var EContext: TEContext); var i, c, Capacity: Integer; InnerEContext: TEContext; Expr: TIDExpression; Token: TTokenID; SItems, DItems: TIDExpressions; IsStatic: Boolean; ASTExpr: TASTExpression; begin i := 0; c := 0; Capacity := 8; IsStatic := True; SetLength(SItems, Capacity); var SContext := EContext.SContext; InitEContext(InnerEContext, SContext, ExprNested); while True do begin Lexer_NextToken(Scope); Token := ParseExpression(Scope, SContext, InnerEContext, {out} ASTExpr); Expr := InnerEContext.Result; if Assigned(Expr) then begin if Expr.Declaration.ItemType <> itConst then IsStatic := False; Inc(c); SItems[i] := Expr; end else if i > 0 then CheckEmptyExpression(Expr); case Token of token_coma: begin if i = 0 then CheckEmptyExpression(Expr); Inc(i); if i >= Capacity then begin Capacity := Capacity * 2; SetLength(SItems, Capacity); end; InnerEContext.Reset; Continue; end; token_closeblock: Break; else ERRORS.UNCLOSED_OPEN_BLOCK; end; end; var AConst: TIDConstant; if c > 0 then begin // prepare expressions array SetLength(DItems, c); Move(SItems[0], DItems[0], SizeOf(Pointer)*c); // infer array type var ArrayType := InferTypeByVector(Scope, DItems); if ArrayType.DataTypeID = dtSet then begin // create anonymous set constant AConst := TIDSetConstant.CreateAsAnonymous(Scope, ArrayType, DItems); AddConstant(AConst); end else begin // create anonymous array constant AConst := TIDDynArrayConstant.CreateAsAnonymous(Scope, ArrayType, DItems); TIDDynArrayConstant(AConst).ArrayStatic := IsStatic; if IsStatic then AddConstant(AConst); end; end else AConst := Sys._EmptyArrayConstant; Expr := TIDExpression.Create(AConst, Lexer.Position); // заталкиваем массив в стек EContext.RPNPushExpression(Expr); end; function TASTDelphiUnit.GetWeakRefType(Scope: TScope; SourceDataType: TIDType): TIDWeekRef; begin if not (SourceDataType.DataTypeID in [dtClass, dtInterface]) then ERRORS.WEAKREF_CANNOT_BE_DECLARED_FOR_TYPE(SourceDataType); Result := SourceDataType.WeakRefType; if not Assigned(Result) then begin Result := TIDWeekRef.CreateAsAnonymous(Scope, SourceDataType); Result.OverloadImplicitTo(SourceDataType); Result.OverloadImplicitFrom(SourceDataType); SourceDataType.WeakRefType := Result; AddType(Result); end; end; function TASTDelphiUnit.ParsePropertyMember(var PMContext: TPMContext; Scope: TScope; Prop: TIDProperty; out Expression: TIDExpression; var EContext: TEContext; const PrevExpr: TIDExpression): TTokenID; var CallExpr: TIDCallExpression; SelfExpr: TIDExpression; Accessor: TIDDeclaration; ArgumentsCount: Integer; begin Result := Lexer_CurTokenID; Expression := TIDExpression.Create(Prop, PMContext.ID.TextPosition); if EContext.EPosition = ExprLValue then begin Accessor := TIDProperty(Prop).Setter; if not Assigned(Accessor) then ERRORS.CANNOT_MODIFY_READONLY_PROPERTY(Expression); // если сеттер - процедура, отодвигаем генерацию вызова на момент оброботки опрератора присвоения if Accessor.ItemType = itProcedure then begin Exit; end; end else begin Accessor := TIDProperty(Prop).Getter; if not Assigned(Accessor) then ERRORS.CANNOT_ACCESS_TO_WRITEONLY_PROPERTY(Expression); end; Expression.Declaration := Accessor; case Accessor.ItemType of itConst: begin PMContext.Clear; Exit; end; itVar: Expression.Declaration := Accessor; itProperty: {продолжаем выполнение}; itProcedure: begin if Assigned(PrevExpr) then SelfExpr := PrevExpr else SelfExpr := TIDProcedure(EContext.Proc).SelfParamExpression; CallExpr := TIDCallExpression.Create(Accessor); CallExpr.TextPosition := Expression.TextPosition; CallExpr.Instance := SelfExpr; if Prop.ParamsCount > 0 then Result := ParseIndexedPropertyArgs(Scope, ArgumentsCount, EContext) else ArgumentsCount := 0; CallExpr.ArgumentsCount := ArgumentsCount; EContext.RPNPushExpression(CallExpr); Expression := Process_CALL(EContext); PMContext.Clear; end; else ERRORS.FEATURE_NOT_SUPPORTED; end; end; function TASTDelphiUnit.CreateAnonymousConstTuple(Scope: TScope; ElementDataType: TIDType): TIDExpression; var Decl: TIDDynArrayConstant; AType: TIDDynArray; begin AType := TIDDynArray.CreateAsAnonymous(Scope); AType.ElementDataType := ElementDataType; Decl := TIDDynArrayConstant.CreateAsAnonymous(Scope, AType, nil); Result := TIDExpression.Create(Decl); end; class function TASTDelphiUnit.CreateRangeType(Scope: TScope; LoBound, HiBound: Integer): TIDRangeType; begin Result := TIDRangeType.CreateAsAnonymous(Scope); Result.LowBound := LoBound; Result.HighBound := HiBound; end; procedure TASTDelphiUnit.CheckIntfSectionMissing(Scope: TScope); begin if not Assigned(Scope) then ERRORS.INTF_SECTION_MISSING; end; procedure TASTDelphiUnit.CheckConstExpression(Expression: TIDExpression); begin if not (Expression.Declaration.ItemType in [itConst, itProcedure]) then ERRORS.CONST_EXPRESSION_REQUIRED(Expression); end; procedure TASTDelphiUnit.CheckConstValueOverflow(Src: TIDExpression; DstDataType: TIDType); var Matched: Boolean; ValueI64: Int64; ValueU64: Int64; DataType: TIDType; begin if Src.Declaration is TIDIntConstant then begin DataType := DstDataType.ActualDataType; ValueI64 := TIDIntConstant(Src.Declaration).AsInt64; ValueU64 := TIDIntConstant(Src.Declaration).AsUInt64; case DataType.DataTypeID of dtInt8: Matched := (ValueI64 >= MinInt8) and (ValueI64 <= MaxInt8); dtInt16: Matched := (ValueI64 >= MinInt16) and (ValueI64 <= MaxInt16); dtInt32: Matched := (ValueI64 >= MinInt32) and (ValueI64 <= MaxInt32); //dtInt64: Matched := (IntValue >= MinInt64) and (IntValue <= MaxInt64); // always true dtUInt8: Matched := (ValueU64 <= MaxUInt8); dtUInt16: Matched := (ValueU64 <= MaxUInt16); dtUInt32: Matched := (ValueU64 <= MaxUInt32); dtUInt64: Matched := (ValueU64 <= MaxUInt64); dtBoolean: Matched := (ValueU64 <= 1); dtAnsiChar: Matched := (ValueU64 <= MaxUInt8); dtChar: Matched := (ValueU64 <= MaxUInt16); else Matched := True; end; // todo: it doesn't work with explicit casted values if not Matched then; // ERRORS.CONST_VALUE_OVERFLOW(Src, DstDataType); end; // необходимо реализовать проверку остальных типов end; class procedure TASTDelphiUnit.CheckDestructorSignature(const DProc: TIDProcedure); begin end; procedure TASTDelphiUnit.CheckEmptyExpression(Expression: TIDExpression); begin if not Assigned(Expression) then ERRORS.EMPTY_EXPRESSION; end; procedure TASTDelphiUnit.CheckEndOfFile(Token: TTokenID); begin if Token = token_eof then ERRORS.END_OF_FILE; end; procedure TASTDelphiUnit.CheckIntExpression(Expression: TIDExpression); begin if Expression.DataTypeID >= dtNativeUInt then ERRORS.INTEGER_TYPE_REQUIRED(Expression.TextPosition); end; procedure TASTDelphiUnit.CheckOrdinalExpression(Expression: TIDExpression); begin if not Expression.DataType.IsOrdinal then ERRORS.ORDINAL_TYPE_REQUIRED(Expression.TextPosition); end; procedure TASTDelphiUnit.CheckOrdinalType(DataType: TIDType); begin if not DataType.IsOrdinal then ERRORS.ORDINAL_TYPE_REQUIRED(Lexer_Position); end; class procedure TASTDelphiUnit.CheckNumericExpression(Expression: TIDExpression); begin if not (Expression.DataTypeID in [dtInt8..dtChar]) then AbortWork(sNumericTypeRequired, Expression.TextPosition); end; class procedure TASTDelphiUnit.CheckPointerType(Expression: TIDExpression); begin if not (Expression.DataTypeID in [dtPointer, dtPAnsiChar, dtPWideChar]) then AbortWork(sPointerTypeRequired, Expression.TextPosition); end; procedure TASTDelphiUnit.CheckProcedureType(DeclType: TIDType); begin if (DeclType.DataTypeID <> dtProcType) then AbortWork('Procedure type required', Lexer.Position); end; class procedure TASTDelphiUnit.CheckIntConstInRange(const Expr: TIDExpression; HiBount, LowBound: Int64); var V64: Int64; begin V64 := Expr.AsIntConst.Value; if (V64 < LowBound) or (V64 > HiBount) then AbortWork('Eexpression must be in range [%d..%d]', [LowBound, HiBount], Expr.TextPosition); end; class procedure TASTDelphiUnit.CheckRecordType(Expression: TIDExpression); var Decl: TIDDeclaration; begin Decl := Expression.Declaration; if (Decl.ItemType <> itType) or (TIDType(Decl).DataTypeID <> dtRecord) then AbortWork(sRecordTypeRequired, Expression.TextPosition); end; class procedure TASTDelphiUnit.CheckReferenceType(Expression: TIDExpression); begin if not Expression.DataType.IsReferenced then AbortWork(sReferenceTypeRequired, Expression.TextPosition); end; class procedure TASTDelphiUnit.CheckSetType(Expression: TIDExpression); begin end; class procedure TASTDelphiUnit.CheckStaticRecordConstructorSign(const CProc: TIDProcedure); begin end; procedure TASTDelphiUnit.CheckStingType(DataType: TIDType); begin if DataType.DataTypeID <> dtString then AbortWork(sStringExpressionRequired, Lexer_Position); end; class procedure TASTDelphiUnit.CheckStringExpression(Expression: TIDExpression); begin if MatchImplicit(Expression.DataType, Expression.Declaration.SysUnit._UnicodeString) = nil then AbortWork(sStringExpressionRequired, Expression.TextPosition); end; class procedure TASTDelphiUnit.CheckStructType(Decl: TIDType); begin if not (Decl is TIDStructure) then AbortWork(sStructTypeRequired, Decl.TextPosition); end; class procedure TASTDelphiUnit.CheckStructType(Expression: TIDExpression); var Decl: TIDDeclaration; begin Decl := Expression.Declaration; if not (Decl is TIDStructure) then AbortWork(sStructTypeRequired, Expression.TextPosition); end; procedure TASTDelphiUnit.CheckType(Expression: TIDExpression); begin if Expression.ItemType <> itType then ERRORS.TYPE_REQUIRED(Expression.TextPosition); end; class procedure TASTDelphiUnit.CheckInterfaceType(Expression: TIDExpression); var Decl: TIDDeclaration; begin Decl := Expression.Declaration; if (Decl.ItemType <> itType) or (TIDType(Decl).DataTypeID <> dtInterface) then AbortWork(sInterfaceTypeRequired, Expression.TextPosition); end; procedure TASTDelphiUnit.CheckClassOrIntfType(Expression: TIDExpression); var Decl: TIDDeclaration; begin Decl := Expression.Declaration; if (Decl.ItemType = itType) and ((TIDType(Decl).DataTypeID = dtClass) or (TIDType(Decl).DataTypeID = dtInterface)) then Exit; ERRORS.CLASS_OR_INTF_TYPE_REQUIRED(Expression.TextPosition); end; procedure TASTDelphiUnit.CheckClassOrClassOfOrIntfType(Expression: TIDExpression); var Decl: TIDDeclaration; begin Decl := Expression.Declaration; if (Decl.ItemType = itType) and ((TIDType(Decl).DataTypeID = dtClass) or (TIDType(Decl).DataTypeID = dtInterface)) then Exit; if (Decl.ItemType = itVar) and (TIDVariable(Decl).DataTypeID = dtClassOf) then Exit; ERRORS.CLASS_OR_INTF_TYPE_REQUIRED(Expression.TextPosition); end; procedure TASTDelphiUnit.CheckClassOrIntfType(DataType: TIDType; const TextPosition: TTextPosition); begin if (DataType.DataTypeID = dtClass) or (DataType.DataTypeID = dtInterface) then Exit; ERRORS.CLASS_OR_INTF_TYPE_REQUIRED(TextPosition); end; procedure TASTDelphiUnit.CheckClassType(Expression: TIDExpression); var Decl: TIDDeclaration; begin Decl := Expression.Declaration; if (Decl.ItemType <> itType) or (TIDType(Decl).DataTypeID <> dtClass) then ERRORS.CLASS_TYPE_REQUIRED(Expression.TextPosition); end; procedure TASTDelphiUnit.CheckExceptionType(Decl: TIDDeclaration); begin // todo: add System.Exception type inheritance if (Decl.ItemType <> itType) or (TIDType(Decl).DataTypeID <> dtClass) {or TIDClass(Decl).IsInheritsForm()} then ERRORS.CLASS_TYPE_REQUIRED(Lexer_Position); end; procedure TASTDelphiUnit.CheckClassExpression(Expression: TIDExpression); begin if Expression.DataTypeID <> dtClass then ERRORS.CLASS_TYPE_REQUIRED(Expression.TextPosition); end; procedure TASTDelphiUnit.CheckImplicitTypes(Src, Dst: TIDType; Position: TTextPosition); begin if not Assigned(Src) then ERRORS.EMPTY_EXPRESSION; if not Assigned(MatchImplicit(Src, Dst)) then AbortWork(sIncompatibleTypesFmt, [Src.DisplayName, Dst.DisplayName], Position); end; procedure TASTDelphiUnit.CheckIncompletedIntfProcs(ClassType: TIDClass); var i: Integer; Intf: TIDInterface; IM, CM: TIDProcedure; Matched: Boolean; begin for i := 0 to ClassType.InterfacesCount - 1 do begin Intf := ClassType.Interfaces[i]; IM := Intf.Methods.First; while Assigned(IM) do begin CM := ClassType.FindMethod(IM.Name); if not Assigned(CM) then ERRORS.INTF_METHOD_NOT_IMPLEMENTED(ClassType, IM); Matched := StrictMatchProc(IM, CM); if not Matched then ERRORS.INTF_METHOD_NOT_IMPLEMENTED(ClassType, IM); // tmp !!! ClassType.MapInterfaceMethod(Intf, IM, CM); IM := TIDProcedure(IM.NextItem); end; end; end; procedure TASTDelphiUnit.CheckIncompleteFwdTypes; var T: TIDType; DT: TIDDeclaration; begin T := TypeSpace.First; while Assigned(T) do begin if T.DataTypeID = dtPointer then begin DT := TIDPointer(T).ReferenceType; // запрос сделает инициализацию ReferenceType if Assigned(DT) then; // Assert(Assigned(DT)); end; T := TIDType(T.NextItem); end; end; class procedure TASTDelphiUnit.CheckIncompleteType(Fields: TScope); var Field: TIDDeclaration; FieldType: TIDType; begin Field := Fields.VarSpace.First; while Assigned(Field) do begin FieldType := Field.DataType; if (Field.DataTypeID = dtRecord) and (not(StructCompleted in TIDStructure(FieldType).StructFlags)) then AbortWork(sRecurciveTypeLinkIsNotAllowed, Field.ID.TextPosition); Field := Field.NextItem; end; end; procedure TASTDelphiUnit.CheckVarExpression(Expression: TIDExpression; VarModifyPlace: TVarModifyPlace); var Flags: TVariableFlags; Decl: TIDDeclaration; begin if Expression.ExpressionType = etDeclaration then Decl := Expression.Declaration else Decl := TIDMultiExpression(Expression).Items[0].Declaration; // пока так // сдесь необходимо отдельно обрабатывать случаи: // 1. доступа к членам класса/структуры // 2. массива // 3. индексного свойства if (Decl.ItemType = itProperty) and Assigned(TIDProperty(Decl).Setter) then Exit; if Decl.ItemType <> itVar then case VarModifyPlace of vmpAssignment: ERRORS.VAR_EXPRESSION_REQUIRED(Expression); vmpPassArgument: ERRORS.ARG_VAR_REQUIRED(Expression); end; Flags := TIDVariable(Decl).Flags; if (VarConst in Flags) and (Expression.DataType <> Sys._UntypedReference) then begin ERRORS.CANNOT_MODIFY_CONSTANT(Expression); end; if VarLoopIndex in Flags then ERRORS.CANNOT_MODIFY_FOR_LOOP_VARIABLE(Expression); end; procedure TASTDelphiUnit.CheckVarParamConformity(Param: TIDVariable; Arg: TIDExpression); begin if (Param.DataTypeID = dtOpenArray) and (Arg.DataType is TIDArray) then Exit; if (Param.DataType <> Sys._UntypedReference) and not ((Param.DataType.DataTypeID = dtPointer) and (Arg.DataType.DataTypeID = dtPointer)) then ERRORS.REF_PARAM_MUST_BE_IDENTICAL(Arg); end; class procedure TASTDelphiUnit.CheckAccessMember(SContext: PSContext; Decl: TIDDeclaration; const ID: TIdentifier); begin case Decl.Visibility of vLocal, vPublic: Exit; vProtected: begin if Decl.Module = SContext.Proc.Module then Exit; if not SContext.Proc.Struct.IsInheritsForm(TStructScope(Decl.Scope).Struct) then SContext.ERRORS.CANNOT_ACCESS_PRIVATE_MEMBER(ID); end; vStrictProtected: begin if not SContext.Proc.Struct.IsInheritsForm(TStructScope(Decl.Scope).Struct) then SContext.ERRORS.CANNOT_ACCESS_PRIVATE_MEMBER(ID); end; vPrivate: begin if Decl.Module = SContext.Proc.Module then Exit; if TStructScope(Decl.Scope).Struct <> SContext.Proc.Struct then SContext.ERRORS.CANNOT_ACCESS_PRIVATE_MEMBER(ID); end; vStrictPrivate: begin if TStructScope(Decl.Scope).Struct <> SContext.Proc.Struct then SContext.ERRORS.CANNOT_ACCESS_PRIVATE_MEMBER(ID); end; end; end; procedure TASTDelphiUnit.CheckArrayExpression(Expression: TIDExpression); begin if not (Expression.DataType is TIDArray) then ERRORS.ARRAY_EXPRESSION_REQUIRED(Expression); end; procedure TASTDelphiUnit.CheckBooleanExpression(Expression: TIDExpression); begin if Expression.DataType <> Sys._Boolean then ERRORS.BOOLEAN_EXPRESSION_REQUIRED(Expression); end; { TSContextHelper } function TSContextHelper.GetErrors: TASTDelphiErrors; begin Result := TASTDelphiUnit(Module).ERRORS; end; function TSContextHelper.GetSysUnit: TSYSTEMUnit; begin Result := TASTDelphiUnit(Module).fSysUnit as TSYSTEMUnit; end; function ScopeToVarList(Scope: TScope; SkipFirstCount: Integer): TIDParamArray; var item: TIDDeclaration; i: Integer; begin if Scope.VarSpace.Count > 0 then begin item := Scope.VarSpace.First; SetLength(Result, Scope.VarSpace.Count - SkipFirstCount); // пропускаем N первых элементов for i := 0 to SkipFirstCount - 1 do item := item.NextItem; i := 0; while Assigned(item) do begin Result[i] := TIDVariable(item); item := item.NextItem; Inc(i); end; end else Result := []; end; { TDeclCache } procedure TDeclCache.Add(Decl: TIDRangeType); begin fRanges.Add(Decl); end; procedure TDeclCache.Add(Decl: TIDSet); begin fSets.Add(Decl); end; constructor TDeclCache.Create; begin fRanges := TList<TIDRangeType>.Create; fSets := TList<TIDSet>.Create; end; destructor TDeclCache.Destroy; begin fRanges.Free; fSets.Free; inherited; end; function TDeclCache.FindRange(BaseType: TIDType; LoBound, HiBound: TIDExpression): TIDRangeType; begin for var i := 0 to fRanges.Count - 1 do begin Result := fRanges[i]; if (Result.BaseType = BaseType) and (Result.LoDecl.AsInt64 = LoBound.AsConst.AsInt64) and (Result.HiDecl.AsInt64 = HiBound.AsConst.AsInt64) then Exit; end; Result := nil; end; function TDeclCache.FindSet(BaseType: TIDType): TIDSet; begin for var i := 0 to fSets.Count - 1 do begin Result := fSets[i]; if Result.BaseType = BaseType then Exit; end; Result := nil; end; end.
// // Generated by JavaToPas v1.4 20140515 - 182154 //////////////////////////////////////////////////////////////////////////////// unit android.app.Instrumentation_ActivityMonitor; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, android.content.IntentFilter, android.app.Instrumentation_ActivityResult, android.app.Activity; type JInstrumentation_ActivityMonitor = interface; JInstrumentation_ActivityMonitorClass = interface(JObjectClass) ['{E45FD81B-EB36-46AF-98DB-679DDBBDBA5B}'] function getFilter : JIntentFilter; cdecl; // ()Landroid/content/IntentFilter; A: $11 function getHits : Integer; cdecl; // ()I A: $11 function getLastActivity : JActivity; cdecl; // ()Landroid/app/Activity; A: $11 function getResult : JInstrumentation_ActivityResult; cdecl; // ()Landroid/app/Instrumentation$ActivityResult; A: $11 function init(cls : JString; result : JInstrumentation_ActivityResult; block : boolean) : JInstrumentation_ActivityMonitor; cdecl; overload;// (Ljava/lang/String;Landroid/app/Instrumentation$ActivityResult;Z)V A: $1 function init(which : JIntentFilter; result : JInstrumentation_ActivityResult; block : boolean) : JInstrumentation_ActivityMonitor; cdecl; overload;// (Landroid/content/IntentFilter;Landroid/app/Instrumentation$ActivityResult;Z)V A: $1 function isBlocking : boolean; cdecl; // ()Z A: $11 function waitForActivity : JActivity; cdecl; // ()Landroid/app/Activity; A: $11 function waitForActivityWithTimeout(timeOut : Int64) : JActivity; cdecl; // (J)Landroid/app/Activity; A: $11 end; [JavaSignature('android/app/Instrumentation_ActivityMonitor')] JInstrumentation_ActivityMonitor = interface(JObject) ['{7776F3A3-14F8-4206-9455-DBEE3AEA86AF}'] end; TJInstrumentation_ActivityMonitor = class(TJavaGenericImport<JInstrumentation_ActivityMonitorClass, JInstrumentation_ActivityMonitor>) end; implementation end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Objects, FMX.Edit, FMX.Menus, FMX.StdCtrls, FMX.Controls.Presentation; type TForm1 = class(TForm) DistanceLabel: TLabel; DistanceEdit: TEdit; SpeedLabel: TLabel; SpeedEdit: TEdit; CalculateButton: TButton; CarImage: TImage; ResultLabel: TLabel; FlagImage: TImage; MainMenu1: TMainMenu; File1: TMenuItem; Calculate1: TMenuItem; N1: TMenuItem; Exit1: TMenuItem; Help1: TMenuItem; About1: TMenuItem; Language1: TMenuItem; procedure FormCreate(Sender: TObject); procedure Language1Click(Sender: TObject); procedure EditChange(Sender: TObject); procedure CalculateButtonClick(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure About1Click(Sender: TObject); private function GetDistance: Double; function GetSpeed: Double; public property Distance: Double read GetDistance; property Speed: Double read GetSpeed; end; var Form1: TForm1; implementation {$R *.fmx} uses NtPattern, NtResource, FMX.NtImageTranslator, FMX.NtLanguageDlg, FMX.NtTranslator; function TForm1.GetDistance: Double; begin Result := StrToFloatDef(DistanceEdit.Text, 0); end; function TForm1.GetSpeed: Double; begin Result := StrToFloatDef(SpeedEdit.Text, 0); end; procedure TForm1.FormCreate(Sender: TObject); begin NtResources._T('English', 'en'); NtResources._T('Finnish', 'fi'); NtResources._T('German', 'de'); NtResources._T('French', 'fr'); NtResources._T('Spanish', 'es'); NtResources._T('Japanese', 'ja'); _T(Self); EditChange(Self); end; procedure TForm1.EditChange(Sender: TObject); begin CalculateButton.Enabled := (Distance > 0) and (Speed > 0); Calculate1.Enabled := CalculateButton.Enabled; end; procedure TForm1.CalculateButtonClick(Sender: TObject); var time: Double; hours, minutes: Integer; begin if Speed = 0 then Exit; time := Distance/Speed; hours := Trunc(time); minutes := Round(60*(time - hours)); // This multi-plural pattern has two parameters (hours and minutes). // It uses standard plural rules of English (1 = singular, all other are plurals) plus special zero case in hours. ResultLabel.Text := TMultiPattern.Format(_T('Driving time{plural, zero { } one { %d hour } other { %d hours }}{plural, one {%d minute} other {%d minutes}}.', 'ResultPlural'), [hours, minutes]); end; procedure TForm1.Language1Click(Sender: TObject); begin TNtLanguageDialog.Select(procedure begin CalculateButtonClick(Self); end); end; procedure TForm1.Exit1Click(Sender: TObject); begin Close; end; procedure TForm1.About1Click(Sender: TObject); begin ShowMessage(_T('Driving time calculator')); end; end.
// // Generated by JavaToPas v1.4 20140515 - 181823 //////////////////////////////////////////////////////////////////////////////// unit org.apache.http.impl.conn.LoggingSessionInputBuffer; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, org.apache.http.io.SessionInputBuffer, org.apache.http.impl.conn.Wire, org.apache.http.util.CharArrayBuffer, org.apache.http.io.HttpTransportMetrics; type JLoggingSessionInputBuffer = interface; JLoggingSessionInputBufferClass = interface(JObjectClass) ['{2ED2179D-1CA9-49CD-A33B-B7D7C6F90925}'] function &read : Integer; cdecl; overload; // ()I A: $1 function &read(b : TJavaArray<Byte>) : Integer; cdecl; overload; // ([B)I A: $1 function &read(b : TJavaArray<Byte>; off : Integer; len : Integer) : Integer; cdecl; overload;// ([BII)I A: $1 function getMetrics : JHttpTransportMetrics; cdecl; // ()Lorg/apache/http/io/HttpTransportMetrics; A: $1 function init(&in : JSessionInputBuffer; wire : JWire) : JLoggingSessionInputBuffer; cdecl;// (Lorg/apache/http/io/SessionInputBuffer;Lorg/apache/http/impl/conn/Wire;)V A: $1 function isDataAvailable(timeout : Integer) : boolean; cdecl; // (I)Z A: $1 function readLine : JString; cdecl; overload; // ()Ljava/lang/String; A: $1 function readLine(buffer : JCharArrayBuffer) : Integer; cdecl; overload; // (Lorg/apache/http/util/CharArrayBuffer;)I A: $1 end; [JavaSignature('org/apache/http/impl/conn/LoggingSessionInputBuffer')] JLoggingSessionInputBuffer = interface(JObject) ['{FDB131D1-B8F1-483A-90B0-C4AC799B33FD}'] function &read : Integer; cdecl; overload; // ()I A: $1 function &read(b : TJavaArray<Byte>) : Integer; cdecl; overload; // ([B)I A: $1 function &read(b : TJavaArray<Byte>; off : Integer; len : Integer) : Integer; cdecl; overload;// ([BII)I A: $1 function getMetrics : JHttpTransportMetrics; cdecl; // ()Lorg/apache/http/io/HttpTransportMetrics; A: $1 function isDataAvailable(timeout : Integer) : boolean; cdecl; // (I)Z A: $1 function readLine : JString; cdecl; overload; // ()Ljava/lang/String; A: $1 function readLine(buffer : JCharArrayBuffer) : Integer; cdecl; overload; // (Lorg/apache/http/util/CharArrayBuffer;)I A: $1 end; TJLoggingSessionInputBuffer = class(TJavaGenericImport<JLoggingSessionInputBufferClass, JLoggingSessionInputBuffer>) end; implementation end.
unit HashAlgEngine_U; // Description: Hashing Engine Base Class // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, SDUGeneral, HashValue_U; type THashAlgEngine = class protected procedure HE_memcpy(var output: array of byte; const input: array of byte; const startA, startB, len: cardinal); overload; procedure HE_memcpy(var output: array of DWORD; const input: array of DWORD; const startA, startB, len: cardinal); overload; procedure HE_memset(var output: array of byte; const value: cardinal; const start, len: cardinal); overload; procedure HE_memset(var output: array of DWORD; const value: DWORD; const start, len: cardinal); overload; procedure HE_memset(var output: array of ULONGLONG; const value: ULONGLONG; const start, len: cardinal); overload; end; implementation // Note: Replace "for loop" with standard memcpy if possible. procedure THashAlgEngine.HE_memcpy(var output: array of byte; const input: array of byte; const startA, startB, len: cardinal); var i: cardinal; begin for i:=1 to len do begin output[startA+i-1] := input[startB+i-1]; end; end; // Note: Replace "for loop" with standard memcpy if possible. procedure THashAlgEngine.HE_memcpy(var output: array of DWORD; const input: array of DWORD; const startA, startB, len: cardinal); var i: cardinal; begin for i:=1 to len do begin output[startA+i-1] := input[startB+i-1]; end; end; // Note: Replace "for loop" with standard memset if possible. procedure THashAlgEngine.HE_memset(var output: array of byte; const value: cardinal; const start, len: cardinal); var i: cardinal; begin for i:=1 to len do begin output[start+i-1] := value; end; end; // Note: Replace "for loop" with standard memset if possible. procedure THashAlgEngine.HE_memset(var output: array of DWORD; const value: DWORD; const start, len: cardinal); var i: cardinal; begin for i:=1 to len do begin output[start+i-1] := value; end; end; // Note: Replace "for loop" with standard memset if possible. procedure THashAlgEngine.HE_memset(var output: array of ULONGLONG; const value: ULONGLONG; const start, len: cardinal); var i: cardinal; begin for i:=1 to len do begin output[start+i-1] := value; end; end; END.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { 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 DPM.Core.Utils.Path; interface type TPathUtils = class //TPath.IsPathRooted treats \xx as rooted which is incorrect class function IsPathRooted(const value : string) : boolean; //SysUtils.IsRelativePath returns false with paths starting with .\ grrrrrr class function IsRelativePath(const value : string) : boolean; class function CompressRelativePath(basePath : string; path : string) : string;overload; class function CompressRelativePath(path : string) : string;overload; class function QuotePath(const value : string; const force : boolean = false) : string; class function StripBase(const base : string; const fileName : string) : string; class function StripWildCard(const value : string) : string; end; implementation uses System.Types, System.IOUtils, System.SysUtils, System.StrUtils, System.RegularExpressions, Spring.Collections, DPM.Core.Utils.Strings; //Copied from XE7 function StartsWith(const current : string; const Value : string; IgnoreCase : Boolean = false) : Boolean; begin if not IgnoreCase then Result := System.SysUtils.StrLComp(PChar(current), PChar(Value), Length(Value)) = 0 else Result := System.SysUtils.StrLIComp(PChar(current), PChar(Value), Length(Value)) = 0; end; function EndsWith(const theString : string; const Value : string; IgnoreCase : Boolean = true) : Boolean; begin if IgnoreCase then Result := EndsText(Value, theString) else result := EndsStr(Value, theString); end; function IndexOfAny(const value : string; const AnyOf : array of Char; StartIndex, Count : Integer) : Integer; var I : Integer; C : Char; Max : Integer; begin if (StartIndex + Count) >= Length(value) then Max := Length(value) else Max := StartIndex + Count; I := StartIndex; while I < Max do begin for C in AnyOf do if value[I] = C then Exit(I); Inc(I); end; Result := -1; end; function LastIndexOf(const theString : string; Value : Char; StartIndex, Count : Integer) : Integer; var I : Integer; Min : Integer; begin if StartIndex < Length(theString) then I := StartIndex else I := Length(theString); if (StartIndex - Count) < 0 then Min := 1 else Min := StartIndex - Count; while I >= Min do begin if theString[I] = Value then Exit(I); Dec(I); end; Result := -1; end; function AntSplit(const value : string; const Separator: array of Char; const Count: Integer): TArray<string>; const DeltaGrow = 32; var NextSeparator, LastIndex: Integer; Total: Integer; CurrentLength: Integer; S: string; begin Total := 0; LastIndex := 1; CurrentLength := 0; NextSeparator := IndexOfAny(value, Separator, LastIndex, Length(value)); while (NextSeparator >= 0) and (Total < Count) do begin S := Copy(value, LastIndex, NextSeparator - LastIndex); if (S <> '') then begin Inc(Total); if CurrentLength < Total then begin CurrentLength := Total + DeltaGrow; SetLength(Result, CurrentLength); end; Result[Total - 1] := S; end; LastIndex := NextSeparator + 1; NextSeparator := IndexOfAny(value, Separator, LastIndex, Length(value)); end; if (LastIndex < Length(value)) and (Total < Count) then begin Inc(Total); SetLength(Result, Total); Result[Total - 1] := Copy(value, LastIndex, Length(value)); end else SetLength(Result, Total); end; { TPathUtils } //class function TPathUtils.CompressRelativePath(const basePath : string; path : string) : string; //var // stack : IStack<string>; // segments : TArray<string>; // segment : string; //begin // if not TPath.IsPathRooted(path) then // path := IncludeTrailingPathDelimiter(basePath) + path // else if not StartsWith(path, basePath) then // exit(path); //should probably except ? // // segments := AntSplit(path, [PathDelim], MaxInt, None); // stack := TCollections.CreateStack < string > ; // for segment in segments do // begin // if segment = '..' then // begin // if stack.Count > 0 then // stack.Pop //up one // else // raise Exception.Create('Relative path goes below base path'); // end // else if segment <> '.' then // stack.Push(segment); // end; // result := ''; // while stack.Count > 0 do // begin // if result <> '' then // result := stack.Pop + PathDelim + result // else // result := stack.Pop; // end; // if EndsWith(path, PathDelim) then // result := IncludeTrailingPathDelimiter(result); //end; class function TPathUtils.CompressRelativePath(basePath: string; path: string): string; var stack : IStack<string>; segments : TArray<string>; segment : string; baseSegments : TArray<string>; baseSegLength : integer; isUnc : boolean; begin if path = '' then exit(path); isUnc := false; if basePath <> '' then begin if TPath.IsUNCPath(basePath) then begin isUnc := true; Delete(basePath,1,2); if StartsWith(path, PathDelim) then path := basePath + path else path := IncludeTrailingPathDelimiter(basePath) + path; end else begin if not TPathUtils.IsPathRooted(path) then //TPath.IsPathRooted treats \ as rooted.. which is incorrect path := IncludeTrailingPathDelimiter(basePath) + path else if not StartsWith(path, basePath) then exit(path); end; baseSegments := AntSplit(basePath, [PathDelim], MaxInt); baseSegLength := Length(baseSegments); end else baseSegLength := 1; stack := TCollections.CreateStack<string>; if TPath.IsUNCPath(path) then begin Delete(path,1,2); isUnc := true; end; segments := AntSplit(path, [PathDelim], MaxInt); for segment in segments do begin if segment = '..' then begin if stack.Count > 1 then stack.Pop; //up one and don't add end else if segment <> '.' then stack.Push(segment); end; result := ''; if stack.Count < baseSegLength then exit(path); while stack.Count > 0 do begin if result <> '' then result := stack.Pop + PathDelim + result else result := stack.Pop; end; if EndsWith(path, PathDelim) then result := IncludeTrailingPathDelimiter(result); if EndsWith(result, ':') then result := result + PathDelim; if isUnc then result := '\\' + result; if (basePath <> '') then begin if isUnc then basePath := '\\' + basePath; //TODO : this is bogus, because a ..\ could change this // it was added for copylocal so need to test that. // if not StartsWith(result, basePath) then // exit(path); end; end; class function TPathUtils.CompressRelativePath(path: string): string; begin if path = '' then exit(path); result := CompressRelativePath('', path); end; class function TPathUtils.IsRelativePath(const value : string) : boolean; begin //why did we need this. System.SysUtils.IsRelativePath seems to work for XE2+ // result := (not TPath.IsUNCPath(value) and TStringUtils.StartsWith(value, '.\')) or System.SysUtils.IsRelativePath(value); result := System.SysUtils.IsRelativePath(value); end; class function TPathUtils.QuotePath(const value: string; const force : boolean = false): string; begin if force or (Pos(' ', value) > 0) then result := '"' + value + '"' else result := value; end; class function TPathUtils.StripBase(const base : string; const fileName : string) : string; begin if TStringUtils.StartsWith(fileName, base) then result := Copy(fileName, Length(base) + 1, Length(fileName)) else //it's below or outside the base path, //there's no way to know what else to do //but just use the filename, so it will //end up in the root folder?? result := ExtractFileName(fileName); end; class function TPathUtils.StripWildCard(const value : string) : string; var i : integer; begin result := value; i := Pos('*', value); if i > 0 then Delete(result, i, Length(result)); end; class function TPathUtils.IsPathRooted(const value: string): boolean; begin result := TRegEx.IsMatch(value, '^[a-zA-z]\:\\|\\\\'); end; end.
//============================================================================= //调用函数说明: // 发送文字到主程序控制台上: // procedure MainOutMessasge(sMsg:String;nMode:integer) // sMsg 为要发送的文本内容 // nMode 为发送模式,0为立即在控制台上显示,1为加入显示队列,稍后显示 // // 取得0-255所代表的颜色 // function GetRGB(bt256:Byte):TColor; // bt256 要查询数字 // 返回值 为代表的颜色 // // 发送广播文字: // procedure SendBroadCastMsg(sMsg:String;MsgType:TMsgType); // sMsg 要发送的文字 // MsgType 文字类型 //============================================================================= unit PlugMain; interface uses Windows, SysUtils, Des{, IniFiles}; procedure InitPlug(AppHandle: THandle; boLoadSucced: Boolean); function DeCodeText(sText: string): string; function SearchIPLocal(sIPaddr: string): string; function DecodeString_3des(Source, Key: string): string; function EncodeString_3des(Source, Key: string): string; function StartRegisterLicense(sRegisterCode: string): Boolean; function CheckLicense(sRegisterCode: string): Boolean; procedure Open(); function GetRegisterName(): string; function GetLicense(sRegisterName: string): Integer;//比较注册码是否正确 //RC6算法 ,保存注册码使用 function String_DRR(Source, Key: string): string;//RC6 解密 function String_ERR(Source, Key: string): string;//RC6 加密 implementation uses Module, QQWry, DESTR, Share, DiaLogMain, HardInfo, MD5EncodeStr,AES, EDcode,sdk, ChinaRAS, RC6; //DES3算法 function DecodeString_3des(Source, Key: string): string; var Decode: TDCP_3des; begin {$I VMProtectBegin.inc} try Result := ''; Decode := TDCP_3des.Create(nil); Decode.InitStr(Key); Decode.Reset; Result := Decode.DecryptString(Source); Decode.Reset; Decode.Free; except Result := ''; end; {$I VMProtectEnd.inc} end; function EncodeString_3des(Source, Key: string): string; var Encode: TDCP_3des; begin {$I VMProtectBegin.inc} try Result := ''; Encode := TDCP_3des.Create(nil); Encode.InitStr(Key); Encode.Reset; Result := Encode.EncryptString(Source); Encode.Reset; Encode.Free; except Result := ''; end; {$I VMProtectEnd.inc} end; //RC6算法 ,保存注册码使用 function String_DRR(Source, Key: string): string; var Decode: TDCP_rc6; begin {$I VMProtectBegin.inc} try Result := ''; Decode := TDCP_rc6.Create(nil); Decode.InitStr(Key); Decode.Reset; Result := Decode.DecryptString(Source); Decode.Reset; Decode.Free; except Result := ''; end; {$I VMProtectEnd.inc} end; function String_ERR(Source, Key: string): string; var Encode: TDCP_rc6; begin {$I VMProtectBegin.inc} try Result := ''; Encode := TDCP_rc6.Create(nil); Encode.InitStr(Key); Encode.Reset; Result := Encode.EncryptString(Source); Encode.Reset; Encode.Free; except Result := ''; end; {$I VMProtectEnd.inc} end; //============================================================================= //加载插件模块时调用的初始化函数 //参数:Apphandle 为主程序句柄 //============================================================================= function GetRegisterName(): string; var sRegisterName, Str: string; begin sRegisterName := ''; Try Str := ''; if sRegisterName = '' then begin try sRegisterName := Trim(HardInfo.GetCPUInfo_); //CPU序列号 except sRegisterName := ''; end; end; if sRegisterName = '' then begin try sRegisterName := Trim({HardInfo.GetAdapterMac(0)}HardInfo.MacAddress); //网卡地址 20080717 except sRegisterName := ''; end; end; if sRegisterName = '' then begin try sRegisterName := Trim(HardInfo.GetScsisn); //硬盘序列号 except sRegisterName := ''; end; end; if sRegisterName <> '' then begin Str := EncodeString_3des(sRegisterName, sDecryKey); Result := RivestStr(Str); end else Result := ''; except end; end; function CheckLicense(sRegisterCode: string): Boolean; var sTempStr: string; i:integer; b:Int64; S:String; const s_s01 = '.O,+*Q)%''&&&&&&&P$>=<;:9^XJKIHGEB'; begin Result := False; Try if m_sRegisterName <> '' then begin {$I VMProtectBegin.inc} //sTempStr := EncodeString_3des(m_sRegisterName, sDecryKey); //sTempStr := RivestStr(sTempStr);// --MD5算法 S := EncodeString_3des(m_sRegisterName, sDecryKey); b:=0; for i:=1 to Length(S) do b:=b+ord(S[i])*10; ChinaRAS_Init(S); ChinaRAS_EN(B); S:=IntToHex(ChinaRAS_EN(b),0) ; //--BlowFish算法 sTempStr:= EncryStr( S, SetDate(s_s01)); sTempStr:= RivestStr(sTempStr);// --MD5算法 sTempStr:= EncryStrHex(sTempStr,SetDate(s_s01)); if CompareText(sTempStr, sRegisterCode) = 0 then Result := True; {$I VMProtectEnd.inc} end; except end; end; function StartRegisterLicense(sRegisterCode: string): Boolean; {var Config: TInifile; sFileName: string; } const s_s01 = '.O,+*Q)%''&&&&&&&P$>=<;:9^XJKIHGEB'; begin Result := False; {$I VMProtectBegin.inc} Try if CheckLicense(sRegisterCode) then begin (*sFileName := ExtractFilePath(Paramstr(0)) + Trim(DecodeInfo('83k2WA1Ngh4B7tQuli10H8zmqZt0Wbg=')){!Setup.txt}; Config := TInifile.Create(sFileName); if Config <> nil then begin Config.WriteString(Trim(DecodeInfo('+0k6BCrV/VCNyfFnuvglmtaFxR/7W8Y=')){Reg}, Trim(DecodeInfo('6WiMJOkUHNE3FCQT4M9t65O/keCMQkI=')){RegisterCode}, String_ERR(SetDate(sRegisterCode), SetDate('.O,+*Q)%''&&&&&&&P$>=<;:9^XJKIHGEB'))); Config.Free; Result := True; end;*) WriteRegKey(1, MySubKey + m_sRegisterName + '\', Trim(DecodeInfo('yzbCkyLHOljn45P4u3UP54sW+Q==')){BasicInfo}, String_ERR(SetDate(sRegisterCode), SetDate(s_s01))); IniWriteString(Trim(DecodeInfo('yzbCkyLHOljn45P4u3UP54sW+Q==')){BasicInfo}, String_ERR(SetDate(sRegisterCode), SetDate(s_s01))); Result := True; end; except end; {$I VMProtectEnd.inc} end; //比较注册码是否正确 function GetLicense(sRegisterName: string): Integer; var //Config: TInifile; //sFileName: string; sRegisterCode, sCode: string; const s_s01 = '.O,+*Q)%''&&&&&&&P$>=<;:9^XJKIHGEB'; begin Result := 0; {$I VMProtectBegin.inc} Try (*sFileName := ExtractFilePath(Paramstr(0)) + Trim(DecodeInfo('83k2WA1Ngh4B7tQuli10H8zmqZt0Wbg=')){!Setup.txt}; if FileExists(sFileName) then begin Config := TInifile.Create(sFileName); if Config <> nil then begin sRegisterCode := Config.ReadString(Trim(DecodeInfo('+0k6BCrV/VCNyfFnuvglmtaFxR/7W8Y=')){Reg}, Trim(DecodeInfo('6WiMJOkUHNE3FCQT4M9t65O/keCMQkI=')){RegisterCode}, ''); if sRegisterCode <> '' then begin sRegisterCode:= SetDate(String_DRR(sRegisterCode, SetDate('.O,+*Q)%''&&&&&&&P$>=<;:9^XJKIHGEB'))); if CheckLicense(sRegisterCode) then Result := 1000; end; Config.Free; end; end; *) if IniReadString(Trim(DecodeInfo('yzbCkyLHOljn45P4u3UP54sW+Q==')){BasicInfo},sRegisterCode) then begin if ReadRegKey(1, MySubKey + m_sRegisterName + '\',Trim(DecodeInfo('yzbCkyLHOljn45P4u3UP54sW+Q==')){BasicInfo}, sCode) then begin if sCode = sRegisterCode then begin sRegisterCode:= SetDate(String_DRR(sRegisterCode, SetDate(s_s01))); if CheckLicense(sRegisterCode) then Result := 1000; end; end; end; except end; {$I VMProtectEnd.inc} end; procedure Open(); begin if nRegister <> 1000 then begin//注册过的,则不弹出注册窗口 FrmDiaLog := TFrmDiaLog.Create(nil); FrmDiaLog.Open; FrmDiaLog.Free; end; end; procedure InitPlug(AppHandle: THandle; boLoadSucced: Boolean); var s03: string; begin {$I VMProtectBegin.inc} {$IF HookSearchMode = 1} nRegister := 0; m_sRegisterName := GetRegisterName();//取机器码 if GetLicense(m_sRegisterName) = 1000 then begin nRegister := 1000; end else begin Open(); nRegister := GetLicense(m_sRegisterName); end; if boLoadSucced and (nRegister = 1000) then begin if nFileLoadSucced <> '' then begin s03:= SetDate(DecodeString(nFileLoadSucced)); end else begin s03:= Trim(DecodeInfo(sStartLoadPlugSucced)); end; MainOutMessasge(s03, 0) end else begin if nFileLoadFail <> '' then begin s03:= SetDate(DecodeString(nFileLoadFail)); end else begin s03:= Trim(DecodeInfo(sStartLoadPlugFail)); end; MainOutMessasge(s03, 0); end; {$ELSE} //20080717 免费插件 nRegister := 1000; if boLoadSucced and (nRegister = 1000) then begin s03:= Trim(DecodeInfo(sStartLoadPlugSucced)); MainOutMessasge(s03, 0); end; {$IFEND} {$I VMProtectEnd.inc} end; //============================================================================= //游戏文本配置信息解码函数(一般用于加解密脚本) //参数:sText 为要解码的字符串 //返回值:返回解码后的字符串(返回的字符串长度不能超过1024字节,超过将引起错误) //============================================================================= //解密函数 Function UncrypKey(Src:String; Key:String):string; var KeyLen :Integer; {$IF HookSearchMode = 1} KeyPos :Integer; offset :Integer; dest :string; SrcPos :Integer; SrcAsc :Integer; TmpSrcAsc :Integer; //Range :Integer; {$IFEND} begin {$I VMProtectBegin.inc} KeyLen:=Length(Key); if KeyLen = 0 then key:='www.IGEM2.com.cn'; {$IF HookSearchMode = 1} KeyPos:=0; SrcPos:=0; SrcAsc:=0; //Range:=256; offset:=StrToInt('$'+ copy(src,1,2)); SrcPos:=3; repeat SrcAsc:=StrToInt('$'+ copy(src,SrcPos,2)); if KeyPos < KeyLen Then KeyPos := KeyPos + 1 else KeyPos := 1; TmpSrcAsc := SrcAsc xor Ord(Key[KeyPos]); if TmpSrcAsc <= offset then TmpSrcAsc := 255 + TmpSrcAsc - offset else TmpSrcAsc := TmpSrcAsc - offset; dest := dest + chr(TmpSrcAsc); offset:=srcAsc; SrcPos:=SrcPos + 2; until SrcPos >= Length(Src); Result:=Dest; {$ELSE} Result:=Src;//20081016 免费版不使用此解密函数 {$IFEND} {$I VMProtectEnd.inc} end; function DeCodeScript(sText: string): string; begin {$I VMProtectBegin.inc} try sText:=UncrypKey(sText,sDecryKey); //20080213 Result := DecodeString_3des(DecryStrHex(sText, sDecryKey), sDecryKey); except Result := ''; end; {$I VMProtectEnd.inc} end; function DeCodeText(sText: string): string; begin Result := ''; if (sText <> '') and (sText[1] <> ';') and (nCheckCode = 4) and (nRegister = 1000) then begin Result := DeCodeScript(sText); end; //Result:='返回值:返回解码后的字符串'; end; //============================================================================= //IP所在地查询函数 //参数:sIPaddr 为要查询的IP地址 //返回值:返回IP所在地文本信息(返回的字符串长度不能超过255字节,超过会被截短) //============================================================================= function SearchIPLocal(sIPaddr: string): string; var QQWry: TQQWry; s02, s03: string; begin try QQWry := TQQWry.Create(sIPFileName); s02 := QQWry.GetIPMsg(QQWry.GetIPRecordID(sIPaddr))[2]; s03 := QQWry.GetIPMsg(QQWry.GetIPRecordID(sIPaddr))[3]; Result := Format('%s%s', [s02, s03]); QQWry.Free; except Result := ''; end; end; end.
unit Daw.Controller.New; interface uses Daw.Adb, DAW.Adb.Parser, DAW.Utils.DosCMD, DAW.Model.Device.New, DAW.Model.Devices; type TdawController = class private FLastDevices: TdawDevices; FAvaibleDevices: TdawDevices; FAdb: TdawAdb; FCmd: TDosCMD; FAdbParser: TdawAdbParser; public constructor Create; function GetDosCMD: TDosCMD; procedure Add(ADevice: TdawDevice); procedure Delete(ADevice: TdawDevice); procedure Connect(ADevice: TdawDevice); procedure Disconnect(ADevice: TdawDevice); procedure AddConnectedInAdb; destructor Destroy; override; property LastDevices: TdawDevices read FLastDevices write FLastDevices; property AvaibleDevices: TdawDevices read FAvaibleDevices write FAvaibleDevices; end; implementation uses Daw.Tools, System.SysUtils; { TdawController } procedure TdawController.Add(ADevice: TdawDevice); var x: Integer; begin x := FLastDevices.IsDuplicat(ADevice); if x > -1 then begin FAdb.Upgrade(ADevice); FLastDevices[x] := ADevice; end else begin FAdb.Upgrade(ADevice); FLastDevices.Add(ADevice); end; end; procedure TdawController.AddConnectedInAdb; var LFromAdb: TArray<TdawDevice>; begin FAvaibleDevices.Clear; LFromAdb := FAdb.getDevicesConnectedByUSB; FAvaibleDevices.AddRange(LFromAdb); end; procedure TdawController.Connect(ADevice: TdawDevice); begin FAdb.connectDevices([ADevice]); end; constructor TdawController.Create; var LDevices: string; begin FLastDevices := TdawDevices.Create(); FAvaibleDevices := TdawDevices.Create(); FAdbParser := TdawAdbParser.Create; FCmd := TDosCMD.Create('', TDawTools.AdbPath); FAdb := TdawAdb.Create(FCmd, FAdbParser); LDevices := TDawTools.LoadData('devices'); if not LDevices.IsEmpty then FLastDevices.FromJSON(LDevices); end; procedure TdawController.Delete(ADevice: TdawDevice); begin FLastDevices.Remove(ADevice); end; destructor TdawController.Destroy; begin TDawTools.SaveData('devices', FLastDevices.ToJSON); FAvaibleDevices.Free; FLastDevices.Free; inherited; end; procedure TdawController.Disconnect(ADevice: TdawDevice); begin FAdb.disconnectDevices([ADevice]); end; function TdawController.GetDosCMD: TDosCMD; begin Result := FCmd; end; end.
unit u_compiler; {$mode objfpc}{$H+} interface uses Classes, SysUtils, u_parser, u_ast_constructions, u_ast_blocks, u_tokens, u_ast_constructions_blocks, u_sem, u_gen; type TMashCompiler = class protected fp, destp: string; public constructor Create(_fp, _destp: string); procedure Compile; end; implementation constructor TMashCompiler.Create(_fp, _destp: string); begin self.fp := _fp; self.destp := _destp; end; procedure TMashCompiler.Compile; var mainpath, path: string; code, included: TStringList; parser: TMashParser; i, k: cardinal; imports_lst, regapi_lst, uses_lst, const_lst, ast_lst: TList; ast: TMashAST; parsers: TList; u: TMashASTB_Uses; t: TMashToken; sem: TMashSEM; outp: TStringList; begin writeln('Starting compilation, target: ', self.fp); mainpath := ExtractFilePath(self.fp); parsers := TList.Create; included := TStringList.Create; included.add(self.fp); code := TStringList.Create; try code.LoadFromFile(self.fp); except on E: Exception do raise Exception.Create('Can''t open file "' + self.fp + '".'); end; parser := TMashParser.Create(code, self.fp); parsers.add(parser); parser.Parse; imports_lst := TList.Create; regapi_lst := TList.Create; uses_lst := TList.Create; const_lst := TList.Create; ast_lst := TList.Create; ast := TMashAST.Create(parser.tokens, imports_lst, regapi_lst, uses_lst, const_lst); ast_lst.add(ast); ast.process; // Including inc\sys.mash path := 'inc\sys.mash'; try code.Clear; code.LoadFromFile(path); except raise Exception.Create('Can''t open file ''' + path + '''.'); end; parser := TMashParser.Create(code, path); parsers.add(parser); parser.Parse; ast := TMashAST.Create(parser.tokens, imports_lst, regapi_lst, uses_lst, const_lst); ast_lst.add(ast); ast.Process; included.add(path); // Checking another uses i := 0; while i < uses_lst.count do begin u := TMashASTB_Uses(uses_lst[i]); path := ''; t := TMashToken(u.Expr[0]); if (u.Expr.count = 1) and (t.info = ttString) then path := mainpath + t.value else begin path := 'inc\'; k := 0; while k < u.Expr.count do begin t := TMashToken(u.Expr[k]); if t.info = ttToken then begin if t.value = '.' then path := path + '\' else raise Exception.Create( 'Invalid uses at line ' + IntToStr(t.line + 1) + ' at file ''' + t.filep^ + '''.' ); end else path := path + t.value; Inc(k); end; path := path + '.mash'; end; if included.IndexOf(path) = -1 then begin try code.Clear; code.LoadFromFile(path); except raise Exception.Create('Can''t open file ''' + path + '''.'); end; //writeln('[uses]: ''' + path + '''...'); parser := TMashParser.Create(code, path); parsers.add(parser); parser.Parse; ast := TMashAST.Create(parser.tokens, imports_lst, regapi_lst, uses_lst, const_lst); ast_lst.add(ast); ast.Process; included.add(path); end; Inc(i); end; // Semantic analyse of code writeln('Semantic analyse...'); Sem := TMashSem.Create(imports_lst, regapi_lst, ast_lst, const_lst); Sem.Process; writeln('Generating output...'); Outp := TStringList.Create; GenerateCode(gaSVM, Sem, Outp); Outp.SaveToFile(self.destp); {CleanUpASTBlocks; FreeAndNil(code); while Parsers.Count > 0 do begin TMashParser(Parsers[0]).Free; Parsers.Delete(0); end; FreeAndNil(parsers); FreeAndNil(imports_lst); FreeAndNil(regapi_lst); FreeAndNil(uses_lst); FreeAndNil(const_lst); while ast_lst.Count > 0 do begin TMashAST(ast_lst[0]).Free; ast_lst.Delete(0); end; FreeAndNil(ast_lst);} end; end.
namespace Calculator.OSX; interface uses AppKit, Calculator.Engine; type [IBObject] MainWindowController = public class(NSWindowController) private var edValue: weak NSTextField; public method init: InstanceType; override; method windowDidLoad; override; [IBAction] method pressBackButton(sender: id); [IBAction] method pressExitButton(sender: id); [IBAction] method pressEvaluateButton(sender: id); [IBAction] method pressCharButton(sender: id); end; implementation method MainWindowController.init: instancetype; begin inherited initWithWindowNibName('MainWindowController') ; end; method MainWindowController.windowDidLoad; begin inherited windowDidLoad(); // Implement this method to handle any initialization after your window controller's // window has been loaded from its nib file. end; method MainWindowController.pressBackButton(sender: id); begin var s := edValue.stringValue; if s.length > 0 then begin s := s.substringToIndex(s.length - 1); edValue.stringValue := s; end; end; method MainWindowController.pressExitButton(sender: id); begin close(); end; method MainWindowController.pressEvaluateButton(sender: id); begin try var eval := new Evaluator(); edValue.stringValue := '' + eval.Evaluate(edValue.stringValue); except on e: EvaluatorError do begin var alert := new NSAlert(); alert.messageText := 'Error evaluating: ' + e.reason; alert.runModal(); end; end; end; method MainWindowController.pressCharButton(sender: id); begin edValue.stringValue := (NSButton(sender)).title; end; end.
unit dxDBDateEdit; interface uses Messages, Classes, Controls, dxDateEdit, DB, DBCtrls; type TdxDBDateEdit = class(TCustomdxDateEdit) private FDataLink: TFieldDataLink; function GetDataField: string; function GetDataSource: TDataSource; function GetField: TField; procedure SetDataField(const Value: string); procedure SetDataSource(Value: TDataSource); procedure DataChange(Sender: TObject); procedure UpdateData(Sender: TObject); procedure WMClear(var Message: TMessage); message WM_CLEAR; procedure WMCut(var Message: TMessage); message WM_CUT; procedure WMPaste(var Message: TMessage); message WM_PASTE; procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK; protected procedure DoDateChanged; override; function DoEditCanModify: Boolean; virtual; function GetShowClearButton: Boolean; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Field: TField read GetField; published property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property AutoSelect; property AutoSize; property BorderStyle; property Color; property Ctl3D; property DragCursor; property DragMode; property Enabled; property Font; property ImeMode; property ImeName; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property ShowTodayButton; property ShowClearButton; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnDateChanged; end; implementation uses Windows; { TdxDBDateEdit } constructor TdxDBDateEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable]; FDataLink := TFieldDataLink.Create; FDataLink.Control := Self; FDataLink.OnDataChange := DataChange; FDataLink.OnUpdateData := UpdateData; end; destructor TdxDBDateEdit.Destroy; begin FDataLink.Free; inherited Destroy; end; function TdxDBDateEdit.GetDataField: string; begin Result := FDataLink.FieldName; end; function TdxDBDateEdit.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; function TdxDBDateEdit.GetField: TField; begin Result := FDataLink.Field; end; procedure TdxDBDateEdit.SetDataField(const Value: string); begin FDataLink.FieldName := Value; end; procedure TdxDBDateEdit.SetDataSource(Value: TDataSource); begin FDataLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); end; procedure TdxDBDateEdit.DataChange(Sender: TObject); begin if FDataLink.Field <> nil then if FDataLink.Field.IsNull then Text := '' else Text := GetDateText(DateOf(FDataLink.Field.AsDateTime)) else if csDesigning in ComponentState then Text := Name else Text := ''; end; procedure TdxDBDateEdit.UpdateData(Sender: TObject); begin if Date = NullDate then FDataLink.Field.Clear else with FDataLink.Field do AsDateTime := Date + TimeOf(AsDateTime); end; procedure TdxDBDateEdit.WMClear(var Message: TMessage); begin DoEditCanModify; inherited; end; procedure TdxDBDateEdit.WMCut(var Message: TMessage); begin DoEditCanModify; inherited; end; procedure TdxDBDateEdit.WMPaste(var Message: TMessage); begin DoEditCanModify; inherited; end; procedure TdxDBDateEdit.CMExit(var Message: TCMExit); begin try FDataLink.UpdateRecord; except SelectAll; SetFocus; raise; end; inherited; end; procedure TdxDBDateEdit.CMGetDatalink(var Message: TMessage); begin Message.Result := Integer(FDataLink); end; procedure TdxDBDateEdit.DoDateChanged; var PrevText: string; begin if FDataLink.Field <> nil then begin PrevText := Text; if FDataLink.CanModify then begin try FDataLink.Edit; except DataChange(nil); raise; end; if not FDataLink.Editing then DataChange(nil) else begin Text := PrevText; FDataLink.Modified; end; end else DataChange(nil); end; inherited DoDateChanged; end; function TdxDBDateEdit.DoEditCanModify: Boolean; begin Result := FDataLink.Edit; if Result then FDataLink.Modified; end; function TdxDBDateEdit.GetShowClearButton: Boolean; begin Result := inherited GetShowClearButton and ((FDataLink.Field = nil) or not FDataLink.Field.Required); end; procedure TdxDBDateEdit.KeyDown(var Key: Word; Shift: TShiftState); begin if Key = VK_DELETE then DoEditCanModify; inherited KeyDown(Key, Shift); end; procedure TdxDBDateEdit.KeyPress(var Key: Char); begin if (Key in [#32..#255]) and (FDataLink.Field <> nil) and not FDataLink.Field.IsValidChar(Key) then begin MessageBeep(0); Key := #0; end; case Key of #8, #32..#255: DoEditCanModify; #27: begin FDataLink.Reset; SelectAll; Key := #0; end; end; inherited KeyPress(Key); end; procedure TdxDBDateEdit.Loaded; begin inherited Loaded; if csDesigning in ComponentState then DataChange(Self); end; procedure TdxDBDateEdit.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FDataLink <> nil) and (AComponent = DataSource) then DataSource := nil; end; end.
unit uConsultaCEP; interface uses System.SysUtils, System.JSON, REST.Client, System.Generics.Collections, IPPeerClient; const URL_PREFIXO = 'http://viacep.com.br/ws/'; URL_SUFIXO = '/json/'; JSON_ERRO = 'erro'; JSON_CEP = 'cep'; JSON_LOGRADOURO = 'logradouro'; JSON_COMPLEMENTO = 'complemento'; JSON_BAIRRO = 'bairro'; JSON_LOCALIDADE = 'localidade'; JSON_UF = 'uf'; JSON_UNIDADE = 'unidade'; JSON_IBGE = 'ibge'; JSON_GIA = 'gia'; type ECEPInvalidoException = class(Exception); EFalhaComunicacaoException = class(Exception); EUFInvalidaException = class(Exception); ECidadeInvalidaException = class(Exception); ELogradouroInvalidoException = class(Exception); ECEPNaoLocalizadoException = class(Exception); EEnderecoNaoLocalizadoException = class(Exception); TConsultaCEPEndereco = class strict private FLogradouro: String; FIBGE: String; FBairro: String; FUF: String; FCEP: String; FUnidade: String; FComplemento: String; FGIA: String; FCidade: String; public function ToString: string; property CEP: String read FCEP write FCEP; property Logradouro: String read FLogradouro write FLogradouro; property Cidade: String read FCidade write FCidade; property UF: String read FUF write FUF; property Complemento: String read FComplemento write FComplemento; property Bairro: String read FBairro write FBairro; property Unidade: String read FUnidade write FUnidade; property IBGE: String read FIBGE write FIBGE; property GIA: String read FGIA write FGIA; end; TConsultaCEPEnderecoList = class(TObjectList<TConsultaCEPEndereco>) public function ToString: string; end; TConsultaCEP = class strict private FRetornoJSONExecute: string; procedure DoRESTRequestAfterExecute(Sender: TCustomRESTRequest); procedure Consultar(_AURL: String); procedure ValidarCEP(_ACEP: String); procedure ValidarEndereco(_AUF, _ACidade, _ALogradouro: String); function GetURL(_ACEP: string): string; overload; function GetURL(_AUF, _ACidade, _ALogradouro: String): string; overload; function ProcessarRetorno: TConsultaCEPEnderecoList; public constructor Create; function ConsultarEnderecoPeloCEP(_ACEP: String): TConsultaCEPEnderecoList; function ConsultarCEPPeloEndereco(_AUF, _ACidade, _ALogradouro: String): TConsultaCEPEnderecoList; end; implementation uses REST.Json, System.StrUtils; function CharInSet(C: AnsiChar; const CharSet: TSysCharSet): Boolean; begin Result := C in CharSet; end; function CharIsNum(const C: AnsiChar): Boolean; begin Result := CharInSet(C, ['0'..'9']) ; end ; function OnlyNumber(_AValue: String): String; var x : integer ; ALenValue : integer; begin Result := ''; ALenValue := Length( _AValue ) ; for x := 1 to ALenValue do begin if CharIsNum(AnsiChar(_AValue[x])) then Result := Result + _AValue[x]; end; end; function IsJSONArray(_AJSONStr: String): Boolean; begin Result := Pos('[{', _AJSONStr) > 0; end; { TConsultaCEP } procedure TConsultaCEP.Consultar(_AURL: String); var ARESTClient: TRESTClient; ARESTRequest: TRESTRequest; ARESTResponse: TRESTResponse; begin ARESTClient := TRESTClient.Create(_AURL); try ARESTClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,'; ARESTClient.AcceptCharset := 'UTF-8, *;q=0.8'; ARESTClient.AcceptEncoding := 'identity'; ARESTClient.ContentType := 'application/json'; ARESTClient.BaseURL := _AURL; ARESTClient.RaiseExceptionOn500 := False; ARESTClient.HandleRedirects := True; ARESTResponse := TRESTResponse.Create(nil); try ARESTResponse.ContentType := 'application/json'; ARESTRequest := TRESTRequest.Create(nil); try ARESTRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,'; ARESTRequest.AcceptCharset := 'UTF-8, *;q=0.8'; ARESTRequest.Client := ARESTClient; ARESTRequest.Response := ARESTResponse; ARESTRequest.SynchronizedEvents := False; ARESTRequest.OnAfterExecute := DoRESTRequestAfterExecute; try ARESTRequest.Execute; except raise EFalhaComunicacaoException.Create('Falha de comunicação com o servidor.'); end; finally ARESTRequest.Free end; finally ARESTResponse.Free; end; finally ARESTClient.Free; end; end; function TConsultaCEP.ConsultarCEPPeloEndereco(_AUF, _ACidade, _ALogradouro: String): TConsultaCEPEnderecoList; begin Result := nil; ValidarEndereco(_AUF, _ACidade, _ALogradouro); Consultar(GetURL(_AUF, _ACidade, _ALogradouro)); Result := ProcessarRetorno; end; function TConsultaCEP.ConsultarEnderecoPeloCEP(_ACEP: String): TConsultaCEPEnderecoList; begin Result := nil; ValidarCEP(_ACEP); Consultar(GetURL(OnlyNumber(_ACEP))); Result := ProcessarRetorno; end; constructor TConsultaCEP.Create; begin FRetornoJSONExecute := EmptyStr; end; procedure TConsultaCEP.DoRESTRequestAfterExecute(Sender: TCustomRESTRequest); begin FRetornoJSONExecute := EmptyStr; if Assigned(Sender.Response.JSONValue) then FRetornoJSONExecute := TJson.Format(Sender.Response.JSONValue); end; function TConsultaCEP.GetURL(_AUF, _ACidade, _ALogradouro: String): string; var ALocalizador: string; begin ALocalizador := Format('%s/%s/%s', [_AUF.Trim, _ACidade.Trim, _ALogradouro.Trim]); Result := Concat(URL_PREFIXO, ALocalizador, URL_SUFIXO); end; function TConsultaCEP.ProcessarRetorno: TConsultaCEPEnderecoList; procedure SetDadosEndereco(_AJsonEndereco: TJSONObject); var AConsultaCEPEndereco: TConsultaCEPEndereco; AJsonPairEndereco: TJSONPair; begin for AJsonPairEndereco in _AJsonEndereco do if SameStr(AJsonPairEndereco.JsonString.Value, JSON_ERRO) then raise ECEPNaoLocalizadoException.Create('CEP não localizado.') else Break; AConsultaCEPEndereco := TConsultaCEPEndereco.Create; try for AJsonPairEndereco in _AJsonEndereco do begin if SameStr(AJsonPairEndereco.JsonString.Value, JSON_LOGRADOURO) then AConsultaCEPEndereco.Logradouro := AJsonPairEndereco.JsonValue.Value else if SameStr(AJsonPairEndereco.JsonString.Value, JSON_COMPLEMENTO) then AConsultaCEPEndereco.Complemento := AJsonPairEndereco.JsonValue.Value else if SameStr(AJsonPairEndereco.JsonString.Value, JSON_BAIRRO) then AConsultaCEPEndereco.Bairro := AJsonPairEndereco.JsonValue.Value else if SameStr(AJsonPairEndereco.JsonString.Value, JSON_LOCALIDADE) then AConsultaCEPEndereco.Cidade := AJsonPairEndereco.JsonValue.Value else if SameStr(AJsonPairEndereco.JsonString.Value, JSON_UF) then AConsultaCEPEndereco.UF := AJsonPairEndereco.JsonValue.Value else if SameStr(AJsonPairEndereco.JsonString.Value, JSON_CEP) then AConsultaCEPEndereco.CEP := AnsiReplaceStr(AJsonPairEndereco.JsonValue.Value, '-', EmptyStr) else if SameStr(AJsonPairEndereco.JsonString.Value, JSON_UNIDADE) then AConsultaCEPEndereco.Unidade := AJsonPairEndereco.JsonValue.Value else if SameStr(AJsonPairEndereco.JsonString.Value, JSON_IBGE) then AConsultaCEPEndereco.IBGE := AJsonPairEndereco.JsonValue.Value else if SameStr(AJsonPairEndereco.JsonString.Value, JSON_GIA) then AConsultaCEPEndereco.GIA := AJsonPairEndereco.JsonValue.Value; end; Result.Add(AConsultaCEPEndereco); except AConsultaCEPEndereco.Free; end; end; procedure SetDadosRetorno; var AJsonObj: TJSONObject; AJsonArray: TJSONArray; AJsonValue, AJsonValueItem: TJSONValue; x: Integer; begin AJsonValue := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(FRetornoJSONExecute), 0) as TJSONValue; try if AJsonValue is TJSONArray then begin AJsonArray := TJSONArray(AJsonValue); if AJsonArray.Count = 0 then raise ECEPNaoLocalizadoException.Create('Endereço não localizado.') else for AJsonValueItem in AJsonArray do SetDadosEndereco(TJSONObject(AJsonValueItem)); end else begin AJsonObj := TJSONObject(AJsonValue); SetDadosEndereco(AJsonObj); end; finally AJsonValue.Free; end; end; begin Result := nil; if FRetornoJSONExecute = EmptyStr then raise EFalhaComunicacaoException.Create('Falha de comunicação com o servidor ou dados inválidos.'); Result := TConsultaCEPEnderecoList.Create(True); SetDadosRetorno; end; function TConsultaCEP.GetURL(_ACEP: string): string; begin Result := Concat(URL_PREFIXO, _ACEP.Trim, URL_SUFIXO); end; procedure TConsultaCEP.ValidarCEP(_ACEP: String); begin _ACEP := OnlyNumber(_ACEP) ; if (_ACEP.Trim = EmptyStr) or (Length(_ACEP.Trim) <> 8) then raise ECEPInvalidoException.Create('CEP inválido.'); end; procedure TConsultaCEP.ValidarEndereco(_AUF, _ACidade, _ALogradouro: String); begin if _AUF.Trim = EmptyStr then raise EUFInvalidaException.Create('UF inválida.'); if (_ACidade.Trim = EmptyStr) or (Length(_ACidade.Trim) < 2) then raise ECidadeInvalidaException.Create('Cidade inválida.'); if (_ALogradouro.Trim = EmptyStr) or (Length(_ALogradouro.Trim) < 2) then raise ELogradouroInvalidoException.Create('Logradouro inválido.'); end; { TConsultaCEPEndereco } function TConsultaCEPEndereco.ToString: string; function GetText(_ALabel, _AValue: String): string; begin Result := Format('%s = %s', [_ALabel, _AValue]) + #13+#10; end; begin Result := Concat( GetText(JSON_CEP, FCEP), GetText(JSON_LOGRADOURO, FLogradouro), GetText(JSON_LOCALIDADE, FCidade), GetText(JSON_UF, FUF), GetText(JSON_COMPLEMENTO, FComplemento), GetText(JSON_BAIRRO, FBairro), GetText(JSON_UNIDADE, FUnidade), GetText(JSON_IBGE, FIBGE), GetText(JSON_GIA, FGIA) ); end; { TConsultaCEPEnderecoList } function TConsultaCEPEnderecoList.ToString: string; var AConsultaCEPEndereco: TConsultaCEPEndereco; ACount: Integer; function GetTitleRegistro(_ANroReg: Integer): string; begin Result := Format('============ REGISTRO %d ============ ', [_ANroReg]); end; begin Result := EmptyStr; ACount := 1; for AConsultaCEPEndereco in Self do begin if Count > 0 then Result := Concat(Result, #13, #10, GetTitleRegistro(ACount), #13, #10); Result := Result + AConsultaCEPEndereco.ToString; Inc(ACount); end; Result := Trim(Result); end; end.
unit uUninstallActions; interface {$WARN SYMBOL_PLATFORM OFF} uses System.Classes, System.SysUtils, System.StrUtils, System.Win.Registry, Winapi.Windows, Winapi.Messages, Winapi.ShellAPI, Dmitry.Utils.System, Dmitry.Utils.Files, uMemory, uActions, uInstallScope, uInstallUtils, uRuntime, uConstants, uTranslate, uActivationUtils, uUserUtils, uStillImage, uSettings, uUpTime, uShellUtils, uProgramStatInfo, uConfiguration; const InstallPoints_Close_PhotoDB = 1024 * 1024; DeleteFilePoints = 128 * 1024; UnInstallPoints_ShortCut = 128 * 1024; UnInstallPoints_FileAcctions = 512 * 1024; UninstallNotifyPoints_ShortCut = 1024 * 1024; DeleteRegistryPoints = 128 * 1024; UnInstallPoints_StillImage = 512 * 1024; UnInstallPoints_AppData = 1024 * 1024; type TInstallCloseApplication = class(TInstallAction) public function CalculateTotalPoints: Int64; override; procedure Execute(Callback: TActionCallback); override; end; TUninstallFiles = class(TInstallAction) public function CalculateTotalPoints: Int64; override; procedure Execute(Callback: TActionCallback); override; end; TInstallFileActions = class(TInstallAction) public function CalculateTotalPoints: Int64; override; procedure Execute(Callback: TActionCallback); override; end; TUninstallShortCuts = class(TInstallAction) public function CalculateTotalPoints: Int64; override; procedure Execute(Callback: TActionCallback); override; end; TUninstallNotify = class(TInstallAction) public function CalculateTotalPoints: Int64; override; procedure Execute(Callback: TActionCallback); override; end; TUninstallRegistry = class(TInstallAction) public function CalculateTotalPoints: Int64; override; procedure Execute(Callback: TActionCallback); override; end; TUnInstallStillImageHandler = class(TInstallAction) function CalculateTotalPoints: Int64; override; procedure Execute(Callback: TActionCallback); override; end; TUnInstallCacheHandler = class(TInstallAction) function CalculateTotalPoints: Int64; override; procedure Execute(Callback: TActionCallback); override; end; implementation { TUninstallFiles } function TUninstallFiles.CalculateTotalPoints: Int64; begin Result := CurrentInstall.Files.Count * DeleteFilePoints; end; procedure TUninstallFiles.Execute(Callback: TActionCallback); var I: Integer; DiskObject: TDiskObject; Destination: string; Terminate: Boolean; begin Terminate := False; for I := 0 to CurrentInstall.Files.Count - 1 do begin DiskObject := CurrentInstall.Files[I]; Destination := IncludeTrailingBackslash(ResolveInstallPath(DiskObject.FinalDestination)) + DiskObject.Name; if DiskObject is TFileObject then System.SysUtils.DeleteFile(Destination); if DiskObject is TDirectoryObject then DeleteDirectoryWithFiles(Destination); Callback(Self, I * DeleteFilePoints, CurrentInstall.Files.Count, Terminate); if Terminate then Break; end; end; { TUninstallShortCuts } function TUninstallShortCuts.CalculateTotalPoints: Int64; var I: Integer; DiskObject: TDiskObject; begin Result := 0; for I := 0 to CurrentInstall.Files.Count - 1 do begin DiskObject := CurrentInstall.Files[I]; Inc(Result, DiskObject.ShortCuts.Count * UnInstallPoints_ShortCut); end; end; procedure TUninstallShortCuts.Execute(Callback: TActionCallback); var I, J: Integer; DiskObject: TDiskObject; CurentPosition: Int64; ShortcutPath, ObjectPath: string; procedure DeleteShortCut(FileName: string); begin System.SysUtils.DeleteFile(FileName); FileName := ExtractFileDir(FileName); RemoveDir(FileName); end; begin CurentPosition := 0; for I := 0 to CurrentInstall.Files.Count - 1 do begin DiskObject := CurrentInstall.Files[I]; for J := 0 to DiskObject.ShortCuts.Count - 1 do begin Inc(CurentPosition, UnInstallPoints_ShortCut); ObjectPath := ResolveInstallPath(IncludeTrailingBackslash(DiskObject.FinalDestination) + DiskObject.Name); ShortcutPath := ResolveInstallPath(DiskObject.ShortCuts[J].Location); if StartsText('http', ShortcutPath) then begin ObjectPath := ChangeFileExt(ObjectPath, '.url'); DeleteShortCut(ObjectPath); ShortcutPath := ResolveInstallPath(DiskObject.ShortCuts[J].Name); DeleteShortCut(ShortcutPath); Continue; end; DeleteShortCut(ShortcutPath); end; end; end; { TUninstallNotify } function TUninstallNotify.CalculateTotalPoints: Int64; begin Result := UninstallNotifyPoints_ShortCut; end; procedure TUninstallNotify.Execute(Callback: TActionCallback); var ExeFileName, NotifyUrl, Version: string; CurrentVersion: TRelease; begin Version := ProductMajorVersionVersion; ExeFileName := ExtractFilePath(ParamStr(0)) + 'PhotoDB.exe'; CurrentVersion := GetExeVersion(ExeFileName); if CurrentVersion.Build > 0 then Version := ReleaseToString(CurrentVersion); NotifyUrl := ResolveLanguageString(UnInstallNotifyURL) + '?v=' + Version + '&ac=' + TActivationManager.Instance.ApplicationCode + '&ut=' + IntToStr(GetCurrentUpTime) + '&f=' + ProgramStatistics.ToString; RunAsUser(NotifyUrl, NotifyUrl, NotifyUrl, False); end; { TUninstallRegistry } function TUninstallRegistry.CalculateTotalPoints: Int64; begin Result := 5 * DeleteRegistryPoints; end; procedure TUninstallRegistry.Execute(Callback: TActionCallback); var FReg: TRegistry; Terminated: Boolean; begin Terminated := False; FReg := TRegistry.Create; try FReg.RootKey := HKEY_CLASSES_ROOT; FReg.DeleteKey('\.photodb'); FReg.DeleteKey('\PhotoDB.PhotodbFile\'); FReg.DeleteKey('\.ids'); FReg.DeleteKey('\PhotoDB.IdsFile\'); FReg.DeleteKey('\.dbl'); FReg.DeleteKey('\PhotoDB.DblFile\'); FReg.DeleteKey('\.ith'); FReg.DeleteKey('\PhotoDB.IthFile\'); FReg.DeleteKey('\Directory\Shell\PhDBBrowse\'); FReg.DeleteKey('\Drive\Shell\PhDBBrowse\'); FReg.DeleteKey('\Drive\Shell\PhDBGetPhotos\'); except end; FReg.Free; Callback(Self, 1 * DeleteRegistryPoints, CalculateTotalPoints, Terminated); FReg := TRegistry.Create; try FReg.RootKey := HKEY_INSTALL; FReg.DeleteKey(RegRoot); except end; FReg.Free; Callback(Self, 2 * DeleteRegistryPoints, CalculateTotalPoints, Terminated); FReg := TRegistry.Create; try FReg.RootKey := HKEY_USER_WORK; FReg.DeleteKey(RegRoot); except end; FReg.Free; Callback(Self, 3 * DeleteRegistryPoints, CalculateTotalPoints, Terminated); FReg := TRegistry.Create; try FReg.RootKey := HKEY_LOCAL_MACHINE; FReg.DeleteKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Photo DataBase'); except end; FReg.Free; Callback(Self, 4 * DeleteRegistryPoints, CalculateTotalPoints, Terminated); FReg := TRegistry.Create; try FReg.RootKey := HKEY_LOCAL_MACHINE; FReg.DeleteKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers\Handlers\PhotoDBGetPhotosHandler'); FReg.DeleteKey('\SOFTWARE\Classes\PhotoDB.AutoPlayHandler'); FReg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers\EventHandlers\ShowPicturesOnArrival', True); FReg.DeleteValue('PhotoDBgetPhotosHandler'); except end; FReg.Free; Callback(Self, 5 * DeleteRegistryPoints, CalculateTotalPoints, Terminated); end; { TInstallCloseApplication } function TInstallCloseApplication.CalculateTotalPoints: Int64; begin Result := InstallPoints_Close_PhotoDB; end; procedure TInstallCloseApplication.Execute(Callback: TActionCallback); const Timeout = 10000; var WinHandle: HWND; StartTime: Cardinal; begin inherited; WinHandle := FindWindow(nil, PChar(DBID)); if WinHandle <> 0 then begin SendMessage(WinHandle, WM_CLOSE, 0, 0); StartTime := GetTickCount; while(true) do begin if (FindWindow(nil, PChar(DB_ID)) = 0) and (FindWindow(nil, PChar(DB_ID_CLOSING)) = 0) then Break; if (GetTickCount - StartTime) > Timeout then Break; Sleep(100); end; end; end; { TInstallFileActions } function TInstallFileActions.CalculateTotalPoints: Int64; var I, J: Integer; DiskObject: TDiskObject; begin Result := 0; for I := 0 to CurrentInstall.Files.Count - 1 do begin DiskObject := CurrentInstall.Files[I]; for J := 0 to DiskObject.Actions.Count - 1 do if DiskObject.Actions[J].Scope = asUninstall then Inc(Result, DiskObject.Actions.Count * UnInstallPoints_FileAcctions); end; end; procedure TInstallFileActions.Execute(Callback: TActionCallback); var I, J: Integer; DiskObject: TDiskObject; CurentPosition: Int64; ObjectPath, FontsDirectory, FontName: string; StartInfo: TStartupInfo; ProcInfo: TProcessInformation; hReg: TRegistry; begin CurentPosition := 0; for I := 0 to CurrentInstall.Files.Count - 1 do begin DiskObject := CurrentInstall.Files[I]; for J := 0 to DiskObject.Actions.Count - 1 do begin if DiskObject.Actions[J].Scope = asUninstall then begin Inc(CurentPosition, UnInstallPoints_FileAcctions); ObjectPath := ResolveInstallPath(IncludeTrailingBackslash(DiskObject.FinalDestination) + DiskObject.Name); { fill with known state } FillChar(StartInfo, SizeOf(TStartupInfo), #0); FillChar(ProcInfo, SizeOf(TProcessInformation), #0); try with StartInfo do begin cb := SizeOf(StartInfo); dwFlags := STARTF_USESHOWWINDOW; wShowWindow := SW_NORMAL; end; CreateProcess(nil, PChar('"' + ObjectPath + '"' + ' ' + DiskObject.Actions[J].CommandLine), nil, nil, False, CREATE_DEFAULT_ERROR_MODE or NORMAL_PRIORITY_CLASS, nil, PChar(ExcludeTrailingPathDelimiter(ExtractFileDir(ObjectPath))), StartInfo, ProcInfo); WaitForSingleObject(ProcInfo.hProcess, 30000); finally CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); end; end; if DiskObject.Actions[J].Scope = asUninstallFont then begin FontsDirectory := GetFontsDirectory; ObjectPath := ResolveInstallPath(IncludeTrailingBackslash(DiskObject.FinalDestination) + DiskObject.Name); FontName := DiskObject.Name; RemoveFontResource(PChar(FontsDirectory + FontName)); hReg := TRegistry.Create; try hReg.RootKey := HKEY_LOCAL_MACHINE; hReg.LazyWrite := False; if hReg.OpenKey('Software\Microsoft\Windows NT\CurrentVersion\Fonts', False) then hReg.DeleteValue(DiskObject.Actions[J].CommandLine); hReg.CloseKey; finally F(hReg); end; DeleteFile(PChar(FontsDirectory + FontName)); SendNotifyMessage(HWND_BROADCAST, WM_FONTCHANGE, SPI_SETDOUBLECLICKTIME, 0); end; end; end; end; { TUnInstallStillImageHandler } function TUnInstallStillImageHandler.CalculateTotalPoints: Int64; begin if IsWindowsXPOnly then Result := UnInstallPoints_StillImage else Result := 0; end; procedure TUnInstallStillImageHandler.Execute(Callback: TActionCallback); begin if IsWindowsXPOnly then UnRegisterStillHandler('Photo Database'); end; { TUnInstallCacheHandler } function TUnInstallCacheHandler.CalculateTotalPoints: Int64; begin Result := UnInstallPoints_AppData; end; procedure TUnInstallCacheHandler.Execute(Callback: TActionCallback); begin DeleteDirectoryWithFiles(GetAppDataDirectory); end; end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.Logger.Provider.Rest Description : Log Api SolR Provider Author : Kike Pérez Version : 1.22 Created : 15/10/2017 Modified : 23/02/2019 This file is part of QuickLogger: https://github.com/exilon/QuickLogger *************************************************************************** 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.Logger.Provider.SolR; {$i QuickLib.inc} interface uses Classes, SysUtils, Quick.HttpClient, Quick.Commons, System.Json, Quick.Logger; type TLogSolrProvider = class (TLogProviderBase) private fHTTPClient : TJsonHTTPClient; fURL : string; fFullURL : string; fCollection : string; fUserAgent : string; procedure CreateCollection(const aName : string); function ExistsCollection(const aName : string) : Boolean; public constructor Create; override; destructor Destroy; override; property URL : string read fURL write fURL; property Collection : string read fCollection write fCollection; property UserAgent : string read fUserAgent write fUserAgent; property JsonOutputOptions : TJsonOutputOptions read fJsonOutputOptions write fJsonOutputOptions; procedure Init; override; procedure Restart; override; procedure WriteLog(cLogItem : TLogItem); override; end; var GlobalLogSolrProvider : TLogSolrProvider; implementation constructor TLogSolrProvider.Create; begin inherited; LogLevel := LOG_ALL; fURL := 'http://localhost:8983/solr'; fCollection := 'logger'; fUserAgent := DEF_USER_AGENT; IncludedInfo := [iiAppName,iiHost,iiEnvironment]; end; destructor TLogSolrProvider.Destroy; begin if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); inherited; end; procedure TLogSolrProvider.Init; begin fFullURL := Format('%s/solr',[fURL]); fHTTPClient := TJsonHTTPClient.Create; fHTTPClient.ContentType := 'application/json'; fHTTPClient.UserAgent := fUserAgent; fHTTPClient.HandleRedirects := True; if not ExistsCollection(fCollection) then CreateCollection(fCollection); inherited; end; procedure TLogSolrProvider.Restart; begin Stop; if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); Init; end; procedure TLogSolrProvider.CreateCollection(const aName : string); var resp : IHttpRequestResponse; begin exit; resp := fHTTPClient.Get(Format('%s/admin/collections?action=CREATE&name=%s',[fFullURL,aName])); if not (resp.StatusCode in [200,201]) then raise ELogger.Create(Format('[TLogSolRProvider] : Can''t create Collection (Error %d : %s)',[resp.StatusCode,resp.StatusText])); end; function TLogSolrProvider.ExistsCollection(const aName : string) : Boolean; var resp : IHttpRequestResponse; json : TJSONValue; a : string; begin Result := False; resp := fHTTPClient.Get(Format('%s/admin/cores?action=STATUS&core=%s',[fFullURL,aName])); if resp.StatusCode in [200,201] then begin json := resp.Response.FindValue(Format('status.%s.name',[aName])); if json <> nil then begin Result := json.Value = aName; //json.Free; end; end else raise ELogger.Create(Format('[TLogSolRProvider] : Can''t check Collection (Error %d : %s)',[resp.StatusCode,resp.StatusText])); end; procedure TLogSolrProvider.WriteLog(cLogItem : TLogItem); var resp : IHttpRequestResponse; begin if CustomMsgOutput then resp := fHTTPClient.Post(Format('%s/%s/update/json/docs',[fFullURL,fCollection]),cLogItem.Msg) else resp := fHTTPClient.Post(Format('%s/%s/update/json/docs',[fFullURL,fCollection]),LogItemToJson(cLogItem)); if not (resp.StatusCode in [200,201]) then raise ELogger.Create(Format('[TLogSolRProvider] : Response %d : %s trying to post event',[resp.StatusCode,resp.StatusText])); end; initialization GlobalLogSolrProvider := TLogSolrProvider.Create; finalization if Assigned(GlobalLogSolrProvider) and (GlobalLogSolrProvider.RefCount = 0) then GlobalLogSolrProvider.Free; end.
unit Client; interface uses SysUtils, DateUtils, SyncObjs, System.Classes, System.Generics.Collections, Simplex.Client, Simplex.Types; type TNodeParams = record NodeId: SpxNodeId; AccessLevel: SpxByte; Excecutable: SpxBoolean; DisplayName: SpxString; Value: SpxVariant; ParentNodeId: SpxNodeId; end; TNodeParamsArray = array of TNodeParams; TSubscribeParams = class NodeParams: TNodeParams; ClientHandle: SpxUInt32; MonitoredItemId: SpxUInt32; Value: SpxDataValue; end; TReadResult = record AttributeName: SpxString; AttributeValue: SpxDataValue; end; TReadResultArray = array of TReadResult; TEvents = class; TClient = class(SpxClientCallback) private FClient: TOpcUaClient; FClientConfig: SpxClientConfig; FEvents: TEvents; FCurrentNode: TNodeParams; FSubscriptionId: SpxUInt32; FSubscribeItems: TList<TSubscribeParams>; function GetNodeId(ANamespaceIndex: Word; AIdent: Cardinal): SpxNodeId; function GetAttributeParams(AIndex: Integer; out AAttributeName: String; out AAttributeId: SpxUInt32): Boolean; procedure ClearSubscribe(); function SaveToFile(const AData: SpxByteArray; const AFileName: string): Boolean; procedure AddValueAttribute(ANodeId: SpxNodeId; AAttributeId: SpxUInt32; var AReadValues: SpxReadValueIdArray); function GetMonitoredItem(ANodeId: SpxNodeId; AClientHandle: Cardinal; ASamplingInterval: double): SpxMonitoredItem; function ReadValue(ANodeId: SpxNodeId; out AValue: SpxDataValue): Boolean; function ReadArguments(AArgumentNodeId: SpxNodeId; out AArguments: SpxArgumentArray): SpxBoolean; public procedure OnChannelEvent(AEvent: SpxChannelEvent; AStatus: SpxStatusCode); override; procedure OnMonitoredItemChange(ASubscriptionId: SpxUInt32; AValues : SpxMonitoredItemNotifyArray); override; procedure OnLog(AMessage: string); override; procedure OnLogWarning(AMessage: string); override; procedure OnLogError(AMessage: string); override; procedure OnLogException(AMessage: string; AException: Exception); override; public constructor Create(AClientConfig: SpxClientConfig; AEvents: TEvents); destructor Destroy; override; procedure Disconnect(); function GetEndpoints(out AEndpoints: SpxEndpointDescriptionArray): Boolean; function ReadServerCertificate(ASecurityPolicyUri: SpxString): Boolean; function Connect(): Boolean; overload; function Connect(ASecurityMode: SpxMessageSecurityMode; ASecurityPolicyUri: SpxString): Boolean; overload; function InitSession(): Boolean; function Browse(AParentNodeId: SpxNodeId; out ABrowseResult: SpxBrowseResultArray): Boolean; function Read(ANodeId, AParentNodeId: SpxNodeId; out AReadResult: TReadResultArray): Boolean; function Subscribe(ANodeParams: TNodeParams): Boolean; function Unsubscribe(ANodeParams: TNodeParams): Boolean; procedure ResetCurrentNodeId(); function ExistSubscribe(ANodeId: SpxNodeId): Boolean; function UpdateSubscribe(ASubscriptionId: SpxUInt32; AValues : SpxMonitoredItemNotifyArray): Boolean; function ReadHistory(ANodeId: SpxNodeId; AStartTime, AEndTime: SpxDateTime; out AHistoryValues: SpxHistoryReadResult): SpxBoolean; function Write(AWriteValue: SpxWriteValue): SpxBoolean; function CallMethod(AMethodToCall: SpxCallMethodRequest; out AMethodResult: SpxCallMethodResult): SpxBoolean; function ReadCallArguments(ACallNodeId: SpxNodeId; out AInputArguments: SpxArgumentArray; out AOutputArguments: SpxArgumentArray): SpxBoolean; public property CurrentNode: TNodeParams read FCurrentNode; property SubscribeItems: TList<TSubscribeParams> read FSubscribeItems; end; TEventType = ( evtNone, evtLog, evtMonitoredItemChange, evtDisconnected ); TEventParams = record EventType: TEventType; Info: SpxString; // evtLog SubscriptionId: SpxUInt32; // evtMonitoredItemChange Values: SpxMonitoredItemNotifyArray; // evtMonitoredItemChange end; TEventArray = array of TEventParams; TEvents = class private FLock: TCriticalSection; FEventArray: TEventArray; public constructor Create(); destructor Destroy; override; procedure AddEvent(AEventParams: TEventParams); function GetEvents(): TEventArray; end; procedure InitClientConfig(var AClientConfig: SpxClientConfig); procedure InitNode(var ANodeParams: TNodeParams); procedure InitNodeId(var ANodeId: SpxNodeId); procedure InitDataValue(var ADataValue: SpxDataValue); procedure InitValue(var AValue: SpxVariant); function StatusCodeToStr(AStatusCode: SpxStatusCode): String; function TypeToStr(AVariant: SpxVariant): String; function ValueToStr(AVariant: SpxVariant): String; function StrToValue(ABuiltInType: SpxBuiltInType; AString: String; out AValue: SpxVariant): Boolean; implementation uses Simplex.Utils, Simplex.LogHelper; const BrowseSize: Integer = 1000; {$region 'TClient'} constructor TClient.Create(AClientConfig: SpxClientConfig; AEvents: TEvents); begin inherited Create(); FEvents := AEvents; ResetCurrentNodeId(); FSubscribeItems := TList<TSubscribeParams>.Create(); FClientConfig := AClientConfig; FClientConfig.Callback := Self; FClient := TOpcUaClient.Create(FClientConfig); end; destructor TClient.Destroy(); begin if Assigned(FClient) then FreeAndNil(FClient); ClearSubscribe(); if Assigned(FSubscribeItems) then FreeAndNil(FSubscribeItems); inherited; end; function TClient.Connect(): Boolean; begin Result := FClient.Connect(); end; function TClient.Connect(ASecurityMode: SpxMessageSecurityMode; ASecurityPolicyUri: SpxString): Boolean; begin Result := FClient.Connect(ASecurityMode, ASecurityPolicyUri); end; procedure TClient.Disconnect(); begin ClearSubscribe(); FClient.Disconnect(); end; function TClient.GetEndpoints(out AEndpoints: SpxEndpointDescriptionArray): Boolean; begin Result := FClient.GetEndpoints(AEndpoints); end; function TClient.InitSession(): Boolean; begin Result := FClient.InitSession(); end; function TClient.Browse(AParentNodeId: SpxNodeId; out ABrowseResult: SpxBrowseResultArray): Boolean; var BrowseDescriptions: SpxBrowseDescriptionArray; BrowseResults: SpxBrowseResultArray; ContinuationPoints: SpxByteArrayArray; i: Integer; begin Result := False; ABrowseResult := nil; ContinuationPoints := nil; SetLength(BrowseDescriptions, 1); BrowseDescriptions[0].NodeId := AParentNodeId; BrowseDescriptions[0].BrowseDirection := SpxBrowseDirection_Forward; BrowseDescriptions[0].ReferenceTypeId := GetNodeId(0, SpxNodeId_HierarchicalReferences); BrowseDescriptions[0].IncludeSubtypes := True; BrowseDescriptions[0].NodeClassMask := SpxUInt32(SpxNodeClass_Unspecified); BrowseDescriptions[0].ResultMask := SpxUInt32(SpxBrowseResultMask_All); while True do begin if (Length(ContinuationPoints) = 0) then begin if (not FClient.Browse(BrowseSize, BrowseDescriptions, BrowseResults)) then Exit; end else begin if (not FClient.BrowseNext(False, ContinuationPoints, BrowseResults)) then Exit; end; if (Length(BrowseResults) = 0) then Exit; for i := Low(BrowseResults) to High(BrowseResults) do begin SetLength(ABrowseResult, Length(ABrowseResult) + 1); ABrowseResult[Length(ABrowseResult) - 1] := BrowseResults[i]; end; // continue browse (if more than BrowseSize references) if (Length(BrowseResults[0].ContinuationPoint) > 0) then begin SetLength(ContinuationPoints, 1); ContinuationPoints[0] := BrowseResults[0].ContinuationPoint; end else Break; end; Result := True; end; function TClient.ReadServerCertificate(ASecurityPolicyUri: SpxString): Boolean; var ClientConfig: SpxClientConfig; Client: TClient; Endpoints: SpxEndpointDescriptionArray; i: Integer; begin Result := False; if (Length(FClientConfig.ServerCertificateFileName) = 0) then begin Result := True; Exit; end; ClientConfig := FClientConfig; ClientConfig.CertificateFileName := ''; ClientConfig.PrivateKeyFileName := ''; ClientConfig.TrustedCertificatesFolder := ''; ClientConfig.ServerCertificateFileName := ''; ClientConfig.Authentication.AuthenticationType := SpxAuthenticationType_Anonymous; ClientConfig.Authentication.UserName := ''; ClientConfig.Authentication.Password := ''; Client := TClient.Create(ClientConfig, FEvents); if Client.Connect() then if Client.GetEndpoints(Endpoints) then Result := True; FreeAndNil(Client); if (Result = False) then Exit; Result := False; for i := Low(Endpoints) to High(Endpoints) do if (Endpoints[i].SecurityPolicyUri = ASecurityPolicyUri) then if not SaveToFile(Endpoints[i].ServerCertificate, FClientConfig.ServerCertificateFileName) then Exit else begin Result := True; Break; end; if (Result = False) then OnLog(Format('[Error] Server does not support SecurityPolicyUri=%s', [ASecurityPolicyUri])); end; {$region 'Read'} function TClient.Read(ANodeId, AParentNodeId: SpxNodeId; out AReadResult: TReadResultArray): Boolean; var ReadValues: SpxReadValueIdArray; ReadResult: SpxDataValueArray; Index: Integer; AttributeName: String; AttributeId: SpxUInt32; begin Result := False; ResetCurrentNodeId(); AReadResult := nil; ReadValues := nil; Index := 0; while True do begin if not GetAttributeParams(Index, AttributeName, AttributeId) then Break; AddValueAttribute(ANodeId, AttributeId, ReadValues); Index := Index + 1; end; if not FClient.ReadValue(0, SpxTimestampsToReturn_Both, ReadValues, ReadResult) then Exit; Index := 0; while True do begin if not GetAttributeParams(Index, AttributeName, AttributeId) then Break; if (Index >= Length(ReadResult)) then Break; SetLength(AReadResult, Length(AReadResult) + 1); AReadResult[Length(AReadResult) - 1].AttributeName := AttributeName; AReadResult[Length(AReadResult) - 1].AttributeValue := ReadResult[Index]; if (AttributeId = SpxAttributes_UserAccessLevel) then FCurrentNode.AccessLevel := ReadResult[Index].Value.AsByte else if (AttributeId = SpxAttributes_UserExecutable) then FCurrentNode.Excecutable := ReadResult[Index].Value.AsBoolean else if (AttributeId = SpxAttributes_DisplayName) then FCurrentNode.DisplayName := ReadResult[Index].Value.AsLocalizedText.Text else if (AttributeId = SpxAttributes_Value) then FCurrentNode.Value := ReadResult[Index].Value; Index := Index + 1; end; FCurrentNode.NodeId := ANodeId; FCurrentNode.ParentNodeId := AParentNodeId; Result := True; end; procedure TClient.AddValueAttribute(ANodeId: SpxNodeId; AAttributeId: SpxUInt32; var AReadValues: SpxReadValueIdArray); begin SetLength(AReadValues, Length(AReadValues) + 1); AReadValues[Length(AReadValues) - 1].NodeId := ANodeId; AReadValues[Length(AReadValues) - 1].AttributeId := AAttributeId; AReadValues[Length(AReadValues) - 1].IndexRange := ''; AReadValues[Length(AReadValues) - 1].DataEncoding.NamespaceIndex := 0; AReadValues[Length(AReadValues) - 1].DataEncoding.Name := ''; end; function TClient.ReadValue(ANodeId: SpxNodeId; out AValue: SpxDataValue): Boolean; var ReadValues: SpxReadValueIdArray; ReadResult: SpxDataValueArray; begin Result := False; InitDataValue(AValue); ReadValues := nil; ReadResult := nil; AddValueAttribute(ANodeId, SpxAttributes_Value, ReadValues); if not FClient.ReadValue(0, SpxTimestampsToReturn_Both, ReadValues, ReadResult) then Exit; if (Length(ReadResult) = 0) then Exit; if StatusIsBad(ReadResult[0].StatusCode) then Exit; AValue := ReadResult[0]; Result := True; end; {$endregion} {$region 'Subscribe'} function TClient.Subscribe(ANodeParams: TNodeParams): Boolean; var Subscription: SpxSubscription; SubscriptionResult: SpxSubscriptionResult; MonitoredItems: SpxMonitoredItemArray; MonitoredItemResult: SpxMonitoredItemResultArray; SubscribeParams: TSubscribeParams; ClientHandle: SpxUInt32; begin Result := False; ClientHandle := FSubscribeItems.Count; // Create subscription if (FSubscribeItems.Count = 0) then begin Subscription.RequestedPublishingInterval := 500; Subscription.RequestedLifetimeCount := 2000; Subscription.RequestedMaxKeepAliveCount := 20; Subscription.MaxNotificationsPerPublish := 20000; Subscription.Priority := 0; if (not FClient.CreateSubscription(True, Subscription, FSubscriptionId, SubscriptionResult)) then Exit; end; // Create monitored item SetLength(MonitoredItems, 1); MonitoredItems[0] := GetMonitoredItem(ANodeParams.NodeId, ClientHandle, 250); if not FClient.CreateMonitoredItems(FSubscriptionId, MonitoredItems, MonitoredItemResult) then Exit; if (Length(MonitoredItemResult) = 0) then Exit; if not StatusIsGood(MonitoredItemResult[0].StatusCode) then Exit; SubscribeParams := TSubscribeParams.Create(); SubscribeParams.NodeParams := ANodeParams; SubscribeParams.ClientHandle := ClientHandle; SubscribeParams.MonitoredItemId := MonitoredItemResult[0].MonitoredItemId; InitDataValue(SubscribeParams.Value); FSubscribeItems.Add(SubscribeParams); Result := True; end; function TClient.Unsubscribe(ANodeParams: TNodeParams): Boolean; var MonitoredItemIds: SpxUInt32Array; StatusCodes: SpxStatusCodeArray; i, j: Integer; begin Result := False; // Delete monitored item SetLength(MonitoredItemIds, 0); for i := 0 to FSubscribeItems.Count - 1 do if IsEqualNodeId(FSubscribeItems[i].NodeParams.NodeId, ANodeParams.NodeId) then begin SetLength(MonitoredItemIds, Length(MonitoredItemIds) + 1); MonitoredItemIds[Length(MonitoredItemIds) - 1] := FSubscribeItems[i].MonitoredItemId; end; if (Length(MonitoredItemIds) = 0) then begin Result := True; Exit; end; if not FClient.DeleteMonitoredItems(FSubscriptionId, MonitoredItemIds, StatusCodes) then Exit; if (Length(StatusCodes) < Length(MonitoredItemIds)) then Exit; for i := Low(MonitoredItemIds) to High(MonitoredItemIds) do begin if not StatusIsGood(StatusCodes[i]) then Exit; for j := FSubscribeItems.Count - 1 downto 0 do if (FSubscribeItems[j].MonitoredItemId = MonitoredItemIds[i]) then begin FSubscribeItems[j].Free(); FSubscribeItems.Delete(j); end; end; // Delete subscription if (FSubscribeItems.Count = 0) then if not FClient.DeleteAllSubscriptions() then Exit; Result := True; end; procedure TClient.ResetCurrentNodeId(); begin InitNode(FCurrentNode); end; function TClient.GetMonitoredItem(ANodeId: SpxNodeId; AClientHandle: Cardinal; ASamplingInterval: double): SpxMonitoredItem; begin Result.NodeId := ANodeId; Result.AttributeId := SpxAttributes_Value; Result.IndexRange := ''; Result.DataEncoding.NamespaceIndex := 0; Result.DataEncoding.Name := ''; Result.MonitoringMode := SpxMonitoringMode_Reporting; Result.ClientHandle := AClientHandle; Result.SamplingInterval := ASamplingInterval; Result.QueueSize := 1; Result.DiscardOldest := True; end; function TClient.UpdateSubscribe(ASubscriptionId: SpxUInt32; AValues : SpxMonitoredItemNotifyArray): Boolean; var i, j: Integer; begin Result := False; for i := Low(AValues) to High(AValues) do for j := 0 to FSubscribeItems.Count - 1 do if (AValues[i].ClientHandle = FSubscribeItems[j].ClientHandle) then begin FSubscribeItems[j].Value := AValues[i].Value; Result := True; end; end; {$endregion} {$region 'History'} function TClient.ReadHistory(ANodeId: SpxNodeId; AStartTime, AEndTime: SpxDateTime; out AHistoryValues: SpxHistoryReadResult): SpxBoolean; var NodesToRead: SpxHistoryReadValueIdArray; HistoryValues: SpxHistoryReadResultArray; begin Result := False; SetLength(NodesToRead, 1); NodesToRead[0].NodeId := ANodeId; NodesToRead[0].IndexRange := ''; NodesToRead[0].DataEncoding.NamespaceIndex := 0; NodesToRead[0].DataEncoding.Name := ''; NodesToRead[0].ContinuationPoint := nil; if (not FClient.ReadHistory(False, AStartTime, AEndTime, 1000, False, SpxTimestampsToReturn_Both, False, NodesToRead, HistoryValues)) then Exit; if (Length(HistoryValues) = 0) then Exit; if not StatusIsGood(HistoryValues[0].StatusCode) then Exit; AHistoryValues := HistoryValues[0]; Result := True; end; {$endregion} {$region 'Write'} function TClient.Write(AWriteValue: SpxWriteValue): SpxBoolean; var WriteValues: SpxWriteValueArray; StatusCodes: SpxStatusCodeArray; begin Result := False; SetLength(WriteValues, 1); WriteValues[0] := AWriteValue; if not FClient.WriteValue(WriteValues, StatusCodes) then Exit; if (Length(StatusCodes) = 0) then Exit; if not StatusIsGood(StatusCodes[0]) then Exit; Result := True; end; {$endregion} {$region 'Call'} function TClient.CallMethod(AMethodToCall: SpxCallMethodRequest; out AMethodResult: SpxCallMethodResult): SpxBoolean; var MethodsToCall: SpxCallMethodRequestArray; MethodsResults: SpxCallMethodResultArray; begin Result := False; SetLength(MethodsToCall, 1); MethodsToCall[0] := AMethodToCall; if not FClient.CallMethod(MethodsToCall, MethodsResults) then Exit; if (Length(MethodsResults) = 0) then Exit; if StatusIsBad(MethodsResults[0].StatusCode) then Exit; AMethodResult := MethodsResults[0]; Result := True; end; function TClient.ReadCallArguments(ACallNodeId: SpxNodeId; out AInputArguments: SpxArgumentArray; out AOutputArguments: SpxArgumentArray): SpxBoolean; var BrowseResult: SpxBrowseResultArray; i, j: Integer; begin Result := False; AInputArguments := nil; AOutputArguments := nil; if not Browse(ACallNodeId, BrowseResult) then Exit; for i := Low(BrowseResult) to High(BrowseResult) do for j := Low(BrowseResult[i].References) to High(BrowseResult[i].References) do if (BrowseResult[i].References[j].BrowseName.Name = SpxBrowseName_InputArguments) then begin if not ReadArguments(BrowseResult[i].References[j].NodeId.NodeId, AInputArguments) then Exit; end else if (BrowseResult[i].References[j].BrowseName.Name = SpxBrowseName_OutputArguments) then begin if not ReadArguments(BrowseResult[i].References[j].NodeId.NodeId, AOutputArguments) then Exit; end; Result := True; end; function TClient.ReadArguments(AArgumentNodeId: SpxNodeId; out AArguments: SpxArgumentArray): SpxBoolean; var Value: SpxDataValue; begin Result := False; AArguments := nil; if not ReadValue(AArgumentNodeId, Value) then Exit; if not ExtensionObjectArrayToAgrumentArray(Value.Value.AsExtensionObjectArray, AArguments) then Exit; Result := True; end; {$endregion} {$region 'Events'} procedure TClient.OnChannelEvent(AEvent: SpxChannelEvent; AStatus: SpxStatusCode); var EventParams: TEventParams; begin if (AEvent = SpxChannelEvent_Disconnected) then begin EventParams.EventType := evtDisconnected; FEvents.AddEvent(EventParams); end; end; procedure TClient.OnMonitoredItemChange(ASubscriptionId: SpxUInt32; AValues : SpxMonitoredItemNotifyArray); var EventParams: TEventParams; begin EventParams.EventType := evtMonitoredItemChange; EventParams.SubscriptionId := ASubscriptionId; EventParams.Values := AValues; FEvents.AddEvent(EventParams); end; procedure TClient.OnLog(AMessage: SpxString); var EventParams: TEventParams; begin EventParams.EventType := evtLog; EventParams.Info := AMessage; FEvents.AddEvent(EventParams); end; procedure TClient.OnLogWarning(AMessage: SpxString); var EventParams: TEventParams; begin EventParams.EventType := evtLog; EventParams.Info := Format('[WARNING] %s', [AMessage]); FEvents.AddEvent(EventParams); end; procedure TClient.OnLogError(AMessage: SpxString); var EventParams: TEventParams; begin EventParams.EventType := evtLog; EventParams.Info := Format('[ERROR] %s', [AMessage]); FEvents.AddEvent(EventParams); end; procedure TClient.OnLogException(AMessage: SpxString; AException: Exception); var EventParams: TEventParams; begin EventParams.EventType := evtLog; EventParams.Info := Format('[EXCEPTION] %s, E.Message=%s', [AMessage, AException.Message]); FEvents.AddEvent(EventParams); end; {$endregion} {$region 'Secondary functions'} function TClient.ExistSubscribe(ANodeId: SpxNodeId): Boolean; var i: Integer; begin Result := False; for i := 0 to FSubscribeItems.Count - 1 do if IsEqualNodeId(ANodeId, FSubscribeItems[i].NodeParams.NodeId) then begin Result := True; Exit; end; end; function TClient.GetNodeId(ANamespaceIndex: Word; AIdent: Cardinal): SpxNodeId; begin Result.NamespaceIndex := ANamespaceIndex; Result.IdentifierType := SpxIdentifierType_Numeric; Result.IdentifierNumeric := AIdent; end; function TClient.GetAttributeParams(AIndex: Integer; out AAttributeName: String; out AAttributeId: SpxUInt32): Boolean; begin Result := False; case AIndex of 0: begin AAttributeName := 'NodeId'; AAttributeId := SpxAttributes_NodeId; end; 1: begin AAttributeName := 'NodeClass'; AAttributeId := SpxAttributes_NodeClass; end; 2: begin AAttributeName := 'BrowseName'; AAttributeId := SpxAttributes_BrowseName; end; 3: begin AAttributeName := 'DisplayName'; AAttributeId := SpxAttributes_DisplayName; end; 4: begin AAttributeName := 'Description'; AAttributeId := SpxAttributes_Description; end; 5: begin AAttributeName := 'WriteMask'; AAttributeId := SpxAttributes_WriteMask; end; 6: begin AAttributeName := 'UserWriteMask'; AAttributeId := SpxAttributes_UserWriteMask; end; 7: begin AAttributeName := 'IsAbstract'; AAttributeId := SpxAttributes_IsAbstract; end; 8: begin AAttributeName := 'Symmetric'; AAttributeId := SpxAttributes_Symmetric; end; 9: begin AAttributeName := 'InverseName'; AAttributeId := SpxAttributes_InverseName; end; 10: begin AAttributeName := 'ContainsNoLoops'; AAttributeId := SpxAttributes_ContainsNoLoops; end; 11: begin AAttributeName := 'EventNotifier'; AAttributeId := SpxAttributes_EventNotifier; end; 12: begin AAttributeName := 'Value'; AAttributeId := SpxAttributes_Value; end; 13: begin AAttributeName := 'DataType'; AAttributeId := SpxAttributes_DataType; end; 14: begin AAttributeName := 'ValueRank'; AAttributeId := SpxAttributes_ValueRank; end; 15: begin AAttributeName := 'ArrayDimensions'; AAttributeId := SpxAttributes_ArrayDimensions; end; 16: begin AAttributeName := 'AccessLevel'; AAttributeId := SpxAttributes_AccessLevel; end; 17: begin AAttributeName := 'UserAccessLevel'; AAttributeId := SpxAttributes_UserAccessLevel; end; 18: begin AAttributeName := 'MinimumSamplingInterval'; AAttributeId := SpxAttributes_MinimumSamplingInterval; end; 19: begin AAttributeName := 'Historizing'; AAttributeId := SpxAttributes_Historizing; end; 20: begin AAttributeName := 'Executable'; AAttributeId := SpxAttributes_Executable; end; 21: begin AAttributeName := 'UserExecutable'; AAttributeId := SpxAttributes_UserExecutable; end; else Exit; end; Result := True; end; procedure TClient.ClearSubscribe(); var i: Integer; begin if (FSubscribeItems = nil) then Exit; for i := 0 to FSubscribeItems.Count - 1 do FSubscribeItems[i].Free(); FSubscribeItems.Clear(); end; function TClient.SaveToFile(const AData: SpxByteArray; const AFileName: string): Boolean; var Stream: TMemoryStream; begin Result := False; Stream := TMemoryStream.Create; try try if FileExists(AFileName) then DeleteFile(AFileName); Stream.WriteBuffer(AData[0], Length(AData)); Stream.SaveToFile(AFileName); Result := True; except on E: Exception do OnLog(Format('[Error] SaveToFile, FileName=%s, Error=%s', [AFileName, E.Message])); end; finally FreeAndNil(Stream); end; end; {$endregion} {$endregion} {$region 'TEvents'} constructor TEvents.Create(); begin inherited Create(); FLock := TCriticalSection.Create(); FEventArray := nil; end; destructor TEvents.Destroy(); begin if Assigned(FLock) then FreeAndNil(FLock); inherited; end; procedure TEvents.AddEvent(AEventParams: TEventParams); begin FLock.Acquire(); try SetLength(FEventArray, Length(FEventArray) + 1); FEventArray[Length(FEventArray) - 1] := AEventParams; finally FLock.Release(); end; end; function TEvents.GetEvents(): TEventArray; begin FLock.Acquire(); try Result := FEventArray; FEventArray := nil; finally FLock.Release(); end; end; {$endregion} {$region 'Public functions'} procedure InitClientConfig(var AClientConfig: SpxClientConfig); begin AClientConfig.ApplicationInfo.ApplicationName := 'Simplex OPC UA Cllient SDK'; // application uri from ClientCertificate.der AClientConfig.ApplicationInfo.ApplicationUri := 'urn:localhost:Simplex OPC UA Client'; AClientConfig.ApplicationInfo.ProductUri := 'urn:Simplex OPC UA Client'; AClientConfig.ApplicationInfo.ManufacturerName := 'Simplex OPC UA'; AClientConfig.ApplicationInfo.SoftwareVersion := '1.0'; AClientConfig.ApplicationInfo.BuildNumber := '1'; AClientConfig.ApplicationInfo.BuildDate := Now; AClientConfig.SessionTimeout := 300; AClientConfig.TraceLevel := tlDebug; end; procedure InitNode(var ANodeParams: TNodeParams); begin InitNodeId(ANodeParams.NodeId); ANodeParams.AccessLevel := SpxAccessLevels_None; ANodeParams.Excecutable := False; ANodeParams.DisplayName := ''; InitValue(ANodeParams.Value); end; procedure InitNodeId(var ANodeId: SpxNodeId); begin ANodeId.NamespaceIndex := 0; ANodeId.IdentifierType := SpxIdentifierType_Numeric; ANodeId.IdentifierNumeric := 0; end; procedure InitDataValue(var ADataValue: SpxDataValue); begin InitValue(ADataValue.Value); ADataValue.StatusCode := SpxStatusCode_Uncertain; ADataValue.SourceTimestamp := 0; ADataValue.SourcePicoseconds := 0; ADataValue.ServerTimestamp := 0; ADataValue.ServerPicoseconds := 0; end; procedure InitValue(var AValue: SpxVariant); begin AValue.ValueRank := SpxValueRanks_Scalar; AValue.BuiltInType := SpxType_Null; end; function StatusCodeToStr(AStatusCode: SpxStatusCode): String; begin Result := ''; if StatusIsGood(AStatusCode) then Result := 'Good' else if StatusIsBad(AStatusCode) then Result := 'Bad' else if StatusIsUncertain(AStatusCode) then Result := 'Uncertain'; end; function TypeToStr(AVariant: SpxVariant): String; begin Result := ''; case AVariant.BuiltInType of SpxType_Boolean: Result := 'Boolean'; SpxType_SByte: Result := 'SByte'; SpxType_Byte: Result := 'Byte'; SpxType_Int16: Result := 'Int16'; SpxType_UInt16: Result := 'UInt16'; SpxType_Int32: Result := 'Int32'; SpxType_UInt32: Result := 'UInt32'; SpxType_Int64: Result := 'Int64'; SpxType_UInt64: Result := 'UInt64'; SpxType_Float: Result := 'Float'; SpxType_Double: Result := 'Double'; SpxType_String: Result := 'String'; SpxType_DateTime: Result := 'DateTime'; SpxType_Guid: Result := 'Guid'; SpxType_ByteString: Result := 'ByteString'; SpxType_XmlElement: Result := 'XmlElement'; SpxType_NodeId: Result := 'NodeId'; SpxType_ExpandedNodeId: Result := 'ExpandedNodeId'; SpxType_StatusCode: Result := 'StatusCode'; SpxType_QualifiedName: Result := 'QualifiedName'; SpxType_LocalizedText: Result := 'LocalizedText'; end; if (AVariant.ValueRank = SpxValueRanks_OneDimension) then if (Length(Result) > 0) then Result := 'ArrayOf' + Result; end; function ValueToStr(AVariant: SpxVariant): String; begin Result := ''; case AVariant.BuiltInType of SpxType_Boolean: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%s', [BoolToStr(AVariant.AsBoolean, True)]) else Result := SpxBooleanArrayToStr(AVariant.AsBooleanArray); end; SpxType_SByte: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%d', [AVariant.AsSByte]) else Result := SpxSByteArrayToStr(AVariant.AsSByteArray); end; SpxType_Byte: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%d', [AVariant.AsByte]) else Result := SpxByteArrayToStr(AVariant.AsByteArray); end; SpxType_Int16: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%d', [AVariant.AsInt16]) else Result := SpxInt16ArrayToStr(AVariant.AsInt16Array); end; SpxType_UInt16: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%d', [AVariant.AsUInt16]) else Result := SpxUInt16ArrayToStr(AVariant.AsUInt16Array); end; SpxType_Int32: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%d', [AVariant.AsInt32]) else Result := SpxInt32ArrayToStr(AVariant.AsInt32Array); end; SpxType_UInt32: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%d', [AVariant.AsUInt32]) else Result := SpxUInt32ArrayToStr(AVariant.AsUInt32Array); end; SpxType_Int64: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%d', [AVariant.AsInt64]) else Result := SpxInt64ArrayToStr(AVariant.AsInt64Array); end; SpxType_UInt64: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%d', [AVariant.AsUInt64]) else Result := SpxUInt64ArrayToStr(AVariant.AsUInt64Array); end; SpxType_Float: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%f', [AVariant.AsFloat]) else Result := SpxFloatArrayToStr(AVariant.AsFloatArray); end; SpxType_Double: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%f', [AVariant.AsDouble]) else Result := SpxDoubleArrayToStr(AVariant.AsDoubleArray); end; SpxType_String: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%s', [AVariant.AsString]) else Result := SpxStringArrayToStr(AVariant.AsStringArray); end; SpxType_DateTime: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%s', [DateTimeToStr(AVariant.AsDateTime)]) else Result := SpxDateTimeArrayToStr(AVariant.AsDateTimeArray); end; SpxType_Guid: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%s', [GUIDToString(AVariant.AsGuid)]) else Result := SpxGuidArrayToStr(AVariant.AsGuidArray); end; SpxType_ByteString: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%s', [SpxByteArrayToStr(AVariant.AsByteString)]) else Result := SpxByteArrayArrayToStr(AVariant.AsByteStringArray); end; SpxType_XmlElement: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := Format('%s', [AVariant.AsXmlElement]) else Result := SpxStringArrayToStr(AVariant.AsXmlElementArray); end; SpxType_NodeId: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := SpxNodeIdToStr(AVariant.AsNodeId) else Result := SpxNodeIdArrayToStr(AVariant.AsNodeIdArray); end; SpxType_ExpandedNodeId: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := SpxExpandedNodeIdToStr(AVariant.AsExpandedNodeId) else Result := SpxExpandedNodeIdArrayToStr(AVariant.AsExpandedNodeIdArray); end; SpxType_StatusCode: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := SpxStatusCodeToStr(AVariant.AsStatusCode) else Result := SpxStatusCodeArrayToStr(AVariant.AsStatusCodeArray); end; SpxType_QualifiedName: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := SpxQualifiedNameToStr(AVariant.AsQualifiedName) else Result := SpxQualifiedNameArrayToStr(AVariant.AsQualifiedNameArray); end; SpxType_LocalizedText: begin if (AVariant.ValueRank = SpxValueRanks_Scalar) then Result := SpxLocalizedTextToStr(AVariant.AsLocalizedText) else Result := SpxLocalizedTextArrayToStr(AVariant.AsLocalizedTextArray); end; end; end; function StrToValue(ABuiltInType: SpxBuiltInType; AString: String; out AValue: SpxVariant): Boolean; var ValInt: Integer; ValInt64: Int64; begin Result := False; AValue.ValueRank := SpxValueRanks_Scalar; AValue.BuiltInType := ABuiltInType; case ABuiltInType of SpxType_Boolean: begin if not TryStrToBool(AString, AValue.AsBoolean) then Exit; end; SpxType_SByte: begin if not TryStrToInt(AString, ValInt) then Exit; AValue.AsSByte := SpxSByte(ValInt); end; SpxType_Byte: begin if not TryStrToInt(AString, ValInt) then Exit; AValue.AsByte := SpxByte(ValInt); end; SpxType_Int16: begin if not TryStrToInt(AString, ValInt) then Exit; AValue.AsInt16 := SpxInt16(ValInt); end; SpxType_UInt16: begin if not TryStrToInt(AString, ValInt) then Exit; AValue.AsUInt16 := SpxUInt16(ValInt); end; SpxType_Int32: begin if not TryStrToInt(AString, AValue.AsInt32) then Exit; end; SpxType_UInt32: begin if not TryStrToInt(AString, ValInt) then Exit; AValue.AsUInt32 := SpxUInt32(ValInt); end; SpxType_Int64: begin if not TryStrToInt64(AString, AValue.AsInt64) then Exit; end; SpxType_UInt64: begin if not TryStrToInt64(AString, ValInt64) then Exit; AValue.AsUInt64 := SpxUInt64(ValInt64); end; SpxType_Float: begin if not TryStrToFloat(AString, AValue.AsFloat) then Exit; end; SpxType_Double: begin if not TryStrToFloat(AString, AValue.AsDouble) then Exit; end; SpxType_String: begin AValue.AsString := AString; end; SpxType_DateTime: begin if not TryStrToDateTime(AString, AValue.AsDateTime) then Exit; end; else Exit; end; Result := True; end; {$endregion} end.
unit unit_utils; interface uses classes; type TByteArr = array of byte; TStringArr = array of String; function RFC2822Date(const LocalDate: TDateTime; const IsDST: Boolean): string; function md5(s: string): string; function bintostr(const bin: array of byte): string; procedure regWriteString(key:string; value:string); procedure regWriteBool(key:string; value:boolean); procedure regWriteInt(key:string; value:integer); function regReadString(key: string; default: string = ''): string; function regReadBool(key: string; default: Boolean = false): boolean; function regReadInt(key: string; default: Integer = -1): Integer; function Explode(separator: String; text: String): TStringList; function DoubleExplode(separator, separator2: String; text: String): TStringList; function ExplodeToArray(separator: String; text: String): TStringArr; implementation uses IdHashMessageDigest, Windows, SysUtils, Variants, Registry; const reg_path = 'SOFTWARE\Megainformer'; function bintostr(const bin: array of byte): string; const HexSymbols = '0123456789ABCDEF'; var i: integer; begin SetLength(Result, 2*Length(bin)); for i := 0 to Length(bin)-1 do begin Result[1 + 2*i + 0] := HexSymbols[1 + bin[i] shr 4]; Result[1 + 2*i + 1] := HexSymbols[1 + bin[i] and $0F]; end; Result := lowercase(result); end; function RFC2822Date(const LocalDate: TDateTime; const IsDST: Boolean): string; const // Days of week and months of year: must be in English for RFC882 Days: array[1..7] of string = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ); Months: array[1..12] of string = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ); var Day, Month, Year: Word; // parts of LocalDate TZ : Windows.TIME_ZONE_INFORMATION; // time zone information Bias: Integer; // bias in seconds BiasTime: TDateTime; // bias in hrs / mins to display GMTOffset: string; // bias as offset from GMT begin // get year, month and day from date SysUtils.DecodeDate(LocalDate, Year, Month, Day); // compute GMT Offset bias Windows.GetTimeZoneInformation(TZ); Bias := TZ.Bias; if IsDST then Bias := Bias + TZ.DaylightBias else Bias := Bias + TZ.StandardBias; BiasTime := SysUtils.EncodeTime(Abs(Bias div 60), Abs(Bias mod 60), 0, 0); if Bias < 0 then GMTOffset := '+' + SysUtils.FormatDateTime('hhnn', BiasTime) else GMTOffset := '-' + SysUtils.FormatDateTime('hhnn', BiasTime); // build final string Result := Days[DayOfWeek(LocalDate)] + ', ' + SysUtils.IntToStr(Day) + ' ' + Months[Month] + ' ' + SysUtils.IntToStr(Year) + ' ' + SysUtils.FormatDateTime('hh:nn:ss', LocalDate) + ' ' + GMTOffset; end; function md5(s: string): string; begin Result := ''; with TIdHashMessageDigest5.Create do try Result := LowerCase(HashStringAsHex(s)); //AnsiLowerCase(AsHex(HashValue(s))); finally Free; end; end; procedure regWriteString(key:string; value:string); var Reg: TRegistry; begin Reg:= TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey(reg_path, TRUE) then begin Reg.WriteString(key, value); end; finally Reg.Free; end; end; procedure regWriteBool(key:string; value:boolean); var Reg: TRegistry; begin Reg:= TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey(reg_path, TRUE) then begin Reg.WriteBool(key, value); end; finally Reg.Free; end; end; procedure regWriteInt(key:string; value:integer); var Reg: TRegistry; begin Reg:= TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey(reg_path, TRUE) then begin Reg.WriteInteger(key, value); end; finally Reg.Free; end; end; function regReadString(key: string; default: string = ''): string; var Reg: TRegistry; begin Result:=default; Reg:= TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey(reg_path, TRUE) then begin if Reg.ValueExists(key) then Result:= Reg.ReadString(key); end; finally Reg.Free; end; end; function regReadBool(key: string; default: Boolean = false): boolean; var Reg: TRegistry; begin Result:=default; Reg:= TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey(reg_path, TRUE) then begin if Reg.ValueExists(key) then Result:= Reg.ReadBool(key); end; finally Reg.Free; end; end; function regReadInt(key: string; default: Integer = -1): Integer; var Reg: TRegistry; begin Result:=default; Reg:= TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey(reg_path, TRUE) then begin if Reg.ValueExists(key) then Result:= Reg.ReadInteger(key); end; finally Reg.Free; end; end; function Explode(separator: String; text: String): TStringList; var ts: TStringList; i_pos: Integer; text_new: String; s_item: String; begin ts := TStringList.Create; text_new := text; while (text_new <> '') do begin i_pos := Pos(separator, text_new); if i_pos = 0 then begin s_item := text_new; text_new := ''; end else begin s_item := Copy(text_new, 1, i_pos - 1); text_new := Copy(text_new, i_pos + Length(separator), Length(text_new) - i_pos); end; ts.Values[IntToStr(ts.Count)] := Trim(s_item); end; Result := ts; end; function ExplodeToArray(separator: String; text: String): TStringArr; var a:TStringArr; i_pos: Integer; text_new: String; s_item: String; num: integer; begin num:=0; text_new := text; while (text_new <> '') do begin i_pos := Pos(separator, text_new); if i_pos = 0 then begin s_item := text_new; text_new := ''; end else begin s_item := Copy(text_new, 1, i_pos - 1); text_new := Copy(text_new, i_pos + Length(separator), Length(text_new) - i_pos); end; inc(num); SetLength(a, num); a[num-1] := Trim(s_item); end; Result := a; end; function DoubleExplode(separator, separator2: String; text: String): TStringList; var ts: TStringList; i_pos: Integer; text_new: String; s_item: String; begin try ts := TStringList.Create; text_new := text; while (text_new <> '') do begin i_pos := Pos(separator, text_new); if i_pos = 0 then begin s_item := text_new; text_new := ''; end else begin s_item := Copy(text_new, 1, i_pos - 1); text_new := Copy(text_new, i_pos + Length(separator), Length(text_new) - i_pos); end; ts.Values[Trim(Copy(s_item, 1, Pos(separator2, s_item)-1))] := Trim(Copy(s_item, Pos(separator2,s_item)+length(separator2), Length(s_item))); end; except ts.Free; ts := nil end; Result := ts; end; end.
unit CalcUnit; interface uses Math; type TCalc = class public function Adicao(Value1, Value2: Real): Real; function Subtracao(Value1, Value2: Real): Real; function Multiplicacao(Value1, Value2: Real): Real; function Divisao(Value1, Value2: Real): Real; end; implementation { TCalc } function TCalc.Adicao(Value1, Value2: Real): Real; begin Result := Value1 + Value2; end; function TCalc.Subtracao(Value1, Value2: Real): Real; begin Result := Value1 - Value2; end; function TCalc.Multiplicacao(Value1, Value2: Real): Real; begin Result := Value1 * Value2; end; function TCalc.Divisao(Value1, Value2: Real): Real; begin try SetRoundMode(rmNearest); Result := RoundTo((Value1 / Value2), -2); except Result := 0; end; end; end.
unit ideSHRegistry; interface uses Windows, SysUtils, Classes, Contnrs, Dialogs, Graphics, StrUtils, ActnList, SHDesignIntf, SHDevelopIntf, ideSHDesignIntf; procedure ideBTRegisterActions(ActionClasses: array of TSHActionClass); procedure ideBTRegisterComponents(ComponentClasses: array of TSHComponentClass); procedure ideBTRegisterComponentForm(const ClassIID: TGUID; const CallString: string; ComponentForm: TSHComponentFormClass); procedure ideBTRegisterPropertyEditor(const ClassIID: TGUID; const PropertyName: string; PropertyEditor: TSHPropertyEditorClass); procedure ideBTRegisterImage(const StringIID, FileName: string); procedure ideBTRegisterInterface(const Intf: IInterface; const Description: string); function ideBTSupportInterface(const IID: TGUID; out Intf; const Description: string): Boolean; type TRegLibraryDescr = class private FDescription: string; FFileName: string; FModuleHandle: HModule; public property Description: string read FDescription write FDescription; property FileName: string read FFileName write FFileName; property ModuleHandle: HModule read FModuleHandle write FModuleHandle; end; TRegPackageDescr = class private FDescription: string; FFileName: string; FModuleHandle: HModule; public property Description: string read FDescription write FDescription; property FileName: string read FFileName write FFileName; property ModuleHandle: HModule read FModuleHandle write FModuleHandle; end; TRegComponentDescr = class private FComponentClass: TSHComponentClass; public property ComponentClass: TSHComponentClass read FComponentClass write FComponentClass; end; TRegComponentFormDescr = class private FClassIID: TGUID; FCallString: string; FComponentForm: TSHComponentFormClass; public property ClassIID: TGUID read FClassIID write FClassIID; property CallString: string read FCallString write FCallString; property ComponentForm: TSHComponentFormClass read FComponentForm write FComponentForm; end; TRegPropertyEditorDescr = class private FClassIID: TGUID; FPropertyName: string; FPropertyEditor: TSHPropertyEditorClass; public property ClassIID: TGUID read FClassIID write FClassIID; property PropertyName: string read FPropertyName write FPropertyName; property PropertyEditor: TSHPropertyEditorClass read FPropertyEditor write FPropertyEditor; end; TideBTRegistry = class(TComponent, IideBTRegistry) private FLibraryList: TObjectList; FPackageList: TObjectList; FInterfaceList: TInterfaceList; FInterfaceDescrList: TStrings; FBranchList: TComponentList; FComponentList: TObjectList; FPropertyEditorList: TObjectList; FComponentFormList: TObjectList; FDemonList: TComponentList; FImageFileList: TStrings; FImageIIDList: TStrings; FCallStringList: TStrings; FPropSavedList: TStrings; function GetRegLibraryCount: Integer; function GetRegPackageCount: Integer; function GetRegComponentCount: Integer; function GetRegComponentFormCount: Integer; function GetRegPropertyEditorCount: Integer; function GetRegInterfaceCount: Integer; function GetRegDemonCount: Integer; function GetRegLibraryDescription(Index: Integer): string; function GetRegLibraryFileName(Index: Integer): string; function GetRegLibraryName(Index: Integer): string; function GetRegPackageDescription(Index: Integer): string; function GetRegPackageFileName(Index: Integer): string; function GetRegPackageName(Index: Integer): string; function GetRegBranchList: TComponentList; function GetRegBranchInfo(Index: Integer): ISHBranchInfo; overload; function GetRegBranchInfo(const BranchIID: TGUID): ISHBranchInfo; overload; function GetRegBranchInfo(const BranchName: string): ISHBranchInfo; overload; function GetRegComponentClass(Index: Integer): TSHComponentClass; function GetRegComponentHint(Index: Integer): string; function GetRegComponentAssociation(Index: Integer): string; function GetRegComponentClassIID(Index: Integer): TGUID; function SupportInterface(const IID: TGUID; out Intf; const Description: string): Boolean; function GetRegDemon(Index: Integer): TSHComponent; overload; function GetRegDemon(const ClassIID: TGUID): TSHComponent; overload; function GetRegComponent(const ClassIID: TGUID): TSHComponentClass; function GetRegImageIndex(const AStringIID: string): Integer; function GetRegCallStrings(const AClassIID: TGUID): TStrings; function GetRegComponentForm(const ClassIID: TGUID; const CallString: string): TSHComponentFormClass; function GetRegComponentFactory(const ClassIID: TGUID): ISHComponentFactory; overload; function GetRegComponentFactory(const ClassIID, BranchIID: TGUID): ISHComponentFactory; overload; function GetRegComponentOptions(const ClassIID: TGUID): ISHComponentOptions; function GetRegPropertyEditor(const ClassIID: TGUID; const PropertyName: string): TSHPropertyEditorClass; function IndexOfLibrary(const FileName: string): Integer; function ExistsLibrary(const FileName: string): Boolean; function AddLibrary(const FileName: string): HModule; procedure RemoveLibrary(const FileName: string); function IndexOfPackage(const FileName: string): Integer; function ExistsPackage(const FileName: string): Boolean; function AddPackage(const FileName: string): HModule; procedure RemovePackage(const FileName: string); function IndexOfComponent(ComponentClass: TSHComponentClass): Integer; function ExistsComponent(ComponentClass: TSHComponentClass): Boolean; procedure AddComponent(ComponentClass: TSHComponentClass); // procedure RemoveComponent(ComponentClass: TSHComponentClass); function IndexOfComponentForm(const ClassIID: TGUID; const CallString: string; ComponentForm: TSHComponentFormClass): Integer; function ExistsComponentForm(const ClassIID: TGUID; const CallString: string; ComponentForm: TSHComponentFormClass): Boolean; procedure AddComponentForm(const ClassIID: TGUID; const CallString: string; ComponentForm: TSHComponentFormClass); // procedure RemoveComponentForm(const ClassIID: TGUID; // const CallString: string; ComponentForm: TSHComponentFormClass); function IndexOfPropertyEditor(const ClassIID: TGUID; const PropertyName: string; PropertyEditor: TSHPropertyEditorClass): Integer; function ExistsPropertyEditor(const ClassIID: TGUID; const PropertyName: string; PropertyEditor: TSHPropertyEditorClass): Boolean; procedure AddPropertyEditor(const ClassIID: TGUID; const PropertyName: string; PropertyEditor: TSHPropertyEditorClass); // procedure RemovePropertyEditor(const ClassIID: TGUID; // const PropertyName: string; PropertyEditor: TSHPropertyEditorClass); // function IndexOfInterface(const Intf: IInterface; // const Description: string): Integer; // function ExistsInterface(const Intf: IInterface; // const Description: string): Boolean; procedure AddInterface(const Intf: IInterface; const Description: string); // procedure RemoveInterface(const Intf: IInterface; // const Description: string); procedure RegisterLibrary(const FileName: string); procedure UnRegisterLibrary(const FileName: string); procedure RegisterPackage(const FileName: string); procedure UnRegisterPackage(const FileName: string); procedure RegisterComponents(ComponentClasses: array of TSHComponentClass); procedure RegisterComponentForm(const ClassIID: TGUID; const CallString: string; ComponentForm: TSHComponentFormClass); procedure RegisterPropertyEditor(const ClassIID: TGUID; const PropertyName: string; PropertyEditor: TSHPropertyEditorClass); procedure RegisterImage(const StringIID, FileName: string); procedure RegisterInterface(const Intf: IInterface; const Description: string); procedure LoadLibrariesFromFile; procedure SaveLibrariesToFile; function InitializeLibraryA(const FileName: string): HModule; // procedure InitializeLibraries; function GetLibraryDescription(ModuleHandle: HModule): string; procedure LoadPackagesFromFile; procedure SavePackagesToFile; function InitializePackageA(const FileName: string): HModule; // procedure InitializePackages; // procedure LoadImagesFromModule(Module: HModule); procedure LoadOptionsFromFile; procedure SaveOptionsToFile; procedure LoadOptionsFromList; procedure SaveOptionsToList; procedure LoadImagesFromFile; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses ideSHSplashFrm, ideSHMainFrm, ideSHConsts, ideSHMessages, ideSHSysUtils, ideSHSystem, SysConst; procedure ideBTRegisterActions(ActionClasses: array of TSHActionClass); var I: Integer; Action: TSHAction; begin for I := Low(ActionClasses) to High(ActionClasses) do if Assigned(ActionClasses[I]) then begin Action := ActionClasses[I].Create(MainForm); Action.ActionList := MainForm.ActionList1; end; end; procedure ideBTRegisterComponents(ComponentClasses: array of TSHComponentClass); begin if Assigned(RegistryIntf) then RegistryIntf.RegisterComponents(ComponentClasses); end; procedure ideBTRegisterComponentForm(const ClassIID: TGUID; const CallString: string; ComponentForm: TSHComponentFormClass); begin if Assigned(RegistryIntf) then RegistryIntf.RegisterComponentForm(ClassIID, CallString, ComponentForm); end; procedure ideBTRegisterPropertyEditor(const ClassIID: TGUID; const PropertyName: string; PropertyEditor: TSHPropertyEditorClass); begin if Assigned(RegistryIntf) then RegistryIntf.RegisterPropertyEditor(ClassIID, PropertyName, PropertyEditor); end; procedure ideBTRegisterImage(const StringIID, FileName: string); begin if Assigned(RegistryIntf) then RegistryIntf.RegisterImage(StringIID, FileName); end; procedure ideBTRegisterInterface(const Intf: IInterface; const Description: string); begin if Assigned(RegistryIntf) then RegistryIntf.RegisterInterface(Intf, Description); end; function ideBTSupportInterface(const IID: TGUID; out Intf; const Description: string): Boolean; begin Result := Assigned(RegistryIntf) and RegistryIntf.SupportInterface(IID, Intf, Description); end; //function ForEachModule(HInstance: Longint; Data: Pointer): Boolean; //type // TPackageLoad = procedure; //var // PackageLoad: TPackageLoad; //begin // @PackageLoad := GetProcAddress(HInstance, 'Initialize'); //Do not localize // if Assigned(PackageLoad) then // begin // InitializePackage(HInstance); // Registry.LoadImagesFromModule(HInstance); // end; // Result := True; //end; procedure _InitializePackage(Module: HMODULE); begin try InitializePackage(Module); except FreeLibrary(Module); raise; end; end; function _GetPackageDescription(Module: HMODULE): string; var ResInfo: HRSRC; ResData: HGLOBAL; begin ResInfo := FindResource(Module, 'DESCRIPTION', RT_RCDATA); if ResInfo <> 0 then begin ResData := LoadResource(Module, ResInfo); if ResData <> 0 then try Result := PWideChar(LockResource(ResData)); UnlockResource(ResData); finally FreeResource(ResData); end; end; end; function _ModuleIsPackage(Module: HMODULE): Boolean; type TPackageLoad = procedure; var PackageLoad: TPackageLoad; begin @PackageLoad := GetProcAddress(Module, 'Initialize'); //Do not localize Result := Assigned(PackageLoad); end; function _ModuleIsSQLHammerPackage(Module: HMODULE): Boolean; begin Result := Pos(AnsiUpperCase('BlazeTop'), AnsiUpperCase(_GetPackageDescription(Module))) = 1; end; function _ModuleDontInit(CurModule: PLibModule): Boolean; begin Result := CurModule.Reserved <> - 100; end; procedure _InitializePackages; var CurModule: PLibModule; ModuleList: TList; I: Integer; begin ModuleList := TList.Create; try CurModule := LibModuleList; while CurModule <> nil do begin if _ModuleIsPackage(CurModule.Instance) and _ModuleIsSQLHammerPackage(CurModule.Instance) and _ModuleDontInit(CurModule) then ModuleList.Add(CurModule); CurModule := CurModule.Next; end; for I := Pred(ModuleList.Count) downto 0 do begin CurModule := ModuleList[I]; _InitializePackage(CurModule.Instance); // Registry.LoadImagesFromModule(CurModule.Instance); CurModule.Reserved := -100; end; finally ModuleList.Free; end; end; function _LoadPackage(const Name: string): HMODULE; begin Result := SafeLoadLibrary(Name); if Result = 0 then raise EPackageError.CreateResFmt(@sErrorLoadingPackage, [Name, SysErrorMessage(GetLastError)]); end; { TideBTRegistry } constructor TideBTRegistry.Create(AOwner: TComponent); begin inherited Create(AOwner); FPackageList := TObjectList.Create; FLibraryList := TObjectList.Create; FInterfaceList := TInterfaceList.Create; FInterfaceDescrList := TStringList.Create; FBranchList := TComponentList.Create(False); FComponentList := TObjectList.Create; FPropertyEditorList := TObjectList.Create; FComponentFormList := TObjectList.Create; FDemonList := TComponentList.Create; FImageFileList := TStringList.Create; FImageIIDList := TStringList.Create; FCallStringList := TStringList.Create; FPropSavedList := TStringList.Create; (FImageFileList as TStringList).Sorted := True; (FImageIIDList as TStringList).Sorted := True; end; destructor TideBTRegistry.Destroy; begin FLibraryList.Free; FPackageList.Free; FInterfaceList := nil; FInterfaceDescrList.Free; FBranchList.Free; FComponentList.Free; FPropertyEditorList.Free; FComponentFormList.Free; FDemonList.Free; FImageFileList.Free; FImageIIDList.Free; FCallStringList.Free; FPropSavedList.Free; inherited Destroy; end; function TideBTRegistry.GetRegLibraryCount: Integer; begin Result := FLibraryList.Count; end; function TideBTRegistry.GetRegPackageCount: Integer; begin Result := FPackageList.Count; end; function TideBTRegistry.GetRegComponentCount: Integer; begin Result := FComponentList.Count; end; function TideBTRegistry.GetRegComponentFormCount: Integer; begin Result := FComponentFormList.Count; end; function TideBTRegistry.GetRegPropertyEditorCount: Integer; begin Result := FPropertyEditorList.Count; end; function TideBTRegistry.GetRegInterfaceCount: Integer; begin Result := FInterfaceList.Count; end; function TideBTRegistry.GetRegDemonCount: Integer; begin Result := FDemonList.Count; end; function TideBTRegistry.GetRegLibraryDescription(Index: Integer): string; begin Result := TRegLibraryDescr(FLibraryList[Index]).Description; end; function TideBTRegistry.GetRegLibraryFileName(Index: Integer): string; begin Result := TRegLibraryDescr(FLibraryList[Index]).FileName; end; function TideBTRegistry.GetRegLibraryName(Index: Integer): string; begin Result := ExtractFileName(TRegLibraryDescr(FLibraryList[Index]).FileName); end; function TideBTRegistry.GetRegPackageDescription(Index: Integer): string; begin Result := TRegPackageDescr(FPackageList[Index]).Description; end; function TideBTRegistry.GetRegPackageFileName(Index: Integer): string; begin Result := TRegPackageDescr(FPackageList[Index]).FileName; end; function TideBTRegistry.GetRegPackageName(Index: Integer): string; begin Result := ExtractFileName(TRegPackageDescr(FPackageList[Index]).FileName); end; function TideBTRegistry.GetRegBranchList: TComponentList; begin Result := FBranchList; end; function TideBTRegistry.GetRegBranchInfo(Index: Integer): ISHBranchInfo; begin Supports(FBranchList[Index], ISHBranchInfo, Result); end; function TideBTRegistry.GetRegBranchInfo(const BranchIID: TGUID): ISHBranchInfo; var I: Integer; begin Result := nil; for I := 0 to Pred(FBranchList.Count) do if IsEqualGUID(TSHComponent(FBranchList[I]).ClassIID, BranchIID) then begin Result := GetRegBranchInfo(I); Break; end; end; function TideBTRegistry.GetRegBranchInfo(const BranchName: string): ISHBranchInfo; var I: Integer; begin Result := nil; for I := 0 to Pred(FBranchList.Count) do if AnsiSameText(GetRegBranchInfo(I).BranchName, BranchName) then begin Result := GetRegBranchInfo(I); Break; end; end; function TideBTRegistry.GetRegComponentClass(Index: Integer): TSHComponentClass; begin Result := TRegComponentDescr(FComponentList[Index]).ComponentClass; end; function TideBTRegistry.GetRegComponentHint(Index: Integer): string; begin Result := TRegComponentDescr(FComponentList[Index]).ComponentClass.GetHintClassFnc; end; function TideBTRegistry.GetRegComponentAssociation(Index: Integer): string; begin Result := TRegComponentDescr(FComponentList[Index]).ComponentClass.GetAssociationClassFnc; end; function TideBTRegistry.GetRegComponentClassIID(Index: Integer): TGUID; begin Result := TRegComponentDescr(FComponentList[Index]).ComponentClass.GetClassIIDClassFnc; end; function TideBTRegistry.SupportInterface(const IID: TGUID; out Intf; const Description: string): Boolean; var I: Integer; begin Result := False; for I := Pred(FInterfaceList.Count) downto 0 do begin Result := Supports(FInterfaceList.Items[I], IID, Intf); if Result then if AnsiSameText(FInterfaceDescrList[I], Description) then Break; end; end; function TideBTRegistry.GetRegDemon(Index: Integer): TSHComponent; begin Result := TSHComponent(FDemonList[Index]); end; function TideBTRegistry.GetRegDemon(const ClassIID: TGUID): TSHComponent; var I: Integer; begin Result := nil; for I := Pred(FDemonList.Count) downto 0 do begin if IsEqualGUID(TSHComponent(FDemonList[I]).ClassIID, ClassIID) then Result := FDemonList[I] as TSHComponent; if Assigned(Result) then Break; end; end; function TideBTRegistry.GetRegComponent(const ClassIID: TGUID): TSHComponentClass; var I: Integer; begin Result := nil; for I := 0 to Pred(FComponentList.Count) do if IsEqualGUID(TRegComponentDescr(FComponentList[I]).ComponentClass.GetClassIIDClassFnc, ClassIID) then begin Result := TRegComponentDescr(FComponentList[I]).ComponentClass; Break; end; end; function TideBTRegistry.GetRegImageIndex(const AStringIID: string): Integer; var I: Integer; begin Result := IMG_DEFAULT; I := FImageIIDList.IndexOf(AnsiUpperCase(AStringIID)); if I <> -1 then Result := Integer(FImageIIDList.Objects[I]); end; function TideBTRegistry.GetRegCallStrings(const AClassIID: TGUID): TStrings; var I: Integer; begin FCallStringList.Clear; for I := Pred(FComponentFormList.Count) downto 0 do if IsEqualGUID(TRegComponentFormDescr(FComponentFormList[I]).ClassIID, AClassIID) then if FCallStringList.IndexOf(TRegComponentFormDescr(FComponentFormList[I]).CallString) = -1 then FCallStringList.Add(TRegComponentFormDescr(FComponentFormList[I]).CallString); Result := FCallStringList; end; function TideBTRegistry.GetRegComponentForm(const ClassIID: TGUID; const CallString: string): TSHComponentFormClass; var I, J: Integer; ClassPtr: TClass; IntfTable: PInterfaceTable; begin Result := nil; ClassPtr := GetRegComponent(ClassIID); while Assigned(ClassPtr) do begin IntfTable := ClassPtr.GetInterfaceTable; if Assigned(IntfTable) then begin for I := Pred(IntfTable.EntryCount) downto 0 do begin for J := Pred(FComponentFormList.Count) downto 0 do if IsEqualGUID(TRegComponentFormDescr(FComponentFormList[J]).ClassIID, IntfTable.Entries[I].IID) and AnsiSameText(TRegComponentFormDescr(FComponentFormList[J]).CallString, CallString) then begin Result := TRegComponentFormDescr(FComponentFormList[J]).ComponentForm; Exit; end; end; end; ClassPtr := ClassPtr.ClassParent; end; end; function TideBTRegistry.GetRegComponentFactory(const ClassIID: TGUID): ISHComponentFactory; var I: Integer; begin Result := nil; for I := Pred(FDemonList.Count) downto 0 do begin Supports(FDemonList[I], ISHComponentFactory, Result); if Assigned(Result) then if Result.SupportComponent(ClassIID) then Break; Result := nil; end; end; function TideBTRegistry.GetRegComponentFactory(const ClassIID, BranchIID: TGUID): ISHComponentFactory; var I: Integer; begin Result := nil; for I := Pred(FDemonList.Count) downto 0 do begin if (FDemonList[I] is TSHComponent) and IsEqualGUID(TSHComponent(FDemonList[I]).BranchIID, BranchIID) then Supports(FDemonList[I], ISHComponentFactory, Result); if Assigned(Result) then if Result.SupportComponent(ClassIID) then Break; Result := nil; end; end; function TideBTRegistry.GetRegComponentOptions(const ClassIID: TGUID): ISHComponentOptions; var I: Integer; begin Result := nil; for I := Pred(FDemonList.Count) downto 0 do begin if IsEqualGUID(TSHComponent(FDemonList[I]).ClassIID, ClassIID) then Supports(FDemonList[I], ClassIID, Result); if Assigned(Result) then Break; end; end; function TideBTRegistry.GetRegPropertyEditor(const ClassIID: TGUID; const PropertyName: string): TSHPropertyEditorClass; var I: Integer; begin Result := nil; for I := Pred(FPropertyEditorList.Count) downto 0 do if IsEqualGUID(TRegPropertyEditorDescr(FPropertyEditorList[I]).ClassIID, ClassIID) and AnsiSameText(TRegPropertyEditorDescr(FPropertyEditorList[I]).PropertyName, PropertyName) then begin Result := TRegPropertyEditorDescr(FPropertyEditorList[I]).PropertyEditor; Break; end; end; function TideBTRegistry.IndexOfPackage(const FileName: string): Integer; var I: Integer; begin Result := -1; for I := 0 to Pred(FPackageList.Count) do if AnsiSameText(ExtractFileName(TRegPackageDescr(FPackageList[I]).FileName), ExtractFileName(FileName)) then begin Result := I; Break; end; end; function TideBTRegistry.ExistsPackage(const FileName: string): Boolean; begin Result := IndexOfPackage(FileName) <> -1; end; function TideBTRegistry.AddPackage(const FileName: string): HModule; var RegPackageDescr: TRegPackageDescr; begin Result := 0; if not ExistsPackage(FileName) then begin Result := InitializePackageA(FileName); if Result <> 0 then begin RegPackageDescr := TRegPackageDescr.Create; RegPackageDescr.FileName := FileName; RegPackageDescr.Description := SysUtils.GetPackageDescription(PChar(FileName)); RegPackageDescr.ModuleHandle := Result; FPackageList.Add(RegPackageDescr); if Assigned(SplashForm) then SplashForm.SplashTrace(RegPackageDescr.Description); end; end; end; procedure TideBTRegistry.RemovePackage(const FileName: string); var I: Integer; begin I := IndexOfPackage(FileName); if I <> -1 then FPackageList.Delete(I); end; function TideBTRegistry.IndexOfLibrary(const FileName: string): Integer; var I: Integer; begin Result := -1; for I := 0 to Pred(FLibraryList.Count) do if AnsiSameText(ExtractFileName(TRegLibraryDescr(FLibraryList[I]).FileName), ExtractFileName(FileName)) then begin Result := I; Break; end; end; function TideBTRegistry.ExistsLibrary(const FileName: string): Boolean; begin Result := IndexOfLibrary(FileName) <> -1; end; function TideBTRegistry.AddLibrary(const FileName: string): HModule; var RegLibraryDescr: TRegLibraryDescr; begin Result := 0; if not ExistsLibrary(FileName) then begin Result := InitializeLibraryA(FileName); if Result <> 0 then begin RegLibraryDescr := TRegLibraryDescr.Create; RegLibraryDescr.FileName := FileName; RegLibraryDescr.Description := GetLibraryDescription(Result); RegLibraryDescr.ModuleHandle := Result; FLibraryList.Add(RegLibraryDescr); if Assigned(SplashForm) then SplashForm.SplashTrace(RegLibraryDescr.Description); // if Assigned(BTSplashForm) then BTSplashForm.SplashTraceDone; end; end; end; procedure TideBTRegistry.RemoveLibrary(const FileName: string); var I: Integer; begin I := IndexOfLibrary(FileName); if I <> -1 then FLibraryList.Delete(I); end; function TideBTRegistry.IndexOfComponent(ComponentClass: TSHComponentClass): Integer; var I: Integer; begin Result := -1; for I := 0 to Pred(FComponentList.Count) do if TRegComponentDescr(FComponentList[I]).ComponentClass = ComponentClass then begin Result := I; Break; end; end; function TideBTRegistry.ExistsComponent(ComponentClass: TSHComponentClass): Boolean; begin if Supports(ComponentClass, ISHDRVNativeDAC) then Result := False else Result := IndexOfComponent(ComponentClass) <> -1; end; procedure TideBTRegistry.AddComponent(ComponentClass: TSHComponentClass); var RegComponentDescr: TRegComponentDescr; begin if not ExistsComponent(ComponentClass) then begin RegComponentDescr := TRegComponentDescr.Create; RegComponentDescr.ComponentClass := ComponentClass; FComponentList.Add(RegComponentDescr); end; end; //procedure TideBTRegistry.RemoveComponent(ComponentClass: TSHComponentClass); //var // I: Integer; //begin // I := IndexOfComponent(ComponentClass); // if I <> -1 then FComponentList.Delete(I); //end; function TideBTRegistry.IndexOfComponentForm(const ClassIID: TGUID; const CallString: string; ComponentForm: TSHComponentFormClass): Integer; var I: Integer; begin Result := -1; for I := 0 to Pred(FComponentFormList.Count) do if IsEqualGUID(TRegComponentFormDescr(FComponentFormList[I]).ClassIID, ClassIID) and AnsiSameText(TRegComponentFormDescr(FComponentFormList[I]).CallString, CallString) and (TRegComponentFormDescr(FComponentFormList[I]).ComponentForm = ComponentForm) then begin Result := I; Break; end; end; function TideBTRegistry.ExistsComponentForm(const ClassIID: TGUID; const CallString: string; ComponentForm: TSHComponentFormClass): Boolean; begin Result := IndexOfComponentForm(ClassIID, CallString, ComponentForm) <> -1; end; procedure TideBTRegistry.AddComponentForm(const ClassIID: TGUID; const CallString: string; ComponentForm: TSHComponentFormClass); var RegComponentFormDescr: TRegComponentFormDescr; begin if not ExistsComponentForm(ClassIID, CallString, ComponentForm) then begin RegComponentFormDescr := TRegComponentFormDescr.Create; RegComponentFormDescr.ClassIID := ClassIID; RegComponentFormDescr.CallString := CallString; RegComponentFormDescr.ComponentForm := ComponentForm; FComponentFormList.Add(RegComponentFormDescr); end; end; //procedure TideBTRegistry.RemoveComponentForm(const ClassIID: TGUID; // const CallString: string; ComponentForm: TSHComponentFormClass); //var // I: Integer; //begin // I := IndexOfComponentForm(ClassIID, CallString, ComponentForm); // if I <> -1 then FComponentFormList.Delete(I); //end; function TideBTRegistry.IndexOfPropertyEditor(const ClassIID: TGUID; const PropertyName: string; PropertyEditor: TSHPropertyEditorClass): Integer; var I: Integer; begin Result := -1; for I := 0 to Pred(FPropertyEditorList.Count) do if IsEqualGUID(TRegPropertyEditorDescr(FPropertyEditorList[I]).ClassIID, ClassIID) and AnsiSameText(TRegPropertyEditorDescr(FPropertyEditorList[I]).PropertyName, PropertyName) and (TRegPropertyEditorDescr(FPropertyEditorList[I]).PropertyEditor = PropertyEditor) then begin Result := I; Break; end; end; function TideBTRegistry.ExistsPropertyEditor(const ClassIID: TGUID; const PropertyName: string; PropertyEditor: TSHPropertyEditorClass): Boolean; begin Result := IndexOfPropertyEditor(ClassIID, PropertyName, PropertyEditor) <> -1; end; procedure TideBTRegistry.AddPropertyEditor(const ClassIID: TGUID; const PropertyName: string; PropertyEditor: TSHPropertyEditorClass); var RegPropertyEditorDescr: TRegPropertyEditorDescr; begin if not ExistsPropertyEditor(ClassIID, PropertyName, PropertyEditor) then begin RegPropertyEditorDescr := TRegPropertyEditorDescr.Create; RegPropertyEditorDescr.ClassIID := ClassIID; RegPropertyEditorDescr.PropertyName := PropertyName; RegPropertyEditorDescr.PropertyEditor := PropertyEditor; FPropertyEditorList.Add(RegPropertyEditorDescr); end; end; //procedure TideBTRegistry.RemovePropertyEditor(const ClassIID: TGUID; // const PropertyName: string; PropertyEditor: TSHPropertyEditorClass); //var // I: Integer; //begin // I := IndexOfPropertyEditor(ClassIID, PropertyName, PropertyEditor); // if I <> -1 then FPropertyEditorList.Delete(I) //end; //function TideBTRegistry.IndexOfInterface(const Intf: IInterface; // const Description: string): Integer; //begin // Result := FInterfaceDescrList.IndexOf(Description); //end; //function TideBTRegistry.ExistsInterface(const Intf: IInterface; // const Description: string): Boolean; //begin // Result := IndexOfInterface(Intf, Description) <> -1; //end; procedure TideBTRegistry.AddInterface(const Intf: IInterface; const Description: string); begin // if not ExistsInterface(Intf, Description) then FInterfaceDescrList.Insert(FInterfaceList.Add(Intf), Description); end; //procedure TideBTRegistry.RemoveInterface(const Intf: IInterface; // const Description: string); //var // I: Integer; //begin // I := IndexOfInterface(Intf, Description); // if I <> -1 then // begin // FInterfaceList.Delete(I); // FInterfaceDescrList.Delete(I); // end; //end; procedure TideBTRegistry.RegisterLibrary(const FileName: string); begin AddLibrary(FileName); end; procedure TideBTRegistry.UnRegisterLibrary(const FileName: string); begin RemoveLibrary(FileName); end; procedure TideBTRegistry.RegisterPackage(const FileName: string); begin AddPackage(FileName); _InitializePackages; end; procedure TideBTRegistry.UnRegisterPackage(const FileName: string); begin RemovePackage(FileName); end; procedure TideBTRegistry.RegisterComponents(ComponentClasses: array of TSHComponentClass); var I: Integer; begin for I := Low(ComponentClasses) to High(ComponentClasses) do begin if Assigned(ComponentClasses[I]) then begin if not ExistsComponent(ComponentClasses[I]) then begin AddComponent(ComponentClasses[I]); if Supports(ComponentClasses[I], ISHDemon) then FDemonList.Add(ComponentClasses[I].Create(nil)); if Supports(ComponentClasses[I], ISHBranchInfo) then FBranchList.Insert(0, FDemonList.Last); end; end; end; end; procedure TideBTRegistry.RegisterComponentForm(const ClassIID: TGUID; const CallString: string; ComponentForm: TSHComponentFormClass); begin AddComponentForm(ClassIID, CallString, ComponentForm); end; procedure TideBTRegistry.RegisterPropertyEditor(const ClassIID: TGUID; const PropertyName: string; PropertyEditor: TSHPropertyEditorClass); begin AddPropertyEditor(ClassIID, PropertyName, PropertyEditor); end; procedure TideBTRegistry.RegisterImage(const StringIID, FileName: string); var I: Integer; begin // I := FImageIIDList.IndexOf(AnsiUpperCase(StringIID)); // if I <> -1 then FImageIIDList.Delete(I); I := FImageFileList.IndexOf(AnsiUpperCase(FileName)); if I <> -1 then FImageIIDList.AddObject(AnsiUpperCase(StringIID), TObject(FImageFileList.Objects[I])); end; procedure TideBTRegistry.RegisterInterface(const Intf: IInterface; const Description: string); begin AddInterface(Intf, Description); end; procedure TideBTRegistry.LoadLibrariesFromFile; var TmpList: TStringList; I{, J}: Integer; f :string; begin TmpList := TStringList.Create; try f :=GetFilePath(SFileConfig); if FileExists(f) then begin LoadStringsFromFile(f, SSectionLibraries, TmpList); FLibraryList.Clear; for I := 0 to Pred(TmpList.Count) do begin try {J := }AddLibrary(DecodeAppPath(TmpList.Values[TmpList.Names[I]])); // if J = 0 then DeleteKeyInFile(SFileConfig, SSectionLibraries, TmpList.Names[I]); except Continue; end; end; end; finally TmpList.Free; end; end; procedure TideBTRegistry.SaveLibrariesToFile; var TmpList: TStringList; I: Integer; f:string; begin TmpList := TStringList.Create; try f:=GetFilePath(SFileConfig); for I := 0 to Pred(FLibraryList.Count) do TmpList.Add(Format('%s=%s', [TRegLibraryDescr(FLibraryList[I]).Description, EncodeAppPath(TRegLibraryDescr(FLibraryList[I]).FileName)])); SaveStringsToFile(f, SSectionLibraries, TmpList,True); finally TmpList.Free; end; end; function TideBTRegistry.GetLibraryDescription(ModuleHandle: HModule): string; type TLibraryDescription = function(): PChar; var Description: TLibraryDescription; begin @Description := GetProcAddress(ModuleHandle, 'GetSQLHammerLibraryDescription'); if Assigned(Description) then Result := AnsiString(Description); if Length(Result) = 0 then Result := Format('%s', [SNone]); end; function TideBTRegistry.InitializeLibraryA(const FileName: string): HModule; begin Result := 0; try Result := LoadLibrary(PChar(FileName)); if Pos(UpperCase('BlazeTop'), AnsiUpperCase(GetLibraryDescription(Result))) = 0 then ShowMsg(Format(SLibraryCantLoad, [FileName]) + sLineBreak + SMustBeDescription, mtWarning); except ShowMsg(Format(SLibraryCantLoad, [FileName]), mtError); end; end; //procedure TideBTRegistry.InitializeLibraries; //begin // TODO //end; procedure TideBTRegistry.LoadPackagesFromFile; var TmpList: TStringList; I{, J}: Integer; f:string; begin TmpList := TStringList.Create; try f:=GetFilePath(SFileConfig); if FileExists(f) then begin LoadStringsFromFile(f, SSectionPackages, TmpList); FPackageList.Clear; for I := 0 to Pred(TmpList.Count) do begin try {J := }AddPackage(DecodeAppPath(TmpList.Values[TmpList.Names[I]])); // if J = 0 then DeleteKeyInFile(SFileConfig, SSectionPackages, TmpList.Names[I]); except Continue; end; end; if Assigned(SplashForm) then SplashForm.SplashTrace(''); if Assigned(SplashForm) then SplashForm.SplashTrace('Initializing Packages...'); _InitializePackages; if Assigned(SplashForm) then SplashForm.SplashTraceDone; end; finally TmpList.Free; end; end; procedure TideBTRegistry.SavePackagesToFile; var TmpList: TStringList; I: Integer; f:string; begin TmpList := TStringList.Create; try f:=GetFilePath(SFileConfig); for I := 0 to Pred(FPackageList.Count) do TmpList.Add(Format('%s=%s', [TRegPackageDescr(FPackageList[I]).Description, EncodeAppPath(TRegPackageDescr(FPackageList[I]).FileName)])); SaveStringsToFile(f, SSectionPackages, TmpList,True); finally TmpList.Free; end; end; function TideBTRegistry.InitializePackageA(const FileName: string): HModule; begin Result := Pos(AnsiUpperCase('BlazeTop'), AnsiUpperCase(SysUtils.GetPackageDescription(PChar(FileName)))); if Result = 0 then begin ShowMsg(Format(SPackageCantLoad, [FileName]) + sLineBreak + SMustBeDescription, mtWarning); Exit; end; Result := _LoadPackage(FileName); end; //procedure TideBTRegistry.InitializePackages; //begin // EnumModules(ForEachModule, nil); //end; (* procedure TideBTRegistry.LoadImagesFromModule(Module: HModule); //var // I: Integer; // Bmp: TBitmap; // Pixel: Integer; begin //Pixel := Bmp.Canvas.ClipRect.Top - Bmp.Canvas.ClipRect.Bottom; Pixel := 15; if Assigned(MainIntf) then begin Bmp := TBitmap.Create; try // // Загрузка глифов для компонентов // for I := 0 to Pred(FComponentList.Count) do begin if TRegComponentDescr(FComponentList[I]).ImageIndex = IMG_DEFAULT then begin Bmp.Handle := LoadBitmap(Module, PChar(AnsiUpperCase(TRegComponentDescr(FComponentList[I]).ComponentClass.ClassName))); if Bmp.Handle <> 0 then TRegComponentDescr(FComponentList[I]).ImageIndex := MainIntf.ImageList.AddMasked(Bmp, Bmp.Canvas.Pixels[0, Pixel]); end; end; // // Загрузка глифов для форм // for I := 0 to Pred(FComponentFormList.Count) do begin if TRegComponentFormDescr(FComponentFormList[I]).ImageIndex = IMG_FORM_SIMPLE then begin Bmp.Handle := LoadBitmap(Module, PChar('FORM_' + AnsiUpperCase(AnsiReplaceText(TRegComponentFormDescr(FComponentFormList[I]).CallString, ' ', '_')))); if Bmp.Handle <> 0 then TRegComponentFormDescr(FComponentFormList[I]).ImageIndex := MainIntf.ImageList.AddMasked(Bmp, Bmp.Canvas.Pixels[0, Pixel]); end; end; // // Загрузка глифов для акшенов // for I := 0 to Pred(MainForm.ActionList1.ActionCount) do begin if TAction(MainForm.ActionList1.Actions[I]).ImageIndex = IMG_DEFAULT then begin Bmp.Handle := LoadBitmap(Module, PChar(AnsiUpperCase(MainForm.ActionList1.Actions[I].ClassName))); if Bmp.Handle <> 0 then TAction(MainForm.ActionList1.Actions[I]).ImageIndex := MainIntf.ImageList.AddMasked(Bmp, Bmp.Canvas.Pixels[0, Pixel]); end; end; finally Bmp.Free; end; end; end; *) procedure TideBTRegistry.LoadOptionsFromFile; var I: Integer; f:string; begin f:=GetFilePath(SFileEnvironment); for I := 0 to Pred(FDemonList.Count) do if Supports(FDemonList[I], ISHComponentOptions) then ReadPropValuesFromFile(f, SSectionOptions, FDemonList[I]); end; procedure TideBTRegistry.SaveOptionsToFile; var I: Integer; f:string; PropNameValues:TStrings; begin f:=GetFilePath(SFileEnvironment); PropNameValues := TStringList.Create; try for I := 0 to Pred(FDemonList.Count) do if Supports(FDemonList[I], ISHComponentOptions) then GetPropValues(FDemonList[I], FDemonList[I].ClassName, PropNameValues); SaveStringsToFile(f, SSectionOptions, PropNameValues,True); finally FreeAndNil(PropNameValues); end; end; procedure TideBTRegistry.LoadOptionsFromList; var I: Integer; begin for I := 0 to Pred(FDemonList.Count) do if Supports(FDemonList[I], ISHComponentOptions) then SetPropValues(FDemonList[I], FDemonList[I].ClassName, FPropSavedList); end; procedure TideBTRegistry.SaveOptionsToList; var I: Integer; begin FPropSavedList.Clear; for I := 0 to Pred(FDemonList.Count) do if Supports(FDemonList[I], ISHComponentOptions) then GetPropValues(FDemonList[I], FDemonList[I].ClassName, FPropSavedList); end; procedure TideBTRegistry.LoadImagesFromFile; const FILE_EXT = '*.bmp'; var SearchRec: TSearchRec; FileAttrs: Integer; Bmp: TBitmap; Pixel: Integer; begin if SysUtils.DirectoryExists(GetDirPath(SDirImages)) then begin FileAttrs := 0; Bmp := TBitmap.Create; Pixel := 15; try if FindFirst(Format('%s%s', [GetDirPath(SDirImages), FILE_EXT]), FileAttrs, SearchRec) = 0 then begin repeat Bmp.LoadFromFile(Format('%s%s', [GetDirPath(SDirImages), SearchRec.Name])); if Bmp.Handle <> 0 then FImageFileList.AddObject(AnsiUpperCase(SearchRec.Name), TObject(MainIntf.ImageList.AddMasked(Bmp, Bmp.Canvas.Pixels[0, Pixel]))); until FindNext(SearchRec) <> 0; FindClose(SearchRec); end; finally Bmp.Free; end; end; end; end.
unit UHistory; interface uses UTypes; { Проверяет пуста ли история } function isEmptyList():Boolean; { Добавляет элемент в историю } procedure addHistoryItem(item: THistoryItem); { Добавляет элемент в конец истории } procedure addLastHistoryCell(cell: THistoryCell); { Очищает историю } procedure clearHistory(); { Возвращает последний элемент истории } function returnLastItem():THistoryItem; { Возвращает все записи в истории } function returnHistory():THistoryArray; { Возвращает и удаляет последний элемент истории } function pop():THistoryCell; implementation uses DateUtils; type { Список истории вычисленных выражений } THistoryList = ^THistoryListElem; THistoryListElem = record cell: THistoryCell; next: THistoryList; end; var list: THistoryList; lastCode: Integer = 0; { Проверяет пуст ли список } function isEmpty(list: THistoryList):Boolean; begin result := list^.next = nil; end; { Добавляет элемент в список } procedure insert(list: THistoryList; cell: THistoryCell); var temp: THistoryList; begin new(temp); temp^.cell := cell; temp^.next := list^.next; list^.next := temp; end; { Удаляет элемент из списка } procedure delete(list: THistoryList); var temp: THistoryList; begin temp := list^.next; list^.next := temp^.next; dispose(temp); end; { Возвращет конец списка истории } function findEnd(list: THistoryList):THistoryList; begin result := list; while not isEmpty(result) do result := result^.next; end; { Очищает список } procedure clearList(list: THistoryList); begin while not isEmpty(list) do delete(list); end; { Создаёт список } procedure createList(var list: THistoryList); begin new(list); list^.next := nil; end; { Разрушает список } procedure destroyList(var list: THistoryList); begin clearList(list); dispose(list); list := nil; end; { Проверяет пуста ли история } function isEmptyList():Boolean; begin result := isEmpty(list); end; { Добавляет элемент в историю } procedure addHistoryItem(item: THistoryItem); var tempCell: THistoryCell; begin inc(lastCode); tempCell.code := lastCode; tempCell.date := today; tempCell.item := item; insert(list, tempCell); end; { Добавляет элемент в конец истории } procedure addLastHistoryCell(cell: THistoryCell); begin if cell.code > lastCode then lastCode := cell.code; insert(findEnd(list), cell); end; { Очищает историю } procedure clearHistory(); begin clearList(list); end; { Возвращает последний элемент истории } function returnLastItem():THistoryItem; begin if list^.next <> nil then result := list^.next^.cell.item else result.operation := opNONE; end; { Возвращает все записи в истории } function returnHistory():THistoryArray; var temp: THistoryList; begin temp := list; SetLength(result, 0); while not isEmpty(temp) do begin SetLength(result, length(result) + 1); result[length(result) - 1] := temp^.next^.cell.item; temp := temp^.next; end; end; { Возвращает и удаляет последний элемент истории } function pop():THistoryCell; begin result := list^.next^.cell; delete(list); end; { При подключении модуля создаёт список } initialization createList(list); { При отключении модуля разрушает список } finalization destroyList(list); end.
unit HMAC; // Description: HMAC implementation // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // // This implementation conforms to the RFC2104 specification for HMAC, and may // be verified by the use of the test cases specificed in RFC2202 interface uses Classes, HashAlg_U, HashValue_U; type TMACValue = class(THashValue); // Generate HMAC function HMACString(const key: string; const data: string; const hashAlg: THashAlg; mac: TMACValue): boolean; function HMACFile(const key: string; const filename: string; const hashAlg: THashAlg; mac: TMACValue): boolean; // Note: This will operate from the *current* *position* in the stream, right // up to the end function HMACStream(const key: string; stream: TStream; const hashAlg: THashAlg; mac: TMACValue): boolean; implementation uses sysutils; // (Internal function only) // Pre-process the key ("K") to produce the key with appropriate length for use // in HMAC processing function _Determine_MAC_K(K: string; hashAlg: THashAlg): string; var retVal: string; hashValue: THashValue; begin if (Length(K) > (hashAlg.BlockLength div 8)) then begin hashValue:= THashValue.Create(); try if hashAlg.HashString(K, hashValue) then begin retVal := hashValue.ValueAsBinary; end; finally hashValue.Free(); end; end else begin retVal := K; end; // rfc2104 states that we should just use the hashlength bytes taken straight // from the hash - but the reference implementation right pads it if it's // less than the blocklength; so we do as well. if (Length(retVal) < (hashAlg.BlockLength div 8)) then begin retVal := retVal + StringOfChar( char(0), ((hashAlg.BlockLength div 8) - Length(retVal)) ); end; Result := retVal; end; // Generate HMAC for string data function HMACString(const key: string; const data: string; const hashAlg: THashAlg; mac: TMACValue): boolean; var stream: TStringStream; begin stream := TStringStream.Create(data); try Result := HMACStream(key, stream, hashAlg, mac); finally stream.Free(); end; end; // Generate HMAC for file function HMACFile(const key: string; const filename: string; const hashAlg: THashAlg; mac: TMACValue): boolean; var stream: TFileStream; begin Result := FALSE; try stream := TFileStream.Create(filename, fmOpenRead OR fmShareDenyWrite); try Result := HMACStream(key, stream, hashAlg, mac); finally stream.Free(); end; except // Nothing - Result already = FALSE end; end; // Generate HMAC for stream // !! IMPORTANT !! // Note: This will operate from the *current* *position* in the stream, right // up to the end function HMACStream(const key: string; stream: TStream; const hashAlg: THashAlg; mac: TMACValue): boolean; var i: integer; processedK: string; Ki: string; Ko: string; retVal: boolean; hv: THashValue; begin processedK := _Determine_MAC_K(key, hashAlg); Ki := ''; for i:=1 to length(processedK) do begin Ki := Ki + char(byte(processedK[i]) XOR $36); end; Ko := ''; for i:=1 to length(processedK) do begin Ko := Ko + char(byte(processedK[i]) XOR $5C); end; hv := THashValue.Create(); try // Outer... hashAlg.Init(); hashAlg.Update(Ki); hashAlg.Update(stream); hashAlg.Final(hv); // Inner... retVal := hashAlg.HashString(Ko + hv.ValueAsBinary, mac); finally hv.Free(); end; // Overwrite temp variables... processedK := StringOfChar(char(random(256)), length(processedK)); Ki := StringOfChar(char(random(256)), length(processedK)); Ko := StringOfChar(char(random(256)), length(processedK)); Result := retVal; end; END.
unit sgDriverSDL2Types; interface {$packrecords c} // // Types from sgBackendTypes.pas // type BytePtr = ^Byte; int = longint; pint = ^int; puint16 = ^uint16; float = single; pfloat = ^single; uint = longword; sg_drawing_surface_kind = ( SGDS_Unknown := 0, SGDS_Window := 1, SGDS_Bitmap := 2 ); sg_drawing_surface = record kind : sg_drawing_surface_kind; width : longint; height : longint; _data : pointer; end; sg_renderer_flip = ( SG_FLIP_NONE := 0, SG_FLIP_HORIZONTAL := 1, SG_FLIP_VERTICAL := 2, SG_FLIP_BOTH := 3 ); sg_mode = record format : uint; width : longint; height : longint; refresh_rate : longint; end; sg_display = record name : pchar; x : longint; y : longint; width : longint; height : longint; refresh_rate : longint; format: dword; num_modes : dword; modes : ^sg_mode; _data : pointer; end; sg_audiospec = record audio_rate : longint; audio_format : longint; audio_channels : longint; times_opened : longint; end; sg_system_data = record num_displays : dword; displays : ^sg_display; audio_specs : sg_audiospec; end; sg_font_kind = (SGFT_UNKNOWN := 0,SGFT_TTF := 1); sg_font_data = record kind : sg_font_kind; _data : pointer; end; sg_sound_kind = ( SGSD_UNKNOWN := 0, SGSD_SOUND_EFFECT := 1, SGSD_MUSIC := 2); sg_sound_data = record kind : sg_sound_kind; // test: longint; // test2: longint; _data : pointer; end; sg_window_data = record close_requested: Longint; has_focus: Longint; mouse_over: Longint; shown: Longint; end; sg_font_style = (SG_FONT_STYLE_NORMAL := 0,SG_FONT_STYLE_BOLD := 1, SG_FONT_STYLE_ITALIC := 2,SG_FONT_STYLE_UNDERLINE := 4, SG_FONT_STYLE_STRIKETHROUGH := 8); sg_connection_kind = ( SGCK_UNKNOWN = 0, SGCK_TCP = 1, SGCK_UDP = 2); sg_network_connection = record kind : sg_connection_kind; _socket: pointer; end; // // sgInterface types // type puint = ^uint; sg_color = record r : single; g : single; b : single; a : single; end; psg_system_data = ^sg_system_data; psg_drawing_surface = ^sg_drawing_surface; psg_font_data = ^sg_font_data; psg_sound_data = ^sg_sound_data; psg_interface = ^sg_interface; // // Function pointers // sg_empty_procedure = procedure(); cdecl; sg_charp_fn = function(): pchar; cdecl; sg_charp_proc = procedure(ttext: pchar); cdecl; sg_rectangle_dimensions_proc = procedure(x, y, w, h: int); cdecl; sg_drawing_surface_proc = procedure(surface: psg_drawing_surface); cdecl; sg_drawing_surface_bool_fn = function(surface: psg_drawing_surface): int; cdecl; sg_single_uint32param_proc = procedure(ms: uint); cdecl; sg_drawing_surface_clr_proc = procedure(surface: psg_drawing_surface; clr: sg_color); cdecl; sg_drawing_proc = procedure(surface: psg_drawing_surface; clr: sg_color;data: pfloat; data_sz: int); cdecl; sg_clip_proc = procedure(surface: psg_drawing_surface; data: pfloat; data_sz: int); cdecl; sg_surface_bool_proc = procedure(surface: psg_drawing_surface; val: int); cdecl; sg_to_pixel_array_proc = procedure(surface: psg_drawing_surface; pixels: pint; sz: int); cdecl; sg_surface_size_proc = procedure(surface: psg_drawing_surface; width, height: int); cdecl; sg_new_surface_fn = function(title: pchar; width, height: int): sg_drawing_surface; cdecl; sg_create_surface_fn = function(width, height: int): sg_drawing_surface; cdecl; sg_surface_color_fn = function(surface: psg_drawing_surface; x, y: int): sg_color; cdecl; sg_system_data_fn = function(): psg_system_data; cdecl; sg_drawing_surface_string_bool_fn = function(surface: psg_drawing_surface; filename: pchar): int; cdecl; // (surface, string) -> bool // // Text-related function pointers // sg_font_load_fn = function(filename: pchar; font_size: int): sg_font_data; cdecl; sg_font_data_proc = procedure(font: psg_font_data); cdecl; sg_font_int_fn = function(font: psg_font_data): int; cdecl; sg_font_int_proc = procedure(font: psg_font_data; style: int); cdecl; sg_font_size_fn = function(font: psg_font_data; ttext: pchar; w, h: pint): int; cdecl; sg_draw_text_proc = procedure(surface: psg_drawing_surface; font: psg_font_data; x, y: float; ttext: pchar; clr: sg_color); cdecl; // // Sound-related function pointers // sg_play_sound_fn = procedure(sound: psg_sound_data; loops: int; volume: float); cdecl; sg_sound_data_proc = procedure(sound: psg_sound_data); cdecl; sg_sound_float_fn = function(sound: psg_sound_data): float; cdecl; sg_sound_fade_proc = procedure(sound: psg_sound_data; loops, ms: int); cdecl; sg_sound_fade_out_proc = procedure(sound: psg_sound_data; ms: int); cdecl; sg_sound_float_proc = procedure(sound: psg_sound_data; val: float); cdecl; sg_intp_proc = procedure(ms: int); cdecl; sg_int_intp_proc = procedure(x, y: int); cdecl; sg_floatp_proc = procedure(val: float); cdecl; sg_float_fn = function(): float; cdecl; sg_int_intp_fn = function(val: int): int; cdecl; sg_float_soundp_fn = function(sound: psg_sound_data): float; cdecl; sg_sound_load_fn = function(name: PChar; kind: sg_sound_kind): sg_sound_data; cdecl; sg_sound_fn = function() : psg_sound_data; // // Utility related // sg_uint_fn = function(): uint; cdecl; // // Image related // sg_load_surface_fn = function(title: pchar): sg_drawing_surface; cdecl; sg_drawing_surface_surface_proc = procedure(src, dst: psg_drawing_surface; src_data: pfloat; src_data_sz: int; dst_data: pfloat; dst_data_sz:int; flip: sg_renderer_flip ); cdecl; // // Network related // psg_network_connection = ^sg_network_connection; sg_create_network_fn = function(host: pchar; port: uint16): sg_network_connection; cdecl; sg_create_udp_network_fn = function(port: uint16): sg_network_connection; cdecl; sg_network_data_fn = function(connection: psg_network_connection; buffer: BytePtr; size: Longint): Longint; cdecl; sg_connection_fn = procedure (connection: psg_network_connection); cdecl; sg_connection_uint_fn = function (connection: psg_network_connection): uint; cdecl; sg_accept_connection_fn = function (connection: psg_network_connection): sg_network_connection; cdecl; sg_udp_send_fn = function (con: psg_network_connection; host: pchar; port: uint16; buffer: pchar; size: LongInt): LongInt; cdecl; sg_read_udp_fn = procedure (con: psg_network_connection; host: puint; port: puint16; buffer: pchar; size: puint); cdecl; // // Input related // sg_mouse_state_fn = function(x, y: pint): uint; cdecl; sg_window_pos_fn = procedure (surface: psg_drawing_surface; x, y: pint); cdecl; sg_surface_xy_proc = procedure(surface: psg_drawing_surface; x, y: int); cdecl; pointer_fn = function (): pointer; cdecl; sg_window_xy_proc = procedure(window: pointer; x, y: Longint); cdecl; sg_window_data_fn = function(surface: psg_drawing_surface): sg_window_data; cdecl; sg_utils_interface = record delay : sg_single_uint32param_proc; get_ticks : sg_uint_fn; end; sg_image_interface = record create_bitmap : sg_create_surface_fn; load_bitmap : sg_load_surface_fn; draw_bitmap : sg_drawing_surface_surface_proc; end; sg_audio_interface = record open_audio : sg_empty_procedure; close_audio : sg_empty_procedure; load_sound_data : sg_sound_load_fn; close_sound_data : sg_sound_data_proc; play_sound : sg_play_sound_fn; sound_playing : sg_sound_float_fn; fade_in : sg_sound_fade_proc; fade_out : sg_sound_fade_out_proc; fade_music_out : sg_intp_proc; fade_all_sound_effects_out : sg_intp_proc; set_music_vol : sg_floatp_proc; music_vol : sg_float_fn; sound_volume : sg_float_soundp_fn; set_sound_volume : sg_sound_float_proc; pause_music : sg_empty_procedure; resume_music : sg_empty_procedure; stop_music : sg_empty_procedure; stop_sound : sg_sound_data_proc; music_playing : sg_float_fn; current_music : sg_sound_fn; end; sg_graphics_interface = record open_window : sg_new_surface_fn; close_drawing_surface : sg_drawing_surface_proc; refresh_window : sg_drawing_surface_proc; clear_drawing_surface : sg_drawing_surface_clr_proc; draw_aabb_rect : sg_drawing_proc; fill_aabb_rect : sg_drawing_proc; draw_rect : sg_drawing_proc; fill_rect : sg_drawing_proc; draw_triangle : sg_drawing_proc; fill_triangle : sg_drawing_proc; draw_circle : sg_drawing_proc; fill_circle : sg_drawing_proc; draw_ellipse : sg_drawing_proc; fill_ellipse : sg_drawing_proc; draw_pixel : sg_drawing_proc; draw_line : sg_drawing_proc; read_pixel : sg_surface_color_fn; set_clip_rect : sg_clip_proc; clear_clip_rect : sg_drawing_surface_proc; to_pixels : sg_to_pixel_array_proc; show_border : sg_surface_bool_proc; show_fullscreen : sg_surface_bool_proc; resize : sg_surface_size_proc; save_png: sg_drawing_surface_string_bool_fn; end; sg_input_callbacks = record do_quit : sg_empty_procedure; handle_key_down : sg_intp_proc; handle_key_up : sg_intp_proc; handle_mouse_up : sg_intp_proc; handle_mouse_down : sg_intp_proc; handle_mouse_wheel : sg_int_intp_proc; handle_input_text : sg_charp_proc; handle_window_resize: sg_window_xy_proc; handle_window_move: sg_window_xy_proc; end; sg_input_interface = record process_events : sg_empty_procedure; window_close_requested : sg_drawing_surface_bool_fn; key_pressed : sg_int_intp_fn; mouse_state : sg_mouse_state_fn; mouse_relative_state : sg_mouse_state_fn; mouse_cursor_state : sg_int_intp_fn; warp_mouse : sg_surface_xy_proc; start_unicode_text_input : sg_rectangle_dimensions_proc; stop_unicode_text_input : sg_empty_procedure; focus_window: pointer_fn; window_position: sg_window_pos_fn; get_window_event_data: sg_window_data_fn; move_window: sg_surface_xy_proc; end; sg_text_interface = record load_font : sg_font_load_fn; close_font : sg_font_data_proc; text_line_skip : sg_font_int_fn; text_size : sg_font_size_fn; get_font_style : sg_font_int_fn; set_font_style : sg_font_int_proc; draw_text : sg_draw_text_proc; end; sg_network_interface = record open_tcp_connection: sg_create_network_fn; open_udp_connection: sg_create_udp_network_fn; read_bytes: sg_network_data_fn; send_bytes: sg_network_data_fn; close_connection: sg_connection_fn; network_address: sg_connection_uint_fn; network_port: sg_connection_uint_fn; accept_new_connection: sg_accept_connection_fn; network_has_data: sg_uint_fn; connection_has_data: sg_connection_uint_fn; send_udp_message: sg_udp_send_fn; read_udp_message: sg_read_udp_fn; end; (* Const before type ignored *) sg_http_method = ( HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_DELETE ); sg_http_request = record request_type: sg_http_method; url: PChar; port: Word; body: PChar; end; sg_http_response = record status: Word; size: uint; data: PChar; end; psg_http_response = ^sg_http_response; sg_http_request_fn = function (request: sg_http_request): sg_http_response; cdecl; sg_free_response_fn = procedure (response: psg_http_response); cdecl; sg_web_interface = record http_request: sg_http_request_fn; free_response: sg_free_response_fn; end; sg_interface = record has_error : longint; current_error : ^char; init : sg_empty_procedure; finalise : sg_empty_procedure; audio : sg_audio_interface; graphics : sg_graphics_interface; image : sg_image_interface; input : sg_input_interface; text : sg_text_interface; utils : sg_utils_interface; network : sg_network_interface; web : sg_web_interface; input_callbacks : sg_input_callbacks; read_system_data : sg_system_data_fn; end; function sg_load(callbacks: sg_input_callbacks): psg_interface; cdecl; external 'libsgsdl2'; var _sg_functions: ^sg_interface; function _ToSGColor(clr: Longint) : sg_color; const SDLK_RETURN = $D; SDLK_ESCAPE = $1B; SDLK_BACKSPACE = $8; SDLK_TAB = $9; SDLK_SPACE = Ord(' '); SDLK_EXCLAIM = Ord('!'); SDLK_QUOTEDBL = Ord('"'); SDLK_HASH = Ord('#'); SDLK_DOLLAR = Ord('$'); SDLK_PERCENT = Ord('%'); SDLK_AMPERSAND = Ord('&'); SDLK_QUOTE = Ord(''''); SDLK_LEFTPAREN = Ord('('); SDLK_RIGHTPAREN = Ord(')'); SDLK_ASTERISK = Ord('*'); SDLK_PLUS = Ord('+'); SDLK_COMMA = Ord(','); SDLK_MINUS = Ord('-'); SDLK_PERIOD = Ord('.'); SDLK_SLASH = Ord('/'); SDLK_0 = Ord('0'); SDLK_1 = Ord('1'); SDLK_2 = Ord('2'); SDLK_3 = Ord('3'); SDLK_4 = Ord('4'); SDLK_5 = Ord('5'); SDLK_6 = Ord('6'); SDLK_7 = Ord('7'); SDLK_8 = Ord('8'); SDLK_9 = Ord('9'); SDLK_COLON = Ord(':'); SDLK_SEMICOLON = Ord(';'); SDLK_LESS = Ord('<'); SDLK_EQUALS = Ord('='); SDLK_GREATER = Ord('>'); SDLK_QUESTION = Ord('?'); SDLK_AT = Ord('@'); SDLK_LEFTBRACKET = Ord('['); SDLK_BACKSLASH = Ord('\'); SDLK_RIGHTBRACKET = Ord(']'); SDLK_CARET = Ord('^'); SDLK_UNDERSCORE = Ord('_'); SDLK_BACKQUOTE = Ord('`'); SDLK_a = Ord('a'); SDLK_b = Ord('b'); SDLK_c = Ord('c'); SDLK_d = Ord('d'); SDLK_e = Ord('e'); SDLK_f = Ord('f'); SDLK_g = Ord('g'); SDLK_h = Ord('h'); SDLK_i = Ord('i'); SDLK_j = Ord('j'); SDLK_k = Ord('k'); SDLK_l = Ord('l'); SDLK_m = Ord('m'); SDLK_n = Ord('n'); SDLK_o = Ord('o'); SDLK_p = Ord('p'); SDLK_q = Ord('q'); SDLK_r = Ord('r'); SDLK_s = Ord('s'); SDLK_t = Ord('t'); SDLK_u = Ord('u'); SDLK_v = Ord('v'); SDLK_w = Ord('w'); SDLK_x = Ord('x'); SDLK_y = Ord('y'); SDLK_z = Ord('z'); SDLK_CAPSLOCK = $40000039; SDLK_F1 = $4000003A; SDLK_F2 = $4000003B; SDLK_F3 = $4000003C; SDLK_F4 = $4000003D; SDLK_F5 = $4000003E; SDLK_F6 = $4000003F; SDLK_F7 = $40000040; SDLK_F8 = $40000041; SDLK_F9 = $40000042; SDLK_F10 = $40000043; SDLK_F11 = $40000044; SDLK_F12 = $40000045; SDLK_PRINTSCREEN = $40000046; SDLK_SCROLLLOCK = $40000047; SDLK_PAUSE = $40000048; SDLK_INSERT = $40000049; SDLK_HOME = $4000004A; SDLK_PAGEUP = $4000004B; SDLK_DELETE = $7F; SDLK_END = $4000004D; SDLK_PAGEDOWN = $4000004E; SDLK_RIGHT = $4000004F; SDLK_LEFT = $40000050; SDLK_DOWN = $40000051; SDLK_UP = $40000052; SDLK_NUMLOCKCLEAR = $40000053; SDLK_KP_DIVIDE = $40000054; SDLK_KP_MULTIPLY = $40000055; SDLK_KP_MINUS = $40000056; SDLK_KP_PLUS = $40000057; SDLK_KP_ENTER = $40000058; SDLK_KP_1 = $40000059; SDLK_KP_2 = $4000005A; SDLK_KP_3 = $4000005B; SDLK_KP_4 = $4000005C; SDLK_KP_5 = $4000005D; SDLK_KP_6 = $4000005E; SDLK_KP_7 = $4000005F; SDLK_KP_8 = $40000060; SDLK_KP_9 = $40000061; SDLK_KP_0 = $40000062; SDLK_KP_PERIOD = $40000063; SDLK_APPLICATION = $40000065; SDLK_POWER = $40000066; SDLK_KP_EQUALS = $40000067; SDLK_F13 = $40000068; SDLK_F14 = $40000069; SDLK_F15 = $4000006A; SDLK_F16 = $4000006B; SDLK_F17 = $4000006C; SDLK_F18 = $4000006D; SDLK_F19 = $4000006E; SDLK_F20 = $4000006F; SDLK_F21 = $40000070; SDLK_F22 = $40000071; SDLK_F23 = $40000072; SDLK_F24 = $40000073; SDLK_EXECUTE = $40000074; SDLK_HELP = $40000075; SDLK_MENU = $40000076; SDLK_SELECT = $40000077; SDLK_STOP = $40000078; SDLK_AGAIN = $40000079; SDLK_UNDO = $4000007A; SDLK_CUT = $4000007B; SDLK_COPY = $4000007C; SDLK_PASTE = $4000007D; SDLK_FIND = $4000007E; SDLK_MUTE = $4000007F; SDLK_VOLUMEUP = $40000080; SDLK_VOLUMEDOWN = $40000081; SDLK_KP_COMMA = $40000085; SDLK_KP_EQUALSAS400 = $40000086; SDLK_ALTERASE = $40000099; SDLK_SYSREQ = $4000009A; SDLK_CANCEL = $4000009B; SDLK_CLEAR = $4000009C; SDLK_PRIOR = $4000009D; SDLK_RETURN2 = $4000009E; SDLK_SEPARATOR = $4000009F; SDLK_OUT = $400000A0; SDLK_OPER = $400000A1; SDLK_CLEARAGAIN = $400000A2; SDLK_CRSEL = $400000A3; SDLK_EXSEL = $400000A4; SDLK_KP_00 = $400000B0; SDLK_KP_000 = $400000B1; SDLK_THOUSANDSSEPARATOR = $400000B2; SDLK_DECIMALSEPARATOR = $400000B3; SDLK_CURRENCYUNIT = $400000B4; SDLK_CURRENCYSUBUNIT = $400000B5; SDLK_KP_LEFTPAREN = $400000B6; SDLK_KP_RIGHTPAREN = $400000B7; SDLK_KP_LEFTBRACE = $400000B8; SDLK_KP_RIGHTBRACE = $400000B9; SDLK_KP_TAB = $400000BA; SDLK_KP_BACKSPACE = $400000BB; SDLK_KP_A = $400000BC; SDLK_KP_B = $400000BD; SDLK_KP_C = $400000BE; SDLK_KP_D = $400000BF; SDLK_KP_E = $400000C0; SDLK_KP_F = $400000C1; SDLK_KP_XOR = $400000C2; SDLK_KP_POWER = $400000C3; SDLK_KP_PERCENT = $400000C4; SDLK_KP_LESS = $400000C5; SDLK_KP_GREATER = $400000C6; SDLK_KP_AMPERSAND = $400000C7; SDLK_KP_DBLAMPERSAND = $400000C8; SDLK_KP_VERTICALBAR = $400000C9; SDLK_KP_DBLVERTICALBAR = $400000CA; SDLK_KP_COLON = $400000CB; SDLK_KP_HASH = $400000CC; SDLK_KP_SPACE = $400000CD; SDLK_KP_AT = $400000CE; SDLK_KP_EXCLAM = $400000CF; SDLK_KP_MEMSTORE = $400000D0; SDLK_KP_MEMRECALL = $400000D1; SDLK_KP_MEMCLEAR = $400000D2; SDLK_KP_MEMADD = $400000D3; SDLK_KP_MEMSUBTRACT = $400000D4; SDLK_KP_MEMMULTIPLY = $400000D5; SDLK_KP_MEMDIVIDE = $400000D6; SDLK_KP_PLUSMINUS = $400000D7; SDLK_KP_CLEAR = $400000D8; SDLK_KP_CLEARENTRY = $400000D9; SDLK_KP_BINARY = $400000DA; SDLK_KP_OCTAL = $400000DB; SDLK_KP_DECIMAL = $400000DC; SDLK_KP_HEXADECIMAL = $400000DD; SDLK_LCTRL = $400000E0; SDLK_LSHIFT = $400000E1; SDLK_LALT = $400000E2; SDLK_LGUI = $400000E3; SDLK_RCTRL = $400000E4; SDLK_RSHIFT = $400000E5; SDLK_RALT = $400000E6; SDLK_RGUI = $400000E7; SDLK_MODE = $40000101; SDLK_AUDIONEXT = $40000102; SDLK_AUDIOPREV = $40000103; SDLK_AUDIOSTOP = $40000104; SDLK_AUDIOPLAY = $40000105; SDLK_AUDIOMUTE = $40000106; SDLK_MEDIASELECT = $40000107; SDLK_WWW = $40000108; SDLK_MAIL = $40000109; SDLK_CALCULATOR = $4000010A; SDLK_COMPUTER = $4000010B; SDLK_AC_SEARCH = $4000010C; SDLK_AC_HOME = $4000010D; SDLK_AC_BACK = $4000010E; SDLK_AC_FORWARD = $4000010F; SDLK_AC_STOP = $40000110; SDLK_AC_REFRESH = $40000111; SDLK_AC_BOOKMARKS = $40000112; SDLK_BRIGHTNESSDOWN = $40000113; SDLK_BRIGHTNESSUP = $40000114; SDLK_DISPLAYSWITCH = $40000115; SDLK_KBDILLUMTOGGLE = $40000116; SDLK_KBDILLUMDOWN = $40000117; SDLK_KBDILLUMUP = $40000118; SDLK_EJECT = $40000119; SDLK_SLEEP = $4000011A; implementation function _ToSGColor(clr: Longint) : sg_color; begin result.a := ((clr and $ff000000) shr 24) / 255.0; result.r := ((clr and $00ff0000) shr 16) / 255.0; result.g := ((clr and $0000ff00) shr 8) / 255.0; result.b := ((clr and $000000ff) ) / 255.0; end; end.
{ *************************************************************************** Copyright (c) 2016-2021 Kike Pérez Unit : Quick.Logger.Provider.InfluxDB Description : Log Api InfluxDB Provider Author : Kike Pérez Version : 1.1 Created : 25/02/2019 Modified : 20/04/2021 This file is part of QuickLogger: https://github.com/exilon/QuickLogger *************************************************************************** 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.Logger.Provider.InfluxDB; {$i QuickLib.inc} interface uses Classes, SysUtils, DateUtils, Quick.HttpClient, Quick.Commons, Quick.Logger; type TLogInfluxDBProvider = class (TLogProviderBase) private fHTTPClient : TJsonHTTPClient; fURL : string; fFullURL : string; fDataBase : string; fUserName : string; fPassword : string; fUserAgent : string; fIncludedTags : TIncludedLogInfo; fCreateDataBaseIfNotExists : Boolean; procedure CreateDataBase; function LogItemToLine(cLogItem: TLogItem): string; procedure SetWriteURL; procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); public constructor Create; override; destructor Destroy; override; property URL : string read fURL write fURL; property DataBase : string read fDataBase write fDataBase; property UserName : string read fUserName write SetUserName; property Password : string read fPassword write SetPassword; property CreateDataBaseIfNotExists : Boolean read fCreateDataBaseIfNotExists write fCreateDataBaseIfNotExists; property UserAgent : string read fUserAgent write fUserAgent; property IncludedTags : TIncludedLogInfo read fIncludedTags write fIncludedTags; property JsonOutputOptions : TJsonOutputOptions read fJsonOutputOptions write fJsonOutputOptions; procedure Init; override; procedure Restart; override; procedure WriteLog(cLogItem : TLogItem); override; end; var GlobalLogInfluxDBProvider : TLogInfluxDBProvider; implementation constructor TLogInfluxDBProvider.Create; begin inherited; LogLevel := LOG_ALL; fURL := 'http://localhost:8086'; fDataBase := 'logger'; fUserName := ''; fPassword := ''; fCreateDataBaseIfNotExists := True; fJsonOutputOptions.UseUTCTime := True; fUserAgent := DEF_USER_AGENT; fIncludedTags := [iiAppName,iiHost,iiEnvironment]; IncludedInfo := [iiAppName,iiHost,iiEnvironment]; end; destructor TLogInfluxDBProvider.Destroy; begin if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); inherited; end; procedure TLogInfluxDBProvider.Init; begin SetWriteURL; fHTTPClient := TJsonHTTPClient.Create; fHTTPClient.ContentType := 'application/json'; fHTTPClient.UserAgent := fUserAgent; fHTTPClient.HandleRedirects := True; if fCreateDataBaseIfNotExists then CreateDataBase; inherited; end; procedure TLogInfluxDBProvider.Restart; begin Stop; if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); Init; end; procedure TLogInfluxDBProvider.SetPassword(const Value: string); begin if fPassword <> Value then begin fPassword := Value; SetWriteURL; end; end; procedure TLogInfluxDBProvider.SetWriteURL; begin if fUserName+fPassword <> '' then fFullURL := Format('%s/write?db=%s&u=%s&p=%s&precision=ms',[fURL,fDataBase,fUserName,fPassword]) else fFullURL := Format('%s/write?db=%s&precision=ms',[fURL,fDataBase]); end; procedure TLogInfluxDBProvider.SetUserName(const Value: string); begin if fUserName <> Value then begin fUserName := Value; SetWriteURL; end; end; procedure TLogInfluxDBProvider.CreateDataBase; var resp : IHttpRequestResponse; begin if fUserName+fPassword <> '' then resp := fHTTPClient.Post(Format('%s/query?q=CREATE DATABASE %s&u=%s&p=%s',[fURL,fDatabase,fUserName,fPassword]),'') else resp := fHTTPClient.Post(Format('%s/query?q=CREATE DATABASE %s',[fURL,fDatabase]),''); if not (resp.StatusCode in [200,204]) then raise ELogger.Create(Format('[TLogInfluxDBProvider] : Response %d : %s trying to create database',[resp.StatusCode,resp.StatusText])); end; function TLogInfluxDBProvider.LogItemToLine(cLogItem: TLogItem): string; var incinfo : TStringList; tags : string; fields : string; begin incinfo := TStringList.Create; try incinfo.Add(Format('type=%s',[EventTypeName[cLogItem.EventType]])); if iiAppName in fIncludedTags then incinfo.Add(Format('application=%s',[SystemInfo.AppName])); if iiHost in fIncludedTags then incinfo.Add(Format('host=%s',[SystemInfo.HostName])); if iiUserName in fIncludedTags then incinfo.Add(Format('user=%s',[SystemInfo.UserName])); if iiOSVersion in fIncludedTags then incinfo.Add(Format('os=%s',[SystemInfo.OsVersion])); if iiEnvironment in fIncludedTags then incinfo.Add(Format('environment=%s',[Environment])); if iiPlatform in fIncludedTags then incinfo.Add(Format('platform=%s',[PlatformInfo])); if iiThreadId in fIncludedTags then incinfo.Add(Format('treadid=%s',[cLogItem.ThreadId])); if iiProcessId in fIncludedTags then incinfo.Add(Format('processid=%s',[SystemInfo.ProcessId])); tags := CommaText(incinfo); incinfo.Clear; incinfo.Add(Format('type="%s"',[EventTypeName[cLogItem.EventType]])); if iiAppName in IncludedInfo then incinfo.Add(Format('application="%s"',[SystemInfo.AppName])); if iiHost in IncludedInfo then incinfo.Add(Format('host="%s"',[SystemInfo.HostName])); if iiUserName in IncludedInfo then incinfo.Add(Format('user="%s"',[SystemInfo.UserName])); if iiOSVersion in IncludedInfo then incinfo.Add(Format('os="%s"',[SystemInfo.OsVersion])); if iiEnvironment in IncludedInfo then incinfo.Add(Format('environment="%s"',[Environment])); if iiPlatform in IncludedInfo then incinfo.Add(Format('platform="%s"',[PlatformInfo])); if iiThreadId in IncludedInfo then incinfo.Add(Format('treadid=%s',[cLogItem.ThreadId])); if iiProcessId in IncludedInfo then incinfo.Add(Format('processid=%s',[SystemInfo.ProcessId])); incinfo.Add(Format('message="%s"',[cLogItem.Msg])); fields := CommaText(incinfo); {$IFDEF DELPHIXE7_UP} Result := Format('logger,%s %s %d',[tags,fields,DateTimeToUnix(LocalTimeToUTC(cLogItem.EventDate),True)*1000]); {$ELSE} Result := Format('logger,%s %s %d',[tags,fields,DateTimeToUnix(LocalTimeToUTC(cLogItem.EventDate))*1000]); {$ENDIF} finally incinfo.Free; end; end; procedure TLogInfluxDBProvider.WriteLog(cLogItem : TLogItem); var resp : IHttpRequestResponse; stream : TStringStream; begin stream := TStringStream.Create(LogItemToLine(cLogItem)); try resp := fHTTPClient.Post(fFullURL,stream); finally stream.Free; end; if not (resp.StatusCode in [200,204]) then raise ELogger.Create(Format('[TLogInfluxDBProvider] : Response %d : %s trying to post event',[resp.StatusCode,resp.StatusText])); end; initialization GlobalLogInfluxDBProvider := TLogInfluxDBProvider.Create; finalization if Assigned(GlobalLogInfluxDBProvider) and (GlobalLogInfluxDBProvider.RefCount = 0) then GlobalLogInfluxDBProvider.Free; end.
{$B-} {$mode delphi} unit pasfunc; interface uses SysUtils, Math, PasCalc, Variants; procedure SetFunctions(PC : TPasCalc); implementation function VarIsString(V : TVar) : boolean; var t: integer; begin t := VarType(V.Value); Result := (t=varString) or (t=varOleStr); end; function fFloatToStr(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var s : string; x: float; begin Result := false; if A.Count<>1 then Exit; x := TPVar(A.Items[0])^.Value; Str(x:0:15,s); while s[Length(s)]='0' do s := copy(s,1,Length(s)-1); if s[Length(s)]='.' then s := copy(s,1,Length(s)-1); R.Value := s; Result := true; end; function fIntToStr(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var i : integer; s : string; begin Result := fFloatToStr(Sender,A,R); if Result then begin s := string(R.Value); i := Pos('.',s); if i>0 then R.Value := copy(s,1,i-1); end; end; function fStrToFloat(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var i : integer; x : extended; begin Result := false; if A.Count<>1 then Exit; Val(Trim(TPVar(A.Items[0])^.Value),x,i); if i<>0 then Exit; R.value := x; Result := true; end; function fStrToInt(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var i : integer; begin Result := false; if A.Count<>1 then Exit; i := StrToInt(TPVar(A.Items[0])^.Value); R.value := i; Result := true; end; function fVal(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var x : extended; i : integer; begin Result := false; if (A.Count<>3) or (TPVar(A.Items[1])^.Name<>'VAR') or (TPVar(A.Items[2])^.Name<>'VAR') then Exit; Val(TPVar(A.Items[0])^.Value,x,i); TPVar(A.Items[1])^.Value := x; TPVar(A.Items[2])^.Value := i; Result := true; end; function fCopy(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>3 then Exit; R.Value := copy(TPVar(A.Items[0])^.Value, Trunc(TPVar(A.Items[1])^.Value), Trunc(TPVar(A.Items[2])^.Value)); Result := true; end; function fPos(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>2 then Exit; R.Value := Pos(TPVar(A.Items[0])^.Value, TPVar(A.Items[1])^.Value); Result := true; end; function fLength(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Length(TPVar(A.Items[0])^.Value); Result := true; end; function fInsert(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var s : widestring; begin Result := false; if (A.Count<>3) or (TPVar(A.Items[1])^.Name<>'VAR') then Exit; s := TPVar(A.Items[1])^.Value; Insert(TPVar(A.Items[0])^.Value,s,Trunc(TPVar(A.Items[1])^.Value)); TPVar(A.Items[1])^.Value := s; R.Value := s; Result := true; end; function fDelete(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var s : string; begin Result := false; if (A.Count<>3) or (TPVar(A.Items[0])^.Name<>'VAR') then Exit; s := TPVar(A.Items[0])^.Value; Delete(s,Trunc(TPVar(A.Items[1])^.Value),Trunc(TPVar(A.Items[1])^.Value)); TPVar(A.Items[0])^.Value := s; R.Value := s; Result := true; end; function fTrim(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Trim(TPVar(A.Items[0])^.Value); Result := true; end; function fTrimLeft(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := TrimLeft(TPVar(A.Items[0])^.Value); Result := true; end; function fTrimRight(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; Result := true; R.Value := TrimRight(TPVar(A.Items[0])^.Value); end; function fUpperCase(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; Result := true; R.Value := AnsiUpperCase(TPVar(A.Items[0])^.Value); end; function fLowerCase(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; Result := true; R.Value := AnsiLowerCase(TPVar(A.Items[0])^.Value); end; function fFormat(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var i,n : integer; ff : boolean; fs,s,fmt : string; begin Result := false; if (A.Count<2) then Exit; Result := true; s:=''; fmt:=''; ff:=false; n:=0; fs := TPVar(A.Items[0])^.Value; for i := 1 to Length(fs) do begin if fs[i]='%' then ff := true; if ff then fmt := fmt + fs[i] else s := s + fs[i]; if ff and (fs[i] in ['A'..'Z','a'..'z']) then begin ff := false; inc(n); if n<A.Count then begin if not VarIsString(TPVar(A.Items[n])^) then begin try s := s + Format(fmt,[TPVar(A.Items[n])^.Value]); except s := s + Format(fmt,[Trunc(TPVar(A.Items[n])^.Value)]); end; end else s := s + Format(fmt,[TPVar(A.Items[n])^.Value]); end; fmt := ''; end; end; R.Value := s+fmt; end; function fDateToStr(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := DateToStr(TPVar(A.Items[0])^.Value); Result := true; end; function fStrToDate(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := StrToDate(TPVar(A.Items[0])^.Value); Result := true; end; function fFormatDateTime(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>2 then Exit; R.Value := FormatDateTime(TPVar(A.Items[0])^.Value, TPVar(A.Items[1])^.Value); Result := true; end; function fNow(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>0 then Exit; Result := true; R.Value := Now; end; function fDate(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>0 then Exit; Result := true; R.Value := Date; end; function fTime(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>0 then Exit; Result := true; R.Value := Time; end; function fStrToTime(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := StrToTime(TPVar(A.Items[0])^.Value); Result := true; end; function fTimeToStr(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := TimeToStr(TPVar(A.Items[0])^.Value); Result := true; end; function fDayOfWeek(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; Result := true; R.Value := DayOfWeek(TPVar(A.Items[0])^.Value); end; function fIncMonth(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>2 then Exit; R.Value := IncMonth(TPVar(A.Items[0])^.Value,Trunc(TPVar(A.Items[1])^.Value)); Result := true; end; function fDecodeDate(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var i : integer; D,M,Y : word; begin Result := false; if A.Count<>4 then Exit; for i := 1 to 3 do if TPVar(A.Items[i])^.Name<>'VAR' then Exit; DecodeDate(TPVar(A.Items[0])^.Value,Y,M,D); TPVar(A.Items[1])^.Value := Y; TPVar(A.Items[2])^.Value := M; TPVar(A.Items[3])^.Value := D; R.Value := TPVar(A.Items[0])^.Value; Result := true; end; function fDecodeTime(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var i : integer; H,M,S,MS : word; begin Result := false; if A.Count<>5 then Exit; for i := 1 to 4 do if TPVar(A.Items[i])^.Name<>'VAR' then Exit; DecodeTime(TPVar(A.Items[0])^.Value,H,M,S,MS); TPVar(A.Items[1])^.Value := H; TPVar(A.Items[2])^.Value := M; TPVar(A.Items[3])^.Value := S; TPVar(A.Items[4])^.Value := MS; R.Value := TPVar(A.Items[0])^.Value; Result := true; end; function fEncodeDate(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>3 then Exit; R.Value := EncodeDate(Trunc(TPVar(A.Items[0])^.Value), Trunc(TPVar(A.Items[1])^.Value), Trunc(TPVar(A.Items[2])^.Value)); Result := true; end; function fEncodeTime(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>4 then Exit; R.Value := EncodeTime(Trunc(TPVar(A.Items[0])^.Value), Trunc(TPVar(A.Items[1])^.Value), Trunc(TPVar(A.Items[2])^.Value), Trunc(TPVar(A.Items[3])^.Value)); Result := true; end; function fSin(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Sin(TPVar(A.Items[0])^.Value); Result := true; end; function fCos(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Cos(TPVar(A.Items[0])^.Value); Result := true; end; function fTan(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Tan(TPVar(A.Items[0])^.Value); Result := true; end; function fArcSin(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := ArcSin(TPVar(A.Items[0])^.Value); Result := true; end; function fArcCos(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := ArcCos(TPVar(A.Items[0])^.Value); Result := true; end; function fArcTan(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := ArcTan(TPVar(A.Items[0])^.Value); Result := true; end; function fExp(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Exp(TPVar(A.Items[0])^.Value); Result := true; end; function fLn(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Ln(TPVar(A.Items[0])^.Value); Result := true; end; function fIntPower(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>2 then Exit; R.Value := IntPower(TPVar(A.Items[0])^.Value,Trunc(TPVar(A.Items[1])^.Value)); Result := true; end; function fSqr(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Sqr(TPVar(A.Items[0])^.Value); Result := true; end; function fSqrt(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Sqrt(TPVar(A.Items[0])^.Value); Result := true; end; function fAbs(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Abs(TPVar(A.Items[0])^.Value); Result := true; end; function fInt(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Int(TPVar(A.Items[0])^.Value); Result := true; end; function fFrac(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Frac(TPVar(A.Items[0])^.Value); Result := true; end; function fRound(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Integer(Round(TPVar(A.Items[0])^.Value)); Result := true; end; function fTrunc(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Integer(Trunc(TPVar(A.Items[0])^.Value)); Result := true; end; function fCeil(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Ceil(TPVar(A.Items[0])^.Value); Result := true; end; function fFloor(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if A.Count<>1 then Exit; R.Value := Floor(TPVar(A.Items[0])^.Value); Result := true; end; function fMax(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var i : integer; N : string; begin Result := false; if A.Count=0 then Exit; N := R.Name; R := TPVar(A.Items[0])^; R.Name := N; for i:=0 to A.Count-1 do begin if VarType(R.Value)<>VarType(TPVar(A.Items[i])^.Value) then Exit; if TPVar(A.Items[i])^.Value>R.Value then R.Value := TPVar(A.Items[i])^.Value; end; Result := true; end; function fMin(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var i : integer; N : string; begin Result := false; if A.Count=0 then Exit; N := R.Name; R := TPVar(A.Items[0])^; R.Name := N; for i:=0 to A.Count-1 do begin if VarType(R.Value)<>VarType(TPVar(A.Items[i])^.Value) then Exit; if TPVar(A.Items[i])^.Value<R.Value then R.Value := TPVar(A.Items[i])^.Value; end; Result := true; end; function fInc(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if (A.Count<1) or (A.Count>2) then Exit; if A.Count=1 then TPVar(A.Items[0])^.Value:=TPVar(A.Items[0])^.Value+1 else TPVar(A.Items[0])^.Value:=TPVar(A.Items[0])^.Value+TPVar(A.Items[1])^.Value; Result:=true; end; function fDec(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin Result := false; if (A.Count<1) or (A.Count>2) then Exit; if A.Count=1 then TPVar(A.Items[0])^.Value:=TPVar(A.Items[0])^.Value-1 else TPVar(A.Items[0])^.Value:=TPVar(A.Items[0])^.Value-TPVar(A.Items[1])^.Value; Result:=true; end; function fSetVar(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var s : string; begin // Set simple variable (not array) value Result := false; if A.Count<>2 then Exit; s := AnsiUpperCase(TPVar(A.Items[0])^.Value); Result := (Sender as TPasCalc).SetValue(s,TPVar(A.Items[1])^.Value); end; function fGetVar(Sender:TObject; var A:TVarList; var R:TVar) : boolean; begin // Get variable value Result := false; if (A.Count<>1) then Exit; Result := (Sender as TPasCalc).VarByName(AnsiUpperCase(TPVar(A.Items[0])^.Value),R); end; function fDecode(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var i : integer; N : string; X : TVar; begin Result := false; if A.Count<3 then Exit; X := TPVar(A.Items[0])^; N := R.Name; i := 1; while i<A.Count-1 do begin if TPVar(A.Items[i])^.Value=X.Value then begin R := TPVar(A.Items[i+1])^; R.Name := N; Result :=true; Exit; end; i := i + 2; end; if not Odd(A.Count) then begin R := TPVar(A.Items[A.Count-1])^; R.Name := N; Result := true; end; end; function fYearDays(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var y,m,d : word; begin Result := false; if A.Count<>1 then Exit; DecodeDate(TPVar(A.Items[0])^.Value,y,m,d); if IsLeapYear(y) then R.Value := 366 else R.Value := 365; Result := true; end; function fYearFrac(Sender:TObject; var A:TVarList; var R:TVar) : boolean; var x : extended; dt1,dt2,ds,de : TDateTime; y1,m1,d1, y2,m2,d2,i,n : word; begin Result := false; if A.Count<>2 then Exit; dt1 := TPVar(A.Items[0])^.Value; dt2 := TPVar(A.Items[1])^.Value; if dt1>dt2 then begin dt1 := dt2; dt2 := TPVar(A.Items[0])^.Value; end; DecodeDate(dt1,y1,m1,d1); DecodeDate(dt2,y2,m2,d2); x := 0; for i := y1 to y2 do begin if i=y1 then ds := dt1 else ds := EncodeDate(i,1,1); if i=y2 then de := dt2 else de := EncodeDate(i+1,1,1); if IsLeapYear(i) then n := 366 else n := 365; x := x + (de-ds)/n; end; R.Value := x; Result := true; end; procedure SetFunctions(PC : TPasCalc); begin // String routines PC.SetFunction('Val', @fVal); PC.SetFunction('IntToStr', @fIntToStr); PC.SetFunction('StrToInt', @fStrToInt); PC.SetFunction('FloatToStr', @fFloatToStr); PC.SetFunction('StrToFloat', @fStrToFloat); PC.SetFunction('Copy', @fCopy); PC.SetFunction('Pos', @fPos); PC.SetFunction('Length', @fLength); PC.SetFunction('Insert', @fInsert); PC.SetFunction('Delete', @fDelete); PC.SetFunction('Trim', @fTrim); PC.SetFunction('TrimLeft', @fTrimLeft); PC.SetFunction('TrimRight', @fTrimRight); PC.SetFunction('UpperCase', @fUpperCase); PC.SetFunction('LowerCase', @fLowerCase); PC.SetFunction('Format', @fFormat); // Date/time routines PC.SetFunction('Now', @fNow); PC.SetFunction('Date', @fDate); PC.SetFunction('Time', @fTime); PC.SetFunction('DateToStr', @fDateToStr); PC.SetFunction('StrToDate', @fStrToDate); PC.SetFunction('TimeToStr', @fTimeToStr); PC.SetFunction('StrToTime', @fStrToTime); PC.SetFunction('FormatDateTime', @fFormatDateTime); PC.SetFunction('DayOfWeek', @fDayOfWeek); PC.SetFunction('IncMonth', @fIncMonth); PC.SetFunction('DecodeDate', @fDecodeDate); PC.SetFunction('DecodeTime', @fDecodeTime); PC.SetFunction('EncodeDate', @fEncodeDate); PC.SetFunction('EncodeTime', @fEncodeTime); // Arithmetic routines PC.SetFunction('Abs', @fAbs); PC.SetFunction('Int', @fInt); PC.SetFunction('Frac', @fFrac); PC.SetFunction('Round', @fRound); PC.SetFunction('Ceil', @fCeil); PC.SetFunction('Floor', @fFloor); PC.SetFunction('Trunc', @fTrunc); PC.SetFunction('Sin', @fSin); PC.SetFunction('Cos', @fCos); PC.SetFunction('Tan', @fTan); PC.SetFunction('ArcSin', @fArcSin); PC.SetFunction('ArcCos', @fArcCos); PC.SetFunction('ArcTan', @fArcTan); PC.SetFunction('Exp', @fExp); PC.SetFunction('Ln', @fLn); PC.SetFunction('IntPower', @fIntPower); PC.SetFunction('Sqr', @fSqr); PC.SetFunction('Sqrt', @fSqrt); PC.SetFunction('Inc', @fInc); PC.SetFunction('Dec', @fDec); // PASCALC functions PC.SetFunction('Min', @fMin); PC.SetFunction('Max', @fMax); PC.SetFunction('GetVar', @fGetVar); PC.SetFunction('SetVar', @fSetVar); PC.SetFunction('Decode', @fDecode); PC.SetFunction('YearDays', @fYearDays); PC.SetFunction('YearFrac', @fYearFrac); end; end.
program csvconv; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, csvdocument_package, CustApp, CSVDocument, Math; type { TCSVDoc } TCSVDoc = class(TCustomApplication) protected procedure DoRun; override; procedure DoConvert(iFile: string; oFile: string); public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; { TCSVDoc } procedure TCSVDoc.DoRun; var ErrorMsg: String; iFile, oFile: String; begin iFile := GetOptionValue('i', 'input'); oFile:= GetOptionValue('o', 'output'); if (iFile = '') or (oFile = '') then begin WriteLn('Usage: csvconv -i <input file> -o <output file>'); Terminate; Exit; end; if not FileExists(iFile) then begin iFile:= GetCurrentDir+iFile; end; oFile := ExtractFilePath(iFile) + ExtractFileName(oFile); WriteLn(Format('convert from %s to %s', [iFile, oFile])); DoConvert(iFile, oFile); Terminate; end; procedure TCSVDoc.DoConvert(iFile: string; oFile: string); var Parser: TCSVParser; FileStream: TFileStream; SLTitle, SLText: TStringList; text: string; SLResult: TStringList; begin Parser:=TCSVParser.Create; FileStream := TFileStream.Create(iFile, fmOpenRead+fmShareDenyWrite); SLTitle := TStringList.Create; SLText := TStringList.Create; SLResult := TStringList.Create; try Parser.Delimiter:=','; Parser.SetSource(FileStream); while Parser.ParseNextCell do begin if Parser.CurrentRow = 0 then Continue; if Parser.CurrentCol = 0 then Continue; case Parser.CurrentCol of 1:SLTitle.Add(' <item>'+Parser.CurrentCellText+'</item>'); 2: begin text := Parser.CurrentCellText; text := StringReplace(text, #13#10, '\n', [rfIgnoreCase, rfReplaceAll]); text := StringReplace(text, #10, '\n', [rfIgnoreCase, rfReplaceAll]); text := StringReplace(text, '&', '&amp;', [rfIgnoreCase, rfReplaceAll]); text := StringReplace(text, '<', '&lt;', [rfIgnoreCase, rfReplaceAll]); text := StringReplace(text, '>', '&gt;', [rfIgnoreCase, rfReplaceAll]); SLText.Add(' <item>'+text+'</item>'); end; end; end; SLResult.Add('<?xml version="1.0" encoding="utf-8"?>'); SLResult.Add('<resources>'); SLResult.Add(' <string-array name="task_title">'); SLResult.Add(SLTitle.Text); SLResult.Add(' </string-array>'); SLResult.Add(' <string-array name="task_text">'); SLResult.Add(SLText.Text); SLResult.Add(' </string-array>'); SLResult.Add('</resources>'); SLResult.SaveToFile(oFile); finally Parser.Free; FileStream.Free; SLResult.Free; end; end; constructor TCSVDoc.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TCSVDoc.Destroy; begin inherited Destroy; end; procedure TCSVDoc.WriteHelp; begin { add your help code here } writeln('Usage: ',ExeName,' -h'); end; var Application: TCSVDoc; begin Application:=TCSVDoc.Create(nil); Application.Title:='lovingyou'; Application.Run; Application.Free; end.
unit uPriceQueryFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uListFormBaseFrm, cxPC, cxControls, cxLookAndFeelPainters, cxGroupBox, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, Menus, StdCtrls, cxButtons, cxCheckBox, cxDropDownEdit, cxCalendar, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, DBClient,DateUtils, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox,cxGridExportLink; type TPriceQueryFrm = class(TListFormBaseFrm) cxPageControl1: TcxPageControl; cxTabSheet1: TcxTabSheet; cxTabSheet2: TcxTabSheet; cxTabSheet3: TcxTabSheet; txt_QDCustomer: TcxButtonEdit; txt_CreateUnit: TcxButtonEdit; txt_QDMaterial: TcxButtonEdit; cxGroupBox1: TcxGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; txt_QDBill: TcxTextEdit; Label4: TLabel; QDbegin: TcxDateEdit; QDEnd: TcxDateEdit; chk_QD: TcxCheckBox; Label5: TLabel; btn_QDQuery: TcxButton; cxGroupBox2: TcxGroupBox; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; RTUnit: TcxButtonEdit; RTMaterial: TcxButtonEdit; RTShop: TcxButtonEdit; RTBill: TcxTextEdit; RTBegin: TcxDateEdit; RTEnd: TcxDateEdit; chk_RT: TcxCheckBox; cxGroupBox3: TcxGroupBox; Label11: TLabel; Label14: TLabel; Label15: TLabel; PUR_Customer: TcxButtonEdit; PurMaterial: TcxButtonEdit; PurBegin: TcxDateEdit; PurEnd: TcxDateEdit; chk_PUR: TcxCheckBox; Label12: TLabel; Pur_Supper: TcxButtonEdit; cxGrid2: TcxGrid; cxGridQD: TcxGridDBTableView; cxGrid2Level1: TcxGridLevel; cxGrid1: TcxGrid; cxGridRT: TcxGridDBTableView; cxGridLevel1: TcxGridLevel; cxGrid3: TcxGrid; cxGridPur: TcxGridDBTableView; cxGridLevel2: TcxGridLevel; cxButton3: TcxButton; btn_RTQuery: TcxButton; cxButton4: TcxButton; cxButton2: TcxButton; cxButton5: TcxButton; cdsQD: TClientDataSet; dsQD: TDataSource; cdsPur: TClientDataSet; dsPur: TDataSource; cdsRT: TClientDataSet; dsRT: TDataSource; Label13: TLabel; cb_PriceType: TcxLookupComboBox; PopupMenu1: TPopupMenu; seeMaterialinfo: TMenuItem; SaveDg: TSaveDialog; Label16: TLabel; procedure txt_CreateUnitKeyPress(Sender: TObject; var Key: Char); procedure txt_QDCustomerKeyPress(Sender: TObject; var Key: Char); procedure txt_QDMaterialKeyPress(Sender: TObject; var Key: Char); procedure RTUnitKeyPress(Sender: TObject; var Key: Char); procedure RTShopKeyPress(Sender: TObject; var Key: Char); procedure RTMaterialKeyPress(Sender: TObject; var Key: Char); procedure Pur_SupperKeyPress(Sender: TObject; var Key: Char); procedure PurMaterialKeyPress(Sender: TObject; var Key: Char); procedure txt_CreateUnitPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure txt_QDCustomerPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure txt_QDMaterialPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure RTUnitPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure RTShopPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure RTMaterialPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure Pur_SupperPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure PurMaterialPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure FormShow(Sender: TObject); procedure btn_QDQueryClick(Sender: TObject); procedure btn_RTQueryClick(Sender: TObject); procedure cxButton2Click(Sender: TObject); procedure seeMaterialinfoClick(Sender: TObject); procedure cxButton3Click(Sender: TObject); procedure cxButton4Click(Sender: TObject); procedure cxButton5Click(Sender: TObject); private { Private declarations } public { Public declarations } QDCustFID,QDUintFID,QDMaterFID : String; RTShopFID,RTUnitFID,RTMaterFID : string; PurCustFID, PURSupperFID,PurMaterFID : string; procedure SetPurCustomer; Function GetSupplerByBranch(suplierFID:string):string; end; var PriceQueryFrm: TPriceQueryFrm; implementation uses FrmCliDM,Pub_Fun,uMaterDataSelectHelper,uDrpHelperClase,StringUtilClass,materialinfo; {$R *.dfm} procedure TPriceQueryFrm.txt_CreateUnitKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key <> #8 then Key := #0 else begin QDUintFID := ''; TcxButtonEdit(Sender).Text := ''; end; end; procedure TPriceQueryFrm.txt_QDCustomerKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key <> #8 then Key := #0 else begin QDCustFID := ''; TcxButtonEdit(Sender).Text := ''; end; end; procedure TPriceQueryFrm.txt_QDMaterialKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key <> #8 then Key := #0 else begin QDMaterFID := ''; TcxButtonEdit(Sender).Text := ''; end; end; procedure TPriceQueryFrm.RTUnitKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key <> #8 then Key := #0 else begin RTUnitFID := ''; TcxButtonEdit(Sender).Text := ''; end; end; procedure TPriceQueryFrm.RTShopKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key <> #8 then Key := #0 else begin RTShopFID := ''; TcxButtonEdit(Sender).Text := ''; end; end; procedure TPriceQueryFrm.RTMaterialKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key <> #8 then Key := #0 else begin RTMaterFID := ''; TcxButtonEdit(Sender).Text := ''; end; end; procedure TPriceQueryFrm.Pur_SupperKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key <> #8 then Key := #0 else begin PURSupperFID:= ''; TcxButtonEdit(Sender).Text := ''; end; end; procedure TPriceQueryFrm.PurMaterialKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key <> #8 then Key := #0 else begin PurMaterFID := ''; TcxButtonEdit(Sender).Text := ''; end; end; procedure TPriceQueryFrm.txt_CreateUnitPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); begin inherited; with Select_Branch('','') do begin if not isEmpty then begin self.QDUintFID := Fieldbyname('FID').AsString; TcxButtonEdit(Sender).Text := Fieldbyname('Fname_l2').AsString; end; end; end; procedure TPriceQueryFrm.txt_QDCustomerPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); begin inherited; with Select_Customer('','','') do begin if not isEmpty then begin self.QDCustFID := Fieldbyname('FID').AsString; TcxButtonEdit(Sender).Text := Fieldbyname('Fname_l2').AsString; end; end; end; procedure TPriceQueryFrm.txt_QDMaterialPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); begin inherited; with Select_Material('','') do begin if not isEmpty then begin self.QDMaterFID := Fieldbyname('FID').AsString; TcxButtonEdit(Sender).Text := Fieldbyname('Fname_l2').AsString; end; end; end; procedure TPriceQueryFrm.RTUnitPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin inherited; with Select_Branch('','') do begin if not isEmpty then begin self.RTUnitFID := Fieldbyname('FID').AsString; TcxButtonEdit(Sender).Text := Fieldbyname('Fname_l2').AsString; end; end; end; procedure TPriceQueryFrm.RTShopPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin inherited; with Select_shop('','') do begin if not isEmpty then begin self.RTShopFID := Fieldbyname('FID').AsString; TcxButtonEdit(Sender).Text := Fieldbyname('Fname_l2').AsString; end; end; end; procedure TPriceQueryFrm.RTMaterialPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin inherited; with Select_Material('','') do begin if not isEmpty then begin self.RTMaterFID := Fieldbyname('FID').AsString; TcxButtonEdit(Sender).Text := Fieldbyname('Fname_l2').AsString; end; end; end; procedure TPriceQueryFrm.Pur_SupperPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin inherited; with Select_Suppliers('','','') do begin if not isEmpty then begin self.PURSupperFID := Fieldbyname('FID').AsString; TcxButtonEdit(Sender).Text := Fieldbyname('Fname_l2').AsString; end; end; end; procedure TPriceQueryFrm.PurMaterialPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin inherited; with Select_Material('','') do begin if not isEmpty then begin self.PurMaterFID := Fieldbyname('FID').AsString; TcxButtonEdit(Sender).Text := Fieldbyname('Fname_l2').AsString; end; end; end; procedure TPriceQueryFrm.FormShow(Sender: TObject); begin inherited; QDbegin.Date := Date; RTBegin.Date := Date; PurBegin.Date := Date; PurEnd.Date := DateUtils.IncDay(Date,60); RTEnd.Date := DateUtils.IncDay(Date,60); QDEnd.Date := DateUtils.IncDay(Date,60); cxPageControl1.ActivePageIndex := OpenFormParameter.mType; cb_PriceType.Properties.ListSource := cliDm.dsPriceType; self.QDUintFID := userinfo.Branch_ID; txt_CreateUnit.Text := userinfo.Branch_Name; RTUnit.Text := userinfo.Branch_Name; self.RTUnitFID := userinfo.Branch_ID; end; procedure TPriceQueryFrm.btn_QDQueryClick(Sender: TObject); var _SQL,ErrMsg : String; i:integer; begin inherited; if self.QDUintFID = '' then begin ShowMsg(self.Handle,'调价机构不能为空! ',[]) ; txt_CreateUnit.SetFocus; abort; end; if (self.QDCustFID = '') and (self.QDMaterFID = '') then begin ShowMsg(self.Handle,'客户和物料必须输入一项! ',[]) ; txt_QDCustomer.SetFocus; abort; end; if chk_QD.Checked then begin if QDBegin.Text = '' then begin ShowMsg(self.Handle,'生效日期不能为空! ',[]) ; QDBegin.SetFocus; abort; end; if QDEnd.Text = '' then begin ShowMsg(self.Handle,'生效日期不能为空! ',[]) ; QDEnd.SetFocus; abort; end; end; _SQL :='select ' +' case when sysdate between custEntry.Fbegindate and custEntry.Fenddate then ''有效'' else ''已过期'' end as IsValid,' +' mater.fnumber,' +' to_char(custEntry.Fbegindate ,''YYYY-MM-DD'') as BeginDate, ' +' to_char(custEntry.Fenddate ,''YYYY-MM-DD'') as EedDate, ' +' cust.fnumber as CustNumber,' +' cust.fname_l2 as CustName,' +' m.FID as MaterialFID, ' +' m.fnumber as FMaterialNumber, ' +' m.fname_l2 as FMaterialName, ' +' py.fname_l2 as pyName,' +' m.cfdistributeprice as FDisPrice,' +' a.fdiscount, ' +' a.fprice ,ctUser.Fname_L2 as ctName' +' from T_I3_PRICEPOLICYMaterialENTRY a ' +' left join t_bd_material m on a.fmaterialid=m.fid ' +' left join t_Scm_Pricetype py on a.fpricetypeid=py.fid' +' left join t_bd_customer cust on cust.fid = a.fcustomerid ' +' left join T_I3_PRICEPOLICYBranchENTRY custEntry on custEntry.FParentID = a.fparentid' +' and custEntry.fcustomerid=a.fcustomerid ' +' left join T_I3_PRICEPOLICY mater on mater.fid=a.fparentid' +' left join t_Pm_User ctUser on ctUser.FID = mater.fcreatorid ' +' where mater.FStatus = 1 '; _SQL := _SQL+' and mater.fbranchid='+Quotedstr(self.QDUintFID); if self.QDCustFID <> '' then _SQL := _SQL+' and a.fcustomerid='+Quotedstr(self.QDCustFID); if self.QDMaterFID <> '' then _SQL := _SQL+' and a.fmaterialid='+Quotedstr(self.QDMaterFID); if trim(txt_QDBill.Text) <> '' then _SQL := _SQL+' and mater.fnumber='+Quotedstr(trim(txt_QDBill.Text)); if chk_QD.Checked then begin _SQL := _SQL+' and to_char(custEntry.Fbegindate ,''YYYY-MM-DD'')>='+Quotedstr(FormatDateTime('YYYY-MM-DD',QDbegin.Date)) +' and to_char(custEntry.Fenddate ,''YYYY-MM-DD'')<='+Quotedstr(FormatDateTime('YYYY-MM-DD',QDEnd.Date)); end; if cb_PriceType.Text <> '' then _SQL := _SQL+' and a.fpricetypeid='+Quotedstr(cb_PriceType.EditingValue); try cxGridQD.BeginUpdate; if not CliDM.Get_OpenSQL(cdsQD,_SQL,ErrMsg) then begin ShowMsg(self.Handle,'查询出错:'+ErrMsg,[]) ; abort; end; if cxGridQD.ColumnCount = 0 then begin cxGridQD.DataController.CreateAllItems(); for i := 0 to cxGridQD.ColumnCount -1 do begin cxGridQD.Columns[i].Width := 80; end; cxGridQD.GetColumnByFieldName('IsValid').Caption := '是否有效'; cxGridQD.GetColumnByFieldName('fnumber').Caption := '调整单号'; cxGridQD.GetColumnByFieldName('BeginDate').Caption := '有效日期'; cxGridQD.GetColumnByFieldName('EedDate').Caption := '失效日期'; cxGridQD.GetColumnByFieldName('CustNumber').Caption := '客户编号'; cxGridQD.GetColumnByFieldName('CustName').Caption := '客户名称'; cxGridQD.GetColumnByFieldName('MaterialFID').Visible := false; cxGridQD.GetColumnByFieldName('FMaterialNumber').Caption := '物料编号'; cxGridQD.GetColumnByFieldName('FMaterialName').Caption := '物料名称'; cxGridQD.GetColumnByFieldName('pyName').Caption := '价格类型'; cxGridQD.GetColumnByFieldName('FDisPrice').Caption := '标准价'; cxGridQD.GetColumnByFieldName('fdiscount').Caption := '折扣'; cxGridQD.GetColumnByFieldName('fprice').Caption := '单价'; cxGridQD.GetColumnByFieldName('ctName').Caption := '制单人'; With cxGridQD.DataController.Summary.FooterSummaryItems.Add do begin ItemLink := cxGridQD.VisibleColumns[0]; Position := spFooter; Kind := skCount; end; end; finally cxGridQD.EndUpdate; end; end; procedure TPriceQueryFrm.btn_RTQueryClick(Sender: TObject); var _SQL,ErrMsg : String; i:integer; begin inherited; if self.RTUnitFID = '' then begin ShowMsg(self.Handle,'调价机构不能为空! ',[]) ; RTUnit.SetFocus; abort; end; if (self.RTShopFID = '') and (self.RTMaterFID = '') then begin ShowMsg(self.Handle,'店铺和物料必须输入一项! ',[]) ; RTShop.SetFocus; abort; end; if chk_RT.Checked then begin if RTBegin.Text = '' then begin ShowMsg(self.Handle,'生效日期不能为空! ',[]) ; RTBegin.SetFocus; abort; end; if RTEnd.Text = '' then begin ShowMsg(self.Handle,'生效日期不能为空! ',[]) ; RTEnd.SetFocus; abort; end; end; _SQL :='select ' +' case when sysdate between custEntry.Fbegindate and custEntry.Fenddate then ''有效'' else ''已过期'' end as IsValid,' +' mater.fnumber,' +' to_char(custEntry.Fbegindate ,''YYYY-MM-DD'') as BeginDate, ' +' to_char(custEntry.Fenddate ,''YYYY-MM-DD'') as EedDate, ' +' cust.fnumber as CustNumber,' +' cust.fname_l2 as CustName,' +' m.FID as MaterialFID, ' +' m.fnumber as FMaterialNumber, ' +' m.fname_l2 as FMaterialName, ' +' m.cfunityprice as FDisPrice,' +' a.fdiscount, ' +' a.fprice ,ctUser.Fname_L2 as ctName' +' from T_SHOP_PRTENTRY a ' +' left join t_bd_material m on a.fmaterialid=m.fid ' +' left join t_db_warehouse cust on cust.fid = a.fcustomerid ' +' left join T_Shop_PRICEPOLICYBranchENTRY custEntry on custEntry.FParentID = a.fparentid' +' and custEntry.fcustomerid=a.fcustomerid ' +' left join T_Shop_PRICEPOLICY mater on mater.fid=a.fparentid' +' left join t_Pm_User ctUser on ctUser.FID = mater.fcreatorid ' +' where mater.FStatus = 1 '; _SQL := _SQL+' and mater.fbranchid='+Quotedstr(self.RTUnitFID); if self.RTShopFID <> '' then _SQL := _SQL+' and a.fcustomerid='+Quotedstr(self.RTShopFID); if self.RTMaterFID <> '' then _SQL := _SQL+' and a.fmaterialid='+Quotedstr(self.RTMaterFID); if trim(RTBill.Text) <> '' then _SQL := _SQL+' and mater.fnumber='+Quotedstr(trim(RTBill.Text)); if chk_RT.Checked then begin _SQL := _SQL+' and to_char(custEntry.Fbegindate ,''YYYY-MM-DD'')>='+Quotedstr(FormatDateTime('YYYY-MM-DD',RTBegin.Date)) +' and to_char(custEntry.Fenddate ,''YYYY-MM-DD'')<='+Quotedstr(FormatDateTime('YYYY-MM-DD',RTEnd.Date)); end; try cxGridRT.BeginUpdate; if not CliDM.Get_OpenSQL(cdsRT,_SQL,ErrMsg) then begin ShowMsg(self.Handle,'查询出错:'+ErrMsg,[]) ; abort; end; if cxGridRT.ColumnCount = 0 then begin cxGridRT.DataController.CreateAllItems(); for i := 0 to cxGridRT.ColumnCount -1 do begin cxGridRT.Columns[i].Width := 80; end; cxGridRT.GetColumnByFieldName('IsValid').Caption := '是否有效'; cxGridRT.GetColumnByFieldName('fnumber').Caption := '调整单号'; cxGridRT.GetColumnByFieldName('BeginDate').Caption := '有效日期'; cxGridRT.GetColumnByFieldName('EedDate').Caption := '失效日期'; cxGridRT.GetColumnByFieldName('CustNumber').Caption := '店铺编号'; cxGridRT.GetColumnByFieldName('CustName').Caption := '店铺名称'; cxGridRT.GetColumnByFieldName('MaterialFID').Visible := false; cxGridRT.GetColumnByFieldName('FMaterialNumber').Caption := '物料编号'; cxGridRT.GetColumnByFieldName('FMaterialName').Caption := '物料名称'; cxGridRT.GetColumnByFieldName('FDisPrice').Caption := '吊牌价'; cxGridRT.GetColumnByFieldName('fdiscount').Caption := '折扣'; cxGridRT.GetColumnByFieldName('fprice').Caption := '单价'; cxGridRT.GetColumnByFieldName('ctName').Caption := '制单人'; With cxGridRT.DataController.Summary.FooterSummaryItems.Add do begin ItemLink := cxGridRT.VisibleColumns[0]; Position := spFooter; Kind := skCount; end; end; finally cxGridRT.EndUpdate; end; end; procedure TPriceQueryFrm.SetPurCustomer; var cds:TClientDataSet; _SQL,ErrMsg:string; begin try cds := TClientDataset.Create(nil); _SQl := 'select FID,fnumber,Fname_l2 from t_bd_customer a where a.finternalcompanyid = ' + Quotedstr(userInfo.Branch_ID); if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then begin ShowMsg(self.Handle,'查询出错:'+ErrMsg,[]) ; exit; end; if not cds.IsEmpty then begin self.PurCustFID := cds.fieldbyname('FID').AsString; PUR_Customer.Text := cds.fieldbyname('fname_l2').AsString; end; finally cds.Free; end; end; function TPriceQueryFrm.GetSupplerByBranch(suplierFID: string): string; var cds:TClientDataSet; _SQL,ErrMsg:string; begin try result := ''; cds := TClientDataset.Create(nil); _SQl := 'select b.finternalcompanyid as bFID from t_bd_supplier b' + Quotedstr(suplierFID); if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then begin ShowMsg(self.Handle,'查询出错:'+ErrMsg,[]) ; exit; end; if not cds.IsEmpty then begin result := cds.fieldbyname('FID').AsString; end; finally cds.Free; end; end; procedure TPriceQueryFrm.cxButton2Click(Sender: TObject); var _SQL,ErrMsg,CreateBranchFID : String; i:integer; begin inherited; if self.PurCustFID = '' then begin ShowMsg(self.Handle,'没有找到当前机构对应的客户信息! ',[]) ; abort; end; if (self.PURSupperFID = '') and (self.PurMaterFID = '') then begin ShowMsg(self.Handle,'供应商和物料必须输入一项! ',[]) ; Pur_Supper.SetFocus; abort; end; if chk_PUR.Checked then begin if PurBegin.Text = '' then begin ShowMsg(self.Handle,'生效日期不能为空! ',[]) ; PurBegin.SetFocus; abort; end; if PurEnd.Text = '' then begin ShowMsg(self.Handle,'生效日期不能为空! ',[]) ; PurEnd.SetFocus; abort; end; end; _SQL :='select ' +' case when sysdate between custEntry.Fbegindate and custEntry.Fenddate then ''有效'' else ''已过期'' end as IsValid,' +' mater.fnumber,' +' to_char(custEntry.Fbegindate ,''YYYY-MM-DD'') as BeginDate, ' +' to_char(custEntry.Fenddate ,''YYYY-MM-DD'') as EedDate, ' +' m.FID as MaterialFID, ' +' m.fnumber as FMaterialNumber, ' +' m.fname_l2 as FMaterialName, ' +' m.cfdistributeprice as FDisPrice,' +' a.fdiscount, ' +' a.fprice ,ctUser.Fname_L2 as ctName' +' from T_SHOP_PRTENTRY a ' +' left join t_bd_material m on a.fmaterialid=m.fid ' +' left join t_db_warehouse cust on cust.fid = a.fcustomerid ' +' left join T_Shop_PRICEPOLICYBranchENTRY custEntry on custEntry.FParentID = a.fparentid' +' and custEntry.fcustomerid=a.fcustomerid ' +' left join T_Shop_PRICEPOLICY mater on mater.fid=a.fparentid' +' left join t_Pm_User ctUser on ctUser.FID = mater.fcreatorid ' +' where mater.FStatus = 1 '; _SQL := _SQL+' and mater.fbranchid='+Quotedstr(GetSupplerByBranch(self.PURSupperFID)); if self.RTShopFID <> '' then _SQL := _SQL+' and a.fcustomerid='+Quotedstr(self.PurCustFID); if self.RTMaterFID <> '' then _SQL := _SQL+' and a.fmaterialid='+Quotedstr(self.PurMaterFID); if chk_RT.Checked then begin _SQL := _SQL+' and to_char(custEntry.Fbegindate ,''YYYY-MM-DD'')>='+Quotedstr(FormatDateTime('YYYY-MM-DD',PurBegin.Date)) +' and to_char(custEntry.Fenddate ,''YYYY-MM-DD'')<='+Quotedstr(FormatDateTime('YYYY-MM-DD',PurEnd.Date)); end; try cxGridPur.BeginUpdate; if not CliDM.Get_OpenSQL(cdsPur,_SQL,ErrMsg) then begin ShowMsg(self.Handle,'查询出错:'+ErrMsg,[]) ; abort; end; if cxGridPur.ColumnCount = 0 then begin cxGridPur.DataController.CreateAllItems(); for i := 0 to cxGridPur.ColumnCount -1 do begin cxGridPur.Columns[i].Width := 80; end; cxGridPur.GetColumnByFieldName('IsValid').Caption := '是否有效'; cxGridPur.GetColumnByFieldName('fnumber').Caption := '调整单号'; cxGridPur.GetColumnByFieldName('BeginDate').Caption := '有效日期'; cxGridPur.GetColumnByFieldName('EedDate').Caption := '失效日期'; cxGridPur.GetColumnByFieldName('MaterialFID').Visible := false; cxGridPur.GetColumnByFieldName('FMaterialNumber').Caption := '物料编号'; cxGridPur.GetColumnByFieldName('FMaterialName').Caption := '物料名称'; cxGridPur.GetColumnByFieldName('FDisPrice').Caption := '标准价'; cxGridPur.GetColumnByFieldName('fdiscount').Caption := '折扣'; cxGridPur.GetColumnByFieldName('fprice').Caption := '单价'; cxGridPur.GetColumnByFieldName('ctName').Caption := '制单人'; With cxGridPur.DataController.Summary.FooterSummaryItems.Add do begin ItemLink := cxGridPur.VisibleColumns[0]; Position := spFooter; Kind := skCount; end; end; finally cxGridPur.EndUpdate; end; end; procedure TPriceQueryFrm.seeMaterialinfoClick(Sender: TObject); begin inherited; if cxPageControl1.ActivePageIndex = 0 then begin if cdsQD.IsEmpty then Exit; getMaterialinfo(cdsQD.FieldByName('MaterialFID').AsString); end else if cxPageControl1.ActivePageIndex = 1 then begin if cdsRT.IsEmpty then Exit; getMaterialinfo(cdsRT.FieldByName('MaterialFID').AsString); end else if cxPageControl1.ActivePageIndex = 2 then begin if cdsPUR.IsEmpty then Exit; getMaterialinfo(cdsPUR.FieldByName('MaterialFID').AsString); end end; procedure TPriceQueryFrm.cxButton3Click(Sender: TObject); begin inherited; if cxGridQD.DataController.DataSource.DataSet.IsEmpty then Exit; SaveDg.FileName := Self.Caption; if SaveDg.Execute then ExportGridToExcel(SaveDg.FileName, cxGrid2, True, true, True); end; procedure TPriceQueryFrm.cxButton4Click(Sender: TObject); begin inherited; if cxGridRT.DataController.DataSource.DataSet.IsEmpty then Exit; SaveDg.FileName := Self.Caption; if SaveDg.Execute then ExportGridToExcel(SaveDg.FileName, cxGrid1, True, true, True); end; procedure TPriceQueryFrm.cxButton5Click(Sender: TObject); begin inherited; if cxGridPur.DataController.DataSource.DataSet.IsEmpty then Exit; SaveDg.FileName := Self.Caption; if SaveDg.Execute then ExportGridToExcel(SaveDg.FileName, cxGrid3, True, true, True); end; end.
unit SDUMultimediaKeys; // Multimedia keys component // Set "MultimediaKeyControl" as appropriate, and then set Active to TRUE. // Note: If MultimediaKeyControl is set to nil, multimedia keystokes won't be /// restricted to a single control // !!! WARNING !!! // Not guaranteed to work correctly if multiple instances of this component // are used in different threads; SetWindowsHookEx(...) uses GetCurrentThread // to setup a hook for the thread - but it only has one SDMultimediaKeysHook interface uses Classes, Controls, Messages, Windows, ShellAPI; type TSDUMultimediaKeysThreadCallback = procedure (cmd: WORD; uDevice: WORD; dwKeys : WORD) of object; TSDUMultimediaKeyEvent = procedure (Sender: TObject; var MultimediaKey: Word; Shift: TShiftState) of object; TSDUMultimediaKeysThread = class(TThread) protected procedure SyncMethod(); public cmd: WORD; uDevice: WORD; dwKeys: WORD; Callback: TSDUMultimediaKeysThreadCallback; procedure AfterConstruction(); override; destructor Destroy(); override; procedure Execute(); override; end; TSDUMultimediaKeys = class(TComponent) private FActive: boolean; FMultimediaKeyControl: TWinControl; FOnMultimediaKeypress: TSDUMultimediaKeyEvent; FOnBrowserBackward: TNotifyEvent; FOnBrowserForward: TNotifyEvent; FOnBrowserRefresh: TNotifyEvent; FOnBrowserStop: TNotifyEvent; FOnBrowserSearch: TNotifyEvent; FOnBrowserFavorites: TNotifyEvent; FOnBrowserHome: TNotifyEvent; FOnVolumeMute: TNotifyEvent; FOnVolumeDown: TNotifyEvent; FOnVolumeUp: TNotifyEvent; FOnMediaNextTrack: TNotifyEvent; FOnMediaPreviousTrack: TNotifyEvent; FOnMediaStop: TNotifyEvent; FOnMediaPlayPause: TNotifyEvent; FOnLaunchMail: TNotifyEvent; FOnLaunchMediaSelect: TNotifyEvent; FOnLaunchApp1: TNotifyEvent; FOnLaunchApp2: TNotifyEvent; FOnBassDown: TNotifyEvent; FOnBassBoost: TNotifyEvent; FOnBassUp: TNotifyEvent; FOnTrebleDown: TNotifyEvent; FOnTrebleUp: TNotifyEvent; protected procedure ResetMultimediaKeyControlHandle(); function GetEventForKey(cmd: WORD): TNotifyEvent; procedure KickOffThread(cmd: WORD; uDevice: WORD; dwKeys : WORD); procedure ThreadCallback(cmd: WORD; uDevice: WORD; dwKeys : WORD); public // Cached MultimediaKeyControl.Handle required as the MultimediaKeyControl may be destroyed // before we are! // Exposed as public to allow the hook callback to check it MultimediaKeyControlHandle: THandle; constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure SetActive(newActive: boolean); procedure SetControl(newControl: TWinControl); function WMAppCommand(lParam: DWORD): boolean; procedure BeforeDestruction(); override; published property Active: boolean read FActive write SetActive; property MultimediaKeyControl: TWinControl read FMultimediaKeyControl write SetControl; // property Hook: HHOOK read FHook; property OnMultimediaKeypress: TSDUMultimediaKeyEvent read FOnMultimediaKeypress write FOnMultimediaKeypress; property OnBrowserBackward: TNotifyEvent read FOnBrowserBackward write FOnBrowserBackward; property OnBrowserForward: TNotifyEvent read FOnBrowserForward write FOnBrowserForward; property OnBrowserRefresh: TNotifyEvent read FOnBrowserRefresh write FOnBrowserRefresh; property OnBrowserStop: TNotifyEvent read FOnBrowserStop write FOnBrowserStop; property OnBrowserSearch: TNotifyEvent read FOnBrowserSearch write FOnBrowserSearch; property OnBrowserFavorites: TNotifyEvent read FOnBrowserFavorites write FOnBrowserFavorites; property OnBrowserHome: TNotifyEvent read FOnBrowserHome write FOnBrowserHome; property OnVolumeMute: TNotifyEvent read FOnVolumeMute write FOnVolumeMute; property OnVolumeDown: TNotifyEvent read FOnVolumeDown write FOnVolumeDown; property OnVolumeUp: TNotifyEvent read FOnVolumeUp write FOnVolumeUp; property OnMediaNextTrack: TNotifyEvent read FOnMediaNextTrack write FOnMediaNextTrack; property OnMediaPreviousTrack: TNotifyEvent read FOnMediaPreviousTrack write FOnMediaPreviousTrack; property OnMediaStop: TNotifyEvent read FOnMediaStop write FOnMediaStop; property OnMediaPlayPause: TNotifyEvent read FOnMediaPlayPause write FOnMediaPlayPause; property OnLaunchMail: TNotifyEvent read FOnLaunchMail write FOnLaunchMail; property OnLaunchMediaSelect: TNotifyEvent read FOnLaunchMediaSelect write FOnLaunchMediaSelect; property OnLaunchApp1: TNotifyEvent read FOnLaunchApp1 write FOnLaunchApp1; property OnLaunchApp2: TNotifyEvent read FOnLaunchApp2 write FOnLaunchApp2; property OnBassDown: TNotifyEvent read FOnBassDown write FOnBassDown; property OnBassBoost: TNotifyEvent read FOnBassBoost write FOnBassBoost; property OnBassUp: TNotifyEvent read FOnBassUp write FOnBassUp; property OnTrebleDown: TNotifyEvent read FOnTrebleDown write FOnTrebleDown; property OnTrebleUp: TNotifyEvent read FOnTrebleUp write FOnTrebleUp; end; const // From winuser.h: APPCOMMAND_BROWSER_BACKWARD = 1; APPCOMMAND_BROWSER_FORWARD = 2; APPCOMMAND_BROWSER_REFRESH = 3; APPCOMMAND_BROWSER_STOP = 4; APPCOMMAND_BROWSER_SEARCH = 5; APPCOMMAND_BROWSER_FAVORITES = 6; APPCOMMAND_BROWSER_HOME = 7; APPCOMMAND_VOLUME_MUTE = 8; APPCOMMAND_VOLUME_DOWN = 9; APPCOMMAND_VOLUME_UP = 10; APPCOMMAND_MEDIA_NEXTTRACK = 11; APPCOMMAND_MEDIA_PREVIOUSTRACK = 12; APPCOMMAND_MEDIA_STOP = 13; APPCOMMAND_MEDIA_PLAY_PAUSE = 14; APPCOMMAND_LAUNCH_MAIL = 15; APPCOMMAND_LAUNCH_MEDIA_SELECT = 16; APPCOMMAND_LAUNCH_APP1 = 17; APPCOMMAND_LAUNCH_APP2 = 18; APPCOMMAND_BASS_DOWN = 19; APPCOMMAND_BASS_BOOST = 20; APPCOMMAND_BASS_UP = 21; APPCOMMAND_TREBLE_DOWN = 22; APPCOMMAND_TREBLE_UP = 23; function WMAppCommandHook(nCode: Integer; wParam: DWORD; lParam: DWORD): Longint; stdcall; procedure Register; implementation uses Contnrs, SDUGeneral, SysUtils; const // From winuser.h: FAPPCOMMAND_MOUSE = $8000; FAPPCOMMAND_KEY = 0; FAPPCOMMAND_OEM = $1000; FAPPCOMMAND_MASK = $F000; var SDMultimediaKeysHook: HHOOK; SDMultimediaKeysObjs: TObjectList; // ---------------------------------------------------------------------------- procedure Register; begin RegisterComponents('SDeanUtils', [TSDUMultimediaKeys]); end; // ---------------------------------------------------------------------------- constructor TSDUMultimediaKeys.Create(AOwner: TComponent); begin inherited; FActive:= FALSE; FMultimediaKeyControl:= nil; MultimediaKeyControlHandle := 0; FOnMultimediaKeypress := nil; FOnBrowserBackward := nil; FOnBrowserForward := nil; FOnBrowserRefresh := nil; FOnBrowserStop := nil; FOnBrowserSearch := nil; FOnBrowserFavorites := nil; FOnBrowserHome := nil; FOnVolumeMute := nil; FOnVolumeDown := nil; FOnVolumeUp := nil; FOnMediaNextTrack := nil; FOnMediaPreviousTrack := nil; FOnMediaStop := nil; FOnMediaPlayPause := nil; FOnLaunchMail := nil; FOnLaunchMediaSelect := nil; FOnLaunchApp1 := nil; FOnLaunchApp2 := nil; FOnBassDown := nil; FOnBassBoost := nil; FOnBassUp := nil; FOnTrebleDown := nil; FOnTrebleUp := nil; end; // ---------------------------------------------------------------------------- destructor TSDUMultimediaKeys.Destroy(); begin inherited; end; // ---------------------------------------------------------------------------- procedure TSDUMultimediaKeys.BeforeDestruction(); begin Active := FALSE; inherited; end; // ---------------------------------------------------------------------------- function WMAppCommandHook(nCode: Integer; wParam: DWORD; lParam: DWORD): Longint; stdcall; var i: integer; retval: Longint; handled: boolean; currObj: TSDUMultimediaKeys; begin handled := FALSE; if (nCode = HSHELL_APPCOMMAND) then begin for i:=0 to (SDMultimediaKeysObjs.count - 1) do begin currObj := TSDUMultimediaKeys(SDMultimediaKeysObjs[i]); if ( (wParam = currObj.MultimediaKeyControlHandle) or (currObj.MultimediaKeyControlHandle = 0) ) then begin currObj.WMAppCommand(lParam); handled := TRUE; break; end; end; end; if handled then begin retval := 1; end else begin retval := CallNextHookEx( SDMultimediaKeysHook, nCode, wParam, lParam ); end; Result := retval; end; // ---------------------------------------------------------------------------- procedure TSDUMultimediaKeys.SetActive(newActive: boolean); begin if (Active <> newActive) then begin if newActive then begin // Update DropControlHandle - the handle could have been changed since // the control was assigned ResetMultimediaKeyControlHandle(); // If not restricted to a certain control, add to end, so any more // instances of this component relating to a specific control get the // event first if (MultimediaKeyControlHandle = 0) then begin SDMultimediaKeysObjs.Add(self); end else begin SDMultimediaKeysObjs.Insert(0, self); end; // If the thread's hook hasn't been setup yet; set it up now if (SDMultimediaKeysHook = 0) then begin SDMultimediaKeysHook := SetWindowsHookEx( WH_SHELL, @WMAppCommandHook, 0, GetCurrentThreadID ); end; end else begin SDMultimediaKeysObjs.Delete(SDMultimediaKeysObjs.IndexOf(self)); if (SDMultimediaKeysObjs.Count <= 0) then begin UnhookWindowsHookEx(SDMultimediaKeysHook); SDMultimediaKeysHook := 0; end; end; FActive := newActive; end; end; // ---------------------------------------------------------------------------- procedure TSDUMultimediaKeys.SetControl(newControl: TWinControl); var prevActive: boolean; begin prevActive := Active; Active := FALSE; FMultimediaKeyControl := newControl; ResetMultimediaKeyControlHandle(); Active := prevActive; end; // ---------------------------------------------------------------------------- procedure TSDUMultimediaKeys.ResetMultimediaKeyControlHandle(); begin if (FMultimediaKeyControl = nil) then begin MultimediaKeyControlHandle:= 0; end else begin MultimediaKeyControlHandle:= FMultimediaKeyControl.Handle; end; end; // ---------------------------------------------------------------------------- // Returns TRUE if handled, otherwise FALSE function TSDUMultimediaKeys.WMAppCommand(lParam: DWORD): boolean; function GET_APPCOMMAND_LPARAM(lParam: Integer): Word; begin Result := HiWord(lParam) and not FAPPCOMMAND_MASK; end; function GET_DEVICE_LPARAM(lParam: Integer): Word; begin Result := HiWord(lParam) and FAPPCOMMAND_MASK; end; function GET_FLAGS_LPARAM(lParam: Integer): Word; begin Result := LoWord(lParam); end; function GET_KEYSTATE_LPARAM(lParam: Integer): Word; begin Result := GET_FLAGS_LPARAM(lParam); end; var cmd: WORD; uDevice: WORD; dwKeys: WORD; begin cmd:= GET_APPCOMMAND_LPARAM(LParam); uDevice:= GET_DEVICE_LPARAM(LParam); dwKeys:= GET_KEYSTATE_LPARAM(LParam); // Because we're still handling the Windows message, we kick off pass // the list of files/dirs dropped over to a thread, and complete // handling the WM. // The thread simply sync's back with us, passing back the list of // files/dirs dropped, and we fire off events as appropriate // This is more complex that you'd expect, but if we call the events // directly from here, and those events carry out actions such as // displaying messageboxes to the user, things start to crash and the // user's application will do "odd things" KickOffThread(cmd, uDevice, dwKeys); Result := TRUE; end; procedure TSDUMultimediaKeys.KickOffThread(cmd: WORD; uDevice: WORD; dwKeys : WORD); var thread: TSDUMultimediaKeysThread; begin thread:= TSDUMultimediaKeysThread.Create(TRUE); thread.cmd := cmd; thread.uDevice := uDevice; thread.dwKeys := dwKeys; thread.Callback:= ThreadCallback; thread.FreeOnTerminate := TRUE; thread.Resume(); end; // ---------------------------------------------------------------------------- function TSDUMultimediaKeys.GetEventForKey(cmd: WORD): TNotifyEvent; var retval: TNotifyEvent; begin retval := nil; case cmd of APPCOMMAND_BROWSER_BACKWARD: retval := FOnBrowserBackward; APPCOMMAND_BROWSER_FORWARD: retval := FOnBrowserForward; APPCOMMAND_BROWSER_REFRESH: retval := FOnBrowserRefresh; APPCOMMAND_BROWSER_STOP: retval := FOnBrowserStop; APPCOMMAND_BROWSER_SEARCH: retval := FOnBrowserSearch; APPCOMMAND_BROWSER_FAVORITES: retval := FOnBrowserFavorites; APPCOMMAND_BROWSER_HOME: retval := FOnBrowserHome; APPCOMMAND_VOLUME_MUTE: retval := FOnVolumeMute; APPCOMMAND_VOLUME_DOWN: retval := FOnVolumeDown; APPCOMMAND_VOLUME_UP: retval := FOnVolumeUp; APPCOMMAND_MEDIA_NEXTTRACK: retval := FOnMediaNextTrack; APPCOMMAND_MEDIA_PREVIOUSTRACK: retval := FOnMediaPreviousTrack; APPCOMMAND_MEDIA_STOP: retval := FOnMediaStop; APPCOMMAND_MEDIA_PLAY_PAUSE: retval := FOnMediaPlayPause; APPCOMMAND_LAUNCH_MAIL: retval := FOnLaunchMail; APPCOMMAND_LAUNCH_MEDIA_SELECT: retval := FOnLaunchMediaSelect; APPCOMMAND_LAUNCH_APP1: retval := FOnLaunchApp1; APPCOMMAND_LAUNCH_APP2: retval := FOnLaunchApp2; APPCOMMAND_BASS_DOWN: retval := FOnBassDown; APPCOMMAND_BASS_BOOST: retval := FOnBassBoost; APPCOMMAND_BASS_UP: retval := FOnBassUp; APPCOMMAND_TREBLE_DOWN: retval := FOnTrebleDown; APPCOMMAND_TREBLE_UP: retval := FOnTrebleUp; end; Result := retval; end; // ---------------------------------------------------------------------------- procedure TSDUMultimediaKeys.ThreadCallback(cmd: WORD; uDevice: WORD; dwKeys : WORD); var event: TNotifyEvent; shiftState: TShiftState; begin shiftState := []; if ((dwKeys and MK_CONTROL) = MK_CONTROL) then begin shiftState := shiftState + [ssCtrl]; end; if ((dwKeys and MK_LBUTTON) = MK_LBUTTON) then begin shiftState := shiftState + [ssLeft]; end; if ((dwKeys and MK_MBUTTON) = MK_MBUTTON) then begin shiftState := shiftState + [ssMiddle]; end; if ((dwKeys and MK_RBUTTON) = MK_RBUTTON) then begin shiftState := shiftState + [ssRight]; end; if ((dwKeys and MK_SHIFT) = MK_SHIFT) then begin shiftState := shiftState + [ssShift]; end; { if ((dwKeys and MK_XBUTTON1) = MK_XBUTTON1) then begin shiftState := shiftState + [???]; end; if ((dwKeys and MK_XBUTTON2) = MK_XBUTTON2) then begin shiftState := shiftState + [???]; end; } if assigned(FOnMultimediaKeypress) then begin FOnMultimediaKeypress(self, cmd, shiftState); end; event := GetEventForKey(cmd); if assigned(event) then begin event(self); end; end; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- procedure TSDUMultimediaKeysThread.SyncMethod(); begin if Assigned(Callback) then begin Callback(cmd, uDevice, dwKeys); end; end; procedure TSDUMultimediaKeysThread.AfterConstruction(); begin inherited; end; destructor TSDUMultimediaKeysThread.Destroy(); begin inherited; end; procedure TSDUMultimediaKeysThread.Execute(); begin Synchronize(SyncMethod); end; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- initialization SDMultimediaKeysHook := 0; SDMultimediaKeysObjs:= TObjectList.Create(); SDMultimediaKeysObjs.OwnsObjects := FALSE; finalization SDMultimediaKeysObjs.Free(); END.
unit ConverterClassData; interface uses Classes; type TTemperatureFormula = record Name : String; A : Extended; B : Extended; C : Extended; end; TTemperature = class private FValue : Extended; FScale : Integer; FFormulas : array of TTemperatureFormula; function GetCount: Integer; protected procedure Assign(ATemperature: TTemperature); procedure SetScale(AScale: Integer); function GetTemperature(AIndex: Integer): Extended; procedure SetTemperature(AIndex: Integer; AValue : Extended); property Scale : Integer read FScale write SetScale; public constructor Create; property Temperature : TTemperature write Assign; procedure LoadFromFile(AFilename: String); function StringToScale(AValue: String): Integer; function ScaleToString(AIndex: Integer): String; property Value[Index : Integer]: Extended read GetTemperature write SetTemperature; default; property ScaleName[Index : Integer]: String read ScaleToString; property Count : Integer read GetCount; end; implementation uses ConvUtils, SysUtils; // CSV: // Name, A, B, C // Base = (Temp - C) / B - A // Temp = (Base + A) * B + C constructor TTemperature.Create; begin FValue := 0; FScale := 0; SetLength(FFormulas, 0); end; function TTemperature.GetTemperature(AIndex: Integer): Extended; begin if Scale = AIndex then Result := FValue else begin Scale := AIndex; Result := FValue; end; end; procedure TTemperature.SetTemperature(AIndex: Integer; AValue: Extended); begin FValue := AValue; FScale := AIndex; end; procedure TTemperature.SetScale(AScale: Integer); var lBase, lNew : Extended; lCur, lTo: TTemperatureFormula; begin lCur := FFormulas[FScale]; lTo := FFormulas[AScale]; lBase := (FValue - lCur.C) / lCur.B - lCur.A; lNew := (lBase + lTo.A) * lTo.B + lTo.C; FValue := lNew; FScale := AScale; end; procedure TTemperature.Assign(ATemperature: TTemperature); begin FValue := ATemperature.FValue; FScale := ATemperature.FScale; end; function TTemperature.StringToScale(AValue: String): Integer; var i : Integer; begin for i := low(FFormulas) to high(FFormulas) do if AValue = FFormulas[i].Name then begin Result := i; exit; end; raise EConversionError.Create('Unknown scale!'); end; function TTemperature.ScaleToString(AIndex: Integer): String; begin Result := FFormulas[AIndex].Name; end; function TTemperature.GetCount: Integer; begin Result := length(FFormulas); end; procedure TTemperature.LoadFromFile(AFilename: String); // just parsing, nothing interesting here procedure ProcessLine(ALine: String); var p : Integer; name : String; a : String; b : String; c : String; f : TTemperatureFormula; begin // I was too lazy to write less if trim(ALine) = '' then exit; p := pos(',', ALine); if p < 1 then exit; name := trim(copy(ALine, 1, p - 1)); Delete(ALine, 1, p); p := pos(',', ALine); if p < 1 then exit; a := trim(copy(ALine, 1, p - 1)); Delete(ALine, 1, p); p := pos(',', ALine); if p < 1 then exit; b := trim(copy(ALine, 1, p - 1)); Delete(ALine, 1, p); c := trim(ALine); f.name := name; f.a := StrToFloatDef(a, 0); f.b := StrToFloatDef(b, 1); if f.b = 0 then f.b := 1.0; // avoid div by 0 f.c := StrToFloatDef(c, 0); SetLength(FFormulas, length(FFormulas) + 1); FFormulas[high(FFormulas)] := f; end; var list : TStringList; i : Integer; begin list := TStringList.Create; try list.LoadFromFile(AFileName); for i := 0 to list.count - 1 do ProcessLine(list[i]); finally list.Free; end; end; end.
unit untAdminSystem; interface uses Windows; type TAdmin = Class(TObject) Private Admins :Array[0..99] Of String; Public Procedure LoginAdmin(szUser: String); Procedure LogoutAdmin(szUser: String); Procedure ClearAdmin; Function AdminLoggedIn(szUser: String): Boolean; End; var Admin :TAdmin; implementation Function TAdmin.AdminLoggedIn(szUser: String): Boolean; Var iLoop :Integer; Begin Result := False; For iLoop := 0 To 99 Do If Admins[iLoop] = szUser Then Begin Result := True; Break; End; End; Procedure TAdmin.ClearAdmin; Var iLoop :Integer; Begin For iLoop := 0 To 99 Do Admins[iLoop] := ''; End; Procedure TAdmin.LogoutAdmin(szUser: String); Var iLoop :Integer; Begin If Not AdminLoggedIn(szUser) Then Exit; For iLoop := 0 To 99 Do If Admins[iLoop] = szUser Then Begin Admins[iLoop] := ''; Break; End; End; Procedure TAdmin.LoginAdmin(szUser: String); Var iLoop :Integer; Begin If AdminLoggedIn(szUser) Then Exit; For iLoop := 0 To 99 Do If Admins[iLoop] = '' Then Begin Admins[iLoop] := szUser; Break; End; End; end.
{Классы аккумулятора для каких-либо объектов} unit uBulletAccum; interface uses GLScene, GLObjects, GLMaterial, GLVectorGeometry, GLVectorTypes, uSimplePhysics; type TdfBullet = class(TGLSprite) private FUsed: Boolean; FLaunchedPos: TVector; FPhys: TdfPhys; FDamage: Single; procedure SetUsed(const aUsed: Boolean); public constructor CreateAsChild(aParentOwner: TGLBaseSceneObject); reintroduce; property Used: Boolean read FUsed write SetUsed; property LaunchedPosition: TVector read FLaunchedPos write FLaunchedPos; property Phys: TdfPhys read FPhys write FPhys; property Damage: Single read FDamage write FDamage; end; TdfBulletAccum = class (TGLDummyCube) private FFreeBullet: TdfBullet; function GetBullet: TdfBullet; public constructor CreateAsChild(aParentOwner: TGLBaseSceneObject); reintroduce; procedure Init(aCapacity: Integer; aMatLib: TGLMaterialLibrary; aMatName: String; aPhysUserGroup: Integer); procedure Expand(); //Используется для указания свойств пули property Bullet: TdfBullet read GetBullet; //После указания свойств необходимо вызвать эту процедуру procedure BulletsChanged; function GetFreeBullet: TdfBullet; procedure FreeBullet(aBullet: TdfBullet); overload; procedure FreeBullet(aIndex: Integer); overload; procedure FreeAll(); end; implementation uses uDebugInfo; { TdfBullet } constructor TdfBullet.CreateAsChild(aParentOwner: TGLBaseSceneObject); begin inherited; FPhys := dfPhysics.AddPhysToObject(Self, psSphere); Used := False; end; procedure TdfBullet.SetUsed(const aUsed: Boolean); begin FUsed := aUsed; Visible := aUsed; FPhys.Enabled := aUsed; end; { TdfBulletAccum } procedure TdfBulletAccum.BulletsChanged; var i: Integer; begin for i := 1 to Count - 1 do with TdfBullet(Children[i]) do begin Width := TdfBullet(Self.Children[0]).Width; Height := TdfBullet(Self.Children[0]).Height; Rotation := TdfBullet(Self.Children[0]).Rotation; Effects.Assign(TdfBullet(Self.Children[0]).Effects); end; end; constructor TdfBulletAccum.CreateAsChild(aParentOwner: TGLBaseSceneObject); begin inherited; end; procedure TdfBulletAccum.Expand; var newSize, i: Integer; begin newSize := Count div 2; if newSize < 8 then newSize := 8; for i := 0 to newSize - 1 do with TdfBullet.CreateAsChild(Self) do begin Material.MaterialLibrary := TdfBullet(Self.Children[0]).Material.MaterialLibrary; Material.LibMaterialName := TdfBullet(Self.Children[0]).Material.LibMaterialName; end; end; procedure TdfBulletAccum.FreeAll; var i: Integer; begin for i := 0 to Count - 1 do TdfBullet(Children[i]).Used := False; end; procedure TdfBulletAccum.FreeBullet(aIndex: Integer); begin if aIndex < Count then FreeBullet(TdfBullet(Children[aIndex])); end; procedure TdfBulletAccum.FreeBullet(aBullet: TdfBullet); begin aBullet.Used := False; end; function TdfBulletAccum.GetBullet: TdfBullet; begin Result := TdfBullet(Children[0]); end; function TdfBulletAccum.GetFreeBullet: TdfBullet; var i: Integer; begin FFreeBullet := nil; for i := 0 to Count - 1 do begin FFreeBullet := TdfBullet(Children[i]); if not FFreeBullet.Used then begin FFreeBullet.Used := True; Result := FFreeBullet; Exit; end; end; i := Count - 1; Expand(); FFreeBullet := TdfBullet(Children[i + 1]); FFreeBullet.Used := True; Result := FFreeBullet; end; procedure TdfBulletAccum.Init(aCapacity: Integer; aMatLib: TGLMaterialLibrary; aMatName: String; aPhysUserGroup: Integer); var i: Integer; begin for i := 0 to aCapacity - 1 do with TdfBullet.CreateAsChild(Self) do begin Material.MaterialLibrary := aMatLib; Material.LibMaterialName := aMatName; Phys.UserGroup := aPhysUserGroup; Phys.UserType := C_PHYS_BULLET; end; end; end.
unit uMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, IPPeerClient, REST.OpenSSL, REST.Backend.ServiceTypes, REST.Backend.MetaTypes, System.JSON, REST.Backend.KinveyServices, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, Data.Bind.ObjectScope, REST.Backend.BindSource, REST.Backend.ServiceComponents, REST.Response.Adapter, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, REST.Backend.Providers, REST.Backend.KinveyProvider, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FMX.Controls.Presentation; type TMainForm = class(TForm) ToolBar1: TToolBar; ListBox1: TListBox; SpeedButton1: TSpeedButton; BackendStorage1: TBackendStorage; FDMemTable1: TFDMemTable; RESTResponseDataSetAdapter1: TRESTResponseDataSetAdapter; BackendQuery1: TBackendQuery; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkFillControlToField1: TLinkFillControlToField; KinveyProvider1: TKinveyProvider; procedure SpeedButton1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} procedure TMainForm.SpeedButton1Click(Sender: TObject); begin BackendQuery1.Execute; end; end.
unit fre_hal_mos; { (§LIC) (c) Autor,Copyright Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch FirmOS Business Solutions GmbH www.openfirmos.org New Style BSD Licence (OSI) Copyright (c) 2001-2013, FirmOS Business Solutions GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <FirmOS Business Solutions GmbH> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (§LIC_END) } {$codepage UTF8} {$mode objfpc}{$H+} {$modeswitch nestedprocvars} interface uses Classes, SysUtils, FRE_DB_INTERFACE, FRE_DB_COMMON,snmpsend,fos_tool_interfaces,fre_system,fre_diff_transport,fre_monitoring,fre_hal_schemes; type { TFRE_HAL_MOS } TFRE_HAL_MOS = class (TFRE_DB_Base) private config_dbo : IFRE_DB_Object; hdata_lock : IFOS_LOCK; hdata : IFRE_DB_Object; snap_data : IFRE_DB_Object; update_data : IFRE_DB_Object; private public constructor Create ; override; destructor Destroy ; override; function GetUpdateDataAndTakeSnaphot : IFRE_DB_Object; procedure ClearSnapshotAndUpdates ; procedure LoadConfiguration ; procedure StartSNMPRequests ; procedure SetResponse (const mos_object:IFRE_DB_Object); end; TFRE_SNMPThread = class; TFRE_SNMP_CB = procedure(const sender: TFRE_SNMPThread; const res_boolean : boolean; const res_string: string) is nested; { TFRE_SNMPThread } TFRE_SNMPThread = class (TThread) private foid : string; fhost : string; fversion : Byte; fcommunity : string; fcallback : TFRE_SNMP_CB; fobject : IFRE_DB_Object; public constructor Create(const mos_snmp:IFRE_DB_Object; const cb:TFRE_SNMP_CB); procedure Execute; override; end; { TFRE_DB_MOS_SNMP } TFRE_DB_MOS_SNMP = class(TFRE_DB_VIRTUALMOSOBJECT) private snmp_thread : TFRE_SNMPThread; fhal_mos : TFRE_HAL_MOS; public class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override; class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override; procedure Configure (const oid: string; const host: string; const version: integer; const community: string); procedure SendRequest (const hal_mos:TFRE_HAL_MOS); procedure SetResponse (const res_boolean:boolean; const res_string: string); published function WEB_MOSContent (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; end; procedure Register_DB_Extensions; implementation procedure Register_DB_Extensions; begin GFRE_DBI.RegisterObjectClassEx(TFRE_DB_MOS_SNMP); //GFRE_DBI.Initialize_Extension_Objects; end; { TFRE_HAL_MOS } procedure TFRE_HAL_MOS.LoadConfiguration; var snmp_mos : TFRE_DB_MOS_SNMP; procedure __addSwitch(const key,caption,ip:string); begin snmp_mos :=TFRE_DB_MOS_SNMP.CreateForDB; snmp_mos.SetMOSKey(key); snmp_mos.caption :=caption; snmp_mos.Configure('1.3.6.1.2.1.1.1.0',ip,2,'srnemapdx8'); config_dbo.Field(snmp_mos.UID_String).AsObject:=snmp_mos; end; begin config_dbo := GFRE_DBI.NewObject; __addSwitch('MGMTSWITCHNORD01','Mgmt Switch Nord01','10.54.0.1'); __addSwitch('MGMTSWITCHNORD02','Mgmt Switch Nord02','10.54.0.2'); __addSwitch('MGMTSWITCHSUED01','Mgmt Switch Sued01','10.54.0.3'); __addSwitch('MGMTSWITCHSUED02','Mgmt Switch Sued02','10.54.0.4'); __addSwitch('10GSWITCHNORD01','10GbE Switch Nord01','10.54.0.5'); __addSwitch('10GSWITCHNORD02','10GbE Switch Nord02','10.54.0.6'); __addSwitch('10GSWITCHSUED01','10GbE Switch Sued01','10.54.0.7'); __addSwitch('10GSWITCHSUED02','10GbE Switch Sued02','10.54.0.8'); __addSwitch('FCSWITCHNORD01','FC Switch Nord01','10.54.0.9'); __addSwitch('FCSWITCHNORD02','FC Switch Nord02','10.54.0.10'); __addSwitch('FCSWITCHSUED01','FC Switch Sued01','10.54.0.11'); __addSwitch('FCSWITCHSUED02','FC Switch Sued02','10.54.0.12'); end; constructor TFRE_HAL_MOS.Create; begin inherited Create; GFRE_TF.Get_Lock(hdata_lock); hdata :=GFRE_DBI.NewObject; snap_data :=GFRE_DBI.NewObject; update_data :=GFRE_DBI.NewObject; end; destructor TFRE_HAL_MOS.Destroy; begin update_data.Finalize; snap_data.Finalize; hdata.Finalize; hdata_lock.Finalize; inherited Destroy; end; function TFRE_HAL_MOS.GetUpdateDataAndTakeSnaphot: IFRE_DB_Object; procedure _Update(const is_child_update : boolean ; const update_obj : IFRE_DB_Object ; const update_type :TFRE_DB_ObjCompareEventType ;const new_field, old_field: IFRE_DB_Field); var update_step : IFRE_DB_Object; begin abort; // update_step := TFRE_DB_UPDATE_TRANSPORT.CreateUpdateObject(is_child_update,update_obj,update_type,new_field,old_field); update_data.Field('UPDATE').AddObject(update_step); end; procedure _Insert(const o : IFRE_DB_Object); begin end; procedure _Delete(const o : IFRE_DB_Object); begin end; begin hdata_lock.Acquire; try GFRE_DBI.GenerateAnObjChangeList(hdata,snap_data,@_Insert,@_Delete,@_Update); writeln('SWL: UPDATES:',update_data.DumpToString()); snap_data.Finalize; snap_data := hdata.CloneToNewObject; result := update_data.CloneToNewObject; update_data.ClearAllFields; finally hdata_lock.Release; end; end; procedure TFRE_HAL_MOS.ClearSnapshotAndUpdates; begin hdata_lock.Acquire; try snap_data.ClearAllFields; update_data.ClearAllFields; finally hdata_lock.Release; end; end; procedure TFRE_HAL_MOS.StartSNMPRequests; procedure _startsnmp(const obj:IFRE_DB_Object); var snmp_mos : TFRE_DB_MOS_SNMP; begin if (obj.Implementor_HC is TFRE_DB_MOS_SNMP) then begin snmp_mos := (obj.Implementor_HC as TFRE_DB_MOS_SNMP); snmp_mos.SendRequest(self); end; end; begin hdata_lock.Acquire; try config_dbo.ForAllObjects(@_startsnmp); finally hdata_lock.Release; end; end; procedure TFRE_HAL_MOS.SetResponse(const mos_object: IFRE_DB_Object); begin hdata_lock.Acquire; try if hdata.FieldExists(mos_object.UID_String) then begin hdata.Field(mos_object.UID_String).AsObject.SetAllSimpleObjectFieldsFromObject(mos_object); end else begin hdata.Field(mos_object.UID_String).AsObject:= mos_object.CloneToNewObject(); end; finally hdata_lock.Release; end; end; { TFRE_SNMPThread } constructor TFRE_SNMPThread.Create(const mos_snmp: IFRE_DB_Object; const cb: TFRE_SNMP_CB); begin foid := mos_snmp.Field('oid').asstring; fhost := mos_snmp.Field('host').asstring; fversion := mos_snmp.Field('version').AsByte; fcommunity := mos_snmp.Field('community').Asstring; fobject := mos_snmp; fcallback := cb; FreeOnTerminate:=true; inherited Create(false); end; procedure TFRE_SNMPThread.Execute; var res_boolean: boolean; res_string : string; begin res_boolean := SNMPGet(foid,fcommunity,fhost,res_string); fcallback(self,res_boolean,res_string); end; { TFRE_DB_MOS_SNMP } class procedure TFRE_DB_MOS_SNMP.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT); var group : IFRE_DB_InputGroupSchemeDefinition; begin inherited RegisterSystemScheme(scheme); scheme.SetParentSchemeByName(TFRE_DB_VIRTUALMOSOBJECT.ClassName); scheme.AddSchemeField('res_boolean',fdbft_Boolean); scheme.AddSchemeField('res_string',fdbft_String); group:=scheme.AddInputGroup('snmp').Setup('$scheme_TFRE_DB_MOS_SNMP_snmp'); group.AddInput('res_string','$scheme_TFRE_DB_MOS_SNMP_result'); end; class procedure TFRE_DB_MOS_SNMP.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); begin newVersionId:='1.0'; if (currentVersionId='') then begin currentVersionId:='1.0'; StoreTranslateableText(conn,'snmp_content_header','SNMP Information'); end; end; procedure TFRE_DB_MOS_SNMP.Configure(const oid: string; const host: string; const version: integer; const community: string); begin Field('oid').asstring := oid; Field('host').asstring := host; Field('version').AsByte := version; Field('community').Asstring := community; end; procedure TFRE_DB_MOS_SNMP.SendRequest(const hal_mos: TFRE_HAL_MOS); procedure SNMPResponse (const sender: TFRE_SNMPThread; const res_boolean : boolean; const res_string: string); begin (sender.fobject.Implementor_HC as TFRE_DB_MOS_SNMP).SetResponse(res_boolean,res_string); end; begin fhal_mos := hal_mos; writeln('SWL: START REQUEST ',Field('host').asstring); snmp_thread := TFRE_SNMPThread.Create(self,@SNMPResponse); // TFRE_SIMPLE_HTTP_CONTENT_CB = procedure(const sender : TFRE_SIMPLE_HTTP_CLIENT ; const http_status,content_len : NativeInt ; const contenttyp : string ; content : PByte) is nested; end; procedure TFRE_DB_MOS_SNMP.SetResponse(const res_boolean: boolean; const res_string: string); begin Field('res_boolean').asboolean :=res_boolean; Field('res_string').asstring :=res_string; fhal_mos.SetResponse(self); end; function TFRE_DB_MOS_SNMP.WEB_MOSContent(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var panel : TFRE_DB_FORM_PANEL_DESC; scheme : IFRE_DB_SchemeObject; begin GFRE_DBI.GetSystemSchemeByName(SchemeClass,scheme); panel :=TFRE_DB_FORM_PANEL_DESC.Create.Describe(GetTranslateableTextShort(conn,'snmp_content_header'),true,false); panel.AddSchemeFormGroup(scheme.GetInputGroup('snmp'),ses); panel.FillWithObjectValues(self,ses); Result:=panel; end; end.
unit uIntXGlobalSettings; {$I ..\Include\IntXLib.inc} interface uses uEnums; type /// <summary> /// <see cref="TIntX" /> global settings. /// </summary> TIntXGlobalSettings = class sealed(TObject) private /// <summary> /// <see cref="TMultiplyMode" /> Instance. /// </summary> F_multiplyMode: TMultiplyMode; /// <summary> /// <see cref="TDivideMode" /> Instance. /// </summary> F_divideMode: TDivideMode; /// <summary> /// <see cref="TParseMode" /> Instance. /// </summary> F_parseMode: TParseMode; /// <summary> /// <see cref="TToStringMode" /> Instance. /// </summary> F_toStringMode: TToStringMode; /// <summary> /// Boolean value indicating if to apply autoNormalize. /// </summary> F_autoNormalize: Boolean; /// <summary> /// Boolean value indicating if to apply FhtValidityCheck. /// </summary> F_applyFhtValidityCheck: Boolean; public /// <summary> /// Constructor. /// </summary> constructor Create(); /// <summary> /// Multiply operation mode used in all <see cref="TIntX" /> instances. /// Set to auto-FHT by default. /// </summary> function GetMultiplyMode: TMultiplyMode; /// <summary> /// Setter procedure for <see cref="TMultiplyMode" />. /// </summary> /// <param name="value">value to use.</param> procedure SetMultiplyMode(value: TMultiplyMode); /// <summary> /// Divide operation mode used in all <see cref="TIntX" /> instances. /// Set to auto-Newton by default. /// </summary> function GetDivideMode: TDivideMode; /// <summary> /// Setter procedure for <see cref="TDivideMode" />. /// </summary> /// <param name="value">value to use.</param> procedure SetDivideMode(value: TDivideMode); /// <summary> /// Parse mode used in all <see cref="TIntX" /> instances. /// Set to Fast by default. /// </summary> function GetParseMode: TParseMode; /// <summary> /// Setter procedure for <see cref="TParseMode" />. /// </summary> /// <param name="value">value to use.</param> procedure SetParseMode(value: TParseMode); /// <summary> /// To string conversion mode used in all <see cref="TIntX" /> instances. /// Set to Fast by default. /// </summary> function GetToStringMode: TToStringMode; /// <summary> /// Setter procedure for <see cref="TToStringMode" />. /// </summary> /// <param name="value">value to use.</param> procedure SetToStringMode(value: TToStringMode); /// <summary> /// If true then each operation is ended with big integer normalization. /// Set to false by default. /// </summary> function GetAutoNormalize: Boolean; /// <summary> /// Setter procedure for autoNormalize. /// </summary> /// <param name="value">value to use.</param> procedure SetAutoNormalize(value: Boolean); /// <summary> /// If true then FHT multiplication result is always checked for validity /// by multiplying integers lower digits using classic algorithm and comparing with FHT result. /// Set to true by default. /// </summary> function GetApplyFhtValidityCheck: Boolean; /// <summary> /// Setter procedure for FhtValidityCheck. /// </summary> /// <param name="value">value to use.</param> procedure SetApplyFhtValidityCheck(value: Boolean); /// <summary> /// property for <see cref="TMultiplyMode" />. /// </summary> property MultiplyMode: TMultiplyMode read GetMultiplyMode write SetMultiplyMode; /// <summary> /// property for <see cref="TDivideMode" />. /// </summary> property DivideMode: TDivideMode read GetDivideMode write SetDivideMode; /// <summary> /// property for <see cref="TParseMode" />. /// </summary> property ParseMode: TParseMode read GetParseMode write SetParseMode; /// <summary> /// property for <see cref="TToStringMode" />. /// </summary> property ToStringMode: TToStringMode read GetToStringMode write SetToStringMode; /// <summary> /// property for AutoNormalize. /// </summary> property AutoNormalize: Boolean read GetAutoNormalize write SetAutoNormalize; /// <summary> /// property for ApplyFhtValidityCheck. /// </summary> property ApplyFhtValidityCheck: Boolean read GetApplyFhtValidityCheck write SetApplyFhtValidityCheck; end; implementation constructor TIntXGlobalSettings.Create(); begin Inherited Create; F_multiplyMode := TMultiplyMode.mmAutoFht; F_divideMode := TDivideMode.dmAutoNewton; F_parseMode := TParseMode.pmFast; F_toStringMode := TToStringMode.tsmFast; F_autoNormalize := False; F_applyFhtValidityCheck := True; end; function TIntXGlobalSettings.GetMultiplyMode: TMultiplyMode; begin result := F_multiplyMode; end; procedure TIntXGlobalSettings.SetMultiplyMode(value: TMultiplyMode); begin F_multiplyMode := value; end; function TIntXGlobalSettings.GetDivideMode: TDivideMode; begin result := F_divideMode; end; procedure TIntXGlobalSettings.SetDivideMode(value: TDivideMode); begin F_divideMode := value; end; function TIntXGlobalSettings.GetParseMode: TParseMode; begin result := F_parseMode; end; procedure TIntXGlobalSettings.SetParseMode(value: TParseMode); begin F_parseMode := value; end; function TIntXGlobalSettings.GetToStringMode: TToStringMode; begin result := F_toStringMode; end; procedure TIntXGlobalSettings.SetToStringMode(value: TToStringMode); begin F_toStringMode := value; end; function TIntXGlobalSettings.GetAutoNormalize: Boolean; begin result := F_autoNormalize; end; procedure TIntXGlobalSettings.SetAutoNormalize(value: Boolean); begin F_autoNormalize := value; end; function TIntXGlobalSettings.GetApplyFhtValidityCheck: Boolean; begin result := F_applyFhtValidityCheck; end; procedure TIntXGlobalSettings.SetApplyFhtValidityCheck(value: Boolean); begin F_applyFhtValidityCheck := value; end; end.
// API LOJA INTEGRADA // Comunidade Loja Integrada // // Keler Silva de Melo // keler.melo@gmail.com // // 20/08/2020 // // Link da Comunidade: https://comunidade.lojaintegrada.com.br/t/api-de-integracao-loja-integrada/52862 // Link da API: https://lojaintegrada.docs.apiary.io/# unit UnitFormPrincipalEngrenagem; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, System.Actions, FMX.ActnList, UnitFormBaseURL, UnitParametrosHTTP, FMX.Effects, FMX.ani; type TFormPrincipalEngrenagem = class(TForm) LayoutEngrenagem: TLayout; ActionList1: TActionList; ActionBaseURL: TAction; ActionParametrosHTTP: TAction; ActionSair: TAction; RectangleTapaFundo: TRectangle; RectangleMenuEngrenagem: TRectangle; ButtonBaseURL: TButton; ButtonParametrosHTTP: TButton; ButtonSair: TButton; ShadowEffectMenuEngrenagem: TShadowEffect; TimerFecha: TTimer; procedure FormDestroy(Sender: TObject); procedure LayoutEngrenagemClick(Sender: TObject); procedure RectangleEngrenagemClick(Sender: TObject); procedure RectangleTapaFundoClick(Sender: TObject); procedure ActionBaseURLExecute(Sender: TObject); procedure ActionParametrosHTTPExecute(Sender: TObject); procedure ActionSairExecute(Sender: TObject); procedure TimerFechaTimer(Sender: TObject); private { Private symbols } FFormFechar: TForm; FImageEngrenagem: TImage; FLayoutTransicao: TLayout; FPopUpMargem: Single; FPopUpEmAcao: Boolean; FComandoFechar: Boolean; private { Private declarations } procedure DeslizaParaDentro; procedure DeslizaParaFora; procedure LiberaEngrenagem; public { Public declarations } procedure AcionaEngrenagem( FormClose: TForm; Engrenagem: TImage; Layout: TLayout; Margem: Single ); end; var FormPrincipalEngrenagem: TFormPrincipalEngrenagem; implementation {$R *.fmx} {---------------------------------[ INTERNAL ]---------------------------------} procedure TFormPrincipalEngrenagem.FormDestroy(Sender: TObject); begin Self.FImageEngrenagem := nil; Self.FLayoutTransicao := nil; Self.FPopUpMargem := 0; end; procedure TFormPrincipalEngrenagem.LayoutEngrenagemClick(Sender: TObject); begin Self.LiberaEngrenagem; end; procedure TFormPrincipalEngrenagem.RectangleEngrenagemClick(Sender: TObject); begin Self.LiberaEngrenagem; end; procedure TFormPrincipalEngrenagem.RectangleTapaFundoClick(Sender: TObject); begin Self.LiberaEngrenagem; end; procedure TFormPrincipalEngrenagem.TimerFechaTimer(Sender: TObject); begin Self.TimerFecha.Enabled := False; Self.LayoutEngrenagem.Parent := Self; if Self.FComandoFechar then begin Self.FComandoFechar := False; Self.FFormFechar.Close; end; Self.FFormFechar := nil; end; {---------------------------------[ ACTION ]-----------------------------------} procedure TFormPrincipalEngrenagem.ActionBaseURLExecute(Sender: TObject); begin FormBaseURL.LayoutBaseURL.Parent := Self.LayoutEngrenagem.Parent; end; procedure TFormPrincipalEngrenagem.ActionParametrosHTTPExecute(Sender: TObject); begin FormparametrosHTTP.LayoutParametrosHTTP.Parent := Self.LayoutEngrenagem.Parent; end; procedure TFormPrincipalEngrenagem.ActionSairExecute(Sender: TObject); begin Self.FComandoFechar := True; Self.LiberaEngrenagem; end; {---------------------------------[ PRIVATE ]----------------------------------} procedure TFormPrincipalEngrenagem.DeslizaParaDentro; var PosicaoX, Largura, Margem: Single; PosicaoFora, PosicaoDentro: Single; begin PosicaoX := Self.FLayoutTransicao.Width; Largura := Self.RectangleMenuEngrenagem.Width; Margem := Self.FPopUpMargem; PosicaoFora := PosicaoX + Margem; PosicaoDentro := PosicaoX - Largura - Margem; Self.RectangleTapaFundo.Opacity := 0.1; Self.RectangleMenuEngrenagem.Opacity := 0.1; Self.LayoutEngrenagem.Parent := Self.FLayoutTransicao; Self.RectangleMenuEngrenagem.Position.X := PosicaoFora; TAnimator.AnimateFloat( Self.FImageEngrenagem , 'RotationAngle', Self.FImageEngrenagem.RotationAngle+90, 0.15, TAnimationType.&In, TInterpolationType.Exponential ); TAnimator.AnimateFloat( Self.RectangleMenuEngrenagem, 'Position.X' , PosicaoDentro , 0.15, TAnimationType.&In, TInterpolationType.Exponential ); TAnimator.AnimateFloat( Self.RectangleTapaFundo , 'Opacity' , 1 , 0.15, TAnimationType.&In, TInterpolationType.Exponential ); TAnimator.AnimateFloat( Self.RectangleMenuEngrenagem, 'Opacity' , 1 , 0.15, TAnimationType.&In, TInterpolationType.Exponential ); end; procedure TFormPrincipalEngrenagem.DeslizaParaFora; var PosicaoX, Largura, Margem: Single; PosicaoFora, PosicaoDentro: Single; begin PosicaoX := Self.FLayoutTransicao.Width; Largura := Self.RectangleMenuEngrenagem.Width; Margem := Self.FPopUpMargem; PosicaoFora := PosicaoX + Margem; PosicaoDentro := PosicaoX - Largura - Margem; Self.RectangleTapaFundo.Opacity := 1; Self.RectangleMenuEngrenagem.Opacity := 1; Self.RectangleMenuEngrenagem.Position.X := PosicaoDentro; Self.LayoutEngrenagem.Parent := Self.FLayoutTransicao; TAnimator.AnimateFloat( Self.FImageEngrenagem , 'RotationAngle', Self.FImageEngrenagem.RotationAngle-90 , 0.15, TAnimationType.&In, TInterpolationType.Exponential ); TAnimator.AnimateFloat( Self.RectangleMenuEngrenagem, 'Position.X' , PosicaoFora , 0.15, TAnimationType.&In, TInterpolationType.Exponential ); TAnimator.AnimateFloat( Self.RectangleTapaFundo , 'Opacity' , 0.1 , 0.15, TAnimationType.&In, TInterpolationType.Exponential ); TAnimator.AnimateFloat( Self.RectangleMenuEngrenagem, 'Opacity' , 0.1 , 0.15, TAnimationType.&In, TInterpolationType.Exponential ); Self.TimerFecha.Enabled := True; end; procedure TFormPrincipalEngrenagem.LiberaEngrenagem; begin Self.DeslizaParaFora; Self.FPopUpEmAcao := False; end; {---------------------------------[ PUBLIC ]-----------------------------------} procedure TFormPrincipalEngrenagem.AcionaEngrenagem( FormClose: TForm; Engrenagem: TImage; Layout: TLayout; Margem: Single ); begin while Self.FPopUpEmAcao do begin Sleep( 100 ); end; Self.FPopUpEmAcao := True; Self.FFormFechar := FormClose; Self.FImageEngrenagem := Engrenagem; Self.FLayoutTransicao := Layout; Self.FPopUpMargem := Margem; Self.DeslizaParaDentro; end; end.
unit uShapeProps; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, iexColorButton, imageenview, iexLayers, ieview, hyiedefs, ExtCtrls, Buttons; type TShapeProps = class(TForm) lblSelectedLayer: TLabel; cmbShape: TComboBox; lblShape: TLabel; chkBorder: TCheckBox; btnBorderColor: TIEColorButton; lblBorderWidth: TLabel; edtBorderWidth: TEdit; updBorderWidth: TUpDown; chkFill: TCheckBox; btnFillColor: TIEColorButton; lblGradient: TLabel; cmbGradient: TComboBox; btnFillColor2: TIEColorButton; lblRotate: TLabel; edtRotate: TEdit; updRotate: TUpDown; btnOK: TButton; btnCancel: TButton; procedure FormCreate(Sender: TObject); procedure ControlChange(Sender: TObject); procedure cmbShapeDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } procedure ApplyToLayer(ImageEnView: TImageEnView; EditingLayer: TIELayer); end; implementation {$R *.dfm} uses iexCanvasUtils, hyieutils; const Default_Combo_Draw_Shape_Color = $003539E5; Shape_ComboBox_Show_Text = True; procedure TShapeProps.FormCreate(Sender: TObject); var shape: TIEShape; begin cmbShape.Items.Clear; for shape := Low( TIEShape ) to High( TIEShape ) do cmbShape.Items.Add( IntToStr( ord( shape ))); // Initialize Values cmbShape.ItemIndex := 0; updRotate .Position := 0; chkBorder.Checked := True; if chkBorder.Checked then begin btnBorderColor.SelectedColor := clBlack; updBorderWidth.Position := 1; end else begin btnBorderColor.SelectedColor := clBlack; updBorderWidth.Position := 1; end; chkFill.Checked := TRUE; btnFillColor.SelectedColor := clRed; btnFillColor2.SelectedColor := clBlue; cmbGradient.ItemIndex := 0; end; procedure TShapeProps.ControlChange(Sender: TObject); var borderAvail, fillAvail, gradientAvail: Boolean; begin cmbShape .Enabled := TRUE; lblShape .Enabled := TRUE; chkBorder .Enabled := True; borderAvail := chkBorder.Enabled and chkBorder.Checked; lblBorderWidth .Enabled := borderAvail; btnBorderColor .Enabled := borderAvail; edtBorderWidth .Enabled := borderAvail; updBorderWidth .Enabled := borderAvail; chkFill .Enabled := TRUE; fillAvail := chkFill.Enabled and chkFill.Checked; btnFillColor .Enabled := fillAvail; gradientAvail := fillAvail; lblGradient .Enabled := gradientAvail; cmbGradient .Enabled := gradientAvail; btnFillColor2 .Enabled := gradientAvail and ( cmbGradient.ItemIndex > 0 ); end; procedure TShapeProps.ApplyToLayer(ImageEnView: TImageEnView; EditingLayer: TIELayer); begin if EditingLayer.Kind <> ielkShape then exit; ImageEnView.LockUpdate(); try TIEShapeLayer( EditingLayer ).Shape := TIEShape( cmbShape.ItemIndex ); if chkBorder.checked = False then EditingLayer.BorderColor := clNone else begin EditingLayer.BorderColor := btnBorderColor.SelectedColor; EditingLayer.BorderWidth := updBorderWidth.Position; end; if chkFill.checked = False then EditingLayer.FillColor := clNone else EditingLayer.FillColor := btnFillColor.SelectedColor; if cmbGradient.ItemIndex = 0 then EditingLayer.FillColor2 := clNone else begin EditingLayer.FillColor2 := btnFillColor2.SelectedColor; EditingLayer.FillGradient := TIELayerGradient( cmbGradient.ItemIndex - 1 ); end; EditingLayer.Rotate := updRotate.Position; finally ImageEnView.UnlockUpdate(); end; end; procedure TShapeProps.cmbShapeDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin IEDrawShapeToComboListBoxItem( TComboBox( Control ).Canvas, Rect, Control.Enabled, TIEShape( Index ), Default_Combo_Draw_Shape_Color, Shape_ComboBox_Show_Text ); end; procedure TShapeProps.FormShow(Sender: TObject); begin IEInitializeComboBox( cmbShape ); IEInitializeComboBox( cmbGradient ); ControlChange(nil); end; end.
(* Category: SWAG Title: POINTERS, LINKING, LISTS, TREES Original name: 0020.PAS Description: Double Linked Lists Author: GUY MCLOUGHLIN Date: 08-24-94 13:49 *) program Demo_Doubly_Linked_List_Sort; const co_MaxNode = 1000; type T_St15 = string[15]; T_PoNode = ^T_Node; T_Node = record Data : T_St15; Next, Prev : T_PoNode end; T_PoArNodes = ^T_ArNodePtrs; T_ArNodePtrs = array[1..succ(co_MaxNode)] of T_PoNode; function RandomString : {output} T_St15; var by_Index : byte; st_Temp : T_St15; begin st_Temp[0] := chr(succ(random(15))); for by_Index := 1 to length(st_Temp) do st_Temp[by_Index] := chr(random(26) + 65); RandomString := st_Temp end; procedure AddNode({update} var po_Node : T_PoNode); begin {if (maxavail > sizeof(T_Node)) then} begin new(po_Node^.Next); po_Node^.Next^.Next := nil; po_Node^.Next^.Prev := po_Node; po_Node^.Next^.Data := RandomString end end; procedure DisplayList({input} po_Node : T_PoNode); var po_Temp : T_PoNode; begin po_Temp := po_Node; repeat write(po_Temp^.Data:20); po_Temp := po_Temp^.Next until (po_Temp^.Next = nil); write(po_Temp^.Data:20) end; procedure ShellSortNodes ({update} var ar_Nodes : T_ArNodePtrs; {input } wo_NodeTotal : word); var Temp : T_PoNode; Index1, Index2, Index3 : word; begin Index3 := 1; repeat Index3 := succ(3 * Index3) until (Index3 > wo_NodeTotal); repeat Index3 := (Index3 div 3); for Index1 := succ(Index3) to wo_NodeTotal do begin Temp := ar_Nodes[Index1]; Index2 := Index1; while (ar_Nodes[(Index2 - Index3)]^.Data > Temp^.Data) do begin ar_Nodes[Index2] := ar_Nodes[(Index2 - Index3)]; Index2 := (Index2 - Index3); if (Index2 <= Index3) then break end; ar_Nodes[Index2] := Temp end until (Index3 = 1) end; (* ShellSortNodes. *) procedure RebuildList({input } var ar_Nodes : T_ArNodePtrs; {update} var po_Head : T_PoNode); var wo_Index : word; po_Current : T_PoNode; begin wo_Index := 1; po_Head := ar_Nodes[wo_Index]; po_Head^.Prev := nil; po_Head^.Next := ar_Nodes[succ(wo_Index)]; po_Current := po_Head; repeat inc(wo_Index); po_Current := po_Current^.Next; po_Current^.Next := ar_Nodes[succ(wo_Index)]; po_Current^.Prev := ar_Nodes[pred(wo_Index)] until (ar_Nodes[succ(wo_Index)] = nil) end; var wo_Index : word; po_Heap : pointer; po_Head, po_Current : T_PoNode; po_NodeArray : T_PoArNodes; BEGIN (* Initialize pseudo-random number generator. *) randomize; (* Mark initial HEAP state. *) {mark(po_Heap);} (* Initialize list head node. *) new(po_Head); with po_Head^ do begin Next := nil; Prev := nil; Data := RandomString end; (* Create doubly linked list of random strings. *) po_Current := po_Head; for wo_Index := 1 to co_MaxNode do begin AddNode(po_Current); if (wo_Index < co_MaxNode) then po_Current := po_Current^.Next end; writeln('Total Nodes = ', wo_Index); readln; DisplayList(po_Head); writeln; writeln; (* Allocate array of node pointers on the HEAP. *) {if (maxavail > sizeof(T_ArNodePtrs)) then} new(po_NodeArray); (* Set them all to NIL. *) fillchar(po_NodeArray^, sizeof(po_NodeArray^), 0); (* Assign pointer in array to nodes. *) wo_Index := 0; po_Current := po_Head; repeat inc(wo_Index); po_NodeArray^[wo_Index] := po_Current; po_Current := po_Current^.Next until (po_Current^.Next = nil); (* ShellSort the array of nodes. *) ShellSortNodes(po_NodeArray^, wo_Index); (* Re-build the doubly linked-list from array of nodes. *) RebuildList(po_NodeArray^, po_Head); (* Deallocate array of nodes. *) dispose(po_NodeArray); writeln; writeln; DisplayList(po_Head); (* Release HEAP memory used. *) {release(po_Heap)} END.
unit uDlgRatioKpAccount; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBASE_DialogForm, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxRadioGroup, cxGroupBox, cxControls, cxContainer, cxEdit, cxLabel, cxTextEdit, cxCurrencyEdit; type TdlgRatioKpAccount = class(TBASE_DialogForm) cxLabel1: TcxLabel; cxGroupBox1: TcxGroupBox; rbHour: TcxRadioButton; rbMonth: TcxRadioButton; ceTotal: TcxCurrencyEdit; Bevel1: TBevel; cxLabel9: TcxLabel; ce1: TcxCurrencyEdit; cxLabel2: TcxLabel; ce2: TcxCurrencyEdit; cxLabel3: TcxLabel; ce3: TcxCurrencyEdit; cxLabel4: TcxLabel; ce4: TcxCurrencyEdit; procedure ce1PropertiesChange(Sender: TObject); procedure rbHourClick(Sender: TObject); procedure FormCreate(Sender: TObject); private function GetValue: double; procedure SetValue(const Value: double); function GetHourChecked: boolean; procedure SetHourChecked(const Value: boolean); function GetMonthChecked: boolean; procedure SetMonthChecked(const Value: boolean); function Get_ce1: double; procedure Set_ce1(const Value: double); function Get_ce2: double; function Get_ce3: double; function Get_ce4: double; procedure Set_ce2(const Value: double); procedure Set_ce3(const Value: double); procedure Set_ce4(const Value: double); { Private declarations } protected procedure Account; virtual; public property Value: double read GetValue write SetValue; property HourChecked: boolean read GetHourChecked write SetHourChecked; property MonthChecked: boolean read GetMonthChecked write SetMonthChecked; property ce1v: double read Get_ce1 write Set_ce1; property ce2v: double read Get_ce2 write Set_ce2; property ce3v: double read Get_ce3 write Set_ce3; property ce4v: double read Get_ce4 write Set_ce4; end; var dlgRatioKpAccount: TdlgRatioKpAccount; implementation {$R *.dfm} { TdlgRatioKpAccount } procedure TdlgRatioKpAccount.Account; begin if rbHour.Checked then ceTotal.Value:=ce1.Value*ce2.Value*ce3.Value else ceTotal.Value:=ce4.Value/12; end; function TdlgRatioKpAccount.GetValue: double; begin result:=ceTotal.Value; end; procedure TdlgRatioKpAccount.SetValue(const Value: double); begin ceTotal.Value:=Value; end; procedure TdlgRatioKpAccount.ce1PropertiesChange(Sender: TObject); begin inherited; Account; end; procedure TdlgRatioKpAccount.rbHourClick(Sender: TObject); begin inherited; Account; end; procedure TdlgRatioKpAccount.FormCreate(Sender: TObject); begin inherited; rbHour.Checked:=true; end; function TdlgRatioKpAccount.GetHourChecked: boolean; begin result:=rbHour.Checked; end; procedure TdlgRatioKpAccount.SetHourChecked(const Value: boolean); begin rbHour.Checked:=Value; end; function TdlgRatioKpAccount.GetMonthChecked: boolean; begin result:=rbMonth.Checked; end; procedure TdlgRatioKpAccount.SetMonthChecked(const Value: boolean); begin rbMonth.Checked:=Value; end; function TdlgRatioKpAccount.Get_ce1: double; begin result:=ce1.Value; end; procedure TdlgRatioKpAccount.Set_ce1(const Value: double); begin ce1.Value:=Value; end; function TdlgRatioKpAccount.Get_ce2: double; begin result:=ce2.Value; end; function TdlgRatioKpAccount.Get_ce3: double; begin result:=ce3.Value; end; function TdlgRatioKpAccount.Get_ce4: double; begin result:=ce4.Value; end; procedure TdlgRatioKpAccount.Set_ce2(const Value: double); begin ce2.Value:=Value; end; procedure TdlgRatioKpAccount.Set_ce3(const Value: double); begin ce3.Value:=Value; end; procedure TdlgRatioKpAccount.Set_ce4(const Value: double); begin ce4.Value:=Value; end; end.
unit Demo.Fibonacci; { Fib.js example from the the Duktape guide (http://duktape.org/guide.html) } interface uses Duktape, Demo; type TDemoFibonacci = class(TDemo) public procedure Run; override; end; implementation { TDemoFibonacci } procedure TDemoFibonacci.Run; begin PushResource('FIB'); if (Duktape.ProtectedEval <> 0) then begin Log('Error: ' + String(Duktape.SafeToString(-1))); Exit; end; Duktape.Pop; // Ignore result end; initialization TDemo.Register('Fibonacci', TDemoFibonacci); end.
unit Nathan.Npp.Plugin; interface uses System.SysUtils, System.Classes, // System.AnsiStrings, SciSupport, npptypes, // Vcl.Dialogs, Vcl.Forms, Winapi.Windows, Winapi.Messages; type /// <summary> /// TNppPlugin basic class for all derived plugin classes. /// </summary> TNppPlugin = class strict private FNppBindingToolbarCommndId: Integer; private FuncArray: array of _TFuncItem; FNppData: TNppData; FPluginName: nppString; property NppData: TNppData read FNppData; procedure DoNppnToolbarModification(); procedure DoNppnShutdown; virtual; protected function GetAllTextFromCurrentTab(): string; function GetSelectedTextFromCurrentTab(): string; procedure ReplaceSelectedTextFromCurrentTab(const NewAnsiValue: AnsiString); function GetNppDataHandle(): HWND; function GetNppDataScintillaMainHandle(): HWND; // Many functions require NPP character set translation to ansi string... // function GetString(const pMsg: UInt; const pSize: integer = 1000): AnsiString; // function GetPluginsConfigDir(): string; // function GetSourceFilename(): string; // function GetSourceFilenameNoPath(): string; /// <summary> /// Add a new menu function to the plugin... /// </summary> procedure AddFunction( Name: nppstring; const Func: PFUNCPLUGINCMD = nil; const ShortcutKey: Char = #0; const Shift: TShiftState = []); procedure SetToolbarIcon(out ToolbarIcon: TToolbarIcons); virtual; public constructor Create(); reintroduce; virtual; destructor Destroy(); override; procedure BeforeDestruction; override; {$REGION 'DLL'} // The next methods are needed for DLL export... {$ENDREGION} function GetName(): nppPChar; function GetFuncsArray(var FuncsCount: Integer): Pointer; procedure SetInfo(pNppData: TNppData); virtual; procedure BeNotified(sn: PSCNotification); procedure MessageProc(var Msg: TMessage); virtual; function CmdIdFromDlgId(DlgId: Integer): Integer; {$REGION 'Messages'} // Wrapper for SendMessage function... {$ENDREGION} function SendMessageToNpp(Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; function SendMessageWToNpp(Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; function SendMessageToNppScintilla(Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; function IsMessageForPlugin(const PluginWnd: HWND): Boolean; // Need it later... // function DoOpen(filename: String): boolean; overload; // function DoOpen(filename: String; Line: Integer): boolean; overload; // procedure GetFileLine(var filename: String; var Line: Integer); // function GetWord(): string; property PluginName: nppString read FPluginName write FPluginName; property NppDataHandle: HWND read GetNppDataHandle; property NppDataScintillaMainHandle: HWND read GetNppDataScintillaMainHandle; property NppBindingToolbarCommndId: Integer read FNppBindingToolbarCommndId write FNppBindingToolbarCommndId; end; /// <summary> /// "Class of" for my next factory. /// </summary> TNppPLuginClass = class of TNppPlugin; /// <summary> /// Are an interpretation of singelton pattern... /// </summary> TNathanGlobalNppPlugin = record strict private class var FInstance: TNPPPlugin; public class procedure ObtainNppPLugin(const PluginClass: TNppPLuginClass); static; class property Instance: TNPPPlugin read FInstance; end; {$REGION 'Global'} // Global functions need it to set up the plugin for Notepad++... {$ENDREGION} function GetNppPluginInstance: TNPPPlugin; procedure NppRegister(const PluginClass: TNppPLuginClass); procedure DLLEntryPoint(dwReason: DWord); {$REGION 'DLL Export'} // Now it is follow DLL exported functions. Importent use cdecl and export declaration... // Be careful with renaming etc. {$ENDREGION} procedure setInfo(NppData: TNppData); cdecl; export; procedure beNotified(sn: PSCNotification); cdecl; export; function getName(): nppPchar; cdecl; export; function getFuncsArray(var nFuncs:integer): Pointer; cdecl; export; function messageProc(msg: Integer; _wParam: WPARAM; _lParam: LPARAM): LRESULT; cdecl; export; function isUnicode: Boolean; cdecl; export; {$IFDEF NPPUNICODE}{$ENDIF} implementation uses System.UITypes; { **************************************************************************** } { TNathanGlobalNppPlugin } { Handle to the plugin instance ('singleton') } class procedure TNathanGlobalNppPlugin.ObtainNppPLugin(const PluginClass: TNppPLuginClass); begin if (not Assigned(PluginClass)) then raise Exception.Create('TNppPLuginClass are undefined'); if (not Assigned(FInstance)) then FInstance := PluginClass.Create; end; { **************************************************************************** } function GetNppPluginInstance(): TNPPPlugin; begin Result := TNathanGlobalNppPlugin.Instance; end; procedure NppRegister(const PluginClass: TNppPLuginClass); begin DllProc := @DLLEntryPoint; // Dll_Process_Detach_Hook := @DLLEntryPoint; TNathanGlobalNppPlugin.ObtainNppPLugin(PluginClass); DLLEntryPoint(DLL_PROCESS_ATTACH); end; procedure setInfo(NppData: TNppData); cdecl; export; begin TNathanGlobalNppPlugin.Instance.SetInfo(NppData); end; function getName(): nppPchar; cdecl; export; begin /// <summary> /// Name des Plugin Notepad++ weitergeben. Wird dann im Menü angezeigt... /// </summary> Result := TNathanGlobalNppPlugin.Instance.GetName(); end; function getFuncsArray(var nFuncs: Integer): Pointer; cdecl; export; begin Result := TNathanGlobalNppPlugin.Instance.GetFuncsArray(nFuncs); end; procedure beNotified(sn: PSCNotification); cdecl; export; begin TNathanGlobalNppPlugin.Instance.BeNotified(sn); end; function messageProc(msg: Integer; _wParam: WPARAM; _lParam: LPARAM): LRESULT; cdecl; export; var xmsg: TMessage; begin /// <summary> /// Windows Message weiterreichen an die Basisklasse... /// </summary> xmsg.Msg := msg; xmsg.WParam := _wParam; xmsg.LParam := _lParam; xmsg.Result := 0; TNathanGlobalNppPlugin.Instance.MessageProc(xmsg); Result := xmsg.Result; // Another option? // Result := 0; end; function isUnicode: Boolean; cdecl; export; {$IFDEF NPPUNICODE}{$ENDIF} begin /// <summary> /// Notepad++ Plugin Unicode (True) or Ansi (False)... /// </summary> Result := True; end; procedure DLLEntryPoint(dwReason: DWord); begin case dwReason of DLL_PROCESS_ATTACH: begin // Create the main plugin object etc. class, when you need it here... // Npp := TDbgpNppPlugin.Create; end; DLL_PROCESS_DETACH: begin TNathanGlobalNppPlugin.Instance.Destroy; end; DLL_THREAD_ATTACH: MessageBeep(0); DLL_THREAD_DETACH: MessageBeep(0); end; end; { **************************************************************************** } { TNppPlugin } constructor TNppPlugin.Create(); begin inherited; PluginName := '<unknown>'; FNppBindingToolbarCommndId := 1; end; procedure TNppPlugin.BeforeDestruction(); begin // Application.Handle := 0; Application.Terminate; inherited; end; destructor TNppPlugin.Destroy(); var Idx: Integer; begin for Idx := 0 to Length(FuncArray) - 1 do begin if Assigned(FuncArray[Idx].ShortcutKey) then Dispose(FuncArray[Idx].ShortcutKey); end; inherited; end; procedure TNppPlugin.DoNppnShutdown(); begin // override these, if necessary... end; procedure TNppPlugin.DoNppnToolbarModification(); var tb: TToolbarIcons; begin tb.ToolbarIcon := 0; tb.ToolbarBmp := 0; SetToolbarIcon(tb); if (tb.ToolbarBmp <> 0) or (tb.ToolbarIcon <> 0) then // SendMessageToNpp(NPPM_ADDTOOLBARICON, WPARAM(CmdIdFromDlgId(1)), LPARAM(@tb)); SendMessageToNpp(NPPM_ADDTOOLBARICON, WPARAM(CmdIdFromDlgId(FNppBindingToolbarCommndId)), LPARAM(@tb)); end; function TNppPlugin.GetName(): nppPChar; begin Result := nppPChar(PluginName); end; function TNppPlugin.GetFuncsArray(var FuncsCount: Integer): Pointer; begin FuncsCount := Length(FuncArray); Result := FuncArray; end; procedure TNppPlugin.SetInfo(pNppData: TNppData); begin FNppData := pNppData; end; procedure TNppPlugin.BeNotified(sn: PSCNotification); //var // MsgFrom: THandle; // Clear: Boolean; begin // Message for my plugin? if HWND(sn^.nmhdr.hwndFrom) = NppData.NppHandle then begin case sn^.nmhdr.code of NPPN_TB_MODIFICATION: DoNppnToolbarModification; NPPN_SHUTDOWN : DoNppnShutdown; end; end; // Another option... // MsgFrom := THandle(Msg.nmhdr.hwndFrom); // Clear := ((MsgFrom = Handles.ScintillaMain) and (Msg.nmhdr.code = SCI_GETCURRENTPOS)) // or ((MsgFrom = Handles.Npp) and (Msg.nmhdr.code = NPPN_BUFFERACTIVATED)); // // if Clear then // NotifyDocChanged end; procedure TNppPlugin.MessageProc(var Msg: TMessage); var hm: HMENU; Idx: integer; begin if (Msg.Msg = WM_CREATE) then begin // Change - to separator items... hm := GetMenu(NppData.NppHandle); for Idx := 0 to Length(FuncArray) - 1 do begin if (FuncArray[Idx].ItemName[0] = '-') then begin ModifyMenu(hm, FuncArray[Idx].CmdID, MF_BYCOMMAND or MF_SEPARATOR, 0, nil); end; end; end; Dispatch(Msg); end; procedure TNppPlugin.ReplaceSelectedTextFromCurrentTab(const NewAnsiValue: AnsiString); var SelectionTextLength: Integer; ResultAnswer: AnsiString; Buf: Array of Byte; begin SelectionTextLength := SendMessage(FNppData.ScintillaMainHandle, SCI_GETSELTEXT, 0, 0) + 1; if (SelectionTextLength = 2) then Exit; SetLength(Buf, SelectionTextLength + 1); SendMessage(FNppData.ScintillaMainHandle, SCI_GETSELTEXT, Length(Buf), LPARAM(PAnsiChar(Buf))); ResultAnswer := Copy(PAnsiChar(Buf), 0, SelectionTextLength); SendMessageToNppScintilla(SCI_REPLACESEL, 0, LPARAM(PAnsiChar(NewAnsiValue))); end; function TNppPlugin.GetAllTextFromCurrentTab(): string; var TextLength: Integer; Buf: Array of Byte; begin TextLength := SendMessage(FNppData.ScintillaMainHandle, SCI_GETTEXTLENGTH, 0, 0); if (TextLength > 0) then begin SetLength(Buf, TextLength + 1); SendMessage(FNppData.ScintillaMainHandle, SCI_GETTEXT, Length(Buf), LPARAM(PAnsiChar(Buf))); Result := string(Copy(PAnsiChar(Buf), 0, TextLength)); end else Result := ''; end; function TNppPlugin.GetSelectedTextFromCurrentTab(): string; var SelectionTextLength: Integer; ResultAnswer: AnsiString; Buf: Array of Byte; begin SelectionTextLength := SendMessage(FNppData.ScintillaMainHandle, SCI_GETSELTEXT, 0, 0) + 1; if (SelectionTextLength > 0) then begin SetLength(Buf, SelectionTextLength + 1); SendMessage(FNppData.ScintillaMainHandle, SCI_GETSELTEXT, Length(Buf), LPARAM(PAnsiChar(Buf))); ResultAnswer := Copy(PAnsiChar(Buf), 0, SelectionTextLength); Result := string(ResultAnswer); end else Result := ''; end; function TNppPlugin.GetNppDataHandle(): HWND; begin Result := FNppData.NppHandle; end; function TNppPlugin.GetNppDataScintillaMainHandle(): HWND; begin Result := FNppData.ScintillaMainHandle; end; procedure TNppPlugin.AddFunction( Name: nppString; const Func: PFUNCPLUGINCMD; const ShortcutKey: Char; const Shift: TShiftState); var NF: _TFuncItem; begin // Set up the new function... FillChar(NF, SizeOf(NF), 0); StrLCopy(NF.ItemName, PChar(Name), FuncItemNameLen); NF.Func := Func; if (ShortcutKey <> #0) then begin New(NF.ShortcutKey); NF.ShortcutKey.IsCtrl := ssCtrl in Shift; NF.ShortcutKey.IsAlt := ssAlt in Shift; NF.ShortcutKey.IsShift := ssShift in Shift; NF.ShortcutKey.Key := vkF12; // NF.ShortcutKey.Key := ShortcutKey; // need widechar ?? // VK_F12 Windows... // NF.ShortcutKey.Key := VK_F12; // use Byte('A') for VK_A-Z end; // Add the new function to the my function list... SetLength(FuncArray, Length(FuncArray) + 1); FuncArray[Length(FuncArray) - 1] := NF; // Zero-based so -1 // Preferred // // Set up the new function // FillChar(NF, SizeOf(NF), 0); // // {$IFDEF NPPUNICODE} // StringToWideChar(Name, NF.ItemName, FuncItemNameLen); // @todo: change to constant // {$ELSE} // StrCopy(NF.ItemName, PChar(Name)); // {$ENDIF} // // NF.Func := Func; // // if (ShortcutKey <> #0) then // begin // New(NF.ShortcutKey); // NF.ShortcutKey.IsCtrl := ssCtrl in Shift; // NF.ShortcutKey.IsAlt := ssAlt in Shift; // NF.ShortcutKey.IsShift := ssShift in Shift; // NF.ShortcutKey.Key := ShortcutKey; // need widechar ?? // end; // // // Add the new function to the list // SetLength(FuncArray, Length(FuncArray) + 1); // FuncArray[Length(FuncArray) - 1] := NF; // Zero-based so -1 // Another option... // LaunchKey.IsCtrl := True; // LaunchKey.IsAlt := False; // LaunchKey.IsShift := False; // LaunchKey.Key := VK_F12; // use Byte('A') for VK_A-Z // // // SetLength(Functions, 1); // Functions[0].ItemName := 'Launch'; // Functions[0].Func := CallLaunchRegExHelper; // Functions[0].CmdID := 0; // Functions[0].Checked := False; // Functions[0].ShortcutKey := @LaunchKey; // // Result := @Functions[0]; // ArrayLength := Length(Functions); end; procedure TNppPlugin.SetToolbarIcon(out ToolbarIcon: TToolbarIcons); begin // To be overridden for customization end; function TNppPlugin.CmdIdFromDlgId(DlgId: Integer): Integer; begin Result := FuncArray[DlgId].CmdId; end; function TNppPlugin.SendMessageToNpp(Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := SendMessage(NppData.NppHandle, Msg, wParam, lParam); end; function TNppPlugin.SendMessageWToNpp(Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := SendMessageW(NppData.NppHandle, Msg, wParam, lParam); end; function TNppPlugin.SendMessageToNppScintilla(Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := SendMessage(NppData.ScintillaMainHandle, Msg, wParam, lParam); end; function TNppPlugin.IsMessageForPlugin(const PluginWnd: HWND): Boolean; begin Result := (PluginWnd = NppData.NppHandle); end; {$REGION 'More Samples'} //function TNppPlugin.GetString(const pMsg: UInt; const pSize: integer): AnsiString; //var //// Answer: AnsiString; // Answer: string; //begin // // overrides // SetLength(Answer, pSize + 1); // SendMessageToNpp(pMsg, pSize, LPARAM(PChar(Answer))); //// {$IFDEF NPPUNICODE} //// Result := WideCharToString(PWideChar(Answer)); //// {$ELSE} //// {$WARNING Untested code with ANSI Version of NPP plugin } // Result := Answer; // Untested so far; wild guess...... //// {$ENDIF} //end; // //function TNppPlugin.GetPluginsConfigDir(): string; //begin // Result := GetString(NPPM_GETPLUGINSCONFIGDIR); //end; // //function TNppPlugin.GetSourceFilename(): string; //begin // Result := GetString(NPPM_GETFULLCURRENTPATH) //end; // //function TNppPlugin.GetSourceFilenameNoPath(): string; //begin // Result := GetString(NPPM_GETFILENAME); //end; //function TNppPlugin.DoOpen(filename: string): boolean; //var // MyText: string; //begin // // ask if we are not already opened // SetLength(MyText, 500); // SendMessageToNpp(NPPM_GETFULLCURRENTPATH, 0, LPARAM(PChar(MyText))); // SetString(MyText, PChar(MyText), strlen(PChar(MyText))); // Result := true; // if (MyText = filename) then // Exit(False); // // Result := SendMessageToNpp(WM_DOOPEN, 0, LPARAM(PChar(filename))) = 0; //end; // //function TNppPlugin.DoOpen(filename: String; Line: Integer): boolean; //begin // Result := DoOpen(filename); // if result then // SendMessageToNppScintilla(SciSupport.SCI_GOTOLINE, Line, 0); //end; // //procedure TNppPlugin.GetFileLine(var filename: string; var Line: Integer); //var // MyText: string; // Res: Integer; //begin // MyText := ''; // SetLength(MyText, 300); // SendMessageToNpp(NPPM_GETFULLCURRENTPATH,0, LPARAM(PChar(MyText))); // SetLength(MyText, StrLen(PChar(MyText))); // filename := MyText; // Res := SendMessageToNppScintilla(SciSupport.SCI_GETCURRENTPOS, 0, 0); // Line := SendMessagetoNppScintilla(SciSupport.SCI_LINEFROMPOSITION, Res, 0); //end; // //function TNppPlugin.GetWord(): string; //begin // Result := GetString(NPPM_GETCURRENTWORD, 800); //end; {$ENDREGION} end.
unit Data.Main; interface uses System.SysUtils, System.Classes, Data.DB, // ------------------------------------------------------------------------ // FireDAC: FDConnection: FireDAC.Comp.Client, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.Phys.Intf, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.VCLUI.Wait, // ------------------------------------------------------------------------ // FireDAC: SQLite: FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, // ------------------------------------------------------------------------ // FireDAC: FDQuery: FireDAC.Comp.DataSet, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Stan.Async, // ------------------------------------------------------------------------ Utils.General; type TDataModMain = class(TDataModule) FDConnection1: TFDConnection; dsBooks: TFDQuery; dsReaders: TFDQuery; dsReports: TFDQuery; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; private function DBVersionToString(VerDB: Integer): string; procedure LogInfoStd (level: Integer; const Msg: string); procedure LogInfoDev (level: Integer; const Msg: string); procedure OpenDataSets; procedure ConnectToDataBase; function GetDatabaseVersion: Variant; procedure LogDatabaseVersion; public procedure VerifyAndConnectToDatabase; function FindReaderByEmil(const email: string): Variant; end; var DataModMain: TDataModMain; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} uses System.Variants, System.StrUtils, ClientAPI.Books, Utils.CipherAES128, Consts.Application, Messaging.EventBus; const SecureKey = 'delphi-is-the-best'; // SecurePassword = AES 128 ('masterkey',SecureKey) // SecurePassword = 'hC52IiCv4zYQY2PKLlSvBaOXc14X41Mc1rcVS6kyr3M='; // SecurePassword = AES 128 ('<null>',SecureKey) SecurePassword = 'EvUlRZOo3hzFEr/IRpHVMA=='; SQL_GetDatabaseVersion = 'SELECT versionnr FROM DBInfo'; resourcestring SWelcomeScreen = 'Welcome screen'; SDBServerGone = 'Database server is gone'; SDBConnectionUserPwdInvalid = 'Invalid database configuration.' + ' Application database user or password is incorrect.'; SDBConnectionError = 'Can''t connect to database server. Unknown error.'; SDBRequireCreate = 'Database is empty. You need to execute script' + ' creating required data.'; SDBErrorSelect = 'Can''t execute SELECT command on the database'; StrNotSupportedDBVersion = 'Not supported database version. Please' + ' update database structures.'; StrExpectedDatabseVersion = 'Oczekiwana wersja bazy: '; StrAktualDatabseVersion = 'Aktualna wersja bazy: '; procedure TDataModMain.ConnectToDataBase; var UserName: String; password: String; msg1: String; begin try UserName := FireDAC.Comp.Client.FDManager.ConnectionDefs.ConnectionDefByName (FDConnection1.ConnectionDefName).Params.UserName; password := AES128_Decrypt(SecurePassword, SecureKey); if password = '<null>' then password := ''; FDConnection1.Open(UserName, password); except on E: FireDAC.Stan.Error.EFDDBEngineException do begin case E.kind of ekUserPwdInvalid: msg1 := SDBConnectionUserPwdInvalid; ekServerGone: msg1 := SDBServerGone; else msg1 := SDBConnectionError end; LogInfoStd(0, msg1); LogInfoDev(1, E.Message); Raise end; end; end; function TDataModMain.DBVersionToString(VerDB: Integer): string; begin Result := (VerDB div 1000).ToString + '.' + (VerDB mod 1000).ToString; end; procedure TDataModMain.VerifyAndConnectToDatabase; begin ConnectToDatabase; LogDatabaseVersion; // ---------------------------------------------------------- OpenDataSets; end; function TDataModMain.FindReaderByEmil(const email: string): Variant; var ok: boolean; begin ok := dsReaders.Locate('email', email, []); if ok then Result := dsReaders.FieldByName('ReaderId').Value else Result := System.Variants.Null() end; function TDataModMain.GetDatabaseVersion: Variant; var Msg: string; begin try Result := FDConnection1.ExecSQLScalar(SQL_GetDatabaseVersion); except on E: EFDDBEngineException do begin Msg := IfThen(E.kind = ekObjNotExists, SDBRequireCreate, SDBErrorSelect); LogInfoStd(0, Msg); LogInfoDev(1, E.Message); Raise; end; end; end; procedure TDataModMain.LogDatabaseVersion; var VersionNr: Variant; begin VersionNr := GetDatabaseVersion; if VersionNr <> ExpectedDatabaseVersionNr then begin LogInfoStd(0, StrNotSupportedDBVersion); LogInfoStd(1, StrExpectedDatabseVersion + DBVersionToString (ExpectedDatabaseVersionNr)); LogInfoStd(1, StrAktualDatabseVersion + DBVersionToString(VersionNr)); end; end; procedure TDataModMain.LogInfoStd(level: Integer; const Msg: string); var AMessage: TEventMessage; begin AMessage.TagString := Msg; AMessage.TagInt := Level; AMessage.TagBoolean := False; TEventBus._Post(EB_DBCONNECTION_AddInfo, AMessage); end; procedure TDataModMain.LogInfoDev(level: Integer; const Msg: string); var AMessage: TEventMessage; begin AMessage.TagString := Msg; AMessage.TagInt := Level; AMessage.TagBoolean := True; TEventBus._Post(EB_DBCONNECTION_AddInfo, AMessage); end; procedure TDataModMain.OpenDataSets; begin dsBooks.Open(); dsReaders.Open(); dsReports.Open(); end; end.
unit ufmMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Generics.Collections, ComCtrls; const CM_PROCEND = WM_USER + 10; SC_STAYONTOP = WM_USER + 11; type TWhichFontFather = class(TForm) btn1: TButton; pnl1: TPanel; btn2: TButton; lvFonts: TListView; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btn1Click(Sender: TObject); private { Private declarations } FFontCache: TDictionary<string, Integer>; procedure AddOrUpdateFont(info: string); procedure LaunchAndHook(szExe: string; szDll: string); procedure WMCopyData(var Msg: TWMCopyData); message WM_COPYDATA; procedure CMProcEnd(var Msg: TMessage); message CM_PROCEND; procedure WMSysCommand(var Message: TWMSysCommand); message WM_SYSCOMMAND; public { Public declarations } end; TFONTINFO = packed record FontWanted: array[0..LF_FACESIZE - 1] of Char; FontStyle: array[0..LF_FACESIZE - 1] of Char; end; PFontInfo = ^TFONTINFO; var WhichFontFather: TWhichFontFather; implementation {$R *.dfm} procedure ProcWaiter(PHandle: THandle); begin WaitForSingleObject(PHandle, INFINITE); CloseHandle(PHandle); PostMessage(WhichFontFather.Handle, CM_PROCEND, 0, 0); end; function RemoteInjectTo(const Guest, AlterGuest: WideString; const procHandle: THandle; bKillTimeOut: Boolean; nTimeout: DWORD; var thrdHandle: Thandle): DWORD; // 远程注入函数 type lpparam = record LibFileName: Pointer; LibAlterFileName: Pointer; hfile: Thandle; dwFlag: Cardinal; func, exitthread: Pointer; end; plpparam = ^lpparam; TLoadLibEx = function(lpLibFileName: PWideChar; hfile: Thandle; dwFlags: DWORD): HMODULE; stdcall; TExitThread = procedure(dwExitCode: DWORD); stdcall; var { 被注入的进程句柄,进程ID } dwRemoteProcessId: DWORD; { 写入远程进程的内容大小 } memSize: DWORD; { 写入到远程进程后的地址 } pszLibMem: Pointer; iReturnCode: Boolean; TempVar: SIZE_T; TempDWORD: Cardinal; { 指向函数LoadLibraryW的地址 } pfnStartAddr: TFNThreadStartRoutine; { dll全路径,需要写到远程进程的内存中去 } pszLibAFilename: PWideChar; pszLibAAlterFileName: PWideChar; lpLibParam: lpparam; // Delphi always assume the thread param is in RCX while in CreateRemoteThread, it's in R8 // Adding an extra useless variable tricks delphi to use R8 as its parameter source // Stack balance is not important as we will call ExitThread to terminate our thread without returns function loader({$IFDEF WIN64}dumy: NativeUInt; {$ENDIF}param: plpparam): HMODULE; stdcall; begin Result := TLoadLibEx(param^.func)(param^.LibFileName, 0, LOAD_WITH_ALTERED_SEARCH_PATH); if Result = 0 then TLoadLibEx(param^.func)(param^.LibAlterFileName, 0, 0); TExitThread(param^.exitthread)(Result); end; begin Result := 0; if procHandle = 0 then begin Result := 0; Exit; end; { 为注入的dll文件路径分配内存大小,由于为WideChar,故要乘2 } GetMem(pszLibAFilename, Length(Guest) * 2 + 2); StringToWideChar(Guest, pszLibAFilename, Length(Guest) * 2 + 2); GetMem(pszLibAAlterFileName, Length(AlterGuest) * 2 + 2); StringToWideChar(AlterGuest, pszLibAAlterFileName, Length(AlterGuest) * 2 + 2); memSize := (1 + Length(Guest)) * SizeOf(WChar) + (Length(AlterGuest) + 1) * SizeOf(WChar) + SizeOf(lpLibParam) + 100; // 100=Loader大小 pszLibMem := VirtualAllocEx(procHandle, nil, memSize, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE); if pszLibMem = nil then begin FreeMem(pszLibAFilename); FreeMem(pszLibAAlterFileName); Result := 0; Exit; end; lpLibParam.LibFileName := Pointer(NativeUInt(pszLibMem) + SizeOf(lpLibParam)); lpLibParam.LibAlterFileName := Pointer(NativeUInt(pszLibMem) + SizeOf(lpLibParam) + (Length(Guest) + 1) * SizeOf(WChar)); lpLibParam.hfile := 0; lpLibParam.dwFlag := LOAD_WITH_ALTERED_SEARCH_PATH; lpLibParam.func := GetProcAddress(GetModuleHandle('Kernel32'), 'LoadLibraryExW'); lpLibParam.exitthread := GetProcAddress(GetModuleHandle('Kernel32'), 'ExitThread'); TempVar := 0; WriteProcessMemory(procHandle, pszLibMem, @lpLibParam, SizeOf(lpLibParam), TempVar); WriteProcessMemory(procHandle, Pointer(NativeUInt(pszLibMem) + memSize - 100), @loader, 100, TempVar); iReturnCode := WriteProcessMemory(procHandle, lpLibParam.LibFileName, pszLibAFilename, (1 + lstrlenW(pszLibAFilename)) * SizeOf(WChar), TempVar); if iReturnCode then iReturnCode := WriteProcessMemory(procHandle, lpLibParam.LibAlterFileName, pszLibAAlterFileName, (1 + Length(AlterGuest)) * SizeOf(WChar), TempVar); if iReturnCode then begin TempVar := 0; { 在远程进程中启动dll } thrdHandle := CreateRemoteThread(procHandle, nil, 0, Pointer(NativeUInt(pszLibMem) + memSize - 100), pszLibMem, 0, TempDWORD); if thrdHandle = 0 then begin VirtualFreeEx(procHandle, pszLibMem, memSize, MEM_DECOMMIT or MEM_RELEASE); FreeMem(pszLibAFilename); FreeMem(pszLibAAlterFileName); Result := 0; Exit; end; if bKillTimeOut then (WaitForSingleObject(thrdHandle, nTimeout)); // Sleep(100); GetExitCodeThread(thrdHandle, Result); end; { 释放内存空间 } // if Result <> 0 then if bKillTimeOut and (Result <> STILL_ACTIVE) then begin VirtualFreeEx(procHandle, pszLibMem, memSize, MEM_DECOMMIT or MEM_RELEASE); CloseHandle(thrdHandle); end; FreeMem(pszLibAFilename); end; procedure TWhichFontFather.FormDestroy(Sender: TObject); begin FFontCache.Free; end; procedure TWhichFontFather.FormCreate(Sender: TObject); var SysMenu: HMENU; begin SysMenu := GetSystemMenu(Handle, False); AppendMenu(SysMenu, MF_SEPARATOR, 0, ''); AppendMenu(SysMenu, MF_STRING, SC_STAYONTOP, '&Stay on top'); FFontCache := TDictionary<string, Integer>.Create; end; procedure TWhichFontFather.AddOrUpdateFont(info: string); var n: Integer; begin lvFonts.Items.BeginUpdate; try if FFontCache.ContainsKey(info) then begin with lvFonts.Items[FFontCache[info]] do begin n := Integer(SubItems.Objects[0]); SubItems.Objects[0] := Pointer(n + 1); Caption := Format('%s *%d', [info, n + 1]); Selected := True; end; end else begin with lvFonts.Items.Add do begin Caption := info; SubItems.AddObject('', Pointer(1)); FFontCache.Add(info, index); end; end; finally lvFonts.Items.EndUpdate; end; end; procedure TWhichFontFather.btn1Click(Sender: TObject); const {$IFDEF WIN64} MACTYPE_DLL = 'MacType64.dll'; MACTYPE_CORE_DLL = 'MacType64.Core.dll'; WHICHFONT_DLL = 'WhichFont64.dll'; {$ELSE} MACTYPE_DLL = 'MacType.dll'; MACTYPE_CORE_DLL = 'MacType.Core.dll'; WHICHFONT_DLL = 'WhichFont.dll'; {$ENDIF} begin if GetModuleHandle(MACTYPE_DLL) + GetModuleHandle(MACTYPE_CORE_DLL) <> 0 then begin MessageBox(Handle, 'Please turn off MacType before start tracing', 'Warning', MB_OK or MB_ICONWARNING); exit; end; with TOpenDialog.Create(nil) do try Filter := 'Excutable|*.exe'; Options := Options + [ofFileMustExist]; if Execute then begin lvFonts.Clear; FFontCache.Clear; pnl1.Hide; LaunchAndHook(FileName, ExtractFilePath(ParamStr(0)) + WHICHFONT_DLL); btn1.Hide; end; finally Free; end; end; procedure TWhichFontFather.CMProcEnd(var Msg: TMessage); begin lvFonts.AddItem('------ Process exited ------', nil); pnl1.Show; end; procedure TWhichFontFather.LaunchAndHook(szExe, szDll: string); var si: TStartupInfo; pi: TProcessInformation; dumy: DWORD; dumyHandle: THandle; bWow64Proc: BOOL; begin if not FileExists(szDll) then begin MessageBox(Handle, 'WhichFont.dll not found!', nil, MB_OK or MB_ICONERROR); Exit; end; fillchar(si, sizeof(si), 0); si.cb := sizeof(si); si.wShowWindow := SW_SHOW; if CreateProcess(nil, PChar(szExe), nil, nil, False, CREATE_SUSPENDED, nil, nil, si, pi) then begin {$IFDEF WIN64} if IsWow64Process(pi.hProcess, @bWow64Proc) and bWow64Proc then begin lvFonts.AddItem('---- Use WhichFont.exe for x86 processes ----', nil); ResumeThread(pi.hThread); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); pnl1.Show; Exit; end; {$ELSE} if IsWow64Process(GetCurrentProcess(), bWow64Proc) and bWow64Proc then // ourself is running in a x64 platform if IsWow64Process(pi.hProcess, @bWow64Proc) and (not bWow64Proc) then begin lvFonts.AddItem('---- Use WhichFont64.exe for x64 processes ----', nil); ResumeThread(pi.hThread); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); pnl1.Show; Exit; end; {$ENDIF} begin CloseHandle(BeginThread(nil, 0, @ProcWaiter, Pointer(pi.hProcess), 0, dumy)); RemoteInjectTo(szDll, '', pi.hProcess, False, 5000, dumyHandle); ResumeThread(pi.hThread); CloseHandle(pi.hThread); end; end; end; procedure TWhichFontFather.WMCopyData(var Msg: TWMCopyData); begin if (Msg.CopyDataStruct.dwData = $12344321) and (Msg.CopyDataStruct.lpData <> nil) then // check magic word begin with PFontInfo(Msg.CopyDataStruct.lpData)^ do AddOrUpdateFont(Format('%s [%s]', [FontWanted, FontStyle])); end; end; procedure TWhichFontFather.WMSysCommand(var Message: TWMSysCommand); begin inherited; case Message.CmdType of SC_STAYONTOP: begin if Self.FormStyle = fsStayOnTop then begin self.FormStyle := fsNormal; CheckMenuItem(GetSystemMenu(Handle, False), SC_STAYONTOP, MF_BYCOMMAND or MF_UNCHECKED); end else begin self.FormStyle := fsStayOnTop; CheckMenuItem(GetSystemMenu(Handle, False), SC_STAYONTOP, MF_BYCOMMAND or MF_CHECKED); end; end; end; end; end.
unit Produtos; interface uses Windows, SysUtils, Classes, Controls, Forms, ComCtrls, DB, SqlExpr, DBClient, StrUtils, Math, Controle; type TProdutos = class private iCodigo: Integer; sDescricao: string; nVlrVenda: Double; protected oControle: TControle; procedure LimparRegistro; public constructor Create(pConexaoControle: TControle); destructor Destroy; override; function PesquisarProduto(pCodigo: Integer): Boolean; property Codigo: integer read iCodigo write iCodigo; property Descricao: string read sDescricao write sDescricao; property VlrVenda: Double read nVlrVenda write nVlrVenda; end; implementation { TProdutos } constructor TProdutos.Create(pConexaoControle: TControle); begin if not Assigned(pConexaoControle) then oControle := TControle.Create else oControle := pConexaoControle; end; destructor TProdutos.Destroy; begin inherited; end; procedure TProdutos.LimparRegistro; begin Self.Codigo := 0; Self.Descricao := ''; Self.VlrVenda := 0; end; function TProdutos.PesquisarProduto(pCodigo: Integer): Boolean; begin if (pCodigo > 0) then begin Result := True; if (not SameValue(Self.Codigo, pCodigo)) then begin oControle.SqlQuery.Close; oControle.SqlQuery.SQL.Clear; oControle.SqlQuery.SQL.Add('SELECT '); oControle.SqlQuery.SQL.Add(' CODIGO, '); oControle.SqlQuery.SQL.Add(' DESCRICAO, '); oControle.SqlQuery.SQL.Add(' VLR_VENDA '); oControle.SqlQuery.SQL.Add('FROM '); oControle.SqlQuery.SQL.Add(' PRODUTOS '); oControle.SqlQuery.SQL.Add('WHERE '); oControle.SqlQuery.SQL.Add(' CODIGO = :pCodigo '); oControle.SqlQuery.Params.Clear; oControle.SqlQuery.Params.CreateParam(ftInteger, 'pCodigo', ptInput); oControle.SqlQuery.ParamByName('pCodigo').AsInteger := pCodigo; try try oControle.SqlQuery.Open; finally if oControle.SqlQuery.IsEmpty then begin LimparRegistro; Result := False; end else begin Self.Codigo := oControle.SqlQuery.FieldByName('CODIGO').AsInteger; Self.Descricao := oControle.SqlQuery.FieldByName('DESCRICAO').AsString; Self.VlrVenda := oControle.SqlQuery.FieldByName('VLR_VENDA').AsCurrency; Result := True; end; oControle.SqlQuery.Close; end; except on e: Exception do begin Result := False; Application.MessageBox(PWideChar('Ocorreu o seguinte erro ao pesquisar um cliente, "'+e.Message+'"'), 'Erro de pesquisa', MB_ICONERROR + MB_OK); end; end; end; end else Result := False; end; end.
unit Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps, Flix.Utils.Maps, Vcl.StdCtrls, System.Generics.Collections, Vcl.ExtCtrls, AdvCombo, System.ImageList, Vcl.ImgList, Vcl.VirtualImageList, AdvGlowButton, AdvPanel, AdvStyleIF, AdvAppStyler, Modules.Resources, DB; type TFrmMain = class(TForm) Map: TTMSFNCMaps; imgNoService: TImage; imgButtons: TVirtualImageList; dlgOpen: TFileOpenDialog; Panel1: TAdvPanel; btnOpen: TAdvGlowButton; cbServices: TAdvComboBox; FormStyler: TAdvFormStyler; btnShow: TAdvGlowButton; btnShowPeople: TAdvGlowButton; btnClear: TAdvGlowButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure cbServicesClick(Sender: TObject); procedure btnOpenClick(Sender: TObject); procedure btnShowClick(Sender: TObject); procedure btnShowPeopleClick(Sender: TObject); procedure btnClearClick(Sender: TObject); private { Private declarations } FAPIKeys: TServiceAPIKeys; FServices: TList<TMapService>; procedure InitComboBox; function GetMapService: TMapService; procedure SetMapService(const Value: TMapService); procedure UpdateUserInterface; procedure SwitchService; procedure LoadState; procedure StoreState; procedure ShowLocations( ADataSet: TDataSet; AIcon :String = 'redflag_40.png'); public { Public declarations } property MapService: TMapService read GetMapService write SetMapService; end; var FrmMain: TFrmMain; implementation uses System.IOUtils, System.Win.Registry, Modules.Data; const REG_KEY = 'Software\FlixEngineering\Mapping'; KEY_CONFIG = 'ConfigFile'; KEY_SERVICE = 'CurrentService'; {$R *.dfm} procedure TFrmMain.btnClearClick(Sender: TObject); begin Map.BeginUpdate; try Map.ClearMarkers; finally Map.EndUpdate; end; end; procedure TFrmMain.btnOpenClick(Sender: TObject); begin if dlgOpen.Execute then begin FApiKeys.LoadFromFile(dlgOpen.Filename); InitComboBox; end; end; procedure TFrmMain.btnShowClick(Sender: TObject); begin ShowLocations(Data.Locations); end; procedure TFrmMain.btnShowPeopleClick(Sender: TObject); begin ShowLocations( Data.Racers, 'finish_40.png' ); end; procedure TFrmMain.cbServicesClick(Sender: TObject); begin SwitchService; end; procedure TFrmMain.FormCreate(Sender: TObject); begin FServices := TList<TMapService>.Create; FAPIKeys := TServiceAPIKeys.Create; LoadState; UpdateUserInterface; end; procedure TFrmMain.FormDestroy(Sender: TObject); begin StoreState; FAPIKeys.Free; FServices.Free; end; function TFrmMain.GetMapService: TMapService; begin Result := Map.Service; end; procedure TFrmMain.InitComboBox; var LService: TMapService; begin // clear items cbServices.Items.Clear; // get all services FAPIKeys.GetServices(FServices); for LService in FServices do begin // add the service name and service cbServices.Items.AddObject( FAPIKeys.GetNameForService(LService), TObject( LService ) ); end; end; procedure TFrmMain.LoadState; var LReg: TRegistry; LFilename: String; LService: TMapService; begin LReg := TRegistry.Create; LReg.RootKey := HKEY_CURRENT_USER; try if LReg.OpenKey( REG_KEY, False ) then begin // read filename last used LFilename := LReg.ReadString( KEY_CONFIG ); // if config file still exists... if TFile.Exists(LFilename) then begin // ...load keys. FAPIKeys.LoadFromFile(LFilename); // show services in combo box InitComboBox; // get the service last used LService := TMapService( LReg.ReadInteger(KEY_SERVICE) ); // select service in combo box cbServices.ItemIndex := cbServices.Items.IndexOfObject(TObject(LService)); // switch to that service SwitchService; end; end; LReg.CloseKey; finally LReg.Free; end; end; procedure TFrmMain.SetMapService(const Value: TMapService); var LAPI: String; begin // get the API key LAPI := FAPIKeys.GetKey(Value); if Length( LAPI ) > 0 then begin // assign the API key Map.APIKey := LAPI; // switch the service Map.Service := Value; // update view // e.g. show map UpdateUserInterface; end; end; procedure TFrmMain.ShowLocations( ADataSet: TDataSet; AIcon: String ); var LMarker : TTMSFNCMapsMarker; LDataset: TDataSet; begin if Assigned( ADataSet ) then begin LDataset := ADataSet; Map.BeginUpdate; LDataset.DisableControls; try LDataset.First; while not LDataset.Eof do begin LMarker := Map.Markers.Add; LMarker.Longitude := LDataset.FieldByName('Lon').AsFloat; LMarker.Latitude := LDataset.FieldByName('Lat').AsFloat; LMarker.Title := LDataset.FieldByName('Name').AsString; LMarker.IconURL := Format( 'http://webcore.flixengineering.com/svg/%s', [AIcon] ); LDataset.Next; end; Map.ZoomToBounds( Map.Markers.ToCoordinateArray ); finally LDataset.EnableControls; Map.EndUpdate; end; end; end; procedure TFrmMain.StoreState; var LReg: TRegistry; begin LReg := TRegistry.Create; LReg.RootKey := HKEY_CURRENT_USER; try if LReg.OpenKey( REG_KEY, True ) then begin // store the filename of the config file LReg.WriteString(KEY_CONFIG, FAPIKeys.Filename); // store the last service used LReg.WriteInteger(KEY_SERVICE, ORD(FAPIKeys.LastService) ); end; LReg.CloseKey; finally LReg.Free; end; end; procedure TFrmMain.SwitchService; begin // if service is selected... if cbServices.ItemIndex <> -1 then begin // set the current service to this service MapService := TMapService( cbServices.Items.Objects[ cbServices.ItemIndex ] ); end; end; procedure TFrmMain.UpdateUserInterface; begin // map is only visible if API key is provided Map.Visible := Map.APIKey <> ''; btnShow.Visible := Map.Visible; // placeholder image is only visible if NO API key provided imgNoService.Visible := NOT Map.Visible; end; end.
// // Created by the DataSnap proxy generator. // 5/19/2014 11:33:04 PM // unit ClientClassesUnit1; interface uses System.JSON, Datasnap.DSProxyRest, Datasnap.DSClientRest, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.FireDACJSONReflect, Data.DBXJSONReflect; type IDSRestCachedTFDJSONDataSets = interface; TServerMethods1Client = class(TDSAdminRestClient) private FEchoStringCommand: TDSRestCommand; FReverseStringCommand: TDSRestCommand; FGetCustomersCommand: TDSRestCommand; FGetCustomersCommand_Cache: TDSRestCommand; FApplyCustomersCommand: TDSRestCommand; public constructor Create(ARestConnection: TDSRestConnection); overload; constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function EchoString(Value: string; const ARequestFilter: string = ''): string; function ReverseString(Value: string; const ARequestFilter: string = ''): string; function GetCustomers(const ARequestFilter: string = ''): TFDJSONDataSets; function GetCustomers_Cache(const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; procedure ApplyCustomers(ADelta: TFDJSONDeltas); end; IDSRestCachedTFDJSONDataSets = interface(IDSRestCachedObject<TFDJSONDataSets>) end; TDSRestCachedTFDJSONDataSets = class(TDSRestCachedObject<TFDJSONDataSets>, IDSRestCachedTFDJSONDataSets, IDSRestCachedCommand) end; const TServerMethods1_EchoString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TServerMethods1_ReverseString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TServerMethods1_GetCustomers: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods1_GetCustomers_Cache: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods1_ApplyCustomers: array [0..0] of TDSRestParameterMetaData = ( (Name: 'ADelta'; Direction: 1; DBXType: 37; TypeName: 'TFDJSONDeltas') ); implementation function TServerMethods1Client.EchoString(Value: string; const ARequestFilter: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FConnection.CreateCommand; FEchoStringCommand.RequestType := 'GET'; FEchoStringCommand.Text := 'TServerMethods1.EchoString'; FEchoStringCommand.Prepare(TServerMethods1_EchoString); end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.Execute(ARequestFilter); Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.ReverseString(Value: string; const ARequestFilter: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FConnection.CreateCommand; FReverseStringCommand.RequestType := 'GET'; FReverseStringCommand.Text := 'TServerMethods1.ReverseString'; FReverseStringCommand.Prepare(TServerMethods1_ReverseString); end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.Execute(ARequestFilter); Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.GetCustomers(const ARequestFilter: string): TFDJSONDataSets; begin if FGetCustomersCommand = nil then begin FGetCustomersCommand := FConnection.CreateCommand; FGetCustomersCommand.RequestType := 'GET'; FGetCustomersCommand.Text := 'TServerMethods1.GetCustomers'; FGetCustomersCommand.Prepare(TServerMethods1_GetCustomers); end; FGetCustomersCommand.Execute(ARequestFilter); if not FGetCustomersCommand.Parameters[0].Value.IsNull then begin FUnMarshal := TDSRestCommand(FGetCustomersCommand.Parameters[0].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FGetCustomersCommand.Parameters[0].Value.GetJSONValue(True))); if FInstanceOwner then FGetCustomersCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethods1Client.GetCustomers_Cache(const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FGetCustomersCommand_Cache = nil then begin FGetCustomersCommand_Cache := FConnection.CreateCommand; FGetCustomersCommand_Cache.RequestType := 'GET'; FGetCustomersCommand_Cache.Text := 'TServerMethods1.GetCustomers'; FGetCustomersCommand_Cache.Prepare(TServerMethods1_GetCustomers_Cache); end; FGetCustomersCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FGetCustomersCommand_Cache.Parameters[0].Value.GetString); end; procedure TServerMethods1Client.ApplyCustomers(ADelta: TFDJSONDeltas); begin if FApplyCustomersCommand = nil then begin FApplyCustomersCommand := FConnection.CreateCommand; FApplyCustomersCommand.RequestType := 'POST'; FApplyCustomersCommand.Text := 'TServerMethods1."ApplyCustomers"'; FApplyCustomersCommand.Prepare(TServerMethods1_ApplyCustomers); end; if not Assigned(ADelta) then FApplyCustomersCommand.Parameters[0].Value.SetNull else begin FMarshal := TDSRestCommand(FApplyCustomersCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FApplyCustomersCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ADelta), True); if FInstanceOwner then ADelta.Free finally FreeAndNil(FMarshal) end end; FApplyCustomersCommand.Execute; end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection); begin inherited Create(ARestConnection); end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); begin inherited Create(ARestConnection, AInstanceOwner); end; destructor TServerMethods1Client.Destroy; begin FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FGetCustomersCommand.DisposeOf; FGetCustomersCommand_Cache.DisposeOf; FApplyCustomersCommand.DisposeOf; inherited; end; end.
unit uResponsables; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013White, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, cxGroupBox, cxTextEdit, cxDBEdit, cxLabel, Vcl.Menus, Vcl.StdCtrls, cxButtons, System.Actions, Vcl.ActnList, Vcl.DBActns; type TfrmResponsables = class(TForm) gbAcciones: TcxGroupBox; gbDatos: TcxGroupBox; lblNombre: TcxLabel; txtNombre: TcxDBTextEdit; btnProcesar: TcxButton; alBD: TActionList; Agregar: TDataSetInsert; btnAgregar: TcxButton; Procesar: TDataSetPost; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure AgregarUpdate(Sender: TObject); procedure AgregarExecute(Sender: TObject); procedure ProcesarUpdate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnProcesarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmResponsables: TfrmResponsables; implementation {$R *.dfm} uses uPrincipal, udmDatos,data.db; procedure TfrmResponsables.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := CaFree; end; procedure TfrmResponsables.FormDestroy(Sender: TObject); begin frmPrincipal.EliminaVentana(frmResponsables.Caption); dmDatos.qResponsables.Close; frmResponsables := nil; end; procedure TfrmResponsables.FormShow(Sender: TObject); begin txtNombre.SetFocus; end; procedure TfrmResponsables.ProcesarUpdate(Sender: TObject); begin Procesar.Enabled := dmDatos.qResponsables.State in [dsInsert]; end; procedure TfrmResponsables.AgregarExecute(Sender: TObject); begin dmDatos.qResponsables.Close; if dmDatos.qResponsables.Active = false then dmDatos.qResponsables.Active := true; dmDatos.qResponsables.Insert; txtNombre.SetFocus; end; procedure TfrmResponsables.AgregarUpdate(Sender: TObject); begin Agregar.Enabled := dmDatos.qResponsables.State in [dsInActive,dsBrowse]; end; procedure TfrmResponsables.btnProcesarClick(Sender: TObject); begin dmDatos.qResponsables.Post; application.MessageBox('El ingreso del Responsable fue satisfactorio','Ingreso de Responsable satisfactorio',mb_ok); end; end.
unit frmPedagogueClassEdit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, dbfunc, uKernel; type TfPedagogueClassEdit = class(TForm) Panel2: TPanel; lvChildList: TListView; Panel5: TPanel; bClose: TButton; Panel3: TPanel; lvClassList: TListView; Panel1: TPanel; bEditRecord: TButton; bDeleteRecord: TButton; Panel8: TPanel; GroupBox1: TGroupBox; chbExpelled: TCheckBox; Splitter1: TSplitter; Panel7: TPanel; rgChooseMode: TRadioGroup; cmbChoose: TComboBox; bInGroup: TButton; eSearchFIO: TEdit; Label3: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure rgChooseModeClick(Sender: TObject); procedure bEditRecordClick(Sender: TObject); procedure bInGroupClick(Sender: TObject); procedure bCloseClick(Sender: TObject); procedure cmbChooseChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure bDeleteRecordClick(Sender: TObject); procedure lvChildListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure lvClassListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure eSearchFIOChange(Sender: TObject); private YearBirth: TResultTable; ChildListForClassMember: TResultTable; ClassMembersList: TResultTable; AcademicYear: TResultTable; FIDEducationProgram: integer; FIDPedagogue: integer; FIDAcademicYear: integer; FStrEducationProgram: string; FStrPedagogue: string; FStrAcademicYear: string; procedure SetIDEducationProgram(const Value: integer); procedure SetIDPedagogue(const Value: integer); procedure SetIDAcademicYear(const Value: integer); procedure SetStrEducationProgram(const Value: string); procedure SetStrPedagogue(const Value: string); procedure SetStrAcademicYear(const Value: string); procedure ShowChildListForClassMember; procedure ShowClassMembersList; procedure ShowChildListForClassMemberByFIO(const inStatus, Mode: integer; const aSearchText: string); public property IDEducationProgram: integer read FIDEducationProgram write SetIDEducationProgram; property IDPedagogue: integer read FIDPedagogue write SetIDPedagogue; property IDAcademicYear: integer read FIDAcademicYear write SetIDAcademicYear; property StrEducationProgram: string read FStrEducationProgram write SetStrEducationProgram; property StrPedagogue: string read FStrPedagogue write SetStrPedagogue; property StrAcademicYear: string read FStrAcademicYear write SetStrAcademicYear; end; var fPedagogueClassEdit: TfPedagogueClassEdit; implementation {$R *.dfm} uses frmPedagogueClassEditMini; procedure TfPedagogueClassEdit.bDeleteRecordClick(Sender: TObject); begin // еще продумать проверку на наличие связанных с нагрузкой записей в расписании и/или журнале if Application.MessageBox('Подтверждаете удаление обучающегося из класса?', 'ДХС', MB_YESNO) = IDYES then begin if (Kernel.DeleteGroup([fPedagogueClassEditMini.IDLearningGroup]) and Kernel.DeleteGroupMember([fPedagogueClassEditMini.IDLearningGroupMember])) then begin ShowMessage('Запись удалена!'); // МОЖЕТ НЕ СТОИТ ВЫВОДИТЬ ЭТО СООБЩЕНИЕ!!??? end else ShowMessage('Ошибка при удалении записи!'); ShowChildListForClassMember; ShowClassMembersList; end; end; procedure TfPedagogueClassEdit.bEditRecordClick(Sender: TObject); begin fPedagogueClassEditMini.NewRecord := false; if (not Assigned(fPedagogueClassEditMini)) then fPedagogueClassEditMini := TfPedagogueClassEditMini.Create(Self); fPedagogueClassEditMini.ShowModal; if fPedagogueClassEditMini.ModalResult = mrOk then begin ShowChildListForClassMember; ShowClassMembersList; end; end; procedure TfPedagogueClassEdit.bCloseClick(Sender: TObject); begin Close; end; procedure TfPedagogueClassEdit.bInGroupClick(Sender: TObject); begin fPedagogueClassEditMini.NewRecord := true; if (not Assigned(fPedagogueClassEditMini)) then fPedagogueClassEditMini := TfPedagogueClassEditMini.Create(Self); fPedagogueClassEditMini.ShowModal; if fPedagogueClassEditMini.ModalResult = mrOk then begin ShowChildListForClassMember; ShowClassMembersList; end; end; procedure TfPedagogueClassEdit.cmbChooseChange(Sender: TObject); begin ShowChildListForClassMember; end; procedure TfPedagogueClassEdit.eSearchFIOChange(Sender: TObject); var vInStatus, vMode: integer; begin vInStatus := 1; // не показывать отчисленных vMode := 0; // результат поиска начинается со строки поиска if length(eSearchFIO.Text) > 2 then ShowChildListForClassMemberByFIO(vInStatus, vMode, eSearchFIO.Text) else ShowChildListForClassMember; end; procedure TfPedagogueClassEdit.FormClose(Sender: TObject; var Action: TCloseAction); begin ModalResult := mrOk; end; procedure TfPedagogueClassEdit.FormCreate(Sender: TObject); begin YearBirth := nil; ChildListForClassMember := nil; ClassMembersList := nil; AcademicYear := nil; end; procedure TfPedagogueClassEdit.FormDestroy(Sender: TObject); begin if Assigned(YearBirth) then FreeAndNil(YearBirth); if Assigned(ChildListForClassMember) then FreeAndNil(ChildListForClassMember); if Assigned(ClassMembersList) then FreeAndNil(ClassMembersList); if Assigned(AcademicYear) then FreeAndNil(AcademicYear); // if Assigned(InOrderList) then end; procedure TfPedagogueClassEdit.FormShow(Sender: TObject); var i: integer; begin fPedagogueClassEditMini.IDEducationProgram := IDEducationProgram; fPedagogueClassEditMini.IDPedagogue := IDPedagogue; fPedagogueClassEditMini.IDAcademicYear := IDAcademicYear; fPedagogueClassEditMini.StrEducationProgram := StrEducationProgram; fPedagogueClassEditMini.StrPedagogue := StrPedagogue; fPedagogueClassEditMini.StrAcademicYear := StrAcademicYear; Panel1.Caption := StrPedagogue + ', ' + StrAcademicYear + ' уч/год, "' + StrEducationProgram + '"'; rgChooseMode.ItemIndex := 0; if not Assigned(AcademicYear) then AcademicYear := Kernel.GetAcademicYear; with cmbChoose do begin Clear; Items.Add('Все'); for i := 0 to AcademicYear.Count - 1 do Items.Add(AcademicYear[i].ValueStrByName('NAME')); DropDownCount := AcademicYear.Count + 1; for i := 0 to AcademicYear.Count - 1 do if AcademicYear[i].ValueStrByName('NAME') = StrAcademicYear then cmbChoose.ItemIndex := i + 1; end; ShowChildListForClassMember; ShowClassMembersList; end; procedure TfPedagogueClassEdit.lvChildListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if ChildListForClassMember.Count > 0 then with ChildListForClassMember[Item.Index] do begin fPedagogueClassEditMini.IDLearningChild := ValueByName('ID_OUT_CHILD'); fPedagogueClassEditMini.StrSurnameNameChild := ValueByName('SURNAME_NAME'); end; end; procedure TfPedagogueClassEdit.lvClassListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if ClassMembersList.Count > 0 then with ClassMembersList[Item.Index] do begin fPedagogueClassEditMini.IDLearningGroup := ValueByName('ID_OUT_LEARNING_GROUP'); fPedagogueClassEditMini.IDLearningLevel := ValueByName('ID_OUT_LEARNING_LEVEL'); fPedagogueClassEditMini.WeekAmountHours := ValueByName('WEEK_AMOUNT_HOURS'); fPedagogueClassEditMini.IDLearningGroupMember := ValueByName('ID_OUT_LEARNING_GROUP_MEMBER'); fPedagogueClassEditMini.IDOrderIn := ValueByName('ID_OUT_ORDER_IN'); if ValueStrByName('ID_OUT_ORDER_OUT') <> 'null' then fPedagogueClassEditMini.IDOrderOut := ValueByName('ID_OUT_ORDER_OUT'); fPedagogueClassEditMini.IDLearningChild := ValueByName('ID_OUT_CHILD'); fPedagogueClassEditMini.StrSurnameNameChild := ValueByName('SURNAME_NAME'); end; end; procedure TfPedagogueClassEdit.rgChooseModeClick(Sender: TObject); var i: integer; begin if rgChooseMode.ItemIndex = 0 then begin // этот кусок дублируется в FormShow if not Assigned(AcademicYear) then AcademicYear := Kernel.GetAcademicYear; with cmbChoose do begin Clear; Items.Add('Все'); for i := 0 to AcademicYear.Count - 1 do Items.Add(AcademicYear[i].ValueStrByName('NAME')); DropDownCount := AcademicYear.Count + 1; for i := 0 to AcademicYear.Count - 1 do if AcademicYear[i].ValueStrByName('NAME') = StrAcademicYear then cmbChoose.ItemIndex := i + 1; end; end else begin if not Assigned(YearBirth) then YearBirth := Kernel.GetYearBirth; with cmbChoose do begin Clear; for i := 0 to YearBirth.Count - 1 do Items.Add(YearBirth[i].ValueStrByName('YearBirth')); DropDownCount := YearBirth.Count + 1; ItemIndex := 0; end; end; ShowChildListForClassMember; end; procedure TfPedagogueClassEdit.SetIDAcademicYear(const Value: integer); begin if FIDAcademicYear <> Value then FIDAcademicYear := Value; end; procedure TfPedagogueClassEdit.SetIDEducationProgram(const Value: integer); begin if FIDEducationProgram <> Value then FIDEducationProgram := Value; end; procedure TfPedagogueClassEdit.SetIDPedagogue(const Value: integer); begin if FIDPedagogue <> Value then FIDPedagogue := Value; end; procedure TfPedagogueClassEdit.SetStrAcademicYear(const Value: string); begin if FStrAcademicYear <> Value then FStrAcademicYear := Value; end; procedure TfPedagogueClassEdit.SetStrEducationProgram(const Value: string); begin if FStrEducationProgram <> Value then FStrEducationProgram := Value; end; procedure TfPedagogueClassEdit.SetStrPedagogue(const Value: string); begin if FStrPedagogue <> Value then FStrPedagogue := Value; end; procedure TfPedagogueClassEdit.ShowChildListForClassMember; var in_id_academic_year, year_birth: integer; begin if rgChooseMode.ItemIndex = 0 then // выбрать сиписок по учебному году begin in_id_academic_year := AcademicYear[cmbChoose.ItemIndex - 1] .ValueByName('ID'); if Assigned(ChildListForClassMember) then FreeAndNil(ChildListForClassMember); ChildListForClassMember := Kernel.GetChildListForClassMemberByAcademicYear (IDEducationProgram, IDPedagogue, in_id_academic_year); end else // выбрать список по дате рождения begin if YearBirth.Count > 0 then year_birth := StrToInt(cmbChoose.Text); if Assigned(ChildListForClassMember) then FreeAndNil(ChildListForClassMember); ChildListForClassMember := Kernel.GetChildListForClassMemberByYearBirth (year_birth); end; Kernel.GetLVChildListClassMemberForEdit(lvChildList, ChildListForClassMember); if lvChildList.Items.Count > 0 then lvChildList.ItemIndex := 0; end; procedure TfPedagogueClassEdit.ShowChildListForClassMemberByFIO(const inStatus, Mode: integer; const aSearchText: string); begin if Assigned(ChildListForClassMember) then FreeAndNil(ChildListForClassMember); ChildListForClassMember := Kernel.GetChildList(inStatus, Mode, aSearchText); Kernel.GetLVChildListForGroupMember(lvChildList, ChildListForClassMember); if lvChildList.Items.Count > 0 then begin lvChildList.ItemIndex := 0; bInGroup.Enabled := true; end else bInGroup.Enabled := false; end; procedure TfPedagogueClassEdit.ShowClassMembersList; begin if Assigned(ClassMembersList) then FreeAndNil(ClassMembersList); ClassMembersList := Kernel.GetChildListClassMember(IDEducationProgram, IDPedagogue, IDAcademicYear); Kernel.GetLVChildListClassMemberForEdit(lvClassList, ClassMembersList); if lvClassList.Items.Count > 0 then lvClassList.ItemIndex := 0; end; end.
unit UnitDesktopPreview; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, VirtualTrees; type TFormDesktopPreview = class(TForm) Image1: TImage; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public LastNode: pVirtualNode; procedure CloseForm; { Public declarations } end; var FormDesktopPreview: TFormDesktopPreview; implementation {$R *.dfm} const WS_EX_LAYERED = $80000; WS_EX_NOACTIVATE = $08000000; LWA_COLORKEY = 1; LWA_ALPHA = 2; function SetLayeredWindowAttributes(hwnd : HWND; // handle to the layered window crKey : TColor; // specifies the color key bAlpha : byte; // value for the blend function dwFlags : DWORD // action ): BOOL; stdcall; external 'user32.dll' name 'SetLayeredWindowAttributes'; procedure TFormDesktopPreview.FormClose(Sender: TObject; var Action: TCloseAction); begin Timer1.Enabled := false; LastNode := nil; end; procedure TFormDesktopPreview.FormCreate(Sender: TObject); begin FormStyle := fsStayOnTop; SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_LAYERED or WS_EX_NOACTIVATE); SetLayeredWindowAttributes(Handle, 0, 180, LWA_ALPHA); end; procedure TFormDesktopPreview.Timer1Timer(Sender: TObject); begin close; end; procedure TFormDesktopPreview.CloseForm; begin Timer1.Enabled := false; Timer1.Enabled := true; end; end.
unit Frame.Welcome; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Messaging.EventBus; type TFrameWelcome = class(TFrame) Panel1: TPanel; lbAppName: TLabel; lbAppVersion: TLabel; tmrFrameReady: TTimer; Bevel1: TBevel; procedure tmrFrameReadyTimer(Sender: TObject); private procedure AddInfo(level: integer; const Msg: string; isInfoForDevelopers: boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ShowInfo(MessageID: integer; const AMessagee: TEventMessage); end; implementation {$R *.dfm} uses Consts.Application, Helper.TApplication; procedure TFrameWelcome.AddInfo(level: integer; const Msg: string; isInfoForDevelopers: boolean); var lbl: TLabel; begin if not(isInfoForDevelopers) or Application.IsDeveloperMode then begin lbl := TLabel.Create(self); lbl.Top := Panel1.Height; Panel1.Height := Panel1.Height + lbl.Height; lbl.Align := alTop; lbl.AlignWithMargins := True; lbl.Parent := Panel1; if level > 0 then lbl.Caption := '* ' + Msg else lbl.Caption := Msg; if isInfoForDevelopers then begin lbl.Font.Style := [fsItalic]; lbl.Font.Color := clGrayText; end; lbl.Margins.Left := 10 + Level * 20; lbl.Margins.Top := 0; lbl.Margins.Bottom := 0; end; end; constructor TFrameWelcome.Create(AOwner: TComponent); begin inherited; TEventBus._Register(EB_DBCONNECTION_AddInfo, ShowInfo); end; destructor TFrameWelcome.Destroy; begin inherited; TEventBus._Unregister(EB_DBCONNECTION_AddInfo, ShowInfo); end; procedure TFrameWelcome.ShowInfo(MessageID: integer; const AMessagee: TEventMessage); begin Self.AddInfo(AMessagee.TagInt, AMessagee.TagString, AMessagee.TagBoolean); end; procedure TFrameWelcome.tmrFrameReadyTimer(Sender: TObject); begin tmrFrameReady.Enabled := false; lbAppName.Caption := Consts.Application.ApplicationName; lbAppVersion.Caption := Consts.Application.ApplicationVersion; end; end.
unit ufmRBMain; interface uses System.Drawing, System.Collections, System.ComponentModel, System.Windows.Forms, System.Data; type TWinForm = class(System.Windows.Forms.Form) {$REGION 'Designer Managed Code'} strict private /// <summary> /// Required designer variable. /// </summary> Components: System.ComponentModel.Container; Panel1: System.Windows.Forms.Panel; pnlPayoffs: System.Windows.Forms.Panel; pnlRegions: System.Windows.Forms.Panel; Label1: System.Windows.Forms.Label; lbRegions: System.Windows.Forms.ListBox; TabControl1: System.Windows.Forms.TabControl; tpNortheast: System.Windows.Forms.TabPage; tpSoutheast: System.Windows.Forms.TabPage; tpNorthCentral: System.Windows.Forms.TabPage; tpSouthCentral: System.Windows.Forms.TabPage; tpPlains: System.Windows.Forms.TabPage; tpNorthwest: System.Windows.Forms.TabPage; tpSouthwest: System.Windows.Forms.TabPage; Label2: System.Windows.Forms.Label; lbNortheast: System.Windows.Forms.ListBox; Label3: System.Windows.Forms.Label; lbSoutheast: System.Windows.Forms.ListBox; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> procedure InitializeComponent; {$ENDREGION} strict protected /// <summary> /// Clean up any resources being used. /// </summary> procedure Dispose(Disposing: Boolean); override; private //fCities: TStringList; public constructor Create; end; [assembly: RuntimeRequiredAttribute(TypeOf(TWinForm))] implementation {$AUTOBOX ON} {$REGION 'Windows Form Designer generated code'} /// <summary> /// Required method for Designer support -- do not modify /// the contents of this method with the code editor. /// </summary> procedure TWinForm.InitializeComponent; type TArrayOfSystem_Object = array of System.Object; begin Self.Panel1 := System.Windows.Forms.Panel.Create; Self.pnlPayoffs := System.Windows.Forms.Panel.Create; Self.pnlRegions := System.Windows.Forms.Panel.Create; Self.Label1 := System.Windows.Forms.Label.Create; Self.lbRegions := System.Windows.Forms.ListBox.Create; Self.TabControl1 := System.Windows.Forms.TabControl.Create; Self.tpNortheast := System.Windows.Forms.TabPage.Create; Self.tpSoutheast := System.Windows.Forms.TabPage.Create; Self.tpNorthCentral := System.Windows.Forms.TabPage.Create; Self.tpSouthCentral := System.Windows.Forms.TabPage.Create; Self.tpPlains := System.Windows.Forms.TabPage.Create; Self.tpNorthwest := System.Windows.Forms.TabPage.Create; Self.tpSouthwest := System.Windows.Forms.TabPage.Create; Self.Label2 := System.Windows.Forms.Label.Create; Self.lbNortheast := System.Windows.Forms.ListBox.Create; Self.Label3 := System.Windows.Forms.Label.Create; Self.lbSoutheast := System.Windows.Forms.ListBox.Create; Self.Panel1.SuspendLayout; Self.pnlRegions.SuspendLayout; Self.TabControl1.SuspendLayout; Self.tpNortheast.SuspendLayout; Self.tpSoutheast.SuspendLayout; Self.SuspendLayout; // // Panel1 // Self.Panel1.Controls.Add(Self.TabControl1); Self.Panel1.Controls.Add(Self.pnlRegions); Self.Panel1.Dock := System.Windows.Forms.DockStyle.Left; Self.Panel1.Location := System.Drawing.Point.Create(0, 0); Self.Panel1.Name := 'Panel1'; Self.Panel1.Size := System.Drawing.Size.Create(224, 493); Self.Panel1.TabIndex := 0; // // pnlPayoffs // Self.pnlPayoffs.Dock := System.Windows.Forms.DockStyle.Fill; Self.pnlPayoffs.Location := System.Drawing.Point.Create(224, 0); Self.pnlPayoffs.Name := 'pnlPayoffs'; Self.pnlPayoffs.Size := System.Drawing.Size.Create(528, 493); Self.pnlPayoffs.TabIndex := 1; // // pnlRegions // Self.pnlRegions.Controls.Add(Self.lbRegions); Self.pnlRegions.Controls.Add(Self.Label1); Self.pnlRegions.Dock := System.Windows.Forms.DockStyle.Top; Self.pnlRegions.Location := System.Drawing.Point.Create(0, 0); Self.pnlRegions.Name := 'pnlRegions'; Self.pnlRegions.Size := System.Drawing.Size.Create(224, 192); Self.pnlRegions.TabIndex := 0; // // Label1 // Self.Label1.Dock := System.Windows.Forms.DockStyle.Top; Self.Label1.Location := System.Drawing.Point.Create(0, 0); Self.Label1.Name := 'Label1'; Self.Label1.Size := System.Drawing.Size.Create(224, 16); Self.Label1.TabIndex := 0; Self.Label1.Text := 'Regions'; Self.Label1.TextAlign := System.Drawing.ContentAlignment.MiddleCenter; // // lbRegions // Self.lbRegions.Dock := System.Windows.Forms.DockStyle.Fill; Self.lbRegions.Items.AddRange(TArrayOfSystem_Object.Create('Plains', 'Sout' + 'heast', 'Southeast', 'Southeast', 'North Central', 'North Central', 'Northeast', 'Northeast', 'Northeast', 'Northeast', 'Northeast', 'S' + 'outhwest', 'South Central', 'South Central', 'South Central', 'Sout' + 'hwest', 'Southwest', 'Plains', 'Northwest', 'Northwest', 'Plains', 'N' + 'orthwest')); Self.lbRegions.Location := System.Drawing.Point.Create(0, 16); Self.lbRegions.MultiColumn := True; Self.lbRegions.Name := 'lbRegions'; Self.lbRegions.Size := System.Drawing.Size.Create(224, 173); Self.lbRegions.TabIndex := 1; // // TabControl1 // Self.TabControl1.Controls.Add(Self.tpNortheast); Self.TabControl1.Controls.Add(Self.tpSoutheast); Self.TabControl1.Controls.Add(Self.tpNorthCentral); Self.TabControl1.Controls.Add(Self.tpSouthCentral); Self.TabControl1.Controls.Add(Self.tpPlains); Self.TabControl1.Controls.Add(Self.tpNorthwest); Self.TabControl1.Controls.Add(Self.tpSouthwest); Self.TabControl1.Dock := System.Windows.Forms.DockStyle.Top; Self.TabControl1.Location := System.Drawing.Point.Create(0, 192); Self.TabControl1.Name := 'TabControl1'; Self.TabControl1.SelectedIndex := 0; Self.TabControl1.Size := System.Drawing.Size.Create(224, 224); Self.TabControl1.TabIndex := 1; // // tpNortheast // Self.tpNortheast.Controls.Add(Self.lbNortheast); Self.tpNortheast.Controls.Add(Self.Label2); Self.tpNortheast.Location := System.Drawing.Point.Create(4, 22); Self.tpNortheast.Name := 'tpNortheast'; Self.tpNortheast.Size := System.Drawing.Size.Create(216, 198); Self.tpNortheast.TabIndex := 0; Self.tpNortheast.Text := 'Northeast'; // // tpSoutheast // Self.tpSoutheast.Controls.Add(Self.lbSoutheast); Self.tpSoutheast.Controls.Add(Self.Label3); Self.tpSoutheast.Location := System.Drawing.Point.Create(4, 22); Self.tpSoutheast.Name := 'tpSoutheast'; Self.tpSoutheast.Size := System.Drawing.Size.Create(216, 198); Self.tpSoutheast.TabIndex := 1; Self.tpSoutheast.Text := 'Southeast'; // // tpNorthCentral // Self.tpNorthCentral.Location := System.Drawing.Point.Create(4, 22); Self.tpNorthCentral.Name := 'tpNorthCentral'; Self.tpNorthCentral.Size := System.Drawing.Size.Create(216, 198); Self.tpNorthCentral.TabIndex := 2; Self.tpNorthCentral.Text := 'North Central'; // // tpSouthCentral // Self.tpSouthCentral.Location := System.Drawing.Point.Create(4, 22); Self.tpSouthCentral.Name := 'tpSouthCentral'; Self.tpSouthCentral.Size := System.Drawing.Size.Create(184, 102); Self.tpSouthCentral.TabIndex := 3; Self.tpSouthCentral.Text := 'South Central'; // // tpPlains // Self.tpPlains.Location := System.Drawing.Point.Create(4, 22); Self.tpPlains.Name := 'tpPlains'; Self.tpPlains.Size := System.Drawing.Size.Create(184, 102); Self.tpPlains.TabIndex := 4; Self.tpPlains.Text := 'Plains'; // // tpNorthwest // Self.tpNorthwest.Location := System.Drawing.Point.Create(4, 22); Self.tpNorthwest.Name := 'tpNorthwest'; Self.tpNorthwest.Size := System.Drawing.Size.Create(184, 102); Self.tpNorthwest.TabIndex := 5; Self.tpNorthwest.Text := 'Northwest'; // // tpSouthwest // Self.tpSouthwest.Location := System.Drawing.Point.Create(4, 22); Self.tpSouthwest.Name := 'tpSouthwest'; Self.tpSouthwest.Size := System.Drawing.Size.Create(184, 102); Self.tpSouthwest.TabIndex := 6; Self.tpSouthwest.Text := 'Southwest'; // // Label2 // Self.Label2.Dock := System.Windows.Forms.DockStyle.Top; Self.Label2.Location := System.Drawing.Point.Create(0, 0); Self.Label2.Name := 'Label2'; Self.Label2.Size := System.Drawing.Size.Create(216, 16); Self.Label2.TabIndex := 0; Self.Label2.Text := 'Northeast'; Self.Label2.TextAlign := System.Drawing.ContentAlignment.MiddleCenter; // // lbNortheast // Self.lbNortheast.Dock := System.Windows.Forms.DockStyle.Fill; Self.lbNortheast.Items.AddRange(TArrayOfSystem_Object.Create('New York', 'N' + 'ew York', 'New York', 'Albany', 'Boston', 'Buffalo', 'Boston', 'Por' + 'tland', 'New York', 'New York', 'New York', 'New York', 'Washington', 'Pittsburgh', 'Pittsburgh', 'Philadelphia', 'Washington', 'Philade' + 'lphia', 'Baltimore', 'Baltimore', 'Baltimore', 'New York')); Self.lbNortheast.Location := System.Drawing.Point.Create(0, 16); Self.lbNortheast.MultiColumn := True; Self.lbNortheast.Name := 'lbNortheast'; Self.lbNortheast.Size := System.Drawing.Size.Create(216, 173); Self.lbNortheast.TabIndex := 1; // // Label3 // Self.Label3.Dock := System.Windows.Forms.DockStyle.Top; Self.Label3.Location := System.Drawing.Point.Create(0, 0); Self.Label3.Name := 'Label3'; Self.Label3.Size := System.Drawing.Size.Create(216, 16); Self.Label3.TabIndex := 0; Self.Label3.Text := 'Southeast'; Self.Label3.TextAlign := System.Drawing.ContentAlignment.MiddleCenter; // // lbSoutheast // Self.lbSoutheast.Dock := System.Windows.Forms.DockStyle.Fill; Self.lbSoutheast.Items.AddRange(TArrayOfSystem_Object.Create('Charlotte', 'C' + 'harlotte', 'Chattanooga', 'Atlanta', 'Atlanta', 'Atlanta', 'Richmon' + 'd', 'Knoxville', 'Mobile', 'Knoxville', 'Mobile', 'Norfolk', 'Norfo' + 'lk', 'Norfolk', 'Charleston', 'Miami', 'Jacksonville', 'Miami', 'Ta' + 'mpa', 'Tampa', 'Mobile', 'Norfolk')); Self.lbSoutheast.Location := System.Drawing.Point.Create(0, 16); Self.lbSoutheast.MultiColumn := True; Self.lbSoutheast.Name := 'lbSoutheast'; Self.lbSoutheast.Size := System.Drawing.Size.Create(216, 173); Self.lbSoutheast.TabIndex := 1; // // TWinForm // Self.AutoScaleBaseSize := System.Drawing.Size.Create(5, 13); Self.ClientSize := System.Drawing.Size.Create(752, 493); Self.Controls.Add(Self.pnlPayoffs); Self.Controls.Add(Self.Panel1); Self.Name := 'TWinForm'; Self.Text := 'WinForm'; Self.Panel1.ResumeLayout(False); Self.pnlRegions.ResumeLayout(False); Self.TabControl1.ResumeLayout(False); Self.tpNortheast.ResumeLayout(False); Self.tpSoutheast.ResumeLayout(False); Self.ResumeLayout(False); end; {$ENDREGION} procedure TWinForm.Dispose(Disposing: Boolean); begin if Disposing then begin if Components <> nil then Components.Dispose(); end; inherited Dispose(Disposing); end; constructor TWinForm.Create; begin inherited Create; // // Required for Windows Form Designer support // InitializeComponent; // // TODO: Add any constructor code after InitializeComponent call // end; end.
{$B-,I-,Q-,R-,S-} {$M 16384,0,655360} {94¦ Apilamiento de Platos. Polonia 2005 ---------------------------------------------------------------------- Las vacas quieren estar en la TV. Ellas han decidido que su mejor oportunidad es mostrar su habilidad en apilar platos tan alto como ellas posiblemente lo puedan hacer. Su propósito es maximizar el valor de entretenimiento apilando ciertos platos que son lanzados del estudio izquierdo al estudio central. Por supuesto, los platos pueden ser únicamente apilados cuando un plato estrictamente menor es puesto encima de un plato más grande. Por lo tanto, algunos platos podrían ser descartados. Dada la secuencia de enteros de N (1 <= N <= 5,000) platos lanzados desde el lado del estudio, calcule la altura (en platos) de la estructura de platos apilados más alta posible que puede ser construida. Los tamaños son enteros en el rango 1..1,000,000. Si los platos fueran lanzados en este orden: 7 10 7 8 9 7 8 6 4 Entonces la pila mas alta posible seria 10, 9, 8, 6, 4, cuya altura es 5. FORMATO DE ENTRADA: - Línea 1: Un solo entero, N - Líneas 2..N+1: La línea i+1 describe el i-'esimo plato lanzado desde el lado del estudio. ENTRADA EJEMPLO (archivo plates.in): 9 7 10 7 8 9 7 8 6 4 FORMATO DE SALIDA: - Línea 1: Una sola línea con la altura máxima de platos que se puede obtener. SALIDA EJEMPLO (archivo plates.out): 5 } var fe,fs : text; n,sol : longint; a,b : array[1..5000] of longint; procedure open; var t : longint; begin assign(fe,'plates.in'); reset(fe); assign(fs,'plates.out'); rewrite(fs); readln(fe,n); for t:=1 to n do readln(fe,a[t]); close(fe); end; procedure work; var i,j : longint; begin sol:=0; fillchar(b,sizeof(b),0); for i:=1 to n do begin for j:=1 to i-1 do if (a[i] < a[j]) and (b[j] > b[i]) then b[i]:=b[j]; inc(b[i]); if b[i]>sol then sol:=b[i]; end; end; procedure closer; begin writeln(fs,sol); close(fs); end; begin open; work; closer; end.
unit frmCliente; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Mask, Vcl.StdCtrls, Vcl.Buttons, Data.DB, Vcl.Grids, Vcl.DBGrids; type TfrmClientes = class(TForm) btnNovo: TBitBtn; btnSalvar: TBitBtn; btnCancelar: TBitBtn; btnLimpar: TBitBtn; btnSair: TBitBtn; Cliente: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; tbNomeCliente: TEdit; tbEndereco: TEdit; tbDataCadastro: TMaskEdit; DBGrid1: TDBGrid; tbDataNascimento: TMaskEdit; btnAdicionarClienteVenda: TBitBtn; procedure btnSairClick(Sender: TObject); procedure tbNomeClienteChange(Sender: TObject); procedure LimparEdits(); procedure btnLimparClick(Sender: TObject); procedure ControlaBotoes(prmEnable: Boolean); procedure ControlaEdits(prmEnable: Boolean); procedure btnNovoClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnAdicionarClienteVendaClick(Sender: TObject); private { Private declarations } public { Public declarations } pbcIDCliente, pbcIDVenda: Integer; end; var frmClientes: TfrmClientes; implementation {$R *.dfm} uses frmDataModulo, Funcoes, untInterfaces, untClasses; procedure TfrmClientes.btnAdicionarClienteVendaClick(Sender: TObject); begin if not dmPrincipal.qrCliente.Active then begin MessageDlg('Favor buscar cliente!',mtConfirmation,[mbOK], 0); tbNomeCliente.SetFocus; Exit(); end; if dmPrincipal.qrCliente.RecordCount = 0 then begin MessageDlg('Cliente inexistente ou não selecionado!',mtConfirmation,[mbOK], 0); tbNomeCliente.SetFocus; Exit(); end; if pbcIDVenda = 0 then begin MessageDlg('Venda não iniciada, impossível adicionar cliente!',mtConfirmation,[mbOK], 0); Exit(); end; pbcIDCliente := dmPrincipal.qrCliente.FieldByName('ID').AsInteger; Close(); end; procedure TfrmClientes.btnCancelarClick(Sender: TObject); begin LimparEdits(); ControlaBotoes(true); ControlaEdits(false); tbNomeCliente.SetFocus(); end; procedure TfrmClientes.btnLimparClick(Sender: TObject); begin ControlaBotoes(true); ControlaEdits(false); LimparEdits(); tbNomeCliente.SetFocus(); dmPrincipal.qrCliente.Close(); end; procedure TfrmClientes.btnNovoClick(Sender: TObject); begin ControlaBotoes(false); ControlaEdits(true); tbDataCadastro.Text := DateToStr(date); dmPrincipal.qrCliente.Close(); tbNomeCliente.SetFocus(); end; procedure TfrmClientes.btnSairClick(Sender: TObject); begin Close; end; procedure TfrmClientes.btnSalvarClick(Sender: TObject); var LocDataNascimento: String; LocAdicionarCliente: IAdicionarCliente; begin try LocAdicionarCliente := TAdicionarCliente.Create(); if tbNomeCliente.Text = '' then //Testando nome vazio begin MessageDlg('Favor digitar o nome do cliente!',mtConfirmation,[mbOK], 0); tbNomeCliente.SetFocus; Exit(); end; if tbEndereco.Text = '' then //Testando endereço vazio begin MessageDlg('Favor digitar o endereço do cliente!',mtConfirmation,[mbOK], 0); tbEndereco.SetFocus; Exit(); end; LocDataNascimento := tbDataNAscimento.Text; LocDataNascimento := Trim(LocDataNascimento.Replace('/','')); if LocDataNascimento = '' then begin MessageDlg('Favor digitar a data de nascimento do cliente!',mtConfirmation,[mbOK], 0); tbDataNAscimento.SetFocus; Exit(); end; if not IsDate(tbDataNascimento.Text) then begin MessageDlg('Favor digitar uma data de nascimento válida!',mtConfirmation,[mbOK], 0); tbDataNAscimento.SetFocus; Exit(); end; if not LocAdicionarCliente.ADD(tbNomeCliente.Text, tbEndereco.Text, tbDataNascimento.Text, tbDataCadastro.Text) then begin MessageDlg('Erro ao salvar Cliente!',mtConfirmation,[mbOK], 0); Exit(); end; if MessageDlg('Cliente '+tbNomeCliente.Text+' salvo com sucesso!'+#13+ 'Deseja adicionar o cliente na venda?', mtConfirmation,[mbYes, mbNO], 0) = 6 then begin if pbcIDVenda = 0 then begin MessageDlg('Venda não iniciada!',mtConfirmation,[mbOK], 0); end else pbcIDCliente := dmPrincipal.qrCliente.FieldByName('ID').AsInteger; end; finally dmPrincipal.qrCliente.Close(); LimparEdits(); tbNomeCliente.SetFocus; ControlaEdits(false); ControlaBotoes(true); end; end; //Função para contorlar os botões procedure TfrmClientes.ControlaBotoes(prmEnable: Boolean); begin btnNovo.Enabled := prmEnable; btnSalvar.Enabled := not prmEnable; btnCancelar.Enabled := not prmEnable; end; procedure TfrmClientes.ControlaEdits(prmEnable: Boolean); begin tbEndereco.Enabled := prmEnable; tbDataNascimento.Enabled := prmEnable; tbDataCadastro.Enabled := prmEnable; end; //Função para limpar os edits do formulário procedure TfrmClientes.LimparEdits; begin tbNomeCliente.Clear(); tbEndereco.Clear(); tbDataCadastro.Clear(); tbDataNAscimento.Clear(); end; procedure TfrmClientes.tbNomeClienteChange(Sender: TObject); var LocBuscarClienteNome: IBuscarClienteNome; begin if (tbNomeCliente.Text <> '') and btnNovo.Enabled then begin LocBuscarClienteNome:= TBuscarClienteNome.Create(); if not LocBuscarClienteNome.Buscar(tbNomeCliente.Text, false) then MessageDlg('Erro ao buscar Cliente!',mtConfirmation,[mbOK], 0); end; end; end.
unit UnitMain; (* The purpose of this demo is to show how to Tab in and out of the Crystal Reports Preview Window when it is part of your Form. Normally the Crystal Preview retains the keyboard focus and is not in the Forms internal List of controls, so cannot be tabbed in and out of. One way around this is to trap the Windows messages that go to the Crystal Preview Window. The actual Report is drawn on a child window, 3 levels deep, so the Window Procedure for this child must be captured and redirected to another user-defined procedure. In this user-defined procedure we can handle the messages as they come in and respond to them as we like. The following demo shows how to handle the TAB keypress to include the Crystal window in the Tab order of the Form. It also displays the Decimal value of any keys that are pressed over the Crystal Window. Many other messages could be trapped, check a good book on Windows API messages, or consult your Delphi source code for more ideas. *) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32, UCrpeClasses; type WParameter = LongInt; LParameter = LongInt; TfrmMain = class(TForm) Panel1: TPanel; btnLoad: TButton; btnClose: TButton; CheckBox1: TCheckBox; Edit1: TEdit; Panel2: TPanel; Crpe1: TCrpe; OpenDialog1: TOpenDialog; btnAbout: TButton; procedure btnLoadClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnAboutKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnAboutClick(Sender: TObject); procedure Panel2Resize(Sender: TObject); procedure btnLoadKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var frmMain : TfrmMain; OldWindowProc : Pointer; FromRpt : Boolean; implementation uses UnitAbout; {$R *.DFM} procedure TfrmMain.btnLoadClick(Sender: TObject); var a1 : array[0..255] of Char; s1 : string; xWnd : HWnd; sWinName1 : string; sWinName2 : string; {This is the replacement Window Procedure for the Crystal Preview} function NewWindowProc(WindowHandle: hWnd; TheMessage: WParameter; ParamW: WParameter; ParamL: LParameter): LongInt stdcall; begin { Process the message of your choice here } case TheMessage of {Scroll keys} WM_VSCROLL: begin frmMain.Edit1.Text := 'Vertical Scroll'; end; WM_HSCROLL: begin frmMain.Edit1.Text := 'Horizontal Scroll'; end; {Any keys} WM_CHAR: begin {If not Tab, handle it...} if ParamW <> 9 then frmMain.Edit1.Text := 'Decimal: ' + IntToStr(ParamW) + ' / ' + 'Ascii: ' + CHR(ParamW); {Could do something like this in response to certain keypresses: SendMessage(WindowHandle, WM_VSCROLL, 1, 0);} end; end; case ParamW of {Tab key pressed} VK_TAB : begin FromRpt := True; {Is Shift key held down?} if GetKeyState(VK_SHIFT) < 0 then begin if ActiveControl = frmMain.btnAbout then ActiveControl := nil; frmMain.edit1.Text := 'About Btn Focused'; frmMain.btnAbout.SetFocus; end {No Shift key} else begin if ActiveControl = frmMain.btnLoad then ActiveControl := nil; frmMain.edit1.Text := 'Load Btn Focused'; frmMain.btnLoad.SetFocus; end; end; end; { Exit here and return zero if you want } { to stop further processing of the message } { Call the old Window procedure to } { allow default processing of the message. } NewWindowProc := CallWindowProc(OldWindowProc, WindowHandle, TheMessage, ParamW, ParamL); end; begin OpenDialog1.FileName := '*.rpt'; OpenDialog1.Filter := 'Crystal Report (*.RPT)|*.rpt'; OpenDialog1.Title := 'Load Report...'; OpenDialog1.InitialDir := ExtractFilePath(Application.ExeName); if not OpenDialog1.Execute then Exit; Refresh; FromRpt := False; Crpe1.ReportName := OpenDialog1.FileName; Crpe1.Output := toWindow; Crpe1.WindowParent := Panel2; Crpe1.WindowStyle.BorderStyle := bsNone; Crpe1.Execute; while Crpe1.Status <> crsJobCompleted do Application.ProcessMessages; {Check Versions} if Crpe1.Version.Crpe.Major > 6 then begin sWinName1 := 'AfxWnd42'; sWinName2 := 'AfxFrameOrView42'; end {SCR 6 uses AfxWnd42s, AfxFrameOrView42s} else begin sWinName1 := 'AfxWnd42s'; sWinName2 := 'AfxFrameOrView42s'; end; xWnd := Crpe1.ReportWindowHandle; {AfxWnd42 - The first child frame} {SCR 6 uses AfxWnd42s} xWnd := GetWindow(xWnd, GW_CHILD); {Afx:n2 or AfxWnd42 - could be either depending on WindowButtonBar settings. We want AfxWnd42, so if this is not it, we need one more step.} xWnd := GetWindow(xWnd, GW_CHILD); GetClassName(xWnd, a1, 256); s1 := StrPas (a1); if s1 <> sWinName1 then xWnd := GetWindow(xWnd, GW_HWNDNEXT); {AfxMDIFrame42 or AfxFrameOrView42 - could be either depending WindowButtonBar settings. We want AfxFrameOrView42, so if this is not it, we need to take two more steps.} xWnd := GetWindow(xWnd, GW_CHILD); GetClassName(xWnd, a1, 256); s1 := StrPas(a1); if s1 <> sWinName2 then begin xWnd := GetWindow(xWnd, GW_CHILD); GetClassName(xWnd, a1, 256); s1 := StrPas(a1); if s1 <> sWinName2 then xWnd := GetWindow(xWnd, GW_HWNDNEXT); end; { Set the new window procedure for the control and remember the old window procedure. If the Crystal Window is separate from the Form, you may have to restore the OldWindowProc if your Form is closed with the Crystal Window open. } OldWindowProc := Pointer(SetWindowLong(xWnd, GWL_WNDPROC, LongInt(@NewWindowProc))); Edit1.Text := 'Report Focused'; Crpe1.SetFocus; ActiveControl := nil; end; procedure TfrmMain.btnAboutKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin {This is the last control. If the focus was changed in forward direction (Tab) set focus to Crpe} if FromRpt then begin FromRpt := False; Exit; end; if Crpe1.ReportWindowHandle = 0 then Exit; if (Key = vk_Tab) and not (ssShift in Shift) then begin if ActiveControl = btnAbout then ActiveControl := nil; Edit1.Text := 'Report Focused'; Crpe1.SetFocus; end; end; procedure TfrmMain.btnCloseClick(Sender: TObject); begin Crpe1.CloseWindow end; procedure TfrmMain.btnAboutClick(Sender: TObject); begin dlgAbout.Show; end; procedure TfrmMain.Panel2Resize(Sender: TObject); begin if Crpe1.ReportWindowHandle > 0 then begin SetWindowPos(Crpe1.ReportWindowHandle, HWND_TOP, 0, 0, Panel2.Width, Panel2.Height, SWP_NOZORDER); end; end; procedure TfrmMain.btnLoadKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin {This is the first control. If the focus was changed in reverse direction (Shift key) set focus to Crpe} if FromRpt then begin FromRpt := False; Exit; end; if Crpe1.ReportWindowHandle = 0 then Exit; if (Key = vk_Tab) and (ssShift in Shift) then begin if ActiveControl = btnLoad then ActiveControl := nil; Edit1.Text := 'Report Focused'; Crpe1.SetFocus; end else Edit1.Text := 'Load Btn Focused'; end; end.
unit TestThItemControl; interface uses TestFramework, BaseTestUnit, FMX.Platform, FMX.StdCtrls, System.Types, System.SysUtils, FMX.Types, FMX.Objects, System.UIConsts; type // #140 아이템을 캔버스에서 제거한다. TestTThItemControl = class(TThCanvasBaseTestUnit) published // #141 아이템 삭제 후 캔버스에 표시되지 않아야 한다. procedure TestItemDelete; // #142 아이템 삭제 후 컨텐츠 숫자가 감소해야 한다. procedure TestItemDeleteCheckContentsCount; // #65 Shift 키를 누르고 객체를 선택하면 선택이 추가된다. procedure TestItemMultiSelectShiftKey; // #67 캔버스를 선택하면 모든 선택이 취소된다. procedure TestItemMultiSelectionCancel; // #66 Shift 키를 누르고 이미 선택된 객체를 선택하면 선택이 취소된다. procedure TestItemMultiUnselect; // #146 다중 선택 후 이동되어야 한다. procedure TestMultiselectAndMove; // #147 다중 선택 후 삭제할 수 있어야 한다. procedure TestMultiselectAndDelete; // #151 다중선택 후 Shift 누른 후 아이템 Tracking 오류 procedure BugTestMultiselectShiftMove; // #150 다른컨트롤에서 Shift 누른 후 여러개 선택 시 여러개 선택되지 않음 procedure BugTestAnotherContrlShfitPressAndMultiselect; // #158 A아이템 삭제 후 Shift로 B 중복선택 시 B가 단독선택되어야 한다. procedure TestItemDeleteAndSelectionClear; // #168 Selected 시 Selection에 반영되야 한다. procedure TestItemSelectToProcessSelction; // #169 마우스 클릭으로 selected 시 Selection에 반영되야 한다. procedure TestItemMouseClickToProcessSelction; // #171 다중 선택 시 Selection에 반영되야 한다. procedure TestItemSelectToShowSelection; procedure TestItemUnselectToHideSelection; // #172 다른아이템 선택 시 아이템 이동 시 선택이 변경되야 한다. procedure TestAnotherSelectedAndMoveChangeSelection; // #173 2개의 아이템 선택 상태에서 이동 시 2개 선택이 유지되어야 한다. procedure TestMultiselectionAndMove; // #174 2개의 아이템 선택 상태에서 하나 클릭 시 클릭한 아이템 선택해제 procedure TestMultiselectAndShiftClickSingleSelect; // #184 다중 선택 시 모든 아이템에 외곽선이 표시되어야 한다. procedure TestMultiselectDrawOutline; // #186 다중 선택 해제 시 하나만 선택되는 경우 ResizeSpot이 표시되어야 한다. procedure TestMultiselectAndUnselectResizeSpot; // #185 다중 선택된 ResizeSpot은 마우스로 크기 변경이 되지 않아야 한다. procedure TestMultiselectCantResize; // #182 다중 선택 시 하이라이트는 마우스오버된 경우만 표시되야 한다. procedure TestShowHighlightOnlyMouseOver; // #229 아이템 Resize(ResizeSpot mouse over) 시 Highligher가 감춰짐 procedure BugHighlightResizeSpotMouserOver; end; implementation uses UnitTestForm, FMX.TestLib, ThCanvas, ThCanvasEditor, ThConsts, ThItem, ThShapeItem, ThItemFactory, FMX.Controls, UITypes; { TestTThItemDelete } procedure TestTThItemControl.TestItemDelete; begin DrawRectangle(10, 10, 100, 100); TestLib.RunMouseClick(50, 50); FCanvas.DeleteSelection; Check(not Assigned(FCanvas.SelectedItem), 'Delete selection'); TestLib.RunMouseClick(50, 50); Check(not Assigned(FCanvas.SelectedItem), 'Not selected item'); end; procedure TestTThItemControl.TestItemDeleteCheckContentsCount; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(20, 20, 110, 110); DrawRectangle(30, 30, 120, 120); TestLib.RunMouseClick(50, 50); FCanvas.DeleteSelection; Check(not Assigned(FCanvas.SelectedItem), 'Delete selection'); TestLib.RunMouseClick(50, 50); Check(FCanvas.ItemCount = 2); end; procedure TestTThItemControl.TestItemMultiSelectShiftKey; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(150, 150, 250, 250); TestLib.RunMouseClick(50, 50); TestLib.RunKeyDownShift; TestLib.RunMouseClick(200, 200); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 2); end; procedure TestTThItemControl.TestItemMultiSelectionCancel; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(150, 150, 250, 250); TestLib.RunMouseClick(50, 50); TestLib.RunKeyDownShift; TestLib.RunMouseClick(200, 200); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 2, 'Select'); TestLib.RunMouseClick(110, 10); Check(FCanvas.SelectionCount = 0, 'Unselect'); end; procedure TestTThItemControl.TestItemMultiUnselect; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(150, 150, 250, 250); TestLib.RunMouseClick(50, 50); TestLib.RunKeyDownShift; TestLib.RunMouseClick(170, 170); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 2, 'Select'); TestLib.RunKeyDownShift; TestLib.RunMouseClick(201, 200); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 1, 'Unselect'); end; procedure TestTThItemControl.TestMultiselectAndMove; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 200, 200); TestLib.RunMouseClick(50, 50); TestLib.RunKeyDownShift; TestLib.RunMouseClick(170, 170); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 2, 'Select'); MousePath.New .Add(170, 180) .Add(170, 200) .Add(200, 200); TestLib.RunMousePath(MousePath.Path); TestLib.RunMouseClick(0, 0); TestLib.RunMouseClick(50, 50); Check(Assigned(FCanvas.SelectedItem), 'Assigned'); Check(Round(FCanvas.SelectedItem.Position.X) = -110, Format('X: %f', [FCanvas.SelectedItem.Position.X])); end; procedure TestTThItemControl.TestMultiselectAndDelete; begin DrawRectangle(10, 10, 50, 50); DrawRectangle(10, 60, 50, 100); DrawRectangle(110, 110, 200, 200); DrawRectangle(10, 110, 70, 200); TestLib.RunMouseClick(40, 40); TestLib.RunKeyDownShift; TestLib.RunMouseClick(170, 170); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 2, 'Select'); FCanvas.DeleteSelection; Check(not Assigned(FCanvas.SelectedItem), 'Delete selection'); TestLib.RunMouseClick(50, 50); Check(FCanvas.ItemCount = 2); end; procedure TestTThItemControl.BugTestMultiselectShiftMove; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(50, 50); TestLib.RunKeyDownShift; TestLib.RunMouseClick(169, 170); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 2, 'Select'); { TestLib.RunMouseClick(1, 1); TestLib.RunMouseClick(170, 175); Check(FCanvas.SelectionCount = 1, 'Select2'); exit; } TestLib.RunKeyDownShift; MousePath.New .Add(150, 150) .Add(171, 181) .Add(172, 182) .Add(173, 183) .Add(174, 184) .Add(180, 200) .Add(200, 200); TestLib.RunMousePath(MousePath.Path); TestLib.RunKeyUpShift; TestLib.RunMouseClick(0, 0); TestLib.RunMouseClick(100, 100); Check(Assigned(FCanvas.SelectedItem), 'Assigned'); Check(Round(FCanvas.SelectedItem.Position.X) = -90, Format('Item.X: %f', [FCanvas.SelectedItem.Position.X])); TestLib.RunMouseClick(200, 200); Check(Assigned(FCanvas.SelectedItem), 'Assigned 2'); Check(Round(FCanvas.SelectedItem.Position.X) = 10, Format('Item2.X: %f', [FCanvas.SelectedItem.Position.X])); end; procedure TestTThItemControl.BugTestAnotherContrlShfitPressAndMultiselect; var Button: TButton; begin Button := TButton.Create(FForm); Button.Parent := FForm; Button.Position.Point := PointF(0,0); Button.Width := 50; Button.Height := 100; Button.SendToBack; DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(50, 50); TestLib.RunKeyDownShift; // Button click TestLib.RunMouseClick(-10, -10); TestLib.RunMouseClick(169, 170); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 2); end; procedure TestTThItemControl.TestItemDeleteAndSelectionClear; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(50, 50); FCanvas.DeleteSelection; TestLib.RunKeyDownShift; TestLib.RunMouseClick(169, 170); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 1); end; procedure TestTThItemControl.TestItemSelectToProcessSelction; begin DrawRectangle(10, 10, 100, 100); TestLib.RunMouseClick(50, 50); CheckNotNull(FCanvas.SelectedItem, 'Click'); FCanvas.SelectedItem.Selected := False; CheckNull(FCanvas.SelectedItem, 'Unselectd'); end; procedure TestTThItemControl.TestItemMouseClickToProcessSelction; begin DrawRectangle(10, 10, 100, 100); TestLib.RunMouseClick(50, 50); CheckNotNull(FCanvas.SelectedItem, 'Click'); TestLib.RunMouseClick(150, 150); CheckNull(FCanvas.SelectedItem, 'Unselectd'); end; procedure TestTThItemControl.TestItemSelectToShowSelection; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(50, 50); Check(TestLib.GetControlPixelColor(FCanvas, 10, 10) = ItemResizeSpotOutColor, Format('Not matching color TopLeft(%d, %d)', [TestLib.GetControlPixelColor(FCanvas, 10, 10), ItemResizeSpotOutColor])); end; procedure TestTThItemControl.TestItemUnselectToHideSelection; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(50, 50); TestLib.RunMouseClick(150, 150); Check(FCanvas.SelectionCount = 1, Format('Count: %d', [FCanvas.SelectionCount])); Check(TestLib.GetControlPixelColor(FCanvas, 10, 10) <> ItemResizeSpotOutColor, Format('Not matching color TopLeft(%d, %d)', [TestLib.GetControlPixelColor(FCanvas, 10, 10), ItemResizeSpotOutColor])); end; procedure TestTThItemControl.TestAnotherSelectedAndMoveChangeSelection; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(50, 50); MousePath.New .Add(150, 150) .Add(180, 200) .Add(200, 200); TestLib.RunMousePath(MousePath.Path); Check(FCanvas.SelectionCount = 1, Format('Count: %d', [FCanvas.SelectionCount])); Check(Round(FCanvas.SelectedItem.Position.X) = 10, Format('Change selection failed X: %f', [FCanvas.SelectedItem.Position.X])); Check(FCanvas.SelectedItem.Width = 70, 'Change selection failed'); end; procedure TestTThItemControl.TestMultiselectionAndMove; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(50, 50); TestLib.RunKeyDownShift; TestLib.RunMouseClick(150, 150); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 2, Format('Selection Count: %d', [FCanvas.SelectionCount])); MousePath.New .Add(150, 150) .Add(180, 200) .Add(200, 200); TestLib.RunMousePath(MousePath.Path); Check(FCanvas.SelectionCount = 2, Format('Count: %d', [FCanvas.SelectionCount])); end; procedure TestTThItemControl.TestMultiselectAndShiftClickSingleSelect; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(50, 50); TestLib.RunKeyDownShift; TestLib.RunMouseClick(150, 150); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 2, Format('Selection Count: %d', [FCanvas.SelectionCount])); TestLib.RunKeyDownShift; TestLib.RunMouseClick(160, 160); TestLib.RunKeyUpShift; Check(FCanvas.SelectionCount = 1, Format('Count: %d', [FCanvas.SelectionCount])); Check(FCanvas.SelectedItem.Position.X = -140, FOrmat('Position %f',[FCanvas.SelectedItem.Position.X])); end; procedure TestTThItemControl.TestMultiselectDrawOutline; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(169, 170); TestLib.RunKeyDownShift; TestLib.RunMouseClick(50, 50); TestLib.RunKeyUpShift; // ResizeSpot 표시 확인 Check(TestLib.GetControlPixelColor(FCanvas, 10, 10) = ItemResizeSpotDisableColor, Format('Not matching color TopLeft(%d, %d)', [TestLib.GetControlPixelColor(FCanvas, 10, 10), ItemResizeSpotDisableColor])); Check(TestLib.GetControlPixelColor(FCanvas, 180, 180) = ItemResizeSpotDisableColor, Format('Not matching color BottomRight(%d, %d)', [TestLib.GetControlPixelColor(FCanvas, 10, 10), ItemResizeSpotDisableColor])); end; procedure TestTThItemControl.TestMultiselectAndUnselectResizeSpot; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(169, 170); TestLib.RunKeyDownShift; TestLib.RunMouseClick(50, 50); TestLib.RunMouseClick(50, 50); TestLib.RunKeyUpShift; Check(TestLib.GetControlPixelColor(FCanvas, 180, 180) = ItemResizeSpotOutColor, Format('Not matching color BottomRight(%d, %d)', [TestLib.GetControlPixelColor(FCanvas, 10, 10), ItemResizeSpotOutColor])); end; procedure TestTThItemControl.TestMultiselectCantResize; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(169, 170); TestLib.RunKeyDownShift; TestLib.RunMouseClick(50, 50); TestLib.RunKeyUpShift; MousePath.New .Add(180, 180) .Add(180, 200) .Add(200, 200); TestLib.RunMousePath(MousePath.Path); FCanvas.ClearSelection; TestLib.RunMouseClick(150, 150); CheckNotNull(FCanvas.SelectedItem); Check(FCanvas.SelectedItem.Width = 70, Format('Width: %f', [FCanvas.SelectedItem.Width])); end; procedure TestTThItemControl.TestShowHighlightOnlyMouseOver; var AC: TAlphaColor; begin DrawRectangle(10, 10, 100, 100); DrawRectangle(110, 110, 180, 180); TestLib.RunMouseClick(169, 170); TestLib.RunKeyDownShift; TestLib.RunMouseClick(50, 50); TestLib.RunKeyUpShift; MousePath.New .Add(250, 250); TestLib.RunMouseMove(MousePath.Path); AC := TestLib.GetControlPixelColor(FCanvas, 20, 100 + (ItemHighlightSize - 1)); Check(AC <> ItemHighlightColor); end; procedure TestTThItemControl.BugHighlightResizeSpotMouserOver; var AC: TAlphaColor; begin Exit; DrawRectangle(10, 10, 100, 100); TestLib.RunMouseClick(50, 50); TestLib.RunMouseMove(MousePath.Add(100, 100).Path); AC := TestLib.GetControlPixelColor(FCanvas, 50, 100 + (ItemHighlightSize - 1)); Check(AC = ItemHighlightColor); end; initialization RegisterTest(TestTThItemControl.Suite); end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2014 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit ClientFormU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IPPeerClient, REST.Backend.EMSProvider, REST.Backend.EMSFireDAC, REST.Backend.ServiceTypes, System.JSON, REST.Backend.EMSServices, Vcl.StdCtrls, REST.Client, Data.Bind.Components, Data.Bind.ObjectScope, REST.Backend.EndPoint, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, System.Actions, Vcl.ActnList; type TClientForm = class(TForm) EMSFireDACClient1: TEMSFireDACClient; EMSProvider1: TEMSProvider; Button1: TButton; DBGrid1: TDBGrid; DBGrid2: TDBGrid; Panel1: TPanel; Button2: TButton; ActionList1: TActionList; ActionGetTables: TAction; ActionPostUpdates: TAction; procedure ActionGetTablesExecute(Sender: TObject); procedure ActionGetTablesUpdate(Sender: TObject); procedure ActionPostUpdatesExecute(Sender: TObject); procedure ActionPostUpdatesUpdate(Sender: TObject); private { Private declarations } public { Public declarations } end; var ClientForm: TClientForm; implementation {$R *.dfm} uses ClientModuleU; procedure TClientForm.ActionGetTablesExecute(Sender: TObject); begin EMSFireDACClient1.GetData; end; procedure TClientForm.ActionGetTablesUpdate(Sender: TObject); begin // end; procedure TClientForm.ActionPostUpdatesExecute(Sender: TObject); begin EMSFireDACClient1.PostUpdates; end; procedure TClientForm.ActionPostUpdatesUpdate(Sender: TObject); begin TAction(Sender).Enabled := EMSFireDACClient1.CanPostUpdates; end; end.
// ################################## // ###### IT PAT 2018 ####### // ###### GrowCery ####### // ###### Tiaan van der Riel ####### // ################################## unit clsDisplayUserInfo_u; interface uses SysUtils; type TDisplayUserInfo = class(TObject) private fUserAccountID: string; public constructor Create(sUserAccountID: string); function GetUserAccountID: string; function TOString: string; end; implementation uses dmDatabase_u; { TDisplayUserInfo } constructor TDisplayUserInfo.Create(sUserAccountID: string); begin fUserAccountID := sUserAccountID; end; function TDisplayUserInfo.GetUserAccountID: string; begin Result := fUserAccountID; end; function TDisplayUserInfo.TOString: string; var sString: string; begin with dmDatabase do Begin qryAccounts.SQL.Clear; qryAccounts.SQL.Add( 'SELECT AccountID, Name, Surname, IsAdmin, AssignedTill '); qryAccounts.SQL.Add('FROM Accounts '); qryAccounts.SQL.Add('WHERE AccountID = "' + fUserAccountID + '"'); qryAccounts.Open; /// Get data from SQL sString := 'Logged On User: ' + qryAccounts['Name'] + ' ' + qryAccounts ['Surname'] + #13; sString := sString + 'Account ID: ' + qryAccounts['AccountID'] + #13; if qryAccounts['IsAdmin'] = FALSE then begin sString := sString + 'Allocated Cash Register: ' + IntToStr (qryAccounts['AssignedTill']) + #13; end; sString := sString + 'GrowCery - Protea Heights Branch' ; if qryAccounts['IsAdmin'] = TRUE then begin sString := sString + #13 + '*** Administrative Rights Granted'; end; End; // With Result := sString; end; end.
unit Watermarks.INI; //------------------------------------------------------------------------------ // класс watermark'ов // работающий на ini-файлах // // параметры конструктора: // AFileName - имя файла // ASectionName - название скции в файле // ASaveInterval - интервал между сохранениями, секунд //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, IniFiles, Classes, // TStringList System.Generics.Collections, Watermarks.Base, Ils.Utils; //------------------------------------------------------------------------------ type //------------------------------------------------------------------------------ //! //------------------------------------------------------------------------------ TSavedPair = TPair<string, Boolean>; TSavedStorage = class(TDictionary<string, Boolean>); //------------------------------------------------------------------------------ //! класс watermark'ов //------------------------------------------------------------------------------ TWatermarksINI = class sealed(TWatermarksTimed) private //! FSaved: TSavedStorage; //! FIniFile: TIniFile; //! FSectionName: string; //! procedure LoadFile(); //! procedure StoreFile(); protected //! procedure OnCycleTimer( Sender: TObject ); override; public //! constructor Create( const AFileName: string; const ASectionName: string; const ASaveInterval: Integer ); //! destructor Destroy(); override; //! procedure SetWatermark( const AKey: string; const ATimestamp: TDateTime ); override; //! procedure DeleteWatermark( const AKey: string ); override; end; //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ // TWatermarksINI //------------------------------------------------------------------------------ constructor TWatermarksINI.Create( const AFileName: string; const ASectionName: string; const ASaveInterval: Integer ); begin inherited Create(ASaveInterval); // FSectionName := ASectionName; FIniFile := TIniFile.Create(AFileName); FSaved := TSavedStorage.Create(); LoadFile(); end; destructor TWatermarksINI.Destroy(); begin StoreFile(); FIniFile.Free(); FSaved.Free(); // inherited Destroy(); end; procedure TWatermarksINI.SetWatermark( const AKey: string; const ATimestamp: TDateTime ); begin FLocker.Acquire(); try inherited; FSaved.AddOrSetValue(AKey, False); finally FLocker.Release(); end; end; procedure TWatermarksINI.DeleteWatermark( const AKey: string ); begin FLocker.Acquire(); try inherited; FSaved.Remove(AKey); FIniFile.DeleteKey(FSectionName, AKey); finally FLocker.Release(); end; end; procedure TWatermarksINI.OnCycleTimer( Sender: TObject ); begin StoreFile(); end; procedure TWatermarksINI.LoadFile(); var //! LoadSL: TStringList; //! TempStr: string; //! I: Integer; //------------------------------------------------------------------------------ begin LoadSL := TStringList.Create(); try FIniFile.ReadSectionValues(FSectionName, LoadSL); for I := 0 to LoadSL.Count - 1 do begin TempStr := LoadSL.Names[I]; FWM.Add(TempStr, IlsToDateTime(LoadSL.Values[TempStr])); end; finally LoadSL.Free(); end; end; procedure TWatermarksINI.StoreFile(); var //! KeyIter: string; //------------------------------------------------------------------------------ begin FLocker.Acquire(); try for KeyIter in FWM.Keys do begin if FSaved.ContainsKey(KeyIter) then begin FIniFile.WriteString(FSectionName, KeyIter, DateTimeToIls(FWM[KeyIter])); FSaved.Remove(KeyIter); end; end; finally FLocker.Release(); end; end; end.
unit Box; interface uses Types, Classes, Contnrs, Graphics, Node; type TBox = class; TBoxClass = class of TBox; TBoxList = class; // TBoxNode = class(TNode) public procedure Measure(inBox: TBox); virtual; abstract; procedure Render(inBox: TBox; inCanvas: TCanvas; inRect: TRect); virtual; abstract; end; // TBox = class protected function CreateBoxList: TBoxList; procedure MeasureBox(inBox: TBox); virtual; procedure MeasureBoxes; public Node: TNode; Left: Integer; Top: Integer; Width: Integer; Height: Integer; Offset: TPoint; Boxes: TBoxList; constructor Create; destructor Destroy; override; function AddBox: TBox; overload; function AddBox(inClass: TBoxClass): TBox; overload; procedure Measure; end; // TBoxList = class(TObjectList) protected function GetBox(inIndex: Integer): TBox; function GetMax: Integer; procedure SetBox(inIndex: Integer; const Value: TBox); public function AddBox: TBox; overload; function AddBox(inClass: TBoxClass): TBox; overload; property Box[inIndex: Integer]: TBox read GetBox write SetBox; default; property Max: Integer read GetMax; end; implementation { TBox } constructor TBox.Create; begin end; destructor TBox.Destroy; begin Boxes.Free; inherited; end; function TBox.CreateBoxList: TBoxList; begin if Boxes = nil then Boxes := TBoxList.Create; Result := Boxes; end; function TBox.AddBox(inClass: TBoxClass): TBox; begin Result := CreateBoxList.AddBox(inClass); end; function TBox.AddBox: TBox; begin Result := AddBox(TBox); end; procedure TBox.MeasureBox(inBox: TBox); begin inBox.Measure; end; procedure TBox.MeasureBoxes; var i: Integer; begin if Boxes <> nil then for i := 0 to Boxes.Max do MeasureBox(Boxes[i]); end; procedure TBox.Measure; begin MeasureBoxes; if (Node <> nil) and (Node is TBoxNode) then TBoxNode(Node).Measure(Self); end; { TBoxList } function TBoxList.AddBox(inClass: TBoxClass): TBox; begin Result := inClass.Create; Add(Result); end; function TBoxList.AddBox: TBox; begin Result := AddBox(TBox); end; function TBoxList.GetBox(inIndex: Integer): TBox; begin Result := TBox(Items[inIndex]); end; function TBoxList.GetMax: Integer; begin Result := Pred(Count); end; procedure TBoxList.SetBox(inIndex: Integer; const Value: TBox); begin Items[inIndex] := Value; end; end.
unit ZFPBKDF_2; interface {$i STD.INC} {$I ZFVer.Inc} uses SysUtils, ZFKeyDeriv; type TPBKDF2 = class (TObject) private //the number of iterations FIterationNumber : Integer; //salt value for the password-based key derivation function FSaltValue : PByteArray; //the length of the salt value FSaltLength : Integer; //password FPassword : AnsiString; public //Create PBKDF2 object, based on the password, salt of the length SaltSize and the given number of iterations constructor Create(Password : AnsiString; SaltSize : Integer; Iterations : Integer); overload; constructor Create(Password : AnsiString; Salt : PByteArray; SaltLength : Integer; Iterations : Integer); overload; destructor Destroy; override; procedure GetKeyBytes(Cb : Integer; var Key : PByteArray); procedure Initialize(); procedure Reset(); function IterationCount : Integer; function GetSaltValue : PByteArray; end; implementation constructor TPBKDF2.Create(Password : AnsiString; SaltSize : Integer; Iterations : Integer); var Data : PByteArray; i : Integer; begin GetMem(Data, SaltSize); Self.FSaltLength := SaltSize; Randomize; for i := 0 to SaltSize - 1 do Data[i] := Byte(Random(255)); Self.FPassword := Password; Self.FSaltValue := Data; Self.FIterationNumber := Iterations; Self.Initialize(); end; destructor TPBKDF2.Destroy; begin FreeMem(Self.FSaltValue); end; constructor TPBKDF2.Create(Password : AnsiString; Salt : PByteArray; SaltLength : Integer; Iterations : Integer); var i : Integer; begin Self.FPassword := Password; Self.FSaltLength := SaltLength; GetMem(Self.FSaltValue, SaltLength); for i := 0 to SaltLength - 1 do Self.FSaltValue^[i] := Salt^[i]; Self.FIterationNumber := Iterations; Self.Initialize; end; procedure TPBKDF2.GetKeyBytes(Cb : Integer; var Key : PByteArray); var Pass : array [1..32767] of AnsiChar; i : Integer; begin GetMem(Key, Cb); for i := 1 to Length(Self.FPassword) do Pass[i] := Self.FPassword[i]; PBKDF2(@Pass, Length(Self.FPassword), Self.FSaltValue, Self.FSaltLength, Self.FIterationNumber, Key^, Cb); end; procedure TPBKDF2.Initialize(); begin end; procedure TPBKDF2.Reset(); begin end; function TPBKDF2.IterationCount : Integer; begin Result := Self.FIterationNumber; end; function TPBKDF2.GetSaltValue : PByteArray; var Res : PByteArray; i : Integer; begin GetMem(Res, Self.FSaltLength); for i:=0 to Self.FSaltLength-1 do Res[i]:=Self.FSaltValue[i]; Result := Res; end; end.
unit LA.LU; interface uses LA.Globals, LA.Matrix, LA.Vector; type T_LU = record L, U: PMatrix; end; /// <summary> 返回LU分解 </summary> function LU(mtx: TMatrix): T_LU; implementation function LU(mtx: TMatrix): T_LU; var n, i, j: integer; a: array of TVector; L: TMatrix; p: double; tmpL, tmpU: TMatrix; begin n := mtx.Row_num; SetLength(a, n); for i := 0 to n - 1 do a[i] := mtx.Get_Row_vector(i); L := TMatrix.Identity(n); for i := 0 to n - 1 do begin // A[i][i]位置是否可以是主元 if Is_zero(a[i][i]) then begin Result.L := nil; Result.U := nil; Exit; end else begin for j := i + 1 to n - 1 do begin p := a[j][i] / a[i][i]; a[j] := a[j] - p * a[i]; L[j, i] := p; end; end; end; new(Result.L); new(Result.U); tmpL := TMatrix.Zero(n, n); tmpU := TMatrix.Zero(n, n); for i := 0 to n - 1 do begin for j := 0 to n - 1 do begin tmpL[i, j] := L[i, j]; tmpU[i, j] := a[i][j]; end; end; Result.L^ := tmpL; Result.U^ := tmpU; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type TForm1 = class(TForm) RichEdit1: TRichEdit; Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure HTMLSyntax(RichEdit: TRichEdit; TextCol, TagCol, DopCol: TColor); var i, iDop: Integer; s: string; Col: TColor; isTag, isDop: Boolean; begin iDop := 0; isDop := False; isTag := False; Col := TextCol; RichEdit.SetFocus; for i := 0 to Length(RichEdit.Text) do begin RichEdit.SelStart := i; RichEdit.SelLength := 1; s := RichEdit.SelText; if (s = '<') or (s = '{') then isTag := True; if isTag then if (s = '"') then if not isDop then begin iDop := 1; isDop := True; end else isDop := False; if isTag then if isDop then begin if iDop <> 1 then Col := DopCol; end else Col := TagCol else Col := TextCol; RichEdit.SelAttributes.Color := Col; iDop := 0; if (s = '>') or (s = '}') then isTag := False; end; RichEdit.SelLength := 0; end; procedure TForm1.Button1Click(Sender: TObject); begin RichEdit1.Lines.BeginUpdate; HTMLSyntax(RichEdit1, clBlue, clRed, clGreen); RichEdit1.Lines.EndUpdate; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmCheckBox Purpose : Simple Replacement for the MSCheckbox to allow for centering the Box. Date : 05-08-2001 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmCheckbox; interface {$I CompilerDefines.INC} uses Windows, Messages, Classes, Controls, Forms, Graphics; type TCBXAlignment = (cbxLeft, cbxRight, cbxCentered); TrmCustomCheckBox = class(TCustomControl) private FChecked: Boolean; FMouseDown : boolean; fKeyDown : boolean; fMouseInControl : boolean; fCBXAlignment: TCBXAlignment; fFlat: Boolean; fShowFocusRect: Boolean; fWantTabs: boolean; fWantArrows: boolean; procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure CMFocusChanged(var MSG:TMessage); message CM_FOCUSCHANGED; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure WMEraseBkgnd(var message: TMessage); message WM_ERASEBKGND; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure SetChecked(Value: Boolean); procedure SetCBXAlignment(const Value: TCBXAlignment); function CaptionRect:TRect; function CBXRect:TRect; procedure SetFlat(const Value: Boolean); procedure SetShowFocusRect(const Value: Boolean); protected procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure PaintCheck(Rect:TRect); virtual; procedure Paint; override; procedure Click; override; property Checked: Boolean read FChecked write SetChecked default False; property CBXAlignment : TCBXAlignment read fCBXAlignment write SetCBXAlignment default cbxLeft; property Flat: Boolean read fFlat write SetFlat default false; property ShowFocusRect : boolean read fShowFocusRect write SetShowFocusRect default true; property IsMouseDown:Boolean read fMouseDown; property IsMouseInControl:boolean read fMouseInControl; property IsKeyDown:boolean read fKeyDown; property WantTabs:boolean read fWantTabs write fWantTabs default false; property WantArrows:boolean read fWantArrows write fWantArrows default false; public constructor Create(AOwner: TComponent); override; end; TrmCheckBox = class(TrmCustomCheckBox) published property Action; property Anchors; property BiDiMode; property Constraints; property CBXAlignment; property Checked; property Caption; property Enabled; property Font; property Flat; property ParentColor; property ParentFont; property ParentShowHint; property ParentBiDiMode; property PopupMenu; property ShowFocusRect; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; end; implementation uses imglist, Actnlist, rmLibrary; { TrmCustomCheckBox } constructor TrmCustomCheckBox.Create(AOwner: TComponent); begin inherited Create(AOwner); SetBounds(0, 0, 90, 17); ControlStyle := [csClickEvents, csCaptureMouse, csDoubleClicks, csSetCaption]; ParentFont := True; Color := clBtnFace; fCBXAlignment := cbxLeft; fMouseInControl := false; FChecked := false; fFlat := false; fShowFocusRect := true; FKeyDown := false; FMouseDown := false; fWantTabs := false; fWantArrows := false; TabStop := true; end; procedure TrmCustomCheckBox.Paint; var wRect : TRect; wFlags : integer; begin Canvas.brush.color := color; Canvas.Font := font; Canvas.FillRect(clientrect); wFlags := dt_VCenter or DT_SingleLine; case fCBXAlignment of cbxLeft: wFlags := wFlags or dt_left; cbxRight: wFlags := wFlags or dt_right; cbxCentered: wFlags := wFlags or DT_CENTER; end; PaintCheck(CBXRect); if fCBXAlignment <> cbxCentered then begin wRect := CaptionRect; DrawText(Canvas.Handle, PChar(Caption), length(caption), wRect, wFlags); if Focused and fShowFocusRect then begin inflaterect(wRect, 2, 2); Canvas.DrawFocusRect(wRect); end; end else begin if Focused and fShowFocusRect then begin wRect := CBXRect; InflateRect(wRect, 2, 2); Canvas.DrawFocusRect(wRect); end; end; end; procedure TrmCustomCheckBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var wRect : TRect; begin Inherited; if canfocus then SetFocus; UnionRect(wRect, CaptionRect, CBXRect); if (Button = mbLeft) and Enabled and ptinrect(wRect, point(x,y)) then begin FMouseDown := true; invalidate; end; end; procedure TrmCustomCheckBox.SetChecked(Value: Boolean); begin if Value <> FChecked then begin FChecked := Value; Invalidate; end; end; procedure TrmCustomCheckBox.CMDialogChar(var Message: TCMDialogChar); begin with Message do if IsAccel(CharCode, Caption) and Enabled and Visible and (Parent <> nil) and Parent.Showing then begin Click; Result := 1; end else inherited; end; procedure TrmCustomCheckBox.CMFontChanged(var Message: TMessage); begin Invalidate; end; procedure TrmCustomCheckBox.CMTextChanged(var Message: TMessage); begin Invalidate; end; procedure TrmCustomCheckBox.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin inherited ActionChange(Sender, CheckDefaults); if Sender is TCustomAction then with TCustomAction(Sender) do begin Invalidate; end; end; procedure TrmCustomCheckBox.PaintCheck(Rect:TRect); var wFlags : integer; begin wFlags := DFCS_BUTTONCHECK; if FFlat then wFlags := wFlags or DFCS_FLAT; if FChecked then wFlags := wFlags or DFCS_CHECKED; if (not Enabled) then wFlags := wFlags or DFCS_INACTIVE; if (fMouseInControl and FMouseDown) or (fKeyDown) then wFlags := wFlags or DFCS_PUSHED; DrawFrameControl(canvas.handle, Rect, DFC_BUTTON, wFlags); end; procedure TrmCustomCheckBox.SetCBXAlignment(const Value: TCBXAlignment); begin if fCBXAlignment <> Value then begin fCBXAlignment := Value; invalidate; end; end; procedure TrmCustomCheckBox.cmFocusChanged(var MSG: TMessage); begin inherited; fKeyDown := false; FMouseDown := False; invalidate; end; procedure TrmCustomCheckBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var wMD: boolean; wRect : TRect; begin inherited; UnionRect(wRect, CaptionRect, CBXRect); wMD := fMouseDown; fMouseDown := false; if wMD and enabled and (ptinrect(wRect, point(x,y))) then begin FChecked := not fChecked; Invalidate; Click; end; end; procedure TrmCustomCheckBox.MouseMove(Shift: TShiftState; X, Y: Integer); var fLastCheck : boolean; begin inherited; fLastCheck := fMouseInControl; fMouseInControl := PTInRect(ClientRect, point(x,y)); if fLastCheck <> fMouseInControl then Invalidate; end; procedure TrmCustomCheckBox.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; if (key = vk_space) and (Shift = []) then begin fKeyDown := true; invalidate; end; end; procedure TrmCustomCheckBox.KeyUp(var Key: Word; Shift: TShiftState); var wKD: boolean; begin inherited; wKD := fKeyDown; fKeyDown := false; if wKD and (key = vk_space) then begin FChecked := not fChecked; Invalidate; click; end; end; procedure TrmCustomCheckBox.WMLButtonUp(var Message: TWMLButtonUp); var wClicked : boolean; begin wClicked := csClicked in ControlState; if wClicked then ControlState := ControlState - [csClicked]; Inherited; if wClicked then ControlState := ControlState + [csClicked]; end; procedure TrmCustomCheckBox.Click; begin inherited; Invalidate; end; function TrmCustomCheckBox.CaptionRect: TRect; begin case fCBXAlignment of cbxLeft: begin result := rect(0, 0, Canvas.textwidth(Caption), Canvas.Textheight(caption)); offsetRect(result, RectWidth(CBXRect)+7, (height div 2) - (RectHeight(result) div 2)); end; cbxRight: begin result := rect(width-Canvas.textwidth(Caption), 0, width, Canvas.Textheight(caption)); offsetRect(result, -(RectWidth(CBXRect)+7), (height div 2) - (RectHeight(result) div 2)); end; cbxCentered: result := CBXRect; end; end; function TrmCustomCheckBox.CBXRect: TRect; begin result := Rect(0, 0, 13, 13); case fCBXAlignment of cbxLeft: offsetRect(result, 3, (height div 2) - (RectHeight(result) div 2)); cbxRight: offsetRect(result, width - (RectWidth(result)+3), (height div 2) - (RectHeight(result) div 2)); cbxCentered: offsetRect(result, (width div 2) - (rectWidth(result) div 2), (height div 2) - (RectHeight(result) div 2)); end; end; procedure TrmCustomCheckBox.CMMouseLeave(var Message: TMessage); begin inherited; invalidate; end; procedure TrmCustomCheckBox.SetFlat(const Value: Boolean); begin fFlat := Value; invalidate; end; procedure TrmCustomCheckBox.SetShowFocusRect(const Value: Boolean); begin fShowFocusRect := Value; invalidate; end; procedure TrmCustomCheckBox.WMEraseBkgnd(var message: TMessage); begin message.result := 0; end; procedure TrmCustomCheckBox.WMGetDlgCode(var Message: TWMGetDlgCode); begin inherited; if fWantTabs then Message.Result := Message.Result or DLGC_WANTTAB; if fWantArrows then Message.Result := Message.Result or DLGC_WANTARROWS; end; end.
unit TpColorProperty; interface uses TypInfo, SysUtils, Classes, Controls, Graphics, Dialogs, dcedit, dcfdes, dcsystem, dcdsgnstuff; type TTpColorProperty = class(TPropertyEditor) function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure SetValue(const Value: string); override; procedure Edit; override; end; procedure RegisterColorPropertyEditor; implementation procedure RegisterColorPropertyEditor; begin RegisterEditClass(TypeInfo(TColor), nil, '', TDCSimpleEdit); RegisterPropertyEditor(TypeInfo(TColor), nil, '', TTpColorProperty); end; { TTpColorProperty } function TTpColorProperty.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes + [ paDialog ]; end; function TTpColorProperty.GetValue: string; var c: TColor; begin c := GetOrdValue; if not ColorToIdent(c, Result) then Result := IntToHex(c, 6); end; procedure TTpColorProperty.SetValue(const Value: string); var c: Integer; begin if not IdentToColor(Value, c) then c := StrToIntDef('$' + Value, 0); SetOrdValue(c); end; procedure TTpColorProperty.Edit; begin with TColorDialog.Create(nil) do try Color := GetOrdValue; if Execute then SetOrdValue(Color); finally Free; end; end; end.
unit uNumericFunctions; interface uses Sysutils, Math, Windows, uSystemTypes, Dialogs; // Antonio M F Souza, December 04, 2012 function prepareStrToFloat(value: Extended): String; // Antonio M F Souza November 25, 2012 function getDisplayFormat(pDecimalPlaces: Integer): String; function CountDecimalPlaces(value: Extended): Integer; function ValidateFloat(cKey: Char): Char; function ValidateCurrency(cKey: Char): Char; function MyStrToFloat(strValue: String): Extended; function MyStrToCurrency(strValue: String): Currency; function MyStrToInt(strValue: String): Integer; function MyFloatToStr(Value: Double; ADecimalFormat: String = '0.00' ): String; function HasOperator(strValue: String): Boolean; function MyRound(Valor: Double; DecimalPlaces: Integer): Double; function TruncMoney(Valor: Double; DecimalPlaces: Integer): Double; function forceRoundInThirdPosition(value: extended; decimal_places: Integer = 2): extended; function TruncCurrency(AValue: Currency; Decimal: Integer; ARoundMode: TFPURoundingMode = rmDown): Currency; function TruncDecimal(Valor: Real; Decimal: integer): Double; function AsloToFloat(Aslo: String): Double; procedure IncFloat(var IncDef : Double; Value : Double); function RetiraSepadorMilhar(StrValue: String): String; function MyFormatCur(Value: Double; Decimal: Char):String; function MyStrToMoney(strValue: String): Currency; function MyStrToDouble(strValue: String): Double;overload; function MyStrToDouble(strValue : String; DS: Char) : Double;overload; function MyFormatTax(Value:Double;Decimal:Char):String; function MyFormatDouble(Value:Double; Decimal:Char):String; function IsNegative(fValue:Double):Boolean; function HasDecimal(fValue : Double) : Boolean; // Funcao que calcula a combinacao de moedas para o Caixa procedure CountToDesired(var aCaixa : TCaixa; TotCash, ValDesired : Double); function IsValidInteger(S: String): Boolean; // 12-07-2006 Max: new functions function SysStrToCurr(Value: String): Currency; function SysCurrToStr(Value: Currency): String; overload; function SysCurrToStr(Value: Currency; Decimal: Char): String; overload; function ValorExtenso(valor: real): string; //Antonio M F Souza, December 14 2012: forceRound to 2 decimal places only function forceRoundTwoDecimals(value: extended): extended; // Antonio M F Souza, December 19 2012: round like database. function roundLikeDatabase(pValue: extended; pDecimals: integer): extended; implementation uses xBase, uDm; // Antonio M F Souza, December 19 2012: Round like database. function roundLikeDatabase(pValue: extended; pDecimals: integer): extended; var factor, fraction: extended; begin factor := IntPower(10, pDecimals); pValue := strToFloat(floatToStr(pValue * factor)); result := int(pValue); fraction := frac(pValue); if ( fraction >= 0.5 ) then begin result := result + 1; end else if ( fraction <= -0.5 ) then begin result := result - 1 end; result := result / factor; end; //Antonio M F Souza, December 14 2012: forceRound to 2 decimal places only function forceRoundTwoDecimals(value: extended): extended; var tempValue: extended; fracValue: extended; valueStr: String; begin valueStr := prepareStrToFloat(value); tempValue := strToFloat(valueStr); tempValue := ( value * 10 ); fracValue := frac(tempValue); if ( fracValue >= 0.5 ) then begin tempValue := tempValue * 10; tempValue := trunc(tempValue); tempValue := tempValue / 10; end else begin tempValue := tempValue * 10; tempValue := trunc(tempValue); tempValue := ( tempValue / 100 ); end; result := tempValue; end; function prepareStrToFloat(value: Extended): String; var valueStr: String; commaPosition: Integer; begin valueStr := formatFloat('#,##0.00', value); commaPosition := pos(',', valueStr); if ( commaPosition > 0 ) then delete(valueStr, commaPosition, 1); result := valueStr; end; function getDisplayFormat(pDecimalPlaces: Integer): String; begin case pDecimalPlaces of 2: result := '0.00'; 3: result := '0.000'; 4: result := '0.0000'; else result := '0.00'; // = 2 end; end; function CountDecimalPlaces(value: Extended): Integer; var valueStr: String; decimalPosition: Integer; begin result := 2; valueStr := getDisplayFormat(dm.FQtyDecimal); decimalPosition := pos('.', valueStr); if ( decimalPosition > 0 ) then result := length(copy(valueStr, decimalPosition + 1, dm.FQtyDecimal )); end; function ValorExtenso(valor: real): string; var Texto, Milhar, Centena, Centavos, msg: string; Const Unidades: array[1..9] of string = ('Um', 'Dois', 'Tres', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove'); Dez: array[1..9] of string = ('Onze', 'Doze', 'Treze', 'Quatorze', 'Quinze', 'Dezesseis', 'Dezessete', 'Dezoito', 'Dezenove'); Dezenas: array[1..9] of string = ('Dez', 'Vinte', 'Trinta', 'Quarenta', 'Cinquenta', 'Sessenta', 'Setenta', 'Oitenta', 'Noventa'); Centenas: array[1..9] of string = ('Cento', 'Duzentos', 'Trezentos', 'Quatrocentos', 'Quinhentos', 'Seiscentos', 'Setecentos', 'Oitocentos', 'Novecentos'); MoedaSigular = 'Real'; MoedaPlural = 'Reais'; CentSingular = 'Centavo'; CentPlural = 'Centavos'; Zero = 'Zero'; ////////////////////////////////fucao auxiliar extenso//////////////////////////////// function ifs(Expressao: Boolean; CasoVerdadeiro, CasoFalso: String): String; begin if Expressao then Result:=CasoVerdadeiro else Result:=CasoFalso; end; ////////////////////////////funcao auxiliar extenso///////////////////////// function MiniExtenso (trio: string): string; var Unidade, Dezena, Centena: string; begin Unidade:=''; Dezena:=''; Centena:=''; if (trio[2]='1') and (trio[3]<>'0') then begin Unidade:=Dez[strtoint(trio[3])]; Dezena:=''; end else begin if trio[2]<>'0' then Dezena:=Dezenas[strtoint(trio[2])]; if trio[3]<>'0' then Unidade:=Unidades[strtoint(trio[3])]; end; if (trio[1]='1') and (Unidade='') and (Dezena='') then Centena:='Cem' else if trio[1]<>'0' then Centena:=Centenas[strtoint(trio[1])] else Centena:=''; Result:= Centena + ifs((Centena<>'') and ((Dezena<>'') or (Unidade<>'')), ' e ', '') + Dezena + ifs((Dezena<>'') and (Unidade<>''),' e ', '') + Unidade; end; begin if (valor>999999.99) or (valor<0) then begin msg := 'O valor está fora do intervalo permitido.'; msg := msg+'O número deve ser maior ou igual a zero e menor que 999.999,99.'; msg := msg+' Se não for corrigido o número não será escrito por extenso.'; Result := ''; exit; end; if valor = 0 then begin Result := ''; Exit; end; Texto := formatfloat('000000.00',valor); Milhar := MiniExtenso(Copy(Texto,1,3)); Centena := MiniExtenso(Copy(Texto,4,3)); Centavos := MiniExtenso('0'+Copy(Texto,8,2)); Result := Milhar; if Milhar <> '' then begin if copy(texto,4,3)='000' then Result := Result+' Mil Reais' else Result := Result+' Mil, '; end; if (((copy(texto,4,2) = '00') and (Milhar <> '') and (copy(texto,6,1) <> '0'))) or (centavos = '00') and (milhar <> '') then Result := Result + ' e '; if (Milhar + Centena <> '') then Result := Result + Centena; if (Milhar = '') and (copy(texto,4,3) = '001') then Result:=Result+' Real' else if (copy(texto,4,3) <> '000') then Result:=Result+' Reais'; if Centavos = '' then begin Result := Result + '.'; Exit; end else begin if (Milhar + Centena = '') then Result := Centavos else Result := Result + ', e ' + Centavos; end; if (copy(texto,8,2) = '01') and (Centavos <> '') then Result := Result + ' Centavo.' else Result := Result + ' Centavos.'; end; function IsNegative(fValue:Double):Boolean; begin Result := (fValue>=0); end; function MyFormatCur(Value:Double;Decimal:Char):String; var OldDecimalSeparator: Char; begin OldDecimalSeparator := DecimalSeparator; DecimalSeparator := Decimal; Result := FormatCurr('0.00',Value); DecimalSeparator := OldDecimalSeparator; end; function MyFormatTax(Value:Double;Decimal:Char):String; var OldDecimalSeparator: Char; begin OldDecimalSeparator := DecimalSeparator; DecimalSeparator := Decimal; Result := FormatCurr('0.0000',Value); DecimalSeparator := OldDecimalSeparator; end; function MyStrToDouble(strValue : String) : Double; var OldDecimalSeparator: Char; begin if Trim(strValue) = '' then begin Result := 0; Exit; end; OldDecimalSeparator := DecimalSeparator; try DecimalSeparator := '.'; if OldDecimalSeparator = ',' then begin strValue := StringReplace(strValue,'.','',[rfReplaceAll ]); strValue := StringReplace(strValue,',','.',[rfReplaceAll ]); end else strValue := StringReplace(strValue,',','',[rfReplaceAll ]); try Result := StrToFloat(strValue); except Result := 0; end; finally DecimalSeparator := OldDecimalSeparator; end; end; function MyStrToMoney(strValue:String) : Currency; var OldDecimalSeparator: Char; begin if Trim(strValue) = '' then begin Result := 0; Exit; end; OldDecimalSeparator := DecimalSeparator; try DecimalSeparator := '.'; if OldDecimalSeparator = ',' then begin strValue := StringReplace(strValue,'.','',[rfReplaceAll ]); strValue := StringReplace(strValue,',','.',[rfReplaceAll ]); end else strValue := StringReplace(strValue,',','',[rfReplaceAll ]); try Result := StrToCurr(strValue); except Result := 0; end; finally DecimalSeparator := OldDecimalSeparator; end; end; function ValidateFloat(cKey:Char):Char; begin if not (cKey IN ['0'..'9','-','.',#8]) then begin Result:=#0; MessageBeep($FFFFFFFF); end else Result:=cKey; end; function ValidateCurrency(cKey:Char):Char; begin if not (cKey IN ['0'..'9','-','.',',',#8]) then begin Result := #0; MessageBeep($FFFFFFFF); end else Result:=cKey; end; function MyStrToCurrency( strValue : String) : Currency; begin if Trim(strValue) = '' then begin Result := 0; Exit; end; try Result := StrToCurr(strValue); except Result := 0; end; end; function MyStrToFloat(strValue : String) : Extended; begin if Trim(strValue) = '' then begin Result := 0; Exit; end; try Result := StrToFloat(strValue); except Result := 0; end; end; function MyStrToInt(strValue : String) : Integer; begin if Trim(strValue) = '' then begin Result := 0; Exit; end; try Result := StrToInt(strValue); except Result := 0; end; end; function MyFloatToStr(Value: Double; ADecimalFormat: String = '0.00' ): String; begin Result := FormatFloat(ADecimalFormat, Value); end; function HasOperator(strValue : String) : Boolean; begin Result := ( Pos('>', strValue) > 0 ) or ( Pos('<', strValue) > 0 ) or ( Pos('=', strValue) > 0 ); end; function MyRound(Valor : Double; DecimalPlaces : Integer) : Double; var SubValue : Double; begin SubValue := Power(10, DecimalPlaces); Result := (Round(Valor * SubValue))/SubValue; end; function HasDecimal(fValue : Double) : Boolean; var sValue : String; iPos : Integer; begin sValue := FormatFloat('###0.0000',fValue); iPos := Pos(DecimalSeparator, sValue); if iPos > 0 then Result := (StrToInt(Copy(sValue, iPos + 1, Length(sValue))) > 0) else Result := False; end; function TruncMoney(Valor: Double; DecimalPlaces: Integer): Double; var SubValue : Double; begin Result := 0; if Valor = 0 then Exit; SubValue := Power(10, DecimalPlaces); if HasDecimal(Valor * SubValue) then Result := (Trunc(Valor * SubValue))/SubValue else Result := (Valor * SubValue)/SubValue; end; function TruncDecimal(Valor: Real; Decimal: integer): Double; var aux: string; bNeg : Boolean; begin bNeg := False; if Valor < 0 then bNeg := True; valor := Abs(valor); valor := valor * 100000; aux := FormatFloat('00000000000000000000',valor); aux := copy( aux, 1, 15) + copy( aux, 16, Decimal); case Decimal of 2: valor := strToFloat(aux) / 100; 3: valor := strToFloat(aux) / 1000; 4: valor := strToFloat(aux) / 10000; 5: valor := strToFloat(aux) / 100000; end; if bNeg then valor := valor * -1; result := Valor; end; function TruncCurrency(AValue: Currency; Decimal: Integer; ARoundMode: TFPURoundingMode = rmDown): Currency; var OldRoundMode: TFPURoundingMode; begin OldRoundMode := GetRoundMode; try SetRoundMode(ARoundMode); Result := RoundTo(AValue, Decimal); finally SetRoundMode(OldRoundMode); end; end; function AsloToFloat(Aslo: String): Double; var F, Str: String; P: Integer; First: Boolean; begin // A S L O B E R U T I // 1 2 3 4 5 6 7 8 9 0 // Esta função deverá ser muito foda mesmo. // Deverá adivinhar se o sepador de decimal e o ponto ou a virgual. // Tudo por causa do MEDIDATA irgh !!!! // Se tiver um só separador, ele é o decimal // Se existirem vários então o decimal é o ultimo Str := Trim(Aslo); P := Length(Str); First := True; while P > 0 do begin case Str[P] of '/': Break; 'A': F := '1' + F; 'S': F := '2' + F; 'L': F := '3' + F; 'O': F := '4' + F; 'B': F := '5' + F; 'E': F := '6' + F; 'R': F := '7' + F; 'U': F := '8' + F; 'T': F := '9' + F; 'I': F := '0' + F; ',', '.': begin if First then begin F := '.' + F; First := False; end; end; end; P := P - 1; end; Result := MyStrToFloat(F); end; procedure IncFloat(var IncDef : Double; Value : Double); begin IncDef := IncDef + Value; end; function RetiraSepadorMilhar(StrValue: String): String; var VPos, PPos: Integer; RealValue: String; begin VPos := POS(',', StrValue); PPos := POS('.', StrValue); if (VPos <> 0) AND (PPos <> 0) then begin // tenho separador de milhar e decimal // O ultimo é o decimal if VPos > PPos then begin // Tenho que retirar o ponto RealValue := LeftStr(StrValue, PPos-1) + RightStr(StrValue, Length(StrValue) - PPos); end else begin // Tenho que retirar a virgula RealValue := LeftStr(StrValue, VPos-1) + RightStr(StrValue, Length(StrValue) - VPos); end; end else RealValue := StrValue; Result := RealValue; end; procedure CountToDesired(var aCaixa : TCaixa; TotCash, ValDesired : Double); var i, DivNota, OldCaixa : integer; SubTot, SubValor, TotRestante : Double; MyNota : Double; begin // Alimenta os totais de notas para chegar no valor mais proximo do Desired SubTot := 0; // Percorre os totais vendo se a parte menor ainda e maior que ValDesired for i := 0 to High(aCaixa) do begin SubValor := aCaixa[i]*aCaixaPotencia[i]; TotRestante := TotCash - SubTot - SubValor; OldCaixa := aCaixa[i]; if TotRestante > ValDesired then begin // Total de notas restantes ainda e maior que o contado, nao pega nada aCaixa[i] := 0; end else begin // Total de notas restantes nao e maior que o contado, pega o minimo possivel DivNota := Trunc((ValDesired - TotRestante)/aCaixaPotencia[i]); MyNota := DivNota; // Teste de divisao sem erro if Abs(MyNota - ((ValDesired - TotRestante)/aCaixaPotencia[i])) < 0.001 then aCaixa[i] := Abs(DivNota) else if (DivNota+1) < aCaixa[i] then aCaixa[i] := Abs(DivNota+1); end; SubTot := SubTot + (OldCaixa-aCaixa[i])*aCaixaPotencia[i]; end; end; function IsValidInteger(S: String): Boolean; begin try StrToInt(S); Result := True; except Result := False; end; end; function MyFormatDouble(Value:Double; Decimal:Char):String; var OldDecimalSeparator: Char; begin OldDecimalSeparator := DecimalSeparator; DecimalSeparator := Decimal; Result := FormatCurr('0.#####',Value); DecimalSeparator := OldDecimalSeparator; end; function MyStrToDouble(strValue : String; DS: Char) : Double; var OldDecimalSeparator: Char; begin if Trim(strValue) = '' then begin Result := 0; Exit; end; OldDecimalSeparator := DecimalSeparator; try DecimalSeparator := DS; try Result := MyStrToDouble(strValue); except Result := 0; end; finally DecimalSeparator := OldDecimalSeparator; end; end; function SysStrToCurr(Value: String): Currency; var FFormat: TFormatSettings; begin FFormat.DecimalSeparator := '.'; Result := StrToFloat(Value, FFormat); end; function SysCurrToStr(Value: Currency): String; begin Result := SysCurrToStr(Value, '.'); end; function SysCurrToStr(Value: Currency; Decimal: Char): String; var FFormat: TFormatSettings; begin FFormat.DecimalSeparator := Decimal; Result := FormatCurr('0.00', Value); end; function forceRoundInThirdPosition(value: extended; decimal_places: Integer): extended; var valueRounded: extended; addDecimal: extended; begin // notes: decimal places doesn't use any more // Antonio M F Souza 14, November 2012 valueRounded := 0; if ( value <> 0 ) then valueRounded := (value * 100 + ifThen(value > 0, 0.5, -0.5))/100; // Antonio M F Souza November 11, 2012: function above is explained below. { if ( value > 0 ) then addDecimal := 0.5 else addDecimal := -0.5; valueRounded := trunc((value * 100) + addDecimal)/100; } result := valueRounded; end; end.
unit Dmitry.Utils.SystemImageLists; // Version 1.1.17 // 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 expressed or // implied. See the License for the specific language governing rights // and limitations under the License. // // // 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 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 either the // MPL or the GPL. // // The initial developer of this code is Jim Kueneman <jimdk@mindspring.com> // //---------------------------------------------------------------------------- interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Menus, Registry, ShlObj, ShellAPI, ActiveX, ImgList, CommCtrl; const SID_IImageList = '{46EB5926-582E-4017-9FDF-E8998DAA0950}'; IID_IImageList: TGUID = SID_IImageList; type IImageList = interface(IUnknown) [SID_IImageList] function Add(Image, Mask: HBITMAP; var Index: Integer): HRESULT; stdcall; function ReplaceIcon(IndexToReplace: Integer; Icon: HICON; var Index: Integer): HRESULT; stdcall; function SetOverlayImage(iImage: Integer; iOverlay: Integer): HRESULT; stdcall; function Replace(Index: Integer; Image, Mask: HBITMAP): HRESULT; stdcall; function AddMasked(Image: HBITMAP; MaskColor: COLORREF; var Index: Integer): HRESULT; stdcall; function Draw(var DrawParams: TImageListDrawParams): HRESULT; stdcall; function Remove(Index: Integer): HRESULT; stdcall; function GetIcon(Index: Integer; Flags: UINT; var Icon: HICON): HRESULT; stdcall; function GetImageInfo(Index: Integer; var ImageInfo: TImageInfo): HRESULT; stdcall; function Copy(iDest: Integer; SourceList: IUnknown; iSource: Integer; Flags: UINT): HRESULT; stdcall; function Merge(i1: Integer; List2: IUnknown; i2, dx, dy: Integer; ID: TGUID; out ppvOut): HRESULT; stdcall; function Clone(ID: TGUID; out ppvOut): HRESULT; stdcall; function GetImageRect(Index: Integer; var rc: TRect): HRESULT; stdcall; function GetIconSize(var cx, cy: Integer): HRESULT; stdcall; function SetIconSize(cx, cy: Integer): HRESULT; stdcall; function GetImageCount(var Count: Integer): HRESULT; stdcall; function SetImageCount(NewCount: UINT): HRESULT; stdcall; function SetBkColor(BkColor: COLORREF; var OldColor: COLORREF): HRESULT; stdcall; function GetBkColor(var BkColor: COLORREF): HRESULT; stdcall; function BeginDrag(iTrack, dxHotSpot, dyHotSpot: Integer): HRESULT; stdcall; function EndDrag: HRESULT; stdcall; function DragEnter(hWndLock: HWND; x, y: Integer): HRESULT; stdcall; function DragLieave(hWndLock: HWND): HRESULT; stdcall; function DragMove(x, y: Integer): HRESULT; stdcall; function SetDragCursorImage(Image: IUnknown; iDrag, dxHotSpot, dyHotSpot: Integer): HRESULT; stdcall; function DragShowNoLock(fShow: BOOL): HRESULT; stdcall; function GetDragImage(var CurrentPos, HotSpot: TPoint; ID: TGUID; out ppvOut): HRESULT; stdcall; function GetImageFlags(i: Integer; dwFlags: DWORD): HRESULT; stdcall; function GetOverlayImage(iOverlay: Integer; var iIndex: Integer): HRESULT; stdcall; end; const {$EXTERNALSYM SHIL_LARGE} SHIL_LARGE = 0; // normally 32x32 {$EXTERNALSYM SHIL_SMALL} SHIL_SMALL = 1; // normally 16x16 {$EXTERNALSYM SHIL_EXTRALARGE} SHIL_EXTRALARGE = 2; // normall 48x48 {$EXTERNALSYM SHIL_SYSSMALL} SHIL_SYSSMALL = 3; // like SHIL_SMALL, but tracks system small icon metric correctly {$EXTERNALSYM SHIL_LAST} SHIL_LAST = SHIL_SYSSMALL; type TSHGetImageList = function(iImageList: Integer; const RefID: TGUID; out ImageList): HRESULT; stdcall; type TSysImageListSize = ( sisSmall, // Large System Images sisLarge, // Small System Images sisExtraLarge // Extra Large Images (48x48) ); type VirtualSysImages = class(TImageList) private FImageSize: TSysImageListSize; FJumboImages: IImageList; procedure SetImageSize(const Value: TSysImageListSize); protected procedure RecreateHandle; procedure Flush; property JumboImages: IImageList read FJumboImages; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property ImageSize: TSysImageListSize read FImageSize write SetImageSize; end; function ExtraLargeSysImages: VirtualSysImages; function LargeSysImages: VirtualSysImages; function SmallSysImages: VirtualSysImages; procedure FlushImageLists; implementation var FExtraLargeSysImages: VirtualSysImages = nil; FLargeSysImages: VirtualSysImages = nil; FSmallSysImages: VirtualSysImages = nil; ShellDLL: HMODULE = 0; procedure FlushImageLists; begin if Assigned(FSmallSysImages) then FSmallSysImages.Flush; if Assigned(FLargeSysImages) then FLargeSysImages.Flush; if Assigned(FExtraLargeSysImages) then FExtraLargeSysImages.Flush end; function ExtraLargeSysImages: VirtualSysImages; begin if not Assigned(FExtraLargeSysImages) then begin FExtraLargeSysImages := VirtualSysImages.Create(nil); FExtraLargeSysImages.ImageSize := sisExtraLarge; end; Result := FExtraLargeSysImages end; function LargeSysImages: VirtualSysImages; begin if not Assigned(FLargeSysImages) then begin FLargeSysImages := VirtualSysImages.Create(nil); FLargeSysImages.ImageSize := sisLarge; end; Result := FLargeSysImages end; function SmallSysImages: VirtualSysImages; begin if not Assigned(FSmallSysImages) then begin FSmallSysImages := VirtualSysImages.Create(nil); FSmallSysImages.ImageSize := sisSmall; end; Result := FSmallSysImages end; function SHGetImageList(iImageList: Integer; const RefID: TGUID; out ppvOut): HRESULT; // Retrieves the system ImageList interface var ImageList: TSHGetImageList; begin Result := E_NOTIMPL; if (Win32Platform = VER_PLATFORM_WIN32_NT) then begin ShellDLL := LoadLibrary(Shell32); if ShellDLL <> 0 then begin ImageList := GetProcAddress(ShellDLL, PChar(727)); if (Assigned(ImageList)) then Result := ImageList(iImageList, RefID, ppvOut); end end; end; { VirtualSysImages } constructor VirtualSysImages.Create(AOwner: TComponent); begin inherited; ShareImages := True; ImageSize := sisSmall; DrawingStyle := dsTransparent end; destructor VirtualSysImages.Destroy; begin inherited; end; procedure VirtualSysImages.Flush; begin RecreateHandle end; procedure VirtualSysImages.RecreateHandle; var PIDL: PItemIDList; Malloc: IMalloc; FileInfo: TSHFileInfo; Flags: Longword; begin Handle := 0; if FImageSize = sisExtraLarge then begin if Succeeded(SHGetImageList(SHIL_EXTRALARGE, IImageList, FJumboImages)) then Handle := THandle(FJumboImages) else begin Flags := SHGFI_PIDL or SHGFI_SYSICONINDEX or SHGFI_LARGEICON or SHGFI_ADDOVERLAYS; SHGetSpecialFolderLocation(0, CSIDL_DESKTOP, PIDL); SHGetMalloc(Malloc); Handle := SHGetFileInfo(PChar(PIDL), 0, FileInfo, SizeOf(FileInfo), Flags); Malloc.Free(PIDL); end end else begin SHGetSpecialFolderLocation(0, CSIDL_DESKTOP, PIDL); SHGetMalloc(Malloc); if FImageSize = sisSmall then Flags := SHGFI_PIDL or SHGFI_SYSICONINDEX or SHGFI_SMALLICON or SHGFI_ADDOVERLAYS else Flags := SHGFI_PIDL or SHGFI_SYSICONINDEX or SHGFI_LARGEICON; Handle := SHGetFileInfo(PChar(PIDL), 0, FileInfo, SizeOf(FileInfo), Flags); Malloc.Free(PIDL); end; end; procedure VirtualSysImages.SetImageSize(const Value: TSysImageListSize); begin FImageSize := Value; RecreateHandle; end; initialization finalization FLargeSysImages.Free; FSmallSysImages.Free; FExtraLargeSysImages.Free; if ShellDLL <> 0 then FreeLibrary(ShellDLL) end.
unit Fornecedor.Controller.Interf; interface uses Fornecedor.Model.Interf, TPAGFORNECEDOR.Entidade.Model; type IFornecedorOperacaoIncluirController = interface; IFornecedorOperacaoAlterarController = interface; IFornecedorOperacaoExcluirController = interface; IFornecedorOperacaoDuplicarController = interface; IFornecedorController = interface ['{649EF46B-3B18-4DA2-89D0-492E71BB62C2}'] function incluir: IFornecedorOperacaoIncluirController; function alterar: IFornecedorOperacaoAlterarController; function excluir: IFornecedorOperacaoExcluirController; function duplicar: IFornecedorOperacaoDuplicarController; function localizar(AValue: string): IFornecedorController; function localizarPeloCNPJ(AValue: string): IFornecedorController; function idFornecedor: string; function nomeFantasia: string; function cnpj: string; function ie: string; function telefone: string; function email: string; end; IFornecedorOperacaoIncluirController = interface ['{E18C9411-321B-49DA-8D47-2CEF6E0AB7A8}'] function fornecedorModel(AValue: IFornecedorModel): IFornecedorOperacaoIncluirController; function nomeFantasia(AValue: string): IFornecedorOperacaoIncluirController; function cnpj(AValue: string): IFornecedorOperacaoIncluirController; function ie(AValue: string): IFornecedorOperacaoIncluirController; function telefone(AValue: string): IFornecedorOperacaoIncluirController; function email(AValue: string): IFornecedorOperacaoIncluirController; procedure finalizar; end; IFornecedorOperacaoAlterarController = interface ['{1EA450B1-040F-4C03-B649-FCF836AED043}'] function fornecedorModel(AValue: IFornecedorModel): IFornecedorOperacaoAlterarController; function fornecedorSelecionado(AValue: TTPAGFORNECEDOR): IFornecedorOperacaoAlterarController; function nomeFantasia(AValue: string): IFornecedorOperacaoAlterarController; function cnpj(AValue: string): IFornecedorOperacaoAlterarController; function ie(AValue: string): IFornecedorOperacaoAlterarController; function telefone(AValue: string): IFornecedorOperacaoAlterarController; function email(AValue: string): IFornecedorOperacaoAlterarController; procedure finalizar; end; IFornecedorOperacaoExcluirController = interface ['{D3E23660-D341-4719-B987-7DD1B2652842}'] function fornecedorModel(AValue: IFornecedorModel): IFornecedorOperacaoExcluirController; function fornecedorSelecionado(AValue: TTPAGFORNECEDOR): IFornecedorOperacaoExcluirController; procedure finalizar; end; IFornecedorOperacaoDuplicarController = interface ['{E56F876D-A2EC-4E5A-A31E-086D420EF83A}'] function fornecedorModel(AValue: IFornecedorModel): IFornecedorOperacaoDuplicarController; function nomeFantasia(AValue: string): IFornecedorOperacaoDuplicarController; function cnpj(AValue: string): IFornecedorOperacaoDuplicarController; function ie(AValue: string): IFornecedorOperacaoDuplicarController; function telefone(AValue: string): IFornecedorOperacaoDuplicarController; function email(AValue: string): IFornecedorOperacaoDuplicarController; procedure finalizar; end; implementation end.
unit ConsoleTools; interface uses {$IFDEF MSWINDOWS} windows, {$ENDIF} commandprocessor, stringx, typex, systemx, sysutils, betterobject; type TConsole = class(TBetterObject) private {$IFDEF MSWINDOWS} FHandle: THandle; {$ENDIF} FForeGroundColorNumber: nativeint; FBAckGroundColorNumber: nativeint; procedure SetBackGroundColorNumber(const Value: nativeint); procedure SetForeGroundColorNumber(const Value: nativeint); protected public {$IFDEF MSWINDOWS} property Handle: THandle read FHandle; {$ENDIF} procedure Init;override; procedure SetTextAttribute(iAttr: nativeint); procedure Write(sString: string); property ForeGroundColorNumber: nativeint read FForeGroundColorNumber write SetForeGroundColorNumber; property BackGroundColorNumber: nativeint read FBAckGroundColorNumber write SetBackGroundColorNumber; end; procedure WatchCommandInConsole(c: TCommand); procedure ClearScreen; var con: TConsole; implementation function TextBar(pct: single): string; begin result := '..........'; for var t := 0 to (round((pct*100)/10))-1 do begin result[t+low(result)] := '#'; end; result := '['+result+']'; end; procedure WatchCommandInConsole(c: TCommand); var s: string; iPrevWriteSize: ni; begin iPrevWriteSize := 0; while not c.WaitFor(250) do begin if assigned(c.Thread) then begin c.Lock; try s := zcopy(c.Thread.GetSignalDebug+' '+floatprecision(c.PercentComplete*100,0)+'% '+TextBar(c.PercentComplete)+c.Status,0,70)+CR; Write(stringx.StringRepeat(' ', iPrevWriteSize)+#13); Write(s); iPrevWriteSize := length(s); finally c.unlock; end; end; end; Write(stringx.StringRepeat(' ', iPrevWriteSize)+#13); s := floatprecision(c.PercentComplete*100,0)+'% '+ zcopy(c.Status,0,70)+CR; Write(s); end; procedure TConsole.Init; begin inherited; {$IFDEF MSWINDOWS} Fhandle := GetStdHandle(STD_OUTPUT_HANDLE); {$ENDIF} end; procedure TConsole.SetBackGroundColorNumber(const Value: nativeint); begin {$IFDEF CONSOLE} FBAckGroundColorNumber := Value; {$IFDEF MSWINDOWS} SetConsoleTextAttribute(handle, ((FBAckGroundColorNumber and $f) shl 4) or (FForeGroundColorNumber and $f)); {$ENDIF} {$ENDIF} end; procedure TConsole.SetForeGroundColorNumber(const Value: nativeint); begin {$IFDEF CONSOLE} FForeGroundColorNumber := Value; {$IFDEF MSWINDOWS} SetConsoleTextAttribute(handle, ((FBAckGroundColorNumber and $f) shl 4) or (FForeGroundColorNumber and $f)); {$ENDIF} {$ENDIF} end; procedure TConsole.SetTextAttribute(iAttr: nativeint); begin {$IFDEF CONSOLE} {$IFDEF MSWINDOWS} windows.SetConsoleTextAttribute(handle, iAttr); {$ENDIF} {$ENDIF} end; procedure TConsole.Write(sString: string); begin {$IFDEF CONSOLE} Writeln(sString); {$ENDIF} end; procedure ClearScreen; {$IFNDEF MSWINDOWS} begin end; {$ELSE} var stdout: THandle; csbi: TConsoleScreenBufferInfo; ConsoleSize: DWORD; NumWritten: DWORD; Origin: TCoord; begin stdout := GetStdHandle(STD_OUTPUT_HANDLE); Win32Check(stdout<>INVALID_HANDLE_VALUE); Win32Check(GetConsoleScreenBufferInfo(stdout, csbi)); ConsoleSize := csbi.dwSize.X * csbi.dwSize.Y; Origin.X := 0; Origin.Y := 0; Win32Check(FillConsoleOutputCharacter(stdout, ' ', ConsoleSize, Origin, NumWritten)); Win32Check(FillConsoleOutputAttribute(stdout, csbi.wAttributes, ConsoleSize, Origin, NumWritten)); Win32Check(SetConsoleCursorPosition(stdout, Origin)); end; {$ENDIF} end.
program Draw; uses Crt; type TLoc = object X,Y: Integer; constructor Init(X1,Y1: Integer); procedure Point; virtual; end; TPoint = object(TLoc) C: Integer; constructor Init(X1,Y1,C1: Integer); procedure Point; virtual; procedure Draw; virtual; end; TRectangle = object(TPoint) XX,YY: Integer; constructor Init(X1,Y1,X2,Y2,C1: Integer); procedure Point; virtual; end; constructor TLoc.Init(X1,Y1: Integer); begin X := X1; Y := Y1; end; procedure TLoc.Point; begin GotoXY(X,Y); end; constructor TPoint.Init(X1,Y1,C1: Integer); begin inherited Init(X1,Y1); C := C1; end; procedure TPoint.Point; begin TextAttr := C; Write('*'); end; procedure TPoint.Draw; begin TLoc.Point; Point; end; constructor TRectangle.Init(X1,Y1,X2,Y2,C1: Integer); begin TPoint.Init(X1,Y1,C1); XX := X2; YY := Y2; end; procedure TRectangle.Point; var S: String; begin TextAttr := C; FillChar(S[1], XX-X, '*'); S[0] := Char(XX-X); Write(S); end; var TAsk: TRectangle; begin ClrScr; TAsk.Init(5,5,10,10,$4F); TAsk.Draw; TAsk.Init(10,10,20, 20,$4F); TAsk.Draw; ReadLn; end.
unit uVSLog; interface uses SysUtils,Forms,xmldom, XMLIntf, msxmldom, XMLDoc,uVSConst, uVSSimpleExpress,uVSCombExpress,uLKJRuntimeFile; type TVSXMLLog = class private m_xmlDoc : TXMLDocument; m_bOpenLog : boolean; m_xmlNode : IXMLNode; public {$region '构造、析构'} constructor Create(); destructor Destroy();override; {$endregion '构造、析构'} public procedure AddRule(RuleTtile : string); function CreateCombExpress(VSExp : TVSExpression;var CurNode : Pointer):IXMLNode; procedure AddCombExpress(VSExp : TVSCombExpression;RecHead: RLKJRTFileHeadInfo; RecRow: TLKJRuntimeFileRec); procedure RebackCombExpress(VSExp : TVSCombExpression); procedure AddExpress(VSExp : TVSExpression;RecHead: RLKJRTFileHeadInfo; RecRow: TLKJRuntimeFileRec); property OpenLog : Boolean read m_bOpenLog write m_bOpenLog; end; var VSLog : TVSXMLLog; ErrorHandle : THandle; implementation { TVSXMLLog } function TVSXMLLog.CreateCombExpress(VSExp: TVSExpression;var CurNode : Pointer):IXMLNode; var strTitle : string; begin if not OpenLog then exit; strTitle := '未命名组合表达式'; if (VSExp.Title <> '') then strTitle := VSExp.Title; Result := m_xmlNode; m_xmlNode := m_xmlNode.AddChild(strTitle); CurNode := Pointer(m_xmlNode); end; procedure TVSXMLLog.AddCombExpress(VSExp: TVSCombExpression; RecHead: RLKJRTFileHeadInfo; RecRow: TLKJRuntimeFileRec); begin if not OpenLog then Exit; try m_xmlNode := IXMLNode(VSExp.ParentData); IXMLNode(VSExp.CurData).Attributes['结果'] := VSExp.GetStateText(VSExp.State); if RecRow <> nil then IXMLNode(VSExp.CurData).Attributes['时间'] := FormatDatetime('HHmmss',TLKJCommonRec(RecRow).CommonRec.DTEvent); except //application.MessageBox(PChar(VSExp.Title),'',0); end; end; procedure TVSXMLLog.AddExpress(VSExp: TVSExpression;RecHead: RLKJRTFileHeadInfo; RecRow: TLKJRuntimeFileRec); var xmlnode : IXMLNode; strTitle : string; begin if not OpenLog then exit; try strTitle := '未命名表达式'; if (vsExp.Title <> '') then strTitle := VSExp.Title; {$region 'TVSCompExpression'} if VSExp.ClassName = 'TVSCompExpression' then begin xmlnode := m_xmlNode.AddChild(strTitle); xmlnode.Attributes['结果'] := TVSExpression.GetStateText(VSExp.State); xmlnode.Attributes['实际值'] := VSExp.GetRecValue(TVSCompExpression(VSExp).Key,RecHead,RecRow); exit; end; {$endregion 'TVSCompExpression'} {$region 'TVSCompExpExpression'} if VSExp.ClassName = 'TVSCompExpExpression' then begin xmlnode := m_xmlNode.AddChild(strTitle); xmlnode.Attributes['结果'] := TVSExpression.GetStateText(VSExp.State); exit; end; {$endregion 'TVSCompExpExpression'} {$region 'TVSOrderExpression'} if VSExp.ClassName = 'TVSOrderExpression' then begin xmlnode := m_xmlNode.AddChild(strTitle); xmlnode.Attributes['结果'] := TVSExpression.GetStateText(VSExp.State); xmlnode.Attributes['初值'] := '无'; if VSExp.AcceptData <> nil then begin xmlnode.Attributes['初值'] := VSExp.GetRecValue(TVSCompExpression(VSExp).Key,RecHead,VSExp.AcceptData); end; xmlnode.Attributes['上一个值'] := ''; if VSExp.LastData <> nil then begin xmlnode.Attributes['上一个值'] := VSExp.GetRecValue(TVSCompExpression(VSExp).Key,RecHead,VSExp.LastData); end; xmlnode.Attributes['实际值'] := VSExp.GetRecValue(TVSCompExpression(VSExp).Key,RecHead,RecRow); exit; end; {$endregion 'TVSOrderExpression'} {$region 'TVSOffsetExpression'} if VSExp.ClassName = 'TVSOffsetExpression' then begin try xmlnode := m_xmlNode.AddChild(strTitle); except on e : Exception do begin end; end; xmlnode.Attributes['结果'] := TVSExpression.GetStateText(VSExp.State); xmlnode.Attributes['初值'] := '无'; if VSExp.AcceptData <> nil then begin xmlnode.Attributes['初值'] := VSExp.GetRecValue(TVSCompExpression(VSExp).Key,RecHead,VSExp.AcceptData); end; xmlnode.Attributes['上一个值'] := ''; if VSExp.LastData <> nil then begin xmlnode.Attributes['上一个值'] := VSExp.GetRecValue(TVSCompExpression(VSExp).Key,RecHead,VSExp.LastData); end; xmlnode.Attributes['实际值'] := VSExp.GetRecValue(TVSCompExpression(VSExp).Key,RecHead,RecRow); exit; end; {$endregion 'TVSOffsetExpression'} {$region 'TVSSpecial3201Expression'} if VSExp.ClassName = 'TVSSpecial3201Expression' then begin xmlnode := m_xmlNode.AddChild(strTitle); xmlnode.Attributes['结果'] := TVSExpression.GetStateText(VSExp.State); end; {$endregion 'TVSSpecial3201Expression'} {$region 'TVSCompBehindExpression'} if VSExp.ClassName = 'TVSCompBehindExpression' then begin xmlnode := m_xmlNode.AddChild(strTitle); xmlnode.Attributes['结果'] := TVSExpression.GetStateText(VSExp.State); xmlnode.Attributes['首值'] := '空'; xmlnode.Attributes['尾值'] := '空'; if TVSCompBehindExpression(VSExp).FrontExp.GetData <> nil then xmlnode.Attributes['首值'] := VSExp.GetRecValue(TVSCompBehindExpression(VSExp).Key,RecHead,TVSCompBehindExpression(VSExp).FrontExp.GetData); if TVSCompBehindExpression(VSExp).BehindExp.GetData <> nil then xmlnode.Attributes['尾值'] := VSExp.GetRecValue(TVSCompBehindExpression(VSExp).Key,RecHead,TVSCompBehindExpression(VSExp).BehindExp.GetData); end; {$endregion 'TVSCompBehindExpression'} finally if (xmlNode <> nil) and (RecRow <> nil) then xmlnode.Attributes['时间'] := FormatDatetime('HHmmss',TLKJCommonRec(RecRow).CommonRec.DTEvent); end; end; procedure TVSXMLLog.AddRule(RuleTtile : string); var strTitle : string; begin if not OpenLog then exit; strTitle := '未命名规则'; if RuleTtile <> '' then begin strTitle := RuleTtile; end; m_xmlNode := m_xmlDoc.DocumentElement.AddChild(strTitle); end; constructor TVSXMLLog.Create; begin m_xmlDoc := TXMLDocument.Create(nil); m_xmlDoc.Active := True; m_xmlDoc.Version := '1.0'; m_xmlDoc.Encoding := 'gb2312'; m_xmlDoc.Options := [doNodeAutoCreate,doNodeAutoIndent,doAttrNull,doAutoPrefix,doNamespaceDecl]; m_xmlDoc.DocumentElement := m_xmlDoc.CreateNode('RuleList'); end; destructor TVSXMLLog.Destroy; begin if OpenLog then begin if not DirectoryExists(ExtractFilePath(Application.ExeName) + 'log\') then begin CreateDir(ExtractFilePath(Application.ExeName) + 'log\') end; m_xmlDoc.SaveToFile(ExtractFilePath(Application.ExeName) + 'log\' + FormatDateTime('yyMMddHHmmss',now)); m_xmlDoc.DocumentElement.ChildNodes.Clear; end; m_xmlDoc.Free; inherited; end; procedure TVSXMLLog.RebackCombExpress(VSExp: TVSCombExpression); begin if not OpenLog then Exit; m_xmlNode := IXMLNode(VSExp.ParentData); end; end.
unit status; { Keep track of duration, octave, slur and beam status. } interface procedure initStatus; procedure saveStatus(voice: integer); procedure resetDuration (voice: integer; dur: char); function duration(voice: integer): char; function slurLevel(voice: integer): integer; function beamLevel(voice: integer): integer; function noBeamMelisma(voice: integer): boolean; function noSlurMelisma(voice, history: integer): boolean; function afterSlur(voice: integer): integer; procedure setUnbeamed(voice: integer); procedure setUnslurred(voice: integer); procedure beginBeam(voice: integer; var note: string); procedure endBeam(voice: integer); procedure beginSlur(voice: integer; var note: string); procedure endSlur(voice: integer; var note: string); procedure activateBeamsAndSlurs(voice: integer); procedure setOctave(voice: integer); procedure resetOctave(voice: integer); function octave(voice: integer): char; procedure newOctave(voice: integer; dir: char); procedure initOctaves(octaves: string); procedure renewPitch (voice: integer; var note: string); function chordPitch(voice: integer): integer; procedure renewChordPitch (voice: integer; note: string); procedure defineRange(voice: integer; range: string); procedure checkRange(voice: integer; note: string); procedure rememberDurations; procedure restoreDurations; procedure chordTie(voice: integer; var lab: char); type int5 = array[1..5] of integer; procedure getChordTies(voice: integer; var pitches: int5; var labels: string); implementation uses globals, strings, mtxline, control, utility, notes; const init_oct: string = ''; lowest_pitch = -9; highest_pitch = 61; range_name: array[-6..49] of string = ( '0c','0d','0e','0f','0g','0a','0b', '1c','1d','1e','1f','1g','1a','1b', '2c','2d','2e','2f','2g','2a','2b', '3c','3d','3e','3f','3g','3a','3b', '4c','4d','4e','4f','4g','4a','4b', '5c','5d','5e','5f','5g','5a','5b', '6c','6d','6e','6f','6g','6a','6b', '7c','7d','7e','7f','7g','7a','7b'); type line_status = record pitch, chord_pitch, octave_adjust, beam_level, slur_level, after_slur: integer; octave, lastnote, chord_lastnote, duration, slurID, tieID: char; beamnext, beamed, slurnext, slurred, no_beam_melisma: boolean; no_slur_melisma: array[1..12] of boolean; chord_tie_pitch: int5; chord_tie_label: string[5]; end; var current: array[voice_index] of line_status; lastdur: array[voice_index] of char; voice_range, range_low, range_high: array[voice_index] of string; { Range limits are user-specified as e.g. 3c. To make comparisons meaningful, a and b (which come after g) are translated to h and i. } procedure checkRange(voice: integer; note: string); var orig_note: string; begin if voice_range[voice]='' then exit; orig_note := note; if length(note)>2 { assume usual PMX form with octave } then note := note[3]+note[1]; if note[2]='a' then note[2]:='h'; if note[2]='b' then note[2]:='i'; if (note<range_low[voice]) or (note>range_high[voice]) then error3(voice, orig_note+' is out of range, specified as '+voice_range[voice]) end; procedure defineRange(voice: integer; range: string); begin voice_range[voice] := range; if range='' then exit; if not ( ('0'<=range[1]) and (range[1]<='7') and ('a'<=range[2]) and (range[2]<='g') and (range[3]='-') and ('0'<=range[4]) and (range[4]<='7') and ('a'<=range[5]) and (range[5]<='g') ) then error('Badly formatted range "'+range+ '" for voice '+voice_label[voice]+', must be e.g. 3c-4a',print); if range[2]='a' then range[2]:='h'; if range[2]='b' then range[2]:='i'; if range[5]='a' then range[5]:='h'; if range[5]='b' then range[5]:='i'; range_low[voice]:=substr(range,1,2); range_high[voice]:=substr(range,4,2); end; procedure chordTie(voice: integer; var lab: char); var n: integer; begin with current[voice] do begin n:=length(chord_tie_label); if n=5 then error3(voice,'Only five slur ties allowed per voice'); if n=0 then lab:='T' else lab:=chord_tie_label[n]; inc(lab); chord_tie_label:=chord_tie_label+lab; inc(n); chord_tie_pitch[n]:=chord_pitch end end; procedure getChordTies(voice: integer; var pitches: int5; var labels: string); begin with current[voice] do begin pitches:=chord_tie_pitch; labels:=chord_tie_label; chord_tie_label:='' end end; procedure rememberDurations; var v: voice_index; begin for v:=1 to nvoices do lastdur[v]:=duration(v) end; procedure restoreDurations; var v: voice_index; begin for v:=1 to nvoices do resetDuration(v,lastdur[v]) end; function duration(voice: integer): char; begin duration := current[voice].duration; end; procedure resetDuration(voice: integer; dur: char); begin if pos1(dur,durations)=0 then begin write('Trying to set duration to ',dur,'; '); error3(voice,'M-Tx system error: resetDuration'); end; current[voice].duration := dur end; procedure activateBeamsAndSlurs(voice: integer); begin with current[voice] do begin if beamnext then begin beamed:=true; beamnext:=false; end; if slurnext then begin slurred:=true; slurnext:=false; end; if slurred then inc(after_slur); end end; procedure saveStatus(voice: integer); begin with current[voice] do begin chord_pitch := pitch; chord_lastnote := lastnote; end; end; function noBeamMelisma(voice: integer): boolean; begin noBeamMelisma := current[voice].no_beam_melisma; end; function afterSlur(voice: integer): integer; begin with current[voice] do begin afterSlur := after_slur; if (after_slur>0) and (slur_level<1) then error3(voice,'M-Tx system error: afterSlur and slur_level incompatible)') end end; function octave(voice: integer): char; begin octave := current[voice].octave; end; procedure resetOctave(voice: integer); begin current[voice].octave := ' '; end; procedure initOctaves(octaves: string); var i: integer; begin init_oct:=octaves; i:=1; while i<=length(init_oct) do if init_oct[i]=' ' then delete1(init_oct,i) else inc(i); end; function initOctave(voice_stave: stave_index): char; begin if voice_stave>length(init_oct) then if pos1(clef[voice_stave],'Gt08')>0 then initOctave:='4' else initOctave:='3' else initOctave:=init_oct[voice_stave]; end; procedure setOctave(voice: integer); begin current[voice].octave:=initOctave(voiceStave(voice)); end; procedure newOctave(voice: integer; dir: char); begin with current[voice] do case dir of '+': inc(octave); '-': dec(octave); end; end; function newPitch (voice: integer; note: string; pitch: integer; lastnote: char): integer; var interval, npitch: integer; oct: char; begin oct:=octaveCode(note); if oct='=' then oct:=initOctave(voiceStave(voice)); if (oct>='0') and (oct<='9') then begin pitch:=7*(ord(oct)-ord('0'))-3; lastnote:='f'; removeOctaveCode(oct,note); oct:=octaveCode(note) end; interval := ord(note[1])-ord(lastnote); if interval>3 then dec(interval,7); if interval<-3 then inc(interval,7); npitch:=pitch+interval; while oct<>' ' do begin if oct='+' then inc(npitch,7) else if oct='-' then dec(npitch,7); removeOctaveCode(oct,note); oct:=octaveCode(note) end; newPitch:=npitch end; procedure repitch(var note: string; diff: integer); procedure delins(var note: string; c1, c2: char; l: integer); var i, n: integer; begin n:=length(note); i:=pos1(c1,note); if i=0 then i:=n+1; while (l>0) and (i<=n) do begin delete1(note,i); dec(n); dec(l); end; i:=pos1(c2,note); if i=0 then if length(note)<2 then error('M-Tx program error',print) else i:=3; while l>0 do begin insertchar(c2,note,i); dec(l); end; end; begin diff:=diff div 7; if diff>0 then delins(note, '-','+',diff) else delins(note, '+','-',-diff); end; procedure setUnbeamed(voice: integer); begin current[voice].beamed:=false end; procedure setUnslurred(voice: integer); begin with current[voice] do begin slurred:=false; after_slur:=0; end; end; procedure beginBeam(voice: integer; var note: string); begin with current[voice] do begin if beamed then error3(voice, 'Starting a forced beam while another is open'); if beam_level>0 then error3(voice, 'Starting a forced beam while another is open (beamlevel>0)'); inc(beam_level); beamnext := true; no_beam_melisma:=startsWith(note,'[['); if no_beam_melisma then predelete(note,1); end; end; procedure endBeam(voice: integer); begin with current[voice] do begin if beam_level<1 then error3(voice, 'Closing a beam that was never opened'); dec(beam_level) end; setUnbeamed(voice) end; function slurLevel(voice: integer): integer; begin slurLevel := current[voice].slur_level; end; function beamLevel(voice: integer): integer; begin beamLevel := current[voice].beam_level; end; function noSlurMelisma(voice, history: integer): boolean; begin with current[voice] do noSlurMelisma := no_slur_melisma[slur_level+history]; end; function slurLabel(voice: integer; note: string): string; var sl: char; begin if note='' then begin slurLabel:=''; exit end; if length(note)<2 then begin slurLabel:=' '; exit end; if (note[2]>='0') and (note[2]<='Z') then sl:=note[2] else sl:=' '; if (sl>='I') and (sl<='T') then warning3(voice,'Slur label in the range I..T may cause conflict'); slurLabel:=sl end; procedure labelSlur(voice: integer; var note: string); var sl: char; begin if note='' then exit; with current[voice] do begin if note[1]=')' then inc(slurID,2) else if note[1]='}' then inc(tieID,2); {* CMO 0.60a: replace assigning tieID to sl by space charater if (note[1]='(') or (note[1]=')') then sl:=slurID else sl:=tieID; } if (note[1]='(') or (note[1]=')') then sl:=slurID else sl:=' '; {* CMO 0.60d: omit insertchar in case of tie insertchar(sl,note,2); } if (note[1]='(') or (note[1]=')') then insertchar(sl,note,2); if note[1]='(' then dec(slurID,2) else if note[1]='{' then dec(tieID,2); if slurID<'I' then warning3(voice,'Too many nested slurs may cause conflict'); if tieID<'I' then warning3(voice,'Too many nested ties may cause conflict') end end; procedure beginSlur(voice: integer; var note: string); var posblind: integer; begin with current[voice] do begin inc(slur_level); if slur_level>12 then Error3(voice,'Too many open slurs'); no_slur_melisma[slur_level] := startsWith(note,'((') or startsWith(note,'{{'); if no_slur_melisma[slur_level] then predelete(note,1); if slurLabel(voice,note)='0' then delete1(note,2) else if slurLabel(voice,note)=' ' then labelSlur(voice,note); posblind:=pos1('~',note); if posblind>0 then if hideBlindSlurs then note:='' else delete1(note,posblind); slurnext := true; end; end; procedure endSlur(voice: integer; var note: string); var poscontinue, posblind: integer; contslur: string; begin with current[voice] do begin contslur:=''; if slur_level<1 then Error3(voice,'Ending a slur that was never started'); if note[1]=')' then poscontinue:=pos1('(',note) else if note[1]='}' then poscontinue:=pos1('{',note); if poscontinue=0 then dec(slur_level) else begin dec(poscontinue); contslur:=note; predelete(contslur,poscontinue); shorten(note,poscontinue); end; if slur_level=0 then setUnslurred(voice); if slurLabel(voice,note)='0' then delete1(note,2) else if slurLabel(voice,note)=' ' then labelSlur(voice,note); if slurLabel(voice,contslur)='0' then delete1(contslur,2) else if slurLabel(voice,contslur)=' ' then labelSlur(voice,contslur); if poscontinue>0 then begin if note[1]='}' then note:=note+'t'; note[1]:='s'; if contslur[1]='{' then contslur:=contslur+'t'; contslur[1]:='s'; end; posblind:=pos1('~',note); if posblind>0 then if hideBlindSlurs then note:='' else delete1(note,posblind); if (note<>'') and (contslur<>'') then note := note + ' ' + contslur; end; end; { This is the routine called by prepmx.pas for every normal and chordal note, immediately after checkOctave. It does two things: adjusts pitch of notes following a C: chord to what it would have been without that chord, and checks for pitch overruns. } procedure renewPitch (voice: integer; var note: string); var pstat: integer; begin with current[voice] do begin pstat:=newPitch (voice, note, chord_pitch, chord_lastnote); pitch := newPitch (voice, note, pitch, lastnote); if pitch<>pstat then repitch(note,pitch-pstat); checkRange(voice,range_name[pitch]); if (pitch<lowest_pitch) and checkPitch then begin write('Pitch of note ',note,' following ',lastnote,' reported as ',pitch); error3(voice,'Pitch too low') end; if (pitch>highest_pitch) and checkPitch then begin write('Pitch of note ',note,' following ',lastnote,' reported as ',pitch); error3(voice,'Pitch too high') end; lastnote:=note[1]; end; end; function chordPitch(voice: integer): integer; begin chordPitch:=current[voice].chord_pitch end; procedure renewChordPitch (voice: integer; note: string); begin with current[voice] do begin chord_pitch:=newPitch(voice,note,chord_pitch,chord_lastnote); if chord_pitch<lowest_pitch then error3(voice,'Pitch in chord too low'); if chord_pitch>highest_pitch then error3(voice,'Pitch in chord too high'); chord_lastnote:=note[1]; end end; procedure initStatus; var voice: integer; begin for voice:=1 to nvoices do with current[voice] do begin duration:=default_duration; octave_adjust:=0; slur_level:=0; beam_level:=0; beamed:=false; beamnext:=false; slurred:=false; slurnext:=false; after_slur:=0; octave:=initOctave(voiceStave(voice)); slurID:='S'; tieID:='T'; lastnote:='f'; pitch:=7*(ord(octave)-ord('0'))-3; chord_tie_label:=''; saveStatus(voice); end; end; end.
// ----------- Parse::Easy::Runtime ----------- // https://github.com/MahdiSafsafi/Parse-Easy // -------------------------------------------- unit Parse.Easy.Parser.State; interface uses System.Classes, System.SysUtils; type TState = class(TObject) private FIndex: Integer; FTerms: TList; FNoTerms: TList; FNumberOfTerms: Integer; FNumberOfNoTerms: Integer; procedure SetNumberOfNoTerms(const Value: Integer); procedure SetNumberOfTerms(const Value: Integer); public constructor Create; virtual; destructor Destroy; override; property Index: Integer read FIndex write FIndex; property NumberOfTerms: Integer read FNumberOfTerms write SetNumberOfTerms; property NumberOfNoTerms: Integer read FNumberOfNoTerms write SetNumberOfNoTerms; property Terms: TList read FTerms; property NoTerms: TList read FNoTerms; end; implementation { TState } constructor TState.Create; begin FNumberOfTerms := -1; FNumberOfNoTerms := -1; FTerms := TList.Create; FNoTerms := TList.Create; end; destructor TState.Destroy; var I: Integer; begin for I := 0 to FTerms.Count - 1 do if Assigned(FTerms[I]) then TObject(FTerms[I]).Free; for I := 0 to FNoTerms.Count - 1 do if Assigned(FNoTerms[I]) then TObject(FNoTerms[I]).Free; FTerms.Free; FNoTerms.Free; inherited; end; procedure TState.SetNumberOfNoTerms(const Value: Integer); var I: Integer; begin if (FNumberOfNoTerms <> Value) then begin FNumberOfNoTerms := Value; FNoTerms.Clear; for I := 0 to Value - 1 do FNoTerms.Add(nil); end; end; procedure TState.SetNumberOfTerms(const Value: Integer); var I: Integer; begin if (FNumberOfTerms <> Value) then begin FNumberOfTerms := Value; FTerms.Clear; for I := 0 to Value - 1 do FTerms.Add(nil); end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GeometryCoordinates<p> Helper functions to convert between different three dimensional coordinate systems. Room for optimisations.<p> <b>History : </b><font size=-1><ul> <li>30/04/03 - EG - Hyperbolic functions moved to GLVectorGeometry.pas <li>30/04/03 - ARH - Remove math.pas dependency <li>24/04/03 - ARH - Double versions added <li>10/04/03 - ARH - Added ProlateSpheroidal,OblateSpheroidal, BiPolarCylindrical <li>09/04/03 - ARH - Initial Version (Cylindrical,Spherical) </ul> } unit GeometryCoordinates; interface uses GLVectorGeometry; {: Convert cylindrical to cartesian [single]. theta in rad} procedure Cylindrical_Cartesian(const r,theta,z1:single;var x,y,z:single);overload; {: Convert cylindrical to cartesian [double]. theta in rads} procedure Cylindrical_Cartesian(const r,theta,z1:double;var x,y,z:double);overload; {: Convert cylindrical to cartesian [single] (with error check). theta in rad} procedure Cylindrical_Cartesian(const r,theta,z1:single;var x,y,z:single; var ierr:integer);overload; {: Convert cylindrical to cartesian [double] (with error check). theta in rad} procedure Cylindrical_Cartesian(const r,theta,z1:double;var x,y,z:double; var ierr:integer);overload; {: Convert cartesian to cylindrical [single]} procedure Cartesian_Cylindrical(const x,y,z1:single; var r,theta,z:single);overload; {: Convert cartesion to cylindrical [double]} procedure Cartesian_Cylindrical(const x,y,z1:double; var r,theta,z:double);overload; {: Convert spherical to cartesion. [single] theta,phi in rads} procedure Spherical_Cartesian(const r,theta,phi:single;var x,y,z:single);overload; {: Convert spherical to cartesion. [double] theta,phi in rads} procedure Spherical_Cartesian(const r,theta,phi:double;var x,y,z:double);overload; {: Convert spherical to cartesian [single] (with error check).theta,phi in rad} procedure Spherical_Cartesian(const r,theta,phi:single;var x,y,z:single; var ierr:integer);overload; {: Convert spherical to cartesian [double] (with error check).theta,phi in rad} procedure Spherical_Cartesian(const r,theta,phi:double;var x,y,z:double; var ierr:integer);overload; {: Convert cartesian to spherical [single]} procedure Cartesian_Spherical(const x,y,z:single; var r,theta,phi:single);overload; procedure Cartesian_Spherical(const v : TAffineVector; var r, theta, phi : Single); overload; {: Convert cartesion to spherical [double]} procedure Cartesian_Spherical(const x,y,z:double; var r,theta,phi:double);overload; {: Convert Prolate-Spheroidal to Cartesian. [single] eta, phi in rad} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single);overload; {: Convert Prolate-Spheroidal to Cantesian. [double] eta,phi in rad} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double);overload; {: Convert Prolate-Spheroidal to Cartesian [single](with error check). eta,phi in rad} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single; var ierr:integer);overload; {: Convert Prolate-Spheroidal to Cartesian [single](with error check). eta,phi in rad} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double; var ierr:integer);overload; {: Convert Oblate-Spheroidal to Cartesian. [Single] eta, phi in rad} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single);overload; {: Convert Oblate-Spheroidal to Cartesian. [Double] eta, phi in rad} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double);overload; {: Convert Oblate-Spheroidal to Cartesian (with error check). eta,phi in rad} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single; var ierr:integer);overload; {: Convert Oblate-Spheroidal to Cartesian (with error check).[Double] eta,phi in rad} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double; var ierr:integer);overload; {: Convert Bipolar to Cartesian. u in rad} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:single; var x,y,z:single);overload; {: Convert Bipolar to Cartesian. [Double] u in rad} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:double; var x,y,z:double);overload; {: Convert Bipolar to Cartesian (with error check). u in rad} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:single; var x,y,z:single; var ierr:integer);overload; {: Convert Bipolar to Cartesian (with error check). [Double] u in rad} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:double; var x,y,z:double; var ierr:integer);overload; implementation // ----- Cylindrical_Cartesian ------------------------------------------------- {** Convert Cylindrical to Cartesian with no checks. Ref: http://mathworld.wolfram.com/CylindricalCoordinates.html} procedure Cylindrical_Cartesian(const r,theta,z1:single;var x,y,z:single); begin GLVectorGeometry.sincos(theta,r,y,x); z := z1; end; // ----- Cylindrical_Cartesian ------------------------------------------------- {** Convert Cylindrical to Cartesian with no checks. Double version Ref: http://mathworld.wolfram.com/CylindricalCoordinates.html} procedure Cylindrical_Cartesian(const r,theta,z1:double;var x,y,z:double); begin GLVectorGeometry.sincos(theta,r,y,x); z := z1; end; // ----- Cylindrical_Cartesian ------------------------------------------------- {** Convert Cylindrical to Cartesian with checks. ierr: [0] = ok, [1] = r out of bounds. Acceptable r: [0,inf) [2] = theta out of bounds. Acceptable theta: [0,2pi) [3] = z1 out of bounds. Acceptable z1 : (-inf,inf) Ref: http://mathworld.wolfram.com/CylindricalCoordinates.html} procedure Cylindrical_Cartesian(const r,theta,z1:single;var x,y,z:single; var ierr:integer); begin {** check input parameters} if (r < 0.0) then ierr := 1 else if ((theta < 0.0) or (theta >= 2*pi)) then ierr := 2 else ierr := 0; if (ierr = 0) then begin GLVectorGeometry.sincos(theta,r,y,x); z := z1; end; end; // ----- Cylindrical_Cartesian ------------------------------------------------- {** Convert Cylindrical to Cartesian with checks. ierr: [0] = ok, [1] = r out of bounds. Acceptable r: [0,inf) [2] = theta out of bounds. Acceptable theta: [0,2pi) [3] = z1 out of bounds. Acceptable z1 : (-inf,inf) Ref: http://mathworld.wolfram.com/CylindricalCoordinates.html} procedure Cylindrical_Cartesian(const r,theta,z1:double;var x,y,z:double; var ierr:integer); begin {** check input parameters} if (r < 0.0) then ierr := 1 else if ((theta < 0.0) or (theta >= 2*pi)) then ierr := 2 else ierr := 0; if (ierr = 0) then begin GLVectorGeometry.sincos(theta,r,y,x); z := z1; end; end; // ----- Cartesian_Cylindrical ------------------------------------------------- {** Convert Cartesian to Cylindrical no checks. Single} procedure Cartesian_Cylindrical(const x,y,z1:single; var r,theta,z:single); begin r := sqrt(x*x+y*y); theta := GLVectorGeometry.arctan2(y,x); z := z1; end; // ----- Cartesian_Cylindrical ------------------------------------------------- {** Convert Cartesian to Cylindrical no checks. Duoble} procedure Cartesian_Cylindrical(const x,y,z1:double; var r,theta,z:double); begin r := sqrt(x*x+y*y); theta := GLVectorGeometry.arctan2(y,x); z := z1; end; // ----- Spherical_Cartesian --------------------------------------------------- {** Convert Spherical to Cartesian with no checks. Ref: http://mathworld.wolfram.com/SphericalCoordinates.html} procedure Spherical_Cartesian(const r,theta,phi:single; var x,y,z:single); var a : single; begin GLVectorGeometry.sincos(phi,r,a,z); // z = r*cos(phi), a=r*sin(phi) GLVectorGeometry.sincos(theta,a,y,x); // x = a*cos(theta), y = a*sin(theta)} end; // ----- Spherical_Cartesian --------------------------------------------------- {** Convert Spherical to Cartesian with no checks. Double version. Ref: http://mathworld.wolfram.com/SphericalCoordinates.html} procedure Spherical_Cartesian(const r,theta,phi:double; var x,y,z:double); var a : double; begin GLVectorGeometry.sincos(phi,r,a,z); // z = r*cos(phi), a=r*sin(phi) GLVectorGeometry.sincos(theta,a,y,x); // x = a*cos(theta), y = a*sin(theta)} end; // ----- Spherical_Cartesian --------------------------------------------------- {** Convert Spherical to Cartesian with checks. ierr: [0] = ok, [1] = r out of bounds [2] = theta out of bounds [3] = phi out of bounds Ref: http://mathworld.wolfram.com/SphericalCoordinates.html} procedure Spherical_Cartesian(const r,theta,phi:single; var x,y,z:single; var ierr:integer); var a : single; begin if (r < 0.0) then ierr := 1 else if ((theta < 0.0) or (theta >= 2*pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin GLVectorGeometry.sincos(phi,r,a,z); // z = r*cos(phi), a=r*sin(phi) GLVectorGeometry.sincos(theta,a,y,x); // x = a*cos(theta), y = a*sin(theta)} end; end; // ----- Spherical_Cartesian --------------------------------------------------- {** Convert Spherical to Cartesian with checks. ierr: [0] = ok, [1] = r out of bounds [2] = theta out of bounds [3] = phi out of bounds Ref: http://mathworld.wolfram.com/SphericalCoordinates.html} procedure Spherical_Cartesian(const r,theta,phi:double; var x,y,z:double; var ierr:integer); var a : double; begin if (r < 0.0) then ierr := 1 else if ((theta < 0.0) or (theta >= 2*pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin GLVectorGeometry.sincos(phi,r,a,z); // z = r*cos(phi), a=r*sin(phi) GLVectorGeometry.sincos(theta,a,y,x); // x = a*cos(theta), y = a*sin(theta)} end; end; // ----- Cartesian_Spherical --------------------------------------------------- {** convert Cartesian to Spherical, no checks, single Ref: http://mathworld.wolfram.com/SphericalCoordinates.html NB: Could be optimised by using jclmath.pas unit? } procedure Cartesian_Spherical(const x,y,z:single; var r,theta,phi:single); begin r := sqrt((x*x)+(y*y)+(z*z)); theta := GLVectorGeometry.arctan2(y,x); phi := GLVectorGeometry.arccos(z/r); end; // Cartesian_Spherical // procedure Cartesian_Spherical(const v : TAffineVector; var r, theta, phi : Single); begin r:=VectorLength(v); theta:=ArcTan2(v[1], v[0]); phi:=ArcCos(v[2]/r); end; // ----- Cartesian_Spherical --------------------------------------------------- {** convert Cartesian to Spherical, no checks, double Ref: http://mathworld.wolfram.com/SphericalCoordinates.html NB: Could be optimised by using jclmath.pas unit? } procedure Cartesian_Spherical(const x,y,z:double; var r,theta,phi:double); begin r := sqrt((x*x)+(y*y)+(z*z)); theta := GLVectorGeometry.arctan2(y,x); phi := GLVectorGeometry.arccos(z/r); end; // ----- ProlateSpheroidal_Cartesian ------------------------------------------- {** Convert Prolate-Spheroidal to Cartesian with no checks. A system of curvilinear coordinates in which two sets of coordinate surfaces are obtained by revolving the curves of the elliptic cylindrical coordinates about the x-axis, which is relabeled the z-axis. The third set of coordinates consists of planes passing through this axis. The coordinate system is parameterised by parameter a. A default value of a=1 is suggesed: http://documents.wolfram.com/v4/AddOns/StandardPackages/Calculus/VectorAnalysis.html Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:single;var x,y,z:single); var sn,cs,snphi,csphi,shx,chx : single; begin GLVectorGeometry.sincos(eta,a,sn,cs); GLVectorGeometry.SinCos(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := sn*shx*csphi; // x = a*sin(eta)*sinh(xi)*cos(phi) y := sn*shx*snphi; // y = a*sin(eta)*sinh(xi)*sin(phi) z := cs*chx; // z = a*cos(eta)*cosh(xi) end; // ----- ProlateSpheroidal_Cartesian ------------------------------------------- {** Convert Prolate-Spheroidal to Cartesian with no checks. Double version. A system of curvilinear coordinates in which two sets of coordinate surfaces are obtained by revolving the curves of the elliptic cylindrical coordinates about the x-axis, which is relabeled the z-axis. The third set of coordinates consists of planes passing through this axis. The coordinate system is parameterised by parameter a. A default value of a=1 is suggesed: http://documents.wolfram.com/v4/AddOns/StandardPackages/Calculus/VectorAnalysis.html Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:double;var x,y,z:double); var sn,cs,snphi,csphi,shx,chx : double; begin GLVectorGeometry.sincos(eta,a,sn,cs); GLVectorGeometry.sincos(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := sn*shx*csphi; // x = a*sin(eta)*sinh(xi)*cos(phi) y := sn*shx*snphi; // y = a*sin(eta)*sinh(xi)*sin(phi) z := cs*chx; // z = a*cos(eta)*cosh(xi) end; // ----- ProlateSpheroidal_Cartesian ------------------------------------------- {** Convert Prolate-Spheroidal to Cartesian with checks. ierr: [0] = ok, [1] = xi out of bounds. Acceptable xi: [0,inf) [2] = eta out of bounds. Acceptable eta: [0,pi] [3] = phi out of bounds. Acceptable phi: [0,2pi) Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single; var ierr:integer);overload; var sn,cs,snphi,csphi,shx,chx : single; begin if (xi < 0.0) then ierr := 1 else if ((eta < 0.0) or (eta > pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin GLVectorGeometry.sincos(eta,a,sn,cs); GLVectorGeometry.sincos(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := sn*shx*csphi; // x = a*sin(eta)*sinh(xi)*cos(phi) y := sn*shx*snphi; // y = a*sin(eta)*sinh(xi)*sin(phi) z := cs*chx; // z = a*cos(eta)*cosh(xi) end; end; // ----- ProlateSpheroidal_Cartesian ------------------------------------------- {** Convert Prolate-Spheroidal to Cartesian with checks. Double Version. ierr: [0] = ok, [1] = xi out of bounds. Acceptable xi: [0,inf) [2] = eta out of bounds. Acceptable eta: [0,pi] [3] = phi out of bounds. Acceptable phi: [0,2pi) Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double; var ierr:integer);overload; var sn,cs,snphi,csphi,shx,chx : double; begin if (xi < 0.0) then ierr := 1 else if ((eta < 0.0) or (eta > pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin GLVectorGeometry.sincos(eta,a,sn,cs); GLVectorGeometry.sincos(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := sn*shx*csphi; // x = a*sin(eta)*sinh(xi)*cos(phi) y := sn*shx*snphi; // y = a*sin(eta)*sinh(xi)*sin(phi) z := cs*chx; // z = a*cos(eta)*cosh(xi) end; end; // ----- OblateSpheroidal_Cartesian ------------------------------------------- {** Convert Oblate-Spheroidal to Cartesian with no checks. A system of curvilinear coordinates in which two sets of coordinate surfaces are obtained by revolving the curves of the elliptic cylindrical coordinates about the y-axis which is relabeled the z-axis. The third set of coordinates consists of planes passing through this axis. The coordinate system is parameterised by parameter a. A default value of a=1 is suggesed: http://documents.wolfram.com/v4/AddOns/StandardPackages/Calculus/VectorAnalysis.html Ref: http://mathworld.wolfram.com/OblateSpheroidalCoordinates.html} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:single;var x,y,z:single); var sn,cs,snphi,csphi,shx,chx : single; begin GLVectorGeometry.sincos(eta,a,sn,cs); GLVectorGeometry.sincos(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := cs*chx*csphi; // x = a*cos(eta)*cosh(xi)*cos(phi) y := cs*chx*snphi; // y = a*cos(eta)*cosh(xi)*sin(phi) z := sn*shx; // z = a*sin(eta)*sinh(xi) end; // ----- OblateSpheroidal_Cartesian ------------------------------------------- {** Convert Oblate-Spheroidal to Cartesian with no checks. Double Version. A system of curvilinear coordinates in which two sets of coordinate surfaces are obtained by revolving the curves of the elliptic cylindrical coordinates about the y-axis which is relabeled the z-axis. The third set of coordinates consists of planes passing through this axis. The coordinate system is parameterised by parameter a. A default value of a=1 is suggesed: http://documents.wolfram.com/v4/AddOns/StandardPackages/Calculus/VectorAnalysis.html Ref: http://mathworld.wolfram.com/OblateSpheroidalCoordinates.html} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:double;var x,y,z:double); var sn,cs,snphi,csphi,shx,chx : double; begin GLVectorGeometry.sincos(eta,a,sn,cs); GLVectorGeometry.sincos(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := cs*chx*csphi; // x = a*cos(eta)*cosh(xi)*cos(phi) y := cs*chx*snphi; // y = a*cos(eta)*cosh(xi)*sin(phi) z := sn*shx; // z = a*sin(eta)*sinh(xi) end; // ----- OblateSpheroidal_Cartesian ------------------------------------------- {** Convert Oblate-Spheroidal to Cartesian with checks. ierr: [0] = ok, [1] = xi out of bounds. Acceptable xi: [0,inf) [2] = eta out of bounds. Acceptable eta: [-0.5*pi,0.5*pi] [3] = phi out of bounds. Acceptable phi: [0,2*pi) Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single; var ierr:integer);overload; var sn,cs,snphi,csphi,shx,chx : single; begin if (xi < 0.0) then ierr := 1 else if ((eta < -0.5*pi) or (eta > 0.5*pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin GLVectorGeometry.SinCos(eta,a,sn,cs); GLVectorGeometry.sincos(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := cs*chx*csphi; // x = a*cos(eta)*cosh(xi)*cos(phi) y := cs*chx*snphi; // y = a*cos(eta)*cosh(xi)*sin(phi) z := sn*shx; // z = a*sin(eta)*sinh(xi) end; end; // ----- OblateSpheroidal_Cartesian ------------------------------------------- {** Convert Oblate-Spheroidal to Cartesian with checks. Double Version. ierr: [0] = ok, [1] = xi out of bounds. Acceptable xi: [0,inf) [2] = eta out of bounds. Acceptable eta: [-0.5*pi,0.5*pi] [3] = phi out of bounds. Acceptable phi: [0,2*pi) Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double; var ierr:integer);overload; var sn,cs,snphi,csphi,shx,chx : double; begin if (xi < 0.0) then ierr := 1 else if ((eta < -0.5*pi) or (eta > 0.5*pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin GLVectorGeometry.SinCos(eta,a,sn,cs); GLVectorGeometry.sincos(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := cs*chx*csphi; // x = a*cos(eta)*cosh(xi)*cos(phi) y := cs*chx*snphi; // y = a*cos(eta)*cosh(xi)*sin(phi) z := sn*shx; // z = a*sin(eta)*sinh(xi) end; end; // ----- BipolarCylindrical_Cartesian ------------------------------------------ {** Convert BiPolarCylindrical to Cartesian with no checks. http://mathworld.wolfram.com/BipolarCylindricalCoordinates.html } procedure BipolarCylindrical_Cartesian(const u,v,z1,a:single;var x,y,z:single); var cs,sn,shx,chx:single; begin GLVectorGeometry.SinCos(u,sn,cs); shx:=sinh(v); chx:=cosh(v); x := a*shx/(chx-cs); y := a*sn/(chx-cs); z := z1; end; // ----- BipolarCylindrical_Cartesian ------------------------------------------ {** Convert BiPolarCylindrical to Cartesian with no checks. Double Version http://mathworld.wolfram.com/BipolarCylindricalCoordinates.html } procedure BipolarCylindrical_Cartesian(const u,v,z1,a:double;var x,y,z:double); var cs,sn,shx,chx:double; begin GLVectorGeometry.SinCos(u,sn,cs); shx:=sinh(v); chx:=cosh(v); x := a*shx/(chx-cs); y := a*sn/(chx-cs); z := z1; end; // ----- BipolarCylindrical_Cartesian ------------------------------------------ {** Convert Oblate-Spheroidal to Cartesian with checks. ierr: [0] = ok, [1] = u out of bounds. Acceptable u: [0,2*pi) [2] = v out of bounds. Acceptable v: (-inf,inf) [3] = z1 out of bounds. Acceptable z1: (-inf,inf) Ref: http://mathworld.wolfram.com/BiPolarCylindricalCoordinates.html} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:single;var x,y,z:single; var ierr:integer);overload; var cs,sn,shx,chx:single; begin if ((u < 0.0) or (u >= 2*pi)) then ierr := 1 else ierr := 0; if (ierr = 0) then begin GLVectorGeometry.SinCos(u,sn,cs); shx:=sinh(v); chx:=cosh(v); x := a*shx/(chx-cs); y := a*sn/(chx-cs); z := z1; end; end; // ----- BipolarCylindrical_Cartesian ------------------------------------------ {** Convert Oblate-Spheroidal to Cartesian with checks. Double Version ierr: [0] = ok, [1] = u out of bounds. Acceptable u: [0,2*pi) [2] = v out of bounds. Acceptable v: (-inf,inf) [3] = z1 out of bounds. Acceptable z1: (-inf,inf) Ref: http://mathworld.wolfram.com/BiPolarCylindricalCoordinates.html} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:double;var x,y,z:double; var ierr:integer);overload; var cs,sn,shx,chx:double; begin if ((u < 0.0) or (u >= 2*pi)) then ierr := 1 else ierr := 0; if (ierr = 0) then begin GLVectorGeometry.SinCos(u,sn,cs); shx:=sinh(v); chx:=cosh(v); x := a*shx/(chx-cs); y := a*sn/(chx-cs); z := z1; end; end; // ============================================================================= end.
(*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* Unit GameConstants *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* [2006/??/??] Helios - Author unstated... ================================================================================ License: (FreeBSD, plus commercial with written permission clause.) ================================================================================ Project Helios - Copyright (c) 2005-2007 All rights reserved. Please refer to Helios.dpr for full license terms. ================================================================================ Overview: ================================================================================ This unit houses game related global variables and constants. ================================================================================ Revisions: ================================================================================ (Format: [yyyy/mm/dd] <Author> - <Desc of Changes>) [2006/09/21] RaX - Created Header. [2006/12/23] Muad_Dib - Added new jobs (nin, gs, xmas). [2007/04/28] CR - Altered header. Rearranged Direction constants to reuse NORTH and NORTHEAST as the bounds for the constant Directions array. *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*) unit GameConstants; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Types; const CHAR_BLEVEL_MAX = 9999; CHAR_JLEVEL_MAX = 9999; CHAR_STAT_MAX = 9999; CHAR_STATPOINT_MAX = 1000000; CHAR_SKILLPOINT_MAX = 1000000; NPC_WARPSPRITE = 45; NPC_INVISIBLE = 32767; L_HAND = 1; R_HAND = 0; //------------------------------------------------------------------------------ // Character Stat Constants //------------------------------------------------------------------------------ STR = 0; {Strength - Increases attack strength and weight capacity } AGI = 1; {Agility - Increases attack speed and dodge rate. } VIT = 2; {Vitality - Increases defense and vitality, as well as HP recovery. } INT = 3; {Intelligence - Increases magic attack and magic defense. } DEX = 4; {Dexterity - Increases accuracy and stabilizes the amount of damage done by a weapon. As well as lowers the cast time to some skills/spells. } LUK = 5; {Luck - Increases Critical hits and perfect dodge rate, and brings about lots of luck. } ASPD = $0035; //------------------------------------------------------------------------------ // Movement Constants //------------------------------------------------------------------------------ NORTH = 0; NORTHWEST = 1; WEST = 2; SOUTHWEST = 3; SOUTH = 4; SOUTHEAST = 5; EAST = 6; NORTHEAST = 7; { Unit direction vectors with North and West being positive Y, and X, respectively. } Directions : array[NORTH..NORTHEAST] of TPoint = ( (X:0;Y:1), //North (X:-1;Y:1), //NorthWest (X:-1;Y:0), //West (X:-1;Y:-1), //SouthWest (X:0;Y:-1), //South (X:1;Y:-1), //SouthEast (X:1;Y:0), //East (X:1;Y:1) //NorthEast ); Diagonals = [NORTHEAST, NORTHWEST, SOUTHEAST, SOUTHWEST]; //------------------------------------------------------------------------------ // Character Job Constants //------------------------------------------------------------------------------ JOB_NOVICE = 0; //Novice JOB_SWORDMAN = 1; //Swordsman JOB_MAGE = 2; //Magician JOB_ARCHER = 3; //Archer JOB_ACOLYTE = 4; //Acolyte JOB_MERCHANT = 5; //Merchant JOB_THIEF = 6; //Thief JOB_KNIGHT = 7; //Knight JOB_PRIEST = 8; //Priest JOB_WIZARD = 9; //Wizard JOB_BLACKSMITH = 10; //Blacksmith JOB_HUNTER = 11; //Hunter JOB_ASSASSIN = 12; //Assassin JOB_KNIGHT_2 = 13; //Mounted Knight(on peco) JOB_CRUSADER = 14; //Crusader JOB_MONK = 15; //Monk JOB_SAGE = 16; //Sage JOB_ROGUE = 17; //Rogue JOB_ALCHEMIST = 18; //Alchemist JOB_BARD = 19; //Bard JOB_DANCER = 20; //Dancer JOB_CRUSADER_2 = 21; //Mounted Crusader(on peco) JOB_WEDDING = 22; //Wedding JOB_SNOVICE = 23; //Super Novice JOB_GUNSLINGER = 24; //Gunslinger JOB_NINJA = 25; //Ninja JOB_XMAS = 26; //Xmas Suit //High (4001+ Job classes) HJOB_OFFSET = 4001; HJOB_HIGH_NOVICE = HJOB_OFFSET + JOB_NOVICE; //4001 High Novice HJOB_HIGH_SWORDMAN = HJOB_OFFSET + JOB_SWORDMAN; //4002 High Swordsman HJOB_HIGH_MAGE = HJOB_OFFSET + JOB_MAGE; //4003 High Magician HJOB_HIGH_ARCHER = HJOB_OFFSET + JOB_ARCHER; //4004 High Archer HJOB_HIGH_ACOLYTE = HJOB_OFFSET + JOB_ACOLYTE; //4005 High Acolyte HJOB_HIGH_MERCHANT = HJOB_OFFSET + JOB_MERCHANT; //4006 High Merchant HJOB_HIGH_THIEF = HJOB_OFFSET + JOB_THIEF; //4007 High Thief HJOB_LORD_KNIGHT = HJOB_OFFSET + JOB_KNIGHT; //4008 Lord Knight HJOB_HIGH_PRIEST = HJOB_OFFSET + JOB_PRIEST; //4009 High Priest HJOB_HIGH_WIZARD = HJOB_OFFSET + JOB_WIZARD; //4010 High Wizard HJOB_WHITESMITH = HJOB_OFFSET + JOB_BLACKSMITH; //4011 Master Smith HJOB_SNIPER = HJOB_OFFSET + JOB_HUNTER; //4012 Sniper HJOB_ASSASSIN_CROSS = HJOB_OFFSET + JOB_ASSASSIN; //4013 Assassin Cross HJOB_PECO_KNIGHT = HJOB_OFFSET + JOB_KNIGHT_2; //4014 Mounted Lord Knight(on peco) HJOB_PALADIN = HJOB_OFFSET + JOB_CRUSADER; //4015 Paladin HJOB_CHAMPION = HJOB_OFFSET + JOB_MONK; //4016 Champion HJOB_PROFESSOR = HJOB_OFFSET + JOB_SAGE; //4017 Scholar HJOB_STALKER = HJOB_OFFSET + JOB_ROGUE; //4018 Stalker HJOB_CREATOR = HJOB_OFFSET + JOB_ALCHEMIST; //4019 Biochemist HJOB_CLOWN = HJOB_OFFSET + JOB_BARD; //4020 Minstrel HJOB_GYPSY = HJOB_OFFSET + JOB_DANCER; //4021 Gypsy HJOB_PECO_PALADIN = HJOB_OFFSET + JOB_CRUSADER_2; //4022 Mounted Paladin(on peco) //Baby (4023+ Job classes) HJOB_BABY_OFFSET = 4023; HJOB_BABY = HJOB_BABY_OFFSET + JOB_NOVICE; //4023 Baby Novice HJOB_BABY_SWORDMAN = HJOB_BABY_OFFSET + JOB_SWORDMAN; //4024 Baby Swordsman HJOB_BABY_MAGE = HJOB_BABY_OFFSET + JOB_MAGE; //4025 Baby Magician HJOB_BABY_ARCHER = HJOB_BABY_OFFSET + JOB_ARCHER; //4026 Baby Archer HJOB_BABY_ACOLYTE = HJOB_BABY_OFFSET + JOB_ACOLYTE; //4027 Baby Acolyte HJOB_BABY_MERCHANT = HJOB_BABY_OFFSET + JOB_MERCHANT; //4028 Baby Merchant HJOB_BABY_THIEF = HJOB_BABY_OFFSET + JOB_THIEF; //4029 Baby Thief HJOB_BABY_KNIGHT = HJOB_BABY_OFFSET + JOB_KNIGHT; //4030 Baby Knight HJOB_BABY_PRIEST = HJOB_BABY_OFFSET + JOB_PRIEST; //4031 Baby Priest HJOB_BABY_WIZARD = HJOB_BABY_OFFSET + JOB_WIZARD; //4032 Baby Wizard HJOB_BABY_BLACKSMITH = HJOB_BABY_OFFSET + JOB_BLACKSMITH; //4033 Baby Blacksmith HJOB_BABY_HUNTER = HJOB_BABY_OFFSET + JOB_HUNTER; //4034 Baby Hunter HJOB_BABY_ASSASSIN = HJOB_BABY_OFFSET + JOB_ASSASSIN; //4035 Baby Assassin HJOB_BABY_KNIGHT_2 = HJOB_BABY_OFFSET + JOB_KNIGHT_2; //4036 Baby Peco Knight HJOB_BABY_CRUSADER = HJOB_BABY_OFFSET + JOB_CRUSADER; //4037 Baby Cruaser HJOB_BABY_MONK = HJOB_BABY_OFFSET + JOB_MONK; //4038 Baby Monk HJOB_BABY_SAGE = HJOB_BABY_OFFSET + JOB_SAGE; //4039 Baby Sage HJOB_BABY_ROGUE = HJOB_BABY_OFFSET + JOB_ROGUE; //4040 Baby Rogue HJOB_BABY_ALCHEMIST = HJOB_BABY_OFFSET + JOB_ALCHEMIST; //4041 Baby Alchemist HJOB_BABY_BARD = HJOB_BABY_OFFSET + JOB_BARD; //4042 Baby Bard HJOB_BABY_DANCER = HJOB_BABY_OFFSET + JOB_DANCER; //4043 Baby Dancer HJOB_BABY_CRUSADER_2 = HJOB_BABY_OFFSET + JOB_CRUSADER_2; //4044 Mounted Baby Crusader(on peco) HJOB_BABY_SNOVICE = 4045; //Baby Super Novice //Expanded (4046+ Job classes) HJOB_EXPANDED_OFFSET = 4046; HJOB_EXPANDED_TAEKWON = HJOB_EXPANDED_OFFSET + JOB_NOVICE; //4046 Taekwon Boy/Girl HJOB_EXPANDED_STAR_GLADIATOR = HJOB_EXPANDED_OFFSET + JOB_SWORDMAN; //4047 Taekwon Master HJOB_EXPANDED_STAR_GLADIATOR_2 = HJOB_EXPANDED_OFFSET + JOB_MAGE; //4048 Taekwon Master(Flying) HJOB_EXPANDED_SOUL_LINKER = HJOB_EXPANDED_OFFSET + JOB_ARCHER; //4049 Soul Linker HJOB_MAX = 4049; MAX_FRIENDS = 40; NAME_LENGTH = 24; //Action types ACTION_ATTACK = $00; ACTION_PICKUP_ITEM = $01; ACTION_SIT = $02; ACTION_STAND = $03; ACTION_CONTINUE_ATTACK = $07; ACTION_MULTIHIT_ATTACK = $08; ACTION_ENDUREATTACK = $09; ACTION_CRITICAL_ATTACK = $0a; ACTION_PERFECT_DODGE = $0b; //Action constants - for AreaLoop event ShowAction ACTION_DO_ATTACK = 1; ACTION_DO_SIT = 2; ACTION_DO_STAND = 3; ACTION_DO_ATTACK_CONTINUOUS = 4; //Max Attack speed ASPEED_MAX = 199; //------------------------------------------------------------------------------ // Options //------------------------------------------------------------------------------ OPTION_NONE = 0; OPTION_CART = 1; OPTION_PECO_PECO = 2; OPTION_FALCON = 3; //------------------------------------------------------------------------------ // Mob Race //------------------------------------------------------------------------------ MOBRACE_FORMLESS = 0; MOBRACE_UNDEAD = 1; MOBRACE_BEAST = 2; MOBRACE_PLANT = 3; MOBRACE_INSECT = 4; MOBRACE_FISH = 5; MOBRACE_DEMON = 6; MOBRACE_DEMI_HUMAN = 7; MOBRACE_ANGEL = 8; MOBRACE_DRAGON = 9; MOBRACE_BOSS = 10; MOBRACE_NON_BOSS = 11; //------------------------------------------------------------------------------ // Mob Property //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Mob Scale //------------------------------------------------------------------------------ MOBSCALE_SMAL = 0; MOBSCALE_MEDIUM = 1; MOBSCALE_LARGE = 2; //------------------------------------------------------------------------------ // Script Constants //------------------------------------------------------------------------------ CHARAVAR_INTEGER = 0; CHARAVAR_STRING = 1; implementation end.
{******************************************************************************} {* frxMvxEditor.pas *} {* This module is part of Internal Project but is released under *} {* the MIT License: http://www.opensource.org/licenses/mit-license.php *} {* Copyright (c) 2006 by Jaimy Azle *} {* All rights reserved. *} {******************************************************************************} {* Desc: *} {******************************************************************************} unit frxMvxEditor; interface {$I frx.inc} implementation uses Windows, Classes, SysUtils, Forms, Controls, frxMvxComponents, frxCustomDB, frxDsgnIntf, frxRes, DB, MvxCon, frxEditMvxParams {$IFDEF Delphi6} , Variants {$ENDIF}; type TfrxMvxParamsProperty = class(TfrxClassProperty) public function GetAttributes: TfrxPropertyAttributes; override; function Edit: Boolean; override; end; TfrxDatabaseProperty = class(TfrxComponentProperty) public function GetValue: String; override; end; TfrxMIProgramProperty = class(TfrxStringProperty) public function GetAttributes: TfrxPropertyAttributes; override; procedure GetValues; override; procedure SetValue(const Value: String); override; end; TfrxMICommandProperty = class(TfrxStringProperty) public function GetAttributes: TfrxPropertyAttributes; override; procedure GetValues; override; procedure SetValue(const Value: String); override; end; { TfrxDatabaseProperty } function TfrxDatabaseProperty.GetValue: String; var db: TfrxMvxDatabase; begin db := TfrxMvxDatabase(GetOrdValue); if db = nil then begin if (MvxComponents <> nil) and (MvxComponents.DefaultDatabase <> nil) then Result := MvxComponents.DefaultDatabase.Name else Result := frxResources.Get('prNotAssigned'); end else Result := inherited GetValue; end; { TfrxMIProgramProperty } function TfrxMIProgramProperty.GetAttributes: TfrxPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList]; end; procedure TfrxMIProgramProperty.GetValues; begin inherited; with TfrxMvxDataset(Component).MvxDataset do if Connection <> nil then frxMvxGetMIProgramNames(Connection, Values); end; procedure TfrxMIProgramProperty.SetValue(const Value: String); begin inherited; Designer.UpdateDataTree; end; { TfrxMICommandProperty } function TfrxMICommandProperty.GetAttributes: TfrxPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList]; end; procedure TfrxMICommandProperty.GetValues; begin inherited; with TfrxMvxDataset(Component) do if MvxDataset <> nil then frxMvxGetMICommandNames(MvxDataset, Values); end; procedure TfrxMICommandProperty.SetValue(const Value: String); begin inherited; Designer.UpdateDataTree; end; { TfrxMvxParamsProperty } function TfrxMvxParamsProperty.Edit: Boolean; var q: TfrxMvxDataset; begin Result := False; q := TfrxMvxDataset(Component); if q.Params.Count <> 0 then with TfrxMvxParamsEditorForm.Create(Designer) do begin Params := q.Params; Result := ShowModal = mrOk; if Result then begin q.UpdateParams; Self.Designer.UpdateDataTree; end; Free; end; end; function TfrxMvxParamsProperty.GetAttributes: TfrxPropertyAttributes; begin Result := [paDialog, paReadOnly]; end; initialization frxPropertyEditors.Register(TypeInfo(TfrxMvxDatabase), TfrxMvxDataset, 'Database', TfrxDatabaseProperty); frxPropertyEditors.Register(TypeInfo(String), TfrxMvxDataset, 'MIProgram', TfrxMIProgramProperty); frxPropertyEditors.Register(TypeInfo(String), TfrxMvxDataset, 'MICommand', TfrxMICommandProperty); frxPropertyEditors.Register(TypeInfo(TfrxParams), TfrxMvxDataset, 'Params', TfrxMvxParamsProperty); end.
unit SpWorkModeEditDays_Edit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxMaskEdit, cxTextEdit, cxSpinEdit, cxTimeEdit, cxControls, cxContainer, cxEdit, cxLabel, ActnList, StdCtrls, cxButtons, ExtCtrls,TuCommonTypes,TuMessages,TuCommonProc,SpWorkModeEditDays_DM, cxCheckBox; type TTuModeDay = class(TObject) public Owner:TComponent; CFStyle:TTuControlFormStyle; Id_Work_Mode :Integer; Id_Day_Week :Integer; Work_Beg :TTime; Work_End :TTime; Break_Beg :TTime; Break_End :TTime; Today_Hours :Extended; Tomorrow_Hours:Extended; end; type TFormDayEdit = class(TForm) Panel1: TPanel; Panel2: TPanel; ButtonOK: TcxButton; ButtonCancel: TcxButton; ActionList: TActionList; ActionYes: TAction; ActionCancel: TAction; Label5: TcxLabel; Label4: TcxLabel; Label1: TcxLabel; Label2: TcxLabel; Label3: TcxLabel; EditNumDay: TcxSpinEdit; EditWorkBeg: TcxTimeEdit; EditWorkEnd: TcxTimeEdit; EditBreakBeg: TcxTimeEdit; EditBreakEnd: TcxTimeEdit; CheckBoxHoliday: TcxCheckBox; procedure ButtonOKClick(Sender: TObject); procedure ButtonCancelClick(Sender: TObject); procedure CheckBoxHolidayPropertiesChange(Sender: TObject); private { Private declarations } public Date: TTuModeDay; constructor Create(Param:TTuModeDay);reintroduce; end; function View_SpWorkModeEditDays(Param:TTuModeDay):Boolean; implementation uses pFIBQuery; //uses SysInit; {$R *.dfm} function View_SpWorkModeEditDays(Param:TTuModeDay):Boolean; var FormDayEdit :TFormDayEdit; Tm: TTime; begin Tm:=EncodeTime(0,0,0,0); if Param.CFStyle=tcfsDelete then begin if TuShowMessage(GetConst('Delete','Error'),GetConst('DeleteText','Error'), mtWarning, [mbYes,mbNo])=6 then begin DModule.StProc.Transaction.StartTransaction; DModule.StProc.StoredProcName:='DT_WORKREG_DELETE'; DModule.StProc.Prepare; DModule.StProc.ParamByName('ID_WORK_MODE').asinteger:=Param.Id_Work_Mode; DModule.StProc.ParamByName('ID_DAY_WEEK').asinteger :=Param.Id_Day_Week; DModule.StProc.ExecProc; DModule.StProc.Transaction.Commit; Result:=True; end else result:=False; Exit; end; FormDayEdit:=TFormDayEdit.Create(Param); if FormDayEdit.ShowModal=mrYes then with DModule.StProc do begin Transaction.StartTransaction; if Param.CFStyle=tcfsInsert then StoredProcName:='DT_WORKREG_INSERT' else StoredProcName:='DT_WORKREG_UPDATE'; Prepare; ParamByName('ID_DAY_WEEK').asinteger :=FormDayEdit.Date.Id_Day_Week; ParamByName('WORK_BEG').AsString :=TimeToStr( FormDayEdit.Date.Work_Beg); ParamByName('WORK_END').AsString :=TimeToStr(FormDayEdit.Date.Work_End); if (FormDayEdit.Date.Break_Beg<>FormDayEdit.Date.Break_End) then begin ParamByName('BREAK_BEG').AsString :=TimeToStr(FormDayEdit.Date.Break_Beg); ParamByName('BREAK_END').AsString :=TimeToStr(FormDayEdit.Date.Break_End); end else begin ParamByName('BREAK_BEG').AsVariant :=Null; ParamByName('BREAK_END').AsVariant :=Null; end; ParamByName('TODAY_HOURS').AsExtended :=FormDayEdit.Date.Today_Hours; ParamByName('TOMORROW_HOURS').AsExtended:=FormDayEdit.Date.Tomorrow_Hours; ParamByName('ID_WORK_MODE').Asinteger :=FormDayEdit.Date.Id_Work_Mode; ExecProc; Transaction.Commit; Result:=True; end else result:=false; end; constructor TFormDayEdit.Create(Param:TTuModeDay); begin inherited Create(Param.Owner); Date:=TTuModeDay.Create; Date:=Param; EditNumDay.Value :=Param.Id_Day_Week; if Param.CFStyle=tcfsUpdate then begin if (Param.Work_Beg=0) and (Param.Work_End=0) then begin CheckBoxHoliday.Checked:=True; CheckBoxHolidayPropertiesChange(self); end; EditWorkBeg.Time :=Param.Work_Beg; EditWorkEnd.Time :=Param.Work_End; EditBreakBeg.Time :=Param.Break_Beg; EditBreakEnd.Time :=Param.Break_End; end; if Param.CFStyle=tcfsUpdate then Caption :=GetConst('Update','Button')+'['+GetConst('TranscriptWorkMode','Form')+']' else Caption :=GetConst('Insert','Button')+'['+GetConst('TranscriptWorkMode','Form')+']'; Label1.Caption :=GetConst('Day','GridColumn')+':'; Label2.Caption :=GetConst('WorkBeg','GridColumn')+':'; Label3.Caption :=GetConst('WorkEnd','GridColumn')+':'; Label4.Caption :=GetConst('BreakBeg','GridColumn')+':'; Label5.Caption :=GetConst('BreakEnd','GridColumn')+':'; ButtonOK.Caption :=GetConst('Yes','Button'); ButtonCancel.Caption :=GetConst('Cancel','Button'); CheckBoxHoliday.Properties.Caption:=GetConst('Holiday','CheckBox'); end; procedure TFormDayEdit.ButtonOKClick(Sender: TObject); var //Tm:string; WorkHourBeg,WorkHourEnd, WorkMntBeg,WorkMntEnd, Sek, BreakHourBeg,BreakHourEnd, BreakMntBeg,BreakMntEnd, MSek:Word; Tm:TTime; WorkTime,TomorrowTime:Extended; begin if (EditNumDay.Text=null)or (EditWorkBeg.Text=null)or (EditWorkEnd.Text=null)or (EditBreakBeg.Text=null)or (EditBreakEnd.Text=null) then begin TuShowMessage(GetConst('Delete','Error'),GetConst('DeleteText','Error'), mtWarning, [mbOK]); Exit; end ; Date.Id_Day_Week :=EditNumDay.Value; if CheckBoxHoliday.Checked then begin Date.Work_Beg :=0; Date.Work_End :=0; Date.Break_Beg :=0; Date.Break_End :=0; end else begin Date.Work_Beg :=EditWorkBeg.Time; Date.Work_End :=EditWorkEnd.Time; Date.Break_Beg :=EditBreakBeg.Time; Date.Break_End :=EditBreakEnd.Time; end; //Из времени считаем количество рабочих часов до и после 24часов/////////////// DecodeTime(Date.Work_Beg, WorkHourBeg, WorkMntBeg, Sek,MSek); DecodeTime(Date.Work_End, WorkHourEnd, WorkMntEnd, Sek,MSek); DecodeTime(Date.Break_Beg,BreakHourBeg, BreakMntBeg,Sek,MSek); DecodeTime(Date.Break_End,BreakHourEnd, BreakMntEnd,Sek,MSek); if Date.Work_Beg>Date.Work_End then begin WorkTime:= (24-WorkHourBeg)+(60-WorkMntBeg+WorkMntEnd)/60-1; TomorrowTime:=WorkHourEnd+WorkMntEnd/60; if Date.Break_Beg>Date.Break_End then begin WorkTime:=WorkTime-(24-BreakHourBeg+(60-BreakMntBeg)/60-1); TomorrowTime:=TomorrowTime-(BreakHourEnd+BreakMntEnd/60); end else if (Date.Work_Beg<Date.Break_Beg)and(Date.Break_Beg<Date.Break_End) then WorkTime:=WorkTime-(BreakHourEnd-BreakHourBeg+(BreakMntEnd-BreakMntBeg)/60); if (Date.Work_End>Date.Break_End)and(Date.Break_End>Date.Break_Beg) then TomorrowTime:=TomorrowTime-(BreakHourEnd-BreakHourBeg+(BreakMntEnd-BreakMntBeg)/60); end else begin WorkTime:=(WorkHourEnd-WorkHourBeg)+(60-WorkMntBeg+WorkMntEnd)/60; WorkTime:=WorkTime-((BreakHourEnd-BreakHourBeg)+(60-BreakMntBeg+BreakMntEnd)/60); TomorrowTime:=0; end; //////////////////////////////////////////////////////////////////////////////// Date.Today_Hours:=WorkTime; Date.Tomorrow_Hours:=TomorrowTime; ModalResult:=mrYes; end; procedure TFormDayEdit.ButtonCancelClick(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TFormDayEdit.CheckBoxHolidayPropertiesChange(Sender: TObject); begin If CheckBoxHoliday.Checked then begin EditWorkBeg.Enabled:=False; EditWorkEnd.Enabled:=False; EditBreakBeg.Enabled:=False; EditBreakEnd.Enabled:=False; end else begin EditWorkBeg.Enabled:=true; EditWorkEnd.Enabled:=true; EditBreakBeg.Enabled:=true; EditBreakEnd.Enabled:=true; end end; end.
{..............................................................................} { Summary Deleting PCB Objects and Updating the Undo System } { The correct way to delete PCB Objects } { } { Copyright (c) 2006 by Altium Limited } { Version 1.1 The way tracks are removed are changed. } {..............................................................................} {..............................................................................} Procedure RemoveTracksOnTopLayer; var CurrentPCBBoard : IPCB_Board; Iterator : IPCB_BoardIterator; Track : IPCB_Track; TrackList : TInterfaceList; I : Integer; Begin CurrentPCBBoard := PCBServer.GetCurrentPCBBoard; If CurrentPCBBoard = Nil Then Exit; Iterator := CurrentPCBBoard.BoardIterator_Create; If Iterator = Nil Then Exit; Iterator.AddFilter_ObjectSet(MkSet(eTrackObject)); Iterator.AddFilter_LayerSet(MkSet(eTopLayer)); // Fetch the first track from the board. // If the first track is not found, the iteration process // is cancelled. // Tracks are stored in a TInterfacelist that are to be deleted later... TrackList := TInterfaceList.Create; Try Track := Iterator.FirstPCBObject; While Track <> Nil Do Begin TrackList.Add(Track); Track := Iterator.NextPCBObject; End; Finally CurrentPCBBoard.BoardIterator_Destroy(Iterator); End; // Remove objects from the board. // TInterfaceList object is updated automatically Try PCBServer.PreProcess; For I := 0 to TrackList.Count - 1 Do Begin Track := TrackList.items[i]; CurrentPCBBoard.RemovePCBObject(Track); End; Finally PCBServer.PostProcess; TrackList.Free; End; // Refresh the PCB document. CurrentPCBBoard.ViewManager_FullUpdate; Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView); End; {..................................................................................................} {..................................................................................................}
unit Lib.TCPSocket; interface uses System.SysUtils, System.Classes, Winapi.Windows, Winapi.Messages, Winapi.WinSock2, Lib.SSL; type TTCPSocket = class private FForceClose: Boolean; FOnDestroy: TNotifyEvent; FOnException: TNotifyEvent; FLocalAddress: string; FLocalPort: Integer; protected FSocket: TSocket; FAdIn: TSockAddrIn; FExceptionCode: Integer; FExceptionMessage: string; procedure DoExceptCode(Code: Integer); virtual; procedure DoExcept(Code: Integer); virtual; procedure DoEvent(EventCode: Word); virtual; abstract; procedure DoTimeout(Code: Integer); virtual; procedure StartEvents(EventCodes: Integer); procedure SetTimeout(Elapsed: Cardinal; Code: Integer); function Check(R: Integer): Boolean; procedure Close; virtual; procedure UpdateLocal; property OnDestroy: TNotifyEvent read FOnDestroy write FOnDestroy; public constructor Create; virtual; destructor Destroy; override; function ToString: string; override; property LocalAddress: string read FLocalAddress write FLocalAddress; property LocalPort: Integer read FLocalPort write FLocalPort; property ExceptionCode: Integer read FExceptionCode; property ExceptionMessage: string read FExceptionMessage; property OnException: TNotifyEvent read FOnException write FOnException; end; TTCPClient = class(TTCPSocket) private FSSL: TSSL; FOnOpen: TNotifyEvent; FOnClose: TNotifyEvent; FOnRead: TNotifyEvent; function GetUseSSL: Boolean; procedure SetUseSSL(Value: Boolean); protected procedure DoExceptCode(Code: Integer); override; procedure DoEvent(EventCode: Word); override; procedure DoOpen; virtual; procedure DoRead; virtual; procedure DoClose; virtual; procedure CheckConnect; public // function WaitForRead(WaitTime: Integer): Boolean; function ConnectTo(const Host: string; Port: Integer): Boolean; procedure Close; override; function ReadString(Encoding: TEncoding = nil): string; function ReadBuf(var Buffer; Count: Integer): Integer; function Read(MaxBuffSize: Integer=10240): TBytes; procedure WriteString(const S: string; Encoding: TEncoding = nil); procedure WriteBuf(var Buffer; Count: Integer); procedure Write(B: TBytes); constructor Create; override; procedure AcceptOn(S: TSocket); function SetKeepAlive(KeepAliveTime: Cardinal=1000; KeepAliveInterval: Cardinal=1000): Boolean; public CertCAFile: string; CertificateFile: string; PrivateKeyFile: string; KeyPassword: string; property UseSSL: Boolean read GetUseSSL write SetUseSSL; property OnOpen: TNotifyEvent read FOnOpen write FOnOpen; property OnRead: TNotifyEvent read FOnRead write FOnRead; property OnClose: TNotifyEvent read FOnClose write FOnClose; end; TTCPServer = class(TTCPSocket) private FAcceptRemoteHost: string; FAcceptRemotePort: Integer; FOnAccept: TNotifyevent; protected procedure DoEvent(EventCode: Word); override; procedure DoAccept; virtual; public procedure Start(const Host: string; Port: Integer); procedure Stop; function AcceptClient: TSocket; public property AcceptRemoteHost: string read FAcceptRemoteHost; property AcceptRemotePort: Integer read FAcceptRemotePort; property OnAccept: TNotifyEvent read FOnAccept write FOnAccept; end; implementation { Support socket messages } const CM_SOCKETMESSAGE = WM_USER + $0001; type TSocketManager = class strict private type TSocketMessage = record Msg: Cardinal; Socket: TSocket; SelectEvent: Word; SelectError: Word; Result: Longint; end; strict private FEventHandle: HWND; Sockets: TArray<TTCPSocket>; procedure WndMethod(var Message: TMessage); procedure CMSocketMessage(var Message: TSocketMessage); message CM_SOCKETMESSAGE; function IndexOf(TCPSocket: TTCPSocket): Integer; overload; function IndexOf(Socket: TSocket): Integer; overload; function Get(Socket: TSocket): TTCPSocket; function TryGet(Socket: TSocket; out TCPSocket: TTCPSocket): Boolean; strict private type TCleanData = record Socket: TSocket; CloseTime: Longint; end; strict private FCleanTimer: THandle; CleanSockets: TArray<TCleanData>; function GetCleanSocketIndex(Socket: TSocket): Integer; function TryGetCleanSocketIndex(Socket: TSocket; out I: Integer): Boolean; procedure RemoveCleanSocketByIndex(I: Integer); function GetFreeCleanIndex: Integer; private procedure AddCleanSocket(Socket: TSocket); procedure CloseCleanSocket(Socket: TSocket); procedure CloseCleanSockets(CloseTime: Longint); strict private type TTimerEvent = record TimerID: UIntPtr; EventCode: Integer; Socket: TTCPSocket; end; strict private TimerEvents: TArray<TTimerEvent>; procedure RemoveTimerEvent(I: Integer); overload; procedure RemoveTimerEvent(TCPSocket: TTCPSocket; Code: Integer); overload; procedure RemoveTimerEvents(TCPSocket: TTCPSocket); function GetEventIndexOf(TCPSocket: TTCPSocket; Code: Integer): Integer; overload; function GetEventIndexOf(TimerID: UIntPtr): Integer; overload; private procedure SetTimerEvent(TCPSocket: TTCPSocket; Code: Integer; Elapsed: Cardinal); procedure DoEvent(TimerID: UIntPtr); public constructor Create; destructor Destroy; override; procedure DefaultHandler(var Message); override; procedure Add(TCPSocket: TTCPSocket; EventCodes: Integer); procedure Remove(TCPSocket: TTCPSocket; Closed: Boolean); end; var SocketManager: TSocketManager; WSAData: TWSAData; constructor TSocketManager.Create; begin Sockets:=nil; CleanSockets:=nil; FCleanTimer:=0; FEventHandle:=AllocateHWnd(WndMethod); end; destructor TSocketManager.Destroy; begin DeallocateHWnd(FEventHandle); CloseCleanSockets(LongInt.MaxValue); end; procedure TSocketManager.DefaultHandler(var Message); begin with TMessage(Message) do Result:=CallWindowProc(@DefWindowProc,FEventHandle,Msg,wParam,lParam); end; procedure TSocketManager.WndMethod(var Message: TMessage); begin try Dispatch(Message); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self); end; end; procedure TSocketManager.CMSocketMessage(var Message: TSocketMessage); var TCPSocket: TTCPSocket; begin if Message.Socket>0 then //if Message.SelectError=0 then if TryGet(Message.Socket,TCPSocket) then begin if Message.SelectEvent=FD_CLOSE then TCPSocket.FForceClose:=True; TCPSocket.DoEvent(Message.SelectEvent); end else if Message.SelectEvent=FD_CLOSE then CloseCleanSocket(Message.Socket); end; function TSocketManager.IndexOf(TCPSocket: TTCPSocket): Integer; begin for Result:=0 to High(Sockets) do if Sockets[Result]=TCPSocket then Exit; Result:=-1; end; function TSocketManager.IndexOf(Socket: TSocket): Integer; begin for Result:=0 to High(Sockets) do if Sockets[Result].FSocket=Socket then Exit; Result:=-1; end; function TSocketManager.Get(Socket: TSocket): TTCPSocket; var I: Integer; begin I:=IndexOf(Socket); if I=-1 then Result:=nil else Result:=Sockets[I]; end; function TSocketManager.TryGet(Socket: TSocket; out TCPSocket: TTCPSocket): Boolean; begin TCPSocket:=Get(Socket); Result:=Assigned(TCPSocket); end; procedure TSocketManager.Add(TCPSocket: TTCPSocket; EventCodes: Integer); begin if TCPSocket.Check(WSAAsyncSelect(TCPSocket.FSocket,FEventHandle,CM_SOCKETMESSAGE,EventCodes)) then Sockets:=Sockets+[TCPSocket]; end; procedure TSocketManager.Remove(TCPSocket: TTCPSocket; Closed: Boolean); begin Delete(Sockets,IndexOf(TCPSocket),1); if not Closed then if WSAAsyncSelect(TCPSocket.FSocket,FEventHandle,0,0)<>-1 then AddCleanSocket(TCPSocket.FSocket); RemoveTimerEvents(TCPSocket); end; function TSocketManager.GetCleanSocketIndex(Socket: TSocket): Integer; begin if Socket>0 then for Result:=0 to High(CleanSockets) do if CleanSockets[Result].Socket=Socket then Exit; Result:=-1; end; function TSocketManager.TryGetCleanSocketIndex(Socket: TSocket; out I: Integer): Boolean; begin I:=GetCleanSocketIndex(Socket); Result:=I<>-1; end; procedure TSocketManager.RemoveCleanSocketByIndex(I: Integer); var C: TSocket; begin C:=CleanSockets[I].Socket; CleanSockets[I].Socket:=0; if C>0 then if closesocket(C)=-1 then raise Exception.Create(SysErrorMessage(WSAGetLastError)); end; procedure TSocketManager.CloseCleanSockets(CloseTime: Longint); var I: Integer; Clean: Boolean; begin Clean:=False; for I:=0 to High(CleanSockets) do if CleanSockets[I].Socket>0 then if CleanSockets[I].CloseTime<CloseTime then RemoveCleanSocketByIndex(I) else Clean:=True; if not Clean then if FCleanTimer>0 then begin KillTimer(0,FCleanTimer); FCleanTimer:=0; end; end; procedure TSocketManager.CloseCleanSocket(Socket: TSocket); var I: Integer; begin if TryGetCleanSocketIndex(Socket,I) then RemoveCleanSocketByIndex(I); end; function TSocketManager.GetFreeCleanIndex: Integer; begin for Result:=0 to High(CleanSockets) do if CleanSockets[Result].Socket=0 then Exit; Result:=Length(CleanSockets); SetLength(CleanSockets,Result+1); end; procedure CleanSocketTimerProc(WND: hwnd; Msg: Longint; idEvent: UINT; dwTime: Longint); stdcall; begin SocketManager.CloseCleanSockets(dwTime); end; procedure TSocketManager.AddCleanSocket(Socket: TSocket); var I: Integer; begin if Socket>0 then begin I:=GetFreeCleanIndex; CleanSockets[I].Socket:=Socket; CleanSockets[I].CloseTime:=TThread.GetTickCount+2000; if FCleanTimer=0 then FCleanTimer:=SetTimer(0,0,2000,@CleanSocketTimerProc); end; end; procedure TSocketManager.DoEvent(TimerID: UIntPtr); var I: Integer; begin I:=GetEventIndexOf(TimerID); if I<>-1 then try TimerEvents[I].Socket.DoTimeout(TimerEvents[I].EventCode); finally I:=GetEventIndexOf(TimerID); if I<>-1 then RemoveTimerEvent(I); end; end; function TSocketManager.GetEventIndexOf(TCPSocket: TTCPSocket; Code: Integer): Integer; begin for Result:=0 to High(TimerEvents) do if (TimerEvents[Result].Socket=TCPSocket) and (TimerEvents[Result].EventCode=Code) then Exit; Result:=-1; end; function TSocketManager.GetEventIndexOf(TimerID: UIntPtr): Integer; begin for Result:=0 to High(TimerEvents) do if TimerEvents[Result].TimerID=TimerID then Exit; Result:=-1; end; procedure EventsTimerProc(WND: hwnd; Msg: Longint; idEvent: UINT; dwTime: Longint); stdcall; begin SocketManager.DoEvent(idEvent); end; procedure TSocketManager.SetTimerEvent(TCPSocket: TTCPSocket; Code: Integer; Elapsed: Cardinal); var Event: TTimerEvent; begin RemoveTimerEvent(TCPSocket,Code); if Elapsed>0 then begin Event.EventCode:=Code; Event.Socket:=TCPSocket; Event.TimerID:=SetTimer(0,0,Elapsed,@EventsTimerProc); TimerEvents:=TimerEvents+[Event]; end; end; procedure TSocketManager.RemoveTimerEvent(I: Integer); begin KillTimer(0,TimerEvents[I].TimerID); Delete(TimerEvents,I,1); end; procedure TSocketManager.RemoveTimerEvent(TCPSocket: TTCPSocket; Code: Integer); var I: Integer; begin I:=GetEventIndexOf(TCPSocket,Code); if I<>-1 then RemoveTimerEvent(I); end; procedure TSocketManager.RemoveTimerEvents(TCPSocket: TTCPSocket); var I: Integer; begin I:=0; while I<Length(TimerEvents) do if TimerEvents[I].Socket=TCPSocket then RemoveTimerEvent(I) else Inc(I); end; { Utilities } function host_isip(const Host: string): Boolean; begin case inet_addr(PAnsiChar(AnsiString(Host))) of INADDR_NONE,0: Result:=False; else Result:=Length(Host.Split(['.']))=4; end; end; function host_ipfromname(const Name: string): string; var H: PHostEnt; begin H:=gethostbyname(PAnsiChar(AnsiString(Name))); if H=nil then Result:='0.0.0.1' else Result:=inet_ntoa(PInAddr(H^.h_addr_list^)^); end; procedure sock_addr_iptoinaddr(const IP: string; var InAddr: TInAddr); var Octets: TArray<string>; begin Octets:=IP.Split(['.']); if Length(Octets)<>4 then Octets:='0.0.0.1'.Split(['.']); InAddr.s_un_b.s_b1:=StrToInt(Octets[0]); InAddr.s_un_b.s_b2:=StrToInt(Octets[1]); InAddr.s_un_b.s_b3:=StrToInt(Octets[2]); InAddr.s_un_b.s_b4:=StrToInt(Octets[3]); end; { TTCPSocket } constructor TTCPSocket.Create; begin FSocket:=0; end; destructor TTCPSocket.Destroy; begin Close; if Assigned(FOnDestroy) then FOnDestroy(Self); inherited; end; function TTCPSocket.ToString: string; begin Result:=inherited+'('+FSocket.ToString+')'; end; procedure TTCPSocket.Close; begin if FSocket<1 then Exit; shutdown(FSocket,1); if FForceClose then closesocket(FSocket); SocketManager.Remove(Self,FForceClose); FSocket:=0; end; procedure TTCPSocket.UpdateLocal; var SockAddrIn: TSockAddrIn; Size: Integer; begin Size:=SizeOf(SockAddrIn); if getsockname(FSocket,TSockAddr(SockAddrIn),Size)=0 then begin FLocalAddress:=string(inet_ntoa(SockAddrIn.sin_addr)); FLocalPort:=ntohs(SockAddrIn.sin_port); end; end; procedure TTCPSocket.DoExceptCode(Code: Integer); begin FExceptionCode:=Code; FExceptionMessage:=SysErrorMessage(Code); end; procedure TTCPSocket.DoExcept(Code: Integer); begin DoExceptCode(Code); FForceClose:=True; Close; if Assigned(FOnException) then FOnException(Self); end; procedure TTCPSocket.DoTimeout(Code: Integer); begin end; function TTCPSocket.Check(R: Integer): Boolean; begin if R=-1 then DoExcept(WSAGetLastError); Result:=R<>-1; end; procedure TTCPSocket.StartEvents(EventCodes: Integer); begin SocketManager.Add(Self,EventCodes); end; procedure TTCPSocket.SetTimeout(Elapsed: Cardinal; Code: Integer); begin SocketManager.SetTimerEvent(Self,Code,Elapsed); end; { TTCPClient } procedure TTCPClient.Close; begin UseSSL:=False; inherited; end; function TTCPClient.GetUseSSL: Boolean; begin Result:=Assigned(FSSL); end; procedure TTCPClient.SetUseSSL(Value: Boolean); begin if Value<>UseSSL then if Value then FSSL:=TSSL.Create else FreeAndNil(FSSL); end; procedure TTCPClient.DoExceptCode(Code: Integer); begin if UseSSL and (FSSL.ErrorCode=Code) then begin FExceptionCode:=FSSL.ErrorCode; FExceptionMessage:=FSSL.ErrorText; end else inherited; end; constructor TTCPClient.Create; begin inherited; FSSL:=nil; end; procedure TTCPClient.AcceptOn(S: TSocket); begin FSocket:=S; FForceClose:=False; DoOpen; UpdateLocal; if UseSSL then begin FSSL.CertCAFile:=CertCAFile; FSSL.CertificateFile:=CertificateFile; FSSL.PrivateKeyFile:=PrivateKeyFile; FSSL.KeyPassword:=KeyPassword; FSSL.Verify:=CertificateFile<>''; if not fSSL.accept(FSocket) then begin DoExcept(fssl.ErrorCode); DoClose; Exit; end; end; StartEvents(FD_READ or FD_CLOSE); end; function TTCPClient.ConnectTo(const Host: string; Port: Integer): Boolean; var R: Integer; IP: string; begin Result:=False; FForceClose:=True; FSocket:=socket(2,1,0); IP:=Host; if not host_isip(IP) then IP:=host_ipfromname(Host); sock_addr_iptoinaddr(IP,FAdIn.sin_addr); FAdIn.sin_family:=2; FAdIn.sin_port:=htons(Port); R:=connect(FSocket,TSockAddr(FAdIn),SizeOf(TSockAddr)); if R<>-1 then Result:=True else if WSAGetLastError<>WSAEWOULDBLOCK then Check(R); if Result then begin FForceClose:=False; DoOpen; UpdateLocal; if UseSSL then begin FSSL.CertCAFile:=CertCAFile; FSSL.CertificateFile:=CertificateFile; FSSL.PrivateKeyFile:=PrivateKeyFile; FSSL.KeyPassword:=KeyPassword; FSSL.Verify:=CertificateFile<>''; if not fssl.connect(FSocket) then begin DoExcept(fssl.ErrorCode); DoClose; Exit(False); end; end; StartEvents(FD_READ or FD_CLOSE); end; end; procedure TTCPClient.DoOpen; begin if Assigned(FOnOpen) then FOnOpen(Self); end; procedure TTCPClient.DoRead; begin if Assigned(FOnRead) then FOnRead(Self); end; procedure TTCPClient.DoClose; begin // Close; if Assigned(FOnClose) then FOnClose(Self); end; procedure TTCPClient.DoEvent(EventCode: Word); begin if EventCode=FD_READ then DoRead; if EventCode=FD_CLOSE then DoClose; end; //function TTCPClient.WaitForRead(WaitTime: Integer): Boolean; //var // FDSet: TFDSet; // TimeVal: TTimeVal; //begin // FD_ZERO(FDSet); // FDSet.fd_array[0]:=FSocket; // FDSet.fd_count:=1; // TimeVal.tv_sec:=WaitTime div 1000; // TimeVal.tv_usec:=WaitTime mod 1000; // Result:=select(0,@FDSet,nil,nil,@TimeVal)>0; //end; procedure TTCPClient.CheckConnect; begin if FSocket=0 then DoExcept(10057); end; function TTCPClient.ReadBuf(var Buffer; Count: Integer): Integer; begin //CheckConnect; if UseSSL then Result:=fSSL.recv(Buffer,Count) else Result:=recv(FSocket,Pointer(Buffer)^,Count,0); if Result=-1 then Result:=0; end; function TTCPClient.Read(MaxBuffSize: Integer=10240): TBytes; begin SetLength(Result,MaxBuffSize); SetLength(Result,ReadBuf(Result,Length(Result))); end; function TTCPClient.ReadString(Encoding: TEncoding = nil): string; begin if Encoding=nil then Result:=TEncoding.Default.GetString(Read) else Result:=Encoding.GetString(Read); end; procedure TTCPClient.WriteBuf(var Buffer; Count: Integer); var I,LE: Integer; begin CheckConnect; while True do begin if UseSSL then I:=fSSL.send(Buffer,Count) else I:=send(FSocket,Pointer(Buffer)^,Count,0); if I=-1 then begin LE:=WSAGetLastError; if LE<>WSAEWOULDBLOCK then Break; end else Break; end; if I=-1 then DoExcept(LE); //Check(I); end; procedure TTCPClient.Write(B: TBytes); begin WriteBuf(B,Length(B)); end; procedure TTCPClient.WriteString(const S: string; Encoding: TEncoding = nil); begin if Encoding=nil then Write(TEncoding.Default.GetBytes(S)) else Write(Encoding.GetBytes(S)); end; const SIO_KEEPALIVE_VALS=(IOC_IN or IOC_VENDOR or 4); type tcp_keepalive = record onoff: u_long; keepalivetime: u_long; keepaliveinterval: u_long; end; function TTCPClient.SetKeepAlive(KeepAliveTime: Cardinal; KeepAliveInterval: Cardinal): Boolean; var ka: tcp_keepalive; Bytes: Cardinal; begin ka.onoff:=1; ka.keepalivetime:=KeepAliveTime; ka.keepaliveinterval:=KeepAliveInterval; Result:=WSAIoctl(FSocket,SIO_KEEPALIVE_VALS,@ka,SizeOf(ka),nil,0,Bytes,nil,nil)=0; end; { TTCPServer } procedure TTCPServer.DoAccept; begin if Assigned(FOnAccept) then FOnAccept(Self); end; procedure TTCPServer.DoEvent(EventCode: Word); begin if EventCode=FD_ACCEPT then DoAccept; end; procedure TTCPServer.Start(const Host: string; Port: Integer); var IP: string; P: PHostEnt; Buf: array [0..127] of Char; s: string; begin FLocalAddress:=''; if gethostname(@Buf,128)=0 then begin P:=gethostbyname(@Buf); if P<>nil then FLocalAddress:=inet_ntoa(PInAddr(p^.h_addr_list^)^); end; FLocalPort:=Port; FForceClose:=True; FSocket:=socket(2,1,0); FAdIn:=Default(TSockAddrIn); if Host<>'' then begin IP:=Host; if not host_isip(IP) then IP:=host_ipfromname(IP); sock_addr_iptoinaddr(IP,FAdIn.sin_addr); end; FAdIn.sin_family:=2; FAdIn.sin_port:=htons(Port); Check(bind(FSocket,TSockAddr(FAdIn),SizeOf(TSockAddr))); Check(listen(FSocket,1)); StartEvents(FD_ACCEPT); end; procedure TTCPServer.Stop; begin Close; end; function TTCPServer.AcceptClient: TSocket; var SockAddr: TSockAddrIn; SockAddrLenght: Integer; begin SockAddrLenght:=SizeOf(SockAddr); SockAddr:=Default(TSockAddrIn); Result:=accept(FSocket,@SockAddr,@SockAddrLenght); FAcceptRemoteHost:=inet_ntoa(SockAddr.sin_addr); FAcceptRemotePort:=ntohs(SockAddr.sin_port); end; initialization SocketManager:=TSocketManager.Create; WSAStartup($202,WSAData); finalization SocketManager.Free; end.
{=============================================================================== RadiantMediaPlayerForm Unit Radiant Shapes - Demo Source Unit Copyright © 2012-2014 by Raize Software, Inc. All Rights Reserved. Modification History ------------------------------------------------------------------------------ 1.0 (29 Oct 2014) * Initial release. ===============================================================================} unit RadiantMediaPlayerForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Controls.Presentation, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Media, FMX.Objects, FMX.Layouts, FMX.Effects, Radiant.Shapes; type TfrmMediaPlayer = class(TForm) MediaPlayerControl1: TMediaPlayerControl; MediaPlayer1: TMediaPlayer; lytFastForward: TLayout; FastForwardChevron1: TRadiantChevron; FastForwardChevron2: TRadiantChevron; lytRewind: TLayout; RewindChevron1: TRadiantChevron; RewindChevron2: TRadiantChevron; PlayTriangle: TRadiantTriangle; lytPlay: TLayout; lytEjectOpen: TLayout; EjectOpenRectangle: TRadiantRectangle; EjectOpenTriangle: TRadiantTriangle; lytPower: TLayout; PowerRectangle: TRadiantRectangle; PowerSector: TRadiantSector; lytPause: TLayout; PauseRectangle1: TRadiantRectangle; PauseRectangle2: TRadiantRectangle; PauseGlowEffect: TGlowEffect; ConfigureGear: TRadiantGear; trkMediaPlayer: TTrackBar; lytFullScreen: TLayout; FullScreenGlowEffect: TGlowEffect; FullScreenFrame: TRadiantFrame; FullScreenArrow: TRadiantArrow; lytConfigure: TLayout; lytControlPanel: TLayout; lytButtons: TLayout; lytButtonsRight: TLayout; lytPlayback: TLayout; tmrPlayback: TTimer; dlgOpen: TOpenDialog; lytButtonsLeft: TLayout; trkVolume: TTrackBar; lytStop: TLayout; StopSquare: TRadiantSquare; RadiantRectangle1: TRadiantRectangle; FastForwardGlowEffect: TGlowEffect; ConfigureGlowEffect: TGlowEffect; EjectOpenGlowEffect: TGlowEffect; PowerGlowEffect: TGlowEffect; PlayGlowEffect: TGlowEffect; RewindGlowEffect: TGlowEffect; StopGlowEffect: TGlowEffect; StyleBook1: TStyleBook; procedure lytEjectOpenClick(Sender: TObject); procedure lytPlayClick(Sender: TObject); procedure lytPauseClick(Sender: TObject); procedure lytFullScreenClick(Sender: TObject); procedure lytConfigureClick(Sender: TObject); procedure lytPowerClick(Sender: TObject); procedure lytStopClick(Sender: TObject); procedure trkVolumeChange(Sender: TObject); procedure trkMediaPlayerChange(Sender: TObject); procedure tmrPlaybackTimer(Sender: TObject); procedure lytFastForwardClick(Sender: TObject); procedure lytRewindClick(Sender: TObject); procedure ButtonMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure ButtonMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure ButtonMouseLeave(Sender: TObject); procedure FormCreate(Sender: TObject); private FFileName: string; FVideoLoaded: Boolean; FButtonColor: TAlphaColor; FHighlightColor: TAlphaColor; procedure UpdateButtonStates; procedure AnimateButtonDown( Control: TControl ); procedure AnimateButtonUp( Control: TControl ); procedure UpdateButtonColors; public end; var frmMediaPlayer: TfrmMediaPlayer; implementation {$R *.fmx} uses FMX.Ani, RadiantMediaPlayerConfigForm; {=============================} {== TfrmMediaPlayer Methods ==} {=============================} procedure TfrmMediaPlayer.FormCreate(Sender: TObject); begin FButtonColor := $FF35C9FD; FHighlightColor := $FFBCF1FF; UpdateButtonColors; end; procedure TfrmMediaPlayer.lytEjectOpenClick(Sender: TObject); begin dlgOpen.Filter := TMediaCodecManager.GetFilterString; if dlgOpen.Execute then begin FFileName := dlgOpen.FileName; MediaPlayer1.FileName := dlgOpen.FileName; FVideoLoaded := True; UpdateButtonStates; if MediaPlayer1.Media <> nil then begin // Label1.Text := IntToStr( MediaPlayer1.Media.VideoSize.Truncate.X ) + 'x' + IntToStr( MediaPlayer1.Media.VideoSize.Truncate.Y ) + 'px ' + // IntToStr( MediaPlayer1.Media.Duration div MediaTimeScale ) + 'ms'; trkMediaPlayer.Max := MediaPlayer1.Media.Duration; trkVolume.Max := MediaPlayer1.Media.Volume; trkVolume.Value := MediaPlayer1.Media.Volume; end; end; end; procedure TfrmMediaPlayer.lytPlayClick(Sender: TObject); begin MediaPlayer1.Play; tmrPlayback.Enabled := True; UpdateButtonStates; end; procedure TfrmMediaPlayer.lytPauseClick(Sender: TObject); begin MediaPlayer1.Stop; tmrPlayback.Enabled := False; UpdateButtonStates; end; procedure TfrmMediaPlayer.lytFastForwardClick(Sender: TObject); begin trkMediaPlayer.Value := trkMediaPlayer.Value + ( trkMediaPlayer.Max / 20 ); end; procedure TfrmMediaPlayer.lytRewindClick(Sender: TObject); begin trkMediaPlayer.Value := trkMediaPlayer.Value - ( trkMediaPlayer.Max / 20 ); end; procedure TfrmMediaPlayer.lytStopClick(Sender: TObject); begin MediaPlayer1.Clear; tmrPlayback.Enabled := False; UpdateButtonStates; end; procedure TfrmMediaPlayer.UpdateButtonStates; var VideoPlaying: Boolean; begin VideoPlaying := MediaPlayer1.State = TMediaState.Playing; lytPlay.Enabled := FVideoLoaded; lytPause.Visible := VideoPlaying; lytPlay.Visible := not VideoPlaying; lytRewind.Enabled := VideoPlaying; lytFastForward.Enabled := VideoPlaying; lytStop.Enabled := VideoPlaying; end; procedure TfrmMediaPlayer.lytFullScreenClick(Sender: TObject); begin if WindowState <> TWindowState.wsMaximized then begin WindowState := TWindowState.wsMaximized; FullScreenArrow.RotationAngle := 225; FullScreenArrow.Position.X := 2; FullScreenArrow.Position.Y := 6; end else begin WindowState := TWindowState.wsNormal; FullScreenArrow.RotationAngle := 45; FullScreenArrow.Position.X := 10; FullScreenArrow.Position.Y := 2; end; end; procedure TfrmMediaPlayer.lytConfigureClick(Sender: TObject); begin frmConfiguration.cbxButtonColor.Color := FButtonColor; frmConfiguration.cbxHighlightColor.Color := FHighlightColor; if frmConfiguration.ShowModal = mrOK then begin FButtonColor := frmConfiguration.SelectedButtonColor; FHighlightColor := frmConfiguration.SelectedHighlightColor; UpdateButtonColors; end; end; procedure TfrmMediaPlayer.lytPowerClick(Sender: TObject); begin Close; end; procedure TfrmMediaPlayer.trkMediaPlayerChange(Sender: TObject); begin if trkMediaPlayer.Tag = 0 then begin MediaPlayer1.CurrentTime := Round( trkMediaPlayer.Value ); end; end; procedure TfrmMediaPlayer.trkVolumeChange(Sender: TObject); begin MediaPlayer1.Volume := trkVolume.Value; end; procedure TfrmMediaPlayer.tmrPlaybackTimer(Sender: TObject); begin trkMediaPlayer.Tag := 1; trkMediaPlayer.Value := MediaPlayer1.CurrentTime; trkMediaPlayer.Tag := 0; if trkMediaPlayer.Value = trkMediaPlayer.Max then begin MediaPlayer1.Stop; tmrPlayback.Enabled := False; UpdateButtonStates; end; end; procedure TfrmMediaPlayer.AnimateButtonDown( Control: TControl ); begin // TAnimator.AnimateFloat( Control, 'Opacity', 0.2, 0.1 ); {$WARN SYMBOL_DEPRECATED OFF} // Control.AnimateFloat was deprecated in XE7, but XE6 does not have TAnimator.AnimateFloat.. Control.AnimateFloat( 'Opacity', 0.2, 0.1 ); {$WARN SYMBOL_DEPRECATED ON} end; procedure TfrmMediaPlayer.AnimateButtonUp( Control: TControl ); begin // TAnimator.AnimateFloat( Control, 'Opacity', 1.0, 0.1 ); {$WARN SYMBOL_DEPRECATED OFF} // Control.AnimateFloat was deprecated in XE7, but XE6 does not have TAnimator.AnimateFloat.. Control.AnimateFloat( 'Opacity', 1.0, 0.1 ); {$WARN SYMBOL_DEPRECATED ON} end; procedure TfrmMediaPlayer.ButtonMouseDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single ); begin AnimateButtonDown( Sender as TControl ); end; procedure TfrmMediaPlayer.ButtonMouseUp( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single ); begin AnimateButtonUp( Sender as TControl ); end; procedure TfrmMediaPlayer.ButtonMouseLeave(Sender: TObject); begin ( Sender as TControl ).Opacity := 1.0; end; procedure TfrmMediaPlayer.UpdateButtonColors; var SectorRing: TRadiantSectorRing; Marker: TRadiantMarker; GlowEffect: TGlowEffect; begin // EjectOpen EjectOpenGlowEffect.GlowColor := FHighlightColor; EjectOpenRectangle.Fill.Color := FButtonColor; EjectOpenTriangle.Fill.Color := FButtonColor; // Power PowerGlowEffect.GlowColor := FHighlightColor; PowerRectangle.Fill.Color := FButtonColor; PowerSector.Fill.Color := FButtonColor; // Stop StopGlowEffect.GlowColor := FHighlightColor; StopSquare.Fill.Color := FButtonColor; // Rewind RewindGlowEffect.GlowColor := FHighlightColor; RewindChevron1.Fill.Color := FButtonColor; RewindChevron2.Fill.Color := FButtonColor; // Play PlayGlowEffect.GlowColor := FHighlightColor; PlayTriangle.Fill.Color := FButtonColor; // Pause PauseGlowEffect.GlowColor := FHighlightColor; PauseRectangle1.Fill.Color := FButtonColor; PauseRectangle2.Fill.Color := FButtonColor; // FastForward FastForwardGlowEffect.GlowColor := FHighlightColor; FastForwardChevron1.Fill.Color := FButtonColor; FastForwardChevron2.Fill.Color := FButtonColor; // Volume SectorRing := StyleBook1.Style.FindStyleResource( 'radiantsectorring1' ) as TRadiantSectorRing; if SectorRing <> nil then begin SectorRing.Fill.Color := FButtonColor; GlowEffect := SectorRing.FindStyleResource( 'SectorRingGlowEffect' ) as TGlowEffect; if GlowEffect <> nil then GlowEffect.GlowColor := FHighlightColor; end; // By resetting the StyleLookup, the updated style will get re-applied to the control trkVolume.StyleLookup := 'trkVolumeStyle1'; // FullScreen FullScreenGlowEffect.GlowColor := FHighlightColor; FullScreenFrame.Fill.Color := FButtonColor; FullScreenArrow.Fill.Color := FButtonColor; // Configure ConfigureGlowEffect.GlowColor := FHighlightColor; ConfigureGear.Fill.Color := FButtonColor; // Playback Marker := StyleBook1.Style.FindStyleResource( 'radiantmarker1' ) as TRadiantMarker; if Marker <> nil then begin Marker.Fill.Color := FButtonColor; GlowEffect := Marker.FindStyleResource( 'MarkerGlowEffect' ) as TGlowEffect; if GlowEffect <> nil then GlowEffect.GlowColor := FHighlightColor; end; // By resetting the StyleLookup, the updated style will get re-applied to the control trkMediaPlayer.StyleLookup := 'trkMediaPlayerStyle1'; end; end.
unit TesteProjeto; interface uses DUnitX.TestFramework, Calculadora; type [TestFixture] TTesteProjeto = class(TObject) private FCalculadora : TCalculadora; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] [TestCase('TestA','1,2,3')] [TestCase('TestB','3,2,5')] procedure Test2(const AValue1 : Integer;const AValue2 : Integer; const aValue3 : Integer); end; implementation procedure TTesteProjeto.Setup; begin FCalculadora := TCalculadora.Create; end; procedure TTesteProjeto.TearDown; begin FCalculadora.Free; end; procedure TTesteProjeto.Test2(const AValue1 : Integer;const AValue2 : Integer; const aValue3 : Integer); var a : Integer; begin a := FCalculadora.Add(aValue1,aValue2); if a=avalue3 then Assert.Pass('Passou') else Assert.Fail('Falhou'); end; initialization TDUnitX.RegisterTestFixture(TTesteProjeto); end.
// Author: Ivan Polyacov (ivan@games4win.com) // Copyright (C) Apus Software, 2002-2003, All rights reserved. www.apus-software.com { There are 2 interfaces there: procedural and class-based. First does not aware about multithreading issues. Use it only if you are sure that you have no concurrent access to ControlFiles from different threads (or you have your own thread-safe shell interface). Class interfae is thread-safe, use one class instance per thread. IMPORTANT: all data is stored as global for this unit. Multiple instances of unit (for example, in plugins or DLL) can lead to dual data representation and thus - data loss. Do not use } {$H+,R-} unit ControlFiles2; interface type TFileMode=(fmBinary, // Binary files fmText, // Textual files fmDefault); // As-is ctlKeyTypes=(cktNone, cktBool, cktInteger, cktReal, cktString, cktArray, cktSection); // Interface class for working with ControlFiles2 unit TControlFile=class path:string; // Key names can be relative constructor Create(fname,password:string); // Create object and load specified file procedure Save; // Save control file destructor Destroy; override; // Free object // Query methods function KeyExists(key:String):Boolean; function GetKeyType(key:String):ctlKeyTypes; // Read methods function GetBool(key:string):boolean; overload; function GetInt(key:string):integer; overload; function GetReal(key:string):double; overload; function GetStr(key:string):string; overload; function GetStrInd(key:String;index:Integer):String; function GetStrCnt(key:String):Integer; function GetKeys(key:string):String; function GetBool(key:string;default:boolean):boolean; overload; function GetInt(key:string;default:integer):integer; overload; function GetReal(key:string;default:double):double; overload; function GetStr(key:string;default:string):string; overload; // Write methods procedure CreateSection(key:string); // Create section with given path procedure SetBool(key:string;value:boolean); procedure SetInt(key:string;value:integer); procedure SetReal(key:string;value:double); procedure SetStr(key:string;value:string); procedure SetStrInd(key:String;index:Integer;value:string); procedure SetStrCnt(key:String;count:integer); procedure AddStr(key:String;newvalue:string); // Delete procedure DeleteKey(key:string); private handle:integer; function GetAbsPath(key:string):string; end; // Load specified control file (and all linked files), return its handle function UseControlFile(filename:string;password:string=''):integer; // Save control file (and all linked files), specified by its handle procedure SaveControlFile(handle:integer;mode:TFileMode=fmDefault); // Save all (modified) control files procedure SaveAllControlFiles; // Free control file (release it's memory) procedure FreeControlFile(handle:integer); // Query functions function IsKeyExists(key:String):Boolean; function ctlGetKeyType(key:String):ctlKeyTypes; // Read functions function ctlGetBool(key:string):boolean; overload; function ctlGetBool(key:string;default:boolean):boolean; overload; function ctlGetInt(key:string):integer; overload; function ctlGetInt(key:string;default:integer):integer; overload; function ctlGetReal(key:string):double; overload; function ctlGetReal(key:string;default:double):double; overload; function ctlGetStr(key:string):string; overload; function ctlGetStr(key:string;default:string):string; overload; function ctlGetStrInd(key:String;index:Integer):String; function ctlGetStrCnt(key:String):Integer; function ctlGetKeys(key:string):String; // Write functions procedure ctlCreateSection(key:string); // Create section with given path procedure ctlSetBool(key:string;value:boolean); procedure ctlSetInt(key:string;value:integer); procedure ctlSetReal(key:string;value:double); procedure ctlSetStr(key:string;value:string); procedure ctlSetStrInd(key:String;index:Integer;value:string); procedure ctlSetStrCnt(key:String;count:integer); procedure ctlAddStr(key:String;newvalue:string); procedure ctlDeleteKey(key:string); implementation uses MyServis,classes,SysUtils,StrUtils,contnrs,hashes,structs,crypto; type // комментарий TCommentLine=class line:string; end; TInclude=class handle:integer; include:string; destructor Destroy; override; end; // Базовый класс для именованых элементов TNamedValue=class name:string; // item's name fullname:string; // full item name (including path), uppercase (for hash) constructor Create; virtual; destructor Destroy; override; procedure MarkFileAsChanged; virtual; end; TIntValue=class(TNamedValue) private v,v2,c:integer; function GetIntValue:integer; procedure SetIntValue(data:integer); protected constructor Create; override; property value:integer read GetIntValue write SetIntValue; end; TFloatValue=class(TNamedValue) private v:double; c:integer; function GetFloatValue:double; procedure SetFloatValue(data:double); protected constructor Create; override; property value:double read GetFloatValue write SetFloatValue; end; TBoolValue=class(TNamedValue) private v,v2,c:boolean; function GetBoolValue:boolean; procedure SetBoolValue(data:boolean); protected constructor Create; override; property value:boolean read GetBoolValue write SetBoolValue; end; TStringValue=class(TNamedValue) private st:string; key:integer; function GetStrValue:string; procedure SetStrValue(data:string); protected constructor Create; override; property value:string read GetStrValue write SetStrValue; end; TStringListValue=class(TNamedValue) private strings:array of string; key:integer; function GetStrValue(index:integer):string; procedure SetStrValue(index:integer;data:string); function GetCount:integer; protected constructor Create; override; procedure Allocate(count:integer); property count:integer read GetCount write Allocate; property value[index:integer]:string read GetStrValue write SetStrValue; end; TSection=class(TNamedValue) end; TCtlFile=class(TSection) fname:string; modified:boolean; curmode:TFileMode; handle:integer; RefCounter:integer; code:cardinal; // encryption code constructor Create(filename:string;filemode:TFileMode); // procedure Free; end; TNamedValueClass=class of TNamedValue; TBinaryHeader=packed record sign1,sign2:cardinal; data:array[0..23] of byte; end; const itComment = 1; itInclude = 2; itSection = 3; itBool = 10; itInt = 11; itFloat = 12; itStr = 13; itStrList = 14; var // Все загруженные данные хранятся в одном дереве // Элементы 1-го уровня - файлы items:TGenericTree; // Хэш для быстрого доступа к именованным элементам дерева (кроме файлов) hash:TStrHash; lasthandle:integer=0; CritSect:TMyCriticalSection; // синхронизация для много поточного доступа //----------------- Copypasted from QStrings.pas since it can't be compiled by FPC type PLong = ^LongWord; { Функции для работы с символьной записью чисел. } function Q_StrToInt64(const S: string; var V: Int64): Boolean; type PArr64 = ^TArr64; TArr64 = array[0..7] of Byte; var P: PChar; C: LongWord; Sign: LongBool; begin V := 0; P := Pointer(S); if not Assigned(P) then begin Result := False; Exit; end; while P^ = ' ' do Inc(P); if P^ = '-' then begin Sign := True; Inc(P); end else begin Sign := False; if P^ = '+' then Inc(P); end; if P^ <> '$' then begin if P^ = #0 then begin Result := False; Exit; end; repeat C := Byte(P^); if Char(C) in ['0'..'9'] then Dec(C,48) else Break; if (V<0) or (V>$CCCCCCCCCCCCCCC) then begin Result := False; Exit; end; V := V*10 + C; Inc(P); until False; if V < 0 then begin Result := (V=$8000000000000000) and Sign and (C=0); Exit; end; end else begin Inc(P); repeat C := Byte(P^); case Char(C) of '0'..'9': Dec(C,48); 'A'..'F': Dec(C,55); 'a'..'f': Dec(C,87); else Break; end; if PArr64(@V)^[7] >= $10 then begin Result := False; Exit; end; V := V shl 4; PLong(@V)^ := PLong(@V)^ or C; Inc(P); until False; if Sign and (V=$8000000000000000) then begin Result := False; Exit; end; end; if Sign then V := -V; Result := C=0; end; function Q_BetweenInt64(const S: string; LowBound, HighBound: Int64): Boolean; var N: Int64; begin Result := Q_StrToInt64(S,N) and (N>=LowBound) and (N<=HighBound); end; function Q_IsInteger(const S: string): Boolean; var L,I: Integer; P: PChar; C: Char; begin P := Pointer(S); L := Length(S); Result := False; while (L>0) and (P^=' ') do begin Dec(L); Inc(P); end; if L > 0 then begin C := P^; Inc(P); if C in ['-','+'] then begin C := P^; Dec(L); Inc(P); if L = 0 then Exit; end; if ((L<10) and (C in ['0'..'9'])) or ((L=10) and (C in ['0'..'1'])) then begin for I := 1 to L-1 do begin if not (P^ in ['0'..'9']) then Exit; Inc(P); end; Result := True; end else if (L=10) and (C='2') then Result := Q_BetweenInt64(S,-2147483647-1,2147483647); end; end; function Q_IsFloat(const S: string): Boolean; var L: Integer; P: PChar; begin P := Pointer(S); L := Length(S); Result := False; while (L>0) and (P^=' ') do begin Dec(L); Inc(P); end; if L > 0 then begin if P^ in ['-','+'] then begin Dec(L); Inc(P); if L = 0 then Exit; end; if not (P^ in ['0'..'9']) then Exit; repeat Dec(L); Inc(P); until (L=0) or not (P^ in ['0'..'9']); if L = 0 then begin Result := True; Exit; end; if P^ = DecimalSeparator then begin Dec(L); Inc(P); if (L=0) or not (P^ in ['0'..'9']) then Exit; repeat Dec(L); Inc(P); until (L=0) or not (P^ in ['0'..'9']); if L = 0 then begin Result := True; Exit; end; end; if P^ in ['E','e'] then begin Dec(L); Inc(P); if (L<>0) and (P^ in ['-','+']) then begin Dec(L); Inc(P); end; if (L=0) or not (P^ in ['0'..'9']) then Exit; repeat Dec(L); Inc(P); until (L=0) or not (P^ in ['0'..'9']); Result := L = 0; end; end; end; // ------------------------------- End of QStrings // Удаление именованного эл-та constructor TNamedValue.Create; begin end; destructor TNamedValue.Destroy; begin // Попаытаемся удалить из хэша: hash.Remove(fullname); inherited; end; procedure TNamedValue.MarkFileAsChanged; var fname,iName:string; i,p:integer; item:TNamedValue; begin p:=pos(':',fullname); if p>0 then begin fname:=copy(fullname,1,p-1); for i:=0 to items.GetChildrenCount-1 do begin item:=items.GetChild(i).data; iName:=Uppercase(item.name); if (item is TCtlFile) and (iName=fname) then begin TCtlFile(item).modified:=true; exit; end; end; end; end; destructor TInclude.Destroy; begin FreeControlFile(handle); inherited; end; { TIntValue } constructor TIntValue.Create; begin c:=random($10000000); v:=1028349272; v2:=v xor $28402850; end; function TIntValue.GetIntValue: integer; begin result:=(v xor $93749127) xor c; end; procedure TIntValue.SetIntValue(data: integer); begin if v2 xor v<>$28402850 then raise EFatalError.Create('CF2: fatal error #1'); v:=(data xor c) xor $93749127; v2:=v xor $28402850; MarkFileAsChanged; end; { TFloatValue } constructor TFloatValue.Create; begin c:=random($10000000); end; function TFloatValue.GetFloatValue: double; begin result:=v; EncryptFast(result,sizeof(result),c); end; procedure TFloatValue.SetFloatValue(data: double); begin EncryptFast(data,sizeof(data),c); v:=data; MarkFileAsChanged; end; { TBoolValue } constructor TBoolValue.Create; begin c:=random(2)=0; end; function TBoolValue.GetBoolValue: boolean; begin if c then result:=v else result:=v2; end; procedure TBoolValue.SetBoolValue(data: boolean); begin v:=data; v2:=data; MarkFileAsChanged; end; { TStringValue } constructor TStringValue.Create; begin key:=random(100000000); end; function TStringValue.GetStrValue: string; begin result:=st; if length(st)>0 then EncryptFast(result[1],length(st),key); end; procedure TStringValue.SetStrValue(data: string); begin if length(data)>0 then EncryptFast(data[1],length(data),key); st:=data; MarkFileAsChanged; end; { TStringListValue } procedure TStringListValue.Allocate(count: integer); begin SetLength(strings,count); end; constructor TStringListValue.Create; begin key:=random(100000000); end; function TStringListValue.GetCount: integer; begin result:=length(strings); end; function TStringListValue.GetStrValue(index: integer): string; begin result:=''; if (index<0) or (index>=Length(strings)) then raise EWarning.Create('CTL2: string index out of bounds'); result:=strings[index]; if length(result)<>0 then EncryptFast(result[1],length(result),key); end; procedure TStringListValue.SetStrValue(index: integer; data: string); begin if (index<0) or (index>=Length(strings)) then raise EWarning.Create('CTL2: string index out of bounds'); if length(data)<>0 then EncryptFast(data[1],length(data),key); strings[index]:=data; MarkFileAsChanged; end; { TCtlFile } constructor TCtlFile.Create(filename: string; filemode:TFileMode); begin fname:=filename; curmode:=filemode; inc(lastHandle); handle:=LastHandle; RefCounter:=1; modified:=false; end; {procedure TCtlFile.Free; begin if self<>nil then begin dec(RefCounter); if refCounter<=0 then inherited; end; end;} function FileByHandle(handle:integer):TGenericTree; var i:integer; item:TObject; begin result:=nil; for i:=0 to items.GetChildrenCount-1 do begin item:=items.GetChild(i).data; if (item is TCtlFile) and ((item as TCtlFile).handle=handle) then begin result:=items.GetChild(i); exit; end; end; end; { Main interface } function UseControlFile; var code:cardinal; i:integer; ctl:TCtlFile; // Загрузить указанный файл, вернуть его handle function Load(filename:string;code:cardinal):integer; var f:file; h:TBinaryHeader; i:integer; mode:TFileMode; // Загрузить файл текстового формата в указанный объект procedure LoadTextual(filename:string;item:TGenericTree); var f:TextFile; // Загрузить секцию в указанный объект, path - путь объекта (без слэша в конце) procedure LoadSection(var f:TextFile;item:TGenericTree;path:string); var st,arg,uArg,st2:string; sa:StringArr; comment:TCommentLine; incl:TInclude; sect:TSection; value:TNamedValue; i,n,ln:integer; begin ln:=0; // Последовательно обрабатываем все строки файла while not eof(f) do begin inc(ln); readln(f,st); st:=trim(st); // Comment line if (length(st)=0) or (st[1] in ['#',';']) then begin comment:=TCommentLine.Create; comment.line:=st; item.AddChild(comment); continue; end; // Разделим команду и аргумент arg:=''; for i:=1 to length(st) do if st[i] in [' ',#9] then begin arg:=TrimLeft(copy(st,i+1,length(st)-i)); SetLength(st,i-1); break; end; // Директива if st[1]='$' then begin // End of section if UpperCase(st)='$ENDOFSECTION' then break; // конец секции // Section if UpperCase(LeftStr(st,8))='$SECTION' then begin sect:=TSection.Create; sect.name:=arg; if arg='' then raise EWarning.Create('CTL2: unnamed section in '+filename+' line: '+inttostr(ln)); i:=item.AddChild(sect); sect.fullname:=UpperCase(path+'\'+arg); hash.Put(sect.fullname,item.GetChild(i)); LoadSection(f,item.GetChild(i),sect.fullname); continue; end; // Include command if UpperCase(LeftStr(st,8))='$INCLUDE' then begin incl:=TInclude.Create; incl.include:=arg; // Correct path so file is in the same directory if pos('\',arg)=0 then begin arg:=ExtractFilePath(filename)+arg; end; n:=useControlFile(arg,''); incl.handle:=n; if n=-1 then raise EWarning.Create('CTL2: include command failed - '+arg); item.AddChild(incl); continue; end; end; // Иначе - данные, нужно проверить тип DecimalSeparator:='.'; uArg:=UpperCase(arg); if (uArg='ON') or (uArg='OFF') or (uArg='YES') or (uArg='NO') then begin // boolean value:=TBoolValue.Create; (value as TBoolValue).value:=(uArg='ON') or (uArg='YES'); end else if Q_IsInteger(arg) then begin // Integer value:=TIntValue.Create; (value as TIntValue).value:=StrToInt(arg); end else if Q_IsFloat(arg) then begin // Float value:=TFloatValue.Create; (value as TFloatValue).value:=StrToFloat(arg); end else begin // String or string list if arg[1]='(' then begin // string list if arg[length(arg)]<>')' then begin // Multiline record repeat readln(f,st2); st2:=trim(st2); arg:=arg+st2; until eof(f) or (st2[length(st2)]=')'); end; // Delete '(' and ')' delete(arg,1,1); SetLength(arg,length(arg)-1); sa:=Split(',',arg,'"'); // Create and fill object value:=TStringlistValue.Create; with value as TStringListValue do begin Allocate(Length(sa)); for i:=0 to length(sa)-1 do value[i]:=UnQuoteStr(chop(sa[i])); end; end else begin arg:=UnQuoteStr(arg); value:=TStringValue.Create; (value as TStringValue).value:=arg; end; end; // Добавим элемент в структуры value.name:=st; value.fullname:=path+'\'+uppercase(st); i:=item.AddChild(value); hash.Put(value.fullname,item.GetChild(i)); end; end; begin // LoadTextual // Открыть файл и загрузить его как секцию assignfile(f,filename); reset(f); LoadSection(f,item,UpperCase(ExtractFileName(filename))+':'); closefile(f); end; procedure LoadBinary(filename:string;item:TGenericTree;code:cardinal); var f:file; h:TBinaryHeader; ms:TMemoryStream; mat:TMatrix32; p:byte; c:cardinal; size:integer; // Прочитать содержимое секции из двоичного файла procedure ReadSection(item:TGenericTree;path:string); var cnt,i,j,n:integer; b:byte; o:TObject; valB:boolean; valI:integer; valF:double; function ReadString:string; var w:word; begin ms.read(w,2); SetLength(result,w); ms.Read(result[1],w); end; begin ms.Read(cnt,4); for i:=1 to cnt do begin ms.Read(b,1); o:=nil; case b of itComment:begin o:=TCommentLine.Create; (o as TCommentLine).line:=ReadString; item.AddChild(o); end; itInclude:begin o:=TInclude.Create; with o as TInclude do begin include:=ReadString; handle:=UseControlFile(include,''); end; item.AddChild(o); end; itSection:begin o:=TSection.Create; (o as TSection).name:=ReadString; n:=item.AddChild(o); ReadSection(item.GetChild(n),path+'\'+UpperCase((o as TSection).name)); end; itBool:begin o:=TBoolValue.Create; (o as TBoolValue).name:=ReadString; ms.Read(valB,1); (o as TBoolValue).value:=valB; item.AddChild(o); end; itInt:begin o:=TIntValue.Create; (o as TIntValue).name:=ReadString; ms.Read(valI,4); (o as TIntValue).value:=valI; item.AddChild(o); end; itFloat:begin o:=TFloatValue.Create; (o as TFloatValue).name:=ReadString; ms.Read(valF,8); (o as TFloatValue).value:=valF; item.AddChild(o); end; itStr:begin o:=TStringValue.Create; (o as TStringValue).name:=ReadString; (o as TStringValue).value:=ReadString; item.AddChild(o); end; itStrList:begin o:=TStringListValue.Create; (o as TStringListValue).name:=ReadString; ms.Read(n,4); (o as TStringListValue).Allocate(n); for j:=0 to n-1 do (o as TStringListValue).value[j]:=ReadString; item.AddChild(o); end; else raise EWarning.Create('Unknown chunk type - new version?'); end; // set item's full name and add to hash if (o<>nil) and (o is TNamedValue) then with o as TNamedValue do begin fullname:=path+'\'+UpperCase(name); hash.Put(fullname,item.GetChild(i-1)); end; end; end; begin assignfile(f,filename); reset(f,1); blockread(f,h,sizeof(h)); p:=(h.sign2 xor h.sign1)-28301740; if p>=20 then raise EError.Create('Invalid file header'); move(h.data[p],c,4); c:=c+code; // Actual encryption code // Generate matrix for decryption GenMatrix32(mat,inttostr(c)); mat:=InvertMatrix32(mat); // Read rest of the file and decrypt it size:=filesize(f)-sizeof(h); ms:=TMemoryStream.Create; ms.SetSize(size); blockread(f,ms.memory^,size); Decrypt32A(ms.memory^,size,mat); ReadSection(item,UpperCase(ExtractFileName(filename))+':'); ms.Destroy; closefile(f); end; begin // Load result:=-1; // Проверка формата файла assignfile(f,filename); reset(f,1); if filesize(f)>=8 then begin blockread(f,h,8); if (h.sign1<=100000000) and (abs((h.sign2 xor h.sign1)-28301740)<=100) then mode:=fmBinary else mode:=fmText; end else mode:=fmText; closefile(f); // Создаем объект и добавляем его в структуры ctl:=TCtlFile.Create(filename,mode); ctl.fname:=filename; ctl.name:=ExtractFileName(filename); ctl.fullname:=UpperCase(ctl.name)+':'; i:=items.AddChild(ctl); hash.Put(ctl.fullname,items.GetChild(i)); ctl.curmode:=mode; ctl.code:=code; if ctl.curmode=fmText then LoadTextual(filename,items.GetChild(i)) else LoadBinary(filename,items.GetChild(i),code); result:=ctl.handle; end; begin try // Проверим, не был ли файл уже загружен ранее filename:=ExpandFileName(filename); for i:=0 to items.GetChildrenCount-1 do begin ctl:=items.GetChild(i).data; if ctl.fname=filename then begin result:=ctl.handle; inc(ctl.RefCounter); exit; end; end; if password<>'' then code:=CheckSumSlow(password[1],length(password),1) else code:=0; result:=Load(filename,code); except on e:Exception do raise EError.Create('CTL2: Can''t load control file: '+filename+', exception: '+e.Message); end; end; procedure SaveControlFile; var name:string; i:integer; item:TGenericTree; ctl:TCtlFile; procedure SaveTextual(item:TGenericTree;filename:string); var f:TextFile; // Сохранить в файл содержимое секции (с указанным отступом) procedure SaveSection(item:TGenericTree;indent:integer); var i,j:integer; o:TObject; pad,st:string; begin DecimalSeparator:='.'; for i:=0 to item.GetChildrenCount-1 do begin o:=item.GetChild(i).data; SetLength(pad,indent); for j:=1 to indent do pad[j]:=' '; // Save comment line if o is TCommentLine then begin writeln(f,pad,(o as TCommentLine).line); continue; end; // Директивы if o is TInclude then begin writeln(f,pad,'$Include ',(o as TInclude).include); SaveControlFile((o as TInclude).handle); continue; end; if o is TSection then begin writeln(f,pad,'$Section ',(o as TSection).name); SaveSection(item.GetChild(i),indent+2); writeln(f,pad,'$EndOfSection'); continue; end; // Format string for named value // Все прочие варианты должны быть обработаны выше! if o is TNamedValue then begin st:=pad+(o as TNamedValue).name+' '; while length(st) mod 8<>0 do st:=st+' '; end; // Save boolean value if o is TBoolValue then begin if (o as TBoolValue).Value then st:=st+'ON' else st:=st+'OFF'; writeln(f,st); continue; end; // Save integer value if o is TIntValue then begin st:=st+inttostr((o as TIntValue).Value); writeln(f,st); continue; end; // Save float value if o is TFloatValue then begin st:=st+floattostrf((o as TFloatValue).Value,ffFixed,9,6); writeln(f,st); continue; end; // Save string value if o is TStringValue then begin //st:=st+QuoteStr((o as TStringValue).value); // Принудительное заключение в кавычки чтобы избежать конфликта с числами st:=st+'"'+(o as TStringValue).value+'"'; writeln(f,st); continue; end; // Save string array value if o is TStringListValue then with o as TStringListValue do begin st:=st+'('; if count=0 then st:=st+')'; j:=length(st); setLength(pad,j); for j:=1 to length(pad) do pad[j]:=' '; for j:=1 to count do begin while length(st) mod 8<>1 do st:=st+' '; st:=st+QuoteStr(value[j-1]); if j<count then st:=st+',' else st:=st+')'; if length(st)>75 then begin writeln(f,st); st:=pad; end; end; // если осталась незаписанная строка if (length(st)<=75) and (st<>pad) then writeln(f,st); continue; end; end; end; begin assignfile(f,filename); rewrite(f); SaveSection(item,0); closefile(f); end; procedure SaveBinary(item:TGenericTree;filename:string); var f:file; h:TBinaryHeader; p:byte; i:integer; code:cardinal; ms:TMemoryStream; o:TObject; mat:TMatrix32; // Save section to binary stream procedure SaveSection(item:TGenericTree); var b:byte; st:string; i,j,n:integer; o:TObject; valB:boolean; valI:integer; valF:double; procedure WriteString(st:string); var w:word; begin w:=length(st); ms.Write(w,2); ms.Write(st[1],w); end; begin n:=item.GetChildrenCount; ms.Write(n,4); for i:=0 to n-1 do begin o:=item.GetChild(i).data; // Save comment line if o is TCommentLine then begin b:=itComment; ms.Write(b,1); WriteString((o as TCommentLine).line); continue; end; // Директивы if o is TInclude then begin b:=itInclude; ms.Write(b,1); WriteString((o as TInclude).include); SaveControlFile((o as TInclude).handle); continue; end; if o is TSection then begin b:=itSection; ms.Write(b,1); WriteString((o as TSection).name); SaveSection(item.GetChild(i)); continue; end; // Save boolean value if o is TBoolValue then begin b:=itBool; ms.Write(b,1); WriteString((o as TBoolValue).name); valB:=(o as TBoolValue).value; ms.Write(valB,1); continue; end; // Save integer value if o is TIntValue then begin b:=itInt; ms.Write(b,1); WriteString((o as TIntValue).name); valI:=(o as TIntValue).value; ms.Write(valI,4); continue; end; // Save float value if o is TFloatValue then begin b:=itFloat; ms.Write(b,1); WriteString((o as TFloatValue).name); valF:=(o as TFloatValue).value; ms.Write(valF,8); continue; end; // Save string value if o is TStringValue then begin b:=itStr; ms.Write(b,1); WriteString((o as TStringValue).name); WriteString((o as TStringValue).value); continue; end; // Save string array value if o is TStringListValue then with o as TStringListValue do begin b:=itStrList; ms.Write(b,1); WriteString((o as TStringListValue).name); n:=count; ms.Write(n,4); for j:=0 to n-1 do WriteString(value[j]); continue; end; end; end; begin assignfile(f,filename); rewrite(f,1); p:=random(20); h.sign1:=random(100000000); h.sign2:=h.sign1 xor (28301740+p); code:=random(1000000); for i:=0 to 23 do h.data[i]:=random(256); move(code,h.data[p],4); o:=item.data; inc(code,(o as TCtlFile).code); // Actual encryption code ms:=TMemoryStream.Create; GenMatrix32(mat,inttostr(code)); SaveSection(item); Encrypt32A(ms.memory^,ms.size,mat); blockwrite(f,h,sizeof(h)); blockwrite(f,ms.memory^,ms.size); closefile(f); ms.Destroy; end; begin name:='unknown'; try item:=FileByHandle(handle); if item=nil then raise EWarning.Create('invalid handle passed'); ctl:=item.data; if mode=fmDefault then mode:=ctl.CurMode; if mode=fmText then SaveTextual(item,ctl.fname) else SaveBinary(item,ctl.fname); ctl.modified:=false; except on e:Exception do raise EWarning.Create('CTL2: Can''t save control file: '+name+', exception: '+e.Message); end; end; procedure SaveAllControlFiles; var i:integer; item:TNamedValue; begin for i:=0 to items.GetChildrenCount-1 do begin item:=items.GetChild(i).data; if (item is TCtlFile) and ((item as TCtlFile).modified) then SaveControlFile(TCtlFile(item).handle); end; end; procedure FreeControlFile; var i:integer; ctl:TCtlFile; item:TGenericTree; begin item:=FileByHandle(handle); if item<>nil then begin ctl:=item.data; dec(ctl.RefCounter); if ctl.RefCounter<=0 then item.Free; end; end; function IsKeyExists(key:String):Boolean; begin result:=(hash.Get(UpperCase(key))<>nil); end; function FindItem(key:string):TObject; var item:TGenericTree; begin result:=nil; item:=hash.Get(UpperCase(key)); if item=nil then exit; result:=item.data; end; function ctlGetKeyType(key:String):ctlKeyTypes; var o:TObject; begin result:=cktNone; o:=FindItem(key); if o=nil then exit; if o is TIntValue then result:=cktInteger; if o is TBoolValue then result:=cktBool; if o is TFloatValue then result:=cktReal; if o is TStringValue then result:=cktString; if o is TStringListValue then result:=cktArray; if o is TSection then result:=cktSection; end; const MessageKeyIncorrect='CTL2: key does not exists or has inproper type - '; MessageWrongType='CTL2: operation requires another type of key - '; MessageCannotCreateKey='CTL2: cannot create key - '; function ctlGetBool(key:string):boolean; var o:TObject; begin o:=FindItem(key); if (o<>nil) and (o is TBoolValue) then result:=(o as TBoolValue).value else raise EWarning.Create(MessageKeyIncorrect+key); end; function ctlGetInt(key:string):integer; var o:TObject; begin o:=FindItem(key); if (o<>nil) and (o is TIntValue) then result:=(o as TIntValue).value else if (o<>nil) and (o is TStringValue) then result:=StrToIntDef((o as TStringValue).value,0) else raise EWarning.Create(MessageKeyIncorrect+key); end; function ctlGetReal(key:string):double; var o:TObject; begin o:=FindItem(key); if (o<>nil) and (o is TFloatValue) then result:=(o as TFloatValue).value else raise EWarning.Create(MessageKeyIncorrect+key); end; function ctlGetStr(key:string):string; var o:TObject; begin o:=FindItem(key); if (o<>nil) and ((o is TStringValue) or (o is TIntValue)) then begin if (o is TStringValue) then result:=(o as TStringValue).value else if (o is TIntValue) then result:=inttostr((o as TIntValue).value); end else raise EWarning.Create(MessageKeyIncorrect+key); end; function ctlGetBool(key:string;default:boolean):boolean; var o:TObject; begin o:=FindItem(key); if (o<>nil) and (o is TBoolValue) then result:=(o as TBoolValue).value else result:=default; end; function ctlGetInt(key:string;default:integer):integer; var o:TObject; begin o:=FindItem(key); if (o<>nil) and (o is TIntValue) then result:=(o as TIntValue).value else result:=default; end; function ctlGetReal(key:string;default:double):double; var o:TObject; begin o:=FindItem(key); if (o<>nil) and (o is TFloatValue) then result:=(o as TFloatValue).value else result:=default; end; function ctlGetStr(key:string;default:string):string; var o:TObject; begin o:=FindItem(key); if (o<>nil) and (o is TStringValue) then result:=(o as TStringValue).value else result:=default; end; function ctlGetStrInd(key:String;index:Integer):String; var o:TObject; begin o:=FindItem(key); if (o<>nil) and (o is TStringListValue) then result:=(o as TStringListValue).value[index] else raise EWarning.Create(MessageKeyIncorrect+key); end; function ctlGetStrCnt(key:String):Integer; var o:TObject; begin o:=FindItem(key); if (o<>nil) and (o is TStringListValue) then result:=(o as TStringListValue).count else raise EWarning.Create(MessageKeyIncorrect+key); end; function ctlGetKeys(key:string):String; var item:TGenericTree; o:TObject; i:integer; begin item:=hash.get(UpperCase(key)); if item=nil then raise EWarning.Create(MessageKeyIncorrect+key); o:=item.data; if not (o is TSection) then raise EWarning.Create(MessageKeyIncorrect+key); result:=''; for i:=0 to item.GetChildrenCount-1 do begin o:=item.GetChild(i).data; if o is TNamedValue then begin if i>0 then result:=result+' '; result:=result+(o as TNamedValue).name; end; end; end; // Write functions procedure ctlCreateSection(key:string); var o:TObject; s,curS:TSection; f:TCtlFile; item:TGenericTree; i:integer; fname,sname:string; fl:boolean; begin o:=FindItem(key); if (o<>nil) and (o is TSection) then exit; // Section already exists if (o<>nil) and not (o is TSection) then raise EWarning.Create('CTL2: Cannot create section - key already exists: '+key); fname:=copy(key,1,pos(':',key)-1); // filename part of path delete(key,1,pos(':',key)+1); key:=key+'\'; // Нужно найти файл в котором нужно создать секцию item:=nil; for i:=0 to items.GetChildrenCount-1 do begin f:=items.GetChild(i).data; if UpperCase(f.name)=UpperCase(fname) then item:=items.GetChild(i); end; if item=nil then raise EWarning.Create('CTL2: Cannot create section - file '+fname+' was not loaded.'); if key='' then exit; repeat sname:=copy(key,1,pos('\',key)-1); delete(key,1,pos('\',key)); fl:=false; for i:=0 to item.GetChildrenCount-1 do begin o:=item.GetChild(i).data; if (o is TSection) and (UpperCase((o as TSection).name)=UpperCase(sname)) then begin item:=item.GetChild(i); fl:=true; break; end; end; if not fl then begin // Subsection not found => create it curS:=item.data; s:=TSection.Create; s.name:=sname; if curs is TCtlFile then s.fullname:=curS.fullname+'\'+uppercase(sname) else s.fullname:=curS.fullname+'\'+uppercase(sname); i:=item.AddChild(s); item:=item.GetChild(i); hash.Put(s.fullname,item); end until length(key)=0; end; // Создает элемент заданного типа, возвращает объект (но не лист дерева!) function CreateKey(key:string;KeyType:TNamedValueClass):TObject; var i,n:integer; s:string; o:TNamedValue; item:TGenericTree; begin result:=nil; for i:=length(key) downto 1 do if key[i]='\' then begin s:=copy(key,1,i-1); ctlCreateSection(s); item:=hash.Get(UpperCase(s)); o:=item.data; if o is TCtlFile then TCtlFile(o).modified:=true; o:=KeyType.Create; o.name:=Copy(key,i+1,length(key)-i); o.fullname:=UpperCase(key); n:=item.AddChild(o); hash.Put(o.fullname,item.GetChild(n)); result:=o; exit; end; end; procedure ctlSetBool(key:string;value:boolean); var o:TObject; begin o:=FindItem(key); if o=nil then begin // Create key o:=CreateKey(key,TBoolValue); if o=nil then raise EWarning.Create(MessageCannotCreateKey+key); end; if o is TBoolValue then (o as TBoolValue).value:=value else raise EWarning.Create(MessageWrongType+key); end; procedure ctlSetInt(key:string;value:integer); var o:TObject; begin o:=FindItem(key); if o=nil then begin // Create key o:=CreateKey(key,TIntValue); if o=nil then raise EWarning.Create(MessageCannotCreateKey+key); end; if o is TIntValue then (o as TIntValue).value:=value else raise EWarning.Create(MessageWrongType+key); end; procedure ctlSetReal(key:string;value:double); var o:TObject; begin o:=FindItem(key); if o=nil then begin // Create key o:=CreateKey(key,TFloatValue); if o=nil then raise EWarning.Create(MessageCannotCreateKey+key); end; if o is TFloatValue then (o as TFloatValue).value:=value else raise EWarning.Create(MessageWrongType+key); end; procedure ctlSetStr(key:string;value:string); var o:TObject; begin o:=FindItem(key); if o=nil then begin // Create key o:=CreateKey(key,TStringValue); if o=nil then raise EWarning.Create(MessageCannotCreateKey+key); end; if o is TStringValue then (o as TStringValue).value:=value else raise EWarning.Create(MessageWrongType+key); end; procedure ctlSetStrInd(key:String;index:Integer;value:string); var o:TObject; begin o:=FindItem(key); if (o=nil) or not (o is TStringListValue) then raise EWarning.Create(MessageKeyIncorrect+key); (o as TStringListValue).value[index]:=value; end; procedure ctlSetStrCnt(key:String;count:integer); var o:TObject; begin o:=FindItem(key); if o=nil then begin // Create key o:=CreateKey(key,TStringListValue); if o=nil then raise EWarning.Create(MessageCannotCreateKey+key); end; if not (o is TStringListValue) then raise EWarning.Create(MessageWrongType+key); (o as TStringListValue).Allocate(count); end; procedure ctlAddStr(key:String;newvalue:string); var o:TObject; begin o:=FindItem(key); if (o=nil) or not (o is TStringListValue) then raise EWarning.Create(MessageKeyIncorrect+key); with o as TStringListValue do begin Allocate(count+1); value[count-1]:=newvalue; end; end; procedure ctlDeleteKey(key:string); var o:TObject; item:TGenericTree; ind:integer; begin item:=hash.Get(uppercase(key)); if item=nil then raise EWarning.Create(MessageKeyIncorrect+key); if item.GetParent=nil then raise EWarning.Create('Can''t delete root section!'); item.Free; end; { TControlFile } procedure TControlFile.AddStr(key, newvalue: string); begin EnterCriticalSection(critSect); try ctlAddStr(GetAbsPath(key),newvalue); finally LeaveCriticalSection(CritSect); end; end; constructor TControlFile.Create(fname,password:string); begin handle:=-1; EnterCriticalSection(critSect); try handle:=UseControlFile(fname,password); path:=ExtractFileName(fname)+':'; finally LeaveCriticalSection(CritSect); end; end; procedure TControlFile.CreateSection(key: string); begin EnterCriticalSection(critSect); try ctlCreateSection(GetAbsPath(key)); finally LeaveCriticalSection(CritSect); end; end; destructor TControlFile.Destroy; begin if handle=-1 then exit; EnterCriticalSection(critSect); try // SaveControlFile(handle); FreeControlFile(handle); finally LeaveCriticalSection(CritSect); end; end; function TControlFile.GetBool(key: string): boolean; begin EnterCriticalSection(critSect); try result:=ctlGetBool(GetAbsPath(key)); finally LeaveCriticalSection(CritSect); end; end; function TControlFile.GetInt(key: string): integer; begin EnterCriticalSection(critSect); try result:=ctlGetInt(GetAbsPath(key)); finally LeaveCriticalSection(CritSect); end; end; function TControlFile.GetKeyType(key: String): ctlKeyTypes; begin EnterCriticalSection(critSect); try result:=ctlGetKeyType(GetAbsPath(key)); finally LeaveCriticalSection(CritSect); end; end; function TControlFile.GetReal(key: string): double; begin EnterCriticalSection(critSect); try result:=ctlGetReal(GetAbsPath(key)); finally LeaveCriticalSection(CritSect); end; end; function TControlFile.GetStr(key: string): string; begin EnterCriticalSection(critSect); try result:=ctlGetStr(GetAbsPath(key)); finally LeaveCriticalSection(CritSect); end; end; function TControlFile.GetStrCnt(key: String): Integer; begin EnterCriticalSection(critSect); try result:=ctlGetStrCnt(GetAbsPath(key)); finally LeaveCriticalSection(CritSect); end; end; function TControlFile.GetStrInd(key: String; index: Integer): String; begin EnterCriticalSection(critSect); try result:=ctlGetStrInd(GetAbsPath(key),index); finally LeaveCriticalSection(CritSect); end; end; function TControlFile.KeyExists(key: String): Boolean; begin EnterCriticalSection(critSect); try result:=IsKeyExists(GetAbsPath(key)); finally LeaveCriticalSection(CritSect); end; end; function TControlFile.GetAbsPath(key:string):string; var i:integer; begin if pos(':',key)>0 then begin result:=path; exit; end; result:=path; if (result<>'') and (result[length(result)]='\') then delete(result,length(result),1); while pos('..\',key)=1 do begin delete(key,1,3); for i:=length(result) downto 1 do if result[i]='\' then begin delete(result,i,length(result)-i+1); break; end; end; result:=result+'\'+key; end; procedure TControlFile.Save; begin EnterCriticalSection(critSect); SaveControlFile(handle); LeaveCriticalSection(CritSect); end; procedure TControlFile.SetBool(key: string; value: boolean); begin EnterCriticalSection(critSect); try ctlSetBool(GetAbsPath(key),value); finally LeaveCriticalSection(CritSect); end; end; procedure TControlFile.SetInt(key: string; value: integer); begin EnterCriticalSection(critSect); try ctlSetInt(GetAbsPath(key),value); finally LeaveCriticalSection(CritSect); end; end; procedure TControlFile.SetReal(key: string; value: double); begin EnterCriticalSection(critSect); try ctlSetReal(GetAbsPath(key),value); finally LeaveCriticalSection(CritSect); end; end; procedure TControlFile.SetStr(key, value: string); begin EnterCriticalSection(critSect); try ctlSetStr(GetAbsPath(key),value); finally LeaveCriticalSection(CritSect); end; end; procedure TControlFile.SetStrCnt(key: String; count: integer); begin EnterCriticalSection(critSect); try ctlSetStrCnt(GetAbsPath(key),count); finally LeaveCriticalSection(CritSect); end; end; procedure TControlFile.SetStrInd(key: String; index: Integer; value: string); begin EnterCriticalSection(critSect); try ctlSetStrInd(GetAbsPath(key),index,value); finally LeaveCriticalSection(CritSect); end; end; function TControlFile.GetKeys(key: string): String; begin EnterCriticalSection(critSect); try result:=ctlGetKeys(GetAbsPath(key)); finally LeaveCriticalSection(CritSect); end; end; procedure TControlFile.DeleteKey(key: string); begin EnterCriticalSection(critSect); try ctlDeleteKey(key); finally LeaveCriticalSection(CritSect); end; end; function TControlFile.GetBool(key: string; default: boolean): boolean; begin try result:=GetBool(key); except result:=default; end; end; function TControlFile.GetInt(key: string; default: integer): integer; begin try result:=GetInt(key); except result:=default; end; end; function TControlFile.GetReal(key: string; default: double): double; begin try result:=GetReal(key); except result:=default; end; end; function TControlFile.GetStr(key, default: string): string; begin try result:=GetStr(key); except result:=default; end; end; initialization items:=TGenericTree.Create(true,true); hash:=TStrHash.Create; InitCritSect(critSect,'CtlFiles2',300); finalization // Удалять свои объекты не стоит - толку никакого, программа все-равно завершает работу // а вот на баги нарываться не хочется... DeleteCritSect(critSect); end.
unit NFSComboBox; {$I NFS_Komponente.inc} //{$Define IBC} interface uses Windows, Messages, SysUtils, Classes, Controls, StdCtrls, DB, {$IfDef IBC} IBC {$Else} IBX.IBDatabase, IBX.IBQuery {$EndIf} ; type TNFSComboBox = class(TComboBox) private { Private-Deklarationen } FValues: TStrings; FSQL : TStrings; {$IfDef IBC} FTransaction : TIBCTransaction; {$Else} FTransaction : TIBTransaction; {$EndIf} procedure setFValues(Value: TStrings); procedure setFSQL(Value: TStrings); protected { Protected-Deklarationen } public { Public-Deklarationen } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Add(aItem: string; aValue: string); overload; procedure Add(aQuery: TDataset; FieldItem, FieldValue: integer); overload; procedure Add(aQuery: TDataset; Anzahl, ID: integer; vor, hinter: string); overload; procedure AddFromSQL(Anzahl, ID: integer; vor, hinter: string); overload; procedure AddFromSQL(Text, ID: integer); overload; procedure Delete(aIdx: integer); function getIdxValue: string; function getIdxValueInt: integer; procedure Clear; override; procedure setItemIndex(aValue: string); overload; procedure setItemIndex(aValue: integer); reintroduce; overload; procedure SelectIdxValue(aValue: integer); procedure SelectNamesValue(aValue: string); published { Published-Deklarationen } property Values : TStrings read FValues write setFValues; property SQL : TStrings read FSQL write setFSQL; {$IfDef IBC} property Transaction : TIBCTransaction read FTransaction write FTransaction; {$Else} property Transaction : TIBTransaction read FTransaction write FTransaction; {$EndIf} end; procedure Register; implementation procedure Register; begin RegisterComponents('new frontiers', [TNFSComboBox]); end; { TNFSComboBox } procedure TNFSComboBox.Add(aItem, aValue: string); begin if Values = nil then Values := TStringList.Create; Items.Add(aItem); FValues.Add(aValue); end; procedure TNFSComboBox.Add(aQuery: TDataset; FieldItem, FieldValue: integer); begin if Values = nil then Values := TStringList.Create; while not aQuery.Eof do begin Add(aQuery.Fields[FieldItem].asString, aQuery.Fields[FieldValue].asString); aQuery.Next; end; end; { Die Methode fügt Felder in der Reihenfolge der Query beginnend mit dem ersten Feld der Query ein Anzahl: wie viele DB-Felder sollen verwendet werden (beginnend mit dem ersten Feld der query) ID: an welcher Stelle ist das Feld mit der zu verwendenden ID vor, hinter: Zeichen vor bzw. hinter allen Feldern nach dem ersten } procedure TNFSComboBox.Add(aQuery: TDataset; Anzahl, ID: integer; vor, hinter: string); var i: integer; temp: string; begin if Values = nil then Values := TStringList.Create; while not aQuery.Eof do begin // Add(aQuery.Fields[FieldItem].asString + ' (' + aQuery.Fields[FieldItem2].asString + ')', aQuery.Fields[FieldValue].asString); temp := aQuery.Fields[0].asString; For i := 1 to (Anzahl - 1) do begin temp := temp + vor + aQuery.Fields[i].asString + hinter end; Add(temp, aQuery.Fields[ID].asString); aQuery.Next; end; end; { Die Methode fügt Felder in der Reihenfolge der Query beginnend mit dem ersten Feld der Query ein Anzahl: wie viele DB-Felder sollen verwendet werden (beginnend mit dem ersten Feld der query) ID: an welcher Stelle ist das Feld mit der zu verwendenden ID vor, hinter: Zeichen vor bzw. hinter allen Feldern nach dem ersten } procedure TNFSComboBox.AddFromSQL(Anzahl, ID: integer; vor, hinter: string); var WasOpen: boolean; {$IfDef IBC} Query: TIBCQuery; {$Else} Query: TIBQuery; {$EndIf} begin if (SQL.Text = '') or (Transaction = nil) then Exit; {$IfDef IBC} Query := TIBCquery.Create(self); {$Else} Query := TIBquery.Create(self); {$EndIf} Query.Transaction := self.Transaction; WasOpen := Transaction.Active; // WasOpen := Transaction.InTransaction; if not WasOpen then Transaction.startTransaction; Query.SQL := SQL; Query.Open; Add(Query, Anzahl, ID, vor, hinter); Query.Close; Query.Free; self.Enabled := (self.ItemCount > 0); if self.Items.Count > 0 then self.ItemIndex := 0 else self.ItemIndex := -1; if not WasOpen then Transaction.Rollback; end; procedure TNFSComboBox.AddFromSQL(Text, ID: integer); var WasOpen: boolean; {$IfDef IBC} Query: TIBCQuery; {$Else} Query: TIBQuery; {$EndIf} begin if (Transaction = nil) then raise Exception.Create('Keine Transaction zugeordnet'); {$IfDef IBC} Query := TIBCquery.Create(self); {$Else} Query := TIBquery.Create(self); {$EndIf} if (SQL.Text = '') then raise Exception.Create('Keine Query eingetragen'); Query.Transaction := self.Transaction; WasOpen := Transaction.Active; if not WasOpen then Transaction.startTransaction; Query.SQL := SQL; Query.Open; Add(Query, Text, ID); Query.Close; Query.Free; self.Enabled := (self.ItemCount > 0); if self.Items.Count > 0 then self.ItemIndex := 0 else self.ItemIndex := -1; if not WasOpen then Transaction.Rollback; end; procedure TNFSComboBox.Clear; begin if Values = nil then Values := TStringList.Create; Items.Clear; Values.Clear; end; constructor TNFSComboBox.Create(AOwner: TComponent); begin inherited; FValues := TStringList.Create; FSQL := TStringList.Create; end; procedure TNFSComboBox.Delete(aIdx: integer); begin if aIdx > Items.Count-1 then Exit else begin Items.Delete(aIdx); Values.Delete(aIdx); end; end; destructor TNFSComboBox.Destroy; begin if FValues <> nil then begin FValues.Free; FValues := nil; end; if FSQL <> nil then begin FSQL.Free; FSQL := nil; end; inherited; end; function TNFSComboBox.getIdxValue: string; begin if (self.ItemIndex <> -1) and (self.ItemIndex < self.Items.Count) then result := Values[self.ItemIndex] else result := 'FEHLER!'; end; function TNFSComboBox.getIdxValueInt: integer; var i: integer; Temp: boolean; Temp2: string; begin // numerisch? Temp := true; Temp2 := getIdxValue; for i := 1 to Length(Temp2) do if not CharInSet(Temp2[i], ['0'..'9']) then begin Temp := false; Break; end; if not Temp then result := -1 else result := StrToInt(Temp2); end; procedure TNFSComboBox.setFSQL(Value: TStrings); begin FSQL.Assign(Value); end; procedure TNFSComboBox.setFValues(Value: TStrings); begin FValues.Assign(Value); end; procedure TNFSComboBox.setItemIndex(aValue: string); var i: integer; found: boolean; begin found := false; for i := 0 to Values.Count-1 do if Values[i] = aValue then begin self.ItemIndex := i; found := true; Break; end; if not found then self.ItemIndex := -1; self.Repaint; end; procedure TNFSComboBox.setItemIndex(aValue: integer); begin setItemIndex(IntToStr(aValue)); end; //[tb 04.12.2012] Es wird nach dem ID-Wert gesucht, wenn gefunden selektiert. procedure TNFSComboBox.SelectIdxValue(aValue: integer); var i1: Integer; iValue: Integer; begin for i1 := 0 to Values.Count - 1 do begin if not TryStrToInt(Values[i1], iValue) then iValue := -2; if aValue = iValue then begin ItemIndex := i1; break; end; end; end; procedure TNFSComboBox.SelectNamesValue(aValue: string); var i1: Integer; begin for i1 := 0 to Items.Count - 1 do begin if Items.Strings[i1] = aValue then begin ItemIndex := i1; break; end; end; end; end.
unit Funcs; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, TAGraph, TASeries, TAFuncSeries, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, Grids, ParseMath, Math; type TFuncs = class procedure CalculateFunc(const AX: Double; out AY: Double); private Parse : TParseMath; function f( x : Real ) : Real; public Serie : TFuncSeries; procedure CreateGraph(n : Integer;x : Integer; expression : String); end; implementation uses main; procedure TFuncs.CalculateFunc(const AX: Double; out AY: Double); begin AY := f(AX); end; function TFuncs.f( x : Real ) : Real; begin Parse.NewValue('x',x); Result := Parse.Evaluate(); end; procedure TFuncs.CreateGraph(n : Integer; x : Integer; expression : String); begin with Form1 do begin Parse := TParseMath.create; Parse.AddVariable('x',0); Parse.Expression := expression; Serie := TFuncSeries.Create(Chart1); Chart1.AddSeries(Serie); Serie.Active := False; with Serie.DomainExclusions do begin //ShowMessage('1 -' + Grid1.Cells[x+1,1]); AddRange(NegInfinity,StrToFloat(Grid1.Cells[x+1,1])-0.0001); x := x + 4; if x > n - 1 then x := x - 4 + abs(x - n); //ShowMessage('2 - ' + Grid1.Cells[x,1]); AddRange(StrToFloat(Grid1.Cells[x,1])+0.0001,Infinity); end; Serie.OnCalculate := @CalculateFunc; Serie.Tag := pos; Serie.Active := True; end; end; end.
unit rtti_broker_uPersistClassRegister; {$mode objfpc}{$H+} interface uses Classes, SysUtils, rtti_broker_iBroker, fgl; type { TRBPersistClassRegister } TRBPersistClassRegister = class(TInterfacedObject, IRBPersistClassRegister) private type TClasses = specialize TFPGList<TPersistentClass>; private fClasses: TClasses; protected procedure Add(const AClass: TPersistentClass); function GetItem(AIndex: integer): TPersistentClass; function GetCount: integer; public procedure AfterConstruction; override; procedure BeforeDestruction; override; end; implementation { TRBPersistClassRegister } procedure TRBPersistClassRegister.Add(const AClass: TPersistentClass); begin if fClasses.IndexOf(AClass) = -1 then fClasses.Add(AClass); end; function TRBPersistClassRegister.GetItem(AIndex: integer): TPersistentClass; begin Result := fClasses[AIndex]; end; function TRBPersistClassRegister.GetCount: integer; begin Result := fClasses.Count; end; procedure TRBPersistClassRegister.AfterConstruction; begin fClasses := TClasses.Create; end; procedure TRBPersistClassRegister.BeforeDestruction; begin FreeAndNil(fClasses); end; end.
unit uDBAdapter; interface uses System.SysUtils, System.DateUtils, System.StrUtils, System.Classes, Data.DB, Data.Win.ADODB, System.Variants, uMemory, uDBConnection, uDBGraphicTypes; type TImageTableAdapter = class(TObject) private FDS: TDataSet; function FilterMemoText(Value: string): string; procedure SetMemoText(FieldName, Value: string); function GetName: string; procedure SetName(const Value: string); function GetFileName: string; procedure SetFileName(const Value: string); function GetID: Integer; procedure SetID(const Value: Integer); function GetRating: Integer; procedure SetRating(const Value: Integer); function GetHeight: Integer; function GetWidth: Integer; procedure SetHeight(const Value: Integer); procedure SetWidth(const Value: Integer); function GetFileSize: Integer; procedure SetFileSize(const Value: Integer); function GetThumb: TField; function GetRotation: Integer; procedure SetRotation(const Value: Integer); function GetAccess: Integer; procedure SetAccess(const Value: Integer); function GetKeyWords: string; procedure SetKeyWords(const Value: string); function GetComment: string; procedure SetComment(const Value: string); function GetDate: TDate; function GetIsDate: Boolean; function GetIsTime: Boolean; function GetTime: TTime; procedure SetDate(const Value: TDate); procedure SetIsDate(const Value: Boolean); procedure SetIsTime(const Value: Boolean); procedure SetTime(const Value: TTime); function GetGroups: string; procedure SetGroups(const Value: string); function GetInclude: Boolean; procedure SetInclude(const Value: Boolean); function GetLongImageID: string; procedure SetLongImageID(const Value: string); function GetLinks: string; procedure SetLinks(const Value: string); function GetAttributes: Integer; procedure SetAttributes(const Value: Integer); function GetColors: string; function GetViewCount: Integer; function GetUpdateDate: TDateTime; procedure SetColors(const Value: string); procedure SetViewCount(const Value: Integer); procedure SetUpdateDate(const Value: TDateTime); public constructor Create(DS: TDataSet); procedure ReadHistogram(var Histogram: THistogrammData); property ID: Integer read GetID write SetID; property Name: string read GetName write SetName; property FileName: string read GetFileName write SetFileName; property Rating: Integer read GetRating write SetRating; property Width: Integer read GetWidth write SetWidth; property Height: Integer read GetHeight write SetHeight; property FileSize: Integer read GetFileSize write SetFileSize; property Thumb: TField read GetThumb; property Rotation: Integer read GetRotation write SetRotation; property Access: Integer read GetAccess write SetAccess; property KeyWords: string read GetKeyWords write SetKeyWords; property Comment: string read GetComment write SetComment; property Date: TDate read GetDate write SetDate; property IsDate: Boolean read GetIsDate write SetIsDate; property Time: TTime read GetTime write SetTime; property IsTime: Boolean read GetIsTime write SetIsTime; property Groups: string read GetGroups write SetGroups; property Include: Boolean read GetInclude write SetInclude; property LongImageID: string read GetLongImageID write SetLongImageID; property Links: string read GetLinks write SetLinks; property Attributes: Integer read GetAttributes write SetAttributes; property Colors: string read GetColors write SetColors; property ViewCount: Integer read GetViewCount write SetViewCount; property UpdateDate: TDateTime read GetUpdateDate write SetUpdateDate; property DataSet: TDataSet read FDS; end; implementation { TDBAdapter } function TImageTableAdapter.FilterMemoText(Value: string): string; begin Result := Trim(Value); end; procedure TImageTableAdapter.SetMemoText(FieldName, Value: string); begin if Value <> '' then FDS.FieldByName(FieldName).AsString := Value else FDS.FieldByName(FieldName).AsString := ' '; end; constructor TImageTableAdapter.Create(DS: TDataSet); begin FDS := DS; end; function TImageTableAdapter.GetAccess: Integer; begin Result := FDS.FieldByName('Access').AsInteger; end; function TImageTableAdapter.GetAttributes: Integer; begin Result := FDS.FieldByName('Attr').AsInteger; end; function TImageTableAdapter.GetColors: string; begin Result := FDS.FieldByName('Colors').AsString; end; function TImageTableAdapter.GetComment: string; begin Result := FilterMemoText(FDS.FieldByName('Comment').AsString); end; function TImageTableAdapter.GetDate: TDate; begin Result := DateOf(FDS.FieldByName('DateToAdd').AsDateTime); end; function TImageTableAdapter.GetFileName: string; begin Result := FDS.FieldByName('FFileName').AsString; end; function TImageTableAdapter.GetFileSize: Integer; begin Result := FDS.FieldByName('FileSize').AsInteger; end; function TImageTableAdapter.GetGroups: string; begin Result := FilterMemoText(FDS.FieldByName('Groups').AsString); end; function TImageTableAdapter.GetHeight: Integer; begin Result := FDS.FieldByName('Height').AsInteger; end; function TImageTableAdapter.GetID: Integer; begin Result := FDS.FieldByName('ID').AsInteger; end; function TImageTableAdapter.GetInclude: Boolean; begin Result := FDS.FieldByName('Include').Value; end; function TImageTableAdapter.GetIsDate: Boolean; begin Result := FDS.FieldByName('IsDate').Value; end; function TImageTableAdapter.GetIsTime: Boolean; begin Result := FDS.FieldByName('IsTime').Value; end; function TImageTableAdapter.GetKeyWords: string; begin Result := FilterMemoText(FDS.FieldByName('Keywords').AsString); end; function TImageTableAdapter.GetLinks: string; begin Result := FilterMemoText(FDS.FieldByName('Links').AsString); end; function TImageTableAdapter.GetLongImageID: string; begin Result := FDS.FieldByName('StrTh').AsString; end; function TImageTableAdapter.GetName: string; begin Result := Trim(FDS.FieldByName('Name').AsString); end; function TImageTableAdapter.GetRating: Integer; begin Result := FDS.FieldByName('Rating').AsInteger; end; function TImageTableAdapter.GetRotation: Integer; begin Result := FDS.FieldByName('Rotated').AsInteger; end; function TImageTableAdapter.GetThumb: TField; begin Result := FDS.FieldByName('thum'); end; function TImageTableAdapter.GetTime: TTime; begin Result := TimeOf(FDS.FieldByName('aTime').AsDateTime); end; function TImageTableAdapter.GetUpdateDate: TDateTime; begin Result := FDS.FieldByName('DateUpdated').AsDateTime; end; function TImageTableAdapter.GetViewCount: Integer; begin Result := FDS.FieldByName('ViewCount').AsInteger; end; function TImageTableAdapter.GetWidth: Integer; begin Result := FDS.FieldByName('Width').AsInteger; end; procedure TImageTableAdapter.ReadHistogram(var Histogram: THistogrammData); var FBS: TStream; DF: TField; begin DF := FDS.FieldByName('Histogram'); FBS := GetBlobStream(DF, bmRead); try FBS.Seek(0, soFromBeginning); FBS.Read(Histogram, SizeOf(Histogram)); finally F(FBS); end; end; procedure TImageTableAdapter.SetAccess(const Value: Integer); begin FDS.FieldByName('Access').AsInteger := Value; end; procedure TImageTableAdapter.SetAttributes(const Value: Integer); begin FDS.FieldByName('Attr').AsInteger := Value; end; procedure TImageTableAdapter.SetColors(const Value: string); begin FDS.FieldByName('Colors').AsString := Value end; procedure TImageTableAdapter.SetComment(const Value: string); begin SetMemoText('Comment', Value); end; procedure TImageTableAdapter.SetDate(const Value: TDate); begin FDS.FieldByName('DateToAdd').AsDateTime := DateOf(Value); end; procedure TImageTableAdapter.SetFileName(const Value: string); begin FDS.FieldByName('FFileName').AsString := Value; end; procedure TImageTableAdapter.SetFileSize(const Value: Integer); begin FDS.FieldByName('FileSize').AsInteger := Value; end; procedure TImageTableAdapter.SetGroups(const Value: string); begin SetMemoText('Groups', Value); end; procedure TImageTableAdapter.SetHeight(const Value: Integer); begin FDS.FieldByName('Height').AsInteger := Value; end; procedure TImageTableAdapter.SetID(const Value: Integer); begin FDS.FieldByName('ID').AsInteger := Value; end; procedure TImageTableAdapter.SetInclude(const Value: Boolean); begin FDS.FieldByName('Include').AsBoolean := Value; end; procedure TImageTableAdapter.SetIsDate(const Value: Boolean); begin FDS.FieldByName('IsDate').AsBoolean := Value; end; procedure TImageTableAdapter.SetIsTime(const Value: Boolean); begin FDS.FieldByName('IsTime').AsBoolean := Value; end; procedure TImageTableAdapter.SetKeyWords(const Value: string); begin SetMemoText('Keywords', Value); end; procedure TImageTableAdapter.SetLinks(const Value: string); begin SetMemoText('Links', Value); end; procedure TImageTableAdapter.SetLongImageID(const Value: string); begin FDS.FieldByName('StrTh').AsString := LeftStr(Value, 100); end; procedure TImageTableAdapter.SetName(const Value: string); begin FDS.FieldByName('Name').AsString := Value; end; procedure TImageTableAdapter.SetRating(const Value: Integer); begin FDS.FieldByName('Rating').AsInteger := Value; end; procedure TImageTableAdapter.SetRotation(const Value: Integer); begin FDS.FieldByName('Rotated').AsInteger := Value; end; procedure TImageTableAdapter.SetTime(const Value: TTime); begin FDS.FieldByName('aTime').AsDateTime := Value; end; procedure TImageTableAdapter.SetUpdateDate(const Value: TDateTime); begin FDS.FieldByName('DateUpdated').AsDateTime := Value; end; procedure TImageTableAdapter.SetViewCount(const Value: Integer); begin FDS.FieldByName('ViewCount').AsInteger := Value; end; procedure TImageTableAdapter.SetWidth(const Value: Integer); begin FDS.FieldByName('Width').AsInteger := Value; end; end.
(* Category: SWAG Title: OOP/TURBO VISION ROUTINES Original name: 0084.PAS Description: Listbox example for TurboVision Author: BRAD PRENDERGAST Date: 05-30-97 18:17 *) {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Program Name : ListBox2.Pas Written By : Brad Prendergast E-Mail : mrealm@ici.net Web Page : http://www.ici.net/cust_pages/mrealm/BANDP.HTM Program Compilation : Borland Turbo Pascal 7.0 Program Description : This demonstration is of a ListBox that allows the jumping through the list by pressing an alphabetic character and then proceding to the first item in the list that begins with that character. This demonstation is very basic, simple and non-complex. It is meant to be built upon and the reenforcement of the ideas. Any questions or comments feel free to email me. =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} Program ListBoxDemo2; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} uses app, objects, dialogs, views, drivers, menus; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} const cmList = 101; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} type PListWindow = ^TListWindow; TListWindow = object (tdialog) Constructor Init; end; PKeyListBox = ^TKeyListBox; TKeyListBox = object (TListBox) searchcharacter: char; Constructor Init(var bounds : TRect; anumcols : word; ascrollbar : PScrollBar); Procedure HandleEvent(var event: TEvent); Virtual; end; PDemoApp = ^TDemoApp; TDemoApp = object (TApplication) Constructor Init; Procedure InitMenuBar;Virtual; Procedure HandleEvent ( var event : TEvent); Virtual; Procedure List_It; Destructor Done;Virtual; end; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} var {$IFDEF DEBUG} the : longint; {$ENDIF} DemoApp : TDemoApp; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} Constructor TListWindow.Init; Var r : Trect; list : PListBox; scrol : PScrollBar; Begin r.Assign ( 0, 0, 37, 14 ); Inherited Init ( r, 'List Box Demo'); options := options or ofcentered; r.Assign ( 32, 3, 33, 10 ); scrol := New(PScrollBar,Init(r)); Insert(scrol); r.assign( 4,3,32,10); list := New ( PKeyListBox, Init ( r, 1, scrol)); Insert (List); r.Assign( 4, 2, 33, 3); Insert (New(Plabel, init (r, '~S~elect from List : ', list))); r.Assign( 8, 11, 18, 13); insert (New(PButton, init (r, '~O~k', cmOk, bfDefault))); r.Move (11, 0); insert (new(PButton, init (r, '~C~ancel', cmCancel, bfNormal))); selectnext(false); End; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} Constructor TKeyListBox.Init(var bounds : TRect; anumcols : word; ascrollbar : PScrollBar); Begin Inherited Init(bounds, anumcols, ascrollbar); searchcharacter := #0; End; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} Procedure TKeyListBox.HandleEvent ( var event : TEvent); var thechar : char; thestr : pstring; function StartWithCharacter(item: PString): boolean; begin StartWithCharacter := (item <> nil) and (item^ <> '') and ((item^[1] = searchcharacter) or (item^[1] = char(ord(searchcharacter) + 32))); end; Begin if (event.what = evkeydown) then begin if (event.charcode <> #0) and not (event.charcode in [#13, #27, #32]) then begin thechar := event.charcode; if (thechar >= 'a') and (thechar <= 'z') then thechar := char(ord(thechar) - 32); searchcharacter := thechar; end else begin inherited handleevent(event); exit; end; clearevent(event); thestr := list^.firstthat(@startwithcharacter); if (thestr <> nil) then begin focusitem(list^.indexof(thestr)); drawview; end; end else inherited handleevent(event); End; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} Constructor TDemoApp.Init; Begin Inherited Init; End; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} Procedure TDemoApp.InitMenuBar; var r : Trect; Begin GetExtent(r); r.b.y := r.a.y + 1; menubar := New (PMenuBar, Init (r, NewMenu( newsubmenu ('~D~emo', hcNoContext, newmenu( newitem ('~L~istbox', '', kbNoKey, cmList, hcNoContext, nil)), nil)))); End; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} Procedure TDemoApp.HandleEvent (var event : TEvent); Begin if (Event.What = evCommand) then Begin case ( event.command ) of cmList : List_It; end; End; Inherited HandleEvent(event); ClearEvent(event); End; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} Procedure TDemoApp.List_It; type TListBoxRec = record list : PCollection; Selection : word; end; var data : TListBoxRec; name : string; result : integer; bounds : TRect; Begin data.list := new(PStringCollection, Init(20, 10)); data.list^.Insert(NewStr('Anchorage')); data.list^.Insert(NewStr('Atlanta')); data.list^.Insert(NewStr('Baltimore')); data.list^.Insert(NewStr('Boston')); data.list^.Insert(NewStr('New York')); data.list^.Insert(NewStr('New Mexico')); data.list^.Insert(NewStr('Nevada')); data.list^.Insert(NewStr('Chugiak')); data.list^.Insert(NewStr('Detroit')); data.list^.Insert(NewStr('Dallas')); data.list^.Insert(NewStr('Lowell')); data.list^.Insert(NewStr('Ketchican')); data.list^.Insert(NewStr('Haines')); data.list^.Insert(NewStr('Juneau')); data.selection := 0; result := ExecuteDialog(New(PListWindow, Init), @data); name := PString(data.List^.At(data.Selection))^; Dispose(data.List, Done); if (result = cmOK) then begin bounds.Assign(15, 5, 65, 12); InsertWindow(New(PWindow, Init(bounds, Concat('Chosen One: ', name), wnNoNumber))); end; End; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} Destructor TDemoApp.Done; Begin Inherited Done; End; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} Begin DemoApp.Init; DemoApp.Run; DemoApp.Done; End.