Initial Version

This commit is contained in:
X4Lo committed 2026-10-30 13:36:27 +00:00
commit 72e35002f7
55 files changed
+4365

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCollections", "GameCollections\GameCollections.csproj", "{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|x64.ActiveCfg = Debug|Any CPU
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|x64.Build.0 = Debug|Any CPU
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|x86.ActiveCfg = Debug|Any CPU
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Debug|x86.Build.0 = Debug|Any CPU
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|Any CPU.Build.0 = Release|Any CPU
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|x64.ActiveCfg = Release|Any CPU
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|x64.Build.0 = Release|Any CPU
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|x86.ActiveCfg = Release|Any CPU
{9D7B275E-DAA1-4243-BB8C-1ACAA57A06C4}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net462</TargetFramework>
<UseWPF>true</UseWPF>
<OutputType>Library</OutputType>
<RootNamespace>GameCollections</RootNamespace>
<AssemblyName>GameCollections</AssemblyName>
<LangVersion>7.3</LangVersion>
<Version>1.0.0</Version>
<Product>Game Collections</Product>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
<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" />
</ItemGroup>
<ItemGroup>
<!-- Localization files are loaded by Playnite from the plugin folder, not compiled into the assembly. -->
<Page Remove="Localization\*.xaml" />
<None Include="Localization\*.xaml" CopyToOutputDirectory="PreserveNewest" />
<None Update="extension.yaml" CopyToOutputDirectory="PreserveNewest" />
<None Update="icon.png" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<!-- Creates an installable .pext package (a zip of the output folder) in <repo>\dist after Release builds.
The file name follows Playnite Toolbox's convention: <extension Id>_<version with underscores>.pext -->
<Target Name="PackPext" AfterTargets="Build" Condition="'$(Configuration)' == 'Release'">
<PropertyGroup>
<PextDirectory>$(MSBuildProjectDirectory)\..\..\dist</PextDirectory>
<PextPath>$(PextDirectory)\GameCollections_3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54_$(Version.Replace('.', '_')).pext</PextPath>
</PropertyGroup>
<MakeDir Directories="$(PextDirectory)" />
<Delete Files="$(PextPath)" />
<ZipDirectory SourceDirectory="$(OutDir)" DestinationFile="$(PextPath)" Overwrite="true" />
</Target>
</Project>
@@ -0,0 +1,182 @@
using GameCollections.Services;
using GameCollections.Settings;
using GameCollections.ViewModels;
using GameCollections.Views;
using Playnite.SDK;
using Playnite.SDK.Events;
using Playnite.SDK.Models;
using Playnite.SDK.Plugins;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Controls;
namespace GameCollections
{
public class GameCollectionsPlugin : GenericPlugin
{
private static readonly ILogger logger = LogManager.GetLogger();
private readonly GameCollectionsSettingsViewModel settings;
private readonly CollectionManager manager;
private readonly DialogService dialogs;
private CollectionsRootViewModel rootViewModel;
public override Guid Id { get; } = Guid.Parse("3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54");
public GameCollectionsPlugin(IPlayniteAPI api) : base(api)
{
settings = new GameCollectionsSettingsViewModel(this);
Properties = new GenericPluginProperties
{
HasSettings = true
};
var dataDirectory = GetPluginUserDataPath();
manager = new CollectionManager(
api,
new CollectionRepository(dataDirectory),
new PosterStorage(Path.Combine(dataDirectory, "Posters")));
dialogs = new DialogService(api, manager);
}
public override void OnApplicationStarted(OnApplicationStartedEventArgs args)
{
// Loading happens here rather than in the constructor because the game database
// is only guaranteed to be available once Playnite has started.
try
{
var warning = manager.Load();
if (warning != null)
{
PlayniteApi.Notifications.Add(new NotificationMessage("GameCollections_LoadWarning", warning, NotificationType.Error));
}
manager.RemoveMissingGames();
manager.DeleteUnreferencedPosters();
}
catch (Exception e)
{
logger.Error(e, "Failed to load collections.");
PlayniteApi.Notifications.Add(new NotificationMessage(
"GameCollections_LoadError",
Loc.Format("LOCGameCollections_ErrorLoadFailed", e.Message),
NotificationType.Error));
}
PlayniteApi.Database.Games.ItemCollectionChanged += Games_ItemCollectionChanged;
PlayniteApi.Database.Games.ItemUpdated += Games_ItemUpdated;
}
public override void OnApplicationStopped(OnApplicationStoppedEventArgs args)
{
PlayniteApi.Database.Games.ItemCollectionChanged -= Games_ItemCollectionChanged;
PlayniteApi.Database.Games.ItemUpdated -= Games_ItemUpdated;
}
public override IEnumerable<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args)
{
yield return new GameMenuItem
{
Description = Loc.Get("LOCGameCollections_MenuAddToCollection"),
Icon = Path.Combine(GetPluginDirectory(), "icon.png"),
Action = menuArgs =>
{
try
{
dialogs.ShowAddToCollection(menuArgs.Games);
}
catch (Exception e)
{
logger.Error(e, "Failed to open the Add to Collection dialog.");
PlayniteApi.Dialogs.ShowErrorMessage(e.Message, Loc.Get("LOCGameCollections_PluginName"));
}
}
};
}
public override IEnumerable<SidebarItem> GetSidebarItems()
{
yield return new SidebarItem
{
Title = Loc.Get("LOCGameCollections_SidebarTitle"),
Type = SiderbarItemType.View,
Icon = Path.Combine(GetPluginDirectory(), "icon.png"),
// A new view is built on every open, while the view model (current page, search,
// sort) persists so the user returns to where they left off.
Opened = () =>
{
if (rootViewModel == null)
{
rootViewModel = new CollectionsRootViewModel(PlayniteApi, manager, dialogs, settings);
}
return new CollectionsRootView { DataContext = rootViewModel };
}
};
}
public override ISettings GetSettings(bool firstRunSettings)
{
return settings;
}
public override UserControl GetSettingsView(bool firstRunSettings)
{
return new GameCollectionsSettingsView();
}
private void Games_ItemCollectionChanged(object sender, ItemCollectionChangedEventArgs<Game> e)
{
if (e.RemovedItems == null || e.RemovedItems.Count == 0)
{
return;
}
var removedIds = e.RemovedItems.Select(g => g.Id).ToList();
RunOnUiThread(() => manager.RemoveGamesFromAllCollections(removedIds));
}
private void Games_ItemUpdated(object sender, ItemUpdatedEventArgs<Game> e)
{
if (rootViewModel == null || e.UpdatedItems == null || e.UpdatedItems.Count == 0)
{
return;
}
var updatedIds = new HashSet<Guid>(e.UpdatedItems.Select(u => u.NewData.Id));
RunOnUiThread(() => rootViewModel.OnGamesUpdated(updatedIds));
}
private void RunOnUiThread(Action action)
{
void SafeAction()
{
try
{
action();
}
catch (Exception e)
{
logger.Error(e, "Failed to process library change.");
}
}
var dispatcher = PlayniteApi.MainView.UIDispatcher;
if (dispatcher == null || dispatcher.CheckAccess())
{
SafeAction();
}
else
{
dispatcher.BeginInvoke((Action)SafeAction);
}
}
private static string GetPluginDirectory()
{
return Path.GetDirectoryName(typeof(GameCollectionsPlugin).Assembly.Location);
}
}
}
@@ -0,0 +1,92 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<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>
<sys:String x:Key="LOCGameCollections_SearchCollections">Search collections</sys:String>
<sys:String x:Key="LOCGameCollections_CreateCollection">Create Collection</sys:String>
<sys:String x:Key="LOCGameCollections_SwitchToListView">Switch to list view</sys:String>
<sys:String x:Key="LOCGameCollections_SwitchToGridView">Switch to grid view</sys:String>
<sys:String x:Key="LOCGameCollections_EmptyTitle">No collections yet</sys:String>
<sys:String x:Key="LOCGameCollections_EmptyDescription">Create a collection here, or right-click a game in your library and choose "Add to Collection".</sys:String>
<sys:String x:Key="LOCGameCollections_NoCollectionsMatch">No collections match "{0}".</sys:String>
<sys:String x:Key="LOCGameCollections_Open">Open</sys:String>
<sys:String x:Key="LOCGameCollections_Edit">Edit</sys:String>
<sys:String x:Key="LOCGameCollections_Delete">Delete</sys:String>
<sys:String x:Key="LOCGameCollections_CollectionCountSingle">1 collection</sys:String>
<sys:String x:Key="LOCGameCollections_CollectionCountPlural">{0} collections</sys:String>
<sys:String x:Key="LOCGameCollections_GameCountSingle">1 game</sys:String>
<sys:String x:Key="LOCGameCollections_GameCountPlural">{0} games</sys:String>
<sys:String x:Key="LOCGameCollections_FilteredGameCount">{0} of {1} games</sys:String>
<sys:String x:Key="LOCGameCollections_DeleteConfirmTitle">Delete collection</sys:String>
<sys:String x:Key="LOCGameCollections_DeleteConfirmMessage">Delete the collection "{0}"?&#x0a;&#x0a;The games in it will stay in your Playnite library.</sys:String>
<sys:String x:Key="LOCGameCollections_UntitledCollection">Untitled collection</sys:String>
<!-- Collection page -->
<sys:String x:Key="LOCGameCollections_BackToCollections">Collections</sys:String>
<sys:String x:Key="LOCGameCollections_EditCollection">Edit</sys:String>
<sys:String x:Key="LOCGameCollections_DeleteCollection">Delete</sys:String>
<sys:String x:Key="LOCGameCollections_ShowAllInLibrary">Select in library</sys:String>
<sys:String x:Key="LOCGameCollections_ShowAllInLibraryTooltip">Switch to the library and select every game in this collection</sys:String>
<sys:String x:Key="LOCGameCollections_SearchGames">Search games</sys:String>
<sys:String x:Key="LOCGameCollections_SortBy">Sort by</sys:String>
<sys:String x:Key="LOCGameCollections_SortCollectionOrder">Collection order</sys:String>
<sys:String x:Key="LOCGameCollections_SortName">Name</sys:String>
<sys:String x:Key="LOCGameCollections_SortReleaseDate">Release date</sys:String>
<sys:String x:Key="LOCGameCollections_SortLastPlayed">Last played</sys:String>
<sys:String x:Key="LOCGameCollections_SortPlaytime">Time played</sys:String>
<sys:String x:Key="LOCGameCollections_SortDateAdded">Date added to library</sys:String>
<sys:String x:Key="LOCGameCollections_SortAscending">Ascending</sys:String>
<sys:String x:Key="LOCGameCollections_SortDescending">Descending</sys:String>
<sys:String x:Key="LOCGameCollections_InstalledOnly">Installed only</sys:String>
<sys:String x:Key="LOCGameCollections_Play">Play</sys:String>
<sys:String x:Key="LOCGameCollections_Install">Install</sys:String>
<sys:String x:Key="LOCGameCollections_ShowInLibrary">Show in library</sys:String>
<sys:String x:Key="LOCGameCollections_RemoveFromCollection">Remove from collection</sys:String>
<sys:String x:Key="LOCGameCollections_CollectionEmptyTitle">This collection is empty</sys:String>
<sys:String x:Key="LOCGameCollections_CollectionEmptyDescription">Right-click a game in your library and choose "Add to Collection" to add it here.</sys:String>
<sys:String x:Key="LOCGameCollections_NoGamesMatch">No games match the current search or filter.</sys:String>
<!-- Add to Collection dialog -->
<sys:String x:Key="LOCGameCollections_AddToCollectionWindowTitle">Add to Collection</sys:String>
<sys:String x:Key="LOCGameCollections_AddToCollectionHeaderSingle">Choose the collections for "{0}"</sys:String>
<sys:String x:Key="LOCGameCollections_AddToCollectionHeaderMultiple">Choose the collections for {0} selected games</sys:String>
<sys:String x:Key="LOCGameCollections_SearchOrCreate">Search or create a collection</sys:String>
<sys:String x:Key="LOCGameCollections_CreateCollectionNamed">Create collection "{0}"</sys:String>
<sys:String x:Key="LOCGameCollections_NewCollectionBadge">New</sys:String>
<sys:String x:Key="LOCGameCollections_AddDialogEmpty">You don't have any collections yet. Type a name above to create one.</sys:String>
<sys:String x:Key="LOCGameCollections_ClearSearch">Clear</sys:String>
<!-- Create / edit dialog -->
<sys:String x:Key="LOCGameCollections_CreateCollectionWindowTitle">Create Collection</sys:String>
<sys:String x:Key="LOCGameCollections_EditCollectionWindowTitle">Edit Collection</sys:String>
<sys:String x:Key="LOCGameCollections_FieldTitle">Title</sys:String>
<sys:String x:Key="LOCGameCollections_FieldDescription">Description</sys:String>
<sys:String x:Key="LOCGameCollections_FieldRating">Rating</sys:String>
<sys:String x:Key="LOCGameCollections_ChoosePoster">Choose poster…</sys:String>
<sys:String x:Key="LOCGameCollections_RemovePoster">Remove custom poster</sys:String>
<sys:String x:Key="LOCGameCollections_PosterHintCustom">Custom poster</sys:String>
<sys:String x:Key="LOCGameCollections_PosterHintAutomatic">Using the cover of the first game in the collection</sys:String>
<sys:String x:Key="LOCGameCollections_PosterHintPlaceholder">No poster yet. The first game's cover will be used once games are added.</sys:String>
<sys:String x:Key="LOCGameCollections_Save">Save</sys:String>
<sys:String x:Key="LOCGameCollections_Cancel">Cancel</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>
<sys:String x:Key="LOCGameCollections_ErrorTitleDuplicate">A collection named "{0}" already exists.</sys:String>
<sys:String x:Key="LOCGameCollections_ErrorCollectionNotFound">The collection no longer exists.</sys:String>
<sys:String x:Key="LOCGameCollections_ErrorPosterFormat">Unsupported image format. Use PNG, JPG, BMP, GIF or TIFF.</sys:String>
<sys:String x:Key="LOCGameCollections_ErrorPosterMissing">The selected poster file could not be found.</sys:String>
<sys:String x:Key="LOCGameCollections_ErrorPosterUnreadable">The selected file could not be read as an image.</sys:String>
<sys:String x:Key="LOCGameCollections_ErrorSaveCollection">The collection could not be saved: {0}</sys:String>
<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_WarningDataUnreadable">Game Collections could not read its data file. The unreadable file was kept at "{0}".</sys:String>
</ResourceDictionary>
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
namespace GameCollections.Models
{
/// <summary>
/// Persisted collection record. Games are referenced by their Playnite database IDs only;
/// no game metadata is duplicated here.
/// </summary>
public class GameCollection
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public double Rating { get; set; }
/// <summary>
/// File name of the custom poster inside the plugin's poster folder, or null when none is assigned.
/// </summary>
public string PosterFileName { get; set; }
public List<Guid> GameIds { get; set; } = new List<Guid>();
public DateTime CreatedAt { get; set; }
public DateTime ModifiedAt { get; set; }
}
/// <summary>
/// Root object of the collections data file.
/// </summary>
public class CollectionsDataFile
{
public int SchemaVersion { get; set; }
public List<GameCollection> Collections { get; set; } = new List<GameCollection>();
}
public enum PosterChange
{
Keep,
Replace,
Remove
}
public enum CollectionsViewMode
{
Grid,
List
}
}
@@ -0,0 +1,474 @@
using GameCollections.Models;
using Playnite.SDK;
using Playnite.SDK.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace GameCollections.Services
{
public class CollectionsChangedEventArgs : EventArgs
{
/// <summary>
/// IDs of the collections that were added, updated or removed.
/// </summary>
public IReadOnlyCollection<Guid> ChangedIds { get; }
public CollectionsChangedEventArgs(IReadOnlyCollection<Guid> changedIds)
{
ChangedIds = changedIds;
}
}
/// <summary>
/// Owns the in-memory collection list and every operation on it. Each mutation is persisted
/// immediately and announced through <see cref="CollectionsChanged"/>.
/// All members must be called on the UI thread.
/// </summary>
public class CollectionManager
{
public const int MaxTitleLength = 100;
public const int MaxDescriptionLength = 2000;
public const double MinRating = 0;
public const double MaxRating = 10;
private static readonly ILogger logger = LogManager.GetLogger();
private readonly IPlayniteAPI playniteApi;
private readonly CollectionRepository repository;
private readonly PosterStorage posterStorage;
private readonly List<GameCollection> collections = new List<GameCollection>();
public event EventHandler<CollectionsChangedEventArgs> CollectionsChanged;
public IReadOnlyList<GameCollection> Collections => collections;
public CollectionManager(IPlayniteAPI playniteApi, CollectionRepository repository, PosterStorage posterStorage)
{
this.playniteApi = playniteApi;
this.repository = repository;
this.posterStorage = posterStorage;
}
/// <summary>
/// Loads collections from disk and returns a warning to show the user, or null.
/// </summary>
public string Load()
{
var result = repository.Load();
collections.Clear();
collections.AddRange(result.Collections);
return result.Warning;
}
public GameCollection GetCollection(Guid id)
{
return collections.FirstOrDefault(c => c.Id == id);
}
#region Validation
public static string NormalizeTitle(string title)
{
return title?.Trim() ?? string.Empty;
}
public static string NormalizeDescription(string description)
{
var trimmed = description?.Trim();
if (string.IsNullOrEmpty(trimmed))
{
return null;
}
return trimmed.Length > MaxDescriptionLength ? trimmed.Substring(0, MaxDescriptionLength) : trimmed;
}
public static double NormalizeRating(double rating)
{
if (double.IsNaN(rating) || double.IsInfinity(rating))
{
return MinRating;
}
return Math.Round(Math.Max(MinRating, Math.Min(MaxRating, rating)), 1, MidpointRounding.AwayFromZero);
}
public static bool TitlesEqual(string first, string second)
{
return string.Equals(NormalizeTitle(first), NormalizeTitle(second), StringComparison.CurrentCultureIgnoreCase);
}
public bool IsTitleTaken(string title, Guid? ignoredId = null)
{
return collections.Any(c => c.Id != ignoredId && TitlesEqual(c.Title, title));
}
/// <summary>
/// Returns a user-facing error message for an invalid title, or null when the title can be used.
/// </summary>
public string ValidateTitle(string title, Guid? ignoredId = null)
{
var normalized = NormalizeTitle(title);
if (normalized.Length == 0)
{
return Loc.Get("LOCGameCollections_ErrorTitleRequired");
}
if (normalized.Length > MaxTitleLength)
{
return Loc.Format("LOCGameCollections_ErrorTitleTooLong", MaxTitleLength);
}
if (IsTitleTaken(normalized, ignoredId))
{
return Loc.Format("LOCGameCollections_ErrorTitleDuplicate", normalized);
}
return null;
}
#endregion
#region Collection operations
public GameCollection CreateCollection(string title, string description, double rating, string posterSourcePath, IEnumerable<Guid> gameIds)
{
var collection = BuildNewCollection(title, gameIds);
collection.Description = NormalizeDescription(description);
collection.Rating = NormalizeRating(rating);
if (!string.IsNullOrEmpty(posterSourcePath))
{
collection.PosterFileName = posterStorage.Import(collection.Id, posterSourcePath);
}
collections.Add(collection);
Persist(new[] { collection.Id });
return collection;
}
public void UpdateCollection(Guid id, string title, string description, double rating, PosterChange posterChange, string posterSourcePath)
{
var collection = GetCollection(id);
if (collection == null)
{
throw new InvalidOperationException(Loc.Get("LOCGameCollections_ErrorCollectionNotFound"));
}
var error = ValidateTitle(title, id);
if (error != null)
{
throw new InvalidOperationException(error);
}
// Import first: if copying the new poster fails, nothing has been changed yet.
string obsoletePoster = null;
var newPoster = collection.PosterFileName;
if (posterChange == PosterChange.Replace)
{
newPoster = posterStorage.Import(id, posterSourcePath);
obsoletePoster = collection.PosterFileName;
}
else if (posterChange == PosterChange.Remove)
{
newPoster = null;
obsoletePoster = collection.PosterFileName;
}
collection.Title = NormalizeTitle(title);
collection.Description = NormalizeDescription(description);
collection.Rating = NormalizeRating(rating);
collection.PosterFileName = newPoster;
collection.ModifiedAt = DateTime.UtcNow;
// The old poster is only deleted once the data file no longer references it.
if (Persist(new[] { id }) && obsoletePoster != null)
{
posterStorage.Delete(obsoletePoster);
}
}
/// <summary>
/// Deletes the collection record only. Games referenced by it are not touched.
/// </summary>
public bool DeleteCollection(Guid id)
{
var collection = GetCollection(id);
if (collection == null)
{
return false;
}
collections.Remove(collection);
if (Persist(new[] { id }) && collection.PosterFileName != null)
{
posterStorage.Delete(collection.PosterFileName);
}
return true;
}
public void AddGames(Guid collectionId, IEnumerable<Guid> gameIds)
{
var collection = GetCollection(collectionId);
if (collection != null && AddDistinct(collection, gameIds))
{
Persist(new[] { collectionId });
}
}
/// <summary>
/// Removes game references from a collection. The games stay in the Playnite library.
/// </summary>
public void RemoveGames(Guid collectionId, IEnumerable<Guid> gameIds)
{
var collection = GetCollection(collectionId);
if (collection != null && RemoveIds(collection, new HashSet<Guid>(gameIds)))
{
Persist(new[] { collectionId });
}
}
/// <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,
/// and every title in <paramref name="newCollectionTitles"/> becomes a new collection containing the games.
/// </summary>
public void ApplyMembership(IReadOnlyCollection<Guid> gameIds, IDictionary<Guid, bool> membership, IEnumerable<string> newCollectionTitles)
{
var changed = new List<Guid>();
foreach (var title in newCollectionTitles)
{
if (ValidateTitle(title) != null)
{
continue;
}
var collection = BuildNewCollection(title, gameIds);
collections.Add(collection);
changed.Add(collection.Id);
}
var gameIdSet = new HashSet<Guid>(gameIds);
foreach (var pair in membership)
{
var collection = GetCollection(pair.Key);
if (collection == null)
{
continue;
}
var modified = pair.Value ? AddDistinct(collection, gameIds) : RemoveIds(collection, gameIdSet);
if (modified)
{
changed.Add(collection.Id);
}
}
if (changed.Count > 0)
{
Persist(changed);
}
}
/// <summary>
/// Drops references to games that were removed from the Playnite library.
/// </summary>
public void RemoveGamesFromAllCollections(IEnumerable<Guid> gameIds)
{
var removed = new HashSet<Guid>(gameIds);
var changed = collections.Where(c => RemoveIds(c, removed)).Select(c => c.Id).ToList();
if (changed.Count > 0)
{
Persist(changed);
}
}
/// <summary>
/// Drops references to games that no longer exist in the library, e.g. ones removed while the plugin was disabled.
/// </summary>
public void RemoveMissingGames()
{
var missing = collections
.SelectMany(c => c.GameIds)
.Distinct()
.Where(id => playniteApi.Database.Games.Get(id) == null)
.ToList();
if (missing.Count > 0)
{
logger.Info($"Removing {missing.Count} game reference(s) no longer present in the library.");
RemoveGamesFromAllCollections(missing);
}
}
public void DeleteUnreferencedPosters()
{
posterStorage.DeleteUnreferenced(collections.Select(c => c.PosterFileName));
}
#endregion
#region Games and posters
/// <summary>
/// Returns the collection's games that still exist in the library, in collection order.
/// </summary>
public List<Game> GetGames(GameCollection collection)
{
return collection.GameIds
.Select(id => playniteApi.Database.Games.Get(id))
.Where(g => g != null)
.ToList();
}
public Game GetFirstGame(GameCollection collection)
{
foreach (var id in collection.GameIds)
{
var game = playniteApi.Database.Games.Get(id);
if (game != null)
{
return game;
}
}
return null;
}
public bool HasCustomPoster(GameCollection collection)
{
return !string.IsNullOrEmpty(collection.PosterFileName);
}
public string GetCustomPosterPath(GameCollection collection)
{
var path = posterStorage.GetFullPath(collection.PosterFileName);
return path != null && File.Exists(path) ? path : null;
}
/// <summary>
/// Picks the image shown for a collection: the custom poster, otherwise the cover of the
/// first game in the collection, otherwise null (the placeholder is shown).
/// </summary>
public string ResolvePosterPath(GameCollection collection)
{
return GetCustomPosterPath(collection) ?? GetGameCoverPath(GetFirstGame(collection));
}
public string GetGameCoverPath(Game game)
{
if (game == null || string.IsNullOrWhiteSpace(game.CoverImage))
{
return null;
}
// Covers that have not been downloaded yet are stored as URLs; treat them as unavailable.
if (game.CoverImage.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
game.CoverImage.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
return null;
}
try
{
var path = playniteApi.Database.GetFullFilePath(game.CoverImage);
return File.Exists(path) ? path : null;
}
catch (Exception e)
{
logger.Warn(e, $"Failed to resolve cover path for game {game.Id}.");
return null;
}
}
#endregion
private GameCollection BuildNewCollection(string title, IEnumerable<Guid> gameIds)
{
var error = ValidateTitle(title);
if (error != null)
{
throw new InvalidOperationException(error);
}
var now = DateTime.UtcNow;
var collection = new GameCollection
{
Id = Guid.NewGuid(),
Title = NormalizeTitle(title),
CreatedAt = now,
ModifiedAt = now
};
if (gameIds != null)
{
AddDistinct(collection, gameIds);
collection.ModifiedAt = now;
}
return collection;
}
private static bool AddDistinct(GameCollection collection, IEnumerable<Guid> gameIds)
{
var existing = new HashSet<Guid>(collection.GameIds);
var added = false;
foreach (var id in gameIds)
{
if (id != Guid.Empty && existing.Add(id))
{
collection.GameIds.Add(id);
added = true;
}
}
if (added)
{
collection.ModifiedAt = DateTime.UtcNow;
}
return added;
}
private static bool RemoveIds(GameCollection collection, HashSet<Guid> gameIds)
{
var removed = collection.GameIds.RemoveAll(gameIds.Contains) > 0;
if (removed)
{
collection.ModifiedAt = DateTime.UtcNow;
}
return removed;
}
private bool Persist(IReadOnlyCollection<Guid> changedIds)
{
var saved = false;
try
{
repository.Save(collections);
saved = true;
}
catch (Exception e)
{
logger.Error(e, "Failed to save collections.");
playniteApi.Notifications.Add(new NotificationMessage(
"GameCollections_SaveError",
Loc.Format("LOCGameCollections_ErrorSaveFailed", e.Message),
NotificationType.Error));
}
try
{
CollectionsChanged?.Invoke(this, new CollectionsChangedEventArgs(changedIds));
}
catch (Exception e)
{
logger.Error(e, "Error while handling collection changes.");
}
return saved;
}
}
}
@@ -0,0 +1,218 @@
using GameCollections.Models;
using Playnite.SDK;
using Playnite.SDK.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace GameCollections.Services
{
public class RepositoryLoadResult
{
public List<GameCollection> Collections { get; }
/// <summary>
/// Message to show the user when data had to be recovered or could not be read; null otherwise.
/// </summary>
public string Warning { get; }
public RepositoryLoadResult(List<GameCollection> collections, string warning)
{
Collections = collections;
Warning = warning;
}
}
/// <summary>
/// Reads and writes the collections JSON file in the plugin's user data folder.
/// Writes go to a temporary file first and are then swapped in, keeping the previous
/// version as a backup, so an interrupted save never leaves a half-written data file.
/// </summary>
public class CollectionRepository
{
public const int CurrentSchemaVersion = 1;
private const string DataFileName = "collections.json";
private static readonly ILogger logger = LogManager.GetLogger();
private readonly string dataDirectory;
private readonly string filePath;
private readonly string backupPath;
private readonly string tempPath;
public CollectionRepository(string dataDirectory)
{
this.dataDirectory = dataDirectory;
filePath = Path.Combine(dataDirectory, DataFileName);
backupPath = filePath + ".bak";
tempPath = filePath + ".tmp";
}
public RepositoryLoadResult Load()
{
if (!File.Exists(filePath) && !File.Exists(backupPath))
{
return new RepositoryLoadResult(new List<GameCollection>(), null);
}
string preservedCopy = null;
if (File.Exists(filePath))
{
if (TryRead(filePath, out var collections))
{
return new RepositoryLoadResult(collections, null);
}
// Move the unreadable file aside so the next save cannot overwrite it.
preservedCopy = PreserveUnreadableFile(filePath);
}
if (File.Exists(backupPath) && TryRead(backupPath, out var backupCollections))
{
logger.Warn("Collections data file was unreadable, restored from backup.");
return new RepositoryLoadResult(backupCollections, Loc.Get("LOCGameCollections_WarningRestoredFromBackup"));
}
return new RepositoryLoadResult(
new List<GameCollection>(),
Loc.Format("LOCGameCollections_WarningDataUnreadable", preservedCopy ?? filePath));
}
public void Save(IEnumerable<GameCollection> collections)
{
Directory.CreateDirectory(dataDirectory);
var payload = new CollectionsDataFile
{
SchemaVersion = CurrentSchemaVersion,
Collections = collections.ToList()
};
var json = Serialization.ToJson(payload, true);
using (var stream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
{
var bytes = new UTF8Encoding(false).GetBytes(json);
stream.Write(bytes, 0, bytes.Length);
stream.Flush(true);
}
if (!File.Exists(filePath))
{
File.Move(tempPath, filePath);
return;
}
try
{
File.Replace(tempPath, filePath, backupPath, true);
}
catch (Exception e) when (e is IOException || e is PlatformNotSupportedException || e is UnauthorizedAccessException)
{
// File.Replace is not supported on every file system; fall back to copy-based replacement.
logger.Warn(e, "File.Replace failed, falling back to copy.");
File.Copy(filePath, backupPath, true);
File.Copy(tempPath, filePath, true);
File.Delete(tempPath);
}
}
private static bool TryRead(string path, out List<GameCollection> collections)
{
collections = null;
try
{
var text = File.ReadAllText(path, Encoding.UTF8);
var data = Serialization.FromJson<CollectionsDataFile>(text);
if (data == null)
{
logger.Error($"Collections file {path} contained no data.");
return false;
}
if (data.SchemaVersion > CurrentSchemaVersion)
{
logger.Warn($"Collections file {path} was written by a newer plugin version ({data.SchemaVersion}).");
}
collections = Sanitize(data.Collections);
return true;
}
catch (Exception e)
{
logger.Error(e, $"Failed to read collections file {path}.");
return false;
}
}
private static string PreserveUnreadableFile(string path)
{
try
{
var target = Path.Combine(
Path.GetDirectoryName(path),
$"{Path.GetFileNameWithoutExtension(path)}.unreadable-{DateTime.Now:yyyyMMdd-HHmmss}.json");
File.Move(path, target);
return target;
}
catch (Exception e)
{
logger.Error(e, $"Failed to move unreadable collections file {path}.");
return null;
}
}
/// <summary>
/// Repairs records that could have been damaged by manual edits so the rest of the plugin can rely on them.
/// </summary>
private static List<GameCollection> Sanitize(List<GameCollection> source)
{
var result = new List<GameCollection>();
if (source == null)
{
return result;
}
var seenIds = new HashSet<Guid>();
foreach (var collection in source)
{
if (collection == null)
{
continue;
}
if (collection.Id == Guid.Empty || !seenIds.Add(collection.Id))
{
collection.Id = Guid.NewGuid();
seenIds.Add(collection.Id);
}
collection.Title = CollectionManager.NormalizeTitle(collection.Title);
if (collection.Title.Length == 0)
{
collection.Title = Loc.Get("LOCGameCollections_UntitledCollection");
}
collection.Description = CollectionManager.NormalizeDescription(collection.Description);
collection.Rating = CollectionManager.NormalizeRating(collection.Rating);
collection.GameIds = (collection.GameIds ?? new List<Guid>())
.Where(id => id != Guid.Empty)
.Distinct()
.ToList();
if (collection.CreatedAt == default(DateTime))
{
collection.CreatedAt = DateTime.UtcNow;
}
if (collection.ModifiedAt == default(DateTime))
{
collection.ModifiedAt = collection.CreatedAt;
}
result.Add(collection);
}
return result;
}
}
}
@@ -0,0 +1,98 @@
using GameCollections.Models;
using GameCollections.ViewModels;
using GameCollections.Views;
using Playnite.SDK;
using Playnite.SDK.Models;
using System;
using System.Collections.Generic;
using System.Windows;
namespace GameCollections.Services
{
/// <summary>
/// Opens the plugin's dialogs in windows created by Playnite so they get the active theme.
/// </summary>
public class DialogService
{
private readonly IPlayniteAPI playniteApi;
private readonly CollectionManager manager;
public DialogService(IPlayniteAPI playniteApi, CollectionManager manager)
{
this.playniteApi = playniteApi;
this.manager = manager;
}
public bool ShowAddToCollection(IReadOnlyList<Game> games)
{
if (games == null || games.Count == 0)
{
return false;
}
var window = CreateWindow(Loc.Get("LOCGameCollections_AddToCollectionWindowTitle"), 460, 560, 360, 380);
var viewModel = new AddToCollectionViewModel(manager, games, result => Close(window, result));
window.Content = new AddToCollectionView { DataContext = viewModel };
return window.ShowDialog() == true;
}
/// <summary>
/// Shows the create dialog and returns the new collection's ID, or null when cancelled.
/// </summary>
public Guid? ShowCreateCollection()
{
return ShowEditor(null);
}
public bool ShowEditCollection(GameCollection collection)
{
return ShowEditor(collection).HasValue;
}
private Guid? ShowEditor(GameCollection collection)
{
var viewModel = new EditCollectionViewModel(playniteApi, manager, collection);
var window = CreateWindow(viewModel.WindowTitle, 640, 480, 520, 420);
viewModel.CloseRequested = result => Close(window, result);
window.Content = new EditCollectionView { DataContext = viewModel };
return window.ShowDialog() == true ? viewModel.SavedCollectionId : null;
}
private Window CreateWindow(string title, double width, double height, double minWidth, double minHeight)
{
var window = playniteApi.Dialogs.CreateWindow(new WindowCreationOptions
{
ShowMinimizeButton = false,
ShowMaximizeButton = false,
ShowCloseButton = true
});
// Keep dialogs usable on small or scaled screens.
var workArea = SystemParameters.WorkArea;
window.Title = title;
window.MinWidth = Math.Min(minWidth, workArea.Width);
window.MinHeight = Math.Min(minHeight, workArea.Height);
window.Width = Math.Max(window.MinWidth, Math.Min(width, workArea.Width * 0.9));
window.Height = Math.Max(window.MinHeight, Math.Min(height, workArea.Height * 0.9));
window.ResizeMode = ResizeMode.CanResize;
window.Owner = playniteApi.Dialogs.GetCurrentAppWindow();
window.WindowStartupLocation = window.Owner != null
? WindowStartupLocation.CenterOwner
: WindowStartupLocation.CenterScreen;
return window;
}
private static void Close(Window window, bool result)
{
try
{
window.DialogResult = result;
}
catch (InvalidOperationException)
{
// DialogResult can only be set while the window is shown modally.
window.Close();
}
}
}
}
@@ -0,0 +1,101 @@
using Playnite.SDK;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
namespace GameCollections.Services
{
/// <summary>
/// Decodes images off the UI thread at a reduced size and caches the results.
/// </summary>
public static class ImageLoader
{
private const int MaxCacheEntries = 400;
private static readonly ILogger logger = LogManager.GetLogger();
private static readonly object cacheLock = new object();
private static readonly Dictionary<string, BitmapSource> cache = new Dictionary<string, BitmapSource>(StringComparer.OrdinalIgnoreCase);
private static readonly SemaphoreSlim limiter = new SemaphoreSlim(Math.Max(2, Environment.ProcessorCount / 2));
public static async Task<BitmapSource> LoadAsync(string path, int decodeWidth)
{
if (string.IsNullOrEmpty(path))
{
return null;
}
await limiter.WaitAsync().ConfigureAwait(false);
try
{
return await Task.Run(() => Load(path, decodeWidth)).ConfigureAwait(false);
}
finally
{
limiter.Release();
}
}
/// <summary>
/// Returns a frozen bitmap decoded to <paramref name="decodeWidth"/> pixels wide, or null when
/// the file is missing or cannot be decoded.
/// </summary>
public static BitmapSource Load(string path, int decodeWidth)
{
try
{
var info = new FileInfo(path);
if (!info.Exists)
{
return null;
}
// Including the write time means a replaced file is never served from a stale cache entry.
var key = $"{info.FullName}|{decodeWidth}|{info.LastWriteTimeUtc.Ticks}|{info.Length}";
lock (cacheLock)
{
if (cache.TryGetValue(key, out var cached))
{
return cached;
}
}
BitmapImage bitmap;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
if (decodeWidth > 0)
{
bitmap.DecodePixelWidth = decodeWidth;
}
bitmap.StreamSource = stream;
bitmap.EndInit();
bitmap.Freeze();
}
lock (cacheLock)
{
if (cache.Count >= MaxCacheEntries)
{
cache.Clear();
}
cache[key] = bitmap;
}
return bitmap;
}
catch (Exception e)
{
logger.Warn(e, $"Failed to load image {path}.");
return null;
}
}
}
}
+40
View File
@@ -0,0 +1,40 @@
using Playnite.SDK;
using System.Globalization;
namespace GameCollections.Services
{
/// <summary>
/// Shortcuts for reading localized strings from Playnite's resource provider.
/// </summary>
public static class Loc
{
public static string Get(string key)
{
return ResourceProvider.GetString(key);
}
public static string Format(string key, params object[] args)
{
return string.Format(CultureInfo.CurrentCulture, Get(key), args);
}
public static string GameCount(int count)
{
return count == 1
? Get("LOCGameCollections_GameCountSingle")
: Format("LOCGameCollections_GameCountPlural", count);
}
public static string CollectionCount(int count)
{
return count == 1
? Get("LOCGameCollections_CollectionCountSingle")
: Format("LOCGameCollections_CollectionCountPlural", count);
}
public static string Rating(double rating)
{
return string.Format(CultureInfo.CurrentCulture, "{0:0.#}/10", rating);
}
}
}
@@ -0,0 +1,115 @@
using Playnite.SDK;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace GameCollections.Services
{
/// <summary>
/// Keeps copies of custom posters inside the plugin data folder so they survive the
/// original file being moved or deleted.
/// </summary>
public class PosterStorage
{
public static readonly string[] SupportedExtensions = { ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tif", ".tiff" };
private static readonly ILogger logger = LogManager.GetLogger();
private readonly string directory;
public PosterStorage(string directory)
{
this.directory = directory;
}
public static bool IsSupportedFile(string path)
{
var extension = Path.GetExtension(path ?? string.Empty).ToLowerInvariant();
return SupportedExtensions.Contains(extension);
}
/// <summary>
/// Copies an image into the poster folder and returns the stored file name.
/// A new name is used on every import so cached images of the old poster are never reused.
/// </summary>
public string Import(Guid collectionId, string sourcePath)
{
if (!IsSupportedFile(sourcePath))
{
throw new NotSupportedException(Loc.Get("LOCGameCollections_ErrorPosterFormat"));
}
if (!File.Exists(sourcePath))
{
throw new FileNotFoundException(Loc.Get("LOCGameCollections_ErrorPosterMissing"), sourcePath);
}
Directory.CreateDirectory(directory);
var fileName = $"{collectionId:N}_{DateTime.UtcNow.Ticks}{Path.GetExtension(sourcePath).ToLowerInvariant()}";
File.Copy(sourcePath, Path.Combine(directory, fileName), false);
return fileName;
}
public string GetFullPath(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName))
{
return null;
}
// Only plain file names are stored; strip anything else so the path cannot leave the folder.
return Path.Combine(directory, Path.GetFileName(fileName));
}
public void Delete(string fileName)
{
var path = GetFullPath(fileName);
if (path == null)
{
return;
}
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch (Exception e)
{
logger.Warn(e, $"Failed to delete poster {path}.");
}
}
/// <summary>
/// Removes poster files left behind by collections that no longer reference them.
/// </summary>
public void DeleteUnreferenced(IEnumerable<string> referencedFileNames)
{
if (!Directory.Exists(directory))
{
return;
}
var referenced = new HashSet<string>(
referencedFileNames.Where(n => !string.IsNullOrWhiteSpace(n)).Select(Path.GetFileName),
StringComparer.OrdinalIgnoreCase);
try
{
foreach (var file in Directory.EnumerateFiles(directory))
{
if (!referenced.Contains(Path.GetFileName(file)))
{
Delete(Path.GetFileName(file));
}
}
}
catch (Exception e)
{
logger.Warn(e, "Failed to clean up unreferenced posters.");
}
}
}
}
@@ -0,0 +1,64 @@
using GameCollections.Models;
using Playnite.SDK;
using Playnite.SDK.Data;
using System.Collections.Generic;
namespace GameCollections.Settings
{
public class GameCollectionsSettings : ObservableObject
{
// Remembered UI state rather than a user-facing option, so it is not shown in the settings view.
private CollectionsViewMode viewMode = CollectionsViewMode.Grid;
public CollectionsViewMode ViewMode { get => viewMode; set => SetValue(ref viewMode, value); }
}
public class GameCollectionsSettingsViewModel : ObservableObject, ISettings
{
private readonly GameCollectionsPlugin plugin;
private GameCollectionsSettings editingClone;
private GameCollectionsSettings settings;
public GameCollectionsSettings Settings
{
get => settings;
set
{
settings = value;
OnPropertyChanged();
}
}
public GameCollectionsSettingsViewModel(GameCollectionsPlugin plugin)
{
// The plugin instance is required for Save/Load because Playnite stores data per plugin.
this.plugin = plugin;
Settings = plugin.LoadPluginSettings<GameCollectionsSettings>() ?? new GameCollectionsSettings();
}
public void Save()
{
plugin.SavePluginSettings(Settings);
}
public void BeginEdit()
{
editingClone = Serialization.GetClone(Settings);
}
public void CancelEdit()
{
Settings = editingClone;
}
public void EndEdit()
{
Save();
}
public bool VerifySettings(out List<string> errors)
{
errors = new List<string>();
return true;
}
}
}
@@ -0,0 +1,15 @@
<UserControl x:Class="GameCollections.Settings.GameCollectionsSettingsView"
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"
mc:Ignorable="d"
d:DesignHeight="200" d:DesignWidth="600">
<!-- No options yet. Future settings bind to Settings.* on GameCollectionsSettingsViewModel. -->
<StackPanel Margin="20">
<TextBlock Style="{StaticResource BaseTextBlockStyle}"
Foreground="{DynamicResource TextBrushDarker}"
TextWrapping="Wrap"
Text="{DynamicResource LOCGameCollections_SettingsEmpty}" />
</StackPanel>
</UserControl>
@@ -0,0 +1,12 @@
using System.Windows.Controls;
namespace GameCollections.Settings
{
public partial class GameCollectionsSettingsView : UserControl
{
public GameCollectionsSettingsView()
{
InitializeComponent();
}
}
}
@@ -0,0 +1,215 @@
using GameCollections.Services;
using Playnite.SDK;
using Playnite.SDK.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
namespace GameCollections.ViewModels
{
/// <summary>
/// One row of the "Add to Collection" dialog.
/// </summary>
public class CollectionToggleItem : ObservableObject
{
/// <summary>
/// Collection ID, or null for a collection created in the dialog that is not saved yet.
/// </summary>
public Guid? CollectionId { get; }
public string Title { get; }
public string GameCountText { get; }
public bool IsNew => CollectionId == null;
/// <summary>
/// Membership before the dialog opened: true when all selected games are in the collection,
/// false when none are, null when only some are.
/// </summary>
public bool? OriginalState { get; }
/// <summary>
/// Only mixed rows can return to the "leave unchanged" state.
/// </summary>
public bool IsThreeState => OriginalState == null;
private bool? isChecked;
public bool? IsChecked { get => isChecked; set => SetValue(ref isChecked, value); }
public CollectionToggleItem(Guid? collectionId, string title, string gameCountText, bool? originalState)
{
CollectionId = collectionId;
Title = title;
GameCountText = gameCountText;
OriginalState = originalState;
isChecked = originalState;
}
public void Toggle()
{
IsChecked = IsChecked != true;
}
}
public class AddToCollectionViewModel : ObservableObject
{
private readonly CollectionManager manager;
private readonly IReadOnlyList<Game> games;
private readonly Action<bool> close;
public ObservableCollection<CollectionToggleItem> Items { get; } = new ObservableCollection<CollectionToggleItem>();
public ListCollectionView ItemsView { get; }
public string HeaderText { get; }
private string searchText = string.Empty;
public string SearchText
{
get => searchText;
set
{
SetValue(ref searchText, value ?? string.Empty);
ItemsView.Refresh();
RaiseStateChanged();
}
}
private CollectionToggleItem selectedItem;
public CollectionToggleItem SelectedItem { get => selectedItem; set => SetValue(ref selectedItem, value); }
public bool IsEmpty => Items.Count == 0;
public bool HasNoResults => !IsEmpty && ItemsView.Count == 0;
public bool ShowEmptyState => IsEmpty && SearchTitle.Length == 0;
/// <summary>
/// True when the search text can become a new collection: it is a valid title and no
/// existing or pending collection already uses it.
/// </summary>
public bool CanCreateFromSearch =>
SearchTitle.Length > 0 &&
SearchTitle.Length <= CollectionManager.MaxTitleLength &&
!Items.Any(i => CollectionManager.TitlesEqual(i.Title, SearchTitle));
public string CreateButtonText => Loc.Format("LOCGameCollections_CreateCollectionNamed", SearchTitle);
public string NoResultsText => Loc.Format("LOCGameCollections_NoCollectionsMatch", SearchTitle);
public RelayCommand CreateFromSearchCommand { get; }
public RelayCommand SaveCommand { get; }
public RelayCommand CancelCommand { get; }
private string SearchTitle => CollectionManager.NormalizeTitle(searchText);
public AddToCollectionViewModel(CollectionManager manager, IReadOnlyList<Game> games, Action<bool> close)
{
this.manager = manager;
this.games = games;
this.close = close;
HeaderText = games.Count == 1
? Loc.Format("LOCGameCollections_AddToCollectionHeaderSingle", games[0].Name)
: Loc.Format("LOCGameCollections_AddToCollectionHeaderMultiple", games.Count);
var gameIds = games.Select(g => g.Id).ToList();
foreach (var collection in manager.Collections)
{
var memberIds = new HashSet<Guid>(collection.GameIds);
var containedCount = gameIds.Count(memberIds.Contains);
bool? state = containedCount == 0 ? false : containedCount == gameIds.Count ? (bool?)true : null;
Items.Add(new CollectionToggleItem(collection.Id, collection.Title, Loc.GameCount(manager.GetGames(collection).Count), state));
}
ItemsView = new ListCollectionView(Items)
{
Filter = FilterItem,
CustomSort = Comparer<CollectionToggleItem>.Create(CompareItems)
};
CreateFromSearchCommand = new RelayCommand(CreateFromSearch);
SaveCommand = new RelayCommand(Save);
CancelCommand = new RelayCommand(() => close(false));
}
public void CreateFromSearch()
{
if (!CanCreateFromSearch)
{
return;
}
var item = new CollectionToggleItem(null, SearchTitle, Loc.Get("LOCGameCollections_NewCollectionBadge"), false);
item.IsChecked = true;
Items.Add(item);
SearchText = string.Empty;
SelectedItem = item;
}
/// <summary>
/// Enter in the search box creates a collection when the text is new, or toggles the
/// only matching collection. Returns false when nothing was done.
/// </summary>
public bool HandleSearchEnter()
{
if (CanCreateFromSearch && ItemsView.Count == 0)
{
CreateFromSearch();
return true;
}
if (SearchTitle.Length > 0 && ItemsView.Count == 1)
{
var item = ItemsView.Cast<CollectionToggleItem>().First();
item.Toggle();
SelectedItem = item;
return true;
}
return false;
}
private void Save()
{
var membership = new Dictionary<Guid, bool>();
foreach (var item in Items.Where(i => !i.IsNew && i.IsChecked.HasValue && i.IsChecked != i.OriginalState))
{
membership[item.CollectionId.Value] = item.IsChecked.Value;
}
var newTitles = Items.Where(i => i.IsNew && i.IsChecked == true).Select(i => i.Title).ToList();
manager.ApplyMembership(games.Select(g => g.Id).ToList(), membership, newTitles);
close(true);
}
private bool FilterItem(object obj)
{
if (SearchTitle.Length == 0)
{
return true;
}
var item = (CollectionToggleItem)obj;
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(item.Title, SearchTitle, CompareOptions.IgnoreCase) >= 0;
}
private static int CompareItems(CollectionToggleItem first, CollectionToggleItem second)
{
// Collections created in this dialog stay on top so they are easy to spot.
if (first.IsNew != second.IsNew)
{
return first.IsNew ? -1 : 1;
}
return string.Compare(first.Title, second.Title, StringComparison.CurrentCultureIgnoreCase);
}
private void RaiseStateChanged()
{
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(HasNoResults));
OnPropertyChanged(nameof(ShowEmptyState));
OnPropertyChanged(nameof(CanCreateFromSearch));
OnPropertyChanged(nameof(CreateButtonText));
OnPropertyChanged(nameof(NoResultsText));
}
}
}
@@ -0,0 +1,110 @@
using GameCollections.Models;
using GameCollections.Services;
using Playnite.SDK;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Media;
namespace GameCollections.ViewModels
{
/// <summary>
/// Actions shared by every place that shows a collection.
/// </summary>
public interface ICollectionActions
{
void OpenCollection(Guid id);
void EditCollection(Guid id);
void DeleteCollection(Guid id);
}
/// <summary>
/// Display state of one collection, used by the grid card, the list row and the collection page header.
/// </summary>
public class CollectionCardViewModel : ObservableObject
{
// Wide enough for the largest place a poster is drawn (the collection page header) on scaled displays.
private const int PosterDecodeWidth = 320;
private static readonly ILogger logger = LogManager.GetLogger();
private readonly CollectionManager manager;
private int posterVersion;
public Guid Id { get; }
private string title;
public string Title { get => title; private set => SetValue(ref title, value); }
private string description;
public string Description { get => description; private set => SetValue(ref description, value); }
private double rating;
public double Rating { get => rating; private set => SetValue(ref rating, value); }
private int gameCount;
public int GameCount { get => gameCount; private set => SetValue(ref gameCount, value); }
private ImageSource poster;
public ImageSource Poster { get => poster; private set => SetValue(ref poster, value); }
public string RatingText => Loc.Rating(rating);
public string GameCountText => Loc.GameCount(gameCount);
public bool HasDescription => !string.IsNullOrWhiteSpace(description);
/// <summary>
/// The game whose cover is used as the automatic poster, if any.
/// </summary>
public Guid? PosterGameId { get; private set; }
public RelayCommand OpenCommand { get; }
public RelayCommand EditCommand { get; }
public RelayCommand DeleteCommand { get; }
public CollectionCardViewModel(GameCollection collection, CollectionManager manager, ICollectionActions actions)
{
this.manager = manager;
Id = collection.Id;
OpenCommand = new RelayCommand(() => actions.OpenCollection(Id));
EditCommand = new RelayCommand(() => actions.EditCollection(Id));
DeleteCommand = new RelayCommand(() => actions.DeleteCollection(Id));
Update(collection);
}
public void Update(GameCollection collection)
{
Title = collection.Title;
Description = collection.Description;
Rating = collection.Rating;
GameCount = manager.GetGames(collection).Count;
OnPropertyChanged(nameof(RatingText));
OnPropertyChanged(nameof(GameCountText));
OnPropertyChanged(nameof(HasDescription));
PosterGameId = manager.HasCustomPoster(collection) ? null : manager.GetFirstGame(collection)?.Id;
_ = LoadPosterAsync(manager.ResolvePosterPath(collection));
}
private async Task LoadPosterAsync(string path)
{
var version = ++posterVersion;
if (path == null)
{
Poster = null;
return;
}
try
{
var image = await ImageLoader.LoadAsync(path, PosterDecodeWidth);
if (version == posterVersion)
{
Poster = image;
}
}
catch (Exception e)
{
logger.Error(e, $"Failed to load poster for collection {Id}.");
}
}
}
}
@@ -0,0 +1,364 @@
using GameCollections.Services;
using Playnite.SDK;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
namespace GameCollections.ViewModels
{
public enum GameSortField
{
CollectionOrder,
Name,
ReleaseDate,
LastPlayed,
Playtime,
DateAdded
}
public class SortOption
{
public GameSortField Field { get; }
public string Label { get; }
public SortOption(GameSortField field, string label)
{
Field = field;
Label = label;
}
}
/// <summary>
/// The page of a single collection: header plus its games.
/// </summary>
public class CollectionDetailsViewModel : ObservableObject
{
private const string AscendingGlyph = "\uea5e";
private const string DescendingGlyph = "\uea5b";
private static readonly ILogger logger = LogManager.GetLogger();
private readonly IPlayniteAPI playniteApi;
private readonly CollectionManager manager;
private readonly CollectionsRootViewModel root;
public CollectionCardViewModel Header { get; }
public Guid CollectionId => Header.Id;
public ObservableCollection<CollectionGameViewModel> Games { get; } = new ObservableCollection<CollectionGameViewModel>();
public ListCollectionView GamesView { get; }
/// <summary>
/// The view's current selection; set by the view.
/// </summary>
public IList SelectedGames { get; set; }
public IReadOnlyList<SortOption> SortOptions { get; } = new List<SortOption>
{
new SortOption(GameSortField.CollectionOrder, Loc.Get("LOCGameCollections_SortCollectionOrder")),
new SortOption(GameSortField.Name, Loc.Get("LOCGameCollections_SortName")),
new SortOption(GameSortField.ReleaseDate, Loc.Get("LOCGameCollections_SortReleaseDate")),
new SortOption(GameSortField.LastPlayed, Loc.Get("LOCGameCollections_SortLastPlayed")),
new SortOption(GameSortField.Playtime, Loc.Get("LOCGameCollections_SortPlaytime")),
new SortOption(GameSortField.DateAdded, Loc.Get("LOCGameCollections_SortDateAdded"))
};
private string searchText = string.Empty;
public string SearchText
{
get => searchText;
set
{
SetValue(ref searchText, value ?? string.Empty);
RefreshView();
}
}
public GameSortField SortField
{
get => root.GameSortField;
set
{
root.GameSortField = value;
OnPropertyChanged();
ApplySort();
}
}
public bool SortDescending
{
get => root.GameSortDescending;
set
{
root.GameSortDescending = value;
OnPropertyChanged();
OnPropertyChanged(nameof(SortDirectionGlyph));
OnPropertyChanged(nameof(SortDirectionTooltip));
ApplySort();
}
}
public string SortDirectionGlyph => SortDescending ? DescendingGlyph : AscendingGlyph;
public string SortDirectionTooltip => Loc.Get(SortDescending ? "LOCGameCollections_SortDescending" : "LOCGameCollections_SortAscending");
private bool installedOnly;
public bool InstalledOnly
{
get => installedOnly;
set
{
SetValue(ref installedOnly, value);
RefreshView();
}
}
public bool IsEmpty => Games.Count == 0;
public bool HasNoResults => !IsEmpty && GamesView.Count == 0;
public string VisibleCountText => GamesView.Count == Games.Count
? Loc.GameCount(Games.Count)
: Loc.Format("LOCGameCollections_FilteredGameCount", GamesView.Count, Games.Count);
public RelayCommand BackCommand { get; }
public RelayCommand ToggleSortDirectionCommand { get; }
public RelayCommand ShowAllInLibraryCommand { get; }
public RelayCommand RemoveSelectedCommand { get; }
public RelayCommand PlaySelectedCommand { get; }
public CollectionDetailsViewModel(IPlayniteAPI playniteApi, CollectionManager manager, CollectionsRootViewModel root, CollectionCardViewModel header)
{
this.playniteApi = playniteApi;
this.manager = manager;
this.root = root;
Header = header;
GamesView = new ListCollectionView(Games) { Filter = FilterGame };
ApplySort();
BackCommand = new RelayCommand(root.ShowHome);
ToggleSortDirectionCommand = new RelayCommand(() => SortDescending = !SortDescending);
ShowAllInLibraryCommand = new RelayCommand(ShowAllInLibrary);
RemoveSelectedCommand = new RelayCommand(RemoveSelected);
PlaySelectedCommand = new RelayCommand(PlaySelected);
Reload();
}
/// <summary>
/// Re-reads the collection's games, reusing existing tiles so loaded covers are kept.
/// </summary>
public void Reload()
{
var collection = manager.GetCollection(CollectionId);
if (collection == null)
{
return;
}
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())
{
Games.Remove(tile);
}
var existing = Games.ToDictionary(g => g.Id);
for (var i = 0; i < games.Count; i++)
{
if (existing.TryGetValue(games[i].Id, out var tile))
{
tile.Update(games[i], i);
}
else
{
Games.Add(new CollectionGameViewModel(games[i], i, manager, this));
}
}
RefreshView();
}
public void OnGamesUpdated(ISet<Guid> gameIds)
{
if (Games.Any(g => gameIds.Contains(g.Id)))
{
Reload();
}
}
public void PlayGame(CollectionGameViewModel tile)
{
try
{
var game = playniteApi.Database.Games.Get(tile.Id);
if (game == null)
{
return;
}
if (game.IsInstalled)
{
playniteApi.StartGame(game.Id);
}
else
{
playniteApi.InstallGame(game.Id);
}
}
catch (Exception e)
{
logger.Error(e, $"Failed to start game {tile.Id}.");
playniteApi.Dialogs.ShowErrorMessage(e.Message, Loc.Get("LOCGameCollections_PluginName"));
}
}
/// <summary>
/// Playnite has no API to open a game's detail page directly, so the game is selected
/// in the library view, which shows its details there.
/// </summary>
public void ShowGameInLibrary(CollectionGameViewModel tile)
{
try
{
playniteApi.MainView.SelectGame(tile.Id);
playniteApi.MainView.SwitchToLibraryView();
}
catch (Exception e)
{
logger.Error(e, $"Failed to show game {tile.Id} in library.");
}
}
/// <summary>
/// Removes the game from this collection only; when the game is part of a multi-selection,
/// the whole selection is removed.
/// </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 };
manager.RemoveGames(CollectionId, targets.Select(t => t.Id));
}
private void RemoveSelected()
{
var selected = SelectedGames?.Cast<CollectionGameViewModel>().ToList();
if (selected != null && selected.Count > 0)
{
manager.RemoveGames(CollectionId, selected.Select(t => t.Id));
}
}
private void PlaySelected()
{
var tile = SelectedGames?.Cast<CollectionGameViewModel>().FirstOrDefault();
if (tile != null)
{
PlayGame(tile);
}
}
private void ShowAllInLibrary()
{
if (Games.Count == 0)
{
return;
}
try
{
playniteApi.MainView.SelectGames(Games.Select(g => g.Id).ToList());
playniteApi.MainView.SwitchToLibraryView();
}
catch (Exception e)
{
logger.Error(e, "Failed to select collection games in library.");
}
}
private bool FilterGame(object obj)
{
var tile = (CollectionGameViewModel)obj;
if (installedOnly && !tile.IsInstalled)
{
return false;
}
var query = searchText.Trim();
return query.Length == 0 ||
CultureInfo.CurrentCulture.CompareInfo.IndexOf(tile.Name ?? string.Empty, query, CompareOptions.IgnoreCase) >= 0;
}
private void ApplySort()
{
GamesView.CustomSort = new GameTileComparer(SortField, SortDescending);
RaiseStateChanged();
}
private void RefreshView()
{
GamesView.Refresh();
RaiseStateChanged();
}
private void RaiseStateChanged()
{
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(HasNoResults));
OnPropertyChanged(nameof(VisibleCountText));
}
private class GameTileComparer : IComparer
{
private readonly GameSortField field;
private readonly bool descending;
public GameTileComparer(GameSortField field, bool descending)
{
this.field = field;
this.descending = descending;
}
public int Compare(object x, object y)
{
var a = (CollectionGameViewModel)x;
var b = (CollectionGameViewModel)y;
var result = CompareField(a, b);
if (result == 0 && field != GameSortField.Name)
{
result = CompareNames(a, b);
}
return descending ? -result : result;
}
private int CompareField(CollectionGameViewModel a, CollectionGameViewModel b)
{
switch (field)
{
case GameSortField.Name:
return CompareNames(a, b);
case GameSortField.ReleaseDate:
return Nullable.Compare(a.Game.ReleaseDate?.Date, b.Game.ReleaseDate?.Date);
case GameSortField.LastPlayed:
return Nullable.Compare(a.Game.LastActivity, b.Game.LastActivity);
case GameSortField.Playtime:
return a.Game.Playtime.CompareTo(b.Game.Playtime);
case GameSortField.DateAdded:
return Nullable.Compare(a.Game.Added, b.Game.Added);
default:
return a.Order.CompareTo(b.Order);
}
}
private static int CompareNames(CollectionGameViewModel a, CollectionGameViewModel b)
{
var first = string.IsNullOrEmpty(a.Game.SortingName) ? a.Name : a.Game.SortingName;
var second = string.IsNullOrEmpty(b.Game.SortingName) ? b.Name : b.Game.SortingName;
return string.Compare(first, second, StringComparison.CurrentCultureIgnoreCase);
}
}
}
}
@@ -0,0 +1,99 @@
using GameCollections.Services;
using Playnite.SDK;
using Playnite.SDK.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Media;
namespace GameCollections.ViewModels
{
/// <summary>
/// A game tile on the collection page. The cover is loaded only once the tile scrolls into view.
/// </summary>
public class CollectionGameViewModel : ObservableObject
{
private const int CoverDecodeWidth = 240;
private static readonly ILogger logger = LogManager.GetLogger();
private readonly CollectionManager manager;
private bool coverRequested;
private string coverPath;
private int coverVersion;
private Game game;
public Game Game => game;
public Guid Id => game.Id;
public string Name => game.Name;
public bool IsInstalled => game.IsInstalled;
/// <summary>
/// Position of the game in the collection, used for the "collection order" sort.
/// </summary>
public int Order { get; private set; }
public string PlayActionText => Loc.Get(IsInstalled ? "LOCGameCollections_Play" : "LOCGameCollections_Install");
private ImageSource cover;
public ImageSource Cover { get => cover; private set => SetValue(ref cover, value); }
public RelayCommand PlayCommand { get; }
public RelayCommand ShowInLibraryCommand { get; }
public RelayCommand RemoveCommand { get; }
public CollectionGameViewModel(Game game, int order, CollectionManager manager, CollectionDetailsViewModel owner)
{
this.game = game;
this.manager = manager;
Order = order;
PlayCommand = new RelayCommand(() => owner.PlayGame(this));
ShowInLibraryCommand = new RelayCommand(() => owner.ShowGameInLibrary(this));
RemoveCommand = new RelayCommand(() => owner.RemoveGame(this));
}
public void Update(Game updatedGame, int order)
{
game = updatedGame;
Order = order;
OnPropertyChanged(nameof(Game));
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(IsInstalled));
OnPropertyChanged(nameof(PlayActionText));
if (coverRequested && manager.GetGameCoverPath(game) != coverPath)
{
_ = LoadCoverAsync();
}
}
public void RequestCover()
{
if (coverRequested)
{
return;
}
coverRequested = true;
_ = LoadCoverAsync();
}
private async Task LoadCoverAsync()
{
var version = ++coverVersion;
var path = manager.GetGameCoverPath(game);
coverPath = path;
try
{
var image = await ImageLoader.LoadAsync(path, CoverDecodeWidth);
if (version == coverVersion)
{
Cover = image;
}
}
catch (Exception e)
{
logger.Error(e, $"Failed to load cover for game {game.Id}.");
}
}
}
}
@@ -0,0 +1,156 @@
using GameCollections.Models;
using GameCollections.Services;
using GameCollections.Settings;
using Playnite.SDK;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
namespace GameCollections.ViewModels
{
/// <summary>
/// The page listing every collection.
/// </summary>
public class CollectionsHomeViewModel : ObservableObject
{
private const string GridGlyph = "\uef5d";
private const string ListGlyph = "\uef74";
private readonly CollectionManager manager;
private readonly ICollectionActions actions;
private readonly GameCollectionsSettingsViewModel settings;
public ObservableCollection<CollectionCardViewModel> Cards { get; } = new ObservableCollection<CollectionCardViewModel>();
public ListCollectionView CardsView { get; }
private string searchText = string.Empty;
public string SearchText
{
get => searchText;
set
{
SetValue(ref searchText, value ?? string.Empty);
CardsView.Refresh();
RaiseStateChanged();
}
}
private CollectionCardViewModel selectedCard;
public CollectionCardViewModel SelectedCard { get => selectedCard; set => SetValue(ref selectedCard, value); }
public bool IsGridView => settings.Settings.ViewMode == CollectionsViewMode.Grid;
public bool IsListView => !IsGridView;
public string ViewModeToggleGlyph => IsGridView ? ListGlyph : GridGlyph;
public string ViewModeToggleTooltip => Loc.Get(IsGridView ? "LOCGameCollections_SwitchToListView" : "LOCGameCollections_SwitchToGridView");
public string CountText => Loc.CollectionCount(Cards.Count);
public bool IsEmpty => Cards.Count == 0;
public bool HasNoResults => !IsEmpty && CardsView.Count == 0;
public string NoResultsText => Loc.Format("LOCGameCollections_NoCollectionsMatch", searchText.Trim());
public RelayCommand CreateCollectionCommand { get; }
public RelayCommand ToggleViewModeCommand { get; }
public CollectionsHomeViewModel(CollectionManager manager, CollectionsRootViewModel root, GameCollectionsSettingsViewModel settings)
{
this.manager = manager;
this.actions = root;
this.settings = settings;
CardsView = new ListCollectionView(Cards)
{
Filter = FilterCard,
CustomSort = Comparer<CollectionCardViewModel>.Create((a, b) => string.Compare(a.Title, b.Title, StringComparison.CurrentCultureIgnoreCase))
};
CreateCollectionCommand = new RelayCommand(() => root.CreateCollection());
ToggleViewModeCommand = new RelayCommand(ToggleViewMode);
Sync(null);
}
public CollectionCardViewModel GetCard(Guid id)
{
return Cards.FirstOrDefault(c => c.Id == id);
}
/// <summary>
/// Brings the cards in line with the manager. Only cards listed in <paramref name="changedIds"/>
/// are refreshed; null refreshes all of them.
/// </summary>
public void Sync(IReadOnlyCollection<Guid> changedIds)
{
var currentIds = new HashSet<Guid>(manager.Collections.Select(c => c.Id));
foreach (var card in Cards.Where(c => !currentIds.Contains(c.Id)).ToList())
{
Cards.Remove(card);
}
var existing = Cards.ToDictionary(c => c.Id);
foreach (var collection in manager.Collections)
{
if (!existing.TryGetValue(collection.Id, out var card))
{
Cards.Add(new CollectionCardViewModel(collection, manager, actions));
}
else if (changedIds == null || changedIds.Contains(collection.Id))
{
card.Update(collection);
}
}
// Titles may have changed, so re-apply sorting and filtering.
var selected = SelectedCard;
CardsView.Refresh();
SelectedCard = selected != null && Cards.Contains(selected) ? selected : null;
RaiseStateChanged();
}
/// <summary>
/// Reloads cards whose automatic poster comes from one of the updated games.
/// </summary>
public void OnGamesUpdated(ISet<Guid> gameIds)
{
foreach (var card in Cards.Where(c => c.PosterGameId.HasValue && gameIds.Contains(c.PosterGameId.Value)))
{
var collection = manager.GetCollection(card.Id);
if (collection != null)
{
card.Update(collection);
}
}
}
private void ToggleViewMode()
{
settings.Settings.ViewMode = IsGridView ? CollectionsViewMode.List : CollectionsViewMode.Grid;
settings.Save();
OnPropertyChanged(nameof(IsGridView));
OnPropertyChanged(nameof(IsListView));
OnPropertyChanged(nameof(ViewModeToggleGlyph));
OnPropertyChanged(nameof(ViewModeToggleTooltip));
}
private bool FilterCard(object obj)
{
var query = searchText.Trim();
if (query.Length == 0)
{
return true;
}
var card = (CollectionCardViewModel)obj;
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(card.Title ?? string.Empty, query, CompareOptions.IgnoreCase) >= 0;
}
private void RaiseStateChanged()
{
OnPropertyChanged(nameof(CountText));
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(HasNoResults));
OnPropertyChanged(nameof(NoResultsText));
}
}
}
@@ -0,0 +1,115 @@
using GameCollections.Services;
using GameCollections.Settings;
using Playnite.SDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
namespace GameCollections.ViewModels
{
/// <summary>
/// Navigation state of the Collections sidebar view. It outlives the view itself, so the open
/// page, search text and sort choices are kept when the user leaves and comes back.
/// </summary>
public class CollectionsRootViewModel : ObservableObject, ICollectionActions
{
private readonly IPlayniteAPI playniteApi;
private readonly CollectionManager manager;
private readonly DialogService dialogs;
public CollectionsHomeViewModel Home { get; }
private object currentPage;
public object CurrentPage { get => currentPage; private set => SetValue(ref currentPage, value); }
// Shared by all collection pages so the chosen sort carries over between collections.
public GameSortField GameSortField { get; set; } = GameSortField.CollectionOrder;
public bool GameSortDescending { get; set; }
public CollectionsRootViewModel(IPlayniteAPI playniteApi, CollectionManager manager, DialogService dialogs, GameCollectionsSettingsViewModel settings)
{
this.playniteApi = playniteApi;
this.manager = manager;
this.dialogs = dialogs;
Home = new CollectionsHomeViewModel(manager, this, settings);
CurrentPage = Home;
manager.CollectionsChanged += OnCollectionsChanged;
}
public void ShowHome()
{
CurrentPage = Home;
}
public void OpenCollection(Guid id)
{
var card = Home.GetCard(id);
if (card != null)
{
Home.SelectedCard = card;
CurrentPage = new CollectionDetailsViewModel(playniteApi, manager, this, card);
}
}
public void CreateCollection()
{
var id = dialogs.ShowCreateCollection();
if (id.HasValue)
{
Home.SelectedCard = Home.GetCard(id.Value);
}
}
public void EditCollection(Guid id)
{
var collection = manager.GetCollection(id);
if (collection != null)
{
dialogs.ShowEditCollection(collection);
}
}
public void DeleteCollection(Guid id)
{
var collection = manager.GetCollection(id);
if (collection == null)
{
return;
}
var answer = playniteApi.Dialogs.ShowMessage(
Loc.Format("LOCGameCollections_DeleteConfirmMessage", collection.Title),
Loc.Get("LOCGameCollections_DeleteConfirmTitle"),
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (answer == MessageBoxResult.Yes)
{
manager.DeleteCollection(id);
}
}
public void OnGamesUpdated(ISet<Guid> gameIds)
{
Home.OnGamesUpdated(gameIds);
(CurrentPage as CollectionDetailsViewModel)?.OnGamesUpdated(gameIds);
}
private void OnCollectionsChanged(object sender, CollectionsChangedEventArgs e)
{
Home.Sync(e.ChangedIds);
if (CurrentPage is CollectionDetailsViewModel details)
{
if (manager.GetCollection(details.CollectionId) == null)
{
ShowHome();
}
else if (e.ChangedIds == null || e.ChangedIds.Contains(details.CollectionId))
{
details.Reload();
}
}
}
}
}
@@ -0,0 +1,226 @@
using GameCollections.Models;
using GameCollections.Services;
using Playnite.SDK;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Media;
namespace GameCollections.ViewModels
{
/// <summary>
/// Backs the dialog used both to create a collection and to edit an existing one.
/// </summary>
public class EditCollectionViewModel : ObservableObject
{
private const int PreviewDecodeWidth = 320;
private static readonly ILogger logger = LogManager.GetLogger();
private readonly IPlayniteAPI playniteApi;
private readonly CollectionManager manager;
private readonly GameCollection existing;
private PosterChange posterChange = PosterChange.Keep;
private string posterSourcePath;
private int previewVersion;
public Action<bool> CloseRequested { get; set; }
public Guid? SavedCollectionId { get; private set; }
public bool IsEditing => existing != null;
public string WindowTitle => Loc.Get(IsEditing ? "LOCGameCollections_EditCollectionWindowTitle" : "LOCGameCollections_CreateCollectionWindowTitle");
public int MaxTitleLength => CollectionManager.MaxTitleLength;
public int MaxDescriptionLength => CollectionManager.MaxDescriptionLength;
private string title = string.Empty;
public string Title
{
get => title;
set
{
SetValue(ref title, value ?? string.Empty);
titleTouched = true;
RaiseValidationChanged();
}
}
private string description = string.Empty;
public string Description { get => description; set => SetValue(ref description, value ?? string.Empty); }
private double rating;
public double Rating
{
get => rating;
set
{
SetValue(ref rating, CollectionManager.NormalizeRating(value));
OnPropertyChanged(nameof(RatingText));
}
}
public string RatingText => Loc.Rating(rating);
private ImageSource posterPreview;
public ImageSource PosterPreview { get => posterPreview; private set => SetValue(ref posterPreview, value); }
private string posterHint;
public string PosterHint { get => posterHint; private set => SetValue(ref posterHint, value); }
public bool HasCustomPoster =>
posterChange == PosterChange.Replace ||
(posterChange == PosterChange.Keep && existing != null && manager.HasCustomPoster(existing));
private string errorMessage;
public string ErrorMessage { get => errorMessage; private set => SetValue(ref errorMessage, value); }
// A fresh "create" dialog should not open with a "title is required" error.
private bool titleTouched;
public string TitleError => titleTouched || IsEditing ? manager.ValidateTitle(title, existing?.Id) : null;
public bool CanSave => manager.ValidateTitle(title, existing?.Id) == null;
public RelayCommand SaveCommand { get; }
public RelayCommand CancelCommand { get; }
public RelayCommand BrowsePosterCommand { get; }
public RelayCommand RemovePosterCommand { get; }
public EditCollectionViewModel(IPlayniteAPI playniteApi, CollectionManager manager, GameCollection existing)
{
this.playniteApi = playniteApi;
this.manager = manager;
this.existing = existing;
if (existing != null)
{
title = existing.Title;
description = existing.Description ?? string.Empty;
rating = existing.Rating;
}
SaveCommand = new RelayCommand(Save);
CancelCommand = new RelayCommand(() => CloseRequested?.Invoke(false));
BrowsePosterCommand = new RelayCommand(BrowsePoster);
RemovePosterCommand = new RelayCommand(RemovePoster);
_ = UpdatePosterPreviewAsync();
}
private void BrowsePoster()
{
var path = playniteApi.Dialogs.SelectImagefile();
if (string.IsNullOrEmpty(path))
{
return;
}
if (!PosterStorage.IsSupportedFile(path))
{
ErrorMessage = Loc.Get("LOCGameCollections_ErrorPosterFormat");
return;
}
// Make sure the image can actually be decoded before accepting it.
if (ImageLoader.Load(path, PreviewDecodeWidth) == null)
{
ErrorMessage = Loc.Get("LOCGameCollections_ErrorPosterUnreadable");
return;
}
ErrorMessage = null;
posterChange = PosterChange.Replace;
posterSourcePath = path;
OnPropertyChanged(nameof(HasCustomPoster));
_ = UpdatePosterPreviewAsync();
}
private void RemovePoster()
{
posterChange = PosterChange.Remove;
posterSourcePath = null;
OnPropertyChanged(nameof(HasCustomPoster));
_ = UpdatePosterPreviewAsync();
}
/// <summary>
/// Shows the poster the collection will have after saving, including the automatic fallback.
/// </summary>
private async Task UpdatePosterPreviewAsync()
{
var version = ++previewVersion;
string path;
if (posterChange == PosterChange.Replace)
{
path = posterSourcePath;
PosterHint = Loc.Get("LOCGameCollections_PosterHintCustom");
}
else
{
var custom = posterChange == PosterChange.Keep && existing != null ? manager.GetCustomPosterPath(existing) : null;
var automatic = existing != null ? manager.GetGameCoverPath(manager.GetFirstGame(existing)) : null;
if (custom != null)
{
path = custom;
PosterHint = Loc.Get("LOCGameCollections_PosterHintCustom");
}
else if (automatic != null)
{
path = automatic;
PosterHint = Loc.Get("LOCGameCollections_PosterHintAutomatic");
}
else
{
path = null;
PosterHint = Loc.Get("LOCGameCollections_PosterHintPlaceholder");
}
}
try
{
var image = await ImageLoader.LoadAsync(path, PreviewDecodeWidth);
if (version == previewVersion)
{
PosterPreview = image;
}
}
catch (Exception e)
{
logger.Error(e, "Failed to load poster preview.");
}
}
private void Save()
{
titleTouched = true;
RaiseValidationChanged();
if (!CanSave)
{
return;
}
try
{
if (existing == null)
{
var created = manager.CreateCollection(title, description, rating, posterChange == PosterChange.Replace ? posterSourcePath : null, null);
SavedCollectionId = created.Id;
}
else
{
manager.UpdateCollection(existing.Id, title, description, rating, posterChange, posterSourcePath);
SavedCollectionId = existing.Id;
}
CloseRequested?.Invoke(true);
}
catch (Exception e)
{
logger.Error(e, "Failed to save collection.");
ErrorMessage = Loc.Format("LOCGameCollections_ErrorSaveCollection", e.Message);
}
}
private void RaiseValidationChanged()
{
OnPropertyChanged(nameof(TitleError));
OnPropertyChanged(nameof(CanSave));
}
}
}
@@ -0,0 +1,88 @@
<UserControl x:Class="GameCollections.Views.AddToCollectionView"
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:AddToCollectionViewModel}"
d:DesignHeight="520" d:DesignWidth="440">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/GameCollections;component/Views/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<DockPanel Margin="15">
<TextBlock DockPanel.Dock="Top" Text="{Binding HeaderText}" Style="{StaticResource GcText}"
FontWeight="SemiBold" TextWrapping="Wrap" Margin="0,0,0,10" />
<local:SearchBox x:Name="SearchInput" DockPanel.Dock="Top" Height="32"
Text="{Binding SearchText}"
Placeholder="{DynamicResource LOCGameCollections_SearchOrCreate}" />
<Button DockPanel.Dock="Top" Style="{StaticResource GcButton}" Margin="0,8,0,0"
HorizontalAlignment="Stretch" HorizontalContentAlignment="Left"
Command="{Binding CreateFromSearchCommand}"
Visibility="{Binding CanCreateFromSearch, Converter={StaticResource BoolToVisibility}}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="&#xefc2;" Style="{StaticResource GcGlyph}" Margin="0,0,8,0" />
<TextBlock Text="{Binding CreateButtonText}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
</StackPanel>
</Button>
<!-- Footer -->
<DockPanel DockPanel.Dock="Bottom" Margin="0,12,0,0" LastChildFill="False">
<Button DockPanel.Dock="Right" MinWidth="90" Margin="8,0,0,0"
IsCancel="True"
Command="{Binding CancelCommand}"
Content="{DynamicResource LOCGameCollections_Cancel}" />
<Button DockPanel.Dock="Right" MinWidth="90"
IsDefault="True"
Command="{Binding SaveCommand}"
Content="{DynamicResource LOCGameCollections_Save}" />
</DockPanel>
<Grid Margin="0,10,0,0">
<ListBox x:Name="CollectionsList"
ItemsSource="{Binding ItemsView}"
SelectedItem="{Binding SelectedItem}"
IsSynchronizedWithCurrentItem="False"
HorizontalContentAlignment="Stretch"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
PreviewKeyDown="CollectionsList_PreviewKeyDown"
AutomationProperties.Name="{DynamicResource LOCGameCollections_PageTitle}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type vm:CollectionToggleItem}">
<DockPanel>
<TextBlock DockPanel.Dock="Right" Text="{Binding GameCountText}" Style="{StaticResource GcMutedText}"
VerticalAlignment="Center" Margin="10,0,0,0" />
<CheckBox IsChecked="{Binding IsChecked}"
IsThreeState="{Binding IsThreeState}"
VerticalContentAlignment="Center"
Focusable="False"
AutomationProperties.Name="{Binding Title}">
<TextBlock Text="{Binding Title}" TextTrimming="CharacterEllipsis" />
</CheckBox>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- No collections exist yet -->
<TextBlock Text="{DynamicResource LOCGameCollections_AddDialogEmpty}" Style="{StaticResource GcMutedText}"
TextWrapping="Wrap" TextAlignment="Center"
HorizontalAlignment="Center" VerticalAlignment="Center" Margin="20"
Visibility="{Binding ShowEmptyState, Converter={StaticResource BoolToVisibility}}" />
<!-- Search matched nothing -->
<TextBlock Text="{Binding NoResultsText}" Style="{StaticResource GcMutedText}"
TextWrapping="Wrap" TextAlignment="Center"
HorizontalAlignment="Center" VerticalAlignment="Center" Margin="20"
Visibility="{Binding HasNoResults, Converter={StaticResource BoolToVisibility}}" />
</Grid>
</DockPanel>
</UserControl>
@@ -0,0 +1,68 @@
using GameCollections.ViewModels;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
namespace GameCollections.Views
{
public partial class AddToCollectionView : UserControl
{
public AddToCollectionView()
{
InitializeComponent();
Loaded += (s, e) => Dispatcher.BeginInvoke(DispatcherPriority.Input, new System.Action(SearchInput.FocusInput));
SearchInput.PreviewKeyDown += SearchInput_PreviewKeyDown;
}
private AddToCollectionViewModel ViewModel => DataContext as AddToCollectionViewModel;
private void SearchInput_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (ViewModel == null)
{
return;
}
if (e.Key == Key.Enter)
{
// Unhandled Enter falls through to the default (Save) button.
e.Handled = ViewModel.HandleSearchEnter();
}
else if (e.Key == Key.Down && CollectionsList.Items.Count > 0)
{
FocusList();
e.Handled = true;
}
}
private void CollectionsList_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space && CollectionsList.SelectedItem is CollectionToggleItem item)
{
item.Toggle();
e.Handled = true;
}
else if (e.Key == Key.Up && CollectionsList.SelectedIndex <= 0)
{
SearchInput.FocusInput();
e.Handled = true;
}
}
private void FocusList()
{
if (CollectionsList.SelectedIndex < 0)
{
CollectionsList.SelectedIndex = 0;
}
CollectionsList.ScrollIntoView(CollectionsList.SelectedItem);
CollectionsList.UpdateLayout();
if (CollectionsList.ItemContainerGenerator.ContainerFromIndex(CollectionsList.SelectedIndex) is UIElement container)
{
container.Focus();
}
}
}
}
@@ -0,0 +1,163 @@
<UserControl x:Class="GameCollections.Views.CollectionDetailsView"
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:CollectionDetailsViewModel}"
d:DesignHeight="700" d:DesignWidth="900">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/GameCollections;component/Views/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
<ContextMenu x:Key="GameContextMenu" x:Shared="False">
<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" />
</ContextMenu>
<Style x:Key="GameContainerStyle" TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="ContextMenu" Value="{StaticResource GameContextMenu}" />
<Setter Property="Margin" Value="0,0,8,8" />
<Setter Property="Padding" Value="6" />
<Setter Property="AutomationProperties.Name" Value="{Binding Name}" />
<Setter Property="ToolTip" Value="{Binding Name}" />
<EventSetter Event="MouseDoubleClick" Handler="GameItem_MouseDoubleClick" />
<EventSetter Event="Loaded" Handler="GameItem_Loaded" />
</Style>
<DataTemplate x:Key="GameTemplate" DataType="{x:Type vm:CollectionGameViewModel}">
<StackPanel Width="130">
<Grid Width="130" Height="195">
<local:PosterImage GlyphSize="40" Glyph="&#xea30;" Source="{Binding Cover}" />
<!-- Dim games that are not installed, as Playnite's own grid does. -->
<Border Background="#80000000" CornerRadius="4" IsHitTestVisible="False"
Visibility="{Binding IsInstalled, Converter={StaticResource InverseBoolToVisibility}}" />
</Grid>
<TextBlock Text="{Binding Name}" Style="{StaticResource GcText}"
TextTrimming="CharacterEllipsis" TextWrapping="NoWrap"
Margin="0,6,0,0" />
</StackPanel>
</DataTemplate>
</ResourceDictionary>
</UserControl.Resources>
<DockPanel Margin="20,10,20,0">
<!-- Back navigation -->
<Button DockPanel.Dock="Top" HorizontalAlignment="Left" Style="{StaticResource GcButton}"
Command="{Binding BackCommand}"
AutomationProperties.Name="{DynamicResource LOCGameCollections_BackToCollections}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="&#xea5c;" Style="{StaticResource GcGlyph}" Margin="0,0,6,0" />
<TextBlock Text="{DynamicResource LOCGameCollections_BackToCollections}" VerticalAlignment="Center" />
</StackPanel>
</Button>
<!-- Collection header -->
<Grid DockPanel.Dock="Top" Margin="0,15,0,15">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<local:PosterImage Width="140" Height="210" GlyphSize="52" Source="{Binding Header.Poster}" VerticalAlignment="Top" />
<StackPanel Grid.Column="1" Margin="20,0,0,0">
<TextBlock Text="{Binding Header.Title}" Style="{StaticResource GcPageTitleText}" TextWrapping="Wrap" />
<StackPanel Orientation="Horizontal" Margin="0,8,0,0">
<TextBlock Text="&#xf000;" Style="{StaticResource GcGlyph}"
Foreground="{DynamicResource GlyphBrush}" Margin="0,0,5,0" />
<TextBlock Text="{Binding Header.RatingText}" Style="{StaticResource GcText}" />
<TextBlock Text="•" Style="{StaticResource GcMutedText}" Margin="10,0" />
<TextBlock Text="{Binding Header.GameCountText}" Style="{StaticResource GcMutedText}" />
</StackPanel>
<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" />
</ScrollViewer>
<WrapPanel Orientation="Horizontal" Margin="0,14,0,0">
<Button Style="{StaticResource GcButton}" Command="{Binding Header.EditCommand}" Margin="0,0,8,0">
<StackPanel Orientation="Horizontal">
<TextBlock Text="&#xec55;" Style="{StaticResource GcGlyph}" Margin="0,0,6,0" />
<TextBlock Text="{DynamicResource LOCGameCollections_EditCollection}" VerticalAlignment="Center" />
</StackPanel>
</Button>
<Button Style="{StaticResource GcButton}" Command="{Binding ShowAllInLibraryCommand}" Margin="0,0,8,0"
ToolTip="{DynamicResource LOCGameCollections_ShowAllInLibraryTooltip}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="&#xef24;" Style="{StaticResource GcGlyph}" Margin="0,0,6,0" />
<TextBlock Text="{DynamicResource LOCGameCollections_ShowAllInLibrary}" VerticalAlignment="Center" />
</StackPanel>
</Button>
<Button Style="{StaticResource GcButton}" Command="{Binding Header.DeleteCommand}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="&#xec53;" Style="{StaticResource GcGlyph}" Margin="0,0,6,0" />
<TextBlock Text="{DynamicResource LOCGameCollections_DeleteCollection}" VerticalAlignment="Center" />
</StackPanel>
</Button>
</WrapPanel>
</StackPanel>
</Grid>
<!-- Toolbar: search, sort, filter -->
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,10" LastChildFill="False">
<local:SearchBox DockPanel.Dock="Left" Width="240" Height="32"
Text="{Binding SearchText}"
Placeholder="{DynamicResource LOCGameCollections_SearchGames}" />
<TextBlock DockPanel.Dock="Left" Text="{DynamicResource LOCGameCollections_SortBy}" Style="{StaticResource GcText}"
VerticalAlignment="Center" Margin="16,0,8,0" />
<ComboBox DockPanel.Dock="Left" MinWidth="150" VerticalAlignment="Center"
ItemsSource="{Binding SortOptions}"
DisplayMemberPath="Label"
SelectedValuePath="Field"
SelectedValue="{Binding SortField}"
AutomationProperties.Name="{DynamicResource LOCGameCollections_SortBy}" />
<Button DockPanel.Dock="Left" Style="{StaticResource GcIconButton}" Height="32" Margin="5,0,0,0"
Content="{Binding SortDirectionGlyph}"
Command="{Binding ToggleSortDirectionCommand}"
ToolTip="{Binding SortDirectionTooltip}"
AutomationProperties.Name="{Binding SortDirectionTooltip}" />
<CheckBox DockPanel.Dock="Left" VerticalAlignment="Center" Margin="16,0,0,0"
IsChecked="{Binding InstalledOnly}"
Content="{DynamicResource LOCGameCollections_InstalledOnly}" />
<TextBlock DockPanel.Dock="Right" Text="{Binding VisibleCountText}" Style="{StaticResource GcMutedText}"
VerticalAlignment="Center" Margin="10,0,0,0" />
</DockPanel>
<Grid>
<ListBox x:Name="GamesList"
Style="{StaticResource GcPlainListBox}"
ItemsSource="{Binding GamesView}"
IsSynchronizedWithCurrentItem="False"
SelectionMode="Extended"
ItemTemplate="{StaticResource GameTemplate}"
ItemContainerStyle="{StaticResource GameContainerStyle}"
ScrollViewer.CanContentScroll="False"
KeyDown="GamesList_KeyDown"
SizeChanged="GamesList_SizeChanged"
AutomationProperties.Name="{Binding Header.Title}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" Margin="0,0,0,10" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
<!-- 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}"
FontSize="{DynamicResource FontSizeLarge}" HorizontalAlignment="Center" />
<TextBlock Text="{DynamicResource LOCGameCollections_CollectionEmptyDescription}" Style="{StaticResource GcMutedText}"
TextWrapping="Wrap" TextAlignment="Center" Margin="0,8,0,0" />
</StackPanel>
<TextBlock Text="{DynamicResource LOCGameCollections_NoGamesMatch}" Style="{StaticResource GcMutedText}"
HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,40,0,0"
Visibility="{Binding HasNoResults, Converter={StaticResource BoolToVisibility}}" />
</Grid>
</DockPanel>
</UserControl>
@@ -0,0 +1,154 @@
using GameCollections.ViewModels;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace GameCollections.Views
{
public partial class CollectionDetailsView : UserControl
{
private readonly DispatcherTimer coverTimer;
private ScrollViewer scrollViewer;
public CollectionDetailsView()
{
InitializeComponent();
// Covers are requested only for tiles near the viewport, batched to avoid work on every scroll tick.
coverTimer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(80) };
coverTimer.Tick += (s, e) =>
{
coverTimer.Stop();
RequestVisibleCovers();
};
GamesList.SelectionChanged += (s, e) => SyncSelection();
DataContextChanged += (s, e) => SyncSelection();
Loaded += OnLoaded;
Unloaded += (s, e) => coverTimer.Stop();
}
private CollectionDetailsViewModel ViewModel => DataContext as CollectionDetailsViewModel;
private void OnLoaded(object sender, RoutedEventArgs e)
{
if (scrollViewer == null)
{
scrollViewer = FindDescendant<ScrollViewer>(GamesList);
if (scrollViewer != null)
{
scrollViewer.ScrollChanged += (s, args) => ScheduleCoverRequest();
}
}
ScheduleCoverRequest();
}
private void SyncSelection()
{
if (ViewModel != null)
{
ViewModel.SelectedGames = GamesList.SelectedItems;
}
}
private void GameItem_Loaded(object sender, RoutedEventArgs e)
{
ScheduleCoverRequest();
}
private void GamesList_SizeChanged(object sender, SizeChangedEventArgs e)
{
ScheduleCoverRequest();
}
private void ScheduleCoverRequest()
{
coverTimer.Stop();
coverTimer.Start();
}
private void RequestVisibleCovers()
{
if (scrollViewer == null || !IsLoaded)
{
return;
}
// Load one extra screen above and below so covers are ready before they scroll in.
var margin = scrollViewer.ViewportHeight;
foreach (var item in GamesList.Items)
{
if (!(GamesList.ItemContainerGenerator.ContainerFromItem(item) is FrameworkElement container) || !container.IsVisible)
{
continue;
}
try
{
var top = container.TransformToAncestor(scrollViewer).Transform(new Point(0, 0)).Y;
if (top + container.ActualHeight >= -margin && top <= scrollViewer.ViewportHeight + margin)
{
((CollectionGameViewModel)item).RequestCover();
}
}
catch (InvalidOperationException)
{
// The container is being detached from the visual tree.
}
}
}
private void GameItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (sender is ListBoxItem item && item.DataContext is CollectionGameViewModel game)
{
game.PlayCommand.Execute(null);
e.Handled = true;
}
}
private void GamesList_KeyDown(object sender, KeyEventArgs e)
{
if (ViewModel == null)
{
return;
}
switch (e.Key)
{
case Key.Enter:
ViewModel.PlaySelectedCommand.Execute(null);
e.Handled = true;
break;
case Key.Delete:
ViewModel.RemoveSelectedCommand.Execute(null);
e.Handled = true;
break;
}
}
private static T FindDescendant<T>(DependencyObject parent) where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T match)
{
return match;
}
var nested = FindDescendant<T>(child);
if (nested != null)
{
return nested;
}
}
return null;
}
}
}
@@ -0,0 +1,192 @@
<UserControl x:Class="GameCollections.Views.CollectionsHomeView"
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:CollectionsHomeViewModel}"
d:DesignHeight="600" d:DesignWidth="900">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/GameCollections;component/Views/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
<ContextMenu x:Key="CardContextMenu" x:Shared="False">
<MenuItem Header="{DynamicResource LOCGameCollections_Open}" Command="{Binding OpenCommand}" FontWeight="SemiBold" />
<MenuItem Header="{DynamicResource LOCGameCollections_Edit}" Command="{Binding EditCommand}" InputGestureText="F2" />
<Separator />
<MenuItem Header="{DynamicResource LOCGameCollections_Delete}" Command="{Binding DeleteCommand}" InputGestureText="Del" />
</ContextMenu>
<Style x:Key="CardContainerStyle" TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="ContextMenu" Value="{StaticResource CardContextMenu}" />
<Setter Property="Margin" Value="0,0,10,10" />
<Setter Property="Padding" Value="8" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
<EventSetter Event="MouseLeftButtonUp" Handler="CardItem_MouseLeftButtonUp" />
</Style>
<Style x:Key="RowContainerStyle" TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="ContextMenu" Value="{StaticResource CardContextMenu}" />
<Setter Property="Padding" Value="8,6" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
<EventSetter Event="MouseDoubleClick" Handler="RowItem_MouseDoubleClick" />
</Style>
<!-- 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}" />
<TextBlock Text="{Binding Title}" ToolTip="{Binding Title}"
Style="{StaticResource GcItemTitleText}" Margin="0,8,0,0" />
<TextBlock Text="{Binding Description}" Style="{StaticResource GcMutedText}"
FontSize="{DynamicResource FontSizeSmall}"
TextWrapping="Wrap" TextTrimming="CharacterEllipsis"
Height="32" Margin="0,3,0,0" />
<DockPanel Margin="0,6,0,0">
<TextBlock DockPanel.Dock="Right" Text="{Binding GameCountText}"
Style="{StaticResource GcMutedText}" FontSize="{DynamicResource FontSizeSmall}" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="&#xf000;" Style="{StaticResource GcGlyph}"
Foreground="{DynamicResource GlyphBrush}" Margin="0,0,4,0" />
<TextBlock Text="{Binding RatingText}" Style="{StaticResource GcText}"
FontSize="{DynamicResource FontSizeSmall}" />
</StackPanel>
</DockPanel>
</StackPanel>
</DataTemplate>
<!-- List row: compact, with inline actions. -->
<DataTemplate x:Key="RowTemplate" DataType="{x:Type vm:CollectionCardViewModel}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="90" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="Auto" />
</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}" />
<TextBlock Text="{Binding Description}" Style="{StaticResource GcMutedText}"
TextTrimming="CharacterEllipsis" Margin="0,3,0,0"
ToolTip="{Binding Description}"
Visibility="{Binding HasDescription, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
<StackPanel Grid.Column="2" Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="&#xf000;" Style="{StaticResource GcGlyph}"
Foreground="{DynamicResource GlyphBrush}" Margin="0,0,5,0" />
<TextBlock Text="{Binding RatingText}" Style="{StaticResource GcText}" />
</StackPanel>
<TextBlock Grid.Column="3" Text="{Binding GameCountText}" Style="{StaticResource GcMutedText}"
VerticalAlignment="Center" />
<StackPanel Grid.Column="4" Orientation="Horizontal" VerticalAlignment="Center">
<Button Style="{StaticResource GcIconButton}" Content="&#xec55;"
Command="{Binding EditCommand}"
ToolTip="{DynamicResource LOCGameCollections_Edit}"
AutomationProperties.Name="{DynamicResource LOCGameCollections_Edit}" />
<Button Style="{StaticResource GcIconButton}" Content="&#xec53;" Margin="5,0,0,0"
Command="{Binding DeleteCommand}"
ToolTip="{DynamicResource LOCGameCollections_Delete}"
AutomationProperties.Name="{DynamicResource LOCGameCollections_Delete}" />
</StackPanel>
</Grid>
</DataTemplate>
</ResourceDictionary>
</UserControl.Resources>
<DockPanel Margin="20,15,20,0">
<!-- Header -->
<Grid DockPanel.Dock="Top" Margin="0,0,0,15">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="{DynamicResource LOCGameCollections_PageTitle}" Style="{StaticResource GcPageTitleText}" />
<TextBlock Text="{Binding CountText}" Style="{StaticResource GcMutedText}"
VerticalAlignment="Center" Margin="12,4,0,0" />
</StackPanel>
<local:SearchBox x:Name="SearchInput" Grid.Column="2" Width="260" Height="32" Margin="10,0,0,0"
Text="{Binding SearchText}"
Placeholder="{DynamicResource LOCGameCollections_SearchCollections}" />
<Button Grid.Column="3" Style="{StaticResource GcIconButton}" Height="32" Margin="10,0,0,0"
Content="{Binding ViewModeToggleGlyph}"
Command="{Binding ToggleViewModeCommand}"
ToolTip="{Binding ViewModeToggleTooltip}"
AutomationProperties.Name="{Binding ViewModeToggleTooltip}" />
<Button Grid.Column="4" Style="{StaticResource GcButton}" Height="32" Margin="10,0,0,0"
Command="{Binding CreateCollectionCommand}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="&#xefc2;" Style="{StaticResource GcGlyph}" Margin="0,0,6,0" />
<TextBlock Text="{DynamicResource LOCGameCollections_CreateCollection}" VerticalAlignment="Center" />
</StackPanel>
</Button>
</Grid>
<Grid>
<!-- Grid view -->
<ListBox x:Name="CardsList"
Style="{StaticResource GcPlainListBox}"
ItemsSource="{Binding CardsView}"
SelectedItem="{Binding SelectedCard}"
IsSynchronizedWithCurrentItem="False"
ItemTemplate="{StaticResource CardTemplate}"
ItemContainerStyle="{StaticResource CardContainerStyle}"
ScrollViewer.CanContentScroll="False"
KeyDown="Collections_KeyDown"
AutomationProperties.Name="{DynamicResource LOCGameCollections_PageTitle}"
Visibility="{Binding IsGridView, Converter={StaticResource BoolToVisibility}}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" Margin="0,0,0,10" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
<!-- List view -->
<ListBox x:Name="RowsList"
Style="{StaticResource GcPlainListBox}"
ItemsSource="{Binding CardsView}"
SelectedItem="{Binding SelectedCard}"
IsSynchronizedWithCurrentItem="False"
ItemTemplate="{StaticResource RowTemplate}"
ItemContainerStyle="{StaticResource RowContainerStyle}"
HorizontalContentAlignment="Stretch"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.ScrollUnit="Pixel"
KeyDown="Collections_KeyDown"
AutomationProperties.Name="{DynamicResource LOCGameCollections_PageTitle}"
Visibility="{Binding IsListView, Converter={StaticResource BoolToVisibility}}" />
<!-- Empty state: no collections at all -->
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" MaxWidth="420"
Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}">
<TextBlock Text="&#xef36;" Style="{StaticResource GcGlyph}" FontSize="64"
Foreground="{DynamicResource GlyphBrush}" Opacity="0.6"
HorizontalAlignment="Center" />
<TextBlock Text="{DynamicResource LOCGameCollections_EmptyTitle}" Style="{StaticResource GcText}"
FontSize="{DynamicResource FontSizeLarge}" HorizontalAlignment="Center" Margin="0,12,0,0" />
<TextBlock Text="{DynamicResource LOCGameCollections_EmptyDescription}" Style="{StaticResource GcMutedText}"
TextWrapping="Wrap" TextAlignment="Center" Margin="0,8,0,0" />
<Button Style="{StaticResource GcButton}" HorizontalAlignment="Center" Margin="0,16,0,0"
Command="{Binding CreateCollectionCommand}"
Content="{DynamicResource LOCGameCollections_CreateCollection}" />
</StackPanel>
<!-- Search matched nothing -->
<TextBlock Text="{Binding NoResultsText}" Style="{StaticResource GcMutedText}"
HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,40,0,0"
Visibility="{Binding HasNoResults, Converter={StaticResource BoolToVisibility}}" />
</Grid>
</DockPanel>
</UserControl>
@@ -0,0 +1,57 @@
using GameCollections.ViewModels;
using System.Windows.Controls;
using System.Windows.Input;
namespace GameCollections.Views
{
public partial class CollectionsHomeView : UserControl
{
public CollectionsHomeView()
{
InitializeComponent();
}
// Grid cards open on a single click, like tiles; buttons and the context menu handle their own clicks.
private void CardItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (sender is ListBoxItem item && item.IsMouseOver && item.DataContext is CollectionCardViewModel card)
{
card.OpenCommand.Execute(null);
e.Handled = true;
}
}
private void RowItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (sender is ListBoxItem item && item.DataContext is CollectionCardViewModel card)
{
card.OpenCommand.Execute(null);
e.Handled = true;
}
}
private void Collections_KeyDown(object sender, KeyEventArgs e)
{
if (!(sender is ListBox list) || !(list.SelectedItem is CollectionCardViewModel card))
{
return;
}
switch (e.Key)
{
case Key.Enter:
card.OpenCommand.Execute(null);
e.Handled = true;
break;
case Key.F2:
card.EditCommand.Execute(null);
e.Handled = true;
break;
case Key.Delete:
card.DeleteCommand.Execute(null);
e.Handled = true;
break;
}
}
}
}
@@ -0,0 +1,16 @@
<UserControl x:Class="GameCollections.Views.CollectionsRootView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GameCollections.Views"
xmlns:vm="clr-namespace:GameCollections.ViewModels">
<!-- Hosts whichever page is current: the collections overview or a single collection. -->
<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:CollectionsHomeViewModel}">
<local:CollectionsHomeView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:CollectionDetailsViewModel}">
<local:CollectionDetailsView />
</DataTemplate>
</UserControl.Resources>
<ContentControl Content="{Binding CurrentPage}" Focusable="False" />
</UserControl>
@@ -0,0 +1,12 @@
using System.Windows.Controls;
namespace GameCollections.Views
{
public partial class CollectionsRootView : UserControl
{
public CollectionsRootView()
{
InitializeComponent();
}
}
}
@@ -0,0 +1,45 @@
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace GameCollections.Views
{
/// <summary>
/// Visible for non-null, non-empty values; Collapsed otherwise. <see cref="Invert"/> flips the result.
/// </summary>
public class HasValueToVisibilityConverter : IValueConverter
{
public bool Invert { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var hasValue = value is string text ? !string.IsNullOrWhiteSpace(text) : value != null;
return hasValue != Invert ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
/// <summary>
/// Visible for true; Collapsed otherwise. <see cref="Invert"/> flips the result.
/// </summary>
public class BoolToVisibilityConverter : IValueConverter
{
public bool Invert { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var flag = value is bool b && b;
return flag != Invert ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
@@ -0,0 +1,94 @@
<UserControl x:Class="GameCollections.Views.EditCollectionView"
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:EditCollectionViewModel}"
d:DesignHeight="440" d:DesignWidth="620">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/GameCollections;component/Views/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<DockPanel Margin="20">
<!-- Footer -->
<DockPanel DockPanel.Dock="Bottom" Margin="0,15,0,0">
<Button DockPanel.Dock="Right" MinWidth="90" Margin="8,0,0,0"
IsCancel="True"
Command="{Binding CancelCommand}"
Content="{DynamicResource LOCGameCollections_Cancel}" />
<Button DockPanel.Dock="Right" MinWidth="90"
IsDefault="True"
Command="{Binding SaveCommand}"
IsEnabled="{Binding CanSave}"
Content="{DynamicResource LOCGameCollections_Save}" />
<TextBlock Text="{Binding ErrorMessage}" Style="{StaticResource GcErrorText}"
VerticalAlignment="Center" Margin="0,0,10,0" />
</DockPanel>
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<!-- Poster -->
<StackPanel Width="160">
<local:PosterImage Width="160" Height="240" GlyphSize="56" Source="{Binding PosterPreview}" />
<TextBlock Text="{Binding PosterHint}" Style="{StaticResource GcMutedText}"
FontSize="{DynamicResource FontSizeSmall}"
TextWrapping="Wrap" Margin="0,6,0,0" />
<Button Style="{StaticResource GcButton}" Margin="0,8,0,0" HorizontalAlignment="Stretch"
Command="{Binding BrowsePosterCommand}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="&#xef4b;" Style="{StaticResource GcGlyph}" Margin="0,0,6,0" />
<TextBlock Text="{DynamicResource LOCGameCollections_ChoosePoster}" VerticalAlignment="Center" />
</StackPanel>
</Button>
<Button Style="{StaticResource GcButton}" Margin="0,6,0,0" HorizontalAlignment="Stretch"
Command="{Binding RemovePosterCommand}"
IsEnabled="{Binding HasCustomPoster}"
Content="{DynamicResource LOCGameCollections_RemovePoster}" />
</StackPanel>
<!-- Fields -->
<StackPanel Grid.Column="1" Margin="20,0,0,0">
<TextBlock Text="{DynamicResource LOCGameCollections_FieldTitle}" Style="{StaticResource GcText}" Margin="0,0,0,5" />
<TextBox x:Name="TitleInput"
Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}"
MaxLength="{Binding MaxTitleLength, Mode=OneTime}"
AutomationProperties.Name="{DynamicResource LOCGameCollections_FieldTitle}" />
<TextBlock Text="{Binding TitleError}" Style="{StaticResource GcErrorText}" Margin="0,4,0,0"
Visibility="{Binding TitleError, Converter={StaticResource HasValueToVisibility}}" />
<TextBlock Text="{DynamicResource LOCGameCollections_FieldDescription}" Style="{StaticResource GcSectionLabel}" />
<TextBox Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}"
MaxLength="{Binding MaxDescriptionLength, Mode=OneTime}"
AcceptsReturn="True" TextWrapping="Wrap"
Height="110" VerticalContentAlignment="Top"
VerticalScrollBarVisibility="Auto"
AutomationProperties.Name="{DynamicResource LOCGameCollections_FieldDescription}" />
<TextBlock Text="{DynamicResource LOCGameCollections_FieldRating}" Style="{StaticResource GcSectionLabel}" />
<DockPanel>
<TextBlock DockPanel.Dock="Right" Text="{Binding RatingText}" Style="{StaticResource GcText}"
MinWidth="50" TextAlignment="Right" VerticalAlignment="Center" Margin="10,0,0,0" />
<Slider Minimum="0" Maximum="10"
TickFrequency="0.5" IsSnapToTickEnabled="True" TickPlacement="BottomRight"
SmallChange="0.5" LargeChange="1"
VerticalAlignment="Center"
Value="{Binding Rating}"
AutomationProperties.Name="{DynamicResource LOCGameCollections_FieldRating}" />
</DockPanel>
</StackPanel>
</Grid>
</ScrollViewer>
</DockPanel>
</UserControl>
@@ -0,0 +1,21 @@
using System;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
namespace GameCollections.Views
{
public partial class EditCollectionView : UserControl
{
public EditCollectionView()
{
InitializeComponent();
Loaded += (s, e) => Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
{
TitleInput.Focus();
Keyboard.Focus(TitleInput);
TitleInput.SelectAll();
}));
}
}
}
@@ -0,0 +1,22 @@
<UserControl x:Class="GameCollections.Views.PosterImage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Root"
Focusable="False">
<!-- Poster with a themed placeholder that shows while no image is available. -->
<Grid>
<Border CornerRadius="{Binding CornerRadius, ElementName=Root}"
Background="{DynamicResource NormalBrush}">
<TextBlock Text="{Binding Glyph, ElementName=Root}"
FontFamily="{DynamicResource FontIcoFont}"
FontSize="{Binding GlyphSize, ElementName=Root}"
Foreground="{DynamicResource GlyphBrush}"
Opacity="0.55"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<!-- Background is set from code to an ImageBrush so the image follows the rounded corners. -->
<Border x:Name="ImageBorder"
CornerRadius="{Binding CornerRadius, ElementName=Root}"
RenderOptions.BitmapScalingMode="HighQuality" />
</Grid>
</UserControl>
@@ -0,0 +1,61 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace GameCollections.Views
{
public partial class PosterImage : UserControl
{
public const string FolderGlyph = "\uef36";
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
nameof(Source), typeof(ImageSource), typeof(PosterImage), new PropertyMetadata(null, OnSourceChanged));
public static readonly DependencyProperty GlyphProperty = DependencyProperty.Register(
nameof(Glyph), typeof(string), typeof(PosterImage), new PropertyMetadata(FolderGlyph));
public static readonly DependencyProperty GlyphSizeProperty = DependencyProperty.Register(
nameof(GlyphSize), typeof(double), typeof(PosterImage), new PropertyMetadata(40.0));
public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(
nameof(CornerRadius), typeof(CornerRadius), typeof(PosterImage), new PropertyMetadata(new CornerRadius(4)));
public ImageSource Source
{
get => (ImageSource)GetValue(SourceProperty);
set => SetValue(SourceProperty, value);
}
public string Glyph
{
get => (string)GetValue(GlyphProperty);
set => SetValue(GlyphProperty, value);
}
public double GlyphSize
{
get => (double)GetValue(GlyphSizeProperty);
set => SetValue(GlyphSizeProperty, value);
}
public CornerRadius CornerRadius
{
get => (CornerRadius)GetValue(CornerRadiusProperty);
set => SetValue(CornerRadiusProperty, value);
}
public PosterImage()
{
InitializeComponent();
}
private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (PosterImage)d;
var source = e.NewValue as ImageSource;
control.ImageBorder.Background = source == null
? null
: new ImageBrush(source) { Stretch = Stretch.UniformToFill };
}
}
}
@@ -0,0 +1,35 @@
<UserControl x:Class="GameCollections.Views.SearchBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Root"
Focusable="False">
<UserControl.Resources>
<ResourceDictionary Source="/GameCollections;component/Views/Styles.xaml" />
</UserControl.Resources>
<Grid>
<TextBox x:Name="InputBox"
Padding="26,0,26,0"
VerticalContentAlignment="Center"
Text="{Binding Text, ElementName=Root, UpdateSourceTrigger=PropertyChanged}"
AutomationProperties.Name="{Binding Placeholder, ElementName=Root}" />
<TextBlock Text="&#xec82;" Style="{StaticResource GcGlyph}"
Foreground="{DynamicResource TextBrushDarker}"
HorizontalAlignment="Left" Margin="8,0,0,0"
IsHitTestVisible="False" />
<TextBlock Text="{Binding Placeholder, ElementName=Root}"
Style="{StaticResource GcMutedText}"
VerticalAlignment="Center" Margin="28,0,28,0"
TextTrimming="CharacterEllipsis"
IsHitTestVisible="False"
Visibility="{Binding Text, ElementName=Root, Converter={StaticResource NoValueToVisibility}}" />
<Button HorizontalAlignment="Right" VerticalAlignment="Center"
Margin="0,0,3,0" Padding="4,2"
Background="Transparent" BorderThickness="0"
Focusable="False" Cursor="Hand"
ToolTip="{DynamicResource LOCGameCollections_ClearSearch}"
Click="ClearButton_Click"
Visibility="{Binding Text, ElementName=Root, Converter={StaticResource HasValueToVisibility}}">
<TextBlock Text="&#xeee4;" Style="{StaticResource GcGlyph}" FontSize="12" />
</Button>
</Grid>
</UserControl>
@@ -0,0 +1,60 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace GameCollections.Views
{
/// <summary>
/// Text box with a search icon, placeholder text and a clear button. Escape clears the text.
/// </summary>
public partial class SearchBox : UserControl
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
nameof(Text), typeof(string), typeof(SearchBox),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public static readonly DependencyProperty PlaceholderProperty = DependencyProperty.Register(
nameof(Placeholder), typeof(string), typeof(SearchBox), new PropertyMetadata(string.Empty));
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public string Placeholder
{
get => (string)GetValue(PlaceholderProperty);
set => SetValue(PlaceholderProperty, value);
}
public SearchBox()
{
InitializeComponent();
InputBox.PreviewKeyDown += InputBox_PreviewKeyDown;
}
public void FocusInput()
{
InputBox.Focus();
Keyboard.Focus(InputBox);
InputBox.SelectAll();
}
private void InputBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
// Only consume Escape when there is something to clear, so dialogs still close on Escape.
if (e.Key == Key.Escape && !string.IsNullOrEmpty(Text))
{
Text = string.Empty;
e.Handled = true;
}
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
Text = string.Empty;
FocusInput();
}
}
}
+67
View File
@@ -0,0 +1,67 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GameCollections.Views">
<!--
Shared styles. Brushes, fonts and sizes come from the active Playnite theme through
DynamicResource, so light and dark themes are both followed.
-->
<local:HasValueToVisibilityConverter x:Key="HasValueToVisibility" />
<local:HasValueToVisibilityConverter x:Key="NoValueToVisibility" Invert="True" />
<local:BoolToVisibilityConverter x:Key="BoolToVisibility" />
<local:BoolToVisibilityConverter x:Key="InverseBoolToVisibility" Invert="True" />
<Style x:Key="GcText" TargetType="TextBlock" BasedOn="{StaticResource BaseTextBlockStyle}" />
<Style x:Key="GcMutedText" TargetType="TextBlock" BasedOn="{StaticResource GcText}">
<Setter Property="Foreground" Value="{DynamicResource TextBrushDarker}" />
</Style>
<Style x:Key="GcPageTitleText" TargetType="TextBlock" BasedOn="{StaticResource GcText}">
<Setter Property="FontSize" Value="{DynamicResource FontSizeLargest}" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
</Style>
<Style x:Key="GcItemTitleText" TargetType="TextBlock" BasedOn="{StaticResource GcText}">
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
<Setter Property="TextWrapping" Value="NoWrap" />
</Style>
<Style x:Key="GcSectionLabel" TargetType="TextBlock" BasedOn="{StaticResource GcText}">
<Setter Property="Margin" Value="0,12,0,5" />
</Style>
<Style x:Key="GcErrorText" TargetType="TextBlock" BasedOn="{StaticResource GcText}">
<Setter Property="Foreground" Value="{DynamicResource WarningBrush}" />
<Setter Property="TextWrapping" Value="Wrap" />
</Style>
<Style x:Key="GcGlyph" TargetType="TextBlock">
<Setter Property="FontFamily" Value="{DynamicResource FontIcoFont}" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<!-- Button holding an icon glyph and an optional label. -->
<Style x:Key="GcButton" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Padding" Value="10,5" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style x:Key="GcIconButton" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Padding" Value="8,5" />
<Setter Property="MinWidth" Value="32" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="FontFamily" Value="{DynamicResource FontIcoFont}" />
<Setter Property="FontSize" Value="16" />
</Style>
<!-- ListBox without its own border/background so it blends into the page. -->
<Style x:Key="GcPlainListBox" TargetType="ListBox" BasedOn="{StaticResource {x:Type ListBox}}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Padding" Value="0" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
</Style>
</ResourceDictionary>
+14
View File
@@ -0,0 +1,14 @@
Id: GameCollections_3f6b8d2e-5c41-4a7e-9e0b-6d2f1a8c7b54
Name: Game Collections
Author: X4Lo
Version: 1.0.0
Module: GameCollections.dll
Type: GenericPlugin
Icon: icon.png
Links:
- Name: GitHub
Url: https://github.com/X4Lo/GameCollections
- Name: Issues Tracker
Url: https://github.com/X4Lo/GameCollections/issues
- Name: User Guide
Url: https://github.com/X4Lo/GameCollections/blob/main/docs/user-guide.md
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB