VisualStudioWorkspaceImpl.cs 56.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
11
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
12 13
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
14
using Microsoft.CodeAnalysis.Notification;
15
using Microsoft.CodeAnalysis.Options;
C
CyrusNajmabadi 已提交
16
using Microsoft.CodeAnalysis.Packaging;
17 18 19 20 21
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Feedback.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
C
CyrusNajmabadi 已提交
22
using Microsoft.VisualStudio.LanguageServices.Packaging;
23 24 25 26
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
C
CyrusNajmabadi 已提交
27
using NuGet.VisualStudio;
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
using Roslyn.Utilities;
using Roslyn.VisualStudio.ProjectSystem;
using VSLangProj;
using VSLangProj140;
using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
    /// <summary>
    /// The Workspace for running inside Visual Studio.
    /// </summary>
    internal abstract class VisualStudioWorkspaceImpl : VisualStudioWorkspace
    {
        private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1);
        private const string AppCodeFolderName = "App_Code";

        protected readonly IServiceProvider ServiceProvider;
        private readonly IVsUIShellOpenDocument _shellOpenDocument;
        private readonly IVsTextManager _textManager;

        // Not readonly because it needs to be set in the derived class' constructor.
        private VisualStudioProjectTracker _projectTracker;

        // document worker coordinator
52
        private ISolutionCrawlerRegistrationService _registrationService;
53

54
        private readonly ForegroundThreadAffinitizedObject _foregroundObject = new ForegroundThreadAffinitizedObject();
55

C
CyrusNajmabadi 已提交
56 57 58
        private PackageInstallerService _packageInstallerService;
        private PackageSearchService _packageSearchService;

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        public VisualStudioWorkspaceImpl(
            SVsServiceProvider serviceProvider,
            WorkspaceBackgroundWork backgroundWork)
            : base(
                CreateHostServices(serviceProvider),
                backgroundWork)
        {
            this.ServiceProvider = serviceProvider;
            _textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager;
            _shellOpenDocument = serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;

            // Ensure the options factory services are initialized on the UI thread
            this.Services.GetService<IOptionService>();

            var session = serviceProvider.GetService(typeof(SVsLog)) as IVsSqmMulti;
            var profileService = serviceProvider.GetService(typeof(SVsFeedbackProfile)) as IVsFeedbackProfile;

            // We have Watson hits where this came back null, so guard against it
            if (profileService != null)
            {
                Sqm.LogSession(session, profileService.IsMicrosoftInternal);
            }
        }

        internal static HostServices CreateHostServices(SVsServiceProvider serviceProvider)
        {
            var composition = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
            return MefV1HostServices.Create(composition.DefaultExportProvider);
        }

        protected void InitializeStandardVisualStudioWorkspace(SVsServiceProvider serviceProvider, SaveEventsService saveEventsService)
        {
            var projectTracker = new VisualStudioProjectTracker(serviceProvider);

            // Ensure the document tracking service is initialized on the UI thread
            var documentTrackingService = this.Services.GetService<IDocumentTrackingService>();
            var documentProvider = new RoslynDocumentProvider(projectTracker, serviceProvider, documentTrackingService);
            projectTracker.DocumentProvider = documentProvider;

            projectTracker.MetadataReferenceProvider = this.Services.GetService<VisualStudioMetadataReferenceManager>();
            projectTracker.RuleSetFileProvider = this.Services.GetService<VisualStudioRuleSetManager>();

            this.SetProjectTracker(projectTracker);

            var workspaceHost = new VisualStudioWorkspaceHost(this);
            projectTracker.RegisterWorkspaceHost(workspaceHost);
            projectTracker.StartSendingEventsToWorkspaceHost(workspaceHost);

            saveEventsService.StartSendingSaveEvents();

            // Ensure the options factory services are initialized on the UI thread
            this.Services.GetService<IOptionService>();
C
CyrusNajmabadi 已提交
111 112 113 114 115

            // Ensure the nuget package services are initialized on the UI thread.
            _packageSearchService = this.Services.GetService<IPackageSearchService>() as PackageSearchService;
            _packageInstallerService = (PackageInstallerService)this.Services.GetService<IPackageInstallerService>();
            _packageInstallerService.Connect(this);
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
        }

        /// <summary>NOTE: Call only from derived class constructor</summary>
        protected void SetProjectTracker(VisualStudioProjectTracker projectTracker)
        {
            _projectTracker = projectTracker;
        }

        internal VisualStudioProjectTracker ProjectTracker
        {
            get
            {
                return _projectTracker;
            }
        }

        internal void ClearReferenceCache()
        {
            _projectTracker.MetadataReferenceProvider.ClearCache();
        }

        internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId)
        {
            var project = GetHostProject(documentId.ProjectId);
            if (project != null)
            {
                return project.GetDocumentOrAdditionalDocument(documentId);
            }

            return null;
        }

        internal IVisualStudioHostProject GetHostProject(ProjectId projectId)
        {
            return this.ProjectTracker.GetProject(projectId);
        }

        private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project)
        {
            project = GetHostProject(projectId);
            return project != null;
        }

        public override bool TryApplyChanges(Microsoft.CodeAnalysis.Solution newSolution)
        {
            // first make sure we can edit the document we will be updating (check them out from source control, etc)
            var changedDocs = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().SelectMany(pd => pd.GetChangedDocuments()).ToList();
            if (changedDocs.Count > 0)
            {
                this.EnsureEditableDocuments(changedDocs);
            }

            return base.TryApplyChanges(newSolution);
        }

        public override bool CanOpenDocuments
        {
            get
            {
                return true;
            }
        }

        internal override bool CanChangeActiveContextDocument
        {
            get
            {
                return true;
            }
        }

        public override bool CanApplyChange(ApplyChangesKind feature)
        {
            switch (feature)
            {
                case ApplyChangesKind.AddDocument:
                case ApplyChangesKind.RemoveDocument:
                case ApplyChangesKind.ChangeDocument:
                case ApplyChangesKind.AddMetadataReference:
                case ApplyChangesKind.RemoveMetadataReference:
                case ApplyChangesKind.AddProjectReference:
                case ApplyChangesKind.RemoveProjectReference:
                case ApplyChangesKind.AddAnalyzerReference:
                case ApplyChangesKind.RemoveAnalyzerReference:
                case ApplyChangesKind.AddAdditionalDocument:
                case ApplyChangesKind.RemoveAdditionalDocument:
                case ApplyChangesKind.ChangeAdditionalDocument:
                    return true;

                default:
                    return false;
            }
        }

        private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project)
        {
            hierarchy = null;
            project = null;

            return this.TryGetHostProject(projectId, out hostProject)
                && this.TryGetHierarchy(projectId, out hierarchy)
                && hierarchy.TryGetProject(out project);
        }

        internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project)
        {
            if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project))
            {
                throw new ArgumentException(string.Format(ServicesVSResources.CouldNotFindProject, projectId));
            }
        }

