Skip to content

Commit

Permalink
fix application crash when message box is opened
Browse files Browse the repository at this point in the history
fixes #269
  • Loading branch information
floribe2000 committed Oct 14, 2023
1 parent bd8e507 commit aa083c9
Show file tree
Hide file tree
Showing 6 changed files with 256 additions and 258 deletions.
243 changes: 121 additions & 122 deletions WoWsShipBuilder.Desktop/App.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,164 +25,163 @@
using WoWsShipBuilder.Infrastructure.Localization.Resources;
using WoWsShipBuilder.Infrastructure.Utility;

namespace WoWsShipBuilder.Desktop
namespace WoWsShipBuilder.Desktop;

[SuppressMessage("System.IO.Abstractions", "IO0003", Justification = "This class is never tested.")]
[SuppressMessage("System.IO.Abstractions", "IO0006", Justification = "This class is never tested.")]
public class App : Application
{
[SuppressMessage("System.IO.Abstractions", "IO0003", Justification = "This class is never tested.")]
[SuppressMessage("System.IO.Abstractions", "IO0006", Justification = "This class is never tested.")]
public class App : Application
{
private readonly ILogger<App> logger = NullLogger<App>.Instance;
private readonly IServiceProvider services = default!;
private readonly ILogger<App> logger = NullLogger<App>.Instance;
private readonly IServiceProvider services = default!;

public App()
{
ModeDetector.OverrideModeDetector(new CustomModeDetector());
}
public App()
{
ModeDetector.OverrideModeDetector(new CustomModeDetector());
}

public IServiceProvider Services
public IServiceProvider Services
{
get => services;
init
{
get => services;
init
{
services = value;
logger = services.GetRequiredService<ILogger<App>>();
}
services = value;
logger = services.GetRequiredService<ILogger<App>>();
}
}

public static async Task<MessageBox.MessageBoxResult> ShowUpdateRestartDialog(Window? parent, ILocalizer localizer)
{
return await Dispatcher.UIThread.InvokeAsync(async () => await MessageBox.Show(
parent,
localizer.GetAppLocalization(nameof(Translation.UpdateMessageBox_Description)).Localization,
localizer.GetAppLocalization(nameof(Translation.UpdateMessageBox_Title)).Localization,
MessageBox.MessageBoxButtons.YesNo,
MessageBox.MessageBoxIcon.Question));
}
public static async Task<MessageBox.MessageBoxResult> ShowUpdateRestartDialog(Window? parent, ILocalizer localizer)
{
return await Dispatcher.UIThread.InvokeAsync(async () => await MessageBox.Show(
parent,
localizer.GetAppLocalization(nameof(Translation.UpdateMessageBox_Description)).Localization,
localizer.GetAppLocalization(nameof(Translation.UpdateMessageBox_Title)).Localization,
MessageBox.MessageBoxButtons.YesNo,
MessageBox.MessageBoxIcon.Question));
}

public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}

public override void OnFrameworkInitializationCompleted()
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
Logging.Initialize(Services.GetRequiredService<ILoggerFactory>());
InitializeSettings();
var settings = Services.GetRequiredService<AppSettings>();
Logging.Initialize(Services.GetRequiredService<ILoggerFactory>());
InitializeSettings();
var settings = Services.GetRequiredService<AppSettings>();

LogManager.ReconfigExistingLoggers();
LogManager.ReconfigExistingLoggers();

desktop.Exit += OnExit;
desktop.MainWindow = new SplashScreen(Services);
logger.LogInformation("AutoUpdate Enabled: {SettingsAutoUpdateEnabled}", settings.AutoUpdateEnabled);
desktop.Exit += OnExit;
desktop.MainWindow = new SplashScreen(Services);
logger.LogInformation("AutoUpdate Enabled: {SettingsAutoUpdateEnabled}", settings.AutoUpdateEnabled);

if (settings.AutoUpdateEnabled)
if (settings.AutoUpdateEnabled)
{
Task.Run(async () =>
{
Task.Run(async () =>
if (OperatingSystem.IsWindows())
{
if (OperatingSystem.IsWindows())
{
await UpdateCheck(Services.GetRequiredService<AppNotificationService>());
logger.LogInformation("Finished updatecheck");
}
else
{
logger.LogInformation("Skipped updatecheck");
}
});
}
await UpdateCheck(Services.GetRequiredService<AppNotificationService>());
logger.LogInformation("Finished updatecheck");
}
else
{
logger.LogInformation("Skipped updatecheck");
}
});
}

