wabbajack/Wabbajack/AppState.cs

420 lines
17 KiB
C#
Raw Normal View History

using Syroot.Windows.IO;
using System;
using ReactiveUI;
2019-07-22 22:17:46 +00:00
using System.Collections.Generic;
using System.Collections.ObjectModel;
2019-07-30 21:45:04 +00:00
using System.ComponentModel;
2019-08-30 23:57:56 +00:00
using System.Diagnostics;
2019-07-22 22:17:46 +00:00
using System.IO;
using System.IO.Compression;
2019-09-26 03:18:36 +00:00
using System.Linq;
using System.Net.Http;
using System.Reactive.Subjects;
using System.Reactive.Disposables;
using System.Reactive.Linq;
2019-07-22 22:17:46 +00:00
using System.Reflection;
using System.Threading;
2019-07-31 03:59:19 +00:00
using System.Windows;
using System.Windows.Input;
2019-09-26 03:18:36 +00:00
using System.Windows.Media.Imaging;
2019-07-22 22:17:46 +00:00
using System.Windows.Threading;
using Wabbajack.Common;
using Wabbajack.Lib.Downloaders;
using Wabbajack.Lib.NexusApi;
using Wabbajack.UI;
using DynamicData;
using DynamicData.Binding;
using System.Reactive;
using System.Text;
using Wabbajack.Lib;
2019-07-22 22:17:46 +00:00
namespace Wabbajack
{
public class AppState : ViewModel, IDataErrorInfo
2019-07-22 22:17:46 +00:00
{
public SlideShow Slideshow { get; }
public readonly FileVersionInfo WabbajackVersionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);
2019-09-14 04:35:42 +00:00
private string _mo2Folder;
2019-10-12 03:12:43 +00:00
public readonly BitmapImage _noneImage = UIUtils.BitmapImageFromResource("Wabbajack.UI.none.jpg");
2019-09-14 04:35:42 +00:00
private readonly Subject<CPUStatus> _statusSubject = new Subject<CPUStatus>();
public ObservableCollectionExtended<CPUStatus> Status { get; } = new ObservableCollectionExtended<CPUStatus>();
2019-09-14 04:35:42 +00:00
private ModList _ModList;
public ModList ModList { get => _ModList; private set => this.RaiseAndSetIfChanged(ref _ModList, value); }
2019-10-12 03:12:43 +00:00
private string _ModListPath;
public string ModListPath { get => _ModListPath; private set => this.RaiseAndSetIfChanged(ref _ModListPath, value); }
private RunMode _Mode;
public RunMode Mode { get => _Mode; private set => this.RaiseAndSetIfChanged(ref _Mode, value); }
private string _ModListName;
public string ModListName { get => _ModListName; set => this.RaiseAndSetIfChanged(ref _ModListName, value); }
2019-10-12 18:42:47 +00:00
private bool _UIReady;
public bool UIReady { get => _UIReady; set => this.RaiseAndSetIfChanged(ref _UIReady, value); }
private string _HTMLReport;
public string HTMLReport { get => _HTMLReport; set => this.RaiseAndSetIfChanged(ref _HTMLReport, value); }
private bool _Installing;
public bool Installing { get => _Installing; set => this.RaiseAndSetIfChanged(ref _Installing, value); }
// Command properties
public IReactiveCommand ChangePathCommand { get; }
public IReactiveCommand ChangeDownloadPathCommand { get; }
2019-10-12 18:42:47 +00:00
public IReactiveCommand BeginCommand { get; }
public IReactiveCommand ShowReportCommand { get; }
public IReactiveCommand OpenReadmeCommand { get; }
public IReactiveCommand OpenModListPropertiesCommand { get; }
public AppState(RunMode mode)
2019-07-30 21:45:04 +00:00
{
2019-10-12 08:02:58 +00:00
if (Path.GetDirectoryName(Assembly.GetEntryAssembly().Location.ToLower()) == KnownFolders.Downloads.Path.ToLower())
2019-09-14 04:35:42 +00:00
{
MessageBox.Show(
"Wabbajack is running inside your Downloads folder. This folder is often highly monitored by antivirus software and these can often " +
2019-10-12 08:02:58 +00:00
"conflict with the operations Wabbajack needs to perform. Please move this executable outside of your Downloads folder and then restart the app.",
"Cannot run inside Downloads",
2019-09-14 04:35:42 +00:00
MessageBoxButton.OK,
MessageBoxImage.Error);
Environment.Exit(1);
}
Mode = mode;
// Define commands
this.ChangePathCommand = ReactiveCommand.Create(ExecuteChangePath);
this.ChangeDownloadPathCommand = ReactiveCommand.Create(ExecuteChangeDownloadPath);
this.ShowReportCommand = ReactiveCommand.Create(ShowReport);
this.OpenModListPropertiesCommand = ReactiveCommand.Create(
execute: OpenModListProperties,
canExecute: this.WhenAny(x => x.UIReady)
.ObserveOnGuiThread());
this.OpenReadmeCommand = ReactiveCommand.Create(
execute: this.OpenReadmeWindow,
2019-10-13 20:14:11 +00:00
canExecute: this.WhenAny(x => x.ModList)
.Select(modList => !string.IsNullOrEmpty(modList?.Readme))
2019-10-12 18:42:47 +00:00
.ObserveOnGuiThread());
this.BeginCommand = ReactiveCommand.Create(
execute: this.ExecuteBegin,
canExecute: this.WhenAny(x => x.UIReady)
.ObserveOnGuiThread());
this.Slideshow = new SlideShow(this);
2019-10-12 03:12:43 +00:00
// Initialize work queue
WorkQueue.Init(
report_function: (id, msg, progress) => this._statusSubject.OnNext(new CPUStatus() { ID = id, Msg = msg, Progress = progress }),
report_queue_size: (max, current) => this.SetQueueSize(max, current));
// Compile progress updates and populate ObservableCollection
this._statusSubject
.ObserveOn(RxApp.TaskpoolScheduler)
.ToObservableChangeSet(x => x.ID)
.Batch(TimeSpan.FromMilliseconds(250))
.EnsureUniqueChanges()
.ObserveOn(RxApp.MainThreadScheduler)
.Sort(SortExpressionComparer<CPUStatus>.Ascending(s => s.ID), SortOptimisations.ComparesImmutableValuesOnly)
.Bind(this.Status)
.Subscribe()
.DisposeWith(this.CompositeDisposable);
2019-07-30 21:45:04 +00:00
}
public ObservableCollection<string> Log { get; } = new ObservableCollection<string>();
2019-07-22 22:17:46 +00:00
private string _Location;
public string Location { get => _Location; set => this.RaiseAndSetIfChanged(ref _Location, value); }
2019-07-31 03:59:19 +00:00
private string _LocationLabel;
public string LocationLabel { get => _LocationLabel; set => this.RaiseAndSetIfChanged(ref _LocationLabel, value); }
private string _DownloadLocation;
public string DownloadLocation { get => _DownloadLocation; set => this.RaiseAndSetIfChanged(ref _DownloadLocation, value); }
2019-10-10 12:16:14 +00:00
private int _queueProgress;
public int QueueProgress { get => _queueProgress; set => this.RaiseAndSetIfChanged(ref _queueProgress, value); }
2019-07-22 22:17:46 +00:00
2019-09-14 04:35:42 +00:00
public string LogFile { get; }
2019-07-22 22:17:46 +00:00
2019-10-09 09:22:03 +00:00
private void ExecuteChangePath()
{
switch (this.Mode)
2019-10-09 09:22:03 +00:00
{
case RunMode.Compile:
Location = UIUtils.ShowFolderSelectionDialog("Select Your MO2 profile directory");
break;
case RunMode.Install:
var folder = UIUtils.ShowFolderSelectionDialog("Select Installation directory");
if (folder == null) return;
Location = folder;
if (DownloadLocation == null)
{
DownloadLocation = Path.Combine(Location, "downloads");
}
break;
default:
throw new NotImplementedException();
2019-10-09 09:22:03 +00:00
}
}
private void ExecuteChangeDownloadPath()
{
var folder = UIUtils.ShowFolderSelectionDialog("Select a location for MO2 downloads");
if (folder != null) DownloadLocation = folder;
}
2019-09-26 03:18:36 +00:00
2019-10-09 09:22:03 +00:00
private void ShowReport()
{
var file = Path.GetTempFileName() + ".html";
File.WriteAllText(file, HTMLReport);
Process.Start(file);
}
private ModlistPropertiesWindow modlistPropertiesWindow;
2019-10-11 08:53:12 +00:00
public string newImagePath;
2019-10-11 12:57:42 +00:00
public string readmePath;
2019-10-09 09:22:03 +00:00
public bool ChangedProperties;
private void OpenModListProperties()
{
if (UIReady)
{
if (modlistPropertiesWindow == null)
{
modlistPropertiesWindow = new ModlistPropertiesWindow(this);
newImagePath = null;
ChangedProperties = false;
}
if(!modlistPropertiesWindow.IsClosed)
modlistPropertiesWindow.Show();
else
{
modlistPropertiesWindow = null;
OpenModListProperties();
}
2019-10-09 09:22:03 +00:00
}
2019-10-11 12:57:42 +00:00
}
private void OpenReadmeWindow()
{
2019-10-13 20:14:11 +00:00
if (string.IsNullOrEmpty(this.ModList.Readme)) return;
2019-10-12 03:12:43 +00:00
using (var fs = new FileStream(this.ModListPath, FileMode.Open, FileAccess.Read, FileShare.Read))
2019-10-11 13:06:56 +00:00
using (var ar = new ZipArchive(fs, ZipArchiveMode.Read))
using (var ms = new MemoryStream())
2019-10-11 12:57:42 +00:00
{
var entry = ar.GetEntry(this.ModList.Readme);
2019-10-11 13:06:56 +00:00
using (var e = entry.Open())
{
2019-10-11 13:06:56 +00:00
e.CopyTo(ms);
}
2019-10-11 13:06:56 +00:00
ms.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(ms))
2019-10-11 12:57:42 +00:00
{
var viewer = new TextViewer(reader.ReadToEnd(), this.ModListName);
viewer.Show();
2019-10-11 12:57:42 +00:00
}
}
}
2019-09-26 03:18:36 +00:00
public string Error => "Error";
2019-09-14 04:35:42 +00:00
public string this[string columnName] => Validate(columnName);
private string Validate(string columnName)
{
string validationMessage = null;
switch (columnName)
{
case "Location":
if (Location == null)
{
validationMessage = null;
}
2019-10-11 08:53:12 +00:00
else switch (Mode)
{
case RunMode.Compile when Location != null && Directory.Exists(Location) && File.Exists(Path.Combine(Location, "modlist.txt")):
2019-10-11 08:53:12 +00:00
Location = Path.Combine(Location, "modlist.txt");
validationMessage = null;
ConfigureForBuild();
break;
case RunMode.Install when Location != null && Directory.Exists(Location) && !Directory.EnumerateFileSystemEntries(Location).Any():
2019-10-11 08:53:12 +00:00
validationMessage = null;
break;
case RunMode.Install when Location != null && Directory.Exists(Location) && Directory.EnumerateFileSystemEntries(Location).Any():
2019-10-11 08:53:12 +00:00
validationMessage = "You have selected a non-empty directory. Installing the modlist here might result in a broken install!";
break;
default:
validationMessage = "Invalid Mod Organizer profile directory";
break;
}
break;
}
return validationMessage;
2019-07-22 22:17:46 +00:00
}
public void LogMsg(string msg)
{
Application.Current.Dispatcher.Invoke(() => Log.Add(msg));
2019-07-22 22:17:46 +00:00
}
2019-08-02 23:04:04 +00:00
public void SetQueueSize(int max, int current)
{
if (max == 0)
max = 1;
2019-08-02 23:04:04 +00:00
var total = current * 100 / max;
QueueProgress = total;
}
2019-07-31 03:59:19 +00:00
private void ConfigureForBuild()
{
var profile_folder = Path.GetDirectoryName(Location);
var mo2folder = Path.GetDirectoryName(Path.GetDirectoryName(profile_folder));
if (!File.Exists(Path.Combine(mo2folder, "ModOrganizer.exe")))
LogMsg($"Error! No ModOrganizer2.exe found in {mo2folder}");
var profile_name = Path.GetFileName(profile_folder);
2019-10-12 03:12:43 +00:00
this.ModListName = profile_name;
this.Mode = RunMode.Compile;
2019-09-26 22:32:15 +00:00
var tmp_compiler = new Compiler(mo2folder);
DownloadLocation = tmp_compiler.MO2DownloadsFolder;
2019-07-31 03:59:19 +00:00
_mo2Folder = mo2folder;
}
2019-10-09 09:22:03 +00:00
internal void ConfigureForInstall(string source, ModList modlist)
2019-08-30 23:57:56 +00:00
{
this.ModList = modlist;
2019-10-12 03:12:43 +00:00
this.ModListPath = source;
this.Mode = RunMode.Install;
ModListName = this.ModList.Name;
HTMLReport = this.ModList.ReportHTML;
2019-10-09 09:22:03 +00:00
Location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var currentWJVersion = new Version(WabbajackVersionInfo.FileVersion);
var modlistWJVersion = new Version(modlist.WabbajackVersion.FileVersion);
if (currentWJVersion > modlistWJVersion)
{
MessageBox.Show(
"The selected Modlist was build with an earlier version of Wabbajack. " +
$"Current Version: {WabbajackVersionInfo.FileVersion}, " +
$"Version used to build the Modlist: {modlist.WabbajackVersion.FileVersion}",
"Information",
MessageBoxButton.OK);
}
else if(currentWJVersion < modlistWJVersion)
{
MessageBox.Show(
"The selected Modlist was build with a newer version of Wabbajack. " +
$"Current Version: {WabbajackVersionInfo.FileVersion}, " +
$"Version used to build the Modlist: {modlist.WabbajackVersion.FileVersion}",
"Information",
MessageBoxButton.OK);
}
this.Slideshow.SlideShowElements = modlist.Archives
.Select(m => m.State)
.OfType<NexusDownloader.State>()
.Select(m =>
new Slide(NexusApiUtils.FixupSummary(m.ModName),m.ModID,
NexusApiUtils.FixupSummary(m.Summary), NexusApiUtils.FixupSummary(m.Author),
m.Adult,m.NexusURL,m.SlideShowPic)).ToList();
2019-10-09 09:22:03 +00:00
this.Slideshow.PreloadSlideShow();
2019-08-30 23:57:56 +00:00
}
2019-07-31 03:59:19 +00:00
private void ExecuteBegin()
{
UIReady = false;
if (this.Mode == RunMode.Install)
2019-07-31 03:59:19 +00:00
{
this.Installing = true;
2019-10-12 03:12:43 +00:00
var installer = new Installer(this.ModListPath, this.ModList, Location)
2019-10-07 11:48:39 +00:00
{
DownloadFolder = DownloadLocation
};
2019-07-31 03:59:19 +00:00
var th = new Thread(() =>
{
UIReady = false;
2019-07-31 03:59:19 +00:00
try
{
installer.Install();
}
catch (Exception ex)
{
while (ex.InnerException != null) ex = ex.InnerException;
LogMsg(ex.StackTrace);
2019-08-22 23:29:44 +00:00
LogMsg(ex.ToString());
LogMsg($"{ex.Message} - Can't continue");
2019-07-31 03:59:19 +00:00
}
finally
{
UIReady = true;
this.Installing = false;
}
2019-10-07 11:48:39 +00:00
})
{
Priority = ThreadPriority.BelowNormal
};
2019-07-31 03:59:19 +00:00
th.Start();
}
else if (_mo2Folder != null)
2019-07-31 03:59:19 +00:00
{
2019-10-07 11:48:39 +00:00
var compiler = new Compiler(_mo2Folder)
{
MO2Profile = ModListName,
2019-10-13 22:08:50 +00:00
ModListName = ChangedProperties ? this.Slideshow.ModName : null,
ModListAuthor = ChangedProperties ? this.Slideshow.AuthorName : null,
ModListDescription = ChangedProperties ? this.Slideshow.Summary : null,
2019-10-11 12:57:42 +00:00
ModListImage = ChangedProperties ? newImagePath : null,
2019-10-14 01:15:41 +00:00
ModListWebsite = ChangedProperties ? this.Slideshow.NexusSiteURL : null,
ModListReadme = ChangedProperties ? readmePath : null,
WabbajackVersionInfo = WabbajackVersionInfo
2019-10-07 11:48:39 +00:00
};
2019-07-31 03:59:19 +00:00
var th = new Thread(() =>
{
UIReady = false;
try
{
compiler.Compile();
2019-08-30 23:57:56 +00:00
if (compiler.ModList != null && compiler.ModList.ReportHTML != null)
HTMLReport = compiler.ModList.ReportHTML;
}
catch (Exception ex)
{
while (ex.InnerException != null) ex = ex.InnerException;
LogMsg(ex.StackTrace);
2019-08-22 23:29:44 +00:00
LogMsg(ex.ToString());
LogMsg($"{ex.Message} - Can't continue");
}
finally
{
UIReady = true;
}
2019-10-07 11:48:39 +00:00
})
{
Priority = ThreadPriority.BelowNormal
};
2019-07-31 03:59:19 +00:00
th.Start();
}
else
{
Utils.Log("Cannot compile modlist: no valid Mod Organizer profile directory selected.");
UIReady = true;
}
2019-07-31 03:59:19 +00:00
}
}
2019-09-14 04:35:42 +00:00
public class CPUStatus
{
public int Progress { get; internal set; }
public string Msg { get; internal set; }
public int ID { get; internal set; }
}
2019-07-22 22:17:46 +00:00
}