L6: IBKRTrader.App.Avalonia -> IBKRTrader.App; letzte WinForms-Spuren raus
Das Suffix ".Avalonia" gab es nur, weil daneben ein WinForms-IBKRTrader.App
stand. Das ist seit L5 weg, also faellt auch das Suffix. Git erkennt alle
Dateien als Umbenennung; Assembly, Wurzel-Namensraum und die
avares://-Ressourcen-URI sind mitgezogen.
Nebeneffekt der Umbenennung: die global::Avalonia-Qualifizierungen entfallen.
Sie waren noetig, weil der Namensraum IBKRTrader.App.Avalonia das
Avalonia-Paket verdeckt hat - ein Ueberbleibsel genau der Namensgebung, die
jetzt weg ist.
Inhaltlich falsch gewordene Aussagen berichtigt - das waren die eigentlichen
Ueberbleibsel, nicht die Kommentare:
- .agents/rules/grundregeln.md schrieb weiterhin "C# .NET 10 WinForms",
RichTextBox-Logging, LauncherForm und PropertyGrid vor. Das ist die Regel,
nach der kuenftig gearbeitet wird - sie haette die Portierung Stueck fuer
Stueck rueckgaengig gemacht. Jetzt: Avalonia, keine Plattform-Suffixe, die
11er-Pinnung mit Begruendung, dazu die beiden Regeln, die uns in L1b am
meisten gekostet haben (UTC persistieren + AppTimeZone statt DateTime.Now;
jede Formatierung mit ausdruecklichem IFormatProvider).
- Core: LogEntry ("wird in RichTextBox geschrieben"), IWorker/WorkerEngine/
WorkerInfo ("DataGridView-Zeile"/"-Binding"), ModuleView ("die
WinForms-Shell castet auf Form").
- Doku: ARCHITECTURE (Modul-Ui-Ordner, "designbare Forms mit Initialize"),
KONZEPT-Modul-Accounting ("UI (WinForms, ein Fenster mit Tabs)").
BEWUSST STEHEN GEBLIEBEN sind die Kommentare, die WinForms nur als
Begruendung nennen - warum LoggingService ein Ereignis hat statt einer
RichTextBox, warum ModuleView Func<object> liefert, warum es benannte
Record-Zeilentypen gibt, warum die Einstellungsmaske aus Attributen entsteht.
Das ist die Herleitung des heutigen Entwurfs; ohne sie sieht spaeter jede
dieser Stellen nach Umstaendlichkeit ohne Grund aus.
KONZEPT-Linux-Portierung.md bekommt einen Statusvermerk: umgesetzt, die
Pfadangaben im Fundstellenverzeichnis beziehen sich auf den alten Aufbau.
Zwei Abweichungen von der Schaetzung sind dort festgehalten - der geringere
Aufwand dank der PolytraderSharp-Vorlage, und dass die dort empfohlene
InvariantGlobalization ein Fehler gewesen waere.
Verifiziert: Build 0 Fehler/0 Warnungen, 193 Tests gruen, Smoke-UI
konstruiert alle 7 Ansichten + Launcher + Dialog, Daemon-Prueflauf OK,
publish -r linux-x64 fuer beide Einstiegspunkte fehlerfrei.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using IBKRTrader.App.Views;
|
||||
using IBKRTrader.Core.Modularity;
|
||||
|
||||
namespace IBKRTrader.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Avalonia-Umsetzung von <see cref="IModuleUiHost"/>. Verhält sich wie der frühere
|
||||
/// WinForms-<c>ShellUiHost</c>: je View höchstens ein Fenster, ein bereits offenes wird nach vorn
|
||||
/// geholt, der Offen-Status wird gemeldet (für die Markierung im Launcher).
|
||||
///
|
||||
/// <para>Der Core-Contract ist toolkit-neutral – <see cref="ModuleView.CreateView"/> liefert
|
||||
/// <see cref="object"/>. Hier wird auf <see cref="Window"/> gecastet: ein anderer Typ ist ein
|
||||
/// Programmierfehler und soll laut scheitern, nicht still ein leeres Fenster ergeben.</para>
|
||||
/// </summary>
|
||||
public sealed class AvaloniaUiHost : IModuleUiHost
|
||||
{
|
||||
private readonly List<ModuleView> _views = [];
|
||||
private readonly Dictionary<string, Window> _open = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private Window? _mainWindow;
|
||||
private bool _shutdownDialogOpen;
|
||||
|
||||
/// <summary>True, sobald das Herunterfahren über die Sicherheitsabfrage bestätigt wurde.</summary>
|
||||
public bool ShutdownConfirmed { get; private set; }
|
||||
|
||||
public event Action? OpenStateChanged;
|
||||
|
||||
public IReadOnlyList<ModuleView> Views => _views;
|
||||
|
||||
public void RegisterView(ModuleView view) => _views.Add(view);
|
||||
|
||||
/// <summary>Setzt das Hauptfenster (Launcher) – Ziel für <see cref="ActivateMain"/>.</summary>
|
||||
public void SetMainWindow(Window main) => _mainWindow = main;
|
||||
|
||||
public bool IsOpen(string viewId) => _open.ContainsKey(viewId);
|
||||
|
||||
public void ActivateMain()
|
||||
{
|
||||
if (_mainWindow is null) return;
|
||||
if (_mainWindow.WindowState == WindowState.Minimized)
|
||||
_mainWindow.WindowState = WindowState.Normal;
|
||||
_mainWindow.Activate();
|
||||
}
|
||||
|
||||
public void OpenView(string viewId)
|
||||
{
|
||||
var view = _views.FirstOrDefault(v => v.Id == viewId);
|
||||
if (view is not null) OpenView(view);
|
||||
}
|
||||
|
||||
private void OpenView(ModuleView view)
|
||||
{
|
||||
if (_open.TryGetValue(view.Id, out var existing))
|
||||
{
|
||||
if (existing.WindowState == WindowState.Minimized)
|
||||
existing.WindowState = WindowState.Normal;
|
||||
existing.Activate();
|
||||
return;
|
||||
}
|
||||
|
||||
var window = (Window)view.CreateView();
|
||||
if (string.IsNullOrEmpty(window.Title)) window.Title = view.Title;
|
||||
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
|
||||
|
||||
_open[view.Id] = window;
|
||||
window.Closed += (_, _) =>
|
||||
{
|
||||
_open.Remove(view.Id);
|
||||
OpenStateChanged?.Invoke();
|
||||
};
|
||||
|
||||
window.Show();
|
||||
OpenStateChanged?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Zeigt die Sicherheitsabfrage und fährt bei Bestätigung herunter. Aus jedem Fenster
|
||||
/// aufrufbar – auch aus Modul-Fenstern, die nur den Core-Contract kennen.
|
||||
///
|
||||
/// <para><c>async void</c> ist hier korrekt: die Methode ist ein Ereignis-Handler hinter dem
|
||||
/// synchronen Contract <see cref="IModuleUiHost.RequestShutdown"/>, und der Dialog muss
|
||||
/// erwartet werden. Ausnahmen können nicht entweichen – der Dialog wirft nicht, und der
|
||||
/// <c>finally</c>-Block gibt die Sperre in jedem Fall frei.</para>
|
||||
/// </summary>
|
||||
public async void RequestShutdown()
|
||||
{
|
||||
if (ShutdownConfirmed || _shutdownDialogOpen) return;
|
||||
_shutdownDialogOpen = true;
|
||||
try
|
||||
{
|
||||
var owner = _mainWindow;
|
||||
if (owner is null) return;
|
||||
|
||||
var confirmed = await new ShutdownConfirmWindow().ShowDialog<bool>(owner);
|
||||
if (!confirmed) return;
|
||||
|
||||
ShutdownConfirmed = true;
|
||||
CloseAllViews();
|
||||
|
||||
if (Application.Current?.ApplicationLifetime
|
||||
is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
desktop.Shutdown();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_shutdownDialogOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Schließt alle offenen View-Fenster (beim Herunterfahren).</summary>
|
||||
public void CloseAllViews()
|
||||
{
|
||||
foreach (var window in _open.Values.ToList())
|
||||
window.Close();
|
||||
_open.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using IBKRTrader.App.Views;
|
||||
using IBKRTrader.Core.Logging;
|
||||
using IBKRTrader.Core.Modularity;
|
||||
using IBKRTrader.Core.Settings;
|
||||
using IBKRTrader.Core.Trading;
|
||||
using IBKRTrader.Core.Workers;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace IBKRTrader.App.Shell;
|
||||
|
||||
/// <summary>Registriert die Core-Ansichten (Dashboard, Workers, Logs, Settings) bei der Shell.</summary>
|
||||
public static class CoreViews
|
||||
{
|
||||
public static void Register(IModuleUiHost host, IServiceProvider sp)
|
||||
{
|
||||
host.RegisterView(new ModuleView
|
||||
{
|
||||
Id = "core.dashboard", Title = "Dashboard", Group = "Core", Order = 5,
|
||||
CreateView = () => new DashboardWindow(
|
||||
host,
|
||||
sp.GetRequiredService<DashboardService>(),
|
||||
sp.GetRequiredService<SettingsService>(),
|
||||
sp.GetServices<IModule>(),
|
||||
sp.GetRequiredService<IConfiguration>(),
|
||||
sp.GetServices<IWorker>())
|
||||
});
|
||||
|
||||
host.RegisterView(new ModuleView
|
||||
{
|
||||
Id = "core.workers", Title = "Workers / Services", Group = "Core", Order = 10,
|
||||
CreateView = () => new WorkersWindow(host, sp.GetRequiredService<WorkerEngine>())
|
||||
});
|
||||
|
||||
host.RegisterView(new ModuleView
|
||||
{
|
||||
Id = "core.logs", Title = "Logs", Group = "Core", Order = 20,
|
||||
CreateView = () => new LogsWindow(host, sp.GetRequiredService<LoggingService>())
|
||||
});
|
||||
|
||||
host.RegisterView(new ModuleView
|
||||
{
|
||||
Id = "core.settings", Title = "Settings", Group = "Core", Order = 30,
|
||||
CreateView = () => new SettingsWindow(host, sp.GetRequiredService<SettingsService>())
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using IBKRTrader.App.Views.Modules;
|
||||
using IBKRTrader.Core.Logging;
|
||||
using IBKRTrader.Core.Modularity;
|
||||
using IBKRTrader.Core.Trading;
|
||||
using IBKRTrader.Core.Workers;
|
||||
using IBKRTrader.Modules.Accounting.Persistence;
|
||||
using IBKRTrader.Modules.Accounting.Services;
|
||||
using IBKRTrader.Modules.CongressTrading.Database;
|
||||
using IBKRTrader.Modules.Supervisor.Agent;
|
||||
using IBKRTrader.Modules.Supervisor.Persistence;
|
||||
using IBKRTrader.Modules.Supervisor.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace IBKRTrader.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Registriert die Fenster der Module bei der Shell.
|
||||
///
|
||||
/// <para><b>Warum hier und nicht im Modul?</b> Ein Modul, das sein eigenes Fenster erzeugt, müsste
|
||||
/// Avalonia referenzieren – und wäre damit nicht mehr kopflos auf Linux lauffähig. Die
|
||||
/// Modulprojekte bleiben deshalb frei von UI-Code; ihr <c>RegisterUi</c> ist leer, und die Shell
|
||||
/// verdrahtet die Fenster zentral. Die Modul-Dienste kommen unverändert aus dem DI-Container.</para>
|
||||
///
|
||||
/// <para>Registriert wird nur, was auch geladen ist: fehlt ein Modul in dieser Sitzung, entfällt
|
||||
/// sein Fenster, und der Launcher zeigt es gar nicht erst an.</para>
|
||||
/// </summary>
|
||||
public static class ModuleViews
|
||||
{
|
||||
public static void Register(IModuleUiHost host, IServiceProvider sp)
|
||||
{
|
||||
RegisterIfLoaded(sp, "CongressTrading", () => host.RegisterView(new ModuleView
|
||||
{
|
||||
Id = "congresstrading.main", Title = "Congress Trading", Group = "CongressTrading", Order = 100,
|
||||
CreateView = () => new CongressTradingWindow(
|
||||
host,
|
||||
sp.GetRequiredService<CongressRepository>(),
|
||||
sp.GetRequiredService<WorkerEngine>(),
|
||||
sp.GetRequiredService<IPortfolioService>(),
|
||||
sp.GetRequiredService<LoggingService>())
|
||||
}));
|
||||
|
||||
RegisterIfLoaded(sp, "Supervisor", () => host.RegisterView(new ModuleView
|
||||
{
|
||||
Id = "supervisor.main", Title = "Supervisor", Group = "Supervisor", Order = 300,
|
||||
CreateView = () => new SupervisorWindow(
|
||||
host,
|
||||
sp.GetRequiredService<SupervisorAgent>(),
|
||||
sp.GetRequiredService<DossierService>(),
|
||||
sp.GetRequiredService<ISupervisorReportRepository>(),
|
||||
sp.GetRequiredService<LoggingService>())
|
||||
}));
|
||||
|
||||
RegisterIfLoaded(sp, "Accounting", () => host.RegisterView(new ModuleView
|
||||
{
|
||||
Id = "accounting.main", Title = "Accounting", Group = "Accounting", Order = 400,
|
||||
CreateView = () => new AccountingWindow(
|
||||
host,
|
||||
sp.GetRequiredService<ILedgerRepository>(),
|
||||
sp.GetRequiredService<IIngestRunRepository>(),
|
||||
sp.GetRequiredService<AccountingReportService>(),
|
||||
sp.GetRequiredService<AccountingIngestService>(),
|
||||
sp.GetRequiredService<LoggingService>())
|
||||
}));
|
||||
}
|
||||
|
||||
/// <summary>Registriert die Ansicht nur, wenn das Modul in dieser Sitzung geladen ist.</summary>
|
||||
private static void RegisterIfLoaded(IServiceProvider sp, string moduleName, Action register)
|
||||
{
|
||||
if (sp.GetServices<IModule>().Any(m => string.Equals(m.Name, moduleName, StringComparison.OrdinalIgnoreCase)))
|
||||
register();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using IBKRTrader.Core.Modularity;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace IBKRTrader.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Die Dienste, die es nur mit Oberfläche gibt. Alles andere kommt aus
|
||||
/// <c>AppHostBuilder</c> und ist mit dem kopflosen Daemon geteilt.
|
||||
/// </summary>
|
||||
public static class ShellServices
|
||||
{
|
||||
public static void Register(IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddSingleton<AvaloniaUiHost>();
|
||||
services.AddSingleton<IModuleUiHost>(sp => sp.GetRequiredService<AvaloniaUiHost>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using IBKRTrader.App.ViewModels;
|
||||
using IBKRTrader.App.Views;
|
||||
using IBKRTrader.Core.Modularity;
|
||||
using IBKRTrader.Core.Settings;
|
||||
using IBKRTrader.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace IBKRTrader.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Konstruktionsprüfung aller Fenster – ohne Message-Loop und ohne laufende Dienste.
|
||||
///
|
||||
/// <para>Nachfolger des <c>--smoke-ui</c>-Laufs der WinForms-Shell, der Konstruktionsfehler
|
||||
/// zuverlässig gefangen hat. Der Host wird bewusst <b>nicht</b> gestartet: sonst liefen Worker,
|
||||
/// Broker-Verbindungen und Marktdaten-Abrufe gegen die echten Endpunkte an – für eine reine
|
||||
/// Konstruktionsprüfung unerwünscht, auf einem Build-Server schlicht falsch.</para>
|
||||
///
|
||||
/// <para>Im Gegensatz zu WinForms braucht Avalonia dafür kein Anzeigegerät:
|
||||
/// <c>SetupWithoutStarting</c> initialisiert das Framework, ohne ein Fenster zu zeigen. Damit ist
|
||||
/// diese Prüfung erstmals CI-tauglich.</para>
|
||||
/// </summary>
|
||||
public static class SmokeUi
|
||||
{
|
||||
public static int Run()
|
||||
{
|
||||
Program.BuildAvaloniaApp().SetupWithoutStarting();
|
||||
|
||||
var modules = AppHostBuilder.CreateModules();
|
||||
using var host = AppHostBuilder.Build(modules, ShellServices.Register);
|
||||
App.Services = host.Services;
|
||||
|
||||
var uiHost = host.Services.GetRequiredService<AvaloniaUiHost>();
|
||||
CoreViews.Register(uiHost, host.Services);
|
||||
foreach (var module in modules)
|
||||
module.RegisterUi(uiHost, host.Services);
|
||||
ModuleViews.Register(uiHost, host.Services);
|
||||
ViewIcons.AssignDefaults(uiHost);
|
||||
|
||||
var failures = 0;
|
||||
Console.WriteLine("=== Smoke-UI: Fenster-Konstruktion (Avalonia) ===");
|
||||
|
||||
foreach (var view in uiHost.Views)
|
||||
failures += Check(view.Id, view.Title, () => view.CreateView());
|
||||
|
||||
failures += Check("shell.launcher", "Launcher", () => new LauncherWindow(uiHost, host.Services));
|
||||
failures += Check("shell.shutdown", "Beenden-Abfrage", () => new ShutdownConfirmWindow());
|
||||
|
||||
// Die Einstellungsmaske entsteht aus den Attributen von AppSettings. Ein Fenster kann
|
||||
// fehlerfrei konstruieren und trotzdem leer sein, wenn die Attribute verlorengehen –
|
||||
// deshalb hier gegen die tatsächliche Feldzahl prüfen.
|
||||
failures += CheckSettingsForm(host.Services.GetRequiredService<SettingsService>());
|
||||
|
||||
Console.WriteLine(failures == 0 ? "=== Smoke-UI OK ===" : $"=== Smoke-UI: {failures} Fehler ===");
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static int Check(string id, string title, Func<object> construct)
|
||||
{
|
||||
try
|
||||
{
|
||||
_ = construct();
|
||||
Console.WriteLine($"[OK] {id} ({title})");
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[FEHLER] {id}: {ex.GetType().Name}: {ex.Message}");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private static int CheckSettingsForm(SettingsService settings)
|
||||
{
|
||||
try
|
||||
{
|
||||
var sections = SettingsModelBuilder.Build(settings.Settings);
|
||||
var fieldCount = sections.Sum(s => s.Fields.Count);
|
||||
|
||||
if (sections.Count == 0 || fieldCount == 0)
|
||||
{
|
||||
Console.WriteLine("[FEHLER] Einstellungsmaske: keine Felder aus AppSettings ermittelt " +
|
||||
"(Category-/DisplayName-Attribute verloren?).");
|
||||
return 1;
|
||||
}
|
||||
|
||||
Console.WriteLine($"[OK] Einstellungsmaske: {sections.Count} Abschnitte, {fieldCount} Felder");
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[FEHLER] Einstellungsmaske: {ex.GetType().Name}: {ex.Message}");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Platform;
|
||||
using IBKRTrader.Core.Modularity;
|
||||
|
||||
namespace IBKRTrader.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Löst die toolkit-neutralen <see cref="ModuleView.IconKey"/>-Schlüssel gegen die
|
||||
/// Avalonia-Bildressourcen auf. Gegenstück zum gleichnamigen Helfer der WinForms-Shell –
|
||||
/// <b>dieselben Schlüssel, dieselben PNG-Dateien</b>, sodass Core und Module unverändert bleiben.
|
||||
/// </summary>
|
||||
public static class ViewIcons
|
||||
{
|
||||
/// <summary>Symbol-Schlüssel → Dateiname unter <c>Resources/</c> (als Avalonia-Asset eingebettet).</summary>
|
||||
private static readonly Dictionary<string, string> FileByKey = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["dashboard"] = "dashboard.png",
|
||||
["workers"] = "system_time.png",
|
||||
["logs"] = "error_log.png",
|
||||
["settings"] = "setting_tools.png",
|
||||
["congresstrading"] = "cross_reference.png",
|
||||
["accounting"] = "coins_in_hand.png",
|
||||
["supervisor"] = "token_quantifier.png",
|
||||
};
|
||||
|
||||
/// <summary>Standard-Symbolschlüssel je View-ID – identisch zur WinForms-Shell.</summary>
|
||||
private static readonly Dictionary<string, string> DefaultKeyByViewId = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["core.dashboard"] = "dashboard",
|
||||
["core.workers"] = "workers",
|
||||
["core.logs"] = "logs",
|
||||
["core.settings"] = "settings",
|
||||
["congresstrading.main"] = "congresstrading",
|
||||
["accounting.main"] = "accounting",
|
||||
["supervisor.main"] = "supervisor",
|
||||
};
|
||||
|
||||
private static readonly ConcurrentDictionary<string, Bitmap?> Cache = new();
|
||||
|
||||
/// <summary>Bild zum Schlüssel, oder <c>null</c> (kein Symbol / Datei fehlt).</summary>
|
||||
public static Bitmap? Resolve(string? iconKey)
|
||||
{
|
||||
if (iconKey is null || !FileByKey.TryGetValue(iconKey, out var file)) return null;
|
||||
|
||||
return Cache.GetOrAdd(iconKey, _ =>
|
||||
{
|
||||
try
|
||||
{
|
||||
using var stream = AssetLoader.Open(
|
||||
new Uri($"avares://IBKRTrader.App/Assets/{file}"));
|
||||
return new Bitmap(stream);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ein fehlendes Symbol darf die Oberfläche nie aufhalten – dann eben nur Text.
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Setzt bei allen registrierten Views den Standard-Schlüssel, falls noch keiner gesetzt ist.</summary>
|
||||
public static void AssignDefaults(IModuleUiHost host)
|
||||
{
|
||||
foreach (var view in host.Views)
|
||||
if (view.IconKey is null && DefaultKeyByViewId.TryGetValue(view.Id, out var key))
|
||||
view.IconKey = key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using IBKRTrader.Core.Modularity;
|
||||
|
||||
namespace IBKRTrader.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Baut das gemeinsame Fenster-Menü, das auf JEDEM Fenster erscheint und das Wechseln zwischen
|
||||
/// allen Fenstern (Launcher + Core + Module) erlaubt. Es nutzt nur den Core-Contract
|
||||
/// <see cref="IModuleUiHost"/> und funktioniert deshalb auch aus Modul-Fenstern.
|
||||
///
|
||||
/// <para>Gegenstück zum gleichnamigen WinForms-Helfer – gleiches Verhalten, anderes Toolkit.</para>
|
||||
/// </summary>
|
||||
public static class WindowMenu
|
||||
{
|
||||
/// <summary>
|
||||
/// Verdrahtet ein <see cref="Menu"/> mit der Fensterliste: füllt es sofort und baut es bei
|
||||
/// jeder Änderung des Offen-Status neu auf. Die Registrierung wird beim Entladen gelöst.
|
||||
/// </summary>
|
||||
/// <param name="currentViewId">ID der eigenen View, oder <c>null</c> im Launcher.</param>
|
||||
public static void Wire(Menu menu, IModuleUiHost host, string? currentViewId)
|
||||
{
|
||||
void Refresh()
|
||||
{
|
||||
// Der Offen-Status kann aus einem beliebigen Fenster gemeldet werden – der Aufbau
|
||||
// der Menüleiste gehört aber auf den UI-Thread.
|
||||
if (Dispatcher.UIThread.CheckAccess()) Populate(menu, host, currentViewId);
|
||||
else Dispatcher.UIThread.Post(() => Populate(menu, host, currentViewId));
|
||||
}
|
||||
|
||||
Populate(menu, host, currentViewId);
|
||||
host.OpenStateChanged += Refresh;
|
||||
menu.DetachedFromVisualTree += (_, _) => host.OpenStateChanged -= Refresh;
|
||||
}
|
||||
|
||||
/// <summary>Baut die Menüleiste komplett neu auf.</summary>
|
||||
public static void Populate(Menu menu, IModuleUiHost host, string? currentViewId)
|
||||
{
|
||||
var items = new List<Control>
|
||||
{
|
||||
BuildItem("Launcher", null, isCurrent: currentViewId is null,
|
||||
isOpen: false, onClick: host.ActivateMain)
|
||||
};
|
||||
|
||||
foreach (var view in host.Views.OrderBy(v => v.Order).ThenBy(v => v.Title))
|
||||
{
|
||||
var id = view.Id;
|
||||
items.Add(BuildItem(view.Title, view.IconKey,
|
||||
isCurrent: id == currentViewId,
|
||||
isOpen: host.IsOpen(id),
|
||||
onClick: () => host.OpenView(id)));
|
||||
}
|
||||
|
||||
// Kontextabhängige rechte Aktion: nur der Launcher darf die Anwendung beenden; jedes
|
||||
// andere Fenster bietet nur „Fenster schließen" (Module laufen weiter).
|
||||
if (currentViewId is null)
|
||||
{
|
||||
items.Add(BuildItem("Beenden", null, false, false, host.RequestShutdown, alignRight: true));
|
||||
}
|
||||
else
|
||||
{
|
||||
items.Add(BuildItem("Fenster schließen", null, false, false,
|
||||
() => (menu.GetVisualRoot() as Window)?.Close(), alignRight: true));
|
||||
}
|
||||
|
||||
menu.ItemsSource = items;
|
||||
}
|
||||
|
||||
private static MenuItem BuildItem(string title, string? iconKey, bool isCurrent, bool isOpen,
|
||||
Action onClick, bool alignRight = false)
|
||||
{
|
||||
var item = new MenuItem
|
||||
{
|
||||
Header = title,
|
||||
FontWeight = isCurrent ? FontWeight.Bold : FontWeight.Normal,
|
||||
// Offene Fenster werden hervorgehoben – Ersatz für das Häkchen der WinForms-Leiste.
|
||||
Foreground = isOpen && !isCurrent ? Brushes.SteelBlue : null,
|
||||
};
|
||||
|
||||
if (alignRight) item.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
|
||||
var icon = ViewIcons.Resolve(iconKey);
|
||||
if (icon is not null)
|
||||
item.Icon = new Image { Source = icon, Width = 16, Height = 16 };
|
||||
|
||||
item.Click += (_, _) => onClick();
|
||||
return item;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user