feat(app): library, jobs, settings, server, welcome and about screens

Local-mode composition root (SQLite index, one JobEngine fed by a single
handler registration list), keyset-paged library with thumbnail cache and
hover scrub, live job list with throttled updates and the shell job bar,
settings with live template validation and encoder self-test, server
connection with trust-on-first-use and DPAPI token, first-run welcome,
About with update check, and --capture screenshots with synthetic data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 12:26:58 +00:00
1 parent 446daeae2b
commit ffbea7cb74
94 files changed
+10130 -374

No files matched your search

+45 -16
View File
@@ -3,19 +3,21 @@
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">
<!-- BRIEF §12.9 (no mockup): built from the kit — panel, label column, one primary action. -->
<Grid Margin="20,16,20,20">
<Border Style="{StaticResource Border.Panel}" Padding="28,24" HorizontalAlignment="Left" VerticalAlignment="Top" MinWidth="560">
<Border Style="{StaticResource Border.Panel}" Padding="28,24" HorizontalAlignment="Left" VerticalAlignment="Top" MinWidth="600">
<StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,0,0,20">
<StackPanel Orientation="Horizontal" Margin="0,0,0,22">
<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" />
<TextBlock Text="{Binding Version}" Style="{StaticResource Text.Secondary}" Margin="0,2,0,0" Typography.NumeralAlignment="Tabular" />
</StackPanel>
</StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="140" />
<ColumnDefinition Width="Auto" MinWidth="140" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
@@ -23,20 +25,47 @@
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="Auto" />
<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}" />
<TextBlock Style="{StaticResource Text.Label}" Text="{l:Loc About.Build}" />
<TextBlock Grid.Column="1" Text="{Binding Build}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
<TextBlock Grid.Row="1" Style="{StaticResource Text.Label}" Text="{l:Loc About.Runtime}" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Runtime}" VerticalAlignment="Center" />
<TextBlock Grid.Row="2" Style="{StaticResource Text.Label}" Text="{l:Loc About.System}" />
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding OperatingSystem}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Row="3" Style="{StaticResource Text.Label}" Text="{l:Loc About.Licence}" />
<Button Grid.Row="3" Grid.Column="1" Style="{StaticResource Button.Link}" FontSize="13" HorizontalAlignment="Left" VerticalAlignment="Center"
Content="{l:Loc About.LicenceLink}" Command="{Binding OpenLicenceCommand}" ToolTip="{l:Loc Tooltips.About.Licence}" />
<TextBlock Grid.Row="4" Style="{StaticResource Text.Label}" Text="{l:Loc About.ThirdParty}" />
<TextBlock Grid.Row="4" Grid.Column="1" Text="{l:Loc About.ThirdPartyNone}" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.About.ThirdParty}" />
<TextBlock Grid.Row="5" Style="{StaticResource Text.Label}" Text="{l:Loc About.Data}" />
<TextBlock Grid.Row="5" Grid.Column="1" Text="{Binding DataFolder}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Row="6" Style="{StaticResource Text.Label}" Text="{l:Loc About.Translation}" Height="28"
Visibility="{Binding IsTranslated, Converter={StaticResource BoolToVisibility}}" />
<StackPanel Grid.Row="6" Grid.Column="1" Orientation="Horizontal" Height="28" Visibility="{Binding IsTranslated, Converter={StaticResource BoolToVisibility}}">
<TextBlock Text="{l:Loc About.MachineTranslated}" VerticalAlignment="Center" />
<Button Style="{StaticResource Button.Link}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center" Content="{l:Loc About.Review}"
Command="{Binding ReviewTranslationCommand}" ToolTip="{l:Loc Tooltips.About.Review}" />
</StackPanel>
<TextBlock Grid.Row="7" Style="{StaticResource Text.Label}" Text="{l:Loc About.Updates}" />
<StackPanel Grid.Row="7" Grid.Column="1" Orientation="Horizontal">
<ui:StatusGlyph Kind="{Binding UpdateKind}" Text="{Binding UpdateText}" FontSize="13" VerticalAlignment="Center"
Visibility="{Binding HasUpdateText, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Link}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center" Content="{l:Loc About.Update.Download}"
Command="{Binding DownloadCommand}" ToolTip="{l:Loc Tooltips.About.Download}"
Visibility="{Binding IsUpdateAvailable, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</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>
<WrapPanel Margin="0,22,0,0">
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc About.Update.Check}" Command="{Binding CheckCommand}" ToolTip="{l:Loc Tooltips.About.Check}" Margin="0,0,8,8" />
<Button Content="{l:Loc About.Releases}" Command="{Binding OpenReleasesCommand}" ToolTip="{l:Loc Tooltips.About.Releases}" ui:ButtonIcon.Glyph="{StaticResource Icon.ExternalLink}" Margin="0,0,8,8" />
<Button Content="{l:Loc About.Diagnostics}" Command="{Binding DiagnosticsCommand}" ToolTip="{l:Loc Tooltips.About.Diagnostics}" ui:ButtonIcon.Glyph="{StaticResource Icon.Export}" Margin="0,0,8,8" />
<Button Content="{l:Loc About.OpenData}" Command="{Binding OpenDataFolderCommand}" ToolTip="{l:Loc Tooltips.About.OpenData}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Margin="0,0,8,8" />
</WrapPanel>
</StackPanel>
</Border>
</Grid>
+149
View File
@@ -0,0 +1,149 @@
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Input;
using Titano.App.About;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
/// <summary>
/// About (BRIEF §12.9): version and build, licence link, third-party notice (none), translation notice,
/// diagnostics bundle and the update check against the public releases repository (BRIEF §18).
/// </summary>
public sealed class AboutViewModel : SectionViewModel
{
private ReleaseInfo? _release;
private UpdateState _state = UpdateState.Unknown;
public AboutViewModel(ShellViewModel shell)
: base(SectionKey.About, "Icon.About")
{
Shell = shell;
CheckCommand = new AsyncRelayCommand(() => CheckAsync(notify: false), () => _state != UpdateState.Checking);
DownloadCommand = new RelayCommand(() =>
{
if (_release is { } release) ShellActions.OpenUrl(release.PageUrl);
}, () => _release is not null);
OpenReleasesCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Releases));
OpenLicenceCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Licence));
ReviewTranslationCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Issues));
OpenDataFolderCommand = new RelayCommand(() => ShellActions.Reveal(DataFolder));
DiagnosticsCommand = new AsyncRelayCommand(DiagnosticsAsync);
}
private enum UpdateState
{
Unknown,
Checking,
UpToDate,
Available,
Failed,
}
public ShellViewModel Shell { get; }
public string Version => AppServices.VersionText;
/// <summary>File version and processor architecture.</summary>
public string Build =>
(typeof(App).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()?.Version ?? Version) + " · " + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant();
public string Runtime => RuntimeInformation.FrameworkDescription;
public string OperatingSystem => RuntimeInformation.OSDescription;
public string DataFolder => Shell.Services.Environment.DataDirectory;
/// <summary>Every language but English is machine-translated and open to review (BRIEF §16).</summary>
public bool IsTranslated => !Loc.Culture.TwoLetterISOLanguageName.Equals("en", StringComparison.OrdinalIgnoreCase);
public ICommand CheckCommand { get; }
public ICommand DownloadCommand { get; }
public ICommand OpenReleasesCommand { get; }
public ICommand OpenLicenceCommand { get; }
public ICommand ReviewTranslationCommand { get; }
public ICommand OpenDataFolderCommand { get; }
public ICommand DiagnosticsCommand { get; }
/// <summary>"Up to date", "Titano 0.2.0 available", …; null before the first check.</summary>
public string? UpdateText => _state switch
{
UpdateState.Checking => Loc.L("About.Update.Checking"),
UpdateState.UpToDate => Loc.L("About.Update.Current"),
UpdateState.Available when _release is { } r => Loc.L("About.Update.Available", UpdateCheck.Display(r.Version)),
UpdateState.Failed => Loc.L("About.Update.Failed"),
_ => null,
};
public StatusKind UpdateKind => _state switch
{
UpdateState.Checking => StatusKind.Running,
UpdateState.UpToDate => StatusKind.Done,
UpdateState.Available => StatusKind.Warning,
_ => StatusKind.Error,
};
public bool HasUpdateText => UpdateText is not null;
public bool IsUpdateAvailable => _state == UpdateState.Available;
/// <summary>Starts the update check on start when allowed (opt-out, BRIEF §18).</summary>
public void Attach()
{
if (Shell.Services.Settings.CheckForUpdates && !Shell.Services.Environment.IsCapture) _ = CheckAsync(notify: true);
}
/// <summary>Sets a result without the network (capture, tests).</summary>
internal void SetResult(ReleaseInfo? release, bool failed = false)
{
_release = release is not null && UpdateCheck.IsNewer(release, UpdateCheck.RunningVersion(Version)) ? release : null;
_state = failed ? UpdateState.Failed : _release is null ? UpdateState.UpToDate : UpdateState.Available;
RaiseUpdate();
}
private async Task CheckAsync(bool notify)
{
_state = UpdateState.Checking;
RaiseUpdate();
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var release = await Shell.Services.CheckForUpdateAsync(timeout.Token);
SetResult(release);
if (notify && _release is { } newer)
{
Shell.Notify(Loc.L("About.Update.Available", UpdateCheck.Display(newer.Version)), actionText: Loc.L("About.Update.Download"),
actionToolTip: Loc.L("Tooltips.About.Download"), action: () => ShellActions.OpenUrl(newer.PageUrl));
}
}
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException)
{
Log.Info("update", "Update check failed: " + ex.Message);
SetResult(null, failed: true);
}
}
private async Task DiagnosticsAsync()
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Advanced.DiagnosticsTitle"));
if (folder is null) return;
var path = await DiagnosticsBundle.CreateAsync(Shell.Services.Environment, folder);
Shell.Notify(Loc.L("Settings.Advanced.DiagnosticsDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
}
private void RaiseUpdate()
{
OnPropertyChanged(nameof(UpdateText));
OnPropertyChanged(nameof(UpdateKind));
OnPropertyChanged(nameof(HasUpdateText));
OnPropertyChanged(nameof(IsUpdateAvailable));
CommandManager.InvalidateRequerySuggested();
}
}
@@ -0,0 +1,9 @@
using Titano.App.Shell;
namespace Titano.App.Sections;
/// <summary>Archive manager (BRIEF §12.5).</summary>
public sealed class ArchiveViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Archive, "Icon.Archive")
{
public ShellViewModel Shell { get; } = shell;
}
@@ -0,0 +1,9 @@
using Titano.App.Shell;
namespace Titano.App.Sections;
/// <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;
}
+161 -3
View File
@@ -2,8 +2,166 @@
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}" />
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
xmlns:s="clr-namespace:Titano.App.Sections"
xmlns:j="clr-namespace:Titano.App.Jobs">
<UserControl.Resources>
<!-- Column layout shared by the header and the rows (Jobs.html grid-template-columns). -->
<Style x:Key="Text.Muted" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsDimmed}" Value="True">
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="Text.MutedNumber" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
<Setter Property="TextAlignment" Value="Right" />
</Style>
<Style x:Key="ProgressBar.Job" TargetType="ProgressBar" BasedOn="{StaticResource {x:Type ProgressBar}}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsDone}" Value="True">
<Setter Property="Foreground" Value="{DynamicResource Brush.Success}" />
</DataTrigger>
<DataTrigger Binding="{Binding IsFailed}" Value="True">
<Setter Property="Foreground" Value="{DynamicResource Brush.Error}" />
</DataTrigger>
</Style.Triggers>
</Style>
<ItemsPanelTemplate x:Key="Panel.Row">
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="56" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Toolbar: state chips · search · workers, Pause all, Clear done. -->
<DockPanel Margin="20,0" LastChildFill="False">
<Button DockPanel.Dock="Right" Content="{l:Loc Jobs.ClearDone}" Command="{Binding ClearDoneCommand}" ToolTip="{l:Loc Tooltips.Jobs.ClearDone}" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Jobs.PauseAll}" Command="{Binding PauseAllCommand}" ToolTip="{l:Loc Tooltips.Jobs.PauseAll}" Margin="12,0,0,0" />
<TextBlock DockPanel.Dock="Right" Text="{Binding WorkersText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center"
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Jobs.Workers}" />
<ItemsControl ItemsSource="{Binding Chips}" ItemsPanel="{StaticResource Panel.Row}" Focusable="False" VerticalAlignment="Center">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type s:JobFilterChip}">
<Button Style="{StaticResource Button.Chip}" Content="{Binding Text}" Tag="{Binding IsSelected}" Command="{Binding SelectCommand}"
ToolTip="{Binding ToolTip}" Margin="0,0,8,0" Typography.NumeralAlignment="Tabular" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="6,0,14,0" VerticalAlignment="Center" />
<TextBox Width="240" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
ui:Field.Placeholder="{l:Loc Jobs.Search}" ToolTip="{l:Loc Tooltips.Jobs.Search}" AutomationProperties.Name="{l:Loc Jobs.Search}" />
</DockPanel>
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="20,0,20,12" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Header -->
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="28" />
<ColumnDefinition Width="120" />
<ColumnDefinition Width="1.6*" MinWidth="160" />
<ColumnDefinition Width="200" />
<ColumnDefinition Width="90" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="110" />
<ColumnDefinition Width="120" />
<ColumnDefinition Width="Auto" MinWidth="150" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Kind}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Target}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Progress}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Speed}" Margin="10,0,0,0" TextAlignment="Right" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Left}" Margin="10,0,0,0" TextAlignment="Right" />
<TextBlock Grid.Column="6" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Where}" Margin="16,0,0,0" />
<TextBlock Grid.Column="7" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.State}" Margin="10,0,0,0" />
</Grid>
</Border>
<!-- Rows: queue order, then the history; expandable log tail. -->
<ListBox Grid.Row="1" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.PlainRow}"
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.ScrollChanged="OnScrollChanged" AutomationProperties.Name="{l:Loc Shell.Nav.Jobs}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type j:JobRowViewModel}">
<StackPanel>
<Grid x:Name="Row" Height="38" Background="Transparent">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="28" />
<ColumnDefinition Width="120" />
<ColumnDefinition Width="1.6*" MinWidth="160" />
<ColumnDefinition Width="200" />
<ColumnDefinition Width="90" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="110" />
<ColumnDefinition Width="120" />
<ColumnDefinition Width="Auto" MinWidth="150" />
</Grid.ColumnDefinitions>
<Button x:Name="Toggle" Style="{StaticResource Button.IconSubtle}" Width="22" Height="22" MinWidth="22" Margin="14,0,0,0"
ui:ButtonIcon.Glyph="{StaticResource Icon.ChevronRight}" Command="{Binding ToggleLogCommand}"
ToolTip="{Binding ToggleToolTip}" AutomationProperties.Name="{Binding ToggleToolTip}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Muted}" Text="{Binding Kind}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding Target}" Margin="10,0,0,0" ToolTip="{Binding Target}" />
<Grid Grid.Column="3" Margin="10,0,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="44" />
</Grid.ColumnDefinitions>
<ProgressBar Style="{StaticResource ProgressBar.Job}" Maximum="1" Value="{Binding Progress, Mode=OneWay}" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.MutedNumber}" Text="{Binding PercentText}" />
</Grid>
<TextBlock Grid.Column="4" Style="{StaticResource Text.MutedNumber}" Text="{Binding SpeedText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.MutedNumber}" Text="{Binding LeftText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="6" Style="{StaticResource Text.Muted}" Text="{Binding WhereText}" Margin="16,0,0,0" />
<ui:StatusGlyph Grid.Column="7" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}"
FontSize="13" VerticalAlignment="Center" Margin="10,0,0,0" />
<ItemsControl Grid.Column="8" ItemsSource="{Binding Actions}" ItemsPanel="{StaticResource Panel.Row}" Focusable="False"
VerticalAlignment="Center" Margin="10,0,8,0">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type j:JobAction}">
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
<Border x:Name="Log" Background="{DynamicResource Brush.Bg}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0"
Padding="52,10,14,12" Visibility="Collapsed">
<TextBlock Style="{StaticResource Text.Log}" Text="{Binding LogText}" />
</Border>
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsExpanded}" Value="True">
<Setter TargetName="Log" Property="Visibility" Value="Visible" />
<Setter TargetName="Row" Property="Background" Value="{DynamicResource Brush.Card}" />
<Setter TargetName="Toggle" Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.ChevronDown}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- Footer -->
<Border Grid.Row="2" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" Padding="14,8">
<DockPanel LastChildFill="False" TextElement.FontSize="12">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Jobs.RenderingSettings}" Command="{Binding RenderingSettingsCommand}"
ToolTip="{l:Loc Tooltips.Jobs.RenderingSettings}" />
<TextBlock Text="{Binding HistoryText}" Foreground="{DynamicResource Brush.TextMuted}" ToolTip="{l:Loc Tooltips.Jobs.History}" />
</DockPanel>
</Border>
</Grid>
</Border>
<ui:EmptyState Grid.Row="1" Message="{l:Loc Jobs.Empty}" Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}" />
</Grid>
</UserControl>
+7
View File
@@ -5,4 +5,11 @@ namespace Titano.App.Sections;
public partial class JobsView : UserControl
{
public JobsView() => InitializeComponent();
/// <summary>Loads older history when the list scrolls near its end.</summary>
private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
{
if (DataContext is not JobsViewModel vm || e.ExtentHeight <= 0) return;
if (e.VerticalOffset + e.ViewportHeight >= e.ExtentHeight - Math.Max(e.ViewportHeight, 200)) _ = vm.LoadMoreAsync();
}
}
+379
View File
@@ -0,0 +1,379 @@
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.App.Jobs;
using Titano.App.Settings;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Jobs;
using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
/// <summary>A filter chip of the Jobs toolbar ("Running · 4").</summary>
public sealed class JobFilterChip(JobFilter filter, Action<JobFilter> select) : ObservableObject
{
private int _count;
private bool _isSelected;
public JobFilter Filter { get; } = filter;
public string Text => Loc.L("Jobs.Filter." + Filter, Formatting.Count(_count));
public string ToolTip => Loc.L("Tooltips.Jobs.Filter." + Filter);
public ICommand SelectCommand { get; } = new RelayCommand(() => select(filter));
public bool IsSelected
{
get => _isSelected;
set => Set(ref _isSelected, value);
}
public int Count
{
get => _count;
set
{
if (Set(ref _count, value)) OnPropertyChanged(nameof(Text));
}
}
internal void Refresh() => OnAllPropertiesChanged();
}
/// <summary>
/// Jobs (BRIEF §12.6, Jobs.html): queue and history with live progress from the engine (batched to about 10
/// updates a second), filters, queue order, an expandable log tail per job, and the row actions. Also feeds the
/// shell's job bar, the status strip and the rail badge.
/// </summary>
public sealed class JobsViewModel : SectionViewModel
{
private static readonly TimeSpan FlushInterval = TimeSpan.FromMilliseconds(100);
private const int PageSize = 200;
private readonly JobListModel _model = new();
private readonly JobUpdateBuffer _buffer = new();
private readonly Dictionary<Guid, JobRowViewModel> _rows = [];
private readonly JobActions _actions;
private CoalescingThrottle? _throttle;
private IJobQueue? _queue;
private JobFilter _filter = JobFilter.All;
private string _searchText = string.Empty;
private string? _cursor;
private bool _hasMore;
private bool _loading;
private bool _hasLoaded;
public JobsViewModel(ShellViewModel shell)
: base(SectionKey.Jobs, "Icon.Jobs")
{
Shell = shell;
_actions = new JobActions(this);
Chips = [.. Enum.GetValues<JobFilter>().Select(f => new JobFilterChip(f, SelectFilter) { IsSelected = f == JobFilter.All })];
PauseCurrentCommand = new AsyncRelayCommand(PauseCurrentAsync, () => _model.Current is not null);
PauseAllCommand = new AsyncRelayCommand(PauseAllAsync, () => _model.RunningCount > 0);
ClearDoneCommand = new RelayCommand(ClearDone, () => _model.CountOf(JobFilter.Done, ClearedAt) + _model.CountOf(JobFilter.Failed, ClearedAt) > 0);
RenderingSettingsCommand = new RelayCommand(() =>
{
Shell.Settings.Page = SettingsPage.Rendering;
Shell.Navigate(SectionKey.Settings);
});
LoadMoreCommand = new RelayCommand(() => _ = LoadMoreAsync());
}
public ShellViewModel Shell { get; }
/// <summary>Rows in display order for the current filter and search.</summary>
public ObservableCollection<JobRowViewModel> Rows { get; } = [];
public IReadOnlyList<JobFilterChip> Chips { get; }
public ICommand PauseCurrentCommand { get; }
public ICommand PauseAllCommand { get; }
public ICommand ClearDoneCommand { get; }
public ICommand RenderingSettingsCommand { get; }
public ICommand LoadMoreCommand { get; }
public JobFilter Filter
{
get => _filter;
set
{
if (!Set(ref _filter, value)) return;
foreach (var chip in Chips) chip.IsSelected = chip.Filter == value;
SyncRows();
}
}
public string SearchText
{
get => _searchText;
set
{
if (Set(ref _searchText, value ?? string.Empty)) SyncRows();
}
}
/// <summary>"Workers 1 / 4".</summary>
public string WorkersText => Loc.L("Jobs.Workers", _model.RunningCount, _queue?.Workers ?? 0);
/// <summary>"History keeps 90 days".</summary>
public string HistoryText => Loc.Plural("Jobs.History", (long)new JobEngineOptions().HistoryRetention.TotalDays);
public bool IsEmpty => _hasLoaded && Rows.Count == 0;
public bool HasRows => Rows.Count > 0;
internal IJobQueue? Queue => _queue;
internal JobListModel Model => _model;
private DateTimeOffset? ClearedAt => Shell.Services.Settings.JobsClearedAt;
/// <summary>Subscribes to the engine and loads the first page of jobs.</summary>
public void Attach()
{
_queue = Shell.Services.Jobs;
if (_queue is null)
{
_hasLoaded = true;
RaiseState();
return;
}
_throttle = new CoalescingThrottle(FlushInterval, SynchronizationContext.Current, Flush);
_queue.JobChanged += OnJobChanged;
_queue.Progress += OnProgress;
_ = LoadMoreAsync();
}
public override void Dispose()
{
if (_queue is not null)
{
_queue.JobChanged -= OnJobChanged;
_queue.Progress -= OnProgress;
}
_throttle?.Dispose();
base.Dispose();
}
/// <summary>Reads the job list again from the first page (after jobs were written outside the engine).</summary>
public Task ReloadAsync()
{
_cursor = null;
_hasMore = true;
_hasLoaded = false;
return LoadMoreAsync();
}
/// <summary>Next page of the history (newest first); the view calls it when the list scrolls near its end.</summary>
public async Task LoadMoreAsync()
{
if (_queue is null || _loading || (_hasLoaded && !_hasMore)) return;
_loading = true;
try
{
var stamp = _model.Stamp;
var page = await _queue.ListAsync(_cursor, PageSize);
foreach (var job in page.Items) _model.ApplyLoaded(job, stamp);
_cursor = page.NextCursor;
_hasMore = page.NextCursor is not null;
}
catch (DatabaseException ex)
{
Log.Warning("jobs", "Job list unavailable", ex);
_hasMore = false;
}
finally
{
_loading = false;
_hasLoaded = true;
}
Flush();
}
/// <summary>Applies everything buffered since the last flush (UI thread).</summary>
internal void Flush()
{
var (jobs, progress) = _buffer.Drain();
foreach (var job in jobs) _model.Apply(job);
foreach (var p in progress) _model.Apply(p);
SyncRows();
UpdateShell();
}
private void OnJobChanged(Job job)
{
_buffer.Post(job);
_throttle?.Signal();
}
private void OnProgress(JobProgressInfo progress)
{
_buffer.Post(progress);
_throttle?.Signal();
}
private void SelectFilter(JobFilter filter) => Filter = filter;
/// <summary>Brings <see cref="Rows"/> to the model's order with moves (rows keep their expanded log).</summary>
private void SyncRows()
{
var ordered = _model.Ordered(_filter, _searchText, ClearedAt);
var wanted = new HashSet<Guid>(ordered.Select(e => e.Id));
for (var i = Rows.Count - 1; i >= 0; i--)
{
if (!wanted.Contains(Rows[i].Id)) Rows.RemoveAt(i);
}
for (var i = 0; i < ordered.Count; i++)
{
var entry = ordered[i];
var position = entry.State == JobState.Queued ? _model.QueuePosition(entry.Id) : 0;
if (!_rows.TryGetValue(entry.Id, out var row))
{
row = new JobRowViewModel(entry, position, _actions);
_rows[entry.Id] = row;
}
else
{
row.Update(entry, position);
}
if (i < Rows.Count && ReferenceEquals(Rows[i], row)) continue;
var existing = Rows.IndexOf(row);
if (existing >= 0) Rows.Move(existing, i);
else Rows.Insert(i, row);
}
foreach (var chip in Chips) chip.Count = _model.CountOf(chip.Filter, ClearedAt);
RaiseState();
}
private void UpdateShell()
{
if (_model.Current is { } current)
Shell.SetJob(JobText.Bar(current), current.Fraction ?? 0, indeterminate: current.Fraction is null);
else
Shell.SetJob(null, 0);
Shell.SetJobCount(_model.RunningCount + _model.QueuedCount, _model.QueuedCount);
Badge = _model.RunningCount;
OnPropertyChanged(nameof(WorkersText));
CommandManager.InvalidateRequerySuggested();
}
private void RaiseState()
{
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(HasRows));
}
private async Task PauseCurrentAsync()
{
if (_model.Current is { } current && _queue is not null) await _queue.PauseAsync(current.Id);
}
private async Task PauseAllAsync()
{
if (_queue is null) return;
foreach (var entry in _model.Ordered(JobFilter.Running).Where(e => e.State == JobState.Running).ToList()) await _queue.PauseAsync(entry.Id);
}
private void ClearDone()
{
Shell.Services.Settings.JobsClearedAt = DateTimeOffset.UtcNow;
Shell.Services.SaveSettings();
SyncRows();
}
/// <summary>Opens what a job worked on inside Titano: its sequence in the editor, or the Archive screen.</summary>
internal async Task OpenTargetAsync(Job job)
{
var db = Shell.Services.Database;
if (db is null || job.TargetIds.Count == 0) return;
if (await db.Sequences.GetAsync(job.TargetIds[0]) is { } sequence) Shell.OpenSequence(sequence.Id);
else Shell.Navigate(SectionKey.Archive);
}
/// <summary>Shows the folder of what a job worked on in Explorer.</summary>
internal async Task RevealTargetAsync(Job job)
{
var db = Shell.Services.Database;
if (db is null || job.TargetIds.Count == 0) return;
var id = job.TargetIds[0];
if (await db.Sequences.GetAsync(id) is { } sequence && await db.Archives.GetAsync(sequence.ArchiveId) is { } owner)
ShellActions.Reveal(Path.Combine(owner.RootPath, sequence.Folder.Replace('/', Path.DirectorySeparatorChar)));
else if (await db.Archives.GetAsync(id) is { } archive)
ShellActions.Reveal(archive.RootPath);
}
}
/// <summary>Row actions per job state (Jobs.html) and their commands.</summary>
internal sealed class JobActions(JobsViewModel owner)
{
public string WorkerId => owner.Queue?.WorkerId ?? Environment.MachineName;
public IReadOnlyList<JobAction> For(JobEntry entry)
{
var job = entry.Job;
return entry.State switch
{
JobState.Running =>
[
Make("Jobs.Action.Pause", "Tooltips.Jobs.Pause", q => q.PauseAsync(job.Id)),
Make("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", q => q.CancelAsync(job.Id)),
],
JobState.Paused =>
[
Make("Jobs.Action.Resume", "Tooltips.Jobs.Resume", q => q.ResumeAsync(job.Id)),
Make("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", q => q.CancelAsync(job.Id)),
],
JobState.Queued when job.Priority < JobPriority.User =>
[
Make("Jobs.Action.MoveUp", "Tooltips.Jobs.MoveUp", q => q.RaisePriorityAsync(job.Id)),
Make("Jobs.Action.Remove", "Tooltips.Jobs.Remove", q => q.CancelAsync(job.Id)),
],
JobState.Queued =>
[
Make("Jobs.Action.Pause", "Tooltips.Jobs.PauseQueued", q => q.PauseAsync(job.Id)),
Make("Jobs.Action.Remove", "Tooltips.Jobs.Remove", q => q.CancelAsync(job.Id)),
],
JobState.Failed =>
[
Make("Jobs.Action.Retry", "Tooltips.Jobs.Retry", q => q.ResumeAsync(job.Id)),
new JobAction(Loc.L("Jobs.Action.Show"), Loc.L("Tooltips.Jobs.Show"), new AsyncRelayCommand(() => owner.OpenTargetAsync(job))),
],
JobState.Cancelled =>
[
Make("Jobs.Action.Retry", "Tooltips.Jobs.Retry", q => q.ResumeAsync(job.Id)),
],
_ =>
[
new JobAction(Loc.L("Jobs.Action.Open"), Loc.L("Tooltips.Jobs.Open"), new AsyncRelayCommand(() => owner.OpenTargetAsync(job))),
new JobAction(Loc.L("Jobs.Action.Folder"), Loc.L("Tooltips.Jobs.Folder"), new AsyncRelayCommand(() => owner.RevealTargetAsync(job))),
],
};
}
/// <summary>Reads the stored log tail of a row (persisted with each checkpoint).</summary>
public async Task LoadLogAsync(JobRowViewModel row)
{
if (owner.Queue is not { } queue) return;
try
{
if (await queue.GetAsync(row.Id) is { } job) row.SetLog(job.LogTail);
}
catch (DatabaseException ex)
{
Log.Warning("jobs", "Job log unavailable", ex);
}
}
private JobAction Make(string textKey, string toolTipKey, Func<IJobQueue, Task> run) =>
new(Loc.L(textKey), Loc.L(toolTipKey), new AsyncRelayCommand(async () =>
{
if (owner.Queue is { } queue) await run(queue);
}));
}
+244 -4
View File
@@ -2,14 +2,254 @@
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}">
xmlns:v="clr-namespace:Titano.Ui.Visuals;assembly=Titano.Ui"
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
xmlns:lib="clr-namespace:Titano.App.Library">
<UserControl.Resources>
<Style x:Key="ListBoxItem.LibraryCard" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Card}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
</Style>
<Style x:Key="ListBoxItem.LibraryRow" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Height" Value="38" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
</Style>
<Style x:Key="Button.Header" TargetType="Button" BasedOn="{StaticResource Button.Subtle}">
<Setter Property="Height" Value="28" />
<Setter Property="MinWidth" Value="0" />
<Setter Property="Padding" Value="0" />
<Setter Property="FontSize" Value="11" />
<Setter Property="Foreground" Value="{DynamicResource Brush.TextFaint}" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="ui:ControlState.HoverBackground" Value="Transparent" />
</Style>
<DataTemplate x:Key="Template.Status" DataType="{x:Type v:CardStatus}">
<ui:StatusGlyph Kind="{Binding Kind}" Text="{Binding Text}" ToolTip="{Binding ToolTip}" Margin="0,0,8,0" />
</DataTemplate>
<ItemsPanelTemplate x:Key="Panel.Row">
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="56" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<!-- Toolbar (Main.html): search, filters, sort · view switch, rescan. -->
<DockPanel Grid.ColumnSpan="2" Margin="20,0" LastChildFill="False">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Icon}" ui:ButtonIcon.Glyph="{StaticResource Icon.Refresh}" Command="{Binding RescanCommand}"
ToolTip="{l:Loc Tooltips.Library.Rescan}" AutomationProperties.Name="{l:Loc Library.Rescan}" Margin="10,0,0,0" />
<v:SegmentedControl DockPanel.Dock="Right" SelectedIndex="{Binding LayoutIndex, Mode=TwoWay}" AutomationProperties.Name="{l:Loc Library.View}">
<v:SegmentedItem Glyph="{StaticResource Icon.ViewGrid}" ToolTip="{l:Loc Tooltips.Library.Grid}" AutomationProperties.Name="{l:Loc Library.View.Grid}" />
<v:SegmentedItem Glyph="{StaticResource Icon.ViewList}" ToolTip="{l:Loc Tooltips.Library.List}" AutomationProperties.Name="{l:Loc Library.View.List}" />
</v:SegmentedControl>
<TextBox Width="260" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
ui:Field.Placeholder="{l:Loc Library.Search}" ToolTip="{l:Loc Tooltips.Library.Search}" AutomationProperties.Name="{l:Loc Library.Search}" />
<ComboBox Style="{StaticResource ComboBox.Filter}" Margin="10,0,0,0" ItemsSource="{Binding Years}" SelectedItem="{Binding SelectedYear}" Tag="{Binding IsYearFiltered}"
ItemTemplate="{StaticResource Template.FilterOption}" ToolTip="{l:Loc Tooltips.Library.Year}" AutomationProperties.Name="{l:Loc Library.Filter.Year}" />
<ComboBox Style="{StaticResource ComboBox.Filter}" Margin="10,0,0,0" ItemsSource="{Binding Cameras}" SelectedItem="{Binding SelectedCamera}" Tag="{Binding IsCameraFiltered}"
ItemTemplate="{StaticResource Template.FilterOption}" ToolTip="{l:Loc Tooltips.Library.Camera}" AutomationProperties.Name="{l:Loc Library.Filter.Camera}" />
<ComboBox Style="{StaticResource ComboBox.Filter}" Margin="10,0,0,0" ItemsSource="{Binding Statuses}" SelectedItem="{Binding SelectedStatus}" Tag="{Binding IsStatusFiltered}"
ItemTemplate="{StaticResource Template.FilterOption}" ToolTip="{l:Loc Tooltips.Library.Status}" AutomationProperties.Name="{l:Loc Library.Filter.Status}" />
<ComboBox Style="{StaticResource ComboBox.Filter}" Margin="10,0,0,0" ItemsSource="{Binding Tags}" SelectedItem="{Binding SelectedTag}" Tag="{Binding IsTagFiltered}"
ItemTemplate="{StaticResource Template.FilterOption}" ToolTip="{l:Loc Tooltips.Library.Tags}" AutomationProperties.Name="{l:Loc Library.Filter.Tags}" />
<ComboBox Style="{StaticResource ComboBox.Filter}" Margin="10,0,0,0" ItemsSource="{Binding Sorts}" SelectedItem="{Binding SelectedSort}"
ItemTemplate="{StaticResource Template.FilterOption}" ToolTip="{l:Loc Tooltips.Library.Sort}" AutomationProperties.Name="{l:Loc Library.Sort}" />
</DockPanel>
<!-- Grid view: virtualised, recycling card grid. -->
<ListBox x:Name="CardGrid" Grid.Row="1" Style="{StaticResource ListBox.Cards}" ItemsSource="{Binding Items}" ItemContainerStyle="{StaticResource ListBoxItem.LibraryCard}"
Visibility="{Binding IsGrid, Converter={StaticResource BoolToVisibility}}" AutomationProperties.Name="{l:Loc Shell.Nav.Library}"
ScrollViewer.ScrollChanged="OnScrollChanged">
<ListBox.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding OpenCommand}" />
<KeyBinding Key="Enter" Command="{Binding OpenCommand}" />
</ListBox.InputBindings>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type lib:SequenceItem}">
<v:SequenceCard Title="{Binding Title}" Subtitle="{Binding Subtitle}" Statuses="{Binding Statuses}" Thumbnail="{Binding Thumbnail}"
ScrubSource="{Binding ScrubSource}" lib:ThumbnailLoading.Width="236"
IsSelected="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}, Mode=TwoWay}"
SelectToolTip="{l:Loc Tooltips.Library.Select}" ToolTip="{l:Loc Tooltips.Library.Card}">
<v:SequenceCard.ActionsContent>
<StackPanel Orientation="Horizontal">
<Button Style="{StaticResource Button.Icon}" Width="28" Height="28" MinWidth="28" ui:ButtonIcon.Glyph="{StaticResource Icon.Sequence}"
Command="{Binding DataContext.OpenItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{l:Loc Tooltips.Library.Open}" AutomationProperties.Name="{l:Loc Library.Action.Open}" Margin="0,0,6,0" />
<Button Style="{StaticResource Button.Icon}" Width="28" Height="28" MinWidth="28" ui:ButtonIcon.Glyph="{StaticResource Icon.Analyse}"
Command="{Binding DataContext.AnalyseItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{l:Loc Tooltips.Library.Analyse}" AutomationProperties.Name="{l:Loc Library.Action.Analyse}" />
</StackPanel>
</v:SequenceCard.ActionsContent>
</v:SequenceCard>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- List view: virtualised table with sortable headers. -->
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="20,4,20,12" Visibility="{Binding IsList, Converter={StaticResource BoolToVisibility}}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="180" />
<ColumnDefinition Width="110" />
<ColumnDefinition Width="170" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="90" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="90" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<Button Style="{StaticResource Button.Header}" Content="{l:Loc Library.Column.Sequence}" Command="{Binding SortByCommand}" CommandParameter="Title" ToolTip="{l:Loc Tooltips.Library.SortTitle}" />
<Button Grid.Column="1" Style="{StaticResource Button.Header}" Content="{l:Loc Library.Column.Date}" Command="{Binding SortByCommand}" CommandParameter="Date" ToolTip="{l:Loc Tooltips.Library.SortDate}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Library.Column.Camera}" Margin="10,0,0,0" />
<Button Grid.Column="3" Style="{StaticResource Button.Header}" Content="{l:Loc Library.Column.Frames}" HorizontalContentAlignment="Right" Command="{Binding SortByCommand}" CommandParameter="FrameCount" ToolTip="{l:Loc Tooltips.Library.SortFrames}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Library.Column.Span}" TextAlignment="Right" Margin="10,0,0,0" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.Header}" Text="{l:Loc Library.Column.Interval}" TextAlignment="Right" Margin="10,0,0,0" />
<Button Grid.Column="6" Style="{StaticResource Button.Header}" Content="{l:Loc Library.Column.Size}" HorizontalContentAlignment="Right" Command="{Binding SortByCommand}" CommandParameter="Size" ToolTip="{l:Loc Tooltips.Library.SortSize}" Margin="10,0,0,0" />
<TextBlock Grid.Column="7" Style="{StaticResource Text.Header}" Text="{l:Loc Library.Column.State}" Margin="16,0,0,0" />
</Grid>
</Border>
<ListBox x:Name="RowList" Grid.Row="1" ItemsSource="{Binding Items}" ItemContainerStyle="{StaticResource ListBoxItem.LibraryRow}" SelectionMode="Extended"
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.ScrollChanged="OnScrollChanged" AutomationProperties.Name="{l:Loc Shell.Nav.Library}">
<ListBox.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding OpenCommand}" />
<KeyBinding Key="Enter" Command="{Binding OpenCommand}" />
</ListBox.InputBindings>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type lib:SequenceItem}">
<Grid ToolTip="{l:Loc Tooltips.Library.Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="180" />
<ColumnDefinition Width="110" />
<ColumnDefinition Width="170" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="90" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="90" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Title}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding DateText}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding Camera}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.CellNumber}" Text="{Binding FramesText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.CellNumber}" Text="{Binding SpanText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.CellNumber}" Text="{Binding IntervalText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="6" Style="{StaticResource Text.CellNumber}" Text="{Binding SizeText}" Margin="10,0,0,0" />
<ItemsControl Grid.Column="7" Margin="16,0,0,0" ItemsSource="{Binding Statuses}" ItemTemplate="{StaticResource Template.Status}"
ItemsPanel="{StaticResource Panel.Row}" VerticalAlignment="Center" Focusable="False" ClipToBounds="True" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
<!-- Empty states: one sentence plus the first actions (Components.html). -->
<ui:EmptyState Grid.Row="1" Message="{l:Loc Library.Empty}" Visibility="{Binding IsLibraryEmpty, Converter={StaticResource BoolToVisibility}}">
<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.Adopt}" Command="{Binding AdoptFolderCommand}" ToolTip="{l:Loc Tooltips.Library.Adopt}" Margin="0,0,8,0" />
<Button Content="{l:Loc Library.Empty.Connect}" Command="{Binding ConnectCommand}" ToolTip="{l:Loc Tooltips.Library.Connect}" />
</StackPanel>
</ui:EmptyState>
<ui:EmptyState Grid.Row="1" Message="{l:Loc Library.NoMatch}" Visibility="{Binding IsNoMatch, Converter={StaticResource BoolToVisibility}}">
<Button Content="{l:Loc Library.ClearFilters}" Command="{Binding ClearFiltersCommand}" ToolTip="{l:Loc Tooltips.Library.ClearFilters}" />
</ui:EmptyState>
<!-- Selection panel (320 px, DESIGN §3). -->
<Border Grid.Row="1" Grid.Column="1" Width="320" Margin="0,4,20,12" Style="{StaticResource Border.Panel}" Padding="16"
Visibility="{Binding HasSelection, Converter={StaticResource BoolToVisibility}}">
<Grid>
<!-- One sequence -->
<ScrollViewer VerticalScrollBarVisibility="Auto" Focusable="False" DataContext="{Binding Selected}"
Visibility="{Binding DataContext.IsSingleSelection, RelativeSource={RelativeSource AncestorType=UserControl}, Converter={StaticResource BoolToVisibility}}">
<StackPanel>
<v:AspectRatioDecorator>
<Border CornerRadius="6" Background="{DynamicResource Brush.Preview}">
<Border CornerRadius="6">
<Border.Background>
<ImageBrush ImageSource="{Binding Thumbnail}" Stretch="UniformToFill" />
</Border.Background>
</Border>
</Border>
</v:AspectRatioDecorator>
<TextBlock Text="{Binding Title}" Style="{StaticResource Text.Title}" Margin="0,12,0,0" TextWrapping="Wrap" TextTrimming="None" />
<ItemsControl ItemsSource="{Binding Statuses}" ItemTemplate="{StaticResource Template.Status}" ItemsPanel="{StaticResource Panel.Row}" Margin="0,6,0,0" Focusable="False" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{StaticResource Grid.LabelColumn}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="24" />
<RowDefinition Height="24" />
<RowDefinition Height="24" />
<RowDefinition Height="24" />
<RowDefinition Height="24" />
<RowDefinition Height="24" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Date}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding DateText}" />
<TextBlock Grid.Row="1" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Frames}" />
<TextBlock Grid.Row="1" Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding FramesText}" />
<TextBlock Grid.Row="2" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Span}" />
<TextBlock Grid.Row="2" Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding SpanText}" />
<TextBlock Grid.Row="3" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Interval}" />
<TextBlock Grid.Row="3" Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding IntervalText}" />
<TextBlock Grid.Row="4" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Camera}" />
<TextBlock Grid.Row="4" Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Camera}" />
<TextBlock Grid.Row="5" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Size}" />
<TextBlock Grid.Row="5" Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding SizeText}" />
<TextBlock Grid.Row="6" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Folder}" VerticalAlignment="Top" Margin="0,4,14,0" />
<TextBlock Grid.Row="6" Grid.Column="1" Text="{Binding Sequence.Folder}" TextWrapping="Wrap" Margin="0,4,0,0" />
<TextBlock Grid.Row="7" Style="{StaticResource Text.Label}" Text="{l:Loc Library.Column.Tags}" VerticalAlignment="Top" Margin="0,8,14,0" />
<TextBlock Grid.Row="7" Grid.Column="1" Text="{Binding TagsText}" TextWrapping="Wrap" Margin="0,8,0,0" />
</Grid>
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Library.Action.Open}" HorizontalAlignment="Stretch" Margin="0,18,0,0"
Command="{Binding DataContext.OpenCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" ToolTip="{l:Loc Tooltips.Library.Open}" />
<WrapPanel Margin="0,8,0,0">
<Button Content="{l:Loc Library.Action.Analyse}" Command="{Binding DataContext.AnalyseCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
ToolTip="{l:Loc Tooltips.Library.Analyse}" ui:ButtonIcon.Glyph="{StaticResource Icon.Analyse}" Margin="0,0,8,8" />
<Button Content="{l:Loc Library.Action.Proxies}" Command="{Binding DataContext.ProxiesCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
ToolTip="{l:Loc Tooltips.Library.Proxies}" ui:ButtonIcon.Glyph="{StaticResource Icon.Layers}" Margin="0,0,8,8" />
<Button Content="{l:Loc Library.Action.Verify}" Command="{Binding DataContext.VerifyCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
ToolTip="{l:Loc Tooltips.Library.Verify}" ui:ButtonIcon.Glyph="{StaticResource Icon.Verify}" Margin="0,0,8,8" />
<Button Content="{l:Loc Library.Action.Folder}" Command="{Binding DataContext.RevealCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
ToolTip="{l:Loc Tooltips.Library.Folder}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Margin="0,0,8,8" />
</WrapPanel>
</StackPanel>
</ScrollViewer>
<!-- Several sequences: mass actions. -->
<StackPanel Visibility="{Binding IsMultiSelection, Converter={StaticResource BoolToVisibility}}">
<TextBlock Text="{Binding SelectionTitle}" Style="{StaticResource Text.Title}" />
<TextBlock Text="{Binding SelectionSummary}" Style="{StaticResource Text.Secondary}" Margin="0,4,0,0" />
<WrapPanel Margin="0,16,0,0">
<Button Content="{l:Loc Library.Action.Analyse}" Command="{Binding AnalyseCommand}" ToolTip="{l:Loc Tooltips.Library.AnalyseAll}" ui:ButtonIcon.Glyph="{StaticResource Icon.Analyse}" Margin="0,0,8,8" />
<Button Content="{l:Loc Library.Action.Proxies}" Command="{Binding ProxiesCommand}" ToolTip="{l:Loc Tooltips.Library.ProxiesAll}" ui:ButtonIcon.Glyph="{StaticResource Icon.Layers}" Margin="0,0,8,8" />
<Button Content="{l:Loc Library.Action.Verify}" Command="{Binding VerifyCommand}" ToolTip="{l:Loc Tooltips.Library.VerifyAll}" ui:ButtonIcon.Glyph="{StaticResource Icon.Verify}" Margin="0,0,8,8" />
<Button Content="{l:Loc Library.Action.ExportList}" Command="{Binding ExportListCommand}" ToolTip="{l:Loc Tooltips.Library.ExportList}" ui:ButtonIcon.Glyph="{StaticResource Icon.Export}" Margin="0,0,8,8" />
</WrapPanel>
<Button Style="{StaticResource Button.Subtle}" Content="{l:Loc Library.Action.ClearSelection}" Command="{Binding ClearSelectionCommand}" ToolTip="{l:Loc Tooltips.Library.ClearSelection}" HorizontalAlignment="Left" Margin="0,8,0,0" />
</StackPanel>
</Grid>
</Border>
</Grid>
</UserControl>
@@ -5,4 +5,11 @@ namespace Titano.App.Sections;
public partial class LibraryView : UserControl
{
public LibraryView() => InitializeComponent();
/// <summary>Loads the next page when the grid or the list scrolls within two screens of its end.</summary>
private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
{
if (DataContext is not LibraryViewModel vm || e.ExtentHeight <= 0) return;
if (e.VerticalOffset + e.ViewportHeight >= e.ExtentHeight - 2 * Math.Max(e.ViewportHeight, 200)) _ = vm.LoadMoreAsync();
}
}
+630
View File
@@ -0,0 +1,630 @@
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Input;
using System.Windows.Threading;
using Titano.App.Infrastructure;
using Titano.App.Jobs;
using Titano.App.Library;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Repositories;
using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
/// <summary>
/// Library (home, BRIEF §12.2): sequences of the index in a virtualised card grid or table, filtered by search,
/// year, camera, status and tag, loaded page by page (keyset paging) as the view scrolls, with a selection panel.
/// </summary>
public sealed class LibraryViewModel : SectionViewModel
{
private const int AnalysingPollMs = 250;
private readonly DispatcherTimer _searchDelay;
private readonly HashSet<Guid> _analysing = [];
private LibraryPager? _pager;
private TitanoDatabase? _db;
private string _searchText = string.Empty;
private FilterOption<int?> _year;
private FilterOption<string?> _camera;
private FilterOption<StatusFilter> _status;
private FilterOption<string?> _tag;
private FilterOption<SequenceSort> _sort;
private IReadOnlyList<FilterOption<int?>> _years;
private IReadOnlyList<FilterOption<string?>> _cameras;
private IReadOnlyList<FilterOption<string?>> _tags;
private IReadOnlyList<FilterOption<StatusFilter>> _statuses;
private IReadOnlyList<FilterOption<SequenceSort>> _sorts;
private bool _isLoading;
private bool _hasLoaded;
private bool _suppressReload;
private int _layoutIndex;
private SequenceItem? _selected;
private int _selectionCount;
private bool _hasArchive;
public LibraryViewModel(ShellViewModel shell)
: base(SectionKey.Library, "Icon.Library")
{
Shell = shell;
_years = [AnyYear()];
_cameras = [AnyCamera()];
_tags = [AnyTag()];
_year = _years[0];
_camera = _cameras[0];
_tag = _tags[0];
_statuses = BuildStatusOptions();
_status = _statuses[0];
_sorts = BuildSortOptions();
_sort = _sorts.FirstOrDefault(s => s.Value == shell.Services.Settings.LibrarySort) ?? _sorts[0];
Loc.CultureChanged += OnCultureChanged;
_layoutIndex = shell.Services.Settings.LibraryLayout == LibraryLayout.List ? 1 : 0;
_searchDelay = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
_searchDelay.Tick += (_, _) =>
{
_searchDelay.Stop();
Reload();
};
LoadMoreCommand = new RelayCommand(() => _ = LoadMoreAsync());
ClearFiltersCommand = new RelayCommand(ClearFilters);
RescanCommand = new AsyncRelayCommand(RescanAsync, () => _db is not null && _hasArchive);
OpenCommand = new RelayCommand(() =>
{
if (Selected is { } s) Shell.OpenSequence(s.Id);
}, () => Selected is not null);
RenderCommand = OpenCommand;
AnalyseCommand = new AsyncRelayCommand(() => EnqueueAsync(JobKind.DeepAnalyse), () => SelectionCount > 0 && _db is not null);
ProxiesCommand = new AsyncRelayCommand(() => EnqueueAsync(JobKind.Proxies), () => SelectionCount > 0 && _db is not null);
VerifyCommand = new AsyncRelayCommand(() => EnqueueAsync(JobKind.Verify), () => SelectionCount > 0 && _db is not null);
RevealCommand = new AsyncRelayCommand(RevealAsync, () => Selected is not null && _db is not null);
ExportListCommand = new AsyncRelayCommand(ExportListAsync, () => SelectionCount > 0);
ClearSelectionCommand = new RelayCommand(ClearSelection, () => SelectionCount > 0);
SortByCommand = new RelayCommand(p =>
{
if (p is "Date") SelectedSort = Sorts.First(o => o.Value == (_sort.Value == SequenceSort.Newest ? SequenceSort.Oldest : SequenceSort.Newest));
else if (p is SequenceSort sort) SelectedSort = Sorts.First(o => o.Value == sort);
else if (p is string name && Enum.TryParse<SequenceSort>(name, out var parsed)) SelectedSort = Sorts.First(o => o.Value == parsed);
});
OpenItemCommand = new RelayCommand(p =>
{
if (p is SequenceItem item) Shell.OpenSequence(item.Id);
});
AnalyseItemCommand = new AsyncRelayCommand(async (p, _) =>
{
if (p is SequenceItem item && Shell.Services.Jobs is { } jobs)
{
await jobs.EnqueueAsync(JobKind.DeepAnalyse, [item.Id], item.Title);
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(JobKind.DeepAnalyse), item.Title), actionText: Loc.L("Shell.Nav.Jobs"),
actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
}
});
ImportCardCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import));
AdoptFolderCommand = new AsyncRelayCommand(AdoptFolderAsync);
ConnectCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Server));
}
public ShellViewModel Shell { get; }
public ObservableCollection<SequenceItem> Items { get; } = [];
public ICommand LoadMoreCommand { get; }
public ICommand ClearFiltersCommand { get; }
public ICommand RescanCommand { get; }
public ICommand OpenCommand { get; }
public ICommand RenderCommand { get; }
public ICommand AnalyseCommand { get; }
public ICommand ProxiesCommand { get; }
public ICommand VerifyCommand { get; }
public ICommand RevealCommand { get; }
public ICommand ExportListCommand { get; }
public ICommand ClearSelectionCommand { get; }
public ICommand SortByCommand { get; }
public ICommand OpenItemCommand { get; }
public ICommand AnalyseItemCommand { get; }
public ICommand ImportCardCommand { get; }
public ICommand AdoptFolderCommand { get; }
public ICommand ConnectCommand { get; }
// ---------------- Layout ----------------
/// <summary>0 = grid, 1 = list (the SegmentedControl's index).</summary>
public int LayoutIndex
{
get => _layoutIndex;
set
{
if (value is < 0 or > 1 || !Set(ref _layoutIndex, value)) return;
Shell.Services.Settings.LibraryLayout = value == 1 ? LibraryLayout.List : LibraryLayout.Grid;
OnPropertyChanged(nameof(IsGrid));
OnPropertyChanged(nameof(IsList));
}
}
public bool IsGrid => _layoutIndex == 0 && HasItems;
public bool IsList => _layoutIndex == 1 && HasItems;
// ---------------- Filters ----------------
public string SearchText
{
get => _searchText;
set
{
if (!Set(ref _searchText, value ?? string.Empty)) return;
_searchDelay.Stop();
_searchDelay.Start();
}
}
public IReadOnlyList<FilterOption<int?>> Years { get => _years; private set => Set(ref _years, value); }
public IReadOnlyList<FilterOption<string?>> Cameras { get => _cameras; private set => Set(ref _cameras, value); }
public IReadOnlyList<FilterOption<StatusFilter>> Statuses { get => _statuses; private set => Set(ref _statuses, value); }
public IReadOnlyList<FilterOption<string?>> Tags { get => _tags; private set => Set(ref _tags, value); }
public IReadOnlyList<FilterOption<SequenceSort>> Sorts { get => _sorts; private set => Set(ref _sorts, value); }
public FilterOption<int?> SelectedYear
{
get => _year;
set => SetFilter(ref _year, value ?? Years[0], nameof(IsYearFiltered));
}
public FilterOption<string?> SelectedCamera
{
get => _camera;
set => SetFilter(ref _camera, value ?? Cameras[0], nameof(IsCameraFiltered));
}
public FilterOption<StatusFilter> SelectedStatus
{
get => _status;
set => SetFilter(ref _status, value ?? Statuses[0], nameof(IsStatusFiltered));
}
public FilterOption<string?> SelectedTag
{
get => _tag;
set => SetFilter(ref _tag, value ?? Tags[0], nameof(IsTagFiltered));
}
public FilterOption<SequenceSort> SelectedSort
{
get => _sort;
set
{
if (value is null || !Set(ref _sort, value)) return;
Shell.Services.Settings.LibrarySort = value.Value;
OnPropertyChanged(nameof(SortColumn));
Reload();
}
}
public bool IsYearFiltered => !_year.IsAny;
public bool IsCameraFiltered => !_camera.IsAny;
public bool IsStatusFiltered => !_status.IsAny;
public bool IsTagFiltered => !_tag.IsAny;
/// <summary>The sort as a column name for the list header ("Newest", "Title", …).</summary>
public string SortColumn => _sort.Value.ToString();
/// <summary>The filter the toolbar describes.</summary>
public LibraryFilter Filter => new()
{
Text = _searchText,
Year = _year.Value,
Camera = _camera.Value,
Status = _status.Value,
Tag = _tag.Value,
Sort = _sort.Value,
};
// ---------------- State ----------------
public bool IsLoading
{
get => _isLoading;
private set => Set(ref _isLoading, value);
}
public bool HasItems => Items.Count > 0;
/// <summary>Loaded, nothing indexed and no filter: the first-run empty state (one sentence, three choices).</summary>
public bool IsLibraryEmpty => _hasLoaded && !HasItems && !_isLoading && Filter.IsUnfiltered;
/// <summary>Loaded, but the filters match nothing.</summary>
public bool IsNoMatch => _hasLoaded && !HasItems && !_isLoading && !Filter.IsUnfiltered;
// ---------------- Selection ----------------
/// <summary>The selected sequence when exactly one is selected.</summary>
public SequenceItem? Selected
{
get => _selected;
private set => Set(ref _selected, value);
}
public int SelectionCount
{
get => _selectionCount;
private set
{
if (!Set(ref _selectionCount, value)) return;
OnPropertyChanged(nameof(HasSelection));
OnPropertyChanged(nameof(IsSingleSelection));
OnPropertyChanged(nameof(IsMultiSelection));
OnPropertyChanged(nameof(SelectionTitle));
OnPropertyChanged(nameof(SelectionSummary));
}
}
public bool HasSelection => _selectionCount > 0;
public bool IsSingleSelection => _selectionCount == 1;
public bool IsMultiSelection => _selectionCount > 1;
/// <summary>"3 selected".</summary>
public string SelectionTitle => Loc.Plural("Library.Selection.Count", _selectionCount);
/// <summary>"10,240 photos · 182 GB" of the selection.</summary>
public string SelectionSummary
{
get
{
var chosen = SelectedItems().ToList();
return Loc.Plural("Shell.Status.Photos", chosen.Sum(i => (long)i.Sequence.FrameCount)) + " · " + Formatting.Bytes(chosen.Sum(i => i.Sequence.TotalBytes));
}
}
public IEnumerable<SequenceItem> SelectedItems() => Items.Where(i => i.IsSelected);
// ---------------- Lifecycle ----------------
/// <summary>Binds to the index and loads filters, totals and the first page.</summary>
public async Task AttachAsync()
{
_db = Shell.Services.Database;
if (_db is null)
{
_hasLoaded = true;
RaiseState();
return;
}
_pager = new LibraryPager((q, ct) => _db.Sequences.ListAsync(q, ct));
if (Shell.Services.Jobs is { } jobs)
{
jobs.JobChanged += OnJobChanged;
}
await RefreshFiltersAsync();
await ReloadAsync();
}
/// <summary>Re-reads filter choices and totals, then the list (after imports, archive changes).</summary>
public async Task RefreshAsync()
{
await RefreshFiltersAsync();
await ReloadAsync();
}
public override void Dispose()
{
Loc.CultureChanged -= OnCultureChanged;
_searchDelay.Stop();
_pager?.Cancel();
if (Shell.Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
base.Dispose();
}
/// <summary>The view calls this when the list scrolls near its end.</summary>
public Task LoadMoreAsync() => ApplyAsync(_pager?.LoadMoreAsync());
/// <summary>The view calls this when container selection changed.</summary>
public void OnSelectionChanged()
{
var count = 0;
SequenceItem? single = null;
foreach (var item in Items)
{
if (!item.IsSelected) continue;
count++;
single = count == 1 ? item : null;
}
Selected = count == 1 ? single : null;
SelectionCount = count;
OnPropertyChanged(nameof(SelectionSummary));
CommandManager.InvalidateRequerySuggested();
}
private void Reload()
{
if (_suppressReload) return;
_ = ReloadAsync();
}
private async Task ReloadAsync()
{
if (_pager is null) return;
await ApplyAsync(_pager.ResetAsync(Filter));
}
private async Task ApplyAsync(Task<LibraryPage?>? pending)
{
if (pending is null) return;
IsLoading = true;
RaiseState();
try
{
var page = await pending;
if (page is null) return;
if (page.IsFirst)
{
foreach (var old in Items) old.PropertyChanged -= OnItemChanged;
Items.Clear();
Selected = null;
SelectionCount = 0;
}
foreach (var sequence in page.Items)
{
var item = new SequenceItem(sequence, Shell.Services.Thumbnails) { IsAnalysing = _analysing.Contains(sequence.Id) };
item.PropertyChanged += OnItemChanged;
Items.Add(item);
}
_hasLoaded = true;
}
catch (Exception ex) when (ex is DatabaseException or InvalidOperationException)
{
Shell.ReportError(ex);
}
finally
{
IsLoading = _pager?.IsLoading ?? false;
RaiseState();
}
}
private async Task RefreshFiltersAsync()
{
if (_db is null) return;
try
{
var stats = await _db.Sequences.GetStatsAsync(null);
var tags = await _db.Tags.ListAsync();
_hasArchive = (await _db.Archives.ListAsync()).Count > 0;
Shell.SetLibraryTotals(stats.Sequences, stats.Photos, stats.Bytes);
_suppressReload = true;
var year = _year.Value;
var camera = _camera.Value;
var tag = _tag.Value;
Years = [AnyYear(), .. stats.ByYear.OrderByDescending(y => y.Year).Select(y => new FilterOption<int?>(y.Year, YearText(y.Year), YearText(y.Year)))];
Cameras =
[
AnyCamera(),
.. stats.ByCamera.Where(c => !string.IsNullOrWhiteSpace(c.Model))
.GroupBy(c => c.Model!, StringComparer.Ordinal)
.Select(g => (Model: g.Key, Name: Core.Naming.PathTemplate.CameraName(g.First().Make, g.Key)))
.OrderBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase)
.Select(c => new FilterOption<string?>(c.Model, c.Name, c.Name)),
];
Tags = [AnyTag(), .. tags.OrderBy(t => t.Name, StringComparer.CurrentCultureIgnoreCase).Select(t => new FilterOption<string?>(t.Name, t.Name, t.Name))];
SelectedYear = Years.FirstOrDefault(o => o.Value == year) ?? Years[0];
SelectedCamera = Cameras.FirstOrDefault(o => o.Value == camera) ?? Cameras[0];
SelectedTag = Tags.FirstOrDefault(o => o.Value == tag) ?? Tags[0];
}
catch (DatabaseException ex)
{
Log.Warning("library", "Library statistics unavailable", ex);
}
finally
{
_suppressReload = false;
}
}
private void SetFilter<T>(ref FilterOption<T> field, FilterOption<T> value, string flagName, [System.Runtime.CompilerServices.CallerMemberName] string? propertyName = null)
{
if (!Set(ref field, value, propertyName)) return;
OnPropertyChanged(flagName);
Reload();
}
private void ClearFilters()
{
_suppressReload = true;
_searchDelay.Stop();
SearchText = string.Empty;
_searchDelay.Stop();
SelectedYear = Years[0];
SelectedCamera = Cameras[0];
SelectedStatus = Statuses[0];
SelectedTag = Tags[0];
_suppressReload = false;
Reload();
}
private void ClearSelection()
{
foreach (var item in Items) item.IsSelected = false;
OnSelectionChanged();
}
private void OnItemChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(SequenceItem.IsSelected)) OnSelectionChanged();
}
private void RaiseState()
{
OnPropertyChanged(nameof(HasItems));
OnPropertyChanged(nameof(IsGrid));
OnPropertyChanged(nameof(IsList));
OnPropertyChanged(nameof(IsLibraryEmpty));
OnPropertyChanged(nameof(IsNoMatch));
}
private void OnJobChanged(Job job)
{
// Engine events arrive on worker threads.
System.Windows.Application.Current?.Dispatcher.BeginInvoke(() => ApplyJob(job));
}
private void ApplyJob(Job job)
{
if (job.Kind is JobKind.LightAnalyse or JobKind.DeepAnalyse)
{
foreach (var id in job.TargetIds)
{
if (job.State == JobState.Running) _analysing.Add(id);
else _analysing.Remove(id);
}
foreach (var item in Items.Where(i => job.TargetIds.Contains(i.Id))) item.IsAnalysing = _analysing.Contains(item.Id);
}
if (job.State == JobState.Done) _ = RefreshTargetsAsync(job);
}
/// <summary>A finished job changed some sequences: refresh those rows in place and the totals.</summary>
private async Task RefreshTargetsAsync(Job job)
{
if (_db is null) return;
try
{
foreach (var item in Items.Where(i => job.TargetIds.Contains(i.Id)).ToList())
{
if (await _db.Sequences.GetAsync(item.Id) is { } fresh) item.Update(fresh);
}
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit) await RefreshAsync();
}
catch (DatabaseException ex)
{
Log.Warning("library", "Refresh after a job failed", ex);
}
}
private async Task EnqueueAsync(JobKind kind)
{
if (Shell.Services.Jobs is not { } jobs) return;
var chosen = SelectedItems().ToList();
if (chosen.Count == 0) return;
var label = chosen.Count == 1 ? chosen[0].Title : Loc.Plural("Library.Selection.Count", chosen.Count);
await jobs.EnqueueAsync(kind, [.. chosen.Select(i => i.Id)], label);
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(kind), label), actionText: Loc.L("Shell.Nav.Jobs"),
actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
}
private async Task RescanAsync()
{
if (_db is null || Shell.Services.Jobs is not { } jobs) return;
var archives = await _db.Archives.ListAsync();
foreach (var archive in archives) await jobs.EnqueueAsync(JobKind.Scan, [archive.Id], archive.Name);
if (archives.Count > 0)
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(JobKind.Scan), archives[0].Name), actionText: Loc.L("Shell.Nav.Jobs"),
actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
}
private async Task RevealAsync()
{
if (_db is null || Selected is not { } item) return;
var archive = await _db.Archives.GetAsync(item.Sequence.ArchiveId);
if (archive is null) return;
ShellActions.Reveal(Path.Combine(archive.RootPath, item.Sequence.Folder.Replace('/', Path.DirectorySeparatorChar)));
}
private async Task AdoptFolderAsync()
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Library.Adopt.Title"));
if (folder is null) return;
await Shell.Services.ArchiveSetup.AdoptAsync(folder);
await RefreshAsync();
}
/// <summary>Writes the selected rows as CSV (UTF-8, invariant numbers) into a chosen folder.</summary>
private async Task ExportListAsync()
{
var chosen = SelectedItems().Select(i => i.Sequence).ToList();
if (chosen.Count == 0) return;
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Library.Export.Title"));
if (folder is null) return;
var path = Path.Combine(folder, $"Titano sequences {DateTime.Now:yyyy-MM-dd HHmm}.csv");
var csv = Csv(chosen);
await Task.Run(() => AtomicFile.WriteAllText(path, csv));
Shell.Notify(Loc.L("Library.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
}
/// <summary>RFC 4180 CSV of sequences (header in English: it is a data file).</summary>
public static string Csv(IEnumerable<Sequence> sequences)
{
var inv = CultureInfo.InvariantCulture;
var sb = new StringBuilder("title,first_capture,last_capture,camera_make,camera_model,frames,bytes,folder,tags\r\n");
foreach (var s in sequences)
{
sb.Append(Field(s.DisplayTitle)).Append(',')
.Append(s.FirstCapture?.ToString("yyyy-MM-dd HH:mm:ss", inv)).Append(',')
.Append(s.LastCapture?.ToString("yyyy-MM-dd HH:mm:ss", inv)).Append(',')
.Append(Field(s.CameraMake)).Append(',')
.Append(Field(s.CameraModel)).Append(',')
.Append(s.FrameCount.ToString(inv)).Append(',')
.Append(s.TotalBytes.ToString(inv)).Append(',')
.Append(Field(s.Folder)).Append(',')
.Append(Field(string.Join(';', s.Tags))).Append("\r\n");
}
return sb.ToString();
static string Field(string? value)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
// Formula-looking values are prefixed so spreadsheets do not execute them.
if (value[0] is '=' or '+' or '-' or '@') value = "'" + value;
return value.IndexOfAny([',', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
}
}
/// <summary>Option labels and row texts follow a language switch without reloading.</summary>
private void OnCultureChanged(object? sender, EventArgs e)
{
_suppressReload = true;
try
{
var status = _status.Value;
var sort = _sort.Value;
Statuses = BuildStatusOptions();
Sorts = BuildSortOptions();
Years = [AnyYear(), .. Years.Skip(1)];
Cameras = [AnyCamera(), .. Cameras.Skip(1)];
Tags = [AnyTag(), .. Tags.Skip(1)];
_status = Statuses.First(o => o.Value == status);
_sort = Sorts.First(o => o.Value == sort);
_year = _year.IsAny ? Years[0] : _year;
_camera = _camera.IsAny ? Cameras[0] : _camera;
_tag = _tag.IsAny ? Tags[0] : _tag;
foreach (var item in Items) item.Update(item.Sequence);
}
finally
{
_suppressReload = false;
}
OnAllPropertiesChanged();
}
private static string YearText(int year) => year.ToString(CultureInfo.InvariantCulture);
private static FilterOption<int?> AnyYear() => new(null, Loc.L("Library.Filter.AnyYear"), Loc.L("Library.Filter.Year"), IsAny: true);
private static FilterOption<string?> AnyCamera() => new(null, Loc.L("Library.Filter.AnyCamera"), Loc.L("Library.Filter.Camera"), IsAny: true);
private static FilterOption<string?> AnyTag() => new(null, Loc.L("Library.Filter.AnyTag"), Loc.L("Library.Filter.Tags"), IsAny: true);
private static IReadOnlyList<FilterOption<StatusFilter>> BuildStatusOptions() =>
[
new(StatusFilter.Any, Loc.L("Library.Filter.AnyStatus"), Loc.L("Library.Filter.Status"), IsAny: true),
.. Enum.GetValues<StatusFilter>().Where(s => s != StatusFilter.Any)
.Select(s => new FilterOption<StatusFilter>(s, Loc.L("Library.Filter.Status." + s), Loc.L("Library.Filter.Status." + s))),
];
private static IReadOnlyList<FilterOption<SequenceSort>> BuildSortOptions() =>
[.. Enum.GetValues<SequenceSort>().Select(s => new FilterOption<SequenceSort>(s, Loc.L("Library.Sort." + s), Loc.L("Library.Sort." + s)))];
}
-164
View File
@@ -1,164 +0,0 @@
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,12 @@
using System.Windows.Input;
using Titano.App.Shell;
using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
/// <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));
}
+114 -3
View File
@@ -2,8 +2,119 @@
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}" />
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
xmlns:srv="clr-namespace:Titano.App.Server">
<UserControl.Resources>
<Style x:Key="Text.RowLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}">
<Setter Property="MinWidth" Value="60" />
<Setter Property="Margin" Value="0,0,10,0" />
</Style>
<Style x:Key="Text.Dot" TargetType="TextBlock">
<Setter Property="Text" Value="·" />
<Setter Property="Foreground" Value="{DynamicResource Brush.TextFaint}" />
<Setter Property="Margin" Value="8,0" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</UserControl.Resources>
<!-- Server.html: the connection panel; the render-node panel (right) and the sync table (below) join later. -->
<Grid Margin="20,16,20,12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border Style="{StaticResource Border.Panel}" Padding="16,14">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Address, servers found on the LAN, connect / disconnect. -->
<TextBlock Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Label.Server}" />
<DockPanel Grid.Column="1" LastChildFill="True">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Connect}" Command="{Binding ConnectCommand}"
ToolTip="{l:Loc Tooltips.Server.Connect}" Margin="10,0,0,0" MinWidth="96"
Visibility="{Binding IsDisconnected, Converter={StaticResource BoolToVisibility}}" />
<Button DockPanel.Dock="Right" Content="{l:Loc Server.Disconnect}" Command="{Binding DisconnectCommand}" ToolTip="{l:Loc Tooltips.Server.Disconnect}"
Margin="10,0,0,0" MinWidth="96" Visibility="{Binding IsConnected, Converter={StaticResource BoolToVisibility}}" />
<Button x:Name="KnownButton" DockPanel.Dock="Right" Style="{StaticResource Button.Icon}" Margin="10,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.ChevronDown}"
IsEnabled="{Binding HasKnownServers}" Click="OnShowKnown" ToolTip="{l:Loc Tooltips.Server.Found}" AutomationProperties.Name="{l:Loc Server.Found}">
<Button.ContextMenu>
<ContextMenu ItemsSource="{Binding KnownServers}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Address}" />
<Setter Property="InputGestureText" Value="{Binding Name}" />
<Setter Property="Command" Value="{Binding DataContext.UseServerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<Setter Property="CommandParameter" Value="{Binding}" />
<Setter Property="ToolTip" Value="{l:Loc Tooltips.Server.UseFound}" />
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</Button.ContextMenu>
</Button>
<TextBox x:Name="AddressBox" Text="{Binding Address, UpdateSourceTrigger=PropertyChanged}" ui:Field.Placeholder="{l:Loc Server.AddressPlaceholder}"
ToolTip="{l:Loc Tooltips.Server.Address}" AutomationProperties.Name="{l:Loc Server.Label.Server}" IsEnabled="{Binding IsDisconnected}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding ConnectCommand}" />
</TextBox.InputBindings>
</TextBox>
</DockPanel>
<!-- Status: state · server · version · latency · trusted certificate. -->
<TextBlock Grid.Row="1" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Label.Status}" Margin="0,12,10,0" />
<WrapPanel Grid.Row="1" Grid.Column="1" Margin="0,12,0,0" VerticalAlignment="Center">
<ui:StatusGlyph Kind="{Binding StatusKind}" Text="{Binding StatusText}" FontSize="13" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Server.Status}" />
<StackPanel Orientation="Horizontal" Visibility="{Binding ServerText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<TextBlock Style="{StaticResource Text.Dot}" />
<TextBlock Text="{Binding ServerText}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
</StackPanel>
<StackPanel Orientation="Horizontal" Visibility="{Binding CertificateText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<TextBlock Style="{StaticResource Text.Dot}" />
<TextBlock Text="{Binding CertificateText}" VerticalAlignment="Center" ToolTip="{Binding CertificateToolTip}" />
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Server.Certificate}" Command="{Binding CertificateCommand}"
ToolTip="{l:Loc Tooltips.Server.Certificate}" Height="24" Margin="10,0,0,0" />
</StackPanel>
<StackPanel Orientation="Horizontal" Visibility="{Binding ErrorText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<TextBlock Style="{StaticResource Text.Dot}" />
<ui:StatusGlyph Kind="Error" Text="{Binding ErrorText}" FontSize="13" VerticalAlignment="Center" />
</StackPanel>
</WrapPanel>
<!-- Account: user · role · quota · sign out. -->
<TextBlock Grid.Row="2" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Label.Account}" Margin="0,12,10,0"
Visibility="{Binding IsConnected, Converter={StaticResource BoolToVisibility}}" />
<DockPanel Grid.Row="2" Grid.Column="1" Margin="0,12,0,0" LastChildFill="False" Visibility="{Binding IsConnected, Converter={StaticResource BoolToVisibility}}">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Server.SignOut}" Command="{Binding SignOutCommand}" ToolTip="{l:Loc Tooltips.Server.SignOut}" />
<Border Width="28" Height="28" CornerRadius="14" Background="{DynamicResource Brush.Card}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="1">
<TextBlock Text="{Binding Initial}" FontWeight="SemiBold" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<TextBlock Text="{Binding Username}" Margin="10,0,0,0" VerticalAlignment="Center" />
<TextBlock Style="{StaticResource Text.Dot}" />
<TextBlock Text="{Binding RoleText}" ToolTip="{Binding RoleToolTip}" VerticalAlignment="Center" />
<StackPanel Orientation="Horizontal" Visibility="{Binding HasQuota, Converter={StaticResource BoolToVisibility}}">
<TextBlock Style="{StaticResource Text.Dot}" />
<ProgressBar Width="160" Maximum="1" Value="{Binding QuotaFraction, Mode=OneWay}" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Server.Quota}" />
</StackPanel>
<TextBlock Text="{Binding QuotaText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" VerticalAlignment="Center"
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Server.Quota}" />
</DockPanel>
<!-- Options of this PC. -->
<Border Grid.Row="3" Grid.ColumnSpan="2" Margin="0,14,0,0" Padding="0,10,0,0" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0">
<WrapPanel>
<CheckBox Content="{l:Loc Server.RenderNode}" IsChecked="{Binding RenderNodeOptIn}" ToolTip="{l:Loc Tooltips.Server.RenderNode}" Margin="0,0,22,0" />
</WrapPanel>
</Border>
</Grid>
</Border>
</Grid>
</UserControl>
@@ -1,8 +1,20 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
namespace Titano.App.Sections;
public partial class ServerView : UserControl
{
public ServerView() => InitializeComponent();
/// <summary>The ▾ button opens the list of servers found on the LAN under itself.</summary>
private void OnShowKnown(object sender, RoutedEventArgs e)
{
if (KnownButton.ContextMenu is not { } menu) return;
menu.DataContext = DataContext;
menu.PlacementTarget = KnownButton;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
}
+209
View File
@@ -0,0 +1,209 @@
using System.ComponentModel;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.App.Server;
using Titano.App.Shell;
using Titano.Core.Localization;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
/// <summary>
/// Server, connection part (BRIEF §12.7, Server.html): address with LAN-discovered servers, connect with
/// trust-on-first-use and login, status (name, version, latency, certificate), account and quota, sign out, and
/// the render-node opt-in. The sync table and render-node panel join this screen later.
/// </summary>
public sealed class ServerViewModel : SectionViewModel
{
private string _address;
private string? _errorText;
private ServerSession? _session;
public ServerViewModel(ShellViewModel shell)
: base(SectionKey.Server, "Icon.Server")
{
Shell = shell;
_address = ServerAddress.Display(shell.Services.Settings.ServerUrl);
ConnectCommand = new AsyncRelayCommand(ConnectAsync, () => !IsBusy && !IsConnected && Address.Trim().Length > 0);
DisconnectCommand = new RelayCommand(() => Session.Disconnect(), () => IsConnected);
SignOutCommand = new AsyncRelayCommand(SignOutAsync, () => IsConnected);
UseServerCommand = new RelayCommand(p =>
{
if (p is DiscoveredServer s) Address = s.Address;
else if (p is string text) Address = text;
});
CertificateCommand = new RelayCommand(ShowCertificate, () => Fingerprint is not null);
}
public ShellViewModel Shell { get; }
private ServerSession Session => _session ?? Shell.Services.Server;
public ICommand ConnectCommand { get; }
public ICommand DisconnectCommand { get; }
public ICommand SignOutCommand { get; }
public ICommand UseServerCommand { get; }
public ICommand CertificateCommand { get; }
/// <summary>Servers found on the LAN plus recently used ones, for the ▾ list.</summary>
public IEnumerable<DiscoveredServer> KnownServers =>
Session.Discovered.Concat(Shell.Services.Settings.RecentServers
.Where(r => !Session.Discovered.Any(d => d.Address.Equals(r, StringComparison.OrdinalIgnoreCase)))
.Select(r => new DiscoveredServer(r, r)));
public bool HasKnownServers => KnownServers.Any();
public string Address
{
get => _address;
set
{
if (Set(ref _address, value ?? string.Empty)) CommandManager.InvalidateRequerySuggested();
}
}
public bool IsBusy => Session.IsBusy;
public bool IsConnected => Session.IsConnected;
public bool IsDisconnected => !Session.IsConnected;
/// <summary>One sentence about the last failure; null when none.</summary>
public string? ErrorText
{
get => _errorText;
private set => Set(ref _errorText, value);
}
// ---- Status row ----
public StatusKind StatusKind => IsConnected ? StatusKind.Online : IsBusy ? StatusKind.Running : ErrorText is null ? StatusKind.Offline : StatusKind.Error;
public string StatusText => IsConnected ? Loc.L("Server.Status.Connected")
: IsBusy ? Loc.L("Server.Status.Connecting")
: Session.HasSavedSession ? Loc.L("Server.Status.Disconnected")
: Loc.L("Server.Status.NotConnected");
/// <summary>"Studio NAS · v1.3.0 · 14 ms".</summary>
public string? ServerText
{
get
{
if (!IsConnected || Session.Flow.Info is not { } info) return null;
var parts = new List<string> { info.Name, Loc.L("Server.Version", info.Version) };
if (Session.Flow.Latency is { } latency) parts.Add(Loc.L("Server.Latency", Math.Max(1, (int)Math.Round(latency.TotalMilliseconds))));
return string.Join(" · ", parts);
}
}
/// <summary>Fingerprint of the trusted self-signed certificate; null for a publicly valid certificate.</summary>
public string? Fingerprint => IsConnected ? Session.TrustOf(Session.Flow.Info?.TlsFingerprint)?.Fingerprint : null;
/// <summary>"TLS 9A:3C:71:E0:… trusted 2026-09-01".</summary>
public string? CertificateText => Fingerprint is { } fp && Session.TrustOf(fp) is { } trust
? Loc.L("Server.Certificate.Trusted", ServerSession.ShortFingerprint(fp), Formatting.Date(trust.TrustedAt))
: null;
public string CertificateToolTip => Loc.L("Tooltips.Server.CertificateTrusted");
// ---- Account row ----
public string? Username => Session.User?.Username;
public string Initial => Username is { Length: > 0 } u ? char.ToUpper(u[0], Loc.Culture).ToString() : string.Empty;
public string? RoleText => Session.User?.Role is { } role ? KnownRole(role) is { } known ? Loc.L("Server.Role." + known) : role : null;
public string? RoleToolTip => Session.User?.Role is { } role && KnownRole(role) is { } known ? Loc.L("Tooltips.Server.Role." + known) : null;
public bool HasQuota => Session.User is { QuotaBytes: > 0 };
public double QuotaFraction => Session.User is { QuotaBytes: > 0 } u ? Math.Clamp((double)u.UsedBytes / u.QuotaBytes, 0, 1) : 0;
/// <summary>"2.1 TB of 5 TB", or the used bytes when unlimited.</summary>
public string? QuotaText => Session.User is not { } u ? null
: u.QuotaBytes > 0 ? Loc.L("Server.Quota", Formatting.Bytes(u.UsedBytes), Formatting.Bytes(u.QuotaBytes))
: Loc.L("Server.QuotaUnlimited", Formatting.Bytes(u.UsedBytes));
// ---- Options ----
public bool RenderNodeOptIn
{
get => Shell.Services.Settings.RenderNodeOptIn;
set
{
if (Shell.Services.Settings.RenderNodeOptIn == value) return;
Shell.Services.Settings.RenderNodeOptIn = value;
Shell.Services.SaveSettings();
OnPropertyChanged();
}
}
/// <summary>Re-reads values another screen changed (Settings › Server).</summary>
public void Refresh() => OnPropertyChanged(nameof(RenderNodeOptIn));
/// <summary>Restores the saved session and starts listening for LAN servers.</summary>
public async Task AttachAsync()
{
_session = Shell.Services.Server;
_session.PropertyChanged += OnSessionChanged;
_session.Discovered.CollectionChanged += (_, _) =>
{
OnPropertyChanged(nameof(KnownServers));
OnPropertyChanged(nameof(HasKnownServers));
if (Address.Length == 0 && Session.Discovered.Count > 0) Address = Session.Discovered[0].Address;
};
if (!Shell.Services.Environment.IsCapture) _session.StartDiscovery();
await _session.RestoreAsync();
if (_session.Flow.Error is not ConnectError.None and var error && !_session.IsConnected) ErrorText = ServerSession.ErrorText(error);
}
public override void Dispose()
{
if (_session is not null) _session.PropertyChanged -= OnSessionChanged;
base.Dispose();
}
private async Task ConnectAsync()
{
ErrorText = null;
var connected = await Session.ConnectAsync(Address, Shell.Services.Dialogs);
if (connected)
{
Address = ServerAddress.Display(Session.SavedAddress);
return;
}
if (Session.Flow.Error is not ConnectError.None and var error) ErrorText = ServerSession.ErrorText(error);
}
private async Task SignOutAsync()
{
await Session.SignOutAsync();
ErrorText = null;
}
private void ShowCertificate()
{
if (Fingerprint is not { } fingerprint) return;
var forget = Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Server.Certificate.Title"),
Message = Loc.L("Server.Certificate.Message"),
Detail = ServerSession.FormatFingerprint(fingerprint),
DetailToolTip = Loc.L("Tooltips.Server.Fingerprint"),
SafeText = Loc.L("Server.Certificate.Keep"),
SafeToolTip = Loc.L("Tooltips.Server.KeepTrust"),
ActionText = Loc.L("Server.Certificate.Forget"),
ActionToolTip = Loc.L("Tooltips.Server.ForgetTrust"),
IsDestructive = true,
});
if (!forget) return;
Session.Disconnect();
Session.Forget(fingerprint);
}
private void OnSessionChanged(object? sender, PropertyChangedEventArgs e)
{
OnAllPropertiesChanged();
CommandManager.InvalidateRequerySuggested();
}
/// <summary>The <see cref="Core.Model.UserRole"/> name of a server role, or null for a role this build does not know.</summary>
private static string? KnownRole(string role) =>
Enum.TryParse<Core.Model.UserRole>(role, ignoreCase: true, out var parsed) ? parsed.ToString() : null;
}
+316 -70
View File
@@ -3,86 +3,332 @@
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">
xmlns:shell="clr-namespace:Titano.App.Shell"
xmlns:st="clr-namespace:Titano.App.Settings">
<UserControl.Resources>
<Style x:Key="Page" TargetType="StackPanel">
<Setter Property="Visibility" Value="Collapsed" />
</Style>
<Style x:Key="Slider.Budget" TargetType="Slider" BasedOn="{StaticResource {x:Type Slider}}">
<Setter Property="ui:ControlState.Accent" Value="{DynamicResource Brush.Sun}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsMemoryAuto}" Value="True">
<Setter Property="ui:ControlState.Accent" Value="{DynamicResource Brush.Accent}" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="Button.Reset" TargetType="Button" BasedOn="{StaticResource Button.IconSubtle}">
<Setter Property="Width" Value="24" />
<Setter Property="Height" Value="24" />
<Setter Property="MinWidth" Value="24" />
<Setter Property="ui:ControlState.CornerRadius" Value="12" />
<Setter Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.Reset}" />
</Style>
</UserControl.Resources>
<Grid Margin="20,16,20,16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
<ColumnDefinition Width="{StaticResource Width.SettingsList}" />
<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>
<!-- Section list: search, sections, settings as JSON. -->
<DockPanel>
<TextBox DockPanel.Dock="Top" Margin="0,0,0,8" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
ui:Field.Placeholder="{l:Loc Settings.Search}" ToolTip="{l:Loc Tooltips.Settings.Search}" AutomationProperties.Name="{l:Loc Settings.Search}" />
<StackPanel DockPanel.Dock="Bottom">
<Button Content="{l:Loc Settings.Export}" Command="{Binding ExportSettingsCommand}" ToolTip="{l:Loc Tooltips.Settings.Export}" HorizontalAlignment="Stretch" Margin="0,0,0,8" />
<Button Content="{l:Loc Settings.Import}" Command="{Binding ImportSettingsCommand}" ToolTip="{l:Loc Tooltips.Settings.Import}" HorizontalAlignment="Stretch" />
</StackPanel>
<ListBox ItemsSource="{Binding VisiblePages}" SelectedItem="{Binding SelectedPageItem}" ItemContainerStyle="{StaticResource ListBoxItem.Section}"
ScrollViewer.VerticalScrollBarVisibility="Auto" AutomationProperties.Name="{l:Loc Shell.Nav.Settings}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type st:SettingsPageItem}">
<TextBlock Text="{Binding Label}" ToolTip="{Binding ToolTip}" TextTrimming="CharacterEllipsis" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
<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>
<DockPanel>
<TextBlock DockPanel.Dock="Top" Text="{Binding PageTitle}" Style="{StaticResource Text.PageTitle}" Margin="0,0,0,18" />
<Border DockPanel.Dock="Bottom" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" Padding="0,12,0,0" Margin="0,12,0,0">
<Button Style="{StaticResource Button.Subtle}" HorizontalAlignment="Right" Content="{l:Loc Settings.ResetSection}" Command="{Binding ResetSectionCommand}"
ToolTip="{l:Loc Tooltips.Settings.ResetSection}" BorderBrush="{DynamicResource Brush.Stroke}" Foreground="{DynamicResource Brush.TextMuted}" />
</Border>
<!-- 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" />
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
<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}" />
<!-- ================= General ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=General}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Language}">
<ComboBox Width="240" HorizontalAlignment="Left" ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}" DisplayMemberPath="Name"
ToolTip="{l:Loc Tooltips.Settings.Language}" AutomationProperties.Name="{l:Loc Settings.General.Language}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Theme}">
<WrapPanel VerticalAlignment="Center" Margin="0,4,0,0">
<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}" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Usage}">
<CheckBox Content="{l:Loc Settings.General.UsageCounts}" IsChecked="{Binding UsageCounts}" ToolTip="{l:Loc Tooltips.Settings.UsageCounts}" Margin="0,4,0,0" />
</HeaderedContentControl>
</StackPanel>
<!-- ================= Archive ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Archive}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Root}">
<WrapPanel>
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding ArchiveRoot.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ArchiveRoot}" ToolTip="{Binding ArchiveRoot.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Archive.Root}" />
<Button Style="{StaticResource Button.Icon}" Margin="10,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Command="{Binding BrowseArchiveCommand}"
ToolTip="{l:Loc Tooltips.Settings.BrowseArchive}" AutomationProperties.Name="{l:Loc Settings.Browse}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding ArchiveFreeText}" Margin="10,0,0,0" ToolTip="{l:Loc Tooltips.Settings.ArchiveFree}" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Folders}">
<TextBox Style="{StaticResource TextBox.SettingMono}" Text="{Binding FolderTemplate.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding FolderTemplate}" ToolTip="{Binding FolderTemplate.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Archive.Folders}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Files}">
<TextBox Style="{StaticResource TextBox.SettingMono}" Text="{Binding FileTemplate.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding FileTemplate}" ToolTip="{Binding FileTemplate.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Archive.Files}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Preview}">
<ItemsControl ItemsSource="{Binding PreviewNames}" Focusable="False" Margin="0,7,0,0" ToolTip="{l:Loc Tooltips.Settings.Preview}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontFamily="{StaticResource Font.Mono}" FontSize="12" Foreground="{DynamicResource Brush.TextMuted}" LineHeight="20" TextTrimming="CharacterEllipsis" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Proxies}">
<ComboBox Width="140" HorizontalAlignment="Left" ItemsSource="{Binding ProxySizes}" SelectedItem="{Binding SelectedProxySize}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Settings.Proxies}" AutomationProperties.Name="{l:Loc Settings.Archive.Proxies}" />
</HeaderedContentControl>
</StackPanel>
<!-- ================= Rendering (Settings.html) ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Rendering}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.Quality}">
<ComboBox Width="160" HorizontalAlignment="Left" ItemsSource="{Binding Qualities}" SelectedItem="{Binding SelectedQuality}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Settings.Quality}" AutomationProperties.Name="{l:Loc Settings.Rendering.Quality}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.Memory}">
<WrapPanel>
<Slider Style="{StaticResource Slider.Budget}" Width="320" Minimum="{Binding MemoryMinimum}" Maximum="{Binding MemoryMaximum}" Value="{Binding MemoryBudget}"
TickFrequency="1" IsSnapToTickEnabled="True" SmallChange="1" LargeChange="2" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Settings.Memory}" AutomationProperties.Name="{l:Loc Settings.Rendering.Memory}" />
<TextBlock Text="{Binding MemoryText}" Margin="12,0,0,0" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding InstalledText}" Margin="12,0,0,0" />
<Button Style="{StaticResource Button.AutoPill}" Content="{Binding MemoryAutoText}" Margin="12,0,0,0" ToolTip="{l:Loc Tooltips.Settings.MemoryAuto}"
Visibility="{Binding IsMemoryAuto, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Reset}" Margin="12,0,0,0" Command="{Binding ResetMemoryCommand}" ToolTip="{l:Loc Tooltips.Settings.MemoryReset}"
AutomationProperties.Name="{l:Loc Settings.BackToAuto}"
Visibility="{Binding IsMemoryAuto, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.Parallelism}">
<WrapPanel>
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding Parallelism.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding Parallelism}" ToolTip="{Binding Parallelism.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Rendering.Parallelism}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding CoresText}" Margin="12,0,0,0" />
<Button Style="{StaticResource Button.AutoPill}" Content="{Binding ParallelismAutoText}" Margin="12,0,0,0" ToolTip="{l:Loc Tooltips.Settings.ParallelismAuto}"
Visibility="{Binding IsParallelismAuto, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Reset}" Margin="12,0,0,0" Command="{Binding ResetParallelismCommand}" ToolTip="{l:Loc Tooltips.Settings.ParallelismReset}"
AutomationProperties.Name="{l:Loc Settings.BackToAuto}"
Visibility="{Binding IsParallelismAuto, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<CheckBox Content="{l:Loc Settings.Rendering.Background}" IsChecked="{Binding BackgroundPriority}" ToolTip="{l:Loc Tooltips.Settings.Background}"
Margin="24,0,0,0" VerticalAlignment="Center" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.Hardware}">
<WrapPanel Margin="0,4,0,0">
<RadioButton GroupName="Hardware" Content="{l:Loc Settings.Rendering.PreferHardware}" IsChecked="{Binding IsPreferHardware}" ToolTip="{l:Loc Tooltips.Settings.PreferHardware}" Margin="0,0,18,0" />
<RadioButton GroupName="Hardware" Content="{l:Loc Settings.Rendering.SoftwareOnly}" IsChecked="{Binding IsSoftwareOnly}" ToolTip="{l:Loc Tooltips.Settings.SoftwareOnly}" Margin="0,0,18,0" />
<RadioButton GroupName="Hardware" Content="{l:Loc Settings.Rendering.PreviewsOnly}" IsChecked="{Binding IsHardwareForPreviews}" ToolTip="{l:Loc Tooltips.Settings.PreviewsOnly}" />
</WrapPanel>
</HeaderedContentControl>
<!-- Encoders on this PC -->
<DockPanel Margin="0,4,0,8" LastChildFill="False">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Settings.Rendering.SelfTest}" Command="{Binding SelfTestCommand}"
ToolTip="{l:Loc Tooltips.Settings.SelfTest}" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Settings.Rendering.Redetect}" Command="{Binding RedetectCommand}"
ToolTip="{l:Loc Tooltips.Settings.Redetect}" />
<TextBlock Text="{l:Loc Settings.Rendering.Encoders}" FontWeight="SemiBold" VerticalAlignment="Center" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding AdapterText}" Margin="10,0,0,0" ToolTip="{l:Loc Tooltips.Settings.Adapter}" />
</DockPanel>
<Border Style="{StaticResource Border.Card}">
<StackPanel>
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="110" />
<ColumnDefinition Width="1.4*" MinWidth="160" />
<ColumnDefinition Width="90" />
<ColumnDefinition Width="120" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Rendering.Column.Codec}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Rendering.Column.Encoder}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Rendering.Column.TenBit}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Rendering.Column.Max}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Rendering.Column.SelfTest}" Margin="10,0,0,0" />
</Grid>
</Border>
<ItemsControl ItemsSource="{Binding Encoders}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type st:EncoderRowViewModel}">
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Height="36" Padding="14,0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="110" />
<ColumnDefinition Width="1.4*" MinWidth="160" />
<ColumnDefinition Width="90" />
<ColumnDefinition Width="120" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Codec}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Name}" Margin="10,0,0,0" ToolTip="{Binding Row.Name}" />
<TextBlock x:Name="TenBit" Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding TenBitText}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextFaint}" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding MaxText}" Margin="10,0,0,0" />
<ui:StatusGlyph Grid.Column="4" Kind="{Binding ResultKind}" Text="{Binding ResultText}" ToolTip="{Binding ResultToolTip}" FontSize="13"
VerticalAlignment="Center" Margin="10,0,0,0" Visibility="{Binding HasResult, Converter={StaticResource BoolToVisibility}}" />
</Grid>
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding HasTenBit}" Value="True">
<Setter TargetName="TenBit" Property="Foreground" Value="{DynamicResource Brush.Success}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
</StackPanel>
<!-- ================= Storage ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Storage}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Storage.Folder}">
<WrapPanel>
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding CacheFolder.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding CacheFolder}" ToolTip="{Binding CacheFolder.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Storage.Folder}" />
<Button Style="{StaticResource Button.Icon}" Margin="10,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Command="{Binding BrowseCacheCommand}"
ToolTip="{l:Loc Tooltips.Settings.BrowseCache}" AutomationProperties.Name="{l:Loc Settings.Browse}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding CacheUsageText}" Margin="10,0,0,0" ToolTip="{l:Loc Tooltips.Settings.CacheUsage}" />
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Settings.Storage.Clear}" Command="{Binding ClearCacheCommand}" ToolTip="{l:Loc Tooltips.Settings.ClearCacheAsk}"
Margin="10,0,0,0" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Storage.Thumbnails}">
<WrapPanel>
<TextBox Style="{StaticResource TextBox.Number}" Width="96" Text="{Binding ThumbnailMemory.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ThumbnailMemory}" ToolTip="{Binding ThumbnailMemory.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Storage.Thumbnails}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Storage.ThumbnailsUnit}" Margin="12,0,0,0" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Storage.Limit}">
<WrapPanel>
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding CacheLimit.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding CacheLimit}" ToolTip="{Binding CacheLimit.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Storage.Limit}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Storage.LimitUnit}" Margin="12,0,0,0" />
</WrapPanel>
</HeaderedContentControl>
</StackPanel>
<!-- ================= Server ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Server}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Default}">
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding DefaultServer.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding DefaultServer}" ToolTip="{Binding DefaultServer.ToolTip}" ui:Field.Placeholder="{l:Loc Server.AddressPlaceholder}"
AutomationProperties.Name="{l:Loc Settings.Server.Default}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.RenderNode}">
<CheckBox Content="{l:Loc Server.RenderNode}" IsChecked="{Binding RenderNodeOptIn}" ToolTip="{l:Loc Tooltips.Server.RenderNode}" Margin="0,4,0,0" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Certificates}">
<Grid>
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Server.NoCertificates}" Margin="0,7,0,0" VerticalAlignment="Top"
Visibility="{Binding HasCertificates, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<ItemsControl ItemsSource="{Binding Certificates}" Focusable="False" Visibility="{Binding HasCertificates, Converter={StaticResource BoolToVisibility}}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type st:TrustedCertificateRow}">
<Grid Height="36">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="160" />
<ColumnDefinition Width="170" />
<ColumnDefinition Width="110" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Server}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Fingerprint}" FontFamily="{StaticResource Font.Mono}" FontSize="12"
ToolTip="{Binding FullFingerprint}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding TrustedText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" />
<Button Grid.Column="3" Style="{StaticResource Button.Row}" Content="{l:Loc Server.Certificate.Forget}" Command="{Binding ForgetCommand}"
ToolTip="{l:Loc Tooltips.Server.ForgetTrust}" Margin="10,0,0,0" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</HeaderedContentControl>
</StackPanel>
<!-- ================= Updates ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Updates}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Updates}">
<CheckBox Content="{l:Loc Settings.General.CheckOnStart}" IsChecked="{Binding CheckForUpdates}" ToolTip="{l:Loc Tooltips.Settings.CheckForUpdates}" Margin="0,4,0,0" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Updates.Latest}">
<WrapPanel>
<Button Content="{l:Loc About.Update.Check}" Command="{Binding Shell.About.CheckCommand}" ToolTip="{l:Loc Tooltips.About.Check}" />
<ui:StatusGlyph Kind="{Binding Shell.About.UpdateKind}" Text="{Binding Shell.About.UpdateText}" FontSize="13" VerticalAlignment="Center" Margin="12,0,0,0"
Visibility="{Binding Shell.About.HasUpdateText, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Link}" Content="{l:Loc About.Update.Download}" Command="{Binding Shell.About.DownloadCommand}" ToolTip="{l:Loc Tooltips.About.Download}"
VerticalAlignment="Center" Margin="12,0,0,0" FontSize="13"
Visibility="{Binding Shell.About.IsUpdateAvailable, Converter={StaticResource BoolToVisibility}}" />
</WrapPanel>
</HeaderedContentControl>
</StackPanel>
<!-- ================= Advanced ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Advanced}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Portable}">
<TextBlock Text="{Binding PortableText}" Margin="0,7,0,0" ToolTip="{l:Loc Tooltips.Settings.Portable}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.DataFolder}">
<WrapPanel>
<TextBox Style="{StaticResource TextBox.Setting}" IsReadOnly="True" Text="{Binding DataFolder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.DataFolder}"
AutomationProperties.Name="{l:Loc Settings.Advanced.DataFolder}" />
<Button Content="{l:Loc Common.Open}" Command="{Binding OpenDataFolderCommand}" ToolTip="{l:Loc Tooltips.Settings.OpenDataFolder}" Margin="10,0,0,0" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Logs}">
<WrapPanel>
<TextBox Style="{StaticResource TextBox.Setting}" IsReadOnly="True" Text="{Binding LogsFolder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.LogsFolder}"
AutomationProperties.Name="{l:Loc Settings.Advanced.Logs}" />
<Button Content="{l:Loc Common.Open}" Command="{Binding OpenLogsCommand}" ToolTip="{l:Loc Tooltips.Common.OpenLogs}" Margin="10,0,0,0" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Diagnostics}">
<Button HorizontalAlignment="Left" Content="{l:Loc Settings.Advanced.ExportBundle}" Command="{Binding ExportDiagnosticsCommand}" ToolTip="{l:Loc Tooltips.Settings.Diagnostics}"
ui:ButtonIcon.Glyph="{StaticResource Icon.Export}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Backup}">
<Button HorizontalAlignment="Left" Content="{l:Loc Settings.Advanced.BackupNow}" Command="{Binding BackupDatabaseCommand}" ToolTip="{l:Loc Tooltips.Settings.Backup}"
ui:ButtonIcon.Glyph="{StaticResource Icon.Database}" />
</HeaderedContentControl>
</StackPanel>
</Grid>
</StackPanel>
</Grid>
</ScrollViewer>
</DockPanel>
</Border>
</Grid>
</UserControl>
@@ -1,7 +1,4 @@
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;
using Titano.Core.Localization;
namespace Titano.App.Sections;
@@ -9,14 +6,3 @@ 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,803 @@
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Text.Json;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
using Titano.Core.Localization;
using Titano.Core.Naming;
using Titano.Data;
using Titano.Ui.Mvvm;
using Titano.Ui.Theming;
namespace Titano.App.Sections;
/// <summary>
/// Settings (BRIEF §12.8, Settings.html): a searchable section list on the left, the controls of one section on
/// the right, tooltips only. Text fields commit on Enter and revert on Esc; invalid input shows the Error border
/// with the reason in the tooltip. Everything persists through <see cref="AppSettings"/> (atomic writes).
/// </summary>
public sealed class SettingsViewModel : SectionViewModel
{
private readonly AppSettings _s;
private SettingsPage _page = SettingsPage.General;
private string _searchText = string.Empty;
private IReadOnlyList<SettingsPageItem> _visiblePages;
private IReadOnlyList<string> _previewNames = [];
private string? _archiveFreeText;
private string? _cacheUsageText;
private string? _adapterText;
private bool _isDetecting;
private bool _isTesting;
private CancellationTokenSource? _selfTest;
public SettingsViewModel(ShellViewModel shell)
: base(SectionKey.Settings, "Icon.Settings")
{
Shell = shell;
_s = shell.Services.Settings;
AllPages =
[
new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", "Settings.General.Usage"]),
new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies"]),
new(SettingsPage.Rendering, ["Settings.Rendering.Quality", "Settings.Rendering.Memory", "Settings.Rendering.Parallelism", "Settings.Rendering.Hardware", "Settings.Rendering.Encoders"]),
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
new(SettingsPage.Updates, ["Settings.General.CheckOnStart"]),
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.Diagnostics", "Settings.Advanced.Backup"]),
];
_visiblePages = AllPages;
// ---- Archive ----
ArchiveRoot = new EditableField(_s.LastArchivePath ?? string.Empty, v => v.Length == 0 ? null : ArchiveLocations.Validate(v), v =>
{
_s.LastArchivePath = v.Length == 0 ? null : Path.GetFullPath(v);
Save();
UpdateArchiveFree();
}, () => Loc.L("Tooltips.Settings.ArchiveRoot"));
FolderTemplate = new EditableField(_s.FolderTemplate, v => NamingPreview.Validate(v, isFolder: true), v =>
{
_s.FolderTemplate = v;
Save();
}, () => Loc.L("Tooltips.Settings.FolderTemplate"));
FileTemplate = new EditableField(_s.FileTemplate, v => NamingPreview.Validate(v, isFolder: false), v =>
{
_s.FileTemplate = v;
Save();
}, () => Loc.L("Tooltips.Settings.FileTemplate"));
FolderTemplate.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
};
FileTemplate.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
};
// ---- Rendering ----
InstalledGb = Math.Max(2, (int)Math.Round(GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 1e9));
Parallelism = new EditableField(EffectiveParallelism.ToString(CultureInfo.CurrentCulture), ValidateParallelism, v =>
{
var n = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
_s.Parallelism = n == ParallelismAuto ? null : n;
Save();
OnPropertyChanged(nameof(IsParallelismAuto));
}, () => Loc.L("Tooltips.Settings.Parallelism"));
// ---- Storage ----
CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
{
var full = Path.GetFullPath(v);
_s.CacheFolder = full.Equals(Shell.Services.Environment.CacheDirectory, StringComparison.OrdinalIgnoreCase) ? null : full;
Save();
_ = UpdateCacheUsageAsync();
}, () => Loc.L("Tooltips.Settings.CacheFolder"));
ThumbnailMemory = new EditableField(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 100, 100_000), v =>
{
_s.ThumbnailMemoryItems = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
Save();
if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
}, () => Loc.L("Tooltips.Settings.ThumbnailMemory"));
CacheLimit = new EditableField(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 1, 100_000), v =>
{
_s.CacheLimitGb = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
Save();
}, () => Loc.L("Tooltips.Settings.CacheLimit"));
// ---- Server ----
DefaultServer = new EditableField(ServerAddress.Display(_s.ServerUrl), v => v.Trim().Length == 0 || ServerAddress.TryParse(v, out _) ? null : Loc.L("Errors.Server.Address"), v =>
{
var display = v.Trim().Length == 0 ? null : ServerAddress.TryParse(v, out var uri) ? ServerAddress.Display(uri) : null;
if (!string.Equals(display, ServerAddress.Display(_s.ServerUrl), StringComparison.OrdinalIgnoreCase))
{
// A saved token belongs to the old server: never send it elsewhere.
_s.ProtectedToken = null;
}
_s.ServerUrl = display;
Save();
}, () => Loc.L("Tooltips.Settings.DefaultServer"));
SelectPageCommand = new RelayCommand(p =>
{
if (p is SettingsPageItem item) Page = item.Page;
else if (p is SettingsPage page) Page = page;
});
BrowseArchiveCommand = new RelayCommand(() => Browse(ArchiveRoot, "Settings.Archive.PickTitle"));
BrowseCacheCommand = new RelayCommand(() => Browse(CacheFolder, "Settings.Storage.PickTitle"));
ResetMemoryCommand = new RelayCommand(() => MemoryBudget = MemoryAuto, () => !IsMemoryAuto);
ResetParallelismCommand = new RelayCommand(() =>
{
_s.Parallelism = null;
Save();
Parallelism.Load(ParallelismAuto.ToString(CultureInfo.CurrentCulture));
OnPropertyChanged(nameof(IsParallelismAuto));
}, () => !IsParallelismAuto);
RedetectCommand = new AsyncRelayCommand(DetectEncodersAsync, () => !_isDetecting && !_isTesting);
SelfTestCommand = new AsyncRelayCommand(SelfTestAsync, () => !_isDetecting && !_isTesting && Encoders.Any(e => e.Row.CanSelfTest));
ClearCacheCommand = new AsyncRelayCommand(ClearCacheAsync);
OpenDataFolderCommand = new RelayCommand(() => ShellActions.Reveal(DataFolder));
OpenLogsCommand = new RelayCommand(() => ShellActions.Reveal(LogsFolder));
ExportDiagnosticsCommand = new AsyncRelayCommand(ExportDiagnosticsAsync);
BackupDatabaseCommand = new AsyncRelayCommand(BackupDatabaseAsync, () => Shell.Services.Database is not null);
ResetSectionCommand = new RelayCommand(ResetSection);
ExportSettingsCommand = new AsyncRelayCommand(ExportSettingsAsync);
ImportSettingsCommand = new AsyncRelayCommand(ImportSettingsAsync);
Loc.CultureChanged += OnCultureChanged;
UpdatePreview();
UpdateArchiveFree();
}
public ShellViewModel Shell { get; }
public IReadOnlyList<SettingsPageItem> AllPages { get; }
// ---------------- Navigation ----------------
public ICommand SelectPageCommand { get; }
public SettingsPage Page
{
get => _page;
set
{
if (!Set(ref _page, value)) return;
OnPropertyChanged(nameof(SelectedPageItem));
OnPropertyChanged(nameof(PageTitle));
if (value == SettingsPage.Rendering && Encoders.Count == 0 && !_isDetecting) _ = DetectEncodersAsync();
if (value == SettingsPage.Storage) _ = UpdateCacheUsageAsync();
}
}
public SettingsPageItem? SelectedPageItem
{
get => AllPages.First(p => p.Page == _page);
set
{
if (value is not null) Page = value.Page;
}
}
public string PageTitle => Loc.L("Settings.Page." + _page);
/// <summary>Filters the section list.</summary>
public string SearchText
{
get => _searchText;
set
{
if (!Set(ref _searchText, value ?? string.Empty)) return;
var text = _searchText.Trim();
VisiblePages = text.Length == 0 ? AllPages : [.. AllPages.Where(p => p.Matches(text))];
if (VisiblePages.Count > 0 && VisiblePages.All(p => p.Page != _page)) Page = VisiblePages[0].Page;
}
}
public IReadOnlyList<SettingsPageItem> VisiblePages
{
get => _visiblePages;
private set => Set(ref _visiblePages, value);
}
// ---------------- General ----------------
public IReadOnlyList<LanguageOption> Languages => LanguageCatalog.Available;
public LanguageOption SelectedLanguage
{
get => LanguageCatalog.Match(Loc.Culture);
set
{
if (value is null || value == SelectedLanguage) return;
_s.Language = value.Code;
UiLanguage.Apply(value.Code);
Save();
}
}
public bool IsDarkTheme
{
get => _s.Theme == AppTheme.Dark;
set
{
if (value) ApplyTheme(AppTheme.Dark);
}
}
public bool IsLightTheme
{
get => _s.Theme == AppTheme.Light;
set
{
if (value) ApplyTheme(AppTheme.Light);
}
}
public bool IsSystemTheme
{
get => _s.Theme == AppTheme.System;
set
{
if (value) ApplyTheme(AppTheme.System);
}
}
public bool UsageCounts
{
get => _s.AnonymousUsageCounts;
set
{
if (_s.AnonymousUsageCounts == value) return;
_s.AnonymousUsageCounts = value;
Save();
OnPropertyChanged();
}
}
// ---------------- Archive ----------------
public EditableField ArchiveRoot { get; }
public EditableField FolderTemplate { get; }
public EditableField FileTemplate { get; }
public ICommand BrowseArchiveCommand { get; }
/// <summary>"1.8 TB free".</summary>
public string? ArchiveFreeText
{
get => _archiveFreeText;
private set => Set(ref _archiveFreeText, value);
}
/// <summary>The first three names the templates produce (live while typing).</summary>
public IReadOnlyList<string> PreviewNames
{
get => _previewNames;
private set => Set(ref _previewNames, value);
}
public IReadOnlyList<SettingsOption<int>> ProxySizes =>
[
new(1280, "1280"),
new(1920, "1920"),
new(2560, "2560"),
new(0, Loc.L("Settings.Archive.FullSize")),
];
public SettingsOption<int> SelectedProxySize
{
get => ProxySizes.FirstOrDefault(p => p.Value == _s.ProxyLongEdge) ?? ProxySizes[1];
set
{
if (value is null || value.Value == _s.ProxyLongEdge) return;
_s.ProxyLongEdge = value.Value;
Save();
OnPropertyChanged();
}
}
// ---------------- Rendering ----------------
public IReadOnlyList<SettingsOption<QualityProfile>> Qualities =>
[.. Enum.GetValues<QualityProfile>().Select(q => new SettingsOption<QualityProfile>(q, Loc.L("Settings.Rendering.Quality." + q)))];
public SettingsOption<QualityProfile> SelectedQuality
{
get => Qualities.First(q => q.Value == _s.Quality);
set
{
if (value is null || value.Value == _s.Quality) return;
_s.Quality = value.Value;
Save();
OnPropertyChanged();
}
}
/// <summary>Installed memory in GB (rounded).</summary>
public int InstalledGb { get; }
public int MemoryMinimum => 2;
public int MemoryMaximum => Math.Max(MemoryMinimum, InstalledGb - 2);
/// <summary>Auto: a quarter of installed memory.</summary>
public int MemoryAuto => Math.Clamp(InstalledGb / 4, MemoryMinimum, MemoryMaximum);
public double MemoryBudget
{
get => _s.MemoryBudgetGb ?? MemoryAuto;
set
{
var gb = (int)Math.Round(Math.Clamp(value, MemoryMinimum, MemoryMaximum));
int? stored = gb == MemoryAuto ? null : gb;
if (stored == _s.MemoryBudgetGb) return;
_s.MemoryBudgetGb = stored;
Save();
OnPropertyChanged();
OnPropertyChanged(nameof(MemoryText));
OnPropertyChanged(nameof(IsMemoryAuto));
}
}
public bool IsMemoryAuto => _s.MemoryBudgetGb is null;
public string MemoryText => Loc.L("Settings.Rendering.Gb", (int)MemoryBudget);
public string InstalledText => Loc.L("Settings.Rendering.Installed", InstalledGb);
public string MemoryAutoText => Loc.L("Settings.Rendering.AutoValue", MemoryAuto);
public ICommand ResetMemoryCommand { get; }
public EditableField Parallelism { get; }
public int LogicalCores => Environment.ProcessorCount;
/// <summary>Auto: cores minus four so the UI stays responsive.</summary>
public int ParallelismAuto => Math.Max(1, LogicalCores - 4);
private int EffectiveParallelism => _s.Parallelism ?? ParallelismAuto;
public bool IsParallelismAuto => _s.Parallelism is null;
public string CoresText => Loc.L("Settings.Rendering.Cores", LogicalCores);
public string ParallelismAutoText => Loc.L("Settings.Rendering.AutoValue", ParallelismAuto);
public ICommand ResetParallelismCommand { get; }
public bool BackgroundPriority
{
get => _s.BackgroundPriority;
set
{
if (_s.BackgroundPriority == value) return;
_s.BackgroundPriority = value;
Save();
OnPropertyChanged();
}
}
public bool IsPreferHardware
{
get => _s.HardwareEncoding == HardwarePreference.PreferHardware;
set => SetHardware(value, HardwarePreference.PreferHardware);
}
public bool IsSoftwareOnly
{
get => _s.HardwareEncoding == HardwarePreference.SoftwareOnly;
set => SetHardware(value, HardwarePreference.SoftwareOnly);
}
public bool IsHardwareForPreviews
{
get => _s.HardwareEncoding == HardwarePreference.HardwareForPreviews;
set => SetHardware(value, HardwarePreference.HardwareForPreviews);
}
public ObservableCollection<EncoderRowViewModel> Encoders { get; } = [];
/// <summary>"NVIDIA GeForce RTX 4070 · 3 encoders".</summary>
public string? AdapterText
{
get => _adapterText;
private set => Set(ref _adapterText, value);
}
public bool IsDetecting
{
get => _isDetecting;
private set => Set(ref _isDetecting, value);
}
public ICommand RedetectCommand { get; }
public ICommand SelfTestCommand { get; }
// ---------------- Storage ----------------
public EditableField CacheFolder { get; }
public EditableField ThumbnailMemory { get; }
public EditableField CacheLimit { get; }
public ICommand BrowseCacheCommand { get; }
public ICommand ClearCacheCommand { get; }
/// <summary>"1.4 GB used · 612 GB free".</summary>
public string? CacheUsageText
{
get => _cacheUsageText;
private set => Set(ref _cacheUsageText, value);
}
// ---------------- Server ----------------
public EditableField DefaultServer { get; }
public bool RenderNodeOptIn
{
get => _s.RenderNodeOptIn;
set
{
if (_s.RenderNodeOptIn == value) return;
_s.RenderNodeOptIn = value;
Save();
OnPropertyChanged();
Shell.Server.Refresh();
}
}
public ObservableCollection<TrustedCertificateRow> Certificates { get; } = [];
public bool HasCertificates => Certificates.Count > 0;
// ---------------- Updates ----------------
public bool CheckForUpdates
{
get => _s.CheckForUpdates;
set
{
if (_s.CheckForUpdates == value) return;
_s.CheckForUpdates = value;
Save();
OnPropertyChanged();
}
}
// ---------------- Advanced ----------------
public string DataFolder => Shell.Services.Environment.DataDirectory;
public string LogsFolder => Shell.Services.Environment.LogDirectory;
public string PortableText => Loc.L(Shell.Services.Environment.IsPortable ? "Settings.Advanced.PortableOn" : "Settings.Advanced.PortableOff");
public ICommand OpenDataFolderCommand { get; }
public ICommand OpenLogsCommand { get; }
public ICommand ExportDiagnosticsCommand { get; }
public ICommand BackupDatabaseCommand { get; }
// ---------------- Footer ----------------
public ICommand ResetSectionCommand { get; }
public ICommand ExportSettingsCommand { get; }
public ICommand ImportSettingsCommand { get; }
/// <summary>Loads what needs the services (certificates, cache usage).</summary>
public void Attach()
{
try
{
CacheStore.Prepare(Shell.Services.Environment.CacheDirectory);
}
catch (IOException ex)
{
Log.Warning("settings", "Cache folder not prepared", ex);
}
LoadCertificates();
Shell.Services.Server.PropertyChanged += (_, _) => LoadCertificates();
}
public override void Dispose()
{
Loc.CultureChanged -= OnCultureChanged;
_selfTest?.Cancel();
base.Dispose();
}
// ---------------- Implementation ----------------
private void Save() => Shell.Services.SaveSettings();
private void ApplyTheme(AppTheme theme)
{
_s.Theme = theme;
ThemeManager.Apply(theme);
Save();
OnPropertyChanged(nameof(IsDarkTheme));
OnPropertyChanged(nameof(IsLightTheme));
OnPropertyChanged(nameof(IsSystemTheme));
}
private void SetHardware(bool value, HardwarePreference preference)
{
if (!value || _s.HardwareEncoding == preference) return;
_s.HardwareEncoding = preference;
Save();
OnPropertyChanged(nameof(IsPreferHardware));
OnPropertyChanged(nameof(IsSoftwareOnly));
OnPropertyChanged(nameof(IsHardwareForPreviews));
}
private void UpdatePreview() => PreviewNames = NamingPreview.FirstNames(FolderTemplate.Text, FileTemplate.Text);
private void UpdateArchiveFree()
{
var path = _s.LastArchivePath;
ArchiveFreeText = ArchiveLocations.FreeSpace(path) is { } free ? Loc.L("Settings.Archive.Free", Formatting.Bytes(free)) : null;
}
private string? ValidateParallelism(string text) => ValidateInt(text, 1, Math.Max(1, LogicalCores * 2));
private static string? ValidateInt(string text, int min, int max) =>
int.TryParse(text.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture, out var n) && n >= min && n <= max
? null
: Loc.L("Errors.Number.Range", min.ToString("N0", Loc.Culture), max.ToString("N0", Loc.Culture));
private void Browse(EditableField field, string titleKey)
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L(titleKey), field.Value.Length > 0 ? field.Value : null);
if (folder is null) return;
field.Text = folder;
field.Commit();
}
/// <summary>Lists the encoders again (Re-detect).</summary>
public async Task DetectEncodersAsync()
{
IsDetecting = true;
try
{
var inventory = Shell.Services.Encoders;
var (adapter, rows) = await Task.Run(() => (inventory.Adapter(), inventory.Detect()));
Encoders.Clear();
foreach (var row in rows) Encoders.Add(new EncoderRowViewModel(row));
var hardware = rows.Count(r => r.Hardware);
AdapterText = string.Join(" · ", new[] { adapter, Loc.Plural("Settings.Rendering.EncoderCount", rows.Count(r => r.Source == EncoderSource.MediaFoundation)) }
.Where(s => !string.IsNullOrEmpty(s)));
Log.Info("settings", $"{rows.Count} encoder(s), {hardware} hardware");
}
catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or PlatformNotSupportedException or DllNotFoundException)
{
Log.Warning("settings", "Encoders could not be detected", ex);
}
finally
{
IsDetecting = false;
CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>Encodes the synthetic test clip with every encoder in turn (Run self-test).</summary>
public async Task SelfTestAsync()
{
_isTesting = true;
_selfTest = new CancellationTokenSource();
try
{
foreach (var row in Encoders.Where(r => r.Row.CanSelfTest).ToList())
{
row.IsTesting = true;
try
{
row.Result = await Shell.Services.Encoders.SelfTestAsync(row.Row, _selfTest.Token);
}
finally
{
row.IsTesting = false;
}
}
}
finally
{
_isTesting = false;
_selfTest.Dispose();
_selfTest = null;
CommandManager.InvalidateRequerySuggested();
}
}
private async Task UpdateCacheUsageAsync()
{
var folder = CacheStore.Folder(Shell.Services.Environment, _s);
var (used, free) = await Task.Run(() => (CacheStore.Size(folder), ArchiveLocations.FreeSpace(folder)));
CacheUsageText = free is { } f
? Loc.L("Settings.Storage.Usage", Formatting.Bytes(used), Formatting.Bytes(f))
: Loc.L("Settings.Storage.Used", Formatting.Bytes(used));
}
private async Task ClearCacheAsync()
{
var folder = CacheStore.Folder(Shell.Services.Environment, _s);
var confirmed = Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Settings.Storage.ClearTitle"),
Message = Loc.L("Settings.Storage.ClearMessage"),
Detail = folder,
DetailToolTip = Loc.L("Tooltips.Settings.CacheFolder"),
SafeText = Loc.L("Settings.Storage.Keep"),
SafeToolTip = Loc.L("Tooltips.Settings.KeepCache"),
ActionText = Loc.L("Settings.Storage.Clear"),
ActionToolTip = Loc.L("Tooltips.Settings.ClearCache"),
IsDestructive = true,
});
if (!confirmed) return;
Shell.Services.Thumbnails?.Clear();
if (!CacheStore.IsOwned(folder))
{
Shell.Notify(Loc.L("Settings.Storage.NotOwned"));
return;
}
var freed = await Task.Run(() => CacheStore.Clear(folder));
Shell.Notify(Loc.L("Settings.Storage.Cleared", Formatting.Bytes(freed)));
await UpdateCacheUsageAsync();
}
private async Task ExportDiagnosticsAsync()
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Advanced.DiagnosticsTitle"));
if (folder is null) return;
var extra = Encoders.Select(e => $"Encoder {e.Codec} {e.Row.DisplayName} hardware={e.Row.Hardware} selftest={e.ResultText}");
var path = await DiagnosticsBundle.CreateAsync(Shell.Services.Environment, folder, extra.ToList());
Shell.Notify(Loc.L("Settings.Advanced.DiagnosticsDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
}
private async Task BackupDatabaseAsync()
{
if (Shell.Services.Database is not { } db) return;
try
{
var path = await db.BackupAsync(Shell.Services.Environment.BackupDirectory);
Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
}
catch (Exception ex) when (ex is DatabaseException or IOException or NotSupportedException)
{
Shell.ReportError(ex);
}
}
private void ResetSection()
{
var defaults = new AppSettings();
switch (_page)
{
case SettingsPage.General:
_s.AnonymousUsageCounts = defaults.AnonymousUsageCounts;
ApplyTheme(defaults.Theme);
_s.Language = null;
UiLanguage.Apply(null);
break;
case SettingsPage.Archive:
_s.FolderTemplate = defaults.FolderTemplate;
_s.FileTemplate = defaults.FileTemplate;
_s.ProxyLongEdge = defaults.ProxyLongEdge;
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
UpdatePreview();
break;
case SettingsPage.Rendering:
_s.Quality = defaults.Quality;
_s.MemoryBudgetGb = null;
_s.Parallelism = null;
_s.BackgroundPriority = defaults.BackgroundPriority;
_s.HardwareEncoding = defaults.HardwareEncoding;
Parallelism.Load(ParallelismAuto.ToString(CultureInfo.CurrentCulture));
break;
case SettingsPage.Storage:
_s.CacheFolder = null;
_s.ThumbnailMemoryItems = defaults.ThumbnailMemoryItems;
_s.CacheLimitGb = defaults.CacheLimitGb;
CacheFolder.Load(CacheStore.Folder(Shell.Services.Environment, _s));
ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
break;
case SettingsPage.Server:
_s.RenderNodeOptIn = defaults.RenderNodeOptIn;
break;
case SettingsPage.Updates:
_s.CheckForUpdates = defaults.CheckForUpdates;
break;
case SettingsPage.Advanced:
break;
}
Save();
OnAllPropertiesChanged();
}
private async Task ExportSettingsAsync()
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Export.Title"));
if (folder is null) return;
var copy = _s.Clone();
// Secrets and machine-bound values stay on this PC.
copy.ProtectedToken = null;
copy.Window = null;
var path = Path.Combine(folder, $"Titano settings {DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json");
await Task.Run(() => AtomicFile.WriteAllText(path, copy.ToJson()));
Shell.Notify(Loc.L("Settings.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
}
private async Task ImportSettingsAsync()
{
var file = Shell.Services.Dialogs.PickJsonFile(Loc.L("Settings.Import.Title"));
if (file is null) return;
AppSettings? imported;
try
{
imported = AppSettings.Parse(await File.ReadAllTextAsync(file));
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
Log.Warning("settings", $"Settings file {file} not imported", ex);
imported = null;
}
if (imported is null)
{
Shell.Notify(Loc.L("Errors.Settings.Import"));
return;
}
// Everything but the session, the window and the first-run flag.
imported.ProtectedToken = _s.ProtectedToken;
imported.ServerUrl = _s.ServerUrl;
imported.Window = _s.Window;
imported.FirstRunCompleted = _s.FirstRunCompleted;
foreach (var property in typeof(AppSettings).GetProperties().Where(p => p.CanRead && p.CanWrite))
property.SetValue(_s, property.GetValue(imported));
Save();
ThemeManager.Apply(_s.Theme);
UiLanguage.Apply(_s.Language);
ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
Parallelism.Load(EffectiveParallelism.ToString(CultureInfo.CurrentCulture));
CacheFolder.Load(CacheStore.Folder(Shell.Services.Environment, _s));
ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
UpdatePreview();
LoadCertificates();
OnAllPropertiesChanged();
Shell.Notify(Loc.L("Settings.Import.Done"));
}
private void LoadCertificates()
{
Certificates.Clear();
foreach (var certificate in _s.TrustedCertificates.OrderByDescending(c => c.TrustedAt))
{
Certificates.Add(new TrustedCertificateRow(certificate, new RelayCommand(() =>
{
Shell.Services.Server.Forget(certificate.Fingerprint);
LoadCertificates();
})));
}
OnPropertyChanged(nameof(HasCertificates));
}
private void OnCultureChanged(object? sender, EventArgs e)
{
foreach (var page in AllPages) page.Refresh();
foreach (var row in Encoders) row.Refresh();
ArchiveRoot.Refresh();
FolderTemplate.Refresh();
FileTemplate.Refresh();
Parallelism.Refresh();
CacheFolder.Refresh();
ThumbnailMemory.Refresh();
CacheLimit.Refresh();
DefaultServer.Refresh();
UpdateArchiveFree();
LoadCertificates();
}
}
+115
View File
@@ -0,0 +1,115 @@
<UserControl x:Class="Titano.App.Sections.WelcomeView"
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">
<UserControl.Resources>
<!-- Welcome.html choice: 68 px card, highlighted = accent border with the AccentSelected glow. -->
<Style x:Key="RadioButton.Choice" TargetType="RadioButton">
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Ring}" />
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
<Setter Property="Height" Value="68" />
<Setter Property="Margin" Value="0,0,0,10" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RadioButton">
<Grid>
<Border x:Name="Glow" Margin="-3" CornerRadius="11" BorderThickness="3" BorderBrush="{DynamicResource Brush.AccentSelected}" Visibility="Collapsed" />
<Border x:Name="Bd" Background="{DynamicResource Brush.Card}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="1"
CornerRadius="{StaticResource Radius.Card}" Padding="16,0">
<ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Stretch" />
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.CardHover}" />
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
<Setter TargetName="Glow" Property="Visibility" Value="Visible" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="Text.ChoiceTitle" TargetType="TextBlock">
<Setter Property="FontSize" Value="14" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
</Style>
<Style x:Key="Text.ChoiceDetail" TargetType="TextBlock">
<Setter Property="FontSize" Value="12" />
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
<Setter Property="Margin" Value="0,3,0,0" />
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
</Style>
</UserControl.Resources>
<Border Width="640" Background="{DynamicResource Brush.Surface}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="1"
CornerRadius="{StaticResource Radius.Dialog}" Padding="32,28" Effect="{StaticResource Shadow.Popup}">
<StackPanel>
<DockPanel LastChildFill="True">
<ComboBox DockPanel.Dock="Right" VerticalAlignment="Top" MinWidth="120" ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}"
DisplayMemberPath="Name" ToolTip="{l:Loc Tooltips.Welcome.Language}" AutomationProperties.Name="{l:Loc Settings.General.Language}" />
<ui:BrandMarkIcon Width="56" Height="56" ShowPlate="True" />
<StackPanel Margin="16,0,16,0" VerticalAlignment="Center">
<TextBlock Text="{l:Loc Shell.Welcome.Title}" FontSize="20" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" />
<TextBlock Text="{l:Loc Shell.Welcome.Question}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,4,0,0" TextTrimming="CharacterEllipsis" />
</StackPanel>
</DockPanel>
<StackPanel Margin="0,20,0,0">
<!-- Create a local archive -->
<RadioButton Style="{StaticResource RadioButton.Choice}" GroupName="Welcome" IsChecked="{Binding IsLocal}" ToolTip="{l:Loc Tooltips.Welcome.Local}"
AutomationProperties.Name="{l:Loc Shell.Welcome.Local}">
<DockPanel>
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Subtle}" Content="{l:Loc Shell.Welcome.Change}" Command="{Binding ChangeRootCommand}"
ToolTip="{l:Loc Tooltips.Welcome.Change}" Foreground="{DynamicResource Brush.TextMuted}" />
<ui:Icon Glyph="{StaticResource Icon.Folder}" Size="24" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
<StackPanel Margin="14,0,8,0" VerticalAlignment="Center">
<TextBlock Style="{StaticResource Text.ChoiceTitle}" Text="{l:Loc Shell.Welcome.Local}" />
<TextBlock Style="{StaticResource Text.ChoiceDetail}" Text="{Binding LocalDetail}" Typography.NumeralAlignment="Tabular" />
</StackPanel>
</DockPanel>
</RadioButton>
<!-- Adopt an existing folder -->
<RadioButton Style="{StaticResource RadioButton.Choice}" GroupName="Welcome" IsChecked="{Binding IsAdopt}" ToolTip="{l:Loc Tooltips.Welcome.Adopt}"
AutomationProperties.Name="{l:Loc Shell.Welcome.Adopt}">
<DockPanel>
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Subtle}" Content="{l:Loc Shell.Welcome.Choose}" Command="{Binding ChooseAdoptCommand}"
ToolTip="{l:Loc Tooltips.Welcome.Choose}" Foreground="{DynamicResource Brush.TextMuted}" />
<ui:Icon Glyph="{StaticResource Icon.Archive}" Size="24" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" />
<StackPanel Margin="14,0,8,0" VerticalAlignment="Center">
<TextBlock Style="{StaticResource Text.ChoiceTitle}" Text="{l:Loc Shell.Welcome.Adopt}" />
<TextBlock Style="{StaticResource Text.ChoiceDetail}" Text="{Binding AdoptDetail}" Visibility="{Binding HasAdoptDetail, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</DockPanel>
</RadioButton>
<!-- Connect to a server -->
<RadioButton Style="{StaticResource RadioButton.Choice}" GroupName="Welcome" IsChecked="{Binding IsServer}" ToolTip="{l:Loc Tooltips.Welcome.Server}"
AutomationProperties.Name="{l:Loc Shell.Welcome.Server}" Margin="0">
<DockPanel>
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Online" Text="{l:Loc Shell.Welcome.Found}" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Welcome.Found}"
Visibility="{Binding IsServerDiscovered, Converter={StaticResource BoolToVisibility}}" />
<ui:Icon Glyph="{StaticResource Icon.Server}" Size="24" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" />
<StackPanel Margin="14,0,8,0" VerticalAlignment="Center">
<TextBlock Style="{StaticResource Text.ChoiceTitle}" Text="{l:Loc Shell.Welcome.Server}" />
<TextBlock Style="{StaticResource Text.ChoiceDetail}" Text="{Binding ServerDetail}" Visibility="{Binding HasServerDetail, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</DockPanel>
</RadioButton>
</StackPanel>
<DockPanel Margin="0,20,0,0" LastChildFill="False">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Height="36" Padding="22,0" Content="{l:Loc Shell.Welcome.Continue}"
Command="{Binding ContinueCommand}" ToolTip="{l:Loc Tooltips.Welcome.Continue}" IsDefault="True" />
<CheckBox Content="{l:Loc Shell.Welcome.Consent}" IsChecked="{Binding UsageCounts}" ToolTip="{l:Loc Tooltips.Settings.UsageCounts}" VerticalAlignment="Center"
Foreground="{DynamicResource Brush.TextMuted}" />
</DockPanel>
</StackPanel>
</Border>
</UserControl>
@@ -0,0 +1,8 @@
using System.Windows.Controls;
namespace Titano.App.Sections;
public partial class WelcomeView : UserControl
{
public WelcomeView() => InitializeComponent();
}
+231
View File
@@ -0,0 +1,231 @@
using System.Collections.Specialized;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
/// <summary>Where the time-lapses live (first run).</summary>
public enum WelcomeChoice
{
LocalArchive,
AdoptFolder,
Server,
}
/// <summary>
/// First run (BRIEF §12.1, Welcome.html): create a local archive, adopt an existing folder or connect to a server,
/// plus the language and the anonymous-usage consent. Shown once; the archive actions go through
/// <see cref="IArchiveSetup"/>.
/// </summary>
public sealed class WelcomeViewModel : LocalizedViewModel
{
private readonly ShellViewModel _shell;
private WelcomeChoice _choice = WelcomeChoice.LocalArchive;
private string _localRoot;
private string? _adoptFolder;
private bool _isBusy;
public WelcomeViewModel(ShellViewModel shell)
{
_shell = shell;
_localRoot = shell.Services.Settings.LastArchivePath ?? ArchiveLocations.SuggestRoot();
ChooseCommand = new RelayCommand(p =>
{
if (p is WelcomeChoice choice) Choice = choice;
else if (p is string name && Enum.TryParse<WelcomeChoice>(name, out var parsed)) Choice = parsed;
});
ChangeRootCommand = new RelayCommand(ChangeRoot);
ChooseAdoptCommand = new RelayCommand(() => PickAdoptFolder());
ContinueCommand = new AsyncRelayCommand(ContinueAsync, () => !_isBusy);
shell.Services.Server.Discovered.CollectionChanged += OnDiscovered;
if (!shell.Services.Environment.IsCapture) shell.Services.Server.StartDiscovery();
}
public ICommand ChooseCommand { get; }
public ICommand ChangeRootCommand { get; }
public ICommand ChooseAdoptCommand { get; }
public ICommand ContinueCommand { get; }
public WelcomeChoice Choice
{
get => _choice;
set
{
if (!Set(ref _choice, value)) return;
OnPropertyChanged(nameof(IsLocal));
OnPropertyChanged(nameof(IsAdopt));
OnPropertyChanged(nameof(IsServer));
}
}
public bool IsLocal
{
get => _choice == WelcomeChoice.LocalArchive;
set
{
if (value) Choice = WelcomeChoice.LocalArchive;
}
}
public bool IsAdopt
{
get => _choice == WelcomeChoice.AdoptFolder;
set
{
if (value) Choice = WelcomeChoice.AdoptFolder;
}
}
public bool IsServer
{
get => _choice == WelcomeChoice.Server;
set
{
if (value) Choice = WelcomeChoice.Server;
}
}
public string LocalRoot
{
get => _localRoot;
private set
{
if (Set(ref _localRoot, value)) OnPropertyChanged(nameof(LocalDetail));
}
}
/// <summary>"D:\TitanoArchive · 1.8 TB free".</summary>
public string LocalDetail => ArchiveLocations.FreeSpace(_localRoot) is { } free
? Loc.L("Shell.Welcome.Local.Detail", _localRoot, Formatting.Bytes(free))
: _localRoot;
/// <summary>The chosen folder to adopt; null until picked.</summary>
public string? AdoptDetail => _adoptFolder;
public bool HasAdoptDetail => _adoptFolder is not null;
/// <summary>The first server announced on the LAN (or the saved one).</summary>
public DiscoveredServer? FoundServer =>
_shell.Services.Server.Discovered.FirstOrDefault()
?? (_shell.Services.Settings.ServerUrl is { } saved ? new DiscoveredServer(saved, saved) : null);
/// <summary>"Studio NAS on this network · https://nas.local:8443".</summary>
public string? ServerDetail => FoundServer is { } s
? s.Name == s.Address ? s.Address : Loc.L("Shell.Welcome.Server.Found", s.Name, s.Address)
: null;
public bool HasServerDetail => ServerDetail is not null;
/// <summary>A server was heard on the LAN (the green dot).</summary>
public bool IsServerDiscovered => _shell.Services.Server.Discovered.Count > 0;
public IReadOnlyList<LanguageOption> Languages => LanguageCatalog.Available;
public LanguageOption SelectedLanguage
{
get => LanguageCatalog.Match(Loc.Culture);
set
{
if (value is null || value == SelectedLanguage) return;
_shell.Services.Settings.Language = value.Code;
UiLanguage.Apply(value.Code);
_shell.Services.SaveSettings();
}
}
public bool UsageCounts
{
get => _shell.Services.Settings.AnonymousUsageCounts;
set
{
_shell.Services.Settings.AnonymousUsageCounts = value;
OnPropertyChanged();
}
}
public bool IsBusy
{
get => _isBusy;
private set => Set(ref _isBusy, value);
}
/// <summary>Sample state for screenshots: a server heard on the LAN.</summary>
internal void ShowDiscovered(DiscoveredServer server)
{
if (!_shell.Services.Server.Discovered.Contains(server)) _shell.Services.Server.Discovered.Add(server);
}
public override void Dispose()
{
_shell.Services.Server.Discovered.CollectionChanged -= OnDiscovered;
base.Dispose();
}
private void OnDiscovered(object? sender, NotifyCollectionChangedEventArgs e)
{
OnPropertyChanged(nameof(FoundServer));
OnPropertyChanged(nameof(ServerDetail));
OnPropertyChanged(nameof(HasServerDetail));
OnPropertyChanged(nameof(IsServerDiscovered));
}
private void ChangeRoot()
{
var folder = _shell.Services.Dialogs.PickFolder(Loc.L("Shell.Welcome.Local.PickTitle"), LocalRoot);
if (folder is null) return;
LocalRoot = folder;
Choice = WelcomeChoice.LocalArchive;
}
private bool PickAdoptFolder()
{
var folder = _shell.Services.Dialogs.PickFolder(Loc.L("Library.Adopt.Title"));
if (folder is null) return false;
_adoptFolder = folder;
OnPropertyChanged(nameof(AdoptDetail));
OnPropertyChanged(nameof(HasAdoptDetail));
Choice = WelcomeChoice.AdoptFolder;
return true;
}
private async Task ContinueAsync()
{
IsBusy = true;
try
{
switch (_choice)
{
case WelcomeChoice.LocalArchive:
if (ArchiveLocations.Validate(LocalRoot) is { } problem)
{
_shell.Notify(problem);
return;
}
await _shell.Services.ArchiveSetup.CreateAsync(LocalRoot);
break;
case WelcomeChoice.AdoptFolder:
if (_adoptFolder is null && !PickAdoptFolder()) return;
await _shell.Services.ArchiveSetup.AdoptAsync(_adoptFolder!);
break;
case WelcomeChoice.Server:
if (FoundServer is { } server) _shell.Server.Address = server.Address;
break;
}
_shell.Services.SaveSettings();
_shell.CompleteWelcome();
Log.Info("app", $"First run completed: {_choice}");
if (_choice == WelcomeChoice.Server) _shell.Navigate(SectionKey.Server);
else await _shell.Library.RefreshAsync();
}
finally
{
IsBusy = false;
}
}
}