base.OnFrameworkInitializationCompleted();
}

private void InitializeSettings()
{
var settingsAccessor = (DesktopSettingsAccessor)services.GetRequiredService<ISettingsAccessor>();
var settings = settingsAccessor.LoadSettingsSync();
settings ??= new();

logger.LogDebug("Updating app settings with settings read from file...");
var appSettings = services.GetRequiredService<AppSettings>();
appSettings.UpdateFromSettings(settings);
AppData.IsInitialized = true;
Thread.CurrentThread.CurrentCulture = appSettings.SelectedLanguage.CultureInfo;
Thread.CurrentThread.CurrentUICulture = appSettings.SelectedLanguage.CultureInfo;
logger.LogDebug("Settings initialization complete");
}
base.OnFrameworkInitializationCompleted();
}

private void InitializeSettings()
{
var settingsAccessor = (DesktopSettingsAccessor)services.GetRequiredService<ISettingsAccessor>();
var settings = settingsAccessor.LoadSettingsSync();
settings ??= new();

logger.LogDebug("Updating app settings with settings read from file...");
var appSettings = services.GetRequiredService<AppSettings>();
appSettings.UpdateFromSettings(settings);
AppData.IsInitialized = true;
Thread.CurrentThread.CurrentCulture = appSettings.SelectedLanguage.CultureInfo;
Thread.CurrentThread.CurrentUICulture = appSettings.SelectedLanguage.CultureInfo;
logger.LogDebug("Settings initialization complete");
}

private void OnExit(object? sender, ControlledApplicationLifetimeExitEventArgs e)
{
logger.LogInformation("Closing app, saving setting and builds");
var settingsAccessor = (DesktopSettingsAccessor)Services.GetRequiredService<ISettingsAccessor>();
settingsAccessor.SaveSettingsSync(Services.GetRequiredService<AppSettings>());
logger.LogInformation("Exiting...");
logger.LogInformation("------------------------------");
}

