feat (ui): Add ConfigServerPicker dialog

So we can connect to different config servers without manually editing spark.conf,
or changing command line args. This will run before the Login dialog.
This commit is contained in:
John Colvin committed 2025-11-19 14:01:01 -05:00
1 parent 5045b1889d
commit 12a3e7a2f4
10 files changed
+231 -12

No files matched your search

@@ -1,7 +1,6 @@
#nullable enable
namespace Spark.Services;
using bts.api;
using bts.api.core;
using Spark.Api.Services;
@@ -9,7 +8,7 @@ using Spark.Api.Services;
using System.Threading.Tasks;
public interface ISparkLoginGuiService : ISparkdLoginService {
new ValueTask<(LoginResult Result, AuthTokenImmutable? Token, string? Workspace)> LoginAsync();
new ValueTask<(LoginResult Result, string? Workspace)> LoginAsync();
async ValueTask<LoginResult> ISparkdLoginService.LoginAsync() =>
(await LoginAsync()).Result;
+11 -4
View File
@@ -10,6 +10,7 @@ using mbts.ui.shell;
using Microsoft.Extensions.Hosting;
using Spark.Api.MarketData;
using Spark.Api.Services;
using Spark.Core;
using Spark.Core.Services;
@@ -21,7 +22,7 @@ using System.Threading.Tasks;
class SparkAppService : IHostedService {
readonly ISparkConfigLoader sparkConfigLoader;
readonly List<IDataStreamFactory> streamFactories;
readonly ISparkLoginGuiService loginService;
readonly ISparkdLoginService loginService;
readonly Api.IServiceProvider serviceProvider;
readonly ServiceContext internalServiceContext;
readonly IMarketDataClient marketDataClient;
@@ -29,7 +30,7 @@ class SparkAppService : IHostedService {
public SparkAppService(
ISparkConfigLoader sparkConfigLoader,
ISparkLoginGuiService loginService,
ISparkdLoginService loginService,
Api.IServiceProvider serviceProvider,
ServiceContext internalServiceContext,
IMarketDataClient marketDataClient,
@@ -44,7 +45,13 @@ class SparkAppService : IHostedService {
}
public async Task StartAsync(CancellationToken cancellationToken) {
var (loginResult, token, workspace) = await loginService.LoginAsync();
LoginResult? loginResult;
string? workspace = null;
if (loginService is ISparkLoginGuiService loginGuiService) {
(loginResult, workspace) = await loginGuiService.LoginAsync();
} else {
loginResult = await loginService.LoginAsync();
}
var sparkAppThread = new Thread(RunSparkApp) {
Name = "SparkApp",
};
@@ -62,7 +69,7 @@ class SparkAppService : IHostedService {
MarketDataClient = marketDataClient,
UserTuple = loginResult.user.assert_value(),
Workspace = workspace,
Token = token,
Token = loginResult.Token,
};
exitCode = sparkApp.Run();
} catch (Exception ex) {
@@ -0,0 +1,67 @@
#nullable enable
namespace Spark.Services;
using bts.collections;
using mbts.ui.shell;
using Microsoft.Extensions.Options;
using Spark.Core.Services;
using System;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Launches dialog to pick config server.
/// </summary>
public class SparkConfigGuiLoader : ISparkConfigLoader {
readonly object syncRoot = new();
readonly SparkConfigLoaderOpts config;
TaskCompletionSource<SparkConfigLoader>? configServerTcs;
public SparkConfigGuiLoader(IOptions<SparkConfigLoaderOpts> config)
: this(config.Value) { }
public SparkConfigGuiLoader(SparkConfigLoaderOpts config) {
this.config = config;
}
public string? ConfigServer => config.ConfigServer;
public async Task InitializeAsync(CancellationToken cancellationToken) {
bool launchGui = false;
lock (syncRoot) {
if (configServerTcs is null) {
launchGui = true;
configServerTcs = new();
}
}
if (launchGui) {
var loginGuiThread = new Thread(RunConfigGui) {
IsBackground = true,
Name = "Login"
};
loginGuiThread.SetApartmentState(ApartmentState.STA);
loginGuiThread.Start();
}
var loader = await configServerTcs.Task;
await loader.InitializeAsync(cancellationToken);
void RunConfigGui() {
var vm = new ConfigServerPickerViewModel();
vm.ConfigServers.AddRange(config.ConfigServers);
vm.OkCmd.executed += s => {
config.ConfigServer = s;
configServerTcs.SetResult(new SparkConfigLoader(config));
};
var view = new ConfigServerPickerView() {
DataContext = vm
};
vm.RequestClose += (s, e) => view.Close();
view.ShowDialog();
configServerTcs.TrySetException(new Exception("Failed to pick config server"));
}
}
}
@@ -17,7 +17,7 @@ using System.Windows.Threading;
class SparkLoginGuiService : IHostedService, ISparkLoginGuiService {
readonly ISparkConfigLoader configLoader;
readonly TaskCompletionSource<(LoginResult Result, AuthTokenImmutable? Token, string? Workspace)> loginTcs = new();
readonly TaskCompletionSource<(LoginResult Result, string? Workspace)> loginTcs = new();
readonly ServiceContext serviceProvider;
public SparkLoginGuiService(ISparkConfigLoader configLoader, ServiceContext serviceProvider) {
@@ -25,7 +25,7 @@ class SparkLoginGuiService : IHostedService, ISparkLoginGuiService {
this.serviceProvider = serviceProvider;
}
public async ValueTask<(LoginResult Result, AuthTokenImmutable? Token, string? Workspace)> LoginAsync() =>
public async ValueTask<(LoginResult Result, string? Workspace)> LoginAsync() =>
await loginTcs.Task;
public async Task StartAsync(CancellationToken cancellationToken) {
@@ -54,7 +54,7 @@ class SparkLoginGuiService : IHostedService, ISparkLoginGuiService {
void OnLoggedIn() {
var (userName, userId, token) = model.get_user();
var workspace = model.get_workspace();
loginTcs.SetResult((new LoginResult() { user = new(userId, userName), Token = token, success = true, }, token, workspace));
loginTcs.SetResult((new() { user = new(userId, userName), Token = token, success = true, }, workspace));
view.Close();
}
}
+9 -2
View File
@@ -22,8 +22,15 @@ public static class SparkServices {
.AddHostedService(sp => sp.GetRequiredService<SparkLoginGuiService>());
public static IServiceCollection AddSparkApp(this IServiceCollection services, IConfiguration configurationSection) {
services.AddSpark(configurationSection.GetSection("Spark"))
.AddSparkApi(configurationSection.GetSection("SparkApi"))
var sparkCfgSection = configurationSection.GetSection("Spark");
var sparkCfg = sparkCfgSection?.Get<SparkConfigLoaderOpts>();
if (sparkCfg?.ConfigServers?.Count > 0) {
// Launch gui to let the user pick a config server from the listed options.
services.AddSpark<SparkConfigGuiLoader>(sparkCfgSection);
} else {
services.AddSpark(sparkCfgSection);
}
services.AddSparkApi(configurationSection.GetSection("SparkApi"))
.AddSparkLoginGui()
.AddMasterWorker(configurationSection.GetSection("MasterWorker"))
.AddViewStreamDatabase()
@@ -0,0 +1,81 @@
<Window
x:Class="mbts.ui.shell.ConfigServerPickerView"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:u="clr-namespace:mbts.ui"
xmlns:shell="clr-namespace:mbts.ui.shell"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:converters="clr-namespace:mbts.ui.converters"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Name="configServerPickerView"
Width="520"
Height="230"
Background="{u:BTSBrush UI.Window.normal_background}"
WindowStyle="None"
ResizeMode="NoResize"
WindowStartupLocation="CenterScreen"
>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Resources/Buttons.xaml" />
<ResourceDictionary Source="/view/Resources/ComboBoxes.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Border BorderBrush="{u:BTSBrush UI.form_border}" BorderThickness="1">
<Grid ClipToBounds="True">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="16" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="5" Command="{Binding CancelCmd}" Style="{StaticResource RoundCloseButton}"/>
<!-- logo -->
<Image
x:Name="_logo"
Grid.Row="2"
RenderOptions.BitmapScalingMode="HighQuality"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="32,32,0,0"
Width="220"
Source="/Images/Icons/BTS.png"
Stretch="Uniform"
SnapsToDevicePixels="True"
/>
<Grid Grid.Row="2" Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="8" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="16" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="16" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="1" HorizontalAlignment="Center" Foreground="{u:BTSBrush UI.default_text}">
Config Server
</TextBlock>
<ComboBox
Grid.Row="2"
Grid.Column="1"
HorizontalAlignment="Stretch"
ItemsSource="{Binding ConfigServers}"
SelectedItem="{Binding SelectedConfigServer}" />
</Grid>
<c:DialogSkirtOKCancel
Grid.Row="3"
Grid.ColumnSpan="2"
OKCommand="{Binding OkCmd}"
OKCommandParameter="{Binding SelectedConfigServer}" />
</Grid>
</Border>
</Window>
@@ -0,0 +1,20 @@
namespace mbts.ui.shell;
using System.Windows;
using System.Windows.Input;
/// <summary>
/// Interaction logic for ConfigServerPickerView.xaml
/// </summary>
partial class ConfigServerPickerView : Window {
public ConfigServerPickerView() {
InitializeComponent();
}
protected override void OnMouseDown(MouseButtonEventArgs e) {
base.OnMouseDown(e);
if (e.LeftButton == MouseButtonState.Pressed) {
DragMove();
}
}
}
@@ -0,0 +1,26 @@
#nullable enable
namespace mbts.ui.shell;
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
class ConfigServerPickerViewModel : ViewModelBase, IRequestViewClose {
string? selectedConfigServer;
public ConfigServerPickerViewModel() {
CancelCmd = new DelegateCommand(() => RequestClose?.Invoke(this, EventArgs.Empty));
}
public event EventHandler? RequestClose;
public ObservableCollection<string> ConfigServers { get; } = new();
public string? SelectedConfigServer {
get => selectedConfigServer;
set => Set(ref selectedConfigServer, value);
}
public EventCommand<string?> OkCmd { get; } = new(s => !string.IsNullOrEmpty(s));
public ICommand CancelCmd { get; }
}
@@ -1,8 +1,11 @@
#nullable enable
namespace Spark.Core.Services;
using System.Collections.Generic;
public class SparkConfigLoaderOpts {
public string? ConfigServer { get; set; }
public List<string>? ConfigServers { get; set; }
public static SparkConfigLoaderOpts Default() => new();
}
@@ -15,4 +15,13 @@ public static class SparkCoreServices {
.AddSingleton<ISparkConfigLoader, SparkConfigLoader>()
.AddHostedService<SparkConfigLoaderService>();
}
public static IServiceCollection AddSpark<T>(this IServiceCollection services, IConfiguration configurationSection) where T : class, ISparkConfigLoader {
if (services.Any(s => s.ServiceType == typeof(ISparkConfigLoader))) {
throw new InvalidOperationException("SparkService has already been added");
}
return services.Configure<SparkConfigLoaderOpts>(configurationSection)
.AddSingleton<ISparkConfigLoader, T>()
.AddHostedService<SparkConfigLoaderService>();
}
}