From 16866018555eab0dca866a446bf4d1be1cbf00e0 Mon Sep 17 00:00:00 2001 From: reduckted Date: Sat, 14 Nov 2026 20:22:02 +1000 Subject: [PATCH 1/4] Refactoring of options, and added a property to indicate when the filter service is filtering. --- .../Commands/FilterProjectsCommand.cs | 30 +-- .../ProjectFilter/Services/FilterBehavior.cs | 39 +++ .../ProjectFilter/Services/FilterOptions.cs | 21 +- .../ProjectFilter/Services/FilterService.cs | 225 +++++++++++------- .../ProjectFilter/Services/IFilterService.cs | 4 + .../Services/SolutionLoadObserver.cs | 2 +- source/ProjectFilter/UI/FilterDialogResult.cs | 24 ++ .../ProjectFilter/UI/FilterDialogViewModel.cs | 13 +- .../Services/FilterOptionsTests.cs | 21 +- .../Services/FilterServiceTests.cs | 130 ++++++---- .../UI/FilterDialogViewModelTests.cs | 25 -- 11 files changed, 313 insertions(+), 221 deletions(-) create mode 100644 source/ProjectFilter/Services/FilterBehavior.cs create mode 100644 source/ProjectFilter/UI/FilterDialogResult.cs diff --git a/source/ProjectFilter/Commands/FilterProjectsCommand.cs b/source/ProjectFilter/Commands/FilterProjectsCommand.cs index 3007d9a..ccd64e9 100644 --- a/source/ProjectFilter/Commands/FilterProjectsCommand.cs +++ b/source/ProjectFilter/Commands/FilterProjectsCommand.cs @@ -37,6 +37,7 @@ protected async override Task ExecuteAsync(OleMenuCmdEventArgs e) { IExtensionSettings globalSettings; ISolutionSettingsManager solutionSettingsManager; SolutionSettings? solutionSettings; + FilterBehavior behavior; FilterDialogViewModel vm; FilterDialog dialog; bool result; @@ -54,19 +55,14 @@ protected async override Task ExecuteAsync(OleMenuCmdEventArgs e) { solutionSettingsManager = await VS.GetRequiredServiceAsync(); solutionSettings = await solutionSettingsManager.GetSettingsAsync(); + behavior = new FilterBehavior(solutionSettings, globalSettings); + vm = new FilterDialogViewModel(hierarchyFactory, textFilterFactory, solutionSettings?.Nodes) { - // Initialize the settings with the settings that were last - // used for this solution. If this solution hasn't been - // filtered before, then we'll use the global settings. - LoadProjectDependencies = solutionSettings?.LoadProjectDependencies ?? globalSettings.LoadProjectDependencies, UseRegularExpressions = solutionSettings?.UseRegularExpressions ?? globalSettings.UseRegularExpressions, - ExpandLoadedProjects = solutionSettings?.ExpandLoadedProjects ?? globalSettings.ExpandLoadedProjects, - HideSolutionFoldersWithoutLoadedProjects = - solutionSettings?.HideSolutionFoldersWithoutLoadedProjects ?? - globalSettings.HideSolutionFoldersWithoutLoadedProjects, - HideSolutionFoldersWithOnlyFiles = - solutionSettings?.HideSolutionFoldersWithOnlyFiles ?? - globalSettings.HideSolutionFoldersWithOnlyFiles + LoadProjectDependencies = behavior.LoadProjectDependencies, + ExpandLoadedProjects = behavior.ExpandLoadedProjects, + HideSolutionFoldersWithoutLoadedProjects = behavior.HideSolutionFoldersWithoutLoadedProjects, + HideSolutionFoldersWithOnlyFiles = behavior.HideSolutionFoldersWithOnlyFiles }; dialog = new FilterDialog { @@ -79,8 +75,8 @@ protected async override Task ExecuteAsync(OleMenuCmdEventArgs e) { // was cancelled. This saves the user from having to re-apply // the settings the next time they open the dialog. solutionSettings = new SolutionSettings { - LoadProjectDependencies = vm.LoadProjectDependencies, UseRegularExpressions = vm.UseRegularExpressions, + LoadProjectDependencies = vm.LoadProjectDependencies, ExpandLoadedProjects = vm.ExpandLoadedProjects, HideSolutionFoldersWithoutLoadedProjects = vm.HideSolutionFoldersWithoutLoadedProjects, HideSolutionFoldersWithOnlyFiles = vm.HideSolutionFoldersWithOnlyFiles @@ -91,8 +87,8 @@ protected async override Task ExecuteAsync(OleMenuCmdEventArgs e) { // Also save the settings to the global settings so that the same settings // can be used for solutions that don't have their own settings yet. - globalSettings.LoadProjectDependencies = solutionSettings.LoadProjectDependencies; globalSettings.UseRegularExpressions = solutionSettings.UseRegularExpressions; + globalSettings.LoadProjectDependencies = solutionSettings.LoadProjectDependencies; globalSettings.ExpandLoadedProjects = solutionSettings.ExpandLoadedProjects; globalSettings.HideSolutionFoldersWithoutLoadedProjects = solutionSettings.HideSolutionFoldersWithoutLoadedProjects ?? false; @@ -101,8 +97,12 @@ protected async override Task ExecuteAsync(OleMenuCmdEventArgs e) { await globalSettings.SaveAsync(); - if (result) { - return vm.Result; + if (result && (vm.Result is not null)) { + return new FilterOptions( + vm.Result.ProjectsToLoad, + vm.Result.ProjectsToUnload, + new FilterBehavior(solutionSettings, globalSettings) + ); } return null; diff --git a/source/ProjectFilter/Services/FilterBehavior.cs b/source/ProjectFilter/Services/FilterBehavior.cs new file mode 100644 index 0000000..11fee29 --- /dev/null +++ b/source/ProjectFilter/Services/FilterBehavior.cs @@ -0,0 +1,39 @@ +namespace ProjectFilter.Services; + + +public class FilterBehavior { + + public FilterBehavior( + SolutionSettings? solutionSettings, + IExtensionSettings globalSettings + ) { + // Initialize the settings with the settings that were last + // used for this solution. If this solution hasn't been + // filtered before, then we'll use the global settings. + + LoadProjectDependencies = solutionSettings?.LoadProjectDependencies ?? globalSettings.LoadProjectDependencies; + + ExpandLoadedProjects = solutionSettings?.ExpandLoadedProjects ?? globalSettings.ExpandLoadedProjects; + + HideSolutionFoldersWithoutLoadedProjects = + solutionSettings?.HideSolutionFoldersWithoutLoadedProjects ?? + globalSettings.HideSolutionFoldersWithoutLoadedProjects; + + HideSolutionFoldersWithOnlyFiles = + solutionSettings?.HideSolutionFoldersWithOnlyFiles ?? + globalSettings.HideSolutionFoldersWithOnlyFiles; + } + + + public bool LoadProjectDependencies { get; } + + + public bool ExpandLoadedProjects { get; } + + + public bool HideSolutionFoldersWithoutLoadedProjects { get; } + + + public bool HideSolutionFoldersWithOnlyFiles { get; } + +} diff --git a/source/ProjectFilter/Services/FilterOptions.cs b/source/ProjectFilter/Services/FilterOptions.cs index e31774b..159fdb0 100644 --- a/source/ProjectFilter/Services/FilterOptions.cs +++ b/source/ProjectFilter/Services/FilterOptions.cs @@ -10,17 +10,11 @@ public class FilterOptions { public FilterOptions( IEnumerable projectsToLoad, IEnumerable projectsToUnload, - bool loadProjectDependencies, - bool expandLoadedProjects, - bool hideSolutionFoldersWithoutLoadedProjects, - bool hideSolutionFoldersWithOnlyFiles + FilterBehavior behavior ) { ProjectsToLoad = [.. projectsToLoad]; ProjectsToUnload = [.. projectsToUnload]; - LoadProjectDependencies = loadProjectDependencies; - ExpandLoadedProjects = expandLoadedProjects; - HideSolutionFoldersWithoutLoadedProjects = hideSolutionFoldersWithoutLoadedProjects; - HideSolutionFoldersWithOnlyFiles = hideSolutionFoldersWithOnlyFiles; + Behavior = behavior; } @@ -30,15 +24,6 @@ bool hideSolutionFoldersWithOnlyFiles public IReadOnlyCollection ProjectsToUnload { get; } - public bool LoadProjectDependencies { get; } - - - public bool ExpandLoadedProjects { get; } - - - public bool HideSolutionFoldersWithoutLoadedProjects { get; } - - - public bool HideSolutionFoldersWithOnlyFiles { get; } + public FilterBehavior Behavior { get; } } diff --git a/source/ProjectFilter/Services/FilterService.cs b/source/ProjectFilter/Services/FilterService.cs index 551d817..009c48b 100644 --- a/source/ProjectFilter/Services/FilterService.cs +++ b/source/ProjectFilter/Services/FilterService.cs @@ -9,6 +9,7 @@ using System.IO; using System.Linq; using System.Runtime.InteropServices; +using System.Threading; using System.Threading.Tasks; using Task = System.Threading.Tasks.Task; @@ -18,6 +19,15 @@ namespace ProjectFilter.Services; public partial class FilterService : IFilterService { + private readonly SemaphoreSlim _synchronizer = new(1, 1); + private int _isFilteringStack; + + + public bool IsFiltering { + get => _isFilteringStack > 0; + } + + public async Task ApplyAsync(FilterOptions options) { ThreadedWaitDialogProgressData progress; IWaitDialogFactory waitDialogFactory; @@ -37,109 +47,132 @@ public async Task ApplyAsync(FilterOptions options) { progress = new ThreadedWaitDialogProgressData("Filtering projects...", "Getting ready...", "", true); using (var dialog = await waitDialogFactory.CreateAsync(Vsix.Name, progress)) { - IEnumerable projectsToUnload; - IEnumerable projectsToLoad; - State state; - ISolutionExplorer solutionExplorer; - IEnumerable expandedFolders; - - - state = new State( - dialog, - progress, - (IVsSolution4)await VS.Services.GetSolutionAsync() - ); - - solutionExplorer = await VS.GetRequiredServiceAsync(); - - // If we are not going to expand the loaded projects, then we will need to collapse - // them instead, because Visual Studio seems to automatically expand them and - // the folders they are in. To work out what should be collapsed after the - // projects are loaded, we first need to know what was originally expanded. - if (!options.ExpandLoadedProjects) { - expandedFolders = await solutionExplorer.GetExpandedFoldersAsync(); - } else { - expandedFolders = new HashSet(); - } + // Project dependencies can be loaded in response to projects being loaded + // outside of this filter service. To prevent that processing from running + // at the same time as a user's request to filter the projects, we'll use + // a semaphore to ensure that only one of those operations can run at a time. + await _synchronizer.WaitAsync(); + _isFilteringStack += 1; + + try { + IEnumerable projectsToUnload; + IEnumerable projectsToLoad; + State state; + ISolutionExplorer solutionExplorer; + IEnumerable expandedFolders; + + + await LogInfoAsync("Starting filtering."); - projectsToUnload = [.. options.ProjectsToUnload]; - projectsToLoad = [.. options.ProjectsToLoad]; - - // Work out which projects actually need to be unloaded - // so that we can calculate an accurate progress. If a - // project is already unloaded, then we can skip it. - state.AddProjectsToUnload(projectsToUnload.Where((x) => IsLoaded(state.Solution, x))); - - // Do the same for the projects that we need to load. We may add - // to this list as we load projects and find their dependencies, - // but we need to start with a known list so that we can give a - // reasonable initial estimation for the progress. Start with the - // projects that we were asked to load that are not already loaded. - state.AddProjectsToLoad(projectsToLoad.Where((x) => !IsLoaded(state.Solution, x))); - - // If we're loading dependencies, then we can add the unloaded - // dependencies of the loaded projects that were requested to be loaded. - if (options.LoadProjectDependencies) { - foreach (var identifier in projectsToLoad.Where((x) => IsLoaded(state.Solution, x))) { - foreach (var dependency in await GetProjectDependenciesAsync(identifier, state)) { - if (!IsLoaded(state.Solution, dependency)) { - state.AddProjectToLoad(dependency); + state = new State( + dialog, + progress, + (IVsSolution4)await VS.Services.GetSolutionAsync() + ); + + solutionExplorer = await VS.GetRequiredServiceAsync(); + + // If we are not going to expand the loaded projects, then we will need to collapse + // them instead, because Visual Studio seems to automatically expand them and + // the folders they are in. To work out what should be collapsed after the + // projects are loaded, we first need to know what was originally expanded. + if (!options.Behavior.ExpandLoadedProjects) { + expandedFolders = await solutionExplorer.GetExpandedFoldersAsync(); + } else { + expandedFolders = new HashSet(); + } + + projectsToUnload = [.. options.ProjectsToUnload]; + projectsToLoad = [.. options.ProjectsToLoad]; + + // Work out which projects actually need to be unloaded + // so that we can calculate an accurate progress. If a + // project is already unloaded, then we can skip it. + state.AddProjectsToUnload(projectsToUnload.Where((x) => IsLoaded(state.Solution, x))); + + // Do the same for the projects that we need to load. We may add + // to this list as we load projects and find their dependencies, + // but we need to start with a known list so that we can give a + // reasonable initial estimation for the progress. Start with the + // projects that we were asked to load that are not already loaded. + state.AddProjectsToLoad(projectsToLoad.Where((x) => !IsLoaded(state.Solution, x))); + + // If we're loading dependencies, then we can add the unloaded + // dependencies of the loaded projects that were requested to be loaded. + if (options.Behavior.LoadProjectDependencies) { + foreach (var identifier in projectsToLoad.Where((x) => IsLoaded(state.Solution, x))) { + foreach (var dependency in await GetProjectDependenciesAsync(identifier, state)) { + if (!IsLoaded(state.Solution, dependency)) { + state.AddProjectToLoad(dependency); + } } } } - } - // Now we can start loading and unloading projects. We're - // filtering projects because the user wants to keep the number - // of projects loaded to a minimum, so start by unloading the - // requested projects before we start loading any new projects. - foreach (var identifier in projectsToUnload) { - if (state.IsCancellationRequested) { - break; + // Now we can start loading and unloading projects. We're + // filtering projects because the user wants to keep the number + // of projects loaded to a minimum, so start by unloading the + // requested projects before we start loading any new projects. + foreach (var identifier in projectsToUnload) { + if (state.IsCancellationRequested) { + break; + } + + await UnloadProjectAsync(identifier, state); } - await UnloadProjectAsync(identifier, state); - } + foreach (var identifier in projectsToLoad) { + if (state.IsCancellationRequested) { + break; + } - foreach (var identifier in projectsToLoad) { - if (state.IsCancellationRequested) { - break; + await LoadProjectAsync(identifier, options.Behavior.LoadProjectDependencies, state); } - await LoadProjectAsync(identifier, options.LoadProjectDependencies, state); - } + // Let Visual Studio catch up with the changes we made before we do + // anything else. If we don't do this, then Solution Explorer can + // end up hiding projects that we just loaded (though, that only seems + // to be a problem if you've loaded a Solution Filter ¯\_(ツ)_/¯). + await Task.Yield(); + + // Even if we've been cancelled, we'll still hide the unloaded + // projects and show the loaded projects. This prevents us from + // getting into a state where we've loaded some projects but they + // remain hidden because the user cancelled half way through. + await solutionExplorer.HideUnloadedProjectsAsync(); + + if ( + options.Behavior.HideSolutionFoldersWithoutLoadedProjects || + options.Behavior.HideSolutionFoldersWithOnlyFiles + ) { + // Hiding unloaded projects will hide the solution folders that those hidden projects + // are in as long as there is nothing else in those folders. If all of the projects + // in a solution folder have been unloaded, but the folder contains other solution + // item (like a readme file or editorconfig file), the folder will not be hidden. + // So when we want to hide solution files without loaded projects, or hide solution + // folders that only contain files, then we need to hide those folders ourselves. + await solutionExplorer.HideSolutionFoldersAsync( + options.Behavior.HideSolutionFoldersWithoutLoadedProjects, + options.Behavior.HideSolutionFoldersWithOnlyFiles + ); + } - // Let Visual Studio catch up with the changes we made before we do - // anything else. If we don't do this, then Solution Explorer can - // end up hiding projects that we just loaded (though, that only seems - // to be a problem if you've loaded a Solution Filter ¯\_(ツ)_/¯). - await Task.Yield(); - - // Even if we've been cancelled, we'll still hide the unloaded - // projects and show the loaded projects. This prevents us from - // getting into a state where we've loaded some projects but they - // remain hidden because the user cancelled half way through. - await solutionExplorer.HideUnloadedProjectsAsync(); - - if (options.HideSolutionFoldersWithoutLoadedProjects || options.HideSolutionFoldersWithOnlyFiles) { - // Hiding unloaded projects will hide the solution folders that those hidden projects - // are in as long as there is nothing else in those folders. If all of the projects - // in a solution folder have been unloaded, but the folder contains other solution - // item (like a readme file or editorconfig file), the folder will not be hidden. - // So when we want to hide solution files without loaded projects, or hide solution - // folders that only contain files, then we need to hide those folders ourselves. - await solutionExplorer.HideSolutionFoldersAsync( - options.HideSolutionFoldersWithoutLoadedProjects, - options.HideSolutionFoldersWithOnlyFiles - ); - } + // Expand the projects if we are supposed to. For some reason, Visual Studio seems to expand + // the projects anyway, so if we are not supposed to expand them, then we will collapse them. + if (options.Behavior.ExpandLoadedProjects) { + await solutionExplorer.ExpandAsync(state.GetLoadedProjects()); - // Expand the projects if we are supposed to. For some reason, Visual Studio seems to expand - // the projects anyway, so if we are not supposed to expand them, then we will collapse them. - if (options.ExpandLoadedProjects) { - await solutionExplorer.ExpandAsync(state.GetLoadedProjects()); - } else { - await solutionExplorer.CollapseAsync(await GetProjectsToCollapseAsync(solutionExplorer, expandedFolders, state)); + } else { + await solutionExplorer.CollapseAsync( + await GetProjectsToCollapseAsync(solutionExplorer, expandedFolders, state) + ); + } + + await LogInfoAsync("Completed filtering."); + + } finally { + _isFilteringStack -= 1; + _synchronizer.Release(); } } } @@ -404,4 +437,14 @@ private static async Task LogFailureAsync(string message, Exception? ex) { await logger.WriteLineAsync($"{message} {exceptionMessage}"); } + + private static async Task LogInfoAsync(string message) { + ILogger logger; + + + logger = await VS.GetRequiredServiceAsync(); + + await logger.WriteLineAsync(message); + } + } diff --git a/source/ProjectFilter/Services/IFilterService.cs b/source/ProjectFilter/Services/IFilterService.cs index e7984a0..71860c0 100644 --- a/source/ProjectFilter/Services/IFilterService.cs +++ b/source/ProjectFilter/Services/IFilterService.cs @@ -1,3 +1,4 @@ +using System; using System.Runtime.InteropServices; using System.Threading.Tasks; @@ -8,6 +9,9 @@ namespace ProjectFilter.Services; [Guid("ac90e7af-8562-37d5-8ccc-9d59e22be32b")] public interface IFilterService { + public bool IsFiltering { get; } + + Task ApplyAsync(FilterOptions options); } diff --git a/source/ProjectFilter/Services/SolutionLoadObserver.cs b/source/ProjectFilter/Services/SolutionLoadObserver.cs index 4588dcf..6de0611 100644 --- a/source/ProjectFilter/Services/SolutionLoadObserver.cs +++ b/source/ProjectFilter/Services/SolutionLoadObserver.cs @@ -46,7 +46,7 @@ private static async Task HideUnloadedProjectsInSolutionExplorerAsync() { // If we know for sure that Solution Explorer is empty, then wait // a bit and try again. If we know it's not empty then we can hide // the unloaded projects. If we don't know if it's empty or not, then - // we'll still try to hide the unloaded projects because if we don't now, + // we'll still try to hide the unloaded projects because if we don't know, // then we may never know, and then we'd end up looping here forever. if (empty.GetValueOrDefault()) { await Task.Delay(1000); diff --git a/source/ProjectFilter/UI/FilterDialogResult.cs b/source/ProjectFilter/UI/FilterDialogResult.cs new file mode 100644 index 0000000..1f21451 --- /dev/null +++ b/source/ProjectFilter/UI/FilterDialogResult.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; + + +namespace ProjectFilter.UI; + + +public class FilterDialogResult { + + public FilterDialogResult( + IEnumerable projectsToLoad, + IEnumerable projectsToUnload + ) { + ProjectsToLoad = [.. projectsToLoad]; + ProjectsToUnload = [.. projectsToUnload]; + } + + + public IReadOnlyCollection ProjectsToLoad { get; } + + + public IReadOnlyCollection ProjectsToUnload { get; } + +} diff --git a/source/ProjectFilter/UI/FilterDialogViewModel.cs b/source/ProjectFilter/UI/FilterDialogViewModel.cs index e556ffe..f4fd349 100644 --- a/source/ProjectFilter/UI/FilterDialogViewModel.cs +++ b/source/ProjectFilter/UI/FilterDialogViewModel.cs @@ -26,7 +26,7 @@ public sealed class FilterDialogViewModel : ObservableObject, IVsWindowSearch { private IVsWindowSearchHost? _searchHost; private HierarchyTreeViewItemCollection _items; private bool _loadProjectDependencies; - private FilterOptions? _result; + private FilterDialogResult? _result; private Visibility _loadingVisibility; private Visibility _loadedVisibility; private bool _useRegularExpressions; @@ -230,7 +230,7 @@ public HierarchyTreeViewItemCollection Items { public DelegateCommand AcceptCommand { get; } - public FilterOptions? Result { + public FilterDialogResult? Result { get => _result; private set { SetProperty(ref _result, value); } } @@ -328,14 +328,7 @@ from node in Items.GetFullHierarchy() select (node.Identifier, Load: node.IsChecked.GetValueOrDefault()) ).ToLookup((x) => x.Load, (x) => x.Identifier); - Result = new FilterOptions( - projects[true], - projects[false], - LoadProjectDependencies, - ExpandLoadedProjects, - _hideSolutionFoldersWithoutLoadedProjects, - _hideSolutionFoldersWithOnlyFiles - ); + Result = new FilterDialogResult(projects[true], projects[false]); } diff --git a/tests/ProjectFilter.UnitTests/Services/FilterOptionsTests.cs b/tests/ProjectFilter.UnitTests/Services/FilterOptionsTests.cs index 4854100..aa9298e 100644 --- a/tests/ProjectFilter.UnitTests/Services/FilterOptionsTests.cs +++ b/tests/ProjectFilter.UnitTests/Services/FilterOptionsTests.cs @@ -1,3 +1,4 @@ +using NSubstitute; using System; using System.Collections.Generic; using Xunit; @@ -21,30 +22,24 @@ public void StoresCopiesOfTheArguments() { FilterOptions options; List loaded; List unloaded; + IExtensionSettings globalSettings; + FilterBehavior behavior; loaded = [ProjectA, ProjectB]; unloaded = [Project1, Project2]; - options = new FilterOptions(loaded, unloaded, true, false, true, false); + globalSettings = Substitute.For(); + behavior = new FilterBehavior(null, globalSettings); + + options = new FilterOptions(loaded, unloaded, behavior); loaded.Add(ProjectC); unloaded.Add(Project3); Assert.Equal([ProjectA, ProjectB], options.ProjectsToLoad); Assert.Equal([Project1, Project2], options.ProjectsToUnload); - - Assert.True(options.LoadProjectDependencies); - Assert.False(options.ExpandLoadedProjects); - Assert.True(options.HideSolutionFoldersWithoutLoadedProjects); - Assert.False(options.HideSolutionFoldersWithOnlyFiles); - - // Flip the booleans to ensure they are stored correctly. - options = new FilterOptions(loaded, unloaded, false, true, false, true); - Assert.False(options.LoadProjectDependencies); - Assert.True(options.ExpandLoadedProjects); - Assert.False(options.HideSolutionFoldersWithoutLoadedProjects); - Assert.True(options.HideSolutionFoldersWithOnlyFiles); + Assert.Same(behavior, options.Behavior); } } diff --git a/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs b/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs index 4704c04..72a0410 100644 --- a/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs +++ b/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs @@ -49,10 +49,7 @@ await ApplyAsync( new FilterOptions( [ProjectAlpha, ProjectBeta], [], - false, - false, - false, - false + CreateBehavior() ) ); @@ -86,10 +83,7 @@ await ApplyAsync( new FilterOptions( [], [ProjectAlpha, ProjectBeta], - false, - false, - false, - false + CreateBehavior() ) ); @@ -123,10 +117,7 @@ await ApplyAsync( new FilterOptions( [ProjectBeta], [ProjectAlpha], - false, - false, - false, - false + CreateBehavior() ) ); @@ -160,10 +151,7 @@ await ApplyAsync( new FilterOptions( [ProjectAlpha], [], - true, - false, - false, - false + CreateBehavior(loadDependencies: true) ) ); @@ -197,10 +185,7 @@ await ApplyAsync( new FilterOptions( [ProjectAlpha], [], - false, - false, - false, - false + CreateBehavior(loadDependencies: false) ) ); @@ -232,10 +217,7 @@ await ApplyAsync( new FilterOptions( [ProjectAlpha], [ProjectBeta], - true, - false, - false, - false + CreateBehavior(loadDependencies: true) ) ); @@ -267,10 +249,7 @@ await ApplyAsync( new FilterOptions( [ProjectAlpha], [], - true, - false, - false, - false + CreateBehavior(loadDependencies: true) ) ); @@ -303,10 +282,7 @@ await ApplyAsync( new FilterOptions( [ProjectAlpha], [], - true, - false, - false, - false + CreateBehavior(loadDependencies: true) ) ); @@ -347,10 +323,7 @@ await ApplyAsync( new FilterOptions( [ProjectAlpha], [], - false, - true, - false, - false + CreateBehavior(expandLoadedProjects: true) ) ); @@ -398,10 +371,7 @@ await ApplyAsync( new FilterOptions( [ProjectAlpha, ProjectGamma], [], - false, - false, - false, - false + CreateBehavior(expandLoadedProjects: false) ) ); @@ -435,10 +405,7 @@ await ApplyAsync( new FilterOptions( [], [ProjectAlpha], - false, - true, - false, - false + CreateBehavior(expandLoadedProjects: true) ) ); @@ -480,10 +447,10 @@ await ApplyAsync( new FilterOptions( [ProjectAlpha], [], - false, - false, - hideSolutionFoldersWithoutLoadedProjects, - hideSolutionFoldersWithOnlyFiles + CreateBehavior( + hideSolutionFoldersWithoutLoadedProjects: hideSolutionFoldersWithoutLoadedProjects, + hideSolutionFoldersWithOnlyFiles: hideSolutionFoldersWithOnlyFiles + ) ) ); @@ -498,6 +465,54 @@ await solutionExplorer.Received(1).HideSolutionFoldersAsync( } + [Fact] + public async Task IndicatesWhenFilteringIsOccurring() { + List isFiltering; + ISolutionExplorer solutionExplorer; + FilterService? service; + + + isFiltering = []; + service = null; + + solutionExplorer = Substitute.For(); + solutionExplorer.ExpandAsync(Arg.Any>()).Returns((_) => { + isFiltering.Add(service?.IsFiltering ?? false); + return Task.CompletedTask; + }); + + Setup( + $@" + + + + + + ", + solutionExplorer: solutionExplorer + ); + + service= CreateService(); + isFiltering.Add(service.IsFiltering); + + await service.ApplyAsync( + new FilterOptions( + [], + [ProjectAlpha], + CreateBehavior(expandLoadedProjects: true) + ) + ); + + isFiltering.Add(service.IsFiltering); + + Assert.Equal( + [false, true, false], + isFiltering + ); + } + + + private void Setup(string data, ISolutionExplorer? solutionExplorer = null) { IVsSolution solution; IVsSolutionBuildManager2 buildManager; @@ -536,6 +551,25 @@ private static IWaitDialogFactory MockWaitDialogFactory() { } + private static FilterBehavior CreateBehavior( + bool loadDependencies = false, + bool expandLoadedProjects = false, + bool hideSolutionFoldersWithoutLoadedProjects = false, + bool hideSolutionFoldersWithOnlyFiles = false + ) { + IExtensionSettings globalSettings; + + + globalSettings = Substitute.For(); + globalSettings.LoadProjectDependencies.Returns(loadDependencies); + globalSettings.ExpandLoadedProjects.Returns(expandLoadedProjects); + globalSettings.HideSolutionFoldersWithoutLoadedProjects.Returns(hideSolutionFoldersWithoutLoadedProjects); + globalSettings.HideSolutionFoldersWithOnlyFiles.Returns(hideSolutionFoldersWithOnlyFiles); + + return new FilterBehavior(null, globalSettings); + } + + private async Task ApplyAsync(FilterOptions options) { await CreateService().ApplyAsync(options); } diff --git a/tests/ProjectFilter.UnitTests/UI/FilterDialogViewModelTests.cs b/tests/ProjectFilter.UnitTests/UI/FilterDialogViewModelTests.cs index d75f2e3..cfaae8a 100644 --- a/tests/ProjectFilter.UnitTests/UI/FilterDialogViewModelTests.cs +++ b/tests/ProjectFilter.UnitTests/UI/FilterDialogViewModelTests.cs @@ -646,31 +646,6 @@ public class AcceptCommandProperty : TestBase { public AcceptCommandProperty(GlobalServiceProvider serviceProvider) : base(serviceProvider) { } - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task SetsOptionsFromProperties(bool loadDependencies) { - IEnumerable hierarchy; - FilterDialogViewModel vm; - - - hierarchy = [ - CreateNode(name: "a"), - CreateNode(name: "b") - ]; - - vm = CreateViewModel(hierarchy); - await vm.OnLoadedAsync(SearchHost); - - vm.LoadProjectDependencies = loadDependencies; - - vm.AcceptCommand.Execute(null); - - Assert.NotNull(vm.Result); - Assert.Equal(loadDependencies, vm.Result!.LoadProjectDependencies); - } - - [Fact] public async Task SetsProjectsBasedOnCheckedState() { IEnumerable hierarchy; From bc9ea5453e05f959bd24396b55c3b3706b49e101 Mon Sep 17 00:00:00 2001 From: reduckted Date: Sat, 14 Nov 2026 22:17:33 +1000 Subject: [PATCH 2/4] Allowed the filter service to apply changes in the background. --- .../Commands/FilterProjectsCommand.cs | 2 +- .../ProjectFilter/Services/FilterService.cs | 113 ++++++++------ .../ProjectFilter/Services/IFilterService.cs | 2 +- .../Services/IWaitDialogFactory.cs | 7 +- .../Services/WaitDialogFactory.cs | 9 +- .../Services/FilterServiceTests.cs | 142 ++++++++++++++++-- 6 files changed, 207 insertions(+), 68 deletions(-) diff --git a/source/ProjectFilter/Commands/FilterProjectsCommand.cs b/source/ProjectFilter/Commands/FilterProjectsCommand.cs index ccd64e9..331a4e2 100644 --- a/source/ProjectFilter/Commands/FilterProjectsCommand.cs +++ b/source/ProjectFilter/Commands/FilterProjectsCommand.cs @@ -25,7 +25,7 @@ protected async override Task ExecuteAsync(OleMenuCmdEventArgs e) { options = await GetOptionsAsync(); if (options is not null) { - await filterService.ApplyAsync(options); + await filterService.ApplyAsync(options, false); } } diff --git a/source/ProjectFilter/Services/FilterService.cs b/source/ProjectFilter/Services/FilterService.cs index 009c48b..3d66144 100644 --- a/source/ProjectFilter/Services/FilterService.cs +++ b/source/ProjectFilter/Services/FilterService.cs @@ -28,11 +28,7 @@ public bool IsFiltering { } - public async Task ApplyAsync(FilterOptions options) { - ThreadedWaitDialogProgressData progress; - IWaitDialogFactory waitDialogFactory; - - + public async Task ApplyAsync(FilterOptions options, bool background) { if (options is null) { throw new ArgumentNullException(nameof(options)); } @@ -43,18 +39,30 @@ public async Task ApplyAsync(FilterOptions options) { return; } - waitDialogFactory = await VS.GetRequiredServiceAsync(); - progress = new ThreadedWaitDialogProgressData("Filtering projects...", "Getting ready...", "", true); + // Project dependencies can be loaded in response to projects being loaded + // outside of this filter service. To prevent that processing from running + // at the same time as a user's request to filter the projects, we'll use + // a semaphore to ensure that only one of those operations can run at a time. + await _synchronizer.WaitAsync(); + _isFilteringStack += 1; - using (var dialog = await waitDialogFactory.CreateAsync(Vsix.Name, progress)) { - // Project dependencies can be loaded in response to projects being loaded - // outside of this filter service. To prevent that processing from running - // at the same time as a user's request to filter the projects, we'll use - // a semaphore to ensure that only one of those operations can run at a time. - await _synchronizer.WaitAsync(); - _isFilteringStack += 1; + try { + ThreadedWaitDialogProgressData progress; + IWaitDialogFactory waitDialogFactory; + TimeSpan delayToShowDialog; - try { + + await LogInfoAsync("Starting filtering."); + + waitDialogFactory = await VS.GetRequiredServiceAsync(); + progress = new ThreadedWaitDialogProgressData("Filtering projects...", "Getting ready...", "", true); + + // If we're trying to do this in the background, then delay the + // appearance of the dialog by a few seconds because we might + // be able to finish within that time and not interrupt the user. + delayToShowDialog = background ? TimeSpan.FromSeconds(3) : TimeSpan.Zero; + + using (var dialog = await waitDialogFactory.CreateAsync(Vsix.Name, progress, delayToShowDialog)) { IEnumerable projectsToUnload; IEnumerable projectsToLoad; State state; @@ -62,8 +70,6 @@ public async Task ApplyAsync(FilterOptions options) { IEnumerable expandedFolders; - await LogInfoAsync("Starting filtering."); - state = new State( dialog, progress, @@ -76,7 +82,9 @@ public async Task ApplyAsync(FilterOptions options) { // them instead, because Visual Studio seems to automatically expand them and // the folders they are in. To work out what should be collapsed after the // projects are loaded, we first need to know what was originally expanded. - if (!options.Behavior.ExpandLoadedProjects) { + // We can skip this if we're doing this in the background because we won't + // be changing the expanded/collapsed state of the projects in that case. + if (!options.Behavior.ExpandLoadedProjects && !background) { expandedFolders = await solutionExplorer.GetExpandedFoldersAsync(); } else { expandedFolders = new HashSet(); @@ -135,45 +143,50 @@ public async Task ApplyAsync(FilterOptions options) { // to be a problem if you've loaded a Solution Filter ¯\_(ツ)_/¯). await Task.Yield(); - // Even if we've been cancelled, we'll still hide the unloaded - // projects and show the loaded projects. This prevents us from - // getting into a state where we've loaded some projects but they - // remain hidden because the user cancelled half way through. - await solutionExplorer.HideUnloadedProjectsAsync(); - - if ( - options.Behavior.HideSolutionFoldersWithoutLoadedProjects || - options.Behavior.HideSolutionFoldersWithOnlyFiles - ) { - // Hiding unloaded projects will hide the solution folders that those hidden projects - // are in as long as there is nothing else in those folders. If all of the projects - // in a solution folder have been unloaded, but the folder contains other solution - // item (like a readme file or editorconfig file), the folder will not be hidden. - // So when we want to hide solution files without loaded projects, or hide solution - // folders that only contain files, then we need to hide those folders ourselves. - await solutionExplorer.HideSolutionFoldersAsync( - options.Behavior.HideSolutionFoldersWithoutLoadedProjects, + // The projects have been loaded or unloaded. If we're trying to + // do this in the background, then we'll skip the changes to Solution Explorer + // so that the loading is as seamless as possible. + if (!background) { + // Even if we've been cancelled, we'll still hide the unloaded + // projects and show the loaded projects. This prevents us from + // getting into a state where we've loaded some projects but they + // remain hidden because the user cancelled half way through. + await solutionExplorer.HideUnloadedProjectsAsync(); + + if ( + options.Behavior.HideSolutionFoldersWithoutLoadedProjects || options.Behavior.HideSolutionFoldersWithOnlyFiles - ); - } + ) { + // Hiding unloaded projects will hide the solution folders that those hidden projects + // are in as long as there is nothing else in those folders. If all of the projects + // in a solution folder have been unloaded, but the folder contains other solution + // item (like a readme file or editorconfig file), the folder will not be hidden. + // So when we want to hide solution files without loaded projects, or hide solution + // folders that only contain files, then we need to hide those folders ourselves. + await solutionExplorer.HideSolutionFoldersAsync( + options.Behavior.HideSolutionFoldersWithoutLoadedProjects, + options.Behavior.HideSolutionFoldersWithOnlyFiles + ); + } - // Expand the projects if we are supposed to. For some reason, Visual Studio seems to expand - // the projects anyway, so if we are not supposed to expand them, then we will collapse them. - if (options.Behavior.ExpandLoadedProjects) { - await solutionExplorer.ExpandAsync(state.GetLoadedProjects()); + // Expand the projects if we are supposed to. For some reason, Visual Studio seems to expand + // the projects anyway, so if we are not supposed to expand them, then we will collapse them. + if (options.Behavior.ExpandLoadedProjects) { + await solutionExplorer.ExpandAsync(state.GetLoadedProjects()); - } else { - await solutionExplorer.CollapseAsync( - await GetProjectsToCollapseAsync(solutionExplorer, expandedFolders, state) - ); + } else { + await solutionExplorer.CollapseAsync( + await GetProjectsToCollapseAsync(solutionExplorer, expandedFolders, state) + ); + } } await LogInfoAsync("Completed filtering."); - - } finally { - _isFilteringStack -= 1; - _synchronizer.Release(); } + + } finally { + _isFilteringStack -= 1; + _synchronizer.Release(); } } diff --git a/source/ProjectFilter/Services/IFilterService.cs b/source/ProjectFilter/Services/IFilterService.cs index 71860c0..e1bcaa9 100644 --- a/source/ProjectFilter/Services/IFilterService.cs +++ b/source/ProjectFilter/Services/IFilterService.cs @@ -12,6 +12,6 @@ public interface IFilterService { public bool IsFiltering { get; } - Task ApplyAsync(FilterOptions options); + Task ApplyAsync(FilterOptions options, bool background); } diff --git a/source/ProjectFilter/Services/IWaitDialogFactory.cs b/source/ProjectFilter/Services/IWaitDialogFactory.cs index 7a2809b..27914a2 100644 --- a/source/ProjectFilter/Services/IWaitDialogFactory.cs +++ b/source/ProjectFilter/Services/IWaitDialogFactory.cs @@ -1,4 +1,5 @@ using Microsoft.VisualStudio.Shell; +using System; using System.Runtime.InteropServices; using System.Threading.Tasks; @@ -9,6 +10,10 @@ namespace ProjectFilter.Services; [Guid("f4ce8cca-9886-3976-b64c-b1699fb7cea2")] public interface IWaitDialogFactory { - Task CreateAsync(string title, ThreadedWaitDialogProgressData progress); + Task CreateAsync( + string title, + ThreadedWaitDialogProgressData progress, + TimeSpan delayToShowDialog + ); } diff --git a/source/ProjectFilter/Services/WaitDialogFactory.cs b/source/ProjectFilter/Services/WaitDialogFactory.cs index fbc9df6..4997835 100644 --- a/source/ProjectFilter/Services/WaitDialogFactory.cs +++ b/source/ProjectFilter/Services/WaitDialogFactory.cs @@ -1,6 +1,7 @@ using Community.VisualStudio.Toolkit; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; +using System; using System.Threading.Tasks; @@ -12,7 +13,11 @@ namespace ProjectFilter.Services; /// public partial class WaitDialogFactory : IWaitDialogFactory { - public async Task CreateAsync(string title, ThreadedWaitDialogProgressData progress) { + public async Task CreateAsync( + string title, + ThreadedWaitDialogProgressData progress, + TimeSpan delayToShowDialog + ) { IVsThreadedWaitDialogFactory waitDialogFactory; @@ -20,7 +25,7 @@ public async Task CreateAsync(string title, ThreadedWaitDialogProgr waitDialogFactory = (IVsThreadedWaitDialogFactory)await VS.Services.GetThreadedWaitDialogAsync(); - return new Dialog(waitDialogFactory.StartWaitDialog(title, progress)); + return new Dialog(waitDialogFactory.StartWaitDialog(title, progress, delayToShowDialog)); } } diff --git a/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs b/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs index 72a0410..fd8879d 100644 --- a/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs +++ b/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs @@ -483,16 +483,16 @@ public async Task IndicatesWhenFilteringIsOccurring() { Setup( $@" - - - - - - ", + + + + + + ", solutionExplorer: solutionExplorer ); - service= CreateService(); + service = CreateService(); isFiltering.Add(service.IsFiltering); await service.ApplyAsync( @@ -500,7 +500,8 @@ await service.ApplyAsync( [], [ProjectAlpha], CreateBehavior(expandLoadedProjects: true) - ) + ), + false ); isFiltering.Add(service.IsFiltering); @@ -512,8 +513,121 @@ await service.ApplyAsync( } + [Fact] + public async Task DoesNotDelayWaitDialogWhenNotRunningInBackground() { + IWaitDialogFactory waitDialogFactory; + + + waitDialogFactory = MockWaitDialogFactory(); - private void Setup(string data, ISolutionExplorer? solutionExplorer = null) { + Setup( + $@" + + + + + + ", + waitDialogFactory: waitDialogFactory + ); + + await CreateService().ApplyAsync( + new FilterOptions( + [], + [ProjectAlpha], + CreateBehavior() + ), + false + ); + + await waitDialogFactory.Received(1).CreateAsync( + Arg.Any(), + Arg.Any(), + TimeSpan.Zero + ); + } + + + [Fact] + public async Task DelaysWaitDialogWhenRunningInBackground() { + IWaitDialogFactory waitDialogFactory; + + + waitDialogFactory = MockWaitDialogFactory(); + + Setup( + $@" + + + + + + ", + waitDialogFactory: waitDialogFactory + ); + + await CreateService().ApplyAsync( + new FilterOptions( + [], + [ProjectAlpha], + CreateBehavior() + ), + true + ); + + await waitDialogFactory.Received(1).CreateAsync( + Arg.Any(), + Arg.Any(), + TimeSpan.FromSeconds(3) + ); + } + + + [Fact] + public async Task DoesNotChangeSolutionExplorerWhenRunningInBackground() { + ISolutionExplorer solutionExplorer; + + + solutionExplorer = Substitute.For(); + + Setup( + $@" + + + + + + ", + solutionExplorer: solutionExplorer + ); + + await CreateService().ApplyAsync( + new FilterOptions( + [], + [ProjectAlpha], + CreateBehavior( + expandLoadedProjects: true, + hideSolutionFoldersWithOnlyFiles: true, + hideSolutionFoldersWithoutLoadedProjects: true + ) + ), + true + ); + + await solutionExplorer.DidNotReceive().ExpandAsync(Arg.Any>()); + await solutionExplorer.DidNotReceive().CollapseAsync(Arg.Any>()); + + await solutionExplorer.DidNotReceive().GetExpandedFoldersAsync(); + await solutionExplorer.DidNotReceive().HideSolutionFoldersAsync(Arg.Any(), Arg.Any()); + await solutionExplorer.DidNotReceive().HideUnloadedProjectsAsync(); + } + + + private void Setup( + string data, + ISolutionExplorer? solutionExplorer = null, + IWaitDialogFactory? waitDialogFactory = null + ) { IVsSolution solution; IVsSolutionBuildManager2 buildManager; @@ -525,7 +639,7 @@ private void Setup(string data, ISolutionExplorer? solutionExplorer = null) { AddService(solution); AddService(buildManager); - AddService(MockWaitDialogFactory()); + AddService(waitDialogFactory ?? MockWaitDialogFactory()); AddService(solutionExplorer ?? Substitute.For()); } @@ -545,7 +659,9 @@ private static IWaitDialogFactory MockWaitDialogFactory() { dialog.CancellationToken.Returns(CancellationToken.None); factory = Substitute.For(); - factory.CreateAsync(Arg.Any(), Arg.Any()).Returns(dialog); + factory + .CreateAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(dialog); return factory; } @@ -570,8 +686,8 @@ private static FilterBehavior CreateBehavior( } - private async Task ApplyAsync(FilterOptions options) { - await CreateService().ApplyAsync(options); + private async Task ApplyAsync(FilterOptions options, bool background = false) { + await CreateService().ApplyAsync(options, background); } From 036f4694e0897b8e5517f758092d504465347642 Mon Sep 17 00:00:00 2001 From: reduckted Date: Sun, 15 Nov 2026 21:06:41 +1000 Subject: [PATCH 3/4] Ensured that loaded projects are made visible when applying the filter in the background. --- source/ProjectFilter/ProjectFilterPackage.cs | 1 + .../ProjectFilter/Services/FilterService.cs | 27 ++- .../Services/ISolutionExplorer.cs | 5 +- .../Services/ProjectLoadObserver.cs | 207 ++++++++++++++++++ .../Services/SolutionExplorer.cs | 35 ++- .../Services/SolutionLoadObserver.cs | 8 +- .../Services/FilterServiceTests.cs | 12 +- 7 files changed, 281 insertions(+), 14 deletions(-) create mode 100644 source/ProjectFilter/Services/ProjectLoadObserver.cs diff --git a/source/ProjectFilter/ProjectFilterPackage.cs b/source/ProjectFilter/ProjectFilterPackage.cs index 64affcd..f8d7947 100644 --- a/source/ProjectFilter/ProjectFilterPackage.cs +++ b/source/ProjectFilter/ProjectFilterPackage.cs @@ -46,6 +46,7 @@ protected override async Task InitializeAsync(CancellationToken cancellationToke await FilterProjectsCommand.InitializeAsync(this); await SolutionLoadObserver.InitializeAsync(); + await ProjectLoadObserver.InitializeAsync(); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _solutionSettingsManager = this.GetService(); diff --git a/source/ProjectFilter/Services/FilterService.cs b/source/ProjectFilter/Services/FilterService.cs index 3d66144..167c3e3 100644 --- a/source/ProjectFilter/Services/FilterService.cs +++ b/source/ProjectFilter/Services/FilterService.cs @@ -143,15 +143,32 @@ public async Task ApplyAsync(FilterOptions options, bool background) { // to be a problem if you've loaded a Solution Filter ¯\_(ツ)_/¯). await Task.Yield(); - // The projects have been loaded or unloaded. If we're trying to - // do this in the background, then we'll skip the changes to Solution Explorer - // so that the loading is as seamless as possible. - if (!background) { + if (background) { + // We're trying to do this in the background, so we won't make too many + // visual changes. We'll leave Solution Explorer alone as much as possible, + // but one change we might need to make to it is to apply visibility to + // the projects, otherwise the projects we just loaded may remain hidden. + // + // If the command to _Show All Files_ at the solution-level is enabled, + // then it means the solution is not currently showing all files. + // That means the projects that we just loaded will remain hidden. + // On the other hand, if that command is disabled, then it means the + // solution is currently showing all files, and the projects that we just + // loaded will already be visible. If we applied project visibility, then + // it would turn off the _Show All Files_ option, which we don't want to do. + // + // So we only need to apply project visibility if the solution + // is currently not showing all files. + if (await solutionExplorer.IsSolutionShowAllFilesEnabledAsync()) { + await solutionExplorer.ApplyProjectVisibilityAsync(); + } + + } else { // Even if we've been cancelled, we'll still hide the unloaded // projects and show the loaded projects. This prevents us from // getting into a state where we've loaded some projects but they // remain hidden because the user cancelled half way through. - await solutionExplorer.HideUnloadedProjectsAsync(); + await solutionExplorer.ApplyProjectVisibilityAsync(); if ( options.Behavior.HideSolutionFoldersWithoutLoadedProjects || diff --git a/source/ProjectFilter/Services/ISolutionExplorer.cs b/source/ProjectFilter/Services/ISolutionExplorer.cs index 39ef04b..b1cd35b 100644 --- a/source/ProjectFilter/Services/ISolutionExplorer.cs +++ b/source/ProjectFilter/Services/ISolutionExplorer.cs @@ -13,7 +13,10 @@ public interface ISolutionExplorer { Task IsEmptyAsync(); - Task HideUnloadedProjectsAsync(); + Task IsSolutionShowAllFilesEnabledAsync(); + + + Task ApplyProjectVisibilityAsync(); Task HideSolutionFoldersAsync( diff --git a/source/ProjectFilter/Services/ProjectLoadObserver.cs b/source/ProjectFilter/Services/ProjectLoadObserver.cs new file mode 100644 index 0000000..1c8f431 --- /dev/null +++ b/source/ProjectFilter/Services/ProjectLoadObserver.cs @@ -0,0 +1,207 @@ +// Ignore Spelling: Unk + +using Community.VisualStudio.Toolkit; +using Microsoft.VisualStudio; +using Microsoft.VisualStudio.Shell; +using Microsoft.VisualStudio.Shell.Interop; +using Microsoft.VisualStudio.Threading; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; +using System.Windows.Threading; +using Task = System.Threading.Tasks.Task; + + +namespace ProjectFilter.Services; + + +public class ProjectLoadObserver : IVsSolutionEvents { + + private static ProjectLoadObserver? _observer; + + + private readonly IFilterService _filterService; + private readonly IVsSolution _solution; + private readonly ILogger _logger; + private readonly object _lock; + private readonly List _buffer; + private DispatcherTimer? _debouncer; + + + public static async Task InitializeAsync() { + await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + + _observer = new ProjectLoadObserver( + await VS.GetRequiredServiceAsync(), + await VS.Services.GetSolutionAsync(), + await VS.GetRequiredServiceAsync() + ); + + IVsSolution svc = await VS.GetRequiredServiceAsync(); + svc.AdviseSolutionEvents(_observer, out _); + } + + + private ProjectLoadObserver( + IFilterService filterService, + IVsSolution solution, + ILogger logger + ) { + _filterService = filterService; + _solution = solution; + _logger = logger; + + _lock = new object(); + _buffer = []; + } + + + public int OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded) { + ThreadHelper.ThrowIfNotOnUIThread(); + + // If "added" is true, it means the project has been loaded after the solution was opened. + // If it's false, it means the project was added while the solution was being loaded. + // We are only interested in projects that are loaded after the solution is opened. + if ((fAdded != 0) && (!_filterService.IsFiltering)) { + if (ErrorHandler.Succeeded(_solution.GetGuidOfProject(pHierarchy, out Guid identifier))) { + string? name; + + + pHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Name, out object obj); + name = (obj as string) ?? identifier.ToString(); + + _logger.WriteLineAsync($"Project '{name}' loaded outside of the filter service.").FireAndForget(); + + // There might be multiple projects being loaded in quick + // succession, so we debounce the processing of the new + // projects to avoid repeated interruptions to the user. + lock (_lock) { + _buffer.Add(identifier); + + _debouncer?.Stop(); + + if (_debouncer is null) { + _debouncer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) }; + _debouncer.Tick += ProcessBuffer; + } + + _debouncer.Start(); + } + } + } + + return VSConstants.S_OK; + } + + + [SuppressMessage( + "Reliability", + "VSSDK007:ThreadHelper.JoinableTaskFactory.RunAsync", + Justification = "Cannot await in an event handler." + )] + private void ProcessBuffer(object sender, EventArgs e) { + Guid[] identifiers; + + + lock (_lock) { + _debouncer?.Stop(); + identifiers = [.. _buffer]; + _buffer.Clear(); + } + + // We can't await in this method because it's an event + // handler, so we use the thread helper to run asynchronously. + ThreadHelper.JoinableTaskFactory.RunAsync(async () => { + try { + FilterBehavior behavior; + + + await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + + await _logger.WriteLineAsync("Processing projects opened outside of the filter service."); + + behavior = await GetFitlerBehaviorAsync(); + + if (!behavior.LoadProjectDependencies) { + await _logger.WriteLineAsync( + "Project dependencies should not be loaded. No additional projects will be loaded." + ); + return; + } + + await _logger.WriteLineAsync("Ensuring that dependencies are loaded..."); + + await _filterService.ApplyAsync(new FilterOptions(identifiers, [], behavior), true); + + await _logger.WriteLineAsync("Finished loading project dependencies."); + + } catch (Exception ex) when (!ErrorHandler.IsCriticalException(ex)) { + await _logger.WriteLineAsync($"Error processing projects opened outside of the filter service: {ex}"); + } + }).FireAndForget(); + } + + + private static async Task GetFitlerBehaviorAsync() { + ISolutionSettingsManager solutionSettingsManager; + SolutionSettings? solutionSettings; + IExtensionSettings globalSettings; + + + solutionSettingsManager = await VS.GetRequiredServiceAsync(); + solutionSettings = await solutionSettingsManager.GetSettingsAsync(); + + globalSettings = await VS.GetRequiredServiceAsync(); + await globalSettings.LoadAsync(); + + return new FilterBehavior(solutionSettings, globalSettings); + } + + + public int OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy) { + return VSConstants.S_OK; + } + + + public int OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel) { + return VSConstants.S_OK; + } + + + public int OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved) { + return VSConstants.S_OK; + } + + + public int OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel) { + return VSConstants.S_OK; + } + + + public int OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy) { + return VSConstants.S_OK; + } + + + public int OnAfterOpenSolution(object pUnkReserved, int fNewSolution) { + return VSConstants.S_OK; + } + + + public int OnQueryCloseSolution(object pUnkReserved, ref int pfCancel) { + return VSConstants.S_OK; + } + + + public int OnBeforeCloseSolution(object pUnkReserved) { + return VSConstants.S_OK; + } + + + public int OnAfterCloseSolution(object pUnkReserved) { + return VSConstants.S_OK; + + } + +} diff --git a/source/ProjectFilter/Services/SolutionExplorer.cs b/source/ProjectFilter/Services/SolutionExplorer.cs index e47174c..d83dede 100644 --- a/source/ProjectFilter/Services/SolutionExplorer.cs +++ b/source/ProjectFilter/Services/SolutionExplorer.cs @@ -53,7 +53,40 @@ public class SolutionExplorer : ISolutionExplorer { } - public async Task HideUnloadedProjectsAsync() { + public async Task IsSolutionShowAllFilesEnabledAsync() { + await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + + Solution? solution; + + + solution = await VS.Solutions.GetCurrentSolutionAsync(); + + if (solution is not null) { + solution.GetItemInfo(out IVsHierarchy hierarchy, out uint itemID, out var _); + + if (hierarchy is IVsUIHierarchy uiHierarchy) { + OLECMD[] command; + + + command = [new OLECMD { cmdID = (uint)KnownCommands.Project_ShowAllFiles.ID }]; + + uiHierarchy.QueryStatusCommand( + itemID, + KnownCommands.Project_ShowAllFiles.Guid, + 1, + command, + IntPtr.Zero + ); + + return (command[0].cmdf & (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED)) != 0; + } + } + + return false; + } + + + public async Task ApplyProjectVisibilityAsync() { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); Solution? solution; diff --git a/source/ProjectFilter/Services/SolutionLoadObserver.cs b/source/ProjectFilter/Services/SolutionLoadObserver.cs index 6de0611..76e0069 100644 --- a/source/ProjectFilter/Services/SolutionLoadObserver.cs +++ b/source/ProjectFilter/Services/SolutionLoadObserver.cs @@ -17,17 +17,17 @@ public static async Task InitializeAsync() { // If a solution is already open, then we need to tell the solution // observer to do whatever it does after a solution is opened. if ((await VS.Services.GetSolutionAsync()).IsOpen()) { - await HideUnloadedProjectsInSolutionExplorerAsync(); + await ApplyProjectVisibilityInSolutionExplorerAsync(); } } private static void OnAfterOpenSolution(SolutionItem? item) { - HideUnloadedProjectsInSolutionExplorerAsync().FireAndForget(); + ApplyProjectVisibilityInSolutionExplorerAsync().FireAndForget(); } - private static async Task HideUnloadedProjectsInSolutionExplorerAsync() { + private static async Task ApplyProjectVisibilityInSolutionExplorerAsync() { ISolutionExplorer solutionExplorer; @@ -55,7 +55,7 @@ private static async Task HideUnloadedProjectsInSolutionExplorerAsync() { } } - await solutionExplorer.HideUnloadedProjectsAsync(); + await solutionExplorer.ApplyProjectVisibilityAsync(); } } diff --git a/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs b/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs index fd8879d..6c46f52 100644 --- a/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs +++ b/tests/ProjectFilter.UnitTests/Services/FilterServiceTests.cs @@ -583,12 +583,17 @@ await waitDialogFactory.Received(1).CreateAsync( } - [Fact] - public async Task DoesNotChangeSolutionExplorerWhenRunningInBackground() { + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task AppliesProjectVisibilityInSolutionExplorerWhenRunningInBackgroundAndNotShowingAllFiles( + bool showAllFilesEnabled + ) { ISolutionExplorer solutionExplorer; solutionExplorer = Substitute.For(); + solutionExplorer.IsSolutionShowAllFilesEnabledAsync().Returns(showAllFilesEnabled); Setup( $@" @@ -614,12 +619,13 @@ await CreateService().ApplyAsync( true ); + await solutionExplorer.Received(showAllFilesEnabled ? 1 : 0).ApplyProjectVisibilityAsync(); + await solutionExplorer.DidNotReceive().ExpandAsync(Arg.Any>()); await solutionExplorer.DidNotReceive().CollapseAsync(Arg.Any>()); await solutionExplorer.DidNotReceive().GetExpandedFoldersAsync(); await solutionExplorer.DidNotReceive().HideSolutionFoldersAsync(Arg.Any(), Arg.Any()); - await solutionExplorer.DidNotReceive().HideUnloadedProjectsAsync(); } From b1a2fa1dc11fc151cc4fb267c89ee2a7ed4c414d Mon Sep 17 00:00:00 2001 From: reduckted Date: Mon, 16 Nov 2026 21:40:16 +1000 Subject: [PATCH 4/4] 2.9.0 --- CHANGELOG.md | 49 +++++++++++++++++++++++++------------------ Directory.Build.props | 2 +- 2 files changed, 30 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8687131..35ce4a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,60 +1,69 @@ +# 2.9.0 (2026-11-16) + +- ✨ Projects loaded by other extensions will become visible in Solution Explorer and will have their dependencies loaded (if that option is enabled). + +# 2.8.0 (2026-10-01) + +- ✨ Style updates to match Visual Studio 2026. +- ✨ New option to hide folders that only contain files. + # 2.7.0 (2026-09-06) -- ✨ New option to hide folders that only contain unloaded projects and miscellaneous files. - - +- ✨ New option to hide folders that only contain unloaded projects and miscellaneous files. + # 2.6.1 (2025-08-19) -- 🔧 Dependency updates. +- 🔧 Dependency updates. # 2.6.0 (2025-08-16) -- ✨ Updated styling to match changes to Visual Studio's Solution Explorer. +- ✨ Updated styling to match changes to Visual Studio's Solution Explorer. # 2.5.1 (2025-07-29) -- 🐛 Improved error handling when loading or unloading projects fails. +- 🐛 Improved error handling when loading or unloading projects fails. # 2.5.0 (2023-12-23) -- ✨ Filtering options (load dependencies, use regular expressions, etc.) are now stored on a per-solution basis. -- ✨ The expanded state of nodes in the Project Filter dialog are remembered. +- ✨ Filtering options (load dependencies, use regular expressions, etc.) are now stored on a per-solution basis. +- ✨ The expanded state of nodes in the Project Filter dialog are remembered. # 2.4.1 (2023-08-14) -- 🐛 When using a Solution Filter (`.slnf`), projects would sometimes be hidden in Solution Explorer after they were loaded (#4). +- 🐛 When using a Solution Filter (`.slnf`), projects would sometimes be hidden in Solution Explorer after they were loaded (#4). # 2.4.0 (2022-10-22) -- ✨ When the option to expand loaded projects is turned off, the projects and any folders they were in will be collapsed instead. +- ✨ When the option to expand loaded projects is turned off, the projects and any folders they were in will be collapsed instead. # 2.3.0 (2022-09-10) -- ✨ Added an option to prevent projects being expanded after they are loaded. +- ✨ Added an option to prevent projects being expanded after they are loaded. # 2.2.0 (2022-06-05) -- ✨ Ensured that shared project dependencies are loaded. +- ✨ Ensured that shared project dependencies are loaded. # 2.1.0 (2021-12-30) -- 🚤 Improved performance when showing the projects in the solution. -- ✨ Improved text searching when filtering the projects. -- ✨ Added support for using a regular expression to filter the projects. +- 🚤 Improved performance when showing the projects in the solution. +- ✨ Improved text searching when filtering the projects. +- ✨ Added support for using a regular expression to filter the projects. # 2.0.0 (2021-12-24) -- ✨ Visual Studio 2022 support. -- 📒 Dropped support for VS 2019. The last version that supported VS 2019 can be downloaded [here](https://github.com/reduckted/ProjectFilter/releases/tag/1.1.1). +- ✨ Visual Studio 2022 support. +- 📒 Dropped support for VS 2019. The last version that supported VS 2019 can be downloaded [here](https://github.com/reduckted/ProjectFilter/releases/tag/1.1.1). # 1.1.1 (2021-03-23) -- 🐛 Ensured the search box is focused when the dialog is opened. +- 🐛 Ensured the search box is focused when the dialog is opened. # 1.1.0 (2021-03-21) -- 🐛 Project icons were sometimes missing in the tree. -- 🔧 Performance improvements. +- 🐛 Project icons were sometimes missing in the tree. +- 🔧 Performance improvements. # 1.0.0 (2021-02-25) -- 🎉 Initial release. +- 🎉 Initial release. diff --git a/Directory.Build.props b/Directory.Build.props index a716e92..903cf93 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,7 +1,7 @@ - 2.8.0 + 2.9.0 net48 enable latest