C
CyrusNajmabadi 已提交
228 229 230 231 232 233 234 235 236
        internal EnvDTE.Project TryGetDTEProject(ProjectId projectId)
        {
            IVisualStudioHostProject hostProject;
            IVsHierarchy hierarchy;
            EnvDTE.Project project;

            return TryGetProjectData(projectId, out hostProject, out hierarchy, out project) ? project : null;
        }

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
        internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName)
        {
            IVisualStudioHostProject hostProject;
            IVsHierarchy hierarchy;
            EnvDTE.Project project;
            try
            {
                GetProjectData(projectId, out hostProject, out hierarchy, out project);
            }
            catch (ArgumentException)
            {
                return false;
            }

            var vsProject = (VSProject)project.Object;
            try
            {
                vsProject.References.Add(assemblyName);
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

        private string GetAnalyzerPath(AnalyzerReference analyzerReference)
        {
            return analyzerReference.FullPath;
        }

        protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
        {
            if (projectId == null)
            {
273
                throw new ArgumentNullException(nameof(projectId));
274 275 276 277
            }

            if (analyzerReference == null)
            {
278
                throw new ArgumentNullException(nameof(analyzerReference));
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
            }

            IVisualStudioHostProject hostProject;
            IVsHierarchy hierarchy;
            EnvDTE.Project project;
            GetProjectData(projectId, out hostProject, out hierarchy, out project);

            string filePath = GetAnalyzerPath(analyzerReference);
            if (filePath != null)
            {
                VSProject3 vsProject = (VSProject3)project.Object;
                vsProject.AnalyzerReferences.Add(filePath);
            }
        }

        protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
        {
            if (projectId == null)
            {
298
                throw new ArgumentNullException(nameof(projectId));
299 300 301 302
            }

            if (analyzerReference == null)
            {
303
                throw new ArgumentNullException(nameof(analyzerReference));
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
            }

            IVisualStudioHostProject hostProject;
            IVsHierarchy hierarchy;
            EnvDTE.Project project;
            GetProjectData(projectId, out hostProject, out hierarchy, out project);

            string filePath = GetAnalyzerPath(analyzerReference);
            if (filePath != null)
            {
                VSProject3 vsProject = (VSProject3)project.Object;
                vsProject.AnalyzerReferences.Remove(filePath);
            }
        }

        private string GetMetadataPath(MetadataReference metadataReference)
        {
            var fileMetadata = metadataReference as PortableExecutableReference;
            if (fileMetadata != null)
            {
                return fileMetadata.FilePath;
            }

            return null;
        }

        protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference)
        {
            if (projectId == null)
            {
334
                throw new ArgumentNullException(nameof(projectId));
335 336 337 338
            }

            if (metadataReference == null)
            {
339
                throw new ArgumentNullException(nameof(metadataReference));
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
            }

            IVisualStudioHostProject hostProject;
            IVsHierarchy hierarchy;
            EnvDTE.Project project;
            GetProjectData(projectId, out hostProject, out hierarchy, out project);

            string filePath = GetMetadataPath(metadataReference);
            if (filePath != null)
            {
                VSProject vsProject = (VSProject)project.Object;
                vsProject.References.Add(filePath);
            }
        }

        protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference)
        {
            if (projectId == null)
            {
359
                throw new ArgumentNullException(nameof(projectId));
360 361 362 363
            }

            if (metadataReference == null)
            {
364
                throw new ArgumentNullException(nameof(metadataReference));
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
            }

            IVisualStudioHostProject hostProject;
            IVsHierarchy hierarchy;
            EnvDTE.Project project;
            GetProjectData(projectId, out hostProject, out hierarchy, out project);

            string filePath = GetMetadataPath(metadataReference);
            if (filePath != null)
            {
                VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object;
                VSLangProj.Reference reference = vsProject.References.Find(filePath);
                if (reference != null)
                {
                    reference.Remove();
                }
            }
        }

        protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
        {
            if (projectId == null)
            {
388
                throw new ArgumentNullException(nameof(projectId));
389 390 391 392
            }

            if (projectReference == null)
            {
393
                throw new ArgumentNullException(nameof(projectReference));
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
            }

            IVisualStudioHostProject hostProject;
            IVsHierarchy hierarchy;
            EnvDTE.Project project;
            GetProjectData(projectId, out hostProject, out hierarchy, out project);

            IVisualStudioHostProject refHostProject;
            IVsHierarchy refHierarchy;
            EnvDTE.Project refProject;
            GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject);

            VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object;
            vsProject.References.AddProject(refProject);
        }

        protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
        {
            if (projectId == null)
            {
414
                throw new ArgumentNullException(nameof(projectId));
415 416 417 418
            }

            if (projectReference == null)
            {
419
                throw new ArgumentNullException(nameof(projectReference));
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
            }

            IVisualStudioHostProject hostProject;
            IVsHierarchy hierarchy;
            EnvDTE.Project project;
            GetProjectData(projectId, out hostProject, out hierarchy, out project);

            IVisualStudioHostProject refHostProject;
            IVsHierarchy refHierarchy;
            EnvDTE.Project refProject;
            GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject);

            VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object;
            foreach (VSLangProj.Reference reference in vsProject.References)
            {
                if (reference.SourceProject == refProject)
                {
                    reference.Remove();
                }
            }
        }

        protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text)
        {
            AddDocumentCore(info, text, isAdditionalDocument: false);
        }

        protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text)
        {
            AddDocumentCore(info, text, isAdditionalDocument: true);
        }

        private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument)
        {
            IVsHierarchy hierarchy;
            EnvDTE.Project project;
            IVisualStudioHostProject hostProject;
            GetProjectData(info.Id.ProjectId, out hostProject, out hierarchy, out project);

            // If the first namespace name matches the name of the project, then we don't want to
            // generate a folder for that.  The project is implicitly a folder with that name.
            var folders = info.Folders.AsEnumerable();
            if (folders.FirstOrDefault() == project.Name)
            {
                folders = folders.Skip(1);
            }

            folders = FilterFolderForProjectType(project, folders);

            if (IsWebsite(project))
            {
                AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
            }
            else if (folders.Any())
            {
                AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
            }
            else
            {
                AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
            }
        }

        private bool IsWebsite(EnvDTE.Project project)
        {
            return project.Kind == VsWebSite.PrjKind.prjKindVenusProject;
        }

        private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders)
        {
            foreach (var folder in folders)
            {
                var items = GetAllItems(project.ProjectItems);
                var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0);
                if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile)
                {
                    yield return folder;
                }
            }
        }

        private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems)
        {
            if (projectItems == null)
            {
                return SpecializedCollections.EmptyEnumerable<ProjectItem>();
            }

            var items = projectItems.OfType<ProjectItem>();
            return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems)));
        }

#if false
        protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders)
        {
            IVsHierarchy hierarchy;
            EnvDTE.Project project;
            IVisualStudioHostProject hostProject;
            GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project);

            // If the first namespace name matches the name of the project, then we don't want to
            // generate a folder for that.  The project is implicitly a folder with that name.
            if (folders.FirstOrDefault() == project.Name)
            {
                folders = folders.Skip(1);
            }

            var name = Path.GetFileName(filePath);

            if (folders.Any())
            {
                AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath);
            }
            else
            {
                AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath);
            }
        }
#endif

        private ProjectItem AddDocumentToProject(
            IVisualStudioHostProject hostProject,
            EnvDTE.Project project,
            DocumentId documentId,
            string documentName,
            SourceCodeKind sourceCodeKind,
            SourceText initialText = null,
            string filePath = null,
            bool isAdditionalDocument = false)
        {
            string folderPath;
            if (!project.TryGetFullPath(out folderPath))
            {
                // TODO(cyrusn): Throw an appropriate exception here.
                throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol);
            }

            return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument);
        }

        private ProjectItem AddDocumentToFolder(
            IVisualStudioHostProject hostProject,
            EnvDTE.Project project,
            DocumentId documentId,
            IEnumerable<string> folders,
            string documentName,
            SourceCodeKind sourceCodeKind,
            SourceText initialText = null,
            string filePath = null,
            bool isAdditionalDocument = false)
        {
            var folder = project.FindOrCreateFolder(folders);

            string folderPath;
            if (!folder.TryGetFullPath(out folderPath))
            {
                // TODO(cyrusn): Throw an appropriate exception here.
                throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol);
            }

            return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument);
        }

        private ProjectItem AddDocumentToProjectItems(
            IVisualStudioHostProject hostProject,
            ProjectItems projectItems,
            DocumentId documentId,
            string folderPath,
            string documentName,
            SourceCodeKind sourceCodeKind,
            SourceText initialText,
            string filePath,
            bool isAdditionalDocument)
        {
            if (filePath == null)
            {
                var baseName = Path.GetFileNameWithoutExtension(documentName);
                var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind);
                var uniqueName = projectItems.GetUniqueName(baseName, extension);
                filePath = Path.Combine(folderPath, uniqueName);
            }

            if (initialText != null)
            {
                using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8))
                {
                    initialText.Write(writer);
                }
            }

            using (var documentIdHint = _projectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId))
            {
                return projectItems.AddFromFile(filePath);
            }
        }

        protected void RemoveDocumentCore(DocumentId documentId)
        {
            if (documentId == null)
            {
620
                throw new ArgumentNullException(nameof(documentId));
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
            }

            var document = this.GetHostDocument(documentId);
            if (document != null)
            {
                var project = document.Project.Hierarchy as IVsProject3;

                var itemId = document.GetItemId();
                if (itemId == (uint)VSConstants.VSITEMID.Nil)
                {
                    // it is no longer part of the solution
                    return;
                }

                int result;
                project.RemoveItem(0, itemId, out result);
            }
        }

        protected override void ApplyDocumentRemoved(DocumentId documentId)
        {
            RemoveDocumentCore(documentId);
        }

        protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId)
        {
            RemoveDocumentCore(documentId);
        }

        public override void OpenDocument(DocumentId documentId, bool activate = true)
        {
            OpenDocumentCore(documentId, activate);
        }

        public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true)
        {
            OpenDocumentCore(documentId, activate);
        }

        public override void CloseDocument(DocumentId documentId)
        {
            CloseDocumentCore(documentId);
        }

        public override void CloseAdditionalDocument(DocumentId documentId)
        {
            CloseDocumentCore(documentId);
        }

