Repository navigation
Expand file tree
/
Copy pathWindows11ContextMenuPageViewModel.cs
More file actions
414 lines (359 loc) · 14.5 KB
/
Copy pathWindows11ContextMenuPageViewModel.cs
File metadata and controls
414 lines (359 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Data;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ContextMenuMgr.Contracts;
using ContextMenuMgr.Frontend.Services;
namespace ContextMenuMgr.Frontend.ViewModels;
/// <summary>
/// Represents the windows11 Context Menu Page View Model.
/// </summary>
public partial class Windows11ContextMenuPageViewModel : ObservableObject, IDisposable
{
private const int RebuildDebounceMilliseconds = 120;
private readonly Windows11ContextMenuService _service;
private readonly LocalizationService _localization;
private readonly ContextMenuWorkspaceService _workspace;
private readonly GlobalSearchNavigationFilterService _globalSearchFilterService;
private readonly FrontendSettingsService _settingsService;
private readonly DelayedLoadingPresentation _loadingPresentation = new();
private CancellationTokenSource? _rebuildCts;
/// <summary>
/// Initializes a new instance of the <see cref="Windows11ContextMenuPageViewModel"/> class.
/// </summary>
public Windows11ContextMenuPageViewModel(
Windows11ContextMenuService service,
LocalizationService localization,
ContextMenuWorkspaceService workspace,
GlobalSearchNavigationFilterService globalSearchFilterService,
FrontendSettingsService settingsService)
{
_service = service;
_localization = localization;
_workspace = workspace;
_globalSearchFilterService = globalSearchFilterService;
_settingsService = settingsService;
_loadingPresentation.PropertyChanged += OnLoadingPresentationChanged;
ItemsView = new ListCollectionView(Items);
ItemsView.Filter = FilterItem;
ItemsView.SortDescriptions.Add(new SortDescription(nameof(Windows11ContextMenuItemViewModel.DisplayName), ListSortDirection.Ascending));
((ListCollectionView)ItemsView).IsLiveSorting = true;
((ListCollectionView)ItemsView).IsLiveFiltering = true;
foreach (var property in new[] { nameof(Windows11ContextMenuItemViewModel.DisplayName), nameof(Windows11ContextMenuItemViewModel.PublisherName),
nameof(Windows11ContextMenuItemViewModel.ContextTypesText), nameof(Windows11ContextMenuItemViewModel.UserNote) })
((ListCollectionView)ItemsView).LiveFilteringProperties.Add(property);
_localization.LanguageChanged += OnLanguageChanged;
_service.ItemsChanged += OnItemsChanged;
_globalSearchFilterService.FilterRequested += OnGlobalSearchFilterRequested;
_workspace.Items.CollectionChanged += OnWorkspaceItemsChanged;
foreach (var item in _workspace.Items)
{
item.PropertyChanged += OnWorkspaceItemPropertyChanged;
}
if (_service.IsSupported)
{
if (_service.CurrentItems.Count > 0)
{
RebuildItems(_service.CurrentItems);
HasLoadError = !_service.IsSnapshotComplete;
}
else
{
_ = EnsureLoadedAsync();
}
}
ApplyPendingGlobalSearchFilter();
}
/// <summary>
/// Gets the items.
/// </summary>
public ObservableCollection<Windows11ContextMenuItemViewModel> Items { get; } = [];
/// <summary>
/// Gets the items View.
/// </summary>
public ICollectionView ItemsView { get; }
/// <summary>
/// Gets or sets a value indicating whether loading.
/// </summary>
[ObservableProperty]
public partial bool IsLoading { get; set; }
/// <summary>
/// Gets or sets the search Text.
/// </summary>
[ObservableProperty]
public partial string SearchText { get; set; } = string.Empty;
public string Title => _localization.Translate("Windows11PageTitle");
public string Description => _localization.Translate("Windows11PageDescription");
public string SearchLabel => _localization.Translate("SearchLabel");
public string LoadingItemsText => _localization.Translate("LoadingItemsText");
public string EmptyItemsText => _localization.Translate("Windows11NoItems");
public string RefreshText => _localization.Translate("Refresh");
public string ItemCountText => _localization.Format("Windows11ItemCount", ItemsView.Cast<object>().Count());
public string LoadErrorText => _localization.Translate(_service.HasSnapshot && !_service.IsSnapshotComplete
? "MenuListIncompleteStatus" : "Windows11LoadFailed");
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsListEmpty))]
[NotifyPropertyChangedFor(nameof(ShowListContent))]
[NotifyPropertyChangedFor(nameof(ShowListPlaceholder))]
public partial bool HasLoadError { get; set; }
public bool IsSupported => _service.IsSupported;
public bool IsListLoading => !_service.HasSnapshot && _loadingPresentation.IsVisible;
public bool ShowListContent => !IsListLoading && !IsListEmpty;
public bool IsListEmpty => !HasLoadError && !IsListLoading && !IsLoading
&& !ItemsView.Cast<object>().Any();
public bool ShowListPlaceholder => IsListLoading || IsListEmpty;
/// <summary>
/// Refreshes async.
/// </summary>
[RelayCommand]
public async Task RefreshAsync()
{
if (!_service.IsSupported || IsLoading)
{
return;
}
IsLoading = true;
HasLoadError = false;
try
{
await _service.RefreshAsync(CancellationToken.None);
RebuildItems(_service.CurrentItems);
HasLoadError = !_service.IsSnapshotComplete;
}
catch (Exception ex)
{
HasLoadError = true;
FrontendDebugLog.Warning(nameof(Windows11ContextMenuPageViewModel), ex.ToString());
}
finally
{
IsLoading = false;
}
}
partial void OnSearchTextChanged(string value)
{
ItemsView.Refresh();
RefreshListPlaceholderState();
}
private void OnGlobalSearchFilterRequested(object? sender, GlobalSearchFilterRequestedEventArgs e)
{
if (!e.IsWindows11)
{
return;
}
ApplyGlobalSearchFilter(e.FilterText, e.ItemId);
_globalSearchFilterService.ConsumePendingWindows11Request();
}
private void ApplyPendingGlobalSearchFilter()
{
var pending = _globalSearchFilterService.ConsumePendingWindows11Request();
if (pending is not null)
{
ApplyGlobalSearchFilter(pending.FilterText, pending.ItemId);
}
}
private void ApplyGlobalSearchFilter(string filterText, string? itemId)
{
if (string.IsNullOrWhiteSpace(filterText))
{
return;
}
SearchText = filterText;
ItemsView.Refresh();
RefreshListPlaceholderState();
FrontendDebugLog.Info(
nameof(Windows11ContextMenuPageViewModel),
"GlobalSearchFilterApplied: "
+ "Page/ViewModel=Windows11ContextMenuPageViewModel, "
+ "Category=<null>, "
+ "IsWindows11=True, "
+ $"ItemId={itemId ?? "<null>"}, "
+ $"FilterText='{SanitizeLogText(filterText)}'.");
}
partial void OnIsLoadingChanged(bool value)
{
_loadingPresentation.Update(value);
RefreshListPlaceholderState();
}
private void OnLoadingPresentationChanged(object? sender, PropertyChangedEventArgs e) => RefreshListPlaceholderState();
private void OnLanguageChanged(object? sender, EventArgs e)
{
OnPropertyChanged(nameof(Title));
OnPropertyChanged(nameof(Description));
OnPropertyChanged(nameof(SearchLabel));
OnPropertyChanged(nameof(LoadingItemsText));
OnPropertyChanged(nameof(EmptyItemsText));
OnPropertyChanged(nameof(RefreshText));
OnPropertyChanged(nameof(ItemCountText));
OnPropertyChanged(nameof(LoadErrorText));
ItemsView.Refresh();
RefreshListPlaceholderState();
}
private async Task EnsureLoadedAsync()
{
try
{
await _service.RestoreCacheAsync(CancellationToken.None);
IsLoading = !_service.HasSnapshot;
await _service.EnsureLoadedAsync(CancellationToken.None);
RebuildItems(_service.CurrentItems);
HasLoadError = !_service.IsSnapshotComplete;
}
catch (Exception ex)
{
HasLoadError = true;
FrontendDebugLog.Warning(nameof(Windows11ContextMenuPageViewModel), ex.ToString());
}
finally
{
IsLoading = false;
}
}
private void OnItemsChanged(object? sender, EventArgs e)
{
// Debounce rebuilds: the service can raise ItemsChanged repeatedly while
// scanning, and rebuilding rebuilds every grouped item view model.
_rebuildCts?.Cancel();
_rebuildCts?.Dispose();
var cts = _rebuildCts = new CancellationTokenSource();
_ = DebouncedRebuildItemsAsync(cts);
}
private async Task DebouncedRebuildItemsAsync(CancellationTokenSource cts)
{
try
{
await Task.Delay(RebuildDebounceMilliseconds, cts.Token);
if (cts.IsCancellationRequested || !ReferenceEquals(_rebuildCts, cts))
{
return;
}
RebuildItems(_service.CurrentItems);
HasLoadError = !_service.IsSnapshotComplete;
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
FrontendDebugLog.Warning(
nameof(Windows11ContextMenuPageViewModel),
$"RebuildItems failed: {ex}");
}
}
private void RebuildItems(IReadOnlyList<Windows11ContextMenuItemDefinition> items)
{
var pendingApprovalKeys = GetPendingApprovalKeys();
var existing = Items.ToDictionary(item => CreateLogicalGroupKey(item.Definitions[0]), StringComparer.OrdinalIgnoreCase);
var target = new List<Windows11ContextMenuItemViewModel>();
foreach (var group in items.GroupBy(CreateLogicalGroupKey, StringComparer.OrdinalIgnoreCase)
.OrderBy(group => group.First().Package.DisplayName, StringComparer.CurrentCultureIgnoreCase))
{
if (!existing.Remove(group.Key, out var row))
row = new Windows11ContextMenuItemViewModel(group.ToArray(), _service, _localization, _settingsService);
else row.UpdateDefinitions(group.ToArray());
row.RefreshPendingApproval(group.Any(definition => pendingApprovalKeys.Contains(ApprovalKey(definition))));
target.Add(row);
}
IncrementalCollection.Apply(Items, target);
foreach (var removed in existing.Values) removed.Dispose();
RefreshListPlaceholderState();
}
private static string CreateLogicalGroupKey(Windows11ContextMenuItemDefinition item)
{
if (item.SourceKind == Windows11ContextMenuSourceKind.SystemCommandStore)
{
return string.Join("|", "win11-system", item.Entry?.KeyName ?? item.Id);
}
return "win11-app|" + item.Package.FamilyName;
}
private static string ApprovalKey(Windows11ContextMenuItemDefinition item) => item.Entry is not null
? ContextMenuApprovalIdentity.CreateLogicalItemKey(item.Entry)
: ContextMenuApprovalIdentity.CreateWindows11LogicalItemKey(item.Package.FamilyName, item.ComServer.Id);
private bool FilterItem(object obj)
{
return obj is Windows11ContextMenuItemViewModel item
&& ContextMenuSearchMatcher.MatchesWindows11Item(item, SearchText);
}
private static string SanitizeLogText(string? text)
{
return (text ?? string.Empty)
.Replace("\r", "\\r", StringComparison.Ordinal)
.Replace("\n", "\\n", StringComparison.Ordinal);
}
/// <summary>
/// Executes dispose.
/// </summary>
public void Dispose()
{
_loadingPresentation.PropertyChanged -= OnLoadingPresentationChanged;
_loadingPresentation.Dispose();
_rebuildCts?.Cancel();
_rebuildCts?.Dispose();
_rebuildCts = null;
_localization.LanguageChanged -= OnLanguageChanged;
_service.ItemsChanged -= OnItemsChanged;
_globalSearchFilterService.FilterRequested -= OnGlobalSearchFilterRequested;
_workspace.Items.CollectionChanged -= OnWorkspaceItemsChanged;
foreach (var item in _workspace.Items)
{
item.PropertyChanged -= OnWorkspaceItemPropertyChanged;
}
foreach (var item in Items)
{
item.Dispose();
}
}
private HashSet<string> GetPendingApprovalKeys()
{
return _workspace.Items
.Where(static item => item.IsPendingApproval && item.IsWindows11ContextMenu)
.Select(static item => ContextMenuApprovalIdentity.CreateLogicalItemKey(item.Entry))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
}
private void RefreshPendingApprovalStates()
{
var pendingApprovalKeys = GetPendingApprovalKeys();
foreach (var item in Items)
{
item.RefreshPendingApproval(item.Definitions.Any(definition => pendingApprovalKeys.Contains(ApprovalKey(definition))));
}
}
private void OnWorkspaceItemsChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems is not null)
{
foreach (ContextMenuItemViewModel item in e.NewItems)
{
item.PropertyChanged += OnWorkspaceItemPropertyChanged;
}
}
if (e.OldItems is not null)
{
foreach (ContextMenuItemViewModel item in e.OldItems)
{
item.PropertyChanged -= OnWorkspaceItemPropertyChanged;
}
}
RefreshPendingApprovalStates();
RefreshListPlaceholderState();
}
private void OnWorkspaceItemPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName is nameof(ContextMenuItemViewModel.IsPendingApproval)
or nameof(ContextMenuItemViewModel.IsWindows11ContextMenu))
{
RefreshPendingApprovalStates();
}
}
private void RefreshListPlaceholderState()
{
OnPropertyChanged(nameof(ItemCountText));
OnPropertyChanged(nameof(LoadErrorText));
OnPropertyChanged(nameof(IsListLoading));
OnPropertyChanged(nameof(ShowListContent));
OnPropertyChanged(nameof(IsListEmpty));
OnPropertyChanged(nameof(ShowListPlaceholder));
}
}