Initial mod dependency work

This commit is contained in:
Joshua Askharoun
2022-03-01 14:14:11 -06:00
parent 65bd5f4e8a
commit 1acf068092
18 changed files with 310 additions and 155 deletions
@@ -1,7 +1,6 @@
using System.Windows;
using System.Windows.Controls;
using OwlCore.AbstractUI.ViewModels;
using OwlCore.AbstractUI.Models;
namespace OwlCore.Wpf.AbstractUI.Controls
{
@@ -16,7 +15,7 @@ namespace OwlCore.Wpf.AbstractUI.Controls
/// Backing property for <see cref="ViewModel"/>.
/// </summary>
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register(nameof(ViewModel), typeof(AbstractUICollectionViewModel), typeof(AbstractUIGroupPresenter), new PropertyMetadata(null, (d, e) => ((AbstractUIGroupPresenter)d).OnViewModelChanged()));
DependencyProperty.Register(nameof(ViewModel), typeof(AbstractUICollectionViewModel), typeof(AbstractUIGroupPresenter), new PropertyMetadata(null));
/// <summary>
/// Backing property for <see cref="TemplateSelector"/>.
@@ -48,62 +47,6 @@ namespace OwlCore.Wpf.AbstractUI.Controls
public AbstractUIGroupPresenter()
{
this.DefaultStyleKey = typeof(AbstractUIGroupPresenter);
AttachEvents();
}
private void AttachEvents()
{
Loaded += OnLoaded;
DataContextChanged += OnDataContextChanged;
}
private void DetachEvents()
{
DataContextChanged -= OnDataContextChanged;
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (_dataContextBeingSet)
return;
_dataContextBeingSet = true;
if (DataContext is AbstractUICollection elementGroup)
ViewModel = new AbstractUICollectionViewModel(elementGroup);
if (DataContext is AbstractUICollectionViewModel elementGroupViewModel)
ViewModel = elementGroupViewModel;
_dataContextBeingSet = false;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
Loaded -= OnLoaded;
Unloaded += OnUnloaded;
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
Unloaded -= OnUnloaded;
DetachEvents();
}
/// <summary>
/// Raised when the <see cref="ViewModel"/> changes.
/// </summary>
public void OnViewModelChanged()
{
if (_dataContextBeingSet)
return;
_dataContextBeingSet = true;
DataContext = ViewModel;
_dataContextBeingSet = false;
}
}
}
@@ -85,6 +85,7 @@
<ControlTemplate TargetType="controls:AbstractUIGroupPresenter">
<ContentControl ContentTemplate="{StaticResource DefaultAbstractUICollectionTemplate}"
Content="{TemplateBinding ViewModel}"
DataContext="{TemplateBinding ViewModel}"
HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
</ControlTemplate>
</Setter.Value>
+61 -16
View File
@@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ZuneModCore.Mods;
@@ -9,20 +10,6 @@ namespace ZuneModCore
{
public abstract class Mod
{
/// <summary>
/// A list of all available mods
/// </summary>
public static readonly IReadOnlyList<Mod> AvailableMods = new List<Mod>
{
new FeaturesOverrideMod(),
new VideoSyncMod(),
new WebservicesMod(),
new BackgroundImageMod(),
new MbidLocatorMod(),
}.AsReadOnly();
public static string ZuneInstallDir { get; set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Zune");
public abstract string Id { get; }
public abstract string Title { get; }
@@ -55,13 +42,71 @@ namespace ZuneModCore
{
get
{
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ZuneModCore", Id);
string dir = Path.Combine(ModManager.CoreStorageDir, Id);
// Create the directory just in case the consumer assumes the folder exists already
Directory.CreateDirectory(dir);
return dir;
}
}
public abstract IReadOnlyList<Type>? DependentMods { get; }
public abstract IReadOnlyList<ModDependency>? DependentMods { get; }
/// <summary>
/// Initializes any missing depedencies.
/// </summary>
public Task InitDependencies() => ForAllDependencies(async mod =>
{
bool isDepApplied = await mod.CheckApplied();
if (!isDepApplied)
await mod.Init();
});
/// <summary>
/// Applies any missing depedencies.
/// </summary>
/// <remarks>
/// Make sure to call <see cref="InitDependencies"/> first.
/// </remarks>
public Task ApplyDependencies() => ForAllDependencies(async mod =>
{
bool isDepApplied = await mod.CheckApplied();
if (!isDepApplied)
await mod.Apply();
});
public Task<bool> CheckApplied() => TrueForAllDependencies(mod => mod.CheckApplied());
private async Task ForAllDependencies(Func<Mod, Task> asyncAction)
{
// Check if there are any dependencies
if (DependentMods == null)
return;
foreach (var dep in DependentMods)
{
var depMod = ModManager.AvailableMods.First(m => m.Id == dep.Id);
if (depMod != null)
await asyncAction(depMod);
}
}
private async Task<bool> TrueForAllDependencies(Func<Mod, Task<bool>> asyncAction)
{
// Check if there are any dependencies
if (DependentMods == null)
return true;
foreach (var dep in DependentMods)
{
var depMod = ModManager.AvailableMods.First(m => m.Id == dep.Id);
if (depMod != null)
if (!await asyncAction(depMod))
return false;
}
return true;
}
public override string ToString() => Title;
}
}
+31
View File
@@ -0,0 +1,31 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace ZuneModCore
{
public class ModDependency
{
public string Id { get; set; }
public ReleaseVersion Version { get; set; }
public ModDependency(string id, ReleaseVersion? version = null)
{
Id = id;
Version = version ?? ModManager.CurrentVersion;
}
/// <summary>
/// DO NOT USE DIRECTLY. This constructor is only for
/// JSON de/serialization.
/// </summary>
[Obsolete]
internal ModDependency() { }
public Task<bool> CheckStatus() => ModManager.CheckStatus(Id);
public override string ToString() => $"{Id} / {Version}";
}
}
+80
View File
@@ -0,0 +1,80 @@
using CommunityToolkit.Diagnostics;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
using ZuneModCore.Mods;
namespace ZuneModCore
{
public static class ModManager
{
/// <summary>
/// A list of all available mods.
/// </summary>
public static readonly IReadOnlyList<Mod> AvailableMods = new List<Mod>
{
new FeaturesOverrideMod(),
new VideoSyncMod(),
new WebservicesMod(),
new BackgroundImageMod(),
new MbidLocatorMod(),
};
public static string ZuneInstallDir { get; set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Zune");
public static readonly ReleaseVersion CurrentVersion = new(2021, 12, 30, 0, Phase.Alpha);
internal static readonly string CoreStorageDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ZuneModCore");
private static readonly string CoreStatusFile = Path.Combine(CoreStorageDir, "ModStatus.json");
/// <summary>
/// Marks the specified mod as applied in the status file.
/// </summary>
internal static Task MarkApplied(string modId) => MarkStatus(modId, true);
/// <summary>
/// Marks the specified mod as reset in the status file.
/// </summary>
internal static Task MarkReset(string modId) => MarkStatus(modId, false);
/// <summary>
/// Sets the status of the specified mod in the status file.
/// </summary>
private static async Task MarkStatus(string modId, bool status)
{
using var stream = File.Open(CoreStatusFile, FileMode.OpenOrCreate);
var model = await JsonSerializer.DeserializeAsync<StatusModel>(stream);
Guard.IsNotNull(model, nameof(model));
bool curStatus = model.InstalledMods.ContainsKey(modId);
if (curStatus && !status)
{
model.InstalledMods.Remove(modId);
}
else if (!curStatus && status)
{
model.InstalledMods.Add(modId, CurrentVersion);
}
await JsonSerializer.SerializeAsync(stream, model);
}
/// <summary>
/// Gets the status of the specified mod from the status file.
/// </summary>
internal static async Task<bool> CheckStatus(string modId)
{
if (!File.Exists(CoreStatusFile))
return false;
using var stream = File.OpenRead(CoreStatusFile);
var model = await JsonSerializer.DeserializeAsync<StatusModel>(stream);
Guard.IsNotNull(model, nameof(model));
return model.InstalledMods.ContainsKey(modId);
}
}
}
+3 -3
View File
@@ -32,7 +32,7 @@ namespace ZuneModCore.Mods
};
}
public override IReadOnlyList<Type>? DependentMods => null;
public override IReadOnlyList<ModDependency>? DependentMods => null;
public override async Task<string?> Apply()
{
@@ -43,7 +43,7 @@ namespace ZuneModCore.Mods
return $"The file '{bgimgInfo.FullName}' does not exist.";
}
FileInfo zsrDllInfo = new(Path.Combine(ZuneInstallDir, "ZuneShellResources.dll"));
FileInfo zsrDllInfo = new(Path.Combine(ModManager.ZuneInstallDir, "ZuneShellResources.dll"));
if (!zsrDllInfo.Exists)
{
return $"The file '{zsrDllInfo.FullName}' does not exist.";
@@ -120,7 +120,7 @@ namespace ZuneModCore.Mods
{
// Copy backup to application folder
File.Copy(Path.Combine(StorageDirectory, "ZuneShellResources.original.dll"),
Path.Combine(ZuneInstallDir, "ZuneShellResources.dll"), true);
Path.Combine(ModManager.ZuneInstallDir, "ZuneShellResources.dll"), true);
return Task.FromResult<string?>(null);
}
+1 -1
View File
@@ -56,7 +56,7 @@ namespace ZuneModCore.Mods
};
}
public override IReadOnlyList<Type>? DependentMods => null;
public override IReadOnlyList<ModDependency>? DependentMods => null;
public override Task Init()
{
+1 -1
View File
@@ -37,7 +37,7 @@ namespace ZuneModCore.Mods
};
}
public override IReadOnlyList<Type>? DependentMods => null;
public override IReadOnlyList<ModDependency>? DependentMods => null;
public override async Task<string?> Apply()
{
+1 -1
View File
@@ -71,6 +71,6 @@ namespace ZuneModCore.Mods
}
}
public override IReadOnlyList<Type>? DependentMods => null;
public override IReadOnlyList<ModDependency>? DependentMods => null;
}
}
+7 -4
View File
@@ -76,7 +76,10 @@ namespace ZuneModCore.Mods
};
}
public override IReadOnlyList<Type>? DependentMods => null;
public override IReadOnlyList<ModDependency>? DependentMods => new List<ModDependency>
{
new(nameof(FeaturesOverrideMod))
};
public override Task Init()
{
@@ -90,7 +93,7 @@ namespace ZuneModCore.Mods
public override async Task<string?> Apply()
{
// Verify that ZuneServices.dll exists
FileInfo zsDllInfo = new(Path.Combine(ZuneInstallDir, "ZuneService.dll"));
FileInfo zsDllInfo = new(Path.Combine(ModManager.ZuneInstallDir, "ZuneService.dll"));
if (!zsDllInfo.Exists)
{
return $"The file '{zsDllInfo.FullName}' does not exist.";
@@ -182,7 +185,7 @@ namespace ZuneModCore.Mods
public override async Task<string?> Reset()
{
string zsDllPath = Path.Combine(ZuneInstallDir, "ZuneService.dll");
string zsDllPath = Path.Combine(ModManager.ZuneInstallDir, "ZuneService.dll");
try
{
// Copy backup to application folder
@@ -258,7 +261,7 @@ namespace ZuneModCore.Mods
}
}
private async Task<string?> Ping(string url)
private static async Task<string?> Ping(string url)
{
try
{
@@ -1,14 +1,13 @@
using CommunityToolkit.Diagnostics;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ZuneModdingHelper
namespace ZuneModCore
{
[JsonConverter(typeof(ReleaseVersionJsonConverter))]
public sealed class ReleaseVersion : ICloneable, IComparable, IComparable<ReleaseVersion?>, IEquatable<ReleaseVersion?>
{
/// <summary>
@@ -481,4 +480,17 @@ namespace ZuneModdingHelper
ReleaseCandidate,
Production
}
internal class ReleaseVersionJsonConverter : JsonConverter<ReleaseVersion>
{
public override ReleaseVersion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return ReleaseVersion.Parse(reader.GetString()!);
}
public override void Write(Utf8JsonWriter writer, ReleaseVersion value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}
}
+20
View File
@@ -0,0 +1,20 @@
using System.Collections.Generic;
namespace ZuneModCore
{
internal class StatusModel
{
/// <summary>
/// The version of ZuneModCore that created this model.
/// </summary>
public ReleaseVersion Version { get; set; }
/// <summary>
/// A list of mods that are currently installed.
/// <para>
/// <c>Key</c> is mod ID and <c>Value</c> is installed version.
/// </para>
/// </summary>
public Dictionary<string, ReleaseVersion> InstalledMods { get; set; }
}
}
+1
View File
@@ -8,6 +8,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Diagnostics" Version="7.1.2" />
<PackageReference Include="Microsoft.Win32.Registry" Version="5.0.0" />
<PackageReference Include="OwlCore" Version="0.0.43" />
<PackageReference Include="System.IO.FileSystem.AccessControl" Version="5.0.0" />
@@ -1,43 +0,0 @@
using MahApps.Metro.Controls;
using OwlCore.AbstractUI.Models;
using OwlCore.AbstractUI.ViewModels;
using OwlCore.Wpf.AbstractUI.Controls;
using System.Windows;
namespace ZuneModdingHelper
{
/// <summary>
/// Interaction logic for AbstractUIGroupDialog.xaml
/// </summary>
public partial class AbstractUIGroupDialog : MetroWindow
{
public AbstractUIGroupDialog(AbstractUICollectionViewModel viewModel)
{
ViewModel = viewModel;
DataContext = ViewModel;
InitializeComponent();
}
public AbstractUIGroupDialog(AbstractUICollection group) : this(new AbstractUICollectionViewModel(group))
{
}
private void OptionsUINextButton_Click(object sender, RoutedEventArgs e) => Finish(true);
private void OptionsUICancelButton_Click(object sender, RoutedEventArgs e) => Finish(false);
private void Finish(bool result)
{
DialogResult = result;
Close();
}
public AbstractUICollectionViewModel ViewModel
{
get => (AbstractUICollectionViewModel)GetValue(ViewModelProperty);
set => SetValue(ViewModelProperty, value);
}
public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(
nameof(ViewModel), typeof(AbstractUICollectionViewModel), typeof(AbstractUIGroupDialog));
}
}
+2 -1
View File
@@ -2,6 +2,7 @@
using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
using ZuneModCore;
namespace ZuneModdingHelper
{
@@ -12,7 +13,7 @@ namespace ZuneModdingHelper
{
public const string Title = "Zune Modding Helper";
public static readonly ReleaseVersion Version = new(2021, 12, 30, 0, Phase.Alpha);
public static readonly ReleaseVersion Version = ModManager.CurrentVersion;
public static readonly string VersionStr = Version.ToString();
public const string DonateLink = "http://josh.askharoun.com/donate";
+8 -9
View File
@@ -41,8 +41,8 @@ namespace ZuneModdingHelper
ThemeManager.Current.ThemeSyncMode = ThemeSyncMode.SyncWithAppMode;
ThemeManager.Current.SyncTheme();
ModList.ItemsSource = Mod.AvailableMods;
ZuneInstallDirBox.Text = Mod.ZuneInstallDir;
ModList.ItemsSource = ModManager.AvailableMods;
ZuneInstallDirBox.Text = ModManager.ZuneInstallDir;
}
private async System.Threading.Tasks.Task RunOnUI(Action action) => await Dispatcher.BeginInvoke(action);
@@ -51,7 +51,7 @@ namespace ZuneModdingHelper
{
// Show a warning if Zune is running
Process[] procs = Process.GetProcessesByName("Zune");
string zuneExePath = Path.Combine(Mod.ZuneInstallDir, "Zune.exe");
string zuneExePath = Path.Combine(ModManager.ZuneInstallDir, "Zune.exe");
if (procs.Length > 0 && procs.Any(p => p.MainModule.FileName == zuneExePath))
{
await this.ShowMessageAsync(
@@ -65,7 +65,7 @@ namespace ZuneModdingHelper
{
var progDialog = await this.ShowProgressAsync("Getting ready...", "Preparing to apply mod", settings: defaultMetroDialogSettings);
Mod mod = (Mod)((FrameworkElement)sender).DataContext;
Mod.ZuneInstallDir = ZuneInstallDirBox.Text;
ModManager.ZuneInstallDir = ZuneInstallDirBox.Text;
progDialog.Maximum = 3;
int numCompleted = 0;
@@ -80,15 +80,14 @@ namespace ZuneModdingHelper
progDialog.SetMessage("Awaiting options...");
if (mod.OptionsUI != null)
{
var optionsDialog = new AbstractUIGroupDialog(mod.OptionsUI);
optionsDialog.Title = optionsDialog.Title + " | " + mod.Title;
var optionsDialog = new OptionsUIDialog(mod);
bool? optionsResult = optionsDialog.ShowDialog();
if (!(optionsResult.HasValue && optionsResult.Value))
{
await progDialog.CloseAsync();
return;
}
mod.OptionsUI = (AbstractUICollection)optionsDialog.ViewModel.Model;
mod.OptionsUI = (AbstractUICollection)optionsDialog.OptionsViewModel.Model;
}
progDialog.SetProgress(++numCompleted);
@@ -122,7 +121,7 @@ namespace ZuneModdingHelper
if (sender is FrameworkElement elem && elem.DataContext is Mod mod)
{
var progDialog = await this.ShowProgressAsync("Getting ready...", "Preparing to reset mod", settings: defaultMetroDialogSettings);
Mod.ZuneInstallDir = ZuneInstallDirBox.Text;
ModManager.ZuneInstallDir = ZuneInstallDirBox.Text;
progDialog.Maximum = 2;
int numCompleted = 0;
@@ -279,7 +278,7 @@ namespace ZuneModdingHelper
CommonOpenFileDialog dialog = new()
{
IsFolderPicker = true,
DefaultDirectory = Mod.ZuneInstallDir
DefaultDirectory = ModManager.ZuneInstallDir
};
CommonFileDialogResult result = dialog.ShowDialog();
if (result == CommonFileDialogResult.Ok)
@@ -1,4 +1,4 @@
<mah:MetroWindow x:Class="ZuneModdingHelper.AbstractUIGroupDialog"
<mah:MetroWindow x:Class="ZuneModdingHelper.OptionsUIDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
@@ -24,8 +24,13 @@
</Grid.RowDefinitions>
<ScrollViewer>
<absui:AbstractUIGroupPresenter x:Name="OptionsUIPresenter" ViewModel="{Binding}"
<StackPanel Orientation="Vertical">
<absui:AbstractUIGroupPresenter x:Name="OptionsUIPresenter" ViewModel="{Binding OptionsViewModel}"
TemplateSelector="{StaticResource GroupTemplateSelector}"/>
<HeaderedItemsControl x:Name="DependenciesPresenter" Header="Dependencies"
ItemsSource="{Binding CurrentMod.DependentMods}"/>
</StackPanel>
</ScrollViewer>
<Border Grid.Row="1" BorderThickness="0,1,0,0" BorderBrush="{StaticResource MahApps.Brushes.Control.Border}">
+57
View File
@@ -0,0 +1,57 @@
using MahApps.Metro.Controls;
using OwlCore.AbstractUI.Models;
using OwlCore.AbstractUI.ViewModels;
using OwlCore.Wpf.AbstractUI.Controls;
using System.Windows;
using ZuneModCore;
namespace ZuneModdingHelper
{
/// <summary>
/// A dialog that displays the options and dependencies for the given <see cref="CurrentMod"/>.
/// </summary>
public partial class OptionsUIDialog : MetroWindow
{
public OptionsUIDialog(Mod mod)
{
InitializeComponent();
DataContext = this;
CurrentMod = mod;
if (CurrentMod.OptionsUI != null)
{
OptionsViewModel = new(CurrentMod.OptionsUI);
}
Title = "Options | " + CurrentMod.Title;
}
private void OptionsUINextButton_Click(object sender, RoutedEventArgs e) => Finish(true);
private void OptionsUICancelButton_Click(object sender, RoutedEventArgs e) => Finish(false);
private void Finish(bool result)
{
DialogResult = result;
Close();
}
public Mod CurrentMod
{
get => (Mod)GetValue(CurrentModProperty);
set => SetValue(CurrentModProperty, value);
}
public static readonly DependencyProperty CurrentModProperty = DependencyProperty.Register(
nameof(CurrentMod), typeof(Mod), typeof(OptionsUIDialog));
public AbstractUICollectionViewModel OptionsViewModel
{
get => (AbstractUICollectionViewModel)GetValue(OptionsViewModelProperty);
set => SetValue(OptionsViewModelProperty, value);
}
public static readonly DependencyProperty OptionsViewModelProperty = DependencyProperty.Register(
nameof(OptionsViewModel), typeof(AbstractUICollectionViewModel), typeof(OptionsUIDialog));
public bool HasOptions => CurrentMod.OptionsUI != null;
}
}