feat: export panel and Render menu, playback options, videos library (owner review 1 phase 5) (#27)
CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s

Owner review 1 R3, R8, R9. A grouped Export step and Render menu; encoding, playback (reverse, boomerang, loops, fades, hold) and still frames; one videos library on the desktop and the server with a verified trash and copies to a videos folder.

Closes #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #27.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-05 09:18:40 +01:00
1 parent 188b2c2e55
commit 728ffa35cb
729 files changed
+26954 -1652

No files matched your search

+6 -1
View File
@@ -121,6 +121,9 @@
ToolTip="{Binding Project.SaveVersionToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Project.Sync}" Command="{Binding Project.SyncCommand}" ToolTip="{Binding Project.SyncToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Project.History}" Command="{Binding Project.HistoryCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.History}" />
<!-- Owner review 1, R3: moved here from the Export step's footer. -->
<MenuItem Header="{l:Loc Editor.ProjectFile.Save}" Command="{Binding Export.SaveProjectCommand}" ToolTip="{Binding Export.SaveProjectToolTip}"
ToolTipService.ShowOnDisabled="True" />
<Separator />
<MenuItem Header="{l:Loc Editor.Project.Open}" Command="{Binding Project.OpenProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Open}" />
<MenuItem Header="{l:Loc Editor.Project.New}" Command="{Binding Project.NewProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.New}" />
@@ -162,8 +165,10 @@
<Button Content="{l:Loc Editor.Analyse}" Command="{Binding AnalyseCommand}" ToolTip="{Binding AnalyseToolTip}" ToolTipService.ShowOnDisabled="True" />
<Button Content="{l:Loc Editor.OptimiseAll}" Command="{Binding OptimiseAllCommand}" ToolTip="{Binding OptimiseAllToolTip}"
ToolTipService.ShowOnDisabled="True" Margin="12,0,0,0" />
<!-- Owner review 1, R3: "Render ▾" whatever the preset, so the header keeps its width; the tooltip gives the details and the
menu, made again at every opening, checks the current preset (Recommended, batch, recent, Other presets ›, Save frame ›). -->
<v:SplitButton x:Name="RenderButton" IsPrimary="True" Margin="12,0,0,0" Content="{Binding RenderText}" Command="{Binding RenderCommand}"
ItemsSource="{Binding RenderChoices}" DisplayMemberPath="Label" SelectedItem="{Binding SelectedRenderChoice}" ToolTip="{Binding RenderToolTip}"
ItemsSource="{Binding RenderMenuItems, Mode=OneWay}" ToolTip="{Binding RenderToolTip}"
ToolTipService.ShowOnDisabled="True" DropDownToolTip="{Binding RenderChoiceToolTip}"
AutomationProperties.Name="{l:Loc Editor.RenderButton}" />
</StackPanel>
@@ -192,6 +192,22 @@
<ComboBox Width="140" HorizontalAlignment="Left" ItemsSource="{Binding ThumbnailSizes}" SelectedItem="{Binding SelectedThumbnailSize}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Settings.ThumbnailSize}" AutomationProperties.Name="{l:Loc Settings.Archive.Thumbnails}" />
</HeaderedContentControl>
<!-- Where Videos › Copy to folder puts copies of renders (owner review 1, R9). -->
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.VideosFolder}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="360" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Style="{StaticResource TextBox.Path}" Text="{Binding VideosFolder.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding VideosFolder}" ToolTip="{Binding VideosFolder.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Archive.VideosFolder}" />
<Button Grid.Column="1" Style="{StaticResource Button.Icon}" Margin="10,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Command="{Binding BrowseVideosCommand}"
ToolTip="{l:Loc Tooltips.Settings.VideosBrowse}" AutomationProperties.Name="{l:Loc Settings.Archive.VideosBrowse}" />
<Button Grid.Column="2" Margin="10,0,0,0" Content="{l:Loc Settings.Archive.VideosOpen}" Command="{Binding OpenVideosFolderCommand}"
ToolTip="{l:Loc Tooltips.Settings.VideosOpen}" ToolTipService.ShowOnDisabled="True" />
</Grid>
</HeaderedContentControl>
</StackPanel>
<!-- ================= Import: defaults of new cards and folders ================= -->
+42 -2
View File
@@ -8,6 +8,7 @@ using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.App.Videos;
using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
@@ -79,7 +80,7 @@ public sealed class SettingsViewModel : SectionViewModel
new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", .. ShowsStartup ? (string[])["Settings.General.Startup"] : [],
"Settings.General.Notifications", .. ProductFeatures.AdsEnabled ? (string[])["Settings.General.Usage"] : []]),
new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies",
"Settings.Archive.Thumbnails"]),
"Settings.Archive.Thumbnails", "Settings.Archive.VideosFolder"]),
new(SettingsPage.Import, ["Import.Scan.Sessions", "Import.Label.Scan", "Import.Scan.Subfolders", "Import.Scan.Verify", "Import.Label.Duplicates",
"Import.Label.After", "Import.After.Eject"]),
new(SettingsPage.Analysis, ["Settings.Analysis.Width", "Settings.Analysis.Night", "Settings.Analysis.Stars", "Settings.Analysis.Deep"]),
@@ -121,6 +122,12 @@ public sealed class SettingsViewModel : SectionViewModel
Save();
_ = OfferReorganizeAsync(UpdateArchiveAsync(a => a with { Templates = a.Templates with { File = v } }), ReorganizeParts.Files);
}, () => Loc.L("Tooltips.Settings.FileTemplate"));
// Where Videos › Copy to folder puts copies (owner review 1, R9): empty leaves it unset; never inside the archive or the workspace.
VideosFolder = new EditableField(_s.VideosFolder ?? string.Empty, ValidateVideosFolder, v =>
{
_s.VideosFolder = v.Trim().Length == 0 ? null : Path.GetFullPath(v.Trim());
Save();
}, () => Loc.L("Tooltips.Settings.VideosFolder"));
FolderTemplate.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
@@ -216,6 +223,8 @@ public sealed class SettingsViewModel : SectionViewModel
});
BrowseArchiveCommand = new RelayCommand(() => Browse(ArchiveRoot, "Settings.Archive.PickTitle"));
BrowseCacheCommand = new RelayCommand(() => Browse(CacheFolder, "Settings.Storage.PickTitle"));
BrowseVideosCommand = new RelayCommand(() => Browse(VideosFolder, "Settings.Archive.VideosPickTitle"));
OpenVideosFolderCommand = new RelayCommand(OpenVideosFolder, () => !string.IsNullOrWhiteSpace(_s.VideosFolder));
ResetMemoryCommand = new RelayCommand(() => MemoryBudget = MemoryAuto, () => !IsMemoryAuto);
ResetParallelismCommand = new RelayCommand(() =>
{
@@ -400,6 +409,11 @@ public sealed class SettingsViewModel : SectionViewModel
public EditableField FileTemplate { get; }
public ICommand BrowseArchiveCommand { get; }
/// <summary>Archive › Videos folder: where Videos › Copy to folder puts copies of renders.</summary>
public EditableField VideosFolder { get; }
public ICommand BrowseVideosCommand { get; }
public ICommand OpenVideosFolderCommand { get; }
/// <summary>"1.8 TB free".</summary>
public string? ArchiveFreeText
{
@@ -1236,7 +1250,7 @@ public sealed class SettingsViewModel : SectionViewModel
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend,
JobKind.WorkspaceMove,
JobKind.WorkspaceMove, JobKind.VideoCopy,
];
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
@@ -1259,6 +1273,28 @@ public sealed class SettingsViewModel : SectionViewModel
? null
: Loc.L("Errors.Number.DecimalRange", min.ToString("0.##", Loc.Culture), max.ToString("0.##", Loc.Culture));
/// <summary>Empty leaves the videos folder unset; a path must be absolute and outside the archive and the workspace.</summary>
private string? ValidateVideosFolder(string text) =>
text.Trim().Length == 0 ? null
: VideosFolders.Problem(text.Trim(), _s.LastArchivePath, Shell.Services.Workspace.Root) is { } problem ? VideoText.FolderReason(problem) : null;
/// <summary>Opens the videos folder in Explorer, creating it first (it is Chronos's own folder for copies).</summary>
private void OpenVideosFolder()
{
if (string.IsNullOrWhiteSpace(_s.VideosFolder)) return;
try
{
Directory.CreateDirectory(_s.VideosFolder);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
Log.Warning("settings", $"The videos folder could not be created: {ex.Message}");
Shell.Notify(Loc.L("Errors.Videos.FolderCreate", _s.VideosFolder), ErrorText.For(ex), isError: true);
return;
}
ShellActions.Reveal(_s.VideosFolder);
}
private void Browse(EditableField field, string titleKey)
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L(titleKey), field.Value.Length > 0 ? field.Value : null);
@@ -1620,8 +1656,10 @@ public sealed class SettingsViewModel : SectionViewModel
_s.FileTemplate = defaults.FileTemplate;
_s.ProxyLongEdge = defaults.ProxyLongEdge;
_s.ThumbnailLongEdge = defaults.ThumbnailLongEdge;
_s.VideosFolder = defaults.VideosFolder;
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
VideosFolder.Load(_s.VideosFolder ?? string.Empty);
UpdatePreview();
Save();
OnAllPropertiesChanged();
@@ -1682,6 +1720,7 @@ public sealed class SettingsViewModel : SectionViewModel
ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
VideosFolder.Load(_s.VideosFolder ?? string.Empty);
LoadImportFields();
LoadAnalysisFields();
Parallelism.Load(EffectiveParallelism.ToString(CultureInfo.CurrentCulture));
@@ -1765,6 +1804,7 @@ public sealed class SettingsViewModel : SectionViewModel
ArchiveRoot.Refresh();
FolderTemplate.Refresh();
FileTemplate.Refresh();
VideosFolder.Refresh();
SessionGap.Refresh();
MinimumFrames.Refresh();
// Decimals are written in the language's own way ("6.25", "6,25").
+285
View File
@@ -0,0 +1,285 @@
<UserControl x:Class="Chronos.App.Sections.VideosView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
xmlns:v="clr-namespace:Chronos.Ui.Visuals;assembly=Chronos.Ui"
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
xmlns:vid="clr-namespace:Chronos.App.Videos">
<UserControl.Resources>
<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" />
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
</Style>
<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" />
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
</Style>
<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>
<!--
The list's preset, format and date columns: with the player open the list keeps the title, duration, size and state
(the player shows the rest), so the state stays in view beside the pane.
-->
<Style x:Key="Column.Preset" TargetType="ColumnDefinition">
<Setter Property="Width" Value="*" />
<Setter Property="MinWidth" Value="110" />
<Style.Triggers>
<DataTrigger Binding="{Binding DataContext.IsPlayerOpen, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="True">
<Setter Property="Width" Value="0" />
<Setter Property="MinWidth" Value="0" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="Column.Format" TargetType="ColumnDefinition" BasedOn="{StaticResource Column.Preset}">
<Setter Property="MinWidth" Value="130" />
</Style>
<Style x:Key="Column.Date" TargetType="ColumnDefinition" BasedOn="{StaticResource Column.Preset}">
<Setter Property="Width" Value="130" />
<Setter Property="MinWidth" Value="0" />
</Style>
<Style x:Key="Text.CellDetail" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
<Style.Triggers>
<DataTrigger Binding="{Binding DataContext.IsPlayerOpen, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="True">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="Text.HeaderDetail" TargetType="TextBlock" BasedOn="{StaticResource Text.Header}">
<Style.Triggers>
<DataTrigger Binding="{Binding DataContext.IsPlayerOpen, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="True">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
<ItemsPanelTemplate x:Key="Panel.Row">
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
<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>
<!--
One render's own menu (the card's and the row's): it acts on the render, or on the selection when the render is part of
it. Tag carries the section's view model to the menu, which lives outside the visual tree.
-->
<ContextMenu x:Key="Menu.Video" x:Shared="False">
<MenuItem Header="{l:Loc Videos.Play}" Command="{Binding PlacementTarget.Tag.PlayCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{Binding MenuPlayToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Videos.ShowInFolder}" Command="{Binding PlacementTarget.Tag.ShowInFolderCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{Binding MenuShowInFolderToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{Binding MenuCopyText}" Command="{Binding PlacementTarget.Tag.CopyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{Binding MenuCopyToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Videos.CopyOnServer}" Command="{Binding PlacementTarget.Tag.CopyOnServerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{Binding MenuCopyOnServerToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Videos.OpenInEdit}" Command="{Binding PlacementTarget.Tag.OpenInEditCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{Binding MenuOpenInEditToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Render.SendAgain}" Command="{Binding PlacementTarget.Tag.SendCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.WorkspaceRow}" ToolTipService.ShowOnDisabled="True"
Visibility="{Binding Entry.IsUnsent, Converter={StaticResource BoolToVisibility}}" />
<Separator />
<MenuItem Header="{l:Loc Videos.Delete}" Command="{Binding PlacementTarget.Tag.DeleteCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{Binding MenuDeleteToolTip}" ToolTipService.ShowOnDisabled="True" />
</ContextMenu>
<Style x:Key="ListBoxItem.VideoCard" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Card}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}" />
<Setter Property="ContextMenu" Value="{StaticResource Menu.Video}" />
<EventSetter Event="MouseDoubleClick" Handler="OnItemDoubleClick" />
</Style>
<Style x:Key="ListBoxItem.VideoRow" 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}" />
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}" />
<Setter Property="ContextMenu" Value="{StaticResource Menu.Video}" />
<EventSetter Event="MouseDoubleClick" Handler="OnItemDoubleClick" />
</Style>
</UserControl.Resources>
<Grid>
<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: search, kind, codec, year, source, order · cards or list (decision 20). -->
<Grid Grid.ColumnSpan="2" Margin="20,0" MinHeight="56">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="260" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="Auto" />
<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 Videos.Search}" ToolTip="{l:Loc Tooltips.Videos.Search}" AutomationProperties.Name="{l:Loc Videos.Search}" />
<WrapPanel Grid.Column="1" VerticalAlignment="Top" Margin="0,8">
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Kinds}" SelectedItem="{Binding SelectedKind}" Tag="{Binding IsKindFiltered}"
ToolTip="{l:Loc Tooltips.Videos.Kind}" AutomationProperties.Name="{l:Loc Videos.Kind.All}" />
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Codecs}" SelectedItem="{Binding SelectedCodec}" Tag="{Binding IsCodecFiltered}"
ToolTip="{l:Loc Tooltips.Videos.Codec}" AutomationProperties.Name="{l:Loc Videos.Codec.All}" />
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Years}" SelectedItem="{Binding SelectedYear}" Tag="{Binding IsYearFiltered}"
ToolTip="{l:Loc Tooltips.Videos.Year}" AutomationProperties.Name="{l:Loc Videos.Year.All}" />
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Sources}" SelectedItem="{Binding SelectedSource}" Tag="{Binding IsSourceFiltered}"
ToolTip="{l:Loc Tooltips.Videos.Source}" AutomationProperties.Name="{l:Loc Videos.Source.All}" />
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Sorts}" SelectedItem="{Binding SelectedSort}"
ToolTip="{l:Loc Tooltips.Videos.Sort}" AutomationProperties.Name="{l:Loc Videos.Sort.Newest}" />
</WrapPanel>
<v:SegmentedControl Grid.Column="2" VerticalAlignment="Top" Margin="10,12,0,0" SelectedIndex="{Binding LayoutIndex, Mode=TwoWay}"
AutomationProperties.Name="{l:Loc Videos.View.Grid}">
<v:SegmentedItem Glyph="{StaticResource Icon.ViewGrid}" ToolTip="{l:Loc Tooltips.Videos.View}" AutomationProperties.Name="{l:Loc Videos.View.Grid}" />
<v:SegmentedItem Glyph="{StaticResource Icon.ViewList}" ToolTip="{l:Loc Tooltips.Videos.View}" AutomationProperties.Name="{l:Loc Videos.View.List}" />
</v:SegmentedControl>
<Button Grid.Column="3" Style="{StaticResource Button.Quick}" VerticalAlignment="Top" Margin="8,14,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Refresh}"
Command="{Binding RefreshCommand}" ToolTip="{l:Loc Tooltips.Videos.Refresh}" AutomationProperties.Name="{l:Loc Videos.Refresh}" />
</Grid>
<!-- The sequence the list is narrowed to (a chip that clears that filter alone), and why the server's videos are not listed. -->
<WrapPanel Grid.Row="1" Grid.ColumnSpan="2" Margin="20,0,20,4">
<Button Style="{StaticResource Button.Chip}" Content="{Binding SequenceFilterText}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}" Command="{Binding ClearSequenceCommand}"
ToolTip="{l:Loc Tooltips.Videos.ClearSequence}" Visibility="{Binding IsSequenceFiltered, Converter={StaticResource BoolToVisibility}}" Margin="0,0,12,4" />
<ui:StatusGlyph Kind="Offline" Text="{Binding ServerStatusText}" ToolTip="{Binding ServerStatusToolTip}" VerticalAlignment="Center" Margin="0,0,12,4"
Visibility="{Binding IsServerLimited, Converter={StaticResource BoolToVisibility}}" />
<ProgressBar Width="120" Height="4" IsIndeterminate="True" VerticalAlignment="Center" Margin="0,0,12,4"
Visibility="{Binding IsLoading, Converter={StaticResource BoolToVisibility}}" />
</WrapPanel>
<!-- Cards: the sequence's cover (or the still itself), title, preset, details and state chips. -->
<ListBox x:Name="CardGrid" Grid.Row="2" Style="{StaticResource ListBox.Cards}" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.VideoCard}"
Visibility="{Binding IsGrid, Converter={StaticResource BoolToVisibility}}" AutomationProperties.Name="{l:Loc Shell.Nav.Videos}"
KeyboardNavigation.TabNavigation="Continue">
<ListBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding PlayCommand}" />
<KeyBinding Key="Delete" Command="{Binding DeleteCommand}" />
</ListBox.InputBindings>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type vid:VideoRowViewModel}">
<v:SequenceCard Title="{Binding Title}" Subtitle="{Binding DetailsText}" Badge="{Binding DurationText}" Statuses="{Binding States}" Thumbnail="{Binding Poster}"
IsSelected="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}, Mode=TwoWay}"
SelectToolTip="{l:Loc Tooltips.Videos.Select}" ToolTip="{Binding ToolTip}" Loaded="OnCardLoaded">
<v:SequenceCard.ActionsContent>
<StackPanel Orientation="Horizontal">
<Button Style="{StaticResource Button.Quick}" ui:ButtonIcon.Glyph="{StaticResource Icon.Play}"
Command="{Binding DataContext.PlayCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{Binding PlayToolTip}" AutomationProperties.Name="{l:Loc Videos.Play}" />
<Button Style="{StaticResource Button.Quick}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}"
Command="{Binding DataContext.ShowInFolderCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{Binding MenuShowInFolderToolTip}" AutomationProperties.Name="{l:Loc Videos.ShowInFolder}" />
<Button Style="{StaticResource Button.Quick}" ui:ButtonIcon.Glyph="{StaticResource Icon.CopyToFolder}"
Command="{Binding DataContext.CopyCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{Binding MenuCopyToolTip}" AutomationProperties.Name="{Binding MenuCopyText}" />
</StackPanel>
</v:SequenceCard.ActionsContent>
</v:SequenceCard>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- List: title, preset, format, duration, size, date and state. -->
<Border Grid.Row="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,6">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" MinWidth="120" />
<ColumnDefinition Style="{StaticResource Column.Preset}" />
<ColumnDefinition Style="{StaticResource Column.Format}" />
<ColumnDefinition Width="72" />
<ColumnDefinition Width="80" />
<ColumnDefinition Style="{StaticResource Column.Date}" />
<ColumnDefinition Width="*" MinWidth="140" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Title}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.HeaderDetail}" Text="{l:Loc Videos.Column.Preset}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.HeaderDetail}" Text="{l:Loc Videos.Column.Format}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Duration}" TextAlignment="Right" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Size}" TextAlignment="Right" Margin="10,0,0,0" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.HeaderDetail}" Text="{l:Loc Videos.Column.Date}" Margin="10,0,0,0" />
<TextBlock Grid.Column="6" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.State}" Margin="16,0,0,0" />
</Grid>
</Border>
<ListBox x:Name="RowList" Grid.Row="1" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.VideoRow}" SelectionMode="Extended"
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" AutomationProperties.Name="{l:Loc Shell.Nav.Videos}" KeyboardNavigation.TabNavigation="Continue">
<ListBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding PlayCommand}" />
<KeyBinding Key="Delete" Command="{Binding DeleteCommand}" />
</ListBox.InputBindings>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type vid:VideoRowViewModel}">
<Grid ToolTip="{Binding ToolTip}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" MinWidth="120" />
<ColumnDefinition Style="{StaticResource Column.Preset}" />
<ColumnDefinition Style="{StaticResource Column.Format}" />
<ColumnDefinition Width="72" />
<ColumnDefinition Width="80" />
<ColumnDefinition Style="{StaticResource Column.Date}" />
<ColumnDefinition Width="*" MinWidth="140" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Title}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.CellDetail}" Text="{Binding Subtitle}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.CellDetail}" Text="{Binding FormatText}" Margin="10,0,0,0" FlowDirection="LeftToRight" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.CellNumber}" Text="{Binding DurationText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.CellNumber}" Text="{Binding SizeText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.CellDetail}" Text="{Binding DateText}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<ItemsControl Grid.Column="6" Margin="16,0,0,0" ItemsSource="{Binding States}" ItemTemplate="{StaticResource Template.Status}"
ItemsPanel="{StaticResource Panel.Row}" VerticalAlignment="Center" Focusable="False" ClipToBounds="True" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
<!-- Empty states: no video anywhere, or none the filters keep. -->
<ui:EmptyState Grid.Row="2" Message="{l:Loc Videos.Empty}" Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}" />
<ui:EmptyState Grid.Row="2" Message="{l:Loc Videos.Empty}" Visibility="{Binding IsNoMatch, Converter={StaticResource BoolToVisibility}}">
<Button Content="{l:Loc Library.ClearFilters}" Command="{Binding ClearFiltersCommand}" ToolTip="{l:Loc Tooltips.Library.ClearFilters}" />
</ui:EmptyState>
<!-- The player pane on the right (decision 21). -->
<vid:VideoPlayerPane Grid.Row="2" Grid.Column="1" Width="420" Margin="0,4,20,12" DataContext="{Binding Player}"
Visibility="{Binding DataContext.IsPlayerOpen, RelativeSource={RelativeSource AncestorType=UserControl}, Converter={StaticResource BoolToVisibility}}" />
<!-- The actions on the selection; Delete… stands apart at the far right, 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}}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<WrapPanel VerticalAlignment="Center">
<TextBlock Text="{Binding SelectionText}" FontWeight="SemiBold" 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 Videos.Play}" Command="{Binding PlayCommand}" ToolTip="{Binding PlayToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.ShowInFolder}" Command="{Binding ShowInFolderCommand}" ToolTip="{Binding ShowInFolderToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{Binding CopyText}" Command="{Binding CopyCommand}" ToolTip="{Binding CopyToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.CopyOnServer}" Command="{Binding CopyOnServerCommand}" ToolTip="{Binding CopyOnServerToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.OpenInEdit}" Command="{Binding OpenInEditCommand}" ToolTip="{Binding OpenInEditToolTip}" />
<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 Grid.Column="1" Style="{StaticResource Button.Destructive}" Height="30" Margin="8,0,8,8" VerticalAlignment="Top" Content="{l:Loc Videos.Delete}"
Command="{Binding DeleteCommand}" ToolTip="{Binding DeleteToolTip}" ToolTipService.ShowOnDisabled="True" />
</Grid>
</Border>
</Grid>
</UserControl>
@@ -0,0 +1,28 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Chronos.App.Videos;
namespace Chronos.App.Sections;
/// <summary>Videos: every render made from the photos, here and on the server, in cards or a list, with a player beside them.</summary>
public partial class VideosView : UserControl
{
public VideosView() => InitializeComponent();
private VideosViewModel? Model => DataContext as VideosViewModel;
/// <summary>A double click plays the render (or shows "Cannot play here" when it cannot).</summary>
private void OnItemDoubleClick(object sender, MouseButtonEventArgs e)
{
if (sender is not ListBoxItem { DataContext: VideoRowViewModel row } || Model is not { } model) return;
if (model.PlayCommand.CanExecute(row)) model.PlayCommand.Execute(row);
e.Handled = true;
}
/// <summary>A card asks for its cover only once it is on screen.</summary>
private void OnCardLoaded(object sender, RoutedEventArgs e)
{
if (sender is FrameworkElement { DataContext: VideoRowViewModel row }) row.RequestPoster();
}
}
+892
View File
@@ -0,0 +1,892 @@
using System.IO;
using System.Net.Http;
using System.Windows.Input;
using System.Windows.Media;
using Chronos.App.Infrastructure;
using Chronos.App.Library;
using Chronos.App.Shell;
using Chronos.App.Videos;
using Chronos.App.Workspace;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Windows.Security;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Videos;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Sections;
/// <summary>
/// The Videos section (owner review 1, R9; decisions 20 and 21): every render of this PC's archive, of the signed-in server
/// and of the workspace (not sent yet) in one list, merged by render id, with filters, an order, cards or a list, and the
/// actions on the selection: Play in the pane on the right, Show in folder, Copy (or Download) to the videos folder checked
/// by hash, Copy on server, Delete… into the trash after a dry run, Open in Edit, and Send for the workspace's renders.
/// An older server, or none, leaves this PC's videos with the reason.
/// </summary>
public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVideosSection
{
private IReadOnlyList<VideoEntry> _entries = [];
private IReadOnlyList<VideoRowViewModel> _rows = [];
private IReadOnlyList<FilterOption<string?>> _kinds = [];
private IReadOnlyList<FilterOption<string?>> _codecs = [];
private IReadOnlyList<FilterOption<int?>> _years = [];
private IReadOnlyList<FilterOption<VideoSourceFilter>> _sources = [];
private IReadOnlyList<FilterOption<string?>> _sorts = [];
private FilterOption<string?> _kind = null!;
private FilterOption<string?> _codec = null!;
private FilterOption<int?> _year = null!;
private FilterOption<VideoSourceFilter> _source = null!;
private FilterOption<string?> _sort = null!;
private string _searchText = string.Empty;
private Guid? _sequenceId;
private string? _sequenceTitle;
private int _layoutIndex;
private bool _isLoading;
private int _loads;
private VideoServer _server = VideoServer.SignedOut;
private VideoPlayerViewModel? _player;
private readonly Dictionary<Guid, Task<Sequence?>> _sequences = [];
public VideosViewModel(ShellViewModel shell)
: base(SectionKey.Videos, "Icon.Videos")
{
Shell = shell;
var services = shell.Services;
LocalLibrary = () => services.Archives?.Videos;
ServerVideos = () => ServerOf(services);
WorkspaceRenders = ct => ReadWorkspaceAsync(services, ct);
Folder = () => services.Settings.VideosFolder;
Enqueue = async request =>
{
if (services.Engine is not { } engine) throw new InvalidOperationException("The job engine is not running.");
await engine.EnqueueAsync(request);
};
Posters = (entry, width, ct) => PosterAsync(services, entry, width, ct);
BuildOptions();
PlayCommand = new RelayCommand(p => Play(Target(p)), p => Target(p) is { Entry.HasLocalFile: true });
ShowInFolderCommand = new RelayCommand(p => ShowInFolder(Target(p)), p => Target(p) is { Entry.HasLocalFile: true });
CopyCommand = new AsyncRelayCommand((p, _) => CopyAsync(Targets(p)), p => CopyBlocker(Targets(p)) is null);
CopyOnServerCommand = new AsyncRelayCommand((p, _) => CopyOnServerAsync(Targets(p)), p => CopyOnServerBlocker(Targets(p)) is null);
DeleteCommand = new AsyncRelayCommand((p, _) => DeleteAsync(Targets(p)), p => DeleteBlocker(Targets(p)) is null);
OpenInEditCommand = new RelayCommand(p => OpenInEdit(Target(p)), p => Target(p) is { } row && CanOpen(row.Entry));
SendCommand = new AsyncRelayCommand((p, _) => SendAsync(Targets(p)), p => Targets(p).Any(r => r.Entry.IsUnsent));
ClearFiltersCommand = new RelayCommand(ClearFilters, () => Filter.IsFiltered);
ClearSequenceCommand = new RelayCommand(() => ShowSequence(null), () => IsSequenceFiltered);
RefreshCommand = new AsyncRelayCommand(RefreshAsync);
_layoutIndex = services.Settings.VideosLayout == LibraryLayout.List ? 1 : 0;
ClearSelectionCommand = new RelayCommand(() =>
{
foreach (var row in _rows) row.IsSelected = false;
}, () => HasSelection);
ClosePlayerCommand = new RelayCommand(() => Player = null);
}
public ShellViewModel Shell { get; }
// ---- Sources (tests substitute their own) ----
/// <summary>This PC's videos library; null while the index is not open.</summary>
internal Func<IVideoLibrary?> LocalLibrary { get; set; }
/// <summary>The signed-in server's videos, and what the account may do there.</summary>
internal Func<VideoServer> ServerVideos { get; set; }
/// <summary>The workspace's renders not sent yet.</summary>
internal Func<CancellationToken, Task<IReadOnlyList<VideoEntry>>> WorkspaceRenders { get; set; }
/// <summary>Queues a job of this PC (a copy into the videos folder).</summary>
internal Func<ArchiveJobRequest, Task> Enqueue { get; set; }
/// <summary>The poster of a card: the sequence's cover, or the still itself.</summary>
internal Func<VideoEntry, int, CancellationToken, Task<ImageSource?>> Posters { get; set; }
/// <summary>The videos folder of this PC (Settings › Archive); null or empty while unset.</summary>
internal Func<string?> Folder { get; set; }
// ---- List ----
/// <summary>Every render, merged, before the filters.</summary>
public IReadOnlyList<VideoEntry> Entries
{
get => _entries;
private set
{
_entries = value;
BuildOptions();
Apply();
}
}
/// <summary>The renders the filters keep, in the chosen order.</summary>
public IReadOnlyList<VideoRowViewModel> Rows
{
get => _rows;
private set
{
foreach (var row in _rows)
{
row.SelectionChanged -= OnSelectionChanged;
row.PosterRequested -= OnPosterRequested;
}
if (!Set(ref _rows, value)) return;
foreach (var row in _rows)
{
row.Section = this;
row.SelectionChanged += OnSelectionChanged;
row.PosterRequested += OnPosterRequested;
}
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(IsNoMatch));
OnSelectionChanged(null);
}
}
public bool IsLoading
{
get => _isLoading;
private set
{
if (!Set(ref _isLoading, value)) return;
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(IsNoMatch));
}
}
/// <summary>No video anywhere: "No videos".</summary>
public bool IsEmpty => !_isLoading && _entries.Count == 0;
/// <summary>Videos, none of which the filters keep: "No videos" and Clear filters.</summary>
public bool IsNoMatch => !_isLoading && _entries.Count > 0 && _rows.Count == 0;
/// <summary>The cards (0) or the list (1), kept for the next run (Settings: <see cref="AppSettings.VideosLayout"/>).</summary>
public int LayoutIndex
{
get => _layoutIndex;
set
{
if (value is < 0 or > 1 || !Set(ref _layoutIndex, value)) return;
Shell.Services.Settings.VideosLayout = value == 1 ? LibraryLayout.List : LibraryLayout.Grid;
OnPropertyChanged(nameof(IsGrid));
OnPropertyChanged(nameof(IsList));
}
}
public bool IsGrid => _layoutIndex == 0;
public bool IsList => _layoutIndex == 1;
// ---- Filters ----
public string SearchText
{
get => _searchText;
set
{
if (Set(ref _searchText, value ?? string.Empty)) Apply();
}
}
public IReadOnlyList<FilterOption<string?>> Kinds { get => _kinds; private set => Set(ref _kinds, value); }
public IReadOnlyList<FilterOption<string?>> Codecs { get => _codecs; private set => Set(ref _codecs, value); }
public IReadOnlyList<FilterOption<int?>> Years { get => _years; private set => Set(ref _years, value); }
public IReadOnlyList<FilterOption<VideoSourceFilter>> Sources { get => _sources; private set => Set(ref _sources, value); }
public IReadOnlyList<FilterOption<string?>> Sorts { get => _sorts; private set => Set(ref _sorts, value); }
public FilterOption<string?> SelectedKind
{
get => _kind;
set => SetFilter(ref _kind, value ?? _kinds[0]);
}
public FilterOption<string?> SelectedCodec
{
get => _codec;
set => SetFilter(ref _codec, value ?? _codecs[0]);
}
public FilterOption<int?> SelectedYear
{
get => _year;
set => SetFilter(ref _year, value ?? _years[0]);
}
public FilterOption<VideoSourceFilter> SelectedSource
{
get => _source;
set => SetFilter(ref _source, value ?? _sources[0]);
}
public FilterOption<string?> SelectedSort
{
get => _sort;
set => SetFilter(ref _sort, value ?? _sorts[0]);
}
public bool IsKindFiltered => _kind is { IsAny: false };
public bool IsCodecFiltered => _codec is { IsAny: false };
public bool IsYearFiltered => _year is { IsAny: false };
public bool IsSourceFiltered => _source is { IsAny: false };
/// <summary>The sequence the list is narrowed to (the Export footer's and the Render menu's "Videos"); null for all.</summary>
public Guid? SequenceId => _sequenceId;
/// <summary>The title of that sequence, shown as a chip that clears it.</summary>
public string? SequenceFilterText => _sequenceId is null ? null : _sequenceTitle ?? _entries.FirstOrDefault(e => e.SequenceId == _sequenceId)?.Title;
public bool IsSequenceFiltered => _sequenceId is not null;
/// <summary>The filters and the order in force.</summary>
public VideoFilter Filter => new()
{
Text = _searchText,
Kind = _kind?.Value,
Codec = _codec?.Value,
Year = _year?.Value,
Source = _source?.Value ?? VideoSourceFilter.All,
SequenceId = _sequenceId,
Sort = _sort?.Value,
};
public ICommand ClearFiltersCommand { get; }
/// <summary>The sequence chip: the videos of every sequence again, the other filters kept.</summary>
public ICommand ClearSequenceCommand { get; }
/// <summary>Reads this PC's, the server's and the workspace's videos again (<see cref="RefreshAsync"/>).</summary>
public ICommand RefreshCommand { get; }
/// <summary>Narrows the list to the videos of one sequence (null: every sequence).</summary>
public void ShowSequence(Guid? sequenceId, string? title = null)
{
_sequenceId = sequenceId;
_sequenceTitle = sequenceId is null ? null : title;
OnPropertyChanged(nameof(SequenceId));
OnPropertyChanged(nameof(SequenceFilterText));
OnPropertyChanged(nameof(IsSequenceFiltered));
Apply();
}
/// <summary>The editor's links to this section (<see cref="Chronos.App.Editor.VideosLink"/>) narrow it the same way.</summary>
void Chronos.App.Editor.IVideosSection.ShowSequence(Guid? sequenceId) => ShowSequence(sequenceId);
// ---- Server ----
/// <summary>How the signed-in server's videos reach the list.</summary>
public VideoServerState ServerState => _server.State;
/// <summary>The server's videos are not listed: the status line says why.</summary>
public bool IsServerLimited => _server.State != VideoServerState.Available && (_server.State != VideoServerState.SignedOut || Shell.Services.Server.HasSavedSession);
/// <summary>"Server not reachable", or "Server" greyed out with its reason in <see cref="ServerStatusToolTip"/>.</summary>
public string ServerStatusText => _server.State == VideoServerState.Unreachable ? Loc.L("Videos.ServerUnreachable") : Loc.L("Videos.Source.Server");
public string? ServerStatusToolTip => _server.State switch
{
VideoServerState.Old => Loc.L("Tooltips.Videos.ServerOld"),
VideoServerState.SignedOut => Loc.L("Tooltips.Videos.ServerOffline"),
VideoServerState.Unreachable => Loc.L("Tooltips.Videos.ServerOffline"),
_ => null,
};
// ---- Selection ----
public IReadOnlyList<VideoRowViewModel> SelectedRows => [.. _rows.Where(r => r.IsSelected)];
public bool HasSelection => _rows.Any(r => r.IsSelected);
/// <summary>"Selected: 3".</summary>
public string SelectionText => Loc.L("Videos.Selected", Formatting.Count(_rows.Count(r => r.IsSelected)));
public ICommand ClearSelectionCommand { get; }
// ---- Actions ----
public ICommand PlayCommand { get; }
/// <summary>The toolbar's Play tooltip: why the selection does not play here, else what Play does.</summary>
public string PlayToolTip => PlayToolTipOf(SelectedRows);
public ICommand ShowInFolderCommand { get; }
public ICommand CopyCommand { get; }
public ICommand CopyOnServerCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand OpenInEditCommand { get; }
public ICommand SendCommand { get; }
/// <summary>Copy to folder, or Download for the server's videos alone.</summary>
public string CopyText => CopyTextOf(SelectedRows);
public string CopyToolTip => CopyToolTipOf(SelectedRows);
public string CopyOnServerToolTip => CopyOnServerToolTipOf(SelectedRows);
public string DeleteToolTip => DeleteToolTipOf(SelectedRows);
/// <summary>Show in folder's tooltip: why it waits (more than one video, a server's video alone, a file gone), else what it does.</summary>
public string ShowInFolderToolTip => ShowInFolderToolTipOf(SelectedRows);
/// <summary>Open in Edit's tooltip: why it waits (more than one video, a server's video alone), else what it does.</summary>
public string OpenInEditToolTip => OpenInEditToolTipOf(SelectedRows);
/// <summary>The row's Copy to folder or Download tooltip (its context menu).</summary>
public string RowCopyToolTip(VideoRowViewModel row) => CopyToolTipOf(Targets(row));
/// <summary>What the row's menu acts on: the selection when the row is part of it, else the row alone (as the commands do).</summary>
internal IReadOnlyList<VideoRowViewModel> TargetsOf(VideoRowViewModel row) => Targets(row);
internal static string PlayToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[var one] => one.PlayToolTip,
{ Count: > 1 } => Loc.L("Tooltips.Videos.SelectOne"),
_ => Loc.L("Tooltips.Videos.Play"),
};
internal static string CopyTextOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows is { Count: > 0 } && rows.All(r => !r.Entry.IsLocal && r.Entry.IsOnServer) ? Loc.L("Videos.Download") : Loc.L("Videos.Copy");
internal string CopyToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
CopyBlocker(rows) ?? (rows.Count > 0 && rows.All(r => !r.Entry.IsLocal) ? Loc.L("Tooltips.Videos.Download") : Loc.L("Tooltips.Videos.Copy"));
internal string CopyOnServerToolTipOf(IReadOnlyList<VideoRowViewModel> rows) => CopyOnServerBlocker(rows) ?? Loc.L("Tooltips.Videos.CopyOnServer");
internal string DeleteToolTipOf(IReadOnlyList<VideoRowViewModel> rows) => DeleteBlocker(rows) ?? Loc.L("Tooltips.Videos.Delete");
internal static string ShowInFolderToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[{ Entry.HasLocalFile: true }] or [] => Loc.L("Tooltips.Videos.ShowInFolder"),
[{ Entry.Missing: true }] => Loc.L("Tooltips.Videos.Missing"),
[_] => Loc.L("Tooltips.Videos.ServerOnly"),
_ => Loc.L("Tooltips.Videos.SelectOne"),
};
internal static string OpenInEditToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[var one] when CanOpen(one.Entry) => Loc.L("Tooltips.Videos.OpenInEdit"),
[{ Entry.IsUnsent: true }] => Loc.L("Tooltips.Videos.WorkspaceRow"),
[_] => Loc.L("Tooltips.Videos.ServerOnly"),
[] => Loc.L("Tooltips.Videos.OpenInEdit"),
_ => Loc.L("Tooltips.Videos.SelectOne"),
};
public ICommand ClosePlayerCommand { get; }
/// <summary>The player pane on the right; null while closed.</summary>
public VideoPlayerViewModel? Player
{
get => _player;
private set
{
if (!Set(ref _player, value)) return;
OnPropertyChanged(nameof(IsPlayerOpen));
}
}
public bool IsPlayerOpen => _player is not null;
/// <summary>Reads the three places again and lists what they hold (the filters stay).</summary>
public async Task RefreshAsync()
{
var load = ++_loads;
IsLoading = true;
try
{
var server = ServerVideos();
var localTask = ReadLocalAsync();
var serverTask = ReadServerAsync(server);
var workspaceTask = ReadWorkspaceSafeAsync();
var local = await localTask;
var (remote, state) = await serverTask;
var workspace = await workspaceTask;
var merged = await WithLocalCopiesAsync(VideoSources.Merge(local, remote, workspace));
if (load != _loads) return;
_server = state;
Entries = merged;
OnPropertyChanged(nameof(ServerState));
OnPropertyChanged(nameof(IsServerLimited));
OnPropertyChanged(nameof(ServerStatusText));
OnPropertyChanged(nameof(ServerStatusToolTip));
OnPropertyChanged(nameof(SequenceFilterText));
}
finally
{
if (load == _loads) IsLoading = false;
}
}
protected override void OnActivated() => _ = RefreshAsync();
protected override void OnLanguageChanged()
{
BuildOptions();
// The rows' words are made with them: made again in the new language.
Rows = [];
Apply();
base.OnLanguageChanged();
}
private async Task<IReadOnlyList<VideoEntry>> ReadLocalAsync()
{
try
{
return await Task.Run(() => VideoSources.ReadLocalAsync(LocalLibrary()));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or InvalidDataException)
{
Log.Warning("videos", "The videos of this PC could not be listed", ex);
Shell.ReportError(ex);
return [];
}
}
/// <summary>The server's renders this PC downloaded, with their copies here (<see cref="VideoSources.WithLocalCopies"/>).</summary>
private async Task<IReadOnlyList<VideoEntry>> WithLocalCopiesAsync(IReadOnlyList<VideoEntry> entries)
{
List<Guid> serverOnly = [.. entries.Where(e => e.IsOnServer && !e.IsLocal && !e.IsUnsent).Select(e => e.Id)];
if (serverOnly.Count == 0 || LocalLibrary() is not { IsAvailable: true } library) return entries;
try
{
return await Task.Run(async () =>
{
var copies = await library.CopiesAsync(serverOnly);
var paths = copies.ToDictionary(c => c.Key, c => (IReadOnlyList<string>)[.. c.Value.Select(copy => copy.Path)]);
return VideoSources.WithLocalCopies(entries, paths, p => File.Exists(p) || Directory.Exists(p));
});
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("videos", "The copies of the server's videos on this PC could not be read", ex);
return entries;
}
}
private static async Task<(IReadOnlyList<VideoEntry> Entries, VideoServer State)> ReadServerAsync(VideoServer server)
{
if (server is not { State: VideoServerState.Available, Connect: { } connect }) return ([], server);
try
{
using var remote = connect();
return (await VideoSources.ReadServerAsync(remote), server);
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException)
{
Log.Warning("videos", "The server's videos could not be listed", ex);
return ([], server with { State = VideoServerState.Unreachable, Connect = null });
}
}
private async Task<IReadOnlyList<VideoEntry>> ReadWorkspaceSafeAsync()
{
try
{
return await WorkspaceRenders(CancellationToken.None);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or WorkspaceException or DatabaseException)
{
Log.Warning("videos", "The workspace's renders could not be listed", ex);
return [];
}
}
private static async Task<IReadOnlyList<VideoEntry>> ReadWorkspaceAsync(AppServices services, CancellationToken cancellationToken)
{
var workspace = services.Workspace;
if (!workspace.IsAvailable || !Directory.Exists(workspace.Root)) return [];
var projects = await workspace.ListAsync(cancellationToken);
return await Task.Run(() => VideoSources.ReadWorkspace(workspace.Store, projects), cancellationToken);
}
/// <summary>The signed-in session's server, its capability and the account's rights.</summary>
private static VideoServer ServerOf(AppServices services)
{
var session = services.Server;
if (!session.IsConnected || session.Flow is not { Address: { } address, Token: { } token, Info: { } info }) return VideoServer.SignedOut;
return VideoServer.Of(info, session.User?.Permissions ?? 0, () =>
new ChronosRemoteVideos(new ChronosClient(address, new CertificatePinning(session.Fingerprints), $"Chronos ({Environment.MachineName})") { Token = token }));
}
private void Apply()
{
// A row is kept while its render reads the same (its selection and its poster with it).
var cache = _rows.ToDictionary(r => r.Entry.Id);
Rows = [.. Filter.Apply(_entries).Select(e => cache.TryGetValue(e.Id, out var row)
? row.Entry == e ? row : new VideoRowViewModel(e) { IsSelected = row.IsSelected, Poster = row.Poster }
: new VideoRowViewModel(e))];
if (_player is { } player && !_entries.Any(e => e.Id == player.Entry.Id)) Player = null;
OnPropertyChanged(nameof(Filter));
}
private void SetFilter<T>(ref FilterOption<T> field, FilterOption<T> value, [System.Runtime.CompilerServices.CallerMemberName] string? name = null)
{
if (EqualityComparer<FilterOption<T>>.Default.Equals(field, value)) return;
field = value;
OnPropertyChanged(name);
OnPropertyChanged(nameof(IsKindFiltered));
OnPropertyChanged(nameof(IsCodecFiltered));
OnPropertyChanged(nameof(IsYearFiltered));
OnPropertyChanged(nameof(IsSourceFiltered));
Apply();
}
private void ClearFilters()
{
_searchText = string.Empty;
_kind = _kinds[0];
_codec = _codecs[0];
_year = _years[0];
_source = _sources[0];
_sequenceId = null;
_sequenceTitle = null;
OnAllPropertiesChanged();
Apply();
}
/// <summary>The choices of the filters: kinds, sources and orders fixed, codecs and years those the videos have; each choice kept.</summary>
private void BuildOptions()
{
var kind = _kind?.Value;
var codec = _codec?.Value;
var year = _year?.Value;
var source = _source?.Value ?? VideoSourceFilter.All;
var sort = _sort?.Value;
var allKinds = Loc.L("Videos.Kind.All");
Kinds =
[
new(null, allKinds, allKinds, IsAny: true),
.. new[] { RenderKind.Video, RenderKind.Still, RenderKind.Sequence }.Select(k => new FilterOption<string?>(k, VideoText.Kind(k), VideoText.Kind(k))),
];
var allCodecs = Loc.L("Videos.Codec.All");
Codecs =
[
new(null, allCodecs, allCodecs, IsAny: true),
.. _entries.Select(e => e.Codec).OfType<string>().Where(c => c.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase)
.Append(codec).OfType<string>().Distinct(StringComparer.OrdinalIgnoreCase)
.Select(c => new FilterOption<string?>(c, VideoSources.CodecText(c), VideoSources.CodecText(c))).OrderBy(o => o.Label, StringComparer.CurrentCulture),
];
var allYears = Loc.L("Videos.Year.All");
Years =
[
new(null, allYears, allYears, IsAny: true),
.. _entries.Select(e => (int?)e.Year).Append(year).OfType<int>().Distinct().OrderDescending()
.Select(y => new FilterOption<int?>(y, y.ToString(Loc.Culture), y.ToString(Loc.Culture))),
];
var allSources = Loc.L("Videos.Source.All");
Sources =
[
new(VideoSourceFilter.All, allSources, allSources, IsAny: true),
new(VideoSourceFilter.Local, Loc.L("Videos.Source.Local"), Loc.L("Videos.Source.Local")),
new(VideoSourceFilter.Server, Loc.L("Videos.Source.Server"), Loc.L("Videos.Source.Server")),
new(VideoSourceFilter.NotSent, Loc.L("Videos.Source.NotSent"), Loc.L("Videos.Source.NotSent")),
];
Sorts = [.. VideoSorts.All.Select(s => new FilterOption<string?>(s, SortText(s), SortText(s), IsAny: s == VideoSorts.Newest))];
_kind = _kinds.First(o => o.Value == kind);
_codec = _codecs.FirstOrDefault(o => string.Equals(o.Value, codec, StringComparison.OrdinalIgnoreCase)) ?? _codecs[0];
_year = _years.First(o => o.Value == year);
_source = _sources.First(o => o.Value == source);
_sort = _sorts.FirstOrDefault(o => o.Value == sort) ?? _sorts[0];
OnPropertyChanged(nameof(SelectedKind));
OnPropertyChanged(nameof(SelectedCodec));
OnPropertyChanged(nameof(SelectedYear));
OnPropertyChanged(nameof(SelectedSource));
OnPropertyChanged(nameof(SelectedSort));
}
private static string SortText(string sort) => sort switch
{
VideoSorts.Oldest => Loc.L("Videos.Sort.Oldest"),
VideoSorts.Largest => Loc.L("Videos.Sort.Largest"),
VideoSorts.Title => Loc.L("Videos.Sort.Title"),
_ => Loc.L("Videos.Sort.Newest"),
};
private void OnSelectionChanged(VideoRowViewModel? row)
{
OnPropertyChanged(nameof(HasSelection));
OnPropertyChanged(nameof(SelectedRows));
OnPropertyChanged(nameof(SelectionText));
OnPropertyChanged(nameof(CopyText));
OnPropertyChanged(nameof(PlayToolTip));
OnPropertyChanged(nameof(CopyToolTip));
OnPropertyChanged(nameof(CopyOnServerToolTip));
OnPropertyChanged(nameof(DeleteToolTip));
OnPropertyChanged(nameof(ShowInFolderToolTip));
OnPropertyChanged(nameof(OpenInEditToolTip));
// A row's menu acts on the selection it is part of: its words follow the selection too.
foreach (var each in _rows) each.RefreshMenu();
CommandManager.InvalidateRequerySuggested();
}
private async void OnPosterRequested(VideoRowViewModel row)
{
try
{
row.Poster = await Posters(row.Entry, 472, CancellationToken.None);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or DatabaseException or InvalidOperationException
or OperationCanceledException)
{
Log.Info("videos", $"The poster of {row.Entry.FileName} could not be loaded: {ex.Message}");
}
}
/// <summary>A still shows itself; any other render of this PC its sequence's cover.</summary>
private async Task<ImageSource?> PosterAsync(AppServices services, VideoEntry entry, int width, CancellationToken cancellationToken)
{
if (entry.Kind == RenderKind.Still && entry.HasLocalFile && VideoSources.ShowsAsImage(entry.LocalPath))
{
return await Task.Run<ImageSource?>(() =>
{
using var stream = File.OpenRead(entry.LocalPath!);
return ThumbnailService.DecodeStream(stream, 1, width);
}, cancellationToken);
}
if (!entry.IsLocal || services.Database is not { } db || services.Thumbnails is not { } thumbnails) return null;
if (!_sequences.TryGetValue(entry.SequenceId, out var sequence)) _sequences[entry.SequenceId] = sequence = db.Sequences.GetAsync(entry.SequenceId, cancellationToken);
return await sequence is { } found ? await thumbnails.HeroAsync(found, width, cancellationToken) : null;
}
// ---- What the actions apply to ----
/// <summary>A row's own menu acts on the row, or on the selection when the row is part of it; the toolbar on the selection.</summary>
private IReadOnlyList<VideoRowViewModel> Targets(object? parameter) =>
parameter is VideoRowViewModel row ? row.IsSelected ? SelectedRows : [row] : SelectedRows;
private VideoRowViewModel? Target(object? parameter) => Targets(parameter) is [var one] ? one : null;
private string? FolderProblem()
{
var folder = Folder();
var problem = VideosFolders.Problem(folder, Shell.Services.Settings.LastArchivePath, Shell.Services.Workspace.Root);
return problem ?? LocalLibrary()?.FolderProblem(folder);
}
/// <summary>Why Copy to folder cannot run on <paramref name="rows"/>; null when it can.</summary>
internal string? CopyBlocker(IReadOnlyList<VideoRowViewModel> rows)
{
if (rows.Count == 0) return Loc.L("Tooltips.Videos.Copy");
if (!rows.Any(r => Copyable(r.Entry))) return rows.All(r => r.Entry.Missing) ? Loc.L("Tooltips.Videos.Missing") : Loc.L("Tooltips.Videos.WorkspaceRow");
if (FolderProblem() is { } problem) return VideoText.FolderReason(problem);
return LocalLibrary() is { IsAvailable: true } ? null : Loc.L("Tooltips.Videos.Copy");
}
/// <summary>Why Copy on server cannot run on <paramref name="rows"/>; null when it can.</summary>
internal string? CopyOnServerBlocker(IReadOnlyList<VideoRowViewModel> rows)
{
if (_server.State != VideoServerState.Available) return ServerStatusToolTip;
if (!_server.CanEdit) return Loc.L("Tooltips.Videos.NoEditRight");
return rows.Any(r => r.Entry is { IsOnServer: true, Missing: false }) ? null : Loc.L("Tooltips.Videos.OnServer");
}
/// <summary>Why Delete… cannot run on <paramref name="rows"/>; null when it can.</summary>
internal string? DeleteBlocker(IReadOnlyList<VideoRowViewModel> rows)
{
if (rows.Count == 0) return Loc.L("Tooltips.Videos.Delete");
if (rows.All(r => r.Entry.IsUnsent)) return Loc.L("Tooltips.Videos.WorkspaceRow");
var local = rows.Any(r => r.Entry.IsLocal) && LocalLibrary() is { IsAvailable: true };
var server = rows.Any(r => !r.Entry.IsLocal && r.Entry.IsOnServer);
if (local) return null;
if (server && _server.State != VideoServerState.Available) return ServerStatusToolTip;
if (server && !_server.CanDelete) return Loc.L("Tooltips.Videos.NoDeleteRight");
return server ? null : Loc.L("Tooltips.Videos.Delete");
}
/// <summary>A render Copy to folder takes: this PC's file, or the server's alone (downloaded).</summary>
private bool Copyable(VideoEntry entry) =>
!entry.IsUnsent && !entry.Missing && (entry.IsLocal || (entry.IsOnServer && _server.State == VideoServerState.Available));
private static bool CanOpen(VideoEntry entry) => entry.IsLocal || entry is { IsUnsent: true, WorkspaceServerHome: false };
// ---- Actions ----
private void Play(VideoRowViewModel? row)
{
if (row is null) return;
Player = new VideoPlayerViewModel(row.Entry, ClosePlayerCommand, new RelayCommand(() => ShowInFolder(row), () => row.Entry.HasLocalFile));
}
private static void ShowInFolder(VideoRowViewModel? row)
{
if (row?.Entry is { HasLocalFile: true, LocalPath: { } path }) ShellActions.Reveal(path);
}
private void OpenInEdit(VideoRowViewModel? row)
{
if (row is not null && CanOpen(row.Entry)) Shell.OpenSequence(row.Entry.SequenceId);
}
/// <summary>
/// Copy to folder: this PC's renders are copied into the videos folder, the server's alone downloaded there, each checked
/// by hash (a <see cref="JobKind.VideoCopy"/> job of this PC); the renders themselves are never touched.
/// </summary>
internal async Task CopyAsync(IReadOnlyList<VideoRowViewModel> rows)
{
if (CopyBlocker(rows) is { } blocker)
{
Shell.Notify(blocker, isError: true);
return;
}
var folder = Path.GetFullPath(Folder()!);
var library = LocalLibrary()!;
var copyable = rows.Select(r => r.Entry).Where(Copyable).ToList();
try
{
foreach (var (fromServer, ids) in new[] { (false, copyable.Where(e => e.IsLocal)), (true, copyable.Where(e => !e.IsLocal)) })
{
IReadOnlyList<Guid> list = [.. ids.Select(e => e.Id)];
if (list.Count == 0) continue;
await Enqueue(library.CopyJob(new VideoCopyParameters(list, folder, fromServer, Environment.MachineName)));
}
Shell.Notify(Loc.L("Videos.Copy.Queued"), Loc.L("Videos.Target.Copy", Formatting.Count(copyable.Count)), Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"),
() => Shell.Navigate(SectionKey.Jobs));
}
catch (VideoLibraryException ex)
{
Shell.Notify(VideoText.Error(ex), isError: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or InvalidOperationException)
{
Shell.ReportError(ex);
}
}
/// <summary>Copy on server: the server copies its renders into its own videos folder, checked by hash.</summary>
internal async Task CopyOnServerAsync(IReadOnlyList<VideoRowViewModel> rows)
{
var blocker = CopyOnServerBlocker(rows);
if (blocker is not null || _server.Connect is not { } connect)
{
Shell.Notify(blocker ?? Loc.L("Tooltips.Videos.ServerOffline"), isError: true);
return;
}
IReadOnlyList<Guid> ids = [.. rows.Where(r => r.Entry is { IsOnServer: true, Missing: false }).Select(r => r.Entry.Id)];
try
{
using var remote = connect();
await remote.CopyAsync(ids);
Shell.Notify(Loc.L("Videos.Copy.Queued"), Loc.L("Videos.Target.Copy", Formatting.Count(ids.Count)));
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException)
{
Log.Warning("videos", "Copying videos on the server failed", ex);
Shell.Notify(ErrorText.ForServer(ex), isError: true);
}
}
/// <summary>
/// Delete…: the dry run first (this PC's renders and the server's alone apart), then one confirmation saying what goes,
/// its bytes, what stays and why, and that copies in the videos folder stay; then each delete with its plan's
/// fingerprint, which a changed plan refuses with nothing moved.
/// </summary>
internal async Task DeleteAsync(IReadOnlyList<VideoRowViewModel> rows)
{
if (DeleteBlocker(rows) is { } blocker)
{
Shell.Notify(blocker, isError: true);
return;
}
var library = LocalLibrary();
IReadOnlyList<Guid> localIds = library is { IsAvailable: true } ? [.. rows.Where(r => r.Entry.IsLocal).Select(r => r.Entry.Id)] : [];
IReadOnlyList<Guid> serverIds = _server is { State: VideoServerState.Available, CanDelete: true }
? [.. rows.Where(r => !r.Entry.IsLocal && r.Entry.IsOnServer).Select(r => r.Entry.Id)]
: [];
VideoDeletePlans plans;
try
{
var local = localIds.Count > 0 ? await Task.Run(() => library!.PlanDeleteAsync(localIds)) : null;
VideoDeletePlanDto? server = null;
if (serverIds.Count > 0 && _server.Connect is { } connect)
{
using var remote = connect();
server = await remote.PlanDeleteAsync(serverIds);
}
plans = new VideoDeletePlans(local, server, rows.DistinctBy(r => r.Entry.Id).ToDictionary(r => r.Entry.Id, r => VideoDeletePlans.NameOf(r.Entry)));
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or TaskCanceledException or UntrustedCertificateException)
{
Shell.Notify(ErrorText.ForServer(ex), isError: true);
return;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Shell.ReportError(ex);
return;
}
LastDeletePlans = plans;
if (plans.Request() is not { } request)
{
if (plans.Blocked > 0) Shell.Notify(Loc.L("Videos.Delete.Blocked", Formatting.Count(plans.Blocked)), string.Join(Environment.NewLine, plans.Lines()), isError: true);
return;
}
if (!Shell.Services.Dialogs.Confirm(request)) return;
var deleted = 0;
try
{
// Each delete asks for exactly the ids that were planned, blocked ones included: its fingerprint covers them all, and
// what is blocked stays where it is.
if (plans.Local is { Items.Count: > 0 } localPlan)
{
var result = await Task.Run(() => library!.DeleteAsync(localIds, localPlan.Fingerprint, Environment.MachineName));
deleted += result.Deleted.Count;
}
if (plans.Server is { Items.Count: > 0 } serverPlan && _server.Connect is { } connect)
{
using var remote = connect();
var result = await remote.DeleteAsync(serverIds, serverPlan.Fingerprint);
deleted += result.Items.Count;
}
Shell.Notify(Loc.L("Videos.Delete.Done", Formatting.Count(deleted)));
}
catch (VideoLibraryException ex)
{
Shell.Notify(VideoText.Error(ex), isError: true);
}
catch (ChronosApiException ex) when (ex.Error?.Code == VideoErrors.PlanChanged)
{
Shell.Notify(Loc.L("Errors.Videos.Fingerprint"), isError: true);
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or TaskCanceledException or UntrustedCertificateException)
{
Shell.Notify(ErrorText.ForServer(ex), isError: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Shell.ReportError(ex);
}
await RefreshAsync();
}
/// <summary>The plans of the last Delete… (tests).</summary>
internal VideoDeletePlans? LastDeletePlans { get; private set; }
/// <summary>Send: queues the sending home of the workspace projects' renders not sent yet.</summary>
private async Task SendAsync(IReadOnlyList<VideoRowViewModel> rows)
{
foreach (var project in rows.Select(r => r.Entry).Where(e => e.IsUnsent && e.WorkspaceProjectId is not null).Select(e => e.WorkspaceProjectId!.Value).Distinct())
{
try
{
if (await Shell.Services.Workspace.SendRendersAsync(project))
Shell.Notify(Loc.L("Editor.Render.Sending"), null, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
catch (Exception ex) when (ex is WorkspaceException or IOException or InvalidDataException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("videos", $"The renders of workspace project {project} could not be queued to be sent", ex);
Shell.Notify(Loc.L("Editor.Render.SendFailed"), ex is WorkspaceException ? ex.Message : ErrorText.For(ex), isError: true);
}
}
}
/// <summary>What Send does for <paramref name="row"/>, worded for its project's home.</summary>
public static string SendToolTip(VideoRowViewModel row)
{
ArgumentNullException.ThrowIfNull(row);
return WorkspaceText.ForHome("Tooltips.Editor.Render.SendAgain", row.Entry.WorkspaceServerHome);
}
}