Browse Source

Merge pull request #188 from ionite34/discord-rich-presence

pull/57/head v2.1.1
Ionite 1 year ago committed by GitHub
parent
commit
2e37d3f76a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 3
      CHANGELOG.md
  2. 8
      StabilityMatrix.Avalonia/App.axaml.cs
  3. 3
      StabilityMatrix.Avalonia/DesignData/DesignData.cs
  4. 18
      StabilityMatrix.Avalonia/DesignData/MockDiscordRichPresenceService.cs
  5. 176
      StabilityMatrix.Avalonia/Services/DiscordRichPresenceService.cs
  6. 8
      StabilityMatrix.Avalonia/Services/IDiscordRichPresenceService.cs
  7. 3
      StabilityMatrix.Avalonia/StabilityMatrix.Avalonia.csproj
  8. 3
      StabilityMatrix.Avalonia/ViewModels/LaunchPageViewModel.cs
  9. 10
      StabilityMatrix.Avalonia/ViewModels/MainWindowViewModel.cs
  10. 11
      StabilityMatrix.Avalonia/ViewModels/SettingsViewModel.cs
  11. 26
      StabilityMatrix.Avalonia/Views/SettingsPage.axaml
  12. 8
      StabilityMatrix.Core/Helper/EventManager.cs
  13. 9
      StabilityMatrix.Core/Models/PackagePair.cs
  14. 2
      StabilityMatrix.Core/Models/Settings/Settings.cs

3
CHANGELOG.md