670
        public bool TryGetInfoBarData(out IVsWindowFrame frame, out IVsInfoBarUIFactory factory)
671
        {
672 673
            frame = null;
            factory = null;
674 675 676 677 678 679
            var monitorSelectionService = ServiceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;
            object value = null;

            // We want to get whichever window is currently in focus (including toolbars) as we could have had an exception thrown from the error list or interactive window
            if (monitorSelectionService != null &&
               ErrorHandler.Succeeded(monitorSelectionService.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_WindowFrame, out value)))
680
            {
681
                frame = value as IVsWindowFrame;
682
            }
683
            else
684
            {
685
                return false;
686 687
            }

688 689
            factory = ServiceProvider.GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory;
            return frame != null && factory != null;
690 691
        }

692 693 694 695
        public void OpenDocumentCore(DocumentId documentId, bool activate = true)
        {
            if (documentId == null)
            {
696
                throw new ArgumentNullException(nameof(documentId));
697 698
            }

699
            if (!_foregroundObject.IsForeground())
700
            {
C
Cyrus Najmabadi 已提交
701
                throw new InvalidOperationException(ServicesVSResources.ThisWorkspaceOnlySupportsOpeningDocumentsOnTheUIThread);
702 703
            }

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
            var document = this.GetHostDocument(documentId);
            if (document != null && document.Project != null)
            {
                IVsWindowFrame frame;
                if (TryGetFrame(document, out frame))
                {
                    if (activate)
                    {
                        frame.Show();
                    }
                    else
                    {
                        frame.ShowNoActivate();
                    }
                }
            }
        }

        private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame)
        {
            frame = null;

            var itemId = document.GetItemId();
            if (itemId == (uint)VSConstants.VSITEMID.Nil)
            {
729
                // If the ItemId is Nil, then IVsProject would not be able to open the 
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
                // document using its ItemId. Thus, we must use OpenDocumentViaProject, which only 
                // depends on the file path.

                uint itemid;
                IVsUIHierarchy uiHierarchy;
                OLEServiceProvider oleServiceProvider;

                return ErrorHandler.Succeeded(_shellOpenDocument.OpenDocumentViaProject(
                    document.FilePath,
                    VSConstants.LOGVIEWID.TextView_guid,
                    out oleServiceProvider,
                    out uiHierarchy,
                    out itemid,
                    out frame));
            }
            else
            {
                // If the ItemId is not Nil, then we should not call IVsUIShellDocument
                // .OpenDocumentViaProject here because that simply takes a file path and opens the
                // file within the context of the first project it finds. That would cause problems
                // if the document we're trying to open is actually a linked file in another 
                // project. So, we get the project's hierarchy and open the document using its item
                // ID.

                // It's conceivable that IVsHierarchy might not implement IVsProject. However, 
                // OpenDocumentViaProject itself relies upon this QI working, so it should be OK to 
                // use here.

                var vsProject = document.Project.Hierarchy as IVsProject;
                return vsProject != null &&
                    ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame));
            }
        }

        public void CloseDocumentCore(DocumentId documentId)
        {
            if (documentId == null)
            {
768
                throw new ArgumentNullException(nameof(documentId));
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
            }

            if (this.IsDocumentOpen(documentId))
            {
                var document = this.GetHostDocument(documentId);
                if (document != null)
                {
                    IVsUIHierarchy uiHierarchy;
                    IVsWindowFrame frame;
                    int isOpen;
                    if (ErrorHandler.Succeeded(_shellOpenDocument.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out uiHierarchy, null, out frame, out isOpen)))
                    {
                        // TODO: do we need save argument for CloseDocument?
                        frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
                    }
                }
            }
        }

        protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
        {
            EnsureEditableDocuments(documentId);
            var hostDocument = GetHostDocument(documentId);
            hostDocument.UpdateText(newText);
        }

        protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText)
        {
            EnsureEditableDocuments(documentId);
            var hostDocument = GetHostDocument(documentId);
            hostDocument.UpdateText(newText);
        }

        private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind)
        {
            // No extension was provided.  Pick a good one based on the type of host project.
            switch (hostProject.Language)
            {
                case LanguageNames.CSharp:
808 809 810
                    // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
                    //return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx";
                    return ".cs";
811
                case LanguageNames.VisualBasic:
812 813 814
                    // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
                    //return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx";
                    return ".vb";
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
                default:
                    throw new InvalidOperationException();
            }
        }

        public override IVsHierarchy GetHierarchy(ProjectId projectId)
        {
            var project = this.GetHostProject(projectId);

            if (project == null)
            {
                return null;
            }

            return project.Hierarchy;
        }

        internal override void SetDocumentContext(DocumentId documentId)
        {
            var hostDocument = GetHostDocument(documentId);
            var itemId = hostDocument.GetItemId();
            if (itemId == (uint)VSConstants.VSITEMID.Nil)
            {
                // the document has been removed from the solution
                return;
            }

842
            var hierarchy = hostDocument.Project.Hierarchy;
843
            var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId);
