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. 203
      StabilityMatrix.Avalonia/App.axaml.cs
  2. 42
      StabilityMatrix.Avalonia/Views/MainWindow.axaml.cs

203
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,11 +74,18 @@ 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 =>
@ -123,8 +131,9 @@ public sealed class App : Application
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,15 +160,17 @@ 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;
@ -176,16 +187,22 @@ public sealed class App : Application
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 =>
settingsManager.Transaction(
s =>
{
s.WindowSettings = new WindowSettings(
mainWindow.Width, mainWindow.Height,
mainWindow.Width,
mainWindow.Height,
validWindowPosition ? mainWindow.Position.X : 0,
validWindowPosition ? mainWindow.Position.Y : 0);
}, ignoreMissingLibraryDir: true);
validWindowPosition ? mainWindow.Position.Y : 0
);
},
ignoreMissingLibraryDir: true
);
};
mainWindow.Closed += (_, _) => Shutdown();
@ -213,7 +230,8 @@ public sealed class App : Application
internal static void ConfigurePageViewModels(IServiceCollection services)
{
services.AddSingleton<PackageManagerViewModel>()
services
.AddSingleton<PackageManagerViewModel>()
.AddSingleton<SettingsViewModel>()
.AddSingleton<InferenceSettingsViewModel>()
.AddSingleton<CheckpointBrowserViewModel>()
@ -223,11 +241,14 @@ public sealed class App : Application
.AddSingleton<ProgressManagerViewModel>()
.AddSingleton<InferenceViewModel>();
services.AddSingleton<MainWindowViewModel>(provider =>
new MainWindowViewModel(provider.GetRequiredService<ISettingsManager>(),
services.AddSingleton<MainWindowViewModel>(
provider =>
new MainWindowViewModel(
provider.GetRequiredService<ISettingsManager>(),
provider.GetRequiredService<IDiscordRichPresenceService>(),
provider.GetRequiredService<ServiceManager<ViewModelBase>>(),
provider.GetRequiredService<ITrackedDownloadService>())
provider.GetRequiredService<ITrackedDownloadService>()
)
{
Pages =
{
@ -237,15 +258,12 @@ public sealed class App : Application
provider.GetRequiredService<CheckpointsPageViewModel>(),
provider.GetRequiredService<CheckpointBrowserViewModel>(),
},
FooterPages =
{
provider.GetRequiredService<SettingsViewModel>()
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)
@ -290,7 +308,8 @@ public sealed class App : Application
services.AddTransient<BatchSizeCardViewModel>();
// Dialog factory
services.AddSingleton<ServiceManager<ViewModelBase>>(provider =>
services.AddSingleton<ServiceManager<ViewModelBase>>(
provider =>
new ServiceManager<ViewModelBase>()
.Register(provider.GetRequiredService<InstallerViewModel>)
.Register(provider.GetRequiredService<OneClickInstallViewModel>)
@ -404,13 +423,15 @@ public sealed class App : Application
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())
@ -460,13 +481,13 @@ 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
@ -475,8 +496,7 @@ public sealed class App : Application
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: (_, _) =>
.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,18 +551,21 @@ 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 =>
services.AddSingleton<IApiFactory, ApiFactory>(
provider =>
new ApiFactory(provider.GetRequiredService<IHttpClientFactory>())
{
RefitSettings = apiFactoryRefitSettings,
});
}
);
ConditionalAddLogViewer(services);
@ -545,18 +573,21 @@ public sealed class App : Application
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();
@ -615,21 +644,30 @@ public sealed class App : Application
ConditionalAddLogViewerNLog(setupBuilder);
setupBuilder.LoadConfiguration(builder => {
var debugTarget = builder.ForTarget("console").WriteTo(new DebuggerTarget
setupBuilder.LoadConfiguration(builder =>
{
Layout = "${message}"
}).WithAsync();
var debugTarget = builder
.ForTarget("console")
.WriteTo(new DebuggerTarget { Layout = "${message}" })
.WithAsync();
var fileTarget = builder.ForTarget("logfile").WriteTo(new FileTarget
var fileTarget = builder
.ForTarget("logfile")
.WriteTo(
new FileTarget
{
Layout = "${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}",
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",
FileName =
"${specialfolder:folder=ApplicationData}/StabilityMatrix/app.log",
ArchiveFileName =
"${specialfolder:folder=ApplicationData}/StabilityMatrix/app.{#}.log",
ArchiveNumbering = ArchiveNumberingMode.Rolling,
MaxArchiveFiles = 2
}).WithAsync();
}
)
.WithAsync();
// Filter some sources to be warn levels or above only
builder.ForLogger("System.*").WriteToNil(NLog.LogLevel.Warn);
@ -637,16 +675,17 @@ public sealed class App : Application
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
});
@ -676,13 +715,19 @@ public sealed class App : Application
[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
}
}

42
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;
@ -44,7 +46,10 @@ public partial class MainWindow : AppWindowBase
navigationService = null!;
}
public MainWindow(INotificationService notificationService, INavigationService navigationService)
public MainWindow(
INotificationService notificationService,
INavigationService navigationService
)
{
this.notificationService = notificationService;
this.navigationService = navigationService;
@ -55,7 +60,6 @@ public partial class MainWindow : AppWindowBase
this.AttachDevTools();
LogWindow.Attach(this, App.Services);
#endif
TitleBar.ExtendsContentIntoTitleBar = true;
TitleBar.TitleBarHitTestType = TitleBarHitTestType.Complex;
}
@ -65,7 +69,9 @@ public partial class MainWindow : AppWindowBase
{
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)
@ -93,8 +99,7 @@ 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);
@ -142,7 +147,9 @@ public partial class MainWindow : AppWindowBase
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());
}
@ -173,7 +180,8 @@ public partial class MainWindow : AppWindowBase
notificationService.ShowPersistent(
"Failed to load image",
$"Could not load '{displayName}'\n({e.Exception.Message})",
NotificationType.Warning);
NotificationType.Warning
);
});
}
@ -189,8 +197,13 @@ public partial class MainWindow : AppWindowBase
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