Portable Tool for an Ideal Windows Setup
C# activatorbloatware-removalcsharpdebloatdebloaterdisable-servicesmonitoring-systemportableprivacy-toolsregistry-tweakssystem-tuningsystem-utilitytelemetrytweakerwindows-10windows-11windows-debloatwindows-defenderwindows-optimizationwindows-tweaks
upd download logic & implement resume support
Greedeks01f0ea1cfa99
diff --git a/.Source/GTweak/Assets/UserControls/FlowPanel.cs b/.Source/GTweak/Assets/UserControls/FlowPanel.csindex 787e8e21..b3aaccb8 100644--- a/.Source/GTweak/Assets/UserControls/FlowPanel.cs+++ b/.Source/GTweak/Assets/UserControls/FlowPanel.cs@@ -223,7 +223,17 @@ namespace GTweak.Assets.UserControls}}- double verticalRequired = totalVerticalHeight + (count > 1 ? (count - 1) * VerticalSpacing : 0);+ double verticalRequired = 0;+ if (count > 1)+ {+ double buttonHeight = GetChildHeight(_visibleCache[count - 1]);+ verticalRequired = totalVerticalHeight - buttonHeight + ((count - 2) * VerticalSpacing);+ verticalRequired = Math.Max(verticalRequired, buttonHeight);+ }+ else+ {+ verticalRequired = totalVerticalHeight;+ }Size resultSize;if (horizontalRequired <= aw || double.IsInfinity(aw))@@ -314,9 +324,18 @@ namespace GTweak.Assets.UserControlsUIElement child = _visibleCache[i];double w = GetChildWidth(child);double h = GetChildHeight(child);- double xOffset = GetResponsiveAlignmentOffset(finalSize.Width, w);- child.Arrange(new Rect(xOffset, y, w, h));- y += h + VerticalSpacing;++ if (i == count - 1 && count > 1)+ {+ double buttonY = Math.Max(0, (GetChildHeight(_visibleCache[0]) - h) / 2.0);+ child.Arrange(new Rect(finalSize.Width - w, buttonY, w, h));+ }+ else+ {+ double xOffset = GetResponsiveAlignmentOffset(finalSize.Width, w);+ child.Arrange(new Rect(xOffset, y, w, h));+ y += h + VerticalSpacing;+ }}}}diff --git a/.Source/GTweak/Core/Service/ToolsetDownloadService.cs b/.Source/GTweak/Core/Services/ToolsetDownloadService.cssimilarity index 62%rename from .Source/GTweak/Core/Service/ToolsetDownloadService.csrename to .Source/GTweak/Core/Services/ToolsetDownloadService.csindex f8d17029..6e5f4f10 100644--- a/.Source/GTweak/Core/Service/ToolsetDownloadService.cs+++ b/.Source/GTweak/Core/Services/ToolsetDownloadService.cs@@ -1,18 +1,23 @@using System;+using System.Collections.Concurrent;using System.IO;+using System.Net;using System.Net.Http;+using System.Net.Http.Headers;using System.Text.RegularExpressions;using System.Threading;using System.Threading.Tasks;using GTweak.Core.Models;+using GTweak.Core.ViewModel.Components;using GTweak.Utilities.Controls;using Newtonsoft.Json.Linq;-namespace GTweak.Core.Service+namespace GTweak.Core.Services{internal static class ToolsetDownloadService{private static readonly HttpClient _httpClient;+ private static readonly ConcurrentDictionary<string, DownloadSession> _sessions = new ConcurrentDictionary<string, DownloadSession>();static ToolsetDownloadService(){@@ -20,7 +25,9 @@ namespace GTweak.Core.Service_httpClient.DefaultRequestHeaders.Add("User-Agent", "GTweak");}- public static async Task<string> ResolveDownloadUrlAsync(ToolsetModel model)+ internal static DownloadSession GetOrCreateSession(ToolsetModel model) => _sessions.GetOrAdd(!string.IsNullOrWhiteSpace(model.SourceUrl) ? model.SourceUrl : model.AppName, _ => new DownloadSession(model));++ internal static async Task<string> GetResolvedDownloadUrl(ToolsetModel model){try{@@ -63,7 +70,8 @@ namespace GTweak.Core.ServicefirstFoundUrl ??= downloadUrl;- if (!string.IsNullOrEmpty(model.FilePattern) && Regex.IsMatch(downloadUrl, model.FilePattern, RegexOptions.IgnoreCase))+ if (!string.IsNullOrEmpty(model.FilePattern) &&+ Regex.IsMatch(downloadUrl, model.FilePattern, RegexOptions.IgnoreCase)){return downloadUrl;}@@ -78,36 +86,75 @@ namespace GTweak.Core.Servicereturn null;}- public static async Task DownloadFileAsync(string url, string destinationPath, string referrer, IProgress<double> progress, CancellationToken ct)+ internal static async Task DownloadFile(string url, string destinationPath, string referrer, IProgress<double> progress, CancellationToken ct){- string tempPath = destinationPath + ".tmp";+ string tempPath = $"{destinationPath}.download";+ long existingBytes = 0;+ bool append = false;+try{+ if (File.Exists(tempPath))+ {+ existingBytes = new FileInfo(tempPath).Length;+ }+using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);+if (!string.IsNullOrEmpty(referrer)){request.Headers.Referrer = new Uri(referrer);}+ if (existingBytes > 0)+ {+ request.Headers.Range = new RangeHeaderValue(existingBytes, null);+ }+using HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);++ if (existingBytes > 0 && response.StatusCode == HttpStatusCode.OK)+ {+ existingBytes = 0;+ append = false;+ }+ else if (response.StatusCode == HttpStatusCode.PartialContent && existingBytes > 0)+ {+ append = true;+ }+response.EnsureSuccessStatusCode();- long totalBytes = response.Content.Headers.ContentLength ?? -1L;+ long contentLength = response.Content.Headers.ContentLength ?? -1L;+ long totalBytes = contentLength;++ if (response.StatusCode == HttpStatusCode.PartialContent && contentLength > 0)+ {+ totalBytes = existingBytes + contentLength;+ }++ long totalReadBytes = existingBytes;+ int lastReportedProgress = -1;using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())- using (FileStream fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None))+ using (FileStream fileStream = new FileStream(tempPath, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.None)){byte[] buffer = new byte[8192];- long totalReadBytes = 0L;int readBytes;- int lastReportedProgress = 0;++ if (progress != null && totalBytes > 0 && existingBytes > 0)+ {+ int initialProgress = (int)Math.Round((double)existingBytes / totalBytes * 100);+ progress.Report(initialProgress);+ lastReportedProgress = initialProgress;+ }while ((readBytes = await streamToReadFrom.ReadAsync(buffer, 0, buffer.Length, ct)) > 0){await fileStream.WriteAsync(buffer, 0, readBytes, ct);totalReadBytes += readBytes;- if (totalBytes != -1 && progress != null)+ if (totalBytes > 0 && progress != null){int newProgress = (int)Math.Round((double)totalReadBytes / totalBytes * 100);if (newProgress != lastReportedProgress)@@ -121,22 +168,20 @@ namespace GTweak.Core.Serviceif (File.Exists(destinationPath)){- File.Delete(destinationPath);+ File.Replace(tempPath, destinationPath, null);+ }+ else+ {+ File.Move(tempPath, destinationPath);}- File.Move(tempPath, destinationPath);progress?.Report(100);}catch (Exception ex){ErrorLogging.LogDebug(ex);- if (File.Exists(tempPath))- {- try { File.Delete(tempPath); }- catch (Exception exc) { ErrorLogging.LogDebug(exc); }- }throw;}}}-}+}\ No newline at end of filediff --git a/.Source/GTweak/Utilities/Managers/ToolsetIconManager.cs b/.Source/GTweak/Core/Services/ToolsetIconService.cssimilarity index 69%rename from .Source/GTweak/Utilities/Managers/ToolsetIconManager.csrename to .Source/GTweak/Core/Services/ToolsetIconService.csindex ee5c8208..8f9552f7 100644--- a/.Source/GTweak/Utilities/Managers/ToolsetIconManager.cs+++ b/.Source/GTweak/Core/Services/ToolsetIconService.cs@@ -8,33 +8,33 @@ using System.Windows.Media;using System.Windows.Media.Imaging;using GTweak.Utilities.Controls;-namespace GTweak.Utilities.Managers+namespace GTweak.Core.Services{- internal static class ToolsetIconManager+ internal class ToolsetIconService{private static readonly ConcurrentDictionary<string, ImageSource> _imageCache = new ConcurrentDictionary<string, ImageSource>();private static readonly HttpClient _httpClient = new HttpClient();- public static ImageSource GetPlaceholder(string group) => Application.Current.TryFindResource(group.ToLower() == "github" ? "Icon_Git" : "Icon_Website") as ImageSource;+ internal static ImageSource GetPlaceholder(string group) => Application.Current.TryFindResource(group.ToLower() == "github" ? "Icon_Git" : "Icon_Website") as ImageSource;- public static async Task<(ImageSource Image, bool IsFallback)> GetAuthorIconAsync(string group, string authorIconUrlOrDomain)+ internal static async Task<(ImageSource Image, bool IsFallback)> GetAuthorIcon(string group, string iconSource){- if (string.IsNullOrWhiteSpace(authorIconUrlOrDomain))+ if (string.IsNullOrWhiteSpace(iconSource)){return (GetPlaceholder(group), true);}- if (_imageCache.TryGetValue(authorIconUrlOrDomain, out ImageSource cachedImage))+ if (_imageCache.TryGetValue(iconSource, out ImageSource cachedImage)){return (cachedImage, false);}- string urlToDownload = authorIconUrlOrDomain;+ string urlToDownload = iconSource;bool isWeb = string.Equals(group, "web", StringComparison.OrdinalIgnoreCase);if (isWeb){- urlToDownload = $"https://www.google.com/s2/favicons?domain={authorIconUrlOrDomain}&sz=48";+ urlToDownload = $"https://www.google.com/s2/favicons?domain={iconSource}&sz=48";}try@@ -44,7 +44,7 @@ namespace GTweak.Utilities.Managersif (image != null){- _imageCache.TryAdd(authorIconUrlOrDomain, image);+ _imageCache.TryAdd(iconSource, image);return (image, false);}}@@ -54,17 +54,16 @@ namespace GTweak.Utilities.Managers{try{- string backupUrl = $"https://icons.duckduckgo.com/ip3/{authorIconUrlOrDomain}.ico";- byte[] imageBytes = await _httpClient.GetByteArrayAsync(backupUrl);+ byte[] imageBytes = await _httpClient.GetByteArrayAsync($"https://icons.duckduckgo.com/ip3/{iconSource}.ico");ImageSource image = LoadImage(imageBytes);if (image != null){- _imageCache.TryAdd(authorIconUrlOrDomain, image);+ _imageCache.TryAdd(iconSource, image);return (image, false);}}- catch (Exception ex) { ErrorLogging.LogDebug(ex); }+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }}}@@ -91,7 +90,5 @@ namespace GTweak.Utilities.Managersreturn null;}-- public static ImageSource GetAppIconFromResource(string resourceName) => Application.Current.TryFindResource(resourceName) as ImageSource;}}diff --git a/.Source/GTweak/Core/ViewModel/Components/DownloadSession.cs b/.Source/GTweak/Core/ViewModel/Components/DownloadSession.csnew file mode 100644index 00000000..a9221934--- /dev/null+++ b/.Source/GTweak/Core/ViewModel/Components/DownloadSession.cs@@ -0,0 +1,102 @@+using System;+using System.IO;+using System.Threading;+using System.Threading.Tasks;+using GTweak.Core.Base;+using GTweak.Core.Models;+using GTweak.Core.Services;+using GTweak.Utilities.Controls;++namespace GTweak.Core.ViewModel.Components+{+ internal sealed class DownloadSession : ViewModelBase+ {+ private readonly ToolsetModel _model;+ private CancellationTokenSource _cts;+ private bool _isDownloading;+ private double _progress;++ public bool IsDownloading+ {+ get => _isDownloading;+ private set+ {+ if (_isDownloading != value)+ {+ _isDownloading = value;+ OnPropertyChanged();+ System.Windows.Input.CommandManager.InvalidateRequerySuggested();+ }+ }+ }++ public double Progress+ {+ get => _progress;+ private set+ {+ if (Math.Abs(_progress - value) > 0.01)+ {+ _progress = value;+ OnPropertyChanged();+ }+ }+ }++ internal DownloadSession(ToolsetModel model)+ {+ _model = model;+ }++ public async Task Start()+ {+ if (!IsDownloading)+ {+ IsDownloading = true;++ _cts?.Dispose();+ _cts = new CancellationTokenSource();++ try+ {+ string finalUrl = await ToolsetDownloadService.GetResolvedDownloadUrl(_model);++ if (!string.IsNullOrEmpty(finalUrl))+ {+ string destinationFolder = SettingsEngine.DownloadPath ?? Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);+ await ToolsetDownloadService.DownloadFile(finalUrl, Path.Combine(destinationFolder, GetFileNameFromUrl(finalUrl)), _model.SourceUrl, new Progress<double>(value => Progress = value), _cts.Token);+ }+ }+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }+ finally+ {+ IsDownloading = false;+ _cts?.Dispose();+ _cts = null;+ System.Windows.Input.CommandManager.InvalidateRequerySuggested();+ }+ }+ }++ public void Cancel()+ {+ _cts?.Cancel();+ }++ private string GetFileNameFromUrl(string url)+ {+ try+ {+ string fileName = Path.GetFileName(new Uri(url).LocalPath);++ if (string.IsNullOrEmpty(Path.GetExtension(fileName)))+ {+ return !string.IsNullOrEmpty(_model.FilePattern) ? _model.FilePattern : $"{_model.AppName}.exe";+ }++ return fileName;+ }+ catch { return $"{_model.AppName}.exe"; }+ }+ }+}diff --git a/.Source/GTweak/Core/ViewModel/Components/ToolsetItem.cs b/.Source/GTweak/Core/ViewModel/Components/ToolsetItem.csnew file mode 100644index 00000000..fe193224--- /dev/null+++ b/.Source/GTweak/Core/ViewModel/Components/ToolsetItem.cs@@ -0,0 +1,78 @@+using System;+using System.ComponentModel;+using System.Threading.Tasks;+using System.Windows;+using System.Windows.Input;+using System.Windows.Media;+using GTweak.Core.Base;+using GTweak.Core.Models;+using GTweak.Core.Services;+using GTweak.Core.ViewModel.Components;+using GTweak.Utilities.Controls;++namespace GTweak.Core.Item+{+ internal class ToolsetItem : ViewModelBase+ {+ private readonly ToolsetModel _model;+ private readonly DownloadSession _downloadSession;++ private ImageSource _appIconSource;+ private ImageSource _authorIconSource;+ private bool _isSquareIcon;++ public ImageSource AppIconSource { get => _appIconSource; set { _appIconSource = value; OnPropertyChanged(); } }+ public string AppName => _model.AppName;+ public string AuthorName => _model.AuthorName;+ public ImageSource AuthorIconSource { get => _authorIconSource; set { _authorIconSource = value; OnPropertyChanged(); } }+ public bool IsSquareIcon { get => _isSquareIcon; set { _isSquareIcon = value; OnPropertyChanged(); } }+ public string SourceUrl => _model.SourceUrl;+ public bool IsDownloading => _downloadSession.IsDownloading;+ public double Progress => _downloadSession.Progress;+ public ICommand DownloadCommand { get; }+ public ICommand CancelCommand { get; }++ public ToolsetItem(ToolsetModel model)+ {+ _model = model;+ _downloadSession = ToolsetDownloadService.GetOrCreateSession(model);++ DownloadCommand = new RelayCommand(async _ => await _downloadSession.Start(), _ => !IsDownloading);+ CancelCommand = new RelayCommand(_ => _downloadSession.Cancel(), _ => IsDownloading);++ PropertyChangedEventManager.AddHandler(_downloadSession, DownloadSession_PropertyChanged, string.Empty);++ _ = LoadIcons();+ }++ private void DownloadSession_PropertyChanged(object sender, PropertyChangedEventArgs e)+ {+ if (e.PropertyName == nameof(DownloadSession.IsDownloading))+ {+ OnPropertyChanged(nameof(IsDownloading));+ CommandManager.InvalidateRequerySuggested();+ }+ else if (e.PropertyName == nameof(DownloadSession.Progress))+ {+ OnPropertyChanged(nameof(Progress));+ }+ }++ private async Task LoadIcons()+ {+ try+ {+ IsSquareIcon = false;++ AppIconSource = Application.Current.TryFindResource(_model.IconResourceName) as ImageSource;+ AuthorIconSource = ToolsetIconService.GetPlaceholder(_model.Group);++ (ImageSource Image, bool IsFallback) = await ToolsetIconService.GetAuthorIcon(_model.Group, _model.AuthorIconUrl);++ AuthorIconSource = Image;+ IsSquareIcon = string.Equals(_model.Group, "web", StringComparison.OrdinalIgnoreCase) && !IsFallback;+ }+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }+ }+ }+}diff --git a/.Source/GTweak/Core/ViewModel/ToolsetViewModel.cs b/.Source/GTweak/Core/ViewModel/ToolsetViewModel.csindex 86ea8ee2..94e64e20 100644--- a/.Source/GTweak/Core/ViewModel/ToolsetViewModel.cs+++ b/.Source/GTweak/Core/ViewModel/ToolsetViewModel.cs@@ -2,16 +2,12 @@ using System;using System.Collections.ObjectModel;using System.Diagnostics;using System.IO;-using System.Threading;-using System.Threading.Tasks;using System.Windows.Input;-using System.Windows.Media;using System.Xml.Linq;using GTweak.Core.Base;+using GTweak.Core.Item;using GTweak.Core.Models;-using GTweak.Core.Service;using GTweak.Utilities.Controls;-using GTweak.Utilities.Managers;using Ookii.Dialogs.Wpf;namespace GTweak.Core.ViewModel@@ -111,122 +107,5 @@ namespace GTweak.Core.ViewModelErrorLogging.LogDebug(ex);}}-- internal class ToolsetItem : ViewModelBase- {- private readonly ToolsetModel _model;- private CancellationTokenSource _cts;-- private ImageSource _appIconSource;- private ImageSource _authorIconSource;- private bool _isDownloading;- private double _progress;- private bool _isSquareIcon;-- public ToolsetItem(ToolsetModel model)- {- _model = model;-- DownloadCommand = new RelayCommand(async _ => await DownloadAsync(), _ => !IsDownloading);- CancelCommand = new RelayCommand(_ => CancelDownload(), _ => IsDownloading);-- _ = LoadIconsAsync();- }-- public string AppName => _model.AppName;- public string AuthorName => _model.AuthorName;- public string SourceUrl => _model.SourceUrl;-- public ImageSource AppIconSource- {- get => _appIconSource;- set { _appIconSource = value; OnPropertyChanged(); }- }-- public ImageSource AuthorIconSource- {- get => _authorIconSource;- set { _authorIconSource = value; OnPropertyChanged(); }- }-- public bool IsDownloading- {- get => _isDownloading;- set { _isDownloading = value; OnPropertyChanged(); }- }-- public double Progress- {- get => _progress;- set { _progress = value; OnPropertyChanged(); }- }-- public bool IsSquareIcon- {- get => _isSquareIcon;- set { _isSquareIcon = value; OnPropertyChanged(); }- }-- public ICommand DownloadCommand { get; }- public ICommand CancelCommand { get; }-- private async Task LoadIconsAsync()- {- try- {- IsSquareIcon = false;-- AppIconSource = ToolsetIconManager.GetAppIconFromResource(_model.IconResourceName);- AuthorIconSource = ToolsetIconManager.GetPlaceholder(_model.Group);-- (ImageSource Image, bool IsFallback) = await ToolsetIconManager.GetAuthorIconAsync(_model.Group, _model.AuthorIconUrl);-- AuthorIconSource = Image;- IsSquareIcon = string.Equals(_model.Group, "web", StringComparison.OrdinalIgnoreCase) && !IsFallback;- }- catch (Exception ex)- {- ErrorLogging.LogDebug(ex);- }- }-- private async Task DownloadAsync()- {- IsDownloading = true;- Progress = 0;- _cts = new CancellationTokenSource();-- Progress<double> progressHandler = new Progress<double>(value => Progress = value);-- try- {- string finalUrl = await ToolsetDownloadService.ResolveDownloadUrlAsync(_model);-- if (!string.IsNullOrEmpty(finalUrl))- {- string destinationPath = Path.Combine(SettingsEngine.DownloadPath ?? Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Path.GetFileName(new Uri(finalUrl).LocalPath));- await ToolsetDownloadService.DownloadFileAsync(finalUrl, destinationPath, _model.SourceUrl, progressHandler, _cts.Token);- }- }- catch (Exception ex) { ErrorLogging.LogDebug(ex); }- finally- {- IsDownloading = false;-- if (Progress != 100)- {- Progress = 0;- }-- _cts?.Dispose();- _cts = null;- }- }-- private void CancelDownload()- {- _cts?.Cancel();- }- }}}\ No newline at end of filediff --git a/.Source/GTweak/GTweak.csproj b/.Source/GTweak/GTweak.csprojindex e294f3aa..59882004 100644--- a/.Source/GTweak/GTweak.csproj+++ b/.Source/GTweak/GTweak.csproj@@ -148,6 +148,8 @@<Compile Include="Core\Base\IViewPageBase.cs" /><Compile Include="Core\Base\ViewModelPageBase.cs" /><Compile Include="Core\Converters\AngleToPercentConverter.cs" />+ <Compile Include="Core\ViewModel\Components\DownloadSession.cs" />+ <Compile Include="Core\ViewModel\Components\ToolsetItem.cs" /><Compile Include="Core\Model\AddonsModel.cs" /><Compile Include="Core\Model\ConfidentialityModel.cs" /><Compile Include="Core\Model\DataSystemModel.cs" />@@ -156,7 +158,8 @@<Compile Include="Core\Model\ServicesModel.cs" /><Compile Include="Core\Model\SystemModel.cs" /><Compile Include="Core\Model\ToolsetModel.cs" />- <Compile Include="Core\Service\ToolsetDownloadService.cs" />+ <Compile Include="Core\Services\ToolsetDownloadService.cs" />+ <Compile Include="Core\Services\ToolsetIconService.cs" /><Compile Include="Core\ViewModel\AddonsViewModel.cs" /><Compile Include="Core\ViewModel\ConfidentialityViewModel.cs" /><Compile Include="Core\ViewModel\DataSystemViewModel.cs" />@@ -172,7 +175,6 @@<Compile Include="Utilities\Helpers\UnlockHandleHelper.cs" /><Compile Include="Utilities\Maintenance\ClearingMemory.cs" /><Compile Include="Utilities\Maintenance\RegistryExporter.cs" />- <Compile Include="Utilities\Managers\ToolsetIconManager.cs" /><Compile Include="Utilities\Tweaks\ConfidentialityTweaks.cs" /><Compile Include="Utilities\Tweaks\DefenderManager\AclPermissionsBackup.cs" /><Compile Include="Utilities\Tweaks\DefenderManager\WindowsDefender.cs" />