@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning 2.0](https://semver.org/spec/v2
## v2.1.1
### Added
- Discord Rich Presence support can now be enabled in Settings
### Fixed
- Launch Page selected package now persists in settings

8
StabilityMatrix.Avalonia/App.axaml.cs

@ -149,7 +149,7 @@ public sealed class App : Application
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)
@ -207,6 +207,7 @@ public sealed class App : Application
services.AddSingleton<MainWindowViewModel>(provider =>
new MainWindowViewModel(provider.GetRequiredService<ISettingsManager>(),
provider.GetRequiredService<IDiscordRichPresenceService>(),
provider.GetRequiredService<ServiceManager<ViewModelBase>>())
{
Pages =
@ -323,6 +324,11 @@ public sealed class App : Application
services.AddSingleton<INotificationService, NotificationService>();
services.AddSingleton<IPyRunner, PyRunner>();
services.AddSingleton<IUpdateHelper, UpdateHelper>();
// Rich presence
services.AddSingleton<IDiscordRichPresenceService, DiscordRichPresenceService>();
services.AddSingleton<IDisposable>(provider =>
provider.GetRequiredService<IDiscordRichPresenceService>());
Config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())

3
StabilityMatrix.Avalonia/DesignData/DesignData.cs

@ -81,7 +81,8 @@ public static class DesignData
.AddSingleton<INotificationService, MockNotificationService>()
.AddSingleton<ISharedFolders, MockSharedFolders>()
.AddSingleton<IDownloadService, MockDownloadService>()
.AddSingleton<IHttpClientFactory, MockHttpClientFactory>();
.AddSingleton<IHttpClientFactory, MockHttpClientFactory>()
.AddSingleton<IDiscordRichPresenceService, MockDiscordRichPresenceService>();
// Placeholder services that nobody should need during design time
services

18
StabilityMatrix.Avalonia/DesignData/MockDiscordRichPresenceService.cs

@ -0,0 +1,18 @@
using System;
using StabilityMatrix.Avalonia.Services;
namespace StabilityMatrix.Avalonia.DesignData;
public class MockDiscordRichPresenceService : IDiscordRichPresenceService
{
/// <inheritdoc />
public void Dispose()
{
GC.SuppressFinalize(this);
}
/// <inheritdoc />
public void UpdateState()
{
}
}

176
StabilityMatrix.Avalonia/Services/DiscordRichPresenceService.cs

@ -0,0 +1,176 @@
using System;
using DiscordRPC;
using DiscordRPC.Logging;
using DiscordRPC.Message;
using Microsoft.Extensions.Logging;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models.Packages;
using StabilityMatrix.Core.Services;
namespace StabilityMatrix.Avalonia.Services;
public class DiscordRichPresenceService : IDiscordRichPresenceService
{
private const string ApplicationId = "1134669805237059615";
private readonly ILogger<DiscordRichPresenceService> logger;
private readonly ISettingsManager settingsManager;
private readonly DiscordRpcClient client;
private readonly string appDetails;
private bool isDisposed;
private RichPresence DefaultPresence => new()
{
Details = appDetails,
Assets = new DiscordRPC.Assets
{
LargeImageKey = "stabilitymatrix-logo-1",
LargeImageText = $"Stability Matrix {appDetails}",
},
Buttons = new[]
{
new Button
{
Label = "GitHub",
Url = "https://github.com/LykosAI/StabilityMatrix",
}
}
};
public DiscordRichPresenceService(
ILogger<DiscordRichPresenceService> logger,
ISettingsManager settingsManager)
{
this.logger = logger;
this.settingsManager = settingsManager;
appDetails = $"v{Compat.AppVersion.WithoutMetadata()}";
client = new DiscordRpcClient(ApplicationId);
client.Logger = new NullLogger();
client.OnReady += OnReady;
client.OnError += OnError;
client.OnClose += OnClose;
client.OnPresenceUpdate += OnPresenceUpdate;
settingsManager.SettingsPropertyChanged += (sender, args) =>
{
if (args.PropertyName == nameof(settingsManager.Settings.IsDiscordRichPresenceEnabled))
{
UpdateState();
}
};
EventManager.Instance.RunningPackageStatusChanged += OnRunningPackageStatusChanged;
}
private void OnReady(object sender, ReadyMessage args)
{
logger.LogInformation("Received Ready from user {User}", args.User.Username);
}
private void OnError(object sender, ErrorMessage args)
{
logger.LogWarning("Received Error: {Message}", args.Message);
}
private void OnClose(object sender, CloseMessage args)
{
logger.LogInformation("Received Close: {Reason}", args.Reason);
}
private void OnPresenceUpdate(object sender, PresenceMessage args)
{
logger.LogDebug("Received Update: {Presence}", args.Presence.ToString());
}
private void OnRunningPackageStatusChanged(object? sender, RunningPackageStatusChangedEventArgs args)
{
if (!client.IsInitialized || !settingsManager.Settings.IsDiscordRichPresenceEnabled) return;
if (args.CurrentPackagePair is null)
{
client.SetPresence(DefaultPresence);
}
else
{
var presence = DefaultPresence;
var packageTitle = args.CurrentPackagePair.BasePackage switch
{
A3WebUI => "Automatic1111 Web UI",
VladAutomatic => "SD.Next Web UI",
ComfyUI => "ComfyUI",
VoltaML => "VoltaML",
InvokeAI => "InvokeAI",
_ => "Stable Diffusion"
};
presence.State = $"Running {packageTitle}";
presence.Assets.SmallImageText = presence.State;
presence.Assets.SmallImageKey = args.CurrentPackagePair.BasePackage switch
{
ComfyUI => "fa_diagram_project",
VoltaML => "ic_package_voltaml",
InvokeAI => "ic_package_invokeai",
_ => "ic_fluent_box_512_filled"
};
presence.WithTimestamps(new Timestamps
{
StartUnixMilliseconds = (ulong?) DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
});
client.SetPresence(presence);
}
}
public void UpdateState()
{
// Set initial rich presence
if (settingsManager.Settings.IsDiscordRichPresenceEnabled)
{
lock (client)
{
if (!client.IsInitialized)
{
client.Initialize();
client.SetPresence(DefaultPresence);
}
}
}
else
{
lock (client)
{
if (client.IsInitialized)
{
client.ClearPresence();
client.Deinitialize();
}
}
}
}
public void Dispose()
{
if (!isDisposed)
{
if (client.IsInitialized)
{
client.ClearPresence();
}
client.Dispose();
EventManager.Instance.RunningPackageStatusChanged -= OnRunningPackageStatusChanged;
}
isDisposed = true;
GC.SuppressFinalize(this);
}
~DiscordRichPresenceService()
{
Dispose();
}
}

8
StabilityMatrix.Avalonia/Services/IDiscordRichPresenceService.cs

@ -0,0 +1,8 @@
using System;
namespace StabilityMatrix.Avalonia.Services;
public interface IDiscordRichPresenceService : IDisposable
{
public void UpdateState();
}

3
StabilityMatrix.Avalonia/StabilityMatrix.Avalonia.csproj

@ -8,7 +8,7 @@
<ApplicationManifest>app.manifest</ApplicationManifest>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
<ApplicationIcon>./Assets/Icon.ico</ApplicationIcon>
<Version>2.1.0-dev.1</Version>
<Version>2.1.1-dev.1</Version>
<InformationalVersion>$(Version)</InformationalVersion>
<EnableWindowsTargeting>true</EnableWindowsTargeting>
</PropertyGroup>
@ -24,6 +24,7 @@
<PackageReference Include="Avalonia.Xaml.Behaviors" Version="11.0.0.1" />
<PackageReference Include="AvaloniaEdit.TextMate" Version="11.0.0" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.1" />
<PackageReference Include="DiscordRichPresence" Version="1.2.1.24" />
<PackageReference Include="FluentAvaloniaUI" Version="2.0.0" />
<PackageReference Include="FluentIcons.Avalonia" Version="1.1.207" />
<PackageReference Include="FluentIcons.FluentAvalonia" Version="1.1.207" />

3
StabilityMatrix.Avalonia/ViewModels/LaunchPageViewModel.cs

@ -249,6 +249,8 @@ public partial class LaunchPageViewModel : PageViewModelBase, IDisposable, IAsyn
await basePackage.RunPackage(packagePath, command, userArgsString);
RunningPackage = basePackage;
EventManager.Instance.OnRunningPackageStatusChanged(new PackagePair(activeInstall, basePackage));
}
// Unpacks sitecustomize.py to the target venv
@ -388,6 +390,7 @@ public partial class LaunchPageViewModel : PageViewModelBase, IDisposable, IAsyn
private void OnProcessExited(object? sender, int exitCode)
{
EventManager.Instance.OnRunningPackageStatusChanged(null);
Dispatcher.UIThread.InvokeAsync(async () =>
{
logger.LogTrace("Process exited ({Code}) at {Time:g}",

10
StabilityMatrix.Avalonia/ViewModels/MainWindowViewModel.cs

@ -23,6 +23,7 @@ public partial class MainWindowViewModel : ViewModelBase
{
private readonly ISettingsManager settingsManager;
private readonly ServiceManager<ViewModelBase> dialogFactory;
private readonly IDiscordRichPresenceService discordRichPresenceService;
public string Greeting => "Welcome to Avalonia!";
[ObservableProperty]
@ -40,10 +41,14 @@ public partial class MainWindowViewModel : ViewModelBase
public ProgressManagerViewModel ProgressManagerViewModel { get; init; }
public UpdateViewModel UpdateViewModel { get; init; }
public MainWindowViewModel(ISettingsManager settingsManager, ServiceManager<ViewModelBase> dialogFactory)
public MainWindowViewModel(
ISettingsManager settingsManager,
IDiscordRichPresenceService discordRichPresenceService,
ServiceManager<ViewModelBase> dialogFactory)
{
this.settingsManager = settingsManager;
this.dialogFactory = dialogFactory;
this.discordRichPresenceService = discordRichPresenceService;
ProgressManagerViewModel = dialogFactory.Get<ProgressManagerViewModel>();
UpdateViewModel = dialogFactory.Get<UpdateViewModel>();
@ -74,6 +79,9 @@ public partial class MainWindowViewModel : ViewModelBase
return;
}
// Initialize Discord Rich Presence (this needs LibraryDir so is set here)
discordRichPresenceService.UpdateState();
// Index checkpoints if we dont have
Task.Run(() => settingsManager.IndexCheckpoints()).SafeFireAndForget();

11
StabilityMatrix.Avalonia/ViewModels/SettingsViewModel.cs

@ -44,6 +44,7 @@ public partial class SettingsViewModel : PageViewModelBase
private readonly IPrerequisiteHelper prerequisiteHelper;
private readonly IPyRunner pyRunner;
private readonly ServiceManager<ViewModelBase> dialogFactory;
public SharedState SharedState { get; }
public override string Title => "Settings";
@ -66,6 +67,9 @@ public partial class SettingsViewModel : PageViewModelBase
// Shared folder options
[ObservableProperty] private bool removeSymlinksOnShutdown;
// Integrations section
[ObservableProperty] private bool isDiscordRichPresenceEnabled;
// Debug section
[ObservableProperty] private string? debugPaths;
[ObservableProperty] private string? debugCompatInfo;
@ -90,14 +94,19 @@ public partial class SettingsViewModel : PageViewModelBase
this.prerequisiteHelper = prerequisiteHelper;
this.pyRunner = pyRunner;
this.dialogFactory = dialogFactory;
SharedState = sharedState;
SelectedTheme = settingsManager.Settings.Theme ?? AvailableThemes[1];
RemoveSymlinksOnShutdown = settingsManager.Settings.RemoveFolderLinksOnShutdown;
settingsManager.RelayPropertyFor(this,
vm => vm.SelectedTheme,
settings => settings.Theme);
settingsManager.RelayPropertyFor(this,
vm => vm.IsDiscordRichPresenceEnabled,
settings => settings.IsDiscordRichPresenceEnabled);
}
partial void OnSelectedThemeChanged(string? value)

26
StabilityMatrix.Avalonia/Views/SettingsPage.axaml

@ -6,7 +6,7 @@
xmlns:ui="using:FluentAvalonia.UI.Controls"
xmlns:mocks="clr-namespace:StabilityMatrix.Avalonia.DesignData"
xmlns:controls="clr-namespace:StabilityMatrix.Avalonia.Controls"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="700"
x:DataType="vm:SettingsViewModel"
x:CompileBindings="True"
d:DataContext="{x:Static mocks:DesignData.SettingsViewModel}"
@ -53,7 +53,7 @@
Description="Select this option if you're having problems moving Stability Matrix to another drive"
Margin="8,8">
<ui:SettingsExpander.Footer>
<CheckBox Margin="8"
<CheckBox Margin="4"
IsChecked="{Binding RemoveSymlinksOnShutdown}"/>
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
@ -108,6 +108,28 @@
</StackPanel>
</Grid>
<!-- Integrations -->
<Grid RowDefinitions="auto,*">
<TextBlock
FontWeight="Medium"
Text="Integrations"
Margin="0,16,0,8" />
<StackPanel Grid.Row="1">
<ui:SettingsExpander
Header="Discord Rich Presence"
Margin="8,0">
<ui:SettingsExpander.IconSource>
<controls:FASymbolIconSource Symbol="fa-brands fa-discord"/>
</ui:SettingsExpander.IconSource>
<ui:SettingsExpander.Footer>
<ToggleSwitch
IsChecked="{Binding IsDiscordRichPresenceEnabled}"
Margin="4" />
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
</StackPanel>
</Grid>
<!-- System Options -->
<Grid RowDefinitions="auto,*">
<TextBlock

8
StabilityMatrix.Core/Helper/EventManager.cs

@ -1,8 +1,11 @@
using StabilityMatrix.Core.Models.Progress;
using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.Progress;
using StabilityMatrix.Core.Models.Update;
namespace StabilityMatrix.Core.Helper;
public record struct RunningPackageStatusChangedEventArgs(PackagePair? CurrentPackagePair);
public class EventManager
{
public static EventManager Instance { get; } = new();
@ -22,6 +25,7 @@ public class EventManager
public event EventHandler<Guid> PackageLaunchRequested;
public event EventHandler? ScrollToBottomRequested;
public event EventHandler<ProgressItem>? ProgressChanged;
public event EventHandler<RunningPackageStatusChangedEventArgs>? RunningPackageStatusChanged;
public void OnGlobalProgressChanged(int progress) => GlobalProgressChanged?.Invoke(this, progress);
public void RequestPageChange(Type pageType) => PageChangeRequested?.Invoke(this, pageType);
@ -36,4 +40,6 @@ public class EventManager
ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);
public void OnProgressChanged(ProgressItem progress) =>
ProgressChanged?.Invoke(this, progress);
public void OnRunningPackageStatusChanged(PackagePair? currentPackagePair) =>
RunningPackageStatusChanged?.Invoke(this, new RunningPackageStatusChangedEventArgs(currentPackagePair));
}

9
StabilityMatrix.Core/Models/PackagePair.cs

@ -0,0 +1,9 @@
using StabilityMatrix.Core.Models.Packages;
namespace StabilityMatrix.Core.Models;
/// <summary>
/// Pair of InstalledPackage and BasePackage
/// </summary>
public record PackagePair(InstalledPackage InstalledPackage, BasePackage BasePackage);

2
StabilityMatrix.Core/Models/Settings/Settings.cs

@ -45,6 +45,8 @@ public class Settings
public bool RemoveFolderLinksOnShutdown { get; set; }
public bool IsDiscordRichPresenceEnabled { get; set; }
public Dictionary<string, string>? EnvironmentVariables { get; set; }
public HashSet<string>? InstalledModelHashes { get; set; } = new();

Loading…
Cancel
Save