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
This commit is contained in:
1 parent
72e35002f7
commit
690a79b014
41 files changed
+3739
-52
No files matched your search
@@ -7,7 +7,7 @@
|
||||
<RootNamespace>GameCollections</RootNamespace>
|
||||
<AssemblyName>GameCollections</AssemblyName>
|
||||
<LangVersion>7.3</LangVersion>
|
||||
<Version>1.0.0</Version>
|
||||
<Version>1.1.0</Version>
|
||||
<Product>Game Collections</Product>
|
||||
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
|
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
||||
@@ -16,6 +16,9 @@
|
||||
<ItemGroup>
|
||||
<!-- Playnite.SDK.dll is supplied by Playnite at runtime, so it is not copied to the output. -->
|
||||
<PackageReference Include="PlayniteSDK" Version="6.11.0" ExcludeAssets="runtime" />
|
||||
<!-- Used for data migrations. Compile-time only: Playnite supplies its own copy at runtime, so this
|
||||
version has to match Playnite's and its NuGet advisory doesn't apply to anything shipped here. -->
|
||||
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" ExcludeAssets="runtime" NoWarn="NU1903" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -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<string> { 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<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args)
|
||||
@@ -98,7 +164,7 @@ namespace GameCollections
|
||||
|
||||
public override IEnumerable<SidebarItem> 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<Game> 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<Game> e)
|
||||
{
|
||||
if (rootViewModel == null || e.UpdatedItems == null || e.UpdatedItems.Count == 0)
|
||||
if (e.UpdatedItems == null || e.UpdatedItems.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var updatedIds = new HashSet<Guid>(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)
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<sys:String x:Key="LOCGameCollections_PluginName">Game Collections</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_SidebarTitle">Collections</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_MenuAddToCollection">Add to Collection…</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_SettingsEmpty">There are no settings for Game Collections yet.</sys:String>
|
||||
|
||||
<!-- Collections page -->
|
||||
<sys:String x:Key="LOCGameCollections_PageTitle">Collections</sys:String>
|
||||
@@ -76,6 +75,97 @@
|
||||
<sys:String x:Key="LOCGameCollections_Save">Save</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_Cancel">Cancel</sys:String>
|
||||
|
||||
<!-- Dynamic collections -->
|
||||
<sys:String x:Key="LOCGameCollections_CollectionType">Type</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_TypeManual">Manual: you choose the games</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_TypeDynamic">Dynamic: filled automatically by rules</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_DynamicBadge">Dynamic</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_WarningReplaceGames">Saving replaces this collection's current games with the games matching the rules.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_NoteKeepGames">Saving keeps the current games, but they will no longer update automatically.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RefreshNow">Refresh now</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RefreshNowTooltip">Check the whole library against the rules again</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RulesSummary">Rules: {0}</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_DynamicEmptyTitle">No games match these rules</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_DynamicEmptyDescription">Edit the collection to change its rules. It updates by itself when a game starts to match.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleBlockTitle">Block {0}</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleBlockHint">A game must meet every condition in this block</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleAddCondition">Add condition</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleRemoveCondition">Remove condition</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleAddBlock">Add block</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleRemoveBlock">Remove block</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleJoinAnd">AND</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleJoinOr">OR</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOrderHint">Blocks are combined in order, from top to bottom. Hidden games are never included.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleAnd">and</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOr">or</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldLabel">Field</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorLabel">Condition</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleChooseValues">Choose…</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleChangeValues">Change…</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleSearchValues">Search</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleNoValues">There is nothing to choose from in your library.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleDateHint">YYYY, YYYY-MM or YYYY-MM-DD</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleErrorDate">Enter a date as YYYY, YYYY-MM or YYYY-MM-DD.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleErrorNumber">Enter a number of 0 or more.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleErrorRange">The second value must not be lower than the first.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RulePreviewIncomplete">Complete every condition to see the matching games.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RulePreviewCount">Currently matches {0}</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleUnitDays">days</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleUnitHours">hours</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleUnitTimes">times</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleUnitScore">out of 100</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldName">Name</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldPlatform">Platform</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldGenre">Genres</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldDeveloper">Developers</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldPublisher">Publishers</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldCategory">Categories</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldFeature">Features</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldTag">Tags</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldSeries">Series</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldCompletionStatus">Completion status</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldReleaseDate">Release date</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldLastPlayed">Last played</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldUserScore">User score</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldCriticScore">Critic score</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldCommunityScore">Community score</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldTimePlayed">Time played</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleFieldPlayCount">Play count</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorContains">includes</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorNotContains">does not include</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorIncludesAny">includes any of</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorIncludesAll">includes all of</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorExcludes">includes none of</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorAtLeast">at least</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorAtMost">at most</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorBetween">between</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorBefore">before</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorAfter">after</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorInLastDays">in the last</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorOlderThanDays">older than</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorIsEmpty">is empty</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_RuleOperatorNoDate">has no date</sys:String>
|
||||
|
||||
<!-- Manual order -->
|
||||
<sys:String x:Key="LOCGameCollections_MoveToTop">Move to top</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_MoveUp">Move earlier</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_MoveDown">Move later</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_MoveToBottom">Move to end</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_ReorderHint">Drag games to reorder them</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_ReorderUnavailableHint">To reorder, sort by Collection order, ascending</sys:String>
|
||||
|
||||
<!-- Game details and settings -->
|
||||
<sys:String x:Key="LOCGameCollections_DetailsHeader">Collections</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_SettingShowDynamicInDetails">Display dynamic collections in details view</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_SettingShowDynamicInDetailsHint">When off, game details only list manual collections.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_SettingAddListToAnyTheme">Show collections in details view</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_SettingAddListToAnyThemeHint">Adds the list below the game description. Turn this off if it looks wrong in your theme.</sys:String>
|
||||
|
||||
<!-- Opening a collection from game details -->
|
||||
<sys:String x:Key="LOCGameCollections_OpenInCollections">Open in Collections</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_OpenInCollectionsTooltip">Go to this collection's page in the Collections section</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_OpenCollectionsManually">"{0}" is open in Collections. Click Collections in the sidebar to see it.</sys:String>
|
||||
|
||||
<!-- Errors and warnings -->
|
||||
<sys:String x:Key="LOCGameCollections_ErrorTitleRequired">A title is required.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_ErrorTitleTooLong">The title can be at most {0} characters long.</sys:String>
|
||||
@@ -88,5 +178,6 @@
|
||||
<sys:String x:Key="LOCGameCollections_ErrorSaveFailed">Game Collections could not save your collections: {0}</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_ErrorLoadFailed">Game Collections could not load your collections: {0}</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_WarningRestoredFromBackup">Game Collections could not read its data file and restored your collections from the most recent backup.</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_WarningNewerData">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}".</sys:String>
|
||||
<sys:String x:Key="LOCGameCollections_WarningDataUnreadable">Game Collections could not read its data file. The unreadable file was kept at "{0}".</sys:String>
|
||||
</ResourceDictionary>
|
||||
@@ -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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One test on a game. Which value members are used depends on the field and operator.
|
||||
/// </summary>
|
||||
public class RuleCondition
|
||||
{
|
||||
public RuleField Field { get; set; }
|
||||
public RuleOperator Operator { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The search text for names, or the first date (YYYY, YYYY-MM or YYYY-MM-DD).
|
||||
/// </summary>
|
||||
public string Text { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The second date of a "between" condition.
|
||||
/// </summary>
|
||||
public string Text2 { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The score, hours, play count or number of days.
|
||||
/// </summary>
|
||||
public double? Number { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The upper bound of a "between" condition.
|
||||
/// </summary>
|
||||
public double? Number2 { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// IDs of the selected platforms, genres, tags etc. IDs are stored rather than names so renaming a tag keeps the rule working.
|
||||
/// </summary>
|
||||
public List<Guid> ItemIds { get; set; } = new List<Guid>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A group of conditions that must all be true.
|
||||
/// </summary>
|
||||
public class RuleBlock
|
||||
{
|
||||
/// <summary>
|
||||
/// How this block combines with the result of the blocks above it. Not used on the first block.
|
||||
/// </summary>
|
||||
public BlockJoin Join { get; set; }
|
||||
|
||||
public List<RuleCondition> Conditions { get; set; } = new List<RuleCondition>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rules of a dynamic collection. Blocks are combined from top to bottom.
|
||||
/// </summary>
|
||||
public class DynamicRules
|
||||
{
|
||||
public List<RuleBlock> Blocks { get; set; } = new List<RuleBlock>();
|
||||
}
|
||||
}
|
||||
@@ -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<Guid> GameIds { get; set; } = new List<Guid>();
|
||||
|
||||
/// <summary>
|
||||
/// The rules of a dynamic collection, or null for a manual one. For a dynamic collection
|
||||
/// <see cref="GameIds"/> holds the latest matches, so it is available without searching the library.
|
||||
/// </summary>
|
||||
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
|
||||
/// </summary>
|
||||
public class CollectionsDataFile
|
||||
{
|
||||
/// <summary>
|
||||
/// The version of this file's format. See <c>CollectionsDataMigrator</c>.
|
||||
/// </summary>
|
||||
public int SchemaVersion { get; set; }
|
||||
public List<GameCollection> Collections { get; set; } = new List<GameCollection>();
|
||||
}
|
||||
|
||||
@@ -21,6 +21,20 @@ namespace GameCollections.Services
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The outcome of searching the library for one dynamic collection.
|
||||
/// </summary>
|
||||
public class DynamicMatchResult
|
||||
{
|
||||
public Guid CollectionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The rules the search used, to detect that they were edited in the meantime.
|
||||
/// </summary>
|
||||
public DynamicRules Rules { get; set; }
|
||||
public List<Guid> GameIds { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Owns the in-memory collection list and every operation on it. Each mutation is persisted
|
||||
/// immediately and announced through <see cref="CollectionsChanged"/>.
|
||||
@@ -38,6 +52,7 @@ namespace GameCollections.Services
|
||||
private readonly CollectionRepository repository;
|
||||
private readonly PosterStorage posterStorage;
|
||||
private readonly List<GameCollection> collections = new List<GameCollection>();
|
||||
private Dictionary<Guid, List<GameCollection>> collectionsByGame;
|
||||
|
||||
public event EventHandler<CollectionsChangedEventArgs> 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<Guid> gameIds)
|
||||
public GameCollection CreateCollection(string title, string description, double rating, string posterSourcePath, IEnumerable<Guid> 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)
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<Guid> gameIds)
|
||||
{
|
||||
var collection = GetCollection(collectionId);
|
||||
if (collection != null && AddDistinct(collection, gameIds))
|
||||
if (collection != null && !collection.IsDynamic && AddDistinct(collection, gameIds))
|
||||
{
|
||||
Persist(new[] { collectionId });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public void RemoveGames(Guid collectionId, IEnumerable<Guid> gameIds)
|
||||
{
|
||||
var collection = GetCollection(collectionId);
|
||||
if (collection != null && RemoveIds(collection, new HashSet<Guid>(gameIds)))
|
||||
if (collection != null && !collection.IsDynamic && RemoveIds(collection, new HashSet<Guid>(gameIds)))
|
||||
{
|
||||
Persist(new[] { collectionId });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves games within a collection, keeping their relative order. They are placed next to
|
||||
/// <paramref name="anchorId"/>: after it when <paramref name="after"/> is set, otherwise before it.
|
||||
/// A null anchor means the end of the collection when <paramref name="after"/> is set, otherwise the start.
|
||||
/// </summary>
|
||||
public bool MoveGames(Guid collectionId, IEnumerable<Guid> gameIds, Guid? anchorId, bool after)
|
||||
{
|
||||
var collection = GetCollection(collectionId);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var moving = new HashSet<Guid>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-checks one dynamic collection against the whole library right away.
|
||||
/// </summary>
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the games matching the rules, sorted by name. Safe to call on a background thread.
|
||||
/// </summary>
|
||||
public static List<Guid> FindMatches(DynamicRules rules, IEnumerable<Game> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public void ApplyMatches(IEnumerable<DynamicMatchResult> results)
|
||||
{
|
||||
var changed = new List<Guid>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public void ApplyGameChanges(ICollection<Guid> gameIds)
|
||||
{
|
||||
var changed = new List<Guid>();
|
||||
var now = DateTime.Now;
|
||||
foreach (var collection in collections.Where(c => c.IsDynamic))
|
||||
{
|
||||
var isMatch = RuleEngine.Compile(collection.Rules, now);
|
||||
var current = new HashSet<Guid>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static bool MergeMatches(GameCollection collection, IReadOnlyCollection<Guid> matches)
|
||||
{
|
||||
var matching = new HashSet<Guid>(matches);
|
||||
var merged = collection.GameIds.Where(matching.Contains).ToList();
|
||||
var current = new HashSet<Guid>(merged);
|
||||
merged.AddRange(matches.Where(id => !current.Contains(id)));
|
||||
if (merged.SequenceEqual(collection.GameIds))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
collection.GameIds = merged;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the result of the "Add to Collection" dialog in a single save:
|
||||
/// <paramref name="membership"/> maps collection IDs to whether the games should be in them,
|
||||
@@ -311,6 +499,32 @@ namespace GameCollections.Services
|
||||
|
||||
#region Games and posters
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public IReadOnlyList<GameCollection> GetCollectionsForGame(Guid gameId)
|
||||
{
|
||||
if (collectionsByGame == null)
|
||||
{
|
||||
collectionsByGame = new Dictionary<Guid, List<GameCollection>>();
|
||||
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<GameCollection>();
|
||||
}
|
||||
|
||||
list.Add(collection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return collectionsByGame.TryGetValue(gameId, out var result) ? result : (IReadOnlyList<GameCollection>)new GameCollection[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the collection's games that still exist in the library, in collection order.
|
||||
/// </summary>
|
||||
@@ -444,6 +658,7 @@ namespace GameCollections.Services
|
||||
|
||||
private bool Persist(IReadOnlyCollection<Guid> changedIds)
|
||||
{
|
||||
collectionsByGame = null;
|
||||
var saved = false;
|
||||
try
|
||||
{
|
||||
|
||||
@@ -32,7 +32,6 @@ namespace GameCollections.Services
|
||||
/// </summary>
|
||||
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<GameCollection> collections)
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private string FinishMigration(List<GameCollection> 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<GameCollection> collections, out DataMigrationResult migration)
|
||||
{
|
||||
collections = null;
|
||||
migration = null;
|
||||
try
|
||||
{
|
||||
var text = File.ReadAllText(path, Encoding.UTF8);
|
||||
var data = Serialization.FromJson<CollectionsDataFile>(text);
|
||||
migration = CollectionsDataMigrator.Migrate(text);
|
||||
var data = Serialization.FromJson<CollectionsDataFile>(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<RuleBlock>()).Where(b => b != null).ToList();
|
||||
foreach (var block in rules.Blocks)
|
||||
{
|
||||
block.Conditions = (block.Conditions ?? new List<RuleCondition>()).Where(c => c != null).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace GameCollections.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// One upgrade of the data file, from <see cref="FromVersion"/> to the next version.
|
||||
/// </summary>
|
||||
public class DataMigrationStep
|
||||
{
|
||||
public int FromVersion { get; }
|
||||
public Action<JObject> Apply { get; }
|
||||
|
||||
public DataMigrationStep(int fromVersion, Action<JObject> apply)
|
||||
{
|
||||
FromVersion = fromVersion;
|
||||
Apply = apply;
|
||||
}
|
||||
}
|
||||
|
||||
public class DataMigrationResult
|
||||
{
|
||||
public string Json { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The version the file had before migrating.
|
||||
/// </summary>
|
||||
public int FromVersion { get; set; }
|
||||
public bool WasMigrated { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The file was written by a newer version of the extension, which this one can't migrate back from.
|
||||
/// </summary>
|
||||
public bool IsNewerThanSupported { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="CurrentVersion"/> and add a step for the previous version.
|
||||
/// Existing steps must never be changed once released.
|
||||
/// </summary>
|
||||
public static class CollectionsDataMigrator
|
||||
{
|
||||
public const int CurrentVersion = 2;
|
||||
public const string VersionProperty = "SchemaVersion";
|
||||
|
||||
private static readonly IReadOnlyList<DataMigrationStep> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws if the file isn't valid JSON or a step is missing or fails. The input is not modified.
|
||||
/// </summary>
|
||||
public static DataMigrationResult Migrate(string json, int targetVersion, IReadOnlyList<DataMigrationStep> 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<int>() < 1)
|
||||
{
|
||||
throw new InvalidOperationException($"Invalid data version: {token}.");
|
||||
}
|
||||
|
||||
return token.Value<int>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<GameCollectionsControl> createControl;
|
||||
private readonly Func<Window> 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<GameCollectionsControl> createControl,
|
||||
Func<Window> 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<Game> games)
|
||||
{
|
||||
currentGame = games != null && games.Count == 1 ? games[0] : null;
|
||||
if (control != null)
|
||||
{
|
||||
control.GameContext = currentGame;
|
||||
}
|
||||
|
||||
searchAttemptsLeft = MaxSearchAttempts;
|
||||
Update();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes sure the list is where it should be right now. Never lets an error reach Playnite.
|
||||
/// </summary>
|
||||
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<string, FrameworkElement>();
|
||||
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<string, FrameworkElement> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,9 @@ namespace GameCollections.Services
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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
|
||||
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<Guid> pendingGames = new HashSet<Guid>();
|
||||
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();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Catches up on changes made while Playnite or the plugin wasn't running.
|
||||
/// </summary>
|
||||
public void Start()
|
||||
{
|
||||
ScheduleFullRefresh(StartupDelay);
|
||||
timeBasedRulesTimer.Start();
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
gameChangeTimer.Stop();
|
||||
fullRefreshTimer.Stop();
|
||||
timeBasedRulesTimer.Stop();
|
||||
}
|
||||
|
||||
public void NotifyGamesChanged(IEnumerable<Guid> gameIds)
|
||||
{
|
||||
pendingGames.UnionWith(gameIds);
|
||||
gameChangeTimer.Stop();
|
||||
gameChangeTimer.Start();
|
||||
}
|
||||
|
||||
public void ScheduleFullRefresh(TimeSpan delay)
|
||||
{
|
||||
fullRefreshTimer.Stop();
|
||||
fullRefreshTimer.Interval = delay;
|
||||
fullRefreshTimer.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-checks every dynamic collection against the whole library on a background thread.
|
||||
/// </summary>
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<RuleOperator> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Relative date rules change their result as time passes, without any game changing.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses YYYY, YYYY-MM or YYYY-MM-DD into the first and last day of that period.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the condition has every value its operator needs, and those values are valid.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static Func<Game, bool> 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<Game, bool> 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<Game, bool> 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<Game, bool> 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<Game, bool> CompileItems(RuleCondition condition)
|
||||
{
|
||||
var getIds = GetItemIds(condition.Field);
|
||||
var wanted = new HashSet<Guid>(condition.ItemIds ?? new List<Guid>());
|
||||
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<Game, IList<Guid>> 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<Game, bool> 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<Game, double?> 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<Game, bool> CompileDate(RuleCondition condition, DateTime now)
|
||||
{
|
||||
Func<Game, DateTime?> 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 _);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// A selectable value of a rule field, such as one platform or tag.
|
||||
/// </summary>
|
||||
public class RuleOption
|
||||
{
|
||||
public Guid Id { get; }
|
||||
public string Name { get; }
|
||||
|
||||
public RuleOption(Guid id, string name)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// User-facing names for rule fields and operators, the values a field can take, and rule summaries.
|
||||
/// </summary>
|
||||
public class RuleText
|
||||
{
|
||||
private readonly IPlayniteAPI playniteApi;
|
||||
private readonly Dictionary<RuleField, List<RuleOption>> optionsCache = new Dictionary<RuleField, List<RuleOption>>();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the values that can be chosen for a field, sorted by name. Loaded once per dialog.
|
||||
/// </summary>
|
||||
public IReadOnlyList<RuleOption> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes rules in one line, for example: Platform includes any of PC and Time played at least 10.
|
||||
/// </summary>
|
||||
public string Describe(DynamicRules rules)
|
||||
{
|
||||
if (rules?.Blocks == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var parts = new List<string>();
|
||||
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<DatabaseObject> 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<DatabaseObject>();
|
||||
}
|
||||
}
|
||||
|
||||
// Developers and publishers share one long company list, so only those actually used in that role are offered.
|
||||
private IEnumerable<DatabaseObject> LoadCompanies(Func<Game, List<Guid>> getIds)
|
||||
{
|
||||
var used = new HashSet<Guid>(playniteApi.Database.Games.Where(g => getIds(g) != null).SelectMany(getIds));
|
||||
return playniteApi.Database.Companies.Where(c => used.Contains(c.Id));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string> errors)
|
||||
|
||||
@@ -5,11 +5,18 @@
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="200" d:DesignWidth="600">
|
||||
<!-- No options yet. Future settings bind to Settings.* on GameCollectionsSettingsViewModel. -->
|
||||
<StackPanel Margin="20">
|
||||
<CheckBox IsChecked="{Binding Settings.AddDetailsListToAnyTheme}"
|
||||
Content="{DynamicResource LOCGameCollections_SettingAddListToAnyTheme}" />
|
||||
<TextBlock Style="{StaticResource BaseTextBlockStyle}"
|
||||
Foreground="{DynamicResource TextBrushDarker}"
|
||||
TextWrapping="Wrap"
|
||||
Text="{DynamicResource LOCGameCollections_SettingsEmpty}" />
|
||||
TextWrapping="Wrap" Margin="0,4,0,16"
|
||||
Text="{DynamicResource LOCGameCollections_SettingAddListToAnyThemeHint}" />
|
||||
<CheckBox IsChecked="{Binding Settings.ShowDynamicCollectionsInDetails}"
|
||||
Content="{DynamicResource LOCGameCollections_SettingShowDynamicInDetails}" />
|
||||
<TextBlock Style="{StaticResource BaseTextBlockStyle}"
|
||||
Foreground="{DynamicResource TextBrushDarker}"
|
||||
TextWrapping="Wrap" Margin="0,4,0,0"
|
||||
Text="{DynamicResource LOCGameCollections_SettingShowDynamicInDetailsHint}" />
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -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<Guid>(collection.GameIds);
|
||||
var containedCount = gameIds.Count(memberIds.Contains);
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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");
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public bool CanReorder => SortField == GameSortField.CollectionOrder && !SortDescending;
|
||||
public string ReorderHint => Loc.Get(CanReorder ? "LOCGameCollections_ReorderHint" : "LOCGameCollections_ReorderUnavailableHint");
|
||||
|
||||
/// <summary>
|
||||
/// Set when the page is shown in its own window instead of the sidebar view.
|
||||
/// </summary>
|
||||
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<Guid>(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
|
||||
/// </summary>
|
||||
public void RemoveGame(CollectionGameViewModel tile)
|
||||
{
|
||||
var selected = SelectedGames?.Cast<CollectionGameViewModel>().ToList() ?? new List<CollectionGameViewModel>();
|
||||
var targets = selected.Contains(tile) ? selected : new List<CollectionGameViewModel> { tile };
|
||||
var targets = GetMoveTargets(tile);
|
||||
manager.RemoveGames(CollectionId, targets.Select(t => t.Id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the games to just before or after another game. Dragging uses this directly.
|
||||
/// </summary>
|
||||
public void MoveGames(IEnumerable<Guid> gameIds, Guid anchorId, bool after)
|
||||
{
|
||||
if (CanReorder)
|
||||
{
|
||||
manager.MoveGames(CollectionId, gameIds, anchorId, after);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the tile, or the whole selection if the tile is part of it, past the neighbouring visible game.
|
||||
/// </summary>
|
||||
public void MoveOneStep(CollectionGameViewModel tile, bool later)
|
||||
{
|
||||
if (!CanReorder)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var targets = GetMoveTargets(tile);
|
||||
var visible = GamesView.Cast<CollectionGameViewModel>().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<CollectionGameViewModel> GetMoveTargets(CollectionGameViewModel tile)
|
||||
{
|
||||
var selected = SelectedGames?.Cast<CollectionGameViewModel>().ToList() ?? new List<CollectionGameViewModel>();
|
||||
return selected.Contains(tile) ? selected : new List<CollectionGameViewModel> { tile };
|
||||
}
|
||||
|
||||
private void RaiseReorderChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(CanReorder));
|
||||
OnPropertyChanged(nameof(ReorderHint));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
private void RemoveSelected()
|
||||
{
|
||||
var selected = SelectedGames?.Cast<CollectionGameViewModel>().ToList();
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -20,6 +20,13 @@ namespace GameCollections.ViewModels
|
||||
|
||||
public CollectionsHomeViewModel Home { get; }
|
||||
|
||||
private CollectionDetailsViewModel windowPage;
|
||||
|
||||
/// <summary>
|
||||
/// Brings the sidebar view to the front; supplied by the plugin, which owns the sidebar item.
|
||||
/// </summary>
|
||||
public Action<Guid> SwitchToSidebarView { get; set; }
|
||||
|
||||
private object currentPage;
|
||||
public object CurrentPage { get => currentPage; private set => SetValue(ref currentPage, value); }
|
||||
|
||||
@@ -52,6 +59,36 @@ namespace GameCollections.ViewModels
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the collection's page in its own window, for places outside the sidebar view.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the window showing the collection and goes to its page in the sidebar view.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Says what happens to the existing games when an existing collection changes type.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A row in the value picker of a list field such as platforms or tags.
|
||||
/// </summary>
|
||||
public class RuleOptionItem : ObservableObject
|
||||
{
|
||||
private readonly Action<RuleOptionItem> 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<RuleOptionItem> selectionChanged)
|
||||
{
|
||||
Id = option.Id;
|
||||
Name = option.Name;
|
||||
this.selectionChanged = selectionChanged;
|
||||
RemoveCommand = new RelayCommand(() => IsSelected = false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One row of the rule builder: field, operator and the value editor for that combination.
|
||||
/// </summary>
|
||||
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<RuleFieldChoice> 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<RuleOperatorChoice> 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<RuleOptionItem> SelectedItems { get; } = new ObservableCollection<RuleOptionItem>();
|
||||
|
||||
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<object>().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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Explains a value that was typed but can't be used. Values not filled in yet aren't errors.
|
||||
/// </summary>
|
||||
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<Guid> 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<Guid>(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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A group of conditions that must all be true.
|
||||
/// </summary>
|
||||
public class RuleBlockViewModel : ObservableObject
|
||||
{
|
||||
private readonly DynamicRulesViewModel owner;
|
||||
private readonly RuleText ruleText;
|
||||
|
||||
public ObservableCollection<RuleConditionViewModel> Conditions { get; } = new ObservableCollection<RuleConditionViewModel>();
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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() };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rule builder of a dynamic collection, with a live preview of the matching games.
|
||||
/// </summary>
|
||||
public class DynamicRulesViewModel : ObservableObject
|
||||
{
|
||||
private const int PreviewNameCount = 6;
|
||||
|
||||
private readonly IPlayniteAPI playniteApi;
|
||||
private readonly RuleText ruleText;
|
||||
private readonly DispatcherTimer previewTimer;
|
||||
|
||||
public ObservableCollection<RuleBlockViewModel> Blocks { get; } = new ObservableCollection<RuleBlockViewModel>();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,13 @@
|
||||
<MenuItem Header="{Binding PlayActionText}" Command="{Binding PlayCommand}" FontWeight="SemiBold" InputGestureText="Enter" />
|
||||
<MenuItem Header="{DynamicResource LOCGameCollections_ShowInLibrary}" Command="{Binding ShowInLibraryCommand}" />
|
||||
<Separator />
|
||||
<MenuItem Header="{DynamicResource LOCGameCollections_RemoveFromCollection}" Command="{Binding RemoveCommand}" InputGestureText="Del" />
|
||||
<MenuItem Header="{DynamicResource LOCGameCollections_MoveToTop}" Command="{Binding MoveToTopCommand}" />
|
||||
<MenuItem Header="{DynamicResource LOCGameCollections_MoveUp}" Command="{Binding MoveUpCommand}" InputGestureText="Alt+Up" />
|
||||
<MenuItem Header="{DynamicResource LOCGameCollections_MoveDown}" Command="{Binding MoveDownCommand}" InputGestureText="Alt+Down" />
|
||||
<MenuItem Header="{DynamicResource LOCGameCollections_MoveToBottom}" Command="{Binding MoveToBottomCommand}" />
|
||||
<Separator Visibility="{Binding CanRemove, Converter={StaticResource BoolToVisibility}}" />
|
||||
<MenuItem Header="{DynamicResource LOCGameCollections_RemoveFromCollection}" Command="{Binding RemoveCommand}" InputGestureText="Del"
|
||||
Visibility="{Binding CanRemove, Converter={StaticResource BoolToVisibility}}" />
|
||||
</ContextMenu>
|
||||
|
||||
<Style x:Key="GameContainerStyle" TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
|
||||
@@ -29,6 +35,9 @@
|
||||
<Setter Property="ToolTip" Value="{Binding Name}" />
|
||||
<EventSetter Event="MouseDoubleClick" Handler="GameItem_MouseDoubleClick" />
|
||||
<EventSetter Event="Loaded" Handler="GameItem_Loaded" />
|
||||
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="GameItem_PreviewMouseLeftButtonDown" />
|
||||
<EventSetter Event="PreviewMouseLeftButtonUp" Handler="GameItem_PreviewMouseLeftButtonUp" />
|
||||
<EventSetter Event="PreviewMouseMove" Handler="GameItem_PreviewMouseMove" />
|
||||
</Style>
|
||||
|
||||
<DataTemplate x:Key="GameTemplate" DataType="{x:Type vm:CollectionGameViewModel}">
|
||||
@@ -50,6 +59,7 @@
|
||||
<DockPanel Margin="20,10,20,0">
|
||||
<!-- Back navigation -->
|
||||
<Button DockPanel.Dock="Top" HorizontalAlignment="Left" Style="{StaticResource GcButton}"
|
||||
Visibility="{Binding IsInWindow, Converter={StaticResource InverseBoolToVisibility}}"
|
||||
Command="{Binding BackCommand}"
|
||||
AutomationProperties.Name="{DynamicResource LOCGameCollections_BackToCollections}">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
@@ -73,7 +83,14 @@
|
||||
<TextBlock Text="{Binding Header.RatingText}" Style="{StaticResource GcText}" />
|
||||
<TextBlock Text="•" Style="{StaticResource GcMutedText}" Margin="10,0" />
|
||||
<TextBlock Text="{Binding Header.GameCountText}" Style="{StaticResource GcMutedText}" />
|
||||
<Border Style="{StaticResource GcBadge}" Margin="10,0,0,0"
|
||||
Visibility="{Binding IsDynamic, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_DynamicBadge}" Style="{StaticResource GcBadgeText}" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding RulesSummary}" Style="{StaticResource GcMutedText}"
|
||||
TextWrapping="Wrap" Margin="0,8,0,0"
|
||||
Visibility="{Binding RulesSummary, Converter={StaticResource HasValueToVisibility}}" />
|
||||
<ScrollViewer MaxHeight="96" Margin="0,10,0,0" VerticalScrollBarVisibility="Auto"
|
||||
Visibility="{Binding Header.HasDescription, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{Binding Header.Description}" Style="{StaticResource GcMutedText}" TextWrapping="Wrap" />
|
||||
@@ -85,7 +102,16 @@
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_EditCollection}" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button Style="{StaticResource GcButton}" Command="{Binding RefreshCommand}" Margin="0,0,8,0"
|
||||
ToolTip="{DynamicResource LOCGameCollections_RefreshNowTooltip}"
|
||||
Content="{DynamicResource LOCGameCollections_RefreshNow}"
|
||||
Visibility="{Binding IsDynamic, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource GcButton}" Command="{Binding OpenInCollectionsCommand}" Margin="0,0,8,0"
|
||||
ToolTip="{DynamicResource LOCGameCollections_OpenInCollectionsTooltip}"
|
||||
Content="{DynamicResource LOCGameCollections_OpenInCollections}"
|
||||
Visibility="{Binding IsInWindow, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource GcButton}" Command="{Binding ShowAllInLibraryCommand}" Margin="0,0,8,0"
|
||||
Visibility="{Binding IsInWindow, Converter={StaticResource InverseBoolToVisibility}}"
|
||||
ToolTip="{DynamicResource LOCGameCollections_ShowAllInLibraryTooltip}">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="" Style="{StaticResource GcGlyph}" Margin="0,0,6,0" />
|
||||
@@ -125,6 +151,9 @@
|
||||
Content="{DynamicResource LOCGameCollections_InstalledOnly}" />
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding VisibleCountText}" Style="{StaticResource GcMutedText}"
|
||||
VerticalAlignment="Center" Margin="10,0,0,0" />
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding ReorderHint}" Style="{StaticResource GcMutedText}"
|
||||
FontSize="{DynamicResource FontSizeSmall}" VerticalAlignment="Center" Margin="10,0,0,0"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
</DockPanel>
|
||||
|
||||
<Grid>
|
||||
@@ -137,6 +166,11 @@
|
||||
ItemContainerStyle="{StaticResource GameContainerStyle}"
|
||||
ScrollViewer.CanContentScroll="False"
|
||||
KeyDown="GamesList_KeyDown"
|
||||
PreviewKeyDown="GamesList_PreviewKeyDown"
|
||||
AllowDrop="True"
|
||||
DragOver="GamesList_DragOver"
|
||||
DragLeave="GamesList_DragLeave"
|
||||
Drop="GamesList_Drop"
|
||||
SizeChanged="GamesList_SizeChanged"
|
||||
AutomationProperties.Name="{Binding Header.Title}">
|
||||
<ListBox.ItemsPanel>
|
||||
@@ -146,12 +180,17 @@
|
||||
</ListBox.ItemsPanel>
|
||||
</ListBox>
|
||||
|
||||
<!-- Shows where dragged games will land. -->
|
||||
<Canvas IsHitTestVisible="False" ClipToBounds="True">
|
||||
<Rectangle x:Name="DropIndicator" Width="3" Fill="{DynamicResource GlyphBrush}" Visibility="Collapsed" />
|
||||
</Canvas>
|
||||
|
||||
<!-- Empty collection -->
|
||||
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,40,0,0" MaxWidth="420"
|
||||
Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_CollectionEmptyTitle}" Style="{StaticResource GcText}"
|
||||
<TextBlock Text="{Binding EmptyTitle}" Style="{StaticResource GcText}"
|
||||
FontSize="{DynamicResource FontSizeLarge}" HorizontalAlignment="Center" />
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_CollectionEmptyDescription}" Style="{StaticResource GcMutedText}"
|
||||
<TextBlock Text="{Binding EmptyDescription}" Style="{StaticResource GcMutedText}"
|
||||
TextWrapping="Wrap" TextAlignment="Center" Margin="0,8,0,0" />
|
||||
</StackPanel>
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using GameCollections.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
@@ -10,8 +12,15 @@ namespace GameCollections.Views
|
||||
{
|
||||
public partial class CollectionDetailsView : UserControl
|
||||
{
|
||||
private const string DragFormat = "GameCollections.Games";
|
||||
// Dragging this close to the top or bottom of the list scrolls it.
|
||||
private const double AutoScrollMargin = 40;
|
||||
private const double AutoScrollStep = 24;
|
||||
|
||||
private readonly DispatcherTimer coverTimer;
|
||||
private ScrollViewer scrollViewer;
|
||||
private Point? dragStart;
|
||||
private bool collapseSelectionOnRelease;
|
||||
|
||||
public CollectionDetailsView()
|
||||
{
|
||||
@@ -120,6 +129,8 @@ namespace GameCollections.Views
|
||||
|
||||
switch (e.Key)
|
||||
{
|
||||
case Key.Delete when !ViewModel.CanRemove:
|
||||
break;
|
||||
case Key.Enter:
|
||||
ViewModel.PlaySelectedCommand.Execute(null);
|
||||
e.Handled = true;
|
||||
@@ -131,6 +142,209 @@ namespace GameCollections.Views
|
||||
}
|
||||
}
|
||||
|
||||
private void GamesList_PreviewKeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
// Windows reports arrow keys pressed with Alt as a "system" key.
|
||||
if (ViewModel == null || e.Key != Key.System || Keyboard.Modifiers != ModifierKeys.Alt)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
bool later;
|
||||
switch (e.SystemKey)
|
||||
{
|
||||
case Key.Left:
|
||||
case Key.Up:
|
||||
later = false;
|
||||
break;
|
||||
case Key.Right:
|
||||
case Key.Down:
|
||||
later = true;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
e.Handled = true;
|
||||
var tile = GamesList.SelectedItems.Cast<CollectionGameViewModel>().FirstOrDefault();
|
||||
if (tile != null)
|
||||
{
|
||||
ViewModel.MoveOneStep(tile, later);
|
||||
GamesList.ScrollIntoView(tile);
|
||||
}
|
||||
}
|
||||
|
||||
private void GameItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
|
||||
{
|
||||
dragStart = null;
|
||||
collapseSelectionOnRelease = false;
|
||||
if (ViewModel == null || !ViewModel.CanReorder || e.ClickCount != 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
dragStart = e.GetPosition(GamesList);
|
||||
|
||||
// Clicking a selected game would normally reduce the selection to it at once, making it
|
||||
// impossible to drag several games. That is put off until the button is released without a drag.
|
||||
var item = (ListBoxItem)sender;
|
||||
if (item.IsSelected && GamesList.SelectedItems.Count > 1 && Keyboard.Modifiers == ModifierKeys.None)
|
||||
{
|
||||
collapseSelectionOnRelease = true;
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void GameItem_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
|
||||
{
|
||||
if (collapseSelectionOnRelease)
|
||||
{
|
||||
GamesList.SelectedItem = ((ListBoxItem)sender).DataContext;
|
||||
}
|
||||
|
||||
collapseSelectionOnRelease = false;
|
||||
dragStart = null;
|
||||
}
|
||||
|
||||
private void GameItem_PreviewMouseMove(object sender, MouseEventArgs e)
|
||||
{
|
||||
if (dragStart == null || e.LeftButton != MouseButtonState.Pressed || ViewModel == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var offset = e.GetPosition(GamesList) - dragStart.Value;
|
||||
if (Math.Abs(offset.X) < SystemParameters.MinimumHorizontalDragDistance &&
|
||||
Math.Abs(offset.Y) < SystemParameters.MinimumVerticalDragDistance)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
dragStart = null;
|
||||
collapseSelectionOnRelease = false;
|
||||
var tile = (CollectionGameViewModel)((ListBoxItem)sender).DataContext;
|
||||
var selected = GamesList.SelectedItems.Cast<CollectionGameViewModel>().ToList();
|
||||
var dragged = selected.Contains(tile) ? selected : new List<CollectionGameViewModel> { tile };
|
||||
var ids = dragged.Select(t => t.Id).ToArray();
|
||||
DragDrop.DoDragDrop((DependencyObject)sender, new DataObject(DragFormat, ids), DragDropEffects.Move);
|
||||
DropIndicator.Visibility = Visibility.Collapsed;
|
||||
}
|
||||
|
||||
private void GamesList_DragOver(object sender, DragEventArgs e)
|
||||
{
|
||||
e.Handled = true;
|
||||
e.Effects = DragDropEffects.None;
|
||||
if (ViewModel == null || !ViewModel.CanReorder || !e.Data.GetDataPresent(DragFormat))
|
||||
{
|
||||
DropIndicator.Visibility = Visibility.Collapsed;
|
||||
return;
|
||||
}
|
||||
|
||||
AutoScroll(e);
|
||||
var target = FindDropTarget(e.GetPosition(GamesList));
|
||||
if (target == null)
|
||||
{
|
||||
DropIndicator.Visibility = Visibility.Collapsed;
|
||||
return;
|
||||
}
|
||||
|
||||
e.Effects = DragDropEffects.Move;
|
||||
var bounds = target.Bounds;
|
||||
Canvas.SetLeft(DropIndicator, (target.After ? bounds.Right + 2 : bounds.Left - 5));
|
||||
Canvas.SetTop(DropIndicator, bounds.Top);
|
||||
DropIndicator.Height = bounds.Height;
|
||||
DropIndicator.Visibility = Visibility.Visible;
|
||||
}
|
||||
|
||||
private void GamesList_DragLeave(object sender, DragEventArgs e)
|
||||
{
|
||||
DropIndicator.Visibility = Visibility.Collapsed;
|
||||
}
|
||||
|
||||
private void GamesList_Drop(object sender, DragEventArgs e)
|
||||
{
|
||||
DropIndicator.Visibility = Visibility.Collapsed;
|
||||
e.Handled = true;
|
||||
if (ViewModel == null || !(e.Data.GetData(DragFormat) is Guid[] ids))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var target = FindDropTarget(e.GetPosition(GamesList));
|
||||
if (target != null)
|
||||
{
|
||||
ViewModel.MoveGames(ids, target.Tile.Id, target.After);
|
||||
}
|
||||
}
|
||||
|
||||
private void AutoScroll(DragEventArgs e)
|
||||
{
|
||||
if (scrollViewer == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var y = e.GetPosition(scrollViewer).Y;
|
||||
if (y < AutoScrollMargin)
|
||||
{
|
||||
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - AutoScrollStep);
|
||||
}
|
||||
else if (y > scrollViewer.ViewportHeight - AutoScrollMargin)
|
||||
{
|
||||
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + AutoScrollStep);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds where a drop at this point lands: the tile on the pointer's row closest to it,
|
||||
/// and which side of that tile. Pointing past the last row means after the last game.
|
||||
/// </summary>
|
||||
private DropTarget FindDropTarget(Point point)
|
||||
{
|
||||
var tiles = new List<DropTarget>();
|
||||
foreach (var item in GamesList.Items)
|
||||
{
|
||||
if (GamesList.ItemContainerGenerator.ContainerFromItem(item) is FrameworkElement container && container.IsVisible)
|
||||
{
|
||||
var topLeft = container.TranslatePoint(new Point(0, 0), GamesList);
|
||||
tiles.Add(new DropTarget
|
||||
{
|
||||
Tile = (CollectionGameViewModel)item,
|
||||
Bounds = new Rect(topLeft, new Size(container.ActualWidth, container.ActualHeight))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (tiles.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var row = tiles.Where(t => point.Y >= t.Bounds.Top && point.Y <= t.Bounds.Bottom + 8).ToList();
|
||||
if (row.Count == 0)
|
||||
{
|
||||
var last = tiles[tiles.Count - 1];
|
||||
if (point.Y > last.Bounds.Bottom)
|
||||
{
|
||||
last.After = true;
|
||||
return last;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
var closest = row.OrderBy(t => Math.Abs(point.X - (t.Bounds.Left + t.Bounds.Width / 2))).First();
|
||||
closest.After = point.X > closest.Bounds.Left + closest.Bounds.Width / 2;
|
||||
return closest;
|
||||
}
|
||||
|
||||
private class DropTarget
|
||||
{
|
||||
public CollectionGameViewModel Tile { get; set; }
|
||||
public Rect Bounds { get; set; }
|
||||
public bool After { get; set; }
|
||||
}
|
||||
|
||||
private static T FindDescendant<T>(DependencyObject parent) where T : DependencyObject
|
||||
{
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
|
||||
|
||||
@@ -41,7 +41,13 @@
|
||||
<!-- Grid card: fixed size so every card lines up regardless of its content. -->
|
||||
<DataTemplate x:Key="CardTemplate" DataType="{x:Type vm:CollectionCardViewModel}">
|
||||
<StackPanel Width="170">
|
||||
<local:PosterImage Width="170" Height="255" GlyphSize="56" Source="{Binding Poster}" />
|
||||
<Grid Width="170" Height="255">
|
||||
<local:PosterImage GlyphSize="56" Source="{Binding Poster}" />
|
||||
<Border Style="{StaticResource GcBadge}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="6"
|
||||
Visibility="{Binding IsDynamic, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_DynamicBadge}" Style="{StaticResource GcBadgeText}" />
|
||||
</Border>
|
||||
</Grid>
|
||||
<TextBlock Text="{Binding Title}" ToolTip="{Binding Title}"
|
||||
Style="{StaticResource GcItemTitleText}" Margin="0,8,0,0" />
|
||||
<TextBlock Text="{Binding Description}" Style="{StaticResource GcMutedText}"
|
||||
@@ -73,7 +79,13 @@
|
||||
</Grid.ColumnDefinitions>
|
||||
<local:PosterImage Width="48" Height="72" GlyphSize="22" CornerRadius="3" Source="{Binding Poster}" />
|
||||
<StackPanel Grid.Column="1" Margin="14,0,10,0" VerticalAlignment="Center">
|
||||
<TextBlock Text="{Binding Title}" Style="{StaticResource GcItemTitleText}" />
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="{Binding Title}" Style="{StaticResource GcItemTitleText}" />
|
||||
<Border Style="{StaticResource GcBadge}" Margin="8,0,0,0"
|
||||
Visibility="{Binding IsDynamic, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_DynamicBadge}" Style="{StaticResource GcBadgeText}" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding Description}" Style="{StaticResource GcMutedText}"
|
||||
TextTrimming="CharacterEllipsis" Margin="0,3,0,0"
|
||||
ToolTip="{Binding Description}"
|
||||
|
||||
@@ -42,4 +42,20 @@ namespace GameCollections.Views
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flips a boolean.
|
||||
/// </summary>
|
||||
public class InverseBoolConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
return !(value is bool b && b);
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
return !(value is bool b && b);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,12 +32,28 @@
|
||||
VerticalAlignment="Center" Margin="0,0,10,0" />
|
||||
</DockPanel>
|
||||
|
||||
<!-- Live result of the rules, kept in view while the rules scroll. -->
|
||||
<Border DockPanel.Dock="Bottom" Margin="0,12,0,0" Padding="12,8"
|
||||
Background="{DynamicResource NormalBrush}" CornerRadius="4"
|
||||
Visibility="{Binding IsDynamic, Converter={StaticResource BoolToVisibility}}">
|
||||
<StackPanel>
|
||||
<TextBlock Text="{Binding Rules.PreviewText}" Style="{StaticResource GcItemTitleText}" />
|
||||
<TextBlock Text="{Binding Rules.PreviewNames}" Style="{StaticResource GcMutedText}"
|
||||
TextTrimming="CharacterEllipsis" Margin="0,3,0,0"
|
||||
Visibility="{Binding Rules.PreviewNames, Converter={StaticResource HasValueToVisibility}}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Poster -->
|
||||
<StackPanel Width="160">
|
||||
@@ -72,7 +88,7 @@
|
||||
<TextBox Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}"
|
||||
MaxLength="{Binding MaxDescriptionLength, Mode=OneTime}"
|
||||
AcceptsReturn="True" TextWrapping="Wrap"
|
||||
Height="110" VerticalContentAlignment="Top"
|
||||
Height="80" VerticalContentAlignment="Top"
|
||||
VerticalScrollBarVisibility="Auto"
|
||||
AutomationProperties.Name="{DynamicResource LOCGameCollections_FieldDescription}" />
|
||||
|
||||
@@ -87,7 +103,20 @@
|
||||
Value="{Binding Rating}"
|
||||
AutomationProperties.Name="{DynamicResource LOCGameCollections_FieldRating}" />
|
||||
</DockPanel>
|
||||
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_CollectionType}" Style="{StaticResource GcSectionLabel}" />
|
||||
<RadioButton GroupName="CollectionType" IsChecked="{Binding IsManual}"
|
||||
Content="{DynamicResource LOCGameCollections_TypeManual}" />
|
||||
<RadioButton GroupName="CollectionType" IsChecked="{Binding IsDynamic}" Margin="0,5,0,0"
|
||||
Content="{DynamicResource LOCGameCollections_TypeDynamic}" />
|
||||
<TextBlock Text="{Binding TypeChangeNote}" Style="{StaticResource GcMutedText}"
|
||||
TextWrapping="Wrap" Margin="0,6,0,0"
|
||||
Visibility="{Binding TypeChangeNote, Converter={StaticResource HasValueToVisibility}}" />
|
||||
</StackPanel>
|
||||
|
||||
<local:RuleBuilderView Grid.Row="1" Grid.ColumnSpan="2" Margin="0,16,0,0"
|
||||
DataContext="{Binding Rules}"
|
||||
Visibility="{Binding DataContext.IsDynamic, RelativeSource={RelativeSource AncestorType=UserControl}, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
</ScrollViewer>
|
||||
</DockPanel>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<controls:PluginUserControl x:Class="GameCollections.Views.GameCollectionsControl"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:controls="clr-namespace:Playnite.SDK.Controls;assembly=Playnite.SDK"
|
||||
xmlns:local="clr-namespace:GameCollections.Views"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="170" d:DesignWidth="500">
|
||||
<controls:PluginUserControl.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="/GameCollections;component/Views/Styles.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
</ResourceDictionary>
|
||||
</controls:PluginUserControl.Resources>
|
||||
|
||||
<StackPanel>
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_DetailsHeader}" Style="{StaticResource GcItemTitleText}" Margin="0,0,0,6" />
|
||||
<ItemsControl x:Name="ItemsList" Focusable="False">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type local:DetailsCollectionItem}">
|
||||
<Button Margin="0,0,8,8" Padding="4"
|
||||
Command="{Binding OpenCommand}"
|
||||
ToolTip="{Binding Title}"
|
||||
AutomationProperties.Name="{Binding Title}">
|
||||
<StackPanel Width="84">
|
||||
<Grid Width="84" Height="126">
|
||||
<local:PosterImage GlyphSize="30" CornerRadius="3" Source="{Binding Poster}" />
|
||||
<Border Style="{StaticResource GcBadge}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="3"
|
||||
Visibility="{Binding IsDynamic, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_DynamicBadge}" Style="{StaticResource GcBadgeText}" />
|
||||
</Border>
|
||||
</Grid>
|
||||
<TextBlock Text="{Binding Title}" Style="{StaticResource GcText}"
|
||||
FontSize="{DynamicResource FontSizeSmall}"
|
||||
TextTrimming="CharacterEllipsis" TextWrapping="NoWrap"
|
||||
Margin="0,4,0,0" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</controls:PluginUserControl>
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// A collection shown in the game details view.
|
||||
/// </summary>
|
||||
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<Guid> 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}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public partial class GameCollectionsControl : PluginUserControl
|
||||
{
|
||||
private readonly CollectionManager manager;
|
||||
private readonly GameCollectionsSettingsViewModel settings;
|
||||
private readonly Action<Guid> openCollection;
|
||||
|
||||
/// <summary>
|
||||
/// True for the instance this extension added itself, rather than one placed by a theme.
|
||||
/// </summary>
|
||||
public bool IsInjected { get; set; }
|
||||
|
||||
public GameCollectionsControl(CollectionManager manager, GameCollectionsSettingsViewModel settings, Action<Guid> 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<GameCollection>()
|
||||
: 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
<UserControl x:Class="GameCollections.Views.RuleBuilderView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:local="clr-namespace:GameCollections.Views"
|
||||
xmlns:vm="clr-namespace:GameCollections.ViewModels"
|
||||
mc:Ignorable="d"
|
||||
d:DataContext="{d:DesignInstance Type=vm:DynamicRulesViewModel}"
|
||||
d:DesignHeight="400" d:DesignWidth="800">
|
||||
<UserControl.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="/GameCollections;component/Views/Styles.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<!-- One condition: field, operator, then the editor for that kind of value. -->
|
||||
<DataTemplate x:Key="ConditionTemplate" DataType="{x:Type vm:RuleConditionViewModel}">
|
||||
<StackPanel Margin="0,0,0,8">
|
||||
<DockPanel>
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource GcIconButton}" Height="30" Margin="8,0,0,0"
|
||||
VerticalAlignment="Top"
|
||||
Content=""
|
||||
Command="{Binding RemoveCommand}"
|
||||
ToolTip="{DynamicResource LOCGameCollections_RuleRemoveCondition}"
|
||||
AutomationProperties.Name="{DynamicResource LOCGameCollections_RuleRemoveCondition}" />
|
||||
<ComboBox DockPanel.Dock="Left" Width="165" Height="30" VerticalAlignment="Top"
|
||||
ItemsSource="{x:Static vm:RuleConditionViewModel.Fields}"
|
||||
DisplayMemberPath="Label"
|
||||
SelectedValuePath="Field"
|
||||
SelectedValue="{Binding Field}"
|
||||
AutomationProperties.Name="{DynamicResource LOCGameCollections_RuleFieldLabel}" />
|
||||
<ComboBox DockPanel.Dock="Left" Width="150" Height="30" Margin="8,0,0,0" VerticalAlignment="Top"
|
||||
ItemsSource="{Binding Operators}"
|
||||
DisplayMemberPath="Label"
|
||||
SelectedValuePath="Operator"
|
||||
SelectedValue="{Binding Operator}"
|
||||
AutomationProperties.Name="{DynamicResource LOCGameCollections_RuleOperatorLabel}" />
|
||||
|
||||
<Grid Margin="8,0,0,0">
|
||||
<!-- Name -->
|
||||
<TextBox Height="30" VerticalContentAlignment="Center"
|
||||
Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"
|
||||
Visibility="{Binding ShowText, Converter={StaticResource BoolToVisibility}}"
|
||||
AutomationProperties.Name="{DynamicResource LOCGameCollections_RuleFieldName}" />
|
||||
|
||||
<!-- Dates -->
|
||||
<DockPanel Visibility="{Binding ShowDate, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBox Width="110" Height="30" VerticalContentAlignment="Center"
|
||||
Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"
|
||||
ToolTip="{DynamicResource LOCGameCollections_RuleDateHint}"
|
||||
AutomationProperties.Name="{DynamicResource LOCGameCollections_RuleDateHint}" />
|
||||
<TextBlock Text="–" Style="{StaticResource GcMutedText}" VerticalAlignment="Center" Margin="8,0"
|
||||
Visibility="{Binding ShowDate2, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBox Width="110" Height="30" VerticalContentAlignment="Center"
|
||||
Text="{Binding Text2, UpdateSourceTrigger=PropertyChanged}"
|
||||
ToolTip="{DynamicResource LOCGameCollections_RuleDateHint}"
|
||||
Visibility="{Binding ShowDate2, Converter={StaticResource BoolToVisibility}}"
|
||||
AutomationProperties.Name="{DynamicResource LOCGameCollections_RuleDateHint}" />
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_RuleDateHint}" Style="{StaticResource GcMutedText}"
|
||||
FontSize="{DynamicResource FontSizeSmall}" VerticalAlignment="Center" Margin="8,0,0,0"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
</DockPanel>
|
||||
|
||||
<!-- Numbers -->
|
||||
<StackPanel Orientation="Horizontal" Visibility="{Binding ShowNumber, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBox Width="80" Height="30" VerticalContentAlignment="Center"
|
||||
Text="{Binding NumberText, UpdateSourceTrigger=PropertyChanged}"
|
||||
AutomationProperties.Name="{Binding UnitText}" />
|
||||
<TextBlock Text="–" Style="{StaticResource GcMutedText}" VerticalAlignment="Center" Margin="8,0"
|
||||
Visibility="{Binding ShowNumber2, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBox Width="80" Height="30" VerticalContentAlignment="Center"
|
||||
Text="{Binding NumberText2, UpdateSourceTrigger=PropertyChanged}"
|
||||
Visibility="{Binding ShowNumber2, Converter={StaticResource BoolToVisibility}}"
|
||||
AutomationProperties.Name="{Binding UnitText}" />
|
||||
<TextBlock Text="{Binding UnitText}" Style="{StaticResource GcMutedText}" VerticalAlignment="Center" Margin="8,0,0,0" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Platforms, genres, tags etc.: removable chips plus a searchable picker. -->
|
||||
<WrapPanel Orientation="Horizontal" Visibility="{Binding ShowItems, Converter={StaticResource BoolToVisibility}}">
|
||||
<ToggleButton x:Name="PickerToggle" Height="30" Padding="10,0" Margin="0,0,6,4"
|
||||
Content="{Binding ItemsButtonText}"
|
||||
IsHitTestVisible="{Binding IsOpen, ElementName=PickerPopup, Converter={StaticResource InverseBool}}" />
|
||||
<Popup x:Name="PickerPopup" StaysOpen="False" AllowsTransparency="True"
|
||||
IsOpen="{Binding IsChecked, ElementName=PickerToggle, Mode=TwoWay}"
|
||||
PlacementTarget="{Binding ElementName=PickerToggle}" Placement="Bottom"
|
||||
Opened="PickerPopup_Opened">
|
||||
<Border Width="300" Padding="8" Margin="0,2,0,0"
|
||||
Background="{DynamicResource PopupBackgroundBrush}"
|
||||
BorderBrush="{DynamicResource PopupBorderBrush}"
|
||||
BorderThickness="1">
|
||||
<DockPanel>
|
||||
<local:SearchBox DockPanel.Dock="Top" Height="30" Margin="0,0,0,6"
|
||||
Text="{Binding OptionSearch}"
|
||||
Placeholder="{DynamicResource LOCGameCollections_RuleSearchValues}" />
|
||||
<TextBlock DockPanel.Dock="Top" Text="{DynamicResource LOCGameCollections_RuleNoValues}"
|
||||
Style="{StaticResource GcMutedText}" TextWrapping="Wrap" Margin="4"
|
||||
Visibility="{Binding HasNoOptions, Converter={StaticResource BoolToVisibility}}" />
|
||||
<ListBox MaxHeight="260"
|
||||
Style="{StaticResource GcPlainListBox}"
|
||||
ItemsSource="{Binding OptionsView}"
|
||||
IsSynchronizedWithCurrentItem="False"
|
||||
SelectionMode="Single"
|
||||
VirtualizingPanel.IsVirtualizing="True"
|
||||
VirtualizingPanel.VirtualizationMode="Recycling">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type vm:RuleOptionItem}">
|
||||
<CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}" />
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Popup>
|
||||
<ItemsControl ItemsSource="{Binding SelectedItems}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type vm:RuleOptionItem}">
|
||||
<Border Background="{DynamicResource NormalBrush}" CornerRadius="3" Height="30" Margin="0,0,6,4" Padding="8,0,2,0">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="{Binding Name}" Style="{StaticResource GcText}" VerticalAlignment="Center" />
|
||||
<Button Style="{StaticResource GcIconButton}" MinWidth="24" Padding="2" Margin="4,0,0,0"
|
||||
BorderThickness="0" Background="Transparent" FontSize="11"
|
||||
Content=""
|
||||
Command="{Binding RemoveCommand}"
|
||||
ToolTip="{DynamicResource LOCGameCollections_ClearSearch}"
|
||||
AutomationProperties.Name="{Binding Name}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</WrapPanel>
|
||||
</Grid>
|
||||
</DockPanel>
|
||||
<TextBlock Text="{Binding ValueError}" Style="{StaticResource GcErrorText}" Margin="323,4,0,0"
|
||||
Visibility="{Binding ValueError, Converter={StaticResource HasValueToVisibility}}" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- One block, with the AND/OR choice joining it to the blocks above. -->
|
||||
<DataTemplate x:Key="BlockTemplate" DataType="{x:Type vm:RuleBlockViewModel}">
|
||||
<StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Margin="12,8" HorizontalAlignment="Center"
|
||||
Visibility="{Binding IsFirst, Converter={StaticResource InverseBoolToVisibility}}">
|
||||
<RadioButton GroupName="{Binding JoinGroupName}" IsChecked="{Binding IsAnd}" Margin="0,0,16,0"
|
||||
Content="{DynamicResource LOCGameCollections_RuleJoinAnd}" />
|
||||
<RadioButton GroupName="{Binding JoinGroupName}" IsChecked="{Binding IsOr}"
|
||||
Content="{DynamicResource LOCGameCollections_RuleJoinOr}" />
|
||||
</StackPanel>
|
||||
<Border BorderBrush="{DynamicResource NormalBrush}" BorderThickness="1" CornerRadius="4" Padding="12,10">
|
||||
<StackPanel>
|
||||
<DockPanel Margin="0,0,0,8">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource GcButton}"
|
||||
Command="{Binding RemoveCommand}"
|
||||
Visibility="{Binding IsFirst, Converter={StaticResource InverseBoolToVisibility}}"
|
||||
Content="{DynamicResource LOCGameCollections_RuleRemoveBlock}" />
|
||||
<TextBlock Text="{Binding Title}" Style="{StaticResource GcItemTitleText}" VerticalAlignment="Center" />
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_RuleBlockHint}" Style="{StaticResource GcMutedText}"
|
||||
FontSize="{DynamicResource FontSizeSmall}" VerticalAlignment="Center" Margin="10,0,0,0" />
|
||||
</DockPanel>
|
||||
<ItemsControl ItemsSource="{Binding Conditions}" ItemTemplate="{StaticResource ConditionTemplate}" Focusable="False" />
|
||||
<Button HorizontalAlignment="Left" Style="{StaticResource GcButton}" Command="{Binding AddConditionCommand}">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="" Style="{StaticResource GcGlyph}" Margin="0,0,6,0" />
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_RuleAddCondition}" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ResourceDictionary>
|
||||
</UserControl.Resources>
|
||||
|
||||
<StackPanel>
|
||||
<ItemsControl ItemsSource="{Binding Blocks}" ItemTemplate="{StaticResource BlockTemplate}" Focusable="False" />
|
||||
<DockPanel Margin="0,10,0,0">
|
||||
<Button DockPanel.Dock="Left" Style="{StaticResource GcButton}" Command="{Binding AddBlockCommand}">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="" Style="{StaticResource GcGlyph}" Margin="0,0,6,0" />
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_RuleAddBlock}" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<TextBlock Text="{DynamicResource LOCGameCollections_RuleOrderHint}" Style="{StaticResource GcMutedText}"
|
||||
FontSize="{DynamicResource FontSizeSmall}" TextWrapping="Wrap"
|
||||
VerticalAlignment="Center" Margin="12,0,0,0" />
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
<local:HasValueToVisibilityConverter x:Key="NoValueToVisibility" Invert="True" />
|
||||
<local:BoolToVisibilityConverter x:Key="BoolToVisibility" />
|
||||
<local:BoolToVisibilityConverter x:Key="InverseBoolToVisibility" Invert="True" />
|
||||
<local:InverseBoolConverter x:Key="InverseBool" />
|
||||
|
||||
<Style x:Key="GcText" TargetType="TextBlock" BasedOn="{StaticResource BaseTextBlockStyle}" />
|
||||
|
||||
@@ -37,6 +38,18 @@
|
||||
<Setter Property="TextWrapping" Value="Wrap" />
|
||||
</Style>
|
||||
|
||||
<!-- Small label marking a collection as dynamic. -->
|
||||
<Style x:Key="GcBadgeText" TargetType="TextBlock" BasedOn="{StaticResource GcText}">
|
||||
<Setter Property="FontSize" Value="{DynamicResource FontSizeSmall}" />
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
</Style>
|
||||
|
||||
<Style x:Key="GcBadge" TargetType="Border">
|
||||
<Setter Property="Background" Value="#CC2A5BA8" />
|
||||
<Setter Property="CornerRadius" Value="3" />
|
||||
<Setter Property="Padding" Value="6,1" />
|
||||
</Style>
|
||||
|
||||
<Style x:Key="GcGlyph" TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="{DynamicResource FontIcoFont}" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Id: GameCollections_3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54
|
||||
Name: Game Collections
|
||||
Author: X4Lo
|
||||
Version: 1.0.0
|
||||
Version: 1.1.0
|
||||
Module: GameCollections.dll
|
||||
Type: GenericPlugin
|
||||
Icon: icon.png
|
||||
|
||||
Reference in new issue
Block a user