using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Interactivity; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using QuiverLauncher.Models; using QuiverLauncher.Services; using QuiverLauncher.Services.Mods; using QuiverLauncher.Services.Mods.Providers.GameBanana; using QuiverLauncher.Services.Mods.Providers.Thunderstore; using System.Diagnostics; using System.IO; namespace QuiverLauncher; public partial class MainView { private bool _isModsOverlayOpen; private bool _isModDetailsOpen; private GameInfo? _modsGame; private ModListItem? _modDetailsItem; private string _modDetailsTab = "Details"; private string? _modDetailsReadmeMarkdown; private string? _modDetailsChangelogMarkdown; private bool _modDetailsReadmeLoaded; private bool _modDetailsChangelogLoaded; private int _modDetailsGamepadFocusIndex = -1; private List _modsCatalog = []; private readonly Dictionary _modsKnownPackages = new(StringComparer.OrdinalIgnoreCase); private readonly HashSet _modsOrphanEnrichAttempted = new(StringComparer.OrdinalIgnoreCase); private List _modsAllItems = []; private string _modsTab = "Browse"; private string? _modsSourceFilterKey; // null = All private string _modsSearchText = string.Empty; private string _modsSortBy = ModListSorter.InstalledFirst; private bool _modsIncludeNsfw; private ModBrowseSession? _modsBrowseSession; private bool _modsUsesPagedBrowse; private bool _modsIsLoadingMore; private bool _modsListIsLoading; private CancellationTokenSource? _modsBackgroundLoadCts; private CancellationTokenSource? _modsSearchDebounceCts; private ModInstallService? _modInstallService; private ModCatalogLoader? _modCatalogLoader; private int _modsGamepadToolbarIndex = -1; private int _modsGamepadFilterIndex = -1; private int _modsGamepadSourceFilterIndex = -1; private int _modsGamepadListIndex = -1; private int _modsGamepadRowActionIndex = -1; private ModInstallService ModInstaller => _modInstallService ??= new ModInstallService(_gameManager.ModProviderRegistry); private ModCatalogLoader ModCatalog => _modCatalogLoader ??= new ModCatalogLoader(_gameManager.ModProviderRegistry); private void OpenMods_Click(object? sender, RoutedEventArgs e) { var game = (sender as MenuItem)?.CommandParameter as GameInfo ?? (sender as Control)?.DataContext as GameInfo; if (game == null || !game.CanOpenMods) return; _ = OpenModsOverlayAsync(game); } private async Task OpenModsOverlayAsync(GameInfo game) { _modsGame = game; _isModsOverlayOpen = true; _isAppUpdatesReviewOpen = false; _mainViewMode = MainViewMode.Library; _modsTab = "Browse"; _modsSourceFilterKey = null; _modsSearchText = string.Empty; _modsBrowseSession = null; _modsUsesPagedBrowse = false; _modsCatalog = []; _modsKnownPackages.Clear(); _modsOrphanEnrichAttempted.Clear(); _modsIncludeNsfw = _settings.ModsIncludeNsfw; if (ModsSearchTextBox != null) ModsSearchTextBox.Text = string.Empty; ApplyModsSortSelection(_settings.ModsSortBy); UpdateModsTabButtons(); BuildModsSourceFilterButtons(); ResetGamepadNavigationIndices(); UpdateMainViewUi(); if (ModsHeaderText != null) ModsHeaderText.Text = $"Mods — {game.Name}"; SetModsStatus(string.Empty); await RefreshModsCatalogAsync(forceRefresh: false).ConfigureAwait(true); if (IsGamepadFocusActive) SelectInitialModsGamepadItem(); else ClearGamepadFocus(); } private void CloseModsOverlay() { if (_isModDetailsOpen) CloseModDetails(); _isModsOverlayOpen = false; _modsGame = null; _modsCatalog = []; _modsKnownPackages.Clear(); _modsOrphanEnrichAttempted.Clear(); _modsAllItems = []; _modsBrowseSession = null; _modsUsesPagedBrowse = false; _modsListIsLoading = false; _modsSearchDebounceCts?.Cancel(); _modsSearchDebounceCts = null; _modsBackgroundLoadCts?.Cancel(); _modsBackgroundLoadCts = null; ModListRows.Clear(); ClearModsGamepadFocus(); UpdateMainViewUi(); if (_gamepadNavigation.ActiveZone is GamepadNavigationZone.ModsOverlayToolbar or GamepadNavigationZone.ModsOverlayFilters or GamepadNavigationZone.ModsOverlaySourceFilters or GamepadNavigationZone.ModsOverlayList or GamepadNavigationZone.ModsOverlayRowActions) { _gamepadNavigation.ActiveZone = GamepadNavigationZone.Library; if (IsGamepadFocusActive) SelectInitialLibraryGamepadItem(); } OnPropertyChanged(nameof(GamepadHintsVisible)); } private void ModsClose_Click(object? sender, RoutedEventArgs e) => CloseModsOverlay(); private async void ModsRefresh_Click(object? sender, RoutedEventArgs e) => await RefreshModsCatalogAsync(forceRefresh: true); private async void ModsUpdateAll_Click(object? sender, RoutedEventArgs e) => await UpdateAllVisibleModsAsync(); private void ModsOpenFolder_Click(object? sender, RoutedEventArgs e) { if (_modsGame == null) return; try { var installRoot = _modsGame.GetInstallPath(_gameManager.GamesFolder); var modsPath = GameModsConfig.NormalizePath(_modsGame.ModsPath); if (string.IsNullOrWhiteSpace(installRoot) || modsPath.Length == 0) { _ = ShowMessageBoxAsync("Mods folder is not configured for this app.", "Mods"); return; } var modsDir = ModInstaller.GetModsDirectory(installRoot, modsPath); Directory.CreateDirectory(modsDir); OpenUrl(modsDir); } catch (Exception ex) { _ = ShowMessageBoxAsync($"Failed to open mod folder: {ex.Message}", "Mods"); } } private void ModsTabFilter_Click(object? sender, RoutedEventArgs e) { if (sender is not Button button || button.Tag is not string tab) return; _modsTab = tab; UpdateModsTabButtons(); // Orphan install inclusion depends on Browse+search vs Installed — rebuild rows. SyncModListItemsFromCatalog(); ApplyModsFiltersToUi(); } private void ModsSearch_TextChanged(object? sender, TextChangedEventArgs e) { _modsSearchText = ModsSearchTextBox?.Text?.Trim() ?? string.Empty; _ = DebouncedModsSearchAsync(); } private async Task DebouncedModsSearchAsync() { _modsSearchDebounceCts?.Cancel(); var cts = new CancellationTokenSource(); _modsSearchDebounceCts = cts; try { await Task.Delay(300, cts.Token).ConfigureAwait(true); if (_modsGame == null || cts.IsCancellationRequested) return; if (string.IsNullOrWhiteSpace(_modsSearchText)) { if (_modsBrowseSession?.IsSearch == true) await RefreshModsCatalogAsync(forceRefresh: false).ConfigureAwait(true); else ApplyModsFiltersToUi(); return; } if (string.Equals(_modsTab, "Installed", StringComparison.OrdinalIgnoreCase) || !ModCatalog.HasRemoteSearchSources(_modsGame.ModsSources)) { ApplyModsFiltersToUi(); return; } await RunRemoteModsSearchAsync(_modsSearchText, cts.Token).ConfigureAwait(true); } catch (OperationCanceledException) { // Newer search keystroke or overlay closed. } } private async Task RunRemoteModsSearchAsync( string query, CancellationToken cancellationToken, bool manageLoading = true) { if (_modsGame == null) return; if (manageLoading) SetModsListLoading(true, "Searching…"); else SetModsListLoadingCaption("Searching…"); try { var options = CurrentModsListOptions(); _modsBrowseSession = await ModCatalog .LoadSearchSessionAsync( _modsGame.ModsSources, _modsSourceFilterKey, query, ModCatalogLoader.DefaultPageSize, options, cancellationToken) .ConfigureAwait(true); if (cancellationToken.IsCancellationRequested) return; _modsUsesPagedBrowse = true; SetModsCatalog(_modsBrowseSession.Packages); SyncModListItemsFromCatalog(); ApplyModsFiltersToUi(); SetModsStatus(FormatModsLoadedStatus()); } catch (OperationCanceledException) { throw; } catch (Exception ex) { SetModsStatus($"Search failed: {ex.Message}"); } finally { if (manageLoading) SetModsListLoading(false); } } private ModListOptions CurrentModsListOptions() => new() { IncludeNsfw = _modsIncludeNsfw, SortMode = _modsSortBy, }; private async void ModsSortByComboBox_SelectionChanged(object? sender, SelectionChangedEventArgs e) { if (ModsSortByComboBox?.SelectedItem is not ComboBoxItem item || item.Tag is not string sortMode) return; var normalized = ModListSorter.Normalize(sortMode); if (string.Equals(_modsSortBy, normalized, StringComparison.OrdinalIgnoreCase)) return; _modsSortBy = normalized; _settings.ModsSortBy = normalized; AppSettings.Save(_settings); if (ModListSorter.IsRemoteSort(normalized)) await RefreshModsCatalogAsync(forceRefresh: false).ConfigureAwait(true); else ApplyModsFiltersToUi(); } private void ApplyModsSortSelection(string? sortBy) { _modsSortBy = ModListSorter.Normalize(sortBy); _settings.ModsSortBy = _modsSortBy; if (ModsSortByComboBox == null) return; foreach (var entry in ModsSortByComboBox.Items) { if (entry is ComboBoxItem item && item.Tag is string tag && string.Equals(tag, _modsSortBy, StringComparison.OrdinalIgnoreCase)) { ModsSortByComboBox.SelectedItem = item; return; } } if (ModsSortByComboBox.Items.Count > 0) ModsSortByComboBox.SelectedIndex = 0; } private async void ModsSourceFilter_Click(object? sender, RoutedEventArgs e) { if (sender is not Button button) return; var tag = button.Tag as string; if (tag is "nsfw") { _modsIncludeNsfw = !_modsIncludeNsfw; _settings.ModsIncludeNsfw = _modsIncludeNsfw; AppSettings.Save(_settings); UpdateModsSourceFilterButtons(); await RefreshModsCatalogAsync(forceRefresh: false).ConfigureAwait(true); return; } _modsSourceFilterKey = tag; // null tag = All if (tag is { Length: 0 }) _modsSourceFilterKey = null; UpdateModsSourceFilterButtons(); // Source filter changes reset GameBanana paging. await RefreshModsCatalogAsync(forceRefresh: false).ConfigureAwait(true); } private async void ModsListScrollViewer_ScrollChanged(object? sender, ScrollChangedEventArgs e) { if (!CanStartLoadMoreMods() || !IsModsListNearBottomForPrefetch()) return; await LoadMoreModsAsync().ConfigureAwait(true); } private bool CanStartLoadMoreMods() => _modsGame != null && _modsUsesPagedBrowse && _modsBrowseSession?.CanLoadMore == true && !_modsIsLoadingMore; /// /// True when the mods list is scrolled near the bottom, or content does not overflow the /// viewport (so mouse users can still page when the last incomplete row fills the view). /// private bool IsModsListNearBottomForPrefetch() { if (ModsListScrollViewer == null) return true; var extent = ModsListScrollViewer.Extent.Height; var viewport = ModsListScrollViewer.Viewport.Height; var offset = ModsListScrollViewer.Offset.Y; if (extent <= viewport) return true; return offset + viewport >= extent - 120; } private bool ShouldPrefetchMoreModsForGamepad(int focusedIndex) => CanStartLoadMoreMods() && ModListRows.Count > 0 && (focusedIndex >= Math.Max(0, ModListRows.Count - 6) || IsModsListNearBottomForPrefetch()); private async void ModRowInstall_Click(object? sender, RoutedEventArgs e) { if (GetModListItem(sender) is not { } item) return; await InstallModAsync(item, updateInstalledFilesOnly: false); } private async void ModRowUpdate_Click(object? sender, RoutedEventArgs e) { if (GetModListItem(sender) is not { } item) return; await InstallModAsync(item, updateInstalledFilesOnly: true); } private async void ModRowUninstall_Click(object? sender, RoutedEventArgs e) { if (GetModListItem(sender) is not { } item) return; await UninstallModAsync(item); } private void ModRowOpenPage_Click(object? sender, RoutedEventArgs e) { if (GetModListItem(sender) is not { } item) return; var url = item.Package.PackagePageUrl; if (string.IsNullOrWhiteSpace(url)) return; try { UrlLauncher.Open(url); } catch (Exception ex) { _ = ShowMessageBoxAsync($"Could not open page: {ex.Message}", "Mods"); } } private static ModListItem? GetModListItem(object? sender) { if (sender is Button button && button.CommandParameter is ModListItem fromCommand) return fromCommand; if (sender is MenuItem menuItem && menuItem.CommandParameter is ModListItem fromMenu) return fromMenu; if (sender is Control control && control.DataContext is ModListItem fromContext) return fromContext; return null; } private async Task RefreshModsCatalogAsync(bool forceRefresh) { if (_modsGame == null) return; SetModsListLoading(true, forceRefresh ? "Refreshing…" : "Loading mods…"); try { _modsBackgroundLoadCts?.Cancel(); _modsBackgroundLoadCts = null; _modsOrphanEnrichAttempted.Clear(); var options = CurrentModsListOptions(); _modsUsesPagedBrowse = ModCatalog.HasPagedSources(_modsGame.ModsSources); // If the user has an active search query, re-run remote search instead of browse. if (!string.IsNullOrWhiteSpace(_modsSearchText) && !string.Equals(_modsTab, "Installed", StringComparison.OrdinalIgnoreCase) && ModCatalog.HasRemoteSearchSources(_modsGame.ModsSources)) { await RunRemoteModsSearchAsync( _modsSearchText, CancellationToken.None, manageLoading: false).ConfigureAwait(true); await RefreshModUpdateFlagsForGameAsync(_modsGame).ConfigureAwait(true); return; } if (_modsUsesPagedBrowse) { _modsBrowseSession = await ModCatalog .LoadBrowseSessionAsync( _modsGame.ModsSources, _modsSourceFilterKey, forceRefresh, ModCatalogLoader.DefaultPageSize, options) .ConfigureAwait(true); SetModsCatalog(_modsBrowseSession.Packages); } else { _modsBrowseSession = null; SetModsCatalog(await ModCatalog .LoadAllPackagesAsync(_modsGame.ModsSources, forceRefresh, options) .ConfigureAwait(true)); } SyncModListItemsFromCatalog(); ApplyModsFiltersToUi(); await RefreshModUpdateFlagsForGameAsync(_modsGame).ConfigureAwait(true); SetModsStatus(FormatModsLoadedStatus()); } catch (Exception ex) { SetModsStatus($"Failed to load mods: {ex.Message}"); } finally { SetModsListLoading(false); } } private async Task LoadMoreModsAsync() { if (!CanStartLoadMoreMods()) return; await LoadMoreModsPageAsync().ConfigureAwait(true); // After each page, keep fetching while still parked at the end (or content still fits). // ScrollChanged during _modsIsLoadingMore is ignored, so without this recheck the last // incomplete row can stall with CanLoadMore still true. while (CanStartLoadMoreMods() && IsModsListNearBottomForPrefetch()) await LoadMoreModsPageAsync().ConfigureAwait(true); } private async Task LoadMoreModsPageAsync() { if (!CanStartLoadMoreMods() || _modsBrowseSession == null || _modsGame == null) return; _modsIsLoadingMore = true; SetModsStatus("Loading more…"); try { var options = CurrentModsListOptions(); _modsBrowseSession = _modsBrowseSession.IsSearch ? await ModCatalog .LoadMoreSearchSessionAsync(_modsBrowseSession, ModCatalogLoader.DefaultPageSize, options) .ConfigureAwait(true) : await ModCatalog .LoadMoreBrowseSessionAsync(_modsBrowseSession, ModCatalogLoader.DefaultPageSize, options) .ConfigureAwait(true); SetModsCatalog(_modsBrowseSession.Packages); SyncModListItemsFromCatalog(); ApplyModsFiltersToUi(); SetModsStatus(FormatModsLoadedStatus()); } catch (Exception ex) { SetModsStatus($"Failed to load more mods: {ex.Message}"); } finally { _modsIsLoadingMore = false; } } private string FormatModsLoadedStatus() => FormatModsLoadedStatus( _modsCatalog.Count, _modsBrowseSession?.IsSearch == true, _modsBrowseSession?.CanLoadMore == true, _modsBrowseSession?.TotalCountHint); /// /// Browse/search status. When paging and a TotalCountHint is available, shows "N of M" /// so gaps between API totals and catalog size are visible while debugging. /// internal static string FormatModsLoadedStatus( int loaded, bool isSearch, bool canLoadMore, int? totalCountHint) { if (isSearch) { if (canLoadMore && totalCountHint is int searchTotal && searchTotal > loaded) return $"{loaded} of {searchTotal} search results"; if (canLoadMore) return $"{loaded} search results (more available)"; return $"{loaded} search results"; } if (canLoadMore && totalCountHint is int total && total > loaded) return $"{loaded} of {total} mods loaded"; if (canLoadMore) return $"{loaded} mods loaded (more available)"; return $"{loaded} mods loaded"; } /// /// True when the list-area loading panel should show (catalog load/search and no rows yet). /// internal static bool ShouldShowModsListLoading(bool isLoading, int rowCount) => isLoading && rowCount == 0; private void SetModsListLoading(bool isLoading, string? caption = null) { _modsListIsLoading = isLoading; SetModsListLoadingCaption(caption); UpdateModsListPlaceholder(); } private void SetModsListLoadingCaption(string? caption) { if (caption != null && ModsListLoadingText != null) ModsListLoadingText.Text = caption; } private void UpdateModsListPlaceholder() { var showLoading = ShouldShowModsListLoading(_modsListIsLoading, ModListRows.Count); if (ModsListLoadingPanel != null) ModsListLoadingPanel.IsVisible = showLoading; if (ModsEmptyText != null) ModsEmptyText.IsVisible = !showLoading && ModListRows.Count == 0; } private void SyncModListItemsFromCatalog() { if (_modsGame == null) return; var installRoot = _modsGame.GetInstallPath(_gameManager.GamesFolder); var installedDoc = string.IsNullOrWhiteSpace(installRoot) || !Directory.Exists(installRoot) ? new InstalledModsDocument() : ModInstaller.LoadInstalled(installRoot); // Remote search: API hits only (no sidecar stubs). Browse / Installed: include orphans, // enriched from packages seen earlier in this overlay session. var orphanMode = _modsBrowseSession?.IsSearch == true && !string.Equals(_modsTab, "Installed", StringComparison.OrdinalIgnoreCase) ? ModOrphanInstallMode.Exclude : ModOrphanInstallMode.Include; _modsAllItems = ModCatalogListBuilder .BuildItems( _modsCatalog, installedDoc, out var idsMigrated, orphanMode, _modsKnownPackages) .ToList(); // Persist Thunderstore UUID → Owner-Name Id migrations so future syncs stay Id-stable. if (idsMigrated && !string.IsNullOrWhiteSpace(installRoot) && Directory.Exists(installRoot)) new InstalledModsStore().Save(installRoot, installedDoc); ScheduleBareOrphanEnrichment(); } /// /// Fetches icon/description for installed cards that are still bare stubs (not on loaded pages /// and not in the session known cache). /// private void ScheduleBareOrphanEnrichment() { if (!_isModsOverlayOpen || _modsGame == null) return; var bare = _modsAllItems .Where(i => i.Status is ModInstallStatus.Installed or ModInstallStatus.UpdateAvailable) .Where(i => string.IsNullOrWhiteSpace(i.Package.IconUrl) && string.IsNullOrWhiteSpace(i.Package.Description)) .Where(i => !string.IsNullOrWhiteSpace(i.Package.Owner) && !string.IsNullOrWhiteSpace(i.Package.Name)) .Select(i => i.Package) .Where(p => { var key = ModCatalogListBuilder.PackageIdentityKey(p); return key != null && _modsOrphanEnrichAttempted.Add(key); }) .ToList(); if (bare.Count == 0) return; // Do not cancel in-flight enrich on load-more sync — only refresh/close reset the CTS. if (_modsBackgroundLoadCts == null || _modsBackgroundLoadCts.IsCancellationRequested) _modsBackgroundLoadCts = new CancellationTokenSource(); _ = EnrichBareOrphansAsync(bare, _modsBackgroundLoadCts.Token); } private async Task EnrichBareOrphansAsync( IReadOnlyList packages, CancellationToken cancellationToken) { const int maxConcurrency = 3; using var gate = new SemaphoreSlim(maxConcurrency); var enrichedCount = 0; var tasks = packages.Select(async package => { await gate.WaitAsync(cancellationToken).ConfigureAwait(false); try { if (cancellationToken.IsCancellationRequested || !_isModsOverlayOpen) return; if (!_gameManager.ModProviderRegistry.TryGet(package.ProviderId, out var provider)) return; ModPackage enriched = package; if (provider is ThunderstoreModProvider thunderstore) { enriched = await thunderstore .EnrichForInstallAsync(package, cancellationToken) .ConfigureAwait(false); } else if (provider is GameBananaModProvider gameBanana) { enriched = await gameBanana .EnrichWithFilesAsync(package, cancellationToken) .ConfigureAwait(false); } else { return; } if (string.IsNullOrWhiteSpace(enriched.IconUrl) && string.IsNullOrWhiteSpace(enriched.Description)) return; await Dispatcher.UIThread.InvokeAsync(() => { if (!_isModsOverlayOpen || cancellationToken.IsCancellationRequested) return; RememberModsCatalogPackages([enriched]); }); Interlocked.Increment(ref enrichedCount); } catch (OperationCanceledException) { // Overlay closed or refresh started. } catch (Exception ex) { Debug.WriteLine($"Failed to enrich installed mod {package.FullName}: {ex.Message}"); } finally { gate.Release(); } }); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) { return; } if (enrichedCount == 0 || cancellationToken.IsCancellationRequested || !_isModsOverlayOpen) return; await Dispatcher.UIThread.InvokeAsync(() => { if (!_isModsOverlayOpen || cancellationToken.IsCancellationRequested) return; SyncModListItemsFromCatalogWithoutEnrichSchedule(); ApplyModsFiltersToUi(); }); } /// Rebuilds list items without re-queuing orphan enrichment (avoids a loop after enrich). private void SyncModListItemsFromCatalogWithoutEnrichSchedule() { if (_modsGame == null) return; var installRoot = _modsGame.GetInstallPath(_gameManager.GamesFolder); var installedDoc = string.IsNullOrWhiteSpace(installRoot) || !Directory.Exists(installRoot) ? new InstalledModsDocument() : ModInstaller.LoadInstalled(installRoot); var orphanMode = _modsBrowseSession?.IsSearch == true && !string.Equals(_modsTab, "Installed", StringComparison.OrdinalIgnoreCase) ? ModOrphanInstallMode.Exclude : ModOrphanInstallMode.Include; _modsAllItems = ModCatalogListBuilder .BuildItems( _modsCatalog, installedDoc, out var idsMigrated, orphanMode, _modsKnownPackages) .ToList(); if (idsMigrated && !string.IsNullOrWhiteSpace(installRoot) && Directory.Exists(installRoot)) new InstalledModsStore().Save(installRoot, installedDoc); } private void RememberModsCatalogPackages(IEnumerable packages) { ModCatalogListBuilder.RememberPackages(_modsKnownPackages, packages); } private void SetModsCatalog(IReadOnlyList packages) { _modsCatalog = packages.ToList(); RememberModsCatalogPackages(_modsCatalog); } private static IReadOnlyList FindInstalledRecords( InstalledModsDocument doc, ModPackage package) => ModCatalogListBuilder.FindMatchingRecords(doc, package); private void ApplyModsFiltersToUi() { var restoreFocus = IsGamepadFocusActive && _gamepadNavigation.ActiveZone is GamepadNavigationZone.ModsOverlayList or GamepadNavigationZone.ModsOverlayRowActions; ModPackage? focusedPackage = null; var fallbackIndex = _modsGamepadListIndex; if (restoreFocus) { var focusedRow = ModListRows.FirstOrDefault(r => r.IsGamepadFocused); if (focusedRow != null) focusedPackage = focusedRow.Package; else if (fallbackIndex >= 0 && fallbackIndex < ModListRows.Count) focusedPackage = ModListRows[fallbackIndex].Package; } IEnumerable query = _modsAllItems; // Remote search already applied NSFW via the API where supported; still hide NSFW client-side // for GameBanana and for any residual listing rows. if (!_modsIncludeNsfw) query = query.Where(i => !i.Package.HasContentRating); if (!string.IsNullOrEmpty(_modsSourceFilterKey) && _modsBrowseSession?.IsSearch != true) query = query.Where(i => string.Equals($"{i.ProviderId}|{i.SourceKey}", _modsSourceFilterKey, StringComparison.OrdinalIgnoreCase)); if (string.Equals(_modsTab, "Installed", StringComparison.OrdinalIgnoreCase)) query = query.Where(i => i.Status is ModInstallStatus.Installed or ModInstallStatus.UpdateAvailable); // Local text filter only when not showing a remote search result set (or on Installed). var useLocalSearchFilter = !string.IsNullOrWhiteSpace(_modsSearchText) && (_modsBrowseSession?.IsSearch != true || string.Equals(_modsTab, "Installed", StringComparison.OrdinalIgnoreCase)); if (useLocalSearchFilter) { var term = _modsSearchText; query = query.Where(i => i.DisplayName.Contains(term, StringComparison.OrdinalIgnoreCase) || i.Owner.Contains(term, StringComparison.OrdinalIgnoreCase) || i.Description.Contains(term, StringComparison.OrdinalIgnoreCase) || i.Package.FullName.Contains(term, StringComparison.OrdinalIgnoreCase)); } var rows = ModListSorter.Sort(query, _modsSortBy); ModListRows.Clear(); foreach (var row in rows) ModListRows.Add(row); UpdateModsListPlaceholder(); if (ModsUpdateAllButton != null) ModsUpdateAllButton.IsEnabled = rows.Any(r => r.CanUpdate); if (!restoreFocus || ModListRows.Count == 0) return; var index = ModCatalogListBuilder.FindListIndexByPackage(ModListRows, focusedPackage, fallbackIndex); if (index >= 0) ApplyModsListSelection(index); } /// /// Updates install status on every catalog row from the sidecar (root plus dependencies) /// without rebuilding ModListItem instances. /// private void ApplyInstalledStateToAllItems() { if (_modsGame == null) return; var installRoot = _modsGame.GetInstallPath(_gameManager.GamesFolder); var installedDoc = string.IsNullOrWhiteSpace(installRoot) || !Directory.Exists(installRoot) ? new InstalledModsDocument() : ModInstaller.LoadInstalled(installRoot); ModCatalogListBuilder.ApplyInstalledState(_modsAllItems, installedDoc); } private void BuildModsSourceFilterButtons() { if (ModsSourceFilterPanel == null || _modsGame == null) return; ModsSourceFilterPanel.Children.Clear(); var allButton = CreateModsFilterButton("All", tag: ""); allButton.Classes.Set("selected", _modsSourceFilterKey == null); ModsSourceFilterPanel.Children.Add(allButton); var resolved = ModCatalog.ResolveSources(_modsGame.ModsSources); foreach (var (_, parsed, _) in resolved) { var tag = $"{parsed.ProviderId}|{parsed.SourceKey}"; var button = CreateModsFilterButton(parsed.DisplayLabel, tag); button.Classes.Set("selected", string.Equals(_modsSourceFilterKey, tag, StringComparison.OrdinalIgnoreCase)); ModsSourceFilterPanel.Children.Add(button); } var nsfwButton = CreateModsFilterButton("Include NSFW", tag: "nsfw"); nsfwButton.Classes.Set("selected", _modsIncludeNsfw); ModsSourceFilterPanel.Children.Add(nsfwButton); } private Button CreateModsFilterButton(string content, string tag) { var button = new Button { Classes = { "catalog-filter" }, Content = content, Tag = tag, FontSize = 11, Margin = new Thickness(0, 0, 6, 6), }; button.Click += ModsSourceFilter_Click; return button; } private void UpdateModsSourceFilterButtons() { if (ModsSourceFilterPanel == null) return; foreach (var child in ModsSourceFilterPanel.Children.OfType