Exemplo n.º 1
0
            private void DocumentEvents_DocumentClosing(EnvDTE.Document document)
            {
                if (!ThreadHelper.CheckAccess() || document == null || _codeMapViewModel.Document == null)
                {
                    return;
                }

                string documentPath, documentKind, documentLanguage;

                try
                {
                    //Sometimes COM interop exceptions popup from getter, so we need to query properties safely
                    documentPath     = document.FullName;
                    documentKind     = document.Kind;
                    documentLanguage = document.Language;
                }
                catch
                {
                    return;
                }

                const string emptyObjectKind = "{00000000-0000-0000-0000-000000000000}";

                if (documentKind == null || documentKind == emptyObjectKind || documentLanguage != Constants.CSharp.LegacyLanguageName ||
                    !string.Equals(documentPath, _codeMapViewModel.Document.FilePath, StringComparison.OrdinalIgnoreCase))
                {
                    return;
                }

                // Handle the case when active document is closed while Code Map tool window is opened and not pinned.
                // In this case VS is not firing WindowActivated event. Therefore we clear Code Map in DocumentClosing DTE event
                _codeMapViewModel.ClearCodeMap();
                _codeMapViewModel.DocumentModel = null;
            }
Exemplo n.º 2
0
        /// <summary>
        /// This method should be on the UI thread. The overrides should ensure that
        /// Sets NuGetPackageImportStamp to a new random guid. This is a hack to let the project system know it is out
        /// of date.
        /// The value does not matter, it just needs to change.
        /// </summary>
        protected static void UpdateImportStamp(EnvDTEProject envDTEProject)
        {
            Debug.Assert(ThreadHelper.CheckAccess());

            IVsBuildPropertyStorage propStore = VsHierarchyUtility.ToVsHierarchy(envDTEProject) as IVsBuildPropertyStorage;

            if (propStore != null)
            {
                // <NuGetPackageImportStamp>af617720</NuGetPackageImportStamp>
                string stamp = Guid.NewGuid().ToString().Split('-')[0];
                try
                {
                    propStore.SetPropertyValue(NuGetImportStamp, string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE, stamp);
                }
                catch (Exception ex1)
                {
                    ExceptionHelper.WriteToActivityLog(ex1);
                }

                // Remove the NuGetImportStamp so that VC++ project file won't be updated with this stamp on disk,
                // which causes unnecessary source control pending changes.
                try
                {
                    propStore.RemoveProperty(NuGetImportStamp, string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE);
                }
                catch (Exception ex2)
                {
                    ExceptionHelper.WriteToActivityLog(ex2);
                }
            }
        }