844 845
            if (sharedHierarchy != null)
            {
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
                if (sharedHierarchy.SetProperty(
                        (uint)VSConstants.VSITEMID.Root,
                        (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext,
                        ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK)
                {
                    // The ASP.NET 5 intellisense project is now updated.
                    return;
                }
                else
                {
                    // Universal Project shared files
                    //     Change the SharedItemContextHierarchy of the project's parent hierarchy, then
                    //     hierarchy events will trigger the workspace to update.
                    var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy);
                }
861 862 863 864 865 866 867 868 869 870 871
            }
            else
            {
                // Regular linked files
                //     Transfer the item (open buffer) to the new hierarchy, and then hierarchy events 
                //     will trigger the workspace to update.
                var vsproj = hierarchy as IVsProject3;
                var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null);
            }
        }

872
        internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId)
873 874 875 876 877 878 879 880 881 882
        {
            // TODO: This is a very roundabout way to update the context

            // The sharedHierarchy passed in has a new context, but we don't know what it is.
            // The documentId passed in is associated with this sharedHierarchy, and this method
            // will be called once for each such documentId. During this process, one of these
            // documentIds will actually belong to the new SharedItemContextHierarchy. Once we
            // find that one, we can map back to the open buffer and set its active context to
            // the appropriate project.

883 884
            var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker);
            if (hostProject.Hierarchy == sharedHierarchy)
