mirror of
https://github.com/microsoft/PowerToys.git
synced 2026-04-03 09:46:54 +02:00
CmdPal: Prevent unsynchornized access to More commands (#46020)
## Summary of the Pull Request This PR fixes a crash caused by unsynchronized access to a context menu: - Fixes `System.ArgumentException: Destination array was not long enough` crash in `CommandItemViewModel.AllCommands` caused by `List<T>.AddRange()` racing with background `BuildAndInitMoreCommands` mutations - Replaces mutable `List<T>` public surfaces with immutable array snapshots protected by a `Lock`; writers hold the lock, mutate the backing list, then atomically publish new snapshots via `volatile` fields that readers access lock-free - Applies the same snapshot pattern to `ContentPageViewModel`, using a bundled `CommandSnapshot` object for atomic publication (since `PrimaryCommand` drives command invocation there, not just UI hints) - Narrows `IContextMenuContext.MoreCommands` and `AllCommands` from `List<T>`/`IEnumerable<T>` to `IReadOnlyList<T>` to prevent consumers from casting back and mutating - Moves `SafeCleanup()` calls outside locks in cleanup paths to avoid holding the lock during cross-process RPC calls <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist - [x] Closes: #45975 <!-- - [ ] Closes: #yyy (add separate lines for additional resolved issues) --> - [ ] **Communication:** I've discussed this with core contributors already. If the work hasn't been agreed, this work might be rejected - [ ] **Tests:** Added/updated and all pass - [ ] **Localization:** All end-user-facing strings can be localized - [ ] **Dev docs:** Added/updated - [ ] **New binaries:** Added on the required places - [ ] [JSON for signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json) for new binaries - [ ] [WXS for installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs) for new binaries and localization folder - [ ] [YML for CI pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml) for new test projects - [ ] [YML for signed pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml) - [ ] **Documentation updated:** If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys) and link it here: #xxx <!-- Provide a more detailed description of the PR, other things fixed, or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed
This commit is contained in:
@@ -122,11 +122,9 @@ public sealed partial class CommandBarViewModel : ObservableObject,
|
|||||||
}
|
}
|
||||||
|
|
||||||
SecondaryCommand = SelectedItem.SecondaryCommand;
|
SecondaryCommand = SelectedItem.SecondaryCommand;
|
||||||
|
var moreCommands = SelectedItem.MoreCommands;
|
||||||
|
|
||||||
var hasMoreThanOneContextItem = SelectedItem.MoreCommands.Count() > 1;
|
ShouldShowContextMenu = moreCommands.Count > 1 && SelectedItem.HasMoreCommands;
|
||||||
var hasMoreThanOneCommand = SelectedItem.MoreCommands.OfType<CommandContextItemViewModel>().Any();
|
|
||||||
|
|
||||||
ShouldShowContextMenu = hasMoreThanOneContextItem && hasMoreThanOneCommand;
|
|
||||||
|
|
||||||
OnPropertyChanged(nameof(HasSecondaryCommand));
|
OnPropertyChanged(nameof(HasSecondaryCommand));
|
||||||
OnPropertyChanged(nameof(SecondaryCommand));
|
OnPropertyChanged(nameof(SecondaryCommand));
|
||||||
|
|||||||
@@ -21,6 +21,12 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
|
|||||||
|
|
||||||
private readonly IContextMenuFactory? _contextMenuFactory;
|
private readonly IContextMenuFactory? _contextMenuFactory;
|
||||||
|
|
||||||
|
private readonly Lock _moreCommandsLock = new();
|
||||||
|
private readonly List<IContextItemViewModel> _moreCommands = [];
|
||||||
|
private volatile CommandContextItemViewModel? _secondaryMoreCommand;
|
||||||
|
private volatile IContextItemViewModel[] _moreCommandsSnapshot = [];
|
||||||
|
private volatile IContextItemViewModel[] _allCommandsSnapshot = [];
|
||||||
|
|
||||||
private ExtensionObject<IExtendedAttributesProvider>? ExtendedAttributesProvider { get; set; }
|
private ExtensionObject<IExtendedAttributesProvider>? ExtendedAttributesProvider { get; set; }
|
||||||
|
|
||||||
private readonly ExtensionObject<ICommandItem> _commandItemModel = new(null);
|
private readonly ExtensionObject<ICommandItem> _commandItemModel = new(null);
|
||||||
@@ -63,33 +69,22 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
|
|||||||
|
|
||||||
public CommandViewModel Command { get; private set; }
|
public CommandViewModel Command { get; private set; }
|
||||||
|
|
||||||
public List<IContextItemViewModel> MoreCommands { get; private set; } = [];
|
// Reuse a cached read-only snapshot so repeated reads don't allocate.
|
||||||
|
public IReadOnlyList<IContextItemViewModel> MoreCommands => _moreCommandsSnapshot;
|
||||||
|
|
||||||
IEnumerable<IContextItemViewModel> IContextMenuContext.MoreCommands => MoreCommands;
|
IReadOnlyList<IContextItemViewModel> IContextMenuContext.MoreCommands => _moreCommandsSnapshot;
|
||||||
|
|
||||||
private List<CommandContextItemViewModel> ActualCommands => MoreCommands.OfType<CommandContextItemViewModel>().ToList();
|
protected Lock MoreCommandsLock => _moreCommandsLock;
|
||||||
|
|
||||||
public bool HasMoreCommands => ActualCommands.Count > 0;
|
protected List<IContextItemViewModel> UnsafeMoreCommands => _moreCommands;
|
||||||
|
|
||||||
public string SecondaryCommandName => SecondaryCommand?.Name ?? string.Empty;
|
public bool HasMoreCommands => _secondaryMoreCommand is not null;
|
||||||
|
|
||||||
|
public string SecondaryCommandName => _secondaryMoreCommand?.Name ?? string.Empty;
|
||||||
|
|
||||||
public CommandItemViewModel? PrimaryCommand => this;
|
public CommandItemViewModel? PrimaryCommand => this;
|
||||||
|
|
||||||
public CommandItemViewModel? SecondaryCommand
|
public CommandItemViewModel? SecondaryCommand => _secondaryMoreCommand;
|
||||||
{
|
|
||||||
get
|
|
||||||
{
|
|
||||||
if (HasMoreCommands)
|
|
||||||
{
|
|
||||||
if (MoreCommands[0] is CommandContextItemViewModel command)
|
|
||||||
{
|
|
||||||
return command;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool ShouldBeVisible => !string.IsNullOrEmpty(Name);
|
public bool ShouldBeVisible => !string.IsNullOrEmpty(Name);
|
||||||
|
|
||||||
@@ -101,18 +96,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
|
|||||||
|
|
||||||
public DataPackageView? DataPackage { get; private set; }
|
public DataPackageView? DataPackage { get; private set; }
|
||||||
|
|
||||||
public List<IContextItemViewModel> AllCommands
|
public IReadOnlyList<IContextItemViewModel> AllCommands => _allCommandsSnapshot;
|
||||||
{
|
|
||||||
get
|
|
||||||
{
|
|
||||||
List<IContextItemViewModel> l = _defaultCommandContextItemViewModel is null ?
|
|
||||||
new() :
|
|
||||||
[_defaultCommandContextItemViewModel];
|
|
||||||
|
|
||||||
l.AddRange(MoreCommands);
|
|
||||||
return l;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static readonly IconInfoViewModel _errorIcon;
|
private static readonly IconInfoViewModel _errorIcon;
|
||||||
|
|
||||||
@@ -246,6 +230,11 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
|
|||||||
UpdateDefaultContextItemIcon();
|
UpdateDefaultContextItemIcon();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
lock (_moreCommandsLock)
|
||||||
|
{
|
||||||
|
RefreshMoreCommandStateUnsafe();
|
||||||
|
}
|
||||||
|
|
||||||
Initialized |= InitializedState.SelectionInitialized;
|
Initialized |= InitializedState.SelectionInitialized;
|
||||||
UpdateProperty(nameof(MoreCommands));
|
UpdateProperty(nameof(MoreCommands));
|
||||||
UpdateProperty(nameof(AllCommands));
|
UpdateProperty(nameof(AllCommands));
|
||||||
@@ -265,7 +254,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
|
|||||||
Command = new(null, PageContext);
|
Command = new(null, PageContext);
|
||||||
_itemTitle = "Error";
|
_itemTitle = "Error";
|
||||||
Subtitle = "Item failed to load";
|
Subtitle = "Item failed to load";
|
||||||
MoreCommands = [];
|
ClearMoreCommands();
|
||||||
_icon = _errorIcon;
|
_icon = _errorIcon;
|
||||||
_titleCache.Invalidate();
|
_titleCache.Invalidate();
|
||||||
_subtitleCache.Invalidate();
|
_subtitleCache.Invalidate();
|
||||||
@@ -304,7 +293,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
|
|||||||
Command = new(null, PageContext);
|
Command = new(null, PageContext);
|
||||||
_itemTitle = "Error";
|
_itemTitle = "Error";
|
||||||
Subtitle = "Item failed to load";
|
Subtitle = "Item failed to load";
|
||||||
MoreCommands = [];
|
ClearMoreCommands();
|
||||||
_icon = _errorIcon;
|
_icon = _errorIcon;
|
||||||
_titleCache.Invalidate();
|
_titleCache.Invalidate();
|
||||||
_subtitleCache.Invalidate();
|
_subtitleCache.Invalidate();
|
||||||
@@ -385,9 +374,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
|
|||||||
|
|
||||||
case nameof(model.MoreCommands):
|
case nameof(model.MoreCommands):
|
||||||
BuildAndInitMoreCommands();
|
BuildAndInitMoreCommands();
|
||||||
UpdateProperty(nameof(SecondaryCommand));
|
UpdateProperty(nameof(SecondaryCommand), nameof(SecondaryCommandName), nameof(HasMoreCommands), nameof(AllCommands));
|
||||||
UpdateProperty(nameof(SecondaryCommandName));
|
|
||||||
UpdateProperty(nameof(HasMoreCommands));
|
|
||||||
|
|
||||||
break;
|
break;
|
||||||
case nameof(DataPackage):
|
case nameof(DataPackage):
|
||||||
@@ -478,9 +465,10 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
|
|||||||
var results = factory.UnsafeBuildAndInitMoreCommands(more, this);
|
var results = factory.UnsafeBuildAndInitMoreCommands(more, this);
|
||||||
|
|
||||||
List<IContextItemViewModel>? freedItems;
|
List<IContextItemViewModel>? freedItems;
|
||||||
lock (MoreCommands)
|
lock (_moreCommandsLock)
|
||||||
{
|
{
|
||||||
ListHelpers.InPlaceUpdateList(MoreCommands, results, out freedItems);
|
ListHelpers.InPlaceUpdateList(_moreCommands, results, out freedItems);
|
||||||
|
RefreshMoreCommandStateUnsafe();
|
||||||
}
|
}
|
||||||
|
|
||||||
freedItems.OfType<CommandContextItemViewModel>()
|
freedItems.OfType<CommandContextItemViewModel>()
|
||||||
@@ -516,20 +504,30 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
|
|||||||
{
|
{
|
||||||
base.UnsafeCleanup();
|
base.UnsafeCleanup();
|
||||||
|
|
||||||
lock (MoreCommands)
|
List<IContextItemViewModel> freedItems;
|
||||||
|
CommandContextItemViewModel? freedDefault;
|
||||||
|
lock (_moreCommandsLock)
|
||||||
{
|
{
|
||||||
MoreCommands.OfType<CommandContextItemViewModel>()
|
freedItems = [.. _moreCommands];
|
||||||
.ToList()
|
_moreCommands.Clear();
|
||||||
.ForEach(c => c.SafeCleanup());
|
|
||||||
MoreCommands.Clear();
|
// Null out here so the single RefreshMoreCommandStateUnsafe call
|
||||||
|
// produces an _allCommandsSnapshot that excludes the default command.
|
||||||
|
freedDefault = _defaultCommandContextItemViewModel;
|
||||||
|
_defaultCommandContextItemViewModel = null;
|
||||||
|
|
||||||
|
RefreshMoreCommandStateUnsafe();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cleanup outside lock to avoid holding it during RPC calls
|
||||||
|
freedItems.OfType<CommandContextItemViewModel>()
|
||||||
|
.ToList()
|
||||||
|
.ForEach(c => c.SafeCleanup());
|
||||||
|
freedDefault?.SafeCleanup();
|
||||||
|
|
||||||
// _listItemIcon.SafeCleanup();
|
// _listItemIcon.SafeCleanup();
|
||||||
_icon = new(null); // necessary?
|
_icon = new(null); // necessary?
|
||||||
|
|
||||||
_defaultCommandContextItemViewModel?.SafeCleanup();
|
|
||||||
_defaultCommandContextItemViewModel = null;
|
|
||||||
|
|
||||||
Command.PropertyChanged -= Command_PropertyChanged;
|
Command.PropertyChanged -= Command_PropertyChanged;
|
||||||
Command.SafeCleanup();
|
Command.SafeCleanup();
|
||||||
|
|
||||||
@@ -545,6 +543,40 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
|
|||||||
base.SafeCleanup();
|
base.SafeCleanup();
|
||||||
Initialized |= InitializedState.CleanedUp;
|
Initialized |= InitializedState.CleanedUp;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected void RefreshMoreCommandStateUnsafe()
|
||||||
|
{
|
||||||
|
_moreCommandsSnapshot = [.. _moreCommands];
|
||||||
|
|
||||||
|
_secondaryMoreCommand = null;
|
||||||
|
foreach (var item in _moreCommands)
|
||||||
|
{
|
||||||
|
if (item is CommandContextItemViewModel command)
|
||||||
|
{
|
||||||
|
_secondaryMoreCommand = command;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_allCommandsSnapshot = _defaultCommandContextItemViewModel is null ?
|
||||||
|
_moreCommandsSnapshot :
|
||||||
|
[_defaultCommandContextItemViewModel, .. _moreCommandsSnapshot];
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ClearMoreCommands()
|
||||||
|
{
|
||||||
|
List<IContextItemViewModel> freedItems;
|
||||||
|
lock (_moreCommandsLock)
|
||||||
|
{
|
||||||
|
freedItems = [.. _moreCommands];
|
||||||
|
_moreCommands.Clear();
|
||||||
|
RefreshMoreCommandStateUnsafe();
|
||||||
|
}
|
||||||
|
|
||||||
|
freedItems.OfType<CommandContextItemViewModel>()
|
||||||
|
.ToList()
|
||||||
|
.ForEach(c => c.SafeCleanup());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[Flags]
|
[Flags]
|
||||||
|
|||||||
@@ -17,13 +17,15 @@ namespace Microsoft.CmdPal.UI.ViewModels;
|
|||||||
public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
|
public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
|
||||||
{
|
{
|
||||||
private readonly ExtensionObject<IContentPage> _model;
|
private readonly ExtensionObject<IContentPage> _model;
|
||||||
|
private readonly Lock _commandsLock = new();
|
||||||
|
private volatile CommandSnapshot _snapshot = CommandSnapshot.Empty;
|
||||||
|
|
||||||
[ObservableProperty]
|
[ObservableProperty]
|
||||||
public partial ObservableCollection<ContentViewModel> Content { get; set; } = [];
|
public partial ObservableCollection<ContentViewModel> Content { get; set; } = [];
|
||||||
|
|
||||||
public List<IContextItemViewModel> Commands { get; private set; } = [];
|
private List<IContextItemViewModel> Commands { get; } = [];
|
||||||
|
|
||||||
public bool HasCommands => ActualCommands.Count > 0;
|
public bool HasCommands => _snapshot.PrimaryCommand is not null;
|
||||||
|
|
||||||
public DetailsViewModel? Details { get; private set; }
|
public DetailsViewModel? Details { get; private set; }
|
||||||
|
|
||||||
@@ -31,19 +33,17 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
|
|||||||
public bool HasDetails => Details is not null;
|
public bool HasDetails => Details is not null;
|
||||||
|
|
||||||
/////// ICommandBarContext ///////
|
/////// ICommandBarContext ///////
|
||||||
public IEnumerable<IContextItemViewModel> MoreCommands => Commands.Skip(1);
|
public IReadOnlyList<IContextItemViewModel> MoreCommands => _snapshot.MoreCommands;
|
||||||
|
|
||||||
private List<CommandContextItemViewModel> ActualCommands => Commands.OfType<CommandContextItemViewModel>().ToList();
|
public bool HasMoreCommands => _snapshot.SecondaryCommand is not null;
|
||||||
|
|
||||||
public bool HasMoreCommands => ActualCommands.Count > 1;
|
public string SecondaryCommandName => _snapshot.SecondaryCommand?.Name ?? string.Empty;
|
||||||
|
|
||||||
public string SecondaryCommandName => SecondaryCommand?.Name ?? string.Empty;
|
public CommandItemViewModel? PrimaryCommand => _snapshot.PrimaryCommand;
|
||||||
|
|
||||||
public CommandItemViewModel? PrimaryCommand => HasCommands ? ActualCommands[0] : null;
|
public CommandItemViewModel? SecondaryCommand => _snapshot.SecondaryCommand;
|
||||||
|
|
||||||
public CommandItemViewModel? SecondaryCommand => HasMoreCommands ? ActualCommands[1] : null;
|
public IReadOnlyList<IContextItemViewModel> AllCommands => _snapshot.AllCommands;
|
||||||
|
|
||||||
public List<IContextItemViewModel> AllCommands => Commands;
|
|
||||||
|
|
||||||
// Remember - "observable" properties from the model (via PropChanged)
|
// Remember - "observable" properties from the model (via PropChanged)
|
||||||
// cannot be marked [ObservableProperty]
|
// cannot be marked [ObservableProperty]
|
||||||
@@ -109,28 +109,14 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
|
|||||||
return; // throw?
|
return; // throw?
|
||||||
}
|
}
|
||||||
|
|
||||||
Commands = model.Commands
|
var commands = BuildCommandViewModels(model.Commands);
|
||||||
.ToList()
|
InitializeCommandViewModels(commands, static contextItem => contextItem.InitializeProperties());
|
||||||
.Select<IContextItem, IContextItemViewModel>(item =>
|
|
||||||
{
|
|
||||||
if (item is ICommandContextItem contextItem)
|
|
||||||
{
|
|
||||||
return new CommandContextItemViewModel(contextItem, PageContext);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
return new SeparatorViewModel();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
Commands
|
lock (_commandsLock)
|
||||||
.OfType<CommandContextItemViewModel>()
|
{
|
||||||
.ToList()
|
ListHelpers.InPlaceUpdateList(Commands, commands);
|
||||||
.ForEach(contextItem =>
|
RefreshCommandSnapshotsUnsafe();
|
||||||
{
|
}
|
||||||
contextItem.InitializeProperties();
|
|
||||||
});
|
|
||||||
|
|
||||||
var extensionDetails = model.Details;
|
var extensionDetails = model.Details;
|
||||||
if (extensionDetails is not null)
|
if (extensionDetails is not null)
|
||||||
@@ -168,37 +154,29 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
|
|||||||
var more = model.Commands;
|
var more = model.Commands;
|
||||||
if (more is not null)
|
if (more is not null)
|
||||||
{
|
{
|
||||||
var newContextMenu = more
|
var newContextMenu = BuildCommandViewModels(more);
|
||||||
.ToList()
|
InitializeCommandViewModels(newContextMenu, static contextItem => contextItem.SlowInitializeProperties());
|
||||||
.Select(item =>
|
|
||||||
{
|
|
||||||
if (item is ICommandContextItem contextItem)
|
|
||||||
{
|
|
||||||
return new CommandContextItemViewModel(contextItem, PageContext) as IContextItemViewModel;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
return new SeparatorViewModel();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
lock (Commands)
|
List<IContextItemViewModel> removedItems;
|
||||||
|
lock (_commandsLock)
|
||||||
{
|
{
|
||||||
ListHelpers.InPlaceUpdateList(Commands, newContextMenu);
|
ListHelpers.InPlaceUpdateList(Commands, newContextMenu, out removedItems);
|
||||||
|
RefreshCommandSnapshotsUnsafe();
|
||||||
}
|
}
|
||||||
|
|
||||||
Commands
|
CleanupCommandViewModels(removedItems);
|
||||||
.OfType<CommandContextItemViewModel>()
|
|
||||||
.ToList()
|
|
||||||
.ForEach(contextItem =>
|
|
||||||
{
|
|
||||||
contextItem.SlowInitializeProperties();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Commands.Clear();
|
List<IContextItemViewModel> removedItems;
|
||||||
|
lock (_commandsLock)
|
||||||
|
{
|
||||||
|
removedItems = [.. Commands];
|
||||||
|
Commands.Clear();
|
||||||
|
RefreshCommandSnapshotsUnsafe();
|
||||||
|
}
|
||||||
|
|
||||||
|
CleanupCommandViewModels(removedItems);
|
||||||
}
|
}
|
||||||
|
|
||||||
UpdateProperty(nameof(PrimaryCommand));
|
UpdateProperty(nameof(PrimaryCommand));
|
||||||
@@ -206,6 +184,7 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
|
|||||||
UpdateProperty(nameof(SecondaryCommandName));
|
UpdateProperty(nameof(SecondaryCommandName));
|
||||||
UpdateProperty(nameof(HasCommands));
|
UpdateProperty(nameof(HasCommands));
|
||||||
UpdateProperty(nameof(HasMoreCommands));
|
UpdateProperty(nameof(HasMoreCommands));
|
||||||
|
UpdateProperty(nameof(MoreCommands));
|
||||||
UpdateProperty(nameof(AllCommands));
|
UpdateProperty(nameof(AllCommands));
|
||||||
DoOnUiThread(
|
DoOnUiThread(
|
||||||
() =>
|
() =>
|
||||||
@@ -243,6 +222,72 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private List<IContextItemViewModel> BuildCommandViewModels(IContextItem[]? items)
|
||||||
|
{
|
||||||
|
if (items is null)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return items
|
||||||
|
.Select<IContextItem, IContextItemViewModel>(item =>
|
||||||
|
{
|
||||||
|
if (item is ICommandContextItem contextItem)
|
||||||
|
{
|
||||||
|
return new CommandContextItemViewModel(contextItem, PageContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new SeparatorViewModel();
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void InitializeCommandViewModels(IEnumerable<IContextItemViewModel> commands, Action<CommandContextItemViewModel> initialize)
|
||||||
|
{
|
||||||
|
foreach (var contextItem in commands.OfType<CommandContextItemViewModel>())
|
||||||
|
{
|
||||||
|
initialize(contextItem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CleanupCommandViewModels(IEnumerable<IContextItemViewModel> commands)
|
||||||
|
{
|
||||||
|
foreach (var contextItem in commands.OfType<CommandContextItemViewModel>())
|
||||||
|
{
|
||||||
|
contextItem.SafeCleanup();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RefreshCommandSnapshotsUnsafe()
|
||||||
|
{
|
||||||
|
var allCommands = (IContextItemViewModel[])[.. Commands];
|
||||||
|
var moreCommands = allCommands.Length > 1
|
||||||
|
? allCommands[1..]
|
||||||
|
: [];
|
||||||
|
|
||||||
|
CommandContextItemViewModel? primary = null;
|
||||||
|
CommandContextItemViewModel? secondary = null;
|
||||||
|
foreach (var item in allCommands)
|
||||||
|
{
|
||||||
|
if (item is not CommandContextItemViewModel command)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (primary is null)
|
||||||
|
{
|
||||||
|
primary = command;
|
||||||
|
}
|
||||||
|
else if (secondary is null)
|
||||||
|
{
|
||||||
|
secondary = command;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_snapshot = new(allCommands, moreCommands, primary, secondary);
|
||||||
|
}
|
||||||
|
|
||||||
// InvokeItemCommand is what this will be in Xaml due to source generator
|
// InvokeItemCommand is what this will be in Xaml due to source generator
|
||||||
// this comes in on Enter keypresses in the SearchBox
|
// this comes in on Enter keypresses in the SearchBox
|
||||||
[RelayCommand]
|
[RelayCommand]
|
||||||
@@ -270,12 +315,15 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
|
|||||||
|
|
||||||
Details?.SafeCleanup();
|
Details?.SafeCleanup();
|
||||||
|
|
||||||
Commands
|
List<IContextItemViewModel> removedItems;
|
||||||
.OfType<CommandContextItemViewModel>()
|
lock (_commandsLock)
|
||||||
.ToList()
|
{
|
||||||
.ForEach(item => item.SafeCleanup());
|
removedItems = [.. Commands];
|
||||||
|
Commands.Clear();
|
||||||
|
RefreshCommandSnapshotsUnsafe();
|
||||||
|
}
|
||||||
|
|
||||||
Commands.Clear();
|
CleanupCommandViewModels(removedItems);
|
||||||
|
|
||||||
foreach (var item in Content)
|
foreach (var item in Content)
|
||||||
{
|
{
|
||||||
@@ -290,4 +338,25 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
|
|||||||
model.ItemsChanged -= Model_ItemsChanged;
|
model.ItemsChanged -= Model_ItemsChanged;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Immutable bundle of derived command state, published atomically via a
|
||||||
|
/// single volatile write so readers never see a torn snapshot.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class CommandSnapshot(
|
||||||
|
IContextItemViewModel[] allCommands,
|
||||||
|
IContextItemViewModel[] moreCommands,
|
||||||
|
CommandContextItemViewModel? primaryCommand,
|
||||||
|
CommandContextItemViewModel? secondaryCommand)
|
||||||
|
{
|
||||||
|
public static CommandSnapshot Empty { get; } = new([], [], null, null);
|
||||||
|
|
||||||
|
public IContextItemViewModel[] AllCommands { get; } = allCommands;
|
||||||
|
|
||||||
|
public IContextItemViewModel[] MoreCommands { get; } = moreCommands;
|
||||||
|
|
||||||
|
public CommandContextItemViewModel? PrimaryCommand { get; } = primaryCommand;
|
||||||
|
|
||||||
|
public CommandContextItemViewModel? SecondaryCommand { get; } = secondaryCommand;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -159,7 +159,6 @@ public partial class ListItemViewModel : CommandItemViewModel
|
|||||||
UpdateShowDetailsCommand();
|
UpdateShowDetailsCommand();
|
||||||
break;
|
break;
|
||||||
case nameof(model.MoreCommands):
|
case nameof(model.MoreCommands):
|
||||||
UpdateProperty(nameof(MoreCommands));
|
|
||||||
AddShowDetailsCommands();
|
AddShowDetailsCommands();
|
||||||
break;
|
break;
|
||||||
case nameof(model.Title):
|
case nameof(model.Title):
|
||||||
@@ -195,19 +194,27 @@ public partial class ListItemViewModel : CommandItemViewModel
|
|||||||
pageContext is ListViewModel listViewModel &&
|
pageContext is ListViewModel listViewModel &&
|
||||||
!listViewModel.ShowDetails)
|
!listViewModel.ShowDetails)
|
||||||
{
|
{
|
||||||
// Check if "Show Details" action already exists to prevent duplicates
|
var addedCommand = false;
|
||||||
if (!MoreCommands.Any(cmd => cmd is CommandContextItemViewModel contextItemViewModel &&
|
lock (MoreCommandsLock)
|
||||||
contextItemViewModel.Command.Id == ShowDetailsCommand.ShowDetailsCommandId))
|
|
||||||
{
|
{
|
||||||
// Create the view model for the show details command
|
// Check if "Show Details" action already exists to prevent duplicates
|
||||||
var showDetailsCommand = new ShowDetailsCommand(Details);
|
if (!UnsafeMoreCommands.Any(cmd => cmd is CommandContextItemViewModel contextItemViewModel &&
|
||||||
var showDetailsContextItem = new CommandContextItem(showDetailsCommand);
|
contextItemViewModel.Command.Id == ShowDetailsCommand.ShowDetailsCommandId))
|
||||||
var showDetailsContextItemViewModel = new CommandContextItemViewModel(showDetailsContextItem, PageContext);
|
{
|
||||||
showDetailsContextItemViewModel.SlowInitializeProperties();
|
var showDetailsCommand = new ShowDetailsCommand(Details);
|
||||||
MoreCommands.Add(showDetailsContextItemViewModel);
|
var showDetailsContextItem = new CommandContextItem(showDetailsCommand);
|
||||||
|
var showDetailsContextItemViewModel = new CommandContextItemViewModel(showDetailsContextItem, PageContext);
|
||||||
|
showDetailsContextItemViewModel.SlowInitializeProperties();
|
||||||
|
UnsafeMoreCommands.Add(showDetailsContextItemViewModel);
|
||||||
|
RefreshMoreCommandStateUnsafe();
|
||||||
|
addedCommand = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
UpdateProperty(nameof(MoreCommands), nameof(AllCommands));
|
if (addedCommand)
|
||||||
|
{
|
||||||
|
UpdateProperty(nameof(MoreCommands), nameof(AllCommands));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,22 +229,27 @@ public partial class ListItemViewModel : CommandItemViewModel
|
|||||||
pageContext is ListViewModel listViewModel &&
|
pageContext is ListViewModel listViewModel &&
|
||||||
!listViewModel.ShowDetails)
|
!listViewModel.ShowDetails)
|
||||||
{
|
{
|
||||||
var existingCommand = MoreCommands.FirstOrDefault(cmd =>
|
CommandContextItemViewModel? oldCommand = null;
|
||||||
cmd is CommandContextItemViewModel contextItemViewModel &&
|
lock (MoreCommandsLock)
|
||||||
contextItemViewModel.Command.Id == ShowDetailsCommand.ShowDetailsCommandId);
|
|
||||||
|
|
||||||
// If the command already exists, remove it to update with the new details
|
|
||||||
if (existingCommand is not null)
|
|
||||||
{
|
{
|
||||||
MoreCommands.Remove(existingCommand);
|
oldCommand = UnsafeMoreCommands
|
||||||
|
.OfType<CommandContextItemViewModel>()
|
||||||
|
.FirstOrDefault(contextItemViewModel => contextItemViewModel.Command.Id == ShowDetailsCommand.ShowDetailsCommandId);
|
||||||
|
|
||||||
|
if (oldCommand is not null)
|
||||||
|
{
|
||||||
|
UnsafeMoreCommands.Remove(oldCommand);
|
||||||
|
}
|
||||||
|
|
||||||
|
var showDetailsCommand = new ShowDetailsCommand(Details);
|
||||||
|
var showDetailsContextItem = new CommandContextItem(showDetailsCommand);
|
||||||
|
var showDetailsContextItemViewModel = new CommandContextItemViewModel(showDetailsContextItem, PageContext);
|
||||||
|
showDetailsContextItemViewModel.SlowInitializeProperties();
|
||||||
|
UnsafeMoreCommands.Add(showDetailsContextItemViewModel);
|
||||||
|
RefreshMoreCommandStateUnsafe();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create the view model for the show details command
|
oldCommand?.SafeCleanup();
|
||||||
var showDetailsCommand = new ShowDetailsCommand(Details);
|
|
||||||
var showDetailsContextItem = new CommandContextItem(showDetailsCommand);
|
|
||||||
var showDetailsContextItemViewModel = new CommandContextItemViewModel(showDetailsContextItem, PageContext);
|
|
||||||
showDetailsContextItemViewModel.SlowInitializeProperties();
|
|
||||||
MoreCommands.Add(showDetailsContextItemViewModel);
|
|
||||||
|
|
||||||
UpdateProperty(nameof(MoreCommands), nameof(AllCommands));
|
UpdateProperty(nameof(MoreCommands), nameof(AllCommands));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,11 +18,11 @@ public record UpdateCommandBarMessage(ICommandBarContext? ViewModel)
|
|||||||
|
|
||||||
public interface IContextMenuContext : INotifyPropertyChanged
|
public interface IContextMenuContext : INotifyPropertyChanged
|
||||||
{
|
{
|
||||||
public IEnumerable<IContextItemViewModel> MoreCommands { get; }
|
public IReadOnlyList<IContextItemViewModel> MoreCommands { get; }
|
||||||
|
|
||||||
public bool HasMoreCommands { get; }
|
public bool HasMoreCommands { get; }
|
||||||
|
|
||||||
public List<IContextItemViewModel> AllCommands { get; }
|
public IReadOnlyList<IContextItemViewModel> AllCommands { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Generates a mapping of key -> command item for this particular item's
|
/// Generates a mapping of key -> command item for this particular item's
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
// Copyright (c) Microsoft Corporation
|
||||||
|
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.CmdPal.UI.ViewModels.Models;
|
||||||
|
using Microsoft.CommandPalette.Extensions.Toolkit;
|
||||||
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
|
|
||||||
|
namespace Microsoft.CmdPal.UI.ViewModels.UnitTests;
|
||||||
|
|
||||||
|
[TestClass]
|
||||||
|
public class CommandItemViewModelTests
|
||||||
|
{
|
||||||
|
private sealed class TestPageContext : IPageContext
|
||||||
|
{
|
||||||
|
public TaskScheduler Scheduler => TaskScheduler.Default;
|
||||||
|
|
||||||
|
public ICommandProviderContext ProviderContext => CommandProviderContext.Empty;
|
||||||
|
|
||||||
|
public void ShowException(Exception ex, string? extensionHint = null)
|
||||||
|
{
|
||||||
|
throw new AssertFailedException($"Unexpected exception from view model: {ex}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void MoreCommandsAndAllCommands_ReturnSnapshots()
|
||||||
|
{
|
||||||
|
// The public getters should return cached read-only snapshots, so
|
||||||
|
// repeated reads don't allocate a new list when the backing data hasn't
|
||||||
|
// changed.
|
||||||
|
var pageContext = new TestPageContext();
|
||||||
|
var item = new CommandItem(new NoOpCommand { Name = "Primary" })
|
||||||
|
{
|
||||||
|
Title = "Primary",
|
||||||
|
MoreCommands =
|
||||||
|
[
|
||||||
|
new CommandContextItem(new NoOpCommand { Name = "Secondary" }),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
var viewModel = new CommandItemViewModel(new(item), new(pageContext), DefaultContextMenuFactory.Instance);
|
||||||
|
viewModel.SlowInitializeProperties();
|
||||||
|
|
||||||
|
var moreCommands = viewModel.MoreCommands;
|
||||||
|
var allCommands = viewModel.AllCommands;
|
||||||
|
|
||||||
|
Assert.AreSame(moreCommands, viewModel.MoreCommands);
|
||||||
|
Assert.AreSame(allCommands, viewModel.AllCommands);
|
||||||
|
Assert.AreEqual(1, moreCommands.Count);
|
||||||
|
Assert.AreEqual(2, allCommands.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SecondaryCommand_IgnoresLeadingSeparators()
|
||||||
|
{
|
||||||
|
// SecondaryCommand/HasMoreCommands should be derived from the first actual command item,
|
||||||
|
// not from the raw first entry in MoreCommands.
|
||||||
|
var pageContext = new TestPageContext();
|
||||||
|
var item = new CommandItem(new NoOpCommand { Name = "Primary" })
|
||||||
|
{
|
||||||
|
Title = "Primary",
|
||||||
|
MoreCommands =
|
||||||
|
[
|
||||||
|
new Separator("Group"),
|
||||||
|
new CommandContextItem(new NoOpCommand { Name = "Secondary" }),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
var viewModel = new CommandItemViewModel(new(item), new(pageContext), DefaultContextMenuFactory.Instance);
|
||||||
|
viewModel.SlowInitializeProperties();
|
||||||
|
|
||||||
|
Assert.IsTrue(viewModel.HasMoreCommands);
|
||||||
|
Assert.IsNotNull(viewModel.SecondaryCommand);
|
||||||
|
Assert.AreEqual("Secondary", viewModel.SecondaryCommand.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
// Copyright (c) Microsoft Corporation
|
||||||
|
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.CommandPalette.Extensions;
|
||||||
|
using Microsoft.CommandPalette.Extensions.Toolkit;
|
||||||
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
|
|
||||||
|
namespace Microsoft.CmdPal.UI.ViewModels.UnitTests;
|
||||||
|
|
||||||
|
[TestClass]
|
||||||
|
public partial class ContentPageViewModelTests
|
||||||
|
{
|
||||||
|
private sealed partial class TestAppExtensionHost : AppExtensionHost
|
||||||
|
{
|
||||||
|
public override string? GetExtensionDisplayName() => "Test Host";
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed partial class TestContentPage : ContentPage
|
||||||
|
{
|
||||||
|
public override IContent[] GetContent() => [];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CommandContextItem Command(string name) => new(new NoOpCommand { Name = name });
|
||||||
|
|
||||||
|
private static ContentPageViewModel CreateViewModel(TestContentPage page) =>
|
||||||
|
new(page, TaskScheduler.Default, new TestAppExtensionHost(), CommandProviderContext.Empty);
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AllCommandsAndMoreCommands_ReturnCachedSnapshots()
|
||||||
|
{
|
||||||
|
// Content pages should expose stable snapshots, not the live Commands
|
||||||
|
// list, so repeated reads don't allocate and callers can't observe
|
||||||
|
// in-place list mutations.
|
||||||
|
var page = new TestContentPage
|
||||||
|
{
|
||||||
|
Id = "content.page",
|
||||||
|
Name = "Content Page",
|
||||||
|
Title = "Content Page",
|
||||||
|
Commands =
|
||||||
|
[
|
||||||
|
Command("Primary"),
|
||||||
|
Command("Secondary"),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
var viewModel = CreateViewModel(page);
|
||||||
|
viewModel.InitializeProperties();
|
||||||
|
|
||||||
|
var allCommands = viewModel.AllCommands;
|
||||||
|
var moreCommands = viewModel.MoreCommands;
|
||||||
|
|
||||||
|
Assert.AreSame(allCommands, viewModel.AllCommands);
|
||||||
|
Assert.AreSame(moreCommands, viewModel.MoreCommands);
|
||||||
|
Assert.AreEqual(2, allCommands.Count);
|
||||||
|
Assert.AreEqual(1, moreCommands.Count);
|
||||||
|
Assert.AreEqual("Primary", viewModel.PrimaryCommand?.Name);
|
||||||
|
Assert.AreEqual("Secondary", viewModel.SecondaryCommand?.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CommandsUpdate_RefreshesSnapshotsConsistently()
|
||||||
|
{
|
||||||
|
// Updating the model commands should swap in a new coherent snapshot.
|
||||||
|
// The old snapshots stay intact, and the new cached values agree on
|
||||||
|
// counts, primary/secondary commands, and "has more" state.
|
||||||
|
var page = new TestContentPage
|
||||||
|
{
|
||||||
|
Id = "content.page",
|
||||||
|
Name = "Content Page",
|
||||||
|
Title = "Content Page",
|
||||||
|
Commands =
|
||||||
|
[
|
||||||
|
Command("Primary"),
|
||||||
|
Command("Secondary"),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
var viewModel = CreateViewModel(page);
|
||||||
|
viewModel.InitializeProperties();
|
||||||
|
|
||||||
|
var oldAllCommands = viewModel.AllCommands;
|
||||||
|
var oldMoreCommands = viewModel.MoreCommands;
|
||||||
|
|
||||||
|
page.Commands =
|
||||||
|
[
|
||||||
|
Command("Updated Primary"),
|
||||||
|
new Separator("Group"),
|
||||||
|
Command("Updated Secondary"),
|
||||||
|
];
|
||||||
|
|
||||||
|
Assert.AreEqual(2, oldAllCommands.Count);
|
||||||
|
Assert.AreEqual(1, oldMoreCommands.Count);
|
||||||
|
|
||||||
|
Assert.AreEqual(3, viewModel.AllCommands.Count);
|
||||||
|
Assert.AreEqual(2, viewModel.MoreCommands.Count);
|
||||||
|
Assert.IsTrue(viewModel.HasCommands);
|
||||||
|
Assert.IsTrue(viewModel.HasMoreCommands);
|
||||||
|
Assert.AreEqual("Updated Primary", viewModel.PrimaryCommand?.Name);
|
||||||
|
Assert.AreEqual("Updated Secondary", viewModel.SecondaryCommand?.Name);
|
||||||
|
Assert.AreEqual("Updated Secondary", viewModel.SecondaryCommandName);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user