[SupportedOSPlatform("windows")]
private async Task UpdateCheck(AppNotificationService notificationService)
{
logger.LogInformation("Current version: {Version}", Assembly.GetExecutingAssembly().GetName().Version);

private void OnExit(object? sender, ControlledApplicationLifetimeExitEventArgs e)
using UpdateManager updateManager = new GithubUpdateManager("https://github.com/WoWs-Builder-Team/WoWs-ShipBuilder");
if (!updateManager.IsInstalledApp)
{
logger.LogInformation("Closing app, saving setting and builds");
var settingsAccessor = (DesktopSettingsAccessor)Services.GetRequiredService<ISettingsAccessor>();
settingsAccessor.SaveSettingsSync(Services.GetRequiredService<AppSettings>());
logger.LogInformation("Exiting...");
logger.LogInformation("------------------------------");
logger.LogInformation("No update.exe found, aborting update check");
return;
}

[SupportedOSPlatform("windows")]
private async Task UpdateCheck(AppNotificationService notificationService)
logger.LogInformation("Update manager initialized");
try
{
logger.LogInformation("Current version: {Version}", Assembly.GetExecutingAssembly().GetName().Version);

using UpdateManager updateManager = new GithubUpdateManager("https://github.com/WoWs-Builder-Team/WoWs-ShipBuilder");
if (!updateManager.IsInstalledApp)
// Can throw a null-reference-exception, no idea why.
var updateInfo = await updateManager.CheckForUpdate();
if (!updateInfo.ReleasesToApply.Any())
{
logger.LogInformation("No update.exe found, aborting update check");
logger.LogInformation("No app update found");
return;
}

logger.LogInformation("Update manager initialized");
try
await notificationService.NotifyAppUpdateStart();
var release = await updateManager.UpdateApp();
if (release == null)
{
// Can throw a null-reference-exception, no idea why.
var updateInfo = await updateManager.CheckForUpdate();
if (!updateInfo.ReleasesToApply.Any())
{
logger.LogInformation("No app update found");
return;
}
logger.LogInformation("No app update found");
return;
}

await notificationService.NotifyAppUpdateStart();
var release = await updateManager.UpdateApp();
if (release == null)
logger.LogInformation("App updated to version {ReleaseVersion}", release.Version);
await notificationService.NotifyAppUpdateComplete();
var result = await ShowUpdateRestartDialog((ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.MainWindow, Services.GetRequiredService<ILocalizer>());
if (result.Equals(MessageBox.MessageBoxResult.Yes))
{
logger.LogInformation("User decided to restart after update");
if (OperatingSystem.IsWindows())
{
logger.LogInformation("No app update found");
return;
UpdateManager.RestartApp();
}

logger.LogInformation("App updated to version {ReleaseVersion}", release.Version);
await notificationService.NotifyAppUpdateComplete();
var result = await ShowUpdateRestartDialog((ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.MainWindow, Services.GetRequiredService<ILocalizer>());
if (result.Equals(MessageBox.MessageBoxResult.Yes))
{
logger.LogInformation("User decided to restart after update");
if (OperatingSystem.IsWindows())
{
UpdateManager.RestartApp();
}
}
}
catch (NullReferenceException)
{
logger.LogDebug("NullReferenceException during app update");
}
catch (Exception e)
{
}
catch (NullReferenceException)
{
logger.LogDebug("NullReferenceException during app update");
}
catch (Exception e)
{
#if DEBUG
logger.LogWarning(e, "Exception during app update");
logger.LogWarning(e, "Exception during app update");
#else
logger.LogError(e, "Exception during app update");
#endif
await notificationService.NotifyAppUpdateError(nameof(Translation.NotificationService_ErrorMessage));
}
await notificationService.NotifyAppUpdateError(nameof(Translation.NotificationService_ErrorMessage));

Check failure on line 179 in WoWsShipBuilder.Desktop/App.axaml.cs

View workflow job for this annotation

GitHub Actions / Build application on dev branch (Windows)

Check failure on line 179 in WoWsShipBuilder.Desktop/App.axaml.cs

View workflow job for this annotation

GitHub Actions / Build application on dev branch (Windows)

}
}

private sealed class CustomModeDetector : IModeDetector
{
public bool? InUnitTestRunner() => false;
}
private sealed class CustomModeDetector : IModeDetector
{
public bool? InUnitTestRunner() => false;
}
}
11 changes: 4 additions & 7 deletions WoWsShipBuilder.Desktop/Common/AppHeader.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
</Button.Styles>
<Path Margin="10,0,10,0"
Stretch="Uniform"
Fill="{StaticResource ThemeForegroundBrush}"
Fill="White"
Data="M2048 1229v-205h-2048v205h2048z"></Path>
</Button>

Expand All @@ -52,7 +52,7 @@
</Button.Styles>
<Path Margin="10,0,10,0"
Stretch="Uniform"
Fill="{StaticResource ThemeForegroundBrush}"
Fill="White"
Name="MaximizeIcon"
Data="M2048 2048v-2048h-2048v2048h2048zM1843 1843h-1638v-1638h1638v1638z"></Path>
</Button>
Expand All @@ -70,11 +70,8 @@
<Style Selector="Button:not(:pointerover) /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="Button:pointerover > Path">
<Setter Property="Fill" Value="{StaticResource ThemeForegroundBrush}"/>
</Style>
<Style Selector="Button:not(:pointerover) > Path">
<Setter Property="Fill" Value="{StaticResource ThemeForegroundBrush}"/>
<Style Selector="Button > Path">
<Setter Property="Fill" Value="White"/>
</Style>
</Button.Styles>
<Path Margin="10,0,10,0"
Expand Down
Loading

0 comments on commit aa083c9

Please sign in to comment.