Skip to content

Commit

Permalink
refactor: app class
Browse files Browse the repository at this point in the history
  • Loading branch information
DorielRivalet committed May 13, 2023
1 parent 99dbef8 commit 65e465a
Show file tree
Hide file tree
Showing 16 changed files with 242 additions and 132 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
# Click-Once directory and Clowd.Squirrel
publish/

# Publish Web Output
Expand Down
164 changes: 163 additions & 1 deletion MHFZ_Overlay/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,173 @@
using System.Windows;
using Squirrel;
using System.Windows;
using NLog;
using MHFZ_Overlay.Core.Class.Log;
using MHFZ_Overlay.Core.Class.IO;
using Microsoft.Extensions.Logging;
using System.Configuration;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Threading.Tasks;
using System;

// TODO: all of this needs testing
namespace MHFZ_Overlay
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

/// <summary>
/// The current program version. TODO: put in env var
/// </summary>
public const string CurrentProgramVersion = "0.22.0";

protected override void OnStartup(StartupEventArgs e)
{
logger.Info("Started WPF application");
logger.Trace("Call stack: {0}", new StackTrace().ToString());
logger.Debug("OS: {0}, is64BitOS: {1}, is64BitProcess: {2}, CLR version: {3}", Environment.OSVersion, Environment.Is64BitOperatingSystem, Environment.Is64BitProcess, Environment.Version);

// run Squirrel first, as the app may exit after these run
SquirrelAwareApp.HandleEvents(
onInitialInstall: OnAppInstall,
onAppUninstall: OnAppUninstall,
onEveryRun: OnAppRun,
onAppUpdate: OnAppUpdate);

// ... other app init code after ...
RestoreSettings();
Settings.Default.Reload();
logger.Info("Reloaded default settings");

base.OnStartup(e);
}

// https://github.com/Squirrel/Squirrel.Windows/issues/198#issuecomment-299262613
// Indeed you can use the methods below to backup your settings,
// typically just after your update has completed,
// so just after your call to await mgr.UpdateApp();
// You want to restore them at the very beginning of your program,
// like just after Squirrel's event handler registration.
// Don't try doing a restore from the onAppUpdate it won't work.
// By the look of it onAppUpdate is executing from the older app process
// as it would not get access to the newer app data folder.

/// <summary>
/// Make a backup of our settings.
/// Used to persist settings across updates.
/// </summary>
private static void BackupSettings()
{
string settingsFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
string destination = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\..\\last.config";
FileManager.CopyFileToDestination(settingsFile, destination, true, "Backed up settings", true);
}

/// <summary>
/// Restore our settings backup if any.
/// Used to persist settings across updates.
/// </summary>
private static void RestoreSettings()
{
//Restore settings after application update
string destFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
string sourceFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\..\\last.config";
var restorationMessage = "Restored settings";
logger.Info("Restore our settings backup if any. Destination: {0}. Source: {1}", destFile, sourceFile);
FileManager.RestoreFileFromSourceToDestination(destFile, sourceFile, restorationMessage);
}

/// <summary>
/// Called when [application install].
/// </summary>
/// <param name="version">The version.</param>
/// <param name="tools">The tools.</param>
private static void OnAppInstall(SemanticVersion version, IAppTools tools)
{
MessageBox.Show("【MHF-Z】Overlay is now installed. Creating a shortcut.", "MHF-Z Overlay Installation", MessageBoxButton.OK, MessageBoxImage.Information);
tools.CreateShortcutForThisExe(ShortcutLocation.StartMenu | ShortcutLocation.Desktop);
logger.Info("Created overlay shortcut");
}

/// <summary>
/// Called when [application uninstall].
/// </summary>
/// <param name="version">The version.</param>
/// <param name="tools">The tools.</param>
private static void OnAppUninstall(SemanticVersion version, IAppTools tools)
{
MessageBox.Show("【MHF-Z】Overlay has been uninstalled. Removing shortcut.", "MHF-Z Overlay Installation", MessageBoxButton.OK, MessageBoxImage.Information);
tools.RemoveShortcutForThisExe(ShortcutLocation.StartMenu | ShortcutLocation.Desktop);
logger.Info("Removed overlay shortcut");
}