Exemplo n.º 3
0
            public async Task SizeToFitAsync()
            {
                // The following work must always happen on UI thread.
                                #pragma warning disable VSTHRD109 // Switch instead of assert in async methods
                ThreadHelper.ThrowIfNotOnUIThread();

                // We won't know how many lines there will be in the inline diff or how
                // wide the widest line in the inline diff will be until the inline diff
                // snapshot has been computed. We register an event handler here that will
                // allow us to calculate the required width and height once the inline diff
                // snapshot has been computed.
                _diffViewer.DifferenceBuffer.SnapshotDifferenceChanged += SnapshotDifferenceChanged;

                // The inline diff snapshot may already have been computed before we registered the
                // above event handler. In this case, we can go ahead and calculate the required width
                // and height.
                CalculateSize();

                // IDifferenceBuffer calculates the inline diff snapshot on the UI thread (on idle).
                // Since we are already on the UI thread, we need to yield control so that the
                // inline diff snapshot computation (and the event handler we registered above to
                // calculate required width and height) get a chance to run and we need to wait until
                // this computation is complete. Once computation is complete, the width and height
                // need to be set from the UI thread. We use ConfigureAwait(true) to stay on the UI thread.
                await _taskCompletion.Task.ConfigureAwait(true);

                // The following work must always happen on UI thread.
                ThreadHelper.ThrowIfNotOnUIThread();

                // We have the height and width required to display the inline diff snapshot now.
                // Set the height and width of the IWpfDifferenceViewer accordingly.
                _diffViewer.VisualElement.Width  = _width;
                _diffViewer.VisualElement.Height = _height;
            }
        /// <summary>
        /// Called before any build actions have begun. This is the last chance to cancel the build before any building begins.
        /// </summary>
        /// <param name="cancelUpdate">Flag indicating cancel update.</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
        public int UpdateSolution_Begin(ref int cancelUpdate)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            // Query build manager operation flag
            uint buildManagerOperation;

            ErrorHandler.ThrowOnFailure(
                _solutionBuildManager.QueryBuildManagerBusyEx(out buildManagerOperation));

            if (buildManagerOperation == (uint)VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_CLEAN)
            {
                // Clear the project.json restore cache on clean to ensure that the next build restores again
                SolutionRestoreWorker.Value.CleanCache();

                return(VSConstants.S_OK);
            }

            if (!ShouldRestoreOnBuild)
            {
                return(VSConstants.S_OK);
            }

            // start a restore task
            var forceRestore = buildManagerOperation == REBUILD_FLAG;

            _restoreTask = RestoreTask.Start(SolutionRestoreWorker.Value, forceRestore);

            return(VSConstants.S_OK);
        }
Exemplo n.º 5
0
        private void DocumentEvents_DocumentClosing(Document document)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            // Work around for file's code model changed event not being raised for web project
            // when file is closed w/o saving changes. Thus, FileChanged change type needs to be
            // processed for web projects only
            if ((document != null) && IsSolutionOpen())
            {
                var fileName = document.FullName;
                if (!string.IsNullOrEmpty(fileName))
                {
                    if (!document.Saved)
                    {
                        var projectItem = _shellProjectService.GetDocumentProjectItem(document);
                        if (projectItem != null)
                        {
                            _solutionEventSubscribers.For(s => s.FileChanged(fileName, projectItem));
                        }
                    }

                    var project = _shellProjectService.GetDocumentProject(document);
                    if (project != null)
                    {
                        _solutionEventSubscribers.For(s => s.FileClosed(fileName, project));
                    }
                }
            }
        }
Exemplo n.º 6
0
        // Refresh the UI after packages are restored.
        // Note that the PackagesMissingStatusChanged event can be fired from a non-UI thread in one case:
        // the VsSolutionManager.Init() method, which is scheduled on the thread pool. So this
        // method needs to use _uiDispatcher.
        private void UpdateAfterPackagesMissingStatusChanged()
        {
            VSThreadHelper.ThrowIfNotOnUIThread();

            Refresh();
            _packageDetail.Refresh();
        }
Exemplo n.º 7
0
        public static VSEventsAdapter CreateAndSubscribe()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            VSEventsAdapter adapter;

            if (SharedVsSettings.VSVersion.VS2022OrNewer)
            {
                adapter = new VSEventsAdapterVS2022();
            }
            else
            {
                adapter = new VSEventsAdapterVS2019();
            }

            try
            {
                if (!adapter.TryInitialize())
                {
                    adapter.SubscribedOnVsEventsSuccessfully = false;
                    return(adapter);
                }

                adapter.SubscribedOnVsEventsSuccessfully = adapter.TrySubscribeAdapterOnVSEvents();
            }
            catch (Exception e)             //Handling exceptions in VS events subscription
            {
                adapter.SubscribedOnVsEventsSuccessfully = false;
                AcuminatorVSPackage.Instance.AcuminatorLogger.LogException(e, logOnlyFromAcuminatorAssemblies: true, LogMode.Error);
            }

            return(adapter);
        }
