Browse Source

Merge branch 'main' into inference

pull/165/head
Ionite 1 year ago committed by GitHub
parent
commit
e46877e68d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 8
      CHANGELOG.md
  2. 13
      StabilityMatrix.Avalonia/App.axaml.cs
  3. 408
      StabilityMatrix.Avalonia/Controls/AutoGrid.cs
  4. 37
      StabilityMatrix.Avalonia/DesignData/DesignData.cs
  5. 52
      StabilityMatrix.Avalonia/Languages/Cultures.cs
  6. 143
      StabilityMatrix.Avalonia/Languages/Resources.Designer.cs
  7. 23
      StabilityMatrix.Avalonia/Languages/Resources.ja-JP.resx
  8. 48
      StabilityMatrix.Avalonia/Languages/Resources.resx
  9. 15
      StabilityMatrix.Avalonia/StabilityMatrix.Avalonia.csproj
  10. 33
      StabilityMatrix.Avalonia/ViewModels/CheckpointBrowserViewModel.cs
  11. 70
      StabilityMatrix.Avalonia/ViewModels/CheckpointManager/CheckpointFile.cs
  12. 4
      StabilityMatrix.Avalonia/ViewModels/CheckpointManager/CheckpointFolder.cs
  13. 32
      StabilityMatrix.Avalonia/ViewModels/CheckpointsPageViewModel.cs
  14. 8
      StabilityMatrix.Avalonia/ViewModels/Dialogs/InstallerViewModel.cs
  15. 2
      StabilityMatrix.Avalonia/ViewModels/Dialogs/OneClickInstallViewModel.cs
  16. 221
      StabilityMatrix.Avalonia/ViewModels/NewCheckpointsPageViewModel.cs
  17. 46
      StabilityMatrix.Avalonia/ViewModels/SettingsViewModel.cs
  18. 2
      StabilityMatrix.Avalonia/Views/CheckpointBrowserPage.axaml
  19. 40
      StabilityMatrix.Avalonia/Views/CheckpointsPage.axaml
  20. 105
      StabilityMatrix.Avalonia/Views/NewCheckpointsPage.axaml
  21. 11
      StabilityMatrix.Avalonia/Views/NewCheckpointsPage.axaml.cs
  22. 773
      StabilityMatrix.Avalonia/Views/SettingsPage.axaml
  23. 18
      StabilityMatrix.Core/Models/Api/CivitModelsRequest.cs
  24. 4
      StabilityMatrix.Core/Models/Api/CivitSortMode.cs
  25. 8
      StabilityMatrix.Core/Models/Packages/BaseGitPackage.cs
  26. 2
      StabilityMatrix.Core/Models/Packages/BasePackage.cs
  27. 2
      StabilityMatrix.Core/Models/Packages/InvokeAI.cs
  28. 47
      StabilityMatrix.Core/Models/Packages/VladAutomatic.cs
  29. 1
      StabilityMatrix.Core/Models/Settings/Settings.cs

8
CHANGELOG.md

