-
Notifications
You must be signed in to change notification settings - Fork 674
/
InfiniteScrollList.xaml.cs
860 lines (719 loc) · 30.7 KB
/
InfiniteScrollList.xaml.cs
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Threading;
using NuGet.Common;
using NuGet.PackageManagement.VisualStudio;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Internal.Contracts;
using NuGet.VisualStudio.Telemetry;
using Mvs = Microsoft.VisualStudio.Shell;
using Resx = NuGet.PackageManagement.UI;
using Task = System.Threading.Tasks.Task;
namespace NuGet.PackageManagement.UI
{
/// <summary>
/// Interaction logic for InfiniteScrollList.xaml
/// </summary>
public partial class InfiniteScrollList : UserControl
{
private readonly LoadingStatusIndicator _loadingStatusIndicator = new LoadingStatusIndicator();
private readonly LoadingStatusIndicator _loadingVulnerabilitiesStatusIndicator = new LoadingStatusIndicator();
private ScrollViewer _scrollViewer;
private static TimeSpan PollingDelay = TimeSpan.FromMilliseconds(100);
public event SelectionChangedEventHandler SelectionChanged;
public event RoutedEventHandler GroupExpansionChanged;
public delegate void UpdateButtonClickEventHandler(PackageItemViewModel[] selectedPackages);
public event UpdateButtonClickEventHandler UpdateButtonClicked;
/// <summary>
/// Fires when the items in the list have finished loading.
/// It is triggered at <see cref="RepopulatePackageList(PackageItemViewModel, IPackageItemLoader, CancellationToken) " />, just before it is finished
/// </summary>
internal event EventHandler LoadItemsCompleted;
private CancellationTokenSource _loadCts;
private IPackageItemLoader _loader;
private INuGetUILogger _logger;
private Task<SearchResultContextInfo> _initialSearchResultTask;
private readonly Lazy<JoinableTaskFactory> _joinableTaskFactory;
private bool _checkBoxesEnabled;
private const string LogEntrySource = "NuGet Package Manager";
private bool _filterByVulnerabilities = false;
// The count of packages that are selected
private int _selectedCount;
public InfiniteScrollList()
: this(new Lazy<JoinableTaskFactory>(() => NuGetUIThreadHelper.JoinableTaskFactory))
{
}
internal InfiniteScrollList(Lazy<JoinableTaskFactory> joinableTaskFactory)
{
if (joinableTaskFactory == null)
{
throw new ArgumentNullException(nameof(joinableTaskFactory));
}
_joinableTaskFactory = joinableTaskFactory;
InitializeComponent();
_list.ItemsLock = ReentrantSemaphore.Create(
initialCount: 1,
joinableTaskContext: _joinableTaskFactory.Value.Context,
mode: ReentrantSemaphore.ReentrancyMode.Stack);
BindingOperations.EnableCollectionSynchronization(Items, _list.ItemsLock);
ItemsView = new CollectionViewSource() { Source = Items }.View;
ICollectionViewLiveShaping itemsView = (ICollectionViewLiveShaping)ItemsView;
itemsView.IsLiveFiltering = true;
itemsView.IsLiveGrouping = true;
itemsView.LiveFilteringProperties.Add(nameof(PackageItemViewModel.IsPackageVulnerable));
itemsView.LiveGroupingProperties.Add(nameof(PackageItemViewModel.PackageLevel));
ItemsView.Filter = item =>
{
return FilterLoadingIndicator(item)
&& FilterVulnerabilitiesIndicator(item)
&& FilterVulnerablePackage(item);
};
DataContext = itemsView;
CheckBoxesEnabled = false;
_loadingStatusIndicator.PropertyChanged += LoadingStatusIndicator_PropertyChanged;
}
private bool FilterVulnerabilitiesIndicator(object item)
{
if (item.Equals(_loadingVulnerabilitiesStatusIndicator))
{
return _filterByVulnerabilities && !(_loadingVulnerabilitiesStatusIndicator.Status == LoadingStatus.NoItemsFound && VulnerablePackagesCount > 0);
}
return true;
}
private bool FilterLoadingIndicator(object item)
{
if (item.Equals(_loadingStatusIndicator))
{
return !_filterByVulnerabilities;
}
return true;
}
private bool FilterVulnerablePackage(object item)
{
if (_filterByVulnerabilities && item is PackageItemViewModel vm && !vm.IsPackageVulnerable)
{
return false;
}
return true;
}
private void LoadingStatusIndicator_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
_joinableTaskFactory.Value.Run(async delegate
{
await _joinableTaskFactory.Value.SwitchToMainThreadAsync();
if (e.PropertyName == nameof(LoadingStatusIndicator.Status)
&& _ltbLoading.Text != _loadingStatusIndicator.LocalizedStatus)
{
_ltbLoading.Text = _loadingStatusIndicator.LocalizedStatus;
}
});
}
public bool CheckBoxesEnabled
{
get => _checkBoxesEnabled;
set
{
if (_checkBoxesEnabled != value)
{
_checkBoxesEnabled = value;
_list.IsItemSelectionEnabled = value;
}
}
}
public bool IsSolution { get; set; }
public ObservableCollection<object> Items { get; } = new ObservableCollection<object>();
public ICollectionView ItemsView { get; private set; }
/// <summary>
/// Count of Items (excluding Loading indicator) that are currently shown after applying any UI filtering.
/// </summary>
private int FilteredItemsCount
{
get
{
return PackageItems.Count();
}
}
/// <summary>
/// All loaded Items (excluding Loading indicator) regardless of filtering.
/// </summary>
public IEnumerable<PackageItemViewModel> PackageItems => Items.OfType<PackageItemViewModel>().ToArray();
private int VulnerablePackagesCount => Items.OfType<PackageItemViewModel>().Where(i => i.IsPackageVulnerable).Count();
public PackageItemViewModel SelectedPackageItem => _list.SelectedItem as PackageItemViewModel;
public int SelectedIndex => _list.SelectedIndex;
public Guid? OperationId => _loader?.State.OperationId;
public int TopLevelPackageCount
{
get
{
var group = ItemsView.Groups.Where(g => (g as CollectionViewGroup).Name.ToString().Equals(PackageLevel.TopLevel.ToString(), StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
return group is not null ? (group as CollectionViewGroup).ItemCount : 0;
}
}
public int TransitivePackageCount
{
get
{
var group = ItemsView.Groups.Where(g => (g as CollectionViewGroup).Name.ToString().Equals(PackageLevel.Transitive.ToString(), StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
return group is not null ? (group as CollectionViewGroup).ItemCount : 0;
}
}
// Load items using the specified loader
internal async Task LoadItemsAsync(
IPackageItemLoader loader,
string loadingMessage,
INuGetUILogger logger,
Task<SearchResultContextInfo> searchResultTask,
CancellationToken token)
{
if (loader == null)
{
throw new ArgumentNullException(nameof(loader));
}
if (string.IsNullOrEmpty(loadingMessage))
{
throw new ArgumentException(Strings.Argument_Cannot_Be_Null_Or_Empty, nameof(loadingMessage));
}
if (searchResultTask == null)
{
throw new ArgumentNullException(nameof(searchResultTask));
}
token.ThrowIfCancellationRequested();
_loader = loader;
_logger = logger;
_initialSearchResultTask = searchResultTask;
_loadingStatusIndicator.Reset(loadingMessage);
_loadingVulnerabilitiesStatusIndicator.Reset(string.Format(CultureInfo.CurrentCulture, Resx.Resources.Vulnerabilities_Loading));
_loadingVulnerabilitiesStatusIndicator.Status = LoadingStatus.Loading;
_loadingStatusBar.Visibility = Visibility.Hidden;
_loadingStatusBar.Reset(loadingMessage, loader.IsMultiSource);
var selectedPackageItem = SelectedPackageItem;
await _list.ItemsLock.ExecuteAsync(() =>
{
ClearPackageList();
return Task.CompletedTask;
});
_selectedCount = 0;
// triggers the package list loader
await LoadItemsAsync(selectedPackageItem, token);
}
/// <summary>
/// Keep the previously selected package after a search.
/// Otherwise, select the first on the search if none was selected before.
/// </summary>
/// <param name="selectedItem">Previously selected item</param>
internal void UpdateSelectedItem(PackageItemViewModel selectedItem)
{
if (selectedItem != null)
{
// select the the previously selected item if it still exists.
selectedItem = PackageItems
.FirstOrDefault(item => item.Id.Equals(selectedItem.Id, StringComparison.OrdinalIgnoreCase));
}
// select the first item if none was selected before
_list.SelectedItem = selectedItem ?? PackageItems.FirstOrDefault();
}
private async Task LoadItemsAsync(PackageItemViewModel selectedPackageItem, CancellationToken token)
{
// If there is another async loading process - cancel it.
var loadCts = CancellationTokenSource.CreateLinkedTokenSource(token);
Interlocked.Exchange(ref _loadCts, loadCts)?.Cancel();
await RepopulatePackageListAsync(selectedPackageItem, _loader, loadCts);
}
private async Task RepopulatePackageListAsync(PackageItemViewModel selectedPackageItem, IPackageItemLoader currentLoader, CancellationTokenSource loadCts)
{
await TaskScheduler.Default;
var addedLoadingIndicator = false;
try
{
// add Loading... indicator if not present
if (!Items.Contains(_loadingStatusIndicator))
{
Items.Add(_loadingStatusIndicator);
addedLoadingIndicator = true;
}
if (!Items.Contains(_loadingVulnerabilitiesStatusIndicator))
{
Items.Add(_loadingVulnerabilitiesStatusIndicator);
}
await LoadItemsCoreAsync(currentLoader, loadCts.Token);
await _joinableTaskFactory.Value.SwitchToMainThreadAsync();
if (selectedPackageItem != null)
{
UpdateSelectedItem(selectedPackageItem);
}
}
catch (OperationCanceledException) when (!loadCts.IsCancellationRequested)
{
loadCts.Cancel();
loadCts.Dispose();
currentLoader.Reset();
await _joinableTaskFactory.Value.SwitchToMainThreadAsync();
// The user cancelled the login, but treat as a load error in UI
// So the retry button and message is displayed
// Do not log to the activity log, since it is not a NuGet error
_logger.Log(new LogMessage(LogLevel.Error, Resx.Resources.Text_UserCanceled));
_loadingStatusIndicator.SetError(Resx.Resources.Text_UserCanceled);
_loadingStatusBar.SetCancelled();
_loadingStatusBar.Visibility = Visibility.Visible;
}
catch (Exception ex) when (!loadCts.IsCancellationRequested)
{
loadCts.Cancel();
loadCts.Dispose();
currentLoader.Reset();
// Write stack to activity log
Mvs.ActivityLog.LogError(LogEntrySource, ex.ToString());
await _joinableTaskFactory.Value.SwitchToMainThreadAsync();
var errorMessage = ExceptionUtilities.DisplayMessage(ex);
_logger.Log(new LogMessage(LogLevel.Error, errorMessage));
_loadingStatusIndicator.SetError(errorMessage);
_loadingStatusBar.SetError();
_loadingStatusBar.Visibility = Visibility.Visible;
}
finally
{
if (VulnerablePackagesCount == 0)
{
_loadingVulnerabilitiesStatusIndicator.Status = LoadingStatus.NoItemsFound;
}
else
{
Items.Remove(_loadingVulnerabilitiesStatusIndicator);
}
if (_loadingStatusIndicator.Status != LoadingStatus.NoItemsFound
&& _loadingStatusIndicator.Status != LoadingStatus.ErrorOccurred)
{
// Ideally, after a search, it should report its status, and
// do not keep the LoadingStatus.Loading forever.
// This is a workaround.
var emptyListCount = addedLoadingIndicator ? 1 : 0;
if (Items.Count == emptyListCount)
{
_loadingStatusIndicator.Status = LoadingStatus.NoItemsFound;
}
else
{
Items.Remove(_loadingStatusIndicator);
}
}
}
UpdateCheckBoxStatus();
LoadItemsCompleted?.Invoke(this, EventArgs.Empty);
}
private async Task LoadItemsCoreAsync(IPackageItemLoader currentLoader, CancellationToken token)
{
token.ThrowIfCancellationRequested();
var loadedItems = await LoadNextPageAsync(currentLoader, token);
token.ThrowIfCancellationRequested();
// multiple loads may occur at the same time as a result of multiple instances,
// makes sure we update using the relevant one.
if (currentLoader == _loader)
{
UpdatePackageList(loadedItems, refresh: false);
}
token.ThrowIfCancellationRequested();
await _joinableTaskFactory.Value.RunAsync(async () =>
{
await _joinableTaskFactory.Value.SwitchToMainThreadAsync();
_loadingStatusBar.ItemsLoaded = currentLoader.State.ItemsCount;
});
token.ThrowIfCancellationRequested();
// keep waiting till completion
await WaitForCompletionAsync(currentLoader, token);
token.ThrowIfCancellationRequested();
if (currentLoader == _loader
&& !loadedItems.Any()
&& currentLoader.State.LoadingStatus == LoadingStatus.Ready)
{
UpdatePackageList(currentLoader.GetCurrent(), refresh: false);
}
token.ThrowIfCancellationRequested();
}
private async Task<IEnumerable<PackageItemViewModel>> LoadNextPageAsync(IPackageItemLoader currentLoader, CancellationToken token)
{
var progress = new Progress<IItemLoaderState>(
s => HandleItemLoaderStateChange(currentLoader, s));
// if searchResultTask is in progress then just wait for it to complete
// without creating new load task
if (_initialSearchResultTask != null)
{
token.ThrowIfCancellationRequested();
// update initial progress
await currentLoader.UpdateStateAndReportAsync(new SearchResultContextInfo(), progress, token);
var results = await _initialSearchResultTask;
token.ThrowIfCancellationRequested();
// update state and progress
await currentLoader.UpdateStateAndReportAsync(results, progress, token);
_initialSearchResultTask = null;
}
else
{
// trigger loading
await currentLoader.LoadNextAsync(progress, token);
}
await WaitForInitialResultsAsync(currentLoader, progress, token);
return currentLoader.GetCurrent();
}
private async Task WaitForCompletionAsync(IItemLoader<PackageItemViewModel> currentLoader, CancellationToken token)
{
var progress = new Progress<IItemLoaderState>(
s => HandleItemLoaderStateChange(currentLoader, s));
// run to completion
while (currentLoader.State.LoadingStatus == LoadingStatus.Loading)
{
token.ThrowIfCancellationRequested();
await Task.Delay(PollingDelay, token);
await currentLoader.UpdateStateAsync(progress, token);
}
}
private async Task WaitForInitialResultsAsync(
IItemLoader<PackageItemViewModel> currentLoader,
IProgress<IItemLoaderState> progress,
CancellationToken token)
{
while (currentLoader.State.LoadingStatus == LoadingStatus.Loading &&
currentLoader.State.ItemsCount == 0)
{
token.ThrowIfCancellationRequested();
await Task.Delay(PollingDelay, token);
await currentLoader.UpdateStateAsync(progress, token);
}
}
/// <summary>
/// Shows the Loading status bar, if necessary. Also, it inserts the Loading... indicator, if necesary
/// </summary>
/// <param name="loader">Current loader</param>
/// <param name="state">Progress reported by the <c>Progress</c> callback</param>
private void HandleItemLoaderStateChange(IItemLoader<PackageItemViewModel> loader, IItemLoaderState state)
{
NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(async () =>
{
if (loader == _loader)
{
await _joinableTaskFactory.Value.SwitchToMainThreadAsync();
_loadingStatusBar.UpdateLoadingState(state);
// decide when to show status bar
var desiredVisibility = EvaluateStatusBarVisibility(loader, state);
if (_loadingStatusBar.Visibility != Visibility.Visible
&& desiredVisibility == Visibility.Visible)
{
_loadingStatusBar.Visibility = desiredVisibility;
}
_loadingStatusIndicator.Status = state.LoadingStatus;
if (!Items.Contains(_loadingStatusIndicator))
{
await _list.ItemsLock.ExecuteAsync(() =>
{
Items.Add(_loadingStatusIndicator);
return Task.CompletedTask;
});
}
}
}).PostOnFailure(nameof(InfiniteScrollList), nameof(HandleItemLoaderStateChange));
}
private Visibility EvaluateStatusBarVisibility(IItemLoader<PackageItemViewModel> loader, IItemLoaderState state)
{
var statusBarVisibility = Visibility.Hidden;
if (state.LoadingStatus == LoadingStatus.Cancelled
|| state.LoadingStatus == LoadingStatus.ErrorOccurred)
{
statusBarVisibility = Visibility.Visible;
}
if (loader.IsMultiSource)
{
var hasMore = _loadingStatusBar.ItemsLoaded != 0 && state.ItemsCount > _loadingStatusBar.ItemsLoaded;
if (hasMore)
{
statusBarVisibility = Visibility.Visible;
}
if (state.LoadingStatus == LoadingStatus.Loading && state.ItemsCount > 0)
{
statusBarVisibility = Visibility.Visible;
}
}
return statusBarVisibility;
}
/// <summary>
/// Appends <c>packages</c> to the internal <see cref="Items"> list
/// </summary>
/// <param name="packages">Packages collection to add</param>
/// <param name="refresh">Clears <see cref="Items"> list if set to <see langword="true" /></param>
private void UpdatePackageList(IEnumerable<PackageItemViewModel> packages, bool refresh)
{
_joinableTaskFactory.Value.Run(async () =>
{
// Synchronize updating Items list
await _list.ItemsLock.ExecuteAsync(() =>
{
// remove the loading status indicator if it's in the list
bool removed = Items.Remove(_loadingStatusIndicator);
if (refresh)
{
ClearPackageList();
}
// add newly loaded items
foreach (var package in packages)
{
package.PropertyChanged += Package_PropertyChanged;
Items.Add(package);
_selectedCount = package.IsSelected ? _selectedCount + 1 : _selectedCount;
}
if (removed)
{
Items.Add(_loadingStatusIndicator);
}
return Task.CompletedTask;
});
});
}
/// <summary>
/// Clear <c>Items</c> list and removes the event handlers for each element
/// </summary>
private void ClearPackageList()
{
foreach (var package in PackageItems)
{
package.PropertyChanged -= Package_PropertyChanged;
package.Dispose();
}
Items.Clear();
_loadingStatusBar.ItemsLoaded = 0;
}
public void UpdatePackageStatus(PackageCollectionItem[] installedPackages)
{
// in this case, we only need to update PackageStatus of
// existing items in the package list
foreach (var package in PackageItems)
{
if (package.PackageLevel == PackageLevel.TopLevel)
{
package.UpdatePackageStatus(installedPackages);
}
else
{
package.UpdateTransitivePackageStatus(package.InstalledVersion);
}
}
}
private void Package_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
var package = sender as PackageItemViewModel;
if (e.PropertyName == nameof(package.IsSelected))
{
if (package.IsSelected)
{
_selectedCount++;
}
else
{
_selectedCount--;
}
UpdateCheckBoxStatus();
}
}
// Update the status of the _selectAllPackages check box and the Update button.
private void UpdateCheckBoxStatus()
{
// The current tab is not "Updates".
if (!CheckBoxesEnabled)
{
_updateButtonContainer.Visibility = Visibility.Collapsed;
return;
}
//Are any packages shown with the current filter?
int packageCount = FilteredItemsCount;
_updateButtonContainer.Visibility =
packageCount > 0 ?
Visibility.Visible :
Visibility.Collapsed;
if (_selectedCount == 0)
{
_selectAllPackages.IsChecked = false;
_updateButton.IsEnabled = false;
}
else if (_selectedCount < packageCount)
{
_selectAllPackages.IsChecked = null;
_updateButton.IsEnabled = true;
}
else
{
_selectAllPackages.IsChecked = true;
_updateButton.IsEnabled = true;
}
}
public PackageItemViewModel SelectedItem
{
get
{
return _list.SelectedItem as PackageItemViewModel;
}
internal set
{
_list.SelectedItem = value;
}
}
private void List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0
&& e.AddedItems[0] is LoadingStatusIndicator)
{
// make the loading object not selectable
if (e.RemovedItems.Count > 0)
{
_list.SelectedItem = e.RemovedItems[0];
}
else
{
_list.SelectedIndex = -1;
}
}
else
{
if (SelectionChanged != null)
{
SelectionChanged(this, e);
}
}
}
private void List_Loaded(object sender, RoutedEventArgs e)
{
_list.Loaded -= List_Loaded;
var c = VisualTreeHelper.GetChild(_list, 0) as Border;
if (c == null)
{
return;
}
c.Padding = new Thickness(0);
_scrollViewer = VisualTreeHelper.GetChild(c, 0) as ScrollViewer;
if (_scrollViewer == null)
{
return;
}
_scrollViewer.Padding = new Thickness(0);
_scrollViewer.ScrollChanged += ScrollViewer_ScrollChanged;
}
private void ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
int packagesCount = Items.Count;
if (Items.Contains(_loadingStatusIndicator))
{
packagesCount--;
}
if (Items.Contains(_loadingVulnerabilitiesStatusIndicator))
{
packagesCount--;
}
if (_loader?.State.LoadingStatus == LoadingStatus.Ready)
{
var first = _scrollViewer.VerticalOffset;
var last = _scrollViewer.ViewportHeight + first;
if (_scrollViewer.ViewportHeight > 0 && last >= packagesCount)
{
NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(() =>
LoadItemsAsync(selectedPackageItem: null, token: CancellationToken.None)
).PostOnFailure(nameof(InfiniteScrollList));
}
}
}
private void SelectAllPackagesCheckBox_Checked(object sender, RoutedEventArgs e)
{
foreach (var item in _list.Items)
{
var package = item as PackageItemViewModel;
// note that item could be the loading indicator, thus we need to check
// for null here.
if (package != null)
{
package.IsSelected = true;
}
}
}
private void SelectAllPackagesCheckBox_Unchecked(object sender, RoutedEventArgs e)
{
foreach (var item in _list.Items)
{
var package = item as PackageItemViewModel;
if (package != null)
{
package.IsSelected = false;
}
}
}
private void _updateButton_Click(object sender, RoutedEventArgs e)
{
var selectedPackages = PackageItems.Where(p => p.IsSelected).ToArray();
UpdateButtonClicked(selectedPackages);
}
private void List_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Space && e.OriginalSource is ListBoxItem && _list.SelectedItem is PackageItemViewModel package)
{
// toggle the selection state when user presses the space bar
package.IsSelected = !package.IsSelected;
e.Handled = true;
}
}
private void _loadingStatusBar_ShowMoreResultsClick(object sender, RoutedEventArgs e)
{
var packageItems = _loader?.GetCurrent() ?? Enumerable.Empty<PackageItemViewModel>();
UpdatePackageList(packageItems, refresh: true);
_loadingStatusBar.ItemsLoaded = _loader?.State.ItemsCount ?? 0;
var desiredVisibility = EvaluateStatusBarVisibility(_loader, _loader.State);
if (_loadingStatusBar.Visibility != desiredVisibility)
{
_loadingStatusBar.Visibility = desiredVisibility;
}
}
private void _loadingStatusBar_DismissClick(object sender, RoutedEventArgs e)
{
_loadingStatusBar.Visibility = Visibility.Hidden;
}
public void ResetLoadingStatusIndicator()
{
_loadingStatusIndicator.Reset(string.Empty);
}
internal void ClearPackageLevelGrouping()
{
ItemsView.GroupDescriptions.Clear();
}
internal void AddVulnerabilitiesFiltering()
{
_filterByVulnerabilities = true;
ItemsView.Refresh();
}
internal void RemoveVulnerabilitiesFiltering()
{
_filterByVulnerabilities = false;
ItemsView.Refresh();
}
internal void AddPackageLevelGrouping()
{
ItemsView.Refresh();
if (Items
.OfType<PackageItemViewModel>()
.Any(p => p.PackageLevel == PackageLevel.Transitive))
{
ItemsView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(PackageItemViewModel.PackageLevel)));
}
}
private void Expander_ExpansionStateToggled(object sender, RoutedEventArgs e)
{
GroupExpansionChanged?.Invoke(sender, e);
}
}
}