Exemplo n.º 8
0
            private async Task WindowEventsWindowActivatedAsync(EnvDTE.Window gotFocus, EnvDTE.Window lostFocus)
            {
                if (!ThreadHelper.CheckAccess())
                {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                }

                if (!_codeMapViewModel.IsVisible || Equals(gotFocus, lostFocus) || gotFocus.Document == null)
                {
                    return;
                }
                else if (gotFocus.Document.Language != Constants.CSharp.LegacyLanguageName)
                {
                    _codeMapViewModel.ClearCodeMap();
                    return;
                }
                else if (gotFocus.Document.FullName == lostFocus?.Document?.FullName ||
                         (lostFocus?.Document == null && _codeMapViewModel.Document != null && gotFocus.Document.FullName == _codeMapViewModel.Document.FilePath))
                {
                    return;
                }

                var activeWpfTextViewTask = AcuminatorVSPackage.Instance.GetWpfTextViewByFilePathAsync(gotFocus.Document.FullName);
                await _codeMapViewModel.RefreshCodeMapInternalAsync(activeWpfTextViewTask, activeDocument : null);
            }
Exemplo n.º 9
0
        public HResult UnloadProject(ProjectViewModel viewModel)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var hierarchy = HierarchyFromViewModel(viewModel);

            return(hierarchy?.UnloadProject() ?? HResults.Failed);
        }
Exemplo n.º 10
0
        private string GetDisplayName(NuGetProject nuGetProject)
        {
            Debug.Assert(ThreadHelper.CheckAccess());

            var solutionManager = (VSSolutionManager)_solutionManager;

            return(GetDisplayName(nuGetProject, solutionManager));
        }
Exemplo n.º 11
0
        private bool IsSolutionOpen()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var dte = _shellProjectService.GetDTE() as DTE;

            return((dte != null) && (dte.Solution != null) && dte.Solution.IsOpen);
        }
Exemplo n.º 12
0
            public CodeMapDteEventsObserver(CodeMapWindowViewModel codeMapViewModel)
            {
                ThreadHelper.ThrowIfNotOnUIThread();

                _codeMapViewModel = codeMapViewModel;
                _vsEventsAdapter  = VSEventsAdapter.CreateAndSubscribe();

                SubscribeCodeMapOnVisualStudioEvents();
            }
Exemplo n.º 13
0
        /// <summary>
        /// Returns solution projects.
        /// </summary>
        /// <param name="flags">Processor flags.</param>
        /// <param name="filter">Code model filter.</param>
        /// <returns>Projects.</returns>
        public SolutionModel GetProjects(ProcessorFlags flags, CodeModelFilterFlags filter = CodeModelFilterFlags.All)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var model = new SolutionModel();

            GetProjectsInternal(model, flags, filter);
            return(model);
        }
Exemplo n.º 14
0
        protected override void Dispose(bool disposing)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            _output?.DeletePane(ref guid);
            _output = null;

            base.Dispose(disposing);
        }
Exemplo n.º 15
0
        protected void Unadvise()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (_cookie != 0)
            {
                _vsSolution?.UnadviseSolutionEvents(_cookie);
            }
        }
Exemplo n.º 16
0
        private static string GetDisplayName(NuGetProject nuGetProject, VSSolutionManager solutionManager)
        {
            Debug.Assert(ThreadHelper.CheckAccess());

            var safeName = solutionManager.GetNuGetProjectSafeName(nuGetProject);
            var project  = solutionManager.GetDTEProject(safeName);

            return(EnvDTEProjectUtility.GetDisplayName(project));
        }