/// <summary>
/// Called when [application run].
/// </summary>
/// <param name="version">The version.</param>
/// <param name="tools">The tools.</param>
/// <param name="firstRun">if set to <c>true</c> [first run].</param>
private static void OnAppRun(SemanticVersion version, IAppTools tools, bool firstRun)
{
tools.SetProcessAppUserModelId();
// show a welcome message when the app is first installed
if (firstRun)
{
MessageBox.Show(
@"【MHF-Z】Overlay is now running! Thanks for installing【MHF-Z】Overlay.
Hotkeys: Shift+F1 (Configuration) | Shift+F5 (Restart) | Shift+F6 (Close)
As an alternative to hotkeys, you can check your system tray options by right-clicking the icon.
Press Alt+Enter if your game resolution changed.
The overlay might take some time to start due to databases.
Happy Hunting!", "MHF-Z Overlay Installation", MessageBoxButton.OK, MessageBoxImage.Information);

logger.Info("Running overlay for first time");
}
}

private void OnAppUpdate(SemanticVersion version, IAppTools tools)
{
logger.Info($"Clowd.Squirrel update process called. {nameof(SemanticVersion)}: {version}");
}

private string programVersion = "";

public static async Task UpdateMyApp()
{
try
{
using var mgr = new GithubUpdateManager(@"https://github.com/DorielRivalet/mhfz-overlay");
var newVersion = await mgr.UpdateApp();
BackupSettings();

// optionally restart the app automatically, or ask the user if/when they want to restart
if (newVersion != null)
{
logger.Info("Overlay has been updated, restarting application");
MessageBox.Show("【MHF-Z】Overlay has been updated, restarting application.", "MHF-Z Overlay Update", MessageBoxButton.OK, MessageBoxImage.Information);
UpdateManager.RestartApp();
}
else
{
logger.Error("No updates available");
MessageBox.Show("No updates available", "MHF-Z Overlay Update", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex)
{
logger.Error(ex);
MessageBox.Show("An error has occurred with the update process, see logs.log for more information", LoggingManager.ERROR_TITLE, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
2 changes: 1 addition & 1 deletion MHFZ_Overlay/ConfigWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -3364,7 +3364,7 @@
<!--https://stackoverflow.com/questions/10238694/example-using-hyperlink-in-wpf-->
<TextBlock ToolTip="View Changelog" Grid.Row="8" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="32"><Hyperlink Foreground="#89b4fa" NavigateUri="https://github.com/DorielRivalet/mhfz-overlay/blob/main/CHANGELOG.md" RequestNavigate="lnkImg_RequestNavigate">View Changelog</Hyperlink></TextBlock>
<TextBlock ToolTip="View Releases Statistics (Put DorielRivalet as GitHub Username and MHFZ_Overlay as Repository Name)" Grid.Row="8" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="32"><Hyperlink Foreground="#89b4fa" NavigateUri="https://somsubhra.github.io/github-release-stats/" RequestNavigate="lnkImg_RequestNavigate">View Releases Statistics</Hyperlink></TextBlock>
<TextBlock ToolTip="Download latest version as 7z file" Grid.Row="8" Grid.Column="2" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="32"><Hyperlink Foreground="#89b4fa" NavigateUri="https://github.com/DorielRivalet/mhfz-overlay/releases/latest/download/Releases.7z" RequestNavigate="lnkImg_RequestNavigate">Get latest version</Hyperlink></TextBlock>
<TextBlock ToolTip="Download latest version as 7z file" Grid.Row="8" Grid.Column="2" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="32"><Hyperlink Foreground="#89b4fa" NavigateUri="https://github.com/DorielRivalet/mhfz-overlay/releases/latest" RequestNavigate="lnkImg_RequestNavigate">Get latest version</Hyperlink></TextBlock>
<TextBlock ToolTip="Total Program Usage Time" Grid.Row="9" Grid.Column="0" Grid.ColumnSpan="3" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="32" Text="{Binding TotalTimeSpent, StringFormat=hh\\:mm\\:ss, Mode=OneTime}"/>

</Grid>
Expand Down
4 changes: 2 additions & 2 deletions MHFZ_Overlay/ConfigWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1166,9 +1166,9 @@ private void DeletexNames_OnClosed()
// TODO: test
private void ExportUserSettings_Click(object sender, RoutedEventArgs e)
{
MainWindow.DataLoader.BackupSettings();
//MainWindow.DataLoader.BackupSettings();

FileManager.SaveSettingsAsJSON();
//FileManager.SaveSettingsAsJSON();
}

private void questLoggingToggle_Check(object sender, RoutedEventArgs e)
Expand Down
3 changes: 3 additions & 0 deletions MHFZ_Overlay/Core/Class/Application/ApplicationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@

namespace MHFZ_Overlay.Core.Class.Application
{
/// <summary>
/// Handles the application's state changes (shutdown, restart, etc.)
/// </summary>
internal class ApplicationManager
{
private static readonly DatabaseManager databaseManager = DatabaseManager.GetInstance();
Expand Down
14 changes: 8 additions & 6 deletions MHFZ_Overlay/Core/Class/DataAccessLayer/DatabaseManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@
// TODO: PascalCase for functions, camelCase for private fields, ALL_CAPS for constants
namespace MHFZ_Overlay
{
// Singleton
/// <summary>
/// Handles the SQLite database, MHFZ_Overlay.sqlite. A singleton.
/// </summary>
internal class DatabaseManager
{
private string _connectionString;
Expand Down Expand Up @@ -9696,7 +9698,7 @@ private void MigrateToSchemaFromVersion(SQLiteConnection conn, int fromVersion)
@"No new schema updates found! Schema version: {0}", fromVersion),
string.Format("MHF-Z Overlay Database Update ({0} to {1})",
previousVersion,
MainWindow.CurrentProgramVersion),
App.CurrentProgramVersion),
MessageBoxButton.OK,
MessageBoxImage.Information);
return;
Expand Down Expand Up @@ -9745,7 +9747,7 @@ private void MigrateToSchemaFromVersion(SQLiteConnection conn, int fromVersion)
MessageBox.Show("Updated database schema, you may proceed.",
string.Format("MHF-Z Overlay Database Update ({0} to {1})",
previousVersion,
MainWindow.CurrentProgramVersion),
App.CurrentProgramVersion),
MessageBoxButton.OK,
MessageBoxImage.Information);
}
Expand All @@ -9770,15 +9772,15 @@ private void UpdateDatabaseSchema(SQLiteConnection connection)
{
int currentUserVersion = GetUserVersion(connection);

if (MainWindow.CurrentProgramVersion.Trim() != previousVersion.Trim() || currentUserVersion == 0)
if (App.CurrentProgramVersion.Trim() != previousVersion.Trim() || currentUserVersion == 0)
{
MessageBoxResult result = MessageBox.Show(
@"A new version of the program has been installed.

Do you want to perform the necessary database updates? A backup of your current MHFZ_Overlay.sqlite file will be done if you accept.

Updating the database structure may take some time, it will transport all of your current data straight to the latest database structure, regardless of the previous database version.",
string.Format("MHF-Z Overlay Database Update ({0} to {1})", previousVersion, MainWindow.CurrentProgramVersion), MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
string.Format("MHF-Z Overlay Database Update ({0} to {1})", previousVersion, App.CurrentProgramVersion), MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
if (result == MessageBoxResult.Yes)
{
// Make a backup of the current SQLite file before updating the schema
Expand Down Expand Up @@ -10426,7 +10428,7 @@ private void WritePreviousVersionToFile()
try
{
if (File.ReadAllText(previousVersionFilePath) == "")
previousVersion = MainWindow.CurrentProgramVersion.Trim();
previousVersion = App.CurrentProgramVersion.Trim();
else
previousVersion = File.ReadAllText(previousVersionFilePath);

Expand Down
11 changes: 7 additions & 4 deletions MHFZ_Overlay/Core/Class/Discord/DiscordManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@

namespace MHFZ_Overlay.Core.Class.Discord
{
/// <summary>
/// Handles the Discord Rich Presence. Should not operate if the user is not enabling it.
/// </summary>
internal class DiscordManager
{

Expand Down Expand Up @@ -184,7 +187,7 @@ private static string GetServerName
/// </summary>
private static RichPresence presenceTemplate = new RichPresence()
{
Details = "【MHF-Z】Overlay " + MainWindow.CurrentProgramVersion,
Details = "【MHF-Z】Overlay " + App.CurrentProgramVersion,
State = "Loading...",
//check img folder
Assets = new Assets()
Expand All @@ -196,7 +199,7 @@ private static string GetServerName
},
Buttons = new DiscordRPC.Button[]
{
new DiscordRPC.Button() {Label = "【MHF-Z】Overlay "+ MainWindow.CurrentProgramVersion, Url = "https://github.com/DorielRivalet/mhfz-overlay"},
new DiscordRPC.Button() {Label = "【MHF-Z】Overlay "+ App.CurrentProgramVersion, Url = "https://github.com/DorielRivalet/mhfz-overlay"},
new DiscordRPC.Button() { Label = "Discord RPC C# Dev Site", Url = "https://lachee.dev/" }
}
};
Expand Down Expand Up @@ -231,7 +234,7 @@ public static void InitializeDiscordRPC()
presenceTemplate.Buttons = new DiscordRPC.Button[] { };
presenceTemplate.Buttons = new DiscordRPC.Button[]
{
new DiscordRPC.Button() {Label = "【MHF-Z】Overlay "+ MainWindow.CurrentProgramVersion, Url = "https://github.com/DorielRivalet/mhfz-overlay"},
new DiscordRPC.Button() {Label = "【MHF-Z】Overlay "+ App.CurrentProgramVersion, Url = "https://github.com/DorielRivalet/mhfz-overlay"},
new DiscordRPC.Button() { Label = "Discord RPC C# Dev Site", Url = "https://lachee.dev/" }
};

Expand All @@ -240,7 +243,7 @@ public static void InitializeDiscordRPC()
presenceTemplate.Buttons = new DiscordRPC.Button[] { };
presenceTemplate.Buttons = new DiscordRPC.Button[]
{
new DiscordRPC.Button() {Label = "【MHF-Z】Overlay "+ MainWindow.CurrentProgramVersion, Url = "https://github.com/DorielRivalet/mhfz-overlay"},
new DiscordRPC.Button() {Label = "【MHF-Z】Overlay "+ App.CurrentProgramVersion, Url = "https://github.com/DorielRivalet/mhfz-overlay"},
new DiscordRPC.Button() { Label = "Join Discord Server", Url = String.Format("https://discord.com/invite/{0}",GetDiscordServerInvite)}
};
}
Expand Down
3 changes: 3 additions & 0 deletions MHFZ_Overlay/Core/Class/IO/FileManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@

namespace MHFZ_Overlay.Core.Class.IO
{
/// <summary>
/// Handles file creation, copying and deletion. Also handles the clipboard (TODO: might want another class for this).
/// </summary>
internal class FileManager
{
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
Expand Down
3 changes: 3 additions & 0 deletions MHFZ_Overlay/Core/Class/Log/LoggingManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@

namespace MHFZ_Overlay.Core.Class.Log
{
/// <summary>
/// Handles logging functionality. Uses NLog.
/// </summary>
internal class LoggingManager
{
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
Expand Down
Loading

0 comments on commit 65e465a

Please sign in to comment.