885 886 887 888 889
            {
                // How?
                return;
            }

890
            if (hostProject.Id != documentId.ProjectId)
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
            {
                // While this documentId is associated with one of the head projects for this
                // sharedHierarchy, it is not associated with the new context hierarchy. Another
                // documentId will be passed to this method and update the context.
                return;
            }

            // This documentId belongs to the new SharedItemContextHierarchy. Update the associated
            // buffer.
            OnDocumentContextUpdated(documentId);
        }

        /// <summary>
        /// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that
        /// is in the current context. For regular files (non-shared and non-linked) and closed
        /// linked files, this is always the provided <see cref="DocumentId"/>. For open linked
        /// files and open shared files, the active context is already tracked by the
        /// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the
        /// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/> 
        /// is preferred.
        /// </summary>
        internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId)
        {
            // If the document is open, then the Workspace knows the current context for both 
            // linked and shared files
            if (IsDocumentOpen(documentId))
            {
                return base.GetDocumentIdInCurrentContext(documentId);
            }

            var hostDocument = GetHostDocument(documentId);
            var itemId = hostDocument.GetItemId();
            if (itemId == (uint)VSConstants.VSITEMID.Nil)
            {
                // An itemid is required to determine whether the file belongs to a Shared Project
                return base.GetDocumentIdInCurrentContext(documentId);
            }

            // If this is a regular document or a closed linked (non-shared) document, then use the
            // default logic for determining current context.
931
            var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId);
932 933 934 935 936 937
            if (sharedHierarchy == null)
            {
                return base.GetDocumentIdInCurrentContext(documentId);
            }

            // This is a closed shared document, so we must determine the correct context.
938 939 940
            var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker);
            var matchingProject = CurrentSolution.GetProject(hostProject.Id);
            if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy)
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
            {
                return base.GetDocumentIdInCurrentContext(documentId);
            }

            if (matchingProject.ContainsDocument(documentId))
            {
                // The provided documentId is in the current context project
                return documentId;
            }

            // The current context document is from another project.
            var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds();
            var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id);
            return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId);
        }

957
        internal bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy)
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
        {
            hierarchy = this.GetHierarchy(projectId);
            return hierarchy != null;
        }

        public override string GetFilePath(DocumentId documentId)
        {
            var document = this.GetHostDocument(documentId);

            if (document == null)
            {
                return null;
            }
            else
            {
                return document.FilePath;
            }
        }

        internal void StartSolutionCrawler()
        {
979
            if (_registrationService == null)
980 981 982
            {
                lock (this)
                {
983
                    if (_registrationService == null)
984
                    {
985 986
                        _registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>();
                        _registrationService.Register(this);
987 988 989 990 991 992 993
                    }
                }
            }
        }

        internal void StopSolutionCrawler()
        {
994
            if (_registrationService != null)
995 996 997
            {
                lock (this)
                {
998
                    if (_registrationService != null)
999
                    {
1000 1001
                        _registrationService.Unregister(this, blockingShutdown: true);
                        _registrationService = null;
1002 1003 1004 1005 1006 1007 1008
                    }
                }
            }
        }

        protected override void Dispose(bool finalize)
        {
C
CyrusNajmabadi 已提交
1009 1010 1011
            _packageInstallerService?.Disconnect(this);
            _packageSearchService?.Dispose();

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
            // workspace is going away. unregister this workspace from work coordinator
            StopSolutionCrawler();

            base.Dispose(finalize);
        }

        public void EnsureEditableDocuments(IEnumerable<DocumentId> documents)
        {
            var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GetService(typeof(SVsQueryEditQuerySave));

            var fileNames = documents.Select(GetFilePath).ToArray();

            uint editVerdict;
            uint editResultFlags;

            // TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn
            int result = queryEdit.QueryEditFiles(
                rgfQueryEdit: 0,
                cFiles: fileNames.Length,
                rgpszMkDocuments: fileNames,
                rgrgf: new uint[fileNames.Length],
                rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length],
                pfEditVerdict: out editVerdict,
                prgfMoreInfo: out editResultFlags);

            if (ErrorHandler.Failed(result) ||
                editVerdict != (uint)tagVSQueryEditResult.QER_EditOK)
            {
                throw new Exception("Unable to check out the files from source control.");
            }

            if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0)
            {
                throw new Exception("A file was reloaded during the source control checkout.");
            }
        }

        public void EnsureEditableDocuments(params DocumentId[] documents)
        {
            this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents);
        }

        internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId)
        {
            var vsDoc = this.GetHostDocument(documentId);
            this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader);
        }

        internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId)
        {
            var vsDoc = this.GetHostDocument(documentId);
            this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader);
        }

        public TInterface GetVsService<TService, TInterface>()
            where TService : class
            where TInterface : class
        {
            return this.ServiceProvider.GetService(typeof(TService)) as TInterface;
        }

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
        public object GetVsService(Type serviceType)
        {
            return ServiceProvider.GetService(serviceType);
        }

        public DTE GetVsDte()
        {
            return GetVsService<SDTE, DTE>();
        }

