text
stringlengths
14
6.51M
unit BasicEvents; interface uses Events, Classes, BackupInterfaces, Languages; const evnKind_FacEvent = 1; type TFacEvent = class( TEvent ) public constructor Create( aDateTick : integer; aDate : TDateTime; aTTL, aPriority : integer; aMetaFacility : string; aText : TMultiString; Tycoon, Town : string; aSender, aURL : string ); private fMetaFacility : string; fCount : integer; fTycoon : string; fTown : string; public property MetaFacility : string read fMetaFacility; property Count : integer read fCount; public function CanAssimilate( Event : TEvent ) : boolean; override; procedure Assimilate( Event : TEvent ); override; function Render : string; override; function Clone : TEvent; override; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; procedure RegisterBackup; implementation uses Protocol, Kernel, MetaInstances, ClassStorage, SysUtils; constructor TFacEvent.Create( aDateTick : integer; aDate : TDateTime; aTTL, aPriority : integer; aMetaFacility : string; aText : TMultiString; Tycoon, Town : string; aSender, aURL : string ); begin inherited Create( evnKind_FacEvent, aDateTick, aDate, aTTL, aPriority, aText, aSender, aURL ); fMetaFacility := aMetaFacility; fTycoon := Tycoon; fTown := Town; fCount := 1; end; function TFacEvent.CanAssimilate( Event : TEvent ) : boolean; begin result := ObjectIs( TFacEvent.ClassName, Event ) and (MetaFacility = TFacEvent(Event).MetaFacility) end; procedure TFacEvent.Assimilate( Event : TEvent ); begin inc( fCount, TFacEvent(Event).Count ); end; function TFacEvent.Render : string; var list : TStringList; enum : string; MF : TMetaFacility; i : integer; begin list := TStringList.Create; try list.Text := inherited Render; MF := TMetaFacility(TheClassStorage.ClassById[tidClassFamily_Facilities, MetaFacility]); for i := 0 to pred(LangList.Count) do begin enum := IntToStr(Count); if Count > 1 then enum := enum + ' ' + MF.PluralName_MLS.Values[LangList[i]] else enum := enum + ' ' + MF.Name_MLS.Values[LangList[i]]; list.Values[tidEventField_Text + IntToStr(i)] := Format( Text.Values[IntToStr(i)], [fTycoon, enum, fTown] ); end; result := list.Text; finally list.Free; end; end; function TFacEvent.Clone : TEvent; begin result := TFacEvent.Create( DateTick, Date, TTL, Priority, MetaFacility, CloneMultiString( Text ), fTycoon, fTown, Sender, URL ); TFacEvent(result).fCount := fCount; end; procedure TFacEvent.LoadFromBackup( Reader : IBackupReader ); begin inherited; fMetaFacility := Reader.ReadString( 'MetaFacility', '' ); fCount := Reader.ReadInteger( 'Count', 0 ); end; procedure TFacEvent.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteString( 'MetaFacility', fMetaFacility ); Writer.WriteInteger( 'Count', fCount ); end; // RegisterBackup procedure RegisterBackup; begin RegisterClass( TFacEvent ); end; end.
{ Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit LogViewer.MessageList.View; { Log message viewer. } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.ImageList, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, Vcl.ComCtrls, Vcl.ImgList, Vcl.Grids, Vcl.DBGrids, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Intf, FireDAC.Comp.DataSet, FireDAC.Stan.StorageBin, VirtualTrees, Spring, Spring.Collections, DDuce.Editor.Interfaces, DDuce.Logger.Interfaces, DDuce.Components.ValueList, DDuce.Components.DBGridView, LogViewer.Messages.Data, LogViewer.Watches.Data, LogViewer.Watches.View, LogViewer.Interfaces, LogViewer.CallStack.Data, LogViewer.CallStack.View, LogViewer.ValueList.View, LogViewer.MessageList.Settings, LogViewer.MessageList.LogNode, LogViewer.DisplayValues.Settings; {$REGION 'documentation'} { Message viewer responsible for displaying all messages from an associated log channel (IChannelReceiver receiver instance) } { TODO: - auto show message details, watches window and callstack (WinODS) } {$ENDREGION} type TfrmMessageList = class(TForm, ILogViewer) {$REGION 'designer controls'} dscMain : TDataSource; edtHandleType : TLabeledEdit; edtHeight : TLabeledEdit; edtMessageFilter : TButtonedEdit; edtPixelFormat : TLabeledEdit; edtWidth : TLabeledEdit; imgBitmap : TImage; imlMessageTypes : TImageList; pgcMessageData : TPageControl; pgcMessageDetails : TPageControl; pnlCallStack : TPanel; pnlCallStackTitle : TPanel; pnlCallStackWatch : TPanel; pnlFilter : TPanel; pnlImageViewer : TPanel; pnlLeft : TPanel; pnlLeftBottom : TPanel; pnlMessageContent : TPanel; pnlMessages : TPanel; pnlRawMessageData : TPanel; pnlRight : TPanel; pnlTextViewer : TPanel; pnlWatches : TPanel; sbxImage : TScrollBox; splLeftHorizontal : TSplitter; splLeftVertical : TSplitter; splVertical : TSplitter; tsDataSet : TTabSheet; tsImageViewer : TTabSheet; tsMessageView : TTabSheet; tsRawData : TTabSheet; tsTextViewer : TTabSheet; tsValueList : TTabSheet; {$ENDREGION} procedure edtMessageFilterChange(Sender: TObject); procedure edtMessageFilterKeyDown( Sender : TObject; var Key : Word; Shift : TShiftState ); procedure edtMessageFilterKeyUp( Sender : TObject; var Key : Word; Shift : TShiftState ); procedure chkAutoFilterClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure edtMessageFilterMouseEnter(Sender: TObject); procedure edtMessageFilterMouseLeave(Sender: TObject); procedure pnlMessagesResize(Sender: TObject); private class var FCounter : Integer; private FUpdate : Boolean; // trigger UpdateActions of Manager FMessageCount : Int64; FCurrentMsg : TLogMessage; FCallStack : IList<TCallStackData>; FWatches : TWatchList; FLogTreeView : TVirtualStringTree; FSubscriber : ISubscriber; FCallStackView : TfrmCallStackView; FWatchesView : TfrmWatchesView; FManager : ILogViewerManager; FEditorView : IEditorView; FExpandParents : Boolean; FLastParent : PVirtualNode; FLastNode : PVirtualNode; FVKPressed : Boolean; FSettings : TMessageListSettings; FAutoSizeColumns : Boolean; FValueList : TfrmValueList; FDataSet : TFDMemTable; FDBGridView : TDBGridView; FMiliSecondsBetweenSelection : Integer; {$REGION 'property access methods'} function GetManager: ILogViewerManager; function GetActions: ILogViewerActions; function GetSubscriber: ISubscriber; function GetForm: TCustomForm; function GetSettings: TMessageListSettings; function GetDisplayValuesSettings: TDisplayValuesSettings; function GetIsActiveView: Boolean; {$ENDREGION} {$REGION 'FLogTreeView event handlers'} procedure FLogTreeViewFilterCallback( Sender : TBaseVirtualTree; Node : PVirtualNode; Data : Pointer; var Abort : Boolean ); procedure FLogTreeViewClick(Sender: TObject); procedure FLogTreeViewDblClick(Sender: TObject); procedure FLogTreeViewFocusChanged( Sender : TBaseVirtualTree; Node : PVirtualNode; Column : TColumnIndex ); procedure FLogTreeViewFocusChanging( Sender : TBaseVirtualTree; OldNode : PVirtualNode; NewNode : PVirtualNode; OldColumn : TColumnIndex; NewColumn : TColumnIndex; var Allowed : Boolean ); procedure FLogTreeViewFreeNode( Sender : TBaseVirtualTree; Node : PVirtualNode ); procedure FLogTreeViewGetImageIndex( Sender : TBaseVirtualTree; Node : PVirtualNode; Kind : TVTImageKind; Column : TColumnIndex; var Ghosted : Boolean; var ImageIndex : TImageIndex ); procedure FLogTreeViewGetText( Sender : TBaseVirtualTree; Node : PVirtualNode; Column : TColumnIndex; TextType : TVSTTextType; var CellText : string ); procedure FLogTreeViewInitNode( Sender : TBaseVirtualTree; ParentNode : PVirtualNode; Node : PVirtualNode; var InitialStates : TVirtualNodeInitStates ); procedure FLogTreeViewKeyPress( Sender : TObject; var Key : Char ); procedure FLogTreeViewBeforeCellPaint( Sender : TBaseVirtualTree; TargetCanvas : TCanvas; Node : PVirtualNode; Column : TColumnIndex; CellPaintMode : TVTCellPaintMode; CellRect : TRect; var ContentRect : TRect ); procedure FLogTreeViewBeforeItemPaint( Sender : TBaseVirtualTree; TargetCanvas : TCanvas; Node : PVirtualNode; ItemRect : TRect; var CustomDraw : Boolean ); procedure FLogTreeViewPaintText( Sender : TBaseVirtualTree; const TargetCanvas : TCanvas; Node : PVirtualNode; Column : TColumnIndex; TextType : TVSTTextType ); procedure FLogTreeViewHotChange( Sender : TBaseVirtualTree; OldNode : PVirtualNode; NewNode : PVirtualNode ); procedure FLogTreeViewAfterGetMaxColumnWidth( Sender : TVTHeader; Column : TColumnIndex; var MaxWidth : Integer ); {$ENDREGION} procedure FSettingsChanged(Sender: TObject); function GetMilliSecondsBetweenSelection: Integer; procedure EnsureIsActiveViewIfFocused; protected procedure FSubscriberReceiveMessage( Sender : TObject; AStream : TStream ); procedure Clear; procedure AutoFitColumns; procedure ApplySettings; procedure ProcessMessage(AStream: TStream); procedure AddMessageToTree(const AMessage: TLogMessage); procedure UpdateCallStackDisplay(ALogNode: TLogNode); procedure UpdateMessageDetails(ALogNode: TLogNode); procedure UpdateComponentDisplay(ALogNode: TLogNode); procedure UpdateBitmapDisplay(ALogNode: TLogNode); procedure UpdateDataSetDisplay(ALogNode: TLogNode); procedure UpdateTextDisplay(ALogNode: TLogNode); procedure UpdateTextStreamDisplay(ALogNode: TLogNode); procedure UpdateColorDisplay(ALogNode: TLogNode); procedure UpdateValueDisplay(ALogNode: TLogNode); procedure UpdateLogTreeView; procedure ClearMessageDetailsControls; procedure CreateLogTreeView; procedure CreateEditor; procedure CreateCallStackView; procedure CreateWatchesView; procedure CreateValueListView; procedure CollapseAll; procedure ExpandAll; procedure SetFocusToFilter; procedure SelectAll; procedure ClearSelection; procedure Activate; override; procedure UpdateActions; override; procedure UpdateView; procedure GotoFirst; procedure GotoLast; property IsActiveView: Boolean read GetIsActiveView; property Manager: ILogViewerManager read GetManager; property Actions: ILogViewerActions read GetActions; property Subscriber: ISubscriber read GetSubscriber; property Settings: TMessageListSettings read GetSettings; property DisplayValuesSettings: TDisplayValuesSettings read GetDisplayValuesSettings; property Form: TCustomForm read GetForm; property MilliSecondsBetweenSelection: Integer read GetMilliSecondsBetweenSelection; public constructor Create( AOwner : TComponent; AManager : ILogViewerManager; ASubscriber : ISubscriber; ASettings : TMessageListSettings ); reintroduce; virtual; procedure AfterConstruction; override; procedure BeforeDestruction; override; end; implementation uses System.StrUtils, System.UITypes, System.DateUtils, System.Math, System.UIConsts, Spring.Helpers, DDuce.Factories.VirtualTrees, DDuce.Editor.Factories, DDuce.Reflect, DDuce.Utils, DDuce.Factories.GridView, DDuce.Logger, DDuce.ObjectInspector.zObjectInspector, DDuce.DynamicRecord, LogViewer.Manager, LogViewer.Factories, LogViewer.Resources; {$R *.dfm} {$REGION 'construction and destruction'} constructor TfrmMessageList.Create(AOwner: TComponent; AManager : ILogViewerManager; ASubscriber: ISubscriber; ASettings: TMessageListSettings); begin inherited Create(AOwner); Guard.CheckNotNull(AManager, 'AManager'); Guard.CheckNotNull(ASubscriber, 'ASubscriber'); Guard.CheckNotNull(ASettings, 'ASettings'); FManager := AManager; FSubscriber := ASubscriber; FSettings := ASettings; end; procedure TfrmMessageList.AfterConstruction; begin inherited AfterConstruction; Inc(FCounter); FMiliSecondsBetweenSelection := -1; edtMessageFilter.OnRightButtonClick := FManager.Actions.Items['actFilterMessages'].OnExecute; FExpandParents := True; CreateEditor; CreateLogTreeView; CreateWatchesView; CreateCallStackView; CreateValueListView; pgcMessageData.ActivePage := tsMessageView; // tsRawData.TabVisible := False; // tsMessageView.TabVisible := False; // tsValueList.TabVisible := False; // tsImageViewer.TabVisible := False; // tsDataSet.TabVisible := False; // tsTextViewer.TabVisible := False; Caption := Copy(ClassName, 2, Length(ClassName)) + IntToStr(FCounter); Subscriber.OnReceiveMessage.Add(FSubscriberReceiveMessage); FSettings.OnChanged.Add(FSettingsChanged); FLogTreeView.PopupMenu := Manager.Menus.LogTreeViewerPopupMenu; FDataSet := TFDMemTable.Create(Self); FDBGridView := TGridViewFactory.CreateDBGridView(Self, tsDataSet, dscMain); ApplySettings; end; procedure TfrmMessageList.BeforeDestruction; begin Logger.Track(Self, 'BeforeDestruction'); FEditorView.Visible := False; if Assigned(FSettings) then begin FSettings.LeftPanelWidth := pnlLeft.Width; FSettings.RightPanelWidth := pnlRight.Width; FSettings.OnChanged.Remove(FSettingsChanged); FSettings := nil; end; if Assigned(FSubscriber) then begin FSubscriber.OnReceiveMessage.Remove(FSubscriberReceiveMessage); FSubscriber := nil; end; FCallStack := nil; FreeAndNil(FValueList); FreeAndNil(FWatches); FreeAndNIl(FWatchesView); FreeAndNil(FCallStackView); FreeAndNil(FLogTreeView); FreeAndNil(FDataSet); FreeAndNil(FDBGridView); inherited BeforeDestruction; end; procedure TfrmMessageList.CreateCallStackView; begin FCallStack := TCollections.CreateObjectList<TCallStackData>; FCallStackView := TLogViewerFactories.CreateCallStackView( Self, pnlCallStack, FCallStack as IObjectList, DisplayValuesSettings ); end; procedure TfrmMessageList.CreateEditor; begin FEditorView := TEditorFactories.CreateView( pnlTextViewer, Manager.EditorManager ); FEditorView.Settings.EditorOptions.WordWrapEnabled := True; end; procedure TfrmMessageList.CreateLogTreeView; var C : TVirtualTreeColumn; B : Boolean; begin FLogTreeView := TVirtualStringTreeFactory.CreateTreeList(Self, pnlMessages); FLogTreeView.AlignWithMargins := False; FLogTreeView.TreeOptions.AutoOptions := FLogTreeView.TreeOptions.AutoOptions + [toAutoSpanColumns]; FLogTreeView.TreeOptions.PaintOptions := [ toHideFocusRect, toHotTrack, toPopupMode, toShowBackground, toShowButtons, toShowDropmark, toStaticBackground, toShowRoot, toShowVertGridLines, toThemeAware, toUseBlendedImages, toUseBlendedSelection, toStaticBackground, toUseExplorerTheme ]; FLogTreeView.NodeDataSize := SizeOf(TLogNode); FLogTreeView.Images := imlMessageTypes; FLogTreeView.HintMode := hmTooltip; FLogTreeView.ShowHint := True; FLogTreeView.OnBeforeItemPaint := FLogTreeViewBeforeItemPaint; FLogTreeView.OnBeforeCellPaint := FLogTreeViewBeforeCellPaint; FLogTreeView.OnFocusChanged := FLogTreeViewFocusChanged; FLogTreeView.OnFocusChanging := FLogTreeViewFocusChanging; FLogTreeView.OnClick := FLogTreeViewClick; FLogTreeView.OnDblClick := FLogTreeViewDblClick; FLogTreeView.OnHotChange := FLogTreeViewHotChange; FLogTreeView.OnInitNode := FLogTreeViewInitNode; FLogTreeView.OnFreeNode := FLogTreeViewFreeNode; FLogTreeView.OnGetText := FLogTreeViewGetText; FLogTreeView.OnPaintText := FLogTreeViewPaintText; FLogTreeView.OnGetImageIndex := FLogTreeViewGetImageIndex; FLogTreeView.OnAfterGetMaxColumnWidth := FLogTreeViewAfterGetMaxColumnWidth; FLogTreeView.OnKeyPress := FLogTreeViewKeyPress; B := Supports(Subscriber, IWinIPC) or Supports(Subscriber, IZMQ); C := FLogTreeView.Header.Columns.Add; C.Text := ''; C.Margin := 0; C.Spacing := 0; C.Width := 10; C.MinWidth := 10; C.MaxWidth := 10; C := FLogTreeView.Header.Columns.Add; C.Text := ''; C.Options := C.Options - [coSmartResize, coAutoSpring]; C.Width := 100; C.MinWidth := 60; C.MaxWidth := 250; C := FLogTreeView.Header.Columns.Add; C.Text := SName; C.Options := C.Options + [coSmartResize, coAutoSpring]; if not B then C.Options := C.Options - [coVisible]; C.Width := 100; C.MinWidth := 20; C.MaxWidth := 2000; C := FLogTreeView.Header.Columns.Add; C.Text := SValue; C.Options := C.Options + [coSmartResize, coAutoSpring]; C.Width := 100; C.MinWidth := 20; C.MaxWidth := 2000; C := FLogTreeView.Header.Columns.Add; C.Text := SType; C.Options := C.Options + [coSmartResize, coAutoSpring]; if not B then C.Options := C.Options - [coVisible]; C.Width := 70; C.MinWidth := 0; C.MaxWidth := 2000; C := FLogTreeView.Header.Columns.Add; C.Text := STimestamp; C.Width := 80; C.MinWidth := 80; C.MaxWidth := 80; FLogTreeView.Header.AutoSizeIndex := COLUMN_VALUETYPE; FLogTreeView.Header.MainColumn := COLUMN_MAIN; FLogTreeView.Header.Options := FLogTreeView.Header.Options + [hoFullRepaintOnResize]; end; procedure TfrmMessageList.CreateValueListView; begin FValueList := TfrmValueList.Create(Self); AssignFormParent(FValueList, tsValueList); end; procedure TfrmMessageList.CreateWatchesView; begin FWatches := TWatchList.Create; FWatchesView := TLogViewerFactories.CreateWatchesView( Self, pnlLeftBottom, FWatches, FSettings.WatchSettings, DisplayValuesSettings ); end; {$ENDREGION} {$REGION 'property access methods'} function TfrmMessageList.GetActions: ILogViewerActions; begin Result := Manager as ILogViewerActions; end; function TfrmMessageList.GetDisplayValuesSettings: TDisplayValuesSettings; begin if Assigned(Manager) and Assigned(Manager.Settings) then Result := Manager.Settings.DisplayValuesSettings else Result := nil; end; function TfrmMessageList.GetForm: TCustomForm; begin Result := Self; end; function TfrmMessageList.GetIsActiveView: Boolean; begin Result := Assigned(Manager.ActiveView) and (Manager.ActiveView = (Self as ILogViewer)); end; function TfrmMessageList.GetManager: ILogViewerManager; begin Result := FManager; end; function TfrmMessageList.GetMilliSecondsBetweenSelection: Integer; begin Result := FMiliSecondsBetweenSelection; end; function TfrmMessageList.GetSubscriber: ISubscriber; begin Result := FSubscriber; end; function TfrmMessageList.GetSettings: TMessageListSettings; begin Result := FSettings; end; {$ENDREGION} {$REGION 'event handlers'} {$REGION 'edtMessageFilter'} procedure TfrmMessageList.edtMessageFilterChange(Sender: TObject); begin if edtMessageFilter.Text <> '' then begin edtMessageFilter.Font.Style := [fsBold]; edtMessageFilter.Color := clYellow; end else begin edtMessageFilter.Font.Style := []; edtMessageFilter.Color := clBtnFace; end; if Settings.AutoFilterMessages then UpdateLogTreeView; end; procedure TfrmMessageList.edtMessageFilterKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var A : Boolean; B : Boolean; C : Boolean; D : Boolean; E : Boolean; F : Boolean; G : Boolean; H : Boolean; begin // SHIFTED and ALTED keycombinations A := (ssAlt in Shift) or (ssShift in Shift); { Single keys that need to be handled by the edit control like all displayable characters but also HOME and END } B := (Key in VK_EDIT_KEYS) and (Shift = []); { CTRL-keycombinations that need to be handled by the edit control like CTRL-C for clipboard copy. } C := (Key in VK_CTRL_EDIT_KEYS) {and (Shift = [ssCtrlOS])}; { SHIFT-keycombinations that need to be handled by the edit control for uppercase characters but also eg. SHIFT-HOME for selections. } D := (Key in VK_SHIFT_EDIT_KEYS) and (Shift = [ssShift]); { Only CTRL key is pressed. } E := (Key = VK_CONTROL) {and (Shift = [ssCtrlOS])}; { Only SHIFT key is pressed. } F := (Key = VK_SHIFT) and (Shift = [ssShift]); { Only (left) ALT key is pressed. } G := (Key = VK_MENU) and (Shift = [ssAlt]); { ESCAPE } H := Key = VK_ESCAPE; if not (A or B or C or D or E or F or G or H) then begin FVKPressed := True; Key := 0; end { Prevents jumping to the application's main menu which happens by default if ALT is pressed. } else if G then begin Key := 0; end; end; procedure TfrmMessageList.edtMessageFilterKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if FVKPressed and FLogTreeView.Enabled then begin FLogTreeView.Perform(WM_KEYDOWN, Key, 0); if Visible and FLogTreeView.CanFocus then FLogTreeView.SetFocus; end; FVKPressed := False; end; procedure TfrmMessageList.edtMessageFilterMouseEnter(Sender: TObject); begin if not edtMessageFilter.Focused then edtMessageFilter.Color := clWhite; end; procedure TfrmMessageList.edtMessageFilterMouseLeave(Sender: TObject); begin if not edtMessageFilter.Focused then edtMessageFilter.Color := clBtnFace; end; {$ENDREGION} {$REGION 'FLogTreeView'} procedure TfrmMessageList.FLogTreeViewBeforeItemPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; ItemRect: TRect; var CustomDraw: Boolean); //var // LN : TLogNode; // DVS : TDisplayValuesSettings; // S : string; begin // LN := Sender.GetNodeData<TLogNode>(Node); // DVS := Manager.Settings.DisplayValuesSettings; // if LN.MessageType in [lmtEnterMethod, lmtLeaveMethod] then // begin // CustomDraw := True; // DVS.Tracing.AssignTo(TargetCanvas); // TargetCanvas.Brush.Color := $00EEEEEE; // TargetCanvas.FillRect(ItemRect); // S := LN.Text; // TargetCanvas.TextRect(ItemRect, S); // end; end; procedure TfrmMessageList.FLogTreeViewAfterGetMaxColumnWidth(Sender: TVTHeader; Column: TColumnIndex; var MaxWidth: Integer); begin MaxWidth := MaxWidth - (MaxWidth div 5); // 20 % less than max end; procedure TfrmMessageList.FLogTreeViewClick(Sender: TObject); begin // FUpdate := True; // FAutoSizeColumns := False; end; procedure TfrmMessageList.FLogTreeViewDblClick(Sender: TObject); begin AutoFitColumns; end; procedure TfrmMessageList.FLogTreeViewBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); var LN : TLogNode; DVS : TDisplayValuesSettings; begin LN := Sender.GetNodeData<TLogNode>(Node); DVS := Manager.Settings.DisplayValuesSettings; if LN.MessageType in [lmtEnterMethod, lmtLeaveMethod] then begin DVS.Tracing.AssignTo(TargetCanvas); //TargetCanvas.Brush.Color := $00EEEEEE; TargetCanvas.FillRect(CellRect); end; if Column = COLUMN_LEVEL then begin // if LN.MessageType in [lmtEnterMethod, lmtLeaveMethod] then // TargetCanvas.Brush.Color := $00EEEEEE // else if LN.MessageType = lmtValue then // TargetCanvas.Brush.Color := clGreen // else if LN.MessageType = lmtObject then // TargetCanvas.Brush.Color := clYellow; TargetCanvas.FillRect(CellRect); end; end; procedure TfrmMessageList.FLogTreeViewFocusChanging(Sender: TBaseVirtualTree; OldNode, NewNode: PVirtualNode; OldColumn, NewColumn: TColumnIndex; var Allowed: Boolean); var LN : TLogNode; begin //Todo: merge with Changed? //The CallStack is only updated if the parent changes Allowed := OldNode <> NewNode; if Allowed and ( (OldNode = nil) or (NewNode = nil) or (OldNode.Parent <> NewNode.Parent) ) then begin LN := Sender.GetNodeData<TLogNode>(NewNode); Guard.CheckNotNull(LN, 'LogNode'); UpdateCallStackDisplay(LN); end; end; procedure TfrmMessageList.FLogTreeViewFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); var LN : TLogNode; begin LN := Sender.GetNodeData<TLogNode>(Node); Guard.CheckNotNull(LN, 'LogNode'); UpdateMessageDetails(LN); end; procedure TfrmMessageList.FLogTreeViewFilterCallback(Sender: TBaseVirtualTree; Node: PVirtualNode; Data: Pointer; var Abort: Boolean); var LN : TLogNode; B : Boolean; begin LN := Sender.GetNodeData<TLogNode>(Node); if Assigned(LN) then begin if (LN.MessageType = lmtText) and (LN.Highlighter <> '') then begin B := Settings.VisibleValueTypes.IndexOf(LN.Highlighter) <> -1; end else begin B := LN.MessageType in Settings.VisibleMessageTypes; end; if edtMessageFilter.Text <> '' then B := B and (ContainsText(LN.Text, edtMessageFilter.Text) or ContainsText(LN.ValueName, edtMessageFilter.Text) or ContainsText(LN.Value, edtMessageFilter.Text)); Sender.IsVisible[Node] := B; end; end; procedure TfrmMessageList.FLogTreeViewGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: TImageIndex); var ND: TLogNode; begin ND := Sender.GetNodeData<TLogNode>(Node); Guard.CheckNotNull(ND, 'ND'); if (Kind in [ikNormal, ikSelected]) and (Column = COLUMN_MAIN) then begin if Integer(ND.MessageType) < imlMessageTypes.Count then begin ImageIndex := Integer(ND.MessageType); end else if ND.MessageType = lmtDataSet then begin ImageIndex := 20; end else if ND.MessageType = lmtAction then begin ImageIndex := 21; end else if ND.MessageType = lmtText then begin ImageIndex := 8; end else begin ImageIndex := 0; end; end; end; procedure TfrmMessageList.FLogTreeViewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var LN : TLogNode; S : string; LDelim : array of string; LTrim : TArray<string>; begin LN := Sender.GetNodeData<TLogNode>(Node); Guard.CheckNotNull(LN, 'ND'); if Column = COLUMN_LEVEL then begin CellText := LN.LogLevel.ToString; end else if Column = COLUMN_MAIN then begin case LN.MessageType of lmtValue: CellText := SValue; lmtAlphaColor, lmtColor: CellText := SColor; lmtBitmap: CellText := SBitmap; lmtComponent: CellText := SComponent; lmtObject: CellText := SObject; lmtPersistent: CellText := SPersistent; lmtInterface: CellText := SInterface; lmtStrings: CellText := SStrings; lmtCheckpoint: CellText := SCheckpoint; lmtDataSet: CellText := SDataSet; lmtScreenShot: CellText := SScreenShot; lmtText: CellText := SText; lmtAction: CellText := SAction; else CellText := LN.Text end; end else if Column = COLUMN_VALUENAME then begin CellText := LN.ValueName; end else if Column = COLUMN_VALUETYPE then begin CellText := LN.ValueType; end else if Column = COLUMN_VALUE then begin LDelim := [sLineBreak]; LTrim := LN.Value.Split(LDelim, 1, TStringSplitOptions.ExcludeEmpty); if Length(LTrim) > 0 then S := LTrim[0]; if (S.Length > MAX_TEXTLENGTH_VALUECOLUMN) then S := S.Substring(0, MAX_TEXTLENGTH_VALUECOLUMN); CellText := S; end else if Column = COLUMN_TIMESTAMP then begin if YearOf(LN.TimeStamp) = YearOf(Now) then // sanity check CellText := FormatDateTime('hh:nn:ss:zzz', LN.TimeStamp); end; end; procedure TfrmMessageList.FLogTreeViewHotChange(Sender: TBaseVirtualTree; OldNode, NewNode: PVirtualNode); var LN1 : TLogNode; LN2 : TLogNode; begin LN1 := Sender.GetNodeData<TLogNode>(NewNode); LN2 := Sender.GetNodeData<TLogNode>(Sender.FocusedNode); if Assigned(LN1) and Assigned(LN2) then begin FMiliSecondsBetweenSelection := MilliSecondsBetween(LN1.TimeStamp, LN2.TimeStamp); end else FMiliSecondsBetweenSelection := -1; end; procedure TfrmMessageList.FLogTreeViewInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var LN : TLogNode; // class type I : Integer; S : string; SL : TStringList; LText : string; begin LN := TLogNode.Create; Node.SetData(LN); LN.MessageData := FCurrentMsg.Data; LN.TimeStamp := FCurrentMsg.TimeStamp; LN.MessageType := TLogMessageType(FCurrentMsg.MsgType); LN.VTNode := Node; LN.LogLevel := FCurrentMsg.LogLevel; LN.Id := FMessageCount; LText := string(FCurrentMsg.Text); case LN.MessageType of lmtValue, lmtComponent, lmtStrings, lmtPersistent, lmtObject, lmtInterface: begin S := LText; I := S.IndexOf('='); LN.ValueName := Copy(S, 1, I); LN.Value := Copy(S, I + 3, S.Length); // ' = ' if LN.Value.StartsWith(#13#10) then // multiline values LN.Value := Copy(LN.Value, 3, LN.Value.Length); LN.ValueType := ExtractText(LN.ValueName, '(', ')'); I := S.IndexOf('('); if I > 1 then LN.ValueName := Copy(S, 1, I); LN.Text := ''; end; lmtDataSet: begin LN.ValueName := LText; LN.ValueType := 'TDataSet'; end; lmtAction: begin LN.ValueName := LText; LN.ValueType := 'TAction'; end; lmtBitmap, lmtScreenShot: begin LN.ValueName := LText; LN.ValueType := 'TBitmap'; end; lmtAlphaColor, lmtColor: begin S := string(FCurrentMsg.Text); I := S.IndexOf('='); LN.ValueName := Copy(S, 1, I); LN.Value := Copy(S, I + 3, S.Length); LN.ValueType := ExtractText(LN.ValueName, '(', ')'); I := S.IndexOf('('); if I > 1 then LN.ValueName := Copy(S, 1, I); LN.Text := ''; end; lmtEnterMethod, lmtLeaveMethod, lmtInfo, lmtWarning, lmtError, lmtConditional: begin LN.Text := string(FCurrentMsg.Text); end; lmtText: begin SL := TStringList.Create; try SL.Text := Trim(string(FCurrentMsg.Text)); if SL.Count > 0 then begin S := SL[0]; I := S.IndexOf('('); if I > 1 then begin LN.ValueName := Copy(S, 1, I); LN.Highlighter := Trim(ExtractText(S, '(', ')')); end; if I <> -1 then SL.Delete(0); end; LN.Value := SL.Text; finally SL.Free; end; end; lmtCheckpoint: begin S := string(FCurrentMsg.Text); I := S.IndexOf('#'); LN.ValueName := Copy(S, 1, I); LN.Value := Copy(S, I + 2, S.Length); end end; end; procedure TfrmMessageList.FLogTreeViewFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var LN: TLogNode; begin LN := Sender.GetNodeData<TLogNode>(Node); LN.Free; end; procedure TfrmMessageList.FLogTreeViewKeyPress(Sender: TObject; var Key: Char); begin if not edtMessageFilter.Focused then begin edtMessageFilter.SetFocus; PostMessage(edtMessageFilter.Handle, WM_CHAR, Ord(Key), 0); // required to prevent the invocation of accelerator keys! Key := #0; end; end; { Used to apply custom settings to TargetCanvas.Font. } procedure TfrmMessageList.FLogTreeViewPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); var LN : TLogNode; DVS : TDisplayValuesSettings; begin LN := Sender.GetNodeData<TLogNode>(Node); Guard.CheckNotNull(LN, 'ND'); DVS := Manager.Settings.DisplayValuesSettings; if not Assigned(Manager) then Exit; if Column = COLUMN_MAIN then begin case LN.MessageType of lmtInfo: begin DVS.Info.AssignTo(TargetCanvas.Font); end; lmtWarning: begin DVS.Warning.AssignTo(TargetCanvas.Font); end; lmtError: begin DVS.Error.AssignTo(TargetCanvas.Font); end; lmtValue, lmtComponent, lmtAlphaColor, lmtColor, lmtBitmap, lmtStrings, lmtObject, lmtPersistent, lmtInterface: begin TargetCanvas.Font.Color := clDkGray; TargetCanvas.Font.Size := 7; end; lmtEnterMethod: begin DVS.Enter.AssignTo(TargetCanvas.Font); end; lmtLeaveMethod: begin DVS.Leave.AssignTo(TargetCanvas.Font); end; lmtCheckpoint: begin DVS.CheckPoint.AssignTo(TargetCanvas.Font); end; lmtAction: begin DVS.Action.AssignTo(TargetCanvas.Font); end; end; end else if Column = COLUMN_LEVEL then begin TargetCanvas.Font.Color := clDkGray; TargetCanvas.Font.Size := 6; end else if Column = COLUMN_VALUENAME then begin DVS.ValueName.AssignTo(TargetCanvas.Font); end else if Column = COLUMN_VALUETYPE then begin DVS.ValueType.AssignTo(TargetCanvas.Font); end else if Column = COLUMN_VALUE then begin DVS.Value.AssignTo(TargetCanvas.Font); end else if Column = COLUMN_TIMESTAMP then begin DVS.TimeStamp.AssignTo(TargetCanvas.Font); end; end; procedure TfrmMessageList.pnlMessagesResize(Sender: TObject); begin FUpdate := True; FAutoSizeColumns := False; end; {$ENDREGION} procedure TfrmMessageList.chkAutoFilterClick(Sender: TObject); begin Settings.AutoFilterMessages := (Sender as TCheckBox).Checked; end; procedure TfrmMessageList.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmMessageList.FSubscriberReceiveMessage(Sender: TObject; AStream: TStream); begin ProcessMessage(AStream); end; procedure TfrmMessageList.FSettingsChanged(Sender: TObject); begin ApplySettings; end; {$ENDREGION} {$REGION 'private methods'} { Makes sure the active view is the current view when it is focused. } procedure TfrmMessageList.EnsureIsActiveViewIfFocused; var B : Boolean; begin B := Focused; if not B and Assigned(Parent) then begin if Parent.Focused then B := True; end; if B then begin Activate; end; end; {$ENDREGION} {$REGION 'protected methods'} procedure TfrmMessageList.ApplySettings; begin // chkAutoFilter.Checked := Settings.AutoFilterMessages; pnlLeft.Width := Settings.LeftPanelWidth; pnlRight.Width := Settings.RightPanelWidth; // DisplayValuesSettings.TimeStamp.AssignTo(edtTimeStamp.Font); // edtTimeStamp.Alignment := DisplayValuesSettings.TimeStamp.HorizontalAlignment; // DisplayValuesSettings.ValueName.AssignTo(edtValueName.Font); // edtValueName.Alignment := DisplayValuesSettings.ValueName.HorizontalAlignment; // DisplayValuesSettings.ValueType.AssignTo(edtValueType.Font); // edtValueType.Alignment := DisplayValuesSettings.ValueType.HorizontalAlignment; // DisplayValuesSettings.Value.AssignTo(edtValue.Font); // edtValue.Alignment := DisplayValuesSettings.Value.HorizontalAlignment; FUpdate := True; end; procedure TfrmMessageList.AutoFitColumns; begin Logger.Track(Self, 'AutoFitColumns'); FLogTreeView.Header.AutoFitColumns(False, smaUseColumnOption, 2); FAutoSizeColumns := True; end; procedure TfrmMessageList.Activate; begin inherited Activate; Manager.ActiveView := Self as ILogViewer; Manager.EditorManager.ActiveView := FEditorView; end; { Parses message data from the TLogMessage record. } procedure TfrmMessageList.AddMessageToTree(const AMessage: TLogMessage); begin FLogTreeView.BeginUpdate; try case TLogMessageType(AMessage.MsgType) of lmtEnterMethod: begin FLastNode := FLogTreeView.AddChild(FLastParent, nil); if FExpandParents then FLogTreeView.Expanded[FLastParent] := True; FLastParent := FLastNode; end; lmtLeaveMethod: begin if (FLastParent = nil) or (FLastParent^.Parent = FLogTreeView.RootNode) then begin FLastNode := FLogTreeView.AddChild(nil, nil); FLastParent := nil; end else begin FLastNode := FLogTreeView.AddChild(FLastParent.Parent, nil); FLastParent := FLastNode.Parent; end; end else begin FLastNode := FLogTreeView.AddChild(FLastParent, nil); end; end; // case if FExpandParents then begin FLogTreeView.Expanded[FLastParent] := True; end; if AutoScroll then FAutoSizeColumns := False else FAutoSizeColumns := True; finally FLogTreeView.EndUpdate; end; end; procedure TfrmMessageList.ClearMessageDetailsControls; begin imgBitmap.Picture := nil; edtWidth.Text := ''; edtHeight.Text := ''; edtPixelFormat.Text := ''; edtHandleType.Text := ''; FDataSet.Active := False; FEditorView.Clear; if Assigned(FValueList) then FValueList.Clear; end; { Reads the received message stream from the active logchannel . } { Message layout in stream 1. Message type (1 byte) => TLogMessage.MsgType (TLogMessageType) 2. Log level (1 byte) 3. Reserved (1 byte) 4. Reserved (1 byte) 5. Timestamp (8 byte) => TLogMessage.TimeStamp 6. Text size (4 byte) 7. Text (variable size) => TLogMessage.Text 8. Data size (4 byte) 9. Data (variable size) => TLogMessage.Data TLogMessage = packed record MsgType : Byte; // (TLogMessageType) Level : Byte; Reserved : Byte; Reserved : Byte; TimeStamp : TDateTime; Text : UTF8String; Data : TStream; end; } procedure TfrmMessageList.ProcessMessage(AStream: TStream); var LTextSize : Integer; LDataSize : Integer; S : string; I : Integer; LName : string; LType : string; LValue : string; begin Guard.CheckNotNull(AStream, 'AStream'); LTextSize := 0; LDataSize := 0; Inc(FMessageCount); AStream.Seek(0, soFromBeginning); AStream.ReadBuffer(FCurrentMsg.MsgType); AStream.ReadBuffer(FCurrentMsg.LogLevel); AStream.ReadBuffer(FCurrentMsg.Reserved1); AStream.ReadBuffer(FCurrentMsg.Reserved2); AStream.ReadBuffer(FCurrentMsg.TimeStamp); AStream.ReadBuffer(LTextSize); if LTextSize > 0 then begin SetLength(FCurrentMsg.Text, LTextSize); AStream.ReadBuffer(FCurrentMsg.Text[1], LTextSize); end; AStream.ReadBuffer(LDataSize); if LDataSize > 0 then begin FCurrentMsg.Data := TMemoryStream.Create; FCurrentMsg.Data.Size := 0; FCurrentMsg.Data.Position := 0; FCurrentMsg.Data.CopyFrom(AStream, LDataSize); end else FCurrentMsg.Data := nil; case TLogMessageType(FCurrentMsg.MsgType) of lmtCounter: begin S := string(FCurrentMsg.Text); I := S.IndexOf('='); LName := Copy(S, 1, I); LValue := Copy(S, I + 2, S.Length); FWatches.Add( LName, LType, LValue, FMessageCount, FCurrentMsg.TimeStamp, True, True ); FWatchesView.UpdateView(FMessageCount); end; lmtWatch: begin S := string(FCurrentMsg.Text); I := S.IndexOf('='); LName := Copy(S, 1, I); LValue := Copy(S, I + 2, S.Length); LType := ExtractText(LName, '(', ')'); I := S.IndexOf('('); if I > 1 then LName := Copy(S, 1, I); FWatches.Add( LName, LType, LValue, FMessageCount, FCurrentMsg.TimeStamp, True, False ); FWatchesView.UpdateView(FMessageCount); end; lmtClear: begin Clear; end else begin AddMessageToTree(FCurrentMsg); if Settings.AutoScrollMessages then begin FLogTreeView.FocusedNode := FLogTreeView.GetLast; FLogTreeView.Selected[FLogTreeView.FocusedNode] := True; end; FUpdate := True; end; end; // case end; {$REGION 'Commands'} procedure TfrmMessageList.Clear; begin ClearMessageDetailsControls; FWatches.Clear; FEditorView.Clear; FCallStack.Clear; FLogTreeView.Clear; FMessageCount := 0; FLastNode := nil; FLastParent := nil; FUpdate := True; end; procedure TfrmMessageList.ClearSelection; begin FLogTreeView.ClearSelection; end; procedure TfrmMessageList.CollapseAll; begin FLogTreeView.FullCollapse; FUpdate := True; FAutoSizeColumns := False; end; procedure TfrmMessageList.ExpandAll; begin FLogTreeView.FullExpand; FUpdate := True; FAutoSizeColumns := False; end; procedure TfrmMessageList.GotoFirst; begin if FWatchesView.HasFocus then begin FWatchesView.GotoFirst; end else begin FLogTreeView.FocusedNode := FLogTreeView.GetFirst; FLogTreeView.Selected[FLogTreeView.FocusedNode] := True; FUpdate := True; FAutoSizeColumns := False; end; end; procedure TfrmMessageList.GotoLast; begin if FWatchesView.HasFocus then begin FWatchesView.GotoLast; end else begin FLogTreeView.FocusedNode := FLogTreeView.GetLast; FLogTreeView.Selected[FLogTreeView.FocusedNode] := True; FUpdate := True; FAutoSizeColumns := False; end; end; procedure TfrmMessageList.SelectAll; begin FLogTreeView.SelectAll(False); end; procedure TfrmMessageList.SetFocusToFilter; begin if edtMessageFilter.CanFocus then edtMessageFilter.SetFocus; end; {$ENDREGION} {$REGION 'Display updating'} procedure TfrmMessageList.UpdateBitmapDisplay(ALogNode: TLogNode); begin if Assigned(ALogNode.MessageData) then begin tsValueList.TabVisible := False; tsImageViewer.TabVisible := False; tsDataSet.TabVisible := False; tsTextViewer.TabVisible := False; ALogNode.MessageData.Position := 0; imgBitmap.Picture.Bitmap.LoadFromStream(ALogNode.MessageData); pgcMessageDetails.ActivePage := tsImageViewer; with imgBitmap.Picture do begin edtWidth.Text := Bitmap.Width.ToString; edtHeight.Text := Bitmap.Height.ToString; edtPixelFormat.Text := Reflect.EnumName(Bitmap.PixelFormat); edtHandleType.Text := Reflect.EnumName(Bitmap.HandleType); end; end; end; procedure TfrmMessageList.UpdateCallStackDisplay(ALogNode: TLogNode); var I : Integer; CSD : TCallStackData; LN : TLogNode; LN2 : TLogNode; VN : PVirtualNode; begin FCallStack.Clear; VN := ALogNode.VTNode; I := FLogTreeView.GetNodeLevel(VN); while I > 0 do begin LN := FLogTreeView.GetNodeData<TLogNode>(VN.Parent); CSD := TCallStackData.Create; CSD.Title := LN.Text; CSD.Level := I; LN2 := FLogTreeView.GetNodeData<TLogNode>(LN.VTNode.NextSibling); if Assigned(LN2) then begin CSD.Duration := MilliSecondsBetween(LN2.TimeStamp, LN.TimeStamp); end; FCallStack.Add(CSD); VN := VN.Parent; Dec(I); end; end; procedure TfrmMessageList.UpdateColorDisplay(ALogNode: TLogNode); var I : Integer; S : string; begin I := ALogNode.Value.IndexOf('('); if I > 1 then begin S := Copy(ALogNode.Value, 1, I - 1); end else S := Trim(ALogNode.Value); // if ALogNode.MessageType = lmtAlphaColor then // // First byte in Alphacolors is the transparancy channel // pnlColor.Color := AlphaColorToColor(S.ToInt64) // else // pnlColor.Color := S.ToInteger; end; procedure TfrmMessageList.UpdateComponentDisplay(ALogNode: TLogNode); var LStream : TStringStream; begin if Assigned(ALogNode.MessageData) then begin LStream := TStringStream.Create('', TEncoding.ANSI); try tsValueList.TabVisible := False; tsImageViewer.TabVisible := False; tsDataSet.TabVisible := False; tsTextViewer.TabVisible := False; pgcMessageDetails.ActivePage := tsTextViewer; ALogNode.MessageData.Position := 0; ObjectBinaryToText(ALogNode.MessageData, LStream); LStream.Position := 0; FEditorView.Text := LStream.DataString; FEditorView.HighlighterName := 'DFM'; finally FreeAndNil(LStream); end; end else begin FEditorView.Text := ALogNode.Value; end; end; procedure TfrmMessageList.UpdateDataSetDisplay(ALogNode: TLogNode); begin tsValueList.TabVisible := False; tsImageViewer.TabVisible := False; tsDataSet.TabVisible := False; tsTextViewer.TabVisible := False; pgcMessageDetails.ActivePage := tsDataSet; ALogNode.MessageData.Position := 0; FDataSet.LoadFromStream(ALogNode.MessageData); dscMain.DataSet := FDataSet; FDBGridView.AutoSizeCols; end; procedure TfrmMessageList.UpdateMessageDetails(ALogNode: TLogNode); begin ClearMessageDetailsControls; FWatchesView.UpdateView(ALogNode.Id); case ALogNode.MessageType of lmtCallStack, {lmtException,} lmtHeapInfo, lmtCustomData: UpdateTextStreamDisplay(ALogNode); lmtAlphaColor, lmtColor: UpdateColorDisplay(ALogNode); lmtComponent: UpdateComponentDisplay(ALogNode); lmtBitmap, lmtScreenShot: UpdateBitmapDisplay(ALogNode); lmtMemory: begin //edtHex.OpenStream(ALogNode.MessageData); // pgcMessageDetails.ActivePageIndex := 3; end; lmtEnterMethod, lmtLeaveMethod, lmtText, lmtInfo, lmtWarning, lmtError, lmtConditional: UpdateTextDisplay(ALogNode); lmtValue, lmtObject, lmtPersistent, lmtInterface, lmtStrings, lmtCheckpoint: UpdateValueDisplay(ALogNode); lmtDataSet: UpdateDataSetDisplay(ALogNode); end; // edtMessageType.Text := LogMessageTypeNameOf(ALogNode.MessageType); // edtTimeStamp.Text := // FormatDateTime('dd:mm:yyyy hh:nn:ss:zzz', ALogNode.TimeStamp); // edtValue.Text := ALogNode.Value; // edtValueName.Text := ALogNode.ValueName; // edtValueType.Text := ALogNode.ValueType; end; procedure TfrmMessageList.UpdateTextDisplay(ALogNode: TLogNode); var S : string; begin tsValueList.TabVisible := False; tsTextViewer.TabVisible := False; tsImageViewer.TabVisible := False; tsDataSet.TabVisible := False; pgcMessageDetails.ActivePage := tsTextViewer; FEditorView.Text := ALogNode.Value; S := ALogNode.Highlighter; if S <> '' then FEditorView.HighlighterName := S; end; procedure TfrmMessageList.UpdateTextStreamDisplay(ALogNode: TLogNode); var LStream : TStringStream; begin tsValueList.TabVisible := False; tsImageViewer.TabVisible := False; tsDataSet.TabVisible := False; tsTextViewer.TabVisible := False; pgcMessageDetails.ActivePage := tsTextViewer; if ALogNode.MessageData = nil then begin FEditorView.Text := ''; end else begin ALogNode.MessageData.Position := 0; LStream := TStringStream.Create('', TEncoding.ANSI); try LStream.Position := 0; LStream.CopyFrom(ALogNode.MessageData, ALogNode.MessageData.Size); LStream.Position := 0; FEditorView.Text := LStream.DataString; FEditorView.HighlighterName := 'TXT'; finally LStream.Free; end; end; end; procedure TfrmMessageList.UpdateLogTreeView; begin FLogTreeView.BeginUpdate; try FLogTreeView.IterateSubtree(nil, FLogTreeViewFilterCallback, nil); if not FAutoSizeColumns then AutoFitColumns; finally FLogTreeView.EndUpdate; end; end; procedure TfrmMessageList.UpdateValueDisplay(ALogNode: TLogNode); var DR : DynamicRecord; SL : TStringList; begin FEditorView.Text := ALogNode.Value; FEditorView.HighlighterName := 'INI'; pgcMessageDetails.ActivePage := tsTextViewer; // test if ALogNode.Value.Contains('=') then begin pgcMessageDetails.ActivePage := tsValueList; DR.FromString(ALogNode.Value); FValueList.Data := DR; end else if ALogNode.Value.Contains(#13#10) then begin SL := TStringList.Create; try SL.Text := ALogNode.Value; DR.FromArray<string>(SL.ToStringArray, True); finally SL.Free; end; pgcMessageDetails.ActivePage := tsValueList; FValueList.Data := DR; end else begin pgcMessageDetails.ActivePage := tsTextViewer; end; end; {$ENDREGION} procedure TfrmMessageList.UpdateActions; begin EnsureIsActiveViewIfFocused; if IsActiveView and FUpdate then begin UpdateLogTreeView; if Assigned(Actions) then begin Actions.UpdateActions; end; FUpdate := False; end; inherited UpdateActions; end; { Force an update of the message viewer. } procedure TfrmMessageList.UpdateView; begin FUpdate := True; FAutoSizeColumns := False; end; {$ENDREGION} end.
Program penghitung_durasi; Uses crt; Type jam = Record hh : Integer; mm : Integer; ss : Integer; End; Var j1 : jam; j2 : jam; j3 : jam; tot_det1 : Longint; tot_det2 : Longint; selisih : Integer; sisa : Integer; Begin Writeln('masukkan jam1'); Readln(j1.hh); Writeln('masukkan menit1'); Readln(j1.mm); Writeln('masukkan detik1'); Readln(j1.ss); Writeln('masukkan jam2'); Readln(j2.hh); Writeln('masukkan menit2'); Readln(j2.mm); Writeln('masukkan detik2'); Readln(j2.ss); Writeln('waktu ke 1 = ',j1.hh,':',j1.mm,':',j1.ss); Writeln('waktu ke 2 = ',j2.hh,':',j2.mm,':',j2.ss); tot_det1 := j1.hh * 3600 + j1.mm * 60 + j1.ss; tot_det2 := j2.hh * 3600 + j2.mm * 60 + j2.ss; Writeln('total detik waktu 1 = ',tot_det1); Writeln('total detik waktu 2 = ',tot_det2); selisih := tot_det2 - tot_det1; Writeln('durasi waktu = ',selisih,' detik') ; j3.hh := selisih Div 3600; sisa := selisih Mod 3600; j3.mm := sisa Div 60; j3.ss := sisa Mod 60; Writeln('durasi waktu = ',j3.hh,':',j3.mm,':',j3.ss) ; End.
unit CtxMenu; interface uses Windows, Messages, Registry, SysUtils, Classes, ComObj, ComServ, ShlObj, ActiveX, ShellApi, ElTools, DizIni, ElStrUtils, ElIni; const CtxMenuGUID : TGuid = '{38CD8D36-B1CA-11D2-A86E-0060080F094D}'; CtxMenuGUIDStr = '{38CD8D36-B1CA-11D2-A86E-0060080F094D}'; type TCtxMenu = class(TComObject, IContextMenu, IShellExtInit) private FFileList : string; FFileCount : integer; public Description : string; Ini : TDizIni; destructor Destroy; override; function QueryContextMenu(Menu: HMENU; indexMenu, idCmdFirst, idCmdLast, uFlags: UINT): HResult; stdcall; function InvokeCommand(var lpici: TCMInvokeCommandInfo) : HResult; stdcall; function GetCommandString(idCmd, uType: UINT; pwReserved: PUINT; pszName: LPSTR; cchMax: UINT): HResult; stdcall; {$warnings off} function Initialize(pidlFolder: PItemIDList; lpdobj: IDataObject; hKeyProgID: HKEY): HResult; stdcall; {$warnings on} end; {$R dialogs.res} function DllRegServer: HResult; stdcall; function DllUnregServer: HResult; stdcall; implementation function EditDlgProc(hwndDlg : HWND; uMsg : integer; wParam, lParam : integer) : integer; stdcall; var p : pointer; i : integer; t : TCtxMenu; begin result :=0; case uMsg of WM_INITDIALOG: begin wParam := GetDlgItem(hwndDlg, 101); SetFocus(wParam); SetDlgItemText(hwndDlg, 101, pchar(TCtxMenu(lparam).Description)); SetWindowLong(hwndDlg, DWL_USER, lparam); result := 1; end; WM_COMMAND: begin if loword(wParam) = 1 then begin i := GetWindowTextLength(GetDlgItem(hwndDlg, 101)); GetMem(P, i + 1); GetDlgItemText(hwndDlg, 101, p, i + 1); T := TCtxMenu(GetWindowLong(hwndDlg, DWL_USER)); if T is TCtxMenu then T.Description := StrPas(P); FreeMem(P); EndDialog(hwndDlg, 1); result := 1; end else if loword(wParam) = 2 then begin EndDialog(hwndDlg, 2); result := 1; end; end; end; end; function ViewDlgProc(hwndDlg : HWND; uMsg : integer; wParam, lParam : integer) : integer; stdcall; begin result :=0; case uMsg of WM_INITDIALOG: begin SetDlgItemText(hwndDlg, 101, pchar(TCtxMenu(lparam).Description)); result := 1; end; WM_COMMAND: begin if loword(wParam) = 1 then begin EndDialog(hwndDlg, 0); result := 1; end; end; end; end; function DllRegServer: HResult; stdcall; var ClassID, FileName: string; begin //Result := SELFREG_E_CLASS; SetLength(FileName, MAX_PATH); GetModuleFileName(HInstance, PChar(FileName), Length(FileName)); SetLength(FileName, StrLen(PChar(FileName))); with TRegistry.Create do try RootKey := HKEY_CLASSES_ROOT; ClassID := '\CLSID\' + CtxMenuGUIDStr; OpenKey(ClassID, True); WriteString('','DizManager Context Menu'); // Default value OpenKey(ClassID + '\InprocServer32', True); WriteString('', FileName); // Default value WriteString('ThreadingModel', 'Apartment'); OpenKey('\*\shellex\ContextMenuHandlers\DizManagerMenu', True); WriteString('', CtxMenuGUIDStr); OpenKey('\Folder\shellex\ContextMenuHandlers\DizManagerMenu', True); WriteString('', CtxMenuGUIDStr); finally Free; end; Result := NOERROR; end; function DllUnregServer: HResult; stdcall; begin try with TRegistry.Create do try RootKey := HKEY_CLASSES_ROOT; DeleteKey('\CLSID\' + CtxMenuGUIDStr); DeleteKey('\*\shellex\ContextMenuHandlers\DizManagerMenu'); DeleteKey('\Folder\shellex\ContextMenuHandlers\DizManagerMenu'); finally Free; end; except //Result := S_FALSE; end; Result := NOERROR; end; const ID_VIEW = 1; ID_EDIT = 2; ID_RUN = 3; function TCtxMenu.QueryContextMenu(Menu: HMENU; indexMenu, idCmdFirst, idCmdLast, uFlags: UINT): HResult; var HSubMenu : HMENU; j : integer; begin HSubMenu := CreatePopupMenu; if FFileCount > 1 then j := MF_GRAYED else j := 0; InsertMenu (HSubMenu, 0, MF_STRING or MF_BYPOSITION or j, idCmdFirst + ID_VIEW, '&View ... '); InsertMenu (HSubMenu, 1, MF_STRING or MF_BYPOSITION, idCmdFirst + ID_EDIT, '&Enter/modify ... '); InsertMenu (Menu, indexMenu, MF_STRING or MF_BYPOSITION or MF_POPUP, HSubMenu, 'Description'); Result := 3; end; function TCtxMenu.InvokeCommand(var lpici: TCMInvokeCommandInfo) : HResult; var FileName : string; //h : THandle; lpProc : pointer; FL, FL1 : TStringList; i : integer; FName : string; DoDel : boolean; function GetFileDescription (FileName : string): string; var d : string; begin d := FileName; while true do if not Replace(d, #13#10, #32) then break; while true do if not Replace(d, '\\', '\?\') then break; d := Trim(d); if Ini.OpenKey('\'+ExtractFilePath(d), false) then begin Ini.ReadString('', ExtractFileName(d), '', d); result :=d; end else begin result := ''; end; end; var VE : TElIniEntry; begin // Make sure we are not being called by an application if HiWord(Integer(lpici.lpVerb)) <> 0 then begin Result := E_FAIL; Exit; end; Result := NOERROR; SetLength(FileName, MAX_PATH); GetModuleFileName(HInstance, PChar(FileName), Length(FileName)); SetLength(FileName, StrLen(PChar(FileName))); FileName := ExtractFilePath(FileName); if Ini = nil then begin Ini := TDizIni.Create(nil); Ini.Path := FileName + 'DizData.eif'; Ini.DivChar := '*'; try Ini.Load; except end; end; case LoWord(lpici.lpVerb) of ID_VIEW: begin Description := GetFileDescription(FFileList); lpProc := MakeProcInstance(@ViewDlgProc, HInstance); DialogBoxParam(HInstance, 'VIEWDIALOG', 0, lpProc, integer(Self)); FreeProcInstance(lpProc); end; ID_EDIT: begin if FFileCount = 1 then Description := GetFileDescription(FFileList); lpProc := MakeProcInstance(@EditDlgProc, HInstance); DialogBoxParam(HInstance, 'EDITDIALOG', 0, lpProc, integer(Self)); FreeProcInstance(lpProc); FL := TStringList.Create; FL1 := TStringList.Create; FL.Text := Description; FL1.Text := FFileList; DoDel := Length(Trim(Description)) = 0; for i := 0 to FL1.Count -1 do begin FName := Trim(FL1[i]); while true do if not Replace(FName, '\\', '\?\') then break; if DoDel then begin VE := Ini.GetValueEntry('\'+ExtractFilePath(FName), ExtractFileName(FName)); if VE <> nil then begin if VE.IsKey and (VE.SubCount >0) then VE.Invalidate else Ini.Delete('\'+ExtractFilePath(FName), ExtractFileName(FName)); end; end else begin if (Length(FName) = 3) and (FName[2] = ':') and ((FName[3] = '\') or (FName[3] = '/')) or DirExists(FName) then begin if Ini.OpenKey('\'+FName, true) then Ini.WriteMultiString('', '', FL); end else if FileExists(FName) then Ini.WriteMultiString('\'+ExtractFilePath(FName), ExtractFileName(FName), FL); end; end; FL.Free; FL1.Free; end; end; end; function TCtxMenu.GetCommandString(idCmd, uType: UINT; pwReserved: PUINT; pszName: LPSTR; cchMax: UINT): HRESULT; begin case uType of // GCS_HELPTEXT: begin case idCmd of // ID_VIEW: StrLCopy(pszName, 'View current description', cchMax); ID_EDIT: StrLCopy(pszName, 'Enter new or modify current description', cchMax); end; // case end; GCS_VERB: case idCmd of // ID_VIEW: StrLCopy(pszName, 'VIEWDIZ', cchMax); ID_EDIT: StrLCopy(pszName, 'EDITDIZ', cchMax); end; // case end; // case Result := NOERROR; end; function TCtxMenu.Initialize(pidlFolder: PItemIDList; lpdobj: IDataObject; hKeyProgID: HKEY): HResult; var StgMedium: TStgMedium; FormatEtc: TFormatEtc; Fl : TStringList; i, k : integer; p : pchar; begin if lpdobj = Nil then begin Result := E_FAIL; Exit; end; with FormatEtc do begin cfFormat := CF_HDROP; // Get file names delimited by double nulls ptd := Nil; // Don't need to provide target device info dwAspect := DVASPECT_CONTENT; // Get the content lindex := -1; // Get all data tymed := TYMED_HGLOBAL; // Storage medium is a global memory handle end; Result := lpdobj.GetData(FormatEtc, StgMedium); if Succeeded(Result) then try FL := TStringList.Create; FFileCount := DragQueryFile(StgMedium.hGlobal, $FFFFFFFF, Nil, 0); for i := 0 to FFileCount - 1 do begin k := DragQueryFile(StgMedium.hGlobal, i, Nil, 0); GetMem(P, k + 1); DragQueryFile(StgMedium.hGlobal, i, p, k + 1); p[k] := #0; FL.Add(StrPas(p)); FreeMem(p); end; FFileList := FL.Text; Fl.Free; result := NOERROR; finally ReleaseStgMedium(StgMedium); end; end; destructor TCtxMenu.Destroy; begin if Assigned(Ini) {and (Ini.Modified) }then begin Ini.Save; Ini.Free; end; inherited; end; initialization TComObjectFactory.Create( ComServer, TCtxMenu, CtxMenuGUID, '', 'EldoS DizManager', ciMultiInstance); end.
unit GameControl; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GameTypes, LanderTypes; type TOnRegionChange = procedure (Sender : TObject; const Origin, Size : TPoint) of object; const WM_UPDATEORIGIN = WM_USER + 1024; type TCustomGameControl = class(TCustomControl, IGameView) public constructor Create(aOwner : TComponent); override; destructor Destroy; override; protected// IUnknown fRefCount : integer; function QueryInterface(const iid : TGUID; out obj) : hresult; stdcall; function _AddRef : integer; stdcall; function _Release : integer; stdcall; protected // IGameUpdater fLockCount : integer; fUpdateDefered : boolean; function Lock : integer; function Unlock : integer; function LockCount : integer; procedure QueryUpdate(Defer : boolean); protected // IGameView fOrigin : TPoint; fDocument : IGameDocument; fZoomLevel : TZoomLevel; fRotation : TRotation; fFocus : IGameFocus; fImageSuit : integer; function GetOrigin : TPoint; procedure SetOrigin(const which : TPoint); function GetDocument : IGameDocument; procedure SetDocument(const which : IGameDocument); function GetZoomLevel : TZoomLevel; procedure SetZoomLevel(which : TZoomLevel); function GetRotation : TRotation; procedure SetRotation(which : TRotation); procedure UpdateRegions(const which : array of TRect); function GetSize : TPoint; function GetFocus : IGameFocus; function ViewPtToScPt(const which : TPoint) : TPoint; function ScPtToViewPt(const which : TPoint) : TPoint; function GetTextDimensions(const text : string; out width, height : integer) : boolean; function GetImageSuit : integer; procedure SetImageSuit(ImageSuit : integer); protected property Document : IGameDocument read fDocument write SetDocument; property ZoomLevel : TZoomLevel read GetZoomLevel write SetZoomLevel; private fOnRegionChange : TOnRegionChange; public property Origin : TPoint read GetOrigin write SetOrigin; property Focus : IGameFocus read fFocus; property ImageSuit : integer read GetImageSuit write SetImageSuit; property OnRegionChange : TOnRegionChange read fOnRegionChange write fOnRegionChange; protected procedure SetParent(which : TWinControl); override; procedure Loaded; override; procedure Paint; override; protected procedure StartScrolling; virtual; procedure ScrollTick(dx, dy : integer); procedure StopScrolling; virtual; procedure Scroll(dx, dy : integer); protected fExposed : boolean; fSnap : TCanvasImage; procedure RenderRegions(const which : array of TRect); virtual; procedure DrawRegions(const which : array of TRect); virtual; procedure CheckExposed; virtual; protected fMouseDown : boolean; fDragging : boolean; fMouseX : integer; fMouseY : integer; 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 KeyDown(var Key: Word; Shift: TShiftState); override; protected // internals procedure RenderControl; procedure UpdateThroughFocus; procedure wmEraseBkgnd(var msg : TMessage); message WM_ERASEBKGND; procedure wmSize(var msg : TWMSize); message WM_SIZE; procedure wmUpdateOrigin(var msg); message WM_UPDATEORIGIN; end; type TGameControl = class(TCustomGameControl) published property Document; property ZoomLevel; property OnRegionChange; published property Align; property Caption; property Color; property Font; property ShowHint; property PopupMenu; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; end; procedure Register; implementation uses ShutDown, ScrollRegions, AxlDebug, FocusTypes {$IFDEF PROFILES}, Profiler, IsoProfile{$ENDIF} {$IFDEF RENDERREPORTS}, RenderReports{$ENDIF}; const cCanvasBitCount = 16; // >>>> type THintWindow = class(TStaticText); // TCustomGameControl constructor TCustomGameControl.Create(aOwner : TComponent); begin inherited; ControlStyle := ControlStyle + [csOpaque]; Canvas.Brush.Color := clBlack; end; destructor TCustomGameControl.Destroy; begin inherited; end; function TCustomGameControl.QueryInterface(const iid : TGUID; out obj) : hresult; const E_NOINTERFACE = $80004002; begin if GetInterface(iid, obj) then Result := 0 else Result := E_NOINTERFACE; end; function TCustomGameControl._AddRef : integer; begin inc(fRefCount); Result := fRefCount; end; function TCustomGameControl._Release : integer; begin dec(fRefCount); Result := fRefCount; end; function TCustomGameControl.Lock : integer; begin inc(fLockCount); Result := fLockCount; end; function TCustomGameControl.Unlock : integer; begin assert(fLockCount > 0); dec(fLockCount); if (fLockCount = 0) and fUpdateDefered then RenderControl; Result := fLockCount; end; function TCustomGameControl.LockCount : integer; begin Result := fLockCount; end; procedure TCustomGameControl.QueryUpdate(Defer : boolean); begin if (fLockCount > 0) and Defer then fUpdateDefered := true else RenderControl; end; function TCustomGameControl.GetOrigin : TPoint; begin Result := fOrigin; end; procedure TCustomGameControl.SetOrigin(const which : TPoint); begin if fFocus <> nil then Scroll(fOrigin.x - which.x, fOrigin.y - which.y) else begin fOrigin := which; PostMessage(Handle, WM_UPDATEORIGIN, 0, 0); end; end; function TCustomGameControl.GetDocument : IGameDocument; begin Result := fDocument; end; procedure TCustomGameControl.SetDocument(const which : IGameDocument); begin if fDocument <> which then begin fDocument := which; // <<>> Change Focus CheckExposed; end; end; function TCustomGameControl.GetZoomLevel : TZoomLevel; begin Result := fZoomLevel; end; procedure TCustomGameControl.SetZoomLevel(which : TZoomLevel); begin if which <> fZoomLevel then fZoomLevel := which; end; function TCustomGameControl.GetRotation : TRotation; begin Result := fRotation; end; procedure TCustomGameControl.SetRotation(which : TRotation); begin if which <> fRotation then fRotation := which; end; procedure TCustomGameControl.UpdateRegions(const which : array of TRect); var i : integer; Clip : TRect; R : TRect; begin Clip := ClientRect; for i := low(which) to high(which) do begin IntersectRect(R, which[i], Clip); if not IsRectEmpty(R) then begin RenderRegions(R); DrawRegions(R); end; end; end; function TCustomGameControl.GetSize : TPoint; begin if fExposed then Result := ClientRect.BottomRight else Result := Point(0, 0); end; function TCustomGameControl.GetFocus : IGameFocus; begin Result := fFocus; end; function TCustomGameControl.ViewPtToScPt(const which : TPoint) : TPoint; begin Result := ClientToScreen(which); end; function TCustomGameControl.ScPtToViewPt(const which : TPoint) : TPoint; begin Result := ScreenToClient(which); end; function TCustomGameControl.GetTextDimensions(const text : string; out width, height : integer) : boolean; begin if fSnap <> nil then with fSnap.Canvas do begin Font.Name := 'Verdana'; Font.Size := 8; Font.Style := [fsBold]; Font.Color := clRed; width := TextWidth(text); height := TextHeight(text); Result := true; end else Result := false; end; function TCustomGameControl.GetImageSuit : integer; begin Result := fImageSuit; end; procedure TCustomGameControl.SetImageSuit(ImageSuit : integer); begin fDocument.SetImageSuit(ImageSuit); fImageSuit := ImageSuit; Repaint; end; procedure TCustomGameControl.SetParent(which : TWinControl); begin inherited; CheckExposed; end; procedure TCustomGameControl.Loaded; begin inherited; CheckExposed; end; procedure TCustomGameControl.Paint; begin if fExposed then RenderControl else inherited; end; procedure TCustomGameControl.StartScrolling; var msg : TGeneralMessage; begin ShutDown.DoSuspend; msg := msgScrollStart; fFocus.Dispatch(msg); end; procedure TCustomGameControl.ScrollTick(dx, dy : integer); const DeltaLimit = 500; type TRegionData = record Header : TRgnDataHeader; Rects : array[byte] of TRect; end; var SnapRect : TRect; {$IFNDEF RENDERSCREEN} Updates : TRegionData; UpdateRgn : HRGN; lx, ly : integer; {$ENDIF} msg : TViewScrolledMsg; begin if fExposed then begin fDocument.ClipMovement(Self, dx, dy); if (dx <> 0) or (dy <> 0) then begin dec(fOrigin.x, dx); dec(fOrigin.y, dy); msg.id := msgViewScrolled; msg.dx := dx; msg.dy := dy; fFocus.Dispatch(msg); SnapRect := ClientRect; {$IFNDEF RENDERSCREEN} lx := DeltaLimit; ly := DeltaLimit; if lx > 3*SnapRect.Right div 4 then lx := 3*SnapRect.Right div 4; if ly > 3*SnapRect.Bottom div 4 then ly := 3*SnapRect.Bottom div 4; if (abs(dx) < lx) and (abs(dy) < ly) then begin UpdateRgn := GetScrollUpdateRegion(Handle, dx, dy); GetRegionData(UpdateRgn, sizeof(Updates), @Updates); DeleteObject(UpdateRgn); RenderRegions(Slice(Updates.Rects, Updates.Header.nCount)); ScrollWindowEx(Handle, dx, dy, nil, nil, 0, nil, 0); // ScrollDC(Canvas.Handle, dx, dy, SnapRect, Snaprect, 0, nil); DrawRegions(Slice(Updates.Rects, Updates.Header.nCount)); end else Invalidate; {$ELSE} RenderRegions(SnapRect); DrawRegions(SnapRect); {$ENDIF} end; end; end; procedure TCustomGameControl.StopScrolling; var msg : TGeneralMessage; begin msg := msgScrollStop; fFocus.Dispatch(msg); UpdateThroughFocus; ShutDown.DoResume; end; procedure TCustomGameControl.Scroll(dx, dy : integer); begin StartScrolling; try ScrollTick(dx, dy); finally StopScrolling; end; end; procedure TCustomGameControl.RenderRegions(const which : array of TRect); var i : integer; begin {$IFDEF PROFILES} Profiler.ProcStarted(prfKind_Main, prfId_Rendering); try {$ENDIF} assert(fExposed); for i := low(which) to high(which) do fDocument.RenderSnapshot(Self, which[i], fSnap); {$IFDEF PROFILES} finally Profiler.ProcEnded(prfKind_Main, prfId_Rendering); end; {$ENDIF} end; procedure TCustomGameControl.DrawRegions(const which : array of TRect); var i : integer; begin {$IFDEF PROFILES} Profiler.ProcStarted(prfKind_Main, prfId_Blitting); try {$ENDIF} for i := low(which) to high(which) do begin fSnap.ClipDraw(Canvas, 0, 0, which[i]); {$IFDEF DRAWREGIONRECTS} Canvas.Pen.Color := clYellow; Canvas.Brush.Style := bsClear; Canvas.Rectangle(which[i].Left, which[i].Top, which[i].Right, which[i].Bottom); {$ENDIF} end; {$IFDEF PROFILES} finally Profiler.ProcEnded(prfKind_Main, prfId_Blitting); end; {$ENDIF} end; procedure TCustomGameControl.CheckExposed; var aux : boolean; begin aux := (Parent <> nil) and (fDocument <> nil); if aux <> fExposed then begin fExposed := aux; if fExposed then begin assert(fSnap = nil); fSnap := TCanvasImage.CreateSized(ClientWidth, ClientHeight, cCanvasBitCount); if fFocus = nil then fFocus := fDocument.CreateFocus(Self); end else begin //fFocus := nil; assert(fSnap <> nil); fSnap.Free; fSnap := nil; end; end; end; procedure TCustomGameControl.MouseDown(Button : TMouseButton; Shift : TShiftState; x, y : Integer); begin inherited; fMouseX := x; fMouseY := y; fMouseDown := true; end; procedure TCustomGameControl.MouseMove(Shift : TShiftState; x, y : integer); const cMinDrag = 8; var dx, dy : integer; begin inherited; if fMouseDown then begin dx := x - fMouseX; dy := y - fMouseY; if not fDragging then begin fDragging := (abs(dx) + abs(dy) > cMinDrag); if fDragging then begin MouseCapture := true; StartScrolling; end; end; if fDragging then begin ScrollTick(dx, dy); fMouseX := x; fMouseY := y; end; end else fFocus.MouseMove(x, y); end; procedure TCustomGameControl.MouseUp(Button : TMouseButton; Shift : TShiftState; x, y : integer); begin inherited; if fMouseDown then begin fMouseDown := false; if fDragging then begin StopScrolling; MouseCapture := false; fDragging := false; end else fFocus.MouseClick; end; end; procedure TCustomGameControl.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; fFocus.KeyPressed(Key, Shift); end; procedure TCustomGameControl.RenderControl; begin {$IFDEF RENDERREPORTS} ResetImgCount; EnableReports; {$ENDIF} fUpdateDefered := false; UpdateRegions([ClientRect]); {$IFDEF RENDERREPORTS} WriteDebugStr(IntToStr(GetImgCount)); DisableReports; {$ENDIF} end; procedure TCustomGameControl.UpdateThroughFocus; begin if fExposed then begin fFocus.QueryUpdate(true); if assigned(fOnRegionChange) then fOnRegionChange(Self, fOrigin, GetSize); end; end; procedure TCustomGameControl.wmEraseBkgnd(var msg : TMessage); begin end; procedure TCustomGameControl.wmSize(var msg : TWMSize); begin inherited; if fExposed then begin fSnap.NewSize(msg.Width, msg.Height, cCanvasBitCount); if assigned(fOnRegionChange) then fOnRegionChange(Self, fOrigin, GetSize); end; end; procedure TCustomGameControl.wmUpdateOrigin(var msg); begin UpdateThroughFocus; end; procedure Register; begin RegisterComponents('Games', [TGameControl]); end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.6 2003-10-12 15:25:50 HHellström Comments added Rev 1.5 2003-10-12 03:08:24 HHellström New implementation; copyright changed. The source code formatting has been adjusted to fit the margins. The new implementation is faster on dotNet compared to the old one, but is slightly slower on Win32. Rev 1.4 2003-10-11 18:44:54 HHellström Range checking and overflow checking disabled in the Coder method only. The purpose of this setting is to force the arithmetic operations performed on LongWord variables to be modulo $100000000. This hack entails reasonable performance on both Win32 and dotNet. Rev 1.3 10/10/2003 2:20:56 PM GGrieve turn range checking off Rev 1.2 2003-09-21 17:31:02 HHellström Version: 1.2 DotNET compatibility Rev 1.1 2/16/2003 03:19:18 PM JPMugaas Should now compile on D7 better. Rev 1.0 11/13/2002 07:53:48 AM JPMugaas } unit IdHashSHA; interface {$i IdCompilerDefines.inc} uses Classes, IdFIPS, IdGlobal, IdHash; { Microsoft.NET notes!!!! In Microsoft.NET, there are some limitations that you need to be aware of. 1) In Microsoft.NET 1.1, 2.0, and 3.0, only the CryptoService SHA1 class is FIPS-complient. Unfortunately, SHA1 will not be permitted after 2010. 2) In Microsoft.NET 3.5,There are more classes ending in CryptoServiceProvider" or "Cng" that are complient. 3) SHA224 is not exposed. } type T5x4LongWordRecord = array[0..4] of LongWord; T512BitRecord = array [0..63] of Byte; {$IFNDEF DOTNET} TIdHashSHA1 = class(TIdHashNativeAndIntF) {$ELSE} TIdHashSHA1 = class(TIdHashIntF) {$ENDIF} protected {$IFNDEF DOTNET} FCheckSum: T5x4LongWordRecord; FCBuffer: TIdBytes; procedure Coder; function NativeGetHashBytes(AStream: TStream; ASize: TIdStreamSize): TIdBytes; override; function HashToHex(const AHash: TIdBytes): String; override; {$ENDIF} function InitHash : TIdHashIntCtx; override; public {$IFDEF DOTNET} class function IsAvailable : Boolean; override; {$ELSE} constructor Create; override; {$ENDIF} class function IsIntfAvailable: Boolean; override; end; {$IFNDEF DOTNET} TIdHashSHA224 = class(TIdHashIntF) protected function InitHash : TIdHashIntCtx; override; public class function IsAvailable : Boolean; override; end; {$ENDIF} TIdHashSHA256 = class(TIdHashIntF) protected function InitHash : TIdHashIntCtx; override; public class function IsAvailable : Boolean; override; end; TIdHashSHA384 = class(TIdHashIntF) protected function InitHash : TIdHashIntCtx; override; public class function IsAvailable : Boolean; override; end; TIdHashSHA512 = class(TIdHashIntF) protected function InitHash : TIdHashIntCtx; override; public class function IsAvailable : Boolean; override; end; implementation uses {$IFDEF DOTNET} IdStreamNET; {$ELSE} IdStreamVCL; {$ENDIF} { TIdHashSHA1 } {$IFDEF DOTNET} function TIdHashSHA1.GetHashInst : TIdHashInst; begin //You can not use SHA256Managed for FIPS complience. Result := System.Security.Cryptography.SHA1CryptoServiceProvider.Create; end; class function TIdHashSHA1.IsIntfAvailable : Boolean; begin Result := True; end; class function TIdHashSHA1.IsAvailable : Boolean; begin Result := True; end; {$ELSE} function SwapLongWord(const AValue: LongWord): LongWord; begin Result := ((AValue and $FF) shl 24) or ((AValue and $FF00) shl 8) or ((AValue and $FF0000) shr 8) or ((AValue and $FF000000) shr 24); end; constructor TIdHashSHA1.Create; begin inherited Create; SetLength(FCBuffer, 64); end; function TIdHashSHA1.InitHash: TIdHashIntCtx; begin Result := GetSHA1HashInst; end; class function TIdHashSHA1.IsIntfAvailable: Boolean; begin Result := IsHashingIntfAvail and IsSHA1HashIntfAvail; end; {$Q-,R-} // Operations performed modulo $100000000 procedure TIdHashSHA1.Coder; var T, A, B, C, D, E: LongWord; { The size of the W variable has been reduced to make the Coder method consume less memory on dotNet. This change has been tested with the v1.1 framework and entails a general increase of performance by >50%. } W: array [0..19] of LongWord; i: LongWord; begin { The first 16 W values are identical to the input block with endian conversion. } for i := 0 to 15 do begin W[i]:= (FCBuffer[i*4] shl 24) or (FCBuffer[i*4+1] shl 16) or (FCBuffer[i*4+2] shl 8) or FCBuffer[i*4+3]; end; { In normal x86 code all of the remaining 64 W values would be calculated here. Here only the four next values are calculated, to reduce the code size of the first of the four loops below. } for i := 16 to 19 do begin T := W[i-3] xor W[i-8] xor W[i-14] xor W[i-16]; W[i] := (T shl 1) or (T shr 31); end; A := FCheckSum[0]; B := FCheckSum[1]; C := FCheckSum[2]; D := FCheckSum[3]; E := FCheckSum[4]; { The following loop could be expanded, but has been kept together to reduce the code size. A small code size entails better performance due to CPU caching. Note that the code size could be reduced further by using the SHA-1 reference code: for i := 0 to 19 do begin T := E + (A shl 5) + (A shr 27) + (D xor (B and (C xor D))) + W[i]; Inc(T,$5A827999); E := D; D := C; C := (B shl 30) + (B shr 2); B := A; A := T; end; The reference code is usually (at least partly) expanded, mostly because the assignments that circle the state variables A, B, C, D and E are costly, in particular on dotNET. (In x86 code further optimization can be achieved by eliminating the loop variable, which occupies a CPU register that is better used by one of the state variables, plus by expanding the W array at the beginning.) } i := 0; repeat Inc(E,(A shl 5) + (A shr 27) + (D xor (B and (C xor D))) + W[i+0]); Inc(E,$5A827999); B := (B shl 30) + (B shr 2); Inc(D,(E shl 5) + (E shr 27) + (C xor (A and (B xor C))) + W[i+1]); Inc(D,$5A827999); A := (A shl 30) + (A shr 2); Inc(C,(D shl 5) + (D shr 27) + (B xor (E and (A xor B))) + W[i+2]); Inc(C,$5A827999); E := (E shl 30) + (E shr 2); Inc(B,(C shl 5) + (C shr 27) + (A xor (D and (E xor A))) + W[i+3]); Inc(B,$5A827999); D := (D shl 30) + (D shr 2); Inc(A,(B shl 5) + (B shr 27) + (E xor (C and (D xor E))) + W[i+4]); Inc(A,$5A827999); C := (C shl 30) + (C shr 2); Inc(i,5); until i = 20; { The following three loops will only use the first 16 elements of the W array in a circular, recursive pattern. The following assignments are a trade-off to avoid having to split up the first loop. } W[0] := W[16]; W[1] := W[17]; W[2] := W[18]; W[3] := W[19]; { In the following three loops the recursive W array expansion is performed "just in time" following a circular pattern. Using circular indicies (e.g. (i+2) and $F) is not free, but the cost of declaring a large W array would be higher on dotNET. Before attempting to optimize this code, please note that the following language features are also costly: * Assignments and moves/copies, in particular on dotNET * Constant lookup tables, in particular on dotNET * Sub functions, in particular on x86 * if..then and case..of. } i := 20; repeat T := W[(i+13) and $F] xor W[(i+8) and $F]; T := T xor W[(i+2) and $F] xor W[i and $F]; T := (T shl 1) or (T shr 31); W[i and $F] := T; Inc(E,(A shl 5) + (A shr 27) + (B xor C xor D) + T + $6ED9EBA1); B := (B shl 30) + (B shr 2); T := W[(i+14) and $F] xor W[(i+9) and $F]; T := T xor W[(i+3) and $F] xor W[(i+1) and $F]; T := (T shl 1) or (T shr 31); W[(i+1) and $F] := T; Inc(D,(E shl 5) + (E shr 27) + (A xor B xor C) + T + $6ED9EBA1); A := (A shl 30) + (A shr 2); T := W[(i+15) and $F] xor W[(i+10) and $F]; T := T xor W[(i+4) and $F] xor W[(i+2) and $F]; T := (T shl 1) or (T shr 31); W[(i+2) and $F] := T; Inc(C,(D shl 5) + (D shr 27) + (E xor A xor B) + T + $6ED9EBA1); E := (E shl 30) + (E shr 2); T := W[i and $F] xor W[(i+11) and $F]; T := T xor W[(i+5) and $F] xor W[(i+3) and $F]; T := (T shl 1) or (T shr 31); W[(i+3) and $F] := T; Inc(B,(C shl 5) + (C shr 27) + (D xor E xor A) + T + $6ED9EBA1); D := (D shl 30) + (D shr 2); T := W[(i+1) and $F] xor W[(i+12) and $F]; T := T xor W[(i+6) and $F] xor W[(i+4) and $F]; T := (T shl 1) or (T shr 31); W[(i+4) and $F] := T; Inc(A,(B shl 5) + (B shr 27) + (C xor D xor E) + T + $6ED9EBA1); C := (C shl 30) + (C shr 2); Inc(i,5); until i = 40; { Note that the constant $70E44324 = $100000000 - $8F1BBCDC has been selected to slightly reduce the probability that the CPU flag C (Carry) is set. This trick is taken from the StreamSec(R) StrSecII(TM) implementation of SHA-1. It entails a marginal but measurable performance gain on some CPUs. } i := 40; repeat T := W[(i+13) and $F] xor W[(i+8) and $F]; T := T xor W[(i+2) and $F] xor W[i and $F]; T := (T shl 1) or (T shr 31); W[i and $F] := T; Inc(E,(A shl 5) + (A shr 27) + ((B and C) or (D and (B or C))) + T); Dec(E,$70E44324); B := (B shl 30) + (B shr 2); T := W[(i+14) and $F] xor W[(i+9) and $F]; T := T xor W[(i+3) and $F] xor W[(i+1) and $F]; T := (T shl 1) or (T shr 31); W[(i+1) and $F] := T; Inc(D,(E shl 5) + (E shr 27) + ((A and B) or (C and (A or B))) + T); Dec(D,$70E44324); A := (A shl 30) + (A shr 2); T := W[(i+15) and $F] xor W[(i+10) and $F]; T := T xor W[(i+4) and $F] xor W[(i+2) and $F]; T := (T shl 1) or (T shr 31); W[(i+2) and $F] := T; Inc(C,(D shl 5) + (D shr 27) + ((E and A) or (B and (E or A))) + T); Dec(C,$70E44324); E := (E shl 30) + (E shr 2); T := W[i and $F] xor W[(i+11) and $F]; T := T xor W[(i+5) and $F] xor W[(i+3) and $F]; T := (T shl 1) or (T shr 31); W[(i+3) and $F] := T; Inc(B,(C shl 5) + (C shr 27) + ((D and E) or (A and (D or E))) + T); Dec(B,$70E44324); D := (D shl 30) + (D shr 2); T := W[(i+1) and $F] xor W[(i+12) and $F]; T := T xor W[(i+6) and $F] xor W[(i+4) and $F]; T := (T shl 1) or (T shr 31); W[(i+4) and $F] := T; Inc(A,(B shl 5) + (B shr 27) + ((C and D) or (E and (C or D))) + T); Dec(A,$70E44324); C := (C shl 30) + (C shr 2); Inc(i,5); until i = 60; { Note that the constant $359D3E2A = $100000000 - $CA62C1D6 has been selected to slightly reduce the probability that the CPU flag C (Carry) is set. This trick is taken from the StreamSec(R) StrSecII(TM) implementation of SHA-1. It entails a marginal but measurable performance gain on some CPUs. } repeat T := W[(i+13) and $F] xor W[(i+8) and $F]; T := T xor W[(i+2) and $F] xor W[i and $F]; T := (T shl 1) or (T shr 31); W[i and $F] := T; Inc(E,(A shl 5) + (A shr 27) + (B xor C xor D) + T - $359D3E2A); B := (B shl 30) + (B shr 2); T := W[(i+14) and $F] xor W[(i+9) and $F]; T := T xor W[(i+3) and $F] xor W[(i+1) and $F]; T := (T shl 1) or (T shr 31); W[(i+1) and $F] := T; Inc(D,(E shl 5) + (E shr 27) + (A xor B xor C) + T - $359D3E2A); A := (A shl 30) + (A shr 2); T := W[(i+15) and $F] xor W[(i+10) and $F]; T := T xor W[(i+4) and $F] xor W[(i+2) and $F]; T := (T shl 1) or (T shr 31); W[(i+2) and $F] := T; Inc(C,(D shl 5) + (D shr 27) + (E xor A xor B) + T - $359D3E2A); E := (E shl 30) + (E shr 2); T := W[i and $F] xor W[(i+11) and $F]; T := T xor W[(i+5) and $F] xor W[(i+3) and $F]; T := (T shl 1) or (T shr 31); W[(i+3) and $F] := T; Inc(B,(C shl 5) + (C shr 27) + (D xor E xor A) + T - $359D3E2A); D := (D shl 30) + (D shr 2); T := W[(i+1) and $F] xor W[(i+12) and $F]; T := T xor W[(i+6) and $F] xor W[(i+4) and $F]; T := (T shl 1) or (T shr 31); W[(i+4) and $F] := T; Inc(A,(B shl 5) + (B shr 27) + (C xor D xor E) + T - $359D3E2A); C := (C shl 30) + (C shr 2); Inc(i,5); until i = 80; FCheckSum[0]:= FCheckSum[0] + A; FCheckSum[1]:= FCheckSum[1] + B; FCheckSum[2]:= FCheckSum[2] + C; FCheckSum[3]:= FCheckSum[3] + D; FCheckSum[4]:= FCheckSum[4] + E; end; function TIdHashSHA1.NativeGetHashBytes(AStream: TStream; ASize: TIdStreamSize): TIdBytes; var LSize: Integer; LLenHi: LongWord; LLenLo: LongWord; I: Integer; begin Result := nil; FCheckSum[0] := $67452301; FCheckSum[1] := $EFCDAB89; FCheckSum[2] := $98BADCFE; FCheckSum[3] := $10325476; FCheckSum[4] := $C3D2E1F0; LLenHi := 0; LLenLo := 0; repeat LSize := ReadTIdBytesFromStream(AStream, FCBuffer, 64); // TODO: handle stream read error Inc(LLenLo, LSize * 8); if LLenLo < LongWord(LSize * 8) then begin Inc(LLenHi); end; if LSize < 64 then begin FCBuffer[LSize] := $80; if LSize >= 56 then begin for I := (LSize + 1) to 63 do begin FCBuffer[i] := 0; end; Coder; LSize := -1; end; for I := (LSize + 1) to 55 do begin FCBuffer[i] := 0; end; FCBuffer[56] := (LLenHi shr 24); FCBuffer[57] := (LLenHi shr 16) and $FF; FCBuffer[58] := (LLenHi shr 8) and $FF; FCBuffer[59] := (LLenHi and $FF); FCBuffer[60] := (LLenLo shr 24); FCBuffer[61] := (LLenLo shr 16) and $FF; FCBuffer[62] := (LLenLo shr 8) and $FF; FCBuffer[63] := (LLenLo and $FF); LSize := 0; end; Coder; until LSize < 64; FCheckSum[0] := SwapLongWord(FCheckSum[0]); FCheckSum[1] := SwapLongWord(FCheckSum[1]); FCheckSum[2] := SwapLongWord(FCheckSum[2]); FCheckSum[3] := SwapLongWord(FCheckSum[3]); FCheckSum[4] := SwapLongWord(FCheckSum[4]); SetLength(Result, SizeOf(LongWord)*5); for I := 0 to 4 do begin CopyTIdLongWord(FCheckSum[I], Result, SizeOf(LongWord)*I); end; end; function TIdHashSHA1.HashToHex(const AHash: TIdBytes): String; begin Result := LongWordHashToHex(AHash, 5); end; {$ENDIF} {$IFNDEF DOTNET} { TIdHashSHA224 } function TIdHashSHA224.InitHash: TIdHashIntCtx; begin Result := GetSHA224HashInst; end; class function TIdHashSHA224.IsAvailable: Boolean; begin Result := IsHashingIntfAvail and IsSHA224HashIntfAvail; end; {$ENDIF} { TIdHashSHA256 } function TIdHashSHA256.InitHash: TIdHashIntCtx; begin Result := GetSHA256HashInst; end; class function TIdHashSHA256.IsAvailable : Boolean; begin Result := IsHashingIntfAvail and IsSHA256HashIntfAvail; end; { TIdHashSHA384 } function TIdHashSHA384.InitHash: TIdHashIntCtx; begin Result := GetSHA384HashInst; end; class function TIdHashSHA384.IsAvailable: Boolean; begin Result := IsHashingIntfAvail and IsSHA384HashIntfAvail; end; { TIdHashSHA512 } function TIdHashSHA512.InitHash: TIdHashIntCtx; begin Result := GetSHA512HashInst; end; class function TIdHashSHA512.IsAvailable: Boolean; begin Result := IsHashingIntfAvail and IsSHA512HashIntfAvail; end; end.
unit ArquivoStream; interface uses System.Classes, System.SysUtils; type TArquivoStream = class private public procedure LoadData(FileName: TFileName); function ReadStreamInt(Stream: TStream): integer; function ReadStreamStr(Stream: TStream): string; procedure SaveData(FileName: TFileName); procedure WriteStreamInt(Stream: TStream; Num: integer); procedure WriteStreamStr(Stream: TStream; Str: string); end; implementation procedure TArquivoStream.SaveData(FileName: TFileName); var MemStr: TMemoryStream; Title: String; begin MemStr:= TMemoryStream.Create; try MemStr.Seek(0, soFromBeginning); WriteStreamStr( MemStr, TItle ); MemStr.SaveToFile(FileName); finally MemStr.Free; end; end; procedure TArquivoStream.LoadData(FileName: TFileName); var MemStr: TMemoryStream; Title: String; begin MemStr:= TMemoryStream.Create; try MemStr.LoadFromFile(FileName); MemStr.Seek(0, soFromBeginning); Title := ReadStreamStr( MemStr ); finally MemStr.Free; end; end; procedure TArquivoStream.WriteStreamInt(Stream : TStream; Num : integer); {writes an integer to the stream} begin Stream.WriteBuffer(Num, SizeOf(Integer)); end; procedure TArquivoStream.WriteStreamStr(Stream : TStream; Str : string); {writes a string to the stream} var StrLen : integer; begin {get length of string} StrLen := Length(Str); {write length of string} WriteStreamInt(Stream, StrLen); if StrLen > 0 then {write characters} //Stream.Write(Str[1], StrLen); Stream.Write(Str[1], StrLen * SizeOf(Str[1])); end; function TArquivoStream.ReadStreamInt(Stream : TStream) : integer; {returns an integer from stream} begin Stream.ReadBuffer(Result, SizeOf(Integer)); end; function TArquivoStream.ReadStreamStr(Stream : TStream) : string; {returns a string from the stream} var LenStr : integer; begin Result := ''; {get length of string} LenStr := ReadStreamInt(Stream); {set string to get memory} SetLength(Result, LenStr); {read characters} Stream.Read(Result[1], LenStr); end; end.
unit LogInterface; interface uses Windows, Classes, Forms, Log4D; procedure Log4DReconfig(Force: Boolean = False); overload; procedure Log4DReconfig(Props: TStringList); overload; { Имя конфигурационного файла } function Log4DConfigFileName: String; implementation uses SysUtils; const CRLF = #13#10; defConfig = 'log4d.appender.logfile=TLogRollingFileAppender' + CRLF + 'log4d.appender.logfile.maxFileSize=10000KB' + CRLF + 'log4d.appender.logfile.maxBackupIndex=3' + CRLF + 'log4d.appender.logfile.append=true' + CRLF + 'log4d.appender.logfile.lockingModel=InterProcessLock' + CRLF + 'log4d.appender.logfile.fileName=app_log4d.log' + CRLF + 'log4d.appender.logfile.layout=TLogPatternLayout' + CRLF + 'log4d.appender.logfile.layout.dateFormat=yyyy-mm-dd hh:nn:ss.zzz' + CRLF + 'log4d.appender.logfile.layout.pattern=%d %p [%c] (%h:%w:%a:%t) - %m%n' + CRLF + CRLF + 'log4d.rootLogger=debug,logfile'; var CriticalSection: TRTLCriticalSection; LogInitialized: boolean; procedure Log4DReconfig(Force: Boolean = False); begin if not Force and LogInitialized then Exit; // EnterCriticalSection(CriticalSection); try LogInitialized := False; TLogPropertyConfigurator.ResetConfiguration; TLogPropertyConfigurator.Configure(Log4DConfigFileName); LogInitialized := True; finally // LeaveCriticalSection(CriticalSection); end; end; procedure Log4DReconfig(Props: TStringList); begin try LogInitialized := False; TLogPropertyConfigurator.ResetConfiguration; TLogPropertyConfigurator.Configure(Props); LogInitialized := True; finally end; end; function Log4DConfigFileName: String; var FS: TFileStream; S: String; begin Result := ExtractFilePath(GetModuleName(0)) + 'log4d.cfg'; if not FileExists(Result) then begin FS := TFileStream.Create(Result, fmCreate); try S := defConfig; FS.WriteBuffer(Pointer(S)^, length(S)); finally FS.Free; end; end; end; initialization { Synchronisation. } InitializeCriticalSection(CriticalSection); LogInitialized := False; finalization { Synchronisation. } DeleteCriticalSection(CriticalSection); end.
unit FTranslate; interface uses SysUtils, Classes, Controls, Forms, StdCtrls, ComCtrls, ToolsAPI, TypInfo, ImgList, ExtCtrls, UProperties; type TfrmNLDTTranslate = class(TForm) sbStatus: TStatusBar; tvComponents: TTreeView; ilsTree: TImageList; lvProperties: TListView; sptProps: TSplitter; procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tvComponentsChange(Sender: TObject; Node: TTreeNode); procedure lvPropertiesChange(Sender: TObject; Item: TListItem; Change: TItemChange); private FEditor: IOTAFormEditor; FProperties: TNLDComponents; FPropFile: String; FActiveComp: TNLDComponentItem; FFormName: String; procedure ListComponents(const AParent: IOTAComponent; const AParentNode: TTreeNode; const AImageIndex: TImageIndex); procedure GetComponent(Sender: TObject; const Name: String; out Component: TComponent); public property Editor: IOTAFormEditor read FEditor write FEditor; end; implementation uses Dialogs; const CIMGForm = 0; CIMGControl = 1; CIMGComponent = 2; CIMGProperty = 3; {$R *.dfm} {**************************************** TfrmNLDTTranslate ****************************************} procedure TfrmNLDTTranslate.FormShow; var otaRoot: IOTAComponent; begin // If the editor is hidden, show it first, this prevents Access Violations // from occuring... FEditor.Show(); FPropFile := ChangeFileExt(FEditor.FileName, '.ntp'); FProperties := TNLDComponents.Create(); FProperties.OnGetComponent := GetComponent; // Get form as component otaRoot := FEditor.GetRootComponent(); if otaRoot <> nil then begin otaRoot.GetPropValueByName('Name', FFormName); Caption := Caption + ' - ' + FFormName; if FileExists(FPropFile) then FProperties.LoadFromFile(FPropFile); ListComponents(otaRoot, nil, CIMGForm); otaRoot := nil; end; end; procedure TfrmNLDTTranslate.FormDestroy; begin if Assigned(FProperties) then begin FProperties.SaveToFile(FPropFile); FreeAndNil(FProperties); end; end; {**************************************** Recursively list components ****************************************} procedure TfrmNLDTTranslate.ListComponents; var otaComponent: IOTAComponent; iComponent: Integer; pNode: TTreeNode; sName: String; sType: String; pType: TClass; pTemp: TTreeNode; begin // Add tree node AParent.GetPropValueByName('Name', sName); pNode := tvComponents.Items.AddChild(AParentNode, sName); pNode.ImageIndex := AImageIndex; pNode.SelectedIndex := AImageIndex; pNode.Data := AParent.GetComponentHandle(); // List components for iComponent := 0 to AParent.GetComponentCount() - 1 do begin otaComponent := AParent.GetComponent(iComponent); try sType := otaComponent.GetComponentType(); pType := GetClass(sType); if Assigned(pType) then begin if pType.InheritsFrom(TWinControl) then // List sub-components ListComponents(otaComponent, pNode, CIMGControl) else begin otaComponent.GetPropValueByName('Name', sName); // It added a TTimer otherwise :confused: if Length(sName) > 0 then begin // Add tree node pTemp := tvComponents.Items.AddChild(pNode, sName); with pTemp do begin ImageIndex := CIMGComponent; SelectedIndex := CIMGComponent; Data := otaComponent.GetComponentHandle(); end; end; end; end; finally otaComponent := nil; end; end; if AParentNode = nil then pNode.Expand(True); end; procedure TfrmNLDTTranslate.tvComponentsChange; procedure GetTypeAndValue(const AComponent: TComponent; const AProp: PPropInfo; out AType: String; out AValue: String); const CTypeNames: array[Low(TTypeKind)..High(TTypeKind)] of String = ('Unknown', 'Integer', 'Char', 'Enumeration', 'Float', 'String', 'Set', 'Class', 'Method', 'WideChar', 'String', 'String', 'Variant', 'Array', 'Record', 'Interface', 'Int64', 'Dynamic Array'); var iValue: Integer; dValue: Double; begin AType := CTypeNames[AProp^.PropType^.Kind]; case AProp^.PropType^.Kind of tkInteger: begin iValue := GetOrdProp(AComponent, AProp); Str(iValue, AValue); end; tkChar, tkWChar, tkString, tkLString, tkWString: begin AValue := GetStrProp(AComponent, AProp); end; tkFloat: begin dValue := GetFloatProp(AComponent, AProp); AValue := FloatToStr(dValue); end; tkSet: begin AValue := GetSetProp(AComponent, AProp, True); end; tkEnumeration: begin AValue := GetEnumProp(AComponent, AProp); end; else AValue := '(unknown)'; end; end; var pComponent: TComponent; pProps: PPropList; iCount: Integer; iSize: Integer; iProp: Integer; sName: String; sValue: String; sType: String; begin lvProperties.Clear(); if not Assigned(Node) then exit; pComponent := TComponent(Node.Data); if (Assigned(pComponent)) and (TObject(pComponent) is TComponent) then begin FActiveComp := FProperties.GetFromComponent(pComponent); lvProperties.Items.BeginUpdate(); try // Retrieve the number of properties iCount := GetPropList(pComponent.ClassInfo, tkProperties, nil); iSize := iCount * SizeOf(TPropInfo); GetMem(pProps, iSize); try // Get the properties list GetPropList(pComponent.ClassInfo, tkProperties, pProps); for iProp := 0 to iCount - 1 do begin sName := pProps[iProp]^.Name; GetTypeAndValue(pComponent, pProps[iProp], sType, sValue); with lvProperties.Items.Add() do begin Caption := sName; SubItems.Add(sValue); SubItems.Add(sType); ImageIndex := CIMGProperty; Checked := FActiveComp.Selected[sName]; end; end; finally FreeMem(pProps, iSize); end; finally lvProperties.Items.EndUpdate(); end; end; end; procedure TfrmNLDTTranslate.lvPropertiesChange; begin if Change = ctState then if Assigned(FActiveComp) then FActiveComp.Selected[Item.Caption] := Item.Checked; end; procedure TfrmNLDTTranslate.GetComponent; var otaComponent: IOTAComponent; begin if CompareText(Name, FFormName) = 0 then otaComponent := FEditor.GetRootComponent() else otaComponent := FEditor.FindComponent(Name); if Assigned(otaComponent) then begin Component := TComponent(otaComponent.GetComponentHandle()); otaComponent := nil; end; end; end.
{ Handle the SYN CHAR syntax. } module sst_r_syn_char; define sst_r_syn_char_get; %include 'sst_r_syn.ins.pas'; { ******************************************************************************** * * Function SST_R_SYN_CHAR_GET (CCODE) * * Processes the CHAR syntax and returns the resulting character code. The * current parsing position must be immediately before the link to the * subordinate CHAR syntax. } function sst_r_syn_char_get ( {get the result of the SYN CHAR syntax} out ccode: sys_int_machine_t) {0-N character code} :boolean; {success, no syntax error encountered} val_param; var tk: string_var4_t; {single character being defined} begin tk.max := size_char(tk.str); {init local var string} sst_r_syn_char_get := false; {init to not completed without error} if not syn_trav_next_down (syn_p^) {down into CHAR syntax} then return; if syn_trav_next_tag(syn_p^) <> 1 then begin {get tag, should be 1} syn_msg_tag_bomb (syn_p^, '', '', nil, 0); {abort on unexpected tag} end; syn_trav_tag_string (syn_p^, tk); {get the single-character string} if tk.len <> 1 then return; {not a single character as expected ?} ccode := ord(tk.str[1]); {return the character code} if not syn_trav_up (syn_p^) {pop back up from CHAR syntax} then return; sst_r_syn_char_get := true; {indicate success, no errors} end;
unit uMainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.TitleBarCtrls, System.ImageList, Vcl.ImgList, Vcl.VirtualImageList, Vcl.BaseImageCollection, Vcl.ImageCollection, Vcl.ComCtrls, Vcl.ToolWin, System.Actions, Vcl.ActnList, IniFiles, WebView2, Winapi.ActiveX, Vcl.Edge; type TMainForm = class(TForm) TitleBarPanel: TTitleBarPanel; ImageCollection: TImageCollection; VirtualImageList: TVirtualImageList; ToolBar: TToolBar; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ActionList: TActionList; actionNewAccount: TAction; PageControl: TPageControl; actionRemAccount: TAction; actionNewMessage: TAction; actionCopyScreen: TAction; procedure actionNewAccountExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure actionRemAccountExecute(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure actionNewMessageExecute(Sender: TObject); procedure actionCopyScreenExecute(Sender: TObject); private { Private declarations } fIniFile: TIniFile; stlAccounts: TStringList; { Credits for the Save/Load Seetings feature: https://www.davidghoyle.co.uk/WordPress/?p=2100 } function MonitorProfile: string; procedure AppSaveSettings; procedure AppLoadSettings; function IsValidAcctName(sAcctName: string): Boolean; function CreateNewTab(sAcctName: string): TTabSheet; function CreateNewEdge(fTabSheet: TTabSheet; sAcctName: string) : TEdgeBrowser; procedure RemoveAccount(sAcctName: string); procedure OnTabSheetShow(Sender: TObject); procedure OnCreateWebViewCompleted(Sender: TCustomEdgeBrowser; AResult: HRESULT); public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} uses System.IOUtils, System.RegularExpressions, System.UITypes; function TMainForm.MonitorProfile: string; const strMask = '%d=%dDPI(%s,%d,%d,%d,%d)'; var iMonitor: Integer; M: TMonitor; K: String; begin Result := ''; for iMonitor := 0 To Screen.MonitorCount - 1 Do begin If Result <> '' Then Result := Result + ':'; M := Screen.Monitors[iMonitor]; Result := Result + Format(strMask, [M.MonitorNum, M.PixelsPerInch, BoolToStr(M.Primary, True), M.Left, M.Top, M.Width, M.Height]); end; end; procedure TMainForm.AppSaveSettings; Var strMonitorProfile: String; recWndPlmt: TWindowPlacement; Begin strMonitorProfile := MonitorProfile; recWndPlmt.Length := SizeOf(TWindowPlacement); GetWindowPlacement(Handle, @recWndPlmt); fIniFile.WriteInteger(strMonitorProfile, 'Top', recWndPlmt.rcNormalPosition.Top); fIniFile.WriteInteger(strMonitorProfile, 'Left', recWndPlmt.rcNormalPosition.Left); fIniFile.WriteInteger(strMonitorProfile, 'Height', recWndPlmt.rcNormalPosition.Height); fIniFile.WriteInteger(strMonitorProfile, 'Width', recWndPlmt.rcNormalPosition.Width); fIniFile.WriteInteger(strMonitorProfile, 'WindowState', recWndPlmt.showCmd); fIniFile.UpdateFile; end; procedure TMainForm.AppLoadSettings; var strMonitorProfile: String; recWndPlmt: TWindowPlacement; begin strMonitorProfile := MonitorProfile; recWndPlmt.Length := SizeOf(TWindowPlacement); recWndPlmt.rcNormalPosition.Top := fIniFile.ReadInteger(strMonitorProfile, 'Top', 100); recWndPlmt.rcNormalPosition.Left := fIniFile.ReadInteger(strMonitorProfile, 'Left', 100); recWndPlmt.rcNormalPosition.Height := fIniFile.ReadInteger(strMonitorProfile, 'Height', 480); recWndPlmt.rcNormalPosition.Width := fIniFile.ReadInteger(strMonitorProfile, 'Width', 640); recWndPlmt.showCmd := fIniFile.ReadInteger(strMonitorProfile, 'WindowState', SW_NORMAL); SetWindowPlacement(Handle, @recWndPlmt); end; procedure TMainForm.actionCopyScreenExecute(Sender: TObject); begin if PageControl.ActivePage.Tag > 0 then begin end; end; procedure TMainForm.actionNewAccountExecute(Sender: TObject); begin var sAcctName: string := ''; if InputQuery('Create a New Account', 'Account Unique Name', sAcctName) then begin sAcctName := sAcctName.Trim; if IsValidAcctName(sAcctName) then begin CreateNewEdge(CreateNewTab(sAcctName), sAcctName); PageControl.ActivePageIndex := PageControl.PageCount - 1; PageControl.ActivePage.OnShow(PageControl.ActivePage); fIniFile.WriteString('Accounts', sAcctName, UpperCase(sAcctName)); stlAccounts.AddPair(sAcctName, UpperCase(sAcctName)); end end; end; procedure TMainForm.actionNewMessageExecute(Sender: TObject); begin if PageControl.ActivePage.Tag > 0 then begin var sNewNumber: string := ''; if InputQuery('Start New Conversation', 'Phone Number', sNewNumber) then begin if not TRegEx.IsMatch(sNewNumber, '^[0-9]*$') then raise Exception.Create ('The account name must contain only letters and numbers!'); var script := 'window.open("https://web.whatsapp.com/send?phone=' + sNewNumber + '&text&app_absent=0","_self")'; TEdgeBrowser(PageControl.ActivePage.Tag).ExecuteScript(script); end; end; end; procedure TMainForm.actionRemAccountExecute(Sender: TObject); begin if PageControl.PageCount > 0 then if MessageDlg('This account will be removed. Confirm?', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0) = IDYES then RemoveAccount(Trim(PageControl.ActivePage.Caption)); end; procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin AppSaveSettings; CanClose := True; end; procedure TMainForm.FormCreate(Sender: TObject); begin stlAccounts := TStringList.Create; fIniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'QuickWhats.ini'); fIniFile.ReadSectionValues('Accounts', stlAccounts); end; procedure TMainForm.FormShow(Sender: TObject); begin AppLoadSettings; if stlAccounts.Count > 0 then begin for var i: Integer := 0 to stlAccounts.Count - 1 do CreateNewEdge(CreateNewTab(stlAccounts.Names[i]), stlAccounts.Names[i]); PageControl.ActivePageIndex := 0; PageControl.ActivePage.OnShow(PageControl.ActivePage); end; end; procedure TMainForm.OnCreateWebViewCompleted(Sender: TCustomEdgeBrowser; AResult: HRESULT); begin Sender.DefaultContextMenusEnabled := True; Sender.DefaultScriptDialogsEnabled := True; // Sender.StatusBarEnabled := True; // Sender.WebMessageEnabled := True; // Sender.ZoomControlEnabled := True; // Sender.DevToolsEnabled := True; end; procedure TMainForm.OnTabSheetShow(Sender: TObject); begin var fBrowserInstance := TEdgeBrowser(TTabSheet(Sender).Tag); if (fBrowserInstance <> nil) and (fBrowserInstance.Tag = 0) then begin fBrowserInstance.Navigate('https://web.whatsapp.com'); fBrowserInstance.Tag := 1; end; end; function TMainForm.IsValidAcctName(sAcctName: string): Boolean; begin if sAcctName.IsEmpty or (sAcctName.Length < 4) then raise Exception.Create ('The account name must contain three or more characters!'); if not TRegEx.IsMatch(sAcctName, '([A-Za-z0-9\-\_]+)') then raise Exception.Create ('The account name must contain only letters and numbers!'); if stlAccounts.IndexOf(sAcctName + '=' + UpperCase(sAcctName)) > -1 then raise Exception.Create('The account name must be unique!'); Result := True; end; function TMainForm.CreateNewTab(sAcctName: string): TTabSheet; begin Result := TTabSheet.Create(PageControl); Result.Name := 'tab' + sAcctName; Result.PageControl := PageControl; Result.Caption := ' ' + sAcctName + ' '; Result.OnShow := OnTabSheetShow; end; function TMainForm.CreateNewEdge(fTabSheet: TTabSheet; sAcctName: string) : TEdgeBrowser; begin var fDataFolder := ExtractFilePath(Application.ExeName) + 'Accounts' + PathDelim + UpperCase(sAcctName); ForceDirectories(fDataFolder); Result := TEdgeBrowser.Create(fTabSheet); Result.Name := 'edge' + sAcctName; Result.OnCreateWebViewCompleted := OnCreateWebViewCompleted; Result.UserDataFolder := fDataFolder; Result.Align := alClient; Result.Parent := fTabSheet; fTabSheet.Tag := Integer(Result); end; procedure TMainForm.RemoveAccount(sAcctName: string); begin TEdgeBrowser(PageControl.ActivePage.Tag).CloseWebView; TEdgeBrowser(PageControl.ActivePage.Tag).Free; PageControl.ActivePage.Free; fIniFile.DeleteKey('Accounts', sAcctName); stlAccounts.Delete(stlAccounts.IndexOf(sAcctName + '=' + UpperCase(sAcctName))); var fDataFolder := ExtractFilePath(Application.ExeName) + 'Accounts' + PathDelim + UpperCase(sAcctName); if DirectoryExists(fDataFolder) then begin Sleep(1000); TDirectory.Delete(fDataFolder, True); end; PageControl.ActivePageIndex := 0; end; end.
{*********************************************************} {* STNVLIST.PAS 3.01 *} {* Copyright (c) TurboPower Software Co., 1996-2000 *} {* All rights reserved. *} {*********************************************************} {$I STDEFINE.INC} {$IFNDEF WIN32} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} unit StNVList; {-non visual component for TStList} interface uses {$IFDEF WIN32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Classes, StBase, StList, StNVCont; type TStNVList = class(TStNVContainerBase) {.Z+} protected {private} {property variables} FContainer : TStList; {instance of the container} protected function GetOnCompare : TStCompareEvent; override; function GetOnDisposeData : TStDisposeDataEvent; override; function GetOnLoadData : TStLoadDataEvent; override; function GetOnStoreData : TStStoreDataEvent; override; procedure SetOnCompare(Value : TStCompareEvent); override; procedure SetOnDisposeData(Value : TStDisposeDataEvent); override; procedure SetOnLoadData(Value : TStLoadDataEvent); override; procedure SetOnStoreData(Value : TStStoreDataEvent); override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; {.Z-} property Container : TStList read FContainer; published property OnCompare; property OnDisposeData; property OnLoadData; property OnStoreData; end; implementation {$IFDEF TRIALRUN} uses {$IFDEF Win32} Registry, {$ELSE} Ver, {$ENDIF} Forms, IniFiles, ShellAPI, SysUtils, StTrial; {$I TRIAL00.INC} {FIX} {$I TRIAL01.INC} {CAB} {$I TRIAL02.INC} {CC} {$I TRIAL03.INC} {VC} {$I TRIAL04.INC} {TCC} {$I TRIAL05.INC} {TVC} {$I TRIAL06.INC} {TCCVC} {$ENDIF} {*** TStNVList ***} constructor TStNVList.Create(AOwner : TComponent); begin {$IFDEF TRIALRUN} TCCVC; {$ENDIF} inherited Create(AOwner); {defaults} if Classes.GetClass(TStList.ClassName) = nil then RegisterClass(TStList); if Classes.GetClass(TStListNode.ClassName) = nil then RegisterClass(TStListNode); FContainer := TStList.Create(TStListNode); end; destructor TStNVList.Destroy; begin FContainer.Free; FContainer := nil; inherited Destroy; end; function TStNVList.GetOnCompare : TStCompareEvent; begin Result := FContainer.OnCompare; end; function TStNVList.GetOnDisposeData : TStDisposeDataEvent; begin Result := FContainer.OnDisposeData; end; function TStNVList.GetOnLoadData : TStLoadDataEvent; begin Result := FContainer.OnLoadData; end; function TStNVList.GetOnStoreData : TStStoreDataEvent; begin Result := FContainer.OnStoreData; end; procedure TStNVList.SetOnCompare(Value : TStCompareEvent); begin FContainer.OnCompare := Value; end; procedure TStNVList.SetOnDisposeData(Value : TStDisposeDataEvent); begin FContainer.OnDisposeData := Value; end; procedure TStNVList.SetOnLoadData(Value : TStLoadDataEvent); begin FContainer.OnLoadData := Value; end; procedure TStNVList.SetOnStoreData(Value : TStStoreDataEvent); begin FContainer.OnStoreData := Value; end; end.
unit Option; interface uses StdCtrls, Forms, MPlayer, Classes; type TOption = class procedure LoadConfig(var Form: TForm); procedure SaveConfig(const Form: TForm); procedure DoPlay(var MediaPlayer: TMediaPlayer; var ListBox: TListBox; var myLabel: TLabel; const index: Integer); function KillProcessByProcessName(const ProcessName: String): Boolean; overload; function KillProcessByProcessList(const ProcessList: TStrings; var ErrorMsg: String): Boolean; overload; function KillProcessByIniFile(const IniFileName: String): Boolean; overload; procedure SaveExceptions(const FunctionName, ExceptionParam: String); private public end; var myOption: TOption; implementation uses SysUtils, Controls, IniFiles, Windows; procedure TOption.LoadConfig(var Form: TForm); var FileName, Key, Value: String; myIniFile: TIniFile; Sections, Config: TStrings; i, j: Integer; Component: TComponent; begin Sections:=TStringList.Create; Config:=TStringList.Create; FileName:=ExtractFilePath(Paramstr(0))+Form.Name+'.ini'; myIniFile:=TiniFile.Create(FileName); myIniFile.ReadSections(Sections); //获取所有小节 for i:=0 to Sections.Count-1 do begin myIniFile.ReadSectionValues(Sections[i], Config); //把小节中的内容读取到TStrings对象中 Component:=Form.FindComponent(Sections[i]); for j:=0 to Config.Count-1 do begin Key:=Copy(Config[j], 0, Pos('=', Config[j])-1); Value:=Copy(Config[j], Pos('=', Config[j])+1, Length(Config[j])-Pos('=', Config[j])+1); if Component is TListBox then with TListBox(Component) do begin if (Key='Selected') then begin if (StrToInt(Value)>=0) and (Items.Count>0) then Selected[StrToInt(Value)]:=true; ItemIndex:=StrToInt(Value); end else Items.Add(Value); end; if Component is TCheckBox then with TCheckBox(Component) do begin if Key='Checked' then Checked:=Value='True'; end; if Component is TMediaPlayer then with TMediaPlayer(Component) do begin if Key='AutoOpen' then AutoOpen:=Value='True'; if Key='Tag' then Tag:=StrToInt(Value); end; end; end; myIniFile.Destroy; Config.Free; Sections.Free; end; procedure GetConfig(const Form: TForm; var Config: TStrings); var Control: TControl; Key, Value: String; i, j: Integer; begin with Form do for i:=0 to ControlCount-1 do begin Control:=Controls[i]; Config.Add('['+Control.Name+']'); if Control is TListBox then with TListBox(Control) do begin for j:=0 to Items.Count-1 do begin Key:=IntToStr(j); Value:=Items[j]; Config.Add(Key+'='+Value); end; Key:='Selected'; Value:=IntToStr(ItemIndex); Config.Add(Key+'='+Value); end; if Control is TCheckBox then with TCheckBox(Control) do begin Key:='Checked'; if Checked then value:='True' else value:='False'; Config.Add(Key+'='+Value); end; if Control is TMediaPlayer then with TMediaPlayer(Control) do begin Key:='AutoOpen'; if AutoOpen then Value:='True' else Value:='False'; Config.Add(Key+'='+Value); Key:='Tag'; Value:=IntToStr(Tag); Config.Add(Key+'='+Value); end; Config.Add(#13); end; end; procedure TOption.SaveConfig(const Form: TForm); var aFile: TextFile; Config: TStrings; begin Config:=TStringList.Create; GetConfig(Form, Config); AssignFile(aFile, ExtractFilePath(Paramstr(0))+Form.Name+'.ini'); Rewrite(aFile); Writeln(aFile, Config.Text); CloseFile(aFile); Config.Free; end; //计算播放索引 procedure SetPlayIndex(var ListBox: TListBox; const index: Integer; var PlayIndex: Integer); begin with ListBox do begin if ItemIndex+index<0 then PlayIndex:=Items.Count-1 else if ItemIndex+index>=Items.Count then PlayIndex:=0 else PlayIndex:=ItemIndex+index; Selected[ItemIndex]:=false; Selected[PlayIndex]:=true; ItemIndex:=PlayIndex; end; end; //播放控制 procedure TOption.DoPlay(var MediaPlayer: TMediaPlayer; var ListBox: TListBox; var myLabel: TLabel; const index: Integer); var PlayIndex: Integer; begin with MediaPlayer do begin if Mode=mpPlaying then Stop; { //多列表判断 case Tag of 1: begin SetPlayIndex(ListBox, index, PlayIndex); FileName:=ListBox.Items[PlayIndex]; end; end; } SetPlayIndex(ListBox, index, PlayIndex); FileName:=ListBox.Items[PlayIndex]; myLabel.Caption:='正在播放:'+FileName; Open; Play; EnabledButtons:=[btPause, btStop, btNext, btPrev]; end; end; procedure TOption.SaveExceptions(const FunctionName, ExceptionParam: string); var ExceptionList: TStrings; begin ExceptionList:=TStringList.Create; with ExceptionList do begin Add('Date: '+FormatDateTime('yyyy-mm-dd hh:nn:ss',Now)); Add('Function: '+FunctionName); Add('Exception: '+ExceptionParam); Add(#13); end; end; function TOption.KillProcessByProcessName(const ProcessName: String): Boolean; begin try WinExec(PAnsiChar('cmd /c'+'taskkill /f /im'+ProcessName), 0); Result:=True; except Result:=False; //Save Exception Info SaveExceptions('KillProcessByProcessName', 'ExceptionParam'); end; end; function TOption.KillProcessByProcessList(const ProcessList: TStrings; var ErrorMsg: String): Boolean; var i: Integer; sl: TStrings; begin sl:=TStringList.Create; try for i:=0 to ProcessList.Count-1 do begin Result:=KillProcessByProcessName(ProcessList[i]); if not Result then sl.Add(ProcessList[i]); end; Result:=sl.Count>0; if not Result then ErrorMsg:='以下进程未能结束:'+#13#10+sl.Text; sl.Free; except Result:=False; //Save Exception Info SaveExceptions('KillProcessByProcessList', 'ExceptionParam'); sl.Free; end end; function TOption.KillProcessByIniFile(const IniFileName: String): Boolean; var FileName, Key, Value: String; myIniFile: TIniFile; Sections, Keys: TStrings; i, j: Integer; begin Sections:=TStringList.Create; Keys:=TStringList.Create; try try FileName:=ExtractFilePath(Paramstr(0))+IniFileName+'.ini'; myIniFile:=TiniFile.Create(FileName); myIniFile.ReadSections(Sections); //获取所有小节 for i:=0 to Sections.Count-1 do begin myIniFile.ReadSection(Sections[i], Keys); //获取小节的所有Key for j:=0 to Keys.Count-1 do begin Key:=Keys[i]; Value:=myIniFile.ReadString(Sections[i], Key, ''); //获取每个Key对应的Value Result:=KillProcessByProcessName(Value); end; end; Result:=True; except Result:=False; //Save Exception Info SaveExceptions('KillProcessByIniFile', 'ExceptionParam'); end; finally myIniFile.Destroy; Sections.Free; end; end; end.
{$S-,R-,V-,I-,B-,F-} {$IFNDEF Ver40} {$S-,O-,A-} {$ENDIF} {$I TPDEFINE.INC} {!!.21} {*********************************************************} {* TPCMD.PAS 5.21 *} {* Copyright (c) TurboPower Software 1987, 1992. *} {* Portions Copyright (c) Sunny Hill Software 1985, 1986 *} {* and used under license to TurboPower Software *} {* All rights reserved. *} {*********************************************************} unit TpCmd; {-Convert keystrokes to commands. This unit is intended primarily for internal use.} interface type MatchType = (NoMatch, PartMatch, FullMatch); const NoCmd = 0; {Returned by GetCommand for invalid keystroke} AlphaCmd = 1; {Returned by GetCommand for alphanumeric char} MapWordStar : Boolean = True; {True to map second character to control char} {************************************************************** KeySet is an array of byte, in the following form: (LengthByte, Key1, Key2, ..., CommandOrd, ..., 0); LengthByte includes the number of keys plus 1 for CommandOrd. **************************************************************} function GetCommand(var KeySet; KeyPtr : Pointer; var ChWord : Word) : Byte; {-Get next command or character} function AddCommandPrim(var KeySet; LastKeyIndex : Word; Cmd, NumKeys : Byte; Key1, Key2 : Word) : Boolean; {-Add a new command key assignment or change an existing one} procedure GetKeysForCommand(var KeySet; Cmd : Byte; var NumKeys : Byte; var Key1, Key2 : Word); {-Search KeySet for Cmd, returning first set of matching keys. NumKeys = 0 if no match found} {--- the following routines, etc. are for installation programs ---} const MaxKeys = 300; MaxCommands = 150; KeyLength = 6; type KeyString = string[KeyLength]; KeyRec = record Modified : Boolean; Conflict : Boolean; CommandCode : Byte; Keys : KeyString; end; UnpackedKeyArray = array[1..MaxCommands] of KeyRec; UnpackedKeyPtr = ^UnpackedKeyArray; PackedKeyArray = array[0..MaxKeys] of Byte; PackedKeyPtr = ^PackedKeyArray; function UnpackKeys(var PackedKeys, UnpackedKeys; MaxCmds : Word; Cols : Byte) : Word; {-Unpack keys into a fixed element array. Returns number of commands in PackedKeys.} function PackKeys(var PackedKeys; NumCmds, MaxBytes : Word; var UnpackedKeys) : Word; {-Convert fixed array into a packed list of keys again. Returns the number of keys that we *wanted* to store. Error if that number is greater than MaxBytes.} function SizeKeys(var UnpackedKeys; NumCmds : Word) : Word; {-Return number of bytes in packed version of UnpackedKeys} function ConflictsFound(var UnpackedKeys; NumCmds : Word) : Boolean; {-Check UnpackedKeys for conflicts. Returns True if Conflicts were found} {--- the following routine is intended for internal use ---} function CheckForKeyConflict(var KeySet; LastKeyIndex : Word; Cmd, NumKeys : Byte; Key1, Key2 : Word) : MatchType; {-Check to see if the specified key combination conflicts with an existing one} {======================================================} implementation type KeyArray = array[0..32000] of Byte; KeyArrayPtr = ^KeyArray; CmdBuffArray = array[0..5] of Byte; function WordStarCommand(K : Byte) : Byte; {-Return ^C, 'C', or 'c' as ^C, etc.} var C : Char absolute K; begin C := Upcase(C); case C of 'A'..'_' : WordStarCommand := K-64; else WordStarCommand := K; end; end; function ScanCommands(K : KeyArrayPtr; var CmdBuffer : CmdBuffArray; BufNext : Word; var Cmd : Byte; var FoundAt : Word) : MatchType; {-Scan K^ for a match on CmdBuffer} var BufIndex : Word; CmdIndex : Word; CmdLen : Byte; Matching : Boolean; begin Cmd := NoCmd; CmdIndex := 0; CmdLen := K^[CmdIndex]; {Scan the command list} while CmdLen <> 0 do begin FoundAt := CmdIndex; Inc(CmdIndex); BufIndex := 0; Matching := True; while Matching and (BufIndex < BufNext) and (BufIndex < CmdLen-1) do if CmdBuffer[BufIndex] = K^[CmdIndex+BufIndex] then Inc(BufIndex) else Matching := False; if not Matching then begin {No match, try next command} Inc(CmdIndex, CmdLen); CmdLen := K^[CmdIndex]; end else begin if BufNext = CmdLen-1 then begin {Complete match} ScanCommands := FullMatch; Cmd := K^[CmdIndex+BufIndex]; end else ScanCommands := PartMatch; Exit; end; end; {No match if we get here} ScanCommands := NoMatch; end; function GetCommand(var KeySet; KeyPtr : Pointer; var ChWord : Word) : Byte; {-Get next command or character. Returns NoCmd for no matching command, AlphaCmd for alphabetic character.} var LCh : Byte; Cmd : Byte; Junk : Word; BufNext : Word; Done : Boolean; CmdBuffer : CmdBuffArray; function GetKeyWord : Word; {-Call routine pointed to by KeyPtr} inline($FF/$5E/<KeyPtr); {Call dword ptr [bp+<KeyPtr]} begin BufNext := 0; Cmd := NoCmd; Done := False; repeat {Get the next keystroke} ChWord := GetKeyWord; LCh := Lo(ChWord); if LCh = 0 then begin {Extended keystroke} CmdBuffer[BufNext] := 0; Inc(BufNext); LCh := Hi(ChWord); end else if (BufNext > 0) and MapWordStar then {Map WordStar keystrokes} LCh := WordStarCommand(LCh); CmdBuffer[BufNext] := LCh; Inc(BufNext); {Map to a command} case ScanCommands(@KeySet, CmdBuffer, BufNext, Cmd, Junk) of FullMatch : Done := True; NoMatch : begin {Return alphanumeric character if it isn't a command} if (BufNext = 1) and (Char(LCh) >= ' ') and (Char(LCh) <> #127) then Cmd := AlphaCmd; Done := True; end; end; until Done; GetCommand := Cmd; end; procedure InitCmdBuffer(var CmdBuffer : CmdBuffArray; NumKeys : Byte; Key1, Key2 : Word; var BufNext : Word); {-Initialize a CmdBuffArray} begin if Lo(Key1) = 0 then begin CmdBuffer[0] := 0; CmdBuffer[1] := Hi(Key1); BufNext := 2; end else begin CmdBuffer[0] := Lo(Key1); BufNext := 1; end; if NumKeys = 2 then if Lo(Key2) = 0 then begin CmdBuffer[BufNext] := 0; Inc(BufNext); CmdBuffer[BufNext] := Hi(Key2); Inc(BufNext); end else begin CmdBuffer[BufNext] := Lo(Key2); Inc(BufNext); end; end; function CheckForKeyConflict(var KeySet; LastKeyIndex : Word; Cmd, NumKeys : Byte; Key1, Key2 : Word) : MatchType; {-Check to see if the specified key combination conflicts with an existing one} var MT : MatchType; BufNext : Word; CTmp : Byte; FoundAt : Word; CmdBuffer : CmdBuffArray; begin if NumKeys = 0 then MT := NoMatch else begin {set up for the search} InitCmdBuffer(CmdBuffer, NumKeys, Key1, Key2, BufNext); {check for duplicate} MT := ScanCommands(@KeySet, CmdBuffer, BufNext, CTmp, FoundAt); end; CheckForKeyConflict := MT; end; function AddCommandPrim(var KeySet; LastKeyIndex : Word; Cmd, NumKeys : Byte; Key1, Key2 : Word) : Boolean; {-Add a new command key assignment or change an existing one} var EditKeys : KeyArray absolute KeySet; CTmp : Byte; SlotFound : Boolean; CmdLen, FoundAt : Word; MT : MatchType; NextCmdIndex : Word; BufNext : Word; CmdBuffer : CmdBuffArray; begin AddCommandPrim := False; if (NumKeys < 1) or (NumKeys > 2) then Exit; {set up for the search} InitCmdBuffer(CmdBuffer, NumKeys, Key1, Key2, BufNext); {check for duplicate} MT := ScanCommands(@KeySet, CmdBuffer, BufNext, CTmp, FoundAt); case MT of FullMatch : begin {change the command} CmdLen := EditKeys[FoundAt]; if Cmd = NoCmd then begin {Disable the keystrokes as well} NextCmdIndex := FoundAt+1; while NextCmdIndex < FoundAt+CmdLen do begin EditKeys[NextCmdIndex] := $FF; Inc(NextCmdIndex); end; end; EditKeys[FoundAt+CmdLen] := Cmd; AddCommandPrim := True; Exit; end; PartMatch : Exit; end; {find next available command slot} NextCmdIndex := 0; SlotFound := False; while not SlotFound and (EditKeys[NextCmdIndex] <> 0) do begin CmdLen := EditKeys[NextCmdIndex]; if EditKeys[NextCmdIndex+CmdLen] = NoCmd then {Command slot is available for reuse} if BufNext+1 = CmdLen then {Slot is the right size} SlotFound := True; if not SlotFound then Inc(NextCmdIndex, EditKeys[NextCmdIndex]+1); end; {make sure it will fit} if (BufNext+2) <= (LastKeyIndex-NextCmdIndex) then begin {plug in the key} EditKeys[NextCmdIndex] := BufNext+1; Inc(NextCmdIndex); Move(CmdBuffer, EditKeys[NextCmdIndex], BufNext); Inc(NextCmdIndex, BufNext); EditKeys[NextCmdIndex] := Cmd; Inc(NextCmdIndex); AddCommandPrim := True; end; end; procedure GetKeysForCommand(var KeySet; Cmd : Byte; var NumKeys : Byte; var Key1, Key2 : Word); {-Search KeySet for Cmd, returning first set of matching keys. NumKeys = 0 if no match found} var Keys : KeyArray absolute KeySet; Kofs : Word; TKey : Word; Klen : Integer; begin NumKeys := 0; Kofs := 0; repeat Klen := Keys[Kofs]; if Klen <> 0 then if Keys[Kofs+Klen] = Cmd then begin {Matches command} {Reduce length by one to avoid Cmd} Dec(Klen); repeat {Get next key byte} Inc(Kofs); Dec(Klen); if Keys[Kofs] = 0 then begin {Extended keystroke} Inc(Kofs); Dec(Klen); TKey := Word(Keys[Kofs]) shl 8; end else {Normal keystroke} TKey := Keys[Kofs]; {Store the keys} Inc(NumKeys); if NumKeys = 1 then Key1 := TKey else if NumKeys = 2 then Key2 := TKey; until Klen <= 0; {Don't allow more than two keys} if NumKeys > 2 then NumKeys := 2; Exit; end; Inc(Kofs, Klen+1); until Klen = 0; {No match} end; function UnpackKeys(var PackedKeys, UnpackedKeys; MaxCmds : Word; Cols : Byte) : Word; {-Unpack keys into a fixed element array. Returns number of commands in PackedKeys.} var PK : PackedKeyArray absolute PackedKeys; UK : UnpackedKeyArray absolute UnpackedKeys; Count, CmdNum, KeyOfs : Word; I, Len : Word; label Done; begin if Cols = 0 then Cols := 1; FillChar(UK, MaxCmds*SizeOf(KeyRec), 0); for I := 1 to MaxCmds do with UK[I] do CommandCode := (Pred(I) div Cols)+1; KeyOfs := 0; Count := 0; while PK[KeyOfs] <> 0 do begin Inc(Count); Len := PK[KeyOfs]; {find an unused entry in the proper row} CmdNum := Word(PK[KeyOfs+Len]-1)*3+1; for I := 1 to Cols do with UK[CmdNum] do if Length(Keys) = 0 then with UK[CmdNum] do begin Move(PK[KeyOfs], Keys, Len); Dec(Keys[0]); goto Done; end else Inc(CmdNum); Done: Inc(KeyOfs, Len+1); end; UnpackKeys := Count; end; function PackKeys(var PackedKeys; NumCmds, MaxBytes : Word; var UnpackedKeys) : Word; {-Convert fixed array into a packed list of keys again. Returns the number of keys that we *wanted* to store. Error if that number is greater than MaxBytes.} var PK : PackedKeyArray absolute PackedKeys; UK : UnpackedKeyArray absolute UnpackedKeys; Len : Byte; CmdNum : Word; KeyOfs : Word; KeyNew : Word; begin FillChar(PK, MaxBytes, 0); KeyOfs := 0; for CmdNum := 1 to NumCmds do with UK[CmdNum] do if Length(Keys) <> 0 then begin Len := Length(Keys)+1; KeyNew := KeyOfs+Len+1; if KeyNew <= MaxBytes then begin {Store the keys if they fit} Inc(Keys[0]); Move(Keys, PK[KeyOfs], Len); PK[KeyNew-1] := CommandCode; end; KeyOfs := KeyNew; end; {Return the number of keys we wanted to store} PackKeys := KeyOfs; end; function SizeKeys(var UnpackedKeys; NumCmds : Word) : Word; {-Return number of bytes in packed version of UnpackedKeys} var UK : UnpackedKeyArray absolute UnpackedKeys; CmdNum : Word; Size : Word; begin Size := 0; for CmdNum := 1 to NumCmds do with UK[CmdNum] do if Length(Keys) <> 0 then Inc(Size, Length(Keys)+2); SizeKeys := Size; end; function ConflictsFound(var UnpackedKeys; NumCmds : Word) : Boolean; {-Check UnpackedKeys for conflicts. Returns False if Conflicts found} var I, J : Word; UK : UnpackedKeyArray absolute UnpackedKeys; begin {assume success} ConflictsFound := False; {turn off all Conflict flags} for I := 1 to NumCmds do UK[I].Conflict := False; {check for conflicts} for I := 1 to NumCmds do with UK[I] do if Length(Keys) <> 0 then for J := 1 to NumCmds do if (J <> I) and (Length(UK[J].Keys) <> 0) then if Pos(UK[J].Keys, Keys) = 1 then begin UK[I].Conflict := True; UK[J].Conflict := True; ConflictsFound := True; end; end; end. 
unit uObsevacaoController; interface uses System.SysUtils, uDMObservacao, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms, uFuncoesSIDomper, Data.DBXJSON, Data.DBXJSONReflect, uConverter, uGenericProperty; type TObservacaoController = class private FModel: TDMObservacao; FOperacao: TOperacao; procedure Post; public procedure Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure FiltrarCodigo(ACodigo: Integer); procedure FiltrarPrograma(AObservacaoPrograma: TEnumPrograma; ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure LocalizarPadrao(APrograma: TEnumPrograma); procedure LocalizarEmailPadrao(APrograma: TEnumPrograma); procedure LocalizarId(AId: Integer); procedure LocalizarCodigo(ACodigo: 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); function ProximoId(): Integer; function ProximoCodigo(): Integer; procedure Pesquisar(AId, Codigo: Integer); function CodigoAtual: Integer; property Model: TDMObservacao read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TObservacaoController } uses uObservacaoVO; procedure TObservacaoController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; function TObservacaoController.CodigoAtual: Integer; begin Result := FModel.CDSCadastroObs_Codigo.AsInteger; end; constructor TObservacaoController.Create; begin inherited Create; FModel := TDMObservacao.Create(nil); end; destructor TObservacaoController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TObservacaoController.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(CObservacao, dm.IdUsuario, AId); FModel.CDSCadastro.Open; TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TObservacaoController.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(CObservacao, AIdUsuario, AId); FModel.CDSConsulta.Delete; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TObservacaoController.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(CObservacao, ACampo, ATexto, AAtivo, AContem); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TObservacaoController.FiltrarCodigo(ACodigo: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.FiltrarCodigo(CObservacao, ACodigo); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TObservacaoController.FiltrarPrograma(AObservacaoPrograma: TEnumPrograma; ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerModule2Client; iEnum: Integer; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try iEnum := Integer(AObservacaoPrograma); FModel.CDSConsulta.Close; Negocio.FiltrarObservacaoPrograma(ACampo, ATexto, AAtivo, iEnum, AContem); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TObservacaoController.Imprimir(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try Negocio.Relatorio(CObservacao, AIdUsuario); FModel.Rel.Print; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TObservacaoController.LocalizarCodigo(ACodigo: integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarCodigo(CObservacao, ACodigo); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TObservacaoController.LocalizarEmailPadrao(APrograma: TEnumPrograma); var Negocio: TServerModule2Client; iEnum: Integer; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try iEnum := Integer(APrograma); FModel.CDSCadastro.Close; Negocio.ObservacaoEmailPadrao(iEnum); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TObservacaoController.LocalizarId(AId: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarId(CObservacao, AId); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TObservacaoController.LocalizarPadrao(APrograma: TEnumPrograma); var Negocio: TServerModule2Client; iEnum: Integer; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try iEnum := Integer(APrograma); FModel.CDSCadastro.Close; Negocio.ObservacaoPadrao(iEnum); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TObservacaoController.Novo(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.Novo(CObservacao, AIdUsuario); FModel.CDSCadastro.Open; FModel.CDSCadastro.Append; FModel.CDSCadastroObs_Codigo.AsInteger := ProximoCodigo(); FOperacao := opIncluir; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TObservacaoController.Pesquisar(AId, Codigo: Integer); begin if AId > 0 then LocalizarId(AId) else LocalizarCodigo(Codigo); end; procedure TObservacaoController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; end; function TObservacaoController.ProximoCodigo: Integer; var Negocio: TServerModule2Client; iCodigo: Integer; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try iCodigo := StrToInt(Negocio.ProximoCodigo(CObservacao).ToString); Result := iCodigo; dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TObservacaoController.ProximoId: Integer; var Negocio: TServerModule2Client; iCodigo: Integer; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try iCodigo := StrToInt(Negocio.ProximoId(CObservacao).ToString); Result := iCodigo; dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TObservacaoController.Salvar(AIdUsuario: Integer): Integer; var Negocio: TServerModule2Client; ObjVO: TObservacaoVO; oObjetoJSON : TJSONValue; begin ObjVO := TObservacaoVO.Create; DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try TGenericProperty.SetProperty<TObservacaoVO>(ObjVO, FModel.cdsCadastro); oObjetoJSON := TConverte.ObjectToJSON(ObjVO); Result := StrToIntDef(Negocio.ObservacaoSalvar(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 SctCalc; { ---------------------------------------------------------------- Ace Reporter Copyright 1995-2004 SCT Associates, Inc. Written by Kevin Maher, Steve Tyrakowski ---------------------------------------------------------------- } interface {$I ace.inc} uses classes; type { TSctCalc } TSctCalc = class(TObject) private FValue, FSum, FMin, FMax: Double; FCount: LongInt; protected function GetAverage: Double; procedure NewVal(Val: Double); public constructor Create; virtual; destructor Destroy; override; procedure Update; virtual; property Value: Double read FValue write NewVal; property Sum: Double read FSum write FSum; property Count: LongInt read FCount write FCount; property Min: Double read FMin write FMin; property Max: Double read FMax write FMax; property Average: Double read GetAverage; procedure Reset; end; { TSctCurrCalc } TSctCurrCalc = class(TObject) private FValue, FSum, FMin, FMax: Currency; FCount: LongInt; protected function GetAverage: Currency; procedure NewVal(Val: Currency); public constructor Create; virtual; destructor Destroy; override; procedure Update; virtual; property Value: Currency read FValue write NewVal; property Sum: Currency read FSum write FSum; property Count: LongInt read FCount write FCount; property Min: Currency read FMin write FMin; property Max: Currency read FMax write FMax; property Average: Currency read GetAverage; procedure Reset; end; implementation { TSctCalc } constructor TSctCalc.Create; begin inherited Create; reset; end; destructor TSctCalc.Destroy; begin inherited Destroy; end; function TSctCalc.GetAverage: Double; begin if Count = 0 Then Result := 0 else Result := (Sum / Count); end; procedure TSctCalc.NewVal(Val: Double); begin FValue := Val; update; end; procedure TSctCalc.update; begin Sum := Sum + Value; if (Count = 0) Then begin Max := Value; Min := Value; end; if Value > Max Then Max := Value; if Value < Min Then Min := Value; Count := Count + 1; end; procedure TSctCalc.Reset; begin Sum := 0; Count := 0; Max := 0; Min := 0; FValue := 0; end; { TSctCurrCalc } constructor TSctCurrCalc.Create; begin inherited Create; reset; end; destructor TSctCurrCalc.Destroy; begin inherited Destroy; end; function TSctCurrCalc.GetAverage: Currency; begin if Count = 0 Then Result := 0 else Result := (Sum / Count); end; procedure TSctCurrCalc.NewVal(Val: Currency); begin FValue := Val; update; end; procedure TSctCurrCalc.update; begin Sum := Sum + Value; if (Count = 0) Then begin Max := Value; Min := Value; end; if Value > Max Then Max := Value; if Value < Min Then Min := Value; Count := Count + 1; end; procedure TSctCurrCalc.Reset; begin Sum := 0; Count := 0; Max := 0; Min := 0; FValue := 0; end; end.
{ Date Created: 5/24/00 2:53:17 PM } unit InfoCECODESTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoCECODESRecord = record PCode: String[8]; PName: String[30]; PAddress1: String[30]; PAddress2: String[30]; PAddress3: String[30]; PCityState: String[25]; PZipCode: String[10]; PContact: String[30]; PPhone: String[30]; PCheckingAccount: String[4]; PLicenseExpiration: String[10]; PCheckHold: Boolean; End; TInfoCECODESBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoCECODESRecord end; TEIInfoCECODES = (InfoCECODESPrimaryKey); TInfoCECODESTable = class( TDBISAMTableAU ) private FDFCode: TStringField; FDFName: TStringField; FDFAddress1: TStringField; FDFAddress2: TStringField; FDFAddress3: TStringField; FDFCityState: TStringField; FDFZipCode: TStringField; FDFContact: TStringField; FDFPhone: TStringField; FDFCheckingAccount: TStringField; FDFLicenseExpiration: TStringField; FDFCheckHold: TBooleanField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPName(const Value: String); function GetPName:String; procedure SetPAddress1(const Value: String); function GetPAddress1:String; procedure SetPAddress2(const Value: String); function GetPAddress2:String; procedure SetPAddress3(const Value: String); function GetPAddress3:String; procedure SetPCityState(const Value: String); function GetPCityState:String; procedure SetPZipCode(const Value: String); function GetPZipCode:String; procedure SetPContact(const Value: String); function GetPContact:String; procedure SetPPhone(const Value: String); function GetPPhone:String; procedure SetPCheckingAccount(const Value: String); function GetPCheckingAccount:String; procedure SetPLicenseExpiration(const Value: String); function GetPLicenseExpiration:String; procedure SetPCheckHold(const Value: Boolean); function GetPCheckHold:Boolean; procedure SetEnumIndex(Value: TEIInfoCECODES); function GetEnumIndex: TEIInfoCECODES; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoCECODESRecord; procedure StoreDataBuffer(ABuffer:TInfoCECODESRecord); property DFCode: TStringField read FDFCode; property DFName: TStringField read FDFName; property DFAddress1: TStringField read FDFAddress1; property DFAddress2: TStringField read FDFAddress2; property DFAddress3: TStringField read FDFAddress3; property DFCityState: TStringField read FDFCityState; property DFZipCode: TStringField read FDFZipCode; property DFContact: TStringField read FDFContact; property DFPhone: TStringField read FDFPhone; property DFCheckingAccount: TStringField read FDFCheckingAccount; property DFLicenseExpiration: TStringField read FDFLicenseExpiration; property DFCheckHold: TBooleanField read FDFCheckHold; property PCode: String read GetPCode write SetPCode; property PName: String read GetPName write SetPName; property PAddress1: String read GetPAddress1 write SetPAddress1; property PAddress2: String read GetPAddress2 write SetPAddress2; property PAddress3: String read GetPAddress3 write SetPAddress3; property PCityState: String read GetPCityState write SetPCityState; property PZipCode: String read GetPZipCode write SetPZipCode; property PContact: String read GetPContact write SetPContact; property PPhone: String read GetPPhone write SetPPhone; property PCheckingAccount: String read GetPCheckingAccount write SetPCheckingAccount; property PLicenseExpiration: String read GetPLicenseExpiration write SetPLicenseExpiration; property PCheckHold: Boolean read GetPCheckHold write SetPCheckHold; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoCECODES read GetEnumIndex write SetEnumIndex; end; { TInfoCECODESTable } procedure Register; implementation procedure TInfoCECODESTable.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFName := CreateField( 'Name' ) as TStringField; FDFAddress1 := CreateField( 'Address1' ) as TStringField; FDFAddress2 := CreateField( 'Address2' ) as TStringField; FDFAddress3 := CreateField( 'Address3' ) as TStringField; FDFCityState := CreateField( 'CityState' ) as TStringField; FDFZipCode := CreateField( 'ZipCode' ) as TStringField; FDFContact := CreateField( 'Contact' ) as TStringField; FDFPhone := CreateField( 'Phone' ) as TStringField; FDFCheckingAccount := CreateField( 'CheckingAccount' ) as TStringField; FDFLicenseExpiration := CreateField( 'LicenseExpiration' ) as TStringField; FDFCheckHold := CreateField( 'CheckHold' ) as TBooleanField; end; { TInfoCECODESTable.CreateFields } procedure TInfoCECODESTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoCECODESTable.SetActive } procedure TInfoCECODESTable.Validate; begin { Enter Validation Code Here } end; { TInfoCECODESTable.Validate } procedure TInfoCECODESTable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoCECODESTable.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoCECODESTable.SetPName(const Value: String); begin DFName.Value := Value; end; function TInfoCECODESTable.GetPName:String; begin result := DFName.Value; end; procedure TInfoCECODESTable.SetPAddress1(const Value: String); begin DFAddress1.Value := Value; end; function TInfoCECODESTable.GetPAddress1:String; begin result := DFAddress1.Value; end; procedure TInfoCECODESTable.SetPAddress2(const Value: String); begin DFAddress2.Value := Value; end; function TInfoCECODESTable.GetPAddress2:String; begin result := DFAddress2.Value; end; procedure TInfoCECODESTable.SetPAddress3(const Value: String); begin DFAddress3.Value := Value; end; function TInfoCECODESTable.GetPAddress3:String; begin result := DFAddress3.Value; end; procedure TInfoCECODESTable.SetPCityState(const Value: String); begin DFCityState.Value := Value; end; function TInfoCECODESTable.GetPCityState:String; begin result := DFCityState.Value; end; procedure TInfoCECODESTable.SetPZipCode(const Value: String); begin DFZipCode.Value := Value; end; function TInfoCECODESTable.GetPZipCode:String; begin result := DFZipCode.Value; end; procedure TInfoCECODESTable.SetPContact(const Value: String); begin DFContact.Value := Value; end; function TInfoCECODESTable.GetPContact:String; begin result := DFContact.Value; end; procedure TInfoCECODESTable.SetPPhone(const Value: String); begin DFPhone.Value := Value; end; function TInfoCECODESTable.GetPPhone:String; begin result := DFPhone.Value; end; procedure TInfoCECODESTable.SetPCheckingAccount(const Value: String); begin DFCheckingAccount.Value := Value; end; function TInfoCECODESTable.GetPCheckingAccount:String; begin result := DFCheckingAccount.Value; end; procedure TInfoCECODESTable.SetPLicenseExpiration(const Value: String); begin DFLicenseExpiration.Value := Value; end; function TInfoCECODESTable.GetPLicenseExpiration:String; begin result := DFLicenseExpiration.Value; end; procedure TInfoCECODESTable.SetPCheckHold(const Value: Boolean); begin DFCheckHold.Value := Value; end; function TInfoCECODESTable.GetPCheckHold:Boolean; begin result := DFCheckHold.Value; end; procedure TInfoCECODESTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Code, String, 8, N'); Add('Name, String, 30, N'); Add('Address1, String, 30, N'); Add('Address2, String, 30, N'); Add('Address3, String, 30, N'); Add('CityState, String, 25, N'); Add('ZipCode, String, 10, N'); Add('Contact, String, 30, N'); Add('Phone, String, 30, N'); Add('CheckingAccount, String, 4, N'); Add('LicenseExpiration, String, 10, N'); Add('CheckHold, Boolean, 0, N'); end; end; procedure TInfoCECODESTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Code, Y, Y, N, N'); end; end; procedure TInfoCECODESTable.SetEnumIndex(Value: TEIInfoCECODES); begin case Value of InfoCECODESPrimaryKey : IndexName := ''; end; end; function TInfoCECODESTable.GetDataBuffer:TInfoCECODESRecord; var buf: TInfoCECODESRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PName := DFName.Value; buf.PAddress1 := DFAddress1.Value; buf.PAddress2 := DFAddress2.Value; buf.PAddress3 := DFAddress3.Value; buf.PCityState := DFCityState.Value; buf.PZipCode := DFZipCode.Value; buf.PContact := DFContact.Value; buf.PPhone := DFPhone.Value; buf.PCheckingAccount := DFCheckingAccount.Value; buf.PLicenseExpiration := DFLicenseExpiration.Value; buf.PCheckHold := DFCheckHold.Value; result := buf; end; procedure TInfoCECODESTable.StoreDataBuffer(ABuffer:TInfoCECODESRecord); begin DFCode.Value := ABuffer.PCode; DFName.Value := ABuffer.PName; DFAddress1.Value := ABuffer.PAddress1; DFAddress2.Value := ABuffer.PAddress2; DFAddress3.Value := ABuffer.PAddress3; DFCityState.Value := ABuffer.PCityState; DFZipCode.Value := ABuffer.PZipCode; DFContact.Value := ABuffer.PContact; DFPhone.Value := ABuffer.PPhone; DFCheckingAccount.Value := ABuffer.PCheckingAccount; DFLicenseExpiration.Value := ABuffer.PLicenseExpiration; DFCheckHold.Value := ABuffer.PCheckHold; end; function TInfoCECODESTable.GetEnumIndex: TEIInfoCECODES; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoCECODESPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoCECODESTable, TInfoCECODESBuffer ] ); end; { Register } function TInfoCECODESBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCode; 2 : result := @Data.PName; 3 : result := @Data.PAddress1; 4 : result := @Data.PAddress2; 5 : result := @Data.PAddress3; 6 : result := @Data.PCityState; 7 : result := @Data.PZipCode; 8 : result := @Data.PContact; 9 : result := @Data.PPhone; 10 : result := @Data.PCheckingAccount; 11 : result := @Data.PLicenseExpiration; 12 : result := @Data.PCheckHold; end; end; end. { InfoCECODESTable }
unit Thread.ImportarPedidosDIRECT; interface uses System.Classes, Control.Entregas, System.SysUtils, System.DateUtils, Control.VerbasExpressas, Control.Bases, Control.EntregadoresExpressas, Generics.Collections, System.StrUtils, Control.ControleAWB, Control.PlanilhaEntradaDIRECT, FireDAC.Comp.Client; type TThread_ImportarPedidosDIRECT = class(TThread) private { Private declarations } FPlanilha: TPlanilhaEntradaDIRECTControl; FEntregas: TEntregasControl; FVerbas: TVerbasExpressasControl; FBases: TBasesControl; FEntregadores: TEntregadoresExpressasControl; FControleAWB: TControleAWBControl; protected procedure Execute; override; procedure UpdateLOG(sMensagem: string); procedure UpdateProgress(dPosition: Double); procedure BeginProcesso; procedure TerminateProcess; public FFile: String; iCodigoCliente: Integer; bCancel : Boolean; bProcess: Boolean; dPositionRegister: double; sLog: String; sAlerta: String; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TThread_ImportarPedidosDIRECT.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } uses Common.ENum, Global.Parametros; { TThread_ImportarPedidosDIRECT } procedure TThread_ImportarPedidosDIRECT.BeginProcesso; var sMensagem: String; begin sLog := ''; bCancel := False; Global.Parametros.pbProcess := True; sMensagem := ''; sMensagem := '>> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' > tratando os dados da planilha. Aguarde...'; UpdateLog(sMensagem); end; procedure TThread_ImportarPedidosDIRECT.Execute; var aParam: Array of variant; iPos, iPosition, iTotal, i, iTipo: Integer; sCEP, sMensagem, sOperacao: String; dPos, dPerformance, dPeso: double; slParam: TStringList; bProcess: Boolean; begin try try BeginProcesso; FPlanilha := TPlanilhaEntradaDIRECTControl.Create; FEntregas := TEntregasControl.Create; if FPLanilha.GetPlanilha(FFile) then begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importando os dados. Aguarde...'; UpdateLOG(sMensagem); iPos := 0; iPosition := 0; dPos := 0; iTotal := FPlanilha.Planilha.Planilha.Count; for i := 0 to Pred(iTotal) do begin SetLength(aParam,3); aParam := ['NNCLIENTE', FPlanilha.Planilha.Planilha[i].Remessa, iCodigoCliente]; if not FEntregas.LocalizarExata(aParam) then begin FEntregas.Entregas.NN := FPlanilha.Planilha.Planilha[i].Remessa; FEntregas.Entregas.Distribuidor := 0; FEntregas.Entregas.Entregador := 0; FEntregas.Entregas.Cliente := FPlanilha.Planilha.Planilha[i].CodigoEmbarcador; FEntregas.Entregas.NF := FPlanilha.Planilha.Planilha[i].NF; FEntregas.Entregas.Consumidor := FPlanilha.Planilha.Planilha[i].NomeConsumidor; FEntregas.Entregas.Endereco := ''; FEntregas.Entregas.Complemento := ''; FEntregas.Entregas.Bairro := FPlanilha.Planilha.Planilha[i].Bairro; FEntregas.Entregas.Cidade := FPlanilha.Planilha.Planilha[i].Municipio; FEntregas.Entregas.Cep := FPlanilha.Planilha.Planilha[i].CEP; FEntregas.Entregas.Telefone := ''; FEntregas.Entregas.Expedicao := FPlanilha.Planilha.Planilha[i].DataRegistro; FEntregas.Entregas.Previsao := IncDay(FPlanilha.Planilha.Planilha[i].DataChegadaLM, 1); FEntregas.Entregas.Volumes := FPlanilha.Planilha.Planilha[i].Volumes; FEntregas.Entregas.Atribuicao := StrToDate('30/12/1899'); FEntregas.Entregas.Baixa := StrToDate('30/12/1899'); FEntregas.Entregas.Baixado := 'N'; FEntregas.Entregas.Pagamento := StrToDate('30/12/1899'); FEntregas.Entregas.Pago := 'N'; FEntregas.Entregas.Fechado := 'N'; FEntregas.Entregas.Status := 0; FEntregas.Entregas.Entrega := StrToDate('30/12/1899'); FEntregas.Entregas.TipoPeso := FPlanilha.Planilha.Planilha[i].Tipo; dPeso := 0; if FPlanilha.Planilha.Planilha[i].PesoCubado > FPlanilha.Planilha.Planilha[i].PesoNominal then begin FEntregas.Entregas.PesoReal := FPlanilha.Planilha.Planilha[i].PesoCubado; end else begin FEntregas.Entregas.PesoReal := FPlanilha.Planilha.Planilha[i].PesoNominal; end; dPeso := FEntregas.Entregas.PesoReal; FEntregas.Entregas.PesoFranquia := 0; FEntregas.Entregas.Advalorem := 0; FEntregas.Entregas.PagoFranquia := 0; FEntregas.Entregas.VerbaEntregador := 0; FEntregas.Entregas.Extrato := '0'; FEntregas.Entregas.Atraso := 0; FEntregas.Entregas.VolumesExtra := 0; FEntregas.Entregas.ValorVolumes := 0; FEntregas.Entregas.PesoCobrado := FEntregas.Entregas.PesoReal; FEntregas.Entregas.Recebimento := StrToDate('30/12/1899'); FEntregas.Entregas.Recebido := 'N'; FEntregas.Entregas.CTRC := 0; FEntregas.Entregas.Manifesto := 0; FEntregas.Entregas.Rastreio := ''; FEntregas.Entregas.VerbaFranquia := 0; FEntregas.Entregas.Lote := 0; FEntregas.Entregas.Retorno := FPlanilha.Planilha.Planilha[i].Chave; FEntregas.Entregas.Credito := StrToDate('30/12/1899');; FEntregas.Entregas.Creditado := 'N'; FEntregas.Entregas.Container := '0'; FEntregas.Entregas.ValorProduto := FPlanilha.Planilha.Planilha[i].Valor; FEntregas.Entregas.Altura := 0; FEntregas.Entregas.Largura := 0; FEntregas.Entregas.Comprimento := 0; FEntregas.Entregas.CodigoFeedback := 0; FEntregas.Entregas.DataFeedback := StrToDate('30/12/1899'); FEntregas.Entregas.Conferido := 0; FEntregas.Entregas.Pedido := FPlanilha.Planilha.Planilha[i].Pedido; FEntregas.Entregas.CodCliente := iCodigoCliente; FEntregas.Entregas.Status := 909; FEntregas.Entregas.Rastreio := '> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importado por ' + Global.Parametros.pUser_Name; FEntregas.Entregas.Acao := tacIncluir; end else begin FEntregas.Entregas.Status := 909; FEntregas.Entregas.Rastreio := FEntregas.Entregas.Rastreio + #13 + '> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' atualizado por importação por ' + Global.Parametros.pUser_Name; FEntregas.Entregas.Acao := tacAlterar; end; Finalize(aParam); if not FEntregas.Gravar() then begin sMensagem := 'Erro ao gravar o NN ' + Fentregas.Entregas.NN + ' !'; UpdateLog(sMensagem); end; iTipo := 0; sOperacao := ''; FControleAWB := TControleAWBControl.Create; if Pos('- TD -', FPlanilha.Planilha.Planilha[iPos].Operacao) > 0 then begin sOperacao := 'TD'; end else if Pos('- TC -', FPlanilha.Planilha.Planilha[iPos].Operacao) > 0 then begin sOperacao := 'TC'; end; SetLength(aParam, 3); aParam := ['REMESSAAWB1', FPlanilha.Planilha.Planilha[iPos].Remessa,FPlanilha.Planilha.Planilha[iPos].AWB1]; if not FControleAWB.LocalizarExato(aParam) then begin FControleAWB.ControleAWB.Remessa := FPlanilha.Planilha.Planilha[iPos].Remessa; FControleAWB.ControleAWB.AWB1 := FPlanilha.Planilha.Planilha[iPos].AWB1; FControleAWB.ControleAWB.AWB2 := FPlanilha.Planilha.Planilha[iPos].AWB2; FControleAWB.ControleAWB.CEP := ReplaceStr(FPlanilha.Planilha.Planilha[iPos].CEP,'-',''); FControleAWB.ControleAWB.Operacao := sOperacao; FControleAWB.ControleAWB.Tipo := iTipo; FControleAWB.ControleAWB.Peso := dPeso; FControleAWB.ControleAWB.Acao := tacIncluir; end; Finalize(aParam); FControleAWB.Free; inc(iPos, 1); dPos := (iPos / iTotal) * 100; if not(Self.Terminated) then begin UpdateProgress(dPos); end else begin Abort; end; end; Synchronize(TerminateProcess); end; Except on E: Exception do begin sMensagem := '** ERROR **' + Chr(13) + 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message; UpdateLog(sMensagem); bCancel := True; end; end; finally FPlanilha.Free; FEntregas.Free; end; end; procedure TThread_ImportarPedidosDIRECT.TerminateProcess; begin Global.Parametros.pbProcess := False; end; procedure TThread_ImportarPedidosDIRECT.UpdateLOG(sMensagem: string); begin if Global.Parametros.psLog <> '' then begin Global.Parametros.psLog := Global.Parametros.psLog + #13; end; Global.Parametros.psLog := Global.Parametros.psLog + sMensagem; end; procedure TThread_ImportarPedidosDIRECT.UpdateProgress(dPosition: Double); begin Global.Parametros.pdPos := dPosition; end; end.
unit Fornecedores; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, DBCtrls, Mask, Grids, DBGrids, Buttons, ExtCtrls; type TformFornecedores = class(TForm) pgFornecedor: TPageControl; tabFornecedor: TTabSheet; fldCodigoFornecedor: TDBText; lblCodigoFornecedor: TLabel; lblNomeFantasia: TLabel; fldNomeFantasia: TDBEdit; lblRazaoSocial: TLabel; fldRazaoSocial: TDBEdit; lblCGC: TLabel; fldCGC: TDBEdit; lblTipoFornecedor: TLabel; fldTipoFornecedor: TDBComboBox; lblEndereco: TLabel; fldEndereco: TDBEdit; lblNumero: TLabel; fldNumero: TDBEdit; lblBairro: TLabel; fldBairro: TDBEdit; fldCidade: TDBEdit; lblCidade: TLabel; lblEstado: TLabel; fldCEP: TDBEdit; lblCEP: TLabel; fldEstado: TDBComboBox; fldTelefone: TDBEdit; fldFAX: TDBEdit; lblTelefone: TLabel; lblFAX: TLabel; lblRepresentante: TLabel; fldRepresentante: TDBEdit; fldRamal: TDBEdit; lblRamal: TLabel; lblHomePage: TLabel; lblEMail: TLabel; fldHomePage: TDBEdit; fldEMail: TDBEdit; tabProdutos: TTabSheet; grdProdutos: TDBGrid; pnlBotoes: TPanel; btnPrimeiroProduto: TSpeedButton; btnUltimoProduto: TSpeedButton; btnAdicionarProduto: TSpeedButton; btnGravarProduto: TSpeedButton; btnExcluirProduto: TSpeedButton; btnPrimeiro: TSpeedButton; btnAnterior: TSpeedButton; btnProximo: TSpeedButton; btnUltimo: TSpeedButton; btnGravar: TSpeedButton; btnLocalizar: TSpeedButton; btnExcluir: TSpeedButton; btnAdicionar: TSpeedButton; btnRetornar: TSpeedButton; procedure btnPrimeiroClick(Sender: TObject); procedure btnAnteriorClick(Sender: TObject); procedure btnProximoClick(Sender: TObject); procedure btnUltimoClick(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnAdicionarClick(Sender: TObject); procedure btnRetornarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnPrimeiroProdutoClick(Sender: TObject); procedure btnUltimoProdutoClick(Sender: TObject); procedure btnGravarProdutoClick(Sender: TObject); procedure btnAdicionarProdutoClick(Sender: TObject); procedure btnExcluirProdutoClick(Sender: TObject); procedure btnLocalizarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var formFornecedores: TformFornecedores; implementation uses ModuloDados, RotinasGerais, SeekFornecedor; {$R *.DFM} procedure TformFornecedores.btnPrimeiroClick(Sender: TObject); begin dmBaseDados.tblFornecedores.First; pgFornecedor.ActivePage := tabFornecedor; fldNomeFantasia.SetFocus; end; procedure TformFornecedores.btnAnteriorClick(Sender: TObject); begin dmBaseDados.tblFornecedores.Prior; if (dmBaseDados.tblFornecedores.Bof) then begin InicioTabela; dmBasedados.tblFornecedores.First; end; pgFornecedor.ActivePage := tabFornecedor; fldNomeFantasia.SetFocus; end; procedure TformFornecedores.btnProximoClick(Sender: TObject); begin dmBaseDados.tblFornecedores.Next; if (dmBaseDados.tblFornecedores.Eof) then begin FimTabela; dmBasedados.tblFornecedores.Last; end; pgFornecedor.ActivePage := tabFornecedor; fldNomeFantasia.SetFocus; end; procedure TformFornecedores.btnUltimoClick(Sender: TObject); begin dmBaseDados.tblFornecedores.Last; pgFornecedor.ActivePage := tabFornecedor; fldNomeFantasia.SetFocus; end; procedure TformFornecedores.btnGravarClick(Sender: TObject); begin dmBaseDados.tblFornecedores.Post; pgFornecedor.ActivePage := tabFornecedor; fldNomeFantasia.SetFocus; end; procedure TformFornecedores.btnExcluirClick(Sender: TObject); begin dmBaseDados.tblFornecedores.Delete; pgFornecedor.ActivePage := tabFornecedor; fldNomeFantasia.SetFocus; end; procedure TformFornecedores.btnAdicionarClick(Sender: TObject); var intCodigo,intTamanho: integer; strCodigo: string; begin dmBaseDados.tblFornecedores.Last; intCodigo := StrToInt(dmBaseDados.tblFornecedoresCodigoFornecedor.AsString); Inc(intCodigo); strCodigo := IntToStr(intCodigo); intTamanho := Length(strCodigo); strCodigo := Copy('0000'+strCodigo,intTamanho+1,4); dmBaseDados.tblFornecedores.Append; dmBaseDados.tblFornecedoresCodigoFornecedor.AsString := strCodigo; dmBaseDados.tblFornecedores.Post; pgFornecedor.ActivePage := tabFornecedor; fldNomeFantasia.SetFocus; end; procedure TformFornecedores.btnRetornarClick(Sender: TObject); begin Close; end; procedure TformFornecedores.FormShow(Sender: TObject); var FArquivo: TextFile; strDados: string; begin dmBaseDados.tblFornecedores.Open; dmBaseDados.tblProdutosFornecidos.Open; AssignFile(FArquivo,'C:\SGE\TABELAS\ESTADOS.TXT'); Reset(FArquivo); ReadLn(FArquivo,strDados); while (not Eof(FArquivo)) do begin fldEstado.Items.Add(strDados); ReadLn(FArquivo,strDados); end; CloseFile(FArquivo); if (dmBaseDados.tblFornecedores.RecordCount = 0) then begin dmBaseDados.tblFornecedores.Append; dmBaseDados.tblFornecedoresCodigoFornecedor.AsString := '0001'; dmBaseDados.tblFornecedores.Post; end; pgFornecedor.ActivePage := tabFornecedor; fldNomeFantasia.SetFocus; end; procedure TformFornecedores.FormClose(Sender: TObject; var Action: TCloseAction); begin dmBaseDados.tblFornecedores.Close; dmBaseDados.tblProdutosFornecidos.Close; end; procedure TformFornecedores.btnPrimeiroProdutoClick(Sender: TObject); begin dmBaseDados.tblProdutosFornecidos.First; grdProdutos.SetFocus; end; procedure TformFornecedores.btnUltimoProdutoClick(Sender: TObject); begin dmBaseDados.tblProdutosFornecidos.Last; grdProdutos.SetFocus; end; procedure TformFornecedores.btnGravarProdutoClick(Sender: TObject); begin dmBaseDados.tblProdutosFornecidos.Post; grdProdutos.SetFocus; end; procedure TformFornecedores.btnAdicionarProdutoClick(Sender: TObject); begin dmBaseDados.tblProdutosFornecidos.Append; grdProdutos.SetFocus; end; procedure TformFornecedores.btnExcluirProdutoClick(Sender: TObject); begin dmBaseDados.tblProdutosFornecidos.Delete; grdProdutos.SetFocus; end; procedure TformFornecedores.btnLocalizarClick(Sender: TObject); begin formSeekFornecedor.ShowModal; end; end.
unit ThreadTimer; interface uses Windows, Threads; const cDefaultInterval = 1000; cDefaultLeadTime = 100; type TNotifyProc = procedure of object; type TThreadTimer = class public constructor Create; destructor Destroy; override; private fInterval : cardinal; fLeadTime : cardinal; fEnabled : boolean; fOnTimer : TNotifyProc; procedure SetInterval(which : cardinal); procedure SetLeadTime(which : cardinal); procedure SetEnabled(which : boolean); procedure SetOnTimer(which : TNotifyProc); published property Interval : cardinal read fInterval write SetInterval; property LeadTime : cardinal read fLeadTime write SetLeadTime; property Enabled : boolean read fEnabled write SetEnabled; property OnTimer : TNotifyProc read fOnTimer write SetOnTimer; private fThread : TAxlThread; fEvent : thandle; procedure ControlManager(const which : array of const); procedure TimerTick(const which : array of const); end; implementation uses SysUtils; // TThreadTimer constructor TThreadTimer.Create; begin inherited; fInterval := cDefaultInterval; fLeadTime := cDefaultLeadTime; fEvent := CreateEvent(nil, false, false, nil); fThread := TExclusiveThread.Create(priNormal); end; destructor TThreadTimer.Destroy; begin fOnTimer := nil; // Go out if waiting fThread.Free; CloseHandle(fEvent); inherited; end; procedure TThreadTimer.SetInterval(which : cardinal); begin assert(which > 0); fInterval := which; end; procedure TThreadTimer.SetLeadTime(which : cardinal); begin assert(which > 0); fLeadTime := which; end; procedure TThreadTimer.SetEnabled(which : boolean); begin if which <> fEnabled then begin fEnabled := which; if tsRunning in fThread.State then SetEvent(fEvent); end; end; procedure TThreadTimer.SetOnTimer(which : TNotifyProc); var old : TNotifyProc; begin if @which <> @fOnTimer then begin old := fOnTimer; fOnTimer := which; if not assigned(old) then fThread.Defer(ControlManager, [0]) else if not assigned(which) then SetEvent(fEvent); end; end; procedure TThreadTimer.ControlManager(const which : array of const); var Delay : dword; ticks : cardinal; LeadTime : cardinal; begin if fLeadTime < fInterval then LeadTime := fLeadTime else LeadTime := 2*fInterval div 3; if fEnabled then Delay := fInterval else Delay := INFINITE; while assigned(fOnTimer) do if WaitForSingleObject(fEvent, Delay) = WAIT_TIMEOUT then if assigned(fOnTimer) then begin ticks := GetTickCount; try Join(TimerTick, which); except // *** protect against exceptions on timer tick, this would kill the thread // and stop the timer forever end; if fEnabled then begin ticks := GetTickCount - ticks; if (fInterval > ticks + LeadTime) then Delay := fInterval - ticks else Delay := LeadTime; end else Delay := INFINITE; end else Delay := INFINITE else // Even pulsed if fEnabled then Delay := fInterval else Delay := INFINITE; end; procedure TThreadTimer.TimerTick(const which : array of const); begin if assigned(fOnTimer) then fOnTimer(); end; end.
unit plLogin; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.DBCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ToolWin, Vcl.ExtCtrls, System.ImageList, Vcl.ImgList, Data.FMTBcd, Data.DB, Data.SqlExpr, FireDAC.Comp.Client; type TfnLogin = class(TForm) edLogin: TEdit; edSenha: TEdit; lbLogin: TLabel; lbSenha: TLabel; ToolBar1: TToolBar; tbEntry: TToolButton; ToolButton2: TToolButton; tbExit: TToolButton; pnTelaLogin: TPanel; imgList: TImageList; SQLConnection1: TSQLConnection; procedure edSenhaKeyPress(Sender: TObject; var Key: Char); procedure FormActivate(Sender: TObject); procedure tbExitClick(Sender: TObject); procedure tbEntryClick(Sender: TObject); private { Private declarations } procedure ChamaInformacoesLogin; public { Public declarations } end; var fnLogin: TfnLogin; bdLogin, bdSenha: String; implementation {$R *.dfm} uses pldmPlaneja; procedure TfnLogin.ChamaInformacoesLogin; var Query: TFDQuery; begin try Query := TFDQuery.Create(nil); Query.Connection := dmPlaneja.Conex„o; Query.SQL.Add('select LOGIN, SENHA from TLOGIN where LOGIN = '+ QuotedStr(edLogin.Text)); Query.Open; if not Query.Eof then begin bdLogin := Query.FieldByName('LOGIN').AsString; bdSenha := Query.FieldByName('SENHA').AsString; end; Query.Close; finally FreeAndNil(Query); end; end; procedure TfnLogin.edSenhaKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin ChamaInformacoesLogin; if (bdSenha = edSenha.Text) and (bdLogin = edLogin.Text) then begin fnLogin.Close; end else begin ShowMessage('Senha ou login incorretos!'); edSenha.Clear; edLogin.SetFocus; end; end; end; procedure TfnLogin.FormActivate(Sender: TObject); begin dmPlaneja.Conex„o.Connected := True; dmPlaneja.tbLogin.Active := True; edLogin.SetFocus; end; procedure TfnLogin.tbEntryClick(Sender: TObject); begin ChamaInformacoesLogin; if (bdSenha = edSenha.Text) and (bdLogin = edLogin.Text) then begin fnLogin.Close; end else begin ShowMessage('Senha ou login incorretos!'); edSenha.Clear; edLogin.SetFocus; end; end; procedure TfnLogin.tbExitClick(Sender: TObject); begin Application.Terminate; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.9 3/5/2005 3:33:54 PM JPMugaas Fix for some compiler warnings having to do with TStream.Read being platform specific. This was fixed by changing the Compressor API to use TIdStreamVCL instead of TStream. I also made appropriate adjustments to other units for this. Rev 1.8 10/24/2004 2:40:28 PM JPMugaas Made a better fix for the problem with SmartFTP. It turns out that we may not be able to avoid a Z_BUF_ERROR in some cases. Rev 1.7 10/24/2004 11:17:08 AM JPMugaas Reimplemented ZLIB Decompression in FTP better. It now should work properly at ftp://ftp.smartftp.com. Rev 1.6 9/16/2004 3:24:04 AM JPMugaas TIdFTP now compresses to the IOHandler and decompresses from the IOHandler. Noted some that the ZLib code is based was taken from ZLibEx. Rev 1.4 9/11/2004 10:58:04 AM JPMugaas FTP now decompresses output directly to the IOHandler. Rev 1.3 6/21/2004 12:10:52 PM JPMugaas Attempt to expand the ZLib support for Int64 support. Rev 1.2 2/21/2004 3:32:58 PM JPMugaas Foxed for Unit rename. Rev 1.1 2/14/2004 9:59:50 PM JPMugaas Reworked the API. There is now a separate API for the Inflate_ and InflateInit2_ functions as well as separate functions for DeflateInit_ and DeflateInit2_. This was required for FTP. The API also includes an optional output stream for the servers. Rev 1.0 2/12/2004 11:27:22 PM JPMugaas New compressor based on ZLibEx. } unit IdCompressorZLib; interface {$i IdCompilerDefines.inc} uses Classes, IdException, IdIOHandler, IdZLibCompressorBase, IdZLibHeaders; type TIdCompressorZLib = class(TIdZLibCompressorBase) protected function GetIsReady : Boolean; override; procedure InternalDecompressStream(LZstream: TZStreamRec; AIOHandler : TIdIOHandler; AOutStream: TStream); public procedure DeflateStream(AInStream, AOutStream : TStream; const ALevel : TIdCompressionLevel=0); override; procedure InflateStream(AInStream, AOutStream : TStream); override; procedure CompressStream(AInStream, AOutStream : TStream; const ALevel : TIdCompressionLevel; const AWindowBits, AMemLevel, AStrategy: Integer); override; procedure DecompressStream(AInStream, AOutStream : TStream; const AWindowBits : Integer); override; procedure CompressFTPToIO(AInStream : TStream; AIOHandler : TIdIOHandler; const ALevel, AWindowBits, AMemLevel, AStrategy: Integer); override; procedure DecompressFTPFromIO(AIOHandler : TIdIOHandler; AOutputStream : TStream; const AWindowBits : Integer); override; end; EIdCompressionException = class(EIdException); EIdCompressorInitFailure = class(EIdCompressionException); EIdDecompressorInitFailure = class(EIdCompressionException); EIdCompressionError = class(EIdCompressionException); EIdDecompressionError = class(EIdCompressionException); implementation uses IdAntiFreezeBase, IdComponent, IdResourceStringsProtocols, IdGlobal, IdGlobalProtocols, IdZLib, SysUtils; const bufferSize = 32768; { TIdCompressorZLib } procedure TIdCompressorZLib.InternalDecompressStream( LZstream: TZStreamRec; AIOHandler: TIdIOHandler; AOutStream: TStream); {Note that much of this is taken from the ZLibEx unit and adapted to use the IOHandler} var zresult : Integer; outBuffer: Array [0..bufferSize-1] of AnsiChar; inSize : Integer; outSize : Integer; LBuf : TIdBytes; function RawReadFromIOHandler(ABuffer : TIdBytes; AOIHandler : TIdIOHandler; AMax : Integer) : Integer; begin //We don't use the IOHandler.ReadBytes because that will check // for disconnect and raise an exception that we don't want. // RLebeau 3/26/09: we need to raise exceptions here! The socket component // that is performing the IO needs to know what is happening on the socket... { repeat AIOHandler.CheckForDataOnSource(1); Result := IndyMin(AIOHandler.InputBuffer.Size, AMax); if Result > 0 then begin AIOHandler.InputBuffer.ExtractToBytes(ABuffer, Result, False); Break; end; until not AIOHandler.Connected; } // copied from TIdIOHandler.ReadStream() and trimmed down... try AIOHandler.ReadBytes(ABuffer, AMax, False); except on E: Exception do begin // RLebeau - ReadFromSource() inside of ReadBytes() // could have filled the InputBuffer with more bytes // than actually requested, so don't extract too // many bytes here... AMax := IndyMin(AMax, AIOHandler.InputBuffer.Size); AIOHandler.InputBuffer.ExtractToBytes(ABuffer, AMax, False); if not (E is EIdConnClosedGracefully) then begin raise; end; end; end; TIdAntiFreezeBase.DoProcess; Result := AMax; end; begin SetLength(LBuf, bufferSize); repeat inSize := RawReadFromIOHandler(LBuf, AIOHandler, bufferSize); if inSize < 1 then begin Break; end; LZstream.next_in := PAnsiChar(@LBuf[0]); LZstream.avail_in := inSize; repeat LZstream.next_out := outBuffer; LZstream.avail_out := bufferSize; DCheck(inflate(LZstream,Z_NO_FLUSH)); outSize := bufferSize - LZstream.avail_out; AOutStream.Write(outBuffer, outSize); until (LZstream.avail_in = 0) and (LZstream.avail_out > 0); until False; { From the ZLIB FAQ at http://www.gzip.org/zlib/FAQ.txt 5. deflate() or inflate() returns Z_BUF_ERROR Before making the call, make sure that avail_in and avail_out are not zero. When setting the parameter flush equal to Z_FINISH, also make sure that avail_out is big enough to allow processing all pending input. Note that a Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be made with more input or output space. A Z_BUF_ERROR may in fact be unavoidable depending on how the functions are used, since it is not possible to tell whether or not there is more output pending when strm.avail_out returns with zero. } repeat LZstream.next_out := outBuffer; LZstream.avail_out := bufferSize; zresult := inflate(LZstream, Z_FINISH); if zresult <> Z_BUF_ERROR then begin zresult := DCheck(zresult); end; outSize := bufferSize - LZstream.avail_out; AOutStream.Write(outBuffer, outSize); until ((zresult = Z_STREAM_END) and (LZstream.avail_out > 0)) or (zresult = Z_BUF_ERROR); DCheck(inflateEnd(LZstream)); end; procedure TIdCompressorZLib.DecompressFTPFromIO(AIOHandler : TIdIOHandler; AOutputStream : TStream; const AWindowBits : Integer); {Note that much of this is taken from the ZLibEx unit and adapted to use the IOHandler} var Lzstream: TZStreamRec; LWinBits : Integer; begin AIOHandler.BeginWork(wmRead); try FillChar(Lzstream,SizeOf(TZStreamRec),0); { This is a workaround for some clients and servers that do not send decompression headers. The reason is that there's an inconsistancy in Internet Drafts for ZLIB compression. One says to include the headers while an older one says do not include the headers. If you add 32 to the Window Bits parameter, } LWinBits := AWindowBits; if LWinBits > 0 then begin LWinBits := Abs( LWinBits) + 32; end; LZstream.zalloc := zlibAllocMem; LZstream.zfree := zlibFreeMem; DCheck(inflateInit2_(Lzstream,LWinBits,ZLIB_VERSION,SizeOf(TZStreamRec))); InternalDecompressStream(Lzstream,AIOHandler,AOutputStream); finally AIOHandler.EndWork(wmRead); end; end; procedure TIdCompressorZLib.CompressFTPToIO(AInStream : TStream; AIOHandler : TIdIOHandler; const ALevel, AWindowBits, AMemLevel, AStrategy: Integer); {Note that much of this is taken from the ZLibEx unit and adapted to use the IOHandler} var LCompressRec : TZStreamRec; zresult : Integer; inBuffer : Array [0..bufferSize-1] of AnsiChar; outBuffer: Array [0..bufferSize-1] of AnsiChar; inSize : Integer; outSize : Integer; begin AIOHandler.BeginWork(wmWrite, AInStream.Size); try FillChar(LCompressRec, SizeOf(TZStreamRec), 0); CCheck( deflateInit2_(LCompressRec, ALevel, Z_DEFLATED, AWindowBits, AMemLevel, AStrategy, ZLIB_VERSION, SizeOf(LCompressRec))); inSize := AInStream.Read(inBuffer, bufferSize); while inSize > 0 do begin LCompressRec.next_in := inBuffer; LCompressRec.avail_in := inSize; repeat LCompressRec.next_out := outBuffer; LCompressRec.avail_out := bufferSize; CCheck(deflate(LCompressRec,Z_NO_FLUSH)); // outSize := zstream.next_out - outBuffer; outSize := bufferSize - LCompressRec.avail_out; if outsize <> 0 then begin AIOHandler.Write(RawToBytes(outBuffer, outSize)); end; until (LCompressRec.avail_in = 0) and (LCompressRec.avail_out > 0); inSize := AInStream.Read(inBuffer, bufferSize); end; repeat LCompressRec.next_out := outBuffer; LCompressRec.avail_out := bufferSize; zresult := CCheck(deflate(LCompressRec,Z_FINISH)); // outSize := zstream.next_out - outBuffer; outSize := bufferSize - LCompressRec.avail_out; // outStream.Write(outBuffer,outSize); if outSize <> 0 then begin AIOHandler.Write(RawToBytes(outBuffer, outSize)); end; until (zresult = Z_STREAM_END) and (LCompressRec.avail_out > 0); CCheck(deflateEnd(LCompressRec)); finally AIOHandler.EndWork(wmWrite); end; end; procedure TIdCompressorZLib.CompressStream(AInStream,AOutStream : TStream; const ALevel : TIdCompressionLevel; const AWindowBits, AMemLevel, AStrategy: Integer); begin IdZLib.IndyCompressStream(AInStream,AOutStream,ALevel,AWindowBits,AMemLevel,AStrategy); end; procedure TIdCompressorZLib.DecompressStream(AInStream, AOutStream : TStream; const AWindowBits : Integer); begin IdZLib.IndyDeCompressStream(AInStream,AOutStream, AWindowBits); end; procedure TIdCompressorZLib.DeflateStream(AInStream, AOutStream : TStream; const ALevel : TIdCompressionLevel=0); begin IdZLib.IndyCompressStream(AInStream,AOutStream,ALevel); end; function TIdCompressorZLib.GetIsReady: Boolean; begin Result := IdZLibHeaders.Loaded; end; procedure TIdCompressorZLib.InflateStream(AInStream, AOutStream : TStream); begin IdZlib.DeCompressStream(AInStream,AOutStream); end; end.
(* example.c -- usage example of the zlib compression library * Copyright(C) 1995 - 2003 Jean - loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h * * Pascal translation * Copyright(C) 1998 by Jacques Nomssi Nzali. * For conditions of distribution and use, see copyright notice in readme.txt * * Adaptation to the zlibpas interface * Copyright(C) 2003 by Cosmin Truta. * For conditions of distribution and use, see copyright notice in readme.txt *) program example; { $DEFINE TEST_COMPRESS } { DO NOT $DEFINE TEST_GZIO } { $DEFINE TEST_DEFLATE } { $DEFINE TEST_INFLATE } { $DEFINE TEST_FLUSH } { $DEFINE TEST_SYNC } { $DEFINE TEST_DICT } uses SysUtils, zlibpas; const TESTFILE = 'foo.gz'; (* "hello world" would be more standard, but the repeated "hello" * stresses the compression code better, sorry... *) const hello: PChar = 'hello, hello!'; const dictionary: PChar = 'hello'; var dictId: LongInt; (* Adler32 value of the dictionary *) procedure CHECK_ERR(err: Integer; msg: String); begin if err <> Z_OK then begin WriteLn(msg, ' error: ', err); Halt(1); end; end; procedure EXIT_ERR(const msg: String); begin WriteLn('Error: ', msg); Halt(1); end; ( * == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == = * Test compress and uncompress *) { $IFDEF TEST_COMPRESS } procedure test_compress(compr: Pointer; comprLen: LongInt; uncompr: Pointer; uncomprLen: LongInt); var err: Integer; len: LongInt; begin len : = StrLen(hello) + 1; err : = compress(compr, comprLen, hello, len); CHECK_ERR(err, 'compress'); StrCopy(PChar(uncompr), 'garbage'); err : = uncompress(uncompr, uncomprLen, compr, comprLen); CHECK_ERR(err, 'uncompress'); if StrComp(PChar(uncompr), hello) <> 0 then EXIT_ERR('bad uncompress') else { WriteLn('uncompress(): ', PChar(uncompr)); } end; { $ENDIF } ( * == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == = * Test read / write of .gz files *) { $IFDEF TEST_GZIO } procedure test_gzio(const fname: PChar; (* compressed file name *) uncompr: Pointer; uncomprLen: LongInt); var err: Integer; len: Integer; zfile: gzFile; pos: LongInt; begin len : = StrLen(hello) + 1; zfile : = gzopen(fname, 'wb'); if zfile = NIL then begin WriteLn('gzopen error'); Halt(1); end; gzputc(zfile, 'h'); if gzputs(zfile, 'ello') <> 4 then begin WriteLn('gzputs err: ', gzerror(zfile, err)); Halt(1); end; { $IFDEF GZ_FORMAT_STRING } if gzprintf(zfile, ', %s!', 'hello') <> 8 then begin WriteLn('gzprintf err: ', gzerror(zfile, err)); Halt(1); end; { $ELSE } if gzputs(zfile, ', hello!') <> 8 then begin WriteLn('gzputs err: ', gzerror(zfile, err)); Halt(1); end; { $ENDIF } gzseek(zfile, 1, SEEK_CUR); (* add one zero byte *) gzclose(zfile); zfile : = gzopen(fname, 'rb'); if zfile = NIL then begin WriteLn('gzopen error'); Halt(1); end; StrCopy(PChar(uncompr), 'garbage'); if gzread(zfile, uncompr, uncomprLen) <> len then begin WriteLn('gzread err: ', gzerror(zfile, err)); Halt(1); end; if StrComp(PChar(uncompr), hello) <> 0 then begin WriteLn('bad gzread: ', PChar(uncompr)); Halt(1); end else { WriteLn('gzread(): ', PChar(uncompr)); } pos : = gzseek(zfile, -8, SEEK_CUR); if (pos <> 6) or (gztell(zfile) <> pos) then begin WriteLn('gzseek error, pos=', pos, ', gztell=', gztell(zfile)); Halt(1); end; if gzgetc(zfile) <> ' ' then begin WriteLn('gzgetc error'); Halt(1); end; if gzungetc(' ', zfile) <> ' ' then begin WriteLn('gzungetc error'); Halt(1); end; gzgets(zfile, PChar(uncompr), uncomprLen); uncomprLen : = StrLen(PChar(uncompr)); if uncomprLen <> 7 then(* " hello!" *) begin WriteLn('gzgets err after gzseek: ', gzerror(zfile, err)); Halt(1); end; if StrComp(PChar(uncompr), hello + 6) <> 0 then begin WriteLn('bad gzgets after gzseek'); Halt(1); end else { WriteLn('gzgets() after gzseek: ', PChar(uncompr)); } gzclose(zfile); end; { $ENDIF } ( * == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == = * Test deflate with small buffers *) { $IFDEF TEST_DEFLATE } procedure test_deflate(compr: Pointer; comprLen: LongInt); var c_stream: z_stream; (* compression stream *) err: Integer; len: LongInt; begin len : = StrLen(hello) + 1; c_stream.zalloc : = NIL; c_stream.zfree : = NIL; c_stream.opaque : = NIL; err : = deflateInit(c_stream, Z_DEFAULT_COMPRESSION); CHECK_ERR(err, 'deflateInit'); c_stream.next_in : = hello; c_stream.next_out : = compr; while (c_stream.total_in <> len) and (c_stream.total_out < comprLen) do begin c_stream.avail_out : = 1; { force small buffers } c_stream.avail_in : = 1; err : = deflate(c_stream, Z_NO_FLUSH); CHECK_ERR(err, 'deflate'); end; (* Finish the stream, still forcing small buffers:*) while TRUE do begin c_stream.avail_out : = 1; err : = deflate(c_stream, Z_FINISH); if err = Z_STREAM_END then break; CHECK_ERR(err, 'deflate'); end; err : = deflateEnd(c_stream); CHECK_ERR(err, 'deflateEnd'); end; { $ENDIF } ( * == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == = * Test inflate with small buffers *) { $IFDEF TEST_INFLATE } procedure test_inflate(compr: Pointer; comprLen : LongInt; uncompr: Pointer; uncomprLen : LongInt); var err: Integer; d_stream: z_stream; (* decompression stream *) begin StrCopy(PChar(uncompr), 'garbage'); d_stream.zalloc : = NIL; d_stream.zfree : = NIL; d_stream.opaque : = NIL; d_stream.next_in : = compr; d_stream.avail_in : = 0; d_stream.next_out : = uncompr; err : = inflateInit(d_stream); CHECK_ERR(err, 'inflateInit'); while (d_stream.total_out < uncomprLen) and (d_stream.total_in < comprLen) do begin d_stream.avail_out : = 1; (* force small buffers *) d_stream.avail_in : = 1; err : = inflate(d_stream, Z_NO_FLUSH); if err = Z_STREAM_END then break; CHECK_ERR(err, 'inflate'); end; err : = inflateEnd(d_stream); CHECK_ERR(err, 'inflateEnd'); if StrComp(PChar(uncompr), hello) <> 0 then EXIT_ERR('bad inflate') else { WriteLn('inflate(): ', PChar(uncompr)); } end; { $ENDIF } ( * == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == = * Test deflate with large buffers and dynamic change of compression level *) { $IFDEF TEST_DEFLATE } procedure test_large_deflate(compr: Pointer; comprLen: LongInt; uncompr: Pointer; uncomprLen: LongInt); var c_stream: z_stream; (* compression stream *) err: Integer; begin c_stream.zalloc : = NIL; c_stream.zfree : = NIL; c_stream.opaque : = NIL; err : = deflateInit(c_stream, Z_BEST_SPEED); CHECK_ERR(err, 'deflateInit'); c_stream.next_out : = compr; c_stream.avail_out : = Integer(comprLen); (* At this point, uncompr is still mostly zeroes, so it should compress * very well: *) c_stream.next_in : = uncompr; c_stream.avail_in : = Integer(uncomprLen); err : = deflate(c_stream, Z_NO_FLUSH); CHECK_ERR(err, 'deflate'); if c_stream.avail_in <> 0 then EXIT_ERR('deflate not greedy'); (* Feed in already compressed data and switch to no compression:*) deflateParams(c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); c_stream.next_in : = compr; c_stream.avail_in : = Integer(comprLen div 2); err : = deflate(c_stream, Z_NO_FLUSH); CHECK_ERR(err, 'deflate'); (* Switch back to compressing mode:*) deflateParams(c_stream, Z_BEST_COMPRESSION, Z_FILTERED); c_stream.next_in : = uncompr; c_stream.avail_in : = Integer(uncomprLen); err : = deflate(c_stream, Z_NO_FLUSH); CHECK_ERR(err, 'deflate'); err : = deflate(c_stream, Z_FINISH); if err <> Z_STREAM_END then EXIT_ERR('deflate should report Z_STREAM_END'); err : = deflateEnd(c_stream); CHECK_ERR(err, 'deflateEnd'); end; { $ENDIF } ( * == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == = * Test inflate with large buffers *) { $IFDEF TEST_INFLATE } procedure test_large_inflate(compr: Pointer; comprLen: LongInt; uncompr: Pointer; uncomprLen: LongInt); var err: Integer; d_stream: z_stream; (* decompression stream *) begin StrCopy(PChar(uncompr), 'garbage'); d_stream.zalloc : = NIL; d_stream.zfree : = NIL; d_stream.opaque : = NIL; d_stream.next_in : = compr; d_stream.avail_in : = Integer(comprLen); err : = inflateInit(d_stream); CHECK_ERR(err, 'inflateInit'); while TRUE do begin d_stream.next_out : = uncompr; (* discard the output *) d_stream.avail_out : = Integer(uncomprLen); err : = inflate(d_stream, Z_NO_FLUSH); if err = Z_STREAM_END then break; CHECK_ERR(err, 'large inflate'); end; err : = inflateEnd(d_stream); CHECK_ERR(err, 'inflateEnd'); if d_stream.total_out <> 2 * uncomprLen + comprLen div 2 then begin WriteLn('bad large inflate: ', d_stream.total_out); Halt(1); end else { WriteLn('large_inflate(): OK'); } end; { $ENDIF } ( * == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == = * Test deflate with full flush *) { $IFDEF TEST_FLUSH } procedure test_flush(compr: Pointer; var comprLen : LongInt); var c_stream: z_stream; (* compression stream *) err: Integer; len: Integer; begin len : = StrLen(hello) + 1; c_stream.zalloc : = NIL; c_stream.zfree : = NIL; c_stream.opaque : = NIL; err : = deflateInit(c_stream, Z_DEFAULT_COMPRESSION); CHECK_ERR(err, 'deflateInit'); c_stream.next_in : = hello; c_stream.next_out : = compr; c_stream.avail_in : = 3; c_stream.avail_out : = Integer(comprLen); err : = deflate(c_stream, Z_FULL_FLUSH); CHECK_ERR(err, 'deflate'); Inc(PByteArray(compr)^[3]); (* force an error in first compressed block *) c_stream.avail_in : = len - 3; err : = deflate(c_stream, Z_FINISH); if err <> Z_STREAM_END then CHECK_ERR(err, 'deflate'); err : = deflateEnd(c_stream); CHECK_ERR(err, 'deflateEnd'); comprLen : = c_stream.total_out; end; { $ENDIF } ( * == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == = * Test inflateSync() *) { $IFDEF TEST_SYNC } procedure test_sync(compr: Pointer; comprLen: LongInt; uncompr: Pointer; uncomprLen : LongInt); var err: Integer; d_stream: z_stream; (* decompression stream *) begin StrCopy(PChar(uncompr), 'garbage'); d_stream.zalloc : = NIL; d_stream.zfree : = NIL; d_stream.opaque : = NIL; d_stream.next_in : = compr; d_stream.avail_in : = 2; (* just read the zlib header *) err : = inflateInit(d_stream); CHECK_ERR(err, 'inflateInit'); d_stream.next_out : = uncompr; d_stream.avail_out : = Integer(uncomprLen); inflate(d_stream, Z_NO_FLUSH); CHECK_ERR(err, 'inflate'); d_stream.avail_in : = Integer(comprLen - 2); (* read all compressed data *) err : = inflateSync(d_stream); (* but skip the damaged part *) CHECK_ERR(err, 'inflateSync'); err : = inflate(d_stream, Z_FINISH); if err <> Z_DATA_ERROR then EXIT_ERR('inflate should report DATA_ERROR'); (* Because of incorrect adler32 *) err : = inflateEnd(d_stream); CHECK_ERR(err, 'inflateEnd'); WriteLn('after inflateSync(): hel', PChar(uncompr)); end; { $ENDIF } ( * == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == = * Test deflate with preset dictionary *) { $IFDEF TEST_DICT } procedure test_dict_deflate(compr: Pointer; comprLen: LongInt); var c_stream: z_stream; (* compression stream *) err: Integer; begin c_stream.zalloc : = NIL; c_stream.zfree : = NIL; c_stream.opaque : = NIL; err : = deflateInit(c_stream, Z_BEST_COMPRESSION); CHECK_ERR(err, 'deflateInit'); err : = deflateSetDictionary(c_stream, dictionary, StrLen(dictionary)); CHECK_ERR(err, 'deflateSetDictionary'); dictId : = c_stream.adler; c_stream.next_out : = compr; c_stream.avail_out : = Integer(comprLen); c_stream.next_in : = hello; c_stream.avail_in : = StrLen(hello) + 1; err : = deflate(c_stream, Z_FINISH); if err <> Z_STREAM_END then EXIT_ERR('deflate should report Z_STREAM_END'); err : = deflateEnd(c_stream); CHECK_ERR(err, 'deflateEnd'); end; { $ENDIF } ( * == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == = * Test inflate with a preset dictionary *) { $IFDEF TEST_DICT } procedure test_dict_inflate(compr: Pointer; comprLen: LongInt; uncompr: Pointer; uncomprLen: LongInt); var err: Integer; d_stream: z_stream; (* decompression stream *) begin StrCopy(PChar(uncompr), 'garbage'); d_stream.zalloc : = NIL; d_stream.zfree : = NIL; d_stream.opaque : = NIL; d_stream.next_in : = compr; d_stream.avail_in : = Integer(comprLen); err : = inflateInit(d_stream); CHECK_ERR(err, 'inflateInit'); d_stream.next_out : = uncompr; d_stream.avail_out : = Integer(uncomprLen); while TRUE do begin err : = inflate(d_stream, Z_NO_FLUSH); if err = Z_STREAM_END then break; if err = Z_NEED_DICT then begin if d_stream.adler <> dictId then EXIT_ERR('unexpected dictionary'); err : = inflateSetDictionary(d_stream, dictionary, StrLen(dictionary)); end; CHECK_ERR(err, 'inflate with dict'); end; err : = inflateEnd(d_stream); CHECK_ERR(err, 'inflateEnd'); if StrComp(PChar(uncompr), hello) <> 0 then EXIT_ERR('bad inflate with dict') else { WriteLn('inflate with dictionary: ', PChar(uncompr)); } end; { $ENDIF } var compr, uncompr: Pointer; comprLen, uncomprLen: LongInt; begin if zlibVersion ^ <> ZLIB_VERSION[1] then EXIT_ERR('Incompatible zlib version'); WriteLn('zlib version: ', zlibVersion); WriteLn('zlib compile flags: ', Format('0x%x', [zlibCompileFlags])); comprLen : = 10000 * SizeOf(Integer); (* don't overflow on MSDOS *) uncomprLen : = comprLen; GetMem(compr, comprLen); GetMem(uncompr, uncomprLen); if (compr = NIL) or (uncompr = NIL) then EXIT_ERR('Out of memory'); (* compr and uncompr are cleared to avoid reading uninitialized * data and to ensure that uncompr compresses well. *) FillChar(compr ^, comprLen, 0); FillChar(uncompr ^, uncomprLen, 0); { $IFDEF TEST_COMPRESS } WriteLn('** Testing compress'); test_compress(compr, comprLen, uncompr, uncomprLen); { $ENDIF } { $IFDEF TEST_GZIO } WriteLn('** Testing gzio'); if ParamCount >= 1 then test_gzio(ParamStr(1), uncompr, uncomprLen) else { test_gzio(TESTFILE, uncompr, uncomprLen); } { $ENDIF } { $IFDEF TEST_DEFLATE } WriteLn('** Testing deflate with small buffers'); test_deflate(compr, comprLen); { $ENDIF } { $IFDEF TEST_INFLATE } WriteLn('** Testing inflate with small buffers'); test_inflate(compr, comprLen, uncompr, uncomprLen); { $ENDIF } { $IFDEF TEST_DEFLATE } WriteLn('** Testing deflate with large buffers'); test_large_deflate(compr, comprLen, uncompr, uncomprLen); { $ENDIF } { $IFDEF TEST_INFLATE } WriteLn('** Testing inflate with large buffers'); test_large_inflate(compr, comprLen, uncompr, uncomprLen); { $ENDIF } { $IFDEF TEST_FLUSH } WriteLn('** Testing deflate with full flush'); test_flush(compr, comprLen); { $ENDIF } { $IFDEF TEST_SYNC } WriteLn('** Testing inflateSync'); test_sync(compr, comprLen, uncompr, uncomprLen); { $ENDIF } comprLen : = uncomprLen; { $IFDEF TEST_DICT } WriteLn('** Testing deflate and inflate with preset dictionary'); test_dict_deflate(compr, comprLen); test_dict_inflate(compr, comprLen, uncompr, uncomprLen); { $ENDIF } FreeMem(compr, comprLen); FreeMem(uncompr, uncomprLen); end.
unit Unit1; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Samples.Spin, Data.Win.ADODB; type TForm1 = class(TForm) lvContacts: TListView; Panel1: TPanel; btnLoad: TButton; seCount: TSpinEdit; pbLoading: TProgressBar; Panel2: TPanel; cbbOperator: TComboBox; lblColumn: TLabel; lblValue: TLabel; edtValue: TEdit; lblOperator: TLabel; cbbColumn: TComboBox; trvSearch: TTreeView; Splitter1: TSplitter; btnSearch: TButton; btnDelete: TButton; pnlSearchPanel: TPanel; edtSearchText: TEdit; btnCloseSearch: TButton; procedure btnLoadClick(Sender: TObject); procedure btnSearchClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lvContactsKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure trvSearchDblClick(Sender: TObject); procedure lvContactsAdvancedCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); procedure btnDeleteClick(Sender: TObject); procedure edtSearchTextKeyPress(Sender: TObject; var Key: Char); procedure btnCloseSearchClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses ListViewHelper; {$R *.dfm} procedure TForm1.btnLoadClick(Sender: TObject); var AlvItem : TListItem; Ix : Integer; st : TStatus; begin lvContacts.Clear; trvSearch.Items.Clear; pbLoading.Max := seCount.Value; pbLoading.Position := 0; for Ix := 0 to seCount.Value do begin st := TStatus.Create; AlvItem := lvContacts.Items.Add; with AlvItem do begin Caption := IntToStr(Ix); SubItems.Add(IsimArr[Random(6)]); SubItems.Add(SoyadArr[Random(6)]); SubItems.Add(IntToStr(Random(50))); Data := st; end; pbLoading.StepBy(1); end; end; procedure TForm1.btnSearchClick(Sender: TObject); var Criter : TCriteria; SearchCount : Integer; SearchParent,SearchNode : TTreeNode; begin SearchCount := 0; Criter := TCriteria .CreateCriteria .AddColumn(cbbColumn.Text) .AddValue(edtValue.Text) .SelectOperator(OperatorArr[cbbOperator.ItemIndex]); trvSearch.Visible := True; Splitter1.Visible := True; if trvSearch.Items.Count = 0 then SearchParent := trvSearch.Items.AddFirst(nil,'Aranan "'+UpperCase(Criter.FValue)+'"') else SearchParent := trvSearch.Items.Add(trvSearch.TopItem,'Aranan "'+UpperCase(Criter.FValue)+'"'); lvContacts .LoopC( Criter, procedure (A:TListItem) var i : Integer; SearchText :string; begin if SearchCount = 0 then SearchNode := trvSearch.Items.AddChild(SearchParent,'Bulunanlar'); Inc(SearchCount); for i := 0 to A.SubItems.Count-1 do SearchText := SearchText + ','+A.SubItems[i]; trvSearch.Items.AddChild(SearchNode,'Satır no :'+IntToStr(A.Index)+SearchText).Data := A; end ); SearchParent.Text := SearchParent.Text +'('+ IntToStr(SearchCount)+' tane değer bulundu)'; trvSearch.FullCollapse; SearchParent.Expand(True); Criter.Free; end; procedure TForm1.edtSearchTextKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin lvContacts.FullTextSearch(trvSearch,edtSearchText.Text); trvSearch.Visible := True; Splitter1.Visible := True; end; end; procedure TForm1.FormCreate(Sender: TObject); var i : integer; begin for i := 0 to lvContacts.Columns.Count-1 do cbbColumn.Items.Add(lvContacts.Column[i].Caption); cbbColumn.ItemIndex := 0; end; procedure TForm1.lvContactsAdvancedCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); begin if Assigned(Item.Data) then if TStatus(Item.Data).FDeleted then Sender.Canvas.Brush.Color := clGray else Sender.Canvas.Brush.Color := clWhite; end; procedure TForm1.lvContactsKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (ssCtrl in Shift) and (Key = ord('F')) then begin pnlSearchPanel.Visible := True; edtSearchText.SetFocus; end; if Assigned((Sender as TListView).Selected) then if Assigned((Sender as TListView).Selected.Data) then if (key = VK_DELETE)then if (TStatus((Sender as TListView).Selected.Data).FDeleted) then TStatus((Sender as TListView).Selected.Data).FDeleted := False else TStatus((Sender as TListView).Selected.Data).FDeleted := True; end; procedure TForm1.trvSearchDblClick(Sender: TObject); begin if Assigned(trvSearch.Selected.Data) then begin lvContacts.ItemIndex := TListItem(trvSearch.Selected.Data).Index; lvContacts.Selected.MakeVisible(true); end; end; procedure TForm1.btnCloseSearchClick(Sender: TObject); begin pnlSearchPanel.Visible := False; trvSearch.Visible := False; Splitter1.Visible := False; end; procedure TForm1.btnDeleteClick(Sender: TObject); begin lvContacts .Loops( stDelete, procedure (A:TListItem) var qry : TADOQuery; begin // try // try // qry := TADOQuery.Create(nil); // qry.Connection := Conn; //adoconnection bağlantısı olan component // // qry.SQL.Text := 'Delete Contacts where ID=:ID'; // qry.Parameters.ParamByName('ID').Value := A.Caption; // qry.ExecSQL; // except // raise Exception.Create('Silme işleminde hata oluştu.'); // end; // finally // qry.Free; // end; A.Free; end ); end; end.
program HelloTeapot; {$mode objfpc}{$H+} { VideoCore IV example - Hello Teapot } { } { Using OpenGL ES and MMAL to show what the Raspberry Pi can do, if you haven't} { seen it before you should be impressed. } { } { To compile the example select Run, Compile (or Run, Build) from the menu. } { } { Once compiled copy the kernel7.img file to an SD card along with the } { firmware files and use it to boot your Raspberry Pi. } { } { Make sure you also copy the teapot.obj.dat and test.h264 files from the Media} { folder. } { } { You also MUST create a config.txt file in the root directory of your SD card } { with at least the following setting: } { } { gpu_mem=128 } { } { This version is for Raspberry Pi 2B and will also work on a 3B. } uses RaspberryPi2, {Include RaspberryPi2 to make sure all standard functions are included} GlobalConst, GlobalTypes, Threads, Console, SysUtils, HTTP, {Include HTTP and WebStatus so we can see from a web browser what is happening} WebStatus, Classes, uTFTP, Winsock2, { needed to use ultibo-tftp } { needed for telnet } Shell, ShellFilesystem, ShellUpdate, RemoteShell, { needed for telnet } Logging, Syscalls, {Include the Syscalls unit to provide C library support} VC4; {Include the VC4 unit to enable access to the GPU} var WindowHandle:TWindowHandle; MyPLoggingDevice : ^TLoggingDevice; HTTPListener:THTTPListener; { needed to use ultibo-tftp } TCP : TWinsock2TCPClient; IPAddress : string; function WaitForIPComplete : string; var TCP : TWinsock2TCPClient; begin TCP := TWinsock2TCPClient.Create; Result := TCP.LocalAddress; if (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') then begin while (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') do begin sleep (1500); Result := TCP.LocalAddress; end; end; TCP.Free; end; procedure Msg (Sender : TObject; s : string); begin ConsoleWindowWriteLn (WindowHandle, s); end; procedure WaitForSDDrive; begin while not DirectoryExists ('C:\') do sleep (500); end; {Link our C library to include the original example} {$linklib hello_teapot} {Import the main function of the example so we can call it from Ultibo} procedure hello_teapot; cdecl; external 'hello_teapot' name 'hello_teapot'; begin {Create a console window as usual} WindowHandle:=ConsoleWindowCreate(ConsoleDeviceGetDefault,CONSOLE_POSITION_FULL,True); ConsoleWindowWriteLn(WindowHandle,'Starting Hello Teapot'); {Wait a couple of seconds for C:\ drive to be ready} ConsoleWindowWriteLn(WindowHandle,'Waiting for drive C:\'); {while not DirectoryExists('C:\') do begin {Sleep for a second} Sleep(1000); end;} // wait for IP address and SD Card to be initialised. WaitForSDDrive; IPAddress := WaitForIPComplete; {Wait a few seconds for all initialization (like filesystem and network) to be done} Sleep(5000); ConsoleWindowWriteLn(WindowHandle,'C:\ drive is ready'); ConsoleWindowWriteLn(WindowHandle,''); ConsoleWindowWriteLn (WindowHandle, 'Local Address ' + IPAddress); SetOnMsg (@Msg); {Create and start the HTTP Listener for our web status page} HTTPListener:=THTTPListener.Create; HTTPListener.Active:=True; {Register the web status page, the "Thread List" page will allow us to see what is happening in the example} WebStatusRegister(HTTPListener,'','',True); {Call the main function of the example, it will return here when completed (if ever)} hello_teapot; ConsoleWindowWriteLn(WindowHandle,'Completed Hello Teapot'); {Halt the main thread here} ThreadHalt(0); end.
unit uGlobalParameters; interface type TGlobalParameters = class public // Information about logged user class var IdUser: string; class var UserName: string; class var UserSurname: string; class var UserUsername: string; class var NumberOfAuthorization: Integer; class var IdWorkstation: string; class var LoginState: string; end; implementation end.
unit daFieldDescription; // Модуль: "w:\common\components\rtl\Garant\DA\daFieldDescription.pas" // Стереотип: "SimpleClass" // Элемент модели: "TdaFieldDescription" MUID: (5538D0A902AF) {$Include w:\common\components\rtl\Garant\DA\daDefine.inc} interface uses l3IntfUses , l3ProtoObject , daInterfaces , daTypes ; type TdaFieldDescription = class(Tl3ProtoObject, IdaFieldDescription) private f_Table: Pointer; f_SQLName: AnsiString; f_Description: AnsiString; f_Required: Boolean; f_DataType: TdaDataType; f_Index: Integer; f_Size: Integer; f_IsPrimaryKey: Boolean; protected function Get_SQLName: AnsiString; function Get_Description: AnsiString; function Get_DataType: TdaDataType; function Get_Required: Boolean; function Get_Table: IdaTableDescription; function Get_Index: Integer; procedure BindToTable(const aTable: IdaTableDescription = nil; anIndex: Integer = -1); function Get_Size: Integer; function Get_IsPrimaryKey: Boolean; public constructor Create(const aSQLName: AnsiString; const aDesc: AnsiString; aRequired: Boolean; aType: TdaDataType; aSize: Integer = 0; anIsPrimaryKey: Boolean = False); reintroduce; class function Make(const aSQLName: AnsiString; const aDesc: AnsiString; aRequired: Boolean; aType: TdaDataType; aSize: Integer = 0; anIsPrimaryKey: Boolean = False): IdaFieldDescription; reintroduce; end;//TdaFieldDescription implementation uses l3ImplUses //#UC START# *5538D0A902AFimpl_uses* //#UC END# *5538D0A902AFimpl_uses* ; constructor TdaFieldDescription.Create(const aSQLName: AnsiString; const aDesc: AnsiString; aRequired: Boolean; aType: TdaDataType; aSize: Integer = 0; anIsPrimaryKey: Boolean = False); //#UC START# *5538D15A03E5_5538D0A902AF_var* //#UC END# *5538D15A03E5_5538D0A902AF_var* begin //#UC START# *5538D15A03E5_5538D0A902AF_impl* inherited Create; f_SQLName := aSQLName; f_Description := aDesc; f_Required := aRequired; f_DataType := aType; f_Size := aSize; f_IsPrimaryKey := anIsPrimaryKey; //#UC END# *5538D15A03E5_5538D0A902AF_impl* end;//TdaFieldDescription.Create class function TdaFieldDescription.Make(const aSQLName: AnsiString; const aDesc: AnsiString; aRequired: Boolean; aType: TdaDataType; aSize: Integer = 0; anIsPrimaryKey: Boolean = False): IdaFieldDescription; var l_Inst : TdaFieldDescription; begin l_Inst := Create(aSQLName, aDesc, aRequired, aType, aSize, anIsPrimaryKey); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TdaFieldDescription.Make function TdaFieldDescription.Get_SQLName: AnsiString; //#UC START# *5538AA34030F_5538D0A902AFget_var* //#UC END# *5538AA34030F_5538D0A902AFget_var* begin //#UC START# *5538AA34030F_5538D0A902AFget_impl* Result := f_SQLName; //#UC END# *5538AA34030F_5538D0A902AFget_impl* end;//TdaFieldDescription.Get_SQLName function TdaFieldDescription.Get_Description: AnsiString; //#UC START# *5538AA4302F7_5538D0A902AFget_var* //#UC END# *5538AA4302F7_5538D0A902AFget_var* begin //#UC START# *5538AA4302F7_5538D0A902AFget_impl* Result := f_Description; //#UC END# *5538AA4302F7_5538D0A902AFget_impl* end;//TdaFieldDescription.Get_Description function TdaFieldDescription.Get_DataType: TdaDataType; //#UC START# *5538AA86026D_5538D0A902AFget_var* //#UC END# *5538AA86026D_5538D0A902AFget_var* begin //#UC START# *5538AA86026D_5538D0A902AFget_impl* Result := f_DataType; //#UC END# *5538AA86026D_5538D0A902AFget_impl* end;//TdaFieldDescription.Get_DataType function TdaFieldDescription.Get_Required: Boolean; //#UC START# *5538AAA000DD_5538D0A902AFget_var* //#UC END# *5538AAA000DD_5538D0A902AFget_var* begin //#UC START# *5538AAA000DD_5538D0A902AFget_impl* Result := f_Required; //#UC END# *5538AAA000DD_5538D0A902AFget_impl* end;//TdaFieldDescription.Get_Required function TdaFieldDescription.Get_Table: IdaTableDescription; //#UC START# *5538AAB4012A_5538D0A902AFget_var* //#UC END# *5538AAB4012A_5538D0A902AFget_var* begin //#UC START# *5538AAB4012A_5538D0A902AFget_impl* Result := IdaTableDescription(f_Table); //#UC END# *5538AAB4012A_5538D0A902AFget_impl* end;//TdaFieldDescription.Get_Table function TdaFieldDescription.Get_Index: Integer; //#UC START# *5538AADD0314_5538D0A902AFget_var* //#UC END# *5538AADD0314_5538D0A902AFget_var* begin //#UC START# *5538AADD0314_5538D0A902AFget_impl* Result := f_Index; //#UC END# *5538AADD0314_5538D0A902AFget_impl* end;//TdaFieldDescription.Get_Index procedure TdaFieldDescription.BindToTable(const aTable: IdaTableDescription = nil; anIndex: Integer = -1); //#UC START# *5538AB95021E_5538D0A902AF_var* //#UC END# *5538AB95021E_5538D0A902AF_var* begin //#UC START# *5538AB95021E_5538D0A902AF_impl* f_Table := Pointer(aTable); f_Index := anIndex; //#UC END# *5538AB95021E_5538D0A902AF_impl* end;//TdaFieldDescription.BindToTable function TdaFieldDescription.Get_Size: Integer; //#UC START# *553A064A03B1_5538D0A902AFget_var* //#UC END# *553A064A03B1_5538D0A902AFget_var* begin //#UC START# *553A064A03B1_5538D0A902AFget_impl* Result := f_Size; //#UC END# *553A064A03B1_5538D0A902AFget_impl* end;//TdaFieldDescription.Get_Size function TdaFieldDescription.Get_IsPrimaryKey: Boolean; //#UC START# *5763DAB80335_5538D0A902AFget_var* //#UC END# *5763DAB80335_5538D0A902AFget_var* begin //#UC START# *5763DAB80335_5538D0A902AFget_impl* Result := f_IsPrimaryKey; //#UC END# *5763DAB80335_5538D0A902AFget_impl* end;//TdaFieldDescription.Get_IsPrimaryKey end.
unit uRotateBitmap; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Buttons, LCLType, IntfGraphics, Types; type TRotateDirection = (rdNormal, rdRight, rdLeft); { TCustomRotatedBitmap } TCustomRotatedBitmap = class private FActiveBitmap: TBitmap; FDirection: TRotateDirection; FNormalBitmap: TBitmap; FRotatedBitmap: TBitmap; FTransparent: Boolean; FActiveBitmapNeedsUpdate: Boolean; function GetBitmap : TBitmap; function GetEmpty: Boolean; procedure NormalBitmapChanged(Sender: TObject); procedure SetBitmap(const AValue: TBitmap); procedure SetDirection(const AValue: TRotateDirection); procedure SetTransparent(const AValue: Boolean); procedure UpdateActiveBitmap; virtual; protected procedure NotifyBitmapChange; virtual; function GetWidth: Integer; virtual; function GetHeight: Integer; virtual; property Bitmap: TBitmap read GetBitmap write SetBitmap; property Transparent: Boolean read FTransparent write SetTransparent; public constructor Create; virtual; destructor Destroy; override; procedure Draw(Canvas: TCanvas; X, Y: Integer); virtual; function IsBitmapStored : Boolean; property Direction: TRotateDirection read FDirection write SetDirection; property Empty: Boolean read GetEmpty; property Width: Integer read GetWidth; property Height: Integer read GetHeight; end; { TRotatedBitmap } TRotatedBitmap = class (TCustomRotatedBitmap) public property Bitmap; property Transparent; end; { TRotatedGlyph } TRotatedGlyph = class (TCustomRotatedBitmap) private FGlyph : TButtonGlyph; FButtonState : TButtonState; FOnChange: TNotifyEvent; procedure SetButtonState(Value: TButtonState); procedure UpdateActiveBitmap; override; protected procedure NotifyBitmapChange; override; public constructor Create; override; destructor Destroy; override; procedure Draw(Canvas: TCanvas; X, Y: Integer); override; property OnChange: TNotifyEvent read FOnChange write FOnChange; property State: TButtonState read FButtonState write SetButtonState; property Bitmap; property Transparent; end; function CreateRotatedBitmap(SrcImage: TRasterImage; Direction: TRotateDirection): TBitmap; procedure DrawRotatedText(Canvas: TCanvas; X, Y, TextWidth, TextHeight: Integer; const Text: String; Direction: TRotateDirection); implementation uses LCLProc; function CreateRotatedBitmap(SrcImage: TRasterImage; Direction: TRotateDirection): TBitmap; var px, py, nx, ny : Integer; RotateImg, NormalImg: TLazIntfImage; begin Result := TBitmap.Create; if (SrcImage.Width = 0) or (SrcImage.Height = 0) then begin Exit; end; NormalImg := SrcImage.CreateIntfImage; RotateImg := TLazIntfImage.Create(NormalImg.Height, NormalImg.Width); RotateImg.DataDescription := NormalImg.DataDescription; RotateImg.SetSize(NormalImg.Height, NormalImg.Width); RotateImg.FillPixels(TColorToFPColor(clBlack)); for px := 0 to NormalImg.Width - 1 do for py := 0 to NormalImg.Height - 1 do begin if Direction = rdRight then begin nx := RotateImg.Width - 1 - py; ny := px; end else begin nx := py; ny := RotateImg.Height - 1 - px; end; RotateImg.Colors[nx,ny] := NormalImg.Colors[px,py]; end; Result.LoadFromIntfImage(RotateImg); if SrcImage.Masked then Result.TransparentColor := SrcImage.TransparentColor; Result.Transparent := SrcImage.Transparent; RotateImg.Free; NormalImg.Free; end; procedure DrawRotatedText(Canvas: TCanvas; X, Y, TextWidth, TextHeight: Integer; const Text: String; Direction: TRotateDirection); begin case Direction of rdNormal: begin Canvas.Font.Orientation := 0; Canvas.TextOut(X, Y, Text); end; rdLeft: begin Canvas.Font.Orientation := 900; Canvas.TextOut(X, Y + TextHeight, Text); end; rdRight: begin Canvas.Font.Orientation := -900; Canvas.TextOut(X + TextWidth, Y, Text); end; end; end; { TCustomRotatedBitmap } function TCustomRotatedBitmap.GetBitmap: TBitmap; begin Result := FNormalBitmap; end; function TCustomRotatedBitmap.GetEmpty: Boolean; begin Result := (FNormalBitmap.Width = 0) or (FNormalBitmap.Height = 0); end; procedure TCustomRotatedBitmap.NormalBitmapChanged(Sender: TObject); begin FActiveBitmapNeedsUpdate := True; NotifyBitmapChange; end; procedure TCustomRotatedBitmap.SetBitmap(const AValue: TBitmap); begin FNormalBitmap.Assign(AValue); FActiveBitmapNeedsUpdate := True; end; procedure TCustomRotatedBitmap.SetDirection(const AValue: TRotateDirection); begin if FDirection = AValue then Exit; FDirection := AValue; FActiveBitmapNeedsUpdate := True; end; procedure TCustomRotatedBitmap.SetTransparent(const AValue: Boolean); begin if FTransparent = AValue then exit; FTransparent := AValue; FActiveBitmap.Transparent := FTransparent; end; procedure TCustomRotatedBitmap.UpdateActiveBitmap; begin FreeAndNil(FRotatedBitmap); if FDirection = rdNormal then FActiveBitmap := FNormalBitmap else begin FRotatedBitmap := CreateRotatedBitmap(FNormalBitmap, FDirection); FActiveBitmap := FRotatedBitmap; end; FActiveBitmapNeedsUpdate := False; end; procedure TCustomRotatedBitmap.NotifyBitmapChange; begin end; function TCustomRotatedBitmap.GetWidth: Integer; begin if FActiveBitmapNeedsUpdate then UpdateActiveBitmap; Result := FActiveBitmap.Width; end; function TCustomRotatedBitmap.GetHeight: Integer; begin if FActiveBitmapNeedsUpdate then UpdateActiveBitmap; Result := FActiveBitmap.Height; end; constructor TCustomRotatedBitmap.Create; begin FDirection := rdNormal; FNormalBitmap := TBitmap.Create; FNormalBitmap.OnChange := @NormalBitmapChanged; FActiveBitmap := FNormalBitmap; end; destructor TCustomRotatedBitmap.Destroy; begin FNormalBitmap.Destroy; FRotatedBitmap.Free; end; procedure TCustomRotatedBitmap.Draw(Canvas: TCanvas; X, Y: Integer); begin if FActiveBitmapNeedsUpdate then UpdateActiveBitmap; Canvas.Draw(X, Y, FActiveBitmap); end; function TCustomRotatedBitmap.IsBitmapStored : Boolean; begin Result := (not FActiveBitmap.Empty) and (FActiveBitmap.Width>0) and (FActiveBitmap.Height>0); end; { TRotatedGlyph } procedure TRotatedGlyph.SetButtonState(Value: TButtonState); begin FButtonState := Value; end; procedure TRotatedGlyph.UpdateActiveBitmap; begin inherited UpdateActiveBitmap; FGlyph.Glyph := FActiveBitmap; end; procedure TRotatedGlyph.NotifyBitmapChange; begin if Assigned(FOnChange) then FOnChange(Self); end; constructor TRotatedGlyph.Create; begin inherited Create; FGlyph := TButtonGlyph.Create; end; destructor TRotatedGlyph.Destroy; begin FGlyph.Destroy; inherited Destroy; end; procedure TRotatedGlyph.Draw(Canvas: TCanvas; X, Y: Integer); var R: TRect; P: TPoint; begin if FActiveBitmapNeedsUpdate then UpdateActiveBitmap; R := Rect(0, 0, FActiveBitmap.Width, FActiveBitmap.Height); P := Point(X, Y); //DebugLn(DbgS(R)); //DebugLn(DbgS(P)); //DebugLn('Transparent: '+BoolToStr(Transparent, true)); FGlyph.Draw(Canvas, R, P, FButtonState, Transparent, 0); end; end.
unit hw_1942; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,ay_8910,rom_engine,pal_engine, sound_engine,qsnapshot; function iniciar_hw1942:boolean; implementation const hw1942_rom:array[0..4] of tipo_roms=( (n:'srb-03.m3';l:$4000;p:0;crc:$d9dafcc3),(n:'srb-04.m4';l:$4000;p:$4000;crc:$da0cf924), (n:'srb-05.m5';l:$4000;p:$8000;crc:$d102911c),(n:'srb-06.m6';l:$2000;p:$c000;crc:$466f8248), (n:'srb-07.m7';l:$4000;p:$10000;crc:$0d31038c)); hw1942_snd_rom:tipo_roms=(n:'sr-01.c11';l:$4000;p:0;crc:$bd87f06b); hw1942_pal:array[0..5] of tipo_roms=( (n:'sb-5.e8';l:$100;p:0;crc:$93ab8153),(n:'sb-6.e9';l:$100;p:$100;crc:$8ab44f7d), (n:'sb-7.e10';l:$100;p:$200;crc:$f4ade9a4),(n:'sb-0.f1';l:$100;p:$300;crc:$6047d91b), (n:'sb-4.d6';l:$100;p:$400;crc:$4858968d),(n:'sb-8.k3';l:$100;p:$500;crc:$f6fad943)); hw1942_char:tipo_roms=(n:'sr-02.f2';l:$2000;p:0;crc:$6ebca191); hw1942_tiles:array[0..5] of tipo_roms=( (n:'sr-08.a1';l:$2000;p:0;crc:$3884d9eb),(n:'sr-09.a2';l:$2000;p:$2000;crc:$999cf6e0), (n:'sr-10.a3';l:$2000;p:$4000;crc:$8edb273a),(n:'sr-11.a4';l:$2000;p:$6000;crc:$3a2726c3), (n:'sr-12.a5';l:$2000;p:$8000;crc:$1bd3d8bb),(n:'sr-13.a6';l:$2000;p:$a000;crc:$658f02c4)); hw1942_sprites:array[0..3] of tipo_roms=( (n:'sr-14.l1';l:$4000;p:0;crc:$2528bec6),(n:'sr-15.l2';l:$4000;p:$4000;crc:$f89287aa), (n:'sr-16.n1';l:$4000;p:$8000;crc:$024418f8),(n:'sr-17.n2';l:$4000;p:$c000;crc:$e2c7e489)); hw1942_dip_a:array [0..4] of def_dip=( (mask:$7;name:'Coin A';number:8;dip:((dip_val:$1;dip_name:'4C 1C'),(dip_val:$2;dip_name:'3C 1C'),(dip_val:$4;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$3;dip_name:'2C 3C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 4C'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),())), (mask:$8;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$8;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Bonus Life';number:4;dip:((dip_val:$30;dip_name:'20K 80K Every 80K'),(dip_val:$20;dip_name:'20K 100K Every 100K'),(dip_val:$10;dip_name:'30K 80K Every 80K'),(dip_val:$0;dip_name:'30K 100K Every 100K'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Lives';number:4;dip:((dip_val:$80;dip_name:'1'),(dip_val:$40;dip_name:'2'),(dip_val:$c0;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),()); hw1942_dip_b:array [0..4] of def_dip=( (mask:$7;name:'Coin B';number:8;dip:((dip_val:$1;dip_name:'4C 1C'),(dip_val:$2;dip_name:'3C 1C'),(dip_val:$4;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$3;dip_name:'2C 3C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 4C'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),())), (mask:$10;name:'Flip Screen';number:2;dip:((dip_val:$10;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$60;name:'Difficulty';number:4;dip:((dip_val:$40;dip_name:'Easy'),(dip_val:$60;dip_name:'Normal'),(dip_val:$20;dip_name:'Difficult'),(dip_val:$0;dip_name:'Very Difficult'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Screen Stop';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var memoria_rom:array[0..2,0..$3fff] of byte; scroll:word; sound_command,rom_bank,palette_bank:byte; procedure update_video_hw1942; procedure draw_sprites; var f,color,nchar,x,y:word; i,h,atrib:byte; begin for f:=$1f downto 0 do begin atrib:=memoria[$cc01+(f*4)]; nchar:=(memoria[$cc00+(f*4)] and $7f)+(atrib and $20) shl 2+(memoria[$cc00+(f*4)] and $80) shl 1; color:=(atrib and $0f) shl 4; x:=240-(memoria[$cc03+(f*4)]-$10*(atrib and $10)); y:=memoria[$cc02+(f*4)]; // handle double or quadruple height i:=(atrib and $c0) shr 6; if (i=2) then i:=3; for h:=i downto 0 do begin put_gfx_sprite(nchar+h,color,false,false,1); actualiza_gfx_sprite(y+16*h,x,1,1); end; end; end; var f,color,nchar,pos,x,y:word; attr:byte; begin for f:=0 to $1ff do begin //tiles if gfx[2].buffer[f] then begin x:=f and $f; y:=31-(f shr 4); pos:=x+((f and $1f0) shl 1); attr:=memoria[$d810+pos]; nchar:=memoria[$d800+pos]+((attr and $80) shl 1); color:=((attr and $1f)+(palette_bank*$20)) shl 3; put_gfx_flip(x*16,y*16,nchar,color,2,2,(attr and $40)<>0,(attr and $20)<>0); gfx[2].buffer[f]:=false; end; end; for f:=0 to $3ff do begin //Chars if gfx[0].buffer[f] then begin x:=f div 32; y:=31-(f mod 32); attr:=memoria[f+$d400]; color:=(attr and $3f) shl 2; nchar:=memoria[f+$d000]+((attr and $80) shl 1); put_gfx_trans(x*8,y*8,nchar,color,3,0); gfx[0].buffer[f]:=false; end; end; scroll__y(2,1,256-scroll); draw_sprites; actualiza_trozo(0,0,256,256,3,0,0,256,256,1); actualiza_trozo_final(16,0,224,256,1); end; procedure eventos_hw1942; begin if event.arcade then begin //P1 if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); //P2 if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20); //SYSTEM 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[1] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); end; end; procedure hw1942_principal; var f:byte; frame_m,frame_s:single; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; case f of $2c:z80_1.change_irq(HOLD_LINE); $6d:begin z80_0.im0:=$cf; z80_0.change_irq(HOLD_LINE); z80_1.change_irq(HOLD_LINE); end; $af:z80_1.change_irq(HOLD_LINE); $f0:begin z80_0.im0:=$d7; z80_0.change_irq(HOLD_LINE); z80_1.change_irq(HOLD_LINE); update_video_hw1942; end; end; end; eventos_hw1942; video_sync; end; end; function hw1942_getbyte(direccion:word):byte; begin case direccion of $0..$7fff,$cc00..$cc7f,$d000..$dbff,$e000..$efff:hw1942_getbyte:=memoria[direccion]; $8000..$bfff:hw1942_getbyte:=memoria_rom[rom_bank,direccion and $3fff]; $c000:hw1942_getbyte:=marcade.in0; $c001:hw1942_getbyte:=marcade.in1; $c002:hw1942_getbyte:=marcade.in2; $c003:hw1942_getbyte:=marcade.dswa; $c004:hw1942_getbyte:=marcade.dswb; end; end; procedure hw1942_putbyte(direccion:word;valor:byte); begin case direccion of 0..$bfff:; $c800:sound_command:=valor; $c802:scroll:=valor or (scroll and $100); $c803:scroll:=((valor and $1) shl 8) or (scroll and $ff); $c804:begin if (valor and $10)<>0 then z80_1.change_reset(ASSERT_LINE) else z80_1.change_reset(CLEAR_LINE); main_screen.flip_main_screen:=(valor and $80)<>0; end; $c805:palette_bank:=valor; $c806:rom_bank:=valor and $3; $cc00..$cc7f,$e000..$efff:memoria[direccion]:=valor; $d000..$d7ff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $d800..$dbff:if memoria[direccion]<>valor then begin gfx[2].buffer[(direccion and $f)+((direccion and $3e0) shr 1)]:=true; memoria[direccion]:=valor; end; end; end; function hw1942_snd_getbyte(direccion:word):byte; begin case direccion of 0..$47ff:hw1942_snd_getbyte:=mem_snd[direccion]; $6000:hw1942_snd_getbyte:=sound_command end; end; procedure hw1942_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$3fff:; $4000..$47ff:mem_snd[direccion]:=valor; $8000:ay8910_0.Control(valor); $8001:ay8910_0.Write(valor); $c000:ay8910_1.Control(valor); $c001:ay8910_1.Write(valor); end; end; procedure hw1942_sound_update; begin ay8910_0.update; ay8910_1.update; end; procedure hw1942_qsave(nombre:string); var data:pbyte; size:word; buffer:array[0..4] of byte; begin open_qsnapshot_save('1942'+nombre); getmem(data,200); //CPU size:=z80_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=z80_1.save_snapshot(data); savedata_qsnapshot(data,size); //SND size:=ay8910_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=ay8910_1.save_snapshot(data); savedata_qsnapshot(data,size); //MEM savedata_com_qsnapshot(@memoria[$c000],$4000); savedata_com_qsnapshot(@mem_snd[$4000],$800); //MISC buffer[0]:=scroll and $ff; buffer[1]:=scroll shr 8; buffer[2]:=sound_command; buffer[3]:=rom_bank; buffer[4]:=palette_bank; savedata_qsnapshot(@buffer,5); freemem(data); close_qsnapshot; end; procedure hw1942_qload(nombre:string); var data:pbyte; buffer:array[0..4] of byte; begin if not(open_qsnapshot_load('1942'+nombre)) then exit; getmem(data,200); //CPU loaddata_qsnapshot(data); z80_0.load_snapshot(data); loaddata_qsnapshot(data); z80_1.load_snapshot(data); //SND loaddata_qsnapshot(data); ay8910_0.load_snapshot(data); loaddata_qsnapshot(data); ay8910_1.load_snapshot(data); //MEM loaddata_qsnapshot(@memoria[$c000]); loaddata_qsnapshot(@mem_snd[$4000]); //MISC loaddata_qsnapshot(@buffer); scroll:=buffer[0] or (buffer[1] shl 8); sound_command:=buffer[2]; rom_bank:=buffer[3]; palette_bank:=buffer[4]; freemem(data); close_qsnapshot; end; //Main procedure reset_hw1942; begin z80_0.reset; z80_1.reset; ay8910_0.reset; ay8910_1.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; scroll:=0; rom_bank:=0; palette_bank:=0; sound_command:=0; end; function iniciar_hw1942:boolean; var colores:tpaleta; f:word; memoria_temp:array[0..$17fff] of byte; const ps_x:array[0..15] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3, 16*16+0, 16*16+1, 16*16+2, 16*16+3, 16*16+8+0, 16*16+8+1, 16*16+8+2, 16*16+8+3); ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16); pt_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7); pt_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8); begin iniciar_hw1942:=false; llamadas_maquina.bucle_general:=hw1942_principal; llamadas_maquina.reset:=reset_hw1942; llamadas_maquina.save_qsnap:=hw1942_qsave; llamadas_maquina.load_qsnap:=hw1942_qload; iniciar_audio(false); screen_init(1,256,512,false,true); screen_init(2,256,512); screen_mod_scroll(2,256,256,255,512,256,511); screen_init(3,256,256,true); iniciar_video(224,256); //Main CPU z80_0:=cpu_z80.create(4000000,$100); z80_0.change_ram_calls(hw1942_getbyte,hw1942_putbyte); //Sound CPU z80_1:=cpu_z80.create(3000000,$100); z80_1.change_ram_calls(hw1942_snd_getbyte,hw1942_snd_putbyte); z80_1.init_sound(hw1942_sound_update); //Sound Chips AY8910_0:=ay8910_chip.create(1500000,AY8910,1); AY8910_1:=ay8910_chip.create(1500000,AY8910,1); //cargar roms y ponerlas en su sitio if not(roms_load(@memoria_temp,hw1942_rom)) then exit; copymemory(@memoria,@memoria_temp,$8000); for f:=0 to 2 do copymemory(@memoria_rom[f,0],@memoria_temp[$8000+(f*$4000)],$4000); //cargar ROMS sonido if not(roms_load(@mem_snd,hw1942_snd_rom)) then exit; //convertir chars if not(roms_load(@memoria_temp,hw1942_char)) then exit; init_gfx(0,8,8,$200); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,16*8,4,0); convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,true); //convertir sprites if not(roms_load(@memoria_temp,hw1942_sprites)) then exit; init_gfx(1,16,16,$200); gfx[1].trans[15]:=true; gfx_set_desc_data(4,0,64*8,512*64*8+4,512*64*8+0,4,0); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,true); //tiles if not(roms_load(@memoria_temp,hw1942_tiles)) then exit; init_gfx(2,16,16,$200); gfx_set_desc_data(3,0,32*8,0,$4000*8,$4000*8*2); convert_gfx(2,0,@memoria_temp,@pt_x,@pt_y,false,true); //poner la paleta if not(roms_load(@memoria_temp,hw1942_pal)) then exit; for f:=0 to $ff do begin colores[f].r:=pal4bit(memoria_temp[f]); colores[f].g:=pal4bit(memoria_temp[f+$100]); colores[f].b:=pal4bit(memoria_temp[f+$200]); gfx[0].colores[f]:=memoria_temp[$300+f]+$80; //chars gfx[2].colores[f]:=memoria_temp[$400+f]; //tiles gfx[2].colores[f+$100]:=memoria_temp[$400+f]+$10; gfx[2].colores[f+$200]:=memoria_temp[$400+f]+$20; gfx[2].colores[f+$300]:=memoria_temp[$400+f]+$30; gfx[1].colores[f]:=memoria_temp[$500+f]+$40; //sprites end; set_pal(colores,256); //DIP marcade.dswa:=$77; marcade.dswa_val:=@hw1942_dip_a; marcade.dswb:=$ff; marcade.dswb_val:=@hw1942_dip_b; //final reset_hw1942; iniciar_hw1942:=true; end; end.
unit BaiduMapAPI.Search.CommTypes; //author:Xubzhlin //Email:371889755@qq.com //百度地图API 检索 公共单元 //TSearchResult 检索结果 interface uses {$IFDEF Android} Androidapi.JNI.baidu.mapapi.search, {$ENDIF} {$IFDEF iOS} iOSapi.BaiduMapAPI_Base, {$ENDIF} FMX.Maps; type TSearchResult_ErrorNo = ( NO_ERROR=0, ///<检索结果正常返回 RESULT_NOT_FOUND, ///<没有找到检索结果 AMBIGUOUS_KEYWORD, ///<检索词有岐义 AMBIGUOUS_ROURE_ADDR, ///<检索地址有岐义 NOT_SUPPORT_BUS, ///<该城市不支持公交搜索 NOT_SUPPORT_BUS_2CITY, ///<不支持跨城市公交 ST_EN_TOO_NEAR, ///<起终点太近 KEY_ERROR, ///<key错误 PERMISSION_UNFINISHED, ///还未完成鉴权,请在鉴权通过后重试 NETWORK_TIME_OUT, ///网络连接超时 NETWORK_ERROR, ///网络连接错误 POIINDOOR_BID_ERROR, ///室内图ID错误 POIINDOOR_FLOOR_ERROR, ///室内图检索楼层错误 POIINDOOR_SERVER_ERROR, ///室内图检索服务器内部错误 INDOOR_ROUTE_NO_IN_BUILDING, ///起终点不在支持室内路线的室内图内 INDOOR_ROUTE_NO_IN_SAME_BUILDING,///室内路线规划起终点不在同一个室内 MASS_TRANSIT_SERVER_ERROR, ///跨城公共交通服务器内部错误 MASS_TRANSIT_OPTION_ERROR, ///跨城公共交通错误码:参数无效 MASS_TRANSIT_NO_POI_ERROR, ///跨城公共交通没有匹配的POI SEARCH_SERVER_INTERNAL_ERROR,///服务器内部错误 SEARCH_OPTION_ERROR, ///参数错误 REQUEST_ERROR///请求错误 ); TPoiType = (POINT = 0, BUS_STATION = 1, BUS_LINE = 2, SUBWAY_STATION = 3, SUBWAY_LINE = 4); TPoiInfo = record name:string; uid:string; address:string; city:string; phoneNum:string; postCode:string; &type:TPoiType; location:TMapCoordinate; isPano:Boolean; end; TCityInfo = record city:string; num:Integer; end; TPoiAddrInfo = record address:string; location:TMapCoordinate; name:string; end; TSearchResult = class(TObject) error:TSearchResult_ErrorNo; end; TRouteLineType = ( BIKINGSTEP, //骑行 DRIVESTEP, //驾车 TRANSITSTEP,//换乘 WALKSTEP //步行 ); //交通工具 枚举 TStepVehicleInfoType = ( ESTEP_BUS,//公交 ESTEP_COACH,//大巴 ESTEP_DRIVING,//驾车 ESTEP_PLANE,//飞机 ESTEP_TRAIN,//火车 ESTEP_WALK//步行 ); // TPriceInfo = record TicketPrice:Double;//获取票价格(元) TicketType:Integer;//获取票类型 end; //路段类型枚举 TTransitRouteStepType = ( BUSLINE,//公交路段 SUBWAY,//地铁路段 WAKLING//路行路段 ); //路线换乘方案里的交通工具信息 //交通工具包括: 公交,地铁 TVehicleInfo = record PassStationNum:Integer;//该交通路线的所乘站数 Title:String;//该交通路线的名称 TotalPrice:string;//该交通路线的全程价格 Uid:string;//该交通路线的标识 ZonePrice:Double;//该交通路线的所乘区间的区间价格 end; TTransitResultNode = record CityId:Integer;//城市编号 CityName:String;//城市名 Location:TMapCoordinate;//坐标 SearchWord:string;//检索时关键字(在检索词模糊,返回建议列表时才有。 end; // 错误类型转换 {$IFDEF Android} function CreateErrorNo(error:JSearchResult_ERRORNO):TSearchResult_ERRORNO; {$ENDIF} {$IFDEF iOS} function CreateErrorNo(error:BMKSearchErrorCode):TSearchResult_ERRORNO; {$ENDIF} implementation {$IFDEF Android} function CreateErrorNo(error:JSearchResult_ERRORNO):TSearchResult_ERRORNO; begin Result:= TSearchResult_ERRORNO.NO_ERROR; if error = TJSearchResult_ERRORNO.JavaClass.NO_ERROR then Result:=TSearchResult_ERRORNO.NO_ERROR else if error = TJSearchResult_ERRORNO.JavaClass.RESULT_NOT_FOUND then Result:=TSearchResult_ERRORNO.RESULT_NOT_FOUND else if error = TJSearchResult_ERRORNO.JavaClass.AMBIGUOUS_KEYWORD then Result:=TSearchResult_ERRORNO.AMBIGUOUS_KEYWORD else if error = TJSearchResult_ERRORNO.JavaClass.AMBIGUOUS_ROURE_ADDR then Result:=TSearchResult_ERRORNO.AMBIGUOUS_ROURE_ADDR else if error = TJSearchResult_ERRORNO.JavaClass.NOT_SUPPORT_BUS then Result:=TSearchResult_ERRORNO.NOT_SUPPORT_BUS else if error = TJSearchResult_ERRORNO.JavaClass.NOT_SUPPORT_BUS_2CITY then Result:=TSearchResult_ERRORNO.NOT_SUPPORT_BUS_2CITY else if error = TJSearchResult_ERRORNO.JavaClass.ST_EN_TOO_NEAR then Result:=TSearchResult_ERRORNO.ST_EN_TOO_NEAR else if error = TJSearchResult_ERRORNO.JavaClass.KEY_ERROR then Result:=TSearchResult_ERRORNO.KEY_ERROR else if error = TJSearchResult_ERRORNO.JavaClass.PERMISSION_UNFINISHED then Result:=TSearchResult_ERRORNO.PERMISSION_UNFINISHED else if error = TJSearchResult_ERRORNO.JavaClass.NETWORK_TIME_OUT then Result:=TSearchResult_ERRORNO.NETWORK_TIME_OUT else if error = TJSearchResult_ERRORNO.JavaClass.NETWORK_ERROR then Result:=TSearchResult_ERRORNO.NETWORK_ERROR else if error = TJSearchResult_ERRORNO.JavaClass.POIINDOOR_BID_ERROR then Result:=TSearchResult_ERRORNO.POIINDOOR_BID_ERROR else if error = TJSearchResult_ERRORNO.JavaClass.POIINDOOR_FLOOR_ERROR then Result:=TSearchResult_ERRORNO.POIINDOOR_FLOOR_ERROR else if error = TJSearchResult_ERRORNO.JavaClass.POIINDOOR_SERVER_ERROR then Result:=TSearchResult_ERRORNO.POIINDOOR_SERVER_ERROR else if error = TJSearchResult_ERRORNO.JavaClass.INDOOR_ROUTE_NO_IN_BUILDING then Result:=TSearchResult_ERRORNO.INDOOR_ROUTE_NO_IN_BUILDING else if error = TJSearchResult_ERRORNO.JavaClass.INDOOR_ROUTE_NO_IN_SAME_BUILDING then Result:=TSearchResult_ERRORNO.INDOOR_ROUTE_NO_IN_SAME_BUILDING else if error = TJSearchResult_ERRORNO.JavaClass.MASS_TRANSIT_SERVER_ERROR then Result:=TSearchResult_ERRORNO.MASS_TRANSIT_SERVER_ERROR else if error = TJSearchResult_ERRORNO.JavaClass.MASS_TRANSIT_OPTION_ERROR then Result:=TSearchResult_ERRORNO.MASS_TRANSIT_OPTION_ERROR else if error = TJSearchResult_ERRORNO.JavaClass.MASS_TRANSIT_NO_POI_ERROR then Result:=TSearchResult_ERRORNO.MASS_TRANSIT_NO_POI_ERROR else if error = TJSearchResult_ERRORNO.JavaClass.SEARCH_SERVER_INTERNAL_ERROR then Result:=TSearchResult_ERRORNO.SEARCH_SERVER_INTERNAL_ERROR else if error = TJSearchResult_ERRORNO.JavaClass.SEARCH_OPTION_ERROR then Result:=TSearchResult_ERRORNO.SEARCH_OPTION_ERROR; end; {$ENDIF} {$IFDEF iOS} function CreateErrorNo(error:BMKSearchErrorCode):TSearchResult_ERRORNO; begin case error of BMK_SEARCH_NO_ERROR: Result:=TSearchResult_ERRORNO.NO_ERROR; BMK_SEARCH_AMBIGUOUS_KEYWORD: Result:=TSearchResult_ERRORNO.AMBIGUOUS_KEYWORD; BMK_SEARCH_AMBIGUOUS_ROURE_ADDR: Result:=TSearchResult_ERRORNO.AMBIGUOUS_ROURE_ADDR; BMK_SEARCH_NOT_SUPPORT_BUS: Result:=TSearchResult_ERRORNO.NOT_SUPPORT_BUS; BMK_SEARCH_NOT_SUPPORT_BUS_2CITY: Result:=TSearchResult_ERRORNO.NOT_SUPPORT_BUS_2CITY; BMK_SEARCH_RESULT_NOT_FOUND: Result:=TSearchResult_ERRORNO.RESULT_NOT_FOUND; BMK_SEARCH_ST_EN_TOO_NEAR: Result:=TSearchResult_ERRORNO.ST_EN_TOO_NEAR; BMK_SEARCH_KEY_ERROR: Result:=TSearchResult_ERRORNO.KEY_ERROR; BMK_SEARCH_NETWOKR_ERROR: Result:=TSearchResult_ERRORNO.NETWORK_ERROR; BMK_SEARCH_NETWOKR_TIMEOUT: Result:=TSearchResult_ERRORNO.NETWORK_TIME_OUT; BMK_SEARCH_PERMISSION_UNFINISHED: Result:=TSearchResult_ERRORNO.PERMISSION_UNFINISHED; BMK_SEARCH_INDOOR_ID_ERROR: Result:=TSearchResult_ERRORNO.POIINDOOR_BID_ERROR; BMK_SEARCH_FLOOR_ERROR: Result:=TSearchResult_ERRORNO.POIINDOOR_FLOOR_ERROR; BMK_SEARCH_INDOOR_ROUTE_NO_IN_BUILDING: Result:=TSearchResult_ERRORNO.INDOOR_ROUTE_NO_IN_BUILDING; BMK_SEARCH_INDOOR_ROUTE_NO_IN_SAME_BUILDING: Result:=TSearchResult_ERRORNO.INDOOR_ROUTE_NO_IN_SAME_BUILDING; BMK_SEARCH_PARAMETER_ERROR: Result:=TSearchResult_ERRORNO.REQUEST_ERROR; end; end; {$ENDIF} end.
unit ColorTableMgr; // Color Translation Tables Manager. Copyright (c) 1998 Jorge Romero Gomez, Merchise. interface uses Windows, SysUtils, Gdi, ColorTrans, MemUtils, ListUtils; // TPaletteInfo type TTransTableStates = ( tsMixMatrixValid, tsHiColor555TableValid, tsHiColor565TableValid, tsHiColorUnpackTableValid, tsTrueColorTableValid ); TTransTableState = set of TTransTableStates; type TPaletteInfo = class; FColorFilter = function( Palette : TPaletteInfo; Data : array of const ) : PRgbPalette; TPaletteInfo = class protected fCount : integer; fRgbPalette : PRgbPalette; fMixMatrix : PColorMixMatrix; fHiColor555Table : PColorTransTableHi; fHiColor565Table : PColorTransTableHi; fHiColorUnpackTable : PColorTransTableTrue; fTrueColorTable : PColorTransTableTrue; fOwned : boolean; fState : TTransTableState; procedure Release; public property Count : integer read fCount; property RgbPalette : PRgbPalette read fRgbPalette; property Owned : boolean read fOwned write fOwned default false; property State : TTransTableState read fState; property MixMatrix : PColorMixMatrix read fMixMatrix; property HiColor555Table : PColorTransTableHi read fHiColor555Table; property HiColor565Table : PColorTransTableHi read fHiColor565Table; property HiColorUnpackTable : PColorTransTableTrue read fHiColorUnpackTable; property TrueColorTable : PColorTransTableTrue read fTrueColorTable; constructor Create; destructor Destroy; override; procedure AttachPalette( const aRgbPalette : PRgbPalette; aCount : integer ); procedure RequiredState( const ReqState : TTransTableState ); procedure UpdateTables; public procedure FilterPalette( Filter : FColorFilter; Data : array of const ); function FilteredPalette( Filter : FColorFilter; Data : array of const ) : TPaletteInfo; end; // TFilterManager type TFilterManager = class protected fFilters : TPointerHash; function GetFilter( const Name : string ) : FColorFilter; function GetFilterIndex( const Name : string ) : integer; function GetFilterByIndex( Indx : integer ) : FColorFilter; public constructor Create; virtual; destructor Destroy; override; procedure Register( const Name : string; aFilter : FColorFilter ); public property Filter[ const Name : string ] : FColorFilter read GetFilter; default; property FilterIndex[ const Name : string ] : integer read GetFilterIndex; property FilterByIndex[ Indx : integer ] : FColorFilter read GetFilterByIndex; end; // TPaletteInfoManager type TPaletteInfoManager = class protected fPaletteData : TObjectList; public property Items : TObjectList read fPaletteData; constructor Create; destructor Destroy; override; function FindByPalette( const Value : PRgbPalette ) : TPaletteInfo; function AddPalette( const Value : PRgbPalette; aCount : integer ) : TPaletteInfo; end; implementation // TFilterManager constructor TFilterManager.Create; begin inherited; fFilters := TPointerHash.Create; end; destructor TFilterManager.Destroy; begin fFilters.Free; inherited; end; function TFilterManager.GetFilterIndex( const Name : string ) : integer; begin Result := fFilters.IndexOf( Name ); assert( Result >= 0, 'Filter ''' + Name + ''' has not been registered in ColorTableMgr.TFilterManager.GetFilterIndex!!' ); end; function TFilterManager.GetFilterByIndex( Indx : integer ) : FColorFilter; begin Result := fFilters.Values[Indx]; assert( Assigned( Result ), 'Filter ' + IntToStr( Indx ) + ' has not been registered in ColorTableMgr.TFilterManager.GetFilter!!' ); end; function TFilterManager.GetFilter( const Name : string ) : FColorFilter; begin Result := fFilters[Name]; assert( Assigned( Result ), 'Filter ''' + Name + ''' has not been registered in ColorTableMgr.TFilterManager.GetFilter!!' ); end; procedure TFilterManager.Register( const Name : string; aFilter : FColorFilter ); begin fFilters[ Name ] := pointer( @aFilter ); end; // TPaletteInfo procedure TPaletteInfo.FilterPalette( Filter : FColorFilter; Data : array of const ); var tRgbPalette : PRgbPalette; bakOwned : boolean; begin tRgbPalette := Filter( Self, Data ); try bakOwned := Owned; Owned := false; Release; Move( tRgbPalette^, fRgbPalette^, Count * sizeof( fRgbPalette[0] ) ); Owned := bakOwned; finally freemem( tRgbPalette ); end; end; function TPaletteInfo.FilteredPalette( Filter : FColorFilter; Data : array of const ) : TPaletteInfo; var tRgbPalette : PRgbPalette; begin tRgbPalette := Filter( Self, Data ); Result := TPaletteInfo.Create; Result.AttachPalette( tRgbPalette, Count ); Result.Owned := true; end; procedure TPaletteInfo.Release; begin FreePtr( fMixMatrix ); FreePtr( fHiColor555Table ); FreePtr( fHiColor565Table ); FreePtr( fHiColorUnpackTable ); FreePtr( fTrueColorTable ); if Owned then FreePtr( fRgbPalette ); fState := []; end; constructor TPaletteInfo.Create; begin inherited; end; destructor TPaletteInfo.Destroy; begin Release; inherited; end; procedure TPaletteInfo.AttachPalette( const aRgbPalette : PRgbPalette; aCount : integer ); begin Release; fRgbPalette := aRgbPalette; fCount := aCount; end; procedure TPaletteInfo.RequiredState( const ReqState : TTransTableState ); var NeededState : TTransTableState; begin NeededState := ReqState - State; if NeededState <> [] then begin assert( Assigned( fRgbPalette ), 'Palette not assigned yet in ColorTableMgr.TPaletteInfo.RequiredState!!' ); if (tsHiColorUnpackTableValid in NeededState) and (fHiColorUnpackTable = nil) then fHiColorUnpackTable := ColorTrans.Tab8toHiColorUnpacked( RgbPalette^, Count, 0, 0, 0 ); if (tsHiColor555TableValid in NeededState) and (fHiColor555Table = nil) then fHiColor555Table := ColorTrans.Tab8toHiColor( RgbPalette^, Count, $7c00, $03e0, $001f ); if (tsHiColor565TableValid in NeededState) and (fHiColor565Table = nil) then fHiColor565Table := ColorTrans.Tab8toHiColor( RgbPalette^, Count, $f800, $07e0, $001f ); if (tsTrueColorTableValid in NeededState) and (fTrueColorTable = nil) then fTrueColorTable := ColorTrans.Tab8toTrueColor( RgbPalette^, Count, 0, 0, 0 ); fState := fState + NeededState; end; end; procedure TPaletteInfo.UpdateTables; begin if (tsHiColorUnpackTableValid in fState) and (fHiColorUnpackTable <> nil) then ColorTrans.Tab8toHiColorUnpackedInPlace( RgbPalette^, Count, fHiColorUnpackTable^, 0, 0, 0 ); if (tsHiColor555TableValid in fState) and (fHiColor555Table <> nil) then ColorTrans.Tab8toHiColorInPlace( RgbPalette^, Count, fHiColor555Table^, 0, 0, 0 ); if (tsHiColor565TableValid in fState) and (fHiColor565Table <> nil) then ColorTrans.Tab8toHiColorInPlace( RgbPalette^, Count, fHiColor565Table^, 0, 0, 0 ); if (tsTrueColorTableValid in fState) and (fTrueColorTable <> nil) then ColorTrans.Tab8toTrueColorInPlace( RgbPalette^, Count, fTrueColorTable^, 0, 0, 0 ); end; // TPaletteInfoManager constructor TPaletteInfoManager.Create; begin inherited; fPaletteData := TObjectList.Create; end; destructor TPaletteInfoManager.Destroy; begin fPaletteData.Free; inherited; end; function TPaletteInfoManager.FindByPalette( const Value : PRgbPalette ) : TPaletteInfo; var i : integer; begin with Items do begin i := 0; while ( i < Count ) and ( TPaletteInfo( Items[i] ).RgbPalette <> Value ) do inc( i ); if i < Count then Result := TPaletteInfo( Items[i] ) else Result := nil; end; end; function TPaletteInfoManager.AddPalette( const Value : PRgbPalette; aCount : integer ) : TPaletteInfo; begin Result := FindByPalette( Value ); if not Assigned( Result ) then begin Result := TPaletteInfo.Create; Result.AttachPalette( Value, aCount ); Items.Add( Result ); end; end; (* procedure TBufferPalette.CreateMixTable( Alpha : integer ); var RgbEntries : TRgbPalette; begin with Palette do begin LogToRgbEntries( 0, NumberOfEntries, Entries, RgbEntries ); MixTable := MixColors( RgbEntries, NumberOfEntries, Alpha ); fMixTableOwned := true; end; end; *) end.
unit RouteActionsUnit; interface uses SysUtils, BaseActionUnit, DataObjectUnit, RouteParametersUnit, AddressUnit, AddressesOrderInfoUnit, RouteParametersQueryUnit, AddOrderToRouteRequestUnit, CommonTypesUnit, NullableBasicTypesUnit, EnumsUnit; type TRouteActions = class(TBaseAction) private function GetRouteId(OptimizationProblemId: NullableString; out ErrorString: String): NullableString; public function Resequence(AddressesOrderInfo: TAddressesOrderInfo; out ErrorString: String): TDataObjectRoute; procedure ResequenceAll(RouteId: String; DisableOptimization: boolean; WhatOptimize: TOptimize; out ErrorString: String); /// <summary> /// Add address(es) into a route. /// </summary> /// <param name="RouteId"> Route ID </param> /// <param name="Addresses"> Valid array of Address objects. </param> /// <param name="OptimalPosition"> If true, an address will be inserted at optimal position of a route </param> /// <param name="ErrorString"> out: Error as string </param> /// <returns> IDs of added addresses </returns> function AddAddresses(RouteId: String; Addresses: TAddressesArray; OptimalPosition: boolean; out ErrorString: String): TArray<integer>; /// <summary> /// Insert an existing order into an existing route. /// </summary> function AddOrder(RouteId: String; RouteParameters: TRouteParameters; Addresses: TOrderedAddressArray; out ErrorString: String): TDataObjectRoute; function Remove(RouteId: String; DestinationId: integer; out ErrorString: String): boolean; function Update(RouteParameters: TRouteParametersQuery; out ErrorString: String): TDataObjectRoute; procedure UpdateCustomFields(RouteId: String; RouteDestinationId: integer; CustomFields: TListStringPair; out ErrorString: String); function MoveDestinationToRoute(ToRouteId: String; RouteDestinationId, AfterDestinationId: integer; out ErrorString: String): boolean; function Get(RouteId: String; GetRouteDirections, GetRoutePathPoints: boolean; out ErrorString: String): TDataObjectRoute; overload; function GetList(Limit, Offset: integer; out ErrorString: String): TDataObjectRouteList; overload; /// <summary> /// Search for the specified text throughout all routes belonging to the userís account. /// </summary> function GetList(Text: String; out ErrorString: String): TDataObjectRouteList; overload; function Delete(RouteIds: TStringArray; out ErrorString: String): TStringArray; function Duplicate(QueryParameters: TRouteParametersQuery; out ErrorString: String): NullableString; /// <summary> /// Share a route via email. /// </summary> procedure Share(RouteId: String; RecipientEmail: String; out ErrorString: String); procedure Merge(RouteIds: TStringArray; out ErrorString: String); end; implementation { TRouteActions } uses System.Generics.Collections, SettingsUnit, RemoveRouteDestinationResponseUnit, RemoveRouteDestinationRequestUnit, AddRouteDestinationRequestUnit, MoveDestinationToRouteResponseUnit, GenericParametersUnit, DeleteRouteResponseUnit, DuplicateRouteResponseUnit, StatusResponseUnit, MergeRouteRequestUnit, UpdateRoutesCustomDataRequestUnit, ErrorResponseUnit, ResequenceAllRoutesRequestUnit; function TRouteActions.AddAddresses(RouteId: String; Addresses: TAddressesArray; OptimalPosition: boolean; out ErrorString: String): TArray<integer>; var Request: TAddRouteDestinationRequest; Response: TDataObject; Address, AddressResponse: TAddress; DestinationIds: TList<integer>; begin Result := TArray<integer>.Create(); Request := TAddRouteDestinationRequest.Create; try Request.RouteId := RouteId; Request.Addresses := Addresses; Request.OptimalPosition := OptimalPosition; Response := FConnection.Put(TSettings.EndPoints.Route, Request, TDataObject, ErrorString) as TDataObject; if (Response = nil) then Exit; DestinationIds := TList<integer>.Create; try for Address in Addresses do for AddressResponse in Response.Addresses do if (AddressResponse.AddressString = Address.AddressString) and (AddressResponse.Latitude = Address.Latitude) and (AddressResponse.Longitude = Address.Longitude) and (AddressResponse.RouteDestinationId.IsNotNull) then begin DestinationIds.Add(AddressResponse.RouteDestinationId); Break; end; Result := DestinationIds.ToArray; finally FreeAndNil(DestinationIds); FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TRouteActions.AddOrder(RouteId: String; RouteParameters: TRouteParameters; Addresses: TOrderedAddressArray; out ErrorString: String): TDataObjectRoute; var Parameters: TAddOrderToRouteRequest; i: integer; begin Parameters := TAddOrderToRouteRequest.Create; try Parameters.RouteId := RouteId; Parameters.Redirect := False; Parameters.Parameters := RouteParameters; for i := 0 to High(Addresses) do Parameters.AddAddress(Addresses[i]); Result := FConnection.Put(TSettings.EndPoints.Route, Parameters, TDataObjectRoute, ErrorString) as TDataObjectRoute; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Order to a Route not added'; finally FreeAndNil(Parameters); end; end; function TRouteActions.Delete(RouteIds: TStringArray; out ErrorString: String): TStringArray; var RouteIdsAsString: String; RouteId: String; Parameters: TGenericParameters; Response: TDeleteRouteResponse; begin SetLength(Result, 0); RouteIdsAsString := EmptyStr; for RouteId in RouteIds do begin if (RouteIdsAsString.Length > 0) then RouteIdsAsString := RouteIdsAsString + ','; RouteIdsAsString := RouteIdsAsString + RouteId; end; Parameters := TGenericParameters.Create; try Parameters.AddParameter('route_id', RouteIdsAsString); Response := FConnection.Delete(TSettings.EndPoints.Route, Parameters, TDeleteRouteResponse, ErrorString) as TDeleteRouteResponse; if (Response <> nil) then Result := Response.RouteIds; finally FreeAndNil(Parameters); end; end; function TRouteActions.Duplicate(QueryParameters: TRouteParametersQuery; out ErrorString: String): NullableString; var Response: TDuplicateRouteResponse; begin Result := NullableString.Null; QueryParameters.ReplaceParameter('to', 'none'); // Redirect to page or return json for none Response := FConnection.Get(TSettings.EndPoints.DuplicateRoute, QueryParameters, TDuplicateRouteResponse, ErrorString) as TDuplicateRouteResponse; try if (Response <> nil) and (Response.Success) then Result := GetRouteId(Response.OptimizationProblemId, ErrorString); finally FreeAndNil(Response); end; end; function TRouteActions.Get(RouteId: String; GetRouteDirections, GetRoutePathPoints: boolean; out ErrorString: String): TDataObjectRoute; var RouteParameters: TRouteParametersQuery; begin RouteParameters := TRouteParametersQuery.Create; try RouteParameters.RouteId := RouteId; if (GetRouteDirections) then RouteParameters.Directions := True; if (GetRoutePathPoints) then RouteParameters.RoutePathOutput := TRoutePathOutput.rpoPoints; Result := FConnection.Get(TSettings.EndPoints.Route, RouteParameters, TDataObjectRoute, ErrorString) as TDataObjectRoute; finally FreeAndNil(RouteParameters); end; end; function TRouteActions.GetList(Text: String; out ErrorString: String): TDataObjectRouteList; var RouteParameters: TGenericParameters; begin RouteParameters := TGenericParameters.Create; try RouteParameters.AddParameter('query', Text); Result := FConnection.Get(TSettings.EndPoints.Route, RouteParameters, TDataObjectRouteList, ErrorString) as TDataObjectRouteList; finally FreeAndNil(RouteParameters); end; end; function TRouteActions.GetList(Limit, Offset: integer; out ErrorString: String): TDataObjectRouteList; var RouteParameters: TRouteParametersQuery; begin RouteParameters := TRouteParametersQuery.Create; try RouteParameters.Limit := Limit; RouteParameters.Offset := Offset; Result := FConnection.Get(TSettings.EndPoints.Route, RouteParameters, TDataObjectRouteList, ErrorString) as TDataObjectRouteList; finally FreeAndNil(RouteParameters); end; end; function TRouteActions.GetRouteId(OptimizationProblemId: NullableString; out ErrorString: String): NullableString; var GenericParameters: TGenericParameters; Response: TDataObject; begin Result := NullableString.Null; if OptimizationProblemId.IsNull then Exit; GenericParameters := TGenericParameters.Create(); try GenericParameters.AddParameter('optimization_problem_id', OptimizationProblemId); GenericParameters.AddParameter('wait_for_final_state', '1'); Response := FConnection.Get(TSettings.EndPoints.Optimization, GenericParameters, TDataObject, ErrorString) as TDataObject; try if (Response <> nil) and (Length(Response.Routes) > 0) then Result := Response.Routes[0].RouteID; finally FreeAndNil(Response); end; finally FreeAndNil(GenericParameters); end; end; procedure TRouteActions.Merge(RouteIds: TStringArray; out ErrorString: String); var Request: TMergeRouteRequest; Response: TStatusResponse; begin Request := TMergeRouteRequest.Create; try Request.RouteIds := RouteIds; Response := FConnection.Post(TSettings.EndPoints.MergeRouteEndPoint, Request, TStatusResponse, ErrorString) as TStatusResponse; try if (Response <> nil) and (Response.Status = False) and (ErrorString = EmptyStr) then ErrorString := 'Rotes not merged'; finally FreeAndNil(Response); end; finally FreeAndnil(Request); end; end; function TRouteActions.MoveDestinationToRoute(ToRouteId: String; RouteDestinationId, AfterDestinationId: integer; out ErrorString: String): boolean; var Response: TMoveDestinationToRouteResponse; Request: TGenericParameters; begin Request := TGenericParameters.Create; try Request.AddBodyParameter('to_route_id', ToRouteId); Request.AddBodyParameter('route_destination_id', IntToStr(RouteDestinationId)); Request.AddBodyParameter('after_destination_id', IntToStr(AfterDestinationId)); Response := FConnection.Post(TSettings.EndPoints.MoveRouteDestination, Request, TMoveDestinationToRouteResponse, ErrorString) as TMoveDestinationToRouteResponse; try if (Response <> nil) then begin if (not Response.Success) and (Response.Error <> EmptyStr) then ErrorString := Response.Error; Result := Response.Success; end else Result := False; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TRouteActions.Remove(RouteId: String; DestinationId: integer; out ErrorString: String): boolean; var Request: TRemoveRouteDestinationRequest; Response: TRemoveRouteDestinationResponse; begin Request := TRemoveRouteDestinationRequest.Create; try Request.RouteId := RouteId; Request.RouteDestinationId := destinationId; Response := FConnection.Delete(TSettings.EndPoints.GetAddress, Request, TRemoveRouteDestinationResponse, ErrorString) as TRemoveRouteDestinationResponse; try Result := (Response <> nil) and (Response.Deleted); finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TRouteActions.Resequence(AddressesOrderInfo: TAddressesOrderInfo; out ErrorString: String): TDataObjectRoute; begin Result := FConnection.Put(TSettings.EndPoints.Route, AddressesOrderInfo, TDataObjectRoute, ErrorString) as TDataObjectRoute; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Route not re-sequenced'; end; procedure TRouteActions.ResequenceAll(RouteId: String; DisableOptimization: boolean; WhatOptimize: TOptimize; out ErrorString: String); var Request: TResequenceAllRoutesRequest; Response: TStatusResponse; begin Request := TResequenceAllRoutesRequest.Create(RouteId, DisableOptimization, WhatOptimize); try Response := FConnection.Get(TSettings.EndPoints.ResequenceRoute, Request, TStatusResponse, ErrorString) as TStatusResponse; try if (Response <> nil) and (Response.Status = False) and (ErrorString = EmptyStr) then ErrorString := 'Routes not resequenced'; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; procedure TRouteActions.Share(RouteId, RecipientEmail: String; out ErrorString: String); var Request: TGenericParameters; Response: TStatusResponse; begin Request := TGenericParameters.Create; try Request.AddParameter('route_id', RouteId); Request.AddParameter('response_format', TOptimizationParametersFormatDescription[opJson]); Request.AddBodyParameter('recipient_email', RecipientEmail); Response := FConnection.Post(TSettings.EndPoints.ShareRoute, Request, TStatusResponse, ErrorString) as TStatusResponse; try if (Response <> nil) and (Response.Status = False) and (ErrorString = EmptyStr) then ErrorString := 'Rote not shared'; finally FreeAndNil(Response); end; finally FreeAndnil(Request); end; end; procedure TRouteActions.UpdateCustomFields(RouteId: String; RouteDestinationId: integer; CustomFields: TListStringPair; out ErrorString: String); var Request: TUpdateRoutesCustomDataRequest; Pair: TStringPair; Address: TAddress; begin Request := TUpdateRoutesCustomDataRequest.Create; try Request.RouteId := RouteId; Request.RouteDestinationId := RouteDestinationId; for Pair in CustomFields do Request.AddCustomField(Pair.Key, Pair.Value); Address := FConnection.Put(TSettings.EndPoints.GetAddress, Request, TAddress, ErrorString) as TAddress; try if (Address = nil) and (ErrorString = EmptyStr) then ErrorString := 'Custom data of the route destinations not updated'; finally FreeAndNil(Address); end; finally FreeAndNil(Request); end; end; function TRouteActions.Update(RouteParameters: TRouteParametersQuery; out ErrorString: String): TDataObjectRoute; begin Result := FConnection.Put(TSettings.EndPoints.Route, RouteParameters, TDataObjectRoute, errorString) as TDataObjectRoute; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Route not updated'; 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 ClpISO10126d2Padding; {$I ..\..\Include\CryptoLib.inc} interface uses ClpIBlockCipherPadding, ClpIISO10126d2Padding, ClpSecureRandom, ClpISecureRandom, ClpCryptoLibTypes; resourcestring SCorruptedPadBlock = 'Pad Block Corrupted'; type /// <summary> /// A padder that adds ISO10126-2 padding to a block. /// </summary> TISO10126d2Padding = class sealed(TInterfacedObject, IISO10126d2Padding, IBlockCipherPadding) strict private var FRandom: ISecureRandom; /// <returns> /// return the name of the algorithm the cipher implements. /// </returns> function GetPaddingName: String; inline; public /// <summary> /// Initialise the padder. /// </summary> /// <param name="random"> /// a SecureRandom if available. /// </param> procedure Init(const random: ISecureRandom); /// <summary> /// Return the name of the algorithm the cipher implements. /// </summary> property PaddingName: String read GetPaddingName; /// <summary> /// add the pad bytes to the passed in block, returning the number of /// bytes added. /// </summary> /// <param name="input"> /// input block to pad /// </param> /// <param name="inOff"> /// offset to start the padding from in the block /// </param> /// <returns> /// returns number of bytes added /// </returns> function AddPadding(const input: TCryptoLibByteArray; inOff: Int32): Int32; /// <summary> /// return the number of pad bytes present in the block. /// </summary> /// <param name="input"> /// block to count pad bytes in /// </param> /// <returns> /// the number of pad bytes present in the block. /// </returns> /// <exception cref="EInvalidCipherTextCryptoLibException"> /// if the padding is badly formed or invalid. /// </exception> function PadCount(const input: TCryptoLibByteArray): Int32; end; implementation { TISO10126d2Padding } function TISO10126d2Padding.AddPadding(const input: TCryptoLibByteArray; inOff: Int32): Int32; var code: Byte; begin code := Byte(System.Length(input) - inOff); while (inOff < (System.Length(input) - 1)) do begin input[inOff] := Byte(FRandom.NextInt32); System.Inc(inOff); end; input[inOff] := code; result := code; end; function TISO10126d2Padding.GetPaddingName: String; begin result := 'ISO10126-2'; end; procedure TISO10126d2Padding.Init(const random: ISecureRandom); begin if random <> Nil then begin FRandom := random; end else begin FRandom := TSecureRandom.Create(); end; end; function TISO10126d2Padding.PadCount(const input: TCryptoLibByteArray): Int32; var count: Int32; begin count := input[System.Length(input) - 1] and $FF; if (count > System.Length(input)) then begin raise EInvalidCipherTextCryptoLibException.CreateRes(@SCorruptedPadBlock); end; result := count; end; end.
// Wave files low level structure. Copyright Merchise Group [PastelCAD] unit WaveLow; interface uses Classes; type TWavFormat = packed record fID : longint; // fmt fLen : longint; // Data length fmtTag : word; // 1 = PCM ... nChannels : word; nSamplesPerSec : longint; nAvgBytesPerSec : longint; nBlockAlign : word; // nChannels * (nBitsPerSample div 8) FormatSpecific : word; // Bits per sample end; PWaveDataChunk = ^TWaveDataChunk; TWaveDataChunk = packed record dID : longint; // "data" dLen : longint; // data length + sizeof(TWaveDataChunk) { here comes Data } end; TWavData = packed record wID : longint; // "WAVE" Format : TWavFormat; Chunk : TWaveDataChunk; end; TWavFileFormat = packed record rID : longint; // "RIFF" rLen : longint; // Length of the data in the next chunk rData : TWavData; // rLen bytes length end; // All mixed PWaveHeader = ^TWaveHeader; TWaveHeader = packed record rID : longint; // "RIFF" rLen : longint; // Length of the data in the next chunk // Wave chunk wID : longint; // "WAVE" fID : longint; // fmt fLen : longint; // Data length fmtTag : word; // 1 = PCM ... nChannels : word; nSamplesPerSec : longint; nAvgBytesPerSec : longint; nBlockAlign : word; // nChannels * (nBitsPerSample div 8) nBitsPerSample : word; // Bits per sample end; const s_RIFF : longint = $46464952; s_WAVE : longint = $45564157; s_fmt : longint = $20746D66; s_data : longint = $61746164; function GetDataFromBuffer(aBuffer : pointer; var Size : integer) : pointer; procedure GetDataFromStream(aStream : TStream; var Size : integer); implementation uses SysUtils; function GetDataFromBuffer(aBuffer : pointer; var Size : integer) : pointer; type PInteger = ^integer; var s : array[0..4] of char; Buffer : pchar absolute aBuffer; begin fillchar(s, sizeof(s), 0); while strcomp(s, 'data') <> 0 do begin move(Buffer^, s, 4); inc(Buffer); end; inc(Buffer, 3); Size := PInteger(Buffer)^; Result := Buffer + sizeof(integer); end; procedure GetDataFromStream(aStream : TStream; var Size : integer); var s : array[0..4] of char; begin fillchar(s, sizeof(s), 0); while strcomp(s, 'data') <> 0 do begin move(s[1], s[0], 3); aStream.Read(s[3], sizeof(char)); end; aStream.Read(Size, sizeof(Size)); end; end.
unit htTableQueryFactory; // Модуль: "w:\common\components\rtl\Garant\HT\htTableQueryFactory.pas" // Стереотип: "SimpleClass" // Элемент модели: "ThtTableQueryFactory" MUID: (554C7FE80228) {$Include w:\common\components\rtl\Garant\HT\htDefineDA.inc} interface uses l3IntfUses , l3ProtoObject , daInterfaces , htInterfaces , daTypes ; type ThtTableQueryFactory = class(Tl3ProtoObject, IdaTableQueryFactory) private f_DataConverter: IhtDataConverter; f_Helper: IhtDataSchemeHelper; protected function MakeTabledQuery(const aFromClause: IdaFromClause): IdaTabledQuery; function MakeSelectField(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const anAlias: AnsiString = ''): IdaSelectField; function MakeParamsCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; anOperation: TdaCompareOperation; const aParamName: AnsiString): IdaCondition; function Get_DataConverter: IdaDataConverter; function MakeLogicCondition(const aLeft: IdaCondition; anOperation: TdaLogicOperation; const aRight: IdaCondition): IdaCondition; function MakeSubQueryCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const aQuery: IdaTabledQuery): IdaCondition; function MakeSortField(const aSelectField: IdaSelectField; aSortOrder: TdaSortOrder = daTypes.da_soAscending): IdaSortField; function MakeJoin(const aLeft: IdaFromClause; const aRight: IdaFromClause; aKind: TdaJoinKind): IdaJoin; function MakeJoinCondition(const aLeftTableAlias: AnsiString; const aLeftField: IdaFieldDescription; const aRightTableAlias: AnsiString; const aRightField: IdaFieldDescription): IdaCondition; function MakeSimpleFromClause(const aTable: IdaTableDescription; const anAlias: AnsiString = ''): IdaFromClause; function MakeAggregateField(anOperation: TdaAggregateOperation; const aField: IdaSelectField; const anAlias: AnsiString): IdaSelectField; function MakeBitwiseCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; anOperation: TdaBitwiseOperator; aValue: Int64): IdaCondition; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aDataConverter: IhtDataConverter; const aHelper: IhtDataSchemeHelper); reintroduce; class function Make(const aDataConverter: IhtDataConverter; const aHelper: IhtDataSchemeHelper): IdaTableQueryFactory; reintroduce; end;//ThtTableQueryFactory implementation uses l3ImplUses , htTabledQuery , daParamsCondition , daSelectField {$If NOT Defined(Nemesis)} , dt_User {$IfEnd} // NOT Defined(Nemesis) , daLogicCondition , daSubQueryCondition , daSortField , daJoin , daJoinCondition , htFromTable , daAggregateField , daBitwiseCondition //#UC START# *554C7FE80228impl_uses* //#UC END# *554C7FE80228impl_uses* ; constructor ThtTableQueryFactory.Create(const aDataConverter: IhtDataConverter; const aHelper: IhtDataSchemeHelper); //#UC START# *554C8017020C_554C7FE80228_var* //#UC END# *554C8017020C_554C7FE80228_var* begin //#UC START# *554C8017020C_554C7FE80228_impl* inherited Create; f_DataConverter := aDataConverter; f_Helper := aHelper; //#UC END# *554C8017020C_554C7FE80228_impl* end;//ThtTableQueryFactory.Create class function ThtTableQueryFactory.Make(const aDataConverter: IhtDataConverter; const aHelper: IhtDataSchemeHelper): IdaTableQueryFactory; var l_Inst : ThtTableQueryFactory; begin l_Inst := Create(aDataConverter, aHelper); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//ThtTableQueryFactory.Make function ThtTableQueryFactory.MakeTabledQuery(const aFromClause: IdaFromClause): IdaTabledQuery; //#UC START# *5549C65D038D_554C7FE80228_var* //#UC END# *5549C65D038D_554C7FE80228_var* begin //#UC START# *5549C65D038D_554C7FE80228_impl* Result := ThtTabledQuery.Make(Self, f_DataConverter, f_Helper, aFromClause); //#UC END# *5549C65D038D_554C7FE80228_impl* end;//ThtTableQueryFactory.MakeTabledQuery function ThtTableQueryFactory.MakeSelectField(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const anAlias: AnsiString = ''): IdaSelectField; //#UC START# *559B80BD00A8_554C7FE80228_var* //#UC END# *559B80BD00A8_554C7FE80228_var* begin //#UC START# *559B80BD00A8_554C7FE80228_impl* Result := TdaSelectField.Make(aTableAlias, aField, anAlias); //#UC END# *559B80BD00A8_554C7FE80228_impl* end;//ThtTableQueryFactory.MakeSelectField function ThtTableQueryFactory.MakeParamsCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; anOperation: TdaCompareOperation; const aParamName: AnsiString): IdaCondition; //#UC START# *559B810003CF_554C7FE80228_var* //#UC END# *559B810003CF_554C7FE80228_var* begin //#UC START# *559B810003CF_554C7FE80228_impl* Result := TdaParamsCondition.Make(aTableAlias, aField, anOperation, aParamName); //#UC END# *559B810003CF_554C7FE80228_impl* end;//ThtTableQueryFactory.MakeParamsCondition function ThtTableQueryFactory.Get_DataConverter: IdaDataConverter; //#UC START# *55C1BFA402E3_554C7FE80228get_var* //#UC END# *55C1BFA402E3_554C7FE80228get_var* begin //#UC START# *55C1BFA402E3_554C7FE80228get_impl* Result := f_DataConverter; //#UC END# *55C1BFA402E3_554C7FE80228get_impl* end;//ThtTableQueryFactory.Get_DataConverter function ThtTableQueryFactory.MakeLogicCondition(const aLeft: IdaCondition; anOperation: TdaLogicOperation; const aRight: IdaCondition): IdaCondition; //#UC START# *56405475021D_554C7FE80228_var* //#UC END# *56405475021D_554C7FE80228_var* begin //#UC START# *56405475021D_554C7FE80228_impl* Result := TdaLogicCondition.Make(aLeft, anOperation, aRight); //#UC END# *56405475021D_554C7FE80228_impl* end;//ThtTableQueryFactory.MakeLogicCondition function ThtTableQueryFactory.MakeSubQueryCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const aQuery: IdaTabledQuery): IdaCondition; //#UC START# *5641E5DB02C3_554C7FE80228_var* //#UC END# *5641E5DB02C3_554C7FE80228_var* begin //#UC START# *5641E5DB02C3_554C7FE80228_impl* Result := TdaSubQueryCondition.Make(aTableALias, aField, aQuery); //#UC END# *5641E5DB02C3_554C7FE80228_impl* end;//ThtTableQueryFactory.MakeSubQueryCondition function ThtTableQueryFactory.MakeSortField(const aSelectField: IdaSelectField; aSortOrder: TdaSortOrder = daTypes.da_soAscending): IdaSortField; //#UC START# *56811844032C_554C7FE80228_var* //#UC END# *56811844032C_554C7FE80228_var* begin //#UC START# *56811844032C_554C7FE80228_impl* Result := TdaSortField.Make(aSelectField, aSortOrder); //#UC END# *56811844032C_554C7FE80228_impl* end;//ThtTableQueryFactory.MakeSortField function ThtTableQueryFactory.MakeJoin(const aLeft: IdaFromClause; const aRight: IdaFromClause; aKind: TdaJoinKind): IdaJoin; //#UC START# *574584D802F6_554C7FE80228_var* //#UC END# *574584D802F6_554C7FE80228_var* begin //#UC START# *574584D802F6_554C7FE80228_impl* Result := TdaJoin.Make(Self, aLeft, aRight, aKind); //#UC END# *574584D802F6_554C7FE80228_impl* end;//ThtTableQueryFactory.MakeJoin function ThtTableQueryFactory.MakeJoinCondition(const aLeftTableAlias: AnsiString; const aLeftField: IdaFieldDescription; const aRightTableAlias: AnsiString; const aRightField: IdaFieldDescription): IdaCondition; //#UC START# *574BF2B20123_554C7FE80228_var* //#UC END# *574BF2B20123_554C7FE80228_var* begin //#UC START# *574BF2B20123_554C7FE80228_impl* Result := TdaJoinCondition.Make(aLeftTableAlias, aLeftField, aRightTableAlias, aRightField); //#UC END# *574BF2B20123_554C7FE80228_impl* end;//ThtTableQueryFactory.MakeJoinCondition function ThtTableQueryFactory.MakeSimpleFromClause(const aTable: IdaTableDescription; const anAlias: AnsiString = ''): IdaFromClause; //#UC START# *574C32760314_554C7FE80228_var* //#UC END# *574C32760314_554C7FE80228_var* begin //#UC START# *574C32760314_554C7FE80228_impl* Result := ThtFromTable.Make(Self, aTable, anAlias); //#UC END# *574C32760314_554C7FE80228_impl* end;//ThtTableQueryFactory.MakeSimpleFromClause function ThtTableQueryFactory.MakeAggregateField(anOperation: TdaAggregateOperation; const aField: IdaSelectField; const anAlias: AnsiString): IdaSelectField; //#UC START# *5755313E0083_554C7FE80228_var* //#UC END# *5755313E0083_554C7FE80228_var* begin //#UC START# *5755313E0083_554C7FE80228_impl* Result := TdaAggregateField.Make(anOperation, aField, anAlias); //#UC END# *5755313E0083_554C7FE80228_impl* end;//ThtTableQueryFactory.MakeAggregateField function ThtTableQueryFactory.MakeBitwiseCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; anOperation: TdaBitwiseOperator; aValue: Int64): IdaCondition; //#UC START# *57A9A66C00A7_554C7FE80228_var* //#UC END# *57A9A66C00A7_554C7FE80228_var* begin //#UC START# *57A9A66C00A7_554C7FE80228_impl* Result := TdaBitwiseCondition.Make(aTableAlias, aField, anOperation, aValue); //#UC END# *57A9A66C00A7_554C7FE80228_impl* end;//ThtTableQueryFactory.MakeBitwiseCondition procedure ThtTableQueryFactory.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_554C7FE80228_var* //#UC END# *479731C50290_554C7FE80228_var* begin //#UC START# *479731C50290_554C7FE80228_impl* f_DataConverter := nil; f_Helper := nil; inherited; //#UC END# *479731C50290_554C7FE80228_impl* end;//ThtTableQueryFactory.Cleanup end.
unit SettingsPersistence; interface function GetAppDataFldPath(SubFolder: string = ''): string; function ReadSetting(Section, Name: string; Default: variant): variant; procedure WriteSetting(Section, Name: string; Value: variant); procedure DeleteSetting(Section, Name: string); // function IncludeTrailingSlash(const S: string): string; // function GetAppTempFldPath: string; // function GetAppLanguagesFldPath: string; // procedure StrToFile(const FileName, SourceString: string); // function qgURLDownloadToFile(LocalFilePathName, URL: string; out Err: string): boolean; // function JSONObjToStr(JSON: TJSONObject): string; implementation uses System.SysUtils , System.IOUtils , System.Variants , System.IniFiles , Constants; function GetAppDataFldPath(SubFolder: string = ''): string; begin Result := TPath.GetHomePath; if Result <> '' then begin Result := Result + TPath.DirectorySeparatorChar + IOT_APP_INTERNAL_NAME; SubFolder := Trim(SubFolder); if SubFolder <> '' then begin if not System.SysUtils.IsPathDelimiter(SubFolder, 1) then SubFolder := TPath.DirectorySeparatorChar + SubFolder; Result := Result + SubFolder; end; Result := System.SysUtils.IncludeTrailingPathDelimiter(Result); if not DirectoryExists(Result) then if not ForceDirectories(Result) then Result := ''; end; end; function ReadSetting(Section, Name: string; Default: variant): variant; var IniFile: TIniFile; IniFilePathName: string; begin IniFilePathName := GetAppDataFldPath + IOT_APP_INTERNAL_NAME + '.ini'; try IniFile := TIniFile.Create(IniFilePathName); try case VarType(Default) of varByte, varShortInt, varSmallint, varInteger, varWord, varLongWord, varInt64: Result := IniFile.ReadInteger(Section, Name, Default); varSingle, varDouble, varCurrency: Result := IniFile.ReadFloat(Section, Name, Default); varBoolean: Result := IniFile.ReadBool(Section, Name, Default); varStrArg, varString: Result := IniFile.ReadString(Section, Name, Default); else Result := IniFile.ReadString(Section, Name, String(Default)); end; finally IniFile.Free; end; except on E: Exception do Result := Default; end; end; procedure WriteSetting(Section, Name: string; Value: variant); var IniFile: TIniFile; IniFilePathName: string; begin IniFilePathName := GetAppDataFldPath + IOT_APP_INTERNAL_NAME + '.ini'; IniFile := TIniFile.Create(IniFilePathName); try case VarType(Value) of varByte, varShortInt, varSmallint, varInteger, varWord, varLongWord, varInt64: IniFile.WriteInteger(Section, Name, Value); varSingle, varDouble, varCurrency: IniFile.WriteFloat(Section, Name, Value); varBoolean: IniFile.WriteBool(Section, Name, Value); varStrArg, varString: IniFile.WriteString(Section, Name, Value); else IniFile.WriteString(Section, Name, Value); end; finally IniFile.Free; end; end; procedure DeleteSetting(Section, Name: string); var IniFile: TIniFile; IniFilePathName: string; begin IniFilePathName := GetAppDataFldPath + IOT_APP_INTERNAL_NAME + '.ini'; IniFile := TIniFile.Create(IniFilePathName); try IniFile.DeleteKey(Section, Name); finally IniFile.Free; end; end; { procedure StrToFile(const FileName, SourceString: string); var List: TStringList; begin List := TStringList.Create; try List.Text := SourceString; List.SaveToFile(FileName); finally List.Free; end; end; } { function JSONObjToStr(JSON: TJSONObject): string; var StringBuilder: TStringBuilder; begin Result := ''; if Assigned(JSON) then begin StringBuilder := TStringBuilder.Create; JSON.ToChars(StringBuilder); Result := StringBuilder.ToString; end; end; } { function IncludeTrailingSlash(const S: string): string; var Index: smallint; begin Result := S; if Result <> '' then begin Index := High(Result); if not ((Index >= Low(string)) and (Index <= High(Result)) and (Result[Index] = '/') and (ByteType(Result, Index) = mbSingleByte)) then Result := Result + '/'; end; end; } { function GetAppTempFldPath: string; begin Result := GetAppDataFldPath; if Result <> '' then begin Result := Result + 'temp' + TPath.DirectorySeparatorChar; if not DirectoryExists(Result) then if not ForceDirectories(Result) then Result := ''; end; end; } end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clSspiAuth; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, Windows, SysUtils, {$ELSE} System.Classes, Winapi.Windows, System.SysUtils, {$ENDIF} clSspi, clWUtils{$IFDEF LOGGER}, clLogger{$ENDIF}; type PSEC_WINNT_AUTH_IDENTITY = ^TSEC_WINNT_AUTH_IDENTITY; TSEC_WINNT_AUTH_IDENTITY = record User: PclChar; UserLength: DWORD; Domain: PclChar; DomainLength: DWORD; Password: PclChar; PasswordLength: DWORD; Flags: DWORD; end; TclAuthIdentity = class private FUser: string; FPassword: string; FDomain: string; FIdentity: TSEC_WINNT_AUTH_IDENTITY; function GetIdentity: PSEC_WINNT_AUTH_IDENTITY; procedure Clear; public constructor Create(const AUser, ADomain, APassword: string); overload; constructor Create(const AUser, APassword: string); overload; destructor Destroy; override; property User: string read FUser; property Domain: string read FDomain; property Password: string read FPassword; property Identity: PSEC_WINNT_AUTH_IDENTITY read GetIdentity; end; TclNtAuthSspi = class(TclSspi) protected FCredHandle: TCredHandle; FCtxtHandle: TCtxtHandle; procedure GenCredentialHandle(const APackage: string; ACredentialUse: DWORD; AuthIdentity: TclAuthIdentity); procedure DeleteSecHandles; public constructor Create; destructor Destroy; override; property CredHandle: TCredHandle read FCredHandle; property CtxtHandle: TCtxtHandle read FCtxtHandle; end; TclNtAuthClientSspi = class(TclNtAuthSspi) public function GenChallenge(const APackage: string; ABuffer: TStream; const ATargetName: string; AuthIdentity: TclAuthIdentity): Boolean; end; TclNtAuthServerSspi = class(TclNtAuthSspi) private FNewConversation: Boolean; public constructor Create; function GenChallenge(const APackage: string; ABuffer: TStream; AuthIdentity: TclAuthIdentity): Boolean; procedure ImpersonateUser; procedure RevertUser; end; const SEC_WINNT_AUTH_IDENTITY_ANSI = 1; {$EXTERNALSYM SEC_WINNT_AUTH_IDENTITY_ANSI} SEC_WINNT_AUTH_IDENTITY_UNICODE = 2; {$EXTERNALSYM SEC_WINNT_AUTH_IDENTITY_UNICODE} implementation { TclAuthIdentity } constructor TclAuthIdentity.Create(const AUser, ADomain, APassword: string); begin inherited Create(); FUser := AUser; FDomain := ADomain; FPassword := APassword; ZeroMemory(@FIdentity, SizeOf(FIdentity)); Clear(); end; procedure TclAuthIdentity.Clear; begin FreeMem(FIdentity.User); FIdentity.User := nil; FIdentity.UserLength := 0; FreeMem(FIdentity.Domain); FIdentity.Domain := nil; FIdentity.DomainLength := 0; FreeMem(FIdentity.Password); FIdentity.Password := nil; FIdentity.PasswordLength := 0; {$IFDEF DELPHI2009} FIdentity.Flags := SEC_WINNT_AUTH_IDENTITY_ANSI; // FIdentity.Flags := SEC_WINNT_AUTH_IDENTITY_UNICODE; it is necessary to move the securityfunction table to unicode {$ELSE} FIdentity.Flags := SEC_WINNT_AUTH_IDENTITY_ANSI; {$ENDIF} end; function TclAuthIdentity.GetIdentity: PSEC_WINNT_AUTH_IDENTITY; function AssignIdentityStr(const AIdentityStr: string): PclChar; var s: TclString; len: Integer; begin s := GetTclString(AIdentityStr); len := Length(s); GetMem(Result, len + SizeOf(TclChar)); system.Move(PclChar(s)^, Result^, len); Result[len] := #0; end; begin Result := @FIdentity; Clear(); if Length(User) > 0 then begin FIdentity.User := AssignIdentityStr(User); FIdentity.UserLength := Length(User); end; if Length(Domain) > 0 then begin FIdentity.Domain := AssignIdentityStr(Domain); FIdentity.DomainLength := Length(Domain); end; if Length(Password) > 0 then begin FIdentity.Password := AssignIdentityStr(Password); FIdentity.PasswordLength := Length(Password); end; end; constructor TclAuthIdentity.Create(const AUser, APassword: string); var ind: Integer; begin inherited Create(); ind := system.Pos('\', AUser); if (ind = 0) then begin ind := system.Pos('/', AUser); end; if (ind > 0) then begin FUser := system.Copy(AUser, ind + 1, Length(AUser)); FDomain := system.Copy(AUser, 1, ind - 1); end else begin FUser := AUser; FDomain := ''; end; FPassword := APassword; ZeroMemory(@FIdentity, SizeOf(FIdentity)); Clear(); end; destructor TclAuthIdentity.Destroy; begin Clear(); inherited Destroy(); end; { TclNtAuthSspi } procedure TclNtAuthSspi.DeleteSecHandles; begin if ((FCtxtHandle.dwLower <> 0) or (FCtxtHandle.dwUpper <> 0)) then begin FunctionTable.DeleteSecurityContext(@FCtxtHandle); end; FCtxtHandle.dwLower := 0; FCtxtHandle.dwUpper := 0; if ((FCredHandle.dwLower <> 0) or (FCredHandle.dwUpper <> 0)) then begin FunctionTable.FreeCredentialHandle(@FCredHandle); end; FCredHandle.dwLower := 0; FCredHandle.dwUpper := 0; end; procedure TclNtAuthSspi.GenCredentialHandle(const APackage: string; ACredentialUse: DWORD; AuthIdentity: TclAuthIdentity); var statusCode: SECURITY_STATUS; authData: PSEC_WINNT_AUTH_IDENTITY; tsExpiry: TTimeStamp; begin authData := nil; if (AuthIdentity <> nil) then begin authData := AuthIdentity.Identity; end; statusCode := FunctionTable.AcquireCredentialsHandle( nil, PclChar(GetTclString(APackage)), ACredentialUse, nil, authData, nil, nil, @FCredHandle, @tsExpiry); if (statusCode <> SEC_E_OK) then begin RaiseSspiError(statusCode); end; end; constructor TclNtAuthSspi.Create; begin inherited Create(); DeleteSecHandles(); end; destructor TclNtAuthSspi.Destroy; begin DeleteSecHandles(); inherited Destroy(); end; { TclNtAuthClientSspi } function TclNtAuthClientSspi.GenChallenge(const APackage: string; ABuffer: TStream; const ATargetName: string; AuthIdentity: TclAuthIdentity): Boolean; var statusCode: SECURITY_STATUS; flags, outFlags: DWORD; inBuffer: TSecBufferDesc; inBuffers: array[0..0] of TSecBuffer; outBuffer: TSecBufferDesc; outBuffers: array[0..0] of TSecBuffer; buf: PclChar; bufSize: Integer; pInBuffer: PSecBufferDesc; pCtxt: PCtxtHandle; tsExpiry: TTimeStamp; begin flags := ISC_REQ_DELEGATE + ISC_REQ_MUTUAL_AUTH + ISC_REQ_REPLAY_DETECT + ISC_REQ_SEQUENCE_DETECT + ISC_REQ_CONFIDENTIALITY + ISC_REQ_CONNECTION + ISC_REQ_INTEGRITY + ISC_REQ_ALLOCATE_MEMORY; outBuffer.ulVersion := SECBUFFER_VERSION; outBuffer.cBuffers := 1; outBuffer.pBuffers := @outBuffers; outBuffers[0].cbBuffer := 0; outBuffers[0].BufferType := SECBUFFER_TOKEN; outBuffers[0].pvBuffer := nil; buf := nil; try bufSize := ABuffer.Size - ABuffer.Position; if (bufSize > 0) then begin inBuffer.ulVersion := SECBUFFER_VERSION; inBuffer.cBuffers := 1; inBuffer.pBuffers := @inBuffers; GetMem(buf, bufSize); ABuffer.Read(buf^, bufSize); inBuffers[0].cbBuffer := bufSize; inBuffers[0].BufferType := SECBUFFER_TOKEN; inBuffers[0].pvBuffer := buf; pInBuffer := @inBuffer; pCtxt := @FCtxtHandle; end else begin DeleteSecHandles(); GenCredentialHandle(APackage, SECPKG_CRED_OUTBOUND, AuthIdentity); pInBuffer := nil; pCtxt := nil; end; statusCode := FunctionTable.InitializeSecurityContext( @FCredHandle, pCtxt, PclChar(GetTclString(ATargetName)), flags, 0, 0, pInBuffer, 0, @FCtxtHandle, @outBuffer, @outFlags, @tsExpiry); Result := (statusCode = SEC_E_OK) or (statusCode = SEC_I_COMPLETE_NEEDED); if (statusCode = SEC_I_COMPLETE_AND_CONTINUE) or (statusCode = SEC_I_COMPLETE_NEEDED) then begin statusCode := FunctionTable.CompleteAuthToken(pCtxt, @outBuffer); if (statusCode <> SEC_E_OK) then begin RaiseSspiError(statusCode); end; end; if (statusCode <> SEC_E_OK) and (statusCode <> SEC_I_CONTINUE_NEEDED) then begin RaiseSspiError(statusCode); end; if (outBuffers[0].pvBuffer <> nil) then begin ABuffer.Size := 0; ABuffer.Write(outBuffers[0].pvBuffer^, outBuffers[0].cbBuffer); ABuffer.Position := 0; end; finally if (outBuffers[0].pvBuffer <> nil) then begin FunctionTable.FreeContextBuffer(outBuffers[0].pvBuffer); end; FreeMem(buf); end; end; { TclNtAuthServerSspi } constructor TclNtAuthServerSspi.Create; begin inherited Create(); FNewConversation := True; end; function TclNtAuthServerSspi.GenChallenge(const APackage: string; ABuffer: TStream; AuthIdentity: TclAuthIdentity): Boolean; var statusCode: SECURITY_STATUS; flags, outFlags: DWORD; inBuffer: TSecBufferDesc; inBuffers: array[0..0] of TSecBuffer; outBuffer: TSecBufferDesc; outBuffers: array[0..0] of TSecBuffer; buf: PclChar; bufSize: Integer; pInBuffer: PSecBufferDesc; pCtxt: PCtxtHandle; tsExpiry: TTimeStamp; begin {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'GenChallenge', ABuffer, 0);{$ENDIF} flags := ASC_REQ_DELEGATE + ASC_REQ_MUTUAL_AUTH + ASC_REQ_REPLAY_DETECT + ASC_REQ_SEQUENCE_DETECT + ASC_REQ_CONFIDENTIALITY + ASC_REQ_CONNECTION + ASC_REQ_INTEGRITY + ASC_REQ_ALLOCATE_MEMORY; outBuffer.ulVersion := SECBUFFER_VERSION; outBuffer.cBuffers := 1; outBuffer.pBuffers := @outBuffers; outBuffers[0].cbBuffer := 0; outBuffers[0].BufferType := SECBUFFER_TOKEN; outBuffers[0].pvBuffer := nil; buf := nil; try bufSize := ABuffer.Size - ABuffer.Position; if (bufSize > 0) then begin inBuffer.ulVersion := SECBUFFER_VERSION; inBuffer.cBuffers := 1; inBuffer.pBuffers := @inBuffers; GetMem(buf, bufSize); ABuffer.Read(buf^, bufSize); inBuffers[0].cbBuffer := bufSize; inBuffers[0].BufferType := SECBUFFER_TOKEN; inBuffers[0].pvBuffer := buf; pInBuffer := @inBuffer; end else begin pInBuffer := nil; end; if FNewConversation then begin DeleteSecHandles(); GenCredentialHandle(APackage, SECPKG_CRED_INBOUND, AuthIdentity); pCtxt := nil; FNewConversation := False; end else begin pCtxt := @FCtxtHandle; end; statusCode := FunctionTable.AcceptSecurityContext( @FCredHandle, pCtxt, pInBuffer, flags, 0, @FCtxtHandle, @outBuffer, @outFlags, @tsExpiry); Result := (statusCode = SEC_E_OK) or (statusCode = SEC_I_COMPLETE_NEEDED); if (statusCode = SEC_I_COMPLETE_AND_CONTINUE) or (statusCode = SEC_I_COMPLETE_NEEDED) then begin statusCode := FunctionTable.CompleteAuthToken(pCtxt, @outBuffer); if (statusCode <> SEC_E_OK) then begin RaiseSspiError(statusCode); end; end; if (statusCode <> SEC_E_OK) and (statusCode <> SEC_I_CONTINUE_NEEDED) then begin RaiseSspiError(statusCode); end; if (outBuffers[0].pvBuffer <> nil) then begin ABuffer.Size := 0; ABuffer.Write(outBuffers[0].pvBuffer^, outBuffers[0].cbBuffer); ABuffer.Position := 0; end; finally if (outBuffers[0].pvBuffer <> nil) then begin FunctionTable.FreeContextBuffer(outBuffers[0].pvBuffer); end; FreeMem(buf); end; end; procedure TclNtAuthServerSspi.ImpersonateUser; var statusCode: SECURITY_STATUS; begin statusCode := FunctionTable.ImpersonateSecurityContext(@FCtxtHandle); if (statusCode <> SEC_E_OK) then begin RaiseSspiError(statusCode); end; end; procedure TclNtAuthServerSspi.RevertUser; var statusCode: SECURITY_STATUS; begin statusCode := FunctionTable.RevertSecurityContext(@FCtxtHandle); if (statusCode <> SEC_E_OK) then begin RaiseSspiError(statusCode); end; end; end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit Consecutivos; interface uses SysUtils, Types, Classes, Variants, QTypes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, QcurrEdit, QGrids, IniFiles; type TfrmConsecutivos = class(TForm) grpConsec: TGroupBox; grdComprobante: TStringGrid; lblComprobante: TLabel; lblActual: TLabel; btnAceptar: TBitBtn; btnCancelar: TBitBtn; cmbCaja: TComboBox; lblCaja: TLabel; txtConsecActual: TcurrEdit; txtConsecNuevo: TcurrEdit; lblNuevo: TLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure RecuperaConsec(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnAceptarClick(Sender: TObject); private sCaja, sComprob : string; bModifica : boolean; procedure RecuperaConfig; procedure RecuperaCajas; procedure RecuperaPermisos; function VerificaDatos : boolean; procedure GuardaDatos; public iUsuario : integer; end; var frmConsecutivos: TfrmConsecutivos; implementation uses dm, Autoriza; {$R *.xfm} procedure TfrmConsecutivos.RecuperaConfig; var iniArchivo : TiniFile; sArriba, sIzq, sValor : string; begin iniArchivo := TiniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin sArriba := ReadString('Consec', 'PosY', ''); sIzq := ReadString('Consec', 'PosX', ''); if (Length(sArriba)>0) and (Length(sIzq)>0) then begin Top := StrToInt(sArriba); Left:= StrToInt(sIzq); end; sValor := ReadString('Consec', 'Caja', ''); if (Length(sValor) > 0) then sCaja := sValor else sCaja := '0'; sValor := ReadString('Consec', 'Comprobante', ''); if (Length(sValor) > 0) then grdComprobante.Row := StrToInt(sValor) else grdComprobante.Row := 0; Free; end; end; procedure TfrmConsecutivos.FormClose(Sender: TObject; var Action: TCloseAction); var iniArchivo : TiniFile; begin iniArchivo := TiniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin WriteString('Consec', 'PosX', IntToStr(Left)); WriteString('Consec', 'PosY', IntToStr(Top)); WriteString('Consec', 'Caja', cmbCaja.Text); WriteString('Consec', 'Comprobante', IntToStr(grdComprobante.Row)); Free; end; end; procedure TfrmConsecutivos.RecuperaCajas; var i : integer; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT numero FROM cajas ORDER BY numero'); Open; i := 0; while(not Eof) do begin cmbCaja.Items.Add(Trim(FieldByName('numero').AsString)); if(sCaja = FieldByName('numero').AsString) then cmbCaja.ItemIndex := i; Inc(i); Next; end; Close; end; end; procedure TfrmConsecutivos.RecuperaConsec(Sender: TObject); begin with dmDatos.qryModifica do begin sComprob := Copy(grdComprobante.Cells[0,grdComprobante.Row],1,1); Close; SQL.Clear; SQL.Add('SELECT MAX(numero) AS consec FROM comprobantes WHERE tipo = '''+ sComprob +''''); if (Length(cmbCaja.Text)>0) then SQL.Add('AND Caja = ' + cmbCaja.Text); Open; txtConsecActual.Value := FieldByName('consec').AsInteger; if (bModifica) then txtConsecNuevo.Value := txtConsecActual.Value; Close; end end; procedure TfrmConsecutivos.RecuperaPermisos; begin with TFrmAutoriza.Create(Self) do try if(not VerificaAutoriza(Self.iUsuario,'V12')) then begin lblNuevo.Visible := false; txtConsecNuevo.Visible := false; bModifica := false; end else begin lblNuevo.Visible := true; txtConsecNuevo.Visible := true; bModifica := true; end; finally Free; end end; procedure TfrmConsecutivos.FormShow(Sender: TObject); begin RecuperaConfig; RecuperaCajas; RecuperaPermisos; end; procedure TfrmConsecutivos.FormCreate(Sender: TObject); begin grdComprobante.Cells[0,0] := 'AJUSTE'; grdComprobante.Cells[0,1] := 'COTIZACION'; grdComprobante.Cells[0,2] := 'FACTURA'; grdComprobante.Cells[0,3] := 'NOTA'; grdComprobante.Cells[0,4] := 'TICKET'; end; procedure TfrmConsecutivos.btnAceptarClick(Sender: TObject); begin if (VerificaDatos) then GuardaDatos; Close; end; function TfrmConsecutivos.VerificaDatos : boolean; begin Result := true; if (txtConsecNuevo.Visible = True) and (txtConsecNuevo.Value = 0) then begin Application.MessageBox('Introduce el número consecutivo nuevo','Error',[smbOK],smsCritical); txtConsecNuevo.SetFocus; Result := false; end else if (not bModifica) then Result := false; end; procedure TfrmConsecutivos.GuardaDatos; begin with dmDatos.qryConsulta do begin Close; SQL.Clear; SQL.Add('INSERT INTO consecutivos(comprobante, numero, caja) VALUES('); SQL.Add(''''+ sComprob + ''',' + FloatToStr(txtConsecActual.Value) + ','+ cmbCaja.Text + ')'); ExecSQL; Close; end; end; end.
unit uTitulosControl; interface uses uTitulosDAO, Data.DB, Utils, uTitulos, System.SysUtils, System.Variants; type TTitulosControl = class private tituloDAO: TitulosDAO; funcoes: TUtils; public constructor create; destructor destroy; override; procedure setNovoTitulo(editar: boolean); procedure excluirTitulo(id: integer); function getTitulos: TDataSource; function getTitulosByParam(descricao, statusid: string): TDataSource; function getStatus: TDataSource; end; implementation { TTitulosControl } uses ufrmCadastroTitulos, ufrmTitulos; constructor TTitulosControl.create; begin tituloDAO := TitulosDAO.Create; end; destructor TTitulosControl.destroy; begin tituloDAO.Free; inherited; end; procedure TTitulosControl.excluirTitulo(id: integer); begin if funcoes.perguntarUsuario('Deseja realmente excluir?') then begin tituloDAO.excluirTitulo(id); funcoes.confirmacaoUsuario('Título excluído com sucesso!'); end; end; function TTitulosControl.getStatus: TDataSource; begin Result := tituloDAO.getStatus; end; function TTitulosControl.getTitulos: TDataSource; begin Result := tituloDAO.getTitulos; end; function TTitulosControl.getTitulosByParam(descricao, statusid: string): TDataSource; begin if (Trim(descricao) = '') and (statusid = '') then Result := tituloDAO.getTitulos else Result := tituloDAO.getTitulosByParam(descricao, statusid); end; procedure TTitulosControl.setNovoTitulo(editar: boolean); var titulo: TTitulos; begin try titulo := TTitulos.create; with frmCadastroTitulos do begin if Trim(edtDescricao.Text) = '' then raise Exception.Create('O campo ''Descriçao do Título'' é obrigatório!'); if cedValor.Value <= 0 then raise Exception.Create('O campo ''Valor'' é obrigatório!'); if DateToStr(dtpDataVencimento.Date) < DateToStr(Date) then raise Exception.Create('A data de vencimento não pode ser inferior à data atual!'); if Trim(dblStatus.Text) = '' then raise Exception.Create('O campo ''Status'' é obrigatório!'); titulo.ID := tituloID; titulo.descricao := edtDescricao.Text; titulo.valor := cedValor.Value; titulo.datalancamento := StrToDate(FormatDateTime('dd/mm/yyyy', Date)); titulo.datavencimento := dtpDataVencimento.Date; titulo.statusid := StrToInt(dblStatus.Value); titulo.observacoes := mmObservacoes.Lines.Text; Clear; end; if editar then begin tituloDAO.editarTitulo(titulo); funcoes.confirmacaoUsuario('Título alterado com sucesso!'); frmCadastroTitulos.Close; end else begin tituloDAO.setNovoTitulo(titulo); funcoes.confirmacaoUsuario('Título cadastrado com sucesso!'); end; titulo.Free; except on e: Exception do funcoes.alertarUsuario(e.Message); end; end; end.
{$MODE OBJFPC} Const ginp='diophante.inp'; gout='diophante.out'; Var a,b,c,x,k:int64; Function Diophante(a,b,c:int64; var x,k:int64):boolean; Var m,n,r,xm,xn,xr,q:int64; Begin m:=a; n:=b; xm:=1; xn:=0; while n<>0 do begin q:=m div n; r:=m-q*n; xr:=xm-q*xn; m:=n; xm:=xn; n:=r; xn:=xr; end; result:=c mod m=0; if not result then exit; q:=c div m; k:=abs(b div m); x:=xm*q mod k; if x<=0 then x:=x+k; End; Function Process:int64; Begin read(a,b,c); result:=0; if (diophante(a,b,c,x,k)) and (x<=(c-b) div a) then result:=((c-b) div a-x) div k+1; End; Begin Assign(input,ginp); Assign(output,gout); Reset(input); Rewrite(output); write(Process); Close(input); Close(output); End.
//Exercicio 22:Escreva um algoritmo que receba o nome e a idade de uma pessoa. Exibir o nome da pessoa e a expressão //"Maior de Idade" ou a expressão "Menor de Idade". { Solução em Portugol Algoritmo Exercicio 22; Var idade: inteiro; nome: caracter; Inicio exiba("Programa que diz se você é maior ou menor de idade."); exiba("Digite o seu nome: "); leia(nome); exiba("Digite sua idade:"); leia(idade); se(idade < 18) então exiba(nome," é Menor de Idade.") senão exiba(nome," é Maior de Idade."); fimse; Fim. } // Solução em Pascal Program Exercicio22; uses crt; var idade: integer; nome: string; begin clrscr; writeln('Programa que diz se você é maior ou menor de idade.'); writeln('Digite o seu nome: '); readln(nome); writeln('Digite a sua idade: '); readln(idade); if(idade < 18) then writeln(nome,' é Menor de Idade.') else writeln(nome,' é Maior de Idade.'); repeat until keypressed; end.
unit MFichas.Controller.Venda.Metodos.DevolverItem; interface uses MFichas.Controller.Venda.Interfaces, MFichas.Model.Venda.Interfaces, MFichas.Model.Item; type TControllerVendaMetodosDevolverItem = class(TInterfacedObject, iControllerVendaMetodosDevolverItem) private [weak] FParent : iControllerVenda; FModel : iModelVenda; FCodigo : String; FQuantidade: Currency; FValor : Currency; constructor Create(AParent: iControllerVenda; AModel: iModelVenda); public destructor Destroy; override; class function New(AParent: iControllerVenda; AModel: iModelVenda): iControllerVendaMetodosDevolverItem; function Codigo(ACodigo: String) : iControllerVendaMetodosDevolverItem; function Quantidade(AQuantidade: Double): iControllerVendaMetodosDevolverItem; function Valor(AValor: Currency) : iControllerVendaMetodosDevolverItem; function Executar : iControllerVendaMetodosDevolverItem; function &End : iControllerVendaMetodos; end; implementation { TControllerVendaMetodosDevolverItem } function TControllerVendaMetodosDevolverItem.Codigo( ACodigo: String): iControllerVendaMetodosDevolverItem; begin Result := Self; FCodigo := ACodigo; end; function TControllerVendaMetodosDevolverItem.&End: iControllerVendaMetodos; begin Result := FParent.Metodos; end; constructor TControllerVendaMetodosDevolverItem.Create(AParent: iControllerVenda; AModel: iModelVenda); begin FParent := AParent; FModel := AModel; end; destructor TControllerVendaMetodosDevolverItem.Destroy; begin inherited; end; function TControllerVendaMetodosDevolverItem.Executar: iControllerVendaMetodosDevolverItem; begin Result := Self; FModel .Item .Iterator .Add( TModelItem.New(FModel) .Metodos .Devolver .Codigo(FCodigo) .Quantidade(FQuantidade) .Valor(FValor) .&End .&End ) .&End; end; class function TControllerVendaMetodosDevolverItem.New(AParent: iControllerVenda; AModel: iModelVenda): iControllerVendaMetodosDevolverItem; begin Result := Self.Create(AParent, AModel); end; function TControllerVendaMetodosDevolverItem.Quantidade( AQuantidade: Double): iControllerVendaMetodosDevolverItem; begin Result := Self; FQuantidade := AQuantidade; end; function TControllerVendaMetodosDevolverItem.Valor( AValor: Currency): iControllerVendaMetodosDevolverItem; begin Result := Self; FValor := AValor; end; end.
var x:real; const q=0.00001; begin x:=0.999999; while x>=-0.999999 do begin x:=x-0.000001; if abs(cos(x)-4*x)>q then continue else writeln('X = ',x) end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCountryFlag; type TForm1 = class(TForm) Label1: TLabel; Timer1: TTimer; Label2: TLabel; GroupBox1: TGroupBox; Image1: TImage; GroupBox2: TGroupBox; PaintBox1: TPaintBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure PaintBox1Paint(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private-Deklarationen } FFlagge : TCountryFlag; procedure CreateEmptyPicture; procedure DrawFlagstoImage; public { Public-Deklarationen } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.CreateEmptyPicture; var bmp : TBitmap; begin bmp := TBitmap.Create; bmp.PixelFormat := pf24bit; bmp.Width := Image1.Width; bmp.Height := Image1.Height; Image1.Picture.Graphic := bmp; end; procedure TForm1.DrawFlagstoImage; const SIZE_X = 50; SIZE_Y = 25; ABSTAND = 5; var i : Integer; r : TRect; begin FFlagge.Canvas := Image1.Picture.Bitmap.Canvas; for i := 0 to 5 do begin FFlagge.Nationality := i; r.Left := 5 + i * (SIZE_X - ABSTAND); r.Right := r.Left + SIZE_X; r.Top := i * (SIZE_Y + Abstand); r.Bottom := r.Top + SIZE_Y; FFlagge.Paint(r); end; end; procedure TForm1.FormCreate(Sender: TObject); begin FFlagge := TCountryFlag.Create; CreateEmptyPicture; DrawFlagstoImage; FFlagge.Nationality := 0; end; procedure TForm1.FormDestroy(Sender: TObject); begin FFlagge.Free; end; procedure TForm1.PaintBox1Paint(Sender: TObject); begin FFlagge.Canvas := PaintBox1.Canvas; FFlagge.Paint(PaintBox1.ClientRect); end; procedure TForm1.Timer1Timer(Sender: TObject); begin FFlagge.Nationality := (FFlagge.Nationality + 1) mod 6; PaintBox1.Invalidate; end; end.
unit Map; {$mode objfpc}{$H+} interface uses ComCtrls,SysUtils,Dialogs,Classes; type TConnectionData = packed record MapNumber: Byte; MapDataPointer: Word; MapLocationRamPointer: Word; WidthHeightVisiblePart: Byte; YChangePoint: Byte; XChangePoint: Byte; Unknown: Byte; UnknownPointer: Word; end; //Header 1 TMapHeader = packed record TilesetNumber: Byte; Height: Byte; Width: Byte; DataPointer: Word; ObjectScriptPointers: Word; LevelScriptPointer: Word; ConnectionDataControl: Byte; ConnectionData: array [$00..$03] of TConnectionData; ObjectDataPointer: Word; BorderBlock: Byte; end; const Ln = #13#10; //table needed for encoding area names Table: array [$00..$FF] of string[4] = ( { 0 1 2 3 4 5 6 7 8 9 A B C D E F } {0}'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' , {1}'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,' ' , {2}'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' , {3}'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' , {4}'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,Ln , {5}'#' ,Ln+Ln ,'HIRO','GARY','POKé',Ln ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' , {6}'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' , {7}'#' ,'#' ,'#' ,'#' ,'#' ,'…' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,' ' , {8}'A' ,'B' ,'C' ,'D' ,'E' ,'F' ,'G' ,'H' ,'I' ,'J' ,'K' ,'L' ,'M' ,'N' ,'O' ,'P' , {9}'Q' ,'R' ,'S' ,'T' ,'U' ,'V' ,'W' ,'X' ,'Y' ,'Z' ,'#' ,'#' ,':' ,'#' ,'#' ,'#' , {A}'a' ,'b' ,'c' ,'d' ,'e' ,'f' ,'g' ,'h' ,'i' ,'j' ,'k' ,'l' ,'m' ,'n' ,'o' ,'p' , {B}'q' ,'r' ,'s' ,'t' ,'u' ,'v' ,'w' ,'x' ,'y' ,'z' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' , {C}'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' , {D}'#' ,'''l' ,'''m' ,'''r' ,'''s' ,'''t' ,'''v' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' , {E}'''' ,'#' ,'#' ,'-' ,'#' ,'#' ,'?' ,'!' ,'.' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' ,'#' , {F}'#' ,' ' ,'#' ,'#' ,',' ,'#' ,'0' ,'1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ); function GBPtrToFilePos(Bank: Byte; Addr: Word): Integer; overload; function GBBank(Position: Integer): Byte; procedure ReadMapHeaderLocations; function GetMapHeader(MapIndex: Byte): TMapHeader; var AreaNames: TStringList; BankLocations: array [$00..$F9] of Byte; MapHeaderOffsets: array [$00..$F9] of Word; implementation uses MapEditor; //converts rombank and, address in that bank, into romfile offset function GBPtrToFilePos(Bank: Byte; Addr: Word): Integer; overload; begin Result := (Bank * $4000) + (Addr xor $4000); end; //gives gameboy rombank number ar specified file offset function GBBank(Position: Integer): Byte; begin Result := (Position div $4000); end; procedure ReadMapHeaderLocations; begin Rom.Position := $C23D; Rom.Read(BankLocations, $F9); Rom.Position := $01AE; Rom.Read(MapHeaderOffsets, $F9 * sizeof(Word)); end; function GetMapHeader(MapIndex: Byte): TMapHeader; var TempHeader: TMapHeader; begin Rom.Position := GBPtrToFilePos(BankLocations[MapIndex], MapHeaderOffsets[MapIndex]); Rom.Read(TempHeader.TilesetNumber, 1); Rom.Read(TempHeader.Height, 1); Rom.Read(TempHeader.Width, 1); Rom.Read(TempHeader.DataPointer, 2); Rom.Read(TempHeader.ObjectScriptPointers, 2); Rom.Read(TempHeader.LevelScriptPointer, 2); Rom.Read(TempHeader.ConnectionDataControl, 1); if (TempHeader.ConnectionDataControl and $08) = $08 then Rom.Read(TempHeader.ConnectionData[0], SizeOf(TConnectionData)); if (TempHeader.ConnectionDataControl and $04) = $04 then Rom.Read(TempHeader.ConnectionData[1], SizeOf(TConnectionData)); if (TempHeader.ConnectionDataControl and $02) = $02 then Rom.Read(TempHeader.ConnectionData[2], SizeOf(TConnectionData)); if (TempHeader.ConnectionDataControl and $01) = $01 then Rom.Read(TempHeader.ConnectionData[3], SizeOf(TConnectionData)); Rom.Read(TempHeader.ObjectDataPointer, 2); Rom.Position := GBPtrToFilePos(BankLocations[MapIndex], TempHeader.ObjectDataPointer); Rom.Read(TempHeader.BorderBlock, 1); Result := TempHeader; end; end.
unit IdHeaderCoder2022JP; interface {$i IdCompilerDefines.inc} {RLebeau: TODO - move this logic into a TIdTextEncoding descendant class} uses IdGlobal, IdHeaderCoderBase; type TIdHeaderCoder2022JP = class(TIdHeaderCoder) public class function Decode(const ACharSet: string; const AData: TIdBytes): String; override; class function Encode(const ACharSet, AData: String): TIdBytes; override; class function CanHandle(const ACharSet: String): Boolean; override; end; // RLebeau 4/17/10: this forces C++Builder to link to this unit so // RegisterHeaderCoder can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdHeaderCoder2022JP"'*) implementation uses SysUtils; const // RLebeau 1/7/09: using integers for #128-#255 because in D2009, the compiler // may change characters >= #128 from their Ansi codepage value to their true // Unicode codepoint value, depending on the codepage used for the source code. // For instance, #128 may become #$20AC... kana_tbl : array[161..223{#$A1..#$DF}] of Word = ( $2123,$2156,$2157,$2122,$2126,$2572,$2521,$2523,$2525,$2527, $2529,$2563,$2565,$2567,$2543,$213C,$2522,$2524,$2526,$2528, $252A,$252B,$252D,$252F,$2531,$2533,$2535,$2537,$2539,$253B, $253D,$253F,$2541,$2544,$2546,$2548,$254A,$254B,$254C,$254D, $254E,$254F,$2552,$2555,$2558,$255B,$255E,$255F,$2560,$2561, $2562,$2564,$2566,$2568,$2569,$256A,$256B,$256C,$256D,$256F, $2573,$212B,$212C); vkana_tbl : array[161..223{#$A1..#$DF}] of Word = ( $0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000, $0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$2574,$0000, $0000,$252C,$252E,$2530,$2532,$2534,$2536,$2538,$253A,$253C, $253E,$2540,$2542,$2545,$2547,$2549,$0000,$0000,$0000,$0000, $0000,$2550,$2553,$2556,$2559,$255C,$0000,$0000,$0000,$0000, $0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000, $0000,$0000,$0000); sj1_tbl : array[128..255{#128..#255}] of byte = ( $00,$21,$23,$25,$27,$29,$2B,$2D,$2F,$31,$33,$35,$37,$39,$3B,$3D, $3F,$41,$43,$45,$47,$49,$4B,$4D,$4F,$51,$53,$55,$57,$59,$5B,$5D, $00,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01, $01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01, $01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01, $01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01, $5F,$61,$63,$65,$67,$69,$6B,$6D,$6F,$71,$73,$75,$77,$79,$7B,$7D, $02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$00,$00,$00); sj2_tbl : array[0..255{#0..#255}] of Word = ( $0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000, $0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000, $0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000, $0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000, $0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000, $0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000,$0000, $0000,$0000,$0000,$0000,$0021,$0022,$0023,$0024,$0025,$0026, $0027,$0028,$0029,$002A,$002B,$002C,$002D,$002E,$002F,$0030, $0031,$0032,$0033,$0034,$0035,$0036,$0037,$0038,$0039,$003A, $003B,$003C,$003D,$003E,$003F,$0040,$0041,$0042,$0043,$0044, $0045,$0046,$0047,$0048,$0049,$004A,$004B,$004C,$004D,$004E, $004F,$0050,$0051,$0052,$0053,$0054,$0055,$0056,$0057,$0058, $0059,$005A,$005B,$005C,$005D,$005E,$005F,$0000,$0060,$0061, $0062,$0063,$0064,$0065,$0066,$0067,$0068,$0069,$006A,$006B, $006C,$006D,$006E,$006F,$0070,$0071,$0072,$0073,$0074,$0075, $0076,$0077,$0078,$0079,$007A,$007B,$007C,$007D,$007E,$0121, $0122,$0123,$0124,$0125,$0126,$0127,$0128,$0129,$012A,$012B, $012C,$012D,$012E,$012F,$0130,$0131,$0132,$0133,$0134,$0135, $0136,$0137,$0138,$0139,$013A,$013B,$013C,$013D,$013E,$013F, $0140,$0141,$0142,$0143,$0144,$0145,$0146,$0147,$0148,$0149, $014A,$014B,$014C,$014D,$014E,$014F,$0150,$0151,$0152,$0153, $0154,$0155,$0156,$0157,$0158,$0159,$015A,$015B,$015C,$015D, $015E,$015F,$0160,$0161,$0162,$0163,$0164,$0165,$0166,$0167, $0168,$0169,$016A,$016B,$016C,$016D,$016E,$016F,$0170,$0171, $0172,$0173,$0174,$0175,$0176,$0177,$0178,$0179,$017A,$017B, $017C,$017D,$017E,$0000,$0000,$0000); class function TIdHeaderCoder2022JP.Decode(const ACharSet: String; const AData: TIdBytes): String; var T : string; I, L : Integer; isK : Boolean; K1, K2 : Byte; K3 : Byte; begin T := ''; {Do not Localize} isK := False; L := Length(AData); I := 0; while I < L do begin if AData[I] = 27 then begin Inc(I); if (I+1) < L then begin if (AData[I] = Ord('$')) and (AData[I+1] = Ord('B')) then begin {do not localize} isK := True; end else if (AData[I] = Ord('(')) and (AData[I+1] = Ord('B')) then begin {do not localize} isK := False; end; Inc(I, 2); { TODO -oTArisawa : Check RFC 1468} end; end else if isK then begin if (I+1) < L then begin K1 := AData[I]; K2 := AData[I+1]; K3 := (K1 - 1) shr 1; if K1 < 95 then begin K3:= K3 + 113; end else begin K3 := K3 + 177; end; if (K1 mod 2) = 1 then begin if K2 < 96 then begin K2 := K2 + 31; end else begin K2 := K2 + 32; end; end else begin K2 := K2 + 126; end; T := T + Char(K3) + Char(k2); Inc(I, 2); end else begin Inc(I); { invalid DBCS } end; end else begin T := T + Char(AData[I]); Inc(I); end; end; Result := T; end; class function TIdHeaderCoder2022JP.Encode(const ACharSet, AData: String): TIdBytes; const desig_asc: array[0..2] of Byte = (27, Ord('('), Ord('B')); {Do not Localize} desig_jis: array[0..2] of Byte = (27, Ord('$'), Ord('B')); {Do not Localize} var T: TIdBytes; I, L: Integer; isK: Boolean; K1: Byte; K2, K3: Word; begin SetLength(T, 0); isK := False; L := Length(AData); I := 1; while I <= L do begin if Ord(AData[I]) < 128 then {Do not Localize} begin if isK then begin AppendByte(T, 27); AppendByte(T, Ord('(')); {Do not Localize} AppendByte(T, Ord('B')); {Do not Localize} isK := False; end; AppendByte(T, Ord(AData[I])); Inc(I); end else begin K1 := sj1_tbl[Ord(AData[I])]; case K1 of 0: Inc(I); { invalid SBCS } 2: Inc(I, 2); { invalid DBCS } 1: begin { halfwidth katakana } if not isK then begin AppendByte(T, 27); AppendByte(T, Ord('$')); {Do not Localize} AppendByte(T, Ord('B')); {Do not Localize} isK := True; end; { simple SBCS -> DBCS conversion } K2 := kana_tbl[Ord(AData[I])]; if (I < L) and ((Ord(AData[I+1]) and $FE) = $DE) then begin { convert kana + voiced mark to voiced kana } K3 := vkana_tbl[Ord(AData[I])]; // This is an if and not a case because of a D8 bug, return to // case when d8 patch is released // RLebeau 1/7/09: using Char() for #128-#255 because in D2009, the compiler // may change characters >= #128 from their Ansi codepage value to their true // Unicode codepoint value, depending on the codepage used for the source code. // For instance, #128 may become #$20AC... if AData[I+1] = Char($DE) then begin { voiced } if K3 <> 0 then begin K2 := K3; Inc(I); end; end else if AData[I+1] = Char($DF) then begin { semivoiced } if (K3 >= $2550) and (K3 <= $255C) then begin K2 := K3 + 1; Inc(I); end; end; end; AppendByte(T, K2 shr 8); AppendByte(T, K2 and $FF); Inc(I); end; else { DBCS } if (I < L) then begin K2 := sj2_tbl[Ord(AData[I+1])]; if K2 <> 0 then begin if not isK then begin AppendByte(T, 27); AppendByte(T, Ord('$')); {Do not Localize} AppendByte(T, Ord('B')); {Do not Localize} isK := True; end; AppendByte(T, K1 + K2 shr 8); AppendByte(T, K2 and $FF); end; end; Inc(I, 2); end; end; end; if isK then begin AppendByte(T, 27); AppendByte(T, Ord('(')); {Do not Localize} AppendByte(T, Ord('B')); {Do not Localize} end; Result := T; end; class function TIdHeaderCoder2022JP.CanHandle(const ACharSet: String): Boolean; begin Result := TextIsSame(ACharSet, 'ISO-2022-JP'); {do not localize} end; initialization RegisterHeaderCoder(TIdHeaderCoder2022JP); finalization UnregisterHeaderCoder(TIdHeaderCoder2022JP); end.
unit AttributeExplorerWordsPack; // Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\AttributeExplorerWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "AttributeExplorerWordsPack" MUID: (553109700297) {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)} uses l3IntfUses ; {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)} uses l3ImplUses , F_AttrExplorer , tfwClassLike , tfwScriptingInterfaces , dt_AttrSchema , TypInfo , tfwAxiomaticsResNameGetter , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *553109700297impl_uses* //#UC END# *553109700297impl_uses* ; type TkwAttrExplorerGotoOnAttrNode = {final} class(TtfwClassLike) {* Слово скрипта AttrExplorer:GotoOnAttrNode } private procedure GotoOnAttrNode(const aCtx: TtfwContext; aAttrExplorer: TAttrExplorer; anAttrID: TdtAttribute); {* Реализация слова скрипта AttrExplorer:GotoOnAttrNode } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwAttrExplorerGotoOnAttrNode TAttributeExplorerWordsPackResNameGetter = {final} class(TtfwAxiomaticsResNameGetter) {* Регистрация скриптованой аксиоматики } public class function ResName: AnsiString; override; end;//TAttributeExplorerWordsPackResNameGetter procedure TkwAttrExplorerGotoOnAttrNode.GotoOnAttrNode(const aCtx: TtfwContext; aAttrExplorer: TAttrExplorer; anAttrID: TdtAttribute); {* Реализация слова скрипта AttrExplorer:GotoOnAttrNode } //#UC START# *553109D90010_553109D90010_528A0B9E02C7_Word_var* //#UC END# *553109D90010_553109D90010_528A0B9E02C7_Word_var* begin //#UC START# *553109D90010_553109D90010_528A0B9E02C7_Word_impl* aAttrExplorer.GotoOnAttrNode(anAttrID); //#UC END# *553109D90010_553109D90010_528A0B9E02C7_Word_impl* end;//TkwAttrExplorerGotoOnAttrNode.GotoOnAttrNode class function TkwAttrExplorerGotoOnAttrNode.GetWordNameForRegister: AnsiString; begin Result := 'AttrExplorer:GotoOnAttrNode'; end;//TkwAttrExplorerGotoOnAttrNode.GetWordNameForRegister function TkwAttrExplorerGotoOnAttrNode.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwAttrExplorerGotoOnAttrNode.GetResultTypeInfo function TkwAttrExplorerGotoOnAttrNode.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwAttrExplorerGotoOnAttrNode.GetAllParamsCount function TkwAttrExplorerGotoOnAttrNode.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TAttrExplorer), TypeInfo(TdtAttribute)]); end;//TkwAttrExplorerGotoOnAttrNode.ParamsTypes procedure TkwAttrExplorerGotoOnAttrNode.DoDoIt(const aCtx: TtfwContext); var l_aAttrExplorer: TAttrExplorer; var l_anAttrID: TdtAttribute; begin try l_aAttrExplorer := TAttrExplorer(aCtx.rEngine.PopObjAs(TAttrExplorer)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aAttrExplorer: TAttrExplorer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anAttrID := TdtAttribute(aCtx.rEngine.PopInt); except on E: Exception do begin RunnerError('Ошибка при получении параметра anAttrID: TdtAttribute : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except GotoOnAttrNode(aCtx, l_aAttrExplorer, l_anAttrID); end;//TkwAttrExplorerGotoOnAttrNode.DoDoIt class function TAttributeExplorerWordsPackResNameGetter.ResName: AnsiString; begin Result := 'AttributeExplorerWordsPack'; end;//TAttributeExplorerWordsPackResNameGetter.ResName {$R AttributeExplorerWordsPack.res} initialization TkwAttrExplorerGotoOnAttrNode.RegisterInEngine; {* Регистрация AttrExplorer_GotoOnAttrNode } TAttributeExplorerWordsPackResNameGetter.Register; {* Регистрация скриптованой аксиоматики } TtfwTypeRegistrator.RegisterType(TypeInfo(TAttrExplorer)); {* Регистрация типа TAttrExplorer } TtfwTypeRegistrator.RegisterType(TypeInfo(TdtAttribute)); {* Регистрация типа TdtAttribute } {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts) end.
unit Model.Venda; interface uses Model.Interfaces, Controller.Observer.Interfaces; type TModelVenda = class(TInterfacedObject, iModelVenda) private FItem : iModelItem; FObserverItem : iSubjectItem; public constructor Create; destructor Destroy; override; class function New : iModelVenda; function Item : iModelItem; function ObserverItem(Value : iSubjectItem) : iModelVenda; overload; function ObserverItem : iSubjectItem; overload; end; implementation uses Model.Item; constructor TModelVenda.Create; begin FItem := TModelItem.New(Self); end; destructor TModelVenda.Destroy; begin inherited; end; function TModelVenda.Item: iModelItem; begin Result := FItem; end; class function TModelVenda.New : iModelVenda; begin Result := Self.Create; end; function TModelVenda.ObserverItem: iSubjectItem; begin Result := FObserverItem; end; function TModelVenda.ObserverItem(Value: iSubjectItem): iModelVenda; begin Result := Self; FObserverItem := Value; end; end.
unit uBackup; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, uUtilitarioController; type TfrmBackup = class(TForm) pnlRodape: TPanel; btnOk: TBitBtn; btnCancelar: TBitBtn; SaveDialog1: TSaveDialog; BalloonHint1: TBalloonHint; pnlBackup: TPanel; Label1: TLabel; btnBackup: TSpeedButton; lblAguarde: TLabel; edtDestino: TEdit; procedure FormCreate(Sender: TObject); procedure btnBackupClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } procedure GerarBackup; public { Public declarations } end; var frmBackup: TfrmBackup; implementation {$R *.dfm} uses uFuncoesSIDomper, uImagens; procedure TfrmBackup.FormCreate(Sender: TObject); var img: TfrmImagens; begin img := TfrmImagens.Create(Self); try btnOk.Glyph := img.btnConfirmar.Glyph; btnCancelar.Glyph := img.btnCancelar.Glyph; finally FreeNotification(img); end; end; procedure TfrmBackup.btnBackupClick(Sender: TObject); begin if SaveDialog1.Execute then edtDestino.Text :=SaveDialog1.FileName; end; procedure TfrmBackup.btnCancelarClick(Sender: TObject); begin Close; end; procedure TfrmBackup.btnOkClick(Sender: TObject); begin if Trim(edtDestino.Text) = '' then begin edtDestino.SetFocus; raise Exception.Create('Informe o Destino do Backup'); end; if TFuncoes.Confirmar('Confirmar geração de backup?') then begin try GerarBackup(); ShowMessage('Fim do Backup!'); except ON E: Exception do begin ShowMessage(E.Message); end; end; end; end; procedure TfrmBackup.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmBackup.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TfrmBackup.FormKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then begin key:=#0; perform(Wm_NextDlgCtl,0,0); end; end; procedure TfrmBackup.GerarBackup; var obj: TUtilitarioController; begin if Trim(edtDestino.Text) = '' then begin edtDestino.SetFocus; raise Exception.Create('Informe o Destino do Backup!'); end; obj := TUtilitarioController.Create; try lblAguarde.Visible := True; btnCancelar.Enabled := False; btnOk.Enabled := False; application.ProcessMessages; obj.GerarBackup(edtDestino.Text); finally lblAguarde.Visible := False; btnCancelar.Enabled := True; btnOk.Enabled := true; application.ProcessMessages; FreeAndNil(obj); end; end; end.
unit CliRefForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DB, DBClient, Grids, DBGrids, MConnect; type TForm1 = class(TForm) cds: TClientDataSet; DCOMConnection1: TDCOMConnection; DataSource1: TDataSource; DBGrid1: TDBGrid; Button1: TButton; Button2: TButton; ListBox1: TListBox; Label1: TLabel; procedure Button1Click(Sender: TObject); procedure cdsAfterPost(DataSet: TDataSet); procedure cdsAfterScroll(DataSet: TDataSet); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} type TMyGrid = class (TDBGrid) end; procedure TForm1.Button1Click(Sender: TObject); begin if cds.ChangeCount = 0 then cds.Refresh; end; procedure TForm1.cdsAfterPost(DataSet: TDataSet); begin cds.ApplyUpdates (-1); end; procedure TForm1.cdsAfterScroll(DataSet: TDataSet); begin // refresh current record only if cds.UpdateStatus = usUnModified then cds.RefreshRecord; // log operation Listbox1.Items.Add (cds['Emp_no']); end; procedure TForm1.Button2Click(Sender: TObject); var i: Integer; bm: TBookmarkStr; begin // refresh visible rows cds.DisableControls; // start with the current row i := TMyGrid(DbGrid1).Row; bm := cds.Bookmark; try // get back t the first visible record while i > 1 do begin cds.Prior; Dec (i); end; // return to the current record i := TMyGrid(DbGrid1).Row; cds.Bookmark := bm; // go ahead until the grid is complete while i < TMyGrid(DbGrid1).RowCount do begin cds.Next; Inc (i); end; finally // set back everything and refresh cds.Bookmark := bm; cds.EnableControls; end; end; procedure TForm1.FormCreate(Sender: TObject); begin cds.Active := True; end; end.
unit fcmsg; { // // Components : TfcCaptureMessageClass // // Copyright (c) 1999 by Woll2Woll Software } {$T-} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Menus; type TfcWndProcEvent = procedure(var Message: TMessage) of object; TfcBeforeWndProcEvent = procedure(var Message: TMessage; var ProcessMessage: boolean) of object; TfcCaptureMessageClass = class(TComponent) private FOnWndProc: TfcWndProcEvent; FOnBeforeWndProc: TfcBeforeWndProcEvent; FEnabled: Boolean; FWndHandle: HWnd; FWndHandlerPtr: Pointer; FOldWndHandler: Pointer; {Restore to this when this component is destroyed } FWinControl: TWinControl; procedure SetWndHandle(Value: Hwnd); procedure SetWndControl(Value: TWinControl); procedure SetEnabled(newValue: Boolean); procedure StartSubClass; procedure EndSubClass; protected procedure WndProc(var Message: TMessage); virtual; procedure Refresh; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure NewWndProc(var Message: TMessage); property WindowHandle: HWnd read FWndHandle write SetWndHandle; property WinControl: TWinControl read FWinControl write SetWndControl; property Enabled: Boolean read FEnabled write SetEnabled; property OnWndProc: TfcWndProcEvent read FOnWndProc write FOnWndProc; property OnBeforeWndProc: TfcBeforeWndProcEvent read FOnBeforeWndProc write FOnBeforeWndProc; end; implementation procedure TfcCaptureMessageClass.Refresh; begin end; { Refresh } constructor TfcCaptureMessageClass.Create(AOwner: TComponent); begin inherited Create(AOwner); FOldWndHandler := nil; FWndHandlerPtr := nil; FWinControl := nil; FWndHandle := 0; FEnabled := false; end; destructor TfcCaptureMessageClass.Destroy; begin Enabled := False; inherited Destroy; end; procedure TfcCaptureMessageClass.NewWndProc(var Message: TMessage); begin WndProc(Message); end; procedure TfcCaptureMessageClass.WndProc(var Message: TMessage); var ProcessMessage: boolean; begin ProcessMessage:= True; if Assigned(FOnBeforeWndProc) then FOnBeforeWndProc(Message, ProcessMessage); if ProcessMessage=False then begin // DefaultHandler(Message); exit; { Paul say call default handler } end; with Message do begin result := CallWindowProc(FOldWndHandler, FWndHandle, Msg, wParam, lParam); end; if Assigned(FOnWndProc) then FOnWndProc(Message); end; procedure TfcCaptureMessageClass.StartSubClass; begin if IsWindow(FWndHandle) then begin FOldWndHandler := Pointer(GetWindowLong(FWndHandle, GWL_WNDPROC)); FWndHandlerPtr := MakeObjectInstance(NewWndProc); if FWndHandlerPtr = nil then raise EOutOfResources.Create('Windows Resources Exhausted'); SetWindowLong(FWndHandle, GWL_WNDPROC, LongInt(FWndHandlerPtr)); FEnabled := true; end end; procedure TfcCaptureMessageClass.EndSubClass; begin if IsWindow(FWndHandle) then begin SetWindowLong(FWndHandle, GWL_WNDPROC, LongInt(FOldWndHandler)); FOldWndHandler := nil; end; if FWndHandlerPtr <> nil then FreeObjectInstance(FWndHandlerPtr); FEnabled := false; end; procedure TfcCaptureMessageClass.SetWndControl(Value: TWinControl); begin if Value <> FWinControl then if Value is TWinControl then begin FWinControl := Value; WindowHandle := FWinControl.Handle; end; end; procedure TfcCaptureMessageClass.SetWndHandle(Value: Hwnd); begin if FWndHandle <> 0 then EndSubClass; FWndHandle := Value; if (FWndHandle <> 0) and FEnabled then StartSubClass; end; procedure TfcCaptureMessageClass.SetEnabled(newValue: Boolean); begin if FEnabled <> newValue then begin FEnabled := newValue; if Enabled then StartSubClass else EndSubClass; end; end; end.
unit perIB; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Datasnap.DBClient, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinsDefaultPainters, EnPngGr, Vcl.ExtCtrls, Vcl.StdCtrls, cxDropDownEdit, cxCalc, cxDBEdit, cxTextEdit, cxMaskEdit, cxSpinEdit, Vcl.Buttons, Vcl.ImgList, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGrid; const IVA = 767; type TFPerIB = class(TForm) cdsPerIB: TClientDataSet; cdsPerIBmonto: TFloatField; ds: TDataSource; btnOK: TButton; btnAnu: TButton; img: TImageList; DsPcia: TDataSource; cdsPerIBjurisdiccion: TIntegerField; vista: TcxGridDBTableView; nivel: TcxGridLevel; grilla: TcxGrid; vistamonto: TcxGridDBColumn; vistajurisdiccion: TcxGridDBColumn; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure btnOKClick(Sender: TObject); private { Private declarations } public { Public declarations } function sumarMonto: Double; end; var FPerIB: TFPerIB; implementation uses Data; {$R *.dfm} procedure TFPerIB.btnOKClick(Sender: TObject); begin if ( cdsPerIB.State in [dsEdit, dsInsert]) then try cdsPerIB.Post; except on e:Exception do begin cdsPerIB.Cancel; raise; end; end; end; procedure TFPerIB.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caHide; end; procedure TFPerIB.FormCreate(Sender: TObject); begin cdsPerIB.CreateDataSet; cdsPerIB.Append; DM.TPcia.Open; end; procedure TFPerIB.FormDestroy(Sender: TObject); begin DM.TPcia.Close; end; function TFPerIB.sumarMonto: Double; begin cdsPerIB.First; result := 0; while not cdsPerIB.Eof do begin result := result + cdsPerIBmonto.Value; cdsPerIB.Next; end; end; end.
Program a5 ; USES QueueADT ; const MAX = 10000 ; type KeyType = integer ; ArrayIndex = 1..MAX ; SortingArray = array[ArrayIndex] of KeyType ; (******************************* SELECTION SORT ***********************************) procedure Swap(var i, j: KeyType) ; var temp : Keytype ; begin temp := i ; i := j ; j := temp ; end; { proc Swap } function Largest(A: SortingArray; i, j: ArrayIndex): ArrayIndex ; var k : ArrayIndex ; BigVal : KeyType ; begin BigVal := A[i] ; Largest := i ; if ( i < j ) then for k := (i + 1) to j do if ( A[k] > BigVal ) then BEGIN BigVal := A[k] ; Largest := k END { if } end; { fxn Largest } procedure SelectionSort(var S: SortingArray; n: integer) ; var j, k : ArrayIndex ; begin for j := n downto 2 do BEGIN k := Largest(S, 1, j) ; Swap(S[k], S[j]) END { for } end; { proc SelectionSort } (************************************ HEAP SORT ***********************************) (* SiftUp(A,i,n) preconditions: A is an array, [i..n] is the range to be reheapified. postconditions: A[i..n] has been reheapified using the SiftUp algorithm found in program 13.10 *) procedure SiftUp(var A: SortingArray; i, n: ArrayIndex); var j: ArrayIndex; RootKey: KeyType; Finished: Boolean; begin RootKey := A[i]; j := 2 * i ; Finished := ( j > n ) ; while not Finished do BEGIN if ( j < n ) then if ( A[j+1] > A[j] ) then inc(j) ; if A[j] <= RootKey then Finished := TRUE else begin A[i] := A[j] ; i := j ; j := 2 * i ; Finished := ( j > n) end { else } END; { while } A[i] := RootKey end; { proc SiftUp } (* HeapSort(A,n) preconditions: A is an array of size n storing values of type KeyType postconditions: A has been sorted using the HeapSort algorithm found in program 13.10 *) procedure HeapSort(var A: SortingArray; n: ArrayIndex); var i : ArrayIndex ; begin for i := (n div 2) downto 2 do SiftUp(A, i, n); for i := n downto 2 do begin SiftUp(A, 1, i) ; Swap(A[1], A[i]) ; end { for } end; { proc HeapSort } (************************************ QUICK SORT ***********************************) (* Partition(A,i,j) preconditions: A is an array, and [i..j] is a range of values to be partitioned postconditions: A[i..j] has been partitioned using the Partition algorithm found in program 13.15 *) procedure Partition(var A: SortingArray; var i, j: ArrayIndex); var Pivot : KeyType; begin Pivot := A[(i+j) div 2]; repeat while A[i] < Pivot do inc(i) ; while A[j] > Pivot do dec(j) ; if i <= j then begin Swap(A[i], A[j]) ; inc(i) ; dec(j) end; { if } until i > j end; { proc Partition } (* QuickSort(A,m,n) preconditions: A is an array, and [m..n] is a range of values to be sorted postconditions: A[m..n] has been sorted using the QuickSort algorithm found in program 13.14 *) procedure QuickSort(var A: SortingArray; m, n: ArrayIndex); var i, j : ArrayIndex ; begin if ( m < n ) then begin i := m; j := n; Partition(A, i, j); QuickSort(A, m, j); QuickSort(A, i, n) end { if } end; { proc QuickSort } (************************************ RADIX SORT ***********************************) (* Power(x, n) preconditions: x and n are integers postconditions: returns x^n HINT: you may need this when you are isolating the digits in RadixSort *) function power(x, n: integer): integer; var i, result : integer; begin result := 1; for i := 1 to n do result := result * x ; power := result end; { fxn Power } (* RadixSort(A,n) preconditions: A is an array of size n postconditions: A[1..n] has been sorted using the RadixSort algorithm *) procedure RadixSort(var A: SortingArray; n: ArrayIndex); var temp : KeyType ; i, j, k, l : ArrayIndex ; { loop indices } Qarray : array[0..19] of Queue ; begin for j := 0 to 19 do CreateQ(Qarray[j]) ; for j := 1 to n do Enq(Qarray[A[j] mod 10], A[j]) ; {*} for j := 0 to 9 do begin write( 'Qarray[', j, '] : ' ); PrintQ(Qarray[j]) end ; for i := 1 to 4 do BEGIN {*} writeln( 'i = ', i ) ; k := 0 ; for j := 0 to 9 do BEGIN l := j ; if ( i mod 2 = 0 ) then l := j + 10 else k := 10 ; while not IsEmpty( Qarray[l] ) do BEGIN temp := Deq(Qarray[l]) ; Enq(Qarray[temp div Power(10, i) mod 10 + k], temp) END { while } END; { for j } {*} for j := 0 to 19 do begin write( 'Qarray[', j, '] : ' ); PrintQ(Qarray[j]) end ; {*} readln ; END; { for i } k := 1 ; for j := 0 to 3 do BEGIN while not IsEmpty( Qarray[j] ) do BEGIN A[k] := Deq(Qarray[j]) ; inc(k) ; END { while } END; { for j } { for j := 0 to 19 do DestroyQ(Qarray[j]) ; } writeln( 'MemCheck: ', memcount, ' nodes not properly destroyed.' ) ; end; { proc RadixSort } (************************************ EXTRA STUFF ***********************************) function Random(var seed: integer): real ; const MODULUS = 35537 ; MULTIPLIER = 27193 ; INCREMENT = 13849 ; begin Random := ((MULTIPLIER * seed) + INCREMENT) mod MODULUS ; end; (* MakeRandomArray(A,n) preconditions: n is the size of array to create postconditions: A[1..n] has been initialized with random numbers in the range 1..MAXINT *) procedure MakeRandomArray(var A: SortingArray; n: ArrayIndex); var i : ArrayIndex ; begin for i := 1 to n do begin A[i] := trunc( MAXINT * Random(i) ) ; A[i] := Abs( A[i] ) end end; (* PrintArray(A,n) preconditions: A is an array of size n postconditions: A[1..n] is printed to the screen *) procedure PrintArray(var A: SortingArray; N: ArrayIndex); var j, k, size: ArrayIndex ; begin for j := 1 to ( N div 11 )+1 do BEGIN if ( j * 11 ) <= N then size := 11 else size := N - ( ( j - 1 ) * 11 ) ; writeln ; for k := 1 to size do write( A[( j - 1 ) * 11 + k]:6 ) ; writeln END { for } end; { proc PrintArray } (* IsSorted(A,n) preconditions: A is an array of size n postconditions: Returns TRUE if A[1..n] is sorted in ascending order. Returns FALSE otherwise *) function IsSorted(var A: SortingArray; n: ArrayIndex): boolean; var i : ArrayIndex ; begin IsSorted := TRUE; for i := 2 to n do if ( A[i] < A[i - 1] ) then begin IsSorted := FALSE; exit(IsSorted) end end; (*********************************** MAIN *************************************) var A: SortingArray; {Array to sort} n, {Number of elements in array} choice, {User input} i, {counter} t, {Number of trials} correct: integer; {Number of correct runs} begin repeat writeln; writeln('1. HeapSort an Array,'); writeln('2. QuickSort an Array,'); writeln('3. SelectionSort an Array,'); writeln('4. RadixSort an Array,'); writeln('5. Test HeapSort,'); writeln('6. Test QuickSort,'); writeln('7. Test SelectionSort,'); writeln('8. Test RadixSort,'); writeln('9. quit'); writeln; readln(choice); case choice of 1,2,3,4 : begin Writeln('This option creates a random array and sorts it'); Writeln; Write('How many elements in the array?'); readln(n); MakeRandomArray(A,n); Writeln; Writeln( 'The random array: ' ); if ( n <= 300 ) then PrintArray(A,n) else Writeln( '*** too BIG to print ***' ); Writeln; Write( 'Press Enter to sort' ); readln; case choice of 1: HeapSort(A,n) ; 2: QuickSort(A,1,n) ; 3: SelectionSort(A,n) ; 4: RadixSort(A,n) ; end; { case } writeln; Writeln( 'The sorted array: ' ); if ( n <= 300 ) then PrintArray(A,n) else Writeln( '*** too BIG to print ***' ); Writeln; Write( ' "IsSorted" returned ', IsSorted(A,n) ) ; readln; end; { 1,2,3,4 } 5,6,7,8 : begin Writeln( 'This option tests a sorting algorithm on a bunch of arrays.' ); Writeln; Write('How many elements in each array?'); readln(n); Write('How many tests do you want to do?'); readln(t); correct := 0; for i := 1 to t do begin MakeRandomArray(A,n); case choice of 5: HeapSort(A,n) ; 6: QuickSort(A,1,n) ; 7: SelectionSort(A,n) ; 8: RadixSort(A,n) ; end; { case } if ( IsSorted(A,n) ) then correct := correct + 1; end; { for } writeln; writeln('IsSorted returned TRUE ', correct, ' times in ', t, ' trials.'); readln; end; { 5,6,7,8 } end; { case choice } until (choice = 9); writeln( 'PROGRAM ENDED.' ) ; end.
Unit mte.core.baseclasses; {----------------------------------------------------------} { Developed by Muhammad Ajmal p } { ajumalp@gmail.com } { pajmal@hotmail.com } { ajmal@erratums.com } {----------------------------------------------------------} {$mode objfpc}{$H+} Interface Uses Classes, SysUtils, fpjson, jsonparser, variants, TypInfo, sqldb; Type TMTEBase = Class; eTJSONReader = (ejrLoadDefault, ejrLoadFromJSONString); TEBaseGetter = Function(Const aCode: eTJSONReader): TMTEBase Of Object; { TMTEBase } TMTEBase = Class(TObject) Strict Private Const cDATA_TYPE = 'DATA_TYPE'; cPROPERTY_NAME = 'Name'; cPROPERTY_VALUE = 'Value'; cPROPERTY_TYPE = 'Type'; cPROPERTY_INDEX = 'Index'; Var FJSONString: String; Procedure WriteToJSON(Var aJSONObject: TJSONObject; Const aName, aValue: String); Overload; Protected Procedure ReadFromJSON(Const aJSONObject: TJSONObject); Procedure WriteToJSON(Var aJSONObject: TJSONObject; Const aPropInfo: PPropInfo); Overload; Procedure WriteToJSON(Var aJSONObject: TJSONObject; Const aPropInfo: PPropInfo; aValue: Variant); Overload; Public Function QueryInterface(constref aID: TGuid; out aObj): Longint; Stdcall; Function _AddRef: Longint; Stdcall; Function _Release: Longint; Stdcall; Function ToJSON: TJSONStringType; Virtual; Procedure LoadFromJSON(Const aJSONData: TJSONStringType); Virtual; End; Implementation { TMTEBase } Procedure TMTEBase.WriteToJSON(Var aJSONObject: TJSONObject; Const aName, aValue: String); Begin aJSONObject.Add(aName, aValue); End; Procedure TMTEBase.ReadFromJSON(Const aJSONObject: TJSONObject); Var varPropType: TTypeKind; varPropName, varPropValue: String; varValue: Variant; varMethod: TMethod; Begin varPropType := TTypeKind(aJSONObject.Integers[cPROPERTY_TYPE]); varPropName := aJSONObject.Strings[cPROPERTY_NAME]; varPropValue := aJSONObject.Strings[cPROPERTY_VALUE]; Case varPropType Of tkInt64: Begin VarCast(varValue, varPropValue, varInt64); SetPropValue(Self, varPropName, varValue); End; tkInteger: Begin VarCast(varValue, varPropValue, varInteger); SetPropValue(Self, varPropName, varValue); End; tkEnumeration: SetEnumProp(Self, varPropName, varPropValue); tkFloat: Begin VarCast(varValue, varPropValue, varDouble); SetPropValue(Self, varPropName, varValue); End; tkBool: Begin VarCast(varValue, varPropValue, varboolean); SetPropValue(Self, varPropName, varValue); End; tkSet: ; tkClass: Begin FJSONString := varPropValue; Try varMethod.Code := GetPropInfo(Self, varPropName)^.GetProc; varMethod.Data := Pointer(Self); TEBaseGetter(varMethod)(ejrLoadFromJSONString); Finally FJSONString := EmptyStr; End; End; tkMethod: ; tkWChar, tkChar, tkUString, tkString, tkLString, tkWString, tkAString: SetPropValue(Self, varPropName, varPropValue); tkVariant: Begin Try VarCast(varValue, varPropValue, varVariant); Except On E: EVariantTypeCastError Do Begin If varPropValue <> '' Then Begin Try VarCast(varValue, varPropValue, varstring); Except Raise; End; End; End; End; SetPropValue(Self, varPropName, varValue); End; End; End; Procedure TMTEBase.WriteToJSON(Var aJSONObject: TJSONObject; Const aPropInfo: PPropInfo); Var varPropValue: Variant; varObject: TObject; Begin Case aPropInfo^.PropType^.Kind Of tkEnumeration, tkInteger, tkInt64, tkFloat, tkChar, tkString, tkAString, tkWChar, tkLString, tkWString, tkVariant, tkUString, tkBool: varPropValue := GetPropValue(Self, aPropInfo^.Name); tkClass: Begin varObject := GetObjectProp(Self, aPropInfo); Assert(varObject.InheritsFrom(TMTEBase), 'Unknown Class. Currently implimented for TEBaseClass only.'); varPropValue := (varObject As TMTEBase).ToJSON; End; Else Assert(False, 'Unknown Class'); End; WriteToJSON(aJSONObject, aPropInfo, varPropValue); End; Procedure TMTEBase.WriteToJSON(Var aJSONObject: TJSONObject; Const aPropInfo: PPropInfo; aValue: Variant); Begin WriteToJSON(aJSONObject, cPROPERTY_NAME, aPropInfo^.Name); WriteToJSON(aJSONObject, cPROPERTY_VALUE, VarToStr(aValue)); WriteToJSON(aJSONObject, cPROPERTY_TYPE, IntToStr(Ord(aPropInfo^.PropType^.Kind))); // WriteToJSON(aJSONObject, cPROPERTY_INDEX, IntToStr(aPropInfo.Index)); End; Function TMTEBase.QueryInterface(constref aID: TGuid; Out aObj): Longint; Stdcall; Begin If GetInterface(aID, aObj) Then Result := 0 Else Result := E_NOINTERFACE; End; Function TMTEBase._AddRef: Longint; Stdcall; Begin Result := 0; End; Function TMTEBase._Release: Longint; Stdcall; Begin Free; Result := 0; End; Function TMTEBase.ToJSON: TJSONStringType; Var varPropList: PPropList; iCnt, iPropCount: Integer; varJSONObject: TJSONObject; varJSONArray: TJSONArray; Begin iPropCount := GetTypeData(ClassInfo)^.PropCount; If iPropCount = 0 Then Exit(''); varPropList := Nil; GetMem(varPropList, iPropCount * SizeOf(PPropInfo)); iPropCount := GetPropList(ClassInfo, tkProperties, varPropList); varJSONArray := TJSONArray.Create; Try For iCnt := 0 To Pred(iPropCount) Do Begin // We export only published properties { Ajmal } If Not IsPublishedProp(Self, varPropList^[iCnt]^.Name) Then Continue; varJSONObject := TJSONObject.Create; WriteToJSON(varJSONObject, varPropList^[iCnt]); varJSONArray.Add(varJSONObject); End; Result := varJSONArray.AsJSON; Finally varJSONArray.Free; FreeMemory(varPropList); End; End; Procedure TMTEBase.LoadFromJSON(Const aJSONData: TJSONStringType); Var varJSONArray: TJSONArray; varJSONObject: TJSONObject; iCnt: Integer; Begin varJSONArray := GetJSON(aJSONData) As TJSONArray; Try For iCnt := 0 To Pred(varJSONArray.Count) Do Begin varJSONObject := varJSONArray.Items[iCnt] As TJSONObject; ReadFromJSON(varJSONObject); End; Finally varJSONArray.Free; End; End; End.
unit PingThread; interface uses Windows, Classes, PingSend, IPUtils, SysUtils, WinSock; type PPingResult = ^TPingResult; TPingResult = Record IPAdress:String; MacAdress:String; Exists:Boolean; end; type TPingThread = class(TThread) private { Private declarations } protected procedure Execute; override; public PingResult:TPingResult; Ready:Boolean; constructor Create(Ping:TPingResult); end; function SendARP(DestIp: DWORD; srcIP: DWORD; pMacAddr: pointer; PhyAddrLen: Pointer): DWORD;stdcall; external 'iphlpapi.dll'; implementation function MySendARP(const IPAddress: String): String; var DestIP: ULONG; MacAddr: Array [0..5] of Byte; MacAddrLen: ULONG; SendArpResult: Cardinal; begin DestIP := inet_addr(PAnsiChar(AnsiString(IPAddress))); MacAddrLen := Length(MacAddr); SendArpResult := SendARP(DestIP, 0, @MacAddr, @MacAddrLen); if SendArpResult = NO_ERROR then Result := Format('%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X', [MacAddr[0], MacAddr[1], MacAddr[2], MacAddr[3], MacAddr[4], MacAddr[5]]) else Result := ''; end; { TPingThread } constructor TPingThread.Create(Ping:TPingResult); begin PingResult.IPAdress := Ping.IPAdress; inherited Create(False); end; procedure TPingThread.Execute; var Ping:TPingSend; begin Ready := False; Ping := TPingSend.Create; Ping.Timeout := 500; PingResult.Exists := Ping.Ping(PingResult.IPAdress); if PingResult.Exists then PingResult.MacAdress := MySendARP(PingResult.IPAdress); Ping.Free; Ready := true; end; end.
unit UFrameSensor; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, UFormConv, IniFiles, SensorTypes; type TQuality = (qOK,qOutOfRange,qCommErr,qAnalogErr); TSampleData = record SumX,SumY:Double; CntX,CntY:Integer; LastQuality:TQuality; end; TFrameSensor = class(TFrame) GroupBox: TGroupBox; stStatus: TStaticText; cbOn: TCheckBox; BtnConv: TButton; procedure BtnConvClick(Sender: TObject); procedure cbOnClick(Sender: TObject); private { Private declarations } procedure CalcCoeffs; public { Public declarations } Section:String; X0,X1,Y0,Y1,Ymin:Double; CoeffK,CoeffB:Double; Host:String; Port,NetNumber:Integer; isSensorOn:Boolean; CurData,LatchedData:TSampleData; LastData:TAnalogData; procedure LoadFromIniSection(Ini:TIniFile; const Section:String); procedure WriteToIni(Ini:TIniFile); procedure TimerProc; procedure addSample(X:Double; Quality:TQuality); procedure LatchData; function GetLatchedY:TAnalogData; end; implementation {$R *.DFM} procedure TFrameSensor.BtnConvClick(Sender: TObject); var CF:TFormConv; MR:Integer; begin CF:=TFormConv.Create(Self); CF.X0:=X0; CF.Y0:=Y0; CF.X1:=X1; CF.Y1:=Y1; CF.Ymin:=Ymin; while True do begin MR:=CF.ShowModal; case MR of mrOK,mrYes: begin X0:=CF.X0; Y0:=CF.Y0; X1:=CF.X1; Y1:=CF.Y1; Ymin:=CF.Ymin; CalcCoeffs; if MR=mrOK then break; end; mrCancel: break; end; end; CF.Free; end; procedure TFrameSensor.CalcCoeffs; begin CoeffK:=(Y1-Y0)/(X1-X0); CoeffB:=Y0-CoeffK*X0; end; procedure TFrameSensor.LoadFromIniSection(Ini: TIniFile; const Section: String); begin Self.Section:=Section; isSensorOn:=Ini.ReadBool(Section,'On',True); NetNumber:=Ini.ReadInteger(Section,'NetNumber',0); cbOn.Checked:=isSensorOn; GroupBox.Caption:=' ¹'+IntToStr(NetNumber)+' '; X0:=Ini.ReadFloat(Section,'X0',0.0); Y0:=Ini.ReadFloat(Section,'Y0',0); X1:=Ini.ReadFloat(Section,'X1',1.0); Y1:=Ini.ReadFloat(Section,'Y1',65535); Ymin:=Ini.ReadFloat(Section,'Ymin',0); CalcCoeffs; Host:=Ini.ReadString(Section,'Host',''); Port:=Ini.ReadInteger(Section,'Port',0); end; procedure TFrameSensor.WriteToIni(Ini: TIniFile); begin Ini.WriteBool(Section,'On',isSensorOn); Ini.WriteFloat(Section,'X0',X0); Ini.WriteFloat(Section,'Y0',Y0); Ini.WriteFloat(Section,'X1',X1); Ini.WriteFloat(Section,'Y1',Y1); Ini.WriteFloat(Section,'Ymin',Ymin); end; procedure TFrameSensor.addSample(X: Double; Quality: TQuality); var Y:Double; begin if Quality<>qCommErr then begin CurData.SumX:=CurData.SumX+X; Inc(CurData.CntX); end; if Quality=qOK then begin Y:=CoeffK*X+CoeffB; if Y<Ymin then Quality:=qAnalogErr else begin CurData.SumY:=CurData.SumY+Y; Inc(CurData.CntY); end; end; CurData.LastQuality:=Quality; end; procedure TFrameSensor.LatchData; begin LatchedData:=CurData; FillChar(CurData,SizeOf(CurData),0); end; function TFrameSensor.GetLatchedY: TAnalogData; begin if (LatchedData.CntY>0) then begin Result.Value:=LatchedData.SumY/LatchedData.CntY; end else begin if isSensorOn then begin case LatchedData.LastQuality of qOK: SetErrADCComm(Result); qOutOfRange: SetErrADCRange(Result); qCommErr: SetErrADCComm(Result); qAnalogErr: SetErrAnalog(Result); end; end else SetSensorRepair(Result); end; LastData:=Result; end; procedure TFrameSensor.TimerProc; var S:String; begin if LatchedData.CntX>0 then begin S:=Format(' %.4e;%3d, ',[LatchedData.SumX/LatchedData.CntX, LatchedData.CntX]); if LatchedData.CntY>0 then S:=S+Format('%05.1f',[LatchedData.SumY/LatchedData.CntY]) else S:=S+GetADMsg(LastData); end else S:=GetADMsg(LastData); stStatus.Caption:=S; end; procedure TFrameSensor.cbOnClick(Sender: TObject); begin isSensorOn:=cbOn.Checked; end; end.
// PARAMS // - ORIFICE [inch] // - SPECIFIC GRAVITY [air=1] // - TEMPERATERUE [f] // - PRESSURE [psig] // - DIFF [diff] // - CONSTANT1 - constant1 => 4.026 // - CONSTANT2 - constant2 => 24 function ART_GASFLOWRATE(orifice, specific_gravity, temperature, pressure, diff, constant1 ,constant2 : real):real; var sqr : real ; e, g1, g3, g5, g7 : real; fb, fg, ftf, y2, fpv, c, gfr : real; fpv1, fpv2, fpv3, fpv4, fpv5, fpv6, fpv7 : real; begin // Get SQR if not (diff = 0) then begin sqr := exp(0.5 * ln((diff * pressure))); end; if not (orifice = 0) then begin // Start Orifice // # Basic Orifice Factor # // Get E e := orifice*(830-5000*orifice/constant1+9000*exp(2 * ln(orifice/constant1))-4200*exp(3 * ln(orifice/constant1))+530/exp(0.5 * ln(constant1))); // Get G1 g1 := 0.5993+0.007/constant1+(0.364+0.076/exp(0.5 * ln(constant1)))*exp(4 * ln(orifice/constant1)); // Get G3 g3 := 0; if((0.07+0.5/constant1-orifice/constant1) > 0) then begin g3 := 0.4*exp(0.5 * ln(1.6-1/constant1))*exp(2.5 * ln(0.07+0.5/constant1-orifice/constant1)); end; // Get G5 g5 := 0; if ((0.5-orifice/constant1) > 0) then begin g5 := (0.009+0.034/constant1)*(exp(1.5 * ln(0.5-orifice/constant1))); end; // Get G7 g7 := 0; if ((orifice/constant1-0.7) > 0) then begin g7 :=(65/exp(2 * ln(constant1))+3)*exp(2.5 * ln(orifice/constant1-0.7)); end; // # End of Basic Orifice Factor # // Get FB fb := 338.17*exp(2 * ln(orifice))*(g1+g3-g5+g7)/(1+15*e/(1000000*orifice)); // Get FG if not (specific_gravity = 0) then begin fg := 1/exp(0.5 * ln(specific_gravity)); end; // Get FTF if not (temperature = 0) then begin ftf := exp(0.5 * ln(520/(temperature+460))); end; // Get Y2 if not (pressure = 0) then begin y2 := exp(0.5 * ln((1+diff/(pressure*27.7)))) - (0.41+(0.35 * (exp(4 * ln(orifice/constant1))))) * diff/(pressure*27.7) / (1.3*(exp(0.5 * ln((1+diff/(pressure*27.7)))))); end; // Get FPV if not (pressure = 0) then begin fpv1 :=(temperature+460)/(170.491+307.344*specific_gravity); fpv2 :=(pressure+0.3)/(709.604-58.718*specific_gravity); fpv3 :=(0.27*fpv2)/(fpv1/0.99); fpv4 :=1+(0.2356+(-1.0467/fpv1)+(-0.5783/exp(3 * ln(fpv1))))*fpv3; fpv5 :=fpv4+(0.5353+(-0.6123/fpv1)+(0.6815/exp(3 *ln(fpv1))))*exp(2 * ln(fpv3)); fpv6 :=1/fpv5; fpv7 := exp(0.5 * ln(fpv6)); fpv := fpv7; end; // Get C if not (pressure = 0) then begin c := fb*fg*ftf*y2*fpv*(constant2/1000); end; // Get GFR [Gas Flow Rate] if not (pressure = 0) then begin gfr := sqr*c/1000; end; end; // end orifice // result GFR ART_GASFLOWRATE := gfr; end;
unit classe; interface uses Vcl.Dialogs; type TPessoa = class private FNome : string; FUsuario: string; protected function GetNome : String; virtual; procedure SetNome(AValue : String); virtual; function GetUsuario: string; virtual; procedure SetUsuario(const Value: string); virtual; public property Nome : string read GetNome write SetNome; property Usuario:string read GetUsuario write SetUsuario; procedure PronunciarIdioma();overload; procedure PronunciarIdioma(Idioma: String);overload; procedure PronunciarIdioma(Idioma: string ; vezes : Integer);overload; constructor Create(Sender: TObject); end; TPessoaFisica = class(TPessoa) private FCPF : string; FRG : string; protected function GetCPF: string; virtual; function GetRG: string; virtual; procedure SetCPF(const Value: string); virtual; procedure SetRG(const Value: string); virtual; function GetNome: string; override; public property CPF : string read GetCPF write SetCPF; property RG:string read GetRG write SetRG; private end; implementation { TPessoa } constructor TPessoa.Create(Sender: TObject); begin inherited Create(); FNome := 'Renato'; end; function TPessoa.GetNome: String; begin Result := FNome; end; function TPessoa.GetUsuario: string; begin Result := FUsuario; end; procedure TPessoa.PronunciarIdioma(Idioma: string; vezes: Integer); var I : Integer; begin for I := 0 to vezes do PronunciarIdioma(Idioma); end; procedure TPessoa.PronunciarIdioma; begin ShowMessage('Português'); end; procedure TPessoa.PronunciarIdioma(Idioma: String); begin ShowMessage(Idioma); end; procedure TPessoa.SetNome(AValue : String); begin FNome := AValue; end; procedure TPessoa.SetUsuario(const Value: string); begin FUsuario := Value; end; { TPessoaFisica } function TPessoaFisica.GetCPF: string; begin Result := FCPF; end; function TPessoaFisica.GetRG: string; begin Result := FRG; end; function TPessoaFisica.GetNome: string; begin Result := 'Classe base '+ inherited GetNome + 'Classe filha Pessoa Fisica'; end; procedure TPessoaFisica.SetCPF(const Value: string); begin FCPF := Value; end; procedure TPessoaFisica.SetRG(const Value: string); begin FRG := Value; end; end.
unit GMList; interface uses Collection; type TGMConnectOptions = (GMCO_HIGHPRIORITY, GMCO_NORMALPRIORITY, GMCO_IGNORE); TGameMasterListInfo = class public constructor Create( aName : string; anOptions : TGMConnectOptions ); private fName : string; fOptions : TGMConnectOptions; public property Name : string read fName; property Options : TGMConnectOptions read fOptions write fOptions; end; TGameMasterList = class public constructor Create; destructor Destroy; override; public function AddGameMaster( aName : string; anOptions : TGMConnectOptions; out Idx : integer ) : TGameMasterListInfo; procedure DeleteGameMaster( aName : string ); function MoveGameMasterUp( GameMaster : TGameMasterListInfo ) : boolean; function MoveGameMasterDown( GameMaster : TGameMasterListInfo ) : boolean; procedure ChangeGameMasterProperties( GameMaster : TGameMasterListInfo; NewOptions : TGMConnectOptions; out NewIdx : integer ); public procedure LoadFromString( const aStr : string ); procedure SaveToString( var aStr : string ); private fGameMasters : TSortedCollection; function getCount : integer; function getItemByIdx( Idx : integer ) : TGameMasterListInfo; function getItemByName( Name : string ) : TGameMasterListInfo; public property Count : integer read getCount; property Item[Idx : integer] : TGameMasterListInfo read getItemByIdx; property ItemByName[Name : string] : TGameMasterListInfo read getItemByName; private function Compare( Item1, Item2 : TObject) : integer; end; implementation uses sysutils, classes; // TGameMasterListInfo constructor TGameMasterListInfo.Create( aName : string; anOptions : TGMConnectOptions ); begin inherited Create; fName := aName; fOptions := anOptions; end; // TGameMasterList constructor TGameMasterList.Create; begin inherited Create; fGameMasters := TSortedCollection.Create( 20, rkBelonguer, Compare ); end; destructor TGameMasterList.Destroy; begin fGameMasters.Free; inherited; end; function TGameMasterList.AddGameMaster( aName : string; anOptions : TGMConnectOptions; out Idx : integer ) : TGameMasterListInfo; begin result := getItemByName( aName ); if result = nil then begin result := TGameMasterListInfo.Create( aName, anOptions ); Idx := fGameMasters.InsertPos( result ); fGameMasters.AtInsert( Idx, result ); end; end; procedure TGameMasterList.DeleteGameMaster( aName : string ); begin fGameMasters.Delete( getItemByName( aName )); end; function TGameMasterList.MoveGameMasterUp( GameMaster : TGameMasterListInfo ) : boolean; var Idx : integer; begin result := false; Idx := fGameMasters.IndexOf( GameMaster ); if (Idx > 0) and (TGameMasterListInfo(fGameMasters[pred(Idx)]).Options = GameMaster.Options) then begin result := true; fGameMasters.Exchange( Idx, pred(Idx) ); end; end; function TGameMasterList.MoveGameMasterDown( GameMaster : TGameMasterListInfo ) : boolean; var Idx : integer; begin result := false; Idx := fGameMasters.IndexOf( GameMaster ); if (Idx <> -1) and (Idx < pred(fGameMasters.Count) ) and (TGameMasterListInfo(fGameMasters[succ(Idx)]).Options = GameMaster.Options) then begin result := true; fGameMasters.Exchange( Idx, succ(Idx) ); end; end; procedure TGameMasterList.ChangeGameMasterProperties( GameMaster : TGameMasterListInfo; NewOptions : TGMConnectOptions; out NewIdx : integer ); begin if GameMaster.Options <> NewOptions then begin fGameMasters.Extract( GameMaster ); GameMaster.Options := NewOptions; NewIdx := fGameMasters.InsertPos( GameMaster ); fGameMasters.AtInsert( NewIdx, GameMaster ); end else NewIdx := fGameMasters.IndexOf( GameMaster ); end; procedure TGameMasterList.LoadFromString( const aStr : string ); var StrList : TStringList; GMCount : integer; Name : string; Opt : TGMConnectOptions; i : integer; begin try StrList := TStringList.Create; try StrList.Text := aStr; try GMCount := StrToInt( StrList.Values['Count'] ); except GMCount := 0; end; fGameMasters.DeleteAll; for i := 0 to pred(GMCount) do begin try Name := StrList.Values['GMName' + IntToStr(i)]; try Opt := TGMConnectOptions( StrToInt( StrList.Values['GMOptions' + IntToStr(i)])); except Opt := GMCO_NORMALPRIORITY; end; fGameMasters.Insert( TGameMasterListInfo.Create( Name, Opt ) ); except end; end; finally StrList.Free; end; except end; end; procedure TGameMasterList.SaveToString( var aStr : string ); var StrList : TStringList; i : integer; begin StrList := TStringList.Create; try StrList.Values['Count'] := IntToStr(fGameMasters.Count); for i := 0 to pred(fGameMasters.Count) do begin StrList.Values['GMName' + IntToStr(i)] := TGameMasterListInfo(fGameMasters[i]).Name; StrList.Values['GMOptions' + IntToStr(i)] := IntToStr(integer(TGameMasterListInfo(fGameMasters[i]).Options)); end; aStr := StrList.Text; finally StrList.Free; end; end; function TGameMasterList.getCount : integer; begin result := fGameMasters.Count; end; function TGameMasterList.getItemByIdx( Idx : integer ) : TGameMasterListInfo; begin result := TGameMasterListInfo(fGameMasters[Idx]); end; function TGameMasterList.getItemByName( Name : string ) : TGameMasterListInfo; var found : boolean; i : integer; begin found := false; i := 0; while (i < fGameMasters.Count) and not found do begin found := TGameMasterListInfo(fGameMasters[i]).Name = Name; inc( i ); end; if found then result := TGameMasterListInfo(fGameMasters[pred(i)]) else result := nil; end; function TGameMasterList.Compare( Item1, Item2 : TObject) : integer; begin if TGameMasterListInfo(Item1).Options > TGameMasterListInfo(Item2).Options then result := 1 else if TGameMasterListInfo(Item1).Options < TGameMasterListInfo(Item2).Options then result := -1 else result := 0; end; end.
unit BulkGeocodingRequestUnit; interface uses REST.Json.Types, SysUtils, JSONNullableAttributeUnit, HttpQueryMemberAttributeUnit, GenericParametersUnit, NullableBasicTypesUnit; type TAddressInfo = class(TGenericParameters) private [JSONName('address')] [Nullable] FAddress: NullableString; [JSONName('email')] [Nullable] FEmail: NullableString; [JSONName('username')] [Nullable] FUsername: NullableString; [JSONName('web-site')] [Nullable] FWebSite: NullableString; [JSONName('phone')] [Nullable] FPhone: NullableString; [JSONName('first_name')] [Nullable] FFirstName: NullableString; [JSONName('last_name')] [Nullable] FLastName: NullableString; public constructor Create(Address, EMail, Username, Website, Phone, FirstName, LastName: String); reintroduce; property Address: NullableString read FAddress write FAddress; property Email: NullableString read FEmail write FEmail; property Username: NullableString read FUsername write FUsername; property WebSite: NullableString read FWebSite write FWebSite; property Phone: NullableString read FPhone write FPhone; property FirstName: NullableString read FFirstName write FFirstName; property LastName: NullableString read FLastName write FLastName; end; TAddressInfoArray = TArray<TAddressInfo>; TBulkGeocodingRequest = class(TGenericParameters) private [JSONName('rows')] FAddresses: TArray<TAddressInfo>; public constructor Create(); override; destructor Destroy; override; procedure AddAddress(Address: TAddressInfo); property Addresses: TArray<TAddressInfo> read FAddresses; end; implementation procedure TBulkGeocodingRequest.AddAddress(Address: TAddressInfo); begin SetLength(FAddresses, Length(FAddresses) + 1); FAddresses[High(FAddresses)] := Address; end; constructor TBulkGeocodingRequest.Create(); begin inherited Create; SetLength(FAddresses, 0); end; destructor TBulkGeocodingRequest.Destroy; var i: integer; begin for i := Length(FAddresses) - 1 downto 0 do FreeAndNil(FAddresses[i]); inherited; end; { TAddressInfo } constructor TAddressInfo.Create( Address, EMail, Username, Website, Phone, FirstName, LastName: String); begin FAddress := Address; FEmail := EMail; FUsername := Username; FWebSite := Website; FPhone := Phone; FFirstName := FirstName; FLastName := LastName; end; end.
program JQMobileDemo; {$mode objfpc}{$H+} {$hints off} {$notes off} { Raspberry Pi 3 Application } { Add your program code below, add additional units to the "uses" section if } { required and create new units by selecting File, New Unit from the menu. } { } { To compile your program select Run, Compile (or Run, Build) from the menu. } uses RaspberryPi3, GlobalConfig, GlobalConst, GlobalTypes, Platform, Threads, SysUtils, Classes, uWebSocket, uFTP, uXMLParser, Console, uTFTP, uLog, Winsock2, HTTP, Ultibo; const ny : array [boolean] of string = ('NO', 'YES'); type { THelper } THelper = class procedure WSText (aThread : TWSThread; aMsg : TMemoryStream); procedure WSPing (aThread : TWSThread; aText : string); procedure WSPong (aThread : TWSThread; aText : string); procedure WSClose (aThread : TWSThread; aCode : integer; aText : string); procedure WSNewClient (aThread : TWSThread); procedure WSFinishClient (aThread : TWSThread); end; { THTTPServer } THTTPServer = class (THTTPListener) Doc : THTTPDocument; Parser : TXMLParser; procedure DoToken (Sender : TObject; Token : TTokens; TokenName : string; Tag : TTagTypes; Params : TList); function DoGet (aHost: THTTPHost; aDocument: THTTPDocument; aRequest: THTTPServerRequest; aResponse: THTTPServerResponse): Boolean; public constructor Create; destructor Destroy; override; end; var Console1, Console2, Console3 : TWindowHandle; IPAddress : string; aHTTP : THTTPServer; aWS : TWSServer; aFTP : TFTPserver; ch : char; aHelper : THelper; a : string; v : integer; // General routines procedure Log1 (s : string); begin ConsoleWindowWriteLn (Console1, s); end; procedure Log2 (s : string); begin ConsoleWindowWriteLn (Console2, s); end; procedure Log3 (s : string); begin ConsoleWindowWriteLn (Console3, s); end; procedure Msg2 (Sender : TObject; s : string); begin Log2 ('TFTP - ' + s); end; function WaitForIPComplete : string; var TCP : TWinsock2TCPClient; begin TCP := TWinsock2TCPClient.Create; Result := TCP.LocalAddress; if (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') then begin while (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') do begin sleep (1000); Result := TCP.LocalAddress; end; end; TCP.Free; end; procedure WaitForSDDrive; begin while not DirectoryExists ('C:\') do sleep (500); end; procedure ShowSlider; begin ConsoleWindowSetXY (Console3, 1, 10); Log3 ('Slider : ' + v.ToString + ' '); end; { THTTPServer } procedure THTTPServer.DoToken (Sender: TObject; Token: TTokens; TokenName: string; Tag: TTagTypes; Params: TList); var aParam : TParam; i : integer; begin if TokenName = 'value' then begin for i := 0 to Params.Count - 1 do begin aParam := TParam (Params[i]); if aParam.Name = 'value' then begin v := aParam.IntValue; ShowSlider; end; end; end; end; function THTTPServer.DoGet (aHost: THTTPHost; aDocument: THTTPDocument; aRequest: THTTPServerRequest; aResponse: THTTPServerResponse): Boolean; var s, p : string; f : TFileStream; x : integer; MimeType, ext : string; begin Result := false; aResponse.Version := HTTP_VERSION; aResponse.Status := HTTP_STATUS_OK; aResponse.Reason := HTTP_REASON_200; if aRequest.Path = '/' then // base page begin aResponse.ContentString := '<!DOCTYPE html>'#10 + '<html class="ui-mobile">'#10 + '<head>'#10 + '<title>Slider Test</title>' + '<meta name="viewport" content="width=device-width, initial-scale=1"/>'#10 + '<link rel="stylesheet" href="jquery.mobile-1.4.5.min.css"/>'#10 + '<link rel="stylesheet" href="themes.min.css"/>'#10 + '<script src="jquery-1.7.1.min.js"></script>'#10 + '<script src="jquery.mobile-1.4.5.min.js"></script>'#10 + '<script src="misc.logic.js"></script>'#10 + '</head>'#10 + '<body onload="Init (''' + IPAddress + ':' + aWS.Port.ToString + ''')">'#10 + '<div data-role="page">'#10 + '<form>'#10 + '<h1>Slider Test</h1>'#10 + '<input id="sdr1" min="0" max="100" value="' + v.ToString + '" type="range" data-highlight="true" data-theme="c"/>'#10 + '</form>'#10 + '</div>'#10 + '</body>'#10 + '</html>'#10; end else if aRequest.Path <> '' then begin p := aRequest.Path; for x := 1 to length (p) do if p[x] = '/' then p[x] := '\'; if p[1] = '\' then p := Copy (p, 2, length (p) - 1); s := 'c:\wwwroot\' + p; if FileExists (s) then begin try HTTPPathExtractextension (s, ext); MimeType := aHost.ResolveMimeType (ext); aResponse.SetHeader (HTTP_ENTITY_HEADER_CONTENT_TYPE, MimeType); f := TFileStream.Create (s, fmOpenRead or fmShareDenyNone); aResponse.Version := HTTP_VERSION; aResponse.Status := HTTP_STATUS_OK; aResponse.Reason := HTTP_REASON_200; aResponse.ContentStream := f; except aResponse.Version := HTTP_VERSION; aResponse.Status := HTTP_STATUS_INTERNAL_SERVER_ERROR; aResponse.Reason := HTTP_REASON_500; aResponse.ContentString := '<html><head><title>Error ' + HTTPStatusToString (aResponse.Status) + ' (' + aResponse.Reason + ')</title></head><body>Error ' + HTTPStatusToString(AResponse.Status) + ' (' + AResponse.Reason + ')</body></html>' + HTTP_LINE_END; end; end else begin aResponse.Version := HTTP_VERSION; aResponse.Status := HTTP_STATUS_NOT_FOUND; aResponse.Reason := HTTP_REASON_404; aResponse.ContentString := '<html><head><title>Error ' + HTTPStatusToString (AResponse.Status) + ' (' + AResponse.Reason + ')</title></head><body>Error ' + HTTPStatusToString(AResponse.Status) + ' (' + AResponse.Reason + ')</body></html>' + HTTP_LINE_END; end; end else begin aResponse.Version := HTTP_VERSION; aResponse.Status := HTTP_STATUS_NOT_FOUND; aResponse.Reason := HTTP_REASON_404; aResponse.ContentString := '<html><head><title>Error ' + HTTPStatusToString (AResponse.Status) + ' (' + AResponse.Reason + ')</title></head><body>Error ' + HTTPStatusToString(AResponse.Status) + ' (' + AResponse.Reason + ')</body></html>' + HTTP_LINE_END; end; Result := true; end; constructor THTTPServer.Create; begin inherited Create; Parser := TXMLParser.Create (Self); Parser.OnToken := @DoToken; Doc := THTTPDocument.Create; Doc.OnGet := @DoGet; RegisterDocument ('', Doc); end; destructor THTTPServer.Destroy; begin Parser.Free; DeRegisterDocument ('', Doc); Doc.Free; inherited Destroy; end; { THelper } procedure THelper.WSText (aThread: TWSThread; aMsg: TMemoryStream); var bThread : TWSThread; begin aHTTP.Parser.Parse (aMsg); bThread := TWSThread (aWS.Threads.First);; while bThread <> nil do begin if aThread <> bThread then bThread.SendString (aMsg); bThread := TWSThread (bThread.Next); end; end; procedure THelper.WSPing (aThread: TWSThread; aText: string); begin Log ('Web Socket PING Received : ' + aText + '.'); end; procedure THelper.WSPong (aThread: TWSThread; aText: string); begin Log ('Web Socket PONG Received : ' + aText + '.'); end; procedure THelper.WSClose (aThread: TWSThread; aCode: integer; aText: string); begin Log ('Web Socket CLOSE Received Code : ' + aCode.ToString + ', Reason : ' + aText + '.'); end; procedure THelper.WSNewClient (aThread: TWSThread); begin Log ('New Web Socket Created.'); end; procedure THelper.WSFinishClient (aThread: TWSThread); begin Log ('Web Socket Finished With.'); end; begin Console1 := ConsoleWindowCreate (ConsoleDeviceGetDefault, CONSOLE_POSITION_LEFT, true); Console2 := ConsoleWindowCreate (ConsoleDeviceGetDefault, CONSOLE_POSITION_TOPRIGHT, false); Console3 := ConsoleWindowCreate (ConsoleDeviceGetDefault, CONSOLE_POSITION_BOTTOMRIGHT, false); SetLogProc (@Log1); Log3 ('JQ Mobile with Web Sockets Test.'); WaitForSDDrive; Log2 ('SD Drive ready.'); Log2 (''); Log3 (''); IPAddress := WaitForIPComplete; Log3 ('1) Open up a web browser.'); Log3 ('2) Enter ' + IPAddress + ' in the location bar. You should see a slider.'); Log3 ('3) Open up another web browser.'); Log3 ('4) Again enter ' + IPAddress + ' in the location bar.'); Log3 (''); Log3 ('Moving the slider in one broswer should change the position of the slider in the other browser.'); Log2 ('TFTP - Syntax "tftp -i ' + IPAddress + ' put kernel7.img"'); SetOnMsg (@Msg2); Log2 (''); aWS := TWSServer.Create; aWS.Port := 8002; aHelper := THelper.Create; aWS.OnClose := @aHelper.WSClose; aWS.OnPing := @aHelper.WSPing; aWS.OnPong := @aHelper.WSPong; aWS.OnText := @aHelper.WSText; aWS.OnNewClient := @aHelper.WSNewClient; aWS.OnFinishClient := @aHelper.WSFinishClient; aWS.Start; aHTTP := THTTPServer.Create; aHTTP.BoundPort := 80; aHTTP.Active := true; v := 34; // initial slider value ShowSlider; aFTP := TFTPServer.Create; // add user accounts and options aFTP.AddUser ('admin', 'admin', 'C:\').Options := [foCanAddFolder, foCanChangeFolder, foCanDelete, foCanDeleteFolder, foRebootOnImg]; aFTP.AddUser ('user', '', 'C:\').Options := [foRebootOnImg]; aFTP.AddUser ('anonymous', '', 'C:\').Options := [foRebootOnImg]; // use standard FTP port aFTP.BoundPort := 21; // set it running aFTP.Active := true; ch := #0; while true do begin if ConsoleGetKey (ch, nil) then case ch of 'C' : ConsoleWindowClear (Console1); 'Q', 'q' : break; end; end; Log ('Halted.'); ThreadHalt (0); end.
unit Lander; interface uses Windows, Classes, Graphics, GameTypes, LanderTypes, Filters, VCLUtils; type PTextRenderingInfo = ^TTextRenderingInfo; TTextRenderingInfo = record x, y : integer; text : string; end; type PTextRenderingInfoArray = ^TTextRenderingInfoArray; TTextRenderingInfoArray = array [0..0] of TTextRenderingInfo; {$IFDEF SHOWCNXS} type TCnxRenderingData = record drawimg : boolean; x, y : integer; end; type PCnxRenderingDataArray = ^TCnxRenderingDataArray; TCnxRenderingDataArray = array [0..0] of TCnxRenderingData; type TCnxsRenderingData = record drawimg : boolean; x, y : integer; count : integer; renderdata : PCnxRenderingDataArray; end; {$ENDIF} type TLander = class(TInterfacedObject, IGameDocument, ICoordinateConverter) public constructor Create(const Map : ILanderMap); destructor Destroy; override; procedure DestroyAll; private // IGameDocument procedure RenderSnapshot(const view : IGameView; const ClipRect : TRect; snap : TCanvasImage); function ClipMovement(const view : IGameView; var dx, dy : integer) : boolean; function CreateFocus(const view : IGameView) : IGameFocus; procedure SetImageSuit( ImageSuit : integer ); private // ICoordinateConverter function ObjectToMap(const view : IGameView; x, y : integer; out i, j : integer; checkbase : boolean) : boolean; function ScreenToMap(const view : IGameView; x, y : integer; out i, j : integer) : boolean; function MapToScreen(const view : IGameView; i, j : integer; out x, y : integer) : boolean; procedure GetViewRegion(const view : IGameView; out imin, jmin, imax, jmax : integer); private fMap : ILanderMap; procedure CalculateFirstGrid(const view : IGameView; var x, y : integer; out i, j : integer); private fLastZoom : TZoomRes; fLastRotation : TRotation; fSpareCache : array [TZoomRes, TRotation] of TGameImage; fDownloadSign : array [TZoomRes, TRotation] of TGameImage; fShadeCache : array [TZoomRes, TRotation] of TGameImage; fRedShadeCache : array [TZoomRes, TRotation] of TGameImage; fBlackShadeCache : array [TZoomRes, TRotation] of TGameImage; fCnxSourceDownCache : array [TZoomRes, TRotation] of TGameImage; fCnxSourceTopCache : array [TZoomRes, TRotation] of TGameImage; fCnxDestDownCache : array [TZoomRes, TRotation] of TGameImage; fCnxDestTopCache : array [TZoomRes, TRotation] of TGameImage; private fTextsToRenderCount : integer; fTextsToRenderAlloc : integer; fTextsToRender : PTextRenderingInfoArray; procedure AddTextToRender(const texttorender : TTextRenderingInfo); {$IFDEF SHOWCNXS} private fCnxsRenderingData : TCnxsRenderingData; {$ENDIF} private function CheckPoint(const view : IGameView; x, y, i, j : integer) : boolean; function CheckBuildingBase(const view : IGameView; x, y : integer; out i, j : integer) : boolean; end; implementation uses SysUtils, AxlDebug, MathUtils, GlassedBuffers, SpriteImages, ColorTableMgr, MapTypes, CanvasBmp, Literals {$IFDEF PROFILES}, Profiler, IsoProfile{$ENDIF}; const cAlpha = 1; // Utils >> function ClipInteger(var i : integer; min, max : integer) : boolean; begin Result := true; if i < min then i := min else if i > max then i := max else Result := false; end; function max(x, y : integer) : integer; begin if x >= y then Result := x else Result := y; end; function min(x, y : integer) : integer; begin if x <= y then Result := x else Result := y; end; procedure RotateItem(var item : TItemInfo; rotation : TRotation); var tmp : integer; begin case rotation of drNorth: ; drEast: begin tmp := item.r; item.r := item.c; item.c := pred(item.size) - tmp; end; drSouth: begin item.r := pred(item.size) - item.r; item.c := pred(item.size) - item.c; end; else // drWest begin tmp := item.r; item.r := pred(item.size) - item.c; item.c := tmp; end; end; end; // Cohen-Sutherland's algorithm function ClipLine(var srcx, srcy, destx, desty : integer; const ClipRect : TRect) : boolean; type TEdge = (edTop, edBottom, edLeft, edRight); type TPointCode = set of TEdge; procedure CodePoint(x, y : integer; out Code : TPointCode); begin Code := []; if x < ClipRect.Left then Code := [edLeft] else if x > ClipRect.Right then Code := [edRight]; if y < ClipRect.Top then Code := Code + [edTop] else if y > ClipRect.Bottom then Code := Code + [edBottom] end; var srccode, destcode : TPointCode; outcode : TPointCode; x, y : single; begin CodePoint(srcx, srcy, srccode); CodePoint(destx, desty, destcode); while (srccode*destcode = []) and ((srccode <> []) or (destcode <> [])) do begin if srccode <> [] then outcode := srccode else outcode := destcode; if edTop in outcode then begin x := srcx + (destx - srcx)*(ClipRect.Top - srcy)/(desty - srcy); y := ClipRect.Top; end else if edBottom in outcode then begin x := srcx + (destx - srcx)*(ClipRect.Bottom - srcy)/(desty - srcy); y := ClipRect.Bottom; end else if edLeft in outcode then begin x := ClipRect.Left; y := srcy + (desty - srcy)*(ClipRect.Left - srcx)/(destx - srcx); end else begin x := ClipRect.Right; y := srcy + (desty - srcy)*(ClipRect.Right - srcx)/(destx - srcx); end; if outcode = srccode then begin srcx := round(x); srcy := round(y); CodePoint(srcx, srcy, srccode) end else begin destx := round(x); desty := round(y); CodePoint(destx, desty, destcode) end; end; if (srccode = []) and (destcode = []) then Result := true else Result := false; end; function ClipDrawLine(const Canvas : TBufferCanvas; x1, y1, x2, y2 : integer; const ClipRect : TRect) : boolean; var srcx, srcy : integer; destx, desty : integer; begin srcx := x1; srcy := y1; destx := x2; desty := y2; { if ClipLine(srcx, srcy, destx, desty, ClipRect) then begin } Canvas.MoveTo(srcx, srcy); Canvas.LineTo(destx, desty); Result := true; { end else Result := false; } end; // TLander constructor TLander.Create(const Map : ILanderMap); begin inherited Create; fMap := Map; end; destructor TLander.Destroy; begin assert(RefCount = 0); {$IFDEF SHOWCNXS} FreeBuffer; {$ENDIF} if fTextsToRender<>nil //.rag then freemem(fTextsToRender); {$IFDEF SHOWCNXS} if fCnxsRenderingData.count <> 0 then freemem(fCnxsRenderingData.renderdata); {$ENDIF} inherited; end; procedure TLander.RenderSnapshot(const view : IGameView; const ClipRect : TRect; snap : TCanvasImage); var x, y : integer; i, j : integer; y1, y2 : integer; u : integer; focus : IGameFocus; Imager : IImager; cols : integer; rows : integer; zoom : TZoomRes; rotation : TRotation; smalltext : string; function FilterObjectPalette(img : TGameImage; const obj : TObjInfo) : TPaletteInfo; begin with obj do if loReddened in Options then Result := img.GetFilteredPalette(pfReddenPalette, [0]) else if loGrayed in Options then Result := img.GetFilteredPalette(pfColorToGray, [0]) else if loRedded in Options then Result := img.GetFilteredPalette(pfRedFilter, [0]) else if loGreened in Options then Result := img.GetFilteredPalette(pfGreenFilter, [0]) else if loDarkened in Options then Result := img.GetFilteredPalette(pfDarkenPalette, [0]) else if loColorTinted in Options then Result := img.GetFilteredPalette(pfTintPalette, [shadeid and $FF, shadeid shr 8 and $FF, shadeid shr 16 and $FF, 0.5]) else Result := nil; end; procedure DrawSpareImage(x, y, Size : integer; const obj : TObjInfo); var i, j : integer; xx, xi : integer; yy, yi : integer; PaletteInfo : TPaletteInfo; begin xi := x; yi := y; if fSpareCache[zoom, rotation] = nil then fSpareCache[zoom, rotation] := Imager.GetSpareImage; if fDownloadSign[zoom, rotation] = nil then fDownloadSign[zoom, rotation] := Imager.GetDownloadImage; PaletteInfo := FilterObjectPalette(fSpareCache[zoom, rotation], obj); for i := 0 to pred(Size) do begin xx := x; yy := y; for j := 0 to pred(Size) do begin if loGlassed in obj.Options then fSpareCache[zoom, rotation].Draw(xx, yy + u - fSpareCache[zoom, rotation].Height, cAlpha, 0, ClipRect, snap, PaletteInfo) else fSpareCache[zoom, rotation].Draw(xx, yy + u - fSpareCache[zoom, rotation].Height, 0, 0, ClipRect, snap, PaletteInfo); inc(xx, 2*u); dec(yy, u); end; inc(x, 2*u); inc(y, u); end; PaletteInfo := FilterObjectPalette(fDownloadSign[zoom, rotation], obj); if loGlassed in obj.Options then fDownloadSign[zoom, rotation].Draw(xi + (4*u*Size - fDownloadSign[zoom, rotation].Width) div 2, yi - fDownloadSign[zoom, rotation].Height + u, cAlpha, 0, ClipRect, snap, PaletteInfo) else fDownloadSign[zoom, rotation].Draw(xi + (4*u*Size - fDownloadSign[zoom, rotation].Width) div 2, yi - fDownloadSign[zoom, rotation].Height + u, 0, 0, ClipRect, snap, PaletteInfo); end; procedure DrawObject(x, y, Size : integer; const obj : TObjInfo); const corSize = 4; var img : TGameImage; delta : integer; _2Delta : integer; dh : integer; textrendinfo : TTextRenderingInfo; PaletteInfo : TPaletteInfo; shadeimg : TGameImage; Temp1, Temp2, Temp3 : integer; begin with obj do begin img := Imager.GetObjectImage(id, angle); delta := u*Size; _2Delta := 2*delta; if img <> nil then dh := img.Height - delta else dh := 2*u*Size - delta; if loGrated in Options then with snap do begin //Pen.Color := $0088BBBB; Canvas.Pen.Color := clLime; Canvas.Pen.Width := 2; // corner A Temp1 := pred(x); ClipDrawLine(Canvas, Temp1, y - 2, Temp1 + _2Delta div corSize, y - delta div corSize - 2, ClipRect); ClipDrawLine(Canvas, Temp1, y - 2, Temp1, y - 1 - dh div corSize - 2, ClipRect); // corner B ClipDrawLine(Canvas, Temp1, y - 1 - dh - 2, Temp1 + _2Delta div corSize, y - 1 - dh - delta div corSize - 2, ClipRect); ClipDrawLine(Canvas, Temp1, y - 1 - dh - 2, Temp1, y - 1 - dh + dh div corSize - 2, ClipRect); // corner G Temp2 := Temp1 + _2Delta; ClipDrawLine(Canvas, Temp2, y - delta - 2, Temp1 + _2Delta - _2Delta div corSize, y - delta + delta div corSize - 2, ClipRect); ClipDrawLine(Canvas, Temp2, y - delta - 2, Temp1 + _2Delta + _2Delta div corSize, y - delta + delta div corSize - 2, ClipRect); ClipDrawLine(Canvas, Temp2, y - delta - 2, Temp1 + _2Delta, y - delta - dh div corSize - 2, ClipRect); // corner H ClipDrawLine(Canvas, Temp2, y - delta - dh - 2, Temp2 - _2Delta div corSize, y - delta + delta div corSize - dh - 2, ClipRect); ClipDrawLine(Canvas, Temp2, y - delta - dh - 2, Temp2 + _2Delta div corSize, y - delta + delta div corSize - dh - 2, ClipRect); ClipDrawLine(Canvas, Temp2, y - delta - dh - 2, Temp2, y - delta - dh + dh div corSize - 2, ClipRect); // corner E Temp3 := Temp1 + 4*delta; ClipDrawLine(Canvas, Temp3, y - 2, Temp3 - _2Delta div corSize, y - delta div corSize - 2, ClipRect); ClipDrawLine(Canvas, Temp3, y - 2, Temp3, y - dh div corSize - 2, ClipRect); // corner F ClipDrawLine(Canvas, Temp3, y - dh - 2, Temp3 - _2Delta div corSize, y - dh - delta div corSize - 2, ClipRect); ClipDrawLine(Canvas, Temp3, y - dh - 2, Temp3, y - dh + dh div corSize - 2, ClipRect); { Pen.Color := clLime; MoveTo(x - 1, y); LineTo(x - 1 + 2*delta, y - 1 - delta); LineTo(x - 1 + 4*delta, y - 1); MoveTo(x - 1 + 2*delta, y - 1 - delta); LineTo(x - 1 + 2*delta, y - 1 - delta - dh); LineTo(x - 1 + 4*delta, y - 1 - dh); MoveTo(x - 1 + 2*delta, y - 1 - delta - dh); LineTo(x - 1, y - 1 - dh); } end; if img <> nil then begin PaletteInfo := FilterObjectPalette(img, obj); if loGlassed in Options then img.Draw(x, y + u*Size - img.Height, cAlpha, Frame, ClipRect, snap, PaletteInfo) else img.Draw(x, y + u*Size - img.Height, 0, Frame, ClipRect, snap, PaletteInfo); end else DrawSpareImage(x, y, size, obj); if loShaded in Options then begin if fShadeCache[zoom, rotation] = nil then fShadeCache[zoom, rotation] := Imager.GetShadeImage; fShadeCache[zoom, rotation].Draw(x + sxshift, y + syshift + u*Size - fShadeCache[zoom, rotation].Height, cAlpha, 0, ClipRect, snap, nil); end; if loRedShaded in Options then begin if fRedShadeCache[zoom, rotation] = nil then fRedShadeCache[zoom, rotation] := Imager.GetRedShadeImage; fRedShadeCache[zoom, rotation].Draw(x + sxshift, y + syshift + u*Size - fRedShadeCache[zoom, rotation].Height, cAlpha, 0, ClipRect, snap, nil); end; if loBlackShaded in Options then begin if fBlackShadeCache[zoom, rotation] = nil then fBlackShadeCache[zoom, rotation] := Imager.GetBlackShadeImage; fBlackShadeCache[zoom, rotation].Draw(x + sxshift, y + syshift + u*Size - fBlackShadeCache[zoom, rotation].Height, cAlpha, 0, ClipRect, snap, nil); end; if loColorShaded in Options then begin shadeimg := Imager.GetObjectImage(shadeid, agN); if shadeimg <> nil then shadeimg.Draw(x + sxshift, y + syshift + u*Size - shadeimg.Height, cAlpha, 0, ClipRect, snap, nil); end; if loGrated in Options then with snap do begin // Aqui se dibuja el canjon de selecion // corner A ClipDrawLine(Canvas, x - 1, y - 2, x - 1 + _2Delta div corSize, y + delta div corSize - 2, ClipRect); // corner B ClipDrawLine(Canvas, x - 1, y - 1 - dh - 2, x - 1 + _2Delta div corSize, y - 1 - dh + delta div corSize - 2, ClipRect); { // corner C MoveTo(x - 1 + 2*delta, y + delta - dh - 2); LineTo(x - 1 + 2*delta - 2*delta div corSize, y - dh + delta - delta div corSize - 2); MoveTo(x - 1 + 2*delta, y + delta - dh - 2); LineTo(x - 1 + 2*delta + 2*delta div corSize, y - dh + delta - delta div corSize - 2); MoveTo(x - 1 + 2*delta, y + delta - dh - 2); LineTo(x - 1 + 2*delta, y + delta - dh + dh div corSize - 2); } // corner D ClipDrawLine(Canvas, x - 1 + _2Delta, y + delta - 2, x - 1 + _2Delta - _2Delta div corSize, y + delta - delta div corSize - 2, ClipRect); ClipDrawLine(Canvas, x - 1 + _2Delta, y + delta - 2, x - 1 + _2Delta + _2Delta div corSize, y + delta - delta div corSize - 2, ClipRect); ClipDrawLine(Canvas, x - 1 + _2Delta, y + delta - 2, x - 1 + _2Delta, y + delta - dh div corSize - 2, ClipRect); // corner E ClipDrawLine(Canvas, x - 1 + 4*delta, y - 2, x - 1 + 4*delta - 2*delta div corSize, y + delta div corSize - 2, ClipRect); // corner F ClipDrawLine(Canvas, x - 1 + 4*delta, y - dh - 2, x - 1 + 4*delta - _2Delta div corSize, y - dh + delta div corSize - 2, ClipRect); { MoveTo(x - 1, y - 1); LineTo(x - 1 + 2*delta, y - 1 + delta); LineTo(x - 1 + 4*delta, y - 1); LineTo(x - 1 + 4*delta, y - 1 - dh); LineTo(x - 1 + 2*delta, y - 1 + delta - dh); LineTo(x - 1 + 2*delta, y - 1 + delta); MoveTo(x - 1, y - 1); LineTo(x - 1, y - 1 - dh); LineTo(x - 1 + 2*delta, y - 1 + delta - dh); } end; if (Caption <> '') or (loGrated in Options) and (id and idMask = idBuildingMask) then begin inc(x, 2*u*Size); if img <> nil then dec(y, img.Height - delta) else dec(y, u*Size - delta); textrendinfo.x := x; textrendinfo.y := y; textrendinfo.text := Caption; AddTextToRender(textrendinfo); end; end; end; procedure DrawSimpleObject(const x, y : integer; const obj : TObjInfo); var img : TGameImage; PaletteInfo : TPaletteInfo; begin with obj do begin img := Imager.GetObjectImage(id, obj.angle); if img <> nil then begin PaletteInfo := FilterObjectPalette(img, obj); if loGlassed in Options then img.Draw(x, y, cAlpha, Frame, ClipRect, snap, PaletteInfo) else img.Draw(x, y, 0, Frame, ClipRect, snap, PaletteInfo); if loGrated in Options then with snap.Canvas do begin Brush.Style := bsClear; Pen.Color := $0088BBBB; Rectangle(x, y, x + img.Width, y + img.Height); end; end; end; end; function InsideRightEdge(const i, j : integer) : boolean; begin case rotation of drNorth: Result := (j < cols) and (i >= 0); drEast: Result := (j >= 0) and (i >= 0); drSouth: Result := (j >= 0) and (i < rows); else // drWest Result := (j < cols) and (i < rows); end; end; function InsideBottomEdge(const i, j : integer) : boolean; begin case rotation of drNorth: Result := i >= 0; drEast: Result := j >= 0; drSouth: Result := i < rows; else // drWest Result := j < cols; end; end; function OnLeftEdge(const i, j : integer) : boolean; begin case rotation of drNorth: Result := j = 0; drEast: Result := i = pred(rows); drSouth: Result := j = pred(cols); else // drWest Result := i = 0; end; end; procedure DrawLandLayers(x, y, i, j : integer); procedure DrawRank(x, i, j : integer); var OnLeft : boolean; OnTop : boolean; item : TItemInfo; k : integer; drawi, drawj : integer; procedure CalcIterationValues(const i, j, Size : integer; out sc, ec, deltac, sr, er, deltar : integer; out colinouterloop : boolean); begin case rotation of drNorth: begin sc := j + Size - 1; ec := j - 1; deltac := -1; sr := i; er := i - Size; deltar := -1; colinouterloop := true; end; drEast: begin sc := j; ec := j - Size; deltac := -1; sr := i - Size + 1; er := i + 1; deltar := 1; colinouterloop := false; end; drSouth: begin sc := j - Size + 1; ec := j + 1; deltac := 1; sr := i; er := i + Size; deltar := 1; colinouterloop := true; end; else // drWest begin sc := j; ec := j + Size; deltac := 1; sr := i + Size - 1; er := i - 1; deltar := -1; colinouterloop := false; end; end; end; procedure StartOuterLoop(const colinouterloop : boolean; const sc, sr : integer; out c, r : integer); begin if colinouterloop then c := sc else r := sr; end; function CheckOuterLoopCond(const colinouterloop : boolean;const c, r, ec, er : integer) : boolean; begin if colinouterloop then Result := c <> ec else Result := r <> er; end; procedure DoOuterLoopStep(const colinouterloop : boolean; var c, r : integer; const deltac, deltar : integer); begin if colinouterloop then inc(c, deltac) else inc(r, deltar); end; procedure StartInnerLoop(const colinouterloop : boolean; const sc, sr : integer; out c, r : integer); begin if not colinouterloop then c := sc else r := sr; end; function CheckInnerLoopCond(const colinouterloop : boolean; const c, r, ec, er : integer) : boolean; begin if not colinouterloop then Result := c <> ec else Result := r <> er; end; procedure DoInnerLoopStep(const colinouterloop : boolean; var c, r : integer; const deltac, deltar : integer); begin if not colinouterloop then inc(c, deltac) else inc(r, deltar); end; procedure DrawItemBase(const item : TItemInfo;x, y, i, j, Size : integer); var r, c : integer; obj : TObjInfo; overlay : TItemInfo; sc, ec : integer; sr, er : integer; deltac : integer; deltar : integer; colinouterloop : boolean; begin inc(x, 2*pred(Size)*u); dec(y, pred(Size)*u); CalcIterationValues(i, j, Size, sc, ec, deltac, sr, er, deltar, colinouterloop); StartOuterLoop(colinouterloop, sc, sr, c, r); while CheckOuterLoopCond(colinouterloop, c, r, ec, er) do begin StartInnerLoop(colinouterloop, sc, sr, c, r); while CheckInnerLoopCond(colinouterloop, c, r, ec, er) do begin if (lsOverlayedGround in item.States) and fMap.GetGroundOverlayInfo(r, c, focus, overlay) then begin if lsGrounded in overlay.States then if fMap.GetGroundInfo(r, c, focus, obj) then DrawObject(x, y, 1, obj); with overlay do DrawObject(x + xshift, y + yshift, 1, overlay); end else if fMap.GetGroundInfo(r, c, focus, obj) then DrawObject(x, y, 1, obj); inc(x, 2*u); inc(y, u); DoInnerLoopStep(colinouterloop, c, r, deltac, deltar); end; dec(x, 2*succ(Size)*u); dec(y, pred(Size)*u); DoOuterLoopStep(colinouterloop, c, r, deltac, deltar); end; end; procedure DrawOverlays(x, y, i, j, Size : integer); var r, c : integer; overlayinfo : TItemOverlayInfo; k : integer; sc, ec : integer; sr, er : integer; deltac : integer; deltar : integer; colinouterloop : boolean; begin inc(x, 2*pred(Size)*u); dec(y, pred(Size)*u); CalcIterationValues(i, j, Size, sc, ec, deltac, sr, er, deltar, colinouterloop); StartOuterLoop(colinouterloop, sc, sr, c, r); while CheckOuterLoopCond(colinouterloop, c, r, ec, er) do begin StartInnerLoop(colinouterloop, sc, sr, c, r); while CheckInnerLoopCond(colinouterloop, c, r, ec, er) do begin if fMap.GetItemOverlayInfo(r, c, focus, overlayinfo) then with overlayinfo do for k := 1 to count do with objects[k] do DrawSimpleObject(x + xshift, y + yshift, objects[k]); inc(x, 2*u); inc(y, u); DoInnerLoopStep(colinouterloop, c, r, deltac, deltar); end; dec(x, 2*succ(Size)*u); dec(y, pred(Size)*u); DoOuterLoopStep(colinouterloop, c, r, deltac, deltar); end; end; procedure ClipDrawOverlays(x, y, i, j : integer; xmin, xmax, ymin, ymax : integer); var overlayinfo : TItemOverlayInfo; k : integer; img : TGameImage; ImgClipRect : TRect; PaletteInfo : TPaletteInfo; begin if fMap.GetItemOverlayInfo(i, j, focus, overlayinfo) then with overlayinfo do for k := 1 to count do with objects[k] do begin img := Imager.GetObjectImage(id, angle); if img <> nil then begin if loNoClip in Options then ImgClipRect := ClipRect else begin ImgClipRect := Rect(max(xmin, x + xshift), max(ymin, y + yshift), min(xmax, x + xshift + img.Width), min(ymax, y + yshift + img.Height)); IntersectRect(ImgClipRect, ImgClipRect, ClipRect); end; if not IsRectEmpty(ImgClipRect) then begin PaletteInfo := FilterObjectPalette(img, objects[k]); if loGlassed in Options then img.Draw(x + xshift, y + yshift, cAlpha, Frame, ImgClipRect, snap, PaletteInfo) else img.Draw(x + xshift, y + yshift, 0, Frame, ImgClipRect, snap, PaletteInfo); end; end; end; end; procedure DrawItemOverlays(x, y : integer; const item : TItemInfo); var k : integer; itemimg : TGameImage; overlimg : TGameImage; PaletteInfo : TPaletteInfo; begin try itemimg := Imager.GetObjectImage(item.id, item.angle); if itemimg <> nil then with item, Overlays do for k := 1 to Count do with Objects[k] do begin overlimg := Imager.GetObjectImage(id, angle); if overlimg <> nil then begin PaletteInfo := FilterObjectPalette(overlimg, objects[k]); if loGlassed in Options then overlimg.Draw(x + xshift, y + u*Size - itemimg.Height + yshift, cAlpha, Frame, ClipRect, snap, PaletteInfo) else overlimg.Draw(x + xshift, y + u*Size - itemimg.Height + yshift, 0, Frame, ClipRect, snap, PaletteInfo); end; end; except end; end; procedure DrawItem(x, y, i, j : integer); var upitem : TItemInfo; ritem : TItemInfo; upi, upj : integer; ri, rj : integer; clipdelta : integer; Temp : boolean; begin if lsHighLand in item.States then clipdelta := 10 else clipdelta := 0; if loUpProjected in item.Options then begin incrow(view, i, j, upi, upj); with item do begin if fMap.GetItemInfo(upi, upj, focus, upitem) and (lsOverlayed in upitem.States) then ClipDrawOverlays(x - 2*u, y - u, upi, upj, x, x + 4*u, y - u - clipdelta, y + u); inccol(view, i, j, upi, upj); if fMap.GetItemInfo(upi, upj, focus, upitem) and (lsOverlayed in upitem.States) then ClipDrawOverlays(x + 2*u, y - u, upi, upj, x, x + 4*u, y - u - clipdelta, y + u); if lsGrounded in States then DrawItemBase(item, x, y, i, j, Size); DrawObject(x + xshift, y + yshift, Size, item); // este es para dibujar los edificios DrawItemOverlays(x, y, item); if lsOverlayed in States then DrawOverlays(x, y, i, j, Size); end; end else begin with item do begin if lsGrounded in States then DrawItemBase(item, x, y, i, j, Size); DrawObject(x + xshift, y + yshift, Size, item); // este dibuja las carreteras end; DrawItemOverlays(x, y, item); incrow(view, i, j, upi, upj); fMap.GetItemInfo(upi, upj, focus, upitem); inccol(view, i, j, ri, rj); fMap.GetItemInfo(ri, rj, focus, ritem); Temp := (lsDoubleOverlayed in item.States) or (lsDoubleOverlayed in upitem.States) or (lsDoubleOverlayed in ritem.States); if Temp then DrawOverlays(x, y, i, j, item.Size); // dibuja los carritos en los puentes if lsOverlayed in upitem.States then ClipDrawOverlays(x - 2*u, y - u, upi, upj, x, x + 4*u, y - u - clipdelta, y + u); if lsOverlayed in ritem.States then ClipDrawOverlays(x + 2*u, y - u, ri, rj, x, x + 4*u, y - u - clipdelta, y + u); // este casi no funciona if not Temp //not (lsDoubleOverlayed in item.States) and //not (lsDoubleOverlayed in upitem.States) and //not (lsDoubleOverlayed in ritem.States) then DrawOverlays(x, y, i, j, item.Size); end; end; begin OnTop := (y <= ClipRect.Top); OnLeft := true; while (x < ClipRect.Right) and InsideRightEdge(i, j) do begin if fMap.GetItemInfo(i, j, focus, item) then with item do begin RotateItem(item, rotation); if (c = 0) and (r = pred(Size)) then DrawItem(x, y, i, j) else if (OnLeft and (r + c = pred(Size))) or (OnTop and (c = 0)) or (OnTop and OnLeft) then begin offsetcoords(view, i, j, drawi, drawj, pred(Size - r), -c); DrawItem(x - 2*u*(Size - r + c - 1), y - u*(Size - r - c - 1), drawi, drawj); // >> ojo, la (i,j) no est'an bien aqu'i para DrawLandBase end; if r < pred(Size - c) then k := r else k := pred(Size - c); end else k := 0; while k >= 0 do begin inccol(view, i, j, i, j); decrow(view, i, j, i, j); inc(x, 4*u); dec(k); end; OnLeft := false; end; // while end; begin while (y < y2) and InsideBottomEdge(i, j) do begin DrawRank(x, i, j); if (x + 4*u < ClipRect.Left) or OnLeftEdge(i, j) then begin decrow(view, i, j, i, j); inc(x, 2*u); end else begin deccol(view, i, j, i, j); dec(x, 2*u); end; inc(y, u); end; end; procedure DrawTexts; procedure DoDrawText(x, y : integer; which : string); const ScanningTextId = 'Literal420'; const ExtraWidth = 100; var Rect : TRect; MidRect : TRect; i, j : integer; org : TPoint; begin if which = '' then which := GetLiteral(ScanningTextId); with snap.Canvas.Font do begin Name := 'Verdana'; Style := [fsBold]; Size := 7; Color := clBlack; END; snap.Canvas.Brush.Style := bsClear; Rect := Classes.Rect(0, 0, 200, 1000); with snap.Canvas do begin DrawText(Handle, pchar(which), length(which), Rect, DT_CALCRECT or DT_CENTER or DT_WORDBREAK or DT_EXPANDTABS); Rect := Classes.Rect(x - ExtraWidth, y - Rect.Bottom, x + ExtraWidth, y); // *** MidRect := Rect; for i := -1 to 1 do for j := -1 to 1 do if ((i = j) or (i = -j)) and (i <> 0) then begin Rect := MidRect; OffsetRect(Rect, i, j); DrawText(Handle, pchar(which), length(which), Rect, DT_CENTER or DT_WORDBREAK or DT_EXPANDTABS); end; snap.Canvas.Font.Color := clYellow; DrawText(Handle, pchar(which), length(which), MidRect, DT_CENTER or DT_WORDBREAK or DT_EXPANDTABS); end; if which = focus.GetText(fkSelection) then begin org := view.Origin; OffsetRect(Rect, org.x, org.y); focus.SetRect(Rect); end; end; var k : integer; textrendinfo : TTextRenderingInfo; begin for k := 0 to pred(fTextsToRenderCount) do begin textrendinfo := fTextsToRender[k]; DoDrawText(textrendinfo.x, textrendinfo.y, textrendinfo.text); end; fTextsToRenderCount := 0; end; {$IFDEF SHOWCNXS} procedure DrawObjectConnections; var k : integer; cnxsinfo : TCnxsInfo; pivotinfo : TCnxInfo; pivotdata : TCnxRenderingData; srcx : integer; srcy : integer; destx : integer; desty : integer; //drawbuff : TCanvasImage; //drawnlines : integer; procedure DoDrawCnxSrcDownImg(x, y : integer); begin if fCnxSourceDownCache[zoom, rotation] = nil then fCnxSourceDownCache[zoom, rotation] := Imager.GetCnxSourceDownImage; fCnxSourceDownCache[zoom, rotation].Draw(x - fCnxSourceDownCache[zoom, rotation].Width div 2, y - fCnxSourceDownCache[zoom, rotation].Height div 2, 0, 0, ClipRect, snap, nil); end; procedure DoDrawCnxSrcTopImg(x, y : integer); begin if fCnxSourceTopCache[zoom, rotation] = nil then fCnxSourceTopCache[zoom, rotation] := Imager.GetCnxSourceTopImage; fCnxSourceTopCache[zoom, rotation].Draw(x - fCnxSourceTopCache[zoom, rotation].Width div 2, y - fCnxSourceTopCache[zoom, rotation].Height div 2, 0, 0, ClipRect, snap, nil); end; procedure DoDrawCnxDestDownImg(x, y : integer); begin if fCnxDestDownCache[zoom, rotation] = nil then fCnxDestDownCache[zoom, rotation] := Imager.GetCnxDestDownImage; fCnxDestDownCache[zoom, rotation].Draw(x - fCnxDestDownCache[zoom, rotation].Width div 2, y - fCnxDestDownCache[zoom, rotation].Height div 2, 0, 0, ClipRect, snap, nil); end; procedure DoDrawCnxDestTopImg(x, y : integer); begin if fCnxDestTopCache[zoom, rotation] = nil then fCnxDestTopCache[zoom, rotation] := Imager.GetCnxDestTopImage; fCnxDestTopCache[zoom, rotation].Draw(x - fCnxDestTopCache[zoom, rotation].Width div 2, y - fCnxDestTopCache[zoom, rotation].Height div 2, 0, 0, ClipRect, snap, nil); end; function CalcCnxRenderingData(const cnx : TCnxInfo; cnxkind : TCnxKind; out cnxrenderdata : TCnxRenderingData) : boolean; var item : TItemInfo; img : TGameImage; imgRect : TRect; function CalcSrcImagesRect(x, y : integer) : TRect; var downRect : TRect; topRect : TRect; whalf : integer; hhalf : integer; begin if fCnxSourceDownCache[zoom, rotation] = nil then fCnxSourceDownCache[zoom, rotation] := Imager.GetCnxSourceDownImage; if fCnxSourceTopCache[zoom, rotation] = nil then fCnxSourceTopCache[zoom, rotation] := Imager.GetCnxSourceTopImage; with cnxrenderdata do begin whalf := fCnxSourceDownCache[zoom, rotation].Width div 2; hhalf := fCnxSourceDownCache[zoom, rotation].Height div 2; downRect := Rect(x - whalf, y - hhalf, x + whalf, y + hhalf); whalf := fCnxSourceTopCache[zoom, rotation].Width div 2; hhalf := fCnxSourceTopCache[zoom, rotation].Height div 2; topRect := Rect(x - whalf, y - hhalf, x + whalf, y + hhalf); end; UnionRect(Result, downRect, topRect); end; function CalcDestImagesRect(x, y : integer) : TRect; var downRect : TRect; topRect : TRect; whalf : integer; hhalf : integer; begin if fCnxDestDownCache[zoom, rotation] = nil then fCnxDestDownCache[zoom, rotation] := Imager.GetCnxDestDownImage; if fCnxDestTopCache[zoom, rotation] = nil then fCnxDestTopCache[zoom, rotation] := Imager.GetCnxDestTopImage; with cnxrenderdata do begin whalf := fCnxDestDownCache[zoom, rotation].Width div 2; hhalf := fCnxDestDownCache[zoom, rotation].Height div 2; downRect := Rect(x - whalf, y - hhalf, x + whalf, y + hhalf); whalf := fCnxDestTopCache[zoom, rotation].Width div 2; hhalf := fCnxDestTopCache[zoom, rotation].Height div 2; topRect := Rect(x - whalf, y - hhalf, x + whalf, y + hhalf); end; UnionRect(Result, downRect, topRect); end; begin Result := false; with cnxrenderdata do begin drawimg := false; if fMap.GetItemInfo(cnx.r, cnx.c, focus, item) and (lsGrounded in item.States) and MapToScreen(view, cnx.r, cnx.c, x, y) then begin img := Imager.GetObjectImage(item.id, item.angle); if img <> nil then begin x := x + 2*u; y := y + u - img.Height; if cnxkind = cnxkInputs then imgRect := CalcSrcImagesRect(x, y) else imgRect := CalcDestImagesRect(x, y); drawimg := IntersectRect(imgRect, imgRect, ClipRect); Result := true; end; end; end; end; begin if fMap.GetCnxsInfo(focus, cnxsinfo) then begin //drawbuff := GetBuffer(snap.Width, snap.Height); //drawnlines := 0; //SetupBufferBackground(ClipRect); with cnxsinfo, fCnxsRenderingData, (*drawbuff*)snap.Canvas do begin if count <> cnxcount then begin if count <> 0 then freemem(renderdata); getmem(renderdata, sizeof(renderdata[0])*cnxcount); count := cnxcount; end; if view.ZoomLevel >= 2 then Pen.Width := 2 else Pen.Width := 1; pivotinfo.r := cnxsinfo.r; pivotinfo.c := cnxsinfo.c; pivotinfo.color := clNone; if cnxkind = cnxkInputs then CalcCnxRenderingData(pivotinfo, cnxkOutputs, pivotdata) else CalcCnxRenderingData(pivotinfo, cnxkInputs, pivotdata); for k := 0 to pred(cnxcount) do if not CalcCnxRenderingData(cnxs[k], cnxkind, renderdata[k]) then begin renderdata[k].drawimg := false; renderdata[k].x := -1; renderdata[k].y := -1; end; if pivotdata.drawimg then case cnxkind of cnxkInputs: DoDrawCnxDestDownImg(pivotdata.x, pivotdata.y); cnxkOutputs: DoDrawCnxSrcDownImg(pivotdata.x, pivotdata.y); end; for k := 0 to pred(cnxcount) do if renderdata[k].drawimg then case cnxkind of cnxkInputs: DoDrawCnxSrcDownImg(renderdata[k].x, renderdata[k].y); cnxkOutputs: DoDrawCnxDestDownImg(renderdata[k].x, renderdata[k].y); end; for k := 0 to pred(cnxcount) do begin srcx := pivotdata.x; srcy := pivotdata.y; destx := renderdata[k].x; desty := renderdata[k].y; if ClipLine(srcx, srcy, destx, desty, ClipRect) then begin Pen.Color := cnxs[k].color; MoveTo(srcx, srcy); LineTo(destx, desty); //inc(drawnlines); end; end; Pen.Width := 1; (*if drawnlines > 0 then RenderBuffer(snap, ClipRect);*) if pivotdata.drawimg then case cnxkind of cnxkInputs: DoDrawCnxDestTopImg(pivotdata.x, pivotdata.y); cnxkOutputs: DoDrawCnxSrcTopImg(pivotdata.x, pivotdata.y); end; for k := 0 to pred(cnxcount) do if renderdata[k].drawimg then case cnxkind of cnxkInputs: DoDrawCnxSrcTopImg(renderdata[k].x, renderdata[k].y); cnxkOutputs: DoDrawCnxDestTopImg(renderdata[k].x, renderdata[k].y); end; end; end; end; {$ENDIF} procedure DrawFocusObject; var obj : TObjInfo; begin if fMap.GetFocusObjectInfo(focus, ClipRect, obj) then DrawSimpleObject(obj.xshift, obj.yshift, obj); end; procedure DrawSurfaceData(x, y, i, j : integer); procedure DrawRank(x, i, j : integer); var surfinfoobj : TObjInfo; begin while (x < ClipRect.Right) and InsideRightEdge(i, j) do begin if fMap.GetSurfaceInfo(i, j, focus, surfinfoobj) then DrawObject(x, y, 1, surfinfoobj); inccol(view, i, j, i, j); decrow(view, i, j, i, j); inc(x, 4*u); end; // while end; begin while (y < y2) and InsideBottomEdge(i, j) do begin DrawRank(x, i, j); if (x + 4*u < ClipRect.Left) or OnLeftEdge(i, j) then begin decrow(view, i, j, i, j); inc(x, 2*u); end else begin deccol(view, i, j, i, j); dec(x, 2*u); end; inc(y, u); end; end; procedure DrawAirObjects; var airobjs : TAirObjsInfo; x, y : integer; k : integer; begin if fMap.GetAirInfo(focus, ClipRect, airobjs) then with airobjs do for k := 0 to pred(count) do begin MapToScreen(view, objects[k].r, objects[k].c, x, y); DrawSimpleObject(x + objects[k].xshift, y + objects[k].yshift, objects[k]); end; end; procedure DrawSmallText; var x, y : integer; j, k : integer; color : TColor; begin if focus.GetSmallTextData(x, y, smalltext, color) then with snap.Canvas do begin SetBkMode(Handle, TRANSPARENT); Font.Name := 'Verdana'; Font.Size := 8; Font.Style := [fsBold]; Font.Color := clBlack; for j := -1 to 1 do for k := -1 to 1 do if ((j = k) or (j = -k)) and (j <> 0) then TextOut(x + j, y + k, smalltext); Font.Color := color; TextOut(x, y, smalltext); end; end; {$IFDEF DRAWGRID} procedure DrawGrid; var x, y : integer; i, j : integer; y1 : integer; u : integer; procedure DrawRank(x, i, j : integer); begin while (x < ClipRect.Right) and InsideRightEdge(i, j) do begin with snap.Canvas do begin MoveTo(x, y); LineTo(x + 2*u, y + u); LineTo(x + 4*u, y); LineTo(x + 2*u, y - u); LineTo(x, y); end; inccol(view, i, j, i, j); decrow(view, i, j, i, j); inc(x, 4*u); end; // while end; begin u := 2 shl view.ZoomLevel; x := ClipRect.Left; y := ClipRect.Top; CalculateFirstGrid(view, x, y, i, j); y1 := ClipRect.Bottom + u; snap.Canvas.Pen.Color := clNavy; while (y < y1) and InsideBottomEdge(i, j) do begin DrawRank(x, i, j); if (x + 2*u <= ClipRect.Left) or OnLeftEdge(i, j) then begin decrow(view, i, j, i, j); inc(x, 2*u); end else begin deccol(view, i, j, i, j); dec(x, 2*u); end; inc(y, u); end; end; {$ENDIF} begin //Profiler.ProcStarted(prfKind_Main, prfId_RenderingInit); focus := view.GetFocus; cols := fMap.GetColumns; rows := fMap.GetRows; Imager := fMap.GetImager(focus); zoom := TZoomRes(view.ZoomLevel); rotation := view.Rotation; u := 2 shl view.ZoomLevel; x := ClipRect.Left - 2*u; y := ClipRect.Top; CalculateFirstGrid(view, x, y, i, j); y1 := ClipRect.Bottom + cMaxLandHeight*u; y2 := y1 + cMaxBuildingHeight*u; //Profiler.ProcEnded(prfKind_Main, prfId_RenderingInit); //Profiler.ProcStarted(prfKind_Main, prfId_RegionFill); snap.Canvas.Brush.Color := clBlack; snap.Canvas.Brush.Style := bsSolid; snap.Canvas.FillRect(ClipRect); //Profiler.ProcEnded(prfKind_Main, prfId_RegionFill); if focus.IsLandVisible then try //Profiler.ProcStarted(prfKind_Main, prfId_LandRendering); DrawLandLayers(x, y, i, j); //Profiler.ProcEnded(prfKind_Main, prfId_LandRendering); DrawFocusObject; except end; //Profiler.ProcStarted(prfKind_Main, prfId_SurfaceRendering); if focus.HasValidSurface then DrawSurfaceData(x, y, i, j); //Profiler.ProcEnded(prfKind_Main, prfId_SurfaceRendering); if focus.IsLandVisible then begin //Profiler.ProcStarted(prfKind_Main, prfId_ConnectionsRendering); {$IFDEF SHOWCNXS} DrawObjectConnections; {$ENDIF} //Profiler.ProcEnded(prfKind_Main, prfId_ConnectionsRendering); //Profiler.ProcStarted(prfKind_Main, prfId_TextRendering); DrawTexts; //Profiler.ProcEnded(prfKind_Main, prfId_TextRendering); //Profiler.ProcStarted(prfKind_Main, prfId_AirplaneRendering); if focus.IsLandVisible then DrawAirObjects; //Profiler.ProcEnded(prfKind_Main, prfId_AirplaneRendering); end; { Profiler.ProcStarted(prfKind_Main, prfId_ChatTextRendering); Profiler.ProcEnded(prfKind_Main, prfId_ChatTextRendering); } DrawSmallText; {$IFDEF DRAWGRID} if true then DrawGrid; {$ENDIF} // >>>> Draw mouse hint if (fLastZoom <> zoom) or (fLastRotation <> rotation) then begin fSpareCache[fLastZoom, fLastRotation] := nil; fDownloadSign[fLastZoom, fLastRotation] := nil; fShadeCache[fLastZoom, fLastRotation] := nil; fRedShadeCache[fLastZoom, fLastRotation] := nil; fBlackShadeCache[fLastZoom, fLastRotation] := nil; fCnxSourceDownCache[fLastZoom, fLastRotation] := nil; fCnxSourceTopCache[fLastZoom, fLastRotation] := nil; fCnxDestDownCache[fLastZoom, fLastRotation] := nil; fCnxDestTopCache[fLastZoom, fLastRotation] := nil; fLastZoom := zoom; fLastRotation := rotation; end; end; function TLander.ClipMovement(const view : IGameView; var dx, dy : integer) : boolean; const cMargin = 14; var i, j : integer; x, y : integer; rows : integer; cols : integer; function ClipRow : boolean; begin case view.Rotation of drNorth: Result := ClipInteger(i, cMargin, rows + cMargin); drEast: Result := ClipInteger(j, cMargin, cols + cMargin); drSouth: Result := ClipInteger(i, -cMargin, rows - cMargin); else // drWest Result := ClipInteger(j, -cMargin, cols - cMargin); end; end; function ClipCol : boolean; begin case view.Rotation of drNorth: Result := ClipInteger(j, 0, cols); drEast: Result := ClipInteger(i, 0, rows); drSouth: Result := ClipInteger(j, 0, cols); else // drWest Result := ClipInteger(i, 0, rows); end; end; begin rows := fMap.GetRows; cols := fMap.GetColumns; x := -dx; y := -dy; ScreenToMap(view, x, y, i, j); {$B+} Result := ClipRow or ClipCol; {$B-} if Result then begin MapToScreen(view, i, j, x, y); dx := -x; dy := -y; end; end; function TLander.CreateFocus(const view : IGameView) : IGameFocus; begin Result := fMap.CreateFocus(view); end; procedure TLander.SetImageSuit( ImageSuit : integer ); begin fMap.SetImageSuit( ImageSuit ); end; function TLander.ObjectToMap(const view : IGameView; x, y : integer; out i, j : integer; checkbase : boolean) : boolean; var xx, yy : integer; u : integer; rows : integer; cols : integer; rinc : integer; cinc : integer; function OnLeftEdge : boolean; begin case view.rotation of drNorth: Result := j = 0; drEast: Result := i = pred(rows); drSouth: Result := j = pred(cols); else // drWest Result := i = 0; end; end; function InsideMap : boolean; begin case view.rotation of drNorth: Result := (i < rows) and (j < cols); drEast: Result := (i >= 0) and (j < cols); drSouth: Result := (i >= 0) and (j >= 0); else // drWest Result := (i < rows) and (j >= 0); end; end; function BelowLeft(out by : integer) : boolean; begin case view.Rotation of drNorth: by := -j; drEast: by := i - pred(rows); drSouth: by := j - pred(cols); else // drWest by := -i; end; Result := by > 0; end; function BelowBottom(out by : integer) : boolean; begin case view.Rotation of drNorth: by := -i; drEast: by := -j; drSouth: by := i - pred(rows); else // drWest by := j - pred(cols); end; Result := by > 0; end; procedure RowLowerBound(var i, j : integer); begin case view.Rotation of drNorth: i := 0; drEast: j := 0; drSouth: i := pred(rows); else // drWest j := pred(cols); end; end; procedure ColLowerBound(var i, j : integer); begin case view.Rotation of drNorth: j := 0; drEast: i := pred(rows); drSouth: j := pred(cols); else // drWest i := 0; end; end; begin rows := fMap.GetRows; cols := fMap.GetColumns; u := 2 shl view.ZoomLevel; ScreenToMap(view, x, y + cMaxBuildingHeight*u, i, j); MapToScreen(view, i, j, xx, yy); if BelowBottom(cinc) then begin offsetcoords(view, i, j, i, j, 0, cinc); dec(yy, 2*u*cinc); RowLowerBound(i, j); end; if BelowLeft(rinc) then begin offsetcoords(view, i, j, i, j, rinc, 0); dec(yy, 2*u*rinc); ColLowerBound(i, j); end; while InsideMap and not CheckPoint(view, x, y, i, j) do begin if (xx + 2*u < x) or OnLeftEdge then begin inc(xx, 2*u); inccol(view, i, j, i, j); end else begin dec(xx, 2*u); incrow(view, i, j, i, j); end; dec(yy, u); end; Result := InsideMap; if not Result and checkbase then Result := CheckBuildingBase(view, x, y, i, j); end; function TLander.ScreenToMap(const view : IGameView; x, y : integer; out i, j : integer) : boolean; var org : TPoint; aux : integer; u, h : integer; tu : integer; rows : integer; cols : integer; begin rows := fMap.GetRows; cols := fMap.GetColumns; if (view.Rotation = drEast) or (view.Rotation = drWest) then begin aux := rows; rows := cols; cols := aux; end; org := view.Origin; inc(x, org.x); inc(y, org.y); u := 2 shl view.ZoomLevel; tu := u shl 2; //tu := u + u; //inc(tu, tu); aux := 2*(u*cols - y); h := aux + tu*succ(rows) - x; if h >= 0 then i := h div tu else i := (h - tu) div tu; h := aux + x; if h >= 0 then j := h div tu else j := (h - tu) div tu; case view.Rotation of drNorth: ; drEast: begin aux := i; i := pred(cols - j); j := aux; end; drSouth: begin i := pred(rows - i); j := pred(cols - j); end; drWest: begin aux := i; i := j; j := pred(rows - aux); end; end; Result := (i >= 0) and (i < rows) and (j >= 0) and (j < cols); end; function TLander.MapToScreen(const view : IGameView; i, j : integer; out x, y : integer) : boolean; var org : TPoint; u : integer; rows : integer; cols : integer; aux : integer; begin rows := fMap.GetRows; cols := fMap.GetColumns; case view.Rotation of drNorth: ; drEast: begin aux := rows; rows := cols; cols := aux; aux := i; i := j; j := pred(cols - aux); end; drSouth: begin i := pred(rows - i); j := pred(cols - j); end; drWest: begin aux := rows; rows := cols; cols := aux; aux := i; i := pred(rows - j); j := aux; end; end; org := view.Origin; u := 2 shl view.ZoomLevel; x := 2*u*(rows - i + j); y := u*((rows - i) + (cols - j)); dec(x, org.x); dec(y, org.y); Result := (i >= 0) and (i < rows) and (j >= 0) and (j < cols); end; procedure TLander.GetViewRegion(const view : IGameView; out imin, jmin, imax, jmax : integer); var i, j : integer; begin with view.GetSize do begin ScreenToMap(view, x, y, i, j); case view.Rotation of drNorth: imin := max(i, 0); drEast: jmin := max(j, 0); drSouth: imax := min(i, pred(fMap.GetRows)); drWest: jmax := min(j, pred(fMap.GetColumns)); end; ScreenToMap(view, 0, y, i, j); case view.Rotation of drNorth: jmin := max(j, 0); drEast: imax := min(i, pred(fMap.GetRows)); drSouth: jmax := min(j, pred(fMap.GetColumns)); drWest: imin := max(i, 0); end; ScreenToMap(view, 0, 0, i, j); case view.Rotation of drNorth: imax := min(i, pred(fMap.GetRows)); drEast: jmax := min(j, pred(fMap.GetColumns)); drSouth: imin := max(i, 0); drWest: jmin := max(j, 0); end; ScreenToMap(view, x, 0, i, j); case view.Rotation of drNorth: jmax := min(j, pred(fMap.GetColumns)); drEast: imin := max(i, 0); drSouth: jmin := max(j, 0); drWest: imax := min(i, pred(fMap.GetRows)); end; end; end; procedure TLander.CalculateFirstGrid(const view : IGameView; var x, y : integer; out i, j : integer); var xb, yb : integer; u : integer; rows : integer; cols : integer; rinc : integer; cinc : integer; function AboveTop(out by : integer) : boolean; begin case view.Rotation of drNorth: by := i - pred(rows); drEast: by := j - pred(cols); drSouth: by := -i; else // drWest by := -j; end; Result := by > 0; end; function BelowLeft(out by : integer) : boolean; begin case view.Rotation of drNorth: by := -j; drEast: by := i - pred(rows); drSouth: by := j - pred(cols); else // drWest by := -i; end; Result := by > 0; end; procedure RowUpperBound(var i, j : integer); begin case view.Rotation of drNorth: i := pred(rows); drEast: j := pred(cols); drSouth: i := 0; else // drWest j := 0; end; end; procedure ColLowerBound(var i, j : integer); begin case view.Rotation of drNorth: j := 0; drEast: i := pred(rows); drSouth: j := pred(cols); else // drWest i := 0; end; end; begin rows := fMap.GetRows; cols := fMap.GetColumns; u := 2 shl view.ZoomLevel; xb := x; yb := y; ScreenToMap(view, x, y, i, j); MapToScreen(view, i, j, x, y); while (y > yb) or (x > xb) do begin dec(x, 2*u); dec(y, u); incrow(view, i, j, i, j); end; if AboveTop(cinc) then begin offsetcoords(view, i, j, i, j, 0, cinc); inc(x, 4*u*cinc); RowUpperBound(i, j); end else if BelowLeft(rinc) then begin offsetcoords(view, i, j, i, j, -rinc, 0); inc(x, 4*u*rinc); ColLowerBound(i, j); end; end; procedure TLander.AddTextToRender(const texttorender : TTextRenderingInfo); const cTextsToRenderDelta = 1; begin if fTextsToRenderCount = fTextsToRenderAlloc then begin inc(fTextsToRenderAlloc, cTextsToRenderDelta); reallocmem(fTextsToRender, fTextsToRenderAlloc*sizeof(fTextsToRender[0])); initialize(fTextsToRender[fTextsToRenderCount], fTextsToRenderAlloc - fTextsToRenderCount); end; fTextsToRender[fTextsToRenderCount] := texttorender; inc(fTextsToRenderCount); end; function TLander.CheckPoint(const view : IGameView; x, y, i, j : integer) : boolean; var xx, yy : integer; item : TItemInfo; Imager : IImager; img : TGameImage; u : integer; focus : IGameFocus; // >>>> nil begin if fMap.GetItemInfo(i, j, focus, item) and (lsFocusable in item.States) then begin RotateItem(item, view.Rotation); with item do begin Imager := fMap.GetImager(view.GetFocus); img := Imager.GetObjectImage(id, angle); if img <> nil then begin u := 2 shl view.ZoomLevel; offsetcoords(view, i, j, i, j, pred(Size), 0); offsetcoords(view, i, j, i, j, -r, -c); MapToScreen(view, i, j, xx, yy); dec(x, xx); dec(y, yy + succ(u*Size - img.Height)); Result := (x >= 0) and (y >= 0) and (x < img.Width) and (y < img.Height) and (img.Pixel[x, y, item.Frame] <> img.TranspIndx); end else Result := false; end end else Result := false; end; function TLander.CheckBuildingBase(const view : IGameView; x, y : integer; out i, j : integer) : boolean; var item : TItemInfo; begin Result := ScreenToMap(view, x, y, i, j) and fMap.GetItemInfo(i, j, view.GetFocus, item) and (lsFocusable in item.States); end; procedure TLander.DestroyAll; begin fMap := nil; end; end.
unit MetaData; {$mode objfpc}{$H+} interface uses Classes, SysUtils, bddatamodule, Dialogs; type { TField_Info } TField_Type = (FTStr, FTInt, FTTime, FTDays); TTitle_Field = record FName: string; FId: integer; max_text_width: integer; end; TGrid_Record = record FValues: array of string; end; TGrid_Cell = record max_text_width: integer; max_text_height: integer; FRecords: array of TGrid_Record; end; TMy_Grid = array of array of TGrid_Cell; TTitle_Array = array of TTitle_Field; TField_Info = class Flength: integer; FName: string; FRu_Name: string; FField_Type: TField_Type; FOwner_Table_Name: string; constructor Create(AOwner_Table_Name, Aname, ARu_Name: string; AField_Type: TField_Type); function Get_Field_Name(): string; virtual; function Get_Inner_From(): string; virtual; function Get_Source_Table(): string; virtual; function Get_Inner_Field(): string; virtual; function Get_Order_By(): string; virtual; end; { TReference_Field_Info } TReference_Field_Info = class(TField_Info) FInner_Table_Name: string; FInner_Field_Name: string; constructor Create(AOwner_Table_Name, AName, ARu_Name: string; AField_Type: TField_Type; AInner_Field_Name, AInner_Table_Name: string); function Get_Field_Name(): string; override; function Get_Inner_From(): string; override; function Get_Source_Table(): string; override; function Get_Inner_Field(): string; override; function Get_Order_By: string; override; end; { TTable_Info } TTable_Info = class private FSelect, FFrom: string; public FReference_Table: boolean; FTable_Name, FTableRuName: string; FFields: array of TField_Info; FGenerator_Name: string; constructor Create(ATable_Name, ATable_Ru_Name, AGenerator_Name: string; AReference_Table: boolean); procedure Add_Field(AName, ARu_Name: string; AField_Type: TField_Type); procedure Add_Field(AName, ARu_Name: string; AField_Type: TField_Type; AInner_Field_Name, AInner_Table_Name: string); function Get_select(): string; function Get_From(): string; function Get_Schedule_select(): string; end; const Count_schedule_fields = 7; var My_Tables: array of TTable_Info; Schedule_Table: TTable_Info; procedure Add_My_Table(ATable_Name, ATable_Ru_Name, AGenerator_Name: string; AReference_Table: boolean); implementation procedure Add_My_Table(ATable_Name, ATable_Ru_Name, AGenerator_Name: string; AReference_Table: boolean); begin setlength(My_Tables, length(My_Tables) + 1); My_Tables[High(My_Tables)] := TTable_Info.Create(ATable_Name, ATable_Ru_Name, AGenerator_Name, AReference_Table); end; { TReference_Field_Info } constructor TReference_Field_Info.Create(AOwner_Table_Name, AName, ARu_Name: string; AField_Type: TField_Type; AInner_Field_Name, AInner_Table_Name: string); begin FInner_Field_Name := AInner_Field_Name; FInner_Table_Name := AInner_Table_Name; inherited Create(AOwner_Table_Name, AName, ARu_Name, AField_Type); end; function TReference_Field_Info.Get_Field_Name: string; begin Result := ' ' + FInner_Table_Name + '.' + FInner_Field_Name + ' '; end; function TReference_Field_Info.Get_Inner_From: string; begin Result := ' inner join ' + FInner_Table_Name + ' on ' + FOwner_Table_Name + '.' + FName + ' = ' + FInner_Table_Name + '.id '; end; function TReference_Field_Info.Get_Source_Table: string; begin Result := FInner_Table_Name; end; function TReference_Field_Info.Get_Inner_Field: string; begin Result := FInner_Field_Name; end; function TReference_Field_Info.Get_Order_By: string; begin if FField_Type = FTDays then Result := ' Order by ' + FInner_Table_Name + '.Field_Index ' else Result := ' Order by ' + FInner_Table_Name + '.' + FInner_Field_Name + ' '; end; { TTable_Info } constructor TTable_Info.Create(ATable_Name, ATable_Ru_Name, AGenerator_Name: string; AReference_Table: boolean); var i: integer; begin FReference_Table := AReference_Table; FTable_Name := ATable_Name; FTableRuName := ATable_Ru_Name; FGenerator_Name := AGenerator_Name; end; procedure TTable_Info.Add_Field(AName, ARu_Name: string; AField_Type: TField_Type); begin SetLength(FFields, Length(FFields) + 1); FFields[High(FFields)] := TField_Info.Create(FTable_Name, AName, ARu_Name, AField_Type); end; procedure TTable_Info.Add_Field(AName, ARu_Name: string; AField_Type: TField_Type; AInner_Field_Name, AInner_Table_Name: string); begin SetLength(FFields, Length(FFields) + 1); FFields[High(FFields)] := TReference_Field_Info.Create(FTable_Name, AName, ARu_Name, AField_Type, AInner_Field_Name, AInner_Table_Name); end; function TTable_Info.Get_select: string; var i: integer; begin Result := ' select '; for i := 0 to High(FFields) do Result += ' ' + FFields[i].Get_Field_Name() + ' ,'; SetLength(Result, Length(Result) - 1); end; function TTable_Info.Get_From: string; var i: integer; begin Result := ' From ' + FTable_Name + ' '; for i := 0 to High(FFields) do Result += FFields[i].Get_Inner_From(); end; function TTable_Info.Get_Schedule_select: string; var i: integer; begin Result := Get_select() + ' ,'; for i := 1 to High(FFields) do begin Result += ' ' + Ffields[i].FName + ' ,'; end; SetLength(Result, Length(Result) - 1); end; { TField_Info } constructor TField_Info.Create(AOwner_Table_Name, Aname, ARu_Name: string; AField_Type: TField_Type); begin FName := Aname; FRu_Name := ARu_Name; FField_Type := AField_Type; FOwner_Table_Name := AOwner_Table_Name; end; function TField_Info.Get_Field_Name: string; begin Result := FOwner_Table_Name + '.' + FName; end; function TField_Info.Get_Inner_From: string; begin Result := ''; end; function TField_Info.Get_Source_Table: string; begin Result := FOwner_Table_Name; end; function TField_Info.Get_Inner_Field: string; begin Result := FName; end; function TField_Info.Get_Order_By: string; begin if FField_Type = FTDays then Result := ' Order by Field_Index ' else Result := ' Order By ' + FName + ' '; end; initialization Add_My_Table('Groups', 'Группы', 'Groups_id', False); My_Tables[High(My_Tables)].Add_Field('Id', 'Ай-Ди', FTInt); My_Tables[High(My_Tables)].Add_Field('Group_Name', 'Имя Группы', FTStr); My_Tables[High(My_Tables)].Add_Field('Students', 'Количество Учащихся', FTInt); Add_My_Table('Disciplines', 'Предметы', 'Disciplines_Id', False); My_Tables[High(My_Tables)].Add_Field('Id', 'Ай-Ди', FTInt); My_Tables[High(My_Tables)].Add_Field('Discipline_Name', 'Название', FTStr); Add_My_Table('Professors', 'Преподаватели', 'Professors_Id', False); My_Tables[High(My_Tables)].Add_Field('Id', 'Ай-Ди', FTInt); My_Tables[High(My_Tables)].Add_Field('Professor_Name', 'Имя', FTStr); Add_My_Table('Days', 'Дни Недели', 'Days_Id', False); My_Tables[High(My_Tables)].Add_Field('Id', 'Ай-Ди', FTInt); My_Tables[High(My_Tables)].Add_Field('Day_Name', 'Наименование', FTDays); My_Tables[High(My_Tables)].Add_Field('Field_Index', 'Номер', FTStr); Add_My_Table('Times', 'Пары', 'Times_Id', False); My_Tables[High(My_Tables)].Add_Field('Id', 'Ай-Ди', FTInt); My_Tables[High(My_Tables)].Add_Field('Begining', 'Начало', FTStr); My_Tables[High(My_Tables)].Add_Field('Finish', 'Окончание', FTStr); My_Tables[High(My_Tables)].Add_Field('Field_Index', 'Номер', FTStr); Add_My_Table('Rooms', 'Кабинеты', 'Rooms_Id', False); My_Tables[High(My_Tables)].Add_Field('Id', 'Ай-Ди', FTInt); My_Tables[High(My_Tables)].Add_Field('Room_Name', 'Имя', FTStr); My_Tables[High(My_Tables)].Add_Field('People', 'Вместимость', FTInt); Add_My_Table('Professors_Disciplines', 'Преподаватель - Предмет', 'Professors_Disciplines_id', True); My_Tables[High(My_Tables)].Add_Field('Id', 'Ай-Ди', FTInt); My_Tables[High(My_Tables)].Add_Field('Professor_id', 'Преподаватель', FTStr, 'Professor_Name', 'Professors'); My_Tables[High(My_Tables)].Add_Field('Discipline_id', 'Предмет', FTSTr, 'Discipline_Name', 'Disciplines'); Add_My_Table('Disciplines_Groups', 'Предмет - Группа', 'Disciplines_Groups_id', True); My_Tables[High(My_Tables)].Add_Field('Id', 'Ай-Ди', FTInt); My_Tables[High(My_Tables)].Add_Field('Discipline_id', 'Предмет', FTStr, 'Discipline_Name', 'Disciplines'); My_Tables[High(My_Tables)].Add_Field('Group_id', 'Группа', FTStr, 'Group_Name', 'Groups'); Add_My_Table('Schedule_Items', 'Расписание', 'Schedule_Items_Id', True); {0} My_Tables[High(My_Tables)].Add_Field('Id', 'Ай-Ди', FTInt); {1} My_Tables[High(My_Tables)].Add_Field('Subject_id', 'Предмет', FTStr, 'Discipline_Name', 'Disciplines'); {2} My_Tables[High(My_Tables)].Add_Field('Professor_id', 'Преподаватель', FTStr, 'Professor_Name', 'Professors'); {3} My_Tables[High(My_Tables)].Add_Field('Day_id', 'День Недели', FTDays, 'Day_Name', 'Days'); {4} My_Tables[High(My_Tables)].Add_Field('Time_id', 'Время', FTStr, 'Begining', 'Times'); {5} My_Tables[High(My_Tables)].Add_Field('Group_id', 'Группа', FTStr, 'Group_Name', 'Groups'); {6} My_Tables[High(My_Tables)].Add_Field('Room_id', 'Кабинет', FTStr, 'Room_Name', 'Rooms'); Schedule_Table := My_Tables[High(My_Tables)]; //Add_My_Table('Groups', 'Группы', // ['id', 'Name', 'peoples'], ['Ай-Ди', 'Имя Гуппы', // 'Количество Учащихся'], false, [], [], [Tint, Tstr, Tint]); // Add_My_Table('Disciplines', 'Предметы', ['id', 'name'], // ['Ай-Ди', 'Название'], false, [], [], [Tint, Tstr]); // Add_My_Table('Professors', 'Преподаватели', ['id', 'Name'], // ['Ай-Ди', 'Имя'], false, [], [], [Tint, Tstr]); // Add_My_Table('Days', 'Дни Недели', ['id', 'Name'], // ['Ай-Ди', 'Наименование'], false, [], [], [Tint, Tstr]); // Add_My_Table('Times', 'Пары', ['id', 'begining', 'finish', 'name'], // ['Ай-Ди', 'Начало', 'Окончание', 'Название'], // false, [], [], [Tint, Tstr, Tstr, Tstr]); // Add_My_Table('Rooms', 'Кабинеты', ['id', 'name', 'peoples'], // ['Ай-Ди', 'Имя', 'Вместимость'], false, [], [], [Tint, Tstr, Tint]); // Add_My_Table('Professor_Discipline', 'Преподаватель - Предмет', // ['Teacher', '"subject"'], ['Преподаватель', 'Предмет'], // true, ['Professors', 'Disciplines'], ['Name', 'Name'], [Tstr, Tstr]); // Add_My_Table('Schedule_items', 'Расписание', // ['subject', 'professor', 'time_s', 'days', '"Group"', 'Room'], // ['Предмет', 'Преподаватель', 'Время', // 'День', 'Группа', 'Кабинет'], true, // ['Disciplines', 'Professors', 'times', 'days', 'groups', 'rooms'], // ['name', 'name', 'name', 'name', 'name', 'name'], [Tstr, Tstr, Tstr, Tstr, Tstr, Tstr]); end.
(*Bouncer1: MiniLib V.4, 2004 -------- Bouncing ball application. Version 1: without ball interaction. ========================================================================*) PROGRAM Bouncer1; USES MetaInfo, OSBridge, MLObj, MLWin, MLAppl; TYPE BouncerWindow = ^BouncerWindowObj; BouncerWindowObj = OBJECT(MLWindowObj) pos: Point; dx, dy, size, speed: INTEGER; CONSTRUCTOR Init(title: STRING); (*overridden methods*) PROCEDURE Open; VIRTUAL; PROCEDURE Redraw; VIRTUAL; PROCEDURE OnIdle; VIRTUAL; PROCEDURE OnCommand(commandNr: INTEGER); VIRTUAL; (*new methods*) PROCEDURE InvertBall; VIRTUAL; PROCEDURE ChangeSize(newSize: INTEGER); VIRTUAL; PROCEDURE ChangeSpeed(newSpeed: INTEGER); VIRTUAL; END; (*OBJECT*) BouncerApplication= ^BouncerApplicationObj; BouncerApplicationObj = OBJECT(MLApplicationObj) CONSTRUCTOR Init(name: STRING); (*overridden methods*) PROCEDURE OpenNewWindow; VIRTUAL; PROCEDURE BuildMenus; VIRTUAL; END; (*OBJECT*) VAR (*size menu:*) smallCommand, mediumCommand, largeCommand: INTEGER; (*speed menu:*) crawlCommand, walkCommand, runCommand, flyCommand: INTEGER; (*=== BouncerWindow ===*) FUNCTION NewBouncerWindow: BouncerWindow; VAR w: BouncerWindow; BEGIN New(w, Init('Bouncer Window')); NewBouncerWindow := w; END; (*NewBouncerWindow*) CONSTRUCTOR BouncerWindowObj.Init(title: STRING); BEGIN INHERITED Init(title); Register('BouncerWindow', 'MLWindow'); pos.x := 0; pos.y := 0; size := 10; speed := 10; dx := speed; dy := speed; END; (*BouncerWindowObj.Init*) PROCEDURE BouncerWindowObj.Open; BEGIN INHERITED Open; InvertBall; END; (*BouncerWindowObj.Open*) PROCEDURE BouncerWindowObj.Redraw; BEGIN InvertBall; END; (*BouncerWindowObj.Redraw*) PROCEDURE BouncerWindowObj.OnIdle; PROCEDURE Move(VAR val, delta: INTEGER; max: INTEGER); BEGIN val := val + delta; IF val < 0 THEN BEGIN val := 0; delta := + speed; END (*THEN*) ELSE IF val + size > max THEN BEGIN val := max - size; delta := -speed; END; (*ELSE*) END; (*Move*) BEGIN (*BouncerWindowObj.OnIdle*) InvertBall; Move(pos.x, dx, Width); Move(pos.y, dy, Height); InvertBall; END; (*BouncerWindowObj.OnIdle*) PROCEDURE BouncerWindowObj.OnCommand(commandNr: INTEGER); BEGIN IF commandNr = smallCommand THEN ChangeSize(10) ELSE IF commandNr = mediumCommand THEN ChangeSize(20) ELSE IF commandNr = largeCommand THEN ChangeSize(40) ELSE IF commandNr = crawlCommand THEN ChangeSpeed(1) ELSE IF commandNr = walkCommand THEN ChangeSpeed(5) ELSE IF commandNr = runCommand THEN ChangeSpeed(10) ELSE IF commandNr = flyCommand THEN ChangeSpeed(20) ELSE INHERITED OnCommand(commandNr); END; (*BouncerWindowObj.OnCommand*) PROCEDURE BouncerWindowObj.InvertBall; BEGIN DrawFilledOval(pos, size, size); END; (*BouncerWindowObj.InvertBall*) PROCEDURE BouncerWindowObj.ChangeSize(newSize: INTEGER); BEGIN InvertBall; size := newSize; InvertBall; END; (*BouncerWindowObj.ChangeSize*) PROCEDURE BouncerWindowObj.ChangeSpeed(newSpeed: INTEGER); BEGIN speed := newSpeed; IF dx < 0 THEN dx := -speed ELSE dx := speed; IF dy < 0 THEN dy := -speed ELSE dy := speed; END; (*BouncerWindowObj.ChangeSpeed*) (*=== BouncerApplication ===*) FUNCTION NewBouncerApplication: BouncerApplication; VAR a: BouncerApplication; BEGIN New(a, Init('Bouncer Application V.1')); NewBouncerApplication := a; END; (*NewBouncerApplication*) CONSTRUCTOR BouncerApplicationObj.Init(name: STRING); BEGIN INHERITED Init(name); Register('BouncerApplication', 'MLApplication'); END; (*BouncerApplicationObj.Init*) PROCEDURE BouncerApplicationObj.OpenNewWindow; BEGIN NewBouncerWindow^.Open; END; (*BouncerApplicationObj.OpenNewWindow*) PROCEDURE BouncerApplicationObj.BuildMenus; BEGIN (*size menu:*) smallCommand := NewMenuCommand('Size', 'Small', 'S'); mediumCommand := NewMenuCommand('Size', 'Medium', 'M'); largeCommand := NewMenuCommand('Size', 'Large', 'L'); (*speed menu:*) crawlCommand := NewMenuCommand('Speed', 'Crawl', '1'); walkCommand := NewMenuCommand('Speed', 'Walk', '2'); runCommand := NewMenuCommand('Speed', 'Run', '3'); flyCommand := NewMenuCommand('Speed', 'Fly', '4'); END; (*BouncerApplicationObj.BuildMenus*) (*=== main program ===*) VAR a: MLApplication; BEGIN (*Bouncer1*) a := NewBouncerApplication; a^.Run; Dispose(a, Done); WriteMetaInfo; END. (*Bouncer1*)
unit greenberet_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,sn_76496,gfx_engine,timer_engine, rom_engine,file_engine,pal_engine,sound_engine,qsnapshot; function iniciar_gberet:boolean; implementation const //Green Beret gberet_rom:array[0..2] of tipo_roms=( (n:'577l03.10c';l:$4000;p:0;crc:$ae29e4ff),(n:'577l02.8c';l:$4000;p:$4000;crc:$240836a5), (n:'577l01.7c';l:$4000;p:$8000;crc:$41fa3e1f)); gberet_pal:array[0..2] of tipo_roms=( (n:'577h09.2f';l:$20;p:0;crc:$c15e7c80),(n:'577h11.6f';l:$100;p:$20;crc:$2a1a992b), (n:'577h10.5f';l:$100;p:$120;crc:$e9de1e53)); gberet_char:tipo_roms=(n:'577l07.3f';l:$4000;p:0;crc:$4da7bd1b); gberet_sprites:array[0..3] of tipo_roms=( (n:'577l06.5e';l:$4000;p:0;crc:$0f1cb0ca),(n:'577l05.4e';l:$4000;p:$4000;crc:$523a8b66), (n:'577l08.4f';l:$4000;p:$8000;crc:$883933a4),(n:'577l04.3e';l:$4000;p:$c000;crc:$ccecda4c)); //Mr Goemon mrgoemon_rom:array[0..1] of tipo_roms=( (n:'621d01.10c';l:$8000;p:0;crc:$b2219c56),(n:'621d02.12c';l:$8000;p:$8000;crc:$c3337a97)); mrgoemon_pal:array[0..2] of tipo_roms=( (n:'621a06.5f';l:$20;p:0;crc:$7c90de5f),(n:'621a08.7f';l:$100;p:$20;crc:$2fb244dd), (n:'621a07.6f';l:$100;p:$120;crc:$3980acdc)); mrgoemon_char:tipo_roms=(n:'621a05.6d';l:$4000;p:0;crc:$f0a6dfc5); mrgoemon_sprites:array[0..1] of tipo_roms=( (n:'621d03.4d';l:$8000;p:0;crc:$66f2b973),(n:'621d04.5d';l:$8000;p:$8000;crc:$47df6301)); //Dip gberet_dip_a:array [0..2] of def_dip=( (mask:$0f;name:'Coin A';number:16;dip:((dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'3C 2C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))), (mask:$f0;name:'Coin B';number:16;dip:((dip_val:$20;dip_name:'4C 1C'),(dip_val:$50;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$40;dip_name:'3C 2C'),(dip_val:$10;dip_name:'4C 3C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$30;dip_name:'3C 4C'),(dip_val:$70;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$60;dip_name:'2C 5C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$90;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Invalid'))),()); gberet_dip_b:array [0..5] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'2'),(dip_val:$2;dip_name:'3'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'7'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$18;name:'Bonus Life';number:4;dip:((dip_val:$18;dip_name:'30K 70K+'),(dip_val:$10;dip_name:'40K 80K+'),(dip_val:$8;dip_name:'50K 100K+'),(dip_val:$0;dip_name:'50K 200K+'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$60;name:'Difficulty';number:4;dip:((dip_val:$60;dip_name:'Easy'),(dip_val:$40;dip_name:'Normal'),(dip_val:$20;dip_name:'Difficult'),(dip_val:$0;dip_name:'Very Difficult'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); gberet_dip_c:array [0..2] of def_dip=( (mask:$1;name:'Flip Screen';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Upright Controls';number:2;dip:((dip_val:$2;dip_name:'Single'),(dip_val:$0;dip_name:'Dual'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); mrgoemon_dip_b:array [0..5] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'2'),(dip_val:$2;dip_name:'3'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'7'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$18;name:'Bonus Life';number:4;dip:((dip_val:$18;dip_name:'20K 60K+'),(dip_val:$10;dip_name:'30K 70K+'),(dip_val:$8;dip_name:'40K 80K+'),(dip_val:$0;dip_name:'50K 90K+'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$60;name:'Difficulty';number:4;dip:((dip_val:$60;dip_name:'Easy'),(dip_val:$40;dip_name:'Normal'),(dip_val:$20;dip_name:'Difficult'),(dip_val:$0;dip_name:'Very Difficult'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var scroll_lineas:array[0..$1f] of word; memoria_rom:array[0..7,0..$7ff] of byte; interrupt_mask,interrupt_ticks,sound_latch,rom_bank,timer_hs:byte; banco_sprites:word; procedure update_video_gberet; var f,x,y,color,nchar,atrib2:word; atrib:byte; begin for f:=$7ff downto 0 do begin if gfx[0].buffer[f] then begin x:=f mod 64; y:=f div 64; //Color RAM //c000-c7ff --> Bits // 0-3 --> Color // 4 --> flip X // 5 --> Flip Y // 6 --> Numero Char // 7 --> prioridad atrib:=memoria[f+$c000]; color:=(atrib and $f) shl 4; nchar:=memoria[f+$c800]+((atrib and $40) shl 2); put_gfx_flip(x*8,y*8,nchar,color,1,0,(atrib and $10)<>0,(atrib and $20)<>0); if (atrib and $80)<>0 then put_gfx_block_trans(x*8,y*8,3,8,8) else put_gfx_mask_flip(x*8,y*8,nchar,color,3,0,0,$f,(atrib and $10)<>0,(atrib and $20)<>0); gfx[0].buffer[f]:=false; end; end; //hacer el scroll independiente linea a linea scroll__x_part2(1,2,8,@scroll_lineas); //sprites for f:=0 to $2f do begin atrib2:=$d000+banco_sprites+(f*4); atrib:=memoria[$1+atrib2]; nchar:=memoria[atrib2]+(atrib and $40) shl 2; color:=(atrib and $f) shl 4; x:=memoria[$2+atrib2]+(atrib and $80) shl 1; y:=memoria[$3+atrib2]; put_gfx_sprite_mask(nchar,color,(atrib and $10)<>0,(atrib and $20)<>0,1,0,$f); actualiza_gfx_sprite(x,y,2,1); end; scroll__x_part2(3,2,8,@scroll_lineas); actualiza_trozo_final(8,16,240,224,2); end; procedure eventos_gberet; begin if event.arcade then begin if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $F7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $Fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); end; end; procedure gberet_principal; var f,ticks_mask:byte; frame_m:single; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 255 do begin z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; if f=239 then update_video_gberet; if (f and $f)=0 then begin //every 16 scanlines ticks_mask:=not(interrupt_ticks) and (interrupt_ticks+1); // 0->1 interrupt_ticks:=interrupt_ticks+1; // NMI on d0 if (ticks_mask and interrupt_mask and 1)<>0 then z80_0.change_nmi(ASSERT_LINE); // IRQ on d4 if (ticks_mask and (interrupt_mask shl 2) and 8)<>0 then z80_0.change_irq(ASSERT_LINE); if (ticks_mask and (interrupt_mask shl 2) and 16)<>0 then z80_0.change_irq(ASSERT_LINE); end; end; eventos_gberet; video_sync; end; end; function gberet_getbyte(direccion:word):byte; begin case direccion of $0000..$e03f:gberet_getbyte:=memoria[direccion]; $f200:gberet_getbyte:=marcade.dswb; $f400:gberet_getbyte:=marcade.dswc; $f600:gberet_getbyte:=marcade.dswa; $f601:gberet_getbyte:=marcade.in1; $f602:gberet_getbyte:=marcade.in0; $f603:gberet_getbyte:=marcade.in2; $f800..$ffff:gberet_getbyte:=memoria_rom[rom_bank,direccion and $7ff]; end; end; procedure gberet_putbyte(direccion:word;valor:byte); var ack_mask:byte; begin case direccion of 0..$bfff,$f800..$ffff:; //ROM $c000..$cfff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $7ff]:=true; memoria[direccion]:=valor; end; $d000..$dfff:memoria[direccion]:=valor; $e000..$e01f:begin scroll_lineas[direccion and $1f]:=(scroll_lineas[direccion and $1f] and $100) or valor; memoria[direccion]:=valor; end; $e020..$e03f:begin scroll_lineas[direccion and $1f]:=(scroll_lineas[direccion and $1f] and $ff) or ((valor and 1) shl 8); memoria[direccion]:=valor; end; $e043:banco_sprites:=(valor and 8) shl 5; $e044:begin // bits 0/1/2 = interrupt enable ack_mask:=not(valor) and interrupt_mask; // 1->0 if (ack_mask and 1)<>0 then z80_0.change_nmi(CLEAR_LINE); if (ack_mask and 6)<>0 then z80_0.change_irq(CLEAR_LINE); interrupt_mask:=valor and 7; // bit 3 = flip screen main_screen.flip_main_screen:=(valor and 8)<>0; end; $f000:rom_bank:=(valor and $e0) shr 5; $f200:sound_latch:=valor; $f400:sn_76496_0.Write(sound_latch); end; end; procedure gberet_sound_update; begin sn_76496_0.update; end; procedure gberet_hi_score; begin if ((memoria[$db06]=3) and (memoria[$db07]=$30) and (memoria[$db08]=0) and (memoria[$db0b]=$1c)) then begin load_hi('gberet.hi',@memoria[$d900],60); copymemory(@memoria[$db06],@memoria[$d900],3); timers.enabled(timer_hs,false); end; end; procedure gberet_qsave(nombre:string); var data:pbyte; size:word; buffer:array[0..5] of byte; begin case main_vars.tipo_maquina of 17:open_qsnapshot_save('gberet'+nombre); 203:open_qsnapshot_save('mrgoemon'+nombre); end; getmem(data,200); //CPU size:=z80_0.save_snapshot(data); savedata_qsnapshot(data,size); //SND size:=sn_76496_0.save_snapshot(data); savedata_qsnapshot(data,size); //MEM savedata_com_qsnapshot(@memoria[$c000],$4000); //MISC savedata_com_qsnapshot(@scroll_lineas,$20*2); buffer[0]:=interrupt_mask; buffer[1]:=interrupt_ticks; buffer[2]:=sound_latch; buffer[3]:=banco_sprites and $ff; buffer[4]:=banco_sprites shr 8; buffer[5]:=rom_bank; savedata_qsnapshot(@buffer,6); freemem(data); close_qsnapshot; end; procedure gberet_qload(nombre:string); var data:pbyte; buffer:array[0..5] of byte; begin case main_vars.tipo_maquina of 17:if not(open_qsnapshot_load('gberet'+nombre)) then exit; 203:if not(open_qsnapshot_load('mrgoemon'+nombre)) then exit; end; getmem(data,200); //CPU loaddata_qsnapshot(data); z80_0.load_snapshot(data); //SND loaddata_qsnapshot(data); sn_76496_0.load_snapshot(data); //MEM loaddata_qsnapshot(@memoria[$c000]); loaddata_qsnapshot(@scroll_lineas); loaddata_qsnapshot(@buffer); //MISC interrupt_mask:=buffer[0]; interrupt_ticks:=buffer[1]; sound_latch:=buffer[2]; banco_sprites:=buffer[3]; banco_sprites:=banco_sprites or (buffer[4] shl 8); rom_bank:=buffer[5]; freemem(data); close_qsnapshot; fillchar(gfx[0].buffer,$800,1); end; //Main procedure reset_gberet; begin z80_0.reset; sn_76496_0.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; banco_sprites:=0; interrupt_mask:=0; interrupt_ticks:=0; sound_latch:=0; fillchar(scroll_lineas[0],$20,0); rom_bank:=0; end; procedure cerrar_gberet; begin if main_vars.tipo_maquina=17 then save_hi('gberet.hi',@memoria[$d900],60); end; function iniciar_gberet:boolean; var colores:tpaleta; f:word; ctemp1:byte; memoria_temp:array[0..$ffff] of byte; const ps_x:array[0..15] of dword=(0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4, 32*8+0*4, 32*8+1*4, 32*8+2*4, 32*8+3*4, 32*8+4*4, 32*8+5*4, 32*8+6*4, 32*8+7*4); ps_y:array[0..15] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, 64*8+0*32, 64*8+1*32, 64*8+2*32, 64*8+3*32, 64*8+4*32, 64*8+5*32, 64*8+6*32, 64*8+7*32); procedure convert_chars; begin init_gfx(0,8,8,512); gfx_set_desc_data(4,0,32*8,0,1,2,3); convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,false); end; procedure convert_sprites; begin init_gfx(1,16,16,512); gfx_set_desc_data(4,0,128*8,0,1,2,3); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); end; begin llamadas_maquina.bucle_general:=gberet_principal; llamadas_maquina.close:=cerrar_gberet; llamadas_maquina.reset:=reset_gberet; llamadas_maquina.fps_max:=60.60606060; llamadas_maquina.save_qsnap:=gberet_qsave; llamadas_maquina.load_qsnap:=gberet_qload; iniciar_gberet:=false; iniciar_audio(false); screen_init(1,512,256); screen_mod_scroll(1,512,256,511,256,256,255); screen_init(2,512,256,false,true); screen_init(3,512,256,true,false); screen_mod_scroll(3,512,256,511,256,256,255); iniciar_video(240,224); //Main CPU z80_0:=cpu_z80.create(3072000,256); z80_0.change_ram_calls(gberet_getbyte,gberet_putbyte); z80_0.init_sound(gberet_sound_update); //Sound Chips sn_76496_0:=sn76496_chip.Create(1536000); case main_vars.tipo_maquina of 17:begin //Green Beret //Timers timer_hs:=timers.init(z80_0.numero_cpu,10000,gberet_hi_score,nil,true); //cargar roms if not(roms_load(@memoria,gberet_rom)) then exit; //convertir chars if not(roms_load(@memoria_temp,gberet_char)) then exit; convert_chars; //convertir sprites if not(roms_load(@memoria_temp,gberet_sprites)) then exit; convert_sprites; //poner la paleta if not(roms_load(@memoria_temp,gberet_pal)) then exit; marcade.dswb_val:=@gberet_dip_b; end; 203:begin //Mr. Goemon if not(roms_load(@memoria_temp,mrgoemon_rom)) then exit; copymemory(@memoria,@memoria_temp,$c000); for f:=0 to 7 do copymemory(@memoria_rom[f,0],@memoria_temp[$c000+(f*$800)],$800); //convertir chars if not(roms_load(@memoria_temp,mrgoemon_char)) then exit; convert_chars; //convertir sprites if not(roms_load(@memoria_temp,mrgoemon_sprites)) then exit; convert_sprites; //poner la paleta if not(roms_load(@memoria_temp,mrgoemon_pal)) then exit; marcade.dswb_val:=@mrgoemon_dip_b; end; end; for f:=0 to 31 do begin ctemp1:=memoria_temp[f]; colores[f].r:=$21*(ctemp1 and 1)+$47*((ctemp1 shr 1) and 1)+$97*((ctemp1 shr 2) and 1); colores[f].g:=$21*((ctemp1 shr 3) and 1)+$47*((ctemp1 shr 4) and 1)+$97*((ctemp1 shr 5) and 1); colores[f].b:=0+$47*((ctemp1 shr 6) and 1)+$97*((ctemp1 shr 7) and 1); end; set_pal(colores,32); //Poner el CLUT for f:=0 to $FF do begin gfx[0].colores[f]:=memoria_temp[$20+f]+$10; gfx[1].colores[f]:=memoria_temp[$120+f] and $f; end; //DIP marcade.dswa:=$ff; marcade.dswb:=$4a; marcade.dswc:=$ff; marcade.dswa_val:=@gberet_dip_a; marcade.dswc_val:=@gberet_dip_c; //final reset_gberet; iniciar_gberet:=true; end; end.
unit ZMMsgStr19; (* ZMMsgStr19.pas - message string handler Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht, Eric W. Engler and Chris Vleghert. This file is part of TZipMaster Version 1.9. TZipMaster 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 3 of the License, or (at your option) any later version. TZipMaster 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 TZipMaster. If not, see <http://www.gnu.org/licenses/>. contact: problems@delphizip.org (include ZipMaster in the subject). updates: http://www.delphizip.org DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip modified 2010-03-15 --------------------------------------------------------------------------- *) interface uses Classes, ZipMstr19, ZMCompat19; var OnZMStr: TZMLoadStrEvent; function LoadZipStr(id: Integer): String; // '*' = Auto, '' = default US, language (number = language id) function SetZipMsgLanguage(const zl: String): String; // get language at index (<0 - default, 0 - current) function GetZipMsgLanguage(idx: Integer): String; // info (-1) = language id, 0 = name, other values as per windows LOCALE_ function GetZipMsgLanguageInfo(idx: Integer; info: Cardinal): String; function LanguageIdent(const seg: Ansistring): Ansistring; function LocaleInfo(loc: Integer; info: Cardinal): String; implementation uses Windows, SysUtils, {$IFDEF UNICODE} AnsiStrings, {$ELSE} ZMUTF819, {$ENDIF} ZMUtils19, ZMMsg19, ZMDefMsgs19, ZMExtrLZ7719; {$I '.\ZMConfig19.inc'} {$IFNDEF VERD6up} type PCardinal = ^Cardinal; {$ENDIF} const SResourceMissingFor = 'Resource missing for '; SUSDefault = 'US: default'; lchars = ['A' .. 'Z', 'a' .. 'z', '0' .. '9', '_']; Uchars = ['a' .. 'z']; Digits = ['0' .. '9']; var {$IFDEF USE_COMPRESSED_STRINGS} DefRes: TZMRawBytes; // default strings {$ENDIF} SelRes: TZMRawBytes; // selected strings SelId: Cardinal; SelName: Ansistring; Setting: bool; function LanguageIdent(const seg: Ansistring): Ansistring; var c: AnsiChar; i: Integer; begin Result := ''; for i := 1 to length(seg) do begin c := seg[i]; if not(c in lchars) then begin if (Result <> '') or (c <> ' ') then break; end else begin if (Result = '') and (c in Digits) then break; // must not start with digit if c in Uchars then c := AnsiChar(Ord(c) - $20); // convert to upper Result := Result + c; end; end; // Result := Uppercase(Result); end; // format is // id: word, data_size: word, label_size: word, label: char[], data: byte[];... ;0 // stream at id // returns id function LoadFromStream(var blk: TZMRawBytes; src: TStream): Cardinal; var r: Integer; so: TMemoryStream; sz: array [0 .. 2] of Word; szw: Integer; begin blk := ''; // empty it Result := 0; if src.Read(sz[0], 3 * sizeof(Word)) <> (3 * sizeof(Word)) then exit; if src.Size < (sz[1] + sz[2] + (3 * sizeof(Word))) then exit; src.Position := src.Position + sz[2]; // skip name try so := TMemoryStream.Create; r := LZ77Extract(so, src, sz[1]); // Assert(r = 0, 'error extracting strings'); if (r = 0) and (so.Size < 50000) then begin szw := (Integer(so.Size) + (sizeof(Word) - 1)); SetLength(blk, szw + sizeof(Word)); so.Position := 0; if so.Read(blk[1], so.Size) = so.Size then begin blk[szw + 1] := #255; blk[szw + 2] := #255; Result := sz[0]; end else blk := ''; end; finally FreeAndNil(so); end; end; // format is // id: word, data_size: word, label_size: word, label: char[], data: byte[];... ;0 // positions stream to point to id // SegName has identifier terminated by ':' function FindInStream(src: TStream; var SegName: Ansistring; var LangId: Word) : Boolean; var c: AnsiChar; i: Word; p: Int64; s: Ansistring; seg: Ansistring; ss: Int64; uname: Ansistring; w: Word; w3: array [0 .. 2] of Word; begin Result := False; if not assigned(src) then exit; seg := LanguageIdent(SegName); if (length(seg) < 2) and (LangId = 0) then exit; uname := ''; for i := 1 to length(SegName) do begin c := SegName[i]; if c in Uchars then c := AnsiChar(Ord(c) - $20); uname := uname + c; end; p := src.Position; ss := src.Size - ((3 * sizeof(Word)) + 2); // id + dlen + nlen + min 2 chars while (not Result) and (p < ss) do begin src.Position := p; src.ReadBuffer(w3[0], 3 * sizeof(Word)); // id, dsize, nsize w := w3[2]; // name size if w > 0 then begin SetLength(s, w); src.ReadBuffer(s[1], w); // read name end; if LangId = 0 then begin // find by name Result := False; for i := 1 to w do begin c := s[i]; if not(c in lchars) then break; if i > length(uname) then begin Result := False; break; end; if c in Uchars then c := AnsiChar(Ord(c) - $20); Result := c = uname[i]; if not Result then break; end; end else // find by language ID Result := (LangId = w3[0]) or ((LangId < $400) and ((w3[0] and $3FF) = LangId)); if not Result then p := src.Position + w3[1]; // skip data to next entry end; if Result then begin SegName := s; LangId := w3[0]; src.Position := p; end; end; // format is // id: word, data_size: word, label_size: word, label: char[], data: byte[];... ;0 // positions stream to point to id // segname has identifier terminated by ':' function IdInStream(src: TStream; var idx: Cardinal; var lang: String): Boolean; var p: Int64; s: Ansistring; ss: Int64; w3: array [0 .. 2] of Word; begin Result := False; if (idx < 1) or not assigned(src) then exit; p := src.Position; ss := src.Size - ((3 * sizeof(Word)) + 20); // id + dlen + nlen + 20 bytes if p > ss then exit; repeat src.ReadBuffer(w3[0], 3 * sizeof(Word)); // id, dsize, nsize if idx <= 1 then break; Dec(idx); p := src.Position + w3[1] + w3[2]; // after name + data if p < ss then src.Position := p else exit; until False; SetLength(s, w3[2]); src.ReadBuffer(s[1], w3[2]); // read name lang := String(s); idx := w3[0]; src.Position := p; Result := True; end; {$IFNDEF VERD6up} function TryStrToInt(const s: String; var v: Integer): Boolean; begin if (s = '') or not CharInSet(s[1], ['0' .. '9', '$']) then Result := False else begin Result := True; try v := StrToInt(s); except on EConvertError do Result := False; end; end; end; {$ENDIF} function SetZipMsgLanguage(const zl: String): String; var i: Integer; id: Word; len: Integer; LangName: Ansistring; newBlock: TZMRawBytes; newId: Cardinal; newres: TZMRawBytes; res: TResourceStream; begin if (zl = '') or Setting then exit; res := nil; try Setting := True; SelRes := ''; // reset to default SelId := 0; SelName := ''; Result := ''; id := 0; LangName := LanguageIdent(Ansistring(zl)); if (length(LangName) < 2) then begin if zl = '*' then id := GetUserDefaultLCID else begin if (not TryStrToInt(zl, i)) or (i <= 0) or (i > $0FFFF) then exit; id := Cardinal(i); end; end; if (LangName <> 'US') and (id <> $0409) then // use default US begin res := OpenResStream(DZRES_Str, RT_RCData); if assigned(res) and FindInStream(res, LangName, id) then begin newId := LoadFromStream(newBlock, res); if newId > 0 then begin len := length(newBlock); SetLength(newres, len); Move(newBlock[1], PAnsiChar(newres)^, len); Result := String(LangName); SelRes := newres; SelName := LangName; SelId := newId; end; end; end; finally Setting := False; FreeAndNil(res); end; end; function LocaleInfo(loc: Integer; info: Cardinal): String; var s: String; begin if (loc <= 0) or (loc = $400) then loc := LOCALE_USER_DEFAULT; SetLength(s, 1024); GetLocaleInfo(loc and $FFFF, info, PChar(s), 1023); Result := PChar(s); // remove any trailing #0 end; // get language at Idx (<0 - default, 0 - current) // info (-1) = language id, 0 = name, other values as per windows LOCALE_ function GetZipMsgLanguageInfo(idx: Integer; info: Cardinal): String; var id: Cardinal; res: TResourceStream; s: String; begin id := $0409; Result := SUSDefault; // default US English if (idx = 0) and (SelRes <> '') then begin Result := String(SelName); id := SelId; end; if idx > 0 then begin res := nil; Result := '><'; id := idx and $FF; try res := OpenResStream(DZRES_Str, RT_RCData); if assigned(res) and IdInStream(res, id, s) then Result := s; finally FreeAndNil(res); end; end; if Result <> '><' then begin if info = 0 then Result := '$' + IntToHex(id, 4) else if info <> Cardinal(-1) then Result := LocaleInfo(id, info); end; end; // get language at index (<0 - current, 0 - default, >0 - index) function GetZipMsgLanguage(idx: Integer): String; begin Result := GetZipMsgLanguageInfo(idx, Cardinal(-1)); end; // Delphi does not like adding offset function _ofsp(blk: PWord; ofs: Integer): PWord; begin Result := blk; inc(Result, ofs); end; // returns String function FindRes1(blkstr: TZMRawBytes; id: Integer): String; var blkP: PWord; bp: Integer; DatSiz: Cardinal; fid: Integer; HedSiz: Cardinal; hp: Integer; l: Cardinal; mx: Integer; rid: Integer; sz: Cardinal; ws: WideString; begin Result := ''; if blkstr = '' then exit; fid := id div 16; try blkP := PWord(PAnsiChar(blkstr)); bp := 0; mx := length(blkstr) div sizeof(Word); while (bp + 9) < mx do begin bp := (bp + 1) and $7FFFE; // dword align DatSiz := pCardinal(_ofsp(blkP, bp))^; HedSiz := pCardinal(_ofsp(blkP, bp + 2))^; if (HedSiz + DatSiz) < 8 then break; // Assert((HedSiz + DatSiz) >= 8, 'header error'); sz := (HedSiz + DatSiz) - 8; hp := bp + 4; inc(bp, 4 + (sz div 2)); if _ofsp(blkP, hp)^ <> $FFFF then continue; // bad res type if _ofsp(blkP, hp + 1)^ <> 6 then continue; // not string table if _ofsp(blkP, hp + 2)^ <> $FFFF then continue; rid := pred(_ofsp(blkP, hp + 3)^); if fid <> rid then continue; rid := rid * 16; inc(hp, (HedSiz - 8) div 2); ws := ''; while rid < id do begin l := _ofsp(blkP, hp)^; inc(hp, l + 1); inc(rid); end; l := _ofsp(blkP, hp)^; if l <> 0 then begin SetLength(ws, l); Move(_ofsp(blkP, hp + 1)^, ws[1], l * sizeof(Widechar)); Result := ws; Result := StringReplace(Result, #10, #13#10, [rfReplaceAll]); break; end; break; end; except Result := ''; end; end; {$IFNDEF USE_COMPRESSED_STRINGS} function FindConst(id: Integer): String; var p: pResStringRec; function Find(idx: Integer): pResStringRec; var wi: Word; i: Integer; begin Result := nil; wi := Word(idx); for i := 0 to high(ResTable) do if ResTable[i].i = wi then begin Result := ResTable[i].s; break; end; end; begin { FindConst } Result := ''; if id < 10000 then exit; p := Find(id); if p <> nil then Result := LoadResString(p); end; {$ELSE} // format is // id: word, data_size: word, label_size: word, label: char[], data: byte[];... ;0 function LoadCompressedDef(const src): Integer; var ms: TMemoryStream; w: Word; pw: PWord; begin Result := -1; pw := @src; if pw^ = $0409 then begin inc(pw); w := pw^; inc(pw); inc(w, pw^); inc(w, (3 * sizeof(Word))); try ms := TMemoryStream.Create; ms.Write(src, w); ms.Position := 0; Result := LoadFromStream(DefRes, ms); finally FreeAndNil(ms); end; end; end; {$ENDIF} // returns String function LoadZipStr(id: Integer): String; var d: String; blk: TZMRawBytes; tmpOnZipStr: TZMLoadStrEvent; begin Result := ''; blk := SelRes; Result := FindRes1(blk, id); {$IFDEF USE_COMPRESSED_STRINGS} if Result = '' then begin if DefRes = '' then LoadCompressedDef(CompBlok); blk := DefRes; Result := FindRes1(blk, id); end; {$ELSE} if Result = '' then Result := FindConst(id); {$ENDIF} tmpOnZipStr := OnZMStr; if assigned(tmpOnZipStr) then begin d := Result; tmpOnZipStr(id, d); if d <> '' then Result := d; end; if Result = '' then Result := SResourceMissingFor + IntToStr(id); end; initialization OnZMStr := nil; Setting := False; {$IFDEF USE_COMPRESSED_STRINGS} DefRes := ''; {$ENDIF} SelRes := ''; finalization {$IFDEF USE_COMPRESSED_STRINGS} DefRes := ''; // force destruction {$ENDIF} SelRes := ''; end.
unit NLDTGlobal; { :: NLDTGlobals contains all of the global variables and functions. This unit :: may contain only generic functions which might be used by other units, :: specific functionality must be contained within the appropriate unit. :$ :$ :$ NLDTranslate is released under the zlib/libpng OSI-approved license. :$ For more information: http://www.opensource.org/ :$ /n/n :$ /n/n :$ Copyright (c) 2002 M. van Renswoude :$ /n/n :$ This software is provided 'as-is', without any express or implied warranty. :$ In no event will the authors be held liable for any damages arising from :$ the use of this software. :$ /n/n :$ Permission is granted to anyone to use this software for any purpose, :$ including commercial applications, and to alter it and redistribute it :$ freely, subject to the following restrictions: :$ /n/n :$ 1. The origin of this software must not be misrepresented; you must not :$ claim that you wrote the original software. If you use this software in a :$ product, an acknowledgment in the product documentation would be :$ appreciated but is not required. :$ /n/n :$ 2. Altered source versions must be plainly marked as such, and must not be :$ misrepresented as being the original software. :$ /n/n :$ 3. This notice may not be removed or altered from any source distribution. } {$I NLDTDefines.inc} interface uses SysUtils, Classes, XDOM_2_3, NLDTInterfaces; type { :$ The specified file does not exist. :: ENLDTFileDoesNotExist is raised when the specified language file could :: not be found. } ENLDTFileDoesNotExist = class(Exception); { :$ The specified file is invalid. :: ENLDTInvalidLangFile is raised when the specified language file does :: not conform to the standard. } ENLDTInvalidLangFile = class(Exception); { :$ Provides a base for NLDTranslate components :: NLDTBaseComponent descends from TComponent and implements the IUnknown :: interface. In this way it does the same thing for TComponent which :: TInterfacedObject does for TObject, except it implicitly adds a :: reference if an Owner is supplied. This prevents the component from :: being destroyed if it is placed on a form. If you do not want this :: behaviour, set AutoDestroy to False, this will prevent the component :: from being destroyed automatically. } TNLDTBaseComponent = class(TComponent, IUnknown) private FAutoDestroy: Boolean; FRefCount: Integer; protected function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public constructor Create(AOwner: TComponent); override; //:$ Determines if the component should be reference-counted //:: Set AutoDestroy to False to prevent the component from being destroyed //:: once the last reference is cleared. //:! Make sure to set AutoDestroy to False directly after creating the //:! component to make sure it will not be destroyed! property AutoDestroy: Boolean read FAutoDestroy write FAutoDestroy; //:$ Returns the current reference count //:: RefCount provides access to the internal reference count. The //:: reference count is inherited from the IUnknown interface. property RefCount: Integer read FRefCount; end; { :$ Implements the INLDTTreeItem interface :: TNLDTTreeItem provides a wrapper around an XML element found in :: the language file. It is primarily used to be passed to the :: translator interfaces. } TNLDTTreeItem = class(TInterfacedObject, INLDTInterface, INLDTTreeItem) private FNode: TDomElement; public //:$ Initializes a new TNLDTTreeItem instance constructor Create(ANode: TDomElement); // INLDTTreeItem implementation //:$ Returns the name of the tree item function GetName(): String; stdcall; //:$ Returns the value of the tree item function GetValue(): String; stdcall; //:$ Returns the number of attributes for the tree item //:: Call GetAttributeCount to get the number of attributes available for //:: the tree item. You can use the GetAttribute method to get the //:: value for a specific attribute. function GetAttributeCount(): Integer; virtual; stdcall; //:$ Returns the name of the specified attribute //:: Use GetAttributeName to get the name of an attribute. The AIndex //:: must be between 0 and GetAttributeCount - 1 or an exception is raised. function GetAttributeName(const AIndex: Integer): String; virtual; stdcall; //:$ Returns the value of the specified attribute //:: Use GetAttributeValue to get the value of an attribute. The AIndex //:: must be between 0 and GetAttributeCount - 1 or an exception is raised. function GetAttributeValue(const AIndex: Integer): String; virtual; stdcall; //:$ Returns the value of the specified attribute //:: Use GetAttributeValueByName to get the value of an attribute. The AName //:: parameter represent the attribute's name. Returns an empty string if //:: the attribute is not found. function GetAttributeValueByName(const AName: String): String; virtual; stdcall; //:$ Gets or sets the Node associated with the tree item //:: Set Node to a valid TDomElement to allow the INLDTTreeItem interface //:: to be implemented. property Node: TDomElement read FNode write FNode; end; { :$ Includes a trailing path delimiter (slash or backslash) :: This function encapsulates the functions IncludeTrailingPathDelimiter :: and IncludeTrailingBackslash, depending on the compiler version. This :: eliminates the 'function is deprecated' warning. } function NLDTIncludeDelimiter(const ASource: String): String; { :$ Exclude a trailing path delimiter (slash or backslash) :: This function encapsulates the functions ExcludeTrailingPathDelimiter :: and ExcludeTrailingBackslash, depending on the compiler version. This :: eliminates the 'function is deprecated' warning. } function NLDTExcludeDelimiter(const ASource: String): String; { :$ Replace predefined variables :: Replaces predefined variables in path parameters. This function :: must be called by any NLDTranslate implementation using paths. } function NLDTReplacePathVars(const ASource: String): String; implementation uses {$IFDEF NLDT_FASTSTRINGS} FastStrings, {$ENDIF} NLDTXDOMUtils, Windows; var GVar_AppPath: String; {******************** TNLDTBaseComponent Initialization ****************************************} constructor TNLDTBaseComponent.Create; begin inherited; FAutoDestroy := True; if Assigned(AOwner) then _AddRef(); end; {******************** TNLDTBaseComponent IUnknown implementation ****************************************} function TNLDTBaseComponent._AddRef; begin Result := InterlockedIncrement(FRefCount); end; function TNLDTBaseComponent._Release; begin Result := InterlockedDecrement(FRefCount); if (Result = 0) and (not FAutoDestroy) then Destroy; end; function TNLDTBaseComponent.QueryInterface; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; {*********************************** TNLDTTreeItem Constructor **************************************************} constructor TNLDTTreeItem.Create; begin inherited Create(); FNode := ANode; end; {*********************************** TNLDTTreeItem INLDTTreeItem implementation **************************************************} function TNLDTTreeItem.GetName; begin Result := ''; if not Assigned(FNode) then exit; Result := FNode.nodeName; end; function TNLDTTreeItem.GetValue; begin Result := ''; if not Assigned(FNode) then exit; Result := FNode.textContent; end; function TNLDTTreeItem.GetAttributeCount; begin Result := 0; if not Assigned(FNode) then exit; Result := FNode.attributes.length; end; function TNLDTTreeItem.GetAttributeName; var xmlAttr: TDomNode; begin Result := ''; if not Assigned(FNode) then exit; xmlAttr := FNode.attributes.item(AIndex); if Assigned(xmlAttr) then Result := xmlAttr.nodeName; end; function TNLDTTreeItem.GetAttributeValue; begin Result := ''; if not Assigned(FNode) then exit; Result := XDOMGetAttributeByIndex(FNode, AIndex); end; function TNLDTTreeItem.GetAttributeValueByName; begin Result := ''; if not Assigned(FNode) then exit; Result := XDOMGetAttribute(FNode, AName); end; {**************************************** Include trailing path delimiter ****************************************} function NLDTIncludeDelimiter; begin {$IFDEF NLDT_D6} Result := IncludeTrailingPathDelimiter(ASource); {$ELSE} Result := IncludeTrailingBackslash(ASource); {$ENDIF} end; {**************************************** Exclude trailing path delimiter ****************************************} function NLDTExcludeDelimiter; begin {$IFDEF NLDT_D6} Result := ExcludeTrailingPathDelimiter(ASource); {$ELSE} Result := ExcludeTrailingBackslash(ASource); {$ENDIF} end; {**************************************** Replace variables ****************************************} function NLDTReplacePathVars; procedure InternalReplace(var ASource: String; const AVarName, AVarValue: String); begin {$IFDEF NLDT_FASTSTRINGS} ASource := FastReplace(ASource, '{' + AVarName + '}', AVarValue, False); {$ELSE} ASource := StringReplace(ASource, '{' + AVarName + '}', AVarValue, [rfReplaceAll, rfIgnoreCase]); {$ENDIF} end; begin Result := ASource; InternalReplace(Result, 'APPPATH', GVar_AppPath); end; initialization // Prepare variables GVar_AppPath := NLDTExcludeDelimiter(ExtractFilePath(ParamStr(0))); end.
unit ModelServerCache; interface uses SysUtils, SyncObjs, CacheAgent, CacheCommon, RDOInterfaces, RDORootServer, Collection; procedure RegisterCacher(const ClassName : string; Agent : CCacheAgent); function GetObjectPath(Obj : TObject; kind, info : integer) : string; function CacheObject(Obj : TObject; kind, info : integer) : boolean; function CacheColl(Coll : TCollection) : boolean; function CacheMetaObject(Obj : TObject; kind, info : integer) : boolean; function UncacheObject(Obj : TObject; kind, info : integer) : boolean; function UncacheColl(Coll : TCollection) : boolean; function UncacheMetaObject(Obj : TObject; kind, info : integer) : boolean; function UpdateObjectCache(Obj : TObject; kind, info : integer) : boolean; function UpdateObjectCacheEx(Obj : TObject; kind, info : integer; update : boolean) : TObjectCache; function SaveImage(Obj : TObjectCache) : boolean; procedure InitModelServerCache; procedure CreateCacheServer(ServerConn : IRDOConnectionsServer; MaxQueryThreads : integer; theWorldLock : TCriticalSection); procedure DoneModelServerCache; function RegisterWorld(const Name, RemoteAddress : WideString; LocalPort, RemotePort : integer; var WorldURL : string) : boolean; procedure SetWorldName(aName : string); function GetWorldName : string; function GetGlobalPath(const path : string) : string; function CreateMapLink(X, Y : integer; const path : string) : string; function CreateOutputLink(X, Y, K, P, C : integer; const Output, Town, Company, Utility, Circuits : string; Role : TFacilityRole) : string; function CreateInputLink(X, Y, Capacity, SupLevel : integer; const Input, Town, Company, Utility, Circuits : string; Role : TFacilityRole) : string; procedure SetMSVersion(ver : integer); procedure SetBackupSection(sect : TCriticalSection); procedure InformBackup(inBackup : boolean); procedure SetLogPath(aPath : string); procedure ClearCacheLog; procedure SetLogVer(ver : integer); procedure WarpLog(ver : integer); //function CreateFacLink(aPath, info : string; MaxTries : integer) : boolean; procedure BackgroundCache(Obj : TObject; rcLinks : boolean); procedure BackgroundUncache(Obj : TObject); procedure BackgroundInvalidateCache(Obj : TObject); function InvalidateCache(Obj : TObject; MetaObject : boolean) : boolean; function InvalidateObjectByPath(path : string) : boolean; procedure CacheObjectLinks(path, links : string); type EMSCacheRDOError = class(Exception); TOnRenewCache = function(Agent, ObjId : string) : TObjectCache of object; TMSObjectCacher = class(TRDORootServer) private fOnRenewCache : TOnRenewCache; public property OnRenewCache : TOnRenewCache read fOnRenewCache write fOnRenewCache; private procedure LockCache; procedure UnlockCache; procedure LockMS; procedure UnlockMS; private fCLCounter : integer; fMLCounter : integer; fCaching : boolean; private function GetReport : string; published function GetCache (Id, kind, info : integer) : OleVariant; function RenewCache(Agent, ObjId : WideString) : OleVariant; property Report : string read GetReport; end; var EnabledLogs : boolean = false; MSVersion : integer = 0; MSCacher : TMSObjectCacher = nil; CacheLock : TCriticalSection = nil; BackingUp : boolean = false; BackupSection : TCriticalSection = nil; implementation uses WinSockRDOConnection, RDOObjectProxy, Logs; const MSCacheDLL = 'ModelServerCache.dll'; const RDOCacheServerTimeout = 10000; procedure RegisterCacher( const ClassName : string; Agent : CCacheAgent ); external MSCacheDLL; function dllCacheObject(Obj : TObject; kind, info : integer) : boolean; external MSCacheDLL name 'CacheObject'; function CacheObject(Obj : TObject; kind, info : integer) : boolean; begin if EnabledLogs then begin {$IFDEF USELogs} //Logs.Log('Cache', TimeToStr(Now) + ' Cache(' + Obj.ClassName + ')'); {$ENDIF} try result := dllCacheObject(Obj, kind, info); {$IFDEF USELogs} //Logs.Log('Cache', TimeToStr(Now) + ' OK!'); {$ENDIF} except {$IFDEF USELogs} //Logs.Log('Survival', DateTimeToStr(Now) + ' MS Error caching object!'); {$ENDIF} result := false; end; end else try result := dllCacheObject(Obj, kind, info); except result := false; end; end; function CacheColl(Coll : TCollection) : boolean; var i : integer; begin result := true; for i := 0 to pred(Coll.Count) do if not CacheObject( Coll[i], noKind, noInfo ) then result := false; end; function GetObjectPath( Obj : TObject; kind, info : integer ) : string; external MSCacheDLL; (* function dllGetObjectPath( Obj : TObject ) : string; external MSCacheDLL name 'GetObjectPath'; function GetObjectPath( Obj : TObject ) : string; begin if EnabledLogs then begin {$IFDEF USELogs} Logs.Log('Cache', TimeToStr(Now) + ' Getting Object Path: ' + Obj.ClassName); {$ENDIF} try result := dllGetObjectPath(Obj); {$IFDEF USELogs} Logs.Log('Cache', TimeToStr(Now) + ' Getting Object Path succeed.'); {$ENDIF} except {$IFDEF USELogs} Logs.Log('Cache', TimeToStr(Now) + ' Error Getting Object Path.'); {$ENDIF} result := ''; end; end else try result := dllGetObjectPath(Obj); except result := ''; end; end; *) function CacheMetaObject( Obj : TObject; kind, info : integer ) : boolean; external MSCacheDLL; function dllUncacheObject( Obj : TObject; kind, info : integer ) : boolean; external MSCacheDLL name 'UncacheObject'; function UncacheObject( Obj : TObject; kind, info : integer ) : boolean; begin if EnabledLogs then begin {$IFDEF USELogs} //Logs.Log('Cache', TimeToStr(Now) + ' Uncache(' + Obj.ClassName + ')'); {$ENDIF} try result := dllUnCacheObject(Obj, kind, info); {$IFDEF USELogs} //Logs.Log('Cache', TimeToStr(Now) + ' OK!'); {$ENDIF} except {$IFDEF USELogs} //Logs.Log('Cache', TimeToStr(Now) + ' Error!'); {$ENDIF} result := false; end; end else try result := dllUnCacheObject(Obj, kind, info); except result := false; end; end; function UncacheColl(Coll : TCollection) : boolean; var i : integer; begin result := true; for i := 0 to pred(Coll.Count) do if not UncacheObject( Coll[i], noKind, noInfo ) then result := false; end; function UncacheMetaObject(Obj : TObject; kind, info : integer) : boolean; external MSCacheDLL; function UpdateObjectCache(Obj : TObject; kind, info : integer) : boolean; external MSCacheDLL; function UpdateObjectCacheEx(Obj : TObject; kind, info : integer; update : boolean) : TObjectCache; external MSCacheDLL; function SaveImage(Obj : TObjectCache) : boolean; external MSCacheDLL; procedure InitCachers; external MSCacheDLL; procedure DoneCachers; external MSCacheDLL; function GetGlobalPath(const path : string) : string; external MSCacheDLL; function CreateMapLink(X, Y : integer; const path : string) : string; external MSCacheDLL; function CreateOutputLink(X, Y, K, P, C : integer; const Output, Town, Company, Utility, Circuits : string; Role : TFacilityRole) : string; external MSCacheDLL; function CreateInputLink(X, Y, Capacity, SupLevel : integer; const Input, Town, Company, Utility, Circuits : string; Role : TFacilityRole) : string; external MSCacheDLL; procedure SetMSVersion(ver : integer); external MSCacheDLL; function GetWorldName : string; external MSCacheDLL; procedure SetWorldName(aName : string); external MSCacheDLL; function GetCacheRootPath : string; external MSCacheDLL; procedure SetCacheRootPath(const aPath : string); external MSCacheDLL; procedure SetLogPath(aPath : string); external MSCacheDLL; procedure ClearCacheLog; external MSCacheDLL; procedure SetLogVer(ver : integer); external MSCacheDLL; procedure WarpLog(ver : integer); external MSCacheDLL; //function CreateFacLink(aPath, info : string; MaxTries : integer) : boolean; external MSCacheDLL; procedure BackgroundCache(Obj : TObject; rcLinks : boolean); external MSCacheDLL; procedure BackgroundUncache(Obj : TObject); external MSCacheDLL; procedure BackgroundInvalidateCache(Obj : TObject); external MSCacheDLL; function InvalidateCache(Obj : TObject; MetaObject : boolean) : boolean; external MSCacheDLL; function InvalidateObjectByPath(path : string) : boolean; external MSCacheDLL; procedure CacheObjectLinks(path, links : string); external MSCacheDLL; procedure SetBackupSection(sect : TCriticalSection); begin BackupSection := sect; end; procedure InformBackup(inBackup : boolean); begin CacheLock.Enter; try BackingUp := inBackup; finally CacheLock.Leave; end; end; // TMSObjectCacher: is the class registered to allow remote modules access // cache using RDO. procedure TMSObjectCacher.LockCache; begin inc(fCLCounter); if CacheLock <> nil then CacheLock.Enter; end; procedure TMSObjectCacher.UnlockCache; begin if CacheLock <> nil then CacheLock.Leave; dec(fCLCounter); end; procedure TMSObjectCacher.LockMS; begin inc(fMLCounter); if BackupSection <> nil then BackupSection.Enter; end; procedure TMSObjectCacher.UnlockMS; begin if BackupSection <> nil then BackupSection.Leave; dec(fMLCounter); end; function TMSObjectCacher.GetCache(Id, kind, info : integer) : OleVariant; var Obj : TObject; Img : TObjectCache; begin result := resError; LockCache; try Obj := TObject(Id); if Obj <> nil then try {$IFDEF USELogs} //Logs.Log('Cache', TimeToStr(Now) + ' GenImage Start: ' + Obj.ClassName + '(' + IntToStr(Id) + ')'); {$ENDIF} if not BackingUp then begin LockMS; // >>> SALVAJADA in Maceo street fCaching := true; try Img := UpdateObjectCacheEx(Obj, kind, info, false); finally fCaching := false; UnlockMS; // >>> SALVAJADA in Maceo street end; end else begin result := resOK; Img := nil; end; except Img := nil; result := resError; end else begin result := resError; Img := nil; end; {$IFDEF USELogs} {if Img <> nil then Logs.Log('Cache', TimeToStr(Now) + ' GenImage end.') else Logs.Log('Cache', DateTimeToStr(Now) + ' Error in GenImage.');} {$ENDIF} finally UnlockCache; end; // Save Image if Img <> nil then try try ModelServerCache.SaveImage(Img); result := resOk; finally Img.Free; end; except result := resError; end; end; function TMSObjectCacher.RenewCache(Agent, ObjId : WideString) : OleVariant; var Img : TObjectCache; begin Img := nil; result := resError; LockCache; try {$IFDEF USELogs} //Logs.Log('Cache', TimeToStr(Now) + ' RDO renewing cache Agent = ' + Agent + '; ObjId = ' + ObjId); {$ENDIF} try if not BackingUp then begin LockMS; fCaching := true; try if Assigned(fOnRenewCache) then Img := fOnRenewCache(Agent, ObjId); finally fCaching := false; UnlockMS; end; end else begin result := resOK; Img := nil; end; except Img := nil; end; {$IFDEF USELogs} {if Img <> nil then Logs.Log('Cache', TimeToStr(Now) + ' Renew GenImage end.') else Logs.Log('Cache', DateTimeToStr(Now) + ' Error in Renew GenImage.');} {$ENDIF} finally UnlockCache; end; // Save Image if Img <> nil then try try ModelServerCache.SaveImage(Img); result := resOk; finally Img.Free; end; except result := resError; end; end; function TMSObjectCacher.GetReport : string; begin result := 'CL: ' + IntToStr(fCLCounter) + ' MSL: ' + IntToStr(fMLCounter); if fCaching then result := result + ' and caching...' end; procedure InitModelServerCache; begin InitCachers; CacheLock := TCriticalSection.Create; end; procedure CreateCacheServer(ServerConn : IRDOConnectionsServer; MaxQueryThreads : integer; theWorldLock : TCriticalSection); begin MSCacher := TMSObjectCacher.Create(ServerConn, MaxQueryThreads, nil, MSObjectCacherName); //MSCacher.RDOServer.SetCriticalSection(WorldLock); SetBackupSection(theWorldLock); end; procedure DoneModelServerCache; begin MSCacher.Free; DoneCachers; CacheLock.Free; CacheLock := nil; end; function RegisterWorld(const Name, RemoteAddress : WideString; LocalPort, RemotePort : integer; var WorldURL : string) : boolean; var ClientConn : IRDOConnectionInit; Proxy : OleVariant; Addr : string; begin SetWorldName(Name); ClientConn := TWinSockRDOConnection.Create('ClientConn'); ClientConn.Server := RemoteAddress; ClientConn.Port := RemotePort; if ClientConn.Connect(RDOCacheServerTimeout) then begin try Proxy := TRDOObjectProxy.Create as IDispatch; Proxy.SetConnection(ClientConn); if Proxy.BindTo(WSObjectCacherName) then begin SetCacheRootPath(Proxy.CachePath); WorldURL := Proxy.WorldURL; Addr := (ClientConn as IRDOConnection).LocalAddress; result := Proxy.RegisterWorld(Name, Addr, LocalPort, MSVersion); SetMSVersion(MSVersion); end else result := false; except result := false; end; end else result := false; end; end.
namespace RemObjects.Train.API; uses RemObjects.Train, System.Threading, RemObjects.Script.EcmaScript, RemObjects.Script.EcmaScript.Internal, System.Text, System.Text.RegularExpressions, System.Xml.Linq, System.Linq, System.IO, System.Runtime.InteropServices; type [PluginRegistration] WindowsPlugin = public class(IPluginRegistration) public method Register(aServices: IApiRegistrationServices); begin if System.Environment.OSVersion.Platform = PlatformID.Win32NT then begin var lWindowsObject := aServices.RegisterObjectValue('windows'); lWindowsObject.AddValue('createStartMenuShortcut', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(WindowsPlugin), 'createStartMenuShortcut')); lWindowsObject.AddValue('createShortcut', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(WindowsPlugin), 'createShortcut')); lWindowsObject.AddValue('getSpecialFolder', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(WindowsPlugin), 'getSpecialFolder')); end; end; [WrapAs('windows.createStartMenuShortcut', SkipDryRun := false)] class method createStartMenuShortcut(aServices: IApiRegistrationServices; ec: ExecutionContext; aDestinationPath: String; aName: String := nil; aDescription: String := nil; aSubFolder: String := nil): Boolean; begin var link := new ShellLink() as IShellLink; // setup shortcut information link.SetDescription(aDescription); link.SetPath(aDestinationPath); // save it var file := System.Runtime.InteropServices.ComTypes.IPersistFile(link); var lPath := System.Environment.GetFolderPath(System.Environment.SpecialFolder.StartMenu); if assigned(aSubFolder) then begin lPath := Path.Combine(lPath, aSubFolder); Directory.CreateDirectory(lPath); end; if length(aName) = 0 then aName := Path.GetFileNameWithoutExtension(aDestinationPath); file.Save(Path.Combine(lPath, aName+".lnk"), false); end; [WrapAs('windows.createShortcut', SkipDryRun := false)] class method createShortcut(aServices: IApiRegistrationServices; ec: ExecutionContext; aDestinationPath: String; aName: String; aFolder: String; aDescription: String := nil): Boolean; begin var link := new ShellLink() as IShellLink; // setup shortcut information link.SetDescription(aDescription); link.SetPath(aDestinationPath); // save it var file := System.Runtime.InteropServices.ComTypes.IPersistFile(link); var lPath: String; if assigned(aFolder) then begin lPath := aFolder; Directory.CreateDirectory(lPath); end else begin lPath := Path.GetDirectoryName(aDestinationPath); end; if length(aName) = 0 then aName := Path.GetFileNameWithoutExtension(aDestinationPath); file.Save(Path.Combine(lPath, aName+".lnk"), false); end; [WrapAs('windows.getSpecialFolder', SkipDryRun := false)] class method getSpecialFolder(aServices: IApiRegistrationServices; ec: ExecutionContext; aFolderName: String): String; begin var value := System.Environment.SpecialFolder(Enum.Parse(typeOf(System.Environment.SpecialFolder), aFolderName)); exit System.Environment.GetFolderPath(value); end; end; [ComImport] [Guid("00021401-0000-0000-C000-000000000046")] ShellLink = assembly class end; [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("000214F9-0000-0000-C000-000000000046")] IShellLink = assembly interface method GetPath([&Out] [MarshalAs(UnmanagedType.LPWStr)] pszFile: StringBuilder; cchMaxPath: Integer; out pfd: IntPtr; fFlags: Integer); method GetIDList(out ppidl: IntPtr); method SetIDList(pidl: IntPtr); method GetDescription([&Out] [MarshalAs(UnmanagedType.LPWStr)] pszName: StringBuilder; cchMaxName: Integer); method SetDescription([MarshalAs(UnmanagedType.LPWStr)] pszName: String); method GetWorkingDirectory([&Out] [MarshalAs(UnmanagedType.LPWStr)] pszDir: StringBuilder; cchMaxPath: Integer); method SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] pszDir: String); method GetArguments([&Out] [MarshalAs(UnmanagedType.LPWStr)] pszArgs: StringBuilder; cchMaxPath: Integer); method SetArguments([MarshalAs(UnmanagedType.LPWStr)] pszArgs: String); method GetHotkey(out pwHotkey: Int16); method SetHotkey(wHotkey: Int16); method GetShowCmd(out piShowCmd: Integer); method SetShowCmd(iShowCmd: Integer); method GetIconLocation([&Out] [MarshalAs(UnmanagedType.LPWStr)] pszIconPath: StringBuilder; cchIconPath: Integer; out piIcon: Integer); method SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] pszIconPath: String; iIcon: Integer); method SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] pszPathRel: String; dwReserved: Integer); method Resolve(hwnd: IntPtr; fFlags: Integer); method SetPath([MarshalAs(UnmanagedType.LPWStr)] pszFile: String); end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, OoMisc, AdPort, Vcl.StdCtrls; type TForm1 = class(TForm) ApdComPort1: TApdComPort; Label1: TLabel; Memo1: TMemo; Button1: TButton; procedure ApdComPort1TriggerAvail(CP: TObject; Count: Word); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private Fmotdepasse: string; Fsaisieencours: string; { Déclarations privées } procedure demarrer; procedure ajouter_chiffre(c: ansichar); procedure Setmotdepasse(const Value: string); procedure Setsaisieencours(const Value: string); procedure tester_mot_de_passe; property motdepasse: string read Fmotdepasse write Setmotdepasse; property saisieencours: string read Fsaisieencours write Setsaisieencours; public { Déclarations publiques } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.ajouter_chiffre(c: ansichar); begin if (c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) and (motdepasse.Length > 0) then begin saisieencours := saisieencours + c; Label1.caption := Label1.caption + c; if saisieencours.Length = motdepasse.Length then tester_mot_de_passe; end else beep; end; procedure TForm1.ApdComPort1TriggerAvail(CP: TObject; Count: Word); var c: ansichar; begin while (Count > 0) do begin c := ApdComPort1.GetChar; ajouter_chiffre(c); dec(Count); end; end; procedure TForm1.Button1Click(Sender: TObject); begin Button1.Visible := false; demarrer; end; procedure TForm1.demarrer; var i: integer; begin Memo1.Lines.Clear; Label1.caption := ''; saisieencours := ''; motdepasse := ''; for i := 1 to 4 do motdepasse := motdepasse + random(10).tostring; Memo1.Lines.Add('A vous de jouer !'); Memo1.Lines.Add('- => chiffre inconnu'); Memo1.Lines.Add('x => chiffre mal positionné'); Memo1.Lines.Add('X => chiffre à sa place'); end; procedure TForm1.FormCreate(Sender: TObject); begin ApdComPort1.Open := true; Label1.caption := ''; Memo1.Lines.Clear; end; procedure TForm1.Setmotdepasse(const Value: string); begin Fmotdepasse := Value; end; procedure TForm1.Setsaisieencours(const Value: string); begin Fsaisieencours := Value; end; procedure TForm1.tester_mot_de_passe; var i: integer; rep_justes: integer; rep: string; begin Label1.caption := ''; rep_justes := 0; for i := 0 to saisieencours.Length - 1 do begin if (saisieencours.Substring(i, 1) = motdepasse.Substring(i, 1)) then begin inc(rep_justes); rep := rep + 'X'; end else if motdepasse.Contains(saisieencours.Substring(i, 1)) then rep := rep + 'x' else rep := rep + '-'; end; if rep_justes = motdepasse.Length then begin Memo1.Lines.Add('Bravo, c''était bien ' + saisieencours); Button1.Visible := true; end else begin Memo1.Lines.Add(saisieencours + ' ' + rep); saisieencours := ''; end; end; end.
unit Constants; interface const pickaxeType = $0E85; ingotType = $1BEF; oneOrePileType = $19B7; twoOresPileType = $19BA; threeOresPileType = $19B8; fourOresPileType = $19B9; oneSausageType = $09C0; luteType = $0EB3; logPileType = $1BDD; tinkerToolsType = $1EBC; sawType = $1034; scrollsType = $0E34; bottleType = $0F0E; emptyBottleColor = $0000; lesserPoisonBottleColor = $0049; nightshadeType = $0F88; daggerType = $0F51; shaftsType = $1BD4; foldedClothType = $175D; sewingKitType = $0F9D; clothBoxType = $1422; clothBoxColor = $0041; antidoteClothBoxColor = $009B; tameHarpType = $0EB2; tameHarpColor = $0185; tinkersToolsType = $1EBC; springsType = $105D; clockPartsType = $104F; ceramicColor = $00F2; starSapphireType = $0F0F; emeraldType = $0F10; sapphireType = $0F11; rubyType = $0F13; citrineType = $0F15; amethystType = $0F16; tourmalineType = $0F18; diamondType = $0F26; mapRollType = $14ED; fishingPoleType = $0DBF; greenFishType = $09CC; brownFishType = $09CD; purpleFishType = $09CE; yellowFishType = $09CF; shipContainerType = $3EAE; rawFishSteakType = $097A; fishSteakType = $097B; fryPanType = $097F; sulfurousAshType = $0F8C; bloodyBandageType = $0E20; cleanBandageType = $0E21; magicArrowScrollsType = $1F32; shepherdsCrookType = $0E81; pigType = $00CB; var orePileTypes: array of Cardinal; logPileTypes: array of Cardinal; gemStoneTypes: array of Cardinal; fishTypes: array of Cardinal; implementation initialization begin SetLength(orePileTypes, 4); orePileTypes[0] := oneOrePileType; orePileTypes[1] := twoOresPileType; orePileTypes[2] := threeOresPileType; orePileTypes[3] := fourOresPileType; SetLength(logPileTypes, 1); logPileTypes[0] := logPileType; SetLength(gemStoneTypes, 8); gemStoneTypes[0] := amethystType; gemStoneTypes[1] := citrineType; gemStoneTypes[2] := diamondType; gemStoneTypes[3] := emeraldType; gemStoneTypes[4] := rubyType; gemStoneTypes[5] := sapphireType; gemStoneTypes[6] := starSapphireType; gemStoneTypes[7] := tourmalineType; SetLength(fishTypes, 4); fishTypes[0] := greenFishType; fishTypes[1] := brownFishType; fishTypes[2] := purpleFishType; fishTypes[3] := yellowFishType; end; end.
unit nsRegistryTools; interface uses Windows ; function GetStringFromRegistry(const aRootKey : HKEY; const aPathKey : string; const aValueName : string; const aDefaultValue : string = ''): string; {-} implementation uses Registry ; function GetStringFromRegistry(const aRootKey: HKEY; const aPathKey: string; const aValueName: string; const aDefaultValue: string): string; begin Result := aDefaultValue; try with TRegistry.Create do try RootKey := aRootKey; if OpenKey(aPathKey, False) then try if ValueExists(aValueName) then Result := ReadString(aValueName); finally CloseKey; end; finally Free; end; except on ERegistryException do; end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP; type TForm1 = class(TForm) IdHTTP1: TIdHTTP; Button1: TButton; Memo1: TMemo; Edit1: TEdit; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var Json: String; Temp: TStringList; begin try Json := IdHTTP1.Get('http://api.rest7.com/v1/ip_to_city.php?ip=' + Edit1.Text); except ShowMessage('Check Internet connection'); Exit; end; if Pos('success":1', Json) < 1 then begin ShowMessage('IP2City failed'); Exit; end; Json := StringReplace(Json, ':', ',', [rfReplaceAll]); Temp := TStringList.Create; Temp.Delimiter := ','; Temp.DelimitedText := Json; Memo1.Lines.Add('Country= ' + Temp[1]); Memo1.Lines.Add('Region= ' + Temp[3]); Memo1.Lines.Add('City= ' + Temp[5]); Memo1.Lines.Add('Latitude= ' + Temp[7]); Memo1.Lines.Add('Longitude= ' + Temp[9]); Temp.Free; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects; type TForm1 = class(TForm) Image1: TImage; procedure Image1Gesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); private { Déclarations privées } LastAngle:Double; public { Déclarations publiques } end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.Image1Gesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); begin if EventInfo.GestureID=igiRotate then begin if (TInteractiveGestureFlag.gfBegin in EventInfo.Flags) then LastAngle:=Image1.RotationAngle else begin if EventInfo.Angle<>0 then begin Image1.RotationAngle:=LastAngle - (EventInfo.Angle*180) / Pi; end; end; end; end; end.
unit kwIterateSubDescriptors; {* Перебирает все SubDescriptot на SubPanel, которые могут быть использованы (!). Такой список задается на этапе проектирвоания/изменения компонета. И не зависит от вида отображения. Формат: [code] @ aWord aLayerID aSubPanel ItarateSubDescriptors [code] aLayerID - слой, в котором производится итерация aSubPanel - контрол сабпанели. aWord - функция для обработки вида: [code] PROCEDURE CheckDescription OBJECT IN aSubDescription // А здесь обрабатываем полученный aSubDescription ; [code] Для извлечения нужной инфорации из aSubDescription есть набор функций: subdescriptor:GetDrawType и т.п. } // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwIterateSubDescriptors.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "IterateSubDescriptors" MUID: (52D643C100A8) // Имя типа: "TkwIterateSubDescriptors" {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , kwSubPanelFromStackWord , evSubPn , tfwScriptingInterfaces ; type TkwIterateSubDescriptors = {final} class(TkwSubPanelFromStackWord) {* Перебирает все SubDescriptot на SubPanel, которые могут быть использованы (!). Такой список задается на этапе проектирвоания/изменения компонета. И не зависит от вида отображения. Формат: [code] @ aWord aLayerID aSubPanel ItarateSubDescriptors [code] aLayerID - слой, в котором производится итерация aSubPanel - контрол сабпанели. aWord - функция для обработки вида: [code] PROCEDURE CheckDescription OBJECT IN aSubDescription // А здесь обрабатываем полученный aSubDescription ; [code] Для извлечения нужной инфорации из aSubDescription есть набор функций: subdescriptor:GetDrawType и т.п. } protected procedure DoWithSubPanel(aControl: TevCustomSubPanel; const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//TkwIterateSubDescriptors {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , Windows {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) //#UC START# *52D643C100A8impl_uses* //#UC END# *52D643C100A8impl_uses* ; procedure TkwIterateSubDescriptors.DoWithSubPanel(aControl: TevCustomSubPanel; const aCtx: TtfwContext); //#UC START# *52D6471802DC_52D643C100A8_var* var i : Integer; l_Obj : TObject; l_Layer : TevSubLayerDescriptor; l_Lambda : TtfwWord; l_LayerID: Integer; //#UC END# *52D6471802DC_52D643C100A8_var* begin //#UC START# *52D6471802DC_52D643C100A8_impl* RunnerAssert(aCtx.rEngine.IsTopInt, 'Слой меток не задан.', aCtx); l_LayerID := aCtx.rEngine.PopInt; RunnerAssert(l_LayerID = 0, 'Не существующее слово.', aCtx); RunnerAssert(aCtx.rEngine.IsTopObj, 'В итератор не передано слово.', aCtx); l_Obj := aCtx.rEngine.PopObj; RunnerAssert(l_Obj is TtfwWord, 'В итератор не передано слово.', aCtx); l_Lambda := l_Obj as TtfwWord; l_Layer := TevSubLayerDescriptor(aControl.SubDescriptors[l_LayerID]); RunnerAssert(l_Layer <> nil, 'Нет такого слоя меток.', aCtx); for i := 0 to 7 do try aCtx.rEngine.PushObj(l_Layer.Flags[i]); l_Lambda.DoIt(aCtx); except on EtfwBreakIterator do Exit; end;//try..except //#UC END# *52D6471802DC_52D643C100A8_impl* end;//TkwIterateSubDescriptors.DoWithSubPanel class function TkwIterateSubDescriptors.GetWordNameForRegister: AnsiString; begin Result := 'IterateSubDescriptors'; end;//TkwIterateSubDescriptors.GetWordNameForRegister initialization TkwIterateSubDescriptors.RegisterInEngine; {* Регистрация IterateSubDescriptors } {$IfEnd} // NOT Defined(NoScripts) end.
(* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Contributor(s): * Jody Dawkins <jdawkins@delphixtreme.com> *) unit dSpec; interface uses Specifiers, dSpecIntf, BaseObjects, TestFramework, AutoDocObjects; type TSpecify = class(TObject) private FContext: Pointer; public constructor Create(const AContext: IContext); destructor Destroy; override; function That(Value : Integer; const ValueName : string = '') : ISpecifier; overload; function That(Value : Boolean; const ValueName : string = '') : ISpecifier; overload; function That(Value : Extended; const ValueName : string = '') : ISpecifier; overload; function That(Value : string; const ValueName : string = '') : ISpecifier; overload; function That(Value : TObject; const ValueName : string = '') : ISpecifier; overload; function That(Value : Pointer; const ValueName : string = '') : ISpecifier; overload; function That(Value : TClass; const ValueName : string = '') : ISpecifier; overload; function That(Value : TDateTime; const ValueName : string = '') : ISpecifier; overload; function That(Value : IInterface; const ValueName : string = '') : ISpecifier; overload; end; TAutoDocClass = class of TBaseAutoDoc; TContext = class(TTestCase, IContext) private FSpecify : TSpecify; FFailures: TFailureList; FTestResult: TTestResult; FSpecDocumentation : string; FContextDescription: string; FAutoDoc : IAutoDoc; { IContext } procedure AddFailure(const AMessage : string; ACallerAddress : Pointer); procedure NewSpecDox(const ValueName : string); procedure DocumentSpec(Value : Variant; const SpecName : string); procedure ReportFailures; procedure RepealLastFailure; function GetAutoDoc : IAutoDoc; procedure SetAutoDoc(const Value: IAutoDoc); function GetContextDescription : string; procedure SetContextDescription(const Value : string); protected property Specify : TSpecify read FSpecify; property ContextDescription : string read GetContextDescription write SetContextDescription; property AutoDoc : IAutoDoc read GetAutoDoc write SetAutoDoc; procedure RunWithFixture(testResult: TTestResult); override; procedure Invoke(AMethod: TTestMethod); override; procedure DoStatus(const Msg : string); function CreateAutoDoc : IAutoDoc; dynamic; public constructor Create(MethodName : string); override; destructor Destroy; override; end; procedure RegisterSpec(spec: ITest); implementation uses dSpecUtils, SysUtils, Variants; procedure RegisterSpec(spec: ITest); begin TestFramework.RegisterTest(spec); end; { Specify } constructor TSpecify.Create(const AContext: IContext); begin inherited Create; FContext := Pointer(AContext); end; destructor TSpecify.Destroy; begin FContext := nil; inherited Destroy; end; function TSpecify.That(Value: Integer; const ValueName : string = ''): ISpecifier; begin Result := TIntegerSpecifier.Create(Value, CallerAddr, IContext(FContext), ValueName); IContext(FContext).NewSpecDox(GetValueName(Value, ValueName)); end; function TSpecify.That(Value: Boolean; const ValueName : string = ''): ISpecifier; begin Result := TBooleanSpecifier.Create(Value, CallerAddr, IContext(FContext), ValueName); IContext(FContext).NewSpecDox(GetValueName(Value, ValueName)); end; function TSpecify.That(Value: Extended; const ValueName : string = ''): ISpecifier; begin Result := TFloatSpecifier.Create(Value, CallerAddr, IContext(FContext), ValueName); IContext(FContext).NewSpecDox(GetValueName(Value, ValueName)); end; function TSpecify.That(Value: string; const ValueName : string = ''): ISpecifier; begin Result := TStringSpecifier.Create(Value, CallerAddr, IContext(FContext), ValueName); IContext(FContext).NewSpecDox(GetValueName(Value, ValueName)); end; function TSpecify.That(Value: TObject; const ValueName : string = ''): ISpecifier; begin Result := TObjectSpecifier.Create(Value, CallerAddr, IContext(FContext), ValueName); if ValueName <> '' then IContext(FContext).NewSpecDox(ValueName) else if Assigned(Value) then IContext(FContext).NewSpecDox(Value.ClassName) else IContext(FContext).NewSpecDox('TObject'); end; function TSpecify.That(Value: Pointer; const ValueName : string = ''): ISpecifier; begin Result := TPointerSpecifier.Create(Value, CallerAddr, IContext(FContext), ValueName); if ValueName <> '' then IContext(FContext).NewSpecDox(ValueName) else IContext(FContext).NewSpecDox('Pointer'); end; function TSpecify.That(Value: TClass; const ValueName : string = ''): ISpecifier; begin Result := TClassSpecifier.Create(Value, CallerAddr, IContext(FContext), ValueName); if ValueName <> '' then IContext(FContext).NewSpecDox(ValueName) else IContext(FContext).NewSpecDox(Value.ClassName); end; function TSpecify.That(Value: TDateTime; const ValueName : string = ''): ISpecifier; begin Result := TDateTimeSpecifier.Create(Value, CallerAddr, IContext(FContext), ValueName); IContext(FContext).NewSpecDox(GetValueName(Value, ValueName)); end; function TSpecify.That(Value: IInterface; const ValueName : string = ''): ISpecifier; begin Result := TInterfaceSpecifier.Create(Value, CallerAddr, IContext(FContext), ValueName); IContext(FContext).NewSpecDox(GetValueName(Value, ValueName)); end; { TContext } procedure TContext.AddFailure(const AMessage: string; ACallerAddress: Pointer); begin FFailures.AddFailure(AMessage, ACallerAddress); end; constructor TContext.Create; begin inherited Create(MethodName); FSpecify := TSpecify.Create(Self); FFailures := TFailureList.Create; FContextDescription := ''; AutoDoc := CreateAutoDoc; AutoDoc.Enabled := False; end; destructor TContext.Destroy; begin FreeAndNil(FSpecify); FreeAndNil(FFailures); AutoDoc := nil; inherited Destroy; end; procedure TContext.DocumentSpec(Value: Variant; const SpecName: string); begin FSpecDocumentation := FSpecDocumentation + '.' + SpecName; if Value <> null then FSpecDocumentation := FSpecDocumentation + Format('(%s)', [VarToStr(Value)]); end; procedure TContext.DoStatus(const Msg: string); begin if Msg <> '' then Status(Msg); end; function TContext.GetAutoDoc: IAutoDoc; begin Result := FAutoDoc; end; function TContext.CreateAutoDoc: IAutoDoc; begin Result := TBaseAutoDoc.Create(Self); end; function TContext.GetContextDescription: string; begin Result := FContextDescription; end; procedure TContext.Invoke(AMethod: TTestMethod); begin DoStatus(FAutoDoc.BeginSpec(ClassName, FTestName)); inherited; DoStatus(FAutoDoc.DocSpec(FSpecDocumentation)); end; procedure TContext.RepealLastFailure; begin if FFailures.Count > 0 then FFailures.Delete(FFailures.Count - 1); end; procedure TContext.ReportFailures; var c: Integer; begin try for c := 0 to FFailures.Count - 1 do FTestResult.AddFailure(Self, ETestFailure.Create(FFailures[c].Message), FFailures[c].FailureAddress); finally FFailures.Clear; end; end; procedure TContext.NewSpecDox(const ValueName : string); begin if FSpecDocumentation <> '' then DoStatus(FAutoDoc.DocSpec(FSpecDocumentation)); FSpecDocumentation := Format('Specify.That(%s).Should', [ValueName]); end; procedure TContext.RunWithFixture(testResult: TTestResult); begin FTestResult := testResult; inherited; FTestResult := nil; end; procedure TContext.SetAutoDoc(const Value: IAutoDoc); begin FAutoDoc := Value; if not Assigned(FAutoDoc) then FAutoDoc := TBaseAutoDoc.Create(Self); end; procedure TContext.SetContextDescription(const Value: string); begin FContextDescription := Value; end; end.
{$IfNDef msmConcreteModelOwnViewControllerMixin_imp} // Модуль: "w:\common\components\gui\Garant\msm\msmConcreteModelOwnViewControllerMixin.imp.pas" // Стереотип: "Impurity" // Элемент модели: "msmConcreteModelOwnViewControllerMixin" MUID: (57AAE9AD018B) // Имя типа: "_msmConcreteModelOwnViewControllerMixin_" {$Define msmConcreteModelOwnViewControllerMixin_imp} // _ConcreteModel_ _msmConcreteModelOwnViewControllerMixin_ = {abstract} class(_msmConcreteModelOwnViewControllerMixin_Parent_) private f_Model: _ConcreteModel_; protected procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aModel: _ConcreteModel_; const aParent: ImsmViewParent); reintroduce; overload; class function Make(const aModel: _ConcreteModel_; const aParent: ImsmViewParent): ImsmViewController; reintroduce; overload; constructor Create(const aModel: _ConcreteModel_; const aParent: ImsmViewParent; const anInitContext: _InitContext_); reintroduce; overload; class function Make(const aModel: _ConcreteModel_; const aParent: ImsmViewParent; const anInitContext: _InitContext_): ImsmViewController; reintroduce; overload; protected property Model: _ConcreteModel_ read f_Model; end;//_msmConcreteModelOwnViewControllerMixin_ {$Else msmConcreteModelOwnViewControllerMixin_imp} {$IfNDef msmConcreteModelOwnViewControllerMixin_imp_impl} {$Define msmConcreteModelOwnViewControllerMixin_imp_impl} constructor _msmConcreteModelOwnViewControllerMixin_.Create(const aModel: _ConcreteModel_; const aParent: ImsmViewParent); //#UC START# *57AAEA5202AA_57AAE9AD018B_var* var l_InitContext : _InitContext_; //#UC END# *57AAEA5202AA_57AAE9AD018B_var* begin //#UC START# *57AAEA5202AA_57AAE9AD018B_impl* Finalize(l_InitContext); System.FillChar(l_InitContext, SizeOf(l_InitContext), 0); Create(aModel, aParent, l_InitContext); //#UC END# *57AAEA5202AA_57AAE9AD018B_impl* end;//_msmConcreteModelOwnViewControllerMixin_.Create class function _msmConcreteModelOwnViewControllerMixin_.Make(const aModel: _ConcreteModel_; const aParent: ImsmViewParent): ImsmViewController; var l_Inst : _msmConcreteModelOwnViewControllerMixin_; begin l_Inst := Create(aModel, aParent); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//_msmConcreteModelOwnViewControllerMixin_.Make constructor _msmConcreteModelOwnViewControllerMixin_.Create(const aModel: _ConcreteModel_; const aParent: ImsmViewParent; const anInitContext: _InitContext_); //#UC START# *57B466EE01D6_57AAE9AD018B_var* //#UC END# *57B466EE01D6_57AAE9AD018B_var* begin //#UC START# *57B466EE01D6_57AAE9AD018B_impl* Assert(aModel <> nil); f_Model := aModel; inherited Create(aModel, aParent, anInitContext); //#UC END# *57B466EE01D6_57AAE9AD018B_impl* end;//_msmConcreteModelOwnViewControllerMixin_.Create class function _msmConcreteModelOwnViewControllerMixin_.Make(const aModel: _ConcreteModel_; const aParent: ImsmViewParent; const anInitContext: _InitContext_): ImsmViewController; var l_Inst : _msmConcreteModelOwnViewControllerMixin_; begin l_Inst := Create(aModel, aParent, anInitContext); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//_msmConcreteModelOwnViewControllerMixin_.Make procedure _msmConcreteModelOwnViewControllerMixin_.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_57AAE9AD018B_var* //#UC END# *479731C50290_57AAE9AD018B_var* begin //#UC START# *479731C50290_57AAE9AD018B_impl* inherited; f_Model := nil; //#UC END# *479731C50290_57AAE9AD018B_impl* end;//_msmConcreteModelOwnViewControllerMixin_.Cleanup {$EndIf msmConcreteModelOwnViewControllerMixin_imp_impl} {$EndIf msmConcreteModelOwnViewControllerMixin_imp}
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi by Dennis D. Spreen <dennis@spreendigital.de> see Behavior3.pas header for full license information } unit Behavior3.Composites.Priority; interface uses Behavior3, Behavior3.Core.Composite, Behavior3.Core.BaseNode, Behavior3.Core.Tick; type (** * Priority ticks its children sequentially until one of them returns * `SUCCESS`, `RUNNING` or `ERROR`. If all children return the failure state, * the priority also returns `FAILURE`. * * @module b3 * @class Priority * @extends Composite **) TB3Priority = class(TB3Composite) private protected public constructor Create; override; (** * Tick method. * @method tick * @param {Tick} tick A tick instance. * @return {Constant} A state constant. **) function Tick(Tick: TB3Tick): TB3Status; override; end; implementation { TB3Priority } uses Behavior3.Helper; constructor TB3Priority.Create; begin inherited; (** * Node name. Default to `Priority`. * @property {String} name * @readonly **) Name := 'Priority'; end; function TB3Priority.Tick(Tick: TB3Tick): TB3Status; var Child: TB3BaseNode; Status: TB3Status; begin for Child in Children do begin Status := Child._Execute(Tick); if Status <> Behavior3.Failure then begin Result := Status; Exit; end; end; Result := Behavior3.Failure; end; end.
{ Routines that create comparison expressions. } module sst_r_syn_compare; define sst_r_syn_comp_var_int; %include 'sst_r_syn.ins.pas'; { ******************************************************************************** * * Subroutine SST_R_SYN_COMP_VAR_INT (SYM, IVAL, OP, EXP_P) * * Create the expression that compares the variable with symbol SYM to the * integer value IVAL. OP is the comparison operator. EXP_P is returned * pointing to the new expression. } procedure sst_r_syn_comp_var_int ( {create exp comparing var to integer constant} in sym: sst_symbol_t; {variable for first term in comparison} in ival: sys_int_machine_t; {integer value to compare against} in op: sst_op2_k_t; {comparison operator} out exp_p: sst_exp_p_t); {returned pointer to new expression} val_param; var term_p: sst_exp_term_p_t; {pointer to second term in expression} begin exp_p := sst_exp_make_var (sym); {init expression with just variable} sst_mem_alloc_scope (sizeof(term_p^), term_p); {get mem for second term} exp_p^.term1.next_p := term_p; {link new term as second term in exp} term_p^.next_p := nil; {init term descriptor} term_p^.op2 := op; term_p^.op1 := sst_op1_none_k; term_p^.str_h.first_char.crange_p := nil; term_p^.str_h.first_char.ofs := 0; term_p^.str_h.last_char := term_p^.str_h.first_char; term_p^.rwflag := [sst_rwflag_read_k]; term_p^.ttype := sst_term_const_k; term_p^.dtype_p := sym_int_p^.dtype_dtype_p; term_p^.dtype_hard := false; term_p^.val_eval := true; term_p^.val_fnd := true; term_p^.val.dtype := sst_dtype_int_k; term_p^.val.int_val := ival; exp_p^.val_eval := false; {reset expression to not evaluated} sst_exp_eval (exp_p^, false); {re-evaluate compound expression} end;
program montecarlo; uses ModLCGReal; type point = array[0..2] of real; var f1, f2 : point; distSum: real; n : longint; procedure centerEllipse(var f1, f2 : point); (* Moves the f1 and f2 point so that they are connected via the x-axis *) var distance : real; begin distance := sqrt(sqr(f1[0]-f2[0])+sqr(f1[1]-f2[1])+sqr(f1[2]-f2[2])); (*Distance between f1 and f2 *) f1[0] := -(distance/2); f1[1] := 0; f1[2] := 0; f2[0] := (distance/2); f2[1] := 0; f2[2] := 0; end; procedure boundingBoxCalc(f1, f2 : point; distSum : real; var boundingBoxXLength, boundingBoxYLength, boundingBoxZLength : real; var boundingBoxVol : real); (*Calculates the bounding box *) begin boundingBoxXLength := distSum; boundingBoxYLength := boundingBoxXLength; boundingBoxZLength := boundingBoxYLength; boundingBoxVol := boundingBoxXLength * boundingBoxYLength * boundingBoxZLength; end; function Volume(f1, f2 : point; distSum: real) : real; var countInEllipse : longint; i : longint; x, y, z : real; boundingBoxXLength : real; boundingBoxYLength : real; boundingBoxZLength : real; boundingBoxVol : real; initialSeed : integer; begin countInEllipse := 0; initialSeed := 5433; centerEllipse(f1, f2); boundingBoxCalc(f1, f2, distSum, boundingBoxXLength, boundingBoxYLength, boundingBoxZLength, boundingBoxVol); (* Using Monte Carlo Method *) initLCG(initialSeed); for i := 1 to n do begin x := randReal*boundingBoxXLength-boundingBoxXLength/2; y := randReal*boundingBoxYLength-boundingBoxYLength/2; z := randReal*boundingBoxZLength-boundingBoxZLength/2; if((sqrt(sqr(f1[0]-x)+sqr(f1[1]-y)+sqr(f1[2]-z))+sqrt(sqr(f2[0]-x)+sqr(f2[1]-y)+sqr(f2[2]-z)))<=distSum) then inc(countInEllipse); end; Volume := boundingBoxVol * (countInEllipse/n); end; begin distSum := 2.0; f1[0] := 1.0; f1[1] := 1.0; f1[2] := 1.0; f2[0] := 1.0; f2[1] := 1.0; f2[2] := 1.0; n := 10; writeln('Volume for n = ', n, ' is', Volume(f1, f2, distSum)); n := 100; writeln('Volume for n = ', n, ' is', Volume(f1, f2, distSum)); n := 1000; writeln('Volume for n = ', n, ' is', Volume(f1, f2, distSum)); n := 10000; writeln('Volume for n = ', n, ' is', Volume(f1, f2, distSum)); n := 100000; writeln('Volume for n = ', n, ' is', Volume(f1, f2, distSum)); n := 1000000; writeln('Volume for n = ', n, ' is', Volume(f1, f2, distSum)); end.
{ Exercicio 57: Em uma eleição municipal existem quatro candidatos. Os votos são informados através de código. Os dados utilizados para a escrutinagem obedecem à seguinte codificação: 1,2,3 e 4 = voto para os respectivos candidatos; 5 = voto nulo; 6 = voto em branco. Elabore um algoritmo que receba os nomes dos candidatos e que calcule e exiba: a) total de votos de cada candidato; b) total de votos nulos; c) total de votos em brancos; d) percentual dos votos brancos e nulos sobre o total. Como finalizador do conjunto de votos, tem-se o valor 0. } { Solução em Portugol Algoritmo Exercicio 57; Var candidato1,candidato2,candidato3,candidato4,nulo,branco: inteiro; percentual: real; voto: caracter; Inicio exiba("Urna eletrônica municipal."); voto <- '8'; //Zerando os acumuladores e colocando um valor qualquer candidato1 <- 0; //em voto para acessar o loop. candidato2 <- 0; candidato3 <- 0; candidato4 <- 0; branco <- 0; nulo <- 0; enquanto(voto <> 0)faça exiba("Digite entre 1-4 para votar nos respectivos candidatos, 5 para votar nulo e 6 para votar branco."); leia(voto); caso(voto)de "1": candidato1 <- candidato1 + 1; //Votos são acumulados aqui. "2": candidato2 <- candidato2 + 1; "3": candidato3 <- candidato3 + 1; "4": candidato4 <- candidato4 + 1; "5": nulo <- nulo + 1; "6": branco <- branco + 1; senão exiba("Digite uma opção válida."); fimcaso; fimenquanto; percentual <- 100 * (branco + nulo)/(candidato1 + candidato2 + candidato3 + candidato + branco + nulo); exiba("Apuração da urna eletrônica."); //Exibição dos resultados da eleição. exiba("O candidato 1 teve ",candidato1," votos."); exiba("O candidato 2 teve ",candidato2," votos."); exiba("O candidato 3 teve ",candidato3," votos."); exiba("O candidato 4 teve ",candidato4," votos."); exiba("Votos brancos: ",branco); exiba("Votos nulos: ",nulo); exiba("O percentual de votos brancos e nulos foi de: ",percentual:0:2), Fim. } // Solução em Pascal Program Exercicio57; uses crt; var candidato1,candidato2,candidato3,candidato4,nulo,branco: integer; percentual: real; voto: char; begin clrscr; writeln('Urna eletrônica municipal.'); voto := '8'; //Zerando os acumuladores e colocando um valor qualquer candidato1 := 0; //em voto para acessar o loop. candidato2 := 0; candidato3 := 0; candidato4 := 0; branco := 0; nulo := 0; while(voto <> '0')do Begin writeln('Digite entre 1-4 para votar nos respectivos candidatos, 5 para votar nulo e 6 para votar branco.'); readln(voto); case(voto)of '1': candidato1 := candidato1 + 1; //Votos são acumulados aqui. '2': candidato2 := candidato2 + 1; '3': candidato3 := candidato3 + 1; '4': candidato4 := candidato4 + 1; '5': nulo := nulo + 1; '6': branco := branco + 1; else writeln('Digite uma opção válida.'); end; End; percentual := 100 * (branco + nulo)/(candidato1 + candidato2 + candidato3 + candidato4 + branco + nulo); writeln('Apuração da urna eletrônica.'); //Exibição dos resultados da eleição. writeln('O candidato 1 teve ',candidato1,' votos.'); writeln('O candidato 2 teve ',candidato2,' votos.'); writeln('O candidato 3 teve ',candidato3,' votos.'); writeln('O candidato 4 teve ',candidato4,' votos.'); writeln('Votos brancos: ',branco); writeln('Votos nulos: ',nulo); writeln('O percentual de votos brancos e nulos foi de: ',percentual:0:2,'%.'); repeat until keypressed; end.
unit AvoidanceZoneQueryUnit; interface uses HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit, NullableBasicTypesUnit, GenericParametersUnit; type TAvoidanceZoneQuery = class(TGenericParameters) private [HttpQueryMember('device_id')] [Nullable] FDeviceId: NullableString; [HttpQueryMember('territory_id')] [Nullable] FTerritoryId: NullableString; public constructor Create; override; property DeviceId: NullableString read FDeviceId write FDeviceId; property TerritoryId: NullableString read FTerritoryId write FTerritoryId; end; implementation { TAddressParameters } constructor TAvoidanceZoneQuery.Create; begin Inherited Create; DeviceId := NullableString.Null; TerritoryId := NullableString.Null; end; end.
unit testfile_unicode; interface implementation function TFSend.IsGSMChar(C: WideChar): Boolean; begin Result := (C = '@') or (C = '£') or (C = '$') or (C = '¥') or (C = 'è') or (C = 'é') or (C = 'ù') or (C = 'î') or (C = 'ô') or (C = 'Ç') or (C = #10) or (C = 'Ø') or (C = 'ø') or (C = #13) or (C = 'Å') or (C = 'å') or (C = 'Δ') or (C = '_') or (C = 'Φ') or (C = 'Γ') or (C = 'Λ') or (C = 'Ω') or (C = 'Π') or (C = 'Ψ') or (C = 'Σ') or (C = 'Θ') or (C = 'Ξ') or (C = #27) or (C = #28) or (C = '^') or (C = '{') or (C = '}') or (C = '\') or (C = '[') or (C = '~') or (C = ']') or (C = '|') or (C = '€') or (C = 'Æ') or (C = 'æ') or (C = 'ß') or (C = 'É') or CharInSet(C, [' '..'#']) or CharInSet(C, ['%'..'?']) or (C = '¡') or CharInSet(C, ['A'..'Z']) or (C = 'Ä') or (C = 'Ö') or (C = 'Ñ') or (C = 'Ü') or (C = '§') or (C = '¿') or CharInSet(C, ['a'..'z']) or (C = 'ä') or (C = 'ö') or (C = 'ñ') or (C = 'ü') or (C = 'à'); end; end.
unit vcmLayoutImplementation; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "VCM$Visual" // Модуль: "w:/common/components/gui/Garant/VCM/implementation/Visual/vcmLayoutImplementation.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::VCM$Visual::Visual::TvcmLayoutImplementation // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc} interface {$If not defined(NoVCM)} uses vcmInterfaces, Controls, l3ProtoObjectWithCOMQI ; {$IfEnd} //not NoVCM {$If not defined(NoVCM)} type IvcmLayoutInternal = interface(IUnknown) ['{3C78DB5C-C875-4768-AC34-75F697D2514D}'] procedure ClearLinkToControl; end;//IvcmLayoutInternal TvcmLayoutImplementation = class(Tl3ProtoObjectWithCOMQI, IvcmLayout, IvcmLayoutInternal) private // private fields f_Control : TWinControl; {* Поле для свойства Control} protected // realized methods function Get_VCLWinControl: TWinControl; procedure ClearLinkToControl; protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } {$If not defined(DesignTimeLibrary)} class function IsCacheable: Boolean; override; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } {$IfEnd} //not DesignTimeLibrary public // public methods constructor Create(aControl: TWinControl); reintroduce; class function Make(aControl: TWinControl): IvcmLayout; reintroduce; {* Сигнатура фабрики TvcmLayoutImplementation.Make } protected // protected properties property Control: TWinControl read f_Control; end;//TvcmLayoutImplementation {$IfEnd} //not NoVCM implementation {$If not defined(NoVCM)} // start class TvcmLayoutImplementation constructor TvcmLayoutImplementation.Create(aControl: TWinControl); //#UC START# *4F827263026A_4F82714B0271_var* //#UC END# *4F827263026A_4F82714B0271_var* begin //#UC START# *4F827263026A_4F82714B0271_impl* inherited Create; f_Control := aControl; //#UC END# *4F827263026A_4F82714B0271_impl* end;//TvcmLayoutImplementation.Create class function TvcmLayoutImplementation.Make(aControl: TWinControl): IvcmLayout; var l_Inst : TvcmLayoutImplementation; begin l_Inst := Create(aControl); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TvcmLayoutImplementation.Get_VCLWinControl: TWinControl; //#UC START# *4F8270EB016E_4F82714B0271get_var* //#UC END# *4F8270EB016E_4F82714B0271get_var* begin //#UC START# *4F8270EB016E_4F82714B0271get_impl* Result := f_Control; //#UC END# *4F8270EB016E_4F82714B0271get_impl* end;//TvcmLayoutImplementation.Get_VCLWinControl procedure TvcmLayoutImplementation.ClearLinkToControl; //#UC START# *4F82737803BE_4F82714B0271_var* //#UC END# *4F82737803BE_4F82714B0271_var* begin //#UC START# *4F82737803BE_4F82714B0271_impl* f_Control := nil; //#UC END# *4F82737803BE_4F82714B0271_impl* end;//TvcmLayoutImplementation.ClearLinkToControl procedure TvcmLayoutImplementation.Cleanup; //#UC START# *479731C50290_4F82714B0271_var* //#UC END# *479731C50290_4F82714B0271_var* begin //#UC START# *479731C50290_4F82714B0271_impl* f_Control := nil; inherited; //#UC END# *479731C50290_4F82714B0271_impl* end;//TvcmLayoutImplementation.Cleanup {$If not defined(DesignTimeLibrary)} class function TvcmLayoutImplementation.IsCacheable: Boolean; //#UC START# *47A6FEE600FC_4F82714B0271_var* //#UC END# *47A6FEE600FC_4F82714B0271_var* begin //#UC START# *47A6FEE600FC_4F82714B0271_impl* Result := true; //#UC END# *47A6FEE600FC_4F82714B0271_impl* end;//TvcmLayoutImplementation.IsCacheable {$IfEnd} //not DesignTimeLibrary {$IfEnd} //not NoVCM end.
unit ureplace; {$MODE Delphi} interface uses SysUtils, Classes, Graphics, Controls, StdCtrls, ExtCtrls, Forms; type // search record TReplaceRec = record StrTextToFind, // textual format StrTextToReplace, StrDataToFind, // real data to find StrDataToReplace: string; // real data to replace with BoolIgnoreCase, // ignore upper/lower case BoolFindText, BoolReplaceText, // find/replace by text or hex data BoolReplaceAll: Boolean; end; TdlgReplace = class(TForm) Button1: TButton; Button2: TButton; Label1: TLabel; edFind: TEdit; cbFindText: TCheckBox; cbNoCase: TCheckBox; Label2: TLabel; edReplace: TEdit; cbReplaceText: TCheckBox; Button3: TButton; procedure edFindChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button3Click(Sender: TObject); private FReplaceAll: Boolean; end; var dlgReplace: TdlgReplace; // create a replace dialog and get options function ReplaceGetOptions(var Options: TReplaceRec): Boolean; implementation {$R *.lfm} // determine if a text contains only hex chars and ' ' function IsHex(const Str: string): Boolean; var LIntLoop: Integer; begin Result := Trim(Str) <> ''; if Result then for LIntLoop := 1 to Length(Str) do if not (Str[LIntLoop] in ['0'..'9',' ','a'..'f','A'..'F']) then begin Result := False; Break; end; end; // create a replace dialog and get options function ReplaceGetOptions(var Options: TReplaceRec): Boolean; begin with TdlgReplace.Create(Application) do try edFind.Text := Options.StrTextToFind; edReplace.Text := Options.StrTextToReplace; // if no previous search, gray "find text" to auto determine text/hex if Options.StrTextToFind <> '' then cbFindText.Checked := Options.BoolFindText; if Options.StrTextToReplace <> '' then cbReplaceText.Checked := Options.BoolReplaceText; cbNoCase.Checked := Options.BoolIgnoreCase; Result := ShowModal = mrOK; if Result then with Options do begin StrTextToFind := edFind.Text; BoolFindText := cbFindText.Checked; StrTextToReplace := edReplace.Text; BoolReplaceText := cbReplaceText.Checked; // eventually find out whether text or hex values (0..9,a..f,' ') are entered if cbFindText.State = cbGrayed then BoolFindText := not IsHex(edFind.Text); if cbReplaceText.State = cbGrayed then BoolReplaceText := not IsHex(edReplace.Text); StrDataToFind := StrTextToFind; StrDataToReplace := StrTextToReplace; BoolIgnoreCase := cbNoCase.Checked; BoolReplaceAll := FReplaceAll; end; finally Free; end; end; procedure TdlgReplace.edFindChange(Sender: TObject); begin Button1.Enabled := edFind.Text <> ''; Button3.Enabled := edFind.Text <> ''; end; procedure TdlgReplace.FormCreate(Sender: TObject); begin FReplaceAll := False; end; procedure TdlgReplace.Button3Click(Sender: TObject); begin FReplaceAll := True; end; end.
unit XMLParse; { $jrsoftware: ishelp/ISHelpGen/XMLParse.pas,v 1.5 2009/07/29 09:50:24 mlaan Exp $ } { XML parser. Currently just calls MSXML 4.0 to do the real work. } interface {$IFNDEF VER80} { if it's not Delphi 1.0 } {$IFNDEF VER90} { if it's not Delphi 2.0 } {$IFNDEF VER93} { and it's not C++Builder 1.0 } {$IFNDEF VER100} { if it's not Delphi 3.0 } {$IFNDEF VER110} { and it's not C++Builder 3.0 } {$IFNDEF VER120} {$IFNDEF VER125} { if it's not Delphi 4 or C++Builder 4 } {$IFNDEF VER130} { if it's not Delphi 5 or C++Builder 5 } {$DEFINE IS_D6} { then it must be at least Delphi 6 or C++Builder 6 } {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} uses Windows, SysUtils{$IFDEF IS_D6}, Variants{$ENDIF}; type IXMLNode = interface function GetAttribute(const AName: String): String; function GetOptionalAttribute(const AName: String): String; function GetFirstChild: IXMLNode; function GetNodeName: String; function GetNextSibling: IXMLNode; function GetNodeType: Integer; function GetParentNode: IXMLNode; function GetPreviousSibling: IXMLNode; function GetRealMSXMLNode: OleVariant; function GetText: String; function HasAttribute(const AName: String): Boolean; function TransformNode(const Stylesheet: IXMLNode): String; property Attributes[const AName: String]: String read GetAttribute; property OptionalAttributes[const AName: String]: String read GetOptionalAttribute; property FirstChild: IXMLNode read GetFirstChild; property NextSibling: IXMLNode read GetNextSibling; property NodeName: String read GetNodeName; property NodeType: Integer read GetNodeType; property ParentNode: IXMLNode read GetParentNode; property PreviousSibling: IXMLNode read GetPreviousSibling; property Text: String read GetText; end; TXMLDocument = class private FDoc: OleVariant; function GetRoot: IXMLNode; public constructor Create; procedure LoadFromFile(const AFilename: String); procedure StripComments; property Root: IXMLNode read GetRoot; end; const { Values for the NodeType property } NODE_INVALID = 0; NODE_ELEMENT = 1; NODE_ATTRIBUTE = 2; NODE_TEXT = 3; NODE_CDATA_SECTION = 4; NODE_ENTITY_REFERENCE = 5; NODE_ENTITY = 6; NODE_PROCESSING_INSTRUCTION = 7; NODE_COMMENT = 8; NODE_DOCUMENT = 9; NODE_DOCUMENT_TYPE = 10; NODE_DOCUMENT_FRAGMENT = 11; NODE_NOTATION = 12; implementation uses ActiveX, ComObj; type TXMLNode = class(TInterfacedObject, IXMLNode) private FRealNode: OleVariant; function GetFirstChild: IXMLNode; function GetAttribute(const AName: String): String; function GetOptionalAttribute(const AName: String): String; function GetNextSibling: IXMLNode; function GetNodeName: String; function GetNodeType: Integer; function GetParentNode: IXMLNode; function GetPreviousSibling: IXMLNode; function GetRealMSXMLNode: OleVariant; function GetText: String; function HasAttribute(const AName: String): Boolean; function TransformNode(const Stylesheet: IXMLNode): String; public constructor Create(const ARealNode: OleVariant); end; function IsVarAssigned(const AVariant: OleVariant): Boolean; begin case VarType(AVariant) of varEmpty: Result := False; varDispatch: Result := Assigned(TVarData(AVariant).VDispatch); else raise Exception.Create('IsVarAssigned: Unexpected variant type'); end; end; function MakeNode(const ARealNode: OleVariant): IXMLNode; begin if IsVarAssigned(ARealNode) then Result := TXMLNode.Create(ARealNode) else Result := nil; end; function WideCharToUTF8String(const Src: PWideChar; const SrcLen: Integer): AnsiString; var DestLen, I: Integer; DestBuf: AnsiString; DestPtr: PAnsiChar; C: Word; begin if (SrcLen < 0) or (SrcLen > High(Integer) div 3) then raise Exception.Create('WideCharToUTF8String: SrcLen out of range'); SetString(DestBuf, nil, SrcLen * 3); DestLen := 0; DestPtr := PAnsiChar(DestBuf); for I := 0 to SrcLen-1 do begin C := Ord(Src[I]); if C <= $7F then begin DestPtr[DestLen] := AnsiChar(C); Inc(DestLen); end else if C <= $7FF then begin DestPtr[DestLen] := AnsiChar($C0 or (C shr 6)); DestPtr[DestLen+1] := AnsiChar($80 or (C and $3F)); Inc(DestLen, 2); end else begin if (C >= $D800) and (C <= $DFFF) then raise Exception.Create('WideCharToUTF8String: Surrogate pairs are not supported'); DestPtr[DestLen] := AnsiChar($E0 or (C shr 12)); DestPtr[DestLen+1] := AnsiChar($80 or ((C shr 6) and $3F)); DestPtr[DestLen+2] := AnsiChar($80 or (C and $3F)); Inc(DestLen, 3); end; end; SetLength(DestBuf, DestLen); Result := DestBuf; { Following is an alternate version which uses WideCharToMultiByte. Consistency across different Windows platforms is uncertain, so I prefer my version. } (* if SrcLen = 0 then Result := '' else begin DestLen := WideCharToMultiByte(CP_UTF8, 0, Src, SrcLen, nil, 0, nil, nil); if DestLen = 0 then RaiseLastWin32Error; SetString(DestBuf, nil, DestLen); if WideCharToMultiByte(CP_UTF8, 0, Src, SrcLen, @DestBuf[1], DestLen, nil, nil) <> DestLen then raise Exception.Create('VariantToUTF8String: Unexpected result from WideCharToMultiByte'); Result := DestBuf; end; *) end; function VariantToUTF8String(const V: OleVariant): String; begin if VarType(V) <> varOleStr then raise Exception.Create('VariantToUTF8String: Expected varOleStr'); Result := WideCharToUTF8String(TVarData(V).VOleStr, SysStringLen(TVarData(V).VOleStr)); end; { TXMLDocument } constructor TXMLDocument.Create; begin inherited Create; FDoc := CreateOleObject('MSXML2.DOMDocument.4.0'); FDoc.async := False; FDoc.preserveWhitespace := True; end; function TXMLDocument.GetRoot: IXMLNode; begin Result := MakeNode(FDoc.documentElement); end; procedure TXMLDocument.LoadFromFile(const AFilename: String); begin if not FDoc.load(AFilename) then begin if Integer(FDoc.parseError.line) <> 0 then raise Exception.CreateFmt('XML parse error (line %d, column %d): %s', [Integer(FDoc.parseError.line), Integer(FDoc.parseError.linepos), FDoc.parseError.reason]) else raise Exception.CreateFmt('XML parse error: %s', [FDoc.parseError.reason]); end; end; procedure TXMLDocument.StripComments; begin FDoc.selectNodes('//comment()').removeAll; end; { TXMLNode } constructor TXMLNode.Create(const ARealNode: OleVariant); begin inherited Create; FRealNode := ARealNode; end; function TXMLNode.GetAttribute(const AName: String): String; var N: OleVariant; begin N := FRealNode.attributes.getNamedItem(AName); if not IsVarAssigned(N) then raise Exception.CreateFmt('Attribute "%s" does not exist', [AName]); Result := VariantToUTF8String(N.value); end; function TXMLNode.GetOptionalAttribute(const AName: String): String; var N: OleVariant; begin N := FRealNode.attributes.getNamedItem(AName); if not IsVarAssigned(N) then Result := '' else Result := VariantToUTF8String(N.value); end; function TXMLNode.GetFirstChild: IXMLNode; begin Result := MakeNode(FRealNode.firstChild); end; function TXMLNode.GetNodeName: String; begin Result := VariantToUTF8String(FRealNode.nodeName); end; function TXMLNode.GetNextSibling: IXMLNode; begin Result := MakeNode(FRealNode.nextSibling); end; function TXMLNode.GetNodeType: Integer; begin Result := FRealNode.nodeType; end; function TXMLNode.GetParentNode: IXMLNode; begin Result := MakeNode(FRealNode.parentNode); end; function TXMLNode.GetPreviousSibling: IXMLNode; begin Result := MakeNode(FRealNode.previousSibling); end; function TXMLNode.GetRealMSXMLNode: OleVariant; begin Result := FRealNode; end; function TXMLNode.GetText: String; begin Result := VariantToUTF8String(FRealNode.text); end; function TXMLNode.HasAttribute(const AName: String): Boolean; begin Result := IsVarAssigned(FRealNode.attributes.getNamedItem(AName)); end; function TXMLNode.TransformNode(const Stylesheet: IXMLNode): String; begin Result := VariantToUTF8String(FRealNode.transformNode(Stylesheet.GetRealMSXMLNode)); end; end.
unit uFrmBase; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs , FMX.Objects, System.Actions, FMX.ActnList , Winapi.Windows, FMX.Platform.Win , QJSON; type TFrmBase = class(TForm) ActionList1: TActionList; actPriorPage: TAction; actNextPage: TAction; actMainPage: TAction; ActOpenPage: TAction; actGoBack: TAction; raImage: TRectangle; procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure ActOpenPageExecute(Sender: TObject); procedure ActGoBackExecute(Sender: TObject); procedure actPriorPageExecute(Sender: TObject); procedure actNextPageExecute(Sender: TObject); procedure actMainPageExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure raImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure raImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure FormDestroy(Sender: TObject); private FImgIndex: Integer; FID: Integer; FGestureX: Single; /// <summary> /// 是否使用手势翻页 /// </summary> FUseGesture: Boolean; FCfg: TQJson; { Private declarations } procedure InitEvent; procedure LoadImage(AImgName: string); function LoadCfg: TQJson; protected procedure SetImgIndex(const Value: Integer); virtual; property UseGesture: Boolean read FUseGesture write FUseGesture default True; property Cfg: TQJson read FCfg; public { Public declarations } property ID: Integer read FID write FID; property ImgIndex: Integer read FImgIndex write SetImgIndex; end; procedure MsCloseOtherForms(AClassName: string = ''); /// <summary> /// 关闭类名为AClassName的窗口 /// </summary> /// <param name="AClassName">窗口类名</param> procedure MsCloseForm(AClassName: string = ''); /// <summary> /// 创建一个窗口 /// </summary> procedure MsCreateForm(AOwner: TComponent; AFormName: string; AID: Integer); var FrmBase: TFrmBase; implementation uses uComm; {$R *.fmx} procedure MsCloseOtherForms(AClassName: string = ''); var i: Integer; vForm: TForm; begin for I:=0 to Screen.FormCount-1 do begin vForm := TForm(Screen.Forms[I]); //if vForm.ID = 1000000 then if UpperCase(vForm.ClassName) = UpperCase('TMainForm') then Continue; if (AClassName <> '') then begin if not (vForm.ClassNameIs(AClassName)) then Continue; end; vForm.Close; //FreeAndNil(vForm); //Break; end; end; procedure MsCloseForm(AClassName: string = ''); var i: Integer; vForm: TForm; begin if AClassName = '' then begin Exit; end; for I:=0 to Screen.FormCount-1 do begin vForm := TForm(Screen.Forms[I]); if not (vForm.ClassNameIs(AClassName)) then Continue; vForm.Close; //FreeAndNil(vForm); Break; end; end; procedure MsCreateForm(AOwner: TComponent; AFormName: string; AID: Integer); function GetFormByName(AFormName: string): TFrmBase; var i: Integer; begin Result := nil; for I:=0 to Screen.FormCount-1 do begin if not (Screen.Forms[I].ClassNameIs(AFormName)) then Continue; Result := TFrmBase(Screen.Forms[I]); Break; end; end; type TFrmBaseClass = class of TFrmBase; var sClassName, s: string; vForm: TFrmBase; begin try vForm := GetFormByName(AFormName); if vForm = nil then begin //创建 s := Copy(Trim(AFormName), 1, 1); if (s <> 'T') and (s <> 't') then sClassName := 'T' + Trim(AFormName) else sClassName := Trim(AFormName); if GetClass(sClassName)<>nil then vForm := TFrmBaseClass(FindClass(sClassName)).Create(AOwner); end; //显示Form try vForm.ID := AID; vForm.ImgIndex := AID mod 100; vForm.ShowModal; finally FreeAndNil(vForm); end; except end; end; procedure TFrmBase.ActGoBackExecute(Sender: TObject); begin Self.Close; end; procedure TFrmBase.actMainPageExecute(Sender: TObject); begin // end; procedure TFrmBase.actNextPageExecute(Sender: TObject); begin ImgIndex := ImgIndex + 1; end; procedure TFrmBase.ActOpenPageExecute(Sender: TObject); var iPageIndex: Integer; begin iPageIndex := TShape(Sender).Tag; if iPageIndex < 1000000 then Exit; //iPageIndex mod 1000000后,得到一个序号,对应的是下级页面TabControl的TabIndex值 MsCreateForm(Self, Format('Tfrm%d', [1000000 * (iPageIndex div 1000000)]), iPageIndex); end; procedure TFrmBase.actPriorPageExecute(Sender: TObject); begin ImgIndex := ImgIndex - 1; end; procedure TFrmBase.FormCreate(Sender: TObject); begin InitEvent; FUseGesture := True; LoadCfg; end; procedure TFrmBase.FormDestroy(Sender: TObject); begin if FCfg <> nil then FreeAndNil(FCfg); end; procedure TFrmBase.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = 27 then begin Key := 0; Self.Close; end; end; procedure TFrmBase.InitEvent; var I: Integer; begin // for I := 0 to Self.ComponentCount - 1 do begin if (Self.Components[I] is TRectangle) or (Self.Components[I] is TRoundRect) then begin {$IFNDEF DEBUG} TShape(Self.Components[I]).Stroke.Kind := TBrushKind.None; {$ENDIF} //上一页 if Self.Components[i].Name = 'raPriorPage' then begin TRectangle(Self.Components[I]).OnClick := actPriorPageExecute; TShape(Self.Components[I]).Cursor := crHandPoint; end; //下一页 if Self.Components[i].Name = 'raNextPage' then begin TRectangle(Self.Components[I]).OnClick := actNextPageExecute; TShape(Self.Components[I]).Cursor := crHandPoint; end; //主页 if Self.Components[i].Name = 'raMainPage' then begin TRectangle(Self.Components[I]).OnClick := actMainPageExecute; TShape(Self.Components[I]).Cursor := crHandPoint; end; //返回 if Self.Components[i].Name = 'raGoBack' then begin TRectangle(Self.Components[I]).OnClick := actGoBackExecute; TShape(Self.Components[I]).Cursor := crHandPoint; end; //打开一个新页面 if Self.Components[I].Tag >= 1000000 then begin TShape(Self.Components[I]).OnClick := ActOpenPageExecute; TShape(Self.Components[I]).Cursor := crHandPoint; end; end; DebugInf('MS - %s', [Self.Components[I].Name]); end; end; function TFrmBase.LoadCfg: TQJson; begin FCfg := TQJson.Create; FCfg.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'cfg.dat'); end; procedure TFrmBase.LoadImage(AImgName: string); var sImgFile: string; begin try //tcPage.TabIndex := 0; //这句话必须加,因为基类里边设置了TabIndex sImgFile := Format('%sImage\%s', [ExtractFilePath(ParamStr(0)), AImgName]); if not FileExists(sImgFile) then begin MessageBox(FormToHWND(Self), PWideChar(Format('缺少图片!'#13'%s', [sImgFile])), '提示', MB_ICONWARNING); Exit; end; raImage.Fill.Kind := TBrushKind.Bitmap; raImage.Fill.Bitmap.Bitmap.LoadFromFile(sImgFile); except on E: Exception do DebugInf('MS - [%s-LoadImage] fail [%s]', [Self.ClassName, E.Message]); end; end; procedure TFrmBase.raImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin FGestureX := X; end; procedure TFrmBase.raImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); var vTmp: Single; begin if not UseGesture then Exit; vTmp := X - FGestureX; if Abs(vTmp) < 80 then Exit; if vTmp < 0 then actNextPage.Execute else actPriorPage.Execute; end; procedure TFrmBase.SetImgIndex(const Value: Integer); var sImgFile: string; vJson: TQJson; begin if FCfg = nil then Exit; vJson := FCfg.ForcePath(Format('%d', [ID div 100 * 100])); if vJson = nil then Exit; if vJson.Count = 0 then Exit; if Value < 0 then Exit; if Value > vJson.Count - 1 then Exit; FImgIndex := Value; sImgFile := Format('%s\%s', [vJson[FImgIndex].ForcePath('Dir').AsString, vJson[FImgIndex].ForcePath('ImgName').AsString]); LoadImage(sImgFile); end; end.
unit xpr.AST; { Author: Jarl K. Holta License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html) Abstract syntax tree } {$I express.inc} interface uses Classes, SysUtils, xpr.express, xpr.bytecode; type (* Abstract base node *) TBaseNode = class(TObject) FDocPos: TDocPos; constructor Create(DocPos:TDocPos); virtual; function ToString: string; reintroduce; virtual; procedure Compile(ctx: TCompilerContext); virtual; end; TNodeArray = array of TBaseNode; (* A list of statements or expressions *) TBlock = class(TBaseNode) List: TNodeArray; constructor Create(AList:TNodeArray; DocPos: TDocPos); reintroduce; constructor Create(AStmt:TBaseNode; DocPos: TDocPos); overload; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; TReturn = class(TBaseNode) Expr:TBaseNode; constructor Create(AExpr:TBaseNode; DocPos: TDocPos); overload; procedure Compile(ctx: TCompilerContext); override; end; TContinue = class(TBaseNode) procedure Compile(ctx: TCompilerContext); override; end; TBreak = class(TBaseNode) procedure Compile(ctx: TCompilerContext); override; end; (* A single statements *) TStatement = class(TBaseNode) Expr: TBaseNode; constructor Create(AExpr:TBaseNode; DocPos: TDocPos); reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* A stub for all constants *) TConstant = class(TBaseNode) StrVal:String; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; TConstNone = class(TConstant) constructor Create(DocPos: TDocPos); reintroduce; procedure Compile(ctx: TCompilerContext); override; end; TConstBool = class(TConstant) Value: Boolean; constructor Create(AValue:String; DocPos: TDocPos); reintroduce; procedure Compile(ctx: TCompilerContext); override; end; TConstChar = class(TConstant) Value: epChar; constructor Create(AValue:String; DocPos: TDocPos); reintroduce; procedure Compile(ctx: TCompilerContext); override; end; TConstInt = class(TConstant) Value: Int64; constructor Create(AValue:String; DocPos: TDocPos); reintroduce; procedure Compile(ctx: TCompilerContext); override; end; TConstFloat = class(TConstant) Value: Extended; constructor Create(AValue:String; DocPos: TDocPos); reintroduce; procedure Compile(ctx: TCompilerContext); override; end; TConstString = class(TConstant) Value: String; constructor Create(AValue:String; DocPos: TDocPos); reintroduce; procedure Compile(ctx: TCompilerContext); override; end; (* A variable *) TVariable = class(TBaseNode) Name: string; constructor Create(AName:String; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; function VarId(ctx: TCompilerContext): Int32; procedure Compile(ctx: TCompilerContext); override; end; TVarArray = array of TVariable; (* For declaring variables *) TVarDecl = class(TBaseNode) Variables: TVarArray; Expr:TBaseNode; constructor Create(AVariables:TVarArray; AExpr:TBaseNode; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* A function *) TFunction = class(TBaseNode) Name: string; Params: TVarArray; Prog: TBlock; constructor Create(AName:string; AParams:TVarArray; AProg:TBlock; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* Call a callable object *) TCall = class(TBaseNode) Callable: TBaseNode; Args: TNodeArray; constructor Create(ACallable:TBaseNode; AArgs:TNodeArray; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* Index an indexable object *) TIndex = class(TBaseNode) Indexable: TBaseNode; Args: TNodeArray; constructor Create(AIndexable:TBaseNode; AArgs:TNodeArray; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* A list expression *) TListExpr = class(TConstant) Expressions: TNodeArray; constructor Create(AExpressions:TNodeArray; DocPos: TDocPos); reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* Unary operation *) TUnaryOp = class(TBaseNode) Left: TBaseNode; Op: TToken; PostFix: Boolean; constructor Create(Operation:TToken; ALeft:TBaseNode; APostFix:Boolean; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* Binary operation - EG: `5/2` *) TBinOp = class(TBaseNode) Left, Right: TBaseNode; Op: TToken; constructor Create(Operation:TToken; ALeft, ARight:TBaseNode; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* simple assignments - EG: `z := 5/2` *) TAssignment = class(TBaseNode) Left: TBaseNode; Right: TBaseNode; Op: TToken; constructor Create(Operation:TToken; ALeft:TBaseNode; ARight:TBaseNode; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* If-Expression *) TIfExpression = class(TBaseNode) Condition: TBaseNode; Left, Right: TBaseNode; constructor Create(ACond:TBaseNode; ALeft, ARight:TBaseNode; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* if statement *) TIf = class(TBaseNode) Condition: TBaseNode; Body: TBlock; ElseBody: TBlock; constructor Create(ACond:TBaseNode; ABody, AElseBody:TBlock; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* while loop *) TWhile = class(TBaseNode) Condition: TBaseNode; Body: TBlock; constructor Create(ACond:TBaseNode; ABody:TBlock; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* repeat loop *) TRepeat = class(TBaseNode) Condition: TBaseNode; Body: TBlock; constructor Create(ACond:TBaseNode; ABody:TBlock; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* for loop *) TFor = class(TBaseNode) Stmt1,Stmt2,Stmt3: TBaseNode; Body: TBlock; constructor Create(AStmt1,AStmt2,AStmt3:TBaseNode; ABody:TBlock; DocPos: TDocPos); virtual; reintroduce; function ToString: string; override; procedure Compile(ctx: TCompilerContext); override; end; (* print statement *) TPrint = class(TBaseNode) Exprs: TNodeArray; constructor Create(AExprs:TNodeArray; DocPos: TDocPos); virtual; reintroduce; function ToString:string; override; procedure Compile(ctx: TCompilerContext); override; end; (* temporary time function / variable thingy *) TTimeNow = class(TBaseNode) constructor Create(DocPos: TDocPos); virtual; reintroduce; function ToString:string; override; procedure Compile(ctx: TCompilerContext); override; end; function CompileAST(astnode:TBaseNode; doFree:Boolean = True): TBytecode; implementation uses xpr.interpreter, xpr.utils, xpr.opcodes, xpr.errors, {$I objects.inc}; function CompileAST(astnode:TBaseNode; doFree:Boolean = True): TBytecode; var ctx:TCompilerContext; begin ctx := TCompilerContext.Create(); astnode.Compile(ctx); ctx.Emit(RETURN, 0, astnode.FDocPos); Result := ctx.Bytecode; ctx.Free; //if doFree then // astNode.Free; end; constructor TBaseNode.Create(DocPos: TDocPos); begin FDocPos := DocPos; end; function TBaseNode.ToString: string; begin if Self.ClassType = TBaseNode then Result := 'BaseNode' else if Self is TContinue then Result := 'Continue' else if Self is TBreak then Result := 'Break' else Result := Self.ToString; end; procedure TBaseNode.Compile(ctx: TCompilerContext); begin Assert(ctx <> nil, 'compiler context is `nil`'); if Self.ClassType = TBaseNode then RaiseException(eSyntaxError, eNotImplemented, FDocPos); Self.Compile(ctx); end; (* Everything should be inside a block.. *) constructor TBlock.Create(AList:TNodeArray; DocPos: TDocPos); begin List := AList; end; constructor TBlock.Create(AStmt:TBaseNode; DocPos: TDocPos); begin SetLength(List, 1); List[0] := AStmt; end; function TBlock.ToString: AnsiString; var i:Int32; begin Result := 'Block(['; for i:=0 to High(List) do begin Result += List[i].ToString; if i <> High(List) then Result += ', '; end; Result += '])'; end; procedure TBlock.Compile(ctx: TCompilerContext); var i:Int32; begin for i:=0 to High(List) do if List[i] = nil then continue else List[i].Compile(ctx); end; (* branching statements *) constructor TReturn.Create(AExpr:TBaseNode; DocPos: TDocPos); begin Expr := AExpr; FDocPos := DocPos; end; procedure TReturn.Compile(ctx: TCompilerContext); begin if Expr <> nil then Expr.Compile(ctx) else ctx.Emit(LOAD_CONST, ctx.GetNone(), FDocPos); ctx.Emit(RETURN, 0, FDocPos); end; procedure TContinue.Compile(ctx: TCompilerContext); begin ctx.Emit(__CONTINUE, 0, FDocPos); end; procedure TBreak.Compile(ctx: TCompilerContext); begin ctx.Emit(__BREAK, 0, FDocPos); end; (* A statement, for example a function-call. *) constructor TStatement.Create(AExpr:TBaseNode; DocPos: TDocPos); begin Expr := AExpr; FDocPos := DocPos; end; function TStatement.ToString: string; begin Result := 'Statement('+Expr.ToString+')'; end; procedure TStatement.Compile(ctx: TCompilerContext); begin Expr.Compile(ctx); ctx.Emit(DISCARD_TOP, 0, FDocPos); end; (* Variables that's considered constants, for example `1.0` in a script is a constant. *) function TConstant.ToString: string; begin Result := 'Constant('+StrVal+')'; end; procedure TConstant.Compile(ctx:TCompilerContext); begin if (Self is TConstBool) then (Self as TConstBool).Compile(ctx) else if (Self is TConstChar) then (Self as TConstChar).Compile(ctx) else if (Self is TConstInt) then (Self as TConstInt).Compile(ctx) else if (Self is TConstFloat) then (Self as TConstFloat).Compile(ctx) else if (Self is TConstString) then (Self as TConstString).Compile(ctx) else RaiseException(eSyntaxError, eNotImplemented, FDocPos); end; (* A None *) constructor TConstNone.Create(DocPos: TDocPos); begin StrVal := 'None'; FDocPos := DocPos; end; procedure TConstNone.Compile(ctx: TCompilerContext); begin ctx.Emit(LOAD_CONST, ctx.GetNone, FDocPos); end; (* A boolean *) constructor TConstBool.Create(AValue:String; DocPos: TDocPos); begin StrVal := AValue; Value := StrToBool(AValue); FDocPos := DocPos; end; procedure TConstBool.Compile(ctx: TCompilerContext); var obj:TEpObject; begin obj := ctx.GC.AllocBool(Value, 2); ctx.Emit(LOAD_CONST, ctx.RegisterConst(obj), FDocPos); end; (* A single character *) constructor TConstChar.Create(AValue:String; DocPos: TDocPos); begin StrVal := AValue; Value := #0; if Length(Value) > 0 then Value := AValue[1]; FDocPos := DocPos; end; procedure TConstChar.Compile(ctx: TCompilerContext); var obj:TEpObject; begin obj := ctx.GC.AllocChar(Value, 2); ctx.Emit(LOAD_CONST, ctx.RegisterConst(obj), FDocPos); end; (* An integer *) constructor TConstInt.Create(AValue:String; DocPos: TDocPos); begin StrVal := AValue; Value := StrToInt(AValue); FDocPos := DocPos; end; procedure TConstInt.Compile(ctx: TCompilerContext); var obj:TEpObject; begin obj := ctx.GC.AllocInt(Value, 2); ctx.Emit(LOAD_CONST, ctx.RegisterConst(obj), FDocPos); end; (* A floating point numbers *) constructor TConstFloat.Create(AValue:String; DocPos: TDocPos); begin StrVal := AValue; Value := StrToFloatDot(AValue); FDocPos := DocPos; end; procedure TConstFloat.Compile(ctx: TCompilerContext); var obj:TEpObject; begin obj := ctx.GC.AllocFloat(Value, 2); ctx.Emit(LOAD_CONST, ctx.RegisterConst(obj), FDocPos); end; (* strings *) constructor TConstString.Create(AValue:String; DocPos: TDocPos); begin StrVal := AValue; FDocPos := DocPos; end; procedure TConstString.Compile(ctx: TCompilerContext); var obj:TEpObject; begin obj := ctx.GC.AllocString(StrVal, 2); ctx.Emit(LOAD_CONST, ctx.RegisterConst(obj), FDocPos); end; (* Variables *) constructor TVariable.Create(AName:String; DocPos: TDocPos); begin Name := AName; FDocPos := DocPos; end; function TVariable.ToString: string; begin Result := 'Variable('+Name+')'; end; function TVariable.VarId(ctx: TCompilerContext): Int32; begin Result := ctx.LookupVar(self.Name, FDocPos); end; procedure TVariable.Compile(ctx: TCompilerContext); begin ctx.Emit(LOAD, ctx.LookupVar(self.Name, FDocPos), FDocPos); end; (* Declaring variables *) constructor TVarDecl.Create(AVariables:TVarArray; AExpr:TBaseNode; DocPos: TDocPos); begin Variables := AVariables; Expr := AExpr; FDocPos := DocPos; end; function TVarDecl.ToString: string; begin Result := 'VarDecl(...)'; end; procedure TVarDecl.Compile(ctx: TCompilerContext); var dest, i:Int32; begin for i:=0 to High(Variables) do begin dest := ctx.RegisterVar(TVariable(Variables[i]).Name, True); if Expr <> nil then begin Expr.Compile(ctx); Variables[i].Compile(ctx); ctx.Emit(RASGN, dest, FDocPos); end; end; end; (* Functions To-do: Fix for recursion, every time the function is called the local vars has to be re-allocated (somehow).. Sadly this will add a major overhead -.-' Edit: I've made temp patch that leaks A LOT, but whatever.. New To-do: Check for a more proper solution. *) constructor TFunction.Create(AName:string; AParams:TVarArray; AProg:TBlock; DocPos: TDocPos); begin Name := AName; Params := AParams; Prog := AProg; FDocPos := DocPos; end; function TFunction.ToString: string; begin Result := 'Function('+Name+')'; end; procedure TFunction.Compile(ctx: TCompilerContext); var dest,funcStart,i,funcID:Int32; funcObj: TFuncObject; varRange: TIntRange; var oldNameMap, funcNameMap: TStringToIntMap; begin funcID := ctx.RegisterVar(Name); //store current context state oldNameMap := ctx.Vars.NamesToNumbers; funcNameMap := oldNameMap.Copy(); //set context to our function and compile begin varRange.Low := Length(ctx.Vars.Names); ctx.Vars.NamesToNumbers := funcNameMap; ctx.PreparePatch(True, 'FUNCTION['+Name+']'); ctx.Emit(__FUNC, -1, FDocPos); funcStart := ctx.CodeSize; (* The caller has pushed arguments onto the stack, we need to store them *) for i:=0 to High(Params) do begin dest := ctx.RegisterVar(Params[High(Params)-i].Name); ctx.Emit(LOAD, dest, Params[High(Params)-i].FDocPos); ctx.Emit(RASGN, dest, Params[High(Params)-i].FDocPos); end; Prog.Compile(ctx); ctx.Emit(LOAD_CONST, ctx.GetNone(), FDocPos); ctx.Emit(RETURN, 0, FDocPos); varRange.High := High(ctx.Vars.Names); funcObj := ctx.GC.AllocFunc(Name, funcStart, varRange, 2) as TFuncObject; ctx.RunPatch(__FUNC, JMP_FORWARD, ctx.CodeSize()); ctx.PopPatch(True, 'END_FUNCTION'); end; //reset context ctx.Vars.NamesToNumbers := oldNameMap; ctx.Emit(LOAD_CONST, ctx.RegisterConst(funcObj), FDocPos); ctx.Emit(STORE_FAST, funcID, FDocPos); end; (* For calling a function, or a function like object *) constructor TCall.Create(ACallable:TBaseNode; AArgs:TNodeArray; DocPos: TDocPos); begin Callable := ACallable; Args := AArgs; FDocPos := DocPos; end; function TCall.ToString: string; begin Result := 'Call('+Callable.ToString+')'; end; procedure TCall.Compile(ctx: TCompilerContext); var i:Int32; begin for i:=0 to High(Args) do Args[i].Compile(ctx); Callable.Compile(ctx); ctx.Emit(CALL, Length(Args), FDocPos); end; (* For calling a function, or a function like object *) constructor TIndex.Create(AIndexable:TBaseNode; AArgs:TNodeArray; DocPos: TDocPos); begin Indexable := AIndexable; Args := AArgs; FDocPos := DocPos; end; function TIndex.ToString: string; begin Result := 'Index('+Indexable.ToString+')'; end; procedure TIndex.Compile(ctx: TCompilerContext); var dest:Int32; begin dest := ctx.PopDestVar; if dest < 0 then dest := ctx.getTempVar; Args[0].Compile(ctx); Indexable.Compile(ctx); ctx.Emit(GET_ITEM, dest, FDocPos); end; (* list expression *) constructor TListExpr.Create(AExpressions:TNodeArray; DocPos: TDocPos); begin FDocPos := DocPos; Expressions := AExpressions; end; function TListExpr.ToString: string; begin Result := 'ListExpr(...)'; end; procedure TListExpr.Compile(ctx: TCompilerContext); var dest,i,l:Int32; begin dest := ctx.PopDestVar; if dest < 0 then dest := ctx.getTempVar; l := Length(Expressions); for i:=0 to l-1 do Expressions[i].Compile(ctx); ctx.Emit(LOAD_CONST, ctx.RegisterConst(ctx.GC.AllocInt(l, 2)), FDocPos); ctx.Emit(BUILD_LIST, dest, FDocPos); end; (* Handling of unary operations, eg "-value" *) constructor TUnaryOp.Create(Operation:TToken; ALeft:TBaseNode; APostFix:Boolean; DocPos: TDocPos); begin Left := ALeft; Op := Operation; PostFix := APostFix; FDocPos := DocPos; end; function TUnaryOp.ToString: string; begin if PostFix then Result := 'UnaryOp('+Left.ToString+'`'+ Op.Value +'`)' else Result := 'UnaryOp('+Left.ToString+'`'+ Op.Value +'`)' end; procedure TUnaryOp.Compile(ctx: TCompilerContext); var dest:Int32; begin dest := ctx.PopDestVar; if dest < 0 then dest := ctx.getTempVar; Left.Compile(ctx); if ((Op.Value = '++') or (Op.Value = '--')) then begin if not(Left is TVariable) then RaiseException(eSyntaxError, eExpectedVar, Left.FDocPos); if PostFix then begin if Op.Value = '++' then ctx.Emit(UNARY_POSTINC, dest, FDocPos) else if Op.Value = '--' then ctx.Emit(UNARY_POSTDEC, dest, FDocPos); end else if Op.Value = '++' then ctx.Emit(UNARY_PREINC, dest, FDocPos) else if Op.Value = '--' then ctx.Emit(UNARY_PREDEC, dest, FDocPos); end else begin if Op.Value = '-' then ctx.Emit(UNARY_SUB, dest, FDocPos) else if Op.Value = '+' then (* nothing *) else if Op.Value = 'not' then ctx.Emit(UNARY_NOT, dest, FDocPos) else if Op.Value = '~' then ctx.Emit(UNARY_BINV, dest, FDocPos) else RaiseException(eSyntaxError, eNotImplemented, Left.FDocPos); end; end; (* Handling of binary operations, eg "var1 * var2" *) constructor TBinOp.Create(Operation:TToken; ALeft, ARight:TBaseNode; DocPos: TDocPos); begin Left := ALeft; Right := ARight; Op := Operation; FDocPos := DocPos; end; function TBinOp.ToString: string; begin Result := 'BinOp(`'+ Op.Value +'`, '+Left.ToString+', '+ Right.ToString +')'; end; procedure TBinOp.Compile(ctx: TCompilerContext); var dest:Int32; begin dest := ctx.PopDestVar; if dest < 0 then dest := ctx.getTempVar; Left.Compile(ctx); Right.Compile(ctx); ctx.Emit(OperatorToOpcode[op.value], dest, FDocPos) end; (* Handle all simple assignment operations *) constructor TAssignment.Create(Operation:TToken; ALeft:TBaseNode; ARight:TBaseNode; DocPos: TDocPos); begin Left := ALeft; Right := ARight; Op := Operation; FDocPos := DocPos; end; function TAssignment.ToString: string; begin Result := 'Assignment(`'+ Op.Value +'`, '+Left.ToString+', '+ Right.ToString +')'; end; procedure TAssignment.Compile(ctx: TCompilerContext); var dest:Int32; isVar,isAsgn:Boolean; begin isVar := (Left is TVariable); isAsgn := (op.value = ':='); if (isVar) then begin dest := ctx.LookupVar(TVariable(Left).Name, Left.FDocPos); if isAsgn then begin if (Right is TBinOp) or (Right is TUnaryOp) or (Right is TIndex) or (Right is TListExpr) then begin ctx.PushDestVar(dest); Right.Compile(ctx); //compile with a destination = left: avoids an assignment ctx.Emit(DISCARD_TOP, 0, FDocPos); end else begin Left.Compile(ctx); Right.Compile(ctx); ctx.Emit(ASGN, dest, FDocPos) end; end else begin Left.Compile(ctx); Right.Compile(ctx); ctx.Emit(OperatorToOpcode[op.value], dest, FDocPos); end; end else if (Left is TIndex) then begin Right.Compile(ctx); TIndex(Left).Indexable.Compile(ctx); //a tad hacky? ;P TIndex(Left).Args[0].Compile(ctx); if isAsgn then ctx.Emit(SET_ITEM, 0, FDocPos) else ctx.Emit(OperatorToOpcode[op.value], 0, FDocPos); end else RaiseException(eSyntaxError, eUnexpected, Left.FDocPos); end; (* <stmt> if (condition) else <stmt> *) constructor TIfExpression.Create(ACond:TBaseNode; ALeft, ARight:TBaseNode; DocPos: TDocPos); begin Condition := ACond; Left := ALeft; Right := ARight; FDocPos := DocPos; end; function TIfExpression.ToString: string; begin Result := 'IfExpr('+Condition.ToString+', '+ Left.ToString +':'+ Right.ToString +')'; end; procedure TIfExpression.Compile(ctx: TCompilerContext); var after,afterElse:Int32; begin Condition.Compile(ctx); after := ctx.Emit(JMP_IF_FALSE, 0, Condition.FDocPos); Left.Compile(ctx); afterElse := ctx.Emit(JMP_FORWARD, 0, Condition.FDocPos); ctx.PatchArg(after, ctx.CodeSize()); //jump here if false Right.Compile(ctx); ctx.PatchArg(afterElse, ctx.CodeSize()); //jump here to skip else end; (* if (condition) then <stmts> end if (condition) <stmt> if (condition) then <stmts> else <stmts> end if (condition) <stmt> else <stmt> NOT ALLOWED: if (condition) <stmt> else <stmts> end *) constructor TIf.Create(ACond:TBaseNode; ABody, AElseBody:TBlock; DocPos: TDocPos); begin Condition := ACond; Body := Abody; ElseBody := AElseBody; FDocPos := DocPos; end; function TIf.ToString: string; begin if ElseBody = nil then Result := 'If('+Condition.ToString+', '+ Body.ToString +')' else Result := 'If('+Condition.ToString+', '+ Body.ToString +''+ ElseBody.ToString +')'; end; procedure TIf.Compile(ctx: TCompilerContext); var after,afterElse:Int32; begin Condition.Compile(ctx); after := ctx.Emit(JMP_IF_FALSE, 0, Condition.FDocPos); Body.Compile(ctx); if (elseBody <> nil) then afterElse := ctx.Emit(JMP_FORWARD, 0, Condition.FDocPos); ctx.PatchArg(after, ctx.CodeSize()); //jump here if false if (elseBody <> nil) then begin ElseBody.Compile(ctx); ctx.PatchArg(afterElse, ctx.CodeSize()); //jump here to skip else end; end; (* while (condition) do <stmts> end while (condition) <stmt> *) constructor TWhile.Create(ACond:TBaseNode; ABody:TBlock; DocPos: TDocPos); begin Condition := ACond; Body := Abody; FDocPos := DocPos; end; function TWhile.ToString: string; begin Result := 'While('+Condition.ToString+', '+ Body.ToString +')'; end; procedure TWhile.Compile(ctx: TCompilerContext); var before,after:Int32; begin ctx.PreparePatch(); before := ctx.CodeSize(); //while --> Condition.Compile(ctx); after := ctx.Emit(JMP_IF_FALSE,0,Condition.FDocPos); //<-- do --> Body.Compile(ctx); ctx.Emit(JMP_BACK, before, Condition.FDocPos); //<-- ctx.PatchArg(after, ctx.CodeSize()); ctx.RunPatch(__CONTINUE, JMP_FORWARD, before); ctx.RunPatch(__BREAK, JMP_FORWARD, ctx.CodeSize()); ctx.PopPatch(); end; (* while (condition) do <stmts> end while (condition) <stmt> *) constructor TRepeat.Create(ACond:TBaseNode; ABody:TBlock; DocPos: TDocPos); begin Condition := ACond; Body := Abody; FDocPos := DocPos; end; function TRepeat.ToString: string; begin Result := 'Repeat('+ Body.ToString +', '+ Condition.ToString +')'; end; procedure TRepeat.Compile(ctx: TCompilerContext); var before,after:Int32; begin ctx.PreparePatch(); before := ctx.CodeSize(); //repeat --> Body.Compile(ctx); //<-- until --> Condition.Compile(ctx); after := ctx.Emit(JMP_IF_TRUE,0,Condition.FDocPos); ctx.Emit(JMP_BACK, before, Condition.FDocPos); //<-- ctx.PatchArg(after, ctx.CodeSize()); ctx.RunPatch(__CONTINUE, JMP_FORWARD, before); ctx.RunPatch(__BREAK, JMP_FORWARD, ctx.CodeSize()); ctx.PopPatch(); end; (* for (stmt1,stmt2,stmt3) do <stmts> end for (stmt1,stmt2,stmt3) <stmt> *) constructor TFor.Create(AStmt1,AStmt2,AStmt3:TBaseNode; ABody:TBlock; DocPos: TDocPos); begin Stmt1 := AStmt1; Stmt2 := AStmt2; Stmt3 := AStmt3; Body := Abody; FDocPos := DocPos; end; function TFor.ToString: string; begin Result := 'For(..., '+ Body.ToString +')'; end; procedure TFor.Compile(ctx: TCompilerContext); var before,after,incPos:Int32; begin if Stmt1 <> nil then Stmt1.Compile(ctx); //before the loop ctx.PreparePatch(); before := ctx.CodeSize(); if Stmt2 <> nil then begin Stmt2.Compile(ctx); //the beginning of the body after := ctx.Emit(JMP_IF_FALSE, 0, Stmt2.FDocPos); end; Body.Compile(ctx); incPos := ctx.CodeSize; if Stmt3 <> nil then Stmt3.Compile(ctx); //after the body ctx.Emit(JMP_BACK, before, FDocPos); if Stmt2 <> nil then ctx.PatchArg(after, ctx.CodeSize()); ctx.RunPatch(__CONTINUE, JMP_FORWARD, incPos); ctx.RunPatch(__BREAK, JMP_FORWARD, ctx.CodeSize()); ctx.PopPatch(); end; (* print <something> *) constructor TPrint.Create(AExprs:TNodeArray; DocPos: TDocPos); begin Exprs := AExprs; FDocPos := DocPos; end; function TPrint.ToString: string; begin Result := 'Print(...)'; end; procedure TPrint.Compile(ctx: TCompilerContext); var i:Int32; begin for i:=0 to High(Exprs) do Exprs[i].Compile(ctx); ctx.Emit(PRINT, Length(Exprs), FDocPos); end; (* print time //used for testing atm *) constructor TTimeNow.Create(DocPos: TDocPos); begin FDocPos := DocPos; end; function TTimeNow.ToString: string; begin Result := 'TimeNow(...)'; end; procedure TTimeNow.Compile(ctx: TCompilerContext); begin ctx.Emit(TIMENOW, 0, FDocPos); end; end.
unit DataSetHelper; interface uses Data.DB, System.SysUtils, Xml.XmlIntf, Xml.XmlDoc {$IFDEF EH_LIB_25} , MemTableEh {$ENDIF} ; type TDataSetLoopOption = ( /// <summary> /// Запрещает восстановление закладок. /// </summary> dsloNoRestoreBookmark, /// <summary> /// Запрещает отключение элементов управления. /// </summary> dsloNoDisableControls, /// <summary> /// Запрещает отключение фильтров. /// </summary> dsloNoDisableFilter, /// <summary> /// Запрещает обнуление события BeforeScroll. /// </summary> dsloNoNullifyBeforeScrollEvent, /// <summary> /// Запрещает обнуление события AfterScroll. /// </summary> dsloNoNullifyAfterScrollEvent, /// <summary> /// Начинать с текущей записи. /// </summary> dsloFromCurrent, /// <summary> /// Идти в обратном порядке. /// </summary> dsloReverseOrder, /// <summary> /// Только текущая запись. /// </summary> dsloOnlyCurrentRecord, /// <summary> /// Только измененные записи. /// </summary> dsloOnlyModifiedRecords ); TDataSetLoopOptions = set of TDataSetLoopOption; TDataSetLoopState = class private broken, restoreBookmark: boolean; public constructor Create; /// <summary> /// Останавливает перебор записей объекта TDataSet. /// </summary> /// <param name="restoreBookmark"> /// Нужно ли восстанавливать закладку. По умолчанию true. /// </param> procedure Break(restoreBookmark: boolean = true); /// <summary> /// Возвращает true, если перебор записей остановлен. /// </summary> property IsBroken: boolean read broken; end; TDataSetHelper = class helper for TDataSet public /// <summary> /// Проверяет, активен ли объект TDataSet и есть ли в нём записи. /// </summary> function HasRecords: boolean; /// <summary> /// Перебирает все записи объекта TDataSet и вызывает для них процедуру proc. /// Во время перебора отключаются элементы управления, фильтр и /// сохраняется закладка. /// </summary> /// <param name="proc"> /// Процедура, которая будет вызвана для каждой записи объекта TDataSet. /// </param> procedure ForEach(proc: TProc); overload; /// <summary> /// Перебирает все записи объекта TDataSet и вызывает для них процедуру proc. /// Во время перебора отключаются элементы управления, фильтр и /// сохраняется закладка. /// </summary> /// <param name="proc"> /// Процедура, которая будет вызвана для каждой записи объекта TDataSet. /// </param> procedure ForEach(proc: TProc<TDataSetLoopState>); overload; /// <summary> /// Перебирает все записи объекта TDataSet и вызывает для них процедуру proc. /// </summary> /// <param name="options"> /// Опции выполнения перебора. /// </param> /// <param name="proc"> /// Процедура, которая будет вызвана для каждой записи объекта TDataSet. /// </param> procedure ForEach(options: TDataSetLoopOptions; proc: TProc); overload; /// <summary> /// Перебирает все записи объекта TDataSet и вызывает для них процедуру proc. /// </summary> /// <param name="options"> /// Опции выполнения перебора. /// </param> /// <param name="proc"> /// Процедура, которая будет вызвана для каждой записи объекта TDataSet. /// </param> procedure ForEach(options: TDataSetLoopOptions; proc: TProc<TDataSetLoopState>); overload; /// <summary> /// Записывает данные в XML, хранящиеся в объекте TDataSet. /// Сохраняются все поля. /// </summary> /// <param name="rowPath"> /// Путь к элементам XML, в которые будут записаны отдельные записи из /// объекта TDataSet начиная с корневого элемента XML, например, '/mydata/myrow'. /// Пространства имён не поддерживаются! /// По умолчанию используется путь '/data/row'. /// </param> function ToXML(rowPath: string = ''): IXMLDocument; overload; /// <summary> /// Записывает данные в XML, хранящиеся в объекте TDataSet. /// </summary> /// <param name="rowPath"> /// Путь к элементам XML, в которые будут записаны отдельные записи из /// объекта TDataSet начиная с корневого элемента XML, например, '/mydata/myrow'. /// Пространства имён не поддерживаются! /// По умолчанию используется путь '/data/row'. /// </param> /// <param name="fields"> /// Имена полей для сохранения в XML. /// Если массив пустой, то идёт сохранение всех полей. /// </param> function ToXML(rowPath: string; fields: array of string) : IXMLDocument; overload; /// <summary> /// Записывает данные в XML, хранящиеся в объекте TDataSet. /// Для записей используется путь '/data/row'. /// Сохраняются все поля. /// </summary> /// <param name="fields"> /// Имена полей для сохранения в XML. /// Если массив пустой, то идёт сохранение всех полей. /// </param> function ToXML(fields: array of string): IXMLDocument; overload; /// <summary> /// Записывает данные в XML, хранящиеся в объекте TDataSet. /// Если XML не указан, то создаёт новый экземпляр IXMLDocument. /// Сохраняются все поля. /// </summary> /// <param name="rowPath"> /// Путь к элементам XML, в которые будут записаны отдельные записи из /// объекта TDataSet начиная с корневого элемента XML, например, '/mydata/myrow'. /// Пространства имён не поддерживаются! /// По умолчанию используется путь '/data/row'. /// </param> /// <param name="doc"> /// Документ, внутрь которого нужно записать данные. /// Если указан nil, то будет создан новый документ. /// </param> /// <returns> /// Возвращает XML-документ с записанными в него данными. /// </returns> function ToXML(rowPath: string; doc: IXMLDocument): IXMLDocument; overload; /// <summary> /// Записывает данные в XML, хранящиеся в объекте TDataSet. /// Если XML не указан, то создаёт новый экземпляр IXMLDocument. /// Сохраняются все поля. /// </summary> /// <param name="doc"> /// Документ, внутрь которого нужно записать данные. /// Если указан nil, то будет создан новый документ. /// </param> /// <returns> /// Возвращает XML-документ с записанными в него данными. /// </returns> function ToXML(doc: IXMLDocument): IXMLDocument; overload; /// <summary> /// Записывает данные в XML, хранящиеся в объекте TDataSet. /// Если XML не указан, то создаёт новый экземпляр IXMLDocument. /// </summary> /// <param name="rowPath"> /// Путь к элементам XML, в которые будут записаны отдельные записи из /// объекта TDataSet начиная с корневого элемента XML, например, '/mydata/myrow'. /// Пространства имён не поддерживаются! /// По умолчанию используется путь '/data/row'. /// </param> /// <param name="doc"> /// Документ, внутрь которого нужно записать данные. /// Если указан nil, то будет создан новый документ. /// </param> /// <param name="fields"> /// Имена полей для сохранения в XML. /// Если массив пустой, то идёт сохранение всех полей. /// </param> /// <returns> /// Возвращает XML-документ с записанными в него данными. /// </returns> function ToXML(rowPath: string; doc: IXMLDocument; fields: array of string) : IXMLDocument; overload; /// <summary> /// Записывает данные в XML, хранящиеся в объекте TDataSet. /// Если XML не указан, то создаёт новый экземпляр IXMLDocument. /// </summary> /// <param name="doc"> /// Документ, внутрь которого нужно записать данные. /// Если указан nil, то будет создан новый документ. /// </param> /// <param name="fields"> /// Имена полей для сохранения в XML. /// Если массив пустой, то идёт сохранение всех полей. /// </param> /// <returns> /// Возвращает XML-документ с записанными в него данными. /// </returns> function ToXML(doc: IXMLDocument; fields: array of string) : IXMLDocument; overload; /// <summary> /// Записывает данные в XML, хранящиеся в объекте TDataSet. /// Если параметр doc = nil, то создаёт новый экземпляр IXMLDocument. /// </summary> /// <param name="options"> /// Опции выполнения перебора. /// </param> /// <param name="rowPath"> /// Путь к элементам XML, в которые будут записаны отдельные записи из /// объекта TDataSet начиная с корневого элемента XML, например, '/mydata/myrow'. /// Пространства имён не поддерживаются! /// По умолчанию используется путь '/data/row'. /// </param> /// <param name="doc"> /// Документ, внутрь которого нужно записать данные. /// Если указан nil, то будет создан новый документ. /// </param> /// <param name="fieldNames"> /// Имена полей для сохранения в XML. /// Если массив пустой, то идёт сохранение всех полей. /// </param> function ToXML(const options: TDataSetLoopOptions; rowPath: string; doc: IXMLDocument; fieldNames: array of string): IXMLDocument; overload; end; TFieldHelper = class helper for TField public /// <summary> /// Считает сумму значений поля во всех записях. /// Значения null пропускаются. /// </summary> /// <returns> /// Возвращает сумму значений. /// Если записей нет или все поля null, то возвращает 0. /// </returns> function Sum: variant; overload; /// <summary> /// Считает сумму значений поля с учётом опций перебора. /// Значения null пропускаются. /// </summary> /// <param name="options"> /// Опции выполнения перебора. /// </param> /// <returns> /// Возвращает сумму значений. /// Если записей нет или все поля null, то возвращает 0. /// </returns> function Sum(options: TDataSetLoopOptions): variant; overload; /// <summary> /// Вычисляет среднее арифметическое значений поля во всех записях. /// Значения null пропускаются. /// </summary> /// <returns> /// Возвращает среднее арифметическое значений. /// Если записей нет или все поля null, то возвращает 0. /// </returns> function Avg: variant; overload; /// <summary> /// Вычисляет среднее арифметическое значений поля с учётом опций перебора. /// Значения null пропускаются. /// </summary> /// <param name="options"> /// Опции выполнения перебора. /// </param> /// <returns> /// Возвращает среднее арифметическое значений. /// Если записей нет или все поля null, то возвращает 0. /// </returns> function Avg(options: TDataSetLoopOptions): variant; overload; /// <summary> /// Находит минимальное значение поля во всех записях. /// Значения null пропускаются. /// </summary> /// <returns> /// Возвращает минимальное значение поля. /// Если записей нет или все поля null, то возвращает 0. /// </returns> function Min: variant; overload; /// <summary> /// Находит минимальное значение поля с учётом опций перебора. /// Значения null пропускаются. /// </summary> /// <param name="options"> /// Опции выполнения перебора. /// </param> /// <returns> /// Возвращает минимальное значение поля. /// Если записей нет или все поля null, то возвращает 0. /// </returns> function Min(options: TDataSetLoopOptions): variant; overload; /// <summary> /// Находит максимальное значение поля во всех записях. /// Значения null пропускаются. /// </summary> /// <returns> /// Возвращает максимальное значение поля. /// Если записей нет или все поля null, то возвращает null. /// </returns> function Max: variant; overload; /// <summary> /// Находит максимальное значение поля с учётом опций перебора. /// Значения null пропускаются. /// </summary> /// <param name="options"> /// Опции выполнения перебора. /// </param> /// <returns> /// Возвращает максимальное значение поля. /// Если записей нет или все поля null, то возвращает null. /// </returns> function Max(options: TDataSetLoopOptions): variant; overload; end; /// <summary> /// Функция возвращает значение ATrue, если AValue равно True и AFalse, если /// AValue равно False. /// </summary> /// <param name="AValue"> /// Флаг, определяющий, какое значение нужно вернуть. /// </param> /// <param name="ATrue"> /// Значение, которое нужно вернуть, если аргумент AValue равен True. /// </param> /// <param name="AFalse"> /// Значение, которое нужно вернуть, если аргумент AValue равен False. /// </param> function IfThenVar(AValue: Boolean; const ATrue: variant; const AFalse: variant) : variant; /// <summary> /// Функция конвертирует значение с типом Variant в строку с учётом локали. /// </summary> /// <param name="v"> /// Конвертируемое значение. /// </param> /// <param name="AFormatSettings"> /// Локальные настройки. /// </param> function VarToStrLoc(const v: variant; const formatSettings: TFormatSettings) : string; /// <summary> /// Конвертирует значение с типом Variant в строку для использования в XML. /// </summary> /// <param name="v"> /// Конвертируемое значение. /// </param> /// <param name="dataType"> /// Тип данных. Используется только для даты и времени. /// </param> function VarToXmlStr(const v: variant; dataType: TFieldType = ftDateTime) : string; implementation uses System.Variants, Soap.XSBuiltIns, Winapi.Windows; var xmlFormatSettings: TFormatSettings; constructor TDataSetLoopState.Create; begin broken := false; restoreBookmark := true; end; procedure TDataSetLoopState.Break(restoreBookmark: boolean = true); begin broken := true; self.restoreBookmark := restoreBookmark; end; procedure TDataSetHelper.ForEach(proc: TProc); begin ForEach([], proc); end; procedure TDataSetHelper.ForEach(proc: TProc<TDataSetLoopState>); begin ForEach([], proc); end; procedure TDataSetHelper.ForEach(options: TDataSetLoopOptions; proc: TProc); begin ForEach(options, procedure (state: TDataSetLoopState) begin proc; end); end; procedure TDataSetHelper.ForEach(options: TDataSetLoopOptions; proc: TProc<TDataSetLoopState>); var state: TDataSetLoopState; cd, fltr: boolean; bmrk: TBookmark; beforeScrollEvent, afterScrollEvent: TDataSetNotifyEvent; begin if not assigned(self) then raise EAccessViolation.Create('Набор данных не существует.'); if Active then begin beforeScrollEvent := BeforeScroll; afterScrollEvent := AfterScroll; if not (dsloNoNullifyBeforeScrollEvent in options) then BeforeScroll := nil; try if not (dsloNoNullifyAfterScrollEvent in options) then AfterScroll := nil; try state := TDataSetLoopState.Create; try cd := ControlsDisabled; if (not cd) and (not (dsloNoDisableControls in options)) then DisableControls; try bmrk := Bookmark; try fltr := Filtered and (not (dsloNoDisableFilter in options)); if fltr then Filtered := false; try if RecordCount > 0 then begin if not (dsloFromCurrent in options) then if dsloReverseOrder in options then Last else First; while ((dsloReverseOrder in options) and (not Bof)) or ((not (dsloReverseOrder in options)) and (not Eof)) do begin if (not (dsloOnlyModifiedRecords in options)) or (UpdateStatus <> usUnmodified) then proc(state); if state.broken or (dsloOnlyCurrentRecord in options) then break; if dsloReverseOrder in options then Prior else Next; end; end; finally if fltr then Filtered := true; end; finally if (not (dsloNoRestoreBookmark in options)) and state.restoreBookmark then begin {$IFDEF EH_LIB_25} if self is TMemTableEh then begin if TMemTableEh(self).BookmarkInVisibleView(bmrk) then Bookmark := bmrk; end else {$ENDIF} if BookmarkValid(bmrk) then Bookmark := bmrk; end; end; finally if (not cd) and (not (dsloNoDisableControls in options)) then EnableControls; end; finally state.Free; end; finally if not (dsloNoNullifyAfterScrollEvent in options) then AfterScroll := afterScrollEvent; end; finally if not (dsloNoNullifyBeforeScrollEvent in options) then BeforeScroll := beforeScrollEvent; end; end; end; function TDataSetHelper.HasRecords: boolean; begin Result := Active and (RecordCount > 0); end; function TDataSetHelper.ToXML(rowPath: string = ''): IXMLDocument; begin Result := ToXML([], rowPath, nil, []); end; function TDataSetHelper.ToXML(rowPath: string; fields: array of string) : IXMLDocument; begin Result := ToXML([], rowPath, nil, fields); end; function TDataSetHelper.ToXML(fields: array of string): IXMLDocument; begin Result := ToXML([], '', nil, fields); end; function TDataSetHelper.ToXML(rowPath: string; doc: IXMLDocument) : IXMLDocument; begin Result := ToXML([], rowPath, doc, []); end; function TDataSetHelper.ToXML(doc: IXMLDocument): IXMLDocument; begin Result := ToXML([], '', doc, []); end; function TDataSetHelper.ToXML(rowPath: string; doc: IXMLDocument; fields: array of string) : IXMLDocument; begin Result := ToXML([], rowPath, doc, fields); end; function TDataSetHelper.ToXML(doc: IXMLDocument; fields: array of string) : IXMLDocument; begin Result := ToXML([], '', doc, fields); end; function TDataSetHelper.ToXML(const options: TDataSetLoopOptions; rowPath: string; doc: IXMLDocument; fieldNames: array of string): IXMLDocument; var path: TArray<string>; node, parentNode: IXMLNode; i: integer; fields: array of TField; rowTagName: string; begin if not assigned(self) then raise EAccessViolation.Create('Набор данных не существует.'); if rowPath.IsEmpty then if assigned(doc) and assigned(doc.DocumentElement) then rowPath := '/' + doc.DocumentElement.NodeName + '/row' else rowPath := '/data/row'; path := rowPath.Split(['/'], TStringSplitOptions.ExcludeEmpty); if Length(path) < 2 then raise Exception.Create('Путь должен состоять как минимум из двух элементов XML, например, ''/data/row''.'); if not assigned(doc) then doc := TXMLDocument.Create(nil); if not doc.Active then doc.Active := true; if not assigned(doc.DocumentElement) then doc.DocumentElement := doc.CreateElement(path[0], '') else if path[0] <> doc.DocumentElement.NodeName then raise Exception.Create('Имя корневого элемента указанное в пути ''' + path[0] + ''' и имя корневого элемента в XML-документе ''' + doc.DocumentElement.NodeName + ''' не соответствуют.'); parentNode := doc.DocumentElement; for i := 1 to Length(path) - 2 do parentNode := parentNode.ChildNodes.Nodes[path[i]]; rowTagName := path[Length(path) - 1]; if Length(fieldNames) = 0 then begin SetLength(fields, FieldCount); for i := 0 to FieldCount - 1 do fields[i] := self.Fields[i]; end else begin SetLength(fields, Length(fieldNames)); for i := 0 to Length(fieldNames) - 1 do fields[i] := self.FieldByName(fieldNames[i]); end; ForEach(options, procedure var field: TField; begin node := parentNode.AddChild(rowTagName); for field in fields do if not field.IsNull then node.SetAttribute(field.FieldName, VarToXmlStr(field.Value, field.DataType)); end ); Result := doc; end; function TFieldHelper.Sum: variant; begin Result := Sum([]); end; function TFieldHelper.Sum(options: TDataSetLoopOptions): variant; var s: variant; begin if not assigned(self) then raise EAccessViolation.Create('Поле не существует.'); s := null; DataSet.ForEach(options, procedure begin if not IsNull then if VarIsNull(s) then s := Value else s := s + Value; end ); if VarIsNull(s) then s := 0; Result := s; end; function TFieldHelper.Avg: variant; begin Result := Avg([]); end; function TFieldHelper.Avg(options: TDataSetLoopOptions): variant; var s, c: variant; begin if not assigned(self) then raise EAccessViolation.Create('Поле не существует.'); Result := 0; c := 0; s := null; DataSet.ForEach(options, procedure begin if not IsNull then begin if VarIsNull(s) then s := Value else s := s + Value; Inc(c); end; end ); if c > 0 then Result := s / c; end; function TFieldHelper.Min: variant; begin Result := Min([]); end; function TFieldHelper.Min(options: TDataSetLoopOptions): variant; var m: variant; begin if not assigned(self) then raise EAccessViolation.Create('Поле не существует.'); m := null; DataSet.ForEach(options, procedure begin if not IsNull then if VarIsNull(m) then m := Value else m := IfThenVar(m < Value, m, Value); end ); Result := m; end; function TFieldHelper.Max: variant; begin Result := Max([]); end; function TFieldHelper.Max(options: TDataSetLoopOptions): variant; var m: variant; begin if not assigned(self) then raise EAccessViolation.Create('Поле не существует.'); m := null; DataSet.ForEach(options, procedure begin if not IsNull then if VarIsNull(m) then m := Value else m := IfThenVar(m > Value, m, Value); end ); Result := m; end; function IfThenVar(AValue: Boolean; const ATrue: variant; const AFalse: variant): variant; begin if AValue then result := ATrue else result := AFalse; end; function VarToStrLoc(const v: variant; const formatSettings: TFormatSettings): string; begin case VarType(v) of varSingle: Result := FloatToStr(v, formatSettings); varDouble: Result := FloatToStr(v, formatSettings); varCurrency: Result := CurrToStr(v, formatSettings); varDate: Result := DateTimeToStr(v, formatSettings); else Result := System.Variants.VarToStr(v); end; end; function VarToXmlStr(const v: variant; dataType: TFieldType): string; begin case VarType(v) of varDate: case dataType of ftDate: Result := FormatDateTime(xmlFormatSettings.ShortDateFormat, v, xmlFormatSettings);//ISO8601 ftTime: Result := FormatDateTime(xmlFormatSettings.ShortTimeFormat, v, xmlFormatSettings);//ISO8601 else //ISO8601 Result := DateTimeToXMLTime(v, false);//без пояса end; else Result := VarToStrLoc(v, xmlFormatSettings); end; end; initialization xmlFormatSettings := TFormatSettings.Create; xmlFormatSettings.DecimalSeparator := '.'; xmlFormatSettings.DateSeparator := '-'; xmlFormatSettings.ShortDateFormat := 'yyyy-mm-dd';//ISO8601 xmlFormatSettings.LongDateFormat := 'yyyy-mm-dd';//ISO8601 xmlFormatSettings.ShortTimeFormat := 'hh":"nn":"ss.zzz';//ISO8601 xmlFormatSettings.LongTimeFormat := 'hh":"nn":"ss.zzz';//ISO8601 end.
{ *************************************************************************** Copyright (c) 2016-2022 Kike Pérez Unit : Quick.Template Description : String Replace Templates Author : Kike Pérez Version : 2.0 Created : 01/04/2020 Modified : 31/03/2022 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Template; {$i QuickLib.inc} interface uses System.SysUtils, System.Generics.Collections, Quick.Commons; type {$IFNDEF FPC} TTokenFunc = reference to function(const aToken : string) : string; {$ELSE} TTokenFunc = function(const aToken : string) : string of object; {$ENDIF} TStringTemplate = class private fVariables : TDictionary<string,string>; fReplaceFunc : TTokenFunc; fQuoteBegin : string; fQuoteEnd : string; fBeginOffSet : Integer; fEndOffSet : Integer; protected constructor Create; overload; public constructor Create(const aQuoteBegin, aQuoteEnd : string; aVariables : TDictionary<string,string>); overload; constructor Create(const aQuoteBegin, aQuoteEnd : string; aReplaceFunc : TTokenFunc); overload; function Replace(const aTemplate : string) : string; virtual; end; EStringTemplateError = class(Exception); implementation { TStringTemplate } constructor TStringTemplate.Create; begin end; constructor TStringTemplate.Create(const aQuoteBegin, aQuoteEnd: string; aVariables: TDictionary<string, string>); begin inherited Create; if aQuoteBegin.IsEmpty or aQuoteEnd.IsEmpty then raise EStringTemplateError.Create('QuoteBegin and QuoteEnd cannot be null!'); if aVariables = nil then raise EStringTemplateError.Create('Dictionary cannot be null!'); fQuoteBegin := aQuoteBegin; fQuoteEnd := aQuoteEnd; fBeginOffSet := aQuoteBegin.Length; fEndOffSet := aQuoteEnd.Length; fVariables := aVariables; end; constructor TStringTemplate.Create(const aQuoteBegin, aQuoteEnd: string; aReplaceFunc: TTokenFunc); begin inherited Create; if aQuoteBegin.IsEmpty or aQuoteEnd.IsEmpty then raise EStringTemplateError.Create('QuoteBegin and QuoteEnd cannot be null!'); if not Assigned(aReplaceFunc) then raise EStringTemplateError.Create('ReplaceFunc cannot be null!'); fQuoteBegin := aQuoteBegin; fQuoteEnd := aQuoteEnd; fBeginOffSet := aQuoteBegin.Length; fEndOffSet := aQuoteEnd.Length; fReplaceFunc := aReplaceFunc; end; function TStringTemplate.Replace(const aTemplate : string) : string; var idx : Integer; st : Integer; et : Integer; token : string; tokrep : string; begin //resolve template Result := ''; st := 0; idx := 1; repeat st := aTemplate.IndexOf(fQuoteBegin,st) + 1; if st > 0 then begin et := aTemplate.IndexOf(fQuoteEnd,st) + 1; if et = 0 then Break; Result := Result + Copy(aTemplate,idx,st-idx); token := Copy(aTemplate,st + fBeginOffSet,et-st-fBeginOffSet); //replace token tokrep := ''; if fVariables <> nil then begin fVariables.TryGetValue(token,tokrep) end else begin tokrep := fReplaceFunc(token); end; if tokrep.IsEmpty then tokrep := fQuoteBegin + token + '?' + fQuoteEnd; Result := Result + tokrep; idx := et + fEndOffSet; end; until st = 0; Result := Result + Copy(aTemplate,idx,aTemplate.Length); end; end.
unit IdHeaderCoderIndy; interface {$i IdCompilerDefines.inc} uses IdGlobal, IdHeaderCoderBase; type TIdHeaderCoderIndy = class(TIdHeaderCoder) public class function Decode(const ACharSet: string; const AData: TIdBytes): String; override; class function Encode(const ACharSet, AData: String): TIdBytes; override; class function CanHandle(const ACharSet: String): Boolean; override; end; // RLebeau 4/17/10: this forces C++Builder to link to this unit so // RegisterHeaderCoder can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdHeaderCoderIndy"'*) implementation uses IdGlobalProtocols; class function TIdHeaderCoderIndy.Decode(const ACharSet: string; const AData: TIdBytes): String; var LEncoding: TIdTextEncoding; begin Result := ''; try LEncoding := CharsetToEncoding(ACharSet); {$IFNDEF DOTNET} try {$ENDIF} Result := LEncoding.GetString(AData); {$IFNDEF DOTNET} finally LEncoding.Free; end; {$ENDIF} except end; end; class function TIdHeaderCoderIndy.Encode(const ACharSet, AData: String): TIdBytes; var LEncoding: TIdTextEncoding; begin Result := nil; try LEncoding := CharsetToEncoding(ACharSet); {$IFNDEF DOTNET} try {$ENDIF} Result := LEncoding.GetBytes(AData); {$IFNDEF DOTNET} finally LEncoding.Free; end; {$ENDIF} except end; end; class function TIdHeaderCoderIndy.CanHandle(const ACharSet: String): Boolean; var LEncoding: TIdTextEncoding; begin try LEncoding := CharsetToEncoding(ACharSet); Result := Assigned(LEncoding); {$IFNDEF DOTNET} if Result then begin LEncoding.Free; end; {$ENDIF} except Result := False; end; end; initialization RegisterHeaderCoder(TIdHeaderCoderIndy); finalization UnregisterHeaderCoder(TIdHeaderCoderIndy); end.
unit HtmlHelpFunc; { Inno Setup Copyright (C) 1997-2006 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Functions for HTML Help $jrsoftware: issrc/Projects/HtmlHelpFunc.pas,v 1.6 2009/03/23 23:16:44 mlaan Exp $ } interface {$I VERSION.INC} uses Windows; const HH_DISPLAY_TOPIC = $0000; HH_KEYWORD_LOOKUP = $000D; type THtmlHelp = function(hwndCaller: HWND; pszFile: PChar; uCommand: UINT; dwData: DWORD): HWND; stdcall; PHH_AKLink = ^THH_AKLink; THH_AKLINK = record cbStruct: Integer; fReserved: Bool; pszKeywords: PChar; pszUrl: PChar; pszMsgText: PChar; pszMsgTitle: PChar; pszWindow: PChar; fIndexOnFail: Bool; end; var HtmlHelp: THtmlHelp; procedure InitHtmlHelpLibrary; procedure FreeHtmlHelpLibrary; implementation uses Messages, SysUtils; var HHCtrl: THandle; procedure InitHtmlHelpLibrary; begin if HHCtrl = 0 then begin HHCtrl := LoadLibrary('hhctrl.ocx'); if HHCtrl <> 0 then HtmlHelp := GetProcAddress(HHCtrl, {$IFDEF UNICODE}'HtmlHelpW'{$ELSE}'HtmlHelpA'{$ENDIF}) else HtmlHelp := nil; end; end; procedure FreeHtmlHelpLibrary; begin if HHCtrl <> 0 then begin HtmlHelp := nil; FreeLibrary(HHCtrl); HHCtrl := 0; end; end; function CloseHtmlHelpWindowsEnumProc(Wnd: HWND; lParam: LPARAM): BOOL; stdcall; var PID: DWORD; ClassName: array[0..31] of Char; MsgResult: DWORD; begin if (GetWindowThreadProcessId(Wnd, @PID) <> 0) and (PID = GetCurrentProcessId) then begin if (GetClassName(Wnd, ClassName, SizeOf(ClassName) div SizeOf(ClassName[0])) > 0) and (StrIComp(ClassName, 'HH Parent') = 0) then begin { Consider only enabled windows. If an HTML Help window is disabled because it's waiting on a modal dialog (e.g. Properties) then it's probably not safe to close it. } if IsWindowEnabled(Wnd) then SendMessageTimeout(Wnd, WM_CLOSE, 0, 0, SMTO_BLOCK, 7500, MsgResult); end; end; Result := True; end; procedure CloseHtmlHelpWindows; begin { Note: We don't call HtmlHelp(HH_CLOSE_ALL) here because its operation is asynchronous. (See: http://helpware.net/FAR/far_faq.htm#HH_CLOSE_ALL) If HHCTRL.OCX is unloaded too quickly after HH_CLOSE_ALL, a crash can occur. Even if HHCTRL.OCX isn't explicitly unloaded, it still *might* be possible for the main thread to exit while the HH thread is still in the process of closing the window and cleaning up the temporary file. Therefore, we use a different approach: we find the window(s) and send a WM_CLOSE message synchronously. } if Assigned(HtmlHelp) then EnumWindows(@CloseHtmlHelpWindowsEnumProc, 0); end; initialization finalization { Must explicitly close any open HTML Help window before terminating, otherwise it leaves behind a temporary file. (Most apps don't bother doing this, including IE and Outlook Express.) } CloseHtmlHelpWindows; end.
unit Unit1; interface uses Windows, SysUtils, Variants, ExtCtrls, Classes, Controls, Forms, StdCtrls, FileCtrl, shellapi, psAPI; const CheckerName='checker.exe'; ProgramName='current.exe'; CheckerLog='check.log'; CheckerInput='test.in'; CheckerOutput='test.out'; ProgramOutput='output.txt'; TesterLog='tester.log'; type TForm1 = class(TForm) Button1: TButton; path: TLabel; Memo3: TMemo; stderr: TMemo; report: TMemo; Timer2: TTimer; Timer1: TTimer; Memo5: TMemo; Memo4: TMemo; Memo7: TMemo; label5: TLabel; Memo6: TMemo; procedure Button1Click(Sender: TObject); procedure testing(pf:string; c,t,m:longint; ch:string; r:boolean; i,o:string); procedure FormCreate(Sender: TObject); procedure test(t:longint); procedure ExecConsoleApp(CommandLine: AnsiString; Output: TStringList); procedure check; procedure kill; procedure kill_checker; procedure KillProgram(ClassName: PChar; WindowTitle: PChar); procedure Timer1Timer(Sender: TObject); function checker_is_active:boolean; procedure Timer2Timer(Sender: TObject); function GetMemUsage(PID:Integer):Integer; function check_abc:boolean; private { Private declarations } public { Public declarations } end; var Form1: TForm1; count,TL,ML:longint; filename,input,output,checkerfilename:string; reportneed,success,Res, bTest:boolean; f,g:text; numb,error,wid,acm_test,acm_type:integer; get,rep,new_version,stdinput,stdoutput:string; time:int64; not_found,first,use_stdin,use_stdout, too_big:boolean; sa: TSECURITYATTRIBUTES; si: TSTARTUPINFO; pi: TPROCESSINFORMATION; hPipeOutputRead,hPipeOutputWrite,hPipeInputRead,hPipeInputWrite: THANDLE; env: array[0..100] of Char; szBuffer: array[0..256] of Char; dwNumberOfBytesRead: DWORD; Stream: TMemoryStream; OutP: TStringList; implementation {$R *.dfm} function GetFileSize(FileName:String):int64; var FS:TFileStream; begin result:=0; try FS:=TFileStream.Create(Filename,fmOpenRead); except Result:=-1; end; if Result<>-1 then Result:=FS.Size; FS.Free; end; procedure tform1.testing(pf:string; c,t,m:longint; ch:string; r:boolean; i,o:string); begin filename:=pf; count:=c; TL:=t; ML:=m; checkerfilename:=ch; reportneed:=r; input:=i; output:=o; if input='' then use_stdin:=true else use_stdin:=false; if output='' then use_stdout:=true else use_stdout:=false; label5.Caption:=''; writeln('Testing...'); button1click(form1); end; function tform1.GetMemUsage(PID:Integer):Integer; var hProc:THandle; pps:TPROCESSMEMORYCOUNTERS; begin hProc:=OpenProcess(PROCESS_VM_READ or PROCESS_QUERY_INFORMATION, False, PID); if hProc<>0 then begin FillChar(pps,Sizeof(pps),0); pps.cb:=Sizeof(pps); GetProcessMemoryInfo(hProc,@pps,Sizeof(pps)); Result:=pps.WorkingSetSize; CloseHandle(hProc); end else Result:=0; end; function tform1.checker_is_active:boolean; var Wnd:hWnd; windowtitle:pchar; begin windowtitle:=pchar(extractfilepath(application.exename)+'tests\'+checkername); wnd:=FindWindow(nil, WindowTitle); if wnd<>0 then result:=true else result:=false; end; procedure TForm1.Timer1Timer(Sender: TObject); label check_existence; var s,st,file_text,error_str:string; re:cardinal; er,i,counter,k,tim,got:longint; report_add:ansistring; F,g:textfile; t1,t2,t3,t4:_filetime; ch:char; begin timer1.Enabled:=false; timer2.Enabled:=false; file_text:=''; er:=0; if error<>5 then error:=0; st:=path.caption; chdir(st); check; if error<>3 then begin GetProcessTimes(pi.hProcess,t1,t2,t3,t4); time:=t3.dwLowDateTime div 1000; end else time:=0; got:=0; if (error=3) and (time<500) and (timer1.Interval=1) then error:=0; if (not not_found) and (not too_big) then begin Stream := TMemoryStream.Create; try while true do begin bTest := ReadFile(hPipeOutputRead, szBuffer, 256, dwNumberOfBytesRead, nil); if not bTest then break; Stream.Write(szBuffer, dwNumberOfBytesRead); end; stream.Position := 0; Outp.LoadFromStream(Stream); finally Stream.Free; end; WaitForSingleObject(pi.hProcess, tl div 1000); if error<>3 then GetExitCodeProcess(pi.hProcess,re) else re:=0; CloseHandle(pi.hProcess); CloseHandle(hPipeOutputRead); closehandle(hPipeInputRead); stderr.lines.assign(outp); OutP.Free; stdoutput:=stderr.text; check_existence: begin if fileexists(extractfilepath(application.exename)+'tests\'+output) or use_stdout then begin if not use_stdout then memo4.lines.LoadFromFile(extractfilepath(application.exename)+'tests\'+output) else memo4.Lines:=stderr.Lines; if error=3 then er:=3 else if error=5 then er:=5 else begin s:=extractfilepath(application.exename)+'tests\'+inttostr(numb)+'.out'; memo5.Lines.loadfromfile(s); if memo5.Lines.count<>memo4.Lines.count then er:=1 else begin assignfile(f,s); reset(f); if not use_stdout then assignfile(g,extractfilepath(application.exename)+'tests\'+output) else begin stderr.Lines.SaveToFile(extractfilepath(application.exename)+'tests\output.txt'); assignfile(g,extractfilepath(application.exename)+'tests\output.txt'); end; reset(g); while (not eof(f)) and (er=0) do begin readln(g,s); readln(f,st); if s<>st then inc(er); end; closefile(f); closefile(g); end; end; end else er:=2; end; if (er=2) and (got=0) then begin sleep(50); if fileexists(extractfilepath(application.exename)+'tests\'+output) then begin er:=0; inc(got); goto check_existence; end; end; if re<>0 then begin error_str:='Runtime error '+inttostr(re); er:=4; end; if (er<2) and (checkerfilename<>'') then begin try if (not(fileexists(extractfilepath(application.ExeName)+'tests\checker.exe'))) or (not(fileexists(extractfilepath(application.ExeName)+'tests\'+inttostr(numb)+'.in'))) or (not(fileexists(extractfilepath(application.ExeName)+'tests\'+inttostr(numb)+'.out'))) then er:=5 else begin if not use_stdout then memo7.Lines.LoadFromFile(extractfilepath(application.ExeName)+'tests\'+output) else memo7.Lines:=stderr.Lines; if not(fileexists(extractfilepath(application.ExeName)+'tests\output.txt')) then begin k:=filecreate(extractfilepath(application.ExeName)+'tests\output.txt'); fileclose(k); end; if not(fileexists(extractfilepath(application.ExeName)+'tests\test.in')) then begin k:=filecreate(extractfilepath(application.ExeName)+'tests\test.in'); fileclose(k); end; if not(fileexists(extractfilepath(application.ExeName)+'tests\test.out')) then begin k:=filecreate(extractfilepath(application.ExeName)+'tests\test.out'); fileclose(k); end; if not(fileexists(extractfilepath(application.ExeName)+'tests\check.log')) then begin k:=filecreate(extractfilepath(application.ExeName)+'tests\check.log'); fileclose(k); end; memo7.Lines.SaveToFile(extractfilepath(application.ExeName)+'tests\output.txt'); memo7.Lines.LoadFromFile(extractfilepath(application.ExeName)+'tests\'+inttostr(numb)+'.in'); memo7.Lines.SaveToFile(extractfilepath(application.ExeName)+'tests\test.in'); memo7.Lines.LoadFromFile(extractfilepath(application.ExeName)+'tests\'+inttostr(numb)+'.out'); memo7.Lines.SaveToFile(extractfilepath(application.ExeName)+'tests\test.out'); tim:=0; chdir(extractfilepath(application.exename)+'tests\'); outp:=TStringList.Create; ExecConsoleApp('checker.exe test.in test.out output.txt check.log',outp); sleep(400); while (checker_is_active) and (tim<100) do begin sleep(100); inc(tim); end; if (tim>=100) then begin kill_checker; er:=6; end else if fileexists(extractfilepath(application.exename)+'tests\check.log')=false then er:=6 else begin memo7.Lines.LoadFromFile(extractfilepath(application.ExeName)+'tests\check.log'); if UpperCase(memo7.lines.strings[0])='OK' then er:=0 else if UpperCase(memo7.lines.strings[0])='WA' then er:=1 else er:=6; end; outp.Free; if fileexists(extractfilepath(application.exename)+'tests\check.log') then DeleteFile(extractfilepath(application.exename)+'tests\check.log'); end; except er:=6; end; end; if er=1 then begin label5.caption:=label5.caption+' '+'W'; if acm_type=0 then begin acm_type:=1; acm_test:=numb; end; end else if er=2 then begin label5.caption:=label5.caption+' '+'O'; if acm_type=0 then begin acm_type:=2; acm_test:=numb; end; end else if er=3 then begin label5.caption:=label5.caption+' '+'T'; if acm_type=0 then begin acm_type:=3; acm_test:=numb; end; end else if er=4 then begin label5.caption:=label5.caption+' '+'R'; if acm_type=0 then begin acm_type:=4; acm_test:=numb; end; end else if er=5 then begin label5.caption:=label5.caption+' '+'M'; if acm_type=0 then begin acm_type:=5; acm_test:=numb; end; error:=0; end else if er=6 then begin label5.caption:=label5.caption+' '+'C'; end; if er=0 then begin label5.caption:=label5.caption+' '+'A'; end; if (er<>3) and (er<>4) and (er<>5) then begin if time=0 then time:=100; end; if time>=TL*1000 then time:=-1; if reportneed then begin report_add:='<tr style="mso-yfti-irow:2"><td class="first"><p class="MsoNormal" align="center"><span class="second">'+inttostr(numb)+'<o:p></o:p></span></p></td><td class="first"><p class="MsoNormal" align="center"><span class="second">'; if (er<>3) and (er<>5) then report_add:=report_add+inttostr(time)+' ms' else report_add:=report_add+'Killed'; report_add:=report_add+'<o:p></o:p></span></p></td><td class="first"><p class="MsoNormal" align="center"><span class="second">'; assignfile(f,extractfilepath(application.exename)+'tests\'+inttostr(numb)+'.in'); reset(f); file_text:=''; i:=0; while (i<255) and (not eof(F)) do begin inc(i); read(f,ch); file_text:=file_text+ch; end; if i=255 then file_text:=file_text+'...'; closefile(f); report_add:=report_add+file_text+'<o:p></o:p></span></p></td><td class="first"><p class="MsoNormal" align="center"><span class="second">'; assignfile(f,extractfilepath(application.exename)+'tests\'+inttostr(numb)+'.out'); reset(f); file_text:=''; i:=0; while (i<255) and (not eof(F)) do begin inc(i); read(f,ch); file_text:=file_text+ch; end; if i=255 then file_text:=file_text+'...'; closefile(f); report_add:=report_add+file_text+'<o:p></o:p></span></p></td><td class="first"><p class="MsoNormal" align="center"><span class="second">'; file_text:=''; if (fileexists(extractfilepath(application.exename)+'tests\'+output) or use_stdout) and (er<>2) and (er<>3) then begin if use_stdout then memo6.lines:=stderr.lines else memo6.lines.loadfromfile(extractfilepath(application.exename)+'tests\'+output); if not fileexists(extractfilepath(application.exename)+'tests\output.txt') then begin i:=filecreate(extractfilepath(application.exename)+'tests\output.txt'); fileclose(i); end; memo6.Lines.SaveToFile(extractfilepath(application.exename)+'tests\output.txt'); assignfile(f,extractfilepath(application.exename)+'tests\output.txt'); reset(f); i:=0; while (i<255) and (not eof(f)) do begin inc(i); read(f,ch); file_text:=file_text+ch; end; if i=255 then file_text:=file_text+'...'; closefile(f); deletefile(extractfilepath(application.exename)+'tests\output.txt'); end; report_add:=report_add+file_text+'<o:p></o:p></span></p></td><td class="first"><p class="MsoNormal" align="center">'; if label5.caption[length(label5.Caption)]='A' then file_text:='<span class="ok">OK' else if label5.caption[length(label5.Caption)]='W' then file_text:='<span class="bad">Wrong Answer' else if label5.caption[length(label5.Caption)]='T' then file_text:='<span class="bad">Time Limit Excedeed' else if label5.caption[length(label5.Caption)]='O' then file_text:='<span class="bad">No Output File' else if label5.caption[length(label5.Caption)]='C' then file_text:='<span class="bad">Checker Error' else if label5.caption[length(label5.Caption)]='M' then file_text:='<span class="bad">Memory Limit Excedeed' else if label5.caption[length(label5.caption)]='R' then file_text:='<span class="bad">'+error_str; report_add:=report_add+file_text+'<o:p></o:p></span></p></td></tr>'; report.lines.Insert(report.lines.count-2,report_add); end; if canvas.TextWidth(label5.Caption)-wid*390>=390 then begin label5.Caption:=label5.Caption+#13; inc(wid); end; if not use_stdin then deletefile(extractfilepath(application.exename)+'tests\'+input); if not use_stdout then deletefile(extractfilepath(application.exename)+'tests\'+output); inc(numb); end; if (numb>count) and (count<>0) then begin DeleteFile(extractfilepath(application.exename)+'tests\'+programname); if fileexists(extractfilepath(application.exename)+'tests\'+checkername) then DeleteFile(extractfilepath(application.exename)+'tests\'+checkername); if fileexists(extractfilepath(application.exename)+'tests\'+CheckerInput) then DeleteFile(extractfilepath(application.exename)+'tests\'+CheckerInput); if fileexists(extractfilepath(application.exename)+'tests\'+checkeroutput) then DeleteFile(extractfilepath(application.exename)+'tests\'+CheckerOutput); if fileexists(extractfilepath(application.exename)+'tests\'+ProgramOutput) then DeleteFile(extractfilepath(application.exename)+'tests\'+ProgramOutput); if error=1 then begin s:=label5.caption; delete(s,length(s),1); label5.Caption:=s; end; counter:=0; for i:=1 to length(label5.caption) do if label5.caption[i]='A' then inc(counter); label5.caption:=label5.Caption+' = '+inttostr(counter); if reportneed then begin report.Lines.Strings[10]:=inttostr(counter); if (not_found=true) and (length(label5.caption)=4) then file_text:='Tests has not been found!' else if acm_type=0 then file_text:='Accepted!' else if acm_type=1 then file_text:='Wrong Answer (Test #'+inttostr(acm_test)+')' else if acm_type=2 then file_text:='No Output File (Test #'+inttostr(acm_test)+')' else if acm_type=3 then file_text:='Time Limit Excedeed (Test #'+inttostr(acm_test)+')' else if acm_type=4 then file_text:='Runtime Error (Test #'+inttostr(acm_test)+')' else if acm_type=5 then file_text:='Memory Limit Excedeed (Test #'+inttostr(acm_test)+')'; report.lines.Strings[12]:=file_text; if checkerfilename<>'' then report.Lines.Insert(9,'</b>&nbsp;&nbsp;&nbsp;Checker: <b>'+checkerfilename); report.Lines.SaveToFile(rep); end; i:=1; s:=label5.Caption; while i<=length(s) do if s[i] in ['A'..'Z'] then inc(i) else delete(s,i,1); assignfile(f,extractfilepath(application.exename)+TesterLog); rewrite(f); writeln(f,s); closefile(f); writeln('Testing completed.'); if reportneed then begin writeln('Report:'); writeln(rep); end; form1.Close; end else begin timer1.Interval:=TL*1000; time:=0; test(numb); timer1.enabled:=true; sleep(100); timer2.Enabled:=true; end; end; procedure tform1.ExecConsoleApp(CommandLine: AnsiString; Output: TStringList); var Buf:array[0..1024] of byte; i:dword; begin sa.nLength:=sizeof(sa); sa.bInheritHandle:=true; sa.lpSecurityDescriptor:=nil; CreatePipe(hPipeOutputRead,hPipeOutputWrite,@sa,0); CreatePipe(hPipeInputRead,hPipeInputWrite,@sa,0); ZeroMemory(@env,SizeOf(env)); ZeroMemory(@si,SizeOf(si)); ZeroMemory(@pi,SizeOf(pi)); si.cb:=SizeOf(si); si.dwFlags:=(STARTF_USESHOWWINDOW) or (STARTF_USESTDHANDLES); si.wShowWindow:=SW_HIDE; if use_stdin then begin StrPCopy(@Buf[0],stdInput+^Z); WriteFile(hPipeInputWrite,Buf,Length(stdInput),i,nil); end; si.hStdInput:=hPipeInputRead; si.hStdOutput:=hPipeOutputWrite; si.hStdError:=hPipeOutputWrite; CloseHandle(hPipeInputWrite); Res:=CreateProcess(nil,pchar(CommandLine),nil,nil,true,(CREATE_NEW_CONSOLE) or (NORMAL_PRIORITY_CLASS),@env,nil,si,pi); if first then begin closehandle(hPipeInputRead); CloseHandle(hPipeOutputRead); end; if not(Res) then begin CloseHandle(hPipeOutputRead); CloseHandle(hPipeOutputWrite); Exit; end; CloseHandle(hPipeOutputWrite); end; procedure tform1.test(t:longint); var k:longint; s:string; f,g:textfile; begin s:=extractfilepath(application.exename)+'tests\'+inttostr(t); if not(use_stdin and (GetFileSize(s+'.in')>1024)) then begin if fileexists(s+'.in') and fileexists(s+'.out') then begin s:=extractfilepath(application.exename)+'tests\'+inttostr(t)+'.in'; assignfile(f,s); reset(f); if not use_stdin then begin k:=filecreate(extractfilepath(application.exename)+'tests\'+input); fileclose(k); assignfile(g,extractfilepath(application.exename)+'tests\'+input); rewrite(g); while not eof(f) do begin readln(f,s); writeln(g,s); end; closefile(g); end else begin stdinput:=''; while not eof(f) do begin readln(f,s); stdinput:=stdinput+s+#10#13; end; end; closefile(f); chdir(extractfilepath(application.exename)+'tests\'); OutP := TStringList.Create; stderr.lines.clear; too_big:=false; not_found:=false; error:=0; ExecConsoleApp('current.exe',OutP); end else begin writeln('File of test #',t,' was not found. Testing stopped.'); not_found:=true; numb:=99999; error:=1; end; end else begin s:='Size of test file #'+inttostr(t)+' exceeds 1024 B (data cannot be transmitted to testing program). Testing stopped.'; too_big:=true; numb:=99999; error:=8; end; end; procedure tform1.KillProgram(ClassName: PChar; WindowTitle: PChar); const PROCESS_TERMINATE = $0001; var ProcessHandle:THandle; ProcessID:Integer; TheWindow:HWND; begin TheWindow:=FindWindow(Classname, WindowTitle); GetWindowThreadProcessID(TheWindow, @ProcessID); ProcessHandle:=OpenProcess(PROCESS_TERMINATE, FALSE, ProcessId); TerminateProcess(ProcessHandle,4); end; function tform1.check_abc:boolean; var Wnd : hWnd; err:byte; windowtitle:pchar; procid:longint; begin err:=0; windowtitle:=pchar(extractfilepath(application.exename)+'tests\'+ProgramName); wnd:=FindWindow(nil, WindowTitle); if wnd<>0 then begin err:=1; GetWindowThreadProcessId(wnd, @ProcId); if ((getmemusage(procid)-1) div (1024*1024)+1)>ML then begin error:=5; timer2.Enabled:=false; timer1.Enabled:=false; timer1.Interval:=1; timer1.Enabled:=true; end; end; if err=0 then result:=true else result:=false; end; procedure tform1.kill; begin Killprogram(nil,pchar(extractfilepath(application.exename)+'tests\'+programname)); Sleep(100); end; procedure tform1.kill_checker; begin Killprogram(nil,pchar(extractfilepath(application.exename)+'tests\'+checkername)); Sleep(100); end; procedure tform1.check; var Wnd:hWnd; windowtitle:pchar; begin windowtitle:=pchar(extractfilepath(application.exename)+'tests\'+programname); wnd:=FindWindow(nil, WindowTitle); if wnd<>0 then begin if error=0 then error:=3; kill; end; end; procedure TForm1.Button1Click(Sender: TObject); var s,st,r,chk:string; i:integer; opStruc:TSHFileOpStruct; frombuf,tobuf:array[0..128] of Char; begin if fileexists(ExtractFilePath(Application.ExeName)+'tests\'+ProgramName) then deletefile(ExtractFilePath(Application.ExeName)+'tests\'+programname); if fileexists(ExtractFilePath(Application.ExeName)+'tests\'+CheckerName) then deletefile(ExtractFilePath(Application.ExeName)+'tests\'+checkername); if not use_stdin then if fileexists(ExtractFilePath(Application.ExeName)+'tests\'+input) then deletefile(ExtractFilePath(Application.ExeName)+'tests\'+input); if not use_stdout then if fileexists(ExtractFilePath(Application.ExeName)+'tests\'+output) then deletefile(ExtractFilePath(Application.ExeName)+'tests\'+output); error:=0; st:=path.caption; s:=ExtractFilePath(Application.ExeName)+'tests\'+programname; if reportneed then begin rep:=extractfilepath(application.ExeName)+'reports\report'; r:=datetostr(now); while pos('.',r)<>0 do delete(r,pos('.',r),1); rep:=rep+'_'+r; r:=timetostr(now); while pos(':',r)<>0 do delete(r,pos(':',r),1); rep:=rep+'_'+r+'.html'; i:=filecreate(rep); fileclose(I); acm_type:=0; acm_test:=0; deletefile(rep); i:=filecreate(rep); fileclose(i); report.lines:=memo3.lines; report.Lines.Strings[4]:=filename; report.lines.strings[2]:=timetostr(now); report.Lines.Strings[6]:=inttostr(TL)+' s'; report.Lines.Strings[8]:=inttostr(ML)+' MB'; end; FillChar(frombuf, Sizeof(frombuf), 0); FillChar(tobuf, Sizeof(tobuf), 0); StrPCopy(frombuf, filename); StrPCopy(tobuf, s); with OpStruc do begin Wnd:=Handle; wFunc:=FO_COPY; pFrom:=@frombuf; pTo:=@tobuf; fFlags:=FOF_NOCONFIRMATION or FOF_RENAMEONCOLLISION; fAnyOperationsAborted:=False; hNameMappings:=nil; lpszProgressTitle:=nil; end; ShFileOperation(OpStruc); if checkerfilename<>'' then begin chk:=ExtractFilePath(Application.ExeName)+'tests\'+checkername; FillChar(frombuf, Sizeof(frombuf), 0); FillChar(tobuf, Sizeof(tobuf), 0); StrPCopy(frombuf, checkerfilename); StrPCopy(tobuf, chk); with OpStruc do begin Wnd:=Handle; wFunc:=FO_COPY; pFrom:=@frombuf; pTo:=@tobuf; fFlags:=FOF_NOCONFIRMATION or FOF_RENAMEONCOLLISION; fAnyOperationsAborted:=False; hNameMappings:=nil; lpszProgressTitle:=nil; end; ShFileOperation(OpStruc); end; chdir(st); timer1.Interval:=TL*1000; time:=0; if not use_stdout then begin first:=true; test(1); sleep(timer1.Interval); check; end; timer1.Enabled:=true; test(1); if not_found=false then begin timer2.Enabled:=true; numb:=1; end; end; procedure TForm1.FormCreate(Sender: TObject); var s:string; begin GetDir(0,s); s:=s+'\'; if DirectoryExists(extractfilepath(application.exename)+'tests\')=false then createdir(extractfilepath(application.exename)+'tests\'); if DirectoryExists(extractfilepath(application.exename)+'reports\')=false then createdir(extractfilepath(application.exename)+'reports\'); path.caption:=s; form1.Width:=0; form1.Height:=0; end; procedure TForm1.Timer2Timer(Sender: TObject); begin inc(time,timer2.Interval); if check_abc then begin timer2.Enabled:=false; timer1.Enabled:=false; timer1.Interval:=1; timer1.Enabled:=true; end; end; end.
unit InfoENTTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoENTRecord = record PEntId: String[8]; PModCount: String[1]; PMentID: String[8]; PLineBus: String[4]; PBillFund: String[1]; PCodeKey: String[8]; PName: String[30]; PAddr1: String[30]; PAddr2: String[30]; PAddr3: String[30]; PCityState: String[25]; Pzip: String[10]; PContact: String[30]; PPhone: String[30]; PCommStat: String[1]; PCommpct: Currency; PAcctId: String[4]; PExpDate: String[8]; PCkHold: String[1]; End; TInfoENTBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoENTRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoENT = (InfoENTPrimaryKey, InfoENTName); TInfoENTTable = class( TDBISAMTableAU ) private FDFEntId: TStringField; FDFModCount: TStringField; FDFMentID: TStringField; FDFLineBus: TStringField; FDFBillFund: TStringField; FDFCodeKey: TStringField; FDFName: TStringField; FDFAddr1: TStringField; FDFAddr2: TStringField; FDFAddr3: TStringField; FDFCityState: TStringField; FDFzip: TStringField; FDFContact: TStringField; FDFPhone: TStringField; FDFCommStat: TStringField; FDFCommpct: TCurrencyField; FDFAcctId: TStringField; FDFExpDate: TStringField; FDFCkHold: TStringField; procedure SetPEntId(const Value: String); function GetPEntId:String; procedure SetPModCount(const Value: String); function GetPModCount:String; procedure SetPMentID(const Value: String); function GetPMentID:String; procedure SetPLineBus(const Value: String); function GetPLineBus:String; procedure SetPBillFund(const Value: String); function GetPBillFund:String; procedure SetPCodeKey(const Value: String); function GetPCodeKey:String; procedure SetPName(const Value: String); function GetPName:String; procedure SetPAddr1(const Value: String); function GetPAddr1:String; procedure SetPAddr2(const Value: String); function GetPAddr2:String; procedure SetPAddr3(const Value: String); function GetPAddr3:String; procedure SetPCityState(const Value: String); function GetPCityState:String; procedure SetPzip(const Value: String); function GetPzip:String; procedure SetPContact(const Value: String); function GetPContact:String; procedure SetPPhone(const Value: String); function GetPPhone:String; procedure SetPCommStat(const Value: String); function GetPCommStat:String; procedure SetPCommpct(const Value: Currency); function GetPCommpct:Currency; procedure SetPAcctId(const Value: String); function GetPAcctId:String; procedure SetPExpDate(const Value: String); function GetPExpDate:String; procedure SetPCkHold(const Value: String); function GetPCkHold:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoENT); function GetEnumIndex: TEIInfoENT; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoENTRecord; procedure StoreDataBuffer(ABuffer:TInfoENTRecord); property DFEntId: TStringField read FDFEntId; property DFModCount: TStringField read FDFModCount; property DFMentID: TStringField read FDFMentID; property DFLineBus: TStringField read FDFLineBus; property DFBillFund: TStringField read FDFBillFund; property DFCodeKey: TStringField read FDFCodeKey; property DFName: TStringField read FDFName; property DFAddr1: TStringField read FDFAddr1; property DFAddr2: TStringField read FDFAddr2; property DFAddr3: TStringField read FDFAddr3; property DFCityState: TStringField read FDFCityState; property DFzip: TStringField read FDFzip; property DFContact: TStringField read FDFContact; property DFPhone: TStringField read FDFPhone; property DFCommStat: TStringField read FDFCommStat; property DFCommpct: TCurrencyField read FDFCommpct; property DFAcctId: TStringField read FDFAcctId; property DFExpDate: TStringField read FDFExpDate; property DFCkHold: TStringField read FDFCkHold; property PEntId: String read GetPEntId write SetPEntId; property PModCount: String read GetPModCount write SetPModCount; property PMentID: String read GetPMentID write SetPMentID; property PLineBus: String read GetPLineBus write SetPLineBus; property PBillFund: String read GetPBillFund write SetPBillFund; property PCodeKey: String read GetPCodeKey write SetPCodeKey; property PName: String read GetPName write SetPName; property PAddr1: String read GetPAddr1 write SetPAddr1; property PAddr2: String read GetPAddr2 write SetPAddr2; property PAddr3: String read GetPAddr3 write SetPAddr3; property PCityState: String read GetPCityState write SetPCityState; property Pzip: String read GetPzip write SetPzip; property PContact: String read GetPContact write SetPContact; property PPhone: String read GetPPhone write SetPPhone; property PCommStat: String read GetPCommStat write SetPCommStat; property PCommpct: Currency read GetPCommpct write SetPCommpct; property PAcctId: String read GetPAcctId write SetPAcctId; property PExpDate: String read GetPExpDate write SetPExpDate; property PCkHold: String read GetPCkHold write SetPCkHold; published property Active write SetActive; property EnumIndex: TEIInfoENT read GetEnumIndex write SetEnumIndex; end; { TInfoENTTable } procedure Register; implementation function TInfoENTTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoENTTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoENTTable.GenerateNewFieldName } function TInfoENTTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoENTTable.CreateField } procedure TInfoENTTable.CreateFields; begin FDFEntId := CreateField( 'EntId' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TStringField; FDFMentID := CreateField( 'MentID' ) as TStringField; FDFLineBus := CreateField( 'LineBus' ) as TStringField; FDFBillFund := CreateField( 'BillFund' ) as TStringField; FDFCodeKey := CreateField( 'CodeKey' ) as TStringField; FDFName := CreateField( 'Name' ) as TStringField; FDFAddr1 := CreateField( 'Addr1' ) as TStringField; FDFAddr2 := CreateField( 'Addr2' ) as TStringField; FDFAddr3 := CreateField( 'Addr3' ) as TStringField; FDFCityState := CreateField( 'CityState' ) as TStringField; FDFzip := CreateField( 'zip' ) as TStringField; FDFContact := CreateField( 'Contact' ) as TStringField; FDFPhone := CreateField( 'Phone' ) as TStringField; FDFCommStat := CreateField( 'CommStat' ) as TStringField; FDFCommpct := CreateField( 'Commpct' ) as TCurrencyField; FDFAcctId := CreateField( 'AcctId' ) as TStringField; FDFExpDate := CreateField( 'ExpDate' ) as TStringField; FDFCkHold := CreateField( 'CkHold' ) as TStringField; end; { TInfoENTTable.CreateFields } procedure TInfoENTTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoENTTable.SetActive } procedure TInfoENTTable.SetPEntId(const Value: String); begin DFEntId.Value := Value; end; function TInfoENTTable.GetPEntId:String; begin result := DFEntId.Value; end; procedure TInfoENTTable.SetPModCount(const Value: String); begin DFModCount.Value := Value; end; function TInfoENTTable.GetPModCount:String; begin result := DFModCount.Value; end; procedure TInfoENTTable.SetPMentID(const Value: String); begin DFMentID.Value := Value; end; function TInfoENTTable.GetPMentID:String; begin result := DFMentID.Value; end; procedure TInfoENTTable.SetPLineBus(const Value: String); begin DFLineBus.Value := Value; end; function TInfoENTTable.GetPLineBus:String; begin result := DFLineBus.Value; end; procedure TInfoENTTable.SetPBillFund(const Value: String); begin DFBillFund.Value := Value; end; function TInfoENTTable.GetPBillFund:String; begin result := DFBillFund.Value; end; procedure TInfoENTTable.SetPCodeKey(const Value: String); begin DFCodeKey.Value := Value; end; function TInfoENTTable.GetPCodeKey:String; begin result := DFCodeKey.Value; end; procedure TInfoENTTable.SetPName(const Value: String); begin DFName.Value := Value; end; function TInfoENTTable.GetPName:String; begin result := DFName.Value; end; procedure TInfoENTTable.SetPAddr1(const Value: String); begin DFAddr1.Value := Value; end; function TInfoENTTable.GetPAddr1:String; begin result := DFAddr1.Value; end; procedure TInfoENTTable.SetPAddr2(const Value: String); begin DFAddr2.Value := Value; end; function TInfoENTTable.GetPAddr2:String; begin result := DFAddr2.Value; end; procedure TInfoENTTable.SetPAddr3(const Value: String); begin DFAddr3.Value := Value; end; function TInfoENTTable.GetPAddr3:String; begin result := DFAddr3.Value; end; procedure TInfoENTTable.SetPCityState(const Value: String); begin DFCityState.Value := Value; end; function TInfoENTTable.GetPCityState:String; begin result := DFCityState.Value; end; procedure TInfoENTTable.SetPzip(const Value: String); begin DFzip.Value := Value; end; function TInfoENTTable.GetPzip:String; begin result := DFzip.Value; end; procedure TInfoENTTable.SetPContact(const Value: String); begin DFContact.Value := Value; end; function TInfoENTTable.GetPContact:String; begin result := DFContact.Value; end; procedure TInfoENTTable.SetPPhone(const Value: String); begin DFPhone.Value := Value; end; function TInfoENTTable.GetPPhone:String; begin result := DFPhone.Value; end; procedure TInfoENTTable.SetPCommStat(const Value: String); begin DFCommStat.Value := Value; end; function TInfoENTTable.GetPCommStat:String; begin result := DFCommStat.Value; end; procedure TInfoENTTable.SetPCommpct(const Value: Currency); begin DFCommpct.Value := Value; end; function TInfoENTTable.GetPCommpct:Currency; begin result := DFCommpct.Value; end; procedure TInfoENTTable.SetPAcctId(const Value: String); begin DFAcctId.Value := Value; end; function TInfoENTTable.GetPAcctId:String; begin result := DFAcctId.Value; end; procedure TInfoENTTable.SetPExpDate(const Value: String); begin DFExpDate.Value := Value; end; function TInfoENTTable.GetPExpDate:String; begin result := DFExpDate.Value; end; procedure TInfoENTTable.SetPCkHold(const Value: String); begin DFCkHold.Value := Value; end; function TInfoENTTable.GetPCkHold:String; begin result := DFCkHold.Value; end; procedure TInfoENTTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('EntId, String, 8, N'); Add('ModCount, String, 1, N'); Add('MentID, String, 8, N'); Add('LineBus, String, 4, N'); Add('BillFund, String, 1, N'); Add('CodeKey, String, 8, N'); Add('Name, String, 30, N'); Add('Addr1, String, 30, N'); Add('Addr2, String, 30, N'); Add('Addr3, String, 30, N'); Add('CityState, String, 25, N'); Add('zip, String, 10, N'); Add('Contact, String, 30, N'); Add('Phone, String, 30, N'); Add('CommStat, String, 1, N'); Add('Commpct, Currency, 0, N'); Add('AcctId, String, 4, N'); Add('ExpDate, String, 8, N'); Add('CkHold, String, 1, N'); end; end; procedure TInfoENTTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, EntId, Y, Y, N, N'); Add('Name, Name, N, N, N, N'); end; end; procedure TInfoENTTable.SetEnumIndex(Value: TEIInfoENT); begin case Value of InfoENTPrimaryKey : IndexName := ''; InfoENTName : IndexName := 'Name'; end; end; function TInfoENTTable.GetDataBuffer:TInfoENTRecord; var buf: TInfoENTRecord; begin fillchar(buf, sizeof(buf), 0); buf.PEntId := DFEntId.Value; buf.PModCount := DFModCount.Value; buf.PMentID := DFMentID.Value; buf.PLineBus := DFLineBus.Value; buf.PBillFund := DFBillFund.Value; buf.PCodeKey := DFCodeKey.Value; buf.PName := DFName.Value; buf.PAddr1 := DFAddr1.Value; buf.PAddr2 := DFAddr2.Value; buf.PAddr3 := DFAddr3.Value; buf.PCityState := DFCityState.Value; buf.Pzip := DFzip.Value; buf.PContact := DFContact.Value; buf.PPhone := DFPhone.Value; buf.PCommStat := DFCommStat.Value; buf.PCommpct := DFCommpct.Value; buf.PAcctId := DFAcctId.Value; buf.PExpDate := DFExpDate.Value; buf.PCkHold := DFCkHold.Value; result := buf; end; procedure TInfoENTTable.StoreDataBuffer(ABuffer:TInfoENTRecord); begin DFEntId.Value := ABuffer.PEntId; DFModCount.Value := ABuffer.PModCount; DFMentID.Value := ABuffer.PMentID; DFLineBus.Value := ABuffer.PLineBus; DFBillFund.Value := ABuffer.PBillFund; DFCodeKey.Value := ABuffer.PCodeKey; DFName.Value := ABuffer.PName; DFAddr1.Value := ABuffer.PAddr1; DFAddr2.Value := ABuffer.PAddr2; DFAddr3.Value := ABuffer.PAddr3; DFCityState.Value := ABuffer.PCityState; DFzip.Value := ABuffer.Pzip; DFContact.Value := ABuffer.PContact; DFPhone.Value := ABuffer.PPhone; DFCommStat.Value := ABuffer.PCommStat; DFCommpct.Value := ABuffer.PCommpct; DFAcctId.Value := ABuffer.PAcctId; DFExpDate.Value := ABuffer.PExpDate; DFCkHold.Value := ABuffer.PCkHold; end; function TInfoENTTable.GetEnumIndex: TEIInfoENT; var iname : string; begin result := InfoENTPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoENTPrimaryKey; if iname = 'NAME' then result := InfoENTName; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoENTTable, TInfoENTBuffer ] ); end; { Register } function TInfoENTBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..19] of string = ('ENTID','MODCOUNT','MENTID','LINEBUS','BILLFUND','CODEKEY' ,'NAME','ADDR1','ADDR2','ADDR3','CITYSTATE' ,'ZIP','CONTACT','PHONE','COMMSTAT','COMMPCT' ,'ACCTID','EXPDATE','CKHOLD' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 19) and (flist[x] <> s) do inc(x); if x <= 19 then result := x else result := 0; end; function TInfoENTBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; 12 : result := ftString; 13 : result := ftString; 14 : result := ftString; 15 : result := ftString; 16 : result := ftCurrency; 17 : result := ftString; 18 : result := ftString; 19 : result := ftString; end; end; function TInfoENTBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PEntId; 2 : result := @Data.PModCount; 3 : result := @Data.PMentID; 4 : result := @Data.PLineBus; 5 : result := @Data.PBillFund; 6 : result := @Data.PCodeKey; 7 : result := @Data.PName; 8 : result := @Data.PAddr1; 9 : result := @Data.PAddr2; 10 : result := @Data.PAddr3; 11 : result := @Data.PCityState; 12 : result := @Data.Pzip; 13 : result := @Data.PContact; 14 : result := @Data.PPhone; 15 : result := @Data.PCommStat; 16 : result := @Data.PCommpct; 17 : result := @Data.PAcctId; 18 : result := @Data.PExpDate; 19 : result := @Data.PCkHold; end; end; end.
unit evTableColumnHotSpot; {* реализует интерфейс IevHotSpot для колонки таблицы. } // Модуль: "w:\common\components\gui\Garant\Everest\evTableColumnHotSpot.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevTableColumnHotSpot" MUID: (4ED31E9500E7) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface {$If Defined(evUseVisibleCursors)} uses l3IntfUses , evColumnBorderMarker , nevGUIInterfaces , l3Variant , nevBase , nevTools , l3Interfaces , afwInterfaces ; type RevTableColumnHotSpot = class of TevTableColumnHotSpot; TevTableColumnHotSpot = class(TevColumnBorderMarker, IevAdvancedHotSpot, IevHotSpotDelta) {* реализует интерфейс IevHotSpot для колонки таблицы. } private f_Delta: Integer; f_CanChangeTable: Boolean; protected function ProportionalChangeWidth(aTable: Tl3Variant; aDelta: Integer; const anOpPack: InevOp): Boolean; procedure ChangeCellWidth(const aView: InevControlView; const aProcessor: InevProcessor; const anOpPack: InevOp; const Keys: TevMouseState; const aRow: InevParaList; aDelta: Integer); function MouseAction(const aView: InevControlView; aButton: Tl3MouseButton; anAction: Tl3MouseAction; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; {* обрабатывает событие от мыши. Возвращает true - если обработано, иначе - false } function Delta: Integer; {* точность } function CanDrag: Boolean; public function CanChangeTable(const aView: InevControlView; aPara: Tl3Variant): Boolean; constructor Create(const aView: InevControlView; aPara: Tl3Variant; aColumnID: Integer; const aHint: Il3CString; aDelta: Integer); reintroduce; class function Make(const aView: InevControlView; aPara: Tl3Variant; aColumnID: Integer; const aHint: Il3CString = nil; aDelta: Integer = 0): IevAdvancedHotSpot; procedure HitTest(const aView: InevControlView; const aState: TafwCursorState; var theInfo: TafwCursorInfo); end;//TevTableColumnHotSpot {$IfEnd} // Defined(evUseVisibleCursors) implementation {$If Defined(evUseVisibleCursors)} uses l3ImplUses , k2Tags , l3Math , evdTypes , Classes , SysUtils , evInternalInterfaces {$If Defined(k2ForEditor)} , evParaTools {$IfEnd} // Defined(k2ForEditor) , CommentPara_Const , l3Base , evEditorInterfaces , l3InterfacesMisc , nevInterfaces {$If Defined(k2ForEditor)} , evTableCellUtils {$IfEnd} // Defined(k2ForEditor) , k2OpMisc , evMsgCode , l3IID //#UC START# *4ED31E9500E7impl_uses* //#UC END# *4ED31E9500E7impl_uses* ; function TevTableColumnHotSpot.ProportionalChangeWidth(aTable: Tl3Variant; aDelta: Integer; const anOpPack: InevOp): Boolean; //#UC START# *4ED321A40385_4ED31E9500E7_var* var l_Width : Integer; l_NewWidth : Integer; function ModifyRow(aRow: Tl3Variant; Index: Integer): Boolean; far; var l_PrevOldDelta : Integer; l_PrevNewDelta : Integer; function ModifyCell(aCell: Tl3Variant; Index: Integer): Boolean; far; var l_NewCellWidth : Integer; begin//ModifyCell Result := true; with aCell do begin with Attr[k2_tiWidth] do if IsValid then begin Inc(l_PrevOldDelta, AsLong); l_NewCellWidth := l3MulDiv(l_PrevOldDelta, l_NewWidth, l_Width) - l_PrevNewDelta; Inc(l_PrevNewDelta, l_NewCellWidth); end else l_NewCellWidth := 0; IntW[k2_tiWidth, anOpPack] := l_NewCellWidth; end;//with aCell end;//ModifyCell begin//ModifyRow l_PrevOldDelta := 0; l_PrevNewDelta := 0; Result := True; aRow.IterateChildrenF(L2Mk2ChildrenIterateChildrenFAction(@ModifyCell)); end;//ModifyRow function GetTableWidth: Integer; var l_Width: Integer absolute Result; function CalcWidth(aCell: Tl3Variant; Index: Integer): Boolean; far; begin Inc(l_Width, aCell.IntA[k2_tiWidth]); Result := True; end; begin l_Width := 0; aTable.Child[0].IterateChildrenF(L2Mk2ChildrenIterateChildrenFAction(@CalcWidth)); end; //#UC END# *4ED321A40385_4ED31E9500E7_var* begin //#UC START# *4ED321A40385_4ED31E9500E7_impl* Result := False; l_Width := GetTableWidth; l_NewWidth := l_Width + aDelta; if (l_NewWidth > 0) AND (l_Width > 0) then begin aTable.IterateChildrenF(L2Mk2ChildrenIterateChildrenFAction(@ModifyRow)); Result := True; end;//l_NewWidth > 0.. //#UC END# *4ED321A40385_4ED31E9500E7_impl* end;//TevTableColumnHotSpot.ProportionalChangeWidth procedure TevTableColumnHotSpot.ChangeCellWidth(const aView: InevControlView; const aProcessor: InevProcessor; const anOpPack: InevOp; const Keys: TevMouseState; const aRow: InevParaList; aDelta: Integer); //#UC START# *4ED3220102EE_4ED31E9500E7_var* var l_Width: Integer; procedure lp_ChangeHeadWidth(const aPara: InevPara; aCheckPrev: Boolean); var l_Cell : InevTableCell; l_PrevPart : InevTableCell; l_NexCell : InevPara; l_PrevPara : InevPara; begin with aPara do begin QT(InevTableCell, l_Cell); if TevMergeStatus(IntA[k2_tiMergeStatus]) = ev_msContinue then l_Cell := l_Cell.GetMergeHead; while l_Cell <> nil do begin l_PrevPart := l_Cell; l_Cell := l_Cell.GetContinueCell(True, fc_Down); if aCheckPrev then begin l_PrevPara := l_PrevPart.Prev; l_PrevPara.AsObject.IntW[k2_tiWidth, anOpPack] := l_PrevPara.AsObject.IntA[k2_tiWidth] + aDelta; end // if aCheckPrev then else l_PrevPart.AsObject.IntW[k2_tiWidth, anOpPack] := l_Width; if (ssShift in Keys.rKeys) then begin l_NexCell := l_PrevPart.Next; if l_NexCell.AsObject.IsValid then l_NexCell.AsObject.IntW[k2_tiWidth, anOpPack] := l_NexCell.AsObject.IntA[k2_tiWidth] - aDelta; end; // if l_WasShift then end; // while l_Cell <> nil do end; // with aPara do end; function lp_HasRowMergedCell(const aNext: InevPara): Boolean; var l_Next: InevPara; begin Result := False; l_Next := aNext; while l_Next.AsObject.IsValid do begin if (TevMergeStatus(l_Next.AsObject.IntA[k2_tiMergeStatus]) <> ev_msNone) then begin Result := True; Break; end; // if (TevMergeStatus(l_Next.IntA[k2_tiMergeStatus]) <> ev_msNone) then l_Next := l_Next.Next; end; // while l_Next.IsValid and (TevMergeStatus(l_Next.IntA[k2_tiMergeStatus]) = ev_msNone) do if Result and l_Next.AsObject.IsValid then lp_ChangeHeadWidth(l_Next, True); end; procedure lp_CorrectNextCell(const aPara, aNext: InevPara); begin aNext.AsObject.IntW[k2_tiWidth, anOpPack] := aNext.AsObject.IntA[k2_tiWidth] - aDelta; aPara.AsObject.IntW[k2_tiWidth, anOpPack] := aPara.AsObject.IntA[k2_tiWidth] + aDelta; end; var l_Next : InevPara; l_Para : InevPara; l_WasMerged : Boolean; //#UC END# *4ED3220102EE_4ED31E9500E7_var* begin //#UC START# *4ED3220102EE_4ED31E9500E7_impl* l_Para := aRow[ColumnID - 1]; with l_Para do begin l_Width := IntA[k2_tiWidth]; Inc(l_Width, aDelta); if (l_Width > 100) then begin if TevMergeStatus(IntA[k2_tiMergeStatus]) = ev_msNone then begin l_Next := l_Para.Next; if l_Next.AsObject.IsValid and (TevMergeStatus(l_Next.AsObject.IntA[k2_tiMergeStatus]) <> ev_msNone) then lp_ChangeHeadWidth(l_Next, True) else begin if lp_HasRowMergedCell(l_Next) then lp_CorrectNextCell(l_Para, l_Next) else IntW[k2_tiWidth, anOpPack] := l_Width; end; end // if TevMergeStatus(l_Para.IntA[k2_tiMergeStatus]) = ev_msNone then else lp_ChangeHeadWidth(l_Para, False); end; // if (l_Delta > 100) then end; // with l_Para do aProcessor.Lock; try aView.Control.SetFlag(ev_uwfRuler); finally aProcessor.Unlock; end; //#UC END# *4ED3220102EE_4ED31E9500E7_impl* end;//TevTableColumnHotSpot.ChangeCellWidth function TevTableColumnHotSpot.CanChangeTable(const aView: InevControlView; aPara: Tl3Variant): Boolean; //#UC START# *4ED3227A01E5_4ED31E9500E7_var* //#UC END# *4ED3227A01E5_4ED31E9500E7_var* begin //#UC START# *4ED3227A01E5_4ED31E9500E7_impl* if (aView.Control = nil) OR not Supports(aView.Control, IevF1LikeEditor) then Result := true else Result := evInPara(aPara, k2_typCommentPara); //#UC END# *4ED3227A01E5_4ED31E9500E7_impl* end;//TevTableColumnHotSpot.CanChangeTable constructor TevTableColumnHotSpot.Create(const aView: InevControlView; aPara: Tl3Variant; aColumnID: Integer; const aHint: Il3CString; aDelta: Integer); //#UC START# *4ED322C700D3_4ED31E9500E7_var* //#UC END# *4ED322C700D3_4ED31E9500E7_var* begin //#UC START# *4ED322C700D3_4ED31E9500E7_impl* inherited Create(aView, aPara, aColumnID, aHint); f_Delta := aDelta; f_CanChangeTable := CanChangeTable(aView, aPara); //#UC END# *4ED322C700D3_4ED31E9500E7_impl* end;//TevTableColumnHotSpot.Create class function TevTableColumnHotSpot.Make(const aView: InevControlView; aPara: Tl3Variant; aColumnID: Integer; const aHint: Il3CString = nil; aDelta: Integer = 0): IevAdvancedHotSpot; //#UC START# *4ED3231B03D7_4ED31E9500E7_var* var l_Spot : TevTableColumnHotSpot; //#UC END# *4ED3231B03D7_4ED31E9500E7_var* begin //#UC START# *4ED3231B03D7_4ED31E9500E7_impl* l_Spot := Create(aView, aPara, aColumnID, aHint, aDelta); try Result := l_Spot; finally l3Free(l_Spot); end;//try..finally //#UC END# *4ED3231B03D7_4ED31E9500E7_impl* end;//TevTableColumnHotSpot.Make procedure TevTableColumnHotSpot.HitTest(const aView: InevControlView; const aState: TafwCursorState; var theInfo: TafwCursorInfo); //#UC START# *48E2622A03C4_4ED31E9500E7_var* //#UC END# *48E2622A03C4_4ED31E9500E7_var* begin //#UC START# *48E2622A03C4_4ED31E9500E7_impl* {$IfDef evChangeTableByMouse} if f_CanChangeTable then begin theInfo.rCursor := ev_csHSplit; if (ssCtrl in aState.rKeys) then theInfo.rHint := Hint else begin if (ssShift in aState.rKeys) AND (ColumnID = Para.AsObject.ChildrenCount) then theInfo.rHint := str_nevmhhTableSize.AsCStr else theInfo.rHint := str_nevmhhColumnSize.AsCStr; end;//ssCtrl in aState.rKeys end;//f_CanChangeTable {$EndIf evChangeTableByMouse} //#UC END# *48E2622A03C4_4ED31E9500E7_impl* end;//TevTableColumnHotSpot.HitTest function TevTableColumnHotSpot.MouseAction(const aView: InevControlView; aButton: Tl3MouseButton; anAction: Tl3MouseAction; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; {* обрабатывает событие от мыши. Возвращает true - если обработано, иначе - false } //#UC START# *48E263CD01BD_4ED31E9500E7_var* var l_Processor : InevProcessor; l_OpPack : InevOp; l_Delta : Integer; l_Column : IedColumn; l_Row : InevParaList; l_Table : InevParaList; //#UC END# *48E263CD01BD_4ED31E9500E7_var* begin //#UC START# *48E263CD01BD_4ED31E9500E7_impl* {$IfDef evChangeTableByMouse} if f_CanChangeTable then begin case aButton of ev_mbLeft : begin case anAction of ev_maDown : begin Effect.rStrob := afw_stVert; Result := True; end;//ev_maDown ev_maUp : begin l_Delta := Keys.rPoint.X - Keys.rInitialPoint.X; l_Delta := evCheckCellWidth(l_Delta); if (ClientValue + l_Delta > 100) AND (aView <> nil) then try l_Processor := aView.Processor; //Processor; l_OpPack := k2StartOp(l_Processor, ev_msgChangeParam); try l_Row := Para.AsList; if not (ssCtrl in Keys.rKeys) then begin l_Table := l_Row.OwnerPara; if (ssShift in Keys.rKeys) then begin if (ColumnID = l_Row.AsObject.ChildrenCount) then begin Result := ProportionalChangeWidth(l_Table.AsObject, l_Delta, l_OpPack); l_Table.Invalidate([nev_spExtent]); //aView._InvalidateShape(l_Table.Shape, True); // - так как написано срочкой выше, так правильнее Exit; end//Column = l_Row.ChildrenCount else begin if l3IOk(evQueryParaInterface(aView, l_Processor, l_Row[ColumnID], Tl3GUID_C(IedColumn), l_Column)) then try l_Column.Width := l_Column.Width - l_Delta; finally l_Column := nil; end;//try..finally end;//Column = l_Row.ChildrenCount end;//Keys.rKeys AND MK_Shift <> 0 l_Table.MakePoint.Formatting.Modify(aView).ChangeParam(aView, Self, Value + l_Delta, l_OpPack); end//not (ssCtrl in Keys.rKeys) else ChangeCellWidth(aView, l_Processor, l_OpPack, Keys, l_Row, l_Delta); finally l_OpPack := nil; end;//try..finally finally l_Processor := nil; end;//try..finally Result := True; end;//ev_maUp ev_maMove : begin Result := (ClientValue + Keys.rPoint.X - Keys.rInitialPoint.X) > 100; end;//ev_maMove else Result := False; end;//case anAction end;//ev_mbLeft else Result := False; end;//case aButton end//f_CanChangeTable else Result := false; {$Else evChangeTableByMouse} Result := False; {$EndIf evChangeTableByMouse} //#UC END# *48E263CD01BD_4ED31E9500E7_impl* end;//TevTableColumnHotSpot.MouseAction function TevTableColumnHotSpot.Delta: Integer; {* точность } //#UC START# *4A23A71A02CC_4ED31E9500E7_var* //#UC END# *4A23A71A02CC_4ED31E9500E7_var* begin //#UC START# *4A23A71A02CC_4ED31E9500E7_impl* Result := f_Delta; //#UC END# *4A23A71A02CC_4ED31E9500E7_impl* end;//TevTableColumnHotSpot.Delta function TevTableColumnHotSpot.CanDrag: Boolean; //#UC START# *4ECCD6840014_4ED31E9500E7_var* //#UC END# *4ECCD6840014_4ED31E9500E7_var* begin //#UC START# *4ECCD6840014_4ED31E9500E7_impl* Result := False; //#UC END# *4ECCD6840014_4ED31E9500E7_impl* end;//TevTableColumnHotSpot.CanDrag {$IfEnd} // Defined(evUseVisibleCursors) end.
procedure TIOForm.TrackBar_InputGainChange(Sender: TObject); begin UpdateFromTrackbar_4_12(Link_InputGain, TrackBar_InputGain, Label_InputGain); end; procedure TIOForm.TrackBar_OutputGainChange(Sender: TObject); begin UpdateFromTrackbar_4_12(Link_OutputGain, TrackBar_OutputGain, Label_OutputGain); end; procedure UpdateDelayValue(aLink : ISignalLink; aTrackbar : TInstrumentTrackBar; aLabel : TInstrumentLabel); begin aLink.Value := aTrackBar.Value; aLabel.Caption := FloatToStrF((aTrackBar.Value / 255.0 * 65536 / 44000), ffFixed, 4, 1) + ' s'; // Delay value 64K buffer 44KHz sample rate end; procedure TIOForm.TrackBar_EchoDelayChange(Sender: TObject); begin UpdateDelayValue(Link_EchoDelay, TrackBar_EchoDelay, Label_EchoDelay); end; procedure TIOForm.TrackBar_EchoLevelChange(Sender: TObject); begin UpdateFromTrackbar_0_8(Link_EchoLevel, TrackBar_EchoLevel, Label_EchoLevel); end; procedure TIOForm.TrackBar_DelayDelayChange(Sender: TObject); begin UpdateDelayValue(Link_DelayDelay, TrackBar_DelayDelay, Label_DelayDelay); end; procedure TIOForm.TrackBar_DelayLevelChange(Sender: TObject); begin UpdateFromTrackbar_0_8(Link_DelayLevel, TrackBar_DelayLevel, Label_DelayLevel); end; procedure TIOForm.IOFormShow(Sender: TObject); begin TrackBar_InputGain .Value := 10; TrackBar_OutputGain.Value := 10; end; procedure TIOForm.InstrumentButton1Click(Sender: TObject); begin EqualizerForm.Show; end; procedure TIOForm.InstrumentButton2Click(Sender: TObject); begin StatusForm.Show; end; procedure TIOForm.InstrumentButton3Click(Sender: TObject); begin FilterDebugForm.Show; end;
unit XmlEditForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, xmldom, XMLIntf, msxmldom, XMLDoc, ComCtrls, ToolWin, OleCtrls, SHDocVw; type TFormXmlEdit = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; MemoXml: TMemo; ToolBar1: TToolBar; btnLoad: TToolButton; TabSheet5: TTabSheet; EditXmlFile: TEdit; Label1: TLabel; btnSave: TToolButton; xmlBar: TStatusBar; Label4: TLabel; EditFolder: TEdit; Label5: TLabel; EditBaseFile: TEdit; btnUpdate: TButton; cbAutoUpdate: TCheckBox; TabSheet7: TTabSheet; XmlBrowser: TWebBrowser; XMLDoc: TXMLDocument; ToolButton1: TToolButton; procedure btnLoadClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure MemoXmlChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnUpdateClick(Sender: TObject); procedure EditFolderOrFileChange(Sender: TObject); procedure TabSheet7Enter(Sender: TObject); procedure MemoXmlKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure MemoXmlMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } public { Public declarations } end; var FormXmlEdit: TFormXmlEdit; implementation {$R *.DFM} procedure TFormXmlEdit.btnLoadClick(Sender: TObject); begin // try to load the file MemoXml.Lines.LoadFromFile (EditXmlFile.Text); end; procedure TFormXmlEdit.btnSaveClick(Sender: TObject); begin // save the file MemoXml.Lines.SaveToFile (EditXmlFile.Text); end; procedure TFormXmlEdit.MemoXmlChange(Sender: TObject); var eParse: IDOMParseError; begin XmlDoc.Active := True; xmlBar.Panels[1].Text := 'OK'; xmlBar.Panels[2].Text := ''; (XmlDoc as IXMLDocumentAccess).DOMPersist.loadxml(MemoXml.Text); eParse := (XmlDoc.DOMDocument as IDOMParseError); if eParse.errorCode <> 0 then with eParse do begin xmlBar.Panels[1].Text := 'Error in: ' + IntToStr (Line) + '.' + IntToStr (LinePos); xmlBar.Panels[2].Text := SrcText + ': ' + Reason; end; end; procedure TFormXmlEdit.FormCreate(Sender: TObject); begin EditFolder.Text := ExtractFilePath (Application.ExeName); btnUpdateClick (self); end; procedure TFormXmlEdit.btnUpdateClick(Sender: TObject); begin EditXmlFile.Text := EditFolder.Text + EditBaseFile.Text + '.xml'; end; procedure TFormXmlEdit.EditFolderOrFileChange(Sender: TObject); begin if cbAutoUpdate.Checked then btnUpdateClick (self); end; procedure TFormXmlEdit.TabSheet7Enter(Sender: TObject); begin XmlBrowser.Navigate (EditXmlFile.Text); end; procedure TFormXmlEdit.MemoXmlKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin xmlBar.Panels[0].Text := 'Pos: ' + IntToStr (MemoXml.CaretPos.Y + 1) + '.' + IntToStr (MemoXml.CaretPos.X + 1); end; procedure TFormXmlEdit.MemoXmlMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin xmlBar.Panels[0].Text := 'Pos: ' + IntToStr (MemoXml.CaretPos.Y + 1) + '.' + IntToStr (MemoXml.CaretPos.X + 1); end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, vtSpin, Migrator, Buttons; type TMainForm = class(TForm) MigrateBtn: TButton; ReportMemo: TMemo; GroupBox1: TGroupBox; Label1: TLabel; edLogin: TEdit; Label2: TLabel; edPassword: TEdit; Label3: TLabel; edServer: TEdit; Label4: TLabel; edPort: TvtSpinEdit; GroupBox2: TGroupBox; Label5: TLabel; edFamilyPath: TEdit; btnSelectDir: TSpeedButton; Label6: TLabel; edStoredProcPath: TEdit; SpeedButton1: TSpeedButton; procedure MigrateBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnSelectDirClick(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); private { Private declarations } f_Migrator: TMigrator; procedure DoReportCallBack(const aStr: String; WriteToLog: Boolean); procedure SetupMigratorParams; procedure ReadBackMigratorParams; public { Public declarations } end; var MainForm: TMainForm; implementation uses FileCtrl, l3Base, l3IniFile, ncsDataAccessServices, daDataProviderParams; {$R *.dfm} procedure TMainForm.DoReportCallBack(const aStr: String; WriteToLog: Boolean); const cMap: array [Boolean] of Byte = (10, 0); begin ReportMemo.Lines.Add(aStr); l3System.Msg2Log(aStr, cMap[WriteToLog]); Application.ProcessMessages; end; procedure TMainForm.MigrateBtnClick(Sender: TObject); begin ReportMemo.Lines.Clear; SetupMigratorParams; f_Migrator.Migrate; end; procedure TMainForm.FormCreate(Sender: TObject); begin InitStationAndServerConfig; TncsDataAccessServices.Instance.InitClient; f_Migrator := TMigrator.Create; f_Migrator.ReportCallback := DoReportCallBack; ReadBackMigratorParams; end; procedure TMainForm.FormDestroy(Sender: TObject); begin FreeANdNil(f_Migrator); end; procedure TMainForm.SetupMigratorParams; begin f_Migrator.PostrgesParams.Login := edLogin.Text; f_Migrator.PostrgesParams.Password := edPassword.Text; f_Migrator.PostrgesParams.DataServerHostName := edServer.Text; f_Migrator.PostrgesParams.DataServerPort := edPort.AsInteger; f_Migrator.PostrgesParams.DocStoragePath := edFamilyPath.Text; f_Migrator.StoredProcPath := edStoredProcPath.Text; end; procedure TMainForm.ReadBackMigratorParams; begin edLogin.Text := f_Migrator.PostrgesParams.Login; edPassword.Text := f_Migrator.PostrgesParams.Password; edServer.Text := f_Migrator.PostrgesParams.DataServerHostName; edPort.AsInteger := f_Migrator.PostrgesParams.DataServerPort; edFamilyPath.Text := f_Migrator.PostrgesParams.DocStoragePath; edStoredProcPath.Text := f_Migrator.StoredProcPath; end; procedure TMainForm.btnSelectDirClick(Sender: TObject); var l_Dir: String; begin l_Dir := edFamilyPath.Text; if SelectDirectory('Database path', '', l_Dir) then edFamilyPath.Text := l_Dir; end; procedure TMainForm.SpeedButton1Click(Sender: TObject); var l_Dir: String; begin l_Dir := edStoredProcPath.Text; if SelectDirectory('Stored proc path', '', l_Dir) then edStoredProcPath.Text := l_Dir; end; end.
unit UNetworkAdjustedTime; interface uses UThread, Classes; type TNetworkAdjustedTime = Class private FTimesList : TPCThreadList; FTimeOffset : Integer; FTotalCounter : Integer; Function IndexOfClientIp(list : TList; const clientIp : AnsiString) : Integer; Procedure UpdateMedian(list : TList); public constructor Create; destructor Destroy; override; procedure UpdateIp(const clientIp : AnsiString; clientTimestamp : Cardinal); procedure AddNewIp(const clientIp : AnsiString; clientTimestamp : Cardinal); procedure RemoveIp(const clientIp : AnsiString); function GetAdjustedTime : Cardinal; property TimeOffset : Integer read FTimeOffset; function GetMaxAllowedTimestampForNewBlock : Cardinal; end; implementation uses UTime, SysUtils, ULog, UConst; { TNetworkAdjustedTime } Type TNetworkAdjustedTimeReg = Record clientIp : AnsiString; // Client IP allows only 1 connection per IP (not using port) timeOffset : Integer; counter : Integer; // To prevent a time attack from a single IP with multiple connections, only 1 will be used for calc NAT End; PNetworkAdjustedTimeReg = ^TNetworkAdjustedTimeReg; procedure TNetworkAdjustedTime.AddNewIp(const clientIp: AnsiString; clientTimestamp : Cardinal); Var l : TList; i : Integer; P : PNetworkAdjustedTimeReg; begin l := FTimesList.LockList; try i := IndexOfClientIp(l,clientIp); if i<0 then begin New(P); P^.clientIp := clientIp; P^.counter := 0; l.Add(P); end else begin P := l[i]; end; P^.timeOffset := clientTimestamp - UnivDateTimeToUnix(DateTime2UnivDateTime(now)); inc(P^.counter); inc(FTotalCounter); UpdateMedian(l); TLog.NewLog(ltDebug,ClassName,Format('AddNewIp (%s,%d) - Total:%d/%d Offset:%d',[clientIp,clientTimestamp,l.Count,FTotalCounter,FTimeOffset])); finally FTimesList.UnlockList; end; end; constructor TNetworkAdjustedTime.Create; begin FTimesList := TPCThreadList.Create('TNetworkAdjustedTime_TimesList'); FTimeOffset := 0; FTotalCounter := 0; end; destructor TNetworkAdjustedTime.Destroy; Var P : PNetworkAdjustedTimeReg; i : Integer; l : TList; begin l := FTimesList.LockList; try for i := 0 to l.Count - 1 do begin P := l[i]; Dispose(P); end; l.Clear; finally FTimesList.UnlockList; end; FreeAndNil(FTimesList); inherited; end; function TNetworkAdjustedTime.GetAdjustedTime: Cardinal; begin Result := UnivDateTimeToUnix(DateTime2UnivDateTime(now)) + FTimeOffset; end; function TNetworkAdjustedTime.GetMaxAllowedTimestampForNewBlock: Cardinal; var l : TList; begin l := FTimesList.LockList; try Result := (GetAdjustedTime + CT_MaxFutureBlockTimestampOffset); finally FTimesList.UnlockList; end; end; function TNetworkAdjustedTime.IndexOfClientIp(list: TList; const clientIp: AnsiString): Integer; begin for Result := 0 to list.Count - 1 do begin if AnsiSameStr(PNetworkAdjustedTimeReg(list[result])^.clientIp,clientIp) then exit; end; Result := -1; end; procedure TNetworkAdjustedTime.RemoveIp(const clientIp: AnsiString); Var l : TList; i : Integer; P : PNetworkAdjustedTimeReg; begin l := FTimesList.LockList; try i := IndexOfClientIp(l,clientIp); if (i>=0) then begin P := l[i]; Dec(P^.counter); if (P^.counter<=0) then begin l.Delete(i); Dispose(P); end; Dec(FTotalCounter); end; UpdateMedian(l); if (i>=0) then TLog.NewLog(ltDebug,ClassName,Format('RemoveIp (%s) - Total:%d/%d Offset:%d',[clientIp,l.Count,FTotalCounter,FTimeOffset])) else TLog.NewLog(ltError,ClassName,Format('RemoveIp not found (%s) - Total:%d/%d Offset:%d',[clientIp,l.Count,FTotalCounter,FTimeOffset])) finally FTimesList.UnlockList; end; end; function SortPNetworkAdjustedTimeReg(p1, p2: pointer): integer; begin Result := PNetworkAdjustedTimeReg(p1)^.timeOffset - PNetworkAdjustedTimeReg(p2)^.timeOffset; end; procedure TNetworkAdjustedTime.UpdateIp(const clientIp: AnsiString; clientTimestamp: Cardinal); Var l : TList; i : Integer; P : PNetworkAdjustedTimeReg; lastOffset : Integer; begin l := FTimesList.LockList; try i := IndexOfClientIp(l,clientIp); if i<0 then begin TLog.NewLog(ltError,ClassName,Format('UpdateIP (%s,%d) not found',[clientIp,clientTimestamp])); exit; end else begin P := l[i]; end; lastOffset := P^.timeOffset; P^.timeOffset := clientTimestamp - UnivDateTimeToUnix(DateTime2UnivDateTime(now)); if (lastOffset<>P^.timeOffset) then begin UpdateMedian(l); TLog.NewLog(ltDebug,ClassName,Format('UpdateIp (%s,%d) - Total:%d/%d Offset:%d',[clientIp,clientTimestamp,l.Count,FTotalCounter,FTimeOffset])); end; finally FTimesList.UnlockList; end; end; procedure TNetworkAdjustedTime.UpdateMedian(list : TList); Var last : Integer; i : Integer; s : String; begin last := FTimeOffset; list.Sort(SortPNetworkAdjustedTimeReg); if list.Count<CT_MinNodesToCalcNAT then begin FTimeOffset := 0; end else if ((list.Count MOD 2)=0) then begin FTimeOffset := (PNetworkAdjustedTimeReg(list[(list.Count DIV 2)-1])^.timeOffset + PNetworkAdjustedTimeReg(list[(list.Count DIV 2)])^.timeOffset) DIV 2; end else begin FTimeOffset := PNetworkAdjustedTimeReg(list[list.Count DIV 2])^.timeOffset; end; if (last<>FTimeOffset) then begin s := ''; for i := 0 to list.Count - 1 do begin s := s + ',' + IntToStr(PNetworkAdjustedTimeReg(list[i])^.timeOffset); end; TLog.NewLog(ltinfo,ClassName, Format('Updated NAT median offset. My offset is now %d (before %d) based on %d/%d connections %s',[FTimeOffset,last,list.Count,FTotalCounter,s])); end; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Grids, Vcl.ValEdit, Vcl.Menus, ShellAPI, UITypes; type TM_Unit = record // структура узла дерева is_param: boolean; name: string[30]; value: integer; v_min: integer; v_max: integer; delta: integer; d_min: integer; d_max: integer; end; PM_Unit = ^TM_Unit; // указатель на структуру TForm1 = class(TForm) TreeView1: TTreeView; Panel1: TPanel; Button1: TButton; ValueListEditor1: TValueListEditor; MainMenu1: TMainMenu; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; File1: TMenuItem; Open1: TMenuItem; Save1: TMenuItem; Exit1: TMenuItem; ree1: TMenuItem; Addroot1: TMenuItem; Addchild1: TMenuItem; Remove1: TMenuItem; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Generate1: TMenuItem; Saveas1: TMenuItem; About1: TMenuItem; PopupMenu1: TPopupMenu; Addroot2: TMenuItem; Addchild2: TMenuItem; Remove2: TMenuItem; Expandall1: TMenuItem; Collapseall1: TMenuItem; procedure TreeView1Change(Sender: TObject; Node: TTreeNode); procedure TreeView1Deletion(Sender: TObject; Node: TTreeNode); procedure TreeView1Edited(Sender: TObject; Node: TTreeNode; var S: string); procedure TreeView1DragDrop(Sender, Source: TObject; X, Y: integer); procedure TreeView1DragOver(Sender, Source: TObject; X, Y: integer; State: TDragState; var Accept: boolean); procedure Button1Click(Sender: TObject); procedure Open1Click(Sender: TObject); procedure Save1Click(Sender: TObject); procedure Addroot1Click(Sender: TObject); procedure Addchild1Click(Sender: TObject); procedure Remove1Click(Sender: TObject); procedure Generate1Click(Sender: TObject); procedure ValueListEditor1KeyPress(Sender: TObject; var Key: Char); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Saveas1Click(Sender: TObject); procedure About1Click(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure Expandall1Click(Sender: TObject); procedure Collapseall1Click(Sender: TObject); private has_global_changes: boolean; has_param_changes: boolean; curNode: TTreeNode; global_counter: integer; function GetParentCount(Node: TTreeNode): integer; function TM_CreateUnit: PM_Unit; procedure TM_AddChild; procedure TM_AddRoot; procedure TM_Remove; procedure TM_Save(FName: string); procedure TM_Load(FName: string); procedure TM_Apply; procedure TM_Generate(FName: string); procedure TM_GenTreeArray(var SL: TStringList); procedure TM_GenParamArray(var SL: TStringList); procedure TM_GenPrintFunc(var SL: TStringList); procedure TM_GenChangeFunc(var SL: TStringList); procedure TM_GenSpecFunc(var SL: TStringList); procedure TM_GenExecFunc(var SL: TStringList); public { Public declarations } end; var Form1: TForm1; implementation uses About; {$R *.dfm} function TForm1.TM_CreateUnit: PM_Unit; var tmp_unit: PM_Unit; begin tmp_unit := new(PM_Unit); tmp_unit.is_param := true; tmp_unit.name := ShortString('Menu' + IntToStr(global_counter)); tmp_unit.value := 0; tmp_unit.v_min := 0; tmp_unit.v_max := 100; tmp_unit.delta := 10; tmp_unit.d_min := 1; tmp_unit.d_max := 100; inc(global_counter); Result := tmp_unit; end; procedure TForm1.TM_AddChild; var tmp_unit: PM_Unit; // tmp_node: TTreeNode; begin if curNode <> nil then begin tmp_unit := TM_CreateUnit; TreeView1.Items.AddChildObject(curNode, string(tmp_unit.name), tmp_unit); tmp_unit := curNode.Data; tmp_unit.is_param := false; ValueListEditor1.Values['Is parameter'] := BoolToStr(tmp_unit.is_param, true); curNode.Expand(false); has_global_changes := true; end; end; procedure TForm1.TM_AddRoot; var tmp_unit: PM_Unit; begin tmp_unit := TM_CreateUnit; TreeView1.Items.AddObject(nil, string(tmp_unit.name), tmp_unit); has_global_changes := true; end; procedure TForm1.TM_Apply; var tmp_unit: PM_Unit; begin if curNode = nil then Exit; if (curNode.getFirstChild <> nil) and (StrToBool(ValueListEditor1.Values['Is parameter'])) then begin MessageDlg('This node cannot be parameter because has children..', mtInformation, [mbOK], 0); ValueListEditor1.Values['Is parameter'] := 'False'; end; tmp_unit := curNode.Data; tmp_unit.is_param := StrToBool(ValueListEditor1.Values['Is parameter']); tmp_unit.name := ShortString(ValueListEditor1.Values['Name']); curNode.Text := string(tmp_unit.name); tmp_unit.value := StrToInt(ValueListEditor1.Values['Init value']); tmp_unit.v_min := StrToInt(ValueListEditor1.Values['Min value']); tmp_unit.v_max := StrToInt(ValueListEditor1.Values['Max value']); tmp_unit.delta := StrToInt(ValueListEditor1.Values['Init delta']); tmp_unit.d_min := StrToInt(ValueListEditor1.Values['Min delta']); tmp_unit.d_max := StrToInt(ValueListEditor1.Values['Max delta']); has_global_changes := true; has_param_changes := false; end; function TForm1.GetParentCount(Node: TTreeNode): integer; var X: integer; begin X := 0; while Node.Parent <> nil do begin inc(X); Node := Node.Parent; end; Result := X; end; procedure TForm1.TM_Generate(FName: string); var SL: TStringList; begin SL := TStringList.Create; TM_GenTreeArray(SL); TM_GenParamArray(SL); TM_GenPrintFunc(SL); TM_GenChangeFunc(SL); TM_GenExecFunc(SL); TM_GenSpecFunc(SL); SL.SaveToFile(FName); SL.Free; ShellExecute(Application.Handle, 'open', PWideChar(FName), '', '', SW_SHOW); end; procedure TForm1.TM_GenChangeFunc(var SL: TStringList); var tmp_unit: PM_Unit; i: integer; begin SL.Add('void ChangeParam(int index){'); SL.Add(' // change parameter function prototype'); SL.Add(' switch(index){'); for i := 0 to TreeView1.Items.Count - 1 do begin tmp_unit := TreeView1.Items[i].Data; if tmp_unit.is_param then begin SL.Add(' case ' + IntToStr(i) + ': // ' + string(tmp_unit.name)); SL.Add(''); SL.Add(' break; // end of ' + string(tmp_unit.name)); end; end; SL.Add(' default:'); SL.Add(' break;'); SL.Add(' }'); SL.Add('}'); SL.Add(''); end; procedure TForm1.TM_GenExecFunc(var SL: TStringList); var tmp_unit: PM_Unit; i: integer; begin SL.Add('void ExecuteCmd(int index){'); SL.Add(' // Сommand execution function prototype'); SL.Add(' switch(index){'); for i := 0 to TreeView1.Items.Count - 1 do begin tmp_unit := TreeView1.Items[i].Data; if (not tmp_unit.is_param) and (TreeView1.Items[i].getFirstChild = nil) then begin SL.Add(' case ' + IntToStr(i) + ': // ' + string(tmp_unit.name)); SL.Add(''); SL.Add(' break; // end of ' + string(tmp_unit.name)); end; end; SL.Add(' default:'); SL.Add(' break;'); SL.Add(' }'); SL.Add('}'); end; procedure TForm1.TM_GenParamArray(var SL: TStringList); var tmp_unit: PM_Unit; i, X: integer; S: string; begin SL.Add('TM_Param params[TM_MENU_SIZE]={'); S := ' '; X := 0; for i := 0 to TreeView1.Items.Count - 1 do begin tmp_unit := TreeView1.Items[i].Data; inc(X); if X > 5 then begin SL.Add(S); S := ' '; X := 1; end; S := S + '{' + IntToStr(tmp_unit.value) + ', ' + IntToStr(tmp_unit.delta); if i < TreeView1.Items.Count - 1 then S := S + '},' else S := S + '}'; end; SL.Add(S); SL.Add('};'); SL.Add(''); end; procedure TForm1.TM_GenPrintFunc(var SL: TStringList); begin SL.Add('void PrintMenu(int index,TM_DeepLevel DeepLevel){'); SL.Add(' // printing function prototype'); SL.Add(' switch(DeepLevel){'); SL.Add(' case DL_NAME: // print name'); SL.Add(''); SL.Add(' break;'); SL.Add(' case DL_DELTA: // print param with cursor on symbol which will be change'); SL.Add(''); SL.Add(' break;'); SL.Add(' case DL_PARAM: // print param with cursor on symbol which changing'); SL.Add(''); SL.Add(' break;'); SL.Add(' }'); SL.Add('}'); SL.Add(''); end; procedure TForm1.TM_GenSpecFunc(var SL: TStringList); var tmp_unit: PM_Unit; i: integer; begin SL.Add('void SpecFunction(int index){'); SL.Add(' // special function prototype'); SL.Add(' switch(index){'); for i := 0 to TreeView1.Items.Count - 1 do begin tmp_unit := TreeView1.Items[i].Data; if TreeView1.Items[i].getFirstChild = nil then begin SL.Add(' case ' + IntToStr(i) + ': // ' + string(tmp_unit.name)); SL.Add(''); SL.Add(' break; // end of ' + string(tmp_unit.name)); end; end; SL.Add(' default:'); SL.Add(' break;'); SL.Add(' }'); SL.Add('}'); SL.Add(''); end; procedure TForm1.TM_GenTreeArray(var SL: TStringList); var S: string; i, j, parent_id, parent_count: integer; tmp_unit: PM_Unit; begin SL.Add('#define TM_MENU_SIZE ' + IntToStr(TreeView1.Items.Count)); SL.Add('const TM_Unit menu[TM_MENU_SIZE]={'); for i := 0 to TreeView1.Items.Count - 1 do begin tmp_unit := TreeView1.Items[i].Data; if TreeView1.Items[i].Parent <> nil then parent_id := TreeView1.Items[i].Parent.AbsoluteIndex else parent_id := -1; parent_count := GetParentCount(TreeView1.Items[i]); S := ''; for j := 1 to parent_count do S := S + ' '; S := S + ' {' + IntToStr(parent_id) + ', ' + LowerCase(BoolToStr(tmp_unit.is_param, true)) + ', "' + string(tmp_unit.name) + '", ' + IntToStr(tmp_unit.v_min) + ', ' + IntToStr(tmp_unit.v_max) + ', ' + IntToStr(tmp_unit.d_min) + ', ' + IntToStr(tmp_unit.d_max); if i < TreeView1.Items.Count - 1 then S := S + '},' else S := S + '}'; SL.Add(S); end; SL.Add('};'); SL.Add(''); end; procedure TForm1.TM_Load(FName: string); var i: integer; tmp_unit: PM_Unit; f: file of TM_Unit; begin TreeView1.LoadFromFile(FName); AssignFile(f, FName + '_'); Reset(f); for i := 0 to TreeView1.Items.Count - 1 do begin tmp_unit := new(PM_Unit); read(f, tmp_unit^); TreeView1.Items[i].Data := tmp_unit; end; CloseFile(f); global_counter := TreeView1.Items.Count; end; procedure TForm1.TM_Remove; begin if curNode <> nil then begin TreeView1.Items.Delete(curNode); has_global_changes := true; end; end; procedure TForm1.TM_Save(FName: string); var i: integer; tmp_unit: PM_Unit; u: TM_Unit; f: file of TM_Unit; begin TreeView1.SaveToFile(FName); AssignFile(f, FName + '_'); Rewrite(f); for i := 0 to TreeView1.Items.Count - 1 do begin tmp_unit := TreeView1.Items[i].Data; u := tmp_unit^; write(f, tmp_unit^); end; CloseFile(f); has_global_changes := false; end; procedure TForm1.Exit1Click(Sender: TObject); begin Form1.Close; end; procedure TForm1.Expandall1Click(Sender: TObject); begin TreeView1.FullExpand; end; procedure TForm1.About1Click(Sender: TObject); begin AboutBox.ShowModal; end; procedure TForm1.Addchild1Click(Sender: TObject); begin TM_AddChild; end; procedure TForm1.Addroot1Click(Sender: TObject); begin TM_AddRoot; end; procedure TForm1.Button1Click(Sender: TObject); begin TM_Apply; end; procedure TForm1.Collapseall1Click(Sender: TObject); begin TreeView1.FullCollapse; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin if has_global_changes then if MessageDlg('Want to save changes?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then if OpenDialog1.FileName <> '' then TM_Save(OpenDialog1.FileName) else if SaveDialog1.FileName <> '' then TM_Save(SaveDialog1.FileName) else if SaveDialog1.Execute then TM_Save(SaveDialog1.FileName) else Action := caNone; end; procedure TForm1.Generate1Click(Sender: TObject); begin TM_Generate('out.txt'); end; procedure TForm1.Open1Click(Sender: TObject); begin if OpenDialog1.Execute then begin TM_Load(OpenDialog1.FileName); Form1.Caption := Form1.Caption + ' - ' + OpenDialog1.FileName; // SaveDialog1.FileName:=OpenDialog1.FileName; end; end; procedure TForm1.Remove1Click(Sender: TObject); begin TM_Remove; end; procedure TForm1.Save1Click(Sender: TObject); begin if OpenDialog1.FileName <> '' then TM_Save(OpenDialog1.FileName) else if SaveDialog1.Execute then if not FileExists(SaveDialog1.FileName) then TM_Save(SaveDialog1.FileName) else if MessageDlg('File is exist. Rewrite?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then TM_Save(SaveDialog1.FileName); end; procedure TForm1.Saveas1Click(Sender: TObject); begin if SaveDialog1.Execute then if not FileExists(SaveDialog1.FileName) then TM_Save(SaveDialog1.FileName) else if MessageDlg('File is exist. Rewrite?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then TM_Save(SaveDialog1.FileName); end; procedure TForm1.TreeView1Change(Sender: TObject; Node: TTreeNode); var tmp_unit: PM_Unit; begin if (has_param_changes) and (curNode <> nil) then if MessageDlg('Want apply changes?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then TM_Apply else has_param_changes := false; curNode := Node; if Node <> nil then begin tmp_unit := Node.Data; ValueListEditor1.Values['Is parameter'] := BoolToStr(tmp_unit.is_param, true); ValueListEditor1.Values['Name'] := string(tmp_unit.name); ValueListEditor1.Values['Init value'] := IntToStr(tmp_unit.value); ValueListEditor1.Values['Min value'] := IntToStr(tmp_unit.v_min); ValueListEditor1.Values['Max value'] := IntToStr(tmp_unit.v_max); ValueListEditor1.Values['Init delta'] := IntToStr(tmp_unit.delta); ValueListEditor1.Values['Min delta'] := IntToStr(tmp_unit.d_min); ValueListEditor1.Values['Max delta'] := IntToStr(tmp_unit.d_max); end; end; procedure TForm1.TreeView1Deletion(Sender: TObject; Node: TTreeNode); var tmp_unit: PM_Unit; begin tmp_unit := Node.Data; dispose(tmp_unit); end; procedure TForm1.TreeView1DragDrop(Sender, Source: TObject; X, Y: integer); var AnItem: TTreeNode; AttachMode: TNodeAttachMode; HT: THitTests; begin AttachMode := naInsert; if TreeView1.Selected = nil then Exit; HT := TreeView1.GetHitTestInfoAt(X, Y); AnItem := TreeView1.GetNodeAt(X, Y); if (HT - [htOnItem, htOnIcon, htNowhere, htOnIndent, htOnRight] <> HT) then begin if (htOnItem in HT) or (htOnIcon in HT) then AttachMode := naAddChild else if htNowhere in HT then AttachMode := naAdd else if (htOnIndent in HT) or (htOnRight in HT) then AttachMode := naInsert; TreeView1.Selected.MoveTo(AnItem, AttachMode); if AttachMode = naAddChild then PM_Unit(AnItem.Data).is_param := false; has_global_changes := true; end; end; procedure TForm1.TreeView1DragOver(Sender, Source: TObject; X, Y: integer; State: TDragState; var Accept: boolean); begin Accept := Sender = Source; end; procedure TForm1.TreeView1Edited(Sender: TObject; Node: TTreeNode; var S: string); var tmp_unit: PM_Unit; begin tmp_unit := Node.Data; tmp_unit.name := ShortString(S); ValueListEditor1.Values['Name'] := string(tmp_unit.name); end; procedure TForm1.ValueListEditor1KeyPress(Sender: TObject; var Key: Char); begin if curNode <> nil then has_param_changes := true; if Key = #13 then TM_Apply; end; end.