text
stringlengths
14
6.51M
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit frmSchemaBrowserList; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, // frmBaseForm, cxPC, cxControls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, StdCtrls, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ComCtrls, ToolWin, cxContainer, cxLabel, ExtCtrls, MemDS, DBAccess, Ora, OraStorage; type TSchemaBrowserListFrm = class(TBaseform) dsList: TDataSource; Panel1: TPanel; lblDescription: TLabel; GridLists: TcxGrid; GridListsDB: TcxGridDBTableView; GridListsLevel1: TcxGridLevel; qList: TOraQuery; imgObject: TImage; procedure GridListsDBCanSelectRecord(Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; var AAllow: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } FObjectName, FObjectOwner : string; FOldObjectType: TDBFormType; procedure GetObjectList; public { Public declarations } procedure Init(ObjName, OwnerName: string); override; end; var SchemaBrowserListFrm: TSchemaBrowserListFrm; implementation {$R *.dfm} uses frmSchemaBrowser, OraScripts, DBQuery, util, OraTable, frmTableProperties, frmTableDetail, OraIndex, frmIndexProperties, OraTriger, frmTriggerProperties, OraView, frmViewProperties, frmViewDetail, OraSequence, frmSequenceProperties, OraProcSource, frmProcedureProperties, OraSynonym, frmSynonymProperties, OraDBLink, frmDatabaseLinkProperties, GenelDM, OraUser, frmUserProperties, OraSysPrivs, OraRole, OraDirectory, OraRollbackSegment, OraTablespace, VisualOptions; procedure TSchemaBrowserListFrm.Init(ObjName, OwnerName: string); begin inherited Show; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); top := 0; left := 0; FObjectName := ObjName; FObjectOwner := OwnerName; lblDescription.Caption := FObjectName; dmGenel.ilSchemaBrowser.GetBitmap(Integer(ObjectType), imgObject.Picture.Bitmap); GetObjectList; end; procedure TSchemaBrowserListFrm.GetObjectList; var str: string; i: integer; begin // if FOldObjectType <> ObjectType then begin FOldObjectType := ObjectType; if ObjectType = dbTable then str := GetTables(FObjectOwner); if ObjectType = dbView then str := GetViews(FObjectOwner); if ObjectType = dbIndexes then str := GetIndexes(FObjectOwner); if ObjectType = dbTriggers then str := GetTriggers(FObjectOwner); if ObjectType = dbSequences then str := GetSequences(FObjectOwner); if ObjectType = dbProcedures then str := GetProcSources('PROCEDURE', FObjectOwner); if ObjectType = dbFunctions then str := GetProcSources('FUNCTION', FObjectOwner); if ObjectType = dbPackages then str := GetProcSources('PACKAGE', FObjectOwner); if ObjectType = dbTypes then str := GetProcSources('TYPE', FObjectOwner); if ObjectType = dbSynonyms then str := GetSynonyms(FObjectOwner); if ObjectType = dbPublicSynonyms then str := GetSynonyms('PUBLIC'); if ObjectType = dbDatabaseLinks then str := GetDBLinks(FObjectOwner); if ObjectType = dbUsers then str := GetUsers(); if ObjectType = dbSysPrivs then str := GetSysPrivs(); if ObjectType = dbRoles then str := GetRoles(); if ObjectType = dbDirectories then str := GetDBDirectories(); if ObjectType = dbRollbackSegments then str := GetRollbackSegments(); if ObjectType = dbTablespaces then str := GetTablespaces(); qList.close; qList.Session := TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).OraSession; qList.SQL.Text := str; qList.Open; GridListsDB.BeginUpdate; GridListsDB.ClearItems; GridListsDB.DataController.CreateAllItems(); for i := 0 to GridListsDB.ColumnCount -1 do GridListsDB.Columns[i].Caption := FormatColumnName(GridListsDB.Columns[i].Caption); //GridListsDB.Columns[0].Summary.FooterFormat GridListsDB.Columns[0].Summary.FooterKind := skCount; GridListsDB.EndUpdate; // GridListsDB.ApplyBestFit(); end; end; procedure TSchemaBrowserListFrm.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; qList.close; // Free; end; procedure TSchemaBrowserListFrm.GridListsDBCanSelectRecord( Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; var AAllow: Boolean); begin inherited; //TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).ObjectName := ds.DataSet.FieldByName('OBJECT_NAME').AsString; end; end.
unit BaiduMapAPI.NaviService.iOS; //author:Xubzhlin //Email:371889755@qq.com //百度地图API iOS导航服务 单元 //官方链接:http://lbsyun.baidu.com/ //TiOSBaiduMapNaviService 百度地图 iOS导航服务 interface uses System.Classes, iOSapi.Foundation, Macapi.ObjectiveC, Macapi.Helpers, BaiduMapAPI.NaviService.CommTypes, BaiduMapAPI.NaviService, iOSapi.BaiduMapAPI_Navi; type TiOSBaiduMapNaviService = class; TBNNaviRoutePlanDelegate = class(TOCLocal, BNNaviRoutePlanDelegate) private [Weak] FNaviService: TiOSBaiduMapNaviService; public procedure routePlanDidFinished(userInfo:NSDictionary); cdecl; procedure searchDidFinished(userInfo:NSDictionary); cdecl; [MethodName('routePlanDidFailedWithError:andUserInfo:')] procedure routePlanDidFailedWithError(error:NSError; userInfo:NSDictionary); cdecl; procedure routePlanDidUserCanceled(userInfo:NSDictionary); cdecl; procedure updateRoadConditionDidFinished(pbData:NSData); cdecl; procedure updateRoadConditionFailed(pbData:NSData); cdecl; constructor Create(NaviService: TiOSBaiduMapNaviService); end; TBNNaviUIManagerDelegate = class(TOCLocal, BNNaviUIManagerDelegate) private [Weak] FNaviService: TiOSBaiduMapNaviService; public function naviPresentedViewController:Pointer; cdecl; [MethodName('extraInfo:extraInfo:')] procedure onExitPage(pageType:BNaviUIType; extraInfo:NSDictionary); cdecl; constructor Create(NaviService: TiOSBaiduMapNaviService); end; // TiOSBaiduMapNaviService = class(TBaiduMapNaviService) private FServices:BNCoreServices; // FRoutePlan:BNRoutePlanManagerProtocol; // FRoutePlanDelegete:TBNNaviRoutePlanDelegate; // FUIManager:BNUIManagerProtocol; // FUIManagerDelegete:TBNNaviUIManagerDelegate; function DoinitDirs:Boolean; procedure DoRoutePlanDidFinished; procedure RealignView; procedure DoInitTTS; protected procedure DoinitService; override; procedure DostartNaviRoutePlan(RoutePlan:TBNRoutePlanNodes); override; procedure DoSetVisible(const Value: Boolean); override; procedure DoUpdateBaiduNaviFromControl; override; end; implementation { TAndroidBaiduMapNaviService } function TiOSBaiduMapNaviService.DoinitDirs: Boolean; begin end; procedure TiOSBaiduMapNaviService.DoinitService; begin FServices:=TBNCoreServices.OCClass.GetInstance; FServices.initServices(StrToNSStr(NaviKey)); end; procedure TiOSBaiduMapNaviService.DoInitTTS; begin end; procedure TiOSBaiduMapNaviService.DoRoutePlanDidFinished; begin // if FUIManager = nil then // FUIManager:=BNUIManagerProtocol(TBNCoreServices.OCClass.UIService); // if FUIManagerDelegete = nil then // FUIManagerDelegete:=TBNNaviUIManagerDelegate.Create(Self); // FUIManager.showPage(BNaviUI_NormalNavi, FUIManagerDelegete, nil); end; procedure TiOSBaiduMapNaviService.DoSetVisible(const Value: Boolean); begin end; procedure TiOSBaiduMapNaviService.DostartNaviRoutePlan( RoutePlan: TBNRoutePlanNodes); var i:Integer; nodesArray:NSMutableArray; Positon:BNPosition; Node:BNRoutePlanNode; begin nodesArray:=TNSMutableArray.Wrap(TNSMutableArray.OCClass.arrayWithCapacity(Length(RoutePlan))); for i := 0 to Length(RoutePlan) - 1 do begin Node:= TBNRoutePlanNode.Create; Node.getPos.setX(RoutePlan[i].location.Latitude); Node.getPos.setY(RoutePlan[i].location.Longitude); Node.getPos.setEType(BNCoordinate_BaiduMapSDK); nodesArray.addObject(Node); end; // if FRoutePlan = nil then // FRoutePlan:=BNRoutePlanManagerProtocol(TBNCoreServices.OCClass.RoutePlanService); // if FRoutePlanDelegete = nil then // FRoutePlanDelegete:=TBNNaviRoutePlanDelegate.Create(Self); // FRoutePlan.startNaviRoutePlan(BNRoutePlanMode_Recommend, nodesArray, nil, FRoutePlanDelegete.GetObjectID, nil); end; procedure TiOSBaiduMapNaviService.DoUpdateBaiduNaviFromControl; begin RealignView; end; procedure TiOSBaiduMapNaviService.RealignView; begin end; { TBNNaviRoutePlanDelegate } constructor TBNNaviRoutePlanDelegate.Create( NaviService: TiOSBaiduMapNaviService); begin inherited Create; FNaviService := NaviService; end; procedure TBNNaviRoutePlanDelegate.routePlanDidFailedWithError(error: NSError; userInfo: NSDictionary); begin end; procedure TBNNaviRoutePlanDelegate.routePlanDidFinished(userInfo: NSDictionary); begin //算了成功 if FNaviService<>nil then FNaviService.DoRoutePlanDidFinished; end; procedure TBNNaviRoutePlanDelegate.routePlanDidUserCanceled( userInfo: NSDictionary); begin end; procedure TBNNaviRoutePlanDelegate.searchDidFinished(userInfo: NSDictionary); begin end; procedure TBNNaviRoutePlanDelegate.updateRoadConditionDidFinished( pbData: NSData); begin end; procedure TBNNaviRoutePlanDelegate.updateRoadConditionFailed(pbData: NSData); begin end; { TBNNaviUIManagerDelegate } constructor TBNNaviUIManagerDelegate.Create( NaviService: TiOSBaiduMapNaviService); begin inherited Create; FNaviService := NaviService; end; function TBNNaviUIManagerDelegate.naviPresentedViewController: Pointer; begin //不用实现默认最上层 end; procedure TBNNaviUIManagerDelegate.onExitPage(pageType: BNaviUIType; extraInfo: NSDictionary); begin //退出UI if FNaviService<>nil then begin FNaviService.RealignView; end; end; end.
unit FFSTabControl; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, extctrls, comctrls, FFSTypes, LabelMenu; const FFSMaxTabs = 99; type TTabAlignment = (taTop, taBottom, taLeft, taRight); TTextHorizontalAlignment = (thaLeft, thaCenter, thaRight); TTextVertialAlignment = (tvaTop, tvaCenter, tvaBottom); TTabChangingEvent = procedure (Sender: TObject; var AllowChange: Boolean) of object; TGetTabHasDataEvent = procedure(Sender:TObject; ATabIndex:integer; var HasData:boolean) of object; TFFSCustomTabControl = class(TCustomControl) private FVisibleCount:integer; FVisibleTabs:array[0..FFSMaxTabs] of boolean; FTabs:TStringList; FTabAlignment: TTabAlignment; FBufferWidth: integer; FTabWidth: integer; FTabHeight: integer; FTabIndex: integer; FTextHorizontalAlignment: TTextHorizontalAlignment; FTextVertialAlignment: TTextVertialAlignment; FOnChange: TNotifyEvent; FOnChanging: TTabChangingEvent; FOnEnter: TNotifyEvent; FOnExit: TNotifyEvent; FShowFocusRectangle: boolean; FOnTabHasData: TGetTabHasDataEvent; FControllist : TList; FPageControl: TPageControl; function GetTabs: TStringList; procedure SetTabs(const Value: TStringList); procedure SetTabAlignment(const Value: TTabAlignment); procedure SetBufferWidth(const Value: integer); procedure SetTabHeight(const Value: integer); procedure SetTabWidth(const Value: integer); procedure SetTabIndex(const Value: integer); procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange; procedure WMLButtonDown(var Msg : TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMSetFocus(var Msg : TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Msg : TWMKillFocus); message WM_KILLFOCUS; procedure WMGetDlgCode(var Msg : TWMGetDlgCode); message WM_GETDLGCODE; procedure WMSIZE(var Message: TWMSIZE); message WM_SIZE; procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED; procedure SetTextHorizontalAlignment(const Value: TTextHorizontalAlignment); procedure SetTextVertialAlignment(const Value: TTextVertialAlignment); procedure PaintTabs; procedure SetOnChange(const Value: TNotifyEvent); procedure SetOnChanging(const Value: TTabChangingEvent); procedure SetOnEnter(const Value: TNotifyEvent); procedure SetOnExit(const Value: TNotifyEvent); procedure SetShowFocusRectangle(const Value: boolean); function GetTabVisible(i: integer): boolean; procedure SetTabVisible(i: integer; const Value: boolean); procedure UpdateVisibleCount; function RealTab(ATab: integer): integer; function TabNext(MoveForward: boolean): integer; procedure SetOnTabHasData(const Value: TGetTabHasDataEvent); procedure OnTabChange(sender:TObject); procedure DisableTabControl(index : integer); procedure EnableTabControl(index : integer); procedure Loaded; override; procedure SetTabControl(i: integer; const Value: TWinControl); procedure SetPageControl(const Value: TPageControl); { Private declarations } protected { Protected declarations } procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure Paint;override; procedure ClearTabControls; property Tabs:TStringList read GetTabs write SetTabs; property TabAlignment:TTabAlignment read FTabAlignment write SetTabAlignment; property BufferWidth:integer read FBufferWidth write SetBufferWidth; property TabHeight:integer read FTabHeight write SetTabHeight; property TabWidth:integer read FTabWidth write SetTabWidth; property TabIndex:integer read FTabIndex write SetTabIndex; property TextHorizontal:TTextHorizontalAlignment read FTextHorizontalAlignment write SetTextHorizontalAlignment; property TextVertialAlignment:TTextVertialAlignment read FTextVertialAlignment write SetTextVertialAlignment; property ShowFocusRectangle:boolean read FShowFocusRectangle write SetShowFocusRectangle default true; property OnChange: TNotifyEvent read FOnChange write SetOnChange; property OnChanging: TTabChangingEvent read FOnChanging write SetOnChanging; property OnEnter: TNotifyEvent read FOnEnter write SetOnEnter; property OnExit: TNotifyEvent read FOnExit write SetOnExit; property OnTabHasData: TGetTabHasDataEvent read FOnTabHasData write SetOnTabHasData; property TabVisible[i:integer]:boolean read GetTabVisible write SetTabVisible; property TabControl[i:integer]:TWinControl write SetTabControl; public { Public declarations } procedure AddTabControls(index: integer; tbcontrol : TWinControl); constructor create(AOwner:TComponent); override; destructor Destroy; override; published { Published declarations } property PageControl:TPageControl read FPageControl write SetPageControl; end; TFFSTabControl = class(TFFSCustomTabControl) public property TabVisible; published property Tabs; property TabAlignment; property BufferWidth; property TabHeight; property TabWidth; property TabIndex; property TextHorizontal; property TextVertialAlignment; property ShowFocusRectangle; property Align; property Enabled; property TabStop; property TabOrder; property Font; property ParentFont; property OnChange; property OnChanging; property OnEnter; property OnExit; property OnTabHasData; end; procedure Register; implementation const FAngle = 2; procedure Register; begin RegisterComponents('FFS Controls', [TFFSTabControl]); end; { TFFSTabControl } constructor TFFSCustomTabControl.create(AOwner: TComponent); var x : integer; begin inherited; controlStyle := ControlStyle - [csNoStdEvents] + [csAcceptsControls]; for x := 0 to FFSMaxTabs do FVisibleTabs[x] := true; Height := 28; Width := 500; FTabs := TStringList.create; FControlList := TList.Create; FTabAlignment := taTop; FBufferWidth := 6; FTabHeight := 22; FTabWidth := 100; FTabIndex := -1; FTextVertialAlignment := tvaCenter; FTextHorizontalAlignment := thaCenter; FShowFocusRectangle := true; tabs.OnChange := OnTabChange; end; destructor TFFSCustomTabControl.Destroy; begin FControlList.Free; FTabs.free; inherited; end; function TFFSCustomTabControl.GetTabs: TStringList; begin result := FTabs; end; function TFFSCustomTabControl.TabNext(MoveForward:boolean):integer; var x,y : integer; vis : boolean; begin if MoveForward then x := 1 else x := FTabs.count - 1; y := tabindex; repeat y := (y + x) mod (FTabs.Count); until TabVisible[y]; result := y; end; procedure TFFSCustomTabControl.KeyDown(var Key: Word; Shift: TShiftState); begin if shift = [] then begin case key of vk_right : if FTabAlignment in [taTop,taBottom] then begin TabIndex := TabNext(true); key := 0; end; vk_left : if FTabAlignment in [taTop,taBottom] then begin TabIndex := TabNext(false); key := 0; end; vk_down : if FTabAlignment in [taLeft,taRight] then begin TabIndex := TabNext(true); key := 0; end; vk_up : if FTabAlignment in [taLeft,taRight] then begin TabIndex := TabNext(false); key := 0; end; end; end; inherited; end; procedure TFFSCustomTabControl.PaintTabs; var r : TRect; origRect : TRect; MiscRect : TRect; x,y : integer; baseleft, basetop : integer; txttop : integer; txtleft : integer; FocusRect : TRect; hasdata: boolean; begin r := GetClientRect; OrigRect := r; MiscRect := r; baseleft := r.left; basetop := r.top; case FTabAlignment of taTop : begin r.Bottom := r.bottom - bufferwidth; r.Top := r.Bottom - TabHeight; OrigRect.Top := r.top; MiscRect.Bottom := R.top; end; taBottom : begin r.Top := r.Top + bufferwidth; r.Bottom := R.Top + Tabheight; OrigRect.Bottom := r.Bottom; MiscRect.Top := R.Bottom; end; taLeft : begin r.Right := r.Right - bufferwidth; r.Left := r.right - TabWidth; OrigRect.Left := r.Left; MiscRect.Right := R.left + 1; end; taRight : begin r.Left := r.Left + bufferwidth; r.Right := r.left + TabWidth; OrigRect.Right := r.Right; MiscRect.Left := R.Right - 1; end; end; Canvas.Brush.color := FFSColor[fcsTabActive]; canvas.FillRect(MiscRect); // Paint the tabs y := -1; for x := 0 to FTabs.count - 1 do begin if TabVisible[x] then begin inc(y); if x = TabIndex then Canvas.brush.Color := FFSColor[fcsTabActive] else Canvas.brush.Color := FFSColor[fcsTabInActive]; case FTabAlignment of taTop, taBottom : begin r.Left := baseleft + (y*tabwidth); r.right := r.left + tabwidth; end; taLeft, taRight : begin r.Top := basetop + (y*tabheight); r.bottom := r.top + tabheight; end; end; canvas.FillRect(r); case FTextHorizontalAlignment of thaLeft : txtleft := 4; thaCenter : txtleft := (TabWidth - canvas.TextWidth(FTabs[x])) div 2; thaRight : txtleft := (TabWidth - canvas.textwidth(FTabs[x]) - 4); end; case FTextVertialAlignment of tvaTop : txttop := 2; tvaCenter : txtTop := (TabHeight - canvas.TextHeight(FTabs[x])) div 2; tvaBottom : txtTop := (TabHeight - canvas.TextHeight(FTabs[x])) - 2; end; if txtLeft < 0 then txtLeft := 4; if txtTop < 0 then txtTop := 2; // text hasdata := false; // check to see if the event for having data is true if assigned(OnTabHasData) then OnTabHasData(self,x,hasdata); case hasdata of true : canvas.Font.Color := FFSColor[fcsTabDataText]; false : canvas.Font.Color := FFSColor[fcsTabNormalText]; end; canvas.TextRect(r, r.left + txtleft, r.top + txtTop, FTabs[x]); canvas.Font.Color := FFSColor[fcsTabNormalText]; // Focus Rectangle // if x = TabIndex then Canvas.brush.Color := FFSColor[fcsTabActive] // else Canvas.brush.Color := FFSColor[fcsTabInActive]; if ShowFocusRectangle then begin if (x = TabIndex) and (Focused) then begin FocusRect := r; InflateRect(FocusRect,-3,-3); canvas.DrawFocusRect(FocusRect); end; end; canvas.pen.Color := clGray; case FTabAlignment of taTop : begin canvas.MoveTo(r.left,r.top); canvas.LineTo(r.left,r.bottom-FAngle); canvas.LineTo(r.left+FAngle,r.bottom); canvas.LineTo(r.right-FAngle, r.bottom); canvas.LineTo(r.right, r.bottom-FAngle); canvas.LineTo(r.right, r.top); if x <> TabIndex then canvas.LineTo(r.left, r.top); canvas.Pixels[r.Left,r.bottom] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Left,r.bottom-1] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Left+1,r.bottom] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Right,r.bottom] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Right-1,r.bottom] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Right,r.bottom-1] := FFSColor[fcsTabBackGround]; end; taBottom : begin canvas.MoveTo(r.left, r.bottom-1); canvas.LineTo(r.left, r.top+FAngle); canvas.LineTo(r.left+FAngle,r.top); canvas.LineTo(r.right-FAngle, r.top); canvas.LineTo(r.right, r.top+FAngle); canvas.LineTo(r.right, r.bottom-1); if x <> TabIndex then canvas.LineTo(r.left, r.bottom-1); canvas.Pixels[r.Left,r.top] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.left+1,r.top] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.left,r.top+1] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Right,r.top] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Right-1,r.top] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Right,r.top+1] := FFSColor[fcsTabBackGround]; end; taRight : begin canvas.MoveTo(r.right-1, r.top); canvas.LineTo(r.left+FAngle, r.top); canvas.LineTo(r.left,r.top+FAngle); canvas.LineTo(r.left, r.bottom-FAngle); canvas.LineTo(r.left+FAngle, r.Bottom); canvas.LineTo(r.right-1, r.bottom); if x <> TabIndex then canvas.LineTo(r.right-1, r.top); canvas.Pixels[r.Left,r.top] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Left+1,r.top] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Left,r.top+1] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Left,r.bottom] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Left+1,r.bottom] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.Left,r.bottom-1] := FFSColor[fcsTabBackGround]; end; taLeft : begin canvas.MoveTo(r.left, r.top); canvas.LineTo(r.right-FAngle, r.top); canvas.LineTo(r.right,r.top+FAngle); canvas.LineTo(r.right, r.bottom-FAngle); canvas.LineTo(r.right-FAngle, r.Bottom); canvas.LineTo(r.left, r.bottom); if x <> TabIndex then canvas.LineTo(r.left, r.top); canvas.Pixels[r.right,r.top] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.right,r.top+1] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.right-1,r.top] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.right,r.bottom] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.right,r.bottom-1] := FFSColor[fcsTabBackGround]; canvas.Pixels[r.right-1,r.bottom] := FFSColor[fcsTabBackGround]; end; end; end; end; // done with all the boxes, just need to finish the line case FTabAlignment of taTop : begin canvas.MoveTo(r.Right, r.Top); canvas.LineTo(origRect.Right, origRect.top); end; taBottom : begin canvas.MoveTo(r.Right, r.Bottom-1); canvas.LineTo(origRect.Right, origRect.Bottom-1); end; taLeft : begin canvas.MoveTo(r.left, r.bottom); canvas.LineTo(origRect.Left, origRect.Bottom); end; taRight : begin canvas.MoveTo(r.Right-1, r.bottom); canvas.LineTo(origRect.Right-1, origRect.Bottom); end; end; end; procedure TFFSCustomTabControl.Paint; var r : TRect; begin Canvas.brush.Color := FFSColor[fcsTabBackGround]; r := GetClientRect; canvas.FillRect(r); PaintTabs; end; procedure TFFSCustomTabControl.SetBufferWidth(const Value: integer); begin FBufferWidth := Value; Invalidate; end; procedure TFFSCustomTabControl.SetTabAlignment(const Value: TTabAlignment); begin FTabAlignment := Value; Invalidate; end; procedure TFFSCustomTabControl.SetTabHeight(const Value: integer); begin if Value > 5 then begin FTabHeight := Value; Invalidate; end; end; procedure TFFSCustomTabControl.SetTabIndex(const Value: integer); var allow:boolean; oldindex : integer; y : integer; begin oldindex := FTabIndex; if (value < -1) or (value >= FTabs.Count) then exit; if (value <= FFSMaxTabs) and (not TabVisible[value]) then exit; if value = FTabIndex then exit; Allow := true; if Assigned(FPageControl) then begin if FPageControl.PageCount > value then FPageControl.ActivePageIndex := Value; end; if Assigned(OnChanging) then OnChanging(self, Allow); if Allow then FTabIndex := Value; if oldindex <> FTabIndex then begin DisableTabControl(oldindex); EnableTabControl(FTabIndex); PaintTabs; if Assigned(OnChange) then OnChange(self); end; end; procedure TFFSCustomTabControl.SetTabs(const Value: TStringList); begin FTabs.assign(Value); while (FTabIndex >= FTabs.Count) do dec(FTabIndex); ClearTabControls; Invalidate; end; procedure TFFSCustomTabControl.SetTabWidth(const Value: integer); begin if Value > 5 then begin FTabWidth := Value; Invalidate; end; end; procedure TFFSCustomTabControl.SetTextHorizontalAlignment(const Value: TTextHorizontalAlignment); begin FTextHorizontalAlignment := Value; Invalidate; end; procedure TFFSCustomTabControl.SetTextVertialAlignment(const Value: TTextVertialAlignment); begin FTextVertialAlignment := Value; Invalidate; end; procedure TFFSCustomTabControl.WMKillFocus(var Msg: TWMKillFocus); begin PaintTabs;//Invalidate; Msg.Result := 0; if assigned(OnExit) then OnExit(self); end; procedure TFFSCustomTabControl.WMLButtonDown(var Msg: TWMLButtonDown); var r : TRect; pt : TPoint; ti : integer; begin if not Enabled then exit; if not Focused and Enabled then SetFocus; r := GetClientRect; pt := SmallPointToPoint(msg.pos); case FTabAlignment of taTop : r.Bottom := r.bottom - bufferwidth; taBottom : r.Top := r.Top + bufferwidth; taLeft : r.Right := r.Right - bufferwidth; taRight : r.Left := r.Left + bufferwidth; end; case FTabAlignment of taTop, taBottom : r.Right := r.left + (FVisibleCount * FTabWidth); taLeft, taRight : r.Bottom := r.Top + (FVisibleCount * FTabHeight); end; if (pt.X >= r.Left) and (pt.x <= r.right) and (pt.y >= r.top) and (pt.y <= r.bottom) then begin case FTabAlignment of taTop, taBottom : ti := pt.x div FTabWidth; taLeft, taRight : ti := pt.y div FTabHeight; end; end; TabIndex := RealTab(ti); Msg.Result := 0; end; function TFFSCustomTabControl.RealTab(ATab:integer):integer; var x,y : integer; begin y := -1; x := 0; while (x < tabs.Count) and (y < ATab) do begin if TabVisible[x] then inc(y); if y < ATab then inc(x); end; result := x; end; procedure TFFSCustomTabControl.WMSetFocus(var Msg: TWMSetFocus); begin PaintTabs;//Invalidate; msg.Result := 0; if assigned(OnEnter) then OnEnter(self); end; procedure TFFSCustomTabControl.WMGetDlgCode(var Msg: TWMGetDlgCode); begin inherited; Msg.Result := Msg.Result or DLGC_WANTCHARS or DLGC_WANTARROWS; end; procedure TFFSCustomTabControl.SetOnChange(const Value: TNotifyEvent); begin FOnChange := Value; end; procedure TFFSCustomTabControl.SetOnChanging(const Value: TTabChangingEvent); begin FOnChanging := Value; end; procedure TFFSCustomTabControl.MsgFFSColorChange(var Msg: TMessage); begin Invalidate; end; procedure TFFSCustomTabControl.SetOnEnter(const Value: TNotifyEvent); begin FOnEnter := Value; end; procedure TFFSCustomTabControl.SetOnExit(const Value: TNotifyEvent); begin FOnExit := Value; end; procedure TFFSCustomTabControl.WMSIZE(var Message: TWMSIZE); begin invalidate; end; procedure TFFSCustomTabControl.SetShowFocusRectangle(const Value: boolean); begin if value = FShowFocusRectangle then exit; FShowFocusRectangle := Value; Invalidate; end; function TFFSCustomTabControl.GetTabVisible(i: integer): boolean; var x : integer; begin x := tabs.count - 1; if x > FFSMaxTabs then x := FFSMaxTabs; if i in [0..x] then result := FVisibleTabs[i] else result := true; end; procedure TFFSCustomTabControl.UpdateVisibleCount; var x,y : integer; begin x := tabs.count - 1; if x > FFSMaxTabs then x := FFSMaxTabs; FVisibleCount := tabs.count; for y := 0 to x do if not FVisibleTabs[y] then dec(FVisibleCount); end; procedure TFFSCustomTabControl.SetTabVisible(i: integer; const Value: boolean); var x,y : integer; begin x := tabs.count - 1; if x > FFSMaxTabs then x := FFSMaxTabs; if i in [0..x] then FVisibleTabs[i] := value; UpdateVisibleCount; end; procedure TFFSCustomTabControl.SetOnTabHasData( const Value: TGetTabHasDataEvent); begin FOnTabHasData := Value; end; procedure TFFSCustomTabControl.OnTabChange(sender: TObject); begin UpdateVisibleCount; end; procedure TFFSCustomTabControl.AddTabControls(index: integer; tbcontrol: TWinControl); begin if index <= -1 then exit; FControlList.Items[index] := tbcontrol; tbcontrol.Enabled := (index = FTabIndex); end; procedure TFFSCustomTabControl.DisableTabControl(index: integer); begin if (index <= -1) or (FControllist.Count = 0) or (index > FControlList.Count -1) then exit; if assigned(FControllist.Items[index]) then TWinControl(FControllist.Items[index]).Enabled := False; end; procedure TFFSCustomTabControl.EnableTabControl(index: integer); begin if (index <= -1) or (FControllist.Count = 0) or (index > FControlList.Count -1) then exit; if assigned(FControllist.Items[index]) then begin TWinControl(FControllist.Items[index]).Enabled := True; tWinControl(FControlList.Items[index]).BringToFront; end; end; procedure TFFSCustomTabControl.CMEnabledChanged(var Message: TMessage); var i : integer; begin if (csDesigning in ComponentState) then exit; if assigned(FControllist.Items[FTabIndex]) then begin TWinControl(FControllist.Items[FTabIndex]).Enabled := Enabled; for i:= 0 to ControlCount -1 do if Controls[I] is TLabelMenu then TLabelMenu(Controls[i]).Enabled := Enabled; end; end; procedure TFFSCustomTabControl.Loaded; var i : integer; begin inherited; for i := 0 to FTabs.Count -1 do FControllist.Add(nil); end; procedure TFFSCustomTabControl.ClearTabControls; var i : integer; begin FControllist.Clear; for i:=0 to FTabs.Count - 1 do FControlList.Add(nil); end; procedure TFFSCustomTabControl.SetTabControl(i: integer; const Value: TWinControl); begin FControllist.Items[i] := Value; end; procedure TFFSCustomTabControl.SetPageControl(const Value: TPageControl); begin FPageControl := Value; end; end.
{$I ok_sklad.inc} unit RemainsAtWH; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, dxCntner6, dxEditor6, StdCtrls, ActnList, ssBaseTypes, ssFormStorage, cxCheckBox, cxControls, cxContainer, cxEdit, cxTextEdit, cxLookAndFeelPainters, cxButtons, ssBaseDlg, ssBevel, ImgList, ssSpeedButton, ssPanel, ssGradientPanel, xButton, dxTL6, dxDBCtrl6, dxDBGrid6, ssDBGrid, DB, DBClient, ssClientDataSet, prTypes, TB2Item, Menus; type TfrmRemainsAtWH = class(TBaseDlg) aSelectWH: TAction; btnMove: TssSpeedButton; bvlMain: TssBevel; cdsRsv_Temp: TssClientDataSet; cdsWHouse: TssClientDataSet; cdsWHouseNAME: TStringField; cdsWHouseREMAIN: TFloatField; cdsWHousereserved: TFloatField; cdsWHouseRSV: TFloatField; cdsWHouseWID: TIntegerField; pmMain: TTBPopupMenu; srcWHouse: TDataSource; TBItem19: TTBItem; grdWHouse: TssDBGrid; colWID: TdxDBGridColumn; colWName: TdxDBGridColumn; colWRemain: TdxDBGridColumn; colWFree: TdxDBGridColumn; colWReserved: TdxDBGridColumn; panEmpty: TPanel; procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure aSelectWHExecute(Sender: TObject); procedure btnMoveClick(Sender: TObject); procedure cdsWHouseBeforeOpen(DataSet: TDataSet); procedure cdsWHouseCalcFields(DataSet: TDataSet); procedure colWFreeGetText(Sender: TObject; ANode: TdxTreeListNode; var AText: String); procedure colWRemainGetText(Sender: TObject; ANode: TdxTreeListNode; var AText: String); procedure colWReservedGetText(Sender: TObject; ANode: TdxTreeListNode; var AText: String); procedure DataModified(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure grdWHouseCustomDrawCell(Sender: TObject; ACanvas: TCanvas; ARect: TRect; ANode: TdxTreeListNode; AColumn: TdxTreeListColumn; ASelected, AFocused, ANewItemRow: Boolean; var AText: String; var AColor: TColor; AFont: TFont; var AAlignment: TAlignment; var ADone: Boolean); procedure grdWHouseDblClick(Sender: TObject); procedure grdWHouseKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); protected procedure setid(const Value: integer); override; procedure SetParentName(const Value: string); override; public ParentHandle: HWND; procedure SetCaptions; override; end; var frmRemainsAtWH: TfrmRemainsAtWH; implementation uses ssBaseConst, prConst, ClientData, prFun, ssCallbackConst, xLngManager, ssDateUtils, ssFun, MatMove, udebug; var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; {$R *.dfm} //============================================================================================== procedure TfrmRemainsAtWH.setid(const Value: integer); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TfrmRemainsAtWH.setid') else _udebug := nil;{$ENDIF} FID := Value; DSRefresh(cdsWHouse, 'wid', 0); panEmpty.Visible := cdsWHouse.IsEmpty; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.FormCloseQuery(Sender: TObject; var CanClose: Boolean); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TfrmRemainsAtWH.FormCloseQuery') else _udebug := nil;{$ENDIF} if ModalResult in [mrOK] then SendMessage(MainHandle, WM_REFRESH, cdsWHouse.FieldByName('wid').AsInteger, Integer(-20)); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.ActionListUpdate') else _udebug := nil;{$ENDIF} aOk.Enabled := (grdWHouse.Count > 0); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.DataModified(Sender: TObject); //{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin //{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.DataModified') else _udebug := nil;{$ENDIF} FModified:=True; //{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.SetCaptions; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.SetCaptions') else _udebug := nil;{$ENDIF} inherited; with dmData.Lng do begin Self.Caption := GetRS('fmWMat', 'MatsAtWH'); aOk.Caption := GetRS('Common', 'Select'); btnMove.Hint := GetRS('fmWMat', 'MoveInfoEx'); panEmpty.Caption := GetRS('fmWMat', 'NoMatAtWH'); aSelectWH.Caption := GetRS('fmWMat', 'SelectWH'); colWName.Caption := GetRS('fmWMat', 'Title'); colWRemain.Caption := GetRS('fmWMat', 'AllRemain'); colWFree.Caption := GetRS('fmWMat', 'Free'); colWReserved.Caption := GetRS('fmWMat', 'Reserved'); end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.SetParentName(const Value: string); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.SetParentName') else _udebug := nil;{$ENDIF} FParentName := Value; SetCaptions; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.cdsWHouseBeforeOpen(DataSet: TDataSet); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.cdsWHouseBeforeOpen') else _udebug := nil;{$ENDIF} DSRefresh(cdsRsv_Temp, 'posid', 0); with (DataSet as TssClientDataSet).Params do begin ParamByName('matid').AsInteger := FID; ParamByName('ondate').AsDateTime := LastSecondInDay(Self.OnDate); ParamByName('wh').AsString := AllowedWH; ParamByName('wid').AsInteger := 0; ParamByName('kaid').AsInteger := 0; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.cdsWHouseCalcFields(DataSet: TDataSet); var FRsv: Extended; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.cdsWHouseCalcFields') else _udebug := nil;{$ENDIF} FRsv := DataSet.FieldByName('Rsv').AsFloat; with cdsRsv_Temp do if Active then begin First; while not Eof do begin if ((FieldByName('visible').AsInteger = 1) or ((FieldByName('visible').AsInteger = 0) and (fieldbyname('addr').AsInteger = ServerAddr))) and (FieldByname('wid').AsInteger = cdsWHouse.FieldByName('wid').AsInteger) and (FieldByname('matid').AsInteger = FID) then FRsv := FRsv + fieldbyname('amount').asFloat; Next; end; end; DataSet.FieldByName('reserved').AsFloat := FRsv; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.colWRemainGetText(Sender: TObject; ANode: TdxTreeListNode; var AText: String); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.colWRemainGetText') else _udebug := nil;{$ENDIF} try AText := FormatFloat(MatDisplayFormat, RoundToA(StrToFloat(AText), MatDisplayDigits)); except end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.colWFreeGetText(Sender: TObject; ANode: TdxTreeListNode; var AText: String); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.colWFreeGetText') else _udebug := nil;{$ENDIF} try AText := FormatFloat(MatDisplayFormat, RoundToA(ANode.Values[colWRemain.Index] - ANode.Values[colWReserved.Index], MatDisplayDigits)); except end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.colWReservedGetText(Sender: TObject; ANode: TdxTreeListNode; var AText: String); var FRsv: Extended; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.colWReservedGetText') else _udebug := nil;{$ENDIF} try FRsv := ANode.Values[colWReserved.Index]; except FRsv := 0; end; AText := FormatFloat(MatDisplayFormat, RoundToA(FRsv, MatDisplayDigits)); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.grdWHouseCustomDrawCell(Sender: TObject; ACanvas: TCanvas; ARect: TRect; ANode: TdxTreeListNode; AColumn: TdxTreeListColumn; ASelected, AFocused, ANewItemRow: Boolean; var AText: String; var AColor: TColor; AFont: TFont; var AAlignment: TAlignment; var ADone: Boolean); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.grdWHouseCustomDrawCell') else _udebug := nil;{$ENDIF} if UseGridOddColor and not ASelected and Odd(ANode.AbsoluteIndex) then AColor := GridOddLinesColor; if (ANode.Values[colWReserved.Index] > 0) and (AColumn = colWReserved) then AFont.Color := clRed; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.grdWHouseDblClick(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.grdWHouseDblClick') else _udebug := nil;{$ENDIF} if grdWHouse.Count > 0 then aOK.Execute; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.grdWHouseKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.grdWHouseKeyDown') else _udebug := nil;{$ENDIF} if Key = 13 then begin Key := 0; grdWHouseDblClick(grdWHouse); end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.btnMoveClick(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.btnMoveClick') else _udebug := nil;{$ENDIF} if grdWHouse.Count = 0 then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; with TfrmMatMove.Create(nil) do try ParentNameEx := 'fmWMat'; OnDate := Self.OnDate; WID := cdsWHouse.FieldByName('wid').AsInteger; ID := FID; ShowModal; finally Free; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmRemainsAtWH.aSelectWHExecute(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmRemainsAtWH.aSelectWHExecute') else _udebug := nil;{$ENDIF} grdWHouseDblClick(grdWHouse); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; initialization {$IFDEF UDEBUG} Debugging := False; DEBUG_unit_ID := debugRegisterUnit('RemainsAtWH', @Debugging, DEBUG_group_ID); {$ENDIF} finalization //{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF} end.
(* this file is a part of audio components suite see the license file for more details. you can contact me at mail@z0m3ie.de this is an sample unit for an driver *) unit driver; interface uses ACS_Audio,SysUtils, Classes, ACS_Types, ACS_Classes, ACS_Strings; const LATENCY = 25; type TOwnAudioOut = class(TACSBaseAudioOut) private EndOfInput, StartInput : Boolean; FDeviceNumber : Integer; FDeviceCount : Integer; procedure SetDevice(Ch : Integer);override; function GetDeviceInfo : TACSDeviceInfo;override; function GetDeviceCount : Integer;override; protected procedure Done; override; function DoOutput(Abort : Boolean):Boolean; override; procedure Prepare; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Pause;override; procedure Resume;override; end; TOwnAudioIn = class(TACSBaseAudioIn) private FDeviceNumber : Integer; FDeviceCount : Integer; FBPS, FChan, FFreq : Integer; FOpened : Integer; FRecTime : Integer; procedure SetDevice(i : Integer);override; procedure OpenAudio; procedure CloseAudio; function GetBPS : Integer; override; function GetCh : Integer; override; function GetSR : Integer; override; function GetTotalTime : real; override; procedure SetRecTime(aRecTime : Integer); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetData(Buffer : Pointer; BufferSize : Integer): Integer; override; procedure Init; override; procedure Flush; override; end; implementation procedure TOwnAudioOut.Prepare; begin FInput.Init; FBuffer := AllocMem(FBufferSize); StartInput := True; EndOfInput := False; //Init your output device here end; procedure TOwnAudioOut.Done; begin //Flush your output device here Finput.Flush; FreeMem(FBuffer); end; function TOwnAudioOut.DoOutput(Abort : Boolean):Boolean; var Len, offs, lb : Integer; Stat : LongWord; Res : HRESULT; PlayTime, CTime : LongWord; begin Result := True; if not Busy then Exit; if not CanOutput then begin Result := False; Exit; end; if StartInput then begin Len := 0; while Len < FBufferSize do begin offs := FInput.GetData(@FBuffer^[Len], FBufferSize-Len); if offs = 0 then begin EndOfInput := True; Break; end; Inc(Len, offs); end; //Do Output Len bytes from FBuffer^ StartInput := False; end; if Abort then begin //Stop your output device CanOutput := False; Result := False; Exit; end; if EndOfInput then begin CanOutput := False; //Stop your output device Result := False; Exit; end; end; constructor TOwnAudioOut.Create; begin inherited Create(AOwner); FBufferSize := $40000; //enumerate devices and set Devicecount FDeviceCount := 0; end; destructor TOwnAudioOut.Destroy; begin //Wahtever end; procedure TOwnAudioOut.Pause; begin if EndOfInput then Exit; //Pause end; procedure TOwnAudioOut.Resume; begin if EndOfInput then Exit; //waht schoud i say ? end; procedure TOwnAudioOut.SetDevice(Ch: Integer); begin FBaseChannel := Ch; end; function TOwnAudioOut.GetDeviceInfo: TACSDeviceInfo; begin if (FBaseChannel >= FDeviceCount) then exit; //return an Deviceinfo end; function TOwnAudioOut.GetDeviceCount: Integer; begin Result := FDeviceCount; end; constructor TOwnAudioIn.Create; begin inherited Create(AOwner); FBPS := 8; FChan := 1; FFreq := 8000; FSize := -1; BufferSize := $2000; //enumerate devices and set Devicecount FDeviceCount := 0; end; destructor TOwnAudioIn.Destroy; begin //whatever inherited Destroy; end; procedure TOwnAudioIn.OpenAudio; var Res : HResult; BufSize : Integer; begin BufSize := BufferSize; if FOpened = 0 then begin //Init your In put device end; Inc(FOpened); end; procedure TOwnAudioIn.CloseAudio; begin if FOpened = 1 then begin //Flush your Input device end; if FOpened > 0 then Dec(FOpened); end; function TOwnAudioIn.GetBPS : Integer; begin Result := FBPS; end; function TOwnAudioIn.GetCh : Integer; begin Result := FChan; end; function TOwnAudioIn.GetSR : Integer; begin Result := FFreq; end; procedure TOwnAudioIn.Init; begin if Busy then raise EACSException.Create(strBusy); if (FDeviceNumber >= FDeviceCount) then raise EACSException.Create(Format(strChannelnotavailable,[FDeviceNumber])); if FRecTime > 0 then FBytesToRead := FRecTime*FFreq*FChan*(FBPS div 8); BufEnd := 0; BufStart := 1; FPosition := 0; Busy := True; FSize := FBytesToRead; OpenAudio; end; procedure TOwnAudioIn.Flush; begin CloseAudio; Busy := False; end; function TOwnAudioIn.GetData(Buffer : Pointer; BufferSize : Integer): Integer; var l : Integer; begin if not Busy then raise EACSException.Create(strStreamnotopen); if (FBytesToRead >=0) and (FPosition >= FBytesToRead) then begin Result := 0; Exit; end; if BufStart >= BufEnd then begin BufStart := 0; //Read Buffersize bytes from your input device and convert to PCM //l is the real readed size maybe you cant ead the full buffer jet BufEnd := l; end; if BufferSize < (BufEnd - BufStart) then Result := BufferSize else Result := BufEnd - BufStart; Move(FBuffer[BufStart], Buffer^, Result); Inc(BufStart, Result); Inc(FPosition, Result); end; procedure TOwnAudioIn.SetRecTime; begin FRecTime := aRecTime; if FRecTime > 0 then FBytesToRead := FRecTime*FFreq*FChan*(FBPS div 8) else FBytesToRead := -1; end; procedure TOwnAudioIn.SetDevice(i : Integer); begin FDeviceNumber := i end; function TOwnAudioIn.GetTotalTime : real; var BytesPerSec : Integer; begin BytesPerSec := FFreq*FChan*(FBPS div 8); Result := FBytesToRead/BytesPerSec; end; initialization RegisterAudioOut('My Drivers Name',TOwnAudioOut,LATENCY); RegisterAudioIn('My Drivers Name',TOwnAudioIn,LATENCY); finalization end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.ProgressDialog.Win; interface uses Winapi.ShlObj, Winapi.ActiveX, FGX.ProgressDialog.Types; type { TWunProgressDialogService } TWunProgressDialogService = class (TInterfacedObject, IFGXProgressDialogService) public { IFGXProgressDialogService } function CreateNativeProgressDialog(const AOwner: TObject): TfgNativeProgressDialog; function CreateNativeActivityDialog(const AOwner: TObject): TfgNativeActivityDialog; end; TWinNativeProgressDialog = class (TfgNativeProgressDialog) private FNativeDialog: IProgressDialog; protected procedure ProgressChanged; override; procedure TitleChanged; override; procedure MessageChanged; override; public constructor Create(const AOwner: TObject); override; destructor Destroy; override; procedure ResetProgress; override; procedure Show; override; procedure Hide; override; end; procedure RegisterService; procedure UnregisterService; var ProgressDialogService: TWunProgressDialogService; implementation uses System.SysUtils, FMX.Platform, FMX.Types, FMX.Forms, FMX.Platform.Win, Winapi.Windows; { TWunProgressDialogService } function TWunProgressDialogService.CreateNativeActivityDialog(const AOwner: TObject): TfgNativeActivityDialog; begin Result := nil; end; function TWunProgressDialogService.CreateNativeProgressDialog(const AOwner: TObject): TfgNativeProgressDialog; begin Result := TWinNativeProgressDialog.Create(AOwner); end; { TWinNativeProgressDialog } constructor TWinNativeProgressDialog.Create(const AOwner: TObject); begin inherited; if S_OK <> CoCreateInstance(CLSID_ProgressDialog, nil, CLSCTX_INPROC_SERVER, IID_IProgressDialog, FNativeDialog) then raise Exception.Create('Невозможно создать нативный диалог'); end; destructor TWinNativeProgressDialog.Destroy; begin FNativeDialog := nil; inherited Destroy; end; procedure TWinNativeProgressDialog.Hide; begin FNativeDialog.StopProgressDialog; end; procedure TWinNativeProgressDialog.MessageChanged; begin FNativeDialog.SetLine(1, StringToOleStr(Message), False, nil); end; procedure TWinNativeProgressDialog.ProgressChanged; begin FNativeDialog.SetProgress(Cardinal(Round(Progress)), 100); end; procedure TWinNativeProgressDialog.ResetProgress; begin inherited ResetProgress; FNativeDialog.SetProgress(0, 100); end; procedure TWinNativeProgressDialog.Show; var WindowsHandle: HWND; REs: HRESULT; begin Assert(Screen.ActiveForm <> nil); Assert(Screen.ActiveForm.Handle <> nil); FNativeDialog.SetTitle(StringToOleStr(Title)); FNativeDialog.SetProgress(Cardinal(Round(Progress)), 100); FNativeDialog.SetLine(1, StringToOleStr(Message), False, nil); WindowsHandle := WindowHandleToPlatform(Screen.ActiveForm.Handle).Wnd; FNativeDialog.StartProgressDialog(WindowsHandle, nil, PROGDLG_MODAL or PROGDLG_AUTOTIME or PROGDLG_NOCANCEL, nil); Application.ProcessMessages; end; procedure TWinNativeProgressDialog.TitleChanged; begin inherited; end; procedure RegisterService; begin if TOSVersion.Check(2, 0) then begin ProgressDialogService := TWunProgressDialogService.Create; TPlatformServices.Current.AddPlatformService(IFGXProgressDialogService, ProgressDialogService); end; end; procedure UnregisterService; begin TPlatformServices.Current.RemovePlatformService(IFGXProgressDialogService); end; end.
unit GetVehiclesUnit; interface uses SysUtils, BaseExampleUnit; type TGetVehicles = class(TBaseExample) public procedure Execute; end; implementation uses VehicleUnit; procedure TGetVehicles.Execute; var ErrorString: String; Vehicles: TVehicleList; begin Vehicles := Route4MeManager.Vehicle.GetList(ErrorString); try WriteLn(''); if (Vehicles.Count > 0) then WriteLn(Format('GetVehicles executed successfully, %d vehicles returned', [Vehicles.Count])) else WriteLn(Format('GetVehicles error: "%s"', [ErrorString])); finally FreeAndNil(Vehicles); end; end; end.
unit fmDameWare; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ADC.GlobalVar, ADC.ADObject, ADC.Common, ADC.Types, Vcl.ExtCtrls, System.StrUtils, ADC.LDAP, ADC.AD, Winapi.ActiveX, ActiveDs_TLB, System.RegularExpressions; type TForm_DameWare = class(TForm) ComboBox_DMRC: TComboBox; CheckBox_DMRC_Auto: TCheckBox; CheckBox_DMRC_Driver: TCheckBox; RadioButton_DMRC_Viewer: TRadioButton; RadioButton_DMRC_RDP: TRadioButton; Edit_DMRC_dom: TEdit; Label_DMRC_Domain: TLabel; Edit_DMRC_pass: TEdit; Label_DMRC_Password: TLabel; Edit_DMRC_user: TEdit; Label_DMRC_Username: TLabel; Label_DMRC_Authorization: TLabel; ComboBox_Computer: TComboBox; Label_DMRC_ComputerName: TLabel; Button_Control: TButton; Button_View: TButton; Button_Cancel: TButton; Bevel1: TBevel; Button_GetIP: TButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ComboBox_DMRCSelect(Sender: TObject); procedure RadioButton_DMRC_RDPClick(Sender: TObject); procedure RadioButton_DMRC_ViewerClick(Sender: TObject); procedure Button_CancelClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Button_ControlClick(Sender: TObject); procedure Button_ViewClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Button_GetIPClick(Sender: TObject); private FDMRC_PrevAuth: SmallInt; FCallingForm: TForm; FObj: TADObject; procedure RefreshFields; procedure SetCallingForm(const Value: TForm); procedure SetADObject(const Value: TADObject); function GetUserWorkstations(ARootDSE: IADs; ADN: string): string; overload; function GetUserWorkstations(ALDAP: PLDAP; ADN: string): string; overload; public procedure AddHostName(AValue: string); property CallingForm: TForm write SetCallingForm; property ADObject: TADObject write SetADObject; end; var Form_DameWare: TForm_DameWare; implementation {$R *.dfm} uses dmDataModule; { TForm_DameWare } procedure TForm_DameWare.AddHostName(AValue: string); var i: Integer; infoIP: PIPAddr; infoDHCP: PDHCPInfo; fqdn: string; begin if not AValue.IsEmpty then begin i := ComboBox_Computer.Items.IndexOf(AValue); if i < 0 then begin i := ComboBox_Computer.Items.Add(AValue); // New(infoIP); // New(infoDHCP); // GetIPAddress(AValue, infoIP); // if Pos('.', infoIP^.FQDN) > 0 // then fqdn := infoIP^.FQDN // else fqdn := AValue; //// GetDHCPInfo(LowerCase(fqdn), infoDHCP); // GetDHCPInfoEx(LowerCase(fqdn), infoDHCP); // if not (infoIP^.v4.IsEmpty and infoDHCP.IPAddress.v4.IsEmpty) then // begin // ComboBox_Computer.Items.Insert( // 0, // IfThen(infoIP^.v4.IsEmpty, infoDHCP.IPAddress.v4, infoIP^.v4) // ); // i := 0; // end; // Dispose(infoIP); // Dispose(infoDHCP); end; ComboBox_Computer.ItemIndex := i; end; end; procedure TForm_DameWare.Button_CancelClick(Sender: TObject); begin Close; end; procedure TForm_DameWare.Button_ControlClick(Sender: TObject); begin DameWareMRC_Connect( apDMRC_Executable, ComboBox_Computer.Text, ComboBox_DMRC.ItemIndex, Edit_DMRC_user.Text, Edit_DMRC_pass.Text, Edit_DMRC_dom.Text, CheckBox_DMRC_Driver.Checked, RadioButton_DMRC_RDP.Checked, CheckBox_DMRC_Auto.Checked, False ); end; procedure TForm_DameWare.Button_GetIPClick(Sender: TObject); var regEx: TRegEx; pcName: string; infoIP: PIPAddr; infoDHCP: PDHCPInfo; begin if ComboBox_Computer.Text = '' then Exit; regEx := TRegEx.Create('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', [roNone]); if regEx.IsMatch(ComboBox_Computer.Text) then pcName := ComboBox_Computer.Text else pcName := LowerCase(ComboBox_Computer.Text + '.' + SelectedDC.DomainDnsName); New(infoIP); New(infoDHCP); GetIPAddress(pcName, infoIP); // GetDHCPInfo(pcName, infoDHCP); GetDHCPInfoEx(pcName, infoDHCP); ComboBox_Computer.Text := IfThen( infoIP^.v4.IsEmpty, infoDHCP^.IPAddress.v4, infoIP^.v4 ); Dispose(infoIP); Dispose(infoDHCP); end; procedure TForm_DameWare.Button_ViewClick(Sender: TObject); begin DameWareMRC_Connect( apDMRC_Executable, ComboBox_Computer.Text, ComboBox_DMRC.ItemIndex, Edit_DMRC_user.Text, Edit_DMRC_pass.Text, Edit_DMRC_dom.Text, CheckBox_DMRC_Driver.Checked, RadioButton_DMRC_RDP.Checked, CheckBox_DMRC_Auto.Checked, True ); end; procedure TForm_DameWare.ComboBox_DMRCSelect(Sender: TObject); begin RefreshFields; end; procedure TForm_DameWare.FormClose(Sender: TObject; var Action: TCloseAction); begin if FCallingForm <> nil then begin FCallingForm.Enabled := True; FCallingForm.Show; FCallingForm := nil; end; FObj := nil; end; procedure TForm_DameWare.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_ESCAPE: begin Close; end; end; end; procedure TForm_DameWare.FormShow(Sender: TObject); begin RefreshFields; end; function TForm_DameWare.GetUserWorkstations(ARootDSE: IADs; ADN: string): string; var hRes: HRESULT; pObj: IADs; v: OleVariant; DomainHostName: string; begin Result := ''; v := ARootDSE.Get('dnsHostName'); DomainHostName := VariantToStringWithDefault(v, ''); VariantClear(v); hRes := ADsOpenObject( PChar('LDAP://' + DomainHostName + '/' + ADN), nil, nil, ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND, IID_IADs, @pObj ); if Succeeded(hRes) then try v := pObj.Get('userWorkstations'); Result := VarToStr(v); VariantClear(v); except end; pObj := nil; end; function TForm_DameWare.GetUserWorkstations(ALDAP: PLDAP; ADN: string): string; var ldapBase: AnsiString; attrArray: array of PAnsiChar; returnCode: ULONG; searchResult: PLDAPMessage; ldapEntry: PLDAPMessage; ldapValue: PPAnsiChar; begin SetLength(attrArray, 2); attrArray[0] := PAnsiChar('userWorkstations'); attrArray[1] := nil; ldapBase := ADN; returnCode := ldap_search_ext_s( ALDAP, PAnsiChar(ldapBase), LDAP_SCOPE_BASE, nil, PAnsiChar(@attrArray[0]), 0, nil, nil, nil, 0, searchResult ); if (returnCode = LDAP_SUCCESS) and (ldap_count_entries(ALDAP, searchResult) > 0 ) then begin ldapEntry := ldap_first_entry(ALDAP, searchResult); ldapValue := ldap_get_values(ALDAP, ldapEntry, attrArray[0]); if ldapValue <> nil then Result := ldapValue^ else Result := ''; ldap_value_free(ldapValue); end; if searchResult <> nil then ldap_msgfree(searchResult); end; procedure TForm_DameWare.RadioButton_DMRC_RDPClick(Sender: TObject); begin ComboBox_DMRC.ItemIndex := -1; RefreshFields; end; procedure TForm_DameWare.RadioButton_DMRC_ViewerClick(Sender: TObject); begin ComboBox_DMRC.ItemIndex := DMRC_AUTH_WINLOGON; RefreshFields; end; procedure TForm_DameWare.RefreshFields; begin case FDMRC_PrevAuth of DMRC_AUTH_PROPRIETARY: begin Edit_DMRC_dom.Text := apDMRC_Domain; end; DMRC_AUTH_SMARTCARD: begin Edit_DMRC_user.Text := apDMRC_User; Edit_DMRC_dom.Text := apDMRC_Domain; end; -1, DMRC_AUTH_CURRENTUSER: begin Edit_DMRC_user.Text := apDMRC_User; Edit_DMRC_pass.Text := apDMRC_Password; Edit_DMRC_dom.Text := apDMRC_Domain; end; end; case ComboBox_DMRC.ItemIndex of -1: begin Edit_DMRC_user.Text := ''; Edit_DMRC_pass.Text := ''; Edit_DMRC_dom.Text := ''; end; DMRC_AUTH_PROPRIETARY: begin Edit_DMRC_dom.Text := ''; end; DMRC_AUTH_SMARTCARD: begin Edit_DMRC_user.Text := ''; Edit_DMRC_dom.Text := ''; end; DMRC_AUTH_CURRENTUSER: begin Edit_DMRC_user.Text := gvUserName; Edit_DMRC_pass.Text := '********'; Edit_DMRC_dom.Text := gvDomainName; end; end; case ComboBox_DMRC.ItemIndex of -1: begin ComboBox_DMRC.Enabled := False; ComboBox_DMRC.Color := clBtnFace; Label_DMRC_Password.Caption := 'Пароль:'; Edit_DMRC_user.Enabled := False; Edit_DMRC_user.Color := clBtnFace; Edit_DMRC_pass.Enabled := False; Edit_DMRC_pass.Color := clBtnFace; Edit_DMRC_dom.Enabled := False; Edit_DMRC_dom.Color := clBtnFace; end; DMRC_AUTH_PROPRIETARY: begin ComboBox_DMRC.Enabled := True; ComboBox_DMRC.Color := clWindow; Label_DMRC_Password.Caption := 'Пароль:'; Edit_DMRC_user.Enabled := True; Edit_DMRC_user.Color := clWindow; Edit_DMRC_pass.Enabled := True; Edit_DMRC_pass.Color := clWindow; Edit_DMRC_dom.Enabled := False; Edit_DMRC_dom.Color := clBtnFace; end; DMRC_AUTH_SMARTCARD: begin ComboBox_DMRC.Enabled := True; ComboBox_DMRC.Color := clWindow; Label_DMRC_Password.Caption := 'PIN-код:'; Edit_DMRC_user.Enabled := False; Edit_DMRC_user.Color := clBtnFace; Edit_DMRC_pass.Enabled := True; Edit_DMRC_pass.Color := clWindow; Edit_DMRC_dom.Enabled := False; Edit_DMRC_dom.Color := clBtnFace; end; DMRC_AUTH_CURRENTUSER: begin ComboBox_DMRC.Enabled := True; ComboBox_DMRC.Color := clWindow; Label_DMRC_Password.Caption := 'Пароль:'; Edit_DMRC_user.Enabled := False; Edit_DMRC_user.Color := clBtnFace; Edit_DMRC_pass.Enabled := False; Edit_DMRC_pass.Color := clBtnFace; Edit_DMRC_dom.Enabled := False; Edit_DMRC_dom.Color := clBtnFace; end; else begin ComboBox_DMRC.Enabled := True; ComboBox_DMRC.Color := clWindow; Label_DMRC_Password.Caption := 'Пароль:'; Edit_DMRC_user.Enabled := True; Edit_DMRC_user.Color := clWindow; Edit_DMRC_pass.Enabled := True; Edit_DMRC_pass.Color := clWindow; Edit_DMRC_dom.Enabled := True; Edit_DMRC_dom.Color := clWindow; end; end; FDMRC_PrevAuth := ComboBox_DMRC.ItemIndex; if RadioButton_DMRC_RDP.Checked then CheckBox_DMRC_Driver.Checked := False; CheckBox_DMRC_Driver.Enabled := RadioButton_DMRC_Viewer.Checked; end; procedure TForm_DameWare.SetADObject(const Value: TADObject); var infoIP: PIPAddr; infoDHCP: PDHCPInfo; begin ComboBox_Computer.Items.Clear; FObj := Value; if FObj <> nil then begin case FObj.ObjectType of otWorkstation, otDomainController, otRODomainController: begin New(infoIP); New(infoDHCP); GetIPAddress(FObj.dNSHostName, infoIP); // GetDHCPInfo(FObj.dNSHostName, infoDHCP); GetDHCPInfoEx(FObj.dNSHostName, infoDHCP); if not infoIP^.v4.IsEmpty then ComboBox_Computer.Items.Add(infoIP^.v4) else if not infoDHCP^.IPAddress.v4.IsEmpty then ComboBox_Computer.Items.Add(infoDHCP^.IPAddress.v4); ComboBox_Computer.Items.Add(FObj.name); Dispose(infoIP); Dispose(infoDHCP); end; otUser: begin case apAPI of ADC_API_LDAP: begin ComboBox_Computer.Items.DelimitedText := GetUserWorkstations(LDAPBinding, FObj.distinguishedName); end; ADC_API_ADSI: begin ComboBox_Computer.Items.DelimitedText := GetUserWorkstations(ADSIBinding, FObj.distinguishedName); end; end; end; end; if ComboBox_Computer.Items.Count > 0 then ComboBox_Computer.ItemIndex := 0; end; end; procedure TForm_DameWare.SetCallingForm(const Value: TForm); begin FCallingForm := Value; if FCallingForm <> nil then FCallingForm.Enabled := False; end; end.
unit StrOptComponent; interface uses FMX.Controls, Classes, FMX.ListBox; const EXPANDER_CHILD_PANEL_HEIGHT = 35; EXPANDER_MARGIN = 5; EXPANDER_CHILD_LABEL_WIDTH = 100; EXPANDER_CHILD_ITEM_WIDTH = 120; EXPANDER_CHILD_LABEL_FONT_SIZE = 15; type IStrOptionComponent = Interface ['{6B3873BC-CB3D-4E85-8C79-76D2DE847E62}'] function GetValue: String; procedure SetValue(val: String); End; TStrOptComboBox = class(TComboBox, IStrOptionComponent) public constructor Create(owner: TComponent); override; function GetValue: String; procedure SetValue(val: String); end; TStrOptCheckButton = class(TButton, IStrOptionComponent) protected procedure CheckBox_OnCheckedChange(sender: TObject); public constructor Create(owner: TComponent); override; function GetValue: String; procedure SetValue(val: String); end; implementation uses FMX.Types, SysUtils; { TStrOptCheckButton } constructor TStrOptCheckButton.Create(owner: TComponent); begin inherited; self.Width := EXPANDER_CHILD_ITEM_WIDTH; self.Align := TAlignLayout.alLeft; self.StaysPressed := true; self.Parent := TFmxObject( owner ); self.OnClick := CheckBox_OnCheckedChange; end; function TStrOptCheckButton.GetValue: String; begin if IsPressed = true then result := 'true' else result := 'false'; end; procedure TStrOptCheckButton.SetValue(val: String); begin if LowerCase( val ) = 'true' then IsPressed := true else IsPressed := false; end; procedure TStrOptCheckButton.CheckBox_OnCheckedChange(sender: TObject); var btn: TButton; begin btn := TButton( sender ); if btn.IsPressed = true then btn.Text := 'Check !' else btn.Text := ''; end; { TStrOptComboBox } constructor TStrOptComboBox.Create(owner: TComponent); begin inherited; self.Width := EXPANDER_CHILD_ITEM_WIDTH; self.Align := TAlignLayout.alLeft; self.Parent := TFmxObject( owner ); end; function TStrOptComboBox.GetValue: String; begin self.Selected.Text; end; procedure TStrOptComboBox.SetValue(val: String); var index: Integer; begin index := self.Items.IndexOf( val ); self.ItemIndex := index; end; end.
PROGRAM InsertionSort_a(INPUT, OUTPUT); { Программа создаст запись Key/Next и скопирует в неё INPUT } CONST Max = 16; ListEnd = 0; TYPE Count = ListEnd .. Max; Rec = RECORD Key: CHAR; Next: Count END; RecArray = ARRAY [1 .. Max] OF Rec; VAR Index: Count; Arr: RecArray; BEGIN { InsertionSort } Index := 0; WHILE NOT EOLN DO BEGIN { Помещать запись в список, если позволяет пространство, иначе игнорировать и сообщать об ошибке } IF Index < Max THEN BEGIN Index := Index + 1; READ(Arr[Index].Key) END ELSE BEGIN WRITELN('Overflow!'); BREAK END END; Index := 1; WHILE Index <> Max DO BEGIN WRITE(Arr[Index].Key); Index := Index + 1 END; WRITELN END. { InsertionSort }
program tp1ej3y4; const corte = 'fin'; const edadJubilacion = 70; //Registro empleado type empleado = record numero:integer; apellido:string; nombre:string; edad:integer; dni:integer; end; archivoEmpleados = file of empleado; procedure leerEmpleado(var e:empleado); begin with e do begin Writeln('apellido: '); Readln(apellido); if (apellido <> corte) then begin writeln('nombre: ');readln(nombre); writeln('dni: ');readln(dni); writeln('edad: ');readln(edad); writeln('numero: ');readln(numero); writeln('-----------------'); end; end; end; procedure cargarEmpleados(var archivo:archivoEmpleados); var e:empleado; begin Rewrite(archivo); leerEmpleado(e); while e.apellido <> corte do begin write(archivo, e); leerEmpleado(e); end; close(archivo); end; procedure agregarEmpleados(var archivo:archivoEmpleados); var e:empleado; begin reset(archivo); leerEmpleado(e); Seek(archivo, FileSize(archivo)); while(e.apellido <> corte) do begin write(archivo, e); leerEmpleado(e); end; close(archivo); end; procedure modificarEdadEmpleados(var archivo:archivoEmpleados); var e:empleado; nombre,apellido:string; nueva_edad:integer; begin reset(archivo); writeln('Ingrese nombre y apellido del empleado que quiere modificar'); writeln('nombre: ');readln(nombre); writeln('apellido: ');readln(apellido); read(archivo, e); while(not Eof(archivo) and (e.apellido <> apellido) and (e.nombre <> nombre)) do read(archivo,e); if ((e.apellido = apellido) and (e.nombre = nombre)) then begin Write('Ingrese la nueva edad: ');readln(nueva_edad); e.edad := nueva_edad; seek(archivo, FilePos(archivo) - 1); Write(archivo, e); end else writeln('No se encontro ningun empleado con esos datos'); close(archivo); end; procedure exportarATexto(var archivo_binario:archivoEmpleados;var archivo_txt:Text); var e:empleado; begin Assign(archivo_txt, 'todos_empleados.txt'); reset(archivo_binario); Rewrite(archivo_txt); while(not eof(archivo_binario)) do begin read(archivo_binario, e); with e do begin writeln(e.nombre:5, e.apellido:5, e.edad:5, e.numero:5, e.dni:5); end; with e do begin writeln(archivo_txt, ' ', e.edad, ' ', e.dni, ' ', e.numero,' ', e.nombre +' '+e.apellido); end; end; close(archivo_binario); close(archivo_txt); end; procedure listarEmpleado(e:empleado); begin with e do begin Writeln('-------------------'); writeln('Nombre: ', nombre); writeln('apellido: ', apellido); writeln('dni: ', dni); writeln('numero: ', numero); writeln('edad: ', edad); Writeln('-------------------'); end; end; procedure imprimirEmpleado(var archivo:archivoEmpleados); var e:empleado; dato:String; begin Reset(archivo); Write('Ingrese nombre o apellido a buscar: '); readln(dato); while(not eof(archivo)) do begin read(archivo, e); if( (dato = e.apellido) or (dato = e.nombre)) then listarEmpleado(e) ; end; close(archivo); end; procedure listarEmpleados(var archivo:archivoEmpleados); var e:empleado; begin reset(archivo); while(not Eof(archivo)) do begin read(archivo,e); listarEmpleado(e); end; close(archivo); end; procedure listarCasiJubilado(var archivo:archivoEmpleados); var e:empleado; begin reset(archivo); while(not eof(archivo)) do begin read(archivo,e); if (e.edad > edadJubilacion) then listarEmpleado(e); end; close(archivo); end; var archivo_logico : archivoEmpleados; archivo_fisico:string; txt: Text; opcion:integer; begin opcion := -1; Writeln('Ingrese el nombre del archivo fisico'); ReadLn(archivo_fisico); Assign(archivo_logico, archivo_fisico); while(opcion <> 0) do begin Writeln('Elija una de las siguientes opciones de la lista o 0 para salir: '); writeln('1. Crear registro de empleados.'); writeln('2. Buscar y listar empleado en pantalla.'); writeln('3. Listar empleados de a uno por linea.'); writeln('4. Listar en pantalla empleados mayores de 70.'); writeln('5. Añadir uno o mas empleados al final del archivo.'); writeln('6. Cambiar la edad de un empleado.'); writeln('7. Exportar todos los empleados a texto.'); Readln(opcion); case opcion of 1: cargarEmpleados(archivo_logico); 2: imprimirEmpleado(archivo_logico); 3: listarEmpleados(archivo_logico); 4: listarCasiJubilado(archivo_logico); 5: agregarEmpleados(archivo_logico); 6: modificarEdadEmpleados(archivo_logico); 7: exportarATexto(archivo_logico, txt); end; end; end.
unit legendkage_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,m6805,main_engine,controls_engine,gfx_engine,ym_2203, rom_engine,pal_engine,sound_engine; function iniciar_lk_hw:boolean; implementation const lk_rom:array[0..1] of tipo_roms=( (n:'a54-01-2.37';l:$8000;p:0;crc:$60fd9734),(n:'a54-02-2.38';l:$8000;p:$8000;crc:$878a25ce)); lk_snd:tipo_roms=(n:'a54-04.54';l:$8000;p:0;crc:$541faf9a); lk_mcu:tipo_roms=(n:'a54-09.53';l:$800;p:0;crc:$0e8b8846); lk_data:tipo_roms=(n:'a54-03.51';l:$4000;p:0;crc:$493e76d8); lk_char:array[0..3] of tipo_roms=( (n:'a54-05-1.84';l:$4000;p:0;crc:$0033c06a),(n:'a54-06-1.85';l:$4000;p:$4000;crc:$9f04d9ad), (n:'a54-07-1.86';l:$4000;p:$8000;crc:$b20561a4),(n:'a54-08-1.87';l:$4000;p:$c000;crc:$3ff3b230)); //Dip lk_dip_a:array [0..5] of def_dip=( (mask:$3;name:'Bonus Life';number:4;dip:((dip_val:$3;dip_name:'200k 700k 500k+'),(dip_val:$2;dip_name:'200k 900k 700k+'),(dip_val:$1;dip_name:'300k 1000k 700k+'),(dip_val:$0;dip_name:'300k 1300k 1000k+'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Free Play';number:2;dip:((dip_val:$4;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$18;name:'Lives';number:4;dip:((dip_val:$18;dip_name:'3'),(dip_val:$10;dip_name:'4'),(dip_val:$8;dip_name:'5'),(dip_val:$0;dip_name:'255 (Cheat)'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Flip Screen';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$80;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); lk_dip_b:array [0..2] of def_dip=( (mask:$f;name:'Coin A';number:16;dip:((dip_val:$f;dip_name:'9C 1C'),(dip_val:$e;dip_name:'8C 1C'),(dip_val:$d;dip_name:'7C 1C'),(dip_val:$c;dip_name:'6C 1C'),(dip_val:$b;dip_name:'5C 1C'),(dip_val:$a;dip_name:'4C 1C'),(dip_val:$9;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(dip_val:$1;dip_name:'1C 2C'),(dip_val:$2;dip_name:'1C 3C'),(dip_val:$3;dip_name:'1C 4C'),(dip_val:$4;dip_name:'1C 5C'),(dip_val:$5;dip_name:'1C 6C'),(dip_val:$6;dip_name:'1C 7C'),(dip_val:$7;dip_name:'1C 8C'))), (mask:$f0;name:'Coin B';number:16;dip:((dip_val:$f0;dip_name:'9C 1C'),(dip_val:$e0;dip_name:'8C 1C'),(dip_val:$d0;dip_name:'7C 1C'),(dip_val:$c0;dip_name:'6C 1C'),(dip_val:$b0;dip_name:'5C 1C'),(dip_val:$a0;dip_name:'4C 1C'),(dip_val:$90;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(dip_val:$10;dip_name:'1C 2C'),(dip_val:$20;dip_name:'1C 3C'),(dip_val:$30;dip_name:'1C 4C'),(dip_val:$40;dip_name:'1C 5C'),(dip_val:$50;dip_name:'1C 6C'),(dip_val:$60;dip_name:'1C 7C'),(dip_val:$70;dip_name:'1C 8C'))),()); lk_dip_c:array [0..6] of def_dip=( (mask:$2;name:'Initial Season';number:2;dip:((dip_val:$2;dip_name:'Spring'),(dip_val:$0;dip_name:'Winter'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Difficulty';number:2;dip:((dip_val:$8;dip_name:'Easy'),(dip_val:$0;dip_name:'Normal'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Coinage Display';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$10;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Year Display';number:2;dip:((dip_val:$0;dip_name:'1985'),(dip_val:$20;dip_name:'MCMLXXXIV'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Invulnerability (Cheat)';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Coin Slots';number:2;dip:((dip_val:$0;dip_name:'1'),(dip_val:$80;dip_name:'2'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var scroll_val:array[0..5] of byte; mem_data:array[0..$3fff] of byte; sound_cmd,color_bnk:byte; bg_bank,fg_bank:word; snd_nmi,pant_enable,prioridad_fg:boolean; //mcu mcu_mem:array[0..$7ff] of byte; port_c_in,port_c_out,port_b_out,port_b_in,port_a_in,port_a_out:byte; ddr_a,ddr_b,ddr_c:byte; from_main,from_mcu:byte; main_sent,mcu_sent:boolean; procedure update_video_lk_hw; var x,y:byte; f,nchar:word; procedure draw_sprites(prio:byte); var f,x,y,nchar:word; atrib,color:byte; flipx,flipy:boolean; begin for f:=0 to $17 do begin atrib:=memoria[$f102+(f*4)]; if (atrib and $80)=prio then begin // 0x01: horizontal flip // 0x02: vertical flip // 0x04: bank select // 0x08: sprite size // 0x70: color // 0x80: priority color:=atrib and $70; flipx:=(atrib and $1)<>0; flipy:=(atrib and $2)<>0; x:=memoria[$f100+(f*4)]-15; y:=240-memoria[$f101+(f*4)]; nchar:=memoria[$f103+(f*4)]+((atrib and $04) shl 6); if (atrib and $08)<>0 then begin //x2 if not(flipy) then nchar:=nchar xor 1; put_gfx_sprite_diff(nchar xor 0,color,flipx,flipy,1,0,0); put_gfx_sprite_diff(nchar xor 1,color,flipx,flipy,1,0,16); actualiza_gfx_sprite_size(x,y-16,4,16,32); end else begin //x1 put_gfx_sprite(nchar,color,flipx,flipy,1); actualiza_gfx_sprite(x,y,4,1); end; end; end; end; begin for f:=0 to $3ff do begin x:=f mod 32; y:=f div 32; //char if gfx[0].buffer[f] then begin nchar:=memoria[$f400+f]; put_gfx_trans(x*8,y*8,nchar,$110,1,0); gfx[0].buffer[f]:=false; end; if pant_enable then begin //BG if gfx[0].buffer[$400+f] then begin nchar:=memoria[$fc00+f]+bg_bank; put_gfx(x*8,y*8,nchar,$300+color_bnk,2,0); gfx[0].buffer[$400+f]:=false; end; //FG if gfx[0].buffer[$800+f] then begin nchar:=memoria[$f800+f]+fg_bank; put_gfx_trans(x*8,y*8,nchar,$200+color_bnk,3,0); gfx[0].buffer[$800+f]:=false; end; end; end; if pant_enable then scroll_x_y(2,4,scroll_val[4]+5,scroll_val[5]) else fill_full_screen(4,$400); if prioridad_fg then begin draw_sprites($80); if pant_enable then scroll_x_y(3,4,scroll_val[2]+3,scroll_val[3]); draw_sprites(0); end else begin draw_sprites(0); if pant_enable then scroll_x_y(3,4,scroll_val[2]+3,scroll_val[3]); draw_sprites($80); end; scroll_x_y(1,4,scroll_val[0]+1,scroll_val[1]); actualiza_trozo_final(16,16,240,224,4); end; procedure eventos_lk_hw; begin if event.arcade then begin //P1 if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $Fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $F7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); //P2 if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $Fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $F7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20); //SYS if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); end; end; procedure lk_hw_principal; var frame_m,frame_s,frame_mcu:single; f:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; frame_mcu:=m6805_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound CPU z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; //MCU CPU m6805_0.run(frame_mcu); frame_mcu:=frame_mcu+m6805_0.tframes-m6805_0.contador; if f=239 then begin z80_0.change_irq(HOLD_LINE); update_video_lk_hw; end; end; eventos_lk_hw; video_sync; end; end; function lk_getbyte(direccion:word):byte; var res:byte; begin case direccion of 0..$e7ff,$f000..$f003,$f0a0..$f0a3,$f400..$ffff:lk_getbyte:=memoria[direccion]; $e800..$efff:lk_getbyte:=buffer_paleta[direccion and $7ff]; $f061:lk_getbyte:=$ff; $f062:begin mcu_sent:=false; lk_getbyte:=from_mcu; end; $f080:lk_getbyte:=marcade.dswa; $f081:lk_getbyte:=marcade.dswb; $f082:lk_getbyte:=marcade.dswc; $f083:lk_getbyte:=marcade.in0; $f084:lk_getbyte:=marcade.in1; $f086:lk_getbyte:=marcade.in2; $f087:begin res:=0; // bit 0 = when 1, mcu is ready to receive data from main cpu // bit 1 = when 1, mcu has sent data to the main cpu if not(main_sent) then res:=res or $01; if mcu_sent then res:=res or $02; lk_getbyte:=res; end; $f0c0..$f0c5:lk_getbyte:=scroll_val[direccion and $7]; end; end; procedure lk_putbyte(direccion:word;valor:byte); var bank:word; procedure cambiar_color(pos:word); var tmp_color:byte; color:tcolor; begin tmp_color:=buffer_paleta[pos+1]; color.r:=pal4bit(tmp_color); tmp_color:=buffer_paleta[pos]; color.g:=pal4bit(tmp_color shr 4); color.b:=pal4bit(tmp_color); pos:=pos shr 1; set_pal_color(color,pos); case pos of $110..$11f:fillchar(gfx[0].buffer[0],$400,1); $200..$2ff:fillchar(gfx[0].buffer[$800],$400,1); $300..$3ff:fillchar(gfx[0].buffer[$400],$400,1); end; end; begin case direccion of 0..$dfff:; $e000..$e7ff,$f0a0..$f0a3,$f100..$f15f:memoria[direccion]:=valor; $e800..$efff:if buffer_paleta[direccion and $7ff]<>valor then begin buffer_paleta[direccion and $7ff]:=valor; cambiar_color(direccion and $7fe); end; $f000..$f003:begin memoria[direccion]:=valor; case (direccion and $3) of 0:begin bank:=(valor and $4) shl 6; if fg_bank<>bank then begin fg_bank:=bank; fillchar(gfx[0].buffer[$800],$400,1); end; end; 1:begin prioridad_fg:=(valor and $2)<>0; if (valor and $8)<>0 then bank:=$100*5 else bank:=$100*1; if bg_bank<>bank then begin bg_bank:=bank; fillchar(gfx[0].buffer[$400],$400,1); end; if color_bnk<>(valor and $f0) then begin color_bnk:=valor and $f0; fillchar(gfx[0].buffer[$400],$800,1); end; end; 2:pant_enable:=(valor and $f0)=$f0; end; end; $f060:if not(snd_nmi) then begin sound_cmd:=valor; z80_1.change_nmi(ASSERT_LINE); snd_nmi:=true; end; $f062:begin from_main:=valor; main_sent:=true; m6805_0.irq_request(0,ASSERT_LINE); end; $f0c0..$f0c5:scroll_val[direccion and $7]:=valor; $f400..$f7ff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $f800..$fbff:if memoria[direccion]<>valor then begin gfx[0].buffer[$800+(direccion and $3ff)]:=true; memoria[direccion]:=valor; end; $fc00..$ffff:if memoria[direccion]<>valor then begin gfx[0].buffer[$400+(direccion and $3ff)]:=true; memoria[direccion]:=valor; end; end; end; function lk_inbyte(puerto:word):byte; begin case puerto of $4000..$7fff:lk_inbyte:=mem_data[puerto and $3fff]; end; end; //Sound function snd_lk_hw_getbyte(direccion:word):byte; begin case direccion of 0..$87ff:snd_lk_hw_getbyte:=mem_snd[direccion]; $9000:snd_lk_hw_getbyte:=ym2203_0.status; $9001:snd_lk_hw_getbyte:=ym2203_0.read; $a000:snd_lk_hw_getbyte:=ym2203_1.status; $a001:snd_lk_hw_getbyte:=ym2203_1.read; $b000:snd_lk_hw_getbyte:=sound_cmd; end; end; procedure snd_lk_hw_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $8000..$87ff:mem_snd[direccion]:=valor; $9000:ym2203_0.control(valor); $9001:ym2203_0.write(valor); $a000:ym2203_1.control(valor); $a001:ym2203_1.write(valor); $b002:begin z80_1.change_nmi(CLEAR_LINE); snd_nmi:=false; end; end; end; function mcu_lk_hw_getbyte(direccion:word):byte; begin direccion:=direccion and $7ff; case direccion of 0:mcu_lk_hw_getbyte:=(port_a_out and ddr_a) or (port_a_in and not(ddr_a)); 1:mcu_lk_hw_getbyte:=(port_b_out and ddr_b) or (port_b_in and not(ddr_b)); 2:begin port_c_in:=0; if main_sent then port_c_in:=port_c_in or $01; if not(mcu_sent) then port_c_in:=port_c_in or $02; mcu_lk_hw_getbyte:=(port_c_out and ddr_c) or (port_c_in and not(ddr_c)); end; 3..$7ff:mcu_lk_hw_getbyte:=mcu_mem[direccion]; end; end; procedure mcu_lk_hw_putbyte(direccion:word;valor:byte); begin direccion:=direccion and $7ff; case direccion of 0:port_a_out:=valor; 1:begin if (((ddr_b and $02)<>0) and ((not(valor) and $02)<>0) and ((port_b_out and $02)<>0)) then begin port_a_in:=from_main; if main_sent then m6805_0.irq_request(0,CLEAR_LINE); main_sent:=false; end; if (((ddr_b and $04)<>0) and ((valor and $04)<>0) and ((not(port_b_out) and $04)<>0)) then begin from_mcu:=port_a_out; mcu_sent:=true; end; port_b_out:=valor; end; 2:port_c_out:=valor; 4:ddr_a:=valor; 5:ddr_b:=valor; 6:ddr_c:=valor; 3,7..$7f:mcu_mem[direccion]:=valor; $80..$7ff:; end; end; procedure snd_irq(irqstate:byte); begin z80_1.change_irq(irqstate); end; procedure lk_hw_sound_update; begin ym2203_0.update; ym2203_1.update; end; //Main procedure reset_lk_hw; begin z80_0.reset; z80_1.reset; m6805_0.reset; ym2203_0.reset; ym2203_1.reset; reset_audio; fillchar(scroll_val[0],5,0); marcade.in0:=$0b; marcade.in1:=$ff; marcade.in2:=$ff; sound_cmd:=0; color_bnk:=0; pant_enable:=false; bg_bank:=0; fg_bank:=0; snd_nmi:=false; prioridad_fg:=false; //mcu port_a_in:=0; port_a_out:=0; ddr_a:=0; port_b_in:=0; port_b_out:=0; ddr_b:=0; port_c_in:=0; port_c_out:=0; ddr_c:=0; mcu_sent:=false; main_sent:=false; from_main:=0; from_mcu:=0; end; function iniciar_lk_hw:boolean; var memoria_temp:array[0..$ffff] of byte; const ps_x:array[0..15] of dword=(7, 6, 5, 4, 3, 2, 1, 0, 64+7, 64+6, 64+5, 64+4, 64+3, 64+2, 64+1, 64+0); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 128+0*8, 128+1*8, 128+2*8, 128+3*8, 128+4*8, 128+5*8, 128+6*8, 128+7*8); begin llamadas_maquina.bucle_general:=lk_hw_principal; llamadas_maquina.reset:=reset_lk_hw; iniciar_lk_hw:=false; iniciar_audio(false); screen_init(1,256,256,true); screen_mod_scroll(1,256,256,255,256,256,255); screen_init(2,256,256); screen_mod_scroll(2,256,256,255,256,256,255); screen_init(3,256,256,true); screen_mod_scroll(3,256,256,255,256,256,255); screen_init(4,256,256,false,true); iniciar_video(240,224); //Main CPU z80_0:=cpu_z80.create(6000000,$100); z80_0.change_ram_calls(lk_getbyte,lk_putbyte); z80_0.change_io_calls(lk_inbyte,nil); //Sound CPU z80_1:=cpu_z80.create(4000000,$100); z80_1.change_ram_calls(snd_lk_hw_getbyte,snd_lk_hw_putbyte); z80_1.init_sound(lk_hw_sound_update); //MCU CPU m6805_0:=cpu_m6805.create(3000000,$100,tipo_m68705); m6805_0.change_ram_calls(mcu_lk_hw_getbyte,mcu_lk_hw_putbyte); //Sound Chips ym2203_0:=ym2203_chip.create(4000000); ym2203_0.change_irq_calls(snd_irq); ym2203_1:=ym2203_chip.create(4000000); //cargar roms if not(roms_load(@memoria,lk_rom)) then exit; //cargar roms snd if not(roms_load(@mem_snd,lk_snd)) then exit; //cargar roms mcu if not(roms_load(@mcu_mem,lk_mcu)) then exit; //cargar data if not(roms_load(@mem_data,lk_data)) then exit; //convertir chars if not(roms_load(@memoria_temp,lk_char)) then exit; init_gfx(0,8,8,$800); gfx[0].trans[0]:=true; gfx_set_desc_data(4,0,8*8,$800*8*8*1,$800*8*8*0,$800*8*8*3,$800*8*8*2); convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,false); //convertir sprites init_gfx(1,16,16,$200); gfx[1].trans[0]:=true; gfx_set_desc_data(4,0,32*8,$200*32*8*1,$200*32*8*0,$200*32*8*3,$200*32*8*2); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); //DIP marcade.dswa:=$7f; marcade.dswb:=$0; marcade.dswc:=$ff; marcade.dswa_val:=@lk_dip_a; marcade.dswb_val:=@lk_dip_b; marcade.dswc_val:=@lk_dip_c; reset_lk_hw; iniciar_lk_hw:=true; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpAsn1Sequence; {$I ..\Include\CryptoLib.inc} interface uses SysUtils, Generics.Collections, ClpCryptoLibTypes, ClpCollectionUtilities, ClpDerNull, {$IFDEF DELPHI} ClpIDerNull, {$ENDIF DELPHI} ClpIBerTaggedObject, ClpAsn1TaggedObject, ClpIAsn1TaggedObject, ClpIAsn1Set, ClpAsn1Encodable, ClpIProxiedInterface, ClpIAsn1SequenceParser, ClpIAsn1Sequence, ClpAsn1Object; resourcestring SInvalidObject = 'Object Implicit - Explicit Expected.'; SUnknownObject = 'Unknown object in GetInstance: %s, "obj"'; SInvalidSequence = '"Failed to Construct Sequence from byte array: " %s'; type /// <summary> /// return an Asn1Sequence from the given object. /// </summary> TAsn1Sequence = class abstract(TAsn1Object, IAsn1Sequence) strict private var FSeq: TList<IAsn1Encodable>; function GetCount: Int32; virtual; function GetParser: IAsn1SequenceParser; virtual; function GetSelf(Index: Integer): IAsn1Encodable; virtual; function GetCurrent(const e: IAsn1Encodable): IAsn1Encodable; type TAsn1SequenceParserImpl = class sealed(TInterfacedObject, IAsn1SequenceParserImpl, IAsn1SequenceParser) strict private var Fouter: IAsn1Sequence; Fmax, Findex: Int32; public constructor Create(const outer: IAsn1Sequence); function ReadObject(): IAsn1Convertible; function ToAsn1Object(): IAsn1Object; end; strict protected function Asn1GetHashCode(): Int32; override; function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; procedure AddObject(const obj: IAsn1Encodable); inline; constructor Create(capacity: Int32); public destructor Destroy(); override; function ToString(): String; override; function GetEnumerable: TCryptoLibGenericArray<IAsn1Encodable>; virtual; // /** // * return the object at the sequence position indicated by index. // * // * @param index the sequence number (starting at zero) of the object // * @return the object at the sequence position indicated by index. // */ property Self[Index: Int32]: IAsn1Encodable read GetSelf; default; /// <summary> /// return an Asn1Sequence from the given object. /// </summary> /// <param name="obj"> /// the object we want converted. /// </param> /// <exception cref="EArgumentCryptoLibException"> /// if the object cannot be converted. /// </exception> class function GetInstance(const obj: TObject): IAsn1Sequence; overload; static; /// <summary> /// return an Asn1Sequence from the given object. /// </summary> /// <param name="obj"> /// the byte array we want converted. /// </param> /// <exception cref="EArgumentCryptoLibException"> /// if the object cannot be converted. /// </exception> class function GetInstance(const obj: TCryptoLibByteArray): IAsn1Sequence; overload; static; // /** // * Return an ASN1 sequence from a tagged object. There is a special // * case here, if an object appears to have been explicitly tagged on // * reading but we were expecting it to be implicitly tagged in the // * normal course of events it indicates that we lost the surrounding // * sequence - so we need to add it back (this will happen if the tagged // * object is a sequence that contains other sequences). If you are // * dealing with implicitly tagged sequences you really <b>should</b> // * be using this method. // * // * @param obj the tagged object. // * @param explicitly true if the object is meant to be explicitly tagged, // * false otherwise. // * @exception ArgumentException if the tagged object cannot // * be converted. // */ class function GetInstance(const obj: IAsn1TaggedObject; explicitly: Boolean): IAsn1Sequence; overload; static; property Parser: IAsn1SequenceParser read GetParser; property Count: Int32 read GetCount; end; implementation uses // included here to avoid circular dependency :) ClpBerSequence, ClpDerSequence; { TAsn1Sequence } function TAsn1Sequence.GetCurrent(const e: IAsn1Encodable): IAsn1Encodable; var encObj: IAsn1Encodable; begin encObj := e; // unfortunately null was allowed as a substitute for DER null if (encObj = Nil) then begin result := TDerNull.Instance; Exit; end; result := encObj; end; procedure TAsn1Sequence.AddObject(const obj: IAsn1Encodable); begin FSeq.Add(obj); end; function TAsn1Sequence.Asn1Equals(const asn1Object: IAsn1Object): Boolean; var other: IAsn1Sequence; l1, l2: TCryptoLibGenericArray<IAsn1Encodable>; o1, o2: IAsn1Object; Idx: Int32; begin if (not Supports(asn1Object, IAsn1Sequence, other)) then begin result := false; Exit; end; if (Count <> other.Count) then begin result := false; Exit; end; l1 := GetEnumerable; l2 := other.GetEnumerable; for Idx := System.Low(l1) to System.High(l1) do begin o1 := GetCurrent(l1[Idx]).ToAsn1Object(); o2 := GetCurrent(l2[Idx]).ToAsn1Object(); if (not(o1.Equals(o2))) then begin result := false; Exit; end; end; result := true; end; function TAsn1Sequence.Asn1GetHashCode: Int32; var hc: Int32; o: IAsn1Encodable; LListAsn1Encodable: TCryptoLibGenericArray<IAsn1Encodable>; begin hc := Count; LListAsn1Encodable := Self.GetEnumerable; for o in LListAsn1Encodable do begin hc := hc * 17; if (o = Nil) then begin hc := hc xor TDerNull.Instance.GetHashCode(); end else begin hc := hc xor o.GetHashCode(); end; end; result := hc; end; constructor TAsn1Sequence.Create(capacity: Int32); begin inherited Create(); FSeq := TList<IAsn1Encodable>.Create(); FSeq.capacity := capacity; end; destructor TAsn1Sequence.Destroy; begin FSeq.Free; inherited Destroy; end; function TAsn1Sequence.GetCount: Int32; begin result := FSeq.Count; end; function TAsn1Sequence.GetEnumerable: TCryptoLibGenericArray<IAsn1Encodable>; begin result := FSeq.ToArray; end; class function TAsn1Sequence.GetInstance(const obj: TObject): IAsn1Sequence; var primitive: IAsn1Object; sequence: IAsn1Sequence; res: IAsn1SequenceParser; begin if ((obj = Nil) or (obj is TAsn1Sequence)) then begin result := obj as TAsn1Sequence; Exit; end; if (Supports(obj, IAsn1SequenceParser, res)) then begin result := TAsn1Sequence.GetInstance(res.ToAsn1Object() as TAsn1Object); Exit; end; if (obj is TAsn1Encodable) then begin primitive := (obj as TAsn1Encodable).ToAsn1Object(); if (Supports(primitive, IAsn1Sequence, sequence)) then begin result := sequence; Exit; end; end; raise EArgumentCryptoLibException.CreateResFmt(@SUnknownObject, [obj.ClassName]); end; class function TAsn1Sequence.GetInstance(const obj: TCryptoLibByteArray) : IAsn1Sequence; begin try result := TAsn1Sequence.GetInstance(FromByteArray(obj) as TAsn1Object); except on e: EIOCryptoLibException do begin raise EArgumentCryptoLibException.CreateResFmt(@SInvalidSequence, [e.Message]); end; end; end; class function TAsn1Sequence.GetInstance(const obj: IAsn1TaggedObject; explicitly: Boolean): IAsn1Sequence; var inner: IAsn1Object; sequence: IAsn1Sequence; begin inner := obj.GetObject(); if (explicitly) then begin if (not(obj.IsExplicit())) then raise EArgumentCryptoLibException.CreateRes(@SInvalidObject); result := inner as IAsn1Sequence; Exit; end; // // constructed object which appears to be explicitly tagged // when it should be implicit means we have to add the // surrounding sequence. // if (obj.IsExplicit()) then begin if (Supports(obj, IBerTaggedObject)) then begin result := TBerSequence.Create(inner); Exit; end; result := TDerSequence.Create(inner); Exit; end; if (Supports(inner, IAsn1Sequence, sequence)) then begin result := sequence; Exit; end; raise EArgumentCryptoLibException.CreateResFmt(@SUnknownObject, [(obj as TAsn1TaggedObject).ClassName]); end; function TAsn1Sequence.GetParser: IAsn1SequenceParser; begin result := TAsn1SequenceParserImpl.Create(Self as IAsn1Sequence); end; function TAsn1Sequence.GetSelf(Index: Integer): IAsn1Encodable; begin result := FSeq[index]; end; function TAsn1Sequence.ToString: String; begin result := TCollectionUtilities.ToStructuredString(FSeq); end; { TAsn1Sequence.TAsn1SequenceParserImpl } constructor TAsn1Sequence.TAsn1SequenceParserImpl.Create (const outer: IAsn1Sequence); begin inherited Create(); Fouter := outer; Fmax := outer.Count; end; function TAsn1Sequence.TAsn1SequenceParserImpl.ReadObject: IAsn1Convertible; var obj: IAsn1Encodable; sequence: IAsn1Sequence; asn1Set: IAsn1Set; begin if (Findex = Fmax) then begin result := Nil; Exit; end; obj := Fouter[Findex]; System.Inc(Findex); if (Supports(obj, IAsn1Sequence, sequence)) then begin result := sequence.Parser; Exit; end; if (Supports(obj, IAsn1Set, asn1Set)) then begin result := asn1Set.Parser; Exit; end; // NB: Asn1OctetString implements Asn1OctetStringParser directly // if (obj is Asn1OctetString) // return ((Asn1OctetString)obj).Parser; result := obj; end; function TAsn1Sequence.TAsn1SequenceParserImpl.ToAsn1Object: IAsn1Object; begin result := Fouter; end; end.
unit comport; //-------------------------------------------------- // Модуль последовательных коммуникационных портов //-------------------------------------------------- {$WARN SYMBOL_DEPRECATED OFF} interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, SyncObjs, Registry; const //-------------------------------------- Идентификаторы ошибок при операция с СОМ-портом cpeOpenFailed = $01; cpeConfigFailed = $02; cpeClearFailed = $03; cpeTrmInitFailed = $04; cpeTrmEndFailed = $05; cpeTrmMistake = $06; cpeTrmEndOverlap = $07; cpeRcvInitFailed = $08; cpeRcvEndFailed = $09; cpeRcvMistake = $0A; cpeRcvEndOverlap = $0B; cpeRcvNoBytes = $0C; // Ошибки при операциях с СОМ-портами CPortErrName : array[$01..$0C] of String[70] = ( 'Не удалось открыть коммуникационный порт %s.', 'Не удалось сконфигурировать порт %s!', 'Не удалось очистить последнюю операцию %s.', 'Не удалось инициировать передачу сообщения по %s.', 'Не удалось завершить передачу сообщения по %s.', 'Ошибка при передаче сообщения по %s.', 'Неверное завершение передачи сообщения по %s.', 'Не удалось инициировать прием сообщения по %s.', 'Не удалось завершить прием сообщения по %s.', 'Ошибка при приеме сообщения по %s.', 'Неверное завершение приема сообщения по %s.', 'Нет принятых байтов по порту %s.' ); // Сообщения из модуля // CPM_TRMFAILED = WM_USER + $7000; // Ошибка при передаче // CPM_TRMSUCCESS = CPM_TRMFAILED + 1; // Успешное завершение передачи // CPM_RCVFAILED = CPM_TRMSUCCESS + 1; // Ошибка при приеме // CPM_RCVSUCCESS = CPM_RCVFAILED + 1; // Успешное завершение приема // Сообщения в модуль // CPM_FILLANDSEND = CPM_RCVSUCCESS + 1; // Заполнить буфер и начать передачу // CPM_RCVSTART = CPM_FILLANDSEND + 1; // Начать прием // CPM_CANCEL = CPM_RCVSTART + 1; // Прервать все операции с портом // CPM_CANCELRCV = CPM_CANCEL + 1; // Прервать прием // CPM_CANCELTRM = CPM_CANCELRCV + 1; // Прервать передачу CPM_TRMSIGNAL = WM_USER + $7009; // Сигнал события передатчика CPM_RCVSIGNAL = CPM_TRMSIGNAL + 1; // Сигнал события приемника // CPM_RTSTGL = CPM_RCVSIGNAL + 1; // Установка сигнала RST // CPM_PURGECOMM = CPM_RTSTGL + 1; // Явно прерывает операции type // Тип номеров СОМ-портов TComNum = 1..4; //------------------------------------------------------------------------ // Класс последовательного коммуникационного порта TComPort //------------------------------------------------------------------------ // Имена СОМ-портов TPortName = type string; // Типы ОС TOSystem = ( osWinNT, osWin3x, osWin9x, osWinMe, osWin2k, osWinXP); // Тип управления портом по сигналу DTR TDTRControl = ( dtr_Disable, dtr_Enable, dtr_Handshake); // Тип управления портом по сигналу RTS TRTSControl = ( rts_Disable, rts_Enable, rts_Handshake, rts_Toggle); // Тип числа битов в символе TSymbSize = 4..8; // Тип паритета TParity = ( pt_No, pt_Odd, pt_Even, pt_Mark, pt_Space); // Тип стоп-битов TStopBits = ( sb_One, sb_OneHalf, sb_Two); // Тип скоростей передачи TBaudRate = ( br_50, br_100, br_300, br_600, br_1200, br_2400, br_4800, br_9600, br_14400, br_19200, br_28800, br_38400, br_57600, br_115200); // Тип управления потоком TFlowControl = ( fc_No, fc_XonXoff, fc_Hardware); // Буферы портов TPortBuffer = record Info : array [ 0..4095] of Byte;// Информация буфера Head : Word; // Голова буфера Tail : Word; // Хвост буфера State : Cardinal; // Состояние буфера end; // TPortBuffer //------------------------------------------------------------------------ // Класс последовательного коммуникационного порта TComPort //------------------------------------------------------------------------ TComPort = class( TComponent) private FPortName : TPortName; // Имя порта FBaudRate : TBaudRate; // Скорость передачи FParityEn : Boolean; // Разрешение обработки паритета FFlowCtrl : TFlowControl; // Управление потоком FCTSFlow : Boolean; // Управление выходом сигналом CTS FDSRFlow : Boolean; // Управление выходом сигналом DSR FDTRControl : TDTRControl; // Тип управления по сигналу DTR FDSRSense : Boolean; // Влияние DSR на течение обмена FTxCont : Boolean; // Продолжать передачу после Xoff FOutX : Boolean; // Флаг исп. XonXoff при передаче FInX : Boolean; // Флаг исп. XonXoff при приеме FErrorReplace : Boolean; // Заменять байты с ош. на ErrorChar FDiscardNull : Boolean; // Удалять нулевые байты из сообщ. FRTSControl : TRTSControl; // Тип управления по сигналу RTS FAbortOnError : Boolean; // Прерывать обмен при ошибке FXonLim : LongInt; // Мин. кол-во байт в буфере перед Xon FXoffLim : LongInt; // Макс. кол-во байт в буфере перед Xoff FSymbSize : TSymbSize; // Кол-во бит в символе FParity : TParity; // Тип паритета FStopBits : TStopBits; // Кол-во стоп-битов FXonChar : Byte; // Код символа Xon FXOffChar : Byte; // Код символа Xoff FErrorChar : Byte; // Код символа ошибки FEofChar : Byte; // Код символа конца данных FEvtChar : Byte; // Код символа сигнализации события FToTotal : Boolean; // Исп. общий таймаут сообщения FToIntv : Boolean; // Исп. интервальный таймаут FToValue : Cardinal; // Величина общего таймаута в мс FWindowHandle : HWND; // Обработчик порта MessageDest : HWND; // Окно назначения сообщения s : string; // Строковые переменные для работы порта(1) sp : string; // (2) protected TimeOuts : TCommTimeouts; //------------------------------ Таймауты ожидания function GetCommNames : Boolean; procedure CalcTimeouts; procedure FillDCB; procedure WndProc(var Msg : TMessage); virtual; public rcverrcnt : cardinal; // Счетчик ошибок порта по приему trmerrcnt : cardinal; // Счетчик ошибок порта по передаче Buffer : array[0..4095] of char; // Буфер порта OSType : TOSystem; // Код операционной системы PortIsOpen : boolean; // Порт открыт PortHandle : Cardinal; // Обработчик порта PortDCB : DCB; // Структура управления порта PortError : Cardinal; // Номер последней ошибки порта TrmOLS : TOverlapped; // Структура перекрытия передачи lvCdt : Cardinal; TrmEvent : TEvent; // Событие по окончании передачи TrmBuf : TPortBuffer; // Буфер передачи TrmdBytes : Cardinal; // Реально переданных байт TrmInProg : Boolean; // Флаг течения передачи RcvOLS : TOverlapped; // Структура асинхронного приема lvCdr : Cardinal; RcvEvent : TEvent; // Событие по окончании приема RcvBuf : TPortBuffer; // Буфер приема RcvdBytes : Cardinal; // Реально принятых байт RcvInProg : Boolean; // Флаг течения приема //======================================================================================== constructor Create( AOwner : TComponent); override; destructor Destroy; override; function RTSOnOff( aOn :Boolean) :Boolean; function DTROnOff( aOn :Boolean) :Boolean; procedure RecieveFinish; procedure TransmitFinish; function OpenPort : Boolean; function ClosePort : Boolean; function InitPort(CommPortParam: string) : Boolean; function StrToComm(trmstring: string) : longword; function StrFromComm(var rcvstring: string) : boolean; function BufToComm(Buf: pchar; Len : Integer) : cardinal; function BufFromComm(Buf: pchar; MaxLen : Integer) : cardinal; published property PortName : TPortName read FPortName write FPortName; property BaudRate : TBaudRate read FBaudRate write FBaudRate default br_600; property ParityEn : Boolean read FParityEn write FParityEn default TRUE; property FlowCtrl : TFlowControl read FFlowCtrl write FFlowCtrl default fc_No; property CTSFlow : Boolean read FCTSFlow write FCTSFlow default FALSE; property DSRFlow : Boolean read FDSRFlow write FDSRFlow default FALSE; property DTRControl : TDTRControl read FDTRControl write FDTRControl default dtr_Disable; property DSRSense : Boolean read FDSRSense write FDSRSense default FALSE; property TxCont : Boolean read FTxCont write FTxCont default FALSE; property OutX : Boolean read FOutX write FOutX default FALSE; property InX : Boolean read FInX write FInX default FALSE; property ErrorReplace : Boolean read FErrorReplace write FErrorReplace default FALSE; property DiscardNull : Boolean read FDiscardNull write FDiscardNull default FALSE; property RTSControl : TRTSControl read FRTSControl write FRTSControl default rts_Disable; property AbortOnError : Boolean read FAbortOnError write FAbortOnError default FALSE; property XonLim : LongInt read FXonLim write FXonLim default 1; property XOffLim : LongInt read FXoffLim write FXoffLim default 512; property SymbSize : TSymbSize read FSymbSize write FSymbSize default 7; property Parity : TParity read FParity write FParity default pt_Odd; property StopBits : TStopBits read FStopBits write FStopBits default sb_Two; property XOnChar : Byte read FXonChar write FXonChar default 3; property XOffChar : Byte read FXoffChar write FXoffChar default 2; property ErrorChar : Byte read FErrorChar write FErrorChar default 23; property EofChar : Byte read FEofChar write FEofChar default 4; property EvtChar : Byte read FEvtChar write FEvtChar default 25; property ToTotal : Boolean read FToTotal write FToTotal; property ToIntv : Boolean read FToIntv write FToIntv; property ToValue : Cardinal read FToValue write FToValue default 1000; end; const // Численные значения скоростей передачи CBaudRateArray : array[ TBaudRate] of Cardinal = (50, 100, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200); var CommNames : TStringList; //------------------------------------ Список имен всех портов implementation //======================================================================================== constructor TComPort.Create( AOwner : TComponent); begin inherited Create( AOwner); //--------------------вызов конструктора предка, TComponent FWindowHandle := AllocateHWnd(WndProc); //--------------- Установить обработчик порта if (Owner <> nil) and (Owner is TWinControl) then //Установить HWND на окно назначения MessageDest := (Owner as TWinControl).Handle else MessageDest := 0; //------------------ Если не является потомком класса TWinControl if CommNames = nil then //-------------- Получить список доступных в системе COM-портов begin // Если не инициализирован список доступных COM-портов - получить полный список CommNames := TStringList.Create; if not GetCommNames then //--------------------------------- если не найдены COM-порты begin ShowMessage('Нет зарегистрированных СОМ-портов!'+#13+'Программа завершает работу.'); Application.Terminate; Exit; end; end; //---------------------------------------------- Установка параметров порта по умолчанию rcverrcnt := 0; //------------------------------------------ счетчик ошибок приема = 0 trmerrcnt := 0; //---------------------------------------- счетчик ошибок передачи = 0 PortIsOpen := false; //--------------------------------------------------- Порт закрыт FBaudRate := br_9600; //--------------------------------------------- скорость 9600 бод FFlowCtrl := fc_No; //---------------------------------- Выключено управление потоком FXOnLim := 1; //--------------------------- Мин. кол-во байт в буфере перед Xon FXOffLim := 512; //------------------------- Макс. кол-во байт в буфере перед Xoff FSymbSize := 8; //-------------------------------------------------- Символ 8 бит FParity := pt_No; //--------------------------------- Контроль паритета отсутствует FStopBits := sb_One; //------------------------------------------------- Один стоп-бит FXOnChar := 3; //----------------------------------------------- Код символа Xon FXOffChar := 2; //------------------------- Макс. кол-во байт в буфере перед Xoff FErrorChar := 23; //-------------------------------------------- Код символа ошибки FEofChar := 4; //-------------------------------------- Код символа конца данных FEvtChar := 25; //------------------------------ Код символа сигнализации события FToTotal := false; //---------------------------------- Исп. общий таймаут сообщения FToIntv := false; //--------------------------------------Исп. интервальный таймаут FToValue := 1000; //--------------------------------- Величина общего таймаута в мс TrmEvent := TEvent.Create(nil,TRUE,TRUE,'CPM_TRANSMIT_COMPLETE' ); //-- событие передачи if TrmEvent.Handle = 0 then begin Application.Terminate; Exit; end //------- не создано else TrmOLS.hEvent := TrmEvent.Handle; //------- установить событие в структуру передачи RcvEvent := TEvent.Create(nil,TRUE,TRUE,'CPM_RECIEVE_COMPLETE');//------- событие приема if RcvEvent.Handle = 0 then begin Application.Terminate; Exit; end //------- не создано else RcvOLS.hEvent := RcvEvent.Handle; //-------- установить событие в структуру приема TrmInProg := FALSE; //----------------------------------- Сбросить флаг течения передачи RcvInProg := FALSE; //--------------------------------------------------------- и приема end; // TComPort.Create //======================================================================================== destructor TComPort.Destroy; begin //---------------------------------------------- Освободить обработчик порта для системы DeallocateHWnd(FWindowHandle); // Закрыть обработчик порта if PortIsOpen then CloseHandle(PortHandle); inherited; end; // TComPort.Destroy //======================================================================================== //------------------------------------------------------------------ Записать буфер в порт function TComPort.BufToComm(Buf: pchar; Len : Integer) : cardinal; var lpe : DWORD; lps : COMSTAT; lpNBWri : Cardinal; begin Result := 0; //-------------------------------------------------- Заполнить структуры состояния порта if ClearCommError(PortHandle, lpe, @lps) then begin if Len > 0 then begin //------------- Записать в буфер порта (lps.cbOutQue = количество символов в буфере) if not WriteFile(PortHandle, Buf[0], Len, lpNBWri, @TrmOLS) then begin if GetLastError <> ERROR_IO_PENDING then begin //--------------------------- Ошибка не была связана с отложенной передачей PurgeComm(PortHandle,PURGE_TXABORT or PURGE_TXCLEAR); //------------ сброс порта inc(trmerrcnt);//---------------------- Увеличить счетчик ошибок передачи порта. Exit; end; end; //---- если кол-во всспринятых для передачи символов(TrmOLS.InternalHigh) отличается //-- от длины передаваемого сообщения(i), то увеличить счетчик ошибок передачи порта if integer(TrmOLS.InternalHigh) <> Len then inc(trmerrcnt); end; result := TrmOLS.InternalHigh; //--------- Вернуть кол-во воспринятых портом символов. end; end; //======================================================================================== //-------------------------------------------------------- Записать строку символов в порт function TComPort.StrToComm(trmstring: string) : longword; var i : integer; lpe : DWORD; lps : COMSTAT; lpNBWri : Cardinal; begin Result := 0; //-------------------------------------------------- Заполнить структуры состояния порта if ClearCommError(PortHandle, lpe, @lps) then begin i := Length(trmstring); //-------------------------------- Вычислить длину сообщения для записи в буфер порта. if i > (Length(Buffer) - integer(lps.cbOutQue)) then i := Length(Buffer) - integer(lps.cbOutQue); //-- Длина сообщения(i) = длина буфера(Length(soob)) - кол-во символов в буфере порта, //--------------------------------- оставшихся после последней передачи(lps.cbOutQue). if i > 0 then begin //-------------------------------------------------------- Копировать данные в буфер Move(trmstring[1], Buffer[0], i); //------------- Записать в буфер порта (lps.cbOutQue = количество символов в буфере) if not WriteFile( PortHandle, Buffer, i, lpNBWri, @TrmOLS) then //----- для передачи begin if GetLastError <> ERROR_IO_PENDING then //если ошибка не флаг отложенной передачи begin PurgeComm( PortHandle, PURGE_TXABORT or PURGE_TXCLEAR); //-------- очистить порт inc(trmerrcnt);//---------------------- Увеличить счетчик ошибок передачи порта. Exit; end; end; //------- Увеличить счетчик ошибок передачи порта, если кол-во принятых для передачи //----- символов(TrmOLS.InternalHigh) отличается от длины передаваемого сообщения(i) if integer(TrmOLS.InternalHigh) <> i then inc(trmerrcnt); end; result := i; // Вернуть кол-во записанных в порт символов. end; end; //======================================================================================== //------------------------------------------------------------- Прочитать из порта в буфер function TComPort.BufFromComm(Buf: pchar; MaxLen : Integer) : cardinal; var j : integer; lpe : DWORD; lps : COMSTAT; lpNBRd : Cardinal; begin lpNBRd := 0; Result := 0; //-------------------------------------------------- Заполнить структуры состояния порта if ClearCommError(PortHandle,lpe,@lps) then//если успешно сброшена ошибка или ее не было begin j := lps.cbInQue; //---------------------- Кол-во символов готовых для чтения из порта //--------------------------------- Сравнить кол-во символов в очереди с длиной буфера if j > MaxLen then j := MaxLen; // Ограничить кол-во читаемых символов по длине буфера if j > 0 then begin //------------------------- Прочитать буфер порта (j = количество символов в буфере) if not ReadFile(PortHandle, Buf[0], j, lpNBRd, @RcvOLS) then begin //------------------------------------------------------- Завершение с ошибкой if GetLastError <> ERROR_IO_PENDING then //---- если это не ошибка ожидания данных begin PurgeComm( PortHandle, PURGE_RXABORT or PURGE_RXCLEAR);//----------очистить порт inc(rcverrcnt);//---------------------- Увеличить счетчик ошибок порта по чтению Exit; end; end; //----------------------- Проверить соответствие кол-ва полученных из порта символов // Увеличить счетчик ошибок порта по приему если счетчик прочитанных // символов(lpNBRd) отличается от кол-ва символов, запрашиваемых из буфера порта(j). if j <> integer(lpNBRd) then inc(rcverrcnt); end; end; result := lpNBRd; end; //======================================================================================== //------------------------------------------------------ Чтение полученных данных из порта function TComPort.StrFromComm(var rcvstring: string) : boolean; var i,j : integer; lpe : DWORD; lps : COMSTAT; lpNBRd : Cardinal; label lp1; begin Result := false; rcvstring := ''; lp1: if ClearCommError(PortHandle, lpe, @lps) then //---- Заполнить структуры состояния порта begin //----------------------------------------------- если функция завершилась успешно while lps.cbInQue > 0 do begin j := lps.cbInQue;//--------------------- Кол-во символов готовых для чтения из порта if j > Length(Buffer) then //--------- если прочитанных символов больше длины буфера j := Length(Buffer);//---------- Ограничить кол-во читаемых символов по длине буфера if j > 0 then //---------------------------------------- если есть символы в буфере begin //- Прочитать буфер порта,j-столько хотим прочитать,lpNBRd - столько прочитали if not ReadFile(PortHandle,Buffer,j,lpNBRd,@RcvOLS) then // если чтение не удалось begin //------------------------------------------ если чтение завершено с ошибкой if GetLastError <> ERROR_IO_PENDING then begin //-------------------- если ошибка не является флагом отложенной передачи PurgeComm(PortHandle,PURGE_RXABORT or PURGE_RXCLEAR); //------- очистить буфер inc(rcverrcnt); //------------------ Увеличить счетчик ошибок порта по чтению Exit; end; end; for i := 0 to j-1 do //--------------- Скопировать символы из буфера в строку rcvstring := rcvstring + Buffer[i]; //--------- добавить в строку данные из буфера if j <> integer(lpNBRd) then //------------ если принято не столько сколько хотели inc(rcverrcnt);//------------------------ Увеличить счетчик ошибок порта по приему end; end; end; result := true; end; //======================================================================================== //---------------------------------------------------------------- Инициализация СОМ порта function TComPort.InitPort(CommPortParam: string) : Boolean; //----------------------------- Параметры передаются в одной строке, разделенные запятыми: // -------------------------------------------------------------------------- Номер порта // ---------------------------- Код скорости работы порта в соответствии с CBaudRateArray // ----------------------------------------------------- Паритет в соответствии с TParity // --------------------------------- Код количества стоп-битов в соответствии с TStopBits // -------------------------------------- Кол-во бит в символе в соответствии с TSymbSize // -------------------------------------------- Код символа сигнализации события FEvtChar //---------------------------- Если значение параметра пустое - оставить прежнее значение //------------------- Код завершения true при отсутствии ошибок в параметрах, иначе false var i,p : integer; begin s := CommPortParam; i := 1; result := false; //--------------------------------------------------------------- Установить номер порта sp := ''; while s[i] <> ',' do begin sp := sp + s[i]; inc(i); if i > Length(s) then exit; end; inc(i); if i > Length(s) then exit; sp := 'COM'+ sp; //----------- Завершить с ошибкой,если такой порт не зарегистрирован в списке COM-портов if (CommNames = nil) or (CommNames.IndexOf(sp) < 0) then exit; PortName := sp; //--------------------------------------------------- Наименование порта //---------------------------------------------------------------- Скорость работы порта sp := ''; while s[i] <> ',' do begin sp := sp + s[i]; inc(i); if i > Length(s) then exit; end; if sp <> '' then begin try p := StrToInt(sp) except exit;//------------------- Завершить с ошибкой если параметр скорости задан не верно end; FBaudRate := TBaudRate(p); //----------------------------------------- скорость обмена end; inc(i); if i > Length(s) then begin result := true; exit; end; //------------------------------------------------------------------------- Тип паритета sp := ''; while s[i] <> ',' do begin sp := sp + s[i]; inc(i); if i > Length(s) then exit; end; if sp <> '' then begin try p := StrToInt(sp) except exit;//------------------- Завершить с ошибкой если параметр паритета задан не верно end; FParity := TParity(p); //----------------------------------------------------- Паритет end; inc(i); if i > Length(s) then begin result := true; exit; end; //------------------------------------------------------------ Код количества стоп-битов sp := ''; while s[i] <> ',' do begin sp := sp + s[i]; inc(i); if i > Length(s) then exit; end; if sp <> '' then begin try p := StrToInt(sp) except exit;//------ Завершить с ошибкой если параметр количества стоп-битов задан не верно end; FStopBits := TStopBits(p); //--------------------------------------- кол-во стоп битов end; inc(i); if i > Length(s) then begin result := true; exit; end; //------------------------------------------------------------- Количество бит в символе sp := ''; while s[i] <> ',' do begin sp := sp + s[i]; inc(i); if i > Length(s) then break; end; if sp <> '' then begin try p := StrToInt(sp) except exit;//--- Завершить с ошибкой если параметр количества бит в символе задан не верно end; FSymbSize := TSymbSize(p); // кол-во бит в символе end; inc(i); if i > Length(s) then begin result := true; exit; end; //----------------------------------------------------- Код символа сигнализации события sp := ''; while s[i] <> ',' do begin sp := sp + s[i]; inc(i); if i > Length(s) then break; end; if sp <> '' then FEvtChar := byte(sp[1]); //----------- Код символа сигнализации события result := true; end; // TComPort.InitPort //======================================================================================== //--------------------------------------------------------------- Закрыть обработчик порта function TComPort.ClosePort : Boolean; begin result := CloseHandle(PortHandle); if result then PortIsOpen := false; end; //======================================================================================== //---------------------------------------------------------- Вычислить параметры таймаутов procedure TComPort.CalcTimeouts; var HSL : Byte; begin //---------------------------------------------------------------- Длина символа в битах HSL := FSymbSize + 2; //---------------------------------- Стартовый и 1 (один) стоповый if FStopBits <> sb_One then Inc( HSL);//------------------- Если больше одного стопового if ( FParity <> pt_No) and FParityEn then Inc( HSL); //----------- За счет бита паритета with Timeouts do begin //-------------------------------------------------------------------- Таймауты чтения if FToIntv then begin //----------------------------------- Таймаут ожидания следующего символа при приеме ReadIntervalTimeout := 10 * ( Trunc( HSL * 1000 / CBaudRateArray[ FBaudRate]) + 1); end else ReadIntervalTimeout := 0; if FToTotal then begin //-------------------------------------- Таймаут ожидания одного символа в сообщении ReadTotalTimeoutMultiplier := Trunc( HSL * 1000 / CBaudRateArray[ FBaudRate]) + 1; //------------------------------ Постоянная составляющая таймаута ожидания сообщения ReadTotalTimeoutConstant := FToValue; end else begin //-------------------------------------- Таймаут ожидания одного символа в сообщении ReadTotalTimeoutMultiplier := 0; //------------------------------ Постоянная составляющая таймаута ожидания сообщения ReadTotalTimeoutConstant := 0; end; //-------------------------------------------------------------------- Таймауты записи WriteTotalTimeoutMultiplier := Trunc( HSL * 1000 / CBaudRAteArray[ FBaudRate]) + 1; WriteTotalTimeoutConstant := 50; end; SetCommTimeouts( PortHandle, Timeouts); end; //======================================================================================== //-- Определяет зарегистрированные в реестре Windows имена посл. портов и формирует список // имен в переменной CommNames. Возвращает "T" при наличии хотя бы одного порта, иначе "F" function TComPort.GetCommNames : Boolean; var VReg : TRegistry; i : integer; Val : TStringList; begin Result := false; VReg := TRegistry.Create; Val := TStringList.Create; with VReg do begin RootKey := HKEY_LOCAL_MACHINE; try if OpenKeyReadOnly('HARDWARE\DEVICEMAP\SERIALCOMM') then begin GetValueNames( Val ); for i := 0 to Val.Count - 1 do begin if (Val.Strings[i] <> '') then CommNames.Add(ReadString(Val.Strings[i])); end; Result := ( CommNames <> nil) and ( CommNames.Count > 0); CloseKey; Val.Free; exit; end; finally Free; end; //---------------------------------------------------------------- try .. finally end; Val.Free; VReg.Free; ShowMessage('В реестре не найдены записи Win98 или Win2k. Com-порты недоступны.'); exit; end;// TComPort.GetCommNames //======================================================================================== // Заполняет поля коммуникационнной структуры DCB из Win32 SDK procedure TComPort.FillDCB; begin with PortDCB do begin DCBLength := SizeOf( DCB); //----------------------------------------- Длина структуры BaudRate := CBaudRateArray [ FBaudRate];//---------------------------- Скорость обмена Flags := 1; //----------------------- Флаги Для Win32 - fBinary установить обязательно if FParityEn then Flags := Flags or $2;//--------------------- Использование паритета if FCTSFlow then Flags := Flags or $4;//------------------ Управление выходом по CTS if FDSRFlow then Flags := Flags or $8;//------------------ Управление выходом по DSR case FDTRControl of dtr_Enable : Flags := Flags or $10;//--------------------------- Есть управление DTR dtr_Handshake : Flags := Flags or $20;//----- Установка соединения с применением DTR end; if FDSRSense then Flags := Flags or $40;//------- Чувствительность к сигналу DSR if FTxCont then Flags := Flags or $80;//------ Продолжение передачи после Xoff if FOutX then Flags := Flags or $100; //--- Использовать XoffXon при передаче if FInX then Flags := Flags or $200;//------ Использовать XoffXon при приеме if FErrorReplace then Flags := Flags or $400;//Заменять байты с ошибками на ErrorChar if FDiscardNull then Flags := Flags or $800;//- Удаление нулевых байтов из сообщения case FRTSControl of rts_Enable : Flags := Flags or $1000;//---------------------- Есть управление RTS rts_Handshake : Flags := Flags or $2000;// Установка соединения с использованием RTS rts_Toggle : Flags := Flags or $3000;//------------------------- Переключение RTS end; if FAbortOnError then Flags := Flags or $4000;//---------- Прерывать обмен при ошибке XOnLim := FXOnLim;//---------------------------- Мин. кол-во байт в буфере перед Xon XOffLim := FXOffLim; //------------------------ Макс. кол-во байт в буфере перед Xoff ByteSize := FSymbSize; //---------------------------------------- Кол-во бит в символе Parity := Ord( FParity);//--------------------------------------------- Тип паритета StopBits := Ord( FStopBits);//-------------------------------------- Кол-во стоп-битов XonChar := Chr( FXonChar);//--------------------------------------- Кол-во стоп-битов XoffChar := Chr( FXoffChar);//-------------------------------------- Кол-во стоп-битов ErrorChar:= Chr( FErrorChar);//------------------------------------ Код символа ошибки EofChar := Chr( FEofChar);//-------------------------------- Код символа конца данных EvtChar := Chr( FEvtChar);//------------------------ Код символа сигнализации события end; end; //======================================================================================== //------------------------------------------- Пытается открыть и сконфигурировать СОМ-порт //------------------------------------------ Возвращает TRUE в случае удачи, иначе - FALSE function TComPort.OpenPort : Boolean; begin OpenPort := FALSE; PortIsOpen := FALSE; PortHandle := CreateFile(PChar('\\.\'+FPortName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); if PortHandle = INVALID_HANDLE_VALUE then begin PortError := GetLastError; Exit; end; //------------------------------------------------------ Заполнить поля блока управления FillDCB; if not SetCommState( PortHandle, PortDCB) then begin PortError := GetLastError; Exit; end; CalcTimeouts; lvCdr := EV_RXFLAG; SetCommMask( PortHandle, lvCdr); CancelIO(PortHandle); OpenPort := TRUE; PortIsOpen := TRUE; end; //======================================================================================== //---------------------------------- Изменяет состояние сигнала RTS - только постоянно !!! function TComPort.RTSOnOff(aOn: Boolean): Boolean; begin if aOn then FRTSControl := rts_Enable else FRTSControl := rts_Disable; FillDCB; Result := SetCommState( PortHandle, PortDCB); end; // TComPort.RTSOnOff //======================================================================================== //---------------------------------- Изменяет состояние сигнала DTR - только постоянно !!! function TComPort.DTROnOff(aOn: Boolean): Boolean; begin if aOn then FDTRControl := dtr_Enable else FDTRControl := dtr_Disable; FillDCB; Result := SetCommState( PortHandle, PortDCB); end; // TComPort.RTSOnOff //======================================================================================== //------------------------------------------------------------- обработчик сообщений порта procedure TComPort.WndProc( var Msg :TMessage); begin with Msg do case Msg of //------------- CPM_TRMSIGNAL = WM_USER + $7009 ------ Сигнал события передатчика CPM_TRMSIGNAL : begin case TWaitResult( WParam) of wrError, wrAbandoned : //----------------------------------- ошибка при ожидании begin PurgeComm( PortHandle, PURGE_TXABORT or PURGE_TXCLEAR); TrmInProg := FALSE; TrmEvent.ResetEvent; end; wrSignaled : //----------------------------------------------------- Есть сигнал begin TransmitFinish; TrmEvent.ResetEvent; end; end; // case TWaitResult( WParam) end; //--------------- CPM_RCVSIGNAL = WM_USER + $7010 ------- Сигнал события приемника CPM_RCVSIGNAL : begin case TWaitResult( WParam) of wrError, wrAbandoned : //----------------------------------- ошибка при ожидании begin PurgeComm( PortHandle, PURGE_RXABORT or PURGE_RXCLEAR); RcvInProg := FALSE; RcvEvent.ResetEvent; end; wrSignaled : //----------------------------------------------------- Есть сигнал begin RecieveFinish; RcvEvent.ResetEvent; end; end; // case TWaitResult( WParam) end; else Result := DefWindowProc( FWindowHandle, Msg, wParam, lParam); end; // case Msg end; // TComPort.WndProc //======================================================================================== //---------------------------------------------------------------------- Завершение приема procedure TComPort.RecieveFinish; //var //HErr : Cardinal; begin if not RcvInProg then Exit; //---------------- Выход, если не уст. флаг течения передачи RcvInProg := FALSE;//-------------------------------------- Сбросить флаг течения приема if not GetOverlappedResult(PortHandle,RcvOLS,RcvdBytes,FALSE) then // если успешно завершено //---------------- CPM_RCVSUCCESS = CPM_RCVFAILED + 1 ------ Успешное завершение приема // PostMessage( MessageDest, CPM_RCVSUCCESS, RcvdBytes, 0) // else //------------------------------------------------------- если завершилось неудачей begin //HErr := GetLastError;//----------------------------------------- Получить номер ошибки CancelIO( PortHandle); //------------- Принудительно завершить все операции с портом //-------------------------------------- Сообщение о незавершенности операции передачи // if HErr = ERROR_IO_INCOMPLETE then //----------------------- CPM_RCVFAILED = CPM_TRMSUCCESS + 1; ----- Ошибка при приеме // PostMessage( MessageDest, CPM_RCVFAILED, cpeRcvEndOverlap, HErr) //else PostMessage( MessageDest, CPM_RCVFAILED, cpeRcvEndFailed, HErr); end; end; // TComPort.RecieveFinish //======================================================================================== //-------------------------------------------------------------------- Завершение передачи procedure TComPort.TransmitFinish; //var // HErr : Cardinal; begin if not TrmInProg then Exit; TrmInProg := FALSE;//------------------------------------ Сбросить флаг течения передачи if not GetOverlappedResult(PortHandle,TrmOLS,TrmdBytes,FALSE) then//неудачное завершение begin // HErr := GetLastError;//----------------------------------------- Получить номер ошибки CancelIO( PortHandle);//---------------- Принудительно завершить все операции с портом RcvInProg := FALSE; //----------------------------------- Сбросить флаг течения приема end; end; //----------------------------------------------------------- TComPort.TransmitFinish end.
unit MinisteriesSheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers, ExtCtrls, ComCtrls, InternationalizerComponent; const tidMinisterCount = 'MinisterCount'; tidActualRuler = 'ActualRuler'; tidCurrBlock = 'CurrBlock'; type TMinisteriesSheetHandler = class; TMinisteriesSheetViewer = class(TVisualControl) lvMinisteries: TListView; Panel1: TPanel; nbPages: TNotebook; pnBudgetEdit: TPanel; lbBudget: TLabel; btnSetBudget: TFramedButton; btnDepose: TFramedButton; edBudget: TEdit; edMinister: TEdit; lbMinister: TLabel; btnElect: TFramedButton; InternationalizerComponent1: TInternationalizerComponent; procedure edBudgetChange(Sender: TObject); procedure lvMinisteriesChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure btnSetBudgetClick(Sender: TObject); procedure btnDeposeClick(Sender: TObject); procedure btnElectClick(Sender: TObject); private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private fHandler : TMinisteriesSheetHandler; fProperties : TStringList; protected procedure SetParent(which : TWinControl); override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; end; TMinisteriesSheetHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TMinisteriesSheetViewer; fHasAccess : boolean; fCurrBlock : integer; public function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; procedure Clear; override; private procedure threadedGetProperties(const parms : array of const); procedure threadedRenderProperties(const parms : array of const); procedure threadedSetMinistryBudget( const parms : array of const ); procedure threadedDeposeMinister( const parms : array of const ); procedure threadedSitMinister( const parms : array of const ); end; var MinisteriesSheetViewer: TMinisteriesSheetViewer; function MinisteriesHandlerCreator : IPropertySheetHandler; stdcall; implementation uses Threads, SheetHandlerRegistry, FiveViewUtils, Protocol, SheetUtils, MathUtils, {$IFDEF VER140} Variants, {$ENDIF} Literals, ClientMLS, CoolSB; {$R *.DFM} // TMinisteriesSheetHandler function TMinisteriesSheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TMinisteriesSheetViewer.Create(Owner); fControl.fProperties := TStringList.Create; fControl.fHandler := self; result := fControl; end; function TMinisteriesSheetHandler.GetControl : TControl; begin result := fControl; end; procedure TMinisteriesSheetHandler.RenderProperties(Properties : TStringList); var cnt : integer; i : integer; iStr : string; Item : TListItem; aux : string; lng : string; begin try fControl.fProperties.Assign( Properties ); SheetUtils.ClearListView(fControl.lvMinisteries); fControl.lvMinisteries.Items.BeginUpdate; try fHasAccess := GrantAccess( fContainer.GetClientView.getSecurityId, Properties.Values['SecurityId'] ) or (uppercase(Properties.Values[tidActualRuler]) = uppercase(fContainer.GetClientView.getUserName)); cnt := StrToInt(Properties.Values[tidMinisterCount]); lng := '.' + ClientMLS.ActiveLanguage; for i := 0 to pred(cnt) do begin iStr := IntToStr(i); Item := fControl.lvMinisteries.Items.Add; Item.Caption := Properties.Values['Ministry' + iStr + lng]; aux := Properties.Values['Minister' + iStr]; if aux = '' then aux := GetLiteral('Literal46'); Item.SubItems.Add(aux); Item.SubItems.Add(Properties.Values['MinisterRating' + iStr] + '%'); Item.SubItems.Add(FormatMoneyStr(Properties.Values['MinisterBudget' + iStr])); end; finally fControl.SetBounds(fControl.Left,fControl.Top,fControl.Width,fControl.Height); fControl.lvMinisteries.Items.EndUpdate; end; if cnt = 0 then SheetUtils.AddItem(fControl.lvMinisteries, [GetLiteral('Literal47')]); fControl.pnBudgetEdit.Visible := fHasAccess; except fControl.pnBudgetEdit.Visible := false; end; end; procedure TMinisteriesSheetHandler.SetFocus; begin if not fLoaded then begin inherited; SheetUtils.AddItem(fControl.lvMinisteries, [GetLiteral('Literal48')]); Threads.Fork( threadedGetProperties, priHigher, [fLastUpdate] ); end; end; procedure TMinisteriesSheetHandler.Clear; begin inherited; fControl.lvMinisteries.Items.BeginUpdate; try fControl.lvMinisteries.Items.Clear; finally fControl.lvMinisteries.Items.EndUpdate; end; end; procedure TMinisteriesSheetHandler.threadedGetProperties(const parms : array of const); var Names : TStringList; Update : integer; Prop : TStringList; Proxy : OleVariant; aux : string; i : integer; iStr : string; lng : string; begin Update := parms[0].vInteger; try Lock; try Proxy := fContainer.GetCacheObjectProxy; if (Update = fLastUpdate) and not VarIsEmpty(Proxy) then begin aux := Proxy.Properties(tidMinisterCount); if (Update = fLastUpdate) and (aux <> '') then begin Names := TStringList.Create; Prop := TStringList.Create; Prop.Values[tidMinisterCount] := aux; try lng := '.' + ClientMLS.ActiveLanguage; for i := 0 to pred(StrToInt(aux)) do begin iStr := IntToStr(i); Names.Add('MinistryId' + iStr); Names.Add('Ministry' + iStr + lng); Names.Add('Minister' + iStr); Names.Add('MinisterRating' + iStr); Names.Add('MinisterBudget' + iStr); Names.Add('SecurityId'); end; Names.Add( tidActualRuler ); Names.Add( tidCurrBlock ); if Update = fLastUpdate then fContainer.GetPropertyList(Proxy, Names, Prop); finally Names.Free; end; if Update = fLastUpdate then Join(threadedRenderProperties, [Prop, Update]) else Prop.Free; end; end; finally Unlock; end; except end; end; procedure TMinisteriesSheetHandler.threadedRenderProperties(const parms : array of const); var Prop : TStringList absolute parms[0].vPointer; begin try try if fLastUpdate = parms[1].vInteger then RenderProperties(Prop); fCurrBlock := StrToInt(Prop.Values[tidCurrBlock]); finally Prop.Free; end; except end; end; procedure TMinisteriesSheetHandler.threadedSetMinistryBudget( const parms : array of const ); var MinId : integer; Budget : currency; MSProxy : olevariant; begin try MinId := parms[0].vInteger; Budget := parms[1].VCurrency^; if fHasAccess and (Budget > 0) then try MSProxy := fContainer.GetMSProxy; MSProxy.BindTo(fCurrBlock); MSProxy.RDOSetMinistryBudget(MinId, CurrToStr(Budget)); except beep; end; except end; end; procedure TMinisteriesSheetHandler.threadedDeposeMinister(const parms : array of const); var MinId : integer; MSProxy : olevariant; begin try MinId := parms[0].vInteger; if fHasAccess then try MSProxy := fContainer.GetMSProxy; MSProxy.BindTo(fCurrBlock); MSProxy.RDOBanMinister(MinId); except beep; end; except end; end; procedure TMinisteriesSheetHandler.threadedSitMinister( const parms : array of const ); var MinId : integer; MSProxy : olevariant; MinName : string; begin try MinId := parms[0].vInteger; MinName := parms[1].vPChar; if fHasAccess then try MSProxy := fContainer.GetMSProxy; MSProxy.BindTo(fCurrBlock); MSProxy.RDOSitMinister(MinId, MinName); except beep; end; except end; end; // TWorkforceSheetViewer procedure TMinisteriesSheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; // MinisteriesHandlerCreator function MinisteriesHandlerCreator : IPropertySheetHandler; begin result := TMinisteriesSheetHandler.Create; end; procedure TMinisteriesSheetViewer.edBudgetChange(Sender: TObject); begin try btnSetBudget.Enabled := (edBudget.Text <> '') and (FormattedStrToMoney( edBudget.Text ) >= 0); except btnSetBudget.Enabled := false; end; end; procedure TMinisteriesSheetViewer.lvMinisteriesChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin edBudget.Enabled := lvMinisteries.Selected <> nil; if lvMinisteries.Selected <> nil then edBudget.Text := lvMinisteries.Selected.SubItems[2] else edBudget.Text := ''; btnSetBudget.Enabled := lvMinisteries.Selected <> nil; btnDepose.Enabled := lvMinisteries.Selected <> nil; if (lvMinisteries.Selected <> nil) then if fProperties.Values['Minister' + IntToStr(lvMinisteries.Selected.Index)] <> '' then nbPages.PageIndex := 0 else nbPages.PageIndex := 1; end; procedure TMinisteriesSheetViewer.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var sum : integer; i : integer; dwStyles : DWORD; begin inherited; if (lvMinisteries <> nil) //and (lvMinisteries.Items <> nil) then begin sum := 0; for i := 0 to pred(lvMinisteries.Columns.Count-1) do inc(sum, lvMinisteries.Columns[i].Width); dwStyles := GetWindowLong(lvMinisteries.Handle, GWL_STYLE); if (dwStyles and WS_VSCROLL) <> 0 then Inc(sum, GetSystemMetrics(SM_CXVSCROLL)); lvMinisteries.Columns[lvMinisteries.Columns.Count-1].Width := lvMinisteries.Width-sum-2; end; end; procedure TMinisteriesSheetViewer.btnSetBudgetClick(Sender: TObject); var budget : currency; begin try lvMinisteries.Selected.SubItems[2] := FormatMoney(FormattedStrToMoney( edBudget.Text )); budget := FormattedStrToMoney(edBudget.Text); Fork( fHandler.threadedSetMinistryBudget, priNormal, [StrToInt(fProperties.Values['MinistryID' + IntToStr(lvMinisteries.Selected.Index)]), budget] ); except end; end; procedure TMinisteriesSheetViewer.btnDeposeClick(Sender: TObject); begin try Fork( fHandler.threadedDeposeMinister, priNormal, [StrToInt(fProperties.Values['MinistryID' + IntToStr(lvMinisteries.Selected.Index)])] ); except end; end; procedure TMinisteriesSheetViewer.btnElectClick(Sender: TObject); begin try Fork( fHandler.threadedSitMinister, priNormal, [StrToInt(fProperties.Values['MinistryID' + IntToStr(lvMinisteries.Selected.Index)]), edMinister.Text] ); except end; end; procedure TMinisteriesSheetViewer.SetParent(which: TWinControl); begin inherited; if InitSkinImage and (which<>nil) then begin InitializeCoolSB(lvMinisteries.Handle); if hThemeLib <> 0 then SetWindowTheme(lvMinisteries.Handle, ' ', ' '); CoolSBEnableBar(lvMinisteries.Handle, FALSE, TRUE); CustomizeListViewHeader( lvMinisteries ); end; end; initialization SheetHandlerRegistry.RegisterSheetHandler('Ministeries', MinisteriesHandlerCreator); end.
unit pdfvrsemantico; {$mode objfpc}{$H+} interface uses Classes, SysUtils, pdfvrlexico, fpvectorial; type AnSemantico = class public close_path_x: String; close_path_y: String; cm_a, cm_b, cm_c, cm_d, cm_e, cm_f: Real; // coordinate spaces constants function generate(c: Command; AData: TvVectorialDocument): String; function convert(x: String; y: String; Axis: Char): String; function startMachine(): String; function endMachine(): String; constructor Create; end; implementation function AnSemantico.generate(c: Command; AData: TvVectorialDocument): String; var enter_line : String; begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.generate'); {$endif} enter_line:= LineEnding; //chr(13) + chr(10); // CR and LF if ((c.code = cc_H_CLOSE_PATH) or (c.code = cc_hS_CLOSE_AND_END_PATH)) then // command h or s begin c.cord_x:=close_path_x; c.cord_y:=close_path_y; end; if ((c.code <> cc_H_CLOSE_PATH) and (c.code <> cc_hS_CLOSE_AND_END_PATH)) then // close path already converted begin if ((c.code = cc_m_START_PATH) or (c.code = cc_l_ADD_LINE_TO_PATH)) then begin //WriteLn(':: anSemantico.generate convert code ', Integer(c.code)); c.cord_x := convert(c.cord_x,c.cord_y,'x'); c.cord_y := convert(c.cord_x,c.cord_y,'y'); end; if ((c.code = cc_c_BEZIER_TO_X_Y_USING_X2_Y2_AND_X3_Y3)) then begin //WriteLn(':: anSemantico.generate convert code ', Integer(c.code)); c.cord_x := convert(c.cord_x,c.cord_y,'x'); c.cord_y := convert(c.cord_x,c.cord_y,'y'); c.cord_x2 := convert(c.cord_x2,c.cord_y2,'x'); c.cord_y2 := convert(c.cord_x2,c.cord_y2,'y'); c.cord_x3 := convert(c.cord_x3,c.cord_y3,'x'); c.cord_y3 := convert(c.cord_x3,c.cord_y3,'y'); end; end; case c.code of cc_m_START_PATH: // command m begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.generate Estado 1 EndPath StartPath'); {$endif} // Result:='G01' + ' ' + 'X' + c.cord_x + ' ' + 'Y' + c.cord_y + enter_line + // 'G01 Z50 // Abaixa a cabeça de gravação'; // Correcao para programas de desenho que geram um novo inicio no // fim do desenho, terminamos qualquer desenho inacabado AData.EndPath(); AData.StartPath(StrToFloat(c.cord_x), StrToFloat(c.cord_y)); close_path_x:=c.cord_x; close_path_y:=c.cord_y; end; cc_l_ADD_LINE_TO_PATH: // command l begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.generate Estado 2 AddPointToPath'); {$endif} // Result:='G01' + ' ' + 'X' + c.cord_x + ' ' + 'Y' + c.cord_y; AData.AddLineToPath(StrToFloat(c.cord_x), StrToFloat(c.cord_y)); end; cc_h_CLOSE_PATH: // command h begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.generate Estado 3 AddPointToPath'); {$endif} //Result:='G01' + ' ' + 'X' + c.cord_x + ' ' + 'Y' + c.cord_y; AData.AddLineToPath(StrToFloat(c.cord_x), StrToFloat(c.cord_y)); end; cc_S_END_PATH: // command S begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.generate Estado 4 EndPath'); {$endif} // Result:='G01 Z0 // Sobe a cabeça de gravação' + enter_line; AData.EndPath(); end; cc_hS_CLOSE_AND_END_PATH: // command s begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.generate Estado 5 AddPoint EndPath'); {$endif} //Result:='G01' + ' ' + 'X' + c.cord_x + ' ' + 'Y' + c.cord_y + enter_line // +'G01 Z0 // Sobe a cabeça de gravação' + enter_line; AData.AddLineToPath(StrToFloat(c.cord_x), StrToFloat(c.cord_y)); AData.EndPath(); end; cc_c_BEZIER_TO_X_Y_USING_X2_Y2_AND_X3_Y3: // command c begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.generate Estado 6 Bezier'); {$endif} //Result:='G01' + ' ' + 'X' + c.cord_x + ' ' + 'Y' + c.cord_y + enter_line // +'G01 Z0 // Sobe a cabeça de gravação' + enter_line; AData.AddBezierToPath( StrToFloat(c.cord_x3), StrToFloat(c.cord_y3), StrToFloat(c.cord_x2), StrToFloat(c.cord_y2), StrToFloat(c.cord_x), StrToFloat(c.cord_y) ); end; cc_CONCATENATE_MATRIX: // command cm begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.cc_CONCATENATE_MATRIX'); {$endif} cm_a := StrToFloat(c.cord_x3); cm_b := StrToFloat(c.cord_y3); cm_c := StrToFloat(c.cord_x2); cm_d := StrToFloat(c.cord_y2); cm_e := StrToFloat(c.cord_x); cm_f := StrToFloat(c.cord_y); end; cc_RESTORE_MATRIX: // command Q begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.cc_RESTORE_MATRIX'); {$endif} cm_a:=1; cm_b:=0; cm_c:=0; cm_d:=1; cm_e:=0; cm_f:=0; end; else {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.generate Estado ELSE'); {$endif} Result:=c.my_operator; end; end; function AnSemantico.convert(x: String; y: String; Axis: Char): String; begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.convert'); {$endif} // convert from 1/72 inch to milimeters and change axis if necessary if (Axis = 'y') then begin // y' = b * x + d * y + f Result:=FloatToStr((cm_b*StrToFloat(x)+cm_d*StrToFloat(y)+cm_f)*(25.40/72)); end else // Axis = 'x' begin // x' = a * x + c * y + e Result:=FloatToStr((cm_a*StrToFloat(x)+cm_c*StrToFloat(y)+cm_e)*(25.40/72)); end; end; function AnSemantico.startMachine(): String; var enter_line : String; begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.startMachine'); {$endif} enter_line:=chr(13) + chr(10); // CR and LF Result:='M216 // Ligar monitor de carga' + enter_line + 'G28 // Ir rapidamente para posição inicial' + enter_line + 'G00' + enter_line; end; function AnSemantico.endMachine(): String; var enter_line : String; begin {$ifdef FPVECTORIALDEBUG} WriteLn(':> AnSemantico.endMachine'); {$endif} enter_line:=chr(13) + chr(10); // CR and LF Result:='M30 // Parar o programa e retornar para posição inicial' + enter_line + 'M215 // Desligar monitor de carga' + enter_line; end; constructor AnSemantico.Create; begin inherited Create; cm_a:=1; cm_b:=0; cm_c:=0; cm_d:=1; cm_e:=0; cm_f:=0; end; end.
unit Vehicles; interface uses ActorPool; type IVehicle = interface; IVehicleArray = interface; TVehicleDirection = (vdirN, vdirNE, vdirE, vdirSE, vdirS, vdirSW, vdirW, vdirNW); TArrayChange = (achUpdate, achVehicleInsertion, achVehicleDeletion); TOnVehicleArrayChanged = procedure( VehicleArray : IVehicleArray; ArrayChange : TArrayChange; const Info ) of object; IVehicle = interface function getX : single; function getY : single; function getAngle : single; function getDir : TVehicleDirection; function getNextDir : TVehicleDirection; function getVisualClass : word; function getCustomData : pointer; function getGroupId : integer; procedure setCustomData( data : pointer; datasize : integer ); end; IVehicleArray = interface function getVehicleCount : integer; function getVehicle( index : integer ) : IVehicle; procedure RegisterNotificationProc ( OnArrayChanged : TOnVehicleArrayChanged ); procedure UnregisterNotificationProc( OnArrayChanged : TOnVehicleArrayChanged ); end; const evnAnswerVehicleArray = 3425; msgAnswerVehicle = 3426; type TMsgAnswerVehicleArrayInfo = record ActorPoolId : TActorPoolId; VehicleArray : IVehicleArray; end; TMsgAnswerVehicle = record MsgId : word; Vehicle : IVehicle; end; implementation end.
{ * AXTextAttributedString.h * * Copyright (c) 2002 Apple Computer, Inc. All rights reserved. * } { Pascal Translation: Gale R Paeper, <gpaeper@empirenet.com>, 2006 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit AXTextAttributedString; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes, CFBase; {$ALIGN POWER} var kAXFontTextAttribute: CFStringRef; external name '_kAXFontTextAttribute'; (* attribute const *) // CFDictionaryRef - see kAXFontTextAttribute keys below var kAXForegroundColorTextAttribute: CFStringRef; external name '_kAXForegroundColorTextAttribute'; (* attribute const *) // CGColorRef var kAXBackgroundColorTextAttribute: CFStringRef; external name '_kAXBackgroundColorTextAttribute'; (* attribute const *) // CGColorRef var kAXUnderlineColorTextAttribute: CFStringRef; external name '_kAXUnderlineColorTextAttribute'; (* attribute const *) // CGColorRef var kAXStrikethroughColorTextAttribute: CFStringRef; external name '_kAXStrikethroughColorTextAttribute'; (* attribute const *) // CGColorRef var kAXUnderlineTextAttribute: CFStringRef; external name '_kAXUnderlineTextAttribute'; (* attribute const *) // CFNumberRef - AXUnderlineStyle var kAXSuperscriptTextAttribute: CFStringRef; external name '_kAXSuperscriptTextAttribute'; (* attribute const *) // CFNumberRef = + number for superscript - for subscript var kAXStrikethroughTextAttribute: CFStringRef; external name '_kAXStrikethroughTextAttribute'; (* attribute const *) // CFBooleanRef var kAXShadowTextAttribute: CFStringRef; external name '_kAXShadowTextAttribute'; (* attribute const *) // CFBooleanRef var kAXAttachmentTextAttribute: CFStringRef; external name '_kAXAttachmentTextAttribute'; (* attribute const *) // AXUIElementRef var kAXLinkTextAttribute: CFStringRef; external name '_kAXLinkTextAttribute'; (* attribute const *) // AXUIElementRef var kAXNaturalLanguageTextAttribute: CFStringRef; external name '_kAXNaturalLanguageTextAttribute'; (* attribute const *) // CFStringRef - the spoken language of the text var kAXReplacementStringTextAttribute: CFStringRef; external name '_kAXReplacementStringTextAttribute'; (* attribute const *) // CFStringRef var kAXMisspelledTextAttribute: CFStringRef; external name '_kAXMisspelledTextAttribute'; (* attribute const *) // AXUIElementRef // kAXFontTextAttribute keys var kAXFontNameKey: CFStringRef; external name '_kAXFontNameKey'; (* attribute const *) // CFStringRef - required var kAXFontFamilyKey: CFStringRef; external name '_kAXFontFamilyKey'; (* attribute const *) // CFStringRef - not required var kAXVisibleNameKey: CFStringRef; external name '_kAXVisibleNameKey'; (* attribute const *) // CFStringRef - not required var kAXFontSizeKey: CFStringRef; external name '_kAXFontSizeKey'; (* attribute const *) // CFNumberRef - required const kAXUnderlineStyleNone = $0; kAXUnderlineStyleSingle = $1; kAXUnderlineStyleThick = $2; kAXUnderlineStyleDouble = $9; type AXUnderlineStyle = UInt32; // DO NOT USE. This is an old, misspelled version of one of the above constants. var kAXForegoundColorTextAttribute: CFStringRef; external name '_kAXForegoundColorTextAttribute'; (* attribute const *) // CGColorRef 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 OfficePartner * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 2000-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) unit ExSMail3; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, OpShared, OpOlkXP, OpOutlk, sEdit, sListBox, sButton, sComboBox, sLabel, sBevel, sPanel; type {: Enum for recipient routing: To. CC, Bcc. Used internal to this file only } TRecipientType = (rtTo, rtCC, rtBCC); {: Simple object wrap an AddressEntry interface since interfaces can not be reliably stored in pointer lists without manually handling _Addref and _Release } TAddressEntryWrapper = class( TObject ) private fAddress: AddressEntry; public {: Return a duplicate of self with Address assigned } function Clone: TAddressEntryWrapper; property Address: AddressEntry read fAddress write fAddress; end; TForm3 = class(TForm) Panel1: TsPanel; Bevel1: TsBevel; Panel2: TsPanel; Bevel2: TsBevel; Panel3: TsPanel; Label1: TsLabel; cbAddressLists: TsComboBox; Label2: TsLabel; lbNames: TsListBox; btnTo: TsButton; edtName: TsEdit; btnCC: TsButton; btnBcc: TsButton; Label3: TsLabel; btnOK: TsButton; btnCancel: TsButton; lbTo: TsListBox; lbCC: TsListBox; lbBcc: TsListBox; procedure FormShow(Sender: TObject); procedure cbAddressListsChange(Sender: TObject); procedure edtNameChange(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnToClick(Sender: TObject); procedure lbToDblClick(Sender: TObject); procedure lbNamesDblClick(Sender: TObject); procedure lbToKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } fOutlook: TOpOutlook; procedure AddCurrentToRecipients( Which: TRecipientType ); {: clear all items and free all objects in the passed list box } procedure FlushListBox( aListBox: TsListBox ); {: clear all items and free all objects from the Names ListBox } procedure FlushNamesListBox; {: clear all items and free all objects from the To, CC, & BCC ListBoxes } procedure FlushRecipientListBoxes; {: Accessor for RecipientTo, RecipientCC, & RecipientBCC } function GetRecipient( Index: integer ): string; {: Set up initial state of all controls } procedure InitControls( bEnabled: Boolean ); public property Outlook: TOpOutlook read fOutlook write fOutlook; //: semicolon delimited string containing the "BCC" recipients' email addresses property RecipientBCC: string index 2 read GetRecipient; //: semicolon delimited string containing the "CC" recipients' email addresses property RecipientCC: string index 1 read GetRecipient; //: semicolon delimited string containing the "To" recipients' email addresses property RecipientTo: string index 0 read GetRecipient; end; var Form3: TForm3; implementation {$R *.DFM} { TAddressEntryWrapper } function TAddressEntryWrapper.Clone: TAddressEntryWrapper; begin result := TAddressEntryWrapper.Create; result.Address := Address; end; { TdlgSelectNames } procedure TForm3.AddCurrentToRecipients(Which: TRecipientType); var oListBox: TListBox; begin case Which of rtTo : oListBox := lbTo; rtCC : oListBox := lbCC; rtBCC : oListBox := lbBcc; else oListBox := lbTo; end; if lbNames.ItemIndex >= 0 then oListBox.Items.AddObject( lbNames.Items[lbNames.ItemIndex], TAddressEntryWrapper(lbNames.Items.Objects[lbNames.ItemIndex]).Clone ); end; procedure TForm3.btnToClick(Sender: TObject); begin if Sender is TButton then AddCurrentToRecipients( TRecipientType(TButton(Sender).Tag )) end; procedure TForm3.FormShow(Sender: TObject); begin if assigned( fOutlook ) and ( fOutlook.Connected )then InitControls( True ) else InitControls( False ); end; procedure TForm3.cbAddressListsChange(Sender: TObject); var idx: integer; oAddressList: AddressList; i: Integer; oAddress: TAddressEntryWrapper; begin cbAddressLists.Update; FlushNamesListBox; idx := cbAddressLists.Items.IndexOf( cbAddressLists.Text ); if idx >= 0 then begin oAddressList := fOutlook.MapiNamespace.AddressLists.Item(idx + 1); if assigned( oAddressList ) then if oAddressList.AddressEntries.Count > 0 then begin lbNames.Items.BeginUpdate; try for i := 1 to oAddressList.AddressEntries.Count do begin oAddress := TAddressEntryWrapper.Create; oAddress.Address := oAddressList.AddressEntries.Item(i); lbNames.Items.AddObject( oAddress.Address.Name, oAddress ) end finally lbNames.Items.EndUpdate; end; end end; end; procedure TForm3.edtNameChange(Sender: TObject); var i: Integer; begin Try if lbNames.Items.Count > 0 then begin for i := 0 to lbNames.Items.Count do { Iterate } if CompareText( edtName.Text, Copy(lbNames.Items[i], 1, Length(edtName.Text)) ) = 0 then begin lbNames.ItemIndex := i; break; end; end; except end; end; procedure TForm3.FlushListBox( aListBox: TsListBox ); var i: Integer; begin if aListBox.Items.Count > 0 then begin for i := aListBox.Items.Count - 1 downto 0 do if assigned( aListBox.Items.Objects[i] ) then aListBox.Items.Objects[i].Free; aListBox.Items.Clear; end; end; procedure TForm3.FlushNamesListBox; begin FlushListBox( lbNames ); end; procedure TForm3.FlushRecipientListBoxes; begin FlushListBox(lbTo); FlushListBox(lbCC); FlushListBox(lbBCC); end; procedure TForm3.FormDestroy(Sender: TObject); begin FlushNamesListBox; FlushRecipientListBoxes; end; function TForm3.GetRecipient(Index: integer): string; var i: Integer; oListBox: TListBox; begin result := ''; // this must be done because otherwise result acts like a static case Index of { } 0: oListBox := lbTo; 1: oListBox := lbCC; 2: oListBox := lbBCC; else oListBox := lbTo; end; { case } if oListBox.Items.Count > 0 then for i := 0 to oListBox.Items.Count - 1 do if assigned( oListBox.Items.Objects[i] ) then result := result + TAddressEntryWrapper(oListBox.Items.Objects[i]). Address.Address + ';'; if Length(result) > 0 then Delete(result, Length(Result), 1 ); end; procedure TForm3.InitControls(bEnabled: Boolean); var i: Integer; begin for i := 0 to ControlCount -1 do Controls[i].Enabled := bEnabled; cbAddressLists.Clear; edtName.Clear; if bEnabled then if fOutlook.MapiNamespace.AddressLists.Count > 0 then begin for i := 1 to fOutlook.MapiNamespace.AddressLists.Count do cbAddressLists.Items.Add(fOutlook.MapiNamespace.AddressLists.Item(i).Name ); end; FlushNamesListBox; FlushRecipientListBoxes; end; procedure TForm3.lbNamesDblClick(Sender: TObject); begin AddCurrentToRecipients(rtTo); end; procedure TForm3.lbToDblClick(Sender: TObject); begin if Sender is TListBox then with TListBox(Sender) do if ItemIndex >= 0 then begin Items.Objects[ItemIndex].Free; Items.Delete(ItemIndex) end; end; //: type ahead search procedure TForm3.lbToKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Sender is TListBox then if Key = VK_Delete then with TListBox(Sender) do if ItemIndex >= 0 then begin Items.Objects[ItemIndex].Free; Items.Delete(ItemIndex) end; end; end .
unit ADC.NetInfo; interface uses Winapi.Windows, Winapi.Winsock2; const AI_PASSIVE = $01; AI_CANONNAME = $02; AI_NUMERICHOST = $04; AI_ALL = $0100; AI_ADDRCONFIG = $0400; AI_V4MAPPED = $0800; AI_NON_AUTHORITATIVE = $04000; AI_SECURE = $08000; AI_RETURN_PREFERRED_NAMES = $010000; AI_FQDN = $00020000; AI_FILESERVER = $00040000; type PADDRINFO = ^addrinfo; addrinfo = packed record ai_flags : Integer; ai_family : Integer; ai_socktype : Integer; ai_protocol : Integer; ai_addrlen : size_t; ai_canonname : PAnsiChar; ai_addr : LPSOCKADDR; ai_next : PADDRINFO; end; type DHCP_IP_ADDRESS = DWORD; PDHCP_IP_ADDRESS = ^DHCP_IP_ADDRESS; LPDHCP_IP_ADDRESS = ^PDHCP_IP_ADDRESS; DHCP_IP_MASK = DWORD; DHCP_RESUME_HANDLE = DWORD; {$MINENUMSIZE 4} type _QuarantineStatus = ( NOQUARANTINE = 0, RESTRICTEDACCESS = 1, DROPPACKET = 2, PROBATION = 3, EXEMPT = 4, DEFAULTQUARSETTING = 5, NOQUARINFO = 6 ); QuarantineStatus =_QuarantineStatus; type _DHCP_BINARY_DATA = record DataLength : DWORD; Data : LPBYTE; end; DHCP_BINARY_DATA = _DHCP_BINARY_DATA; LPDHCP_BINARY_DATA = ^DHCP_BINARY_DATA; DHCP_CLIENT_UID = DHCP_BINARY_DATA; type _DATE_TIME = record dwLowDateTime : DWORD; dwHighDateTime : DWORD; end; DATE_TIME = _DATE_TIME; LPDATE_TIME = ^DATE_TIME; type _DHCP_HOST_INFO = record IpAddress : DHCP_IP_ADDRESS; NetBiosName : LPWSTR; HostName : LPWSTR; end; DHCP_HOST_INFO = _DHCP_HOST_INFO; LPDHCP_HOST_INFO = ^DHCP_HOST_INFO; type _DHCP_CLIENT_SEARCH_TYPE = ( DhcpClientIpAddress, DhcpClientHardwareAddress, DhcpClientName ); DHCP_SEARCH_INFO_TYPE = _DHCP_CLIENT_SEARCH_TYPE; LPDHCP_SEARCH_INFO_TYPE = ^DHCP_SEARCH_INFO_TYPE; type _DHCP_CLIENT_SEARCH_UNION = record case Integer of 0: (ClientIpAddress: DHCP_IP_ADDRESS); 1: (ClientHardwareAddress: DHCP_CLIENT_UID); 2: (ClientName: LPWSTR); end; type _DHCP_CLIENT_SEARCH_INFO = record SearchType: DHCP_SEARCH_INFO_TYPE; SearchInfo: _DHCP_CLIENT_SEARCH_UNION; end; DHCP_SEARCH_INFO = _DHCP_CLIENT_SEARCH_INFO; LPDHCP_SEARCH_INFO = ^DHCP_SEARCH_INFO; type _DHCPDS_SERVER = record Version : DWORD; ServerName : LPWSTR; ServerAddress : DWORD; Flags : DWORD; State : DWORD; DsLocation : LPWSTR; DsLocType : DWORD; end; DHCPDS_SERVER = _DHCPDS_SERVER; PDHCPDS_SERVER = ^DHCPDS_SERVER; PDhcpServerArray = ^TDhcpServerArray; TDhcpServerArray = array [0..100] of DHCPDS_SERVER; type _DHCPDS_SERVERS = record Flags : DWORD; NumElements : DWORD; Servers : PDhcpServerArray; end; DHCPDS_SERVERS = _DHCPDS_SERVERS; PDHCPDS_SERVERS = ^DHCPDS_SERVERS; PDHCP_SERVER_INFO_ARRAY = ^DHCPDS_SERVERS; LPDHCP_SERVER_INFO_ARRAY = ^PDHCP_SERVER_INFO_ARRAY; type _DHCP_CLIENT_INFO = record ClientIpAddress : DHCP_IP_ADDRESS; SubnetMask : DHCP_IP_MASK; ClientHardwareAddress : DHCP_CLIENT_UID; ClientName : LPWSTR; ClientComment : LPWSTR; ClientLeaseExpires : DATE_TIME; OwnerHost : DHCP_HOST_INFO; end; DHCP_CLIENT_INFO = _DHCP_CLIENT_INFO; PDHCP_CLIENT_INFO = ^DHCP_CLIENT_INFO; LPDHCP_CLIENT_INFO = ^PDHCP_CLIENT_INFO; type _DHCPV4_FAILOVER_CLIENT_INFO = record ClientIpAddress : DHCP_IP_ADDRESS; SubnetMask : DHCP_IP_MASK; ClientHardwareAddress : DHCP_CLIENT_UID; ClientName : LPWSTR; ClientComment : LPWSTR; ClientLeaseExpires : DATE_TIME; OwnerHost : DHCP_HOST_INFO; bClientType : BYTE; AddressState : BYTE; Status : QuarantineStatus; ProbationEnds : DATE_TIME; QuarantineCapable : Boolean; SentPotExpTime : DWORD; AckPotExpTime : DWORD; RecvPotExpTime : DWORD; StartTime : DWORD; CltLastTransTime : DWORD; LastBndUpdTime : DWORD; bndMsgStatus : DWORD; PolicyName : LPWSTR; flags : BYTE; end; DHCPV4_FAILOVER_CLIENT_INFO = _DHCPV4_FAILOVER_CLIENT_INFO; LPDHCPV4_FAILOVER_CLIENT_INFO = ^DHCPV4_FAILOVER_CLIENT_INFO; type _DHCP_CLIENT_INFO_PB = record ClientIpAddress : DHCP_IP_ADDRESS; SubnetMask : DHCP_IP_MASK; ClientHardwareAddress : DHCP_CLIENT_UID; ClientName : PWideChar; ClientComment : PWideChar; ClientLeaseExpires : DATE_TIME; OwnerHost : DHCP_HOST_INFO; bClientType : BYTE; AddressState : BYTE; Status : QuarantineStatus; ProbationEnds : DATE_TIME; QuarantineCapable : Boolean; FilterStatus : DWORD; PolicyName : PWideChar; end; DHCP_CLIENT_INFO_PB = _DHCP_CLIENT_INFO_PB; LPDHCP_CLIENT_INFO_PB = ^DHCP_CLIENT_INFO_PB; type _DHCP_IP_ARRAY = record NumElements: DWORD; Elements: LPDHCP_IP_ADDRESS; end; DHCP_IP_ARRAY = _DHCP_IP_ARRAY; LPDHCP_IP_ARRAY = ^DHCP_IP_ARRAY; type _DHCP_CLIENT_INFO_ARRAY = record NumElements: DWORD; Clients: LPDHCP_CLIENT_INFO; end; DHCP_CLIENT_INFO_ARRAY = _DHCP_CLIENT_INFO_ARRAY; LPDHCP_CLIENT_INFO_ARRAY = ^DHCP_CLIENT_INFO_ARRAY; TDhcpGetClientInfo = function(ServerIpAddress: PWideChar; SearchInfo: LPDHCP_SEARCH_INFO; ClientInfo: PDHCP_CLIENT_INFO): DWORD; stdcall; TDhcpV4GetClientInfo = function(ServerIpAddress: PWideChar; SearchInfo: LPDHCP_SEARCH_INFO; ClientInfo: LPDHCP_CLIENT_INFO_PB): DWORD; stdcall; TDhcpV4FailoverGetClientInfo = function(ServerIpAddress: PWideChar; SearchInfo: LPDHCP_SEARCH_INFO; ClientInfo: LPDHCPV4_FAILOVER_CLIENT_INFO): DWORD; stdcall; function DhcpEnumServers(Flags: DWORD; IdInfo: LPVOID; Servers: LPDHCP_SERVER_INFO_ARRAY; CallbackFn: LPVOID; CallbackData: LPVOID): DWORD; stdcall; function DhcpEnumSubnets(ServerIpAddress: PWideChar; var ResumeHandle: DHCP_RESUME_HANDLE; PreferredMaximum: DWORD; EnumInfo: LPDHCP_IP_ARRAY; out ElementsRead, ElementsTotal: DWORD): DWORD; stdcall; function DhcpEnumSubnetClients(ServerIpAddress: PWideChar; SubnetAddress: DHCP_IP_ADDRESS; var ResumeHandle: DHCP_RESUME_HANDLE; PreferredMaximum: DWORD; ClientInfo: LPDHCP_CLIENT_INFO_ARRAY; out ClientsRead, ClientsTotal: DWORD): DWORD; stdcall; //function DhcpGetClientInfo(ServerIpAddress: PWideChar; SearchInfo: LPDHCP_SEARCH_INFO; // ClientInfo: LPDHCP_CLIENT_INFO): DWORD; stdcall; //function DhcpV4GetClientInfo(ServerIpAddress: PWideChar; // SearchInfo: LPDHCP_SEARCH_INFO; ClientInfo: LPDHCP_CLIENT_INFO_PB): DWORD; stdcall; //function DhcpV4FailoverGetClientInfo(ServerIpAddress: PWideChar; // SearchInfo: LPDHCP_SEARCH_INFO; ClientInfo: LPDHCPV4_FAILOVER_CLIENT_INFO): DWORD; stdcall; procedure DhcpRpcFreeMemory(BufferPointer: Pointer); stdcall; function getaddrinfo(pNodeName: PAnsiChar; pServiceName: PAnsiChar; const pHints: PADDRINFO; out ppResult: PADDRINFO): Integer; stdcall; procedure freeaddrinfo(ai: PADDRINFO); stdcall; implementation function DhcpEnumServers; external 'dhcpsapi.dll' name 'DhcpEnumServers'; function DhcpEnumSubnets; external 'dhcpsapi.dll' name 'DhcpEnumSubnets'; function DhcpEnumSubnetClients; external 'dhcpsapi.dll' name 'DhcpEnumSubnetClients'; //function DhcpGetClientInfo; external 'dhcpsapi.dll' name 'DhcpGetClientInfo'; //function DhcpV4GetClientInfo; external 'dhcpsapi.dll' name 'DhcpV4GetClientInfo'; //function DhcpV4FailoverGetClientInfo; external 'dhcpsapi.dll' name 'DhcpV4FailoverGetClientInfo'; procedure DhcpRpcFreeMemory; external 'dhcpsapi.dll' name 'DhcpRpcFreeMemory'; function getaddrinfo; external 'Ws2_32.dll' name 'getaddrinfo'; procedure freeaddrinfo; external 'Ws2_32.dll' name 'freeaddrinfo'; end.
unit GX_GExperts; {$I GX_CondDefine.inc} interface uses Classes, ToolsAPI, Controls, GX_EditorExpertManager, GX_Experts; type TGExperts = class(TNotifierObject, IOTANotifier, IOTAWizard) private FEditorExpertsManager: TGxEditorExpertManager; FExpertList: TList; FStartingUp: Boolean; procedure InstallAddIn; function GetExpert(const Index: Integer): TGX_Expert; function GetExpertCount: Integer; procedure InitializeGExperts; protected // IOTAWizard function GetIDString: string; function GetName: string; function GetState: TWizardState; procedure Execute; public constructor Create; destructor Destroy; override; procedure LoadEditorExperts; procedure FreeEditorExperts; function FindExpert(const ExpertName: string; out Idx: Integer): boolean; property EditorExpertManager: TGxEditorExpertManager read FEditorExpertsManager; property ExpertList[const Index: Integer]: TGX_Expert read GetExpert; property ExpertCount: Integer read GetExpertCount; property StartingUp: Boolean read FStartingUp; procedure RefreshExpertShortCuts; procedure ShowConfigurationForm; class procedure DelayedRegister; class procedure DoInitialize(Sender: TObject); procedure DoAfterIDEInitialized(Sender: TObject); function GetSharedImages: TImageList; function GetExpertList: TList; end; function GExpertsInst(ForceValid: Boolean = False): TGExperts; procedure ShowGXAboutForm; procedure ShowGXConfigurationForm; procedure InitSharedResources; procedure FreeSharedResources; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} SysUtils, Dialogs, ExtCtrls, GX_GenericUtils, GX_GetIdeVersion, GX_About, GX_MenuActions, GX_MessageBox, GX_ConfigurationInfo, GX_Configure, GX_KbdShortCutBroker, GX_SharedImages, GX_IdeUtils, GX_IdeEnhance, GX_EditorChangeServices, GX_ToolbarDropDown; type TInitHelper = class(TObject) private FInitTimer: TTimer; FCallback: TNotifyEvent; FInitCount: Integer; procedure OnInitTimer(Sender: TObject); public constructor Create(CallBack: TNotifyEvent); end; TUnsupportedIDEMessage = class(TGxMsgBoxAdaptor) protected function GetMessage: string; override; function ShouldShow: Boolean; override; end; var FPrivateGExpertsInst: TGExperts = nil; InitHelper: TInitHelper = nil; SharedImages: TdmSharedImages = nil; function GExpertsInst(ForceValid: Boolean): TGExperts; begin if ForceValid and (not Assigned(FPrivateGExpertsInst)) then raise Exception.Create('GExpertsInst is not a valid reference'); Result := FPrivateGExpertsInst; end; procedure ShowGXAboutForm; begin with gblAboutFormClass.Create(nil) do try ShowModal; finally Free; end; end; procedure ShowGXConfigurationForm; begin with TfmConfiguration.Create(nil) do try ShowModal; finally Free; end; end; procedure InitSharedResources; begin if not Assigned(SharedImages) then SharedImages := TdmSharedImages.Create(nil); end; procedure FreeSharedResources; begin {$IFOPT D+} SendDebug('Freeing shared images'); {$ENDIF} FreeAndNil(SharedImages); end; { TGExperts } constructor TGExperts.Create; begin {$IFOPT D+} SendDebug('TGExperts.Create'); {$ENDIF} inherited Create; FStartingUp := True; InitializeGExperts; InitHelper := TInitHelper.Create(DoAfterIDEInitialized); gblAboutFormClass.AddToAboutDialog; end; class procedure TGExperts.DelayedRegister; begin {$IFOPT D+} SendDebug('TGExperts.DelayedRegister'); {$ENDIF} InitHelper := TInitHelper.Create(DoInitialize); end; procedure TGExperts.InitializeGExperts; resourcestring SInitError = 'Initialization Error:' + sLineBreak; begin FExpertList := TList.Create; FPrivateGExpertsInst := Self; InitSharedResources; // Create the action manager. {$IFOPT D+} SendDebug('Creating GXActionManager'); {$ENDIF} CreateGXMenuActionManager; try {$IFOPT D+} SendDebug('Installing AddIn'); {$ENDIF} InstallAddIn; {$IFOPT D+} SendDebug('Successfully installed AddIn'); {$ENDIF} except on E: Exception do begin GxLogException(E); MessageDlg(SInitError + E.Message, mtError, [mbOK], 0); { Swallow the exception; at least D5 and BCB5 are allergic to exceptions when loading *packages*. Better safe than sorry for DLLs. } end; end; end; destructor TGExperts.Destroy; resourcestring SDestructionError = 'GExperts destruction error: '; var i: Integer; begin try {$IFOPT D+} SendDebug('Destroying GExperts'); {$ENDIF} gblAboutFormClass.RemoveFromAboutDialog; GxKeyboardShortCutBroker.BeginUpdate; try try {$IFOPT D+} SendDebug('Destroying Experts'); {$ENDIF} if FExpertList <> nil then begin for i := 0 to FExpertList.Count - 1 do begin {$IFOPT D+}if ExpertList[i] <> nil then SendDebug('Destroying Expert: ' + ExpertList[i].GetName); {$ENDIF} try ExpertList[i].Free; except on E: Exception do begin // Report the exception and continue to destroy the other experts MessageDlg(Format('Error destroying expert %d: %s', [i, E.Message]), mtError, [mbOK], 0); {$IFOPT D+} SendDebugError(Format('Error destroying expert %d: %s', [i, E.Message])); {$ENDIF} end; end; end; {$IFOPT D+} SendDebug('Done freeing experts'); {$ENDIF} FreeAndNil(FExpertList); end; finally // Release the editor expert manager and the editor experts {$IFOPT D+} SendDebug('Releasing editor expert manager'); {$ENDIF} FreeEditorExperts; FreeIdeEnhancements; ReleaseEditorChangeServices; FreeGXToolBarDropDowns; // Free the action manager and remove any registered keybindings {$IFOPT D+} SendDebug('Freeing Action manager'); {$ENDIF} FreeGXMenuActionManager; FreeSharedResources; end; finally GxKeyboardShortCutBroker.EndUpdate; end; FPrivateGExpertsInst := nil; inherited Destroy; except on E: Exception do begin {$IFOPT D+} SendDebugError('TGExperts.Destroy Error ' + E.Message); {$ENDIF} GxLogAndShowException(E, SDestructionError); raise; end; end; end; procedure TGExperts.Execute; begin //FI:W519 // Do nothing. We install menu and other items to trigger actions. end; function TGExperts.FindExpert(const ExpertName: string; out Idx: Integer): boolean; var i: Integer; begin for i := 0 to ExpertCount - 1 do begin if SameText(ExpertList[i].GetName, ExpertName) then begin Idx := i; Result := True; Exit; end; end; Result := False; end; procedure TGExperts.FreeEditorExperts; begin FreeAndNil(FEditorExpertsManager); end; function TGExperts.GetExpert(const Index: Integer): TGX_Expert; begin Result := TGX_Expert(FExpertList.Items[Index]); end; function TGExperts.GetExpertCount: Integer; begin Result := FExpertList.Count; end; function TGExperts.GetExpertList: TList; begin Result := FExpertList; end; function TGExperts.GetIDString: string; begin Result := 'GExperts.GExperts'; // Do not localize. end; function TGExperts.GetName: string; begin Result := 'GExperts'; // Do not localize. end; function TGExperts.GetSharedImages: TImageList; begin Result := nil; if Assigned(SharedImages) then Result := SharedImages.Images; end; function TGExperts.GetState: TWizardState; begin Result := [wsEnabled]; end; procedure TGExperts.InstallAddIn; resourcestring SExpertCreationFailed = 'Expert "%s" could not be created.' + sLineBreak + 'Reason: %s'; var Expert: TGX_Expert; ExpertClass: TGX_ExpertClass; i: Integer; begin GxKeyboardShortCutBroker.BeginUpdate; try for i := 0 to GX_ExpertList.Count - 1 do begin ExpertClass := GetGX_ExpertClassByIndex(i); try Expert := ExpertClass.Create; FExpertList.Add(Expert); Expert.LoadSettings; except on E: Exception do begin MessageDlg(Format(SExpertCreationFailed, [ExpertClass.ClassName, E.Message]), mtError, [mbOK], 0); // Eat the exception and load other experts (is this safe?) end; end; end; if ConfigInfo.EditorExpertsEnabled then LoadEditorExperts; IdeEnhancements.Initialize; finally GxKeyboardShortCutBroker.EndUpdate; end; ShowGxMessageBox(TUnsupportedIDEMessage); end; procedure TGExperts.LoadEditorExperts; begin FEditorExpertsManager := TGxEditorExpertManager.Create; end; procedure TGExperts.RefreshExpertShortCuts; var i: Integer; Expert: TGX_Expert; begin for i := 0 to GetExpertCount - 1 do begin Expert := GetExpert(i); Expert.ShortCut := Expert.ShortCut; //FI:W503 - Assignment has side effects end; end; procedure TGExperts.ShowConfigurationForm; begin with TfmConfiguration.Create(nil) do try ShowModal; finally Free; end; end; class procedure TGExperts.DoInitialize(Sender: TObject); begin {$IFOPT D+} SendDebug('TGExperts.DoInitialize'); {$ENDIF} (BorlandIDEServices as IOTAWizardServices).AddWizard(TGExperts.Create as IOTAWizard); end; procedure TGExperts.DoAfterIDEInitialized(Sender: TObject); var i: Integer; begin FStartingUp := False; for i := 0 to FExpertList.Count - 1 do ExpertList[i].AfterIDEInitialized; if RunningDelphi8OrGreater then GxKeyboardShortCutBroker.DoUpdateKeyBindings; GXMenuActionManager.ArrangeMenuItems; GXMenuActionManager.MoveMainMenuItems; end; { TUnsupportedIDEMessage } function TUnsupportedIDEMessage.GetMessage: string; resourcestring SBadIDEVersion = 'You are currently using an outdated version of this IDE that has ' + 'patches or update packs available from Embarcadero. GExperts might work, but is ' + 'unsupported running under your IDE. We recommend you upgrade ' + 'using the downloads available on the Embarcadero web site: '+ 'http://cc.embarcadero.com/myreg'; begin Result := SBadIDEVersion; end; function TUnsupportedIDEMessage.ShouldShow: Boolean; begin Result := (GetBorlandIdeVersion in [ // List IDEs here that have OTA/IDE bugs that bother GExperts ideD600, ideD601R, ideD601F, ideD800, ideD801, ideRS2010, ideRS2010U1 // Keyboard macro streaming broken ]); end; { TInitHelper } constructor TInitHelper.Create(CallBack: TNotifyEvent); begin inherited Create; Assert(Assigned(Callback)); FInitTimer := TTimer.Create(nil); FInitTimer.Enabled := False; FInitTimer.OnTimer := OnInitTimer; FInitTimer.Interval := 400; FInitTimer.Enabled := True; FInitCount := 0; FCallback := CallBack; end; procedure TInitHelper.OnInitTimer(Sender: TObject); begin Inc(FInitCount); if (FInitCount >= 4) then begin FInitTimer.Enabled := False; FreeAndNil(FInitTimer); if Assigned(FCallback) then FCallback(Self); end; end; initialization finalization FreeAndNil(InitHelper); end.
{ This file is part of the AF UDF library for Firebird 1.0 or high. Copyright (c) 2007-2009 by Arteev Alexei, OAO Pharmacy Tyumen. See the file COPYING.TXT, included in this distribution, for details about the copyright. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. email: alarteev@yandex.ru, arteev@pharm-tmn.ru, support@pharm-tmn.ru **********************************************************************} unit uafxml; {$ifdef fpc} {$MODE objfpc} {$H+} {$endif} interface uses Classes, SysUtils, ufbblob, DOM, ib_util, uafudfs,XMLRead, XPath,uxmldtd {$IFDEF linux} ,iconvenc ,xmliconv {$IFDEF DEBUG},BaseUnix{$ENDIF} {$else} ,iconvwin ,xmliconv_windows {$ENDIF} ; Type { TUDFXMLDocument } TUDFXMLDocument=class private FEncoding: string; FInputOutputEncoding: string; FDocument:TXMLDocument; public constructor Create(AutoCreate:boolean); destructor Destroy;override; property Encoding: string read FEncoding write FEncoding; property InputOutputEncoding:string read FInputOutputEncoding write FInputOutputEncoding; property Document:TXMLDocument read FDocument write FDocument; end; (*** Document XML ***) {Creates an XML (empty)} function CreateXmlDocument: PtrUdf; cdecl; {Creates an XML object from a string by converting from the encoding specified in XML} function CreateXmlDocFromString (S: PChar): PtrUdf; cdecl; {Creates XML object stored in BLOB encoded in UTF-8} function CreateXmlDocFromBLOB (var BLOB: TFBBlob): PtrUdf; cdecl; {Produces an XML file in UTF-8} function CreateXmlDocFromFile (FileName: PChar): PtrUdf; cdecl; {Setting version xml file} function XMLSetVersion (var Handle: PtrUdf; Ver: PChar): integer; cdecl; {Specifies the encoding in which the data read / write database Encoding} function XMLEncoding (var Handle: PtrUdf; Encoding: PChar): integer; cdecl; {File encoding destination} function XMLEncodingXML (var Handle: PtrUdf; Encoding: PChar): integer; cdecl; {Returns current encoding parameter in vtorroy} function XMLGetEncodingXML (var Handle: PtrUdf): PChar; cdecl; {Returns an XML document to a string encoding purposes.   substituted attribute encoding   Warning limit 32KB !!!} function XMLToString (var Handle: PtrUdf): PChar; cdecl; {Returns an XML document into a BLOB encoded destination   substituted attribute encoding} procedure XMLToBlob (var Handle: PtrUdf; var Blob: TFBBlob); cdecl; {XML node encoding "Encoding"    substituted encoding attribute that clause is used for the database} function XMLXmlNode (var Handle: PtrUdf; var Node: PtrUdf): PChar; cdecl; {Store XML file} function XmlToFile (var Handle: PtrUdf; filename: PChar): integer; cdecl; {------------------------------------------------------------------------------} (*** Tags ***) {Creates a tag to tag Parent (Index - not used TagName, Value encoding Encoding)} function XMLAddNode (var Handle: PtrUdf;var Parent: PtrUdf; TagName: PChar; var Index: integer): PtrUdf; cdecl; {Set the text node of encoding Encoding} function XMLNodeSetText (var Handle: PtrUdf; var Node: PtrUdf; Value: PChar): integer; cdecl; {Returns the text (value) of the node encoding Encoding} function XMLTextNode (var Handle: PtrUdf; var Node: PtrUdf): PChar; cdecl; {Returns the host name or attribute encoding Encoding} function XmlNodeName (var Handle: PtrUdf; var Node: PtrUdf): PChar; cdecl; {Returns whether the node child nodes} function XmlNodeHasChildNodes (var Handle: PtrUdf; var Node: PtrUdf): integer; cdecl; {Returns the number of child nodes of node Node} function XmlNodeCountNodes (var Handle: PtrUdf; var Node: PtrUdf): integer; cdecl; {Returns the child node for Node at index Index} function XmlNodeByIndex (var Handle: PtrUdf; var Node: PtrUdf; var Index: integer): PtrUdf; cdecl; {Search node name in Node} function XmlNodeByName (var Handle: PtrUdf; var Node: PtrUdf; NameNode: PChar): PtrUdf; cdecl; {Returns the text node for simple tag and attribute for an XML tag to tag} procedure XMLTextNodeBlob (var Handle: PtrUdf; var Node: PtrUdf; var Blob: TFBBlob); cdecl; {Store XML node in the Blob. The encoded database} procedure XMLXmlNodeBlob (var Handle: PtrUdf; var Node: PtrUdf; var Blob: TFBBlob); cdecl; {------------------------------------------------------------------------------} (*** Attributes ***) {Creates a tag attribute Parent (Index - not used AttName, Value encoding Encoding)} function XMLAddAtt (var Handle: PtrUdf; var Parent: PtrUdf; AttName: PChar; Value: PChar; var {%H-}Index: integer): PtrUdf; cdecl; {Returns whether the node attributes} function XmlNodeHasAttribute (var Handle: PtrUdf; var Node: PtrUdf; Attribute: PChar): integer; cdecl; {Number attributes of a node} function XmlNodeCountAtt (var Handle: PtrUdf; var Node: PtrUdf): integer; cdecl; {Gets attribute by index} function XmlNodeAttByIndex (var Handle: PtrUdf; var Node: PtrUdf; var Index: integer): PtrUdf; cdecl; {Returns the attribute name encoding Encoding} function XmlNodeAttByName (var Handle: PtrUdf; var Node: PtrUdf; NameAtt: PChar): PtrUdf; cdecl; {Returns the text attribute Value name attribute NameAtt encoding Encoding} function XmlNodeAttByNameVal (var Handle: PtrUdf; var Node: PtrUdf; NameAtt: PChar): PChar; cdecl; {------------------------------------------------------------------------------} (*** XPath ***) {   XmlXPathEval: Evaluates an expression AExpressionString xpath                 AExpressionString: XPath expression                 AContextNode: The context in which the search (XMLDocument, XMLNode)                 Result: Returns a pointer to the list, or zero TDOMNode                                       if an error occurred.   Note: Do not use Free !!! } function XmlXPathEval (var Handle: PtrUdf; AExpressionString: PChar; var AContextNode: PtrUdf): PtrUdf; cdecl; {   XmlXPathEvalValueStr: Evaluates an expression AExpressionString xpath                 Handle: A pointer to the XML object                 AExpressionString: XPath expression                 AContextNode: The context in which the search (XMLDocument, XMLNode)                 Result: Returns the text nodes satisfying expression } function XmlXPathEvalValueStr (var Handle: PtrUdf; AExpressionString: PChar; var AContextNode: PtrUdf): PChar; cdecl; {   XmlXPathEvalValueNum: Evaluates an expression AExpressionString xpath                 Handle: A pointer to the XML object                 AExpressionString: XPath expression                 AContextNode: The context in which the search (XMLDocument, XMLNode)                 Result: Returns the number of (znachnie_ satisfying expression } function XmlXPathEvalValueNum (var Handle: PtrUdf; AExpressionString: PChar; var AContextNode: PtrUdf): Double; cdecl; {   XmlXPathNodeSetItem: Evaluates an expression AExpressionString xpath                 Handle: A pointer to the XML object                 HandleNodeSet: A pointer to the list of TDOMNode XmlXPathEval                 Index: The index of starting from scratch                 Result: Returns a pointer to TXMLNode } function XmlXPathNodeSetItem (var Handle: PtrUdf; var HandleNodeSet: PtrUdf; var Index: integer): PtrUdf; cdecl; {   XmlXPathNodeSetCount: The number in the set when prompted XmlXPathEval                 Handle: A pointer to the XML object                 HandleNodeSet: A pointer to the list of TDOMNode XmlXPathEval                 Result: Returns the number in the set when prompted XmlXPathEval } function XmlXPathNodeSetCount (var Handle: PtrUdf; var HandleNodeSet: PtrUdf): Integer; cdecl; {------------------------------------------------------------------------------} (*** XML DTD 1.5 ***) function CreateXmlFromStream (AStream: TStream): Pchar; {Creates an XML object from a string using a validation document} function CreateXmlDocFromStringDTD (S: PChar): PChar; cdecl; {Creates a BLOB using XML from the validation document} function CreateXmlDocFromBLOBDTD (var BLOB: TFBBlob): PChar; cdecl; {Produces an XML file using a validation document} function CreateXmlDocFromFileDTD (FileName: PChar): PChar; cdecl; {------------------------------------------------- -----------------------------} (*** Auxiliary functions ***) {Return XML document encoded in UTF-8} function inGetXML (doc: TUDFXMLDocument): DOMString; overload; {Any returns XML in UTF-8} function inGetXML (Element: TDOMNode): DOMString; overload; {Conversion of encoding Encoding in UTF-8 encoding of the database} function inConvStrToDOM (const Encoding, AStr: ansistring): DOMString; {Converting from UTF-8 encoding in the Encoding charset for the database} function inConvDOMToStr (const Encoding, AStr: DOMString): ansistring; {Returns the encoding Encoding database that is used to communicate with the database} function inGetEncoding (AObject: TObject): string; inline; {Determines whether to convert to a different encoding different from UTF8} function isNeedConvert (AObject: TObject): boolean; inline; function _getXmlNodeText (XmlNode: TDOMNode): DOMString; (*** Processing attribute encoding ***) {Returns Encoding} function encEncoding (const AXml: AnsiString): AnsiString; {Adds the value of the tag encoding} procedure encAddEncoding (var AXml: String; const Encoding: AnsiString); {Deletes the information about the encoding} procedure encDelEncoding (var AXml: DOMString); {XmlXPathEvalHelper not exported} function XmlXPathEvalHelper (Handle: PtrUdf; AExpressionString: PChar; var AContextNode: PtrUdf): TXPathVariable; implementation uses XMLWrite; const DOMDefaultEncode = 'utf-8'; function CreateXmlDocument: PtrUdf; cdecl; var afobj: TAFObj; XmlDoc: TUDFXMLDocument; begin Result := 0; try XmlDoc := TUDFXMLDocument.Create(true); except if Assigned(XmlDoc) then XmlDoc.Free; exit; end; afobj := TAFObj.Create(XmlDoc); Result := afobj.Handle; end; function CreateXmlDocFromString(S: PChar): PtrUdf; cdecl; var bs:TStringStream; DocOut: TXMLDocument; XmlDoc: TUDFXMLDocument; begin bs:=TStringStream.Create(S); try try ReadXMLFile(DocOut,bs); XmlDoc := TUDFXMLDocument.Create(false); XmlDoc.Document := DocOut; Result := TAFObj.Create(XmlDoc).Handle; except result := 0; end; finally bs.free; end; end; function CreateXmlDocFromBLOB(var BLOB: TFBBlob):PtrUdf;cdecl; var bs:TFBBlobStream; DocOut: TXMLDocument; XmlDoc: TUDFXMLDocument; begin bs:=TFBBlobStream.Create(@BLOB); try try ReadXMLFile(DocOut,bs); XmlDoc := TUDFXMLDocument.Create(false); XmlDoc.Document := DocOut; Result := TAFObj.Create(XmlDoc).Handle; except result := 0; end; finally bs.free; end; end; function CreateXmlDocFromFile(FileName:PChar):PtrUdf;cdecl; var DocOut: TXMLDocument; XmlDoc: TUDFXMLDocument; begin Result := 0; try ReadXMLFile(DocOut,FileName); XmlDoc := TUDFXMLDocument.Create(false); XmlDoc.Document := DocOut; Result := TAFObj.Create(XmlDoc).Handle; except exit(0); end; end; function XMLSetVersion(var Handle: PtrUdf; Ver: PChar): integer; cdecl; var afobj: TAFObj; begin Result := 0; try afobj := HandleToAfObj(Handle); TUDFXMLDocument(afobj.Obj).Document.XMLVersion := Ver; Result := 1; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XMLEncoding(var Handle: PtrUdf; Encoding: PChar): integer; cdecl; var afobj: TAFObj; begin Result := 0; try afobj := HandleToAfObj(Handle); TUDFXMLDocument(afobj.Obj).InputOutputEncoding := Encoding; Result := 1; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XMLEncodingXML(var Handle: PtrUdf; Encoding: PChar): integer; cdecl; var afobj: TAFObj; begin Result := 0; try afobj := HandleToAfObj(Handle); TUDFXMLDocument(afobj.Obj).Encoding := Encoding; Result := 1; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XMLAddNode(var Handle: PtrUdf; var Parent: PtrUdf; TagName: PChar; var Index: integer): PtrUdf; cdecl; var afobj: TAFObj; XmlParent: TDOMElement; XmlNode: TDOMElement; XmlBefore : TDOMNode; XmlTagName: DOMString; begin Result := 0; try afobj := HandleToAfObj(Handle); XmlParent := TDOMElement({%H-}Pointer( PtrUdf(Parent))); XmlTagName := inConvStrToDOM(inGetEncoding(afobj.Obj), TagName); if XmlParent = nil{Parent=0} then begin XmlNode := TUDFXMLDocument(afobj.Obj).Document.CreateElement(XmlTagName); if TUDFXMLDocument(afobj.Obj).Document.HasChildNodes then raise Exception.Create('Only one tag can be root.'); TUDFXMLDocument(afobj.Obj).Document.AppendChild(XmlNode); end else begin XmlParent := TDOMElement({%H-}Pointer(PtrUdf(Parent))); XmlNode := TUDFXMLDocument(afobj.Obj).Document.CreateElement(XmlTagName); with XmlParent.ChildNodes do begin if (Index>=0)and (Index<Integer(Count)) then begin XmlBefore:= Item[Index]; XmlParent.InsertBefore(XmlNode,XmlBefore); end else XmlParent.AppendChild(XmlNode); end; end; Result := ObjToHandle(XmlNode); except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XMLGetEncodingXML(var Handle: PtrUdf): PChar; cdecl; var afobj: TAFObj; sXML: String; begin try afobj := HandleToAfObj(Handle); sXml := UTF8Encode(TUDFXMLDocument(afobj.Obj).Encoding); if sXml = '' then sXml := 'utf-8'; Result := ib_util_malloc(Length(sXML)+1); StrPLCopy(Result, sXML, MaxVarCharLength - 1); except on e: Exception do begin if Assigned(afobj) then afobj.FixedError(e); Result := nil; end; end; end; function XMLToString(var Handle: PtrUdf): PChar; cdecl; var afobj: TAFObj; sXML: string; sXMLDom: DOMString; begin try afobj := HandleToAfObj(Handle); sXMLDom := inGetXML(TUDFXMLDocument(afobj.Obj)); if isNeedConvert(afobj.Obj) then begin with TUDFXMLDocument(afobj.Obj) do begin sXml := inConvDOMToStr(Encoding,sXMLDom); encAddEncoding(sXml,Encoding); end; end else begin sXML := UTF8Encode(sXMLDom); end; Result := ib_util_malloc(Length(sXML)+1); StrPLCopy(Result, sXML , MaxVarCharLength - 1); except on e: Exception do begin if Assigned(afobj) then afobj.FixedError(e); result := nil; end; end; end; procedure XMLToBlob(var Handle: PtrUdf; var Blob: TFBBlob); cdecl; var afobj: TAFObj; sXML: string; sXMLDom: DOMString; begin try afobj := HandleToAfObj(Handle); sXMLDom := inGetXML(TUDFXMLDocument(afobj.Obj)); if isNeedConvert(afobj.Obj) then with TUDFXMLDocument(afobj.Obj) do begin sXml := inConvDOMToStr(Encoding,sXMLDom); encAddEncoding(sXml,Encoding); end else begin sXML := UTF8Encode(sXMLDom); end; with TFBBlobStream.Create(@Blob) do try Write(Pchar(AnsiString(sXML))^,Length(sXML)); finally free; end; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XMLNodeSetText(var Handle: PtrUdf; var Node: PtrUdf; Value: PChar): integer; cdecl; var afobj: TAFObj; XmlNode: TDOMNode; begin Result := 0; try afobj := HandleToAfObj(Handle); XmlNode := HandleToObj(Node) as TDOMNode; if XmlNode <> nil then begin XmlNode.TextContent := inConvStrToDOM(inGetEncoding(afobj.Obj), Value); end else raise Exception.Create('Node is not found.'); Result := 1; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XMLXmlNode(var Handle: PtrUdf; var Node: PtrUdf): PChar; cdecl; var afobj: TAFObj; XmlNode: TDOMNode; s: String; begin try afobj := HandleToAfObj(Handle); XmlNode := HandleToObj(Node) as TDOMNode; if XmlNode = nil then raise Exception.Create('Node not found.'); s := inConvDOMToStr(inGetEncoding(afobj.Obj), inGetXML(XmlNode)); Result := ib_util_malloc(Length(s)+1); StrPLCopy(Result, s , MaxVarCharLength - 1); except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XmlToFile(var Handle: PtrUdf; filename: PChar):integer; cdecl; var afobj : TAFObj; sXML : string; sXMLDom: DOMString; fst : TFileStream; p : ^Pchar; begin result := 0; try afobj := HandleToAfObj(Handle); sXMLDom := inGetXML(TUDFXMLDocument(afobj.Obj)); if isNeedConvert(afobj.Obj) then with TUDFXMLDocument(afobj.Obj) do begin sXml := inConvDOMToStr(Encoding,sXMLDom); encAddEncoding(sXml,Encoding); end else begin sXML := UTF8Encode(sXMLDom); end; if FileExists(filename) then DeleteFile(filename); fst := TFileStream.Create(filename,fmCreate or fmOpenWrite); try p := @sXml[1]; fst.WriteBuffer(p^,length(sXml)); finally fst.Free; end; result := 1; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XMLTextNode(var Handle: PtrUdf; var Node: PtrUdf): PChar; cdecl; var afobj: TAFObj; XmlNode: TDOMNode; s: String; begin try afobj := HandleToAfObj(Handle); XmlNode := HandleToObj(Node) as TDOMNode; if XmlNode = nil then raise Exception.Create('Node not found.'); s := inConvDOMToStr(inGetEncoding(afobj.Obj), XmlNode.TextContent); Result := ib_util_malloc(Length(s)+1); StrPLCopy(Result,s,MaxVarCharLength - 1); except on e: Exception do begin if Assigned(afobj) then afobj.FixedError(e); Result := nil; end; end; end; function XmlNodeName(var Handle: PtrUdf; var Node: PtrUdf): PChar; cdecl; var afobj: TAFObj; XmlNode: TDOMNode; sTagName: DOMString; s: String; begin try afobj := HandleToAfObj(Handle); XmlNode := HandleToObj(Node) as TDOMNode; if XmlNode = nil then raise Exception.Create('Node not found.'); if XmlNode is TDOMElement then sTagName := TDOMElement(XmlNode).TagName else if XmlNode is TDOMAttr then sTagName := TDOMAttr(XmlNode).Name; s := inConvDOMToStr(inGetEncoding(afobj.Obj), sTagName); Result := ib_util_malloc(Length(s)+1); StrPLCopy(Result,s,MaxVarCharLength - 1); except on e: Exception do begin if Assigned(afobj) then afobj.FixedError(e); Result := nil; end; end; end; function XmlNodeHasChildNodes(var Handle: PtrUdf; var Node: PtrUdf): integer; cdecl; var afobj: TAFObj; XmlNode: TDOMNode; begin Result := 0; try afobj := HandleToAfObj(Handle); XmlNode := HandleToObj(Node) as TDOMNode; if (XmlNode <> nil) then if XmlNode.HasChildNodes then result := 1; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XmlNodeHasAttribute(var Handle: PtrUdf; var Node: PtrUdf; Attribute: PChar): integer; cdecl; var afobj: TAFObj; XmlNode: TDOMNode; begin Result := 0; try afobj := HandleToAfObj(Handle); XmlNode := HandleToObj(Node) as TDOMNode; if XmlNode <> nil then Result := integer(XmlNode.Attributes.GetNamedItem(Attribute) <> nil) except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XmlNodeCountNodes(var Handle: PtrUdf; var Node: PtrUdf): integer; cdecl; var afobj: TAFObj; XmlNode: TDOMNode; cld: TDOMNodeList; begin Result := 0; try afobj := HandleToAfObj(Handle); XmlNode := HandleToObj(Node) as TDOMNode; if XmlNode <> nil then cld := XmlNode.ChildNodes else cld := TUDFXMLDocument(afobj.Obj).Document.ChildNodes; Result := cld.Count; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XmlNodeByIndex(var Handle: PtrUdf; var Node: PtrUdf; var Index: integer): PtrUdf; cdecl; var afobj: TAFObj; XmlParent: TDOMNode; XmlFind: TDOMNode; chld : TDOMNodeList; begin Result := 0; try afobj := HandleToAfObj(Handle); XmlParent := HandleToObj(Node) as TDOMNode; try if XmlParent = nil then chld := TUDFXMLDocument(afobj.Obj).Document.ChildNodes else chld := XmlParent.ChildNodes; XmlFind := chld.Item[Index]; finally end; if XmlFind = nil then raise Exception.Create('Node #' + IntToStr(Index) + ' not found.'); Result := ObjToHandle(XmlFind); except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XmlNodeByName(var Handle: PtrUdf; var Node: PtrUdf; NameNode: PChar): PtrUdf; cdecl; var afobj: TAFObj; XmlParent: TDOMNode; XmlFind: TDOMNode; sNameNode: DOMString; begin Result := 0; try afobj := HandleToAfObj(Handle); XmlParent := TDOMNode(HandleToObj(Node)); sNameNode := inConvStrToDOM(inGetEncoding(afobj.Obj), NameNode); try if XmlParent = nil then XmlFind := TUDFXMLDocument(afobj.Obj).Document.FindNode(sNameNode) else XmlFind := XmlParent.FindNode(sNameNode); if XmlFind = nil then raise Exception.Create('Node "' + NameNode + '" not found.'); Result := ObjToHandle(XmlFind); finally end; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XmlNodeCountAtt(var Handle: PtrUdf; var Node: PtrUdf): integer; cdecl; var afobj: TAFObj; XmlNode: TDOMNode; begin Result := 0; try afobj := HandleToAfObj(Handle); XmlNode := HandleToObj(Node) as TDOMNode; if XmlNode = nil then raise Exception.Create('Node not found.'); Result := XmlNode.Attributes.Length; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XmlNodeAttByIndex(var Handle: PtrUdf; var Node: PtrUdf; var Index: integer): PtrUdf; cdecl; var afobj: TAFObj; XmlParent: TDOMNode; XmlFind: TDOMNode; begin Result := 0; try afobj := HandleToAfObj(Handle); XmlParent := HandleToObj(Node) as TDOMNode; if XmlParent <> nil then begin XmlFind := XmlParent.Attributes.Item[Index]; if XmlFind = nil then raise Exception.Create('Node #' + IntToStr(Index) + ' not found.'); Result := ObjToHandle(XmlFind); end else raise Exception.Create('Node not found.'); except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XmlNodeAttByName(var Handle: PtrUdf; var Node: PtrUdf; NameAtt: PChar): PtrUdf; cdecl; var afobj: TAFObj; XmlParent: TDOMNode; XmlFind: TDOMNode; sNameNode: DOMString; begin Result := 0; try afobj := HandleToAfObj(Handle); XmlParent := HandleToObj(Node) as TDOMNode; sNameNode := inConvStrToDOM(inGetEncoding(afobj.Obj), NameAtt); if XmlParent = nil then raise Exception.Create('Node not found.'); try XmlFind := XmlParent.Attributes.GetNamedItem(sNameNode); if XmlFind = nil then begin raise Exception.Create('Node "' + NameAtt + '" not found.'); End; Result := ObjToHandle(XmlFind); finally //SetLength(sNameNode,0); end; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XMLAddAtt(var Handle: PtrUdf; var Parent: PtrUdf; AttName: PChar; Value: PChar; var Index: integer): PtrUdf; cdecl; var afobj: TAFObj; XmlParent: TDOMElement; XmlNode: TDOMNode; sNameAttr: DOMString; begin {Index - не используется} Result := 0; try afobj := HandleToAfObj(Handle); if HandleToObj(Parent) is TUDFXMLDocument then XmlParent := TUDFXMLDocument(afobj.Obj).Document.DocumentElement else XmlParent := HandleToObj(Parent) as TDOMElement; if XmlParent <> nil then begin sNameAttr := inConvStrToDOM(inGetEncoding(afobj.Obj), AttName); if XmlParent.Attributes.GetNamedItem(sNameAttr)<>nil then raise Exception.CreateFmt('Attribute %s already exists',[AttName]); XmlParent.AttribStrings[sNameAttr] := inConvStrToDOM(inGetEncoding(afobj.Obj), Value); XmlNode := XmlParent.GetAttributeNode(sNameAttr); end else raise Exception.Create('Parent Node not found.'); Result := ObjToHandle(XmlNode); except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function XmlNodeAttByNameVal(var Handle: PtrUdf; var Node: PtrUdf; NameAtt: PChar): PChar; cdecl; var afobj: TAFObj; XmlParent: TDOMElement; XmlFind: TDOMNode; sNameAttr: DOMString; s: String; begin try afobj := HandleToAfObj(Handle); if HandleToObj(Node) is TUDFXMLDocument then XmlParent := TUDFXMLDocument(afobj.Obj).Document.DocumentElement else XmlParent := HandleToObj(Node) as TDOMElement; if XmlParent <> nil then begin sNameAttr := inConvStrToDOM(inGetEncoding(afobj.Obj), NameAtt); XmlFind := XmlParent.Attributes.GetNamedItem(sNameAttr); if XmlFind = nil then raise Exception.Create('Attribute "' + NameAtt + '" not found.'); s := inConvDOMToStr(inGetEncoding(afobj.Obj),XmlFind.TextContent); Result:= ib_util_malloc(Length(s)+1); StrPLCopy(Result, s,MaxVarCharLength - 1); end else raise Exception.Create('Node not found.'); except on e: Exception do begin if Assigned(afobj) then afobj.FixedError(e); Result := nil; end; end; end; function XmlXPathEval(var Handle: PtrUdf; AExpressionString: PChar; var AContextNode: PtrUdf): PtrUdf; cdecl; var pv: TXPathVariable; begin pv := XmlXPathEvalHelper(handle,AExpressionString,AContextNode); if pv=nil then Result := 0 else Result := ObjToHandle(pv); // Must be later --> FreeAFObject(TXPathVariable) end; function XmlXPathEvalValueStr(var Handle: PtrUdf; AExpressionString: PChar; var AContextNode: PtrUdf): PChar; cdecl; var pv: TXPathVariable; s: String; udfxml: TUDFXMLDocument; begin try pv := XmlXPathEvalHelper(handle,AExpressionString,AContextNode); try if pv=nil then exit(nil); udfxml := TUDFXMLDocument(TAFObj.FindObj(Handle, taoObject).Obj); s := inConvDOMToStr(inGetEncoding(udfxml),pv.AsText); Result := ib_util_malloc(Length(s)+1); StrPLCopy(Result,s,MaxVarCharLength - 1); finally pv.Free; end; except result := nil; end; end; function XmlXPathEvalHelper(Handle: PtrUdf; AExpressionString: PChar; var AContextNode: PtrUdf): TXPathVariable; var sExpressionString: DOMString; obj : TObject; afobj: TAFObj; xpathVar: TXPathVariable; begin try afobj := HandleToAfObj(Handle); if AContextNode=0 then Exception.Create('XmlXPathEval: ContextNode must be set'); obj := HandleToObj(AContextNode); if obj is TAFObj then obj := TUDFXMLDocument(afobj.Obj).Document else if (not (obj is TDOMNode)) and (not (obj is TXMLDocument)) then raise Exception.Create('XmlXPathEval: ContextNode must be XmlDocument or XmlNode'); sExpressionString := inConvStrToDOM(inGetEncoding(afobj.Obj),AExpressionString); xpathVar := EvaluateXPathExpression(sExpressionString, TDOMNode(obj)); result := xpathVar; except on e: Exception do begin if Assigned(afobj) then afobj.FixedError(e); Result := nil; end; end; end; function XmlXPathEvalValueNum(var Handle: PtrUdf; AExpressionString: PChar; var AContextNode: PtrUdf): Double; cdecl; var pv: TXPathVariable; begin try try pv := XmlXPathEvalHelper(handle,AExpressionString,AContextNode); if pv=nil then exit(0); result := pv.AsNumber; finally pv.free; end; except result := 0; end; end; function XmlXPathNodeSetItem(var Handle:PtrUdf; var HandleNodeSet: PtrUdf; var Index: integer ): PtrUdf; cdecl; var afobj: TAFObj; ns: TNodeSet; obj: TObject; begin try result := 0; afobj := HandleToAfObj(Handle); if HandleNodeSet=0 then Exception.Create('XmlXPathNodeSetItem: ContextNode must be set'); obj := HandleToObj(HandleNodeSet); if (not(obj is TXPathVariable)) then raise Exception.CreateFmt('HandleNodeSet: Bad type %s',[obj.ClassName]); if TXPathVariable(obj).TypeName <> SNodeSet then exit(0); ns := TXPathNodeSetVariable(obj).Value; if (Index<0) or (Index>=ns.Count) then raise Exception.CreateFmt('XmlXPathNodeSetItem: Index %d of bounds',[Index]); try Result:={%H-}PtrUdf(TXPathNodeSetVariable(obj).Value.Items[Index]); finally // --> not: ns.free; end; except on e: Exception do begin if Assigned(afobj) then afobj.FixedError(e); Result := 0; end; end; end; function XmlXPathNodeSetCount(var Handle: PtrUdf; var HandleNodeSet: PtrUdf ): Integer; cdecl; var afobj: TAFObj; obj: TObject; begin try afobj := HandleToAfObj(Handle); if HandleNodeSet=0 then Exception.Create('XmlXPathEval: ContextNode must be set'); obj := HandleToObj(HandleNodeSet); if not (obj is TXPathVariable) then raise Exception.CreateFmt('HandleNodeSet: Bad type %s',[obj.ClassName]); if TXPathVariable(obj).TypeName <> SNodeSet then exit(0); try Result:=TXPathNodeSetVariable(obj).Value.Count; finally // not -> ns.Free; end; except on e: Exception do begin if Assigned(afobj) then afobj.FixedError(e); Result := 0; end; end; end; procedure XMLTextNodeBlob(var Handle: PtrUdf; var Node: PtrUdf; var Blob: TFBBlob); cdecl; var afobj: TAFObj; XmlNode: TDOMNode; s: ansistring; begin try afobj := HandleToAfObj(Handle); XmlNode := HandleToObj(Node) as TDOMNode; if XmlNode <> nil then begin s := inConvDOMToStr(inGetEncoding(afobj.Obj), _getXmlNodeText(XmlNode)); end else raise Exception.Create('Node not found'); with TFBBlobStream.Create(@Blob) do try Write(Pchar(s)^,Length(s)); finally free; end; except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function isNeedConvert(AObject: TObject): boolean; inline; begin result := (not SameText(TUDFXMLDocument(AObject).Encoding,'utf-8')) or (Length(TUDFXMLDocument(AObject).Encoding)=0); end; function _getXmlNodeText(XmlNode: TDOMNode): DOMString; var s: DOMString; i: integer; cld: TDOMNodeList; begin if not (XmlNode is TDOMElement) then Result := inGetXML(XmlNode) else begin s := ''; cld := XmlNode.ChildNodes; try for i := 0 to cld.Count - 1 do begin s := s + inGetXML(cld[i]); end; finally // cld.Release; // ChildNodes end; Result := s; end; end; function encEncoding(const AXml: AnsiString): AnsiString; var i: LongInt; P : ^char; Pst : ^char; k: LongInt; begin i:=Pos('?>',AXml); if i=0 then exit; k := Pos('encoding="',AXml); if (k=0) or (k>i) then exit; p:= @AXml[k+ length('encoding="')]; Pst := p; while not (p^ in [#0,#13,#10,'"']) do begin inc(p); end; result := copy(Pchar(Pst),1,p-pst); end; procedure encAddEncoding(var AXml: String; const Encoding: AnsiString); var i: LongInt; begin AXml := StringReplace(AXml,'encoding="utf-8"','',[]); i:=Pos('?>',AXml); if i<>0 then insert(' encoding="'+Encoding+'" ',AXml,i); end; procedure encDelEncoding(var AXml: DOMString); var i: LongInt; P : ^WChar; Pst : ^WChar; k: LongInt; begin i:=Pos('?>',AXml); if i=0 then exit; k := Pos('encoding="',AXml); if (k=0) or (k>i) or (k+1>length(AXml)) then exit; p:= @AXml[k+ length('encoding="')*2+1]; Pst := @AXml[k]; while not (p^ in [#0,'"']) do begin inc(p); end; Delete(AXml,k,p-pst + 1); end; procedure XMLXmlNodeBlob(var Handle: PtrUdf; var Node: PtrUdf; var Blob: TFBBlob); cdecl; var afobj: TAFObj; sXML: ansistring; XmlNode: TDOMNode; begin try afobj := HandleToAfObj(Handle); XmlNode := HandleToObj(Node) as TDOMNode; if XmlNode = nil then raise Exception.Create('Node not found.'); sXML := inConvDOMToStr(inGetEncoding(afobj.Obj), inGetXML(XmlNode)); PCharToBlob(PChar(sXML), Blob); except on e: Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function CreateXmlDocFromStringDTD(S: PChar): PChar; cdecl; var Stream: TStream; begin try Stream := TStringStream.Create(s); try Result := CreateXmlFromStream(Stream); finally Stream.Free; end; except on e:Exception do begin Result := ib_util_malloc(Length('ERROR:'+e.Message)+1); StrPLCopy(Result,'ERROR:'+e.Message,MaxVarCharLength-1); end; end; end; function CreateXmlDocFromBLOBDTD(var BLOB: TFBBlob): PChar; cdecl; var Stream: TFBBlobStream; begin try Stream := TFBBlobStream.Create(@BLOB); try Result := CreateXmlFromStream(Stream); finally Stream.Free; end; except on e:Exception do begin Result := ib_util_malloc(Length('ERROR:'+e.Message)+1); StrPLCopy(Result,'ERROR:'+e.Message,MaxVarCharLength-1); end; end; end; function CreateXmlFromStream(AStream:TStream):Pchar; var dtd : TXmlDTD; DocOut : TXMLDocument; XmlDoc : TUDFXMLDocument; sError : string; s : string; begin dtd := TXmlDTD.Create; try try if dtd.CreateXmlDocFromStreamDTD(AStream,DocOut,sError) then begin XmlDoc := TUDFXMLDocument.Create(false); XmlDoc.Document := DocOut; s := IntToStr(TAFObj.Create(XmlDoc).Handle); Result := ib_util_malloc(Length(s)+1); StrPLCopy(Result, s,MaxVarCharLength - 1); end else begin Result:= ib_util_malloc(Length(sError)+1); StrPLCopy(Result, sError,MaxVarCharLength - 1); end; finally dtd.Free; end; except on e:Exception do begin s := 'ERROR:'+ e.Message; Result := ib_util_malloc(Length(s)+1); StrPLCopy(Result, s,MaxVarCharLength - 1); end; end; end; function CreateXmlDocFromFileDTD(FileName: PChar): PChar; cdecl; var Stream: TFileStream; begin try Stream := TFileStream.Create(FileName,fmOpenRead); try Result := CreateXmlFromStream(Stream); finally Stream.Free; end; except on e:Exception do begin Result := ib_util_malloc(Length('ERROR:'+e.Message)+1); StrPLCopy(Result,'ERROR:'+e.Message,MaxVarCharLength-1); end; end; end; function inGetXML(doc: TUDFXMLDocument): DOMString; var MemSt: TMemoryStream; s:ansistring; begin Result := ''; MemSt := TMemoryStream.Create; try WriteXML(doc.Document, MemSt); SetLength(s,MemSt.Size); MemSt.Position:=0; MemSt.Read (Pointer(s)^,MemSt.Size); result:=UTF8Decode(s); finally MemSt.Free; end; end; function inGetXML2(doc: TUDFXMLDocument): string; var MemSt: TMemoryStream; s:string; begin Result := ''; MemSt := TMemoryStream.Create; try WriteXML(doc.Document, MemSt); SetLength(s,MemSt.Size); MemSt.Position:=0; MemSt.Read(Pointer(s)^,MemSt.Size); result:=s; finally MemSt.Free; end; end; function inGetXML(Element: TDOMNode): DOMString; var MemSt: TMemoryStream; begin Result := ''; MemSt := TMemoryStream.Create; try WriteXML(Element, MemSt); Result := UTF8Decode(Copy(PChar(MemSt.Memory), 1, MemSt.Size)); finally MemSt.Free; end; end; function inConvStrToDOM(const Encoding, AStr: ansistring): DOMString; var res: ansistring; begin res := ''; Iconvert(AStr, res, Encoding, DOMDefaultEncode); Result := UTF8Decode(res); end; function inConvDOMToStr(const Encoding, AStr: DOMString): ansistring; var res: ansistring; begin res := ''; Iconvert(UTF8Encode(AStr), res, DOMDefaultEncode, Encoding); Result := res; end; function inGetEncoding(AObject: TObject): string; inline; begin Result := TUDFXMLDocument(AObject).InputOutputEncoding; if Result = '' then Result := DOMDefaultEncode; end; { TUDFXMLDocument } constructor TUDFXMLDocument.Create(AutoCreate:boolean); begin FInputOutputEncoding:= 'utf-8'; FEncoding:='utf-8'; if AutoCreate then FDocument := TXMLDocument.Create; end; destructor TUDFXMLDocument.Destroy; begin if Assigned(FDocument) then FDocument.Free; inherited Destroy; end; initialization end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.10 2/10/2005 2:24:42 PM JPMugaas Minor Restructures for some new UnixTime Service components. Rev 1.9 2004.02.03 5:44:34 PM czhower Name changes Rev 1.8 1/21/2004 4:20:56 PM JPMugaas InitComponent Rev 1.7 1/3/2004 1:00:00 PM JPMugaas These should now compile with Kudzu's change in IdCoreGlobal. Rev 1.6 4/11/2003 02:45:44 PM JPMugaas Rev 1.5 4/5/2003 7:23:56 PM BGooijen Raises exception on timeout now Rev 1.4 4/4/2003 8:02:34 PM BGooijen made host published Rev 1.3 2/24/2003 10:37:00 PM JPMugaas Should compile. TODO: Figure out what to do with TIdTime and the timeout feature. Rev 1.2 12/7/2002 06:43:38 PM JPMugaas These should now compile except for Socks server. IPVersion has to be a property someplace for that. Rev 1.1 12/6/2002 05:30:48 PM JPMugaas Now descend from TIdTCPClientCustom instead of TIdTCPClient. Rev 1.0 11/13/2002 08:03:14 AM JPMugaas } unit IdTime; {*******************************************************} { } { Indy Time Client TIdTime } { } { Copyright (C) 2000 Winshoes Working Group } { Original author J. Peter Mugaas } { 2000-April-24 } { Based on RFC RFC 868 } { } {*******************************************************} { 2001-Sep -21 J. Peter Mugaas - adjusted formula as suggested by Vaclav Korecek. The old one would give wrong date, time if RoundTripDelay was over a value of 1000 2000-May -04 J. Peter Mugaas -Changed RoundTripDelay to a cardinal and I now use the GetTickCount function for more accuracy -The formula had to adjusted for this. 2000-May -03 J. Peter Mugaas -Added BaseDate to the date the calculations are based on can be adjusted to work after the year 2035 2000-Apr.-29 J. Peter Mugaas -Made the time more accurate by taking into account time-zone bias by subtracting IdGlobal.TimeZoneBias. -I also added a correction for the time it took to receive the Integer from the server ( ReadInteger ) -Changed Time property to DateTime and TimeCard to DateTimeCard to be more consistant with TIdSNTP. } interface {$i IdCompilerDefines.inc} uses {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} Classes, {$ENDIF} IdAssignedNumbers, IdGlobalProtocols, IdTCPClient; const TIME_TIMEOUT = 2500; type TIdCustomTime = class(TIdTCPClientCustom) protected FBaseDate: TDateTime; FRoundTripDelay: Cardinal; FTimeout: Integer; // function GetDateTimeCard: Cardinal; function GetDateTime: TDateTime; procedure InitComponent; override; public {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} constructor Create(AOwner: TComponent); reintroduce; overload; {$ENDIF} {This synchronizes the local clock with the Time Server} function SyncTime: Boolean; {This is the number of seconds since 12:00 AM, 1900 - Jan-1} property DateTimeCard: LongWord read GetDateTimeCard; {This is the current time according to the server. TimeZone and Time used to receive the data are accounted for} property DateTime: TDateTime read GetDateTime; {This is the time it took to receive the Time from the server. There is no need to use this to calculate the current time when using DateTime property as we have done that here} property RoundTripDelay: Cardinal read FRoundTripDelay; published property Timeout: Integer read FTimeout write FTimeout default TIME_TIMEOUT; property Host; end; TIdTime = class(TIdCustomTime) published {This property is used to set the Date that the Time server bases its calculations from. If both the server and client are based from the same date which is higher than the original date, you can extend it beyond the year 2035} property BaseDate: TDateTime read FBaseDate write FBaseDate; property Timeout: Integer read FTimeout write FTimeout default TIME_TIMEOUT; property Port default IdPORT_TIME; end; implementation uses {$IFDEF USE_VCL_POSIX} {$IFDEF DARWIN} Macapi.CoreServices, {$ENDIF} Posix.SysTime, {$ENDIF} IdGlobal, IdTCPConnection; { TIdCustomTime } {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} constructor TIdCustomTime.Create(AOwner: TComponent); begin inherited Create(AOwner); end; {$ENDIF} procedure TIdCustomTime.InitComponent; begin inherited; Port := IdPORT_TIME; {This indicates that the default date is Jan 1, 1900 which was specified by RFC 868.} FBaseDate := TIME_BASEDATE; FTimeout := TIME_TIMEOUT; end; function TIdCustomTime.GetDateTime: TDateTime; var BufCard: LongWord; begin BufCard := GetDateTimeCard; if BufCard <> 0 then begin {The formula is The Time cardinal we receive divided by (24 * 60*60 for days + RoundTrip divided by one-thousand since this is based on seconds - the Time Zone difference} Result := ( ((BufCard + (FRoundTripDelay div 1000))/ (24 * 60 * 60) ) + Int(fBaseDate)) -TimeZoneBias; end else begin { Somehow, I really doubt we are ever going to really get a time such as 12/30/1899 12:00 am so use that as a failure test} Result := 0; end; end; function TIdCustomTime.GetDateTimeCard: LongWord; var LTimeBeforeRetrieve: Cardinal; begin Connect; try // Check for timeout // Timeout is actually a time with no traffic, not a total timeout. IOHandler.ReadTimeout:=Timeout; LTimeBeforeRetrieve := Ticks; Result := IOHandler.ReadLongWord; {Theoritically, it should take about 1/2 of the time to receive the data but in practice, it could be any portion depending upon network conditions. This is also as per RFC standard} {This is just in case the TickCount rolled back to zero} FRoundTripDelay := GetTickDiff(LTimeBeforeRetrieve,Ticks) div 2; finally Disconnect; end; end; function TIdCustomTime.SyncTime: Boolean; var LBufTime: TDateTime; begin LBufTime := DateTime; Result := LBufTime <> 0; if Result then begin Result := IndySetLocalTime(LBufTime); end; end; end.
(** This module contains a frame for the web browser so that this code can be used in more than one applciation without having to conditionally compile a form for inclusion in the IDE or an external application. @Version 1.0 @Author David Hoyle @Date 10 Sep 2017 **) Unit WebBrowserFrame; Interface Uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ActnList, ComCtrls, OleCtrls, SHDocVw, Buttons, ExtCtrls, StdCtrls; {$INCLUDE CompilerDefinitions.inc} Type (** This is a class to represent a frame for the web browser including an address bar and toolbar buttons. **) TfmWebBrowser = Class(TFrame) wbBrowser: TWebBrowser; sbrStatus: TStatusBar; alActions: TActionList; actBack: TAction; actForward: TAction; actConfigure: TAction; ilImages: TImageList; pnlToolbar: TPanel; btnBack: TSpeedButton; btnForward: TSpeedButton; cbxURL: TComboBox; btnStop: TSpeedButton; btnRefresh: TSpeedButton; btnConfig: TSpeedButton; actStop: TAction; actRefresh: TAction; actOpen: TAction; btnOpen: TSpeedButton; Procedure actBackExecute(Sender: TObject); Procedure actForwardExecute(Sender: TObject); Procedure wbBrowserCommandStateChange(ASender: TObject; Command: Integer; Enable: WordBool); Procedure wbBrowserDownloadBegin(Sender: TObject); procedure wbBrowserDownloadComplete(Sender: TObject); procedure wbBrowserProgressChange(ASender: TObject; Progress, ProgressMax: Integer); procedure wbBrowserBeforeNavigate2(ASender: TObject; const pDisp: IDispatch; const URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); procedure wbBrowserStatusTextChange(ASender: TObject; const Text: WideString); procedure cbxURLKeyPress(Sender: TObject; var Key: Char); procedure actStopExecute(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure wbBrowserDocumentComplete(ASender: TObject; const pDisp: IDispatch; const URL: OleVariant); procedure sbrStatusDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); procedure actConfigureExecute(Sender: TObject); procedure cbxURLSelect(Sender: TObject); procedure actOpenExecute(Sender: TObject); procedure wbBrowserTitleChange(ASender: TObject; const Text: WideString); Private {Private declarations} FPercent : Double; Public {Public declarations} Constructor Create(AOwner : TComponent); Override; Procedure Navigate(strURL: String); Function CurrentURL : String; End; Implementation {$R *.dfm} Uses UtilityFunctions, DGHIDEHelphelperConfigForm, ApplicationsOptions, ShellAPI, ToolsAPI; {TfmWebBrowser} (** This is an on execute event handler for the Back action. @precon None. @postcon Asks the browser to go to the previous pahe in the history. @param Sender as a TObject **) Procedure TfmWebBrowser.actBackExecute(Sender: TObject); Begin wbBrowser.GoBack; End; (** This is an on execute event handler for the Configure action. @precon None. @postcon Displays the configuration dialogue and if confirmed updates the application options and ensures that any new Permanent URLs are in the address bar list. @param Sender as a TObject **) Procedure TfmWebBrowser.actConfigureExecute(Sender: TObject); {$IFNDEF DXE00} Var iIndex : Integer; i: Integer; {$ENDIF} Begin {$IFNDEF DXE00} iIndex := AppOptions.SearchURLIndex; If TfrmDGHIDEHelphelperConfig.Execute(AppOptions.SearchURLs, AppOptions.PermanentURLs, iIndex) Then Begin AppOptions.SearchURLIndex := iIndex; For i := 0 To AppOptions.PermanentURLs.Count - 1 Do If cbxURL.Items.IndexOf(AppOptions.PermanentURLs[i]) = -1 Then cbxURL.Items.Add(AppOptions.PermanentURLs[i]); End; {$ELSE} (BorlandIDEServices As IOTAServices).GetEnvironmentOptions.EditOptions('', 'IDE Help Helper.Options'); {$ENDIF} End; (** This is an on execute event handler for the Forward action. @precon None. @postcon Asks the browser to go to the next page in the history list. @param Sender as a TObject **) Procedure TfmWebBrowser.actForwardExecute(Sender: TObject); Begin wbBrowser.GoForward; End; (** This is an on execute event handler for the Open action. @precon None. @postcon Asks the OS to open the current URL in an external browser. @param Sender as a TObject **) Procedure TfmWebBrowser.actOpenExecute(Sender: TObject); Begin ShellExecute(Application.Handle, 'open', PChar(cbxURL.Text), '', '', SW_SHOWNORMAL); End; (** This is an on execute event handler for the Refresh action. @precon None. @postcon Asks the browser to refresh the current page. @param Sender as a TObject **) Procedure TfmWebBrowser.actRefreshExecute(Sender: TObject); Begin wbBrowser.Refresh; End; (** This is an on execute event handler for the Stop action. @precon None. @postcon Aks the browser to stop processing the currently loading page. @param Sender as a TObject **) Procedure TfmWebBrowser.actStopExecute(Sender: TObject); Begin wbBrowser.Stop; End; (** This is an on key press event handler for the URL combo box. @precon None. @postcon If the enter key is pressed it forces the browser to display for the current URL. If this is not a qualitied URL a default search will be done. @param Sender as a TObject @param Key as a Char as a reference **) Procedure TfmWebBrowser.cbxURLKeyPress(Sender: TObject; Var Key: Char); Begin If Key = #13 Then Begin wbBrowser.Navigate(cbxURL.Text); Key := #0; End; End; (** This is an on select item event handler for the URL combo box. @precon None. @postcon Asks the browser to display the selected URL. @param Sender as a TObject **) Procedure TfmWebBrowser.cbxURLSelect(Sender: TObject); Begin wbBrowser.Navigate(cbxURL.Text); End; (** A constructor for the TfmWebBrowser class. @precon None. @postcon Adds the permanent URLs to the URL list. @param AOwner as a TComponent **) Constructor TfmWebBrowser.Create(AOwner: TComponent); Begin Inherited Create(AOwner); cbxURL.Items.Assign(AppOptions.PermanentURLs); End; (** This method returns the current URL of the browser. @precon None. @postcon The current URL of the browser is returned. @return a String **) Function TfmWebBrowser.CurrentURL: String; Begin Result := wbBrowser.LocationURL; End; (** This method is the only public method for the class and is used by external code to invoke the browser to dislpay a URL. @precon None. @postcon The given URL is displayed. @param strURL as a String **) Procedure TfmWebBrowser.Navigate(strURL: String); Begin wbBrowser.Navigate(strURL); End; (** This is an owner draw method for the status bar panel and is used to draw a progress bar in the second panel for the loading of the page in the browser. @precon None. @postcon The progress of the browser loading is dislpayed as a progress ar with a percentage. @param StatusBar as a TStatusBar @param Panel as a TStatusPanel @param Rect as a TRect as a constant **) Procedure TfmWebBrowser.sbrStatusDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; Const Rect: TRect); Var R : TRect; strText : String; iX: Integer; iY: Integer; Begin If Panel.Index = 1 Then Begin R := Rect; strText := Panel.Text; StatusBar.Canvas.Brush.Color := clBtnFace; StatusBar.Canvas.FillRect(R); iX := R.Left + ((R.Right - R.Left) - StatusBar.Canvas.TextWidth(strText)) Div 2; iY := R.Top + ((R.Bottom - R.Top) - StatusBar.Canvas.TextHeight(strText)) Div 2; StatusBar.Canvas.TextRect(R, iX, iY, strText); R.Right := R.Left + Trunc(FPercent / 100.0 * Int(R.Right - R.Left)); StatusBar.Canvas.Brush.Color := clLime; StatusBar.Canvas.FillRect(R); StatusBar.Canvas.TextRect(R, iX, iY, strText); End; End; (** This is an on BeforeNavigate event handler for the browser. @precon None. @postcon The browser toolbar buttons are updated and the URL is added to the list of URLs. @param ASender as a TObject @param pDisp as an IDispatch as a constant @param URL as an OleVariant as a constant @param Flags as an OleVariant as a constant @param TargetFrameName as an OleVariant as a constant @param PostData as an OleVariant as a constant @param Headers as an OleVariant as a constant @param Cancel as a WordBool as a reference **) Procedure TfmWebBrowser.wbBrowserBeforeNavigate2(ASender: TObject; Const pDisp: IDispatch; Const URL, Flags, TargetFrameName, PostData, Headers: OleVariant; Var Cancel: WordBool); Begin cbxURL.Text := VarToStr(URL); If cbxURL.Items.IndexOf(cbxURL.Text) = -1 Then cbxURL.Items.Add(cbxURL.Text); actStop.Enabled := True; actRefresh.Enabled := False; actOpen.Enabled := True; End; (** This is an on change event handler for the Browser control. @precon None. @postcon This is upudates the state of the Back and Forward toolbar buttons. @param ASender as a TObject @param Command as an Integer @param Enable as a WordBool **) Procedure TfmWebBrowser.wbBrowserCommandStateChange(ASender: TObject; Command: Integer; Enable: WordBool); Begin Case Command Of CSC_NAVIGATEBACK: actBack.Enabled := Enable; CSC_NAVIGATEFORWARD: actForward.Enabled := Enable; Else //actStop.Enabled := wbBrowser.Busy; //actRefresh.Enabled := Not wbBrowser.Busy; End; End; (** This is an on Document complete event handler for the browser. @precon None. @postcon The stop and refresh buttons states are changed if the document is fully loaded. @param ASender as a TObject @param pDisp as an IDispatch as a constant @param URL as an OleVariant as a constant **) Procedure TfmWebBrowser.wbBrowserDocumentComplete(ASender: TObject; Const pDisp: IDispatch; Const URL: OleVariant); Begin If wbBrowser.ReadyState = READYSTATE_COMPLETE Then Begin actStop.Enabled := False; actRefresh.Enabled := True; End; End; (** This is an on DownloadBegin event handler for the browser. @precon None. @postcon Updates the status panel to say loading. @param Sender as a TObject **) Procedure TfmWebBrowser.wbBrowserDownloadBegin(Sender: TObject); Begin sbrStatus.Panels[0].Text := 'Loading...'; End; (** This is an on DownloadComplete event handler for the browser. @precon None. @postcon Updates the status panel to say loaded. @param Sender as a TObject **) Procedure TfmWebBrowser.wbBrowserDownloadComplete(Sender: TObject); Begin sbrStatus.Panels[0].Text := 'Loaded.'; End; (** This is an on change event handler for the Browser control. @precon None. @postcon Updates the percentage complete for the progress panel. @param ASender as a TObject @param Progress as an Integer @param ProgressMax as an Integer **) Procedure TfmWebBrowser.wbBrowserProgressChange(ASender: TObject; Progress, ProgressMax: Integer); Begin If ProgressMax > 0 Then FPercent := Int(Progress) / Int(ProgressMax) * 100.0 Else FPercent := 100; sbrStatus.Panels[1].Text := Format('%1.1n%%', [FPercent]); Application.ProcessMessages; End; (** This is an on change event handler for the status of the browser control. @precon None. @postcon Updates the third panel on the status bar with the browser information. @param ASender as a TObject @param Text as a WideString as a constant **) Procedure TfmWebBrowser.wbBrowserStatusTextChange(ASender: TObject; Const Text: WideString); Begin sbrStatus.Panels[2].Text := Text; End; (** This is an on change event handler for the browser title control. @precon None. @postcon Updates the host forms caption with the name of the page. @param ASender as a TObject @param Text as a WideString as a constant **) Procedure TfmWebBrowser.wbBrowserTitleChange(ASender: TObject; Const Text: WideString); Begin If Parent Is TForm Then (Parent As TForm).Caption := 'IDE Help Helper Browser: ' + Text; End; End.
unit TestWSRequest; {$ifndef VER3}{$fatal WS tests requires FPC 3}{$endif} {$mode objfpc}{$H+} interface uses Classes, HTTPDefs, fpcunit, JCoreWSIntf, JCoreWSRequest; type { TTestWSRequest } TTestWSRequest = class(TTestCase) private FRequest: TRequest; FResponse: TResponse; FRouter: IJCoreWSRequestRouter; function GetRequest: TRequest; function GetResponse: TResponse; function GetRouter: IJCoreWSRequestRouter; protected function CreateRouter: IJCoreWSRequestRouter; virtual; abstract; procedure TearDown; override; property Request: TRequest read GetRequest; property Response: TResponse read GetResponse; property Router: IJCoreWSRequestRouter read GetRouter; end; { TTestWSRequestSimpleRouter } TTestWSRequestSimpleRouter = class(TTestWSRequest) protected function CreateRouter: IJCoreWSRequestRouter; override; published procedure Simple; procedure NoSlash; procedure PatternPrefix; procedure PatternMiddle; procedure PatternSuffix; procedure PatternNoSlash1; procedure PatternNoSlash2; procedure FirstHandlerMatch1; procedure FirstHandlerMatch2; procedure NoHandler404; procedure Simple404; procedure NoPattern404; procedure PatternPrefix404; procedure PatternMiddle404; procedure PatternSuffix404; end; { TTestWSRequestRESTRouter } TTestWSRequestRESTRouter = class(TTestWSRequest) protected function CreateRouter: IJCoreWSRequestRouter; override; published procedure Simple; procedure NoSlash; procedure OneField; procedure TwoFields; procedure TwoFieldsNoSlash; procedure ThreeFields; procedure FirstHandlerMatch1; procedure FirstHandlerMatch2; procedure NoHandler404; procedure Simple404; procedure ShortUrl404; end; { TTestRequest } TTestRequest = class(TRequest) end; { TTestResponse } TTestResponse = class(TResponse) protected procedure DoSendContent; override; procedure DoSendHeaders(Headers: TStrings); override; end; { TTestSimple1RequestHandler } TTestSimple1RequestHandler = class(TInterfacedObject, IJCoreWSRequestHandler) public procedure HandleRequest(const ARequest: TRequest; const AResponse: TResponse); end; { TTestSimple2RequestHandler } TTestSimple2RequestHandler = class(TInterfacedObject, IJCoreWSRequestHandler) public procedure HandleRequest(const ARequest: TRequest; const AResponse: TResponse); end; implementation uses sysutils, testregistry; function TTestWSRequest.GetRequest: TRequest; begin if not Assigned(FRequest) then FRequest := TTestRequest.Create; Result := FRequest; end; function TTestWSRequest.GetResponse: TResponse; begin if not Assigned(FResponse) then begin FResponse := TTestResponse.Create(Request); FResponse.Contents.LineBreak := '\n'; end; Result := FResponse; end; function TTestWSRequest.GetRouter: IJCoreWSRequestRouter; begin if not Assigned(FRouter) then FRouter := CreateRouter; Result := FRouter; end; procedure TTestWSRequest.TearDown; begin inherited TearDown; FreeAndNil(FRequest); FreeAndNil(FResponse); FRouter := nil; end; { TTestWSRequestSimpleRouter } function TTestWSRequestSimpleRouter.CreateRouter: IJCoreWSRequestRouter; begin Result := TJCoreWSSimpleMatchRequestRouter.Create; end; procedure TTestWSRequestSimpleRouter.Simple; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple'); Request.PathInfo := '/simple'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); end; procedure TTestWSRequestSimpleRouter.NoSlash; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple'); Request.PathInfo := 'simple'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); end; procedure TTestWSRequestSimpleRouter.PatternPrefix; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '*.page'); Request.PathInfo := '/simple/url/some.page'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); end; procedure TTestWSRequestSimpleRouter.PatternMiddle; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple/*.page'); Request.PathInfo := '/simple/url/some.page'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); end; procedure TTestWSRequestSimpleRouter.PatternSuffix; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple/*'); Request.PathInfo := '/simple/url'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); end; procedure TTestWSRequestSimpleRouter.PatternNoSlash1; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple*'); Request.PathInfo := '/simpleurl'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); end; procedure TTestWSRequestSimpleRouter.PatternNoSlash2; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple*'); Request.PathInfo := '/simple/url'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); end; procedure TTestWSRequestSimpleRouter.FirstHandlerMatch1; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple/url'); Router.AddRequestHandler(TTestSimple2RequestHandler.Create, '/simple/*'); Request.PathInfo := '/simple/url'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); end; procedure TTestWSRequestSimpleRouter.FirstHandlerMatch2; begin Router.AddRequestHandler(TTestSimple2RequestHandler.Create, '/simple/*'); Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple/url'); Request.PathInfo := '/simple/url'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'two\n', Response.Content); end; procedure TTestWSRequestSimpleRouter.NoHandler404; begin Request.PathInfo := '/any'; Router.RouteRequest(Request, Response); AssertEquals('status code', 404, Response.Code); end; procedure TTestWSRequestSimpleRouter.Simple404; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple'); Request.PathInfo := '/wrong/url'; Router.RouteRequest(Request, Response); AssertEquals('status code', 404, Response.Code); end; procedure TTestWSRequestSimpleRouter.NoPattern404; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple'); Request.PathInfo := '/simple/url'; Router.RouteRequest(Request, Response); AssertEquals('status code', 404, Response.Code); end; procedure TTestWSRequestSimpleRouter.PatternPrefix404; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '*.page'); Request.PathInfo := '/simple/url/some.pages'; Router.RouteRequest(Request, Response); AssertEquals('status code', 404, Response.Code); end; procedure TTestWSRequestSimpleRouter.PatternMiddle404; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple/*.page'); Request.PathInfo := '/simple/url/somepage'; Router.RouteRequest(Request, Response); AssertEquals('status code', 404, Response.Code); end; procedure TTestWSRequestSimpleRouter.PatternSuffix404; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/simple/*'); Request.PathInfo := '/simple'; Router.RouteRequest(Request, Response); AssertEquals('status code', 404, Response.Code); end; { TTestWSRequestRESTRouter } function TTestWSRequestRESTRouter.CreateRouter: IJCoreWSRequestRouter; begin Result := TJCoreWSRESTRequestRouter.Create; end; procedure TTestWSRequestRESTRouter.Simple; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/attr'); Request.PathInfo := '/attr'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); end; procedure TTestWSRequestRESTRouter.NoSlash; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/attr'); Request.PathInfo := 'attr'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); end; procedure TTestWSRequestRESTRouter.OneField; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/attr/:master'); Request.PathInfo := '/attr/first'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); AssertEquals('field 1', 'first', Request.QueryFields.Values['master']); end; procedure TTestWSRequestRESTRouter.TwoFields; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/attr/:master/:next'); Request.PathInfo := '/attr/first/second'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); AssertEquals('field 1', 'first', Request.QueryFields.Values['master']); AssertEquals('field 2', 'second', Request.QueryFields.Values['next']); end; procedure TTestWSRequestRESTRouter.TwoFieldsNoSlash; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/attr/:master/:next'); Request.PathInfo := 'attr/first/second'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); AssertEquals('field 1', 'first', Request.QueryFields.Values['master']); AssertEquals('field 2', 'second', Request.QueryFields.Values['next']); end; procedure TTestWSRequestRESTRouter.ThreeFields; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/attr/:master/:next'); Request.PathInfo := '/attr/first/second/third'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); AssertEquals('field 1', 'first', Request.QueryFields.Values['master']); AssertEquals('field 2', 'second', Request.QueryFields.Values['next']); AssertEquals('returned path info', '/attr/first/second', Request.ReturnedPathInfo); end; procedure TTestWSRequestRESTRouter.FirstHandlerMatch1; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/attr/url'); Router.AddRequestHandler(TTestSimple2RequestHandler.Create, '/attr'); Request.PathInfo := '/attr/url'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'one\n', Response.Content); end; procedure TTestWSRequestRESTRouter.FirstHandlerMatch2; begin Router.AddRequestHandler(TTestSimple2RequestHandler.Create, '/attr'); Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/attr/url'); Request.PathInfo := '/attr/url'; Router.RouteRequest(Request, Response); AssertEquals('status code', 200, Response.Code); AssertEquals('content', 'two\n', Response.Content); end; procedure TTestWSRequestRESTRouter.NoHandler404; begin Request.PathInfo := '/any'; Router.RouteRequest(Request, Response); AssertEquals('status code', 404, Response.Code); end; procedure TTestWSRequestRESTRouter.Simple404; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/attr/:first'); Request.PathInfo := '/other/one'; Router.RouteRequest(Request, Response); AssertEquals('status code', 404, Response.Code); end; procedure TTestWSRequestRESTRouter.ShortUrl404; begin Router.AddRequestHandler(TTestSimple1RequestHandler.Create, '/attr/:first'); Request.PathInfo := '/attr/'; Router.RouteRequest(Request, Response); AssertEquals('status code', 404, Response.Code); end; { TTestResponse } procedure TTestResponse.DoSendContent; begin end; procedure TTestResponse.DoSendHeaders(Headers: TStrings); begin end; { TTestSimple1RequestHandler } procedure TTestSimple1RequestHandler.HandleRequest(const ARequest: TRequest; const AResponse: TResponse); begin AResponse.Content := 'one'; end; { TTestSimple2RequestHandler } procedure TTestSimple2RequestHandler.HandleRequest(const ARequest: TRequest; const AResponse: TResponse); begin AResponse.Content := 'two'; end; initialization RegisterTest('jcore.ws.request', TTestWSRequestSimpleRouter); RegisterTest('jcore.ws.request', TTestWSRequestRESTRouter); end.
unit ImgRes; interface uses Windows, Classes, Collection; type TScreenRes = (res640x480, res800x600, res1024x768); type // Classes defined TImgDesc = class; TImgRes = class; // MetaClasses defined CImgDesc = class of TImgDesc; CImgRes = class of TImgRes; // TImgDesc describes one of the multiple images that can be used // to visually identify some object. Location is the URL (relative) // to the image resource. Size is the size in pixels of the image. // Resolution is the screen resolution the image was designed for. // And TrueColor specifies whether the image was designed for the // game|browser palette, or contains true color information. TImgDesc = class public constructor Create( aLocation : string; aSize : TPoint; aResolution : TScreenRes; aTrueColor : boolean ); private fLocation : string; fSize : TPoint; fResolution : TScreenRes; fTrueColor : boolean; public property Location : string read fLocation; property Resolution : TScreenRes read fResolution; property Size : TPoint read fSize; property TrueColor : boolean read fTrueColor; end; // TImgRes is a set of ImgDesc. A TImgRes should be considered as // a single image. Image Handlers will choose the proper TImgDesc // for this particular image (TImgRes) according to the visualization // context. TImgRes = class public constructor Create; destructor Destroy; override; private fDescriptors : TCollection; public property Descriptors : TCollection read fDescriptors; end; implementation // TImgDesc constructor TImgDesc.Create( aLocation : string; aSize : TPoint; aResolution : TScreenRes; aTrueColor : boolean ); begin inherited Create; fLocation := aLocation; fSize := aSize; fResolution := aResolution; fTrueColor := aTrueColor; end; // TImgRes constructor TImgRes.Create; begin inherited; fDescriptors := TCollection.Create( 5, 2, rkBelonguer ); end; destructor TImgRes.Destroy; begin fDescriptors.Free; inherited; end; end.
program Ch2; {$mode objfpc} uses SysUtils,Types; procedure QuickSort(var Arr:array of Integer;Left,Right:Integer); var I,J,Pivot,Temp:Integer; begin I := Left; J := Right; Pivot := Arr[(Left + Right) div 2]; repeat while Pivot < Arr[I] do Inc(I); while Pivot > Arr[J] do Dec(J); if I <= J then begin Temp := Arr[I]; Arr[I] := Arr[J]; Arr[J] := Temp; Inc(I); Dec(J); end; until I > J; if Left < J then QuickSort(Arr,Left,J); if I < Right then QuickSort(Arr,I,Right); end; function FrequencyEqualizer(constref Str:AnsiString):Boolean; var Freq:array[0..25] of Integer; Arr:TIntegerDynArray; I,J,Count:Integer; begin J := 0; Count := 0; FillDWord(Freq,Length(Freq),0); for I := Low(Str) to High(Str) do Inc(Freq[Ord(Str[I]) - Ord('a')]); for I := Low(Freq) to High(Freq) do if Freq[I] <> 0 then Inc(Count); SetLength(Arr,Count); Assert(Assigned(Arr)); for I := Low(Freq) to High(Freq) do if Freq[I] <> 0 then begin Arr[J] := Freq[I]; Inc(J); end; QuickSort(Arr,Low(Arr),High(Arr)); if((Arr[0] = Arr[1]+1) and (Arr[High(Arr)] = Arr[1])) then Result := True else Result := False; end; begin WriteLn(FrequencyEqualizer('abbc')); WriteLn(FrequencyEqualizer('xyzyyxz')); WriteLn(FrequencyEqualizer('xzxz')); end.
unit GX_OTAEditorNotifier; interface uses Classes, ToolsAPI; type IGxOtaEditorNotifier = interface(IOTAEditorNotifier) ['{D925E276-6494-4A5C-A989-2017DA55C80F}'] procedure Attach(_Editor: IOTASourceEditor); procedure Detach; end; ///<summary> /// Implements the IOTAEditorNotifier interface without actually declaring that it does so. /// All methods are empty, descendants can simply override those methods that they are /// interested in. </summary> TGxOTAEditorNotifier = class(TNotifierObject) protected FEditor: IOTASourceEditor; FNotifierIndex: Integer; protected procedure ViewActivated(const View: IOTAEditView); virtual; procedure ViewNotification(const View: IOTAEditView; Operation: TOperation); virtual; protected procedure Attach(_Editor: IOTASourceEditor); procedure Detach; end; implementation uses GX_OtaUtils; { TGxEditorNotifier } procedure TGxOTAEditorNotifier.Attach(_Editor: IOTASourceEditor); begin FEditor := _Editor; FNotifierIndex := FEditor.AddNotifier(Self as IOTAEditorNotifier); end; procedure TGxOTAEditorNotifier.Detach; begin if Assigned(FEditor) then begin if FNotifierIndex <> InvalidNotifierIndex then FEditor.RemoveNotifier(FNotifierIndex); FEditor := nil; end; end; procedure TGxOTAEditorNotifier.ViewActivated(const View: IOTAEditView); begin // do nothing end; procedure TGxOTAEditorNotifier.ViewNotification(const View: IOTAEditView; Operation: TOperation); begin // do nothing end; end.
{ Subroutine SST_R_PAS_EXP (EXP_STR_H,NVAL_ERR,EXP_P) * * Process EXPRESSION syntax. EXP_P will be returned pointing to the * compiled expression descriptor. EXP_STR_H is the SYN string handle for the * whole expression. If NVAL_ERR is TRUE, then it will be an error if the * expression can not be evaluated to a constant. * * This subroutine is set up to handle any of the EXPRESSIONn syntaxes, * regardless of which one the previous tag is for. } module sst_r_pas_EXP; define sst_r_pas_exp; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_exp ( {create compiled expression from input stream} in exp_str_h: syo_string_t; {SYN string handle for whole EXPRESSION syntax} in nval_err: boolean; {unknown value at compile time is err if TRUE} out exp_p: sst_exp_p_t); {returned pointer to new expression def} var tag: sys_int_machine_t; {syntax tag ID} str_h: syo_string_t; {handle to string associated with TAG} tag2: sys_int_machine_t; {to avoid corrupting TAG} str2_h: syo_string_t; {handle to string associated with TAG2} term_p: sst_exp_term_p_t; {points to current term in expression} levels_down: sys_int_machine_t; {number of syntax levels currently down} label exp_loop, term_loop, leave; begin sst_mem_alloc_namesp ( {allocate memory for expression descriptor} sizeof(exp_p^), exp_p); levels_down := 0; {init number of syntax levels down from call} exp_p^.str_h := exp_str_h; {save string handle for whole expression} exp_p^.val_eval := false; {init to not tried to evaluate expression} exp_loop: {back here if just contains one nested exp} syo_level_down; {down into this EXPRESSIONn syntax level} levels_down := levels_down + 1; {one more syntax level down from caller} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0); {item or nested exp} case tag of { ************************************* * * First term is nested expression. If this is the only term in the whole * expression, then we will compress out this level. } 1: begin syo_push_pos; {save position at nested expression} syo_get_tag_msg (tag2, str2_h, 'sst_pas_read', 'exp_bad', nil, 0); {operator tag, if any} syo_pop_pos; {restore current pos to nested expression} if tag2 = syo_tag_end_k {only one nested expression at this level ?} then goto exp_loop; {don't create structure for "pass thru" level} { * The expression here contains more than just one nested expression. * This means we will be filling in the data structures at this level. } exp_p^.term1.op2 := sst_op2_none_k; {first term has no diadic operator before it} sst_r_pas_exp_term (str_h, nval_err, exp_p^.term1); {fill in first term} end; {end of first term is expression case} { ************************************* * * First term is an ITEM syntax. } 2: begin exp_p^.term1.str_h := str_h; {save string handle to whole ITEM} sst_r_pas_item (exp_p^.term1); {read and process ITEM syntax} exp_p^.term1.next_p := nil; {init to first term is last in expression} exp_p^.term1.op2 := sst_op2_none_k; {first term has no diadic operator before it} end; {end of first term is ITEM case} { ************************************* * * Unexpected TAG value for first tag in EXPRESSION. } otherwise syo_error_tag_unexp (tag, str_h); end; {end of cases for first tag in EXPRESSION} term_p := addr(exp_p^.term1); {init address to last term in expression} { * The first term in the expression has been processed, and the expression * has been initialized as if this were the only term. We now loop back here * once for every new operator/term pair in the expression. TERM_P * is pointing to the descriptor for the previous term. } term_loop: syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0); {get operator tag} if tag = syo_tag_end_k {hit end of expression ?} then goto leave; sst_mem_alloc_namesp ( {allocate memory for new term descriptor} sizeof(term_p^.next_p^), term_p^.next_p); term_p := term_p^.next_p; {make new expression descriptor current} with term_p^: term do begin {TERM is descriptor for this new term} term.next_p := nil; {init to this is last term in expression} case tag of {which operator between this and prev term ?} 1: begin {+} term.op2 := sst_op2_add_k; end; 2: begin {-} term.op2 := sst_op2_sub_k; end; 3: begin {**} term.op2 := sst_op2_pwr_k; end; 4: begin {*} term.op2 := sst_op2_mult_k; end; 5: begin {/} term.op2 := sst_op2_div_k; end; 6: begin {div} term.op2 := sst_op2_divi_k; end; 7: begin {mod} term.op2 := sst_op2_rem_k; end; 8: begin {&} term.op2 := sst_op2_btand_k; end; 9: begin {!} term.op2 := sst_op2_btor_k; end; 10: begin {=} term.op2 := sst_op2_eq_k; end; 11: begin {<>} term.op2 := sst_op2_ne_k; end; 12: begin {>=} term.op2 := sst_op2_ge_k; end; 13: begin {>} term.op2 := sst_op2_gt_k; end; 14: begin {<=} term.op2 := sst_op2_le_k; end; 15: begin {<} term.op2 := sst_op2_lt_k; end; 16: begin {and} term.op2 := sst_op2_and_k; end; 17: begin {or} term.op2 := sst_op2_or_k; end; 18: begin {in} term.op2 := sst_op2_in_k; end; 19: begin {and then} term.op2 := sst_op2_andthen_k; end; 20: begin {or else} term.op2 := sst_op2_orelse_k; end; otherwise syo_error_tag_unexp (tag, str_h); end; {end of operator tag cases} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0); {get tag for new term} case tag of {what kind of term is this ?} { * This new term in the expression is a nested expression. } 1: begin sst_r_pas_exp_term (str_h, nval_err, term); {process nested expression as new term} end; {end of new term is expression} { * This new term in the expression is an item. } 2: begin term.str_h := str_h; {save string handle to whole ITEM} sst_r_pas_item (term); {read and process ITEM syntax} end; {end of new term is item} { * Unexpected TAG value for new term in expression. } otherwise syo_error_tag_unexp (tag, str_h); end; {end of new term type cases} { * Some of the Pascal operators server dual functions. Now look at the * data type of the resulting term and alter the diadic operator, if neccessary. } case term.val.dtype of sst_dtype_set_k: begin {term data type is SET} case term.op2 of sst_op2_add_k: term.op2 := sst_op2_union_k; sst_op2_sub_k: term.op2 := sst_op2_remov_k; sst_op2_mult_k: term.op2 := sst_op2_isect_k; sst_op2_ge_k: term.op2 := sst_op2_superset_eq_k; sst_op2_gt_k: term.op2 := sst_op2_superset_k; sst_op2_le_k: term.op2 := sst_op2_subset_eq_k; sst_op2_lt_k: term.op2 := sst_op2_subset_k; end; end; end; {end of term data type cases} goto term_loop; {back for next operator/term pair in this exp} end; {done with TERM abbreviation} { * Common exit point. We skipped over any expression levels if they only * contained another nested expression. LEVELS_DOWN indicates how many syntax * levels we are down from the caller's level. We must return to the caller's * syntax level. } leave: while levels_down > 0 do begin {once for each nested syntax level} syo_level_up; {pop back one syntax level} levels_down := levels_down - 1; {keep track of current nesting level} end; {back to pop another level up} sst_exp_eval (exp_p^, nval_err); {find data types and evaluate if possible} end;
unit FIWSender; interface uses FIWClasses, System.Generics.Collections, System.SysUtils, System.Net.HttpClient, System.Net.HTTPClientComponent, System.Classes; type TFIWSender = class class procedure SendToServer(Info: TObjectList<TWlanInfo>); end; const SERVER_IP='192.168.43.40'; SERVER_PORT='5678'; SERVER_ENDPOINT=''; implementation class procedure TFIWSender.SendToServer(Info: TObjectList<TWlanInfo>); var Network: TWlanInfo; Client: TNetHTTPClient; i: integer; URL: string; StringList: TStringList; FS:TFormatSettings; Response: IHTTPResponse; begin FS.DecimalSeparator:='.'; Client := TNetHTTPClient.Create(nil); StringList := TStringList.Create; for Network in Info do begin try Writeln('Sending network called ' + Network.Name); URL := 'http://' + SERVER_IP + ':' + SERVER_PORT + '/' + SERVER_ENDPOINT + '?' + 'name=' + Network.Name + '&' + 'lat=' + FloatTostr(Network.Location.Latitude,FS) + 'F&' + 'long=' + FloatToStr(Network.Location.Longitude,FS) + 'F'; Writeln(URL); Response:=Client.Post(URL,StringList); Writeln(Response.ContentAsString()); except continue; end; end; FreeAndNil(Client); FreeAndNil(StringList); end; end.
unit TWFloatEdit; interface uses Windows, Messages, SysUtils, Classes, Controls, StdCtrls; type TTWFloatEdit = class(TCustomEdit) procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditChange(Sender: TObject); constructor Create(Owner: TComponent); override; private { Private declarations } protected { Protected declarations } public { Public declarations } published { Published declarations } function getFloat: Real; end; //procedure Register; implementation uses Qt, QDialogs; (*procedure Register; begin RegisterComponents('TheWay', [TTWFloatEdit]); end; *) constructor TTWFloatEdit.Create(Owner: TComponent); begin inherited Create(Owner); OnKeyDown:=EditKeyDown; OnKeyUp :=EditKeyUp; OnChange :=EditChange; AutoSelect:=true; //Alignment := taRightJustify; end; procedure TTWFloatEdit.EditChange(Sender: TObject); begin SelStart:=0; end; procedure TTWFloatEdit.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin SelStart:=0; // Key:=0; end; procedure TTWFloatEdit.EditKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); (*var i: integer; ss,sl: integer;*) begin SelStart:=0; (* ss:=SelStart; sl:=SelLength; case key of Key_0..Key_9: begin end; Key_Comma: begin if length(text)=0 then if CanUndo then Undo; //Verifica se já há uma vírgula digitada. for i := 1 to length(text) do begin if text[i]=',' then if CanUndo then Undo; end; end; else begin if CanUndo then Undo; if ss>=length(text) then SelStart:=length(text)-1 else SelStart:=ss; SelLength:=sl; end; end; ClearUndo; *) end; function TTWFloatEdit.getFloat: Real; var i: integer; texto: string; begin texto:=text; for i := 1 to length(texto) do begin if texto[i]=',' then texto[i]:='.'; end; Result:=StrToFloat(texto); end; end.
Program Aufgabe6; {$codepage utf8} Var Bool1, Bool2: Boolean; Begin Bool1 := True; Bool2 := False; WriteLn('Bool1 = ', Bool1, ', Bool2 = ', Bool2); WriteLn('not Bool1 = ', not Bool1); WriteLn('Bool1 and Bool2 = ', Bool1 and Bool2); WriteLn('Bool1 or Bool2 = ', Bool1 or Bool2); WriteLn('Bool1 xor Bool2 = ', Bool1 xor Bool2); End.
unit Design_AttrValues; {* Локализуемые значения атрибутов значений тегов таблицы тегов Design } // Модуль: "w:\common\components\gui\Garant\Everest\Design_AttrValues.pas" // Стереотип: "UtilityPack" // Элемент модели: "Design_AttrValues" MUID: (3DBAA1891003) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , l3StringIDEx ; {$If Defined(DesignTimeLibrary)} const {* Локализуемые строки AttrValues } str_TextStyle_MainMenu_Font_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_MainMenu_Font_Name_Value'; rValue : 'Verdana'); {* Локализуемое значения атрибута TextStyle_MainMenu_Font_Name_Value } str_TextStyle_MainMenu_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_MainMenu_Name_Value'; rValue : 'Основное меню'); {* Локализуемое значения атрибута TextStyle_MainMenu_Name_Value } str_TextStyle_MainMenuConstPath_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_MainMenuConstPath_Name_Value'; rValue : 'Постоянная часть'); {* Локализуемое значения атрибута TextStyle_MainMenuConstPath_Name_Value } str_TextStyle_MainMenuChangePath_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_MainMenuChangePath_Name_Value'; rValue : 'Переменная часть'); {* Локализуемое значения атрибута TextStyle_MainMenuChangePath_Name_Value } str_TextStyle_MainMenuHeader_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_MainMenuHeader_Name_Value'; rValue : 'Заголовок'); {* Локализуемое значения атрибута TextStyle_MainMenuHeader_Name_Value } str_TextStyle_MainMenuInteractiveHeader_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_MainMenuInteractiveHeader_Name_Value'; rValue : 'Интерактивный'); {* Локализуемое значения атрибута TextStyle_MainMenuInteractiveHeader_Name_Value } {$IfEnd} // Defined(DesignTimeLibrary) implementation uses l3ImplUses //#UC START# *3DBAA1891003impl_uses* //#UC END# *3DBAA1891003impl_uses* ; initialization {$If Defined(DesignTimeLibrary)} str_TextStyle_MainMenu_Font_Name_Value.Init; {* Инициализация str_TextStyle_MainMenu_Font_Name_Value } {$IfEnd} // Defined(DesignTimeLibrary) {$If Defined(DesignTimeLibrary)} str_TextStyle_MainMenu_Name_Value.Init; {* Инициализация str_TextStyle_MainMenu_Name_Value } {$IfEnd} // Defined(DesignTimeLibrary) {$If Defined(DesignTimeLibrary)} str_TextStyle_MainMenuConstPath_Name_Value.Init; {* Инициализация str_TextStyle_MainMenuConstPath_Name_Value } {$IfEnd} // Defined(DesignTimeLibrary) {$If Defined(DesignTimeLibrary)} str_TextStyle_MainMenuChangePath_Name_Value.Init; {* Инициализация str_TextStyle_MainMenuChangePath_Name_Value } {$IfEnd} // Defined(DesignTimeLibrary) {$If Defined(DesignTimeLibrary)} str_TextStyle_MainMenuHeader_Name_Value.Init; {* Инициализация str_TextStyle_MainMenuHeader_Name_Value } {$IfEnd} // Defined(DesignTimeLibrary) {$If Defined(DesignTimeLibrary)} str_TextStyle_MainMenuInteractiveHeader_Name_Value.Init; {* Инициализация str_TextStyle_MainMenuInteractiveHeader_Name_Value } {$IfEnd} // Defined(DesignTimeLibrary) end.
unit kwIterateSubDecriptorsOnSubPanel; {* Перебирает все SubDescriptot на SubPanel, которые *могут быть* отрисованы (!). Т.е. проверка на Visible не производится. Если это нужно, то можно реализвать в скриптах. Формат: [code] @ aWord aLayerID aSubPanel IterateSubDecriptorsOnSubPanel [code] aLayerID - слой, в котором производится итерация aSubPanel - контрол сабпанели. aWord - функция для обработки вида: [code] PROCEDURE CheckDescription OBJECT IN aSubDescription INTEGER IN aHandle // А здесь обрабатываем полученный aSubDescription ; [code] Для извлечения нужной инфорации из aSubDescription есть набор функций: subdescriptor:GetDrawType и т.п. aHandle - номер саба, к которому рисуется метка. } // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwIterateSubDecriptorsOnSubPanel.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "IterateSubDecriptorsOnSubPanel" MUID: (52D78486017B) // Имя типа: "TkwIterateSubDecriptorsOnSubPanel" {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , kwSubPanelFromStackWord , tfwScriptingInterfaces , evSubPn , evSubPanelSub ; type TkwIterateSubDecriptorsOnSubPanel = {final} class(TkwSubPanelFromStackWord) {* Перебирает все SubDescriptot на SubPanel, которые *могут быть* отрисованы (!). Т.е. проверка на Visible не производится. Если это нужно, то можно реализвать в скриптах. Формат: [code] @ aWord aLayerID aSubPanel IterateSubDecriptorsOnSubPanel [code] aLayerID - слой, в котором производится итерация aSubPanel - контрол сабпанели. aWord - функция для обработки вида: [code] PROCEDURE CheckDescription OBJECT IN aSubDescription INTEGER IN aHandle // А здесь обрабатываем полученный aSubDescription ; [code] Для извлечения нужной инфорации из aSubDescription есть набор функций: subdescriptor:GetDrawType и т.п. aHandle - номер саба, к которому рисуется метка. } protected procedure PushObjData(const aCtx: TtfwContext; aSubDescription: TevSubDescriptor; aSubPanelSub: TevSubPanelSub); virtual; procedure DoWithSubPanel(aControl: TevCustomSubPanel; const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//TkwIterateSubDecriptorsOnSubPanel {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , evSubPanelSubCollection , evSubPanelSubArray , Windows {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) //#UC START# *52D78486017Bimpl_uses* //#UC END# *52D78486017Bimpl_uses* ; procedure TkwIterateSubDecriptorsOnSubPanel.PushObjData(const aCtx: TtfwContext; aSubDescription: TevSubDescriptor; aSubPanelSub: TevSubPanelSub); //#UC START# *53EDFA0401B8_52D78486017B_var* //#UC END# *53EDFA0401B8_52D78486017B_var* begin //#UC START# *53EDFA0401B8_52D78486017B_impl* aCtx.rEngine.PushObj(aSubDescription); aCtx.rEngine.PushInt(aSubPanelSub.Handle); //#UC END# *53EDFA0401B8_52D78486017B_impl* end;//TkwIterateSubDecriptorsOnSubPanel.PushObjData procedure TkwIterateSubDecriptorsOnSubPanel.DoWithSubPanel(aControl: TevCustomSubPanel; const aCtx: TtfwContext); //#UC START# *52D6471802DC_52D78486017B_var* var i : Integer; k : Integer; l_Obj : TObject; l_Lambda : TtfwWord; l_SubArray : TevSubPanelSubArray; l_Collection : TevSubPanelSubCollection; l_SubDescriptor : TevSubDescriptor; //#UC END# *52D6471802DC_52D78486017B_var* begin //#UC START# *52D6471802DC_52D78486017B_impl* RunnerAssert(aCtx.rEngine.IsTopObj, 'В итератор не передано слово.', aCtx); l_Obj := aCtx.rEngine.PopObj; RunnerAssert(l_Obj is TtfwWord, 'В итератор не передано слово.', aCtx); l_Lambda := l_Obj as TtfwWord; l_Collection := aControl.GetSubPanelSubCollection; for i := 0 to l_Collection.Count - 1 do try l_SubArray := l_Collection.Items[i]; {$IFDEF NoScripts} l_SubDescriptor := nil; {$ELSE} l_SubDescriptor := aControl.SubDescriptors[l_SubArray.Handle]; {$ENDIF NoScripts} if l_SubDescriptor <> nil then for k := 0 to l_SubArray.Count - 1 do begin PushObjData(aCtx, l_SubDescriptor, l_SubArray.Items[k]); l_Lambda.DoIt(aCtx); end; // for k := 0 to l_SubArray.Count - 1 do except on EtfwBreakIterator do Exit; end;//try..except //#UC END# *52D6471802DC_52D78486017B_impl* end;//TkwIterateSubDecriptorsOnSubPanel.DoWithSubPanel class function TkwIterateSubDecriptorsOnSubPanel.GetWordNameForRegister: AnsiString; begin Result := 'IterateSubDecriptorsOnSubPanel'; end;//TkwIterateSubDecriptorsOnSubPanel.GetWordNameForRegister initialization TkwIterateSubDecriptorsOnSubPanel.RegisterInEngine; {* Регистрация IterateSubDecriptorsOnSubPanel } {$IfEnd} // NOT Defined(NoScripts) end.
unit uTabWorkSpace; interface uses uWorkSpace, ComCtrls, Controls, Classes, Sysutils; type TTabWorkSpace = class(TWorkSpace) private FTabSheet: TTabSheet; procedure SetCaption(FileName: string); protected procedure DoSave(); public constructor Create(AOwner: TComponent; iIndex: Integer; FileName: string); destructor Destroy; override; function TabWS_GetPageIndex() : Integer; end; implementation uses uConstFile; { TTabWorkSpace } constructor TTabWorkSpace.Create(AOwner: TComponent; iIndex: Integer; FileName: string); begin inherited; FTabSheet := TTabSheet.Create(nil); FTabSheet.PageControl := TPageControl(AOwner); FTabSheet.Align := alClient; FTabSheet.Visible := True; FTabSheet.Tag := iIndex; end; destructor TTabWorkSpace.Destroy; begin FTabSheet.Free; FTabSheet := nil; inherited; end; procedure TTabWorkSpace.DoSave; begin SetCaption(GetFileName()); end; procedure TTabWorkSpace.SetCaption(FileName: string); begin if FileName = '' then FTabSheet.Caption := cst_Default_Title else FTabSheet.Caption := System.Copy(ExtractFileName(FileName), 1, 10); end; function TTabWorkSpace.TabWS_GetPageIndex: Integer; begin Result := FTabSheet.PageIndex; end; end.
unit Frame.Basic; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation; type TFrameBasic = class(TFrame) ButtonError: TButton; ButtonInfo: TButton; ButtonEnterExitMethod: TButton; ButtonWarning: TButton; procedure ButtonInfoClick(Sender: TObject); procedure ButtonWarningClick(Sender: TObject); procedure ButtonErrorClick(Sender: TObject); procedure ButtonEnterExitMethodClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.fmx} uses Grijjy.CloudLogging, SampleClasses; procedure TFrameBasic.ButtonErrorClick(Sender: TObject); begin GrijjyLog.Send('Sample Error Message', TgoLogLevel.Error); end; procedure TFrameBasic.ButtonInfoClick(Sender: TObject); begin GrijjyLog.Send('Sample Info Message', TgoLogLevel.Info); end; procedure TFrameBasic.ButtonEnterExitMethodClick(Sender: TObject); var Foo: TSampleFoo; begin Foo := TSampleFoo.Create; try GrijjyLog.EnterMethod(Self, 'ButtonMethodClick'); GrijjyLog.Send('Inside TFormMain.ButtonMethodClick', TgoLogLevel.Info); Foo.SomeMethod; GrijjyLog.ExitMethod(Self, 'ButtonMethodClick'); finally Foo.Free; end; end; procedure TFrameBasic.ButtonWarningClick(Sender: TObject); begin GrijjyLog.Send('Sample Warning Message', TgoLogLevel.Warning); end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons, StdCtrls, rxdbgrid, vclutils, rxmemds, db, IniPropStorage; type { TForm1 } TForm1 = class(TForm) Datasource1: TDatasource; Edit1: TEdit; IniPropStorage1: TIniPropStorage; PaintBox1: TPaintBox; RadioGroup1: TRadioGroup; RxDBGrid1: TRxDBGrid; RxMemoryData1: TRxMemoryData; RxMemoryData1Demo21: TStringField; RxMemoryData1DEMO_11: TLongintField; procedure CheckBox1Change(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PaintBox1Paint(Sender: TObject); private { private declarations } public { public declarations } end; var Form1: TForm1; implementation { TForm1 } procedure TForm1.PaintBox1Paint(Sender: TObject); var FOri:TTextOrientation; begin PaintBox1.Canvas.TextOut(1,1, 'Text for test'); case RadioGroup1.ItemIndex of 0:FOri:=toHorizontal; 1:FOri:=toVertical90; 2:FOri:=toHorizontal180; 3:FOri:=toVertical270; 4:FOri:=toHorizontal360; end; OutTextXY90(PaintBox1.Canvas, 1, 20, Edit1.Text, FOri); end; procedure TForm1.CheckBox1Change(Sender: TObject); var FOri:TTextOrientation; begin PaintBox1.Invalidate; case RadioGroup1.ItemIndex of 0:FOri:=toHorizontal; 1:FOri:=toVertical90; 2:FOri:=toHorizontal180; 3:FOri:=toVertical270; 4:FOri:=toHorizontal360; end; (RxDBGrid1.Columns[0].Title as TRxColumnTitle).Orientation:=FOri; end; procedure TForm1.Edit1Change(Sender: TObject); begin PaintBox1.Invalidate; (RxDBGrid1.Columns[0].Title as TRxColumnTitle).Caption:=Edit1.Text; end; procedure TForm1.FormCreate(Sender: TObject); begin RxMemoryData1.Open; end; initialization {$I unit1.lrs} end.
unit uUpdateListObserverInterface; interface uses Classes; type IUpdateListObserver = interface ['{56056643-4EF8-42CF-8300-BE775C9DE515}'] procedure UpdateCheckListBox(const Values: TStrings); end; IDisplay = interface ['{B4BA606A-3A00-418A-BF08-D8E4CBCEDA4B}'] procedure InitializeDisplayGrid; procedure DisplayData; end; ISubject = interface ['{2DCD8EFF-BA86-48DD-B852-B1ADF3C7CAE8}'] procedure RegisterObserver(aObserver: IUpdateListObserver); procedure RemoveObserver(aObserver: IUpdateListObserver); procedure NotifyObservers; end; implementation end.
{ Module of routines that implement the application specific pre-processor * for the Pascal front end to the translator. See the comment headers for * routine SST_R_PAS_PREPROC for more details (below). } module sst_r_pas_preproc; define sst_r_pas_preproc_init; define sst_r_pas_preproc; %include 'sst_r_pas.ins.pas'; const n_dir_names = 29; {number of valid compiler directive names} max_dir_name_len = 17; {max length of any compiler directive name} stack_file_block_size = 2048; {minimum size of stack blocks for file state} stack_mode_block_size = 512; {minimum size of stack blocks for parse mode} stack_align_block_size = 128; {minimum size of stack blocks for align mode} max_msg_parms = 4; {max parameters we can pass to a message} dir_name_dim_len = max_dir_name_len + 1; {storage length for directive name} dir_names_len = {number of chars for directive names list} (dir_name_dim_len * n_dir_names) - 1; type mode_k_t = ( {parsing mode for current character} mode_open_k, {not within any restrictions} mode_quote_k, {within quoted string} mode_comment_k, {within a comment} mode_token_k, {looking for start of a token} mode_token2_k, {currently accumulating a token, unquoted} mode_token2q_k, {currently accumulating a token, quoted} mode_directive_k, {at start of pre-proc directive (after "%")} mode_directive_end_k, {look for semicolon to end directive} mode_token_dir_k, {token just read is directive name} mode_token_incl_k, {just read include file name token} mode_token_incl2_k, {just read ";" after INCLUDE directive} mode_token_lnum_k, {just got line number token} mode_token_lnum2_k, mode_token_ifpush_k, {just got INFILE_PUSH file name} mode_token_ifpush2_k, mode_debug1_k, {part of DEBUG directive} mode_debug2_k); {part of DEBUG directive} frame_file_p_t = {pointer to input file state stack frame} ^frame_file_t; frame_mode_p_t = {pointer to parse mode state stack frame} ^frame_mode_t; frame_align_p_t = {pointer to stack frame for alignment state} ^frame_align_t; frame_file_t = record {stack frame for state per input file} prev_p: frame_file_p_t; {points to previous stack frame} line_p: syo_line_p_t; {points to partially unsed line, if any} start_char: sys_int_machine_t; {first unused character in the line} end; frame_mode_t = record {stack frame for saving parsing mode state} mode: mode_k_t; {saved parsing mode} end; frame_align_t = record {stack frame for saving curr alignment state} rule_align: sys_int_machine_t; {save current default alignment rule} end; directive_name_t = {for storing one compiler directive name} array[1..dir_name_dim_len] of char; var {static storage local to this module} stack_file: util_stack_handle_t; {stack for saving nested include file state} stack_mode: util_stack_handle_t; {stack for saving nested parse mode state} stack_align: util_stack_handle_t; {stack for saving curr alignment mode state} f_p: frame_file_p_t; {pointer to stack frame for current state} token_p: string_var_p_t; {points to current token being built} comment: string_var4_t; {end of comment string} comment_start: string_var4_t; {string that started current comment} directive: string_var32_t; {pre-processor directive name} parm: string_treename_t; {pre-processor directive parameter} mode: mode_k_t; {current input char parsing mode} pop_when_empty: boolean; {pop stack when current state exhausted} directive_names: {list of all the valid compiler directives} array[1..n_dir_names] of directive_name_t := [ 'BEGIN_INLINE ', {1} 'BEGIN_NOINLINE ', {2} 'DEBUG ', {3} 'EJECT ', {4} 'ELSE ', {5} 'ELSEIF ', {6} 'ELSEIFDEF ', {7} 'ENABLE ', {8} 'END_INLINE ', {9} 'END_NOINLINE ', {10} 'ENDIF ', {11} 'ERROR ', {12} 'EXIT ', {13} 'IF ', {14} 'INCLUDE ', {15} 'LIST ', {16} 'NATURAL_ALIGNMENT', {17} 'NOLIST ', {18} 'SLIBRARY ', {19} 'THEN ', {20} 'POP_ALIGNMENT ', {21} 'PUSH_ALIGNMENT ', {22} 'VAR ', {23} 'WARNING ', {24} 'WORD_ALIGNMENT ', {25} 'IFDEF ', {26} 'LNUM ', {27} 'INFILE_PUSH ', {28} 'INFILE_POP ' {29} ] ; { ********************************************* * * Subroutine SST_R_PAS_PREPROC_INIT * * Initialize the pre-processor. This is called before the first call to * PREPROC. } procedure sst_r_pas_preproc_init; begin comment.max := sizeof(comment.str); {init var strings in static storage} comment_start.max := sizeof(comment_start.str); directive.max := sizeof(directive.str); parm.max := sizeof(parm.str); syo_stack_alloc (stack_file); {create our stack for nested include state} stack_file^.stack_len := stack_file_block_size; {we won't be using much stack space} util_stack_push {create stack frame for top level state} (stack_file, sizeof(f_p^), f_p); f_p^.prev_p := nil; {indicate this is the top stack frame} f_p^.line_p := nil; {indicate no unfinished line is waiting} syo_stack_alloc (stack_mode); {create our stack for nested parse modes} stack_mode^.stack_len := stack_mode_block_size; {we won't be using much stack space} syo_stack_alloc (stack_align); {create our stack for nested align rules} stack_align^.stack_len := stack_align_block_size; {we won't be using much stack space} mode := mode_open_k; {init mode for first char in first file} pop_when_empty := false; {don't pop when stack when line is exhausted} end; { ********************************************* * * Subroutine SST_R_PAS_PREPROC (LINE_P,START_CHAR,N_CHARS) * * Specific pre-processor for the SYN program. } procedure sst_r_pas_preproc ( {pre-processor before syntaxer interpretation} out line_p: syo_line_p_t; {points to descriptor for line chars are from} out start_char: sys_int_machine_t; {starting char within line, first = 1} out n_chars: sys_int_machine_t); {number of characters returned by this call} var i: sys_int_machine_t; {index to current input character} cval: sys_int_machine_t; {integer value of current character} j, k: sys_int_machine_t; {scratch integers and loop counters} end_char: sys_int_machine_t; {index of last char to definately return} pick: sys_int_machine_t; {number of token picked from list} frame_file_new_p: frame_file_p_t; {points to new stack frame} frame_align_p: frame_align_p_t; {points to alignment stack frame} fnam: string_treename_t; {scratch file name} pass_char: boolean; {TRUE if curr char is to be passed back} pass_chunk: boolean; {TRUE if pass back chunk so far} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; {completion status code} label loop_line_in, loop_char_in, char_open_mode, not_comment_end, not_comment_start, directive_end, include_not_local, include_open_ok, next_char_in; { ************************************* * * Local subroutine MODE_PUSH (NEW_MODE) * This subroutine is local to routine SST_R_PAS_PREPROC. * * Push the current parsing mode onto the stack and then set the parsing mode * to NEW_MODE. } procedure mode_push ( in new_mode: mode_k_t); {new parsing mode to set} var frame_p: frame_mode_p_t; {pointer to new stack frame} begin util_stack_push (stack_mode, sizeof(frame_p^), frame_p); {make new stack frame} frame_p^.mode := mode; {save current state on new stack frame} mode := new_mode; {set new current state} end; { ************************************* * * Local subroutine MODE_POP * This subroutine is local to routine SST_R_PAS_PREPROC. * * Restore the current parsing state from the stack. The state must have * been previously saved with routine MODE_PUSH. } procedure mode_pop; var frame_p: frame_mode_p_t; {pointer to new stack frame} begin util_stack_last_frame (stack_mode, sizeof(frame_p^), frame_p); {get pnt to frame} mode := frame_p^.mode; {restore state from stack frame} util_stack_pop (stack_mode, sizeof(frame_p^)); {remove this stack frame} end; { ************************************* * * Start of main routine (SST_R_PAS_PREPROC) } begin fnam.max := sizeof(fnam.str); {init local var string} { * Init the subroutine return arguments LINE_P, START_CHAR. * LINE_P and START_CHAR will be initialized to point to the very next * input stream character. This may come from a partially processed input * source line left on the current stack frame, or from the next line from * the input files. The local variable LAST_CHAR will be initialized to * indicate that no characters are definately to be passed back (yet) from * the new line. * * We may also jump back here if the next character after the end of the * current line is needed. In this case it is assumed that any part of the * current line to be passed back has been, and it is therefore OK to trash * the state associated with it. } loop_line_in: {back here for next input line} if f_p^.line_p <> nil then begin {a previously unfinished line exists} line_p := f_p^.line_p; {restart where left off before} start_char := f_p^.start_char; f_p^.line_p := nil; {indicate no longer any previous line left} end else begin {no previously unfinished line found} if pop_when_empty then begin {need to pop to previous file ?} pop_when_empty := false; {don't pop until next end of file} f_p := f_p^.prev_p; {make previous stack frame current} util_stack_pop (stack_file, sizeof(f_p^)); {remove old stack frame from stack} goto loop_line_in; {re-try with popped state} end; syo_infile_read (line_p, stat); {read next line from input file} if file_eof(stat) then begin {this is last "line" from this file ?} pop_when_empty := {pop stack after this line if not top file} f_p^.prev_p <> nil; end; if sys_error(stat) then begin {hard error on trying to read input file ?} sys_msg_parm_int (msg_parm[1], line_p^.line_n); sys_msg_parm_vstr (msg_parm[2], line_p^.file_p^.conn_p^.tnam); sys_error_abort (stat, 'syn', 'syntax_error_msg', msg_parm, 2); end; start_char := 1; {start at first character on line} end ; {LINE_P and START_CHAR have been initialized} i := start_char; {init index of last character processed} end_char := start_char - 1; {init to no chars definately passed back yet} pass_chunk := false; {init to not force pass back of curr chunk} { * Loop back here to process each new character. } loop_char_in: {jump here to process the current character} pass_char := true; {init to this character must be passed back} cval := ord(line_p^.c[i]); {init integer character value} if cval > 127 then cval := cval ! ~127; {special flag char values are negative} case mode of {what parsing mode applies to this char ?} { ************************* * * This character is not within any restrictions. } mode_open_k: begin {not within any restrictions} char_open_mode: {jump here for common code with other modes} case line_p^.c[i] of '''': begin {start of a quoted string} if mode = mode_token2_k then begin {accumulating a token ?} mode_pop; {this ends the token} goto loop_char_in; {re-process this char with popped mode} end; mode_push (mode_quote_k); {we are now in a quoted string} end; '{': begin {start of a comment} mode_push (mode_comment_k); comment_start.str[1] := '{'; {remember comment start string} comment_start.len := 1; comment.str[1] := '}'; {set close comment character} comment.len := 1; pass_char := false; pass_chunk := true; {pass back chunk up to this comment} end; '"': begin {start of a comment} mode_push (mode_comment_k); comment_start.str[1] := '"'; {remember comment start string} comment_start.len := 1; comment.str[1] := '"'; {set close comment character} comment.len := 1; pass_char := false; pass_chunk := true; {pass back chunk up to this comment} end; '(': begin {possibly the start of a comment} if (i < line_p^.n_chars) and then {another character exists on this line ?} (line_p^.c[i+1] = '*') {next char confirms comment start ?} then begin {this is definately a comment start} mode_push (mode_comment_k); comment_start.str[1] := '('; {remember comment start string} comment_start.str[2] := '*'; comment_start.len := 2; comment.str[1] := '*'; {set close comment string} comment.str[2] := ')'; comment.len := 2; pass_char := false; i := i + 1; {skip over second comment start character} pass_chunk := true; {pass back chunk up to this comment} end; end; '%': begin {pre-processor directive follows} mode_push (mode_directive_k); pass_char := false; {don't pass back the "%" character} pass_chunk := true; {pass back chunk so far up to here} end; end; {done with OPEN mode character cases} if mode = mode_token_k {looking for start of a token ?} then mode := mode_token2_k; {this character starts the token} if {currently accumulating a token ?} (mode = mode_token2_k) or (mode = mode_token2q_k) then begin if token_p^.len < token_p^.max then begin {room for another char in token ?} token_p^.len := token_p^.len + 1; {one more character in token} token_p^.str[token_p^.len] := line_p^.c[i]; {copy character into token} end; end; end; {done processing character in OPEN mode} { ************************* * * We are looking for the start of a token as part of a pre-processor directive. } mode_token_k: begin {looking for the start of a directive token} pass_char := false; {definalely don't send this character on} if cval < 0 then goto next_char_in; {skip over special characters} case line_p^.c[i] of ' ': ; {skip over blanks} '''': begin {token is a quoted string} mode := mode_token2q_k; end; otherwise {not one of the characters above} mode := mode_token2_k; {token is not a quoted string} goto loop_char_in; {back and re-process char with new mode} end; end; { ************************* * * We are currently accumulating a token. The token is not quoted. } mode_token2_k: begin pass_char := false; {definately don't send this character on} if cval < 0 then begin {special character ends token} mode_pop; goto loop_char_in; end; case line_p^.c[i] of ' ', ';': begin {these characters end tokens} mode_pop; goto loop_char_in; end; end; {end of character cases} goto char_open_mode; {to common code with OPEN mode} end; { ************************* * * We are currently accumulating a token. The token IS quoted. } mode_token2q_k: begin {currently accumulating a directive token} pass_char := false; {definately don't send this character on} if cval < 0 then begin {special character ends token} mode_pop; goto loop_char_in; end; case line_p^.c[i] of '''': begin {end quote ends token} mode_pop; end; otherwise goto char_open_mode; {to common code with OPEN mode} end; {end of special handling character cases} end; { ************************* * * This character is within a quoted string. } mode_quote_k: begin {we are inside a quoted string} if (ord(line_p^.c[i]) > 127) or {special character not allowed in quotes ?} (line_p^.c[i] = '''') {explicit end of quoted string ?} then begin mode_pop; {end the quoted string, pop parsing mode} end; end; { ************************* * * This character is within a comment. } mode_comment_k: begin {we are inside a comment} pass_char := false; {don't pass back comment characters} if line_p^.c[i] = comment.str[1] then begin {could be start of end-comment ?} if (i + comment.len - 1) <= line_p^.n_chars then begin {end-comment could fit ?} k := i + 1; {init source line index of next comment char} for j := 2 to comment.len do begin {once for each remaining end-comment char} if line_p^.c[k] <> comment.str[j] {doesn't match comment end ?} then goto not_comment_end; k := k + 1; {advance source character index} end; {back and test next comment character} i := k - 1; {just got done with last comment end char} mode_pop; {no longer within a comment} goto next_char_in; {back and process next input stream character} end; end; not_comment_end: {jump here if definately still in a comment} if line_p^.c[i] = comment_start.str[1] then begin {could be start-comment ?} if (i + comment_start.len - 1) <= line_p^.n_chars then begin {could fit ?} k := i + 1; {init source line index of next comment char} for j := 2 to comment_start.len do begin {once for each remaining char} if line_p^.c[k] <> comment_start.str[j] {doesn't match comment start ?} then goto not_comment_start; k := k + 1; {advance source character index} end; {back and test next comment character} sys_msg_parm_int (msg_parm[1], line_p^.line_n); sys_msg_parm_vstr (msg_parm[2], line_p^.file_p^.conn_p^.tnam); sys_message_parms ('sst_pas_read', 'comment_start_start', msg_parm, 2); string_vstring (fnam, line_p^.c, line_p^.n_chars-1); {make writeable string} writeln (fnam.str:fnam.len); {show the line with the error} writeln ('':i-1, '^'); {point to offending character} sys_bomb; end; end; not_comment_start: {jump here if not hit illegal start of comm} if cval = syo_ichar_eof_k then begin {hit end of file within a comment ?} sys_msg_parm_vstr (msg_parm[1], line_p^.file_p^.conn_p^.tnam); sys_message_bomb ('sst_pas_read', 'comment_eof', msg_parm, 1); end; end; { ************************* * * This character is the first character of a directive name. } mode_directive_k: begin token_p := univ_ptr(addr(directive)); {point to token to accumulate} token_p^.len := 0; {init accumulated token length} mode := mode_token_dir_k; {set mode to pop back to after done token} mode_push (mode_token_k); {cause token to be accumulated} goto loop_char_in; {back and re-process char with new mode} end; { ************************* * * Skip to the ";" ending this compiler directive. } mode_directive_end_k: begin pass_char := false; {definately don't pass on this character} case cval of ord(' '), syo_ichar_eol_k: ; {skip over blanks and end of lines} ord(';'): begin {this is what we are looking for} mode_pop; {pop back to previous parse state} end; otherwise sys_msg_parm_int (msg_parm[1], line_p^.line_n); sys_msg_parm_vstr (msg_parm[2], line_p^.file_p^.conn_p^.tnam); sys_message_bomb ('sst_pas_read', 'directive_semicolon_missing', msg_parm, 2); end; end; { ************************* * * Current character is first character after directive name token. The * directive name is in DIRECTIVE. } mode_token_dir_k: begin string_upcase (directive); {make upper case for token matching} string_tkpick_s ( {pick token from list of valid choices} directive, {token to pick from list} directive_names, {list of valid choices} dir_names_len, {number of characters in choice list} pick); {number of token picked from list} case pick of { * All the legal but ignored compiler directives. } 1, {BEGIN_INLINE} 2, {BEGIN_NOINLINE} 4, {EJECT} 9, {END_INLINE} 10, {END_NOINLINE} 16, {LIST} 18: begin {NOLIST} directive_end: {jump here for common code to eat ";"} mode_pop; {set mode to pop back to after reading ";"} mode_push (mode_directive_end_k); {look for ";" ending this compiler directive} goto loop_char_in; {back and re-process this char with new mode} end; { * DEBUG } 3: begin token_p := univ_ptr(addr(parm)); {point to token to accumulate} token_p^.len := 0; {init accumulated token length} mode := mode_debug1_k; {mode to pop back to after done token} mode_push (mode_token_k); {cause token to be accumulated} goto loop_char_in; {back and re-process this char with new mode} end; { * INCLUDE <pathname> } 15: begin token_p := univ_ptr(addr(parm)); {point to token to accumulate} token_p^.len := 0; {init accumulated token length} mode := mode_token_incl_k; {set mode to pop back to after done token} mode_push (mode_token_k); {cause token to be accumulated} goto loop_char_in; {back and re-process this char with new mode} end; { * NATURAL_ALIGNMENT } 17: begin sst_align := sst_align_natural_k; goto directive_end; end; { * POP_ALIGNMENT } 21: begin util_stack_last_frame {get pointer to last alignment stack frame} (stack_align, sizeof(frame_align_p^), frame_align_p); sst_align := frame_align_p^.rule_align; {restore current alignment rule} util_stack_pop (stack_align, sizeof(frame_align_p^)); {remove last frame from stack} goto directive_end; end; { * PUSH_ALIGNMENT } 22: begin util_stack_push {create stack frame for saving state} (stack_align, sizeof(frame_align_p^), frame_align_p); frame_align_p^.rule_align := sst_align; {save alignment rule in stack frame} goto directive_end; end; { * WORD_ALIGNMENT } 25: begin sst_align := 2; goto directive_end; end; { * LNUM line_number } 27: begin token_p := univ_ptr(addr(parm)); {point to token to accumulate} token_p^.len := 0; {init accumulated token length} mode := mode_token_lnum_k; {set mode to pop back to after done token} mode_push (mode_token_k); {cause token to be accumulated} goto loop_char_in; {back and re-process this char with new mode} end; { * INFILE_PUSH filename } 28: begin token_p := univ_ptr(addr(parm)); {point to token to accumulate} token_p^.len := 0; {init accumulated token length} mode := mode_token_ifpush_k; {set mode to pop back to after done token} mode_push (mode_token_k); {cause token to be accumulated} goto loop_char_in; {back and re-process this char with new mode} end; { * INFILE_POP } 29: begin syo_infile_name_pop; goto directive_end; end; { * Unrecognized compiler directive. } otherwise sys_msg_parm_vstr (msg_parm[1], directive); sys_msg_parm_int (msg_parm[2], line_p^.line_n); sys_msg_parm_vstr (msg_parm[3], line_p^.file_p^.conn_p^.tnam); sys_message_bomb ('sst_pas_read', 'directive_unrecognized', msg_parm, 3); end; {end of directive name choices} end; { ************************* * * The include file name has just been read into PARM. } mode_token_incl_k: begin mode := mode_token_incl2_k; {mode to pop back to after found ";"} mode_push (mode_directive_end_k); {look for ";" to end directive} goto loop_char_in; {back and re-process char with new mode} end; mode_token_incl2_k: begin f_p^.line_p := line_p; {save state of current file on stack} f_p^.start_char := i; util_stack_push {make new stack frame for nested file state} (stack_file, sizeof(frame_file_new_p^), frame_file_new_p); frame_file_new_p^.prev_p := f_p; {point new frame back to its parent} f_p := frame_file_new_p; {make the new frame current} f_p^.line_p := nil; {init to no partial line read in new file} if sst_local_ins then begin {look for include file in local directory ?} string_generic_fnam (parm, '', fnam); {make leafname of include file in FNAM} syo_infile_push_sext (fnam, '', stat); {try for include file in current directory} if file_not_found(stat) then goto include_not_local; if not sys_error(stat) then goto include_open_ok; sys_msg_parm_vstr (msg_parm[1], parm); sys_msg_parm_int (msg_parm[2], line_p^.line_n); sys_msg_parm_vstr (msg_parm[3], line_p^.file_p^.conn_p^.tnam); sys_msg_parm_vstr (msg_parm[4], fnam); sys_error_abort (stat, 'sst_pas_read', 'directive_include_open_local', msg_parm, 4); end; {done handling LOCAL_INS switch ON} include_not_local: {open include file name exactly as given} syo_infile_push_sext (parm, '', stat); {save state and switch input to new file} if sys_error(stat) then begin {error opening include file ?} sys_msg_parm_vstr (msg_parm[1], parm); sys_msg_parm_int (msg_parm[2], line_p^.line_n); sys_msg_parm_vstr (msg_parm[3], line_p^.file_p^.conn_p^.tnam); sys_error_abort (stat, 'sst_pas_read', 'directive_include_open', msg_parm, 3); end; include_open_ok: {done opening include file, was successful} mode_pop; {pop to state before INCLUDE directive} goto loop_line_in; {get first line from new file} end; { ************************* * * PARM now contains the optional debug level string. It will be of zero * length if none was given. For compatibility with the Pascal compiler, * this will be interpreted as debug level 1. } mode_debug1_k: begin if parm.len > 0 then begin {a token was found} string_t_int (parm, j, stat); {convert token to debug level in J} if sys_error(stat) or (j < 1) then begin {bad or out of range parameter ?} sys_msg_parm_vstr (msg_parm[1], parm); sys_msg_parm_vstr (msg_parm[2], directive); sys_msg_parm_int (msg_parm[3], line_p^.line_n); sys_msg_parm_vstr (msg_parm[4], line_p^.file_p^.conn_p^.tnam); sys_message_bomb ('sst_pas_read', 'directive_parm_bad', msg_parm, 4); end; end else begin {no token was found, use default} j := 1; {set default debug level} end ; {J is now set to selected debug level} if sst_level_debug >= j then begin {debug code IS selected} mode_pop; {set state top pop back to after ";" is read} end else begin {debug code is NOT selected} mode := mode_debug2_k; {mode to pop back to after ";" is read} end ; mode_push (mode_directive_end_k); {look for ";" to end directive} goto loop_char_in; {back and re-process char with new mode} end; mode_debug2_k: begin {skip over input stream until end of line} pass_char := false; {init to not pass on this character} if cval = syo_ichar_eol_k then begin {found end of this line ?} mode_pop; pass_char := true; end; end; { ************************* * * The LNUM line number has just been read into PARM. } mode_token_lnum_k: begin mode := mode_token_lnum2_k; {mode to pop back to after found ";"} mode_push (mode_directive_end_k); {look for ";" to end directive} goto loop_char_in; {back and re-process char with new mode} end; mode_token_lnum2_k: begin string_t_int (parm, j, stat); {convert token to integer value} if sys_error(stat) then begin sys_msg_parm_vstr (msg_parm[1], parm); sys_msg_parm_vstr (msg_parm[2], directive); sys_msg_parm_int (msg_parm[3], line_p^.line_n); sys_msg_parm_vstr (msg_parm[4], line_p^.file_p^.conn_p^.tnam); sys_error_abort (stat, 'sst_pas_read', 'directive_parm_bad', msg_parm, 4); end; syo_infile_name_lnum (j); {set logical number of next input line} mode_pop; {pop to state before directive} end; { ************************* * * The INFILE_PUSH file name has just been read into PARM. } mode_token_ifpush_k: begin mode := mode_token_ifpush2_k; {mode to pop back to after found ";"} mode_push (mode_directive_end_k); {look for ";" to end directive} goto loop_char_in; {back and re-process char with new mode} end; mode_token_ifpush2_k: begin syo_infile_name_push (parm); {push new logical input file name} mode_pop; {pop to state before directive} end; { ************************* * * All done with the current character. * * At this point LINE_P, START_CHAR, and END_CHAR indicate the range of * characters from this line that will definately be returned so far. I * is the character index of the last character examined. * * If I indicates the last character on the current input line, then we * will pass back the definate portion of the current input line and restart * next time with the next line. * * PASS_CHAR indicates that the current character (at index I) is definately * to be passed back. PASS_CHUNK indicates that the current chunk so far * is to be passed back now. } end; {end of parsing mode cases} next_char_in: {jump here to advance to next input character} if pass_char then begin {current character must be passed back ?} if end_char < start_char then begin {this is first "solid" char this chunk ?} start_char := i; {reset start of chunk to this character} end; end_char := i; {this character will definately be passed back} end; pass_chunk := {end of input line forces pass back of chunk} pass_chunk or (i >= line_p^.n_chars); if pass_chunk then begin {need to pass back current chunk ?} if i < line_p^.n_chars then begin {more left on line after this chunk ?} f_p^.line_p := line_p; {save rest of line for next time} f_p^.start_char := i + 1; {restart at next char after current} end; n_chars := end_char - start_char + 1; {number of characters to return} if n_chars <= 0 then goto loop_line_in; {nothing left to return on this line ?} return; {pass back last piece of this line} end; i := i + 1; {make index of next character on current line} goto loop_char_in; {back and process this new character} end;
program facebook; const dimF = 200; type foto = record titulo :string; autor :string; likes :integer; clics :integer; comentarios :integer; end; fotos = array[1..dimF] of foto; procedure leerFoto(var f:foto); begin write('Ingrese el título: '); readln(f.titulo); write('Ingrese el autor: '); readln(f.autor); write('Ingrese la cantidad de likes: '); readln(f.likes); write('Ingrese la cantida de clics: '); readln(f.clics); write('Ingrese la cantida de comentarios: '); readln(f.comentarios); end; procedure comprobarMaximo(var fMax:foto; fActual:foto); begin if (fActual.clics >= fMax.clics) then fMax := fActual; end; var fs :fotos; maximo :foto; i, likesAutorCond :integer; begin maximo.clics := 0; likesAutorCond := 0; // Leer datos de las fotos for i:=1 to dimF do begin leerFoto(fs[i]); end; // Procesar datos de las fotos for i:=1 to dimF do begin // Más vista comprobarMaximo(maximo, fs[i]); // Likes de Art Vandelay if (fs[i].autor = 'Art Vandelay') then likesAutorCond := likesAutorCond + fs[i].likes; // Cantidad de comentarios writeln( 'La cantidad de comentarios para la foto es: ', fs[i].comentarios ); end; writeln('El título de la foto más vista es: ', maximo.titulo); end.
unit AppLogger; interface uses LoggerInterface; type TAppLoger = class(TObject) private class function GetLogger: ILogger; static; public class property Logger: ILogger read GetLogger; end; implementation uses Logger, AppSettings, System.SysUtils; var FLogger: TLogger = nil; class function TAppLoger.GetLogger: ILogger; begin if FLogger = nil then FLogger := TLogger.Create(nil, TAppSettings.Settings.Logger); Result := FLogger; end; initialization finalization if FLogger <> nil then FreeAndNil(FLogger); end.
unit ImageLoader; interface uses GameTypes; function LoadGameImage(const FileName : string) : TGameImage; implementation uses SysUtils, Classes, SpeedBmp, Dib2Frames, SpriteLoaders, ImageLoaders, GifLoader; function LoadGameImage(const FileName : string) : TGameImage; function HasGifExtension(const FileName : string) : boolean; const GifExt = '.GIF'; var i, j : integer; begin i := Length(FileName); j := Length(GifExt); while (j > 0) and (i > 0) and (UpCase( FileName[i] ) = GifExt[j]) do begin dec(i); dec(j); end; Result := j = 0; end; var aux : TSpeedBitmap; ImgStream : TMemoryStream; begin if HasGifExtension(FileName) then begin try ImgStream := TMemoryStream.Create; try ImgStream.LoadFromFile(FileName); LoadFrameImage(Result, ImgStream); finally ImgStream.Free; end; except Result := nil; end; end else begin aux := TSpeedBitmap.Create; try try aux.LoadFromFile(FileName); Result := FrameFromDib(aux.DibHeader, aux.ScanLines); finally aux.Free; end; except Result := nil; end; end; end; initialization RegisterLoader( GetGifLoader, 0 ); end.
unit ClientView; interface uses Windows, Classes, Controls, GameTypes, Protocol, MapTypes, VoyagerInterfaces, VoyagerServerInterfaces, Matrix; const evnSetWorldInfo = 65123; // >>>>> const cMapRows = 1000; cMapCols = 1000; type TSetWorldInfo = record MapImage : TMapImage; BuildClasses : IBuildingClassBag; end; type TTestMasterUrlHandler = class(TInterfacedObject, IMetaURLHandler, IMasterURLHandler, IClientView) public constructor Create; destructor Destroy; override; private // IMetaURLHandler function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL(URL : TURL) : THandlingAbility; function Instantiate : IURLHandler; private // IMasterURLHandler function HandleURL(URL : TURL) : TURLHandlingResult; function HandleEvent(EventId : TEventId; var info) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler(URLHandler : IMasterURLHandler); function RegisterMetaHandler(aMetaURLHandler : IMetaURLHandler) : TMetaHandlerRegistrationResult; procedure RegisterDefaultHandler(Handler : string); procedure RegisterExclusion(Excluder, ToExclude : string; mutual : boolean); procedure ReportNavigation( Handler : IURLHandler; URL : TURL; localBack, localForward : boolean ); function getURLIsLocal(URL : TURL) : boolean; private // IClientView procedure SetViewedArea( x, y, dx, dy : integer; out ErrorCode : TErrorCode ); function ObjectsInArea( x, y, dx, dy : integer; out ErrorCode : TErrorCode ) : TObjectReport; function ObjectAt( x, y : integer; out ErrorCode : TErrorCode ) : TObjId; function ObjectStatusText( kind : TStatusKind; Id : TObjId; out ErrorCode : TErrorCode ) : TStatusText; function ContextText : string; function ObjectConnections( Id : TObjId; out ErrorCode : TErrorCode ) : TCnxReport; procedure FocusObject( Id : TObjId; out ErrorCode : TErrorCode ); procedure UnfocusObject( Id : TObjId; out ErrorCode : TErrorCode ); function SwitchFocus( From : TObjId; toX, toY : integer; out ErrorCode : TErrorCode ) : TObjId; function GetCompanyList( out ErrorCode : TErrorCode ) : TCompanyReport; function NewCompany( name, cluster : string; out ErrorCode : TErrorCode ) : TCompanyInfo; procedure NewFacility( FacilityId : string; CompanyId : integer; x, y : integer; out ErrorCode : TErrorCode ); function ConnectFacilities( Facility1, Facility2 : TObjId; out ErrorCode : TErrorCode ) : string; function GetUserList( out ErrorCode : TErrorCode ) : TStringList; function GetChannelList( out ErrorCode : TErrorCode ) : TStringList; procedure SayThis( Dest, Msg : string; out ErrorCode : TErrorCode ); procedure VoiceThis( const Buffer : array of byte; len, TxId, NewTx : integer; out ErrorCode : TErrorCode ); function VoiceRequest( out ErrorCode : TErrorCode ) : integer; procedure CancelVoiceRequest( out ErrorCode : TErrorCode ); procedure VoiceStatusChanged( Status : integer; out ErrorCode : TErrorCode ); procedure VoiceTxOver( out ErrorCode : TErrorCode ); procedure CreateChannel( ChannelName, Password, aSessionApp, aSessionAppId : string; anUserLimit : integer; out ErrorCode : TErrorCode ); procedure JoinChannel( ChannelName, Password : string; out ErrorCode : TErrorCode ); function GetChannelInfo( ChannelName : string; out ErrorCode : TErrorCode ) : string; procedure MsgCompositionChanged( State : TMsgCompositionState; out ErrorCode : TErrorCode ); procedure Chase( UserName : string; out ErrorCode : TErrorCode ); procedure StopChase( out ErrorCode : TErrorCode ); procedure EnableEvents( out ErrorCode : TErrorCode ); procedure DisableEvents( out ErrorCode : TErrorCode ); procedure Logoff( out ErrorCode : TErrorCode ); procedure CreateCircuitSeg( CircuitId, OwnerId, x1, y1, x2, y2, cost : integer; out ErrorCode : TErrorCode ); procedure BreakCircuitAt( CircuitId, OwnerId, x, y : integer; out ErrorCode : TErrorCode ); procedure WipeCircuit( CircuitId, OwnerId, x1, y1, x2, y2 : integer; out ErrorCode : TErrorCode ); function SegmentsInArea( CircuitId, x, y, dx, dy : integer; out ErrorCode : TErrorCode ) : TSegmentReport; function GetSurface( SurfaceId : string; x, y, dx, dy : integer; out ErrorCode : TErrorCode ) : IMatrix; procedure DefineZone( TycoonId, ZoneId, x1, y1, x2, y2 : integer; out ErrorCode : TErrorCode ); function GetCookie( CookieId : string; out ErrorCode : TErrorCode ) : string; procedure SetCookie( CookieId, ValueId : string; out ErrorCode : TErrorCode ); procedure CloneFacility( x, y : integer; LimitToTown, LimitToCompany : boolean ); procedure GetNearestTownHall( x, y : integer; out xTown, yTown : integer ; out ErrorCode : TErrorCode ); function Echo( value : integer ) : integer; procedure ClientAware; procedure ClientNotAware; function getUserName : string; function getMoney : currency; function getCompanyName : string; function getCompanyId : TCompanyId; function getTycoonId : TObjId; function getTycoonUId : integer; function getDate : TDateTime; function getSeason : integer; function getWorldName : string; function getWorldURL : string; function getWorldXSize : integer; function getWorldYSize : integer; function getDAAddr : string; function getDAPort : integer; function getDALockPort : integer; function getISAddr : string; function getISPort : integer; function getMailAddr : string; function getMailPort : integer; function getMailAccount : string; function getCacheAddr : string; function getCachePort : integer; function getSecurityId : string; function getClientViewId : TObjId; function getChasedUser : string; procedure SuplantedBy( NewClientView : IClientView ); procedure DisposeObjectReport ( var ObjectReport : TObjectReport ); procedure DisposeSegmentReport( var SegmentReport : TSegmentReport ); procedure DisposeCnxReport( var CnxReport : TCnxReport ); procedure SetAutologon( active : boolean ); function Offline : boolean; private fFocus : TObjId; fBuildings : array[0..pred(cMapRows), 0..pred(cMapCols)] of word; fRoadSegs : TStringList; fRailroadSegs : TStringList; fWorldMap : TMapImage; fBuildClasses : IBuildingClassBag; procedure CreateBuildings; procedure FillBuilding(ii, jj : integer; const bclass : TBuildingClass); end; implementation uses SysUtils, Land, ServerCnxEvents, URLParser; const tidMetaHandlerName_TestServer = 'TestServer'; type PSingleArray = ^TSingleArray; TSingleArray = array[0 .. 0] of single; type TTestMatrix = class( TInterfacedObject, IMatrix ) private destructor Destroy; override; private fRows, fCols : integer; fItems : PSingleArray; private function getCols : integer; function getRows : integer; procedure setDimensions( n, m : integer ); function getElement ( i, j : integer ) : single; procedure setElement ( i, j : integer; value : single ); end; destructor TTestMatrix.Destroy; begin if fItems <> nil then freemem( fItems, fRows*fCols*sizeof(single) ); inherited; end; function TTestMatrix.getCols : integer; begin result := fCols; end; function TTestMatrix.getRows : integer; begin result := fRows; end; procedure TTestMatrix.setDimensions( n, m : integer ); begin if fItems <> nil then freemem( fItems, fRows*fCols*sizeof(single) ); fCols := m; fRows := n; getmem( fItems, fRows*fCols*sizeof(single) ); end; function TTestMatrix.getElement( i, j : integer ) : single; begin result := fItems[i*fCols + j]; end; procedure TTestMatrix.setElement( i, j : integer; value : single ); begin fItems[i*fCols + j] := value; end; constructor TTestMasterUrlHandler.Create; begin inherited; fRoadSegs := TStringList.Create; fRoadSegs.LoadFromFile(getWorldURL + '\roads.dat'); fRailroadSegs := TStringList.Create; fRailroadSegs.LoadFromFile( getWorldURL + '\railroads.dat'); end; destructor TTestMasterUrlHandler.Destroy; begin assert(RefCount = 0); fRoadSegs.Free; fRailroadSegs.Free; inherited end; function TTestMasterUrlHandler.getName : string; begin Result := tidMetaHandlerName_TestServer; end; function TTestMasterUrlHandler.getOptions : TURLHandlerOptions; begin Result := [hopNonvisual]; end; function TTestMasterUrlHandler.getCanHandleURL(URL : TURL) : THandlingAbility; begin Result := 0; end; function TTestMasterUrlHandler.Instantiate : IURLHandler; begin Result := IMasterUrlHandler(self); end; function TTestMasterUrlHandler.HandleURL(URL : TURL) : TURLHandlingResult; begin Result := urlNotHandled; end; function TTestMasterUrlHandler.HandleEvent(EventId : TEventId; var info) : TEventHandlingResult; var ClientView : IClientView absolute info; begin case EventId of evnAnswerClientView : begin ClientView := self; Result := evnHandled; end; evnSetWorldInfo : with TSetWorldInfo(info) do begin fWorldMap := MapImage; fBuildClasses := BuildClasses; CreateBuildings; Result := evnHandled; end; else Result := evnNotHandled; end; end; function TTestMasterUrlHandler.getControl : TControl; begin Result := nil; end; procedure TTestMasterUrlHandler.setMasterURLHandler(URLHandler : IMasterURLHandler); begin end; function TTestMasterUrlHandler.RegisterMetaHandler(aMetaURLHandler : IMetaURLHandler) : TMetaHandlerRegistrationResult; begin Result := mhrRegistered; end; procedure TTestMasterUrlHandler.RegisterDefaultHandler(Handler : string); begin end; procedure TTestMasterUrlHandler.RegisterExclusion(Excluder, ToExclude : string; mutual : boolean); begin end; procedure TTestMasterUrlHandler.ReportNavigation( Handler : IURLHandler; URL : TURL; localBack, localForward : boolean ); begin end; function TTestMasterUrlHandler.getURLIsLocal(URL : TURL) : boolean; begin Result := URLParser.GetAnchorData( URL ).FrameId = ''; end; procedure TTestMasterUrlHandler.SetViewedArea(x, y, dx, dy : integer; out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; function TTestMasterUrlHandler.ObjectsInArea(x, y, dx, dy : integer; out ErrorCode : TErrorCode) : TObjectReport; function CountObjects : integer; var i, j : integer; begin Result := 0; for i := y to y + dy do for j := x to x + dx do if (i <= cMapRows) and (j <= cMapCols) and (fBuildings[i, j] < pred(high(fBuildings[i, j]))) then inc(Result); end; procedure AddObjects; var i, j : integer; idx : integer; begin idx := 0; for i := y to y + dy do for j := x to x + dx do if (i <= cMapRows) and (j <= cMapCols) and (fBuildings[i, j] < pred(high(fBuildings[i, j]))) then begin Result.Objects[idx].VisualClass := fBuildings[i, j]; Result.Objects[idx].CompanyId := (i + j) mod 6; Result.Objects[idx].x := j; Result.Objects[idx].y := i; inc(idx); end; end; begin ErrorCode := NOERROR; Result.ObjectCount := CountObjects; if Result.ObjectCount > 0 then begin getmem(Result.Objects, Result.ObjectCount*sizeof(Result.Objects[0])); AddObjects; end else Result.Objects := nil; end; function TTestMasterUrlHandler.ObjectAt(x, y : integer; out ErrorCode : TErrorCode) : TObjId; begin if fBuildings[y, x] < pred(high(fBuildings[y, x])) then Result := x*succ(high(word)) + succ(y) else Result := 0; ErrorCode := NOERROR; end; function TTestMasterUrlHandler.ObjectStatusText(kind : TStatusKind; Id : TObjId; out ErrorCode : TErrorCode) : TStatusText; var i, j : integer; begin j := id div succ(high(word)); i := pred(id mod succ(high(word))); Result := IntToStr(ord(kind)) + ': (' + IntToStr(i) + ', ' + IntToStr(j) + ')' + #13#10 + 'Visual class:' + IntToStr(fBuildings[i, j]); ErrorCode := NOERROR; end; function TTestMasterUrlHandler.ContextText : string; begin Result := ''; end; function TTestMasterUrlHandler.ObjectConnections(Id : TObjId; out ErrorCode : TErrorCode) : TCnxReport; begin ErrorCode := NOERROR; fillchar(Result, sizeof(Result), 0); end; procedure TTestMasterUrlHandler.FocusObject(Id : TObjId; out ErrorCode : TErrorCode); begin fFocus := id; ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.UnfocusObject(Id : TObjId; out ErrorCode : TErrorCode); begin fFocus := 0; ErrorCode := NOERROR; end; function TTestMasterUrlHandler.SwitchFocus(From : TObjId; toX, toY : integer; out ErrorCode : TErrorCode) : TObjId; begin if fBuildings[toY, toX] < pred(high(fBuildings[toY, toX])) then fFocus := toX*succ(high(word)) + succ(toY) else fFocus := 0; ErrorCode := NOERROR; Result := fFocus; end; function TTestMasterUrlHandler.GetCompanyList(out ErrorCode : TErrorCode) : TCompanyReport; begin Result := nil; ErrorCode := NOERROR; end; function TTestMasterUrlHandler.NewCompany(name, cluster : string; out ErrorCode : TErrorCode) : TCompanyInfo; var TextualInfo : string; begin TextualInfo := ''; Result := ParseCompanyInfo(TextualInfo); ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.NewFacility(FacilityId : string; CompanyId : integer; x, y : integer; out ErrorCode : TErrorCode); var theClass : PBuildingClass; begin theClass := fBuildClasses.Get(strtoint(FacilityId)); assert(theClass <> nil); FillBuilding(y, x, theClass^); ErrorCode := NOERROR; // >>>>> end; function TTestMasterUrlHandler.ConnectFacilities( Facility1, Facility2 : TObjId; out ErrorCode : TErrorCode ) : string; begin Result := ''; end; function TTestMasterUrlHandler.GetUserList(out ErrorCode : TErrorCode) : TStringList; begin Result := TStringList.Create; Result.Text := 'med'^M^J'mike'; ErrorCode := NOERROR; end; function TTestMasterUrlHandler.GetChannelList(out ErrorCode : TErrorCode) : TStringList; begin Result := TStringList.Create; Result.Text := ''; ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.SayThis(Dest, Msg : string; out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.VoiceThis( const Buffer : array of byte; len, TxId, NewTx : integer; out ErrorCode : TErrorCode ); begin ErrorCode := NOERROR; end; function TTestMasterUrlHandler.VoiceRequest(out ErrorCode : TErrorCode) : integer; begin ErrorCode := NOERROR; Result := 0; end; procedure TTestMasterUrlHandler.CancelVoiceRequest(out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.VoiceStatusChanged(Status : integer; out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.VoiceTxOver(out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.CreateChannel(ChannelName, Password, aSessionApp, aSessionAppId : string; anUserLimit : integer; out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.JoinChannel(ChannelName, Password : string; out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; function TTestMasterUrlHandler.GetChannelInfo( ChannelName : string; out ErrorCode : TErrorCode ) : string; begin ErrorCode := NOERROR; Result := ''; end; procedure TTestMasterUrlHandler.MsgCompositionChanged(State : TMsgCompositionState; out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.Chase(UserName : string; out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.StopChase(out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.EnableEvents(out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.DisableEvents(out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.Logoff(out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.CreateCircuitSeg(CircuitId, OwnerId, x1, y1, x2, y2, cost : integer; out ErrorCode : TErrorCode); var RawSegments : TStringList; FileName : string; begin ErrorCode := NOERROR; case CircuitId of cirRoads: begin RawSegments := fRoadSegs; FileName := '\roads.dat'; end; cirRailroads: begin RawSegments := fRailroadSegs; FileName := '\railroads.dat'; end else RawSegments := nil; end; if RawSegments <> nil then begin RawSegments.Add(IntToStr(x1)); RawSegments.Add(IntToStr(y1)); RawSegments.Add(IntToStr(x2)); RawSegments.Add(IntToStr(y2)); RawSegments.SaveToFile(getWorldURL + FileName); end; end; procedure TTestMasterUrlHandler.BreakCircuitAt(CircuitId, OwnerId, x, y : integer; out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; procedure TTestMasterUrlHandler.WipeCircuit(CircuitId, OwnerId, x1, y1, x2, y2 : integer; out ErrorCode : TErrorCode); begin ErrorCode := NOERROR; end; function TTestMasterUrlHandler.SegmentsInArea(CircuitId, x, y, dx, dy : integer; out ErrorCode : TErrorCode) : TSegmentReport; var SegmentReport : TSegmentReport; SegmentIdx : integer; x1, y1 : integer; x2, y2 : integer; tmp : integer; RawSegments : TStringList; begin ErrorCode := NOERROR; case CircuitId of cirRoads: RawSegments := fRoadSegs; cirRailroads: RawSegments := fRailroadSegs else RawSegments := nil; end; if (RawSegments <> nil) and (RawSegments.Count <> 0) then with SegmentReport do begin getmem(Segments, RawSegments.Count div 4 * sizeof(TSegmentInfo)); SegmentCount := 0; for SegmentIdx := 0 to RawSegments.Count div 4 - 1 do begin x1 := StrToInt(RawSegments[SegmentIdx * 4]); y1 := StrToInt(RawSegments[SegmentIdx * 4 + 1]); x2 := StrToInt(RawSegments[SegmentIdx * 4 + 2]); y2 := StrToInt(RawSegments[SegmentIdx * 4 + 3]); if x1 > x2 then begin tmp := x1; x1 := x2; x2 := tmp end; if y1 > y2 then begin tmp := y1; y1 := y2; y2 := tmp end; if ( x1 < x + dx ) and ( x2 >= x ) and ( y1 < y + dx ) and ( y2 >= y ) then begin Segments[SegmentCount].x1 := x1; Segments[SegmentCount].y1 := y1; Segments[SegmentCount].x2 := x2; Segments[SegmentCount].y2 := y2; inc(SegmentCount); end end; ReallocMem( Segments, SegmentCount * SizeOf( TSegmentInfo ) ) end else begin SegmentReport.SegmentCount := 0; SegmentReport.Segments := nil end; Result := SegmentReport end; var curgen : integer = 0; function SinPlusCos(i, j : integer) : single; begin Result := cos(i*Pi/5) + sin(j*Pi/5); end; function SinMultCos(i, j : integer) : single; begin Result := cos(i*Pi/5)*sin(j*Pi/5); end; function SqSinPlusSqCos(i, j : integer) : single; begin Result := sqr(cos(i*Pi/5)) + sqr(sin(j*Pi/5)); end; function TTestMasterUrlHandler.GetSurface( SurfaceId : string; x, y, dx, dy : integer; out ErrorCode : TErrorCode ) : IMatrix; type TSurfaceGenFun = function(i, j : integer) : single; type TSurfaceGenData = record fun : TSurfaceGenFun; min : single; max : single; end; const SurfaceGenData : array [0 .. 2] of TSurfaceGenData = ( (fun : SinPlusCos; min : -2; max : 2), (fun : SinMultCos; min : -1; max : 1), (fun : SqSinPlusSqCos; min : 0; max : 2) ); function ScaleValue(val, min, max : single) : single; begin Result := 10*(val - min)/(max - min); end; var SurfaceData : IMatrix; i, j : integer; begin SurfaceData := TTestMatrix.Create; SurfaceData.SetDimensions(dy, dx); with SurfaceGenData[curgen] do for i := 0 to pred(dy) do for j := 0 to pred(dx) do SurfaceData.SetElement(i, j, ScaleValue(fun(i, j), min, max)); curgen := (curgen + 1) mod 3; ErrorCode := NOERROR; Result := SurfaceData; end; procedure TTestMasterUrlHandler.DefineZone( TycoonId, ZoneId, x1, y1, x2, y2 : integer; out ErrorCode : TErrorCode ); begin ErrorCode := NOERROR; end; function TTestMasterUrlHandler.GetCookie( CookieId : string; out ErrorCode : TErrorCode ) : string; begin Result := ''; end; procedure TTestMasterUrlHandler.SetCookie( CookieId, ValueId : string; out ErrorCode : TErrorCode ); begin end; procedure TTestMasterUrlHandler.CloneFacility( x, y : integer; LimitToTown, LimitToCompany : boolean ); begin end; procedure TTestMasterUrlHandler.GetNearestTownHall( x, y : integer; out xTown, yTown : integer ; out ErrorCode : TErrorCode ); begin end; function TTestMasterUrlHandler.Echo( value : integer ) : integer; begin Result := value; end; procedure TTestMasterUrlHandler.ClientAware; begin end; procedure TTestMasterUrlHandler.ClientNotAware; begin end; function TTestMasterUrlHandler.getUserName : string; begin Result := 'med'; end; function TTestMasterUrlHandler.getMoney : currency; begin Result := 400000; end; function TTestMasterUrlHandler.getCompanyName : string; begin Result := 'Merchise'; end; function TTestMasterUrlHandler.getTycoonId : TObjId; begin Result := 1; end; function TTestMasterUrlHandler.getTycoonUId : integer; begin Result := 0; end; function TTestMasterUrlHandler.getCompanyId : TCompanyId; begin Result := 1; // >>>> end; function TTestMasterUrlHandler.getDate : TDateTime; begin Result := SysUtils.Date; end; function TTestMasterUrlHandler.getSeason : integer; begin Result := random(4); end; function TTestMasterUrlHandler.getWorldName : string; begin Result := 'Zyrane'; end; function TTestMasterUrlHandler.getWorldURL : string; begin Result := ExtractFilePath(ParamStr(0)) + 'Cache'; end; function TTestMasterUrlHandler.getWorldXSize : integer; begin Result := cMapCols; // >>>> end; function TTestMasterUrlHandler.getWorldYSize : integer; begin Result := cMapRows; // >>>> end; function TTestMasterUrlHandler.getDAAddr : string; begin Result := ''; end; function TTestMasterUrlHandler.getDAPort : integer; begin Result := 0; end; function TTestMasterUrlHandler.getDALockPort : integer; begin Result := 0; end; function TTestMasterUrlHandler.getISAddr: string; begin Result := '220.0.1.128'; end; function TTestMasterUrlHandler.getISPort: integer; begin Result := 0; end; function TTestMasterUrlHandler.getMailAddr : string; begin Result := 'med@merchise.vcl.sld.cu'; end; function TTestMasterUrlHandler.getMailPort : integer; begin Result := 0; end; function TTestMasterUrlHandler.getMailAccount : string; begin Result := 'med'; end; function TTestMasterUrlHandler.getCacheAddr : string; begin Result := ''; end; function TTestMasterUrlHandler.getCachePort : integer; begin Result := 0; end; function TTestMasterUrlHandler.getSecurityId : string; begin Result := '0'; end; function TTestMasterUrlHandler.getClientViewId : TObjId; begin Result := 0; end; function TTestMasterUrlHandler.getChasedUser : string; begin Result := ''; end; procedure TTestMasterUrlHandler.SuplantedBy(NewClientView : IClientView); begin end; procedure TTestMasterUrlHandler.DisposeObjectReport(var ObjectReport : TObjectReport); begin with ObjectReport do begin freemem(Objects); ObjectCount := 0; Objects := nil; end; end; procedure TTestMasterUrlHandler.DisposeSegmentReport( var SegmentReport : TSegmentReport ); begin with SegmentReport do begin Freemem(Segments); SegmentCount := 0; Segments := nil; end; end; procedure TTestMasterUrlHandler.DisposeCnxReport( var CnxReport : TCnxReport ); begin end; procedure TTestMasterUrlHandler.SetAutologon( active : boolean ); begin end; function TTestMasterUrlHandler.Offline : boolean; begin Result := false; end; procedure TTestMasterUrlHandler.CreateBuildings; const cLoopCount = 1; var i, j : integer; loop : integer; lid : byte; bclass : PBuildingClass; {$IFNDEF USESMALLBCLASSSET} maxid : integer; {$ENDIF} function RandomBClassId : integer; {$IFDEF USESMALLBCLASSSET} const BClassIdSet : array [0..5] of integer = (2132, 2136, 2152, 2156, 2162, 2166); {$ENDIF} begin {$IFDEF USESMALLBCLASSSET} Result := BClassIdSet[random(6)]; {$ELSE} Result := random(maxid); {$ENDIF} end; begin fillchar(fBuildings, sizeof(fBuildings), $FF); {$IFNDEF USESMALLBCLASSSET} maxid := fBuildClasses.GetMaxId; {$ENDIF} for loop := 1 to cLoopCount do for i := 0 to high(fBuildings) - 4 do for j := 0 to high(fBuildings[i]) - 4 do begin lid := byte(fWorldMap.PixelAddr[j, i, 0]^); if LandClassOf(lid) <> lncZoneD then begin bclass := fBuildClasses.Get(RandomBClassId); if (bclass <> nil) and (bclass.ImagePath <> '') then FillBuilding(i, j, bclass^); end; end; end; procedure TTestMasterUrlHandler.FillBuilding(ii, jj : integer; const bclass : TBuildingClass); var i, j : integer; size : integer; ok : boolean; land : TLandClass; lid : byte; begin size := bclass.Size; ok := true; lid := byte(fWorldMap.PixelAddr[jj, ii, 0]^); land := LandClassOf(lid); i := ii; while (i < ii + size) and ok do begin j := jj; while (j < jj + size) and ok do begin lid := byte(fWorldMap.PixelAddr[j, i, 0]^); ok := LandClassOf(lid) = land; inc(j); end; inc(i); end; if ok then begin j := jj; while (fBuildings[ii, j] = high(fBuildings[ii, j])) and (j < jj + size) do inc(j); if j >= jj + size then begin i := ii; while (fBuildings[i, jj] = high(fBuildings[i, jj])) and (i < ii + size) do inc(i); if i >= ii + size then begin for i := ii to pred(ii + size) do for j := jj to pred(jj + size) do fBuildings[i, j] := pred(high(fBuildings[i, j])); fBuildings[ii, jj] := bclass.id; end; end; end; end; end.
unit TwoEmptyParaForOneReplacerTest; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "TestFormsTest" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/Daily/TwoEmptyParaForOneReplacerTest.pas" // Начат: 05.07.2010 16:14 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TTwoEmptyParaForOneReplacerTest // // Тест замены двух пустых абзацев на один // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses SearchAndReplacePrimTest, nevTools, evTypes ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} type TTwoEmptyParaForOneReplacerTest = {abstract} class(TSearchAndReplacePrimTest) {* Тест замены двух пустых абзацев на один } protected // realized methods function Searcher: IevSearcher; override; function Replacer: IevReplacer; override; function Options: TevSearchOptionSet; override; protected // overridden protected methods function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TTwoEmptyParaForOneReplacerTest {$IfEnd} //nsTest AND not NoVCM implementation {$If defined(nsTest) AND not defined(NoVCM)} uses SysUtils, evSearch, TestFrameWork ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // start class TTwoEmptyParaForOneReplacerTest function TTwoEmptyParaForOneReplacerTest.Searcher: IevSearcher; //#UC START# *4C288BAA0058_4C31CC59002B_var* var l_Searcher : TevRegExpMultipartSearcher; //#UC END# *4C288BAA0058_4C31CC59002B_var* begin //#UC START# *4C288BAA0058_4C31CC59002B_impl* l_Searcher := TevRegExpMultipartSearcher.Create; try l_Searcher.Options := Options; //l_Searcher.Multiblock := True; l_Searcher.Text := '$$'; Result := l_Searcher; finally FreeAndNil(l_Searcher); end;//try..finally //#UC END# *4C288BAA0058_4C31CC59002B_impl* end;//TTwoEmptyParaForOneReplacerTest.Searcher function TTwoEmptyParaForOneReplacerTest.Replacer: IevReplacer; //#UC START# *4C288BFC002C_4C31CC59002B_var* //#UC END# *4C288BFC002C_4C31CC59002B_var* begin //#UC START# *4C288BFC002C_4C31CC59002B_impl* Result := TevTextReplacer.Make(#13#10, Options); //#UC END# *4C288BFC002C_4C31CC59002B_impl* end;//TTwoEmptyParaForOneReplacerTest.Replacer function TTwoEmptyParaForOneReplacerTest.Options: TevSearchOptionSet; //#UC START# *4C288CC60231_4C31CC59002B_var* //#UC END# *4C288CC60231_4C31CC59002B_var* begin //#UC START# *4C288CC60231_4C31CC59002B_impl* Result := [ev_soGlobal, ev_soReplace, ev_soReplaceAll]; //#UC END# *4C288CC60231_4C31CC59002B_impl* end;//TTwoEmptyParaForOneReplacerTest.Options function TTwoEmptyParaForOneReplacerTest.GetFolder: AnsiString; {-} begin Result := 'Everest'; end;//TTwoEmptyParaForOneReplacerTest.GetFolder function TTwoEmptyParaForOneReplacerTest.GetModelElementGUID: AnsiString; {-} begin Result := '4C31CC59002B'; end;//TTwoEmptyParaForOneReplacerTest.GetModelElementGUID {$IfEnd} //nsTest AND not NoVCM end.
unit xdg_foreign_unstable_v2_protocol; {$mode objfpc} {$H+} {$interfaces corba} interface uses Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol; type Pzxdg_exporter_v2 = Pointer; Pzxdg_importer_v2 = Pointer; Pzxdg_exported_v2 = Pointer; Pzxdg_imported_v2 = Pointer; Pzxdg_exporter_v2_listener = ^Tzxdg_exporter_v2_listener; Tzxdg_exporter_v2_listener = record end; Pzxdg_importer_v2_listener = ^Tzxdg_importer_v2_listener; Tzxdg_importer_v2_listener = record end; Pzxdg_exported_v2_listener = ^Tzxdg_exported_v2_listener; Tzxdg_exported_v2_listener = record handle : procedure(data: Pointer; AZxdgExportedV2: Pzxdg_exported_v2; AHandle: Pchar); cdecl; end; Pzxdg_imported_v2_listener = ^Tzxdg_imported_v2_listener; Tzxdg_imported_v2_listener = record destroyed : procedure(data: Pointer; AZxdgImportedV2: Pzxdg_imported_v2); cdecl; end; TZxdgExporterV2 = class; TZxdgImporterV2 = class; TZxdgExportedV2 = class; TZxdgImportedV2 = class; IZxdgExporterV2Listener = interface ['IZxdgExporterV2Listener'] end; IZxdgImporterV2Listener = interface ['IZxdgImporterV2Listener'] end; IZxdgExportedV2Listener = interface ['IZxdgExportedV2Listener'] procedure zxdg_exported_v2_handle(AZxdgExportedV2: TZxdgExportedV2; AHandle: String); end; IZxdgImportedV2Listener = interface ['IZxdgImportedV2Listener'] procedure zxdg_imported_v2_destroyed(AZxdgImportedV2: TZxdgImportedV2); end; TZxdgExporterV2 = class(TWLProxyObject) private const _DESTROY = 0; const _EXPORT_TOPLEVEL = 1; public destructor Destroy; override; function ExportToplevel(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TZxdgExportedV2}): TZxdgExportedV2; function AddListener(AIntf: IZxdgExporterV2Listener): LongInt; end; TZxdgImporterV2 = class(TWLProxyObject) private const _DESTROY = 0; const _IMPORT_TOPLEVEL = 1; public destructor Destroy; override; function ImportToplevel(AHandle: String; AProxyClass: TWLProxyObjectClass = nil {TZxdgImportedV2}): TZxdgImportedV2; function AddListener(AIntf: IZxdgImporterV2Listener): LongInt; end; TZxdgExportedV2 = class(TWLProxyObject) private const _DESTROY = 0; public destructor Destroy; override; function AddListener(AIntf: IZxdgExportedV2Listener): LongInt; end; TZxdgImportedV2 = class(TWLProxyObject) private const _DESTROY = 0; const _SET_PARENT_OF = 1; public destructor Destroy; override; procedure SetParentOf(ASurface: TWlSurface); function AddListener(AIntf: IZxdgImportedV2Listener): LongInt; end; var zxdg_exporter_v2_interface: Twl_interface; zxdg_importer_v2_interface: Twl_interface; zxdg_exported_v2_interface: Twl_interface; zxdg_imported_v2_interface: Twl_interface; implementation var vIntf_zxdg_exporter_v2_Listener: Tzxdg_exporter_v2_listener; vIntf_zxdg_importer_v2_Listener: Tzxdg_importer_v2_listener; vIntf_zxdg_exported_v2_Listener: Tzxdg_exported_v2_listener; vIntf_zxdg_imported_v2_Listener: Tzxdg_imported_v2_listener; destructor TZxdgExporterV2.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZxdgExporterV2.ExportToplevel(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TZxdgExportedV2}): TZxdgExportedV2; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _EXPORT_TOPLEVEL, @zxdg_exported_v2_interface, nil, ASurface.Proxy); if AProxyClass = nil then AProxyClass := TZxdgExportedV2; Result := TZxdgExportedV2(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TZxdgExportedV2) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZxdgExportedV2]); end; function TZxdgExporterV2.AddListener(AIntf: IZxdgExporterV2Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_exporter_v2_Listener, @FUserDataRec); end; destructor TZxdgImporterV2.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZxdgImporterV2.ImportToplevel(AHandle: String; AProxyClass: TWLProxyObjectClass = nil {TZxdgImportedV2}): TZxdgImportedV2; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _IMPORT_TOPLEVEL, @zxdg_imported_v2_interface, nil, PChar(AHandle)); if AProxyClass = nil then AProxyClass := TZxdgImportedV2; Result := TZxdgImportedV2(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TZxdgImportedV2) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZxdgImportedV2]); end; function TZxdgImporterV2.AddListener(AIntf: IZxdgImporterV2Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_importer_v2_Listener, @FUserDataRec); end; destructor TZxdgExportedV2.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZxdgExportedV2.AddListener(AIntf: IZxdgExportedV2Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_exported_v2_Listener, @FUserDataRec); end; destructor TZxdgImportedV2.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; procedure TZxdgImportedV2.SetParentOf(ASurface: TWlSurface); begin wl_proxy_marshal(FProxy, _SET_PARENT_OF, ASurface.Proxy); end; function TZxdgImportedV2.AddListener(AIntf: IZxdgImportedV2Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_imported_v2_Listener, @FUserDataRec); end; procedure zxdg_exported_v2_handle_Intf(AData: PWLUserData; Azxdg_exported_v2: Pzxdg_exported_v2; AHandle: Pchar); cdecl; var AIntf: IZxdgExportedV2Listener; begin if AData = nil then Exit; AIntf := IZxdgExportedV2Listener(AData^.ListenerUserData); AIntf.zxdg_exported_v2_handle(TZxdgExportedV2(AData^.PascalObject), AHandle); end; procedure zxdg_imported_v2_destroyed_Intf(AData: PWLUserData; Azxdg_imported_v2: Pzxdg_imported_v2); cdecl; var AIntf: IZxdgImportedV2Listener; begin if AData = nil then Exit; AIntf := IZxdgImportedV2Listener(AData^.ListenerUserData); AIntf.zxdg_imported_v2_destroyed(TZxdgImportedV2(AData^.PascalObject)); end; const pInterfaces: array[0..12] of Pwl_interface = ( (nil), (nil), (nil), (nil), (nil), (nil), (nil), (nil), (@zxdg_exported_v2_interface), (@wl_surface_interface), (@zxdg_imported_v2_interface), (nil), (@wl_surface_interface) ); zxdg_exporter_v2_requests: array[0..1] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'export_toplevel'; signature: 'no'; types: @pInterfaces[8]) ); zxdg_importer_v2_requests: array[0..1] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'import_toplevel'; signature: 'ns'; types: @pInterfaces[10]) ); zxdg_exported_v2_requests: array[0..0] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]) ); zxdg_exported_v2_events: array[0..0] of Twl_message = ( (name: 'handle'; signature: 's'; types: @pInterfaces[0]) ); zxdg_imported_v2_requests: array[0..1] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'set_parent_of'; signature: 'o'; types: @pInterfaces[12]) ); zxdg_imported_v2_events: array[0..0] of Twl_message = ( (name: 'destroyed'; signature: ''; types: @pInterfaces[0]) ); initialization Pointer(vIntf_zxdg_exported_v2_Listener.handle) := @zxdg_exported_v2_handle_Intf; Pointer(vIntf_zxdg_imported_v2_Listener.destroyed) := @zxdg_imported_v2_destroyed_Intf; zxdg_exporter_v2_interface.name := 'zxdg_exporter_v2'; zxdg_exporter_v2_interface.version := 1; zxdg_exporter_v2_interface.method_count := 2; zxdg_exporter_v2_interface.methods := @zxdg_exporter_v2_requests; zxdg_exporter_v2_interface.event_count := 0; zxdg_exporter_v2_interface.events := nil; zxdg_importer_v2_interface.name := 'zxdg_importer_v2'; zxdg_importer_v2_interface.version := 1; zxdg_importer_v2_interface.method_count := 2; zxdg_importer_v2_interface.methods := @zxdg_importer_v2_requests; zxdg_importer_v2_interface.event_count := 0; zxdg_importer_v2_interface.events := nil; zxdg_exported_v2_interface.name := 'zxdg_exported_v2'; zxdg_exported_v2_interface.version := 1; zxdg_exported_v2_interface.method_count := 1; zxdg_exported_v2_interface.methods := @zxdg_exported_v2_requests; zxdg_exported_v2_interface.event_count := 1; zxdg_exported_v2_interface.events := @zxdg_exported_v2_events; zxdg_imported_v2_interface.name := 'zxdg_imported_v2'; zxdg_imported_v2_interface.version := 1; zxdg_imported_v2_interface.method_count := 2; zxdg_imported_v2_interface.methods := @zxdg_imported_v2_requests; zxdg_imported_v2_interface.event_count := 1; zxdg_imported_v2_interface.events := @zxdg_imported_v2_events; end.
unit ParseGen_Syn; interface var success : boolean; procedure Grammar; (* entry for recursive descent parser *) implementation uses ParseGen_Lex, FileWriter; procedure Rule(var r : string); FORWARD; procedure Expr(var e : string); FORWARD; procedure Term(var t : string); FORWARD; procedure Fact(var f : string); FORWARD; function syIsNot(expected : symbol) : boolean; begin if sy <> expected then success := FALSE; SyIsNot := NOT success; end; procedure Grammar; var r : string; begin (* Grammar = Rule { Rule }. *) Rule(r); if not success then exit; while (sy <> nonTermSy) do begin Rule(r); if not success then exit; end; end; procedure Rule(var r : string); var e : string; begin if sy <> nonTermSy then begin success := FALSE; exit; end; newSy; if sy <> isSy then begin success := FALSE; exit; end; newSy; Expr(e); if not success then exit; if sy <> dotSy then begin success := FALSE; exit; end; newSy; writeln('END'); end; procedure Expr(var e : string); var t : string; begin if(sy = arrowLeftSy) then begin Term(t); if not success then exit; while sy = barSy do begin Term(t); if not success then exit; end; if sy <> arrowRightSy then begin success := FALSE; exit; end; end else begin Term(t); if not success then exit; end; end; procedure Term(var t : string); var f : string; begin Fact(f); if not success then exit; while (sy <> nonTermSy) do begin Fact(f); if not success then exit; end; end; procedure Fact(var f : string); begin success := TRUE; case sy of nonTermSy: begin newSy; end; leftParSy: begin newSy; Expr(f); if not success then exit; if sy <> rightParSy then begin success := FALSE; exit; end; end; leftSqBrSy: begin newSy; Expr(f); if not success then exit; if sy <> rightSqBrSy then begin success := FALSE; exit; end; end; leftCurlSy: begin newSy; Expr(f); if not success then exit; if sy <> rightCurlSy then begin success := FALSE; exit; end; end; else begin newSy; end; end; end; begin end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** 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 SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StTree.pas 4.04 *} {*********************************************************} {* SysTools: AVL Tree class *} {*********************************************************} {$I StDefine.inc} {Notes: - These binary trees are self-balancing in the AVL sense (the depth of any left branch differs by no more than one from the depth of the right branch). - Duplicate data is not allowed in a tree. - Nodes can be of type TStTreeNode or any descendant. - The Compare property of the TStContainer ancestor must be set to specify the sort order of the tree. The Compare function operates on Data pointers. The Data pointer could be typecast to a number (any integer type), to a string pointer, to a record pointer, or to an instance of a class. - Next and Prev should not be used to iterate through an entire tree. This is much slower than calling the Iterate method. } unit StTree; interface uses Windows, SysUtils, Classes, StConst, StBase; type TStTreeNode = class(TStNode) {.Z+} protected tnPos : array[Boolean] of TStTreeNode; {Child nodes} tnBal : Integer; {Used during balancing} {.Z-} public constructor Create(AData : Pointer); override; {-Initialize node} end; TStTree = class(TStContainer) {.Z+} protected trRoot : TStTreeNode; {Root of tree} trIgnoreDups : Boolean; {Ignore duplicates during Join?} procedure ForEachPointer(Action : TIteratePointerFunc; OtherData : pointer); override; function StoresPointers : boolean; override; procedure trInsertNode(N : TStTreeNode); {.Z-} public constructor Create(NodeClass : TStNodeClass); virtual; {-Initialize an empty tree} procedure LoadFromStream(S : TStream); override; {-Create a list and its data from a stream} procedure StoreToStream(S : TStream); override; {-Write a list and its data to a stream} procedure Clear; override; {-Remove all nodes from container but leave it instantiated} function Insert(Data : Pointer) : TStTreeNode; {-Add a new node} procedure Delete(Data : Pointer); {-Delete a node} function Find(Data : Pointer) : TStTreeNode; {-Return node that matches Data} procedure Assign(Source: TPersistent); override; {-Assign another container's contents to this one} procedure Join(T: TStTree; IgnoreDups : Boolean); {-Add tree T into this one and dispose T} function Split(Data : Pointer) : TStTree; {-Split tree, putting all nodes above and including Data into new tree} function Iterate(Action : TIterateFunc; Up : Boolean; OtherData : Pointer) : TStTreeNode; {-Call Action for all the nodes, returning the last node visited} function First : TStTreeNode; {-Return the smallest-value node in the tree} function Last : TStTreeNode; {-Return the largest-value node in the tree} function Next(N : TStTreeNode) : TStTreeNode; {-Return the next node whose value is larger than N's} function Prev(N : TStTreeNode) : TStTreeNode; {-Return the largest node whose value is smaller than N's} end; {.Z+} TStTreeClass = class of TStTree; {.Z-} {======================================================================} implementation {$IFDEF ThreadSafe} var ClassCritSect : TRTLCriticalSection; {$ENDIF} procedure EnterClassCS; begin {$IFDEF ThreadSafe} EnterCriticalSection(ClassCritSect); {$ENDIF} end; procedure LeaveClassCS; begin {$IFDEF ThreadSafe} LeaveCriticalSection(ClassCritSect); {$ENDIF} end; const Left = False; Right = True; {Following stack declarations are used to avoid recursion in all tree routines. Because the tree is AVL-balanced, a stack size of 40 allows at least 2**32 elements in the tree without overflowing the stack.} const StackSize = 40; type StackNode = record Node : TStTreeNode; Comparison : Integer; end; StackArray = array[1..StackSize] of StackNode; constructor TStTreeNode.Create(AData : Pointer); begin inherited Create(AData); end; {----------------------------------------------------------------------} function Sign(I : Integer) : Integer; begin if I < 0 then Sign := -1 else if I > 0 then Sign := +1 else Sign := 0; end; procedure DelBalance(var P : TStTreeNode; var SubTreeDec : Boolean; CmpRes : Integer); var P1, P2 : TStTreeNode; B1, B2 : Integer; LR : Boolean; begin CmpRes := Sign(CmpRes); if P.tnBal = CmpRes then P.tnBal := 0 else if P.tnBal = 0 then begin P.tnBal := -CmpRes; SubTreeDec := False; end else begin LR := (CmpRes < 0); P1 := P.tnPos[LR]; B1 := P1.tnBal; if (B1 = 0) or (B1 = -CmpRes) then begin {Single RR or LL rotation} P.tnPos[LR] := P1.tnPos[not LR]; P1.tnPos[not LR] := P; if B1 = 0 then begin P.tnBal := -CmpRes; P1.tnBal := CmpRes; SubTreeDec := False; end else begin P.tnBal := 0; P1.tnBal := 0; end; P := P1; end else begin {Double RL or LR rotation} P2 := P1.tnPos[not LR]; B2 := P2.tnBal; P1.tnPos[not LR] := P2.tnPos[LR]; P2.tnPos[LR] := P1; P.tnPos[LR] := P2.tnPos[not LR]; P2.tnPos[not LR] := P; if B2 = -CmpRes then P.tnBal := CmpRes else P.tnBal := 0; if B2 = CmpRes then P1.tnBal := -CmpRes else P1.tnBal := 0; P := P2; P2.tnBal := 0; end; end; end; procedure InsBalance(var P : TStTreeNode; var SubTreeInc : Boolean; CmpRes : Integer); var P1 : TStTreeNode; P2 : TStTreeNode; LR : Boolean; begin CmpRes := Sign(CmpRes); if P.tnBal = -CmpRes then begin P.tnBal := 0; SubTreeInc := False; end else if P.tnBal = 0 then P.tnBal := CmpRes else begin LR := (CmpRes > 0); P1 := P.tnPos[LR]; if P1.tnBal = CmpRes then begin P.tnPos[LR] := P1.tnPos[not LR]; P1.tnPos[not LR] := P; P.tnBal := 0; P := P1; end else begin P2 := P1.tnPos[not LR]; P1.tnPos[not LR] := P2.tnPos[LR]; P2.tnPos[LR] := P1; P.tnPos[LR] := P2.tnPos[not LR]; P2.tnPos[not LR] := P; if P2.tnBal = CmpRes then P.tnBal := -CmpRes else P.tnBal := 0; if P2.tnBal = -CmpRes then P1.tnBal := CmpRes else P1.tnBal := 0; P := P2; end; P.tnBal := 0; SubTreeInc := False; end; end; function JoinNode(Container : TStContainer; Node : TStNode; OtherData : Pointer) : Boolean; far; var N : TStTreeNode; begin Result := True; N := TStTree(OtherData).Find(Node.Data); if Assigned(N) then if TStTree(OtherData).trIgnoreDups then begin Node.Free; Exit; end else RaiseContainerError(stscDupNode); with TStTreeNode(Node) do begin tnPos[Left] := nil; tnPos[Right] := nil; tnBal := 0; end; TStTree(OtherData).trInsertNode(TStTreeNode(Node)); end; type SplitRec = record SData : Pointer; STree : TStTree; end; function SplitTree(Container : TStContainer; Node : TStNode; OtherData : Pointer) : Boolean; far; var D : Pointer; begin Result := True; if Container.DoCompare(Node.Data, SplitRec(OtherData^).SData) >= 0 then begin D := Node.Data; TStTree(Container).Delete(D); SplitRec(OtherData^).STree.Insert(D); end; end; type TStoreInfo = record Wtr : TWriter; SDP : TStoreDataProc; end; function StoreNode(Container : TStContainer; Node : TStNode; OtherData : Pointer) : Boolean; far; begin Result := True; with TStoreInfo(OtherData^) do SDP(Wtr, Node.Data); end; function AssignData(Container : TStContainer; Data, OtherData : Pointer) : Boolean; far; var OurTree : TStTree absolute OtherData; begin OurTree.Insert(Data); Result := true; end; {----------------------------------------------------------------------} procedure TStTree.Assign(Source: TPersistent); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {The only containers that we allow to be assigned to a tree are - a SysTools linked list (TStList) - another SysTools binary search tree (TStTree) - a SysTools collection (TStCollection, TStSortedCollection)} if not AssignPointers(Source, AssignData) then inherited Assign(Source); {$IFDEF ThreadSafe} finally LeaveCS; end;{try..finally} {$ENDIF} end; procedure TStTree.Clear; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if conNodeProt = 0 then Iterate(DestroyNode, True, nil); trRoot := nil; FCount := 0; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStTree.ForEachPointer(Action : TIteratePointerFunc; OtherData : pointer); var P : TStTreeNode; Q : TStTreeNode; StackP : Integer; Stack : StackArray; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} StackP := 0; P := trRoot; repeat while Assigned(P) do begin Inc(StackP); Stack[StackP].Node := P; P := P.tnPos[false]; end; if StackP = 0 then begin Exit; end; P := Stack[StackP].Node; Dec(StackP); Q := P; P := P.tnPos[true]; if not Action(Self, Q.Data, OtherData) then begin Exit; end; until False; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStTree.StoresPointers : boolean; begin Result := true; end; constructor TStTree.Create(NodeClass : TStNodeClass); begin CreateContainer(NodeClass, 0); end; procedure TStTree.Delete(Data : Pointer); var P : TStTreeNode; Q : TStTreeNode; TmpData : Pointer; CmpRes : Integer; Found : Boolean; SubTreeDec : Boolean; StackP : Integer; Stack : StackArray; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} P := trRoot; if not Assigned(P) then Exit; {Find node to delete and stack the nodes to reach it} Found := False; StackP := 0; while not Found do begin CmpRes := DoCompare(Data, P.Data); Inc(StackP); if CmpRes = 0 then begin {Found node to delete} with Stack[StackP] do begin Node := P; Comparison := -1; end; Found := True; end else begin with Stack[StackP] do begin Node := P; Comparison := CmpRes; end; P := P.tnPos[CmpRes > 0]; if not Assigned(P) then {Node to delete not found} Exit; end; end; {Delete the node found} Q := P; if (not Assigned(Q.tnPos[Right])) or (not Assigned(Q.tnPos[Left])) then begin {Node has at most one branch} Dec(StackP); P := Q.tnPos[Assigned(Q.tnPos[Right])]; if StackP = 0 then trRoot := P else with Stack[StackP] do Node.tnPos[Comparison > 0] := P; end else begin {Node has two branches; stack nodes to reach one with no right child} P := Q.tnPos[Left]; while Assigned(P.tnPos[Right]) do begin Inc(StackP); with Stack[StackP] do begin Node := P; Comparison := 1; end; P := P.tnPos[Right]; end; {Swap the node to delete with the terminal node} TmpData := Q.Data; Q.Data := P.Data; Q := P; with Stack[StackP] do begin Node.tnPos[Comparison > 0].Data := TmpData; Node.tnPos[Comparison > 0] := P.tnPos[Left]; end; end; {Dispose of the deleted node} DisposeNodeData(Q); Q.Free; Dec(FCount); {Unwind the stack and rebalance} SubTreeDec := True; while (StackP > 0) and SubTreeDec do begin if StackP = 1 then DelBalance(trRoot, SubTreeDec, Stack[1].Comparison) else with Stack[StackP-1] do DelBalance(Node.tnPos[Comparison > 0], SubTreeDec, Stack[StackP].Comparison); dec(StackP); end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStTree.Find(Data : Pointer) : TStTreeNode; var P : TStTreeNode; CmpRes : Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} P := trRoot; while Assigned(P) do begin CmpRes := DoCompare(Data, P.Data); if CmpRes = 0 then begin Result := P; Exit; end else P := P.tnPos[CmpRes > 0]; end; Result := nil; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStTree.First : TStTreeNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Count = 0 then Result := nil else begin Result := trRoot; while Assigned(Result.tnPos[Left]) do Result := Result.tnPos[Left]; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStTree.Insert(Data : Pointer) : TStTreeNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {Create the node} Result := TStTreeNode(conNodeClass.Create(Data)); trInsertNode(Result); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStTree.Iterate(Action : TIterateFunc; Up : Boolean; OtherData : Pointer) : TStTreeNode; var P : TStTreeNode; Q : TStTreeNode; StackP : Integer; Stack : StackArray; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} StackP := 0; P := trRoot; repeat while Assigned(P) do begin Inc(StackP); Stack[StackP].Node := P; P := P.tnPos[not Up]; end; if StackP = 0 then begin Result := nil; Exit; end; P := Stack[StackP].Node; Dec(StackP); Q := P; P := P.tnPos[Up]; if not Action(Self, Q, OtherData) then begin Result := Q; Exit; end; until False; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStTree.Join(T: TStTree; IgnoreDups : Boolean); begin {$IFDEF ThreadSafe} EnterClassCS; EnterCS; T.EnterCS; try {$ENDIF} trIgnoreDups := IgnoreDups; T.Iterate(JoinNode, True, Self); T.IncNodeProtection; T.Free; {$IFDEF ThreadSafe} finally T.LeaveCS; LeaveCS; LeaveClassCS; end; {$ENDIF} end; function TStTree.Last : TStTreeNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Count = 0 then Result := nil else begin Result := trRoot; while Assigned(Result.tnPos[Right]) do Result := Result.tnPos[Right]; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStTree.Next(N : TStTreeNode) : TStTreeNode; var Found : Word; P : TStTreeNode; StackP : Integer; Stack : StackArray; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Result := nil; Found := 0; StackP := 0; P := trRoot; repeat while Assigned(P) do begin Inc(StackP); Stack[StackP].Node := P; P := P.tnPos[Left]; end; if StackP = 0 then Exit; P := Stack[StackP].Node; Dec(StackP); if Found = 1 then begin Result := P; Exit; end; if P = N then Inc(Found); P := P.tnPos[Right]; until False; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStTree.Prev(N : TStTreeNode) : TStTreeNode; var Found : Word; P : TStTreeNode; StackP : Integer; Stack : StackArray; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Result := nil; Found := 0; StackP := 0; P := trRoot; repeat while Assigned(P) do begin Inc(StackP); Stack[StackP].Node := P; P := P.tnPos[Right]; end; if StackP = 0 then Exit; P := Stack[StackP].Node; Dec(StackP); if Found = 1 then begin Result := P; Exit; end; if P = N then Inc(Found); P := P.tnPos[Left]; until False; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStTree.Split(Data : Pointer) : TStTree; var SR : SplitRec; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {Create and initialize the new tree} Result := TStTreeClass(ClassType).Create(conNodeClass); Result.Compare := Compare; Result.OnCompare := OnCompare; Result.DisposeData := DisposeData; Result.OnDisposeData := OnDisposeData; {Scan all elements to transfer some to new tree} SR.SData := Data; SR.STree := Result; {Prevent SplitTree from disposing of node data it moves from old tree to new} DisposeData := nil; OnDisposeData := nil; Iterate(SplitTree, True, @SR); {Restore DisposeData property} DisposeData := Result.DisposeData; OnDisposeData := Result.OnDisposeData; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStTree.trInsertNode(N : TStTreeNode); var P : TStTreeNode; CmpRes : Integer; StackP : Integer; Stack : StackArray; SubTreeInc : Boolean; begin if not Assigned(N) then Exit; {Handle first node} P := trRoot; if not Assigned(P) then begin trRoot := N; Inc(FCount); Exit; end; {Find where new node should fit in tree} StackP := 0; CmpRes := 0; {prevent D32 from generating a warning} while Assigned(P) do begin CmpRes := DoCompare(N.Data, P.Data); if CmpRes = 0 then begin {New node matches a node already in the tree, free it} N.Free; RaiseContainerError(stscDupNode); end; Inc(StackP); with Stack[StackP] do begin Node := P; Comparison := CmpRes; end; P := P.tnPos[CmpRes > 0]; end; {Insert new node} Stack[StackP].Node.tnPos[CmpRes > 0] := N; Inc(FCount); {Unwind the stack and rebalance} SubTreeInc := True; while (StackP > 0) and SubTreeInc do begin if StackP = 1 then InsBalance(trRoot, SubTreeInc, Stack[1].Comparison) else with Stack[StackP-1] do InsBalance(Node.tnPos[Comparison > 0], SubTreeInc, Stack[StackP].Comparison); dec(StackP); end; end; procedure TStTree.LoadFromStream(S : TStream); var Data : pointer; Reader : TReader; StreamedClass : TPersistentClass; StreamedNodeClass : TPersistentClass; StreamedClassName : string; StreamedNodeClassName : string; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Clear; Reader := TReader.Create(S, 1024); try with Reader do begin StreamedClassName := ReadString; StreamedClass := GetClass(StreamedClassName); if (StreamedClass = nil) then RaiseContainerErrorFmt(stscUnknownClass, [StreamedClassName]); if (not IsOrInheritsFrom(StreamedClass, Self.ClassType)) or (not IsOrInheritsFrom(TStTree, StreamedClass)) then RaiseContainerError(stscWrongClass); StreamedNodeClassName := ReadString; StreamedNodeClass := GetClass(StreamedNodeClassName); if (StreamedNodeClass = nil) then RaiseContainerErrorFmt(stscUnknownNodeClass, [StreamedNodeClassName]); if (not IsOrInheritsFrom(StreamedNodeClass, conNodeClass)) or (not IsOrInheritsFrom(TStTreeNode, StreamedNodeClass)) then RaiseContainerError(stscWrongNodeClass); ReadListBegin; while not EndOfList do begin Data := DoLoadData(Reader); Insert(Data); end; ReadListEnd; end; finally Reader.Free; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStTree.StoreToStream(S : TStream); var Writer : TWriter; StoreInfo : TStoreInfo; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Writer := TWriter.Create(S, 1024); try with Writer do begin WriteString(Self.ClassName); WriteString(conNodeClass.ClassName); WriteListBegin; StoreInfo.Wtr := Writer; StoreInfo.SDP := StoreData; Iterate(StoreNode, false, @StoreInfo); WriteListEnd; end; finally Writer.Free; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; {$IFDEF ThreadSafe} initialization Windows.InitializeCriticalSection(ClassCritSect); finalization Windows.DeleteCriticalSection(ClassCritSect); {$ENDIF} end.
unit TurnOffTimeMachineKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы TurnOffTimeMachine } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Common\TurnOffTimeMachineKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "TurnOffTimeMachineKeywordsPack" MUID: (DDD2ACFF7489) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses , vtRadioButton , vtDblClickDateEdit {$If NOT Defined(NoVCL)} , ExtCtrls {$IfEnd} // NOT Defined(NoVCL) , vtLabel , vtButton ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , TurnOffTimeMachine_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_TurnOffTimeMachine = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы TurnOffTimeMachine ---- *Пример использования*: [code] 'aControl' форма::TurnOffTimeMachine TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_TurnOffTimeMachine Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rb_totmChangeDate ---- *Пример использования*: [code] контрол::rb_totmChangeDate TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rb_totmChangeDate ---- *Пример использования*: [code] контрол::rb_totmChangeDate:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate_Push Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rb_totmStayInCurrentRedaction ---- *Пример использования*: [code] контрол::rb_totmStayInCurrentRedaction TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rb_totmStayInCurrentRedaction ---- *Пример использования*: [code] контрол::rb_totmStayInCurrentRedaction:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction_Push Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rb_totmGotoActualRedaction ---- *Пример использования*: [code] контрол::rb_totmGotoActualRedaction TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rb_totmGotoActualRedaction ---- *Пример использования*: [code] контрол::rb_totmGotoActualRedaction:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction_Push Tkw_TurnOffTimeMachine_Control_deChangeDate = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола deChangeDate ---- *Пример использования*: [code] контрол::deChangeDate TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_deChangeDate Tkw_TurnOffTimeMachine_Control_deChangeDate_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола deChangeDate ---- *Пример использования*: [code] контрол::deChangeDate:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_deChangeDate_Push Tkw_TurnOffTimeMachine_Control_pbDialogIcon = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола pbDialogIcon ---- *Пример использования*: [code] контрол::pbDialogIcon TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_pbDialogIcon Tkw_TurnOffTimeMachine_Control_pbDialogIcon_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола pbDialogIcon ---- *Пример использования*: [code] контрол::pbDialogIcon:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_pbDialogIcon_Push Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола lblTurnOnTimeMachineInfo ---- *Пример использования*: [code] контрол::lblTurnOnTimeMachineInfo TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола lblTurnOnTimeMachineInfo ---- *Пример использования*: [code] контрол::lblTurnOnTimeMachineInfo:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo_Push Tkw_TurnOffTimeMachine_Control_btnOk = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола btnOk ---- *Пример использования*: [code] контрол::btnOk TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_btnOk Tkw_TurnOffTimeMachine_Control_btnOk_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола btnOk ---- *Пример использования*: [code] контрол::btnOk:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_btnOk_Push Tkw_TurnOffTimeMachine_Control_btnCancel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола btnCancel ---- *Пример использования*: [code] контрол::btnCancel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_btnCancel Tkw_TurnOffTimeMachine_Control_btnCancel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола btnCancel ---- *Пример использования*: [code] контрол::btnCancel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TurnOffTimeMachine_Control_btnCancel_Push TkwEnTurnOffTimeMachineRbTotmChangeDate = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_TurnOffTimeMachine.rb_totmChangeDate } private function rb_totmChangeDate(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtRadioButton; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.rb_totmChangeDate } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnTurnOffTimeMachineRbTotmChangeDate TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_TurnOffTimeMachine.rb_totmStayInCurrentRedaction } private function rb_totmStayInCurrentRedaction(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtRadioButton; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.rb_totmStayInCurrentRedaction } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_TurnOffTimeMachine.rb_totmGotoActualRedaction } private function rb_totmGotoActualRedaction(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtRadioButton; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.rb_totmGotoActualRedaction } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction TkwEnTurnOffTimeMachineDeChangeDate = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_TurnOffTimeMachine.deChangeDate } private function deChangeDate(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.deChangeDate } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnTurnOffTimeMachineDeChangeDate TkwEnTurnOffTimeMachinePbDialogIcon = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_TurnOffTimeMachine.pbDialogIcon } private function pbDialogIcon(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TPaintBox; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.pbDialogIcon } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnTurnOffTimeMachinePbDialogIcon TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_TurnOffTimeMachine.lblTurnOnTimeMachineInfo } private function lblTurnOnTimeMachineInfo(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtLabel; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.lblTurnOnTimeMachineInfo } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo TkwEnTurnOffTimeMachineBtnOk = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_TurnOffTimeMachine.btnOk } private function btnOk(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtButton; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.btnOk } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnTurnOffTimeMachineBtnOk TkwEnTurnOffTimeMachineBtnCancel = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_TurnOffTimeMachine.btnCancel } private function btnCancel(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtButton; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.btnCancel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnTurnOffTimeMachineBtnCancel function Tkw_Form_TurnOffTimeMachine.GetString: AnsiString; begin Result := 'en_TurnOffTimeMachine'; end;//Tkw_Form_TurnOffTimeMachine.GetString class function Tkw_Form_TurnOffTimeMachine.GetWordNameForRegister: AnsiString; begin Result := 'форма::TurnOffTimeMachine'; end;//Tkw_Form_TurnOffTimeMachine.GetWordNameForRegister function Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate.GetString: AnsiString; begin Result := 'rb_totmChangeDate'; end;//Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate.GetString class procedure Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate.RegisterInEngine class function Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rb_totmChangeDate'; end;//Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate.GetWordNameForRegister procedure Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rb_totmChangeDate'); inherited; end;//Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate_Push.DoDoIt class function Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rb_totmChangeDate:push'; end;//Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate_Push.GetWordNameForRegister function Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction.GetString: AnsiString; begin Result := 'rb_totmStayInCurrentRedaction'; end;//Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction.GetString class procedure Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction.RegisterInEngine class function Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rb_totmStayInCurrentRedaction'; end;//Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction.GetWordNameForRegister procedure Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rb_totmStayInCurrentRedaction'); inherited; end;//Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction_Push.DoDoIt class function Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rb_totmStayInCurrentRedaction:push'; end;//Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction_Push.GetWordNameForRegister function Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction.GetString: AnsiString; begin Result := 'rb_totmGotoActualRedaction'; end;//Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction.GetString class procedure Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction.RegisterInEngine class function Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rb_totmGotoActualRedaction'; end;//Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction.GetWordNameForRegister procedure Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rb_totmGotoActualRedaction'); inherited; end;//Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction_Push.DoDoIt class function Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rb_totmGotoActualRedaction:push'; end;//Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction_Push.GetWordNameForRegister function Tkw_TurnOffTimeMachine_Control_deChangeDate.GetString: AnsiString; begin Result := 'deChangeDate'; end;//Tkw_TurnOffTimeMachine_Control_deChangeDate.GetString class procedure Tkw_TurnOffTimeMachine_Control_deChangeDate.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtDblClickDateEdit); end;//Tkw_TurnOffTimeMachine_Control_deChangeDate.RegisterInEngine class function Tkw_TurnOffTimeMachine_Control_deChangeDate.GetWordNameForRegister: AnsiString; begin Result := 'контрол::deChangeDate'; end;//Tkw_TurnOffTimeMachine_Control_deChangeDate.GetWordNameForRegister procedure Tkw_TurnOffTimeMachine_Control_deChangeDate_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('deChangeDate'); inherited; end;//Tkw_TurnOffTimeMachine_Control_deChangeDate_Push.DoDoIt class function Tkw_TurnOffTimeMachine_Control_deChangeDate_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::deChangeDate:push'; end;//Tkw_TurnOffTimeMachine_Control_deChangeDate_Push.GetWordNameForRegister function Tkw_TurnOffTimeMachine_Control_pbDialogIcon.GetString: AnsiString; begin Result := 'pbDialogIcon'; end;//Tkw_TurnOffTimeMachine_Control_pbDialogIcon.GetString class procedure Tkw_TurnOffTimeMachine_Control_pbDialogIcon.RegisterInEngine; begin inherited; TtfwClassRef.Register(TPaintBox); end;//Tkw_TurnOffTimeMachine_Control_pbDialogIcon.RegisterInEngine class function Tkw_TurnOffTimeMachine_Control_pbDialogIcon.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pbDialogIcon'; end;//Tkw_TurnOffTimeMachine_Control_pbDialogIcon.GetWordNameForRegister procedure Tkw_TurnOffTimeMachine_Control_pbDialogIcon_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('pbDialogIcon'); inherited; end;//Tkw_TurnOffTimeMachine_Control_pbDialogIcon_Push.DoDoIt class function Tkw_TurnOffTimeMachine_Control_pbDialogIcon_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pbDialogIcon:push'; end;//Tkw_TurnOffTimeMachine_Control_pbDialogIcon_Push.GetWordNameForRegister function Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo.GetString: AnsiString; begin Result := 'lblTurnOnTimeMachineInfo'; end;//Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo.GetString class procedure Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo.RegisterInEngine class function Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo.GetWordNameForRegister: AnsiString; begin Result := 'контрол::lblTurnOnTimeMachineInfo'; end;//Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo.GetWordNameForRegister procedure Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('lblTurnOnTimeMachineInfo'); inherited; end;//Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo_Push.DoDoIt class function Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::lblTurnOnTimeMachineInfo:push'; end;//Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo_Push.GetWordNameForRegister function Tkw_TurnOffTimeMachine_Control_btnOk.GetString: AnsiString; begin Result := 'btnOk'; end;//Tkw_TurnOffTimeMachine_Control_btnOk.GetString class procedure Tkw_TurnOffTimeMachine_Control_btnOk.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtButton); end;//Tkw_TurnOffTimeMachine_Control_btnOk.RegisterInEngine class function Tkw_TurnOffTimeMachine_Control_btnOk.GetWordNameForRegister: AnsiString; begin Result := 'контрол::btnOk'; end;//Tkw_TurnOffTimeMachine_Control_btnOk.GetWordNameForRegister procedure Tkw_TurnOffTimeMachine_Control_btnOk_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('btnOk'); inherited; end;//Tkw_TurnOffTimeMachine_Control_btnOk_Push.DoDoIt class function Tkw_TurnOffTimeMachine_Control_btnOk_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::btnOk:push'; end;//Tkw_TurnOffTimeMachine_Control_btnOk_Push.GetWordNameForRegister function Tkw_TurnOffTimeMachine_Control_btnCancel.GetString: AnsiString; begin Result := 'btnCancel'; end;//Tkw_TurnOffTimeMachine_Control_btnCancel.GetString class procedure Tkw_TurnOffTimeMachine_Control_btnCancel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtButton); end;//Tkw_TurnOffTimeMachine_Control_btnCancel.RegisterInEngine class function Tkw_TurnOffTimeMachine_Control_btnCancel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::btnCancel'; end;//Tkw_TurnOffTimeMachine_Control_btnCancel.GetWordNameForRegister procedure Tkw_TurnOffTimeMachine_Control_btnCancel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('btnCancel'); inherited; end;//Tkw_TurnOffTimeMachine_Control_btnCancel_Push.DoDoIt class function Tkw_TurnOffTimeMachine_Control_btnCancel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::btnCancel:push'; end;//Tkw_TurnOffTimeMachine_Control_btnCancel_Push.GetWordNameForRegister function TkwEnTurnOffTimeMachineRbTotmChangeDate.rb_totmChangeDate(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtRadioButton; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.rb_totmChangeDate } begin Result := aen_TurnOffTimeMachine.rb_totmChangeDate; end;//TkwEnTurnOffTimeMachineRbTotmChangeDate.rb_totmChangeDate class function TkwEnTurnOffTimeMachineRbTotmChangeDate.GetWordNameForRegister: AnsiString; begin Result := '.Ten_TurnOffTimeMachine.rb_totmChangeDate'; end;//TkwEnTurnOffTimeMachineRbTotmChangeDate.GetWordNameForRegister function TkwEnTurnOffTimeMachineRbTotmChangeDate.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnTurnOffTimeMachineRbTotmChangeDate.GetResultTypeInfo function TkwEnTurnOffTimeMachineRbTotmChangeDate.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnTurnOffTimeMachineRbTotmChangeDate.GetAllParamsCount function TkwEnTurnOffTimeMachineRbTotmChangeDate.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_TurnOffTimeMachine)]); end;//TkwEnTurnOffTimeMachineRbTotmChangeDate.ParamsTypes procedure TkwEnTurnOffTimeMachineRbTotmChangeDate.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rb_totmChangeDate', aCtx); end;//TkwEnTurnOffTimeMachineRbTotmChangeDate.SetValuePrim procedure TkwEnTurnOffTimeMachineRbTotmChangeDate.DoDoIt(const aCtx: TtfwContext); var l_aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine; begin try l_aen_TurnOffTimeMachine := Ten_TurnOffTimeMachine(aCtx.rEngine.PopObjAs(Ten_TurnOffTimeMachine)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rb_totmChangeDate(aCtx, l_aen_TurnOffTimeMachine)); end;//TkwEnTurnOffTimeMachineRbTotmChangeDate.DoDoIt function TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.rb_totmStayInCurrentRedaction(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtRadioButton; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.rb_totmStayInCurrentRedaction } begin Result := aen_TurnOffTimeMachine.rb_totmStayInCurrentRedaction; end;//TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.rb_totmStayInCurrentRedaction class function TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.GetWordNameForRegister: AnsiString; begin Result := '.Ten_TurnOffTimeMachine.rb_totmStayInCurrentRedaction'; end;//TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.GetWordNameForRegister function TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.GetResultTypeInfo function TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.GetAllParamsCount function TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_TurnOffTimeMachine)]); end;//TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.ParamsTypes procedure TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rb_totmStayInCurrentRedaction', aCtx); end;//TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.SetValuePrim procedure TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.DoDoIt(const aCtx: TtfwContext); var l_aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine; begin try l_aen_TurnOffTimeMachine := Ten_TurnOffTimeMachine(aCtx.rEngine.PopObjAs(Ten_TurnOffTimeMachine)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rb_totmStayInCurrentRedaction(aCtx, l_aen_TurnOffTimeMachine)); end;//TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.DoDoIt function TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.rb_totmGotoActualRedaction(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtRadioButton; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.rb_totmGotoActualRedaction } begin Result := aen_TurnOffTimeMachine.rb_totmGotoActualRedaction; end;//TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.rb_totmGotoActualRedaction class function TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.GetWordNameForRegister: AnsiString; begin Result := '.Ten_TurnOffTimeMachine.rb_totmGotoActualRedaction'; end;//TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.GetWordNameForRegister function TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.GetResultTypeInfo function TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.GetAllParamsCount function TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_TurnOffTimeMachine)]); end;//TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.ParamsTypes procedure TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rb_totmGotoActualRedaction', aCtx); end;//TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.SetValuePrim procedure TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.DoDoIt(const aCtx: TtfwContext); var l_aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine; begin try l_aen_TurnOffTimeMachine := Ten_TurnOffTimeMachine(aCtx.rEngine.PopObjAs(Ten_TurnOffTimeMachine)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rb_totmGotoActualRedaction(aCtx, l_aen_TurnOffTimeMachine)); end;//TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.DoDoIt function TkwEnTurnOffTimeMachineDeChangeDate.deChangeDate(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.deChangeDate } begin Result := aen_TurnOffTimeMachine.deChangeDate; end;//TkwEnTurnOffTimeMachineDeChangeDate.deChangeDate class function TkwEnTurnOffTimeMachineDeChangeDate.GetWordNameForRegister: AnsiString; begin Result := '.Ten_TurnOffTimeMachine.deChangeDate'; end;//TkwEnTurnOffTimeMachineDeChangeDate.GetWordNameForRegister function TkwEnTurnOffTimeMachineDeChangeDate.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtDblClickDateEdit); end;//TkwEnTurnOffTimeMachineDeChangeDate.GetResultTypeInfo function TkwEnTurnOffTimeMachineDeChangeDate.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnTurnOffTimeMachineDeChangeDate.GetAllParamsCount function TkwEnTurnOffTimeMachineDeChangeDate.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_TurnOffTimeMachine)]); end;//TkwEnTurnOffTimeMachineDeChangeDate.ParamsTypes procedure TkwEnTurnOffTimeMachineDeChangeDate.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству deChangeDate', aCtx); end;//TkwEnTurnOffTimeMachineDeChangeDate.SetValuePrim procedure TkwEnTurnOffTimeMachineDeChangeDate.DoDoIt(const aCtx: TtfwContext); var l_aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine; begin try l_aen_TurnOffTimeMachine := Ten_TurnOffTimeMachine(aCtx.rEngine.PopObjAs(Ten_TurnOffTimeMachine)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(deChangeDate(aCtx, l_aen_TurnOffTimeMachine)); end;//TkwEnTurnOffTimeMachineDeChangeDate.DoDoIt function TkwEnTurnOffTimeMachinePbDialogIcon.pbDialogIcon(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TPaintBox; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.pbDialogIcon } begin Result := aen_TurnOffTimeMachine.pbDialogIcon; end;//TkwEnTurnOffTimeMachinePbDialogIcon.pbDialogIcon class function TkwEnTurnOffTimeMachinePbDialogIcon.GetWordNameForRegister: AnsiString; begin Result := '.Ten_TurnOffTimeMachine.pbDialogIcon'; end;//TkwEnTurnOffTimeMachinePbDialogIcon.GetWordNameForRegister function TkwEnTurnOffTimeMachinePbDialogIcon.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TPaintBox); end;//TkwEnTurnOffTimeMachinePbDialogIcon.GetResultTypeInfo function TkwEnTurnOffTimeMachinePbDialogIcon.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnTurnOffTimeMachinePbDialogIcon.GetAllParamsCount function TkwEnTurnOffTimeMachinePbDialogIcon.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_TurnOffTimeMachine)]); end;//TkwEnTurnOffTimeMachinePbDialogIcon.ParamsTypes procedure TkwEnTurnOffTimeMachinePbDialogIcon.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству pbDialogIcon', aCtx); end;//TkwEnTurnOffTimeMachinePbDialogIcon.SetValuePrim procedure TkwEnTurnOffTimeMachinePbDialogIcon.DoDoIt(const aCtx: TtfwContext); var l_aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine; begin try l_aen_TurnOffTimeMachine := Ten_TurnOffTimeMachine(aCtx.rEngine.PopObjAs(Ten_TurnOffTimeMachine)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(pbDialogIcon(aCtx, l_aen_TurnOffTimeMachine)); end;//TkwEnTurnOffTimeMachinePbDialogIcon.DoDoIt function TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.lblTurnOnTimeMachineInfo(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtLabel; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.lblTurnOnTimeMachineInfo } begin Result := aen_TurnOffTimeMachine.lblTurnOnTimeMachineInfo; end;//TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.lblTurnOnTimeMachineInfo class function TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.GetWordNameForRegister: AnsiString; begin Result := '.Ten_TurnOffTimeMachine.lblTurnOnTimeMachineInfo'; end;//TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.GetWordNameForRegister function TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.GetResultTypeInfo function TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.GetAllParamsCount function TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_TurnOffTimeMachine)]); end;//TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.ParamsTypes procedure TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству lblTurnOnTimeMachineInfo', aCtx); end;//TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.SetValuePrim procedure TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.DoDoIt(const aCtx: TtfwContext); var l_aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine; begin try l_aen_TurnOffTimeMachine := Ten_TurnOffTimeMachine(aCtx.rEngine.PopObjAs(Ten_TurnOffTimeMachine)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(lblTurnOnTimeMachineInfo(aCtx, l_aen_TurnOffTimeMachine)); end;//TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.DoDoIt function TkwEnTurnOffTimeMachineBtnOk.btnOk(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtButton; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.btnOk } begin Result := aen_TurnOffTimeMachine.btnOk; end;//TkwEnTurnOffTimeMachineBtnOk.btnOk class function TkwEnTurnOffTimeMachineBtnOk.GetWordNameForRegister: AnsiString; begin Result := '.Ten_TurnOffTimeMachine.btnOk'; end;//TkwEnTurnOffTimeMachineBtnOk.GetWordNameForRegister function TkwEnTurnOffTimeMachineBtnOk.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtButton); end;//TkwEnTurnOffTimeMachineBtnOk.GetResultTypeInfo function TkwEnTurnOffTimeMachineBtnOk.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnTurnOffTimeMachineBtnOk.GetAllParamsCount function TkwEnTurnOffTimeMachineBtnOk.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_TurnOffTimeMachine)]); end;//TkwEnTurnOffTimeMachineBtnOk.ParamsTypes procedure TkwEnTurnOffTimeMachineBtnOk.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству btnOk', aCtx); end;//TkwEnTurnOffTimeMachineBtnOk.SetValuePrim procedure TkwEnTurnOffTimeMachineBtnOk.DoDoIt(const aCtx: TtfwContext); var l_aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine; begin try l_aen_TurnOffTimeMachine := Ten_TurnOffTimeMachine(aCtx.rEngine.PopObjAs(Ten_TurnOffTimeMachine)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(btnOk(aCtx, l_aen_TurnOffTimeMachine)); end;//TkwEnTurnOffTimeMachineBtnOk.DoDoIt function TkwEnTurnOffTimeMachineBtnCancel.btnCancel(const aCtx: TtfwContext; aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine): TvtButton; {* Реализация слова скрипта .Ten_TurnOffTimeMachine.btnCancel } begin Result := aen_TurnOffTimeMachine.btnCancel; end;//TkwEnTurnOffTimeMachineBtnCancel.btnCancel class function TkwEnTurnOffTimeMachineBtnCancel.GetWordNameForRegister: AnsiString; begin Result := '.Ten_TurnOffTimeMachine.btnCancel'; end;//TkwEnTurnOffTimeMachineBtnCancel.GetWordNameForRegister function TkwEnTurnOffTimeMachineBtnCancel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtButton); end;//TkwEnTurnOffTimeMachineBtnCancel.GetResultTypeInfo function TkwEnTurnOffTimeMachineBtnCancel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnTurnOffTimeMachineBtnCancel.GetAllParamsCount function TkwEnTurnOffTimeMachineBtnCancel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_TurnOffTimeMachine)]); end;//TkwEnTurnOffTimeMachineBtnCancel.ParamsTypes procedure TkwEnTurnOffTimeMachineBtnCancel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству btnCancel', aCtx); end;//TkwEnTurnOffTimeMachineBtnCancel.SetValuePrim procedure TkwEnTurnOffTimeMachineBtnCancel.DoDoIt(const aCtx: TtfwContext); var l_aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine; begin try l_aen_TurnOffTimeMachine := Ten_TurnOffTimeMachine(aCtx.rEngine.PopObjAs(Ten_TurnOffTimeMachine)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_TurnOffTimeMachine: Ten_TurnOffTimeMachine : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(btnCancel(aCtx, l_aen_TurnOffTimeMachine)); end;//TkwEnTurnOffTimeMachineBtnCancel.DoDoIt initialization Tkw_Form_TurnOffTimeMachine.RegisterInEngine; {* Регистрация Tkw_Form_TurnOffTimeMachine } Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate } Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate_Push.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_rb_totmChangeDate_Push } Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction } Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction_Push.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_rb_totmStayInCurrentRedaction_Push } Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction } Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction_Push.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_rb_totmGotoActualRedaction_Push } Tkw_TurnOffTimeMachine_Control_deChangeDate.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_deChangeDate } Tkw_TurnOffTimeMachine_Control_deChangeDate_Push.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_deChangeDate_Push } Tkw_TurnOffTimeMachine_Control_pbDialogIcon.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_pbDialogIcon } Tkw_TurnOffTimeMachine_Control_pbDialogIcon_Push.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_pbDialogIcon_Push } Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo } Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo_Push.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_lblTurnOnTimeMachineInfo_Push } Tkw_TurnOffTimeMachine_Control_btnOk.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_btnOk } Tkw_TurnOffTimeMachine_Control_btnOk_Push.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_btnOk_Push } Tkw_TurnOffTimeMachine_Control_btnCancel.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_btnCancel } Tkw_TurnOffTimeMachine_Control_btnCancel_Push.RegisterInEngine; {* Регистрация Tkw_TurnOffTimeMachine_Control_btnCancel_Push } TkwEnTurnOffTimeMachineRbTotmChangeDate.RegisterInEngine; {* Регистрация en_TurnOffTimeMachine_rb_totmChangeDate } TkwEnTurnOffTimeMachineRbTotmStayInCurrentRedaction.RegisterInEngine; {* Регистрация en_TurnOffTimeMachine_rb_totmStayInCurrentRedaction } TkwEnTurnOffTimeMachineRbTotmGotoActualRedaction.RegisterInEngine; {* Регистрация en_TurnOffTimeMachine_rb_totmGotoActualRedaction } TkwEnTurnOffTimeMachineDeChangeDate.RegisterInEngine; {* Регистрация en_TurnOffTimeMachine_deChangeDate } TkwEnTurnOffTimeMachinePbDialogIcon.RegisterInEngine; {* Регистрация en_TurnOffTimeMachine_pbDialogIcon } TkwEnTurnOffTimeMachineLblTurnOnTimeMachineInfo.RegisterInEngine; {* Регистрация en_TurnOffTimeMachine_lblTurnOnTimeMachineInfo } TkwEnTurnOffTimeMachineBtnOk.RegisterInEngine; {* Регистрация en_TurnOffTimeMachine_btnOk } TkwEnTurnOffTimeMachineBtnCancel.RegisterInEngine; {* Регистрация en_TurnOffTimeMachine_btnCancel } TtfwTypeRegistrator.RegisterType(TypeInfo(Ten_TurnOffTimeMachine)); {* Регистрация типа Ten_TurnOffTimeMachine } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtRadioButton)); {* Регистрация типа TvtRadioButton } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtDblClickDateEdit)); {* Регистрация типа TvtDblClickDateEdit } TtfwTypeRegistrator.RegisterType(TypeInfo(TPaintBox)); {* Регистрация типа TPaintBox } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLabel)); {* Регистрация типа TvtLabel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtButton)); {* Регистрация типа TvtButton } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
// ************************************************************************************************** // // Unit uSynEditPopupEdit // unit for the Delphi Preview Handler https://github.com/RRUZ/delphi-preview-handler // // 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 uSynEditPopupEdit.pas. // // The Initial Developer of the Original Code is Rodrigo Ruz V. // Portions created by Rodrigo Ruz V. are Copyright (C) 2011-2023 Rodrigo Ruz V. // All Rights Reserved. // // ************************************************************************************************* unit uSynEditPopupEdit; interface uses ActnList, Menus, Classes, SynEdit; type TSynEdit = class(SynEdit.TSynEdit) private FActnList: TActionList; FPopupMenu: TPopupMenu; procedure CreateActns; procedure FillPopupMenu(APopupMenu: TPopupMenu); procedure CutExecute(Sender: TObject); procedure CutUpdate(Sender: TObject); procedure CopyExecute(Sender: TObject); procedure CopyUpdate(Sender: TObject); procedure PasteExecute(Sender: TObject); procedure PasteUpdate(Sender: TObject); procedure DeleteExecute(Sender: TObject); procedure DeleteUpdate(Sender: TObject); procedure SelectAllExecute(Sender: TObject); procedure SelectAllUpdate(Sender: TObject); procedure RedoExecute(Sender: TObject); procedure RedoUpdate(Sender: TObject); procedure UndoExecute(Sender: TObject); procedure UndoUpdate(Sender: TObject); procedure SetPopupMenu_(const Value: TPopupMenu); function GetPopupMenu_: TPopupMenu; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property PopupMenu: TPopupMenu read GetPopupMenu_ write SetPopupMenu_; end; implementation uses System.Actions, System.SysUtils; const MenuName = 'uSynEditPopupMenu'; procedure TSynEdit.CopyExecute(Sender: TObject); begin Self.CopyToClipboard; end; procedure TSynEdit.CopyUpdate(Sender: TObject); begin TAction(Sender).Enabled := Self.SelAvail; end; procedure TSynEdit.CutExecute(Sender: TObject); begin Self.CutToClipboard; end; procedure TSynEdit.CutUpdate(Sender: TObject); begin TAction(Sender).Enabled := Self.SelAvail and not Self.ReadOnly; end; procedure TSynEdit.DeleteExecute(Sender: TObject); begin Self.SelText := ''; end; procedure TSynEdit.DeleteUpdate(Sender: TObject); begin TAction(Sender).Enabled := Self.SelAvail and not Self.ReadOnly; end; procedure TSynEdit.PasteExecute(Sender: TObject); begin Self.PasteFromClipboard; end; procedure TSynEdit.PasteUpdate(Sender: TObject); begin TAction(Sender).Enabled := Self.CanPaste; end; procedure TSynEdit.RedoExecute(Sender: TObject); begin Self.Redo; end; procedure TSynEdit.RedoUpdate(Sender: TObject); begin TAction(Sender).Enabled := Self.CanRedo; end; procedure TSynEdit.SelectAllExecute(Sender: TObject); begin Self.SelectAll; end; procedure TSynEdit.SelectAllUpdate(Sender: TObject); begin TAction(Sender).Enabled := Self.Lines.Text <> ''; end; procedure TSynEdit.UndoExecute(Sender: TObject); begin Self.Undo; end; procedure TSynEdit.UndoUpdate(Sender: TObject); begin TAction(Sender).Enabled := Self.CanUndo; end; constructor TSynEdit.Create(AOwner: TComponent); begin inherited; FActnList := TActionList.Create(Self); FPopupMenu := TPopupMenu.Create(Self); FPopupMenu.Name := MenuName; CreateActns; FillPopupMenu(FPopupMenu); PopupMenu := FPopupMenu; end; procedure TSynEdit.CreateActns; procedure AddActItem(const AText: string; AShortCut: TShortCut; AEnabled: Boolean; OnExecute, OnUpdate: TNotifyEvent); Var ActionItem: TAction; begin ActionItem := TAction.Create(FActnList); ActionItem.ActionList := FActnList; ActionItem.Caption := AText; ActionItem.ShortCut := AShortCut; ActionItem.Enabled := AEnabled; ActionItem.OnExecute := OnExecute; ActionItem.OnUpdate := OnUpdate; end; begin AddActItem('&Undo', Menus.ShortCut(Word('Z'), [ssCtrl]), False, UndoExecute, UndoUpdate); AddActItem('&Redo', Menus.ShortCut(Word('Z'), [ssCtrl, ssShift]), False, RedoExecute, RedoUpdate); AddActItem('-', 0, False, nil, nil); AddActItem('Cu&t', Menus.ShortCut(Word('X'), [ssCtrl]), False, CutExecute, CutUpdate); AddActItem('&Copy', Menus.ShortCut(Word('C'), [ssCtrl]), False, CopyExecute, CopyUpdate); AddActItem('&Paste', Menus.ShortCut(Word('V'), [ssCtrl]), False, PasteExecute, PasteUpdate); AddActItem('De&lete', 0, False, DeleteExecute, DeleteUpdate); AddActItem('-', 0, False, nil, nil); AddActItem('Select &All', Menus.ShortCut(Word('A'), [ssCtrl]), False, SelectAllExecute, SelectAllUpdate); AddActItem('-', 0, False, nil, nil); //AddActItem('&Selection Mode', 0, False, UndoExecute, UndoUpdate); end; procedure TSynEdit.SetPopupMenu_(const Value: TPopupMenu); Var MenuItem: TMenuItem; begin SynEdit.TSynEdit(Self).PopupMenu := Value; if CompareText(MenuName, Value.Name) <> 0 then begin MenuItem := TMenuItem.Create(Value); MenuItem.Caption := '-'; Value.Items.Add(MenuItem); FillPopupMenu(Value); end; end; function TSynEdit.GetPopupMenu_: TPopupMenu; begin Result := SynEdit.TSynEdit(Self).PopupMenu; end; destructor TSynEdit.Destroy; begin FPopupMenu.Free; FActnList.Free; inherited; end; procedure TSynEdit.FillPopupMenu(APopupMenu: TPopupMenu); var i: integer; MenuItem: TMenuItem; begin if Assigned(FActnList) then for i := 0 to FActnList.ActionCount - 1 do begin MenuItem := TMenuItem.Create(APopupMenu); MenuItem.Action := FActnList.Actions[i]; APopupMenu.Items.Add(MenuItem); end; end; end.
(* Copyright (c) 1998-2004 by HiComponents. All rights reserved. This software comes without any warranty either implied or expressed. In no case shall the author be liable for any damage or unwanted behavior of any computer hardware and/or software. HiComponents grants you the right to include the compiled component in your application, whether COMMERCIAL, SHAREWARE, or FREEWARE, BUT YOU MAY NOT DISTRIBUTE THIS SOURCE CODE OR ITS COMPILED .DCU IN ANY FORM. ImageEn may not be included in any commercial, shareware or freeware DELPHI libraries or components. email: support@hicomponents.com http://www.hicomponents.com *) unit hvideocap; {$R-} {$Q-} {$I ie.inc} {$ifdef IEINCLUDEVIDEOCAPTURE} interface uses Windows, Messages, SysUtils, StdCtrls, Classes, Graphics, Controls, Forms, ImageEnView, ImageEnProc, hyiedefs, videocap, ieview, hyieutils; const VH_FRAMEMESSAGE=WM_USER+5000; VH_DESTROYWINDOW=WM_USER+5001; type //TcapVideoStreamCallback = function(hWnd:HWND; lpVHdr:PVIDEOHDR):LRESULT; stdcall; TImageEnVideoCap = class(TComponent) private fCapture:boolean; // se true inizia cattura fWndC:HWND; // Handle finestra Video Capture (0=da creare) fDrivers:TStringList; // driver disponibili fVideoSource:integer; // indice video source corrente fCallBackFrame:boolean; // Se True chiama attiva la callback CallBackFrameFunc fOnVideoFrame:TVideoFrameEvent; fOnVideoFrameRaw:TVideoFrameRawEvent; fhBitmapInfo:THandle; // Handle della Bitmapinfo riempita da FillBitmapInfo fBitmapInfoUp:boolean; // true se fhBitmapInfo è aggiornata (serve a FillBitmapInfo) fConnected:boolean; // true se connesso al driver fOnJob:TIEJobEvent; fHDrawDib:HDRAWDIB; fBitmap:TIEDibBitmap; fPix:pointer; fDone:boolean; fDriverBusy:boolean; fEnding:boolean; fUseWindowsCodec:boolean; // per registrazione fRecFileName:string; // nome file destinazione fRecFrameRate:integer; // frames per secondo (dwRequestMicroSecPerFrame) fRecAudio:boolean; // true cattura audio (fCaptureAudio) fRecMultitask:boolean; // false disabilita multitasking (fYeld) [ESC=abort] fRecording:boolean; // true se in registrazione fWinHandle:HWND; protected procedure SetCapture(v:boolean); procedure DriverConnect; function DriverConnectNE:boolean; procedure DriverDisconnect; procedure FillDrivers; procedure SetVideoSource(v:integer); function GetHasDlgVideoSource:boolean; function GetHasDlgVideoFormat:boolean; function GetHasDlgVideoDisplay:boolean; function GetHasOverlay:boolean; procedure GetCaps(var fDriverCaps:TCAPDRIVERCAPS); procedure SetCallBackFrame(v:boolean); procedure SetOnVideoFrame(v:TVideoFrameEvent); procedure SetOnVideoFrameRaw(v:TVideoFrameRawEvent); function FillBitmapInfo:boolean; procedure CreateCaptureWindow; procedure DestroyCaptureWindow; procedure DoJob(job:TIEJob; per:integer); procedure AllocateWindow; function GetAudioFormat:word; procedure SetAudioFormat(v:word); function GetAudioChannels:word; procedure SetAudioChannels(v:word); function GetAudioSamplesPerSec:dword; procedure SetAudioSamplesPerSec(v:dword); function GetAudioBitsPerSample:word; procedure SetAudioBitsPerSample(v:word); procedure GetWaveFormat(var wf:TWAVEFORMATEX); procedure SetWaveFormat(var wf:TWAVEFORMATEX); public constructor Create(Owner: TComponent); override; destructor Destroy; override; property Capture:boolean read fCapture write SetCapture default false; function DoConfigureSource:boolean; function DoConfigureFormat:boolean; function DoConfigureDisplay:boolean; function DoConfigureCompression:boolean; property VideoSourceList:TStringList read fDrivers; property HasOverlay:boolean read GetHasOverlay; property HasDlgVideoSource:boolean read GetHasDlgVideoSource; property HasDlgVideoFormat:boolean read GetHasDlgVideoFormat; property HasDlgVideoDisplay:boolean read GetHasDlgVideoDisplay; procedure StartRecord; procedure StopRecord; property RecFileName:string read fRecFileName write fRecFileName; property RecFrameRate:integer read fRecFrameRate write fRecFrameRate; property RecAudio:boolean read fRecAudio write fRecAudio; property RecMultitask:boolean read fRecMultitask write fRecMultitask; property WndCaptureHandle:HWND read fWndC; property AudioFormat:word read GetAudioFormat write SetAudioFormat; property AudioChannels:word read GetAudioChannels write SetAudioChannels; property AudioSamplesPerSec:dword read GetAudioSamplesPerSec write SetAudioSamplesPerSec; property AudioBitsPerSample:word read GetAudioBitsPerSample write SetAudioBitsPerSample; // Formato video function GetVideoSize:TRect; property UseWindowsCodec:boolean read fUseWindowsCodec write fUseWindowsCodec; published property VideoSource:integer read fVideoSource write SetVideoSource default 0; property OnVideoFrame:TVideoFrameEvent read fOnVideoFrame write SetOnVideoFrame; property OnVideoFrameRaw:TVideoFrameRawEvent read fOnVideoFrameRaw write SetOnVideoFrameRaw; property OnJob:TIEJobEvent read fOnJob write fOnJob; end; implementation {$R-} const DLL2 = 'AVICAP32.DLL'; // VIDEOCAP CONSTS WM_CAP_START = WM_USER; WM_CAP_GET_STATUS = WM_CAP_START + 54; WM_CAP_SET_CALLBACK_STATUS = WM_CAP_START + 3; WM_CAP_DRIVER_CONNECT = WM_CAP_START + 10; WM_CAP_SEQUENCE = WM_CAP_START + 62; WM_CAP_STOP = WM_CAP_START + 69; WM_CAP_ABORT = WM_CAP_START + 68; WM_CAP_FILE_SET_CAPTURE_FILE = WM_CAP_START + 20; WM_CAP_SETPREVIEW = WM_CAP_START + 50; WM_CAP_SETPREVIEWRATE = WM_CAP_START + 52; WM_CAP_SETOVERLAY = WM_CAP_START + 51; WM_CAP_SET_SCALE = WM_CAP_START + 53; WM_CAP_DRIVER_DISCONNECT = WM_CAP_START + 11; WM_CAP_GRAB_FRAME = WM_CAP_START + 60; WM_CAP_SET_CALLBACK_FRAME = WM_CAP_START + 5; WM_CAP_DLG_VIDEOFORMAT = WM_CAP_START + 41; WM_CAP_DLG_VIDEOSOURCE = WM_CAP_START + 42; WM_CAP_DLG_VIDEODISPLAY = WM_CAP_START + 43; WM_CAP_DRIVER_GET_CAPS = WM_CAP_START + 14; WM_CAP_GET_VIDEOFORMAT = WM_CAP_START + 44; WM_CAP_SET_VIDEOFORMAT = WM_CAP_START + 45; WM_CAP_DRIVER_GET_NAME = WM_CAP_START + 12; WM_CAP_SET_SEQUENCE_SETUP = WM_CAP_START + 64; WM_CAP_GET_SEQUENCE_SETUP = WM_CAP_START + 65; WM_CAP_DLG_VIDEOCOMPRESSION = WM_CAP_START + 46; WM_CAP_FILE_SAVEDIB = WM_CAP_START+ 25; WM_CAP_EDIT_COPY = WM_CAP_START+ 30; WM_CAP_SET_USER_DATA = WM_CAP_START+ 9; WM_CAP_GET_USER_DATA = WM_CAP_START+ 8; WM_CAP_SEQUENCE_NOFILE = WM_CAP_START+ 63; WM_CAP_SET_CALLBACK_VIDEOSTREAM = WM_CAP_START+ 6; WM_CAP_SET_CALLBACK_YIELD = WM_CAP_START+ 4; WM_CAP_SET_CALLBACK_ERROR = WM_CAP_START+ 2; WM_CAP_SET_AUDIOFORMAT = WM_CAP_START+ 35; WM_CAP_GET_AUDIOFORMAT = WM_CAP_START+ 36; IDS_CAP_BEGIN = 300; // "Capture Start" */ IDS_CAP_END = 301; // "Capture End" */ // AVICAP function capCreateCaptureWindowA(lpszWindowName:PAnsiChar; dwStyle:dword; x,y,nWidth,nHeight:integer; hwndParent:HWND; nID:integer):HWND; stdcall; external DLL2; function capGetDriverDescriptionA(wDriverIndex:integer; lpszName:PAnsiChar; cnName:integer; lpszVer:PAnsiChar; cbVer:integer):longbool; stdcall; external DLL2; function CallBackFrameFunc(hWnd:HWND; lpVHdr:PVIDEOHDR):LRESULT; stdcall; forward; function CallBackYeldFunc(hWnd:HWND):LRESULT; stdcall; forward; function CallBackStatusFunc(hWnd:HWND; nID:integer; lpsz:PAnsiChar):LRESULT; stdcall; forward; function capErrorCallback(hWnd:HWND; nID:integer; lpsz:PAnsiChar):LRESULT; stdcall; forward; ///////////////////////////////////////////////////////////////////////////////////// constructor TImageEnVideoCap.Create(Owner: TComponent); begin inherited Create(Owner); // fUseWindowsCodec:=true; fEnding:=false; fCallBackFrame:=false; fDrivers:=TStringList.Create; fVideoSource:=0; FillDrivers; fWndC:=0; fCapture:=false; fOnVideoFrame:=nil; fhBitmapInfo:=GlobalAlloc(GHND,sizeof(TBITMAPINFO)+sizeof(TRGBQUAD)*256); fConnected:=false; fBitmapInfoUp:=false; fRecFileName:='Capture.avi'; fRecFrameRate:=15; // 15 frames per second (dwRequestMicroSecPerFrame=66667) fRecAudio:=false; fRecMultitask:=true; fRecording:=false; fOnJob:=nil; fHDrawDib:=IEDrawDibOpen; fBitmap:=TIEDibBitmap.create; fPix:=nil; fDone:=true; fDriverBusy:=false; AllocateWindow; end; ///////////////////////////////////////////////////////////////////////////////////// destructor TImageEnVideoCap.Destroy; begin if fCapture then SetCapture(false); // qui richiama anche SetDisplayMode fDrivers.free; DestroyCaptureWindow; GlobalFree(fhBitmapInfo); IEDrawDibClose(fHDrawDib); fBitmap.free; PostMessage(fWinHandle, VH_DESTROYWINDOW, 0, 0); if fPix<>nil then freemem(fPix); // inherited; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.FillDrivers; var DeviceName:array [0..79] of char; DeviceVersion:array [0..79] of char; q:integer; begin fDrivers.Clear; for q:=0 to 9 do if capGetDriverDescriptionA(q,DeviceName,80,DeviceVersion,80) then fDrivers.Add(string(DeviceName)+' '+string(DeviceVersion)); end; ///////////////////////////////////////////////////////////////////////////////////// // - Se il driver è occupato genera l'eccezione TVideoCapException. procedure TImageEnVideoCap.SetCapture(v:boolean); var cp:TCAPTUREPARMS; begin if fWndC=0 then CreateCaptureWindow; if v then begin // START VIDEO INPUT fEnding:=false; fCapture:=true; if fWndC<>0 then begin if not fConnected then DriverConnect; SendMessage(fWndC,WM_CAP_SET_SCALE,1,0); SendMessage(fWndC,WM_CAP_SET_USER_DATA,0,integer(pointer(self))); // SendMessage(fWndC,WM_CAP_GET_SEQUENCE_SETUP,sizeof(cp),integer(@cp)); cp.fAbortLeftMouse:=false; cp.fAbortRightMouse:=false; cp.fLimitEnabled:=false; cp.dwRequestMicroSecPerFrame:=round( (1/fRecFrameRate)*1000000 ); cp.wPercentDropForError:=100; if fRecording then begin cp.fYield:=fRecMultitask; cp.fCaptureAudio:=fRecAudio; SendMessage(fWndC,WM_CAP_SET_SEQUENCE_SETUP,sizeof(cp),integer(@cp)); if SendMessage(fWndC,WM_CAP_FILE_SET_CAPTURE_FILE,0,integer(PAnsiChar(fRecFileName)))=0 then raise TVideoCapException.Create('Unable to create AVI file'); SetCallBackFrame(fCallBackFrame); if SendMessage(fWndC,WM_CAP_SEQUENCE,0,0)=0 then raise TVideoCapException.Create('Unable to start video recording'); end else begin cp.fYield:=true; cp.fCaptureAudio:=false; //cp.wNumVideoRequested:=120; //cp.fStepCaptureAt2x:=true; SendMessage(fWndC,WM_CAP_SET_SEQUENCE_SETUP,sizeof(cp),integer(@cp)); SetCallBackFrame(fCallBackFrame); SendMessage(fWndC,WM_CAP_SEQUENCE_NOFILE,0,0); end; end; end else begin // STOP VIDEO INPUT fEnding:=true; SendMessage(fWndC,WM_CAP_STOP,0,0); SendMessage(fWndC,WM_CAP_SET_USER_DATA,0,0); DriverDisconnect; fCapture:=false; DestroyCaptureWindow; end; end; ///////////////////////////////////////////////////////////////////////////////////// // Assegna fWndC // nota: prima di chiamare questa funzione assicurarsi che fWndC sia ZERO procedure TImageEnVideoCap.CreateCaptureWindow; begin fWndC:=capCreateCaptureWindowA(PAnsiChar(name),WS_CHILD,0,0,50,50,IEFindHandle(self),0); //if fCapture then // SetCapture(true); // qui richiama anche SetDisplayMode end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.DestroyCaptureWindow; begin if fWndC<>0 then begin SendMessage(fWndC,WM_CAP_SET_USER_DATA,0,0); DestroyWindow(fWndC); fWndC:=0; end; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.DriverDisconnect; begin SendMessage(fWndC,WM_CAP_DRIVER_DISCONNECT,0,0); fConnected:=false; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.SetVideoSource(v:integer); begin fVideoSource:=v; if fCapture then begin SetCapture(false); SetCapture(true); end; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.DriverConnect; begin if fWndC=0 then CreateCaptureWindow; DoJob(iejVIDEOCAP_CONNECTING,0); if SendMessage(fWndC,WM_CAP_DRIVER_CONNECT,fVideoSource,0)=0 then raise TVideoCapException.Create('Unable to open video capture driver'); fConnected:=true; fBitmapInfoUp:=false; FillBitmapInfo; DoJob(iejNOTHING,0); end; ///////////////////////////////////////////////////////////////////////////////////// // Come DriverConnect, ma rest. false se la connessione fallisce function TImageEnVideoCap.DriverConnectNE:boolean; begin if fWndC=0 then CreateCaptureWindow; result:=SendMessage(fWndC,WM_CAP_DRIVER_CONNECT,fVideoSource,0)<>0; fConnected:=result; end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.GetHasDlgVideoSource:boolean; var fDriverCaps:TCAPDRIVERCAPS; begin GetCaps(fDriverCaps); result:=fDriverCaps.fHasDlgVideoSource; end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.GetHasDlgVideoFormat:boolean; var fDriverCaps:TCAPDRIVERCAPS; begin GetCaps(fDriverCaps); result:=fDriverCaps.fHasDlgVideoFormat; end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.GetHasDlgVideoDisplay:boolean; var fDriverCaps:TCAPDRIVERCAPS; begin GetCaps(fDriverCaps); result:=fDriverCaps.fHasDlgVideoDisplay; end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.GetHasOverlay:boolean; var fDriverCaps:TCAPDRIVERCAPS; begin GetCaps(fDriverCaps); result:=fDriverCaps.fHasOverlay; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.GetCaps(var fDriverCaps:TCAPDRIVERCAPS); var lcon:boolean; begin lcon:=fConnected; if not fConnected then DriverConnect; SendMessage(fWndC,WM_CAP_DRIVER_GET_CAPS,sizeof(TCAPDRIVERCAPS),integer(@fDriverCaps)); if not lcon then DriverDisconnect; end; ///////////////////////////////////////////////////////////////////////////////////// // Se ci sono errori genera l'eccezione TVideoCapException procedure TImageEnVideoCap.StartRecord; (* var cp:TCAPTUREPARMS; begin fEnding:=false; if fRecording then exit; SendMessage(fWndC,WM_CAP_GET_SEQUENCE_SETUP,sizeof(cp),integer(@cp)); cp.fYield:=fRecMultitask; cp.fCaptureAudio:=fRecAudio; cp.fAbortLeftMouse:=false; cp.fAbortRightMouse:=false; cp.dwRequestMicroSecPerFrame:=round( (1/fRecFrameRate)*1000000 ); SendMessage(fWndC,WM_CAP_SET_SEQUENCE_SETUP,sizeof(cp),integer(@cp)); if SendMessage(fWndC,WM_CAP_FILE_SET_CAPTURE_FILE,0,integer(PAnsiChar(fRecFileName)))=0 then raise TVideoCapException.Create('Unable to create AVI file'); if SendMessage(fWndC,WM_CAP_SEQUENCE,0,0)=0 then raise TVideoCapException.Create('Unable to start video recording'); fRecording:=true; end; *) begin fRecording:=true; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.StopRecord; begin fRecording:=false; end; (* begin fEnding:=true; if not fRecording then exit; SendMessage(fWndC,WM_CAP_STOP,0,0); fRecording:=false; end; *) ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.DoConfigureSource:boolean; var lcon:boolean; begin lcon:=fConnected; result:=fConnected; if not fConnected then result:=DriverConnectNE; if result then begin result:=SendMessage(fWndC,WM_CAP_DLG_VIDEOSOURCE,0,0)<>0; fBitmapInfoUp:=false; FillBitmapInfo; if not lcon then DriverDisconnect end; end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.DoConfigureFormat:boolean; var lcon:boolean; begin lcon:=fConnected; result:=fConnected; if not fConnected then result:=DriverConnectNE; if result then begin result:=SendMessage(fWndC,WM_CAP_DLG_VIDEOFORMAT,0,0)<>0; fBitmapInfoUp:=false; FillBitmapInfo; if not lcon then DriverDisconnect end; end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.DoConfigureDisplay:boolean; var lcon:boolean; begin lcon:=fConnected; result:=fConnected; if not fConnected then result:=DriverConnectNE; if result then begin result:=SendMessage(fWndC,WM_CAP_DLG_VIDEODISPLAY,0,0)<>0; fBitmapInfoUp:=false; FillBitmapInfo; if not lcon then DriverDisconnect end; end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.FillBitmapInfo:boolean; var sz:integer; pt:PBITMAPINFO; lcon:boolean; begin if not fBitmapInfoUp then begin lcon:=fConnected; result:=fConnected; if not fConnected then result:=DriverConnectNE; if result then begin GlobalFree(fhBitmapInfo); sz:=SendMessage(fWndC,WM_CAP_GET_VIDEOFORMAT,0,0); // get size fhBitmapInfo:=GlobalAlloc(GHND,IMAX(sizeof(TBITMAPINFO)+sizeof(TRGBQUAD)*256,sz)); pt:=GlobalLock(fhBitmapInfo); SendMessage(fWndC,WM_CAP_GET_VIDEOFORMAT,sz,integer(pt)); if pt^.bmiHeader.biBitCount=1 then fBitmap.AllocateBits(pt^.bmiHeader.biWidth,pt^.bmiHeader.biHeight,1) else fBitmap.AllocateBits(pt^.bmiHeader.biWidth,pt^.bmiHeader.biHeight,24); if fPix<>nil then freemem(fPix); getmem(fPix,pt^.bmiHeader.biSizeImage); GlobalUnLock(fhBitmapInfo); if not lcon then DriverDisconnect; end; fBitmapInfoUp:=true; end else result:=true; end; ///////////////////////////////////////////////////////////////////////////////////// // Rest. dimensioni dell'input video function TImageEnVideoCap.GetVideoSize:TRect; var pt:PBITMAPINFO; begin if fWndC=0 then CreateCaptureWindow; FillBitmapInfo; with result do begin Left:=0; Top:=0; pt:=GlobalLock(fhBitmapInfo); Right:=pt^.bmiHeader.biWidth-1; Bottom:=pt^.bmiHeader.biHeight-1; GlobalUnLock(fhBitmapInfo); end; end; ///////////////////////////////////////////////////////////////////////////////////// // Attiva/disattiva chiamata funzione CallBackFrameFunc() procedure TImageEnVideoCap.SetCallBackFrame(v:boolean); begin fCallBackFrame:=v; if fConnected then begin // attiva/disattiva "al volo" if v then begin SendMessage(fWndC,WM_CAP_SET_CALLBACK_VIDEOSTREAM,0,integer(@CallBackFrameFunc)); SendMessage(fWndC,WM_CAP_SET_CALLBACK_ERROR,0,integer(@capErrorCallback)); SendMessage(fWndC,WM_CAP_SET_CALLBACK_YIELD,0,integer(@CallBackYeldFunc)); SendMessage(fWndC,WM_CAP_SET_CALLBACK_STATUS,0,integer(@CallBackStatusFunc)); end else begin SendMessage(fWndC,WM_CAP_SET_CALLBACK_VIDEOSTREAM,0,0); SendMessage(fWndC,WM_CAP_SET_CALLBACK_ERROR,0,0); SendMessage(fWndC,WM_CAP_SET_CALLBACK_YIELD,0,0); SendMessage(fWndC,WM_CAP_SET_CALLBACK_STATUS,0,0); end; end; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.SetOnVideoFrame(v:TVideoFrameEvent); begin fOnVideoFrame:=v; SetCallBackFrame( assigned(fOnVideoFrame) or assigned(fOnVideoFrameRaw) ); end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.SetOnVideoFrameRaw(v:TVideoFrameRawEvent); begin fOnVideoFrameRaw:=v; SetCallBackFrame( assigned(fOnVideoFrame) or assigned(fOnVideoFrameRaw) ); end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.DoConfigureCompression:boolean; var lcon:boolean; begin lcon:=fConnected; result:=fConnected; if not fConnected then result:=DriverConnectNE; if result then begin result:=SendMessage(fWndC,WM_CAP_DLG_VIDEOCOMPRESSION,0,0)<>0; fBitmapInfoUp:=false; FillBitmapInfo; if not lcon then DriverDisconnect end; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.DoJob(job:TIEJob; per:integer); begin if assigned(fOnJob) then fOnJob(self,job,per); end; ///////////////////////////////////////////////////////////////////////////////////// // Funzione callback frame (* /* dwFlags field of VIDEOHDR */ #define VHDR_DONE 0x00000001 /* Done bit */ #define VHDR_PREPARED 0x00000002 /* Set if this header has been prepared */ #define VHDR_INQUEUE 0x00000004 /* Reserved for driver */ #define VHDR_KEYFRAME 0x00000008 /* Key Frame */ *) function CallBackFrameFunc(hWnd:HWND; lpVHdr:PVIDEOHDR):LRESULT; var pobj:pointer; obj:TImageEnVideoCap; {$ifdef IEDELPHI3} i:integer; {$else} {$ifdef IECPPBUILDER3} i:integer; {$else} i:cardinal; {$endif} {$endif} begin result:=0; if (lpVHdr^.dwFlags and 1=0) or (lpVHdr^.dwFlags and 2=0) then exit; if SendMessageTimeOut(hWnd,WM_CAP_GET_USER_DATA,0,0,SMTO_ABORTIFHUNG or SMTO_BLOCK,100,i)<>0 then begin pobj:=pointer(i); if assigned(pobj) then begin obj:=pobj; if (obj.fDone) and (not obj.fEnding) then begin obj.fDone:=false; copymemory(obj.fpix,lpVHdr^.lpData,lpVHdr^.dwBufferLength); PostMessage(obj.fWinHandle,VH_FRAMEMESSAGE,0,cardinal(pobj)); end; end; end; end; function capErrorCallback(hWnd:HWND; nID:integer; lpsz:PAnsiChar):LRESULT; begin result:=0; end; function CallBackYeldFunc(hWnd:HWND):LRESULT; begin result:=1; end; function CallBackStatusFunc(hWnd:HWND; nID:integer; lpsz:PAnsiChar):LRESULT; var pobj:pointer; obj:TImageEnVideoCap; {$ifdef IEDELPHI3} i:integer; {$else} {$ifdef IECPPBUILDER3} i:integer; {$else} i:cardinal; {$endif} {$endif} begin if SendMessageTimeOut(hWnd,WM_CAP_GET_USER_DATA,0,0,SMTO_ABORTIFHUNG or SMTO_BLOCK,100,i)<>0 then begin pobj:=pointer(i); if assigned(pobj) then begin obj:=pobj; case nID of IDS_CAP_BEGIN: obj.fDriverBusy:=true; IDS_CAP_END: obj.fDriverBusy:=false; end; end; end; result:=0; end; function VideoCapWndProc(Window: HWND; Message, wParam, lParam: Longint): Longint; stdcall; var pbi:PBITMAPINFOHEADER; obj:TImageEnVideoCap; begin case Message of VH_FRAMEMESSAGE: begin obj:=TImageEnVideoCap(lParam); with obj do begin if assigned(fOnVideoFrame) and (not fEnding) then begin pbi:=GlobalLock(fhBitmapInfo); if fUseWindowsCodec then IEDrawDibDraw(fHDrawDib,fBitmap.HDC,0,0,pbi^.biWidth,pbi^.biHeight,pbi^,fPix,0,0,pbi^.biWidth,pbi^.biHeight,0) else _CopyDIB2BitmapEx(integer(pbi),fBitmap,fPix,false); GlobalUnLock(fhBitmapInfo); fOnVideoFrame(obj,fBitmap); end; if assigned(fOnVideoFrameRaw) and (not fEnding) then fOnVideoFrameRaw(obj,fhBitmapInfo,fpix); fDone:=true; Result := 0; end; end; VH_DESTROYWINDOW: begin DestroyWindow(Window); Result := 0; end; else Result := DefWindowProc(Window, Message, wParam, lParam); end; end; var VideoCapWindowClass: TWndClass = ( style: 0; lpfnWndProc: @VideoCapWndProc; cbClsExtra: 0; cbWndExtra: 0; hInstance: 0; hIcon: 0; hCursor: 0; hbrBackground: 0; lpszMenuName: nil; lpszClassName: 'TVideoCapWindow'); procedure TImageEnVideoCap.AllocateWindow; var TempClass: TWndClass; ClassRegistered: Boolean; begin VideoCapWindowClass.hInstance := HInstance; ClassRegistered := GetClassInfo(HInstance, VideoCapWindowClass.lpszClassName,TempClass); if not ClassRegistered or (TempClass.lpfnWndProc <> @VideoCapWndProc) then begin if ClassRegistered then Windows.UnregisterClass(VideoCapWindowClass.lpszClassName, HInstance); Windows.RegisterClass(VideoCapWindowClass); end; fWinHandle:= CreateWindow(VideoCapWindowClass.lpszClassName, '', 0, 0, 0, 0, 0, 0, 0, HInstance, nil); end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.GetWaveFormat(var wf:TWAVEFORMATEX); var lcon:boolean; begin lcon:=fConnected; if not fConnected then DriverConnect; SendMessage(fWndC,WM_CAP_GET_AUDIOFORMAT,sizeof(TWAVEFORMATEX),integer(@wf)); if not lcon then DriverDisconnect; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.SetWaveFormat(var wf:TWAVEFORMATEX); var lcon:boolean; begin lcon:=fConnected; if not fConnected then DriverConnect; wf.nAvgBytesPerSec:=0; wf.cbSize:=0; SendMessage(fWndC,WM_CAP_SET_AUDIOFORMAT,sizeof(TWAVEFORMATEX),integer(@wf)); if not lcon then DriverDisconnect; end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.GetAudioFormat:word; var wf:TWAVEFORMATEX; begin GetWaveFormat(wf); result:=wf.wFormatTag end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.SetAudioFormat(v:word); var wf:TWAVEFORMATEX; begin GetWaveFormat(wf); wf.wFormatTag:=v; SetWaveFormat(wf); end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.GetAudioChannels:word; var wf:TWAVEFORMATEX; begin GetWaveFormat(wf); result:=wf.nChannels; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.SetAudioChannels(v:word); var wf:TWAVEFORMATEX; begin GetWaveFormat(wf); wf.nChannels:=v; SetWaveFormat(wf); end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.GetAudioSamplesPerSec:dword; var wf:TWAVEFORMATEX; begin GetWaveFormat(wf); result:=wf.nSamplesPerSec; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.SetAudioSamplesPerSec(v:dword); var wf:TWAVEFORMATEX; begin GetWaveFormat(wf); wf.nSamplesPerSec:=v; SetWaveFormat(wf); end; ///////////////////////////////////////////////////////////////////////////////////// function TImageEnVideoCap.GetAudioBitsPerSample:word; var wf:TWAVEFORMATEX; begin GetWaveFormat(wf); result:=wf.wBitsPerSample; end; ///////////////////////////////////////////////////////////////////////////////////// procedure TImageEnVideoCap.SetAudioBitsPerSample(v:word); var wf:TWAVEFORMATEX; begin GetWaveFormat(wf); wf.wBitsPerSample:=v; SetWaveFormat(wf); end; {$else} // {$ifdef IEINCLUDEVIDEOCAPTURE} interface implementation {$endif} end.
{ для работы с OPC используется OPCDAAuto.dll из комплекта "OPC DA Auto 2.02 Source Code 5.30.msi" установка: import component -> import a type library -> OPC DA Automation Wrapper 2.02 version 1.0 -> pallete page ActiveX -> install new package compile -> install unhide button ActiveX (TOPCGroups,TOPCGroup,TOPCActivator,TOPCServer) в uses добавить (OPCAutomation_TLB,OleServer) } unit thread_opc; interface uses SysUtils, Classes, Windows, ActiveX, OPCAutomation_TLB, OleServer, Forms, DateUtils, ZDataset; type TThreadOpc = class(TThread) private { Private declarations } protected procedure Execute; override; end; TIdHeat = Record Heat : string[26]; // плавка Grade : string[50]; // марка стали Section : string[50]; // профиль Standard : string[50]; // стандарт StrengthClass : string[50]; // клас прочности constructor Create(_Heat, _Grade, _Section, _Standard, _StrengthClass: string); end; var ThreadOpc: TThreadOpc; OPCServer: TOPCServer; OPCGroup1: TOPCGroup; OPCGroup: IOPCGroup; OPCTagArray: Array [1 .. 10] of OPCItem; OPCGroupName: string = 'QCRollingMill'; left, right: TIdHeat; // {$DEFINE DEBUG} procedure WrapperOpc; // обертка для синхронизации и выполнения с другим потоком function ConfigOPCServer(InData: bool): bool; function OPCReadTags: bool; function SqlWriteTemperature(InTemperature, InSide: integer; InCogging: bool): bool; function OPCWriteTags: bool; function SqlReadAlert(InTid, InSide: integer): OleVariant; implementation uses logging, settings, sql; procedure TThreadOpc.Execute; begin CoInitialize(nil); while True do begin Synchronize(WrapperOpc); sleep(1000); end; CoUninitialize; end; procedure WrapperOpc; begin try if not PConnect.Ping then PConnect.Reconnect; except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; try OPCReadTags; except on E: Exception do SaveLog('error'+#9#9+E.ClassName+', с сообщением: '+E.Message); end; try OPCWriteTags; except on E: Exception do SaveLog('error'+#9#9+E.ClassName+', с сообщением: '+E.Message); end; end; function ConfigOPCServer(InData: bool): bool; begin {$IFDEF DEBUG} SaveLog('debug' + #9#9 + 'OpcConfigServerName -> ' + OpcConfigArray[1]); {$ENDIF} if InData and (OpcConfigArray[1] <> '') then begin try OPCServer := TOPCServer.Create(nil); OPCGroup1 := TOPCGroup.Create(nil); OPCServer.Connect1(OpcConfigArray[1]); OPCGroup := OPCServer.OPCGroups.Add(OPCGroupName); OPCGroup.UpdateRate := 1000; OPCGroup.IsActive := True; OPCGroup.IsSubscribed := True; // создаем Tags OPCTagArray[1] := OPCGroup.OPCItems.AddItem(OpcConfigArray[2], 1); OPCTagArray[2] := OPCGroup.OPCItems.AddItem(OpcConfigArray[3], 2); OPCTagArray[3] := OPCGroup.OPCItems.AddItem(OpcConfigArray[4], 3); OPCTagArray[4] := OPCGroup.OPCItems.AddItem(OpcConfigArray[5], 4); OPCTagArray[5] := OPCGroup.OPCItems.AddItem(OpcConfigArray[6], 5); OPCTagArray[6] := OPCGroup.OPCItems.AddItem(OpcConfigArray[7], 6); OPCTagArray[7] := OPCGroup.OPCItems.AddItem(OpcConfigArray[8], 7); except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; end; if (InData = false) and (OpcConfigArray[1] <> '') then begin try OPCGroup.IsActive := false; OPCGroup.IsSubscribed := false; OPCServer.OPCGroups.Remove(OPCGroupName); OPCServer.Disconnect; except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; end; end; function OPCReadTags: bool; var Tags: Array [1 .. 4, 1 .. 4] of OleVariant; // read 4 values -> source,value,quality,timestamp begin try OPCTagArray[1].Read(Tags[1, 1], Tags[1, 2], Tags[1, 3], Tags[1, 4]); OPCTagArray[2].Read(Tags[2, 1], Tags[2, 2], Tags[1, 3], Tags[2, 4]); OPCTagArray[3].Read(Tags[3, 1], Tags[3, 2], Tags[3, 3], Tags[3, 4]); OPCTagArray[4].Read(Tags[4, 1], Tags[4, 2], Tags[4, 3], Tags[4, 4]); except on E: Exception do begin SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); ConfigOPCServer(false); ConfigOPCServer(true); end; end; {$IFDEF DEBUG} SaveLog('debug' + #9#9 + 'TempLeft -> ' + inttostr(Tags[1, 2])); SaveLog('debug' + #9#9 + 'TempRight -> ' + inttostr(Tags[2, 2])); SaveLog('debug' + #9#9 + 'CoggingLeft -> ' + booltostr(Tags[3, 2])); SaveLog('debug' + #9#9 + 'CoggingRight -> ' + booltostr(Tags[4, 2])); {$ENDIF} //left -> 0 try SqlWriteTemperature(Tags[1, 2], 0, Tags[3, 2]); except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; //right -> 1 try SqlWriteTemperature(Tags[2, 2], 1, Tags[4, 2]); except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; end; function OPCWriteTags: bool; type alert = record tid : integer; TagValue : OleVariant; end; var left, right: alert; begin try SQuery.Close; SQuery.SQL.Clear; SQuery.SQL.Add('SELECT * FROM settings'); SQuery.Open; except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; while not SQuery.Eof do begin if SQuery.FieldByName('name').AsString = '::tid::side0' then left.tid := SQuery.FieldByName('value').AsInteger; if SQuery.FieldByName('name').AsString = '::tid::side1' then right.tid := SQuery.FieldByName('value').AsInteger; SQuery.Next; end; left.TagValue := SqlReadAlert(left.tid, 0); right.TagValue := SqlReadAlert(right.tid, 1); try OPCTagArray[5].Write(left.TagValue); OPCTagArray[6].Write(right.TagValue); if left.TagValue or right.TagValue then OPCTagArray[7].Write(true) else OPCTagArray[7].Write(false); except on E: Exception do begin SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); ConfigOPCServer(false); ConfigOPCServer(true); //free memory Finalize(left); FillChar(left,sizeof(left),0); Finalize(right); FillChar(right,sizeof(right),0); end; end; {$IFDEF DEBUG} SaveLog('debug' + #9#9 + 'LightAlertLeft -> ' + inttostr(left.TagValue)); SaveLog('debug' + #9#9 + 'LightAlertRight -> ' + inttostr(right.TagValue)); {$ENDIF} //free memory Finalize(left); FillChar(left,sizeof(left),0); Finalize(right); FillChar(right,sizeof(right),0); end; function SqlWriteTemperature(InTemperature, InSide: integer; InCogging: bool): bool; var heat, tid: string; main: TIdHeat; begin main.Create('','','','',''); if InSide = 0 then begin main.Heat := left.Heat; main.Grade := left.Grade; main.Section := left.Section; main.Standard := left.Standard; main.StrengthClass := left.StrengthClass; end else begin main.Heat := right.Heat; main.Grade := right.Grade; main.Section := right.Section; main.Standard := right.Standard; main.StrengthClass := right.StrengthClass; end; if not InCogging or (main.Heat = '') then begin try FQueryOPC.Close; FQueryOPC.SQL.Clear; FQueryOPC.SQL.Add('select first 1'); FQueryOPC.SQL.Add('NOPLAV as heat, MARKA as grade, KLASS as strength_class, RAZM1 as section, STANDART as standard, SIDE'); FQueryOPC.SQL.Add('FROM melts'); FQueryOPC.SQL.Add('where side='+inttostr(InSide)+''); FQueryOPC.SQL.Add('and state=1'); FQueryOPC.SQL.Add('order by begindt desc'); {$IFDEF DEBUG} SaveLog('debug' + #9#9 + 'FQueryOPC side '+inttostr(InSide)+' -> ' + FQueryOPC.SQL.Text); {$ENDIF} Application.ProcessMessages; // следующая операция не тормозит интерфейс FQueryOPC.ExecQuery; except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; main.Heat := FQueryOPC.FieldByName('heat').AsString; main.Grade := FQueryOPC.FieldByName('grade').AsString; main.Section := FQueryOPC.FieldByName('section').AsString; main.Standard := FQueryOPC.FieldByName('standard').AsString; main.StrengthClass := FQueryOPC.FieldByName('strength_class').AsString; if InSide = 0 then begin left.Heat := main.Heat; left.Grade := main.Grade; left.Section := main.Section; left.Standard := main.Standard; left.StrengthClass := main.StrengthClass; end else begin right.Heat := main.Heat; right.Grade := main.Grade; right.Section := main.Section; right.Standard := main.Standard; right.StrengthClass := main.StrengthClass; end; end; {$IFDEF DEBUG} SaveLog('debug' + #9#9 + 'main.Heat -> ' + main.Heat); SaveLog('debug' + #9#9 + 'main.Grade -> ' + main.Grade); SaveLog('debug' + #9#9 + 'main.Section -> ' + main.Section); SaveLog('debug' + #9#9 + 'main.Standard -> ' + main.Standard); SaveLog('debug' + #9#9 + 'main.StrengthClass -> ' + main.StrengthClass); SaveLog('debug' + #9#9 + 'InSide -> ' + inttostr(Inside)); SaveLog('debug' + #9#9 + 'InCoggingRight -> ' + booltostr(InCogging)); {$ENDIF} try SQuery.Close; SQuery.SQL.Clear; SQuery.SQL.Add('SELECT * FROM settings'); SQuery.Open; except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; while not SQuery.Eof do begin if SQuery.FieldByName('name').AsString = '::heat::side'+inttostr(InSide) then heat := SQuery.FieldByName('value').AsString; if SQuery.FieldByName('name').AsString = '::tid::side'+inttostr(InSide) then tid := SQuery.FieldByName('value').AsString; SQuery.Next; end; if heat <> main.Heat then begin tid := inttostr(DateTimeToUnix(NOW)); try SQuery.Close; SQuery.SQL.Clear; SQuery.SQL.Add('INSERT OR REPLACE INTO settings (name, value)'); SQuery.SQL.Add('VALUES (''::heat::side'+inttostr(InSide)+''','); SQuery.SQL.Add(''''+main.Heat+''')'); SQuery.ExecSQL; except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; try SQuery.Close; SQuery.SQL.Clear; SQuery.SQL.Add('INSERT OR REPLACE INTO settings (name, value)'); SQuery.SQL.Add('VALUES (''::tid::side'+inttostr(InSide)+''','); SQuery.SQL.Add(''''+tid+''')'); SQuery.ExecSQL; except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; end; {$IFDEF DEBUG} SaveLog('debug' + #9#9 + 'heat side '+inttostr(InSide)+' -> ' + heat); SaveLog('debug' + #9#9 + 'tid side '+inttostr(InSide)+' -> ' + tid); {$ENDIF} try PQuery.Close; PQuery.SQL.Clear; PQuery.SQL.Add('WITH upsert AS (UPDATE temperature_current SET timestamp=EXTRACT(EPOCH FROM now()),'); PQuery.SQL.Add('heat='''+main.Heat+''','); PQuery.SQL.Add('grade='''+main.Grade+''','); PQuery.SQL.Add('strength_class='''+main.StrengthClass+''','); PQuery.SQL.Add('section='+main.Section+','); PQuery.SQL.Add('standard='''+main.Standard+''','); PQuery.SQL.Add('temperature='+inttostr(InTemperature)+''); PQuery.SQL.Add('WHERE tid='+tid+' and side='+inttostr(InSide)+' RETURNING *)'); PQuery.SQL.Add('INSERT INTO temperature_current (tid,timestamp,heat,grade,'); PQuery.SQL.Add('strength_class,section,standard,side,temperature)'); PQuery.SQL.Add('SELECT '+tid+', EXTRACT(EPOCH FROM now()),'); PQuery.SQL.Add(''''+main.Heat+''','); PQuery.SQL.Add(''''+main.Grade+''','); PQuery.SQL.Add(''''+main.StrengthClass+''','); PQuery.SQL.Add(''+main.Section+','); PQuery.SQL.Add(''''+main.Standard+''','); PQuery.SQL.Add(''+inttostr(InSide)+','); PQuery.SQL.Add(''+inttostr(InTemperature)+''); PQuery.SQL.Add('WHERE NOT EXISTS (SELECT * FROM upsert)'); {$IFDEF DEBUG} SaveLog('debug' + #9#9 + 'PQuery side '+inttostr(InSide)+' -> ' + PQuery.SQL.Text); {$ENDIF} PQuery.ExecSQL; except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; end; function SqlReadAlert(InTid, InSide: integer): OleVariant; var PQueryAlert: TZQuery; begin PQueryAlert := TZQuery.Create(nil); PQueryAlert.Connection := PConnect; try PQueryAlert.Close; PQueryAlert.SQL.Clear; PQueryAlert.SQL.Add('SELECT alarm FROM alarm'); PQueryAlert.SQL.Add('WHERE aid='+inttostr(InTid)+' and side='+inttostr(InSide)+''); {$IFDEF DEBUG} SaveLog('debug' + #9#9 + 'PQueryAlert side '+inttostr(InSide)+' -> ' + PQueryAlert.SQL.Text); {$ENDIF} PQueryAlert.Open; except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; if PQueryAlert.FieldByName('alarm').AsInteger = 1 then begin try FreeAndNil(PQueryAlert); except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; Result := true; end else begin try FreeAndNil(PQueryAlert); except on E: Exception do SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; Result := false; end; end; constructor TIdHeat.Create(_Heat, _Grade, _Section, _Standard, _StrengthClass: string); begin Heat := _Heat; // плавка Grade := _Grade; // марка стали Section := _Section; // профиль Standard := _Standard; // стандарт StrengthClass := _StrengthClass; // клас прочности end; // При загрузке программы класс будет создаваться initialization // создаем поток True - создание остановка, False - создание старт ThreadOpc := TThreadOpc.Create(True); ThreadOpc.Priority := tpNormal; ThreadOpc.FreeOnTerminate := True; left.Create('','','','',''); right.Create('','','','',''); // При закрытии программы уничтожаться finalization ThreadOpc.Terminate; FreeAndNil(left); FreeAndNil(right); end.
unit ufmIDEDialog; {$I ASCRIPT.INC} interface uses Classes, Dialogs, {$IFDEF THEMED_IDE} AdvAppStyler, AdvStyleIF, {$ENDIF} IDEMain, fIDEEditor; type TIDECloseAction = (icaCloseAll, icaNothing); TCustomIDEDialog = class(TComponent) private FEngine: TIDEEngine; FIDEForm: TIDEEditorForm; //FScripter: TIDEScripter; FTitle: string; FCloseAction: TIDECloseAction; FOnCreateIDEForm: TNotifyEvent; FOnShowIDEForm: TNotifyEvent; {$IFDEF THEMED_IDE} FAppStyler: TAdvAppStyler; {$ENDIF} //FCloseProjectOnExit: boolean; function GetEngine: TIDEEngine; procedure SetEngine(const Value: TIDEEngine); {$IFDEF THEMED_IDE} procedure SetAppStyler(const Value: TAdvAppStyler); {$ENDIF} protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Execute(Sender: TComponent); property OnCreateIDEForm: TNotifyEvent read FOnCreateIDEForm write FOnCreateIDEForm; property OnShowIDEForm: TNotifyEvent read FOnShowIDEForm write FOnShowIDEForm; published property Engine: TIDEEngine read GetEngine write SetEngine; property Title: string read FTitle write FTitle; property IDECloseAction: TIDECloseAction read FCloseAction write FCloseAction; {$IFDEF THEMED_IDE} property AppStyler: TAdvAppStyler read FAppStyler write SetAppStyler; {$ENDIF} //property CloseProjectOnExit: boolean read FCloseProjectOnExit write FCloseProjectOnExit; end; implementation { TIDEDialog } constructor TCustomIDEDialog.Create(AOwner: TComponent); begin inherited; FTitle := 'IDE - %s'; FCloseAction := icaCloseAll; //FIDEForm := TIDEEditorForm.Create(nil); end; destructor TCustomIDEDialog.Destroy; begin {FIDEForm.Free; FIDEForm := nil;} inherited; end; procedure TCustomIDEDialog.Execute(Sender: TComponent); begin if Engine = nil then raise EIDEException.Create('Engine component not defined in TIDEDialog component.'); //FIDEForm.Scripter := FScripter; FIDEForm := TIDEEditorForm.Create(Sender); try FIDEForm.AttachEngine(FEngine); if Assigned(FOnCreateIDEForm) then FOnCreateIDEForm(FIDEForm); FIDEForm.OnNotifyShow := FOnShowIDEForm; FIDEForm.Title := FTitle; case FCloseAction of icaCloseAll: FIDEForm.CloseAllOnExit := true; icaNothing: FIDEForm.CloseAllOnExit := false; end; {$IFDEF THEMED_IDE} FIDEForm.AppStyler := FAppStyler; {$ENDIF} // FIDEForm.Show; FIDEForm.ShowModal; FIDEForm.DetachEngine; finally FIDEForm.Free; FIDEForm := nil; end; end; function TCustomIDEDialog.GetEngine: TIDEEngine; begin result := FEngine; end; procedure TCustomIDEDialog.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FEngine) then FEngine := nil; {$IFDEF THEMED_IDE} if (Operation = opRemove) and (AComponent = FAppStyler) then FAppStyler := nil; {$ENDIF} end; {$IFDEF THEMED_IDE} procedure TCustomIDEDialog.SetAppStyler(const Value: TAdvAppStyler); begin if FAppStyler <> Value then begin if FAppStyler <> nil then FAppStyler.RemoveFreeNotification(Self); FAppStyler := Value; if FAppStyler <> nil then FAppStyler.FreeNotification(Self); end; end; {$ENDIF} procedure TCustomIDEDialog.SetEngine(const Value: TIDEEngine); begin if FEngine <> Value then begin if FEngine <> nil then FEngine.RemoveFreeNotification(Self); FEngine := Value; if FEngine <> nil then FEngine.FreeNotification(Self); end; end; end.
unit Main; interface //#################################################################### ■ uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Objects, FMX.Edit, LUX, LUX.Matrix.L4, LUX.Color, LUX.Raytrace, LUX.Raytrace.Geometry, LUX.Raytrace.Material, LUX.Raytrace.Render, LIB.Raytrace, LIB.Raytrace.Geometry, LIB.Raytrace.Material; type TForm1 = class(TForm) Image1: TImage; Panel1: TPanel; GroupBoxI: TGroupBox; LabelIW: TLabel; EditIW: TEdit; LabelIH: TLabel; EditIH: TEdit; GroupBoxR: TGroupBox; ButtonP: TButton; ButtonS: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ButtonPClick(Sender: TObject); procedure ButtonSClick(Sender: TObject); private { private 宣言 } public { public 宣言 } _Render :TRayRender; _World :TRayWorld; _Sky :TRaySky; _Camera :TRayCamera; _Light :TRayLight; _Ground :TRayGround; ///// メソッド procedure MakeScene; end; var Form1: TForm1; implementation //############################################################### ■ {$R *.fmx} uses System.Math; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public /////////////////////////////////////////////////////////////////////// メソッド procedure TForm1.MakeScene; var N :Integer; begin ////////// 世界 _World := TRayWorld.Create; with _World do begin RecursN := 8; end; _Render.World := _World; ////////// カメラ _Camera := TRayCamera.Create( _World ); with _Camera do begin LocalMatrix := TSingleM4.RotateX( DegToRad( -30 ) ) * TSingleM4.Translate( 0, 0, 15 ); end; _Render.Camera := _Camera; ////////// ライト _Light := TRayLight.Create( _World ); with _Light do begin LocalMatrix := TSingleM4.Translate( 0, 100, 0 ); Color := TSingleRGBA.Create( 1, 1, 1 ); end; ////////// 地面 _Ground := TRayGround.Create( _World ); with _Ground do begin LocalMatrix := TSingleM4.Translate( 0, -6, 0 ); Material := TMaterialDiff.Create; with TMaterialDiff( Material ) do begin DiffRatio := TSingleRGB.Create( 1, 1, 1 ); end; end; ////////// 空 _Sky := TRaySky.Create( _World ); with _Sky do begin Material := TMaterialTexColor.Create; with TMaterialTexColor( Material ) do begin Texture.LoadFromFile( '..\..\_DATA\Sky.png' ); end; end; ////////// 球 for N := 1 to 64 do begin with TMyGeometry.Create( _World ) do begin Radius := 1; LocalMatrix := TSingleM4.Translate( 10 * Random - 5, 10 * Random - 5, 10 * Random - 5 ) * TSingleM4.RotateX( Pi2 * Random ) * TSingleM4.RotateY( Pi2 * Random ) * TSingleM4.RotateZ( Pi2 * Random ) * TSingleM4.Scale( 0.2 + 0.8 * Random, 0.2 + 0.8 * Random, 0.2 + 0.8 * Random ); Material := TMyMaterial.Create; with TMyMaterial( Material ) do begin DiffRatio := TSingleRGB.Create( 0.2 + 0.8 * Random, 0.2 + 0.8 * Random, 0.2 + 0.8 * Random ); end; end; end; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& procedure TForm1.FormCreate(Sender: TObject); begin _Render := TRayRender.Create; with _Render do begin MaxSampleN := 64; ConvN := 4; ConvE := 1/32; end; MakeScene; end; procedure TForm1.FormDestroy(Sender: TObject); begin _World.Free; _Render.Free; end; //------------------------------------------------------------------------------ procedure TForm1.ButtonPClick(Sender: TObject); begin ButtonP.Enabled := False; ButtonS.Enabled := True ; with _Render do begin Pixels.BricX := EditIW.Text.ToInteger; Pixels.BricY := EditIH.Text.ToInteger; Run; CopyToBitmap( Image1.Bitmap ); end; Image1.Bitmap.SaveToFile( 'Image.png' ); ButtonP.Enabled := True ; ButtonS.Enabled := False; end; procedure TForm1.ButtonSClick(Sender: TObject); begin ButtonS.Enabled := False; _Render.Stop; end; end. //######################################################################### ■
unit objPedido; interface uses System.SysUtils, FireDAC.Comp.Client, Vcl.Dialogs; type TPedido = class(TObject) private Fnumero: Integer; Fdata : TDate; Fdescricao : String; Fsituacao : Integer; FvalorTotal : Double; Fconexao : TFDConnection; protected function getNumero : Integer; function getData : TDate; function getDescricao: String; function getSituacao: Integer; function getValorTotal: Double; procedure setNumero(const Value: Integer); procedure setData(const Value: TDate); procedure setDescricao(const Value: String); procedure setSituacao(const Value: Integer); procedure setValorTotal(const Value: Double); public property numero : Integer read getNumero write setNumero; property data : TDate read getData write setData; property descricao : String read getDescricao write setDescricao; property situacao : Integer read getSituacao write setSituacao; property valorTotal : Double read getValorTotal write setValorTotal; function Salvar : Boolean; function Editar : Boolean; function Excluir : Boolean; procedure AlterarSituacao; procedure AtualizarValorTotal; procedure CarregarPedidos(var quPedidos : TFDQuery; dataInicial, dataFinal : TDate); procedure LimparDados; constructor Create(objConexao : TFDConnection); destructor Destroy; end; implementation { TPedido } constructor TPedido.Create(objConexao : TFDConnection); begin inherited Create; Fconexao := objConexao; end; destructor TPedido.Destroy; begin inherited; end; function TPedido.getData: TDate; begin result := Fdata; end; function TPedido.getDescricao: String; begin result := Fdescricao; end; function TPedido.getNumero: Integer; begin result := Fnumero; end; function TPedido.getSituacao: Integer; begin result := Fsituacao; end; function TPedido.getValorTotal: Double; begin result := FvalorTotal; end; procedure TPedido.LimparDados; begin try numero := 0; data := Now; descricao := ''; situacao := 0; valorTotal := 0; except on e:Exception do raise Exception.Create('Erro ao limpar dados do pedido!' + #13 + 'Erro: ' + e.Message); end; end; procedure TPedido.setData(const Value: TDate); begin Fdata := Value; end; procedure TPedido.setDescricao(const Value: String); begin Fdescricao := Value; end; procedure TPedido.setNumero(const Value: Integer); begin Fnumero := Value; end; procedure TPedido.setSituacao(const Value: Integer); begin Fsituacao := Value; end; procedure TPedido.setValorTotal(const Value: Double); begin FvalorTotal := Value; end; procedure TPedido.CarregarPedidos(var quPedidos: TFDQuery; dataInicial, dataFinal : TDate); begin try quPedidos.Close; quPedidos.SQL.Clear; quPedidos.SQL.Add('SELECT PED.NUMERO, PED.DATA, PED.DESCRICAO, PED.SITUACAO, PED.VALORTOTAL, SIT.DESCRICAO AS SITUACAO_FMT'); quPedidos.SQL.Add('FROM PEDIDOS PED'); quPedidos.SQL.Add(' INNER JOIN SITUACOES SIT ON SIT.CODIGO = PED.SITUACAO'); quPedidos.SQL.Add('WHERE 0 = 0'); if numero > 0 then begin quPedidos.SQL.Add('AND PED.NUMERO = :NUMERO'); quPedidos.Params.ParamByName('NUMERO').AsInteger := numero; end; quPedidos.SQL.Add('AND PED.DATA BETWEEN :DATAINICIAL AND :DATAFINAL'); quPedidos.Params.ParamByName('DATAINICIAL').AsDate := dataInicial; quPedidos.Params.ParamByName('DATAFINAL').AsDate := dataFinal; if situacao > 0 then begin quPedidos.SQL.Add('AND PED.SITUACAO = :SITUACAO'); quPedidos.Params.ParamByName('SITUACAO').AsInteger := situacao; end; quPedidos.SQL.Add('ORDER BY PED.NUMERO DESC'); quPedidos.Open; except on e:Exception do ShowMessage('Erro ao carregar pedidos!' + #13 + 'Erro: ' + e.Message); end; end; function TPedido.Salvar : Boolean; var quInserir : TFDQuery; begin try result := False; quInserir := TFDQuery.Create(nil); quInserir.Connection := Fconexao; try quInserir.Close; quInserir.SQL.Clear; quInserir.SQL.Add('INSERT INTO PEDIDOS (DATA, DESCRICAO, SITUACAO, VALORTOTAL)'); quInserir.SQL.Add('VALUES (:DATA, :DESCRICAO, :SITUACAO, :VALORTOTAL)'); quInserir.Params.ParamByName('DATA').AsDate := data; quInserir.Params.ParamByName('DESCRICAO').AsString := descricao; quInserir.Params.ParamByName('SITUACAO').AsInteger := situacao; quInserir.Params.ParamByName('VALORTOTAL').AsFloat := valorTotal; quInserir.ExecSQL; if quInserir.RowsAffected < 1 then raise Exception.Create('Pedido não inserido.'); result := True; except on e:Exception do raise Exception.Create(e.Message); end; finally quInserir.Close; FreeAndNil(quInserir); end; end; function TPedido.Editar : Boolean; var quEditar : TFDQuery; begin try result := False; quEditar := TFDQuery.Create(nil); quEditar.Connection := Fconexao; try quEditar.Close; quEditar.SQL.Clear; quEditar.SQL.Add('UPDATE PEDIDOS'); quEditar.SQL.Add('SET DATA = :DATA,'); quEditar.SQL.Add(' DESCRICAO = :DESCRICAO'); quEditar.SQL.Add('WHERE NUMERO = :NUMERO'); quEditar.Params.ParamByName('DATA').AsDate := data; quEditar.Params.ParamByName('DESCRICAO').AsString := descricao; quEditar.Params.ParamByName('NUMERO').AsInteger := numero; quEditar.ExecSQL; if quEditar.RowsAffected <> 1 then raise Exception.Create('Pedido não alterado.'); result := True; except on e:Exception do raise Exception.Create(e.Message); end; finally quEditar.Close; FreeAndNil(quEditar); end; end; function TPedido.Excluir : Boolean; var quExcluir : TFDQuery; begin try result := False; quExcluir := TFDQuery.Create(nil); quExcluir.Connection := Fconexao; try quExcluir.Close; quExcluir.SQL.Clear; quExcluir.SQL.Add('DELETE FROM PEDIDOS'); quExcluir.SQL.Add('WHERE NUMERO = :NUMERO'); quExcluir.Params.ParamByName('NUMERO').AsInteger := numero; quExcluir.ExecSQL; if quExcluir.RowsAffected <> 1 then raise Exception.Create('Pedido não excluído. Linhas afetadas: ' + IntToStr(quExcluir.RowsAffected)); result := True; except on e:Exception do raise Exception.Create(e.Message); end; finally quExcluir.Close; FreeAndNil(quExcluir); end; end; procedure TPedido.AlterarSituacao; var quAlterarSituacao : TFDQuery; begin try quAlterarSituacao := TFDQuery.Create(nil); quAlterarSituacao.Connection := Fconexao; try quAlterarSituacao.Close; quAlterarSituacao.SQL.Clear; quAlterarSituacao.SQL.Add('UPDATE PEDIDOS'); quAlterarSituacao.SQL.Add('SET SITUACAO = :SITUACAO'); quAlterarSituacao.SQL.Add('WHERE NUMERO = :NUMERO'); quAlterarSituacao.Params.ParamByName('SITUACAO').AsInteger := situacao; quAlterarSituacao.Params.ParamByName('NUMERO').AsInteger := numero; quAlterarSituacao.ExecSQL; if quAlterarSituacao.RowsAffected <> 1 then raise Exception.Create('Situação não alterada.'); except on e:Exception do raise Exception.Create(e.Message); end; finally quAlterarSituacao.Close; FreeAndNil(quAlterarSituacao); end; end; procedure TPedido.AtualizarValorTotal; var quAtualizarValor : TFDQuery; begin try quAtualizarValor := TFDQuery.Create(nil); quAtualizarValor.Connection := Fconexao; try quAtualizarValor.Close; quAtualizarValor.SQL.Clear; quAtualizarValor.SQL.Add('UPDATE PEDIDOS'); quAtualizarValor.SQL.Add('SET VALORTOTAL = :VALORTOTAL'); quAtualizarValor.SQL.Add('WHERE NUMERO = :NUMERO'); quAtualizarValor.Params.ParamByName('VALORTOTAL').AsFloat := valorTotal; quAtualizarValor.Params.ParamByName('NUMERO').AsInteger := numero; quAtualizarValor.ExecSQL; if quAtualizarValor.RowsAffected <> 1 then raise Exception.Create('Valor total não atualizado.'); except on e:Exception do raise Exception.Create(e.Message); end; finally quAtualizarValor.Close; FreeAndNil(quAtualizarValor); end; end; end.
unit uScannerImagem; interface uses Windows, System.UITypes, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, jpeg, DelphiTwain, DelphiTwain_Vcl; type TfrmScannerImagem = class(TForm) PnlTop: TPanel; BtnScanWithoutDialog: TSpeedButton; LBSources: TListBox; ImgHolder: TImage; spbAceitar: TSpeedButton; spbCancelar: TSpeedButton; Label1: TLabel; procedure edtDescrImagemKeyPress(Sender: TObject; var Key: Char); procedure BtnScanWithoutDialogClick(Sender: TObject); procedure spbCancelarClick(Sender: TObject); procedure spbAceitarClick(Sender: TObject); private Twain: TDelphiTwain; procedure ReloadSources; procedure TwainTwainAcquire(Sender: TObject; const Index: Integer; Image: TBitmap; var Cancel: Boolean); public protected procedure DoCreate; override; procedure DoDestroy; override; end; var frmScannerImagem : TfrmScannerImagem; procedure EscanearImagem(var AIMG: TImage); implementation {$R *.dfm} procedure EscanearImagem(var AIMG: TImage); var frm: TfrmScannerImagem; Jpg : TJPEGImage; MemoryStream : TMemoryStream; Stream: TStream; begin frm := TfrmScannerImagem.Create(Application); try frm.ShowModal; if frm.ModalResult = mrOk then begin try MemoryStream := TMemoryStream.Create; Jpg := TJpegImage.Create; Jpg.Assign(frm.ImgHolder.Picture.Graphic); Jpg.CompressionQuality := 40; Jpg.Compress; jpg.SaveToStream(MemoryStream); if MemoryStream.Size > 400000 then begin MessageDlg('Arquivo maior que 400KB, tamanho não permitido!',mtInformation,[mbok],0); exit; end; AIMG.Picture.Assign(Jpg); finally Jpg.Free; //MemoryStream.Free; end end else AIMG.Picture.Assign(nil); finally frm.Free; frm := nil; memoryStream.Free; end; end; procedure TfrmScannerImagem.BtnScanWithoutDialogClick(Sender: TObject); begin Twain.SelectedSourceIndex := LBSources.ItemIndex; if Assigned(Twain.SelectedSource) then begin //Load source, select transference method and enable (display interface)} Twain.SelectedSource.Loaded := True; Twain.SelectedSource.ShowUI := False; Twain.SelectedSource.Enabled := True; end; end; procedure TfrmScannerImagem.spbAceitarClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TfrmScannerImagem.spbCancelarClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfrmScannerImagem.DoCreate; begin inherited; Twain := TDelphiTwain.Create; Twain.OnTwainAcquire := TwainTwainAcquire; if Twain.LoadLibrary then begin //Load source manager Twain.SourceManagerLoaded := TRUE; ReloadSources; end else begin ShowMessage('Twain is not installed.'); end; end; procedure TfrmScannerImagem.DoDestroy; begin Twain.Free;//Don't forget to free Twain! inherited; end; procedure TfrmScannerImagem.edtDescrImagemKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then SelectNext(Sender as TWinControl, True, True); end; procedure TfrmScannerImagem.ReloadSources; var I: Integer; begin LBSources.Items.Clear; for I := 0 to Twain.SourceCount-1 do LBSources.Items.Add(Twain.Source[I].ProductName); if LBSources.Items.Count > 0 then LBSources.ItemIndex := 0; end; procedure TfrmScannerImagem.TwainTwainAcquire(Sender: TObject; const Index: Integer; Image: TBitmap; var Cancel: Boolean); begin ImgHolder.Picture.Assign(Image); Cancel := True;//Only want one image end; end.
unit ClassDeviceConnect; interface uses System.Generics.Collections, FMX.Graphics; type TIoTDeviceType = (dtNetwaveCam); TImgExtraVal = class private AValue: TBitmap; function GetValue: TBitmap; procedure SetValue(Value: TBitmap); public property Value: TBitmap read GetValue write SetValue default nil; end; TStrExtraVal = class private AValue: string; function GetValue: string; procedure SetValue(Value: string); public property Value: string read GetValue write SetValue; constructor Create; end; IDeviceConnect = interface ['{FECCEE16-20EE-4A5F-A692-9642A6B0498F}'] {$REGION 'Internal Declarations'} function GetHost: string; procedure SetHost(Value: string); function GetPort: integer; procedure SetPort(Value: integer); function GetAuth: string; procedure SetAuth(Value: string); {$ENDREGION 'Internal Declarations'} property Host: string read GetHost write SetHost; property Port: integer read GetPort write SetPort; property Auth: string read GetAuth write SetAuth; function Connect(out ErrMasg: string): TDictionary<string, TObject>; procedure Free; end; TDeviceConnect = class (TInterfacedObject, IDeviceConnect) private AHost: string; APort: integer; AAuth: string; function ExcludeTrailingSlash(const S: string): string; protected function GetHost: string; virtual; procedure SetHost(Value: string); virtual; function GetPort: integer; virtual; procedure SetPort(Value: integer); virtual; function GetAuth: string; virtual; procedure SetAuth(Value: string); virtual; public property Host: string read GetHost write SetHost; property Port: integer read GetPort write SetPort default 0; property Auth: string read GetAuth write SetAuth; constructor Create; virtual; destructor Destroy; override; function Connect(out ErrMsg: string): TDictionary<string, TObject>; virtual; abstract; end; implementation uses System.SysUtils; { TDeviceConnect } constructor TDeviceConnect.Create; begin inherited Create; Host := ''; Auth := ''; end; destructor TDeviceConnect.Destroy; begin inherited Destroy; end; function TDeviceConnect.GetHost: string; begin Result := AHost; end; function TDeviceConnect.GetAuth: string; begin Result := AAuth; end; function TDeviceConnect.GetPort: integer; begin Result := APort; end; function TDeviceConnect.ExcludeTrailingSlash(const S: string): string; var Index: smallint; begin Result := S; Index := High(Result); if (Index >= Low(string)) and (Index <= High(Result)) and (Result[Index] = '/') and (ByteType(Result, Index) = mbSingleByte) then SetLength(Result, Length(Result)-1); end; procedure TDeviceConnect.SetHost(Value: string); begin Value := ExcludeTrailingSlash(Value); if Value <> AHost then AHost := Value; end; procedure TDeviceConnect.SetAuth(Value: string); begin if Value <> AAuth then AAuth := Value; end; procedure TDeviceConnect.SetPort(Value: integer); begin if Value <> APort then APort := Value; end; { TImgExtraVal } function TImgExtraVal.GetValue: TBitmap; begin Result := AValue; end; procedure TImgExtraVal.SetValue(Value: TBitmap); begin if (not Assigned(AValue)) or (not AValue.Equals(Value)) then AValue := Value; end; { TStrExtraVal } constructor TStrExtraVal.Create; begin inherited Create; SetValue(''); end; function TStrExtraVal.GetValue: string; begin Result := AValue; end; procedure TStrExtraVal.SetValue(Value: string); begin if Value <> AValue then AValue := Value; end; end.
namespace Sugar.RegularExpressions; interface uses Sugar.Collections; type RegexOptions = public flags (IgnoreCase, IgnoreWhitespace, Multiline, Singleline); Regex = public class mapped to {$IF COOPER}java.util.regex.Pattern {$ELSEIF ECHOES}System.Text.RegularExpressions.Regex {$ELSEIF TOFFEE}NSRegularExpression{$ENDIF} private class method OptionsToBitfield(PatternOptions: RegexOptions): Integer; public constructor(Pattern: String; PatternOptions: RegexOptions); constructor(Pattern: String); method FindFirstMatch(Input: String): Match; method FindMatches(Input: String): List<Match>; method IsMatch(Input: String): Boolean; method ReplaceMatches(Input: String; Replacement: String): String; end; implementation constructor Regex(Pattern: String; PatternOptions: RegexOptions); begin var Bitfield: Integer := OptionsToBitfield(PatternOptions); {$IF COOPER} exit java.util.regex.Pattern.compile(Pattern, Bitfield); {$ELSEIF ECHOES} exit new System.Text.RegularExpressions.Regex(Pattern, System.Text.RegularExpressions.RegexOptions(Bitfield)); {$ELSEIF TOFFEE} var Error: NSError; exit NSRegularExpression.regularExpressionWithPattern(Pattern) options(NSRegularExpressionOptions(Bitfield)) error(var Error); {$ENDIF} end; constructor Regex(Pattern: String); begin constructor(Pattern, RegexOptions(0)); end; method Regex.FindFirstMatch(Input: String): Match; begin {$IF COOPER} var Matcher: java.util.regex.Matcher := mapped.matcher(Input); exit if Matcher.find() then Matcher else nil; {$ELSEIF ECHOES} var FirstMatch: System.Text.RegularExpressions.Match := mapped.Match(Input); exit if FirstMatch.Success then FirstMatch else nil; {$ELSEIF TOFFEE} var FirstMatch: NSTextCheckingResult := mapped.firstMatchInString(Input) options(NSMatchingOptions(0)) range(NSMakeRange(0, Input.length)); exit if FirstMatch <> nil then new Match(FirstMatch, Input) else nil; {$ENDIF} end; method Regex.FindMatches(Input: String): List<Match>; begin var Matches: List<Match> := new List<Match>(); {$IF COOPER} var Matcher: java.util.regex.Matcher := mapped.matcher(Input); while (Matcher.find()) do Matches.Add(Match(Matcher.toMatchResult())); {$ELSEIF ECHOES} var PlatformMatches: System.Text.RegularExpressions.MatchCollection := mapped.Matches(Input); for PlatformMatch in PlatformMatches do Matches.Add(Match(PlatformMatch)); {$ELSEIF TOFFEE} var PlatformMatches: NSArray := mapped.matchesInString(Input) options(NSMatchingOptions(0)) range(NSMakeRange(0, Input.length)); for PlatformMatch in PlatformMatches do Matches.Add(new Match(PlatformMatch, Input)); {$ENDIF} exit Matches; end; method Regex.IsMatch(Input: String): Boolean; begin {$IF COOPER} exit mapped.matcher(Input).find(); {$ELSEIF ECHOES} exit mapped.IsMatch(Input); {$ELSEIF TOFFEE} var MatchCount: Integer := mapped.numberOfMatchesInString(Input) options(NSMatchingOptions(0)) range(NSMakeRange(0, Input.length)); exit MatchCount > 0; {$ENDIF} end; class method Regex.OptionsToBitfield(PatternOptions: RegexOptions): Integer; begin var Bitfield: Integer := 0; if RegexOptions.IgnoreCase in PatternOptions then Bitfield := Bitfield or {$IF COOPER}java.util.regex.Pattern.CASE_INSENSITIVE {$ELSEIF ECHOES}System.Text.RegularExpressions.RegexOptions.IgnoreCase {$ELSEIF TOFFEE}NSRegularExpressionOptions.NSRegularExpressionCaseInsensitive{$ENDIF}; if RegexOptions.IgnoreWhitespace in PatternOptions then Bitfield := Bitfield or {$IF COOPER}java.util.regex.Pattern.COMMENTS {$ELSEIF ECHOES}System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace {$ELSEIF TOFFEE}NSRegularExpressionOptions.NSRegularExpressionAllowCommentsAndWhitespace{$ENDIF}; if RegexOptions.Multiline in PatternOptions then Bitfield := Bitfield or {$IF COOPER}java.util.regex.Pattern.MULTILINE {$ELSEIF ECHOES}System.Text.RegularExpressions.RegexOptions.Multiline {$ELSEIF TOFFEE}NSRegularExpressionOptions.NSRegularExpressionAnchorsMatchLines{$ENDIF}; if RegexOptions.Singleline in PatternOptions then Bitfield := Bitfield or {$IF COOPER}java.util.regex.Pattern.DOTALL {$ELSEIF ECHOES}System.Text.RegularExpressions.RegexOptions.Singleline {$ELSEIF TOFFEE}NSRegularExpressionOptions.NSRegularExpressionDotMatchesLineSeparators{$ENDIF}; exit Bitfield; end; method Regex.ReplaceMatches(Input: String; Replacement: String): String; begin {$IF COOPER} exit mapped.matcher(Input).replaceAll(Replacement); {$ELSEIF ECHOES} exit mapped.Replace(Input, Replacement); {$ELSEIF TOFFEE} exit mapped.stringByReplacingMatchesInString(Input) options(NSMatchingOptions(0)) range(NSMakeRange(0, Input.length)) withTemplate(Replacement); {$ENDIF} end; end.
unit classEnviarEmail; interface uses IdSMTP, IdSSLOpenSSL, IdMessage, IdText, IdAttachmentFile, IdExplicitTLSClientServerBase, System.Classes; type TEmail = class Port :Integer; Host :String; Username :String; Password :String; public constructor create(pPort: Integer; pHost, pUsername, pPassword: String); procedure enviarEmail(remetente, nomeRemetente: String; destinatarios, assunto, mensagem:String; anexo: String = ''); end; implementation uses System.SysUtils, Vcl.Dialogs; { TEmail } constructor TEmail.create(pPort: Integer; pHost, pUsername, pPassword: String); begin Self.Port := pPort; self.Host := pHost; self.Username := pUsername; self.Password := pPassword; end; procedure TEmail.enviarEmail(remetente, nomeRemetente: String; destinatarios, assunto, mensagem, anexo: String); var IdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL; IdSMTP: TIdSMTP; IdMessage: TIdMessage; IdText: TIdText; index: Integer; begin IdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create(); IdSMTP := TIdSMTP.Create(); IdMessage := TIdMessage.Create(); try IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23; IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient; IdSMTP.IOHandler := IdSSLIOHandlerSocket; IdSMTP.UseTLS := utUseImplicitTLS; IdSMTP.AuthType := satDefault; IdSMTP.Port := self.Port; IdSMTP.Host := self.Host; IdSMTP.Username := self.Username; IdSMTP.Password := self.Password; IdMessage.From.Address := remetente; IdMessage.From.Name := nomeRemetente; IdMessage.ReplyTo.EMailAddresses := IdMessage.From.Address; IdMessage.Recipients.Add.Text := destinatarios; IdMessage.Subject := assunto; IdMessage.Encoding := meMIME; IdText := TIdText.Create(IdMessage.MessageParts); IdText.Body.Add(mensagem); IdText.ContentType := 'text/plain; charset=iso-8859-1'; if (anexo <> '') then begin if FileExists(anexo) then begin TIdAttachmentFile.Create(IdMessage.MessageParts, anexo); end; end; try IdSMTP.Connect; IdSMTP.Authenticate; except on E:Exception do begin MessageDlg('Erro na conexão ou autenticação: ' + E.Message, mtWarning, [mbOK], 0); Exit; end; end; try IdSMTP.Send(IdMessage); MessageDlg('Mensagem enviada com sucesso!', mtInformation, [mbOK], 0); except On E:Exception do begin MessageDlg('Erro ao enviar a mensagem: ' + E.Message, mtWarning, [mbOK], 0); end; end; finally IdSMTP.Disconnect; UnLoadOpenSSLLibrary; FreeAndNil(IdMessage); FreeAndNil(IdSSLIOHandlerSocket); FreeAndNil(IdSMTP); end; end; end.
// Copyright (c) 2016, Jordi Corbilla // 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 this library 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. unit lib.nodes; interface uses FMX.StdCtrls, FMX.Objects; type TNode = class(TObject) private FColorOff: cardinal; FColorOn: cardinal; FAction: string; FlabelNode: TLabel; FRoundRect: TRoundRect; procedure SetAction(const Value: string); procedure SetColorOff(const Value: cardinal); procedure SetColorOn(const Value: cardinal); procedure SetLabelNode(const Value: TLabel); procedure SetRoundRect(const Value: TRoundRect); function GetAction() : string; function GetColorOn() : cardinal; function GetColorOff() : cardinal; function GetLabelNode() : TLabel; function GetRoundRect() : TRoundRect; public property Action : string read GetAction write SetAction; property ColorOn : cardinal read GetColorOn write SetColorOn; property ColorOff : cardinal read GetColorOff write SetColorOff; property LabelNode : TLabel read GetLabelNode write SetLabelNode; property RoundRect : TRoundRect read GetRoundRect write SetRoundRect; constructor Create(action : string; colorOn : cardinal; colorOff : cardinal; labelNode: TLabel; RoundRect: TRoundRect); end; implementation { TNode } constructor TNode.Create(action: string; colorOn, colorOff: cardinal; labelNode: TLabel; RoundRect: TRoundRect); begin SetAction(action); SetColorOn(colorOn); SetColorOff(colorOff); SetLabelNode(labelNode); SetRoundRect(RoundRect); end; function TNode.GetAction: string; begin result := FAction; end; function TNode.GetColorOff: cardinal; begin result := FColorOff; end; function TNode.GetColorOn: cardinal; begin result := FColorOn; end; function TNode.GetLabelNode: TLabel; begin result := FLabelNode; end; function TNode.GetRoundRect: TRoundRect; begin result := FRoundRect; end; procedure TNode.SetAction(const Value: string); begin FAction := Value; end; procedure TNode.SetColorOff(const Value: cardinal); begin FColorOff := Value; end; procedure TNode.SetColorOn(const Value: cardinal); begin FColorOn := Value; end; procedure TNode.SetLabelNode(const Value: TLabel); begin FLabelNode := Value; end; procedure TNode.SetRoundRect(const Value: TRoundRect); begin FRoundRect := Value; end; end.
unit fuImages; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ClipBrd, Vcl.ExtCtrls, Vcl.ComCtrls, JPEG, Vcl.StdCtrls, AdvEdit, HTMLText, AdvGlowButton; type TfrmImages = class(TForm) pnlImageHeader: TPanel; lvImage: TListView; imgImport: TImage; eImageTitle: TAdvEdit; eImageNotes: TAdvEdit; lblHowToAddImage: THTMLStaticText; btnSelectImage: TAdvGlowButton; btnClear: TAdvGlowButton; btnSaveImage: TAdvGlowButton; odSelectImage: TOpenDialog; procedure lvImageKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnSelectImageClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure SetComponentsAndButtonsStateToImage; private { Private declarations } public { Public declarations } end; var frmImages: TfrmImages; implementation {$R *.dfm} procedure TfrmImages.btnSelectImageClick(Sender: TObject); var jpgIncoming : TJPEGImage; sFileIn : String; begin if odSelectImage.Execute then begin sFileIn:= odSelectImage.FileName; if (POS('.jpg',LowerCase(sFileIn)) > 0) or (POS('.jpeg',LowerCase(sFileIn)) > 0) then try jpgIncoming:= TJPEGImage.Create; jpgIncoming.LoadFromFile(sFileIn); imgImport.Picture.Bitmap.Assign(jpgIncoming); finally jpgIncoming.Free; end else imgImport.Picture.LoadFromFile(odSelectImage.FileName); SetComponentsAndButtonsStateToImage; end; end; procedure TfrmImages.btnClearClick(Sender: TObject); begin lvImage.Visible:= true; lblHowToAddImage.Visible:= true; imgImport.Picture:= nil; btnSaveImage.Enabled:= false; end; procedure TfrmImages.lvImageKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (ssCtrl in Shift) and ((Key = Ord('V')) or (Key = Ord('v'))) and Clipboard.HasFormat(CF_BITMAP) then begin imgImport.Picture.Bitmap.Assign(Clipboard) ; SetComponentsAndButtonsStateToImage; end; end; procedure TfrmImages.SetComponentsAndButtonsStateToImage; begin lvImage.Visible:= false; lblHowToAddImage.Visible:= false; btnSaveImage.Enabled:= true; end; end.
(* MP_Lex: HDO, 2004-02-06 ------- Lexical analyzer (scanner) for the MiniPascal Interpreter and the MiniPascal Compiler. ===================================================================*) UNIT MP_Lex; INTERFACE TYPE Symbol = ( noSy, errSy, eofSy, beginSy, endSy, integerSy, programSy, readSy, varSy, writeSy, plusSy, minusSy, timesSy, divSy, leftParSy, rightParSy, commaSy, colonSy, assignSy, semicolonSy, periodSy, identSy, numberSy, ifSy, thenSy, elseSy, whileSy, doSy ); VAR sy: Symbol; (* current symbol *) syLnr, syCnr: INTEGER; (* start position of current symbol *) identStr: STRING; (* string when sy = identSy *) numberVal: STRING; (* value when sy = numberSy *) PROCEDURE InitScanner(srcName: STRING; VAR ok: BOOLEAN); PROCEDURE NewSy; (* updates sy, syLnr, syCnr and when sy = identSy then identStr or when sy = numberSy then numberVal *) IMPLEMENTATION CONST EF = Chr(0); TAB = Chr(9); VAR srcFile: TEXT; srcLine: STRING; ch: CHAR; (* current character *) chLnr, chCnr: INTEGER; (* position of current character *) PROCEDURE NewCh; BEGIN IF chCnr < Length(srcLine) THEN BEGIN chCnr := chCnr + 1; ch := srcLine[chCnr] END (*THEN*) ELSE BEGIN IF NOT Eof(srcFile) THEN BEGIN ReadLn(srcFile, srcLine); chLnr:= chLnr + 1; chCnr := 0; ch := ' '; (*to sparate two lines*) END (*THEN*) ELSE BEGIN Close(srcFile); ch := EF; END; (*ELSE*) END; (*ELSE*) END; (*NewCh*) PROCEDURE InitScanner(srcName: STRING; VAR ok: BOOLEAN); (*-----------------------------------------------------------------*) BEGIN Assign(srcFile, srcName); (*$I-*) Reset(srcFile); (*$I+*) ok := IOResult = 0; IF ok THEN BEGIN srcLine := ''; chLnr := 0; chCnr := 1; NewCh; NewSy; END; (*IF*) END; (*InitScanner*) PROCEDURE NewSy; (*-----------------------------------------------------------------*) BEGIN WHILE (ch = ' ') OR (ch = TAB) DO BEGIN NewCh; END; (*WHILE*) syLnr := chLnr; syCnr := chCnr; CASE ch OF EF: BEGIN sy := eofSy; END; '+': BEGIN sy := plusSy; NewCh; END; '-': BEGIN sy := minusSy; NewCh; END; '*': BEGIN sy := timesSy; NewCh; END; '/': BEGIN sy := divSy; NewCh; END; '(': BEGIN NewCh; sy := leftParSy; END; ')': BEGIN sy := rightParSy; NewCh; END; ',': BEGIN sy := commaSy; NewCh; END; ':': BEGIN NewCh; IF ch <> '=' THEN sy := colonSy ELSE BEGIN (*ch = '='*) sy := assignSy; NewCh; END; (*ELSE*) END; ';': BEGIN sy := semicolonSy; NewCh; END; '.': BEGIN sy := periodSy; NewCh; END; 'a'..'z', 'A'..'Z': BEGIN identStr := ''; WHILE ch IN ['a'.. 'z', 'A' ..'Z', '0'..'9', '_'] DO BEGIN identStr := Concat(identStr, UpCase(ch)); NewCh; END; (*WHILE*) IF identStr = 'BEGIN' THEN sy := beginSy ELSE IF identStr = 'END' THEN sy := endSy ELSE IF identStr = 'INTEGER' THEN sy := integerSy ELSE IF identStr = 'PROGRAM' THEN sy := programSy ELSE IF identStr = 'READ' THEN sy := readSy ELSE IF identStr = 'VAR' THEN sy := varSy ELSE IF identStr = 'WRITE' THEN sy := writeSy ELSE IF identStr = 'IF' THEN sy := ifSy ELSE IF identStr = 'THEN' THEN sy := thenSy ELSE IF identStr = 'ELSE' THEN sy := elseSy ELSE IF identStr = 'WHILE' THEN sy := whileSy ELSE IF identStr = 'DO' THEN sy := doSy ELSE sy := identSy; END; '0'..'9': BEGIN sy := numberSy; numberVal := ch; NewCh; WHILE ch IN ['0'..'9'] DO BEGIN numberVal := numberVal + ch; NewCh; END; (*WHILE*) END; ELSE (*default*) sy := errSy; END; (*CASE*) END; (*NewSy*) END. (*MP_Lex*)
{ Модуль списка иконок типов сообщений журнала. } unit ICLogImageList; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs; const INFO_IMG_INDEX = 0; DEBUG_IMG_INDEX = 1; WARNING_IMG_INDEX = 2; ERROR_IMG_INDEX = 3; FATAL_IMG_INDEX = 4; SERVICE_IMG_INDEX = 5; type { Список иконок типов сообщений журнала } TICLogImageList = class(TImageList) private FBmp0, FBmp1, FBmp2, FBmp3, FBmp4, FBmp5 : TBitmap; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published end; procedure Register; implementation procedure Register; begin {$I iclogimagelist_icon.lrs} RegisterComponents('IC Tools',[TICLogImageList]); end; constructor TICLogImageList.Create(AOwner: TComponent); begin inherited; FBmp0 := LoadBitmapFromLazarusResource('information'); Add(FBmp0, nil); FBmp1 := LoadBitmapFromLazarusResource('bug'); Add(FBmp1, nil); FBmp2 := LoadBitmapFromLazarusResource('error'); Add(FBmp2, nil); FBmp3 := LoadBitmapFromLazarusResource('exclamation'); Add(FBmp3, nil); FBmp4 := LoadBitmapFromLazarusResource('stop'); Add(FBmp4, nil); FBmp5 := LoadBitmapFromLazarusResource('comment'); Add(FBmp5, nil); end; destructor TICLogImageList.Destroy; begin FBmp0.Free; FBmp1.Free; FBmp2.Free; FBmp3.Free; FBmp4.Free; FBmp5.Free; inherited; end; initialization { Подключение ресурса с картинками } {$I log_icon_resource.lrs} end.
unit uRamalController; interface uses System.SysUtils, uDMRamal, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms, uFuncoesSIDomper, Data.DBXJSON, Data.DBXJSONReflect, uConverter, uGenericProperty, uRamalVO, uRamalItensVO; type TRamalController = class private FModel: TdmRamal; FOperacao: TOperacao; procedure Post; public procedure Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure FiltrarId(AId: Integer); procedure LocalizarId(AId: Integer); procedure Novo(AIdUsuario: Integer); procedure Editar(AId: Integer; AFormulario: TForm); function Salvar(AIdUsuario: Integer): Integer; procedure Excluir(AIdUsuario, AId: Integer); procedure Cancelar(); procedure Imprimir(AIdUsuario: Integer); procedure ListarItens(AIdRamal: Integer); procedure ListarTudo(); property Model: TdmRamal read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TObservacaoController } procedure TRamalController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; constructor TRamalController.Create; begin inherited Create; FModel := TdmRamal.Create(nil); end; destructor TRamalController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TRamalController.Editar(AId: Integer; AFormulario: TForm); var Negocio: TServerModule2Client; Resultado: Boolean; begin if AId = 0 then raise Exception.Create('Não há Registro para Editar!'); DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(CRamal, dm.IdUsuario, AId); FModel.CDSCadastro.Open; ListarItens(AId); TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRamalController.Excluir(AIdUsuario, AId: Integer); var Negocio: TServerModule2Client; begin if AId = 0 then raise Exception.Create('Não há Registro para Excluir!'); DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try Negocio.Excluir(CRamal, AIdUsuario, AId); FModel.CDSConsulta.Delete; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRamalController.Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.Filtrar(CRamal, ACampo, ATexto, AAtivo, AContem); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRamalController.FiltrarId(AId: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.RamalFiltrarId(AId); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRamalController.Imprimir(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try Negocio.Relatorio(CRamal, AIdUsuario); FModel.Rel.Print; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRamalController.ListarItens(AIdRamal: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSItens.Close; Negocio.RamalListarItens(AIdRamal); FModel.CDSItens.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRamalController.ListarTudo; begin FModel.CDSImpressao.Close; FModel.CDSImpressao.Open; end; procedure TRamalController.LocalizarId(AId: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarId(CRamal, AId); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRamalController.Novo(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.Novo(CRamal, AIdUsuario); FModel.CDSCadastro.Open; ListarItens(0); FModel.CDSCadastro.Append; FOperacao := opIncluir; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TRamalController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; end; function TRamalController.Salvar(AIdUsuario: Integer): Integer; var Negocio: TServerModule2Client; ObjVO: TRamalVO; ItensVO: TRamalItensVO; oObjetoJSON : TJSONValue; begin ObjVO := TRamalVO.Create; DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try // ObjVO.Id := FModel.CDSCadastroRam_Id.AsInteger; // ObjVO.Departamento := FModel.CDSCadastroRam_Departamento.AsString; TGenericProperty.SetProperty<TRamalVO>(ObjVO, FModel.cdsCadastro); FModel.CDSItens.DisableControls; try FModel.CDSItens.First; while not FModel.CDSItens.Eof do begin ItensVO := TRamalItensVO.Create; ItensVO.Id := FModel.CDSItensRamIt_Id.AsInteger; ItensVO.IdRamal := FModel.CDSItensRamIt_Ramal.AsInteger; ItensVO.Nome := FModel.CDSItensRamIt_Nome.AsString; ItensVO.Numero := FModel.CDSItensRamIt_Numero.AsInteger; ObjVO.Itens.Add(ItensVO); FModel.CDSItens.Next; end; finally FModel.CDSItens.First; FModel.CDSItens.EnableControls; end; oObjetoJSON := TConverte.ObjectToJSON(ObjVO); Result := StrToIntDef(Negocio.RamalSalvar(AIdUsuario, oObjetoJSON).ToString(),0); Post; FOperacao := opNavegar; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); FreeAndNil(ObjVO); end; end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, iOSapi.CoreLocation, DPF.iOS.Common, DPF.iOS.MapKit, DPF.iOS.BaseControl, DPF.iOS.MKMapView, DPF.iOS.UIButton, DPF.iOS.UIView, DPF.iOS.UILabel, DPF.iOS.ApplicationManager; type TFMapView = class( TForm ) DPFMapView1: TDPFMapView; DPFButton1: TDPFButton; DPFButton2: TDPFButton; DPFUIView1: TDPFUIView; DPFButton3: TDPFButton; DPFButton4: TDPFButton; DPFLabel1: TDPFLabel; DPFUIView2: TDPFUIView; DPFApplicationManager1: TDPFApplicationManager; DPFUIView3: TDPFUIView; DPFLabelSpeed: TDPFLabel; DPFLabelLocation: TDPFLabel; procedure DPFButton1Click( Sender: TObject ); procedure DPFButton2Click( Sender: TObject ); procedure DPFButton3Click( Sender: TObject ); procedure DPFButton4Click( Sender: TObject ); procedure FormShow( Sender: TObject ); procedure DPFApplicationManager1MemoryWarning( Sender: TObject ); procedure FormCreate( Sender: TObject ); procedure DPFMapView1ZoomChanged( sender: TObject ); procedure DPFMapView1DidUpdateUserLocation( sender: TObject; Location: TDPFLocation ); private { Private declarations } Marker1 : MKPointAnnotation; Marker2 : MKPointAnnotation; Circle : MKCircle; Polyline: MKPolyline; Polygon : MKPolygon; procedure OnPolygonClick( sender: TObject; PolygonView: MKPolygonView; Polygon: MKPolygon ); procedure OnPolylineClick( sender: TObject; PolylineView: MKPolylineView; Polyline: MKPolyline ); procedure OnCircleClick( sender: TObject; CircleView: MKCircleView; Circle: MKCircle ); procedure OnAnnotationClick( sender: TObject; AnnotationView: MKAnnotationView; Annotation: MKAnnotation; AnnotationInfo: PAnnotationInfo ); procedure OnAnnotationCalloutClick( sender: TObject; AnnotationView: MKAnnotationView; Annotation: MKAnnotation; AnnotationInfo: PAnnotationInfo ); protected procedure PaintRects( const UpdateRects: array of TRectF ); override; public { Public declarations } end; var FMapView: TFMapView; implementation {$R *.fmx} procedure TFMapView.DPFApplicationManager1MemoryWarning( Sender: TObject ); begin DPFLabelLocation.Text := 'Low Memory'; end; procedure TFMapView.DPFButton1Click( Sender: TObject ); var Polys: TArray<CLLocationCoordinate2D>; begin setLength( Polys, 4 ); Polys[0].latitude := 35.738362; Polys[0].longitude := 51.402916; Polys[1].latitude := 35.738745; Polys[1].longitude := 51.408387; Polys[2].latitude := 35.731185; Polys[2].longitude := 51.408355; Polys[3].latitude := 35.734268; Polys[3].longitude := 51.402422; Circle := DPFMapView1.AddCircle( 35.735775, 51.405775, 100, TAlphaColors.Blue, TAlphaColors.Darkblue, 5, 0.2, 'Circle Title', 'Circle SubTitle' ); Polyline := DPFMapView1.AddPolyLine( Polys, TAlphaColors.Red, TAlphaColors.Black, 20, 0.6, 'Polyline Title', 'Polyline Sub Title' ); setLength( Polys, 4 ); Polys[0].latitude := 35.735313; Polys[0].longitude := 51.404461; Polys[1].latitude := 35.735766; Polys[1].longitude := 51.40725; Polys[2].latitude := 35.733659; Polys[2].longitude := 51.406735; Polys[3].latitude := 35.733798; Polys[3].longitude := 51.404632; Polygon := DPFMapView1.AddPolygon( Polys, TAlphaColors.Yellow, TAlphaColors.Red, 10, 0.6, 'Polygon Title', 'Polygon Sub Title' ); Marker1 := DPFMapView1.AddAnnotation( 'Iran', 'Tehran - Asad Abadi SQ.', 35.737177, 51.405807, 15, '', true, 1.0, pcRed, 'flag_iran.png', 'flag_iran.png', true, true ); Marker2 := DPFMapView1.AddAnnotation( 'Iran', 'Tehran - Traffic Zone!', 35.736202, 51.403280, 15, 'TagStr 2', false, 1.0, pcGreen, 'trafficlight_on.png', 'flag_iran.png', true, true ); end; procedure TFMapView.DPFButton2Click( Sender: TObject ); begin DPFMapView1.RemoveAnnotation( Marker1 ); DPFMapView1.RemoveAnnotation( Marker2 ); DPFMapView1.RemoveOverlay( Circle ); DPFMapView1.RemoveOverlay( Polyline ); DPFMapView1.RemoveOverlay( Polygon ); end; procedure TFMapView.DPFButton3Click( Sender: TObject ); begin DPFMapView1.ZoomLevel := DPFMapView1.ZoomLevel + 1; end; procedure TFMapView.DPFButton4Click( Sender: TObject ); begin DPFMapView1.ZoomLevel := DPFMapView1.ZoomLevel - 1; end; procedure TFMapView.DPFMapView1DidUpdateUserLocation( sender: TObject; Location: TDPFLocation ); begin DPFLabelSpeed.Text := 'Speed: ' + FormatFloat( '0.00', Location.speed ); DPFLabelLocation.Text := 'Loc: ' + FormatFloat( '0.000000', Location.latitude ) + ' - ' + FormatFloat( '0.000000', Location.longitude ); end; procedure TFMapView.DPFMapView1ZoomChanged( sender: TObject ); begin DPFLabel1.Text := FloatToStr( DPFMapView1.ZoomLevel ); end; procedure TFMapView.FormCreate( Sender: TObject ); begin DPFMapView1.OnPolygonClick := OnPolygonClick; DPFMapView1.OnPolylineClick := OnPolylineClick; DPFMapView1.OnCircleClick := OnCircleClick; DPFMapView1.OnAnnotationClick := OnAnnotationClick; DPFMapView1.OnAnnotationCalloutClick := OnAnnotationCalloutClick; end; procedure TFMapView.FormShow( Sender: TObject ); begin DPFLabel1.Text := FloatToStr( DPFMapView1.ZoomLevel ); end; procedure TFMapView.OnAnnotationCalloutClick( sender: TObject; AnnotationView: MKAnnotationView; Annotation: MKAnnotation; AnnotationInfo: PAnnotationInfo ); var tagStr: string; begin tagStr := ''; if assigned( AnnotationInfo ) then tagStr := AnnotationInfo^.TagStr; ShowAlert( 'call out Clicked on : ' + UTF8ToString( Annotation.title.UTF8String ) + ', ' + AnnotationInfo^.TagStr ); end; procedure TFMapView.OnAnnotationClick( sender: TObject; AnnotationView: MKAnnotationView; Annotation: MKAnnotation; AnnotationInfo: PAnnotationInfo ); var tagStr: string; begin tagStr := ''; if assigned( AnnotationInfo ) then tagStr := AnnotationInfo^.TagStr; ShowAlert( 'Clicked on : ' + UTF8ToString( Annotation.title.UTF8String ) + ', ' + TagStr ); end; procedure TFMapView.OnCircleClick( sender: TObject; CircleView: MKCircleView; Circle: MKCircle ); begin ShowAlert( 'Clicked on : ' + UTF8ToString( Circle.title.UTF8String ) ); end; procedure TFMapView.OnPolygonClick( sender: TObject; PolygonView: MKPolygonView; Polygon: MKPolygon ); begin ShowAlert( 'Clicked on : ' + UTF8ToString( Polygon.title.UTF8String ) ); end; procedure TFMapView.OnPolylineClick( sender: TObject; PolylineView: MKPolylineView; Polyline: MKPolyline ); begin ShowAlert( 'Clicked on : ' + UTF8ToString( Polyline.title.UTF8String ) ); end; procedure TFMapView.PaintRects( const UpdateRects: array of TRectF ); begin { } end; end.
unit vtNavigatorRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "VT" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/VT/vtNavigatorRes.pas" // Начат: 02.03.2010 17:58 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::VT::vtNavigator::vtNavigatorRes // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\VT\vtDefine.inc} interface uses l3StringIDEx ; var { Локализуемые строки TvtNavigatorHints } str_vtAutoHideOffHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtAutoHideOffHint'; rValue : 'Зафиксировать панель навигации'); { 'Зафиксировать панель навигации' } str_vtAutoHideOnHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtAutoHideOnHint'; rValue : 'Сворачивать панель навигации'); { 'Сворачивать панель навигации' } str_vtMinimazedOnHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMinimazedOnHint'; rValue : 'Свернуть'); { 'Свернуть' } str_vtMinimazedOffHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMinimazedOffHint'; rValue : 'Развернуть'); { 'Развернуть' } str_vtBtnCloseHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtBtnCloseHint'; rValue : 'Прикрепить навигатор'); { 'Прикрепить навигатор' } implementation uses l3MessageID ; initialization // Инициализация str_vtAutoHideOffHint str_vtAutoHideOffHint.Init; // Инициализация str_vtAutoHideOnHint str_vtAutoHideOnHint.Init; // Инициализация str_vtMinimazedOnHint str_vtMinimazedOnHint.Init; // Инициализация str_vtMinimazedOffHint str_vtMinimazedOffHint.Init; // Инициализация str_vtBtnCloseHint str_vtBtnCloseHint.Init; end.
unit REST.Social; interface uses System.Sysutils, System.Classes, System.JSON, IPPeerClient, REST.Client, REST.Authenticator.OAuth, REST.Response.Adapter, REST.types, idHTTP, IdSSL, IdSSLOpenSSL, System.Generics.Collections; type TCustomSocialBase = class(TObject) public procedure FromJson(aJson: string); virtual; procedure LoadFromJson(js: TJsonObject); virtual; procedure LoadFromJsonFile(sFile: string); virtual; end; TCustomSocialAuthBase = class(TCustomSocialBase) private FAccessToken: string; FClient_ID: string; FClient_Secret: string; procedure SetAccessToken(const Value: string); procedure SetClient_ID(const Value: string); procedure SetClient_Secret(const Value: string); public procedure LoadFromJson(js: TJsonObject); override; published property AccessToken: string read FAccessToken write SetAccessToken; property Client_ID: string read FClient_ID write SetClient_ID; property Client_Secret: string read FClient_Secret write SetClient_Secret; end; TRESTSocialClient = class(TRESTClient) private FResource : string; FAuth2: TOAuth2Authenticator; RESTRequest1: TRESTRequest; RESTResponse1: TRESTResponse; FResponseText: string; FOnResponseTextChange: TNotifyEvent; function GetAccessToken: string; function send(url: string; AResource: string; AMethod: TRESTRequestMethod): string; procedure SetAccessToken(const Value: string); function GetResource: string; procedure SetResource(const Value: string); function GetRequestMethod: TRESTRequestMethod; procedure SetRequestMethod(const Value: TRESTRequestMethod); procedure SetResponseText(const Value: string); procedure SetOnResponseTextChange(const Value: TNotifyEvent); function GetParameterByName(AName: string): TRESTRequestParameter; procedure SetParameterByName(AName: string; const AValue: TRESTRequestParameter); protected public StatusCode: Integer; constructor create(ow: TComponent); override; destructor destroy; override; procedure Clear; virtual; function GetAuth2: TOAuth2Authenticator; virtual; property ParameterByName[AName: string]: TRESTRequestParameter read GetParameterByName write SetParameterByName; // configuração de acesso ao servidor property ResponseText: string read FResponseText write SetResponseText; function Get(url: string; AResource,AService: string): string; overload; virtual; function Get(AService:String=''): string; overload; virtual; function GetStream(AUrl: string; AResource: string; AStream: TStream) : Integer; virtual; function Post(url: string; AResource,AService: string): string; overload; virtual; function Post(AService:string): string; overload; virtual; function GetRequest: TRESTRequest; virtual; function GetResponse: TRESTResponse; virtual; function SendStream(AUrl, AResource: string; AStream: TStream) : Integer; virtual; procedure Execute; published property BaseURL; property Resource: string read GetResource write SetResource; property RequestMethod: TRESTRequestMethod read GetRequestMethod write SetRequestMethod; property OnResponseTextChange: TNotifyEvent read FOnResponseTextChange write SetOnResponseTextChange; property Request: TRESTRequest read GetRequest; property Response: TRESTResponse read GetResponse; property AccessToken: string read GetAccessToken write SetAccessToken; end; function Indy_Send_File(ACommand: string; AccessToken, AFileName, ADPFileName: string): Integer; overload; function Indy_Download_File(AccessToken: string; const exportLinks: string; AStream: System.Classes.TStream; FSSL: boolean): Integer; implementation function Indy_Download_File(AccessToken: string; const exportLinks: string; AStream: System.Classes.TStream; FSSL: boolean): Integer; var res: String; LidHTTP: TIdHttp; link: string; begin LidHTTP := TIdHttp.create(nil); try // add authorization from stored key LidHTTP.Request.CustomHeaders.Values['Authorization'] := 'Bearer ' + AccessToken; // use SSL if FSSL then LidHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.create(LidHTTP); try AStream.Position := 0; LidHTTP.Get(exportLinks, AStream); result := LidHTTP.Response.ResponseCode; except // on E: Exception do begin // rezultat_String.Add ('Eroare ! ' + E.Message); // end; raise; end; AStream.Position := 0; // Stream.SaveToFile(file_name) finally LidHTTP.Free; // Stream.Free; end; end; function Indy_Send_File_Stream(AccessToken, AUrl: string; AStream: TStream; ASSL: boolean; var AResponseText: string): Integer; overload; var LidHTTP: TIdHttp; begin LidHTTP := TIdHttp.create(nil); try LidHTTP.Request.CustomHeaders.Values['Authorization'] := 'Bearer ' + AccessToken; LidHTTP.Request.ContentType := 'application/octet-stream'; // LIdHttp.Request.CustomHeaders.Values['Dropbox-API-Arg'] := '{ "path":"/apps/tete.pdf", "mode":"add","autorename": true, "mute": false }'; if ASSL then LidHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.create(LidHTTP); AStream.Position := 0; try LidHTTP.Put(AUrl + '', AStream); except end; AResponseText := LidHTTP.Response.ResponseText; result := LidHTTP.ResponseCode; finally LidHTTP.Free; end; end; function Indy_Send_File(ACommand: string; AccessToken, AFileName, ADPFileName: string): Integer; overload; var AStream: TFileStream; rsp: string; cmd: string; begin cmd := ACommand + ADPFileName; AStream := TFileStream.create(AFileName, fmOpenRead); try result := Indy_Send_File_Stream(AccessToken, cmd, AStream, true, rsp); finally AStream.Free; end; end; { ****************************** TCustomSocialBase ******************************* } procedure TCustomSocialBase.FromJson(aJson: string); var js: TJsonObject; begin js := TJsonObject.ParseJSONValue(aJson) as TJsonObject; try LoadFromJson(js); finally js.Free; end; end; procedure TCustomSocialBase.LoadFromJson(js: TJsonObject); begin // abstract; end; procedure TCustomSocialBase.LoadFromJsonFile(sFile: string); var str: TstringList; js: TJsonObject; begin str := TstringList.create; try str.LoadFromFile(sFile); FromJson(str.text); finally str.Free; end; end; { **************************** TCustomSocialAuthBase ***************************** } procedure TCustomSocialAuthBase.LoadFromJson(js: TJsonObject); begin inherited; js.TryGetValue<string>('Access_Token', FAccessToken); js.TryGetValue<string>('Client_ID', FClient_ID); js.TryGetValue<string>('Client_Secret', FClient_Secret); end; procedure TCustomSocialAuthBase.SetAccessToken(const Value: string); begin FAccessToken := Value; end; procedure TCustomSocialAuthBase.SetClient_ID(const Value: string); begin FClient_ID := Value; end; procedure TCustomSocialAuthBase.SetClient_Secret(const Value: string); begin FClient_Secret := Value; end; { TRESTClientDropBox } { ****************************** TRESTSocialClient ******************************* } constructor TRESTSocialClient.create(ow: TComponent); begin inherited; FAuth2 := TOAuth2Authenticator.create(self); RESTResponse1 := TRESTResponse.create(self); RESTResponse1.Name := 'ResponseInternal'; RESTResponse1.ContentType := 'application/json'; RESTRequest1 := TRESTRequest.create(self); RESTRequest1.Name := 'RequestInternal'; RESTRequest1.Client := self; RESTRequest1.Response := RESTResponse1; Authenticator := FAuth2; Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,'; AcceptCharset := 'UTF-8, *;q=0.8'; HandleRedirects := true; RaiseExceptionOn500 := false; end; destructor TRESTSocialClient.destroy; begin FAuth2.Free; inherited; end; procedure TRESTSocialClient.Execute; begin RESTRequest1.Execute; ResponseText := RESTResponse1.Content; end; function TRESTSocialClient.GetAuth2: TOAuth2Authenticator; begin result := FAuth2; end; function TRESTSocialClient.GetParameterByName( AName: string): TRESTRequestParameter; begin result:= RESTRequest1.Params.ParameterByName(AName); end; procedure TRESTSocialClient.Clear; begin RESTRequest1.Params.Clear; RESTRequest1.SynchronizedEvents := false; end; function TRESTSocialClient.Get(url: string; AResource,AService: string): string; begin result := send(url, AResource+AService, TRESTRequestMethod.rmGET); end; function TRESTSocialClient.Get(AService:String=''): string; begin result := Get(BaseURL, Resource, AService); end; function TRESTSocialClient.GetAccessToken: string; begin result := FAuth2.AccessToken; end; function TRESTSocialClient.GetRequestMethod: TRESTRequestMethod; begin result := RESTRequest1.Method; end; function TRESTSocialClient.GetResource: string; begin result := FResource; end; function TRESTSocialClient.GetStream(AUrl: string; AResource: string; AStream: TStream): Integer; begin result := Indy_Download_File(AccessToken, AUrl + AResource, AStream, true); end; function TRESTSocialClient.Post(AService:string): string; begin result := Post(BaseURL, Resource, AService); end; function TRESTSocialClient.Post(url: string; AResource,AService: string): string; begin result := send(url, AResource, TRESTRequestMethod.rmPost); end; function TRESTSocialClient.GetRequest: TRESTRequest; begin result := RESTRequest1; end; function TRESTSocialClient.GetResponse: TRESTResponse; begin result := RESTResponse1; end; function TRESTSocialClient.send(url: string; AResource: string; AMethod: TRESTRequestMethod): string; begin RESTRequest1.Method := AMethod; RESTRequest1.Resource := AResource; BaseURL := url; RESTRequest1.Execute; ResponseText := RESTResponse1.Content; result := ResponseText; StatusCode := RESTResponse1.StatusCode; end; function TRESTSocialClient.SendStream(AUrl, AResource: string; AStream: TStream): Integer; var rst: String; begin result := Indy_Send_File_Stream(AccessToken, AUrl + AResource, AStream, true, rst); ResponseText := rst; end; procedure TRESTSocialClient.SetAccessToken(const Value: string); begin FAuth2.AccessToken := Value; end; procedure TRESTSocialClient.SetOnResponseTextChange(const Value: TNotifyEvent); begin FOnResponseTextChange := Value; end; procedure TRESTSocialClient.SetParameterByName(AName: string; const AValue: TRESTRequestParameter); var lcl:TRESTRequestParameter; begin lcl := RESTRequest1.Params.ParameterByName(AName); if assigned(lcl) then with lcl do begin Name := AValue.name; Value := AValue.Value; Kind := AValue.Kind; Options := AValue.Options; ContentType := AValue.ContentType; DisplayName := AValue.DisplayName; end; end; procedure TRESTSocialClient.SetRequestMethod(const Value: TRESTRequestMethod); begin RESTRequest1.Method := Value; end; procedure TRESTSocialClient.SetResource(const Value: string); begin FResource := Value; RESTRequest1.Resource := Value; end; procedure TRESTSocialClient.SetResponseText(const Value: string); begin FResponseText := Value; if assigned(FOnResponseTextChange) then FOnResponseTextChange(self); end; end.
unit Types interface type TIntegerArray = Array of Integer; TNode = record name: String; idx: Integer; edges: TNodeArray; procedure Init(const aName: Integer; const aEdges: TNodeArray); end; TNodeArray = Array of TNode; implementation end.
unit l3IString; { $Id: l3IString.pas,v 1.1 2011/07/08 13:14:39 fireton Exp $ } // $Log: l3IString.pas,v $ // Revision 1.1 2011/07/08 13:14:39 fireton // - работа с IString // interface uses l3Interfaces, l3Types, l3Base, IOUnit ; type Tl3IString = class(Tl3CustomString, Il3CString) private // internal fields f_String : IString; protected // internal methods class function IsCacheable: Bool; override; {-} function GetAsPCharLen: Tl3PCharLenPrim; override; {-} procedure Cleanup; override; {-} public // public methods constructor Create(const aString: IString); reintroduce; {-} procedure Insert(const aSt : Tl3PCharLenPrim; aPos : Long; aRepeat : Long = 1); override; {* - вставляет строку aSt в позицию aPos, aRepeat раз. } end;//Tl3IString Tl3ConstIString = class(Tl3IString) public // public methods class function MakeI(const aStr: IString): Il3CString; {-} end;//Tl3ConstIString function l3CStr(const aString: IString): Il3CString; overload; implementation uses l3String ; function l3CStr(const aString: IString): Il3CString; //overload; begin Result := Tl3ConstIString.MakeI(aString); end; // start class Tl3IString constructor Tl3IString.Create(const aString: IString); //reintroduce; {-} begin inherited Create; f_String := aString; end; procedure Tl3IString.Insert(const aSt : Tl3PCharLenPrim; aPos : Long; aRepeat : Long = 1); //override; {* - вставляет строку aSt в позицию aPos, aRepeat раз. } begin Assert(false); end; procedure Tl3IString.Cleanup; //override; {-} begin f_String := nil; inherited; end; class function Tl3IString.IsCacheable: Bool; //override; {-} begin Result := true; end; function Tl3IString.GetAsPCharLen: Tl3PCharLenPrim; //override; {-} begin if (f_String = nil) then l3AssignNil(Result) else Result := l3PCharLen(f_String.GetData, f_String.GetLength, f_String.GetCodePage); end; class function Tl3ConstIString.MakeI(const aStr: IString): Il3CString; {-} var l_S : Tl3ConstIString; begin l_S := Create(aStr); try Result := l_S; finally l3Free(l_S); end;//try..finally end; end.
unit MarqueeCtrl; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; const cidxBack = 0; cidxFore = 1; cidxGrill = 2; cidxLight = 3; type TFadeDirection = (fdUp, fdDown); type TMarquee = class(TCustomControl) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; private fBitmap : TBitmap; fMarqueeText : string; fCacheText : string; //TStringList; fMarqueeWidth : integer; fTextHeight : integer; fOffset : integer; fGap : integer; fStep : integer; fBackColor : TColor; fForeColor : TColor; fShowGrill : boolean; fClickStop : boolean; fStoped : boolean; fLeftMargin : integer; fTopBorder : integer; fRaiseText : boolean; fDirection : TFadeDirection; fDigitalize : boolean; fLastX : integer; fLastY : integer; fIsCaption : boolean; private function MatchStrings(text1, text2 : string; maxDeltaPerc : byte) : boolean; procedure SetBmpPalette; procedure DigitalizeBmp; procedure AcceptText(text : string); protected procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure Paint; override; procedure Loaded; override; procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure WMHitTest(var Message : TMessage); message WM_NCHITTEST; public procedure Tick; private procedure SetMarqueeText(text : string); procedure SetBackColor(Color : TColor); procedure SetForeColor(Color : TColor); published property Caption : string read fMarqueeText write SetMarqueeText; property Gap : integer read fGap write fGap; property Step : integer read fStep write fStep; property ShowGrill : boolean read fShowGrill write fShowGrill; property BackColor : TColor read fBackColor write SetBackColor; property ForeColor : TColor read fForeColor write SetForeColor; property ClickStop : boolean read fClickStop write fClickStop; property LeftMargin : integer read fLeftMargin write fLeftMargin; property Direction : TFadeDirection read fDirection write fDirection; property Digitalize : boolean read fDigitalize write fDigitalize; property IsCaption : boolean read fIsCaption write fIsCaption; property Align; property DragCursor; property DragMode; property Enabled; property Font; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation uses MathUtils, CompStringsParser; // TMarquee constructor TMarquee.Create(AOwner: TComponent); begin inherited; //fCacheText := TStringList.Create; fBitmap := TBitmap.Create; fBitmap.PixelFormat := pf8bit; Width := 200; Height := 50; fGap := 50; fStep := 2; fBackColor := clBlack; fBackColor := clWhite; fShowGrill := true; end; destructor TMarquee.Destroy; begin //fCacheText.Free; fBitmap.Free; inherited; end; function TMarquee.MatchStrings(text1, text2 : string; maxDeltaPerc : byte) : boolean; var maxLen : integer; minLen : integer; mrqLen : integer; chLen : integer; aux : string; p : integer; wCount : integer; fCount : integer; begin mrqLen := length(text1); chLen := length(text2); maxLen := max(mrqLen, chLen); minLen := min(mrqLen, chLen); if maxLen - minLen < maxLen*maxDeltaPerc/100 then begin p := 1; wCount := 0; fCount := 0; repeat aux := CompStringsParser.GetNextStringUpTo(text1, p, ' '); inc(wCount); if pos(aux, text1) <> 0 then inc(fCount); until not CompStringsParser.SkipChar(text1, p, ' '); result := fCount/wCount > 0.6; end else result := false; end; procedure TMarquee.SetBmpPalette; type TRGB = packed record Blue : byte; Green : byte; Red : byte; Unk : byte; end; var pal : PLogPalette; rgb1 : TRGB; rgb2 : TRGB; hpal : HPALETTE; i : integer; begin GetMem(pal, sizeof(TLogPalette) + 3*sizeof(TPaletteEntry)); pal.palVersion := $300; pal.palNumEntries := 3; // I hate this... i := cidxBack; pal.palPalEntry[i] := TPaletteEntry(fBackColor); i := cidxFore; pal.palPalEntry[i] := TPaletteEntry(fForeColor); rgb1 := TRGB(fBackColor); rgb2 := TRGB(fForeColor); rgb1.Blue := (rgb1.Blue + 2*rgb2.Blue) div 3; rgb1.Green := (rgb1.Green + 2*rgb2.Green) div 3; rgb1.Red := (rgb1.Red + 2*rgb2.Red) div 3; i := cidxGrill; pal.palPalEntry[i] := TPaletteEntry(rgb1); hpal := CreatePalette(pal^); fBitmap.Palette := hpal; freemem(pal); end; procedure TMarquee.DigitalizeBmp; var i, j : integer; line : PByteArray; begin for i := 0 to pred(fBitmap.Height) do begin line := fBitmap.ScanLine[i]; if i mod 2 = 0 then for j := 0 to pred(fBitmap.Width) do if (j mod 2 = 0) and (fShowGrill or (line[j] = cidxFore)) then line[j] := cidxGrill; { else for j := 0 to pred(fBitmap.Width) do if (j mod 2 <> 0) and (fShowGrill or (line[j] = cidxFore)) then line[j] := cidxGrill; } end; end; procedure TMarquee.AcceptText(text : string); begin fMarqueeText := text; fMarqueeWidth := fBitmap.Canvas.TextWidth(fMarqueeText); fTextHeight := fBitmap.Canvas.TextHeight(fMarqueeText); Hint := text; fRaiseText := false; end; procedure TMarquee.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited; fBitmap.Width := aWidth; fBitmap.Height := aHeight; end; procedure TMarquee.Paint; var R : TRect; offs : integer; y : integer; flag : boolean; begin if fRaiseText then y := fTopBorder else y := (Height - fTextHeight) div 2; R := ClientRect; fBitmap.Canvas.Brush.Color := fBackColor; fBitmap.Canvas.Brush.Style := bsSolid; fBitmap.Canvas.FillRect(R); fBitmap.Canvas.Font.Color := fForeColor; flag := (Width > fMarqueeWidth) or fRaiseText; offs := fOffset; repeat fBitmap.Canvas.TextOut(offs, y, fMarqueeText); inc(offs, fMarqueeWidth + fGap); until flag or (offs > Width); if fDigitalize then DigitalizeBmp; Canvas.CopyRect(R, fBitmap.Canvas, R); end; procedure TMarquee.Loaded; begin //AcceptText(fMarqueeText); fOffset := Width; end; procedure TMarquee.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TMarquee.CMFontChanged(var Message: TMessage); begin fBitmap.Canvas.Font := Font; fMarqueeWidth := Canvas.TextWidth(fMarqueeText); fTextHeight := Canvas.TextHeight(fMarqueeText); end; procedure TMarquee.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin fLastX := X; fLastY := Y; fStoped := not fStoped; end; procedure TMarquee.MouseMove(Shift: TShiftState; X, Y: Integer); var deltaX : integer; begin if ssLeft in Shift then begin deltaX := X - fLastX; fLastX := X; if abs(deltaX) > 1 then begin if fMarqueeWidth > Width - fLeftMargin then fOffset := min(Width, fOffset + deltaX) else fOffset := max(fLeftMargin, fOffset + deltaX); Refresh; fStoped := true; end; end; end; procedure TMarquee.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin end; procedure TMarquee.WMHitTest(var Message : TMessage); begin if fIsCaption then Message.Result := HTTRANSPARENT else inherited; end; procedure TMarquee.Tick; begin if not fStoped then begin if fMarqueeWidth > Width - fLeftMargin then begin if fMarqueeWidth + fOffset < 0 then fOffset := fGap; dec(fOffset, fStep); end else fOffset := max(fLeftMargin, fOffset - fStep); if fRaiseText then begin if fDirection = fdUp then begin dec(fTopBorder, 2); fRaiseText := fTopBorder + fTextHeight > 0; end else begin inc(fTopBorder, 2); fRaiseText := fTopBorder < Height; end; if not fRaiseText then begin AcceptText(fCacheText); fOffset := Width; end; end; Refresh; end; end; procedure TMarquee.SetMarqueeText(text : string); var match : boolean; begin if csDesigning in ComponentState then begin AcceptText(text); fOffset := fLeftMargin; end else begin if fRaiseText then fCacheText := text else begin match := MatchStrings(fMarqueeText, text, 10); if not fStoped and not match then begin fTopBorder := (Height - fTextHeight) div 2; fCacheText := text; fRaiseText := true; end else begin AcceptText(text); if not match and fStoped and (fOffset < fLeftMargin) then fOffset := fLeftMargin; end; end; end; Refresh; end; procedure TMarquee.SetBackColor(Color : TColor); begin fBackColor := Color; SetBmpPalette; Refresh; end; procedure TMarquee.SetForeColor(Color : TColor); begin fForeColor := Color; SetBmpPalette; Refresh; end; procedure Register; begin RegisterComponents('Five', [TMarquee]); end; end.
unit Startup; interface uses IdHTTPWebBrokerBridge, System.SysUtils, MVCFramework.Logger, MVCFramework.Commons, MVCFramework.REPLCommandsHandlerU; type TStartup = class public class procedure RunServer(Port: Integer); static; end; implementation class procedure TStartup.RunServer(Port: Integer); var server: TIdHTTPWebBrokerBridge; customHandler: TMVCCustomREPLCommandsHandler; command: string; begin Writeln('DMVCFramework Server - Build: ' + DMVCFRAMEWORK_VERSION); if ParamCount >= 1 then command := ParamStr(1) else command := 'Start'; customHandler := function(const Value: String; const server: TIdHTTPWebBrokerBridge; out Handled: Boolean): THandleCommandResult begin Handled := False; Result := THandleCommandResult.Unknown; end; server := TIdHTTPWebBrokerBridge.Create(nil); try server.DefaultPort := Port; server.MaxConnections := 0; server.ListenQueue := 200; Writeln('Digite "quit" or "exit" para finalizar o servidor'); repeat if command.IsEmpty then begin Write(''); ReadLn(command) end; try case HandleCommand(command.ToLower, server, customHandler) of THandleCommandResult.Continue: begin Continue; end; THandleCommandResult.Break: begin Break; end; THandleCommandResult.Unknown: begin REPLEmit('Comando desconhecido: ' + command); end; end; finally command := ''; end; until False; finally server.Free; end; end; end.
program Demo3; {$APPTYPE CONSOLE} var i: Integer; begin i := 0; while i < 10 do begin WriteLn('Hello ', i); Inc(i); end; end.
Unit fpc_jemalloc; Interface {$LINKLIB jemalloc} const LibName = 'libjemalloc'; Function je_malloc(Size: ptruint): Pointer; cdecl; external LibName name 'je_malloc'; Procedure je_free(P: Pointer); cdecl; external LibName name 'je_free'; Function je_realloc(P: Pointer; Size: ptruint): Pointer; cdecl; external LibName name 'je_realloc'; Implementation type pptruint = ^ptruint; Function JEGetMem(Size: ptruint): Pointer; begin JEGetMem := je_malloc(Size + sizeof(ptruint)); if JEGetMem <> nil then begin pptrint(JEGetMem)^ := Size; Inc(JEGetMem, sizeof(ptruint)); end; end; Function JEFreeMem(P: Pointer): ptruint; begin if P <> nil then Dec(P, sizeof(ptruint)); je_free(P); JEFreeMem := 0; end; Function JEFreeMemSize(P: Pointer; Size: ptruint): ptruint; begin if Size <= 0 then begin if Size = 0 then exit; runerror(204); end; if P <> nil then begin if Size <> pptruint(P - sizeof(ptruint))^ then runerror(204); end; JEFreeMemSize := JEFreeMem(P); end; Function JEAllocMem(Size: ptruint): Pointer; var TotalSize: ptruint; begin TotalSize := Size + sizeof(ptruint); JEAllocMem := je_malloc(TotalSize); if JEAllocMem <> nil then begin FillByte(JEAllocMem, TotalSize, 0); pptruint(JEAllocMem)^ := Size; Inc(JEAllocMem, sizeof(ptruint)); end; end; Function JEReAllocMem(var P: Pointer; Size: ptruint): Pointer; begin if Size = 0 then begin if P <> Nil then begin Dec(P, sizeof(ptruint)); je_free(P); P := nil; end; end else begin Inc(Size, sizeof(ptruint)); if P = nil then P := je_malloc(Size) else begin Dec(P, sizeof(ptruint)); P := je_realloc(P, Size); end; if P <> nil then begin pptruint(P)^ := Size - sizeof(ptruint); Inc(P, sizeof(ptruint)); end; end; JEReAllocMem := P; end; Function JEMemSize(P: Pointer): ptruint; begin JEMemSize := pptruint(P - sizeof(ptruint))^; end; { TODO } Function JEGetHeapStatus: THeapStatus; begin FillChar(JEGetHeapStatus, sizeof(JEGetHeapStatus), 0); end; Function JEGetFPCHeapStatus: TFPCHeapStatus; begin FillChar(JEGetFPCHeapStatus, sizeof(JEGetHeapStatus), 0); end; const JEMemoryManager: TMemoryManager = ( NeedLock: false (* TODO: verify *); GetMem: @JEGetMem; FreeMem: @JEFreeMem; FreeMemSize: @JEFreeMemSize; AllocMem: @JEAllocMem; ReAllocMem: @JEReAllocMem; MemSize: @JEMemSize; InitThread: Nil; DoneThread: Nil; RelocateHeap: Nil; GetHeapStatus: @JEGetHeapStatus; GetFPCHeapStatus: @JEGetFPCHeapStatus; ); var PreviousMemoryManager: TMemoryManager; Initialization GetMemoryManager(PreviousMemoryManager); SetMemoryManager(JEMemoryManager); Finalization SetMemoryManager(PreviousMemoryManager); end.
unit clAbastecimentos; interface uses System.Classes, clConexao; type TAbastecimentos = Class(TObject) private function getCupom: String; function getData: TDateTime; function getEntregador: Integer; function getManutencao: TDateTime; function getNumero: Integer; function getPlaca: String; function getProduto: String; function getQuantidade: Double; function getTotal: Double; function getUnitario: Double; function getExecutante: String; function getDescontado: String; function getExtrato: Integer; function getDesconto: Double; function getVerba: Double; function getBase: TDate; procedure setCupom(const Value: String); procedure setData(const Value: TDateTime); procedure setEntregador(const Value: Integer); procedure setExecutante(const Value: String); procedure setManutencao(const Value: TDateTime); procedure setNumero(const Value: Integer); procedure setPlaca(const Value: String); procedure setProduto(const Value: String); procedure setQuantidade(const Value: Double); procedure setUnitario(const Value: Double); procedure setDescontado(const Value: String); procedure setTotal(const Value: Double); procedure setExtrato(const Value: Integer); procedure setDesconto(const Value: Double); procedure setVerba(const Value: Double); procedure setBase(const Value: TDate); function getNome: String; procedure setNome(const Value: String); function getControle: Integer; procedure setControle(const Value: Integer); protected _numero: Integer; _cupom: String; _entregador: Integer; _nome: String; _placa: String; _data: TDateTime; _produto: String; _quantidade: Double; _unitario: Double; _total: Double; _executante: String; _manutencao: TDateTime; _descontado: String; _extrato: Integer; _verba: Double; _desconto: Double; _base: TDateTime; _controle : Integer; _conexao: TConexao; public constructor Create; destructor Destroy; property Numero: Integer read getNumero write setNumero; property Cupom: String read getCupom write setCupom; property Entregador: Integer read getEntregador write setEntregador; property Nome: String read getNome write setNome; property Placa: String read getPlaca write setPlaca; property Data: TDateTime read getData write setData; property Produto: String read getProduto write setProduto; property Quantidade: Double read getQuantidade write setQuantidade; property Unitario: Double read getUnitario write setUnitario; property Total: Double read getTotal write setTotal; property Executante: String read getExecutante write setExecutante; property Manutencao: TDateTime read getManutencao write setManutencao; property Descontado: String read getDescontado write setDescontado; property Extrato: Integer read getExtrato write setExtrato; property Verba: Double read getVerba write setVerba; property Desconto: Double read getDesconto write setDesconto; property Base: TDate read getBase write setBase; property Controle: Integer read getControle write setControle; procedure MaxNum; function Validar(): Boolean; function Delete(filtro: String): Boolean; function DeletePeriodo(dtInicial, dtFinal: TDateTime): Boolean; function getObject(id, filtro: String): Boolean; function getObjects(): Boolean; function Insert(): Boolean; function Update(): Boolean; function getField(campo, coluna: String): String; function Periodo(sdatInicial, sdatFinal: String): Boolean; function TotalPeriodo(sdatInicial, sdatFinal, sEntregador: String): Double; function Fechar(sdatInicial, sdatFinal, sEntregador, sNumero: String; sTipo: String): Boolean; function Exist(): Boolean; function PopulaProdutos(filtro: string): TStringList; function ConsolidaAbastecimentos(sInicio: String; sTermino: String) : Boolean; end; const TABLENAME = 'TBABASTECIMENTO'; implementation { TAbastecimentos } uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB, uGlobais; constructor TAbastecimentos.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TAbastecimentos.Destroy; begin _conexao.Free; end; function TAbastecimentos.getBase: TDate; begin REsult := _base end; function TAbastecimentos.getCupom: String; begin REsult := _cupom; end; function TAbastecimentos.getData: TDateTime; begin REsult := _data; end; function TAbastecimentos.getEntregador: Integer; begin REsult := _entregador; end; function TAbastecimentos.getExecutante: String; begin REsult := _executante; end; function TAbastecimentos.getManutencao: TDateTime; begin REsult := _manutencao; end; function TAbastecimentos.getNome: String; begin REsult := _nome; end; function TAbastecimentos.getNumero: Integer; begin REsult := _numero; end; function TAbastecimentos.getPlaca: String; begin REsult := _placa; end; function TAbastecimentos.getProduto: String; begin REsult := _produto; end; function TAbastecimentos.getQuantidade: Double; begin REsult := _quantidade; end; function TAbastecimentos.getTotal: Double; begin REsult := _total; end; function TAbastecimentos.getUnitario: Double; begin REsult := _unitario; end; function TAbastecimentos.getExtrato: Integer; begin REsult := _extrato; end; function TAbastecimentos.getDesconto: Double; begin REsult := _desconto; end; function TAbastecimentos.getVerba: Double; begin REsult := _verba; end; function TAbastecimentos.getControle: Integer; begin Result := _controle; end; procedure TAbastecimentos.MaxNum; begin try dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Text := 'SELECT MAX(NUM_ABASTECIMENTO) AS NUMERO FROM ' + TABLENAME; dm.ZConn.PingServer; dm.QryGetObject.Open; if not(dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; end; Self.Numero := (dm.QryGetObject.FieldByName('NUMERO').AsInteger) + 1; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.Validar(): Boolean; var sValor1, sValor2: String; begin try sValor1 := ''; sValor2 := ''; REsult := False; if TUtil.Empty(Self.Cupom) then begin MessageDlg('Informe Número do Cupom!', mtWarning, [mbOK], 0); Exit; end else begin if StrToInt(Self.Cupom) = 0 then begin MessageDlg('Informe Número do Cupom!', mtWarning, [mbOK], 0); Exit; end; end; if TUtil.Empty(Self.Produto) then begin MessageDlg('Informe a Descrição do Abastecimento!', mtWarning, [mbOK], 0); Exit; end; if TUtil.Empty(Self.Placa) then begin MessageDlg('Informe a Placa do Veículo!', mtWarning, [mbOK], 0); Exit; end; if TUtil.Empty(DateToStr(Self.Data)) then begin MessageDlg('Informe a Data do Abastecimento!', mtWarning, [mbOK], 0); Exit; end; if TUtil.Empty(DateToStr(Self.Base)) then begin MessageDlg('Informe a Data Base do Abastecimento!', mtWarning, [mbOK], 0); Exit; end; if Self.Quantidade = 0 then begin MessageDlg('Informe a Quantidade do Abastecimento!', mtWarning, [mbOK], 0); Exit; end; if Self.Unitario = 0 then begin MessageDlg('Informe o Valor Unitário do Abastecimento!', mtWarning, [mbOK], 0); Exit; end; if Self.Total = 0 then begin MessageDlg('Informe o Valor Total do Abastecimento!', mtWarning, [mbOK], 0); Exit; end; sValor1 := FormatFloat(',0.00', Self.Total); sValor2 := FormatFloat(',0.00', (Self.Quantidade * Self.Unitario)); if sValor1 <> sValor2 then begin MessageDlg ('Verifique os Valores Unitário e Quantidade pois o Valor Total do Abastecimento está Incorreto!', mtWarning, [mbOK], 0); end; REsult := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.Delete(filtro: String): Boolean; begin try REsult := False; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'NUMERO' then begin dm.QryCRUD.SQL.Add('WHERE NUM_ABASTECIMENTO = :NUMERO'); dm.QryCRUD.ParamByName('NUMERO').AsInteger := Self.Numero; end else if filtro = 'CONTROLE' then begin dm.QryGetObject.SQL.Add('WHERE ID_CONTROLE = :CONTROLE'); dm.QryGetObject.ParamByName('CONTROLE').AsInteger := Self.Controle; end else if filtro = 'CUPOM' then begin dm.QryCRUD.SQL.Add('WHERE NUM_CUPOM = :CUPOM'); dm.QryCRUD.ParamByName('CUPOM').AsString := Self.Cupom; end else if filtro = 'ENTREGADOR' then begin dm.QryCRUD.SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); dm.QryCRUD.ParamByName('ENTREGADOR').AsInteger := Self.Entregador; end else if filtro = 'BASE' then begin dm.QryCRUD.SQL.Add('WHERE DAT_BASE = :BASE'); dm.QryCRUD.ParamByName('BASE').AsDate := Self.Base; end; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; REsult := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.DeletePeriodo(dtInicial, dtFinal: TDateTime): Boolean; begin try REsult := False; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Add('DELETE FROM ' + TABLENAME); dm.QryCRUD.SQL.Add('WHERE DAT_ABASTECIMENTO BETWEEN :INICIO AND :FINAL'); dm.QryCRUD.SQL.Add(' AND DOM_DESCONTO = ' + QuotedStr('N')); dm.QryCRUD.ParamByName('INICIO').AsDate := dtInicial; dm.QryCRUD.ParamByName('FINAL').AsDate := dtFinal; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; REsult := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.getObject(id, filtro: String): Boolean; begin try REsult := False; if TUtil.Empty(id) then begin if filtro <> 'CHAVE' then begin Exit; end; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'NUMERO' then begin dm.QryGetObject.SQL.Add('WHERE NUM_ABASTECIMENTO = :NUMERO'); dm.QryGetObject.ParamByName('NUMERO').AsInteger := StrToInt(id); end else if filtro = 'CONTROLE' then begin dm.QryGetObject.SQL.Add('WHERE ID_CONTROLE = :CONTROLE'); dm.QryGetObject.ParamByName('CONTROLE').AsInteger := StrToIntDef(id,0); end else if filtro = 'CUPOM' then begin dm.QryGetObject.SQL.Add('WHERE NUM_CUPOM = :CUPOM'); dm.QryGetObject.ParamByName('CUPOM').AsString := id; end else if filtro = 'PLACA' then begin dm.QryGetObject.SQL.Add('WHERE DES_PLACA = :PLACA'); dm.QryGetObject.ParamByName('PLACA').AsString := id; end else if filtro = 'ENTREGADOR' then begin dm.QryGetObject.SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); dm.QryGetObject.ParamByName('ENTREGADOR').AsInteger := StrToInt(id); end else if filtro = 'DATA' then begin dm.QryGetObject.SQL.Add('WHERE DAT_ABASTECIMENTO = :DATA'); dm.QryGetObject.ParamByName('DATA').AsDate := StrToDate(id); end else if filtro = 'CHAVE' then begin dm.QryGetObject.SQL.Add ('WHERE NUM_CUPOM = :CUPOM AND DES_PLACA = :PLACA AND ' + 'DAT_ABASTECIMENTO = :DATA AND DES_PRODUTO = :PRODUTO AND ' + 'FORMAT(QTD_ABASTECIMENTO,3) = :QTDE AND ' + 'FORMAT(VAL_UNITARIO,3) = :UNIDARIO ' + 'AND FORMAT(VAL_TOTAL,2) = :TOTAL AND DAT_BASE = ::BASE'); dm.QryGetObject.ParamByName('CUPOM').AsString := Self.Cupom; dm.QryGetObject.ParamByName('PLACA').AsString := Self.Placa; dm.QryGetObject.ParamByName('DATA').AsDate := Self.Data; dm.QryGetObject.ParamByName('PRODUTO').AsString := Copy(Self.Produto, 1, 30); dm.QryGetObject.ParamByName('QTDE').AsFloat := Self.Total; dm.QryGetObject.ParamByName('UNIDARIO').AsFloat := Self.Total; dm.QryGetObject.ParamByName('TOTAL').AsFloat := Self.Total; dm.QryGetObject.ParamByName('BASE').AsDate := Self.Base; end; dm.ZConn.PingServer; dm.QryGetObject.Open; if (not dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; end; if dm.QryGetObject.RecordCount > 0 then begin Self.Numero := dm.QryGetObject.FieldByName('NUM_ABASTECIMENTO').AsInteger; Self.Cupom := dm.QryGetObject.FieldByName('NUM_CUPOM').AsString; Self.Entregador := dm.QryGetObject.FieldByName('COD_ENTREGADOR') .AsInteger; Self.Nome := dm.QryGetObject.FieldByName('NOM_ENTREGADOR').AsString; Self.Placa := dm.QryGetObject.FieldByName('DES_PLACA').AsString; Self.Data := dm.QryGetObject.FieldByName('DAT_ABASTECIMENTO').AsDateTime; Self.Produto := dm.QryGetObject.FieldByName('DES_PRODUTO').AsString; Self.Quantidade := dm.QryGetObject.FieldByName ('QTD_ABASTECIMENTO').AsFloat; Self.Unitario := dm.QryGetObject.FieldByName('VAL_UNITARIO').AsFloat; Self.Total := dm.QryGetObject.FieldByName('VAL_TOTAL').AsFloat; Self.Executante := dm.QryGetObject.FieldByName('NOM_EXECUTANTE').AsString; Self.Manutencao := dm.QryGetObject.FieldByName('DAT_MANUTENCAO') .AsDateTime; Self.Descontado := dm.QryGetObject.FieldByName('DOM_DESCONTO').AsString; Self.Verba := dm.QryGetObject.FieldByName ('VAL_VERBA_COMBUSTIVEL').AsFloat; Self.Desconto := dm.QryGetObject.FieldByName('VAL_DESCONTO').AsFloat; Self.Base := dm.QryGetObject.FieldByName('DAT_BASE').AsDateTime; Self.Controle := dm.QryGetObject.FieldByName('ID_controle').AsInteger; REsult := True; end else begin dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.Insert(): Boolean; begin try REsult := False; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'NUM_ABASTECIMENTO, ' + 'NUM_CUPOM, ' + 'DES_PLACA, ' + 'COD_ENTREGADOR, ' + 'NOM_ENTREGADOR, ' + 'DAT_ABASTECIMENTO, ' + 'DES_PRODUTO, ' + 'QTD_ABASTECIMENTO, ' + 'VAL_UNITARIO, ' + 'VAL_TOTAL, ' + 'VAL_VERBA_COMBUSTIVEL, ' + 'VAL_DESCONTO, ' + 'NOM_EXECUTANTE, ' + 'DAT_MANUTENCAO, ' + 'DOM_DESCONTO, ' + 'NUM_EXTRATO, ' + 'DAT_BASE, ' + 'ID_controle)' + 'VALUES (' + ':NUMERO, ' + ':CUPOM, ' + ':PLACA, ' + ':ENTREGADOR, ' + ':NOME, ' + ':DATA, ' + ':PRODUTO, ' + ':QUANTIDADE, ' + ':UNITARIO, ' + ':TOTAL, ' + ':VERBA, ' + ':DESCONTO, ' + ':EXECUTANTE, ' + ':MANUTENCAO, ' + ':DESCONTADO, ' + ':EXTRATO, ' + ':BASE, ' + ':CONTROLE)'; MaxNum; dm.QryCRUD.ParamByName('NUMERO').AsInteger := Self.Numero; dm.QryCRUD.ParamByName('CUPOM').AsString := Self.Cupom; dm.QryCRUD.ParamByName('ENTREGADOR').AsInteger := Self.Entregador; dm.QryCRUD.ParamByName('NOME').AsString := Self.Nome; dm.QryCRUD.ParamByName('PLACA').AsString := Self.Placa; dm.QryCRUD.ParamByName('DATA').AsDate := Self.Data; dm.QryCRUD.ParamByName('PRODUTO').AsString := Self.Produto; dm.QryCRUD.ParamByName('QUANTIDADE').AsFloat := Self.Quantidade; dm.QryCRUD.ParamByName('UNITARIO').AsFloat := Self.Unitario; dm.QryCRUD.ParamByName('TOTAL').AsFloat := Self.Total; dm.QryCRUD.ParamByName('VERBA').AsFloat := Self.Verba; dm.QryCRUD.ParamByName('DESCONTO').AsFloat := Self.Desconto; dm.QryCRUD.ParamByName('EXECUTANTE').AsString := Self.Executante; dm.QryCRUD.ParamByName('MANUTENCAO').AsDateTime := Self.Manutencao; dm.QryCRUD.ParamByName('DESCONTADO').AsString := Self.Descontado; dm.QryCRUD.ParamByName('EXTRATO').AsInteger := Self.Extrato; dm.QryCRUD.ParamByName('BASE').AsDate := Self.Base; dm.qryCRUD.ParamByName('CONTROLE').AsInteger := Self.Controle; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; REsult := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.Update(): Boolean; begin try REsult := False; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'NUM_CUPOM = :CUPOM, ' + 'COD_ENTREGADOR = :ENTREGADOR, ' + 'NOM_ENTREGADOR = :NOME, ' + 'DES_PLACA = :PLACA, ' + 'DAT_ABASTECIMENTO = :DATA, ' + 'DES_PRODUTO = :PRODUTO, ' + 'QTD_ABASTECIMENTO = :QUANTIDADE, ' + 'VAL_UNITARIO = :UNITARIO, ' + 'VAL_TOTAL = :TOTAL, ' + 'VAL_VERBA_COMBUSTIVEL = :VERBA, ' + 'VAL_DESCONTO = :DESCONTO, ' + 'NOM_EXECUTANTE = :EXECUTANTE, ' + 'DAT_MANUTENCAO = :MANUTENCAO, ' + 'DOM_DESCONTO = :DESCONTADO, ' + 'NUM_EXTRATO = :EXTRATO, ' + 'DAT_BASE = :BASE, ' + 'ID_CONTROLE := :CONTROLE ' + 'WHERE ' + 'NUM_ABASTECIMENTO = :NUMERO'; dm.QryCRUD.ParamByName('NUMERO').AsInteger := Self.Numero; dm.QryCRUD.ParamByName('CUPOM').AsString := Self.Cupom; dm.QryCRUD.ParamByName('ENTREGADOR').AsInteger := Self.Entregador; dm.QryCRUD.ParamByName('NOME').AsString := Self.Nome; dm.QryCRUD.ParamByName('PLACA').AsString := Self.Placa; dm.QryCRUD.ParamByName('DATA').AsDate := Self.Data; dm.QryCRUD.ParamByName('PRODUTO').AsString := Self.Produto; dm.QryCRUD.ParamByName('QUANTIDADE').AsFloat := Self.Quantidade; dm.QryCRUD.ParamByName('UNITARIO').AsFloat := Self.Unitario; dm.QryCRUD.ParamByName('TOTAL').AsFloat := Self.Total; dm.QryCRUD.ParamByName('VERBA').AsFloat := Self.Verba; dm.QryCRUD.ParamByName('DESCONTO').AsFloat := Self.Desconto; dm.QryCRUD.ParamByName('EXECUTANTE').AsString := Self.Executante; dm.QryCRUD.ParamByName('MANUTENCAO').AsDateTime := Self.Manutencao; dm.QryCRUD.ParamByName('DESCONTADO').AsString := Self.Descontado; dm.QryCRUD.ParamByName('EXTRATO').AsInteger := Self.Extrato; dm.QryCRUD.ParamByName('BASE').AsDate := Self.Base; dm.qryCRUD.ParamByName('CONTROLE').AsInteger := Self.Controle; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; REsult := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.getField(campo, coluna: String): String; begin try REsult := ''; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME; if coluna = 'NUMERO' then begin dm.QryGetObject.SQL.Add(' WHERE NUM_ABASTECIMENTO =:NUMERO '); dm.QryGetObject.ParamByName('NUMERO').AsInteger := Self.Numero; end else if coluna = 'CONTROLE' then begin dm.QryGetObject.SQL.Add(' WHERE ID_CONTROLE =:CONTROLE '); dm.QryGetObject.ParamByName('CONTROLE').AsInteger := Self.Controle; end else if coluna = 'CUPOM' then begin dm.QryGetObject.SQL.Add(' WHERE NUM_CUPOM =:CUPOM '); dm.QryGetObject.ParamByName('CUPOM').AsString := Self.Cupom; end else if coluna = 'DATA' then begin dm.QryGetObject.SQL.Add(' WHERE DAT_ABASTECIMENTO =:DATA '); dm.QryGetObject.ParamByName('DATA').AsDate := Self.Data; end else if coluna = 'ENTREGADOR' then begin dm.QryGetObject.SQL.Add(' WHERE COD_ENTREGADOR = :ENTREGADOR '); dm.QryGetObject.ParamByName('ENTREGADOR').AsInteger := Self.Entregador; end; dm.ZConn.PingServer; dm.QryGetObject.Open; if (not dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; end; if dm.QryGetObject.RecordCount > 0 then begin REsult := dm.QryGetObject.FieldByName(campo).AsString; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.Periodo(sdatInicial, sdatFinal: String): Boolean; begin try REsult := False; if TUtil.Empty(sdatInicial) then Exit; if TUtil.Empty(sdatFinal) then Exit; dm.qryGeral.Close; dm.qryGeral.SQL.Clear; dm.qryGeral.SQL.Add('SELECT * FROM ' + TABLENAME); dm.qryGeral.SQL.Add('WHERE DAT_ABASTECIMENTO BETWEEN :INICIO AND :FINAL '); dm.qryGeral.ParamByName('INICIO').AsDate := StrToDate(sdatInicial); dm.qryGeral.ParamByName('FINAL').AsDate := StrToDate(sdatFinal); dm.qryGeral.SQL.Add ('ORDER BY COD_ENTREGADOR, DAT_ABASTECIMENTO, DES_PLACA'); dm.ZConn.PingServer; dm.qryGeral.Open; if (not dm.qryGeral.IsEmpty) then begin dm.qryGeral.First; end else begin dm.qryGeral.Close; dm.qryGeral.SQL.Clear; Exit; end; REsult := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.TotalPeriodo(sdatInicial, sdatFinal, sEntregador: String): Double; begin try REsult := 0; if TUtil.Empty(sdatInicial) then begin Exit; end; if TUtil.Empty(sdatFinal) then begin Exit; end; if TUtil.Empty(sEntregador) then begin Exit; end; dm.qryCalculo.Close; dm.qryCalculo.SQL.Clear; dm.qryCalculo.SQL.Add('SELECT COD_ENTREGADOR, SUM(VAL_TOTAL) TOTAL FROM ' + TABLENAME); dm.qryCalculo.SQL.Add ('WHERE DAT_ABASTECIMENTO BETWEEN :INICIO AND :FINAL '); dm.qryCalculo.SQL.Add ('AND COD_ENTREGADOR = :ENTREGADOR AND DOM_DESCONTO <> :DESCONTADO'); dm.qryCalculo.ParamByName('INICIO').AsDate := StrToDate(sdatInicial); dm.qryCalculo.ParamByName('FINAL').AsDate := StrToDate(sdatFinal); dm.qryCalculo.ParamByName('ENTREGADOR').AsInteger := StrToInt(sEntregador); dm.qryCalculo.ParamByName('DESCONTADO').AsString := 'S'; dm.qryCalculo.SQL.Add('GROUP BY COD_ENTREGADOR'); dm.ZConn.PingServer; dm.qryCalculo.Open; if (not dm.qryCalculo.IsEmpty) then begin dm.qryCalculo.First; end else begin dm.qryCalculo.Close; dm.qryCalculo.SQL.Clear; Exit; end; REsult := dm.qryCalculo.FieldByName('TOTAL').AsFloat; dm.qryCalculo.Close; dm.qryCalculo.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.Fechar(sdatInicial, sdatFinal, sEntregador, sNumero: String; sTipo: String): Boolean; begin try REsult := False; if TUtil.Empty(sdatInicial) then begin Exit; end; if TUtil.Empty(sdatFinal) then begin Exit; end; if TUtil.Empty(sEntregador) then begin Exit; end; if TUtil.Empty(sNumero) then begin Exit; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Add('UPDATE ' + TABLENAME); dm.QryCRUD.SQL.Add('SET DOM_DESCONTO = :DESCONTADO, '); if sTipo = 'FECHAR' then begin dm.QryCRUD.SQL.Add('NUM_EXTRATO = :EXTRATO '); dm.QryCRUD.SQL.Add('WHERE DAT_ABASTECIMENTO <= :FINAL '); dm.QryCRUD.SQL.Add('AND COD_ENTREGADOR = :ENTREGADOR '); dm.QryCRUD.ParamByName('FINAL').AsDate := StrToDate(sdatFinal); dm.QryCRUD.ParamByName('ENTREGADOR').AsInteger := StrToInt(sEntregador); dm.QryCRUD.ParamByName('DESCONTADO').AsString := 'S'; dm.QryCRUD.ParamByName('EXTRATO').AsString := sNumero; end else begin dm.QryCRUD.SQL.Add('NUM_EXTRATO = "0" '); dm.QryCRUD.SQL.Add('WHERE NUM_EXTRATO = :EXTRATO '); dm.QryCRUD.SQL.Add('AND COD_ENTREGADOR = :ENTREGADOR '); dm.QryCRUD.ParamByName('ENTREGADOR').AsInteger := StrToInt(sEntregador); dm.QryCRUD.ParamByName('DESCONTADO').AsString := 'N'; dm.QryCRUD.ParamByName('EXTRATO').AsString := sNumero; end; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; REsult := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.Exist(): Boolean; begin try Result := False; Self.Numero := 0; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME); dm.QryGetObject.SQL.Add ('WHERE NUM_CUPOM = :CUPOM AND DES_PLACA = :PLACA AND ' + 'DAT_ABASTECIMENTO = :DATA AND DES_PRODUTO = :PRODUTO AND ' + 'QTD_ABASTECIMENTO = :QTDE AND ' + 'DAT_BASE = :BASE'); dm.QryGetObject.ParamByName('CUPOM').AsString := Self.Cupom; dm.QryGetObject.ParamByName('PLACA').AsString := Self.Placa; dm.QryGetObject.ParamByName('DATA').AsDate := Self.Data; dm.QryGetObject.ParamByName('PRODUTO').AsString := Self.Produto; dm.QryGetObject.ParamByName('QTDE').AsFloat := Self.Quantidade; dm.QryGetObject.ParamByName('BASE').AsDate := Self.Base; dm.ZConn.PingServer; dm.QryGetObject.Open; if dm.QryGetObject.IsEmpty then begin dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Exit; end; Self.Numero := dm.qryGetObject.FieldByName('NUM_ABASTECIMENTO').AsInteger; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; REsult := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.getObjects(): Boolean; begin try REsult := False; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; dm.QryGetObject.Open; if (not dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; REsult := True; end else begin dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TAbastecimentos.PopulaProdutos(filtro: string): TStringList; var lista: TStringList; campo: String; begin lista := TStringList.Create; REsult := lista; if filtro = 'PRODUTO' then begin campo := 'DES_PRODUTO'; end else begin Exit; end; dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; dm.qryPesquisa.SQL.Text := 'SELECT DISTINCT(' + campo + ') FROM ' + TABLENAME; dm.ZConn.PingServer; dm.qryPesquisa.Open; while (not dm.qryPesquisa.Eof) do begin lista.Add(dm.qryPesquisa.FieldByName(campo).AsString); dm.qryPesquisa.Next; end; dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; REsult := lista; end; procedure TAbastecimentos.setBase(const Value: TDate); begin _base := Value; end; procedure TAbastecimentos.setCupom(const Value: String); begin _cupom := Value; end; procedure TAbastecimentos.setData(const Value: TDateTime); begin _data := Value; end; procedure TAbastecimentos.setEntregador(const Value: Integer); begin _entregador := Value; end; procedure TAbastecimentos.setExecutante(const Value: String); begin _executante := Value; end; procedure TAbastecimentos.setManutencao(const Value: TDateTime); begin _manutencao := Value; end; procedure TAbastecimentos.setNome(const Value: String); begin _nome := Value; end; procedure TAbastecimentos.setNumero(const Value: Integer); begin _numero := Value; end; procedure TAbastecimentos.setPlaca(const Value: String); begin _placa := Value; end; procedure TAbastecimentos.setProduto(const Value: String); begin _produto := Value; end; procedure TAbastecimentos.setQuantidade(const Value: Double); begin _quantidade := Value; end; procedure TAbastecimentos.setUnitario(const Value: Double); begin _unitario := Value; end; function TAbastecimentos.getDescontado: String; begin REsult := _descontado; end; procedure TAbastecimentos.setDescontado(const Value: String); begin _descontado := Value; end; procedure TAbastecimentos.setTotal(const Value: Double); begin _total := Value; end; procedure TAbastecimentos.setExtrato(const Value: Integer); begin _extrato := Value; end; procedure TAbastecimentos.setDesconto(const Value: Double); begin _desconto := Value; end; procedure TAbastecimentos.setVerba(const Value: Double); begin _verba := Value; end; procedure TAbastecimentos.setControle(const Value: Integer); begin _controle := Value; end; function TAbastecimentos.ConsolidaAbastecimentos(sInicio: String; sTermino: String): Boolean; begin Result := False; dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; dm.qryPesquisa.SQL.Text := 'SELECT ' + 'TBABASTECIMENTO.COD_ENTREGADOR, ' + 'SUM(TBABASTECIMENTO.VAL_TOTAL) AS VAL_TOTAL ' + 'FROM ' + TABLENAME + ' WHERE TBABASTECIMENTO.DAT_ABASTECIMENTO <= :TERMINO AND DOM_DESCONTO <> :DESCONTO ' + 'GROUP BY TBABASTECIMENTO.COD_ENTREGADOR;'; //dm.qryPesquisa.ParamByName('INICIO').AsDate := StrToDate(sInicio); dm.qryPesquisa.ParamByName('TERMINO').AsDate := StrToDate(sTermino); dm.qryPesquisa.ParamByName('DESCONTO').AsString := 'S'; dm.ZConn.PingServer; dm.qryPesquisa.Open; if dm.qryPesquisa.IsEmpty then begin dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; Exit; end; dm.qryPesquisa.First; Result := True; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIAsn1Set; {$I ..\Include\CryptoLib.inc} interface uses ClpCryptoLibTypes, ClpIProxiedInterface, ClpIAsn1SetParser; type IAsn1Set = interface(IAsn1Object) ['{0BA9633A-73D2-4F5E-A1C0-0FCF2623847C}'] function GetCount: Int32; function GetParser: IAsn1SetParser; function GetSelf(Index: Integer): IAsn1Encodable; function GetCurrent(const e: IAsn1Encodable): IAsn1Encodable; function ToString(): String; function ToArray(): TCryptoLibGenericArray<IAsn1Encodable>; function GetEnumerable: TCryptoLibGenericArray<IAsn1Encodable>; property Self[Index: Int32]: IAsn1Encodable read GetSelf; default; property Parser: IAsn1SetParser read GetParser; property Count: Int32 read GetCount; end; type IAsn1SetParserImpl = interface(IAsn1SetParser) ['{23EAFC37-244E-42D7-89A8-1740B12656C1}'] end; implementation end.
unit uSolicitacaoTempoVO; interface uses uKeyField, uTableName, System.SysUtils, System.Generics.Collections, uUsuarioVO, uSolicitacaoVO, uStatusVO, uClienteVO; type [TableName('Solicitacao_Tempo')] TSolicitacaoTempoVO = class private FIdUsuario: Integer; FId: Integer; FHoraFim: TTime; FIdSolicitacao: Integer; FHoraInicio: TTime; FData: TDate; FTotalHoras: Double; FUsuario: TUsuarioVO; FSolicitacao: TSolicitacaoVO; FIdStatus: Integer; FStatus: TStatusVO; FCliente: TClienteVO; FPrograma: string; procedure SetData(const Value: TDate); procedure SetHoraFim(const Value: TTime); procedure SetHoraInicio(const Value: TTime); procedure SetId(const Value: Integer); procedure SetIdSolicitacao(const Value: Integer); procedure SetIdUsuario(const Value: Integer); procedure SetTotalHoras(const Value: Double); procedure SetUsuario(const Value: TUsuarioVO); procedure SetSolicitacao(const Value: TSolicitacaoVO); procedure SetIdStatus(const Value: Integer); procedure SetStatus(const Value: TStatusVO); procedure SetCliente(const Value: TClienteVO); procedure SetPrograma(const Value: string); public [KeyField('STemp_Id')] property Id: Integer read FId write SetId; [FieldName('STemp_Solicitacao')] property IdSolicitacao: Integer read FIdSolicitacao write SetIdSolicitacao; [FieldName('STemp_UsuarioOperacional')] property IdUsuario: Integer read FIdUsuario write SetIdUsuario; [FieldDate('STemp_Data')] property Data: TDate read FData write SetData; [FieldTime('STemp_HoraInicio')] property HoraInicio: TTime read FHoraInicio write SetHoraInicio; [FieldTime('STemp_HoraFim')] property HoraFim: TTime read FHoraFim write SetHoraFim; [FieldName('STemp_TotalHoras')] property TotalHoras: Double read FTotalHoras write SetTotalHoras; [FieldNull('STemp_Status')] property IdStatus: Integer read FIdStatus write SetIdStatus; property Usuario: TUsuarioVO read FUsuario write SetUsuario; property Solicitacao: TSolicitacaoVO read FSolicitacao write SetSolicitacao; property Status: TStatusVO read FStatus write SetStatus; property Cliente: TClienteVO read FCliente write SetCliente; property Programa: string read FPrograma write SetPrograma; constructor create; destructor destroy; override; end; TListaSolicitacaoTempo = TObjectList<TSolicitacaoTempoVO>; implementation { TSolicitacaoTempoVO } constructor TSolicitacaoTempoVO.create; begin inherited create; FUsuario := TUsuarioVO.Create; FSolicitacao := TSolicitacaoVO.Create; FStatus := TStatusVO.Create; FCliente := TClienteVO.create; end; destructor TSolicitacaoTempoVO.destroy; begin FreeAndNil(FUsuario); FreeAndNil(FSolicitacao); FreeAndNil(FStatus); FreeAndNil(FCliente); inherited; end; procedure TSolicitacaoTempoVO.SetCliente(const Value: TClienteVO); begin FCliente := Value; end; procedure TSolicitacaoTempoVO.SetData(const Value: TDate); begin FData := Value; end; procedure TSolicitacaoTempoVO.SetHoraFim(const Value: TTime); begin FHoraFim := Value; end; procedure TSolicitacaoTempoVO.SetHoraInicio(const Value: TTime); begin FHoraInicio := Value; end; procedure TSolicitacaoTempoVO.SetId(const Value: Integer); begin FId := Value; end; procedure TSolicitacaoTempoVO.SetIdSolicitacao(const Value: Integer); begin FIdSolicitacao := Value; end; procedure TSolicitacaoTempoVO.SetIdStatus(const Value: Integer); begin FIdStatus := Value; end; procedure TSolicitacaoTempoVO.SetIdUsuario(const Value: Integer); begin FIdUsuario := Value; end; procedure TSolicitacaoTempoVO.SetPrograma(const Value: string); begin FPrograma := Value; end; procedure TSolicitacaoTempoVO.SetSolicitacao(const Value: TSolicitacaoVO); begin FSolicitacao := Value; end; procedure TSolicitacaoTempoVO.SetStatus(const Value: TStatusVO); begin FStatus := Value; end; procedure TSolicitacaoTempoVO.SetTotalHoras(const Value: Double); begin FTotalHoras := Value; end; procedure TSolicitacaoTempoVO.SetUsuario(const Value: TUsuarioVO); begin FUsuario := Value; end; end.
unit MaleFemaleBoolean; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls; type TOnCheckMasculino = procedure(value : Boolean; Sender : TObject) of object; TMaleFemaleBoolean = class(TGroupBox) private FCheckMasculino : TRadioButton; FCheckFeminino : TRadioButton; FOnChange: TNotifyEvent; FOnCheckedMasculino: TOnCheckMasculino; function GetCheckMasculino: Boolean; procedure SetCheckMasculino(const Value: Boolean); function GetCheckFeminino: Boolean; procedure SetCheckFeminino(const Value: Boolean); procedure SetOnChange(const Value: TNotifyEvent); procedure SetOnCheckedMasculino(const Value: TOnCheckMasculino); { Private declarations } protected { Protected declarations } procedure CreateWnd; override; procedure RadioClick(Sendert : TObject);virtual; public { Public declarations } constructor Create(AOwner: TComponent); override; published { Published declarations } property CheckMasculino : Boolean read GetCheckMasculino write SetCheckMasculino; property CheckFeminino : Boolean read GetCheckFeminino write SetCheckFeminino; property OnChange : TNotifyEvent read FOnChange write SetOnChange; property OnCheckedMasculino : TOnCheckMasculino read FOnCheckedMasculino write SetOnCheckedMasculino; end; procedure Register; implementation procedure Register; begin RegisterComponents('componenteOW', [TMaleFemaleBoolean]); end; { TMaleFemaleBoolean } constructor TMaleFemaleBoolean.Create(AOwner: TComponent); begin inherited; Width := 100; Height := 60; FCheckMasculino := TRadioButton.Create(Self); FCheckMasculino.Parent := Self; FCheckMasculino.Caption := '&Masculino'; FCheckMasculino.Left := 20; FCheckMasculino.Top := 18; FCheckMasculino.Width := 75; FCheckMasculino.OnClick := RadioClick; FCheckFeminino := TRadioButton.Create(Self); FCheckFeminino.Parent := Self; FCheckFeminino.Caption := '&Feminino'; FCheckFeminino.Left := 20; FCheckFeminino.Top := 35; FCheckFeminino.Width := 75; FCheckFeminino.OnClick := RadioClick; FCheckMasculino.SetSubComponent(True); FCheckFeminino.SetSubComponent(True); end; procedure TMaleFemaleBoolean.CreateWnd; begin inherited; Caption := ''; end; function TMaleFemaleBoolean.GetCheckFeminino: Boolean; begin Result := FCheckFeminino.Checked; end; function TMaleFemaleBoolean.GetCheckMasculino: Boolean; begin Result := FCheckMasculino.Checked; end; procedure TMaleFemaleBoolean.RadioClick(Sendert: TObject); begin if Assigned(FOnChange) then OnChange(Self); if Assigned(FOnCheckedMasculino) then FOnCheckedMasculino(FCheckMasculino.Checked, FCheckMasculino); end; procedure TMaleFemaleBoolean.SetCheckFeminino(const Value: Boolean); begin FCheckFeminino.Checked := Value; end; procedure TMaleFemaleBoolean.SetCheckMasculino(const Value: Boolean); begin FCheckMasculino.Checked := Value; if Assigned(FOnCheckedMasculino) then FOnCheckedMasculino(Value, FCheckMasculino); end; procedure TMaleFemaleBoolean.SetOnChange(const Value: TNotifyEvent); begin FOnChange := Value; end; procedure TMaleFemaleBoolean.SetOnCheckedMasculino(const Value: TOnCheckMasculino); begin FOnCheckedMasculino := Value; end; end.
{ CSI 1101-X, Winter 1999 } { Assignment 4, Question 2 } { Identification: Mark Sattolo, student# 428500 } { tutorial group DGD-4, t.a. = Manon Sanscartier } program a4q2 (input,output) ; type element_type = real ; pointer = ^node ; node = record value: element_type ; next: pointer end ; list = pointer ; { variable for the main program - NOT to be referenced anywhere else } var YESorNO: char ; { The following global variable is used for memory management. You might find it useful while debugging your code, but the solutions you hand in must not refer to this variable in any way. } memory_count: integer ; { ********* MEMORY MANAGEMENT PROCEDURES ********* } { get_node - Returns a pointer to a new node. } procedure get_node( var P: pointer ); begin memory_count := memory_count + 1 ; new( P ) end ; { return_node - Make the node pointed at by P "free" (available to get_node). } procedure return_node(var P: pointer) ; begin memory_count := memory_count - 1 ; P^.value := -7777.77 ; { "scrub" memory to aid debugging } P^.next := P ; { "scrub" memory to aid debugging } dispose( P ) end ; {************************************************************} { create_empty - sets list L to be empty. } procedure create_empty ( var L: list ) ; begin L := nil end ; procedure write_list ( var L:list ); var p: pointer ; begin if L = nil then writeln('empty list') else begin p := L ; while p <> nil do begin write( ' ',p^.value:4:1 ); p := p^.next end ; writeln end end ; procedure destroy( var L:list ) ; begin if L <> Nil then { General case } begin destroy (L^.next) ; { step 1 } return_node (L) ; { step 2 } end { i.e. Base case = "else, do nothing" } end; { procedure } procedure insert_at_end(var L:list; V: element_type) ; var q, temp : pointer ; begin get_node(q) ; q^.value := V ; q^.next := nil ; if L = nil then L := q else begin temp := L ; while (temp^.next <> nil) do temp := temp^.next ; temp^.next := q ; end { else } end; { procedure } procedure delete_all_occurrences( var L:list; V: element_type) ; var p, q, temp : pointer ; begin while (L <> nil) and (L^.value = V) do begin p := L ; L := L^.next ; return_node(p); end ; { while } temp := L ; while (temp <> nil) and (temp^.next <> nil) do begin if (temp^.next^.value = V) then begin q := temp^.next ; temp^.next := q^.next ; return_node(q) ; end { if } else temp := temp^.next ; end ; { while } end; procedure assignment4q2 ; var L: list ; val: element_type ; begin create_empty( L ); writeln('enter a list of reals, all values on one line'); while (not eoln) do begin read(val) ; insert_at_end(L,val) end ; readln ; { clear the empty line } writeln ; writeln('Here is the list you entered'); write_list(L); writeln ; writeln('enter a value to be deleted (empty line to quit)' ); while (not eoln) do begin readln(val) ; delete_all_occurrences(L, val) ; writeln('Here is the list after deleting all occurrences of ',val:6:1); write_list(L); writeln ; writeln('enter a value to be deleted (empty line to quit)' ) end ; readln ; { clear the empty line } { to finish off, return all the nodes in all lists back to the global pool } destroy( L ) end; {**** YOU MUST CHANGE THIS PROCEDURE TO DESCRIBE YOURSELF ****} procedure identify_myself ; { Writes who you are to the screen } begin writeln ; writeln('CSI 1101-X (winter, 1999). Assignment 4, Question 2.') ; writeln('Mark Sattolo, student# 428500.') ; writeln('tutorial section DGD-4, t.a. = Manon Sanscartier') ; writeln end ; begin { main program } memory_count := 0 ; identify_myself ; repeat assignment4q2 ; writeln('Amount of dynamic memory allocated but not returned (should be 0) ', memory_count:0) ; writeln('Do you wish to continue (y or n) ?') ; readln(YESorNO); until (YESorNO <> 'y') end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clWebUpdate; interface {$I clVer.inc} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$ENDIF} uses {$IFNDEF DELPHIXE2} Classes, Windows, msxml, SysUtils, Math, Forms, {$ELSE} System.Classes, Winapi.Windows, Winapi.msxml, System.SysUtils, System.Math, Vcl.Forms, {$ENDIF} clDownloader, clDC, clDCUtils, clUtils, clMultiDC, clXmlUtils, clSspiTls, clFtpUtils, clHttpUtils, clWUtils, clResourceState; type TclVersionFormat = (vfStandard, vfNumber, vfTimeStamp); TclUpdateStatus = (usDownload, usReady, usSuccess, usFailed); TclUpdateState = (utGetUpdateInfo, utDownload, utGetTimeStamp); TclRunUpdateResult = (urSuccess, urError, urCancel); TclUpdateInfoItem = class(TCollectionItem) private FURL: string; FVersion: string; FSize: string; FLocalFile: string; FUpdateDate: string; FStatus: TclUpdateStatus; FUpdateScript: TStrings; FNeedTerminate: Boolean; FResourceState: TclResourceStateList; FDescription: string; FContentType: string; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure UpdateStatus(ANewStatus: TclUpdateStatus); property UpdateScript: TStrings read FUpdateScript; property URL: string read FURL write FURL; property LocalFile: string read FLocalFile write FLocalFile; property Size: string read FSize write FSize; property Version: string read FVersion write FVersion; property UpdateDate: string read FUpdateDate write FUpdateDate; property Status: TclUpdateStatus read FStatus write FStatus; property NeedTerminate: Boolean read FNeedTerminate write FNeedTerminate; property ResourceState: TclResourceStateList read FResourceState; property Description: string read FDescription write FDescription; property ContentType: string read FContentType write FContentType; end; TclUpdateInfoList = class(TCollection) private function GetItem(Index: Integer): TclUpdateInfoItem; procedure SetItem(Index: Integer; const Value: TclUpdateInfoItem); function GetHasDownloads: Boolean; function GetHasUpdates: Boolean; function GetLastVersion: string; procedure LoadResourceState(ANode: IXMLDomNode; AResourceState: TclResourceStateList); procedure SaveResourceState(ANode: IXMLDomNode; AResourceState: TclResourceStateList); {$IFDEF DELPHI6} function GetBigInt(AValue: Int64): Int64; {$ELSE} function GetBigInt(AValue: Integer): Integer; {$ENDIF} public constructor Create; function GetFirst(AStatus: TclUpdateStatus): Integer; procedure LoadFromXml(const AFileName: string); procedure SaveToXml(const AFileName: string); function ItemByUrl(const AUrl: string): TclUpdateInfoItem; function LastItemByUrl(const AUrl: string): TclUpdateInfoItem; function LastItemByStatus(AStatus: TclUpdateStatus): TclUpdateInfoItem; function Add: TclUpdateInfoItem; property Items[Index: Integer]: TclUpdateInfoItem read GetItem write SetItem; default; property HasDownloads: Boolean read GetHasDownloads; property HasUpdates: Boolean read GetHasUpdates; property LastVersion: string read GetLastVersion; end; TclWebUpdate = class; TclHasUpdateEvent = procedure (Sender: TObject; const AUpdateItem: TclUpdateInfoItem; ActualInfo: TclUpdateInfoList; var CanUpdate, Handled: Boolean) of object; TclDownloadEvent = procedure (Sender: TObject; const DownloadURL, DownloadFile: string) of object; TclRunUpdateEvent = procedure (Sender: TObject; AUpdateScript: TStrings; ANeedTerminate: Boolean; var CanRun: Boolean; var Result: TclRunUpdateResult; var AErrors: string) of object; TclTerminatingEvent = procedure (Sender: TObject; var CanTerminate: Boolean) of object; TclDownloadProgressEvent = procedure (Sender: TObject; UpdateNo: Integer; Downloaded, Total: Int64) of object; TclShowInfoEvent = procedure (Sender: TObject; AUpdater: TclWebUpdate; var CanUpdate: Boolean) of object; TclGetUpdateInfoEvent = procedure (Sender: TObject; ActualInfo: TclUpdateInfoList; UpdateInfo: TclUpdateInfoList) of object; TclWebUpdateErrorEvent = procedure (Sender: TObject; UpdateNo: Integer; const Error: string; ErrorCode: Integer) of object; TclWebUpdate = class(TComponent) private FIsBusy: Boolean; FDownloader: TclDownloader; FUpdateState: TclUpdateState; FUpdateURL: string; FActualUpdateInfoFile: string; FVersionFormat: TclVersionFormat; FNeedShowInfo: Boolean; FActualInfo: TclUpdateInfoList; FUpdateInfo: TclUpdateInfoList; FUpdateNo: Integer; FNeedTerminate: Boolean; FProductName: string; FProductURL: string; FAuthor: string; FEmail: string; FUpdateDir: string; FErrorWords: TStrings; FOnDownloadProgress: TclDownloadProgressEvent; FOnError: TclWebUpdateErrorEvent; FOnHasUpdate: TclHasUpdateEvent; FOnTerminating: TclTerminatingEvent; FOnRunUpdate: TclRunUpdateEvent; FOnAfterDownload: TclDownloadEvent; FOnBeforeDownload: TclDownloadEvent; FOnShowInfo: TclShowInfoEvent; FOnNoUpdatesFound: TNotifyEvent; FOnGetUpdateInfo: TclGetUpdateInfoEvent; FOnProcessCompleted: TNotifyEvent; procedure DoOnProcessCompleted(Sender: TObject); procedure DoOnError(Sender: TObject; const Error: string; ErrorCode: Integer); procedure DoOnDataItemProceed(Sender: TObject; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer); function GetIsBusy: Boolean; function CheckUpdateVersion(AUpdateItem: TclUpdateInfoItem): Boolean; function HasUpdate(AUpdateItem: TclUpdateInfoItem): Boolean; procedure CheckUpdateInfo; function ShowInfo(): Boolean; procedure GetUpdateInfo; procedure StoreActualInfo; procedure StartDownloading; procedure StartUpdating; function RunUpdate(AUpdateItem: TclUpdateInfoItem): Boolean; procedure Terminating; procedure SetUpdateDir(const Value: string); function PerformCmdFile(const AFileName: string): Integer; function GetLogError(ALogStrings: TStrings): string; procedure SetErrorWords(const Value: TStrings); procedure ReplaceScriptKeywords(AScript: TStrings); function GetBatchSize: Integer; function GetPort_: Integer; procedure SetBatchSize(const Value: Integer); procedure SetPort_(const Value: Integer); function GetPassiveFtpMode: Boolean; procedure SetPassiveFtpMode(const Value: Boolean); function GetCertificateFlags: TclCertificateVerifyFlags; function GetFtpProxySettings: TclFtpProxySettings; function GetHttpProxySettings: TclHttpProxySettings; function GetTryCount: Integer; function GetInternetAgent: string; function GetProxyBypass: TStrings; function GetReconnectAfter: Integer; function GetThreadCount: Integer; function GetTimeOut: Integer; procedure SetCertificateFlags(const Value: TclCertificateVerifyFlags); procedure SetFtpProxySettings(const Value: TclFtpProxySettings); procedure SetHttpProxySettings(const Value: TclHttpProxySettings); procedure SetTryCount(const Value: Integer); procedure SetInternetAgent(const Value: string); procedure SetProxyBypass(const Value: TStrings); procedure SetReconnectAfter(const Value: Integer); procedure SetThreadCount(const Value: Integer); procedure SetTimeOut(const Value: Integer); function MakeCompleteNumber(S: string): Integer; function CheckUpdateTimeStamp(AUpdateItem: TclUpdateInfoItem): Boolean; function GetTimeStamp(const AURL: string): string; function GetPassword: string; function GetUserName_: string; procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); protected procedure DoGetUpdateInfo; dynamic; procedure DoHasUpdate(const AUpdateItem: TclUpdateInfoItem; ActualInfo: TclUpdateInfoList; var CanUpdate, Handled: Boolean); dynamic; procedure DoBeforeDownload(const DownloadURL, DownloadFile: string); dynamic; procedure DoAfterDownload(const DownloadURL, DownloadFile: string); dynamic; procedure DoShowInfo(var CanUpdate: Boolean); dynamic; procedure DoRunUpdate(AUpdateScript: TStrings; ANeedTerminate: Boolean; var CanRun: Boolean; var Result: TclRunUpdateResult; var AErrors: string); dynamic; procedure DoTerminating(var CanTerminate: Boolean); dynamic; procedure DoDownloadProgress(UpdateNo: Integer; Downloaded, Total: Int64); dynamic; procedure DoError(UpdateNo: Integer; const Error: string; ErrorCode: Integer); dynamic; procedure DoNoUpdatesFound; procedure DoProcessCompleted; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Start(IsAsynch: Boolean = True); procedure Stop; property IsBusy: Boolean read GetIsBusy; property NeedTerminate: Boolean read FNeedTerminate; property ActualInfo: TclUpdateInfoList read FActualInfo; property UpdateInfo: TclUpdateInfoList read FUpdateInfo; published property ProductName: string read FProductName write FProductName; property Author: string read FAuthor write FAuthor; property ProductURL: string read FProductURL write FProductURL; property Email: string read FEmail write FEmail; property UpdateURL: string read FUpdateURL write FUpdateURL; property UpdateDir: string read FUpdateDir write SetUpdateDir; property ActualUpdateInfoFile: string read FActualUpdateInfoFile write FActualUpdateInfoFile; property VersionFormat: TclVersionFormat read FVersionFormat write FVersionFormat default vfStandard; property NeedShowInfo: Boolean read FNeedShowInfo write FNeedShowInfo default True; property ErrorWords: TStrings read FErrorWords write SetErrorWords; property UserName: string read GetUserName_ write SetUserName; property Password: string read GetPassword write SetPassword; property Port: Integer read GetPort_ write SetPort_ default 0; property PassiveFtpMode: Boolean read GetPassiveFtpMode write SetPassiveFtpMode default False; property HttpProxySettings: TclHttpProxySettings read GetHttpProxySettings write SetHttpProxySettings; property FtpProxySettings: TclFtpProxySettings read GetFtpProxySettings write SetFtpProxySettings; property ProxyBypass: TStrings read GetProxyBypass write SetProxyBypass; property InternetAgent: string read GetInternetAgent write SetInternetAgent; property TryCount: Integer read GetTryCount write SetTryCount default DefaultTryCount; property TimeOut: Integer read GetTimeOut write SetTimeOut default DefaultTimeOut; property ReconnectAfter: Integer read GetReconnectAfter write SetReconnectAfter default DefaultTimeOut; property CertificateFlags: TclCertificateVerifyFlags read GetCertificateFlags write SetCertificateFlags default []; property ThreadCount: Integer read GetThreadCount write SetThreadCount default DefaultThreadCount; property BatchSize: Integer read GetBatchSize write SetBatchSize default DefaultBatchSize; property OnGetUpdateInfo: TclGetUpdateInfoEvent read FOnGetUpdateInfo write FOnGetUpdateInfo; property OnShowInfo: TclShowInfoEvent read FOnShowInfo write FOnShowInfo; property OnHasUpdate: TclHasUpdateEvent read FOnHasUpdate write FOnHasUpdate; property OnBeforeDownload: TclDownloadEvent read FOnBeforeDownload write FOnBeforeDownload; property OnAfterDownload: TclDownloadEvent read FOnAfterDownload write FOnAfterDownload; property OnRunUpdate: TclRunUpdateEvent read FOnRunUpdate write FOnRunUpdate; property OnTerminating: TclTerminatingEvent read FOnTerminating write FOnTerminating; property OnDownloadProgress: TclDownloadProgressEvent read FOnDownloadProgress write FOnDownloadProgress; property OnError: TclWebUpdateErrorEvent read FOnError write FOnError; property OnNoUpdatesFound: TNotifyEvent read FOnNoUpdatesFound write FOnNoUpdatesFound; property OnProcessCompleted: TNotifyEvent read FOnProcessCompleted write FOnProcessCompleted; end; const cAppDir = '$(app)'; cUpdateDir = '$(update)'; implementation uses clUpdateInfoForm, clSingleDC, clWinInet, clUriUtils; const cUpdateStatusNames: array[TclUpdateStatus] of string = ('download', 'ready', 'success', 'failed'); cBooleanNames: array[Boolean] of string = ('no', 'yes'); { TclWebUpdate } constructor TclWebUpdate.Create(AOwner: TComponent); begin inherited Create(AOwner); FErrorWords := TStringList.Create(); FErrorWords.Add('fatal'); FErrorWords.Add('failed'); FErrorWords.Add('error'); FActualInfo := TclUpdateInfoList.Create(); FUpdateInfo := TclUpdateInfoList.Create(); FDownloader := TclDownloader.Create(nil); FDownloader.OnProcessCompleted := DoOnProcessCompleted; FDownloader.OnError := DoOnError; FDownloader.OnDataItemProceed := DoOnDataItemProceed; FActualUpdateInfoFile := 'lastupdate.xml'; FVersionFormat := vfStandard; FNeedShowInfo := True; FUpdateDir := '.\'; end; destructor TclWebUpdate.Destroy; begin Stop(); while IsBusy do begin Application.ProcessMessages(); end; FDownloader.Free(); FUpdateInfo.Free(); FActualInfo.Free(); FErrorWords.Free(); inherited Destroy(); end; procedure TclWebUpdate.StartUpdating; var i: Integer; begin for i := 0 to ActualInfo.Count - 1 do begin if FIsBusy and (ActualInfo[i].Status = usReady) then begin if not RunUpdate(ActualInfo[i]) then begin Break; end; end; end; FIsBusy := False; DoProcessCompleted(); if NeedTerminate then begin Terminating(); end; end; procedure TclWebUpdate.Terminating; var CanTerminate: Boolean; begin CanTerminate := True; DoTerminating(CanTerminate); if CanTerminate then begin Application.Terminate(); end; end; procedure TclWebUpdate.DoOnProcessCompleted(Sender: TObject); var Success: Boolean; begin if (FUpdateState = utGetTimeStamp) then begin Exit; end; Success := (FDownloader.ResourceState.LastStatus = psSuccess); if (FUpdateState = utDownload) then begin if Success then begin ActualInfo[FUpdateNo].UpdateStatus(usReady); end else begin ActualInfo[FUpdateNo].ResourceState.Assign(FDownloader.ResourceState); end; StoreActualInfo(); if Success then begin DoAfterDownload(FDownloader.URL, FDownloader.LocalFile); repeat Inc(FUpdateNo); until ((FUpdateNo >= ActualInfo.Count) or (ActualInfo[FUpdateNo].Status = usDownload)); if (FUpdateNo < ActualInfo.Count) then begin StartDownloading(); end else begin FUpdateState := utGetUpdateInfo; StartUpdating(); end; end else begin FIsBusy := False; DoProcessCompleted(); end; end else if Success then begin CheckUpdateInfo(); end else begin FIsBusy := False; DoProcessCompleted(); end; end; procedure TclWebUpdate.CheckUpdateInfo; var i: integer; begin GetUpdateInfo(); for i := 0 to UpdateInfo.Count - 1 do begin if HasUpdate(UpdateInfo[i]) then begin ActualInfo.Add().Assign(UpdateInfo[i]); end; end; if not FIsBusy then Exit; if ActualInfo.HasDownloads then begin if ShowInfo() then begin FUpdateNo := ActualInfo.GetFirst(usDownload); FUpdateState := utDownload; StoreActualInfo(); StartDownloading(); end else begin FIsBusy := False; DoProcessCompleted(); end; end else if ActualInfo.HasUpdates then begin StartUpdating(); end else begin DoNoUpdatesFound(); FIsBusy := False; DoProcessCompleted(); end; end; procedure TclWebUpdate.Start(IsAsynch: Boolean); begin if FIsBusy then Exit; FUpdateNo := -1; FIsBusy := True; FUpdateState := utGetUpdateInfo; FNeedTerminate := False; FDownloader.LocalFolder := UpdateDir; FDownloader.URL := UpdateURL; FDownloader.UserName := UserName; FDownloader.Password := Password; FDownloader.Start(); end; function TclWebUpdate.MakeCompleteNumber(S: string): Integer; var i, Cnt, Len, OldPos: Integer; begin S := Trim(S); Result := 0; Len := Length(S); Cnt := 0; OldPos := Len + 1; for i := Len downto 1 do begin if (S[i] = '.') then begin Result := Result + StrToIntDef('0' + system.Copy(S, i + 1, OldPos - i - 1), 0) * Round(Power(1000, Cnt)); Inc(Cnt); OldPos := i; end else if (i = 1) then begin Result := Result + StrToIntDef('0' + system.Copy(S, i, OldPos - i), 0) * Round(Power(1000, Cnt)); end; end; end; function TclWebUpdate.GetTimeStamp(const AURL: string): string; begin Result := ''; FUpdateState := utGetTimeStamp; FDownloader.URL := AURL; FDownloader.CloseConnection(); FDownloader.GetResourceInfo(False); if (FDownloader.Errors.Count > 0) or (FDownloader.ResourceInfo = nil) then Exit; Result := FloatToStr(FDownloader.ResourceInfo.Date); end; function TclWebUpdate.CheckUpdateTimeStamp(AUpdateItem: TclUpdateInfoItem): Boolean; var ActualItem: TclUpdateInfoItem; begin ActualItem := ActualInfo.LastItemByUrl(AUpdateItem.URL); AUpdateItem.Version := GetTimeStamp(AUpdateItem.URL); Result := (ActualItem = nil) or (StrToFloatDef(ActualItem.Version, 0) < StrToFloatDef(AUpdateItem.Version, 0)); end; function TclWebUpdate.CheckUpdateVersion(AUpdateItem: TclUpdateInfoItem): Boolean; begin Result := True; if (ActualInfo.LastVersion = '') then Exit; if (VersionFormat = vfStandard) then begin Result := (MakeCompleteNumber(AUpdateItem.Version) > MakeCompleteNumber(ActualInfo.LastVersion)); end else if (VersionFormat = vfTimeStamp) then begin Result := CheckUpdateTimeStamp(AUpdateItem); end else if (VersionFormat = vfNumber) then begin Result := StrToIntDef(AUpdateItem.Version, 0) > StrToIntDef(ActualInfo.LastVersion, 0); end else begin Assert(False, 'Not implemented'); end; end; function TclWebUpdate.HasUpdate(AUpdateItem: TclUpdateInfoItem): Boolean; var handled: Boolean; begin handled := False; Result := True; DoHasUpdate(AUpdateItem, ActualInfo, Result, handled); if not handled then begin Result := CheckUpdateVersion(AUpdateItem); end; end; procedure TclWebUpdate.GetUpdateInfo; var i: Integer; begin UpdateInfo.LoadFromXml(FDownloader.LocalFile); for i := 0 to UpdateInfo.Count - 1 do begin UpdateInfo[i].URL := TclUrlParser.CombineUrl(UpdateInfo[i].URL, UpdateURL); end; ActualInfo.LoadFromXml(ActualUpdateInfoFile); DoGetUpdateInfo(); end; function TclWebUpdate.GetUserName_: string; begin Result := FDownloader.UserName; end; function TclWebUpdate.ShowInfo(): Boolean; begin Result := True; DoShowInfo(Result); if NeedShowInfo then begin Result := TfrmUpdateInfo.ShowInfo(Self); end; end; procedure TclWebUpdate.StartDownloading; begin FDownloader.URL := ActualInfo[FUpdateNo].URL; if (FDownloader.UserName = '') then begin FDownloader.UserName := UserName; end; if (FDownloader.Password = '') then begin FDownloader.Password := Password; end; ActualInfo[FUpdateNo].FLocalFile := FDownloader.LocalFile; DoBeforeDownload(FDownloader.URL, FDownloader.LocalFile); FDownloader.ResourceState.Assign(ActualInfo[FUpdateNo].ResourceState); FDownloader.Start(); end; function TclWebUpdate.PerformCmdFile(const AFileName: string): Integer; var StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; Res: DWORD; s: string; begin ZeroMemory(@StartupInfo, SizeOf(TStartupInfo)); StartupInfo.cb := SizeOf(TStartupInfo); StartupInfo.dwFlags := StartupInfo.dwFlags or STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := SW_HIDE; ZeroMemory(@ProcessInfo, SizeOf(TProcessInformation)); s := Trim(AFileName + ' '); if not CreateProcess(nil, PChar(s), nil, nil, False, CREATE_NEW_CONSOLE or CREATE_NO_WINDOW, nil, nil, StartupInfo, ProcessInfo) then begin raise Exception.CreateFmt('Can not run cmd file, error %d', [GetLastError()]); end; CloseHandle(ProcessInfo.hThread); WaitForSingleObject(ProcessInfo.hProcess, INFINITE); GetExitCodeProcess(ProcessInfo.hProcess, Res); Result := Res; CloseHandle(ProcessInfo.hProcess); end; function TclWebUpdate.GetLogError(ALogStrings: TStrings): string; function CheckWordExists(const Buffer, NeededString: String): Boolean; var ind: Integer; begin ind := system.Pos(LowerCase(NeededString), LowerCase(Buffer)); Result := (ind > 0); if not Result then Exit; if (ind > 1) and not CharInSet(Buffer[ind - 1], [#32, #9, #10]) then begin Result := False; end; if not Result then Exit; ind := ind + Length(NeededString) - 1; if (ind < Length(Buffer)) and not CharInSet(Buffer[ind + 1], [#32, #9, #13, ',', '.']) then begin Result := False; end; end; var i, j: Integer; begin for i := 0 to ALogStrings.Count - 1 do begin Result := ALogStrings[i]; for j := 0 to ErrorWords.Count - 1 do begin if CheckWordExists(LowerCase(Result), LowerCase(ErrorWords[j])) then Exit; end; end; Result := ''; end; procedure TclWebUpdate.ReplaceScriptKeywords(AScript: TStrings); var path: string; begin path := ExtractFilePath(ParamStr(0)); if (path <> '') and (path[Length(path)] = '\') then begin Delete(path, Length(path), 1); end; AScript.Text := StringReplace(AScript.Text, cAppDir, path, [rfReplaceAll, rfIgnoreCase]); AScript.Text := StringReplace(AScript.Text, cUpdateDir, UpdateDir, [rfReplaceAll, rfIgnoreCase]); end; function TclWebUpdate.RunUpdate(AUpdateItem: TclUpdateInfoItem): Boolean; const cRunName = 'B1BD76091FF7'; var tempCmdName, tempLogName, error: string; canRun: Boolean; logStrings, script: TStrings; runResult: TclRunUpdateResult; begin if (AUpdateItem.NeedTerminate) then begin FNeedTerminate := True; end; canRun := True; error := ''; script := TStringList.Create(); try script.Assign(AUpdateItem.UpdateScript); ReplaceScriptKeywords(script); runResult := urSuccess; DoRunUpdate(script, AUpdateItem.NeedTerminate, canRun, runResult, error); if canRun and (runResult = urSuccess) and (script.Count > 0) then begin tempCmdName := GetFullFileName(cRunName + '.cmd', ExtractFilePath(ParamStr(0))); tempLogName := GetFullFileName(cRunName + '.log', ExtractFilePath(ParamStr(0))); logStrings := TStringList.Create(); try script.SaveToFile(tempCmdName); PerformCmdFile('"' + tempCmdName + '" > "' + tempLogName + '"'); logStrings.LoadFromFile(tempLogName); error := GetLogError(logStrings); if (error <> '') then begin runResult := urError; end; finally logStrings.Free(); DeleteFile(PChar(tempLogName)); DeleteFile(PChar(tempCmdName)); end; end; finally script.Free(); end; case runResult of urSuccess: begin AUpdateItem.UpdateStatus(usSuccess); end; urError: begin AUpdateItem.UpdateStatus(usFailed); DoError(AUpdateItem.Index, Format('The updating of %s file was returned with errors (%s). ', [ExtractFileName(AUpdateItem.LocalFile), error]), -1); end; end; Result := (runResult <> urError); StoreActualInfo(); end; procedure TclWebUpdate.StoreActualInfo; begin ActualInfo.SaveToXml(ActualUpdateInfoFile); end; procedure TclWebUpdate.Stop; begin FIsBusy := False; FDownloader.Stop(); end; procedure TclWebUpdate.DoOnDataItemProceed(Sender: TObject; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer); begin if (FUpdateState = utDownload) then begin DoDownloadProgress(FUpdateNo, AStateItem.ResourceState.BytesProceed, ResourceInfo.Size); end; end; procedure TclWebUpdate.DoOnError(Sender: TObject; const Error: string; ErrorCode: Integer); begin DoError(FUpdateNo, Error, ErrorCode); end; procedure TclWebUpdate.DoAfterDownload(const DownloadURL, DownloadFile: string); begin if Assigned(OnAfterDownload) then begin OnAfterDownload(Self, DownloadURL, DownloadFile); end; end; procedure TclWebUpdate.DoBeforeDownload(const DownloadURL, DownloadFile: string); begin if Assigned(OnBeforeDownload) then begin OnBeforeDownload(Self, DownloadURL, DownloadFile); end; end; procedure TclWebUpdate.DoDownloadProgress(UpdateNo: Integer; Downloaded, Total: Int64); begin if Assigned(OnDownloadProgress) then begin OnDownloadProgress(Self, UpdateNo, Downloaded, Total); end; end; procedure TclWebUpdate.DoError(UpdateNo: Integer; const Error: string; ErrorCode: Integer); begin if Assigned(OnError) then begin OnError(Self, UpdateNo, Error, ErrorCode); end; end; procedure TclWebUpdate.DoHasUpdate(const AUpdateItem: TclUpdateInfoItem; ActualInfo: TclUpdateInfoList; var CanUpdate, Handled: Boolean); begin if Assigned(OnHasUpdate) then begin OnHasUpdate(Self, AUpdateItem, ActualInfo, CanUpdate, Handled); end; end; procedure TclWebUpdate.DoRunUpdate(AUpdateScript: TStrings; ANeedTerminate: Boolean; var CanRun: Boolean; var Result: TclRunUpdateResult; var AErrors: string); begin if Assigned(OnRunUpdate) then begin OnRunUpdate(Self, AUpdateScript, ANeedTerminate, CanRun, Result, AErrors); end; end; procedure TclWebUpdate.DoShowInfo(var CanUpdate: Boolean); begin if Assigned(OnShowInfo) then begin OnShowInfo(Self, Self, CanUpdate); end; end; procedure TclWebUpdate.DoTerminating(var CanTerminate: Boolean); begin if Assigned(OnTerminating) then begin OnTerminating(Self, CanTerminate); end; end; procedure TclWebUpdate.DoNoUpdatesFound; begin if Assigned(OnNoUpdatesFound) then begin OnNoUpdatesFound(Self); end; end; procedure TclWebUpdate.DoGetUpdateInfo; begin if Assigned(OnGetUpdateInfo) then begin OnGetUpdateInfo(Self, ActualInfo, UpdateInfo); end; end; function TclWebUpdate.GetTryCount: Integer; begin Result := FDownloader.TryCount; end; function TclWebUpdate.GetInternetAgent: string; begin Result := FDownloader.InternetAgent; end; function TclWebUpdate.GetIsBusy: Boolean; begin Result := FDownloader.IsBusy or FIsBusy; end; procedure TclWebUpdate.SetUpdateDir(const Value: string); begin FUpdateDir := Value; if not (csLoading in ComponentState) then begin ActualUpdateInfoFile := GetFullFileName(ActualUpdateInfoFile, FUpdateDir); end; end; procedure TclWebUpdate.SetUserName(const Value: string); begin FDownloader.UserName := Value; end; procedure TclWebUpdate.SetErrorWords(const Value: TStrings); begin FErrorWords.Assign(Value); end; procedure TclWebUpdate.SetFtpProxySettings(const Value: TclFtpProxySettings); begin FDownloader.FtpProxySettings := Value; end; procedure TclWebUpdate.SetHttpProxySettings(const Value: TclHttpProxySettings); begin FDownloader.HttpProxySettings := Value; end; procedure TclWebUpdate.SetTryCount(const Value: Integer); begin FDownloader.TryCount := Value; end; procedure TclWebUpdate.SetInternetAgent(const Value: string); begin FDownloader.InternetAgent := Value; end; function TclWebUpdate.GetBatchSize: Integer; begin Result := FDownloader.BatchSize; end; function TclWebUpdate.GetCertificateFlags: TclCertificateVerifyFlags; begin Result := FDownloader.CertificateFlags; end; function TclWebUpdate.GetFtpProxySettings: TclFtpProxySettings; begin Result := FDownloader.FtpProxySettings; end; function TclWebUpdate.GetHttpProxySettings: TclHttpProxySettings; begin Result := FDownloader.HttpProxySettings; end; procedure TclWebUpdate.SetBatchSize(const Value: Integer); begin FDownloader.BatchSize := Value; end; procedure TclWebUpdate.SetCertificateFlags(const Value: TclCertificateVerifyFlags); begin FDownloader.CertificateFlags := Value; end; function TclWebUpdate.GetPort_: Integer; begin Result := FDownloader.Port; end; function TclWebUpdate.GetProxyBypass: TStrings; begin Result := FDownloader.ProxyBypass; end; function TclWebUpdate.GetReconnectAfter: Integer; begin Result := FDownloader.ReconnectAfter; end; function TclWebUpdate.GetThreadCount: Integer; begin Result := FDownloader.ThreadCount; end; function TclWebUpdate.GetTimeOut: Integer; begin Result := FDownloader.TimeOut; end; procedure TclWebUpdate.SetPort_(const Value: Integer); begin FDownloader.Port := Value; end; procedure TclWebUpdate.SetProxyBypass(const Value: TStrings); begin FDownloader.ProxyBypass := Value; end; procedure TclWebUpdate.SetReconnectAfter(const Value: Integer); begin FDownloader.ReconnectAfter := Value; end; procedure TclWebUpdate.SetThreadCount(const Value: Integer); begin FDownloader.ThreadCount := Value; end; procedure TclWebUpdate.SetTimeOut(const Value: Integer); begin FDownloader.TimeOut := Value; end; procedure TclWebUpdate.DoProcessCompleted; begin if Assigned(OnProcessCompleted) then begin OnProcessCompleted(Self); end; end; function TclWebUpdate.GetPassiveFtpMode: Boolean; begin Result := FDownloader.PassiveFTPMode; end; function TclWebUpdate.GetPassword: string; begin Result := FDownloader.Password; end; procedure TclWebUpdate.SetPassiveFtpMode(const Value: Boolean); begin FDownloader.PassiveFTPMode := Value; end; procedure TclWebUpdate.SetPassword(const Value: string); begin FDownloader.Password := Value; end; { TclUpdateInfoList } function TclUpdateInfoList.Add: TclUpdateInfoItem; begin Result := TclUpdateInfoItem(inherited Add()); end; constructor TclUpdateInfoList.Create; begin inherited Create(TclUpdateInfoItem); end; function TclUpdateInfoList.GetLastVersion: string; begin if (Count > 0) then begin Result := Items[Count - 1].Version; end else begin Result := ''; end; end; function TclUpdateInfoList.ItemByUrl(const AUrl: string): TclUpdateInfoItem; var i: Integer; begin for i := 0 to Count - 1 do begin if SameText(AUrl, Items[i].URL) then begin Result := Items[i]; Exit; end; end; Result := nil; end; function TclUpdateInfoList.GetFirst(AStatus: TclUpdateStatus): Integer; var i: Integer; begin for i := 0 to Count - 1 do begin if (Items[i].Status = AStatus) then begin Result := i; Exit; end; end; Result := -1; end; function TclUpdateInfoList.GetHasDownloads: Boolean; var i: Integer; begin for i := Count - 1 downto 0 do begin Result := (Items[i].Status = usDownload); if Result then Exit; end; Result := False; end; function TclUpdateInfoList.GetHasUpdates: Boolean; var i: Integer; begin for i := Count - 1 downto 0 do begin Result := (Items[i].Status = usReady); if Result then Exit; end; Result := False; end; function TclUpdateInfoList.GetItem(Index: Integer): TclUpdateInfoItem; begin Result := TclUpdateInfoItem(inherited GetItem(Index)); end; function TclUpdateInfoList.LastItemByStatus(AStatus: TclUpdateStatus): TclUpdateInfoItem; var i: Integer; begin for i := Count - 1 downto 0 do begin if (Items[i].Status = AStatus) then begin Result := Items[i]; Exit; end; end; Result := nil; end; function TclUpdateInfoList.LastItemByUrl(const AUrl: string): TclUpdateInfoItem; var i: Integer; begin for i := Count - 1 downto 0 do begin if SameText(AUrl, Items[i].URL) then begin Result := Items[i]; Exit; end; end; Result := nil; end; procedure TclUpdateInfoList.LoadFromXml(const AFileName: string); var i, ind: Integer; Item: TclUpdateInfoItem; Dom: IXMLDomDocument; NodeList: IXMLDOMNodeList; node: IXMLDomNode; begin Dom := CoDOMDocument.Create(); Dom.load(AFileName); Clear(); NodeList := Dom.selectNodes('updateinfo/update'); for i := 0 to NodeList.length - 1 do begin Item := Add(); Item.FURL := GetAttributeValue(NodeList.item[i], 'url'); Item.FLocalFile := GetAttributeValue(NodeList.item[i], 'localfile'); Item.FSize := GetAttributeValue(NodeList.item[i], 'size'); Item.FVersion := GetAttributeValue(NodeList.item[i], 'version'); Item.FUpdateDate := GetAttributeValue(NodeList.item[i], 'updatedate'); Item.FDescription := GetNodeValueByName(NodeList.item[i], 'description'); Item.FContentType := GetAttributeValue(NodeList.item[i], 'contenttype'); XMLToStrings(Item.UpdateScript, NodeList.item[i].selectSingleNode('script')); ind := IndexOfStrArray(GetAttributeValue(NodeList.item[i], 'status'), cUpdateStatusNames); if (ind > -1) then begin Item.FStatus := TclUpdateStatus(ind); end; ind := IndexOfStrArray(GetAttributeValue(NodeList.item[i], 'terminate'), cBooleanNames); if (ind > -1) then begin Item.FNeedTerminate := Boolean(ind); end; node := NodeList.item[i].selectSingleNode('resourcestate'); if (node <> nil) then begin LoadResourceState(node, Item.ResourceState); end; end; end; procedure TclUpdateInfoList.LoadResourceState(ANode: IXMLDomNode; AResourceState: TclResourceStateList); var i: Integer; NodeList: IXMLDOMNodeList; Item: TclResourceStateItem; begin AResourceState.ResourceSize := StrToIntDef(GetAttributeValue(ANode, 'resourcesize'), 0); NodeList := ANode.selectNodes('item'); for i := 0 to NodeList.length - 1 do begin Item := AResourceState.Add(); Item.ResourcePos := StrToIntDef(GetAttributeValue(NodeList.item[i], 'resourcepos'), 0); Item.BytesToProceed := StrToIntDef(GetAttributeValue(NodeList.item[i], 'bytestoproceed'), 0); Item.BytesProceed := StrToIntDef(GetAttributeValue(NodeList.item[i], 'bytesproceed'), 0); end; end; {$IFDEF DELPHI6} function TclUpdateInfoList.GetBigInt(AValue: Int64): Int64; begin Result := AValue; end; {$ELSE} function TclUpdateInfoList.GetBigInt(AValue: Integer): Integer; begin Result := AValue; end; {$ENDIF} procedure TclUpdateInfoList.SaveResourceState(ANode: IXMLDomNode; AResourceState: TclResourceStateList); var i: Integer; node: IXMLDomNode; begin (ANode as IXMLDOMElement).setAttribute('resourcesize', GetBigInt(AResourceState.ResourceSize)); for i := 0 to AResourceState.Count - 1 do begin node := ANode.ownerDocument.createElement('item'); ANode.appendChild(node); (node as IXMLDOMElement).setAttribute('resourcepos', GetBigInt(AResourceState[i].ResourcePos)); (node as IXMLDOMElement).setAttribute('bytestoproceed', GetBigInt(AResourceState[i].BytesToProceed)); (node as IXMLDOMElement).setAttribute('bytesproceed', GetBigInt(AResourceState[i].BytesProceed)); end; end; procedure TclUpdateInfoList.SaveToXml(const AFileName: string); var i: Integer; Dom: IXMLDomDocument; UpdateInfoNode, Node, tempNode: IXMLDOMElement; begin Dom := CoDOMDocument.Create(); UpdateInfoNode := Dom.createElement('updateinfo'); Dom.appendChild(UpdateInfoNode); for i := 0 to Count - 1 do begin Node := Dom.createElement('update'); UpdateInfoNode.appendChild(Node); SetAttributeValue(Node, 'url', Items[i].URL); SetAttributeValue(Node, 'localfile', Items[i].LocalFile); SetAttributeValue(Node, 'size', Items[i].Size); SetAttributeValue(Node, 'version', Items[i].Version); SetAttributeValue(Node, 'updatedate', Items[i].UpdateDate); tempNode := Dom.createElement('script'); Node.appendChild(tempNode); StringsToXML(Items[i].UpdateScript, tempNode); Node.setAttribute('status', cUpdateStatusNames[Items[i].Status]); Node.setAttribute('terminate', cBooleanNames[Items[i].NeedTerminate]); if (Items[i].ResourceState.Count > 0) then begin tempNode := Dom.createElement('resourcestate'); Node.appendChild(tempNode); SaveResourceState(tempNode, Items[i].ResourceState); end; end; SaveXMLToFile(AFileName, Dom, ['script']); end; procedure TclUpdateInfoList.SetItem(Index: Integer; const Value: TclUpdateInfoItem); begin inherited SetItem(Index, Value); end; { TclUpdateInfoItem } procedure TclUpdateInfoItem.Assign(Source: TPersistent); var src: TclUpdateInfoItem; begin if (Source is TclUpdateInfoItem) then begin src := TclUpdateInfoItem(Source); FURL := src.URL; FVersion := src.Version; FSize := src.Size; FLocalFile := src.LocalFile; FUpdateDate := src.UpdateDate; FStatus := src.Status; FUpdateScript.Assign(src.UpdateScript); FNeedTerminate := src.NeedTerminate; FResourceState.Assign(src.ResourceState); FDescription := src.Description; FContentType := src.ContentType; end else begin inherited Assign(Source); end; end; constructor TclUpdateInfoItem.Create(Collection: TCollection); begin inherited Create(Collection); FUpdateScript := TStringList.Create(); FResourceState := TclResourceStateList.Create(); end; destructor TclUpdateInfoItem.Destroy; begin FResourceState.Free(); FUpdateScript.Free(); inherited Destroy(); end; procedure TclUpdateInfoItem.UpdateStatus(ANewStatus: TclUpdateStatus); begin FStatus := ANewStatus; FUpdateDate := DateTimeToStr(Date()); end; end.
unit mos6566; //{$DEFINE CIA_OLD} interface uses {$IFDEF WINDOWS}windows,{$ENDIF}dialogs,sysutils,pal_engine,cpu_misc, main_engine,gfx_engine; type mos6566_chip=class constructor create(clock:dword); destructor free; public linea:word; vbase:byte; procedure reset; function update(linea_:word):byte; function read(direccion:byte):byte; procedure write(direccion,valor:byte); procedure change_calls(irq_call:cpu_outport_call); procedure ChangedVA(new_va:word); private clock:dword; irq_raster:word; // Interrupt raster line rc:word; // Row counter vc:word; // Video counter vc_base:word; // Video counter base x_scroll:byte; // X scroll value y_scroll:byte; // Y scroll value cia_vabase:word; // CIA VA14/15 video base mx,mc:array[0..7] of word; // VIC registers mx8:byte; my:array[0..7] of byte; mc_color_lookup:array[0..3] of byte; ctrl1, ctrl2:byte; lpx, lpy:byte; me,mxe,mye,mdp,mmc:byte; sprite_on:byte; irq_flag, irq_mask:byte; clx_spr,clx_bgr:byte; ec,mm0,mm1:byte; sc:array[0..7] of byte; display_idx:byte; // Index of current display mode display_state:boolean; // true: Display state, false: Idle state border_on:boolean; // Flag: Upper/lower border on border_40_col:boolean; // Flag: 40 column border bad_lines_enabled:boolean; // Flag: Bad Lines enabled for this frame lp_triggered:boolean; // Flag: Lightpen was triggered in this frame matrix_base:pbyte; // Video matrix base char_base:pbyte; // Character generator base bitmap_base:pbyte; // Bitmap base mm0_color, mm1_color:byte; // Indices for MOB multicolors spr_color:array[0..7] of byte; // Indices for MOB colors row25:boolean; spr_coll_buf:array[0..$17f] of byte; // Buffer for sprite-sprite collisions and priorities fore_mask_buf:array[0..$2f] of byte; // Foreground mask for sprite-graphics collisions and priorities irq_call:cpu_outport_call; procedure raster_irq; function get_physical(direccion:word):pbyte; procedure vblank; procedure draw_sprites; function update_mc(linea:word):byte; end; const c64_paleta:array[0..15] of integer=( $000000,$FDFEFC,$BE1A24,$30E6C6, $B41AE2,$1FD21E,$211BAE,$DFF60A, $B84104,$6A3304,$FE4A57,$424540, $70746F,$59FE59,$5F53FE,$A4A7A2); FIRST_DISP_LINE=$10; //Linea donde empieza lo visible (incluido borde) LAST_DISP_LINE=$11c; //Linea donde termina lo visible (Incluido borde) DISPLAY_X=$195; //Pixels de una linea FIRST_DMA_LINE=$30; LAST_DMA_LINE=$f7; COL40_XSTART=$20; //Pixel donde empieza el borde COL40_XSTOP=$160; //?? COL38_XSTART=$27; //Pixel donde empieza el borde si 38 cols COL38_XSTOP=$157; ExpTable:array[0..255] of word=( $0000, $0003, $000C, $000F, $0030, $0033, $003C, $003F, $00C0, $00C3, $00CC, $00CF, $00F0, $00F3, $00FC, $00FF, $0300, $0303, $030C, $030F, $0330, $0333, $033C, $033F, $03C0, $03C3, $03CC, $03CF, $03F0, $03F3, $03FC, $03FF, $0C00, $0C03, $0C0C, $0C0F, $0C30, $0C33, $0C3C, $0C3F, $0CC0, $0CC3, $0CCC, $0CCF, $0CF0, $0CF3, $0CFC, $0CFF, $0F00, $0F03, $0F0C, $0F0F, $0F30, $0F33, $0F3C, $0F3F, $0FC0, $0FC3, $0FCC, $0FCF, $0FF0, $0FF3, $0FFC, $0FFF, $3000, $3003, $300C, $300F, $3030, $3033, $303C, $303F, $30C0, $30C3, $30CC, $30CF, $30F0, $30F3, $30FC, $30FF, $3300, $3303, $330C, $330F, $3330, $3333, $333C, $333F, $33C0, $33C3, $33CC, $33CF, $33F0, $33F3, $33FC, $33FF, $3C00, $3C03, $3C0C, $3C0F, $3C30, $3C33, $3C3C, $3C3F, $3CC0, $3CC3, $3CCC, $3CCF, $3CF0, $3CF3, $3CFC, $3CFF, $3F00, $3F03, $3F0C, $3F0F, $3F30, $3F33, $3F3C, $3F3F, $3FC0, $3FC3, $3FCC, $3FCF, $3FF0, $3FF3, $3FFC, $3FFF, $C000, $C003, $C00C, $C00F, $C030, $C033, $C03C, $C03F, $C0C0, $C0C3, $C0CC, $C0CF, $C0F0, $C0F3, $C0FC, $C0FF, $C300, $C303, $C30C, $C30F, $C330, $C333, $C33C, $C33F, $C3C0, $C3C3, $C3CC, $C3CF, $C3F0, $C3F3, $C3FC, $C3FF, $CC00, $CC03, $CC0C, $CC0F, $CC30, $CC33, $CC3C, $CC3F, $CCC0, $CCC3, $CCCC, $CCCF, $CCF0, $CCF3, $CCFC, $CCFF, $CF00, $CF03, $CF0C, $CF0F, $CF30, $CF33, $CF3C, $CF3F, $CFC0, $CFC3, $CFCC, $CFCF, $CFF0, $CFF3, $CFFC, $CFFF, $F000, $F003, $F00C, $F00F, $F030, $F033, $F03C, $F03F, $F0C0, $F0C3, $F0CC, $F0CF, $F0F0, $F0F3, $F0FC, $F0FF, $F300, $F303, $F30C, $F30F, $F330, $F333, $F33C, $F33F, $F3C0, $F3C3, $F3CC, $F3CF, $F3F0, $F3F3, $F3FC, $F3FF, $FC00, $FC03, $FC0C, $FC0F, $FC30, $FC33, $FC3C, $FC3F, $FCC0, $FCC3, $FCCC, $FCCF, $FCF0, $FCF3, $FCFC, $FCFF, $FF00, $FF03, $FF0C, $FF0F, $FF30, $FF33, $FF3C, $FF3F, $FFC0, $FFC3, $FFCC, $FFCF, $FFF0, $FFF3, $FFFC, $FFFF); MultiExpTable:array[0..255] of word=( $0000, $0005, $000A, $000F, $0050, $0055, $005A, $005F, $00A0, $00A5, $00AA, $00AF, $00F0, $00F5, $00FA, $00FF, $0500, $0505, $050A, $050F, $0550, $0555, $055A, $055F, $05A0, $05A5, $05AA, $05AF, $05F0, $05F5, $05FA, $05FF, $0A00, $0A05, $0A0A, $0A0F, $0A50, $0A55, $0A5A, $0A5F, $0AA0, $0AA5, $0AAA, $0AAF, $0AF0, $0AF5, $0AFA, $0AFF, $0F00, $0F05, $0F0A, $0F0F, $0F50, $0F55, $0F5A, $0F5F, $0FA0, $0FA5, $0FAA, $0FAF, $0FF0, $0FF5, $0FFA, $0FFF, $5000, $5005, $500A, $500F, $5050, $5055, $505A, $505F, $50A0, $50A5, $50AA, $50AF, $50F0, $50F5, $50FA, $50FF, $5500, $5505, $550A, $550F, $5550, $5555, $555A, $555F, $55A0, $55A5, $55AA, $55AF, $55F0, $55F5, $55FA, $55FF, $5A00, $5A05, $5A0A, $5A0F, $5A50, $5A55, $5A5A, $5A5F, $5AA0, $5AA5, $5AAA, $5AAF, $5AF0, $5AF5, $5AFA, $5AFF, $5F00, $5F05, $5F0A, $5F0F, $5F50, $5F55, $5F5A, $5F5F, $5FA0, $5FA5, $5FAA, $5FAF, $5FF0, $5FF5, $5FFA, $5FFF, $A000, $A005, $A00A, $A00F, $A050, $A055, $A05A, $A05F, $A0A0, $A0A5, $A0AA, $A0AF, $A0F0, $A0F5, $A0FA, $A0FF, $A500, $A505, $A50A, $A50F, $A550, $A555, $A55A, $A55F, $A5A0, $A5A5, $A5AA, $A5AF, $A5F0, $A5F5, $A5FA, $A5FF, $AA00, $AA05, $AA0A, $AA0F, $AA50, $AA55, $AA5A, $AA5F, $AAA0, $AAA5, $AAAA, $AAAF, $AAF0, $AAF5, $AAFA, $AAFF, $AF00, $AF05, $AF0A, $AF0F, $AF50, $AF55, $AF5A, $AF5F, $AFA0, $AFA5, $AFAA, $AFAF, $AFF0, $AFF5, $AFFA, $AFFF, $F000, $F005, $F00A, $F00F, $F050, $F055, $F05A, $F05F, $F0A0, $F0A5, $F0AA, $F0AF, $F0F0, $F0F5, $F0FA, $F0FF, $F500, $F505, $F50A, $F50F, $F550, $F555, $F55A, $F55F, $F5A0, $F5A5, $F5AA, $F5AF, $F5F0, $F5F5, $F5FA, $F5FF, $FA00, $FA05, $FA0A, $FA0F, $FA50, $FA55, $FA5A, $FA5F, $FAA0, $FAA5, $FAAA, $FAAF, $FAF0, $FAF5, $FAFA, $FAFF, $FF00, $FF05, $FF0A, $FF0F, $FF50, $FF55, $FF5A, $FF5F, $FFA0, $FFA5, $FFAA, $FFAF, $FFF0, $FFF5, $FFFA, $FFFF); var mos6566_0:mos6566_chip; matrix_line,color_line:array[0..39] of byte; implementation uses commodore64,{$IFNDEF CIA_OLD}mos6526{$ELSE}mos6526_old{$ENDIF}; constructor mos6566_chip.create(clock:dword); var f:byte; colores:tpaleta; begin self.clock:=clock; for f:=0 to 15 do begin colores[f].r:=c64_paleta[f] shr 16; colores[f].g:=(c64_paleta[f] shr 8) and $ff; colores[f].b:=c64_paleta[f] and $ff; end; set_pal(colores,16); self.reset; end; destructor mos6566_chip.free; begin end; procedure mos6566_chip.change_calls(irq_call:cpu_outport_call); begin self.irq_call:=irq_call; end; procedure mos6566_chip.reset; var f:byte; begin self.linea:=0; self.irq_raster:=0; // Interrupt raster line self.rc:=7; // Row counter self.vc:=0; // Video counter self.vc_base:=0; // Video counter base self.x_scroll:=0; // X scroll value self.y_scroll:=0; // Y scroll value self.cia_vabase:=0; // CIA VA14/15 video base for f:=0 to 7 do begin mx[f]:=0; my[f]:=0; sc[f]:=0; spr_color[f]:=0; mc[f]:=63; end; for f:=0 to 3 do self.mc_color_lookup[f]:=0; for f:=0 to $2f do fore_mask_buf[f]:=0; self.ctrl1:=0; self.ctrl2:=0; self.lpx:=0; self.lpy:=0; self.sprite_on:=0; self.me:=0; self.mxe:=0; self.mye:=0; self.mdp:=0; self.mmc:=0; self.vbase:=0; self.irq_flag:=0; self.irq_mask:=0; self.clx_spr:=0; self.clx_bgr:=0; self.ec:=0; self.mm0:=0; self.mm1:=0; self.display_idx:=0; // Index of current display mode self.display_state:=false; // true: Display state, false: Idle state self.border_on:=false; // Flag: Upper/lower border on self.border_40_col:=false; // Flag: 40 column border self.bad_lines_enabled:=false; // Flag: Bad Lines enabled for this frame self.lp_triggered:=false; self.matrix_base:=@memoria[0]; // Video matrix base self.char_base:=@memoria[0]; // Character generator base self.bitmap_base:=@memoria[0]; // Bitmap base self.mm0_color:=0; self.mm1_color:=0; // Indices for MOB multicolors end; procedure mos6566_chip.ChangedVA(new_va:word); begin self.cia_vabase:=new_va shl 14; self.write($18,self.vbase); // Force update of memory pointers end; function mos6566_chip.get_physical(direccion:word):pbyte; var va:word; ret:pbyte; begin va:=direccion or self.cia_vabase; if (((va and $f000)=$9000) or ((va and $f000)=$1000)) then ret:=@char_rom[va and $fff] else ret:=@memoria[va]; get_physical:=ret; end; function mos6566_chip.read(direccion:byte):byte; var ret:byte; begin case direccion of 0,2,4,6,8,$a,$c,$e:ret:=self.mx[direccion shr 1]; 1,3,5,7,9,$b,$d,$f:ret:=self.my[direccion shr 1]; $10:ret:=self.mx8; // Sprite X position MSB $11:ret:=(self.ctrl1 and $7f) or ((self.linea and $100) shr 1); // Control register 1 $12:ret:=self.linea; // Raster counter $13:ret:=self.lpx; // Light pen X $14:ret:=self.lpy; // Light pen Y $15:ret:=self.me; // Sprite enable $16:ret:=self.ctrl2 or $c0; // Control register 2 $17:ret:=self.mye; // Sprite Y expansion $18:ret:=self.vbase or $01; // Memory pointers $19:ret:=self.irq_flag or $70; // IRQ flags $1a:ret:=self.irq_mask or $f0; // IRQ mask $1b:ret:=self.mdp; // Sprite data priority $1c:ret:=self.mmc; // Sprite multicolor $1d:ret:=self.mxe; // Sprite X expansion $1e:begin // Sprite-sprite collision ret:=self.clx_spr; self.clx_spr:=0; // Read and clear end; $1f:begin // Sprite-background collision ret:=self.clx_bgr; self.clx_bgr:=0; // Read and clear end; $20:ret:=self.ec or $f0; $21:ret:=self.mc_color_lookup[0] or $f0; $22:ret:=self.mc_color_lookup[1] or $f0; $23:ret:=self.mc_color_lookup[2] or $f0; $24:ret:=self.mc_color_lookup[3] or $f0; $25:ret:=self.mm0 or $f0; $26:ret:=self.mm1 or $f0; $27,$28,$29,$2a,$2b,$2c,$2d,$2e:ret:=self.sc[direccion-$27] or $f0; else ret:=$ff; end; read:=ret; end; procedure mos6566_chip.raster_irq; begin self.irq_flag:=self.irq_flag or $01; if (self.irq_mask and $01)<>0 then begin self.irq_flag:=irq_flag or $80; self.irq_call(ASSERT_LINE); end; end; procedure mos6566_chip.write(direccion,valor:byte); var j,new_irq_raster:word; i:byte; begin case direccion of 0,2,4,6,8,$a,$c,$e:self.mx[direccion shr 1]:=(self.mx[direccion shr 1] and $ff00) or valor; 1,3,5,7,9,$b,$d,$f:self.my[direccion shr 1]:=valor; $10:begin self.mx8:=valor; j:=1; for i:=0 to 7 do begin if (self.mx8 and j)<>0 then self.mx[i]:=self.mx[i] or $100 else self.mx[i]:=self.mx[i] and $ff; j:=j shl 1; end; end; $11:begin // Control register 1 self.ctrl1:=valor; self.y_scroll:=valor and 7; new_irq_raster:=(self.irq_raster and $ff) or ((valor and $80) shl 1); if ((self.irq_raster<>new_irq_raster) and (self.linea=new_irq_raster)) then self.raster_irq; self.irq_raster:=new_irq_raster; self.row25:=(valor and 8)<>0; self.display_idx:=((self.ctrl1 and $60) or (self.ctrl2 and $10)) shr 4; end; $12:begin // Raster counter new_irq_raster:=(self.irq_raster and $ff00) or valor; if ((self.irq_raster<>new_irq_raster) and (self.linea=new_irq_raster)) then self.raster_irq; self.irq_raster:=new_irq_raster; end; $15:self.me:=valor; // Sprite enable $16:begin // Control register 2 self.ctrl2:=valor; self.x_scroll:=valor and 7; self.border_40_col:=(valor and 8)<>0; self.display_idx:=((self.ctrl1 and $60) or (self.ctrl2 and $10)) shr 4; end; $17:self.mye:=valor; // Sprite Y expansion $18:begin // Memory pointers self.vbase:=valor; self.matrix_base:=self.get_physical((valor and $f0) shl 6); self.char_base:=self.get_physical((valor and $0e) shl 10); self.bitmap_base:=self.get_physical((valor and $08) shl 10); end; $19:begin // IRQ flags self.irq_flag:=self.irq_flag and (not(valor) and $0f); self.irq_call(CLEAR_LINE); if (self.irq_flag and self.irq_mask)<>0 then self.irq_flag:=self.irq_flag or $80; // Set master bit if allowed interrupt still pending end; $1a:begin // IRQ mask self.irq_mask:=valor and $0f; if (self.irq_flag and self.irq_mask)<>0 then begin // Trigger interrupt if pending and now allowed self.irq_flag:=self.irq_flag or $80; self.irq_call(ASSERT_LINE); end else begin self.irq_flag:=self.irq_flag and $7f; self.irq_call(CLEAR_LINE); end; end; $1b:self.mdp:=valor; // Sprite data priority $1c:self.mmc:=valor; // Sprite multicolor $1d:self.mxe:=valor; // Sprite X expansion $20:self.ec:=valor and $f; $21:self.mc_color_lookup[0]:=valor and $f; $22:self.mc_color_lookup[1]:=valor and $f; $23:self.mc_color_lookup[2]:=valor and $f; $24:self.mc_color_lookup[3]:=valor and $f; $25:begin self.mm0:=valor; self.mm0_color:=valor and $f; end; $26:begin self.mm1:=valor; self.mm1_color:=valor and $f; end; $27,$28,$29,$2a,$2b,$2c,$2d,$2e:begin self.sc[direccion-$27]:=valor; self.spr_color[direccion-$27]:=valor and $f; end; end; end; procedure mos6566_chip.vblank; begin self.vc_base:=0; self.lp_triggered:=false; {$IFNDEF CIA_OLD} mos6526_0.CountTOD1; mos6526_0.CountTOD2; {$ELSE} mos6526_0.clock_tod; mos6526_1.clock_tod; {$ENDIF} end; procedure mos6566_chip.draw_sprites; var snum,sbit:byte; spr_coll,gfx_coll:byte; ptemp:pword; color,coll_pos:byte; ptemp1:pbyte; col,f,ptempb:byte; plane0_r,plane1_r,plane0_l,plane1_l,sdata,fore_mask,sdata_l,sdata_r,fore_mask_r:dword; sshift,spr_mask_pos:byte; begin spr_coll:=0; gfx_coll:=0; sbit:=1; for snum:=0 to 7 do begin if (((self.sprite_on and sbit)<>0) and (self.mx[snum]<(DISPLAY_X-32))) then begin ptemp:=punbuf; inc(ptemp,self.mx[snum]+8); coll_pos:=self.mx[snum]+8; //Datos ptemp1:=self.get_physical(self.matrix_base[$3f8+snum] shl 6 or self.mc[snum]); sdata:=(ptemp1^ shl 24);inc(ptemp1); sdata:=sdata or (ptemp1^ shl 16);inc(ptemp1); sdata:=sdata or (ptemp1^ shl 8); color:=spr_color[snum] and $f; //Color //Back foreground spr_mask_pos:=coll_pos-self.x_scroll; ptempb:=spr_mask_pos div 8; sshift:=spr_mask_pos and 7; fore_mask:=(self.fore_mask_buf[ptempb] shl 24) or (self.fore_mask_buf[ptempb+1] shl 16) or (self.fore_mask_buf[ptempb+2] shl 8) or (self.fore_mask_buf[ptempb+3] shl sshift) or (self.fore_mask_buf[ptempb+4] shr (8-sshift)); if (self.mxe and sbit)<>0 then begin //X_expanded if (self.mx[snum]>=(DISPLAY_X-56)) then continue; fore_mask_r:=(self.fore_mask_buf[ptempb+4] shl 24) or (self.fore_mask_buf[ptempb+5] shl 16) or (self.fore_mask_buf[ptempb+6] shl 8) or (self.fore_mask_buf[ptempb+7] shl sshift) or (self.fore_mask_buf[ptempb+8] shr (8-sshift)); if (self.mmc and sbit)<>0 then begin // Multicolor mode // Expand sprite data sdata_l:=MultiExpTable[(sdata shr 24) and $ff] shl 16 or MultiExpTable[(sdata shr 16) and $ff]; sdata_r:=0 or MultiExpTable[(sdata shr 8) and $ff] shl 16; // Convert sprite chunky pixels to bitplanes plane0_l:=(sdata_l and $55555555) or (sdata_l and $55555555) shl 1; plane1_l:=(sdata_l and $aaaaaaaa) or (sdata_l and $aaaaaaaa) shr 1; plane0_r:=(sdata_r and $55555555) or (sdata_r and $55555555) shl 1; plane1_r:=(sdata_r and $aaaaaaaa) or (sdata_r and $aaaaaaaa) shr 1; // Collision with graphics? if (((fore_mask and (plane0_l or plane1_l))<>0) or ((fore_mask_r and (plane0_r or plane1_r))<>0)) then begin gfx_coll:=gfx_coll or sbit; if (self.mdp and sbit)<>0 then begin plane0_l:=plane0_l and not(fore_mask); // Mask sprite if in background plane1_l:=plane1_l and not(fore_mask); plane0_r:=plane0_r and not(fore_mask_r); plane1_r:=plane1_r and not(fore_mask_r); end; end; // Paint sprite for f:=0 to 31 do begin if (plane1_l and $80000000)<>0 then begin if (plane0_l and $80000000)<>0 then col:=mm1 else col:=color; end else begin if (plane0_l and $80000000)<>0 then col:=mm0 else begin inc(ptemp); plane0_l:=plane0_l shl 1; plane1_l:=plane1_l shl 1; continue; end; end; if self.spr_coll_buf[coll_pos+f]<>0 then spr_coll:=spr_coll or self.spr_coll_buf[coll_pos+f] or sbit else begin ptemp^:=paleta[col]; self.spr_coll_buf[coll_pos+f]:=sbit; end; inc(ptemp); plane0_l:=plane0_l shl 1; plane1_l:=plane1_l shl 1; end; for f:=32 to 47 do begin if (plane1_r and $80000000)<>0 then begin if (plane0_r and $80000000)<>0 then col:=mm1 else col:=color; end else begin if (plane0_r and $80000000)<>0 then col:=mm0 else begin inc(ptemp); plane0_r:=plane0_r shl 1; plane1_r:=plane1_r shl 1; continue; end; end; // Collision with sprite? if self.spr_coll_buf[coll_pos+f]<>0 then begin spr_coll:=spr_coll or self.spr_coll_buf[coll_pos+f] or sbit; end else begin // Draw pixel if no collision ptemp^:=paleta[col]; self.spr_coll_buf[coll_pos+f]:=sbit; end; inc(ptemp); plane0_r:=plane0_r shl 1; plane1_r:=plane1_r shl 1; end; end else begin // Standard mode // Expand sprite data sdata_l:=(ExpTable[(sdata shr 24) and $ff] shl 16) or ExpTable[(sdata shr 16) and $ff]; sdata_r:=ExpTable[(sdata shr 8) and $ff] shl 16; // Collision with graphics? if (((fore_mask and sdata_l)<>0) or ((fore_mask_r and sdata_r)<>0)) then begin gfx_coll:=gfx_coll or sbit; if (self.mdp and sbit)<>0 then begin sdata_l:=sdata_l and not(fore_mask); // Mask sprite if in background sdata_r:=sdata_r and not(fore_mask_r); end; end; // Paint sprite for f:=0 to 31 do begin if (sdata_l and $80000000)<>0 then begin // Collision with sprite? if self.spr_coll_buf[coll_pos+f]<>0 then begin spr_coll:=spr_coll or self.spr_coll_buf[coll_pos+f] or sbit end else begin // Draw pixel if no collision ptemp^:=paleta[color]; self.spr_coll_buf[coll_pos+f]:=sbit; end; end; inc(ptemp); sdata_l:=sdata_l shl 1; end; for f:=32 to 47 do begin if (sdata_r and $80000000)<>0 then begin // Collision with sprite? if self.spr_coll_buf[coll_pos+f]<>0 then begin spr_coll:=spr_coll or self.spr_coll_buf[coll_pos+f] or sbit; end else begin // Draw pixel if no collision ptemp^:=paleta[color]; self.spr_coll_buf[coll_pos+f]:=sbit; end; end; inc(ptemp); sdata_r:=sdata_r shl 1; end; end; end else begin //No expanded if (self.mmc and sbit)<>0 then begin // Multicolor mode // Convert sprite chunky pixels to bitplanes plane0_l:=(sdata and $55555555) or ((sdata and $55555555) shl 1); plane1_l:=(sdata and $aaaaaaaa) or ((sdata and $aaaaaaaa) shr 1); // Collision with graphics? if (fore_mask and (plane0_l or plane1_l))<>0 then begin gfx_coll:=gfx_coll or sbit; if (self.mdp and sbit)<>0 then begin plane0_l:=plane0_l and not(fore_mask); // Mask sprite if in background plane1_l:=plane1_l and not(fore_mask); end; end; // Paint sprite for f:=0 to 23 do begin if (plane1_l and $80000000)<>0 then begin if (plane0_l and $80000000)<>0 then col:=self.mm1 else col:=color; end else begin if (plane0_l and $80000000)<>0 then col:=self.mm0 else begin inc(ptemp); plane0_l:=plane0_l shl 1; plane1_l:=plane1_l shl 1; continue; end; end; if self.spr_coll_buf[coll_pos+f]<>0 then spr_coll:=self.spr_coll_buf[coll_pos+f] or sbit else begin ptemp^:=paleta[col]; self.spr_coll_buf[coll_pos+f]:=sbit; end; plane0_l:=plane0_l shl 1; plane1_l:=plane1_l shl 1; inc(ptemp); end; end else begin // Standard mode // Collision with graphics? {if (fore_mask and sdata)<>0 then begin gfx_coll:=gfx_coll or sbit; if (self.mdp and sbit)<>0 then sdata:=sdata and not(fore_mask); // Mask sprite if in background end;} // Paint sprite for f:=0 to 23 do begin if (sdata and $80000000)<>0 then begin // Collision with sprite? if (self.spr_coll_buf[coll_pos+f]<>0) then begin spr_coll:=spr_coll or self.spr_coll_buf[coll_pos+f] or sbit; end else begin // Draw pixel if no collision ptemp^:=paleta[color]; self.spr_coll_buf[coll_pos+f]:=sbit; end; end; inc(ptemp); sdata:=sdata shl 1; end; end; end; end; // Check sprite-sprite collisions if (self.clx_spr<>0) then self.clx_spr:=self.clx_spr or spr_coll else begin self.clx_spr:=self.clx_spr or spr_coll; self.irq_flag:=self.irq_flag or $04; if (self.irq_mask and $04)<>0 then begin self.irq_flag:=self.irq_flag or $80; self.irq_call(ASSERT_LINE); end; end; // Check sprite-background collisions if (self.clx_bgr<>0) then self.clx_bgr:=self.clx_bgr or gfx_coll else begin self.clx_bgr:=self.clx_bgr or gfx_coll; self.irq_flag:=self.irq_flag or $02; if (self.irq_mask and $02)<>0 then begin self.irq_flag:=self.irq_flag or $80; self.irq_call(ASSERT_LINE); end; end; sbit:=sbit shl 1; end; //del for end; function mos6566_chip.update_mc(linea:word):byte; var i,j:byte; cycles_used:byte; spron,spren,sprye:byte; begin spron:=self.sprite_on; spren:=self.me; sprye:=self.mye; cycles_used:=0; // Increment sprite data counters j:=1; for i:=0 to 7 do begin // Sprite enabled? if (spren and j)<>0 then // Yes, activate if Y position matches raster counter if (my[i]=(linea and $ff)) then begin self.mc[i]:=0; spron:=spron or j; // No, turn sprite off when data counter exceeds 60 and increment counter end else if (self.mc[i]<>63) then begin if (sprye and j)<>0 then begin // Y expansion if (((self.my[i] xor (linea and $ff)) and 1)=0) then begin self.mc[i]:=self.mc[i]+3; cycles_used:=cycles_used+2; if (self.mc[i]=63) then spron:=spron and not(j); end; end else begin self.mc[i]:=self.mc[i]+3; cycles_used:=cycles_used+2; if (self.mc[i]=63) then spron:=spron and not(j); end; end else if (self.mc[i]<>63) then begin if (sprye and j)<>0 then begin // Y expansion if (((self.my[i] xor (linea and $ff)) and 1)=0) then begin self.mc[i]:=self.mc[i]+3; cycles_used:=cycles_used+2; if (self.mc[i]=63) then spron:=spron and not(j); end; end else begin self.mc[i]:=self.mc[i]+3; cycles_used:=cycles_used+2; if (self.mc[i]=63) then spron:=spron and not(j); end; end; j:=j shl 1; end; self.sprite_on:=spron; update_mc:=cycles_used; end; function mos6566_chip.update(linea_:word):byte; var ptemp:pword; cycles_left:byte; is_bad_line:boolean; pbyte1,pbyte2,ptemp1,ptemp2:pbyte; procedure pinta_linea; var f,h,color,color2,bcolor,bcolor2,data:byte; lookup:array[0..3] of byte; begin ptemp:=punbuf; inc(ptemp,32); if self.display_state then begin fillword(ptemp,self.x_scroll,paleta[self.mc_color_lookup[0]]); case self.display_idx of 0:for f:=0 to 39 do begin //Texto normal color:=color_line[f] and $f; ptemp1:=char_base; inc(ptemp1,(matrix_line[f] shl 3)+self.rc); data:=ptemp1^; fore_mask_buf[f+4]:=data; for h:=0 to 7 do begin if (data and $80)=0 then ptemp^:=paleta[self.mc_color_lookup[0]] else ptemp^:=paleta[color]; data:=data shl 1; inc(ptemp); end; end; 1:for f:=0 to 39 do begin ptemp1:=char_base; inc(ptemp1,rc); inc(ptemp1,(matrix_line[f] shl 3)); data:=ptemp1^; if (color_line[f] and 8)<>0 then begin self.mc_color_lookup[3]:=color_line[f] and 7; fore_mask_buf[f+4]:=(data and $aa) or (data and $aa) shr 1; color:=self.mc_color_lookup[(data shr 6) and 3]; ptemp^:=paleta[color];inc(ptemp); ptemp^:=paleta[color];inc(ptemp); color:=self.mc_color_lookup[(data shr 4) and 3]; ptemp^:=paleta[color];inc(ptemp); ptemp^:=paleta[color];inc(ptemp); color:=self.mc_color_lookup[(data shr 2) and 3]; ptemp^:=paleta[color];inc(ptemp); ptemp^:=paleta[color];inc(ptemp); color:=self.mc_color_lookup[(data shr 0) and 3]; ptemp^:=paleta[color];inc(ptemp); ptemp^:=paleta[color];inc(ptemp); end else begin // Standard mode in multicolor mode color:=color_line[f] and $f; fore_mask_buf[f+4]:=data; for h:=0 to 7 do begin if (data and $80)=0 then begin ptemp^:=paleta[self.mc_color_lookup[0]]; inc(ptemp); end else begin ptemp^:=paleta[color]; inc(ptemp); end; data:=data shl 1; end; end; end; 2:begin //standar gfx ptemp1:=bitmap_base; inc(ptemp1,(vc shl 3)+rc); for f:=0 to 39 do begin data:=ptemp1^; inc(ptemp1,8); fore_mask_buf[f+4]:=data; color:=matrix_line[f] shr 4; bcolor:=matrix_line[f] and $f; for h:=0 to 7 do begin if (data and $80)=0 then ptemp^:=paleta[bcolor] else ptemp^:=paleta[color]; data:=data shl 1; inc(ptemp); end; end; end; 3:begin //160x200 multi color lookup[0]:=self.mc_color_lookup[0]; ptemp1:=bitmap_base; inc(ptemp1,(vc shl 3)+rc); for f:=0 to 39 do begin lookup[1]:=matrix_line[f] shr 4; lookup[2]:=matrix_line[f] and $f; lookup[3]:=color_line[f] and $f; data:=ptemp1^; inc(ptemp1,8); fore_mask_buf[f+4]:=(data and $aa) or (data and $aa) shr 1; color:=lookup[(data shr 6) and 3]; ptemp^:=paleta[color];inc(ptemp); ptemp^:=paleta[color];inc(ptemp); color:=lookup[(data shr 4) and 3]; ptemp^:=paleta[color];inc(ptemp); ptemp^:=paleta[color];inc(ptemp); color:=lookup[(data shr 2) and 3]; ptemp^:=paleta[color];inc(ptemp); ptemp^:=paleta[color];inc(ptemp); color:=lookup[(data shr 0) and 3]; ptemp^:=paleta[color];inc(ptemp); ptemp^:=paleta[color];inc(ptemp); end; end; 4:for f:=0 to 39 do begin data:=matrix_line[f]; fore_mask_buf[f+4]:=data; color:=color_line[f]; bcolor:=self.mc_color_lookup[(data shr 6) and 3]; ptemp1:=char_base; inc(ptemp1,rc); inc(ptemp1,(data and $3f) shl 3); data:=ptemp1^; for h:=0 to 7 do begin if (data and $80)=0 then ptemp^:=paleta[bcolor] else ptemp^:=paleta[color]; data:=data shl 1; inc(ptemp); end; end; 5,6,7:fillword(ptemp,320,paleta[0]); //Invalid! end; self.vc:=self.vc+40; end else begin case self.display_idx of 0,1,4:begin if (ctrl1 and $40)<>0 then ptemp1:=get_physical($39ff) else ptemp1:=get_physical($3fff); data:=ptemp1^; for f:=0 to 39 do begin fore_mask_buf[f+4]:=data; for h:=0 to 7 do begin if (data and $80)=0 then ptemp^:=paleta[self.mc_color_lookup[0]] else ptemp^:=paleta[0]; data:=data shl 1; inc(ptemp); end; end; end; 3:begin ptemp1:=get_physical($3fff); data:=ptemp1^; lookup[0]:=self.mc_color_lookup[0]; lookup[1]:=0; lookup[2]:=0; lookup[3]:=0; color:=lookup[(data shr 6) and 3]; color2:=lookup[(data shr 4) and 3]; bcolor:=lookup[(data shr 2) and 3]; bcolor2:=lookup[(data shr 0) and 3]; for f:=0 to 39 do begin ptemp^:=paleta[color];inc(ptemp); ptemp^:=paleta[color];inc(ptemp); ptemp^:=paleta[color2];inc(ptemp); ptemp^:=paleta[color2];inc(ptemp); ptemp^:=paleta[bcolor];inc(ptemp); ptemp^:=paleta[bcolor];inc(ptemp); ptemp^:=paleta[bcolor2];inc(ptemp); ptemp^:=paleta[bcolor2];inc(ptemp); fore_mask_buf[f+4]:=data; end; end; 2,5,6,7:fillword(ptemp,320,paleta[0]); //Invalid! end; end; //Draw sprites //fillword(punbuf,384,0); if (self.sprite_on<>0) then begin fillchar(self.spr_coll_buf,$180,0); self.draw_sprites; end; //Bordes izq y der ptemp:=punbuf; if border_40_col then begin fillword(ptemp,32,paleta[self.ec]); inc(ptemp,352); fillword(ptemp,32,paleta[self.ec]); end else begin fillword(ptemp,32,paleta[self.ec]); inc(ptemp,336); fillword(ptemp,32+16,paleta[self.ec]); end; end; begin self.linea:=linea_; // Trigger raster IRQ if IRQ line reached if (linea_=self.irq_raster) then self.raster_irq; // Vblank? case linea_ of 0..15,301..311:begin //estoy en Vblank update:=63; exit; end; 300:begin //empiezo vblank self.vblank; update:=63; exit; end; end; cycles_left:=63; // Cycles left for CPU is_bad_line:=false; // In line $30, the DEN bit controls if Bad Lines can occur if (linea_=$30) then self.bad_lines_enabled:=(self.ctrl1 and $10)<>0; // Estoy dentro de lo visible? Si no, estoy en vblank if ((linea_>=FIRST_DISP_LINE) and (linea_<=LAST_DISP_LINE)) then begin // Set video counter self.vc:=self.vc_base; // Bad Line condition? Si es asi, cojo los datos para las siguientes 8 lineas!! if ((linea_>=FIRST_DMA_LINE) and (linea_<=LAST_DMA_LINE) and (((linea_ and 7)=self.y_scroll)) and bad_lines_enabled) then begin // Turn on display self.display_state:=true; is_bad_line:=true; cycles_left:=23; self.rc:=0; // Cojo 40 bytes de los datos para pintar la pantalla pbyte1:=@matrix_line[0]; pbyte2:=@color_line[0]; ptemp1:=matrix_base; inc(ptemp1,self.vc); ptemp2:=@color_ram[0]; inc(ptemp2,self.vc); copymemory(pbyte1,ptemp1,40); copymemory(pbyte2,ptemp2,40); end; ptemp:=punbuf; case linea_ of 16..50,251..299:fillword(ptemp,384,paleta[self.ec]); //borde 51..54,247..250:if self.row25 then pinta_linea else fillword(ptemp,384,paleta[self.ec]); //borde 55..246:pinta_linea; end; // Increment row counter, go to idle state on overflow if (self.rc=7) then begin self.display_state:=false; self.vc_base:=self.vc; end else self.rc:=self.rc+1; if ((linea_>=FIRST_DMA_LINE-1) and (linea_<=LAST_DMA_LINE-1) and ((((linea_+1) and 7)=self.y_scroll)) and self.bad_lines_enabled) then self.rc:=0; end; if (self.me or self.sprite_on)<>0 then cycles_left:=cycles_left-self.update_mc(linea_); update:=cycles_left; end; end.
unit uPlanoContasC; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uModelo, ZAbstractDataset, ZDataset, DB, ZAbstractRODataset, ZConnection, ActnList, Grids, DBGrids, RPDBGrid, ComCtrls, DBCtrls, Buttons, ExtCtrls, StdCtrls, JvExControls, JvNavigationPane, JvExMask, JvToolEdit, JvDBControls, Mask, JvExStdCtrls, JvCombobox, JvDBCombobox, CheckDoc, funcoes, JvSpeedButton, udmPrincipal; type TfrmPlanoContasC = class(TfrmModelo) qrFicha: TZQuery; qrGrid: TZReadOnlyQuery; qrGridid: TSmallintField; qrGridcod_nat_cc: TStringField; qrGridind_cta: TStringField; qrGridnivel: TLargeintField; qrGridcod_cta: TStringField; qrGridnome_cta: TStringField; qrGridcod_cta_ref: TStringField; qrGridcnpj_est: TStringField; qrGridativo: TStringField; qrFichaid: TSmallintField; qrFichacod_nat_cc: TStringField; qrFichaind_cta: TStringField; qrFichanivel: TLargeintField; qrFichacod_cta: TStringField; qrFichanome_cta: TStringField; qrFichacod_cta_ref: TStringField; qrFichacnpj_est: TStringField; qrFichaativo: TStringField; JvNavPanelHeader1: TJvNavPanelHeader; DBText2: TDBText; DBText1: TDBText; lbControle: TLabel; Bevel1: TBevel; PageControl2: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; jvnvpnlhdr1: TJvNavPanelHeader; lbl1: TLabel; Bevel2: TBevel; Label1: TLabel; DBEdit1: TDBEdit; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Bevel3: TBevel; Label10: TLabel; JvDBDateEdit1: TJvDBDateEdit; DBEdit2: TDBEdit; DBEdit3: TDBEdit; JvDBDateEdit2: TJvDBDateEdit; qrFichauser_inclusao: TStringField; qrFichauser_alteracao: TStringField; qrGriduser_inclusao: TStringField; qrGriduser_alteracao: TStringField; JvDBComboBox1: TJvDBComboBox; JvDBComboBox2: TJvDBComboBox; DBEdit4: TDBEdit; DBEdit5: TDBEdit; Label11: TLabel; DBEdit6: TDBEdit; Label12: TLabel; DBCheckDocEdit1: TDBCheckDocEdit; Bevel4: TBevel; Label13: TLabel; Bevel5: TBevel; Label14: TLabel; Label15: TLabel; qrFichadata_inclusao: TDateField; qrFichadata_alteracao: TDateField; qrGriddata_inclusao: TDateField; qrGriddata_alteracao: TDateField; JvSpeedButton1: TJvSpeedButton; Label16: TLabel; Bevel6: TBevel; Label17: TLabel; JvDBComboBox3: TJvDBComboBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actNovoExecute(Sender: TObject); procedure actAlterarExecute(Sender: TObject); procedure actGravaExecute(Sender: TObject); procedure qrGridativoGetText(Sender: TField; var Text: string; DisplayText: Boolean); procedure qrGridind_ctaGetText(Sender: TField; var Text: string; DisplayText: Boolean); procedure JvSpeedButton1Click(Sender: TObject); procedure actExcluirExecute(Sender: TObject); procedure actImprimeExecute(Sender: TObject); procedure dsFichaDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } end; var frmPlanoContasC: TfrmPlanoContasC; implementation {$R *.dfm} procedure TfrmPlanoContasC.FormCreate(Sender: TObject); begin inherited; qrGrid.Open; qrFicha.Open; end; procedure TfrmPlanoContasC.FormDestroy(Sender: TObject); begin inherited; qrGrid.Close; qrFicha.Close; end; procedure TfrmPlanoContasC.actNovoExecute(Sender: TObject); begin inherited; if DBEdit1.CanFocus then DBEdit1.SetFocus end; procedure TfrmPlanoContasC.actAlterarExecute(Sender: TObject); begin inherited; if DBEdit1.CanFocus then DBEdit1.SetFocus end; procedure TfrmPlanoContasC.actGravaExecute(Sender: TObject); var ID: Integer; begin if StringEmBranco(qrFichacod_cta.AsString) then begin MessageBox(handle, 'O Código não pode ser nulo!', 'Erro', mb_ok + mb_IconError); if DBEdit1.CanFocus then DBEdit1.SetFocus; Exit; end; if StringEmBranco(qrFichacod_nat_cc.AsString) then begin MessageBox(handle, 'O Código da Natureza pode ser nulo!', 'Erro', mb_ok + mb_IconError); if JvDBComboBox1.CanFocus then JvDBComboBox1.SetFocus; Exit; end; if StringEmBranco(qrFichaind_cta.AsString) then begin MessageBox(handle, 'O Indicador da conta pode ser nulo!', 'Erro', mb_ok + mb_IconError); if JvDBComboBox2.CanFocus then JvDBComboBox2.SetFocus; Exit; end; if StringEmBranco(qrFichanome_cta.AsString) then begin MessageBox(handle, 'O nome da conta pode ser nulo!', 'Erro', mb_ok + mb_IconError); if DBEdit5.CanFocus then DBEdit5.SetFocus; Exit; end; if qrFicha.State = dsInsert then begin qrFicha['user_inclusao'] := dmPrincipal.usuario; qrFicha['data_inclusao'] := dmPrincipal.DataHora; end else begin qrFicha['user_alteracao'] := dmPrincipal.usuario; qrFicha['data_alteracao'] := dmPrincipal.SoData; end; inherited; qrGrid.Refresh; qrGrid.Locate('id', ID, []); actGridFicha.Execute; end; procedure TfrmPlanoContasC.qrGridativoGetText(Sender: TField; var Text: string; DisplayText: Boolean); begin inherited; if Sender.AsString = 'S' then Text := 'SIM' else if Sender.AsString = 'N' then Text := 'NÃO'; end; procedure TfrmPlanoContasC.qrGridind_ctaGetText(Sender: TField; var Text: string; DisplayText: Boolean); begin inherited; if Sender.AsString = 'S' then Text := 'SINTÉTICO' else if Sender.AsString = 'A' then Text := 'ANALÍTICO'; end; procedure TfrmPlanoContasC.JvSpeedButton1Click(Sender: TObject); begin inherited; qrFichacnpj_est.Clear end; procedure TfrmPlanoContasC.actExcluirExecute(Sender: TObject); begin if MessageBox(Handle, PChar('Essa opção NÃO irá excluir sua conta, mas vai desativá-la. Tem certeza que deseja DESATIVAR a conta?'), 'Atenção', MB_ICONINFORMATION + MB_YESNO + MB_DEFBUTTON2) = IDYES then begin qrFicha.Edit; qrFicha['ativo'] := 'N'; qrFicha['user_alteracao'] := dmPrincipal.usuario; qrFicha['data_alteracao'] := dmPrincipal.SoData; qrFicha.Post; qrGrid.Refresh; end end; procedure TfrmPlanoContasC.actImprimeExecute(Sender: TObject); begin inherited; RPDBGrid1.Print; end; procedure TfrmPlanoContasC.dsFichaDataChange(Sender: TObject; Field: TField); begin inherited; (***** Barra de Status *****) if StringEmBranco(qrFichauser_inclusao.AsString) then StatusBar1.Panels[1].Text := '' else StatusBar1.Panels[1].Text := 'Inclusão: ' + qrFichauser_inclusao.AsString + ' - ' + qrFichadata_inclusao.AsString; if StringEmBranco(qrFichauser_alteracao.AsString) then StatusBar1.Panels[2].Text := '' else StatusBar1.Panels[2].Text := 'Alteração: ' + qrFichauser_alteracao.AsString + ' - ' + qrFichadata_alteracao.AsString; ; end; end.
unit TestStepParam; interface uses TestBaseClasses, TestFramework, StepParam, StepParamIntf; type TestTStepParam = class(TParseContext) strict private FStepParam: IStepParam; public procedure SetUp; override; procedure TearDown; override; published procedure ShouldHaveAName; procedure ShouldHaveAValue; end; implementation procedure TestTStepParam.SetUp; begin FStepParam := TStepParam.Create; end; procedure TestTStepParam.ShouldHaveAName; begin FStepParam.Name := 'Hello'; Specify.That(FStepParam.Name).Should.Not_.Be.Empty; Specify.That(FStepParam.Name).Should.Equal('Hello'); end; procedure TestTStepParam.ShouldHaveAValue; begin FStepParam.Value := 'World!'; Specify.That(FStepParam.Value).Should.Not_.Be.Empty; Specify.That(FStepParam.Value).Should.Equal('World!'); end; procedure TestTStepParam.TearDown; begin FStepParam := nil; end; initialization // Register any test cases with the test runner RegisterTest(TestTStepParam.Suite); end.
unit SWIFT_UMsgFormat; interface uses SysUtils, Generics.Collections, Generics.Defaults, XMLIntf, XMLDoc, synautil, Classes, Controls, StdCtrls; type ESwiftException = class(Exception); ESwiftValidatorException = class(ESwiftException); TSwiftMessage = class; // базовый класс по проверке объекта (поля или сообщения) TSwiftValidator = class abstract protected procedure Error(const aText: string); virtual; abstract; public constructor Create(aSubject: TObject); virtual; function Valid(): Boolean; virtual; abstract; end; TSwiftValidatorClass = class of TSwiftValidator; TSwiftValidatorClassArray = TArray<TSwiftValidatorClass>; TSwiftValidateElement = class protected function Validate(aValidators: TSwiftValidatorClassArray): Boolean; virtual; end; TSwiftBlock = class abstract(TSwiftValidateElement) protected FColumn: Integer; FLine: Integer; FMessage: TSwiftMessage; FNumber: Integer; FText: string; procedure Error(aLine: Integer; const aText: string); overload; procedure Error(aLine: Integer; const aFormat: string; const aArgs: array of const); overload; public constructor Create(aMessage: TSwiftMessage); virtual; function Valid(): Boolean; virtual; abstract; property Column: Integer read FColumn write FColumn; property Line: Integer read FLine write FLine; property Number: Integer read FNumber; property Text: string read FText write FText; public end; // базовый класс для блоков 1 и 2 TSwiftValueBlock = class abstract(TSwiftBlock); TSwiftBlock1 = class(TSwiftValueBlock) private // FText: string; function GetSender(): string; public constructor Create(aMessage: TSwiftMessage; const aText: string); reintroduce; virtual; function Valid(): Boolean; override; property Sender: string read GetSender; end; TSwiftBlock2 = class(TSwiftValueBlock) private // FText: string; function GetReciever(): string; public constructor Create(aMessage: TSwiftMessage; const aText: string); reintroduce; virtual; function Valid(): Boolean; override; property Reciever: string read GetReciever; end; TSwiftTag = class protected type TSwiftTagList = class(TObjectList<TSwiftTag>); private FColumn: Integer; FLine: Integer; FName: string; FSequence: Boolean; FValue: string; FQualifier: string; FTags: TSwiftTagList; FParentSequence: TSwiftTag; FEditor: TCustomEdit; FFullName: string; // полное имя procedure SetEditor(aValue : TCustomEdit); function GetEditor: TCustomEdit; public constructor Create(const aData: string); destructor Destroy(); override; function GetTagBy(const aName: string; aOption: Boolean = False): TSwiftTag;//??? property Column: Integer read FColumn write FColumn; property Line: Integer read FLine write FLine; property Name: string read FName write FName; property Sequence: Boolean read FSequence write FSequence; property Value: string read FValue write FValue; property Tags: TSwiftTagList read FTags; property Qualifier: string read FQualifier write FQualifier; property ParentSequence: TSwiftTag read FParentSequence write FParentSequence; property FullName: string read FFullName write FFullName; {Добавление редактора для тэга} property Editor : TCustomEdit read GetEditor write SetEditor; end; TSwiftField = class(TSwiftValidateElement) protected FMessage: TSwiftMessage; FTag: TSwiftTag; protected procedure Error(aLine: Integer; const aText: string); overload; procedure Error(aLine: Integer; const aFormat: string; const aArgs: array of const); overload; public constructor Create(aMessage: TSwiftMessage; aTag: TSwiftTag); virtual; function Valid(): Boolean; virtual; property Message: TSwiftMessage read FMessage; property Tag: TSwiftTag read FTag; end; // базовый класс для блоков 3, 4 и 5 TSwiftTagListBlock = class abstract(TSwiftBlock) protected type TSwiftTagList = class(TObjectList<TSwiftTag>); TSwiftFieldList = class(TObjectList<TSwiftField>); var FTags: TSwiftTagList; FSequence: TSwiftTag; // текущая function FieldBy(aTag: TSwiftTag): TSwiftField; function GetCount(): Integer; function GetTag(Index: Integer): TSwiftTag; function GetFieldList(): TSwiftFieldList; public constructor Create(aMessage: TSwiftMessage); override; destructor Destroy(); override; function AddTag(aTag: TSwiftTag; aSequence: TSwiftTag = nil): TSwiftTag; function GetTagBy(const aName: string; aOption: Boolean = False): TSwiftTag; function GetFieldBy(const aName: string): TSwiftField; function GetSequence(const aName: string): TSwiftTag; function ExistTag(const aName: string): Boolean; function ExistOptionTag(const aName: string): Boolean; function Valid(): Boolean; override; property Count: Integer read GetCount; property Tags[Index: Integer]: TSwiftTag read GetTag; default; end; TSwiftBlock3 = class(TSwiftTagListBlock) public constructor Create(aMessage: TSwiftMessage); override; end; TSwiftBlock4 = class(TSwiftTagListBlock) protected type TSwiftDict = TDictionary<string,TSwiftTag>; var FSwiftDict: TSwiftDict; procedure FillSwiftDict; public constructor Create(aMessage: TSwiftMessage); override; destructor Destroy(); override; function Valid(): Boolean; override; function GetFieldValueBy(const aName: string): string; function GetFieldByEx(const aFullName: string): TSwiftField; function ExistTagBy(const aName: string): Boolean; function ExistOptionTagBy(const aName: string): Boolean; function SwiftDictToString: string; procedure RecreateTags; end; TSwiftBlock5 = class(TSwiftTagListBlock) public constructor Create(aMessage: TSwiftMessage); override; end; // структура описывающая ошибку в swift сообщении TSwiftError = record Level: Integer; {при разбиении текста (0), при валидации блоков (1), ...} Line, Column: Integer; Text: string; Number: Integer; constructor Create(const aText: string; aLevel, aLine, aColumn: Integer; aNumber: Integer); function ToString(): string; end; TSwiftErorrComparer = class(TComparer<TSwiftError>) public function Compare(const Left, Right: TSwiftError): Integer; override; end; TSwiftErrorList = class(TList<TSwiftError>) public function ToString(): string; override; end; {$REGION 'Классы валидации полей SWIFT сообщения, нижний уровень'} // базовый класс по проверке полей сообщения определенному правилу TSwiftFieldValidator = class abstract(TSwiftValidator) private function ValidateNumber(ANumPos: Integer; out AError: string): Boolean; protected FField: TSwiftField; procedure Error(const aText: string); override; public constructor Create(aSubject: TObject); override; end; // имя поля не может быть пустым и соответствует формату \d{2}[A-Z]? TSwiftFieldNameValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; // поле не должно быть пустым, а длина строки поля не превышать 35 символов // поля 15A, 15B, 15C, ... должны буть всегда пустыми // для поля 79 разрешено в строке содержать до 50 символов, а не 35 TSwiftFieldValueValidator = class(TSwiftFieldValidator) private procedure Error2(aLine: Integer; const aText: string); public function Valid(): Boolean; override; end; // проверка поля на соответствие шаблону из базы, формат regex // поля 15A, 15B, 15C, ... игнорируются TSwiftPatternValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; TSwiftCheckingForSlashesValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; // поле должно содержать одно из следующих кодов "Y,N" TSwift17TValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; TSwift17UValidator = class(TSwift17TValidator); // для SWIFT сообщения мт300, поле должно содержать одно из следующих кодов: // "NEWT,EXOP,DUPL,CANC,AMND" // для SWIFT сообщения мт320, поле должно содержать одно из следующих кодов: // "NEWT,DUPL,CANC,AMND" TSwift22AValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; // коды должны располагаться в алфавитном порядке TSwift22CValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; // дата в поле должна соответствовать формату YYYYMMDD TSwift30TValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; TSwift30VValidator = class(TSwift30TValidator); // дата в поле должна соответствовать формату YYMMDD TSwift30Validator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; // неверный разделитель дробной части "." (проверка по шаблону) TSwift36Validator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; TSwift32BValidator = class(TSwift36Validator); TSwift33BValidator = class(TSwift36Validator); // значение поля не соответствует значению SWIFT-кода банка TSwift82AValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; // неверный SWIFT-код (не найден в справочнике субъектов(финансовых оргнаизаций)) // было исключение в мт210 TSwift56AValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; TSwift57AValidator = class(TSwift56AValidator); TSwift87AValidator = class(TSwift56AValidator); TSwift58AValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; // поле должно содержать одно из следующих кодов "AGNT,BILA,BROK" TSwift94AValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; // поле TSwift35BValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; TSwift90AValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; TSwift90BValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; TSwift19AValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; TSwift92AValidator = class(TSwiftFieldValidator) public function Valid(): Boolean; override; end; {$ENDREGION} {$REGION 'Классы валидации SWIFT сообщения, верхний уровень'} // базовый класс по проверке сообщения определенному правилу TSwiftMessageValidator = class abstract(TSwiftValidator) protected FMessage: TSwiftMessage; procedure Error(const aText: string); override; public constructor Create(aSubject: TObject); override; end; // проверка на наличие обязательных полей в тексте сообщения TSwiftMandatoryFieldsValidator = class(TSwiftMessageValidator) public function Valid(): Boolean; override; end; // проверка на наличие в тексте сообщения 79 поля или копии обязательных // используется в сообщениях MT(392, 395, 396) TSwift79OrCopyValidator = class(TSwiftMessageValidator) public function Valid(): Boolean; override; end; // правило сети С1 - отсутствует обязательное поле :21: TSwift22AAnd21Validator = class(TSwiftMessageValidator) public function Valid(): Boolean; override; end; TSwift22CAnd82AValidator = class(TSwiftMessageValidator) public function Valid(): Boolean; override; end; TSwift22CAnd87AValidator = class(TSwiftMessageValidator) public function Valid(): Boolean; override; end; TSwiftSQLQueryValidator = class(TSwiftMessageValidator) private function CheckElement(const aRule, aValue: string): Boolean; function TryGetSwiftTag(const aSequence, aTag: string; aOption: Boolean; out aSwiftTag: TSwiftTag): Boolean; public class function LoadXMLTemplate(aMsgTypeID: Integer): IXMLDocument; function Valid(): Boolean; override; end; // правило сети С1 - отсутствует обязательное поле :21: (от 22A и 22B) TSwift22ABAnd21Validator = class(TSwiftMessageValidator) public function Valid(): Boolean; override; end; // проверка структуры для МТ5nn TSwiftStructureValidate = class(TSwiftMessageValidator) public function Valid(): Boolean; override; end; // проверка обязательного поля 22F если получатель EUROCLEAR TSwit22FValidator = class(TSwiftMessageValidator) public function Valid(): Boolean; override; end; {$ENDREGION} TSwiftFieldProc = reference to procedure (aField: TSwiftField); TSwiftFieldsProc = class(TDictionary<string, TSwiftFieldProc>); TSwiftMessage = class(TSwiftValidateElement) protected type TSwiftBlockList = class(TObjectList<TSwiftBlock>); var FBlocks: TSwiftBlockList; FBlock1: TSwiftBlock1; FBlock2: TSwiftBlock2; FBlock4: TSwiftBlock4; FErrors: TSwiftErrorList; FFieldsProc: TSwiftFieldsProc; FMsgType: Integer; function GetBlock(Index: Integer): TSwiftBlock; function GetCount(): Integer; function GetMsgText: string; public constructor Create(aMsgType: Integer); virtual; destructor Destroy(); override; function AddBlock(aBlock: TSwiftBlock): TSwiftBlock; function Valid(): Boolean; virtual; property Block1: TSwiftBlock1 read FBlock1; property Block2: TSwiftBlock2 read FBlock2; property Block4: TSwiftBlock4 read FBlock4; property Blocks[Index: Integer]: TSwiftBlock read GetBlock; property Count: Integer read GetCount; property Errors: TSwiftErrorList read FErrors; property FieldsProc: TSwiftFieldsProc read FFieldsProc; property MsgType: Integer read FMsgType; property MsgText: string read GetMsgText; end; TSwiftMatchTag = record Left, Right: string; Explicit, Option: Boolean; end; TSwiftMatchTagArray = TArray<TSwiftMatchTag>; TSwiftFieldsRec = record FullName: string; Mandatory: Integer; Content, Pattern: string; end; TSwift = class private class function GetInstance(aMsgType: Integer = -1): TSwiftMessage; public class function MsgFormatValid(aMsgType: Integer; const aData: string; out aErrors: string; aFieldsProc: TSwiftFieldsProc = nil): Boolean; class function Load(aMsgType: Integer; const aData: string): TSwiftMessage; end; TSwiftMatchingFunc = function(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean of object; TSwiftMatchingProtocolFunc = function(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string): Boolean of object; TSwiftArchive = class private class function MatchBlockFour300(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; overload; class function MatchBlockFour320(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; overload; class function MatchBlockFour600(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; overload; class function MatchBlockFour202(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; overload; class function MatchBlockFour5n(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; overload; class function MatchBlockFour5nNotStrict(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; overload; class function MatchBlockFour5Types(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string; aLogging: Boolean = False; aStrict: Boolean = True): Boolean; class function MatchBlockFour300Protocol(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string): Boolean; overload; class function MatchBlockFour320Protocol(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string): Boolean; overload; class function MatchBlockFour600Protocol(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string): Boolean; overload; class function MatchBlockFour202Protocol(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string): Boolean; overload; class function MatchBlockFour5nProtocol(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string): Boolean; overload; class function MatchBlockFour(aMsgType: Integer; const aLeft, aRight: string; aMatchTags: array of TSwiftMatchTag; aMatching: TSwiftMatchingFunc = nil): Boolean; class function MatchBlockFourProtocol(aMsgType: Integer; const aLeft, aRight: string; aMatchTags: array of TSwiftMatchTag; aMatching: TSwiftMatchingProtocolFunc; var aProtocol: string): Boolean; public // для SWIFT сообщений MT300 и MT320 (в дальнейшем список может быть расширен) class function MsgMatching(aMsgType: Integer; const aLeft, aRight: string; aStrict: Boolean = True): Boolean; overload; class function MsgMatchingProtocol(aMsgType: Integer; const aLeft, aRight: string; var aProtocol: string): Boolean; end; TXMLDocumentHelper = class public class function SelectNodes(aNode: IXMLNode; const aPath: string): IXMLNodeList; static; class function SelectSingleNode(aNode: IXMLNode; const aPath: string): IXMLNode; static; class procedure ForEach(aNodes: IXMLNodeList; aProc: TProc<IXMLNode>); static; end; function CheckSWIFTMsgFormat(const aMsgText: string; aMsgType: Integer = 0): string; stdcall; const cSwiftFieldsFour518: array [0..39] of TSwiftFieldsRec = ( // последовательность A (FullName: 'GENL.16R'; Mandatory: 1; Content: 'GENL'; Pattern: '^GENL$'), (FullName: 'GENL.20C.SEME'; Mandatory: 1; Content: ':4!c//16x'; Pattern: '^(:SEME//)[\w\-:\(\)\.,\+\?\/ ]{1,16}$'), (FullName: 'GENL.23G'; Mandatory: 1; Content: '4!c[/4!c]'; Pattern: '^(CANC|NEWM)(/(CODU|COPY|DUPL))?$'), (FullName: 'GENL.22F.TRTR'; Mandatory: 1; Content: ':4!c/[8c]/4!c'; Pattern: '^(:TRTR/)([A-Z0-9]{1,8})?(/(BASK|INDX|LIST|PROG|TRAD))$'), (FullName: 'GENL.16S'; Mandatory: 1; Content: 'GENL'; Pattern: '^GENL$'), // последовательность B (FullName: 'CONFDET.16R'; Mandatory: 1; Content: 'CONFDET'; Pattern: '^CONFDET$'), (FullName: 'CONFDET.98A.SETT'; Mandatory: 1; Content: ':4!c//8!n'; Pattern: '^(:SETT//)\d{8}$'), (FullName: 'CONFDET.98A.TRAD'; Mandatory: 1; Content: ':4!c//8!n'; Pattern: '^(:TRAD//)\d{8}$'), (FullName: 'CONFDET.90A.DEAL'; Mandatory: 1; Content: ':4!c//4!c/15d'; Pattern: '^(:DEAL//)([A-Z0-9]{4})(/[(\d+)?,(\d+)?]*)$'), (FullName: 'CONFDET.99A.DAAC'; Mandatory: 0; Content: ':4!c//[N]3!n'; Pattern: '^(:DAAC//)N?\d{3}$'), (FullName: 'CONFDET.22H.BUSE'; Mandatory: 1; Content: ':4!c//4!c'; Pattern: '^(:BUSE//)(BUYI|CROF|CROT|DIVR|IPOO|REDM|SELL|SUBS|SWIF|SWIT)$'), (FullName: 'CONFDET.22H.PAYM'; Mandatory: 1; Content: ':4!c//4!c'; Pattern: '^(:PAYM//)(APMT|FREE)$'), // последовательность B1 (FullName: 'CONFDET.CONFPRTY.16R'; Mandatory: 1; Content: 'CONFPRTY'; Pattern: '^CONFPRTY$'), (FullName: 'CONFDET.CONFPRTY.95P'; Mandatory: 2; Content: ':4!c//4!a2!a2!c[3!c]'; Pattern: '^(:(BUYR|SELL)//)(([A-Z]{6})([A-Z0-9]{2})([A-Z0-9]{3})?)$'), (FullName: 'CONFDET.CONFPRTY.97A.CASH'; Mandatory: 0; Content: ':4!c//35x'; Pattern: '^(:CASH//)([\w\-:\(\)\.,\+\?\/ ]{1,35})$'), (FullName: 'CONFDET.CONFPRTY.22F.TRCA'; Mandatory: 0; Content: ':4!c/[8c]/4!c'; Pattern: '^(:TRCA/)([A-Z0-9]{1,8})?(/(AGEN|BAGN|CAGN|CPRN|INFI|MKTM|MLTF|OAGNPRAG|PRIN|RMKT|SINT|TAGT))$'), (FullName: 'CONFDET.CONFPRTY.16S'; Mandatory: 1; Content: 'CONFPRTY'; Pattern: '^CONFPRTY$'), (FullName: 'CONFDET.36B.CONF'; Mandatory: 1; Content: ':4!c//4!c/15d'; Pattern: '^(:CONF//)([A-Z0-9]{4})(/[(\d+)?,(\d+)?]*)$'), // последовательность B2 (FullName: 'CONFDET.FIA.16R'; Mandatory: 0; Content: 'FIA'; Pattern: '^FIA$'), (FullName: 'CONFDET.FIA.12A'; Mandatory: 0; Content: ':4!c/[8c]/30x'; Pattern: '^(:(CLAS|OPST|OPTI)/)([A-Z0-9]{1,8})?(/[\w\-:\(\)\.,\+\?\/ ]{1,30})$'), (FullName: 'CONFDET.FIA.11A'; Mandatory: 0; Content: ':4!c//3!a'; Pattern: '^(:DENO//)([A-Z]{3})$'), (FullName: 'CONFDET.FIA.98A.MATU'; Mandatory: 0; Content: ':4!c//8!n'; Pattern: '^(:MATU//)(\d{8})$'), (FullName: 'CONFDET.FIA.92A.INTR'; Mandatory: 0; Content: ':4!c//[N]15d'; Pattern: '^(:INTR//)N?([(\d+)?,(\d+)?]*)$'), (FullName: 'CONFDET.FIA.70E.FIAN'; Mandatory: 0; Content: ':4!c//10*35x'; Pattern: '\A(:FIAN//)(([\w\-:\(\)\.,\+\?\/ ]{1,35}(\r\n)?))(^([\w\-:\(\)\.,\+\?\/ ]{1,35}(\r\n)?)){0,9}\Z'), (FullName: 'CONFDET.FIA.16S'; Mandatory: 0; Content: 'FIA'; Pattern: '^FIA$'), (FullName: 'CONFDET.70E.TPRO'; Mandatory: 0; Content: ':4!c//10*35x'; Pattern: '^(:TPRO//)([\w\-:\(\)\.,\+\?\/ ]{0,35})(\r\n)?(([\w\-:\(\)\.,\+\?\/ ]{0,35}(\r\n)?){0,9})$'), (FullName: 'CONFDET.16S'; Mandatory: 1; Content: 'CONFDET'; Pattern: '^CONFDET$'), // последовательность C (FullName: 'SETDET.16R'; Mandatory: 1; Content: 'SETDET'; Pattern: '^SETDET$'), (FullName: 'SETDET.22F.SETR'; Mandatory: 1; Content: ':4!c/[8c]/4!c'; Pattern: '^(:(SETR|RTGS)/)([A-Z0-9]{1,8})?(/[A-Z]{4})$'), // последовательность C1 (FullName: 'SETDET.SETPRTY.16R'; Mandatory: 1; Content: 'SETPRTY'; Pattern: '^SETPRTY$'), (FullName: 'SETDET.SETPRTY.95P'; Mandatory: 2; Content: ':4!c//4!a2!a2!c[3!c]'; Pattern: '^(:(SELL|DEAG|BUYR|REAG)//)(([A-Z]{6})([A-Z0-9]{2})([A-Z0-9]{3})?)$'), (FullName: 'SETDET.SETPRTY.16S'; Mandatory: 1; Content: 'SETPRTY'; Pattern: '^SETPRTY$'), // последовательность C2 (FullName: 'SETDET.CSHPRTY.16R'; Mandatory: 1; Content: 'CSHPRTY'; Pattern: '^CSHPRTY$'), (FullName: 'SETDET.CSHPRTY.95P.ACCW'; Mandatory: 1; Content: ':4!c//4!a2!a2!c[3!c]'; Pattern: '^(:ACCW//)(([A-Z]{6})([A-Z0-9]{2})([A-Z0-9]{3})?)$'), (FullName: 'SETDET.CSHPRTY.97A.CASH'; Mandatory: 0; Content: ':4!c//35x'; Pattern: '^(:CASH//)([\w\-:\(\)\.,\+\?\/ ]{1,35})$'), (FullName: 'SETDET.CSHPRTY.16S'; Mandatory: 1; Content: 'CSHPRTY'; Pattern: '^CSHPRTY$'), // последовательность C3 (FullName: 'SETDET.AMT.16R'; Mandatory: 1; Content: 'AMT'; Pattern: '^AMT$'), (FullName: 'SETDET.AMT.19A'; Mandatory: 2; Content: ':4!c//[N]3!a15d'; Pattern: '^(:(SETT|ACRU)//)(N?)([A-Z]{3})([(\d+)?,(\d+)?]*)$'), (FullName: 'SETDET.AMT.16S'; Mandatory: 1; Content: 'AMT'; Pattern: '^AMT$'), (FullName: 'SETDET.16S'; Mandatory: 1; Content: 'SETDET'; Pattern: '^SETDET$') ); cSwiftFieldsFour541: array [0..25] of TSwiftFieldsRec = ( // последовательность A (FullName: 'GENL.16R'; Mandatory: 1; Content: 'GENL'; Pattern: '^GENL$'), (FullName: 'GENL.20C.SEME'; Mandatory: 1; Content: ':4!c//16x'; Pattern: '^(:SEME//)[\w\-:\(\)\.,\+\?\/ ]{1,16}$'), (FullName: 'GENL.23G'; Mandatory: 1; Content: '4!c[/4!c]'; Pattern: '^(CANC|NEWM)(/(CODU|COPY|DUPL))?$'), (FullName: 'GENL.16S'; Mandatory: 1; Content: 'GENL'; Pattern: '^GENL$'), // последовательность B (FullName: 'TRADDET.16R'; Mandatory: 1; Content: 'TRADDET'; Pattern: '^TRADDET$'), (FullName: 'TRADDET.98A.SETT'; Mandatory: 1; Content: ':4!c//8!n'; Pattern: '^(:SETT//)\d{8}$'), (FullName: 'TRADDET.98A.TRAD'; Mandatory: 1; Content: ':4!c//8!n'; Pattern: '^(:TRAD//)\d{8}$'), (FullName: 'TRADDET.90A.DEAL'; Mandatory: 0; Content: ':4!c//4!c/15d'; Pattern: '^(:DEAL//)(DISC|PRCT|PREM|YIEL)(/[(\d+)?,(\d+)?]*)$'), (FullName: 'TRADDET.90B.DEAL'; Mandatory: 0; Content: ':4!c//4!c/3!a15d'; Pattern: '^(:DEAL//)(ACTU|DISC|PREM)(/[A-Z]{3})([(\d+)?,(\d+)?]*)$'), (FullName: 'TRADDET.16S'; Mandatory: 1; Content: 'TRADDET'; Pattern: '^TRADDET$'), // последовательность C (FullName: 'FIAC.16R'; Mandatory: 0; Content: 'FIAC'; Pattern: '^FIAC$'), (FullName: 'FIAC.36B.SETT'; Mandatory: 1; Content: ':4!c//4!c/15d'; Pattern: '^(:SETT//)(AMOR|FAMT|UNIT)(/[(\d+)?,(\d+)?]*)$'), // ^(?!(.{16,}))(\d)+(,){1}\d*$ - формат 15d (FullName: 'FIAC.97A.SAFE'; Mandatory: 1; Content: ':4!c//35x'; Pattern: '^(:SAFE//)([\w\-:\(\)\.,\+\?\/ ]{1,35})$'), (FullName: 'FIAC.97A'; Mandatory: 2; Content: ':4!c//35x'; Pattern: '^(:(SAFE|CASH)//)([\w\-:\(\)\.,\+\?\/ ]{1,35})$'), (FullName: 'FIAC.16S'; Mandatory: 0; Content: 'FIAC'; Pattern: '^FIAC$'), // последовательность E (FullName: 'SETDET.16R'; Mandatory: 1; Content: 'SETDET'; Pattern: '^SETDET$'), (FullName: 'SETDET.22F.SETR'; Mandatory: 1; Content: ':4!c/[8c]/4!c'; Pattern: '^(:(SETR)/)([A-Z0-9]{1,8})?(/[A-Z]{4})$'), (FullName: 'SETDET.22F.RTGS'; Mandatory: 0; Content: ':4!c/[8c]/4!c'; Pattern: '^(:(RTGS)/)([A-Z0-9]{1,8})?(/[A-Z]{4})$'), // последовательность E1 (FullName: 'SETDET.SETPRTY.16R'; Mandatory: 1; Content: 'SETPRTY'; Pattern: '^SETPRTY$'), (FullName: 'SETDET.SETPRTY.95P'; Mandatory: 2; Content: ':4!c//4!a2!a2!c[3!c]'; Pattern: '^(:(SELL|DEAG|BUYR|REAG|PSET)//)(([A-Z]{6})([A-Z0-9]{2})([A-Z0-9]{3})?)$'), (FullName: 'SETDET.SETPRTY.97A'; Mandatory: 0; Content: ':4!c//35x'; Pattern: '^(:(SAFE|CASH)//)([\w\-:\(\)\.,\+\?\/ ]{1,35})$'), (FullName: 'SETDET.SETPRTY.16S'; Mandatory: 1; Content: 'SETPRTY'; Pattern: '^SETPRTY$'), // последовательность E3 (FullName: 'SETDET.AMT.16R'; Mandatory: 1; Content: 'AMT'; Pattern: '^AMT$'), (FullName: 'SETDET.AMT.19A.SETT'; Mandatory: 1; Content: ':4!c//[N]3!a15d'; Pattern: '^(:SETT//)(N?)([A-Z]{3})([(\d+)?,(\d+)?]*)$'), (FullName: 'SETDET.AMT.16S'; Mandatory: 1; Content: 'AMT'; Pattern: '^AMT$'), (FullName: 'SETDET.16S'; Mandatory: 1; Content: 'SETDET'; Pattern: '^SETDET$') ); //////////////////////////////////////////////////////////////////////////////// implementation //////////////////////////////////////////////////////////////////////////////// uses StrUtils, Types, Math, RegularExpressions, DateUtils, SYS_uDBTools, API_uSwiftTrans, SWIFT_UUtils, SYS_UDllInit, xmldom{, Dialogs}, API_uAppSettings; const cInvalidSymbols = 'Недопустимые символы (%s)'; cUnbalancedBrackets = 'Несбалансированное количество скобок'; cUnknownBlock = 'Неизвестный блок {%s}'; cEmptyTagName = 'Поле с пустым именем недопустимо'; cEmptyTagValue = ':%s: Поле не может быть пустым'; cNotEmptyTagValue = ':%s: Поле должно быть пустым'; cInvalidTagName = 'Недопустимое имя поля (%s)'; cInvalidTagSymbols = ':%s: Поле содержит недопустимые символы (%s)'; cInvalidTagLenght = ':%s: Длина строки поля превышает допустимую'; cInvalidTagLinesCount = ':%s: Количество строк поля превышает допустимое'; cInvalidTagEmpty = ':%s: Строка поля является пустой'; cInvalidTagFormat = ':%s: Значение поля "%s" не соответствует формату "%s"'; cEmptyBlock = 'Пустой блок {%d...}'; cInvalidBlockLength = 'Не правильная длина данных блока {%d...}'; сInvalidBlockType = 'Невозможно отпределить тип блока {%d...}'; сNoFindMandatoryTag = 'Отсутствует обязательное поле %s'; сNoFindOptionMandatoryTag = 'Отсутствует обязательное опциональное поле %s'; cNoSlashesTagValue = ':%s: Поле не может начинаться, заканчиваться слэшем или содержать внутри двойной слэш'; cBlockNotFound = 'Не найден блок %d'; cEmptyMessage = 'Пустое сообщение'; cCommaCheckError = 'Отсутствует ","'; cLengthCheckError = 'Длина больше 15 символов'; cRegExpError = 'Ошибка "%s" в регулярном выражении "%s"'; const // теги исключения, должны содержать пустое значение cEmptyTags: array [0..8] of string = ( '15A', '15B', '15C', '15D', '15E', '15F', '15G', '15H', '15I'); cSequenceTags: array [0..9] of string = ( '15A', '15B', '15C', '15D', '15E', '15F', '15G', '15H', '15I', '16R'); // теги для сравнения 4 блока в 300-ых сообщениях cMatchTagBlockFour300: array [0..13] of TSwiftMatchTag = ((Left: '15A.22C'; Right: '15A.22C'; Explicit: True), (Left: '15A.82A'; Right: '15A.87A'; Explicit: True), (Left: '15A.87A'; Right: '15A.82A'; Explicit: True), (Left: '15B.30T'; Right: '15B.30T'; Explicit: True), (Left: '15B.30V'; Right: '15B.30V'; Explicit: True), (Left: '15B.36'; Right: '15B.36'; Explicit: True), (Left: '15B.32B'; Right: '15B.33B'; Explicit: True), (Left: '15B.32B.53'; Right: '15B.33B.53'; Explicit: True; Option: True), (Left: '15B.32B.56'; Right: '15B.33B.56'; Explicit: True; Option: True), (Left: '15B.32B.57'; Right: '15B.33B.57'; Explicit: True; Option: True), (Left: '15B.33B'; Right: '15B.32B'; Explicit: True), (Left: '15B.33B.53'; Right: '15B.32B.53'; Explicit: True; Option: True), (Left: '15B.33B.56'; Right: '15B.32B.56'; Explicit: True; Option: True), (Left: '15B.33B.57'; Right: '15B.32B.57'; Explicit: True; Option: True)); // теги для сравнения 4 блока в 320-ых сообщениях cMatchTagBlockFour320: array [0..28] of TSwiftMatchTag = ((Left: '15A.22B'; Right: '15A.22B'; Explicit: True), (Left: '15A.82A'; Right: '15A.87A'; Explicit: True), (Left: '15A.87A'; Right: '15A.82A'; Explicit: True), (Left: '15B.17R'; Right: '15B.17R'; Explicit: True), (Left: '15B.30T'; Right: '15B.30T'; Explicit: True), (Left: '15B.30V'; Right: '15B.30V'; Explicit: True), (Left: '15B.30P'; Right: '15B.30P'; Explicit: True), (Left: '15B.32B'; Right: '15B.32B'; Explicit: True), (Left: '15B.32H'; Right: '15B.32H'; Explicit: True){*}, (Left: '15B.30X'; Right: '15B.30X'; Explicit: True), (Left: '15B.34E'; Right: '15B.34E'; Explicit: True), (Left: '15B.37G'; Right: '15B.37G'; Explicit: True), (Left: '15B.14D'; Right: '15B.14D'; Explicit: True), (Left: '15C.53'; Right: '15D.53'; Explicit: True; Option: True), (Left: '15C.56'; Right: '15D.56'; Explicit: True; Option: True), (Left: '15C.57'; Right: '15D.57'; Explicit: True; Option: True), (Left: '15C.58'; Right: '15D.58'; Explicit: True; Option: True), (Left: '15D.53'; Right: '15C.53'; Explicit: True; Option: True), (Left: '15D.56'; Right: '15C.56'; Explicit: True; Option: True), (Left: '15D.57'; Right: '15C.57'; Explicit: True; Option: True), (Left: '15D.58'; Right: '15C.58'; Explicit: True; Option: True), (Left: '15E.53'; Right: '15F.53'; Explicit: True; Option: True), (Left: '15E.56'; Right: '15F.56'; Explicit: True; Option: True), (Left: '15E.57'; Right: '15F.57'; Explicit: True; Option: True), (Left: '15E.58'; Right: '15F.58'; Explicit: True; Option: True), (Left: '15F.53'; Right: '15E.53'; Explicit: True; Option: True), (Left: '15F.56'; Right: '15E.56'; Explicit: True; Option: True), (Left: '15F.57'; Right: '15E.57'; Explicit: True; Option: True), (Left: '15F.58'; Right: '15E.58'; Explicit: True; Option: True)); // теги для сравнения 4 блока в 600-ых сообщениях cMatchTagBlockFour600: array [0..13] of TSwiftMatchTag = ((Left: '15A.22'; Right: '15A.22'; Explicit: True), (Left: '15A.82'; Right: '15A.87'; Explicit: True; Option: True), (Left: '15A.87'; Right: '15A.82'; Explicit: True; Option: True), (Left: '15A.30'; Right: '15A.30'; Explicit: True), (Left: '15A.26C'; Right: '15A.26C'; Explicit: True), (Left: '15A.33G'; Right: '15A.33G'; Explicit: True), (Left: '15B.32B'; Right: '15C.32F'; Explicit: True), (Left: '15B.87'; Right: '15C.87'; Explicit: True; Option: True), (Left: '15B.34R'; Right: '15C.34R'; Explicit: True), (Left: '15B.57'; Right: '15C.57'; Explicit: True; Option: True), (Left: '15C.32F'; Right: '15B.32B'; Explicit: True), (Left: '15C.87'; Right: '15B.87'; Explicit: True; Option: True), (Left: '15C.34R'; Right: '15B.34R'; Explicit: True), (Left: '15C.57'; Right: '15B.57'; Explicit: True; Option: True)); // теги для сравнения 4 блока в 202-ых сообщениях cMatchTagBlockFour202: array [0..3] of TSwiftMatchTag = ((Left: '32A'; Right: '32A'), (Left: '56'; Right: '56'; Option: True), (Left: '57'; Right: '57'; Option: True), (Left: '58'; Right: '58'; Option: True)); // теги для сравнения 4 блока в 518-ых сообщениях // формат строки - регулярное выражение вида // ^TAG\.SEQ\.SUBSEQ\.QUAL$ // TAG - наименование поля (тэга) // SEQ - наименование последовательности (тэг 16R) // SUBSEQ - наименование подпоследовательности внутри незакрытой (тэг 16S) последовательности // QUAL - наименование квалификатора (значение поля вида :4!c) cMatchTagBlockFour518: array [0..19] of TSwiftMatchTag = ( (Left: '^(23G.GENL)$'; Right: '^(23G.GENL)$'; Explicit: True), (Left: '^(22F.GENL(.TRTR)?)$'; Right: '^(22F.GENL(.TRTR)?)$'; Explicit: True), (Left: '^(98A.CONFDET.TRAD)$'; Right: '^(98A.CONFDET.TRAD)$'; Explicit: True), (Left: '^(98A.CONFDET.SETT)$'; Right: '^(98A.CONFDET.SETT)$'; Explicit: True), (Left: '^(90A.CONFDET.DEAL)$'; Right: '^(90A.CONFDET.DEAL)$'; Explicit: True), (Left: '^(99A.CONFDET.(DAAC|GIUP))$'; Right: '^(99A.CONFDET.(DAAC|GIUP))$'; Explicit: True), (Left: '^(22H.CONFDET.PAYM)$'; Right: '^(22H.CONFDET.PAYM)$'; Explicit: True), (Left: '^(95P.CONFDET.CONFPRTY.BUYR)$'; Right: '^(95P.CONFDET.CONFPRTY.BUYR)$'; Explicit: True), (Left: '^(95P.CONFDET.CONFPRTY.SELL)$'; Right: '^(95P.CONFDET.CONFPRTY.SELL)$'; Explicit: True), (Left: '^(36B.CONFDET.CONF)$'; Right: '^(36B.CONFDET.CONF)$'; Explicit: True), (Left: '^(35B.CONFDET)$'; Right: '^(35B.CONFDET)$'; Explicit: True), (Left: '^(11A.CONFDET.FIA.DENO)$'; Right: '^(11A.CONFDET.FIA.DENO)$'; Explicit: True), (Left: '^(98A.CONFDET.FIA.([A-Z]){4})$'; Right: '^(98A.CONFDET.FIA.([A-Z]){4})$'; Explicit: True), (Left: '^(92A.CONFDET.FIA.([A-Z]){4})$'; Right: '^(92A.CONFDET.FIA.([A-Z]){4})$'; Explicit: True), (Left: '^(22F.SETDET.SETR)$'; Right: '^(22F.SETDET.SETR)$'; Explicit: True), (Left: '^(95P.SETDET.SETPRTY.SELL)$'; Right: '^(95P.SETDET.SETPRTY.SELL)$'; Explicit: True), (Left: '^(95P.SETDET.SETPRTY.BUYR)$'; Right: '^(95P.SETDET.SETPRTY.BUYR)$'; Explicit: True), (Left: '^(95P.SETDET.CSHPRTY.ACCW)$'; Right: '^(95P.SETDET.CSHPRTY.ACCW)$'; Explicit: True), (Left: '^(19A.SETDET.AMT.SETT)$'; Right: '^(19A.SETDET.AMT.SETT)$'; Explicit: True), (Left: '^(19A.SETDET.AMT.ACRU)$'; Right: '^(19A.SETDET.AMT.ACRU)$'; Explicit: True) ); cMatchTagBlockFour541: array [0..7] of TSwiftMatchTag = ( (Left: '^(23G.GENL)$'; Right: '^(23G.GENL)$'; Explicit: True), (Left: '^(98A.TRADDET.(SETT|ESET))$'; Right: '^(98A.TRADDET.(SETT|ESET))$'; Explicit: True; Option: True), (Left: '^(35B.TRADDET)$'; Right: '^(35B.TRADDET)$'; Explicit: True), (Left: '^(36B.FIAC.(SETT|ESTT))$'; Right: '^(36B.FIAC.(SETT|ESTT))$'; Explicit: True; Option: True), (Left: '^(97A.FIAC.SAFE)$'; Right: '^(97A.FIAC.SAFE)$'; Explicit: True), (Left: '^(97A.FIAC.CASH)$'; Right: '^(97A.FIAC.CASH)$'; Explicit: True), (Left: '^(22F.SETDET.SETR)$'; Right: '^(22F.SETDET.SETR)$'; Explicit: True), (Left: '^(19A.SETDET.AMT.(SETT|ESTT))$'; Right: '^(19A.SETDET.AMT.(SETT|ESTT))$'; Explicit: True; Option: True) ); // теги для сравнения 4 блока в 300-ых сообщениях (не строгий) cMatchTagBlockFour300NotStrict: array [0..3] of TSwiftMatchTag = ((Left: '15A.22C'; Right: '15A.22C'; Explicit: True), (Left: '15B.30V'; Right: '15B.30V'; Explicit: True), (Left: '15B.32B'; Right: '15B.33B'; Explicit: True), (Left: '15B.33B'; Right: '15B.32B'; Explicit: True)); // теги для сравнения 4 блока в 320-ых сообщениях (не строгий) cMatchTagBlockFour320NotStrict: array [0..3] of TSwiftMatchTag = ((Left: '15A.22C'; Right: '15A.22C'; Explicit: True), (Left: '15B.30V'; Right: '15B.30V'; Explicit: True), (Left: '15B.30P'; Right: '15B.30P'; Explicit: True), (Left: '15B.32B'; Right: '15B.32B'; Explicit: True)); // теги для сравнения 4 блока в 600-ых сообщениях (не строгий) cMatchTagBlockFour600NotStrict: array [0..10] of TSwiftMatchTag = ((Left: '15A.22'; Right: '15A.22'; Explicit: True), (Left: '15A.82'; Right: '15A.87'; Explicit: True; Option: True), (Left: '15A.87'; Right: '15A.82'; Explicit: True; Option: True), (Left: '15A.30'; Right: '15A.30'; Explicit: True), (Left: '15A.33G'; Right: '15A.33G'; Explicit: True), (Left: '15B.32B'; Right: '15C.32F'; Explicit: True), (Left: '15B.34R'; Right: '15C.34R'; Explicit: True), (Left: '15B.57'; Right: '15C.57'; Explicit: True; Option: True), (Left: '15C.32F'; Right: '15B.32B'; Explicit: True), (Left: '15C.34R'; Right: '15B.34R'; Explicit: True), (Left: '15C.57'; Right: '15B.57'; Explicit: True; Option: True)); // теги для сравнения 4 блока в 202-ых сообщениях (не строгий) cMatchTagBlockFour202NotStrict: array [0..0] of TSwiftMatchTag = ((Left: '32A'; Right: '32A')); // теги для сравнения 4 блока в 518-ых сообщениях cMatchTagBlockFour518NotStrict: array [0..8] of TSwiftMatchTag = ( (Left: '^(23G.GENL)$'; Right: '^(23G.GENL)$'; Explicit: True), (Left: '^(98A.CONFDET.SETT)$'; Right: '^(98A.CONFDET.SETT)$'; Explicit: True), (Left: '^(90A.CONFDET.DEAL)$'; Right: '^(90A.CONFDET.DEAL)$'; Explicit: True), (Left: '^(36B.CONFDET.CONF)$'; Right: '^(36B.CONFDET.CONF)$'; Explicit: True), (Left: '^(11A.CONFDET.FIA.DENO)$'; Right: '^(11A.CONFDET.FIA.DENO)$'; Explicit: True), (Left: '^(98A.CONFDET.FIA.([A-Z]){4})$'; Right: '^(98A.CONFDET.FIA.([A-Z]){4})$'; Explicit: True), (Left: '^(92A.CONFDET.FIA.([A-Z]){4})$'; Right: '^(92A.CONFDET.FIA.([A-Z]){4})$'; Explicit: True), (Left: '^(19A.SETDET.AMT.SETT)$'; Right: '^(19A.SETDET.AMT.SETT)$'; Explicit: True), (Left: '^(19A.SETDET.AMT.ACRU)$'; Right: '^(19A.SETDET.AMT.ACRU)$'; Explicit: True) ); cMatchTagBlockFour541NotStrict: array [0..3] of TSwiftMatchTag = ( (Left: '^(23G.GENL)$'; Right: '^(23G.GENL)$'; Explicit: True), (Left: '^(98A.TRADDET.(SETT|ESET))$'; Right: '^(98A.TRADDET.(SETT|ESET))$'; Explicit: True; Option: True), (Left: '^(36B.FIAC.(SETT|ESTT))$'; Right: '^(36B.FIAC.(SETT|ESTT))$'; Explicit: True; Option: True), (Left: '^(19A.SETDET.AMT.(SETT|ESTT))$'; Right: '^(19A.SETDET.AMT.(SETT|ESTT))$'; Explicit: True; Option: True) ); type TSwiftValidatorRegistry = class(TDictionary<string, TSwiftValidatorClassArray>) public function Add(const aKey: string; aValue: TSwiftValidatorClassArray): TSwiftValidatorRegistry; end; var gFieldValidator: TSwiftValidatorRegistry = nil; gFieldDefaultValidator: TSwiftValidatorClassArray = nil; gMessageValidator: TSwiftValidatorRegistry = nil; gMessageDefaultValidator: TSwiftValidatorClassArray = nil; type TSwiftMsgFormat = record public Content: string; Description: string; Mandatory: Boolean; Notes: string; Pattern: string; constructor Create(const aContent, aPattern, aNotes, aDescription: string; aMandatory: Boolean); class function Empty(): TSwiftMsgFormat; static; function IsEmpty(): Boolean; end; TSwiftMandatoryField = record strict private function GetNameWithoutColon(): string; public Name: string; Mandatory: Integer; constructor Create(aName: string; aMandatory: Integer); property NameWithoutColon: string read GetNameWithoutColon; end; TSwiftMandatoryFieldArray = array of TSwiftMandatoryField; //??? TSwiftMsgArchive = record ID: Integer; Direction: Integer;//0..1; Reference {22 поле}, Sender, Reciever: string; Text: string; constructor Create(aID: Integer; aDirection: Integer; aReference, aSender, aReciever: string; const aText: string); end; TSwiftMsgArchiveArray = TArray<TSwiftMsgArchive>; TSwiftDatabase = class public class function GetMsgFormat(aMsgType: Integer; const aFieldName: string): TSwiftMsgFormat; overload; class function GetMsgFormat(aMsgType: Integer; const aField: TSwiftField): TSwiftMsgFormat; overload; class function GetMandatoryFields(aMsgType: Integer): TSwiftMandatoryFieldArray; class function GetFieldsFormatFromArray(aFieldsArray: array of TSwiftFieldsRec; const aFieldName: string): TSwiftMsgFormat; public // возможно, нужно исключить из расмотрения записи, которые уже зависимы //??? class function GetMsgArchive(aID: Integer): TSwiftMsgArchive; class function GetMsgArchiveMatching(aMsgType: Integer; aMsgArchive: TSwiftMsgArchive): TSwiftMsgArchiveArray; end; TSwiftParser = class private FCurrentLine: Integer; FErrors: TSwiftErrorList; FMessage: string; FMessageObj: TSwiftMessage; function CreateTag(const aText: string; aLine: Integer): TSwiftTag; function SubString(const aData: string; aBegin, aEnd: Integer): string; procedure Correct(const aData: string; var aLine: Integer; aIndex: Integer; aOffset: Integer = 1); procedure InvalidSymbols(aLine: Integer; const aSymbols: string); procedure UnknownBlock(aLine: Integer; const aData: string); procedure UnbalancedBrackets(aLine: Integer); function FindBlockStart(const aText: string; aOffset: Integer): Integer; function ReadUntilBlockEnd(const aText: string; aOffset: Integer): string; function IsBlockStart(aChar: Char): Boolean; function IsTextBlock(const aData: string): Boolean; function IsBlockEnd(aIsTextBlock: Boolean; const aData: string; aIndex: Integer): Boolean; overload; function IsBlockEnd(aChar: Char): Boolean; overload; function IdentifyBlock(const aText: string): Integer; // на входе текст блока, без фигурных скобок function TagListBlockConsume(aBlock: TSwiftTagListBlock; const aTextBlock: string; aLine: Integer): TSwiftBlock; function Block4Consume(aBlock: TSwiftTagListBlock; const aTextBlock: string; aLine: Integer): TSwiftBlock; public constructor Create(); destructor Destroy(); override; procedure Build(aMessage: TSwiftMessage; const aData: string); property Errors: TSwiftErrorList read FErrors; end; {$Region 'TSwiftParser'} function TSwiftParser.Block4Consume(aBlock: TSwiftTagListBlock; const aTextBlock: string; aLine: Integer): TSwiftBlock; const sTextBlockBegin = sLineBreak + ':'; sTextBlockEnd = sLineBreak + '-'; sFieldDelimiter = sLineBreak + ':'; var Data, eData: string; Start, Finish, Index, Line: Integer; begin Line := aLine; // J7852 // Для старых сообщений необходимо заменить символ '~', который // использовался для перевода строки eData := aTextBlock; eData := ReplaceStr(eData, '~', #$D#$A); Data := AdjustLineBreaks(eData {aTextBlock}); aBlock.Text := Data; // удаление меток в начале и конце блока данных Index := Pos(sTextBlockBegin, Data); Correct(Data, aLine, Index + Length(sTextBlockBegin) - 1); if Index <> 1 then InvalidSymbols(Line, SubString(Data, 1, Index)); Delete(Data, 1, Index + Length(sTextBlockBegin) - 1); Finish := Pos(sTextBlockEnd, Data); Start := 1; Index := PosEx(sFieldDelimiter, Data, Start); while (Start <> 0) and (Index <> 0) do begin aBlock.AddTag(CreateTag(SubString(Data, Start, Index), aLine)); Correct(Data, aLine, Index + Length(sFieldDelimiter) - 1, Start); Start := Index + Length(sFieldDelimiter); Index := PosEx(sFieldDelimiter, Data, Start); end; if (Start <> 0) and (Index = 0) then aBlock.AddTag( CreateTag(SubString(Data, Start, IfThen(Finish = 0, Length(Data), Finish)), aLine)); if (Finish <> 0) and ((Finish + Length(sTextBlockEnd)) < (Length(Data) + 1)) then begin Correct(Data, aLine, Finish + Length(sTextBlockEnd) - 1, Start); InvalidSymbols(aLine, SubString(Data, Finish + Length(sTextBlockEnd), Length(Data) + 1)); end; Result := aBlock; end; procedure TSwiftParser.Correct(const aData: string; var aLine: Integer; aIndex, aOffset: Integer); var Point: Integer; begin Point := aOffset; while (Point <= aIndex) do begin if (aData[Point] = #10) and (((Point - 1) > 0) and (aData[Point - 1] = #13)) then Inc(aLine); Inc(Point); end; end; constructor TSwiftParser.Create(); begin FCurrentLine := 1; FErrors := TSwiftErrorList.Create(); FMessage := ''; end; function TSwiftParser.CreateTag(const aText: string; aLine: Integer): TSwiftTag; begin Result := TSwiftTag.Create(aText); Result.Line := aLine; // 32B и 33B являются подсекциями 15B в 300 swift-сообщении if Assigned(FMessageObj) and (FMessageObj.MsgType = 300) and MatchText(Result.Name, ['32B', '33B']) then Result.Sequence := True else if MatchText(Result.Name, cSequenceTags) then Result.Sequence := True; end; destructor TSwiftParser.Destroy; begin FErrors.Free(); inherited; end; function TSwiftParser.FindBlockStart(const aText: string; aOffset: Integer): Integer; begin Result := aOffset; while (Result <= Length(aText)) and not IsBlockStart(aText[Result]) do begin Inc(Result); Correct(aText, FCurrentLine, Result, Result); // определение текущей строки end; Result := IfThen(Result <= Length(aText), Result, -1); end; function TSwiftParser.IdentifyBlock(const aText: string): Integer; begin Result := StrToIntDef(Copy(aText, 1, Pos(':', aText) - 1), -1); end; procedure TSwiftParser.InvalidSymbols(aLine: Integer; const aSymbols: string); begin FErrors.Add( TSwiftError.Create( Format(cInvalidSymbols, [ReplaceText(aSymbols, #13#10, ' ')]), 0, aLine, 1, FErrors.Count)); end; function TSwiftParser.IsBlockEnd(aChar: Char): Boolean; begin Result := aChar = '}'; end; function TSwiftParser.IsBlockEnd(aIsTextBlock: Boolean; const aData: string; aIndex: Integer): Boolean; const sTextBlockEnd = sLineBreak + '-'; begin if IsBlockEnd(aData[aIndex]) then begin if aIsTextBlock then begin if Copy(aData, aIndex - Length(sTextBlockEnd), Length(sTextBlockEnd)) = sTextBlockEnd then Result := True else Result := False; end else Result := True; end else Result := False; end; function TSwiftParser.IsBlockStart(aChar: Char): Boolean; begin Result := aChar = '{'; end; function TSwiftParser.IsTextBlock(const aData: string): Boolean; var Offset: Integer; begin if Length(aData) < 3 then Exit(False); Offset := 1; if Copy(aData, Offset, 2) = '4:' then begin Inc(Offset, 2); while (Offset < Length(aData)) do begin if aData[Offset] = '{' then Exit(False) else if aData[Offset] = ':' then Exit(True); Inc(Offset); end; Result := True; end else Result := False; end; procedure TSwiftParser.Build(aMessage: TSwiftMessage; const aData: string); var Offset: Integer; Buffer, Before, After: string; Block: TSwiftBlock; BlockBegin, BlockEnd: Integer; CurrentLine: Integer; Ident, Index: Integer; begin FCurrentLine := 1; FErrors.Clear(); if (aData = '') then fErrors.Add(TSwiftError.Create(cEmptyMessage, 0, 1, 1, fErrors.Count)); FMessage := aData; FMessageObj := aMessage; BlockBegin := 1; Offset := FindBlockStart(FMessage, 1); while Offset <> -1 do begin CurrentLine := FCurrentLine; if (BlockBegin = 1) and (Offset > 1) then if not SameText(SubString(FMessage, BlockBegin, Offset), #01) then begin Index := Pos(#01, SubString(FMessage, BlockBegin, Offset)); if Index = 0 then begin if Length(SubString(FMessage, BlockBegin, Offset)) > 0 then InvalidSymbols(CurrentLine, SubString(FMessage, BlockBegin, Offset)) end else if Index = 1 then InvalidSymbols(CurrentLine, SubString(FMessage, BlockBegin + Length(#01), Offset)) else begin Before := SubString(FMessage, BlockBegin, BlockBegin + Index - 1); After := SubString(FMessage, BlockBegin + Index - 1 + Length(#01), Offset); if Before <> '' then InvalidSymbols(CurrentLine, Before); if After <> '' then InvalidSymbols(CurrentLine, After); end; end; BlockBegin := Offset; Buffer := ReadUntilBlockEnd(FMessage, Offset); BlockEnd := BlockBegin + Length(Buffer) + 1; Ident := IdentifyBlock(Buffer); if Ident in [1..5] then begin Index := Pos(':', Buffer); if Index > 1 then begin Correct(Buffer, FCurrentLine, Index); Delete(Buffer, 1, Index); end; end; // в Buffer(-е) содержится текст соответствующего блока без его идентификации case Ident of 1: Block := TSwiftBlock1.Create(aMessage, Buffer); 2: Block := TSwiftBlock2.Create(aMessage, Buffer); 3: Block := TagListBlockConsume(TSwiftBlock3.Create(aMessage), Buffer, CurrentLine); 4: Block := Block4Consume(TSwiftBlock4.Create(aMessage), Buffer, CurrentLine); 5: Block := TagListBlockConsume(TSwiftBlock5.Create(aMessage), Buffer, CurrentLine); else Block := nil; end; if Assigned(Block) then begin Block.Line := CurrentLine; aMessage.AddBlock(Block); end else UnknownBlock(CurrentLine, Buffer); CurrentLine := FCurrentLine; Offset := FindBlockStart(FMessage, Offset + Length(Buffer) + 1); if (BlockEnd + 1) < Offset then InvalidSymbols(CurrentLine, SubString(FMessage, BlockEnd + 1, Offset)) //между блоками else if Offset = -1 then if not SameText(SubString(FMessage, BlockEnd + 1, Length(FMessage) + 1), #03) then begin Index := Pos(#03, SubString(FMessage, BlockEnd + 1, Length(FMessage) + 1)); if Index = 0 then begin if Length(SubString(FMessage, BlockEnd + 1, Length(FMessage) + 1)) > 0 then InvalidSymbols(CurrentLine, SubString(FMessage, BlockEnd + 1, Length(FMessage) + 1)) end else if Index = 1 then InvalidSymbols(CurrentLine, SubString(FMessage, BlockEnd + 1 + Length(#03), Length(FMessage) + 1)) else begin Before := SubString(FMessage, BlockEnd + 1, BlockEnd + 1 + Index - 1); After := SubString(FMessage, BlockEnd + 1 + Index - 1 + Length(#03), Length(FMessage) + 1); if Before <> '' then InvalidSymbols(CurrentLine, Before); if After <> '' then InvalidSymbols(CurrentLine, After); end; end; BlockBegin := Offset; end; if (aMessage.Block1 = nil) then FErrors.Add( TSwiftError.Create(Format(cBlockNotFound, [1]), 0, 1, 1, FErrors.Count)); if (aMessage.Block2 = nil) then FErrors.Add( TSwiftError.Create(Format(cBlockNotFound, [2]), 0, 1, 1, FErrors.Count)); if (aMessage.FBlock4 = nil) then FErrors.Add( TSwiftError.Create(Format(cBlockNotFound, [4]), 0, 1, 1, FErrors.Count)); end; function TSwiftParser.ReadUntilBlockEnd(const aText: string; aOffset: Integer): string; var Index: Integer; Len, Starts, Count, Start: Integer; CheckNested, IsTextBlock_: Boolean; CurrentLine: Integer; begin IsTextBlock_ := False; // анализируемый блок не текстовый CheckNested := True; // проверка на закрыващуюся скобку блока '}' Count := 0; Index := aOffset + 1; // позиция начала блока и его длина Start := aOffset; Len := 0; Starts := 1; // говорит о том, что начало блока уже положено CurrentLine := FCurrentLine; while True do begin // анализ считываемого текста на предмет специального блока, текстового if (not IsTextBlock_) and (Count >= 3) then begin IsTextBlock_ := IsTextBlock(Copy(aText, Start, Count)); if IsTextBlock_ then CheckNested := False; end; Inc(Count); // если дошли до конца разбираемого текста if Index > Length(aText) then Break else begin if CheckNested and IsBlockStart(aText[Index]) then Inc(Starts); if IsBlockEnd(IsTextBlock_, aText, Index) then begin if CheckNested then begin Dec(Starts); if Starts = 0 then Break else Inc(Len); end else Break; end else Inc(Len); end; Correct(aText, FCurrentLine, Index, Index); Inc(Index); end; // не совпадает по количеству открывающихся и закрывающихся фигурных скобок if CheckNested then if (Starts <> 0) and (Len > 0) then UnbalancedBrackets(CurrentLine); Result := Copy(aText, Start + 1, Len); end; function TSwiftParser.SubString(const aData: string; aBegin, aEnd: Integer): string; begin Result := Copy(aData, aBegin, aEnd - aBegin); end; function TSwiftParser.TagListBlockConsume(aBlock: TSwiftTagListBlock; const aTextBlock: string; aLine: Integer): TSwiftBlock; var Finish, Index, Line, Temp: Integer; Data: string; begin Data := aTextBlock; // Сохраним текст aBlock.Text := Data; Index := 1; while (Index > 0) and (Index <= Length(Data)) do begin Correct(Data, aLine, Index, Index); Line := aLine; if Data[Index] = '{' then begin Finish := PosEx('}', Data, Index); if Finish > 1 then begin aBlock.AddTag(CreateTag(SubString(Data, Index + 1, Finish), Line)); Correct(Data, aLine, Finish, Index); Index := Finish + 1; Continue; end; end else begin Temp := Index; // пропускаем все символы, пока не найдем начало блока Index := PosEx('{', Data, Index); if Index >= 0 then InvalidSymbols(Line, SubString(Data, Temp, IfThen(Index > 0, Index, Length(Data) + 1))); Correct(Data, aLine, Index, Temp); Continue; end; Correct(Data, aLine, Index, Index); Inc(Index); end; Result := aBlock; end; procedure TSwiftParser.UnbalancedBrackets(aLine: Integer); begin FErrors.Add( TSwiftError.Create(cUnbalancedBrackets, 0, aLine, 1, FErrors.Count)); end; procedure TSwiftParser.UnknownBlock(aLine: Integer; const aData: string); begin FErrors.Add( TSwiftError.Create( Format(cUnknownBlock, [aData]), 0, aLine, 1, FErrors.Count)); end; {$ENDREGION} {$Region 'TSwiftDatabase'} class function TSwiftDatabase.GetMandatoryFields( aMsgType: Integer): TSwiftMandatoryFieldArray; var Index: Integer; function GetMandatoryFieldsFromArray(aFieldsArray: array of TSwiftFieldsRec): TSwiftMandatoryFieldArray; var I : Integer; begin SetLength(Result, 0); for I := 0 to High(aFieldsArray) do begin if (aFieldsArray[ I ].Mandatory in [1, 2]) then begin SetLength(Result, Length(Result) + 1); Result[ High(Result) ] := TSwiftMandatoryField.Create( aFieldsArray[ I ].FullName, aFieldsArray[ I ].Mandatory); end; end; end; begin if not Contains(aMsgType, [518, 541, 543]) then begin with TMyQuery.Create() do try SQL.Text := 'select t.fieldname as tag, t.mandatory '#13#10 + ' from SWIFTMSGFORMAT t '#13#10 + ' where t.msgformat = :MSGTYPE '#13#10 + ' and t.mandatory = 1 '#13#10 + 'union '#13#10 + 'select distinct '':'' || substr(t.fieldname, 2, 2) || '':'' as tag, t.mandatory '#13#10 + ' from SWIFTMSGFORMAT t '#13#10 + ' where t.msgformat = :MSGTYPE '#13#10 + ' and t.mandatory = 2'; ParamByName('MSGTYPE').AsInteger := aMsgType; Active := True; SetLength(Result, RecordCount); for Index := 0 to RecordCount - 1 do if not Eof then begin Result[Index] := TSwiftMandatoryField.Create( FieldByName('TAG').AsString, FieldByName('MANDATORY').AsInteger); Next(); end; finally Free(); end; end else begin case aMsgType of 518: Result := GetMandatoryFieldsFromArray(cSwiftFieldsFour518); 541,543: Result := GetMandatoryFieldsFromArray(cSwiftFieldsFour541); end; end; end; class function TSwiftDatabase.GetMsgArchive(aID: Integer): TSwiftMsgArchive; begin with TMyQuery.Create() do try SQL.Text := 'select * from SWIFTMSGARCHIVE t where t.swiftmsgid = :ID'; ParamByName('ID').AsInteger := aID; Active := True; if not Eof then Result := TSwiftMsgArchive.Create( aID, FieldByName('DIRECTION').AsInteger, ''{FieldByName('').AsString}, FieldByName('SENDER').AsString, FieldByName('RECEIVER').AsString, ReplaceStr(FieldByName('MSGTEXT').AsString, '~', ''#$D#$A'')) else Result := TSwiftMsgArchive.Create(aID, -1, '', '', '', ''); finally Free(); end; end; class function TSwiftDatabase.GetMsgArchiveMatching(aMsgType: Integer; aMsgArchive: TSwiftMsgArchive): TSwiftMsgArchiveArray; var Index: Integer; begin // возможно, нужно исключить те записи, которые уже связанные (linkmsgid, entitytid) with TMyQuery.Create() do try SQL.Text := 'select * '#13#10 + ' from SWIFTMSGARCHIVE t '#13#10 + ' where t.msgtype = :MSGTYPE '#13#10 + ' and t.direction = :DIRECTION '#13#10 + IfThen(aMsgArchive.Direction = 0, ' and t.sender = :SENDER', ' and t.reciever = :RECIEVER');// + // IfThen(aMsgArchive.Direction = 0, // ' '#13#10 + // ' and t.linkmsgid is not null '#13#10 + // ' and t.entitytid is not null', // ''); ParamByName('MSGTYPE').AsInteger := aMsgType; ParamByName('DIRECTION').AsInteger := IfThen(aMsgArchive.Direction = 0, 1, 0); //ParamByName('').AsString := aMsgArchive.Reference; if aMsgArchive.Direction = 0 then ParamByName('SENDER').AsString := aMsgArchive.Reciever else ParamByName('RECIEVER').AsString := aMsgArchive.Sender; Active := True; SetLength(Result, RecordCount); for Index := 0 to RecordCount - 1 do if not Eof then begin Result[Index] := TSwiftMsgArchive.Create( FieldByName('SWIFTMSGID').AsInteger, FieldByName('DIRECTION').AsInteger, ''{FieldByName('').AsString}, FieldByName('SENDER').AsString, FieldByName('RECEIVER').AsString, ReplaceStr(FieldByName('MSGTEXT').AsString, '~', ''#$D#$A'')); Next(); end; finally Free(); end; end; class function TSwiftDatabase.GetMsgFormat(aMsgType: Integer; const aFieldName: string): TSwiftMsgFormat; begin if Contains(aMsgType, [518, 541, 543]) then begin Result := TSwiftMsgFormat.Empty(); Exit; end; with TMyQuery.Create() do try SQL.Text := 'select * from SWIFTMSGFORMAT t where t.msgformat in (:MSGTYPE, :MSGTYPEBASE) and t.fieldname = concat(concat('':'', :FIELDNAME), '':'') order by t.msgformat desc'; ParamByName('MSGTYPE').AsInteger := aMsgType; ParamByName('MSGTYPEBASE').AsInteger := aMsgType mod 100; ParamByName('FIELDNAME').AsString := aFieldName; Active := True; if not Eof then Result := TSwiftMsgFormat.Create( ReplaceText(AdjustLineBreaks(FieldByName('CONTENT').AsString), sLineBreak, ' '), FieldByName('PATTERN').AsString, FieldByName('NOTES').AsString, FieldByName('DESCRIPTION').AsString, Boolean(FieldByName('MANDATORY').AsInteger)) else Result := TSwiftMsgFormat.Empty(); finally Free(); end; end; class function TSwiftDatabase.GetFieldsFormatFromArray(aFieldsArray: array of TSwiftFieldsRec; const aFieldName: string): TSwiftMsgFormat; var I : Integer; begin for I := 0 to High(aFieldsArray) do begin if (SameText(aFieldsArray[ I ].FullName, aFieldName)) or (Pos(aFieldsArray[ I ].FullName, aFieldName) > 0) then begin Result := TSwiftMsgFormat.Create( aFieldsArray[ I ].Content, aFieldsArray[ I ].Pattern,'','', Boolean(aFieldsArray[ I ].Mandatory)); Break; end else Result := TSwiftMsgFormat.Empty(); end; end; class function TSwiftDatabase.GetMsgFormat(aMsgType: Integer; const aField: TSwiftField): TSwiftMsgFormat; begin if not Contains(aMsgType, [518, 541, 543]) then begin with TMyQuery.Create() do try SQL.Text := 'select * from SWIFTMSGFORMAT t where t.msgformat in (:MSGTYPE, :MSGTYPEBASE) and t.fieldname = concat(concat('':'', :FIELDNAME), '':'') order by t.msgformat desc'; ParamByName('MSGTYPE').AsInteger := aMsgType; ParamByName('MSGTYPEBASE').AsInteger := aMsgType mod 100; ParamByName('FIELDNAME').AsString := aField.Tag.Name; Active := True; if not Eof then Result := TSwiftMsgFormat.Create( ReplaceText(AdjustLineBreaks(FieldByName('CONTENT').AsString), sLineBreak, ' '), FieldByName('PATTERN').AsString, FieldByName('NOTES').AsString, FieldByName('DESCRIPTION').AsString, Boolean(FieldByName('MANDATORY').AsInteger)) else Result := TSwiftMsgFormat.Empty(); finally Free(); end; end else begin case aMsgType of 518: Result := GetFieldsFormatFromArray(cSwiftFieldsFour518, aField.Tag.FullName); 541,543: Result := GetFieldsFormatFromArray(cSwiftFieldsFour541, aField.Tag.FullName); end; end; end; {$ENDREGION} {$Region 'TSwiftMsgFormat'} constructor TSwiftMsgFormat.Create(const aContent, aPattern, aNotes, aDescription: string; aMandatory: Boolean); begin Content := aContent; Pattern := aPattern; Notes := aNotes; Description := aDescription; Mandatory := aMandatory; end; class function TSwiftMsgFormat.Empty: TSwiftMsgFormat; begin Result := TSwiftMsgFormat.Create('', '', '', '', False); end; function TSwiftMsgFormat.IsEmpty: Boolean; begin Result := (Content = '') and (Pattern = '') and (Notes = '') and (Description = '') and (Mandatory = False); end; {$ENDREGION} {$Region 'TSwift'} class function TSwift.GetInstance(aMsgType: Integer): TSwiftMessage; begin Result := nil; try Result := TSwiftMessage.Create(aMsgType); except on E: Exception do Exception.RaiseOuterException(ESwiftException.Create(E.Message)); end; end; function SplitString(const S, Delimiter: string): TStringDynArray; var StartIdx, FoundIdx: Integer; SplitPoints, CurrentSplit: Integer; i: Integer; begin Result := nil; if S <> '' then begin { Determine the length of the resulting array } SplitPoints := 0; i := PosEx(Delimiter, s); while i <> 0 do begin Inc(i, Length(Delimiter)); Inc(SplitPoints); i := PosEx(Delimiter, s, i); end; SetLength(Result, SplitPoints + 1); { Split the string and fill the resulting array } StartIdx := 1; CurrentSplit := 0; repeat FoundIdx := PosEx(Delimiter, S, StartIdx); if FoundIdx <> 0 then begin Result[CurrentSplit] := Copy(S, StartIdx, FoundIdx - StartIdx); Inc(CurrentSplit); StartIdx := FoundIdx + Length(Delimiter); end; until CurrentSplit = SplitPoints; // copy the remaining part in case the string does not end in a delimiter Result[SplitPoints] := Copy(S, StartIdx, Length(S) - StartIdx + 1); end; end; function TrimEnd(const aText, aSubText: string): string; overload; var I: Integer; begin I := Length(aText) - Length(aSubText) + 1; if (I > 0) and (not SameText(Copy(aText, I, Length(aSubText)), aSubText)) then Exit(aText); while (I > 0) and SameText(Copy(aText, I, Length(aSubText)), aSubText) do Dec(I, Length(aSubText)); Result := Copy(aText, 1, I + Length(aSubText) - 1); end; function TrimEnd(const aText: string; aChars: TSysCharSet): string; overload; var I: Integer; begin I := Length(aText); if (I > 0) and (not CharInSet(aText[I], aChars)) then Exit(aText); while (I > 0) and (CharInSet(aText[I], aChars)) do Dec(I); Result := Copy(aText, 1, I); end; class function TSwiftArchive.MatchBlockFour(aMsgType: Integer; const aLeft, aRight: string; aMatchTags: array of TSwiftMatchTag; aMatching: TSwiftMatchingFunc): Boolean; var Left, Right: TSwiftMessage; Parser: TSwiftParser; eMsgType: Integer; begin try Left := TSwift.GetInstance(aMsgType); // для сверки swift сообщений различных типов if Contains(aMsgType, [541,543,545,547]) then begin case aMsgType of 541: eMsgType := 545; 543: eMsgType := 547; 545: eMsgType := 541; 547: eMsgType := 543; end; end else eMsgType := aMsgType; Right := TSwift.GetInstance(eMsgType); try // разбор текстов SWIFT сообщений Parser := TSwiftParser.Create(); try Parser.Build(Left, TrimEnd(aLeft, [#10, #13])); Parser.Build(Right, TrimEnd(aRight, [#10, #13])); finally Parser.Free(); end; Result := aMatching(Left, Right, aMatchTags); finally Left.Free(); Right.Free(); end; except Result := False; end; end; class function TSwiftArchive.MsgMatching(aMsgType: Integer; const aLeft, aRight: string; aStrict: Boolean): Boolean; begin try if aStrict then begin case aMsgType of 300: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour300, TSwiftArchive.MatchBlockFour300); 320: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour320, TSwiftArchive.MatchBlockFour320); 600: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour600, TSwiftArchive.MatchBlockFour600); 202: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour202, TSwiftArchive.MatchBlockFour202); 518: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour518, TSwiftArchive.MatchBlockFour5n); 541,545,543,547: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour541, TSwiftArchive.MatchBlockFour5n); else Result := False; end; end else begin case aMsgType of 300: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour300NotStrict, TSwiftArchive.MatchBlockFour300); 320: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour320NotStrict, TSwiftArchive.MatchBlockFour320); 600: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour600NotStrict, TSwiftArchive.MatchBlockFour600); 202: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour202NotStrict, TSwiftArchive.MatchBlockFour202); 518: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour518NotStrict, TSwiftArchive.MatchBlockFour5n); 541,545,543,547: Result := TSwiftArchive.MatchBlockFour(aMsgType, aLeft, aRight, cMatchTagBlockFour541NotStrict, TSwiftArchive.MatchBlockFour5nNotStrict); else Result := False; end; end; except Result := False; end; end; class function TSwiftArchive.MsgMatchingProtocol(aMsgType: Integer; const aLeft, aRight: string; var aProtocol: string): Boolean; begin case aMsgType of 300: Result := TSwiftArchive.MatchBlockFourProtocol(aMsgType, aLeft, aRight, cMatchTagBlockFour300, TSwiftArchive.MatchBlockFour300Protocol, aProtocol); 320: Result := TSwiftArchive.MatchBlockFourProtocol(aMsgType, aLeft, aRight, cMatchTagBlockFour320, TSwiftArchive.MatchBlockFour320Protocol, aProtocol); 600: Result := TSwiftArchive.MatchBlockFourProtocol(aMsgType, aLeft, aRight, cMatchTagBlockFour600, TSwiftArchive.MatchBlockFour600Protocol, aProtocol); 202: Result := TSwiftArchive.MatchBlockFourProtocol(aMsgType, aLeft, aRight, cMatchTagBlockFour202, TSwiftArchive.MatchBlockFour202Protocol, aProtocol); 518: Result := TSwiftArchive.MatchBlockFourProtocol(aMsgType, aLeft, aRight, cMatchTagBlockFour518, TSwiftArchive.MatchBlockFour5nProtocol, aProtocol); 541,545,543,547: Result := TSwiftArchive.MatchBlockFourProtocol(aMsgType, aLeft, aRight, cMatchTagBlockFour541, TSwiftArchive.MatchBlockFour5nProtocol, aProtocol); else Result := False; end; end; class function TSwiftArchive.MatchBlockFour202(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; begin Result := TSwiftArchive.MatchBlockFour300(aLeft, aRight, aMatchTags); end; class function TSwiftArchive.MatchBlockFour202Protocol(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string): Boolean; begin Result := TSwiftArchive.MatchBlockFour300Protocol(aLeft, aRight, aMatchTags, aProtocol); end; class function TSwiftArchive.MatchBlockFour300(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; var MatchTag: TSwiftMatchTag; SequenceLeft, Left, SequenceRight, Right: TSwiftTag; Data: TStringDynArray; begin Result := False; try if Assigned(aLeft.Block4) and Assigned(aRight.Block4) then for MatchTag in aMatchTags do begin // если задан полный путь, sequence и имя поля, то... if MatchTag.Explicit then begin Data := SplitString(MatchTag.Left, '.'); SequenceLeft := aLeft.Block4.GetSequence(Data[Length(Data)-2]); if Assigned(SequenceLeft) then Left := SequenceLeft.GetTagBy(Data[Length(Data)-1], MatchTag.Option) // Option - только по цифрам else Left := nil; Data := SplitString(MatchTag.Right, '.'); SequenceRight := aRight.Block4.GetSequence(Data[Length(Data)-2]); if Assigned(SequenceRight) then begin if MatchTag.Option then if Assigned(Left) then Right := SequenceRight.GetTagBy(Data[Length(Data)-1] + Copy(Left.Name, Length(Left.Name), 1))// а символ из левой части else Right := nil else Right := SequenceRight.GetTagBy(Data[Length(Data)-1]); end else Right := nil; // если нету последовательностей с обеих сторон, то это нормально if not Assigned(SequenceLeft) and not Assigned(SequenceRight) then Continue; end else begin Left := aLeft.Block4.GetTagBy(MatchTag.Left, MatchTag.Option); if MatchTag.Option then if Assigned(Left) then Right := aRight.Block4.GetTagBy(MatchTag.Right + Copy(Left.Name, Length(Left.Name), 1))// а символ из левой части else Right := nil else Right := aRight.Block4.GetTagBy(MatchTag.Right); end; // если нету полей с обеих сторон, то это нормально if not Assigned(Left) and not Assigned(Right) then Continue; if not Assigned(Left) or not Assigned(Right) or not SameText(Left.Value, Right.Value) then Exit; end; Result := True; except Result := False; end; end; class function TSwiftArchive.MatchBlockFour300Protocol(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string): Boolean; var MatchTag: TSwiftMatchTag; SequenceLeft, Left, SequenceRight, Right: TSwiftTag; Data: TStringDynArray; iTag: TSwiftTag; begin aProtocol := ''; Result := False; if Assigned(aLeft.Block4) and Assigned(aRight.Block4) then begin for MatchTag in aMatchTags do begin // если задан полный путь, sequence и имя поля, то... if MatchTag.Explicit then begin Data := SplitString(MatchTag.Left, '.'); SequenceLeft := aLeft.Block4.GetSequence(Data[Length(Data)-2]); if Assigned(SequenceLeft) then Left := SequenceLeft.GetTagBy(Data[Length(Data)-1], MatchTag.Option) // Option - только по цифрам else Left := nil; Data := SplitString(MatchTag.Right, '.'); SequenceRight := aRight.Block4.GetSequence(Data[Length(Data)-2]); if Assigned(SequenceRight) then Right := SequenceRight.GetTagBy(Data[Length(Data)-1], MatchTag.Option) else Right := nil; // если нету последовательностей с обеих сторон, то это нормально if not Assigned(SequenceLeft) and not Assigned(SequenceRight) then Continue; end else begin Left := aLeft.Block4.GetTagBy(MatchTag.Left, MatchTag.Option); Right := aRight.Block4.GetTagBy(MatchTag.Right, MatchTag.Option); end; // если нету полей с обеих сторон, то это нормально if not Assigned(Left) and not Assigned(Right) then Continue; if Assigned(Right) then begin if Assigned(Left) then begin if not SameText(Left.Value, Right.Value) then aProtocol := aProtocol + Format('Поле "%s": %s, требуется: %s', [iff(MatchTag.Option, MatchTag.Right + copy(Right.FName, length(Right.FName), 1), MatchTag.Right), ReplaceStr(Right.Value, ''#$D#$A'', ' '), ReplaceStr(Left.Value, ''#$D#$A'', ' ')]) + sLineBreak end else aProtocol := aProtocol + Format('Поле "%s": %s, требуется: %s', [iff(MatchTag.Option, MatchTag.Right + copy(Right.FName, length(Right.FName), 1), MatchTag.Right), ReplaceStr(Right.Value, ''#$D#$A'', ' '), 'должно отсутствовать']) + sLineBreak; end else begin if Assigned(Left) then aProtocol := aProtocol + Format('Поле "%s": не найдено, требуется: %s', [iff(MatchTag.Option, MatchTag.Right + 'a', MatchTag.Right), ReplaceStr(Left.Value, ''#$D#$A'', ' ')]) + sLineBreak; end; end; if aRight.MsgType = 300 then begin aProtocol := aProtocol + sLineBreak + 'Дополнительная информация по сообщениям' + sLineBreak; iTag := aLeft.Block4.GetSequence('33B'); if Assigned(iTag) then begin iTag := iTag.GetTagBy('58', True); if Assigned(iTag) then aProtocol := aProtocol + Format('Поле "%s": исходного сообщения: %s', ['15B.33B.' + iTag.Name, ReplaceStr(iTag.Value, ''#$D#$A'', ' ')]) + sLineBreak else aProtocol := aProtocol + Format('Поле "%s": исходного сообщения: %s', ['15B.33B.58a', 'не найдено']) + sLineBreak end; iTag := aright.Block4.GetSequence('33B'); if Assigned(iTag) then begin iTag := iTag.GetTagBy('58', True); if Assigned(iTag) then aProtocol := aProtocol + Format('Поле "%s": сообщения, с которым сверяемся: %s', ['15B.33B.' + iTag.Name, ReplaceStr(iTag.Value, ''#$D#$A'', ' ')]) + sLineBreak else aProtocol := aProtocol + Format('Поле "%s": сообщения, с которым сверяемся: %s', ['15B.33B.58a', 'не найдено']) + sLineBreak end; end; end; if aProtocol <> '' then Result := True; end; class function TSwiftArchive.MatchBlockFour320(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; var MatchTag: TSwiftMatchTag; SequenceLeft, Left, SequenceRight, Right, Tag: TSwiftTag; Data: TStringDynArray; begin Result := False; try if Assigned(aLeft.Block4) and Assigned(aRight.Block4) then for MatchTag in aMatchTags do begin // если задан полный путь, sequence и имя поля, то... if MatchTag.Explicit then begin Data := SplitString(MatchTag.Left, '.'); SequenceLeft := aLeft.Block4.GetSequence(Data[Length(Data)-2]); if Assigned(SequenceLeft) then Left := SequenceLeft.GetTagBy(Data[Length(Data)-1], MatchTag.Option) // Option - только по цифрам else Left := nil; Data := SplitString(MatchTag.Right, '.'); SequenceRight := aRight.Block4.GetSequence(Data[Length(Data)-2]); if Assigned(SequenceRight) then begin if MatchTag.Option then if Assigned(Left) then Right := SequenceRight.GetTagBy(Data[Length(Data)-1] + Copy(Left.Name, Length(Left.Name), 1))// а символ из левой части else Right := nil else Right := SequenceRight.GetTagBy(Data[Length(Data)-1]); end else Right := nil; // если нету последовательностей с обеих сторон, то это нормально if not Assigned(SequenceLeft) and not Assigned(SequenceRight) then Continue; end else begin Left := aLeft.Block4.GetTagBy(MatchTag.Left, MatchTag.Option); if MatchTag.Option then if Assigned(Left) then Right := aRight.Block4.GetTagBy(MatchTag.Right + Copy(Left.Name, Length(Left.Name), 1))// а символ из левой части else Right := nil else Right := aRight.Block4.GetTagBy(MatchTag.Right); end; // если нету полей с обеих сторон, то это нормально if not Assigned(Left) and not Assigned(Right) then Continue; // специальное сравнение (17R 320) if SameText(MatchTag.Left, '15B.17R') then begin if Assigned(Left) and Assigned(Right) then begin if (SameText(Left.Value, 'L') and SameText(Right.Value, 'B')) or (SameText(Left.Value, 'B') and SameText(Right.Value, 'L')) then Continue; end; Exit; end; // для опциональных полей (32H 320) // поле 22B должно быть равно "MATU", тогда сравнивается 32H if SameText(MatchTag.Left, '15B.32H') then begin Tag := aLeft.Block4.GetTagBy('22B'); if not Assigned(Tag) and not SameText(Tag.Value, 'MATU') then Continue; Tag := aRight.Block4.GetTagBy('22B'); if not Assigned(Tag) and not SameText(Tag.Value, 'MATU') then Continue; end; if not Assigned(Left) or not Assigned(Right) or not SameText(Left.Value, Right.Value) then Exit; end; Result := True; except Result := False; end; end; class function TSwiftArchive.MatchBlockFour320Protocol(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string): Boolean; var MatchTag: TSwiftMatchTag; SequenceLeft, Left, SequenceRight, Right, Tag: TSwiftTag; Data: TStringDynArray; begin aProtocol := ''; Result := False; if Assigned(aLeft.Block4) and Assigned(aRight.Block4) then for MatchTag in aMatchTags do begin // если задан полный путь, sequence и имя поля, то... if MatchTag.Explicit then begin Data := SplitString(MatchTag.Left, '.'); SequenceLeft := aLeft.Block4.GetSequence(Data[Length(Data)-2]); if Assigned(SequenceLeft) then Left := SequenceLeft.GetTagBy(Data[Length(Data)-1], MatchTag.Option) // Option - только по цифрам else Left := nil; Data := SplitString(MatchTag.Right, '.'); SequenceRight := aRight.Block4.GetSequence(Data[Length(Data)-2]); if Assigned(SequenceRight) then begin if MatchTag.Option then if Assigned(Left) then Right := SequenceRight.GetTagBy(Data[Length(Data)-1] + Copy(Left.Name, Length(Left.Name), 1))// а символ из левой части else Right := nil else Right := SequenceRight.GetTagBy(Data[Length(Data)-1]); end else Right := nil; // если нету последовательностей с обеих сторон, то это нормально if not Assigned(SequenceLeft) and not Assigned(SequenceRight) then Continue; end else begin Left := aLeft.Block4.GetTagBy(MatchTag.Left, MatchTag.Option); if MatchTag.Option then if Assigned(Left) then Right := aRight.Block4.GetTagBy(MatchTag.Right + Copy(Left.Name, Length(Left.Name), 1))// а символ из левой части else Right := nil else Right := aRight.Block4.GetTagBy(MatchTag.Right); end; // если нету полей с обеих сторон, то это нормально if not Assigned(Left) and not Assigned(Right) then Continue; // специальное сравнение (17R 320) if SameText(MatchTag.Left, '15B.17R') then begin if Assigned(Left) and Assigned(Right) then begin if (SameText(Left.Value, 'L') and SameText(Right.Value, 'B')) or (SameText(Left.Value, 'B') and SameText(Right.Value, 'L')) then Continue else begin aProtocol := aProtocol + Format('Поле "%s": %s, требуется: %s', [MatchTag.Right, ReplaceStr(Right.Value, ''#$D#$A'', ''), IfThen(Left.Value = 'L', 'B', 'L')]) + sLineBreak; Continue; end; end else begin if Assigned(Left) then begin aProtocol := aProtocol + Format('Поле "%s": не найдено, требуется: %s', [MatchTag.Right, IfThen(Left.Value = 'L', 'B', 'L')]) + sLineBreak; Continue; end else if Assigned(Right) then begin aProtocol := aProtocol + Format('Поле "%s": %s, требуется: должно отсутствовать', [MatchTag.Right, ReplaceStr(Right.Value, ''#$D#$A'', '')]) + sLineBreak; Continue; end; Continue; end; end; // для опциональных полей (32H 320) // поле 22B должно быть равно "MATU", тогда сравнивается 32H if SameText(MatchTag.Left, '15B.32H') then begin Tag := aLeft.Block4.GetTagBy('22B'); if not Assigned(Tag) and not SameText(Tag.Value, 'MATU') then Continue; Tag := aRight.Block4.GetTagBy('22B'); if not Assigned(Tag) and not SameText(Tag.Value, 'MATU') then Continue; end; if Assigned(Right) then begin if Assigned(Left) then begin if not SameText(Left.Value, Right.Value) then aProtocol := aProtocol + Format('Поле "%s": %s, требуется: %s', [MatchTag.Right, ReplaceStr(Right.Value, ''#$D#$A'', ''), ReplaceStr(Left.Value, ''#$D#$A'', '')]) + sLineBreak end else aProtocol := aProtocol + Format('Поле "%s": %s, требуется: %s', [MatchTag.Right, ReplaceStr(Right.Value, ''#$D#$A'', ''), 'должно отсутствовать']) + sLineBreak; end else begin if Assigned(Left) then aProtocol := aProtocol + Format('Поле "%s": не найдено, требуется: %s', [MatchTag.Right, ReplaceStr(Left.Value, ''#$D#$A'', '')]) + sLineBreak; end; end; if aProtocol <> '' then Result := True; end; class function TSwiftArchive.MatchBlockFour600(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; begin Result := TSwiftArchive.MatchBlockFour300(aLeft, aRight, aMatchTags); end; class function TSwiftArchive.MatchBlockFour600Protocol(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string): Boolean; begin Result := TSwiftArchive.MatchBlockFour300Protocol(aLeft, aRight, aMatchTags, aProtocol); end; class function TSwiftArchive.MatchBlockFour5Types(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string; aLogging: Boolean = False; aStrict: Boolean = True): Boolean; type TSwiftMatchTagEx = record ATagKeyL, AQualifierL, ATagKeyR, AQualifierR: string; end; const cTagKeysEx: TSwiftMatchTagEx = (ATagKeyL: '^(20C.GENL.SEME)$'; AQUalifierL: 'SEME'; ATagKeyR: '^(20C.GENL.LINK.RELA)$'; AQUalifierR: 'RELA'); var MatchTag: TSwiftMatchTag; eTagLeft, eTagRight: TSwiftTag; eDictLeft, eDictRight: TDictionary<string, TSwiftTag>; eSeq, eSubSeq, eTagKeyL, eTagKeyR, eQualifierL, eQualifierR: string; eMatches: TStringList; I: Integer; // заполняем структуру типа Dictionary из блока 4 procedure FillDictionary(aBlock: TSwiftBlock4; out aDictionary: TDictionary<string, TSwiftTag>); var I: Integer; eTagKey: string; eTmpTag: TSwiftTag; begin // создаем коллекцию объектов типа ключ - значение // ключ строится по принципу: // Tag(имя поля).Seq(имя последовательности).[SubSeq(имя подпоследовательности)].[Qualifier(имя квалификатора)] for I := 0 to aBlock.GetFieldList.Count - 1 do begin eTmpTag := aBlock.GetFieldList.Items[I].Tag; if (SameText(eTmpTag.Name, '16R')) then begin // это начало последовательности if (eSeq > '') and (eSeq <> eTmpTag.Value) then begin eSubSeq := eTmpTag.Value; end else eSeq := eTmpTag.Value; end; if (SameText(eTmpTag.Name, '16S')) then begin // это закрытие секции if eSeq = eTmpTag.Value then eSeq := '' else if eSubSeq = eTmpTag.Value then eSubSeq := ''; end; if MatchText(eTmpTag.Name, ['16R','16S']) then Continue; // тэг с наименованием последовательности пропускаем eTagKey := eTmpTag.Name; // наименование тэга if (Assigned(eTmpTag.ParentSequence)) and (eSeq > '') then eTagKey := eTagKey + '.' + eSeq; // добавляем наименование последовательности if (Assigned(eTmpTag.ParentSequence.ParentSequence)) and (eSubSeq > '') then eTagKey := eTagKey + '.' + eSubSeq; // добавляем наименование подпоследовательности if (eTmpTag.Qualifier > '') then eTagKey := eTagKey + '.' + eTmpTag.Qualifier; // добавляем наименование квалификатора aDictionary.AddOrSetValue( eTagKey, eTmpTag ); end; end; function GetValueByRegExp(const aPattern: string; aDict: TDictionary<string, TSwiftTag>; out aTag: TSwiftTag): Boolean; var eKey, eFindKey: string; eRegEx: TRegEx; begin Result := False; aTag := nil; // поиск ключа по регулярному выражению eFindKey := ''; for eKey in aDict.Keys do begin if eRegEx.IsMatch(eKey, aPattern) then begin eFindKey := eKey; Break; end; end; if eFindKey > '' then Result := aDict.TryGetValue(eFindKey, aTag); end; function GetMatchesByRegExp(const aPattern: string; aDict: TDictionary<string, TSwiftTag>; out aMatches: TStringList): Boolean; var eKey, eFindKey: string; eRegEx: TRegEx; begin aMatches.Clear; // поиск ключа по регулярному выражению eFindKey := ''; for eKey in aDict.Keys do begin if eRegEx.IsMatch(eKey, aPattern) then begin aMatches.Add(eKey); end; end; Result := aMatches.Count > 0; end; function CompareField(const aLeftKey, aRightKey: string; Option: Boolean): Boolean; var eLeftVal, eRightVal: string; begin Result := False; // поиск элемента по регулярному выражению и сравнение GetValueByRegExp(aLeftKey, eDictLeft, eTagLeft); GetValueByRegExp(aRightKey, eDictRight, eTagRight); // если нет полей с обеих сторон, то это нормально if not Assigned(eTagLeft) and not Assigned(eTagRight) then begin Result := True; Exit; end; // если нет поля слева или справа или значения полей не совпадают, // то матчинг не пройден if Assigned(eTagRight) then begin if Assigned(eTagLeft) then begin // поле 35B.TRADDET - сверка только номера ISIN if TRegEx.IsMatch(aLeftKey, '35B.TRADDET') then begin eLeftVal := Trim(GetBetweenEx('ISIN', #$D#$A, eTagLeft.Value)); eRightVal := Trim(GetBetweenEx('ISIN', #$D#$A, eTagRight.Value)); if (not SameText(eLeftVal, eRightVal)) then begin if aLogging then begin aProtocol := aProtocol + Format(#7#32'MT%d Поле "%s": %s, требуется: %s', [aRight.MsgType, eTagRight.Name, eRightVal, eLeftVal]) + sLineBreak; Exit; end; Exit; end; end else if ((not Option) and (not SameText(eTagLeft.Value, eTagRight.Value))) or ((Option) and (not SameText(SeparateRight(eTagLeft.Value, eTagLeft.Qualifier + '//'), SeparateRight(eTagRight.Value, eTagRight.Qualifier + '//')))) then begin if aLogging then begin aProtocol := aProtocol + Format(#7#32'MT%d Поле "%s": %s, требуется: %s', [aRight.MsgType, eTagRight.Name, ReplaceStr(eTagRight.Value, #$D#$A, #32), ReplaceStr(eTagLeft.Value, #$D#$A, #32)]) + sLineBreak; Exit; end; Exit; end; end else begin if aLogging then begin aProtocol := aProtocol + Format(#7#32'MT%d Поле "%s": не найдено, требуется: %s', [aRight.MsgType, eTagRight.Name, eTagRight.Value]) + sLineBreak; Exit; end; Exit; end; end else begin if Assigned(eTagLeft) and aLogging then begin aProtocol := aProtocol + Format(#7#32'MT%d Поле "%s": не найдено, требуется: %s', [aLeft.MsgType, eTagLeft.Name, eTagLeft.Value]) + sLineBreak; Exit; end; Exit; end; Result := True; end; begin Result := False; try if Assigned(aLeft.Block4) and Assigned(aRight.Block4) then // 1. Создаем коллекцию TDictionary типа ключ = значение eDictLeft := TDictionary<string, TSwiftTag>.Create; eDictRight := TDictionary<string, TSwiftTag>.Create; // 2. Заполняем структуру FillDictionary(aLeft.Block4, eDictLeft); FillDictionary(aRight.Block4, eDictRight); try { перебор коллекции паттернов полей для матчинга } for MatchTag in aMatchTags do begin if not CompareField(MatchTag.Left, MatchTag.Right, MatchTag.Option) then if aLogging then Continue else Exit; end; // дополнительное сравнение поля 22H последовательности CONFDET // для МТ518 if (aLeft.MsgType = 518) and (aStrict) then begin GetValueByRegExp('^(22H.CONFDET.BUSE)$', eDictLeft, eTagLeft); GetValueByRegExp('^(22H.CONFDET.BUSE)$', eDictRight, eTagRight); // если нет полей с обеих сторон, то это нормально if not Assigned(eTagLeft) and not Assigned(eTagRight) then begin Result := True; Exit; end; if (Assigned(eTagLeft)) and (Assigned(eTagRight)) then begin if (Pos('SELL', eTagLeft.Value) > 0) then begin if (not Pos('BUYI', eTagRight.Value) > 0) and aLogging then begin aProtocol := aProtocol + Format(#7#32'Поле "%s": %s, требуется: %s', [eTagRight.Name, eTagRight.Value, 'BUYI']) + sLineBreak; end; end else if (Pos('BUYI', eTagLeft.Value) > 0 ) then begin if (not Pos('SELL', eTagRight.Value) > 0) and aLogging then begin aProtocol := aProtocol + Format(#7#32'Поле "%s": %s, требуется: %s', [eTagRight.Name, eTagRight.Value, 'SELL']) + sLineBreak; end; end; end else Exit; if (not aLogging) or (aProtocol > '') then Result := True; end; // дополнительное сравнение поля 20С последовательности GENL // для МТ541,МТ543,MT545,MT547 if MatchText(IntToStr(aLeft.MsgType), ['541','543','545','547']) then begin // 1. Проверка поля LINK/20C/ eTagKeyL := ''; eQualifierL := ''; eTagKeyR := ''; eQualifierR := ''; if Contains(aLeft.MsgType, [541, 543 ]) then begin eTagKeyL := cTagKeysEx.ATagKeyL; eQualifierL := cTagKeysEx.AQualifierL; end; if Contains(aLeft.MsgType, [545, 547 ]) then begin eTagKeyL := cTagKeysEx.ATagKeyR; eQualifierL := cTagKeysEx.AQualifierR; end; if Contains(aRight.MsgType, [541, 543 ]) then begin eTagKeyR := cTagKeysEx.ATagKeyL; eQualifierR := cTagKeysEx.AQualifierL; end; if Contains(aRight.MsgType, [545, 547 ]) then begin eTagKeyR := cTagKeysEx.ATagKeyR; eQualifierR := cTagKeysEx.AQualifierR; end; if not CompareField(eTagKeyL, eTagKeyR, True) then begin Result := True; Exit; end; if (not aLogging) or (aProtocol > '') then Result := True; end; finally eDictLeft.Free; eDictRight.Free; end; except Result := False; end; end; class function TSwiftArchive.MatchBlockFour5n(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; var eProtocol: string; begin eProtocol := ''; Result := MatchBlockFour5Types(aLeft, aRight, aMatchTags, eProtocol); end; class function TSwiftArchive.MatchBlockFour5nNotStrict(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag): Boolean; var eProtocol: string; begin eProtocol := ''; Result := MatchBlockFour5Types(aLeft, aRight, aMatchTags, eProtocol, False, False); end; class function TSwiftArchive.MatchBlockFour5nProtocol(aLeft, aRight: TSwiftMessage; aMatchTags: array of TSwiftMatchTag; var aProtocol: string): Boolean; begin Result := MatchBlockFour5Types(aLeft, aRight, aMatchTags, aProtocol, True); end; class function TSwiftArchive.MatchBlockFourProtocol(aMsgType: Integer; const aLeft, aRight: string; aMatchTags: array of TSwiftMatchTag; aMatching: TSwiftMatchingProtocolFunc; var aProtocol: string): Boolean; var Left, Right: TSwiftMessage; Parser: TSwiftParser; eMsgType: Integer; begin try Left := TSwift.GetInstance(aMsgType); // для сверки swift сообщений различных типов if Contains(aMsgType, [541,543,545,547]) then begin case aMsgType of 541: eMsgType := 545; 543: eMsgType := 547; 545: eMsgType := 541; 547: eMsgType := 543; end; end else eMsgType := aMsgType; Right := TSwift.GetInstance(eMsgType); try // разбор текстов SWIFT сообщений Parser := TSwiftParser.Create(); try Parser.Build(Left, TrimEnd(aLeft, [#10, #13])); Parser.Build(Right, TrimEnd(aRight, [#10, #13])); finally Parser.Free(); end; Result := aMatching(Left, Right, aMatchTags, aProtocol); finally Left.Free(); Right.Free(); end; except Result := False; end; end; //////////////////////////////////////////////////////////////////////////////// /// TSwift //////////////////////////////////////////////////////////////////////////////// class function TSwift.Load(aMsgType: Integer; const aData: string): TSwiftMessage; begin Result := TSwift.GetInstance(aMsgType); try with TSwiftParser.Create() do try Build(Result, TrimEnd(aData, [#10, #13])); finally Free(); end; except FreeAndNil(Result); raise; end; end; class function TSwift.MsgFormatValid(aMsgType: Integer; const aData: string; out aErrors: string; aFieldsProc: TSwiftFieldsProc): Boolean; var Parser: TSwiftParser; Message: TSwiftMessage; Errors: TSwiftErrorList; Item: TPair<string, TSwiftFieldProc>; begin Result := True; aErrors := ''; try Message := TSwift.GetInstance(aMsgType); try Errors := TSwiftErrorList.Create(TSwiftErorrComparer.Create()); try Parser := TSwiftParser.Create(); try Parser.Build(Message, TrimEnd(aData, [#10, #13, '$'])); Errors.AddRange(Parser.Errors); finally Parser.Free(); end; if Assigned(aFieldsProc) then for Item in aFieldsProc do Message.FieldsProc.Add(Item.Key, Item.Value); Result := Message.Valid(); Errors.AddRange(Message.Errors); Result := Result and (Errors.Count = 0); finally if not Result then begin Errors.Sort(); aErrors := Errors.ToString(); end; Errors.Free(); end; finally Message.Free(); end; except on E: Exception do Exception.RaiseOuterException(ESwiftException.Create(E.Message)); end; end; {$ENDREGION} {$Region 'TSwiftBlock'} constructor TSwiftBlock.Create(aMessage: TSwiftMessage); begin FColumn := 1; FLine := 1; FMessage := aMessage; FNumber := 0; end; procedure TSwiftBlock.Error(aLine: Integer; const aText: string); begin FMessage.Errors.Add(TSwiftError.Create(aText, 1, aLine, 1, FMessage.Errors.Count)); end; procedure TSwiftBlock.Error(aLine: Integer; const aFormat: string; const aArgs: array of const); begin Error(aLine, Format(aFormat, aArgs)); end; {$ENDREGION} {$Region 'TSwiftTag'} constructor TSwiftTag.Create(const aData: string); var Index: Integer; begin FColumn := 1; FLine := 1; Index := Pos(':', aData); FName := Copy(aData, 1, Index - 1); FValue := Copy(aData, Index + 1, Length(aData) - Index); FSequence := False; FTags := TSwiftTagList.Create(False); FParentSequence := nil; FQualifier := GetBetweenEx(':', '/', FValue); end; destructor TSwiftTag.Destroy; begin FTags.Free(); inherited; end; function TSwiftTag.GetTagBy(const aName: string; aOption: Boolean): TSwiftTag; var Tag: TSwiftTag; begin Result := nil; if aOption then begin for Tag in FTags do if Pos(aName, Tag.Name) = 1 then // только по цифрам в начале Exit(Tag); end else begin for Tag in FTags do if SameText(Tag.Name, aName) then Exit(Tag); end; end; procedure TSwiftTag.SetEditor(aValue: TCustomEdit); begin if Assigned(aValue) then FEditor := aValue; end; function TSwiftTag.GetEditor: TCustomEdit; begin Result := FEditor; end; {$ENDREGION} {$Region 'TSwiftField'} constructor TSwiftField.Create(aMessage: TSwiftMessage; aTag: TSwiftTag); begin FMessage := aMessage; FTag := aTag; end; procedure TSwiftField.Error(aLine: Integer; const aText: string); begin FMessage.Errors.Add(TSwiftError.Create(aText, 1, aLine, 1, FMessage.Errors.Count)); end; procedure TSwiftField.Error(aLine: Integer; const aFormat: string; const aArgs: array of const); begin Error(aLine, Format(aFormat, aArgs)); end; function TSwiftField.Valid: Boolean; var Validators: TSwiftValidatorClassArray; begin // по умолчанию для всех TSwiftFieldNameValidator, TSwiftFieldValueValidator, // TSwiftPatternValidator Result := Validate(gFieldDefaultValidator); // валидаторы для данного поля соообщений if gFieldValidator.TryGetValue(FTag.Name, Validators) then Result := Validate(Validators) and Result; end; {$ENDREGION} {$Region 'TSwiftTagListBlock'} function TSwiftTagListBlock.AddTag(aTag: TSwiftTag; aSequence: TSwiftTag): TSwiftTag; var Tag: TSwiftTag; begin FTags.Add(aTag); Result := aTag; case FMessage.MsgType of 300: begin // 32B и 33B являются подсекциями 15B if MatchText(Result.Name, ['32B', '33B']) then begin FSequence := aTag; Tag := GetTagBy('15B'); if Assigned(Tag) then begin Tag.Tags.Add(aTag); aTag.ParentSequence := Tag; end; Exit; end; end; end; if aTag.Sequence then begin aTag.ParentSequence := FSequence; FSequence := aTag; if Assigned(aSequence) then begin FSequence := aSequence; FSequence.Tags.Add(aTag); aTag.ParentSequence := FSequence; end; end else begin if Assigned(aSequence) then begin FSequence := aSequence; FSequence.Tags.Add(aTag); aTag.ParentSequence := FSequence; end else if Assigned(FSequence) then begin FSequence.Tags.Add(aTag); aTag.ParentSequence := FSequence; end; end; end; constructor TSwiftTagListBlock.Create(aMessage: TSwiftMessage); begin inherited; FTags := TSwiftTagList.Create(True); FSequence := nil; end; destructor TSwiftTagListBlock.Destroy; begin FTags.Free(); inherited; end; function TSwiftTagListBlock.ExistOptionTag(const aName: string): Boolean; var Tag: TSwiftTag; begin Result := False; for Tag in FTags do if Pos(aName, Tag.Name) = 1 then Exit(True); end; function TSwiftTagListBlock.ExistTag(const aName: string): Boolean; var Tag: TSwiftTag; begin Result := False; for Tag in FTags do if SameText(Tag.Name, aName) then Exit(True); end; function TSwiftTagListBlock.FieldBy(aTag: TSwiftTag): TSwiftField; begin Result := TSwiftField.Create(FMessage, aTag); end; function TSwiftTagListBlock.GetCount: Integer; begin Result := FTags.Count; end; function TSwiftTagListBlock.GetFieldBy(const aName: string): TSwiftField; var Tag: TSwiftTag; begin Tag := GetTagBy(aName); if Assigned(Tag) then Result := FieldBy(Tag) else Result := nil; end; function TSwiftTagListBlock.GetFieldList: TSwiftFieldList; var Tag: TSwiftTag; begin Result := TSwiftFieldList.Create(True); for Tag in FTags do Result.Add(FieldBy(Tag)); end; function TSwiftTagListBlock.GetSequence(const aName: string): TSwiftTag; var Tag: TSwiftTag; begin Result := nil; for Tag in FTags do if Tag.Sequence and SameText(Tag.Name, aName) then Exit(Tag); end; function TSwiftTagListBlock.GetTag(Index: Integer): TSwiftTag; begin Result := FTags[Index]; end; function TSwiftTagListBlock.GetTagBy(const aName: string; aOption: Boolean): TSwiftTag; var Tag: TSwiftTag; begin Result := nil; if aOption then begin for Tag in FTags do if Pos(aName, Tag.Name) = 1 then // только по цифрам в начале Exit(Tag); end else begin for Tag in FTags do if SameText(Tag.Name, aName) then Exit(Tag); end; end; function TSwiftTagListBlock.Valid: Boolean; begin Result := not (FTags.Count = 0); if not Result then Error(FLine, cEmptyBlock, [FNumber]); end; {$ENDREGION} {$Region 'TSwiftBlock4'} constructor TSwiftBlock4.Create(aMessage: TSwiftMessage); begin inherited; FNumber := 4; FSwiftDict := TSwiftDict.Create; end; destructor TSwiftBlock4.Destroy(); begin FSwiftDict.Free; inherited; end; function TSwiftBlock4.ExistOptionTagBy(const aName: string): Boolean; var eKey, eFindKey: string; eRegEx: TRegEx; eTag: TSwiftTag; begin Result := False; eTag := nil; FillSwiftDict; if FSwiftDict.Count = 0 then Exit; // поиск ключа eFindKey := ''; for eKey in FSwiftDict.Keys do begin if TRegEx.IsMatch(eKey, aName) then begin eFindKey := eKey; Break; end; end; if eFindKey > '' then begin if (FSwiftDict.TryGetValue(eFindKey, eTag)) and (Assigned(eTag)) then Result := True; end; end; function TSwiftBlock4.ExistTagBy(const aName: string): Boolean; var eKey, eFindKey: string; eRegEx: TRegEx; eTag: TSwiftTag; begin Result := False; eTag := nil; FillSwiftDict; if FSwiftDict.Count = 0 then Exit; // поиск ключа eFindKey := ''; for eKey in FSwiftDict.Keys do begin if SameText(eKey, aName) then begin eFindKey := eKey; Break; end; end; if eFindKey > '' then begin if (FSwiftDict.TryGetValue(eFindKey, eTag)) and (Assigned(eTag)) then Result := True; end; end; function TSwiftBlock4.Valid: Boolean; var Field: TSwiftField; Fields: TSwiftFieldList; begin Result := inherited Valid(); if Result then begin FillSwiftDict; Fields := GetFieldList(); try for Field in Fields do Result := Field.Valid() and Result; finally Fields.Free(); end; end; end; // заполняем структуру типа Dictionary из блока 4 procedure TSwiftBlock4.FillSwiftDict; var I: Integer; eTmpTag: TSwiftTag; Field : TSwiftField; Fields: TSwiftFieldList; eTagKey, eSeq, eSubSeq: string; begin // создаем коллекцию объектов типа ключ - значение // ключ строится по принципу: // Tag(имя поля).Seq(имя последовательности).[SubSeq(имя подпоследовательности)].[Qualifier(имя квалификатора)] FSwiftDict.Clear; Fields := GetFieldList; for Field in Fields do begin eTmpTag := Field.Tag; if (MatchText(eTmpTag.Name, cSequenceTags)) or (MatchText(eTmpTag.Name, ['32B','33B'])) then begin // это начало последовательности if (SameText(eTmpTag.Name, '16R')) then begin // для 5-ой категории if (eSeq > '') and (eSeq <> eTmpTag.Value) then begin eSubSeq := eTmpTag.Value; end else eSeq := eTmpTag.Value; end else begin if (MatchText(eTmpTag.Name, ['32B','33B'])) then begin eSubSeq := eTmpTag.Name; end else eSeq := eTmpTag.Name; end; end; // для блоков if (MatchText(eTmpTag.Name, cSequenceTags)) or (SameText(eTmpTag.Name, '16S')) then begin eTagKey := eSeq; if eSubSeq > '' then eTagKey := eTagKey + '.' + eSubSeq; eTagKey := eTagKey + '.' + eTmpTag.Name; eTmpTag.FullName := eTagKey; FSwiftDict.AddOrSetValue( eTagKey, eTmpTag ); if (SameText(eTmpTag.Name, '16S')) then begin // это закрытие секции if eSeq = eTmpTag.Value then eSeq := '' else if eSubSeq = eTmpTag.Value then eSubSeq := ''; end; Continue; end; eTagKey := eTmpTag.Name; // наименование тэга if (Assigned(eTmpTag.ParentSequence)) and (eSeq > '') then if (Assigned(eTmpTag.ParentSequence.ParentSequence)) and (eSubSeq > '') and (eSubSeq <> eTagKey) then eTagKey := eSeq + '.' + eSubSeq + '.' + eTagKey // добавляем наименование подпоследовательности else eTagKey := eSeq + '.' + eTagKey; // добавляем наименование последовательности if (eTmpTag.Qualifier > '') then eTagKey := eTagKey + '.' + eTmpTag.Qualifier; // добавляем наименование квалификатора eTmpTag.FullName := eTagKey; FSwiftDict.AddOrSetValue( eTagKey, eTmpTag ); end; end; function TSwiftBlock4.GetFieldValueBy(const aName: string): string; var eKey, eFindKey: string; eRegEx: TRegEx; eTag: TSwiftTag; begin Result := ''; eTag := nil; FillSwiftDict; if FSwiftDict.Count = 0 then Exit; // поиск ключа по регулярному выражению eFindKey := ''; for eKey in FSwiftDict.Keys do begin if eRegEx.IsMatch(eKey, aName) then begin eFindKey := eKey; Break; end; end; if eFindKey > '' then begin if (FSwiftDict.TryGetValue(eFindKey, eTag)) and (Assigned(eTag)) then Result := eTag.Value; end; end; function TSwiftBlock4.GetFieldByEx(const aFullName: string): TSwiftField; var eKey, eFindKey: string; eTag: TSwiftTag; begin Result := nil; eTag := nil; FillSwiftDict; if FSwiftDict.Count = 0 then Exit; // поиск ключа по регулярному выражению eFindKey := ''; for eKey in FSwiftDict.Keys do begin if TRegEx.IsMatch(eKey, aFullName) then begin eFindKey := eKey; Break; end; end; if eFindKey > '' then begin if (FSwiftDict.TryGetValue(eFindKey, eTag)) and (Assigned(eTag)) then Result := TSwiftField.Create(FMessage, eTag); end; end; procedure TSwiftBlock4.RecreateTags; begin FillSwiftDict; end; function TSwiftBlock4.SwiftDictToString: string; var s: TStringBuilder; eKey: string; LArray : TArray<string>; begin Result := ''; s := TStringBuilder.Create; try FillSwiftDict; // Sort LArray := FSwiftDict.Keys.ToArray; TArray.Sort<string>(LArray); if FSwiftDict.Count = 0 then Exit; for eKey in LArray do s.AppendFormat('%s = %s'#10, [eKey, FSwiftDict.Items[ eKey ].Value]); Result := s.ToString; finally s.Free; end; end; {$ENDREGION} {$Region 'TSwiftMessage'} function TSwiftMessage.AddBlock(aBlock: TSwiftBlock): TSwiftBlock; begin FBlocks.Add(aBlock); Result := aBlock; if aBlock is TSwiftBlock1 then FBlock1 := aBlock as TSwiftBlock1; if aBlock is TSwiftBlock2 then FBlock2 := aBlock as TSwiftBlock2; if aBlock is TSwiftBlock4 then FBlock4 := aBlock as TSwiftBlock4; end; constructor TSwiftMessage.Create(aMsgType: Integer); begin FBlock1 := nil; FBlock2 := nil; FBlock4 := nil; FBlocks := TSwiftBlockList.Create(True); FErrors := TSwiftErrorList.Create(); FFieldsProc := TSwiftFieldsProc.Create(); FMsgType := aMsgType; end; destructor TSwiftMessage.Destroy; begin FFieldsProc.Free(); FErrors.Free(); FBlocks.Free(); inherited; end; function TSwiftMessage.GetBlock(Index: Integer): TSwiftBlock; begin Result := FBlocks[Index]; end; function TSwiftMessage.GetCount: Integer; begin Result := FBlocks.Count; end; function TSwiftMessage.GetMsgText: string; var eTag : TSwiftTag; eBuffer: TSWIFTBuilder; I: Integer; sHeader: string; begin eBuffer := TSWIFTBuilder.Create(); try sHeader := Format('{1:%s}{2:%s}', [FBlock1.Text, FBlock2.Text]); if (GetItemValue('CreateSection3', ItemPathName, '0') = '1') then // есть блок 3 sHeader := sHeader + Format('{3:%s}', [Blocks[2].Text]); // строим текст блока 4 eBuffer.AppendLine(sHeader + '{4:'); for I := 0 to FBlock4.GetFieldList.Count - 1 do begin eTag := FBlock4.GetFieldList.Items[I].Tag; if Assigned(eTag.Editor) then eBuffer.AppendLineFmt(':%s:%s', [eTag.Name, eTag.Editor.Text]); end; eBuffer.Append('-}'#03); Result := eBuffer.ToString(); finally eBuffer.Free(); end; end; function TSwiftMessage.Valid(): Boolean; var Block: TSwiftBlock; Validators: TSwiftValidatorClassArray; begin Result := True; try for Block in FBlocks do Result := Block.Valid() and Result; // по умолчанию для всех TSwiftMandatoryFieldsValidator Result := Validate(gMessageDefaultValidator) and Result; // валидаторы для данного типа соообщений if gMessageValidator.TryGetValue(IntToStr(FMsgType), Validators) then Result := Validate(Validators) and Result; except on E: ESwiftValidatorException do raise; on E: Exception do Exception.RaiseOuterException(ESwiftValidatorException.Create(E.Message)); end; end; {$ENDREGION} {$Region 'TSwiftBlock1'} constructor TSwiftBlock1.Create(aMessage: TSwiftMessage; const aText: string); begin inherited Create(aMessage); FNumber := 1; FText := aText; end; function TSwiftBlock1.GetSender: string; begin Result := Copy(FText, 7, 8); if not SameText(Copy(FText, 16, 3), 'XXX') then Result := Result + Copy(FText, 16, 3); end; function TSwiftBlock1.Valid: Boolean; begin Result := not (Length(FText) <> (25)); if not Result then Error(FLine, cInvalidBlockLength, [FNumber]); end; {$ENDREGION} {$Region 'TSwiftBlock2'} constructor TSwiftBlock2.Create(aMessage: TSwiftMessage; const aText: string); begin inherited Create(aMessage); FNumber := 2; FText := aText; end; function TSwiftBlock2.GetReciever: string; begin Result := Copy(FText, 5, 8); //8 -> 5 if not SameText(Copy(FText, 13, 3), 'XXX') then // 16 -> 13 Result := Result + Copy(FText, 16, 3); end; function TSwiftBlock2.Valid: Boolean; var Index: Integer; begin Index := IndexText(Copy(FText, 1, 1), ['I', 'O']); case Index of 0, 1: begin Result := not (((Index = 0) and (Length(FText) <> 17)) or ((Index = 1) and (Length(FText) <> 47))); if not Result then Error(FLine, cInvalidBlockLength, [FNumber]); end; else begin Result := False; Error(FLine, сInvalidBlockType, [FNumber]); end; end; end; {$ENDREGION} {$Region 'TSwiftBlock3'} constructor TSwiftBlock3.Create(aMessage: TSwiftMessage); begin inherited; FNumber := 3; end; {$ENDREGION} {$Region 'TSwiftBlock5'} constructor TSwiftBlock5.Create(aMessage: TSwiftMessage); begin inherited; FNumber := 5; end; {$ENDREGION} {$Region 'TSwiftError'} constructor TSwiftError.Create(const aText: string; aLevel, aLine, aColumn: Integer; aNumber: Integer); begin Text := aText; Level := aLevel; Line := aLine; Column := aColumn; Number := aNumber; end; function TSwiftError.ToString: string; begin if (Line = -1) or (Column = -1) then Result := Format('%s', [Text]) else Result := Format('[%d:%d] %s', [Line, Column, Text]); end; {$ENDREGION} {$Region 'TSwiftErrorList'} function TSwiftErrorList.ToString: string; var Error: TSwiftError; begin Result := ''; for Error in Self do Result := Result + Error.ToString() + sLineBreak; end; {$ENDREGION} {$Region 'TSwiftMandatoryFieldsValidator'} function TSwiftMandatoryFieldsValidator.Valid: Boolean; var Fields: TSwiftMandatoryFieldArray; Field: TSwiftMandatoryField; IsValid: Boolean; eTagName, eError: string; begin // обязательное поле в опциональном sequence является необязательным // поле с Field.Mandatory = 2 опциональное, т.е. (A|D|J) Result := True; if Assigned(FMessage.Block4) then begin Fields := TSwiftDatabase.GetMandatoryFields(FMessage.MsgType); for Field in Fields do begin if Field.Mandatory = 2 then begin if Contains(FMessage.MsgType, [518,541,543]) then begin eTagName := Field.Name; eError := Format(сNoFindMandatoryTag, [ eTagName ]); IsValid := FMessage.Block4.ExistOptionTagBy(eTagName); end else begin eTagName := Field.NameWithoutColon; eError := Format(сNoFindOptionMandatoryTag, [':' + eTagName + 'a' + ':']); IsValid := FMessage.Block4.ExistOptionTag(eTagName); end; if not IsValid then begin Result := False; Error(eError); end end else begin if Contains(FMessage.MsgType, [518,541,543]) then begin eTagName := Field.Name; IsValid := FMessage.Block4.ExistTagBy(eTagName); end else begin eTagName := Field.NameWithoutColon; IsValid := FMessage.Block4.ExistTag(eTagName); end; eError := eTagName; if not IsValid then begin Result := False; Error(Format(сNoFindMandatoryTag, [eError])); end; end; end; end; end; {$ENDREGION} {$Region 'TSwiftMessageValidator'} constructor TSwiftMessageValidator.Create(aSubject: TObject); begin FMessage := aSubject as TSwiftMessage; end; procedure TSwiftMessageValidator.Error(const aText: string); begin FMessage.Errors.Add(TSwiftError.Create(aText, 2, -1, -1, FMessage.Errors.Count)); end; {$ENDREGION} {$Region 'TSwiftValidator'} constructor TSwiftValidator.Create(aSubject: TObject); begin end; {$ENDREGION} {$Region 'TSwift79OrCopyValidator'} function TSwift79OrCopyValidator.Valid: Boolean; begin Result := True; if Assigned(FMessage.Block4) then begin Result := not (FMessage.Block4.ExistTag('79') and FMessage.Block4.ExistTag('15A')); if not Result then Error('Заполены поля :79: и Копия полей исходного сообщения. Одно из этих полей должно быть пустым'); end; end; {$ENDREGION} {$Region 'TSwiftErorrComparer'} function TSwiftErorrComparer.Compare(const Left, Right: TSwiftError): Integer; begin if (Left.Level in [0,1]) and (Right.Level in [0,1]) then begin Result := CompareValue(Left.Line, Right.Line); if Result = 0 then begin Result := CompareValue(Left.Level, Right.Level); if Result = 0 then Result := CompareValue(Left.Number, Right.Number); end; end else if (Left.Level = 2) and (Right.Level = 2) then Result := CompareValue(Left.Number, Right.Number) else begin if Left.Level = 2 then Result := 1 else Result := -1; end; end; {$ENDREGION} {$Region 'TSwiftFieldValidator'} constructor TSwiftFieldValidator.Create(aSubject: TObject); begin inherited; FField := aSubject as TSwiftField; end; procedure TSwiftFieldValidator.Error(const aText: string); begin FField.Message.Errors.Add( TSwiftError.Create(aText, 1, FField.Tag.Line, 1, FField.Message.Errors.Count)); end; function TSwiftFieldValidator.ValidateNumber(ANumPos: Integer; out AError: string): Boolean; var eNumber: string; begin eNumber := Copy(FField.Tag.Value, ANumPos); AError := cInvalidTagFormat; Result := Length(eNumber) < 16; if not Result then begin AError := AError + '.' + cLengthCheckError; end else begin Result := Pos(',', eNumber) > 1; if not Result then AError := AError + '.' + cCommaCheckError; end; end; {$ENDREGION} {$Region 'TSwiftPatternValidator'} function TSwiftPatternValidator.Valid: Boolean; var MsgFormat: TSwiftMsgFormat; Errors: string; begin Result := True; // проверка на недопустимы символы в поле // J.9245 - закомментировано для исключения дублирования сообщения об ошибке Result := not IsSWIFTPermissible(ReplaceText(FField.Tag.Value, sLineBreak, ''), Errors); if not Result then begin Error(Format(cInvalidTagSymbols, [FField.Tag.Name, Errors])); Exit; end; // есть теги, которые должны быть всегда пустыми if MatchText(FField.Tag.Name, cEmptyTags) then Exit; MsgFormat := TSwiftDatabase.GetMsgFormat(FField.Message.MsgType, FField); if (not MsgFormat.IsEmpty()) and (MsgFormat.Pattern <> '') then try Result := TRegEx.IsMatch(FField.Tag.Value, MsgFormat.Pattern, [roMultiLine]); if not Result then Error(Format(cInvalidTagFormat, [FField.Tag.Name, FField.Tag.Value, MsgFormat.Content])) except on E: Exception do begin Result := False; Error(Format(cRegExpError, [E.Message, MsgFormat.Pattern])); end; end; end; {$ENDREGION} {$Region 'TSwiftCheckingForSlashesValidator'} function TSwiftCheckingForSlashesValidator.Valid: Boolean; begin Result := CheckingForSlashes(FField.Tag.Value, FField.Tag.Name) = ''; if not Result then Error(Format(cNoSlashesTagValue, [FField.Tag.Name])); end; {$ENDREGION} {$Region 'TSwiftFieldNameValidator'} function TSwiftFieldNameValidator.Valid: Boolean; begin // проверка корректности имени поля Result := False; if FField.Tag.Name = '' then Error(cEmptyTagName) else if not TRegEx.IsMatch(FField.Tag.Name, '^\d{2}[A-Z]?$', [roSingleLine]) then Error(Format(cInvalidTagName, [FField.Tag.Name])) else Result := True; end; {$ENDREGION} {$Region 'TSwiftFieldValueValidator'} procedure TSwiftFieldValueValidator.Error2(aLine: Integer; const aText: string); begin FField.Message.Errors.Add( TSwiftError.Create(aText, 1, aLine, 1, FField.Message.Errors.Count)); end; function TSwiftFieldValueValidator.Valid: Boolean; var Errors: string; Lines: TStringDynArray; Index: Integer; Proc: TSwiftFieldProc; begin // проверка корректности значения поля if MatchText(FField.Tag.Name, cEmptyTags) then begin Result := not (FField.Tag.Value <> ''); if not Result then Error(Format(cNotEmptyTagValue, [FField.Tag.Name])); end else if FField.Tag.Value = '' then begin Result := False; Error(Format(cEmptyTagValue, [FField.Tag.Name])); end else begin Result := True; // проверка на длину строки в поле Lines := SplitString(AdjustLineBreaks(FField.Tag.Value), sLineBreak); // для 79 поля специальная обработка, должно быть 50 символов в строке if SameText(FField.Tag.Name, '79') then begin FField.Message.FieldsProc.TryGetValue('79', Proc); for Index := Low(Lines) to High(Lines) do begin if Length(Lines[Index]) > 50 then begin Result := False; Error2(FField.Tag.Line + Index, Format(cInvalidTagLenght, [FField.Tag.Name])); end else if Length(Lines[Index]) = 0 then begin Result := False; Error2(FField.Tag.Line + Index, Format(cInvalidTagEmpty, [FField.Tag.Name])); end; if Assigned(Proc) then Proc(FField); end; end; end; end; {$ENDREGION} {$Region 'TSwift22AValidator'} function TSwift22AValidator.Valid: Boolean; begin // у сообщений типа MT 392, 395, 396 есть зависимость от MT 300 // было замечено, что для 320 набор значений отличается case FField.Message.MsgType of 300, 392, 395, 396: begin Result := MatchText(FField.Tag.Value, ['NEWT', 'EXOP', 'DUPL', 'CANC', 'AMND']); if not Result then Error('Поле должно содержать одно из следующих кодов "NEWT,EXOP,DUPL,CANC,AMND"'); end; 320, 330: begin Result := MatchText(FField.Tag.Value, ['NEWT', 'DUPL', 'CANC', 'AMND']); if not Result then Error('Поле должно содержать одно из следующих кодов "NEWT,DUPL,CANC,AMND"'); end else // случай, если забыли реализовать прверку этого поля для нового сообщения raise ESwiftValidatorException.CreateFmt( 'Проверка поля :22A: для сообщения типа MT%d не предусмотрена', [FField.Message.MsgType]); end; end; {$ENDREGION} {$Region 'TSwift94AValidator'} function TSwift94AValidator.Valid: Boolean; begin Result := MatchText(FField.Tag.Value, ['AGNT', 'BILA', 'BROK']); if not Result then Error('Поле должно содержать одно из следующих кодов "AGNT,BILA,BROK"'); end; {$ENDREGION} {$Region 'TSwift22CValidator'} function TSwift22CValidator.Valid: Boolean; begin Result := Copy(FField.Tag.Value, 1, 4) <= Copy(FField.Tag.Value, 11, 4); if not Result then Error('Коды должны располагаться в алфавитном порядке'); end; {$ENDREGION} {$Region 'TSwift17TValidator'} function TSwift17TValidator.Valid: Boolean; begin Result := MatchText(FField.Tag.Value, ['N', 'Y']); if not Result then Error('Поле должно содержать одно из следующих кодов "Y,N"'); end; {$ENDREGION} {$Region 'TSwift82AValidator'} function TSwift82AValidator.Valid: Boolean; var Value: string; begin Result := True; if ((FField.FMessage.FMsgType = 300) or (FField.FMessage.FMsgType = 320) ) and (Copy(FField.Tag.Value, 1, 1) <> '/') then begin try Value := GetSubjectInfoSwift(1).siSWIFT; except Value := CurrContext.GetVal(['REGISTRY','COMMON','BANK','SWIFT_CODE']); end; Result := FField.Tag.Value = Value; if not Result then Error(Format('''%s'' не соответствует значению SWIFT-кода банка ''%s''', [ReplaceText(FField.Tag.Value, sLineBreak, ' '), Value])); end; end; {$ENDREGION} {$Region 'TSwift56AValidator'} function TSwift56AValidator.Valid: Boolean; var Lines: TStringDynArray; begin Result := True; if Copy(FField.Tag.Value, 1, 1) <> '/' then begin Result := ValidateSWIFT(FField.Tag.Value); if not Result then Error(Format('''%s'' неверный SWIFT-код (не найден в справочнике банков)', [ReplaceText(FField.Tag.Value, sLineBreak, ' ')])); end else begin Lines := SplitString(AdjustLineBreaks(FField.Tag.Value), sLineBreak); if Length(Lines) > 1 then begin Result := ValidateSWIFT(Lines[1]); if not Result then Error(Format('''%s'' неверный SWIFT-код (не найден в справочнике банков)', [Lines[1]])); end; end; end; {$ENDREGION} {$Region 'TSwift30TValidator'} function TSwift30TValidator.Valid: Boolean; begin Result := DateUtils.IsValidDate( StrToIntDef(Copy(FField.Tag.Value, 1, 4), 0), StrToIntDef(Copy(FField.Tag.Value, 5, 2), 0), StrToIntDef(Copy(FField.Tag.Value, 7, 2), 0)); if not Result then Error(Format('''%s'' дата не соответствует формату YYYYMMDD)', [FField.Tag.Value])); end; {$ENDREGION} {$Region 'TSwift36Validator'} function TSwift36Validator.Valid: Boolean; begin Result := Pos('.', FField.Tag.Value) = 0; if not Result then Error('Неверный разделитель дробной части "."'); end; {$ENDREGION} {$Region 'TSwift58AValidator'} function TSwift58AValidator.Valid: Boolean; begin Result := True; if Copy(FField.Tag.Value, 1, 1) <> '/' then begin Result := ValidateSWIFT(FField.Tag.Value); if not Result then Error(Format('''%s'' неверный SWIFT-код (не найден в справочнике банков)', [ReplaceText(FField.Tag.Value, sLineBreak, ' ')])); end; end; {$ENDREGION} {$Region 'TSwift22AAnd21Validator'} function TSwift22AAnd21Validator.Valid: Boolean; var Field: TSwiftField; begin Result := True; if Assigned(FMessage.Block4) then begin Field := FMessage.Block4.GetFieldBy('22A'); if Assigned(Field) then begin if MatchText(Field.Tag.Value, ['AMND', 'CANC']) then Result := FMessage.Block4.ExistTag('21'); if not Result then Error('Правило С1 - отсутствует обязательное поле :21:'); end; end; end; {$ENDREGION} {$Region 'TSwift22CAnd82AValidator'} function TSwift22CAnd82AValidator.Valid: Boolean; var Field22C, Field82A: TSwiftField; Value1, Value2: string; begin Result := True; if Assigned(FMessage.Block4) then begin Field22C := FMessage.Block4.GetFieldBy('22C'); Field82A := FMessage.Block4.GetFieldBy('82A'); if Assigned(Field22C) and Assigned(Field82A) and (Copy(Field82A.Tag.Value, 1, 1) <> '/') then begin Value1 := Copy(Field22C.Tag.Value, 1, 4); Value2 := Copy(Field22C.Tag.Value, 11, 4); Result := (Pos(Value1, Field82A.Tag.Value) <> 0) or (Pos(Value2, Field82A.Tag.Value) <> 0); if not Result then Error('В поле :22С: ' + Format('''%s'',''%s'' коды не соответствуют SWIFT коду поля :82A:',[Value1, Value2])); end; end; end; {$ENDREGION} {$Region 'TSwift22CAnd87AValidator'} function TSwift22CAnd87AValidator.Valid: Boolean; var Field22C, Field87A: TSwiftField; Value1, Value2: string; begin Result := True; if Assigned(FMessage.Block4) then begin Field22C := FMessage.Block4.GetFieldBy('22C'); Field87A := FMessage.Block4.GetFieldBy('87A'); if Assigned(Field22C) and Assigned(Field87A) and (Copy(Field87A.Tag.Value, 1, 1) <> '/') then begin Value1 := Copy(Field22C.Tag.Value, 1, 4); Value2 := Copy(Field22C.Tag.Value, 11, 4); Result := (Pos(Value1, Field87A.Tag.Value) <> 0) or (Pos(Value2, Field87A.Tag.Value) <> 0); if not Result then Error('В поле :22С: ' + Format('''%s'',''%s'' коды не соответствуют SWIFT коду поля :87A:',[Value1, Value2])); end; end; end; {$ENDREGION} {$Region 'TMandatoryField'} constructor TSwiftMandatoryField.Create(aName: string; aMandatory: Integer); begin Name := aName; Mandatory := aMandatory; end; {$ENDREGION} {$Region 'TSwift30Validator'} function TSwift30Validator.Valid: Boolean; begin Result := DateUtils.IsValidDate( StrToIntDef(Copy(FField.Tag.Value, 1, 2), 0), StrToIntDef(Copy(FField.Tag.Value, 3, 2), 0), StrToIntDef(Copy(FField.Tag.Value, 5, 2), 0)); if not Result then Error(Format('''%s'' дата не соответствует формату YYMMDD)', [FField.Tag.Value])); end; {$ENDREGION} {$Region 'TSwiftValidateElement'} function TSwiftValidateElement.Validate(aValidators: TSwiftValidatorClassArray): Boolean; var Validator: TSwiftValidatorClass; begin Result := True; try for Validator in aValidators do with Validator.Create(Self) do try Result := Valid() and Result; finally Free(); end; except on E: ESwiftValidatorException do raise; on E: Exception do Exception.RaiseOuterException(ESwiftValidatorException.Create(E.Message)); end; end; {$ENDREGION} {$Region 'TSwift22ABAnd21Validator'} function TSwift22ABAnd21Validator.Valid: Boolean; var Field22A, Field22B: TSwiftField; Flag22A1, Flag22A2, Flag22B1, Flag22B2: Boolean; // по умолчанию: False begin Result := True; if Assigned(FMessage.Block4) then begin Field22A := FMessage.Block4.GetFieldBy('22A'); Field22B := FMessage.Block4.GetFieldBy('22B'); if Assigned(Field22A) and Assigned(Field22B) then begin Flag22A1 := (not SameText(Field22A.Tag.Value, '')) and (not SameText(Field22A.Tag.Value, 'NEWT')); Flag22A2 := not SameText(Field22A.Tag.Value, ''); Flag22B1 := SameText(Field22B.Tag.Value, 'CONF'); Flag22B2 := (not SameText(Field22B.Tag.Value, '')) and (not SameText(Field22B.Tag.Value, 'CONF')); if (Flag22B1 and Flag22A1) or (Flag22B2 and Flag22A2) then Result := FMessage.Block4.ExistTag('21'); if not Result then Error('Правило С1 - отсутствует обязательное поле :21:'); end; end; end; {$ENDREGION} {$Region 'TSwiftValidatorRegistry'} function TSwiftValidatorRegistry.Add(const aKey: string; aValue: TSwiftValidatorClassArray): TSwiftValidatorRegistry; begin inherited Add(aKey, aValue); Result := Self; end; function TSwiftMandatoryField.GetNameWithoutColon: string; begin Result := ReplaceText(Name, ':', ''); end; {$ENDREGION} {$Region 'TSwiftMsgArchive'} constructor TSwiftMsgArchive.Create(aID, aDirection: Integer; aReference, aSender, aReciever: string; const aText: string); begin ID := aID; Direction := aDirection; Reference := aReference; Sender := aSender; Reciever := aReciever; Text := aText; end; {$ENDREGION} {$Region 'TSwift32BAnd33BValidator'} function TSwiftSQLQueryValidator.CheckElement(const aRule, aValue: string): Boolean; begin with TMyQuery.Create() do try Result := OpenQuery(aRule, [aValue]); finally Free(); end; end; class function TSwiftSQLQueryValidator.LoadXMLTemplate(aMsgTypeID: Integer): IXMLDocument; const cnSQLText = 'select * from SWIFTMSGTYPESREF SMTR where SMTR.MSGTYPEID = :MSGTYPEID'; begin Result := nil; with TMyQuery.Create() do try if OpenQuery(cnSQLText, [aMsgTypeID]) and (FieldByName('XMLTEMPLATE').AsString <> '') then Result := LoadXMLData(FieldByName('XMLTEMPLATE').AsString); finally Free(); end; end; function TSwiftSQLQueryValidator.TryGetSwiftTag(const aSequence, aTag: string; aOption: Boolean; out aSwiftTag: TSwiftTag): Boolean; var Sequence: TSwiftTag; begin if aSequence = '' then aSwiftTag := FMessage.Block4.GetTagBy(aTag, aOption) else begin Sequence := FMessage.Block4.GetSequence(aSequence); if Assigned(Sequence) then aSwiftTag := Sequence.GetTagBy(aTag, aOption) else aSwiftTag := nil; end; Result := Assigned(aSwiftTag); end; function TSwiftSQLQueryValidator.Valid: Boolean; var XMLTemplate: IXMLDocument; Rules: IXMLNode; Sequences: IXMLNodeList; Output: Boolean; begin Result := True; Output := Result; if Assigned(FMessage.Block4) then begin XMLTemplate := LoadXMLTemplate(FMessage.MsgType); if not Assigned(XMLTemplate) then Exit; // получаем ссылку на правили swift-шаблона Rules := TXMLDocumentHelper.SelectSingleNode(XMLTemplate.DocumentElement, '/message/system/rules'); Sequences := TXMLDocumentHelper.SelectNodes(XMLTemplate.DocumentElement, '/message/text-block/sequence'); TXMLDocumentHelper.ForEach( Sequences, procedure(aSequence: IXMLNode) var Tags: IXMLNodeList; begin // получаем все теги с правилом проверки "sqlquery" Tags := TXMLDocumentHelper.SelectNodes(XMLTemplate.DocumentElement, Format('/message/text-block/sequence[@shortname="%s"]//tag[@shortname!="" and option/element/rule/@type="sqlquery"]', [aSequence.Attributes['shortname']])); TXMLDocumentHelper.ForEach( Tags, procedure(aTag: IXMLNode) var Element: IDOMNode; Name, Option, Value, Temp: string; SwiftTag: TSwiftTag; Checked: Boolean; Data: TStringDynArray; Rule: IXMLNode; begin // имя последовательности Temp := IfThen( (not aSequence.HasAttribute('shortname')) or (aSequence.Attributes['shortname'] = ''), '', '15' + aSequence.Attributes['shortname']); if TryGetSwiftTag(Temp, aTag.Attributes['shortname'], True, SwiftTag) then begin Name := SwiftTag.Name; Option := Copy(SwiftTag.Name, 3, 1); Value := ''; // проверяем значение тега по правилу из xml // если без имени, то берем правило из тега rule в element // иначе в справочнике ищем по типу и имени Rule := TXMLDocumentHelper.SelectSingleNode(aTag, Format('option[@name="%0:s" or ("%0:s"="" and not(@name))]/element/rule[@type="sqlquery"]', [Option])); if Assigned(Rule) then begin // разбитие значения тега на составляющие Element := Rule.DOMNode.ParentNode; if SameText(Element.attributes.getNamedItem('name').nodeValue, 'Currency') then Value := Copy(SwiftTag.Value, 1, 3) else if SameText(Element.attributes.getNamedItem('name').nodeValue, 'BIC') then begin Data := SplitString(SwiftTag.Value, sLineBreak); if (Length(Data) > 1) then begin if Data[0][1] = '/' then Value := Copy(Data[1], 1, 11) else Value := Copy(Data[0], 1, 11); end else Value := Copy(Data[0], 1, 11); end else Value := ''; // праверка на соответствие строки правилу if not Rule.HasAttribute('name') then Checked := CheckElement(Rule.NodeValue, Value) else begin Rule := TXMLDocumentHelper.SelectSingleNode(Rules, Format('rule[@name="%s" and @type="sqlquery"]', [Rule.Attributes['name']])); Checked := CheckElement(Rule.NodeValue, Value); end; Output := Output and Checked; if not Checked then Error(Format('Поле :%s: ' + Rule.Attributes['message'], [Name, Value])); end; end; end); end); end; Result := Output; end; {$ENDREGION} {$Region 'TXMLDocumentHelper'} class procedure TXMLDocumentHelper.ForEach(aNodes: IXMLNodeList; aProc: TProc<IXMLNode>); var Index: Integer; begin for Index := 0 to aNodes.Count - 1 do aProc(aNodes[Index]); end; class function TXMLDocumentHelper.SelectNodes(aNode: IXMLNode; const aPath: string): IXMLNodeList; var intfSelect : IDomNodeSelect; intfAccess : IXmlNodeAccess; dnlResult : IDomNodeList; intfDocAccess : IXmlDocumentAccess; doc: TXmlDocument; i : Integer; dn : IDomNode; begin Result := nil; if not Assigned(aNode) or not Supports(aNode, IXmlNodeAccess, intfAccess) or not Supports(aNode.DOMNode, IDomNodeSelect, intfSelect) then Exit; dnlResult := intfSelect.selectNodes(aPath); if Assigned(dnlResult) then begin Result := TXmlNodeList.Create(intfAccess.GetNodeObject, '', nil); if Supports(aNode.OwnerDocument, IXmlDocumentAccess, intfDocAccess) then doc := intfDocAccess.DocumentObject else doc := nil; for i := 0 to dnlResult.length - 1 do begin dn := dnlResult.item[i]; Result.Add(TXmlNode.Create(dn, nil, doc)); end; end; end; class function TXMLDocumentHelper.SelectSingleNode(aNode: IXMLNode; const aPath: string): IXMLNode; var intfSelect : IDOMNodeSelect; intfResult : IDOMNode; intfDocumentAccess : IXMLDocumentAccess; Document: TXmlDocument; begin Result := nil; if not Assigned(aNode) or not Supports(aNode.DOMNode, IDomNodeSelect, intfSelect) then Exit; intfResult := intfSelect.selectNode(aPath); if Assigned(intfResult) then begin if Supports(aNode.OwnerDocument, IXmlDocumentAccess, intfDocumentAccess) then Document := intfDocumentAccess.DocumentObject else Document := nil; Result := TXMLNode.Create(intfResult, nil, Document); end; end; {$ENDREGION} //////////////////////////////////////////////////////////////////////////////// function CheckSWIFTMsgFormat(const aMsgText: string; aMsgType: Integer = 0): string; var iMsgType: Integer; iTmp: string; begin if ((pos('{2:I', aMsgText) > 0) and (length(aMsgText) >= pos('{2:I', aMsgText) + 7)) then if (aMsgType = 0) then iMsgType := strtoint(copy(aMsgText, pos('{2:I', aMsgText) + 4, 3)) // тип сообщения определяем по 2 блоку else iMsgType := aMsgType else iMsgType := aMsgType; TSwift.MsgFormatValid(iMsgType, trim(aMsgText), Result); end; //////////////////////////////////////////////////////////////////////////////// { TSwiftStructureValidate } function TSwiftStructureValidate.Valid: Boolean; var StrBlock4: string; eBlock4: TSwiftBlock4; eTmpTag: TSwiftTag; i: Integer; s: string; function FindBlockStart( aSeqName: string; aFrom: Integer ): Boolean; var I: Integer; eTag: TSwiftTag; begin Result := False; for I := aFrom downto 0 do begin eTag := eBlock4.GetFieldList.Items[ I ].Tag; if (SameText(eTag.Name, '16R')) and (SameText(eTag.Value, aSeqName)) then begin Result := True; Break; end; end; end; function FindBlockEnd( aSeqName: string; aFrom: Integer ): Boolean; var I: Integer; eTag: TSwiftTag; begin Result := False; for I := aFrom to eBlock4.GetFieldList.Count - 1 do begin eTag := eBlock4.GetFieldList.Items[ I ].Tag; if (SameText(eTag.Name, '16S')) and (SameText(eTag.Value, aSeqName)) then begin Result := True; Break; end; end; end; begin // проверка структуры Result := True; eBlock4 := FMessage.Block4; if Assigned(eBlock4) then begin StrBlock4 := eBlock4.Text; for I := 0 to eBlock4.GetFieldList.Count - 1 do begin eTmpTag := eBlock4.GetFieldList.Items[ I ].Tag; if (SameText(eTmpTag.Name, '16R')) then begin if not FindBlockEnd(eTmpTag.Value, I) then begin Result := False; s := s + Format('[%d:1] Блок %s не закрыт'#13, [eTmpTag.Line, eTmpTag.Value]); end; end; end; for I := eBlock4.GetFieldList.Count - 1 downto 0 do begin eTmpTag := eBlock4.GetFieldList.Items[ I ].Tag; if (SameText(eTmpTag.Name, '16S')) then begin if not FindBlockStart(eTmpTag.Value, I) then begin Result := False; s := s + Format('[%d:1] Блок %s не открыт'#13, [eTmpTag.Line, eTmpTag.Value]); end; end; end; if not Result then Error(s); end; end; { TSwit22FValidator } function TSwit22FValidator.Valid: Boolean; var eReceiver: string; begin // проверка получателя Result := True; eReceiver := FMessage.Block2.GetReciever; if SameText(eReceiver, 'MGTCBEBE') then begin // проверка наличия поля SETDET.22F.RTGS Result := FMessage.Block4.ExistTagBy('SETDET.22F.RTGS'); if not Result then begin Error(Format(сNoFindMandatoryTag, ['SETDET.22F.RTGS'])); end; end; end; { TSwift35BValidator } function TSwift35BValidator.Valid: Boolean; const cPatternSubField1 = '\A(ISIN [A-Z0-9]{12})\Z'; cPatternSubField2 = '\A(^([\w\-:\(\)\.,''\+\?\/ ]{1,35}(\r\n)?)){1,4}\Z'; var TextStrings: TStringList; SubField1, SubField2: string; begin // проверка формата поля 35B [ISIN1!e12!c] [4*35x] Result := True; TextStrings := TStringList.Create; try TextStrings.Text := FField.Tag.Value; if TextStrings.Count = 0 then Exit; SubField1 := TextStrings[ 0 ]; if Pos('ISIN', SubField1) > 0 then begin TextStrings.Delete(0); SubField2 := TextStrings.Text; Result := TRegEx.IsMatch(SubField1, cPatternSubField1); end else begin SubField2 := TextStrings.Text; end; if Result then Result := TRegEx.IsMatch(SubField2, cPatternSubField2, [roMultiLine]); if not Result then Error(Format(cInvalidTagFormat, [FField.Tag.Name, FField.Tag.Value, '[ISIN1!e12!c] [4*35x]'])) finally TextStrings.Free; end; end; { TSwift90AValidator } function TSwift90AValidator.Valid: Boolean; var eError: string; begin // 4!c//4!c/15d Result := ValidateNumber(13, eError); if not Result then Error(Format(eError, [FField.Tag.Name, FField.Tag.Value, '[4!c//4!c/15d]'])); end; { TSwift90BValidator } function TSwift90BValidator.Valid: Boolean; var eError: string; begin // 4!c//4!c/3!a15d Result := ValidateNumber(16, eError); if not Result then Error(Format(eError, [FField.Tag.Name, FField.Tag.Value, '[4!c//4!c/3!a15d]'])); end; { TSwift19AValidator } function TSwift19AValidator.Valid: Boolean; var eStr, eError: string; begin // 4!c//[N]3!a15d eStr := FField.Tag.Value; if eStr[ 8 ] = 'N' then Result := ValidateNumber(12, eError) else Result := ValidateNumber(11, eError); if not Result then Error(Format(eError, [FField.Tag.Name, FField.Tag.Value, '[4!c//[N]3!a15d]'])); end; { TSwift92AValidator } function TSwift92AValidator.Valid: Boolean; var eStr, eError: string; begin // 4!c//[N]15d eStr := FField.Tag.Value; if eStr[ 8 ] = 'N' then Result := ValidateNumber(9, eError) else Result := ValidateNumber(8, eError); if not Result then Error(Format(eError, [FField.Tag.Name, FField.Tag.Value, '[4!c//[N]15d]'])); end; initialization //////////////////////////////////////////////////////////////////////////////// // по умолчанию для всех тегов: TSwiftFieldNameValidator, TSwiftFieldValueValidator, // TSwiftPatternValidator gFieldDefaultValidator := TSwiftValidatorClassArray.Create( TSwiftFieldNameValidator, TSwiftFieldValueValidator, TSwiftPatternValidator); gFieldValidator := TSwiftValidatorRegistry.Create(); gFieldValidator .Add('17T', TSwiftValidatorClassArray.Create(TSwift17TValidator)) .Add('17U', TSwiftValidatorClassArray.Create(TSwift17UValidator)) .Add('20', TSwiftValidatorClassArray.Create(TSwiftCheckingForSlashesValidator)) .Add('20C', TSwiftValidatorClassArray.Create(TSwiftCheckingForSlashesValidator)) .Add('21', TSwiftValidatorClassArray.Create(TSwiftCheckingForSlashesValidator)) .Add('22A', TSwiftValidatorClassArray.Create(TSwift22AValidator)) .Add('22C', TSwiftValidatorClassArray.Create(TSwift22CValidator)) .Add('30', TSwiftValidatorClassArray.Create(TSwift30Validator)) .Add('30T', TSwiftValidatorClassArray.Create(TSwift30TValidator)) .Add('30V', TSwiftValidatorClassArray.Create(TSwift30VValidator)) .Add('32B', TSwiftValidatorClassArray.Create(TSwift32BValidator)) .Add('33B', TSwiftValidatorClassArray.Create(TSwift33BValidator)) .Add('36', TSwiftValidatorClassArray.Create(TSwift36Validator)) .Add('56A', TSwiftValidatorClassArray.Create(TSwift56AValidator)) .Add('57A', TSwiftValidatorClassArray.Create(TSwift57AValidator)) .Add('58A', TSwiftValidatorClassArray.Create(TSwift58AValidator)) .Add('82A', TSwiftValidatorClassArray.Create(TSwift82AValidator)) .Add('87A', TSwiftValidatorClassArray.Create(TSwift87AValidator)) .Add('94A', TSwiftValidatorClassArray.Create(TSwift94AValidator)) .Add('35B', TSwiftValidatorClassArray.Create(TSwift35BValidator)) .Add('90A', TSwiftValidatorClassArray.Create(TSwift90AValidator)) .Add('90B', TSwiftValidatorClassArray.Create(TSwift90BValidator)) .Add('36B', TSwiftValidatorClassArray.Create(TSwift90AValidator)) .Add('19A', TSwiftValidatorClassArray.Create(TSwift19AValidator)) .Add('92A', TSwiftValidatorClassArray.Create(TSwift92AValidator)); // по умолчанию для всех сообщений: TSwiftMandatoryFieldsValidator gMessageDefaultValidator := TSwiftValidatorClassArray.Create( TSwiftMandatoryFieldsValidator); gMessageValidator := TSwiftValidatorRegistry.Create(); gMessageValidator .Add('300', TSwiftValidatorClassArray.Create( TSwift22AAnd21Validator, TSwift22CAnd82AValidator, TSwift22CAnd87AValidator, TSwiftSQLQueryValidator)) .Add('320', TSwiftValidatorClassArray.Create( TSwift22ABAnd21Validator, TSwift22CAnd82AValidator, TSwift22CAnd87AValidator)) .Add('392', TSwiftValidatorClassArray.Create(TSwift79OrCopyValidator)) .Add('395', TSwiftValidatorClassArray.Create(TSwift79OrCopyValidator)) .Add('396', TSwiftValidatorClassArray.Create(TSwift79OrCopyValidator)) .Add('592', TSwiftValidatorClassArray.Create(TSwift79OrCopyValidator)) .Add('595', TSwiftValidatorClassArray.Create(TSwift79OrCopyValidator)) .Add('596', TSwiftValidatorClassArray.Create(TSwift79OrCopyValidator)) .Add('518', TSwiftValidatorClassArray.Create(TSwiftStructureValidate)) .Add('541', TSwiftValidatorClassArray.Create(TSwiftStructureValidate, TSwit22FValidator)) .Add('543', TSwiftValidatorClassArray.Create(TSwiftStructureValidate, TSwit22FValidator)) ; finalization gFieldValidator.Free(); gMessageValidator.Free(); end.
unit CRC32; interface function CRC_Byte(const Octet : byte; const LastCrc : integer) : integer; function CRC_File(const FileName : string) : integer; function CRC_FileInRange(const FileName : string; const LowLimit, HighLimit : integer) : integer; const NOT_FIND = integer($FFFFFFFF); function Search(const Source, Pattern: pchar; const SourceSize, PatternSize : integer): integer; implementation uses MemMapFile; const CRC_32_TAB : array[byte] of longword = ( $00000000, $77073096, $ee0e612c, $990951ba, $076dc419, $706af48f, $e963a535, $9e6495a3, $0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988, $09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91, $1db71064, $6ab020f2, $f3b97148, $84be41de, $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7, $136c9856, $646ba8c0, $fd62f97a, $8a65c9ec, $14015c4f, $63066cd9, $fa0f3d63, $8d080df5, $3b6e20c8, $4c69105e, $d56041e4, $a2677172, $3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b, $35b5a8fa, $42b2986c, $dbbbc9d6, $acbcf940, $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59, $26d930ac, $51de003a, $c8d75180, $bfd06116, $21b4f4b5, $56b3c423, $cfba9599, $b8bda50f, $2802b89e, $5f058808, $c60cd9b2, $b10be924, $2f6f7c87, $58684c11, $c1611dab, $b6662d3d, $76dc4190, $01db7106, $98d220bc, $efd5102a, $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433, $7807c9a2, $0f00f934, $9609a88e, $e10e9818, $7f6a0dbb, $086d3d2d, $91646c97, $e6635c01, $6b6b51f4, $1c6c6162, $856530d8, $f262004e, $6c0695ed, $1b01a57b, $8208f4c1, $f50fc457, $65b0d9c6, $12b7e950, $8bbeb8ea, $fcb9887c, $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65, $4db26158, $3ab551ce, $a3bc0074, $d4bb30e2, $4adfa541, $3dd895d7, $a4d1c46d, $d3d6f4fb, $4369e96a, $346ed9fc, $ad678846, $da60b8d0, $44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9, $5005713c, $270241aa, $be0b1010, $c90c2086, $5768b525, $206f85b3, $b966d409, $ce61e49f, $5edef90e, $29d9c998, $b0d09822, $c7d7a8b4, $59b33d17, $2eb40d81, $b7bd5c3b, $c0ba6cad, $edb88320, $9abfb3b6, $03b6e20c, $74b1d29a, $ead54739, $9dd277af, $04db2615, $73dc1683, $e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8, $e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1, $f00f9344, $8708a3d2, $1e01f268, $6906c2fe, $f762575d, $806567cb, $196c3671, $6e6b06e7, $fed41b76, $89d32be0, $10da7a5a, $67dd4acc, $f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5, $d6d6a3e8, $a1d1937e, $38d8c2c4, $4fdff252, $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b, $d80d2bda, $af0a1b4c, $36034af6, $41047a60, $df60efc3, $a867df55, $316e8eef, $4669be79, $cb61b38c, $bc66831a, $256fd2a0, $5268e236, $cc0c7795, $bb0b4703, $220216b9, $5505262f, $c5ba3bbe, $b2bd0b28, $2bb45a92, $5cb36a04, $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d, $9b64c2b0, $ec63f226, $756aa39c, $026d930a, $9c0906a9, $eb0e363f, $72076785, $05005713, $95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38, $92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21, $86d3d2d4, $f1d4e242, $68ddb3f8, $1fda836e, $81be16cd, $f6b9265b, $6fb077e1, $18b74777, $88085ae6, $ff0f6a70, $66063bca, $11010b5c, $8f659eff, $f862ae69, $616bffd3, $166ccf45, $a00ae278, $d70dd2ee, $4e048354, $3903b3c2, $a7672661, $d06016f7, $4969474d, $3e6e77db, $aed16a4a, $d9d65adc, $40df0b66, $37d83bf0, $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9, $bdbdf21c, $cabac28a, $53b39330, $24b4a3a6, $bad03605, $cdd70693, $54de5729, $23d967bf, $b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94, $b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d ); function CRC_Byte(const Octet : Byte; const LastCrc : integer) : integer; begin result := CRC_32_TAB[byte(LastCrc xor integer(Octet))] xor ((LastCrc shr 8) and $00FFFFFF); end{ CRC_32 }; function CRC_File(const FileName : string) : integer; var Buffer : TFileMap; tmp : pchar; index : integer; begin result := $FFFFFFFF; Buffer := TFileMap.Create(FileName); try tmp := Buffer.Address; for index := 1 to Buffer.Size do result := CRC_Byte(byte(tmp[index - 1]), result); result := not result; finally Buffer.Free; end; end; function CRC_FileInRange(const FileName : string; const LowLimit, HighLimit : integer) : integer; var Buffer : TFileMap; tmp : pchar; index : integer; begin result := $FFFFFFFF; Buffer := TFileMap.Create(FileName); try tmp := Buffer.Address; if (LowLimit <= HighLimit) and (HighLimit <= Buffer.Size) then begin for index := 1 to LowLimit do result := CRC_Byte(byte(tmp[index - 1]), result); for index := HighLimit to Buffer.Size do result := CRC_Byte(byte(tmp[index - 1]), result); end else result := CRC_Byte(HighLimit, LowLimit); result := not result; finally Buffer.Free; end; end; function Search(const Source, Pattern: pchar; const SourceSize, PatternSize : integer): integer; var SourcePos : integer; asm push edi push esi mov edi, Source mov esi, Pattern mov SourcePos, edi sub ecx, PatternSize inc ecx cld @Again: push ecx push edi push esi mov ecx, PatternSize repe cmpsb pop esi pop edi pop ecx je @Find inc edi loop @Again mov eax, NOT_FIND jmp @Finish @Find: mov eax, edi sub eax, SourcePos @Finish: pop esi pop edi end; end.
{*******************************************************} { } { EldoS Markup Language Generator (MlGen) } { } { Lite Version 1.1 } { } { Copyright (c) 1999-2003 Mikhail Chernyshev } { } {*******************************************************} {$i ElMLGen.inc} {$ifdef ELMLGEN_ACTIVEX} {$R ElMLGen.dcr} {$endif} unit ElMlGen; (* Language description Template parameters. <params> <param name="Param_Name" value="ParamValue"/> <param name="Param_Name">ParamValue</param> <param name="Param_Name" value="ParamVa">lue</param> <translation name="Translation_Table_Name" default="template|macro|all"> <replace string="string1" with="string2"/> <replace string="string1">string2</replace> <replace string="string1" with="stri">ng2</replace> </translation name="Translation_Table_Name"> </params> Loops. <repeat name="loop name"> </repeat name="loop name"> Macros. Tag is completely replaced. <macro name="macro name"/> Conditions. Either firs or second part of the comlex tag is executed. <if name="condition name"> <else name="condition name"/> </if name="condition name"> Comments: <comment name="any_name"> </comment name="any_name"> or <comment name="any_name"/> If the line doesn't contain anything except spaces and macros which turns into empty space, empty line will not be generated. *) interface uses SysUtils, {$ifdef ELMLGEN_ACTIVEX} Windows, Messages, Forms, Controls, Graphics, {$endif} Classes; type TDynamicString = array of String; TStringsRec = record ValueName, Value : string; end; TArrayOfStringsRec = array of TStringsRec; TTranslationTable = class; TStringParameters = class; TMlPageEvent = procedure (Sender: TObject; PageNumb : integer) of object; TMlIfFoundEvent = procedure (Sender: TObject; IfName : string; TagParameters : TStringParameters; var ResultValue : boolean) of object; TMlLoopIterateEvent = procedure (Sender: TObject; LoopNumb : integer; LoopName : string; TagParameters : TStringParameters; var LoopDone : boolean) of object; TMlMacroFoundEvent = procedure (Sender: TObject; MacroName : string; TagParameters : TStringParameters; var MacroResult : string; var UseTranslationTable : boolean) of object; TMlWriteStringEvent = procedure (Sender: TObject; Value : string) of object; TMlTagFoundEvent = procedure (Sender: TObject; Tag : string; const TagClosed : boolean; TagParameters : TStringParameters) of object; TMlIsTagEvent = procedure (Sender: TObject; TagName : string; var IsTag : boolean) of object; TStringParameters = class (TPersistent) private FData: TArrayOfStringsRec; function GetCount: Integer; function GetValue(Index: Integer): string; function GetValueByName(ValueName : string): string; function GetValueName(Index: Integer): string; procedure SetCount(Value: Integer); procedure SetValue(Index: Integer; const Value: string); procedure SetValueByName(ValueName : string; const Value: string); procedure SetValueName(Index: Integer; const Value: string); public constructor Create; destructor Destroy; override; function AddValue(const aValueName, aValue : string): Integer; procedure Assign(Source: TPersistent); override; procedure AssignTo(Dest: TPersistent); override; procedure Clear; function FindItemByName(ValueName : string): Integer; function GetValueByNameEx(ValueName, DefaultValue : string): string; property Count: Integer read GetCount write SetCount; property Data: TArrayOfStringsRec read FData; property Value[Index: Integer]: string read GetValue write SetValue; property ValueByName[ValueName : string]: string read GetValueByName write SetValueByName; property ValueName[Index: Integer]: string read GetValueName write SetValueName; end; TTranslationTables = class (TCollection) private FDefaultForMacro: Integer; FDefaultForTemplate: Integer; function GetItems(Index: Integer): TTranslationTable; procedure SetDefaultForMacro(Value: Integer); procedure SetDefaultForTemplate(Value: Integer); procedure SetItems(Index: Integer; Value: TTranslationTable); public constructor Create; function Add(const TableName : string): TTranslationTable; procedure Assign(Source: TPersistent); override; procedure Clear; function FindTableByName(const TableName : string): Integer; procedure GetTableNames(Strings : TStrings); property DefaultForMacro: Integer read FDefaultForMacro write SetDefaultForMacro; property DefaultForTemplate: Integer read FDefaultForTemplate write SetDefaultForTemplate; property Items[Index: Integer]: TTranslationTable read GetItems write SetItems; default; end; TTranslationTable = class (TCollectionItem) private FName: string; FTable: TStringParameters; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function Translate(Source : string): string; property Name: string read FName write FName; property Table: TStringParameters read FTable; end; {$ifdef ELMLGEN_ACTIVEX} TBaseElMLGen = class (TCustomControl) {$else} TBaseElMLGen = class (TComponent) {$endif} private FCancelJob: Boolean; FCode: TStrings; FCommentName: string; FCustomTagNames: TStrings; {{ Устанавливается в истину при открытии следующего выходящего файла. Снимается тогда, когда будет найдена точка из которой была вызвана команда на открытие нового файла. Считается,что точка найдена, когда будет найден последний цикл из которого была вызвано требование открыть следующий файл. Если в этот момент циклов не было, то флаг будет снят немедленно при открытии выходящего файла. } FEnteringInNextPage: Boolean; FExecuting: Boolean; {$ifdef ELMLGEN_ACTIVEX} FIcon: TBitmap; {$endif} FIfNames: array of string; {{ Указатель на начало циклов } FLoopBeginPos: array of integer; {{ Указатель на начало циклов } FLoopBeginPosRzrv: array of integer; {{ Если не пустая строка, то это означает, что мы пропускаем все до конца цикла. } FLoopBreak: string; {{ Счетчики циклов } FLoopCounters: array of integer; {{ Счетчики циклов } FLoopCountersCurrentPage: array of integer; {{ Счетчики циклов } FLoopCountersRzrv: array of integer; FLoopNames: array of string; FLoopNamesRzrv: array of string; FNewPageProcessing: Boolean; FPageCount: Integer; FParameters: TStringParameters; FSource: string; FSrcPos: Integer; FTagParameters: TStringParameters; FTagPrefix: string; FTemplate: TStrings; {{ Для случая вложенных одноименных ифов } FSkipIfsDownToIndex : Integer; {{ Используется при распознавании параметров шаблона. } FTranslationTable: TTranslationTable; FTranslationTables: TTranslationTables; procedure CheckEndPos; function DoCodeBegin: Boolean; procedure DoCodeEnd; function DoCommentBegin: Boolean; function DoCommentEnd: Boolean; {{ Возвращает истину, если обнаруженный тэг является концом последнего обрабатываемого if'а. } function DoIfDone: Boolean; function DoIfElse: Boolean; function DoIfFound(CallUserEvent : boolean): Boolean; function DoIsTag(const TagName : string): Boolean; {{ Разбирает тэг макроса. При вызове переменная SrcPos установлена на начало '<macro' В конце работы должна быть установлена на следующий символ после '>'. } function DoMacroFound: string; procedure DoNextPage; function DoParamBegin(var ParamName : string; var ParamNumb : integer): Boolean; procedure DoParamEnd; function DoParamsBegin: Boolean; procedure DoParamsEnd; procedure DoRepeatBegin; procedure DoRepeatDone; function DoRepeatSkipDone: Boolean; function DoReplaceBegin(var ParamName : string; var ParamNumb : integer): Boolean; procedure DoReplaceEnd; procedure DoTagFound(TagName : string); procedure DoTranslationBegin(var TableName : string); procedure DoTranslationEnd(var TableName : string); procedure FreeArrays; procedure FreeRzrvArrays; function GetLoopCount: Integer; function GetLoopCounter(Index: Integer): Integer; function GetLoopCountersCurrentPage(Index: Integer): Integer; function GetLoopCountersCurrentPageStr(LoopName : string): Integer; function GetLoopCounterStr(LoopName : string): Integer; function GetLoopName(Index: Integer): string; {{ При вызове метода считается,что мы находимся внутри тега, и нам предстоит разобрать, что именно за параметры у этого тэга. Если параметров больше не найдено, возвращаем пустые строки. } procedure GetTagProp(var ClosedTag : boolean; TagOptions : TStringParameters); procedure PrepareTemplate; procedure SetCustomTagNames(Value: TStrings); procedure SetTagPrefix(const Value: string); procedure SetTemplate(Value: TStrings); procedure TemplateChanged(Sender: TObject); protected procedure AfterExecute; virtual; abstract; procedure BeforeExecute; virtual; abstract; {{ Calculates the part to be processed } procedure IfFound(IfName : string; TagParameters : TStringParameters; var ResultValue : boolean); virtual; abstract; procedure IsTag(TagName : string; var IsTag : boolean); virtual; {{ One of the loops starts new iteration. The user can interrupt loop execution } procedure LoopIteration(LoopNumb: integer; LoopName: string; TagParameters : TStringParameters; var LoopDone : boolean); virtual; abstract; {{ Macro detected } procedure MacroFound(MacroName : string; TagParameters : TStringParameters; var MacroResult : string; var UseTranslationTable : boolean); virtual; abstract; procedure PageBegin(PageNumb : integer); virtual; abstract; procedure PageEnd(PageNumb : integer); virtual; abstract; {$ifdef ELMLGEN_ACTIVEX} procedure Paint; override; procedure Resize; override; {$endif} procedure ProcessMessages; virtual; procedure TagFound(Tag : string; const TagClosed : boolean; TagParameters : TStringParameters); virtual; procedure WriteString(Value : string); virtual; abstract; public constructor Create(AOwner: TComponent); override; constructor CreateFrom(AOwner: TBaseElMLGen); destructor Destroy; override; procedure Abort; virtual; procedure Assign(Source: TPersistent); override; {{ Starts template processing. } procedure Execute; virtual; function GetLoopIndex(const LoopName : string): Integer; procedure LoopBreak(LoopName : string); procedure LoopContinue(LoopName : string); procedure NextPage; property Code: TStrings read FCode; property CustomTagNames: TStrings read FCustomTagNames write SetCustomTagNames; property Executing: Boolean read FExecuting; {{ The number of loops that we are currently "in" } property LoopCount: Integer read GetLoopCount; {{ Provides access to loop iteration counters. The oughtermost loop has index 0. } property LoopCounter[Index: Integer]: Integer read GetLoopCounter; {{ Provides access to loop iteration counters that count iterations on the current page. The oughtermost loop has index 0. } property LoopCountersCurrentPage[Index: Integer]: Integer read GetLoopCountersCurrentPage; property LoopCountersCurrentPageStr[LoopName : string]: Integer read GetLoopCountersCurrentPageStr; property LoopCounterStr[LoopName : string]: Integer read GetLoopCounterStr; property LoopName[Index: Integer]: string read GetLoopName; property PageCount: Integer read FPageCount; property Parameters: TStringParameters read FParameters; property TagPrefix: string read FTagPrefix write SetTagPrefix; property Template: TStrings read FTemplate write SetTemplate; property TranslationTables: TTranslationTables read FTranslationTables; end; TCustomElMLGen = class (TBaseElMLGen) private FOnAfterExecute: TNotifyEvent; FOnBeforeExecute: TNotifyEvent; FOnIfFound: TMlIfFoundEvent; FOnIsTag: TMlIsTagEvent; FOnLoopIteration: TMlLoopIterateEvent; FOnMacroFound: TMlMacroFoundEvent; FOnPageBegin: TMlPageEvent; FOnPageEnd: TMlPageEvent; FOnProcessMessages: TNotifyEvent; FOnTagFound: TMlTagFoundEvent; FOnWriteString: TMlWriteStringEvent; protected procedure AfterExecute; override; procedure BeforeExecute; override; procedure IfFound(IfName : string; TagParameters : TStringParameters; var ResultValue : boolean); override; procedure IsTag(TagName : string; var IsTag : boolean); override; procedure LoopIteration(LoopNumb: integer; LoopName: string; TagParameters : TStringParameters; var LoopDone : boolean); override; procedure MacroFound(MacroName : string; TagParameters : TStringParameters; var MacroResult : string; var UseTranslationTable : boolean); override; procedure PageBegin(PageNumb : integer); override; procedure PageEnd(PageNumb : integer); override; procedure ProcessMessages; override; procedure TagFound(Tag : string; const TagClosed : boolean; TagParameters : TStringParameters); override; procedure WriteString(Value : string); override; property OnAfterExecute: TNotifyEvent read FOnAfterExecute write FOnAfterExecute; property OnBeforeExecute: TNotifyEvent read FOnBeforeExecute write FOnBeforeExecute; property OnIfFound: TMlIfFoundEvent read FOnIfFound write FOnIfFound; property OnIsTag: TMlIsTagEvent read FOnIsTag write FOnIsTag; property OnLoopIteration: TMlLoopIterateEvent read FOnLoopIteration write FOnLoopIteration; property OnMacroFound: TMlMacroFoundEvent read FOnMacroFound write FOnMacroFound; property OnPageBegin: TMlPageEvent read FOnPageBegin write FOnPageBegin; property OnPageEnd: TMlPageEvent read FOnPageEnd write FOnPageEnd; property OnProcessMessages: TNotifyEvent read FOnProcessMessages write FOnProcessMessages; property OnTagFound: TMlTagFoundEvent read FOnTagFound write FOnTagFound; property OnWriteString: TMlWriteStringEvent read FOnWriteString write FOnWriteString; end; TElMLGen = class (TCustomElMLGen) published property CustomTagNames; property OnAfterExecute; property OnBeforeExecute; property OnIfFound; property OnIsTag; property OnLoopIteration; property OnMacroFound; property OnPageBegin; property OnPageEnd; property OnProcessMessages; property OnTagFound; property OnWriteString; property TagPrefix; property Template; end; MlGenException = class (Exception) private FMlGen: TBaseElMLGen; public constructor Create(MlGen : TBaseElMlGen; Msg: string); end; procedure Register; {$ifndef HAS_ALSTRTOOLS} function CheckPath (InpPath : string; IsPath : boolean) : string; function SetStrWidth(Value : string; Width : integer) : string; function GetWordEx(S : string; var CharNumb : integer; Breaks : TSysCharSet) : string; function GetPosOfNewString(const Value : string; CurPos : Integer) : Integer; procedure GetTextLineByStringPos(const Value : string; ValuePos: integer; var Line, CharPos: Integer); function PosP (const SubStr :string; Value : string; BegPos, EndPos : integer) : integer; function PosEx(const substr : AnsiString; const s : AnsiString; EndPos, BegPos : Integer) : Integer; {$endif} resourcestring SCanNotFindValueNameS = 'Can not find ValueName "%s"'; SDuplicateTranslationTableName = 'Duplicate translation table name.'; SCanNotSetDefaultTranslationTableIndexOutOfRange = 'Can not set default Translation Table. Index out of range.'; SNameOfCommentTagMustBeSpecified = 'Name of ''comment'' tag must be specified.'; SErrorInCommentTagDeclaration = 'Error in ''/comment'' tag declaration.'; SConditionWasNotDeclaredOrClosingTagForInnerConditionIsSkipped = 'Condition was not declared, or closing tag for inner condition is skipped.'; SErrorInElseTagDeclaration = 'Error in ''else'' tag declaration.'; SNameOfElseTagMustBeSpecified = 'Name of ''else'' tag must be specified.'; SErrorInIfTagDeclaration = 'Error in ''if'' tag declaration.'; SNameOfIfTagMustBeSpecified = 'Name of ''if'' tag must be specified.'; SErrorInMacroDeclaration = 'Error in macro declaration.'; SNameOfMacroMustBeSpecified = 'Name of macro must be specified.'; SNameOfParamTagMustBeSpecified = 'Name of ''param'' tag must be specified.'; SErrorInParamTagDeclaration1 = 'Error in ''/param'' tag declaration.'; SErrorInParamsTagDeclaration1 = 'Error in ''/params'' tag declaration.'; SErrorInRepeatTagDeclaration = 'Error in ''repeat'' tag declaration.'; SNameOfRepeatTagMustBeSpecified = 'Name of ''repeat'' tag must be specified.'; SDuplicateLoopNameS = 'Duplicate loop name ''%s''.'; STryingToCloseNotOpenedLoopInternalError = 'Trying to close not opened loop. Internal error.'; SStringInReplaceTagMustBeSpecified = 'String in ''replace'' tag must be specified.'; SEmbeddedTranslationTablesAreNotAllowed = 'Embedded translation tables are not allowed.'; SNameOfTranslationTagMustBeSpecified = 'Name of ''translation'' tag must be specified.'; SErrorInTranslationTagDeclaration1 = 'Error in ''/translation'' tag declaration.'; SNameOfTranslationTagMustBeSpecified1 = 'Name of ''/translation'' tag must be specified.'; STryingToCloseNotPreviouslyOpenedTranslationTableSS = 'Trying to close not previously opened translation table "%s". Ожидается закрытие "%s".'; SErrorInTemplateDLoopsWereNotClosed = 'Error in template: %d loops were not closed.'; SErrorInTemplateDConditionsWereNotClosed = 'Error in template: %d conditions were not closed.'; SErrorInTemplateNotAllTagsHaveBeenClosed = 'Error in template. Not all tags have been closed.'; SCanNotAnalyzeTag = 'Can not analyze tag'; SAttemptToCloseTheLoopThatHasNotBeenOpenedBefore = 'Attempt to close the loop that has not been opened before.'; SRepeatedRequestForNewPageIsNotAllowed = 'Repeated request for new page is not allowed.'; SErrorInTemplateParamsDeclaration = 'Error in template params declaration.'; SInvalidCharDSInTagPrefixString = 'Invalid char %d (%s) in tag prefix string'; SCanTChangeTemplateDuringExecution = 'Can''t change template during execution.'; SErrorInIfTagDeclaration1 = 'Error in ''/if'' tag declaration.'; SNameOfIfTagMustBeSpecified1 = 'Name of ''/if'' tag must be specified.'; SErrorInRepeatTagDeclaration1 = 'Error in ''/repeat'' tag declaration.'; SRepeatTagDoesnTHaveMatchingRepeatTag1 = '''/repeat'' tag doesn''t have matching ''repeat'' tag'; SErrorInReplaceTagDeclaration1 = 'Error in ''/replace'' tag declaration.'; SErrorWhileDetectingPositionInLineIndexOutOfRange = 'Error while detecting position in line. Index (%d) out of range (%d).'; SCanNotAssignObjectToTranslationTableList = 'Can not assign object to translation table list'; SIndexOutOfRange = 'Index out of range.'; SLoopNameIsNotFound = 'Loop name is not found.'; SErrorInCodeTagDeclaration = 'Error in ''/code'' tag declaration'; SLineChar = '%s Line: %d, Char: %d.'; SError = 'Error.'; SCanNotAssignToTranslationTable = 'Can not assign to Translation Table.'; SUnableToFindPointToReturn = 'Unable to find point to return.'; SUnableToFindPointToReturnPossibleReasonIsDuplicatedLoopName = 'Unable to find point to return. Possible reason is duplicated loop name.'; implementation {$ifdef HAS_ALSTRTOOLS} uses AlStrTools; {$endif} procedure Register; begin RegisterComponents('EldoS', [TElMLGen]); end; {$ifndef HAS_ALSTRTOOLS} {------------------------------------------------------------------------------} // проверка и модификация пути function CheckPath (InpPath : string; IsPath : boolean) : string; label l1; var p, l : integer; begin //1. Проверяем на отсутствие двойных косых черточек \\ Result := InpPath; if Result = '' then Exit; l1: p := Pos('\\', InpPath); if p <> 0 then begin Result := Copy(InpPath, 1, p); l := Length(InpPath); if p+1 < l then Result := Result + Copy(InpPath, p+2, l-p-1); InpPath := Result; goto l1; end; //2. Проверяем и удаляем кавычки if Result[1] = '"' then Result := Copy(Result, 2, Length(Result)-1); l := Length(Result); if Result[l] = '"' then Result := Copy(Result, 1, l-1); //3. Если это путь, то проверяем на наличие в конце косой черты \ if IsPath then begin l := Length(Result); if l <> 0 then if Result[l] <> '\' then Result := Result + '\'; end; end; {------------------------------------------------------------------------------} // выделение слова function GetWordEx(S : string; var CharNumb : integer; Breaks : TSysCharSet) : string; var Len : integer; begin Result := ''; Len := Length(s); if CharNumb > Len then exit; while CharNumb <= Len do if not (s[CharNumb] in Breaks) then break else inc(CharNumb); if CharNumb > Len then exit; while CharNumb <= Len do begin if s[CharNumb] in Breaks then break; Result := Result + S[CharNumb]; inc(CharNumb); end; inc(CharNumb); end; {------------------------------------------------------------------------------} // возвращает номер позиции с которой начинается следующая строка. function GetPosOfNewString(const Value : string; CurPos : Integer) : Integer; var EndPos, i : Integer; // EndStrType: // 0 еще не известно // 1 #13 - Unix // 2 #10 // 3 #13#10 - Windows // 4 #10#13 - Mac EndStrType : Integer; begin Result := -1; EndPos := Length(Value); EndStrType := 0; // for i := CurPos to EndPos do begin case Value[i] of #13 : case EndStrType of 0 : EndStrType := 1; 1, 3, 4 : begin Result := i; break; end; 2 : EndStrType := 4; end; // case #10 : case EndStrType of 0 : EndStrType := 2; 1 : EndStrType := 3; 2, 3, 4 : begin Result := i; break; end; end; // case else case EndStrType of 1, 2, 3, 4 : begin Result := i; break; end; end; // case end; // case end; // for end; {------------------------------------------------------------------------------} // Устанавливает у строки длину в символах, обрезает лишнее добавляя '...' если текст // не влазит, добавляет пробелами если строка слишком короткая function SetStrWidth(Value : string; Width : integer) : string; var i, j : Integer; begin j := Length(Value); Result := Value; if j < Width then begin SetLength(Result, Width); FillChar(Result[j+1], Width-j, #32); end else if j > Width then begin SetLength(Result, Width); for i := Width - 2 to Width do Result[i] := '.'; end; end; {------------------------------------------------------------------------------} procedure GetTextLineByStringPos(const Value : string; ValuePos: integer; var Line, CharPos: Integer); var SrcPos, SrcLen : Integer; begin SrcLen := Length(Value); if ValuePos > SrcLen then Raise Exception.Create(Format( SErrorWhileDetectingPositionInLineIndexOutOfRange, [ValuePos, SrcLen])); SrcPos := 1; Line := 1; CharPos := 1; while SrcPos <= SrcLen do begin if SrcPos >= ValuePos then break; case Value[SrcPos] of #10, #13 : begin SrcPos := GetPosOfNewString(Value, SrcPos); inc(Line); CharPos := 1; end; else begin inc(CharPos); inc(SrcPos); end; end; // case end; // while end; {------------------------------------------------------------------------------} // Поиск подстроки в строке начиная с символа номер N function PosP (const SubStr :string; Value : string; BegPos, EndPos : integer) : integer; begin if EndPos <= 0 then EndPos := Length(Value); Value := Copy(Value, BegPos, EndPos-BegPos+1); Result := Pos(SubStr, Value); if Result > 0 then inc(Result, BegPos - 1); end; {------------------------------------------------------------------------------} type StrRec = packed record allocSiz: Longint; refCnt: Longint; length: Longint; end; const skew = sizeof(StrRec); function PosEx(const substr : AnsiString; const s : AnsiString; EndPos, BegPos : Integer) : Integer; asm { ->EAX Pointer to substr } { EDX Pointer to string } { ECX Last char (= length(s) if (EndPos <=0) or (EndPos > Length(s))) } { <-EAX Position of substr in s or 0 } TEST EAX,EAX JE @@noWork TEST EDX,EDX JE @@stringEmpty // Проверяем EndPos, если < 0 или больше длины строки, то присваиваем длину строки TEST ECX,ECX JL @@Label3 CMP ECX,[EDX-skew].StrRec.length // Проверяем правильность переданного параметра EndPos JLE @@Label1 // Переход если длина строки < EndPos @@Label3: MOV ECX,[EDX-skew].StrRec.length { ECX = Length(s)} // конечное значение @@Label1: DEC BegPos JL @@stringEmpty // Переход если BegPos < 0 SUB ECX,BegPos // EndPos = EndPos - BegPos Проверяем чтобы Index был меньше EndPos JL @@stringEmpty // Переход если BegPos > EndPos PUSH EBX PUSH ESI PUSH EDI MOV ESI,EAX { Point ESI to substr } // начало строки MOV EDI,EDX { Point EDI to s } ADD EDI,BegPos // устанавливаем другой номер символа с которого начинаем искать. // MOV ECX,[EDI-skew].StrRec.length { ECX = Length(s) } // конечное значение значение PUSH EDI { remember s position to calculate index } MOV EDX,[ESI-skew].StrRec.length { EDX = Length(substr) } DEC EDX { EDX = Length(substr) - 1 } JS @@fail { < 0 ? return 0 } MOV AL,[ESI] { AL = first char of substr } INC ESI { Point ESI to 2'nd char of substr } SUB ECX,EDX { #positions in s to look at } { = Length(s) - Length(substr) + 1 } JLE @@fail @@loop: REPNE SCASB JNE @@fail MOV EBX,ECX { save outer loop counter } PUSH ESI { save outer loop substr pointer } PUSH EDI { save outer loop s pointer } MOV ECX,EDX REPE CMPSB POP EDI { restore outer loop s pointer } POP ESI { restore outer loop substr pointer } JE @@found MOV ECX,EBX { restore outer loop counter } JMP @@loop @@fail: POP EDX { get rid of saved s pointer } XOR EAX,EAX JMP @@exit @@stringEmpty: XOR EAX,EAX JMP @@noWork @@found: POP EDX { restore pointer to first char of s } MOV EAX,EDI { EDI points of char after match } SUB EAX,EDX { the difference is the correct index } ADD EAX,BegPos @@exit: POP EDI POP ESI POP EBX @@noWork: end; {$endif} {$ifdef ELDEMO} const DEMO_BUFFER_SIZE = 2100; DEMO_BUFFER_SIZE2= 2100 xor $0FF0; DEMO_BUFFER_SIZE3= 2100 xor $0A0A; {$endif ELDEMO} { ****************************** TStringParameters ******************************* } constructor TStringParameters.Create; begin inherited Create; end;{ TStringParameters.Create } destructor TStringParameters.Destroy; begin FData := nil; inherited Destroy; end;{ TStringParameters.Destroy } function TStringParameters.AddValue(const aValueName, aValue : string): Integer; begin Result := FindItemByName(aValueName); if Result < 0 then begin Result := Length(FData); SetLength(FData, Result + 1); with FData[Result] do begin ValueName := aValueName; Value := aValue; end; // with end else begin with FData[Result] do Value := Value + aValue; end; end;{ TStringParameters.AddValue } procedure TStringParameters.Assign(Source: TPersistent); var i, j: Integer; begin if Source is TStringParameters then begin j := Length(TStringParameters(Source).FData); SetLength(FData, j); for i := 0 to j - 1 do begin with TStringParameters(Source).FData[i] do begin FData[i].Value := Value; FData[i].ValueName := ValueName; end; // with end; // for end else inherited; end;{ TStringParameters.Assign } procedure TStringParameters.AssignTo(Dest: TPersistent); var i: Integer; begin if Dest is TStringParameters then Dest.Assign(self) else if Dest is TStrings then begin TStrings(Dest).Clear; if Length(FData) > 0 then for i := 0 to High(FData) do begin TStrings(Dest).Add(Format('%s=%s', [FData[i].ValueName, FData[i].Value])); end; // for end else inherited; end;{ TStringParameters.AssignTo } procedure TStringParameters.Clear; begin FData := nil; end;{ TStringParameters.Clear } function TStringParameters.FindItemByName(ValueName : string): Integer; var i: Integer; begin Result := -1; for i := 0 to High(FData) do begin if FData[i].ValueName = ValueName then begin Result := i; break; end; end; // for end;{ TStringParameters.FindItemByName } function TStringParameters.GetCount: Integer; begin Result := Length(FData); end;{ TStringParameters.GetCount } function TStringParameters.GetValue(Index: Integer): string; begin Result := FData[Index].Value; end;{ TStringParameters.GetValue } function TStringParameters.GetValueByName(ValueName : string): string; var i: Integer; begin i := FindItemByName(ValueName); if i < 0 then Raise Exception.Create(Format(SCanNotFindValueNameS, [ValueName])); Result := FData[i].Value; end;{ TStringParameters.GetValueByName } function TStringParameters.GetValueByNameEx(ValueName, DefaultValue : string): string; var i: Integer; begin i := FindItemByName(ValueName); if i >= 0 then Result := FData[i].Value else Result := DefaultValue; end;{ TStringParameters.GetValueByNameEx } function TStringParameters.GetValueName(Index: Integer): string; begin Result := FData[Index].ValueName; end;{ TStringParameters.GetValueName } procedure TStringParameters.SetCount(Value: Integer); begin SetLength(FData, Value); end;{ TStringParameters.SetCount } procedure TStringParameters.SetValue(Index: Integer; const Value: string); begin FData[Index].Value := Value; end;{ TStringParameters.SetValue } procedure TStringParameters.SetValueByName(ValueName : string; const Value: string); var i: Integer; begin i := FindItemByName(ValueName); if i < 0 then Raise Exception.Create(Format(SCanNotFindValueNameS, [ValueName])); FData[i].Value := Value; end;{ TStringParameters.SetValueByName } procedure TStringParameters.SetValueName(Index: Integer; const Value: string); begin FData[Index].ValueName := Value; end;{ TStringParameters.SetValueName } { ****************************** TTranslationTables ****************************** } constructor TTranslationTables.Create; begin inherited Create(TTranslationTable); FDefaultForMacro := -1; FDefaultForTemplate := -1; end;{ TTranslationTables.Create } function TTranslationTables.Add(const TableName : string): TTranslationTable; var i: Integer; begin i := FindTableByName(TableName); if i >= 0 then Raise Exception.Create(SDuplicateTranslationTableName); Result := TTranslationTable(inherited Add); Result.Name := TableName; end;{ TTranslationTables.Add } procedure TTranslationTables.Assign(Source: TPersistent); begin if Source is TTranslationTables then begin inherited Assign(Source); DefaultForMacro := TTranslationTables(Source).DefaultForMacro; DefaultForTemplate := TTranslationTables(Source).DefaultForTemplate; end else Raise Exception.Create(SCanNotAssignObjectToTranslationTableList); end;{ TTranslationTables.Assign } procedure TTranslationTables.Clear; begin FDefaultForMacro := -1; FDefaultForTemplate := -1; inherited Clear; end;{ TTranslationTables.Clear } function TTranslationTables.FindTableByName(const TableName : string): Integer; var i: Integer; begin Result := -1; for i := 0 to Count - 1 do begin if Items[i].Name = TableName then begin Result := i; break; end; end; // for end;{ TTranslationTables.FindTableByName } function TTranslationTables.GetItems(Index: Integer): TTranslationTable; begin Result := TTranslationTable(inherited GetItem(Index)); end;{ TTranslationTables.GetItems } procedure TTranslationTables.GetTableNames(Strings : TStrings); var i: Integer; begin for i := 0 to Count - 1 do begin Strings.Add(Items[i].Name); end; // for end;{ TTranslationTables.GetTableNames } procedure TTranslationTables.SetDefaultForMacro(Value: Integer); begin if FDefaultForMacro <> Value then begin if Value >= Count then Raise Exception.Create(SCanNotSetDefaultTranslationTableIndexOutOfRange); FDefaultForMacro := Value; end; end;{ TTranslationTables.SetDefaultForMacro } procedure TTranslationTables.SetDefaultForTemplate(Value: Integer); begin if FDefaultForTemplate <> Value then begin if Value >= Count then Raise Exception.Create(SCanNotSetDefaultTranslationTableIndexOutOfRange); FDefaultForTemplate := Value; end; end;{ TTranslationTables.SetDefaultForTemplate } procedure TTranslationTables.SetItems(Index: Integer; Value: TTranslationTable); begin inherited SetItem(Index, Value); end;{ TTranslationTables.SetItems } { ****************************** TTranslationTable ******************************* } constructor TTranslationTable.Create(Collection: TCollection); begin inherited Create(Collection); // FName := ''; FTable := TStringParameters.Create; end;{ TTranslationTable.Create } destructor TTranslationTable.Destroy; begin if Assigned(Collection) and (Collection is TTranslationTables) then begin if TTranslationTables(Collection).DefaultForMacro = Index then TTranslationTables(Collection).DefaultForMacro := -1; if TTranslationTables(Collection).DefaultForTemplate = Index then TTranslationTables(Collection).DefaultForTemplate := -1; end; FTable.Free; inherited Destroy; end;{ TTranslationTable.Destroy } procedure TTranslationTable.Assign(Source: TPersistent); begin if Source is TTranslationTable then begin FName := TTranslationTable(Source).Name; FTable.Assign(TTranslationTable(Source).Table); end else Raise Exception.Create(SCanNotAssignToTranslationTable); end;{ TTranslationTable.Assign } function TTranslationTable.Translate(Source : string): string; var i, j, k, SrcPos, SrcLen, ReplCount: Integer; s: string; Replace: Boolean; begin Result := ''; SrcLen := Length(Source); SrcPos := 1; ReplCount := High(FTable.FData); while SrcPos <= SrcLen do begin Replace := False; for i := 0 to ReplCount do begin s := FTable.FData[i].ValueName; k := Length(s); if (SrcPos + k - 1) <= SrcLen then begin Replace := True; for j := 1 to k do begin if Source[SrcPos + j - 1] <> s[j] then begin Replace := False; break; end; end; // for if Replace then begin Result := Result + FTable.FData[i].Value; inc(SrcPos, k); break; end; end; end; // for if not Replace then begin Result := Result + Source[SrcPos]; inc(SrcPos); end; end; // while end;{ TTranslationTable.Translate } { ********************************* TBaseElMLGen ********************************* } constructor TBaseElMLGen.Create(AOwner: TComponent); begin inherited Create(AOwner); {$ifdef ELMLGEN_ACTIVEX} FIcon := TBitmap.Create; FIcon.LoadFromResourceName(Hinstance, 'TELMLGEN'); {$endif} // FExecuting := False; // FNewPageProcessing := False; // FEnteringInNextPage := False; // FSource := ''; // FCommentName := ''; // FTagPrefix := ''; // FLoopBreak := ''; // FTranslationTable := nil; FTemplate := TStringList.Create; FCode := TStringList.Create; TStringList(FTemplate).OnChange := TemplateChanged; FCustomTagNames := TStringList.Create; FParameters := TStringParameters.Create; FTranslationTables := TTranslationTables.Create; FTagParameters := TStringParameters.Create; end;{ TBaseElMLGen.Create } constructor TBaseElMLGen.CreateFrom(AOwner: TBaseElMLGen); begin Create(AOwner); FCode.Assign(AOwner.FCode); FCommentName := AOwner.FCommentName; FCustomTagNames.Assign(AOwner.FCustomTagNames); FParameters.Assign(AOwner.FParameters); FTagParameters.Assign(AOwner.FTagParameters); FTagPrefix := AOwner.FTagPrefix; FTemplate.Assign(AOwner.FTemplate); FTranslationTables.Assign(AOwner.FTranslationTables); end;{ TBaseElMLGen.CreateFrom } destructor TBaseElMLGen.Destroy; begin FreeArrays; FreeRzrvArrays; FTagParameters.Free; FTranslationTables.Free; FParameters.Free; TStringList(FTemplate).OnChange := nil; FTemplate.Free; FCode.Free; FCustomTagNames.Free; {$ifdef ELMLGEN_ACTIVEX} FIcon.Free; {$endif} inherited Destroy; end;{ TBaseElMLGen.Destroy } procedure TBaseElMLGen.Abort; begin FCancelJob := True; end;{ TBaseElMLGen.Abort } procedure TBaseElMLGen.Assign(Source: TPersistent); begin Raise Exception.Create('TBaseElMLGen.Assign: Can not assign unknown object.'); end;{ TBaseElMLGen.Assign } procedure TBaseElMLGen.CheckEndPos; var j, k, SrcLen: Integer; begin // ищем конец строки в темплейте SrcLen := Length(FSource); j := FSrcPos; // Указатель на следующий символ после макроса while j <= SrcLen do begin case FSource[j] of #9, ' ' : ; #10, #13 : begin k := GetPosOfNewString(FSource, j); if k > 0 then j := k else j := SrcLen + 1; break; end; else exit; // надо записать все. (Хотя по хорошему, то что мы нашли может быть началом нового макроса) end; // case inc(j); end; // while // Теперь мы точно знаем, что строку писать не надо. Вырежем ее. FSrcPos := j; end;{ TBaseElMLGen.CheckEndPos } function TBaseElMLGen.DoCodeBegin: Boolean; var ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 5{Length('<code')}; GetTagProp(ClosedTag, FTagParameters); Result := not ClosedTag; end;{ TBaseElMLGen.DoCodeBegin } procedure TBaseElMLGen.DoCodeEnd; var ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 6{Length('</code')}; GetTagProp(ClosedTag, FTagParameters); if ClosedTag then Raise MlGenException.Create(self, SErrorInCodeTagDeclaration); end;{ TBaseElMLGen.DoCodeEnd } function TBaseElMLGen.DoCommentBegin: Boolean; var j: Integer; ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 8{Length('<comment')}; GetTagProp(ClosedTag, FTagParameters); j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array if j < 0 then Raise MlGenException.Create(self, SNameOfCommentTagMustBeSpecified); if FTagParameters.FData[j].Value = '' then Raise MlGenException.Create(self, SNameOfCommentTagMustBeSpecified); Result := not ClosedTag; if Result then FCommentName := FTagParameters.FData[j].Value; end;{ TBaseElMLGen.DoCommentBegin } function TBaseElMLGen.DoCommentEnd: Boolean; var j: Integer; ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 9{Length('</comment')}; GetTagProp(ClosedTag, FTagParameters); if ClosedTag then Raise MlGenException.Create(self, SErrorInCommentTagDeclaration); j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array // if j < 0 then // CreateException('Error in tag ''/comment'' declaration.'); // if TagPropValue[j] = '' then // CreateException('Name of tag ''/comment'' must be specified.'); if j >= 0 then Result := FCommentName = FTagParameters.FData[j].Value else Result := False; if Result then FCommentName := ''; end;{ TBaseElMLGen.DoCommentEnd } {{ Возвращает истину, если обнаруженный тэг является концом последнего обрабатываемого if'а. } function TBaseElMLGen.DoIfDone: Boolean; var i, j: Integer; ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 4{Length('</if')}; GetTagProp(ClosedTag, FTagParameters); if ClosedTag then Raise MlGenException.Create(self, SErrorInIfTagDeclaration1); j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array if j < 0 then Raise MlGenException.Create(self, SNameOfIfTagMustBeSpecified1); if FTagParameters.FData[j].Value = '' then Raise MlGenException.Create(self, SNameOfIfTagMustBeSpecified1); i := Length(FIfNames) - 1; if i >= 0 then Result := FIfNames[i] = FTagParameters.FData[j].Value else Result := False; if not Result then Raise MlGenException.Create(self, SConditionWasNotDeclaredOrClosingTagForInnerConditionIsSkipped); if Result then begin FIfNames[i] := ''; SetLength(FIfNames, i); end; if FSkipIfsDownToIndex >= 0 then begin Result := FSkipIfsDownToIndex = i; if Result then FSkipIfsDownToIndex := -1; end; end;{ TBaseElMLGen.DoIfDone } function TBaseElMLGen.DoIfElse: Boolean; var i, j: Integer; ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 5{Length('<else')}; GetTagProp(ClosedTag, FTagParameters); if not ClosedTag then Raise MlGenException.Create(self, SErrorInElseTagDeclaration); j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array if j < 0 then Raise MlGenException.Create(self, SNameOfElseTagMustBeSpecified); if FTagParameters.FData[j].Value = '' then Raise MlGenException.Create(self, SNameOfElseTagMustBeSpecified); i := Length(FIfNames) - 1; Result := i >= 0; if Result then Result := FIfNames[i] = FTagParameters.FData[j].Value; end;{ TBaseElMLGen.DoIfElse } function TBaseElMLGen.DoIfFound(CallUserEvent : boolean): Boolean; var i, j: Integer; ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 3{Length('<if')}; GetTagProp(ClosedTag, FTagParameters); if ClosedTag then Raise MlGenException.Create(self, SErrorInIfTagDeclaration); j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array if j < 0 then Raise MlGenException.Create(self, SNameOfIfTagMustBeSpecified); if FTagParameters.FData[j].Value = '' then Raise MlGenException.Create(self, SNameOfIfTagMustBeSpecified); Result := True; if CallUserEvent then IfFound(FTagParameters.FData[j].Value, FTagParameters, Result); i := Length(FIfNames); SetLength(FIfNames, i + 1); FIfNames[i] := FTagParameters.FData[j].Value; // Для пропуска вложенных ифов if not Result then FSkipIfsDownToIndex := i; end;{ TBaseElMLGen.DoIfFound } function TBaseElMLGen.DoIsTag(const TagName : string): Boolean; begin Result := False; IsTag(TagName, Result); end;{ TBaseElMLGen.DoIsTag } {{ Разбирает тэг макроса. При вызове переменная SrcPos установлена на начало '<macro' В конце работы должна быть установлена на следующий символ после '>'. } function TBaseElMLGen.DoMacroFound: string; var j: Integer; ClosedTag: Boolean; UseTranslationTable: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 6{Length('<macro')}; GetTagProp(ClosedTag, FTagParameters); if not ClosedTag then Raise MlGenException.Create(self, SErrorInMacroDeclaration); j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array if j < 0 then Raise MlGenException.Create(self, SNameOfMacroMustBeSpecified); if FTagParameters.FData[j].Value = '' then Raise MlGenException.Create(self, SNameOfMacroMustBeSpecified); UseTranslationTable := True; Result := ''; MacroFound(FTagParameters.FData[j].Value, FTagParameters, Result, UseTranslationTable); with FTranslationTables do begin if UseTranslationTable and (DefaultForMacro >= 0) then Result := Items[DefaultForMacro].Translate(Result); end; // with end;{ TBaseElMLGen.DoMacroFound } procedure TBaseElMLGen.DoNextPage; begin FNewPageProcessing := False; if Length(FLoopCountersRzrv) <> 0 then FEnteringInNextPage := True; inc(FPageCount); FreeArrays; PageBegin(PageCount); end;{ TBaseElMLGen.DoNextPage } function TBaseElMLGen.DoParamBegin(var ParamName : string; var ParamNumb : integer): Boolean; var ClosedTag: Boolean; j: Integer; ParamValue: string; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 6{Length('<param')}; GetTagProp(ClosedTag, FTagParameters); Result := not ClosedTag; j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array if j < 0 then Raise MlGenException.Create(self, SNameOfParamTagMustBeSpecified); if FTagParameters.FData[j].Value = '' then Raise MlGenException.Create(self, SNameOfParamTagMustBeSpecified); ParamName := FTagParameters.FData[j].Value; j := FTagParameters.FindItemByName('value'); // Номер параметра содержащего значение if j >= 0 then ParamValue := FTagParameters.FData[j].Value else ParamValue := ''; ParamNumb := FParameters.AddValue(ParamName, ParamValue); if not Result then begin ParamName := ''; ParamNumb := 0; end; end;{ TBaseElMLGen.DoParamBegin } procedure TBaseElMLGen.DoParamEnd; var ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 7{Length('</param')}; GetTagProp(ClosedTag, FTagParameters); if ClosedTag then Raise MlGenException.Create(self, SErrorInParamTagDeclaration1); end;{ TBaseElMLGen.DoParamEnd } function TBaseElMLGen.DoParamsBegin: Boolean; var ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 7{Length('<params')}; GetTagProp(ClosedTag, FTagParameters); Result := not ClosedTag; end;{ TBaseElMLGen.DoParamsBegin } procedure TBaseElMLGen.DoParamsEnd; var ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 8{Length('</params')}; GetTagProp(ClosedTag, FTagParameters); if ClosedTag then Raise MlGenException.Create(self, SErrorInParamsTagDeclaration1); end;{ TBaseElMLGen.DoParamsEnd } procedure TBaseElMLGen.DoRepeatBegin; var i, j, k: Integer; s: string; ClosedTag: Boolean; b: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 7{Length('<repeat')}; GetTagProp(ClosedTag, FTagParameters); if ClosedTag then Raise MlGenException.Create(self, SErrorInRepeatTagDeclaration); j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array if j < 0 then Raise MlGenException.Create(self, SNameOfRepeatTagMustBeSpecified); s := FTagParameters.FData[j].Value; if s = '' then Raise MlGenException.Create(self, SNameOfRepeatTagMustBeSpecified); // Смотрим не было ли такого цикла ранее for i := 0 to High(FLoopNames) do begin if FLoopNames[i] = s then Raise MlGenException.Create(self, Format(SDuplicateLoopNameS, [s])); end; // for i := Length(FLoopCounters) + 1; SetLength(FLoopCounters, i); SetLength(FLoopNames, i); SetLength(FLoopBeginPos, i); SetLength(FLoopCountersCurrentPage, i); dec(i); FLoopNames[i] := s; FLoopCountersCurrentPage[i] := 0; if not FEnteringInNextPage then begin FLoopCounters[i] := 0; end else begin // Если мы ищем точку вхождения в новом файле if FLoopNamesRzrv[0] = FLoopNames[0] then begin // Мы уже нашли первый цикл, и это означает, что все последующие названия должны совпадать if FLoopNames[i] <> FLoopNamesRzrv[i] then Raise MlGenException.Create(self, SUnableToFindPointToReturn); FLoopCounters[i] := FLoopCountersRzrv[i]; if Length(FLoopNames) = Length(FLoopNames) then FEnteringInNextPage := False; end else begin // Мы еще не дошли до первого цикла в котором находились на момент выхода. Это просто новый цикл. // Но этого имени не должно быть у нас в записях! s := FTagParameters.FData[j].Value; for k := 0 to High(FLoopNamesRzrv) do begin if s = FLoopNamesRzrv[k] then Raise MlGenException.Create(self, SUnableToFindPointToReturnPossibleReasonIsDuplicatedLoopName); end; // for FLoopCounters[i] := 0; end; end; FLoopBeginPos[i] := FSrcPos; b := False; // Цикл выполняется один раз. LoopIteration(i, FTagParameters.FData[j].Value, FTagParameters, b); if b then begin // Цикл завершен не начавшись i := High(FLoopCounters); FLoopBreak := FLoopNames[i]; { SetLength(FLoopCounters, i); SetLength(FLoopCountersCurrentPage, i); SetLength(FLoopBeginPos, i); FLoopNames[i] := ''; SetLength(FLoopNames, i);} end; end;{ TBaseElMLGen.DoRepeatBegin } procedure TBaseElMLGen.DoRepeatDone; var i, j: Integer; s: string; b: Boolean; ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 8{Length('</repeat')}; GetTagProp(ClosedTag, FTagParameters); if ClosedTag then Raise MlGenException.Create(self, SErrorInRepeatTagDeclaration1); j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array if j >= 0 then begin s := FTagParameters.FData[j].Value; i := GetLoopIndex(s); if i < 0 then Raise MlGenException.Create(self, SRepeatTagDoesnTHaveMatchingRepeatTag1); end else begin i := High(FLoopCounters); s := FLoopNames[i]; end; // Вызов события о следующей итерации цикла должен происходить с новым значением итератора inc(FLoopCounters[i]); inc(FLoopCountersCurrentPage[i]); // b := not LoopIteration(i, s, TagProp, TagPropValue); b := True; LoopIteration(i, s, FTagParameters, b); if (not b) and FNewPageProcessing then begin // Если цикл находится в резервном списке, прекращаем его выполнение. for j := 0 to High(FLoopNamesRzrv) do begin if (FLoopNamesRzrv[j] = s) and (FLoopBeginPos[j] = FLoopBeginPosRzrv[j]) then begin b := True; break; end; end; // for end; if b then begin // Цикл завершен SetLength(FLoopCounters, i); SetLength(FLoopCountersCurrentPage, i); SetLength(FLoopBeginPos, i); SetLength(FLoopNames, i); end else begin // Цикл продолжается // Если один /repeat закрывает несколько циклов, то информацию о них надо уничтожить if i < High(FLoopNames) then begin j := i + 1; SetLength(FLoopCounters, j); SetLength(FLoopCountersCurrentPage, j); SetLength(FLoopBeginPos, j); SetLength(FLoopNames, j); end; FSrcPos := FLoopBeginPos[i]; end; end;{ TBaseElMLGen.DoRepeatDone } function TBaseElMLGen.DoRepeatSkipDone: Boolean; var i, j: Integer; ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 8{Length('</repeat')}; GetTagProp(ClosedTag, FTagParameters); if ClosedTag then Raise MlGenException.Create(self, SErrorInRepeatTagDeclaration1); j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array if j >= 0 then begin Result := FLoopBreak = FTagParameters.FData[j].Value; if Result then begin // Цикл завершен i := GetLoopIndex(FLoopBreak); if i < 0 then Raise MlGenException.Create(self, STryingToCloseNotOpenedLoopInternalError); FLoopBreak := ''; SetLength(FLoopCounters, i); SetLength(FLoopCountersCurrentPage, i); SetLength(FLoopBeginPos, i); SetLength(FLoopNames, i); end; end else Result := False; // это не наш цикл, мы дожидаемся закрытия другого цикла end;{ TBaseElMLGen.DoRepeatSkipDone } function TBaseElMLGen.DoReplaceBegin(var ParamName : string; var ParamNumb : integer): Boolean; var ClosedTag: Boolean; j: Integer; ParamValue: string; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 8{Length('<replace')}; GetTagProp(ClosedTag, FTagParameters); Result := not ClosedTag; j := FTagParameters.FindItemByName('string'); // Position of name parameter in the array if j < 0 then Raise MlGenException.Create(self, SStringInReplaceTagMustBeSpecified); if FTagParameters.FData[j].Value = '' then Raise MlGenException.Create(self, SStringInReplaceTagMustBeSpecified); ParamName := FTagParameters.FData[j].Value; j := FTagParameters.FindItemByName('with'); // Номер параметра содержащего значение if j >= 0 then ParamValue := FTagParameters.FData[j].Value else ParamValue := ''; ParamNumb := FTranslationTable.Table.AddValue(ParamName, ParamValue); if not Result then begin ParamName := ''; ParamNumb := 0; end; end;{ TBaseElMLGen.DoReplaceBegin } procedure TBaseElMLGen.DoReplaceEnd; var ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 9{Length('</replace')}; GetTagProp(ClosedTag, FTagParameters); if ClosedTag then Raise MlGenException.Create(self, SErrorInReplaceTagDeclaration1); end;{ TBaseElMLGen.DoReplaceEnd } procedure TBaseElMLGen.DoTagFound(TagName : string); var ClosedTag: Boolean; begin FSrcPos := FSrcPos + Length(FTagPrefix) + Length(TagName) + 1; GetTagProp(ClosedTag, FTagParameters); TagFound(TagName, ClosedTag, FTagParameters); end;{ TBaseElMLGen.DoTagFound } procedure TBaseElMLGen.DoTranslationBegin(var TableName : string); var ClosedTag: Boolean; j: Integer; s : string; begin if TableName <> '' then Raise MlGenException.Create(self, SEmbeddedTranslationTablesAreNotAllowed); FSrcPos := FSrcPos + Length(FTagPrefix) + 12{Length('<translation')}; GetTagProp(ClosedTag, FTagParameters); j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array if j < 0 then Raise MlGenException.Create(self, SNameOfTranslationTagMustBeSpecified); TableName := FTagParameters.FData[j].Value; if TableName = '' then Raise MlGenException.Create(self, SNameOfTranslationTagMustBeSpecified); FTranslationTable := FTranslationTables.Add(TableName); j := FTagParameters.FindItemByName('default'); if j >= 0 then begin s := LowerCase(FTagParameters.FData[j].Value); if s = 'macro' then FTranslationTables.DefaultForMacro := FTranslationTable.Index else if s = 'template' then FTranslationTables.DefaultForTemplate := FTranslationTable.Index else if s = 'all' then begin FTranslationTables.DefaultForMacro := FTranslationTable.Index; FTranslationTables.DefaultForTemplate := FTranslationTable.Index; end else Raise MlGenException.Create(self, 'Unknown value for ''default'' property.'); end; if ClosedTag then begin TableName := ''; FTranslationTable := nil; end; end;{ TBaseElMLGen.DoTranslationBegin } procedure TBaseElMLGen.DoTranslationEnd(var TableName : string); var ClosedTag: Boolean; j: Integer; s: string; begin FSrcPos := FSrcPos + Length(FTagPrefix) + 13{Length('</translation')}; GetTagProp(ClosedTag, FTagParameters); if ClosedTag then Raise MlGenException.Create(self, SErrorInTranslationTagDeclaration1); j := FTagParameters.FindItemByName('name'); // Position of name parameter in the array if j < 0 then Raise MlGenException.Create(self, SNameOfTranslationTagMustBeSpecified1); s := FTagParameters.FData[j].Value; if s = '' then Raise MlGenException.Create(self, SNameOfTranslationTagMustBeSpecified1); if s <> TableName then Raise MlGenException.Create(self, Format(STryingToCloseNotPreviouslyOpenedTranslationTableSS, [s, TableName])); TableName := ''; FTranslationTable := nil; end;{ TBaseElMLGen.DoTranslationEnd } {{ Starts template processing. } procedure TBaseElMLGen.Execute; var SrcLen: Integer; OldSrcPos, TagStart: Integer; i, LenTagPrefix: Integer; s: string; IfPass, CommentPass, ParamsPass, CodePass: Boolean; SavingInterval, Substitution: string; function CheckSavingInterval : boolean; var i, m : Integer; // Counters begin Result := False; // Если Substitution <> '' то пишем все как есть // 04.Sep.02 проверка выполняется перед вызовом функции // if Substitution <> '' then // exit; // проверка на наличие только пробелов в строке на которой находится макрос // ищем начало строки или символ по которому точно будет решено, что надо строку записать. m := Length(SavingInterval); i := TagStart - 1; if i <> 0 then while i >= (TagStart - m - 1) do begin case FSource[i] of #9, ' ' : ; #10, #13 : begin m := i - (TagStart - m - 1); break; end; else exit; // надо записать все. end; // case dec(i); end // while else m := 0; SavingInterval := Copy(SavingInterval, 1, m); Result := True; end; var aTagFound : boolean; j : Integer; begin FExecuting := True; try // FreeArrays; // вызывается в обработчике новой страницы FSrcPos := 0; FreeRzrvArrays; FCancelJob := False; IfPass := False; CommentPass := False; ParamsPass := False; CodePass := False; FPageCount := 0; FLoopBreak := ''; FSkipIfsDownToIndex := -1; BeforeExecute; FSource := FTemplate.Text; SrcLen := Length(FSource); LenTagPrefix := Length(FTagPrefix); try repeat ProcessMessages; if FCancelJob then exit; DoNextPage; try FSrcPos := 1; OldSrcPos := 1; while FSrcPos <= SrcLen do begin ProcessMessages; if FCancelJob then exit; TagStart := PosEx('<', FSource, SrcLen, FSrcPos); if TagStart <= 0 then begin // Макросов больше нет. Запишем конец болванки if not CommentPass then WriteString(Copy(FSource, OldSrcPos, SrcLen - OldSrcPos + 1)); break; end; FSrcPos := TagStart; i := FSrcPos + 1; s := GetWordEx(FSource, i, [' ', '>']); // Если после символа '<' идет пробел, учтем это, так как в поиске слова // пробелы были пропущены. if FSource[i] = ' ' then s := s + ' '; Substitution := ''; // SavingInterval := ''; // Смотрим, что за тэг мы нашли if (FTagPrefix = '') or (FTagPrefix = Copy(s, 1, LenTagPrefix)) then begin // Это тег, который мы должны обработать if FTagPrefix <> '' then Delete(s, 1, LenTagPrefix); // Если в конце есть закрывающий знак, то его надо исключить. j := Length(s); if (j > 0) and (s[j] = '/') then SetLength(s, j - 1); aTagFound := True; if not CommentPass then begin if not CodePass then begin if not ParamsPass then begin if FLoopBreak = '' then begin if not IfPass then begin SavingInterval := Copy(FSource, OldSrcPos, FSrcPos - OldSrcPos); if s = 'comment' then begin CommentPass := DoCommentBegin; end else if s = 'macro' then begin Substitution := DoMacroFound; // SavingInterval := SavingInterval + Substitution; end else if s = 'repeat' then begin DoRepeatBegin; end else if s = '/repeat' then begin DoRepeatDone; end else if s = 'if' then begin IfPass := not DoIfFound(True); end else if s = 'else' then begin IfPass := DoIfElse; end else if s = '/if' then begin DoIfDone; end else if s = 'params' then begin ParamsPass := DoParamsBegin; end else if s = 'code' then begin CodePass := DoCodeBegin; end else begin if DoIsTag(s) then begin // 04.Sep.02 убрано, так как эта команда вызывается ранее // SavingInterval := Copy(FSource, OldSrcPos, FSrcPos - OldSrcPos); DoTagFound(s); end else begin aTagFound := False; inc(FSrcPos); SavingInterval := Copy(FSource, OldSrcPos, FSrcPos - OldSrcPos); end; end; // проверяем, есть ли на строке с макросом еще что-нибуть кроме макроса // пропуск служебных строк if aTagFound then begin // Подстановок не было, либо была подставлена пустая строка // Проверяем строку с найденным тэгом, если строку писать не надо, переносим FSrcPos в новую позицию. if Substitution = '' then if CheckSavingInterval then CheckEndPos; end; with FTranslationTables do begin if DefaultForTemplate >= 0 then SavingInterval := Items[DefaultForTemplate].Translate(SavingInterval); end; // with if Substitution <> '' then SavingInterval := SavingInterval + Substitution; // Запишем если надо что-то записать if SavingInterval <> '' then WriteString(SavingInterval); end // if IfFound then else begin // Если найдено условие, и результат выполнения False, то пропускаем кусок текста. if s = 'if' then begin DoIfFound(False); end else if s = 'else' then begin IfPass := not DoIfElse; end else if s = '/if' then begin IfPass := not DoIfDone; end else if s = 'comment' then begin CommentPass := DoCommentBegin; end else begin inc(FSrcPos); aTagFound := False; end; // проверяем не надо ли нам пропустить перенос строк // пропуск служебных строк if aTagFound then CheckEndPos; end; // if IfFound else end else begin // !if not LoopSkip then if s = '/repeat' then begin DoRepeatSkipDone; end else if s = 'comment' then begin CommentPass := DoCommentBegin; end else begin inc(FSrcPos); aTagFound := False; end; // проверяем не надо ли нам пропустить перенос строк // пропуск служебных строк if aTagFound then CheckEndPos; end; end // if not ParametresPass else begin if s = '/params' then begin DoParamsEnd; ParamsPass := False; end else if s = 'comment' then begin CommentPass := DoCommentBegin; end else begin inc(FSrcPos); aTagFound := False; end; // проверяем не надо ли нам пропустить перенос строк // пропуск служебных строк if aTagFound then CheckEndPos; end; // !if not ParametresPass end // if not CodePass else begin if s = '/code' then begin DoCodeEnd; CodePass := False; end else if s = 'comment' then begin CommentPass := DoCommentBegin; end else begin inc(FSrcPos); aTagFound := False; end; // проверяем не надо ли нам пропустить перенос строк // пропуск служебных строк if aTagFound then CheckEndPos; end; // !if not CodePass end // if not CommentPass else begin // !if not CommentPass if s = '/comment' then begin CommentPass := not DoCommentEnd; end else begin inc(FSrcPos); aTagFound := False; end; // проверяем не надо ли нам пропустить перенос строки // пропуск служебных строк if aTagFound then CheckEndPos; end; OldSrcPos := FSrcPos; end else begin // пропуск чужих тегов inc(FSrcPos); end; end; // while // Проверяем все ли тэги были закрыты // Циклы i := Length(FLoopCounters); if i > 0 then Raise Exception.Create(Format(SErrorInTemplateDLoopsWereNotClosed, [i])); // Условия i := Length(FIfNames); if i > 0 then Raise Exception.Create(Format(SErrorInTemplateDConditionsWereNotClosed, [i])); if IfPass or CommentPass or ParamsPass then Raise Exception.Create(SErrorInTemplateNotAllTagsHaveBeenClosed); finally // wrap up PageEnd(FPageCount); end; // try/finally until not FNewPageProcessing; // Прекращаем только если не было команды на создание нового файла finally // wrap up FreeArrays; FreeRzrvArrays; end; // try/finally finally // wrap up FExecuting := False; FSource := ''; AfterExecute; end; // try/finally end;{ TBaseElMLGen.Execute } procedure TBaseElMLGen.FreeArrays; begin FLoopBeginPos := nil; FLoopCounters := nil; FLoopCountersCurrentPage := nil; FLoopNames := nil; FIfNames := nil; end;{ TBaseElMLGen.FreeArrays } procedure TBaseElMLGen.FreeRzrvArrays; begin FLoopBeginPosRzrv := nil; FLoopCountersRzrv := nil; FLoopNamesRzrv := nil; end;{ TBaseElMLGen.FreeRzrvArrays } function TBaseElMLGen.GetLoopCount: Integer; begin Result := Length(FLoopCounters); end;{ TBaseElMLGen.GetLoopCount } function TBaseElMLGen.GetLoopCounter(Index: Integer): Integer; begin if (Index < 0) or (Index >= Length(FLoopCounters)) then Raise Exception.Create(SIndexOutOfRange); Result := FLoopCounters[Index]; end;{ TBaseElMLGen.GetLoopCounter } function TBaseElMLGen.GetLoopCountersCurrentPage(Index: Integer): Integer; begin if (Index < 0) or (Index >= Length(FLoopCountersCurrentPage)) then Raise Exception.Create(SIndexOutOfRange); Result := FLoopCountersCurrentPage[Index]; end;{ TBaseElMLGen.GetLoopCountersCurrentPage } function TBaseElMLGen.GetLoopCountersCurrentPageStr(LoopName : string): Integer; var Index: Integer; begin Index := GetLoopIndex(LoopName); if (Index < 0) or (Index >= Length(FLoopCountersCurrentPage)) then Raise Exception.Create(SLoopNameIsNotFound); Result := FLoopCountersCurrentPage[Index]; end;{ TBaseElMLGen.GetLoopCountersCurrentPageStr } function TBaseElMLGen.GetLoopCounterStr(LoopName : string): Integer; var Index: Integer; begin Index := GetLoopIndex(LoopName); if (Index < 0) or (Index >= Length(FLoopCounters)) then Raise Exception.Create(SLoopNameIsNotFound); Result := FLoopCounters[Index]; end;{ TBaseElMLGen.GetLoopCounterStr } function TBaseElMLGen.GetLoopIndex(const LoopName : string): Integer; var i: Integer; begin Result := -1; for i := 0 to High(FLoopNames) do begin if FLoopNames[i] = LoopName then begin Result := i; break; end; end; // for end;{ TBaseElMLGen.GetLoopIndex } function TBaseElMLGen.GetLoopName(Index: Integer): string; begin if (Index < 0) or (Index >= Length(FLoopNames)) then Raise Exception.Create(SIndexOutOfRange); Result := FLoopNames[Index]; end;{ TBaseElMLGen.GetLoopName } {{ При вызове метода считается,что мы находимся внутри тега, и нам предстоит разобрать, что именно за параметры у этого тэга. Если параметров больше не найдено, возвращаем пустые строки. } procedure TBaseElMLGen.GetTagProp(var ClosedTag : boolean; TagOptions : TStringParameters); const AllocateBy = 10; var SrcLen: Integer; QuoutType: Integer; // 0 - не найдено, 1 - ", 2 - ' QuoutBeginPos : Integer; // позиция первой кавычки PropCount : Integer; // Кол-во найденных параметров тега EndTag : boolean; s, s1 : string; function ConvertParamValue(const Value : string) : string; var ValuePos, NewValuePos, ValueLen, j : Integer; s : string; i : byte; begin Result := ''; ValuePos := 1; ValueLen := Length(Value); j := ValueLen - 2; if ValuePos <= j then begin while ValuePos <= j do begin NewValuePos := PosEx('#', Value, ValueLen, ValuePos); if NewValuePos <= 0 then begin Result := Result + Copy(Value, ValuePos, ValueLen - ValuePos + 1); break; end; Result := Result + Copy(Value, ValuePos, NewValuePos - ValuePos); s := Copy(Value, NewValuePos, 3); s[1] := '$'; try i := StrToInt(s); Result := Result + Char(i); except s[1] := '#'; Result := Result + s; end; // try/except ValuePos := NewValuePos + 3; end; // while end else Result := Value; end; procedure AddProp(Prop, Value : string); var i : Integer; begin // Prop := AnsiLowerCase(Prop); // Value := AnsiLowerCase(Value); inc(PropCount); i := Length(TagOptions.FData); if i < PropCount then begin SetLength(TagOptions.FData, i + AllocateBy); end; TagOptions.Data[PropCount-1].ValueName := Prop; TagOptions.Data[PropCount-1].Value := ConvertParamValue(Value); end; begin QuoutBeginPos := 0; // обход предупреждения компилятора ClosedTag := False; PropCount := 0; // Кол-во найденных параметров тега TagOptions.Clear; SetLength(TagOptions.FData, AllocateBy); // резервируем немного места EndTag := False; // Признак конца тэга SrcLen := Length(FSource); if FSrcPos > SrcLen then Raise MlGenException.Create(self, SCanNotAnalyzeTag); try repeat // Пропускаем пробелы в начале while FSrcPos <= SrcLen do begin case FSource[FSrcPos] of #9, ' ', #13, #10 : inc(FSrcPos); else break; end; // case end; if FSrcPos > SrcLen then Raise MlGenException.Create(self, SCanNotAnalyzeTag); // Выделяем название параметра s := ''; while FSrcPos <= SrcLen do begin case FSource[FSrcPos] of #10, #13 : begin FSrcPos := GetPosOfNewString(FSource, FSrcPos) - 1; if FSrcPos <=0 then // Если так, то начала следующей строки не найдено FSrcPos := SrcLen; break; end; #9, ' ', '=' : break; '>' : begin inc(FSrcPos); EndTag := True; break; end; '<', '"' : Raise MlGenException.Create(self, SCanNotAnalyzeTag); '/' : begin if (FSrcPos = SrcLen) or (FSource[FSrcPos + 1] <> '>') then Raise MlGenException.Create(self, SCanNotAnalyzeTag); ClosedTag := True; EndTag := True; inc(FSrcPos, 2); break; end; else s := s + FSource[FSrcPos] end; // case inc(FSrcPos); end; if (FSrcPos > SrcLen) or ((s = '') and (not EndTag)) then Raise MlGenException.Create(self, SCanNotAnalyzeTag); if EndTag then begin if s <> '' then begin // Тэг закончился, а в конце был параметр без значения AddProp(s, ''); end; break; end; // Проверяем знак = if FSource[FSrcPos] <> '=' then begin // В данном параметре нет значений AddProp(s, ''); continue; end; inc(FSrcPos); // Выделяем значение параметра if FSource[FSrcPos] = '"' then QuoutType := 1 else if FSource[FSrcPos] = #39 then QuoutType := 2 else QuoutType := 0; if QuoutType > 0 then begin QuoutBeginPos := FSrcPos; inc(FSrcPos); end; s1 := ''; while FSrcPos <= SrcLen do begin case FSource[FSrcPos] of #10, #13 : begin if QuoutType > 0 then begin // Если перевод строки идет сразу после открытия кавычек, игнориуем его if FSrcPos <> (QuoutBeginPos+1) then s1 := s1 + ' '; end else break; FSrcPos := GetPosOfNewString(FSource, FSrcPos) - 1; if FSrcPos < 0 then // Если так, то начала следующей строки не найдено FSrcPos := SrcLen; end; #9, ' ' : if QuoutType > 0 then s1 := s1 + FSource[FSrcPos] else break; '>' : if QuoutType > 0 then s1 := s1 + FSource[FSrcPos] else begin EndTag := True; break; end; '"' : case QuoutType of 0: Raise MlGenException.Create(self, SCanNotAnalyzeTag); 1: break; 2: s1 := s1 + FSource[FSrcPos]; end; // case #39 : case QuoutType of 0: Raise MlGenException.Create(self, SCanNotAnalyzeTag); 1: s1 := s1 + FSource[FSrcPos]; 2: break; end; // case '/' : if QuoutType > 0 then s1 := s1 + FSource[FSrcPos] else begin if (FSrcPos = SrcLen) or (FSource[FSrcPos + 1] <> '>') then Raise MlGenException.Create(self, SCanNotAnalyzeTag); ClosedTag := True; EndTag := True; inc(FSrcPos, 2); break; end; else s1 := s1 + FSource[FSrcPos]; end; // case inc(FSrcPos); end; inc(FSrcPos); AddProp(s, s1); until EndTag; finally // wrap up SetLength(TagOptions.FData, PropCount); end; // try/finally end;{ TBaseElMLGen.GetTagProp } procedure TBaseElMLGen.IsTag(TagName : string; var IsTag : boolean); begin IsTag := FCustomTagNames.IndexOf(TagName) >=0; end;{ TBaseElMLGen.IsTag } procedure TBaseElMLGen.LoopBreak(LoopName : string); var i: Integer; begin i := GetLoopIndex(LoopName); if i < 0 then Raise Exception.Create(SAttemptToCloseTheLoopThatHasNotBeenOpenedBefore); FLoopBreak := LoopName; end;{ TBaseElMLGen.LoopBreak } procedure TBaseElMLGen.LoopContinue(LoopName : string); begin end;{ TBaseElMLGen.LoopContinue } procedure TBaseElMLGen.NextPage; var i, j: Integer; begin if FNewPageProcessing or FEnteringInNextPage then Raise Exception.Create(SRepeatedRequestForNewPageIsNotAllowed); FNewPageProcessing := True; j := Length(FLoopBeginPos); SetLength(FLoopBeginPosRzrv, j); for i := 0 to j-1 do FLoopBeginPosRzrv[i] := FLoopBeginPos[i]; j := Length(FLoopCounters); SetLength(FLoopCountersRzrv, j); for i := 0 to j-1 do FLoopCountersRzrv[i] := FLoopCounters[i]; j := Length(FLoopNames); SetLength(FLoopNamesRzrv, j); for i := 0 to j-1 do FLoopNamesRzrv[i] := FLoopNames[i]; end;{ TBaseElMLGen.NextPage } {$ifdef ELMLGEN_ACTIVEX} procedure TBaseElMLGen.Paint; begin Canvas.Brush.Color := clBtnFace; Canvas.FillRect(ClientRect); Canvas.BrushCopy(ClientRect, FIcon, Rect(0, 0, 24, 24), clFuchsia); end;{ TBaseElMLGen.Paint } {$endif} procedure TBaseElMLGen.PrepareTemplate; var SrcLen: Integer; OldSrcPos, TagStart: Integer; i, LenTagPrefix: Integer; s: string; CommentPass: Boolean; ParamsFound, CodeFound: Boolean; ParamName, TranslationTableName, ReplaceString: string; ParamNumb, ReplaceStringNumb: Integer; SavingInterval, CodeText: string; {$ifdef ELDEMO} FSource1 : array [0..DEMO_BUFFER_SIZE] of char; {$endif ELDEMO} begin FExecuting := True; try FParameters.Clear; FTranslationTables.Clear; FCode.Clear; CommentPass := False; ParamsFound := False; CodeFound := False; ParamName := ''; TranslationTableName := ''; ReplaceString := ''; CodeText := ''; {$ifdef ELDEMO} SrcLen := Length(FTemplate.Text); Move(FTemplate.Text[1], FSource1, SrcLen); SetLength(FSource, SrcLen); Move(FSource1, FSource[1], SrcLen); {$else ELDEMO} FSource := FTemplate.Text; SrcLen := Length(FSource); {$endif ELDEMO} LenTagPrefix := Length(FTagPrefix); FSrcPos := 1; OldSrcPos := 1; while FSrcPos <= SrcLen do begin TagStart := PosEx('<', FSource, SrcLen, FSrcPos); if TagStart <= 0 then begin break; end; FSrcPos := TagStart; i := FSrcPos + 1; s := GetWordEx(FSource, i, [' ', '>']); // Если после символа '<' идет пробел, учтем это, так как в поиске слова // пробелы были пропущены. if FSource[i] = ' ' then s := s + ' '; // Смотрим, что за тэг мы нашли if (FTagPrefix = '') or (FTagPrefix = Copy(s, 1, LenTagPrefix)) then begin // Это тег, который мы должны обработать if FTagPrefix <> '' then Delete(s, 1, LenTagPrefix); if not CommentPass then begin if s = 'comment' then begin CommentPass := DoCommentBegin; end else begin if ParamsFound then begin // Обработчик содержимого между тегами params /params if TranslationTableName = '' then begin if ParamName = '' then begin if s = '/params' then begin ParamsFound := False; DoParamsEnd; end else if s = 'translation' then begin DoTranslationBegin(TranslationTableName); end else if s = 'param' then begin DoParamBegin(ParamName, ParamNumb); CheckEndPos; end else inc(FSrcPos); end // if not ParamFound else begin if s = '/param' then begin SavingInterval := Copy(FSource, OldSrcPos, FSrcPos - OldSrcPos); ParamName := ''; DoParamEnd; CheckEndPos; end else begin inc(FSrcPos); SavingInterval := Copy(FSource, OldSrcPos, FSrcPos - OldSrcPos); end; with FParameters.FData[ParamNumb] do Value := Value + SavingInterval; end; // !if not ParamFound end else begin // Обработчик содержимого между тегами translation /translation if ReplaceString = '' then begin if s = '/translation' then begin DoTranslationEnd(TranslationTableName); end else if s = 'replace' then begin DoReplaceBegin(ReplaceString, ReplaceStringNumb); CheckEndPos; end else inc(FSrcPos); end // if not ReplaceFound else begin if s = '/replace' then begin SavingInterval := Copy(FSource, OldSrcPos, FSrcPos - OldSrcPos); ReplaceString := ''; DoReplaceEnd; CheckEndPos; end else begin inc(FSrcPos); SavingInterval := Copy(FSource, OldSrcPos, FSrcPos - OldSrcPos); end; with FTranslationTable.Table.FData[ReplaceStringNumb] do Value := Value + SavingInterval; end; // !if not ReplaceFound end; end else begin if CodeFound then begin if s = '/code' then begin SavingInterval := Copy(FSource, OldSrcPos, FSrcPos - OldSrcPos); CodeFound := False; DoCodeEnd; CheckEndPos; end else begin inc(FSrcPos); SavingInterval := Copy(FSource, OldSrcPos, FSrcPos - OldSrcPos); end; CodeText := CodeText + SavingInterval; end // if CodeFound else begin // обработчик в момент поиска секции с параметрами или скриптом if s = 'params' then begin ParamsFound := DoParamsBegin; end else if s = 'code' then begin CodeFound := DoCodeBegin; // if CodeFound and (CodeText <> '') then // CodeText := CodeText + #13#10; CheckEndPos; end else inc(FSrcPos); end; // !if CodeFound end; // !if ParamsFound end; // !if s = 'comment' end // if not CommentPass else begin // !if not CommentPass if s = '/comment' then begin CommentPass := not DoCommentEnd; end else begin inc(FSrcPos); end; end; OldSrcPos := FSrcPos; end else begin // пропуск чужих тегов inc(FSrcPos); end; end; // while if ParamsFound or (TranslationTableName <> '') or (ParamName <> '') or (ReplaceString <> '') then Raise Exception.Create(SErrorInTemplateParamsDeclaration); FCode.Text := CodeText; finally // wrap up FExecuting := False; FSource := ''; end; // try/finally end;{ TBaseElMLGen.PrepareTemplate } procedure TBaseElMLGen.ProcessMessages; begin end;{ TBaseElMLGen.ProcessMessages } {$ifdef ELMLGEN_ACTIVEX} procedure TBaseElMLGen.Resize; begin inherited; SetBounds(Left, Top, 24, 24); end;{ TBaseElMLGen.Resize } {$endif} procedure TBaseElMLGen.SetCustomTagNames(Value: TStrings); begin FCustomTagNames.Assign(Value); end;{ TBaseElMLGen.SetCustomTagNames } procedure TBaseElMLGen.SetTagPrefix(const Value: string); var i: Integer; begin if FTagPrefix <> Value then begin // Проверим корректность префикса for i := 1 to Length(Value) do begin if Value[i] in [#0..' ', '"', #39, '<', '>', '/'] then Raise Exception.Create(Format(SInvalidCharDSInTagPrefixString, [i, Value[i]])); end; // for FTagPrefix := Value; end; end;{ TBaseElMLGen.SetTagPrefix } procedure TBaseElMLGen.SetTemplate(Value: TStrings); begin FTemplate.Assign(Value); end;{ TBaseElMLGen.SetTemplate } procedure TBaseElMLGen.TagFound(Tag : string; const TagClosed : boolean; TagParameters : TStringParameters); begin end;{ TBaseElMLGen.TagFound } procedure TBaseElMLGen.TemplateChanged(Sender: TObject); {$ifdef ELDEMO} var i : integer; {$endif ELDEMO} begin if FExecuting then Raise Exception.Create(SCanTChangeTemplateDuringExecution); {$ifdef ELDEMO} {$O-} i := DEMO_BUFFER_SIZE2; if Length(FTemplate.Text) >= i xor $0FF0 then Raise Exception.Create('This is a demo version of EldoS MLGen.'#13#10'Visit http://www.eldos.org/elmlgen/elmlgen.html to register your version.'); //** demo text {$O+} {$endif ELDEMO} PrepareTemplate; end;{ TBaseElMLGen.TemplateChanged } { ******************************** TCustomElMLGen ******************************** } procedure TCustomElMLGen.AfterExecute; begin if Assigned(FOnAfterExecute) then FOnAfterExecute(self); end;{ TCustomElMLGen.AfterExecute } procedure TCustomElMLGen.BeforeExecute; begin if Assigned(FOnBeforeExecute) then FOnBeforeExecute(self); end;{ TCustomElMLGen.BeforeExecute } procedure TCustomElMLGen.IfFound(IfName : string; TagParameters : TStringParameters; var ResultValue : boolean); begin if Assigned(FOnIfFound) then FOnIfFound(self, IfName, TagParameters, ResultValue); end;{ TCustomElMLGen.IfFound } procedure TCustomElMLGen.IsTag(TagName : string; var IsTag : boolean); begin inherited IsTag(TagName, IsTag); if Assigned(FOnIsTag) then FOnIsTag(Self, TagName, IsTag); end;{ TCustomElMLGen.IsTag } procedure TCustomElMLGen.LoopIteration(LoopNumb: integer; LoopName: string; TagParameters : TStringParameters; var LoopDone : boolean); begin if Assigned(FOnLoopIteration) then FOnLoopIteration(self, LoopNumb, LoopName, TagParameters, LoopDone); end;{ TCustomElMLGen.LoopIteration } procedure TCustomElMLGen.MacroFound(MacroName : string; TagParameters : TStringParameters; var MacroResult : string; var UseTranslationTable : boolean); begin if Assigned(FOnMacroFound) then FOnMacroFound(self, MacroName, TagParameters, MacroResult, UseTranslationTable) end;{ TCustomElMLGen.MacroFound } procedure TCustomElMLGen.PageBegin(PageNumb : integer); begin if Assigned(FOnPageBegin) then FOnPageBegin(self, PageNumb); end;{ TCustomElMLGen.PageBegin } procedure TCustomElMLGen.PageEnd(PageNumb : integer); begin if Assigned(FOnPageEnd) then FOnPageEnd(self, PageNumb); end;{ TCustomElMLGen.PageEnd } procedure TCustomElMLGen.ProcessMessages; begin if Assigned(FOnProcessMessages) then FOnProcessMessages(self); end;{ TCustomElMLGen.ProcessMessages } procedure TCustomElMLGen.TagFound(Tag : string; const TagClosed : boolean; TagParameters : TStringParameters); begin if Assigned(FOnTagFound) then FOnTagFound(self, Tag, TagClosed, TagParameters); end;{ TCustomElMLGen.TagFound } procedure TCustomElMLGen.WriteString(Value : string); begin if Assigned(FOnWriteString) then FOnWriteString(self, Value); end;{ TCustomElMLGen.WriteString } { ******************************** MlGenException ******************************** } constructor MlGenException.Create(MlGen : TBaseElMlGen; Msg: string); var i, j, k: Integer; begin inherited Create(Msg); FMlGen := MlGen; i := Length(Msg); if i > 0 then begin if Msg[i] <> '.' then Msg := Msg + '.'; end else Msg := SError; GetTextLineByStringPos(MlGen.FSource, MlGen.FSrcPos, j, k); inherited Create(Format(SLineChar, [Msg, j, k])); end;{ MlGenException.Create } end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, StdCtrls, XPMan; type TMainForm = class(TForm) AllEmploeersStringGrid: TStringGrid; AddEmploeeStringGrid: TStringGrid; FindedEmpoeers: TStringGrid; ButtonAddEmploee: TButton; ButtonSaveChanges: TButton; XPStyle: TXPManifest; ButtonFindPensioners: TButton; ButtonLoadEmploeersFromFile: TButton; LabelAllEmploeers: TLabel; LabelAddEmploee: TLabel; EditDepartament: TEdit; LabelDepartment: TLabel; EditMiddleAgeOfWork: TEdit; LabelMiddleAgeOfWork: TLabel; ButtonFindMiddleAgeOfWork: TButton; ButtonSaveEmploeersInFile: TButton; EditDelEmploee: TEdit; LabelDeleteEmploee: TLabel; ButtonDeleteEmploee: TButton; LabelDelEmploeeName: TLabel; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; procedure FormCreate(Sender: TObject); procedure ButtonAddEmploeeClick(Sender: TObject); procedure ButtonFindPensionersClick(Sender: TObject); procedure ButtonFindMiddleAgeOfWorkClick(Sender: TObject); procedure ButtonSaveChangesClick(Sender: TObject); procedure ButtonDeleteEmploeeClick(Sender: TObject); procedure ButtonLoadEmploeersFromFileClick(Sender: TObject); procedure ButtonSaveEmploeersInFileClick(Sender: TObject); private { Private declarations } public { Public declarations } end; Employee = Record Name: String; Department: String; YearOfBorn: Integer; LengthOfWork: Byte; JobTitle: String; Salary: Integer; end; TEmploee = Array of Employee; var MainForm: TMainForm; Employers: TEmploee; implementation {$R *.dfm} procedure AddNewEmploee(SG: TStringGrid; Line, NumberOfEmploee: Integer); var i: Byte; begin if NumberOfEmploee = -1 then begin i := Length(Employers); SetLength(Employers, i + 1); end else i := NumberOfEmploee; Employers[i].Name := SG.Cells[0, Line]; Employers[i].Department := SG.Cells[1, Line]; Employers[i].YearOfBorn := StrToInt(SG.Cells[2, Line]); Employers[i].LengthOfWork := StrToInt(SG.Cells[3, Line]); Employers[i].JobTitle := SG.Cells[4, Line]; Employers[i].Salary := StrToInt(SG.Cells[5, Line]); end; procedure CleanGrid(SG: TStringGrid); var i: Byte; begin for i := 1 to SG.RowCount - 1 do SG.Rows[i].Text := ''; SG.RowCount := 2; end; procedure PrintEmploee(SG: TStringGrid; NumberEmploee: Byte); var Line: Byte; begin Line := SG.RowCount - 1; SG.RowCount := SG.RowCount + 1; SG.Cells[0, Line] := Employers[NumberEmploee].Name; SG.Cells[1, Line] := Employers[NumberEmploee].Department; SG.Cells[2, Line] := IntToStr(Employers[NumberEmploee].YearOfBorn); SG.Cells[3, Line] := IntToStr(Employers[NumberEmploee].LengthOfWork); SG.Cells[4, Line] := Employers[NumberEmploee].JobTitle; SG.Cells[5, Line] := IntToStr(Employers[NumberEmploee].Salary); end; procedure PrintAllEmploeers(SG: TStringGrid); var NumberEmploee: Byte; begin CleanGrid(SG); for NumberEmploee := 0 to length(Employers) - 1 do PrintEmploee(SG, NumberEmploee); SG.RowCount := SG.RowCount - 1; end; procedure FillingGrid(CurrentGrid: TStringGrid); begin CurrentGrid.Cols[0].Text := 'Фамилия' ; CurrentGrid.Cols[1].Text := 'Отдел'; CurrentGrid.Cols[2].Text := 'Год рожд.'; CurrentGrid.Cols[3].Text := 'Стаж'; CurrentGrid.Cols[4].Text := 'Должность'; CurrentGrid.Cols[5].Text := 'Оклад'; end; function CheckNumericData(NumData: String; TypeOfData: Byte): Boolean; var TestInteger: Integer; IsDateCorrect: Boolean; LowerAllowableValue, HigherAllowableValue: Integer; ErrorText: String; begin case TypeOfData of 1 : begin LowerAllowableValue := 1920; HigherAllowableValue := 2000; ErrorText := 'Введите корректный год рождения'; end; 2 : begin LowerAllowableValue := 0; HigherAllowableValue := 80; ErrorText := 'Введите корректный стаж'; end; 3 : begin LowerAllowableValue := 100; HigherAllowableValue := 2000000; ErrorText := 'Введите корректный оклад'; end; end; IsDateCorrect := True; if TryStrToInt(NumData, TestInteger) then begin if ((TestInteger) > HigherAllowableValue) or ((TestInteger) < LowerAllowableValue) then begin ShowMessage('Мне кажется, что таких людей не существует'); IsDateCorrect := False; end; end else begin ShowMessage('Необходимо корректно заполнить поля'); IsDateCorrect := False; end; CheckNumericData := IsDateCorrect; end; function GetEmploeeId(EmploeeName: String): Integer; var i: Integer; ID: Integer; begin ID := -1; for i := 0 to Length(Employers) - 1 do if Employers[i].Name = EmploeeName then ID := i; GetEmploeeId := ID; end; procedure FindOldEmploeers; var CurrentEmploee: Integer; begin CleanGrid(MainForm.FindedEmpoeers); for CurrentEmploee := 0 to Length(Employers) - 1 do if Employers[CurrentEmploee].YearOfBorn < 1960 then PrintEmploee(MainForm.FindedEmpoeers, CurrentEmploee); MainForm.FindedEmpoeers.RowCount := MainForm.FindedEmpoeers.RowCount - 1; end; function CheckGrid(SG: TStringGrid; Line: Byte): Boolean; var i: Byte; IsGridCorrect: Boolean; YearOfBorn, LengthOfWork: Integer; begin IsGridCorrect := True; i := 0; while (i < 6) and (IsGridCorrect) do begin if Length(SG.Cells[i, Line]) = 0 then begin IsGridCorrect := False; ShowMessage('Пустые поля недопустимы'); end; Inc(i); end; //check correct input data if not (CheckNumericData(SG.Cells[2, Line], 1)) then IsGridCorrect := False; if not (CheckNumericData(SG.Cells[3, Line], 2)) then IsGridCorrect := False; if not (CheckNumericData(SG.Cells[5, Line], 3)) then IsGridCorrect := False; //check collision if IsGridCorrect then begin YearOfBorn := StrToInt(SG.Cells[2, Line]); LengthOfWork := StrToInt(SG.Cells[3, Line]); if (YearOfBorn + LengthOfWork) > 2003 then begin ShowMessage('Вы серьёзно думаете, что этот человек может иметь такой стаж?)'); IsGridCorrect := False; end; end; CheckGrid := IsGridCorrect; end; function CheckDepartmentExists(FindingDepartment: String): Boolean; var i: Byte; IsDepartmentExists: Boolean; begin IsDepartmentExists := False; for i := 0 to Length(Employers) - 1 do if Employers[i].Department = FindingDepartment then IsDepartmentExists := True; CheckDepartmentExists := IsDepartmentExists; end; procedure ReadEmploeersFromGrid(SG: TStringGrid); var i: Integer; begin for i := 1 to SG.RowCount - 1 do if CheckGrid(SG, i) then AddNewEmploee(SG, i, i - 1); end; procedure FindMiddleAgeOfWork(FindingDepartment: String; var EditAnswer: TEdit); var EmploeersQt, SumAgeOfWork: Integer; i: Byte; MiddleAgeOfWork: Double; AnswerString: String; begin EmploeersQt := 0; SumAgeOfWork := 0; for i := 0 to Length(Employers) - 1 do if Employers[i].Department = FindingDepartment then begin Inc(EmploeersQt); Inc(SumAgeOfWork, Employers[i].LengthOfWork); end; MiddleAgeOfWork := SumAgeOfWork / EmploeersQt; AnswerString := Format('%n', [MiddleAgeOfWork]); if AnswerString[length(AnswerString) - 1] = '0' then Delete(AnswerString, length(AnswerString) - 2, 3); EditAnswer.Text := AnswerString; end; procedure DeleteEmploee(EmploeeName: String); var CurrentEmploee: Integer; LastEmploee: Integer; begin CurrentEmploee := GetEmploeeId(EmploeeName); LastEmploee := Length(Employers) - 1; if (CurrentEmploee <> -1) then begin Employers[CurrentEmploee] := Employers[LastEmploee]; SetLength(Employers, LastEmploee); end else ShowMessage('Удаляемый работник не найден'); end; function ReadFromFile(FileName: String): Boolean; var InputFile: Text; i: Integer; InputArray: TEmploee; IsCorrectValue : boolean ; YearB, LengthW, Salary: String; begin Assign(InputFile, FileName); Reset(InputFile); i := -1; IsCorrectValue := true ; {$I-} while ((not EOf(InputFile)) and (IsCorrectValue))do begin Inc(i); SetLength(InputArray, i + 1); ReadLn(InputFile, InputArray[i].Name); ReadLn(InputFile, InputArray[i].Department); ReadLn(InputFile, YearB); ReadLn(InputFile, LengthW); ReadLn(InputFile, InputArray[i].JobTitle); ReadLn(InputFile, Salary); ReadLn(InputFile); if CheckNumericData(YearB, 1) and CheckNumericData(LengthW, 2) and CheckNumericData(Salary, 3) then begin InputArray[i].YearOfBorn := StrToInt(YearB); InputArray[i].LengthOfWork := StrToInt(LengthW); InputArray[i].Salary := StrToInt(Salary); end else IsCorrectValue := False ; end; CloseFile(InputFile); if IsCorrectValue then Employers := InputArray; ReadFromFile := IsCorrectValue; end; procedure PrintIntoFile(FileName: String); var i, j: Byte; OutputFile: Text; OutputNumber: String; begin AssignFile(OutputFile, FileName); Rewrite(OutputFile); for i := 0 to length(Employers) - 1 do begin WriteLn(OutputFile, Employers[i].Name); WriteLn(OutputFile, Employers[i].Department); WriteLn(OutputFile, Employers[i].YearOfBorn ); WriteLn(OutputFile, Employers[i].LengthOfWork); WriteLn(OutputFile, Employers[i].JobTitle); WriteLn(OutputFile, Employers[i].Salary); WriteLn(OutputFile); end; Close(OutputFile); end; procedure TMainForm.ButtonAddEmploeeClick(Sender: TObject); begin if CheckGrid(AddEmploeeStringGrid, 1) then begin if GetEmploeeID(AddEmploeeStringGrid.Cells[0, 1]) = -1 then begin AddNewEmploee(AddEmploeeStringGrid, 1, -1); PrintAllEmploeers(AllEmploeersStringGrid); end else ShowMessage('Работник с таким именем уже записан'); end; end; procedure TMainForm.ButtonFindPensionersClick(Sender: TObject); begin if (Length(Employers) <> 0) then FindOldEmploeers else ShowMessage('В компании нет ни одного сотрудника'); end; procedure TMainForm.FormCreate(Sender: TObject); begin FillingGrid(AllEmploeersStringGrid); FillingGrid(AddEmploeeStringGrid); FillingGrid(FindedEmpoeers); end; procedure TMainForm.ButtonFindMiddleAgeOfWorkClick(Sender: TObject); begin if (Length(Employers) <> 0) and CheckDepartmentExists(EditDepartament.Text) then FindMiddleAgeOfWork(EditDepartament.Text, EditMiddleAgeOfWork) else ShowMessage('Такого отдела не существует.'); end; procedure TMainForm.ButtonSaveChangesClick(Sender: TObject); begin if Length(Employers) <> 0 then ReadEmploeersFromGrid(AllEmploeersStringGrid) else ShowMessage('Мы не можем изменять, так как нет ни одного сотрудника'); end; procedure TMainForm.ButtonDeleteEmploeeClick(Sender: TObject); begin if Length(Employers) <> 0 then begin DeleteEmploee(EditDelEmploee.Text); if Length(Employers) <> 0 then PrintAllEmploeers(AllEmploeersStringGrid) else CleanGrid(AllEmploeersStringGrid); end else ShowMessage('Некого удалять. Работников нет.'); end; procedure TMainForm.ButtonLoadEmploeersFromFileClick(Sender: TObject); begin OpenDialog.Filter := 'Text Files only |*.txt' ; if OpenDialog.Execute then if ReadFromFile(OpenDialog.FileName) then begin ShowMessage('Загрузка из файла прошла успешно'); PrintAllEmploeers(AllEmploeersStringGrid); end else ShowMessage('Загрузка из файла прошла неудачно'); end; procedure TMainForm.ButtonSaveEmploeersInFileClick(Sender: TObject); begin if Length(Employers) <> 0 then begin SaveDialog.Filter := 'Text Files only |*.txt' ; if SaveDialog.Execute then begin PrintIntoFile(SaveDialog.FileName); ShowMEssage('Запись в файл прошла успешно'); end; end else ShowMEssage('ЭЭЭНЕЕТ. Пустой файл мы сейвить не будем'); end; end.
unit udmPlanoContas; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmPlanoContas = class(TdmPadrao) qryManutencaoCODIGO: TStringField; qryManutencaoDESCRICAO: TStringField; qryManutencaoDC: TStringField; qryManutencaoGRUPO: TStringField; qryManutencaoSUB_GRUPO: TStringField; qryManutencaoCONTA: TStringField; qryManutencaoSUB_CONTA: TStringField; qryManutencaoANALITICO: TStringField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryManutencaoCODIGO_EXT: TFloatField; qryManutencaoCOD_ACESSO: TFloatField; qryLocalizacaoCODIGO: TStringField; qryLocalizacaoDESCRICAO: TStringField; qryLocalizacaoDC: TStringField; qryLocalizacaoGRUPO: TStringField; qryLocalizacaoSUB_GRUPO: TStringField; qryLocalizacaoCONTA: TStringField; qryLocalizacaoSUB_CONTA: TStringField; qryLocalizacaoANALITICO: TStringField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoCODIGO_EXT: TFloatField; qryLocalizacaoCOD_ACESSO: TFloatField; private fCodigo: string; procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; public property Nro_Conta: string read fCodigo write fCodigo; end; var dmPlanoContas: TdmPlanoContas; implementation {$R *.dfm} { TdmPlanoContas } procedure TdmPlanoContas.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add('SELECT * FROM STWCPGTPCON'); SQL.Add('WHERE CODIGO = :CODIGO'); SQL.Add('ORDER BY CODIGO'); ParamByName('CODIGO').AsString := fCodigo; end; end; procedure TdmPlanoContas.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add('SELECT * FROM STWCPGTPCON'); SQL.Add('ORDER BY CODIGO'); end; end; end.
program TesteSortiereListe(input, output); type tNatZahl = 0..maxint; tRefListe = ^tListe; tListe = record info : tNatZahl; next : tRefListe; end; var RefListe : tRefListe; procedure RemoveFromFront (var ioListe, iofirstElement : tRefListe); { Entfernt das erste Element und korrigiert den Listenanfang. Das entfernte Element wird in firstElement zurückgeliefrt } begin iofirstElement := ioListe; ioListe := ioListe^.next; iofirstElement^.next := nil; end; procedure InsertSorted (var ioListe : tRefListe; item :tRefListe); { Element 'item' sortiert in Liste einfügen } var iterator : tRefListe; { Iteration über die Liste } last : tRefListe; { "Schlepp" - Zeiger, zeigt auf das Element aus der letzen Iteration } begin iterator := ioListe; last := nil; while ( iterator <> nil) and ( item^.info > iterator^.info ) do begin last := iterator; iterator := iterator^.next; end; if iterator = ioListe then begin item^.next := ioListe; ioListe := item; end else begin item^.next := iterator; last^.next := item; end; end; procedure SortiereListe (var ioListe: tRefListe); { sortiert eine lineare Liste aufsteigend } var sorted, unsorted, element : tRefListe; begin if (ioListe <> nil) and (ioListe^.next <> nil) then begin sorted := ioListe; unsorted := ioListe^.next; element := nil; sorted^.next := nil; while unsorted <> nil do begin RemoveFromFront (unsorted, element); InsertSorted (sorted, element); end; ioListe := sorted; end; end; procedure Anhaengen(var ioListe : tRefListe; inZahl : tNatZahl); { Haengt inZahl an ioListe an } var Zeiger : tRefListe; begin Zeiger := ioListe; if Zeiger = nil then begin new(ioListe); ioListe^.info := inZahl; ioListe^.next := nil; end else begin while Zeiger^.next <> nil do Zeiger := Zeiger^.next; { Jetzt zeigt Zeiger auf das letzte Element } new(Zeiger^.next); Zeiger := Zeiger^.next; Zeiger^.info := inZahl; Zeiger^.next := nil; end; end; procedure ListeEinlesen(var outListe:tRefListe); { liest eine durch Leerzeile abgeschlossene Folge von Integer- Zahlen ein und speichert diese in der linearen Liste RefListe. } var Liste : tRefListe; Zeile : string; Zahl, Code : integer; begin writeln('Bitte geben Sie die zu sortierenden Zahlen ein.'); writeln('Beenden Sie Ihre Eingabe mit einer Leerzeile.'); Liste := nil; readln(Zeile); val(Zeile, Zahl, Code); { val konvertiert String nach Integer } while Code=0 do begin Anhaengen(Liste, Zahl); readln(Zeile); val(Zeile, Zahl, Code); end; { while } outListe := Liste; end; { ListeEinlesen } procedure GibListeAus(inListe : tRefListe); { Gibt die Elemente von inListe aus } var Zeiger : tRefListe; begin Zeiger := inListe; while Zeiger <> nil do begin writeln(Zeiger^.info); Zeiger := Zeiger^.next; end; { while } end; { GibListeAus } begin ListeEinlesen(RefListe); SortiereListe(RefListe); GibListeAus(RefListe) end.
unit cEnemyStatistics; interface uses contnrs; type TEnemyStatistic = class private _PWeaponDamage : Byte; _CWeaponDamage : Byte; _IWeaponDamage : Byte; _BWeaponDamage : Byte; _FWeaponDamage : Byte; _EWeaponDamage : Byte; _GWeaponDamage : Byte; _PlayerDamage : Byte; _Score : Byte; public property PWeaponDamage : Byte read _PWeaponDamage write _PWeaponDamage; property CWeaponDamage : Byte read _CWeaponDamage write _CWeaponDamage; property IWeaponDamage : Byte read _IWeaponDamage write _IWeaponDamage; property BWeaponDamage : Byte read _BWeaponDamage write _BWeaponDamage; property FWeaponDamage : Byte read _FWeaponDamage write _FWeaponDamage; property EWeaponDamage : Byte read _EWeaponDamage write _EWeaponDamage; property GWeaponDamage : Byte read _GWeaponDamage write _GWeaponDamage; property PlayerDamage : Byte read _PlayerDamage write _PlayerDamage; property Score : Byte read _Score write _Score; end; TEnemyStatisticList = class(TObjectList) protected function GetItem(Index: Integer) : TEnemyStatistic; procedure SetItem(Index: Integer; const Value: TEnemyStatistic); public function Add(AObject: TEnemyStatistic) : Integer; property Items[Index: Integer] : TEnemyStatistic read GetItem write SetItem;default; function Last : TEnemyStatistic; end; implementation { TEnemyStatisticList } function TEnemyStatisticList.Add(AObject: TEnemyStatistic): Integer; begin Result := inherited Add(AObject); end; function TEnemyStatisticList.GetItem(Index: Integer): TEnemyStatistic; begin Result := TEnemyStatistic(inherited Items[Index]); end; procedure TEnemyStatisticList.SetItem(Index: Integer; const Value: TEnemyStatistic); begin inherited Items[Index] := Value; end; function TEnemyStatisticList.Last : TEnemyStatistic; begin result := TEnemyStatistic(inherited Last); end; end.
unit SelectionSort; interface uses StrategyInterface, ArraySubroutines; type TSelectionsort = class(TInterfacedObject, ISorter) procedure Sort(var A: Array of Integer); destructor Destroy; override; end; implementation procedure TSelectionsort.Sort(var A : array of Integer); var CurIndex, Minimum, ToSwap, i: Integer; begin for CurIndex := Low(A) to High(A) do begin Minimum := A[CurIndex]; ToSwap := CurIndex; for i := CurIndex + 1 to High(A) do begin if A[i] < Minimum then begin Minimum := A[i]; ToSwap := i; end; end; Swap(A[CurIndex], A[ToSwap]); end; end; destructor TSelectionSort.Destroy; begin WriteLn('Selection sort destr'); inherited; end; end.
unit MVC_Blog.Controller.Conexao; interface uses MVC_Blog.Model.Conexao; type iController = interface ['{98311B51-7289-4FDB-8221-2AF54B789AF3}'] function Entidades : iModelEntidadeFactory; end; Type TController = class(TInterfacedObject, iController) private FModelEntidades : iModelEntidadeFactory; public constructor Create; destructor Destroy; override; class function New : iController; function Entidades : iModelEntidadeFactory; end; implementation { TController } constructor TController.Create; begin FModelEntidades := TModelEntidadesFactory.New; end; destructor TController.Destroy; begin inherited; end; function TController.Entidades: iModelEntidadeFactory; begin Result := FModelEntidades; end; class function TController.New: iController; begin Result := Self.Create; end; end.
unit UpgradeTo104; // Изменение значений полей ShortName и FullName таблицы FILE по след. алгоритму: // если поле содержит подстроку "(снято с контроля)", то тогда // эта самая подстрока должна быть отрезана. { $Id: UpgradeTo104.pas,v 1.9 2015/02/10 08:04:16 fireton Exp $ } // $Log: UpgradeTo104.pas,v $ // Revision 1.9 2015/02/10 08:04:16 fireton // - исправляем несобирающееся // // Revision 1.8 2011/12/12 14:02:52 fireton // - DbReformer и DbInfo переехали в DT // // Revision 1.7 2007/12/03 14:00:54 fireton // - отвязываем updater от имен таблиц dt_const и проводим профилактику подобных злоупотреблений // // Revision 1.6 2007/08/14 14:31:48 lulin // - оптимизируем перемещение блоков памяти. // // Revision 1.5 2004/05/25 15:41:49 step // new: classes TDocBaseUpgrade, TAdminBaseUpgrade // // Revision 1.4 2004/05/07 17:37:48 step // куча мелких исправлений // // Revision 1.3 2004/03/23 14:05:51 step // bug fix // // Revision 1.2 2004/03/10 14:34:05 step // поиск подстроки БЕЗ учета регистра // // Revision 1.1 2004/03/09 18:40:03 step // добавлен update № 104 (изменение полей табл. FILE) // interface uses DbUpgrade; type TUpgradeTo104 = class(TDocBaseUpgrade) protected procedure ModifyBd; override; procedure InitRestorableTableList; override; public class function PrevVersion: Integer; override; // 103 class function Version: Integer; override; // 104 end; implementation uses Ht_Dll, Ht_Const, SysUtils, l3Base, l3Chars, DT_DbReformer, StrUtils; {$INCLUDE nodt_const.inc} const TABLE = 'FILE001'; SEARCH_SUBSTR = '(снято с контроля)'; class function TUpgradeTo104.PrevVersion: Integer; begin Result := 103; end; function fn_RecalcField(gRecNo: LongInt; fpRecord: Pointer; fpUser: Pointer): Boolean; pascal; var l_Found: PChar; begin l_Found := SearchBuf(PChar(fpRecord) + PFieldData(fpUser)^.Offset, PFieldData(fpUser)^.Length, 0, 0, SEARCH_SUBSTR, [soDown]); if l_Found <> nil then begin // сдвигаем хвост влево (затирая найденную подстроку) // количество сдвигаемых байт = (длина поля) - ((отступ найденной подстроки) + (длина подстроки)) l3Move((l_Found + Length(SEARCH_SUBSTR))^, l_Found^, PFieldData(fpUser)^.Length - (l_Found - (PChar(fpRecord) + PFieldData(fpUser)^.Offset)) - Length(SEARCH_SUBSTR)); // добиваем пробелами то место, где только что был хвост (последние Length(SEARCH_SUBSTR) байт) l3FillChar((PChar(fpRecord) + PFieldData(fpUser)^.Offset + PFieldData(fpUser)^.Length - Length(SEARCH_SUBSTR))^, Length(SEARCH_SUBSTR), Ord(cc_HardSpace)); end; Result := True; end; procedure TUpgradeTo104.ModifyBd; begin with f_DbReformer do begin Log('Исправление значений поля FILE.SHORTNAME: удаление подстрок "(снято с контроля)"'); RecalcStrField(FamilyTable(TABLE), 2, @fn_RecalcField, PChar('*' + SEARCH_SUBSTR + '*')); Log('Исправление значений поля FILE.FULLNAME: удаление подстрок "(снято с контроля)"'); RecalcStrField(FamilyTable(TABLE), 3, @fn_RecalcField, PChar('*' + SEARCH_SUBSTR + '*')); end; // with end; class function TUpgradeTo104.Version: Integer; begin Result := 104; end; procedure TUpgradeTo104.InitRestorableTableList; begin inherited; with f_DbReformer do AddToRestorableList(FamilyTable(TABLE)); end; end.
unit UStorage; interface uses Classes, UOrphan, UPCOperationsComp, UOperationsHashTree; type { TStorage } TStorage = Class private FOrphan: TOrphan; FReadOnly: Boolean; protected FIsMovingBlockchain : Boolean; procedure SetOrphan(const Value: TOrphan); virtual; procedure SetReadOnly(const Value: Boolean); virtual; Function DoLoadBlockChain(Operations : TPCOperationsComp; Block : Cardinal) : Boolean; virtual; abstract; Function DoSaveBlockChain(Operations : TPCOperationsComp) : Boolean; virtual; abstract; Function DoMoveBlockChain(StartBlock : Cardinal; Const DestOrphan : TOrphan; DestStorage : TStorage) : Boolean; virtual; abstract; Function DoSaveBank : Boolean; virtual; abstract; Function DoRestoreBank(max_block : Int64) : Boolean; virtual; abstract; Procedure DoDeleteBlockChainBlocks(StartingDeleteBlock : Cardinal); virtual; abstract; function GetFirstBlockNumber: Int64; virtual; abstract; function GetLastBlockNumber: Int64; virtual; abstract; function DoInitialize:Boolean; virtual; abstract; Function DoCreateSafeBoxStream(blockCount : Cardinal) : TStream; virtual; abstract; Procedure DoEraseStorage; virtual; abstract; Procedure DoSavePendingBufferOperations(OperationsHashTree : TOperationsHashTree); virtual; abstract; Procedure DoLoadPendingBufferOperations(OperationsHashTree : TOperationsHashTree); virtual; abstract; public // Skybuck: moved to here so TPCBank can access it Function BlockExists(Block : Cardinal) : Boolean; virtual; abstract; Function LoadBlockChainBlock(Operations : TPCOperationsComp; Block : Cardinal) : Boolean; Function SaveBlockChainBlock(Operations : TPCOperationsComp) : Boolean; Function MoveBlockChainBlocks(StartBlock : Cardinal; Const DestOrphan : TOrphan; DestStorage : TStorage) : Boolean; Procedure DeleteBlockChainBlocks(StartingDeleteBlock : Cardinal); Function SaveBank : Boolean; Function RestoreBank(max_block : Int64) : Boolean; Constructor Create; Property Orphan : TOrphan read FOrphan write SetOrphan; Property ReadOnly : Boolean read FReadOnly write SetReadOnly; Procedure CopyConfiguration(Const CopyFrom : TStorage); virtual; Property FirstBlock : Int64 read GetFirstBlockNumber; Property LastBlock : Int64 read GetLastBlockNumber; Function Initialize : Boolean; Function CreateSafeBoxStream(blockCount : Cardinal) : TStream; Function HasUpgradedToVersion2 : Boolean; virtual; abstract; Procedure CleanupVersion1Data; virtual; abstract; Procedure EraseStorage; Procedure SavePendingBufferOperations(OperationsHashTree : TOperationsHashTree); Procedure LoadPendingBufferOperations(OperationsHashTree : TOperationsHashTree); End; implementation uses SysUtils, ULog, UPascalCoinBank, UPascalCoinSafeBox; { TStorage } procedure TStorage.CopyConfiguration(const CopyFrom: TStorage); begin Orphan := CopyFrom.Orphan; end; constructor TStorage.Create; begin inherited; FOrphan := ''; FReadOnly := false; FIsMovingBlockchain := False; end; procedure TStorage.DeleteBlockChainBlocks(StartingDeleteBlock: Cardinal); begin if ReadOnly then raise Exception.Create('Cannot delete blocks because is ReadOnly'); DoDeleteBlockChainBlocks(StartingDeleteBlock); end; function TStorage.Initialize: Boolean; begin Result := DoInitialize; end; function TStorage.CreateSafeBoxStream(blockCount: Cardinal): TStream; begin Result := DoCreateSafeBoxStream(blockCount); end; procedure TStorage.EraseStorage; begin TLog.NewLog(ltInfo,ClassName,'Executing EraseStorage'); DoEraseStorage; end; procedure TStorage.SavePendingBufferOperations(OperationsHashTree : TOperationsHashTree); begin DoSavePendingBufferOperations(OperationsHashTree); end; procedure TStorage.LoadPendingBufferOperations(OperationsHashTree : TOperationsHashTree); begin DoLoadPendingBufferOperations(OperationsHashTree); end; function TStorage.LoadBlockChainBlock(Operations: TPCOperationsComp; Block: Cardinal): Boolean; begin if (Block<FirstBlock) Or (Block>LastBlock) then result := false else Result := DoLoadBlockChain(Operations,Block); end; function TStorage.MoveBlockChainBlocks(StartBlock: Cardinal; const DestOrphan: TOrphan; DestStorage : TStorage): Boolean; begin if Assigned(DestStorage) then begin if DestStorage.ReadOnly then raise Exception.Create('Cannot move blocks because is ReadOnly'); end else if ReadOnly then raise Exception.Create('Cannot move blocks from myself because is ReadOnly'); Result := DoMoveBlockChain(StartBlock,DestOrphan,DestStorage); end; function TStorage.RestoreBank(max_block: Int64): Boolean; begin Result := DoRestoreBank(max_block); end; function TStorage.SaveBank: Boolean; begin Result := true; If FIsMovingBlockchain then Exit; if Not TPCSafeBox.MustSafeBoxBeSaved(PascalCoinSafeBox.BlocksCount) then exit; // No save Try Result := DoSaveBank; PascalCoinSafeBox.CheckMemory; Except On E:Exception do begin TLog.NewLog(lterror,Classname,'Error saving Bank: '+E.Message); Raise; end; End; end; function TStorage.SaveBlockChainBlock(Operations: TPCOperationsComp): Boolean; begin Try if ReadOnly then raise Exception.Create('Cannot save because is ReadOnly'); Result := DoSaveBlockChain(Operations); Except On E:Exception do begin TLog.NewLog(lterror,Classname,'Error saving block chain: '+E.Message); Raise; end; End; end; procedure TStorage.SetOrphan(const Value: TOrphan); begin FOrphan := Value; end; procedure TStorage.SetReadOnly(const Value: Boolean); begin FReadOnly := Value; end; end.
unit udmPagTitulo; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmPagTitulo = class(TdmPadrao) qryManutencaoIDPGTITULO: TFloatField; qryManutencaoIDNFPAG: TFloatField; qryManutencaoEMISSAO: TStringField; qryManutencaoDESCRICAO_COMPL: TStringField; qryManutencaoQTDPARCELAS: TIntegerField; qryManutencaoVALOR_TITULO: TFloatField; qryLocalizacaoIDPGTITULO: TFloatField; qryLocalizacaoIDNFPAG: TFloatField; qryLocalizacaoEMISSAO: TStringField; qryLocalizacaoDESCRICAO_COMPL: TStringField; qryLocalizacaoQTDPARCELAS: TIntegerField; qryLocalizacaoVALOR_TITULO: TFloatField; qryManutencaoTIPO: TStringField; qryLocalizacaoTIPO: TStringField; qryManutencaoNUM_TITULO: TStringField; qryLocalizacaoNUM_TITULO: TStringField; procedure qryManutencaoBeforePost(DataSet: TDataSet); protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FCodigoNF: real; public property CodigoNF: real read FCodigoNF write FCodigoNF; end; const SQL_DEFAULT = ' SELECT ' + ' IDPGTITULO, ' + ' IDNFPAG, ' + ' EMISSAO, ' + ' DESCRICAO_COMPL, ' + ' QTDPARCELAS, ' + ' VALOR_TITULO, ' + ' TIPO, ' + ' NUM_TITULO ' + ' FROM PAG_TITULO '; var dmPagTitulo: TdmPagTitulo; implementation uses udmPrincipal; {$R *.dfm} { TdmPadrao1 } procedure TdmPagTitulo.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Add(SQL_DEFAULT); SQL.Add('WHERE IDNFPAG = :IDNFPAG'); Params[0].AsFloat := FCodigoNF; end; end; procedure TdmPagTitulo.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('ORDER BY IDNFPAG, IDPGTITULO'); end; end; procedure TdmPagTitulo.qryManutencaoBeforePost(DataSet: TDataSet); begin inherited; if (qryManutencaoIDPGTITULO.isNull) or (qryManutencaoIDPGTITULO.AsInteger = 0) then qryManutencaoIDPGTITULO.AsFloat := dmPrincipal.GeraGenerator('GEN_PAGTITULO'); end; end.
program exRecords; type Books = record title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1..100] of char; book_id: longint; end; var Book1, Book2: Books; (* Declare Book1 and Book2 of type Books *) rptr1 : ^Books; begin rptr1:=@rptr1; writeln('rptr1 points to a value: ', HexStr(rptr1)); inc(rptr1); writeln('rptr1 points to a value: ', HexStr(rptr1)); (* book 1 specification *) Book1.title := 'C Programming'; Book1.author := 'Nuha Ali '; Book1.subject := 'C Programming Tutorial'; Book1.book_id := 6495407; (* book 2 specification *) Book2.title := 'Telecom Billing'; Book2.author := 'Zara Ali'; Book2.subject := 'Telecom Billing Tutorial'; Book2.book_id := 6495700; (* print Book1 info *) writeln ('Book 1 title : ', Book1.title); writeln('Book 1 author : ', Book1.author); writeln( 'Book 1 subject : ', Book1.subject); writeln( 'Book 1 book_id : ', Book1.book_id); writeln; (* print Book2 info *) writeln ('Book 2 title : ', Book2.title); writeln('Book 2 author : ', Book2.author); writeln( 'Book 2 subject : ', Book2.subject); writeln( 'Book 2 book_id : ', Book2.book_id); end.
unit m2U64Lib; {* Функции для работы с беззнаковыми 64-битными числами. } (* // // // .Author: Mickael P. Golovin. // .Copyright: 1997-2001 by Archivarius Team, free for non commercial use. // // *) // $Id: m2u64lib.pas,v 1.1 2008/02/22 17:10:08 lulin Exp $ // $Log: m2u64lib.pas,v $ // Revision 1.1 2008/02/22 17:10:08 lulin // - библиотека переехала. // // Revision 1.2 2007/12/10 15:33:04 lulin // - cleanup. // // Revision 1.1 2007/12/07 11:51:05 lulin // - переезд. // // Revision 1.2 2001/10/18 12:10:32 law // - comments: xHelpGen. // {$I m2Define.inc} interface function m2U64Min (const AParamA: Int64; const AParamB: Int64 ): Int64; pascal; {* - возвращает минимальное из двух чисел. } function m2U64Max (const AParamA: Int64; const AParamB: Int64 ): Int64; pascal; {* - возвращает максимальное из двух чисел. } function m2U64Compare (const AParamA: Int64; const AParamB: Int64 ): Integer; pascal; {* - сравнивает два числа. } implementation function m2U64Min(const AParamA: Int64; const AParamB: Int64 ): Int64; asm push ebx mov ecx,dword ptr [AParamA][+$00] mov ebx,dword ptr [AParamA][+$04] mov eax,dword ptr [AParamB][+$00] mov edx,dword ptr [AParamB][+$04] cmp ebx,edx ja @@02 jnz @@01 cmp ecx,eax ja @@02 @@01: mov eax,ecx mov edx,ebx @@02: pop ebx end; function m2U64Max(const AParamA: Int64; const AParamB: Int64 ): Int64; asm push ebx mov ecx,dword ptr [AParamA][+$00] mov ebx,dword ptr [AParamA][+$04] mov eax,dword ptr [AParamB][+$00] mov edx,dword ptr [AParamB][+$04] cmp edx,ebx ja @@02 jnz @@01 cmp eax,ecx ja @@02 @@01: mov eax,ecx mov edx,ebx @@02: pop ebx end; function m2U64Compare(const AParamA: Int64; const AParamB: Int64 ): Integer; asm push ebx mov ecx,dword ptr [AParamA][+$00] mov ebx,dword ptr [AParamA][+$04] mov eax,dword ptr [AParamB][+$00] mov edx,dword ptr [AParamB][+$04] cmp ebx,edx ja @@04 jnz @@01 cmp ecx,eax ja @@04 @@01: cmp edx,ebx ja @@02 jnz @@03 cmp eax,ecx jbe @@03 @@02: xor eax,eax dec eax jmp @@05 @@03: xor eax,eax jmp @@05 @@04: xor eax,eax inc eax @@05: pop ebx end; end.
{ Double Commander ------------------------------------------------------------------------- Graphic functions Copyright (C) 2013-2017 Alexander Koblov (alexx2000@mail.ru) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA } unit uGraphics; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Controls; type { TImageListHelper } TImageListHelper = class helper for TImageList public procedure LoadThemeIcon(Index: Integer; const AIconName: String); end; procedure BitmapAssign(Bitmap: TBitmap; Image: TRasterImage); procedure BitmapAlpha(var ABitmap: TBitmap; APercent: Single); implementation uses GraphType, FPimage, IntfGraphics, uPixMapManager; type TRawAccess = class(TRasterImage) end; procedure BitmapAssign(Bitmap: TBitmap; Image: TRasterImage); var RawImage: PRawImage; begin RawImage:= TRawAccess(Image).GetRawImagePtr; // Simply change raw image owner without data copy Bitmap.LoadFromRawImage(RawImage^, True); // Set image data pointer to nil, so it will not free double RawImage^.ReleaseData; end; procedure BitmapAlpha(var ABitmap: TBitmap; APercent: Single); var X, Y: Integer; Color: TFPColor; AImage: TLazIntfImage; begin if ABitmap.RawImage.Description.AlphaPrec <> 0 then begin AImage:= ABitmap.CreateIntfImage(); for X:= 0 to AImage.Width - 1 do begin for Y:= 0 to AImage.Height - 1 do begin Color:= AImage.Colors[X, Y]; Color.Alpha:= Round(Color.Alpha * APercent); AImage.Colors[X, Y]:= Color; end; end; ABitmap.LoadFromIntfImage(AImage); AImage.Free; end; end; { TImageListHelper } procedure TImageListHelper.LoadThemeIcon(Index: Integer; const AIconName: String); var ABitmap: TBitmap; begin ABitmap:= PixMapManager.GetThemeIcon(AIconName, Self.Width); if (ABitmap = nil) then ABitmap:= TBitmap.Create; if (Index < Count) then Self.Replace(Index, ABitmap , nil) else begin Self.Insert(Index, ABitmap , nil) end; ABitmap.Free; end; end.
unit LandGenerator; interface uses Land, Classes, Collection, Windows, Graphics; const LandMax = 10000; type PLandMatrix = ^TLandMatrix; TLandMatrix = array[0..LandMax*LandMax] of TLandVisualClassId; TLandCheckOption = (chkCenter, chkBorder, chkDontCare); TLandDetectMatrix = array[0..2, 0..2] of TLandCheckOption; TVisualClass = class public constructor Create( aLandVisualClassId : TLandVisualClassId; aMapColor : TColor ); private fLandVisualClassId : TLandVisualClassId; fMapColor : TColor; public property LandVisualClassId : TLandVisualClassId read fLandVisualClassId; property MapColor : TColor read fMapColor; end; TLandDetector = class public constructor Create( aCenterClass, aBorderClass : TLandClass; aLandType : TLandType ); private fCenterClass : TLandClass; fBorderClass : TLandClass; fLandType : TLandType; fDetectionMatrix : TLandDetectMatrix; fVisualClasses : TCollection; public function DetectLand( x, y : integer; LandSource : PLandMatrix; LandWidth : integer ) : TLandVisualClassId; function RandomLand : TLandVisualClassId; function VisualClassMatches( aLandClass : TLandClass; aLandType : TLandType ) : boolean; procedure AddVisualClass( aVisualClass : TVisualClass ); protected function GenerateLandDetectMatrix : TLandDetectMatrix; virtual; end; TLandRenderer = class public constructor Create( ClassDir : string ); destructor Destroy; override; private fLandSize : TPoint; fLandBitmap : TBitmap; fLandSource : PLandMatrix; fLandDest : PLandMatrix; fDetectors : TCollection; fClassCount : integer; public property LandSize : TPoint read fLandSize; property LandSource : PLandMatrix read fLandSource; property LandDest : PLandMatrix read fLandDest; property ClassCount : integer read fClassCount; private fVisualClasses : TCollection; private function GetVisualClass( VisualClassId : TLandVisualClassId ) : TVisualClass; public property VisualClass[VisualClassId : TLandVisualClassId] : TVisualClass read GetVisualClass; property VisualClasses : TCollection read fVisualClasses; public procedure RenderLand; procedure LoadLandInfo( filename : string ); procedure LoadRenderedLand( filename : string ); procedure StoreRenderedLand( filename : string ); private fColors : array[TLandClass] of TColor; private procedure ScanForColors; function GetDetector( aLandClass : TLandClass; aLandType : TLandType ) : TLandDetector; end; implementation uses SysUtils, IniFiles; const O = chkCenter; m = chkBorder; x = chkDontCare; const CommonDetectors : array[TLandType] of TLandDetectMatrix = // Center ( ((O, O, O), (O, O, O), (O, O, O)), // N ((x, m, x), (O, O, O), (x, x, x)), // E ((x, O, x), (x, O, m), (x, O, x)), // S ((x, x, x), (O, O, O), (x, m, x)), // W ((x, O, x), (m, O, x), (x, O, x)), // NEo ((x, m, x), (O, O, m), (x, O, x)), // SEo ((x, O, x), (O, O, m), (x, m, x)), // SWo ((x, O, x), (m, O, O), (x, m, x)), // NWo ((x, m, x), (m, O, O), (x, O, x)), // NEi ((x, O, m), (x, O, O), (x, x, x)), // SEi ((x, x, x), (x, O, O), (x, O, m)), // SWi ((x, x, x), (O, O, x), (m, O, x)), // NWi ((m, O, x), (O, O, x), (x, x, x)), // Special ((O, O, O), (O, O, O), (O, O, O)) ); // TVisualClass constructor TVisualClass.Create( aLandVisualClassId : TLandVisualClassId; aMapColor : TColor ); begin inherited Create; fLandVisualClassId := aLandVisualClassId; fMapColor := aMapColor; end; // TLandDetector constructor TLandDetector.Create( aCenterClass, aBorderClass : TLandClass; aLandType : TLandType ); begin inherited Create; fCenterClass := aCenterClass; fBorderClass := aBorderClass; fLandType := aLandType; fVisualClasses := TCollection.Create( 0, rkUse ); fDetectionMatrix := GenerateLandDetectMatrix; end; function TLandDetector.DetectLand( x, y : integer; LandSource : PLandMatrix; LandWidth : integer ) : TLandVisualClassId; var matches : boolean; i, j : integer; Check : TLandCheckOption; LandId : TLandVisualClassId; begin if fVisualClasses.Count > 0 then begin matches := true; i := 0; while (i < 3) and matches do begin j := 0; while (j < 3) and matches do begin Check := fDetectionMatrix[i, j]; LandId := LandSource[LandWidth*(y - 1 + i) + x - 1 + j]; matches := (LandId = NoLand) or (Check = chkDontCare) or (Check = chkCenter) and (Land.LandPrimaryClassOf( LandId ) = fCenterClass) or (Check = chkBorder) and (Land.LandPrimaryClassOf( LandId ) = fBorderClass); inc( j ); end; inc( i ); end; if matches then result := RandomLand else result := NoLand; end else result := NoLand; end; function TLandDetector.RandomLand : TLandVisualClassId; begin result := TVisualClass(fVisualClasses[random(fVisualClasses.Count)]).LandVisualClassId; end; function TLandDetector.VisualClassMatches( aLandClass : TLandClass; aLandType : TLandType ) : boolean; begin result := (fCenterClass = aLandClass) and (fLandType = aLandType); end; procedure TLandDetector.AddVisualClass( aVisualClass : TVisualClass ); begin fVisualClasses.Insert( aVisualClass ); end; function TLandDetector.GenerateLandDetectMatrix : TLandDetectMatrix; begin result := CommonDetectors[fLandType]; end; // TLandRenderer constructor TLandRenderer.Create( ClassDir : string ); procedure LoadClasses; var SearchRec : TSearchRec; found : boolean; IniFile : TIniFile; VisualClass : TVisualClass; LandPClass : TLandClass; LandSClass : TLandClass; LandType : TLandType; Detector : TLandDetector; begin found := FindFirst( ClassDir + '*.ini', faAnyFile, SearchRec ) = 0; while found do begin IniFile := TIniFile.Create( ClassDir + SearchRec.Name ); VisualClass := TVisualClass.Create( IniFile.ReadInteger( 'General', 'Id', NoLand ), IniFile.ReadInteger( 'General', 'MapColor', 0 )); LandPClass := Land.LandPrimaryClassOf( VisualClass.LandVisualClassId ); LandSClass := Land.LandSecondaryClassOf( VisualClass.LandVisualClassId ); LandType := Land.LandTypeOf( VisualClass.LandVisualClassId ); Detector := GetDetector( LandPClass, LandType ); if Detector = nil then begin Detector := TLandDetector.Create( LandPClass, LandSClass, LandType ); fDetectors.Insert( Detector ); end; fVisualClasses.Insert( VisualClass ); Detector.AddVisualClass( VisualClass ); found := FindNext( SearchRec ) = 0; inc( fClassCount ); end; end; begin inherited Create; fDetectors := TCollection.Create( 0, rkBelonguer ); fVisualClasses := TCollection.Create( 0, rkBelonguer ); LoadClasses; end; destructor TLandRenderer.Destroy; begin fDetectors.Free; fLandBitmap.Free; fVisualClasses.Free; inherited; end; function TLandRenderer.GetVisualClass( VisualClassId : TLandVisualClassId ) : TVisualClass; var i : integer; begin i := 0; while (i < fVisualClasses.Count) and (TVisualClass(fVisualClasses[i]).LandVisualClassId <> VisualClassId) do inc( i ); if i < fVisualClasses.Count then result := TVisualClass(fVisualClasses[i]) else result := nil; end; procedure TLandRenderer.LoadLandInfo( filename : string ); function LandValueOfColor( Color : TColor ) : TLandVisualClassId; var LandClass : TLandClass; begin LandClass := low(LandClass); while (LandClass <= high(LandClass)) and (fColors[LandClass] <> Color) do inc( LandClass ); result := Land.PrimaryLandClassIds[LandClass]; end; var x, y : integer; begin fLandBitmap := TBitmap.Create; fLandBitmap.LoadFromFile( filename ); ScanForColors; fLandSize.x := fLandBitmap.Width; fLandSize.y := fLandBitmap.Height; getmem( fLandSource, fLandSize.y*fLandSize.x*sizeof(fLandSource[0]) ); fillchar( fLandSource^, fLandSize.y*fLandSize.x*sizeof(fLandSource[0]), NoLand ); getmem( fLandDest, fLandSize.y*fLandSize.x*sizeof(fLandSource[0]) ); fillchar( fLandDest^, fLandSize.y*fLandSize.x*sizeof(fLandSource[0]), NoLand ); for y := 0 to pred(fLandSize.y) do for x := 0 to pred(fLandSize.x) do fLandSource[fLandSize.x*y + x] := LandValueOfColor( fLandBitmap.Canvas.Pixels[x, y] ); end; procedure TLandRenderer.LoadRenderedLand( filename : string ); var x, y : integer; line : PByteArray; begin fLandBitmap := TBitmap.Create; fLandBitmap.LoadFromFile( filename ); fLandSize.x := fLandBitmap.Width; fLandSize.y := fLandBitmap.Height; getmem( fLandSource, fLandSize.y*fLandSize.x*sizeof(fLandSource[0]) ); fillchar( fLandSource^, fLandSize.y*fLandSize.x*sizeof(fLandSource[0]), NoLand ); { getmem( fLandDest, fLandSize.y*fLandSize.x*sizeof(fLandSource[0]) ); fillchar( fLandDest^, fLandSize.y*fLandSize.x*sizeof(fLandSource[0]), NoLand ); } for y := 0 to pred(fLandSize.y) do begin line := fLandBitmap.ScanLine[y]; for x := 0 to pred(fLandSize.x) do fLandSource[fLandSize.x*y + x] := line[x]; end; fLandBitmap.Free; end; procedure TLandRenderer.StoreRenderedLand( filename : string ); var S : TStream; begin S := TFileStream.Create( filename, fmOpenWrite ); try S.WriteBuffer( fLandSize, sizeof(fLandSize) ); S.WriteBuffer( fLandDest^, fLandSize.x*fLandSize.y*sizeof(TLandVisualClassId) ); finally S.Free; end; end; procedure TLandRenderer.RenderLand; var x, y, i : integer; AccurateId : TLandVisualClassId; Center : TLandDetector; begin for y := 1 to fLandSize.y - 2 do for x := 1 to fLandSize.x - 2 do begin i := 0; repeat AccurateId := TLandDetector(fDetectors[i]).DetectLand( x, y, fLandSource, fLandSize.x ); inc( i ); until (i = fDetectors.Count) or (AccurateId <> NoLand); if AccurateId = NoLand then begin Center := GetDetector( LandPrimaryClassOf(fLandSource[y*fLandSize.x + x]), ldtCenter ); AccurateId := Center.RandomLand; end; fLandDest[fLandSize.x*y + x] := AccurateId; end; end; procedure TLandRenderer.ScanForColors; var i : TLandClass; begin for i := low(i) to high(i) do fColors[i] := fLandBitmap.Canvas.Pixels[integer(i), 0]; end; function TLandRenderer.GetDetector( aLandClass : TLandClass; aLandType : TLandType ) : TLandDetector; var i : integer; begin i := 0; while (i < fDetectors.Count) and not (TLandDetector(fDetectors[i]).VisualClassMatches( aLandClass, aLandType )) do inc( i ); if i < fDetectors.Count then result := TLandDetector(fDetectors[i]) else result := nil; end; end.
unit untCPedidoProduto; interface uses System.SysUtils, Data.Win.ADODB, untDataModuleWK, untCProduto, Dialogs; type TpedidoProduto = class private FGetidpedidoproduto: Integer; FGetidpedido: Integer; FGetidproduto: Integer; FGetquantidade: Double; FGetvalorunit: Double; FGetvalortotalproduto: Double; procedure Setidpedidoproduto(const Value: Integer); procedure Setidpedido(const Value: Integer); procedure Setidproduto(const Value: Integer); procedure Setquantidade(const Value: Double); procedure Setvalorunit(const Value: Double); procedure Setvalortotalproduto(const Value: Double); protected Public property Getidpedidoproduto : Integer read FGetidpedidoproduto write Setidpedidoproduto; property Getidpedido : Integer read FGetidpedido write Setidpedido; property Getidproduto : Integer read FGetidproduto write Setidproduto; property Getquantidade :Double read FGetquantidade write Setquantidade; property Getvalorunit : Double read FGetvalorunit write Setvalorunit; property Getvalortotalproduto : Double read FGetvalortotalproduto write Setvalortotalproduto; function ConsultarPedidoProduto : Boolean; function ApagarPedidoProduto : Boolean; function ApagarItenPedido : Boolean; Constructor Create; // declaração do metodo construtor Destructor Destroy; Override; function SalvarPedidoProduto : Boolean; end; implementation { TpedidoProduto } function TpedidoProduto.ApagarItenPedido: Boolean; var ibQueryGenerica : TADOQuery; begin try ibQueryGenerica := TADOQuery.Create(nil); ibQueryGenerica.Connection := DataModuleWK.ADOConnectionwk; ibQueryGenerica.SQL.Add('delete from cadpedidoproduto where idpedido = ' + IntToStr(FGetidpedido)); ibQueryGenerica.ExecSQL; if ibQueryGenerica.IsEmpty then Result := True else Result := False; FreeAndNil(ibQueryGenerica); Except on E : Exception do ShowMessage(E.ClassName + 'erro gerado, com mensagem: ' + E.Message); end; end; function TpedidoProduto.ApagarPedidoProduto: Boolean; var ibQueryGenerica : TADOQuery; begin try ibQueryGenerica := TADOQuery.Create(nil); ibQueryGenerica.Connection := DataModuleWK.ADOConnectionwk; ibQueryGenerica.SQL.Add('delete from cadpedidoproduto where idpedidoproduto = ' + IntToStr(FGetidpedidoproduto)); ibQueryGenerica.ExecSQL; if ibQueryGenerica.IsEmpty then Result := True else Result := False; FreeAndNil(ibQueryGenerica); Except on E : Exception do ShowMessage(E.ClassName + 'erro gerado, com mensagem: ' + E.Message); end; end; function TpedidoProduto.ConsultarPedidoProduto: Boolean; var ibQueryGenerica : TADOQuery; begin try ibQueryGenerica := TADOQuery.Create(nil); ibQueryGenerica.Connection := DataModuleWK.ADOConnectionwk; ibQueryGenerica.SQL.Add('SELECT idpedidoproduto FROM cadpedidoproduto where idpedidoproduto = ' + IntToStr(FGetidpedidoproduto)); ibQueryGenerica.Open; if ibQueryGenerica.IsEmpty then Result := True else Result := False; FreeAndNil(ibQueryGenerica); Except on E : Exception do ShowMessage(E.ClassName + 'erro gerado, com mensagem: ' + E.Message); end; end; constructor TpedidoProduto.Create; begin FGetidpedido := 0; FGetidpedidoproduto := 0; FGetidproduto := 0; FGetquantidade := 0; FGetvalorunit := 0; FGetvalortotalproduto := 0; end; destructor TpedidoProduto.Destroy; begin //destroi inherited; end; function TpedidoProduto.SalvarPedidoProduto: Boolean; var ibQueryGenerica : TADOQuery; begin try ibQueryGenerica := TADOQuery.Create(nil); ibQueryGenerica.Connection := DataModuleWK.ADOConnectionwk; if ConsultarPedidoProduto then begin ibQueryGenerica.SQL.Add('INSERT INTO cadpedidoproduto'); ibQueryGenerica.SQL.Add('('); ibQueryGenerica.SQL.Add('idpedido,'); ibQueryGenerica.SQL.Add('idproduto,'); ibQueryGenerica.SQL.Add('quantidade,'); ibQueryGenerica.SQL.Add('valorunit,'); ibQueryGenerica.SQL.Add('valortotalproduto)'); ibQueryGenerica.SQL.Add('VALUES ('); ibQueryGenerica.SQL.Add(IntToStr(FGetidpedido) + ','); ibQueryGenerica.SQL.Add(IntToStr(FGetidproduto) + ','); ibQueryGenerica.SQL.Add(StringReplace(formatFloat('0.00',FGetquantidade), ',', '.', [rfReplaceAll])+ ','); ibQueryGenerica.SQL.Add(StringReplace(formatFloat('0.00',FGetvalorunit), ',', '.', [rfReplaceAll]) + ','); ibQueryGenerica.SQL.Add( StringReplace(formatFloat('0.00',FGetvalortotalproduto), ',', '.', [rfReplaceAll])+ ')'); end else begin ibQueryGenerica.SQL.Add('UPDATE cadpedidoproduto SET'); ibQueryGenerica.SQL.Add('idpedido = ' + IntToStr(FGetidpedido) + ','); ibQueryGenerica.SQL.Add('idproduto = ' + IntToStr(FGetidproduto) + ','); ibQueryGenerica.SQL.Add('quantidade = ' + StringReplace(formatFloat('0.00',FGetquantidade), ',', '.', [rfReplaceAll]) + ','); ibQueryGenerica.SQL.Add('valorunit = ' + StringReplace(formatFloat('0.00',FGetvalorunit), ',', '.', [rfReplaceAll]) + ','); ibQueryGenerica.SQL.Add('valortotalproduto = ' + StringReplace(formatFloat('0.00',FGetvalortotalproduto), ',', '.', [rfReplaceAll])); ibQueryGenerica.SQL.Add('WHERE idpedidoproduto = ' + IntToStr(FGetidpedidoproduto)); end; ibQueryGenerica.ExecSQL; FreeAndNil(ibQueryGenerica); Result := True; Except on E : Exception do ShowMessage(E.ClassName + 'erro gerado, com mensagem: ' + E.Message); end; end; procedure TpedidoProduto.Setidpedidoproduto(const Value: Integer); begin FGetidpedidoproduto := Value; end; procedure TpedidoProduto.Setidpedido(const Value: Integer); begin FGetidpedido := Value; end; procedure TpedidoProduto.Setidproduto(const Value: Integer); begin FGetidproduto := Value; end; procedure TpedidoProduto.Setquantidade(const Value: Double); begin FGetquantidade := Value; end; procedure TpedidoProduto.Setvalortotalproduto(const Value: Double); begin FGetvalortotalproduto := Value; end; procedure TpedidoProduto.Setvalorunit(const Value: Double); begin FGetvalorunit := Value; end; end.
unit G2Mobile.Model.CamaraFria; interface uses FMX.ListView, uDmDados, uRESTDWPoolerDB, System.SysUtils, IdSSLOpenSSLHeaders, FireDAC.Comp.Client, FMX.Dialogs, FMX.ListView.Appearances, FMX.ListView.Types, System.Classes, Datasnap.DBClient, FireDAC.Comp.DataSet, Data.DB, FMX.Objects, G2Mobile.Controller.CamaraFria; const CONST_DELETECAMARAFRIA = 'DELETE FROM CAMARA_FRIA'; CONST_BUSCACAMARAFRIASERVIDOR = 'SELECT COD_CAMARA, DESCRICAO FROM T_CAMARA_FRIA'; CONST_INSERTCAMARAFRIA = 'INSERT INTO CAMARA_FRIA ( COD_CAMARA, DESCRICAO) VALUES ( :COD_CAMARA, :DESCRICAO)'; CONST_BUSCARCAMARAFRIA = 'SELECT DESCRICAO FROM CAMARA_FRIA WHERE COD_CAMARA = :COD_CAMARA'; CONST_lISTACAMARAFRIA = 'select * from camara_fria'; CONST_RETORNACAMARAFRIAVENDEDOR = 'SELECT u.cod_camara, c.descricao FROM usuarios u ' + 'left outer join camara_fria c on (c.cod_camara = u.cod_camara) ' + 'where u.cod_user = :COD_USER'; type TModelCamaraFria = class(TInterfacedObject, iModelCamaraFria) private FQry : TFDQuery; FRdwSQLTemp: TRESTDWClientSQL; public constructor create; destructor destroy; override; class function new: iModelCamaraFria; function BuscaCamaraFriaServidor(ADataSet: TFDMemTable): iModelCamaraFria; function PopulaCamaraFriaSqLite(ADataSet: TFDMemTable): iModelCamaraFria; function LimpaTabelaCamaraFria: iModelCamaraFria; function PopulaListView(value: TListView; imageForma: Timage): iModelCamaraFria; function BuscarCamaraFria(value: Integer): String; function RetornaCamaraFriaVendedor(value: Integer): String; end; implementation { TModelCamaraFria } class function TModelCamaraFria.new: iModelCamaraFria; begin result := self.create; end; constructor TModelCamaraFria.create; begin FQry := TFDQuery.create(nil); FQry.Connection := DmDados.ConexaoInterna; FQry.FetchOptions.RowsetSize := 50000; FQry.Active := false; FQry.SQL.Clear; FRdwSQLTemp := TRESTDWClientSQL.create(nil); FRdwSQLTemp.DataBase := DmDados.RESTDWDataBase1; FRdwSQLTemp.BinaryRequest := True; FRdwSQLTemp.FormatOptions.MaxStringSize := 10000; FRdwSQLTemp.Active := false; FRdwSQLTemp.SQL.Clear; end; destructor TModelCamaraFria.destroy; begin FreeAndNil(FQry); inherited; end; function TModelCamaraFria.LimpaTabelaCamaraFria: iModelCamaraFria; begin result := self; FQry.ExecSQL(CONST_DELETECAMARAFRIA) end; function TModelCamaraFria.BuscaCamaraFriaServidor(ADataSet: TFDMemTable): iModelCamaraFria; begin result := self; FRdwSQLTemp.SQL.Text := CONST_BUSCACAMARAFRIASERVIDOR; FRdwSQLTemp.Active := True; FRdwSQLTemp.RecordCount; ADataSet.CopyDataSet(FRdwSQLTemp, [coStructure, coRestart, coAppend]); end; function TModelCamaraFria.PopulaCamaraFriaSqLite(ADataSet: TFDMemTable): iModelCamaraFria; var i: Integer; begin result := self; ADataSet.First; for i := 0 to ADataSet.RecordCount - 1 do begin FQry.SQL.Text := CONST_INSERTCAMARAFRIA; FQry.ParamByName('COD_CAMARA').AsInteger := ADataSet.FieldByName('COD_CAMARA').AsInteger; FQry.ParamByName('DESCRICAO').AsString := ADataSet.FieldByName('DESCRICAO').AsString; FQry.ExecSQL; ADataSet.Next; end; end; function TModelCamaraFria.BuscarCamaraFria(value: Integer): String; begin FQry.SQL.Text := CONST_BUSCARCAMARAFRIA; FQry.ParamByName('COD_CAMARA').AsInteger := value; FQry.Open; if FQry.RecordCount = 0 then result := EmptyStr else result := FQry.FieldByName('DESCRICAO').AsString; end; function TModelCamaraFria.PopulaListView(value: TListView; imageForma: Timage): iModelCamaraFria; var x : Integer; item: TListViewItem; txt : TListItemText; img : TListItemImage; foto: TStream; begin result := self; try FQry.Open(CONST_lISTACAMARAFRIA); value.Items.Clear; value.BeginUpdate; for x := 0 to FQry.RecordCount - 1 do begin item := value.Items.Add; with item do begin txt := TListItemText(Objects.FindDrawable('codigo')); txt.Text := formatfloat('0000', FQry.FieldByName('cod_camara').AsFloat); txt.TagString := FQry.FieldByName('cod_camara').AsString; txt := TListItemText(Objects.FindDrawable('desc')); txt.Text := FQry.FieldByName('descricao').AsString; img := TListItemImage(Objects.FindDrawable('Image')); img.Bitmap := imageForma.Bitmap; end; FQry.Next end; finally value.EndUpdate; end; end; function TModelCamaraFria.RetornaCamaraFriaVendedor(value: Integer): String; begin FQry.SQL.Text := CONST_RETORNACAMARAFRIAVENDEDOR; FQry.ParamByName('COD_USER').AsInteger := value; FQry.Open; if FQry.RecordCount = 0 then result := '0' else result := formatfloat('0000', FQry.FieldByName('cod_camara').AsFloat); end; end.
unit UModem; interface uses Classes,CommInt,SysUtils; type TModemState = (msNotOpen,msNotReady, msOffline,msConnection,msOnline,msDisconnection); TCustomModem = class (TCustomComm) protected function GetResponseInLine: String; procedure SetState(NewState:TModemState); protected FState:TModemState; FOnConnFailed:TNotifyEvent; FOnConnect:TNotifyEvent; FOnDisconnect:TNotifyEvent; FOnModemRxChar:TCommRxCharEvent; FOnModemTxEmpty:TNotifyEvent; FOnResponse:TNotifyEvent; FResponseCode:Integer; FResponse:String; LastLine:String; protected procedure ProcessResponse; procedure OnCommStateChange(Sender:TObject); procedure OnCommRxChar(Sender: TObject; Count: Integer); procedure OnCommTxEmpty(Sender: TObject); property OnConnFailed:TNotifyEvent read FOnConnFailed write FOnConnFailed; property OnConnect:TNotifyEvent read FOnConnect write FOnConnect; property OnDisconnect:TNotifyEvent read FOnDisconnect write FOnDisconnect; property OnModemRxChar:TCommRxCharEvent read FOnModemRxChar write FOnModemRxChar; property OnModemTxEmpty:TNotifyEvent read FOnModemTxEmpty write FOnModemTxEmpty; property OnResponse:TNotifyEvent read FOnResponse write FOnResponse; public constructor Create(AOwner: TComponent); override; procedure Open; reintroduce; procedure Close; reintroduce; procedure Connect(ConnectCmd:String); procedure DoCmd(Cmd:String); procedure Disconnect(ReinitCmd:String = ''); property State:TModemState read FState; property Response:String read FResponse; property ResponseInLine:String read GetResponseInLine; property ResponseCode:Integer read FResponseCode; end; TModem = class(TCustomModem) published // TCustomComm property DeviceName; property ReadTimeout; property WriteTimeout; property ReadBufSize; property WriteBufSize; property MonitorEvents; property BaudRate; property Parity; property Stopbits; property Databits; property EventChars; property Options; property FlowControl; property OnBreak; property OnCts; property OnRing; property OnError; property OnRxFlag; // TCustomModem property OnConnFailed; property OnConnect; property OnDisconnect; property OnModemRxChar; property OnModemTxEmpty; property OnResponse; end; const mrcUnknown = -1; mrcOk = 0; mrcConnect = 1; mrcRing = 2; mrcNoCarrier = 3; mrcError = 4; mrcNoDialtone = 6; mrcBusy = 7; mrcNoAnswer = 8; mrcDtrDropped = 9; mrcDsrDropped = 10; mrcClosed = 11; ModemResponses:array[-1..11] of String=( '???', // -1 'OK', // 0 'CONNECT', // 1 'RING', // 2 'NO CARRIER', // 3 'ERROR', // 4 'connect1200', // 5 (not used here) 'NO DIALTONE', // 6 'BUSY', // 7 'NO ANSWER', // 8 'DTR DROPPED', // 9 '[Not ready]', //10 '[Port closed]' //11 ); const sModemStates:array [TModemState] of String=( '- - -', 'Нет готовности (DSR=0)', 'Командный режим (CD=0)', 'Попытка соединения', 'Есть несущая (CD=1)', 'Разъединение' ); procedure Register; implementation uses Windows,Forms; procedure Register; begin RegisterComponents('W.Vitek', [TModem]); end; { TCustomModem } procedure TCustomModem.Connect(ConnectCmd: String); begin SetState(msConnection); DoCmd(ConnectCmd); end; constructor TCustomModem.Create(AOwner: TComponent); begin inherited; FState:=msNotOpen; FResponseCode:=mrcUnknown; OnRLSD:=OnCommStateChange; OnDSR:=OnCommStateChange; OnRxChar:=OnCommRxChar; OnTxEmpty:=OnCommTxEmpty; end; procedure TCustomModem.Disconnect(ReinitCmd:String); const PPP:String='+++'; Inside:Boolean=False; var i:Integer; OldState:TModemState; begin if not Enabled or Inside then exit; Inside:=True; if RLSD then begin sleep(250); Application.ProcessMessages(); Write(PPP[1],Length(PPP)); sleep(250); Application.ProcessMessages(); if ReinitCmd<>'' then DoCmd(ReinitCmd); SetRtsState(False); SetDtrState(False); OldState:=FState; FState:=msOffline; // OnCommStateChange(Self); for i:=1 to 16 do begin if not RLSD then break; sleep(250); // if ReinitCmd<>'' then DoCmd(ReinitCmd); Application.ProcessMessages(); end; SetDtrState(True); SetRtsState(True); FState:=OldState; if (FState<>msOnline) and (FState<>msDisconnection) then SetState(msOffline) else SetState(msDisconnection); // пока не пропадет сигнал CD (RLSD) end else SetState(msOffline); Inside:=False; end; procedure TCustomModem.DoCmd(Cmd: String); var S:String; begin S:=Cmd+#13; Write(S[1],Length(S)); end; procedure TCustomModem.OnCommStateChange(Sender: TObject); const NewStates:array [Boolean,Boolean] of TModemState = ( //RLSD=(0,1) (msNotReady,msNotReady ), // DSR=0 (msOffline, msOnline ) // DSR=1 ); var DSRState:Boolean; begin if coDsrSensitivity in Options then DSRState:=DSR else DSRState:=True; SetState(NewStates[DSRState,RLSD]); end; procedure TCustomModem.OnCommRxChar(Sender: TObject; Count: Integer); var Buf:String; i,j:Integer; c:Char; CR:Boolean; begin if FState = msOnline then begin if Assigned(FOnModemRxChar) then FOnModemRxChar(Self,Count); end else begin SetLength(Buf,Count); Read(Buf[1],Count); CR:=(LastLine<>'') and (LastLine[Length(LastLine)]=#13); for i:=1 to Length(Buf) do begin c:=Buf[i]; LastLine:=LastLine+c; if CR and (c=#10) then begin CR:=False; FResponse:=FResponse+LastLine; j:=High(ModemResponses); while (j>=0) and (Pos(ModemResponses[j],LastLine)<>1) do Dec(j); LastLine:=''; if (j>=0) then begin FResponseCode:=j; ProcessResponse; FResponse:=''; FResponseCode:=-1; end; end else CR:=c=#13; end; end; end; procedure TCustomModem.OnCommTxEmpty(Sender: TObject); begin if FState = msOnline then begin if Assigned(FOnModemTxEmpty) then FOnModemTxEmpty(Self); end; end; procedure TCustomModem.ProcessResponse; begin if (FState=msConnection) and (FResponseCode in [mrcNoCarrier,mrcError,mrcNoDialtone,mrcBusy,mrcNoAnswer]) then SetState(msOffline); if Assigned(FOnResponse) then FOnResponse(Self); end; function TCustomModem.GetResponseInLine: String; var i:Integer; c:Char; begin Result:=''; for i:=1 to Length(FResponse) do begin c:=FResponse[i]; if c=#13 then Result:=Result+'<cr>' else if c=#10 then Result:=Result+'<lf>' else if (#0<=c)and(c<' ') then Result:=Result+Format('<%d>',[Ord(c)]) else Result:=Result+c; end; end; procedure TCustomModem.Open; begin inherited Open; FState:=msOffline; SetDtrState(True); SetRtsState(True); OnCommStateChange(Self); end; procedure TCustomModem.Close; begin if not Enabled then exit; SetRtsState(False); SetDtrState(False); SetState(msOffline); inherited Close; end; procedure TCustomModem.SetState(NewState: TModemState); var OldState:TModemState; begin if NewState=FState then exit; OldState:=FState; FState:=NewState; case NewState of msNotOpen, msNotReady, msOffline: begin case OldState of msConnection,msOnline,msDisconnection: begin case NewState of msNotOpen: FResponseCode:=mrcClosed; msNotReady: FResponseCode:=mrcDsrDropped; end; case OldState of msConnection: if Assigned(FOnConnFailed) then FOnConnFailed(Self); msOnline,msDisconnection: if Assigned(FOnDisconnect) then FOnDisconnect(Self); end; end end; end; msOnline: if OldState=msDisconnection then FState:=msDisconnection else if Assigned(FOnConnect) then FOnConnect(Self); end; end; end.