Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

fix: correct registry paths and improve feature toggle logic

fatDuck9b0ca23cb5d4
diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.cs
index 762b028..4332cdb 100644
--- a/optimizerDuck/App.xaml.cs
+++ b/optimizerDuck/App.xaml.cs
@@ -1,4 +1,5 @@
-using System.Globalization;
+using System.ComponentModel;
+using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Media;
@@ -10,6 +11,7 @@ using Microsoft.Extensions.Options;
using optimizerDuck.Common.Extensions;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Configuration;
+using optimizerDuck.Resources.Languages;
using optimizerDuck.Services;
using optimizerDuck.Services.Managers;
using optimizerDuck.Services.OptimizationServices;
@@ -23,7 +25,9 @@ using Serilog.Formatting;
using Serilog.Parsing;
using Wpf.Ui;
using Wpf.Ui.Appearance;
+using Wpf.Ui.Controls;
using Wpf.Ui.DependencyInjection;
+using Wpf.Ui.Extensions;
namespace optimizerDuck;
@@ -50,7 +54,7 @@ public class ScopeBlockTextFormatter : ITextFormatter
};
//var prefix = $"{timestamp} | {ctx,-67} | {levelText,-7} | "; // byebye 67 char SourceContext truncation, we have a new design now...
- var prefix = $"{timestamp} | {ctx, -35} | {levelText, -7} | ";
+ var prefix = $"{timestamp} | {ctx,-35} | {levelText,-7} | ";
// print message
output.WriteLine(prefix + RenderWithoutQuotes(logEvent));
@@ -110,6 +114,10 @@ public partial class App : Application
{
private IHost? _host;
private ILogger<App> _logger = null!;
+ private bool _allowClose;
+ private IContentDialogService? _contentDialogService = null;
+
+ public bool HasPendingChanges { get; set; }
protected override async void OnStartup(StartupEventArgs e)
{
@@ -131,10 +139,10 @@ public partial class App : Application
// ignore logging failures during fatal startup handling
}
- MessageBox.Show(
+ System.Windows.MessageBox.Show(
$"Failed to start optimizerDuck.{Environment.NewLine}{Environment.NewLine}{ex.Message}",
"optimizerDuck",
- MessageBoxButton.OK,
+ System.Windows.MessageBoxButton.OK,
MessageBoxImage.Error
);
Shutdown(-1);
@@ -282,6 +290,7 @@ public partial class App : Application
);
var mainWindow = _host.Services.GetRequiredService<MainWindow>();
+ mainWindow.Closing += MainWindow_Closing;
mainWindow.Show();
});
}
@@ -308,4 +317,83 @@ public partial class App : Application
base.OnExit(e);
}
+
+ protected async void MainWindow_Closing(object? sender,
+ CancelEventArgs e)
+ {
+ if (_allowClose)
+ {
+ return;
+ }
+
+ if (!HasPendingChanges)
+ {
+ return;
+ }
+
+ e.Cancel = true;
+
+ try
+ {
+ _contentDialogService ??=
+ _host!.Services.GetRequiredService<IContentDialogService>();
+
+ var result = await _contentDialogService.ShowSimpleDialogAsync(
+ new SimpleContentDialogCreateOptions
+ {
+ Title = Translations.Dialog_PendingChanges_Title,
+ Content = Translations.Dialog_PendingChanges_Content,
+ CloseButtonText =
+ Translations.Dialog_PendingChanges_CloseButton,
+ PrimaryButtonText =
+ Translations.Dialog_PendingChanges_PrimaryButton,
+ SecondaryButtonText =
+ Translations.Dialog_PendingChanges_SecondaryButton
+ }
+ );
+
+ switch (result)
+ {
+ case ContentDialogResult.Primary:
+ _logger.LogInformation(
+ "User chose to restart PC."
+ );
+
+ ShellService.CMD("shutdown /r /t 0");
+ break;
+
+ case ContentDialogResult.Secondary:
+ _logger.LogInformation(
+ "User chose to restart Explorer."
+ );
+
+ ShellService.CMD(
+ "taskkill /f /im explorer.exe && start explorer.exe"
+ );
+
+ _allowClose = true;
+ Current.Shutdown();
+ break;
+
+ case ContentDialogResult.None:
+ _logger.LogInformation(
+ "User chose to exit without applying changes."
+ );
+
+ _allowClose = true;
+ Current.Shutdown();
+ break;
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(
+ ex,
+ "Failed to show pending changes dialog."
+ );
+
+ _allowClose = true;
+ Current.Shutdown();
+ }
+ }
}
diff --git a/optimizerDuck/Domain/Features/Categories/Gaming.cs b/optimizerDuck/Domain/Features/Categories/Gaming.cs
index 60e36d7..113103a 100644
--- a/optimizerDuck/Domain/Features/Categories/Gaming.cs
+++ b/optimizerDuck/Domain/Features/Categories/Gaming.cs
@@ -148,24 +148,24 @@ public class Gaming : IFeatureCategory
{
Path = @"HKCU\Control Panel\Mouse",
Name = "MouseSpeed",
- OnValue = "1",
- OffValue = "0",
+ OnValue = "0",
+ OffValue = "1",
DefaultValue = "1",
},
new()
{
Path = @"HKCU\Control Panel\Mouse",
Name = "MouseThreshold1",
- OnValue = "6",
- OffValue = "0",
+ OnValue = "0",
+ OffValue = "6",
DefaultValue = "6",
},
new()
{
Path = @"HKCU\Control Panel\Mouse",
Name = "MouseThreshold2",
- OnValue = "10",
- OffValue = "0",
+ OnValue = "0",
+ OffValue = "10",
DefaultValue = "10",
},
];
diff --git a/optimizerDuck/Domain/Features/Categories/Preferences.cs b/optimizerDuck/Domain/Features/Categories/Preferences.cs
index 4ef4a3e..e0841fa 100644
--- a/optimizerDuck/Domain/Features/Categories/Preferences.cs
+++ b/optimizerDuck/Domain/Features/Categories/Preferences.cs
@@ -122,7 +122,7 @@ public class Preferences : IFeatureCategory
new()
{
Path =
- @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize",
+ @"HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize",
Name = "AppsUseLightTheme",
OnValue = 0,
OffValue = 1,
@@ -131,7 +131,7 @@ public class Preferences : IFeatureCategory
new()
{
Path =
- @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize",
+ @"HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize",
Name = "SystemUsesLightTheme",
OnValue = 0,
OffValue = 1,
diff --git a/optimizerDuck/Domain/Features/Categories/SystemFeatures.cs b/optimizerDuck/Domain/Features/Categories/SystemFeatures.cs
index 04f5b26..a30aa5c 100644
--- a/optimizerDuck/Domain/Features/Categories/SystemFeatures.cs
+++ b/optimizerDuck/Domain/Features/Categories/SystemFeatures.cs
@@ -33,17 +33,17 @@ public class SystemFeatures : IFeatureCategory
{
Path = @"HKU\.DEFAULT\Control Panel\Keyboard",
Name = "InitialKeyboardIndicators",
- OnValue = "2",
- OffValue = "0",
- DefaultValue = "0",
+ OnValue = 2,
+ OffValue = 0,
+ DefaultValue = 0,
},
new()
{
- Path = @"HKCU\\Control Panel\\Keyboard",
+ Path = @"HKCU\Control Panel\Keyboard",
Name = "InitialKeyboardIndicators",
- OnValue = "2",
- OffValue = "0",
- DefaultValue = "0",
+ OnValue = 2,
+ OffValue = 0,
+ DefaultValue = 0,
},
];
}
diff --git a/optimizerDuck/Domain/Features/Models/RegistryToggle.cs b/optimizerDuck/Domain/Features/Models/RegistryToggle.cs
index 8c1a787..5d4dc95 100644
--- a/optimizerDuck/Domain/Features/Models/RegistryToggle.cs
+++ b/optimizerDuck/Domain/Features/Models/RegistryToggle.cs
@@ -17,8 +17,13 @@ public class RegistryToggle
public bool GetState()
{
var value = GetRawValue();
+
if (value == null)
- return OnValue == null;
+ {
+ // If value is null and TreatMissingAsDefault is false,
+ // treat it as the default state (off)
+ return TreatMissingAsDefault ? AreEqual(DefaultValue, OnValue) : false;
+ }
return AreEqual(value, OnValue);
}
@@ -31,14 +36,50 @@ public class RegistryToggle
if (a == null || b == null)
return false;
+ // Handle numeric types with direct comparison to avoid precision loss
if (a is IConvertible && b is IConvertible)
{
- var da = Convert.ToDecimal(a);
- var db = Convert.ToDecimal(b);
- return da == db;
+ try
+ {
+ // Try direct type comparison first
+ if (a.GetType() == b.GetType())
+ {
+ return a.Equals(b);
+ }
+
+ // For numeric types, compare as the most precise type
+ var typeA = a.GetType();
+ var typeB = b.GetType();
+
+ // If both are integers, compare as long
+ if ((typeA == typeof(int) || typeA == typeof(long) || typeA == typeof(short) || typeA == typeof(byte)) &&
+ (typeB == typeof(int) || typeB == typeof(long) || typeB == typeof(short) || typeB == typeof(byte)))
+ {
+ return Convert.ToInt64(a) == Convert.ToInt64(b);
+ }
+
+ // For floating point, compare as double
+ if ((typeA == typeof(float) || typeA == typeof(double) || typeA == typeof(decimal)) &&
+ (typeB == typeof(float) || typeB == typeof(double) || typeB == typeof(decimal)))
+ {
+ return Convert.ToDouble(a) == Convert.ToDouble(b);
+ }
+
+ // Fallback to decimal comparison for other convertible types
+ var da = Convert.ToDecimal(a);
+ var db = Convert.ToDecimal(b);
+ return da == db;
+ }
+ catch
+ {
+ // If conversion fails, fall back to string comparison
+ }
}
- return a.ToString()?.Equals(b.ToString(), StringComparison.OrdinalIgnoreCase) == true;
+ // String comparison - use ordinal for case-sensitive, ordinal ignore case for case-insensitive
+ var strA = a.ToString();
+ var strB = b.ToString();
+ return strA != null && strB != null && strA.Equals(strB, StringComparison.Ordinal);
}
private object? GetRawValue()
@@ -48,7 +89,7 @@ public class RegistryToggle
if (value == null && TreatMissingAsDefault)
return DefaultValue;
- return value ?? DefaultValue;
+ return value;
}
public void SetState(bool isOn)
diff --git a/optimizerDuck/Resources/Languages/Translations.Designer.cs b/optimizerDuck/Resources/Languages/Translations.Designer.cs
index ab630f9..d71427d 100644
--- a/optimizerDuck/Resources/Languages/Translations.Designer.cs
+++ b/optimizerDuck/Resources/Languages/Translations.Designer.cs
@@ -799,6 +799,51 @@ namespace optimizerDuck.Resources.Languages {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Exit Anyway.
+ /// </summary>
+ internal static string Dialog_PendingChanges_CloseButton {
+ get {
+ return ResourceManager.GetString("Dialog.PendingChanges.CloseButton", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Some changes require a restart to take effect. What would you like to do before exiting?.
+ /// </summary>
+ internal static string Dialog_PendingChanges_Content {
+ get {
+ return ResourceManager.GetString("Dialog.PendingChanges.Content", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Restart PC.
+ /// </summary>
+ internal static string Dialog_PendingChanges_PrimaryButton {
+ get {
+ return ResourceManager.GetString("Dialog.PendingChanges.PrimaryButton", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Restart Explorer.
+ /// </summary>
+ internal static string Dialog_PendingChanges_SecondaryButton {
+ get {
+ return ResourceManager.GetString("Dialog.PendingChanges.SecondaryButton", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Apply Changes.
+ /// </summary>
+ internal static string Dialog_PendingChanges_Title {
+ get {
+ return ResourceManager.GetString("Dialog.PendingChanges.Title", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Clean Selected ({0}).
/// </summary>
diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resx
index ace3e10..6611b82 100644
--- a/optimizerDuck/Resources/Languages/Translations.resx
+++ b/optimizerDuck/Resources/Languages/Translations.resx
@@ -1714,4 +1714,19 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value>
<data name="LegalDialog.Warning.Message" xml:space="preserve">
<value>We recommend creating a backup before applying any changes.</value>
</data>
+ <data name="Dialog.PendingChanges.Title" xml:space="preserve">
+ <value>Apply Changes</value>
+ </data>
+ <data name="Dialog.PendingChanges.Content" xml:space="preserve">
+ <value>Some changes require a restart to take effect. What would you like to do before exiting?</value>
+ </data>
+ <data name="Dialog.PendingChanges.CloseButton" xml:space="preserve">
+ <value>Exit Anyway</value>
+ </data>
+ <data name="Dialog.PendingChanges.PrimaryButton" xml:space="preserve">
+ <value>Restart PC</value>
+ </data>
+ <data name="Dialog.PendingChanges.SecondaryButton" xml:space="preserve">
+ <value>Restart Explorer</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
index 9b2fc04..cfe7f48 100644
--- a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
@@ -1706,4 +1706,19 @@ Cập nhật ngay để trải nghiệm các tính năng mới, cải tiến và
<data name="LegalDialog.Warning.Message" xml:space="preserve">
<value>Khuyến nghị tạo bản sao lưu trước khi áp dụng bất kỳ thay đổi nào.</value>
</data>
+ <data name="Dialog.PendingChanges.Title" xml:space="preserve">
+ <value>Áp dụng thay đổi</value>
+ </data>
+ <data name="Dialog.PendingChanges.Content" xml:space="preserve">
+ <value>Một số thay đổi yêu cầu khởi động lại để có hiệu lực. Bạn muốn làm gì trước khi thoát?</value>
+ </data>
+ <data name="Dialog.PendingChanges.CloseButton" xml:space="preserve">
+ <value>Vẫn thoát</value>
+ </data>
+ <data name="Dialog.PendingChanges.PrimaryButton" xml:space="preserve">
+ <value>Khởi động lại máy tính</value>
+ </data>
+ <data name="Dialog.PendingChanges.SecondaryButton" xml:space="preserve">
+ <value>Khởi động lại Explorer</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.cs
index a191028..d78d27a 100644
--- a/optimizerDuck/Services/Revert/RevertManager.cs
+++ b/optimizerDuck/Services/Revert/RevertManager.cs
@@ -1,4 +1,4 @@
-using System.Collections.Concurrent;
+using System.Collections.Concurrent;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Logging;
diff --git a/optimizerDuck/UI/Pages/Features/Categories/FeatureCategoryPage.xaml b/optimizerDuck/UI/Pages/Features/Categories/FeatureCategoryPage.xaml
index 9ea972e..7208a1b 100644
--- a/optimizerDuck/UI/Pages/Features/Categories/FeatureCategoryPage.xaml
+++ b/optimizerDuck/UI/Pages/Features/Categories/FeatureCategoryPage.xaml
@@ -17,8 +17,7 @@
ui:Design.Foreground="White"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
ScrollViewer.CanContentScroll="False"
- mc:Ignorable="d"
->
+ mc:Ignorable="d">
<Page.Resources>
<converters:BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter" />
</Page.Resources>
@@ -36,22 +35,22 @@
Margin="0,0,12,0"
VerticalAlignment="Center"
FontSize="24"
- Symbol="{Binding ViewModel.CategoryIcon}"
- />
+ Symbol="{Binding ViewModel.CategoryIcon}" />
<ui:TextBlock
VerticalAlignment="Center"
FontTypography="Title"
- Text="{Binding ViewModel.CategoryName}"
- />
+ Text="{Binding ViewModel.CategoryName}" />
</StackPanel>
<ui:TextBlock
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="{Binding ViewModel.CategoryDescription}"
- TextWrapping="Wrap"
- />
+ TextWrapping="Wrap" />
</StackPanel>
- <WrapPanel Grid.Row="1" Margin="0,0,0,16" Orientation="Horizontal">
+ <WrapPanel
+ Grid.Row="1"
+ Margin="0,0,0,16"
+ Orientation="Horizontal">
<ui:TextBox
MinWidth="200"
Margin="0,0,8,0"
@@ -59,8 +58,7 @@
VerticalAlignment="Center"
Icon="{ui:SymbolIcon Search24}"
PlaceholderText="{ext:Loc Common.Search.Placeholder}"
- Text="{Binding ViewModel.SearchText, UpdateSourceTrigger=PropertyChanged}"
- />
+ Text="{Binding ViewModel.SearchText, UpdateSourceTrigger=PropertyChanged}" />
<ComboBox
Margin="0,0,8,0"
@@ -68,20 +66,17 @@
SelectedIndex="{Binding ViewModel.SelectedSortByIndex}"
ToolTip="{ext:Loc Common.SortBy}"
ToolTipService.BetweenShowDelay="160"
- ToolTipService.Placement="Top"
- >
+ ToolTipService.Placement="Top">
<ComboBoxItem HorizontalContentAlignment="Left">
<Grid HorizontalAlignment="Left" ColumnDefinitions="Auto Auto">
<ui:SymbolIcon
Margin="0,0,6,0"
HorizontalAlignment="Left"
- Symbol="TextSortAscending24"
- />
+ Symbol="TextSortAscending24" />
<TextBlock
Grid.Column="1"
HorizontalAlignment="Left"
- Text="{ext:Loc Common.SortBy.Name}"
- />
+ Text="{ext:Loc Common.SortBy.Name}" />
</Grid>
</ComboBoxItem>
<ComboBoxItem HorizontalContentAlignment="Left">
@@ -89,13 +84,11 @@
<ui:SymbolIcon
Margin="0,0,6,0"
HorizontalAlignment="Left"
- Symbol="ToggleRight24"
- />
+ Symbol="ToggleRight24" />
<TextBlock
Grid.Column="1"
HorizontalAlignment="Left"
- Text="{ext:Loc Common.SortBy.Status}"
- />
+ Text="{ext:Loc Common.SortBy.Status}" />
</Grid>
</ComboBoxItem>
</ComboBox>
@@ -104,8 +97,7 @@
<ScrollViewer
Grid.Row="2"
HorizontalScrollBarVisibility="Disabled"
- VerticalScrollBarVisibility="Auto"
- >
+ VerticalScrollBarVisibility="Auto">
<!-- Sections -->
<ItemsControl Margin="0,0,16,0" ItemsSource="{Binding ViewModel.Sections}">
<ItemsControl.ItemTemplate>
@@ -114,8 +106,7 @@
<ui:TextBlock
Margin="0,0,0,6"
FontTypography="BodyStrong"
- Text="{Binding Name}"
- />
+ Text="{Binding Name}" />
<ItemsControl ItemsSource="{Binding Features}">
<ItemsControl.ItemTemplate>
<DataTemplate>
@@ -128,27 +119,38 @@
<ui:TextBlock
FontTypography="Body"
Text="{Binding Name}"
- TextWrapping="Wrap"
- />
+ TextWrapping="Wrap" />
<ui:TextBlock
Margin="0,4,0,0"
- Foreground="{DynamicResource TextFillColorSecondaryBrush}"
FontTypography="Caption"
+ Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="{Binding Description}"
TextTrimming="WordEllipsis"
- TextWrapping="Wrap"
- />
+ TextWrapping="Wrap" />
</StackPanel>
</ui:CardControl.Header>
- <ui:ToggleSwitch
+ <StackPanel
+ Margin="0,0,0,0"
HorizontalAlignment="Right"
- VerticalAlignment="Center"
- Command="{Binding ToggleCommand}"
- Cursor="Hand"
- IsChecked="{Binding IsEnabled, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
- OffContent="{ext:Loc Common.Toggle.Off}"
- OnContent="{ext:Loc Common.Toggle.On}"
- />
+ Orientation="Horizontal">
+ <ui:ToggleSwitch
+ VerticalAlignment="Center"
+ Command="{Binding ToggleCommand}"
+ Cursor="Hand"
+ IsChecked="{Binding IsEnabled, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
+ OffContent="{ext:Loc Common.Toggle.Off}"
+ OnContent="{ext:Loc Common.Toggle.On}" />
+ <ui:Button
+ Margin="8,0,0,0"
+ VerticalAlignment="Center"
+ Background="Transparent"
+ BorderBrush="Transparent"
+ Command="{Binding DataContext.ViewModel.ViewSourceOnGitHubCommand, RelativeSource={RelativeSource AncestorType=Page}}"
+ CommandParameter="{Binding}"
+ Cursor="Hand"
+ Icon="{ui:SymbolIcon Code24}"
+ ToolTip="{ext:Loc Optimizer.Menu.ViewSource}" />
+ </StackPanel>
</ui:CardControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
@@ -159,10 +161,7 @@
</ItemsControl>
</ScrollViewer>
- <Border
- Grid.Row="2"
- Visibility="{Binding ViewModel.IsLoading, Converter={StaticResource BoolToVisibilityConverter}}"
- >
+ <Border Grid.Row="2" Visibility="{Binding ViewModel.IsLoading, Converter={StaticResource BoolToVisibilityConverter}}">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<ui:ProgressRing
Width="48"
@@ -170,13 +169,11 @@
Margin="0,0,0,16"
HorizontalAlignment="Center"
VerticalAlignment="Center"
- IsIndeterminate="True"
- />
+ IsIndeterminate="True" />
<ui:TextBlock
HorizontalAlignment="Center"
FontTypography="BodyStrong"
- Text="{ext:Loc Features.Loading}"
- />
+ Text="{ext:Loc Features.Loading}" />
</StackPanel>
</Border>
</Grid>
diff --git a/optimizerDuck/UI/ViewModels/Features/FeatureCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Features/FeatureCategoryViewModel.cs
index ecf6e90..7c25aa4 100644
--- a/optimizerDuck/UI/ViewModels/Features/FeatureCategoryViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Features/FeatureCategoryViewModel.cs
@@ -1,6 +1,11 @@
-using System.Collections.ObjectModel;
+using System.Collections.Concurrent;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Net.Http;
using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
+using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Features.Models;
using optimizerDuck.Resources.Languages;
@@ -11,6 +16,13 @@ namespace optimizerDuck.UI.ViewModels.Pages;
public partial class FeatureCategoryViewModel : ViewModel
{
+ private static readonly HttpClient httpClient = new() { Timeout = TimeSpan.FromSeconds(5) };
+ private static readonly ConcurrentDictionary<
+ string,
+ (string Content, DateTime FetchedAt)
+ > _sourceCache = new();
+ private static readonly TimeSpan SourceCacheTtl = TimeSpan.FromMinutes(5);
+
private readonly List<FeatureViewModel> _allFeatures = [];
private readonly IFeatureCategory? _currentCategory;
@@ -103,11 +115,72 @@ public partial class FeatureCategoryViewModel : ViewModel
var section = new FeatureSection
{
Name = group.Key,
- Features = new ObservableCollection<FeatureViewModel>(group.ToList()),
+ Features = new ObservableCollection<FeatureViewModel>([.. group]),
};
sections.Add(section);
}
Sections = sections;
}
+
+ [RelayCommand]
+ private async Task ViewSourceOnGitHubAsync(FeatureViewModel featureViewModel)
+ {
+ if (featureViewModel is null)
+ return;
+
+ if (featureViewModel.Feature is not BaseFeature baseFeature || baseFeature.OwnerType == null)
+ return;
+
+ var fileName = baseFeature.OwnerType.Name;
+ var className = baseFeature.FeatureKey;
+ var namespacePath = (baseFeature.OwnerType.Namespace ?? string.Empty).Replace('.', '/');
+ var relativePath = $"{namespacePath}/{fileName}.cs";
+ var url = $"{Shared.GitHubRepoURL}/blob/master/{relativePath}";
+
+ // Fetch source from GitHub raw content to find the class line number
+ try
+ {
+ var rawUrl =
+ $"https://raw.githubusercontent.com/itsfatduck/optimizerDuck/master/{relativePath}";
+
+ string source;
+ if (
+ _sourceCache.TryGetValue(rawUrl, out var cached)
+ && DateTime.UtcNow - cached.FetchedAt < SourceCacheTtl
+ )
+ {
+ source = cached.Content;
+ }
+ else
+ {
+ source = await httpClient.GetStringAsync(rawUrl);
+ _sourceCache[rawUrl] = (source, DateTime.UtcNow);
+ }
+
+ var lines = source.Split('\n');
+ for (var i = 0; i < lines.Length; i++)
+ if (lines[i].Contains($"class {className} : {nameof(BaseFeature)}", StringComparison.OrdinalIgnoreCase))
+ {
+ url += $"#L{i + 1}";
+ break;
+ }
+ }
+ catch (Exception ex)
+ {
+ // Log warning but still try to open the URL without line number
+ System.Diagnostics.Debug.WriteLine(
+ $"Could not fetch source to find line number for {className}: {ex.Message}"
+ );
+ }
+
+ try
+ {
+ Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"Failed to open GitHub URL: {url}. Error: {ex.Message}");
+ }
+ }
}
diff --git a/optimizerDuck/UI/ViewModels/Features/FeatureViewModel.cs b/optimizerDuck/UI/ViewModels/Features/FeatureViewModel.cs
index 0fd0634..95c56cd 100644
--- a/optimizerDuck/UI/ViewModels/Features/FeatureViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Features/FeatureViewModel.cs
@@ -1,4 +1,5 @@
-using CommunityToolkit.Mvvm.ComponentModel;
+using System.Windows;
+using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using optimizerDuck.Domain.Abstractions;
@@ -13,6 +14,9 @@ public partial class FeatureViewModel(IFeature feature, ILoggerFactory loggerFac
private readonly ILogger<FeatureViewModel> _logger =
loggerFactory.CreateLogger<FeatureViewModel>();
+ public IFeature Feature => feature;
+
+
[ObservableProperty]
private string _description = feature.Description;
@@ -73,6 +77,8 @@ public partial class FeatureViewModel(IFeature feature, ILoggerFactory loggerFac
IsEnabled = false;
}
+ ((App)Application.Current).HasPendingChanges = true;
+
scope.Dispose();
_logger.LogInformation(
diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
index 1791724..758255f 100644
--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
@@ -2,6 +2,7 @@ using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Net.Http;
+using System.Windows;
using System.Windows.Controls;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
@@ -190,6 +191,8 @@ public partial class OptimizationCategoryViewModel : ViewModel
return;
}
+ ((App)Application.Current).HasPendingChanges = true;
+
// Retry only if there are some successful steps and some failed steps
var retryOutcome = await HandleRetryableFailuresAsync(
optimization,