feat: Phase 0 shells, design system, server skeleton, Docker and CI
- Titano.Ui: DESIGN.md tokens (dark/light), generated 16-px icon set, styles for all standard controls, custom chrome window with snap layouts, rail, job bar, Auto/manual slider, chips, toasts. - Titano desktop shell with sections, Settings (language, theme), About and a --capture screenshot mode. - Titano Server skeleton: env/server.json configuration, self-signed TLS with fingerprint, /health, /server/info, i18n endpoint and the embedded admin panel; in-process server tests. - Docker image (multi-arch, PUID/PGID, health check), compose file, Unraid template; CI, release and nightly workflows; changelog tool. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
122 files changed
+6838
-22
No files matched your search
@@ -1,4 +1,12 @@
|
||||
<Application x:Class="Titano.App.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
ShutdownMode="OnMainWindowClose">
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="Shell/SectionTemplates.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
@@ -1,7 +1,97 @@
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Ui.Mvvm;
|
||||
using Titano.Ui.Theming;
|
||||
|
||||
namespace Titano.App;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
private FileLogSink? _log;
|
||||
|
||||
public AppEnvironment Environment { get; private set; } = null!;
|
||||
public AppSettings Settings { get; private set; } = null!;
|
||||
|
||||
public static new App Current => (App)Application.Current;
|
||||
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
base.OnStartup(e);
|
||||
Environment = AppEnvironment.Detect();
|
||||
_log = new FileLogSink(Environment.LogDirectory, "titano");
|
||||
Log.SetSink(_log);
|
||||
Log.Info("app", $"Titano {typeof(App).Assembly.GetName().Version} starting; data at {Environment.DataDirectory}");
|
||||
|
||||
Settings = AppSettings.Load(Environment.SettingsPath);
|
||||
ApplyLanguage(Settings.Language);
|
||||
ThemeManager.Initialize(this, Settings.Theme);
|
||||
|
||||
DispatcherUnhandledException += OnUnhandledException;
|
||||
AppDomain.CurrentDomain.UnhandledException += (_, args) => Log.Error("app", "Unhandled exception", args.ExceptionObject as Exception);
|
||||
TaskScheduler.UnobservedTaskException += (_, args) =>
|
||||
{
|
||||
Log.Error("app", "Unobserved task exception", args.Exception);
|
||||
args.SetObserved();
|
||||
};
|
||||
|
||||
var shell = new ShellViewModel(Settings);
|
||||
AsyncRelayCommand.Failed += ex => shell.ReportError(ex);
|
||||
var window = new MainWindow(shell);
|
||||
MainWindow = window;
|
||||
|
||||
var captureIndex = Array.IndexOf(e.Args, "--capture");
|
||||
if (captureIndex >= 0)
|
||||
{
|
||||
var dir = captureIndex + 1 < e.Args.Length ? e.Args[captureIndex + 1] : "screenshots";
|
||||
ScreenCapture.Run(window, shell, dir);
|
||||
return;
|
||||
}
|
||||
window.Show();
|
||||
}
|
||||
|
||||
/// <summary>Switches the UI language at run time (BRIEF §16) and remembers the choice.</summary>
|
||||
public void ApplyLanguage(string? code)
|
||||
{
|
||||
var culture = Languages.BestMatch(code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code));
|
||||
CultureInfo.DefaultThreadCurrentUICulture = culture;
|
||||
CultureInfo.CurrentUICulture = culture;
|
||||
Loc.SetCulture(culture);
|
||||
foreach (Window w in Windows)
|
||||
w.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
|
||||
}
|
||||
|
||||
public void SaveSettings()
|
||||
{
|
||||
try
|
||||
{
|
||||
Settings.Save(Environment.SettingsPath);
|
||||
}
|
||||
catch (System.IO.IOException ex)
|
||||
{
|
||||
Log.Warning("app", "Settings not saved", ex);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnExit(ExitEventArgs e)
|
||||
{
|
||||
SaveSettings();
|
||||
Log.Info("app", "Titano exiting");
|
||||
_log?.Dispose();
|
||||
base.OnExit(e);
|
||||
}
|
||||
|
||||
private void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
|
||||
{
|
||||
Log.Error("app", "Unhandled UI exception", e.Exception);
|
||||
if (MainWindow?.DataContext is ShellViewModel shell)
|
||||
{
|
||||
shell.ReportError(e.Exception);
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.IO;
|
||||
|
||||
namespace Titano.App.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Where the client keeps its data (BRIEF §6.2): <c>%LOCALAPPDATA%\Titano</c>, or <c>.\data</c> next to the
|
||||
/// executable when <c>portable.txt</c> exists. Never inside Documents/OneDrive (SQLite corrupts in synced folders).
|
||||
/// </summary>
|
||||
public sealed class AppEnvironment
|
||||
{
|
||||
private AppEnvironment(string dataDirectory, bool portable)
|
||||
{
|
||||
DataDirectory = dataDirectory;
|
||||
IsPortable = portable;
|
||||
Directory.CreateDirectory(DataDirectory);
|
||||
Directory.CreateDirectory(LogDirectory);
|
||||
Directory.CreateDirectory(CacheDirectory);
|
||||
}
|
||||
|
||||
public string DataDirectory { get; }
|
||||
public bool IsPortable { get; }
|
||||
public string LogDirectory => Path.Combine(DataDirectory, "logs");
|
||||
public string CacheDirectory => Path.Combine(DataDirectory, "cache");
|
||||
public string DatabasePath => Path.Combine(DataDirectory, "titano.db");
|
||||
public string SettingsPath => Path.Combine(DataDirectory, "settings.json");
|
||||
|
||||
public static AppEnvironment Detect()
|
||||
{
|
||||
var exeDir = AppContext.BaseDirectory;
|
||||
if (File.Exists(Path.Combine(exeDir, "portable.txt")))
|
||||
return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true);
|
||||
var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
return new AppEnvironment(Path.Combine(local, "Titano"), portable: false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Ui.Theming;
|
||||
|
||||
namespace Titano.App.Infrastructure;
|
||||
|
||||
/// <summary>Per-user preferences needed before the database opens (language, theme, window layout).</summary>
|
||||
public sealed class AppSettings
|
||||
{
|
||||
public string? Language { get; set; }
|
||||
public AppTheme Theme { get; set; } = AppTheme.Dark;
|
||||
public bool RailCollapsed { get; set; }
|
||||
public bool CheckForUpdates { get; set; } = true;
|
||||
public bool AnonymousUsageCounts { get; set; }
|
||||
public string? LastArchivePath { get; set; }
|
||||
public WindowPlacement? Window { get; set; }
|
||||
|
||||
public sealed class WindowPlacement
|
||||
{
|
||||
public double Left { get; set; }
|
||||
public double Top { get; set; }
|
||||
public double Width { get; set; }
|
||||
public double Height { get; set; }
|
||||
public bool Maximized { get; set; }
|
||||
}
|
||||
|
||||
public static AppSettings Load(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
return JsonSerializer.Deserialize(File.ReadAllText(path), AppSettingsJson.Default.AppSettings) ?? new AppSettings();
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// A corrupt settings file must never block startup; defaults apply.
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
return new AppSettings();
|
||||
}
|
||||
|
||||
public void Save(string path) => AtomicFile.WriteAllText(path, JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings));
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)]
|
||||
[JsonSerializable(typeof(AppSettings))]
|
||||
internal sealed partial class AppSettingsJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,34 @@
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.App.Infrastructure;
|
||||
|
||||
/// <summary>Culture-aware number, size and duration formatting for the UI.</summary>
|
||||
public static class Formatting
|
||||
{
|
||||
private static readonly string[] ByteUnits = ["B", "KB", "MB", "GB", "TB", "PB"];
|
||||
|
||||
/// <summary>1,536 → "1.5 KB" (decimal units, as Explorer shows for drives).</summary>
|
||||
public static string Bytes(long bytes)
|
||||
{
|
||||
double value = bytes;
|
||||
var unit = 0;
|
||||
while (value >= 1000 && unit < ByteUnits.Length - 1)
|
||||
{
|
||||
value /= 1000;
|
||||
unit++;
|
||||
}
|
||||
var format = unit == 0 || value >= 100 ? "0" : "0.#";
|
||||
return value.ToString(format, Loc.Culture) + " " + ByteUnits[unit];
|
||||
}
|
||||
|
||||
public static string Count(long n) => n.ToString("N0", Loc.Culture);
|
||||
|
||||
/// <summary>Compact duration: "2 h 00 m", "5 min", "40 s".</summary>
|
||||
public static string Duration(TimeSpan t)
|
||||
{
|
||||
if (t.TotalHours >= 24) return Loc.L("Common.Duration.Days", (int)t.TotalDays, t.Hours);
|
||||
if (t.TotalHours >= 1) return Loc.L("Common.Duration.Hours", (int)t.TotalHours, t.Minutes.ToString("00", Loc.Culture));
|
||||
if (t.TotalMinutes >= 1) return Loc.L("Common.Duration.Minutes", (int)Math.Round(t.TotalMinutes));
|
||||
return Loc.L("Common.Duration.Seconds", (int)Math.Round(t.TotalSeconds));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Titano.App.Infrastructure;
|
||||
|
||||
/// <summary>Public links (BRIEF §19.4). Overridable at build time via the TitanoReleasesRepo property.</summary>
|
||||
public static class ProductLinks
|
||||
{
|
||||
public static string ReleasesRepository { get; } =
|
||||
typeof(ProductLinks).Assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyMetadataAttribute), false)
|
||||
.OfType<System.Reflection.AssemblyMetadataAttribute>()
|
||||
.FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value ?? "alby96/titano-releases";
|
||||
|
||||
public static string Releases => $"https://github.com/{ReleasesRepository}/releases";
|
||||
|
||||
public static string LatestReleaseApi => $"https://api.github.com/repos/{ReleasesRepository}/releases/latest";
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace Titano.App.Infrastructure;
|
||||
|
||||
/// <summary>The only shell launches the product performs (BRIEF §8.6): open a URL, reveal a folder.</summary>
|
||||
public static class ShellActions
|
||||
{
|
||||
public static void OpenUrl(string url)
|
||||
{
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http" or "ms-windows-store")) return;
|
||||
Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true });
|
||||
}
|
||||
|
||||
public static void OpenFolder(string path)
|
||||
{
|
||||
if (!Directory.Exists(path)) return;
|
||||
Process.Start(new ProcessStartInfo(path) { UseShellExecute = true, Verb = "explore" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<UserControl x:Class="Titano.App.Sections.AboutView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
|
||||
<Grid Margin="20,16,20,20">
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="28,24" HorizontalAlignment="Left" VerticalAlignment="Top" MinWidth="560">
|
||||
<StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,20">
|
||||
<ui:BrandMarkIcon Width="56" Height="56" ShowPlate="True" />
|
||||
<StackPanel Margin="16,0,0,0" VerticalAlignment="Center">
|
||||
<TextBlock Text="{l:Loc Shell.AppName}" Style="{StaticResource Text.PageTitle}" FontSize="22" />
|
||||
<TextBlock Text="{Binding Version}" Style="{StaticResource Text.Secondary}" Margin="0,2,0,0" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="140" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="28" />
|
||||
<RowDefinition Height="28" />
|
||||
<RowDefinition Height="28" />
|
||||
<RowDefinition Height="28" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{l:Loc About.Runtime}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding Runtime}" />
|
||||
<TextBlock Grid.Row="1" Text="{l:Loc About.System}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding OperatingSystem}" />
|
||||
<TextBlock Grid.Row="2" Text="{l:Loc About.ThirdParty}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" Text="{l:Loc About.ThirdPartyNone}" />
|
||||
<TextBlock Grid.Row="3" Text="{l:Loc About.Data}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding DataFolder}" />
|
||||
</Grid>
|
||||
<StackPanel Orientation="Horizontal" Margin="0,20,0,0">
|
||||
<Button Content="{l:Loc About.Releases}" Command="{Binding OpenReleasesCommand}" ToolTip="{l:Loc Tooltips.About.Releases}" Margin="0,0,8,0" ui:ButtonIcon.Glyph="{StaticResource Icon.ExternalLink}" />
|
||||
<Button Content="{l:Loc About.OpenData}" Command="{Binding OpenDataFolderCommand}" ToolTip="{l:Loc Tooltips.About.OpenData}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,8 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
public partial class AboutView : UserControl
|
||||
{
|
||||
public AboutView() => InitializeComponent();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<UserControl x:Class="Titano.App.Sections.ArchiveView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
|
||||
<Grid Margin="20">
|
||||
<ui:EmptyState Message="{l:Loc Archive.Empty}" />
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,8 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
public partial class ArchiveView : UserControl
|
||||
{
|
||||
public ArchiveView() => InitializeComponent();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<UserControl x:Class="Titano.App.Sections.ImportView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
|
||||
<Grid Margin="20">
|
||||
<ui:EmptyState Message="{l:Loc Import.Empty}" />
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,8 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
public partial class ImportView : UserControl
|
||||
{
|
||||
public ImportView() => InitializeComponent();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<UserControl x:Class="Titano.App.Sections.JobsView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
|
||||
<Grid Margin="20">
|
||||
<ui:EmptyState Message="{l:Loc Jobs.Empty}" />
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,8 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
public partial class JobsView : UserControl
|
||||
{
|
||||
public JobsView() => InitializeComponent();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<UserControl x:Class="Titano.App.Sections.LibraryView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
|
||||
<Grid Margin="20">
|
||||
<ui:EmptyState Message="{l:Loc Library.Empty}">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Library.Empty.ImportCard}" Command="{Binding ImportCardCommand}" ToolTip="{l:Loc Tooltips.Library.ImportCard}" Margin="0,0,8,0" />
|
||||
<Button Content="{l:Loc Library.Empty.OpenArchive}" Command="{Binding OpenArchiveCommand}" ToolTip="{l:Loc Tooltips.Library.OpenArchive}" Margin="0,0,8,0" />
|
||||
<Button Content="{l:Loc Library.Empty.Connect}" Command="{Binding ConnectCommand}" ToolTip="{l:Loc Tooltips.Library.Connect}" />
|
||||
</StackPanel>
|
||||
</ui:EmptyState>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,8 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
public partial class LibraryView : UserControl
|
||||
{
|
||||
public LibraryView() => InitializeComponent();
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using System.Reflection;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Ui.Mvvm;
|
||||
using Titano.Ui.Theming;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>Library (home): sequences of the archive (BRIEF §12.2).</summary>
|
||||
public sealed class LibraryViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Library, "Icon.Library")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
public ICommand ImportCardCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Import));
|
||||
public ICommand OpenArchiveCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Archive));
|
||||
public ICommand ConnectCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Server));
|
||||
}
|
||||
|
||||
/// <summary>Card and folder import (BRIEF §12.4).</summary>
|
||||
public sealed class ImportViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Import, "Icon.Import")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
}
|
||||
|
||||
/// <summary>Sequence editor (BRIEF §12.3).</summary>
|
||||
public sealed class SequenceViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Sequence, "Icon.Sequence")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
public ICommand OpenLibraryCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Library));
|
||||
}
|
||||
|
||||
/// <summary>Archive manager (BRIEF §12.5).</summary>
|
||||
public sealed class ArchiveViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Archive, "Icon.Archive")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
}
|
||||
|
||||
/// <summary>Job queue and history (BRIEF §12.6).</summary>
|
||||
public sealed class JobsViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Jobs, "Icon.Jobs")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
}
|
||||
|
||||
/// <summary>Server connection and sync (BRIEF §12.7).</summary>
|
||||
public sealed class ServerViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Server, "Icon.Server")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
}
|
||||
|
||||
public sealed record LanguageOption(string Code, string Name);
|
||||
|
||||
/// <summary>Settings (BRIEF §12.8): section list on the left, controls on the right, tooltips only.</summary>
|
||||
public sealed class SettingsViewModel : SectionViewModel
|
||||
{
|
||||
private readonly AppSettings _settings;
|
||||
private string _page = "General";
|
||||
|
||||
public SettingsViewModel(ShellViewModel shell, AppSettings settings)
|
||||
: base(SectionKey.Settings, "Icon.Settings")
|
||||
{
|
||||
Shell = shell;
|
||||
_settings = settings;
|
||||
Languages = Core.Localization.Languages.Shipped
|
||||
.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))
|
||||
.ToList();
|
||||
SelectPageCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is string page) Page = page;
|
||||
});
|
||||
}
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
public IReadOnlyList<string> Pages { get; } = ["General", "Advanced"];
|
||||
|
||||
public ICommand SelectPageCommand { get; }
|
||||
|
||||
public string Page
|
||||
{
|
||||
get => _page;
|
||||
set => Set(ref _page, value);
|
||||
}
|
||||
|
||||
public IReadOnlyList<LanguageOption> Languages { get; }
|
||||
|
||||
public LanguageOption SelectedLanguage
|
||||
{
|
||||
get => Languages.FirstOrDefault(l => l.Code.Equals(Loc.Culture.Name, StringComparison.OrdinalIgnoreCase)) ?? Languages[0];
|
||||
set
|
||||
{
|
||||
if (value is null) return;
|
||||
_settings.Language = value.Code;
|
||||
App.Current.ApplyLanguage(value.Code);
|
||||
App.Current.SaveSettings();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsDarkTheme
|
||||
{
|
||||
get => _settings.Theme == AppTheme.Dark;
|
||||
set
|
||||
{
|
||||
if (value) ApplyTheme(AppTheme.Dark);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsLightTheme
|
||||
{
|
||||
get => _settings.Theme == AppTheme.Light;
|
||||
set
|
||||
{
|
||||
if (value) ApplyTheme(AppTheme.Light);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsSystemTheme
|
||||
{
|
||||
get => _settings.Theme == AppTheme.System;
|
||||
set
|
||||
{
|
||||
if (value) ApplyTheme(AppTheme.System);
|
||||
}
|
||||
}
|
||||
|
||||
public bool CheckForUpdates
|
||||
{
|
||||
get => _settings.CheckForUpdates;
|
||||
set
|
||||
{
|
||||
_settings.CheckForUpdates = value;
|
||||
App.Current.SaveSettings();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyTheme(AppTheme theme)
|
||||
{
|
||||
_settings.Theme = theme;
|
||||
ThemeManager.Apply(theme);
|
||||
App.Current.SaveSettings();
|
||||
OnPropertyChanged(nameof(IsDarkTheme));
|
||||
OnPropertyChanged(nameof(IsLightTheme));
|
||||
OnPropertyChanged(nameof(IsSystemTheme));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>About (BRIEF §12.9).</summary>
|
||||
public sealed class AboutViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.About, "Icon.About")
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
|
||||
public string Version => typeof(App).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
|
||||
|
||||
public string Runtime => System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription;
|
||||
|
||||
public string OperatingSystem => System.Runtime.InteropServices.RuntimeInformation.OSDescription;
|
||||
|
||||
public string DataFolder => App.Current.Environment.DataDirectory;
|
||||
|
||||
public ICommand OpenDataFolderCommand => new RelayCommand(() => ShellActions.OpenFolder(DataFolder));
|
||||
|
||||
public ICommand OpenReleasesCommand => new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Releases));
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<UserControl x:Class="Titano.App.Sections.SequenceView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
|
||||
<Grid Margin="20">
|
||||
<ui:EmptyState Message="{l:Loc Editor.Empty}">
|
||||
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Shell.Nav.Library}" Command="{Binding OpenLibraryCommand}" ToolTip="{l:Loc Tooltips.Nav.Library}" />
|
||||
</ui:EmptyState>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,8 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
public partial class SequenceView : UserControl
|
||||
{
|
||||
public SequenceView() => InitializeComponent();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<UserControl x:Class="Titano.App.Sections.ServerView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
|
||||
<Grid Margin="20">
|
||||
<ui:EmptyState Message="{l:Loc Server.Empty}" />
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,8 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
public partial class ServerView : UserControl
|
||||
{
|
||||
public ServerView() => InitializeComponent();
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<UserControl x:Class="Titano.App.Sections.SettingsView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
|
||||
xmlns:s="clr-namespace:Titano.App.Sections">
|
||||
<Grid Margin="20,16,20,20">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="200" />
|
||||
<ColumnDefinition Width="16" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Section list -->
|
||||
<ListBox ItemsSource="{Binding Pages}" SelectedItem="{Binding Page}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Converter={x:Static s:SettingsPageNameConverter.Instance}}" />
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<Border Grid.Column="2" Style="{StaticResource Border.Panel}" Padding="22,18">
|
||||
<Grid>
|
||||
<!-- General -->
|
||||
<StackPanel x:Name="General">
|
||||
<StackPanel.Style>
|
||||
<Style TargetType="StackPanel">
|
||||
<Setter Property="Visibility" Value="Collapsed" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding Page}" Value="General"><Setter Property="Visibility" Value="Visible" /></DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</StackPanel.Style>
|
||||
<TextBlock Text="{l:Loc Settings.Page.General}" Style="{StaticResource Text.PageTitle}" Margin="0,0,0,16" />
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="180" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="44" />
|
||||
<RowDefinition Height="44" />
|
||||
<RowDefinition Height="44" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{l:Loc Settings.General.Language}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<ComboBox Grid.Column="1" Width="240" HorizontalAlignment="Left" ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}"
|
||||
DisplayMemberPath="Name" ToolTip="{l:Loc Tooltips.Settings.Language}" />
|
||||
<TextBlock Grid.Row="1" Text="{l:Loc Settings.General.Theme}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<RadioButton GroupName="Theme" Content="{l:Loc Settings.General.Theme.Dark}" IsChecked="{Binding IsDarkTheme}" ToolTip="{l:Loc Tooltips.Settings.ThemeDark}" Margin="0,0,20,0" />
|
||||
<RadioButton GroupName="Theme" Content="{l:Loc Settings.General.Theme.Light}" IsChecked="{Binding IsLightTheme}" ToolTip="{l:Loc Tooltips.Settings.ThemeLight}" Margin="0,0,20,0" />
|
||||
<RadioButton GroupName="Theme" Content="{l:Loc Settings.General.Theme.System}" IsChecked="{Binding IsSystemTheme}" ToolTip="{l:Loc Tooltips.Settings.ThemeSystem}" />
|
||||
</StackPanel>
|
||||
<TextBlock Grid.Row="2" Text="{l:Loc Settings.General.Updates}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<CheckBox Grid.Row="2" Grid.Column="1" Content="{l:Loc Settings.General.CheckOnStart}" IsChecked="{Binding CheckForUpdates}" ToolTip="{l:Loc Tooltips.Settings.CheckForUpdates}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Advanced -->
|
||||
<StackPanel>
|
||||
<StackPanel.Style>
|
||||
<Style TargetType="StackPanel">
|
||||
<Setter Property="Visibility" Value="Collapsed" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding Page}" Value="Advanced"><Setter Property="Visibility" Value="Visible" /></DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</StackPanel.Style>
|
||||
<TextBlock Text="{l:Loc Settings.Page.Advanced}" Style="{StaticResource Text.PageTitle}" Margin="0,0,0,16" />
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="180" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="44" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{l:Loc Settings.Advanced.DataFolder}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBox Grid.Column="1" IsReadOnly="True" Text="{Binding Shell.About.DataFolder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.DataFolder}" />
|
||||
<Button Grid.Column="2" Margin="8,0,0,0" Content="{l:Loc Common.Open}" Command="{Binding Shell.About.OpenDataFolderCommand}" ToolTip="{l:Loc Tooltips.Settings.OpenDataFolder}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Globalization;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
public partial class SettingsView : UserControl
|
||||
{
|
||||
public SettingsView() => InitializeComponent();
|
||||
}
|
||||
|
||||
/// <summary>Settings page id → localized page name.</summary>
|
||||
public sealed class SettingsPageNameConverter : IValueConverter
|
||||
{
|
||||
public static SettingsPageNameConverter Instance { get; } = new();
|
||||
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is string page ? Loc.L("Settings.Page." + page) : string.Empty;
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<ui:TitanoWindow x:Class="Titano.App.Shell.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
|
||||
xmlns:shell="clr-namespace:Titano.App.Shell"
|
||||
Title="{Binding WindowTitle}"
|
||||
Width="1440" Height="900" MinWidth="1200" MinHeight="760"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Navigation rail: full names, collapsible to icons (BRIEF §12.1). -->
|
||||
<Border x:Name="Rail" Background="{DynamicResource Brush.Chrome}" Width="128" ui:NavRail.IsCollapsed="{Binding IsRailCollapsed}">
|
||||
<DockPanel Margin="8,8,8,8" LastChildFill="False">
|
||||
<Button DockPanel.Dock="Top" Style="{StaticResource Button.IconSubtle}" HorizontalAlignment="Left" Margin="0,0,0,6"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.Menu}" Command="{Binding ToggleRailCommand}"
|
||||
ToolTip="{Binding RailToggleToolTip}" AutomationProperties.Name="{Binding RailToggleToolTip}" />
|
||||
<ItemsControl DockPanel.Dock="Top" ItemsSource="{Binding TopSections}" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type shell:SectionViewModel}">
|
||||
<ui:NavRailButton GroupName="Rail" Glyph="{Binding Glyph}" Content="{Binding Label}" Badge="{Binding Badge}"
|
||||
IsChecked="{Binding IsSelected}" ToolTip="{Binding ToolTip}" AutomationProperties.Name="{Binding Label}"
|
||||
Command="{Binding DataContext.NavigateCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}" CommandParameter="{Binding}" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<ItemsControl DockPanel.Dock="Bottom" ItemsSource="{Binding BottomSections}" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type shell:SectionViewModel}">
|
||||
<ui:NavRailButton GroupName="Rail" Glyph="{Binding Glyph}" Content="{Binding Label}" Badge="{Binding Badge}"
|
||||
IsChecked="{Binding IsSelected}" ToolTip="{Binding ToolTip}" AutomationProperties.Name="{Binding Label}"
|
||||
Command="{Binding DataContext.NavigateCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}" CommandParameter="{Binding}" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
|
||||
<Grid Grid.Column="1">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<ui:JobBar Text="{Binding JobText}" Progress="{Binding JobProgress}" IsActive="{Binding IsJobActive}" IsIndeterminate="{Binding IsJobIndeterminate}"
|
||||
StopCommand="{Binding StopJobCommand}" StopToolTip="{l:Loc Tooltips.Shell.StopJob}" />
|
||||
|
||||
<ContentControl Grid.Row="1" Content="{Binding Current}" Focusable="False" />
|
||||
|
||||
<!-- Status strip -->
|
||||
<Border Grid.Row="2" Height="30" Background="{DynamicResource Brush.Chrome}" Padding="20,0">
|
||||
<StackPanel Orientation="Horizontal" TextElement.FontSize="12" TextElement.Foreground="{DynamicResource Brush.TextMuted}">
|
||||
<TextBlock Text="{Binding SequencesText}" Margin="0,0,18,0" />
|
||||
<TextBlock Text="{Binding PhotosText}" Margin="0,0,18,0" />
|
||||
<TextBlock Text="{Binding StorageText}" Margin="0,0,18,0" />
|
||||
<TextBlock x:Name="Connection" Text="{Binding ConnectionText}" Margin="0,0,18,0" />
|
||||
<TextBlock Text="{Binding JobsText}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<ui:ToastHost x:Name="Toasts" Grid.Row="0" Grid.RowSpan="3" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
</ui:TitanoWindow>
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Collections.Specialized;
|
||||
using System.Windows;
|
||||
using Titano.Ui.Controls;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
|
||||
public partial class MainWindow : TitanoWindow
|
||||
{
|
||||
private readonly ShellViewModel _shell;
|
||||
|
||||
public MainWindow(ShellViewModel shell)
|
||||
{
|
||||
_shell = shell;
|
||||
DataContext = shell;
|
||||
InitializeComponent();
|
||||
Rail.Width = shell.IsRailCollapsed ? 48 : 128;
|
||||
shell.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName is nameof(ShellViewModel.IsRailCollapsed) or "")
|
||||
Rail.Width = shell.IsRailCollapsed ? 48 : 128;
|
||||
if (e.PropertyName is nameof(ShellViewModel.IsConnected) or "")
|
||||
Connection.Foreground = (System.Windows.Media.Brush)FindResource(shell.IsConnected ? "Brush.Accent" : "Brush.TextMuted");
|
||||
};
|
||||
shell.PendingToasts.CollectionChanged += OnToastRequested;
|
||||
RestorePlacement();
|
||||
Closing += (_, _) => SavePlacement();
|
||||
}
|
||||
|
||||
private void OnToastRequested(object? sender, NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
if (e.Action != NotifyCollectionChangedAction.Add || e.NewItems is null) return;
|
||||
foreach (Toast t in e.NewItems) Toasts.Show(t);
|
||||
Dispatcher.BeginInvoke(() => _shell.PendingToasts.Clear());
|
||||
}
|
||||
|
||||
private void RestorePlacement()
|
||||
{
|
||||
var p = App.Current.Settings.Window;
|
||||
if (p is null || p.Width < MinWidth || p.Height < MinHeight) return;
|
||||
var virtualScreen = new Rect(SystemParameters.VirtualScreenLeft, SystemParameters.VirtualScreenTop, SystemParameters.VirtualScreenWidth, SystemParameters.VirtualScreenHeight);
|
||||
var rect = new Rect(p.Left, p.Top, p.Width, p.Height);
|
||||
if (!virtualScreen.IntersectsWith(rect)) return;
|
||||
WindowStartupLocation = WindowStartupLocation.Manual;
|
||||
Left = p.Left;
|
||||
Top = p.Top;
|
||||
Width = p.Width;
|
||||
Height = p.Height;
|
||||
if (p.Maximized) WindowState = WindowState.Maximized;
|
||||
}
|
||||
|
||||
private void SavePlacement()
|
||||
{
|
||||
var b = RestoreBounds;
|
||||
App.Current.Settings.Window = new Infrastructure.AppSettings.WindowPlacement
|
||||
{
|
||||
Left = b.Left,
|
||||
Top = b.Top,
|
||||
Width = b.Width,
|
||||
Height = b.Height,
|
||||
Maximized = WindowState == WindowState.Maximized,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Threading;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Ui.Theming;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// <c>Titano.exe --capture <dir></c>: renders every section at 1440×900 in dark and light themes to PNG for
|
||||
/// visual regression and phase reports (BRIEF §20.2), then exits.
|
||||
/// </summary>
|
||||
public static class ScreenCapture
|
||||
{
|
||||
public static void Run(MainWindow window, ShellViewModel shell, string directory)
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
window.WindowStartupLocation = WindowStartupLocation.Manual;
|
||||
window.Left = -20000;
|
||||
window.Top = -20000;
|
||||
window.Width = 1440;
|
||||
window.Height = 900;
|
||||
window.ShowActivated = false;
|
||||
window.ShowInTaskbar = false;
|
||||
window.Show();
|
||||
|
||||
window.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var theme in new[] { AppTheme.Dark, AppTheme.Light })
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
foreach (var section in shell.AllSections)
|
||||
{
|
||||
shell.Navigate(section.Key);
|
||||
Settle(window);
|
||||
Save(window, Path.Combine(directory, $"{section.Key}-{theme.ToString().ToLowerInvariant()}.png"));
|
||||
}
|
||||
}
|
||||
Log.Info("capture", $"Screenshots written to {Path.GetFullPath(directory)}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error("capture", "Capture failed", ex);
|
||||
Environment.ExitCode = 1;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Application.Current.Shutdown();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void Settle(Window window)
|
||||
{
|
||||
window.UpdateLayout();
|
||||
// Let bindings, templates and deferred renders complete.
|
||||
window.Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, () => { });
|
||||
window.UpdateLayout();
|
||||
}
|
||||
|
||||
private static void Save(Window window, string path)
|
||||
{
|
||||
if (VisualTreeHelper.GetChildrenCount(window) == 0) return;
|
||||
var root = (FrameworkElement)VisualTreeHelper.GetChild(window, 0);
|
||||
var dpi = VisualTreeHelper.GetDpi(window);
|
||||
var width = (int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX);
|
||||
var height = (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY);
|
||||
if (width <= 0 || height <= 0) return;
|
||||
var bitmap = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
|
||||
bitmap.Render(root);
|
||||
var encoder = new PngBitmapEncoder();
|
||||
encoder.Frames.Add(BitmapFrame.Create(bitmap));
|
||||
using var stream = File.Create(path);
|
||||
encoder.Save(stream);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:s="clr-namespace:Titano.App.Sections">
|
||||
<!-- Section view model → view. -->
|
||||
<DataTemplate DataType="{x:Type s:LibraryViewModel}"><s:LibraryView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ImportViewModel}"><s:ImportView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:SequenceViewModel}"><s:SequenceView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ArchiveViewModel}"><s:ArchiveView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:JobsViewModel}"><s:JobsView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ServerViewModel}"><s:ServerView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:SettingsViewModel}"><s:SettingsView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:AboutViewModel}"><s:AboutView /></DataTemplate>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,59 @@
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
|
||||
public enum SectionKey
|
||||
{
|
||||
Library,
|
||||
Import,
|
||||
Sequence,
|
||||
Archive,
|
||||
Jobs,
|
||||
Server,
|
||||
Settings,
|
||||
About,
|
||||
}
|
||||
|
||||
/// <summary>A top-level destination of the navigation rail.</summary>
|
||||
public abstract class SectionViewModel(SectionKey key, string iconKey) : LocalizedViewModel
|
||||
{
|
||||
private bool _isSelected;
|
||||
private int _badge;
|
||||
|
||||
public SectionKey Key { get; } = key;
|
||||
|
||||
/// <summary>Resource key of the rail icon (e.g. "Icon.Library").</summary>
|
||||
public string IconKey { get; } = iconKey;
|
||||
|
||||
public IconData? Glyph => System.Windows.Application.Current?.TryFindResource(IconKey) as IconData;
|
||||
|
||||
/// <summary>Rail label ("Library").</summary>
|
||||
public string Label => Core.Localization.Loc.L("Shell.Nav." + Key);
|
||||
|
||||
/// <summary>Rail tooltip: what the section is for.</summary>
|
||||
public string ToolTip => Core.Localization.Loc.L("Tooltips.Nav." + Key);
|
||||
|
||||
/// <summary>Window title suffix ("Titano — Import").</summary>
|
||||
public virtual string Title => Label;
|
||||
|
||||
public bool IsSelected
|
||||
{
|
||||
get => _isSelected;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isSelected, value) && value) OnActivated();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Count of items needing attention, shown as a rail badge.</summary>
|
||||
public int Badge
|
||||
{
|
||||
get => _badge;
|
||||
protected set => Set(ref _badge, value);
|
||||
}
|
||||
|
||||
protected virtual void OnActivated()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Sections;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Shell;
|
||||
|
||||
/// <summary>State of the main window: rail, current section, job bar and status strip (BRIEF §12.1).</summary>
|
||||
public sealed class ShellViewModel : LocalizedViewModel
|
||||
{
|
||||
private readonly AppSettings _settings;
|
||||
private SectionViewModel _current;
|
||||
private bool _isRailCollapsed;
|
||||
private string? _jobText;
|
||||
private double _jobProgress;
|
||||
private bool _jobActive;
|
||||
private bool _jobIndeterminate;
|
||||
private long _sequenceCount;
|
||||
private long _photoCount;
|
||||
private long _totalBytes;
|
||||
private string? _serverName;
|
||||
private int _jobCount;
|
||||
|
||||
public ShellViewModel(AppSettings settings)
|
||||
{
|
||||
_settings = settings;
|
||||
_isRailCollapsed = settings.RailCollapsed;
|
||||
Library = new LibraryViewModel(this);
|
||||
Import = new ImportViewModel(this);
|
||||
Sequence = new SequenceViewModel(this);
|
||||
Archive = new ArchiveViewModel(this);
|
||||
Jobs = new JobsViewModel(this);
|
||||
Server = new ServerViewModel(this);
|
||||
Settings = new SettingsViewModel(this, settings);
|
||||
About = new AboutViewModel(this);
|
||||
TopSections = [Library, Import, Sequence, Archive, Jobs, Server];
|
||||
BottomSections = [Settings, About];
|
||||
_current = Library;
|
||||
Library.IsSelected = true;
|
||||
|
||||
NavigateCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is SectionViewModel s) Navigate(s.Key);
|
||||
else if (p is SectionKey k) Navigate(k);
|
||||
else if (p is string name && Enum.TryParse<SectionKey>(name, out var key)) Navigate(key);
|
||||
});
|
||||
ToggleRailCommand = new RelayCommand(() => IsRailCollapsed = !IsRailCollapsed);
|
||||
}
|
||||
|
||||
public LibraryViewModel Library { get; }
|
||||
public ImportViewModel Import { get; }
|
||||
public SequenceViewModel Sequence { get; }
|
||||
public ArchiveViewModel Archive { get; }
|
||||
public JobsViewModel Jobs { get; }
|
||||
public ServerViewModel Server { get; }
|
||||
public SettingsViewModel Settings { get; }
|
||||
public AboutViewModel About { get; }
|
||||
|
||||
public IReadOnlyList<SectionViewModel> TopSections { get; }
|
||||
public IReadOnlyList<SectionViewModel> BottomSections { get; }
|
||||
public IEnumerable<SectionViewModel> AllSections => TopSections.Concat(BottomSections);
|
||||
|
||||
public ICommand NavigateCommand { get; }
|
||||
public ICommand ToggleRailCommand { get; }
|
||||
|
||||
/// <summary>In-window notifications; the window binds its <see cref="ToastHost"/> here.</summary>
|
||||
public ObservableCollection<Toast> PendingToasts { get; } = [];
|
||||
|
||||
public SectionViewModel Current
|
||||
{
|
||||
get => _current;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _current, value)) OnPropertyChanged(nameof(WindowTitle));
|
||||
}
|
||||
}
|
||||
|
||||
public string WindowTitle => Current == Library ? "Titano" : "Titano — " + Current.Title;
|
||||
|
||||
public bool IsRailCollapsed
|
||||
{
|
||||
get => _isRailCollapsed;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _isRailCollapsed, value)) return;
|
||||
_settings.RailCollapsed = value;
|
||||
OnPropertyChanged(nameof(RailToggleToolTip));
|
||||
}
|
||||
}
|
||||
|
||||
public string RailToggleToolTip => Loc.L(IsRailCollapsed ? "Tooltips.Shell.ExpandRail" : "Tooltips.Shell.CollapseRail");
|
||||
|
||||
// ---- Job bar ----
|
||||
public string JobText => _jobActive && _jobText is not null ? _jobText : Loc.L("Shell.JobBar.Ready", _jobCount);
|
||||
public double JobProgress { get => _jobProgress; private set => Set(ref _jobProgress, value); }
|
||||
public bool IsJobActive { get => _jobActive; private set => Set(ref _jobActive, value); }
|
||||
public bool IsJobIndeterminate { get => _jobIndeterminate; private set => Set(ref _jobIndeterminate, value); }
|
||||
public ICommand? StopJobCommand { get; set; }
|
||||
|
||||
/// <summary>Updates the global job bar (and the taskbar progress through the window).</summary>
|
||||
public void SetJob(string? text, double progress, bool indeterminate = false)
|
||||
{
|
||||
_jobText = text;
|
||||
IsJobActive = text is not null;
|
||||
JobProgress = progress;
|
||||
IsJobIndeterminate = indeterminate;
|
||||
OnPropertyChanged(nameof(JobText));
|
||||
}
|
||||
|
||||
// ---- Status strip ----
|
||||
public string SequencesText => Loc.Plural("Shell.Status.Sequences", _sequenceCount);
|
||||
public string PhotosText => Loc.Plural("Shell.Status.Photos", _photoCount);
|
||||
public string StorageText => Formatting.Bytes(_totalBytes);
|
||||
public string ConnectionText => _serverName is null ? Loc.L("Shell.Status.NotConnected") : Loc.L("Shell.Status.Connected", _serverName);
|
||||
public bool IsConnected => _serverName is not null;
|
||||
public string JobsText => Loc.Plural("Shell.Status.Jobs", _jobCount);
|
||||
|
||||
public void SetLibraryTotals(long sequences, long photos, long bytes)
|
||||
{
|
||||
_sequenceCount = sequences;
|
||||
_photoCount = photos;
|
||||
_totalBytes = bytes;
|
||||
OnPropertyChanged(nameof(SequencesText));
|
||||
OnPropertyChanged(nameof(PhotosText));
|
||||
OnPropertyChanged(nameof(StorageText));
|
||||
}
|
||||
|
||||
public void SetConnection(string? serverName)
|
||||
{
|
||||
_serverName = serverName;
|
||||
OnPropertyChanged(nameof(ConnectionText));
|
||||
OnPropertyChanged(nameof(IsConnected));
|
||||
}
|
||||
|
||||
public void SetJobCount(int count)
|
||||
{
|
||||
_jobCount = count;
|
||||
OnPropertyChanged(nameof(JobsText));
|
||||
OnPropertyChanged(nameof(JobText));
|
||||
}
|
||||
|
||||
public void Navigate(SectionKey key)
|
||||
{
|
||||
var target = AllSections.First(s => s.Key == key);
|
||||
foreach (var s in AllSections) s.IsSelected = ReferenceEquals(s, target);
|
||||
Current = target;
|
||||
}
|
||||
|
||||
public void ShowToast(Toast toast) => PendingToasts.Add(toast);
|
||||
|
||||
/// <summary>Errors are one sentence saying what happened plus one action (BRIEF §0.2 rule 6).</summary>
|
||||
public void ReportError(Exception ex)
|
||||
{
|
||||
Log.Error("ui", "Operation failed", ex);
|
||||
ShowToast(new Toast
|
||||
{
|
||||
Title = Loc.L("Errors.Unexpected"),
|
||||
Message = ex.Message,
|
||||
ActionText = Loc.L("Common.OpenLogs"),
|
||||
ActionToolTip = Loc.L("Tooltips.Common.OpenLogs"),
|
||||
ActionCommand = new RelayCommand(() => ShellActions.OpenFolder(App.Current.Environment.LogDirectory)),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Titano.Protocol;
|
||||
|
||||
/// <summary>Error body of every failed API call: <c>{ code, message, details }</c> (BRIEF §14.3).</summary>
|
||||
public sealed record ApiError(string Code, string Message, string? Details = null);
|
||||
|
||||
/// <summary>Upload limits announced by the server.</summary>
|
||||
public sealed record ServerLimits(long MaxUploadBytes, int ChunkSizeBytes);
|
||||
|
||||
/// <summary><c>GET /api/v1/server/info</c>.</summary>
|
||||
public sealed record ServerInfo(
|
||||
string Name,
|
||||
string Version,
|
||||
int ApiVersion,
|
||||
IReadOnlyList<string> Capabilities,
|
||||
string? TlsFingerprint,
|
||||
IReadOnlyList<string> Formats,
|
||||
ServerLimits Limits);
|
||||
|
||||
/// <summary><c>GET /health</c>.</summary>
|
||||
public sealed record HealthStatus(string Status, string Version, IReadOnlyDictionary<string, string> Checks);
|
||||
|
||||
/// <summary>Source-generated JSON contracts shared by server and clients (camelCase, enums as strings).</summary>
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
UseStringEnumConverter = true)]
|
||||
[JsonSerializable(typeof(ApiError))]
|
||||
[JsonSerializable(typeof(ServerInfo))]
|
||||
[JsonSerializable(typeof(HealthStatus))]
|
||||
[JsonSerializable(typeof(Dictionary<string, string>))]
|
||||
public sealed partial class ProtocolJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,100 @@
|
||||
/* Titano Server admin — DESIGN.md light tokens (the web admin is light-only). */
|
||||
:root {
|
||||
--bg: #f3f3f3;
|
||||
--chrome: #ffffff;
|
||||
--surface: #ffffff;
|
||||
--card: #ffffff;
|
||||
--card-hover: #f5f5f5;
|
||||
--stroke: #e5e5e5;
|
||||
--stroke-strong: #d1d1d1;
|
||||
--text: #1a1a1a;
|
||||
--text-muted: #616161;
|
||||
--text-faint: #9e9e9e;
|
||||
--accent: #0067c0;
|
||||
--accent-hover: #1975c5;
|
||||
--on-accent: #ffffff;
|
||||
--accent-selected: #e8f1fa;
|
||||
--sun: #e08a1e;
|
||||
--success: #0f7b4f;
|
||||
--warning: #9a6700;
|
||||
--error: #c42b1c;
|
||||
--radius: 6px;
|
||||
--radius-card: 8px;
|
||||
--font: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Noto Sans", sans-serif;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body { height: 100%; }
|
||||
body { margin: 0; font: 13px/1.45 var(--font); color: var(--text); background: var(--bg); }
|
||||
button, input, select { font: inherit; color: inherit; }
|
||||
a { color: var(--accent); }
|
||||
.num { font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* Shell */
|
||||
.shell { display: grid; grid-template-columns: 220px 1fr; min-height: 100vh; }
|
||||
.sidebar { background: var(--chrome); border-right: 1px solid var(--stroke); display: flex; flex-direction: column; padding: 16px 12px; }
|
||||
.brand { display: flex; align-items: center; gap: 10px; padding: 4px 8px 20px; }
|
||||
.brand img { width: 28px; height: 28px; }
|
||||
.brand strong { display: block; font-size: 14px; }
|
||||
.brand span { display: block; font-size: 11px; color: var(--text-muted); }
|
||||
.nav a { display: flex; align-items: center; gap: 12px; height: 36px; padding: 0 12px; border-radius: var(--radius); color: var(--text); text-decoration: none; margin-bottom: 2px; }
|
||||
.nav a:hover { background: var(--card-hover); }
|
||||
.nav a[aria-current="page"] { background: var(--accent-selected); color: var(--accent); font-weight: 600; }
|
||||
.nav svg { width: 16px; height: 16px; flex: none; }
|
||||
.nav .badge { margin-left: auto; min-width: 18px; height: 16px; padding: 0 5px; border-radius: 8px; background: var(--accent); color: var(--on-accent); font-size: 10px; font-weight: 600; display: inline-flex; align-items: center; justify-content: center; }
|
||||
.sidebar .user { margin-top: auto; border-top: 1px solid var(--stroke); padding: 12px 8px 0; display: flex; align-items: center; gap: 10px; }
|
||||
.avatar { width: 28px; height: 28px; border-radius: 50%; background: var(--accent-selected); color: var(--accent); display: grid; place-items: center; font-weight: 600; }
|
||||
.user .who { flex: 1; min-width: 0; }
|
||||
.user .who strong { display: block; }
|
||||
.user .who span { color: var(--text-muted); font-size: 11px; }
|
||||
|
||||
.main { display: flex; flex-direction: column; min-width: 0; }
|
||||
.header { height: 60px; display: flex; align-items: center; gap: 12px; padding: 0 24px; border-bottom: 1px solid var(--stroke); background: var(--chrome); }
|
||||
.header h1 { font-size: 18px; font-weight: 600; margin: 0; }
|
||||
.header .meta { color: var(--text-muted); }
|
||||
.header .spacer { flex: 1; }
|
||||
.content { padding: 24px; display: grid; gap: 20px; }
|
||||
|
||||
/* Controls */
|
||||
.btn { height: 32px; min-width: 44px; padding: 0 12px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
|
||||
.btn:hover { background: var(--card-hover); border-color: var(--stroke-strong); }
|
||||
.btn:focus-visible, .input:focus-visible, select:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); font-weight: 600; }
|
||||
.btn.primary:hover { background: var(--accent-hover); }
|
||||
.btn.subtle { border-color: transparent; background: transparent; }
|
||||
.btn.icon { width: 32px; padding: 0; }
|
||||
.btn:disabled { opacity: .4; cursor: default; }
|
||||
.input { height: 32px; width: 100%; padding: 0 10px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); }
|
||||
.input:hover { border-color: var(--stroke-strong); }
|
||||
.input:focus { border-color: var(--accent); outline: none; }
|
||||
.input[aria-invalid="true"] { border-color: var(--error); }
|
||||
select.input { padding-right: 24px; }
|
||||
|
||||
.panel { background: var(--surface); border: 1px solid var(--stroke); border-radius: var(--radius-card); padding: 18px 20px; }
|
||||
.panel h2 { font-size: 14px; font-weight: 600; margin: 0 0 12px; }
|
||||
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; }
|
||||
.tile .label { color: var(--text-muted); }
|
||||
.tile .value { font-size: 28px; font-weight: 600; margin-top: 4px; }
|
||||
.tile .value small { font-size: 13px; font-weight: 400; color: var(--text-muted); margin-left: 6px; }
|
||||
.tile .sub { color: var(--text-muted); margin-top: 6px; }
|
||||
.progress { height: 6px; border-radius: 3px; background: var(--stroke); overflow: hidden; margin-top: 10px; }
|
||||
.progress > div { height: 6px; background: var(--accent); }
|
||||
|
||||
.status-ok { color: var(--success); }
|
||||
.status-warn { color: var(--warning); }
|
||||
.status-err { color: var(--error); }
|
||||
|
||||
/* Login */
|
||||
.login { min-height: 100vh; display: grid; place-items: center; padding: 16px; }
|
||||
.login form { width: 360px; max-width: 100%; display: grid; gap: 14px; }
|
||||
.login .brand { padding: 0 0 8px; }
|
||||
.login label { display: grid; gap: 6px; color: var(--text-muted); }
|
||||
.login .error { color: var(--error); min-height: 18px; }
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.shell { grid-template-columns: 1fr; }
|
||||
.sidebar { flex-direction: row; overflow-x: auto; padding: 8px; }
|
||||
.sidebar .brand, .sidebar .user { display: none; }
|
||||
.nav { display: flex; gap: 4px; }
|
||||
.nav a span { display: none; }
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Same API as the desktop clients: cookie session + double-submit CSRF token for the web admin (BRIEF §14.2).
|
||||
export class ApiFailure extends Error {
|
||||
constructor(status, code, message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
const SESSION_KEY = "titano.admin.user";
|
||||
|
||||
function csrfToken() {
|
||||
const m = document.cookie.match(/(?:^|; )titano_csrf=([^;]+)/);
|
||||
return m ? decodeURIComponent(m[1]) : "";
|
||||
}
|
||||
|
||||
async function request(method, url, body) {
|
||||
const headers = { Accept: "application/json" };
|
||||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||||
if (method !== "GET") headers["X-CSRF-Token"] = csrfToken();
|
||||
const res = await fetch(url, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
if (res.status === 401 && url !== "/api/v1/auth/login") sessionStorage.removeItem(SESSION_KEY);
|
||||
if (!res.ok) {
|
||||
let err = { code: "http_" + res.status, message: res.statusText };
|
||||
try { err = await res.json(); } catch { /* non-JSON error */ }
|
||||
throw new ApiFailure(res.status, err.code, err.message);
|
||||
}
|
||||
return res.status === 204 ? null : res.json();
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: (url) => request("GET", url),
|
||||
post: (url, body) => request("POST", url, body ?? {}),
|
||||
patch: (url, body) => request("PATCH", url, body),
|
||||
del: (url) => request("DELETE", url),
|
||||
isSignedIn: () => sessionStorage.getItem(SESSION_KEY) !== null,
|
||||
user: () => JSON.parse(sessionStorage.getItem(SESSION_KEY) ?? "null"),
|
||||
async signIn(username, password) {
|
||||
const r = await request("POST", "/api/v1/auth/login", { username, password, clientName: "admin-web", cookie: true });
|
||||
sessionStorage.setItem(SESSION_KEY, JSON.stringify(r.user));
|
||||
return r;
|
||||
},
|
||||
async signOut() {
|
||||
try { await request("POST", "/api/v1/auth/logout", {}); } catch { /* already gone */ }
|
||||
sessionStorage.removeItem(SESSION_KEY);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
// Titano Server admin panel — vanilla ES modules, no build step (BRIEF §14.8).
|
||||
import { api, ApiFailure } from "./api.js";
|
||||
import { t, loadStrings, applyStrings } from "./i18n.js";
|
||||
import { icons } from "./icons.js";
|
||||
|
||||
const app = document.getElementById("app");
|
||||
const pages = ["dashboard", "users", "archive", "jobs", "settings", "logs", "about"];
|
||||
const pageIcon = { dashboard: "dashboard", users: "users", archive: "archive", jobs: "jobs", settings: "settings", logs: "logs", about: "about" };
|
||||
|
||||
let info = null;
|
||||
|
||||
async function start() {
|
||||
await loadStrings(navigator.language);
|
||||
info = await api.get("/api/v1/server/info").catch(() => null);
|
||||
window.addEventListener("hashchange", render);
|
||||
render();
|
||||
}
|
||||
|
||||
function currentPage() {
|
||||
const p = location.hash.replace(/^#\/?/, "");
|
||||
return pages.includes(p) ? p : "dashboard";
|
||||
}
|
||||
|
||||
function render() {
|
||||
if (!api.isSignedIn()) {
|
||||
renderLogin();
|
||||
return;
|
||||
}
|
||||
renderShell(currentPage());
|
||||
}
|
||||
|
||||
function renderLogin() {
|
||||
app.innerHTML = `
|
||||
<main class="login">
|
||||
<form novalidate>
|
||||
<div class="brand"><img src="favicon.svg" alt=""><div><strong>Titano Server</strong><span class="num">${escapeHtml(info?.name ?? "")} · v${escapeHtml(info?.version ?? "")}</span></div></div>
|
||||
<label><span data-i18n="Admin.Login.User"></span><input class="input" name="username" autocomplete="username" required></label>
|
||||
<label><span data-i18n="Admin.Login.Password"></span><input class="input" name="password" type="password" autocomplete="current-password" required></label>
|
||||
<div class="error" role="alert"></div>
|
||||
<button class="btn primary" type="submit" data-i18n="Admin.Login.SignIn" data-i18n-title="Admin.Login.SignIn.Tip"></button>
|
||||
</form>
|
||||
</main>`;
|
||||
applyStrings(app);
|
||||
const form = app.querySelector("form");
|
||||
const error = form.querySelector(".error");
|
||||
form.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
error.textContent = "";
|
||||
const data = new FormData(form);
|
||||
try {
|
||||
await api.signIn(String(data.get("username")), String(data.get("password")));
|
||||
render();
|
||||
} catch (err) {
|
||||
error.textContent = err instanceof ApiFailure && err.status === 401 ? t("Admin.Login.Failed") : t("Admin.Error.Unreachable");
|
||||
}
|
||||
});
|
||||
form.querySelector("input").focus();
|
||||
}
|
||||
|
||||
function renderShell(page) {
|
||||
const nav = pages.map((p) => `
|
||||
<a href="#/${p}" ${p === page ? 'aria-current="page"' : ""} data-i18n-title="Admin.Nav.${cap(p)}.Tip">${icons[pageIcon[p]]}<span data-i18n="Admin.Nav.${cap(p)}"></span></a>`).join("");
|
||||
const user = api.user();
|
||||
app.innerHTML = `
|
||||
<div class="shell">
|
||||
<aside class="sidebar">
|
||||
<div class="brand"><img src="favicon.svg" alt=""><div><strong>Titano Server</strong><span class="num">${escapeHtml(info?.name ?? "")} · v${escapeHtml(info?.version ?? "")}</span></div></div>
|
||||
<nav class="nav">${nav}</nav>
|
||||
<div class="user">
|
||||
<div class="avatar">${escapeHtml((user?.username ?? "?").slice(0, 1).toUpperCase())}</div>
|
||||
<div class="who"><strong>${escapeHtml(user?.username ?? "")}</strong><span data-i18n="Admin.Role.${cap(user?.role ?? "viewer")}"></span></div>
|
||||
<button class="btn icon subtle" id="signout" data-i18n-title="Admin.SignOut.Tip" aria-label="${escapeHtml(t("Admin.SignOut.Tip"))}">${icons.power}</button>
|
||||
</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<header class="header"><h1 data-i18n="Admin.Nav.${cap(page)}"></h1><span class="meta" id="meta"></span><span class="spacer"></span></header>
|
||||
<section class="content" id="content"></section>
|
||||
</div>
|
||||
</div>`;
|
||||
applyStrings(app);
|
||||
app.querySelector("#signout").addEventListener("click", async () => {
|
||||
await api.signOut();
|
||||
render();
|
||||
});
|
||||
const content = app.querySelector("#content");
|
||||
import(`./pages/${page}.js`)
|
||||
.then((m) => m.render(content, { api, t, info, meta: app.querySelector("#meta") }))
|
||||
.catch(() => {
|
||||
content.innerHTML = `<div class="panel"><span data-i18n="Admin.Error.Unreachable"></span></div>`;
|
||||
applyStrings(content);
|
||||
});
|
||||
}
|
||||
|
||||
export function escapeHtml(s) {
|
||||
return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
||||
}
|
||||
|
||||
function cap(s) {
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
|
||||
<rect x="0" y="0" width="256" height="256" rx="56" fill="#1a1a1e"/>
|
||||
<path d="M142.4 37.1 A92 92 0 0 1 161.0 42.1" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.14"/>
|
||||
<path d="M185.9 56.5 A92 92 0 0 1 199.5 70.1" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.22"/>
|
||||
<path d="M213.9 95.0 A92 92 0 0 1 218.9 113.6" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.3"/>
|
||||
<path d="M218.9 142.4 A92 92 0 0 1 213.9 161.0" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.37"/>
|
||||
<path d="M199.5 185.9 A92 92 0 0 1 185.9 199.5" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.45"/>
|
||||
<path d="M161.0 213.9 A92 92 0 0 1 142.4 218.9" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.53"/>
|
||||
<path d="M113.6 218.9 A92 92 0 0 1 95.0 213.9" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.61"/>
|
||||
<path d="M70.1 199.5 A92 92 0 0 1 56.5 185.9" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.69"/>
|
||||
<path d="M42.1 161.0 A92 92 0 0 1 37.1 142.4" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.77"/>
|
||||
<path d="M37.1 113.6 A92 92 0 0 1 42.1 95.0" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.84"/>
|
||||
<path d="M56.5 70.1 A92 92 0 0 1 70.1 56.5" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.92"/>
|
||||
<path d="M95.0 42.1 A92 92 0 0 1 113.6 37.1" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="1.0"/>
|
||||
<circle cx="152" cy="104" r="30" fill="#f5a524"/>
|
||||
<circle cx="204" cy="204" r="40" fill="#1a1a1e" stroke="#4cc2ff" stroke-width="6"/><rect x="185" y="188" width="38" height="12" rx="4" fill="#4cc2ff"/><rect x="185" y="208" width="38" height="12" rx="4" fill="#4cc2ff"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
@@ -0,0 +1,27 @@
|
||||
// Strings come from /api/v1/i18n/{culture}, generated from the same .resx catalog as the desktop apps.
|
||||
let strings = {};
|
||||
|
||||
export async function loadStrings(culture) {
|
||||
try {
|
||||
const res = await fetch(`/api/v1/i18n/${encodeURIComponent(culture || "en")}`);
|
||||
strings = await res.json();
|
||||
} catch {
|
||||
strings = {};
|
||||
}
|
||||
document.documentElement.lang = strings.$culture || "en";
|
||||
document.documentElement.dir = strings.$rtl === "true" ? "rtl" : "ltr";
|
||||
}
|
||||
|
||||
/** Localized string for key with {0}, {1}… placeholders filled from args. */
|
||||
export function t(key, ...args) {
|
||||
const s = strings[key];
|
||||
if (s === undefined) return `⟦${key}⟧`;
|
||||
return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => (args[Number(i)] ?? ""));
|
||||
}
|
||||
|
||||
/** Fills data-i18n (text), data-i18n-title (tooltip) and data-i18n-placeholder attributes. */
|
||||
export function applyStrings(root) {
|
||||
root.querySelectorAll("[data-i18n]").forEach((el) => { el.textContent = t(el.dataset.i18n); });
|
||||
root.querySelectorAll("[data-i18n-title]").forEach((el) => { el.title = t(el.dataset.i18nTitle); });
|
||||
root.querySelectorAll("[data-i18n-placeholder]").forEach((el) => { el.placeholder = t(el.dataset.i18nPlaceholder); });
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Generated from branding/ui-icons/icons.py (same 16-px set as the desktop apps).
|
||||
export const icons = {
|
||||
dashboard: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
users: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5 5 A3 3 0 1 0 11 5 A3 3 0 1 0 5 5 Z M2.5 14 A5.5 5.5 0 0 1 13.5 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
archive: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2 4.5 H14 V13.5 H2 Z M2 2 H14 V4.5 H2 Z M6 8 H10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
jobs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 8 H13 M3 4 H13 M3 12 H9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
settings: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5.8 8 A2.2 2.2 0 1 0 10.2 8 A2.2 2.2 0 1 0 5.8 8 Z M8 1.5 V3.5 M8 12.5 V14.5 M1.5 8 H3.5 M12.5 8 H14.5 M3.4 3.4 L4.8 4.8 M11.2 11.2 L12.6 12.6 M3.4 12.6 L4.8 11.2 M11.2 4.8 L12.6 3.4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
logs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
about: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M8 7 V11 M8 4.8 V5.2" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
power: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 V7.5 M11.54 4.59 A5.5 5.5 0 1 1 4.46 4.59" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
moon: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.5 1.8 A6.5 6.5 0 1 0 14.2 11.2 A5.5 5.5 0 0 1 9.5 1.8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
refresh: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M10.75 3.24 A5.5 5.5 0 1 1 4.46 3.79 M13.2 2.6 L13.2 5.3 L10.5 5.3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
close: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M4 4 L12 12 M12 4 L4 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
plus: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 3 V13 M3 8 H13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
search: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 7 A4.5 4.5 0 1 0 11.5 7 A4.5 4.5 0 1 0 2.5 7 Z M10.4 10.4 L14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
};
|
||||
@@ -1 +1,15 @@
|
||||
<!doctype html><title>Titano</title>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light">
|
||||
<title>Titano Server</title>
|
||||
<link rel="icon" href="favicon.svg" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="admin.css">
|
||||
<script type="module" src="app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" aria-live="polite"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { applyStrings } from "../i18n.js";
|
||||
import { escapeHtml } from "../app.js";
|
||||
|
||||
export async function render(root, { info }) {
|
||||
root.innerHTML = `
|
||||
<div class="panel">
|
||||
<h2 data-i18n="Admin.About.Title"></h2>
|
||||
<p class="num">Titano Server ${escapeHtml(info?.version ?? "")} · API ${escapeHtml(String(info?.apiVersion ?? ""))}</p>
|
||||
<p class="num"><span data-i18n="Admin.About.Fingerprint"></span> ${escapeHtml(info?.tlsFingerprint ?? "–")}</p>
|
||||
</div>`;
|
||||
applyStrings(root);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Dashboard: storage, archive, jobs, render nodes (BRIEF §14.8). Data from the public API only.
|
||||
import { applyStrings } from "../i18n.js";
|
||||
|
||||
export async function render(root, { api, t, info, meta }) {
|
||||
const health = await api.get("/health").catch(() => null);
|
||||
meta.textContent = info ? `v${info.version} · TLS ${info.tlsFingerprint ? "auto" : "proxy"}` : "";
|
||||
root.innerHTML = `
|
||||
<div class="tiles">
|
||||
<div class="panel tile"><div class="label" data-i18n="Admin.Dashboard.Server"></div>
|
||||
<div class="value">${health?.status === "ok" ? `<span class="status-ok">●</span>` : `<span class="status-err">✕</span>`}<small>${health?.status ?? ""}</small></div>
|
||||
<div class="sub num">${info?.name ?? ""}</div></div>
|
||||
<div class="panel tile"><div class="label" data-i18n="Admin.Dashboard.Archive"></div>
|
||||
<div class="value">${health?.checks?.archive === "ok" ? `<span class="status-ok">●</span>` : `<span class="status-warn">▲</span>`}<small>${health?.checks?.archive ?? ""}</small></div></div>
|
||||
<div class="panel tile"><div class="label" data-i18n="Admin.Dashboard.Api"></div>
|
||||
<div class="value num">${info?.apiVersion ?? "–"}</div><div class="sub">${(info?.capabilities ?? []).join(" · ")}</div></div>
|
||||
</div>`;
|
||||
applyStrings(root);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary><c>/health</c>, <c>/api/v1/server/info</c> and <c>/api/v1/i18n/{culture}</c>.</summary>
|
||||
public static class SystemEndpoints
|
||||
{
|
||||
private static readonly string[] AdminAreas = ["Common", "Admin"];
|
||||
|
||||
public static string Version { get; } =
|
||||
typeof(SystemEndpoints).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
|
||||
|
||||
public static void Map(WebApplication app, ServerOptions options, ServerState state)
|
||||
{
|
||||
app.MapGet("/health", () =>
|
||||
{
|
||||
var checks = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["archive"] = Directory.Exists(options.ArchivePath) ? "ok" : "missing",
|
||||
["data"] = Directory.Exists(options.DataPath) ? "ok" : "missing",
|
||||
};
|
||||
return Results.Json(new HealthStatus("ok", Version, checks), ProtocolJson.Default.HealthStatus);
|
||||
});
|
||||
|
||||
var api = app.MapGroup("/api/v1");
|
||||
api.MapGet("/server/info", () => Results.Json(new ServerInfo(
|
||||
options.ServerName,
|
||||
Version,
|
||||
ApiVersion.Current,
|
||||
state.Capabilities,
|
||||
state.TlsFingerprint,
|
||||
["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"],
|
||||
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes)), ProtocolJson.Default.ServerInfo));
|
||||
|
||||
api.MapGet("/i18n/{culture}", (string culture) =>
|
||||
{
|
||||
CultureInfo ci;
|
||||
try
|
||||
{
|
||||
ci = Languages.BestMatch(CultureInfo.GetCultureInfo(culture));
|
||||
}
|
||||
catch (CultureNotFoundException)
|
||||
{
|
||||
ci = CultureInfo.GetCultureInfo("en");
|
||||
}
|
||||
var strings = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var area in AdminAreas)
|
||||
foreach (var (k, v) in Loc.GetArea(area, ci)) strings[k] = v;
|
||||
strings["$culture"] = ci.Name;
|
||||
strings["$rtl"] = ci.TextInfo.IsRightToLeft ? "true" : "false";
|
||||
return Results.Json(strings, ProtocolJson.Default.DictionaryStringString);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Process-wide facts computed at startup.</summary>
|
||||
public sealed class ServerState
|
||||
{
|
||||
public string? TlsFingerprint { get; set; }
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events"];
|
||||
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Titano.Server.Configuration;
|
||||
|
||||
public enum TlsMode
|
||||
{
|
||||
/// <summary>Self-signed certificate generated at first start (stored under /data/tls).</summary>
|
||||
Auto,
|
||||
|
||||
/// <summary>Certificate and key from PEM files.</summary>
|
||||
Pem,
|
||||
|
||||
/// <summary>Plain HTTP behind a TLS-terminating reverse proxy.</summary>
|
||||
Proxy,
|
||||
}
|
||||
|
||||
public enum DatabaseKind
|
||||
{
|
||||
Postgres,
|
||||
Sqlite,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Server configuration (BRIEF §14.9): environment variables override <c>/data/server.json</c>, which overrides defaults.
|
||||
/// </summary>
|
||||
public sealed class ServerOptions
|
||||
{
|
||||
public string ServerName { get; set; } = "Titano Server";
|
||||
public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\TitanoArchive" : "/archive";
|
||||
public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Titano Server") : "/data";
|
||||
public string? AdminUser { get; set; }
|
||||
public string? AdminPassword { get; set; }
|
||||
public DatabaseKind Database { get; set; } = OperatingSystem.IsWindows() ? DatabaseKind.Sqlite : DatabaseKind.Postgres;
|
||||
public string DbHost { get; set; } = "postgres";
|
||||
public int DbPort { get; set; } = 5432;
|
||||
public string DbName { get; set; } = "titano";
|
||||
public string DbUser { get; set; } = "titano";
|
||||
public string? DbPassword { get; set; }
|
||||
public string DbSslMode { get; set; } = "prefer";
|
||||
public int HttpPort { get; set; } = 8080;
|
||||
public int HttpsPort { get; set; } = 8443;
|
||||
public TlsMode TlsMode { get; set; } = TlsMode.Auto;
|
||||
public string? TlsCert { get; set; }
|
||||
public string? TlsKey { get; set; }
|
||||
public string Language { get; set; } = "en";
|
||||
public int Workers { get; set; } = Math.Max(1, Environment.ProcessorCount / 2);
|
||||
public bool Discovery { get; set; } = true;
|
||||
public long MaxUploadBytes { get; set; } = 2L * 1024 * 1024 * 1024;
|
||||
public int ChunkSizeBytes { get; set; } = 8 * 1024 * 1024;
|
||||
public int JobHistoryDays { get; set; } = 90;
|
||||
public int TokenLifetimeDays { get; set; } = 30;
|
||||
|
||||
[JsonIgnore]
|
||||
public string LogPath => Path.Combine(DataPath, "logs");
|
||||
|
||||
[JsonIgnore]
|
||||
public string TlsPath => Path.Combine(DataPath, "tls");
|
||||
|
||||
[JsonIgnore]
|
||||
public string UploadsPath => Path.Combine(DataPath, "uploads");
|
||||
|
||||
/// <summary>Loads <c>{DataPath}/server.json</c> (if present) then applies <c>TITANO_*</c> environment variables.</summary>
|
||||
public static ServerOptions Load(IReadOnlyDictionary<string, string?>? environment = null)
|
||||
{
|
||||
var env = environment ?? ReadEnvironment();
|
||||
string? Env(string name) => env.TryGetValue(name, out var v) && !string.IsNullOrWhiteSpace(v) ? v : null;
|
||||
|
||||
var dataPath = Env("TITANO_DATA_PATH") ?? new ServerOptions().DataPath;
|
||||
var options = new ServerOptions();
|
||||
var file = Path.Combine(dataPath, "server.json");
|
||||
if (File.Exists(file))
|
||||
{
|
||||
try
|
||||
{
|
||||
options = JsonSerializer.Deserialize(File.ReadAllText(file), ServerOptionsJson.Default.ServerOptions) ?? options;
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidOperationException($"{file} is not valid JSON: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
options.DataPath = dataPath;
|
||||
|
||||
options.ServerName = Env("TITANO_SERVER_NAME") ?? options.ServerName;
|
||||
options.ArchivePath = Env("TITANO_ARCHIVE_PATH") ?? options.ArchivePath;
|
||||
options.AdminUser = Env("TITANO_ADMIN_USER") ?? options.AdminUser;
|
||||
options.AdminPassword = Env("TITANO_ADMIN_PASSWORD") ?? options.AdminPassword;
|
||||
if (Env("TITANO_DB") is { } db) options.Database = Enum.Parse<DatabaseKind>(db, ignoreCase: true);
|
||||
options.DbHost = Env("TITANO_DB_HOST") ?? options.DbHost;
|
||||
if (Env("TITANO_DB_PORT") is { } port) options.DbPort = int.Parse(port, System.Globalization.CultureInfo.InvariantCulture);
|
||||
options.DbName = Env("TITANO_DB_NAME") ?? options.DbName;
|
||||
options.DbUser = Env("TITANO_DB_USER") ?? options.DbUser;
|
||||
options.DbPassword = Env("TITANO_DB_PASSWORD") ?? options.DbPassword;
|
||||
options.DbSslMode = Env("TITANO_DB_SSLMODE") ?? options.DbSslMode;
|
||||
if (Env("TITANO_HTTP_PORT") is { } http) options.HttpPort = int.Parse(http, System.Globalization.CultureInfo.InvariantCulture);
|
||||
if (Env("TITANO_HTTPS_PORT") is { } https) options.HttpsPort = int.Parse(https, System.Globalization.CultureInfo.InvariantCulture);
|
||||
if (Env("TITANO_TLS_MODE") is { } tls) options.TlsMode = Enum.Parse<TlsMode>(tls, ignoreCase: true);
|
||||
options.TlsCert = Env("TITANO_TLS_CERT") ?? options.TlsCert;
|
||||
options.TlsKey = Env("TITANO_TLS_KEY") ?? options.TlsKey;
|
||||
options.Language = Env("TITANO_LANG") ?? options.Language;
|
||||
if (Env("TITANO_WORKERS") is { } workers) options.Workers = Math.Max(1, int.Parse(workers, System.Globalization.CultureInfo.InvariantCulture));
|
||||
if (Env("TITANO_DISCOVERY") is { } discovery) options.Discovery = bool.Parse(discovery);
|
||||
options.Validate();
|
||||
return options;
|
||||
}
|
||||
|
||||
private static Dictionary<string, string?> ReadEnvironment()
|
||||
{
|
||||
// Variables may differ only by case on Linux (no_proxy/NO_PROXY); the last one wins.
|
||||
var result = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (System.Collections.DictionaryEntry e in Environment.GetEnvironmentVariables()) result[(string)e.Key] = (string?)e.Value;
|
||||
return result;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows() && Database == DatabaseKind.Sqlite)
|
||||
throw new InvalidOperationException("TITANO_DB=sqlite is supported on Windows only; use postgres (BRIEF §14.9).");
|
||||
if (TlsMode == TlsMode.Pem && (string.IsNullOrEmpty(TlsCert) || string.IsNullOrEmpty(TlsKey)))
|
||||
throw new InvalidOperationException("TITANO_TLS_MODE=pem requires TITANO_TLS_CERT and TITANO_TLS_KEY.");
|
||||
// Port 0 asks the OS for a free port (used by the in-process test host).
|
||||
if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535)
|
||||
throw new InvalidOperationException("Ports must be between 0 and 65535.");
|
||||
}
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true, PropertyNameCaseInsensitive = true)]
|
||||
[JsonSerializable(typeof(ServerOptions))]
|
||||
internal sealed partial class ServerOptionsJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// TLS certificate for Kestrel (BRIEF §14.2): self-signed ECDSA P-256 generated once and kept in /data/tls
|
||||
/// (mode auto), loaded from PEM files (mode pem), or none (mode proxy).
|
||||
/// </summary>
|
||||
public static class CertificateStore
|
||||
{
|
||||
public static X509Certificate2? Load(ServerOptions options, ILogger logger)
|
||||
{
|
||||
switch (options.TlsMode)
|
||||
{
|
||||
case TlsMode.Proxy:
|
||||
return null;
|
||||
case TlsMode.Pem:
|
||||
{
|
||||
var pem = X509Certificate2.CreateFromPemFile(options.TlsCert!, options.TlsKey);
|
||||
return Exportable(pem);
|
||||
}
|
||||
default:
|
||||
{
|
||||
Directory.CreateDirectory(options.TlsPath);
|
||||
var path = Path.Combine(options.TlsPath, "server.pfx");
|
||||
if (File.Exists(path))
|
||||
{
|
||||
var existing = X509CertificateLoader.LoadPkcs12FromFile(path, password: null, X509KeyStorageFlags.Exportable);
|
||||
if (existing.NotAfter > DateTime.UtcNow.AddDays(30)) return existing;
|
||||
logger.LogWarning("Self-signed certificate expires {NotAfter:u}; generating a new one (clients will see a new fingerprint).", existing.NotAfter);
|
||||
}
|
||||
var created = CreateSelfSigned(options.ServerName);
|
||||
File.WriteAllBytes(path, created.Export(X509ContentType.Pkcs12));
|
||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
logger.LogInformation("Generated self-signed TLS certificate, SHA-256 fingerprint {Fingerprint}", Fingerprint(created));
|
||||
return created;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>SHA-256 fingerprint as colon-separated upper-case hex, as shown to users for trust-on-first-use.</summary>
|
||||
public static string Fingerprint(X509Certificate2 certificate) =>
|
||||
string.Join(':', certificate.GetCertHash(HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)));
|
||||
|
||||
public static X509Certificate2 CreateSelfSigned(string serverName)
|
||||
{
|
||||
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
var request = new CertificateRequest(new X500DistinguishedName($"CN={Sanitize(serverName)}, O=Titano"), key, HashAlgorithmName.SHA256);
|
||||
var san = new SubjectAlternativeNameBuilder();
|
||||
san.AddDnsName("localhost");
|
||||
try
|
||||
{
|
||||
var host = Dns.GetHostName();
|
||||
san.AddDnsName(host);
|
||||
foreach (var address in Dns.GetHostAddresses(host).Where(a => a.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6))
|
||||
san.AddIpAddress(address);
|
||||
}
|
||||
catch (SocketException)
|
||||
{
|
||||
// Without name resolution the certificate still covers localhost.
|
||||
}
|
||||
san.AddIpAddress(IPAddress.Loopback);
|
||||
request.CertificateExtensions.Add(san.Build());
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
|
||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
|
||||
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new Oid("1.3.6.1.5.5.7.3.1")], false));
|
||||
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(5));
|
||||
return Exportable(certificate);
|
||||
}
|
||||
|
||||
private static X509Certificate2 Exportable(X509Certificate2 certificate) =>
|
||||
X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12), password: null, X509KeyStorageFlags.Exportable);
|
||||
|
||||
private static string Sanitize(string name) => new(name.Where(c => char.IsLetterOrDigit(c) || c is ' ' or '-' or '.').Take(60).ToArray());
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Serves the admin panel from embedded resources named <c>admin/…</c> (no build step, single-file friendly),
|
||||
/// with strong ETags, conditional GET and SPA fallback to <c>index.html</c>.
|
||||
/// </summary>
|
||||
public sealed class EmbeddedStaticFiles
|
||||
{
|
||||
private static readonly FrozenDictionary<string, string> ContentTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[".html"] = "text/html; charset=utf-8",
|
||||
[".js"] = "text/javascript; charset=utf-8",
|
||||
[".mjs"] = "text/javascript; charset=utf-8",
|
||||
[".css"] = "text/css; charset=utf-8",
|
||||
[".svg"] = "image/svg+xml",
|
||||
[".png"] = "image/png",
|
||||
[".json"] = "application/json; charset=utf-8",
|
||||
[".ico"] = "image/x-icon",
|
||||
[".woff2"] = "font/woff2",
|
||||
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private readonly FrozenDictionary<string, (byte[] Content, string ETag, string ContentType)> _files;
|
||||
|
||||
public EmbeddedStaticFiles(Assembly assembly, string prefix)
|
||||
{
|
||||
var files = new Dictionary<string, (byte[], string, string)>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var name in assembly.GetManifestResourceNames().Where(n => n.StartsWith(prefix, StringComparison.Ordinal)))
|
||||
{
|
||||
using var stream = assembly.GetManifestResourceStream(name)!;
|
||||
using var ms = new MemoryStream();
|
||||
stream.CopyTo(ms);
|
||||
var bytes = ms.ToArray();
|
||||
var path = name[prefix.Length..].Replace('\\', '/');
|
||||
var etag = "\"" + Convert.ToHexString(SHA256.HashData(bytes).AsSpan(0, 12)) + "\"";
|
||||
var type = ContentTypes.TryGetValue(Path.GetExtension(path), out var t) ? t : "application/octet-stream";
|
||||
files[path] = (bytes, etag, type);
|
||||
}
|
||||
_files = files.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public int Count => _files.Count;
|
||||
|
||||
public async Task<bool> TryServeAsync(HttpContext context, string relativePath)
|
||||
{
|
||||
var path = relativePath.TrimStart('/');
|
||||
if (path.Length == 0) path = "index.html";
|
||||
if (!_files.TryGetValue(path, out var file))
|
||||
{
|
||||
// Client-side routes (no extension) fall back to the shell.
|
||||
if (Path.HasExtension(path) || !_files.TryGetValue("index.html", out file)) return false;
|
||||
}
|
||||
var response = context.Response;
|
||||
response.Headers.ETag = file.ETag;
|
||||
response.Headers.CacheControl = path.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ? "no-cache" : "public, max-age=3600";
|
||||
response.Headers.XContentTypeOptions = "nosniff";
|
||||
if (context.Request.Headers.IfNoneMatch == file.ETag)
|
||||
{
|
||||
response.StatusCode = StatusCodes.Status304NotModified;
|
||||
return true;
|
||||
}
|
||||
response.ContentType = file.ContentType;
|
||||
response.ContentLength = file.Content.Length;
|
||||
if (!HttpMethods.IsHead(context.Request.Method)) await response.Body.WriteAsync(file.Content, context.RequestAborted);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Titano.Core.Diagnostics;
|
||||
using CoreLogLevel = Titano.Core.Diagnostics.LogLevel;
|
||||
using MsLogLevel = Microsoft.Extensions.Logging.LogLevel;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>In-house structured file logging for ASP.NET Core (rotating daily files under /data/logs).</summary>
|
||||
public sealed class FileLoggerProvider(FileLogSink sink) : ILoggerProvider
|
||||
{
|
||||
public ILogger CreateLogger(string categoryName) => new FileLogger(sink, categoryName);
|
||||
|
||||
public void Dispose() => sink.Dispose();
|
||||
|
||||
private sealed class FileLogger(FileLogSink sink, string category) : ILogger
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(MsLogLevel logLevel) => logLevel >= MsLogLevel.Information;
|
||||
|
||||
public void Log<TState>(MsLogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(logLevel)) return;
|
||||
var level = logLevel switch
|
||||
{
|
||||
MsLogLevel.Trace => CoreLogLevel.Trace,
|
||||
MsLogLevel.Debug => CoreLogLevel.Debug,
|
||||
MsLogLevel.Information => CoreLogLevel.Info,
|
||||
MsLogLevel.Warning => CoreLogLevel.Warning,
|
||||
_ => CoreLogLevel.Error,
|
||||
};
|
||||
sink.Write(level, category, formatter(state, exception), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Bridges engine logging (Titano.Core.Diagnostics.Log) into ASP.NET Core logging.</summary>
|
||||
public sealed class LoggerSink(ILoggerFactory factory) : ILogSink
|
||||
{
|
||||
public void Write(CoreLogLevel level, string category, string message, Exception? exception)
|
||||
{
|
||||
var logger = factory.CreateLogger("Titano." + category);
|
||||
var ms = level switch
|
||||
{
|
||||
CoreLogLevel.Trace => MsLogLevel.Trace,
|
||||
CoreLogLevel.Debug => MsLogLevel.Debug,
|
||||
CoreLogLevel.Info => MsLogLevel.Information,
|
||||
CoreLogLevel.Warning => MsLogLevel.Warning,
|
||||
_ => MsLogLevel.Error,
|
||||
};
|
||||
#pragma warning disable CA2254 // Engine messages are preformatted.
|
||||
logger.Log(ms, exception, message);
|
||||
#pragma warning restore CA2254
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// <c>Titano.Server --healthcheck</c>: probes the local /health endpoint and exits 0/1, so the container
|
||||
/// HEALTHCHECK needs no curl/wget in the image.
|
||||
/// </summary>
|
||||
public static class HealthProbe
|
||||
{
|
||||
public static async Task<int> RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var port = ServerOptions.Load().HttpPort;
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
|
||||
using var response = await http.GetAsync(new Uri($"http://127.0.0.1:{port}/health")).ConfigureAwait(false);
|
||||
return response.IsSuccessStatusCode ? 0 : 1;
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException)
|
||||
{
|
||||
await Console.Error.WriteLineAsync(ex.Message).ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Api;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>Builds the Titano Server web application from <see cref="ServerOptions"/> (used by Program and tests).</summary>
|
||||
public static class ServerHost
|
||||
{
|
||||
public static WebApplication Build(ServerOptions options, string[] args)
|
||||
{
|
||||
Directory.CreateDirectory(options.DataPath);
|
||||
Directory.CreateDirectory(options.LogPath);
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder(args);
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.AddSimpleConsole(c => c.SingleLine = true);
|
||||
builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server")));
|
||||
builder.Logging.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning);
|
||||
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", Microsoft.Extensions.Logging.LogLevel.Information);
|
||||
|
||||
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true));
|
||||
var certificate = CertificateStore.Load(options, bootLoggerFactory.CreateLogger("Titano.Server"));
|
||||
var state = new ServerState { TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate) };
|
||||
|
||||
builder.WebHost.ConfigureKestrel(k =>
|
||||
{
|
||||
k.AddServerHeader = false;
|
||||
k.Limits.MaxRequestBodySize = options.ChunkSizeBytes + 64 * 1024;
|
||||
k.ListenAnyIP(options.HttpPort);
|
||||
if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l =>
|
||||
{
|
||||
l.Protocols = HttpProtocols.Http1AndHttp2;
|
||||
l.UseHttps(certificate);
|
||||
});
|
||||
});
|
||||
builder.Services.AddSingleton(options);
|
||||
builder.Services.AddSingleton(state);
|
||||
builder.Services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default));
|
||||
if (options.TlsMode == TlsMode.Proxy)
|
||||
{
|
||||
builder.Services.Configure<ForwardedHeadersOptions>(f =>
|
||||
{
|
||||
f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
|
||||
f.KnownIPNetworks.Clear();
|
||||
f.KnownProxies.Clear();
|
||||
});
|
||||
}
|
||||
|
||||
var app = builder.Build();
|
||||
Log.SetSink(new LoggerSink(app.Services.GetRequiredService<ILoggerFactory>()));
|
||||
var logger = app.Logger;
|
||||
logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · TLS {Tls}{Fingerprint}",
|
||||
SystemEndpoints.Version, options.ArchivePath, options.DataPath, options.TlsMode,
|
||||
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
|
||||
|
||||
if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders();
|
||||
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
context.Response.Headers[ApiVersion.Header] = ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
context.Response.Headers.XContentTypeOptions = "nosniff";
|
||||
context.Response.Headers["Referrer-Policy"] = "no-referrer";
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (Exception ex) when (!context.Response.HasStarted && ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(ex, "Unhandled error on {Method} {Path}", context.Request.Method, context.Request.Path);
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
await context.Response.WriteAsJsonAsync(new ApiError("internal", "Unexpected server error."), ProtocolJson.Default.ApiError);
|
||||
}
|
||||
});
|
||||
|
||||
var admin = new EmbeddedStaticFiles(typeof(ServerHost).Assembly, "admin/");
|
||||
app.MapGet("/", () => Results.Redirect("/admin/"));
|
||||
app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) =>
|
||||
{
|
||||
// Relative asset URLs need the trailing slash.
|
||||
if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path))
|
||||
{
|
||||
context.Response.Redirect("/admin/");
|
||||
return;
|
||||
}
|
||||
if (!await admin.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
});
|
||||
|
||||
SystemEndpoints.Map(app, options, state);
|
||||
|
||||
app.MapFallback("/api/{**path}", () => Results.Json(new ApiError("not_found", "No such endpoint."), ProtocolJson.Default.ApiError, statusCode: 404));
|
||||
app.Lifetime.ApplicationStopping.Register(() => logger.LogInformation("Titano Server stopping"));
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var app = builder.Build();
|
||||
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));
|
||||
app.Run();
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Hosting;
|
||||
|
||||
if (args.Contains("--healthcheck")) return await HealthProbe.RunAsync();
|
||||
|
||||
var app = ServerHost.Build(ServerOptions.Load(), args);
|
||||
await app.RunAsync();
|
||||
return 0;
|
||||
|
||||
/// <summary>Entry point type, visible to the in-process test host.</summary>
|
||||
public partial class Program;
|
||||
@@ -0,0 +1,90 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Titano.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Builds release notes from Conventional Commits. Reads <c>git log --format=%h%x09%s</c> lines from stdin
|
||||
/// (or <c>--in file</c>) and writes Markdown grouped by type.
|
||||
/// </summary>
|
||||
internal sealed partial class ChangelogCommand : ICommand
|
||||
{
|
||||
private static readonly (string Type, string Heading)[] Sections =
|
||||
[
|
||||
("feat", "Added"),
|
||||
("fix", "Fixed"),
|
||||
("perf", "Performance"),
|
||||
("security", "Security"),
|
||||
("i18n", "Localization"),
|
||||
("docs", "Documentation"),
|
||||
];
|
||||
|
||||
public string Name => "changelog";
|
||||
public string Summary => "Release notes from Conventional Commits on stdin (--title, --out file)";
|
||||
|
||||
public async Task<int> RunAsync(string[] args)
|
||||
{
|
||||
var a = new Args(args);
|
||||
IReadOnlyList<string> input = a.Get("in") is { } file ? await File.ReadAllLinesAsync(file) : ReadStdin();
|
||||
var markdown = Render(input, a.Get("title"));
|
||||
if (a.Get("out") is { } outFile)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outFile))!);
|
||||
await File.WriteAllTextAsync(outFile, markdown, new UTF8Encoding(false));
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.Write(markdown);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal static string Render(IEnumerable<string> lines, string? title)
|
||||
{
|
||||
var groups = new Dictionary<string, List<string>>(StringComparer.Ordinal);
|
||||
var breaking = new List<string>();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var tab = line.IndexOf('\t');
|
||||
var hash = tab > 0 ? line[..tab] : string.Empty;
|
||||
var subject = tab > 0 ? line[(tab + 1)..] : line;
|
||||
var m = Conventional().Match(subject);
|
||||
if (!m.Success) continue;
|
||||
var type = m.Groups["type"].Value.ToLowerInvariant();
|
||||
var scope = m.Groups["scope"].Success ? $"**{m.Groups["scope"].Value}**: " : string.Empty;
|
||||
var entry = $"- {scope}{m.Groups["desc"].Value.Trim()}{(hash.Length > 0 ? $" ({hash})" : string.Empty)}";
|
||||
if (m.Groups["bang"].Success) breaking.Add(entry);
|
||||
if (!groups.TryGetValue(type, out var list)) groups[type] = list = [];
|
||||
list.Add(entry);
|
||||
}
|
||||
|
||||
var sb = new StringBuilder();
|
||||
if (title is not null) sb.Append("# ").AppendLine(title).AppendLine();
|
||||
if (breaking.Count > 0)
|
||||
{
|
||||
sb.AppendLine("### Breaking changes");
|
||||
foreach (var e in breaking) sb.AppendLine(e);
|
||||
sb.AppendLine();
|
||||
}
|
||||
foreach (var (type, heading) in Sections)
|
||||
{
|
||||
if (!groups.TryGetValue(type, out var entries)) continue;
|
||||
sb.Append("### ").AppendLine(heading);
|
||||
foreach (var e in entries) sb.AppendLine(e);
|
||||
sb.AppendLine();
|
||||
}
|
||||
if (sb.Length == 0) sb.AppendLine("Maintenance release.");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static List<string> ReadStdin()
|
||||
{
|
||||
var lines = new List<string>();
|
||||
if (!Console.IsInputRedirected) return lines;
|
||||
while (Console.In.ReadLine() is { } line) lines.Add(line);
|
||||
return lines;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^(?<type>[a-zA-Z]+)(?:\((?<scope>[^)]+)\))?(?<bang>!)?:\s*(?<desc>.+)$")]
|
||||
private static partial Regex Conventional();
|
||||
}
|
||||
@@ -83,6 +83,8 @@ internal sealed partial class I18nCommand : ICommand
|
||||
foreach (var (file, key) in UsedKeys(root))
|
||||
{
|
||||
if (en.ContainsKey(key)) continue;
|
||||
// Prefix lookups such as L("Settings.Page." + page) are satisfied by any key under the prefix.
|
||||
if (key.EndsWith('.') && en.Keys.Any(k => k.StartsWith(key, StringComparison.Ordinal))) continue;
|
||||
// Plural lookups reference the stem; any suffix satisfies them.
|
||||
if (en.Keys.Any(k => k.StartsWith(key + ".", StringComparison.Ordinal) && PluralSuffix().IsMatch(k[(key.Length + 1)..]))) continue;
|
||||
errors.Add($"{Path.GetRelativePath(root, file)}: unknown key {key}");
|
||||
|
||||
@@ -7,6 +7,7 @@ var commands = new ICommand[]
|
||||
new I18nCommand(),
|
||||
new XamlLintCommand(),
|
||||
new PackageGuardCommand(),
|
||||
new ChangelogCommand(),
|
||||
};
|
||||
|
||||
if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>
|
||||
/// Advisor-aware slider (BRIEF §10.4, DESIGN §4): in Auto the track is accent with an "Auto · value" pill whose
|
||||
/// tooltip carries the advisor's reason; touching the slider switches to manual (sun track, value shown, reset
|
||||
/// button returns to Auto). When not applicable the value reads "n/a" with the reason in the tooltip.
|
||||
/// </summary>
|
||||
[TemplatePart(Name = PartSlider, Type = typeof(Slider))]
|
||||
public class AutoSlider : Control
|
||||
{
|
||||
public const string PartSlider = "PART_Slider";
|
||||
|
||||
public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(nameof(Header), typeof(string), typeof(AutoSlider));
|
||||
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(nameof(Value), typeof(double), typeof(AutoSlider),
|
||||
new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnValueChanged));
|
||||
public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register(nameof(Minimum), typeof(double), typeof(AutoSlider), new PropertyMetadata(0.0));
|
||||
public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register(nameof(Maximum), typeof(double), typeof(AutoSlider), new PropertyMetadata(1.0));
|
||||
public static readonly DependencyProperty SmallChangeProperty = DependencyProperty.Register(nameof(SmallChange), typeof(double), typeof(AutoSlider), new PropertyMetadata(0.01));
|
||||
public static readonly DependencyProperty IsSnapToTickEnabledProperty = DependencyProperty.Register(nameof(IsSnapToTickEnabled), typeof(bool), typeof(AutoSlider), new PropertyMetadata(false));
|
||||
public static readonly DependencyProperty TickFrequencyProperty = DependencyProperty.Register(nameof(TickFrequency), typeof(double), typeof(AutoSlider), new PropertyMetadata(1.0));
|
||||
public static readonly DependencyProperty IsAutoProperty = DependencyProperty.Register(nameof(IsAuto), typeof(bool), typeof(AutoSlider),
|
||||
new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
|
||||
public static readonly DependencyProperty AutoValueProperty = DependencyProperty.Register(nameof(AutoValue), typeof(double), typeof(AutoSlider), new PropertyMetadata(0.0, OnAutoValueChanged));
|
||||
public static readonly DependencyProperty AutoReasonProperty = DependencyProperty.Register(nameof(AutoReason), typeof(string), typeof(AutoSlider));
|
||||
public static readonly DependencyProperty IsApplicableProperty = DependencyProperty.Register(nameof(IsApplicable), typeof(bool), typeof(AutoSlider), new PropertyMetadata(true));
|
||||
public static readonly DependencyProperty NotApplicableReasonProperty = DependencyProperty.Register(nameof(NotApplicableReason), typeof(string), typeof(AutoSlider));
|
||||
public static readonly DependencyProperty ValueFormatProperty = DependencyProperty.Register(nameof(ValueFormat), typeof(string), typeof(AutoSlider), new PropertyMetadata("0.##", OnFormatChanged));
|
||||
public static readonly DependencyProperty DisplayValueProperty = DependencyProperty.Register(nameof(DisplayValue), typeof(string), typeof(AutoSlider), new PropertyMetadata(string.Empty));
|
||||
public static readonly DependencyProperty AutoTextProperty = DependencyProperty.Register(nameof(AutoText), typeof(string), typeof(AutoSlider), new PropertyMetadata(string.Empty));
|
||||
public static readonly DependencyProperty SliderToolTipProperty = DependencyProperty.Register(nameof(SliderToolTip), typeof(object), typeof(AutoSlider));
|
||||
|
||||
public static readonly RoutedCommand ResetCommand = new(nameof(ResetCommand), typeof(AutoSlider));
|
||||
|
||||
private Slider? _slider;
|
||||
private bool _syncing;
|
||||
|
||||
static AutoSlider()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(AutoSlider), new FrameworkPropertyMetadata(typeof(AutoSlider)));
|
||||
}
|
||||
|
||||
public AutoSlider()
|
||||
{
|
||||
CommandBindings.Add(new CommandBinding(ResetCommand, (_, _) => ResetToAuto()));
|
||||
UpdateTexts();
|
||||
}
|
||||
|
||||
public string? Header { get => (string?)GetValue(HeaderProperty); set => SetValue(HeaderProperty, value); }
|
||||
public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); }
|
||||
public double Minimum { get => (double)GetValue(MinimumProperty); set => SetValue(MinimumProperty, value); }
|
||||
public double Maximum { get => (double)GetValue(MaximumProperty); set => SetValue(MaximumProperty, value); }
|
||||
public double SmallChange { get => (double)GetValue(SmallChangeProperty); set => SetValue(SmallChangeProperty, value); }
|
||||
public bool IsSnapToTickEnabled { get => (bool)GetValue(IsSnapToTickEnabledProperty); set => SetValue(IsSnapToTickEnabledProperty, value); }
|
||||
public double TickFrequency { get => (double)GetValue(TickFrequencyProperty); set => SetValue(TickFrequencyProperty, value); }
|
||||
public bool IsAuto { get => (bool)GetValue(IsAutoProperty); set => SetValue(IsAutoProperty, value); }
|
||||
public double AutoValue { get => (double)GetValue(AutoValueProperty); set => SetValue(AutoValueProperty, value); }
|
||||
public string? AutoReason { get => (string?)GetValue(AutoReasonProperty); set => SetValue(AutoReasonProperty, value); }
|
||||
public bool IsApplicable { get => (bool)GetValue(IsApplicableProperty); set => SetValue(IsApplicableProperty, value); }
|
||||
public string? NotApplicableReason { get => (string?)GetValue(NotApplicableReasonProperty); set => SetValue(NotApplicableReasonProperty, value); }
|
||||
public string ValueFormat { get => (string)GetValue(ValueFormatProperty); set => SetValue(ValueFormatProperty, value); }
|
||||
|
||||
/// <summary>Formatted current value (read by the template).</summary>
|
||||
public string DisplayValue { get => (string)GetValue(DisplayValueProperty); private set => SetValue(DisplayValueProperty, value); }
|
||||
|
||||
/// <summary>"Auto · 41" pill text; the "Auto" word comes from the catalog (Common.Auto).</summary>
|
||||
public string AutoText { get => (string)GetValue(AutoTextProperty); private set => SetValue(AutoTextProperty, value); }
|
||||
|
||||
/// <summary>Tooltip of the slider track: what moving it does.</summary>
|
||||
public object? SliderToolTip { get => GetValue(SliderToolTipProperty); set => SetValue(SliderToolTipProperty, value); }
|
||||
|
||||
public override void OnApplyTemplate()
|
||||
{
|
||||
if (_slider is not null)
|
||||
{
|
||||
_slider.ValueChanged -= OnSliderValueChanged;
|
||||
_slider.PreviewMouseDown -= OnSliderTouched;
|
||||
_slider.PreviewKeyDown -= OnSliderTouched;
|
||||
}
|
||||
base.OnApplyTemplate();
|
||||
_slider = GetTemplateChild(PartSlider) as Slider;
|
||||
if (_slider is not null)
|
||||
{
|
||||
_slider.Value = IsAuto ? AutoValue : Value;
|
||||
_slider.ValueChanged += OnSliderValueChanged;
|
||||
_slider.PreviewMouseDown += OnSliderTouched;
|
||||
_slider.PreviewKeyDown += OnSliderTouched;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns the control to the advisor's value.</summary>
|
||||
public void ResetToAuto()
|
||||
{
|
||||
IsAuto = true;
|
||||
Value = AutoValue;
|
||||
UpdateTexts();
|
||||
}
|
||||
|
||||
private void OnSliderTouched(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (e is KeyEventArgs k && k.Key is not (Key.Left or Key.Right or Key.Up or Key.Down or Key.PageUp or Key.PageDown or Key.Home or Key.End)) return;
|
||||
IsAuto = false;
|
||||
}
|
||||
|
||||
private void OnSliderValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
|
||||
{
|
||||
if (_syncing) return;
|
||||
Value = e.NewValue;
|
||||
}
|
||||
|
||||
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
var s = (AutoSlider)d;
|
||||
if (s._slider is not null && !s._syncing)
|
||||
{
|
||||
s._syncing = true;
|
||||
s._slider.Value = (double)e.NewValue;
|
||||
s._syncing = false;
|
||||
}
|
||||
s.UpdateTexts();
|
||||
}
|
||||
|
||||
private static void OnAutoValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
var s = (AutoSlider)d;
|
||||
if (s.IsAuto) s.Value = (double)e.NewValue;
|
||||
s.UpdateTexts();
|
||||
}
|
||||
|
||||
private static void OnFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((AutoSlider)d).UpdateTexts();
|
||||
|
||||
private void UpdateTexts()
|
||||
{
|
||||
var culture = Core.Localization.Loc.Culture;
|
||||
DisplayValue = Value.ToString(ValueFormat, culture);
|
||||
AutoText = Core.Localization.Loc.L("Common.Auto") + " · " + AutoValue.ToString(ValueFormat, culture);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using Titano.Core.Branding;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>The Titano mark drawn as vectors from <see cref="BrandMark"/> geometry (plate optional).</summary>
|
||||
public sealed class BrandMarkIcon : FrameworkElement
|
||||
{
|
||||
public static readonly DependencyProperty ShowPlateProperty = DependencyProperty.Register(
|
||||
nameof(ShowPlate), typeof(bool), typeof(BrandMarkIcon), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
|
||||
|
||||
private static readonly Brush Accent = Frozen(new SolidColorBrush(Color.FromRgb(BrandMark.Accent.R, BrandMark.Accent.G, BrandMark.Accent.B)));
|
||||
private static readonly Brush Sun = Frozen(new SolidColorBrush(Color.FromRgb(BrandMark.Sun.R, BrandMark.Sun.G, BrandMark.Sun.B)));
|
||||
private static readonly Brush Plate = Frozen(new SolidColorBrush(Color.FromRgb(BrandMark.Plate.R, BrandMark.Plate.G, BrandMark.Plate.B)));
|
||||
|
||||
public bool ShowPlate
|
||||
{
|
||||
get => (bool)GetValue(ShowPlateProperty);
|
||||
set => SetValue(ShowPlateProperty, value);
|
||||
}
|
||||
|
||||
protected override Size MeasureOverride(Size availableSize)
|
||||
{
|
||||
var s = double.IsInfinity(availableSize.Width) ? 16 : Math.Min(availableSize.Width, double.IsInfinity(availableSize.Height) ? availableSize.Width : availableSize.Height);
|
||||
return new Size(s, s);
|
||||
}
|
||||
|
||||
protected override void OnRender(DrawingContext dc)
|
||||
{
|
||||
var size = Math.Min(ActualWidth, ActualHeight);
|
||||
if (size <= 0) return;
|
||||
var scale = size / BrandMark.Canvas;
|
||||
dc.PushTransform(new ScaleTransform(scale, scale));
|
||||
if (ShowPlate)
|
||||
dc.DrawRoundedRectangle(Plate, null, new Rect(0, 0, BrandMark.Canvas, BrandMark.Canvas), BrandMark.PlateRadius, BrandMark.PlateRadius);
|
||||
// Below ~24 px keep the stroke at least ~1.3 device pixels.
|
||||
var stroke = Math.Max(BrandMark.StrokeWidth, 1.3 / scale);
|
||||
for (var i = 0; i < BrandMark.TickCount; i++)
|
||||
{
|
||||
var (a0, a1) = BrandMark.TickAngles(i);
|
||||
var (x0, y0) = BrandMark.Polar(a0);
|
||||
var (x1, y1) = BrandMark.Polar(a1);
|
||||
var figure = new PathFigure { StartPoint = new Point(x0, y0) };
|
||||
figure.Segments.Add(new ArcSegment(new Point(x1, y1), new Size(BrandMark.RingRadius, BrandMark.RingRadius), 0, false, SweepDirection.Clockwise, true));
|
||||
var geometry = new PathGeometry([figure]);
|
||||
var pen = new Pen(Accent, stroke) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round };
|
||||
dc.PushOpacity(BrandMark.TickOpacity(i));
|
||||
dc.DrawGeometry(null, pen, geometry);
|
||||
dc.Pop();
|
||||
}
|
||||
dc.DrawEllipse(Sun, null, new Point(BrandMark.SunX, BrandMark.SunY), BrandMark.SunRadius, BrandMark.SunRadius);
|
||||
dc.Pop();
|
||||
}
|
||||
|
||||
private static Brush Frozen(SolidColorBrush b)
|
||||
{
|
||||
b.Freeze();
|
||||
return b;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>24-px pill (DESIGN §4). Selected or recommended chips use the accent border and text.</summary>
|
||||
public class Chip : ContentControl
|
||||
{
|
||||
public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register(nameof(IsSelected), typeof(bool), typeof(Chip));
|
||||
public static readonly DependencyProperty IsRecommendedProperty = DependencyProperty.Register(nameof(IsRecommended), typeof(bool), typeof(Chip));
|
||||
public static readonly DependencyProperty RemoveCommandProperty = DependencyProperty.Register(nameof(RemoveCommand), typeof(ICommand), typeof(Chip));
|
||||
public static readonly DependencyProperty RemoveCommandParameterProperty = DependencyProperty.Register(nameof(RemoveCommandParameter), typeof(object), typeof(Chip));
|
||||
public static readonly DependencyProperty RemoveToolTipProperty = DependencyProperty.Register(nameof(RemoveToolTip), typeof(object), typeof(Chip));
|
||||
|
||||
static Chip()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(Chip), new FrameworkPropertyMetadata(typeof(Chip)));
|
||||
}
|
||||
|
||||
public bool IsSelected { get => (bool)GetValue(IsSelectedProperty); set => SetValue(IsSelectedProperty, value); }
|
||||
public bool IsRecommended { get => (bool)GetValue(IsRecommendedProperty); set => SetValue(IsRecommendedProperty, value); }
|
||||
|
||||
/// <summary>When set, a small ✕ button removes the chip (filters, tags).</summary>
|
||||
public ICommand? RemoveCommand { get => (ICommand?)GetValue(RemoveCommandProperty); set => SetValue(RemoveCommandProperty, value); }
|
||||
|
||||
public object? RemoveCommandParameter { get => GetValue(RemoveCommandParameterProperty); set => SetValue(RemoveCommandParameterProperty, value); }
|
||||
public object? RemoveToolTip { get => GetValue(RemoveToolTipProperty); set => SetValue(RemoveToolTipProperty, value); }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>Attached brushes that let one control template serve every button variant (DESIGN §4 states).</summary>
|
||||
public static class ControlState
|
||||
{
|
||||
public static readonly DependencyProperty HoverBackgroundProperty = DependencyProperty.RegisterAttached("HoverBackground", typeof(Brush), typeof(ControlState));
|
||||
public static readonly DependencyProperty PressedBackgroundProperty = DependencyProperty.RegisterAttached("PressedBackground", typeof(Brush), typeof(ControlState));
|
||||
public static readonly DependencyProperty HoverBorderBrushProperty = DependencyProperty.RegisterAttached("HoverBorderBrush", typeof(Brush), typeof(ControlState));
|
||||
public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.RegisterAttached("CornerRadius", typeof(CornerRadius), typeof(ControlState), new FrameworkPropertyMetadata(new CornerRadius(6)));
|
||||
public static readonly DependencyProperty AccentProperty = DependencyProperty.RegisterAttached("Accent", typeof(Brush), typeof(ControlState), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits));
|
||||
|
||||
public static Brush? GetHoverBackground(DependencyObject d) => (Brush?)d.GetValue(HoverBackgroundProperty);
|
||||
public static void SetHoverBackground(DependencyObject d, Brush? v) => d.SetValue(HoverBackgroundProperty, v);
|
||||
public static Brush? GetPressedBackground(DependencyObject d) => (Brush?)d.GetValue(PressedBackgroundProperty);
|
||||
public static void SetPressedBackground(DependencyObject d, Brush? v) => d.SetValue(PressedBackgroundProperty, v);
|
||||
public static Brush? GetHoverBorderBrush(DependencyObject d) => (Brush?)d.GetValue(HoverBorderBrushProperty);
|
||||
public static void SetHoverBorderBrush(DependencyObject d, Brush? v) => d.SetValue(HoverBorderBrushProperty, v);
|
||||
public static CornerRadius GetCornerRadius(DependencyObject d) => (CornerRadius)d.GetValue(CornerRadiusProperty);
|
||||
public static void SetCornerRadius(DependencyObject d, CornerRadius v) => d.SetValue(CornerRadiusProperty, v);
|
||||
|
||||
/// <summary>Fill colour of slider tracks and progress (accent = Auto, sun = manual).</summary>
|
||||
public static Brush? GetAccent(DependencyObject d) => (Brush?)d.GetValue(AccentProperty);
|
||||
|
||||
public static void SetAccent(DependencyObject d, Brush? v) => d.SetValue(AccentProperty, v);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>null → Collapsed, otherwise Visible.</summary>
|
||||
public sealed class NullToCollapsedConverter : IValueConverter
|
||||
{
|
||||
public static NullToCollapsedConverter Instance { get; } = new();
|
||||
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is null || value is string { Length: 0 } ? Visibility.Collapsed : Visibility.Visible;
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
/// <summary>true → Collapsed (inverse of BooleanToVisibilityConverter).</summary>
|
||||
public sealed class InverseBoolToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static InverseBoolToVisibilityConverter Instance { get; } = new();
|
||||
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is true ? Visibility.Collapsed : Visibility.Visible;
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
/// <summary>0 → Collapsed, any other number → Visible.</summary>
|
||||
public sealed class ZeroToCollapsedConverter : IValueConverter
|
||||
{
|
||||
public static ZeroToCollapsedConverter Instance { get; } = new();
|
||||
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value switch
|
||||
{
|
||||
int i => i == 0 ? Visibility.Collapsed : Visibility.Visible,
|
||||
long l => l == 0 ? Visibility.Collapsed : Visibility.Visible,
|
||||
double d => d == 0 ? Visibility.Collapsed : Visibility.Visible,
|
||||
_ => Visibility.Collapsed,
|
||||
};
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>Empty state: the mark, one sentence and the action buttons supplied as content (BRIEF §0.2 rule 6).</summary>
|
||||
public class EmptyState : ContentControl
|
||||
{
|
||||
public static readonly DependencyProperty MessageProperty = DependencyProperty.Register(nameof(Message), typeof(string), typeof(EmptyState));
|
||||
|
||||
static EmptyState()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(EmptyState), new FrameworkPropertyMetadata(typeof(EmptyState)));
|
||||
}
|
||||
|
||||
public string? Message { get => (string?)GetValue(MessageProperty); set => SetValue(MessageProperty, value); }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>Attached field helpers: placeholder text and an inline leading icon for text inputs.</summary>
|
||||
public static class Field
|
||||
{
|
||||
public static readonly DependencyProperty PlaceholderProperty = DependencyProperty.RegisterAttached(
|
||||
"Placeholder", typeof(string), typeof(Field), new FrameworkPropertyMetadata(null));
|
||||
|
||||
public static readonly DependencyProperty GlyphProperty = DependencyProperty.RegisterAttached(
|
||||
"Glyph", typeof(IconData), typeof(Field), new FrameworkPropertyMetadata(null));
|
||||
|
||||
public static string? GetPlaceholder(DependencyObject d) => (string?)d.GetValue(PlaceholderProperty);
|
||||
|
||||
public static void SetPlaceholder(DependencyObject d, string? value) => d.SetValue(PlaceholderProperty, value);
|
||||
|
||||
public static IconData? GetGlyph(DependencyObject d) => (IconData?)d.GetValue(GlyphProperty);
|
||||
|
||||
public static void SetGlyph(DependencyObject d, IconData? value) => d.SetValue(GlyphProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>Attached glyph for buttons: renders an <see cref="IconData"/> before (or instead of) the content.</summary>
|
||||
public static class ButtonIcon
|
||||
{
|
||||
public static readonly DependencyProperty GlyphProperty = DependencyProperty.RegisterAttached(
|
||||
"Glyph", typeof(IconData), typeof(ButtonIcon), new FrameworkPropertyMetadata(null));
|
||||
|
||||
public static IconData? GetGlyph(DependencyObject d) => (IconData?)d.GetValue(GlyphProperty);
|
||||
|
||||
public static void SetGlyph(DependencyObject d, IconData? value) => d.SetValue(GlyphProperty, value);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>Renders an <see cref="IconData"/> on the 16-unit grid, scaled to the element size, in the inherited foreground.</summary>
|
||||
public sealed class Icon : FrameworkElement
|
||||
{
|
||||
public static readonly DependencyProperty GlyphProperty = DependencyProperty.Register(
|
||||
nameof(Glyph), typeof(IconData), typeof(Icon),
|
||||
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
|
||||
|
||||
public static readonly DependencyProperty ForegroundProperty = TextElement.ForegroundProperty.AddOwner(
|
||||
typeof(Icon), new FrameworkPropertyMetadata(Brushes.Gray, FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.AffectsRender));
|
||||
|
||||
public static readonly DependencyProperty SizeProperty = DependencyProperty.Register(
|
||||
nameof(Size), typeof(double), typeof(Icon),
|
||||
new FrameworkPropertyMetadata(16.0, FrameworkPropertyMetadataOptions.AffectsMeasure));
|
||||
|
||||
public static readonly DependencyProperty StrokeWidthProperty = DependencyProperty.Register(
|
||||
nameof(StrokeWidth), typeof(double), typeof(Icon),
|
||||
new FrameworkPropertyMetadata(1.5, FrameworkPropertyMetadataOptions.AffectsRender));
|
||||
|
||||
static Icon()
|
||||
{
|
||||
SnapsToDevicePixelsProperty.OverrideMetadata(typeof(Icon), new FrameworkPropertyMetadata(true));
|
||||
FocusableProperty.OverrideMetadata(typeof(Icon), new FrameworkPropertyMetadata(false));
|
||||
}
|
||||
|
||||
public IconData? Glyph
|
||||
{
|
||||
get => (IconData?)GetValue(GlyphProperty);
|
||||
set => SetValue(GlyphProperty, value);
|
||||
}
|
||||
|
||||
public Brush Foreground
|
||||
{
|
||||
get => (Brush)GetValue(ForegroundProperty);
|
||||
set => SetValue(ForegroundProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>Edge length in device-independent pixels (default 16).</summary>
|
||||
public double Size
|
||||
{
|
||||
get => (double)GetValue(SizeProperty);
|
||||
set => SetValue(SizeProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>Stroke width on the 16-unit grid (default 1.5).</summary>
|
||||
public double StrokeWidth
|
||||
{
|
||||
get => (double)GetValue(StrokeWidthProperty);
|
||||
set => SetValue(StrokeWidthProperty, value);
|
||||
}
|
||||
|
||||
protected override Size MeasureOverride(Size availableSize) => new(Size, Size);
|
||||
|
||||
protected override void OnRender(DrawingContext dc)
|
||||
{
|
||||
var glyph = Glyph;
|
||||
if (glyph is null) return;
|
||||
var scale = Size / 16.0;
|
||||
dc.PushTransform(new ScaleTransform(scale, scale));
|
||||
if (glyph.Fill is not null) dc.DrawGeometry(Foreground, null, glyph.Fill);
|
||||
if (glyph.Stroke is not null)
|
||||
{
|
||||
var pen = new Pen(Foreground, StrokeWidth)
|
||||
{
|
||||
StartLineCap = PenLineCap.Round,
|
||||
EndLineCap = PenLineCap.Round,
|
||||
LineJoin = PenLineJoin.Round,
|
||||
};
|
||||
pen.Freeze();
|
||||
dc.DrawGeometry(null, pen, glyph.Stroke);
|
||||
}
|
||||
dc.Pop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>A 16×16 icon: a stroked outline and an optional filled part (DESIGN.md §5).</summary>
|
||||
public sealed class IconData
|
||||
{
|
||||
private Geometry? _stroke;
|
||||
private Geometry? _fill;
|
||||
|
||||
/// <summary>Outline drawn with a 1.5-px round pen in the foreground colour.</summary>
|
||||
public Geometry? Stroke
|
||||
{
|
||||
get => _stroke;
|
||||
set => _stroke = Freeze(value);
|
||||
}
|
||||
|
||||
/// <summary>Solid part filled with the foreground colour.</summary>
|
||||
public Geometry? Fill
|
||||
{
|
||||
get => _fill;
|
||||
set => _fill = Freeze(value);
|
||||
}
|
||||
|
||||
private static Geometry? Freeze(Geometry? g)
|
||||
{
|
||||
if (g is { CanFreeze: true, IsFrozen: false }) g.Freeze();
|
||||
return g;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>40-px strip under the title bar: current job, progress, time left and a stop button (DESIGN §4).</summary>
|
||||
public class JobBar : Control
|
||||
{
|
||||
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(JobBar));
|
||||
public static readonly DependencyProperty ProgressProperty = DependencyProperty.Register(nameof(Progress), typeof(double), typeof(JobBar), new PropertyMetadata(0.0));
|
||||
public static readonly DependencyProperty IsIndeterminateProperty = DependencyProperty.Register(nameof(IsIndeterminate), typeof(bool), typeof(JobBar));
|
||||
public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register(nameof(IsActive), typeof(bool), typeof(JobBar));
|
||||
public static readonly DependencyProperty StopCommandProperty = DependencyProperty.Register(nameof(StopCommand), typeof(ICommand), typeof(JobBar));
|
||||
public static readonly DependencyProperty StopToolTipProperty = DependencyProperty.Register(nameof(StopToolTip), typeof(object), typeof(JobBar));
|
||||
|
||||
static JobBar()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(JobBar), new FrameworkPropertyMetadata(typeof(JobBar)));
|
||||
}
|
||||
|
||||
public string? Text { get => (string?)GetValue(TextProperty); set => SetValue(TextProperty, value); }
|
||||
|
||||
/// <summary>0..1.</summary>
|
||||
public double Progress { get => (double)GetValue(ProgressProperty); set => SetValue(ProgressProperty, value); }
|
||||
|
||||
public bool IsIndeterminate { get => (bool)GetValue(IsIndeterminateProperty); set => SetValue(IsIndeterminateProperty, value); }
|
||||
|
||||
/// <summary>A job is running: shows the progress fill and the stop button.</summary>
|
||||
public bool IsActive { get => (bool)GetValue(IsActiveProperty); set => SetValue(IsActiveProperty, value); }
|
||||
|
||||
public ICommand? StopCommand { get => (ICommand?)GetValue(StopCommandProperty); set => SetValue(StopCommandProperty, value); }
|
||||
public object? StopToolTip { get => GetValue(StopToolTipProperty); set => SetValue(StopToolTipProperty, value); }
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>Attached state of the navigation rail (DESIGN §3: 128 px, collapses to 48 px icons).</summary>
|
||||
public static class NavRail
|
||||
{
|
||||
public static readonly DependencyProperty IsCollapsedProperty = DependencyProperty.RegisterAttached(
|
||||
"IsCollapsed", typeof(bool), typeof(NavRail), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits));
|
||||
|
||||
public static bool GetIsCollapsed(DependencyObject d) => (bool)d.GetValue(IsCollapsedProperty);
|
||||
|
||||
public static void SetIsCollapsed(DependencyObject d, bool value) => d.SetValue(IsCollapsedProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>One rail entry: icon, label, optional attention badge; active = card fill + 3-px accent edge.</summary>
|
||||
public class NavRailButton : RadioButton
|
||||
{
|
||||
public static readonly DependencyProperty GlyphProperty = DependencyProperty.Register(
|
||||
nameof(Glyph), typeof(IconData), typeof(NavRailButton));
|
||||
|
||||
public static readonly DependencyProperty BadgeProperty = DependencyProperty.Register(
|
||||
nameof(Badge), typeof(int), typeof(NavRailButton), new PropertyMetadata(0));
|
||||
|
||||
static NavRailButton()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(NavRailButton), new FrameworkPropertyMetadata(typeof(NavRailButton)));
|
||||
}
|
||||
|
||||
public IconData? Glyph
|
||||
{
|
||||
get => (IconData?)GetValue(GlyphProperty);
|
||||
set => SetValue(GlyphProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>Count of things needing attention; hidden when 0.</summary>
|
||||
public int Badge
|
||||
{
|
||||
get => (int)GetValue(BadgeProperty);
|
||||
set => SetValue(BadgeProperty, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>Status vocabulary of DESIGN §4: colour is always paired with a glyph and a word.</summary>
|
||||
public enum StatusKind
|
||||
{
|
||||
Analysed,
|
||||
NotAnalysed,
|
||||
Proxies,
|
||||
NoProxies,
|
||||
Rendered,
|
||||
Synced,
|
||||
Remote,
|
||||
Analysing,
|
||||
Warning,
|
||||
Error,
|
||||
Running,
|
||||
Queued,
|
||||
Done,
|
||||
Failed,
|
||||
Paused,
|
||||
Online,
|
||||
Offline,
|
||||
}
|
||||
|
||||
/// <summary>Glyph + text in the colour of the status kind.</summary>
|
||||
public class StatusGlyph : Control
|
||||
{
|
||||
public static readonly DependencyProperty KindProperty = DependencyProperty.Register(nameof(Kind), typeof(StatusKind), typeof(StatusGlyph), new PropertyMetadata(StatusKind.Analysed));
|
||||
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(StatusGlyph));
|
||||
|
||||
static StatusGlyph()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(StatusGlyph), new FrameworkPropertyMetadata(typeof(StatusGlyph)));
|
||||
FocusableProperty.OverrideMetadata(typeof(StatusGlyph), new FrameworkPropertyMetadata(false));
|
||||
}
|
||||
|
||||
public StatusKind Kind { get => (StatusKind)GetValue(KindProperty); set => SetValue(KindProperty, value); }
|
||||
public string? Text { get => (string?)GetValue(TextProperty); set => SetValue(TextProperty, value); }
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Shell;
|
||||
using Titano.Ui.Interop;
|
||||
using Titano.Ui.Theming;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>
|
||||
/// Window with Titano's custom chrome: 34-px title bar in the Chrome colour, brand mark, title, optional
|
||||
/// title-bar content and drawn caption buttons. The maximise button answers HTMAXBUTTON so Windows 11
|
||||
/// snap layouts appear on hover.
|
||||
/// </summary>
|
||||
[TemplatePart(Name = PartMaximize, Type = typeof(Button))]
|
||||
public class TitanoWindow : Window
|
||||
{
|
||||
public const string PartMaximize = "PART_Maximize";
|
||||
|
||||
public static readonly DependencyProperty TitleBarContentProperty = DependencyProperty.Register(
|
||||
nameof(TitleBarContent), typeof(object), typeof(TitanoWindow));
|
||||
|
||||
public static readonly DependencyProperty IsDialogProperty = DependencyProperty.Register(
|
||||
nameof(IsDialog), typeof(bool), typeof(TitanoWindow), new PropertyMetadata(false));
|
||||
|
||||
public static readonly DependencyProperty IsMaximizeHoveredProperty = DependencyProperty.Register(
|
||||
nameof(IsMaximizeHovered), typeof(bool), typeof(TitanoWindow), new PropertyMetadata(false));
|
||||
|
||||
private Button? _maximize;
|
||||
|
||||
static TitanoWindow()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(TitanoWindow), new FrameworkPropertyMetadata(typeof(TitanoWindow)));
|
||||
}
|
||||
|
||||
public TitanoWindow()
|
||||
{
|
||||
WindowChrome.SetWindowChrome(this, new WindowChrome
|
||||
{
|
||||
CaptionHeight = 34,
|
||||
ResizeBorderThickness = new Thickness(6),
|
||||
GlassFrameThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(0),
|
||||
UseAeroCaptionButtons = false,
|
||||
});
|
||||
CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, (_, _) => SystemCommands.CloseWindow(this)));
|
||||
CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, (_, _) => SystemCommands.MinimizeWindow(this)));
|
||||
CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, (_, _) => ToggleMaximize()));
|
||||
CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, (_, _) => ToggleMaximize()));
|
||||
UseLayoutRounding = true;
|
||||
TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display);
|
||||
}
|
||||
|
||||
/// <summary>Extra content placed in the title bar between the title and the caption buttons.</summary>
|
||||
public object? TitleBarContent
|
||||
{
|
||||
get => GetValue(TitleBarContentProperty);
|
||||
set => SetValue(TitleBarContentProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>Dialog windows show only the close button.</summary>
|
||||
public bool IsDialog
|
||||
{
|
||||
get => (bool)GetValue(IsDialogProperty);
|
||||
set => SetValue(IsDialogProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>True while the pointer is over the maximise button (non-client, so tracked from WndProc).</summary>
|
||||
public bool IsMaximizeHovered
|
||||
{
|
||||
get => (bool)GetValue(IsMaximizeHoveredProperty);
|
||||
set => SetValue(IsMaximizeHoveredProperty, value);
|
||||
}
|
||||
|
||||
public override void OnApplyTemplate()
|
||||
{
|
||||
base.OnApplyTemplate();
|
||||
_maximize = GetTemplateChild(PartMaximize) as Button;
|
||||
}
|
||||
|
||||
protected override void OnSourceInitialized(EventArgs e)
|
||||
{
|
||||
base.OnSourceInitialized(e);
|
||||
ThemeManager.ApplyChrome(this);
|
||||
if (PresentationSource.FromVisual(this) is HwndSource source) source.AddHook(WndProc);
|
||||
}
|
||||
|
||||
private void ToggleMaximize()
|
||||
{
|
||||
if (WindowState == WindowState.Maximized) SystemCommands.RestoreWindow(this);
|
||||
else SystemCommands.MaximizeWindow(this);
|
||||
}
|
||||
|
||||
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
|
||||
{
|
||||
switch (msg)
|
||||
{
|
||||
case NativeMethods.WM_NCHITTEST when _maximize is { IsVisible: true } && ResizeMode is ResizeMode.CanResize or ResizeMode.CanResizeWithGrip:
|
||||
if (IsOverMaximize(lParam))
|
||||
{
|
||||
IsMaximizeHovered = true;
|
||||
handled = true;
|
||||
return NativeMethods.HTMAXBUTTON;
|
||||
}
|
||||
IsMaximizeHovered = false;
|
||||
break;
|
||||
case NativeMethods.WM_NCLBUTTONDOWN when wParam == NativeMethods.HTMAXBUTTON:
|
||||
handled = true;
|
||||
break;
|
||||
case NativeMethods.WM_NCLBUTTONUP when wParam == NativeMethods.HTMAXBUTTON:
|
||||
handled = true;
|
||||
ToggleMaximize();
|
||||
break;
|
||||
case NativeMethods.WM_NCMOUSELEAVE:
|
||||
IsMaximizeHovered = false;
|
||||
break;
|
||||
}
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
private bool IsOverMaximize(IntPtr lParam)
|
||||
{
|
||||
if (_maximize is null) return false;
|
||||
var x = unchecked((short)(long)lParam);
|
||||
var y = unchecked((short)((long)lParam >> 16));
|
||||
try
|
||||
{
|
||||
var point = _maximize.PointFromScreen(new Point(x, y));
|
||||
return point.X >= 0 && point.Y >= 0 && point.X < _maximize.ActualWidth && point.Y < _maximize.ActualHeight;
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.Ui.Controls;
|
||||
|
||||
/// <summary>One in-window notification (DESIGN §4: 420 px, accent left edge, one action, 8 s, hover pauses).</summary>
|
||||
public sealed class Toast : ObservableObject
|
||||
{
|
||||
public required string Title { get; init; }
|
||||
public string? Message { get; init; }
|
||||
public string? ActionText { get; init; }
|
||||
public ICommand? ActionCommand { get; init; }
|
||||
public string? ActionToolTip { get; init; }
|
||||
public TimeSpan Lifetime { get; init; } = TimeSpan.FromSeconds(8);
|
||||
}
|
||||
|
||||
/// <summary>Bottom-right stack of <see cref="Toast"/>s with auto-dismiss.</summary>
|
||||
public class ToastHost : ItemsControl
|
||||
{
|
||||
private readonly Dictionary<Toast, DispatcherTimer> _timers = [];
|
||||
|
||||
static ToastHost()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(ToastHost), new FrameworkPropertyMetadata(typeof(ToastHost)));
|
||||
}
|
||||
|
||||
public ToastHost()
|
||||
{
|
||||
ItemsSource = Toasts;
|
||||
CommandBindings.Add(new CommandBinding(DismissCommand, (_, e) =>
|
||||
{
|
||||
if (e.Parameter is Toast t) Dismiss(t);
|
||||
}));
|
||||
}
|
||||
|
||||
public static RoutedCommand DismissCommand { get; } = new(nameof(DismissCommand), typeof(ToastHost));
|
||||
|
||||
public ObservableCollection<Toast> Toasts { get; } = [];
|
||||
|
||||
public void Show(Toast toast)
|
||||
{
|
||||
Toasts.Add(toast);
|
||||
while (Toasts.Count > 3) Dismiss(Toasts[0]);
|
||||
var timer = new DispatcherTimer { Interval = toast.Lifetime };
|
||||
timer.Tick += (_, _) => Dismiss(toast);
|
||||
_timers[toast] = timer;
|
||||
timer.Start();
|
||||
}
|
||||
|
||||
/// <summary>Pauses or resumes the dismissal timer (hover pauses).</summary>
|
||||
public void SetPaused(Toast toast, bool paused)
|
||||
{
|
||||
if (!_timers.TryGetValue(toast, out var timer)) return;
|
||||
if (paused) timer.Stop();
|
||||
else timer.Start();
|
||||
}
|
||||
|
||||
public void Dismiss(Toast toast)
|
||||
{
|
||||
if (_timers.Remove(toast, out var timer)) timer.Stop();
|
||||
Toasts.Remove(toast);
|
||||
}
|
||||
|
||||
protected override void OnPreviewMouseMove(MouseEventArgs e)
|
||||
{
|
||||
base.OnPreviewMouseMove(e);
|
||||
foreach (var t in Toasts.ToList()) SetPaused(t, true);
|
||||
}
|
||||
|
||||
protected override void OnMouseLeave(MouseEventArgs e)
|
||||
{
|
||||
base.OnMouseLeave(e);
|
||||
foreach (var t in Toasts.ToList()) SetPaused(t, false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls">
|
||||
<!-- Generated by branding/ui-icons/icons.py — 16-px grid, 1.5-px round strokes (DESIGN.md §5). Do not edit by hand. -->
|
||||
<ui:IconData x:Key="Icon.About" Stroke="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M8 7 V11 M8 4.8 V5.2" />
|
||||
<ui:IconData x:Key="Icon.ActualSize" Stroke="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M5 6 L6 5.5 V10.5 M9.5 6 L10.5 5.5 V10.5 M8 7 V7.1 M8 9.5 V9.6" />
|
||||
<ui:IconData x:Key="Icon.Analyse" Stroke="M1.5 8.5 H4.5 L6.5 3.5 L9.5 12.5 L11.5 8.5 H14.5" />
|
||||
<ui:IconData x:Key="Icon.Archive" Stroke="M2 4.5 H14 V13.5 H2 Z M2 2 H14 V4.5 H2 Z M6 8 H10" />
|
||||
<ui:IconData x:Key="Icon.Back" Stroke="M13 8 H3 M7 4 L3 8 L7 12" />
|
||||
<ui:IconData x:Key="Icon.Calendar" Stroke="M3.0 3 H13.0 A1.5 1.5 0 0 1 14.5 4.5 V13.0 A1.5 1.5 0 0 1 13.0 14.5 H3.0 A1.5 1.5 0 0 1 1.5 13.0 V4.5 A1.5 1.5 0 0 1 3.0 3 Z M1.5 6.5 H14.5 M5 1.5 V4 M11 1.5 V4" />
|
||||
<ui:IconData x:Key="Icon.Camera" Stroke="M1.5 5 A1 1 0 0 1 2.5 4 H4.5 L6 2.5 H10 L11.5 4 H13.5 A1 1 0 0 1 14.5 5 V12.5 A1 1 0 0 1 13.5 13.5 H2.5 A1 1 0 0 1 1.5 12.5 Z M5.2 8.5 A2.8 2.8 0 1 0 10.8 8.5 A2.8 2.8 0 1 0 5.2 8.5 Z" />
|
||||
<ui:IconData x:Key="Icon.Cancel" Stroke="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M5.8 5.8 L10.2 10.2 M10.2 5.8 L5.8 10.2" />
|
||||
<ui:IconData x:Key="Icon.Card" Stroke="M4.5 1.5 H10 L12.5 4 V13.5 A1 1 0 0 1 11.5 14.5 H4.5 A1 1 0 0 1 3.5 13.5 V2.5 A1 1 0 0 1 4.5 1.5 Z M6 3.5 V5.5 M8 3.5 V5.5 M10 4.5 V5.5" />
|
||||
<ui:IconData x:Key="Icon.Chart" Stroke="M2 2 V14 H14 M4.5 10.5 L7.5 7 L9.5 9 L13.5 4" />
|
||||
<ui:IconData x:Key="Icon.Check" Stroke="M3 8.5 L6.5 12 L13 4.5" />
|
||||
<ui:IconData x:Key="Icon.ChevronDown" Stroke="M4 6 L8 10 L12 6" />
|
||||
<ui:IconData x:Key="Icon.ChevronLeft" Stroke="M10 4 L6 8 L10 12" />
|
||||
<ui:IconData x:Key="Icon.ChevronRight" Stroke="M6 4 L10 8 L6 12" />
|
||||
<ui:IconData x:Key="Icon.ChevronUp" Stroke="M4 10 L8 6 L12 10" />
|
||||
<ui:IconData x:Key="Icon.Clipboard" Stroke="M4.0 2.5 H12.0 A1.5 1.5 0 0 1 13.5 4.0 V13.0 A1.5 1.5 0 0 1 12.0 14.5 H4.0 A1.5 1.5 0 0 1 2.5 13.0 V4.0 A1.5 1.5 0 0 1 4.0 2.5 Z M6.3 1.5 H9.7 A0.8 0.8 0 0 1 10.5 2.3 V3.2 A0.8 0.8 0 0 1 9.7 4.0 H6.3 A0.8 0.8 0 0 1 5.5 3.2 V2.3 A0.8 0.8 0 0 1 6.3 1.5 Z" />
|
||||
<ui:IconData x:Key="Icon.Clock" Stroke="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M8 4.5 V8 L10.5 9.5" />
|
||||
<ui:IconData x:Key="Icon.Close" Stroke="M4 4 L12 12 M12 4 L4 12" />
|
||||
<ui:IconData x:Key="Icon.Compare" Stroke="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M8 1 V15" />
|
||||
<ui:IconData x:Key="Icon.Copy" Stroke="M6.5 5 H13.0 A1.5 1.5 0 0 1 14.5 6.5 V13.0 A1.5 1.5 0 0 1 13.0 14.5 H6.5 A1.5 1.5 0 0 1 5 13.0 V6.5 A1.5 1.5 0 0 1 6.5 5 Z M11 5 V2.5 A1 1 0 0 0 10 1.5 H2.5 A1 1 0 0 0 1.5 2.5 V10 A1 1 0 0 0 2.5 11 H5" />
|
||||
<ui:IconData x:Key="Icon.CropMask" Stroke="M4 1.5 V12 H14.5 M1.5 4 H12 V14.5" />
|
||||
<ui:IconData x:Key="Icon.Cross" Stroke="M4.5 4.5 L11.5 11.5 M11.5 4.5 L4.5 11.5" />
|
||||
<ui:IconData x:Key="Icon.Database" Stroke="M2.5 3.8 C2.5 2.5 13.5 2.5 13.5 3.8 C13.5 5.1 2.5 5.1 2.5 3.8 Z M2.5 3.8 V12.2 C2.5 13.5 13.5 13.5 13.5 12.2 V3.8 M2.5 8 C2.5 9.3 13.5 9.3 13.5 8" />
|
||||
<ui:IconData x:Key="Icon.Delete" Stroke="M2.5 4 H13.5 M6 4 V2.5 H10 V4 M3.8 4 L4.6 14 H11.4 L12.2 4 M6.6 6.8 V11.2 M9.4 6.8 V11.2" />
|
||||
<ui:IconData x:Key="Icon.Dot" Fill="M4.5 8 A3.5 3.5 0 1 0 11.5 8 A3.5 3.5 0 1 0 4.5 8 Z" />
|
||||
<ui:IconData x:Key="Icon.Download" Stroke="M8 2 V10 M4.5 6.5 L8 10 L11.5 6.5 M2.5 13.5 H13.5" />
|
||||
<ui:IconData x:Key="Icon.Drive" Stroke="M3.0 4.5 H13.0 A1.5 1.5 0 0 1 14.5 6.0 V10.0 A1.5 1.5 0 0 1 13.0 11.5 H3.0 A1.5 1.5 0 0 1 1.5 10.0 V6.0 A1.5 1.5 0 0 1 3.0 4.5 Z M4.5 8 H4.6 M7 8 H11.5" />
|
||||
<ui:IconData x:Key="Icon.Duplicate" Stroke="M6.5 5 H13.0 A1.5 1.5 0 0 1 14.5 6.5 V13.0 A1.5 1.5 0 0 1 13.0 14.5 H6.5 A1.5 1.5 0 0 1 5 13.0 V6.5 A1.5 1.5 0 0 1 6.5 5 Z M11 5 V2.5 A1 1 0 0 0 10 1.5 H2.5 A1 1 0 0 0 1.5 2.5 V10 A1 1 0 0 0 2.5 11 H5" />
|
||||
<ui:IconData x:Key="Icon.Eject" Stroke="M3 13 H13" Fill="M8 2.8 L13 9.5 H3 Z" />
|
||||
<ui:IconData x:Key="Icon.ErrorCircle" Stroke="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M5.8 5.8 L10.2 10.2 M10.2 5.8 L5.8 10.2" />
|
||||
<ui:IconData x:Key="Icon.Exclude" Stroke="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M3.4 12.6 L12.6 3.4" />
|
||||
<ui:IconData x:Key="Icon.Export" Stroke="M8 10 V1.8 M4.8 5 L8 1.8 L11.2 5 M5 7.5 H3 A1 1 0 0 0 2 8.5 V13.5 A1 1 0 0 0 3 14.5 H13 A1 1 0 0 0 14 13.5 V8.5 A1 1 0 0 0 13 7.5 H11" />
|
||||
<ui:IconData x:Key="Icon.Exposure" Stroke="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M3.4 12.6 L12.6 3.4 M4.5 6 H7 M5.75 4.75 V7.25 M9 10 H11.5" />
|
||||
<ui:IconData x:Key="Icon.ExternalLink" Stroke="M9.5 2 H14 V6.5 M14 2 L7.5 8.5 M12 9.5 V13 A1 1 0 0 1 11 14 H3 A1 1 0 0 1 2 13 V5 A1 1 0 0 1 3 4 H6.5" />
|
||||
<ui:IconData x:Key="Icon.Eye" Stroke="M1.5 8 C3.5 4 12.5 4 14.5 8 C12.5 12 3.5 12 1.5 8 Z M5.8 8 A2.2 2.2 0 1 0 10.2 8 A2.2 2.2 0 1 0 5.8 8 Z" />
|
||||
<ui:IconData x:Key="Icon.Filmstrip" Stroke="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M4.5 2.5 V13.5 M11.5 2.5 V13.5 M1.5 6 H4.5 M1.5 10 H4.5 M11.5 6 H14.5 M11.5 10 H14.5" />
|
||||
<ui:IconData x:Key="Icon.Filter" Stroke="M1.5 2.5 H14.5 L9.5 8.5 V13.5 L6.5 12 V8.5 Z" />
|
||||
<ui:IconData x:Key="Icon.Folder" Stroke="M1.5 4 A1 1 0 0 1 2.5 3 H6 L7.5 4.5 H13.5 A1 1 0 0 1 14.5 5.5 V12.5 A1 1 0 0 1 13.5 13.5 H2.5 A1 1 0 0 1 1.5 12.5 Z" />
|
||||
<ui:IconData x:Key="Icon.FolderOpen" Stroke="M1.5 12.5 V4 A1 1 0 0 1 2.5 3 H6 L7.5 4.5 H12.5 V6.5 M1.5 12.5 L3.5 7 H14.5 L12.5 13.5 H2.5 A1 1 0 0 1 1.5 12.5 Z" />
|
||||
<ui:IconData x:Key="Icon.Forward" Stroke="M3 8 H13 M9 4 L13 8 L9 12" />
|
||||
<ui:IconData x:Key="Icon.Fullscreen" Stroke="M2 6 V2 H6 M10 2 H14 V6 M14 10 V14 H10 M6 14 H2 V10" />
|
||||
<ui:IconData x:Key="Icon.Gpu" Stroke="M5.0 3.5 H11.0 A1.5 1.5 0 0 1 12.5 5.0 V11.0 A1.5 1.5 0 0 1 11.0 12.5 H5.0 A1.5 1.5 0 0 1 3.5 11.0 V5.0 A1.5 1.5 0 0 1 5.0 3.5 Z M6.5 6 H9.5 A0.5 0.5 0 0 1 10 6.5 V9.5 A0.5 0.5 0 0 1 9.5 10 H6.5 A0.5 0.5 0 0 1 6 9.5 V6.5 A0.5 0.5 0 0 1 6.5 6 Z M6 1.5 V3.5 M10 1.5 V3.5 M6 12.5 V14.5 M10 12.5 V14.5 M1.5 6 H3.5 M1.5 10 H3.5 M12.5 6 H14.5 M12.5 10 H14.5" />
|
||||
<ui:IconData x:Key="Icon.Grip" Fill="M5 4 A1 1 0 1 0 7 4 A1 1 0 1 0 5 4 ZM9 4 A1 1 0 1 0 11 4 A1 1 0 1 0 9 4 ZM5 8 A1 1 0 1 0 7 8 A1 1 0 1 0 5 8 ZM9 8 A1 1 0 1 0 11 8 A1 1 0 1 0 9 8 ZM5 12 A1 1 0 1 0 7 12 A1 1 0 1 0 5 12 ZM9 12 A1 1 0 1 0 11 12 A1 1 0 1 0 9 12 Z" />
|
||||
<ui:IconData x:Key="Icon.HalfDot" Stroke="M4.5 8 A3.5 3.5 0 1 0 11.5 8 A3.5 3.5 0 1 0 4.5 8 Z" Fill="M8 4.5 A3.5 3.5 0 0 1 8 11.5 Z" />
|
||||
<ui:IconData x:Key="Icon.Hero" Stroke="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z" Fill="M8 4.8 L8.9 6.9 L11.1 7.1 L9.4 8.5 L9.9 10.7 L8 9.5 L6.1 10.7 L6.6 8.5 L4.9 7.1 L7.1 6.9 Z" />
|
||||
<ui:IconData x:Key="Icon.Image" Stroke="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M1.5 11 L5.5 7 L9 10.5 L11 8.5 L14.5 12" Fill="M9.600000000000001 5.6 A1.2 1.2 0 1 0 12.0 5.6 A1.2 1.2 0 1 0 9.600000000000001 5.6 Z" />
|
||||
<ui:IconData x:Key="Icon.Import" Stroke="M8 2V10 M4.5 6.5 L8 10 L11.5 6.5 M2.5 13.5 H13.5" />
|
||||
<ui:IconData x:Key="Icon.Info" Stroke="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M8 7 V11 M8 4.8 V5.2" />
|
||||
<ui:IconData x:Key="Icon.Jobs" Stroke="M3 8 H13 M3 4 H13 M3 12 H9" />
|
||||
<ui:IconData x:Key="Icon.Key" Stroke="M2 10.5 A3 3 0 1 0 8 10.5 A3 3 0 1 0 2 10.5 Z M7.2 8.3 L13.5 2 M11.5 4 L13 5.5 M9.8 5.7 L11 6.9" />
|
||||
<ui:IconData x:Key="Icon.Keyframe" Stroke="M8 2 L13 8 L8 14 L3 8 Z" />
|
||||
<ui:IconData x:Key="Icon.Layers" Stroke="M8 1.8 L14.5 5.2 L8 8.6 L1.5 5.2 Z M1.5 8.2 L8 11.6 L14.5 8.2 M1.5 11 L8 14.4 L14.5 11" />
|
||||
<ui:IconData x:Key="Icon.Library" Stroke="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" />
|
||||
<ui:IconData x:Key="Icon.Link" Stroke="M6.8 9.2 L9.2 6.8 M7.5 4.5 L9 3 A2.8 2.8 0 0 1 13 7 L11.5 8.5 M8.5 11.5 L7 13 A2.8 2.8 0 0 1 3 9 L4.5 7.5" />
|
||||
<ui:IconData x:Key="Icon.Lock" Stroke="M4.5 7 H11.5 A1.5 1.5 0 0 1 13 8.5 V13.0 A1.5 1.5 0 0 1 11.5 14.5 H4.5 A1.5 1.5 0 0 1 3 13.0 V8.5 A1.5 1.5 0 0 1 4.5 7 Z M5.5 7 V5 A2.5 2.5 0 0 1 10.5 5 V7" />
|
||||
<ui:IconData x:Key="Icon.Logs" Stroke="M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5" />
|
||||
<ui:IconData x:Key="Icon.Menu" Stroke="M2.5 4 H13.5 M2.5 8 H13.5 M2.5 12 H13.5" />
|
||||
<ui:IconData x:Key="Icon.Minus" Stroke="M3 8 H13" />
|
||||
<ui:IconData x:Key="Icon.Moon" Stroke="M9.5 1.8 A6.5 6.5 0 1 0 14.2 11.2 A5.5 5.5 0 0 1 9.5 1.8 Z" />
|
||||
<ui:IconData x:Key="Icon.More" Fill="M2.4 8 A1.1 1.1 0 1 0 4.6 8 A1.1 1.1 0 1 0 2.4 8 ZM6.9 8 A1.1 1.1 0 1 0 9.1 8 A1.1 1.1 0 1 0 6.9 8 ZM11.4 8 A1.1 1.1 0 1 0 13.6 8 A1.1 1.1 0 1 0 11.4 8 Z" />
|
||||
<ui:IconData x:Key="Icon.Motion" Stroke="M1.5 8 C3.5 3 5.5 3 7.5 8 C9.5 13 11.5 13 14.5 8" />
|
||||
<ui:IconData x:Key="Icon.Network" Stroke="M2 6 A8.5 8.5 0 0 1 14 6 M4 8.5 A5.5 5.5 0 0 1 12 8.5 M6 11 A2.6 2.6 0 0 1 10 11" Fill="M6.9 13 A1.1 1.1 0 1 0 9.1 13 A1.1 1.1 0 1 0 6.9 13 Z" />
|
||||
<ui:IconData x:Key="Icon.Optimise" Stroke="M7 2 L8.2 5.8 L12 7 L8.2 8.2 L7 12 L5.8 8.2 L2 7 L5.8 5.8 Z M12.5 10.5 L13 12 L14.5 12.5 L13 13 L12.5 14.5 L12 13 L10.5 12.5 L12 12 Z" />
|
||||
<ui:IconData x:Key="Icon.Pause" Fill="M4.8 3 H5.8 A0.8 0.8 0 0 1 6.6 3.8 V12.2 A0.8 0.8 0 0 1 5.8 13 H4.8 A0.8 0.8 0 0 1 4 12.2 V3.8 A0.8 0.8 0 0 1 4.8 3 ZM10.200000000000001 3 H11.2 A0.8 0.8 0 0 1 12.0 3.8 V12.2 A0.8 0.8 0 0 1 11.2 13 H10.200000000000001 A0.8 0.8 0 0 1 9.4 12.2 V3.8 A0.8 0.8 0 0 1 10.200000000000001 3 Z" />
|
||||
<ui:IconData x:Key="Icon.Play" Fill="M4.5 2.8 L13 8 L4.5 13.2 Z" />
|
||||
<ui:IconData x:Key="Icon.Plus" Stroke="M8 3 V13 M3 8 H13" />
|
||||
<ui:IconData x:Key="Icon.Power" Stroke="M8 1.8 V7.5 M11.54 4.59 A5.5 5.5 0 1 1 4.46 4.59" />
|
||||
<ui:IconData x:Key="Icon.Refresh" Stroke="M10.75 3.24 A5.5 5.5 0 1 1 4.46 3.79 M13.2 2.6 L13.2 5.3 L10.5 5.3" />
|
||||
<ui:IconData x:Key="Icon.Regions" Stroke="M1.5 9.5 C4 8 6 10.5 8.5 9 C10.5 7.8 12.5 8.5 14.5 9.5 M1.5 13.5 H14.5 M1.5 2.5 H14.5" />
|
||||
<ui:IconData x:Key="Icon.Render" Stroke="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z" Fill="M6.5 5.5 L10.8 8 L6.5 10.5 Z" />
|
||||
<ui:IconData x:Key="Icon.Reset" Stroke="M3.67 6.00 A5 5 0 1 1 5.50 12.83 M3.2 3.2 V6.2 H6.2" />
|
||||
<ui:IconData x:Key="Icon.Retry" Stroke="M10.75 3.24 A5.5 5.5 0 1 1 4.46 3.79 M13.2 2.6 L13.2 5.3 L10.5 5.3" />
|
||||
<ui:IconData x:Key="Icon.Ring" Stroke="M4.5 8 A3.5 3.5 0 1 0 11.5 8 A3.5 3.5 0 1 0 4.5 8 Z" />
|
||||
<ui:IconData x:Key="Icon.Search" Stroke="M2.5 7 A4.5 4.5 0 1 0 11.5 7 A4.5 4.5 0 1 0 2.5 7 Z M10.4 10.4 L14 14" />
|
||||
<ui:IconData x:Key="Icon.Sequence" Stroke="M2 12.5 L11.5 3 L13 4.5 L3.5 14 H2 Z" />
|
||||
<ui:IconData x:Key="Icon.Server" Stroke="M4.5 12.5 A3 3 0 0 1 4.2 6.5 A4 4 0 0 1 11.9 5.5 A3.5 3.5 0 0 1 12.2 12.5 Z" />
|
||||
<ui:IconData x:Key="Icon.Settings" Stroke="M5.8 8 A2.2 2.2 0 1 0 10.2 8 A2.2 2.2 0 1 0 5.8 8 Z M8 1.5 V3.5 M8 12.5 V14.5 M1.5 8 H3.5 M12.5 8 H14.5 M3.4 3.4 L4.8 4.8 M11.2 11.2 L12.6 12.6 M3.4 12.6 L4.8 11.2 M11.2 4.8 L12.6 3.4" />
|
||||
<ui:IconData x:Key="Icon.Sort" Stroke="M5 2.5 V13.5 M2.5 11 L5 13.5 L7.5 11 M11 13.5 V2.5 M8.5 5 L11 2.5 L13.5 5" />
|
||||
<ui:IconData x:Key="Icon.Spline" Stroke="M2 13 C5 13 5 3 8 8 C11 13 11 3 14 3" Fill="M0.8 13 A1.2 1.2 0 1 0 3.2 13 A1.2 1.2 0 1 0 0.8 13 ZM12.8 3 A1.2 1.2 0 1 0 15.2 3 A1.2 1.2 0 1 0 12.8 3 Z" />
|
||||
<ui:IconData x:Key="Icon.Stack" Stroke="M8 1.8 L14.5 5.2 L8 8.6 L1.5 5.2 Z M1.5 8.2 L8 11.6 L14.5 8.2 M1.5 11 L8 14.4 L14.5 11" />
|
||||
<ui:IconData x:Key="Icon.Star" Stroke="M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z" />
|
||||
<ui:IconData x:Key="Icon.StarFilled" Fill="M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z" />
|
||||
<ui:IconData x:Key="Icon.Stop" Fill="M5.0 3.5 H11.0 A1.5 1.5 0 0 1 12.5 5.0 V11.0 A1.5 1.5 0 0 1 11.0 12.5 H5.0 A1.5 1.5 0 0 1 3.5 11.0 V5.0 A1.5 1.5 0 0 1 5.0 3.5 Z" />
|
||||
<ui:IconData x:Key="Icon.SuccessCircle" Stroke="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M5 8.3 L7.1 10.3 L11 6" />
|
||||
<ui:IconData x:Key="Icon.Sun" Stroke="M5 8 A3 3 0 1 0 11 8 A3 3 0 1 0 5 8 Z M8 1 V2.5 M8 13.5 V15 M1 8 H2.5 M13.5 8 H15 M3 3 L4 4 M12 12 L13 13 M3 13 L4 12 M12 4 L13 3" />
|
||||
<ui:IconData x:Key="Icon.Sync" Stroke="M9.88 2.83 A5.5 5.5 0 0 1 9.88 13.17 M6.12 13.17 A5.5 5.5 0 0 1 6.12 2.83 M13.5 6.5 L13.2 9.4 L10.6 8.4 M2.5 9.5 L2.8 6.6 L5.4 7.6" />
|
||||
<ui:IconData x:Key="Icon.Tag" Stroke="M1.5 2.5 A1 1 0 0 1 2.5 1.5 H7.5 L14.5 8.5 L8.5 14.5 L1.5 7.5 Z M5 5 H5.1" />
|
||||
<ui:IconData x:Key="Icon.Time" Stroke="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M8 4.5 V8 L10.5 9.5" />
|
||||
<ui:IconData x:Key="Icon.Tray" Stroke="M1.5 9.5 H5 L6.5 11.5 H9.5 L11 9.5 H14.5 M1.5 9.5 L3.5 3 H12.5 L14.5 9.5 V13.5 H1.5 Z" />
|
||||
<ui:IconData x:Key="Icon.Triangle" Fill="M8 3 L13.5 12.5 H2.5 Z" />
|
||||
<ui:IconData x:Key="Icon.TriangleRight" Fill="M5 3 L12 8 L5 13 Z" />
|
||||
<ui:IconData x:Key="Icon.Upload" Stroke="M8 10.5 V2.5 M4.5 6 L8 2.5 L11.5 6 M2.5 13.5 H13.5" />
|
||||
<ui:IconData x:Key="Icon.User" Stroke="M5 5 A3 3 0 1 0 11 5 A3 3 0 1 0 5 5 Z M2.5 14 A5.5 5.5 0 0 1 13.5 14" />
|
||||
<ui:IconData x:Key="Icon.Users" Stroke="M5 5 A3 3 0 1 0 11 5 A3 3 0 1 0 5 5 Z M2.5 14 A5.5 5.5 0 0 1 13.5 14" />
|
||||
<ui:IconData x:Key="Icon.Vectors" Stroke="M2.5 12.5 L7 8 M7 8 H4.5 M7 8 V10.5 M9 7 L13.5 2.5 M13.5 2.5 H11 M13.5 2.5 V5" />
|
||||
<ui:IconData x:Key="Icon.Verify" Stroke="M8 1.5 L13.5 3.5 V7.5 C13.5 11 11 13.3 8 14.5 C5 13.3 2.5 11 2.5 7.5 V3.5 Z M5.5 8 L7.3 9.8 L10.6 6.3" />
|
||||
<ui:IconData x:Key="Icon.ViewGrid" Stroke="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" />
|
||||
<ui:IconData x:Key="Icon.ViewList" Stroke="M5.5 4 H13.5 M5.5 8 H13.5 M5.5 12 H13.5 M2.5 4 H2.6 M2.5 8 H2.6 M2.5 12 H2.6" />
|
||||
<ui:IconData x:Key="Icon.ViewTimeline" Stroke="M2 13.5 H14 M3.5 11 V8 M6 11 V5 M8.5 11 V7 M11 11 V3.5 M13.5 11 V9" />
|
||||
<ui:IconData x:Key="Icon.Warning" Stroke="M8 1.8 L14.8 13.8 H1.2 Z M8 6.2 V9.6 M8 11.7 V11.8" />
|
||||
<ui:IconData x:Key="Icon.Window" Stroke="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M1.5 5.5 H14.5" />
|
||||
<ui:IconData x:Key="Icon.Wipe" Stroke="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M8 1 V15" />
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Ui.Interop;
|
||||
|
||||
/// <summary>The few Win32/DWM calls the shared UI needs (window chrome and theme).</summary>
|
||||
internal static partial class NativeMethods
|
||||
{
|
||||
public const int WM_NCHITTEST = 0x0084;
|
||||
public const int WM_NCMOUSEMOVE = 0x00A0;
|
||||
public const int WM_NCLBUTTONDOWN = 0x00A1;
|
||||
public const int WM_NCLBUTTONUP = 0x00A2;
|
||||
public const int WM_NCMOUSELEAVE = 0x02A2;
|
||||
public const int WM_GETMINMAXINFO = 0x0024;
|
||||
public const int HTMAXBUTTON = 9;
|
||||
|
||||
public const int DWMWA_USE_IMMERSIVE_DARK_MODE_OLD = 19;
|
||||
public const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
|
||||
public const int DWMWA_WINDOW_CORNER_PREFERENCE = 33;
|
||||
public const int DWMWA_BORDER_COLOR = 34;
|
||||
public const int DWMWA_CAPTION_COLOR = 35;
|
||||
|
||||
[LibraryImport("dwmapi.dll")]
|
||||
public static partial int DwmSetWindowAttribute(IntPtr hwnd, int attribute, ref int value, int size);
|
||||
|
||||
/// <summary>Sets a 32-bit DWM attribute; false when the OS does not support it.</summary>
|
||||
public static bool TrySetDwm(IntPtr hwnd, int attribute, int value)
|
||||
{
|
||||
if (hwnd == IntPtr.Zero || !OperatingSystem.IsWindows()) return false;
|
||||
try
|
||||
{
|
||||
return DwmSetWindowAttribute(hwnd, attribute, ref value, sizeof(int)) == 0;
|
||||
}
|
||||
catch (DllNotFoundException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (EntryPointNotFoundException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>COLORREF (0x00BBGGRR) from RGB bytes.</summary>
|
||||
public static int ColorRef(byte r, byte g, byte b) => r | g << 8 | b << 16;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System.ComponentModel;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Markup;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.Ui.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// XAML access to the string catalog: <c>Text="{l:Loc Library.Filter.Year}"</c>. The value is a binding, so
|
||||
/// changing <see cref="Loc.SetCulture"/> updates the whole UI without restart (BRIEF §16).
|
||||
/// </summary>
|
||||
[MarkupExtensionReturnType(typeof(string))]
|
||||
public sealed class LocExtension : MarkupExtension
|
||||
{
|
||||
public LocExtension()
|
||||
{
|
||||
}
|
||||
|
||||
public LocExtension(string key) => Key = key;
|
||||
|
||||
[ConstructorArgument("key")]
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Optional format applied to the localized string (e.g. "{0}…").</summary>
|
||||
public string? StringFormat { get; set; }
|
||||
|
||||
public override object ProvideValue(IServiceProvider serviceProvider)
|
||||
{
|
||||
var binding = new Binding("[" + Key + "]")
|
||||
{
|
||||
Source = LocSource.Instance,
|
||||
Mode = BindingMode.OneWay,
|
||||
StringFormat = StringFormat,
|
||||
};
|
||||
return binding.ProvideValue(serviceProvider);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Indexer source for <see cref="LocExtension"/> bindings; raises a refresh on culture change.</summary>
|
||||
public sealed class LocSource : INotifyPropertyChanged
|
||||
{
|
||||
private LocSource() => Loc.CultureChanged += (_, _) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
|
||||
|
||||
public static LocSource Instance { get; } = new();
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
public string this[string key] => Loc.L(key);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.Ui.Mvvm;
|
||||
|
||||
/// <summary>Minimal INotifyPropertyChanged base.</summary>
|
||||
public abstract class ObservableObject : INotifyPropertyChanged
|
||||
{
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
protected bool Set<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
|
||||
{
|
||||
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
|
||||
field = value;
|
||||
OnPropertyChanged(propertyName);
|
||||
return true;
|
||||
}
|
||||
|
||||
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) =>
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
||||
|
||||
/// <summary>Signals that every property changed (used after a culture switch).</summary>
|
||||
protected void OnAllPropertiesChanged() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty));
|
||||
}
|
||||
|
||||
/// <summary>View model whose computed, localized texts refresh when the UI language changes.</summary>
|
||||
public abstract class LocalizedViewModel : ObservableObject, IDisposable
|
||||
{
|
||||
protected LocalizedViewModel() => Loc.CultureChanged += OnCultureChanged;
|
||||
|
||||
public virtual void Dispose()
|
||||
{
|
||||
Loc.CultureChanged -= OnCultureChanged;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private void OnCultureChanged(object? sender, EventArgs e) => OnAllPropertiesChanged();
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace Titano.Ui.Mvvm;
|
||||
|
||||
/// <summary>Synchronous command with optional can-execute predicate.</summary>
|
||||
public sealed class RelayCommand(Action<object?> execute, Func<object?, bool>? canExecute = null) : ICommand
|
||||
{
|
||||
public RelayCommand(Action execute, Func<bool>? canExecute = null)
|
||||
: this(_ => execute(), canExecute is null ? null : _ => canExecute())
|
||||
{
|
||||
}
|
||||
|
||||
public event EventHandler? CanExecuteChanged
|
||||
{
|
||||
add => CommandManager.RequerySuggested += value;
|
||||
remove => CommandManager.RequerySuggested -= value;
|
||||
}
|
||||
|
||||
public bool CanExecute(object? parameter) => canExecute?.Invoke(parameter) ?? true;
|
||||
|
||||
public void Execute(object? parameter) => execute(parameter);
|
||||
}
|
||||
|
||||
/// <summary>Asynchronous command that disables itself while running and reports failures through <see cref="Failed"/>.</summary>
|
||||
public sealed class AsyncRelayCommand(Func<object?, CancellationToken, Task> execute, Func<object?, bool>? canExecute = null) : ICommand
|
||||
{
|
||||
private CancellationTokenSource? _cts;
|
||||
|
||||
public AsyncRelayCommand(Func<Task> execute, Func<bool>? canExecute = null)
|
||||
: this((_, _) => execute(), canExecute is null ? null : _ => canExecute())
|
||||
{
|
||||
}
|
||||
|
||||
public event EventHandler? CanExecuteChanged;
|
||||
|
||||
/// <summary>Raised on the UI thread when the command throws (other than cancellation).</summary>
|
||||
public static event Action<Exception>? Failed;
|
||||
|
||||
public bool IsRunning => _cts is not null;
|
||||
|
||||
public bool CanExecute(object? parameter) => !IsRunning && (canExecute?.Invoke(parameter) ?? true);
|
||||
|
||||
public async void Execute(object? parameter)
|
||||
{
|
||||
if (!CanExecute(parameter)) return;
|
||||
_cts = new CancellationTokenSource();
|
||||
RaiseCanExecuteChanged();
|
||||
try
|
||||
{
|
||||
await execute(parameter, _cts.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Failed?.Invoke(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_cts.Dispose();
|
||||
_cts = null;
|
||||
RaiseCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public void Cancel() => _cts?.Cancel();
|
||||
|
||||
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,70 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
|
||||
<!-- DESIGN.md §1 tokens, Dark theme. Colours are referenced through DynamicResource so the theme can switch at run time. -->
|
||||
<Color x:Key="Color.Bg">#1F1F23</Color>
|
||||
<Color x:Key="Color.Chrome">#1A1A1E</Color>
|
||||
<Color x:Key="Color.Surface">#26262C</Color>
|
||||
<Color x:Key="Color.Card">#2F3038</Color>
|
||||
<Color x:Key="Color.CardHover">#383943</Color>
|
||||
<Color x:Key="Color.CardPressed">#2A2B32</Color>
|
||||
<Color x:Key="Color.Stroke">#3E404A</Color>
|
||||
<Color x:Key="Color.StrokeStrong">#535663</Color>
|
||||
<Color x:Key="Color.Text">#F2F3F5</Color>
|
||||
<Color x:Key="Color.TextMuted">#A9AEB9</Color>
|
||||
<Color x:Key="Color.TextFaint">#7B818E</Color>
|
||||
<Color x:Key="Color.Accent">#4CC2FF</Color>
|
||||
<Color x:Key="Color.AccentHover">#6FCFFF</Color>
|
||||
<Color x:Key="Color.AccentPressed">#3BA9E0</Color>
|
||||
<Color x:Key="Color.OnAccent">#0B1B24</Color>
|
||||
<Color x:Key="Color.AccentSelected">#404CC2FF</Color>
|
||||
<Color x:Key="Color.AccentSubtle">#1F4CC2FF</Color>
|
||||
<Color x:Key="Color.Sun">#F5A524</Color>
|
||||
<Color x:Key="Color.Success">#35C48F</Color>
|
||||
<Color x:Key="Color.Warning">#E8B339</Color>
|
||||
<Color x:Key="Color.Error">#F0625D</Color>
|
||||
<Color x:Key="Color.Region">#5AD1C8</Color>
|
||||
<Color x:Key="Color.ToolTip">#F2F3F5</Color>
|
||||
<Color x:Key="Color.OnToolTip">#1A1A1A</Color>
|
||||
<Color x:Key="Color.Scrim">#99000000</Color>
|
||||
<Color x:Key="Color.Track">#3E404A</Color>
|
||||
<Color x:Key="Color.Preview">#141417</Color>
|
||||
<Color x:Key="Color.WarningSubtle">#1FE8B339</Color>
|
||||
<Color x:Key="Color.ErrorSubtle">#1FF0625D</Color>
|
||||
<Color x:Key="Color.SuccessSubtle">#1F35C48F</Color>
|
||||
<Color x:Key="Color.SunSubtle">#26F5A524</Color>
|
||||
<Color x:Key="Color.CaptionCloseHover">#C42B1C</Color>
|
||||
<Color x:Key="Color.Shadow">#66000000</Color>
|
||||
<SolidColorBrush x:Key="Brush.Bg" Color="{StaticResource Color.Bg}" />
|
||||
<SolidColorBrush x:Key="Brush.Chrome" Color="{StaticResource Color.Chrome}" />
|
||||
<SolidColorBrush x:Key="Brush.Surface" Color="{StaticResource Color.Surface}" />
|
||||
<SolidColorBrush x:Key="Brush.Card" Color="{StaticResource Color.Card}" />
|
||||
<SolidColorBrush x:Key="Brush.CardHover" Color="{StaticResource Color.CardHover}" />
|
||||
<SolidColorBrush x:Key="Brush.CardPressed" Color="{StaticResource Color.CardPressed}" />
|
||||
<SolidColorBrush x:Key="Brush.Stroke" Color="{StaticResource Color.Stroke}" />
|
||||
<SolidColorBrush x:Key="Brush.StrokeStrong" Color="{StaticResource Color.StrokeStrong}" />
|
||||
<SolidColorBrush x:Key="Brush.Text" Color="{StaticResource Color.Text}" />
|
||||
<SolidColorBrush x:Key="Brush.TextMuted" Color="{StaticResource Color.TextMuted}" />
|
||||
<SolidColorBrush x:Key="Brush.TextFaint" Color="{StaticResource Color.TextFaint}" />
|
||||
<SolidColorBrush x:Key="Brush.Accent" Color="{StaticResource Color.Accent}" />
|
||||
<SolidColorBrush x:Key="Brush.AccentHover" Color="{StaticResource Color.AccentHover}" />
|
||||
<SolidColorBrush x:Key="Brush.AccentPressed" Color="{StaticResource Color.AccentPressed}" />
|
||||
<SolidColorBrush x:Key="Brush.OnAccent" Color="{StaticResource Color.OnAccent}" />
|
||||
<SolidColorBrush x:Key="Brush.AccentSelected" Color="{StaticResource Color.AccentSelected}" />
|
||||
<SolidColorBrush x:Key="Brush.AccentSubtle" Color="{StaticResource Color.AccentSubtle}" />
|
||||
<SolidColorBrush x:Key="Brush.Sun" Color="{StaticResource Color.Sun}" />
|
||||
<SolidColorBrush x:Key="Brush.Success" Color="{StaticResource Color.Success}" />
|
||||
<SolidColorBrush x:Key="Brush.Warning" Color="{StaticResource Color.Warning}" />
|
||||
<SolidColorBrush x:Key="Brush.Error" Color="{StaticResource Color.Error}" />
|
||||
<SolidColorBrush x:Key="Brush.Region" Color="{StaticResource Color.Region}" />
|
||||
<SolidColorBrush x:Key="Brush.ToolTip" Color="{StaticResource Color.ToolTip}" />
|
||||
<SolidColorBrush x:Key="Brush.OnToolTip" Color="{StaticResource Color.OnToolTip}" />
|
||||
<SolidColorBrush x:Key="Brush.Scrim" Color="{StaticResource Color.Scrim}" />
|
||||
<SolidColorBrush x:Key="Brush.Track" Color="{StaticResource Color.Track}" />
|
||||
<SolidColorBrush x:Key="Brush.Preview" Color="{StaticResource Color.Preview}" />
|
||||
<SolidColorBrush x:Key="Brush.WarningSubtle" Color="{StaticResource Color.WarningSubtle}" />
|
||||
<SolidColorBrush x:Key="Brush.ErrorSubtle" Color="{StaticResource Color.ErrorSubtle}" />
|
||||
<SolidColorBrush x:Key="Brush.SuccessSubtle" Color="{StaticResource Color.SuccessSubtle}" />
|
||||
<SolidColorBrush x:Key="Brush.SunSubtle" Color="{StaticResource Color.SunSubtle}" />
|
||||
<SolidColorBrush x:Key="Brush.CaptionCloseHover" Color="{StaticResource Color.CaptionCloseHover}" />
|
||||
<SolidColorBrush x:Key="Brush.Shadow" Color="{StaticResource Color.Shadow}" />
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,70 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
|
||||
<!-- DESIGN.md §1 tokens, Light theme. Colours are referenced through DynamicResource so the theme can switch at run time. -->
|
||||
<Color x:Key="Color.Bg">#F3F3F3</Color>
|
||||
<Color x:Key="Color.Chrome">#FFFFFF</Color>
|
||||
<Color x:Key="Color.Surface">#FFFFFF</Color>
|
||||
<Color x:Key="Color.Card">#FFFFFF</Color>
|
||||
<Color x:Key="Color.CardHover">#F5F5F5</Color>
|
||||
<Color x:Key="Color.CardPressed">#EBEBEB</Color>
|
||||
<Color x:Key="Color.Stroke">#E5E5E5</Color>
|
||||
<Color x:Key="Color.StrokeStrong">#D1D1D1</Color>
|
||||
<Color x:Key="Color.Text">#1A1A1A</Color>
|
||||
<Color x:Key="Color.TextMuted">#616161</Color>
|
||||
<Color x:Key="Color.TextFaint">#9E9E9E</Color>
|
||||
<Color x:Key="Color.Accent">#0067C0</Color>
|
||||
<Color x:Key="Color.AccentHover">#1975C5</Color>
|
||||
<Color x:Key="Color.AccentPressed">#005AA8</Color>
|
||||
<Color x:Key="Color.OnAccent">#FFFFFF</Color>
|
||||
<Color x:Key="Color.AccentSelected">#E8F1FA</Color>
|
||||
<Color x:Key="Color.AccentSubtle">#F0F6FC</Color>
|
||||
<Color x:Key="Color.Sun">#E08A1E</Color>
|
||||
<Color x:Key="Color.Success">#0F7B4F</Color>
|
||||
<Color x:Key="Color.Warning">#9A6700</Color>
|
||||
<Color x:Key="Color.Error">#C42B1C</Color>
|
||||
<Color x:Key="Color.Region">#1A9E95</Color>
|
||||
<Color x:Key="Color.ToolTip">#1A1A1A</Color>
|
||||
<Color x:Key="Color.OnToolTip">#F2F3F5</Color>
|
||||
<Color x:Key="Color.Scrim">#66000000</Color>
|
||||
<Color x:Key="Color.Track">#E0E0E0</Color>
|
||||
<Color x:Key="Color.Preview">#E9E9EC</Color>
|
||||
<Color x:Key="Color.WarningSubtle">#FFF4CE</Color>
|
||||
<Color x:Key="Color.ErrorSubtle">#FDE7E9</Color>
|
||||
<Color x:Key="Color.SuccessSubtle">#DFF6DD</Color>
|
||||
<Color x:Key="Color.SunSubtle">#FFF1DE</Color>
|
||||
<Color x:Key="Color.CaptionCloseHover">#C42B1C</Color>
|
||||
<Color x:Key="Color.Shadow">#33000000</Color>
|
||||
<SolidColorBrush x:Key="Brush.Bg" Color="{StaticResource Color.Bg}" />
|
||||
<SolidColorBrush x:Key="Brush.Chrome" Color="{StaticResource Color.Chrome}" />
|
||||
<SolidColorBrush x:Key="Brush.Surface" Color="{StaticResource Color.Surface}" />
|
||||
<SolidColorBrush x:Key="Brush.Card" Color="{StaticResource Color.Card}" />
|
||||
<SolidColorBrush x:Key="Brush.CardHover" Color="{StaticResource Color.CardHover}" />
|
||||
<SolidColorBrush x:Key="Brush.CardPressed" Color="{StaticResource Color.CardPressed}" />
|
||||
<SolidColorBrush x:Key="Brush.Stroke" Color="{StaticResource Color.Stroke}" />
|
||||
<SolidColorBrush x:Key="Brush.StrokeStrong" Color="{StaticResource Color.StrokeStrong}" />
|
||||
<SolidColorBrush x:Key="Brush.Text" Color="{StaticResource Color.Text}" />
|
||||
<SolidColorBrush x:Key="Brush.TextMuted" Color="{StaticResource Color.TextMuted}" />
|
||||
<SolidColorBrush x:Key="Brush.TextFaint" Color="{StaticResource Color.TextFaint}" />
|
||||
<SolidColorBrush x:Key="Brush.Accent" Color="{StaticResource Color.Accent}" />
|
||||
<SolidColorBrush x:Key="Brush.AccentHover" Color="{StaticResource Color.AccentHover}" />
|
||||
<SolidColorBrush x:Key="Brush.AccentPressed" Color="{StaticResource Color.AccentPressed}" />
|
||||
<SolidColorBrush x:Key="Brush.OnAccent" Color="{StaticResource Color.OnAccent}" />
|
||||
<SolidColorBrush x:Key="Brush.AccentSelected" Color="{StaticResource Color.AccentSelected}" />
|
||||
<SolidColorBrush x:Key="Brush.AccentSubtle" Color="{StaticResource Color.AccentSubtle}" />
|
||||
<SolidColorBrush x:Key="Brush.Sun" Color="{StaticResource Color.Sun}" />
|
||||
<SolidColorBrush x:Key="Brush.Success" Color="{StaticResource Color.Success}" />
|
||||
<SolidColorBrush x:Key="Brush.Warning" Color="{StaticResource Color.Warning}" />
|
||||
<SolidColorBrush x:Key="Brush.Error" Color="{StaticResource Color.Error}" />
|
||||
<SolidColorBrush x:Key="Brush.Region" Color="{StaticResource Color.Region}" />
|
||||
<SolidColorBrush x:Key="Brush.ToolTip" Color="{StaticResource Color.ToolTip}" />
|
||||
<SolidColorBrush x:Key="Brush.OnToolTip" Color="{StaticResource Color.OnToolTip}" />
|
||||
<SolidColorBrush x:Key="Brush.Scrim" Color="{StaticResource Color.Scrim}" />
|
||||
<SolidColorBrush x:Key="Brush.Track" Color="{StaticResource Color.Track}" />
|
||||
<SolidColorBrush x:Key="Brush.Preview" Color="{StaticResource Color.Preview}" />
|
||||
<SolidColorBrush x:Key="Brush.WarningSubtle" Color="{StaticResource Color.WarningSubtle}" />
|
||||
<SolidColorBrush x:Key="Brush.ErrorSubtle" Color="{StaticResource Color.ErrorSubtle}" />
|
||||
<SolidColorBrush x:Key="Brush.SuccessSubtle" Color="{StaticResource Color.SuccessSubtle}" />
|
||||
<SolidColorBrush x:Key="Brush.SunSubtle" Color="{StaticResource Color.SunSubtle}" />
|
||||
<SolidColorBrush x:Key="Brush.CaptionCloseHover" Color="{StaticResource Color.CaptionCloseHover}" />
|
||||
<SolidColorBrush x:Key="Brush.Shadow" Color="{StaticResource Color.Shadow}" />
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,85 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:sys="clr-namespace:System;assembly=System.Runtime">
|
||||
<!-- DESIGN.md §2–3: one typeface, six sizes, 4-px spacing scale, fixed radii and sizes. -->
|
||||
<FontFamily x:Key="Font.Ui">Segoe UI Variable Text, Segoe UI, Microsoft YaHei UI, Yu Gothic UI, Malgun Gothic, Leelawadee UI, Nirmala UI, Tahoma</FontFamily>
|
||||
<FontFamily x:Key="Font.Display">Segoe UI Variable Display, Segoe UI, Microsoft YaHei UI, Yu Gothic UI, Malgun Gothic</FontFamily>
|
||||
<FontFamily x:Key="Font.Mono">Cascadia Mono, Consolas</FontFamily>
|
||||
|
||||
<sys:Double x:Key="Size.PageTitle">18</sys:Double>
|
||||
<sys:Double x:Key="Size.Title">16</sys:Double>
|
||||
<sys:Double x:Key="Size.Section">14</sys:Double>
|
||||
<sys:Double x:Key="Size.Body">13</sys:Double>
|
||||
<sys:Double x:Key="Size.Secondary">12</sys:Double>
|
||||
<sys:Double x:Key="Size.Chip">11</sys:Double>
|
||||
|
||||
<Thickness x:Key="Space.1">4</Thickness>
|
||||
<Thickness x:Key="Space.2">8</Thickness>
|
||||
<Thickness x:Key="Space.3">12</Thickness>
|
||||
<Thickness x:Key="Space.4">16</Thickness>
|
||||
<Thickness x:Key="Space.5">20</Thickness>
|
||||
|
||||
<CornerRadius x:Key="Radius.Control">6</CornerRadius>
|
||||
<CornerRadius x:Key="Radius.Card">8</CornerRadius>
|
||||
<CornerRadius x:Key="Radius.Pill">12</CornerRadius>
|
||||
<CornerRadius x:Key="Radius.Dialog">12</CornerRadius>
|
||||
|
||||
<sys:Double x:Key="Height.Control">32</sys:Double>
|
||||
<sys:Double x:Key="Height.Compact">28</sys:Double>
|
||||
<sys:Double x:Key="Height.Row">38</sys:Double>
|
||||
<sys:Double x:Key="Height.TitleBar">34</sys:Double>
|
||||
<sys:Double x:Key="Height.JobBar">40</sys:Double>
|
||||
<sys:Double x:Key="Height.Toolbar">56</sys:Double>
|
||||
<sys:Double x:Key="Height.StatusBar">30</sys:Double>
|
||||
<sys:Double x:Key="Width.Rail">128</sys:Double>
|
||||
<sys:Double x:Key="Width.RailCollapsed">48</sys:Double>
|
||||
<sys:Double x:Key="Width.SidePanel">320</sys:Double>
|
||||
<sys:Double x:Key="Width.SettingsList">200</sys:Double>
|
||||
<GridLength x:Key="Grid.LabelColumn">116</GridLength>
|
||||
<GridLength x:Key="Grid.SettingsLabelColumn">180</GridLength>
|
||||
|
||||
<Style x:Key="Text.Base" TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="{StaticResource Font.Ui}" />
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.Body}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
</Style>
|
||||
<Style x:Key="Text.PageTitle" TargetType="TextBlock" BasedOn="{StaticResource Text.Base}">
|
||||
<Setter Property="FontFamily" Value="{StaticResource Font.Display}" />
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.PageTitle}" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="LineHeight" Value="24" />
|
||||
</Style>
|
||||
<Style x:Key="Text.Title" TargetType="TextBlock" BasedOn="{StaticResource Text.Base}">
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.Title}" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="LineHeight" Value="22" />
|
||||
</Style>
|
||||
<Style x:Key="Text.Section" TargetType="TextBlock" BasedOn="{StaticResource Text.Base}">
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.Section}" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="LineHeight" Value="20" />
|
||||
</Style>
|
||||
<Style x:Key="Text.Body" TargetType="TextBlock" BasedOn="{StaticResource Text.Base}" />
|
||||
<Style x:Key="Text.Secondary" TargetType="TextBlock" BasedOn="{StaticResource Text.Base}">
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.Secondary}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
</Style>
|
||||
<Style x:Key="Text.Faint" TargetType="TextBlock" BasedOn="{StaticResource Text.Base}">
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.Chip}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextFaint}" />
|
||||
</Style>
|
||||
<Style x:Key="Text.Chip" TargetType="TextBlock" BasedOn="{StaticResource Text.Base}">
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.Chip}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
</Style>
|
||||
<Style x:Key="Text.ColumnHeader" TargetType="TextBlock" BasedOn="{StaticResource Text.Faint}">
|
||||
<Setter Property="FontSize" Value="11" />
|
||||
</Style>
|
||||
<!-- Tabular numbers for tables and counters (DESIGN §2). -->
|
||||
<Style x:Key="Text.Number" TargetType="TextBlock" BasedOn="{StaticResource Text.Base}">
|
||||
<Setter Property="Typography.NumeralAlignment" Value="Tabular" />
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,112 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Media;
|
||||
using Microsoft.Win32;
|
||||
using Titano.Ui.Interop;
|
||||
|
||||
namespace Titano.Ui.Theming;
|
||||
|
||||
public enum AppTheme
|
||||
{
|
||||
System,
|
||||
Dark,
|
||||
Light,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the Titano design system into an application and switches between the dark and light token sets
|
||||
/// at run time (DESIGN.md §1: dark is the client default, light follows the OS when System is chosen).
|
||||
/// </summary>
|
||||
public static class ThemeManager
|
||||
{
|
||||
private const string Base = "pack://application:,,,/Titano.Ui;component/";
|
||||
private static ResourceDictionary? _tokens;
|
||||
private static Application? _app;
|
||||
private static bool _initialized;
|
||||
|
||||
public static AppTheme Requested { get; private set; } = AppTheme.Dark;
|
||||
|
||||
public static bool IsDark { get; private set; }
|
||||
|
||||
public static event EventHandler? Changed;
|
||||
|
||||
/// <summary>Merges typography, tokens, icons and control styles into <paramref name="app"/>.</summary>
|
||||
public static void Initialize(Application app, AppTheme theme)
|
||||
{
|
||||
_app = app;
|
||||
var merged = app.Resources.MergedDictionaries;
|
||||
// Controls.xaml merges Typography.xaml and Icons.xaml itself so its StaticResources resolve at load.
|
||||
_tokens = Load(TokensFor(Resolve(theme)));
|
||||
merged.Insert(0, _tokens);
|
||||
merged.Insert(1, Load("Themes/Controls.xaml"));
|
||||
|
||||
ToolTipService.InitialShowDelayProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(400));
|
||||
ToolTipService.BetweenShowDelayProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(100));
|
||||
ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(20000));
|
||||
|
||||
SystemEvents.UserPreferenceChanged += (_, e) =>
|
||||
{
|
||||
if (e.Category == UserPreferenceCategory.General && Requested == AppTheme.System)
|
||||
app.Dispatcher.BeginInvoke(() => Apply(AppTheme.System));
|
||||
};
|
||||
Apply(theme);
|
||||
}
|
||||
|
||||
public static void Apply(AppTheme theme)
|
||||
{
|
||||
if (_app is null || _tokens is null) throw new InvalidOperationException("ThemeManager.Initialize first.");
|
||||
Requested = theme;
|
||||
var dark = Resolve(theme);
|
||||
if (dark != IsDark || !_initialized)
|
||||
{
|
||||
var merged = _app.Resources.MergedDictionaries;
|
||||
var index = merged.IndexOf(_tokens);
|
||||
_tokens = Load(TokensFor(dark));
|
||||
merged[index] = _tokens;
|
||||
IsDark = dark;
|
||||
_initialized = true;
|
||||
}
|
||||
foreach (Window w in _app.Windows) ApplyChrome(w);
|
||||
Changed?.Invoke(null, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>True when Windows apps are set to dark mode.</summary>
|
||||
public static bool SystemPrefersDark()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize");
|
||||
return key?.GetValue("AppsUseLightTheme") is not int light || light == 0;
|
||||
}
|
||||
catch (System.Security.SecurityException)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Colours the DWM frame (border/caption) to match the current tokens.</summary>
|
||||
public static void ApplyChrome(Window window)
|
||||
{
|
||||
var hwnd = new WindowInteropHelper(window).Handle;
|
||||
if (hwnd == IntPtr.Zero) return;
|
||||
NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_USE_IMMERSIVE_DARK_MODE, IsDark ? 1 : 0);
|
||||
NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_USE_IMMERSIVE_DARK_MODE_OLD, IsDark ? 1 : 0);
|
||||
NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_WINDOW_CORNER_PREFERENCE, 2);
|
||||
if (_app?.TryFindResource("Color.Chrome") is Color chrome)
|
||||
NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_CAPTION_COLOR, NativeMethods.ColorRef(chrome.R, chrome.G, chrome.B));
|
||||
if (_app?.TryFindResource("Color.Stroke") is Color stroke)
|
||||
NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_BORDER_COLOR, NativeMethods.ColorRef(stroke.R, stroke.G, stroke.B));
|
||||
}
|
||||
|
||||
private static bool Resolve(AppTheme theme) => theme switch
|
||||
{
|
||||
AppTheme.Dark => true,
|
||||
AppTheme.Light => false,
|
||||
_ => SystemPrefersDark(),
|
||||
};
|
||||
|
||||
private static string TokensFor(bool dark) => dark ? "Themes/Tokens.Dark.xaml" : "Themes/Tokens.Light.xaml";
|
||||
|
||||
private static ResourceDictionary Load(string path) => new() { Source = new Uri(Base + path, UriKind.Absolute) };
|
||||
}
|
||||
Reference in new issue
Block a user