-
Notifications
You must be signed in to change notification settings - Fork 847
Expand file tree
/
Copy pathPackageCollections.cs
More file actions
387 lines (339 loc) · 14.1 KB
/
Copy pathPackageCollections.cs
File metadata and controls
387 lines (339 loc) · 14.1 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
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net.Http;
using Avalonia.Collections;
using Avalonia.Media.Imaging;
using Avalonia.Threading;
using UniGetUI.Avalonia.ViewModels.Pages;
using UniGetUI.Core.Logging;
using UniGetUI.Core.SettingsEngine;
using UniGetUI.Core.Tools;
using UniGetUI.Interface.Enums;
using UniGetUI.PackageEngine.Interfaces;
#if WINDOWS
using UniGetUI.PackageEngine.Managers.WingetManager;
#endif
// ReSharper disable once CheckNamespace
namespace UniGetUI.PackageEngine.PackageClasses;
/// <summary>
/// Avalonia-compatible package wrapper (replaces the WinUI PackageWrapper that uses Microsoft.UI.Xaml).
/// </summary>
public sealed class PackageWrapper : INotifyPropertyChanged, IDisposable
{
private static readonly HttpClient _iconHttpClient = new(CoreTools.GenericHttpClientParameters)
{
Timeout = TimeSpan.FromSeconds(8),
};
private static readonly ConcurrentDictionary<long, Bitmap?> _iconCache = new();
private static readonly SemaphoreSlim _iconLoadSemaphore = new(4, 4);
public IPackage Package { get; }
public PackageWrapper Self => this;
public int Index { get; set; }
public event PropertyChangedEventHandler? PropertyChanged;
private readonly PackagesPageViewModel _page;
private Bitmap? _iconBitmap;
public Bitmap? IconBitmap
{
get => _iconBitmap;
private set
{
_iconBitmap = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IconBitmap)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasCustomIcon)));
}
}
public bool HasCustomIcon => _iconBitmap is not null;
public bool IsChecked
{
get => Package.IsChecked;
set
{
Package.IsChecked = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsChecked)));
_page.UpdatePackageCount();
}
}
public string VersionComboString { get; }
public string ListedNameTooltip { get; private set; } = "";
public float ListedOpacity { get; private set; } = 1.0f;
public string TagIconPath { get; private set; } = "";
public bool TagIconVisible { get; private set; }
public bool InstallerHostChanged { get; private set; }
public string InstallerHostChangeTooltip { get; private set; } = "";
private CancellationTokenSource? _installerHostCheckCts;
public string SourceIconPath => IconTypeToSvgPath(Package.Source.IconId);
private static string IconTypeToSvgPath(IconType icon)
{
string name = icon switch
{
IconType.Chocolatey => "choco",
IconType.MsStore => "ms_store",
IconType.LocalPc => "local_pc",
IconType.SaveAs => "save_as",
IconType.SysTray => "sys_tray",
IconType.ClipboardList => "clipboard_list",
IconType.OpenFolder => "open_folder",
IconType.AddTo => "add_to",
_ => icon.ToString().ToLowerInvariant(),
};
return $"avares://UniGetUI.Avalonia/Assets/Symbols/{name}.svg";
}
public PackageWrapper(IPackage package, PackagesPageViewModel page)
{
Package = package;
_page = page;
VersionComboString = package.VersionString;
Package.PropertyChanged += Package_PropertyChanged;
UpdateDisplayState();
if (!Settings.Get(Settings.K.DisableIconsOnPackageLists))
_ = LoadIconAsync();
MaybeStartInstallerHostCheck();
}
/// <summary>
/// For upgradable WinGet packages, asynchronously fetches the installer URL host for
/// both the installed and the new version, and flags the row when the hosts differ.
/// See issue #4617 — defense-in-depth signal that an upgrade may be redirecting the
/// download to a different domain than the user originally trusted.
/// </summary>
private void MaybeStartInstallerHostCheck()
{
#if WINDOWS
if (!Package.IsUpgradable) return;
if (Package.Manager is not WinGet) return;
if (Settings.Get(Settings.K.DisableInstallerHostChangeWarning)) return;
string installedVersion = Package.VersionString;
string newVersion = Package.NewVersionString;
if (string.IsNullOrWhiteSpace(installedVersion) || string.IsNullOrWhiteSpace(newVersion))
return;
if (installedVersion == newVersion) return;
_installerHostCheckCts?.Cancel();
_installerHostCheckCts = new CancellationTokenSource();
CancellationToken token = _installerHostCheckCts.Token;
_ = Task.Run(async () =>
{
try
{
if (token.IsCancellationRequested) return;
var oldHosts = WinGet.TryGetInstallerHostsForVersion(Package, installedVersion);
if (token.IsCancellationRequested) return;
var newHosts = WinGet.TryGetInstallerHostsForVersion(Package, newVersion);
if (token.IsCancellationRequested) return;
if (oldHosts is null || newHosts is null) return;
// Only flag when the two host sets are fully disjoint. If they share even
// one host, the publisher hasn't moved hosting — adding/removing CDN mirrors
// or architectures shouldn't trigger the warning.
if (oldHosts.Overlaps(newHosts)) return;
string tooltip = CoreTools.Translate(
"Installer host changed since the installed version.\n"
+ "Old: {0}\n"
+ "New: {1}\n\n"
+ "This is usually harmless (the publisher moved hosting), "
+ "but can also indicate a hijacked package manifest. "
+ "Verify the new source before upgrading.",
string.Join(", ", oldHosts),
string.Join(", ", newHosts)
);
await Dispatcher.UIThread.InvokeAsync(() =>
{
if (token.IsCancellationRequested) return;
InstallerHostChanged = true;
InstallerHostChangeTooltip = tooltip;
PropertyChanged?.Invoke(
this,
new PropertyChangedEventArgs(nameof(InstallerHostChanged))
);
PropertyChanged?.Invoke(
this,
new PropertyChangedEventArgs(nameof(InstallerHostChangeTooltip))
);
});
}
catch (Exception ex)
{
Logger.Warn($"Installer-host check failed for {Package.Id}: {ex.Message}");
}
}, token);
#endif
}
private async Task LoadIconAsync()
{
long hash = Package.GetHash();
if (_iconCache.TryGetValue(hash, out Bitmap? cached))
{
if (cached is not null)
IconBitmap = cached;
return;
}
try
{
await _iconLoadSemaphore.WaitAsync().ConfigureAwait(false);
Bitmap bitmap;
try
{
var uri = await Task.Run(Package.GetIconUrlIfAny).ConfigureAwait(false);
if (uri is null) { _iconCache[hash] = null; return; }
if (uri.IsFile)
{
if (!IsSkiaDecodableExtension(uri.LocalPath))
{
// Avalonia's Bitmap (Skia) can't decode SVG/AVIF/ICO/TIFF — the
// icon cache may produce those. Reject upfront so we don't throw.
_iconCache[hash] = null;
return;
}
bitmap = await Task.Run(() => new Bitmap(uri.LocalPath)).ConfigureAwait(false);
}
else if (uri.Scheme is "http" or "https")
{
var bytes = await _iconHttpClient.GetByteArrayAsync(uri).ConfigureAwait(false);
using var ms = new MemoryStream(bytes);
bitmap = new Bitmap(ms);
}
else { _iconCache[hash] = null; return; }
_iconCache[hash] = bitmap;
}
finally
{
_iconLoadSemaphore.Release();
}
await Dispatcher.UIThread.InvokeAsync(() => IconBitmap = bitmap);
}
catch { _iconCache[hash] = null; }
}
private static bool IsSkiaDecodableExtension(string path)
{
string ext = Path.GetExtension(path);
return ext.Equals(".png", StringComparison.OrdinalIgnoreCase)
|| ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase)
|| ext.Equals(".jpeg", StringComparison.OrdinalIgnoreCase)
|| ext.Equals(".gif", StringComparison.OrdinalIgnoreCase)
|| ext.Equals(".bmp", StringComparison.OrdinalIgnoreCase)
|| ext.Equals(".webp", StringComparison.OrdinalIgnoreCase);
}
private void Package_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Package.Tag))
{
UpdateDisplayState();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ListedOpacity)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ListedNameTooltip)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TagIconPath)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TagIconVisible)));
}
else if (e.PropertyName == nameof(Package.IsChecked))
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsChecked)));
}
else
{
PropertyChanged?.Invoke(this, e);
}
}
private void UpdateDisplayState()
{
ListedOpacity = Package.Tag switch
{
PackageTag.OnQueue or PackageTag.BeingProcessed or PackageTag.Unavailable => 0.5f,
_ => 1.0f,
};
ListedNameTooltip = Package.Name;
string tagName = Package.Tag switch
{
PackageTag.AlreadyInstalled => "installed_filled",
PackageTag.IsUpgradable => "upgradable_filled",
PackageTag.Pinned => "pin_filled",
PackageTag.OnQueue => "sandclock",
PackageTag.BeingProcessed => "loading_filled",
PackageTag.Failed => "warning_filled",
_ => "",
};
TagIconVisible = tagName.Length > 0;
TagIconPath = TagIconVisible
? $"avares://UniGetUI.Avalonia/Assets/Symbols/{tagName}.svg"
: "";
}
public void Dispose()
{
Package.PropertyChanged -= Package_PropertyChanged;
_installerHostCheckCts?.Cancel();
_installerHostCheckCts?.Dispose();
_installerHostCheckCts = null;
}
}
/// <summary>
/// Avalonia-compatible observable collection of PackageWrapper with sorting support
/// (replaces WinUI's ObservablePackageCollection that used SortableObservableCollection).
/// </summary>
public sealed class ObservablePackageCollection : AvaloniaList<PackageWrapper>
{
public enum Sorter
{
Checked,
Name,
Id,
Version,
NewVersion,
Source,
}
public Sorter CurrentSorter { get; private set; } = Sorter.Name;
private bool _ascending = true;
/// <summary>Fires when any wrapper's IsChecked changes, or when items are added/removed.</summary>
public event EventHandler? SelectionStateChanged;
public ObservablePackageCollection()
{
CollectionChanged += OnCollectionChanged;
}
private void OnCollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.OldItems is not null)
foreach (PackageWrapper w in e.OldItems) w.PropertyChanged -= OnWrapperPropertyChanged;
if (e.NewItems is not null)
foreach (PackageWrapper w in e.NewItems) w.PropertyChanged += OnWrapperPropertyChanged;
SelectionStateChanged?.Invoke(this, EventArgs.Empty);
}
private void OnWrapperPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(PackageWrapper.IsChecked))
SelectionStateChanged?.Invoke(this, EventArgs.Empty);
}
/// <summary>Returns the tri-state value for a "select-all" checkbox: true=all, false=none, null=some.</summary>
public bool? GetSelectionState()
{
if (Count == 0) return false;
int checkedCount = 0;
foreach (var w in this) if (w.IsChecked) checkedCount++;
if (checkedCount == 0) return false;
if (checkedCount == Count) return true;
return null;
}
public List<IPackage> GetPackages() =>
this.Select(w => w.Package).ToList();
public List<IPackage> GetCheckedPackages() =>
this.Where(w => w.IsChecked).Select(w => w.Package).ToList();
public void SelectAll()
{
foreach (var w in this) w.IsChecked = true;
}
public void ClearSelection()
{
foreach (var w in this) w.IsChecked = false;
}
public void SortBy(Sorter sorter) => CurrentSorter = sorter;
public void SetSortDirection(bool ascending) => _ascending = ascending;
/// <summary>Returns <paramref name="items"/> in the current sort order.</summary>
public IEnumerable<PackageWrapper> ApplyToList(IEnumerable<PackageWrapper> items) =>
_ascending
? items.OrderBy(GetSortKey, StringComparer.OrdinalIgnoreCase)
: items.OrderByDescending(GetSortKey, StringComparer.OrdinalIgnoreCase);
private string GetSortKey(PackageWrapper w) => CurrentSorter switch
{
Sorter.Checked => w.IsChecked ? "0" : "1",
Sorter.Name => w.Package.Name,
Sorter.Id => w.Package.Id,
Sorter.Version => w.Package.NormalizedVersion.ToString() ?? string.Empty,
Sorter.NewVersion => w.Package.NormalizedNewVersion.ToString() ?? string.Empty,
Sorter.Source => w.Package.Source.AsString_DisplayName,
_ => w.Package.Name,
};
}