@ -6,17 +6,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning 2.0](https://semver.org/spec/v2.0.0.html).
## v2.3.0
### Added
- New installable Package - [Fooocus](https://github.com/lllyasviel/Fooocus)
- Added "Select New Data Directory" button to Settings
- Pause/Resume/Cancel buttons on downloads popup. Paused downloads persists and may be resumed after restarting the app
### Fixed
- Fixed issue where model version wouldn't be selected in the "All Versions" section of the Model Browser
- Improved Checkpoints page indexing performance
- Fixed issue where Checkpoints page may not show all checkpoints after clearing search filter
- Fixed issue where Checkpoints page may show incorrect checkpoints for the given filter after changing pages
### Changed
- Changed update method for SD.Next to use the built-in upgrade functionality
## v2.2.1
### Fixed
- Fixed SD.Next shared folders config not working with new config format, reverted to Junctions / Symlinks
## v2.2.1

13
StabilityMatrix.Avalonia/App.axaml.cs

@ -35,12 +35,14 @@ using StabilityMatrix.Avalonia.Controls;
using StabilityMatrix.Avalonia.Controls.CodeCompletion;
using StabilityMatrix.Avalonia.DesignData;
using StabilityMatrix.Avalonia.Helpers;
using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.Models;
using StabilityMatrix.Avalonia.Models.TagCompletion;
using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels;
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;
@ -62,8 +64,6 @@ using StabilityMatrix.Core.Python;
using StabilityMatrix.Core.Services;
using StabilityMatrix.Core.Updater;
using Application = Avalonia.Application;
using CheckpointFile = StabilityMatrix.Avalonia.ViewModels.CheckpointManager.CheckpointFile;
using CheckpointFolder = StabilityMatrix.Avalonia.ViewModels.CheckpointManager.CheckpointFolder;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace StabilityMatrix.Avalonia;
@ -199,7 +199,12 @@ public sealed class App : Application
Services = services.BuildServiceProvider();
var settingsManager = Services.GetRequiredService<ISettingsManager>();
settingsManager.TryFindLibrary();
if (settingsManager.TryFindLibrary())
{
Cultures.TrySetSupportedCulture(settingsManager.Settings.Language);
}
Services.GetRequiredService<ProgressManagerViewModel>().StartEventListener();
}
@ -210,6 +215,7 @@ public sealed class App : Application
.AddSingleton<InferenceSettingsViewModel>()
.AddSingleton<CheckpointBrowserViewModel>()
.AddSingleton<CheckpointsPageViewModel>()
.AddSingleton<NewCheckpointsPageViewModel>()
.AddSingleton<LaunchPageViewModel>()
.AddSingleton<ProgressManagerViewModel>()
.AddSingleton<InferenceViewModel>();
@ -334,6 +340,7 @@ public sealed class App : Application
services.AddTransient<UpscalerCard>();
services.AddTransient<ModelCard>();
services.AddTransient<BatchSizeCard>();
services.AddSingleton<NewCheckpointsPage>();
// Dialogs
services.AddTransient<SelectDataDirectoryDialog>();

408
StabilityMatrix.Avalonia/Controls/AutoGrid.cs

@ -0,0 +1,408 @@
// Modified from https://github.com/AvaloniaUI/AvaloniaAutoGrid
/*The MIT License (MIT)
Copyright (c) 2013 Charles Brown (carbonrobot)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Layout;
namespace StabilityMatrix.Avalonia.Controls;
/// <summary>
/// Defines a flexible grid area that consists of columns and rows.
/// Depending on the orientation, either the rows or the columns are auto-generated,
/// and the children's position is set according to their index.
/// </summary>
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
public class AutoGrid : Grid
{
/// <summary>
/// Gets or sets the child horizontal alignment.
/// </summary>
/// <value>The child horizontal alignment.</value>
[Category("Layout"), Description("Presets the horizontal alignment of all child controls")]
public HorizontalAlignment? ChildHorizontalAlignment
{
get => (HorizontalAlignment?)GetValue(ChildHorizontalAlignmentProperty);
set => SetValue(ChildHorizontalAlignmentProperty, value);
}
/// <summary>
/// Gets or sets the child margin.
/// </summary>
/// <value>The child margin.</value>
[Category("Layout"), Description("Presets the margin of all child controls")]
public Thickness? ChildMargin
{
get => (Thickness?)GetValue(ChildMarginProperty);
set => SetValue(ChildMarginProperty, value);
}
/// <summary>
/// Gets or sets the child vertical alignment.
/// </summary>
/// <value>The child vertical alignment.</value>
[Category("Layout"), Description("Presets the vertical alignment of all child controls")]
public VerticalAlignment? ChildVerticalAlignment
{
get => (VerticalAlignment?)GetValue(ChildVerticalAlignmentProperty);
set => SetValue(ChildVerticalAlignmentProperty, value);
}
/// <summary>
/// Gets or sets the column count
/// </summary>
[Category("Layout"), Description("Defines a set number of columns")]
public int ColumnCount
{
get => (int)GetValue(ColumnCountProperty)!;
set => SetValue(ColumnCountProperty, value);
}
/// <summary>
/// Gets or sets the fixed column width
/// </summary>
[Category("Layout"), Description("Presets the width of all columns set using the ColumnCount property")]
public GridLength ColumnWidth
{
get => (GridLength)GetValue(ColumnWidthProperty)!;
set => SetValue(ColumnWidthProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether the children are automatically indexed.
/// <remarks>
/// The default is <c>true</c>.
/// Note that if children are already indexed, setting this property to <c>false</c> will not remove their indices.
/// </remarks>
/// </summary>
[Category("Layout"), Description("Set to false to disable the auto layout functionality")]
public bool IsAutoIndexing
{
get => (bool)GetValue(IsAutoIndexingProperty)!;
set => SetValue(IsAutoIndexingProperty, value);
}
/// <summary>
/// Gets or sets the orientation.
/// <remarks>The default is Vertical.</remarks>
/// </summary>
/// <value>The orientation.</value>
[Category("Layout"), Description("Defines the directionality of the autolayout. Use vertical for a column first layout, horizontal for a row first layout.")]
public Orientation Orientation
{
get => (Orientation)GetValue(OrientationProperty)!;
set => SetValue(OrientationProperty, value);
}
/// <summary>
/// Gets or sets the number of rows
/// </summary>
[Category("Layout"), Description("Defines a set number of rows")]
public int RowCount
{
get => (int)GetValue(RowCountProperty)!;
set => SetValue(RowCountProperty, value);
}
/// <summary>
/// Gets or sets the fixed row height
/// </summary>
[Category("Layout"), Description("Presets the height of all rows set using the RowCount property")]
public GridLength RowHeight
{
get => (GridLength)GetValue(RowHeightProperty)!;
set => SetValue(RowHeightProperty, value);
}
/// <summary>
/// Handles the column count changed event
/// </summary>
public static void ColumnCountChanged(AvaloniaPropertyChangedEventArgs e)
{
if ((int)e.NewValue! < 0)
return;
var grid = (AutoGrid)e.Sender;
// look for an existing column definition for the height
var width = grid.ColumnWidth;
if (!grid.IsSet(ColumnWidthProperty) && grid.ColumnDefinitions.Count > 0)
width = grid.ColumnDefinitions[0].Width;
// clear and rebuild
grid.ColumnDefinitions.Clear();
for (var i = 0; i < (int)e.NewValue; i++)
grid.ColumnDefinitions.Add(
new ColumnDefinition() { Width = width });
}
/// <summary>
/// Handle the fixed column width changed event
/// </summary>
public static void FixedColumnWidthChanged(AvaloniaPropertyChangedEventArgs e)
{
var grid = (AutoGrid)e.Sender;
// add a default column if missing
if (grid.ColumnDefinitions.Count == 0)
grid.ColumnDefinitions.Add(new ColumnDefinition());
// set all existing columns to this width
foreach (var t in grid.ColumnDefinitions)
t.Width = (GridLength)e.NewValue!;
}
/// <summary>
/// Handle the fixed row height changed event
/// </summary>
public static void FixedRowHeightChanged(AvaloniaPropertyChangedEventArgs e)
{
var grid = (AutoGrid)e.Sender;
// add a default row if missing
if (grid.RowDefinitions.Count == 0)
grid.RowDefinitions.Add(new RowDefinition());
// set all existing rows to this height
foreach (var t in grid.RowDefinitions)
t.Height = (GridLength)e.NewValue!;
}
/// <summary>
/// Handles the row count changed event
/// </summary>
public static void RowCountChanged(AvaloniaPropertyChangedEventArgs e)
{
if ((int)e.NewValue! < 0)
return;
var grid = (AutoGrid)e.Sender;
// look for an existing row to get the height
var height = grid.RowHeight;
if (!grid.IsSet(RowHeightProperty) && grid.RowDefinitions.Count > 0)
height = grid.RowDefinitions[0].Height;
// clear and rebuild
grid.RowDefinitions.Clear();
for (var i = 0; i < (int)e.NewValue; i++)
grid.RowDefinitions.Add(
new RowDefinition() { Height = height });
}
/// <summary>
/// Called when [child horizontal alignment changed].
/// </summary>
private static void OnChildHorizontalAlignmentChanged(AvaloniaPropertyChangedEventArgs e)
{
var grid = (AutoGrid)e.Sender;
foreach (var child in grid.Children)
{
child.SetValue(HorizontalAlignmentProperty,
grid.ChildHorizontalAlignment ?? AvaloniaProperty.UnsetValue);
}
}
/// <summary>
/// Called when [child layout changed].
/// </summary>
private static void OnChildMarginChanged(AvaloniaPropertyChangedEventArgs e)
{
var grid = (AutoGrid)e.Sender;
foreach (var child in grid.Children)
{
child.SetValue(MarginProperty, grid.ChildMargin ?? AvaloniaProperty.UnsetValue);
}
}
/// <summary>
/// Called when [child vertical alignment changed].
/// </summary>
private static void OnChildVerticalAlignmentChanged(AvaloniaPropertyChangedEventArgs e)
{
var grid = (AutoGrid)e.Sender;
foreach (var child in grid.Children)
{
child.SetValue(VerticalAlignmentProperty, grid.ChildVerticalAlignment ?? AvaloniaProperty.UnsetValue);
}
}
/// <summary>
/// Apply child margins and layout effects such as alignment
/// </summary>
private void ApplyChildLayout(Control child)
{
if (ChildMargin != null)
{
child.SetValue(MarginProperty, ChildMargin.Value, BindingPriority.Template);
}
if (ChildHorizontalAlignment != null)
{
child.SetValue(HorizontalAlignmentProperty, ChildHorizontalAlignment.Value, BindingPriority.Template);
}
if (ChildVerticalAlignment != null)
{
child.SetValue(VerticalAlignmentProperty, ChildVerticalAlignment.Value, BindingPriority.Template);
}
}
/// <summary>
/// Clamp a value to its maximum.
/// </summary>
private int Clamp(int value, int max)
{
return (value > max) ? max : value;
}
/// <summary>
/// Perform the grid layout of row and column indexes
/// </summary>
private void PerformLayout()
{
var fillRowFirst = Orientation == Orientation.Horizontal;
var rowCount = RowDefinitions.Count;
var colCount = ColumnDefinitions.Count;
if (rowCount == 0 || colCount == 0)
return;
var position = 0;
var skip = new bool[rowCount, colCount];
foreach (var child in Children.OfType<Control>())
{
var childIsCollapsed = !child.IsVisible;
if (IsAutoIndexing && !childIsCollapsed)
{
if (fillRowFirst)
{
var row = Clamp(position / colCount, rowCount - 1);
var col = Clamp(position % colCount, colCount - 1);
if (skip[row, col])
{
position++;
row = (position / colCount);
col = (position % colCount);
}
SetRow(child, row);
SetColumn(child, col);
position += GetColumnSpan(child);
var offset = GetRowSpan(child) - 1;
while (offset > 0)
{
skip[row + offset--, col] = true;
}
}
else
{
var row = Clamp(position % rowCount, rowCount - 1);
var col = Clamp(position / rowCount, colCount - 1);
if (skip[row, col])
{
position++;
row = position % rowCount;
col = position / rowCount;
}
SetRow(child, row);
SetColumn(child, col);
position += GetRowSpan(child);
var offset = GetColumnSpan(child) - 1;
while (offset > 0)
{
skip[row, col + offset--] = true;
}
}
}
ApplyChildLayout(child);
}
}
public static readonly AvaloniaProperty<HorizontalAlignment?> ChildHorizontalAlignmentProperty =
AvaloniaProperty.Register<AutoGrid, HorizontalAlignment?>("ChildHorizontalAlignment");
public static readonly AvaloniaProperty<Thickness?> ChildMarginProperty =
AvaloniaProperty.Register<AutoGrid, Thickness?>("ChildMargin");
public static readonly AvaloniaProperty<VerticalAlignment?> ChildVerticalAlignmentProperty =
AvaloniaProperty.Register<AutoGrid, VerticalAlignment?>("ChildVerticalAlignment");
public static readonly AvaloniaProperty<int> ColumnCountProperty =
AvaloniaProperty.RegisterAttached<Control, int>("ColumnCount", typeof(AutoGrid), 1);
public static readonly AvaloniaProperty<GridLength> ColumnWidthProperty =
AvaloniaProperty.RegisterAttached<Control, GridLength>("ColumnWidth", typeof(AutoGrid), GridLength.Auto);
public static readonly AvaloniaProperty<bool> IsAutoIndexingProperty =
AvaloniaProperty.Register<AutoGrid, bool>("IsAutoIndexing", true);
public static readonly AvaloniaProperty<Orientation> OrientationProperty =
AvaloniaProperty.Register<AutoGrid, Orientation>("Orientation", Orientation.Vertical);
public static readonly AvaloniaProperty<int> RowCountProperty =
AvaloniaProperty.RegisterAttached<Control, int>("RowCount", typeof(AutoGrid), 1);
public static readonly AvaloniaProperty<GridLength> RowHeightProperty =
AvaloniaProperty.RegisterAttached<Control, GridLength>("RowHeight", typeof(AutoGrid), GridLength.Auto);
static AutoGrid()
{
AffectsMeasure<AutoGrid>(ChildHorizontalAlignmentProperty, ChildMarginProperty,
ChildVerticalAlignmentProperty, ColumnCountProperty, ColumnWidthProperty, IsAutoIndexingProperty, OrientationProperty,
RowHeightProperty);
ChildHorizontalAlignmentProperty.Changed.Subscribe(OnChildHorizontalAlignmentChanged);
ChildMarginProperty.Changed.Subscribe(OnChildMarginChanged);
ChildVerticalAlignmentProperty.Changed.Subscribe(OnChildVerticalAlignmentChanged);
ColumnCountProperty.Changed.Subscribe(ColumnCountChanged);
RowCountProperty.Changed.Subscribe(RowCountChanged);
ColumnWidthProperty.Changed.Subscribe(FixedColumnWidthChanged);
RowHeightProperty.Changed.Subscribe(FixedRowHeightChanged);
}
#region Overrides
/// <summary>
/// Measures the children of a <see cref="T:System.Windows.Controls.Grid"/> in anticipation of arranging them during the <see cref="M:ArrangeOverride"/> pass.
/// </summary>
/// <param name="constraint">Indicates an upper limit size that should not be exceeded.</param>
/// <returns>
/// <see cref="Size"/> that represents the required size to arrange child content.
/// </returns>
protected override Size MeasureOverride(Size constraint)
{
PerformLayout();
return base.MeasureOverride(constraint);
}
#endregion Overrides
}

37
StabilityMatrix.Avalonia/DesignData/DesignData.cs

@ -203,6 +203,11 @@ public static class DesignData
{
Title = "StableDiffusion",
DirectoryPath = "Packages/Lora/Subfolder",
},
new(settingsManager, downloadService, modelFinder)
{
Title = "Lora",
DirectoryPath = "Packages/StableDiffusion/Subfolder",
}
},
CheckpointFiles = new AdvancedObservableList<CheckpointFile>
@ -234,6 +239,35 @@ public static class DesignData
})
};
NewCheckpointsPageViewModel.AllCheckpoints = new ObservableCollection<CheckpointFile>
{
new()
{
FilePath = "~/Models/StableDiffusion/electricity-light.safetensors",
Title = "Auroral Background",
PreviewImagePath = "https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/" +
"78fd2a0a-42b6-42b0-9815-81cb11bb3d05/00009-2423234823.jpeg",
ConnectedModel = new ConnectedModelInfo
{
VersionName = "Lightning Auroral",
BaseModel = "SD 1.5",
ModelName = "Auroral Background",
ModelType = CivitModelType.Model,
FileMetadata = new CivitFileMetadata
{
Format = CivitModelFormat.SafeTensor,
Fp = CivitModelFpType.fp16,
Size = CivitModelSize.pruned,
}
}
},
new()
{
FilePath = "~/Models/Lora/model.safetensors",
Title = "Some model"
}
};
ProgressManagerViewModel.ProgressItems.AddRange(new ProgressItemViewModelBase[]
{
new ProgressItemViewModel(new ProgressItem(Guid.NewGuid(), "Test File.exe",
@ -283,6 +317,9 @@ public static class DesignData
public static CheckpointsPageViewModel CheckpointsPageViewModel =>
Services.GetRequiredService<CheckpointsPageViewModel>();
public static NewCheckpointsPageViewModel NewCheckpointsPageViewModel =>
Services.GetRequiredService<NewCheckpointsPageViewModel>();
public static SettingsViewModel SettingsViewModel =>
Services.GetRequiredService<SettingsViewModel>();

52
StabilityMatrix.Avalonia/Languages/Cultures.cs

@ -0,0 +1,52 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace StabilityMatrix.Avalonia.Languages;
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
public static class Cultures
{
public static CultureInfo Default { get; } = new("en-US");
public static CultureInfo Current => Resources.Culture;
public static readonly Dictionary<string, CultureInfo> SupportedCulturesByCode =
new Dictionary<string, CultureInfo>
{
["en-US"] = Default,
["ja-JP"] = new("ja-JP")
};
public static IReadOnlyList<CultureInfo> SupportedCultures
=> SupportedCulturesByCode.Values.ToImmutableList();
public static CultureInfo GetSupportedCultureOrDefault(string? cultureCode)
{
if (cultureCode is null
|| !SupportedCulturesByCode.TryGetValue(cultureCode, out var culture))
{
return Default;
}
return culture;
}
public static bool TrySetSupportedCulture(string? cultureCode)
{
if (cultureCode is null
|| !SupportedCulturesByCode.TryGetValue(cultureCode, out var culture))
{
return false;
}
Resources.Culture = culture;
return true;
}
public static bool TrySetSupportedCulture(CultureInfo? cultureInfo)
{
return cultureInfo is not null && TrySetSupportedCulture(cultureInfo.Name);
}
}

143
StabilityMatrix.Avalonia/Languages/Resources.Designer.cs generated

@ -0,0 +1,143 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace StabilityMatrix.Avalonia.Languages {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("StabilityMatrix.Avalonia.Languages.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Cancel.
/// </summary>
public static string Action_Cancel {
get {
return ResourceManager.GetString("Action_Cancel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Launch.
/// </summary>
public static string Action_Launch {
get {
return ResourceManager.GetString("Action_Launch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Quit.
/// </summary>
public static string Action_Quit {
get {
return ResourceManager.GetString("Action_Quit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Relaunch.
/// </summary>
public static string Action_Relaunch {
get {
return ResourceManager.GetString("Action_Relaunch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Relaunch Later.
/// </summary>
public static string Action_RelaunchLater {
get {
return ResourceManager.GetString("Action_RelaunchLater", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Save.
/// </summary>
public static string Action_Save {
get {
return ResourceManager.GetString("Action_Save", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Language.
/// </summary>
public static string Label_Language {
get {
return ResourceManager.GetString("Label_Language", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Relaunch Required.
/// </summary>
public static string Label_RelaunchRequired {
get {
return ResourceManager.GetString("Label_RelaunchRequired", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Relaunch is required for new language option to take effect.
/// </summary>
public static string Text_RelaunchRequiredToApplyLanguage {
get {
return ResourceManager.GetString("Text_RelaunchRequiredToApplyLanguage", resourceCulture);
}
}
}
}

23
StabilityMatrix.Avalonia/Languages/Resources.ja-JP.resx

@ -0,0 +1,23 @@
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Action_Save" xml:space="preserve">
<value>保存</value>
</data>
<data name="Action_Cancel" xml:space="preserve">
<value>戻る</value>
</data>
<data name="Label_Language" xml:space="preserve">
<value>言語</value>
</data>
</root>

48
StabilityMatrix.Avalonia/Languages/Resources.resx

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Action_Launch" xml:space="preserve">
<value>Launch</value>
</data>
<data name="Action_Quit" xml:space="preserve">
<value>Quit</value>
</data>
<data name="Action_Save" xml:space="preserve">
<value>Save</value>
</data>
<data name="Action_Cancel" xml:space="preserve">
<value>Cancel</value>
</data>
<data name="Label_Language" xml:space="preserve">
<value>Language</value>
</data>
<data name="Text_RelaunchRequiredToApplyLanguage" xml:space="preserve">
<value>Relaunch is required for new language option to take effect</value>
</data>
<data name="Action_Relaunch" xml:space="preserve">
<value>Relaunch</value>
</data>
<data name="Action_RelaunchLater" xml:space="preserve">
<value>Relaunch Later</value>
</data>
<data name="Label_RelaunchRequired" xml:space="preserve">
<value>Relaunch Required</value>
</data>
</root>

15
StabilityMatrix.Avalonia/StabilityMatrix.Avalonia.csproj

@ -89,4 +89,19 @@
<!-- Only for linux-64 -->
<AvaloniaResource Include="Assets\linux-x64\**" Condition="'$(RuntimeIdentifier)' == 'linux-x64'" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Languages\Resources.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Compile Update="Languages\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
</Project>

33
StabilityMatrix.Avalonia/ViewModels/CheckpointBrowserViewModel.cs

@ -17,6 +17,7 @@ using Refit;
using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.ViewModels.CheckpointBrowser;
using StabilityMatrix.Avalonia.ViewModels.CheckpointManager;
using StabilityMatrix.Avalonia.Views;
using StabilityMatrix.Core.Api;
using StabilityMatrix.Core.Attributes;
@ -250,9 +251,15 @@ public partial class CheckpointBrowserViewModel : PageViewModelBase
}).ToList();
allModelCards = updateCards;
ModelCards =
new ObservableCollection<CheckpointBrowserCardViewModel>(
updateCards.Where(FilterModelCardsPredicate));
var filteredCards = updateCards.Where(FilterModelCardsPredicate);
if (SortMode == CivitSortMode.Installed)
{
filteredCards =
filteredCards.OrderByDescending(x => x.UpdateCardText == "Update Available");
}
ModelCards =new ObservableCollection<CheckpointBrowserCardViewModel>(filteredCards);
}
TotalPages = metadata?.TotalPages ?? 1;
CanGoToPreviousPage = CurrentPageNumber > 1;
@ -310,6 +317,26 @@ public partial class CheckpointBrowserViewModel : PageViewModelBase
modelRequest.BaseModel = SelectedBaseModelType;
}
if (SortMode == CivitSortMode.Installed)
{
var connectedModels =
CheckpointFile.GetAllCheckpointFiles(settingsManager.ModelsDirectory)
.Where(c => c.IsConnectedModel);
if (SelectedModelType != CivitModelType.All)
{
connectedModels = connectedModels.Where(c => c.ModelType == SelectedModelType);
}
modelRequest = new CivitModelsRequest
{
CommaSeparatedModelIds = string.Join(",",
connectedModels.Select(c => c.ConnectedModel!.ModelId).GroupBy(m => m)
.Select(g => g.First())),
Types = SelectedModelType == CivitModelType.All ? null : new[] {SelectedModelType}
};
}
// See if query is cached
var cachedQuery = await liteDbContext.CivitModelQueryCache
.IncludeAll()

70
StabilityMatrix.Avalonia/ViewModels/CheckpointManager/CheckpointFile.cs

@ -14,6 +14,7 @@ using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Core.Extensions;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.Api;
using StabilityMatrix.Core.Models.Progress;
using StabilityMatrix.Core.Processes;
@ -46,6 +47,7 @@ public partial class CheckpointFile : ViewModelBase
public bool IsConnectedModel => ConnectedModel != null;
[ObservableProperty] private bool isLoading;
[ObservableProperty] private CivitModelType modelType;
public string FileName => Path.GetFileName((string?) FilePath);
@ -224,6 +226,39 @@ public partial class CheckpointFile : ViewModelBase
}
}
public static IEnumerable<CheckpointFile> GetAllCheckpointFiles(string modelsDirectory)
{
foreach (var file in Directory.EnumerateFiles(modelsDirectory, "*.*", SearchOption.AllDirectories))
{
if (!SupportedCheckpointExtensions.Any(ext => file.Contains(ext)))
continue;
var checkpointFile = new CheckpointFile
{
Title = Path.GetFileNameWithoutExtension(file),
FilePath = file,
};
var jsonPath = Path.Combine(Path.GetDirectoryName(file),
Path.GetFileNameWithoutExtension(file) + ".cm-info.json");
if (File.Exists(jsonPath))
{
var json = File.ReadAllText(jsonPath);
var connectedModelInfo = ConnectedModelInfo.FromJson(json);
checkpointFile.ConnectedModel = connectedModelInfo;
checkpointFile.ModelType = GetCivitModelType(file);
}
checkpointFile.PreviewImagePath = SupportedImageExtensions
.Select(ext => Path.Combine(Path.GetDirectoryName(file),
$"{Path.GetFileNameWithoutExtension(file)}.preview{ext}")).Where(File.Exists)
.FirstOrDefault();
yield return checkpointFile;
}
}
/// <summary>
/// Index with progress reporting.
/// </summary>
@ -238,4 +273,39 @@ public partial class CheckpointFile : ViewModelBase
yield return checkpointFile;
}
}
private static CivitModelType GetCivitModelType(string filePath)
{
if (filePath.Contains(SharedFolderType.StableDiffusion.ToString()))
{
return CivitModelType.Checkpoint;
}
if (filePath.Contains(SharedFolderType.ControlNet.ToString()))
{
return CivitModelType.Controlnet;
}
if (filePath.Contains(SharedFolderType.Lora.ToString()))
{
return CivitModelType.LORA;
}
if (filePath.Contains(SharedFolderType.TextualInversion.ToString()))
{
return CivitModelType.TextualInversion;
}
if (filePath.Contains(SharedFolderType.Hypernetwork.ToString()))
{
return CivitModelType.Hypernetwork;
}
if (filePath.Contains(SharedFolderType.LyCORIS.ToString()))
{
return CivitModelType.LoCon;
}
return CivitModelType.Unknown;
}
}

4
StabilityMatrix.Avalonia/ViewModels/CheckpointManager/CheckpointFolder.cs

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
@ -414,8 +415,7 @@ public partial class CheckpointFolder : ViewModelBase
{
// Create subfolder
var subFolder = new CheckpointFolder(settingsManager,
downloadService, modelFinder,
useCategoryVisibility: false)
downloadService, modelFinder, useCategoryVisibility: false)
{
Title = Path.GetFileName(folder),
DirectoryPath = folder,

32
StabilityMatrix.Avalonia/ViewModels/CheckpointsPageViewModel.cs

@ -73,6 +73,7 @@ public partial class CheckpointsPageViewModel : PageViewModelBase
public override async Task OnLoadedAsync()
{
var sw = Stopwatch.StartNew();
DisplayedCheckpointFolders = CheckpointFolders;
// Set UI states
@ -80,21 +81,23 @@ public partial class CheckpointsPageViewModel : PageViewModelBase
// Refresh search filter
OnSearchFilterChanged(string.Empty);
Logger.Info($"Loaded {DisplayedCheckpointFolders.Count} checkpoint folders in {sw.ElapsedMilliseconds}ms");
if (Design.IsDesignMode) return;
await Dispatcher.UIThread.InvokeAsync(async () =>
{
IsLoading = CheckpointFolders.Count == 0;
IsIndexing = CheckpointFolders.Count > 0;
await IndexFolders();
IsLoading = false;
IsIndexing = false;
});
IsLoading = CheckpointFolders.Count == 0;
IsIndexing = CheckpointFolders.Count > 0;
await IndexFolders();
IsLoading = false;
IsIndexing = false;
Logger.Info($"OnLoadedAsync in {sw.ElapsedMilliseconds}ms");
}
// ReSharper disable once UnusedParameterInPartialMethod
partial void OnSearchFilterChanged(string value)
{
var sw = Stopwatch.StartNew();
if (string.IsNullOrWhiteSpace(SearchFilter))
{
DisplayedCheckpointFolders = new ObservableCollection<CheckpointFolder>(
@ -103,15 +106,21 @@ public partial class CheckpointsPageViewModel : PageViewModelBase
x.SearchFilter = SearchFilter;
return x;
}));
sw.Stop();
Logger.Info($"OnSearchFilterChanged in {sw.ElapsedMilliseconds}ms");
return;
}
sw.Restart();
var filteredFolders = CheckpointFolders
.Where(ContainsSearchFilter).ToList();
foreach (var folder in filteredFolders)
{
folder.SearchFilter = SearchFilter;
}
sw.Stop();
Logger.Info($"ContainsSearchFilter in {sw.ElapsedMilliseconds}ms");
DisplayedCheckpointFolders = new ObservableCollection<CheckpointFolder>(filteredFolders);
}
@ -143,11 +152,13 @@ public partial class CheckpointsPageViewModel : PageViewModelBase
var folders = Directory.GetDirectories(modelsDirectory);
var sw = Stopwatch.StartNew();
// Index all folders
var indexTasks = folders.Select(async f =>
{
var checkpointFolder =
new CheckpointManager.CheckpointFolder(settingsManager, downloadService, modelFinder)
new CheckpointFolder(settingsManager, downloadService, modelFinder)
{
Title = Path.GetFileName(f),
DirectoryPath = f,
@ -159,6 +170,9 @@ public partial class CheckpointsPageViewModel : PageViewModelBase
await Task.WhenAll(indexTasks);
sw.Stop();
Logger.Info($"IndexFolders in {sw.ElapsedMilliseconds}ms");
// Set new observable collection, ordered by alphabetical order
CheckpointFolders =
new ObservableCollection<CheckpointFolder>(indexTasks

8
StabilityMatrix.Avalonia/ViewModels/Dialogs/InstallerViewModel.cs

@ -199,14 +199,14 @@ public partial class InstallerViewModel : ContentDialogViewModelBase
version = SelectedVersion?.TagName ??
throw new NullReferenceException("Selected version is null");
await DownloadPackage(version, false);
await DownloadPackage(version, false, null);
}
else
{
version = SelectedCommit?.Sha ??
throw new NullReferenceException("Selected commit is null");
await DownloadPackage(version, true);
await DownloadPackage(version, true, SelectedVersion!.TagName);
}
await InstallPackage();
@ -271,7 +271,7 @@ public partial class InstallerViewModel : ContentDialogViewModelBase
return branch == null ? version : $"{branch}@{version[..7]}";
}
private Task<string> DownloadPackage(string version, bool isCommitHash)
private Task<string> DownloadPackage(string version, bool isCommitHash, string? branch)
{
InstallProgress.Text = "Downloading package...";
@ -282,7 +282,7 @@ public partial class InstallerViewModel : ContentDialogViewModelBase
EventManager.Instance.OnGlobalProgressChanged((int) progress.Percentage);
});
return SelectedPackage.DownloadPackage(version, isCommitHash, progress);
return SelectedPackage.DownloadPackage(version, isCommitHash, branch, progress);
}
private async Task InstallPackage()

2
StabilityMatrix.Avalonia/ViewModels/Dialogs/OneClickInstallViewModel.cs

@ -157,7 +157,7 @@ public partial class OneClickInstallViewModel : ViewModelBase
EventManager.Instance.OnGlobalProgressChanged(OneClickInstallProgress);
});
await SelectedPackage.DownloadPackage(version, false, progress);
await SelectedPackage.DownloadPackage(version, false, version, progress);
SubHeaderText = "Download Complete";
OneClickInstallProgress = 100;
}

221
StabilityMatrix.Avalonia/ViewModels/NewCheckpointsPageViewModel.cs

@ -0,0 +1,221 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using AsyncAwaitBestPractices;
using Avalonia.Controls;
using Avalonia.Controls.Notifications;
using AvaloniaEdit.Utils;
using CommunityToolkit.Mvvm.ComponentModel;
using FluentAvalonia.UI.Controls;
using Microsoft.Extensions.Logging;
using Refit;
using StabilityMatrix.Avalonia.Controls;
using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.ViewModels.CheckpointManager;
using StabilityMatrix.Avalonia.ViewModels.Dialogs;
using StabilityMatrix.Avalonia.Views;
using StabilityMatrix.Avalonia.Views.Dialogs;
using StabilityMatrix.Core.Api;
using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Database;
using StabilityMatrix.Core.Extensions;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.Api;
using StabilityMatrix.Core.Services;
using Symbol = FluentIcons.Common.Symbol;
using SymbolIconSource = FluentIcons.FluentAvalonia.SymbolIconSource;
namespace StabilityMatrix.Avalonia.ViewModels;
[View(typeof(NewCheckpointsPage))]
public partial class NewCheckpointsPageViewModel : PageViewModelBase
{
private readonly ILogger<NewCheckpointsPageViewModel> logger;
private readonly ISettingsManager settingsManager;
private readonly ILiteDbContext liteDbContext;
private readonly ICivitApi civitApi;
private readonly ServiceManager<ViewModelBase> dialogFactory;
private readonly INotificationService notificationService;
public override string Title => "Checkpoint Manager";
public override IconSource IconSource => new SymbolIconSource
{Symbol = Symbol.Cellular5g, IsFilled = true};
public NewCheckpointsPageViewModel(ILogger<NewCheckpointsPageViewModel> logger,
ISettingsManager settingsManager, ILiteDbContext liteDbContext, ICivitApi civitApi,
ServiceManager<ViewModelBase> dialogFactory, INotificationService notificationService)
{
this.logger = logger;
this.settingsManager = settingsManager;
this.liteDbContext = liteDbContext;
this.civitApi = civitApi;
this.dialogFactory = dialogFactory;
this.notificationService = notificationService;
}
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ConnectedCheckpoints))]
[NotifyPropertyChangedFor(nameof(NonConnectedCheckpoints))]
private ObservableCollection<CheckpointFile> allCheckpoints = new();
[ObservableProperty]
private ObservableCollection<CivitModel> civitModels = new();
public ObservableCollection<CheckpointFile> ConnectedCheckpoints => new(
AllCheckpoints.Where(x => x.IsConnectedModel)
.OrderBy(x => x.ConnectedModel!.ModelName)
.ThenBy(x => x.ModelType)
.GroupBy(x => x.ConnectedModel!.ModelId)
.Select(x => x.First()));
public ObservableCollection<CheckpointFile> NonConnectedCheckpoints => new(
AllCheckpoints.Where(x => !x.IsConnectedModel).OrderBy(x => x.ModelType));
public override async Task OnLoadedAsync()
{
if (Design.IsDesignMode) return;
var files = CheckpointFile.GetAllCheckpointFiles(settingsManager.ModelsDirectory);
AllCheckpoints = new ObservableCollection<CheckpointFile>(files);
var connectedModelIds = ConnectedCheckpoints.Select(x => x.ConnectedModel.ModelId);
var modelRequest = new CivitModelsRequest
{
CommaSeparatedModelIds = string.Join(',', connectedModelIds)
};
// See if query is cached
var cachedQuery = await liteDbContext.CivitModelQueryCache
.IncludeAll()
.FindByIdAsync(ObjectHash.GetMd5Guid(modelRequest));
// If cached, update model cards
if (cachedQuery is not null)
{
CivitModels = new ObservableCollection<CivitModel>(cachedQuery.Items);
// Start remote query (background mode)
// Skip when last query was less than 2 min ago
var timeSinceCache = DateTimeOffset.UtcNow - cachedQuery.InsertedAt;
if (timeSinceCache?.TotalMinutes >= 2)
{
CivitQuery(modelRequest).SafeFireAndForget();
}
}
else
{
await CivitQuery(modelRequest);
}
}
public async Task ShowVersionDialog(int modelId)
{
var model = CivitModels.FirstOrDefault(m => m.Id == modelId);
if (model == null)
{
notificationService.Show(new Notification("Model has no versions available",
"This model has no versions available for download", NotificationType.Warning));
return;
}
var versions = model.ModelVersions;
if (versions is null || versions.Count == 0)
{
notificationService.Show(new Notification("Model has no versions available",
"This model has no versions available for download", NotificationType.Warning));
return;
}
var dialog = new BetterContentDialog
{
Title = model.Name,
IsPrimaryButtonEnabled = false,
IsSecondaryButtonEnabled = false,
IsFooterVisible = false,
MaxDialogWidth = 750,
};
var viewModel = dialogFactory.Get<SelectModelVersionViewModel>();
viewModel.Dialog = dialog;
viewModel.Versions = versions.Select(version =>
new ModelVersionViewModel(
settingsManager.Settings.InstalledModelHashes ?? new HashSet<string>(), version))
.ToImmutableArray();
viewModel.SelectedVersionViewModel = viewModel.Versions[0];
dialog.Content = new SelectModelVersionDialog
{
DataContext = viewModel
};
var result = await dialog.ShowAsync();
if (result != ContentDialogResult.Primary)
{
return;
}
var selectedVersion = viewModel?.SelectedVersionViewModel?.ModelVersion;
var selectedFile = viewModel?.SelectedFile?.CivitFile;
}
private async Task CivitQuery(CivitModelsRequest request)
{
try
{
var modelResponse = await civitApi.GetModels(request);
var models = modelResponse.Items;
// Filter out unknown model types and archived/taken-down models
models = models.Where(m => m.Type.ConvertTo<SharedFolderType>() > 0)
.Where(m => m.Mode == null).ToList();
// Database update calls will invoke `OnModelsUpdated`
// Add to database
await liteDbContext.UpsertCivitModelAsync(models);
// Add as cache entry
var cacheNew = await liteDbContext.UpsertCivitModelQueryCacheEntryAsync(
new CivitModelQueryCacheEntry
{
Id = ObjectHash.GetMd5Guid(request),
InsertedAt = DateTimeOffset.UtcNow,
Request = request,
Items = models,
Metadata = modelResponse.Metadata
});
if (cacheNew)
{
CivitModels = new ObservableCollection<CivitModel>(models);
}
}
catch (OperationCanceledException)
{
notificationService.Show(new Notification("Request to CivitAI timed out",
"Could not check for checkpoint updates. Please try again later."));
logger.LogWarning($"CivitAI query timed out ({request})");
}
catch (HttpRequestException e)
{
notificationService.Show(new Notification("CivitAI can't be reached right now",
"Could not check for checkpoint updates. Please try again later."));
logger.LogWarning(e, $"CivitAI query HttpRequestException ({request})");
}
catch (ApiException e)
{
notificationService.Show(new Notification("CivitAI can't be reached right now",
"Could not check for checkpoint updates. Please try again later."));
logger.LogWarning(e, $"CivitAI query ApiException ({request})");
}
catch (Exception e)
{
notificationService.Show(new Notification("CivitAI can't be reached right now",
$"Unknown exception during CivitAI query: {e.GetType().Name}"));
logger.LogError(e, $"CivitAI query unknown exception ({request})");
}
}
}

46
StabilityMatrix.Avalonia/ViewModels/SettingsViewModel.cs

@ -4,6 +4,7 @@ using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
@ -19,6 +20,7 @@ using Avalonia.Controls.Primitives;
using Avalonia.Media.Imaging;
using Avalonia.Platform.Storage;
using Avalonia.Styling;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FluentAvalonia.UI.Controls;
@ -27,6 +29,7 @@ using SkiaSharp;
using StabilityMatrix.Avalonia.Controls;
using StabilityMatrix.Avalonia.Extensions;
using StabilityMatrix.Avalonia.Helpers;
using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.Models;
using StabilityMatrix.Avalonia.Models.TagCompletion;
using StabilityMatrix.Avalonia.Services;
@ -78,6 +81,11 @@ public partial class SettingsViewModel : PageViewModelBase
"System",
};
[ObservableProperty] private CultureInfo selectedLanguage;
// ReSharper disable once MemberCanBeMadeStatic.Global
public IReadOnlyList<CultureInfo> AvailableLanguages => Cultures.SupportedCultures;
public IReadOnlyList<float> AnimationScaleOptions { get; } = new[]
{
0f,
@ -140,6 +148,7 @@ public partial class SettingsViewModel : PageViewModelBase
SharedState = sharedState;
SelectedTheme = settingsManager.Settings.Theme ?? AvailableThemes[1];
SelectedLanguage = Cultures.GetSupportedCultureOrDefault(settingsManager.Settings.Language);
RemoveSymlinksOnShutdown = settingsManager.Settings.RemoveFolderLinksOnShutdown;
SelectedAnimationScale = settingsManager.Settings.AnimationScale;
@ -195,6 +204,43 @@ public partial class SettingsViewModel : PageViewModelBase
};
}
partial void OnSelectedLanguageChanged(CultureInfo? oldValue, CultureInfo newValue)
{
if (oldValue is null || newValue.Name == Cultures.Current.Name) return;
// Set locale
if (AvailableLanguages.Contains(newValue))
{
Logger.Info("Changing language from {Old} to {New}",
oldValue, newValue);
Cultures.TrySetSupportedCulture(newValue);
settingsManager.Transaction(s => s.Language = newValue.Name);
var dialog = new BetterContentDialog
{
Title = Resources.Label_RelaunchRequired,
Content = Resources.Text_RelaunchRequiredToApplyLanguage,
DefaultButton = ContentDialogButton.Primary,
PrimaryButtonText = Resources.Action_Relaunch,
CloseButtonText = Resources.Action_RelaunchLater
};
Dispatcher.UIThread.InvokeAsync(async () =>
{
if (await dialog.ShowAsync() == ContentDialogResult.Primary)
{
Process.Start(Compat.AppCurrentPath);
App.Shutdown();
}
});
}
else
{
Logger.Info("Requested invalid language change from {Old} to {New}",
oldValue, newValue);
}
}
partial void OnRemoveSymlinksOnShutdownChanged(bool value)
{
settingsManager.Transaction(s => s.RemoveFolderLinksOnShutdown = value);

2
StabilityMatrix.Avalonia/Views/CheckpointBrowserPage.axaml

@ -40,7 +40,7 @@
Margin="0,8,0,8"
Height="300"
StretchDirection="Both"
CornerRadius="4"
CornerRadius="8"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Center"
Source="{Binding CardImage}"

40
StabilityMatrix.Avalonia/Views/CheckpointsPage.axaml

@ -239,17 +239,19 @@
</Grid>
</Expander.Header>
<StackPanel Orientation="Vertical">
<Grid RowDefinitions="Auto, Auto">
<!-- Subfolders -->
<StackPanel Orientation="Vertical">
<ItemsControl
HorizontalAlignment="Stretch"
ItemTemplate="{DynamicResource CheckpointFolderGridDataTemplate}"
ItemsSource="{Binding SubFolders, Mode=OneWay}"
Margin="8,0,8,8" />
</StackPanel>
<ItemsRepeater Grid.Row="0"
HorizontalAlignment="Stretch"
ItemTemplate="{DynamicResource CheckpointFolderGridDataTemplate}"
ItemsSource="{Binding SubFolders, Mode=OneWay}"
Margin="8,0,8,8" >
<ItemsRepeater.Layout>
<StackLayout Orientation="Vertical"/>
</ItemsRepeater.Layout>
</ItemsRepeater>
<!-- Files Grid -->
<Grid Name="FilesGrid"
<Grid Grid.Row="1" Name="FilesGrid"
Background="Transparent"
DragDrop.AllowDrop="True">
<ItemsRepeater
@ -265,11 +267,8 @@
TextAlignment="Center"
HorizontalAlignment="Center"
Margin="8"
IsVisible="{Binding !CheckpointFiles.Count}">
<Run Text="Drag &amp; drop"/>
<Run Text="{Binding FolderType}"/>
<Run Text="checkpoints here to import"/>
</TextBlock>
Text="Drag &amp; drop checkpoints here to import"
IsVisible="{Binding !CheckpointFiles.Count}"/>
<!-- Blurred background for drag and drop -->
<Border
CornerRadius="8"
@ -291,27 +290,26 @@
<StackPanel
Margin="0,8"
Orientation="Vertical"
DataContext="{Binding Progress}"
VerticalAlignment="Center">
<!-- Import progress -->
<TextBlock
Effect="{StaticResource TextDropShadowEffect}"
FontSize="18"
HorizontalAlignment="Center"
Text="{Binding Text}"
Text="{Binding Progress.Text}"
VerticalAlignment="Center"
IsVisible="{Binding IsTextVisible}" />
IsVisible="{Binding Progress.IsTextVisible}" />
<ProgressBar
Effect="{StaticResource TextDropShadowEffect}"
HorizontalAlignment="Stretch"
IsIndeterminate="{Binding IsIndeterminate, FallbackValue=False}"
IsIndeterminate="{Binding Progress.IsIndeterminate, FallbackValue=False}"
Margin="64,8"
VerticalAlignment="Center"
IsVisible="{Binding IsProgressVisible}"
Value="{Binding Value, FallbackValue=20}" />
IsVisible="{Binding Progress.IsProgressVisible}"
Value="{Binding Progress.Value, FallbackValue=20}" />
</StackPanel>
</Grid>
</StackPanel>
</Grid>
</Expander>
</DataTemplate>

105
StabilityMatrix.Avalonia/Views/NewCheckpointsPage.axaml

@ -0,0 +1,105 @@
<controls:UserControlBase xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="clr-namespace:StabilityMatrix.Avalonia.ViewModels"
xmlns:mocks="clr-namespace:StabilityMatrix.Avalonia.DesignData"
xmlns:checkpointManager="clr-namespace:StabilityMatrix.Avalonia.ViewModels.CheckpointManager"
xmlns:controls="clr-namespace:StabilityMatrix.Avalonia.Controls"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="StabilityMatrix.Avalonia.Views.NewCheckpointsPage"
d:DataContext="{x:Static mocks:DesignData.NewCheckpointsPageViewModel}"
x:CompileBindings="True"
x:Name="ControlBase"
x:DataType="viewModels:NewCheckpointsPageViewModel">
<ScrollViewer>
<Grid RowDefinitions="Auto, Auto" Margin="8">
<TextBlock Text="Installed Checkpoints"
FontSize="24"
Margin="8"/>
<ItemsRepeater Grid.Row="1" ItemsSource="{Binding ConnectedCheckpoints}">
<ItemsRepeater.Layout>
<UniformGridLayout />
</ItemsRepeater.Layout>
<ItemsRepeater.ItemTemplate>
<DataTemplate DataType="{x:Type checkpointManager:CheckpointFile}">
<controls:Card
Margin="8"
MaxHeight="450"
Width="300"
CornerRadius="8">
<Grid RowDefinitions="Auto, Auto, Auto, Auto">
<TextBlock Grid.Row="0"
Margin="0,0,0,8"
Text="{Binding ConnectedModel.ModelName}" />
<controls:BetterAdvancedImage
Grid.Row="1"
Height="250"
Stretch="UniformToFill"
CornerRadius="8"
Source="{Binding PreviewImagePath}" />
<Grid Grid.Row="1"
Margin="8,8,0,0"
ColumnDefinitions="Auto, Auto">
<controls:Card
Grid.Column="0"
Classes="info"
Height="24"
HorizontalAlignment="Left"
Padding="4"
Margin="0,0,4,0"
VerticalAlignment="Top">
<TextBlock
FontSize="11"
FontWeight="Medium"
HorizontalAlignment="Center"
Text="{Binding ModelType}"
VerticalAlignment="Center" />
</controls:Card>
<controls:Card
Grid.Column="1"
Classes="info"
Height="24"
Margin="4,0"
HorizontalAlignment="Left"
Padding="4"
VerticalAlignment="Top">
<TextBlock
FontSize="11"
FontWeight="Medium"
HorizontalAlignment="Center"
Text="{Binding ConnectedModel.BaseModel}"
VerticalAlignment="Center" />
</controls:Card>
</Grid>
<Grid Grid.Row="2"
Margin="0,16,0,0"
ColumnDefinitions="*, *">
<Button Grid.Column="0"
Content="Update"
Classes="accent"
Margin="0,0,4,0"
HorizontalAlignment="Stretch" />
<Button Grid.Column="1"
Margin="4,0,0,0"
Content="All Versions"
Classes="accent"
Command="{Binding $parent[ItemsRepeater].((viewModels:NewCheckpointsPageViewModel)DataContext).ShowVersionDialog}"
CommandParameter="{Binding ConnectedModel.ModelId}"
HorizontalAlignment="Stretch" />
</Grid>
</Grid>
</controls:Card>
</DataTemplate>
</ItemsRepeater.ItemTemplate>
</ItemsRepeater>
</Grid>
</ScrollViewer>
</controls:UserControlBase>

11
StabilityMatrix.Avalonia/Views/NewCheckpointsPage.axaml.cs

@ -0,0 +1,11 @@
using StabilityMatrix.Avalonia.Controls;
namespace StabilityMatrix.Avalonia.Views;
public partial class NewCheckpointsPage : UserControlBase
{
public NewCheckpointsPage()
{
InitializeComponent();
}
}

773
StabilityMatrix.Avalonia/Views/SettingsPage.axaml

@ -1,429 +1,368 @@
<controls:UserControlBase xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:StabilityMatrix.Avalonia.ViewModels"
xmlns:ui="using:FluentAvalonia.UI.Controls"
xmlns:mocks="clr-namespace:StabilityMatrix.Avalonia.DesignData"
xmlns:controls="clr-namespace:StabilityMatrix.Avalonia.Controls"
xmlns:avalonia="clr-namespace:Projektanker.Icons.Avalonia;assembly=Projektanker.Icons.Avalonia"
xmlns:icons="clr-namespace:Projektanker.Icons.Avalonia;assembly=Projektanker.Icons.Avalonia"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="700"
x:DataType="vm:SettingsViewModel"
x:CompileBindings="True"
d:DataContext="{x:Static mocks:DesignData.SettingsViewModel}"
x:Class="StabilityMatrix.Avalonia.Views.SettingsPage">
<Grid>
<ScrollViewer VerticalScrollBarVisibility="Auto">
<Grid RowDefinitions="Auto, Auto, Auto, Auto, Auto, Auto, Auto, Auto, Auto, Auto"
Margin="8, 16">
<!-- Theme -->
<Grid Grid.Row="0" RowDefinitions="auto,*">
<TextBlock
FontWeight="Medium"
Text="Appearance"
Margin="0,0,0,8" />
<ui:SettingsExpander
Grid.Row="1"
Header="Theme"
IconSource="WeatherMoon"
Margin="8,0,8,4">
<ui:SettingsExpander.Footer>
<ComboBox
ItemsSource="{Binding AvailableThemes}"
SelectedItem="{Binding SelectedTheme}"
MinWidth="100"/>
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
</Grid>
<!-- TODO: Text2Image host port settings -->
<!-- Checkpoints Manager Options -->
<Grid Grid.Row="1" Margin="0,8,0,0" RowDefinitions="auto,*,Auto">
<TextBlock
FontWeight="Medium"
Text="Checkpoint Manager"
Margin="0,0,0,8" />
<ui:SettingsExpander
Grid.Row="1"
IconSource="Folder"
Header="Remove shared checkpoints directory symbolic links on shutdown"
Description="Select this option if you're having problems moving Stability Matrix to another drive"
Margin="8,0">
<ui:SettingsExpander.Footer>
<CheckBox Margin="8"
IsChecked="{Binding RemoveSymlinksOnShutdown}"/>
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
<ui:SettingsExpander
Grid.Row="2"
IconSource="Refresh"
Header="Reset Checkpoints Cache"
Description="Rebuilds the installed checkpoints cache. Use if checkpoints are incorrectly labeled in the Model Browser."
Margin="8, 4">
<ui:SettingsExpander.Footer>
<Button Command="{Binding ResetCheckpointCache}"
Content="Reset Checkpoints Cache"/>
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
</Grid>
<!-- Environment Options -->
<Grid Grid.Row="2" Margin="0,8,0,0" RowDefinitions="Auto, Auto, Auto">
<TextBlock
FontWeight="Medium"
Text="Package Environment"
Margin="0,0,0,8" />
<ui:SettingsExpander Grid.Row="1"
Header="Environment Variables"
IconSource="OtherUser"
Margin="8,0">
<ui:SettingsExpander.Footer>
<Button Content="Edit"
Command="{Binding OpenEnvVarsDialogCommand}"/>
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
<ui:SettingsExpander Grid.Row="2"
Header="Embedded Python"
Margin="8,4">
<ui:SettingsExpander.IconSource>
<controls:FASymbolIconSource Symbol="fa-brands fa-python"/>
</ui:SettingsExpander.IconSource>
<ui:SettingsExpander.Footer>
<StackPanel Orientation="Horizontal" Spacing="16">
<controls:ProgressRing
IsEnabled="{Binding CheckPythonVersionCommand.IsRunning}"
IsVisible="{Binding CheckPythonVersionCommand.IsRunning}"
IsIndeterminate="True"
BorderThickness="3"/>
<Button Content="Check Version" Command="{Binding CheckPythonVersionCommand}"/>
</StackPanel>
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
</Grid>
<!-- Inference UI -->
<Grid Grid.Row="3" Margin="0,8,0,0" RowDefinitions="auto,*">
<TextBlock
FontWeight="Medium"
Text="Inference UI"
Margin="0,0,0,8" />
<!-- Auto Completion -->
<ui:SettingsExpander Grid.Row="1"
Header="Prompt Auto Completion"
Margin="8,0,8,4">
<ui:SettingsExpander.IconSource>
<controls:FASymbolIconSource Symbol="fa-solid fa-wand-magic-sparkles"/>
</ui:SettingsExpander.IconSource>
<!-- Enable toggle -->
<ui:SettingsExpanderItem Content="Enable">
<ui:SettingsExpanderItem.Footer>
<ToggleSwitch
IsChecked="{Binding IsPromptCompletionEnabled}" />
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<!-- Tag csv selection -->
<ui:SettingsExpanderItem Content="Tag Source"
IconSource="Tag"
IsEnabled="{Binding IsPromptCompletionEnabled}"
Description="Tags to use for completion in .csv format (Compatible with a1111-sd-webui-tagcomplete)">
<ui:SettingsExpanderItem.Footer>
<ui:FAComboBox
ItemsSource="{Binding AvailableTagCompletionCsvs}"
SelectedItem="{Binding SelectedTagCompletionCsv}"/>
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<!-- Tag csv import -->
<ui:SettingsExpanderItem Content="Import Tag Source .csv"
IconSource="Add"
IsEnabled="{Binding IsPromptCompletionEnabled}">
<ui:SettingsExpanderItem.Footer>
<Button
Command="{Binding ImportTagCsvCommand}"
Content="Import"/>
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<!-- Remove underscores -->
<ui:SettingsExpanderItem
Content="Replace underscores with spaces when inserting completions"
IconSource="Underline"
IsEnabled="{Binding IsPromptCompletionEnabled}">
<ui:SettingsExpanderItem.Footer>
<CheckBox Margin="8"
IsChecked="{Binding IsCompletionRemoveUnderscoresEnabled}"/>
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
</ui:SettingsExpander>
</Grid>
<!-- Integrations -->
<Grid Grid.Row="4" Margin="0,8,0,0" RowDefinitions="auto,*">
<TextBlock
FontWeight="Medium"
Text="Integrations"
Margin="0,0,0,8" />
<ui:SettingsExpander Grid.Row="1"
Header="Discord Rich Presence"
Margin="8,0,8,4">
<ui:SettingsExpander.IconSource>
<controls:FASymbolIconSource Symbol="fa-brands fa-discord"/>
</ui:SettingsExpander.IconSource>
<ui:SettingsExpander.Footer>
<ToggleSwitch
IsChecked="{Binding IsDiscordRichPresenceEnabled}" />
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
</Grid>
<!-- System Options -->
<Grid Grid.Row="5" Margin="0,8,0,0" RowDefinitions="auto,*,*">
<TextBlock
FontWeight="Medium"
Text="System"
Margin="0,0,0,8" />
<ui:SettingsExpander
Grid.Row="1"
ToolTip.Tip="{OnPlatform Default='Only available on Windows', Windows={x:Null}}"
Header="Add Stability Matrix to the Start Menu"
Description="Uses the current app location, you can run this again if you move the app"
IconSource="StarAdd"
Margin="8,0,8,4">
<ui:SettingsExpander.Footer>
<StackPanel Orientation="Horizontal" Spacing="8">
<controls:ProgressRing
IsIndeterminate="True"
IsEnabled="{Binding IsVisible, RelativeSource={RelativeSource Self}}"
BorderThickness="3">
<controls:ProgressRing.IsVisible>
<MultiBinding Converter="{x:Static BoolConverters.Or}">
<Binding Path="AddToStartMenuCommand.IsRunning"/>
<Binding Path="AddToGlobalStartMenuCommand.IsRunning"/>
</MultiBinding>
</controls:ProgressRing.IsVisible>
</controls:ProgressRing>
<SplitButton
Command="{Binding AddToStartMenuCommand}"
IsEnabled="{OnPlatform Default=False, Windows=True}"
Content="Add for Current User">
<SplitButton.Flyout>
<ui:FAMenuFlyout Placement="Bottom">
<ui:MenuFlyoutItem
Command="{Binding AddToGlobalStartMenuCommand}"
IconSource="Admin"
Text="Add for All Users"/>
</ui:FAMenuFlyout>
</SplitButton.Flyout>
</SplitButton>
</StackPanel>
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
<ui:SettingsExpander Grid.Row="2"
Header="Select New Data Directory"
Description="Does not move existing data"
IconSource="MoveToFolder"
Margin="8,0">
<ui:SettingsExpander.Footer>
<Button Command="{Binding PickNewDataDirectory}">
<Grid ColumnDefinitions="Auto, Auto">
<avalonia:Icon Grid.Row="0" Value="fa-solid fa-folder-open"
Margin="0,0,8,0"
VerticalAlignment="Center" />
<TextBlock Grid.Column="1"
VerticalAlignment="Center"
Text="Select Directory"/>
</Grid>
</Button>
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
</Grid>
<!-- Debug Options -->
<Grid Grid.Row="6" RowDefinitions="auto,*"
Margin="0,8,0,0"
IsVisible="{Binding SharedState.IsDebugMode}" >
<TextBlock
FontWeight="Medium"
Text="Debug Options"
Margin="0,0,0,8" />
<ui:SettingsExpander
Grid.Row="1"
IconSource="Code"
Command="{Binding LoadDebugInfo}"
Header="Debug Options"
Margin="8, 0,8,0">
<ui:SettingsExpanderItem Description="Paths" IconSource="Folder"
Margin="4, 0">
<SelectableTextBlock Text="{Binding DebugPaths}"
Foreground="{DynamicResource TextControlPlaceholderForeground}"
TextWrapping="WrapWithOverflow" />
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem Description="Compat Info" IconSource="StarFilled"
Margin="4,0">
<SelectableTextBlock Text="{Binding DebugCompatInfo}"
Foreground="{DynamicResource TextControlPlaceholderForeground}"
TextWrapping="WrapWithOverflow" />
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem Description="GPU Info" IconSource="FullScreenMaximize"
Margin="4,0">
<SelectableTextBlock Text="{Binding DebugGpuInfo}"
Foreground="{DynamicResource TextControlPlaceholderForeground}"
TextWrapping="WrapWithOverflow" />
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem Content="Animation Scale" IconSource="Clock"
Description="Lower values = faster animations. 0x means animations are instant."
Margin="4,0">
<ui:SettingsExpanderItem.Footer>
<ComboBox ItemsSource="{Binding AnimationScaleOptions}"
SelectedItem="{Binding SelectedAnimationScale}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding }"/><Run Text="x"/>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem Content="Notification" IconSource="CommentAdd"
Margin="4,0">
<ui:SettingsExpanderItem.Footer>
<Button
Command="{Binding DebugNotificationCommand}"
Content="New Notification"/>
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem Content="Content Dialog" IconSource="NewWindow"
Margin="4,0">
<ui:SettingsExpanderItem.Footer>
<Button
Command="{Binding DebugContentDialogCommand}"
Content="Show Dialog"/>
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem Content="Exceptions" IconSource="Flag"
Margin="4,0">
<ui:SettingsExpanderItem.Footer>
<Button
Command="{Binding DebugThrowExceptionCommand}"
Content="Unhandled Exception"/>
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem Content="Download Manager tests" IconSource="Flag"
Margin="4,0,4,4">
<ui:SettingsExpanderItem.Footer>
<SplitButton
Margin="0, 8"
Command="{Binding DebugThrowExceptionCommand}"
Content="Command Exception">
<SplitButton.Flyout>
<ui:FAMenuFlyout>
<ui:MenuFlyoutItem
Text="Async Command Exception"
Command="{Binding DebugThrowAsyncExceptionCommand}"/>
</ui:FAMenuFlyout>
</SplitButton.Flyout>
</SplitButton>
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem Content="Image Processor Demos" IconSource="ImageCopy">
<ui:SettingsExpanderItem.Footer>
<Button
Command="{Binding DebugMakeImageGridCommand}"
Content="Make Image Grid from Files"/>
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem Content="Load Completion Source" IconSource="ImageCopy">
<ui:SettingsExpanderItem.Footer>
<Button
Command="{Binding DebugLoadCompletionCsvCommand}"
Content="Load CSV File"/>
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<controls:UserControlBase
x:Class="StabilityMatrix.Avalonia.Views.SettingsPage"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:avalonia="clr-namespace:Projektanker.Icons.Avalonia;assembly=Projektanker.Icons.Avalonia"
xmlns:controls="clr-namespace:StabilityMatrix.Avalonia.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:mocks="clr-namespace:StabilityMatrix.Avalonia.DesignData"
xmlns:ui="using:FluentAvalonia.UI.Controls"
xmlns:vm="clr-namespace:StabilityMatrix.Avalonia.ViewModels"
xmlns:lang="clr-namespace:StabilityMatrix.Avalonia.Languages"
d:DataContext="{x:Static mocks:DesignData.SettingsViewModel}"
d:DesignHeight="700"
d:DesignWidth="800"
x:CompileBindings="True"
x:DataType="vm:SettingsViewModel"
mc:Ignorable="d">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel Margin="8,16" Spacing="8">
<!-- Theme -->
<Grid RowDefinitions="Auto,*,*">
<TextBlock
Margin="0,0,0,8"
FontWeight="Medium"
Text="Appearance" />
<ui:SettingsExpander
Grid.Row="1"
Margin="8,0,8,4"
Header="Theme"
IconSource="WeatherMoon">
<ui:SettingsExpander.Footer>
<ComboBox
MinWidth="100"
ItemsSource="{Binding AvailableThemes}"
SelectedItem="{Binding SelectedTheme}" />
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
<ui:SettingsExpander
Grid.Row="2"
IsVisible="{Binding SharedState.IsDebugMode}"
Margin="8,0,8,4"
Header="{x:Static lang:Resources.Label_Language}"
IconSource="Character">
<ui:SettingsExpander.Footer>
<ComboBox
MinWidth="100"
ItemsSource="{Binding AvailableLanguages}"
DisplayMemberBinding="{Binding NativeName}"
SelectedItem="{Binding SelectedLanguage}" />
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
</Grid>
</ui:SettingsExpander>
</Grid>
<!-- Checkpoints Manager Options -->
<Grid RowDefinitions="auto,*,Auto">
<TextBlock
Margin="0,0,0,8"
FontWeight="Medium"
Text="Checkpoint Manager" />
<ui:SettingsExpander
Grid.Row="1"
Margin="8,0"
Description="Select this option if you're having problems moving Stability Matrix to another drive"
Header="Remove shared checkpoints directory symbolic links on shutdown"
IconSource="Folder">
<ui:SettingsExpander.Footer>
<CheckBox Margin="8" IsChecked="{Binding RemoveSymlinksOnShutdown}" />
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
<ui:SettingsExpander
Grid.Row="2"
Margin="8,4"
Description="Rebuilds the installed checkpoints cache. Use if checkpoints are incorrectly labeled in the Model Browser."
Header="Reset Checkpoints Cache"
IconSource="Refresh">
<ui:SettingsExpander.Footer>
<Button Command="{Binding ResetCheckpointCache}" Content="Reset Checkpoints Cache" />
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
</Grid>
<!-- TODO: Python card -->
<!-- Environment Options -->
<Grid RowDefinitions="Auto, Auto, Auto">
<TextBlock
Margin="0,0,0,8"
FontWeight="Medium"
Text="Package Environment" />
<ui:SettingsExpander
Grid.Row="1"
Margin="8,0"
Header="Environment Variables"
IconSource="OtherUser">
<ui:SettingsExpander.Footer>
<Button Command="{Binding OpenEnvVarsDialogCommand}" Content="Edit" />
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
<ui:SettingsExpander
Grid.Row="2"
Margin="8,4"
Header="Embedded Python">
<ui:SettingsExpander.IconSource>
<controls:FASymbolIconSource Symbol="fa-brands fa-python" />
</ui:SettingsExpander.IconSource>
<ui:SettingsExpander.Footer>
<StackPanel Orientation="Horizontal" Spacing="16">
<controls:ProgressRing
BorderThickness="3"
IsEnabled="{Binding CheckPythonVersionCommand.IsRunning}"
IsIndeterminate="True"
IsVisible="{Binding CheckPythonVersionCommand.IsRunning}" />
<Button Command="{Binding CheckPythonVersionCommand}" Content="Check Version" />
</StackPanel>
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
</Grid>
<!-- TODO: Debug card -->
<!-- Integrations -->
<Grid RowDefinitions="auto,*">
<TextBlock
Margin="0,0,0,8"
FontWeight="Medium"
Text="Integrations" />
<ui:SettingsExpander
Grid.Row="1"
Margin="8,0,8,4"
Header="Discord Rich Presence">
<ui:SettingsExpander.IconSource>
<controls:FASymbolIconSource Symbol="fa-brands fa-discord" />
</ui:SettingsExpander.IconSource>
<ui:SettingsExpander.Footer>
<ToggleSwitch IsChecked="{Binding IsDiscordRichPresenceEnabled}" />
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
</Grid>
<!-- TODO: Directories card -->
<!-- System Options -->
<Grid RowDefinitions="auto, auto, auto">
<TextBlock
Margin="0,0,0,8"
FontWeight="Medium"
Text="System" />
<ui:SettingsExpander
Grid.Row="1"
Margin="8,0,8,4"
Description="Uses the current app location, you can run this again if you move the app"
Header="Add Stability Matrix to the Start Menu"
IconSource="StarAdd"
ToolTip.Tip="{OnPlatform Default='Only available on Windows',
Windows={x:Null}}">
<ui:SettingsExpander.Footer>
<StackPanel Orientation="Horizontal" Spacing="8">
<controls:ProgressRing
BorderThickness="3"
IsEnabled="{Binding IsVisible, RelativeSource={RelativeSource Self}}"
IsIndeterminate="True">
<controls:ProgressRing.IsVisible>
<MultiBinding Converter="{x:Static BoolConverters.Or}">
<Binding Path="AddToStartMenuCommand.IsRunning" />
<Binding Path="AddToGlobalStartMenuCommand.IsRunning" />
</MultiBinding>
</controls:ProgressRing.IsVisible>
</controls:ProgressRing>
<SplitButton
Command="{Binding AddToStartMenuCommand}"
Content="Add for Current User"
IsEnabled="{OnPlatform Default=False,
Windows=True}">
<SplitButton.Flyout>
<ui:FAMenuFlyout Placement="Bottom">
<ui:MenuFlyoutItem
Command="{Binding AddToGlobalStartMenuCommand}"
IconSource="Admin"
Text="Add for All Users" />
</ui:FAMenuFlyout>
</SplitButton.Flyout>
</SplitButton>
</StackPanel>
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
<ui:SettingsExpander
Grid.Row="2"
Margin="8,0"
Description="Does not move existing data"
Header="Select New Data Directory"
IconSource="MoveToFolder">
<ui:SettingsExpander.Footer>
<Button Command="{Binding PickNewDataDirectory}">
<Grid ColumnDefinitions="Auto, Auto">
<avalonia:Icon
Grid.Row="0"
Margin="0,0,8,0"
VerticalAlignment="Center"
Value="fa-solid fa-folder-open" />
<TextBlock
Grid.Column="1"
VerticalAlignment="Center"
Text="Select Directory" />
</Grid>
</Button>
</ui:SettingsExpander.Footer>
</ui:SettingsExpander>
</Grid>
<Grid Grid.Row="7" RowDefinitions="auto,*" Margin="0,4,0,0">
<StackPanel
Grid.Row="1"
HorizontalAlignment="Left"
Orientation="Vertical">
<TextBlock
FontSize="15"
FontWeight="Bold"
<!-- Debug Options -->
<Grid
IsVisible="{Binding SharedState.IsDebugMode}"
RowDefinitions="auto,*">
<TextBlock
Margin="0,0,0,8"
FontWeight="Medium"
Text="Debug Options" />
<ui:SettingsExpander
Grid.Row="1"
Margin="8,0,8,0"
Command="{Binding LoadDebugInfo}"
Header="Debug Options"
IconSource="Code">
<ui:SettingsExpanderItem
Margin="4,0"
Description="Paths"
IconSource="Folder">
<SelectableTextBlock
Foreground="{DynamicResource TextControlPlaceholderForeground}"
Text="{Binding DebugPaths}"
TextWrapping="WrapWithOverflow" />
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem
Margin="4,0"
Description="Compat Info"
IconSource="StarFilled">
<SelectableTextBlock
Foreground="{DynamicResource TextControlPlaceholderForeground}"
Text="{Binding DebugCompatInfo}"
TextWrapping="WrapWithOverflow" />
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem
Margin="4,0"
Description="GPU Info"
IconSource="FullScreenMaximize">
<SelectableTextBlock
Foreground="{DynamicResource TextControlPlaceholderForeground}"
Text="{Binding DebugGpuInfo}"
TextWrapping="WrapWithOverflow" />
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem
Margin="4,0"
Content="Animation Scale"
Description="Lower values = faster animations. 0x means animations are instant."
IconSource="Clock">
<ui:SettingsExpanderItem.Footer>
<ComboBox ItemsSource="{Binding AnimationScaleOptions}" SelectedItem="{Binding SelectedAnimationScale}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding}" /><Run Text="x" />
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem
Margin="4,0"
Content="Notification"
IconSource="CommentAdd">
<ui:SettingsExpanderItem.Footer>
<Button Command="{Binding DebugNotificationCommand}" Content="New Notification" />
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem
Margin="4,0"
Content="Content Dialog"
IconSource="NewWindow">
<ui:SettingsExpanderItem.Footer>
<Button Command="{Binding DebugContentDialogCommand}" Content="Show Dialog" />
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem
Margin="4,0"
Content="Exceptions"
IconSource="Flag">
<ui:SettingsExpanderItem.Footer>
<Button Command="{Binding DebugThrowExceptionCommand}" Content="Unhandled Exception" />
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<ui:SettingsExpanderItem
Margin="4,0,4,4"
Content="Download Manager tests"
IconSource="Flag">
<ui:SettingsExpanderItem.Footer>
<Button
Margin="0,8"
Text="About" />
<Image
Height="112"
HorizontalAlignment="Left"
Margin="8"
Source="/Assets/Icon.png"
Width="112" />
<TextBlock
FontWeight="Medium"
Margin="8"
Text="Stability Matrix" />
<Panel>
<Button
Name="VersionButton"
Command="{Binding OnVersionClick}"
Classes="transparent"
BorderThickness="0"
Content="{Binding AppVersion}"
Margin="8,0,8,8"
Padding="2,0,2,0"/>
<ui:TeachingTip
PreferredPlacement="RightTop"
Target="{Binding #VersionButton}"
IsOpen="{Binding IsVersionTapTeachingTipOpen}"
Title="{Binding VersionFlyoutText}"/>
</Panel>
Command="{Binding DebugTrackedDownloadCommand}"
Content="Add Tracked Download" />
</ui:SettingsExpanderItem.Footer>
</ui:SettingsExpanderItem>
<StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
<Button
Content="License and Open Source Notices"
Command="{Binding ShowLicensesDialogCommand}"
HorizontalAlignment="Left"
Margin="8" />
</StackPanel>
</StackPanel>
</Grid>
</ui:SettingsExpander>
</Grid>
<!-- Extra space at the bottom -->
<Panel Grid.Row="8" Margin="0,0,0,16" />
<!-- TODO: Directories card -->
<Grid RowDefinitions="auto,*">
<StackPanel
Grid.Row="1"
HorizontalAlignment="Left"
Orientation="Vertical">
<TextBlock
Margin="0,8"
FontSize="15"
FontWeight="Bold"
Text="About" />
<Image
Width="112"
Height="112"
Margin="8"
HorizontalAlignment="Left"
Source="/Assets/Icon.png" />
<TextBlock
Margin="8"
FontWeight="Medium"
Text="Stability Matrix" />
<Panel>
<Button
Name="VersionButton"
Margin="8,0,8,8"
Padding="2,0,2,0"
BorderThickness="0"
Classes="transparent"
Command="{Binding OnVersionClick}"
Content="{Binding AppVersion}" />
<ui:TeachingTip
Title="{Binding VersionFlyoutText}"
IsOpen="{Binding IsVersionTapTeachingTipOpen}"
PreferredPlacement="RightTop"
Target="{Binding #VersionButton}" />
</Panel>
<StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
<Button
Margin="8"
HorizontalAlignment="Left"
Command="{Binding ShowLicensesDialogCommand}"
Content="License and Open Source Notices" />
</StackPanel>
</StackPanel>
</Grid>
</ScrollViewer>
</Grid>
<!-- Extra space at the bottom -->
<Panel Margin="0,0,0,16" />
</StackPanel>
</ScrollViewer>
</controls:UserControlBase>

18
StabilityMatrix.Core/Models/Api/CivitModelsRequest.cs

@ -117,4 +117,22 @@ public class CivitModelsRequest
/// </summary>
[AliasAs("baseModels")]
public string? BaseModel { get; set; }
[AliasAs("ids")]
public string CommaSeparatedModelIds { get; set; }
public override string ToString()
{
return $"Page: {Page}, " +
$"Query: {Query}, " +
$"Tag: {Tag}, " +
$"Username: {Username}, " +
$"Types: {Types}, " +
$"Sort: {Sort}, " +
$"Period: {Period}, " +
$"Rating: {Rating}, " +
$"Nsfw: {Nsfw}, " +
$"BaseModel: {BaseModel}, " +
$"CommaSeparatedModelIds: {CommaSeparatedModelIds}";
}
}

4
StabilityMatrix.Core/Models/Api/CivitSortMode.cs

@ -11,5 +11,7 @@ public enum CivitSortMode
[EnumMember(Value = "Most Downloaded")]
MostDownloaded,
[EnumMember(Value = "Newest")]
Newest
Newest,
[EnumMember(Value = "Installed")]
Installed,
}

8
StabilityMatrix.Core/Models/Packages/BaseGitPackage.cs

@ -139,7 +139,7 @@ public abstract class BaseGitPackage : BasePackage
}
public override async Task<string> DownloadPackage(string version, bool isCommitHash,
IProgress<ProgressReport>? progress = null)
string? branch, IProgress<ProgressReport>? progress = null)
{
var downloadUrl = GetDownloadUrl(version, isCommitHash);
@ -246,7 +246,8 @@ public abstract class BaseGitPackage : BasePackage
{
var releases = await GetAllReleases().ConfigureAwait(false);
var latestRelease = releases.First(x => includePrerelease || !x.Prerelease);
await DownloadPackage(latestRelease.TagName, false, progress).ConfigureAwait(false);
await DownloadPackage(latestRelease.TagName, false, null, progress)
.ConfigureAwait(false);
await InstallPackage(progress).ConfigureAwait(false);
return latestRelease.TagName;
}
@ -261,7 +262,8 @@ public abstract class BaseGitPackage : BasePackage
throw new Exception("No commits found for branch");
}
await DownloadPackage(latestCommit.Sha, true, progress).ConfigureAwait(false);
await DownloadPackage(latestCommit.Sha, true, installedPackage.InstalledBranch, progress)
.ConfigureAwait(false);
await InstallPackage(progress).ConfigureAwait(false);
return latestCommit.Sha;
}

2
StabilityMatrix.Core/Models/Packages/BasePackage.cs

@ -33,7 +33,7 @@ public abstract class BasePackage
public virtual bool ShouldIgnoreReleases => false;
public virtual bool UpdateAvailable { get; set; }
public abstract Task<string> DownloadPackage(string version, bool isCommitHash,
public abstract Task<string> DownloadPackage(string version, bool isCommitHash, string? branch,
IProgress<ProgressReport>? progress = null);
public abstract Task InstallPackage(IProgress<ProgressReport>? progress = null);
public abstract Task RunPackage(string installedPackagePath, string command, string arguments);

2
StabilityMatrix.Core/Models/Packages/InvokeAI.cs

@ -116,7 +116,7 @@ public class InvokeAI : BaseGitPackage
public override Task<string> GetLatestVersion() => Task.FromResult("main");
public override Task<string> DownloadPackage(string version, bool isCommitHash,
public override Task<string> DownloadPackage(string version, bool isCommitHash, string? branch,
IProgress<ProgressReport>? progress = null)
{
return Task.FromResult(version);

47
StabilityMatrix.Core/Models/Packages/VladAutomatic.cs

@ -188,16 +188,18 @@ public class VladAutomatic : BaseGitPackage
progress?.Report(new ProgressReport(1, isIndeterminate: false));
}
public override async Task<string> DownloadPackage(string version, bool isCommitHash, IProgress<ProgressReport>? progress = null)
public override async Task<string> DownloadPackage(string version, bool isCommitHash,
string? branch, IProgress<ProgressReport>? progress = null)
{
progress?.Report(new ProgressReport(0.1f, message: "Downloading package...", isIndeterminate: true, type: ProgressType.Download));
progress?.Report(new ProgressReport(0.1f, message: "Downloading package...",
isIndeterminate: true, type: ProgressType.Download));
var installDir = new DirectoryPath(InstallLocation);
installDir.Create();
await PrerequisiteHelper.RunGit(
installDir.Parent ?? "", "clone", "https://github.com/vladmandic/automatic", installDir.Name)
.ConfigureAwait(false);
await PrerequisiteHelper
.RunGit(installDir.Parent ?? "", "clone", "https://github.com/vladmandic/automatic",
installDir.Name).ConfigureAwait(false);
await PrerequisiteHelper.RunGit(
InstallLocation, "checkout", version).ConfigureAwait(false);
@ -244,15 +246,18 @@ public class VladAutomatic : BaseGitPackage
}
progress?.Report(new ProgressReport(0.1f, message: "Downloading package update...",
isIndeterminate: true, type: ProgressType.Download));
isIndeterminate: true, type: ProgressType.Update));
var version = await GithubApi.GetAllCommits(Author, Name, installedPackage.InstalledBranch).ConfigureAwait(false);
var latest = version?.FirstOrDefault();
await PrerequisiteHelper.RunGit(installedPackage.FullPath, "checkout",
installedPackage.InstalledBranch).ConfigureAwait(false);
var venvRunner = new PyVenvRunner(Path.Combine(installedPackage.FullPath!, "venv"));
venvRunner.WorkingDirectory = InstallLocation;
venvRunner.EnvironmentVariables = SettingsManager.Settings.EnvironmentVariables;
await venvRunner.CustomInstall("launch.py --upgrade --test", OnConsoleOutput)
.ConfigureAwait(false);
if (latest?.Sha is null)
{
throw new Exception("Could not get latest version");
}
try
{
@ -261,22 +266,18 @@ public class VladAutomatic : BaseGitPackage
.GetGitOutput(installedPackage.FullPath, "rev-parse", "HEAD")
.ConfigureAwait(false);
if (output.Replace(Environment.NewLine, "") == latest.Sha)
{
return latest.Sha;
}
return output.Replace(Environment.NewLine, "").Replace("\n", "");
}
catch (Exception e)
{
Logger.Warn(e, "Could not get current git hash, continuing with update");
}
finally
{
progress?.Report(new ProgressReport(1f, message: "Update Complete", isIndeterminate: false,
type: ProgressType.Update));
}
await PrerequisiteHelper.RunGit(installedPackage.FullPath, "pull",
"origin", installedPackage.InstalledBranch).ConfigureAwait(false);
progress?.Report(new ProgressReport(1f, message: "Update Complete", isIndeterminate: false,
type: ProgressType.Generic));
return latest.Sha;
return installedPackage.InstalledBranch;
}
}

1
StabilityMatrix.Core/Models/Settings/Settings.cs

@ -8,6 +8,7 @@ public class Settings
public int? Version { get; set; } = 1;
public bool FirstLaunchSetupComplete { get; set; }
public string? Theme { get; set; } = "Dark";
public string? Language { get; set; } = "en-US";
public List<InstalledPackage> InstalledPackages { get; set; } = new();

Loading…
Cancel
Save