From 216ea4e0c47524ced606db1cbc73af585b6f2a9c Mon Sep 17 00:00:00 2001 From: aL1CesT <63580499+aL1CesT@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:16:50 +0800 Subject: [PATCH] =?UTF-8?q?refactor(desktop):=20=E9=A1=B5=E9=9D=A2?= =?UTF-8?q?=E5=88=87=E6=8D=A2=E7=BB=9F=E4=B8=80=E8=B5=B0=20INavigationServ?= =?UTF-8?q?ice?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 侧栏原先是在 MainWindow.axaml.cs 里用一个针对 ListBox.SelectedIndex 的 switch 接起来的,直接调 App.Services.GetRequiredService<...> 从 code-behind 赋页面。 NavigationService 存在、已注册,却从没被用过。 后果:首页的深层链接无法改变侧栏选中项;新增一个页面要同时改 view model 和 code-behind;每个页面即使该是单例也会被重新构造。 现在: - INavigationService 增加 NavigateRoot(),用于"跳到顶层页面"(清空回退栈), 与已有的 NavigateTo()、GoBack() 并存。 - MainWindowViewModel 订阅 NavigationChanged,把当前 view model 反映射成侧栏 索引,因此从首页卡片跳转时侧栏高亮会跟着走。 - MainWindow.axaml.cs 基本清空;ListBox 绑索引,导航由 view model 发起。 这个提交里两处对话框服务的新增是给后面页面用的: - ShowFilesPickerAsync —— 多选,解密页需要 - ShowQrCodeLoginDialogAsync —— 把网易云二维码对话框作为模态窗口承载 - ShowMessageAsync 补进接口。它早已实现、也早已被调用,只是没写进契约。 --- .../Services/DialogService.cs | 63 ++++++++++++++-- .../Services/IDialogService.cs | 14 ++++ .../Services/INavigationService.cs | 10 +++ .../Services/NavigationService.cs | 68 ++++++++++++++++-- .../Services/ServiceCollectionExtensions.cs | 13 +++- .../ViewModels/MainWindowViewModel.cs | 72 +++++++++++++++++-- .../Views/MainWindow.axaml | 18 ++++- .../Views/MainWindow.axaml.cs | 27 ------- 8 files changed, 239 insertions(+), 46 deletions(-) diff --git a/src/ZonyLrcTools.Desktop/Services/DialogService.cs b/src/ZonyLrcTools.Desktop/Services/DialogService.cs index 9e3706e..320d736 100644 --- a/src/ZonyLrcTools.Desktop/Services/DialogService.cs +++ b/src/ZonyLrcTools.Desktop/Services/DialogService.cs @@ -2,6 +2,7 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform.Storage; +using ZonyLrcTools.Desktop.ViewModels; using ZonyLrcTools.Desktop.Views.Dialogs; namespace ZonyLrcTools.Desktop.Services; @@ -28,22 +29,58 @@ public class DialogService : IDialogService public async Task ShowFilePickerAsync(string title, string[]? filters = null) { - if (MainWindow == null) return null; + var files = await ShowFilesPickerAsync(title, filters); + return files.FirstOrDefault(); + } - var fileTypes = filters?.Select(f => new FilePickerFileType(f) - { - Patterns = new[] { f } - }).ToList(); + public async Task> ShowFilesPickerAsync(string title, string[]? filters = null) + { + if (MainWindow == null) return Array.Empty(); + + var fileTypes = BuildFileTypes(filters); var files = await MainWindow.StorageProvider.OpenFilePickerAsync( new FilePickerOpenOptions { Title = title, - AllowMultiple = false, + AllowMultiple = true, FileTypeFilter = fileTypes }); - return files.FirstOrDefault()?.Path.LocalPath; + return files + .Select(f => f.Path.LocalPath) + .Where(p => !string.IsNullOrEmpty(p)) + .ToList(); + } + + /// + /// Turn a list of bare extensions (".mp3", "mp3", "*.mp3") into Avalonia file type filters. + /// + private static List? BuildFileTypes(string[]? filters) + { + if (filters == null || filters.Length == 0) + { + return null; + } + + var patterns = filters + .Where(f => !string.IsNullOrWhiteSpace(f)) + .Select(f => f.StartsWith('*') ? f : $"*.{f.TrimStart('.')}") + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + + if (patterns.Length == 0) + { + return null; + } + + var name = string.Join(" / ", patterns.Select(p => p.TrimStart('*', '.'))); + + return new List + { + new(name) { Patterns = patterns }, + new("All files") { Patterns = new[] { "*" } } + }; } public async Task ShowConfirmDialogAsync(string title, string message) @@ -62,4 +99,16 @@ public class DialogService : IDialogService var dialog = new MessageDialog(title, message); await dialog.ShowDialog(MainWindow); } + + public async Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel) + { + if (MainWindow == null) + { + viewModel.RequestClose(); + return; + } + + var dialog = new QrCodeLoginDialog(viewModel); + await dialog.ShowDialog(MainWindow); + } } diff --git a/src/ZonyLrcTools.Desktop/Services/IDialogService.cs b/src/ZonyLrcTools.Desktop/Services/IDialogService.cs index 0428216..3e1e3ad 100644 --- a/src/ZonyLrcTools.Desktop/Services/IDialogService.cs +++ b/src/ZonyLrcTools.Desktop/Services/IDialogService.cs @@ -1,9 +1,23 @@ +using ZonyLrcTools.Desktop.ViewModels; + namespace ZonyLrcTools.Desktop.Services; public interface IDialogService { Task ShowFolderPickerAsync(string title); + Task ShowFilePickerAsync(string title, string[]? filters = null); + + Task> ShowFilesPickerAsync(string title, string[]? filters = null); + Task ShowConfirmDialogAsync(string title, string message); + Task ShowMessageAsync(string title, string message); + + /// + /// Open the NetEase QR-code login dialog as a modal child of the main window. + /// The returned task completes when the user or the login flow closes it; callers that + /// only want the dialog on screen can ignore it. + /// + Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel); } diff --git a/src/ZonyLrcTools.Desktop/Services/INavigationService.cs b/src/ZonyLrcTools.Desktop/Services/INavigationService.cs index f3697f0..76acbc3 100644 --- a/src/ZonyLrcTools.Desktop/Services/INavigationService.cs +++ b/src/ZonyLrcTools.Desktop/Services/INavigationService.cs @@ -7,7 +7,17 @@ public interface INavigationService ViewModelBase? CurrentViewModel { get; } event EventHandler? NavigationChanged; + /// + /// Push a page onto the navigation stack. Use for drill-down (detail pages, wizards). + /// TViewModel NavigateTo() where TViewModel : ViewModelBase; + + /// + /// Replace the whole stack with a single page. This is what the sidebar uses: switching + /// sections is not a back-navigable action, so the stack must not grow on every click. + /// + TViewModel NavigateRoot() where TViewModel : ViewModelBase; + void GoBack(); bool CanGoBack { get; } } diff --git a/src/ZonyLrcTools.Desktop/Services/NavigationService.cs b/src/ZonyLrcTools.Desktop/Services/NavigationService.cs index 57fa5e2..18a7c2b 100644 --- a/src/ZonyLrcTools.Desktop/Services/NavigationService.cs +++ b/src/ZonyLrcTools.Desktop/Services/NavigationService.cs @@ -22,13 +22,43 @@ public class NavigationService : INavigationService { var viewModel = _serviceProvider.GetRequiredService(); - if (_navigationStack.TryPeek(out var current)) + if (_navigationStack.TryPeek(out var current) && ReferenceEquals(current, viewModel)) { - _ = current.OnDeactivatedAsync(); + // Already showing this page; do not restart it. + return viewModel; + } + + if (_navigationStack.TryPeek(out current)) + { + _ = SafeDeactivateAsync(current); } _navigationStack.Push(viewModel); - _ = viewModel.OnActivatedAsync(); + _ = SafeActivateAsync(viewModel); + + NavigationChanged?.Invoke(this, viewModel); + return viewModel; + } + + public TViewModel NavigateRoot() where TViewModel : ViewModelBase + { + var viewModel = _serviceProvider.GetRequiredService(); + + if (_navigationStack.Count == 1 && ReferenceEquals(_navigationStack.Peek(), viewModel)) + { + return viewModel; + } + + while (_navigationStack.TryPop(out var previous)) + { + if (!ReferenceEquals(previous, viewModel)) + { + _ = SafeDeactivateAsync(previous); + } + } + + _navigationStack.Push(viewModel); + _ = SafeActivateAsync(viewModel); NavigationChanged?.Invoke(this, viewModel); return viewModel; @@ -39,12 +69,40 @@ public class NavigationService : INavigationService if (!CanGoBack) return; var current = _navigationStack.Pop(); - _ = current.OnDeactivatedAsync(); + _ = SafeDeactivateAsync(current); if (_navigationStack.TryPeek(out var previous)) { - _ = previous.OnActivatedAsync(); + _ = SafeActivateAsync(previous); NavigationChanged?.Invoke(this, previous); } } + + /// + /// Page lifecycle hooks are fire-and-forget from the caller's perspective; an exception thrown + /// inside one must not tear down the navigation call that triggered it. + /// + private static async Task SafeActivateAsync(ViewModelBase viewModel) + { + try + { + await viewModel.OnActivatedAsync().ConfigureAwait(false); + } + catch (Exception) + { + // A failing OnActivated must not crash navigation. + } + } + + private static async Task SafeDeactivateAsync(ViewModelBase viewModel) + { + try + { + await viewModel.OnDeactivatedAsync().ConfigureAwait(false); + } + catch (Exception) + { + // A failing OnDeactivated must not crash navigation. + } + } } diff --git a/src/ZonyLrcTools.Desktop/Services/ServiceCollectionExtensions.cs b/src/ZonyLrcTools.Desktop/Services/ServiceCollectionExtensions.cs index 7f42578..77fadb0 100644 --- a/src/ZonyLrcTools.Desktop/Services/ServiceCollectionExtensions.cs +++ b/src/ZonyLrcTools.Desktop/Services/ServiceCollectionExtensions.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.DependencyInjection; using ZonyLrcTools.Common.Infrastructure.DependencyInject; using ZonyLrcTools.Common.Infrastructure.Logging; using ZonyLrcTools.Common.Infrastructure.Network; +using ZonyLrcTools.Desktop.Infrastructure.Configuration; using ZonyLrcTools.Desktop.Infrastructure.Localization; using ZonyLrcTools.Desktop.ViewModels; @@ -20,7 +21,10 @@ public static class ServiceCollectionExtensions services.BeginAutoDependencyInject(); // Configure Common services - services.ConfigureConfiguration(); + // ConfigureConfiguration() from Common always reads config.yaml from the executable + // folder, which breaks portable installs and read-only install locations. The desktop + // app resolves a writable location first and binds from there instead. + services.ConfigureDesktopConfiguration(); services.ConfigureLocalization(); services.ConfigureToolService(); @@ -39,11 +43,18 @@ public static class ServiceCollectionExtensions services.AddSingleton(); services.AddSingleton(); + // Stores the NetEase login cookie between launches so the QR dialog is a first-run event. + services.AddSingleton(); + + // Remembers a manually chosen KuGou database path (machine state, not a user preference). + services.AddSingleton(); + // Register ViewModels (Singleton to preserve state across navigation) services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); return services; diff --git a/src/ZonyLrcTools.Desktop/ViewModels/MainWindowViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/MainWindowViewModel.cs index 479dec8..53c6f52 100644 --- a/src/ZonyLrcTools.Desktop/ViewModels/MainWindowViewModel.cs +++ b/src/ZonyLrcTools.Desktop/ViewModels/MainWindowViewModel.cs @@ -9,6 +9,7 @@ public partial class MainWindowViewModel : ViewModelBase { private readonly IThemeService _themeService; private readonly IUILocalizationService _localization; + private readonly INavigationService _navigation; [ObservableProperty] private ViewModelBase? _currentPage; @@ -27,6 +28,7 @@ public partial class MainWindowViewModel : ViewModelBase public string NavHome => _localization["Nav_Home"]; public string NavLyricsDownload => _localization["Nav_LyricsDownload"]; public string NavAlbumDownload => _localization["Nav_AlbumDownload"]; + public string NavDecrypt => _localization["Nav_Decrypt"]; public string NavSettings => _localization["Nav_Settings"]; public string HomeDescription => _localization["Home_Description"]; @@ -37,25 +39,87 @@ public partial class MainWindowViewModel : ViewModelBase public MainWindowViewModel( IThemeService themeService, IUILocalizationService localization, - HomeViewModel homeViewModel) + INavigationService navigation) { _themeService = themeService; _localization = localization; + _navigation = navigation; // Subscribe to language changes _localization.LanguageChanged += OnLanguageChanged; - // Set initial page - CurrentPage = homeViewModel; - SelectedNavigationIndex = 0; + // The navigation service is the single owner of "which page is showing". + _navigation.NavigationChanged += OnNavigationChanged; + + NavigateToIndex(0); } + // Guards against the re-entrant loop "index changed -> navigate -> navigation changed -> index changed". + private bool _isSyncingNavigation; + + partial void OnSelectedNavigationIndexChanged(int value) + { + if (_isSyncingNavigation) + { + return; + } + + NavigateToIndex(value); + } + + private void NavigateToIndex(int index) + { + // NavigateRoot keeps the stack depth at one: sidebar switching is not a back-navigable + // action, so clicking around must not grow history. + CurrentPage = index switch + { + 1 => _navigation.NavigateRoot(), + 2 => _navigation.NavigateRoot(), + 3 => _navigation.NavigateRoot(), + 4 => _navigation.NavigateRoot(), + _ => _navigation.NavigateRoot() + }; + } + + private void OnNavigationChanged(object? sender, ViewModelBase viewModel) + { + CurrentPage = viewModel; + + // The home page quick actions navigate directly, so the sidebar has to follow them. + var index = IndexOf(viewModel); + if (index < 0 || index == SelectedNavigationIndex) + { + return; + } + + _isSyncingNavigation = true; + try + { + SelectedNavigationIndex = index; + } + finally + { + _isSyncingNavigation = false; + } + } + + private static int IndexOf(ViewModelBase viewModel) => viewModel switch + { + LyricsDownloadViewModel => 1, + AlbumDownloadViewModel => 2, + DecryptViewModel => 3, + SettingsViewModel => 4, + HomeViewModel => 0, + _ => -1 + }; + private void OnLanguageChanged(object? sender, EventArgs e) { // Notify all localized properties have changed OnPropertyChanged(nameof(NavHome)); OnPropertyChanged(nameof(NavLyricsDownload)); OnPropertyChanged(nameof(NavAlbumDownload)); + OnPropertyChanged(nameof(NavDecrypt)); OnPropertyChanged(nameof(NavSettings)); OnPropertyChanged(nameof(HomeDescription)); OnPropertyChanged(nameof(ThemeButtonText)); diff --git a/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml b/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml index ee46002..f9db75d 100644 --- a/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml +++ b/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml @@ -92,8 +92,7 @@ + Margin="0,8,0,0"> + + + + + + + + + + diff --git a/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml.cs b/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml.cs index 942028f..b7fc324 100644 --- a/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml.cs +++ b/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml.cs @@ -1,6 +1,4 @@ using Avalonia.Controls; -using Microsoft.Extensions.DependencyInjection; -using ZonyLrcTools.Desktop.ViewModels; namespace ZonyLrcTools.Desktop.Views; @@ -10,29 +8,4 @@ public partial class MainWindow : Window { InitializeComponent(); } - - private void OnNavigationSelectionChanged(object? sender, SelectionChangedEventArgs e) - { - if (DataContext is not MainWindowViewModel viewModel) return; - if (sender is not ListBox listBox) return; - - var services = App.Services; - if (services == null) return; - - switch (listBox.SelectedIndex) - { - case 0: - viewModel.CurrentPage = services.GetRequiredService(); - break; - case 1: - viewModel.CurrentPage = services.GetRequiredService(); - break; - case 2: - viewModel.CurrentPage = services.GetRequiredService(); - break; - case 3: - viewModel.CurrentPage = services.GetRequiredService(); - break; - } - } }