Exemplo n.º 17
0
            private void CalculateSize()
            {
                // The following work must always happen on UI thread.
                ThreadHelper.ThrowIfNotOnUIThread();

                if ((_diffViewer.DifferenceBuffer.CurrentInlineBufferSnapshot == null) ||
                    (Interlocked.CompareExchange(ref _calculationStarted, 1, 0) == 1))
                {
                    // Return if inline diff snapshot is not yet ready or
                    // if the size calculation is already in progress.
                    return;
                }

                // Unregister the event handler - we don't need it anymore since the inline diff
                // snapshot is available at this point.
                _diffViewer.DifferenceBuffer.SnapshotDifferenceChanged -= SnapshotDifferenceChanged;

                IWpfTextView  textView;
                ITextSnapshot snapshot;

                if (_diffViewer.ViewMode == DifferenceViewMode.RightViewOnly)
                {
                    textView = _diffViewer.RightView;
                    snapshot = _diffViewer.DifferenceBuffer.RightBuffer.CurrentSnapshot;
                }
                else if (_diffViewer.ViewMode == DifferenceViewMode.LeftViewOnly)
                {
                    textView = _diffViewer.LeftView;
                    snapshot = _diffViewer.DifferenceBuffer.LeftBuffer.CurrentSnapshot;
                }
                else
                {
                    textView = _diffViewer.InlineView;
                    snapshot = _diffViewer.DifferenceBuffer.CurrentInlineBufferSnapshot;
                }

                // Perform a layout without actually rendering the content on the screen so that
                // we can calculate the exact height and width required to render the content on
                // the screen before actually rendering it. This helps us avoiding the flickering
                // effect that would be caused otherwise when the UI is rendered twice with
                // different sizes.
                textView.DisplayTextLineContainingBufferPosition(
                    new SnapshotPoint(snapshot, 0),
                    0.0, ViewRelativePosition.Top, double.MaxValue, double.MaxValue);

                _width = Math.Max(textView.MaxTextRightCoordinate * (textView.ZoomLevel / 100), _minWidth);                  // Width of the widest line.
                Debug.Assert(IsNormal(_width));

                _height = textView.LineHeight * (textView.ZoomLevel / 100) *                 // Height of each line.
                          snapshot.LineCount;                                                // Number of lines.
                Debug.Assert(IsNormal(_height));

                // Calculation of required height and width is now complete.
                _taskCompletion.SetResult(null);
            }
        protected void Advise(IVsSolution vsSolution)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            Assumes.Present(vsSolution);

            _vsSolution = vsSolution;
            var hr = _vsSolution.AdviseSolutionEvents(this, out _cookie);

            ErrorHandler.ThrowOnFailure(hr);
        }
Exemplo n.º 19
0
            private void SnapshotDifferenceChanged(object sender, SnapshotDifferenceChangeEventArgs args)
            {
                // The following work must always happen on UI thread.
                ThreadHelper.ThrowIfNotOnUIThread();

                // This event handler will only be called when the inline diff snapshot computation is complete.
                Debug.Assert(_diffViewer.DifferenceBuffer.CurrentInlineBufferSnapshot != null);

                // We can go ahead and calculate the required height and width now.
                CalculateSize();
            }
Exemplo n.º 20
0
        public void UnsubscribeAdapterFromVSEvents()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (SubscribedOnVsEventsSuccessfully && !TryUnsubscribeAdapterFromVSEvents())
            {
                string errorMsg = VSIXResource.CodeMap_FailedToUnsubscribeFromVsEvents_ErrorMessage + Environment.NewLine +
                                  VSIXResource.CreateIssue_Message;
                AcuminatorVSPackage.Instance.AcuminatorLogger.LogMessage(errorMsg, LogMode.Error);
            }
        }
Exemplo n.º 21
0
        private void SolutionEvents_Renamed(string oldName)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var dte     = _shellProjectService.GetDTE() as DTE;
            var newName = (dte != null) && (dte.Solution != null) ? dte.Solution.FileName : null;

            if (!string.IsNullOrEmpty(oldName) && !string.IsNullOrEmpty(newName))
            {
                _solutionEventSubscribers.For(s => s.SolutionRenamed(oldName, newName));
            }
        }
