merge: Library after the review (trash, busy checks, keyboard timeline, delete dialog, remote cards)

This commit is contained in:
Claude committed 2026-10-06 21:18:20 +00:00
commit d3de5b86e3
65 files changed
+5610 -628

No files matched your search

@@ -395,6 +395,7 @@ public sealed class RetagDialogViewModel : ArchiveDialogViewModel
private async Task ApplyAsync()
{
var changes = Changes();
var (add, remove) = (Retag.Parse(Add.Text), Retag.Parse(Remove.Text));
var run = _run = new CancellationTokenSource();
var done = 0;
ClearError();
@@ -403,9 +404,10 @@ public sealed class RetagDialogViewModel : ArchiveDialogViewModel
{
for (; done < changes.Count && !run.IsCancellationRequested; done++)
{
var (s, tags) = changes[done];
var id = changes[done].Sequence.Id;
BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(done + 1), Formatting.Count(changes.Count));
await Task.Run(() => _archives.SetSequenceInfoAsync(s.Id, s.Title, tags, s.Rating, s.Notes));
// The tags as they are now (the set may predate an edit or a sync); title, rating and notes stay untouched.
await Task.Run(() => _archives.EditSequenceInfoAsync(id, info => info with { Tags = Retag.Apply(info.Tags, add, remove) }));
}
Log.Info("archive", $"Retag: {done} of {changes.Count} sequence(s) changed");
await _applied(done);
+253
View File
@@ -0,0 +1,253 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
xmlns:ar="clr-namespace:Titano.App.Archiving"
xmlns:infra="clr-namespace:Titano.App.Infrastructure"
xmlns:shell="clr-namespace:Titano.App.Shell">
<!-- In-window dialogs of the archive engine's operations, shared by the Archive manager and the Library. -->
<!-- Rows that only show text: focusable, so the arrow keys move through a long list. -->
<Style x:Key="ListBoxItem.Preview" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Inset}" />
<Setter Property="AutomationProperties.Name" Value="{Binding To}" />
<Setter Property="AutomationProperties.HelpText" Value="{Binding From}" />
</Style>
<!-- Dialog labels: a column at least 116 px wide that grows with the longest label (DESIGN §2: no fixed-width labels). -->
<Style x:Key="Text.DialogLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}">
<Setter Property="TextTrimming" Value="None" />
</Style>
<!-- A status line screen readers announce when it changes. -->
<Style x:Key="Text.Live" TargetType="TextBlock">
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
<Setter Property="AutomationProperties.LiveSetting" Value="Polite" />
</Style>
<!-- A dialog's failure: one sentence in the error colour with its glyph, the engine's own text in the tooltip, announced at once. -->
<Style x:Key="Status.DialogError" TargetType="ui:StatusGlyph" BasedOn="{StaticResource {x:Type ui:StatusGlyph}}">
<Setter Property="Kind" Value="Error" />
<Setter Property="FontSize" Value="12" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Text" Value="{Binding ErrorText}" />
<Setter Property="ToolTip" Value="{Binding ErrorToolTip}" />
<Setter Property="AutomationProperties.LiveSetting" Value="Assertive" />
<Setter Property="infra:LiveRegion.Text" Value="{Binding ErrorText}" />
<Setter Property="Visibility" Value="{Binding ErrorText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
</Style>
<!-- Dialog card (DESIGN §4: Surface, Stroke, radius 12, 24 px shadow, two buttons). -->
<Style x:Key="Border.Dialog" TargetType="Border">
<Setter Property="Background" Value="{DynamicResource Brush.Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Stroke}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="{StaticResource Radius.Dialog}" />
<Setter Property="Padding" Value="24,18,24,20" />
<Setter Property="Effect" Value="{StaticResource Shadow.Popup}" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<DataTemplate DataType="{x:Type ar:RebuildDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{l:Loc Archive.Rebuild.Heading}" Style="{StaticResource Text.Title}" />
<ItemsControl ItemsSource="{Binding FactRows}" Focusable="False" Margin="0,14,0,0" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:DialogFact}">
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="FactLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Label}" Style="{StaticResource Text.DialogLabel}" />
<TextBlock x:Name="Value" Grid.Column="1" Text="{Binding Value}" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}"
Typography.NumeralAlignment="Tabular" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsPath}" Value="True">
<Setter TargetName="Value" Property="FlowDirection" Value="LeftToRight" />
<Setter TargetName="Value" Property="HorizontalAlignment" Value="Left" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}"
Visibility="{Binding BusyText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,18,0,0">
<Button Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True" IsCancel="True"
MinWidth="96" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Rebuild.Start}" Command="{Binding RebuildCommand}" ToolTip="{Binding RebuildToolTip}"
MinWidth="96" Margin="8,0,0,0" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ar:RenameDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="720" MaxHeight="560">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<Grid Grid.Row="1" Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Archive.Rename.Template}" Style="{StaticResource Text.DialogLabel}" />
<!-- A naming template keeps its tokens and separators in order in every language. -->
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Mono}" FlowDirection="LeftToRight"
Text="{Binding Template.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Template}"
ToolTip="{Binding Template.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Rename.Template}" />
</Grid>
<TextBlock Grid.Row="2" Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,6" Typography.NumeralAlignment="Tabular" />
<ListBox Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.Preview}" MinHeight="120"
AutomationProperties.Name="{l:Loc Archive.Rename.Preview}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ar:RenameRow}">
<Grid Height="30" TextElement.FontSize="12">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="120" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" MinWidth="120" />
</Grid.ColumnDefinitions>
<TextBlock x:Name="From" Style="{StaticResource Text.Cell}" Text="{Binding From}" Foreground="{DynamicResource Brush.TextMuted}" ToolTip="{Binding From}" />
<ui:Icon Grid.Column="1" Glyph="{StaticResource Icon.Forward}" Margin="10,0" VerticalAlignment="Center" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock x:Name="To" Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding To}" ToolTip="{Binding To}" />
</Grid>
<DataTemplate.Triggers>
<!-- Move lists folders: paths stay left to right; Rename lists titles, which read in the language's direction. -->
<DataTrigger Binding="{Binding DataContext.Mode, RelativeSource={RelativeSource AncestorType=ListBox}}" Value="Folders">
<Setter TargetName="From" Property="FlowDirection" Value="LeftToRight" />
<Setter TargetName="From" Property="HorizontalAlignment" Value="Left" />
<Setter TargetName="To" Property="FlowDirection" Value="LeftToRight" />
<Setter TargetName="To" Property="HorizontalAlignment" Value="Left" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<DockPanel Grid.Row="4" Margin="0,16,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Rename.Apply}" Command="{Binding ApplyCommand}"
ToolTip="{Binding ApplyToolTip}" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True"
IsCancel="True" MinWidth="96" />
<Grid Margin="0,0,12,0">
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" Typography.NumeralAlignment="Tabular" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
</Grid>
</DockPanel>
</Grid>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ar:RetagDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Archive.Retag.Add}" Style="{StaticResource Text.DialogLabel}" />
<TextBox Grid.Column="1" Text="{Binding Add.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Add}"
ToolTip="{Binding Add.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Retag.Add}" />
<TextBlock Grid.Row="1" Text="{l:Loc Archive.Retag.Remove}" Style="{StaticResource Text.DialogLabel}" Margin="0,10,14,0" />
<TextBox Grid.Row="1" Grid.Column="1" Margin="0,10,0,0" Text="{Binding Remove.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding Remove}" ToolTip="{Binding Remove.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Retag.Remove}" />
</Grid>
<TextBlock Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,0" Typography.NumeralAlignment="Tabular" />
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Retag.Apply}" Command="{Binding ApplyCommand}"
ToolTip="{Binding ApplyToolTip}" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True"
IsCancel="True" MinWidth="96" />
<Grid Margin="0,0,12,0">
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" Typography.NumeralAlignment="Tabular" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
</Grid>
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<!-- Delete…: how far the dry run, then the move into the trash, has got; Cancel stops between two sequences. -->
<DataTemplate DataType="{x:Type ar:DeleteDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" />
<ProgressBar Maximum="1" Value="{Binding Progress, Mode=OneWay}" Margin="0,16,0,0" AutomationProperties.Name="{Binding Heading}"
AutomationProperties.HelpText="{Binding BusyText}" />
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True"
IsDefault="True" MinWidth="96" />
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" Typography.NumeralAlignment="Tabular"
Margin="0,0,12,0" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<!-- The archive's trash: deleted sequences, newest first, each with Restore. -->
<DataTemplate DataType="{x:Type ar:TrashDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="640" MaxHeight="520">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Row="1" Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,8,0,8" Typography.NumeralAlignment="Tabular" />
<!-- An empty trash is the summary sentence alone. -->
<ListBox Grid.Row="2" ItemsSource="{Binding Rows}" MinHeight="120" AutomationProperties.Name="{l:Loc Archive.Trash.List}" KeyboardNavigation.TabNavigation="Continue"
Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ar:TrashRowViewModel}">
<DockPanel Height="48">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Content="{l:Loc Archive.Trash.Restore}" Command="{Binding RestoreCommand}"
ToolTip="{l:Loc Tooltips.Archive.TrashRestore}" />
<TextBlock DockPanel.Dock="Right" Text="{Binding DeletedText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" Margin="12,0"
Typography.NumeralAlignment="Tabular" />
<StackPanel VerticalAlignment="Center">
<TextBlock Text="{Binding Title}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" ToolTip="{Binding Title}" />
<TextBlock Text="{Binding Detail}" Style="{StaticResource Text.Secondary}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Detail}"
Typography.NumeralAlignment="Tabular" />
</StackPanel>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<DockPanel Grid.Row="3" Margin="0,16,0,0">
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Close}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True"
IsDefault="True" MinWidth="96" />
<Grid Margin="0,0,12,0">
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
</Grid>
</DockPanel>
</Grid>
</Border>
</DataTemplate>
</ResourceDictionary>
+1 -1
View File
@@ -17,7 +17,7 @@ public static class ArchiveFailures
ArchiveOfflineException offline => Loc.L(offline.Availability == ArchiveAvailability.ReadOnly ? "Archive.Error.ReadOnly" : "Archive.Error.Offline",
Formatting.LeftToRight(offline.Root)),
// Already one localized sentence each.
LeaseUnavailableException or StaleRenamePlanException => ex.Message,
LeaseUnavailableException or NewerFormatException or StaleRenamePlanException or StaleDeletePlanException or SequenceInLibraryException => ex.Message,
UnauthorizedAccessException => Loc.L("Archive.Failed.Access"),
DatabaseException => Loc.L("Archive.Failed.Index"),
ArgumentException => Loc.L("Archive.Failed.Gone"),
+7 -2
View File
@@ -5,11 +5,11 @@ namespace Titano.App.Archiving;
/// <summary>
/// The Archive views that <c>--capture</c> renders (<c>archive-&lt;view&gt;-&lt;theme&gt;.png</c>) and the screen smoke
/// tests check, on the sample archive: the tree with figures and charts, the maintenance view with its reports, the
/// rebuild dialog, and the Move dialog with its dry run.
/// rebuild dialog, the Move dialog with its dry run, and the trash (Maintenance › Trash…) with deleted sequences.
/// </summary>
public static class ArchiveScenes
{
public static readonly IReadOnlyList<string> Views = ["overview", "maintenance", "rebuild", "move"];
public static readonly IReadOnlyList<string> Views = ["overview", "maintenance", "rebuild", "move", "trash"];
public static async Task ShowAsync(ShellViewModel shell, string view)
{
@@ -41,6 +41,11 @@ public static class ArchiveScenes
await move.PlanAsync();
}
break;
case "trash":
archive.ViewIndex = 1;
await archive.OpenTrashAsync();
if (archive.Dialog is TrashDialogViewModel trash && archive.SelectedArchive is { } shown) trash.Show(SampleReports.Trash(shown.Id, locations));
break;
default:
throw new ArgumentOutOfRangeException(nameof(view), view, "Unknown Archive view.");
}
@@ -0,0 +1,174 @@
using System.IO;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Ui.Mvvm;
namespace Titano.App.Archiving;
/// <summary>
/// "Delete…" of the Library and the Archive manager (BRIEF §0.2 rule 8, §12.2, §12.5) in an in-window dialog that says
/// how far it is and stops on Cancel: the archive engine's dry run, sequence by sequence; the destructive confirmation
/// that asks to type the number of sequences (DESIGN §4); then the move into the archives' trash, each sequence whole
/// or not at all. The toast that follows names what moved and brings it back.
/// </summary>
public sealed class DeleteDialogViewModel : ArchiveDialogViewModel
{
private readonly ShellViewModel _shell;
private readonly IReadOnlyList<Guid> _ids;
private CancellationTokenSource? _run;
private double _progress;
public DeleteDialogViewModel(ShellViewModel shell, IReadOnlyList<Guid> sequenceIds, Action<ArchiveDialogViewModel> close)
: base(close)
{
_shell = shell;
_ids = sequenceIds;
}
/// <summary>"Deleting 3 sequences".</summary>
public string Heading => Loc.Plural("Archive.Delete.Progress", _ids.Count);
/// <summary>0–1 of the dry run, then of the move.</summary>
public double Progress { get => _progress; private set => Set(ref _progress, value); }
protected override bool CanStop => _run is not null;
/// <summary>Stops the dry run, or the move after the sequence that is moving.</summary>
protected override void Stop() => _run?.Cancel();
public override void Dispose()
{
_run?.Cancel();
base.Dispose();
}
/// <summary>Plans, asks, deletes and offers to undo, then closes; true when something moved to the trash.</summary>
public async Task<bool> RunAsync()
{
using var run = _run = new CancellationTokenSource();
IsBusy = true;
try
{
if (_shell.Services.Archives is not { } archives || _ids.Count == 0) return false;
if (await PlanAsync(archives, run.Token) is not { } plan) return false;
if (DeletePlans.Request(plan) is not { } request)
{
_shell.Notify(Loc.L("Archive.Delete.Nothing"), string.Join(Environment.NewLine, DeletePlans.Blocked(plan, DeletePlans.BlockedLines)));
return false;
}
BusyText = null;
if (!_shell.Services.Dialogs.Confirm(request) || !await SequenceDeletion.CloseEditorAsync(_shell, plan)) return false;
return await DeleteAsync(archives, plan, run.Token);
}
finally
{
_run = null;
IsBusy = false;
Close();
}
}
/// <summary>The dry run; null when it was stopped or failed (said in a toast).</summary>
private async Task<DeletePlan?> PlanAsync(ArchiveService archives, CancellationToken cancellationToken)
{
var checking = new Progress<int>(n => Report("Archive.Delete.Checking", n, _ids.Count));
try
{
return await Task.Run(() => archives.PlanDeleteAsync(_ids, checking, cancellationToken), cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
{
Log.Warning("archive", "Delete dry run failed", ex);
_shell.Notify(Loc.L("Archive.Delete.Failed"), ArchiveFailures.Cause(ex));
return null;
}
}
/// <summary>
/// Moves the planned sequences; whatever moved before a stop or a failure is read back from the trash, so the toast
/// names it and offers to bring it back.
/// </summary>
private async Task<bool> DeleteAsync(ArchiveService archives, DeletePlan plan, CancellationToken cancellationToken)
{
var started = DateTimeOffset.UtcNow;
var moving = new Progress<int>(n => Report("Archive.Delete.Moving", n, plan.Steps.Count));
Report("Archive.Delete.Moving", 0, plan.Steps.Count);
Exception? failure = null;
try
{
await Task.Run(() => archives.DeleteAsync(plan, Environment.UserName, moving, cancellationToken), cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
Log.Info("archive", "Delete stopped between two sequences");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or StaleDeletePlanException or NewerFormatException
or ArgumentException or DatabaseException)
{
Log.Warning("archive", "Delete failed", ex);
failure = ex;
}
var moved = await MovedAsync(archives, plan, started);
var removed = await RemovedRowsAsync(plan);
Log.Info("archive", $"{moved.Count} sequence(s) moved to the trash, {removed} without a folder removed from the index");
await SequenceDeletion.RefreshAsync(_shell);
var undo = moved.Count == 0 ? null : new AsyncRelayCommand(() => SequenceDeletion.RestoreAsync(_shell, moved));
if (failure is not null)
_shell.Notify(Loc.L("Archive.Delete.Failed"), ArchiveFailures.Cause(failure), undo is null ? null : Loc.L("Archive.Delete.Undo"), Loc.L("Tooltips.Archive.DeleteUndo"),
undo is null ? null : () => undo.Execute(null));
else if (moved.Count > 0)
_shell.Notify(Loc.Plural("Archive.Delete.Done", moved.Count), Loc.L("Archive.Delete.Kept"), Loc.L("Archive.Delete.Undo"),
Loc.L("Tooltips.Archive.DeleteUndo"), () => undo!.Execute(null));
else if (removed > 0)
_shell.Notify(Loc.Plural("Archive.Delete.Removed", removed));
return moved.Count + removed > 0;
}
/// <summary>The trash entries this run made: the planned sequences that entered their archive's trash since it started.</summary>
private static async Task<IReadOnlyList<TrashEntry>> MovedAsync(ArchiveService archives, DeletePlan plan, DateTimeOffset started)
{
var planned = plan.Steps.Where(s => s.TrashFolder is not null).Select(s => s.Sequence.Id).ToHashSet();
var moved = new List<TrashEntry>();
foreach (var archive in plan.Steps.Where(s => s.TrashFolder is not null).Select(s => s.Sequence.ArchiveId).Distinct())
{
try
{
var entries = await Task.Run(() => archives.ListTrashAsync(archive));
moved.AddRange(entries.Where(e => planned.Contains(e.SequenceId) && e.DeletedAt >= started));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
{
Log.Warning("archive", "The trash could not be read after a delete", ex);
}
}
return moved;
}
/// <summary>Planned sequences without a folder (nothing to keep in a trash) whose rows are gone.</summary>
private async Task<int> RemovedRowsAsync(DeletePlan plan)
{
if (_shell.Services.Database is not { } db) return 0;
var removed = 0;
foreach (var step in plan.Steps.Where(s => s.TrashFolder is null))
{
if (await db.Sequences.GetAsync(step.Sequence.Id) is null) removed++;
}
return removed;
}
private void Report(string key, int done, int total)
{
BusyText = Loc.L(key, Formatting.Count(done), Formatting.Count(total));
Progress = total == 0 ? 0 : (double)done / total;
}
}
+51
View File
@@ -0,0 +1,51 @@
using System.Globalization;
using Titano.App.Infrastructure;
using Titano.Core.Localization;
using Titano.Data.Archiving;
namespace Titano.App.Archiving;
/// <summary>The words of a delete dry run (<see cref="DeletePlan"/>): the destructive confirmation and the lines of what cannot move.</summary>
public static class DeletePlans
{
/// <summary>Sequences that move, named one by one in the confirmation; the rest are counted.</summary>
public const int ListedLines = 6;
/// <summary>Sequences that cannot move, named one by one; the rest are counted. With <see cref="ListedLines"/> it keeps the confirmation within a 768 px screen.</summary>
public const int BlockedLines = 3;
/// <summary>The destructive confirmation of a plan; null when nothing in it can move.</summary>
public static ConfirmRequest? Request(DeletePlan plan)
{
if (plan.Steps.Count == 0) return null;
var count = plan.Steps.Count.ToString(CultureInfo.InvariantCulture);
var lines = plan.Steps.Take(ListedLines).Select(s => Loc.L("Archive.Delete.Line", s.Sequence.DisplayTitle,
Loc.Plural("Shell.Status.Photos", s.Sequence.FrameCount), Formatting.Bytes(s.Bytes))).ToList();
if (plan.Steps.Count > ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", plan.Steps.Count - ListedLines));
lines.AddRange(Blocked(plan, BlockedLines));
return new ConfirmRequest
{
Heading = Loc.Plural("Archive.Delete.Heading", plan.Steps.Count),
Message = Loc.L("Archive.Delete.Message", Loc.Plural("Shell.Status.Photos", plan.Frames), Loc.Plural("Archive.Delete.Files", plan.Files),
Formatting.Bytes(plan.Bytes)),
Detail = string.Join(Environment.NewLine, lines),
IsDetailMonospaced = false,
DetailToolTip = Loc.L("Tooltips.Archive.DeletePlan"),
SafeText = Loc.L("Archive.Delete.Keep"),
SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
ActionText = Loc.L("Archive.Delete.Action"),
ActionToolTip = Loc.Plural("Tooltips.Archive.DeleteAction", plan.Steps.Count),
IsDestructive = true,
TypedConfirmation = count,
TypedPrompt = Loc.L("Archive.Delete.Type", count),
};
}
/// <summary>"Not moved: Comet over the ridge · a job is working on it", at most <paramref name="max"/> lines.</summary>
public static IReadOnlyList<string> Blocked(DeletePlan plan, int max)
{
var lines = plan.Blocked.Take(max).Select(b => Loc.L("Archive.Delete.Blocked", b.Sequence.DisplayTitle, Loc.L("Archive.Delete.Reason." + b.Reason))).ToList();
if (plan.Blocked.Count > max) lines.Add(Loc.Plural("Archive.Delete.More", plan.Blocked.Count - max));
return lines;
}
}
+1 -2
View File
@@ -94,8 +94,7 @@ public sealed record ArchiveSetFilter(string? Camera = null, StatusFilter Status
{
if (Camera is not null && CameraOf(sequence) != Camera) return false;
if (Tag is not null && !sequence.Tags.Contains(Tag, StringComparer.OrdinalIgnoreCase)) return false;
var (with, without) = LibraryFilter.Flags(Status);
return (sequence.Status & with) == with && (sequence.Status & without) == 0;
return LibraryFilter.MatchesStatus(sequence, Status);
}
/// <summary>"Canon EOS R5 · Not analysed · sunset"; empty without a filter.</summary>
+12 -1
View File
@@ -5,7 +5,7 @@ using Titano.Data.Repositories;
namespace Titano.App.Archiving;
/// <summary>
/// Capture and smoke-test data ONLY: maintenance reports and rebuild counts over the sample archive's sequences
/// Capture and smoke-test data ONLY: maintenance reports, rebuild counts and trash rows over the sample archive's sequences
/// (the sample index has no sidecars on disk, so the real searches would find nothing to show).
/// </summary>
public static class SampleReports
@@ -31,6 +31,17 @@ public static class SampleReports
? new OrphanReport([], [], [])
: new OrphanReport([new SequenceOrphans(sequences[2].Folder, ["IMG_0412.CR2", "IMG_0413.CR2"], [])], [sequences[3]], ["2024/2024-12-31 Unsorted"]);
/// <summary>The trash dialog's rows: the first two sample sequences, deleted an hour and a day ago (nothing moves on disk).</summary>
public static IReadOnlyList<TrashEntry> Trash(Guid archiveId, IReadOnlyList<SequenceLocation> sequences)
{
var now = DateTimeOffset.UtcNow;
return
[
.. sequences.Take(2).Select((s, i) => new TrashEntry(archiveId, s.Id.ToString("N"), s.Id, s.Title ?? s.Folder, s.Folder, 1_200 * (i + 1), 1_206 * (i + 1),
31_457_280L * 1_200 * (i + 1), now.AddHours(-1 - (23 * i)), Environment.UserName)),
];
}
/// <summary>What the rebuild dialog counts: a sidecar in every sequence folder but the last two, read by metadata instead.</summary>
public static IReadOnlyList<SequenceFolder> Folders(IReadOnlyList<SequenceLocation> sequences)
{
@@ -0,0 +1,55 @@
using System.IO;
using Titano.App.Shell;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Data;
using Titano.Data.Archiving;
namespace Titano.App.Archiving;
/// <summary>What Delete (<see cref="DeleteDialogViewModel"/>) and its Undo share in the Library and the Archive manager.</summary>
public static class SequenceDeletion
{
/// <summary>Brings deleted sequences back from their archives' trash and indexes them again.</summary>
public static async Task RestoreAsync(ShellViewModel shell, IReadOnlyList<TrashEntry> entries)
{
if (shell.Services.Archives is not { } archives) return;
var restored = 0;
try
{
foreach (var entry in entries)
{
await Task.Run(() => archives.RestoreAsync(entry.ArchiveId, entry.Name));
restored++;
}
shell.Notify(Loc.Plural("Archive.Trash.Restored", restored));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or SequenceInLibraryException or NewerFormatException
or ArgumentException or DatabaseException)
{
Log.Warning("archive", "Restore from the trash failed", ex);
shell.Notify(Loc.L("Archive.Trash.Failed"), ArchiveFailures.Cause(ex));
}
await RefreshAsync(shell);
}
/// <summary>
/// The editor of a sequence about to move stores its last edit (so the trash keeps it) and closes; false when that
/// edit could not be stored and the user kept it.
/// </summary>
internal static async Task<bool> CloseEditorAsync(ShellViewModel shell, DeletePlan plan)
{
if (shell.Sequence.Editor is null || shell.CurrentSequenceId is not { } open || plan.Steps.All(s => s.Sequence.Id != open)) return true;
if (!await shell.Sequence.ConfirmCloseAsync()) return false;
await shell.Sequence.CloseAsync();
return true;
}
internal static async Task RefreshAsync(ShellViewModel shell)
{
await shell.Library.RefreshAsync();
await shell.Archive.LoadAsync();
shell.Services.Sync.RequestRefresh();
}
}
@@ -0,0 +1,120 @@
using System.IO;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Ui.Mvvm;
namespace Titano.App.Archiving;
/// <summary>One deleted sequence in the trash: what it was, when it went, and Restore.</summary>
public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore)
{
public TrashEntry Entry { get; } = entry;
public string Title => Entry.Title;
/// <summary>"3,600 photos · 96.2 GB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language).</summary>
public string Detail => string.Join(" · ", Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder));
/// <summary>"Deleted 02/10/2026 18:04".</summary>
public string DeletedText => Loc.L("Archive.Trash.Deleted", Formatting.Date(Entry.DeletedAt) + " " + Formatting.TimeOfDay(Entry.DeletedAt));
public ICommand RestoreCommand { get; } = restore;
}
/// <summary>
/// The archive's trash (BRIEF §0.2 rule 8): every sequence deleted from the Library or the Archive manager, newest
/// first, each restorable into its folder (or a free one next to it) with its ids, settings and renders.
/// </summary>
public sealed class TrashDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly Core.Model.Archive _archive;
private readonly Func<Task> _restored;
private IReadOnlyList<TrashRowViewModel> _rows = [];
public TrashDialogViewModel(ArchiveService archives, Core.Model.Archive archive, Func<Task> restored, Action<ArchiveDialogViewModel> close)
: base(close)
{
_archives = archives;
_archive = archive;
_restored = restored;
}
public string Heading => Loc.L("Archive.Trash.Heading", _archive.Name);
public IReadOnlyList<TrashRowViewModel> Rows
{
get => _rows;
private set
{
if (!Set(ref _rows, value)) return;
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(HasRows));
OnPropertyChanged(nameof(SummaryText));
}
}
public bool IsEmpty => _rows.Count == 0;
/// <summary>The list shows; an empty trash is its summary sentence alone.</summary>
public bool HasRows => _rows.Count > 0;
/// <summary>"3 sequences · 182 GB", or "The trash is empty".</summary>
public string SummaryText => _rows.Count == 0 ? Loc.L("Archive.Trash.Empty")
: Loc.Plural("Shell.Status.Sequences", _rows.Count) + " · " + Formatting.Bytes(_rows.Sum(r => r.Entry.Bytes));
/// <summary>Reads the trash of the archive (off the UI thread).</summary>
public async Task LoadAsync()
{
ClearError();
BusyText = Loc.L("Archive.Trash.Reading");
try
{
var entries = await Task.Run(() => _archives.ListTrashAsync(_archive.Id));
Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => RestoreAsync(e), () => !IsBusy)))];
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException)
{
Log.Warning("archive", "Reading the trash failed", ex);
ShowError(ex);
}
finally
{
BusyText = null;
}
}
/// <summary>Shows entries read elsewhere (capture).</summary>
public void Show(IReadOnlyList<TrashEntry> entries) =>
Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => Task.CompletedTask)))];
private async Task RestoreAsync(TrashEntry entry)
{
ClearError();
IsBusy = true;
BusyText = Loc.L("Archive.Trash.Restoring", entry.Title);
try
{
await Task.Run(() => _archives.RestoreAsync(entry.ArchiveId, entry.Name));
Log.Info("archive", $"{entry.Title} restored from the trash");
Rows = [.. _rows.Where(r => r.Entry != entry)];
BusyText = null;
await _restored();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or SequenceInLibraryException or NewerFormatException
or DatabaseException or ArgumentException)
{
Log.Warning("archive", $"Restoring {entry.Title} failed", ex);
ShowError(ex);
}
finally
{
IsBusy = false;
BusyText = null;
}
}
}
+23 -1
View File
@@ -4,6 +4,7 @@ using Titano.App.About;
using Titano.App.Editor;
using Titano.App.Import;
using Titano.App.Infrastructure;
using Titano.App.Library;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.Core.Advice;
@@ -101,6 +102,7 @@ public sealed class SampleData
foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job);
await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList());
await SampleCards.InsertAsync(db, (SampleDeviceMonitor)_services.Devices, _services.Environment.DataDirectory);
await FillViewsAsync(db);
settings.LastArchivePath = @"D:\TitanoArchive";
settings.ServerUrl = "https://nas.local:8443";
@@ -112,6 +114,15 @@ public sealed class SampleData
settings.FirstRunCompleted = true;
}
/// <summary>Two saved views of the Library ("Not analysed, largest" and one camera), BRIEF §12.2.</summary>
private static async Task FillViewsAsync(TitanoDatabase db)
{
var views = new SavedViewStore(db.Settings);
await views.SaveAsync(SavedView.Of(Guid.CreateVersion7(), "Not analysed, largest",
new LibraryFilter { Status = StatusFilter.NotAnalysed, Sort = Data.Repositories.SequenceSort.Size }));
await views.SaveAsync(SavedView.Of(Guid.CreateVersion7(), "Nikon Z 8", new LibraryFilter { Camera = "NIKON Z 8" }));
}
/// <summary>
/// Transfers for the sync table: an upload at 46 % (Comet over the ridge), an upload waiting (Fog lifting, Asti), a
/// download of originals running (Sunrise over Superga) and one paused (Lake Como storm).
@@ -204,7 +215,8 @@ public sealed class SampleData
/// <summary>
/// The server's side: six sequences this PC also holds (two the same, one with settings changed on both sides, one
/// with more originals on the server, one with more here, one with renders this PC lacks) and two only on the server;
/// with more originals on the server, one with more here, one with renders this PC lacks) and two only on the server
/// (captured in the months the local sample spans, so they join the Library's year choices and timeline);
/// the others are only here.
/// </summary>
private async Task FillServerAsync(TitanoDatabase db, IReadOnlyList<Sequence> local)
@@ -233,6 +245,11 @@ public sealed class SampleData
ArchiveId = Guid.Empty,
Title = "Sunrise over Superga",
Folder = "2026/2026-07-02 Sony ILCE-7M4",
CameraMake = "SONY",
CameraModel = "ILCE-7M4",
FirstCapture = DateTime.Today.AddDays(-96).AddHours(5.2),
LastCapture = DateTime.Today.AddDays(-96).AddHours(6.8),
MedianInterval = 2,
FrameCount = 2_880,
TotalBytes = 2_880 * 21_000_000L,
Status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt,
@@ -245,6 +262,11 @@ public sealed class SampleData
ArchiveId = Guid.Empty,
Title = "Lake Como storm",
Folder = "2026/2026-08-21 Canon EOS R5",
CameraMake = "Canon",
CameraModel = "Canon EOS R5",
FirstCapture = DateTime.Today.AddDays(-46).AddHours(16.5),
LastCapture = DateTime.Today.AddDays(-46).AddHours(17.3),
MedianInterval = 2,
FrameCount = 1_450,
TotalBytes = 1_450 * 45_000_000L,
Status = SequenceStatus.ThumbsBuilt,
@@ -13,6 +13,9 @@ public enum LibraryLayout
{
Grid,
List,
/// <summary>Year bands with photos per month above the card grid.</summary>
Timeline,
}
/// <summary>Rendering quality profile (Settings › Rendering).</summary>
+4 -1
View File
@@ -6,9 +6,12 @@ public sealed record ConfirmRequest
public required string Heading { get; init; }
public required string Message { get; init; }
/// <summary>Monospaced detail (certificate fingerprint); null hides it.</summary>
/// <summary>Detail block (certificate fingerprint, list of what changes); null hides it.</summary>
public string? Detail { get; init; }
/// <summary>The detail is set in the monospaced font (fingerprints, values to compare); false sets it in the UI font (names, sentences).</summary>
public bool IsDetailMonospaced { get; init; } = true;
public string? DetailToolTip { get; init; }
public required string SafeText { get; init; }
public required string SafeToolTip { get; init; }
+249
View File
@@ -0,0 +1,249 @@
using System.IO;
using System.Net.Http;
using Titano.App.Archiving;
using Titano.App.Jobs;
using Titano.App.Server;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Archiving.Jobs;
using Titano.Data.Processing;
using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Protocol.Client;
namespace Titano.App.Library;
/// <summary>
/// What the Library's quick and mass actions run (BRIEF §12.2): analyses, proxies, verifies and renders as jobs on
/// this PC's engine, or posted to the server for a sequence that only lives there; uploads, downloads and settings
/// exchanges through the sync engine (as the Server screen does); ratings through the archive engine (sidecar and
/// index together). Every queued job is announced with a toast that opens the Jobs screen.
/// </summary>
public sealed class LibraryActions(ShellViewModel shell)
{
/// <summary>Wire names of the job kinds a remote card posts (<c>POST /api/v1/jobs</c>).</summary>
private const string RenderKind = "render";
private const string DeepAnalyseKind = "deep-analyse";
private Infrastructure.AppServices Services => shell.Services;
/// <summary>The signed-in server's sync engine and connection; null while signed out.</summary>
public RemoteSource? Remote() =>
Services.Sync is { Service: { } service, Server: { } server, Remote: { } remote } ? new RemoteSource(service, server, remote) : null;
/// <summary>What the signed-in account may do; nothing while signed out.</summary>
public SyncRights Rights => Services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
/// <summary>A job can be posted to the server now (a remote card's Analyse and Render).</summary>
public bool CanPost => Services.Server is { IsConnected: true, Flow: { Address: not null, Token: not null } };
/// <summary>Deep analysis of sequences on this PC (one job), or of a remote card on the server.</summary>
public async Task AnalyseAsync(IReadOnlyList<Sequence> sequences)
{
if (sequences is [{ Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly } remote])
{
await PostAsync(() => Task.FromResult(new CreateJobRequest(DeepAnalyseKind, [remote.Id], null)), JobKind.DeepAnalyse, remote.DisplayTitle);
return;
}
await QueueAsync(ProcessingJobs.DeepAnalysis([.. sequences.Select(s => s.Id)], Label(sequences)));
}
public Task ProxiesAsync(IReadOnlyList<Sequence> sequences) => QueueAsync(ArchiveJobs.Proxies([.. sequences.Select(s => s.Id)], Label(sequences)));
/// <summary>Verification is an archive job: one per archive, naming its sequences.</summary>
public async Task VerifyAsync(IReadOnlyList<Sequence> sequences)
{
if (Services.Database is not { } db) return;
foreach (var group in sequences.GroupBy(s => s.ArchiveId))
{
if (await db.Archives.GetAsync(group.Key) is { } archive) await QueueAsync(ArchiveJobs.Verify(archive, [.. group.Select(s => s.Id)]));
}
}
/// <summary>
/// The Render quick action: the sequence's own export with its project as stored — the preset chosen in the editor,
/// else the advisor's recommendation the analyses store in the project, else the default — on this PC's engine, or
/// posted to the server for a remote card, which renders it where the originals are.
/// </summary>
public async Task RenderAsync(Sequence sequence)
{
if (sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly })
{
if (Remote() is not { } remote)
{
NotConnected();
return;
}
await PostAsync(async () =>
{
var (project, width, height) = await RemoteProjectAsync(remote, sequence.Id);
return new CreateJobRequest(RenderKind, [sequence.Id], ProcessingJobs.Render(sequence, project.Export with { Batch = [] }, width, height).ParametersJson);
}, JobKind.Render, sequence.DisplayTitle);
return;
}
if (Services.Database is not { } db) return;
// The project as stored now: the editor may have changed it since the card was read.
var current = await db.Sequences.GetAsync(sequence.Id) ?? sequence;
var first = (await db.Frames.ListBySequenceAsync(sequence.Id, -1, 1)).FirstOrDefault();
var (w, h) = first is null ? (0, 0) : first.Orientation is >= 5 and <= 8 ? (first.Height, first.Width) : (first.Width, first.Height);
var export = Project(current.SettingsJson).Export with { Batch = [] };
await QueueAsync(ProcessingJobs.Render(current, export, w, h));
}
/// <summary>Runs one row action of the sync table on a sequence (the card's Sync, a mass Upload or Download); false when it could not start.</summary>
public async Task<bool> SyncAsync(SelectedSequence selected, SyncAction action)
{
if (Remote() is not { } remote || Services.Engine is not { } engine) return false;
var entry = selected.Sync;
switch (action)
{
case SyncAction.Upload when !selected.IsRemote:
await remote.Service.EnqueueUploadAsync(engine, remote.Server, selected.Sequence);
return true;
case SyncAction.SendExports when !selected.IsRemote:
await remote.Service.EnqueueSendExportsAsync(engine, remote.Server, selected.Sequence);
return true;
case SyncAction.DownloadOriginals when entry is not null:
if ((entry.Local?.ArchiveId ?? (await Services.Sync.CurrentArchiveAsync())?.Id) is not { } archive)
{
shell.Notify(Loc.L("Errors.Sync.NoArchive"));
return false;
}
await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
return true;
case SyncAction.GetExports when entry is not null:
await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
return true;
case SyncAction.SyncSettings when entry is not null:
await remote.Service.SyncSettingsAsync(remote.Remote, entry.Id, Services.Sync.Policy, CancellationToken.None);
return true;
default:
return false;
}
}
/// <summary>
/// Opens a remote card with proxies (BRIEF §14.5): at once when its proxies are cached here, otherwise after the
/// proxy download this queues. Returns that download job, or null when the editor opened (or nothing could start).
/// </summary>
public async Task<Guid?> OpenRemoteAsync(Sequence sequence)
{
if (Remote() is not { } remote || Services.Engine is not { } engine)
{
NotConnected();
return null;
}
// The proxy cache is read off the UI thread: its manifest holds every frame.
if (await Task.Run(() => remote.Service.OpenRemote(remote.Server, sequence.Id)) is not null)
{
shell.OpenSequence(sequence.Id);
return null;
}
var job = await remote.Service.EnqueueDownloadAsync(engine, remote.Server, sequence.Id, sequence.DisplayTitle, SyncDownloadMode.Proxies, null);
Queued(JobKind.Download, sequence.DisplayTitle);
return job.Id;
}
/// <summary>
/// Sets the rating of sequences on this PC (sidecar and index together), changing nothing else: the title, tags and
/// notes are those the sidecar holds then, not the Library's copy. Returns how many changed.
/// </summary>
public async Task<int> RateAsync(IReadOnlyList<Sequence> sequences, int rating)
{
if (Services.Archives is not { } archives || Services.Database is not { } db) return 0;
var changed = 0;
try
{
foreach (var s in sequences)
{
if (await db.Sequences.GetAsync(s.Id) is not { } current || current.Rating == rating) continue;
await Task.Run(() => archives.EditSequenceInfoAsync(s.Id, info => info with { Rating = rating }));
changed++;
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
{
Log.Warning("library", "Rating failed", ex);
shell.Notify(Loc.L("Library.Rate.Failed"), ArchiveFailures.Cause(ex));
}
return changed;
}
/// <summary>"Deep analysis queued · Harbour sunset", with a way to the Jobs screen.</summary>
public void Queued(JobKind kind, string 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));
public static string Label(IReadOnlyList<Sequence> sequences) =>
sequences.Count == 1 ? sequences[0].DisplayTitle : Loc.Plural("Library.Selection.Count", sequences.Count);
private async Task QueueAsync(ArchiveJobRequest request)
{
if (request.Targets.Count == 0) return;
if (Services.Engine is not { } engine)
{
shell.Notify(Loc.L("Library.Blocked.NoIndex"));
return;
}
await engine.EnqueueAsync(request);
Queued(request.Kind, request.Label ?? string.Empty);
}
/// <summary>Posts a job to the signed-in server, which runs it or hands it to a render node (BRIEF §14.6, §14.7).</summary>
private async Task PostAsync(Func<Task<CreateJobRequest>> build, JobKind kind, string label)
{
var session = Services.Server;
if (!CanPost || session.Flow is not { Address: { } address, Token: { } token })
{
NotConnected();
return;
}
try
{
var request = await build();
using var client = new TitanoClient(address, new CertificatePinning(session.Fingerprints), $"Titano ({Environment.MachineName})") { Token = token };
await client.CreateJobAsync(request);
shell.Notify(Loc.L("Library.QueuedServer", JobText.Kind(kind), label));
}
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException or TaskCanceledException)
{
Log.Warning("library", $"Posting a {kind} job to {address} failed", ex);
shell.Notify(Loc.L("Library.Post.Failed"), ex.Message);
}
}
/// <summary>A remote card's action could not start: the session ended since the card was drawn.</summary>
private void NotConnected() => shell.Notify(Loc.L("Library.Remote.Unavailable"), Loc.L("Library.Blocked.NotConnected"));
/// <summary>The project of a remote card: from its proxy cache when it was opened here, else from the server's manifest; and its frame size when cached.</summary>
private static async Task<(ProjectSettings Project, int Width, int Height)> RemoteProjectAsync(RemoteSource remote, Guid id)
{
if (await Task.Run(() => remote.Service.OpenRemote(remote.Server, id)) is { } cached)
{
var frame = cached.Frames.FirstOrDefault(f => f.Width > 0);
var size = frame is null ? (0, 0) : frame.Orientation is >= 5 and <= 8 ? (frame.Height, frame.Width) : (frame.Width, frame.Height);
return (Project(cached.Sequence.SettingsJson), size.Item1, size.Item2);
}
var manifest = await remote.Remote.GetManifestAsync(id, CancellationToken.None);
return (Project(manifest.SettingsJson), 0, 0);
}
private static ProjectSettings Project(string? json)
{
try
{
return json is null ? new ProjectSettings() : ProjectSettings.FromJson(json);
}
catch (System.Text.Json.JsonException ex)
{
Log.Warning("library", "Unreadable project settings; rendering the defaults", ex);
return new ProjectSettings();
}
}
}
+38
View File
@@ -0,0 +1,38 @@
using System.Globalization;
using System.Text;
using Titano.Core.Model;
namespace Titano.App.Library;
/// <summary>The Library's "Export list as CSV" (BRIEF §12.2): RFC 4180, UTF-8, invariant numbers and dates.</summary>
public static class LibraryCsv
{
/// <summary>One row per sequence; the header is English because the file is data, not UI.</summary>
public static string Write(IEnumerable<Sequence> sequences)
{
var inv = CultureInfo.InvariantCulture;
var sb = new StringBuilder("title,first_capture,last_capture,camera_make,camera_model,frames,bytes,folder,tags,origin\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(',')
.Append(s is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly } ? "server" : "local").Append("\r\n");
}
return sb.ToString();
}
private 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;
}
}
+44
View File
@@ -0,0 +1,44 @@
using Titano.Core.Model;
using Titano.Data.Repositories;
namespace Titano.App.Library;
/// <summary>
/// What the Library's Year and Camera choices and its timeline bands count (BRIEF §4.4 mixed mode): the index's
/// figures, the server's sequences without a copy here, or both, as the origin filter says.
/// </summary>
public static class LibraryFacets
{
/// <summary>
/// <paramref name="local"/> with its years, months and cameras replaced by those of the origins in view: the index's
/// own unless only the server's sequences show, plus the remote cards' unless only this PC's show.
/// </summary>
public static ArchiveStats Of(ArchiveStats local, IReadOnlyList<Sequence> remote, OriginFilter origin)
{
var keepLocal = origin != OriginFilter.Server;
var years = keepLocal ? local.ByYear.ToDictionary(y => y.Year) : [];
var months = keepLocal ? local.ByMonth.ToDictionary(m => (m.Year, m.Month)) : [];
var cameras = keepLocal ? local.ByCamera.ToDictionary(c => (c.Make, c.Model)) : [];
foreach (var s in origin == OriginFilter.Local ? [] : remote)
{
if (s.FirstCapture is { } at)
{
years[at.Year] = years.TryGetValue(at.Year, out var y)
? y with { Sequences = y.Sequences + 1, Photos = y.Photos + s.FrameCount, Bytes = y.Bytes + s.TotalBytes }
: new YearBucket(at.Year, 1, s.FrameCount, s.TotalBytes);
months[(at.Year, at.Month)] = months.TryGetValue((at.Year, at.Month), out var m)
? m with { Sequences = m.Sequences + 1, Photos = m.Photos + s.FrameCount }
: new MonthBucket(at.Year, at.Month, 1, s.FrameCount);
}
cameras[(s.CameraMake, s.CameraModel)] = cameras.TryGetValue((s.CameraMake, s.CameraModel), out var c)
? c with { Sequences = c.Sequences + 1, Photos = c.Photos + s.FrameCount, Bytes = c.Bytes + s.TotalBytes }
: new CameraBucket(s.CameraMake, s.CameraModel, 1, s.FrameCount, s.TotalBytes);
}
return local with
{
ByYear = [.. years.Values.OrderBy(y => y.Year)],
ByMonth = [.. months.Values.OrderBy(m => m.Year).ThenBy(m => m.Month)],
ByCamera = [.. cameras.Values],
};
}
}
+84 -4
View File
@@ -3,7 +3,7 @@ using Titano.Data.Repositories;
namespace Titano.App.Library;
/// <summary>Status choices of the Library toolbar; each maps onto status flags the index can filter on.</summary>
/// <summary>Status choices of the Library toolbar (Main.html: analysed, proxies, rendered, synced); each is a test the index can run.</summary>
public enum StatusFilter
{
Any,
@@ -11,12 +11,23 @@ public enum StatusFilter
NotAnalysed,
Proxies,
NoProxies,
Rendered,
NotRendered,
Verified,
NotVerified,
Synced,
Warnings,
}
/// <summary>Library filters (search, year, camera, status, tag) and sort; immutable so a page request can carry it.</summary>
/// <summary>Where the sequences of the Library live (BRIEF §4.4 mixed mode): both, this PC, or only the signed-in server.</summary>
public enum OriginFilter
{
Any,
Local,
Server,
}
/// <summary>Library filters (search, year, camera, status, tag, origin) and sort; immutable so a page request can carry it.</summary>
public sealed record LibraryFilter
{
public string? Text { get; init; }
@@ -24,14 +35,19 @@ public sealed record LibraryFilter
public string? Camera { get; init; }
public StatusFilter Status { get; init; }
public string? Tag { get; init; }
public OriginFilter Origin { get; init; }
public SequenceSort Sort { get; init; } = SequenceSort.Newest;
/// <summary>No filter narrows the list (the sort may differ): an empty result means an empty library.</summary>
public bool IsUnfiltered => string.IsNullOrWhiteSpace(Text) && Year is null && Camera is null && Status == StatusFilter.Any && Tag is null;
public bool IsUnfiltered => string.IsNullOrWhiteSpace(Text) && Year is null && Camera is null && Status == StatusFilter.Any && Tag is null
&& Origin == OriginFilter.Any;
/// <summary>The same sort without filters ("Clear filters").</summary>
public LibraryFilter Cleared() => new() { Sort = Sort };
/// <summary>Sync states a "Synced" sequence is in: the ones whose card wears the ● Synced glyph.</summary>
public static IReadOnlyCollection<SyncState> SyncedStates { get; } = [SyncState.InSync, SyncState.LocalAhead];
/// <summary>The repository query for one page.</summary>
public SequenceQuery ToQuery(int limit, string? cursor)
{
@@ -44,13 +60,77 @@ public sealed record LibraryFilter
Tag = Tag,
WithStatus = with,
WithoutStatus = without,
Rendered = Status switch
{
StatusFilter.Rendered => true,
StatusFilter.NotRendered => false,
_ => null,
},
SyncStates = Status == StatusFilter.Synced ? SyncedStates : null,
Sort = Sort,
Limit = limit,
Cursor = cursor,
};
}
/// <summary>Flags that must be set and clear for a status choice.</summary>
/// <summary>
/// The same test the index applies to its rows (<see cref="ToQuery"/>), for sequences that are not in the index
/// (server sequences without a local copy): title, camera or tag text, capture year, camera model, status, tag.
/// </summary>
public bool Matches(Sequence sequence)
{
if (Year is { } year && sequence.FirstCapture?.Year != year) return false;
if (Camera is not null && sequence.CameraModel != Camera) return false;
if (!MatchesStatus(sequence, Status)) return false;
if (Tag is not null && !sequence.Tags.Contains(TagRepository.Normalize(Tag), StringComparer.OrdinalIgnoreCase)) return false;
if (string.IsNullOrWhiteSpace(Text)) return true;
var text = Text.Trim();
return new[] { sequence.Title, sequence.CameraMake, sequence.CameraModel }.Any(v => v?.Contains(text, StringComparison.OrdinalIgnoreCase) == true)
|| sequence.Tags.Any(t => t.Contains(text, StringComparison.OrdinalIgnoreCase));
}
/// <summary>The index's order of <see cref="Sort"/> (missing values last, the id as tie-breaker), for merging pages with other sequences.</summary>
public int Compare(Sequence a, Sequence b)
{
var order = Sort switch
{
SequenceSort.Newest => Nullable(a.FirstCapture, b.FirstCapture, descending: true),
SequenceSort.Oldest => Nullable(a.FirstCapture, b.FirstCapture, descending: false),
SequenceSort.Title => string.CompareOrdinal(a.DisplayTitle.ToLowerInvariant(), b.DisplayTitle.ToLowerInvariant()),
SequenceSort.FrameCount => b.FrameCount.CompareTo(a.FrameCount),
_ => b.TotalBytes.CompareTo(a.TotalBytes),
};
if (order != 0) return order;
var ids = string.CompareOrdinal(a.Id.ToString(), b.Id.ToString());
return Sort is SequenceSort.Oldest or SequenceSort.Title ? ids : -ids;
static int Nullable(DateTime? x, DateTime? y, bool descending) => (x, y) switch
{
(null, null) => 0,
(null, _) => 1,
(_, null) => -1,
_ => descending ? y!.Value.CompareTo(x!.Value) : x!.Value.CompareTo(y!.Value),
};
}
/// <summary>The status test of the index (<see cref="ToQuery"/>) on one sequence.</summary>
public static bool MatchesStatus(Sequence sequence, StatusFilter status)
{
switch (status)
{
case StatusFilter.Rendered:
return sequence.RenderedCount > 0;
case StatusFilter.NotRendered:
return sequence.RenderedCount == 0;
case StatusFilter.Synced:
return SyncedStates.Contains(sequence.SyncState);
default:
var (with, without) = Flags(status);
return (sequence.Status & with) == with && (sequence.Status & without) == 0;
}
}
/// <summary>Flags that must be set and clear for a status choice (none for the choices that test renders or sync).</summary>
public static (SequenceStatus With, SequenceStatus Without) Flags(StatusFilter status) => status switch
{
StatusFilter.Analysed => (SequenceStatus.AnalyzedLight, SequenceStatus.None),
+68
View File
@@ -0,0 +1,68 @@
using Titano.App.Archiving;
using Titano.App.Infrastructure;
using Titano.App.Shell;
namespace Titano.App.Library;
/// <summary>
/// The Library states that <c>--capture</c> renders (<c>library-&lt;scene&gt;-&lt;theme&gt;.png</c>) and the screen smoke
/// tests check, on the sample index while signed in to the sample server: the timeline with a month chosen, a selection
/// with the whole mass actions bar, the server's sequences without a copy here as remote cards, and "Save view" naming
/// the filters on screen.
/// </summary>
public static class LibraryScenes
{
public static readonly IReadOnlyList<string> Scenes = ["timeline", "mass", "remote", "viewname"];
/// <summary>Sequences selected for the mass actions bar.</summary>
public const int MassSelection = 3;
public static async Task ShowAsync(ShellViewModel shell, string scene)
{
var library = shell.Library;
shell.Navigate(SectionKey.Library);
library.Dialog?.CloseCommand.Execute(null);
library.ClearSelectionCommand.Execute(null);
library.ClearFiltersCommand.Execute(null);
library.LayoutIndex = 0;
await library.RefreshAsync();
switch (scene)
{
case "timeline":
library.LayoutIndex = 2;
// A month further down the list: the year becomes the filter and the grid scrolls to the month.
if (library.Items.Count > 0 && library.Items[Math.Min(12, library.Items.Count - 1)].Sequence.FirstCapture is { } month)
{
library.ShowMonth(month.Year, month.Month);
await library.RefreshAsync();
}
break;
case "mass":
foreach (var item in library.Items.Where(i => !i.IsRemote).Take(MassSelection)) item.IsSelected = true;
break;
case "remote":
library.SelectedOrigin = library.Origins.First(o => o.Value == OriginFilter.Server);
await library.RefreshAsync();
if (library.Items.FirstOrDefault() is { } remote) remote.IsSelected = true;
// Remote thumbnails come through the sync engine's connection, not the local thumbnail service.
for (var i = 0; i < 60 && library.Items.Any(item => item.Thumbnail is null); i++) await Task.Delay(50);
break;
case "viewname":
library.SelectedStatus = library.Statuses.First(o => o.Value == StatusFilter.NotRendered);
await library.RefreshAsync();
library.OpenSaveView();
if (library.Dialog is ViewNameDialogViewModel naming) naming.Name.Text = library.SelectedStatus.Label;
break;
default:
throw new ArgumentOutOfRangeException(nameof(scene), scene, "Unknown Library scene.");
}
}
/// <summary>The confirmation Delete shows for the selection: the archive engine's dry run (nothing moves).</summary>
public static async Task<ConfirmRequest?> DeleteRequestAsync(ShellViewModel shell)
{
var archives = shell.Services.Archives ?? throw new InvalidOperationException("The sample index is not open.");
var ids = shell.Library.SelectedItems().Where(i => !i.IsRemote).Select(i => i.Id).ToList();
return DeletePlans.Request(await Task.Run(() => archives.PlanDeleteAsync(ids)));
}
}
+63
View File
@@ -0,0 +1,63 @@
using Titano.App.Archiving;
using Titano.Core.Model;
using Titano.Data.Repositories;
namespace Titano.App.Library;
/// <summary>
/// The Library's timeline layout (BRIEF §12.2): one band per capture year, newest first, with the density of photos
/// per month (the Archive heatmap's figures), and the way between a band's month and the sequences of the grid.
/// </summary>
public sealed class LibraryTimeline
{
private LibraryTimeline(IReadOnlyList<HeatRow> bands, IReadOnlyList<int> years)
{
Bands = bands;
Years = years;
}
public static LibraryTimeline Empty { get; } = new([], []);
/// <summary>One row per year, newest first; months to come are NaN.</summary>
public IReadOnlyList<HeatRow> Bands { get; }
/// <summary>The year of each band.</summary>
public IReadOnlyList<int> Years { get; }
public static LibraryTimeline From(ArchiveStats stats, DateTime today)
{
var rows = ArchiveFigures.PhotosPerMonth(stats, today).Reverse().ToList();
var first = stats.ByMonth.Count == 0 ? 0 : stats.ByMonth.Max(m => m.Year);
return new LibraryTimeline(rows, [.. Enumerable.Range(0, rows.Count).Select(i => first - i)]);
}
/// <summary>Year and month of a band's slot; null outside the bands.</summary>
public (int Year, int Month)? MonthAt(int band, int slot) =>
band >= 0 && band < Years.Count && slot is >= 0 and < 12 ? (Years[band], slot + 1) : null;
/// <summary>Band and slot of a month; (−1, −1) when no band shows that year.</summary>
public (int Band, int Slot) SlotOf(int year, int month)
{
var band = IndexOf(Years, year);
return band < 0 || month is < 1 or > 12 ? (-1, -1) : (band, month - 1);
}
/// <summary>Position of the first sequence first captured in that month, in list order; −1 when none of <paramref name="sequences"/> is.</summary>
public static int FirstOfMonth(IReadOnlyList<Sequence> sequences, int year, int month)
{
for (var i = 0; i < sequences.Count; i++)
{
if (sequences[i].FirstCapture is { } at && at.Year == year && at.Month == month) return i;
}
return -1;
}
private static int IndexOf(IReadOnlyList<int> values, int value)
{
for (var i = 0; i < values.Count; i++)
{
if (values[i] == value) return i;
}
return -1;
}
}
+126
View File
@@ -0,0 +1,126 @@
using Titano.App.Server;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Sync;
namespace Titano.App.Library;
/// <summary>The actions of the Library's mass actions bar (BRIEF §12.2).</summary>
public enum MassAction
{
Analyse,
Proxies,
Verify,
Tag,
Rate,
Move,
Upload,
Download,
Delete,
ExportList,
}
/// <summary>A selected sequence and, while signed in, its row of the sync table.</summary>
public sealed record SelectedSequence(Sequence Sequence, SyncEntry? Sync)
{
/// <summary>Only on the server: no copy on this PC (a remote card).</summary>
public bool IsRemote => Sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly };
}
/// <summary>What this PC can do right now.</summary>
/// <param name="HasEngine">The index and the job engine are open.</param>
/// <param name="IsSignedIn">A server session is open (uploads, downloads, remote cards).</param>
public sealed record SelectionContext(bool HasEngine, bool IsSignedIn, SyncRights Rights);
/// <summary>
/// Which selected sequences each mass action works on and, when it works on none, why (the disabled button's
/// tooltip, DESIGN §4). Archive actions touch sequences on this PC; Upload and Download follow the sync table's own
/// row actions (<see cref="SyncText.Actions"/>), so the Library and the Server screen never disagree.
/// </summary>
public static class MassActions
{
/// <summary>The selected sequences <paramref name="action"/> works on.</summary>
public static IReadOnlyList<SelectedSequence> Targets(MassAction action, IReadOnlyList<SelectedSequence> selection, SelectionContext context) => action switch
{
MassAction.ExportList => selection,
MassAction.Upload => [.. selection.Where(s => !s.IsRemote && UploadStep(s, context.Rights) is not null)],
MassAction.Download => [.. selection.Where(s => DownloadStep(s, context.Rights) is not null)],
_ => [.. selection.Where(s => !s.IsRemote)],
};
/// <summary>Why <paramref name="action"/> cannot run on the selection, localized; null when it can.</summary>
public static string? Blocker(MassAction action, IReadOnlyList<SelectedSequence> selection, SelectionContext context)
{
if (selection.Count == 0) return Loc.L("Library.Blocked.NoSelection");
if (action == MassAction.ExportList) return null;
if (!context.HasEngine) return Loc.L("Library.Blocked.NoIndex");
var targets = Targets(action, selection, context);
switch (action)
{
case MassAction.Upload or MassAction.Download when !context.IsSignedIn:
return Loc.L("Library.Blocked.NotConnected");
case MassAction.Upload when !context.Rights.CanUpload:
return Loc.L("Library.Blocked.NoUploadRight");
case MassAction.Download when !context.Rights.CanFetchOriginals:
return Loc.L("Library.Blocked.NoDownloadRight");
case MassAction.Upload when targets.Count == 0:
return Loc.L("Library.Blocked.NothingToUpload");
case MassAction.Download when targets.Count == 0:
return Loc.L("Library.Blocked.NothingToDownload");
case MassAction.Upload or MassAction.Download:
return null;
}
if (targets.Count == 0) return Loc.L("Library.Blocked.ServerOnly");
return action == MassAction.Move && targets.Select(t => t.Sequence.ArchiveId).Distinct().Count() > 1 ? Loc.L("Library.Blocked.Archives") : null;
}
/// <summary>The enabled tooltip: what the action does to how many sequences.</summary>
public static string ToolTip(MassAction action, int targets) => Loc.Plural("Tooltips.Library.Mass." + action, targets);
/// <summary>What an upload of a selected local sequence sends: its originals and settings, or only its renders; null when nothing.</summary>
public static SyncAction? UploadStep(SelectedSequence selected, SyncRights rights)
{
// Compared before the table lists it: the sequence is only here.
if (selected.Sync is not { } entry) return rights.CanUpload && !selected.IsRemote ? SyncAction.Upload : null;
var actions = SyncText.Actions(entry, rights);
return actions.Contains(SyncAction.Upload) ? SyncAction.Upload : actions.Contains(SyncAction.SendExports) ? SyncAction.SendExports : null;
}
/// <summary>What a download of a selected sequence fetches: the server's originals, or only its renders; null when nothing.</summary>
public static SyncAction? DownloadStep(SelectedSequence selected, SyncRights rights)
{
if (selected.Sync is not { } entry) return null;
var actions = SyncText.Actions(entry, rights);
return actions.Contains(SyncAction.DownloadOriginals) ? SyncAction.DownloadOriginals : actions.Contains(SyncAction.GetExports) ? SyncAction.GetExports : null;
}
/// <summary>
/// The card's Sync quick action: the first transfer or settings exchange the sync table offers, or Resolve
/// (on the Server screen) for a conflict; null with <paramref name="blocker"/> when there is nothing to do.
/// </summary>
public static SyncAction? QuickSync(SelectedSequence selected, SelectionContext context, out string? blocker)
{
blocker = null;
if (!context.IsSignedIn)
{
blocker = Loc.L("Library.Blocked.NotConnected");
return null;
}
if (selected.Sync is not { } entry) return UploadStep(selected, context.Rights) ?? Blocked(Loc.L("Library.Blocked.NoUploadRight"), out blocker);
if (entry.Transfer is not null) return Blocked(Loc.L("Library.Blocked.Transferring"), out blocker);
if (entry.Status == SyncStatus.Conflict) return SyncAction.KeepMine;
var actions = SyncText.Actions(entry, context.Rights);
SyncAction[] preferred = [SyncAction.Upload, SyncAction.DownloadOriginals, SyncAction.SyncSettings, SyncAction.SendExports, SyncAction.GetExports];
foreach (var action in preferred)
{
if (actions.Contains(action)) return action;
}
return Blocked(Loc.L(entry.Status == SyncStatus.InSync ? "Library.Blocked.InSync" : "Library.Blocked.NoSyncRight"), out blocker);
static SyncAction? Blocked(string reason, out string? why)
{
why = reason;
return null;
}
}
}
+109
View File
@@ -0,0 +1,109 @@
using Titano.Core.Model;
using Titano.Data.Sync;
using Titano.Protocol;
namespace Titano.App.Library;
/// <summary>
/// Server sequences without a copy on this PC, as Library cards (BRIEF §4.4 mixed mode): from the sync table of the
/// signed-in server, with the details of the server's listing when it was read, else what the table keeps.
/// </summary>
public static class RemoteCards
{
/// <summary>Entries of the sync table that have no local copy (only on the server, or kept here as proxies).</summary>
public static IEnumerable<SyncEntry> RemoteOnly(IEnumerable<SyncEntry> entries) => entries.Where(e => e is { Local: null, Link: not null });
/// <summary>One card per remote-only entry: the listing's sequence when known, else the table's title, counts and status.</summary>
public static IReadOnlyList<Sequence> Build(IEnumerable<SyncEntry> entries, IReadOnlyDictionary<Guid, SequenceDto>? listing) =>
[
.. RemoteOnly(entries).Select(e => listing is not null && listing.TryGetValue(e.Link!.RemoteId, out var dto) ? ToSequence(dto) : FromLink(e.Link!)),
];
/// <summary>A server sequence as a card: origin server, remote only, no archive on this PC.</summary>
public static Sequence ToSequence(SequenceDto dto) => new()
{
Id = dto.Id,
ArchiveId = Guid.Empty,
Title = dto.Title,
Folder = dto.Folder,
CameraMake = dto.CameraMake,
CameraModel = dto.CameraModel,
Lens = dto.Lens,
FirstCapture = dto.FirstCapture,
LastCapture = dto.LastCapture,
FrameCount = dto.FrameCount,
MedianInterval = dto.MedianInterval,
TotalBytes = dto.TotalBytes,
Status = (SequenceStatus)dto.Status,
RenderedCount = dto.RenderedCount,
HeroFrameId = dto.HeroFrameId,
Tags = dto.Tags,
Rating = dto.Rating,
Notes = dto.Notes,
SettingsVersion = dto.SettingsVersion,
FramesVersion = dto.FramesVersion,
WarningCount = dto.WarningCount,
OwnerUserId = dto.OwnerUserId,
UpdatedAt = dto.UpdatedAt,
Origin = SequenceOrigin.Server,
SyncState = SyncState.RemoteOnly,
};
/// <summary>What the sync table knows of a server sequence when its listing could not be read.</summary>
public static Sequence FromLink(SyncLink link) => new()
{
Id = link.RemoteId,
ArchiveId = Guid.Empty,
Title = link.Title,
Folder = string.Empty,
FrameCount = link.FrameCount,
TotalBytes = link.TotalBytes,
Status = link.RemoteStatus,
RenderedCount = link.RenderCount,
SettingsVersion = link.RemoteSettingsVersion,
FramesVersion = link.RemoteFramesVersion,
UpdatedAt = link.RemoteUpdatedAt,
Origin = SequenceOrigin.Server,
SyncState = SyncState.RemoteOnly,
};
}
/// <summary>
/// Interleaves remote cards with the index's pages in the order of the filter's sort: each page brings the remote
/// cards that sort before its last row; the last page brings the rest. Not thread-safe: call from one thread (the UI).
/// </summary>
public sealed class RemoteMerge
{
private readonly List<Sequence> _pending = [];
private LibraryFilter _filter = new();
/// <summary>Remote cards not yet handed out.</summary>
public int Pending => _pending.Count;
/// <summary>Starts over with the cards that match <paramref name="filter"/>, in its order.</summary>
public void Reset(LibraryFilter filter, IEnumerable<Sequence> remote)
{
_filter = filter;
_pending.Clear();
if (filter.Origin != OriginFilter.Local) _pending.AddRange(remote.Where(filter.Matches));
_pending.Sort(filter.Compare);
}
/// <summary>A page of the index with the remote cards that belong among it, in order; <paramref name="last"/> adds every card left.</summary>
public IReadOnlyList<Sequence> Merge(IReadOnlyList<Sequence> page, bool last)
{
var take = last ? _pending.Count
: page.Count == 0 ? 0
: _pending.FindIndex(r => _filter.Compare(r, page[^1]) > 0) is var after and >= 0 ? after : _pending.Count;
if (take == 0) return page;
var merged = new List<Sequence>(page.Count + take);
int a = 0, b = 0;
while (a < page.Count || b < take)
{
if (b >= take || (a < page.Count && _filter.Compare(page[a], _pending[b]) <= 0)) merged.Add(page[a++]);
else merged.Add(_pending[b++]);
}
_pending.RemoveRange(0, take);
return merged;
}
}
+103
View File
@@ -0,0 +1,103 @@
using System.Collections.Concurrent;
using System.IO;
using System.Windows.Media;
using Titano.Core.Model;
using Titano.Data.Sync;
using Titano.Ui.Visuals;
namespace Titano.App.Library;
/// <summary>Hero thumbnails (and hover-scrub frames, where there are any) of the Library's cards.</summary>
public interface ISequenceThumbnails
{
Task<ImageSource?> HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct);
/// <summary>Frames for hover scrubbing; null when the sequence has none to scrub.</summary>
IThumbnailSource? ScrubSource(Sequence sequence);
}
/// <summary>The signed-in server as remote cards see it: its sync engine, its key and a connection.</summary>
public sealed record RemoteSource(SyncService Service, string Server, ISyncRemote Remote);
/// <summary>
/// Thumbnails of server sequences without a copy here (BRIEF §4.4): the hero frame (else the first) from the proxy
/// cache when the sequence was fetched with proxies, otherwise the server's thumbnail of that frame through the API.
/// The first frame of a sequence without a hero is asked once (one row of its frames page) and remembered. Decoded at
/// a 64 px width step and kept in an LRU cache; failed downloads are not cached, so they are tried again.
/// </summary>
public sealed class RemoteThumbnails(Func<RemoteSource?> source, int capacity = 256) : ISequenceThumbnails, IDisposable
{
private const int WidthStep = 64;
private readonly ConcurrentDictionary<Guid, Guid?> _heroes = new();
/// <summary>The first frame of sequences without a hero frame (a sequence with no frame yet is asked again later).</summary>
private readonly ConcurrentDictionary<Guid, Guid> _firstFrames = new();
private ThumbnailCache<(Guid Sequence, int Width), ImageSource>? _cache;
private ThumbnailCache<(Guid Sequence, int Width), ImageSource> Cache => _cache ??= new(capacity, LoadAsync, maxConcurrentLoads: 4);
public Task<ImageSource?> HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct)
{
_heroes[sequence.Id] = sequence.HeroFrameId;
return Cache.GetAsync((sequence.Id, Math.Clamp((pixelWidth + WidthStep - 1) / WidthStep * WidthStep, WidthStep, 1024)), ct);
}
/// <summary>Remote cards do not scrub: every frame would be a download.</summary>
public IThumbnailSource? ScrubSource(Sequence sequence) => null;
/// <summary>Forgets every thumbnail (another server, or the cache was cleared).</summary>
public void Clear()
{
_cache?.Clear();
_firstFrames.Clear();
}
public void Dispose() => _cache?.Dispose();
private async Task<ImageSource?> LoadAsync((Guid Sequence, int Width) key, CancellationToken ct)
{
if (source() is not { } connection) return null;
var hero = _heroes.GetValueOrDefault(key.Sequence);
if (connection.Service.OpenRemote(connection.Server, key.Sequence) is { CachedCount: > 0 } cached)
{
var index = hero is { } id ? IndexOf(cached.Frames, id) : -1;
if (index < 0 || cached.Files[index] is null) index = FirstCached(cached.Files);
await using var file = new FileStream(cached.Files[index]!, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous);
return ThumbnailService.DecodeStream(file, cached.Frames[index].Orientation, key.Width);
}
var frameId = hero ?? await FirstFrameAsync(connection.Remote, key.Sequence, ct).ConfigureAwait(false);
if (frameId is null) return null;
using var thumbnail = new MemoryStream();
await connection.Remote.DownloadFrameAsync(frameId.Value, "thumb", thumbnail, ct).ConfigureAwait(false);
thumbnail.Position = 0;
// The server draws its thumbnails upright.
return ThumbnailService.DecodeStream(thumbnail, 1, key.Width);
}
private async Task<Guid?> FirstFrameAsync(ISyncRemote remote, Guid sequence, CancellationToken ct)
{
if (_firstFrames.TryGetValue(sequence, out var known)) return known;
if ((await remote.FirstFrameAsync(sequence, ct).ConfigureAwait(false))?.Id is not { } first) return null;
_firstFrames[sequence] = first;
return first;
}
private static int IndexOf(IReadOnlyList<Frame> frames, Guid id)
{
for (var i = 0; i < frames.Count; i++)
{
if (frames[i].Id == id) return i;
}
return -1;
}
private static int FirstCached(IReadOnlyList<string?> files)
{
for (var i = 0; i < files.Count; i++)
{
if (files[i] is not null) return i;
}
return -1;
}
}
+91
View File
@@ -0,0 +1,91 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Data.Repositories;
namespace Titano.App.Library;
/// <summary>A named set of Library filters and sort ("Night, 4K, not rendered"), BRIEF §12.2.</summary>
public sealed record SavedView
{
public const int MaxName = 40;
public required Guid Id { get; init; }
public required string Name { get; init; }
public string? Text { get; init; }
public int? Year { get; init; }
public string? Camera { get; init; }
public StatusFilter Status { get; init; }
public string? Tag { get; init; }
public OriginFilter Origin { get; init; }
public SequenceSort Sort { get; init; } = SequenceSort.Newest;
public static SavedView Of(Guid id, string name, LibraryFilter filter) => new()
{
Id = id,
Name = name.Trim(),
Text = string.IsNullOrWhiteSpace(filter.Text) ? null : filter.Text.Trim(),
Year = filter.Year,
Camera = filter.Camera,
Status = filter.Status,
Tag = filter.Tag,
Origin = filter.Origin,
Sort = filter.Sort,
};
public LibraryFilter ToFilter() => new() { Text = Text, Year = Year, Camera = Camera, Status = Status, Tag = Tag, Origin = Origin, Sort = Sort };
/// <summary>The Library shows exactly this view (search text compared trimmed and case-insensitively).</summary>
public bool Matches(LibraryFilter filter) =>
string.Equals(Text ?? string.Empty, filter.Text?.Trim() ?? string.Empty, StringComparison.OrdinalIgnoreCase)
&& Year == filter.Year && Camera == filter.Camera && Status == filter.Status && Tag == filter.Tag && Origin == filter.Origin && Sort == filter.Sort;
/// <summary>The problem of a view name, localized; null when it can be used.</summary>
/// <param name="others">Names of the other saved views (a name is used once).</param>
public static string? Validate(string? name, IEnumerable<string> others)
{
var trimmed = name?.Trim() ?? string.Empty;
if (trimmed.Length == 0) return Loc.L("Library.Views.Error.Empty");
if (trimmed.Length > MaxName || trimmed.Any(char.IsControl)) return Loc.L("Library.Views.Error.Long", MaxName);
return others.Contains(trimmed, StringComparer.CurrentCultureIgnoreCase) ? Loc.L("Library.Views.Error.Taken") : null;
}
}
/// <summary>Saved views as app-scope settings rows (<c>library.view.&lt;id&gt;</c>), one row per view.</summary>
public sealed class SavedViewStore(SettingsRepository settings)
{
private const string Prefix = "library.view.";
/// <summary>Every saved view by name; unreadable rows are skipped.</summary>
public async Task<IReadOnlyList<SavedView>> ListAsync(CancellationToken cancellationToken = default)
{
var views = new List<SavedView>();
foreach (var (key, json) in await settings.ListAsync(SettingScope.App, null, cancellationToken))
{
if (!key.StartsWith(Prefix, StringComparison.Ordinal)) continue;
try
{
if (JsonSerializer.Deserialize(json, SavedViewJson.Default.SavedView) is { } view) views.Add(view);
}
catch (JsonException ex)
{
Log.Warning("library", $"Saved view {key} is unreadable", ex);
}
}
return [.. views.OrderBy(v => v.Name, StringComparer.CurrentCultureIgnoreCase)];
}
/// <summary>Adds the view or replaces the one with its id.</summary>
public Task SaveAsync(SavedView view, CancellationToken cancellationToken = default) =>
settings.SetAsync(SettingScope.App, null, Key(view.Id), view, SavedViewJson.Default.SavedView, cancellationToken);
public Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default) => settings.DeleteAsync(SettingScope.App, null, Key(id), cancellationToken);
private static string Key(Guid id) => Prefix + id.ToString("N");
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true)]
[JsonSerializable(typeof(SavedView))]
internal sealed partial class SavedViewJson : JsonSerializerContext;
+80 -3
View File
@@ -1,20 +1,30 @@
using System.Text.Json;
using System.Windows.Media;
using Titano.App.Infrastructure;
using Titano.Core.Diagnostics;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Naming;
using Titano.Core.Project;
using Titano.Data.Processing;
using Titano.Data.Sync;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
using Titano.Ui.Visuals;
namespace Titano.App.Library;
/// <summary>One sequence of the Library grid and list (BRIEF §12.2).</summary>
/// <summary>One sequence of the Library grid and list (BRIEF §12.2): on this PC, or a server sequence without a copy here (a remote card).</summary>
public sealed class SequenceItem : ObservableObject
{
private readonly ThumbnailService? _thumbnails;
private readonly ISequenceThumbnails? _thumbnails;
private Sequence _sequence;
private SyncEntry? _sync;
private string? _syncToolTip;
private bool _canSync;
private string? _quickBlocker;
private string? _presetName;
private ImageSource? _thumbnail;
private IThumbnailSource? _scrub;
private CancellationTokenSource? _loading;
@@ -22,7 +32,7 @@ public sealed class SequenceItem : ObservableObject
private bool _isSelected;
private bool _isAnalysing;
public SequenceItem(Sequence sequence, ThumbnailService? thumbnails)
public SequenceItem(Sequence sequence, ISequenceThumbnails? thumbnails)
{
_sequence = sequence;
_thumbnails = thumbnails;
@@ -31,6 +41,38 @@ public sealed class SequenceItem : ObservableObject
public Sequence Sequence => _sequence;
public Guid Id => _sequence.Id;
/// <summary>Only on the signed-in server (the editor opens it with proxies; archive actions do not apply).</summary>
public bool IsRemote => _sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly };
/// <summary>Its row of the sync table of the signed-in server; null while signed out or not compared yet.</summary>
public SyncEntry? Sync => _sync;
/// <summary>The Sync quick action can run (<see cref="SyncToolTip"/> says what it does, or why not).</summary>
public bool CanSync => _canSync;
public string SyncToolTip => _syncToolTip ?? Loc.L("Library.Blocked.NotConnected");
/// <summary>The Analyse and Render quick actions can start (<see cref="AnalyseToolTip"/> says why not).</summary>
public bool CanRunQuick => _quickBlocker is null;
/// <summary>What Analyse does here or on the server, or why it cannot start.</summary>
public string AnalyseToolTip => _quickBlocker ?? Loc.L(IsRemote ? "Tooltips.Library.AnalyseServer" : "Tooltips.Library.Analyse");
/// <summary>
/// "Queue a render with 4K archive…": the preset the Render quick action queues, or why it cannot start. A remote
/// card's project lives on the server, which renders it with the sequence's own preset.
/// </summary>
public string RenderToolTip => _quickBlocker ?? (IsRemote ? Loc.L("Tooltips.Library.QuickRenderServer") : Loc.L("Tooltips.Library.QuickRender", PresetName));
/// <summary>
/// The export preset of the sequence's project: the one chosen in the editor, else the advisor's recommendation the
/// analyses store in the project (Auto), else the default.
/// </summary>
public string PresetName => _presetName ??= ResolvePreset(_sequence.SettingsJson);
/// <summary>How the card reacts to the mouse; remote cards have no frames here to scrub.</summary>
public string CardToolTip => Loc.L(IsRemote ? "Tooltips.Library.CardRemote" : "Tooltips.Library.Card");
/// <summary>User title or "{date} {camera}".</summary>
public string Title => _sequence.DisplayTitle;
@@ -70,6 +112,27 @@ public sealed class SequenceItem : ObservableObject
/// <summary>Frames for hover scrubbing; created on first use.</summary>
public IThumbnailSource? ScrubSource => _thumbnails is null || _sequence.FrameCount == 0 ? null : _scrub ??= _thumbnails.ScrubSource(_sequence);
/// <summary>The sync table's row of this sequence and what its Sync quick action does (or why it cannot).</summary>
public void SetSync(SyncEntry? entry, bool canSync, string toolTip)
{
_sync = entry;
_canSync = canSync;
_syncToolTip = toolTip;
OnPropertyChanged(nameof(Sync));
OnPropertyChanged(nameof(CanSync));
OnPropertyChanged(nameof(SyncToolTip));
}
/// <summary>Why Analyse and Render cannot start now (no engine here, or the server is not connected); null when they can.</summary>
public void SetQuickBlocker(string? blocker)
{
if (_quickBlocker == blocker) return;
_quickBlocker = blocker;
OnPropertyChanged(nameof(CanRunQuick));
OnPropertyChanged(nameof(AnalyseToolTip));
OnPropertyChanged(nameof(RenderToolTip));
}
public bool IsSelected
{
get => _isSelected;
@@ -90,6 +153,7 @@ public sealed class SequenceItem : ObservableObject
public void Update(Sequence sequence)
{
var heroChanged = sequence.HeroFrameId != _sequence.HeroFrameId || sequence.FrameCount != _sequence.FrameCount;
if (sequence.SettingsJson != _sequence.SettingsJson) _presetName = null;
_sequence = sequence;
if (heroChanged)
{
@@ -141,6 +205,19 @@ public sealed class SequenceItem : ObservableObject
}
}
private static string ResolvePreset(string? settingsJson)
{
try
{
var project = settingsJson is null ? new ProjectSettings() : ProjectSettings.FromJson(settingsJson);
return ProcessingJobs.PresetName(ExportResolver.Resolve(project.Export));
}
catch (JsonException)
{
return ProcessingJobs.PresetName(ExportResolver.Resolve(new ExportSettings()));
}
}
private void RaiseStatuses()
{
OnPropertyChanged(nameof(Statuses));
+3 -1
View File
@@ -17,7 +17,7 @@ public readonly record struct ThumbnailKey(Guid FrameId, int Width);
/// original and decoded by WIC at the requested width (falling back to decoding the original), turned upright,
/// frozen and kept in an LRU cache. Loads run off the UI thread and stop when the card scrolls away.
/// </summary>
public sealed class ThumbnailService : IDisposable
public sealed class ThumbnailService : ISequenceThumbnails, IDisposable
{
/// <summary>Embedded previews larger than this are not read (a damaged index would make us read gigabytes).</summary>
private const long MaxPreviewBytes = 64L << 20;
@@ -81,6 +81,8 @@ public sealed class ThumbnailService : IDisposable
/// <summary>Hover-scrub frames of a sequence, sampled to at most <paramref name="positions"/> positions.</summary>
public IThumbnailSource ScrubSource(Sequence sequence, int positions = 120) => new ScrubFrames(this, sequence, positions);
IThumbnailSource? ISequenceThumbnails.ScrubSource(Sequence sequence) => ScrubSource(sequence);
/// <summary>Drops decoded thumbnails (Settings › Storage › Clear).</summary>
public void Clear()
{
@@ -0,0 +1,60 @@
using System.Windows.Input;
using Titano.App.Archiving;
using Titano.App.Settings;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Data;
using Titano.Ui.Mvvm;
namespace Titano.App.Library;
/// <summary>Names a saved view: "Save view" (the current filters under a new name) or "Rename view".</summary>
public sealed class ViewNameDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<string, Task> _save;
/// <param name="others">Names of the other saved views (each name is used once).</param>
public ViewNameDialogViewModel(bool rename, string name, IReadOnlyList<string> others, Func<string, Task> save, Action<ArchiveDialogViewModel> close)
: base(close)
{
IsRename = rename;
_save = save;
Name = new EditableField(name, n => SavedView.Validate(n, others), _ => { }, () => Loc.L("Tooltips.Library.ViewName"));
Name.PropertyChanged += (_, _) =>
{
OnPropertyChanged(nameof(SaveToolTip));
CommandManager.InvalidateRequerySuggested();
};
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy && !Name.HasErrors);
}
public bool IsRename { get; }
public string Heading => Loc.L(IsRename ? "Library.Views.RenameHeading" : "Library.Views.SaveHeading");
public EditableField Name { get; }
public ICommand SaveCommand { get; }
public string SaveToolTip => Name.Error ?? Loc.L(IsRename ? "Tooltips.Library.ViewRenameApply" : "Tooltips.Library.ViewSaveApply");
private async Task SaveAsync()
{
ClearError();
IsBusy = true;
try
{
await _save(Name.Text.Trim());
Close();
}
catch (DatabaseException ex)
{
Log.Warning("library", "Saving a view failed", ex);
ShowError(ex);
}
finally
{
IsBusy = false;
}
}
}
+102 -265
View File
@@ -8,239 +8,66 @@
xmlns:infra="clr-namespace:Titano.App.Infrastructure"
xmlns:shell="clr-namespace:Titano.App.Shell">
<UserControl.Resources>
<!-- Keyboard focus drawn inside the row (DESIGN §4 ring): an outer ring would be clipped by the list's scroll viewer. -->
<Style x:Key="Focus.Inset">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Border BorderBrush="{DynamicResource Brush.Accent}" BorderThickness="2" CornerRadius="{StaticResource Radius.Control}" SnapsToDevicePixels="True" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- The dialogs (and their styles) are shared with the Library, which runs Delete… too. -->
<ResourceDictionary Source="pack://application:,,,/Titano;component/Archive/ArchiveDialogs.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- Keyboard focus drawn inside the row (DESIGN §4 ring): an outer ring would be clipped by the list's scroll viewer. -->
<Style x:Key="Focus.Inset">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Border BorderBrush="{DynamicResource Brush.Accent}" BorderThickness="2" CornerRadius="{StaticResource Radius.Control}" SnapsToDevicePixels="True" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--
Lists keep their panel's fill while the screen behind a dialog is disabled: the system template would paint them
white. Rows and buttons dim themselves.
-->
<Style TargetType="ListBox" BasedOn="{StaticResource {x:Type ListBox}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"
Padding="1" SnapsToDevicePixels="True">
<ScrollViewer Focusable="False" Padding="{TemplateBinding Padding}">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--
Lists keep their panel's fill while the screen behind a dialog is disabled: the system template would paint them
white. Rows and buttons dim themselves.
-->
<Style TargetType="ListBox" BasedOn="{StaticResource {x:Type ListBox}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"
Padding="1" SnapsToDevicePixels="True">
<ScrollViewer Focusable="False" Padding="{TemplateBinding Padding}">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="Text.PanelHeading" TargetType="TextBlock" BasedOn="{StaticResource Text.Section}">
<Setter Property="FontSize" Value="13" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style x:Key="Button.Bar" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="0,0,8,0" />
</Style>
<Style x:Key="Button.Tool" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Margin" Value="0,0,8,8" />
</Style>
<!-- Rows that only show text: focusable, so the arrow keys move through a long list. -->
<Style x:Key="ListBoxItem.Preview" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Inset}" />
<Setter Property="AutomationProperties.Name" Value="{Binding To}" />
<Setter Property="AutomationProperties.HelpText" Value="{Binding From}" />
</Style>
<!-- Report rows with their own buttons: Tab reaches every button. -->
<Style x:Key="ListBoxItem.Duplicate" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
<Setter Property="AutomationProperties.Name" Value="{Binding Row.Title}" />
<Setter Property="AutomationProperties.HelpText" Value="{Binding Row.Detail}" />
</Style>
<!-- Dialog labels: a column at least 116 px wide that grows with the longest label (DESIGN §2: no fixed-width labels). -->
<Style x:Key="Text.DialogLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}">
<Setter Property="TextTrimming" Value="None" />
</Style>
<!-- A status line screen readers announce when it changes. -->
<Style x:Key="Text.Live" TargetType="TextBlock">
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
<Setter Property="AutomationProperties.LiveSetting" Value="Polite" />
</Style>
<!-- A dialog's failure: one sentence in the error colour with its glyph, the engine's own text in the tooltip, announced at once. -->
<Style x:Key="Status.DialogError" TargetType="ui:StatusGlyph" BasedOn="{StaticResource {x:Type ui:StatusGlyph}}">
<Setter Property="Kind" Value="Error" />
<Setter Property="FontSize" Value="12" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Text" Value="{Binding ErrorText}" />
<Setter Property="ToolTip" Value="{Binding ErrorToolTip}" />
<Setter Property="AutomationProperties.LiveSetting" Value="Assertive" />
<Setter Property="infra:LiveRegion.Text" Value="{Binding ErrorText}" />
<Setter Property="Visibility" Value="{Binding ErrorText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
</Style>
<!-- A filter menu: its values, each checked while chosen. -->
<Style x:Key="MenuItem.Choice" TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Label}" />
<Setter Property="IsChecked" Value="{Binding IsChecked, Mode=OneWay}" />
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="ToolTip" Value="{l:Loc Tooltips.Archive.FilterChoice}" />
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
</Style>
<!-- Dialog card (DESIGN §4: Surface, Stroke, radius 12, 24 px shadow, two buttons). -->
<Style x:Key="Border.Dialog" TargetType="Border">
<Setter Property="Background" Value="{DynamicResource Brush.Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Stroke}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="{StaticResource Radius.Dialog}" />
<Setter Property="Padding" Value="24,18,24,20" />
<Setter Property="Effect" Value="{StaticResource Shadow.Popup}" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<DataTemplate DataType="{x:Type ar:RebuildDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{l:Loc Archive.Rebuild.Heading}" Style="{StaticResource Text.Title}" />
<ItemsControl ItemsSource="{Binding FactRows}" Focusable="False" Margin="0,14,0,0" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:DialogFact}">
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="FactLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Label}" Style="{StaticResource Text.DialogLabel}" />
<TextBlock x:Name="Value" Grid.Column="1" Text="{Binding Value}" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}"
Typography.NumeralAlignment="Tabular" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsPath}" Value="True">
<Setter TargetName="Value" Property="FlowDirection" Value="LeftToRight" />
<Setter TargetName="Value" Property="HorizontalAlignment" Value="Left" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}"
Visibility="{Binding BusyText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,18,0,0">
<Button Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True" IsCancel="True"
MinWidth="96" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Rebuild.Start}" Command="{Binding RebuildCommand}" ToolTip="{Binding RebuildToolTip}"
MinWidth="96" Margin="8,0,0,0" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ar:RenameDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="720" MaxHeight="560">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<Grid Grid.Row="1" Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Archive.Rename.Template}" Style="{StaticResource Text.DialogLabel}" />
<!-- A naming template keeps its tokens and separators in order in every language. -->
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Mono}" FlowDirection="LeftToRight"
Text="{Binding Template.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Template}"
ToolTip="{Binding Template.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Rename.Template}" />
</Grid>
<TextBlock Grid.Row="2" Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,6" Typography.NumeralAlignment="Tabular" />
<ListBox Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.Preview}" MinHeight="120"
AutomationProperties.Name="{l:Loc Archive.Rename.Preview}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ar:RenameRow}">
<Grid Height="30" TextElement.FontSize="12">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="120" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" MinWidth="120" />
</Grid.ColumnDefinitions>
<TextBlock x:Name="From" Style="{StaticResource Text.Cell}" Text="{Binding From}" Foreground="{DynamicResource Brush.TextMuted}" ToolTip="{Binding From}" />
<ui:Icon Grid.Column="1" Glyph="{StaticResource Icon.Forward}" Margin="10,0" VerticalAlignment="Center" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock x:Name="To" Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding To}" ToolTip="{Binding To}" />
</Grid>
<DataTemplate.Triggers>
<!-- Move lists folders: paths stay left to right; Rename lists titles, which read in the language's direction. -->
<DataTrigger Binding="{Binding DataContext.Mode, RelativeSource={RelativeSource AncestorType=ListBox}}" Value="Folders">
<Setter TargetName="From" Property="FlowDirection" Value="LeftToRight" />
<Setter TargetName="From" Property="HorizontalAlignment" Value="Left" />
<Setter TargetName="To" Property="FlowDirection" Value="LeftToRight" />
<Setter TargetName="To" Property="HorizontalAlignment" Value="Left" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<DockPanel Grid.Row="4" Margin="0,16,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Rename.Apply}" Command="{Binding ApplyCommand}"
ToolTip="{Binding ApplyToolTip}" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True"
IsCancel="True" MinWidth="96" />
<Grid Margin="0,0,12,0">
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" Typography.NumeralAlignment="Tabular" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
</Grid>
</DockPanel>
</Grid>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ar:RetagDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Archive.Retag.Add}" Style="{StaticResource Text.DialogLabel}" />
<TextBox Grid.Column="1" Text="{Binding Add.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Add}"
ToolTip="{Binding Add.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Retag.Add}" />
<TextBlock Grid.Row="1" Text="{l:Loc Archive.Retag.Remove}" Style="{StaticResource Text.DialogLabel}" Margin="0,10,14,0" />
<TextBox Grid.Row="1" Grid.Column="1" Margin="0,10,0,0" Text="{Binding Remove.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding Remove}" ToolTip="{Binding Remove.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Retag.Remove}" />
</Grid>
<TextBlock Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,0" Typography.NumeralAlignment="Tabular" />
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Retag.Apply}" Command="{Binding ApplyCommand}"
ToolTip="{Binding ApplyToolTip}" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True"
IsCancel="True" MinWidth="96" />
<Grid Margin="0,0,12,0">
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" Typography.NumeralAlignment="Tabular" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
</Grid>
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<Style x:Key="Text.PanelHeading" TargetType="TextBlock" BasedOn="{StaticResource Text.Section}">
<Setter Property="FontSize" Value="13" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style x:Key="Button.Bar" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="0,0,8,0" />
</Style>
<Style x:Key="Button.Tool" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Margin" Value="0,0,8,8" />
</Style>
<!-- Report rows with their own buttons: Tab reaches every button. -->
<Style x:Key="ListBoxItem.Duplicate" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
<Setter Property="AutomationProperties.Name" Value="{Binding Row.Title}" />
<Setter Property="AutomationProperties.HelpText" Value="{Binding Row.Detail}" />
</Style>
<!-- A filter menu: its values, each checked while chosen. -->
<Style x:Key="MenuItem.Choice" TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Label}" />
<Setter Property="IsChecked" Value="{Binding IsChecked, Mode=OneWay}" />
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="ToolTip" Value="{l:Loc Tooltips.Archive.FilterChoice}" />
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
</Style>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
@@ -288,6 +115,7 @@
<MenuItem Header="{l:Loc Archive.Maintenance.DryRun}" Command="{Binding MaintenanceDryRunCommand}" ToolTip="{l:Loc Tooltips.Archive.MaintenanceDryRun}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Archive.Maintenance.Proxies}" Command="{Binding RebuildProxiesCommand}" ToolTip="{Binding RebuildProxiesToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Archive.Maintenance.Backup}" Command="{Binding BackupCommand}" ToolTip="{l:Loc Tooltips.Archive.Backup}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Archive.Maintenance.Trash}" Command="{Binding TrashCommand}" ToolTip="{l:Loc Tooltips.Archive.Trash}" ToolTipService.ShowOnDisabled="True" />
<Separator />
<MenuItem Header="{l:Loc Archive.Maintenance.Relink}" Command="{Binding RelinkCommand}" ToolTip="{l:Loc Tooltips.Archive.Relink}" ToolTipService.ShowOnDisabled="True" />
</ContextMenu>
@@ -601,41 +429,50 @@
</Grid>
</Grid>
<!-- ===================== Mass operations on the selected, filtered set ===================== -->
<!-- ===================== Mass operations on the selected, filtered set; Delete… apart at the far right (Archive.html) ===================== -->
<Border Grid.Row="3" Style="{StaticResource Border.Panel}" Padding="14,8,6,0" Margin="0,14,0,0" MinHeight="48"
Visibility="{Binding IsOverview, Converter={StaticResource BoolToVisibility}}">
<WrapPanel VerticalAlignment="Center">
<TextBlock Text="{l:Loc Archive.Set.Label}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,10,8" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" BorderBrush="{DynamicResource Brush.Accent}" Click="OnOpenMenu" ToolTip="{l:Loc Tooltips.Archive.Set}"
AutomationProperties.Name="{Binding SetFilterName}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding SetText}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" MaxWidth="260" TextTrimming="CharacterEllipsis" />
<ui:Icon Glyph="{StaticResource Icon.ChevronDown}" Margin="6,0,0,0" VerticalAlignment="Center" />
</StackPanel>
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="{l:Loc Library.Filter.Camera}" ItemsSource="{Binding CameraChoices}" ItemContainerStyle="{StaticResource MenuItem.Choice}"
ToolTip="{l:Loc Tooltips.Archive.FilterCamera}" />
<MenuItem Header="{l:Loc Library.Filter.Status}" ItemsSource="{Binding StatusChoices}" ItemContainerStyle="{StaticResource MenuItem.Choice}"
ToolTip="{l:Loc Tooltips.Archive.FilterStatus}" />
<MenuItem Header="{l:Loc Library.Filter.Tags}" ItemsSource="{Binding TagChoices}" ItemContainerStyle="{StaticResource MenuItem.Choice}"
ToolTip="{l:Loc Tooltips.Archive.FilterTag}" />
<Separator />
<MenuItem Header="{l:Loc Archive.Set.ClearFilter}" Command="{Binding ClearFilterCommand}" ToolTip="{l:Loc Tooltips.Archive.ClearFilter}" ToolTipService.ShowOnDisabled="True" />
</ContextMenu>
</Button.ContextMenu>
</Button>
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="4,0,12,8" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Analyse}" Command="{Binding AnalyseSetCommand}" ToolTip="{Binding AnalyseSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Proxies}" Command="{Binding ProxiesSetCommand}" ToolTip="{Binding ProxiesSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Thumbnails}" Command="{Binding ThumbnailsSetCommand}"
ToolTip="{Binding ThumbnailsSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Verify}" Command="{Binding VerifySetCommand}" ToolTip="{Binding VerifySetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Rename}" Command="{Binding RenameSetCommand}" ToolTip="{Binding RenameSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Move}" Command="{Binding MoveSetCommand}" ToolTip="{Binding MoveSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Retag}" Command="{Binding RetagSetCommand}" ToolTip="{Binding RetagSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Export}" Command="{Binding ExportSetCommand}" ToolTip="{Binding ExportSetToolTip}" />
</WrapPanel>
<!-- Delete… last in the tab order too. -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<WrapPanel VerticalAlignment="Center">
<TextBlock Text="{l:Loc Archive.Set.Label}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,10,8" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" BorderBrush="{DynamicResource Brush.Accent}" Click="OnOpenMenu" ToolTip="{l:Loc Tooltips.Archive.Set}"
AutomationProperties.Name="{Binding SetFilterName}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding SetText}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" MaxWidth="260" TextTrimming="CharacterEllipsis" />
<ui:Icon Glyph="{StaticResource Icon.ChevronDown}" Margin="6,0,0,0" VerticalAlignment="Center" />
</StackPanel>
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="{l:Loc Library.Filter.Camera}" ItemsSource="{Binding CameraChoices}" ItemContainerStyle="{StaticResource MenuItem.Choice}"
ToolTip="{l:Loc Tooltips.Archive.FilterCamera}" />
<MenuItem Header="{l:Loc Library.Filter.Status}" ItemsSource="{Binding StatusChoices}" ItemContainerStyle="{StaticResource MenuItem.Choice}"
ToolTip="{l:Loc Tooltips.Archive.FilterStatus}" />
<MenuItem Header="{l:Loc Library.Filter.Tags}" ItemsSource="{Binding TagChoices}" ItemContainerStyle="{StaticResource MenuItem.Choice}"
ToolTip="{l:Loc Tooltips.Archive.FilterTag}" />
<Separator />
<MenuItem Header="{l:Loc Archive.Set.ClearFilter}" Command="{Binding ClearFilterCommand}" ToolTip="{l:Loc Tooltips.Archive.ClearFilter}" ToolTipService.ShowOnDisabled="True" />
</ContextMenu>
</Button.ContextMenu>
</Button>
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="4,0,12,8" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Analyse}" Command="{Binding AnalyseSetCommand}" ToolTip="{Binding AnalyseSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Proxies}" Command="{Binding ProxiesSetCommand}" ToolTip="{Binding ProxiesSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Thumbnails}" Command="{Binding ThumbnailsSetCommand}"
ToolTip="{Binding ThumbnailsSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Verify}" Command="{Binding VerifySetCommand}" ToolTip="{Binding VerifySetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Rename}" Command="{Binding RenameSetCommand}" ToolTip="{Binding RenameSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Move}" Command="{Binding MoveSetCommand}" ToolTip="{Binding MoveSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Retag}" Command="{Binding RetagSetCommand}" ToolTip="{Binding RetagSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Export}" Command="{Binding ExportSetCommand}" ToolTip="{Binding ExportSetToolTip}" />
</WrapPanel>
<Button Grid.Column="1" Style="{StaticResource Button.Destructive}" Height="30" Margin="8,0,8,8" VerticalAlignment="Top" Content="{l:Loc Archive.Set.Delete}"
Command="{Binding DeleteSetCommand}" ToolTip="{Binding DeleteSetToolTip}" />
</Grid>
</Border>
<ui:EmptyState Grid.Row="2" Message="{l:Loc Archive.Empty}" Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}">
@@ -643,7 +480,7 @@
</ui:EmptyState>
</Grid>
<!-- In-window dialogs (rebuild, rename, retag) over a scrim; the keyboard stays inside the dialog. -->
<!-- In-window dialogs (rebuild, rename, retag, trash) over a scrim; the keyboard stays inside the dialog. -->
<Grid Visibility="{Binding IsDialogOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
<Border Background="{DynamicResource Brush.Scrim}" />
+39 -4
View File
@@ -25,8 +25,9 @@ namespace Titano.App.Sections;
/// <summary>
/// Archive manager (BRIEF §12.5, Archive.html): the archive's tree (years, sequences) with its availability, its
/// figures and charts, mass operations on the selected and filtered set (analyse, proxies, thumbnails, verify, rename,
/// move, retag, CSV), and the operations on the whole archive as jobs (scan, rebuild with its dialog, verify,
/// maintenance), plus the maintenance view: index health, duplicates and orphans with safe fixes, recent runs. The
/// move, retag, CSV, delete into the trash), and the operations on the whole archive as jobs (scan, rebuild with its
/// dialog, verify, maintenance), the trash, plus the maintenance view: index health, duplicates and orphans with safe
/// fixes, recent runs. The
/// tree selection is only ever changed by the user: reloads and expanding keep it.
/// </summary>
public sealed class ArchiveViewModel : SectionViewModel
@@ -97,6 +98,8 @@ public sealed class ArchiveViewModel : SectionViewModel
MoveSetCommand = new AsyncRelayCommand(() => OpenRenameDialogAsync(RenameMode.Folders), () => HasSet() && IsOnline());
RetagSetCommand = new RelayCommand(OpenRetag, () => HasSet() && IsOnline());
ExportSetCommand = new AsyncRelayCommand(ExportAsync, HasSet);
DeleteSetCommand = new AsyncRelayCommand(DeleteSetAsync, () => HasSet() && IsOnline());
TrashCommand = new AsyncRelayCommand(OpenTrashAsync, () => _archive is not null);
FindDuplicatesCommand = new AsyncRelayCommand(FindDuplicatesAsync, () => _archive is not null && _search is null);
FindOrphansCommand = new AsyncRelayCommand(FindOrphansAsync, () => IsOnline() && _search is null);
@@ -162,6 +165,7 @@ public sealed class ArchiveViewModel : SectionViewModel
public string RenameSetToolTip => WhenSet("Tooltips.Archive.SetRename", needsOnline: true);
public string MoveSetToolTip => WhenSet("Tooltips.Archive.SetMove", needsOnline: true);
public string RetagSetToolTip => WhenSet("Tooltips.Archive.SetRetag", needsOnline: true);
public string DeleteSetToolTip => WhenSet("Tooltips.Archive.SetDelete", needsOnline: true);
public ICommand ScanCommand { get; }
public ICommand RebuildCommand { get; }
@@ -178,6 +182,9 @@ public sealed class ArchiveViewModel : SectionViewModel
public ICommand RelinkCommand { get; }
public ICommand HistoryCommand { get; }
/// <summary>"Maintenance ▾ › Trash…": the sequences deleted from this archive, each restorable.</summary>
public ICommand TrashCommand { get; }
// ---------------- Overview ----------------
public ObservableCollection<ArchiveTreeRowViewModel> TreeRows { get; } = [];
@@ -257,6 +264,9 @@ public sealed class ArchiveViewModel : SectionViewModel
public ICommand RetagSetCommand { get; }
public ICommand ExportSetCommand { get; }
/// <summary>Moves the set to the archive's trash after its dry run and a typed confirmation.</summary>
public ICommand DeleteSetCommand { get; }
/// <summary>The view reports the rows the user selected; the list's own clearing while rows are rebuilt is not a choice.</summary>
public void SetSelection(IEnumerable<ArchiveTreeRowViewModel> rows)
{
@@ -333,7 +343,7 @@ public sealed class ArchiveViewModel : SectionViewModel
// ---------------- Dialogs ----------------
/// <summary>The open in-window dialog (rebuild, rename, retag); null when none.</summary>
/// <summary>The open in-window dialog (rebuild, rename, retag, trash); null when none.</summary>
public ArchiveDialogViewModel? Dialog
{
get => _dialog;
@@ -534,6 +544,7 @@ public sealed class ArchiveViewModel : SectionViewModel
OnPropertyChanged(nameof(RenameSetToolTip));
OnPropertyChanged(nameof(MoveSetToolTip));
OnPropertyChanged(nameof(RetagSetToolTip));
OnPropertyChanged(nameof(DeleteSetToolTip));
CommandManager.InvalidateRequerySuggested();
}
@@ -660,6 +671,30 @@ public sealed class ArchiveViewModel : SectionViewModel
await dialog.PlanAsync();
}
/// <summary>
/// Delete… on the set: the dry run, the typed confirmation and the move into the trash, in the in-window dialog the
/// Library shares, which says how far it is and stops on Cancel. True when something left the archive.
/// </summary>
public async Task<bool> DeleteSetAsync()
{
var dialog = new DeleteDialogViewModel(Shell, [.. Set().Select(s => s.Id)], CloseDialog);
OpenDialog(dialog);
return await dialog.RunAsync();
}
/// <summary>Opens the trash of the archive and reads it.</summary>
public async Task OpenTrashAsync()
{
if (Services.Archives is not { } archives || _archive is not { } archive) return;
var dialog = new TrashDialogViewModel(archives, archive, async () =>
{
await LoadAsync();
await Shell.Library.RefreshAsync();
}, CloseDialog);
OpenDialog(dialog);
await dialog.LoadAsync();
}
private void OpenRetag()
{
if (Services.Archives is not { } archives) return;
@@ -754,7 +789,7 @@ public sealed class ArchiveViewModel : SectionViewModel
var folder = Services.Dialogs.PickFolder(Loc.L("Library.Export.Title"));
if (folder is null || set.Count == 0) return;
var path = Path.Combine(folder, $"Titano sequences {DateTime.Now:yyyy-MM-dd HHmm}.csv");
var csv = LibraryViewModel.Csv(set);
var csv = LibraryCsv.Write(set);
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));
+374 -187
View File
@@ -4,180 +4,332 @@
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
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">
xmlns:lib="clr-namespace:Titano.App.Library"
xmlns:shell="clr-namespace:Titano.App.Shell">
<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>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Titano;component/Archive/ArchiveDialogs.xaml" />
</ResourceDictionary.MergedDictionaries>
<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>
<Style x:Key="Button.Bar" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="0,0,8,8" />
</Style>
<!-- Quick actions revealed on a card (28 px) or a row (26 px, DESIGN §4). -->
<Style x:Key="Button.Quick" TargetType="Button" BasedOn="{StaticResource Button.Icon}">
<Setter Property="Width" Value="28" />
<Setter Property="Height" Value="28" />
<Setter Property="MinWidth" Value="28" />
<Setter Property="Margin" Value="6,0,0,0" />
</Style>
<Style x:Key="Button.RowQuick" TargetType="Button" BasedOn="{StaticResource Button.Quick}">
<Setter Property="Width" Value="26" />
<Setter Property="Height" Value="26" />
<Setter Property="MinWidth" Value="26" />
</Style>
<!-- A menu of choices (saved views, ratings): each checked while it is the one in force. -->
<Style x:Key="MenuItem.View" TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Label}" />
<Setter Property="IsChecked" Value="{Binding IsChecked, Mode=OneWay}" />
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="ToolTip" Value="{l:Loc Tooltips.Library.ViewChoice}" />
</Style>
<Style x:Key="MenuItem.Rating" TargetType="MenuItem" BasedOn="{StaticResource MenuItem.View}">
<Setter Property="ToolTip" Value="{l:Loc Tooltips.Library.RateChoice}" />
</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>
<!-- A row's quick actions: on the hovered row, on selected rows and while the keyboard is in the row (Tab reaches them). -->
<Style x:Key="Border.RowActions" TargetType="Border">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=ListBoxItem}}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding IsKeyboardFocusWithin, RelativeSource={RelativeSource AncestorType=ListBoxItem}}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
<!-- The toolbar's filters: each capped and trimmed; they wrap to a second line rather than push the right-hand group out. -->
<Style x:Key="ComboBox.ToolbarFilter" TargetType="ComboBox" BasedOn="{StaticResource ComboBox.Filter}">
<Setter Property="Margin" Value="10,4,0,4" />
<Setter Property="MaxWidth" Value="170" />
<Setter Property="ItemTemplate" Value="{StaticResource Template.FilterOption}" />
</Style>
<ItemsPanelTemplate x:Key="Panel.Row">
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
<!-- Save view / Rename view: one name field. -->
<DataTemplate DataType="{x:Type lib:ViewNameDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Library.Views.Name}" Style="{StaticResource Text.DialogLabel}" />
<TextBox Grid.Column="1" Text="{Binding Name.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Name}"
ToolTip="{Binding Name.ToolTip}" AutomationProperties.Name="{l:Loc Library.Views.Name}" />
</Grid>
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Library.Views.Save}" Command="{Binding SaveCommand}"
ToolTip="{Binding SaveToolTip}" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True"
MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="56" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid IsEnabled="{Binding IsContentEnabled}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</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>
<!--
Toolbar (Main.html): search, filters, sort · saved views, layout switch, rescan. The search box gives way first
(down to 160 px); filters that still do not fit wrap to a second line, so the right-hand group is never cut.
-->
<Grid Grid.ColumnSpan="2" Margin="20,0" MinHeight="56">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="260" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox VerticalAlignment="Top" Margin="0,12,0,0" 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}" />
<WrapPanel Grid.Column="1" VerticalAlignment="Top" Margin="0,8">
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Years}" SelectedItem="{Binding SelectedYear}" Tag="{Binding IsYearFiltered}"
ToolTip="{l:Loc Tooltips.Library.Year}" AutomationProperties.Name="{l:Loc Library.Filter.Year}" />
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Cameras}" SelectedItem="{Binding SelectedCamera}" Tag="{Binding IsCameraFiltered}"
ToolTip="{l:Loc Tooltips.Library.Camera}" AutomationProperties.Name="{l:Loc Library.Filter.Camera}" />
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Statuses}" SelectedItem="{Binding SelectedStatus}" Tag="{Binding IsStatusFiltered}"
ToolTip="{l:Loc Tooltips.Library.Status}" AutomationProperties.Name="{l:Loc Library.Filter.Status}" />
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Tags}" SelectedItem="{Binding SelectedTag}" Tag="{Binding IsTagFiltered}"
ToolTip="{l:Loc Tooltips.Library.Tags}" AutomationProperties.Name="{l:Loc Library.Filter.Tags}" />
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Origins}" SelectedItem="{Binding SelectedOrigin}" Tag="{Binding IsOriginFiltered}"
ToolTip="{l:Loc Tooltips.Library.Origin}" AutomationProperties.Name="{l:Loc Library.Filter.Origin}"
Visibility="{Binding ShowsOrigin, Converter={StaticResource BoolToVisibility}}" />
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Sorts}" SelectedItem="{Binding SelectedSort}"
ToolTip="{l:Loc Tooltips.Library.Sort}" AutomationProperties.Name="{l:Loc Library.Sort}" />
</WrapPanel>
<StackPanel Grid.Column="2" Orientation="Horizontal" VerticalAlignment="Top" Margin="10,12,0,0">
<Button x:Name="ViewsButton" Click="OnOpenMenu" ui:ButtonIcon.Glyph="{StaticResource Icon.Filter}" ToolTip="{Binding ViewsToolTip}"
AutomationProperties.Name="{l:Loc Library.Views}" Margin="0,0,10,0">
<Button.Style>
<Style TargetType="Button" BasedOn="{StaticResource Button.Icon}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsViewActive}" Value="True">
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
<Setter Property="Foreground" Value="{DynamicResource Brush.Accent}" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="{l:Loc Library.Views.Apply}" ItemsSource="{Binding ViewChoices}" ItemContainerStyle="{StaticResource MenuItem.View}"
IsEnabled="{Binding HasViews}" ToolTip="{Binding ViewsApplyToolTip}" ToolTipService.ShowOnDisabled="True" />
<Separator />
<MenuItem Header="{l:Loc Library.Views.SaveMenu}" Command="{Binding SaveViewCommand}" ToolTip="{Binding ViewSaveToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Library.Views.RenameMenu}" Command="{Binding RenameViewCommand}" ToolTip="{Binding ViewRenameToolTip}"
ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Library.Views.Delete}" Command="{Binding DeleteViewCommand}" ToolTip="{Binding ViewDeleteToolTip}"
ToolTipService.ShowOnDisabled="True" />
</ContextMenu>
</Button.ContextMenu>
</Button>
<v:SegmentedControl 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:SegmentedItem Glyph="{StaticResource Icon.ViewTimeline}" ToolTip="{l:Loc Tooltips.Library.Timeline}" AutomationProperties.Name="{l:Loc Library.View.Timeline}" />
</v:SegmentedControl>
<Button 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" />
</StackPanel>
</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.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>
<!-- Timeline: one band per year, photos per month; a month narrows to its year and scrolls the grid to it. -->
<Border Grid.Row="1" Grid.ColumnSpan="2" Style="{StaticResource Border.Panel}" Margin="20,4,20,8" Padding="14,8"
Visibility="{Binding IsTimeline, Converter={StaticResource BoolToVisibility}}">
<ScrollViewer MaxHeight="172" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
<v:TimelineBands x:Name="Timeline" Bands="{Binding TimelineBands}" SlotLabels="{Binding MonthLabels}" BandHeight="56"
CurrentBand="{Binding TimelineBand, Mode=OneWay}" CurrentSlot="{Binding TimelineSlot, Mode=OneWay}" ValueFormatter="{Binding CountFormatter}"
SlotActivated="OnSlotActivated" ToolTip="{l:Loc Tooltips.Library.TimelineBands}" AutomationProperties.Name="{l:Loc Library.View.Timeline}" />
</ScrollViewer>
</Border>
<!-- 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}}">
<!-- Grid view (also under the timeline): virtualised, recycling card grid. -->
<ListBox x:Name="CardGrid" Grid.Row="2" 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" KeyboardNavigation.TabNavigation="Continue">
<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="{Binding CardToolTip}">
<v:SequenceCard.ActionsContent>
<StackPanel Orientation="Horizontal">
<Button Style="{StaticResource Button.Quick}" 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}" />
<Button Style="{StaticResource Button.Quick}" ui:ButtonIcon.Glyph="{StaticResource Icon.Analyse}"
Command="{Binding DataContext.AnalyseItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{Binding AnalyseToolTip}" AutomationProperties.Name="{l:Loc Library.Action.Analyse}" />
<Button Style="{StaticResource Button.Quick}" ui:ButtonIcon.Glyph="{StaticResource Icon.Render}"
Command="{Binding DataContext.RenderItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{Binding RenderToolTip}" AutomationProperties.Name="{l:Loc Library.Action.Render}" />
<Button Style="{StaticResource Button.Quick}" ui:ButtonIcon.Glyph="{StaticResource Icon.Sync}"
Command="{Binding DataContext.SyncItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{Binding SyncToolTip}" AutomationProperties.Name="{l:Loc Library.Action.Sync}" />
</StackPanel>
</v:SequenceCard.ActionsContent>
</v:SequenceCard>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- List view: virtualised table with sortable headers; columns share the width, row actions appear on the hovered row. -->
<Border Grid.Row="2" Grid.ColumnSpan="2" 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="2*" MinWidth="160" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" MinWidth="100" />
<ColumnDefinition Width="72" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="64" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="*" MinWidth="120" />
</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}"
KeyboardNavigation.TabNavigation="Continue">
<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="2*" MinWidth="160" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" MinWidth="100" />
<ColumnDefinition Width="72" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="64" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="*" MinWidth="120" />
</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" />
<Border Grid.Column="7" HorizontalAlignment="Right" Background="{DynamicResource Brush.Card}" Padding="6,0,0,0" Style="{StaticResource Border.RowActions}">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<Button Style="{StaticResource Button.RowQuick}" 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}" />
<Button Style="{StaticResource Button.RowQuick}" ui:ButtonIcon.Glyph="{StaticResource Icon.Analyse}"
Command="{Binding DataContext.AnalyseItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{Binding AnalyseToolTip}" AutomationProperties.Name="{l:Loc Library.Action.Analyse}" />
<Button Style="{StaticResource Button.RowQuick}" ui:ButtonIcon.Glyph="{StaticResource Icon.Render}"
Command="{Binding DataContext.RenderItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{Binding RenderToolTip}" AutomationProperties.Name="{l:Loc Library.Action.Render}" />
<Button Style="{StaticResource Button.RowQuick}" ui:ButtonIcon.Glyph="{StaticResource Icon.Sync}"
Command="{Binding DataContext.SyncItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{Binding SyncToolTip}" AutomationProperties.Name="{l:Loc Library.Action.Sync}" />
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
<!-- Empty states: one sentence plus the first actions (Components.html). -->
<ui:EmptyState Grid.Row="2" Grid.ColumnSpan="2" 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.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="2" Grid.ColumnSpan="2" 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>
<!-- One sequence selected in the grid or the timeline: its details (320 px, DESIGN §3). -->
<Border Grid.Row="2" Grid.Column="1" Width="320" Margin="0,4,20,12" Style="{StaticResource Border.Panel}" Padding="16"
Visibility="{Binding ShowsDetails, Converter={StaticResource BoolToVisibility}}">
<ScrollViewer VerticalScrollBarVisibility="Auto" Focusable="False" DataContext="{Binding Selected}">
<StackPanel>
<v:AspectRatioDecorator>
<Border CornerRadius="6" Background="{DynamicResource Brush.Preview}">
@@ -218,38 +370,73 @@
<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" />
<!-- A folder path reads left to right in every language. -->
<TextBlock Grid.Row="6" Grid.Column="1" Text="{Binding Sequence.Folder}" TextWrapping="Wrap" Margin="0,4,0,0" FlowDirection="LeftToRight"
HorizontalAlignment="Left" />
<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.Render}" Command="{Binding DataContext.RenderItemCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
CommandParameter="{Binding}" ToolTip="{Binding RenderToolTip}" ui:ButtonIcon.Glyph="{StaticResource Icon.Render}" 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" />
ToolTip="{Binding DataContext.RevealToolTip, RelativeSource={RelativeSource AncestorType=UserControl}}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}"
Margin="0,0,8,8" />
</WrapPanel>
</StackPanel>
</ScrollViewer>
</Border>
<!-- 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" />
<!--
Mass actions bar on the selection (BRIEF §12.2): each button disabled with its reason when it cannot run on it.
Delete… stands apart at the far right (Archive.html), the destructive action last.
-->
<Border Grid.Row="3" Grid.ColumnSpan="2" Style="{StaticResource Border.Panel}" Padding="14,8,6,0" Margin="20,0,20,12" MinHeight="48"
Visibility="{Binding HasSelection, Converter={StaticResource BoolToVisibility}}">
<!-- Delete… last in the tab order too. -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<WrapPanel VerticalAlignment="Center">
<TextBlock Text="{Binding SelectionTitle}" FontWeight="SemiBold" VerticalAlignment="Center" Margin="0,0,8,8" Typography.NumeralAlignment="Tabular" />
<TextBlock Text="{Binding SelectionSummary}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,12,8"
Typography.NumeralAlignment="Tabular" />
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="0,0,12,8" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Analyse}" Command="{Binding AnalyseCommand}" ToolTip="{Binding AnalyseToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Proxies}" Command="{Binding ProxiesCommand}" ToolTip="{Binding ProxiesToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Verify}" Command="{Binding VerifyCommand}" ToolTip="{Binding VerifyToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Tag}" Command="{Binding TagCommand}" ToolTip="{Binding TagToolTip}" />
<Button Style="{StaticResource Button.Bar}" Click="OnOpenMenu" IsEnabled="{Binding CanRate}" ToolTip="{Binding RateToolTip}" AutomationProperties.Name="{l:Loc Library.Action.Rate}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{l:Loc Library.Action.Rate}" />
<ui:Icon Glyph="{StaticResource Icon.ChevronDown}" Margin="6,0,0,0" VerticalAlignment="Center" />
</StackPanel>
<Button.ContextMenu>
<ContextMenu ItemsSource="{Binding RatingChoices}" ItemContainerStyle="{StaticResource MenuItem.Rating}" />
</Button.ContextMenu>
</Button>
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Move}" Command="{Binding MoveCommand}" ToolTip="{Binding MoveToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Upload}" Command="{Binding UploadCommand}" ToolTip="{Binding UploadToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Download}" Command="{Binding DownloadCommand}" ToolTip="{Binding DownloadToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.ExportList}" Command="{Binding ExportListCommand}" ToolTip="{Binding ExportListToolTip}" />
<Button Style="{StaticResource Button.Subtle}" Height="30" Margin="0,0,8,8" Content="{l:Loc Library.Action.ClearSelection}" Command="{Binding ClearSelectionCommand}"
ToolTip="{l:Loc Tooltips.Library.ClearSelection}" />
</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>
<Button Grid.Column="1" Style="{StaticResource Button.Destructive}" Height="30" Margin="8,0,8,8" VerticalAlignment="Top"
Content="{l:Loc Library.Action.Delete}" Command="{Binding DeleteCommand}" ToolTip="{Binding DeleteToolTip}" />
</Grid>
</Border>
</Grid>
<!-- In-window dialogs (tags, move, view name, delete) over a scrim; the keyboard stays inside the dialog. -->
<Grid Visibility="{Binding IsDialogOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
<Border Background="{DynamicResource Brush.Scrim}" />
<ContentPresenter x:Name="DialogHost" Content="{Binding Dialog}" Margin="20" />
</Grid>
</Grid>
</UserControl>
+52 -2
View File
@@ -1,15 +1,65 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;
using Titano.App.Library;
using Titano.Ui.Visuals;
namespace Titano.App.Sections;
public partial class LibraryView : UserControl
{
public LibraryView() => InitializeComponent();
public LibraryView()
{
InitializeComponent();
DataContextChanged += OnDataContextChanged;
}
private LibraryViewModel? Model => DataContext as LibraryViewModel;
/// <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 (Model is not { } vm || e.ExtentHeight <= 0) return;
if (e.VerticalOffset + e.ViewportHeight >= e.ExtentHeight - 2 * Math.Max(e.ViewportHeight, 200)) _ = vm.LoadMoreAsync();
}
/// <summary>A month of the timeline: the Library narrows to its year and the grid scrolls to it.</summary>
private void OnSlotActivated(object sender, ChartItemEventArgs e) => Model?.ShowSlot(e.Row, e.Column);
/// <summary>"Saved views" and "Rate ▾" open their menu under themselves.</summary>
private void OnOpenMenu(object sender, RoutedEventArgs e)
{
if (sender is not Button { ContextMenu: { } menu } button) return;
menu.DataContext = DataContext;
menu.PlacementTarget = button;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is LibraryViewModel old)
{
old.ScrollRequested -= OnScrollRequested;
old.PropertyChanged -= OnModelChanged;
}
if (e.NewValue is LibraryViewModel model)
{
model.ScrollRequested += OnScrollRequested;
model.PropertyChanged += OnModelChanged;
}
}
private void OnScrollRequested(SequenceItem item) =>
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => CardGrid.ScrollIntoView(item));
/// <summary>A dialog that opens takes the keyboard: its first field or button.</summary>
private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(LibraryViewModel.Dialog) || Model?.Dialog is null || !IsVisible) return;
Dispatcher.BeginInvoke(DispatcherPriority.Input, () => DialogHost.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)));
}
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -14,7 +14,7 @@
<TextBlock Text="{Binding Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" TextTrimming="None" LineHeight="18" />
<Border Style="{StaticResource Border.Card}" Margin="0,16,0,0" Padding="12,10" ToolTip="{Binding DetailToolTip}"
Visibility="{Binding Detail, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<TextBlock Text="{Binding Detail}" FontFamily="{StaticResource Font.Mono}" FontSize="{StaticResource Size.Secondary}" TextWrapping="Wrap" TextTrimming="None" LineHeight="18"
<TextBlock x:Name="DetailText" Text="{Binding Detail}" FontFamily="{StaticResource Font.Mono}" FontSize="{StaticResource Size.Secondary}" TextWrapping="Wrap" TextTrimming="None" LineHeight="18"
FlowDirection="LeftToRight" />
</Border>
<StackPanel x:Name="Typing" Margin="0,16,0,0" Visibility="Collapsed">
@@ -12,6 +12,12 @@ public sealed partial class ConfirmDialog : TitanoWindow
DataContext = request;
InitializeComponent();
Action.SetResourceReference(StyleProperty, request.IsDestructive ? "Button.Destructive" : "Button.Primary");
if (!request.IsDetailMonospaced)
{
// Names and sentences follow the reading direction; only fingerprints stay left to right.
DetailText.SetResourceReference(FontFamilyProperty, "Font.Ui");
DetailText.ClearValue(FlowDirectionProperty);
}
if (request.TypedConfirmation is null)
{
Loaded += (_, _) => Safe.Focus();
+28
View File
@@ -8,6 +8,7 @@ using Titano.App.DesignTime;
using Titano.App.Editor;
using Titano.App.Import;
using Titano.App.Infrastructure;
using Titano.App.Library;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.Core.Diagnostics;
@@ -65,6 +66,8 @@ public static class ScreenCapture
await shell.Services.Server.RestoreAsync();
await shell.Services.Sync.RefreshAsync();
await shell.Server.Sync.ReloadAsync();
// The server's sequences without a copy here join the Library as remote cards.
await shell.Library.RefreshAsync();
shell.About.SetResult(null);
await shell.Settings.DetectEncodersAsync();
await shell.Settings.SelfTestAsync();
@@ -86,6 +89,7 @@ public static class ScreenCapture
shell.IsRailCollapsed = true;
written += await SaveAsync(window, directory, "library-rail-collapsed", theme, waitForThumbnails: shell);
shell.IsRailCollapsed = false;
written += await CaptureLibraryScenesAsync(window, shell, directory, theme);
shell.Navigate(SectionKey.Jobs);
if (shell.Jobs.Rows.Count > 0) shell.Jobs.Rows[0].IsExpanded = true;
@@ -156,6 +160,30 @@ public static class ScreenCapture
}
}
/// <summary>
/// <c>library-timeline</c>, <c>library-mass</c> (the selection with the whole bar), <c>library-delete</c> (the dry run
/// of deleting that selection, behind its typed confirmation), <c>library-remote</c> (the server's sequences as
/// remote cards) and <c>library-viewname</c> (Save view), then the Library as it was.
/// </summary>
private static async Task<int> CaptureLibraryScenesAsync(MainWindow window, ShellViewModel shell, string directory, AppTheme theme)
{
var written = 0;
foreach (var scene in LibraryScenes.Scenes)
{
DismissToasts(window);
await LibraryScenes.ShowAsync(shell, scene);
written += await SaveAsync(window, directory, "library-" + scene, theme, waitForThumbnails: shell);
if (scene == "mass" && await LibraryScenes.DeleteRequestAsync(shell) is { } request)
written += await SaveDialogAsync(new ConfirmDialog(request), directory, "library-delete", theme);
}
shell.Library.Dialog?.CloseCommand.Execute(null);
shell.Library.ClearSelectionCommand.Execute(null);
shell.Library.ClearFiltersCommand.Execute(null);
shell.Library.LayoutIndex = 0;
await shell.Library.RefreshAsync();
return written;
}
private static void SelectSyncFilter(ShellViewModel shell, SyncFilter filter) =>
shell.Server.Sync.Chips.First(c => c.Filter == filter).SelectCommand.Execute(null);
+52 -10
View File
@@ -10,7 +10,8 @@ namespace Titano.Data.Archiving;
/// <summary>
/// What the desktop client and the server call to work with archives (BRIEF §7, §12.4, §12.5, §14.4): open, create
/// or adopt an archive, plan and apply mass renames, plan imports and card erases, query duplicates and orphans, and
/// or adopt an archive, plan and apply mass renames, plan imports and card erases, delete sequences into the trash and
/// restore them, query duplicates and orphans, and
/// the job handlers for the long operations (enqueue them with <see cref="ArchiveJobs"/>).
/// </summary>
public sealed class ArchiveService : IJobHandlerProvider
@@ -29,6 +30,7 @@ public sealed class ArchiveService : IJobHandlerProvider
Renamer = new MassRenamer(db, _writer, Indexer);
Images = new ArchiveImages(db, _writer, Indexer);
Imports = new ImportService(db, Ingest);
Trash = new SequenceTrash(db, _writer, Indexer);
}
public ArchiveIndexer Indexer { get; }
@@ -42,6 +44,9 @@ public sealed class ArchiveService : IJobHandlerProvider
public ArchiveImages Images { get; }
public ImportService Imports { get; }
/// <summary>Deletes sequences into the archive's trash and restores them.</summary>
public SequenceTrash Trash { get; }
/// <summary>Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs; register them on the <see cref="JobEngine"/>.</summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
[
@@ -110,20 +115,37 @@ public sealed class ArchiveService : IJobHandlerProvider
public static ArchiveAvailability GetAvailability(Archive archive) => ArchiveVolume.Probe(new ArchivePaths(archive.RootPath));
/// <summary>Changes title, tags, rating and notes in the sidecar and the index together (settings version + 1).</summary>
public async Task<Sequence> SetSequenceInfoAsync(Guid sequenceId, string? title, IReadOnlyList<string> tags, int rating, string? notes,
CancellationToken cancellationToken = default)
public Task<Sequence> SetSequenceInfoAsync(Guid sequenceId, string? title, IReadOnlyList<string> tags, int rating, string? notes,
CancellationToken cancellationToken = default) =>
EditSequenceInfoAsync(sequenceId, _ => new SequenceInfo(title, tags, rating, notes), cancellationToken);
/// <summary>
/// Changes some of title, tags, rating and notes from their current values — read under the sequence's lease from
/// the sidecar, or from the index when it is ahead (an edit made there only) — so fields <paramref name="edit"/>
/// leaves alone keep any change made since the caller read the sequence. Sidecar and index change together
/// (settings version + 1).
/// </summary>
public async Task<Sequence> EditSequenceInfoAsync(Guid sequenceId, Func<SequenceInfo, SequenceInfo> edit, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(edit);
var (archive, sequence) = await LoadSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var manifest = await _writer.UpdateAsync(paths, sequenceId, sequence.Folder, m => m with
var manifest = await _writer.UpdateAsync(paths, sequenceId, sequence.Folder, m =>
{
Title = string.IsNullOrWhiteSpace(title) ? null : title.Trim(),
Tags = tags,
Rating = rating,
Notes = notes,
Versions = m.Versions with { Settings = System.Math.Max(m.Versions.Settings, sequence.SettingsVersion) + 1 },
UpdatedAt = DateTimeOffset.UtcNow,
var current = sequence.SettingsVersion > m.Versions.Settings
? new SequenceInfo(sequence.Title, sequence.Tags, sequence.Rating, sequence.Notes)
: new SequenceInfo(m.Title, m.Tags, m.Rating, m.Notes);
var info = edit(current);
return m with
{
Title = string.IsNullOrWhiteSpace(info.Title) ? null : info.Title.Trim(),
Tags = info.Tags,
Rating = info.Rating,
Notes = info.Notes,
Versions = m.Versions with { Settings = System.Math.Max(m.Versions.Settings, sequence.SettingsVersion) + 1 },
UpdatedAt = DateTimeOffset.UtcNow,
};
}, cancellationToken).ConfigureAwait(false);
var folder = paths.Sequence(sequence.Folder);
var updated = SequenceMapping.ToSequence(manifest, archive.Id, folder, sequence);
@@ -160,6 +182,23 @@ public sealed class ArchiveService : IJobHandlerProvider
await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken)
.ConfigureAwait(false);
/// <summary>Dry run of moving sequences to their archive's trash; <paramref name="progress"/> counts the sequences checked.</summary>
public Task<DeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> sequenceIds, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
Trash.PlanAsync(sequenceIds, progress, cancellationToken);
/// <summary>Moves exactly the planned sequences to the trash; returns the trash entries made.</summary>
public Task<IReadOnlyList<TrashEntry>> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress<int>? progress = null,
CancellationToken cancellationToken = default) =>
Trash.DeleteAsync(plan, deletedBy, progress, cancellationToken);
/// <summary>The sequences in an archive's trash, newest first.</summary>
public async Task<IReadOnlyList<TrashEntry>> ListTrashAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
await Trash.ListAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
/// <summary>Moves a sequence back from the trash and indexes it again.</summary>
public async Task<Sequence> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default) =>
await Trash.RestoreAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), entryName, cancellationToken).ConfigureAwait(false);
/// <summary>Plans a card or folder import into an archive (nothing is copied).</summary>
public async Task<ImportPlan> PlanImportAsync(Guid archiveId, string sourceRoot, ImportOptions options, Guid? cardId = null, IProgress<int>? progress = null,
CancellationToken cancellationToken = default) =>
@@ -200,6 +239,9 @@ public sealed class ArchiveService : IJobHandlerProvider
}
}
/// <summary>The fields of a sequence the user describes it with (sidecar and index).</summary>
public sealed record SequenceInfo(string? Title, IReadOnlyList<string> Tags, int Rating, string? Notes);
/// <summary>Builds the archive jobs; enqueue with <see cref="EnqueueAsync"/>.</summary>
public static class ArchiveJobs
{
+554
View File
@@ -0,0 +1,554 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Archiving.Jobs;
namespace Titano.Data.Archiving;
/// <summary>Why a sequence cannot go to the trash; nothing of it is touched.</summary>
public enum DeleteBlock
{
/// <summary>The archive is offline or read-only.</summary>
Offline,
/// <summary>The photos lie in the archive root itself (a folder adopted in place): the root never moves.</summary>
ArchiveRoot,
/// <summary>Other sequences live in folders below this one; moving it would take them along.</summary>
ContainsSequences,
/// <summary>A running or paused job works on the sequence, or on its whole archive (a scan, a rebuild, an import, a verify, maintenance).</summary>
Busy,
/// <summary>The folder's sidecar names another sequence: the index is out of date (a scan fixes it).</summary>
ForeignSidecar,
/// <summary>The index names a folder that is not on disk: there is nothing to keep in the trash, so the Orphans check removes the row.</summary>
FolderMissing,
}
/// <summary>One sequence of a delete plan: its folder moves to <see cref="TrashFolder"/> and its index rows go.</summary>
/// <param name="TrashFolder">Archive-relative folder the sequence folder moves to; null for a sequence that has no folder yet (created on the server, no photo received), of which only the rows go.</param>
/// <param name="Files">Files under the folder (originals, proxies, exports, sidecars).</param>
/// <param name="Bytes">Their size on disk.</param>
public sealed record DeleteStep(Sequence Sequence, string? TrashFolder, int Files, long Bytes);
public sealed record BlockedDelete(Sequence Sequence, DeleteBlock Reason);
/// <summary>The dry run of moving sequences to their archive's trash (BRIEF §0.2 rule 8): what moves, and what cannot.</summary>
public sealed record DeletePlan(IReadOnlyList<DeleteStep> Steps, IReadOnlyList<BlockedDelete> Blocked)
{
public int Frames => Steps.Sum(s => s.Sequence.FrameCount);
public int Files => Steps.Sum(s => s.Files);
public long Bytes => Steps.Sum(s => s.Bytes);
public int Renders => Steps.Sum(s => s.Sequence.RenderedCount);
}
/// <summary>A deleted sequence kept in an archive's trash, as <see cref="SequenceTrash.ListAsync"/> lists it.</summary>
/// <param name="Name">Folder name inside the trash; pass it to <see cref="SequenceTrash.RestoreAsync"/>.</param>
/// <param name="Folder">Archive-relative folder the sequence came from (and returns to when it is free).</param>
public sealed record TrashEntry(Guid ArchiveId, string Name, Guid SequenceId, string Title, string Folder, int Frames, int Files, long Bytes,
DateTimeOffset DeletedAt, string? DeletedBy);
/// <summary>The plan no longer matches the index or the jobs (a sequence moved, vanished or got busy since it was made); nothing was deleted.</summary>
public sealed class StaleDeletePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
{
public Guid SequenceId { get; } = sequenceId;
}
/// <summary>A trash entry cannot come back: the index already holds its sequence (restored before, or scanned again); nothing moved.</summary>
public sealed class SequenceInLibraryException(Guid sequenceId, string title) : InvalidOperationException(Loc.L("Archive.Error.InLibrary", title))
{
public Guid SequenceId { get; } = sequenceId;
}
/// <summary>
/// Deleting sequences without erasing anything (BRIEF §0.2 rule 8, §12.2, §12.5): <see cref="PlanAsync"/> is the dry
/// run; <see cref="DeleteAsync"/> moves each sequence folder whole — originals, proxies, exports and its sidecars — into
/// <c>.titano/trash/&lt;id&gt;</c> of its archive under the sequence's leases, next to a record of its index row and
/// renders, then removes the index rows. <see cref="RestoreAsync"/> moves a folder back and indexes it again from its
/// sidecar with the same ids. The trash is a hidden folder of the archive, so scans never index it. Once a folder has
/// moved, its index step runs to the end whatever the caller cancels; when that step fails, the folder moves back, so
/// the trash and the index never disagree.
/// </summary>
public sealed class SequenceTrash
{
/// <summary>Folder of the trash inside the archive's <c>.titano</c>.</summary>
public const string FolderName = "trash";
private const string RecordExtension = ".json";
private const int JobPage = 200;
/// <summary>Bytes of a sidecar read to find its id (written second, after the schema version).</summary>
private const int SidecarHead = 4096;
private readonly TitanoDatabase _db;
private readonly SequenceWriter _writer;
private readonly ArchiveIndexer _indexer;
/// <summary>A trash of its own (hosts without an <see cref="ArchiveService"/>); lease files keep it in step with other writers.</summary>
public SequenceTrash(TitanoDatabase db, ArchiveServiceOptions? options = null)
: this(db, new SequenceWriter(options ?? new ArchiveServiceOptions()), null)
{
}
internal SequenceTrash(TitanoDatabase db, SequenceWriter writer, ArchiveIndexer? indexer)
{
_db = db;
_writer = writer;
_indexer = indexer ?? new ArchiveIndexer(db, writer);
}
/// <summary>The trash folder of an archive.</summary>
public static string TrashDirectory(ArchivePaths archive) => Path.Combine(archive.MetaDirectory, FolderName);
/// <summary>The dry run: for each sequence, where its folder goes and how many files and bytes it holds, or why it cannot go.</summary>
/// <param name="progress">Sequences checked so far.</param>
/// <exception cref="ArgumentException">A sequence is not in the index.</exception>
public async Task<DeletePlan> PlanAsync(IReadOnlyList<Guid> sequenceIds, IProgress<int>? progress = null, CancellationToken cancellationToken = default)
{
var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
var archives = new Dictionary<Guid, ArchiveContext?>();
var steps = new List<DeleteStep>();
var blocked = new List<BlockedDelete>();
var claimed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var checkedCount = 0;
foreach (var id in sequenceIds.Distinct())
{
cancellationToken.ThrowIfCancellationRequested();
var sequence = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown sequence {id}.", nameof(sequenceIds));
var context = await ContextAsync(archives, sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown archive {sequence.ArchiveId}.", nameof(sequenceIds));
if (Block(sequence, context, busy) is { } reason)
{
blocked.Add(new BlockedDelete(sequence, reason));
}
else if (sequence.Folder.Length == 0)
{
steps.Add(new DeleteStep(sequence, null, 0, 0));
}
else
{
var folder = context.Paths.Sequence(sequence.Folder).Folder;
var (files, bytes) = await Task.Run(() => Measure(folder, cancellationToken), cancellationToken).ConfigureAwait(false);
var name = EntryName(context.Paths, sequence.Id, claimed);
claimed.Add(name);
steps.Add(new DeleteStep(sequence, context.Paths.ToRelative(Path.Combine(TrashDirectory(context.Paths), name)), files, bytes));
}
progress?.Report(++checkedCount);
}
return new DeletePlan(steps, blocked);
}
/// <summary>
/// Moves the planned sequences to the trash, one at a time, each completely (folder, then index rows) before the
/// next; cancelling stops between two sequences. Returns the trash entries made.
/// </summary>
/// <param name="deletedBy">Who asked (user name or client), kept in the trash record.</param>
/// <param name="progress">Sequences moved so far.</param>
/// <exception cref="StaleDeletePlanException">A sequence moved, vanished or got busy since the plan; nothing was deleted.</exception>
/// <exception cref="ArchiveOfflineException">An archive is offline; sequences before it are in the trash.</exception>
public async Task<IReadOnlyList<TrashEntry>> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress<int>? progress = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
await RevalidateAsync(plan, cancellationToken).ConfigureAwait(false);
var entries = new List<TrashEntry>(plan.Steps.Count);
for (var i = 0; i < plan.Steps.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
if (await DeleteOneAsync(plan.Steps[i], deletedBy, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry);
progress?.Report(i + 1);
}
return entries;
}
/// <summary>The sequences in an archive's trash, newest first; records whose folder is gone are left out.</summary>
public async Task<IReadOnlyList<TrashEntry>> ListAsync(Archive archive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
var trash = TrashDirectory(new ArchivePaths(archive.RootPath));
return await Task.Run(() =>
{
if (!Directory.Exists(trash)) return (IReadOnlyList<TrashEntry>)[];
var entries = new List<TrashEntry>();
foreach (var path in Directory.EnumerateFiles(trash, "*" + RecordExtension))
{
cancellationToken.ThrowIfCancellationRequested();
var name = Path.GetFileNameWithoutExtension(path);
if (!Directory.Exists(Path.Combine(trash, name)) || ReadRecord(path) is not { } record) continue;
entries.Add(Entry(archive.Id, name, record));
}
return entries.OrderByDescending(e => e.DeletedAt).ToList();
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Moves a sequence back from the trash into its folder (or, when that is taken, a free one next to it) and indexes
/// it again from its sidecar with its ids, settings and renders. A folder without a sidecar is adopted under the
/// sequence's id, as a scan would adopt it, with the title, tags, rating and notes the record kept. Returns the
/// restored row. When it cannot be indexed, the folder goes back into the trash with its record.
/// </summary>
/// <exception cref="SequenceInLibraryException">The index already holds that sequence.</exception>
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
public async Task<Sequence> RestoreAsync(Archive archive, string name, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentException.ThrowIfNullOrWhiteSpace(name);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var trash = TrashDirectory(paths);
var source = Path.Combine(trash, Path.GetFileName(name));
var recordPath = source + RecordExtension;
if (!Directory.Exists(source) || ReadRecord(recordPath) is not { } record)
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
var id = record.Sequence.Id;
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not null)
throw new SequenceInLibraryException(id, record.Sequence.DisplayTitle);
var locations = (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Folder)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var folder = FreeFolder(paths, record.Sequence.Folder, locations);
var sequence = paths.Sequence(folder);
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
{
cancellationToken.ThrowIfCancellationRequested();
Directory.CreateDirectory(Path.GetDirectoryName(sequence.Folder)!);
Directory.Move(source, sequence.Folder);
try
{
var manifest = File.Exists(sequence.ManifestPath) ? SequenceWriter.ReadLocked(sequence, id) : Adopt(sequence, record.Sequence, cancellationToken);
// The index step runs to the end once it starts: a cancel cannot leave half the rows written.
await IndexAsync(archive, sequence, manifest, record, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Warning("archive", $"{record.Sequence.DisplayTitle} could not be restored; its folder goes back into the trash", ex);
MoveBack(sequence.Folder, source);
throw;
}
Log.Info("archive", $"{record.Sequence.DisplayTitle} restored from the trash to {folder}");
await RecordStampsAsync(archive, sequence, id).ConfigureAwait(false);
File.Delete(recordPath);
}
return await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false)
?? throw new InvalidOperationException($"{record.Sequence.DisplayTitle} was restored but is not in the index.");
}
/// <summary>
/// A sidecar for a restored folder that lost its own, built as a scan adopts a folder: its frames get new ids, the
/// sequence keeps its id, and the title, tags, rating and notes of the record go into it so sidecar and index agree.
/// </summary>
private SequenceManifest Adopt(SequencePaths sequence, Sequence kept, CancellationToken cancellationToken)
{
var built = SequenceAdopter.Build(kept.Id, sequence, _writer.Options.Owner, cancellationToken);
var manifest = built with
{
Title = kept.Title,
Tags = kept.Tags,
Rating = kept.Rating,
Notes = kept.Notes,
Versions = built.Versions with { Settings = System.Math.Max(built.Versions.Settings, kept.SettingsVersion) },
};
Directory.CreateDirectory(sequence.MetaDirectory);
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
return manifest;
}
/// <summary>The restored sequence's rows: the sidecar's frames, the record's row and renders; a hero frame the sidecar no longer has is dropped.</summary>
private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, TrashRecord record, CancellationToken cancellationToken)
{
var deleted = record.Sequence;
var hero = deleted.HeroFrameId is { } frame && manifest.Frames.Any(f => f.Id == frame) ? frame : (Guid?)null;
var kept = deleted with { ArchiveId = archive.Id, Folder = sequence.RelativeFolder, RenderedCount = 0, HeroFrameId = hero };
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, kept), cancellationToken).ConfigureAwait(false);
await tx.Frames.SyncSequenceAsync(deleted.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
foreach (var key in manifest.SessionKeys) await tx.Sequences.MapSessionKeyAsync(archive.Id, key, deleted.Id, cancellationToken).ConfigureAwait(false);
foreach (var render in record.Renders)
{
var moved = render with { OutputPath = Rebase(render.OutputPath, deleted.Folder, sequence.RelativeFolder) };
await tx.Renders.InsertAsync(moved, cancellationToken).ConfigureAwait(false);
}
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The next incremental scan skips the restored folder; when the stamps cannot be written it only reads the folder again.</summary>
private async Task RecordStampsAsync(Archive archive, SequencePaths sequence, Guid id)
{
try
{
await _indexer.RecordStampsAsync(archive, sequence, id, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("archive", $"Scan stamps of {sequence.RelativeFolder} not recorded; the next scan reads it again", ex);
}
}
/// <summary>Checks the plan again just before anything moves, without measuring the folders again; any change refuses it whole.</summary>
private async Task RevalidateAsync(DeletePlan plan, CancellationToken cancellationToken)
{
var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
var archives = new Dictionary<Guid, ArchiveContext?>();
foreach (var step in plan.Steps)
{
cancellationToken.ThrowIfCancellationRequested();
var row = await _db.Sequences.GetAsync(step.Sequence.Id, cancellationToken).ConfigureAwait(false);
if (row is null || row.ArchiveId != step.Sequence.ArchiveId || row.Folder != step.Sequence.Folder) throw new StaleDeletePlanException(step.Sequence.Id);
if (await ContextAsync(archives, row.ArchiveId, cancellationToken).ConfigureAwait(false) is not { } context) throw new StaleDeletePlanException(row.Id);
switch (Block(row, context, busy))
{
case DeleteBlock.Offline:
throw new ArchiveOfflineException(context.Paths.Root, context.Availability);
case not null:
throw new StaleDeletePlanException(row.Id);
}
}
}
private async Task<TrashEntry?> DeleteOneAsync(DeleteStep step, string? deletedBy, CancellationToken cancellationToken)
{
var sequence = step.Sequence;
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new StaleDeletePlanException(sequence.Id);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
{
var row = await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
if (row is null || row.Folder != sequence.Folder) throw new StaleDeletePlanException(sequence.Id);
if (step.TrashFolder is null)
{
await RemoveRowsAsync(archive.Id, row, cancellationToken).ConfigureAwait(false);
Log.Info("archive", $"{row.DisplayTitle} removed from the index (no folder yet)");
return null;
}
var folder = paths.Sequence(sequence.Folder);
if (!Directory.Exists(folder.Folder) || (File.Exists(folder.ManifestPath) && SidecarId(folder.ManifestPath) != sequence.Id))
throw new StaleDeletePlanException(sequence.Id);
var trash = TrashDirectory(paths);
Directory.CreateDirectory(trash);
var name = EntryName(paths, sequence.Id, new HashSet<string>());
var target = Path.Combine(trash, name);
var record = new TrashRecord(row, await _db.Renders.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false), step.Files,
step.Bytes, DateTimeOffset.UtcNow, deletedBy);
cancellationToken.ThrowIfCancellationRequested();
// The record first: a crash before the move leaves a record without a folder, which the listing ignores.
var recordPath = target + RecordExtension;
AtomicFile.WriteAllText(recordPath, JsonSerializer.Serialize(record, TrashJson.Default.TrashRecord));
try
{
Directory.Move(folder.Folder, target);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A file of the folder is open elsewhere: nothing moved, so the record goes and the rows stay.
File.Delete(recordPath);
throw;
}
try
{
// The folder has moved: its rows go too, to the end, whatever the caller cancels meanwhile.
await RemoveRowsAsync(archive.Id, row, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Warning("archive", $"{row.DisplayTitle} could not leave the index; its folder goes back", ex);
if (MoveBack(target, folder.Folder)) File.Delete(recordPath);
throw;
}
Log.Info("archive", $"{row.DisplayTitle} moved to the trash: {row.Folder} → {name} ({step.Files} files, {step.Bytes} bytes)");
return Entry(archive.Id, name, record);
}
}
private async Task RemoveRowsAsync(Guid archiveId, Sequence sequence, CancellationToken cancellationToken)
{
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
await tx.Sequences.DeleteAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
// A sequence without a folder has no scan state; the root's belongs to a folder adopted in place.
if (sequence.Folder.Length > 0) await tx.Archives.DeleteFolderStateAsync(archiveId, sequence.Folder, cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Undoes a folder move after a failed index step; false (logged) when the folder cannot move back either.</summary>
private static bool MoveBack(string from, string to)
{
try
{
Directory.Move(from, to);
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Error("archive", $"{from} could not move back to {to}; it stays where it is", ex);
return false;
}
}
private async Task<ArchiveContext?> ContextAsync(Dictionary<Guid, ArchiveContext?> known, Guid archiveId, CancellationToken cancellationToken)
{
if (known.TryGetValue(archiveId, out var context)) return context;
if (await _db.Archives.GetAsync(archiveId, cancellationToken).ConfigureAwait(false) is { } archive)
{
var paths = new ArchivePaths(archive.RootPath);
context = new ArchiveContext(paths, ArchiveVolume.Probe(paths),
await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false));
}
known[archiveId] = context;
return context;
}
private static DeleteBlock? Block(Sequence sequence, ArchiveContext context, IReadOnlySet<Guid> busy)
{
if (context.Availability != ArchiveAvailability.Online) return DeleteBlock.Offline;
if (busy.Contains(sequence.Id) || busy.Contains(sequence.ArchiveId)) return DeleteBlock.Busy;
// An empty folder is the archive root of a folder adopted in place, or a server sequence still waiting for its first frame.
if (sequence.Folder.Length == 0) return sequence.FrameCount > 0 ? DeleteBlock.ArchiveRoot : null;
var folder = context.Paths.Sequence(sequence.Folder);
if (!Directory.Exists(folder.Folder)) return DeleteBlock.FolderMissing;
var prefix = sequence.Folder + "/";
if (context.Locations.Any(l => l.Id != sequence.Id && l.Folder.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) return DeleteBlock.ContainsSequences;
return File.Exists(folder.ManifestPath) && SidecarId(folder.ManifestPath) != sequence.Id ? DeleteBlock.ForeignSidecar : null;
}
/// <summary>
/// What running and paused jobs hold: the sequences they target (renders, analyses, proxies, transfers) and the
/// archives of archive-wide ones (scan, rebuild, import, maintenance, a verify of everything). An import's folders
/// are known only to its plan, so it holds its whole archive; a verify of named sequences holds only those.
/// </summary>
private async Task<IReadOnlySet<Guid>> BusyAsync(CancellationToken cancellationToken)
{
var busy = new HashSet<Guid>();
foreach (var state in new[] { JobState.Running, JobState.Paused })
{
string? cursor = null;
do
{
var page = await _db.Jobs.ListAsync(state, JobPage, cursor, cancellationToken).ConfigureAwait(false);
foreach (var job in page.Items) busy.UnionWith(Holds(job));
cursor = page.NextCursor;
}
while (cursor is not null);
}
return busy;
}
private static IReadOnlyList<Guid> Holds(Job job)
{
if (job.Kind != JobKind.Verify) return job.TargetIds;
try
{
return ArchiveJobJson.Read(job, ArchiveJobJson.Default.VerifyParameters, new VerifyParameters(null)).SequenceIds ?? job.TargetIds;
}
catch (JsonException)
{
return job.TargetIds;
}
}
/// <summary>
/// The id a sidecar names, from its head (the id is written second), so checking a 35 MB sidecar does not parse it;
/// the whole file is read only when the head does not hold the id. Null when the file is unreadable.
/// </summary>
private static Guid? SidecarId(string path)
{
try
{
var head = new byte[SidecarHead];
int length;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
length = stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false);
var reader = new Utf8JsonReader(head.AsSpan(0, length), isFinalBlock: length < head.Length, state: default);
while (reader.Read())
{
if (reader.TokenType != JsonTokenType.PropertyName || reader.CurrentDepth != 1) continue;
if (reader.ValueTextEquals("id"u8))
{
if (!reader.Read()) break;
return reader.TokenType == JsonTokenType.String && reader.TryGetGuid(out var id) ? id : null;
}
if (!reader.TrySkip()) break;
}
return ManifestStore.ReadSequence(path).Id;
}
catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException or UnauthorizedAccessException)
{
return null;
}
}
private static (int Files, long Bytes) Measure(string folder, CancellationToken cancellationToken)
{
int files = 0;
long bytes = 0;
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0 }))
{
cancellationToken.ThrowIfCancellationRequested();
files++;
bytes += file.Length;
}
return (files, bytes);
}
/// <summary>The sequence id, or the id with a time stamp when an earlier deletion of the same sequence is still in the trash.</summary>
private static string EntryName(ArchivePaths paths, Guid sequenceId, IReadOnlySet<string> claimed)
{
var trash = TrashDirectory(paths);
var name = sequenceId.ToString("N");
var stamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
for (var n = 1; claimed.Contains(name) || Directory.Exists(Path.Combine(trash, name)); n++)
name = $"{sequenceId:N}-{stamp}" + (n > 1 ? "-" + n.ToString(System.Globalization.CultureInfo.InvariantCulture) : string.Empty);
return name;
}
/// <summary>The original folder when it is free on disk and in the index, else "folder (2)", "folder (3)", …</summary>
private static string FreeFolder(ArchivePaths paths, string folder, IReadOnlySet<string> indexed)
{
var candidate = folder;
for (var n = 2; indexed.Contains(candidate) || Directory.Exists(paths.Sequence(candidate).Folder); n++)
candidate = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{folder} ({n})");
return candidate;
}
/// <summary>A render stored inside the old folder points into the folder it was restored to.</summary>
private static string Rebase(string outputPath, string from, string to) =>
from != to && outputPath.StartsWith(from + "/", StringComparison.Ordinal) ? to + outputPath[from.Length..] : outputPath;
private static TrashEntry Entry(Guid archiveId, string name, TrashRecord record) =>
new(archiveId, name, record.Sequence.Id, record.Sequence.DisplayTitle, record.Sequence.Folder, record.Sequence.FrameCount, record.Files,
record.Bytes, record.DeletedAt, record.DeletedBy);
private static TrashRecord? ReadRecord(string path)
{
try
{
return JsonSerializer.Deserialize(File.ReadAllText(path), TrashJson.Default.TrashRecord);
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Trash record {path} is unreadable", ex);
return null;
}
}
/// <summary>An archive as the plan sees it: where it is, whether it can be written, and where its sequences are.</summary>
private sealed record ArchiveContext(ArchivePaths Paths, ArchiveAvailability Availability, IReadOnlyList<Repositories.SequenceLocation> Locations);
}
/// <summary>What the trash keeps next to a deleted folder: the index row and renders the sidecar does not carry.</summary>
internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList<Render> Renders, int Files, long Bytes, DateTimeOffset DeletedAt, string? DeletedBy);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true, IgnoreReadOnlyProperties = true)]
[JsonSerializable(typeof(TrashRecord))]
internal sealed partial class TrashJson : JsonSerializerContext;
@@ -35,6 +35,12 @@ public sealed record SequenceQuery
public string? Tag { get; init; }
/// <summary>True: with at least one render; false: without any; null: either.</summary>
public bool? Rendered { get; init; }
/// <summary>Sync states of which the sequence must be in one; null or empty: any.</summary>
public IReadOnlyCollection<SyncState>? SyncStates { get; init; }
/// <summary>Case-insensitive substring of the title, camera make/model or a tag.</summary>
public string? Text { get; init; }
@@ -396,6 +402,8 @@ public sealed class SequenceRepository
where.Add($"(s.status & {mask}) = {mask}");
}
if (query.WithoutStatus != SequenceStatus.None) where.Add($"(s.status & {p.Add((int)query.WithoutStatus)}) = 0");
if (query.Rendered is { } rendered) where.Add(rendered ? "s.rendered_count > 0" : "s.rendered_count = 0");
if (query.SyncStates is { Count: > 0 } states) where.Add($"s.sync_state IN ({string.Join(", ", states.Select(state => p.Add((int)state)))})");
if (query.Tag is { } tag)
where.Add("EXISTS (SELECT 1 FROM sequence_tags st JOIN tags t ON t.id = st.tag_id " +
$"WHERE st.sequence_id = s.id AND t.name_key = {p.Add(TagRepository.Key(tag))})");
+8
View File
@@ -23,6 +23,10 @@ public interface ISyncRemote : IDisposable
/// <summary>Every frame row of a sequence, in index order.</summary>
Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken);
/// <summary>The first frame row of a sequence (its thumbnail stands for a sequence without a hero frame); null when it has none yet.</summary>
async Task<FrameDto?> FirstFrameAsync(Guid sequenceId, CancellationToken cancellationToken) =>
(await ListFramesAsync(sequenceId, cancellationToken).ConfigureAwait(false)).FirstOrDefault();
/// <summary>A 409 <see cref="TitanoApiException"/> means the settings version moved on the server.</summary>
Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken);
@@ -98,6 +102,10 @@ public sealed class TitanoSyncRemote(TitanoClient client, bool ownsClient) : ISy
return all;
}
/// <summary>One row of the first frames page instead of the whole list.</summary>
public async Task<FrameDto?> FirstFrameAsync(Guid sequenceId, CancellationToken cancellationToken) =>
(await client.ListFramesAsync(sequenceId, null, 1, cancellationToken).ConfigureAwait(false)).Items.FirstOrDefault();
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) =>
client.UpdateSequenceAsync(id, request, cancellationToken);
+50 -17
View File
@@ -2,9 +2,11 @@ using System.Buffers.Text;
using System.Globalization;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Processing;
using Titano.Data.Repositories;
using Titano.Protocol;
@@ -154,32 +156,63 @@ public static class SequenceEndpoints
}
/// <summary>
/// Removes a sequence from the index and moves its folder into the archive's trash (BRIEF §0.2 rule 8: nothing is
/// erased). <c>?dryRun=true</c> only reports what would happen. Owners and admins only.
/// Moves a sequence's folder into the archive's trash and removes it from the index through the archive engine's
/// <see cref="SequenceTrash"/> (BRIEF §0.2 rule 8: nothing is erased, the trash keeps it restorable).
/// <c>?dryRun=true</c> only reports what would happen. Owners and admins only. A sequence that cannot move is refused
/// with the reason as its code: 409 <c>sequence_busy</c> (a job works on it or its archive), <c>archive_root</c>,
/// <c>contains_sequences</c>, <c>sidecar_mismatch</c>, <c>folder_missing</c>; 503 <c>archive_offline</c>.
/// </summary>
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db, ServerArchive archive,
ServerOptions options, AuditLog audit, EventHub events)
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db,
[FromServices] ArchiveService? archives, AuditLog audit, EventHub events)
{
if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
var ct = context.RequestAborted;
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context);
var folder = string.IsNullOrEmpty(sequence.Folder) ? null : ArchivePathGuard.Resolve(archive.Root, sequence.Folder);
var trash = Path.Combine(options.TrashPath, id.ToString("N"));
var hasFolder = folder is not null && Directory.Exists(folder);
var plan = new SequenceDeletePlan(id, sequence.Folder, hasFolder ? Path.GetRelativePath(archive.Root, trash).Replace('\\', '/') : null,
sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true);
if (dryRun == true) return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan);
if (hasFolder)
var trash = archives?.Trash ?? new SequenceTrash(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
DeletePlan plan;
try
{
Directory.CreateDirectory(options.TrashPath);
Directory.Move(folder!, trash);
plan = await trash.PlanAsync([id], null, ct);
if (plan.Blocked is [{ } blocked]) return Refused(context, blocked.Reason);
if (dryRun != true) await trash.DeleteAsync(plan, caller.User.Username, null, ct);
}
await db.Sequences.DeleteAsync(id, context.RequestAborted);
catch (ArgumentException)
{
// Deleted by someone else between the lookup and the plan.
return ApiErrors.NotFound(context, "sequence");
}
catch (Titano.Core.Archiving.ArchiveOfflineException)
{
return Refused(context, DeleteBlock.Offline);
}
catch (Exception ex) when (ex is StaleDeletePlanException or Titano.Core.Archiving.LeaseUnavailableException)
{
return Refused(context, DeleteBlock.Busy);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A file of the folder is open elsewhere: nothing moved.
return ApiErrors.Conflict(context, "folder_in_use");
}
var step = plan.Steps[0];
var result = new SequenceDeletePlan(id, sequence.Folder, step.TrashFolder, sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true);
if (dryRun == true) return Results.Json(result, ProtocolJson.Default.SequenceDeletePlan);
await audit.WriteAsync(caller, context, "sequence_deleted", "sequence", id.ToString(), sequence.DisplayTitle);
events.Publish(new SequenceChangedEvent(id, "deleted", sequence.FramesVersion, sequence.SettingsVersion));
return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan);
return Results.Json(result, ProtocolJson.Default.SequenceDeletePlan);
}
private static IResult Refused(HttpContext context, DeleteBlock reason) => reason switch
{
DeleteBlock.Offline => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline"),
DeleteBlock.Busy => ApiErrors.Conflict(context, "sequence_busy"),
DeleteBlock.ArchiveRoot => ApiErrors.Conflict(context, "archive_root"),
DeleteBlock.ContainsSequences => ApiErrors.Conflict(context, "contains_sequences"),
DeleteBlock.ForeignSidecar => ApiErrors.Conflict(context, "sidecar_mismatch"),
_ => ApiErrors.Conflict(context, "folder_missing"),
};
/// <summary>Everything a client needs to mirror a sequence and detect changes (BRIEF §14.5); ETag over the version counters.</summary>
private static async Task<IResult> ManifestAsync(HttpContext context, Guid id, TitanoDatabase db)
{
+5
View File
@@ -126,11 +126,16 @@
<Trigger Property="IsScrubbing" Value="True">
<Setter TargetName="ScrubTrack" Property="Visibility" Value="Visible" />
</Trigger>
<!-- A selected card keeps its actions in sight, so the keyboard reaches them (Tab from the card). -->
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="Select" Property="Visibility" Value="Visible" />
<Setter TargetName="Actions" Property="Visibility" Value="Visible" />
<Setter TargetName="Frame" Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
<Setter TargetName="Glow" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter TargetName="Actions" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.4" />
</Trigger>
+1 -1
View File
@@ -82,7 +82,7 @@ public class SequenceCard : Control
/// <summary>Tooltip of the selection check box.</summary>
public object? SelectToolTip { get => GetValue(SelectToolTipProperty); set => SetValue(SelectToolTipProperty, value); }
/// <summary>Quick actions shown bottom-right of the thumbnail on hover (Open, Analyse, Render, Sync).</summary>
/// <summary>Quick actions shown bottom-right of the thumbnail on hover, while selected and while the keyboard is in them (Open, Analyse, Render, Sync).</summary>
public object? ActionsContent { get => GetValue(ActionsContentProperty); set => SetValue(ActionsContentProperty, value); }
/// <summary>Selection state; bind two-way to the container's IsSelected so the check box toggles it.</summary>
+83 -3
View File
@@ -9,8 +9,10 @@ namespace Titano.Ui.Visuals;
/// Library timeline mode (BRIEF §12.2): one band per year with its label on the left and a density bar per slot
/// (month) on a scale shared by all bands, slot labels underneath and a divider between bands. The current slot
/// (<see cref="CurrentBand"/>, <see cref="CurrentSlot"/>) is outlined in Accent; clicking a slot makes it current
/// and raises <see cref="SlotActivatedEvent"/>. Desired height = bands × <see cref="BandHeight"/>, so the control
/// scrolls inside a ScrollViewer.
/// and raises <see cref="SlotActivatedEvent"/>. From the keyboard, the arrow keys move a dashed focus ring from month to
/// month (Left and Right run across years, Up and Down change year, Home and End go to the year's ends) with its
/// readout, and Enter or Space activates the slot under it. Desired height = bands × <see cref="BandHeight"/>, so the
/// control scrolls inside a ScrollViewer and brings the focused band into sight.
/// </summary>
public sealed class TimelineBands : DrawingElement
{
@@ -46,6 +48,16 @@ public sealed class TimelineBands : DrawingElement
private (int Band, int Slot) _hover = (-1, -1);
/// <summary>The slot the keyboard is on; (−1, −1) until the control first takes keyboard focus.</summary>
private (int Band, int Slot) _keyboard = (-1, -1);
static TimelineBands()
{
FocusableProperty.OverrideMetadata(typeof(TimelineBands), new FrameworkPropertyMetadata(true));
// The focused slot is outlined on the drawing itself.
FocusVisualStyleProperty.OverrideMetadata(typeof(TimelineBands), new FrameworkPropertyMetadata(null));
}
/// <summary>One band per year: label + one value per slot.</summary>
public IReadOnlyList<ChartRow>? Bands { get => (IReadOnlyList<ChartRow>?)GetValue(BandsProperty); set => SetValue(BandsProperty, value); }
@@ -90,6 +102,7 @@ public sealed class TimelineBands : DrawingElement
protected override void OnDataChanged()
{
_hover = (-1, -1);
if (_keyboard.Band >= (Bands?.Count ?? 0) || _keyboard.Slot >= SlotCount) _keyboard = (-1, -1);
base.OnDataChanged();
}
@@ -137,6 +150,8 @@ public sealed class TimelineBands : DrawingElement
}
if (b == CurrentBand && s == CurrentSlot)
dc.DrawRoundedRectangle(null, GetPen("Brush.Accent", 1.5), new Rect(cx - pitch / 2 + 2, top + 4, pitch - 4, BandHeight - 8), 4, 4);
if (IsKeyboardFocused && b == _keyboard.Band && s == _keyboard.Slot)
dc.DrawRoundedRectangle(null, GetPen("Brush.Accent", 2, LineDash.Dashed), new Rect(cx - pitch / 2 + 0.5, top + 1, pitch - 1, BandHeight - 2), 5, 5);
}
if (b < bands.Count - 1)
{
@@ -174,10 +189,75 @@ public sealed class TimelineBands : DrawingElement
base.OnMouseLeftButtonUp(e);
var (band, slot) = HitTest(e.GetPosition(this));
if (band < 0) return;
_keyboard = (band, slot);
Activate(band, slot);
e.Handled = true;
}
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
base.OnGotKeyboardFocus(e);
if (_keyboard.Band < 0 && Bands is { Count: > 0 } && SlotCount > 0)
_keyboard = CurrentBand >= 0 && CurrentSlot >= 0 ? (CurrentBand, CurrentSlot) : (0, 0);
InvalidateVisual();
}
protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
base.OnLostKeyboardFocus(e);
Readout.Hide();
InvalidateVisual();
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
var bands = Bands?.Count ?? 0;
var slots = SlotCount;
if (e.Handled || bands == 0 || slots == 0) return;
var (band, slot) = _keyboard.Band >= 0 ? _keyboard : (0, 0);
switch (e.Key)
{
case Key.Enter or Key.Space:
Activate(band, slot);
e.Handled = true;
return;
// Bands run newest first: Left goes back in time, into the year below after January.
case Key.Left:
(band, slot) = slot > 0 ? (band, slot - 1) : band < bands - 1 ? (band + 1, slots - 1) : (band, slot);
break;
case Key.Right:
(band, slot) = slot < slots - 1 ? (band, slot + 1) : band > 0 ? (band - 1, 0) : (band, slot);
break;
case Key.Up:
band = Math.Max(0, band - 1);
break;
case Key.Down:
band = Math.Min(bands - 1, band + 1);
break;
case Key.Home:
slot = 0;
break;
case Key.End:
slot = slots - 1;
break;
default:
return;
}
_keyboard = (band, slot);
var pitch = SlotPitch;
var top = band * BandHeight;
BringIntoView(new Rect(0, top, ActualWidth, BandHeight));
Readout.Show(ReadoutText(band, slot), new Point(LabelColumn + pitch * (slot + 0.5), top + BandHeight / 2));
InvalidateVisual();
e.Handled = true;
}
private void Activate(int band, int slot)
{
SetCurrentValue(CurrentBandProperty, band);
SetCurrentValue(CurrentSlotProperty, slot);
RaiseEvent(new ChartItemEventArgs(SlotActivatedEvent, band, slot));
e.Handled = true;
}
private (int Band, int Slot) HitTest(Point p)