/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> /// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param> /// <param name="progress">A provider for progress updates.</param> /// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns> protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { Dte = await GetServiceAsync(typeof(SDTE)) as DTE2; _serviceProvider = new ServiceProvider((IServiceProvider)Dte); var componentModel = (IComponentModel)GetGlobalService(typeof(SComponentModel)); _undoHistoryRegistry = componentModel.DefaultExportProvider.GetExportedValue <ITextUndoHistoryRegistry>(); var plugin = new VsRunningDocTableEventsHandler(this); MenuCommandService = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService; await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _runningDocumentTable = new RunningDocumentTable(this); _runningDocumentTable.Advise(plugin); OptionsPage = (OptionsPage)GetDialogPage(typeof(OptionsPage)); _solutionExplorerContextMenu = new SolutionExplorerContextMenu(this); await EnableDisableFormatOnSaveCommand.InitializeAsync(this); }
private bool FetchRunningDocumentTable() { var rdt = new RunningDocumentTable(_serviceProvider); foreach (var info in rdt) { // Get doc data if (!FullPath.IsValid(info.Moniker)) continue; var path = new FullPath(info.Moniker); if (_openDocuments.ContainsKey(path)) continue; // Get vs buffer IVsTextBuffer docData = null; try { docData = info.DocData as IVsTextBuffer; } catch (Exception e) { Logger.LogWarning(e, "Error getting IVsTextBuffer for document {0}, skipping document", path); } if (docData == null) continue; // Get ITextDocument var textBuffer = _vsEditorAdaptersFactoryService.GetDocumentBuffer(docData); if (textBuffer == null) continue; ITextDocument document; if (!_textDocumentFactoryService.TryGetTextDocument(textBuffer, out document)) continue; _openDocuments[path] = document; } return true; }
private void GetDocumentInfo(uint cookie, ref IVsProject project, ref uint item, ref string path) { string pbstrMkDocument = ""; IVsProject pProject = null; uint pitemid = 0; ThreadHelper.JoinableTaskFactory.Run(async() => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); uint pgrfRDTFlags; uint pdwReadLocks; uint pdwEditLocks; IVsHierarchy ppHier; IntPtr ppunkDocData; ErrorHandler.ThrowOnFailure(RunningDocumentTable.GetDocumentInfo( cookie, out pgrfRDTFlags, out pdwReadLocks, out pdwEditLocks, out pbstrMkDocument, out ppHier, out pitemid, out ppunkDocData)); pProject = ppHier as IVsProject; }); project = pProject; path = pbstrMkDocument; item = pitemid; }
private static T GetOpenedDocData <T>(Document document) where T : class { var rdt = new RunningDocumentTable(ServiceProvider.GlobalProvider); var documentInfo = rdt.FirstOrDefault(info => info.Moniker.Equals(document.FullName, StringComparison.OrdinalIgnoreCase)); return(documentInfo.DocData as T); }
internal DocumentMonitorService(SVsServiceProvider vsServiceProvider, ICompletionBroker completionBroker) { _vsServiceProvider = vsServiceProvider; _runningDocumentTable = new RunningDocumentTable(vsServiceProvider); _runningDocumentTable.Advise(this); _completionBroker = completionBroker; _dte = (DTE)vsServiceProvider.GetService(typeof(_DTE)); // NB: Resharper somehow f***s with this event, we need to do as // little as possible in the event handler itself var documentChanged = _changed .ObserveOn(RxApp.TaskpoolScheduler) .Throttle(TimeSpan.FromSeconds(2.0), RxApp.TaskpoolScheduler) .Where(_ => !isCompletionActive()) .Select(_ => Unit.Default) .ObserveOn(RxApp.MainThreadScheduler); documentChanged.Subscribe(_ => SaveAll()); // NB: We use the message bus here, because we want to effectively // merge all of the text change notifications from any document MessageBus.Current.RegisterMessageSource(documentChanged, "AnyDocumentChanged"); checkAlreadyOpenDocuments(vsServiceProvider); _dte.Events.WindowEvents.WindowActivated += (o, e) => _changed.OnNext(Unit.Default); }
///------------------------------------------------------------------------------------------------------------- /// <summary> /// Override of Dispose so we can free our lock after DocData. /// </summary> ///------------------------------------------------------------------------------------------------------------- protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (_cookie != 0 && _rdt != null) { // prevent recursion uint cookie = _cookie; _cookie = 0; try { // Unlock the document, specifying to save if this is the last lock and the buffer is dirty _rdt.UnlockDocument(_VSRDTFLAGS.RDT_EditLock | _VSRDTFLAGS.RDT_Unlock_SaveIfDirty, cookie); } finally { _cookie = 0; _rdt = null; } } _serviceProvider = null; } }
#pragma warning disable VSTHRD100 // Avoid async void methods - ok as an event handler private async void Execute(object sender, EventArgs e) #pragma warning restore VSTHRD100 // Avoid async void methods { System.Windows.Forms.Cursor previousCursor = System.Windows.Forms.Cursor.Current; System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; try { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); this.Logger?.RecordFeatureUsage(nameof(AnalyzeCurrentDocumentCommand)); var dte = await Instance.AsyncPackage.GetServiceAsync <DTE, DTE>(); var vs = new VisualStudioAbstraction(this.Logger, this.AsyncPackage, dte); var filePath = vs.GetActiveDocumentFilePath(); // Ensure that the open document has been saved so get latest version var rdt = new RunningDocumentTable(Package); rdt.SaveFileIfDirty(filePath); RapidXamlDocumentCache.Invalidate(filePath); RapidXamlDocumentCache.TryUpdate(filePath); } catch (Exception exc) { this.Logger?.RecordException(exc); } finally { System.Windows.Forms.Cursor.Current = previousCursor; } }
internal async Task <IServiceManager> CreateServicesAsync(string root, InterpreterConfiguration configuration = null) { configuration = configuration ?? PythonVersions.LatestAvailable; configuration.AssertInstalled(); Trace.TraceInformation("Cache Path: " + configuration.ModuleCachePath); configuration.ModuleCachePath = TestData.GetAstAnalysisCachePath(configuration.Version, true); configuration.SearchPaths = new[] { GetAnalysisTestDataFilesPath() }; configuration.TypeshedPath = TestData.GetDefaultTypeshedPath(); var sm = CreateServiceManager(); sm.AddService(new DiagnosticsService()); TestLogger.Log(TraceEventType.Information, "Create TestDependencyResolver"); var dependencyResolver = new TestDependencyResolver(); sm.AddService(dependencyResolver); TestLogger.Log(TraceEventType.Information, "Create PythonAnalyzer"); var analyzer = new PythonAnalyzer(sm); sm.AddService(analyzer); TestLogger.Log(TraceEventType.Information, "Create PythonInterpreter"); var interpreter = await PythonInterpreter.CreateAsync(configuration, root, sm); sm.AddService(interpreter); TestLogger.Log(TraceEventType.Information, "Create RunningDocumentTable"); var documentTable = new RunningDocumentTable(root, sm); sm.AddService(documentTable); return(sm); }
public TextDocumentTable( [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider, IFileSystem fileSystem, ITextDocumentFactoryService textDocumentFactoryService, IVsEditorAdaptersFactoryService vsEditorAdaptersFactoryService) { _fileSystem = fileSystem; _textDocumentFactoryService = textDocumentFactoryService; _vsEditorAdaptersFactoryService = vsEditorAdaptersFactoryService; _firstRun = new Lazy <bool>(FetchRunningDocumentTable); _runningDocumentTable = new RunningDocumentTable(serviceProvider); var vsDocTable = serviceProvider.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable4; if (vsDocTable != null) { var runningDocTableEvents = new VsRunningDocTableEvents(vsDocTable, vsEditorAdaptersFactoryService); runningDocTableEvents.DocumentOpened += RunningDocTableEventsOnDocumentOpened; runningDocTableEvents.DocumentClosed += RunningDocTableEventsOnDocumentClosed; runningDocTableEvents.DocumentRenamed += RunningDocTableEventsOnDocumentRenamed; _runningDocTableEventsCookie = _runningDocumentTable.Advise(runningDocTableEvents); } else { Logger.LogWarn("Error getting {0} from Service Provider", typeof(IVsRunningDocumentTable4).FullName); } }
/// <summary> /// Gets the designer from the specified file if it is open in its default editor. /// </summary> /// <param name="fileName">The physical path to the file to open.</param> public static T GetDesignerData <T>(string fileName) where T : class { var dte = ServiceProvider.GlobalProvider.GetService <SDTE, DTE>(); var rdt = new RunningDocumentTable(ServiceProvider.GlobalProvider); var documentInfo = rdt.FirstOrDefault(info => info.Moniker.Equals(fileName, StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrEmpty(documentInfo.Moniker)) { ActivateDocument(documentInfo.Moniker); var docData = documentInfo.DocData as T; if (docData == null) { // Close file is not opened in 'designer' view var projectItem = dte.Solution.FindProjectItem(documentInfo.Moniker); projectItem.Document.Close(vsSaveChanges.vsSaveChangesYes); // Open in designer mode (invisibly) docData = GetOpenedDocData <T>(OpenDesigner(fileName, false)); } return(docData); } return(null); }
protected VSCommonPackage() { if (_documentTable == null) { _documentTable = new RunningDocumentTable(ServiceProvider.GlobalProvider); } }
private async Task <Manifest> GetManifestAsync(string configFilePath, IDependencies dependencies) { RunningDocumentTable rdt = new RunningDocumentTable(ServiceProvider.GlobalProvider); IVsTextBuffer textBuffer = rdt.FindDocument(configFilePath) as IVsTextBuffer; ITextBuffer documentBuffer = null; Manifest manifest = null; if (textBuffer != null) { IComponentModel componentModel = ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel)) as IComponentModel; IVsEditorAdaptersFactoryService editorAdapterService = componentModel.GetService <IVsEditorAdaptersFactoryService>(); documentBuffer = editorAdapterService.GetDocumentBuffer(textBuffer); } // If the documentBuffer is null, then libman.json is not open. In that case, we'll use the manifest as is. // If documentBuffer is not null, then libman.json file is open and could be dirty. So we'll get the contents for the manifest from the buffer. if (documentBuffer != null) { manifest = Manifest.FromJson(documentBuffer.CurrentSnapshot.GetText(), dependencies); } else { manifest = await Manifest.FromFileAsync(configFilePath, dependencies, CancellationToken.None).ConfigureAwait(false); } return(manifest); }
/// <summary> /// The event explorer user control constructor. /// </summary> public VSEventHandler() { // Advise the RDT of this event sink. DTEObj = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2; ServiceProvider sp = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)DTEObj); //IOleServiceProvider sp = // Package.GetGlobalService(typeof(IOleServiceProvider)) as IOleServiceProvider; if (sp == null) { return; } rdt = new RunningDocumentTable(sp); if (rdt == null) { return; } rdtCookie = rdt.Advise(this); DTEObj.Events.BuildEvents.OnBuildDone += new _dispBuildEvents_OnBuildDoneEventHandler(BuildEvents_OnBuildDone); DTEObj.Events.SolutionEvents.Opened += new _dispSolutionEvents_OpenedEventHandler(SolutionEvents_Opened); }
int IVsRunningDocTableEvents.OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame) { RunningDocumentTable rdt = new RunningDocumentTable(this); RunningDocumentInfo doc = rdt.GetDocumentInfo(docCookie); return(0); }
public bool PromptSaveDocument(string path) { ThreadHelper.ThrowIfNotOnUIThread(); if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } SccDocumentData data; if (!_docMap.TryGetValue(path, out data)) { return(false); } data.CheckDirty(_poller); if (!data.IsDirty || (data.Cookie == 0)) { return(true); // Not/never modified, no need to save } // Save the document if it is dirty return(VSErr.Succeeded(RunningDocumentTable.SaveDocuments((uint)__VSRDTSAVEOPTIONS.RDTSAVEOPT_PromptSave, data.Hierarchy, data.ItemId, data.Cookie))); }
public static void SaveFile(this ITextView textView) { RunningDocumentTable rdt = new RunningDocumentTable(RPackage.Current); string filePath = textView.TextBuffer.GetFilePath(); rdt.SaveFileIfDirty(filePath); }
internal void OnCloseFrame(FrameWrapper closingFrame) { if (_mapFrameToUri.ContainsKey(closingFrame)) { _mapFrameToUri.Remove(closingFrame); if (null != closingFrame.Uri) { var rdt = new RunningDocumentTable(_package); var doc = rdt.FindDocument(closingFrame.Uri.LocalPath); if (doc != null) { var isModified = false; using (var docData = new DocData(doc)) { isModified = docData.Modified; } if (isModified) { // document was modified but was closed without saving changes; // we need to refresh all sets that refer to the document // so that they revert to the document that is persisted in the file system // TODO: add this functinality //ModelManager.RefreshModelForLocation(closingFrame.Uri); } } } } }
public FormatDocumentOnBeforeSave(DTE dte, RunningDocumentTable runningDocumentTable, IVsTextManager txtMngr, SettingsPage settingsPage) { _runningDocumentTable = runningDocumentTable; _txtMngr = txtMngr; _dte = dte; _settingsPage = settingsPage; }
internal DocumentMonitorService(SVsServiceProvider vsServiceProvider, ICompletionBroker completionBroker) { _vsServiceProvider = vsServiceProvider; _runningDocumentTable = new RunningDocumentTable(vsServiceProvider); _runningDocumentTable.Advise(this); _completionBroker = completionBroker; _dte = (DTE)vsServiceProvider.GetService(typeof(_DTE)); // NB: Resharper somehow f***s with this event, we need to do as // little as possible in the event handler itself var documentChanged = _changed .ObserveOn(RxApp.TaskpoolScheduler) .Throttle(TimeSpan.FromSeconds(2.0), RxApp.TaskpoolScheduler) .Where(_ => !isCompletionActive()) .Select(_ => Unit.Default) .ObserveOn(RxApp.MainThreadScheduler); documentChanged.Subscribe(_ => SaveAll()); // NB: We use the message bus here, because we want to effectively // merge all of the text change notifications from any document MessageBus.Current.RegisterMessageSource(documentChanged, "AnyDocumentChanged"); checkAlreadyOpenDocuments(vsServiceProvider); _dte.Events.WindowEvents.WindowActivated += (o,e) => _changed.OnNext(Unit.Default); }
private EnvDTE.ProjectItem GetProjectItemFromDocumentCookie(uint cookie) { uint pgrfRDTFlags; uint pdwReadLocks; uint pdwEditLocks; string pbstrMkDocument; IVsHierarchy ppHier; uint pitemid; IntPtr ppunkDocData; try { if (RunningDocumentTable.GetDocumentInfo( cookie, out pgrfRDTFlags, out pdwReadLocks, out pdwEditLocks, out pbstrMkDocument, out ppHier, out pitemid, out ppunkDocData) == VSConstants.S_OK) { return(DTEUtil.GetProjectItem(ppHier, pitemid)); } } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); throw; } return(null); }
/// <summary> /// Initialization of the package; this method is called right after /// the package is sited, so this is the place where you can put all /// the initialization code that rely on services provided by /// VisualStudio. /// </summary> /// <param name="cancellationToken"></param> /// <param name="progress"></param> /// <returns></returns> protected override async System.Threading.Tasks.Task InitializeAsync( CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Make initial progress report. progress.Report(new ServiceProgressData( waitMessage: "Initializing", progressText: "Initializing", currentStep: 1, totalSteps: 4)); var serviceContainer = this as IServiceContainer; await base.InitializeAsync(cancellationToken, progress); // Check if cancelled. if (cancellationToken.IsCancellationRequested) { return; } // Make progress report. progress.Report(new ServiceProgressData( waitMessage: "Registering services", progressText: "Initializing", currentStep: 2, totalSteps: 4)); AddService(typeof(SNopyCopyService), CreateServiceNopyCopyServiceAsync); // Check if cancelled. if (cancellationToken.IsCancellationRequested) { return; } // Make progress report. progress.Report(new ServiceProgressData( waitMessage: "Retrieving services", progressText: "Retrieving NopyCopyService", currentStep: 3, totalSteps: 4)); nopyCopyService = await GetServiceAsync(typeof(SNopyCopyService)) as NopyCopyService; Assumes.Present(nopyCopyService); var runningDocumentTable = new RunningDocumentTable(this); // Make progress report. progress.Report(new ServiceProgressData( waitMessage: "Finished", progressText: "Completed", currentStep: 4, totalSteps: 4)); return; }
public TextFormatterRunningDocumentTableEvents(DTE dte, RunningDocumentTable runningDocumentTable, IReadOnlyDictionary <string, ITextFormatter> textFormatters) { _dte = dte; _runningDocumentTable = runningDocumentTable; _textFormatters = textFormatters; }
public EventEx(RunningDocumentTable rdt, string message, uint cookie, IVsHierarchy oldHierarchy, uint itemidOld, string pszMkDocumentOld) : base(rdt, message, cookie) { this.OldHierarchy = oldHierarchy; this.itemidOld = itemidOld; this.pszMkDocumentOld = pszMkDocumentOld; }
private async Task SetUpRunningDocumentTableEventsAsync(CancellationToken cancellationToken) { await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var runningDocumentTable = new RunningDocumentTable(this); runningDocumentTable.Advise(MyRunningDocTableEvents.Instance); }
public void EndTrack() { ThreadHelper.JoinableTaskFactory.Run(async() => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); RunningDocumentTable.UnadviseRunningDocTableEvents(_cookie); }); }
/// <summary> /// Base class for all other RDT event wrappers. Each event wrapper /// stores event-specific information and formats it for display /// in the Properties window. /// </summary> /// <param name="rdt">Running Document Table instance</param> /// <param name="message">Message to be displayed in the grid</param> /// <param name="cookie">Cookie to unadvise RDT events</param> public GenericEvent(RunningDocumentTable rdt, string message, uint cookie) { this.message = message; if (rdt == null || cookie == 0) return; rdi = rdt.GetDocumentInfo(cookie); docNameShort = GetShortDocName(rdi.Moniker); }
public void SaveDocuments(DocumentSaveType type) { ThreadHelper.ThrowIfNotOnUIThread(); var dte = _serviceProvider.GetService(typeof(DTE)) as DTE; Assumes.Present(dte); switch (type) { case DocumentSaveType.ActiveDocument: if (dte.ActiveDocument?.Saved == false) { dte.ActiveDocument.Save(); } break; case DocumentSaveType.OpenDocuments: var documentTable = new RunningDocumentTable(_serviceProvider); var vsDocumentTable = _serviceProvider.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable; Assumes.Present(vsDocumentTable); foreach (var document in documentTable) { // save only files in the tabs if ((document.Flags & (uint)(_VSRDTFLAGS.RDT_VirtualDocument | _VSRDTFLAGS.RDT_CantSave)) == 0) { vsDocumentTable.SaveDocuments( (uint)__VSRDTSAVEOPTIONS.RDTSAVEOPT_SaveIfDirty, document.Hierarchy, document.ItemId, document.DocCookie); } } break; case DocumentSaveType.ProjectDocuments: if (dte.ActiveSolutionProjects is Array activeSolutionProjects && activeSolutionProjects.Length > 0) { if (activeSolutionProjects.GetValue(0) is EnvDTE.Project activeProject) { foreach (ProjectItem item in activeProject.ProjectItems) { SaveDocumentsRecursively(item); } } } break; case DocumentSaveType.SolutionDocuments: foreach (EnvDTE.Project project in dte.Solution.Projects) { foreach (ProjectItem item in project.ProjectItems) { SaveDocumentsRecursively(item); } } break; } }
private void ConnectRunningDocumentTable() { ThreadHelper.ThrowIfNotOnUIThread(); if (_runningDocTableEventCookie == 0) { RunningDocumentTable?.AdviseRunningDocTableEvents(this, out _runningDocTableEventCookie); } }
internal TextManager( IVsAdapter adapter, SVsServiceProvider serviceProvider) { _adapter = adapter; _serviceProvider = serviceProvider; _textManager = _serviceProvider.GetService <SVsTextManager, IVsTextManager>(); _table = new RunningDocumentTable(_serviceProvider); }
/// <summary> /// Initializes a new instance of the <see cref="RunningDocumentTableEventListener"/> class. /// </summary> /// <param name="package">The package hosting the event listener.</param> internal RunningDocumentTableEventListener(EditorConfigPackage package) : base(package) { // Create and store a reference to the running document table. RunningDocumentTable = new RunningDocumentTable(package); // Register with the running document table for events. EventCookie = RunningDocumentTable.Advise(this); }
///------------------------------------------------------------------------------------------------------------- /// <summary> /// Constructor. Aquires edit lock on document. /// </summary> ///------------------------------------------------------------------------------------------------------------- public LockedDocData(IServiceProvider serviceProvider, string fileName) : base(serviceProvider, fileName) { _serviceProvider = serviceProvider; _rdt = new RunningDocumentTable(serviceProvider); // Locate and lock the document _rdt.FindDocument(fileName, out _cookie); _rdt.LockDocument(_VSRDTFLAGS.RDT_EditLock, _cookie); }
///------------------------------------------------------------------------------------------------------------- /// <summary> /// Constructor. Aquires edit lock on document. /// </summary> ///------------------------------------------------------------------------------------------------------------- public LockedDocData(IServiceProvider serviceProvider, string fileName) : base(serviceProvider, fileName) { _serviceProvider = serviceProvider; _rdt = new RunningDocumentTable(serviceProvider); // Locate and lock the document _rdt.FindDocument(fileName, out _cookie); _rdt.LockDocument(_VSRDTFLAGS.RDT_EditLock , _cookie); }
internal TextManager( IVsAdapter adapter, SVsServiceProvider serviceProvider) { _adapter = adapter; _serviceProvider = serviceProvider; _textManager = _serviceProvider.GetService<SVsTextManager, IVsTextManager>(); _table = new RunningDocumentTable(_serviceProvider); }
/// <summary> /// Initializes a new instance of the <see cref="RunningDocumentTableEventListener" /> class. /// </summary> /// <param name="package">The package hosting the event listener.</param> internal RunningDocumentTableEventListener(CodeMaidPackage package) : base(package) { // Create and store a reference to the running document table. RunningDocumentTable = new RunningDocumentTable(package); // Register with the running document table for events. EventCookie = RunningDocumentTable.Advise(this); }
private async Task SetUpRunningDocumentTableEventsAsync(CancellationToken cancellationToken) { await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var runningDocumentTable = new RunningDocumentTable(this); var plugin = new RapidXamlRunningDocTableEvents(this, runningDocumentTable); runningDocumentTable.Advise(plugin); }
public RunningDocTableEvents(IServiceProvider serviceProvider, Action <uint> OnAfterSave = null, Action OnAfterSaveAll = null) { rdt = new RunningDocumentTable(serviceProvider); cookie = rdt.Advise(this); OnAfterSaveFn = OnAfterSave; OnAfterSaveAllFn = OnAfterSaveAll; }
/// <summary> /// Initializes a new instance of the <see cref="RunningDocumentTableEventListener"/> class. /// </summary> /// <param name="package">The package hosting the event listener.</param> internal RunningDocumentTableEventListener(EditorConfigPackage package) : base(package) { _editorAdaptersFactory = Package.ComponentModel.GetService<IVsEditorAdaptersFactoryService>(); // Create and store a reference to the running document table. RunningDocumentTable = new RunningDocumentTable(package); // Register with the running document table for events. EventCookie = RunningDocumentTable.Advise(this); }
public static IVsHierarchy GetVsHierarchy(string filePath, IServiceProvider serviceProvider) { IVsHierarchy hier = null; var rdt = new RunningDocumentTable(serviceProvider); uint itemId = 0; uint docCookie = 0; rdt.FindDocument(filePath, out hier, out itemId, out docCookie); return hier; }
internal VsAdapter( IVsEditorAdaptersFactoryService editorAdaptersFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, SVsServiceProvider serviceProvider) { _editorAdaptersFactoryService = editorAdaptersFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; _serviceProvider = serviceProvider; _textManager = _serviceProvider.GetService<SVsTextManager, IVsTextManager>(); _table = new RunningDocumentTable(_serviceProvider); _uiShell = _serviceProvider.GetService<SVsUIShell, IVsUIShell>(); }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { var dte = (DTE)GetService(typeof(DTE)); var txtMgr = (IVsTextManager)GetService(typeof(SVsTextManager)); var runningDocumentTable = new RunningDocumentTable(this); var documentFormatter = new DocumentFormatter(txtMgr, dte); plugin = new FormatDocumentOnBeforeSave(dte, runningDocumentTable, documentFormatter); runningDocumentTable.Advise(plugin); base.Initialize(); }
internal TextManager( IVsAdapter adapter, ITextDocumentFactoryService textDocumentFactoryService, ITextBufferFactoryService textBufferFactoryService, SVsServiceProvider serviceProvider) { _vsAdapter = adapter; _serviceProvider = serviceProvider; _textManager = _serviceProvider.GetService<SVsTextManager, IVsTextManager>(); _textDocumentFactoryService = textDocumentFactoryService; _textBufferFactoryService = textBufferFactoryService; _table = new RunningDocumentTable(_serviceProvider); }
internal VsAdapter( IVsEditorAdaptersFactoryService editorAdaptersFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, IIncrementalSearchFactoryService incrementalSearchFactoryService, SVsServiceProvider serviceProvider) { _incrementalSearchFactoryService = incrementalSearchFactoryService; _editorAdaptersFactoryService = editorAdaptersFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; _serviceProvider = serviceProvider; _textManager = _serviceProvider.GetService<SVsTextManager, IVsTextManager>(); _table = new RunningDocumentTable(_serviceProvider); _uiShell = _serviceProvider.GetService<SVsUIShell, IVsUIShell>(); _monitorSelection = _serviceProvider.GetService<SVsShellMonitorSelection, IVsMonitorSelection>(); }
public int OnAfterAttributeChangeEx( uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew) { // We only need to worry about linked undo for artifacts that are not cached code gen models, since code gen artifacts don't exist // when the designer is open if (!IsCodeGenArtifact) { // First check to see if this is our document and it's being reloaded if (!_disabledBufferUndo && (grfAttribs & (uint)__VSRDTATTRIB.RDTA_DocDataReloaded) == (uint)__VSRDTATTRIB.RDTA_DocDataReloaded) { var rdt = new RunningDocumentTable(Services.ServiceProvider); var rdi = rdt.GetDocumentInfo(docCookie); if (rdi.Moniker.Equals(Uri.LocalPath, StringComparison.OrdinalIgnoreCase)) { // DocData is XmlModelDocData var textBufferProvider = rdi.DocData as IVsTextBufferProvider; Debug.Assert( textBufferProvider != null, "The XML Model DocData over the diagram file is not IVsTextBufferProvider. Linked undo may not work correctly"); if (textBufferProvider != null) { IVsTextLines textLines; var hr = textBufferProvider.GetTextBuffer(out textLines); Debug.Assert( textLines != null, "The IVsTextLines could not be found from the IVsTextBufferProvider. Linked undo may not work correctly"); if (NativeMethods.Succeeded(hr) && textLines != null) { IOleUndoManager bufferUndoMgr; hr = textLines.GetUndoManager(out bufferUndoMgr); Debug.Assert( bufferUndoMgr != null, "Couldn't find the buffer undo manager. Linked undo may not work correctly"); if (NativeMethods.Succeeded(hr) && bufferUndoMgr != null) { bufferUndoMgr.Enable(0); _disabledBufferUndo = true; } } } } } } return VSConstants.S_OK; }
internal VsAdapter( IVsEditorAdaptersFactoryService editorAdaptersFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, IIncrementalSearchFactoryService incrementalSearchFactoryService, IPowerToolsUtil powerToolsUtil, SVsServiceProvider vsServiceProvider) { _incrementalSearchFactoryService = incrementalSearchFactoryService; _editorAdaptersFactoryService = editorAdaptersFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; _serviceProvider = vsServiceProvider; _textManager = _serviceProvider.GetService<SVsTextManager, IVsTextManager>(); _table = new RunningDocumentTable(_serviceProvider); _uiShell = _serviceProvider.GetService<SVsUIShell, IVsUIShell>(); _monitorSelection = _serviceProvider.GetService<SVsShellMonitorSelection, IVsMonitorSelection>(); _powerToolsUtil = powerToolsUtil; _visualStudioVersion = vsServiceProvider.GetVisualStudioVersion(); }
private void Excute(object sender, EventArgs e) { lstExcludeEndsWith = dte.GetValue("ExcludeEndsWith"); count = 0; selectedMenu = (PkgCmdIDList)((MenuCommand)sender).CommandID.ID; var table = new RunningDocumentTable(this); lstAlreadyOpenFiles = (from info in table select info.Moniker).ToList<string>(); var selectedItem = dte.SelectedItems.Item(1); WriteLog("\r\n===================================================================================="); WriteLog("Start :" + DateTime.Now.ToString()); Stopwatch sp = new Stopwatch(); sp.Start(); if (selectedItem.Project == null && selectedItem.ProjectItem == null) { ProcessSolution(); } else if (selectedItem.Project != null) { ProcessProject(selectedItem.Project); } else if (selectedItem.ProjectItem != null) { if (selectedItem.ProjectItem.ProjectItems.Count > 0) { ProcessProjectItem(selectedItem.ProjectItem); ProcessProjectItems(selectedItem.ProjectItem.ProjectItems); } else { ProcessProjectItem(selectedItem.ProjectItem); } } sp.Stop(); WriteLog(string.Format("Finish:{0} Times:{1}s Files:{2}", DateTime.Now.ToString(), sp.ElapsedMilliseconds / 1000, count - 2)); dte.ExecuteCommand("View.Output"); myOutPane.Activate(); }
private void Excute(object sender, EventArgs e) { _lstExcludePath = _dte.GetValue("ExcludePath"); _count = 0; _selectedMenu = (PkgCmdIdList)((MenuCommand)sender).CommandID.ID; var table = new RunningDocumentTable(this); _lstAlreadyOpenFiles = (from info in table select info.Moniker).ToList(); var selectedItem = _dte.SelectedItems.Item(1); WriteLog($"{Environment.NewLine}===================================================================================="); WriteLog($"Start: {DateTime.Now}"); Stopwatch sp = new Stopwatch(); sp.Start(); if (selectedItem.Project == null && selectedItem.ProjectItem == null) { ProcessSolution(); } else if (selectedItem.Project != null) { ProcessProject(selectedItem.Project); } else if (selectedItem.ProjectItem != null) { if (selectedItem.ProjectItem.ProjectItems.Count > 0) { ProcessProjectItem(selectedItem.ProjectItem); ProcessProjectItems(selectedItem.ProjectItem.ProjectItems); } else { ProcessProjectItem(selectedItem.ProjectItem); } } sp.Stop(); WriteLog($"Finish: {DateTime.Now} Times: {sp.ElapsedMilliseconds / 1000}s Files: {_count - 2}"); _dte.ExecuteCommand("View.Output"); _myOutPane.Activate(); }
internal DocumentMonitorService(SVsServiceProvider vsServiceProvider, ICompletionBroker completionBroker) { _runningDocumentTable = new RunningDocumentTable(vsServiceProvider); _runningDocumentTable.Advise(this); _completionBroker = completionBroker; _dte = (DTE)vsServiceProvider.GetService(typeof(_DTE)); var documentChanged = Observable.FromEventPattern(x => _changed += x, x => _changed -= x) .Throttle(TimeSpan.FromSeconds(2.0), RxApp.MainThreadScheduler) .Where(_ => !IsCompletionActive()) .Select(_ => Unit.Default); var dispatcher = Dispatcher.CurrentDispatcher; documentChanged.Subscribe(_ => dispatcher.BeginInvoke(new Action(() => SaveAll()))); // NB: We use the message bus here, because we want to effectively // merge all of the text change notifications from any document MessageBus.Current.RegisterMessageSource(documentChanged, "AnyDocumentChanged"); CheckAlreadyOpenDocuments(vsServiceProvider); }
public LockEvent(RunningDocumentTable rdt, string message, uint cookie, uint dwRDTLockType) : base(rdt, message, cookie) { this.dwRDTLockType = dwRDTLockType; }
public ShowEvent(RunningDocumentTable rdt, string message, uint cookie, int fFirstShow, IVsWindowFrame pFrame) : base(rdt, message, cookie) { this.fFirstShow = fFirstShow; this.pFrame = pFrame; }
public WindowFrameEvent(RunningDocumentTable rdt, string message, uint cookie, IVsWindowFrame pFrame) : base(rdt, message, cookie) { this.pFrame = pFrame; }
public FormatDocumentOnBeforeSave(DTE dte, RunningDocumentTable runningDocumentTable, DocumentFormatter documentFormatter) { _runningDocumentTable = runningDocumentTable; _documentFormatter = documentFormatter; _dte = dte; }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); dte = GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; _props = dte.get_Properties("Remove Trailing Whitespaces", "Options"); rdt = new RunningDocumentTable(this); rdt.Advise(new RunningDocTableEvents(this)); var mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs != null) { // Create the command for the menu item. CommandID menuCommandID = new CommandID( GuidList.guidRemoveTrailingWhitespacesCmdSet, (int)PkgCmdIDList.cmdIdRemoveTrailingWhitespaces); OleMenuCommand menuItem = new OleMenuCommand(onRemoveTrailingWhitespacesPressed, menuCommandID); menuItem.BeforeQueryStatus += onBeforeQueryStatus; mcs.AddCommand(menuItem); } }
public DocumentEventListener(IServiceProvider package) { _table = new RunningDocumentTable(package); _cookie = _table.Advise(this); }
/// <summary> /// The event explorer user control constructor. /// </summary> public RdtEventControl() { InitializeComponent(); // Create a selection container for tracking selected RDT events. selectionContainer = new MsVsShell.SelectionContainer(); // Advise the RDT of this event sink. IOleServiceProvider sp = Package.GetGlobalService(typeof(IOleServiceProvider)) as IOleServiceProvider; if (sp == null) return; rdt = new RunningDocumentTable(new ServiceProvider(sp)); if (rdt == null) return; rdtCookie = rdt.Advise(this); // Obtain the single instance of the options via automation. try { DTE dte = (DTE)Package.GetGlobalService(typeof(DTE)); EnvDTE.Properties props = dte.get_Properties("RDT Event Explorer", "Explorer Options"); IOptions o = props.Item("ContainedOptions").Object as IOptions; options = (Options)o; } catch { IVsActivityLog log = Package.GetGlobalService( typeof(SVsActivityLog)) as IVsActivityLog; if (log != null) { log.LogEntry( (UInt32)__ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION, this.ToString(), string.Format(CultureInfo.CurrentCulture, "RdtEventExplorer could not obtain properties via automation: {0}", this.ToString()) ); } options = new Options(); } // Prepare the event grid. eventGrid.AutoGenerateColumns = false; eventGrid.AllowUserToAddRows = false; eventGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect; eventGrid.Columns.Add("Event", Resources.EventHeader); eventGrid.Columns.Add("Moniker", Resources.MonikerHeader); eventGrid.Columns["Event"].ReadOnly = true; eventGrid.Columns["Moniker"].ReadOnly = true; eventGrid.AllowUserToResizeRows = false; eventGrid.AllowUserToResizeColumns = true; eventGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; int x = Screen.PrimaryScreen.Bounds.Size.Width; int y = Screen.PrimaryScreen.Bounds.Size.Height; Size = new Size(x / 3, y / 3); }
public void ReportTasks(ArrayList errors) { TaskProvider taskProvider = this.GetTaskProvider(); TaskReporter tr = this.GetTaskReporter(); if (null == taskProvider || null == tr) { Debug.Assert(false, "null task provider or task reporter - exiting ReportTasks"); return; } string fname = this.GetFilePath(); // Clear out this file's tasks tr.ClearBackgroundTasksForFile(fname); int errorMax = this.service.Preferences.MaxErrorMessages; RunningDocumentTable rdt = new RunningDocumentTable(this.service.Site); IVsHierarchy thisHeirarchy = rdt.GetHierarchyItem(fname); // Here we merge errors lists to reduce flicker. It is not a very intelligent merge // but that is ok, the worst case is the task list flickers a bit. But 99% of the time // one error is added or removed as the user is typing, and this merge will reduce flicker // in this case. errors = GroupBySeverity(errors); taskProvider.SuspendRefresh(); // batch updates. TaskErrorCategory mostSevere = TaskErrorCategory.Message; for (int i = 0, n = errors.Count; i < n; i++) { ErrorNode enode = (ErrorNode)errors[i]; string filename = enode.uri; string subcategory = enode.subcategory; bool thisFile = (!string.IsNullOrEmpty(filename) && NativeMethods.IsSamePath(fname, filename)); TextSpan span = enode.context; Severity severity = enode.severity; string message = enode.message; if (message == null) continue; message = NormalizeErrorString(message); //normalize text span if (thisFile) { FixupMarkerSpan(ref span); } else { TextSpanHelper.MakePositive(ref span); } //set options TaskPriority priority = TaskPriority.Normal; TaskCategory category = TaskCategory.BuildCompile; MARKERTYPE markerType = MARKERTYPE.MARKER_CODESENSE_ERROR; TaskErrorCategory errorCategory = TaskErrorCategory.Warning; if (severity == Severity.Fatal || severity == Severity.Error) { priority = TaskPriority.High; errorCategory = TaskErrorCategory.Error; } else if (severity == Severity.Hint) { category = TaskCategory.Comments; markerType = MARKERTYPE.MARKER_INVISIBLE; errorCategory = TaskErrorCategory.Message; } else if (severity == Severity.Warning) { markerType = MARKERTYPE.MARKER_COMPILE_ERROR; errorCategory = TaskErrorCategory.Warning; } if (errorCategory < mostSevere) { mostSevere = errorCategory; } IVsHierarchy hierarchy = thisHeirarchy; if (!thisFile) { // must be an error reference to another file. hierarchy = rdt.GetHierarchyItem(filename); markerType = MARKERTYPE.MARKER_OTHER_ERROR; // indicate to CreateErrorTaskItem } DocumentTask docTask = this.CreateErrorTaskItem(span, filename, subcategory, message, priority, category, markerType, errorCategory); docTask.HierarchyItem = hierarchy; tr.AddTask(docTask); } tr.OutputTaskList(); taskProvider.ResumeRefresh(); // batch updates. }
protected override void OnBeforeHandleXmlModelTransactionCompleted(object sender, XmlTransactionEventArgs args) { base.OnBeforeHandleXmlModelTransactionCompleted(sender, args); #if DEBUG var rDT = new RunningDocumentTable(PackageManager.Package); uint cookie = 0; rDT.FindDocument(Uri.LocalPath, out cookie); var info = rDT.GetDocumentInfo(cookie); Debug.Print( string.Format( CultureInfo.CurrentCulture, "There are now {0} Edit Locks, and {1} Read Locks.", info.EditLocks, info.ReadLocks)); #endif }
/// <summary> /// Get the ORMTestWindow structure for the given ORM file /// </summary> /// <param name="ormHooks">An ORMTestHooks instance</param> /// <param name="fullName">The full name of the file. Retrieve from a Document.FullName property. /// If fullName is null or empty then the path of the active document is used.</param> /// <returns>ORMTestWindow structure. May be empty.</returns> public static ORMTestWindow FindORMTestWindow(ORMTestHooks ormHooks, string fullName) { if (fullName == null || fullName.Length == 0) { fullName = ormHooks.DTE.ActiveDocument.FullName; } RunningDocumentTable docTable = new RunningDocumentTable(ormHooks.ServiceProvider); ORMDesignerDocData document = docTable.FindDocument(fullName) as ORMDesignerDocData; if (document != null) { ORMDesignerDocView docView = (ORMDesignerDocView)document.DocViews[0]; return new ORMTestWindow(docView.CurrentDesigner.DiagramClientView, ormHooks); } return Empty; }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { var dte = (DTE)GetService(typeof(DTE)); var runningDocumentTable = new RunningDocumentTable(this); var documentFormatService = new DocumentFormatService(dte, () => (ExtensionsCfg)GetDialogPage(typeof(ExtensionsCfg))); plugin = new FormatDocumentOnBeforeSave(dte, runningDocumentTable, documentFormatService); runningDocumentTable.Advise(plugin); base.Initialize(); }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); // Add our command handlers for menu (commands must exist in the .vsct file) OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (null != mcs) { // Create the Refresh Command and its handler CommandID refreshCommandID = new CommandID(GuidList.guidVSPackageGDBACmdSet, (int)PkgCmdIDList.cmdidRefreshContextMenu); MenuCommand menuRefresh = new MenuCommand(RefreshCommandCallBack, refreshCommandID); mcs.AddCommand(menuRefresh); // Create the command for the tool window for the RDT Event List CommandID toolwndCommandID = new CommandID(GuidList.guidRdtEventExplorerCmdSet, (int)PkgCmdIDList.cmdidMyTool); MenuCommand menuToolWin = new MenuCommand(new EventHandler(ShowToolWindow), toolwndCommandID); mcs.AddCommand(menuToolWin); } //Alternative method //uint dwCookie = 0; //IVsRunningDocumentTable rdt2 = (IVsRunningDocumentTable)Package.GetGlobalService(typeof(SVsRunningDocumentTable)); //rdt2.AdviseRunningDocTableEvents(this, out dwCookie); // Create a selection container for tracking selected RDT events. selectionContainer = new Microsoft.VisualStudio.Shell.SelectionContainer(); // Advise the RDT of this event sink. Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp = Package.GetGlobalService(typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider)) as Microsoft.VisualStudio.OLE.Interop.IServiceProvider; if (sp == null) return; rdt = new RunningDocumentTable(new ServiceProvider(sp)); if (rdt == null) return; rdtCookie = rdt.Advise(this); }