Exemplo n.º 22
0
        public void Dispose()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (_solutionEvents != null)
            {
                _solutionEvents.Renamed -= SolutionEvents_Renamed;
                _solutionEvents          = null;
            }

            if (_documentEvents != null)
            {
                _documentEvents.DocumentOpened  -= DocumentEvents_DocumentOpened;
                _documentEvents.DocumentClosing -= DocumentEvents_DocumentClosing;
                _documentEvents.DocumentSaved   -= DocumentEvents_DocumentSaved;
                _documentEvents = null;
            }

            if (_codeModelEvents != null)
            {
                _codeModelEvents.ElementAdded   -= CodeModelEvents_ElementAdded;
                _codeModelEvents.ElementChanged -= CodeModelEvents_ElementChanged;
                _codeModelEvents.ElementDeleted -= CodeModelEvents_ElementDeleted;
                _codeModelEvents = null;
            }

            if (_solutionCookie != 0)
            {
                var solution = _serviceProvider.GetService <IVsSolution, SVsSolution>(false);
                if (solution != null)
                {
                    solution.UnadviseSolutionEvents(_solutionCookie);
                }
            }

            if (_docEventsCookie != 0)
            {
                var docEvents = _serviceProvider.GetService <IVsTrackProjectDocuments2, SVsTrackProjectDocuments>(false);
                if (docEvents != null)
                {
                    docEvents.UnadviseTrackProjectDocumentsEvents(_docEventsCookie);
                }
            }

            if (_windowEventsCookie != 0)
            {
                var windowEvents = _serviceProvider.GetService <IVsRunningDocumentTable, SVsRunningDocumentTable>(false);
                if (windowEvents != null)
                {
                    windowEvents.UnadviseRunningDocTableEvents(_windowEventsCookie);
                }
            }
        }
Exemplo n.º 23
0
 private void UnRegisterDocumentEvents()
 {
     if (VSConstants.VSCOOKIE_NIL != _tpdTrackProjectDocumentsCookie)
     {
         ThreadHelper.ThrowIfNotOnUIThread();
         IVsTrackProjectDocuments2 tpdService = (IVsTrackProjectDocuments2)_sccProvider.GetService(typeof(SVsTrackProjectDocuments));
         tpdService.UnadviseTrackProjectDocumentsEvents(_tpdTrackProjectDocumentsCookie);
         _tpdTrackProjectDocumentsCookie = VSConstants.VSCOOKIE_NIL;
     }
     _windowEvents.WindowActivated -= _windowEvents_WindowActivated;
     _solutionEvents.Opened        -= _solutionEvents_Opened;
 }
Exemplo n.º 24
0
        public TextWriter GetOutputTextWriter()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (_output.GetPane(ref guid, out IVsOutputWindowPane pane) == VSConstants.S_OK)
            {
                pane.Clear();

                return(this);
            }

            return(null);
        }
Exemplo n.º 25
0
        private IEnumerable <string> GetDisplayNames(IEnumerable <NuGetProject> allProjects)
        {
            Debug.Assert(ThreadHelper.CheckAccess());

            List <string> projectNames    = new List <string>();
            var           solutionManager = (VSSolutionManager)_solutionManager;

            foreach (var nuGetProject in allProjects)
            {
                string displayName = GetDisplayName(nuGetProject, solutionManager);
                projectNames.Add(displayName);
            }
            return(projectNames);
        }
