fix(app): import gates, partial results and plan editing after review

- a card that leaves needs a new check; formatting re-lists the card and refuses
  one that changed since its check; files that are not photos are named in the
  format confirmation
- an import never stays stuck in Running; Retry never resumes an older job
- server imports list refused files and keep what was uploaded when stopped
- the archive result matches each copy to its job's record and shows the job's
  own error per file
- refreshing devices keeps typed titles and choices; titles lock while copying
- three destination names, merge and split of sessions, camera profiles shared
  by the cards of a camera, photo counts and a new-card toast
- disabled controls say why; keyboard focus follows the nickname field and
  Show plan (Esc closes it); label column fits longer languages
- capture states for insertion, running, failed and a new card

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 10:44:22 +00:00
1 parent 5aa5edab57
commit 29c82eba5c
27 files changed
+1286 -285

No files matched your search

+81 -22
View File
@@ -16,6 +16,7 @@
<Setter Property="Padding" Value="12,0" />
<Setter Property="Background" Value="{DynamicResource Brush.Surface}" />
<Setter Property="ToolTip" Value="{Binding StateText}" />
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
@@ -37,7 +38,7 @@
</Setter>
</Style>
<!-- One form line: 116 px label column, then the controls (Import.html grid). -->
<!-- One form line: a label column at least 116 px wide, as wide as the longest label of the form, then the controls (Import.html grid). -->
<Style x:Key="Import.Row" TargetType="HeaderedContentControl">
<Setter Property="Focusable" Value="False" />
<Setter Property="Margin" Value="0,0,0,10" />
@@ -46,10 +47,10 @@
<ControlTemplate TargetType="HeaderedContentControl">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{StaticResource Grid.LabelColumn}" />
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="ImportLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{TemplateBinding Header}" Style="{StaticResource Text.Label}" VerticalAlignment="Top" Margin="0,6,12,0" />
<TextBlock Text="{TemplateBinding Header}" Style="{StaticResource Text.Label}" TextTrimming="None" VerticalAlignment="Top" Margin="0,6,12,0" />
<ContentPresenter Grid.Column="1" VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
@@ -77,6 +78,43 @@
<Style x:Key="Session.Grid" TargetType="Grid">
<Setter Property="Height" Value="34" />
</Style>
<Style x:Key="ListBoxItem.Session" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
<Setter Property="AutomationProperties.Name" Value="{Binding Row.TimeText}" />
</Style>
<!-- Show plan and failure rows: focusable, so the arrow keys move through a long list. -->
<Style x:Key="ListBoxItem.PlanRow" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="AutomationProperties.Name" Value="{Binding Source}" />
</Style>
<Style x:Key="ListBoxItem.Failure" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="AutomationProperties.Name" Value="{Binding}" />
</Style>
<!-- "Folder…" (Import.html): transparent, 1 px dashed Stroke border. -->
<Style x:Key="Button.Dashed" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle x:Name="Edge" Fill="Transparent" Stroke="{DynamicResource Brush.Stroke}" StrokeThickness="1" StrokeDashArray="4 3" RadiusX="6" RadiusY="6" />
<ContentPresenter Margin="{TemplateBinding Padding}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="Center" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Edge" Property="Fill" Value="{DynamicResource Brush.Card}" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter TargetName="Edge" Property="Stroke" Value="{DynamicResource Brush.Accent}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid Margin="20,16">
@@ -97,7 +135,7 @@
VerticalContentAlignment="Top">
<TextBlock Text="{l:Loc Import.Devices.Auto}" TextWrapping="Wrap" Foreground="{DynamicResource Brush.TextMuted}" />
</CheckBox>
<ScrollViewer VerticalScrollBarVisibility="Auto" Focusable="False" IsEnabled="{Binding IsFormEnabled}">
<ScrollViewer VerticalScrollBarVisibility="Auto" Focusable="False" IsEnabled="{Binding CanChangeSource}">
<StackPanel>
<ListBox ItemsSource="{Binding Sources}" SelectedItem="{Binding SelectedSource}" ItemContainerStyle="{StaticResource ListBoxItem.Device}"
AutomationProperties.Name="{l:Loc Import.Devices.Title}">
@@ -126,6 +164,7 @@
<DataTrigger Binding="{Binding Kind}" Value="Drive">
<Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.Drive}" />
<Setter TargetName="State" Property="Kind" Value="Offline" />
<Setter TargetName="Root" Property="TextElement.Foreground" Value="{DynamicResource Brush.TextMuted}" />
</DataTrigger>
<DataTrigger Binding="{Binding Kind}" Value="Folder">
<Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.Folder}" />
@@ -142,7 +181,7 @@
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Height="44" HorizontalContentAlignment="Left" Background="Transparent" Command="{Binding PickFolderCommand}" ToolTip="{l:Loc Tooltips.Import.Folder}">
<Button Style="{StaticResource Button.Dashed}" Height="44" HorizontalContentAlignment="Left" Command="{Binding PickFolderCommand}" ToolTip="{l:Loc Tooltips.Import.Folder}">
<StackPanel Orientation="Horizontal">
<ui:Icon Glyph="{StaticResource Icon.Folder}" Margin="0,0,10,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Text="{l:Loc Import.Devices.Folder}" Foreground="{DynamicResource Brush.TextMuted}" />
@@ -163,7 +202,7 @@
<!-- Profile header: nickname (or its field for a new card), identity, Edit ▾. -->
<DockPanel Margin="0,0,0,14" MinHeight="32">
<Button x:Name="EditButton" DockPanel.Dock="Right" Click="OnOpenMenu" IsEnabled="{Binding CanEditProfile}" ToolTip="{l:Loc Tooltips.Import.Edit}">
<Button x:Name="EditButton" DockPanel.Dock="Right" Click="OnOpenMenu" IsEnabled="{Binding CanEditProfile}" ToolTip="{Binding EditToolTip}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{l:Loc Import.Profile.Edit}" VerticalAlignment="Center" />
<ui:Icon Glyph="{StaticResource Icon.ChevronDown}" Margin="6,0,0,0" />
@@ -171,6 +210,8 @@
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="{l:Loc Import.Profile.Rename}" Command="{Binding RenameCommand}" ToolTip="{l:Loc Tooltips.Import.Rename}" />
<MenuItem Header="{l:Loc Import.Profile.Camera}" Command="{Binding FollowCameraCommand}" IsCheckable="False" IsChecked="{Binding FollowsCamera, Mode=OneWay}"
ToolTip="{Binding FollowCameraToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Import.Profile.CopyFrom}" ItemsSource="{Binding OtherCards}" ToolTip="{l:Loc Tooltips.Import.CopyFrom}">
<MenuItem.ItemContainerStyle>
<Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
@@ -188,7 +229,7 @@
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="{Binding SourceTitle}" Style="{StaticResource Text.Title}" VerticalAlignment="Center" MaxWidth="320" TextTrimming="CharacterEllipsis"
Visibility="{Binding IsNicknameOpen, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<TextBox Width="240" Text="{Binding Nickname.Text, UpdateSourceTrigger=PropertyChanged}" shell:EditBehavior.Field="{Binding Nickname}"
<TextBox x:Name="NicknameBox" Width="240" Text="{Binding Nickname.Text, UpdateSourceTrigger=PropertyChanged}" shell:EditBehavior.Field="{Binding Nickname}"
ui:Field.Placeholder="{l:Loc Import.Profile.Nickname}" ToolTip="{Binding Nickname.ToolTip}" AutomationProperties.Name="{l:Loc Import.Profile.Nickname}"
Visibility="{Binding IsNicknameOpen, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
@@ -197,7 +238,7 @@
</DockPanel>
<!-- The form (Import.html grid). -->
<StackPanel Grid.Row="1" IsEnabled="{Binding IsFormEnabled}">
<StackPanel Grid.Row="1" IsEnabled="{Binding IsFormEnabled}" Grid.IsSharedSizeScope="True">
<HeaderedContentControl Style="{StaticResource Import.Row}" Header="{l:Loc Import.Label.Destination}">
<WrapPanel>
<RadioButton GroupName="Destination" Content="{l:Loc Import.Destination.Archive}" IsChecked="{Binding IsArchiveDestination}"
@@ -262,7 +303,6 @@
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Text}" />
<Setter Property="InputGestureText" Value="{Binding ToolTip}" />
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
<Setter Property="Command" Value="{Binding DataContext.InsertTokenCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<Setter Property="CommandParameter" Value="{Binding}" />
@@ -288,18 +328,18 @@
<WrapPanel>
<RadioButton GroupName="After" Content="{l:Loc Import.After.Keep}" IsChecked="{Binding KeepCard}" ToolTip="{l:Loc Tooltips.Import.Keep}" />
<RadioButton GroupName="After" Content="{l:Loc Import.After.Delete}" IsChecked="{Binding DeleteImported}" IsEnabled="{Binding CardActionsApply}"
ToolTip="{l:Loc Tooltips.Import.DeleteChoice}" />
ToolTip="{Binding DeleteChoiceToolTip}" />
<RadioButton GroupName="After" Content="{l:Loc Import.After.Format}" IsChecked="{Binding FormatCard}" IsEnabled="{Binding CardActionsApply}"
ToolTip="{l:Loc Tooltips.Import.FormatChoice}" />
ToolTip="{Binding FormatChoiceToolTip}" />
<Border Width="1" Height="20" Background="{DynamicResource Brush.Stroke}" Margin="0,0,18,0" VerticalAlignment="Center" />
<CheckBox Content="{l:Loc Import.After.Eject}" IsChecked="{Binding Eject}" ToolTip="{l:Loc Tooltips.Import.EjectChoice}" />
<CheckBox Content="{l:Loc Import.After.Deep}" IsChecked="{Binding DeepAnalysis}" IsEnabled="{Binding IsArchiveDestination}" ToolTip="{l:Loc Tooltips.Import.Deep}" />
<CheckBox Content="{l:Loc Import.After.Deep}" IsChecked="{Binding DeepAnalysis}" IsEnabled="{Binding IsArchiveDestination}" ToolTip="{Binding DeepToolTip}" />
</WrapPanel>
</HeaderedContentControl>
</StackPanel>
<!-- ===================== Plan panel ===================== -->
<Border Grid.Row="2" Style="{StaticResource Border.Card}" Padding="16,14" Margin="0,14,0,0">
<Border Grid.Row="2" Style="{StaticResource Border.Card}" Padding="16,14" Margin="0,14,0,0" IsEnabled="{Binding IsPlanPanelEnabled}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -329,7 +369,7 @@
</StackPanel>
<!-- Sessions of the plan with editable titles. -->
<Grid Grid.Row="1" Visibility="{Binding HasPlan, Converter={StaticResource BoolToVisibility}}">
<Grid Grid.Row="1" Visibility="{Binding HasPlan, Converter={StaticResource BoolToVisibility}}" Grid.IsSharedSizeScope="True">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
@@ -341,6 +381,7 @@
<ColumnDefinition Width="0.6*" MinWidth="56" />
<ColumnDefinition Width="0.8*" MinWidth="64" />
<ColumnDefinition Width="1.9*" MinWidth="150" />
<ColumnDefinition Width="Auto" SharedSizeGroup="SessionAction" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Session}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Frames}" Margin="10,0,0,0" />
@@ -348,7 +389,8 @@
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Camera}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Sequence}" Margin="10,0,0,0" />
</Grid>
<ListBox Grid.Row="1" ItemsSource="{Binding Sessions}" ItemContainerStyle="{StaticResource ListBoxItem.PlainRow}" AutomationProperties.Name="{l:Loc Import.Plan.Title}">
<ListBox Grid.Row="1" ItemsSource="{Binding Sessions}" ItemContainerStyle="{StaticResource ListBoxItem.Session}" AutomationProperties.Name="{l:Loc Import.Plan.Title}"
KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type imp:ImportSessionRowViewModel}">
<Grid Style="{StaticResource Session.Grid}" TextElement.FontSize="12">
@@ -358,6 +400,7 @@
<ColumnDefinition Width="0.6*" MinWidth="56" />
<ColumnDefinition Width="0.8*" MinWidth="64" />
<ColumnDefinition Width="1.9*" MinWidth="150" />
<ColumnDefinition Width="Auto" SharedSizeGroup="SessionAction" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Row.TimeText}" ToolTip="{Binding Row.TimeText}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Row.FramesText}" Margin="10,0,0,0" />
@@ -367,8 +410,11 @@
<TextBlock x:Name="Target" DockPanel.Dock="Right" Text="{l:Loc Import.Session.NewShort}" Foreground="{DynamicResource Brush.Accent}"
VerticalAlignment="Center" Margin="8,0,0,0" ToolTip="{Binding Row.TargetText}" />
<TextBox Height="26" Padding="8,0" Text="{Binding Title.Text, UpdateSourceTrigger=PropertyChanged}" shell:EditBehavior.Field="{Binding Title}"
ui:Field.Placeholder="{Binding Placeholder}" ToolTip="{Binding Title.ToolTip}" AutomationProperties.Name="{l:Loc Import.Session.Column.Sequence}" />
IsEnabled="{Binding IsEditable}" ui:Field.Placeholder="{Binding Placeholder}" ToolTip="{Binding TitleToolTip}" ToolTipService.ShowOnDisabled="True"
AutomationProperties.Name="{l:Loc Import.Session.Column.Sequence}" />
</DockPanel>
<Button Grid.Column="5" Style="{StaticResource Button.Row}" Margin="8,0,0,0" Content="{l:Loc Import.Session.Merge}" Command="{Binding MergeCommand}"
ToolTip="{Binding MergeToolTip}" Visibility="{Binding HasMerge, Converter={StaticResource BoolToVisibility}}" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Row.IsNew}" Value="False">
@@ -393,7 +439,7 @@
<ui:StatusGlyph Kind="{Binding ResultKind}" Text="{Binding ResultText}" FontSize="16" FontWeight="SemiBold" ToolTip="{l:Loc Tooltips.Import.Result}" />
<TextBlock Text="{Binding DetailText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="14,0,0,0" VerticalAlignment="Center" />
</StackPanel>
<ListBox Grid.Row="1" ItemsSource="{Binding Failures}" Margin="0,8,0,0" ItemContainerStyle="{StaticResource ListBoxItem.PlainRow}"
<ListBox Grid.Row="1" ItemsSource="{Binding Failures}" Margin="0,8,0,0" ItemContainerStyle="{StaticResource ListBoxItem.Failure}"
Visibility="{Binding HasFailures, Converter={StaticResource BoolToVisibility}}" AutomationProperties.Name="{l:Loc Import.Result.FailuresName}">
<ListBox.ItemTemplate>
<DataTemplate>
@@ -443,7 +489,7 @@
<!-- Footer: Show plan and Import, or the progress while copying. -->
<DockPanel Grid.Row="2" Margin="0,10,0,0" Visibility="{Binding HasPlan, Converter={StaticResource BoolToVisibility}}">
<Button DockPanel.Dock="Left" Content="{l:Loc Import.Plan.Show}" Command="{Binding ShowPlanCommand}" ToolTip="{l:Loc Tooltips.Import.ShowPlan}"
<Button x:Name="ShowPlanButton" DockPanel.Dock="Left" Content="{l:Loc Import.Plan.Show}" Command="{Binding ShowPlanCommand}" ToolTip="{l:Loc Tooltips.Import.ShowPlan}"
Visibility="{Binding IsRunning, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Height="36" Padding="22,0" Content="{Binding StartText}" Command="{Binding StartCommand}"
ToolTip="{Binding StartToolTip}" Visibility="{Binding IsRunning, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
@@ -463,8 +509,12 @@
<!-- ===================== Show plan ===================== -->
<Border Grid.RowSpan="3" Style="{StaticResource Border.Panel}" Background="{DynamicResource Brush.Surface}" Padding="0" Margin="-8"
Visibility="{Binding IsDetailsOpen, Converter={StaticResource BoolToVisibility}}">
<Grid DataContext="{Binding Details}" Margin="16,12">
Visibility="{Binding IsDetailsOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
<Border.InputBindings>
<KeyBinding Key="Escape" Command="{Binding CloseDetailsCommand}" />
</Border.InputBindings>
<Grid DataContext="{Binding Details}" Margin="16,12" Grid.IsSharedSizeScope="True">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -472,7 +522,7 @@
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<DockPanel>
<Button DockPanel.Dock="Right" Style="{StaticResource Button.IconSubtle}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}"
<Button x:Name="ClosePlanButton" DockPanel.Dock="Right" Style="{StaticResource Button.IconSubtle}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}"
Command="{Binding DataContext.CloseDetailsCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" ToolTip="{l:Loc Tooltips.Import.ClosePlan}"
AutomationProperties.Name="{l:Loc Import.Details.Close}" />
<TextBlock Text="{l:Loc Import.Details.Title}" Style="{StaticResource Text.Title}" VerticalAlignment="Center" />
@@ -492,13 +542,15 @@
<ColumnDefinition Width="1.8*" MinWidth="180" />
<ColumnDefinition Width="0.8*" MinWidth="90" />
<ColumnDefinition Width="0.5*" MinWidth="64" />
<ColumnDefinition Width="Auto" SharedSizeGroup="PlanAction" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Source}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Destination}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Action}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Size}" Margin="10,0,0,0" TextAlignment="Right" />
</Grid>
<ListBox Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.PlainRow}" AutomationProperties.Name="{l:Loc Import.Details.Title}">
<ListBox x:Name="PlanRows" Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.PlanRow}" AutomationProperties.Name="{l:Loc Import.Details.Title}"
KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type imp:PlanDetailRow}">
<Grid x:Name="Row" Height="30" TextElement.FontSize="12">
@@ -507,13 +559,20 @@
<ColumnDefinition Width="1.8*" MinWidth="180" />
<ColumnDefinition Width="0.8*" MinWidth="90" />
<ColumnDefinition Width="0.5*" MinWidth="64" />
<ColumnDefinition Width="Auto" SharedSizeGroup="PlanAction" />
</Grid.ColumnDefinitions>
<TextBlock x:Name="Source" Style="{StaticResource Text.Cell}" Text="{Binding Source}" ToolTip="{Binding Source}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Destination}" Margin="10,0,0,0" ToolTip="{Binding Destination}" />
<TextBlock x:Name="Action" Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding ActionText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.CellNumber}" Text="{Binding SizeText}" Margin="10,0,0,0" />
<Button x:Name="Split" Grid.Column="4" Style="{StaticResource Button.Row}" Margin="10,0,4,0" Content="{l:Loc Import.Details.Split}"
Command="{Binding DataContext.SplitCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{Binding}"
ToolTip="{l:Loc Tooltips.Import.Split}" Visibility="Hidden" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding CanSplit}" Value="True">
<Setter TargetName="Split" Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding Kind}" Value="Session">
<Setter TargetName="Source" Property="FontWeight" Value="SemiBold" />
<Setter TargetName="Row" Property="Height" Value="34" />
+35 -1
View File
@@ -1,13 +1,21 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;
namespace Titano.App.Sections;
public partial class ImportView : UserControl
{
public ImportView() => InitializeComponent();
private bool _nicknameOpen;
public ImportView()
{
InitializeComponent();
DataContextChanged += OnDataContextChanged;
}
private ImportViewModel? Model => DataContext as ImportViewModel;
@@ -25,4 +33,30 @@ public partial class ImportView : UserControl
private void OnFolderTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: true);
private void OnFileTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: false);
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is INotifyPropertyChanged old) old.PropertyChanged -= OnModelChanged;
if (e.NewValue is INotifyPropertyChanged model) model.PropertyChanged += OnModelChanged;
}
/// <summary>
/// Keyboard focus follows what opens: the nickname field when it appears (a new card, Rename), and "Show plan"
/// (focus returns to its button when it closes).
/// </summary>
private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
{
if (Model is not { } model) return;
if (e.PropertyName is nameof(ImportViewModel.IsNicknameOpen) or "")
{
var opened = model.IsNicknameOpen && !_nicknameOpen;
_nicknameOpen = model.IsNicknameOpen;
if (opened && IsVisible) FocusLater(NicknameBox);
}
if (e.PropertyName is nameof(ImportViewModel.IsDetailsOpen) && IsVisible)
FocusLater(model.IsDetailsOpen ? ClosePlanButton : ShowPlanButton);
}
/// <summary>After layout: an element that just became visible cannot take focus yet.</summary>
private void FocusLater(UIElement element) => Dispatcher.BeginInvoke(DispatcherPriority.Input, () => element.Focus());
}
+293 -69
View File
@@ -43,10 +43,11 @@ public sealed record ProfileSource(string Name, ICommand Command);
/// <summary>
/// Card and folder import (BRIEF §12.4, §13, Import.html): the card pool, the remembered profile of the selected
/// card, the destination (this PC's archive, a folder, or the signed-in server), the plan before anything is
/// copied (sessions with editable titles, duplicates, space, "Show plan"), the hash-verified import itself (a job
/// for the archive, run here for a folder or the server), its verification result and the after-import actions.
/// Inserted cards raise a toast; a known card with automatic import starts with its profile.
/// card (its own, or its camera's shared profile), the destination (this PC's archive, a folder, or the signed-in
/// server), the plan before anything is copied (sessions with editable titles, merges and splits, duplicates, space,
/// "Show plan"), the hash-verified import itself (a job for the archive, run here for a folder or the server), its
/// verification result and the after-import actions. Inserted cards raise a toast; a known card with automatic
/// import starts with its profile.
/// </summary>
public sealed class ImportViewModel : SectionViewModel
{
@@ -54,6 +55,9 @@ public sealed class ImportViewModel : SectionViewModel
private readonly DispatcherTimer _planDelay;
private readonly Dictionary<string, string> _titles = new(StringComparer.Ordinal);
private readonly HashSet<string> _splits = new(StringComparer.Ordinal);
private readonly HashSet<string> _merges = new(StringComparer.Ordinal);
private readonly Dictionary<string, CardContents> _contents = new(StringComparer.Ordinal);
private IReadOnlyList<MediaCard> _cards = [];
private ImportSource? _selected;
private string? _folderSource;
@@ -76,6 +80,9 @@ public sealed class ImportViewModel : SectionViewModel
private string? _errorText;
private Guid? _jobId;
private string? _jobSourceKey;
private Guid? _jobCardId;
private CameraProfile? _camera;
private bool _followsCamera;
private bool _jobEventsAttached;
private bool _loaded;
private string? _autoStartKey;
@@ -115,10 +122,12 @@ public sealed class ImportViewModel : SectionViewModel
field.Commit();
});
RenameCommand = new RelayCommand(() => IsRenaming = true, () => CanEditProfile);
FollowCameraCommand = new AsyncRelayCommand(() => SetFollowsCameraAsync(!_followsCamera), () => CanFollowCamera);
ForgetCommand = new AsyncRelayCommand(ForgetCardAsync, () => CanEditProfile);
ShowPlanCommand = new RelayCommand(() => Details = _plan is null ? null : ImportPlans.Details(_plan, _choices.Destination, _choices.VerifyCopies),
() => _plan is not null);
CloseDetailsCommand = new RelayCommand(() => Details = null);
SplitCommand = new RelayCommand(p => Split((PlanDetailRow)p!), p => _phase == ImportPhase.Ready && p is PlanDetailRow { CanSplit: true });
StartCommand = new AsyncRelayCommand(StartAsync, () => StartBlocker is null);
CancelCommand = new AsyncRelayCommand(CancelAsync, () => _phase == ImportPhase.Running);
NewImportCommand = new RelayCommand(() =>
@@ -156,6 +165,9 @@ public sealed class ImportViewModel : SectionViewModel
public ICommand RefreshCommand { get; }
public ICommand PickFolderCommand { get; }
/// <summary>The source of a running import stays selected.</summary>
public bool CanChangeSource => _phase != ImportPhase.Running;
/// <summary>Start the import with the card's profile as soon as this card is inserted (per card, BRIEF §12.4).</summary>
public bool AutoImport
{
@@ -197,6 +209,21 @@ public sealed class ImportViewModel : SectionViewModel
/// <summary>A remembered card's profile can be edited, except while its import runs.</summary>
public bool CanEditProfile => _selected?.Card is not null && _phase != ImportPhase.Running;
public string EditToolTip => _selected?.Card is null ? Loc.L("Import.Blocked.EditNeedsCard")
: _phase == ImportPhase.Running ? Loc.L("Import.Blocked.Copying")
: Loc.L("Tooltips.Import.Edit");
/// <summary>The card imports with its camera's shared profile (BRIEF §13); changes made here apply to every card that follows it.</summary>
public bool FollowsCamera => _followsCamera;
public bool CanFollowCamera => CanEditProfile && _selected?.Card?.CameraModel is not null;
public string FollowCameraToolTip => !CanEditProfile ? EditToolTip
: _selected?.Card?.CameraModel is null ? Loc.L("Import.Blocked.CameraUnknown")
: Loc.L("Tooltips.Import.FollowCamera", PathTemplate.CameraName(_selected.Card.CameraMake, _selected.Card.CameraModel));
public ICommand FollowCameraCommand { get; }
public IReadOnlyList<ProfileSource> OtherCards =>
[
.. _cards.Where(c => c.Id != _selected?.Card?.Id)
@@ -292,16 +319,10 @@ public sealed class ImportViewModel : SectionViewModel
/// <summary>The view tells which template field the "{ }" menu writes into.</summary>
public void SetActiveTemplate(bool folder) => _activeTemplateIsFolder = folder;
/// <summary>"→ 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2".</summary>
public string NamePreview
{
get
{
var first = _plan is null ? null : ImportPlans.FirstDestination(_plan, _choices.Destination);
first ??= NamingPreview.FirstNames(_choices.FolderTemplate, _choices.FileTemplate).FirstOrDefault();
return first is null ? string.Empty : Loc.L("Import.Names.Preview", first);
}
}
/// <summary>The first three names the plan copies to, or the templates' sample names before a plan (BRIEF §7.1).</summary>
public string NamePreview => ImportPlans.NamePreview(_plan is { CopyCount: > 0 } plan
? ImportPlans.FirstDestinations(plan, _choices.Destination)
: NamingPreview.FirstNames(_choices.FolderTemplate, _choices.FileTemplate));
public bool SkipDuplicates
{
@@ -363,6 +384,12 @@ public sealed class ImportViewModel : SectionViewModel
/// <summary>Card actions only exist for a card imported into this PC's archive.</summary>
public bool CardActionsApply => _choices.Destination == ImportDestinationKind.Archive && _selected?.Kind == SourceKind.Card;
public string DeleteChoiceToolTip => CardActionsApply ? Loc.L("Tooltips.Import.DeleteChoice") : Loc.L("Import.Blocked.CardActions");
public string FormatChoiceToolTip => CardActionsApply ? Loc.L("Tooltips.Import.FormatChoice") : Loc.L("Import.Blocked.CardActions");
public string DeepToolTip => IsArchiveDestination ? Loc.L("Tooltips.Import.Deep") : Loc.L("Import.Blocked.DeepNeedsArchive");
// ---------------- Plan ----------------
public ImportPhase Phase
@@ -371,6 +398,7 @@ public sealed class ImportViewModel : SectionViewModel
private set
{
if (!Set(ref _phase, value)) return;
foreach (var row in Sessions) row.IsEditable = value != ImportPhase.Running;
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
}
@@ -380,7 +408,11 @@ public sealed class ImportViewModel : SectionViewModel
public ImportPlan? Plan => _plan;
public bool IsBusyPlanning => _phase == ImportPhase.Planning;
public bool IsFormEnabled => _phase != ImportPhase.Running;
/// <summary>The form is fixed while copying, and behind "Show plan" while it is open.</summary>
public bool IsFormEnabled => _phase != ImportPhase.Running && _details is null;
public bool IsPlanPanelEnabled => _details is null;
public bool HasPlan => _plan is not null && _phase is ImportPhase.Ready or ImportPhase.Running;
public bool IsRunning => _phase == ImportPhase.Running;
public bool IsDone => _phase == ImportPhase.Done;
@@ -406,7 +438,10 @@ public sealed class ImportViewModel : SectionViewModel
get => _details;
private set
{
if (Set(ref _details, value)) OnPropertyChanged(nameof(IsDetailsOpen));
if (!Set(ref _details, value)) return;
OnPropertyChanged(nameof(IsDetailsOpen));
OnPropertyChanged(nameof(IsFormEnabled));
OnPropertyChanged(nameof(IsPlanPanelEnabled));
}
}
@@ -415,6 +450,9 @@ public sealed class ImportViewModel : SectionViewModel
public ICommand ShowPlanCommand { get; }
public ICommand CloseDetailsCommand { get; }
/// <summary>"Split here" on a file of "Show plan": a new session starts at that photo.</summary>
public ICommand SplitCommand { get; }
// ---------------- Start, progress, result ----------------
public ICommand StartCommand { get; }
@@ -463,7 +501,10 @@ public sealed class ImportViewModel : SectionViewModel
_ = RefreshSourcesAsync();
}
/// <summary>Lists the devices and remembered cards again, keeping the selection.</summary>
/// <summary>
/// Lists the devices and remembered cards again, keeping the selection and what was typed for it; the selected card
/// that leaves or comes back is planned again, unless its import runs or ended (its result and resume stay).
/// </summary>
public async Task RefreshSourcesAsync()
{
try
@@ -478,28 +519,44 @@ public sealed class ImportViewModel : SectionViewModel
{
Log.Warning("import", "Card list unavailable", ex);
}
var key = _selected?.Key;
await ListContentsAsync();
var previous = _selected;
var pool = Rebuild();
var again = pool.FirstOrDefault(s => s.Key == key) ?? pool.FirstOrDefault(s => s.IsInserted && s.Kind == SourceKind.Card);
// The card of a running, failed or finished import may leave and come back: its import, result and resume stay.
var keepsImport = again is not null && again.Key == key && _phase is ImportPhase.Running or ImportPhase.Failed or ImportPhase.Done;
if (Equals(again, _selected) || keepsImport)
if (previous is not null && pool.FirstOrDefault(s => s.Key == previous.Key) is { } again)
{
_selected = again;
_result?.SetDevice(again?.Device);
_result?.SetDevice(again.Device);
_ = LoadIdentityAsync();
OnPropertyChanged(string.Empty);
if (again.Root != previous.Root && _phase is not (ImportPhase.Running or ImportPhase.Failed or ImportPhase.Done)) Replan();
return;
}
else
_selected = pool.FirstOrDefault(s => s.IsInserted && s.Kind == SourceKind.Card);
OnSourceChanged();
}
/// <summary>Counts the photos of newly inserted cards (a directory walk, off the UI thread); a card that left is forgotten.</summary>
private async Task ListContentsAsync()
{
var devices = Services.Devices.Devices;
foreach (var gone in _contents.Keys.Where(k => devices.All(d => d.Identity != k)).ToList()) _contents.Remove(gone);
foreach (var device in devices.Where(d => d.HasDcim && !_contents.ContainsKey(d.Identity)))
{
_selected = again;
OnSourceChanged();
try
{
_contents[device.Identity] = await Task.Run(() => CardContents.Read(device.Root));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", $"Cannot list {device.Root}", ex);
}
}
}
/// <summary>Lists inserted devices, remembered cards and the picked folder again.</summary>
private IReadOnlyList<ImportSource> Rebuild()
{
var pool = CardPool.Build(Services.Devices.Devices, _cards, _folderSource);
var pool = CardPool.Build(Services.Devices.Devices, _cards, _folderSource, _contents);
_refreshing = true;
try
{
@@ -530,6 +587,17 @@ public sealed class ImportViewModel : SectionViewModel
return _result!;
}
/// <summary>Shows the plan's import copying, at <paramref name="progress"/>, without running it (capture).</summary>
public void ShowRunning(ImportProgress progress)
{
Details = null;
Phase = ImportPhase.Running;
ShowProgress(progress);
}
/// <summary>Shows an import that stopped with <paramref name="message"/>, without running it (capture).</summary>
public void ShowFailed(string message) => Fail(message);
public override void Dispose()
{
_planDelay.Stop();
@@ -550,19 +618,39 @@ public sealed class ImportViewModel : SectionViewModel
{
_isRenaming = false;
_titles.Clear();
_splits.Clear();
_merges.Clear();
_jobId = null;
_jobSourceKey = null;
_jobCardId = null;
Details = null;
Result = null;
Nickname.Load(_selected?.Card?.Nickname ?? string.Empty);
_planning = SelectAsync();
}
/// <summary>Loads the selected source's settings — the card's own, its camera's shared profile, or the defaults — and plans it.</summary>
private async Task SelectAsync()
{
var key = _selected?.Key;
var camera = _selected?.Card is { } selected ? await FindCameraAsync(selected.CameraMake, selected.CameraModel) : null;
// A refresh may have replaced the record meanwhile; another source may have been chosen.
if (_selected?.Key != key) return;
var card = _selected?.Card;
// A card that has a camera but no saved settings takes the camera profile now; one seen for the first time
// takes it once its first plan names the camera (InheritedProfile).
// A card seen for the first time takes its camera's profile once its first plan names the camera (InheritCameraAsync).
_profileResolved = _selected?.Kind != SourceKind.Card || card is { ProfileJson.Length: > 0 } || card?.CameraModel is not null;
LoadChoices(card is { ProfileJson.Length: > 0 } ? ImportService.ProfileOf(card)
: card is not null && CameraProfiles.Find(card.CameraMake, card.CameraModel, _cards.Where(c => c.Id != card.Id)) is { } camera ? camera
: DefaultProfile());
var resolved = card is null ? new ResolvedProfile(DefaultProfile(), false) : CameraProfiles.Resolve(card, camera, DefaultProfile());
if (card is not null && camera is not null && resolved.FollowsCamera) await FollowCameraAsync(card, camera);
else
{
_camera = camera;
_followsCamera = false;
LoadChoices(resolved.Profile);
}
_ = LoadIdentityAsync();
OnPropertyChanged(string.Empty);
Replan();
await _planning;
}
/// <summary>A new card starts from the archive's templates and the brief's defaults.</summary>
@@ -584,6 +672,61 @@ public sealed class ImportViewModel : SectionViewModel
Choices = loaded;
}
private async Task<CameraProfile?> FindCameraAsync(string? make, string? model)
{
if (model is null || Services.Database is not { } db) return null;
try
{
return await new CameraProfileStore(db).FindAsync(make, model);
}
catch (DatabaseException ex)
{
Log.Warning("import", "Camera profile unavailable", ex);
return null;
}
}
/// <summary>Joins or leaves the camera's shared profile; a card that leaves keeps the settings it has now as its own.</summary>
private async Task SetFollowsCameraAsync(bool follow)
{
if (_selected?.Card is not { CameraModel: { } model } card || Services.Database is not { } db || Services.Archives is not { } archives) return;
try
{
var store = new CameraProfileStore(db);
var camera = await store.FindAsync(card.CameraMake, model) ?? new CameraProfile(card.CameraMake, model, _choices.ToProfile(), []);
camera = follow ? camera.With(card.Id) : camera.Without(card.Id);
await store.SaveAsync(camera);
_camera = camera;
_followsCamera = follow;
if (follow) LoadChoices(camera.Profile);
else await ReplaceCardAsync(await archives.Imports.SaveCardAsync(card.Id, card.Nickname, _choices.ToProfile(), card.AutoImport));
OnPropertyChanged(string.Empty);
}
catch (DatabaseException ex)
{
Shell.ReportError(ex);
}
}
/// <summary>Remembers the settings an import starts with: on the card, and on its camera's profile when the card follows it.</summary>
private async Task SaveProfileAsync(MediaCard card, ImportChoices choices)
{
if (Services.Archives is not { } archives || Services.Database is not { } db) return;
try
{
await archives.Imports.SaveCardAsync(card.Id, card.Nickname, choices.ToProfile(), card.AutoImport);
if (_followsCamera && card.CameraModel is { } model)
{
var camera = (_camera ?? new CameraProfile(card.CameraMake, model, choices.ToProfile(), [])) with { Profile = choices.ToProfile() };
await new CameraProfileStore(db).SaveAsync(_camera = camera.With(card.Id));
}
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card profile was not saved", ex);
}
}
private async Task LoadIdentityAsync()
{
var text = _selected?.IdentityText ?? string.Empty;
@@ -654,6 +797,18 @@ public sealed class ImportViewModel : SectionViewModel
_ = RefreshAndSelectAsync(folder);
}
/// <summary>
/// Archive manager "Adopt folder › Copy into the layout" (BRIEF §12.5): the folder becomes the source and this PC's
/// archive the destination; the plan shows where every photo goes before anything is copied.
/// </summary>
public async Task ImportFolderAsync(string folder)
{
if (_phase == ImportPhase.Running) return;
_folderSource = folder;
if (CanUseArchive) _choices = _choices with { Destination = ImportDestinationKind.Archive };
await RefreshAndSelectAsync(folder);
}
private async Task RefreshAndSelectAsync(string key)
{
await RefreshSourcesAsync();
@@ -725,7 +880,7 @@ public sealed class ImportViewModel : SectionViewModel
{
if (!cts.IsCancellationRequested) SetStatus(ImportPhase.Planning, Loc.Plural("Import.Status.ReadingCount", n));
});
var options = _choices.ToOptions(_titles);
var options = _choices.ToOptions(_titles, _splits, _merges);
var cardId = _selected.Kind == SourceKind.Card ? await RegisteredCardIdAsync() : null;
try
{
@@ -736,7 +891,8 @@ public sealed class ImportViewModel : SectionViewModel
if (cts.IsCancellationRequested) return;
_existingFolders = folders;
_rawPlan = plan;
if (InheritedProfile(plan) is { } camera) LoadChoices(camera);
await InheritCameraAsync(plan);
if (cts.IsCancellationRequested) return;
ApplyPlan();
SetStatus(ImportPhase.Ready, null);
// An inherited profile that groups or names differently plans again first.
@@ -756,12 +912,44 @@ public sealed class ImportViewModel : SectionViewModel
}
}
/// <summary>The camera profile of a card seen for the first time, once its first plan names the camera (BRIEF §13).</summary>
private CardProfile? InheritedProfile(ImportPlan plan)
/// <summary>
/// A card seen for the first time: its first plan names the camera (and the index now records it); a camera with a
/// shared profile gives the card its settings (BRIEF §13), which may group or name differently and plan again.
/// </summary>
private async Task InheritCameraAsync(ImportPlan plan)
{
if (_profileResolved || _selected?.Card is not { } card) return null;
if (_profileResolved || _selected?.Card is not { } card || Services.Database is not { } db) return;
_profileResolved = true;
return plan.Sessions is [var first, ..] ? CameraProfiles.Find(first.CameraMake, first.CameraModel, _cards.Where(c => c.Id != card.Id)) : null;
if (plan.Sessions is not [var first, ..]) return;
try
{
// An archive plan recorded the card's camera; keep the screen's copy of the card in step with the index.
if (await db.MediaCards.GetAsync(card.Id) is { } saved) await ReplaceCardAsync(saved);
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card could not be read again", ex);
}
var make = _selected?.Card?.CameraMake ?? first.CameraMake;
var model = _selected?.Card?.CameraModel ?? first.CameraModel;
if (await FindCameraAsync(make, model) is { } camera && _selected?.Card?.Id == card.Id) await FollowCameraAsync(card, camera);
}
/// <summary>The card takes its camera's shared profile and is recorded among the cards that follow it.</summary>
private async Task FollowCameraAsync(MediaCard card, CameraProfile camera)
{
_camera = camera.With(card.Id);
_followsCamera = true;
LoadChoices(camera.Profile);
if (camera.Follows(card.Id) || Services.Database is not { } db) return;
try
{
await new CameraProfileStore(db).SaveAsync(_camera);
}
catch (DatabaseException ex)
{
Log.Warning("import", "The camera profile was not saved", ex);
}
}
/// <summary>The selected card's id, registering an inserted card on first sight.</summary>
@@ -791,10 +979,11 @@ public sealed class ImportViewModel : SectionViewModel
_plan = _choices.TitlesChangeNames ? plan : ImportPlans.WithTitles(plan, _titles);
_totals = ImportPlans.Totals(_plan, _choices.VerifyCopies);
var rows = ImportPlans.Sessions(_plan, _choices.Destination, _existingFolders);
if (!rows.Select(r => r.SessionKey).SequenceEqual(Sessions.Select(s => s.Row.SessionKey)))
// Typed titles do not rebuild the rows (the field being typed in stays); anything else the planner changed does.
if (!rows.Select(r => r with { Title = null }).SequenceEqual(Sessions.Select(s => s.Row with { Title = null })))
{
Sessions.Clear();
foreach (var row in rows) Sessions.Add(new ImportSessionRowViewModel(row, OnTitleChanged));
foreach (var row in rows) Sessions.Add(new ImportSessionRowViewModel(row, OnTitleChanged, Merge) { IsEditable = _phase != ImportPhase.Running });
}
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
@@ -808,6 +997,23 @@ public sealed class ImportViewModel : SectionViewModel
else ApplyPlan();
}
/// <summary>Joins a session to the earlier one of the same camera and format (BRIEF §13: merge in the plan).</summary>
private void Merge(PlanSessionRow row)
{
_splits.Remove(row.FirstPath);
_merges.Add(row.FirstPath);
Replan();
}
/// <summary>Starts a new session at a photo of "Show plan" (BRIEF §13: split in the plan).</summary>
private void Split(PlanDetailRow row)
{
_merges.Remove(row.Source);
_splits.Add(row.Source);
Details = null;
Replan();
}
private void SetStatus(ImportPhase phase, string? text)
{
_statusText = text;
@@ -821,32 +1027,25 @@ public sealed class ImportViewModel : SectionViewModel
{
if (_plan is not { } plan || _selected is not { Root: { } root } source) return;
var choices = _choices;
if (source.Card is { } card && Services.Archives is { } archives)
{
try
{
await archives.Imports.SaveCardAsync(card.Id, card.Nickname, choices.ToProfile(), card.AutoImport);
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card profile was not saved", ex);
}
}
// A new import: an earlier failed job of this screen is no longer what Retry resumes.
_jobId = null;
_jobCardId = null;
_jobSourceKey = source.Key;
if (source.Card is { } card) await SaveProfileAsync(card, choices);
Details = null;
ErrorText = null;
Progress = 0;
ProgressText = Loc.L("Import.Progress.Starting");
_jobSourceKey = source.Key;
Phase = ImportPhase.Running;
if (choices.Destination == ImportDestinationKind.Archive)
{
await StartJobAsync(plan, choices, source);
return;
}
var cts = _runCts = new CancellationTokenSource();
var progress = new Progress<ImportProgress>(ShowProgress);
try
{
if (choices.Destination == ImportDestinationKind.Archive)
{
await StartJobAsync(plan, choices, source, cts.Token);
return;
}
var progress = new Progress<ImportProgress>(ShowProgress);
var outcome = choices.Destination == ImportDestinationKind.Folder
? await Task.Run(() => LocalImport.RunAsync(plan, new FolderImportSink(choices.FolderPath!), choices.VerifyCopies, progress, cts.Token), cts.Token)
: await RunServerAsync(plan, choices, progress, cts.Token);
@@ -856,8 +1055,9 @@ public sealed class ImportViewModel : SectionViewModel
{
Fail(Loc.L("Import.Status.Cancelled"));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or TitanoApiException or HttpRequestException or UntrustedCertificateException)
catch (Exception ex)
{
// Whatever stopped it, the screen leaves Running: the form, the sources and Retry come back.
Log.Warning("import", $"Import of {root} failed", ex);
Fail(ex.Message);
}
@@ -871,16 +1071,29 @@ public sealed class ImportViewModel : SectionViewModel
using var client = new TitanoClient(address, new CertificatePinning(Services.Server.Fingerprints), $"Titano ({Environment.MachineName})") { Token = token };
try
{
return await Task.Run(() => LocalImport.RunAsync(plan, new ServerImportSink(client, staging), choices.VerifyCopies, progress, ct), ct);
var sink = new ServerImportSink(client, staging);
return await Task.Run(() => LocalImport.RunAsync(plan, sink, choices.VerifyCopies, progress, ct, sink.Report), ct);
}
finally
{
// Our own staging folder: verified copies not uploaded yet stay on the card.
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
DeleteStaging(staging);
}
}
private async Task StartJobAsync(ImportPlan plan, ImportChoices choices, ImportSource source)
/// <summary>Our own staging folder: verified copies not uploaded yet stay on the card, so a leftover is only disk space.</summary>
private static void DeleteStaging(string staging)
{
try
{
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", $"Staging folder {staging} left behind", ex);
}
}
private async Task StartJobAsync(ImportPlan plan, ImportChoices choices, ImportSource source, CancellationToken cancelled)
{
if (Services.Engine is not { } engine || _archive is not { } archive)
{
@@ -891,6 +1104,9 @@ public sealed class ImportViewModel : SectionViewModel
var cardId = source.Kind == SourceKind.Card ? source.Card?.Id ?? await RegisteredCardIdAsync() : null;
var job = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, cardId, choices.VerifyCopies));
_jobId = job.Id;
_jobCardId = cardId;
// Cancel pressed while the job was being queued.
if (cancelled.IsCancellationRequested && Services.Jobs is { } jobs) await jobs.CancelAsync(job.Id);
Shell.Notify(Loc.L("Import.Toast.Started", source.Title), plan.CopyCount > 0 ? _totals?.Text : null, Loc.L("Shell.Nav.Jobs"),
Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
@@ -926,6 +1142,7 @@ public sealed class ImportViewModel : SectionViewModel
case JobState.Done:
_jobId = null;
var outcome = await VerifyAsync(plan, job);
_jobCardId = null;
Finish(plan, outcome);
await QueueDeepAnalysisAsync(plan);
break;
@@ -942,14 +1159,21 @@ public sealed class ImportViewModel : SectionViewModel
}
}
/// <summary>Every planned copy must be a frame of the archive now (BRIEF §12.4 verification result).</summary>
/// <summary>Every planned copy must be a frame of the archive now, matched through the job's own records (BRIEF §12.4 verification result).</summary>
private async Task<ImportOutcome> VerifyAsync(ImportPlan plan, Job job)
{
if (Services.Database is not { } db || _archive is not { } archive) return new ImportOutcome(0, 0, 0, [], false);
var verify = _choices.VerifyCopies;
return await Task.Run(() => ImportOutcome.CheckAsync(plan, verify,
async (item, ct) => (await db.Frames.FindBySizeAndCaptureAsync(archive.Id, item.Size, item.CapturedAt, ct).ConfigureAwait(false)).Count > 0,
CancellationToken.None));
var cardId = _jobCardId;
try
{
return await Task.Run(() => ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, cardId, verify, CancellationToken.None));
}
catch (DatabaseException ex)
{
Log.Warning("import", "The import could not be checked against the index", ex);
return ImportOutcome.From(plan, [], verify, stopped: ex.Message);
}
}
/// <summary>
@@ -1061,8 +1285,8 @@ public sealed class ImportViewModel : SectionViewModel
}
Shell.ShowToast(new Toast
{
Title = Loc.L("Import.Toast.Inserted", source.Title),
Message = source.Subtitle,
Title = Loc.L(source.IsKnown ? "Import.Toast.Inserted" : "Import.Toast.NewCard", source.Title),
Message = source.ToastText,
ActionText = Loc.L("Import.Toast.Import"),
ActionToolTip = Loc.L("Tooltips.Import.OpenCard"),
ActionCommand = new RelayCommand(() =>