From 690a79b014673e6b8604444d18640afe9c75e4a6 Mon Sep 17 00:00:00 2001 From: X4Lo Date: Mon, 2 Nov 2026 17:39:57 +0000 Subject: [PATCH] feat: add dynamic collections, manual ordering and game details list - Add dynamic collections filled by rules: condition blocks combined with AND/OR, a rule builder with live preview, and automatic updates when games change, on startup and after library updates - Add manual game ordering by drag and drop, context menu and Alt+arrow keys - Show the selected game's collections below the description in the game details view, as a theme element or inserted automatically - Add settings to turn off the automatic list and to hide dynamic collections from it - Add "Open in Collections" to the collection window opened from game details - Migrate collections.json step by step using SchemaVersion, keeping a copy of the old file - Add developer and theme integration docs - Bump version to 1.1.0 --- CHANGELOG.md | 8 + README.md | 11 + docs/architecture.md | 26 +- docs/developer-guide.md | 278 +++++++++ docs/theme-integration.md | 40 ++ docs/user-guide.md | 72 ++- manifests/installer_manifest.yaml | 10 + source/GameCollections/GameCollections.csproj | 5 +- .../GameCollections/GameCollectionsPlugin.cs | 139 ++++- .../GameCollections/Localization/en_US.xaml | 93 ++- source/GameCollections/Models/DynamicRules.cs | 114 ++++ .../GameCollections/Models/GameCollection.cs | 14 + .../Services/CollectionManager.cs | 225 ++++++- .../Services/CollectionRepository.cs | 68 +- .../Services/CollectionsDataMigrator.cs | 117 ++++ .../Services/DetailsViewIntegration.cs | 218 +++++++ .../GameCollections/Services/DialogService.cs | 27 +- .../Services/DynamicCollectionRefresher.cs | 165 +++++ source/GameCollections/Services/RuleEngine.cs | 346 +++++++++++ source/GameCollections/Services/RuleText.cs | 148 +++++ .../Services/SidebarNavigator.cs | 57 ++ .../Settings/GameCollectionsSettings.cs | 16 + .../Settings/GameCollectionsSettingsView.xaml | 13 +- .../ViewModels/AddToCollectionViewModel.cs | 3 +- .../ViewModels/CollectionCardViewModel.cs | 4 + .../ViewModels/CollectionDetailsViewModel.cs | 113 +++- .../ViewModels/CollectionGameViewModel.cs | 13 + .../ViewModels/CollectionsRootViewModel.cs | 50 ++ .../ViewModels/EditCollectionViewModel.cs | 61 +- .../ViewModels/RuleBuilderViewModels.cs | 585 ++++++++++++++++++ .../Views/CollectionDetailsView.xaml | 45 +- .../Views/CollectionDetailsView.xaml.cs | 214 +++++++ .../Views/CollectionsHomeView.xaml | 16 +- source/GameCollections/Views/Converters.cs | 16 + .../Views/EditCollectionView.xaml | 31 +- .../Views/GameCollectionsControl.xaml | 50 ++ .../Views/GameCollectionsControl.xaml.cs | 123 ++++ .../Views/RuleBuilderView.xaml | 194 ++++++ .../Views/RuleBuilderView.xaml.cs | 48 ++ source/GameCollections/Views/Styles.xaml | 13 + source/GameCollections/extension.yaml | 2 +- 41 files changed, 3739 insertions(+), 52 deletions(-) create mode 100644 docs/developer-guide.md create mode 100644 docs/theme-integration.md create mode 100644 source/GameCollections/Models/DynamicRules.cs create mode 100644 source/GameCollections/Services/CollectionsDataMigrator.cs create mode 100644 source/GameCollections/Services/DetailsViewIntegration.cs create mode 100644 source/GameCollections/Services/DynamicCollectionRefresher.cs create mode 100644 source/GameCollections/Services/RuleEngine.cs create mode 100644 source/GameCollections/Services/RuleText.cs create mode 100644 source/GameCollections/Services/SidebarNavigator.cs create mode 100644 source/GameCollections/ViewModels/RuleBuilderViewModels.cs create mode 100644 source/GameCollections/Views/GameCollectionsControl.xaml create mode 100644 source/GameCollections/Views/GameCollectionsControl.xaml.cs create mode 100644 source/GameCollections/Views/RuleBuilderView.xaml create mode 100644 source/GameCollections/Views/RuleBuilderView.xaml.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cbf8a7..4d6fcd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,14 @@ Every release must also be added to [manifests/installer_manifest.yaml](manifests/installer_manifest.yaml), which is what Playnite reads to offer updates. +## 1.1.0 – 2026-11-02 + +- Added: Reorder games in a collection by dragging, from the right-click menu, or with Alt+arrow keys. +- Added: Dynamic collections, filled automatically by rules made of condition blocks combined with AND/OR. +- Added: A list of the selected game's collections in the game details view. +- Added: Settings to turn that list off, and to show or hide dynamic collections in it. +- Added: Automatic migrations of the data file, based on its `SchemaVersion`. + ## 1.0.0 – 2026-10-30 - Initial release. diff --git a/README.md b/README.md index d7b3025..d01fd13 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,11 @@ - **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. +- **Manual order**: drag games into the order you want, or use the right-click menu or Alt+arrow keys. +- **Dynamic collections** fill themselves from your rules, for example *Platform is PS1 and Genres include Indie*. + Combine conditions into blocks, join blocks with AND or OR, and see the matching games live while you edit. +- **Game details integration**: see the selected game's collections in the details view, with any theme that + keeps Playnite's standard layout. Themes can also choose where the list goes. - **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. @@ -48,8 +53,14 @@ Requires a recent Playnite 10 release (extension SDK 6.11 or later), in Desktop - [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. +- [Developer guide](docs/developer-guide.md): how it works in depth, the data format, adding rule fields, testing and releasing. - [Changelog](CHANGELOG.md) +## Theme Integration + +Theme authors can choose where the collections list appears and bind to the extension's settings. +See [Theme integration](docs/theme-integration.md). + ## Building ``` diff --git a/docs/architecture.md b/docs/architecture.md index c21a037..f363e6b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,5 +1,7 @@ # Architecture and development +For how it works in depth and how to change it, see the [developer guide](developer-guide.md). + ## Repository layout ``` @@ -19,7 +21,7 @@ GameCollections/ ├─ 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 +├─ docs/ user guide, developer guide, theme integration ├─ screenshots/ images for the README and add-on database ├─ .github/ CI build/release workflow, issue template └─ dist/ build output: the .pext package (git-ignored) @@ -59,7 +61,14 @@ To try a build in Playnite, open the `.pext` file (Playnite installs it after a | `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`. | +| `CollectionManager` | All collection rules: validation, unique titles, create/update/delete, membership changes in one save, ordering, applying dynamic matches, the game-to-collections lookup, poster resolution, pruning deleted games. Raises `CollectionsChanged`. | +| `CollectionsDataMigrator` | Upgrades `collections.json` step by step from its `SchemaVersion` to the current one. | +| `SidebarNavigator` | Switches to the Collections section through Playnite's internals, as the SDK has no API for it. | +| `RuleEngine` | Compiles dynamic rules into a predicate over games. Pure and thread-safe. | +| `DynamicCollectionRefresher` | Decides when dynamic collections are evaluated: debounced game changes, delayed startup and library-update refreshes on a background thread, an hourly refresh for time-based rules. | +| `RuleText` | Field and operator names, the values offered for each field, and rule summaries. | +| `GameCollectionsControl` | Lists the selected game's collections. Themes can place it as a custom element. | +| `DetailsViewIntegration` | For themes that don't place that element: inserts one instance below `PART_ElemDescription` (or `PART_ElemNotes`) in the visual tree. Stands aside if the theme has its own, skips `Grid` parents, and only searches the tree after a selection or view change, up to 3 times. | | `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. | @@ -70,7 +79,7 @@ To try a build in Playnite, open the `.pext` file (Playnite installs it after a ```json { - "SchemaVersion": 1, + "SchemaVersion": 2, "Collections": [ { "Id": "guid", @@ -79,6 +88,7 @@ To try a build in Playnite, open the `.pext` file (Playnite installs it after a "Rating": 8.5, "PosterFileName": "guid_ticks.png", "GameIds": ["game guid", "..."], + "Rules": null, "CreatedAt": "2026-10-30T12:00:00Z", "ModifiedAt": "2026-10-30T12:00:00Z" } @@ -88,6 +98,16 @@ To try a build in Playnite, open the `.pext` file (Playnite installs it after a Only game IDs are stored. Missing games are removed on startup and whenever Playnite deletes a game. +### Dynamic collections + +`Rules` on a collection makes it dynamic (null means manual), and `GameIds` caches its latest matches. Pages and the +game details therefore never search the library. Rules store IDs rather than names, so renaming a tag keeps them +working. Enums are stored as numbers, so existing values must not be renumbered. + +Evaluation only reads in-memory game fields. A change to some games tests only those games, and full searches run on +a background thread and are discarded if the rules were edited meanwhile. In a synthetic test, a full search of 20 +collections over 20,000 games took under a second. The data file is only written when membership really changed. + ### Performance Covers and posters are decoded at display size, off the UI thread, and cached. On a collection's page, diff --git a/docs/developer-guide.md b/docs/developer-guide.md new file mode 100644 index 0000000..39dad86 --- /dev/null +++ b/docs/developer-guide.md @@ -0,0 +1,278 @@ +# Developer guide + +How Game Collections works and how to change it. For a short overview of the layout and components, see +[architecture.md](architecture.md). For behaviour as users see it, see [user-guide.md](user-guide.md). + +## Getting started + +You need Windows and a .NET SDK (6.0 or later recommended). The .NET Framework 4.6.2 reference assemblies come from +NuGet, so no targeting pack is needed. The project targets `net462` with C# 7.3, matching Playnite extensions, and +references `PlayniteSDK` 6.11.0. + +``` +dotnet build source/GameCollections.sln -c Debug +``` + +To run it, add `source/GameCollections/bin/Debug` under Playnite's *Settings → For developers → Custom extension +folders* and restart Playnite after each build. A Release build also creates the `.pext` in `dist/`. + +Logs go to Playnite's `extensions.log`. Data is in `ExtensionsData\3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54`. + +## How the pieces fit together + +``` +GameCollectionsPlugin Playnite entry point and event wiring + ├─ CollectionManager the only code that changes collections + │ ├─ CollectionRepository collections.json: load, recover, atomic save + │ ├─ PosterStorage Posters\ folder + │ └─ RuleEngine rules -> predicate (static, no state) + ├─ DynamicCollectionRefresher when dynamic collections are re-evaluated + ├─ DetailsViewIntegration inserts the list into themes without the element + ├─ DialogService dialogs in Playnite-created windows + └─ CollectionsRootViewModel sidebar state; created on first use, kept for the session + ├─ CollectionsHomeViewModel -> CollectionCardViewModel + └─ CollectionDetailsViewModel -> CollectionGameViewModel +``` + +### Rules to keep + +- **All changes go through `CollectionManager`.** Each change saves and then raises `CollectionsChanged` with the + affected IDs. View models and `GameCollectionsControl` react to that event, and don't update themselves. +- **`CollectionManager` is UI-thread only.** Playnite's database events can arrive on other threads, so the plugin + sends them through `RunOnUiThread`. Only the static `CollectionManager.FindMatches` and `RuleEngine` are safe on a + background thread. +- **Collections store game IDs only.** Metadata is always read from Playnite's database. +- **Views use theme resources only**, such as `TextBrush`, `NormalBrush` and `FontIcoFont`, through `DynamicResource`, + so light and dark themes both work. The one fixed colour is the dynamic badge in `Styles.xaml`. +- **No user-visible text in code or XAML.** Add a `LOCGameCollections_*` key to `Localization/en_US.xaml`, and read it + with `Loc` in code or `DynamicResource` in XAML. + +## Startup and lifecycle + +1. **Constructor:** creates settings, services and the dialog host, and registers settings and custom element support. + The game database isn't ready yet, so nothing is loaded. +2. **`OnApplicationStarted`:** loads collections, prunes games no longer in the library, deletes unreferenced posters, + subscribes to database events, then starts the refresher and, in Desktop mode, the details integration. +3. **`GetSidebarItems` → `Opened`:** builds a new view each time around the same `CollectionsRootViewModel`. That is + why the open page, search and sort survive leaving the sidebar page. +4. **`OnApplicationStopped`:** unsubscribes and stops the timers. + +## Data + +### collections.json + +`CollectionsDataFile` holds `SchemaVersion` and a list of `GameCollection`. See the example in +[architecture.md](architecture.md#data-model). + +**Saving** (`CollectionRepository.Save`) writes a temp file, then swaps it in with `File.Replace`, keeping the previous +version as `collections.json.bak`. It falls back to copying where `File.Replace` isn't supported. + +**Loading** moves an unreadable file aside as `collections.unreadable-.json` so a later save can't overwrite +it, then tries the backup, and returns a warning that the plugin shows as a notification. `Sanitize` repairs damaged +records, such as missing IDs, duplicate IDs, or out-of-range ratings. + +### Versioning and migrations + +The file has a `SchemaVersion`, and `CollectionsDataMigrator` runs on every load, before the JSON becomes model objects: + +1. It reads `SchemaVersion`, or assumes 1 if it's missing. +2. It applies each step from that version up to `CurrentVersion`, in order, so someone updating from 1 to 7 runs + 1→2, 2→3 and so on. +3. `CollectionRepository` copies the original to `collections.json.v.bak` and saves the migrated data. + +If a step fails or is missing, the file counts as unreadable: it's moved aside and the normal backup is tried, also +through the migrator. A file from a **newer** version isn't changed by the migrator. It loads as well as it can, a copy +is kept, and the user gets a warning, because properties this version doesn't know about are lost on the next save. + +**To change the format:** + +1. Change the model, and repair or default the value in `Sanitize`. +2. Increase `CollectionsDataMigrator.CurrentVersion`. +3. Add a step to `Steps` with `FromVersion` set to the previous version. It edits the raw `JObject`: + + ```csharp + // 2 -> 3 (extension 1.2.0): renamed Rating to Score. + new DataMigrationStep(2, data => + { + foreach (var collection in data["Collections"]) + { + collection["Score"] = collection["Rating"]; + ((JObject)collection).Remove("Rating"); + } + }) + ``` + +4. Add a line to the version history below. + +Steps use raw JSON so they keep working after the model changes. Never edit a released step, rename a property without +a step, or renumber an enum value, because enums are stored as numbers. A new property with a safe default still needs +a version bump only if old files need converting, but bumping keeps the history clear. + +Version history: **1** was the initial format (extension 1.0.0); **2** added `GameCollection.Rules` (extension 1.1.0). + +`config.json` (settings) isn't versioned. Playnite reads it directly, and new settings simply take their defaults. + +### Settings + +`GameCollectionsSettings` is saved by Playnite to `config.json`. Add a property using `SetValue`, and bind to +`Settings.` in `GameCollectionsSettingsView.xaml`. Mark state that shouldn't be saved with `[DontSerialize]`. +Themes can read these properties through `{PluginSettings Plugin=GameCollections, Path=}`. +`SettingsChanged` fires after the settings dialog is saved or cancelled. + +## Manual order + +The order is simply the order of `GameCollection.GameIds`, which is also what the automatic poster uses (first game). +`CollectionManager.MoveGames(collectionId, gameIds, anchorId, after)` is the single move operation. Selected games keep +their relative order. + +On the page, `CollectionDetailsViewModel.CanReorder` requires the *Collection order, ascending* sort, because a moved +game wouldn't stay put in any other. Moves relate to *visible* games, so with a filter active, "move earlier" passes the +previous visible game. + +Dragging is in `CollectionDetailsView.xaml.cs`. A click on an already selected game in a multi-selection delays +collapsing the selection until the mouse button is released, otherwise several games couldn't be dragged. +`FindDropTarget` picks the closest tile on the pointer's row and which side of it to use. + +## Dynamic collections + +A collection is dynamic when `Rules` is not null. `GameIds` stores the latest matches, so no page has to search the +library. + +### Evaluation + +`RuleEngine.Compile(rules, now)` returns a `Func`: + +- Conditions in a block are ANDed. +- Blocks combine strictly from top to bottom using each block's `Join`, without AND taking priority over OR. This + matches how they read in the editor. +- Hidden games never match. +- Rules that aren't complete compile to "match nothing", so damaged data can't fill a collection with the whole library. +- Compile once and reuse the predicate. It prepares `HashSet`s and parsed dates up front. + +`MergeMatches` applies results: games still matching keep their position, which preserves manual order, and new ones go +at the end. + +### When it runs + +`DynamicCollectionRefresher` owns the timing: + +| Trigger | Method | Scope and thread | +|---|---|---| +| Collection created or edited | `CreateCollection` / `UpdateCollection` | One collection, UI thread | +| Game added or updated | `NotifyGamesChanged` → `ApplyGameChanges` | Changed games only, 1 s debounce, UI thread | +| Startup | `Start` → `RefreshAllAsync` | All, after 5 s, background | +| Library update finished | `ScheduleFullRefresh` | All, after 1 s, background | +| Hourly, if a rule uses relative days | `RefreshAllAsync` | All, background | +| **Refresh now** button | `RefreshCollection` | One collection, UI thread | + +Two details prevent wrong results from a background search: + +- Each result carries the `DynamicRules` object it used. `ApplyMatches` skips it if the collection now has a different + one, because every save of the editor creates a new object. +- Game changes arriving during a search stay queued and are applied after its results. + +### Adding a rule field + +1. Add it to the end of `RuleField` in `Models/DynamicRules.cs`. +2. In `RuleEngine`, update `GetValueKind` and add it to `GetItemIds` or `GetNumber` (or the date selection in + `CompileDate`). +3. For a list field, return its items from `RuleText.LoadItems`. +4. Add it to `FieldOrder` in `RuleConditionViewModel`, plus `UnitText` if it has a unit. +5. Add `LOCGameCollections_RuleField` to the strings. The key is built from the enum name. + +`RuleText.Describe` and the editor pick it up from there. + +### Adding an operator + +Add it to the end of `RuleOperator`, offer it in `RuleEngine.GetOperators`, handle it in the matching `Compile*` method +and in `IsComplete`, and add `LOCGameCollections_RuleOperator`. If it needs different inputs, adjust the +`Show*` properties of `RuleConditionViewModel`, `ToModel` and `RuleBuilderView.xaml`. + +### Editor + +`DynamicRulesViewModel` → `RuleBlockViewModel` → `RuleConditionViewModel`. Values stay as text while editing, and +`ToModel()` produces the saved form, so `RuleEngine.IsComplete` is the one source of validation. The preview searches +the library after a 250 ms pause, on the UI thread, which is fast enough at the sizes tested (see Performance). + +## Game details + +For theme authors, see [theme-integration.md](theme-integration.md). `GameCollectionsControl` is a `PluginUserControl`. It reads `GameContext`, uses the cached +`CollectionManager.GetCollectionsForGame` lookup, and collapses when there's nothing to show. It subscribes to events +only while loaded, so a discarded instance can be collected. + +It reaches the screen in one of two ways: + +1. **Custom element.** A theme adds ``, and Playnite + calls `GetGameViewControl`. This is the supported route and works in Desktop mode only. +2. **`DetailsViewIntegration`.** Playnite has no API for adding to a theme, so this walks the main window's visual tree + for `PART_ElemDescription`, or else `PART_ElemNotes`, and inserts one control after it. + +The integration's safeguards: + +- It stands aside when it finds a theme-placed control (`IsInjected` is false). +- It doesn't insert into a `Grid`, which would need a new row, or an items host. +- It searches only after a game selection, a view change or a settings change, up to 3 times each, and skips + `ListBoxItem`s, which hold most of the tree. A 1 second timer only compares `ActiveDesktopView`. +- Every error is caught and logged, and stops further searching until the next trigger. + +**This relies on Playnite's internal part names.** Check it after Playnite updates. The default layouts are +`Themes/Desktop/Default/Views/DetailsViewGameOverview.xaml` and `GridViewGameOverview.xaml` in Playnite's repository. + +Clicking a collection calls `CollectionsRootViewModel.OpenCollectionInWindow`. The page uses `CloseWindow` to know it's +in a window, where **Open in Collections** replaces **Select in library**. That button opens the page in the sidebar +view's state, closes the window, then calls `SidebarNavigator.TryActivate`. + +The SDK has no way to switch sidebar views, so `SidebarNavigator` uses reflection to run the `Command` of the matching +entry in `SidebarItems` on the main window's view model, as Playnite's `SwitchToLibraryView` does. **This relies on +Playnite's internals, so check it after Playnite updates.** If it fails, a notification tells the user to click +Collections, and the page is already open there. + +## Images + +`ImageLoader` decodes at the size needed, off the UI thread, with limited concurrency, and returns frozen bitmaps. Its +cache key includes the path, width, modified time and file size, so a changed file is reloaded. Pass the display width +to it rather than loading full-size artwork. Game covers on a collection's page load only near the viewport. + +## Performance + +Measured in the test harness, not in Playnite: 20 full searches of 20,000 synthetic games took about 0.85 s in total. +Keep these costs in mind: + +- Nothing should scan the library on the UI thread when a game is selected. +- Writes happen only when something changed, because `collections.json` is rewritten in full each time. +- Don't subscribe to `ItemUpdated` for per-game work without a debounce. Library updates send many at once. + +## Testing + +**There's no test project in the repository yet.** The checks so far ran in a throwaway harness outside it, against a +fake Playnite API built with `RealProxy`. Its limits: + +- `Playnite.SDK.Data.Serialization` and `API.Instance` are normally set by Playnite, so any test host has to supply + them. The SDK alone throws `NullReferenceException`. +- It doesn't load a real theme, so screenshots have wrong glyphs and default button colours. Theming can only be judged + in Playnite. +- Real mouse drag-and-drop and insertion into real theme layouts can't be tested there. + +Before a release, check these by hand in Playnite: + +1. Create, edit and delete manual and dynamic collections, in a light and a dark theme. +2. Open the value picker in the rule builder, search, and tick several values. +3. Drag one game and several games, including scrolling while dragging. +4. Select games in Details and Grid view, and switch between views; the list should appear once, below the description. + Click a collection there, then **Open in Collections**. +5. Toggle both details view settings. +6. Change a game's tags, and play a game, and watch a dynamic collection update. + +## Known issues to watch + +- `ApplicationMode` other than Desktop is untested, and the views need Desktop theme styles. +- A search of the library in the rule preview runs on the UI thread. Very large libraries could feel it while editing. +- Only `en_US` strings exist so far. + +## Releasing + +Update the version in both `GameCollections.csproj` and `extension.yaml`, add it to `CHANGELOG.md`, and add a new entry +at the top of `Packages` in `manifests/installer_manifest.yaml`. Pushing a `v*` tag makes the +[workflow](../.github/workflows/build.yml) build the `.pext` and create the release. Check the manifest with +`Toolbox.exe verify installer `. `PackageUrl` must match the file name exactly, which includes the extension ID and +the version with underscores. diff --git a/docs/theme-integration.md b/docs/theme-integration.md new file mode 100644 index 0000000..fc27f83 --- /dev/null +++ b/docs/theme-integration.md @@ -0,0 +1,40 @@ +# Theme integration + +For theme authors. Everything here is optional: Game Collections works in themes that do none of it. + +## Collections list + +Shows the collections of the selected game, each with its poster. Clicking one opens it. The list collapses itself when +the game is in no collection or no single game is selected. + +By default, the extension inserts the list below the game description in any theme that keeps Playnite's standard +description or notes section. To choose the position yourself, add this anywhere in a game details view: + +```xml + +``` + +When your theme has this element, the extension doesn't insert a second list, and your list stays visible even if the +user turns off **Show collections in details view**. The list shown there includes dynamic collections unless the user +turns off **Display dynamic collections in details view**. + +## Settings available to themes + +Bind to these with `PluginSettings`: + +| Path | Type | Meaning | +|---|---|---| +| `IsDetailsControlVisible` | `bool` | The list currently has collections to show. Use it to hide a surrounding header or panel. | +| `ShowDynamicCollectionsInDetails` | `bool` | The user's choice for listing dynamic collections. | +| `AddDetailsListToAnyTheme` | `bool` | The user's choice for inserting the list automatically. | + +```xml + + + +``` + +## Compatibility + +Keep the element name and these setting names stable across themes: they're treated as public, and any future +changes or new integration points will be listed in this file. diff --git a/docs/user-guide.md b/docs/user-guide.md index 7a5022c..bf64690 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -37,17 +37,80 @@ Deleting a collection never deletes or changes any games. 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. +## Dynamic collections + +A dynamic collection fills itself from rules. To make one, choose **Dynamic** under **Type** when creating or +editing a collection. + +- A **block** is a group of conditions. A game must meet **every** condition in a block. +- Between blocks, choose **AND** or **OR**. Blocks combine from top to bottom, so + *A OR B AND C* means *(A or B) and C*. +- The bar at the bottom shows how many games currently match, and some of their names. +- Hidden games are never included. + +| You can filter by | Conditions | +|---|---| +| Name | includes, does not include | +| Platform, genres, developers, publishers, categories, features, tags, series | includes any of, all of or none of; is empty | +| Completion status | includes any of or none of; is empty | +| Release date, last played | after, before, between; in the last or older than a number of days; has no date | +| User, critic and community score | at least, at most, between; is empty | +| Time played (hours), play count | at least, at most, between | + +Dates can be a year, a month or a day (`2005`, `2005-03` or `2005-03-14`). *After 2005* starts at 2006, and +*between 1995 and 1999* includes both years. + +**Example:** Block 1: *Platform includes any of Windows PC* and *Categories includes any of Boomer shooter*. +OR Block 2: *Tags includes any of Action*. + +**When it updates** (nothing you need to do): + +| When | What is checked | +|---|---| +| You create or edit the collection | That collection, right away | +| A game is added or changed, including after playing it | Only those games, about a second later | +| A game is removed from Playnite | Removed from collections right away | +| Playnite starts (after 5 seconds) and after a library update | Every dynamic collection, in the background | +| Every hour, if a rule uses "in the last" or "older than" days | Every dynamic collection, in the background | +| You click **Refresh now** on its page | That collection, right away | + +You can't add or remove a dynamic collection's games by hand, but you can reorder them; the order is kept when it +updates, and new games go at the end. Switching a dynamic collection to manual keeps its current games. Switching a +manual collection to dynamic replaces its games with the matches, and the dialog warns you first. + +If a tag, genre or similar is deleted from Playnite, it stops counting in rules. If a condition is left with no +values, the rules match nothing until you edit them, so a broken rule can never pull in your whole library. + +## Game details + +The selected game's collections appear below the description in Playnite's game details, each with its poster. +Click one to open it in a window, where **Open in Collections** takes you to its page in the Collections section. The list is hidden when the game is in no collection or several games are selected. + +In the extension's settings: + +- **Show collections in details view** turns the automatic list on or off. +- **Display dynamic collections in details view** lists dynamic collections as well as manual ones. + +The list is added to the theme's layout automatically, because Playnite has no official way to do this. It needs the +theme to keep Playnite's standard description or notes section in a simple panel, so a heavily customized theme may +not show it. List view has no details panel, so it doesn't appear there. Theme authors can see +[Theme integration](theme-integration.md). + ## A collection's page - Header with poster, title, rating, game count and description, plus **Edit**, **Select in library** and **Delete**. + Dynamic collections also show their rules and a **Refresh now** button. - **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. +- **Sort** by collection order (the order you arranged, or 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). + Not available in dynamic collections. +- **Reorder** while sorted by collection order, ascending: drag games (several at once if selected), use + **Move to top / earlier / later / to end** in the right-click menu, or press **Alt+arrow keys**. ## Where data is stored @@ -56,6 +119,7 @@ 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. +- `collections.json.v.bak` – a copy from before an update changed the file's format. 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. @@ -67,5 +131,9 @@ 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 have no official way to switch to their own sidebar view, so **Open in Collections** uses Playnite's + internals. If that ever stops working, the page is still ready, and a notification tells you to click Collections. +- Extensions have no official way to add to a theme's details view, so the list is inserted into the theme's layout. + It may not appear in heavily customized themes. - 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/installer_manifest.yaml b/manifests/installer_manifest.yaml index 2b15b37..85634a7 100644 --- a/manifests/installer_manifest.yaml +++ b/manifests/installer_manifest.yaml @@ -1,5 +1,15 @@ AddonId: GameCollections_3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54 Packages: + - Version: 1.1.0 + RequiredApiVersion: 6.11.0 + ReleaseDate: 2026-11-02 + PackageUrl: https://github.com/X4Lo/GameCollections/releases/download/v1.1.0/GameCollections_3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54_1_1_0.pext + Changelog: + - 'Added: Reorder games in a collection by dragging, from the right-click menu, or with Alt+arrow keys' + - 'Added: Dynamic collections, filled automatically by rules made of condition blocks combined with AND/OR' + - 'Added: List of the selected game''s collections in the game details view' + - 'Added: Settings to turn that list off, and to show or hide dynamic collections in it' + - 'Added: Automatic migrations of the data file between versions' - Version: 1.0.0 RequiredApiVersion: 6.11.0 ReleaseDate: 2026-10-30 diff --git a/source/GameCollections/GameCollections.csproj b/source/GameCollections/GameCollections.csproj index c52c50b..52d2e7e 100644 --- a/source/GameCollections/GameCollections.csproj +++ b/source/GameCollections/GameCollections.csproj @@ -7,7 +7,7 @@ GameCollections GameCollections 7.3 - 1.0.0 + 1.1.0 Game Collections false false @@ -16,6 +16,9 @@ + + diff --git a/source/GameCollections/GameCollectionsPlugin.cs b/source/GameCollections/GameCollectionsPlugin.cs index cfd631c..8a99754 100644 --- a/source/GameCollections/GameCollectionsPlugin.cs +++ b/source/GameCollections/GameCollectionsPlugin.cs @@ -10,7 +10,9 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Windows; using System.Windows.Controls; +using System.Windows.Threading; namespace GameCollections { @@ -18,10 +20,18 @@ namespace GameCollections { private static readonly ILogger logger = LogManager.GetLogger(); + private const string SourceName = "GameCollections"; + private const string CollectionsControlName = "CollectionsControl"; + private readonly GameCollectionsSettingsViewModel settings; private readonly CollectionManager manager; private readonly DialogService dialogs; + private DynamicCollectionRefresher refresher; + private DetailsViewIntegration detailsIntegration; private CollectionsRootViewModel rootViewModel; + private SidebarItem sidebarItem; + + public GameCollectionsSettingsViewModel Settings => settings; public override Guid Id { get; } = Guid.Parse("3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54"); @@ -39,6 +49,18 @@ namespace GameCollections new CollectionRepository(dataDirectory), new PosterStorage(Path.Combine(dataDirectory, "Posters"))); dialogs = new DialogService(api, manager); + + AddSettingsSupport(new AddSettingsSupportArgs + { + SourceName = SourceName, + SettingsRoot = $"{nameof(Settings)}.{nameof(Settings.Settings)}" + }); + + AddCustomElementSupport(new AddCustomElementSupportArgs + { + ElementList = new List { CollectionsControlName }, + SourceName = SourceName + }); } public override void OnApplicationStarted(OnApplicationStartedEventArgs args) @@ -67,12 +89,56 @@ namespace GameCollections PlayniteApi.Database.Games.ItemCollectionChanged += Games_ItemCollectionChanged; PlayniteApi.Database.Games.ItemUpdated += Games_ItemUpdated; + + RunOnUiThread(() => + { + refresher = new DynamicCollectionRefresher(PlayniteApi, manager, PlayniteApi.MainView.UIDispatcher ?? Dispatcher.CurrentDispatcher); + refresher.Start(); + + if (PlayniteApi.ApplicationInfo.Mode == ApplicationMode.Desktop) + { + detailsIntegration = new DetailsViewIntegration( + PlayniteApi, + settings, + () => new GameCollectionsControl(manager, settings, OpenCollectionInWindow), + () => Application.Current?.MainWindow, + PlayniteApi.MainView.UIDispatcher ?? Dispatcher.CurrentDispatcher); + detailsIntegration.Start(); + } + }); + } + + public override void OnGameSelected(OnGameSelectedEventArgs args) + { + var games = args.NewValue; + RunOnUiThread(() => detailsIntegration?.OnGameSelected(games)); + } + + public override void OnLibraryUpdated(OnLibraryUpdatedEventArgs args) + { + RunOnUiThread(() => refresher?.ScheduleFullRefresh(TimeSpan.FromSeconds(1))); + } + + public override Control GetGameViewControl(GetGameViewControlArgs args) + { + // The control relies on Desktop mode's theme styles, and collections are a Desktop mode feature. + if (args.Name != CollectionsControlName || PlayniteApi.ApplicationInfo.Mode != ApplicationMode.Desktop) + { + return null; + } + + return new GameCollectionsControl(manager, settings, OpenCollectionInWindow); } public override void OnApplicationStopped(OnApplicationStoppedEventArgs args) { PlayniteApi.Database.Games.ItemCollectionChanged -= Games_ItemCollectionChanged; PlayniteApi.Database.Games.ItemUpdated -= Games_ItemUpdated; + RunOnUiThread(() => + { + refresher?.Stop(); + detailsIntegration?.Stop(); + }); } public override IEnumerable GetGameMenuItems(GetGameMenuItemsArgs args) @@ -98,7 +164,7 @@ namespace GameCollections public override IEnumerable GetSidebarItems() { - yield return new SidebarItem + sidebarItem = sidebarItem ?? new SidebarItem { Title = Loc.Get("LOCGameCollections_SidebarTitle"), Type = SiderbarItemType.View, @@ -107,14 +173,11 @@ namespace GameCollections // 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 }; + return new CollectionsRootView { DataContext = GetRootViewModel() }; } }; + + yield return sidebarItem; } public override ISettings GetSettings(bool firstRunSettings) @@ -129,24 +192,74 @@ namespace GameCollections private void Games_ItemCollectionChanged(object sender, ItemCollectionChangedEventArgs e) { - if (e.RemovedItems == null || e.RemovedItems.Count == 0) + if (e.RemovedItems != null && e.RemovedItems.Count > 0) { - return; + var removedIds = e.RemovedItems.Select(g => g.Id).ToList(); + RunOnUiThread(() => manager.RemoveGamesFromAllCollections(removedIds)); } - var removedIds = e.RemovedItems.Select(g => g.Id).ToList(); - RunOnUiThread(() => manager.RemoveGamesFromAllCollections(removedIds)); + if (e.AddedItems != null && e.AddedItems.Count > 0) + { + var addedIds = e.AddedItems.Select(g => g.Id).ToList(); + RunOnUiThread(() => refresher?.NotifyGamesChanged(addedIds)); + } } private void Games_ItemUpdated(object sender, ItemUpdatedEventArgs e) { - if (rootViewModel == null || e.UpdatedItems == null || e.UpdatedItems.Count == 0) + if (e.UpdatedItems == null || e.UpdatedItems.Count == 0) { return; } var updatedIds = new HashSet(e.UpdatedItems.Select(u => u.NewData.Id)); - RunOnUiThread(() => rootViewModel.OnGamesUpdated(updatedIds)); + RunOnUiThread(() => + { + rootViewModel?.OnGamesUpdated(updatedIds); + refresher?.NotifyGamesChanged(updatedIds); + }); + } + + private CollectionsRootViewModel GetRootViewModel() + { + if (rootViewModel == null) + { + rootViewModel = new CollectionsRootViewModel(PlayniteApi, manager, dialogs, settings) + { + SwitchToSidebarView = SwitchToSidebarView + }; + } + + return rootViewModel; + } + + private void SwitchToSidebarView(Guid collectionId) + { + // Queued so the collection's modal window has finished closing before the main view changes. + (PlayniteApi.MainView.UIDispatcher ?? Dispatcher.CurrentDispatcher).BeginInvoke((Action)(() => + { + if (!SidebarNavigator.TryActivate(Application.Current?.MainWindow, sidebarItem)) + { + // The page is already showing in the sidebar view, so one click gets there. + PlayniteApi.Notifications.Add(new NotificationMessage( + "GameCollections_OpenManually", + Loc.Format("LOCGameCollections_OpenCollectionsManually", manager.GetCollection(collectionId)?.Title), + NotificationType.Info)); + } + })); + } + + private void OpenCollectionInWindow(Guid collectionId) + { + try + { + GetRootViewModel().OpenCollectionInWindow(collectionId); + } + catch (Exception e) + { + logger.Error(e, $"Failed to open collection {collectionId}."); + PlayniteApi.Dialogs.ShowErrorMessage(e.Message, Loc.Get("LOCGameCollections_PluginName")); + } } private void RunOnUiThread(Action action) diff --git a/source/GameCollections/Localization/en_US.xaml b/source/GameCollections/Localization/en_US.xaml index 5ab7ffe..07b0a40 100644 --- a/source/GameCollections/Localization/en_US.xaml +++ b/source/GameCollections/Localization/en_US.xaml @@ -4,7 +4,6 @@ Game Collections Collections Add to Collection… - There are no settings for Game Collections yet. Collections @@ -76,6 +75,97 @@ Save Cancel + + Type + Manual: you choose the games + Dynamic: filled automatically by rules + Dynamic + Saving replaces this collection's current games with the games matching the rules. + Saving keeps the current games, but they will no longer update automatically. + Refresh now + Check the whole library against the rules again + Rules: {0} + No games match these rules + Edit the collection to change its rules. It updates by itself when a game starts to match. + Block {0} + A game must meet every condition in this block + Add condition + Remove condition + Add block + Remove block + AND + OR + Blocks are combined in order, from top to bottom. Hidden games are never included. + and + or + Field + Condition + Choose… + Change… + Search + There is nothing to choose from in your library. + YYYY, YYYY-MM or YYYY-MM-DD + Enter a date as YYYY, YYYY-MM or YYYY-MM-DD. + Enter a number of 0 or more. + The second value must not be lower than the first. + Complete every condition to see the matching games. + Currently matches {0} + days + hours + times + out of 100 + Name + Platform + Genres + Developers + Publishers + Categories + Features + Tags + Series + Completion status + Release date + Last played + User score + Critic score + Community score + Time played + Play count + includes + does not include + includes any of + includes all of + includes none of + at least + at most + between + before + after + in the last + older than + is empty + has no date + + + Move to top + Move earlier + Move later + Move to end + Drag games to reorder them + To reorder, sort by Collection order, ascending + + + Collections + Display dynamic collections in details view + When off, game details only list manual collections. + Show collections in details view + Adds the list below the game description. Turn this off if it looks wrong in your theme. + + + Open in Collections + Go to this collection's page in the Collections section + "{0}" is open in Collections. Click Collections in the sidebar to see it. + A title is required. The title can be at most {0} characters long. @@ -88,5 +178,6 @@ 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. + Your collections were saved by a newer version of Game Collections. Update the extension to avoid losing data. A copy of the file was kept at "{0}". Game Collections could not read its data file. The unreadable file was kept at "{0}". diff --git a/source/GameCollections/Models/DynamicRules.cs b/source/GameCollections/Models/DynamicRules.cs new file mode 100644 index 0000000..cd73a78 --- /dev/null +++ b/source/GameCollections/Models/DynamicRules.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; + +namespace GameCollections.Models +{ + // The enums below are stored in the data file by number, so existing values must never be renumbered. + + public enum RuleField + { + Name = 0, + Platform = 1, + Genre = 2, + Developer = 3, + Publisher = 4, + Category = 5, + Feature = 6, + Tag = 7, + Series = 8, + CompletionStatus = 9, + ReleaseDate = 10, + LastPlayed = 11, + UserScore = 12, + CriticScore = 13, + CommunityScore = 14, + TimePlayed = 15, + PlayCount = 16 + } + + public enum RuleOperator + { + Contains = 0, + NotContains = 1, + IncludesAny = 2, + IncludesAll = 3, + Excludes = 4, + AtLeast = 5, + AtMost = 6, + Between = 7, + Before = 8, + After = 9, + InLastDays = 10, + OlderThanDays = 11, + IsEmpty = 12 + } + + public enum BlockJoin + { + And = 0, + Or = 1 + } + + public enum RuleValueKind + { + Text, + Items, + Number, + Date + } + + /// + /// One test on a game. Which value members are used depends on the field and operator. + /// + public class RuleCondition + { + public RuleField Field { get; set; } + public RuleOperator Operator { get; set; } + + /// + /// The search text for names, or the first date (YYYY, YYYY-MM or YYYY-MM-DD). + /// + public string Text { get; set; } + + /// + /// The second date of a "between" condition. + /// + public string Text2 { get; set; } + + /// + /// The score, hours, play count or number of days. + /// + public double? Number { get; set; } + + /// + /// The upper bound of a "between" condition. + /// + public double? Number2 { get; set; } + + /// + /// IDs of the selected platforms, genres, tags etc. IDs are stored rather than names so renaming a tag keeps the rule working. + /// + public List ItemIds { get; set; } = new List(); + } + + /// + /// A group of conditions that must all be true. + /// + public class RuleBlock + { + /// + /// How this block combines with the result of the blocks above it. Not used on the first block. + /// + public BlockJoin Join { get; set; } + + public List Conditions { get; set; } = new List(); + } + + /// + /// The rules of a dynamic collection. Blocks are combined from top to bottom. + /// + public class DynamicRules + { + public List Blocks { get; set; } = new List(); + } +} diff --git a/source/GameCollections/Models/GameCollection.cs b/source/GameCollections/Models/GameCollection.cs index df0a2f3..2180a56 100644 --- a/source/GameCollections/Models/GameCollection.cs +++ b/source/GameCollections/Models/GameCollection.cs @@ -1,3 +1,4 @@ +using Playnite.SDK.Data; using System; using System.Collections.Generic; @@ -20,6 +21,16 @@ namespace GameCollections.Models public string PosterFileName { get; set; } public List GameIds { get; set; } = new List(); + + /// + /// The rules of a dynamic collection, or null for a manual one. For a dynamic collection + /// holds the latest matches, so it is available without searching the library. + /// + public DynamicRules Rules { get; set; } + + [DontSerialize] + public bool IsDynamic => Rules != null; + public DateTime CreatedAt { get; set; } public DateTime ModifiedAt { get; set; } } @@ -29,6 +40,9 @@ namespace GameCollections.Models /// public class CollectionsDataFile { + /// + /// The version of this file's format. See CollectionsDataMigrator. + /// public int SchemaVersion { get; set; } public List Collections { get; set; } = new List(); } diff --git a/source/GameCollections/Services/CollectionManager.cs b/source/GameCollections/Services/CollectionManager.cs index 502adde..bcef594 100644 --- a/source/GameCollections/Services/CollectionManager.cs +++ b/source/GameCollections/Services/CollectionManager.cs @@ -21,6 +21,20 @@ namespace GameCollections.Services } } + /// + /// The outcome of searching the library for one dynamic collection. + /// + public class DynamicMatchResult + { + public Guid CollectionId { get; set; } + + /// + /// The rules the search used, to detect that they were edited in the meantime. + /// + public DynamicRules Rules { get; set; } + public List GameIds { get; set; } + } + /// /// Owns the in-memory collection list and every operation on it. Each mutation is persisted /// immediately and announced through . @@ -38,6 +52,7 @@ namespace GameCollections.Services private readonly CollectionRepository repository; private readonly PosterStorage posterStorage; private readonly List collections = new List(); + private Dictionary> collectionsByGame; public event EventHandler CollectionsChanged; @@ -58,6 +73,7 @@ namespace GameCollections.Services var result = repository.Load(); collections.Clear(); collections.AddRange(result.Collections); + collectionsByGame = null; return result.Warning; } @@ -132,7 +148,7 @@ namespace GameCollections.Services #region Collection operations - public GameCollection CreateCollection(string title, string description, double rating, string posterSourcePath, IEnumerable gameIds) + public GameCollection CreateCollection(string title, string description, double rating, string posterSourcePath, IEnumerable gameIds, DynamicRules rules = null) { var collection = BuildNewCollection(title, gameIds); collection.Description = NormalizeDescription(description); @@ -142,12 +158,22 @@ namespace GameCollections.Services collection.PosterFileName = posterStorage.Import(collection.Id, posterSourcePath); } + if (rules != null) + { + collection.Rules = rules; + MergeMatches(collection, FindMatches(rules, playniteApi.Database.Games, DateTime.Now)); + } + collections.Add(collection); Persist(new[] { collection.Id }); return collection; } - public void UpdateCollection(Guid id, string title, string description, double rating, PosterChange posterChange, string posterSourcePath) + /// + /// Saves the collection's properties. Passing rules makes it dynamic and replaces its games with + /// the matches; passing null makes it manual, and a dynamic collection keeps its current games. + /// + public void UpdateCollection(Guid id, string title, string description, double rating, PosterChange posterChange, string posterSourcePath, DynamicRules rules = null) { var collection = GetCollection(id); if (collection == null) @@ -180,6 +206,11 @@ namespace GameCollections.Services collection.Rating = NormalizeRating(rating); collection.PosterFileName = newPoster; collection.ModifiedAt = DateTime.UtcNow; + collection.Rules = rules; + if (rules != null) + { + MergeMatches(collection, FindMatches(rules, playniteApi.Database.Games, DateTime.Now)); + } // The old poster is only deleted once the data file no longer references it. if (Persist(new[] { id }) && obsoletePoster != null) @@ -211,24 +242,181 @@ namespace GameCollections.Services public void AddGames(Guid collectionId, IEnumerable gameIds) { var collection = GetCollection(collectionId); - if (collection != null && AddDistinct(collection, gameIds)) + if (collection != null && !collection.IsDynamic && AddDistinct(collection, gameIds)) { Persist(new[] { collectionId }); } } /// - /// Removes game references from a collection. The games stay in the Playnite library. + /// Removes game references from a manual collection. The games stay in the Playnite library. + /// The games of a dynamic collection are decided by its rules, so they can't be removed by hand. /// public void RemoveGames(Guid collectionId, IEnumerable gameIds) { var collection = GetCollection(collectionId); - if (collection != null && RemoveIds(collection, new HashSet(gameIds))) + if (collection != null && !collection.IsDynamic && RemoveIds(collection, new HashSet(gameIds))) { Persist(new[] { collectionId }); } } + /// + /// Moves games within a collection, keeping their relative order. They are placed next to + /// : after it when is set, otherwise before it. + /// A null anchor means the end of the collection when is set, otherwise the start. + /// + public bool MoveGames(Guid collectionId, IEnumerable gameIds, Guid? anchorId, bool after) + { + var collection = GetCollection(collectionId); + if (collection == null) + { + return false; + } + + var moving = new HashSet(gameIds); + if (anchorId.HasValue && moving.Contains(anchorId.Value)) + { + return false; + } + + var moved = collection.GameIds.Where(moving.Contains).ToList(); + var remaining = collection.GameIds.Where(id => !moving.Contains(id)).ToList(); + int index; + if (anchorId.HasValue) + { + index = remaining.IndexOf(anchorId.Value); + if (index < 0) + { + return false; + } + + index += after ? 1 : 0; + } + else + { + index = after ? remaining.Count : 0; + } + + remaining.InsertRange(index, moved); + if (moved.Count == 0 || remaining.SequenceEqual(collection.GameIds)) + { + return false; + } + + collection.GameIds = remaining; + collection.ModifiedAt = DateTime.UtcNow; + Persist(new[] { collectionId }); + return true; + } + + /// + /// Re-checks one dynamic collection against the whole library right away. + /// + public void RefreshCollection(Guid collectionId) + { + var collection = GetCollection(collectionId); + if (collection != null && collection.IsDynamic && + MergeMatches(collection, FindMatches(collection.Rules, playniteApi.Database.Games, DateTime.Now))) + { + Persist(new[] { collectionId }); + } + } + + /// + /// Finds the games matching the rules, sorted by name. Safe to call on a background thread. + /// + public static List FindMatches(DynamicRules rules, IEnumerable games, DateTime now) + { + var isMatch = RuleEngine.Compile(rules, now); + return games + .Where(isMatch) + .OrderBy(g => string.IsNullOrEmpty(g.SortingName) ? g.Name : g.SortingName, StringComparer.CurrentCultureIgnoreCase) + .Select(g => g.Id) + .ToList(); + } + + /// + /// Applies background search results in a single save. A result is skipped if the collection's + /// rules were changed after the search started, since it would be out of date. + /// + public void ApplyMatches(IEnumerable results) + { + var changed = new List(); + foreach (var result in results) + { + var collection = GetCollection(result.CollectionId); + if (collection != null && ReferenceEquals(collection.Rules, result.Rules) && MergeMatches(collection, result.GameIds)) + { + changed.Add(collection.Id); + } + } + + if (changed.Count > 0) + { + Persist(changed); + } + } + + /// + /// Updates dynamic collections after the given games were added or changed. Only these games + /// are tested, so the cost depends on how many changed and not on the size of the library. + /// + public void ApplyGameChanges(ICollection gameIds) + { + var changed = new List(); + var now = DateTime.Now; + foreach (var collection in collections.Where(c => c.IsDynamic)) + { + var isMatch = RuleEngine.Compile(collection.Rules, now); + var current = new HashSet(collection.GameIds); + var modified = false; + foreach (var id in gameIds) + { + var matches = isMatch(playniteApi.Database.Games.Get(id)); + if (matches && current.Add(id)) + { + collection.GameIds.Add(id); + modified = true; + } + else if (!matches && current.Remove(id)) + { + collection.GameIds.Remove(id); + modified = true; + } + } + + if (modified) + { + changed.Add(collection.Id); + } + } + + if (changed.Count > 0) + { + Persist(changed); + } + } + + /// + /// Makes the collection hold exactly the matching games. Games already in it keep their position, + /// which preserves any manual ordering, and new ones go at the end. + /// + private static bool MergeMatches(GameCollection collection, IReadOnlyCollection matches) + { + var matching = new HashSet(matches); + var merged = collection.GameIds.Where(matching.Contains).ToList(); + var current = new HashSet(merged); + merged.AddRange(matches.Where(id => !current.Contains(id))); + if (merged.SequenceEqual(collection.GameIds)) + { + return false; + } + + collection.GameIds = merged; + return true; + } + /// /// Applies the result of the "Add to Collection" dialog in a single save: /// maps collection IDs to whether the games should be in them, @@ -311,6 +499,32 @@ namespace GameCollections.Services #region Games and posters + /// + /// Returns the collections containing the game. The lookup is cached between changes because + /// this runs every time a different game is selected in the library. + /// + public IReadOnlyList GetCollectionsForGame(Guid gameId) + { + if (collectionsByGame == null) + { + collectionsByGame = new Dictionary>(); + foreach (var collection in collections.OrderBy(c => c.Title, StringComparer.CurrentCultureIgnoreCase)) + { + foreach (var id in collection.GameIds) + { + if (!collectionsByGame.TryGetValue(id, out var list)) + { + collectionsByGame[id] = list = new List(); + } + + list.Add(collection); + } + } + } + + return collectionsByGame.TryGetValue(gameId, out var result) ? result : (IReadOnlyList)new GameCollection[0]; + } + /// /// Returns the collection's games that still exist in the library, in collection order. /// @@ -444,6 +658,7 @@ namespace GameCollections.Services private bool Persist(IReadOnlyCollection changedIds) { + collectionsByGame = null; var saved = false; try { diff --git a/source/GameCollections/Services/CollectionRepository.cs b/source/GameCollections/Services/CollectionRepository.cs index f6165bb..6b185a1 100644 --- a/source/GameCollections/Services/CollectionRepository.cs +++ b/source/GameCollections/Services/CollectionRepository.cs @@ -32,7 +32,6 @@ namespace GameCollections.Services /// public class CollectionRepository { - public const int CurrentSchemaVersion = 1; private const string DataFileName = "collections.json"; private static readonly ILogger logger = LogManager.GetLogger(); @@ -59,16 +58,16 @@ namespace GameCollections.Services string preservedCopy = null; if (File.Exists(filePath)) { - if (TryRead(filePath, out var collections)) + if (TryRead(filePath, out var collections, out var migration)) { - return new RepositoryLoadResult(collections, null); + return new RepositoryLoadResult(collections, FinishMigration(collections, migration)); } // Move the unreadable file aside so the next save cannot overwrite it. preservedCopy = PreserveUnreadableFile(filePath); } - if (File.Exists(backupPath) && TryRead(backupPath, out var backupCollections)) + if (File.Exists(backupPath) && TryRead(backupPath, out var backupCollections, out _)) { logger.Warn("Collections data file was unreadable, restored from backup."); return new RepositoryLoadResult(backupCollections, Loc.Get("LOCGameCollections_WarningRestoredFromBackup")); @@ -84,7 +83,7 @@ namespace GameCollections.Services Directory.CreateDirectory(dataDirectory); var payload = new CollectionsDataFile { - SchemaVersion = CurrentSchemaVersion, + SchemaVersion = CollectionsDataMigrator.CurrentVersion, Collections = collections.ToList() }; @@ -116,22 +115,58 @@ namespace GameCollections.Services } } - private static bool TryRead(string path, out List collections) + /// + /// Keeps a copy of the file as it was before a migration or from a newer version, and saves the migrated + /// data. Returns a warning for the user, or null. A failed save isn't fatal: the data is loaded, and + /// the file is simply migrated again next time. + /// + private string FinishMigration(List collections, DataMigrationResult migration) + { + if (!migration.WasMigrated && !migration.IsNewerThanSupported) + { + return null; + } + + var copyPath = $"{filePath}.v{migration.FromVersion}.bak"; + try + { + if (!File.Exists(copyPath)) + { + File.Copy(filePath, copyPath); + } + + if (migration.WasMigrated) + { + Save(collections); + logger.Info($"Migrated collections data from version {migration.FromVersion} to {CollectionsDataMigrator.CurrentVersion}."); + } + } + catch (Exception e) + { + logger.Error(e, "Failed to finish migrating the collections data file."); + } + + return migration.IsNewerThanSupported ? Loc.Format("LOCGameCollections_WarningNewerData", copyPath) : null; + } + + private static bool TryRead(string path, out List collections, out DataMigrationResult migration) { collections = null; + migration = null; try { var text = File.ReadAllText(path, Encoding.UTF8); - var data = Serialization.FromJson(text); + migration = CollectionsDataMigrator.Migrate(text); + var data = Serialization.FromJson(migration.Json); if (data == null) { logger.Error($"Collections file {path} contained no data."); return false; } - if (data.SchemaVersion > CurrentSchemaVersion) + if (migration.IsNewerThanSupported) { - logger.Warn($"Collections file {path} was written by a newer plugin version ({data.SchemaVersion})."); + logger.Warn($"Collections file {path} was written by a newer plugin version ({migration.FromVersion})."); } collections = Sanitize(data.Collections); @@ -198,6 +233,7 @@ namespace GameCollections.Services .Where(id => id != Guid.Empty) .Distinct() .ToList(); + SanitizeRules(collection.Rules); if (collection.CreatedAt == default(DateTime)) { @@ -214,5 +250,19 @@ namespace GameCollections.Services return result; } + + private static void SanitizeRules(DynamicRules rules) + { + if (rules == null) + { + return; + } + + rules.Blocks = (rules.Blocks ?? new List()).Where(b => b != null).ToList(); + foreach (var block in rules.Blocks) + { + block.Conditions = (block.Conditions ?? new List()).Where(c => c != null).ToList(); + } + } } } diff --git a/source/GameCollections/Services/CollectionsDataMigrator.cs b/source/GameCollections/Services/CollectionsDataMigrator.cs new file mode 100644 index 0000000..a39d023 --- /dev/null +++ b/source/GameCollections/Services/CollectionsDataMigrator.cs @@ -0,0 +1,117 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace GameCollections.Services +{ + /// + /// One upgrade of the data file, from to the next version. + /// + public class DataMigrationStep + { + public int FromVersion { get; } + public Action Apply { get; } + + public DataMigrationStep(int fromVersion, Action apply) + { + FromVersion = fromVersion; + Apply = apply; + } + } + + public class DataMigrationResult + { + public string Json { get; set; } + + /// + /// The version the file had before migrating. + /// + public int FromVersion { get; set; } + public bool WasMigrated { get; set; } + + /// + /// The file was written by a newer version of the extension, which this one can't migrate back from. + /// + public bool IsNewerThanSupported { get; set; } + } + + /// + /// Upgrades collections.json from whichever version it has to the current one, one step at a time, so + /// a user can jump across several extension updates. Steps work on the raw JSON rather than the model + /// classes because they must still understand properties the current classes no longer have. + /// To change the format: increase and add a step for the previous version. + /// Existing steps must never be changed once released. + /// + public static class CollectionsDataMigrator + { + public const int CurrentVersion = 2; + public const string VersionProperty = "SchemaVersion"; + + private static readonly IReadOnlyList Steps = new[] + { + // 1 -> 2 (extension 1.1.0): added GameCollection.Rules, for which a missing value already means + // a manual collection, so nothing needs converting. + new DataMigrationStep(1, data => { }) + }; + + public static DataMigrationResult Migrate(string json) + { + return Migrate(json, CurrentVersion, Steps); + } + + /// + /// Throws if the file isn't valid JSON or a step is missing or fails. The input is not modified. + /// + public static DataMigrationResult Migrate(string json, int targetVersion, IReadOnlyList steps) + { + var data = JObject.Parse(json); + var fromVersion = ReadVersion(data); + var result = new DataMigrationResult { Json = json, FromVersion = fromVersion }; + if (fromVersion > targetVersion) + { + result.IsNewerThanSupported = true; + return result; + } + + if (fromVersion == targetVersion) + { + return result; + } + + for (var version = fromVersion; version < targetVersion; version++) + { + var step = steps.SingleOrDefault(s => s.FromVersion == version); + if (step == null) + { + throw new InvalidOperationException($"No migration exists from data version {version}."); + } + + step.Apply(data); + } + + data[VersionProperty] = targetVersion; + result.Json = data.ToString(); + result.WasMigrated = true; + return result; + } + + private static int ReadVersion(JObject data) + { + var token = data[VersionProperty]; + + // Every released file has a version, but a hand-edited one may not. Migrating it from the start is safe. + if (token == null) + { + return 1; + } + + if (token.Type != JTokenType.Integer || token.Value() < 1) + { + throw new InvalidOperationException($"Invalid data version: {token}."); + } + + return token.Value(); + } + } +} diff --git a/source/GameCollections/Services/DetailsViewIntegration.cs b/source/GameCollections/Services/DetailsViewIntegration.cs new file mode 100644 index 0000000..e190709 --- /dev/null +++ b/source/GameCollections/Services/DetailsViewIntegration.cs @@ -0,0 +1,218 @@ +using GameCollections.Settings; +using GameCollections.Views; +using Playnite.SDK; +using Playnite.SDK.Models; +using System; +using System.Collections.Generic; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using System.Windows.Threading; + +namespace GameCollections.Services +{ + /// + /// Shows the collections list in themes that don't place the custom element. Playnite has no API for + /// this, so the list is inserted into the theme's visual tree, below the game description. It stands + /// aside when a theme places the element itself, and does nothing if it finds no suitable place. + /// All members must be called on the UI thread. + /// + public class DetailsViewIntegration + { + // Named parts Playnite's details views use, in order of preference. The list goes below the first one found. + private static readonly string[] AnchorNames = { "PART_ElemDescription", "PART_ElemNotes" }; + private const int MaxSearchAttempts = 3; + private static readonly ILogger logger = LogManager.GetLogger(); + + private readonly IPlayniteAPI playniteApi; + private readonly GameCollectionsSettingsViewModel settings; + private readonly Func createControl; + private readonly Func getWindow; + private readonly DispatcherTimer timer; + + private GameCollectionsControl control; + private Game currentGame; + private DesktopView? lastView; + private int searchAttemptsLeft = MaxSearchAttempts; + + public DetailsViewIntegration( + IPlayniteAPI playniteApi, + GameCollectionsSettingsViewModel settings, + Func createControl, + Func getWindow, + Dispatcher dispatcher) + { + this.playniteApi = playniteApi; + this.settings = settings; + this.createControl = createControl; + this.getWindow = getWindow; + settings.SettingsChanged += Settings_SettingsChanged; + + // The overview of a library view only exists once that view is shown, and there is no event for + // switching views. Reading the current view is cheap; the visual tree is only searched after a change. + timer = new DispatcherTimer(DispatcherPriority.Background, dispatcher) { Interval = TimeSpan.FromSeconds(1) }; + timer.Tick += (s, e) => Update(); + } + + public void Start() + { + timer.Start(); + } + + public void Stop() + { + timer.Stop(); + settings.SettingsChanged -= Settings_SettingsChanged; + } + + public void OnGameSelected(IList games) + { + currentGame = games != null && games.Count == 1 ? games[0] : null; + if (control != null) + { + control.GameContext = currentGame; + } + + searchAttemptsLeft = MaxSearchAttempts; + Update(); + } + + /// + /// Makes sure the list is where it should be right now. Never lets an error reach Playnite. + /// + public void Update() + { + try + { + var view = playniteApi.MainView.ActiveDesktopView; + if (view != lastView) + { + lastView = view; + searchAttemptsLeft = MaxSearchAttempts; + } + + if (!settings.Settings.AddDetailsListToAnyTheme) + { + Remove(); + return; + } + + // Already in a visible overview, which is the normal case, so no searching is needed. + if (control?.Parent is Panel host && host.IsVisible) + { + return; + } + + if (searchAttemptsLeft > 0) + { + searchAttemptsLeft--; + Search(); + } + } + catch (Exception e) + { + logger.Error(e, "Failed to add the collections list to the details view."); + searchAttemptsLeft = 0; + } + } + + private void Settings_SettingsChanged(object sender, EventArgs e) + { + searchAttemptsLeft = MaxSearchAttempts; + Update(); + } + + private void Search() + { + var window = getWindow(); + if (window == null) + { + return; + } + + var found = new Dictionary(); + var themeHasElement = false; + Walk(window, found, ref themeHasElement); + if (themeHasElement) + { + searchAttemptsLeft = 0; + Remove(); + return; + } + + foreach (var name in AnchorNames) + { + if (found.TryGetValue(name, out var anchor) && Insert(anchor)) + { + searchAttemptsLeft = 0; + return; + } + } + } + + private void Walk(DependencyObject parent, Dictionary found, ref bool themeHasElement) + { + for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent) && !themeHasElement; i++) + { + var child = VisualTreeHelper.GetChild(parent, i); + + // The library's game lists hold most of the tree and never contain the overview. + if (child is ListBoxItem) + { + continue; + } + + if (child is GameCollectionsControl existing) + { + if (!existing.IsInjected) + { + themeHasElement = true; + return; + } + + continue; + } + + // An overview from a view that isn't showing can still be in the tree, so visibility of the parent counts. + if (child is FrameworkElement element && Array.IndexOf(AnchorNames, element.Name) >= 0 && + !found.ContainsKey(element.Name) && element.Parent is Panel panel && panel.IsVisible) + { + found[element.Name] = element; + } + + Walk(child, found, ref themeHasElement); + } + } + + private bool Insert(FrameworkElement anchor) + { + // A Grid would need a row of its own, and changing a theme's rows could break its layout. + if (!(anchor.Parent is Panel panel) || panel is Grid || panel.IsItemsHost) + { + return false; + } + + Remove(); + if (control == null) + { + control = createControl(); + control.IsInjected = true; + control.Margin = new Thickness(0, 10, 0, 0); + } + + if (panel is DockPanel) + { + DockPanel.SetDock(control, DockPanel.GetDock(anchor)); + } + + panel.Children.Insert(panel.Children.IndexOf(anchor) + 1, control); + control.GameContext = currentGame; + return true; + } + + private void Remove() + { + (control?.Parent as Panel)?.Children.Remove(control); + } + } +} diff --git a/source/GameCollections/Services/DialogService.cs b/source/GameCollections/Services/DialogService.cs index 5c0b535..955d7d9 100644 --- a/source/GameCollections/Services/DialogService.cs +++ b/source/GameCollections/Services/DialogService.cs @@ -14,6 +14,9 @@ namespace GameCollections.Services /// public class DialogService { + private const double DynamicEditorWidth = 980; + private const double DynamicEditorHeight = 920; + private readonly IPlayniteAPI playniteApi; private readonly CollectionManager manager; @@ -52,12 +55,34 @@ namespace GameCollections.Services private Guid? ShowEditor(GameCollection collection) { var viewModel = new EditCollectionViewModel(playniteApi, manager, collection); - var window = CreateWindow(viewModel.WindowTitle, 640, 480, 520, 420); + var window = CreateWindow(viewModel.WindowTitle, viewModel.IsDynamic ? DynamicEditorWidth : 640, viewModel.IsDynamic ? DynamicEditorHeight : 560, 520, 420); viewModel.CloseRequested = result => Close(window, result); + viewModel.DynamicModeChanged += (s, e) => + { + // The rule builder needs more room; switching back leaves the size the user sees alone. + if (viewModel.IsDynamic) + { + var workArea = SystemParameters.WorkArea; + window.Width = Math.Max(window.Width, Math.Min(DynamicEditorWidth, workArea.Width * 0.9)); + window.Height = Math.Max(window.Height, Math.Min(DynamicEditorHeight, workArea.Height * 0.9)); + } + }; window.Content = new EditCollectionView { DataContext = viewModel }; return window.ShowDialog() == true ? viewModel.SavedCollectionId : null; } + /// + /// Shows a collection's page in its own window. Used from the game details view, because + /// Playnite has no API for a plugin to switch to its sidebar view. + /// + public void ShowCollectionPage(CollectionDetailsViewModel viewModel) + { + var window = CreateWindow(viewModel.Header.Title, 1000, 760, 700, 500); + viewModel.CloseWindow = () => window.Close(); + window.Content = new CollectionDetailsView { DataContext = viewModel }; + window.ShowDialog(); + } + private Window CreateWindow(string title, double width, double height, double minWidth, double minHeight) { var window = playniteApi.Dialogs.CreateWindow(new WindowCreationOptions diff --git a/source/GameCollections/Services/DynamicCollectionRefresher.cs b/source/GameCollections/Services/DynamicCollectionRefresher.cs new file mode 100644 index 0000000..03f2b12 --- /dev/null +++ b/source/GameCollections/Services/DynamicCollectionRefresher.cs @@ -0,0 +1,165 @@ +using GameCollections.Models; +using Playnite.SDK; +using Playnite.SDK.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Threading; + +namespace GameCollections.Services +{ + /// + /// Decides when dynamic collections are re-evaluated, keeping the work away from the UI thread + /// and from Playnite's startup. All members must be called on the UI thread. + /// + public class DynamicCollectionRefresher + { + // Library updates and metadata downloads change many games in quick succession. + private static readonly TimeSpan GameChangeDelay = TimeSpan.FromSeconds(1); + private static readonly TimeSpan StartupDelay = TimeSpan.FromSeconds(5); + private static readonly TimeSpan TimeBasedRulesInterval = TimeSpan.FromHours(1); + private static readonly ILogger logger = LogManager.GetLogger(); + + private readonly IPlayniteAPI playniteApi; + private readonly CollectionManager manager; + private readonly DispatcherTimer gameChangeTimer; + private readonly DispatcherTimer fullRefreshTimer; + private readonly DispatcherTimer timeBasedRulesTimer; + private readonly HashSet pendingGames = new HashSet(); + private bool isFullRefreshRunning; + private bool isFullRefreshRequested; + + public DynamicCollectionRefresher(IPlayniteAPI playniteApi, CollectionManager manager, Dispatcher dispatcher) + { + this.playniteApi = playniteApi; + this.manager = manager; + + gameChangeTimer = new DispatcherTimer(DispatcherPriority.Background, dispatcher) { Interval = GameChangeDelay }; + gameChangeTimer.Tick += (s, e) => + { + gameChangeTimer.Stop(); + ProcessPendingGames(); + }; + + fullRefreshTimer = new DispatcherTimer(DispatcherPriority.Background, dispatcher); + fullRefreshTimer.Tick += async (s, e) => + { + fullRefreshTimer.Stop(); + await RefreshAllAsync(); + }; + + timeBasedRulesTimer = new DispatcherTimer(DispatcherPriority.Background, dispatcher) { Interval = TimeBasedRulesInterval }; + timeBasedRulesTimer.Tick += async (s, e) => + { + // "Played in the last 30 days" changes with time alone, without any game event to react to. + if (manager.Collections.Any(c => RuleEngine.DependsOnCurrentTime(c.Rules))) + { + await RefreshAllAsync(); + } + }; + } + + /// + /// Catches up on changes made while Playnite or the plugin wasn't running. + /// + public void Start() + { + ScheduleFullRefresh(StartupDelay); + timeBasedRulesTimer.Start(); + } + + public void Stop() + { + gameChangeTimer.Stop(); + fullRefreshTimer.Stop(); + timeBasedRulesTimer.Stop(); + } + + public void NotifyGamesChanged(IEnumerable gameIds) + { + pendingGames.UnionWith(gameIds); + gameChangeTimer.Stop(); + gameChangeTimer.Start(); + } + + public void ScheduleFullRefresh(TimeSpan delay) + { + fullRefreshTimer.Stop(); + fullRefreshTimer.Interval = delay; + fullRefreshTimer.Start(); + } + + /// + /// Re-checks every dynamic collection against the whole library on a background thread. + /// + public async Task RefreshAllAsync() + { + if (isFullRefreshRunning) + { + isFullRefreshRequested = true; + return; + } + + isFullRefreshRunning = true; + try + { + var targets = manager.Collections + .Where(c => c.IsDynamic) + .Select(c => new { c.Id, c.Rules }) + .ToList(); + + if (targets.Count > 0) + { + var games = playniteApi.Database.Games.ToList(); + var now = DateTime.Now; + var results = await Task.Run(() => targets + .Select(t => new DynamicMatchResult + { + CollectionId = t.Id, + Rules = t.Rules, + GameIds = CollectionManager.FindMatches(t.Rules, games, now) + }) + .ToList()); + + manager.ApplyMatches(results); + } + } + catch (Exception e) + { + logger.Error(e, "Failed to refresh dynamic collections."); + } + finally + { + isFullRefreshRunning = false; + } + + // Games changed during the search may be out of date in its results, so they are applied last. + ProcessPendingGames(); + if (isFullRefreshRequested) + { + isFullRefreshRequested = false; + await RefreshAllAsync(); + } + } + + private void ProcessPendingGames() + { + if (isFullRefreshRunning || pendingGames.Count == 0) + { + return; + } + + var gameIds = pendingGames.ToList(); + pendingGames.Clear(); + try + { + manager.ApplyGameChanges(gameIds); + } + catch (Exception e) + { + logger.Error(e, "Failed to update dynamic collections after game changes."); + } + } + } +} diff --git a/source/GameCollections/Services/RuleEngine.cs b/source/GameCollections/Services/RuleEngine.cs new file mode 100644 index 0000000..bf4a7aa --- /dev/null +++ b/source/GameCollections/Services/RuleEngine.cs @@ -0,0 +1,346 @@ +using GameCollections.Models; +using Playnite.SDK.Models; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace GameCollections.Services +{ + /// + /// Turns dynamic collection rules into a predicate over games. Compiled predicates only read + /// in-memory game fields, so they are cheap and safe to run on a background thread. + /// + public static class RuleEngine + { + private const double SecondsPerHour = 3600; + + public static RuleValueKind GetValueKind(RuleField field) + { + switch (field) + { + case RuleField.Name: + return RuleValueKind.Text; + case RuleField.ReleaseDate: + case RuleField.LastPlayed: + return RuleValueKind.Date; + case RuleField.UserScore: + case RuleField.CriticScore: + case RuleField.CommunityScore: + case RuleField.TimePlayed: + case RuleField.PlayCount: + return RuleValueKind.Number; + default: + return RuleValueKind.Items; + } + } + + public static IReadOnlyList GetOperators(RuleField field) + { + switch (GetValueKind(field)) + { + case RuleValueKind.Text: + return new[] { RuleOperator.Contains, RuleOperator.NotContains }; + case RuleValueKind.Date: + return new[] { RuleOperator.After, RuleOperator.Before, RuleOperator.Between, RuleOperator.InLastDays, RuleOperator.OlderThanDays, RuleOperator.IsEmpty }; + case RuleValueKind.Number: + return IsScore(field) + ? new[] { RuleOperator.AtLeast, RuleOperator.AtMost, RuleOperator.Between, RuleOperator.IsEmpty } + : new[] { RuleOperator.AtLeast, RuleOperator.AtMost, RuleOperator.Between }; + default: + // A game has only one completion status, so "all of" could never match two of them. + return field == RuleField.CompletionStatus + ? new[] { RuleOperator.IncludesAny, RuleOperator.Excludes, RuleOperator.IsEmpty } + : new[] { RuleOperator.IncludesAny, RuleOperator.IncludesAll, RuleOperator.Excludes, RuleOperator.IsEmpty }; + } + } + + public static bool IsScore(RuleField field) + { + return field == RuleField.UserScore || field == RuleField.CriticScore || field == RuleField.CommunityScore; + } + + /// + /// Relative date rules change their result as time passes, without any game changing. + /// + public static bool DependsOnCurrentTime(DynamicRules rules) + { + return rules?.Blocks != null && rules.Blocks.Any(b => b.Conditions != null && b.Conditions.Any(c => + c.Operator == RuleOperator.InLastDays || c.Operator == RuleOperator.OlderThanDays)); + } + + /// + /// Parses YYYY, YYYY-MM or YYYY-MM-DD into the first and last day of that period. + /// + public static bool TryParseDatePeriod(string text, out DateTime start, out DateTime end) + { + start = end = default(DateTime); + var value = text?.Trim(); + if (string.IsNullOrEmpty(value)) + { + return false; + } + + var culture = CultureInfo.InvariantCulture; + if (DateTime.TryParseExact(value, "yyyy-M-d", culture, DateTimeStyles.None, out start)) + { + end = start; + return true; + } + + if (DateTime.TryParseExact(value, "yyyy-M", culture, DateTimeStyles.None, out start)) + { + end = start.AddMonths(1).AddDays(-1); + return true; + } + + if (DateTime.TryParseExact(value, "yyyy", culture, DateTimeStyles.None, out start)) + { + end = start.AddYears(1).AddDays(-1); + return true; + } + + return false; + } + + /// + /// True when the condition has every value its operator needs, and those values are valid. + /// + public static bool IsComplete(RuleCondition condition) + { + if (condition == null) + { + return false; + } + + if (condition.Operator == RuleOperator.IsEmpty) + { + return true; + } + + switch (GetValueKind(condition.Field)) + { + case RuleValueKind.Text: + return !string.IsNullOrWhiteSpace(condition.Text); + case RuleValueKind.Items: + return condition.ItemIds != null && condition.ItemIds.Count > 0; + case RuleValueKind.Number: + return condition.Number >= 0 && (condition.Operator != RuleOperator.Between || condition.Number2 >= condition.Number); + default: + return IsDateConditionComplete(condition); + } + } + + public static bool IsComplete(DynamicRules rules) + { + return rules?.Blocks != null && rules.Blocks.Count > 0 && rules.Blocks.All(b => + b.Conditions != null && b.Conditions.Count > 0 && b.Conditions.All(IsComplete)); + } + + /// + /// Builds a predicate for the rules. Blocks are combined strictly from top to bottom, matching how + /// they read in the editor. Hidden games never match, and neither do damaged or incomplete rules, + /// so a broken rule can never fill a collection with the whole library. + /// + public static Func Compile(DynamicRules rules, DateTime now) + { + if (!IsComplete(rules)) + { + return game => false; + } + + var blocks = rules.Blocks + .Select(b => new { b.Join, Test = CompileBlock(b, now) }) + .ToList(); + + return game => + { + if (game == null || game.Hidden) + { + return false; + } + + var result = blocks[0].Test(game); + for (var i = 1; i < blocks.Count; i++) + { + result = blocks[i].Join == BlockJoin.And + ? result && blocks[i].Test(game) + : result || blocks[i].Test(game); + } + + return result; + }; + } + + private static Func CompileBlock(RuleBlock block, DateTime now) + { + var tests = block.Conditions.Select(c => CompileCondition(c, now)).ToList(); + return game => + { + foreach (var test in tests) + { + if (!test(game)) + { + return false; + } + } + + return true; + }; + } + + private static Func CompileCondition(RuleCondition condition, DateTime now) + { + switch (GetValueKind(condition.Field)) + { + case RuleValueKind.Text: + return CompileText(condition); + case RuleValueKind.Items: + return CompileItems(condition); + case RuleValueKind.Number: + return CompileNumber(condition); + default: + return CompileDate(condition, now); + } + } + + private static Func CompileText(RuleCondition condition) + { + var query = condition.Text.Trim(); + var negate = condition.Operator == RuleOperator.NotContains; + return game => (game.Name != null && game.Name.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0) != negate; + } + + private static Func CompileItems(RuleCondition condition) + { + var getIds = GetItemIds(condition.Field); + var wanted = new HashSet(condition.ItemIds ?? new List()); + switch (condition.Operator) + { + case RuleOperator.IncludesAll: + return game => + { + var ids = getIds(game); + return ids != null && wanted.All(ids.Contains); + }; + case RuleOperator.Excludes: + return game => + { + var ids = getIds(game); + return ids == null || !ids.Any(wanted.Contains); + }; + case RuleOperator.IsEmpty: + return game => + { + var ids = getIds(game); + return ids == null || ids.Count == 0; + }; + default: + return game => + { + var ids = getIds(game); + return ids != null && ids.Any(wanted.Contains); + }; + } + } + + private static Func> GetItemIds(RuleField field) + { + switch (field) + { + case RuleField.Platform: return g => g.PlatformIds; + case RuleField.Genre: return g => g.GenreIds; + case RuleField.Developer: return g => g.DeveloperIds; + case RuleField.Publisher: return g => g.PublisherIds; + case RuleField.Category: return g => g.CategoryIds; + case RuleField.Feature: return g => g.FeatureIds; + case RuleField.Tag: return g => g.TagIds; + case RuleField.Series: return g => g.SeriesIds; + case RuleField.CompletionStatus: + return g => g.CompletionStatusId == Guid.Empty ? null : new[] { g.CompletionStatusId }; + default: + throw new ArgumentOutOfRangeException(nameof(field)); + } + } + + private static Func CompileNumber(RuleCondition condition) + { + var getValue = GetNumber(condition.Field); + var low = condition.Number ?? 0; + var high = condition.Number2 ?? 0; + switch (condition.Operator) + { + case RuleOperator.AtMost: + return game => getValue(game) <= low; + case RuleOperator.Between: + return game => getValue(game) >= low && getValue(game) <= high; + case RuleOperator.IsEmpty: + return game => getValue(game) == null; + default: + return game => getValue(game) >= low; + } + } + + private static Func GetNumber(RuleField field) + { + switch (field) + { + case RuleField.UserScore: return g => g.UserScore; + case RuleField.CriticScore: return g => g.CriticScore; + case RuleField.CommunityScore: return g => g.CommunityScore; + case RuleField.TimePlayed: return g => g.Playtime / SecondsPerHour; + case RuleField.PlayCount: return g => g.PlayCount; + default: + throw new ArgumentOutOfRangeException(nameof(field)); + } + } + + private static Func CompileDate(RuleCondition condition, DateTime now) + { + Func getDate; + if (condition.Field == RuleField.ReleaseDate) + { + getDate = g => g.ReleaseDate?.Date; + } + else + { + getDate = g => g.LastActivity; + } + + var days = condition.Number ?? 0; + TryParseDatePeriod(condition.Text, out var start, out var end); + TryParseDatePeriod(condition.Text2, out _, out var end2); + switch (condition.Operator) + { + case RuleOperator.Before: + return game => getDate(game)?.Date < start; + case RuleOperator.After: + return game => getDate(game)?.Date > end; + case RuleOperator.Between: + return game => getDate(game)?.Date >= start && getDate(game)?.Date <= end2; + case RuleOperator.InLastDays: + return game => getDate(game) >= now.AddDays(-days); + case RuleOperator.OlderThanDays: + return game => getDate(game) < now.AddDays(-days); + default: + return game => getDate(game) == null; + } + } + + private static bool IsDateConditionComplete(RuleCondition condition) + { + switch (condition.Operator) + { + case RuleOperator.InLastDays: + case RuleOperator.OlderThanDays: + return condition.Number >= 0; + case RuleOperator.Between: + return TryParseDatePeriod(condition.Text, out var start, out _) && + TryParseDatePeriod(condition.Text2, out _, out var end) && + end >= start; + default: + return TryParseDatePeriod(condition.Text, out _, out _); + } + } + } +} diff --git a/source/GameCollections/Services/RuleText.cs b/source/GameCollections/Services/RuleText.cs new file mode 100644 index 0000000..da523a3 --- /dev/null +++ b/source/GameCollections/Services/RuleText.cs @@ -0,0 +1,148 @@ +using GameCollections.Models; +using Playnite.SDK; +using Playnite.SDK.Models; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace GameCollections.Services +{ + /// + /// A selectable value of a rule field, such as one platform or tag. + /// + public class RuleOption + { + public Guid Id { get; } + public string Name { get; } + + public RuleOption(Guid id, string name) + { + Id = id; + Name = name; + } + } + + /// + /// User-facing names for rule fields and operators, the values a field can take, and rule summaries. + /// + public class RuleText + { + private readonly IPlayniteAPI playniteApi; + private readonly Dictionary> optionsCache = new Dictionary>(); + + public RuleText(IPlayniteAPI playniteApi) + { + this.playniteApi = playniteApi; + } + + public static string FieldName(RuleField field) + { + return Loc.Get("LOCGameCollections_RuleField" + field); + } + + public static string OperatorName(RuleField field, RuleOperator op) + { + // Dates read differently from the other kinds: "is empty" is "has no date", and so on. + return Loc.Get(op == RuleOperator.IsEmpty && RuleEngine.GetValueKind(field) == RuleValueKind.Date + ? "LOCGameCollections_RuleOperatorNoDate" + : "LOCGameCollections_RuleOperator" + op); + } + + /// + /// Returns the values that can be chosen for a field, sorted by name. Loaded once per dialog. + /// + public IReadOnlyList GetOptions(RuleField field) + { + if (!optionsCache.TryGetValue(field, out var options)) + { + options = LoadItems(field) + .Where(i => i != null && !string.IsNullOrWhiteSpace(i.Name)) + .Select(i => new RuleOption(i.Id, i.Name)) + .OrderBy(o => o.Name, StringComparer.CurrentCultureIgnoreCase) + .ToList(); + optionsCache[field] = options; + } + + return options; + } + + /// + /// Describes rules in one line, for example: Platform includes any of PC and Time played at least 10. + /// + public string Describe(DynamicRules rules) + { + if (rules?.Blocks == null) + { + return string.Empty; + } + + var parts = new List(); + foreach (var block in rules.Blocks) + { + var text = string.Join(" " + Loc.Get("LOCGameCollections_RuleAnd") + " ", block.Conditions.Select(Describe)); + if (parts.Count > 0) + { + parts.Add(Loc.Get(block.Join == BlockJoin.And ? "LOCGameCollections_RuleAnd" : "LOCGameCollections_RuleOr").ToUpper(CultureInfo.CurrentCulture)); + } + + parts.Add(rules.Blocks.Count > 1 ? "(" + text + ")" : text); + } + + return string.Join(" ", parts); + } + + private string Describe(RuleCondition condition) + { + var label = FieldName(condition.Field) + " " + OperatorName(condition.Field, condition.Operator); + if (condition.Operator == RuleOperator.IsEmpty) + { + return label; + } + + switch (RuleEngine.GetValueKind(condition.Field)) + { + case RuleValueKind.Text: + return $"{label} \"{condition.Text}\""; + case RuleValueKind.Items: + var options = GetOptions(condition.Field); + var names = condition.ItemIds.Select(id => options.FirstOrDefault(o => o.Id == id)?.Name).Where(n => n != null); + return label + " " + string.Join(", ", names); + case RuleValueKind.Number: + return condition.Operator == RuleOperator.Between ? $"{label} {condition.Number} – {condition.Number2}" : $"{label} {condition.Number}"; + default: + if (condition.Operator == RuleOperator.InLastDays || condition.Operator == RuleOperator.OlderThanDays) + { + return $"{label} {condition.Number} {Loc.Get("LOCGameCollections_RuleUnitDays")}"; + } + + return condition.Operator == RuleOperator.Between ? $"{label} {condition.Text} – {condition.Text2}" : $"{label} {condition.Text}"; + } + } + + private IEnumerable LoadItems(RuleField field) + { + var database = playniteApi.Database; + switch (field) + { + case RuleField.Platform: return database.Platforms; + case RuleField.Genre: return database.Genres; + case RuleField.Category: return database.Categories; + case RuleField.Feature: return database.Features; + case RuleField.Tag: return database.Tags; + case RuleField.Series: return database.Series; + case RuleField.CompletionStatus: return database.CompletionStatuses; + case RuleField.Developer: return LoadCompanies(g => g.DeveloperIds); + case RuleField.Publisher: return LoadCompanies(g => g.PublisherIds); + default: return Enumerable.Empty(); + } + } + + // Developers and publishers share one long company list, so only those actually used in that role are offered. + private IEnumerable LoadCompanies(Func> getIds) + { + var used = new HashSet(playniteApi.Database.Games.Where(g => getIds(g) != null).SelectMany(getIds)); + return playniteApi.Database.Companies.Where(c => used.Contains(c.Id)); + } + } +} diff --git a/source/GameCollections/Services/SidebarNavigator.cs b/source/GameCollections/Services/SidebarNavigator.cs new file mode 100644 index 0000000..6cfe9eb --- /dev/null +++ b/source/GameCollections/Services/SidebarNavigator.cs @@ -0,0 +1,57 @@ +using Playnite.SDK; +using Playnite.SDK.Plugins; +using System; +using System.Collections; +using System.Windows; +using System.Windows.Input; + +namespace GameCollections.Services +{ + /// + /// Switches Playnite to a plugin's sidebar view. The SDK has no API for this, so it does what Playnite's + /// own SwitchToLibraryView does: run the Command of the entry in the main view model's SidebarItems. + /// Those are Playnite internals that could change, so callers must handle this returning false. + /// + public static class SidebarNavigator + { + private static readonly ILogger logger = LogManager.GetLogger(); + + public static bool TryActivate(Window mainWindow, SidebarItem item) + { + try + { + var viewModel = mainWindow?.DataContext; + var entries = viewModel?.GetType().GetProperty("SidebarItems")?.GetValue(viewModel) as IEnumerable; + if (entries == null) + { + logger.Warn("Could not find Playnite's sidebar items."); + return false; + } + + foreach (var entry in entries) + { + var type = entry.GetType(); + var sideItem = type.GetProperty("SideItem")?.GetValue(entry) as SidebarItem; + if (sideItem == null || (!ReferenceEquals(sideItem, item) && !(sideItem.Type == item.Type && sideItem.Title == item.Title))) + { + continue; + } + + if (type.GetProperty("Command")?.GetValue(entry) is ICommand command) + { + command.Execute(null); + return true; + } + } + + logger.Warn("Could not find this extension's sidebar entry."); + } + catch (Exception e) + { + logger.Error(e, "Failed to switch to the sidebar view."); + } + + return false; + } + } +} diff --git a/source/GameCollections/Settings/GameCollectionsSettings.cs b/source/GameCollections/Settings/GameCollectionsSettings.cs index 34e02cf..c559d9f 100644 --- a/source/GameCollections/Settings/GameCollectionsSettings.cs +++ b/source/GameCollections/Settings/GameCollectionsSettings.cs @@ -1,6 +1,7 @@ using GameCollections.Models; using Playnite.SDK; using Playnite.SDK.Data; +using System; using System.Collections.Generic; namespace GameCollections.Settings @@ -10,6 +11,17 @@ namespace GameCollections.Settings // 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); } + + private bool showDynamicCollectionsInDetails = true; + public bool ShowDynamicCollectionsInDetails { get => showDynamicCollectionsInDetails; set => SetValue(ref showDynamicCollectionsInDetails, value); } + + private bool addDetailsListToAnyTheme = true; + public bool AddDetailsListToAnyTheme { get => addDetailsListToAnyTheme; set => SetValue(ref addDetailsListToAnyTheme, value); } + + // For themes, which can bind to this to lay out their details view around the list. + private bool isDetailsControlVisible; + [DontSerialize] + public bool IsDetailsControlVisible { get => isDetailsControlVisible; set => SetValue(ref isDetailsControlVisible, value); } } public class GameCollectionsSettingsViewModel : ObservableObject, ISettings @@ -17,6 +29,8 @@ namespace GameCollections.Settings private readonly GameCollectionsPlugin plugin; private GameCollectionsSettings editingClone; + public event EventHandler SettingsChanged; + private GameCollectionsSettings settings; public GameCollectionsSettings Settings { @@ -48,11 +62,13 @@ namespace GameCollections.Settings public void CancelEdit() { Settings = editingClone; + SettingsChanged?.Invoke(this, EventArgs.Empty); } public void EndEdit() { Save(); + SettingsChanged?.Invoke(this, EventArgs.Empty); } public bool VerifySettings(out List errors) diff --git a/source/GameCollections/Settings/GameCollectionsSettingsView.xaml b/source/GameCollections/Settings/GameCollectionsSettingsView.xaml index 0b3246d..31338e6 100644 --- a/source/GameCollections/Settings/GameCollectionsSettingsView.xaml +++ b/source/GameCollections/Settings/GameCollectionsSettingsView.xaml @@ -5,11 +5,18 @@ xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="200" d:DesignWidth="600"> - + + TextWrapping="Wrap" Margin="0,4,0,16" + Text="{DynamicResource LOCGameCollections_SettingAddListToAnyThemeHint}" /> + + diff --git a/source/GameCollections/ViewModels/AddToCollectionViewModel.cs b/source/GameCollections/ViewModels/AddToCollectionViewModel.cs index 8f82ca4..b55573c 100644 --- a/source/GameCollections/ViewModels/AddToCollectionViewModel.cs +++ b/source/GameCollections/ViewModels/AddToCollectionViewModel.cs @@ -111,7 +111,8 @@ namespace GameCollections.ViewModels : Loc.Format("LOCGameCollections_AddToCollectionHeaderMultiple", games.Count); var gameIds = games.Select(g => g.Id).ToList(); - foreach (var collection in manager.Collections) + // The games of a dynamic collection are decided by its rules, so it can't be chosen here. + foreach (var collection in manager.Collections.Where(c => !c.IsDynamic)) { var memberIds = new HashSet(collection.GameIds); var containedCount = gameIds.Count(memberIds.Contains); diff --git a/source/GameCollections/ViewModels/CollectionCardViewModel.cs b/source/GameCollections/ViewModels/CollectionCardViewModel.cs index 1918a61..12fd7f4 100644 --- a/source/GameCollections/ViewModels/CollectionCardViewModel.cs +++ b/source/GameCollections/ViewModels/CollectionCardViewModel.cs @@ -47,6 +47,9 @@ namespace GameCollections.ViewModels private ImageSource poster; public ImageSource Poster { get => poster; private set => SetValue(ref poster, value); } + private bool isDynamic; + public bool IsDynamic { get => isDynamic; private set => SetValue(ref isDynamic, value); } + public string RatingText => Loc.Rating(rating); public string GameCountText => Loc.GameCount(gameCount); public bool HasDescription => !string.IsNullOrWhiteSpace(description); @@ -75,6 +78,7 @@ namespace GameCollections.ViewModels Title = collection.Title; Description = collection.Description; Rating = collection.Rating; + IsDynamic = collection.IsDynamic; GameCount = manager.GetGames(collection).Count; OnPropertyChanged(nameof(RatingText)); OnPropertyChanged(nameof(GameCountText)); diff --git a/source/GameCollections/ViewModels/CollectionDetailsViewModel.cs b/source/GameCollections/ViewModels/CollectionDetailsViewModel.cs index b9f826c..2e4bfc3 100644 --- a/source/GameCollections/ViewModels/CollectionDetailsViewModel.cs +++ b/source/GameCollections/ViewModels/CollectionDetailsViewModel.cs @@ -7,6 +7,7 @@ using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Windows.Data; +using System.Windows.Input; namespace GameCollections.ViewModels { @@ -84,6 +85,7 @@ namespace GameCollections.ViewModels { root.GameSortField = value; OnPropertyChanged(); + RaiseReorderChanged(); ApplySort(); } } @@ -97,6 +99,7 @@ namespace GameCollections.ViewModels OnPropertyChanged(); OnPropertyChanged(nameof(SortDirectionGlyph)); OnPropertyChanged(nameof(SortDirectionTooltip)); + RaiseReorderChanged(); ApplySort(); } } @@ -115,6 +118,30 @@ namespace GameCollections.ViewModels } } + private bool isDynamic; + public bool IsDynamic { get => isDynamic; private set => SetValue(ref isDynamic, value); } + + public bool CanRemove => !isDynamic; + + private string rulesSummary; + public string RulesSummary { get => rulesSummary; private set => SetValue(ref rulesSummary, value); } + + public string EmptyTitle => Loc.Get(isDynamic ? "LOCGameCollections_DynamicEmptyTitle" : "LOCGameCollections_CollectionEmptyTitle"); + public string EmptyDescription => Loc.Get(isDynamic ? "LOCGameCollections_DynamicEmptyDescription" : "LOCGameCollections_CollectionEmptyDescription"); + + /// + /// Games can only be reordered while the page shows the collection's own order; + /// in any other sort, a dragged game wouldn't stay where it was dropped. + /// + public bool CanReorder => SortField == GameSortField.CollectionOrder && !SortDescending; + public string ReorderHint => Loc.Get(CanReorder ? "LOCGameCollections_ReorderHint" : "LOCGameCollections_ReorderUnavailableHint"); + + /// + /// Set when the page is shown in its own window instead of the sidebar view. + /// + public Action CloseWindow { get; set; } + public bool IsInWindow => CloseWindow != null; + public bool IsEmpty => Games.Count == 0; public bool HasNoResults => !IsEmpty && GamesView.Count == 0; public string VisibleCountText => GamesView.Count == Games.Count @@ -126,6 +153,8 @@ namespace GameCollections.ViewModels public RelayCommand ShowAllInLibraryCommand { get; } public RelayCommand RemoveSelectedCommand { get; } public RelayCommand PlaySelectedCommand { get; } + public RelayCommand RefreshCommand { get; } + public RelayCommand OpenInCollectionsCommand { get; } public CollectionDetailsViewModel(IPlayniteAPI playniteApi, CollectionManager manager, CollectionsRootViewModel root, CollectionCardViewModel header) { @@ -137,11 +166,23 @@ namespace GameCollections.ViewModels GamesView = new ListCollectionView(Games) { Filter = FilterGame }; ApplySort(); - BackCommand = new RelayCommand(root.ShowHome); + BackCommand = new RelayCommand(() => + { + if (CloseWindow != null) + { + CloseWindow(); + } + else + { + root.ShowHome(); + } + }); ToggleSortDirectionCommand = new RelayCommand(() => SortDescending = !SortDescending); ShowAllInLibraryCommand = new RelayCommand(ShowAllInLibrary); RemoveSelectedCommand = new RelayCommand(RemoveSelected); PlaySelectedCommand = new RelayCommand(PlaySelected); + RefreshCommand = new RelayCommand(() => manager.RefreshCollection(CollectionId)); + OpenInCollectionsCommand = new RelayCommand(() => root.ShowInCollectionsSection(CollectionId)); Reload(); } @@ -157,6 +198,14 @@ namespace GameCollections.ViewModels return; } + IsDynamic = collection.IsDynamic; + RulesSummary = collection.IsDynamic + ? Loc.Format("LOCGameCollections_RulesSummary", new RuleText(playniteApi).Describe(collection.Rules)) + : null; + OnPropertyChanged(nameof(CanRemove)); + OnPropertyChanged(nameof(EmptyTitle)); + OnPropertyChanged(nameof(EmptyDescription)); + 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()) @@ -198,6 +247,7 @@ namespace GameCollections.ViewModels return; } + CloseWindow?.Invoke(); if (game.IsInstalled) { playniteApi.StartGame(game.Id); @@ -222,6 +272,7 @@ namespace GameCollections.ViewModels { try { + CloseWindow?.Invoke(); playniteApi.MainView.SelectGame(tile.Id); playniteApi.MainView.SwitchToLibraryView(); } @@ -237,11 +288,67 @@ namespace GameCollections.ViewModels /// public void RemoveGame(CollectionGameViewModel tile) { - var selected = SelectedGames?.Cast().ToList() ?? new List(); - var targets = selected.Contains(tile) ? selected : new List { tile }; + var targets = GetMoveTargets(tile); manager.RemoveGames(CollectionId, targets.Select(t => t.Id)); } + /// + /// Moves the games to just before or after another game. Dragging uses this directly. + /// + public void MoveGames(IEnumerable gameIds, Guid anchorId, bool after) + { + if (CanReorder) + { + manager.MoveGames(CollectionId, gameIds, anchorId, after); + } + } + + /// + /// Moves the tile, or the whole selection if the tile is part of it, past the neighbouring visible game. + /// + public void MoveOneStep(CollectionGameViewModel tile, bool later) + { + if (!CanReorder) + { + return; + } + + var targets = GetMoveTargets(tile); + var visible = GamesView.Cast().ToList(); + var indexes = targets.Select(t => visible.IndexOf(t)).Where(i => i >= 0).ToList(); + if (indexes.Count == 0) + { + return; + } + + var neighbour = later ? indexes.Max() + 1 : indexes.Min() - 1; + if (neighbour >= 0 && neighbour < visible.Count) + { + manager.MoveGames(CollectionId, targets.Select(t => t.Id), visible[neighbour].Id, later); + } + } + + public void MoveToEdge(CollectionGameViewModel tile, bool toEnd) + { + if (CanReorder) + { + manager.MoveGames(CollectionId, GetMoveTargets(tile).Select(t => t.Id), null, toEnd); + } + } + + private List GetMoveTargets(CollectionGameViewModel tile) + { + var selected = SelectedGames?.Cast().ToList() ?? new List(); + return selected.Contains(tile) ? selected : new List { tile }; + } + + private void RaiseReorderChanged() + { + OnPropertyChanged(nameof(CanReorder)); + OnPropertyChanged(nameof(ReorderHint)); + CommandManager.InvalidateRequerySuggested(); + } + private void RemoveSelected() { var selected = SelectedGames?.Cast().ToList(); diff --git a/source/GameCollections/ViewModels/CollectionGameViewModel.cs b/source/GameCollections/ViewModels/CollectionGameViewModel.cs index a1b337e..2c92a85 100644 --- a/source/GameCollections/ViewModels/CollectionGameViewModel.cs +++ b/source/GameCollections/ViewModels/CollectionGameViewModel.cs @@ -17,6 +17,7 @@ namespace GameCollections.ViewModels private static readonly ILogger logger = LogManager.GetLogger(); private readonly CollectionManager manager; + private readonly CollectionDetailsViewModel owner; private bool coverRequested; private string coverPath; private int coverVersion; @@ -40,15 +41,26 @@ namespace GameCollections.ViewModels public RelayCommand PlayCommand { get; } public RelayCommand ShowInLibraryCommand { get; } public RelayCommand RemoveCommand { get; } + public RelayCommand MoveToTopCommand { get; } + public RelayCommand MoveUpCommand { get; } + public RelayCommand MoveDownCommand { get; } + public RelayCommand MoveToBottomCommand { get; } + + public bool CanRemove => owner.CanRemove; public CollectionGameViewModel(Game game, int order, CollectionManager manager, CollectionDetailsViewModel owner) { this.game = game; this.manager = manager; + this.owner = owner; Order = order; PlayCommand = new RelayCommand(() => owner.PlayGame(this)); ShowInLibraryCommand = new RelayCommand(() => owner.ShowGameInLibrary(this)); RemoveCommand = new RelayCommand(() => owner.RemoveGame(this)); + MoveToTopCommand = new RelayCommand(() => owner.MoveToEdge(this, false), () => owner.CanReorder); + MoveUpCommand = new RelayCommand(() => owner.MoveOneStep(this, false), () => owner.CanReorder); + MoveDownCommand = new RelayCommand(() => owner.MoveOneStep(this, true), () => owner.CanReorder); + MoveToBottomCommand = new RelayCommand(() => owner.MoveToEdge(this, true), () => owner.CanReorder); } public void Update(Game updatedGame, int order) @@ -59,6 +71,7 @@ namespace GameCollections.ViewModels OnPropertyChanged(nameof(Name)); OnPropertyChanged(nameof(IsInstalled)); OnPropertyChanged(nameof(PlayActionText)); + OnPropertyChanged(nameof(CanRemove)); if (coverRequested && manager.GetGameCoverPath(game) != coverPath) { diff --git a/source/GameCollections/ViewModels/CollectionsRootViewModel.cs b/source/GameCollections/ViewModels/CollectionsRootViewModel.cs index c37eb63..5621375 100644 --- a/source/GameCollections/ViewModels/CollectionsRootViewModel.cs +++ b/source/GameCollections/ViewModels/CollectionsRootViewModel.cs @@ -20,6 +20,13 @@ namespace GameCollections.ViewModels public CollectionsHomeViewModel Home { get; } + private CollectionDetailsViewModel windowPage; + + /// + /// Brings the sidebar view to the front; supplied by the plugin, which owns the sidebar item. + /// + public Action SwitchToSidebarView { get; set; } + private object currentPage; public object CurrentPage { get => currentPage; private set => SetValue(ref currentPage, value); } @@ -52,6 +59,36 @@ namespace GameCollections.ViewModels } } + /// + /// Opens the collection's page in its own window, for places outside the sidebar view. + /// + public void OpenCollectionInWindow(Guid id) + { + var card = Home.GetCard(id); + if (card != null) + { + windowPage = new CollectionDetailsViewModel(playniteApi, manager, this, card); + try + { + dialogs.ShowCollectionPage(windowPage); + } + finally + { + windowPage = null; + } + } + } + + /// + /// Closes the window showing the collection and goes to its page in the sidebar view. + /// + public void ShowInCollectionsSection(Guid id) + { + OpenCollection(id); + windowPage?.CloseWindow?.Invoke(); + SwitchToSidebarView?.Invoke(id); + } + public void CreateCollection() { var id = dialogs.ShowCreateCollection(); @@ -94,6 +131,7 @@ namespace GameCollections.ViewModels { Home.OnGamesUpdated(gameIds); (CurrentPage as CollectionDetailsViewModel)?.OnGamesUpdated(gameIds); + windowPage?.OnGamesUpdated(gameIds); } private void OnCollectionsChanged(object sender, CollectionsChangedEventArgs e) @@ -110,6 +148,18 @@ namespace GameCollections.ViewModels details.Reload(); } } + + if (windowPage != null) + { + if (manager.GetCollection(windowPage.CollectionId) == null) + { + windowPage.CloseWindow?.Invoke(); + } + else if (e.ChangedIds == null || e.ChangedIds.Contains(windowPage.CollectionId)) + { + windowPage.Reload(); + } + } } } } diff --git a/source/GameCollections/ViewModels/EditCollectionViewModel.cs b/source/GameCollections/ViewModels/EditCollectionViewModel.cs index 5ee6132..d5b81ef 100644 --- a/source/GameCollections/ViewModels/EditCollectionViewModel.cs +++ b/source/GameCollections/ViewModels/EditCollectionViewModel.cs @@ -75,7 +75,58 @@ namespace GameCollections.ViewModels // 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 bool CanSave => manager.ValidateTitle(title, existing?.Id) == null && (!isDynamic || Rules.IsComplete); + + public DynamicRulesViewModel Rules { get; } + + private bool isDynamic; + public bool IsDynamic + { + get => isDynamic; + set + { + if (isDynamic == value) + { + return; + } + + SetValue(ref isDynamic, value); + OnPropertyChanged(nameof(IsManual)); + OnPropertyChanged(nameof(TypeChangeNote)); + RaiseValidationChanged(); + if (value) + { + Rules.UpdatePreview(); + } + + DynamicModeChanged?.Invoke(this, EventArgs.Empty); + } + } + + public bool IsManual { get => !isDynamic; set => IsDynamic = !value; } + + public event EventHandler DynamicModeChanged; + + /// + /// Says what happens to the existing games when an existing collection changes type. + /// + public string TypeChangeNote + { + get + { + if (existing == null || existing.IsDynamic == isDynamic) + { + return null; + } + + if (isDynamic) + { + return existing.GameIds.Count > 0 ? Loc.Get("LOCGameCollections_WarningReplaceGames") : null; + } + + return Loc.Get("LOCGameCollections_NoteKeepGames"); + } + } public RelayCommand SaveCommand { get; } public RelayCommand CancelCommand { get; } @@ -95,6 +146,10 @@ namespace GameCollections.ViewModels rating = existing.Rating; } + isDynamic = existing?.IsDynamic == true; + Rules = new DynamicRulesViewModel(playniteApi, existing?.Rules); + Rules.RulesChanged += (s, e) => RaiseValidationChanged(); + SaveCommand = new RelayCommand(Save); CancelCommand = new RelayCommand(() => CloseRequested?.Invoke(false)); BrowsePosterCommand = new RelayCommand(BrowsePoster); @@ -199,12 +254,12 @@ namespace GameCollections.ViewModels { if (existing == null) { - var created = manager.CreateCollection(title, description, rating, posterChange == PosterChange.Replace ? posterSourcePath : null, null); + var created = manager.CreateCollection(title, description, rating, posterChange == PosterChange.Replace ? posterSourcePath : null, null, isDynamic ? Rules.ToModel() : null); SavedCollectionId = created.Id; } else { - manager.UpdateCollection(existing.Id, title, description, rating, posterChange, posterSourcePath); + manager.UpdateCollection(existing.Id, title, description, rating, posterChange, posterSourcePath, isDynamic ? Rules.ToModel() : null); SavedCollectionId = existing.Id; } diff --git a/source/GameCollections/ViewModels/RuleBuilderViewModels.cs b/source/GameCollections/ViewModels/RuleBuilderViewModels.cs new file mode 100644 index 0000000..87d0d84 --- /dev/null +++ b/source/GameCollections/ViewModels/RuleBuilderViewModels.cs @@ -0,0 +1,585 @@ +using GameCollections.Models; +using GameCollections.Services; +using Playnite.SDK; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Linq; +using System.Windows.Data; +using System.Windows.Threading; + +namespace GameCollections.ViewModels +{ + public class RuleFieldChoice + { + public RuleField Field { get; } + public string Label { get; } + + public RuleFieldChoice(RuleField field) + { + Field = field; + Label = RuleText.FieldName(field); + } + } + + public class RuleOperatorChoice + { + public RuleOperator Operator { get; } + public string Label { get; } + + public RuleOperatorChoice(RuleField field, RuleOperator op) + { + Operator = op; + Label = RuleText.OperatorName(field, op); + } + } + + /// + /// A row in the value picker of a list field such as platforms or tags. + /// + public class RuleOptionItem : ObservableObject + { + private readonly Action selectionChanged; + + public Guid Id { get; } + public string Name { get; } + + private bool isSelected; + public bool IsSelected + { + get => isSelected; + set + { + if (isSelected != value) + { + SetValue(ref isSelected, value); + selectionChanged(this); + } + } + } + + public RelayCommand RemoveCommand { get; } + + public RuleOptionItem(RuleOption option, Action selectionChanged) + { + Id = option.Id; + Name = option.Name; + this.selectionChanged = selectionChanged; + RemoveCommand = new RelayCommand(() => IsSelected = false); + } + } + + /// + /// One row of the rule builder: field, operator and the value editor for that combination. + /// + public class RuleConditionViewModel : ObservableObject + { + private static readonly RuleField[] FieldOrder = + { + RuleField.Name, RuleField.Platform, RuleField.Genre, RuleField.Developer, RuleField.Publisher, + RuleField.Category, RuleField.Feature, RuleField.Tag, RuleField.Series, RuleField.CompletionStatus, + RuleField.ReleaseDate, RuleField.LastPlayed, RuleField.TimePlayed, RuleField.PlayCount, + RuleField.UserScore, RuleField.CriticScore, RuleField.CommunityScore + }; + + private readonly RuleText ruleText; + private readonly Action changed; + + public static IReadOnlyList Fields { get; } = FieldOrder.Select(f => new RuleFieldChoice(f)).ToList(); + + public RuleBlockViewModel Block { get; } + + private RuleField field; + public RuleField Field + { + get => field; + set + { + if (field == value) + { + return; + } + + SetValue(ref field, value); + // Values from another field wouldn't make sense here, except that a name or date is re-typed anyway. + text = text2 = numberText = numberText2 = string.Empty; + OnPropertyChanged(nameof(Text)); + OnPropertyChanged(nameof(Text2)); + OnPropertyChanged(nameof(NumberText)); + OnPropertyChanged(nameof(NumberText2)); + LoadFieldState(null); + Operator = Operators[0].Operator; + OnPropertyChanged(nameof(Operators)); + RaiseEditorChanged(); + } + } + + public IReadOnlyList Operators { get; private set; } + + private RuleOperator op; + public RuleOperator Operator + { + get => op; + set + { + SetValue(ref op, value); + RaiseEditorChanged(); + } + } + + private string text = string.Empty; + public string Text { get => text; set => SetEditorValue(ref text, value); } + + private string text2 = string.Empty; + public string Text2 { get => text2; set => SetEditorValue(ref text2, value); } + + private string numberText = string.Empty; + public string NumberText { get => numberText; set => SetEditorValue(ref numberText, value); } + + private string numberText2 = string.Empty; + public string NumberText2 { get => numberText2; set => SetEditorValue(ref numberText2, value); } + + public ObservableCollection SelectedItems { get; } = new ObservableCollection(); + + private ListCollectionView optionsView; + public ListCollectionView OptionsView { get => optionsView; private set => SetValue(ref optionsView, value); } + + private string optionSearch = string.Empty; + public string OptionSearch + { + get => optionSearch; + set + { + SetValue(ref optionSearch, value ?? string.Empty); + OptionsView?.Refresh(); + } + } + + public bool HasNoOptions => OptionsView == null || OptionsView.SourceCollection.Cast().FirstOrDefault() == null; + + private RuleValueKind Kind => RuleEngine.GetValueKind(field); + private bool IsDayCount => op == RuleOperator.InLastDays || op == RuleOperator.OlderThanDays; + private bool NeedsValue => op != RuleOperator.IsEmpty; + + public bool ShowText => Kind == RuleValueKind.Text; + public bool ShowItems => Kind == RuleValueKind.Items && NeedsValue; + public bool ShowDate => Kind == RuleValueKind.Date && NeedsValue && !IsDayCount; + public bool ShowDate2 => ShowDate && op == RuleOperator.Between; + public bool ShowNumber => (Kind == RuleValueKind.Number && NeedsValue) || (Kind == RuleValueKind.Date && IsDayCount); + public bool ShowNumber2 => Kind == RuleValueKind.Number && op == RuleOperator.Between; + + public string UnitText + { + get + { + if (IsDayCount) + { + return Loc.Get("LOCGameCollections_RuleUnitDays"); + } + + switch (field) + { + case RuleField.TimePlayed: return Loc.Get("LOCGameCollections_RuleUnitHours"); + case RuleField.PlayCount: return Loc.Get("LOCGameCollections_RuleUnitTimes"); + case RuleField.UserScore: + case RuleField.CriticScore: + case RuleField.CommunityScore: return Loc.Get("LOCGameCollections_RuleUnitScore"); + default: return null; + } + } + } + + /// + /// Explains a value that was typed but can't be used. Values not filled in yet aren't errors. + /// + public string ValueError + { + get + { + if (ShowDate) + { + var hasBadDate = (text.Trim().Length > 0 && !RuleEngine.TryParseDatePeriod(text, out _, out _)) || + (ShowDate2 && text2.Trim().Length > 0 && !RuleEngine.TryParseDatePeriod(text2, out _, out _)); + if (hasBadDate) + { + return Loc.Get("LOCGameCollections_RuleErrorDate"); + } + + return ShowDate2 && text.Trim().Length > 0 && text2.Trim().Length > 0 && !RuleEngine.IsComplete(ToModel()) + ? Loc.Get("LOCGameCollections_RuleErrorRange") + : null; + } + + if (ShowNumber) + { + var hasBadNumber = (numberText.Trim().Length > 0 && !IsValidNumber(numberText)) || + (ShowNumber2 && numberText2.Trim().Length > 0 && !IsValidNumber(numberText2)); + if (hasBadNumber) + { + return Loc.Get("LOCGameCollections_RuleErrorNumber"); + } + + return ShowNumber2 && numberText.Trim().Length > 0 && numberText2.Trim().Length > 0 && !RuleEngine.IsComplete(ToModel()) + ? Loc.Get("LOCGameCollections_RuleErrorRange") + : null; + } + + return null; + } + } + + public string ItemsButtonText => SelectedItems.Count == 0 + ? Loc.Get("LOCGameCollections_RuleChooseValues") + : Loc.Get("LOCGameCollections_RuleChangeValues"); + + public bool IsComplete => RuleEngine.IsComplete(ToModel()); + + public RelayCommand RemoveCommand { get; } + + public RuleConditionViewModel(RuleBlockViewModel block, RuleText ruleText, RuleCondition source, Action changed) + { + Block = block; + this.ruleText = ruleText; + this.changed = changed; + RemoveCommand = new RelayCommand(() => block.RemoveCondition(this)); + + field = source?.Field ?? RuleField.Platform; + LoadFieldState(source?.ItemIds); + op = source != null && Operators.Any(o => o.Operator == source.Operator) ? source.Operator : Operators[0].Operator; + if (source != null) + { + text = source.Text ?? string.Empty; + text2 = source.Text2 ?? string.Empty; + numberText = source.Number?.ToString(CultureInfo.CurrentCulture) ?? string.Empty; + numberText2 = source.Number2?.ToString(CultureInfo.CurrentCulture) ?? string.Empty; + } + } + + public RuleCondition ToModel() + { + var condition = new RuleCondition { Field = field, Operator = op }; + if (ShowText || ShowDate) + { + condition.Text = text.Trim(); + } + + if (ShowDate2) + { + condition.Text2 = text2.Trim(); + } + + if (ShowNumber) + { + condition.Number = ParseNumber(numberText); + } + + if (ShowNumber2) + { + condition.Number2 = ParseNumber(numberText2); + } + + if (ShowItems) + { + condition.ItemIds = SelectedItems.Select(i => i.Id).ToList(); + } + + return condition; + } + + private void LoadFieldState(IList selectedIds) + { + Operators = RuleEngine.GetOperators(field).Select(o => new RuleOperatorChoice(field, o)).ToList(); + SelectedItems.Clear(); + optionSearch = string.Empty; + OnPropertyChanged(nameof(OptionSearch)); + + if (Kind != RuleValueKind.Items) + { + OptionsView = null; + return; + } + + var items = ruleText.GetOptions(field).Select(o => new RuleOptionItem(o, OnOptionSelectionChanged)).ToList(); + // Selections referring to a deleted tag or genre are dropped here, as there is nothing left to show for them. + if (selectedIds != null) + { + var selected = new HashSet(selectedIds); + foreach (var item in items.Where(i => selected.Contains(i.Id))) + { + item.IsSelected = true; + } + } + + OptionsView = new ListCollectionView(items) { Filter = FilterOption }; + OnPropertyChanged(nameof(HasNoOptions)); + } + + private bool FilterOption(object obj) + { + var query = optionSearch.Trim(); + return query.Length == 0 || ((RuleOptionItem)obj).Name.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0; + } + + private void OnOptionSelectionChanged(RuleOptionItem item) + { + if (item.IsSelected) + { + SelectedItems.Add(item); + } + else + { + SelectedItems.Remove(item); + } + + OnPropertyChanged(nameof(ItemsButtonText)); + changed?.Invoke(); + } + + private void SetEditorValue(ref string target, string value) + { + SetValue(ref target, value ?? string.Empty); + OnPropertyChanged(nameof(ValueError)); + changed?.Invoke(); + } + + private void RaiseEditorChanged() + { + OnPropertyChanged(nameof(ShowText)); + OnPropertyChanged(nameof(ShowItems)); + OnPropertyChanged(nameof(ShowDate)); + OnPropertyChanged(nameof(ShowDate2)); + OnPropertyChanged(nameof(ShowNumber)); + OnPropertyChanged(nameof(ShowNumber2)); + OnPropertyChanged(nameof(UnitText)); + OnPropertyChanged(nameof(ValueError)); + OnPropertyChanged(nameof(ItemsButtonText)); + changed?.Invoke(); + } + + private static bool IsValidNumber(string value) + { + return ParseNumber(value) >= 0; + } + + private static double? ParseNumber(string value) + { + return double.TryParse(value?.Trim(), NumberStyles.Float, CultureInfo.CurrentCulture, out var number) && !double.IsNaN(number) && !double.IsInfinity(number) + ? number + : (double?)null; + } + } + + /// + /// A group of conditions that must all be true. + /// + public class RuleBlockViewModel : ObservableObject + { + private readonly DynamicRulesViewModel owner; + private readonly RuleText ruleText; + + public ObservableCollection Conditions { get; } = new ObservableCollection(); + + private BlockJoin join; + public BlockJoin Join + { + get => join; + set + { + SetValue(ref join, value); + OnPropertyChanged(nameof(IsAnd)); + OnPropertyChanged(nameof(IsOr)); + owner.OnRulesChanged(); + } + } + + public bool IsAnd { get => join == BlockJoin.And; set { if (value) { Join = BlockJoin.And; } } } + public bool IsOr { get => join == BlockJoin.Or; set { if (value) { Join = BlockJoin.Or; } } } + + // Radio buttons are grouped by name, and each block's pair is its own group. + public string JoinGroupName { get; } = Guid.NewGuid().ToString("N"); + + private bool isFirst; + public bool IsFirst { get => isFirst; set => SetValue(ref isFirst, value); } + + private string title; + public string Title { get => title; set => SetValue(ref title, value); } + + public RelayCommand AddConditionCommand { get; } + public RelayCommand RemoveCommand { get; } + + public RuleBlockViewModel(DynamicRulesViewModel owner, RuleText ruleText, RuleBlock source) + { + this.owner = owner; + this.ruleText = ruleText; + join = source?.Join ?? BlockJoin.And; + AddConditionCommand = new RelayCommand(() => AddCondition(null)); + RemoveCommand = new RelayCommand(() => owner.RemoveBlock(this)); + + if (source?.Conditions != null) + { + foreach (var condition in source.Conditions) + { + Conditions.Add(new RuleConditionViewModel(this, ruleText, condition, owner.OnRulesChanged)); + } + } + + if (Conditions.Count == 0) + { + Conditions.Add(new RuleConditionViewModel(this, ruleText, null, owner.OnRulesChanged)); + } + } + + public void AddCondition(RuleCondition source) + { + Conditions.Add(new RuleConditionViewModel(this, ruleText, source, owner.OnRulesChanged)); + owner.OnRulesChanged(); + } + + /// + /// A block always keeps one condition: removing the last one removes the block, or resets + /// it when it is the only block, so the builder is never left with nothing to fill in. + /// + public void RemoveCondition(RuleConditionViewModel condition) + { + Conditions.Remove(condition); + if (Conditions.Count == 0) + { + if (owner.Blocks.Count > 1) + { + owner.RemoveBlock(this); + return; + } + + Conditions.Add(new RuleConditionViewModel(this, ruleText, null, owner.OnRulesChanged)); + } + + owner.OnRulesChanged(); + } + + public RuleBlock ToModel() + { + return new RuleBlock { Join = join, Conditions = Conditions.Select(c => c.ToModel()).ToList() }; + } + } + + /// + /// The rule builder of a dynamic collection, with a live preview of the matching games. + /// + public class DynamicRulesViewModel : ObservableObject + { + private const int PreviewNameCount = 6; + + private readonly IPlayniteAPI playniteApi; + private readonly RuleText ruleText; + private readonly DispatcherTimer previewTimer; + + public ObservableCollection Blocks { get; } = new ObservableCollection(); + + public event EventHandler RulesChanged; + + public bool IsComplete => RuleEngine.IsComplete(ToModel()); + + private int matchCount; + public int MatchCount { get => matchCount; private set => SetValue(ref matchCount, value); } + + private string previewText; + public string PreviewText { get => previewText; private set => SetValue(ref previewText, value); } + + private string previewNames; + public string PreviewNames { get => previewNames; private set => SetValue(ref previewNames, value); } + + public RelayCommand AddBlockCommand { get; } + + public DynamicRulesViewModel(IPlayniteAPI playniteApi, DynamicRules source) + { + this.playniteApi = playniteApi; + ruleText = new RuleText(playniteApi); + AddBlockCommand = new RelayCommand(AddBlock); + + // Waits for a pause in typing, so the library isn't searched on every keystroke. + previewTimer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(250) }; + previewTimer.Tick += (s, e) => + { + previewTimer.Stop(); + UpdatePreview(); + }; + + if (source?.Blocks != null) + { + foreach (var block in source.Blocks) + { + Blocks.Add(new RuleBlockViewModel(this, ruleText, block)); + } + } + + if (Blocks.Count == 0) + { + Blocks.Add(new RuleBlockViewModel(this, ruleText, null)); + } + + UpdateBlockTitles(); + UpdatePreview(); + } + + public DynamicRules ToModel() + { + return new DynamicRules { Blocks = Blocks.Select(b => b.ToModel()).ToList() }; + } + + public void OnRulesChanged() + { + previewTimer?.Stop(); + previewTimer?.Start(); + OnPropertyChanged(nameof(IsComplete)); + RulesChanged?.Invoke(this, EventArgs.Empty); + } + + public void RemoveBlock(RuleBlockViewModel block) + { + if (Blocks.Count > 1) + { + Blocks.Remove(block); + UpdateBlockTitles(); + OnRulesChanged(); + } + } + + public void UpdatePreview() + { + var rules = ToModel(); + if (!RuleEngine.IsComplete(rules)) + { + MatchCount = 0; + PreviewText = Loc.Get("LOCGameCollections_RulePreviewIncomplete"); + PreviewNames = null; + return; + } + + var isMatch = RuleEngine.Compile(rules, DateTime.Now); + var matches = playniteApi.Database.Games.Where(isMatch).ToList(); + MatchCount = matches.Count; + PreviewText = Loc.Format("LOCGameCollections_RulePreviewCount", Loc.GameCount(matches.Count)); + PreviewNames = matches.Count == 0 + ? null + : string.Join(", ", matches.Select(g => g.Name).OrderBy(n => n, StringComparer.CurrentCultureIgnoreCase).Take(PreviewNameCount)) + + (matches.Count > PreviewNameCount ? "…" : string.Empty); + } + + private void AddBlock() + { + Blocks.Add(new RuleBlockViewModel(this, ruleText, null)); + UpdateBlockTitles(); + OnRulesChanged(); + } + + private void UpdateBlockTitles() + { + for (var i = 0; i < Blocks.Count; i++) + { + Blocks[i].IsFirst = i == 0; + Blocks[i].Title = Loc.Format("LOCGameCollections_RuleBlockTitle", i + 1); + } + } + } +} diff --git a/source/GameCollections/Views/CollectionDetailsView.xaml b/source/GameCollections/Views/CollectionDetailsView.xaml index 20d7cb2..f6272cf 100644 --- a/source/GameCollections/Views/CollectionDetailsView.xaml +++ b/source/GameCollections/Views/CollectionDetailsView.xaml @@ -18,7 +18,13 @@ - + + + + + + @@ -50,6 +59,7 @@ + + + + + + diff --git a/source/GameCollections/Views/GameCollectionsControl.xaml.cs b/source/GameCollections/Views/GameCollectionsControl.xaml.cs new file mode 100644 index 0000000..d6152dd --- /dev/null +++ b/source/GameCollections/Views/GameCollectionsControl.xaml.cs @@ -0,0 +1,123 @@ +using GameCollections.Models; +using GameCollections.Services; +using GameCollections.Settings; +using Playnite.SDK; +using Playnite.SDK.Controls; +using Playnite.SDK.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Media; + +namespace GameCollections.Views +{ + /// + /// A collection shown in the game details view. + /// + public class DetailsCollectionItem : ObservableObject + { + private const int PosterDecodeWidth = 170; + private static readonly ILogger logger = LogManager.GetLogger(); + + public string Title { get; } + public bool IsDynamic { get; } + public RelayCommand OpenCommand { get; } + + private ImageSource poster; + public ImageSource Poster { get => poster; private set => SetValue(ref poster, value); } + + public DetailsCollectionItem(GameCollection collection, string posterPath, Action open) + { + Title = collection.Title; + IsDynamic = collection.IsDynamic; + var id = collection.Id; + OpenCommand = new RelayCommand(() => open(id)); + _ = LoadPosterAsync(posterPath); + } + + private async Task LoadPosterAsync(string path) + { + try + { + Poster = await ImageLoader.LoadAsync(path, PosterDecodeWidth); + } + catch (Exception e) + { + logger.Error(e, $"Failed to load poster for collection {Title}."); + } + } + } + + /// + /// Lists the collections of the selected game, in themes that place this custom element. + /// Playnite creates one instance per place the theme uses it and supplies the game through the game context. + /// + public partial class GameCollectionsControl : PluginUserControl + { + private readonly CollectionManager manager; + private readonly GameCollectionsSettingsViewModel settings; + private readonly Action openCollection; + + /// + /// True for the instance this extension added itself, rather than one placed by a theme. + /// + public bool IsInjected { get; set; } + + public GameCollectionsControl(CollectionManager manager, GameCollectionsSettingsViewModel settings, Action openCollection) + { + this.manager = manager; + this.settings = settings; + this.openCollection = openCollection; + InitializeComponent(); + Visibility = Visibility.Collapsed; + + // Subscribed only while shown, so a control the theme discards doesn't stay alive through these events. + Loaded += (s, e) => + { + manager.CollectionsChanged += Manager_CollectionsChanged; + settings.SettingsChanged += Settings_SettingsChanged; + UpdateItems(); + }; + Unloaded += (s, e) => + { + manager.CollectionsChanged -= Manager_CollectionsChanged; + settings.SettingsChanged -= Settings_SettingsChanged; + }; + } + + public override void GameContextChanged(Game oldContext, Game newContext) + { + UpdateItems(); + } + + private void Manager_CollectionsChanged(object sender, CollectionsChangedEventArgs e) + { + UpdateItems(); + } + + private void Settings_SettingsChanged(object sender, EventArgs e) + { + UpdateItems(); + } + + private void UpdateItems() + { + var game = GameContext; + var collections = game == null + ? new List() + : manager.GetCollectionsForGame(game.Id) + .Where(c => !c.IsDynamic || settings.Settings.ShowDynamicCollectionsInDetails) + .ToList(); + + ItemsList.ItemsSource = collections + .Select(c => new DetailsCollectionItem(c, manager.ResolvePosterPath(c), openCollection)) + .ToList(); + + var hasItems = collections.Count > 0; + Visibility = hasItems ? Visibility.Visible : Visibility.Collapsed; + settings.Settings.IsDetailsControlVisible = hasItems; + } + } +} diff --git a/source/GameCollections/Views/RuleBuilderView.xaml b/source/GameCollections/Views/RuleBuilderView.xaml new file mode 100644 index 0000000..683d726 --- /dev/null +++ b/source/GameCollections/Views/RuleBuilderView.xaml @@ -0,0 +1,194 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source/GameCollections/Views/RuleBuilderView.xaml.cs b/source/GameCollections/Views/RuleBuilderView.xaml.cs new file mode 100644 index 0000000..0d3c8b7 --- /dev/null +++ b/source/GameCollections/Views/RuleBuilderView.xaml.cs @@ -0,0 +1,48 @@ +using System; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Media; +using System.Windows.Threading; + +namespace GameCollections.Views +{ + public partial class RuleBuilderView : UserControl + { + public RuleBuilderView() + { + InitializeComponent(); + } + + private void PickerPopup_Opened(object sender, EventArgs e) + { + var popup = (Popup)sender; + Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() => + { + if (popup.Child != null && FindSearchBox(popup.Child) is SearchBox searchBox) + { + searchBox.FocusInput(); + } + })); + } + + private static SearchBox FindSearchBox(Visual parent) + { + for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) + { + var child = VisualTreeHelper.GetChild(parent, i) as Visual; + if (child is SearchBox match) + { + return match; + } + + var nested = child == null ? null : FindSearchBox(child); + if (nested != null) + { + return nested; + } + } + + return null; + } + } +} diff --git a/source/GameCollections/Views/Styles.xaml b/source/GameCollections/Views/Styles.xaml index 5ca7de4..17d5b86 100644 --- a/source/GameCollections/Views/Styles.xaml +++ b/source/GameCollections/Views/Styles.xaml @@ -9,6 +9,7 @@ + + + + + +