1083 1084 1085 1086 1087 1088 1089 1090 1091
        internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject)
        {
            _foregroundObject.AssertIsForeground();

            IVsHierarchy referencingHierarchy;
            IVsHierarchy referencedHierarchy;
            if (!TryGetHierarchy(referencingProject, out referencingHierarchy) ||
                !TryGetHierarchy(referencedProject, out referencedHierarchy))
            {
1092 1093
                // Couldn't even get a hierarchy for this project. So we have to assume
                // that adding a reference is disallowed.
1094 1095 1096
                return false;
            }

1097 1098
            // First we have to see if either project disallows the reference being added.
            const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference;
1099

1100 1101
            uint canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN;
            uint canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN;
1102

1103 1104 1105
            var referencingProjectFlavor3 = referencingHierarchy as IVsProjectFlavorReferences3;
            if (referencingProjectFlavor3 != null)
            {
1106
                string unused;
1107
                if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out unused)))
1108 1109 1110 1111 1112 1113
                {
                    // Something went wrong even trying to see if the reference would be allowed.
                    // Assume it won't be allowed.
                    return false;
                }

1114
                if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY)
1115
                {
1116
                    // Adding this project reference is not allowed.
1117 1118
                    return false;
                }
1119
            }
1120

1121 1122 1123 1124 1125
            var referencedProjectFlavor3 = referencedHierarchy as IVsProjectFlavorReferences3;
            if (referencedProjectFlavor3 != null)
            {
                string unused;
                if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out unused)))
1126
                {
1127 1128 1129 1130 1131 1132 1133 1134 1135
                    // Something went wrong even trying to see if the reference would be allowed.
                    // Assume it won't be allowed.
                    return false;
                }

                if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY)
                {
                    // Adding this project reference is not allowed.
                    return false;
1136
                }
1137
            }
1138

1139 1140 1141 1142 1143 1144 1145
            // Neither project denied the reference being added.  At this point, if either project
            // allows the reference to be added, and the other doesn't block it, then we can add 
            // the reference.
            if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW ||
                canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW)
            {
                return true;
1146 1147
            }

1148 1149
            // In both directions things are still unknown.  Fallback to the reference manager
            // to make the determination here.
1150 1151 1152
            var referenceManager = GetVsService<SVsReferenceManager, IVsReferenceManager>();
            if (referenceManager == null)
            {
1153
                // Couldn't get the reference manager.  Have to assume it's not allowed.
1154 1155 1156
                return false;
            }

1157 1158
            // As long as the reference manager does not deny things, then we allow the 
            // reference to be added.
1159
            var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy);
1160
            return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY;
1161 1162
        }

1163 1164 1165 1166
        /// <summary>
        /// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just
        /// forwards the calls down to the underlying Workspace.
        /// </summary>
