{"repo_name": "Winhance", "file_name": "/Winhance/src/Winhance.WPF/Features/Common/Views/MainWindow.xaml.cs", "inference_info": {"prefix_code": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Interop;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Utilities;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n public partial class MainWindow : Window\n {\n private readonly Winhance.Core.Features.Common.Interfaces.INavigationService _navigationService =\n null!;\n private WindowSizeManager _windowSizeManager;\n private readonly UserPreferencesService _userPreferencesService;\n private readonly IApplicationCloseService _applicationCloseService;\n\n private void LogDebug(string message, Exception? ex = null)\n {\n string fullMessage = message + (ex != null ? $\" - Exception: {ex.Message}\" : \"\");\n\n // Use proper logging service for application logging\n _messengerService?.Send(\n new LogMessage\n {\n Message = fullMessage,\n Level = ex != null ? LogLevel.Error : LogLevel.Debug,\n Exception = ex,\n }\n );\n\n // Also log to diagnostic file for troubleshooting\n FileLogger.Log(\"MainWindow\", fullMessage);\n\n // If there's an exception, log the stack trace as well\n if (ex != null)\n {\n FileLogger.Log(\"MainWindow\", $\"Stack trace: {ex.StackTrace}\");\n }\n\n // Also log to WinhanceStartupLog.txt for debugging the white screen issue\n LogToStartupLog(fullMessage);\n if (ex != null)\n {\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n\n /// \n /// Logs a message directly to the WinhanceStartupLog.txt file\n /// \n private void LogToStartupLog(string message)\n {\n#if DEBUG\n try\n {\n string logsDir = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\"\n );\n string logFile = Path.Combine(logsDir, \"WinhanceStartupLog.txt\");\n\n // Ensure the logs directory exists\n if (!Directory.Exists(logsDir))\n {\n Directory.CreateDirectory(logsDir);\n }\n\n // Format the log message with timestamp\n string formattedMessage =\n $\"[{DateTime.Now:yyyy/MM/dd HH:mm:ss}] [MainWindow] {message}\";\n\n // Append to the log file\n using (StreamWriter writer = File.AppendText(logFile))\n {\n writer.WriteLine(formattedMessage);\n }\n }\n catch\n {\n // Ignore errors in logging to avoid cascading issues\n }\n#endif\n }\n\n public MainWindow()\n {\n LogDebug(\"Default constructor called - THIS SHOULD NOT HAPPEN\");\n try\n {\n // Don't worry about this error, it is initialized at runtime.\n InitializeComponent();\n LogDebug(\"Default constructor completed initialization\");\n\n // Direct event handlers for window control buttons\n this.MinimizeButton.Click += (s, e) => this.WindowState = WindowState.Minimized;\n this.MaximizeRestoreButton.Click += (s, e) =>\n {\n this.WindowState =\n (this.WindowState == WindowState.Maximized)\n ? WindowState.Normal\n : WindowState.Maximized;\n };\n this.CloseButton.Click += CloseButton_Click;\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in default constructor\", ex);\n throw;\n }\n }\n\n // No need to define InitializeComponent here, it's generated by the WPF build system\n\n public MainWindow(\n IThemeManager themeManager,\n IServiceProvider serviceProvider,\n IMessengerService messengerService,\n Winhance.Core.Features.Common.Interfaces.INavigationService navigationService,\n IVersionService versionService,\n UserPreferencesService userPreferencesService,\n IApplicationCloseService applicationCloseService\n )\n {\n try\n {\n // Use FileLogger directly to ensure we capture everything\n FileLogger.Log(\"MainWindow\", \"MainWindow constructor starting\");\n FileLogger.Log(\n \"MainWindow\",\n $\"Parameters: themeManager={themeManager != null}, serviceProvider={serviceProvider != null}, messengerService={messengerService != null}, navigationService={navigationService != null}, versionService={versionService != null}, userPreferencesService={userPreferencesService != null}\"\n );\n\n // Verify dependencies\n if (themeManager == null)\n throw new ArgumentNullException(nameof(themeManager));\n if (serviceProvider == null)\n throw new ArgumentNullException(nameof(serviceProvider));\n if (messengerService == null)\n throw new ArgumentNullException(nameof(messengerService));\n if (navigationService == null)\n throw new ArgumentNullException(nameof(navigationService));\n if (versionService == null)\n throw new ArgumentNullException(nameof(versionService));\n if (userPreferencesService == null)\n throw new ArgumentNullException(nameof(userPreferencesService));\n FileLogger.Log(\"MainWindow\", \"Dependencies verified\");\n\n // Let the build system initialize the component\n try\n {\n LogToStartupLog(\"Starting InitializeComponent\");\n\n // We'll use a try-catch block around each part of the InitializeComponent process\n try\n {\n LogToStartupLog(\"Calling InitializeComponent()\");\n InitializeComponent();\n LogToStartupLog(\"InitializeComponent() completed successfully\");\n }\n catch (Exception initEx)\n {\n LogToStartupLog($\"ERROR in InitializeComponent(): {initEx.Message}\");\n LogToStartupLog($\"Stack trace: {initEx.StackTrace}\");\n throw; // Re-throw to be caught by the outer try-catch\n }\n\n LogToStartupLog(\"InitializeComponent completed\");\n\n // Direct event handlers for window control buttons\n try\n {\n LogToStartupLog(\"Setting up window control button event handlers\");\n\n LogToStartupLog($\"MinimizeButton exists: {this.MinimizeButton != null}\");\n this.MinimizeButton.Click += (s, e) =>\n this.WindowState = WindowState.Minimized;\n\n LogToStartupLog(\n $\"MaximizeRestoreButton exists: {this.MaximizeRestoreButton != null}\"\n );\n this.MaximizeRestoreButton.Click += (s, e) =>\n {\n this.WindowState =\n (this.WindowState == WindowState.Maximized)\n ? WindowState.Normal\n : WindowState.Maximized;\n\n // Update button content when window state changes\n if (DataContext is MainViewModel viewModel)\n {\n viewModel.MaximizeButtonContent =\n (this.WindowState == WindowState.Maximized)\n ? \"WindowRestore\"\n : \"WindowMaximize\";\n }\n };\n\n LogToStartupLog($\"CloseButton exists: {this.CloseButton != null}\");\n this.CloseButton.Click += CloseButton_Click;\n\n LogToStartupLog($\"MoreButton exists: {this.MoreButton != null}\");\n LogToStartupLog($\"MoreMenuControl exists: {this.MoreMenuControl != null}\");\n this.MoreButton.Click += MoreButton_Click;\n\n LogToStartupLog(\n \"Successfully set up all window control button event handlers\"\n );\n }\n catch (Exception buttonEx)\n {\n LogToStartupLog(\n $\"ERROR setting up button event handlers: {buttonEx.Message}\"\n );\n LogToStartupLog($\"Stack trace: {buttonEx.StackTrace}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in InitializeComponent\", ex);\n // This is not ideal, but we'll continue since the constructor errors will be handled\n }\n\n LogDebug(\"Setting fields\");\n _themeManager = themeManager;\n _serviceProvider = serviceProvider;\n _messengerService = messengerService;\n _navigationService = navigationService;\n _versionService =\n versionService ?? throw new ArgumentNullException(nameof(versionService));\n\n // Create the window size manager\n try\n {\n var logService =\n _serviceProvider.GetService(typeof(ILogService)) as ILogService;\n\n if (userPreferencesService != null && logService != null)\n {\n _windowSizeManager = new WindowSizeManager(\n this,\n userPreferencesService,\n logService\n );\n LogDebug(\"WindowSizeManager created successfully\");\n }\n else\n {\n LogDebug(\"Could not create WindowSizeManager: services not available\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error creating WindowSizeManager: {ex.Message}\", ex);\n }\n _userPreferencesService =\n userPreferencesService\n ?? throw new ArgumentNullException(nameof(userPreferencesService));\n _applicationCloseService =\n applicationCloseService\n ?? throw new ArgumentNullException(nameof(applicationCloseService));\n LogDebug(\"Fields set\");\n\n // Hook up events for ContentPresenter-based navigation\n if (\n _navigationService\n is Winhance.Core.Features.Common.Interfaces.INavigationService navService\n )\n {\n LogDebug(\"Setting up navigation service for ContentPresenter-based navigation\");\n\n // Add PreviewMouseWheel event handler for better scrolling\n this.PreviewMouseWheel += MainWindow_PreviewMouseWheel;\n\n // We'll navigate once the window is fully loaded\n this.Loaded += (sender, e) =>\n {\n LogDebug(\"Window loaded, navigating to default view\");\n\n // Apply the theme to ensure all toggle switches are properly initialized\n try\n {\n LogDebug(\"Applying theme to initialize toggle switches\");\n if (_themeManager != null)\n {\n // Apply the theme which will update all toggle switches\n _themeManager.ApplyTheme();\n LogDebug(\"Successfully initialized toggle switches\");\n\n // Update the app icon based on the theme\n UpdateThemeIcon();\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error initializing toggle switches: {ex.Message}\", ex);\n }\n\n if (DataContext is MainViewModel mainViewModel)\n {\n try\n {\n // Navigate to SoftwareApps view by default\n LogDebug(\"Navigating to SoftwareApps view\");\n _navigationService.NavigateTo(\"SoftwareApps\");\n\n // Verify that navigation succeeded\n if (mainViewModel.CurrentViewModel == null)\n {\n LogDebug(\n \"WARNING: Navigation succeeded but CurrentViewModel is null\"\n );\n }\n else\n {\n LogDebug(\n $\"Navigation succeeded, CurrentViewModel is {mainViewModel.CurrentViewModel.GetType().Name}\"\n );\n }\n }\n catch (Exception ex)\n {\n LogDebug(\n $\"Error navigating to SoftwareApps view: {ex.Message}\",\n ex\n );\n\n // Try to recover by navigating to another view\n try\n {\n LogDebug(\"Attempting to navigate to About view as fallback\");\n _navigationService.NavigateTo(\"About\");\n }\n catch (Exception fallbackEx)\n {\n LogDebug(\n $\"Error navigating to fallback view: {fallbackEx.Message}\",\n fallbackEx\n );\n }\n }\n }\n else\n {\n LogDebug(\n $\"DataContext is not MainViewModel, it is {DataContext?.GetType().Name ?? \"null\"}\"\n );\n }\n };\n\n // Add StateChanged event to update Maximize/Restore button content only\n this.StateChanged += (sender, e) =>\n {\n if (DataContext is MainViewModel viewModel)\n {\n viewModel.MaximizeButtonContent =\n (this.WindowState == WindowState.Maximized)\n ? \"WindowRestore\"\n : \"WindowMaximize\";\n }\n };\n\n // We no longer save window position/size to preferences\n }\n else\n {\n LogDebug(\n $\"_navigationService is not INavigationService, it is {_navigationService?.GetType().Name ?? \"null\"}\"\n );\n }\n\n // Register for window state messages\n LogDebug(\"Registering for window state messages\");\n _messengerService.Register(this, HandleWindowStateMessage);\n LogDebug(\"Registered for window state messages\");\n\n // Add Closing event handler to log the closing process\n this.Closing += MainWindow_Closing;\n\n // Clean up when window is closed\n this.Closed += (sender, e) =>\n {\n LogDebug(\"Window closed, unregistering from messenger service\");\n _messengerService.Unregister(this);\n };\n\n LogDebug($\"DataContext is {(DataContext == null ? \"null\" : \"not null\")}\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in parameterized constructor\", ex);\n throw;\n }\n }\n\n private async void CloseButton_Click(object sender, RoutedEventArgs e)\n {\n try\n {\n LogDebug(\"CloseButton_Click called, delegating to ApplicationCloseService\");\n await _applicationCloseService.CloseApplicationWithSupportDialogAsync();\n }\n catch (Exception ex)\n {\n LogDebug($\"Error in CloseButton_Click: {ex.Message}\", ex);\n\n // Fallback to direct close if there's an error\n try\n {\n this.Close();\n }\n catch\n {\n // Last resort\n Application.Current.Shutdown();\n }\n }\n }\n\n private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n {\n try\n {\n // Check if the DataContext is MainViewModel\n if (DataContext is MainViewModel viewModel)\n {\n LogDebug(\"DataContext is MainViewModel\");\n\n // Log any relevant properties or state from the ViewModel\n LogDebug($\"CurrentViewName: {viewModel.CurrentViewName}\");\n LogDebug(\n $\"CurrentViewModel type: {viewModel.CurrentViewModel?.GetType().FullName ?? \"null\"}\"\n );\n }\n else\n {\n LogDebug(\n $\"DataContext is not MainViewModel, it is {DataContext?.GetType().Name ?? \"null\"}\"\n );\n }\n\n // Log active windows\n LogDebug(\"Active windows:\");\n foreach (Window window in Application.Current.Windows)\n {\n LogDebug(\n $\"Window: {window.GetType().FullName}, IsVisible: {window.IsVisible}, WindowState: {window.WindowState}\"\n );\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error in MainWindow_Closing: {ex.Message}\", ex);\n }\n }\n\n private readonly IMessengerService _messengerService = null!;\n private readonly IVersionService _versionService = null!;\n\n #region More Button Event Handlers\n\n /// \n /// Event handler for the More button click\n /// Shows the context menu when the More button is clicked\n /// \n private void MoreButton_Click(object sender, RoutedEventArgs e)\n {\n // Log to the startup log file\n LogToStartupLog(\"More button clicked\");\n\n try\n {\n // Show the context menu using the MoreMenu control\n LogToStartupLog($\"MoreMenuControl exists: {MoreMenuControl != null}\");\n LogToStartupLog($\"MoreButton exists: {MoreButton != null}\");\n\n if (MoreMenuControl != null)\n {\n LogToStartupLog(\"About to call MoreMenuControl.ShowMenu()\");\n\n try\n {\n // Show the menu with the More button as the placement target\n MoreMenuControl.ShowMenu(MoreButton);\n LogToStartupLog(\"MoreMenuControl.ShowMenu() called successfully\");\n }\n catch (Exception menuEx)\n {\n LogToStartupLog($\"ERROR in MoreMenuControl.ShowMenu(): {menuEx.Message}\");\n LogToStartupLog($\"Stack trace: {menuEx.StackTrace}\");\n }\n }\n else\n {\n LogToStartupLog(\"MoreMenuControl is null, cannot show menu\");\n }\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"Error in MoreButton_Click: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n\n // Context menu event handlers have been moved to MoreMenuViewModel\n\n #endregion\n\n private void HandleWindowStateMessage(WindowStateMessage message)\n {\n LogDebug($\"Received window state message: {message.Action}\");\n\n try\n {\n switch (message.Action)\n {\n case WindowStateMessage.WindowStateAction.Minimize:\n LogDebug(\"Processing minimize action\");\n WindowState = WindowState.Minimized;\n break;\n\n case WindowStateMessage.WindowStateAction.Maximize:\n LogDebug(\"Processing maximize action\");\n WindowState = WindowState.Maximized;\n break;\n\n case WindowStateMessage.WindowStateAction.Restore:\n LogDebug(\"Processing restore action\");\n WindowState = WindowState.Normal;\n break;\n\n case WindowStateMessage.WindowStateAction.Close:\n LogDebug(\"Processing close action\");\n Close();\n break;\n\n default:\n LogDebug($\"Unknown window state action: {message.Action}\");\n break;\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error handling window state message: {ex.Message}\", ex);\n }\n }\n\n private readonly IServiceProvider _serviceProvider = null!;\n private readonly IThemeManager _themeManager = null!;\n\n protected override void OnSourceInitialized(EventArgs e)\n {\n LogDebug(\"OnSourceInitialized starting\");\n try\n {\n base.OnSourceInitialized(e);\n LogDebug(\"Base OnSourceInitialized called\");\n\n var helper = new WindowInteropHelper(this);\n if (helper.Handle == IntPtr.Zero)\n {\n throw new InvalidOperationException(\"Window handle not available\");\n }\n LogDebug(\"Window handle verified\");\n\n // Initialize the window size manager to set size and center the window\n if (_windowSizeManager != null)\n {\n _windowSizeManager.Initialize();\n LogDebug(\"WindowSizeManager initialized\");\n }\n else\n {\n // Fallback if window size manager is not available\n SetDynamicWindowSize();\n LogDebug(\"Used fallback dynamic window sizing\");\n }\n\n EnableBlur();\n LogDebug(\"Blur enabled successfully\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in OnSourceInitialized\", ex);\n // Don't throw - blur is not critical\n }\n }\n\n /// \n /// Sets the window size dynamically based on the screen resolution\n /// \n private void SetDynamicWindowSize()\n {\n try\n {\n LogDebug(\"Setting dynamic window size\");\n\n // Get the current screen's working area (excludes taskbar)\n var workArea = GetCurrentScreenWorkArea();\n\n // Get DPI scaling factor for the current screen\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n\n try\n {\n var presentationSource = PresentationSource.FromVisual(this);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n LogDebug($\"DPI scale factors: X={dpiScaleX}, Y={dpiScaleY}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n\n // Calculate available screen space\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n double screenLeft = workArea.X / dpiScaleX;\n double screenTop = workArea.Y / dpiScaleY;\n\n // Calculate window size (75% of screen size with minimum/maximum constraints)\n double windowWidth = Math.Min(1600, screenWidth * 0.75);\n double windowHeight = Math.Min(900, screenHeight * 0.75);\n\n // Ensure minimum size for usability\n windowWidth = Math.Max(windowWidth, 1024);\n windowHeight = Math.Max(windowHeight, 700);\n\n // Set the window size\n this.Width = windowWidth;\n this.Height = windowHeight;\n\n // Center the window on screen\n this.Left = screenLeft + (screenWidth - windowWidth) / 2;\n this.Top = screenTop + (screenHeight - windowHeight) / 2;\n\n LogDebug(\n $\"Screen resolution: {screenWidth}x{screenHeight}, Window size set to: {windowWidth}x{windowHeight}\"\n );\n LogDebug($\"Window centered at: Left={this.Left}, Top={this.Top}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error setting dynamic window size: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Gets the working area of the screen that contains the window\n /// \n private Rect GetCurrentScreenWorkArea()\n {\n try\n {\n // Get the window handle\n var windowHandle = new WindowInteropHelper(this).Handle;\n if (windowHandle != IntPtr.Zero)\n {\n // Get the monitor info for the monitor containing the window\n var monitorInfo = new MONITORINFO();\n monitorInfo.cbSize = Marshal.SizeOf(typeof(MONITORINFO));\n\n if (\n GetMonitorInfo(\n MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST),\n ref monitorInfo\n )\n )\n {\n // Convert the working area to a WPF Rect\n return new Rect(\n monitorInfo.rcWork.left,\n monitorInfo.rcWork.top,\n monitorInfo.rcWork.right - monitorInfo.rcWork.left,\n monitorInfo.rcWork.bottom - monitorInfo.rcWork.top\n );\n }\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting current screen: {ex.Message}\", ex);\n }\n\n // Fallback to primary screen working area\n return SystemParameters.WorkArea;\n }\n\n [DllImport(\"user32.dll\")]\n private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);\n\n [DllImport(\"user32.dll\")]\n private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);\n\n private const uint MONITOR_DEFAULTTONEAREST = 2;\n\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct MONITORINFO\n {\n public int cbSize;\n public RECT rcMonitor;\n public RECT rcWork;\n public uint dwFlags;\n }\n\n private void EnableBlur()\n {\n LogDebug(\"EnableBlur starting\");\n var windowHelper = new WindowInteropHelper(this);\n var accent = new AccentPolicy { AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND };\n var accentStructSize = Marshal.SizeOf(accent);\n\n var accentPtr = IntPtr.Zero;\n try\n {\n accentPtr = Marshal.AllocHGlobal(accentStructSize);\n Marshal.StructureToPtr(accent, accentPtr, false);\n\n var data = new WindowCompositionAttributeData\n {\n Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,\n SizeOfData = accentStructSize,\n Data = accentPtr,\n };\n\n int result = SetWindowCompositionAttribute(windowHelper.Handle, ref data);\n if (result == 0)\n {\n throw new InvalidOperationException(\"SetWindowCompositionAttribute failed\");\n }\n LogDebug(\"Blur effect applied successfully\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error enabling blur\", ex);\n throw;\n }\n finally\n {\n if (accentPtr != IntPtr.Zero)\n {\n Marshal.FreeHGlobal(accentPtr);\n }\n }\n }\n\n [DllImport(\"user32.dll\")]\n internal static extern int SetWindowCompositionAttribute(\n IntPtr hwnd,\n ref WindowCompositionAttributeData data\n );\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct AccentPolicy\n {\n public AccentState AccentState;\n public int AccentFlags;\n public int GradientColor;\n public int AnimationId;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct WindowCompositionAttributeData\n {\n public WindowCompositionAttribute Attribute;\n public IntPtr Data;\n public int SizeOfData;\n }\n\n internal enum AccentState\n {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5,\n }\n\n internal enum WindowCompositionAttribute\n {\n WCA_ACCENT_POLICY = 19,\n }\n\n // Window control is now handled through ViewModel commands and messaging\n\n /// \n /// Updates the window and image icons based on the current theme\n /// \n private void UpdateThemeIcon()\n {\n if (_themeManager == null)\n {\n LogDebug(\"Cannot update theme icon: ThemeManager is null\");\n return;\n }\n\n try\n {\n LogDebug(\n $\"Updating theme icon. Current theme: {(_themeManager.IsDarkTheme ? \"Dark\" : \"Light\")}\"\n );\n\n // Get the appropriate icon based on the theme\n string iconPath = _themeManager.IsDarkTheme\n ? \"pack://application:,,,/Resources/AppIcons/winhance-rocket-white-transparent-bg.ico\"\n : \"pack://application:,,,/Resources/AppIcons/winhance-rocket-black-transparent-bg.ico\";\n\n LogDebug($\"Selected icon path: {iconPath}\");\n\n // Create a BitmapImage from the icon path\n var iconImage = new BitmapImage(new Uri(iconPath, UriKind.Absolute));\n iconImage.Freeze(); // Freeze for better performance and thread safety\n\n // Set the window icon\n this.Icon = iconImage;\n LogDebug(\"Window icon updated\");\n\n // Set the image control source\n if (AppIconImage != null)\n {\n AppIconImage.Source = iconImage;\n LogDebug(\"AppIconImage source updated\");\n }\n else\n {\n LogDebug(\"AppIconImage is null, cannot update source\");\n }\n }\n catch (Exception ex)\n {\n LogDebug(\"Error updating theme icon\", ex);\n\n // If there's an error, fall back to the default icon\n try\n {\n var defaultIcon = new BitmapImage(\n new Uri(\n \"pack://application:,,,/Resources/AppIcons/winhance-rocket.ico\",\n UriKind.Absolute\n )\n );\n this.Icon = defaultIcon;\n if (AppIconImage != null)\n {\n AppIconImage.Source = defaultIcon;\n }\n }\n catch (Exception fallbackEx)\n {\n LogDebug(\"Error setting fallback icon\", fallbackEx);\n }\n }\n }\n\n /// \n /// Handles mouse wheel events at the window level and redirects them to the ScrollViewer\n /// \n ", "suffix_code": "\n\n /// \n /// Finds a visual child of the specified type in the visual tree\n /// \n private static T FindVisualChild(DependencyObject obj)\n where T : DependencyObject\n {\n for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(obj, i);\n\n if (child != null && child is T)\n {\n return (T)child;\n }\n\n T childOfChild = FindVisualChild(child);\n if (childOfChild != null)\n {\n return childOfChild;\n }\n }\n\n return null;\n }\n }\n}\n", "middle_code": "private void MainWindow_PreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n var scrollViewer = FindVisualChild(this);\n if (scrollViewer != null)\n {\n if (e.Delta < 0)\n {\n scrollViewer.LineDown();\n }\n else\n {\n scrollViewer.LineUp();\n }\n e.Handled = true;\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/Winhance/src/Winhance.WPF/Features/Common/Utilities/WindowSizeManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Interop;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Utilities;\n\nnamespace Winhance.WPF.Features.Common.Utilities\n{\n /// \n /// Manages window size and position, including dynamic sizing based on screen resolution\n /// and handling multiple monitors and DPI scaling.\n /// \n public class WindowSizeManager\n {\n private readonly Window _window;\n private readonly ILogService _logService;\n\n // Default window dimensions\n private const double DEFAULT_WIDTH = 1600;\n private const double DEFAULT_HEIGHT = 900;\n private const double MIN_WIDTH = 1024;\n private const double MIN_HEIGHT = 700; // Reduced minimum height to fit better on smaller screens\n private const double SCREEN_PERCENTAGE = 0.9; // Use 90% of screen size for better fit\n\n public WindowSizeManager(Window window, UserPreferencesService userPreferencesService, ILogService logService)\n {\n _window = window ?? throw new ArgumentNullException(nameof(window));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n \n // No events registered - we don't save window position anymore\n }\n\n /// \n /// Initializes the window size and position\n /// \n public void Initialize()\n {\n try\n {\n // Set dynamic window size based on screen resolution (75% of screen)\n SetDynamicWindowSize();\n \n // Always center the window on screen\n // This ensures consistent behavior regardless of WindowStartupLocation\n CenterWindowOnScreen();\n \n LogDebug($\"Window initialized with size: {_window.Width}x{_window.Height}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error initializing window size manager: {ex.Message}\", ex);\n }\n }\n \n /// \n /// Centers the window on the current screen\n /// \n private void CenterWindowOnScreen()\n {\n try\n {\n // Get the current screen's working area\n var workArea = GetCurrentScreenWorkArea();\n \n // Get DPI scaling factor\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n \n try\n {\n var presentationSource = PresentationSource.FromVisual(_window);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n \n // Convert screen coordinates to account for DPI\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n double screenLeft = workArea.X / dpiScaleX;\n double screenTop = workArea.Y / dpiScaleY;\n \n // Calculate center position\n double left = screenLeft + (screenWidth - _window.Width) / 2;\n double top = screenTop + (screenHeight - _window.Height) / 2;\n \n // Set window position\n _window.Left = left;\n _window.Top = top;\n \n LogDebug($\"Window explicitly centered at: Left={left}, Top={top}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error centering window: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Sets the window size dynamically based on the screen resolution\n /// \n private void SetDynamicWindowSize()\n {\n try\n {\n LogDebug(\"Setting dynamic window size\");\n \n // Get the current screen's working area (excludes taskbar)\n var workArea = GetCurrentScreenWorkArea();\n \n // Get DPI scaling factor for the current screen\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n \n try\n {\n var presentationSource = PresentationSource.FromVisual(_window);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n LogDebug($\"DPI scale factors: X={dpiScaleX}, Y={dpiScaleY}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n \n // Calculate available screen space\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n \n // Calculate window size (75% of screen size with minimum/maximum constraints)\n double windowWidth = Math.Min(DEFAULT_WIDTH, screenWidth * SCREEN_PERCENTAGE);\n double windowHeight = Math.Min(DEFAULT_HEIGHT, screenHeight * SCREEN_PERCENTAGE);\n \n // Ensure minimum size for usability\n windowWidth = Math.Max(windowWidth, MIN_WIDTH);\n windowHeight = Math.Max(windowHeight, MIN_HEIGHT);\n \n // Only set the window size, let WPF handle the centering via WindowStartupLocation=\"CenterScreen\"\n _window.Width = windowWidth;\n _window.Height = windowHeight;\n \n LogDebug($\"Dynamic window size set to: Width={windowWidth}, Height={windowHeight}\");\n LogDebug($\"Screen dimensions: Width={screenWidth}, Height={screenHeight}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error setting dynamic window size: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Gets the working area of the screen that contains the window\n /// \n private Rect GetCurrentScreenWorkArea()\n {\n try\n {\n // Get the window handle\n var windowHandle = new WindowInteropHelper(_window).Handle;\n if (windowHandle != IntPtr.Zero)\n {\n // Get the monitor info for the monitor containing the window\n var monitorInfo = new MONITORINFO();\n monitorInfo.cbSize = Marshal.SizeOf(typeof(MONITORINFO));\n \n if (GetMonitorInfo(MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST), ref monitorInfo))\n {\n // Convert the working area to a WPF Rect\n return new Rect(\n monitorInfo.rcWork.left,\n monitorInfo.rcWork.top,\n monitorInfo.rcWork.right - monitorInfo.rcWork.left,\n monitorInfo.rcWork.bottom - monitorInfo.rcWork.top);\n }\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting current screen: {ex.Message}\", ex);\n }\n \n // Fallback to primary screen working area\n return SystemParameters.WorkArea;\n }\n\n // Event handlers for window state, location, and size changes have been removed\n // as we no longer save window position/size to preferences\n\n /// \n /// Logs a debug message\n /// \n private void LogDebug(string message, Exception ex = null)\n {\n try\n {\n _logService?.Log(LogLevel.Debug, message, ex);\n \n // Also log to file logger for troubleshooting\n FileLogger.Log(\"WindowSizeManager\", message + (ex != null ? $\" - Exception: {ex.Message}\" : \"\"));\n }\n catch\n {\n // Ignore logging errors\n }\n }\n\n #region Win32 API\n\n [DllImport(\"user32.dll\")]\n private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);\n \n [DllImport(\"user32.dll\")]\n private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);\n \n private const uint MONITOR_DEFAULTTONEAREST = 2;\n \n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n \n [StructLayout(LayoutKind.Sequential)]\n private struct MONITORINFO\n {\n public int cbSize;\n public RECT rcMonitor;\n public RECT rcWork;\n public uint dwFlags;\n }\n\n #endregion\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/MainViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Input;\nusing System.Windows.Interop;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Utilities;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n public partial class MainViewModel : BaseViewModel\n {\n // Window control is now handled through messaging\n\n private readonly IThemeManager _themeManager;\n private readonly INavigationService _navigationService;\n private readonly IMessengerService _messengerService;\n private readonly IUnifiedConfigurationService _unifiedConfigService;\n private readonly IDialogService _dialogService;\n private readonly Features.Common.Services.UserPreferencesService _userPreferencesService;\n\n public INavigationService NavigationService => _navigationService;\n\n [ObservableProperty]\n private object _currentViewModel;\n\n // Helper method to log window actions for debugging\n private void LogWindowAction(string message)\n {\n string formattedMessage = $\"Window Action: {message}\";\n\n // Send to application logging system\n _messengerService.Send(\n new LogMessage { Message = formattedMessage, Level = LogLevel.Debug }\n );\n\n // Also log to diagnostic file for troubleshooting\n FileLogger.Log(\"MainViewModel\", formattedMessage);\n }\n\n private string _currentViewName = string.Empty;\n public string CurrentViewName\n {\n get => _currentViewName;\n set => SetProperty(ref _currentViewName, value);\n }\n\n [ObservableProperty]\n private string _maximizeButtonContent = \"\\uE739\";\n\n /// \n /// Gets the ViewModel for the More menu functionality\n /// \n public MoreMenuViewModel MoreMenuViewModel { get; }\n\n /// \n /// Gets the command to save a unified configuration.\n /// \n public ICommand SaveUnifiedConfigCommand { get; }\n\n /// \n /// Gets the command to import a unified configuration.\n /// \n public ICommand ImportUnifiedConfigCommand { get; }\n\n /// \n /// Gets the command to open the donation page in a browser.\n /// \n public ICommand OpenDonateCommand { get; }\n\n public MainViewModel(\n IThemeManager themeManager,\n INavigationService navigationService,\n ITaskProgressService progressService,\n IMessengerService messengerService,\n IDialogService dialogService,\n IUnifiedConfigurationService unifiedConfigService,\n Features.Common.Services.UserPreferencesService userPreferencesService,\n ILogService logService,\n IVersionService versionService,\n IApplicationCloseService applicationCloseService\n )\n : base(progressService, messengerService)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n _navigationService =\n navigationService ?? throw new ArgumentNullException(nameof(navigationService));\n _messengerService =\n messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n _dialogService =\n dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _unifiedConfigService =\n unifiedConfigService\n ?? throw new ArgumentNullException(nameof(unifiedConfigService));\n _userPreferencesService =\n userPreferencesService\n ?? throw new ArgumentNullException(nameof(userPreferencesService));\n\n // Initialize the MoreMenuViewModel\n MoreMenuViewModel = new MoreMenuViewModel(logService, versionService, _messengerService, applicationCloseService, _dialogService);\n\n // Initialize command properties\n _minimizeWindowCommand = new RelayCommand(MinimizeWindow);\n _maximizeRestoreWindowCommand = new RelayCommand(MaximizeRestoreWindow);\n // Use AsyncRelayCommand instead of RelayCommand for async methods\n _closeWindowCommand = new AsyncRelayCommand(CloseWindowAsync);\n SaveUnifiedConfigCommand = new RelayCommand(SaveUnifiedConfig);\n ImportUnifiedConfigCommand = new RelayCommand(ImportUnifiedConfig);\n OpenDonateCommand = new RelayCommand(OpenDonate);\n\n // Note: View mappings are now registered in App.xaml.cs when configuring the FrameNavigationService\n\n // Subscribe to navigation events\n _navigationService.Navigated += NavigationService_Navigated;\n\n // We'll initialize with the default view later, after the window is loaded\n // This will be called from MainWindow.xaml.cs after the window is loaded\n // This will be called from MainWindow.xaml.cs after the window is loaded\n }\n\n private void NavigationService_Navigated(object sender, NavigationEventArgs e)\n {\n CurrentViewName = e.Route;\n\n // The NavigationService sets e.Parameter to the ViewModel instance\n // This ensures the CurrentViewModel is properly set\n if (e.Parameter != null && e.Parameter is IViewModel)\n {\n CurrentViewModel = e.Parameter;\n }\n else if (e.ViewModelType != null)\n {\n // If for some reason the parameter is not set, try to get the ViewModel from the service provider\n try\n {\n // Get the view model from the navigation event parameter\n if (e.Parameter != null)\n {\n CurrentViewModel = e.Parameter;\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error getting current view model: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n }\n\n [RelayCommand]\n private void Navigate(string viewName)\n {\n try\n {\n _navigationService.NavigateTo(viewName);\n }\n catch (Exception ex)\n {\n // Log the error using the messaging system\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Navigation error to {viewName}: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n MessageBox.Show(\n $\"Navigation error while attempting to navigate to {viewName}.\\nError: {ex.Message}\",\n \"Navigation Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n }\n }\n\n [RelayCommand]\n private void ToggleTheme()\n {\n _themeManager.ToggleTheme();\n }\n\n // Explicit command property for MinimizeWindow\n private ICommand _minimizeWindowCommand;\n public ICommand MinimizeWindowCommand\n {\n get\n {\n if (_minimizeWindowCommand == null)\n {\n _minimizeWindowCommand = new RelayCommand(MinimizeWindow);\n }\n return _minimizeWindowCommand;\n }\n }\n\n private void MinimizeWindow()\n {\n LogWindowAction(\"MinimizeWindow command called\");\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"MainWindow is null\");\n return;\n }\n\n // Try to minimize the window directly\n try\n {\n mainWindow.WindowState = WindowState.Minimized;\n LogWindowAction(\"Directly set WindowState to Minimized\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Minimize,\n }\n );\n }\n }\n\n // Explicit command property for MaximizeRestoreWindow\n private ICommand _maximizeRestoreWindowCommand;\n public ICommand MaximizeRestoreWindowCommand\n {\n get\n {\n if (_maximizeRestoreWindowCommand == null)\n {\n _maximizeRestoreWindowCommand = new RelayCommand(MaximizeRestoreWindow);\n }\n return _maximizeRestoreWindowCommand;\n }\n }\n\n private void MaximizeRestoreWindow()\n {\n LogWindowAction(\"MaximizeRestoreWindow command called\");\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"MainWindow is null\");\n return;\n }\n\n if (mainWindow.WindowState == WindowState.Maximized)\n {\n // Try to restore the window directly\n try\n {\n mainWindow.WindowState = WindowState.Normal;\n LogWindowAction(\"Directly set WindowState to Normal\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Restore,\n }\n );\n }\n\n // Update the button icon\n MaximizeButtonContent = \"\\uE739\";\n LogWindowAction(\"Updated MaximizeButtonContent to Maximize icon\");\n }\n else\n {\n // Try to maximize the window directly\n try\n {\n mainWindow.WindowState = WindowState.Maximized;\n LogWindowAction(\"Directly set WindowState to Maximized\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Maximize,\n }\n );\n }\n\n // Update the button icon\n MaximizeButtonContent = \"\\uE923\";\n LogWindowAction(\"Updated MaximizeButtonContent to Restore icon\");\n }\n }\n\n // Explicit command property for CloseWindow\n private ICommand _closeWindowCommand;\n public ICommand CloseWindowCommand\n {\n get\n {\n if (_closeWindowCommand == null)\n {\n // Use AsyncRelayCommand instead of RelayCommand for async methods\n _closeWindowCommand = new AsyncRelayCommand(CloseWindowAsync);\n }\n return _closeWindowCommand;\n }\n }\n\n // Make sure this method is public so it can be called directly for testing\n public async Task CloseWindowAsync()\n {\n LogWindowAction(\"CloseWindowAsync method called\");\n\n // Log basic information\n _messengerService.Send(\n new LogMessage\n {\n Message = \"CloseWindow method executing in MainViewModel\",\n Level = LogLevel.Debug,\n }\n );\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"ERROR: MainWindow is null\");\n return;\n }\n\n // The donation dialog is now handled in MainWindow.CloseButton_Click\n // so we can simply close the window here\n\n try\n {\n LogWindowAction(\"About to call mainWindow.Close()\");\n mainWindow.Close();\n LogWindowAction(\"mainWindow.Close() called successfully\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"ERROR closing window directly: {ex.Message}\");\n\n // Fall back to messaging\n LogWindowAction(\"Falling back to WindowStateMessage.Close\");\n _messengerService.Send(\n new WindowStateMessage { Action = WindowStateMessage.WindowStateAction.Close }\n );\n }\n\n LogWindowAction(\"CloseWindowAsync method completed\");\n }\n\n /// \n /// Saves a unified configuration by delegating to the current view model.\n /// \n private async void SaveUnifiedConfig()\n {\n try\n {\n // Use the injected unified configuration service\n var unifiedConfigService = _unifiedConfigService;\n\n if (unifiedConfigService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"UnifiedConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Using UnifiedConfigurationService to save unified configuration\",\n Level = LogLevel.Info,\n }\n );\n\n // Create a unified configuration with settings from all view models\n var unifiedConfig = await unifiedConfigService.CreateUnifiedConfigurationAsync();\n\n // Get the configuration service from the application\n IConfigurationService configService = null;\n\n // Try to get the service from the application\n if (Application.Current is App appInstance3)\n {\n try\n {\n // Use reflection to access the _host.Services property\n var hostField = appInstance3\n .GetType()\n .GetField(\"_host\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (hostField != null)\n {\n var host = hostField.GetValue(appInstance3);\n var servicesProperty = host.GetType().GetProperty(\"Services\");\n if (servicesProperty != null)\n {\n var services = servicesProperty.GetValue(host);\n var getServiceMethod = services\n .GetType()\n .GetMethod(\"GetService\", new[] { typeof(Type) });\n if (getServiceMethod != null)\n {\n configService =\n getServiceMethod.Invoke(\n services,\n new object[] { typeof(IConfigurationService) }\n ) as IConfigurationService;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error accessing ConfigurationService: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n if (configService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"ConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n // Save the unified configuration\n bool saveResult = await unifiedConfigService.SaveUnifiedConfigurationAsync(\n unifiedConfig\n );\n\n if (saveResult)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Unified configuration saved successfully\",\n Level = LogLevel.Info,\n }\n );\n\n // Show a single success dialog using CustomDialog to match the application style\n var sections = new List();\n if (unifiedConfig.WindowsApps.Items.Any())\n sections.Add(\"Windows Apps\");\n if (unifiedConfig.ExternalApps.Items.Any())\n sections.Add(\"External Apps\");\n if (unifiedConfig.Customize.Items.Any())\n sections.Add(\"Customizations\");\n if (unifiedConfig.Optimize.Items.Any())\n sections.Add(\"Optimizations\");\n\n Winhance.WPF.Features.Common.Views.CustomDialog.ShowInformation(\n \"Configuration Saved\",\n \"Configuration saved successfully.\",\n sections,\n \"You can now import this configuration on another system.\"\n );\n }\n else\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Save unified configuration canceled by user\",\n Level = LogLevel.Info,\n }\n );\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error saving unified configuration: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n // FallbackToViewModelImplementation method removed as part of unified configuration cleanup\n\n /// \n /// Imports a unified configuration by delegating to the current view model.\n /// \n private async void ImportUnifiedConfig()\n {\n try\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Starting unified configuration import process\",\n Level = LogLevel.Info,\n }\n );\n\n // Use the injected unified configuration service\n var unifiedConfigService = _unifiedConfigService;\n\n _messengerService.Send(\n new LogMessage\n {\n Message =\n \"Using UnifiedConfigurationService to import unified configuration\",\n Level = LogLevel.Info,\n }\n );\n\n // Get the configuration service from the application\n IConfigurationService configService = null;\n\n // Try to get the service from the application\n if (Application.Current is App appInstance2)\n {\n try\n {\n // Use reflection to access the _host.Services property\n var hostField = appInstance2\n .GetType()\n .GetField(\"_host\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (hostField != null)\n {\n var host = hostField.GetValue(appInstance2);\n var servicesProperty = host.GetType().GetProperty(\"Services\");\n if (servicesProperty != null)\n {\n var services = servicesProperty.GetValue(host);\n var getServiceMethod = services\n .GetType()\n .GetMethod(\"GetService\", new[] { typeof(Type) });\n if (getServiceMethod != null)\n {\n configService =\n getServiceMethod.Invoke(\n services,\n new object[] { typeof(IConfigurationService) }\n ) as IConfigurationService;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error accessing ConfigurationService: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n if (configService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"ConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n // Load the unified configuration\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing file dialog to select configuration file\",\n Level = LogLevel.Info,\n }\n );\n\n var unifiedConfig = await unifiedConfigService.LoadUnifiedConfigurationAsync();\n\n if (unifiedConfig == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Import unified configuration canceled by user\",\n Level = LogLevel.Info,\n }\n );\n return;\n }\n\n _messengerService.Send(\n new LogMessage\n {\n Message =\n $\"Configuration loaded with sections: WindowsApps ({unifiedConfig.WindowsApps.Items.Count} items), \"\n + $\"ExternalApps ({unifiedConfig.ExternalApps.Items.Count} items), \"\n + $\"Customize ({unifiedConfig.Customize.Items.Count} items), \"\n + $\"Optimize ({unifiedConfig.Optimize.Items.Count} items)\",\n Level = LogLevel.Info,\n }\n );\n\n // Show the unified configuration dialog to let the user select which sections to import\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing unified configuration dialog for section selection\",\n Level = LogLevel.Info,\n }\n );\n\n // Show the unified configuration dialog to let the user select which sections to import\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing unified configuration dialog for section selection\",\n Level = LogLevel.Info,\n }\n );\n\n // Create a dictionary of sections with their availability and item counts\n var sectionInfo = new Dictionary<\n string,\n (bool IsSelected, bool IsAvailable, int ItemCount)\n >\n {\n {\n \"WindowsApps\",\n (\n true,\n unifiedConfig.WindowsApps.Items.Count > 0,\n unifiedConfig.WindowsApps.Items.Count\n )\n },\n {\n \"ExternalApps\",\n (\n true,\n unifiedConfig.ExternalApps.Items.Count > 0,\n unifiedConfig.ExternalApps.Items.Count\n )\n },\n {\n \"Customize\",\n (\n true,\n unifiedConfig.Customize.Items.Count > 0,\n unifiedConfig.Customize.Items.Count\n )\n },\n {\n \"Optimize\",\n (\n true,\n unifiedConfig.Optimize.Items.Count > 0,\n unifiedConfig.Optimize.Items.Count\n )\n },\n };\n\n // Create and show the dialog\n var dialog = new Views.UnifiedConfigurationDialog(\n \"Select Configuration Sections\",\n \"Select which sections you want to import from the unified configuration.\",\n sectionInfo,\n false\n );\n\n // Only set the Owner if the dialog is not the main window itself\n if (dialog != Application.Current.MainWindow)\n {\n try\n {\n dialog.Owner = Application.Current.MainWindow;\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error setting dialog owner: {ex.Message}\",\n Level = LogLevel.Warning,\n }\n );\n // Continue without setting the owner\n }\n }\n bool? dialogResult = dialog.ShowDialog();\n\n if (dialogResult != true)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"User canceled unified configuration import\",\n Level = LogLevel.Info,\n }\n );\n return;\n }\n\n // Get the selected sections from the dialog\n var result = dialog.GetResult();\n var selectedSections = result\n .Where(kvp => kvp.Value)\n .Select(kvp => kvp.Key)\n .ToList();\n\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Selected sections: {string.Join(\", \", selectedSections)}\",\n Level = LogLevel.Info,\n }\n );\n\n if (!selectedSections.Any())\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"No sections selected for import\",\n Level = LogLevel.Info,\n }\n );\n _dialogService.ShowMessage(\n \"Please select at least one section to import from the unified configuration.\",\n \"No sections selected\"\n );\n return;\n }\n\n // Apply the configuration to the selected sections\n _messengerService.Send(\n new LogMessage\n {\n Message =\n $\"Applying configuration to selected sections: {string.Join(\", \", selectedSections)}\",\n Level = LogLevel.Info,\n }\n );\n\n // Apply the configuration to the selected sections\n await unifiedConfigService.ApplyUnifiedConfigurationAsync(\n unifiedConfig,\n selectedSections\n );\n\n // Always show a success message since the settings are being applied correctly\n // even if the updatedCount is 0\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Unified configuration imported successfully\",\n Level = LogLevel.Info,\n }\n );\n\n // Show a success message using CustomDialog to match the application style\n var importedSections = new List();\n foreach (var section in selectedSections)\n {\n switch (section)\n {\n case \"WindowsApps\":\n importedSections.Add(\"Windows Apps\");\n break;\n case \"ExternalApps\":\n importedSections.Add(\"External Apps\");\n break;\n case \"Customize\":\n importedSections.Add(\"Customizations\");\n break;\n case \"Optimize\":\n importedSections.Add(\"Optimizations\");\n break;\n }\n }\n\n Winhance.WPF.Features.Common.Views.CustomDialog.ShowInformation(\n \"Configuration Imported\",\n \"The unified configuration has been imported successfully.\",\n importedSections,\n \"The selected settings have been applied to your system.\"\n );\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error importing unified configuration: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n // Show an error message to the user\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"An error occurred while importing the configuration: {ex.Message}\",\n \"Import Error\"\n );\n }\n }\n }\n\n // FallbackToViewModelImportImplementation method removed as part of unified configuration cleanup\n\n /// \n /// Opens the donation page in the default browser.\n /// \n private void OpenDonate()\n {\n try\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Opening donation page in browser\",\n Level = LogLevel.Info,\n }\n );\n\n // Use ProcessStartInfo to open the URL in the default browser\n var psi = new ProcessStartInfo\n {\n FileName = \"https://ko-fi.com/memstechtips\",\n UseShellExecute = true,\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error opening donation page: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n // Show an error message to the user\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"An error occurred while opening the donation page: {ex.Message}\",\n \"Error\"\n );\n }\n }\n }\n\n\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/LoadingWindow.xaml.cs", "using System;\nusing System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Media.Imaging;\nusing System.Runtime.InteropServices;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Interaction logic for LoadingWindow.xaml\n /// \n public partial class LoadingWindow : Window\n {\n private readonly IThemeManager? _themeManager;\n private LoadingWindowViewModel? _viewModel;\n\n /// \n /// Default constructor for design-time\n /// \n public LoadingWindow()\n {\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n }\n\n /// \n /// Constructor with dependency injection\n /// \n /// The theme manager\n public LoadingWindow(IThemeManager themeManager)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n }\n\n /// \n /// Constructor with dependency injection and progress service\n /// \n /// The theme manager\n /// The progress service\n public LoadingWindow(IThemeManager themeManager, ITaskProgressService progressService)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n\n // Create and set the view model\n _viewModel = new LoadingWindowViewModel(progressService);\n DataContext = _viewModel;\n\n // Set the appropriate icon based on the theme\n UpdateThemeIcon();\n }\n\n /// \n /// Called when the window source is initialized\n /// \n /// Event arguments\n protected override void OnSourceInitialized(EventArgs e)\n {\n base.OnSourceInitialized(e);\n\n try\n {\n var helper = new WindowInteropHelper(this);\n if (helper.Handle != IntPtr.Zero)\n {\n EnableBlur();\n }\n }\n catch (Exception)\n {\n // Ignore blur errors - not critical for loading window\n }\n }\n\n /// \n /// Enables the blur effect on the window\n /// \n private void EnableBlur()\n {\n var windowHelper = new WindowInteropHelper(this);\n var accent = new AccentPolicy { AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND };\n var accentStructSize = Marshal.SizeOf(accent);\n\n var accentPtr = IntPtr.Zero;\n try\n {\n accentPtr = Marshal.AllocHGlobal(accentStructSize);\n Marshal.StructureToPtr(accent, accentPtr, false);\n\n var data = new WindowCompositionAttributeData\n {\n Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,\n SizeOfData = accentStructSize,\n Data = accentPtr\n };\n\n SetWindowCompositionAttribute(windowHelper.Handle, ref data);\n }\n finally\n {\n if (accentPtr != IntPtr.Zero)\n {\n Marshal.FreeHGlobal(accentPtr);\n }\n }\n }\n\n /// \n /// P/Invoke for SetWindowCompositionAttribute\n /// \n [DllImport(\"user32.dll\")]\n internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);\n\n /// \n /// Accent policy structure\n /// \n [StructLayout(LayoutKind.Sequential)]\n internal struct AccentPolicy\n {\n public AccentState AccentState;\n public int AccentFlags;\n public int GradientColor;\n public int AnimationId;\n }\n\n /// \n /// Window composition attribute data structure\n /// \n [StructLayout(LayoutKind.Sequential)]\n internal struct WindowCompositionAttributeData\n {\n public WindowCompositionAttribute Attribute;\n public IntPtr Data;\n public int SizeOfData;\n }\n\n /// \n /// Accent state enum\n /// \n internal enum AccentState\n {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5\n }\n\n /// \n /// Window composition attribute enum\n /// \n internal enum WindowCompositionAttribute\n {\n WCA_ACCENT_POLICY = 19\n }\n\n /// \n /// Updates the window and image icons based on the current theme\n /// \n private void UpdateThemeIcon()\n {\n if (_themeManager == null)\n {\n Debug.WriteLine(\"Cannot update theme icon: ThemeManager is null\");\n return;\n }\n\n try\n {\n Debug.WriteLine($\"Updating theme icon. Current theme: {(_themeManager.IsDarkTheme ? \"Dark\" : \"Light\")}\");\n\n // Get the appropriate icon based on the theme\n string iconPath = _themeManager.IsDarkTheme\n ? \"pack://application:,,,/Resources/AppIcons/winhance-rocket-white-transparent-bg.ico\"\n : \"pack://application:,,,/Resources/AppIcons/winhance-rocket-black-transparent-bg.ico\";\n\n Debug.WriteLine($\"Selected icon path: {iconPath}\");\n\n // Create a BitmapImage from the icon path\n var iconImage = new BitmapImage(new Uri(iconPath, UriKind.Absolute));\n iconImage.Freeze(); // Freeze for better performance and thread safety\n\n // Set the window icon\n this.Icon = iconImage;\n Debug.WriteLine(\"Window icon updated\");\n\n // Set the image control source\n if (AppIconImage != null)\n {\n AppIconImage.Source = iconImage;\n Debug.WriteLine(\"AppIconImage source updated\");\n }\n else\n {\n Debug.WriteLine(\"AppIconImage is null, cannot update source\");\n }\n }\n catch (Exception ex)\n {\n // If there's an error, fall back to the default icon\n try\n {\n var defaultIcon = new BitmapImage(new Uri(\"pack://application:,,,/Resources/AppIcons/winhance-rocket.ico\", UriKind.Absolute));\n this.Icon = defaultIcon;\n if (AppIconImage != null)\n {\n AppIconImage.Source = defaultIcon;\n }\n }\n catch\n {\n // Ignore any errors with the fallback icon\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/MoreMenu.xaml.cs", "using System;\nusing System.IO;\nusing System.Windows;\nusing System.Windows.Controls;\nusing Winhance.WPF.Features.Common.Utilities;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for MoreMenu.xaml\n /// \n public partial class MoreMenu : UserControl\n {\n public MoreMenu()\n {\n try\n {\n LogToStartupLog(\"MoreMenu constructor starting\");\n InitializeComponent();\n LogToStartupLog(\"MoreMenu constructor completed successfully\");\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"ERROR in MoreMenu constructor: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n throw; // Re-throw to ensure the error is properly handled\n }\n }\n\n /// \n /// Logs a message directly to the WinhanceStartupLog.txt file\n /// \n private void LogToStartupLog(string message)\n {\n#if DEBUG\n try\n {\n string logsDir = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\"\n );\n string logFile = Path.Combine(logsDir, \"WinhanceStartupLog.txt\");\n\n // Ensure the logs directory exists\n if (!Directory.Exists(logsDir))\n {\n Directory.CreateDirectory(logsDir);\n }\n\n // Format the log message with timestamp\n string formattedMessage =\n $\"[{DateTime.Now:yyyy/MM/dd HH:mm:ss}] [MoreMenu] {message}\";\n\n // Append to the log file\n using (StreamWriter writer = File.AppendText(logFile))\n {\n writer.WriteLine(formattedMessage);\n }\n }\n catch\n {\n // Ignore errors in logging to avoid cascading issues\n }\n#endif\n }\n\n /// \n /// Shows the context menu at the specified placement target\n /// \n /// The UI element that the context menu should be positioned relative to\n public void ShowMenu(UIElement placementTarget)\n {\n try\n {\n LogToStartupLog(\"ShowMenu method called\");\n LogToStartupLog($\"placementTarget exists: {placementTarget != null}\");\n LogToStartupLog($\"DataContext exists: {DataContext != null}\");\n LogToStartupLog(\n $\"DataContext type: {(DataContext != null ? DataContext.GetType().FullName : \"null\")}\"\n );\n\n // Get the context menu from resources\n var contextMenu = Resources[\"MoreButtonContextMenu\"] as ContextMenu;\n LogToStartupLog($\"ContextMenu from resources exists: {contextMenu != null}\");\n\n if (contextMenu != null)\n {\n try\n {\n // Ensure the context menu has the same DataContext as the control\n LogToStartupLog(\"Setting context menu DataContext\");\n contextMenu.DataContext = this.DataContext;\n LogToStartupLog(\n $\"Context menu DataContext set: {contextMenu.DataContext != null}\"\n );\n\n // Add a handler to log when menu items are clicked\n foreach (var item in contextMenu.Items)\n {\n if (item is MenuItem menuItem)\n {\n LogToStartupLog(\n $\"Menu item: {menuItem.Header}, Command bound: {menuItem.Command != null}\"\n );\n\n // Add a Click handler to log when the item is clicked\n menuItem.Click += (s, e) =>\n {\n LogToStartupLog($\"Menu item clicked: {menuItem.Header}\");\n if (menuItem.Command != null)\n {\n LogToStartupLog(\n $\"Command can execute: {menuItem.Command.CanExecute(null)}\"\n );\n }\n };\n }\n }\n\n // Set the placement target\n LogToStartupLog(\"Setting placement target\");\n contextMenu.PlacementTarget = placementTarget;\n LogToStartupLog(\"Placement target set successfully\");\n\n // Set placement mode to Right to show menu to the right of the button\n LogToStartupLog(\"Setting placement mode\");\n contextMenu.Placement = System\n .Windows\n .Controls\n .Primitives\n .PlacementMode\n .Right;\n LogToStartupLog(\"Placement mode set successfully\");\n\n // No horizontal or vertical offset\n LogToStartupLog(\"Setting offset values\");\n contextMenu.HorizontalOffset = 0;\n contextMenu.VerticalOffset = 0;\n LogToStartupLog(\"Offset values set successfully\");\n\n // Open the context menu\n LogToStartupLog(\"About to open context menu\");\n contextMenu.IsOpen = true;\n LogToStartupLog(\"Context menu opened successfully\");\n }\n catch (Exception menuEx)\n {\n LogToStartupLog($\"ERROR configuring context menu: {menuEx.Message}\");\n LogToStartupLog($\"Stack trace: {menuEx.StackTrace}\");\n }\n }\n else\n {\n LogToStartupLog(\"ERROR: ContextMenu from resources is null, cannot show menu\");\n }\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"ERROR in ShowMenu method: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/App.xaml.cs", "using System;\nusing System.IO;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Services;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Services;\nusing Winhance.Infrastructure.Features.Customize.Services;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Implementations;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Services.Configuration;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Customize.ViewModels;\nusing Winhance.WPF.Features.Customize.Views;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.Optimize.Views;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.Views;\n\nnamespace Winhance.WPF\n{\n public partial class App : Application\n {\n private readonly IHost _host;\n\n public App()\n {\n // Add global unhandled exception handlers\n AppDomain.CurrentDomain.UnhandledException += (sender, args) =>\n {\n var ex = args.ExceptionObject as Exception;\n LogStartupError($\"Unhandled AppDomain exception: {ex?.Message}\", ex);\n };\n\n Current.DispatcherUnhandledException += (sender, args) =>\n {\n LogStartupError(\n $\"Unhandled Dispatcher exception: {args.Exception.Message}\",\n args.Exception\n );\n args.Handled = true; // Prevent the application from crashing\n };\n\n TaskScheduler.UnobservedTaskException += (sender, args) =>\n {\n LogStartupError(\n $\"Unobserved Task exception: {args.Exception.Message}\",\n args.Exception\n );\n args.SetObserved(); // Prevent the application from crashing\n };\n\n _host = Host.CreateDefaultBuilder()\n .ConfigureServices(\n (context, services) =>\n {\n ConfigureServices(services);\n }\n )\n .Build();\n\n LogStartupError(\"Application constructor completed\");\n }\n\n protected override async void OnStartup(StartupEventArgs e)\n {\n LogStartupError(\"OnStartup method beginning\");\n LoadingWindow? loadingWindow = null;\n\n // Ensure the application has administrator privileges\n try\n {\n LogStartupError(\"Checking for administrator privileges\");\n var systemServices = _host.Services.GetService();\n if (systemServices != null)\n {\n bool isAdmin = systemServices.RequireAdministrator();\n LogStartupError($\"Administrator privileges check result: {isAdmin}\");\n }\n else\n {\n LogStartupError(\"ISystemServices not available for admin check\");\n }\n }\n catch (Exception adminEx)\n {\n LogStartupError(\n \"Error checking administrator privileges: \" + adminEx.Message,\n adminEx\n );\n }\n\n // Set the application icon for all windows\n try\n {\n // We'll continue to use the original icon for the application icon (taskbar, shortcuts, etc.)\n var iconUri = new Uri(\"/Resources/AppIcons/winhance-rocket.ico\", UriKind.Relative);\n Current.Resources[\"ApplicationIcon\"] = new System.Windows.Media.Imaging.BitmapImage(\n iconUri\n );\n LogStartupError(\"Application icon set successfully\");\n }\n catch (Exception iconEx)\n {\n LogStartupError(\"Failed to set application icon: \" + iconEx.Message, iconEx);\n }\n\n try\n {\n // Create and show loading window first\n LogStartupError(\"Attempting to get theme manager\");\n var themeManager = _host.Services.GetRequiredService();\n LogStartupError(\"Got theme manager\");\n\n // Ensure the IsDarkTheme resource is set in the application resources\n Application.Current.Resources[\"IsDarkTheme\"] = themeManager.IsDarkTheme;\n LogStartupError($\"Set IsDarkTheme resource to {themeManager.IsDarkTheme}\");\n\n LogStartupError(\"Attempting to get task progress service\");\n var initialProgressService =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got task progress service\");\n\n LogStartupError(\"Creating loading window\");\n loadingWindow = new LoadingWindow(themeManager, initialProgressService);\n LogStartupError(\"Loading window created\");\n\n LogStartupError(\"Showing loading window\");\n loadingWindow.Show();\n LogStartupError(\"Loading window shown\");\n\n // Start the host and initialize services\n LogStartupError(\"Starting host\");\n await _host.StartAsync();\n LogStartupError(\"Host started\");\n\n // Get required services\n LogStartupError(\"Getting main window\");\n var mainWindow = _host.Services.GetRequiredService();\n LogStartupError(\"Got main window\");\n\n LogStartupError(\"Getting main view model\");\n var mainViewModel = _host.Services.GetRequiredService();\n LogStartupError(\"Got main view model\");\n\n LogStartupError(\"Getting software apps view model\");\n var windowsAppsViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got Windows apps view model\");\n\n // Set the DataContext\n LogStartupError(\"Setting main window DataContext\");\n mainWindow.DataContext = mainViewModel;\n LogStartupError(\"Main window DataContext set\");\n\n // Preload the SoftwareAppsViewModel data\n LogStartupError(\"Loading apps and checking installation status...\");\n\n // Create a progress handler to update the loading window\n var progressHandler = new EventHandler(\n (sender, args) =>\n {\n if (\n loadingWindow != null\n && loadingWindow.DataContext is LoadingWindowViewModel vm\n )\n {\n vm.Progress = args.Progress * 100;\n vm.StatusMessage = args.StatusText;\n vm.IsIndeterminate = args.IsIndeterminate;\n vm.ShowProgressText = !args.IsIndeterminate && args.IsTaskRunning;\n\n // Update detail message based on the current operation\n if (args.StatusText.Contains(\"Loading installable apps\"))\n {\n vm.DetailMessage = \"Discovering available applications...\";\n }\n else if (args.StatusText.Contains(\"Loading removable apps\"))\n {\n vm.DetailMessage = \"Identifying Windows applications...\";\n }\n else if (args.StatusText.Contains(\"Checking installation status\"))\n {\n vm.DetailMessage = \"Verifying which applications are installed...\";\n }\n else if (args.StatusText.Contains(\"Organizing apps\"))\n {\n vm.DetailMessage = \"Sorting applications for display...\";\n }\n }\n }\n );\n\n // Subscribe to progress events\n LogStartupError(\"Getting task progress service\");\n var taskProgressService = _host.Services.GetRequiredService();\n LogStartupError(\"Got task progress service\");\n\n LogStartupError(\"Subscribing to progress events\");\n taskProgressService.ProgressChanged += progressHandler;\n LogStartupError(\"Subscribed to progress events\");\n\n try\n {\n // Load apps and check installation status while showing the loading screen\n LogStartupError(\n \"Starting LoadAppsAndCheckInstallationStatusAsync for WindowsAppsViewModel\"\n );\n await windowsAppsViewModel.LoadAppsAndCheckInstallationStatusAsync();\n LogStartupError(\"WindowsApps loaded and installation status checked\");\n\n // Also preload the SoftwareAppsViewModel data\n LogStartupError(\"Getting SoftwareAppsViewModel\");\n var softwareAppsViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got SoftwareAppsViewModel\");\n\n LogStartupError(\"Starting Initialize for SoftwareAppsViewModel\");\n await softwareAppsViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"SoftwareAppsViewModel initialized\");\n\n // Preload the OptimizeViewModel to ensure all registry settings are loaded\n LogStartupError(\"Getting OptimizeViewModel\");\n var optimizeViewModel = _host.Services.GetRequiredService();\n LogStartupError(\"Got OptimizeViewModel\");\n\n // Initialize the OptimizeViewModel and wait for it to complete\n LogStartupError(\"Starting Initialize for OptimizeViewModel\");\n if (loadingWindow?.DataContext is LoadingWindowViewModel loadingVM)\n {\n loadingVM.StatusMessage = \"Loading system settings...\";\n loadingVM.DetailMessage = \"Checking registry settings...\";\n }\n await optimizeViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"OptimizeViewModel initialized\");\n\n // Preload the CustomizeViewModel to ensure all customization settings are loaded\n LogStartupError(\"Getting CustomizeViewModel\");\n var customizeViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got CustomizeViewModel\");\n\n // Initialize the CustomizeViewModel and wait for it to complete\n LogStartupError(\"Starting Initialize for CustomizeViewModel\");\n if (loadingWindow?.DataContext is LoadingWindowViewModel loadingVMCustomize)\n {\n loadingVMCustomize.StatusMessage = \"Loading customization settings...\";\n loadingVMCustomize.DetailMessage = \"Checking customization options...\";\n }\n await customizeViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"CustomizeViewModel initialized\");\n }\n finally\n {\n // Unsubscribe from progress events\n LogStartupError(\"Unsubscribing from progress events\");\n taskProgressService.ProgressChanged -= progressHandler;\n LogStartupError(\"Unsubscribed from progress events\");\n }\n\n // Show the main window\n LogStartupError(\"Showing main window\");\n mainWindow.Show();\n LogStartupError(\"Main window shown\");\n\n // Close the loading window\n LogStartupError(\"Closing loading window\");\n loadingWindow.Close();\n loadingWindow = null;\n LogStartupError(\"Loading window closed\");\n\n // Check for updates\n await CheckForUpdatesAsync(mainWindow);\n\n LogStartupError(\"Calling base.OnStartup\");\n base.OnStartup(e);\n LogStartupError(\"OnStartup method completed successfully\");\n }\n catch (Exception ex)\n {\n LogStartupError(\"Error during startup\", ex);\n MessageBox.Show(\n $\"Error during startup: {ex.Message}\\n\\nStack Trace:\\n{ex.StackTrace}\",\n \"Startup Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n\n // Ensure loading window is closed if there was an error\n if (loadingWindow != null)\n {\n loadingWindow.Close();\n }\n\n Current.Shutdown();\n }\n }\n\n private async Task CheckForUpdatesAsync(Window ownerWindow)\n {\n try\n {\n LogStartupError(\"Checking for updates...\");\n var versionService = _host.Services.GetRequiredService();\n var latestVersion = await versionService.CheckForUpdateAsync();\n\n if (latestVersion.IsUpdateAvailable)\n {\n LogStartupError($\"Update available: {latestVersion.Version}\");\n\n // Get current version\n var currentVersion = versionService.GetCurrentVersion();\n\n // Show the styled update dialog\n string message = \"Good News! A New Version of Winhance is available.\";\n\n // Create a download and install action\n Func downloadAndInstallAction = async () =>\n {\n await versionService.DownloadAndInstallUpdateAsync();\n\n // Close the application without showing a message\n System.Windows.Application.Current.Shutdown();\n };\n\n // Show the update dialog\n bool installNow = await UpdateDialog.ShowAsync(\n \"Update Available\",\n message,\n currentVersion,\n latestVersion,\n downloadAndInstallAction\n );\n\n if (installNow)\n {\n LogStartupError(\"User chose to download and install the update\");\n }\n else\n {\n LogStartupError(\"User chose to be reminded later\");\n }\n }\n else\n {\n LogStartupError(\"No updates available\");\n }\n }\n catch (Exception ex)\n {\n LogStartupError($\"Error checking for updates: {ex.Message}\", ex);\n // Don't show error to user, just log it\n }\n }\n\n protected override async void OnExit(ExitEventArgs e)\n {\n try\n {\n // Material Design resources are automatically unloaded\n\n // Dispose of the ThemeManager to clean up event subscriptions\n try\n {\n var themeManager = _host.Services.GetService();\n themeManager?.Dispose();\n }\n catch (Exception disposeEx)\n {\n LogStartupError(\"Error disposing ThemeManager\", disposeEx);\n }\n\n using (_host)\n {\n await _host.StopAsync();\n }\n }\n catch (Exception ex)\n {\n LogStartupError(\"Error during shutdown\", ex);\n }\n finally\n {\n base.OnExit(e);\n }\n }\n\n private void LogStartupError(string message, Exception? ex = null)\n {\n string fullMessage = $\"[{DateTime.Now}] {message}\";\n if (ex != null)\n {\n fullMessage += $\"\\nException: {ex.Message}\\nStack Trace: {ex.StackTrace}\";\n if (ex.InnerException != null)\n {\n fullMessage += $\"\\nInner Exception: {ex.InnerException.Message}\";\n }\n }\n\n try\n {\n string logPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\",\n \"WinhanceStartupLog.txt\"\n );\n\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(logPath));\n File.AppendAllText(logPath, $\"{fullMessage}\\n\");\n }\n catch\n {\n MessageBox.Show(\n fullMessage,\n \"Startup Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n }\n }\n\n private void ConfigureServices(IServiceCollection services)\n {\n try\n {\n LogStartupError(\"Beginning service configuration...\");\n\n // Core Services\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton<\n Winhance.Core.Interfaces.Services.IFileSystemService,\n Winhance.Infrastructure.FileSystem.FileSystemService\n >();\n\n // Register the base services\n services.AddSingleton();\n services.AddSingleton(provider =>\n provider.GetRequiredService()\n );\n services.AddSingleton();\n services.AddSingleton(\n provider => new SpecialAppHandlerService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton<\n ISearchService,\n Winhance.Infrastructure.Features.Common.Services.SearchService\n >();\n services.AddSingleton<\n IConfigurationService,\n Winhance.Infrastructure.Features.Common.Services.ConfigurationService\n >();\n // Register UserPreferencesService as a singleton to ensure the same instance is used throughout the app\n services.AddSingleton(provider =>\n {\n var logService = provider.GetRequiredService();\n var userPreferencesService =\n new Features.Common.Services.UserPreferencesService(logService);\n\n // Log that the UserPreferencesService has been registered\n logService.Log(LogLevel.Info, \"UserPreferencesService registered as singleton\");\n\n return userPreferencesService;\n });\n services.AddSingleton(\n provider => new Winhance.WPF.Features.Common.Services.UnifiedConfigurationService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register configuration services\n services.AddConfigurationServices();\n\n // Keep the old service for backward compatibility during transition\n services.AddSingleton(\n provider => new Winhance.WPF.Features.Common.Services.ConfigurationCoordinatorService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton();\n\n // Register script generation services\n services.AddScriptGenerationServices();\n\n services.AddSingleton(\n provider => new PowerShellExecutionService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register power plan service\n services.AddSingleton<\n Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService,\n Winhance.Infrastructure.Features.Optimize.Services.PowerPlanService\n >();\n\n // Register the installation and removal services\n // Register WinGet verification methods\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n // Register the composite verifier\n services.AddSingleton();\n\n // Register the WinGet installer\n services.AddSingleton();\n\n // Register the adapter for backward compatibility\n services.AddSingleton<\n IWinGetInstallationService,\n WinGetInstallationServiceAdapter\n >();\n\n // Register the main installation service\n services.AddSingleton(\n provider => new AppInstallationService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton(provider => new AppRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n services.AddSingleton<\n ICapabilityInstallationService,\n CapabilityInstallationService\n >();\n services.AddSingleton(\n provider => new CapabilityRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton();\n services.AddSingleton(provider => new FeatureRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register the orchestrator\n services.AddSingleton();\n\n // Register the PackageManager with its dependencies\n services.AddSingleton(provider => new PackageManager(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetService()\n ));\n\n // Register the InternetConnectivityService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.Common.Services.InternetConnectivityService(\n provider.GetRequiredService()\n )\n );\n\n // Register the AppInstallationCoordinatorService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.SoftwareApps.Services.AppInstallationCoordinatorService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetService(),\n provider.GetService()\n )\n );\n\n // Use fully qualified type name to resolve ambiguity between Winhance.Core.Models.WindowsService\n // and Winhance.Infrastructure.Features.Common.Services.WindowsSystemService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.Common.Services.WindowsSystemService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n null, // Intentionally not passing IThemeService to break circular dependency\n provider.GetRequiredService()\n )\n );\n\n // Register theme and wallpaper services\n services.AddSingleton();\n services.AddSingleton(provider => new ThemeService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton<\n Core.Features.Common.Interfaces.IDialogService,\n Features.Common.Services.DialogService\n >();\n services.AddSingleton();\n services.AddSingleton();\n\n // Register the notification service\n services.AddSingleton<\n Core.Features.UI.Interfaces.INotificationService,\n Winhance.Infrastructure.Features.UI.Services.NotificationService\n >();\n\n // Register the messenger service\n services.AddSingleton<\n Core.Features.Common.Interfaces.IMessengerService,\n Features.Common.Services.MessengerService\n >();\n\n // Register navigation service\n services.AddSingleton(\n provider =>\n {\n var navigationService = new FrameNavigationService(\n provider,\n provider.GetRequiredService()\n );\n\n // Register view mappings\n navigationService.RegisterViewMapping(\n \"SoftwareApps\",\n typeof(Features.SoftwareApps.Views.SoftwareAppsView),\n typeof(Features.SoftwareApps.ViewModels.SoftwareAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"WindowsApps\",\n typeof(Features.SoftwareApps.Views.WindowsAppsView),\n typeof(Features.SoftwareApps.ViewModels.WindowsAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"ExternalApps\",\n typeof(Features.SoftwareApps.Views.ExternalAppsView),\n typeof(Features.SoftwareApps.ViewModels.ExternalAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"Optimize\",\n typeof(Features.Optimize.Views.OptimizeView),\n typeof(Features.Optimize.ViewModels.OptimizeViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"Customize\",\n typeof(Features.Customize.Views.CustomizeView),\n typeof(Features.Customize.ViewModels.CustomizeViewModel)\n );\n\n return navigationService;\n }\n );\n\n services.AddSingleton<\n IParameterSerializer,\n Winhance.Infrastructure.Features.Common.Services.JsonParameterSerializer\n >();\n\n // Register ThemeManager with navigation service dependency\n services.AddSingleton(\n provider => new Features.Common.Resources.Theme.ThemeManager(\n provider.GetRequiredService()\n )\n );\n\n // Register design-time data service\n services.AddSingleton<\n Features.Common.Services.IDesignTimeDataService,\n Features.Common.Services.DesignTimeDataService\n >();\n\n // Register ViewModels with explicit factory methods for all view models\n services.AddSingleton(provider => new MainViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new WindowsAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new ExternalAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register UacSettingsService\n services.AddSingleton(\n provider => new UacSettingsService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register child ViewModels for OptimizeViewModel\n services.AddSingleton(\n provider => new WindowsSecurityOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new PrivacyOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new GamingandPerformanceOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new UpdateOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new PowerOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // ViewModels are registered above\n\n services.AddSingleton(provider => new OptimizeViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register child ViewModels for CustomizeViewModel\n services.AddSingleton(\n provider => new TaskbarCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new StartMenuCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new ExplorerCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new ExplorerOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new NotificationOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new SoundOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new WindowsThemeCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(provider => new CustomizeViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new SoftwareAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider\n ));\n\n // Register Views\n services.AddTransient