commit 72e35002f704178c5341fcbd663d64bcf22cbfb5 Author: X4Lo Date: Fri Oct 30 13:36:27 2026 +0000 Initial Version diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..2553732 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,29 @@ +name: Bug report +description: Report a problem with Game Collections +labels: ['bug'] +body: + - type: input + attributes: + label: Extension version + description: Shown in Playnite under Add-ons → Extensions → Game Collections. + validations: + required: true + - type: input + attributes: + label: Playnite version + validations: + required: true + - type: textarea + attributes: + label: What happened? + description: What you did, what you expected, and what happened instead. + validations: + required: true + - type: textarea + attributes: + label: Logs + description: | + Attach `playnite.log` and `extensions.log`. In Playnite, open the main menu → About Playnite → "Open logs folder" + (or `%AppData%\Playnite` for an installed copy, the Playnite folder for a portable one). + validations: + required: true diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..0b1436d --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,32 @@ +name: Build + +on: + push: + branches: [main] + tags: ['v*'] + pull_request: + +permissions: + contents: write + +jobs: + build: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - name: Build + run: dotnet build source/GameCollections.sln -c Release + + - uses: actions/upload-artifact@v4 + with: + name: pext + path: dist/*.pext + + # Pushing a tag such as v1.0.1 publishes a GitHub release with the .pext attached. + - name: Publish release + if: startsWith(github.ref, 'refs/tags/v') + uses: softprops/action-gh-release@v2 + with: + files: dist/*.pext + generate_release_notes: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fb97901 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +# Build output +[Bb]in/ +[Oo]bj/ +dist/ +*.pext + +# Visual Studio / Rider +.vs/ +.idea/ +*.user +*.suo + +# NuGet +packages/ + +# OS +Thumbs.db +.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..7cbf8a7 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,8 @@ +# Changelog + +Every release must also be added to [manifests/installer_manifest.yaml](manifests/installer_manifest.yaml), +which is what Playnite reads to offer updates. + +## 1.0.0 – 2026-10-30 + +- Initial release. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9238b91 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 X4Lo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d7b3025 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +

+ Game Collections icon +

+ +

Game Collections for Playnite

+ +

+ Group your Playnite games into custom collections with a poster, description and rating. +

+ +

+ License: MIT + Playnite SDK 6.11 + Built with Claude Opus 5.5 +

+ +![Collections page](screenshots/collections-page.webp) + +## Features + +- **Add to Collection…** in every game's right-click menu, for one game or many. Search your collections, + tick or untick them, or type a new name and press Enter to create one on the spot. +- **Collections** in the sidebar: every collection in a grid or a list (your choice is remembered), with search + and create, edit and delete. +- **Collection pages** show the poster, description, rating and games. You can search, sort by name, release date, + last played, time played or date added, show installed games only, and Play/Install, Show in library or + Remove games. +- **Posters**: use your own image, or let the collection use its first game's cover. +- **Safe with your library and data**: + - Deleting a collection never touches its games. + - Games removed from Playnite are dropped from collections automatically. + - Saves are atomic and keep a backup. +- Works with light and dark themes, because it uses Playnite's theme styles throughout. + +| Collection page | Add to Collection | +|---|---| +| ![Collection page](screenshots/collection-details-page.webp) | ![Add to Collection dialog](screenshots/add-to-collection-dialog.webp) | + +## Installation + +- **From Playnite**: once it's listed, use *Add-ons → Browse → Generic* and search for "Game Collections". +- **Manually**: download the `.pext` file from the [latest release](https://github.com/X4Lo/GameCollections/releases/latest) + and open it. Playnite installs it and asks to restart. + +Requires a recent Playnite 10 release (extension SDK 6.11 or later), in Desktop mode. + +## Documentation + +- [User guide](docs/user-guide.md): how to use every feature, keyboard shortcuts, where data is stored, and known limitations. +- [Architecture and development](docs/architecture.md): repository layout, building, and how the code is organized. +- [Changelog](CHANGELOG.md) + +## Building + +``` +dotnet build source/GameCollections.sln -c Release +``` + +The installable package is written to `dist/`. See [docs/architecture.md](docs/architecture.md) for details. + +## Credits + +Developed by X4Lo with the help of **Claude Opus 5.5** (Anthropic), which wrote the code and documentation +from X4Lo's specification. + +## License + +[MIT](LICENSE) diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..c21a037 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,94 @@ +# Architecture and development + +## Repository layout + +``` +GameCollections/ +├─ source/ +│ ├─ GameCollections.sln +│ └─ GameCollections/ the extension project +│ ├─ GameCollectionsPlugin.cs entry point (GenericPlugin) +│ ├─ extension.yaml Playnite extension manifest +│ ├─ icon.png extension, menu and sidebar icon +│ ├─ Localization/en_US.xaml all user-visible strings (LOCGameCollections_*) +│ ├─ Models/ persisted data types +│ ├─ Services/ storage, business logic, dialogs, image loading +│ ├─ Settings/ ISettings implementation and settings view +│ ├─ ViewModels/ MVVM view models +│ └─ Views/ XAML views, shared styles, converters +├─ manifests/ +│ ├─ installer_manifest.yaml release list Playnite reads for installs and updates +│ └─ X4Lo_GameCollections.yaml entry for the Playnite add-on database +├─ docs/ this documentation +├─ screenshots/ images for the README and add-on database +├─ .github/ CI build/release workflow, issue template +└─ dist/ build output: the .pext package (git-ignored) +``` + +## Building + +Requirements: the .NET SDK (any version that supports SDK-style projects; 6.0 or later recommended). +The .NET Framework 4.6.2 reference assemblies are restored from NuGet automatically, so no targeting pack is needed. + +``` +dotnet build source/GameCollections.sln -c Release +``` + +This produces `source/GameCollections/bin/Release/` and the installable package +`dist/GameCollections_3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54_.pext`. + +To try a build in Playnite, open the `.pext` file (Playnite installs it after a restart), or add +`source/GameCollections/bin/Debug` under *Settings → For developers → Custom extension folders*. + +## Playnite conventions followed + +- `Playnite.SDK` is referenced with `ExcludeAssets="runtime"`, so the SDK DLL is never shipped – Playnite provides it. +- All strings live in `Localization/en_US.xaml` and are read with `ResourceProvider.GetString`; Playnite loads the + file matching the user's language, falling back to `en_US`. +- Views only use Playnite theme resources (`TextBrush`, `NormalBrush`, `FontIcoFont`, …) so every theme, + light or dark, styles them. +- Dialogs are created with `PlayniteApi.Dialogs.CreateWindow` so they get the theme's window style. +- Logging goes through `LogManager.GetLogger()` into Playnite's `extensions.log`. +- Data lives in `GetPluginUserDataPath()`; settings use `LoadPluginSettings` / `SavePluginSettings`. +- Database events are unsubscribed in `OnApplicationStopped`, and UI updates are marshalled to the UI dispatcher. + +## Main components + +| Component | Responsibility | +|-----------|----------------| +| `GameCollectionsPlugin` | Wires everything together; game menu item, sidebar item, settings; reacts to library changes. | +| `CollectionRepository` | Reads/writes `collections.json`. Atomic save (temp file + `File.Replace` with a `.bak`), recovery from the backup, data sanitising. | +| `PosterStorage` | Copies custom posters into `Posters\`, deletes them, cleans up orphans. | +| `CollectionManager` | All collection rules: validation, unique titles, create/update/delete, membership changes in one save, poster resolution, pruning deleted games. Raises `CollectionsChanged`. | +| `ImageLoader` | Asynchronous, downscaled (`DecodePixelWidth`), frozen, cached image decoding with limited concurrency. | +| `DialogService` | Hosts the Add to Collection and create/edit dialogs in Playnite windows. | +| `CollectionsRootViewModel` | Sidebar page navigation (home ↔ collection) and shared open/edit/delete actions. Lives for the whole session so view state is kept. | +| `CollectionsHomeViewModel` / `CollectionDetailsViewModel` | The Collections page and a collection's page. | +| `AddToCollectionViewModel` / `EditCollectionViewModel` | The two dialogs. | + +### Data model + +```json +{ + "SchemaVersion": 1, + "Collections": [ + { + "Id": "guid", + "Title": "Couch co-op", + "Description": "", + "Rating": 8.5, + "PosterFileName": "guid_ticks.png", + "GameIds": ["game guid", "..."], + "CreatedAt": "2026-10-30T12:00:00Z", + "ModifiedAt": "2026-10-30T12:00:00Z" + } + ] +} +``` + +Only game IDs are stored. Missing games are removed on startup and whenever Playnite deletes a game. + +### Performance + +Covers and posters are decoded at display size, off the UI thread, and cached. On a collection's page, +covers are only requested for tiles that are scrolled into view. diff --git a/docs/user-guide.md b/docs/user-guide.md new file mode 100644 index 0000000..7a5022c --- /dev/null +++ b/docs/user-guide.md @@ -0,0 +1,71 @@ +# User guide + +## Adding games to collections + +1. Select one or more games in the library, right-click, and choose **Add to Collection…**. +2. Type in the search box to filter your collections, then tick or untick them. + - With several games selected, a collection that contains only some of them shows a mixed (■) check. + Clicking it cycles through *remove from all → add to all → leave as is*. +3. If no collection matches what you typed, press **Enter** or click **Create "…"** to create one with that name. + It is ticked automatically. Names are unique, ignoring capitals and extra spaces. +4. Click **Save** (or press **Enter**) to apply. **Cancel** or **Esc** discards every change, including new collections. + +Keyboard: **↓/↑** move between the search box and the list, **Space** toggles the highlighted collection. + +## The Collections page + +Click **Collections** in the sidebar. The page keeps its state (open collection, search, sort) while Playnite is running. + +- **Search** filters by title. +- **Grid / List** toggle (top right) switches views; your choice is remembered between sessions. +- **New collection** opens the create dialog. +- Open a collection with a click (grid) or a double-click (list). +- Edit or delete from the right-click menu, the buttons on list rows, or the keyboard: + **Enter** opens, **F2** edits, **Delete** deletes (after confirmation). + +Deleting a collection never deletes or changes any games. + +## Creating and editing a collection + +| Field | Notes | +|-------------|-------| +| Title | Required, up to 100 characters, unique (case-insensitive). | +| Description | Optional, up to 2000 characters. | +| Rating | 0–10 in steps of 0.5, shown as `8.5/10`. | +| Poster | Optional PNG, JPG, BMP, GIF or TIFF. The image is copied into the extension's data, so moving the original later is fine. **Remove** goes back to the automatic poster. | + +When there's no custom poster, the cover of the first game in the collection is used; with no cover either, +a placeholder is shown. + +## A collection's page + +- Header with poster, title, rating, game count and description, plus **Edit**, **Select in library** and **Delete**. +- **Search** the collection's games by name. +- **Sort** by collection order (the order games were added), name, release date, last played, time played + or date added, ascending or descending. +- **Installed only** hides games that aren't installed (uninstalled games are dimmed otherwise). +- For each game (right-click, or keyboard): + - **Play** / **Install** – double-click or **Enter**. + - **Show in library** – selects the game in Playnite's library view. + - **Remove from collection** – **Delete**. Works on several selected games at once (Ctrl/Shift-click). + +## Where data is stored + +In Playnite's `ExtensionsData\3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54` folder: + +- `collections.json` – your collections. `collections.json.bak` holds the previous save. +- `Posters\` – copies of custom posters. +- `config.json` – extension settings. + +Back up this folder to back up your collections. If `collections.json` ever becomes unreadable, it is renamed to +`collections.unreadable-.json`, the backup is loaded instead, and Playnite shows a notification. + +## Known limitations + +These come from Playnite's extension API: + +- Extensions can't open a game's details page directly. **Show in library** selects the game and switches to + the library view, where its details appear. If a library filter hides the game, Playnite can't select it – + clear the filter and try again. +- Extensions can't embed Playnite's own library grid, so a collection's page uses its own game grid. +- The extension targets Desktop mode. Fullscreen mode doesn't show sidebar views or game context menus from extensions. diff --git a/manifests/X4Lo_GameCollections.yaml b/manifests/X4Lo_GameCollections.yaml new file mode 100644 index 0000000..d9bb3ff --- /dev/null +++ b/manifests/X4Lo_GameCollections.yaml @@ -0,0 +1,28 @@ +AddonId: GameCollections_3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54 +Type: Generic +Name: Game Collections +Author: X4Lo +ShortDescription: Group games into custom collections with a poster, description and rating. +InstallerManifestUrl: https://raw.githubusercontent.com/X4Lo/GameCollections/main/manifests/installer_manifest.yaml +SourceUrl: https://github.com/X4Lo/GameCollections +Description: |- + Organize your library into custom collections, such as "Couch co-op", "Backlog 2026" or "Best RPGs". + + - Right-click any game (or several) and choose "Add to Collection..." to tick existing collections or create a new one from the search box. + - Open "Collections" in the sidebar to browse every collection in a grid or a list, search them, and create, edit or delete them. + - Each collection has a title, description, 0-10 rating and poster. Without a custom poster, the first game's cover is used. + - A collection page lists its games with search, sorting, an "installed only" filter, and Play/Install, Show in library and Remove actions. + + Collections only reference games, so deleting a collection never touches your library. Games removed from Playnite are dropped from collections automatically. +Tags: ["Generic", "Library", "Organization", "Collections"] +Links: + GitHub: https://github.com/X4Lo/GameCollections + User Guide: https://github.com/X4Lo/GameCollections/blob/main/docs/user-guide.md +IconUrl: https://raw.githubusercontent.com/X4Lo/GameCollections/main/source/GameCollections/icon.png +Screenshots: + - Thumbnail: https://raw.githubusercontent.com/X4Lo/GameCollections/main/screenshots/collections-page_thumb.webp + Image: https://raw.githubusercontent.com/X4Lo/GameCollections/main/screenshots/collections-page.webp + - Thumbnail: https://raw.githubusercontent.com/X4Lo/GameCollections/main/screenshots/collection-details-page_thumb.webp + Image: https://raw.githubusercontent.com/X4Lo/GameCollections/main/screenshots/collection-details-page.webp + - Thumbnail: https://raw.githubusercontent.com/X4Lo/GameCollections/main/screenshots/add-to-collection-dialog_thumb.webp + Image: https://raw.githubusercontent.com/X4Lo/GameCollections/main/screenshots/add-to-collection-dialog.webp diff --git a/manifests/installer_manifest.yaml b/manifests/installer_manifest.yaml new file mode 100644 index 0000000..2b15b37 --- /dev/null +++ b/manifests/installer_manifest.yaml @@ -0,0 +1,8 @@ +AddonId: GameCollections_3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54 +Packages: + - Version: 1.0.0 + RequiredApiVersion: 6.11.0 + ReleaseDate: 2026-10-30 + PackageUrl: https://github.com/X4Lo/GameCollections/releases/download/v1.0.0/GameCollections_3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54_1_0_0.pext + Changelog: + - 'Initial release' diff --git a/screenshots/add-to-collection-dialog.webp b/screenshots/add-to-collection-dialog.webp new file mode 100644 index 0000000..5ffff38 Binary files /dev/null and b/screenshots/add-to-collection-dialog.webp differ diff --git a/screenshots/add-to-collection-dialog_thumb.webp b/screenshots/add-to-collection-dialog_thumb.webp new file mode 100644 index 0000000..c4e6128 Binary files /dev/null and b/screenshots/add-to-collection-dialog_thumb.webp differ diff --git a/screenshots/collection-details-page.webp b/screenshots/collection-details-page.webp new file mode 100644 index 0000000..5d7f1eb Binary files /dev/null and b/screenshots/collection-details-page.webp differ diff --git a/screenshots/collection-details-page_thumb.webp b/screenshots/collection-details-page_thumb.webp new file mode 100644 index 0000000..c54de76 Binary files /dev/null and b/screenshots/collection-details-page_thumb.webp differ diff --git a/screenshots/collections-page.webp b/screenshots/collections-page.webp new file mode 100644 index 0000000..a3a836b Binary files /dev/null and b/screenshots/collections-page.webp differ diff --git a/screenshots/collections-page_thumb.webp b/screenshots/collections-page_thumb.webp new file mode 100644 index 0000000..2297dff Binary files /dev/null and b/screenshots/collections-page_thumb.webp differ diff --git a/source/GameCollections.sln b/source/GameCollections.sln new file mode 100644 index 0000000..d8530a8 --- /dev/null +++ b/source/GameCollections.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCollections", "GameCollections\GameCollections.csproj", "{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|x64.ActiveCfg = Debug|Any CPU + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|x64.Build.0 = Debug|Any CPU + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|x86.ActiveCfg = Debug|Any CPU + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|x86.Build.0 = Debug|Any CPU + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|Any CPU.Build.0 = Release|Any CPU + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|x64.ActiveCfg = Release|Any CPU + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|x64.Build.0 = Release|Any CPU + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|x86.ActiveCfg = Release|Any CPU + {9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/source/GameCollections/GameCollections.csproj b/source/GameCollections/GameCollections.csproj new file mode 100644 index 0000000..c52c50b --- /dev/null +++ b/source/GameCollections/GameCollections.csproj @@ -0,0 +1,41 @@ + + + + net462 + true + Library + GameCollections + GameCollections + 7.3 + 1.0.0 + Game Collections + false + false + + + + + + + + + + + + + + + + + + + $(MSBuildProjectDirectory)\..\..\dist + $(PextDirectory)\GameCollections_3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54_$(Version.Replace('.', '_')).pext + + + + + + + diff --git a/source/GameCollections/GameCollectionsPlugin.cs b/source/GameCollections/GameCollectionsPlugin.cs new file mode 100644 index 0000000..cfd631c --- /dev/null +++ b/source/GameCollections/GameCollectionsPlugin.cs @@ -0,0 +1,182 @@ +using GameCollections.Services; +using GameCollections.Settings; +using GameCollections.ViewModels; +using GameCollections.Views; +using Playnite.SDK; +using Playnite.SDK.Events; +using Playnite.SDK.Models; +using Playnite.SDK.Plugins; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Windows.Controls; + +namespace GameCollections +{ + public class GameCollectionsPlugin : GenericPlugin + { + private static readonly ILogger logger = LogManager.GetLogger(); + + private readonly GameCollectionsSettingsViewModel settings; + private readonly CollectionManager manager; + private readonly DialogService dialogs; + private CollectionsRootViewModel rootViewModel; + + public override Guid Id { get; } = Guid.Parse("3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54"); + + public GameCollectionsPlugin(IPlayniteAPI api) : base(api) + { + settings = new GameCollectionsSettingsViewModel(this); + Properties = new GenericPluginProperties + { + HasSettings = true + }; + + var dataDirectory = GetPluginUserDataPath(); + manager = new CollectionManager( + api, + new CollectionRepository(dataDirectory), + new PosterStorage(Path.Combine(dataDirectory, "Posters"))); + dialogs = new DialogService(api, manager); + } + + public override void OnApplicationStarted(OnApplicationStartedEventArgs args) + { + // Loading happens here rather than in the constructor because the game database + // is only guaranteed to be available once Playnite has started. + try + { + var warning = manager.Load(); + if (warning != null) + { + PlayniteApi.Notifications.Add(new NotificationMessage("GameCollections_LoadWarning", warning, NotificationType.Error)); + } + + manager.RemoveMissingGames(); + manager.DeleteUnreferencedPosters(); + } + catch (Exception e) + { + logger.Error(e, "Failed to load collections."); + PlayniteApi.Notifications.Add(new NotificationMessage( + "GameCollections_LoadError", + Loc.Format("LOCGameCollections_ErrorLoadFailed", e.Message), + NotificationType.Error)); + } + + PlayniteApi.Database.Games.ItemCollectionChanged += Games_ItemCollectionChanged; + PlayniteApi.Database.Games.ItemUpdated += Games_ItemUpdated; + } + + public override void OnApplicationStopped(OnApplicationStoppedEventArgs args) + { + PlayniteApi.Database.Games.ItemCollectionChanged -= Games_ItemCollectionChanged; + PlayniteApi.Database.Games.ItemUpdated -= Games_ItemUpdated; + } + + public override IEnumerable GetGameMenuItems(GetGameMenuItemsArgs args) + { + yield return new GameMenuItem + { + Description = Loc.Get("LOCGameCollections_MenuAddToCollection"), + Icon = Path.Combine(GetPluginDirectory(), "icon.png"), + Action = menuArgs => + { + try + { + dialogs.ShowAddToCollection(menuArgs.Games); + } + catch (Exception e) + { + logger.Error(e, "Failed to open the Add to Collection dialog."); + PlayniteApi.Dialogs.ShowErrorMessage(e.Message, Loc.Get("LOCGameCollections_PluginName")); + } + } + }; + } + + public override IEnumerable GetSidebarItems() + { + yield return new SidebarItem + { + Title = Loc.Get("LOCGameCollections_SidebarTitle"), + Type = SiderbarItemType.View, + Icon = Path.Combine(GetPluginDirectory(), "icon.png"), + // A new view is built on every open, while the view model (current page, search, + // sort) persists so the user returns to where they left off. + Opened = () => + { + if (rootViewModel == null) + { + rootViewModel = new CollectionsRootViewModel(PlayniteApi, manager, dialogs, settings); + } + + return new CollectionsRootView { DataContext = rootViewModel }; + } + }; + } + + public override ISettings GetSettings(bool firstRunSettings) + { + return settings; + } + + public override UserControl GetSettingsView(bool firstRunSettings) + { + return new GameCollectionsSettingsView(); + } + + private void Games_ItemCollectionChanged(object sender, ItemCollectionChangedEventArgs e) + { + if (e.RemovedItems == null || e.RemovedItems.Count == 0) + { + return; + } + + var removedIds = e.RemovedItems.Select(g => g.Id).ToList(); + RunOnUiThread(() => manager.RemoveGamesFromAllCollections(removedIds)); + } + + private void Games_ItemUpdated(object sender, ItemUpdatedEventArgs e) + { + if (rootViewModel == null || e.UpdatedItems == null || e.UpdatedItems.Count == 0) + { + return; + } + + var updatedIds = new HashSet(e.UpdatedItems.Select(u => u.NewData.Id)); + RunOnUiThread(() => rootViewModel.OnGamesUpdated(updatedIds)); + } + + private void RunOnUiThread(Action action) + { + void SafeAction() + { + try + { + action(); + } + catch (Exception e) + { + logger.Error(e, "Failed to process library change."); + } + } + + var dispatcher = PlayniteApi.MainView.UIDispatcher; + if (dispatcher == null || dispatcher.CheckAccess()) + { + SafeAction(); + } + else + { + dispatcher.BeginInvoke((Action)SafeAction); + } + } + + private static string GetPluginDirectory() + { + return Path.GetDirectoryName(typeof(GameCollectionsPlugin).Assembly.Location); + } + } +} diff --git a/source/GameCollections/Localization/en_US.xaml b/source/GameCollections/Localization/en_US.xaml new file mode 100644 index 0000000..5ab7ffe --- /dev/null +++ b/source/GameCollections/Localization/en_US.xaml @@ -0,0 +1,92 @@ + + Game Collections + Collections + Add to Collection… + There are no settings for Game Collections yet. + + + Collections + Search collections + Create Collection + Switch to list view + Switch to grid view + No collections yet + Create a collection here, or right-click a game in your library and choose "Add to Collection". + No collections match "{0}". + Open + Edit + Delete + 1 collection + {0} collections + 1 game + {0} games + {0} of {1} games + Delete collection + Delete the collection "{0}"? The games in it will stay in your Playnite library. + Untitled collection + + + Collections + Edit + Delete + Select in library + Switch to the library and select every game in this collection + Search games + Sort by + Collection order + Name + Release date + Last played + Time played + Date added to library + Ascending + Descending + Installed only + Play + Install + Show in library + Remove from collection + This collection is empty + Right-click a game in your library and choose "Add to Collection" to add it here. + No games match the current search or filter. + + + Add to Collection + Choose the collections for "{0}" + Choose the collections for {0} selected games + Search or create a collection + Create collection "{0}" + New + You don't have any collections yet. Type a name above to create one. + Clear + + + Create Collection + Edit Collection + Title + Description + Rating + Choose poster… + Remove custom poster + Custom poster + Using the cover of the first game in the collection + No poster yet. The first game's cover will be used once games are added. + Save + Cancel + + + A title is required. + The title can be at most {0} characters long. + A collection named "{0}" already exists. + The collection no longer exists. + Unsupported image format. Use PNG, JPG, BMP, GIF or TIFF. + The selected poster file could not be found. + The selected file could not be read as an image. + The collection could not be saved: {0} + Game Collections could not save your collections: {0} + Game Collections could not load your collections: {0} + Game Collections could not read its data file and restored your collections from the most recent backup. + Game Collections could not read its data file. The unreadable file was kept at "{0}". + diff --git a/source/GameCollections/Models/GameCollection.cs b/source/GameCollections/Models/GameCollection.cs new file mode 100644 index 0000000..df0a2f3 --- /dev/null +++ b/source/GameCollections/Models/GameCollection.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; + +namespace GameCollections.Models +{ + /// + /// Persisted collection record. Games are referenced by their Playnite database IDs only; + /// no game metadata is duplicated here. + /// + public class GameCollection + { + public Guid Id { get; set; } + public string Title { get; set; } + public string Description { get; set; } + public double Rating { get; set; } + + /// + /// File name of the custom poster inside the plugin's poster folder, or null when none is assigned. + /// + public string PosterFileName { get; set; } + + public List GameIds { get; set; } = new List(); + public DateTime CreatedAt { get; set; } + public DateTime ModifiedAt { get; set; } + } + + /// + /// Root object of the collections data file. + /// + public class CollectionsDataFile + { + public int SchemaVersion { get; set; } + public List Collections { get; set; } = new List(); + } + + public enum PosterChange + { + Keep, + Replace, + Remove + } + + public enum CollectionsViewMode + { + Grid, + List + } +} diff --git a/source/GameCollections/Services/CollectionManager.cs b/source/GameCollections/Services/CollectionManager.cs new file mode 100644 index 0000000..502adde --- /dev/null +++ b/source/GameCollections/Services/CollectionManager.cs @@ -0,0 +1,474 @@ +using GameCollections.Models; +using Playnite.SDK; +using Playnite.SDK.Models; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace GameCollections.Services +{ + public class CollectionsChangedEventArgs : EventArgs + { + /// + /// IDs of the collections that were added, updated or removed. + /// + public IReadOnlyCollection ChangedIds { get; } + + public CollectionsChangedEventArgs(IReadOnlyCollection changedIds) + { + ChangedIds = changedIds; + } + } + + /// + /// Owns the in-memory collection list and every operation on it. Each mutation is persisted + /// immediately and announced through . + /// All members must be called on the UI thread. + /// + public class CollectionManager + { + public const int MaxTitleLength = 100; + public const int MaxDescriptionLength = 2000; + public const double MinRating = 0; + public const double MaxRating = 10; + + private static readonly ILogger logger = LogManager.GetLogger(); + private readonly IPlayniteAPI playniteApi; + private readonly CollectionRepository repository; + private readonly PosterStorage posterStorage; + private readonly List collections = new List(); + + public event EventHandler CollectionsChanged; + + public IReadOnlyList Collections => collections; + + public CollectionManager(IPlayniteAPI playniteApi, CollectionRepository repository, PosterStorage posterStorage) + { + this.playniteApi = playniteApi; + this.repository = repository; + this.posterStorage = posterStorage; + } + + /// + /// Loads collections from disk and returns a warning to show the user, or null. + /// + public string Load() + { + var result = repository.Load(); + collections.Clear(); + collections.AddRange(result.Collections); + return result.Warning; + } + + public GameCollection GetCollection(Guid id) + { + return collections.FirstOrDefault(c => c.Id == id); + } + + #region Validation + + public static string NormalizeTitle(string title) + { + return title?.Trim() ?? string.Empty; + } + + public static string NormalizeDescription(string description) + { + var trimmed = description?.Trim(); + if (string.IsNullOrEmpty(trimmed)) + { + return null; + } + + return trimmed.Length > MaxDescriptionLength ? trimmed.Substring(0, MaxDescriptionLength) : trimmed; + } + + public static double NormalizeRating(double rating) + { + if (double.IsNaN(rating) || double.IsInfinity(rating)) + { + return MinRating; + } + + return Math.Round(Math.Max(MinRating, Math.Min(MaxRating, rating)), 1, MidpointRounding.AwayFromZero); + } + + public static bool TitlesEqual(string first, string second) + { + return string.Equals(NormalizeTitle(first), NormalizeTitle(second), StringComparison.CurrentCultureIgnoreCase); + } + + public bool IsTitleTaken(string title, Guid? ignoredId = null) + { + return collections.Any(c => c.Id != ignoredId && TitlesEqual(c.Title, title)); + } + + /// + /// Returns a user-facing error message for an invalid title, or null when the title can be used. + /// + public string ValidateTitle(string title, Guid? ignoredId = null) + { + var normalized = NormalizeTitle(title); + if (normalized.Length == 0) + { + return Loc.Get("LOCGameCollections_ErrorTitleRequired"); + } + + if (normalized.Length > MaxTitleLength) + { + return Loc.Format("LOCGameCollections_ErrorTitleTooLong", MaxTitleLength); + } + + if (IsTitleTaken(normalized, ignoredId)) + { + return Loc.Format("LOCGameCollections_ErrorTitleDuplicate", normalized); + } + + return null; + } + + #endregion + + #region Collection operations + + public GameCollection CreateCollection(string title, string description, double rating, string posterSourcePath, IEnumerable gameIds) + { + var collection = BuildNewCollection(title, gameIds); + collection.Description = NormalizeDescription(description); + collection.Rating = NormalizeRating(rating); + if (!string.IsNullOrEmpty(posterSourcePath)) + { + collection.PosterFileName = posterStorage.Import(collection.Id, posterSourcePath); + } + + collections.Add(collection); + Persist(new[] { collection.Id }); + return collection; + } + + public void UpdateCollection(Guid id, string title, string description, double rating, PosterChange posterChange, string posterSourcePath) + { + var collection = GetCollection(id); + if (collection == null) + { + throw new InvalidOperationException(Loc.Get("LOCGameCollections_ErrorCollectionNotFound")); + } + + var error = ValidateTitle(title, id); + if (error != null) + { + throw new InvalidOperationException(error); + } + + // Import first: if copying the new poster fails, nothing has been changed yet. + string obsoletePoster = null; + var newPoster = collection.PosterFileName; + if (posterChange == PosterChange.Replace) + { + newPoster = posterStorage.Import(id, posterSourcePath); + obsoletePoster = collection.PosterFileName; + } + else if (posterChange == PosterChange.Remove) + { + newPoster = null; + obsoletePoster = collection.PosterFileName; + } + + collection.Title = NormalizeTitle(title); + collection.Description = NormalizeDescription(description); + collection.Rating = NormalizeRating(rating); + collection.PosterFileName = newPoster; + collection.ModifiedAt = DateTime.UtcNow; + + // The old poster is only deleted once the data file no longer references it. + if (Persist(new[] { id }) && obsoletePoster != null) + { + posterStorage.Delete(obsoletePoster); + } + } + + /// + /// Deletes the collection record only. Games referenced by it are not touched. + /// + public bool DeleteCollection(Guid id) + { + var collection = GetCollection(id); + if (collection == null) + { + return false; + } + + collections.Remove(collection); + if (Persist(new[] { id }) && collection.PosterFileName != null) + { + posterStorage.Delete(collection.PosterFileName); + } + + return true; + } + + public void AddGames(Guid collectionId, IEnumerable gameIds) + { + var collection = GetCollection(collectionId); + if (collection != null && AddDistinct(collection, gameIds)) + { + Persist(new[] { collectionId }); + } + } + + /// + /// Removes game references from a collection. The games stay in the Playnite library. + /// + public void RemoveGames(Guid collectionId, IEnumerable gameIds) + { + var collection = GetCollection(collectionId); + if (collection != null && RemoveIds(collection, new HashSet(gameIds))) + { + Persist(new[] { collectionId }); + } + } + + /// + /// Applies the result of the "Add to Collection" dialog in a single save: + /// maps collection IDs to whether the games should be in them, + /// and every title in becomes a new collection containing the games. + /// + public void ApplyMembership(IReadOnlyCollection gameIds, IDictionary membership, IEnumerable newCollectionTitles) + { + var changed = new List(); + foreach (var title in newCollectionTitles) + { + if (ValidateTitle(title) != null) + { + continue; + } + + var collection = BuildNewCollection(title, gameIds); + collections.Add(collection); + changed.Add(collection.Id); + } + + var gameIdSet = new HashSet(gameIds); + foreach (var pair in membership) + { + var collection = GetCollection(pair.Key); + if (collection == null) + { + continue; + } + + var modified = pair.Value ? AddDistinct(collection, gameIds) : RemoveIds(collection, gameIdSet); + if (modified) + { + changed.Add(collection.Id); + } + } + + if (changed.Count > 0) + { + Persist(changed); + } + } + + /// + /// Drops references to games that were removed from the Playnite library. + /// + public void RemoveGamesFromAllCollections(IEnumerable gameIds) + { + var removed = new HashSet(gameIds); + var changed = collections.Where(c => RemoveIds(c, removed)).Select(c => c.Id).ToList(); + if (changed.Count > 0) + { + Persist(changed); + } + } + + /// + /// Drops references to games that no longer exist in the library, e.g. ones removed while the plugin was disabled. + /// + public void RemoveMissingGames() + { + var missing = collections + .SelectMany(c => c.GameIds) + .Distinct() + .Where(id => playniteApi.Database.Games.Get(id) == null) + .ToList(); + + if (missing.Count > 0) + { + logger.Info($"Removing {missing.Count} game reference(s) no longer present in the library."); + RemoveGamesFromAllCollections(missing); + } + } + + public void DeleteUnreferencedPosters() + { + posterStorage.DeleteUnreferenced(collections.Select(c => c.PosterFileName)); + } + + #endregion + + #region Games and posters + + /// + /// Returns the collection's games that still exist in the library, in collection order. + /// + public List GetGames(GameCollection collection) + { + return collection.GameIds + .Select(id => playniteApi.Database.Games.Get(id)) + .Where(g => g != null) + .ToList(); + } + + public Game GetFirstGame(GameCollection collection) + { + foreach (var id in collection.GameIds) + { + var game = playniteApi.Database.Games.Get(id); + if (game != null) + { + return game; + } + } + + return null; + } + + public bool HasCustomPoster(GameCollection collection) + { + return !string.IsNullOrEmpty(collection.PosterFileName); + } + + public string GetCustomPosterPath(GameCollection collection) + { + var path = posterStorage.GetFullPath(collection.PosterFileName); + return path != null && File.Exists(path) ? path : null; + } + + /// + /// Picks the image shown for a collection: the custom poster, otherwise the cover of the + /// first game in the collection, otherwise null (the placeholder is shown). + /// + public string ResolvePosterPath(GameCollection collection) + { + return GetCustomPosterPath(collection) ?? GetGameCoverPath(GetFirstGame(collection)); + } + + public string GetGameCoverPath(Game game) + { + if (game == null || string.IsNullOrWhiteSpace(game.CoverImage)) + { + return null; + } + + // Covers that have not been downloaded yet are stored as URLs; treat them as unavailable. + if (game.CoverImage.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + game.CoverImage.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + try + { + var path = playniteApi.Database.GetFullFilePath(game.CoverImage); + return File.Exists(path) ? path : null; + } + catch (Exception e) + { + logger.Warn(e, $"Failed to resolve cover path for game {game.Id}."); + return null; + } + } + + #endregion + + private GameCollection BuildNewCollection(string title, IEnumerable gameIds) + { + var error = ValidateTitle(title); + if (error != null) + { + throw new InvalidOperationException(error); + } + + var now = DateTime.UtcNow; + var collection = new GameCollection + { + Id = Guid.NewGuid(), + Title = NormalizeTitle(title), + CreatedAt = now, + ModifiedAt = now + }; + + if (gameIds != null) + { + AddDistinct(collection, gameIds); + collection.ModifiedAt = now; + } + + return collection; + } + + private static bool AddDistinct(GameCollection collection, IEnumerable gameIds) + { + var existing = new HashSet(collection.GameIds); + var added = false; + foreach (var id in gameIds) + { + if (id != Guid.Empty && existing.Add(id)) + { + collection.GameIds.Add(id); + added = true; + } + } + + if (added) + { + collection.ModifiedAt = DateTime.UtcNow; + } + + return added; + } + + private static bool RemoveIds(GameCollection collection, HashSet gameIds) + { + var removed = collection.GameIds.RemoveAll(gameIds.Contains) > 0; + if (removed) + { + collection.ModifiedAt = DateTime.UtcNow; + } + + return removed; + } + + private bool Persist(IReadOnlyCollection changedIds) + { + var saved = false; + try + { + repository.Save(collections); + saved = true; + } + catch (Exception e) + { + logger.Error(e, "Failed to save collections."); + playniteApi.Notifications.Add(new NotificationMessage( + "GameCollections_SaveError", + Loc.Format("LOCGameCollections_ErrorSaveFailed", e.Message), + NotificationType.Error)); + } + + try + { + CollectionsChanged?.Invoke(this, new CollectionsChangedEventArgs(changedIds)); + } + catch (Exception e) + { + logger.Error(e, "Error while handling collection changes."); + } + + return saved; + } + } +} diff --git a/source/GameCollections/Services/CollectionRepository.cs b/source/GameCollections/Services/CollectionRepository.cs new file mode 100644 index 0000000..f6165bb --- /dev/null +++ b/source/GameCollections/Services/CollectionRepository.cs @@ -0,0 +1,218 @@ +using GameCollections.Models; +using Playnite.SDK; +using Playnite.SDK.Data; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace GameCollections.Services +{ + public class RepositoryLoadResult + { + public List Collections { get; } + + /// + /// Message to show the user when data had to be recovered or could not be read; null otherwise. + /// + public string Warning { get; } + + public RepositoryLoadResult(List collections, string warning) + { + Collections = collections; + Warning = warning; + } + } + + /// + /// Reads and writes the collections JSON file in the plugin's user data folder. + /// Writes go to a temporary file first and are then swapped in, keeping the previous + /// version as a backup, so an interrupted save never leaves a half-written data file. + /// + public class CollectionRepository + { + public const int CurrentSchemaVersion = 1; + private const string DataFileName = "collections.json"; + + private static readonly ILogger logger = LogManager.GetLogger(); + private readonly string dataDirectory; + private readonly string filePath; + private readonly string backupPath; + private readonly string tempPath; + + public CollectionRepository(string dataDirectory) + { + this.dataDirectory = dataDirectory; + filePath = Path.Combine(dataDirectory, DataFileName); + backupPath = filePath + ".bak"; + tempPath = filePath + ".tmp"; + } + + public RepositoryLoadResult Load() + { + if (!File.Exists(filePath) && !File.Exists(backupPath)) + { + return new RepositoryLoadResult(new List(), null); + } + + string preservedCopy = null; + if (File.Exists(filePath)) + { + if (TryRead(filePath, out var collections)) + { + return new RepositoryLoadResult(collections, null); + } + + // Move the unreadable file aside so the next save cannot overwrite it. + preservedCopy = PreserveUnreadableFile(filePath); + } + + if (File.Exists(backupPath) && TryRead(backupPath, out var backupCollections)) + { + logger.Warn("Collections data file was unreadable, restored from backup."); + return new RepositoryLoadResult(backupCollections, Loc.Get("LOCGameCollections_WarningRestoredFromBackup")); + } + + return new RepositoryLoadResult( + new List(), + Loc.Format("LOCGameCollections_WarningDataUnreadable", preservedCopy ?? filePath)); + } + + public void Save(IEnumerable collections) + { + Directory.CreateDirectory(dataDirectory); + var payload = new CollectionsDataFile + { + SchemaVersion = CurrentSchemaVersion, + Collections = collections.ToList() + }; + + var json = Serialization.ToJson(payload, true); + using (var stream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)) + { + var bytes = new UTF8Encoding(false).GetBytes(json); + stream.Write(bytes, 0, bytes.Length); + stream.Flush(true); + } + + if (!File.Exists(filePath)) + { + File.Move(tempPath, filePath); + return; + } + + try + { + File.Replace(tempPath, filePath, backupPath, true); + } + catch (Exception e) when (e is IOException || e is PlatformNotSupportedException || e is UnauthorizedAccessException) + { + // File.Replace is not supported on every file system; fall back to copy-based replacement. + logger.Warn(e, "File.Replace failed, falling back to copy."); + File.Copy(filePath, backupPath, true); + File.Copy(tempPath, filePath, true); + File.Delete(tempPath); + } + } + + private static bool TryRead(string path, out List collections) + { + collections = null; + try + { + var text = File.ReadAllText(path, Encoding.UTF8); + var data = Serialization.FromJson(text); + if (data == null) + { + logger.Error($"Collections file {path} contained no data."); + return false; + } + + if (data.SchemaVersion > CurrentSchemaVersion) + { + logger.Warn($"Collections file {path} was written by a newer plugin version ({data.SchemaVersion})."); + } + + collections = Sanitize(data.Collections); + return true; + } + catch (Exception e) + { + logger.Error(e, $"Failed to read collections file {path}."); + return false; + } + } + + private static string PreserveUnreadableFile(string path) + { + try + { + var target = Path.Combine( + Path.GetDirectoryName(path), + $"{Path.GetFileNameWithoutExtension(path)}.unreadable-{DateTime.Now:yyyyMMdd-HHmmss}.json"); + File.Move(path, target); + return target; + } + catch (Exception e) + { + logger.Error(e, $"Failed to move unreadable collections file {path}."); + return null; + } + } + + /// + /// Repairs records that could have been damaged by manual edits so the rest of the plugin can rely on them. + /// + private static List Sanitize(List source) + { + var result = new List(); + if (source == null) + { + return result; + } + + var seenIds = new HashSet(); + foreach (var collection in source) + { + if (collection == null) + { + continue; + } + + if (collection.Id == Guid.Empty || !seenIds.Add(collection.Id)) + { + collection.Id = Guid.NewGuid(); + seenIds.Add(collection.Id); + } + + collection.Title = CollectionManager.NormalizeTitle(collection.Title); + if (collection.Title.Length == 0) + { + collection.Title = Loc.Get("LOCGameCollections_UntitledCollection"); + } + + collection.Description = CollectionManager.NormalizeDescription(collection.Description); + collection.Rating = CollectionManager.NormalizeRating(collection.Rating); + collection.GameIds = (collection.GameIds ?? new List()) + .Where(id => id != Guid.Empty) + .Distinct() + .ToList(); + + if (collection.CreatedAt == default(DateTime)) + { + collection.CreatedAt = DateTime.UtcNow; + } + + if (collection.ModifiedAt == default(DateTime)) + { + collection.ModifiedAt = collection.CreatedAt; + } + + result.Add(collection); + } + + return result; + } + } +} diff --git a/source/GameCollections/Services/DialogService.cs b/source/GameCollections/Services/DialogService.cs new file mode 100644 index 0000000..5c0b535 --- /dev/null +++ b/source/GameCollections/Services/DialogService.cs @@ -0,0 +1,98 @@ +using GameCollections.Models; +using GameCollections.ViewModels; +using GameCollections.Views; +using Playnite.SDK; +using Playnite.SDK.Models; +using System; +using System.Collections.Generic; +using System.Windows; + +namespace GameCollections.Services +{ + /// + /// Opens the plugin's dialogs in windows created by Playnite so they get the active theme. + /// + public class DialogService + { + private readonly IPlayniteAPI playniteApi; + private readonly CollectionManager manager; + + public DialogService(IPlayniteAPI playniteApi, CollectionManager manager) + { + this.playniteApi = playniteApi; + this.manager = manager; + } + + public bool ShowAddToCollection(IReadOnlyList games) + { + if (games == null || games.Count == 0) + { + return false; + } + + var window = CreateWindow(Loc.Get("LOCGameCollections_AddToCollectionWindowTitle"), 460, 560, 360, 380); + var viewModel = new AddToCollectionViewModel(manager, games, result => Close(window, result)); + window.Content = new AddToCollectionView { DataContext = viewModel }; + return window.ShowDialog() == true; + } + + /// + /// Shows the create dialog and returns the new collection's ID, or null when cancelled. + /// + public Guid? ShowCreateCollection() + { + return ShowEditor(null); + } + + public bool ShowEditCollection(GameCollection collection) + { + return ShowEditor(collection).HasValue; + } + + private Guid? ShowEditor(GameCollection collection) + { + var viewModel = new EditCollectionViewModel(playniteApi, manager, collection); + var window = CreateWindow(viewModel.WindowTitle, 640, 480, 520, 420); + viewModel.CloseRequested = result => Close(window, result); + window.Content = new EditCollectionView { DataContext = viewModel }; + return window.ShowDialog() == true ? viewModel.SavedCollectionId : null; + } + + private Window CreateWindow(string title, double width, double height, double minWidth, double minHeight) + { + var window = playniteApi.Dialogs.CreateWindow(new WindowCreationOptions + { + ShowMinimizeButton = false, + ShowMaximizeButton = false, + ShowCloseButton = true + }); + + // Keep dialogs usable on small or scaled screens. + var workArea = SystemParameters.WorkArea; + window.Title = title; + window.MinWidth = Math.Min(minWidth, workArea.Width); + window.MinHeight = Math.Min(minHeight, workArea.Height); + window.Width = Math.Max(window.MinWidth, Math.Min(width, workArea.Width * 0.9)); + window.Height = Math.Max(window.MinHeight, Math.Min(height, workArea.Height * 0.9)); + window.ResizeMode = ResizeMode.CanResize; + window.Owner = playniteApi.Dialogs.GetCurrentAppWindow(); + window.WindowStartupLocation = window.Owner != null + ? WindowStartupLocation.CenterOwner + : WindowStartupLocation.CenterScreen; + return window; + } + + private static void Close(Window window, bool result) + { + try + { + window.DialogResult = result; + } + catch (InvalidOperationException) + { + // DialogResult can only be set while the window is shown modally. + window.Close(); + } + } + } +} diff --git a/source/GameCollections/Services/ImageLoader.cs b/source/GameCollections/Services/ImageLoader.cs new file mode 100644 index 0000000..8228718 --- /dev/null +++ b/source/GameCollections/Services/ImageLoader.cs @@ -0,0 +1,101 @@ +using Playnite.SDK; +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Media.Imaging; + +namespace GameCollections.Services +{ + /// + /// Decodes images off the UI thread at a reduced size and caches the results. + /// + public static class ImageLoader + { + private const int MaxCacheEntries = 400; + + private static readonly ILogger logger = LogManager.GetLogger(); + private static readonly object cacheLock = new object(); + private static readonly Dictionary cache = new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly SemaphoreSlim limiter = new SemaphoreSlim(Math.Max(2, Environment.ProcessorCount / 2)); + + public static async Task LoadAsync(string path, int decodeWidth) + { + if (string.IsNullOrEmpty(path)) + { + return null; + } + + await limiter.WaitAsync().ConfigureAwait(false); + try + { + return await Task.Run(() => Load(path, decodeWidth)).ConfigureAwait(false); + } + finally + { + limiter.Release(); + } + } + + /// + /// Returns a frozen bitmap decoded to pixels wide, or null when + /// the file is missing or cannot be decoded. + /// + public static BitmapSource Load(string path, int decodeWidth) + { + try + { + var info = new FileInfo(path); + if (!info.Exists) + { + return null; + } + + // Including the write time means a replaced file is never served from a stale cache entry. + var key = $"{info.FullName}|{decodeWidth}|{info.LastWriteTimeUtc.Ticks}|{info.Length}"; + lock (cacheLock) + { + if (cache.TryGetValue(key, out var cached)) + { + return cached; + } + } + + BitmapImage bitmap; + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + { + bitmap = new BitmapImage(); + bitmap.BeginInit(); + bitmap.CacheOption = BitmapCacheOption.OnLoad; + bitmap.CreateOptions = BitmapCreateOptions.IgnoreColorProfile; + if (decodeWidth > 0) + { + bitmap.DecodePixelWidth = decodeWidth; + } + + bitmap.StreamSource = stream; + bitmap.EndInit(); + bitmap.Freeze(); + } + + lock (cacheLock) + { + if (cache.Count >= MaxCacheEntries) + { + cache.Clear(); + } + + cache[key] = bitmap; + } + + return bitmap; + } + catch (Exception e) + { + logger.Warn(e, $"Failed to load image {path}."); + return null; + } + } + } +} diff --git a/source/GameCollections/Services/Loc.cs b/source/GameCollections/Services/Loc.cs new file mode 100644 index 0000000..a793e87 --- /dev/null +++ b/source/GameCollections/Services/Loc.cs @@ -0,0 +1,40 @@ +using Playnite.SDK; +using System.Globalization; + +namespace GameCollections.Services +{ + /// + /// Shortcuts for reading localized strings from Playnite's resource provider. + /// + public static class Loc + { + public static string Get(string key) + { + return ResourceProvider.GetString(key); + } + + public static string Format(string key, params object[] args) + { + return string.Format(CultureInfo.CurrentCulture, Get(key), args); + } + + public static string GameCount(int count) + { + return count == 1 + ? Get("LOCGameCollections_GameCountSingle") + : Format("LOCGameCollections_GameCountPlural", count); + } + + public static string CollectionCount(int count) + { + return count == 1 + ? Get("LOCGameCollections_CollectionCountSingle") + : Format("LOCGameCollections_CollectionCountPlural", count); + } + + public static string Rating(double rating) + { + return string.Format(CultureInfo.CurrentCulture, "{0:0.#}/10", rating); + } + } +} diff --git a/source/GameCollections/Services/PosterStorage.cs b/source/GameCollections/Services/PosterStorage.cs new file mode 100644 index 0000000..77686af --- /dev/null +++ b/source/GameCollections/Services/PosterStorage.cs @@ -0,0 +1,115 @@ +using Playnite.SDK; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace GameCollections.Services +{ + /// + /// Keeps copies of custom posters inside the plugin data folder so they survive the + /// original file being moved or deleted. + /// + public class PosterStorage + { + public static readonly string[] SupportedExtensions = { ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tif", ".tiff" }; + + private static readonly ILogger logger = LogManager.GetLogger(); + private readonly string directory; + + public PosterStorage(string directory) + { + this.directory = directory; + } + + public static bool IsSupportedFile(string path) + { + var extension = Path.GetExtension(path ?? string.Empty).ToLowerInvariant(); + return SupportedExtensions.Contains(extension); + } + + /// + /// Copies an image into the poster folder and returns the stored file name. + /// A new name is used on every import so cached images of the old poster are never reused. + /// + public string Import(Guid collectionId, string sourcePath) + { + if (!IsSupportedFile(sourcePath)) + { + throw new NotSupportedException(Loc.Get("LOCGameCollections_ErrorPosterFormat")); + } + + if (!File.Exists(sourcePath)) + { + throw new FileNotFoundException(Loc.Get("LOCGameCollections_ErrorPosterMissing"), sourcePath); + } + + Directory.CreateDirectory(directory); + var fileName = $"{collectionId:N}_{DateTime.UtcNow.Ticks}{Path.GetExtension(sourcePath).ToLowerInvariant()}"; + File.Copy(sourcePath, Path.Combine(directory, fileName), false); + return fileName; + } + + public string GetFullPath(string fileName) + { + if (string.IsNullOrWhiteSpace(fileName)) + { + return null; + } + + // Only plain file names are stored; strip anything else so the path cannot leave the folder. + return Path.Combine(directory, Path.GetFileName(fileName)); + } + + public void Delete(string fileName) + { + var path = GetFullPath(fileName); + if (path == null) + { + return; + } + + try + { + if (File.Exists(path)) + { + File.Delete(path); + } + } + catch (Exception e) + { + logger.Warn(e, $"Failed to delete poster {path}."); + } + } + + /// + /// Removes poster files left behind by collections that no longer reference them. + /// + public void DeleteUnreferenced(IEnumerable referencedFileNames) + { + if (!Directory.Exists(directory)) + { + return; + } + + var referenced = new HashSet( + referencedFileNames.Where(n => !string.IsNullOrWhiteSpace(n)).Select(Path.GetFileName), + StringComparer.OrdinalIgnoreCase); + + try + { + foreach (var file in Directory.EnumerateFiles(directory)) + { + if (!referenced.Contains(Path.GetFileName(file))) + { + Delete(Path.GetFileName(file)); + } + } + } + catch (Exception e) + { + logger.Warn(e, "Failed to clean up unreferenced posters."); + } + } + } +} diff --git a/source/GameCollections/Settings/GameCollectionsSettings.cs b/source/GameCollections/Settings/GameCollectionsSettings.cs new file mode 100644 index 0000000..34e02cf --- /dev/null +++ b/source/GameCollections/Settings/GameCollectionsSettings.cs @@ -0,0 +1,64 @@ +using GameCollections.Models; +using Playnite.SDK; +using Playnite.SDK.Data; +using System.Collections.Generic; + +namespace GameCollections.Settings +{ + public class GameCollectionsSettings : ObservableObject + { + // Remembered UI state rather than a user-facing option, so it is not shown in the settings view. + private CollectionsViewMode viewMode = CollectionsViewMode.Grid; + public CollectionsViewMode ViewMode { get => viewMode; set => SetValue(ref viewMode, value); } + } + + public class GameCollectionsSettingsViewModel : ObservableObject, ISettings + { + private readonly GameCollectionsPlugin plugin; + private GameCollectionsSettings editingClone; + + private GameCollectionsSettings settings; + public GameCollectionsSettings Settings + { + get => settings; + set + { + settings = value; + OnPropertyChanged(); + } + } + + public GameCollectionsSettingsViewModel(GameCollectionsPlugin plugin) + { + // The plugin instance is required for Save/Load because Playnite stores data per plugin. + this.plugin = plugin; + Settings = plugin.LoadPluginSettings() ?? new GameCollectionsSettings(); + } + + public void Save() + { + plugin.SavePluginSettings(Settings); + } + + public void BeginEdit() + { + editingClone = Serialization.GetClone(Settings); + } + + public void CancelEdit() + { + Settings = editingClone; + } + + public void EndEdit() + { + Save(); + } + + public bool VerifySettings(out List errors) + { + errors = new List(); + return true; + } + } +} diff --git a/source/GameCollections/Settings/GameCollectionsSettingsView.xaml b/source/GameCollections/Settings/GameCollectionsSettingsView.xaml new file mode 100644 index 0000000..0b3246d --- /dev/null +++ b/source/GameCollections/Settings/GameCollectionsSettingsView.xaml @@ -0,0 +1,15 @@ + + + + + + diff --git a/source/GameCollections/Settings/GameCollectionsSettingsView.xaml.cs b/source/GameCollections/Settings/GameCollectionsSettingsView.xaml.cs new file mode 100644 index 0000000..b780437 --- /dev/null +++ b/source/GameCollections/Settings/GameCollectionsSettingsView.xaml.cs @@ -0,0 +1,12 @@ +using System.Windows.Controls; + +namespace GameCollections.Settings +{ + public partial class GameCollectionsSettingsView : UserControl + { + public GameCollectionsSettingsView() + { + InitializeComponent(); + } + } +} diff --git a/source/GameCollections/ViewModels/AddToCollectionViewModel.cs b/source/GameCollections/ViewModels/AddToCollectionViewModel.cs new file mode 100644 index 0000000..8f82ca4 --- /dev/null +++ b/source/GameCollections/ViewModels/AddToCollectionViewModel.cs @@ -0,0 +1,215 @@ +using GameCollections.Services; +using Playnite.SDK; +using Playnite.SDK.Models; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Linq; +using System.Windows.Data; + +namespace GameCollections.ViewModels +{ + /// + /// One row of the "Add to Collection" dialog. + /// + public class CollectionToggleItem : ObservableObject + { + /// + /// Collection ID, or null for a collection created in the dialog that is not saved yet. + /// + public Guid? CollectionId { get; } + public string Title { get; } + public string GameCountText { get; } + public bool IsNew => CollectionId == null; + + /// + /// Membership before the dialog opened: true when all selected games are in the collection, + /// false when none are, null when only some are. + /// + public bool? OriginalState { get; } + + /// + /// Only mixed rows can return to the "leave unchanged" state. + /// + public bool IsThreeState => OriginalState == null; + + private bool? isChecked; + public bool? IsChecked { get => isChecked; set => SetValue(ref isChecked, value); } + + public CollectionToggleItem(Guid? collectionId, string title, string gameCountText, bool? originalState) + { + CollectionId = collectionId; + Title = title; + GameCountText = gameCountText; + OriginalState = originalState; + isChecked = originalState; + } + + public void Toggle() + { + IsChecked = IsChecked != true; + } + } + + public class AddToCollectionViewModel : ObservableObject + { + private readonly CollectionManager manager; + private readonly IReadOnlyList games; + private readonly Action close; + + public ObservableCollection Items { get; } = new ObservableCollection(); + public ListCollectionView ItemsView { get; } + + public string HeaderText { get; } + + private string searchText = string.Empty; + public string SearchText + { + get => searchText; + set + { + SetValue(ref searchText, value ?? string.Empty); + ItemsView.Refresh(); + RaiseStateChanged(); + } + } + + private CollectionToggleItem selectedItem; + public CollectionToggleItem SelectedItem { get => selectedItem; set => SetValue(ref selectedItem, value); } + + public bool IsEmpty => Items.Count == 0; + public bool HasNoResults => !IsEmpty && ItemsView.Count == 0; + public bool ShowEmptyState => IsEmpty && SearchTitle.Length == 0; + + /// + /// True when the search text can become a new collection: it is a valid title and no + /// existing or pending collection already uses it. + /// + public bool CanCreateFromSearch => + SearchTitle.Length > 0 && + SearchTitle.Length <= CollectionManager.MaxTitleLength && + !Items.Any(i => CollectionManager.TitlesEqual(i.Title, SearchTitle)); + + public string CreateButtonText => Loc.Format("LOCGameCollections_CreateCollectionNamed", SearchTitle); + public string NoResultsText => Loc.Format("LOCGameCollections_NoCollectionsMatch", SearchTitle); + + public RelayCommand CreateFromSearchCommand { get; } + public RelayCommand SaveCommand { get; } + public RelayCommand CancelCommand { get; } + + private string SearchTitle => CollectionManager.NormalizeTitle(searchText); + + public AddToCollectionViewModel(CollectionManager manager, IReadOnlyList games, Action close) + { + this.manager = manager; + this.games = games; + this.close = close; + + HeaderText = games.Count == 1 + ? Loc.Format("LOCGameCollections_AddToCollectionHeaderSingle", games[0].Name) + : Loc.Format("LOCGameCollections_AddToCollectionHeaderMultiple", games.Count); + + var gameIds = games.Select(g => g.Id).ToList(); + foreach (var collection in manager.Collections) + { + var memberIds = new HashSet(collection.GameIds); + var containedCount = gameIds.Count(memberIds.Contains); + bool? state = containedCount == 0 ? false : containedCount == gameIds.Count ? (bool?)true : null; + Items.Add(new CollectionToggleItem(collection.Id, collection.Title, Loc.GameCount(manager.GetGames(collection).Count), state)); + } + + ItemsView = new ListCollectionView(Items) + { + Filter = FilterItem, + CustomSort = Comparer.Create(CompareItems) + }; + + CreateFromSearchCommand = new RelayCommand(CreateFromSearch); + SaveCommand = new RelayCommand(Save); + CancelCommand = new RelayCommand(() => close(false)); + } + + public void CreateFromSearch() + { + if (!CanCreateFromSearch) + { + return; + } + + var item = new CollectionToggleItem(null, SearchTitle, Loc.Get("LOCGameCollections_NewCollectionBadge"), false); + item.IsChecked = true; + Items.Add(item); + SearchText = string.Empty; + SelectedItem = item; + } + + /// + /// Enter in the search box creates a collection when the text is new, or toggles the + /// only matching collection. Returns false when nothing was done. + /// + public bool HandleSearchEnter() + { + if (CanCreateFromSearch && ItemsView.Count == 0) + { + CreateFromSearch(); + return true; + } + + if (SearchTitle.Length > 0 && ItemsView.Count == 1) + { + var item = ItemsView.Cast().First(); + item.Toggle(); + SelectedItem = item; + return true; + } + + return false; + } + + private void Save() + { + var membership = new Dictionary(); + foreach (var item in Items.Where(i => !i.IsNew && i.IsChecked.HasValue && i.IsChecked != i.OriginalState)) + { + membership[item.CollectionId.Value] = item.IsChecked.Value; + } + + var newTitles = Items.Where(i => i.IsNew && i.IsChecked == true).Select(i => i.Title).ToList(); + manager.ApplyMembership(games.Select(g => g.Id).ToList(), membership, newTitles); + close(true); + } + + private bool FilterItem(object obj) + { + if (SearchTitle.Length == 0) + { + return true; + } + + var item = (CollectionToggleItem)obj; + return CultureInfo.CurrentCulture.CompareInfo.IndexOf(item.Title, SearchTitle, CompareOptions.IgnoreCase) >= 0; + } + + private static int CompareItems(CollectionToggleItem first, CollectionToggleItem second) + { + // Collections created in this dialog stay on top so they are easy to spot. + if (first.IsNew != second.IsNew) + { + return first.IsNew ? -1 : 1; + } + + return string.Compare(first.Title, second.Title, StringComparison.CurrentCultureIgnoreCase); + } + + private void RaiseStateChanged() + { + OnPropertyChanged(nameof(IsEmpty)); + OnPropertyChanged(nameof(HasNoResults)); + OnPropertyChanged(nameof(ShowEmptyState)); + OnPropertyChanged(nameof(CanCreateFromSearch)); + OnPropertyChanged(nameof(CreateButtonText)); + OnPropertyChanged(nameof(NoResultsText)); + } + } +} diff --git a/source/GameCollections/ViewModels/CollectionCardViewModel.cs b/source/GameCollections/ViewModels/CollectionCardViewModel.cs new file mode 100644 index 0000000..1918a61 --- /dev/null +++ b/source/GameCollections/ViewModels/CollectionCardViewModel.cs @@ -0,0 +1,110 @@ +using GameCollections.Models; +using GameCollections.Services; +using Playnite.SDK; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Windows.Media; + +namespace GameCollections.ViewModels +{ + /// + /// Actions shared by every place that shows a collection. + /// + public interface ICollectionActions + { + void OpenCollection(Guid id); + void EditCollection(Guid id); + void DeleteCollection(Guid id); + } + + /// + /// Display state of one collection, used by the grid card, the list row and the collection page header. + /// + public class CollectionCardViewModel : ObservableObject + { + // Wide enough for the largest place a poster is drawn (the collection page header) on scaled displays. + private const int PosterDecodeWidth = 320; + private static readonly ILogger logger = LogManager.GetLogger(); + + private readonly CollectionManager manager; + private int posterVersion; + + public Guid Id { get; } + + private string title; + public string Title { get => title; private set => SetValue(ref title, value); } + + private string description; + public string Description { get => description; private set => SetValue(ref description, value); } + + private double rating; + public double Rating { get => rating; private set => SetValue(ref rating, value); } + + private int gameCount; + public int GameCount { get => gameCount; private set => SetValue(ref gameCount, value); } + + private ImageSource poster; + public ImageSource Poster { get => poster; private set => SetValue(ref poster, value); } + + public string RatingText => Loc.Rating(rating); + public string GameCountText => Loc.GameCount(gameCount); + public bool HasDescription => !string.IsNullOrWhiteSpace(description); + + /// + /// The game whose cover is used as the automatic poster, if any. + /// + public Guid? PosterGameId { get; private set; } + + public RelayCommand OpenCommand { get; } + public RelayCommand EditCommand { get; } + public RelayCommand DeleteCommand { get; } + + public CollectionCardViewModel(GameCollection collection, CollectionManager manager, ICollectionActions actions) + { + this.manager = manager; + Id = collection.Id; + OpenCommand = new RelayCommand(() => actions.OpenCollection(Id)); + EditCommand = new RelayCommand(() => actions.EditCollection(Id)); + DeleteCommand = new RelayCommand(() => actions.DeleteCollection(Id)); + Update(collection); + } + + public void Update(GameCollection collection) + { + Title = collection.Title; + Description = collection.Description; + Rating = collection.Rating; + GameCount = manager.GetGames(collection).Count; + OnPropertyChanged(nameof(RatingText)); + OnPropertyChanged(nameof(GameCountText)); + OnPropertyChanged(nameof(HasDescription)); + + PosterGameId = manager.HasCustomPoster(collection) ? null : manager.GetFirstGame(collection)?.Id; + _ = LoadPosterAsync(manager.ResolvePosterPath(collection)); + } + + private async Task LoadPosterAsync(string path) + { + var version = ++posterVersion; + if (path == null) + { + Poster = null; + return; + } + + try + { + var image = await ImageLoader.LoadAsync(path, PosterDecodeWidth); + if (version == posterVersion) + { + Poster = image; + } + } + catch (Exception e) + { + logger.Error(e, $"Failed to load poster for collection {Id}."); + } + } + } +} diff --git a/source/GameCollections/ViewModels/CollectionDetailsViewModel.cs b/source/GameCollections/ViewModels/CollectionDetailsViewModel.cs new file mode 100644 index 0000000..b9f826c --- /dev/null +++ b/source/GameCollections/ViewModels/CollectionDetailsViewModel.cs @@ -0,0 +1,364 @@ +using GameCollections.Services; +using Playnite.SDK; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Linq; +using System.Windows.Data; + +namespace GameCollections.ViewModels +{ + public enum GameSortField + { + CollectionOrder, + Name, + ReleaseDate, + LastPlayed, + Playtime, + DateAdded + } + + public class SortOption + { + public GameSortField Field { get; } + public string Label { get; } + + public SortOption(GameSortField field, string label) + { + Field = field; + Label = label; + } + } + + /// + /// The page of a single collection: header plus its games. + /// + public class CollectionDetailsViewModel : ObservableObject + { + private const string AscendingGlyph = "\uea5e"; + private const string DescendingGlyph = "\uea5b"; + private static readonly ILogger logger = LogManager.GetLogger(); + + private readonly IPlayniteAPI playniteApi; + private readonly CollectionManager manager; + private readonly CollectionsRootViewModel root; + + public CollectionCardViewModel Header { get; } + public Guid CollectionId => Header.Id; + + public ObservableCollection Games { get; } = new ObservableCollection(); + public ListCollectionView GamesView { get; } + + /// + /// The view's current selection; set by the view. + /// + public IList SelectedGames { get; set; } + + public IReadOnlyList SortOptions { get; } = new List + { + new SortOption(GameSortField.CollectionOrder, Loc.Get("LOCGameCollections_SortCollectionOrder")), + new SortOption(GameSortField.Name, Loc.Get("LOCGameCollections_SortName")), + new SortOption(GameSortField.ReleaseDate, Loc.Get("LOCGameCollections_SortReleaseDate")), + new SortOption(GameSortField.LastPlayed, Loc.Get("LOCGameCollections_SortLastPlayed")), + new SortOption(GameSortField.Playtime, Loc.Get("LOCGameCollections_SortPlaytime")), + new SortOption(GameSortField.DateAdded, Loc.Get("LOCGameCollections_SortDateAdded")) + }; + + private string searchText = string.Empty; + public string SearchText + { + get => searchText; + set + { + SetValue(ref searchText, value ?? string.Empty); + RefreshView(); + } + } + + public GameSortField SortField + { + get => root.GameSortField; + set + { + root.GameSortField = value; + OnPropertyChanged(); + ApplySort(); + } + } + + public bool SortDescending + { + get => root.GameSortDescending; + set + { + root.GameSortDescending = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(SortDirectionGlyph)); + OnPropertyChanged(nameof(SortDirectionTooltip)); + ApplySort(); + } + } + + public string SortDirectionGlyph => SortDescending ? DescendingGlyph : AscendingGlyph; + public string SortDirectionTooltip => Loc.Get(SortDescending ? "LOCGameCollections_SortDescending" : "LOCGameCollections_SortAscending"); + + private bool installedOnly; + public bool InstalledOnly + { + get => installedOnly; + set + { + SetValue(ref installedOnly, value); + RefreshView(); + } + } + + public bool IsEmpty => Games.Count == 0; + public bool HasNoResults => !IsEmpty && GamesView.Count == 0; + public string VisibleCountText => GamesView.Count == Games.Count + ? Loc.GameCount(Games.Count) + : Loc.Format("LOCGameCollections_FilteredGameCount", GamesView.Count, Games.Count); + + public RelayCommand BackCommand { get; } + public RelayCommand ToggleSortDirectionCommand { get; } + public RelayCommand ShowAllInLibraryCommand { get; } + public RelayCommand RemoveSelectedCommand { get; } + public RelayCommand PlaySelectedCommand { get; } + + public CollectionDetailsViewModel(IPlayniteAPI playniteApi, CollectionManager manager, CollectionsRootViewModel root, CollectionCardViewModel header) + { + this.playniteApi = playniteApi; + this.manager = manager; + this.root = root; + Header = header; + + GamesView = new ListCollectionView(Games) { Filter = FilterGame }; + ApplySort(); + + BackCommand = new RelayCommand(root.ShowHome); + ToggleSortDirectionCommand = new RelayCommand(() => SortDescending = !SortDescending); + ShowAllInLibraryCommand = new RelayCommand(ShowAllInLibrary); + RemoveSelectedCommand = new RelayCommand(RemoveSelected); + PlaySelectedCommand = new RelayCommand(PlaySelected); + + Reload(); + } + + /// + /// Re-reads the collection's games, reusing existing tiles so loaded covers are kept. + /// + public void Reload() + { + var collection = manager.GetCollection(CollectionId); + if (collection == null) + { + return; + } + + var games = manager.GetGames(collection); + var currentIds = new HashSet(games.Select(g => g.Id)); + foreach (var tile in Games.Where(g => !currentIds.Contains(g.Id)).ToList()) + { + Games.Remove(tile); + } + + var existing = Games.ToDictionary(g => g.Id); + for (var i = 0; i < games.Count; i++) + { + if (existing.TryGetValue(games[i].Id, out var tile)) + { + tile.Update(games[i], i); + } + else + { + Games.Add(new CollectionGameViewModel(games[i], i, manager, this)); + } + } + + RefreshView(); + } + + public void OnGamesUpdated(ISet gameIds) + { + if (Games.Any(g => gameIds.Contains(g.Id))) + { + Reload(); + } + } + + public void PlayGame(CollectionGameViewModel tile) + { + try + { + var game = playniteApi.Database.Games.Get(tile.Id); + if (game == null) + { + return; + } + + if (game.IsInstalled) + { + playniteApi.StartGame(game.Id); + } + else + { + playniteApi.InstallGame(game.Id); + } + } + catch (Exception e) + { + logger.Error(e, $"Failed to start game {tile.Id}."); + playniteApi.Dialogs.ShowErrorMessage(e.Message, Loc.Get("LOCGameCollections_PluginName")); + } + } + + /// + /// Playnite has no API to open a game's detail page directly, so the game is selected + /// in the library view, which shows its details there. + /// + public void ShowGameInLibrary(CollectionGameViewModel tile) + { + try + { + playniteApi.MainView.SelectGame(tile.Id); + playniteApi.MainView.SwitchToLibraryView(); + } + catch (Exception e) + { + logger.Error(e, $"Failed to show game {tile.Id} in library."); + } + } + + /// + /// Removes the game from this collection only; when the game is part of a multi-selection, + /// the whole selection is removed. + /// + public void RemoveGame(CollectionGameViewModel tile) + { + var selected = SelectedGames?.Cast().ToList() ?? new List(); + var targets = selected.Contains(tile) ? selected : new List { tile }; + manager.RemoveGames(CollectionId, targets.Select(t => t.Id)); + } + + private void RemoveSelected() + { + var selected = SelectedGames?.Cast().ToList(); + if (selected != null && selected.Count > 0) + { + manager.RemoveGames(CollectionId, selected.Select(t => t.Id)); + } + } + + private void PlaySelected() + { + var tile = SelectedGames?.Cast().FirstOrDefault(); + if (tile != null) + { + PlayGame(tile); + } + } + + private void ShowAllInLibrary() + { + if (Games.Count == 0) + { + return; + } + + try + { + playniteApi.MainView.SelectGames(Games.Select(g => g.Id).ToList()); + playniteApi.MainView.SwitchToLibraryView(); + } + catch (Exception e) + { + logger.Error(e, "Failed to select collection games in library."); + } + } + + private bool FilterGame(object obj) + { + var tile = (CollectionGameViewModel)obj; + if (installedOnly && !tile.IsInstalled) + { + return false; + } + + var query = searchText.Trim(); + return query.Length == 0 || + CultureInfo.CurrentCulture.CompareInfo.IndexOf(tile.Name ?? string.Empty, query, CompareOptions.IgnoreCase) >= 0; + } + + private void ApplySort() + { + GamesView.CustomSort = new GameTileComparer(SortField, SortDescending); + RaiseStateChanged(); + } + + private void RefreshView() + { + GamesView.Refresh(); + RaiseStateChanged(); + } + + private void RaiseStateChanged() + { + OnPropertyChanged(nameof(IsEmpty)); + OnPropertyChanged(nameof(HasNoResults)); + OnPropertyChanged(nameof(VisibleCountText)); + } + + private class GameTileComparer : IComparer + { + private readonly GameSortField field; + private readonly bool descending; + + public GameTileComparer(GameSortField field, bool descending) + { + this.field = field; + this.descending = descending; + } + + public int Compare(object x, object y) + { + var a = (CollectionGameViewModel)x; + var b = (CollectionGameViewModel)y; + var result = CompareField(a, b); + if (result == 0 && field != GameSortField.Name) + { + result = CompareNames(a, b); + } + + return descending ? -result : result; + } + + private int CompareField(CollectionGameViewModel a, CollectionGameViewModel b) + { + switch (field) + { + case GameSortField.Name: + return CompareNames(a, b); + case GameSortField.ReleaseDate: + return Nullable.Compare(a.Game.ReleaseDate?.Date, b.Game.ReleaseDate?.Date); + case GameSortField.LastPlayed: + return Nullable.Compare(a.Game.LastActivity, b.Game.LastActivity); + case GameSortField.Playtime: + return a.Game.Playtime.CompareTo(b.Game.Playtime); + case GameSortField.DateAdded: + return Nullable.Compare(a.Game.Added, b.Game.Added); + default: + return a.Order.CompareTo(b.Order); + } + } + + private static int CompareNames(CollectionGameViewModel a, CollectionGameViewModel b) + { + var first = string.IsNullOrEmpty(a.Game.SortingName) ? a.Name : a.Game.SortingName; + var second = string.IsNullOrEmpty(b.Game.SortingName) ? b.Name : b.Game.SortingName; + return string.Compare(first, second, StringComparison.CurrentCultureIgnoreCase); + } + } + } +} diff --git a/source/GameCollections/ViewModels/CollectionGameViewModel.cs b/source/GameCollections/ViewModels/CollectionGameViewModel.cs new file mode 100644 index 0000000..a1b337e --- /dev/null +++ b/source/GameCollections/ViewModels/CollectionGameViewModel.cs @@ -0,0 +1,99 @@ +using GameCollections.Services; +using Playnite.SDK; +using Playnite.SDK.Models; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Windows.Media; + +namespace GameCollections.ViewModels +{ + /// + /// A game tile on the collection page. The cover is loaded only once the tile scrolls into view. + /// + public class CollectionGameViewModel : ObservableObject + { + private const int CoverDecodeWidth = 240; + private static readonly ILogger logger = LogManager.GetLogger(); + + private readonly CollectionManager manager; + private bool coverRequested; + private string coverPath; + private int coverVersion; + + private Game game; + public Game Game => game; + public Guid Id => game.Id; + public string Name => game.Name; + public bool IsInstalled => game.IsInstalled; + + /// + /// Position of the game in the collection, used for the "collection order" sort. + /// + public int Order { get; private set; } + + public string PlayActionText => Loc.Get(IsInstalled ? "LOCGameCollections_Play" : "LOCGameCollections_Install"); + + private ImageSource cover; + public ImageSource Cover { get => cover; private set => SetValue(ref cover, value); } + + public RelayCommand PlayCommand { get; } + public RelayCommand ShowInLibraryCommand { get; } + public RelayCommand RemoveCommand { get; } + + public CollectionGameViewModel(Game game, int order, CollectionManager manager, CollectionDetailsViewModel owner) + { + this.game = game; + this.manager = manager; + Order = order; + PlayCommand = new RelayCommand(() => owner.PlayGame(this)); + ShowInLibraryCommand = new RelayCommand(() => owner.ShowGameInLibrary(this)); + RemoveCommand = new RelayCommand(() => owner.RemoveGame(this)); + } + + public void Update(Game updatedGame, int order) + { + game = updatedGame; + Order = order; + OnPropertyChanged(nameof(Game)); + OnPropertyChanged(nameof(Name)); + OnPropertyChanged(nameof(IsInstalled)); + OnPropertyChanged(nameof(PlayActionText)); + + if (coverRequested && manager.GetGameCoverPath(game) != coverPath) + { + _ = LoadCoverAsync(); + } + } + + public void RequestCover() + { + if (coverRequested) + { + return; + } + + coverRequested = true; + _ = LoadCoverAsync(); + } + + private async Task LoadCoverAsync() + { + var version = ++coverVersion; + var path = manager.GetGameCoverPath(game); + coverPath = path; + try + { + var image = await ImageLoader.LoadAsync(path, CoverDecodeWidth); + if (version == coverVersion) + { + Cover = image; + } + } + catch (Exception e) + { + logger.Error(e, $"Failed to load cover for game {game.Id}."); + } + } + } +} diff --git a/source/GameCollections/ViewModels/CollectionsHomeViewModel.cs b/source/GameCollections/ViewModels/CollectionsHomeViewModel.cs new file mode 100644 index 0000000..c7f1c12 --- /dev/null +++ b/source/GameCollections/ViewModels/CollectionsHomeViewModel.cs @@ -0,0 +1,156 @@ +using GameCollections.Models; +using GameCollections.Services; +using GameCollections.Settings; +using Playnite.SDK; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Linq; +using System.Windows.Data; + +namespace GameCollections.ViewModels +{ + /// + /// The page listing every collection. + /// + public class CollectionsHomeViewModel : ObservableObject + { + private const string GridGlyph = "\uef5d"; + private const string ListGlyph = "\uef74"; + + private readonly CollectionManager manager; + private readonly ICollectionActions actions; + private readonly GameCollectionsSettingsViewModel settings; + + public ObservableCollection Cards { get; } = new ObservableCollection(); + public ListCollectionView CardsView { get; } + + private string searchText = string.Empty; + public string SearchText + { + get => searchText; + set + { + SetValue(ref searchText, value ?? string.Empty); + CardsView.Refresh(); + RaiseStateChanged(); + } + } + + private CollectionCardViewModel selectedCard; + public CollectionCardViewModel SelectedCard { get => selectedCard; set => SetValue(ref selectedCard, value); } + + public bool IsGridView => settings.Settings.ViewMode == CollectionsViewMode.Grid; + public bool IsListView => !IsGridView; + public string ViewModeToggleGlyph => IsGridView ? ListGlyph : GridGlyph; + public string ViewModeToggleTooltip => Loc.Get(IsGridView ? "LOCGameCollections_SwitchToListView" : "LOCGameCollections_SwitchToGridView"); + + public string CountText => Loc.CollectionCount(Cards.Count); + public bool IsEmpty => Cards.Count == 0; + public bool HasNoResults => !IsEmpty && CardsView.Count == 0; + public string NoResultsText => Loc.Format("LOCGameCollections_NoCollectionsMatch", searchText.Trim()); + + public RelayCommand CreateCollectionCommand { get; } + public RelayCommand ToggleViewModeCommand { get; } + + public CollectionsHomeViewModel(CollectionManager manager, CollectionsRootViewModel root, GameCollectionsSettingsViewModel settings) + { + this.manager = manager; + this.actions = root; + this.settings = settings; + + CardsView = new ListCollectionView(Cards) + { + Filter = FilterCard, + CustomSort = Comparer.Create((a, b) => string.Compare(a.Title, b.Title, StringComparison.CurrentCultureIgnoreCase)) + }; + + CreateCollectionCommand = new RelayCommand(() => root.CreateCollection()); + ToggleViewModeCommand = new RelayCommand(ToggleViewMode); + Sync(null); + } + + public CollectionCardViewModel GetCard(Guid id) + { + return Cards.FirstOrDefault(c => c.Id == id); + } + + /// + /// Brings the cards in line with the manager. Only cards listed in + /// are refreshed; null refreshes all of them. + /// + public void Sync(IReadOnlyCollection changedIds) + { + var currentIds = new HashSet(manager.Collections.Select(c => c.Id)); + foreach (var card in Cards.Where(c => !currentIds.Contains(c.Id)).ToList()) + { + Cards.Remove(card); + } + + var existing = Cards.ToDictionary(c => c.Id); + foreach (var collection in manager.Collections) + { + if (!existing.TryGetValue(collection.Id, out var card)) + { + Cards.Add(new CollectionCardViewModel(collection, manager, actions)); + } + else if (changedIds == null || changedIds.Contains(collection.Id)) + { + card.Update(collection); + } + } + + // Titles may have changed, so re-apply sorting and filtering. + var selected = SelectedCard; + CardsView.Refresh(); + SelectedCard = selected != null && Cards.Contains(selected) ? selected : null; + RaiseStateChanged(); + } + + /// + /// Reloads cards whose automatic poster comes from one of the updated games. + /// + public void OnGamesUpdated(ISet gameIds) + { + foreach (var card in Cards.Where(c => c.PosterGameId.HasValue && gameIds.Contains(c.PosterGameId.Value))) + { + var collection = manager.GetCollection(card.Id); + if (collection != null) + { + card.Update(collection); + } + } + } + + private void ToggleViewMode() + { + settings.Settings.ViewMode = IsGridView ? CollectionsViewMode.List : CollectionsViewMode.Grid; + settings.Save(); + OnPropertyChanged(nameof(IsGridView)); + OnPropertyChanged(nameof(IsListView)); + OnPropertyChanged(nameof(ViewModeToggleGlyph)); + OnPropertyChanged(nameof(ViewModeToggleTooltip)); + } + + private bool FilterCard(object obj) + { + var query = searchText.Trim(); + if (query.Length == 0) + { + return true; + } + + var card = (CollectionCardViewModel)obj; + return CultureInfo.CurrentCulture.CompareInfo.IndexOf(card.Title ?? string.Empty, query, CompareOptions.IgnoreCase) >= 0; + } + + private void RaiseStateChanged() + { + OnPropertyChanged(nameof(CountText)); + OnPropertyChanged(nameof(IsEmpty)); + OnPropertyChanged(nameof(HasNoResults)); + OnPropertyChanged(nameof(NoResultsText)); + } + } +} diff --git a/source/GameCollections/ViewModels/CollectionsRootViewModel.cs b/source/GameCollections/ViewModels/CollectionsRootViewModel.cs new file mode 100644 index 0000000..c37eb63 --- /dev/null +++ b/source/GameCollections/ViewModels/CollectionsRootViewModel.cs @@ -0,0 +1,115 @@ +using GameCollections.Services; +using GameCollections.Settings; +using Playnite.SDK; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows; + +namespace GameCollections.ViewModels +{ + /// + /// Navigation state of the Collections sidebar view. It outlives the view itself, so the open + /// page, search text and sort choices are kept when the user leaves and comes back. + /// + public class CollectionsRootViewModel : ObservableObject, ICollectionActions + { + private readonly IPlayniteAPI playniteApi; + private readonly CollectionManager manager; + private readonly DialogService dialogs; + + public CollectionsHomeViewModel Home { get; } + + private object currentPage; + public object CurrentPage { get => currentPage; private set => SetValue(ref currentPage, value); } + + // Shared by all collection pages so the chosen sort carries over between collections. + public GameSortField GameSortField { get; set; } = GameSortField.CollectionOrder; + public bool GameSortDescending { get; set; } + + public CollectionsRootViewModel(IPlayniteAPI playniteApi, CollectionManager manager, DialogService dialogs, GameCollectionsSettingsViewModel settings) + { + this.playniteApi = playniteApi; + this.manager = manager; + this.dialogs = dialogs; + Home = new CollectionsHomeViewModel(manager, this, settings); + CurrentPage = Home; + manager.CollectionsChanged += OnCollectionsChanged; + } + + public void ShowHome() + { + CurrentPage = Home; + } + + public void OpenCollection(Guid id) + { + var card = Home.GetCard(id); + if (card != null) + { + Home.SelectedCard = card; + CurrentPage = new CollectionDetailsViewModel(playniteApi, manager, this, card); + } + } + + public void CreateCollection() + { + var id = dialogs.ShowCreateCollection(); + if (id.HasValue) + { + Home.SelectedCard = Home.GetCard(id.Value); + } + } + + public void EditCollection(Guid id) + { + var collection = manager.GetCollection(id); + if (collection != null) + { + dialogs.ShowEditCollection(collection); + } + } + + public void DeleteCollection(Guid id) + { + var collection = manager.GetCollection(id); + if (collection == null) + { + return; + } + + var answer = playniteApi.Dialogs.ShowMessage( + Loc.Format("LOCGameCollections_DeleteConfirmMessage", collection.Title), + Loc.Get("LOCGameCollections_DeleteConfirmTitle"), + MessageBoxButton.YesNo, + MessageBoxImage.Question); + + if (answer == MessageBoxResult.Yes) + { + manager.DeleteCollection(id); + } + } + + public void OnGamesUpdated(ISet gameIds) + { + Home.OnGamesUpdated(gameIds); + (CurrentPage as CollectionDetailsViewModel)?.OnGamesUpdated(gameIds); + } + + private void OnCollectionsChanged(object sender, CollectionsChangedEventArgs e) + { + Home.Sync(e.ChangedIds); + if (CurrentPage is CollectionDetailsViewModel details) + { + if (manager.GetCollection(details.CollectionId) == null) + { + ShowHome(); + } + else if (e.ChangedIds == null || e.ChangedIds.Contains(details.CollectionId)) + { + details.Reload(); + } + } + } + } +} diff --git a/source/GameCollections/ViewModels/EditCollectionViewModel.cs b/source/GameCollections/ViewModels/EditCollectionViewModel.cs new file mode 100644 index 0000000..5ee6132 --- /dev/null +++ b/source/GameCollections/ViewModels/EditCollectionViewModel.cs @@ -0,0 +1,226 @@ +using GameCollections.Models; +using GameCollections.Services; +using Playnite.SDK; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Windows.Media; + +namespace GameCollections.ViewModels +{ + /// + /// Backs the dialog used both to create a collection and to edit an existing one. + /// + public class EditCollectionViewModel : ObservableObject + { + private const int PreviewDecodeWidth = 320; + private static readonly ILogger logger = LogManager.GetLogger(); + + private readonly IPlayniteAPI playniteApi; + private readonly CollectionManager manager; + private readonly GameCollection existing; + private PosterChange posterChange = PosterChange.Keep; + private string posterSourcePath; + private int previewVersion; + + public Action CloseRequested { get; set; } + public Guid? SavedCollectionId { get; private set; } + + public bool IsEditing => existing != null; + public string WindowTitle => Loc.Get(IsEditing ? "LOCGameCollections_EditCollectionWindowTitle" : "LOCGameCollections_CreateCollectionWindowTitle"); + public int MaxTitleLength => CollectionManager.MaxTitleLength; + public int MaxDescriptionLength => CollectionManager.MaxDescriptionLength; + + private string title = string.Empty; + public string Title + { + get => title; + set + { + SetValue(ref title, value ?? string.Empty); + titleTouched = true; + RaiseValidationChanged(); + } + } + + private string description = string.Empty; + public string Description { get => description; set => SetValue(ref description, value ?? string.Empty); } + + private double rating; + public double Rating + { + get => rating; + set + { + SetValue(ref rating, CollectionManager.NormalizeRating(value)); + OnPropertyChanged(nameof(RatingText)); + } + } + + public string RatingText => Loc.Rating(rating); + + private ImageSource posterPreview; + public ImageSource PosterPreview { get => posterPreview; private set => SetValue(ref posterPreview, value); } + + private string posterHint; + public string PosterHint { get => posterHint; private set => SetValue(ref posterHint, value); } + + public bool HasCustomPoster => + posterChange == PosterChange.Replace || + (posterChange == PosterChange.Keep && existing != null && manager.HasCustomPoster(existing)); + + private string errorMessage; + public string ErrorMessage { get => errorMessage; private set => SetValue(ref errorMessage, value); } + + // A fresh "create" dialog should not open with a "title is required" error. + private bool titleTouched; + public string TitleError => titleTouched || IsEditing ? manager.ValidateTitle(title, existing?.Id) : null; + public bool CanSave => manager.ValidateTitle(title, existing?.Id) == null; + + public RelayCommand SaveCommand { get; } + public RelayCommand CancelCommand { get; } + public RelayCommand BrowsePosterCommand { get; } + public RelayCommand RemovePosterCommand { get; } + + public EditCollectionViewModel(IPlayniteAPI playniteApi, CollectionManager manager, GameCollection existing) + { + this.playniteApi = playniteApi; + this.manager = manager; + this.existing = existing; + + if (existing != null) + { + title = existing.Title; + description = existing.Description ?? string.Empty; + rating = existing.Rating; + } + + SaveCommand = new RelayCommand(Save); + CancelCommand = new RelayCommand(() => CloseRequested?.Invoke(false)); + BrowsePosterCommand = new RelayCommand(BrowsePoster); + RemovePosterCommand = new RelayCommand(RemovePoster); + + _ = UpdatePosterPreviewAsync(); + } + + private void BrowsePoster() + { + var path = playniteApi.Dialogs.SelectImagefile(); + if (string.IsNullOrEmpty(path)) + { + return; + } + + if (!PosterStorage.IsSupportedFile(path)) + { + ErrorMessage = Loc.Get("LOCGameCollections_ErrorPosterFormat"); + return; + } + + // Make sure the image can actually be decoded before accepting it. + if (ImageLoader.Load(path, PreviewDecodeWidth) == null) + { + ErrorMessage = Loc.Get("LOCGameCollections_ErrorPosterUnreadable"); + return; + } + + ErrorMessage = null; + posterChange = PosterChange.Replace; + posterSourcePath = path; + OnPropertyChanged(nameof(HasCustomPoster)); + _ = UpdatePosterPreviewAsync(); + } + + private void RemovePoster() + { + posterChange = PosterChange.Remove; + posterSourcePath = null; + OnPropertyChanged(nameof(HasCustomPoster)); + _ = UpdatePosterPreviewAsync(); + } + + /// + /// Shows the poster the collection will have after saving, including the automatic fallback. + /// + private async Task UpdatePosterPreviewAsync() + { + var version = ++previewVersion; + string path; + if (posterChange == PosterChange.Replace) + { + path = posterSourcePath; + PosterHint = Loc.Get("LOCGameCollections_PosterHintCustom"); + } + else + { + var custom = posterChange == PosterChange.Keep && existing != null ? manager.GetCustomPosterPath(existing) : null; + var automatic = existing != null ? manager.GetGameCoverPath(manager.GetFirstGame(existing)) : null; + if (custom != null) + { + path = custom; + PosterHint = Loc.Get("LOCGameCollections_PosterHintCustom"); + } + else if (automatic != null) + { + path = automatic; + PosterHint = Loc.Get("LOCGameCollections_PosterHintAutomatic"); + } + else + { + path = null; + PosterHint = Loc.Get("LOCGameCollections_PosterHintPlaceholder"); + } + } + + try + { + var image = await ImageLoader.LoadAsync(path, PreviewDecodeWidth); + if (version == previewVersion) + { + PosterPreview = image; + } + } + catch (Exception e) + { + logger.Error(e, "Failed to load poster preview."); + } + } + + private void Save() + { + titleTouched = true; + RaiseValidationChanged(); + if (!CanSave) + { + return; + } + + try + { + if (existing == null) + { + var created = manager.CreateCollection(title, description, rating, posterChange == PosterChange.Replace ? posterSourcePath : null, null); + SavedCollectionId = created.Id; + } + else + { + manager.UpdateCollection(existing.Id, title, description, rating, posterChange, posterSourcePath); + SavedCollectionId = existing.Id; + } + + CloseRequested?.Invoke(true); + } + catch (Exception e) + { + logger.Error(e, "Failed to save collection."); + ErrorMessage = Loc.Format("LOCGameCollections_ErrorSaveCollection", e.Message); + } + } + + private void RaiseValidationChanged() + { + OnPropertyChanged(nameof(TitleError)); + OnPropertyChanged(nameof(CanSave)); + } + } +} diff --git a/source/GameCollections/Views/AddToCollectionView.xaml b/source/GameCollections/Views/AddToCollectionView.xaml new file mode 100644 index 0000000..0da0016 --- /dev/null +++ b/source/GameCollections/Views/AddToCollectionView.xaml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source/GameCollections/Views/SearchBox.xaml.cs b/source/GameCollections/Views/SearchBox.xaml.cs new file mode 100644 index 0000000..b0c40b5 --- /dev/null +++ b/source/GameCollections/Views/SearchBox.xaml.cs @@ -0,0 +1,60 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace GameCollections.Views +{ + /// + /// Text box with a search icon, placeholder text and a clear button. Escape clears the text. + /// + public partial class SearchBox : UserControl + { + public static readonly DependencyProperty TextProperty = DependencyProperty.Register( + nameof(Text), typeof(string), typeof(SearchBox), + new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + + public static readonly DependencyProperty PlaceholderProperty = DependencyProperty.Register( + nameof(Placeholder), typeof(string), typeof(SearchBox), new PropertyMetadata(string.Empty)); + + public string Text + { + get => (string)GetValue(TextProperty); + set => SetValue(TextProperty, value); + } + + public string Placeholder + { + get => (string)GetValue(PlaceholderProperty); + set => SetValue(PlaceholderProperty, value); + } + + public SearchBox() + { + InitializeComponent(); + InputBox.PreviewKeyDown += InputBox_PreviewKeyDown; + } + + public void FocusInput() + { + InputBox.Focus(); + Keyboard.Focus(InputBox); + InputBox.SelectAll(); + } + + private void InputBox_PreviewKeyDown(object sender, KeyEventArgs e) + { + // Only consume Escape when there is something to clear, so dialogs still close on Escape. + if (e.Key == Key.Escape && !string.IsNullOrEmpty(Text)) + { + Text = string.Empty; + e.Handled = true; + } + } + + private void ClearButton_Click(object sender, RoutedEventArgs e) + { + Text = string.Empty; + FocusInput(); + } + } +} diff --git a/source/GameCollections/Views/Styles.xaml b/source/GameCollections/Views/Styles.xaml new file mode 100644 index 0000000..5ca7de4 --- /dev/null +++ b/source/GameCollections/Views/Styles.xaml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source/GameCollections/extension.yaml b/source/GameCollections/extension.yaml new file mode 100644 index 0000000..2226207 --- /dev/null +++ b/source/GameCollections/extension.yaml @@ -0,0 +1,14 @@ +Id: GameCollections_3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54 +Name: Game Collections +Author: X4Lo +Version: 1.0.0 +Module: GameCollections.dll +Type: GenericPlugin +Icon: icon.png +Links: + - Name: GitHub + Url: https://github.com/X4Lo/GameCollections + - Name: Issues Tracker + Url: https://github.com/X4Lo/GameCollections/issues + - Name: User Guide + Url: https://github.com/X4Lo/GameCollections/blob/main/docs/user-guide.md diff --git a/source/GameCollections/icon.png b/source/GameCollections/icon.png new file mode 100644 index 0000000..7656a80 Binary files /dev/null and b/source/GameCollections/icon.png differ