Exemplo n.º 26
0
            private void SetVisibilityForCodeMapWindow(EnvDTE.Window window, bool windowIsVisible)
            {
                if (!ThreadHelper.CheckAccess())
                {
                    return;
                }

                string windowObjectKind, windowKind, windowDocumentPath, documentLanguage;

                try
                {
                    //Sometimes COM interop exceptions popup from getter, so we need to query properties safely
                    windowObjectKind   = window.ObjectKind;
                    windowDocumentPath = window.Document?.FullName;
                    documentLanguage   = window.Document?.Language;
                    windowKind         = window.Kind;
                }
                catch
                {
                    return;
                }

                if (windowObjectKind == null || !Guid.TryParse(windowObjectKind, out Guid windowId))
                {
                    return;
                }

                if (windowId == CodeMapWindow.CodeMapWindowGuid)                  //Case when Code Map is displayed
                {
                    bool wasVisible = _codeMapViewModel.IsVisible;
                    _codeMapViewModel.IsVisible = windowIsVisible;

                    if (!wasVisible && _codeMapViewModel.IsVisible)                       //Handle the case when WindowShowing event happens after WindowActivated event
                    {
                        RefreshCodeMapAsync()
                        .FileAndForget($"vs/{AcuminatorVSPackage.PackageName}/{nameof(CodeMapWindowViewModel)}/{nameof(SetVisibilityForCodeMapWindow)}");
                    }
                }
                else if (IsSwitchingToAnotherDocumentWhileCodeMapIsEmpty())
                {
                    RefreshCodeMapAsync()
                    .FileAndForget($"vs/{AcuminatorVSPackage.PackageName}/{nameof(CodeMapWindowViewModel)}/{nameof(SetVisibilityForCodeMapWindow)}");
                }

                //-------------------------------------------Local Function----------------------------------------------------------------------------------------
                bool IsSwitchingToAnotherDocumentWhileCodeMapIsEmpty() =>
                _codeMapViewModel.IsVisible && _codeMapViewModel.Document == null && windowIsVisible && windowKind == "Document" && windowId != default &&
                documentLanguage == Constants.CSharp.LegacyLanguageName && !windowDocumentPath.IsNullOrWhiteSpace();
            }
Exemplo n.º 27
0
        /// <summary>
        /// One time subscriber notification that solution's been opened.
        /// </summary>
        /// <remarks>Solution may or may not be actually open.</remarks>
        public void NotifySolutionOpened()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            _shellStatusBarService.SetStatusBarText($"{_packageService.ProductName} {_packageService.Version} initialized");

            var dte      = _shellProjectService.GetDTE() as DTE;
            var solution = dte.Solution;

            if ((solution == null) || !solution.IsOpen)
            {
                return;
            }

            OnAfterOpenSolution(null, Convert.ToInt32(false));
        }
Exemplo n.º 28
0
        protected void Advise(IServiceProvider serviceProvider)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            _vsSolution = serviceProvider.GetService <SVsSolution, IVsSolution>();
            if (_vsSolution != null)
            {
                var hr = _vsSolution.AdviseSolutionEvents(this, out _cookie);
                ErrorHandler.ThrowOnFailure(hr);
            }
        }
        private void SetupDocumentEvents()
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            IVsTrackProjectDocuments2 tpdService = (IVsTrackProjectDocuments2)_sccProvider.GetService(typeof(SVsTrackProjectDocuments));

            tpdService.AdviseTrackProjectDocumentsEvents(this, out _tpdTrackProjectDocumentsCookie);
            Debug.Assert(VSConstants.VSCOOKIE_NIL != _tpdTrackProjectDocumentsCookie);

            var activeIde = SolutionExtensions.GetActiveIDE();

            //var activeIde = BasicSccProvider.GetServiceEx<EnvDTE80.DTE2>();
            //activeIde.Events.SolutionItemsEvents.
            _windowEvents   = activeIde.Events.WindowEvents;
            _solutionEvents = activeIde.Events.SolutionEvents;
            _solutionEvents.ProjectAdded  += _solutionEvents_ProjectAdded;
            _windowEvents.WindowActivated += _windowEvents_WindowActivated;
        }
Exemplo n.º 30
0
        private void DocumentEvents_DocumentOpened(Document document)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if ((document != null) && IsSolutionOpen())
            {
                var fileName = document.FullName;
                if (!string.IsNullOrEmpty(fileName))
                {
                    var projectItem = _shellProjectService.GetDocumentProjectItem(document);
                    if (projectItem != null)
                    {
                        _solutionEventSubscribers.For(s => s.FileOpened(fileName, projectItem));
                    }
                }
            }
        }