1167
        protected sealed class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkspaceHost2, IVisualStudioWorkingFolder
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
        {
            private readonly VisualStudioWorkspaceImpl _workspace;

            private Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>();

            public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace)
            {
                _workspace = workspace;
            }

            void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions)
            {
                _workspace.OnCompilationOptionsChanged(projectId, compilationOptions);
                _workspace.OnParseOptionsChanged(projectId, parseOptions);
            }

            void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo)
            {
                _workspace.OnDocumentAdded(documentInfo);
            }

            void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext)
            {
                // TODO: Move this out to DocumentProvider. As is, this depends on being able to 
                // access the host document which will already be deleted in some cases, causing 
                // a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a
                // Mercury shared document is closed.
                // UnsubscribeFromSharedHierarchyEvents(documentId);
1196 1197 1198 1199
                using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed"))
                {
                    _workspace.OnDocumentClosed(documentId, loader, updateActiveContext);
                }
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
            }

            void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext)
            {
                SubscribeToSharedHierarchyEvents(documentId);
                _workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext);
            }

            private void SubscribeToSharedHierarchyEvents(DocumentId documentId)
            {
                // Todo: maybe avoid double alerts.
                var hostDocument = _workspace.GetHostDocument(documentId);
                if (hostDocument == null)
                {
                    return;
                }

                var hierarchy = hostDocument.Project.Hierarchy;

                var itemId = hostDocument.GetItemId();
                if (itemId == (uint)VSConstants.VSITEMID.Nil)
                {
                    // the document has been removed from the solution
                    return;
                }

1226
                var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId);
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
                if (sharedHierarchy != null)
                {
                    uint cookie;
                    var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId);
                    var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out cookie);

                    if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId))
                    {
                        _documentIdToHierarchyEventsCookieMap.Add(documentId, cookie);
                    }
                }
            }

            private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId)
            {
                var hostDocument = _workspace.GetHostDocument(documentId);
                var itemId = hostDocument.GetItemId();
                if (itemId == (uint)VSConstants.VSITEMID.Nil)
                {
                    // the document has been removed from the solution
                    return;
                }

1250
                var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId);
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
                if (sharedHierarchy != null)
                {
                    uint cookie;
                    if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out cookie))
                    {
                        var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie);
                        _documentIdToHierarchyEventsCookieMap.Remove(documentId);
                    }
                }
            }

            private void RegisterPrimarySolutionForPersistentStorage(SolutionId solutionId)
            {
                var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService;
                if (service == null)
                {
                    return;
                }

                service.RegisterPrimarySolution(solutionId);
            }

            private void UnregisterPrimarySolutionForPersistentStorage(SolutionId solutionId, bool synchronousShutdown)
            {
                var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService;
                if (service == null)
                {
                    return;
                }

                service.UnregisterPrimarySolution(solutionId, synchronousShutdown);
            }

            void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId)
            {
                _workspace.OnDocumentRemoved(documentId);
            }

            void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference)
            {
                _workspace.OnMetadataReferenceAdded(projectId, metadataReference);
            }

            void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference)
            {
                _workspace.OnMetadataReferenceRemoved(projectId, metadataReference);
            }

            void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo)
            {
1301 1302 1303 1304
                using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project"))
                {
                    _workspace.OnProjectAdded(projectInfo);
                }
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
            }

            void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
            {
                _workspace.OnProjectReferenceAdded(projectId, projectReference);
            }

            void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
            {
                _workspace.OnProjectReferenceRemoved(projectId, projectReference);
            }

            void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId)
            {
1319 1320 1321 1322
                using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project"))
                {
                    _workspace.OnProjectRemoved(projectId);
                }
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
            }

            void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo)
            {
                RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id);

                _workspace.OnSolutionAdded(solutionInfo);
            }

            void IVisualStudioWorkspaceHost.OnSolutionRemoved()
            {
                var solutionId = _workspace.CurrentSolution.Id;

                _workspace.OnSolutionRemoved();
                _workspace.ClearReferenceCache();

                UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false);
            }

            void IVisualStudioWorkspaceHost.ClearSolution()
            {
                _workspace.ClearSolution();
                _workspace.ClearReferenceCache();
            }

            void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id)
            {
                _workspace.OnDocumentTextUpdatedOnDisk(id);
            }

            void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName)
            {
                _workspace.OnAssemblyNameChanged(id, assemblyName);
            }

            void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath)
            {
                _workspace.OnOutputFilePathChanged(id, outputFilePath);
            }

            void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath)
            {
                _workspace.OnProjectNameChanged(projectId, name, filePath);
            }

            void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
            {
                _workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference);
            }

            void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
            {
                _workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference);
            }

            void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo additionalDocumentInfo)
            {
                _workspace.OnAdditionalDocumentAdded(additionalDocumentInfo);
            }

            void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId additionalDocumentId)
            {
                _workspace.OnAdditionalDocumentRemoved(additionalDocumentId);
            }

            void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext)
            {
                _workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext);
            }

            void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader)
            {
                _workspace.OnAdditionalDocumentClosed(documentId, loader);
            }

            void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id)
            {
                _workspace.OnAdditionalDocumentTextUpdatedOnDisk(id);
            }

1403 1404 1405 1406 1407
            void IVisualStudioWorkspaceHost2.OnHasAllInformation(ProjectId projectId, bool hasAllInformation)
            {
                _workspace.OnHasAllInformationChanged(projectId, hasAllInformation);
            }

1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
            void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange()
            {
                UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true);
            }

            void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange()
            {
                var solutionId = _workspace.CurrentSolution.Id;

                _workspace.ProjectTracker.UpdateSolutionProperties(solutionId);
                RegisterPrimarySolutionForPersistentStorage(solutionId);
            }
        }
    }
}