Browse Source

Add compile conditions to fix release build

pull/165/head
Ionite 1 year ago
parent
commit
8bcbcb0964
No known key found for this signature in database
  1. 399
      StabilityMatrix.Avalonia/App.axaml.cs
  2. 76
      StabilityMatrix.Avalonia/Views/MainWindow.axaml.cs

399
StabilityMatrix.Avalonia/App.axaml.cs

@ -1,3 +1,7 @@
#if DEBUG
using StabilityMatrix.Avalonia.Diagnostics.LogViewer;
using StabilityMatrix.Avalonia.Diagnostics.LogViewer.Extensions;
#endif
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
@ -32,10 +36,7 @@ using Polly.Timeout;
using Refit;
using Sentry;
using StabilityMatrix.Avalonia.Controls;
using StabilityMatrix.Avalonia.Controls.CodeCompletion;
using StabilityMatrix.Avalonia.DesignData;
using StabilityMatrix.Avalonia.Diagnostics.LogViewer;
using StabilityMatrix.Avalonia.Diagnostics.LogViewer.Extensions;
using StabilityMatrix.Avalonia.Helpers;
using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.Models;
@ -46,8 +47,8 @@ using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.ViewModels.CheckpointBrowser;
using StabilityMatrix.Avalonia.ViewModels.CheckpointManager;
using StabilityMatrix.Avalonia.ViewModels.Dialogs;
using StabilityMatrix.Avalonia.ViewModels.PackageManager;
using StabilityMatrix.Avalonia.ViewModels.Inference;
using StabilityMatrix.Avalonia.ViewModels.PackageManager;
using StabilityMatrix.Avalonia.ViewModels.Settings;
using StabilityMatrix.Avalonia.Views;
using StabilityMatrix.Avalonia.Views.Dialogs;
@ -73,12 +74,19 @@ namespace StabilityMatrix.Avalonia;
public sealed class App : Application
{
[NotNull] public static IServiceProvider? Services { get; private set; }
[NotNull] public static Visual? VisualRoot { get; private set; }
[NotNull] public static IStorageProvider? StorageProvider { get; private set; }
[NotNull]
public static IServiceProvider? Services { get; private set; }
[NotNull]
public static Visual? VisualRoot { get; private set; }
[NotNull]
public static IStorageProvider? StorageProvider { get; private set; }
// ReSharper disable once MemberCanBePrivate.Global
[NotNull] public static IConfiguration? Config { get; private set; }
[NotNull]
public static IConfiguration? Config { get; private set; }
// ReSharper disable once MemberCanBePrivate.Global
public IClassicDesktopStyleApplicationLifetime? DesktopLifetime =>
ApplicationLifetime as IClassicDesktopStyleApplicationLifetime;
@ -93,11 +101,11 @@ public sealed class App : Application
RequestedThemeVariant = ThemeVariant.Dark;
}
}
public override void OnFrameworkInitializationCompleted()
{
base.OnFrameworkInitializationCompleted();
if (Design.IsDesignMode)
{
DesignData.DesignData.Initialize();
@ -122,9 +130,10 @@ public sealed class App : Application
setupWindow.ShowAsDialog = true;
setupWindow.ShowActivated = true;
setupWindow.ShowAsyncCts = new CancellationTokenSource();
setupWindow.ExtendClientAreaChromeHints = Program.Args.NoWindowChromeEffects ?
ExtendClientAreaChromeHints.NoChrome : ExtendClientAreaChromeHints.PreferSystemChrome;
setupWindow.ExtendClientAreaChromeHints = Program.Args.NoWindowChromeEffects
? ExtendClientAreaChromeHints.NoChrome
: ExtendClientAreaChromeHints.PreferSystemChrome;
DesktopLifetime.MainWindow = setupWindow;
@ -151,47 +160,55 @@ public sealed class App : Application
private void ShowMainWindow()
{
if (DesktopLifetime is null) return;
if (DesktopLifetime is null)
return;
var mainViewModel = Services.GetRequiredService<MainWindowViewModel>();
var mainWindow = Services.GetRequiredService<MainWindow>();
mainWindow.DataContext = mainViewModel;
mainWindow.ExtendClientAreaChromeHints = Program.Args.NoWindowChromeEffects ?
ExtendClientAreaChromeHints.NoChrome : ExtendClientAreaChromeHints.PreferSystemChrome;
mainWindow.ExtendClientAreaChromeHints = Program.Args.NoWindowChromeEffects
? ExtendClientAreaChromeHints.NoChrome
: ExtendClientAreaChromeHints.PreferSystemChrome;
var settingsManager = Services.GetRequiredService<ISettingsManager>();
var windowSettings = settingsManager.Settings.WindowSettings;
if (windowSettings != null && !Program.Args.ResetWindowPosition)
{
mainWindow.Position = new PixelPoint(windowSettings.X, windowSettings.Y);
mainWindow.Width = windowSettings.Width;
mainWindow.Height = windowSettings.Height;
mainWindow.Height = windowSettings.Height;
}
else
{
mainWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
}
mainWindow.Closing += (_, _) =>
{
var validWindowPosition =
mainWindow.Screens.All.Any(screen => screen.Bounds.Contains(mainWindow.Position));
var validWindowPosition = mainWindow.Screens.All.Any(
screen => screen.Bounds.Contains(mainWindow.Position)
);
settingsManager.Transaction(s =>
{
s.WindowSettings = new WindowSettings(
mainWindow.Width, mainWindow.Height,
validWindowPosition ? mainWindow.Position.X : 0,
validWindowPosition ? mainWindow.Position.Y : 0);
}, ignoreMissingLibraryDir: true);
settingsManager.Transaction(
s =>
{
s.WindowSettings = new WindowSettings(
mainWindow.Width,
mainWindow.Height,
validWindowPosition ? mainWindow.Position.X : 0,
validWindowPosition ? mainWindow.Position.Y : 0
);
},
ignoreMissingLibraryDir: true
);
};
mainWindow.Closed += (_, _) => Shutdown();
VisualRoot = mainWindow;
StorageProvider = mainWindow.StorageProvider;
DesktopLifetime.MainWindow = mainWindow;
DesktopLifetime.Exit += OnExit;
}
@ -200,20 +217,21 @@ public sealed class App : Application
{
var services = ConfigureServices();
Services = services.BuildServiceProvider();
var settingsManager = Services.GetRequiredService<ISettingsManager>();
if (settingsManager.TryFindLibrary())
{
Cultures.TrySetSupportedCulture(settingsManager.Settings.Language);
}
Services.GetRequiredService<ProgressManagerViewModel>().StartEventListener();
}
internal static void ConfigurePageViewModels(IServiceCollection services)
{
services.AddSingleton<PackageManagerViewModel>()
services
.AddSingleton<PackageManagerViewModel>()
.AddSingleton<SettingsViewModel>()
.AddSingleton<InferenceSettingsViewModel>()
.AddSingleton<CheckpointBrowserViewModel>()
@ -222,30 +240,30 @@ public sealed class App : Application
.AddSingleton<LaunchPageViewModel>()
.AddSingleton<ProgressManagerViewModel>()
.AddSingleton<InferenceViewModel>();
services.AddSingleton<MainWindowViewModel>(provider =>
new MainWindowViewModel(provider.GetRequiredService<ISettingsManager>(),
provider.GetRequiredService<IDiscordRichPresenceService>(),
provider.GetRequiredService<ServiceManager<ViewModelBase>>(),
provider.GetRequiredService<ITrackedDownloadService>())
{
Pages =
{
provider.GetRequiredService<LaunchPageViewModel>(),
provider.GetRequiredService<InferenceViewModel>(),
provider.GetRequiredService<PackageManagerViewModel>(),
provider.GetRequiredService<CheckpointsPageViewModel>(),
provider.GetRequiredService<CheckpointBrowserViewModel>(),
},
FooterPages =
services.AddSingleton<MainWindowViewModel>(
provider =>
new MainWindowViewModel(
provider.GetRequiredService<ISettingsManager>(),
provider.GetRequiredService<IDiscordRichPresenceService>(),
provider.GetRequiredService<ServiceManager<ViewModelBase>>(),
provider.GetRequiredService<ITrackedDownloadService>()
)
{
provider.GetRequiredService<SettingsViewModel>()
Pages =
{
provider.GetRequiredService<LaunchPageViewModel>(),
provider.GetRequiredService<InferenceViewModel>(),
provider.GetRequiredService<PackageManagerViewModel>(),
provider.GetRequiredService<CheckpointsPageViewModel>(),
provider.GetRequiredService<CheckpointBrowserViewModel>(),
},
FooterPages = { provider.GetRequiredService<SettingsViewModel>() }
}
});
);
// Register disposable view models for shutdown cleanup
services.AddSingleton<IDisposable>(p
=> p.GetRequiredService<LaunchPageViewModel>());
services.AddSingleton<IDisposable>(p => p.GetRequiredService<LaunchPageViewModel>());
}
internal static void ConfigureDialogViewModels(IServiceCollection services)
@ -260,21 +278,21 @@ public sealed class App : Application
services.AddTransient<EnvVarsViewModel>();
services.AddTransient<ImageViewerViewModel>();
services.AddTransient<PackageImportViewModel>();
// Dialog view models (singleton)
services.AddSingleton<FirstLaunchSetupViewModel>();
services.AddSingleton<UpdateViewModel>();
// Other transients (usually sub view models)
services.AddTransient<CheckpointFolder>();
services.AddTransient<CheckpointFile>();
services.AddTransient<InferenceTextToImageViewModel>();
services.AddTransient<CheckpointBrowserCardViewModel>();
services.AddTransient<PackageCardViewModel>();
// Global progress
services.AddSingleton<ProgressManagerViewModel>();
// Controls
services.AddTransient<RefreshBadgeViewModel>();
@ -288,38 +306,39 @@ public sealed class App : Application
services.AddTransient<StackExpanderViewModel>();
services.AddTransient<ModelCardViewModel>();
services.AddTransient<BatchSizeCardViewModel>();
// Dialog factory
services.AddSingleton<ServiceManager<ViewModelBase>>(provider =>
new ServiceManager<ViewModelBase>()
.Register(provider.GetRequiredService<InstallerViewModel>)
.Register(provider.GetRequiredService<OneClickInstallViewModel>)
.Register(provider.GetRequiredService<SelectModelVersionViewModel>)
.Register(provider.GetRequiredService<SelectDataDirectoryViewModel>)
.Register(provider.GetRequiredService<LaunchOptionsViewModel>)
.Register(provider.GetRequiredService<UpdateViewModel>)
.Register(provider.GetRequiredService<CheckpointBrowserCardViewModel>)
.Register(provider.GetRequiredService<CheckpointFolder>)
.Register(provider.GetRequiredService<CheckpointFile>)
.Register(provider.GetRequiredService<PackageCardViewModel>)
.Register(provider.GetRequiredService<RefreshBadgeViewModel>)
.Register(provider.GetRequiredService<ExceptionViewModel>)
.Register(provider.GetRequiredService<EnvVarsViewModel>)
.Register(provider.GetRequiredService<ProgressManagerViewModel>)
.Register(provider.GetRequiredService<InferenceTextToImageViewModel>)
.Register(provider.GetRequiredService<SeedCardViewModel>)
.Register(provider.GetRequiredService<SamplerCardViewModel>)
.Register(provider.GetRequiredService<ImageGalleryCardViewModel>)
.Register(provider.GetRequiredService<PromptCardViewModel>)
.Register(provider.GetRequiredService<StackCardViewModel>)
.Register(provider.GetRequiredService<StackExpanderViewModel>)
.Register(provider.GetRequiredService<UpscalerCardViewModel>)
.Register(provider.GetRequiredService<ModelCardViewModel>)
.Register(provider.GetRequiredService<BatchSizeCardViewModel>)
.Register(provider.GetRequiredService<ImageViewerViewModel>)
.Register(provider.GetRequiredService<FirstLaunchSetupViewModel>)
.Register(provider.GetRequiredService<PackageImportViewModel>)
);
services.AddSingleton<ServiceManager<ViewModelBase>>(
provider =>
new ServiceManager<ViewModelBase>()
.Register(provider.GetRequiredService<InstallerViewModel>)
.Register(provider.GetRequiredService<OneClickInstallViewModel>)
.Register(provider.GetRequiredService<SelectModelVersionViewModel>)
.Register(provider.GetRequiredService<SelectDataDirectoryViewModel>)
.Register(provider.GetRequiredService<LaunchOptionsViewModel>)
.Register(provider.GetRequiredService<UpdateViewModel>)
.Register(provider.GetRequiredService<CheckpointBrowserCardViewModel>)
.Register(provider.GetRequiredService<CheckpointFolder>)
.Register(provider.GetRequiredService<CheckpointFile>)
.Register(provider.GetRequiredService<PackageCardViewModel>)
.Register(provider.GetRequiredService<RefreshBadgeViewModel>)
.Register(provider.GetRequiredService<ExceptionViewModel>)
.Register(provider.GetRequiredService<EnvVarsViewModel>)
.Register(provider.GetRequiredService<ProgressManagerViewModel>)
.Register(provider.GetRequiredService<InferenceTextToImageViewModel>)
.Register(provider.GetRequiredService<SeedCardViewModel>)
.Register(provider.GetRequiredService<SamplerCardViewModel>)
.Register(provider.GetRequiredService<ImageGalleryCardViewModel>)
.Register(provider.GetRequiredService<PromptCardViewModel>)
.Register(provider.GetRequiredService<StackCardViewModel>)
.Register(provider.GetRequiredService<StackExpanderViewModel>)
.Register(provider.GetRequiredService<UpscalerCardViewModel>)
.Register(provider.GetRequiredService<ModelCardViewModel>)
.Register(provider.GetRequiredService<BatchSizeCardViewModel>)
.Register(provider.GetRequiredService<ImageViewerViewModel>)
.Register(provider.GetRequiredService<FirstLaunchSetupViewModel>)
.Register(provider.GetRequiredService<PackageImportViewModel>)
);
}
internal static void ConfigureViews(IServiceCollection services)
@ -333,10 +352,10 @@ public sealed class App : Application
services.AddSingleton<CheckpointBrowserPage>();
services.AddSingleton<ProgressManagerPage>();
services.AddSingleton<InferencePage>();
// Inference tabs
services.AddTransient<InferenceTextToImageView>();
// Inference controls
services.AddTransient<ImageGalleryCard>();
services.AddTransient<SeedCard>();
@ -348,7 +367,7 @@ public sealed class App : Application
services.AddTransient<ModelCard>();
services.AddTransient<BatchSizeCard>();
services.AddSingleton<NewCheckpointsPage>();
// Dialogs
services.AddTransient<SelectDataDirectoryDialog>();
services.AddTransient<LaunchOptionsDialog>();
@ -357,15 +376,15 @@ public sealed class App : Application
services.AddTransient<EnvVarsDialog>();
services.AddTransient<ImageViewerDialog>();
services.AddTransient<PackageImportDialog>();
// Controls
services.AddTransient<RefreshBadge>();
// Windows
services.AddSingleton<MainWindow>();
services.AddSingleton<FirstLaunchSetupWindow>();
}
internal static void ConfigurePackages(IServiceCollection services)
{
services.AddSingleton<BasePackage, A3WebUI>();
@ -385,7 +404,7 @@ public sealed class App : Application
ConfigurePageViewModels(services);
ConfigureDialogViewModels(services);
ConfigurePackages(services);
// Other services
services.AddSingleton<ISettingsManager, SettingsManager>();
services.AddSingleton<ISharedFolders, SharedFolders>();
@ -402,23 +421,25 @@ public sealed class App : Application
services.AddSingleton<ICompletionProvider, CompletionProvider>();
services.AddSingleton<ITokenizerProvider, TokenizerProvider>();
services.AddSingleton<IModelIndexService, ModelIndexService>();
services.AddSingleton<ITrackedDownloadService, TrackedDownloadService>();
services.AddSingleton<IDisposable>(provider =>
(IDisposable) provider.GetRequiredService<ITrackedDownloadService>());
services.AddSingleton<IDisposable>(
provider => (IDisposable)provider.GetRequiredService<ITrackedDownloadService>()
);
// Rich presence
services.AddSingleton<IDiscordRichPresenceService, DiscordRichPresenceService>();
services.AddSingleton<IDisposable>(provider =>
provider.GetRequiredService<IDiscordRichPresenceService>());
services.AddSingleton<IDisposable>(
provider => provider.GetRequiredService<IDiscordRichPresenceService>()
);
Config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
services.Configure<DebugOptions>(Config.GetSection(nameof(DebugOptions)));
if (Compat.IsWindows)
{
services.AddSingleton<IPrerequisiteHelper, WindowsPrerequisiteHelper>();
@ -460,23 +481,22 @@ public sealed class App : Application
jsonSerializerOptions.Converters.Add(new ObjectToInferredTypesConverter());
jsonSerializerOptions.Converters.Add(new DefaultUnknownEnumConverter<CivitFileType>());
jsonSerializerOptions.Converters.Add(
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
);
jsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
var defaultRefitSettings = new RefitSettings
{
ContentSerializer =
new SystemTextJsonContentSerializer(jsonSerializerOptions)
ContentSerializer = new SystemTextJsonContentSerializer(jsonSerializerOptions)
};
// Refit settings for IApiFactory
var defaultSystemTextJsonSettings =
SystemTextJsonContentSerializer.GetDefaultJsonSerializerOptions();
defaultSystemTextJsonSettings.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
var apiFactoryRefitSettings = new RefitSettings
{
ContentSerializer =
new SystemTextJsonContentSerializer(defaultSystemTextJsonSettings),
ContentSerializer = new SystemTextJsonContentSerializer(defaultSystemTextJsonSettings),
};
// HTTP Policies
@ -488,9 +508,10 @@ public sealed class App : Application
HttpStatusCode.ServiceUnavailable, // 503
HttpStatusCode.GatewayTimeout // 504
};
var delay = Backoff
.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromMilliseconds(80),
retryCount: 5);
var delay = Backoff.DecorrelatedJitterBackoffV2(
medianFirstRetryDelay: TimeSpan.FromMilliseconds(80),
retryCount: 5
);
var retryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>()
@ -499,25 +520,29 @@ public sealed class App : Application
// Shorter timeout for local requests
var localTimeout = Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(3));
var localDelay = Backoff
.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromMilliseconds(50),
retryCount: 3);
var localDelay = Backoff.DecorrelatedJitterBackoffV2(
medianFirstRetryDelay: TimeSpan.FromMilliseconds(50),
retryCount: 3
);
var localRetryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>()
.OrResult(r => retryStatusCodes.Contains(r.StatusCode))
.WaitAndRetryAsync(localDelay, onRetryAsync: (_, _) =>
{
Debug.WriteLine("Retrying local request...");
return Task.CompletedTask;
});
.WaitAndRetryAsync(
localDelay,
onRetryAsync: (_, _) =>
{
Debug.WriteLine("Retrying local request...");
return Task.CompletedTask;
}
);
// named client for update
services.AddHttpClient("UpdateClient")
.AddPolicyHandler(retryPolicy);
services.AddHttpClient("UpdateClient").AddPolicyHandler(retryPolicy);
// Add Refit clients
services.AddRefitClient<ICivitApi>(defaultRefitSettings)
services
.AddRefitClient<ICivitApi>(defaultRefitSettings)
.ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri("https://civitai.com");
@ -526,37 +551,43 @@ public sealed class App : Application
.AddPolicyHandler(retryPolicy);
// Add Refit client managers
services.AddHttpClient("A3Client")
services
.AddHttpClient("A3Client")
.AddPolicyHandler(localTimeout.WrapAsync(localRetryPolicy));
/*services.AddHttpClient("IComfyApi")
.AddPolicyHandler(localTimeout.WrapAsync(localRetryPolicy));*/
// Add Refit client factory
services.AddSingleton<IApiFactory, ApiFactory>(provider =>
new ApiFactory(provider.GetRequiredService<IHttpClientFactory>())
{
RefitSettings = apiFactoryRefitSettings,
});
services.AddSingleton<IApiFactory, ApiFactory>(
provider =>
new ApiFactory(provider.GetRequiredService<IHttpClientFactory>())
{
RefitSettings = apiFactoryRefitSettings,
}
);
ConditionalAddLogViewer(services);
// Add logging
services.AddLogging(builder =>
{
builder.ClearProviders();
builder.AddFilter("Microsoft.Extensions.Http", LogLevel.Warning)
builder
.AddFilter("Microsoft.Extensions.Http", LogLevel.Warning)
.AddFilter("Microsoft.Extensions.Http.DefaultHttpClientFactory", LogLevel.Warning)
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning);
builder.SetMinimumLevel(LogLevel.Debug);
#if DEBUG
builder.AddNLog(ConfigureLogging(),
builder.AddNLog(
ConfigureLogging(),
new NLogProviderOptions
{
IgnoreEmptyEventId = false,
CaptureEventId = EventIdCaptureType.Legacy
});
}
);
#else
builder.AddNLog(ConfigureLogging());
#endif
@ -573,8 +604,8 @@ public sealed class App : Application
/// <exception cref="NullReferenceException">If Application.Current is null</exception>
public static void Shutdown(int exitCode = 0)
{
if (Current is null) throw new NullReferenceException(
"Current Application was null when Shutdown called");
if (Current is null)
throw new NullReferenceException("Current Application was null when Shutdown called");
if (Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime)
{
lifetime.Shutdown(exitCode);
@ -588,11 +619,9 @@ public sealed class App : Application
var settingsManager = Services.GetRequiredService<ISettingsManager>();
// If RemoveFolderLinksOnShutdown is set, delete all package junctions
if (settingsManager is
{
IsLibraryDirSet: true,
Settings.RemoveFolderLinksOnShutdown: true
})
if (
settingsManager is { IsLibraryDirSet: true, Settings.RemoveFolderLinksOnShutdown: true }
)
{
var sharedFolders = Services.GetRequiredService<ISharedFolders>();
sharedFolders.RemoveLinksForAllPackages();
@ -614,43 +643,53 @@ public sealed class App : Application
var setupBuilder = LogManager.Setup();
ConditionalAddLogViewerNLog(setupBuilder);
setupBuilder.LoadConfiguration(builder => {
var debugTarget = builder.ForTarget("console").WriteTo(new DebuggerTarget
{
Layout = "${message}"
}).WithAsync();
var fileTarget = builder.ForTarget("logfile").WriteTo(new FileTarget
{
Layout = "${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}",
ArchiveOldFileOnStartup = true,
FileName = "${specialfolder:folder=ApplicationData}/StabilityMatrix/app.log",
ArchiveFileName = "${specialfolder:folder=ApplicationData}/StabilityMatrix/app.{#}.log",
ArchiveNumbering = ArchiveNumberingMode.Rolling,
MaxArchiveFiles = 2
}).WithAsync();
setupBuilder.LoadConfiguration(builder =>
{
var debugTarget = builder
.ForTarget("console")
.WriteTo(new DebuggerTarget { Layout = "${message}" })
.WithAsync();
var fileTarget = builder
.ForTarget("logfile")
.WriteTo(
new FileTarget
{
Layout =
"${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}",
ArchiveOldFileOnStartup = true,
FileName =
"${specialfolder:folder=ApplicationData}/StabilityMatrix/app.log",
ArchiveFileName =
"${specialfolder:folder=ApplicationData}/StabilityMatrix/app.{#}.log",
ArchiveNumbering = ArchiveNumberingMode.Rolling,
MaxArchiveFiles = 2
}
)
.WithAsync();
// Filter some sources to be warn levels or above only
builder.ForLogger("System.*").WriteToNil(NLog.LogLevel.Warn);
builder.ForLogger("Microsoft.*").WriteToNil(NLog.LogLevel.Warn);
builder.ForLogger("Microsoft.Extensions.Http.*").WriteToNil(NLog.LogLevel.Warn);
// Disable console trace logging by default
builder.ForLogger("StabilityMatrix.Avalonia.ViewModels.ConsoleViewModel").WriteToNil(NLog.LogLevel.Debug);
builder
.ForLogger("StabilityMatrix.Avalonia.ViewModels.ConsoleViewModel")
.WriteToNil(NLog.LogLevel.Debug);
builder.ForLogger().FilterMinLevel(NLog.LogLevel.Trace).WriteTo(debugTarget);
builder.ForLogger().FilterMinLevel(NLog.LogLevel.Debug).WriteTo(fileTarget);
#if DEBUG
var logViewerTarget = builder.ForTarget("DataStoreLogger").WriteTo(new DataStoreLoggerTarget()
{
Layout = "${message}"
});
var logViewerTarget = builder
.ForTarget("DataStoreLogger")
.WriteTo(new DataStoreLoggerTarget() { Layout = "${message}" });
builder.ForLogger().FilterMinLevel(NLog.LogLevel.Trace).WriteTo(logViewerTarget);
#endif
});
// Sentry
if (SentrySdk.IsEnabled)
{
@ -669,20 +708,26 @@ public sealed class App : Application
}
LogManager.ReconfigExistingLoggers();
return LogManager.Configuration;
}
[Conditional("DEBUG")]
private static void ConditionalAddLogViewer(IServiceCollection services)
{
#if DEBUG
services.AddLogViewer();
#endif
}
[Conditional("DEBUG")]
private static void ConditionalAddLogViewerNLog(ISetupBuilder setupBuilder)
{
setupBuilder.SetupExtensions(extensionBuilder =>
extensionBuilder.RegisterTarget<DataStoreLoggerTarget>("DataStoreLogger"));
#if DEBUG
setupBuilder.SetupExtensions(
extensionBuilder =>
extensionBuilder.RegisterTarget<DataStoreLoggerTarget>("DataStoreLogger")
);
#endif
}
}

76
StabilityMatrix.Avalonia/Views/MainWindow.axaml.cs

@ -22,11 +22,13 @@ using FluentAvalonia.UI.Windowing;
using Microsoft.Extensions.DependencyInjection;
using StabilityMatrix.Avalonia.Animations;
using StabilityMatrix.Avalonia.Controls;
using StabilityMatrix.Avalonia.Diagnostics.Views;
using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels;
using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Core.Processes;
#if DEBUG
using StabilityMatrix.Avalonia.Diagnostics.Views;
#endif
namespace StabilityMatrix.Avalonia.Views;
@ -43,19 +45,21 @@ public partial class MainWindow : AppWindowBase
notificationService = null!;
navigationService = null!;
}
public MainWindow(INotificationService notificationService, INavigationService navigationService)
public MainWindow(
INotificationService notificationService,
INavigationService navigationService
)
{
this.notificationService = notificationService;
this.navigationService = navigationService;
InitializeComponent();
#if DEBUG
this.AttachDevTools();
LogWindow.Attach(this, App.Services);
#endif
TitleBar.ExtendsContentIntoTitleBar = true;
TitleBar.TitleBarHitTestType = TitleBarHitTestType.Complex;
}
@ -64,15 +68,17 @@ public partial class MainWindow : AppWindowBase
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
navigationService.SetFrame(FrameView ?? throw new NullReferenceException("Frame not found"));
navigationService.SetFrame(
FrameView ?? throw new NullReferenceException("Frame not found")
);
// Navigate to first page
if (DataContext is not MainWindowViewModel vm)
{
throw new NullReferenceException("DataContext is not MainWindowViewModel");
}
navigationService.NavigateTo(vm.Pages[0], new DrillInNavigationTransitionInfo());
}
@ -81,7 +87,7 @@ public partial class MainWindow : AppWindowBase
base.OnOpened(e);
Application.Current!.ActualThemeVariantChanged += OnActualThemeVariantChanged;
var theme = ActualThemeVariant;
// Enable mica for Windows 11
if (IsWindows11 && theme != FluentAvaloniaTheme.HighContrastTheme)
@ -93,11 +99,10 @@ public partial class MainWindow : AppWindowBase
protected override void OnClosing(WindowClosingEventArgs e)
{
// Show confirmation if package running
var launchPageViewModel = App.Services
.GetRequiredService<LaunchPageViewModel>();
var launchPageViewModel = App.Services.GetRequiredService<LaunchPageViewModel>();
launchPageViewModel.OnMainWindowClosing(e);
base.OnClosing(e);
}
@ -106,7 +111,7 @@ public partial class MainWindow : AppWindowBase
base.OnLoaded(e);
// Initialize notification service using this window as the visual root
notificationService.Initialize(this);
// Attach error notification handler for image loader
if (ImageLoader.AsyncImageLoader is FallbackRamCachedWebImageLoader loader)
{
@ -117,7 +122,7 @@ public partial class MainWindow : AppWindowBase
protected override void OnUnloaded(RoutedEventArgs e)
{
base.OnUnloaded(e);
// Detach error notification handler for image loader
if (ImageLoader.AsyncImageLoader is FallbackRamCachedWebImageLoader loader)
{
@ -134,20 +139,22 @@ public partial class MainWindow : AppWindowBase
{
return;
}
if (nvi.Tag is null)
{
throw new InvalidOperationException("NavigationViewItem Tag is null");
}
if (nvi.Tag is not ViewModelBase vm)
{
throw new InvalidOperationException($"NavigationViewItem Tag must be of type ViewModelBase, not {nvi.Tag?.GetType()}");
throw new InvalidOperationException(
$"NavigationViewItem Tag must be of type ViewModelBase, not {nvi.Tag?.GetType()}"
);
}
navigationService.NavigateTo(vm, new BetterEntranceNavigationTransition());
}
}
private void OnActualThemeVariantChanged(object? sender, EventArgs e)
{
if (IsWindows11)
@ -163,7 +170,7 @@ public partial class MainWindow : AppWindowBase
}
}
}
private void OnImageLoadFailed(object? sender, ImageLoadFailedEventArgs e)
{
Dispatcher.UIThread.Post(() =>
@ -173,24 +180,30 @@ public partial class MainWindow : AppWindowBase
notificationService.ShowPersistent(
"Failed to load image",
$"Could not load '{displayName}'\n({e.Exception.Message})",
NotificationType.Warning);
NotificationType.Warning
);
});
}
private void TryEnableMicaEffect()
{
TransparencyBackgroundFallback = Brushes.Transparent;
TransparencyLevelHint = new[]
{
WindowTransparencyLevel.Mica,
WindowTransparencyLevel.Mica,
WindowTransparencyLevel.AcrylicBlur,
WindowTransparencyLevel.Blur
};
if (ActualThemeVariant == ThemeVariant.Dark)
{
var color = this.TryFindResource("SolidBackgroundFillColorBase",
ThemeVariant.Dark, out var value) ? (Color2)(Color)value! : new Color2(32, 32, 32);
var color = this.TryFindResource(
"SolidBackgroundFillColorBase",
ThemeVariant.Dark,
out var value
)
? (Color2)(Color)value!
: new Color2(32, 32, 32);
color = color.LightenPercent(-0.8f);
@ -199,8 +212,13 @@ public partial class MainWindow : AppWindowBase
else if (ActualThemeVariant == ThemeVariant.Light)
{
// Similar effect here
var color = this.TryFindResource("SolidBackgroundFillColorBase",
ThemeVariant.Light, out var value) ? (Color2)(Color)value! : new Color2(243, 243, 243);
var color = this.TryFindResource(
"SolidBackgroundFillColorBase",
ThemeVariant.Light,
out var value
)
? (Color2)(Color)value!
: new Color2(243, 243, 243);
color = color.LightenPercent(0.5f);

Loading…
Cancel
Save