feat(P7): desktop Videos section with player, copy, delete and videos folder
Adds the Videos rail section (Ctrl+4; Archive, Jobs and Server move to Ctrl+5..7) that lists every render of this PC's archive, the signed-in server and the workspace (not sent yet) in one list merged by render id, with search, kind, codec, year, source and order filters, cards or a list, and a player pane that plays in-process and falls back to "Cannot play here". Copy to folder queues a hash-verified VideoCopy job into the new Settings > Archive > Videos folder (never inside the archive or the workspace, the reason given when unset); Delete... runs the dry run first, shows its bytes and what stays, and deletes with the plan's fingerprint. An older server, or one out of reach, leaves this PC's videos with the reason. The trash dialog restores videos entries through the videos library, and a finished VideoCopy job raises its toast. Refs #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d472dfdec1
commit
8c87a9f47f
18 files changed
+2665
-15
No files matched your search
@@ -2,6 +2,7 @@ using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Videos;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
@@ -9,6 +10,7 @@ using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Archiving;
|
||||
@@ -22,9 +24,16 @@ public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore)
|
||||
/// <summary>"Photos", "Sequence": what the entry holds.</summary>
|
||||
public string KindText => TrashEmptyPlans.KindText(Entry.Kind);
|
||||
|
||||
/// <summary>"Photos · 12 photos · 340 MB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language).</summary>
|
||||
public string Detail => string.Join(Loc.Separator, KindText, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes),
|
||||
Formatting.LeftToRight(Entry.Folder));
|
||||
/// <summary>
|
||||
/// "Photos · 12 photos · 340 MB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language); a videos
|
||||
/// entry has no photos: "Videos · 1.2 GB · …".
|
||||
/// </summary>
|
||||
public string Detail => Entry.Kind == TrashKind.Videos
|
||||
? string.Join(Loc.Separator, KindText, Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder))
|
||||
: string.Join(Loc.Separator, KindText, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder));
|
||||
|
||||
/// <summary>What Restore brings back: the render into its sequence's renders, or the sequence or photos.</summary>
|
||||
public string RestoreToolTip => Entry.Kind == TrashKind.Videos ? Loc.L("Tooltips.Archive.TrashRestoreVideo") : Loc.L("Tooltips.Archive.TrashRestore");
|
||||
|
||||
/// <summary>"Deleted 02/10/2026 18:04".</summary>
|
||||
public string DeletedText => Loc.L("Archive.Trash.Deleted", Formatting.Date(Entry.DeletedAt) + " " + Formatting.TimeOfDay(Entry.DeletedAt));
|
||||
@@ -175,6 +184,11 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
|
||||
BusyText = Loc.L("Archive.Trash.Restoring", entry.Title);
|
||||
try
|
||||
{
|
||||
if (entry.Kind == TrashKind.Videos)
|
||||
{
|
||||
await RestoreVideoAsync(entry);
|
||||
return;
|
||||
}
|
||||
var result = await Task.Run(() => _archives.RestoreEntryAsync(entry.ArchiveId, entry.Name, _followUps));
|
||||
Log.Info("archive", $"{entry.Title} restored from the trash ({entry.Kind}, {result.Photos} photo(s), {result.Kept.Count} kept)");
|
||||
BusyText = null;
|
||||
@@ -205,6 +219,27 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A render deleted from Videos goes back among its sequence's renders after its hash is checked (the videos library
|
||||
/// refuses a file that changed in the trash, or a sequence that is gone, and says why).
|
||||
/// </summary>
|
||||
private async Task RestoreVideoAsync(TrashEntry entry)
|
||||
{
|
||||
try
|
||||
{
|
||||
var render = await Task.Run(() => _archives.Videos.RestoreAsync(entry.ArchiveId, entry.Name));
|
||||
Log.Info("archive", $"{entry.Title} restored from the trash (render {render.Id})");
|
||||
Rows = [.. _rows.Where(r => r.Entry != entry)];
|
||||
await _restored();
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
Log.Warning("archive", $"Restoring {entry.Title} failed: {ex.Code}", ex);
|
||||
var text = VideoText.Error(ex, entry.Title);
|
||||
ShowMessage(text, text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The line of what a restore kept in the trash, and its tooltip: one reason's sentence ("2 photos stayed in the trash:
|
||||
/// they could not be moved back."), or how many stayed when they stayed for different reasons. The tooltip holds that
|
||||
|
||||
@@ -110,6 +110,12 @@ public sealed class AppSettings
|
||||
public string FolderTemplate { get; set; } = TemplateDefaults.Folder;
|
||||
public string FileTemplate { get; set; } = TemplateDefaults.File;
|
||||
|
||||
/// <summary>
|
||||
/// Where Videos › Copy to folder puts copies of renders (owner review 1, R9): Videos\Chronos by default, null or empty
|
||||
/// when unset (Copy then says why it cannot run). Never inside the archive or the workspace.
|
||||
/// </summary>
|
||||
public string? VideosFolder { get; set; } = Videos.VideosFolders.Default();
|
||||
|
||||
/// <summary>Proxy long edge of new archives (also written into the open archive); 0 = full size, -1 = no proxies.</summary>
|
||||
public int ProxyLongEdge { get; set; } = 1920;
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ public static class JobNotices
|
||||
private static bool Announces(JobKind kind) =>
|
||||
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
|
||||
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash or JobKind.Convert or JobKind.WorkspaceRender or JobKind.WorkspaceSend
|
||||
or JobKind.WorkspaceMove;
|
||||
or JobKind.WorkspaceMove or JobKind.VideoCopy;
|
||||
|
||||
/// <summary>
|
||||
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
|
||||
|
||||
@@ -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 ================= -->
|
||||
|
||||
@@ -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.ReportError(ex);
|
||||
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").
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
<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>
|
||||
<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="{l:Loc Tooltips.Videos.Play}" ToolTipService.ShowOnDisabled="True" />
|
||||
<MenuItem Header="{l:Loc Videos.ShowInFolder}" Command="{Binding PlacementTarget.Tag.ShowInFolderCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.ShowInFolder}" ToolTipService.ShowOnDisabled="True" />
|
||||
<MenuItem Header="{l:Loc Videos.Copy}" Command="{Binding PlacementTarget.Tag.CopyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.Copy}" ToolTipService.ShowOnDisabled="True" />
|
||||
<MenuItem Header="{l:Loc Videos.CopyOnServer}" Command="{Binding PlacementTarget.Tag.CopyOnServerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.CopyOnServer}" ToolTipService.ShowOnDisabled="True" />
|
||||
<MenuItem Header="{l:Loc Videos.OpenInEdit}" Command="{Binding PlacementTarget.Tag.OpenInEditCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.OpenInEdit}" 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="{l:Loc Tooltips.Videos.Delete}" 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" />
|
||||
</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>
|
||||
</Grid>
|
||||
|
||||
<!-- The sequence the list is narrowed to (a chip that clears the filters), 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 ClearFiltersCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Library.ClearFilters}" 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="{l:Loc Tooltips.Videos.Play}" 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="{l:Loc Tooltips.Videos.ShowInFolder}" 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="{l:Loc Tooltips.Videos.Copy}" AutomationProperties.Name="{l:Loc Videos.Copy}" />
|
||||
</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="160" />
|
||||
<ColumnDefinition Width="*" MinWidth="110" />
|
||||
<ColumnDefinition Width="*" MinWidth="130" />
|
||||
<ColumnDefinition Width="72" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="130" />
|
||||
<ColumnDefinition Width="*" MinWidth="140" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Title}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Preset}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" 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.Header}" 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="160" />
|
||||
<ColumnDefinition Width="*" MinWidth="110" />
|
||||
<ColumnDefinition Width="*" MinWidth="130" />
|
||||
<ColumnDefinition Width="72" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="130" />
|
||||
<ColumnDefinition Width="*" MinWidth="140" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Title}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Subtitle}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" 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.Cell}" 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="{l:Loc Tooltips.Videos.Play}" />
|
||||
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.ShowInFolder}" Command="{Binding ShowInFolderCommand}" ToolTip="{l:Loc Tooltips.Videos.ShowInFolder}" />
|
||||
<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="{l:Loc Tooltips.Videos.OpenInEdit}" />
|
||||
<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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,801 @@
|
||||
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
|
||||
{
|
||||
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);
|
||||
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.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).</summary>
|
||||
public int LayoutIndex
|
||||
{
|
||||
get => _layoutIndex;
|
||||
set
|
||||
{
|
||||
if (value is < 0 or > 1 || !Set(ref _layoutIndex, value)) return;
|
||||
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>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();
|
||||
}
|
||||
|
||||
// ---- 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; }
|
||||
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 => SelectedRows is { Count: > 0 } rows && rows.All(r => !r.Entry.IsLocal && r.Entry.IsOnServer) ? Loc.L("Videos.Download") : Loc.L("Videos.Copy");
|
||||
|
||||
public string CopyToolTip => CopyBlocker(SelectedRows) ?? (SelectedRows.All(r => !r.Entry.IsLocal) && SelectedRows.Count > 0
|
||||
? Loc.L("Tooltips.Videos.Download")
|
||||
: Loc.L("Tooltips.Videos.Copy"));
|
||||
|
||||
public string CopyOnServerToolTip => CopyOnServerBlocker(SelectedRows) ?? Loc.L("Tooltips.Videos.CopyOnServer");
|
||||
|
||||
public string DeleteToolTip => DeleteBlocker(SelectedRows) ?? Loc.L("Tooltips.Videos.Delete");
|
||||
|
||||
/// <summary>The row's Copy to folder or Download tooltip (its context menu).</summary>
|
||||
public string RowCopyToolTip(VideoRowViewModel row) => CopyBlocker([row]) ?? Loc.L(row.Entry.IsLocal ? "Tooltips.Videos.Copy" : "Tooltips.Videos.Download");
|
||||
|
||||
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;
|
||||
if (load != _loads) return;
|
||||
_server = state;
|
||||
Entries = VideoSources.Merge(local, remote, workspace);
|
||||
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 [];
|
||||
}
|
||||
}
|
||||
|
||||
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(CopyToolTip));
|
||||
OnPropertyChanged(nameof(CopyOnServerToolTip));
|
||||
OnPropertyChanged(nameof(DeleteToolTip));
|
||||
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);
|
||||
}
|
||||
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
|
||||
{
|
||||
if (plans.Local is { Items.Count: > 0 } localPlan)
|
||||
{
|
||||
var result = await Task.Run(() => library!.DeleteAsync([.. localPlan.Items.Select(i => i.Render.Id)], 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([.. serverPlan.Items.Select(i => i.Id)], 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);
|
||||
}
|
||||
}
|
||||
@@ -13,20 +13,22 @@
|
||||
<ui:ChronosWindow.TaskbarItemInfo>
|
||||
<TaskbarItemInfo ProgressState="{Binding TaskbarState}" ProgressValue="{Binding TaskbarProgress}" />
|
||||
</ui:ChronosWindow.TaskbarItemInfo>
|
||||
<!-- Sections by keyboard, as the rail tooltips list them (BRIEF §12.1): Ctrl+1…6 down the rail, Ctrl+, for Settings. -->
|
||||
<!-- Sections by keyboard, as the rail tooltips list them (BRIEF §12.1): Ctrl+1…7 down the rail (Videos at Ctrl+4, owner review 1, R9), Ctrl+, for Settings. -->
|
||||
<ui:ChronosWindow.InputBindings>
|
||||
<KeyBinding Key="D1" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Library}" />
|
||||
<KeyBinding Key="D2" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Import}" />
|
||||
<KeyBinding Key="D3" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Edit}" />
|
||||
<KeyBinding Key="D4" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Archive}" />
|
||||
<KeyBinding Key="D5" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Jobs}" />
|
||||
<KeyBinding Key="D6" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Server}" />
|
||||
<KeyBinding Key="D4" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Videos}" />
|
||||
<KeyBinding Key="D5" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Archive}" />
|
||||
<KeyBinding Key="D6" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Jobs}" />
|
||||
<KeyBinding Key="D7" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Server}" />
|
||||
<KeyBinding Key="NumPad1" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Library}" />
|
||||
<KeyBinding Key="NumPad2" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Import}" />
|
||||
<KeyBinding Key="NumPad3" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Edit}" />
|
||||
<KeyBinding Key="NumPad4" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Archive}" />
|
||||
<KeyBinding Key="NumPad5" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Jobs}" />
|
||||
<KeyBinding Key="NumPad6" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Server}" />
|
||||
<KeyBinding Key="NumPad4" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Videos}" />
|
||||
<KeyBinding Key="NumPad5" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Archive}" />
|
||||
<KeyBinding Key="NumPad6" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Jobs}" />
|
||||
<KeyBinding Key="NumPad7" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Server}" />
|
||||
<KeyBinding Key="OemComma" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Settings}" />
|
||||
<!-- The rail's names or its icons alone (owner review 1). -->
|
||||
<KeyBinding Key="B" Modifiers="Control" Command="{Binding ToggleRailCommand}" />
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
<DataTemplate DataType="{x:Type s:LibraryViewModel}"><s:LibraryView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ImportViewModel}"><s:ImportView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:SequenceViewModel}"><s:SequenceView /></DataTemplate>
|
||||
<!-- The videos library (owner review 1, R9). -->
|
||||
<DataTemplate DataType="{x:Type s:VideosViewModel}"><s:VideosView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ArchiveViewModel}"><s:ArchiveView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:JobsViewModel}"><s:JobsView /></DataTemplate>
|
||||
<!-- Jobs › Scheduled, the second tab of Jobs (owner review 2, R10). -->
|
||||
|
||||
@@ -10,6 +10,9 @@ public enum SectionKey
|
||||
|
||||
/// <summary>One sequence analysed, edited and rendered step by step (owner review 1, R7; formerly Sequence).</summary>
|
||||
Edit,
|
||||
|
||||
/// <summary>Every render of this PC, of the server and of the workspace in one list (owner review 1, R9; Ctrl+4).</summary>
|
||||
Videos,
|
||||
Archive,
|
||||
Jobs,
|
||||
Server,
|
||||
|
||||
@@ -44,12 +44,14 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
Sequence = new SequenceViewModel(this);
|
||||
// The workspace's clean-up never takes the project open in Edit (phase 5c).
|
||||
services.Workspace.OpenProject = () => Sequence.OpenProjectId;
|
||||
Videos = new VideosViewModel(this);
|
||||
Archive = new ArchiveViewModel(this);
|
||||
Jobs = new JobsViewModel(this);
|
||||
Server = new ServerViewModel(this);
|
||||
Settings = new SettingsViewModel(this);
|
||||
About = new AboutViewModel(this);
|
||||
TopSections = [Library, Import, Sequence, Archive, Jobs, Server];
|
||||
// Videos after Edit (owner review 1, R9, decision 20): Ctrl+4, then Archive, Jobs and Server at Ctrl+5…7.
|
||||
TopSections = [Library, Import, Sequence, Videos, Archive, Jobs, Server];
|
||||
// About is the last page of Settings (owner review 2, R5): Settings alone docks at the bottom of the rail.
|
||||
BottomSections = [Settings];
|
||||
foreach (var section in AllSections) section.InCollapsedRail = _isRailCollapsed;
|
||||
@@ -57,7 +59,7 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
Library.IsSelected = true;
|
||||
Library.PropertyChanged += OnCurrentChanged;
|
||||
|
||||
// The rail and its shortcuts (Ctrl+1…6, Ctrl+,) navigate only while no first-run dialog covers the shell.
|
||||
// The rail and its shortcuts (Ctrl+1…7, Ctrl+,) navigate only while no first-run dialog covers the shell.
|
||||
NavigateCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is SectionViewModel s) Navigate(s.Key);
|
||||
@@ -75,6 +77,10 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
public LibraryViewModel Library { get; }
|
||||
public ImportViewModel Import { get; }
|
||||
public SequenceViewModel Sequence { get; }
|
||||
|
||||
/// <summary>The videos library (owner review 1, R9).</summary>
|
||||
public VideosViewModel Videos { get; }
|
||||
|
||||
public ArchiveViewModel Archive { get; }
|
||||
public JobsViewModel Jobs { get; }
|
||||
public ServerViewModel Server { get; }
|
||||
@@ -194,6 +200,16 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
/// </summary>
|
||||
internal void KeepSequence(Guid? sequenceId) => CurrentSequenceId = sequenceId;
|
||||
|
||||
/// <summary>
|
||||
/// Opens Videos, narrowed to the renders of <paramref name="sequenceId"/> (the Export footer's "Videos (n)" and the Render
|
||||
/// menu's "Videos"), or to every render with null; <paramref name="title"/> names the sequence in its filter chip.
|
||||
/// </summary>
|
||||
public void OpenVideos(Guid? sequenceId = null, string? title = null)
|
||||
{
|
||||
Videos.ShowSequence(sequenceId, title);
|
||||
Navigate(SectionKey.Videos);
|
||||
}
|
||||
|
||||
/// <summary>Closes the first-run overlay for good.</summary>
|
||||
public void CompleteWelcome()
|
||||
{
|
||||
@@ -362,6 +378,7 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
Jobs.Dispose();
|
||||
Library.Dispose();
|
||||
Import.Dispose();
|
||||
Videos.Dispose();
|
||||
Archive.Dispose();
|
||||
Server.Dispose();
|
||||
Settings.Dispose();
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<UserControl x:Class="Chronos.App.Videos.VideoPlayerPane"
|
||||
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:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui">
|
||||
<!--
|
||||
The player pane of the Videos section (decision 21): the render played in-process (Windows Media Foundation through
|
||||
MediaElement), a still, GIF or APNG shown as an image, and "Cannot play here" when Windows cannot decode the file, with
|
||||
Show in folder still offered. Pictures stay left to right in a right-to-left window.
|
||||
-->
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="14">
|
||||
<DockPanel>
|
||||
<DockPanel DockPanel.Dock="Top">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.IconSubtle}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}" Command="{Binding CloseCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Videos.ClosePlayer}" AutomationProperties.Name="{l:Loc Videos.Player.Close}" VerticalAlignment="Top" />
|
||||
<StackPanel>
|
||||
<TextBlock Text="{Binding Title}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" TextTrimming="None" />
|
||||
<TextBlock Text="{Binding DetailsText}" Style="{StaticResource Text.Secondary}" Margin="0,4,0,0" FlowDirection="LeftToRight" HorizontalAlignment="Left"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" Margin="0,12,0,0">
|
||||
<Button Content="{l:Loc Videos.Play}" ui:ButtonIcon.Glyph="{StaticResource Icon.Play}" Click="OnReplay" ToolTip="{l:Loc Tooltips.Videos.Play}"
|
||||
Visibility="{Binding IsVideo, Converter={StaticResource BoolToVisibility}}" Margin="0,0,8,0" />
|
||||
<Button Content="{l:Loc Videos.ShowInFolder}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Command="{Binding ShowInFolderCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Videos.ShowInFolder}" ToolTipService.ShowOnDisabled="True" />
|
||||
</StackPanel>
|
||||
<Border Margin="0,12,0,0" CornerRadius="6" Background="{DynamicResource Brush.Preview}" MinHeight="180" ClipToBounds="True" FlowDirection="LeftToRight">
|
||||
<Grid>
|
||||
<MediaElement x:Name="Media" Source="{Binding Source}" LoadedBehavior="Manual" UnloadedBehavior="Close" Stretch="Uniform" MediaFailed="OnMediaFailed"
|
||||
MediaOpened="OnMediaOpened" Visibility="{Binding IsVideo, Converter={StaticResource BoolToVisibility}}" Loaded="OnMediaLoaded"
|
||||
AutomationProperties.Name="{Binding Title}" />
|
||||
<Image Source="{Binding Image}" Stretch="Uniform" Visibility="{Binding IsImage, Converter={StaticResource BoolToVisibility}}"
|
||||
AutomationProperties.Name="{Binding Title}" />
|
||||
<ui:EmptyState Message="{Binding CannotPlayText}" ToolTip="{Binding CannotPlayToolTip}" Visibility="{Binding CannotPlay, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Chronos.App.Videos;
|
||||
|
||||
/// <summary>The player pane: plays the render in-process and falls back to "Cannot play here" when Windows cannot decode it.</summary>
|
||||
public partial class VideoPlayerPane : UserControl
|
||||
{
|
||||
public VideoPlayerPane()
|
||||
{
|
||||
InitializeComponent();
|
||||
DataContextChanged += (_, _) => Start();
|
||||
}
|
||||
|
||||
private VideoPlayerViewModel? Model => DataContext as VideoPlayerViewModel;
|
||||
|
||||
private void OnMediaLoaded(object sender, RoutedEventArgs e) => Start();
|
||||
|
||||
/// <summary>A new render plays from its start.</summary>
|
||||
private void Start()
|
||||
{
|
||||
if (!Media.IsLoaded) return;
|
||||
if (Model is { IsVideo: true })
|
||||
{
|
||||
Media.Position = TimeSpan.Zero;
|
||||
Media.Play();
|
||||
}
|
||||
else
|
||||
{
|
||||
Media.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnReplay(object sender, RoutedEventArgs e) => Start();
|
||||
|
||||
private void OnMediaOpened(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// A file that opens without a video stream (audio alone, a codec Windows lacks) shows nothing: said as such.
|
||||
if (!Media.HasVideo) Model?.MediaFailed(null);
|
||||
}
|
||||
|
||||
private void OnMediaFailed(object? sender, ExceptionRoutedEventArgs e) => Model?.MediaFailed(e.ErrorException);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Videos;
|
||||
|
||||
/// <summary>What the player pane shows (decision 21).</summary>
|
||||
public enum VideoPlayerMode
|
||||
{
|
||||
/// <summary>A video file, played in-process by Windows Media Foundation (WPF <c>MediaElement</c>).</summary>
|
||||
Video,
|
||||
|
||||
/// <summary>A still, a GIF or an APNG, shown as an image.</summary>
|
||||
Image,
|
||||
|
||||
/// <summary>Windows cannot decode the file here (or it is not on this PC): "Cannot play here", Show in folder stays.</summary>
|
||||
CannotPlay,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The right-hand player pane of the Videos section (decision 21): one render played in-process, never handed to another
|
||||
/// program (BRIEF §8.6). A file Windows cannot decode says so, and Show in folder stays offered.
|
||||
/// </summary>
|
||||
public sealed class VideoPlayerViewModel : ObservableObject
|
||||
{
|
||||
/// <summary>The longest edge an image is decoded at for the pane.</summary>
|
||||
public const int ImageEdge = 1600;
|
||||
|
||||
private VideoPlayerMode _mode;
|
||||
private ImageSource? _image;
|
||||
|
||||
public VideoPlayerViewModel(VideoEntry entry, ICommand close, ICommand showInFolder)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
Entry = entry;
|
||||
CloseCommand = close;
|
||||
ShowInFolderCommand = showInFolder;
|
||||
_mode = ModeOf(entry);
|
||||
if (_mode == VideoPlayerMode.Video) Source = new Uri(entry.LocalPath!, UriKind.Absolute);
|
||||
}
|
||||
|
||||
public VideoEntry Entry { get; }
|
||||
|
||||
public string Title => Entry.Title;
|
||||
|
||||
public string DetailsText => VideoText.Details(Entry);
|
||||
|
||||
public VideoPlayerMode Mode
|
||||
{
|
||||
get => _mode;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _mode, value)) return;
|
||||
OnPropertyChanged(nameof(IsVideo));
|
||||
OnPropertyChanged(nameof(IsImage));
|
||||
OnPropertyChanged(nameof(CannotPlay));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsVideo => _mode == VideoPlayerMode.Video;
|
||||
public bool IsImage => _mode == VideoPlayerMode.Image;
|
||||
public bool CannotPlay => _mode == VideoPlayerMode.CannotPlay;
|
||||
|
||||
/// <summary>The video file the <c>MediaElement</c> plays; null for an image or a file that cannot play.</summary>
|
||||
public Uri? Source { get; }
|
||||
|
||||
/// <summary>The still (or the first frame of a GIF or APNG), decoded at <see cref="ImageEdge"/> once asked for.</summary>
|
||||
public ImageSource? Image
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_image is null && _mode == VideoPlayerMode.Image) _image = LoadImage();
|
||||
return _image;
|
||||
}
|
||||
}
|
||||
|
||||
public string CannotPlayText => Loc.L("Videos.Player.CannotPlay");
|
||||
|
||||
public string CannotPlayToolTip => Loc.L("Tooltips.Videos.CannotPlay");
|
||||
|
||||
public ICommand CloseCommand { get; }
|
||||
|
||||
public ICommand ShowInFolderCommand { get; }
|
||||
|
||||
/// <summary>Show in folder applies: the file is on this PC.</summary>
|
||||
public bool CanShowInFolder => Entry.HasLocalFile;
|
||||
|
||||
/// <summary>The <c>MediaElement</c> could not open or decode the file (a codec Windows lacks, HEVC without its extension).</summary>
|
||||
public void MediaFailed(Exception? error)
|
||||
{
|
||||
Log.Info("videos", $"{Entry.FileName} cannot play here: {error?.Message}");
|
||||
Mode = VideoPlayerMode.CannotPlay;
|
||||
}
|
||||
|
||||
/// <summary>How <paramref name="entry"/> plays: as a video or an image when its file is here and of a kind the pane shows, else not.</summary>
|
||||
public static VideoPlayerMode ModeOf(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
if (!entry.HasLocalFile || entry.Kind == RenderKind.Sequence || !File.Exists(entry.LocalPath)) return VideoPlayerMode.CannotPlay;
|
||||
if (entry.Kind == RenderKind.Still || VideoSources.ShowsAsImage(entry.LocalPath)) return VideoPlayerMode.Image;
|
||||
return VideoSources.PlaysAsVideo(entry.LocalPath) ? VideoPlayerMode.Video : VideoPlayerMode.CannotPlay;
|
||||
}
|
||||
|
||||
private BitmapSource? LoadImage()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var stream = File.OpenRead(Entry.LocalPath!);
|
||||
var image = new BitmapImage();
|
||||
image.BeginInit();
|
||||
image.CacheOption = BitmapCacheOption.OnLoad;
|
||||
image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
|
||||
if (Entry.Width >= Entry.Height) image.DecodePixelWidth = Math.Min(ImageEdge, Math.Max(1, Entry.Width));
|
||||
else image.DecodePixelHeight = Math.Min(ImageEdge, Math.Max(1, Entry.Height));
|
||||
image.StreamSource = stream;
|
||||
image.EndInit();
|
||||
image.Freeze();
|
||||
return image;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or InvalidOperationException or ArgumentException)
|
||||
{
|
||||
Log.Info("videos", $"{Entry.FileName} cannot be shown here: {ex.Message}");
|
||||
Mode = VideoPlayerMode.CannotPlay;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
using System.Globalization;
|
||||
using System.Windows.Media;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Videos;
|
||||
|
||||
/// <summary>The words of the Videos section: kinds, states, details and the errors of the videos library.</summary>
|
||||
public static class VideoText
|
||||
{
|
||||
/// <summary>"Videos", "Stills", "Image sequences"; a newer kind as it is.</summary>
|
||||
public static string Kind(string kind) => kind switch
|
||||
{
|
||||
RenderKind.Video => Loc.L("Videos.Kind.Video"),
|
||||
RenderKind.Still => Loc.L("Videos.Kind.Still"),
|
||||
RenderKind.Sequence => Loc.L("Videos.Kind.Sequence"),
|
||||
_ => kind,
|
||||
};
|
||||
|
||||
/// <summary>"0:42" for a video; empty for a still, which has no duration.</summary>
|
||||
public static string Duration(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
return entry.Kind == RenderKind.Still || entry.DurationSeconds <= 0 ? string.Empty : Formatting.Elapsed(TimeSpan.FromSeconds(entry.DurationSeconds));
|
||||
}
|
||||
|
||||
/// <summary>"3840×2160 · HEVC" (the size and codec, left to right in every language).</summary>
|
||||
public static string Format(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
var size = entry.Width > 0 && entry.Height > 0
|
||||
? entry.Width.ToString(CultureInfo.InvariantCulture) + "×" + entry.Height.ToString(CultureInfo.InvariantCulture)
|
||||
: string.Empty;
|
||||
var codec = VideoSources.CodecText(entry.Codec);
|
||||
return size.Length == 0 ? codec : codec.Length == 0 ? size : size + Loc.Separator + codec;
|
||||
}
|
||||
|
||||
/// <summary>"3840×2160 · HEVC · 0:42 · 1.2 GB" (<c>Videos.Details</c>).</summary>
|
||||
public static string Details(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
return Loc.L("Videos.Details", entry.Width.ToString(CultureInfo.InvariantCulture), entry.Height.ToString(CultureInfo.InvariantCulture),
|
||||
VideoSources.CodecText(entry.Codec), Duration(entry), Formatting.Bytes(entry.Bytes));
|
||||
}
|
||||
|
||||
/// <summary>The state chips of a render: where its file is, whether it was copied, and a missing file.</summary>
|
||||
public static IReadOnlyList<CardStatus> States(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
var states = new List<CardStatus>();
|
||||
if (entry.Missing) states.Add(new CardStatus(StatusKind.Warning, Loc.L("Videos.State.Missing"), Loc.L("Tooltips.Videos.Missing")));
|
||||
if (entry.IsUnsent) states.Add(new CardStatus(StatusKind.Queued, Loc.L("Videos.State.NotSent"), Loc.L("Tooltips.Videos.NotSent")));
|
||||
else if (entry.IsLocal && entry.IsOnServer) states.Add(new CardStatus(StatusKind.Synced, Loc.L("Videos.State.HereAndServer"), Loc.L("Tooltips.Videos.HereAndServer")));
|
||||
else if (entry.IsLocal) states.Add(new CardStatus(StatusKind.Done, Loc.L("Videos.State.Here"), Loc.L("Tooltips.Videos.Here")));
|
||||
else if (entry.IsOnServer) states.Add(new CardStatus(StatusKind.Remote, Loc.L("Videos.State.OnServer"), Loc.L("Tooltips.Videos.OnServer")));
|
||||
if (entry.Copies.Count > 0)
|
||||
{
|
||||
states.Add(new CardStatus(StatusKind.Rendered, Loc.L("Videos.State.Copied"),
|
||||
Loc.L("Tooltips.Videos.Copied", string.Join(Environment.NewLine, entry.Copies.Select(Formatting.LeftToRight)))));
|
||||
}
|
||||
return states;
|
||||
}
|
||||
|
||||
/// <summary>The sentence of a videos library error (<see cref="VideoErrors"/>); <paramref name="name"/> is the file or sequence it is about.</summary>
|
||||
public static string Error(VideoLibraryException ex, string? name = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ex);
|
||||
return ex.Code switch
|
||||
{
|
||||
VideoErrors.FolderUnset => Loc.L("Errors.Videos.FolderUnset"),
|
||||
VideoErrors.FolderInvalid => Loc.L("Errors.Videos.FolderInsideArchive"),
|
||||
VideoErrors.PlanChanged => Loc.L("Errors.Videos.Fingerprint"),
|
||||
VideoErrors.HashMismatch => Loc.L("Errors.Videos.TrashMismatch"),
|
||||
VideoErrors.NoSpace => Loc.L("Errors.Videos.NoSpace", name ?? string.Empty),
|
||||
VideoErrors.SequenceGone => Loc.L("Errors.Videos.SequenceGone", name ?? string.Empty),
|
||||
VideoErrors.Busy => Loc.L("Errors.Videos.Busy", name ?? string.Empty),
|
||||
_ => ex.Message,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Why a copy into <paramref name="problem"/>'s folder is refused (a tooltip), from <see cref="VideosFolders.Problem"/>.</summary>
|
||||
public static string FolderReason(string problem) =>
|
||||
problem == VideoErrors.FolderUnset ? Loc.L("Tooltips.Videos.FolderUnset") : Loc.L("Errors.Videos.FolderInsideArchive");
|
||||
|
||||
/// <summary>"In use by a job", "Not found".</summary>
|
||||
public static string BlockReason(string reason) =>
|
||||
reason == VideoBlockReasons.Busy ? Loc.L("Videos.Blocked.Busy") : Loc.L("Videos.Blocked.NotFound");
|
||||
}
|
||||
|
||||
/// <summary>One render of the Videos section, as a card of the grid or a row of the list.</summary>
|
||||
public sealed class VideoRowViewModel(VideoEntry entry) : ObservableObject
|
||||
{
|
||||
private bool _isSelected;
|
||||
private ImageSource? _poster;
|
||||
private bool _posterRequested;
|
||||
|
||||
public VideoEntry Entry { get; } = entry;
|
||||
|
||||
public string Title => Entry.Title;
|
||||
|
||||
/// <summary>The preset name (and the project's, when a project was rendered).</summary>
|
||||
public string Subtitle => Entry.ProjectName is { Length: > 0 } project ? Entry.PresetName + Loc.Separator + project : Entry.PresetName;
|
||||
|
||||
public string DetailsText => VideoText.Details(Entry);
|
||||
public string FormatText => VideoText.Format(Entry);
|
||||
public string DurationText => VideoText.Duration(Entry);
|
||||
public string SizeText => Formatting.Bytes(Entry.Bytes);
|
||||
public string DateText => Formatting.Date(Entry.Created) + " " + Formatting.TimeOfDay(Entry.Created);
|
||||
public string KindText => VideoText.Kind(Entry.Kind);
|
||||
public IReadOnlyList<CardStatus> States { get; } = VideoText.States(entry);
|
||||
|
||||
/// <summary>The card's and the row's tooltip: what it is, then how to select it.</summary>
|
||||
public string ToolTip => Entry.IsUnsent ? Loc.L("Tooltips.Videos.WorkspaceRow") : Loc.L("Tooltips.Videos.Select");
|
||||
|
||||
/// <summary>The file name, left to right in every language.</summary>
|
||||
public string FileNameText => Formatting.LeftToRight(Entry.FileName);
|
||||
|
||||
public bool IsSelected
|
||||
{
|
||||
get => _isSelected;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isSelected, value)) SelectionChanged?.Invoke(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The sequence's cover, or the still itself; null until loaded (<see cref="RequestPoster"/>).</summary>
|
||||
public ImageSource? Poster
|
||||
{
|
||||
get => _poster;
|
||||
internal set => Set(ref _poster, value);
|
||||
}
|
||||
|
||||
/// <summary>The card came on screen: its poster is loaded once by <see cref="PosterRequested"/>.</summary>
|
||||
public void RequestPoster()
|
||||
{
|
||||
if (_posterRequested || _poster is not null) return;
|
||||
_posterRequested = true;
|
||||
PosterRequested?.Invoke(this);
|
||||
}
|
||||
|
||||
internal event Action<VideoRowViewModel>? SelectionChanged;
|
||||
|
||||
internal event Action<VideoRowViewModel>? PosterRequested;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of a delete of videos (decision 17) in the words of its confirmation: what goes into the trash (and how
|
||||
/// many bytes), the renders whose file is missing (only their entry goes), the renders left where they are and why, and
|
||||
/// that copies in the videos folder stay. This PC's renders and the server's are planned apart and confirmed together.
|
||||
/// </summary>
|
||||
public sealed record VideoDeletePlans(VideoDeletePlan? Local, VideoDeletePlanDto? Server)
|
||||
{
|
||||
/// <summary>The renders that go.</summary>
|
||||
public int Count => (Local?.Items.Count ?? 0) + (Server?.Items.Count ?? 0);
|
||||
|
||||
/// <summary>The bytes that move into the trash.</summary>
|
||||
public long Bytes => (Local?.Bytes ?? 0) + (Server?.Bytes ?? 0);
|
||||
|
||||
/// <summary>The renders left where they are.</summary>
|
||||
public int Blocked => (Local?.Blocked.Count ?? 0) + (Server?.Blocked.Count ?? 0);
|
||||
|
||||
/// <summary>The renders whose file is missing: only their entry goes.</summary>
|
||||
public int Missing => (Local?.Items.Count(i => i.Missing) ?? 0) + (Server?.Items.Count(i => i.Missing) ?? 0);
|
||||
|
||||
/// <summary>The lines of what goes, then of what stays and why (<see cref="DeletePlans.ListedLines"/> each, the rest counted).</summary>
|
||||
public IReadOnlyList<string> Lines()
|
||||
{
|
||||
var goes = (Local?.Items.Select(i => (i.SequenceTitle, i.FileName, i.Render.Bytes, i.Missing)) ?? [])
|
||||
.Concat(Server?.Items.Select(i => (i.SequenceTitle, FileName: i.FileName ?? string.Empty, i.Bytes, i.Missing)) ?? []).ToList();
|
||||
var lines = new List<string>();
|
||||
foreach (var (title, file, bytes, missing) in goes.Take(DeletePlans.ListedLines))
|
||||
{
|
||||
lines.Add(Loc.L("Archive.Delete.Line", title, Formatting.LeftToRight(file),
|
||||
missing ? Loc.L("Videos.State.Missing") : Formatting.Bytes(bytes)));
|
||||
}
|
||||
if (goes.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", goes.Count - DeletePlans.ListedLines));
|
||||
var stays = (Local?.Blocked.Select(b => (b.Video?.SequenceTitle ?? b.RenderId.ToString("D"), b.Reason)) ?? [])
|
||||
.Concat(Server?.Blocked.Select(b => (b.Id.ToString("D"), b.Reason)) ?? []).ToList();
|
||||
if (stays.Count > 0) lines.Add(Loc.L("Videos.Delete.Blocked", Formatting.Count(stays.Count)));
|
||||
foreach (var (name, reason) in stays.Take(DeletePlans.ListedLines)) lines.Add(name + Loc.Separator + VideoText.BlockReason(reason));
|
||||
if (stays.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", stays.Count - DeletePlans.ListedLines));
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <summary>The confirmation of moving the planned renders into the trash; null when nothing would go.</summary>
|
||||
public ConfirmRequest? Request()
|
||||
{
|
||||
if (Count == 0) return null;
|
||||
var message = Loc.L("Videos.Delete.Summary", Formatting.Count(Count), Formatting.Bytes(Bytes)) + Environment.NewLine + Loc.L("Videos.Delete.CopiesStay");
|
||||
if (Missing > 0) message += Environment.NewLine + Loc.L("Videos.Delete.Missing");
|
||||
return new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Videos.Delete.Title"),
|
||||
Message = message,
|
||||
Detail = string.Join(Environment.NewLine, Lines()),
|
||||
IsDetailMonospaced = false,
|
||||
DetailToolTip = Loc.L("Tooltips.Videos.Delete"),
|
||||
SafeText = Loc.L("Archive.Delete.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
|
||||
ActionText = Loc.L("Videos.Delete.Confirm"),
|
||||
ActionToolTip = Loc.L("Tooltips.Videos.DeleteConfirm"),
|
||||
IsDestructive = true,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Videos;
|
||||
|
||||
/// <summary>Which renders the Videos section lists (its Source filter, owner review 1, R9).</summary>
|
||||
public enum VideoSourceFilter
|
||||
{
|
||||
All,
|
||||
|
||||
/// <summary>Renders whose file is on this PC: the archive's and the workspace's not sent yet.</summary>
|
||||
Local,
|
||||
|
||||
/// <summary>Renders the signed-in server holds.</summary>
|
||||
Server,
|
||||
|
||||
/// <summary>Renders of workspace projects not at their home yet.</summary>
|
||||
NotSent,
|
||||
}
|
||||
|
||||
/// <summary>How the signed-in server's videos reach the Videos section.</summary>
|
||||
public enum VideoServerState
|
||||
{
|
||||
/// <summary>Listed with this PC's.</summary>
|
||||
Available,
|
||||
|
||||
/// <summary>Not signed in to a server: this PC's videos alone.</summary>
|
||||
SignedOut,
|
||||
|
||||
/// <summary>The server's Chronos has no videos library (no <see cref="ServerCapabilities.Videos"/>): this PC's videos alone.</summary>
|
||||
Old,
|
||||
|
||||
/// <summary>The server did not answer: this PC's videos alone.</summary>
|
||||
Unreachable,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One render of the Videos section (decision 20): the archive's, the signed-in server's and the workspace's renders merged
|
||||
/// by render id, with where its file is. WPF-free.
|
||||
/// </summary>
|
||||
public sealed record VideoEntry
|
||||
{
|
||||
public required Guid Id { get; init; }
|
||||
public required Guid SequenceId { get; init; }
|
||||
|
||||
/// <summary>The sequence's display title.</summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
public required string PresetName { get; init; }
|
||||
public string? Codec { get; init; }
|
||||
public int Width { get; init; }
|
||||
public int Height { get; init; }
|
||||
public double Fps { get; init; }
|
||||
public double DurationSeconds { get; init; }
|
||||
public long Bytes { get; init; }
|
||||
public DateTimeOffset Created { get; init; }
|
||||
|
||||
/// <summary><see cref="RenderKind.Video"/>, <see cref="RenderKind.Still"/>, <see cref="RenderKind.Sequence"/> or a newer kind as it is.</summary>
|
||||
public required string Kind { get; init; }
|
||||
|
||||
/// <summary>The file (or folder) name.</summary>
|
||||
public required string FileName { get; init; }
|
||||
|
||||
/// <summary>The file (or folder) on this PC; null for a render the server alone holds.</summary>
|
||||
public string? LocalPath { get; init; }
|
||||
|
||||
/// <summary>The render is in this PC's index (its archive).</summary>
|
||||
public bool IsLocal { get; init; }
|
||||
|
||||
/// <summary>The signed-in server holds the render.</summary>
|
||||
public bool IsOnServer { get; init; }
|
||||
|
||||
/// <summary>A workspace render not at its home yet: read-only here (Play, Show in folder, Send).</summary>
|
||||
public bool IsUnsent { get; init; }
|
||||
|
||||
/// <summary>The file is not where it was recorded (here, or on the server for a render the server alone holds).</summary>
|
||||
public bool Missing { get; init; }
|
||||
|
||||
/// <summary>The workspace project of an unsent render; null otherwise.</summary>
|
||||
public Guid? WorkspaceProjectId { get; init; }
|
||||
|
||||
/// <summary>The workspace project's home is a server.</summary>
|
||||
public bool WorkspaceServerHome { get; init; }
|
||||
|
||||
/// <summary>The project rendered; null for a render of the sequence's settings.</summary>
|
||||
public string? ProjectName { get; init; }
|
||||
|
||||
/// <summary>The paths of its verified copies in videos folders (of this PC and of the server).</summary>
|
||||
public IReadOnlyList<string> Copies { get; init; } = [];
|
||||
|
||||
/// <summary>The render's file is on this PC.</summary>
|
||||
public bool HasLocalFile => LocalPath is not null && !Missing;
|
||||
|
||||
/// <summary>The year the render was made (UTC, as the server filters it).</summary>
|
||||
public int Year => Created.UtcDateTime.Year;
|
||||
}
|
||||
|
||||
/// <summary>The filters and the order of the Videos section; every member optional, combined with "and".</summary>
|
||||
public sealed record VideoFilter
|
||||
{
|
||||
public static VideoFilter None { get; } = new();
|
||||
|
||||
/// <summary>Text in the title, the preset name or the file name (any case).</summary>
|
||||
public string? Text { get; init; }
|
||||
|
||||
/// <summary>One of <see cref="RenderKind"/>; null for every kind.</summary>
|
||||
public string? Kind { get; init; }
|
||||
|
||||
/// <summary>A codec as recorded; null for every codec.</summary>
|
||||
public string? Codec { get; init; }
|
||||
|
||||
public int? Year { get; init; }
|
||||
|
||||
public VideoSourceFilter Source { get; init; }
|
||||
|
||||
/// <summary>The renders of one sequence (the Export footer's and the Render menu's "Videos").</summary>
|
||||
public Guid? SequenceId { get; init; }
|
||||
|
||||
/// <summary>One of <see cref="VideoSorts"/>; null for newest first.</summary>
|
||||
public string? Sort { get; init; }
|
||||
|
||||
/// <summary>Anything narrows the list (the order alone does not).</summary>
|
||||
public bool IsFiltered => !string.IsNullOrWhiteSpace(Text) || Kind is not null || Codec is not null || Year is not null || Source != VideoSourceFilter.All
|
||||
|| SequenceId is not null;
|
||||
|
||||
public bool Matches(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
if (SequenceId is { } sequence && entry.SequenceId != sequence) return false;
|
||||
if (Kind is { } kind && !string.Equals(entry.Kind, kind, StringComparison.Ordinal)) return false;
|
||||
if (Codec is { } codec && !string.Equals(entry.Codec, codec, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (Year is { } year && entry.Year != year) return false;
|
||||
if (Source switch
|
||||
{
|
||||
VideoSourceFilter.Local => !entry.IsLocal && !entry.IsUnsent,
|
||||
VideoSourceFilter.Server => !entry.IsOnServer,
|
||||
VideoSourceFilter.NotSent => !entry.IsUnsent,
|
||||
_ => false,
|
||||
})
|
||||
return false;
|
||||
if (Text?.Trim() is { Length: > 0 } text
|
||||
&& !entry.Title.Contains(text, StringComparison.CurrentCultureIgnoreCase)
|
||||
&& !entry.PresetName.Contains(text, StringComparison.CurrentCultureIgnoreCase)
|
||||
&& !entry.FileName.Contains(text, StringComparison.CurrentCultureIgnoreCase))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The entries that match, in the chosen order (ties newest first, then by id, so the order is stable).</summary>
|
||||
public IReadOnlyList<VideoEntry> Apply(IEnumerable<VideoEntry> entries)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entries);
|
||||
var matching = entries.Where(Matches);
|
||||
IOrderedEnumerable<VideoEntry> ordered = Sort switch
|
||||
{
|
||||
VideoSorts.Oldest => matching.OrderBy(e => e.Created),
|
||||
VideoSorts.Largest => matching.OrderByDescending(e => e.Bytes).ThenByDescending(e => e.Created),
|
||||
VideoSorts.Title => matching.OrderBy(e => e.Title, StringComparer.CurrentCultureIgnoreCase).ThenByDescending(e => e.Created),
|
||||
_ => matching.OrderByDescending(e => e.Created),
|
||||
};
|
||||
return [.. ordered.ThenBy(e => e.Id)];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The signed-in server's videos library (<c>/api/v1/videos</c>) as the Videos section uses it; one connection, disposed
|
||||
/// after use. Tests substitute a fake server.
|
||||
/// </summary>
|
||||
public interface IRemoteVideos : IDisposable
|
||||
{
|
||||
/// <summary>One page of the server's videos.</summary>
|
||||
Task<VideoPageDto> ListAsync(VideoQueryDto query, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>The dry run of deleting <paramref name="ids"/> into the server's trash.</summary>
|
||||
Task<VideoDeletePlanDto> PlanDeleteAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>The delete as planned; a changed plan is a 409 <c>plan_changed</c>.</summary>
|
||||
Task<VideoDeletePlanDto> DeleteAsync(IReadOnlyList<Guid> ids, string fingerprint, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Queues the copy of <paramref name="ids"/> into the server's videos folder.</summary>
|
||||
Task<VideoCopyResultDto> CopyAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary><see cref="IRemoteVideos"/> over a signed-in <see cref="ChronosClient"/>, which it owns.</summary>
|
||||
public sealed class ChronosRemoteVideos(ChronosClient client) : IRemoteVideos
|
||||
{
|
||||
public Task<VideoPageDto> ListAsync(VideoQueryDto query, CancellationToken cancellationToken = default) => client.ListVideosAsync(query, cancellationToken);
|
||||
|
||||
public Task<VideoDeletePlanDto> PlanDeleteAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default) =>
|
||||
client.PlanDeleteVideosAsync(ids, cancellationToken);
|
||||
|
||||
public Task<VideoDeletePlanDto> DeleteAsync(IReadOnlyList<Guid> ids, string fingerprint, CancellationToken cancellationToken = default) =>
|
||||
client.DeleteVideosAsync(ids, fingerprint, cancellationToken);
|
||||
|
||||
public Task<VideoCopyResultDto> CopyAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default) => client.CopyVideosAsync(ids, cancellationToken);
|
||||
|
||||
public void Dispose() => client.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The signed-in server as the Videos section sees it: whether its videos can be listed, a connection when they can, and
|
||||
/// what the account may do there.
|
||||
/// </summary>
|
||||
/// <param name="Connect">A new connection to the server; null unless <paramref name="State"/> is <see cref="VideoServerState.Available"/>.</param>
|
||||
public sealed record VideoServer(VideoServerState State, Func<IRemoteVideos>? Connect = null, bool CanEdit = false, bool CanDelete = false)
|
||||
{
|
||||
public static VideoServer SignedOut { get; } = new(VideoServerState.SignedOut);
|
||||
|
||||
/// <summary>The server of <paramref name="info"/> for an account of <paramref name="permissions"/>: <see cref="VideoServerState.Old"/> without the capability.</summary>
|
||||
public static VideoServer Of(ServerInfo? info, long permissions, Func<IRemoteVideos> connect)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(connect);
|
||||
if (info is null) return SignedOut;
|
||||
if (!info.Capabilities.Contains(ServerCapabilities.Videos)) return new VideoServer(VideoServerState.Old);
|
||||
return new VideoServer(VideoServerState.Available, connect, (permissions & (long)Permissions.Edit) != 0, (permissions & (long)Permissions.Delete) != 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reading and merging the three places renders are (decision 20): the archive, the signed-in server, the workspace.</summary>
|
||||
public static class VideoSources
|
||||
{
|
||||
/// <summary>Pages read from one place at most (500 videos each).</summary>
|
||||
public const int MaxPages = 40;
|
||||
|
||||
/// <summary>Extensions the player pane plays with Windows Media Foundation (decision 21).</summary>
|
||||
private static readonly string[] VideoExtensions = [".mp4", ".m4v", ".mov", ".wmv", ".avi", ".mkv", ".webm"];
|
||||
|
||||
/// <summary>Extensions the player pane shows as an image (stills, GIF, APNG).</summary>
|
||||
private static readonly string[] ImageExtensions = [".png", ".apng", ".jpg", ".jpeg", ".tif", ".tiff", ".gif", ".bmp"];
|
||||
|
||||
/// <summary>A render of this PC's index.</summary>
|
||||
public static VideoEntry FromLocal(VideoItem item)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
var render = item.Render;
|
||||
return new VideoEntry
|
||||
{
|
||||
Id = render.Id,
|
||||
SequenceId = render.SequenceId,
|
||||
Title = item.SequenceTitle,
|
||||
PresetName = render.PresetName,
|
||||
Codec = render.Codec,
|
||||
Width = render.Width,
|
||||
Height = render.Height,
|
||||
Fps = render.Fps,
|
||||
DurationSeconds = render.DurationSeconds,
|
||||
Bytes = render.Bytes,
|
||||
Created = render.Created,
|
||||
Kind = item.Kind,
|
||||
FileName = item.FileName,
|
||||
LocalPath = item.FullPath,
|
||||
IsLocal = true,
|
||||
Missing = item.Missing,
|
||||
ProjectName = item.ProjectName,
|
||||
Copies = [.. item.Copies.Select(c => c.Path)],
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A render of the signed-in server.</summary>
|
||||
public static VideoEntry FromServer(VideoDto video)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(video);
|
||||
return new VideoEntry
|
||||
{
|
||||
Id = video.Id,
|
||||
SequenceId = video.SequenceId,
|
||||
Title = video.SequenceTitle,
|
||||
PresetName = video.PresetName,
|
||||
Codec = video.Codec,
|
||||
Width = video.Width,
|
||||
Height = video.Height,
|
||||
Fps = video.Fps,
|
||||
DurationSeconds = video.DurationSeconds,
|
||||
Bytes = video.Bytes,
|
||||
Created = video.Created,
|
||||
Kind = video.Kind,
|
||||
FileName = video.FileName ?? video.PresetName,
|
||||
IsOnServer = true,
|
||||
Missing = video.State == VideoStates.Missing,
|
||||
ProjectName = video.ProjectName,
|
||||
Copies = [.. video.Copies.Select(c => c.Path)],
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A workspace render not sent yet (<paramref name="path"/> its file on this PC).</summary>
|
||||
public static VideoEntry FromWorkspace(WorkspaceRenderEntry render, WorkspaceEntry project, string path, bool exists)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(render);
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
return new VideoEntry
|
||||
{
|
||||
Id = render.RenderId,
|
||||
SequenceId = project.SequenceId,
|
||||
Title = project.SequenceTitle,
|
||||
PresetName = render.PresetName,
|
||||
Codec = render.Codec,
|
||||
Width = render.Width,
|
||||
Height = render.Height,
|
||||
Fps = render.Fps,
|
||||
DurationSeconds = render.DurationSeconds,
|
||||
Bytes = render.Size,
|
||||
Created = render.Rendered,
|
||||
Kind = RenderKind.Of(null, render.Codec),
|
||||
FileName = Path.GetFileName(path.TrimEnd('/', '\\')),
|
||||
LocalPath = path,
|
||||
IsUnsent = true,
|
||||
Missing = !exists,
|
||||
WorkspaceProjectId = project.ProjectId,
|
||||
WorkspaceServerHome = project.IsServerHome,
|
||||
ProjectName = project.Name,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One list, one entry per render id: this PC's renders first (their file here), marked when the server holds the same
|
||||
/// render too ("Here and on server"); the server's other renders; then the workspace's renders that neither holds yet.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<VideoEntry> Merge(IEnumerable<VideoEntry> local, IEnumerable<VideoEntry> server, IEnumerable<VideoEntry> workspace)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(local);
|
||||
ArgumentNullException.ThrowIfNull(server);
|
||||
ArgumentNullException.ThrowIfNull(workspace);
|
||||
var merged = new Dictionary<Guid, VideoEntry>();
|
||||
var order = new List<Guid>();
|
||||
foreach (var entry in local)
|
||||
{
|
||||
if (merged.TryAdd(entry.Id, entry)) order.Add(entry.Id);
|
||||
}
|
||||
foreach (var entry in server)
|
||||
{
|
||||
if (merged.TryGetValue(entry.Id, out var here))
|
||||
{
|
||||
merged[entry.Id] = here with { IsOnServer = true, Copies = [.. here.Copies.Concat(entry.Copies).Distinct(StringComparer.OrdinalIgnoreCase)] };
|
||||
}
|
||||
else if (merged.TryAdd(entry.Id, entry))
|
||||
{
|
||||
order.Add(entry.Id);
|
||||
}
|
||||
}
|
||||
// A workspace render the archive or the server holds was sent: the library's entry stands for it.
|
||||
foreach (var entry in workspace)
|
||||
{
|
||||
if (merged.TryAdd(entry.Id, entry)) order.Add(entry.Id);
|
||||
}
|
||||
return [.. order.Select(id => merged[id])];
|
||||
}
|
||||
|
||||
/// <summary>Every render of this PC's index (<see cref="MaxPages"/> pages at most); none while the library is not there.</summary>
|
||||
public static async Task<IReadOnlyList<VideoEntry>> ReadLocalAsync(IVideoLibrary? library, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (library is null || !library.IsAvailable) return [];
|
||||
var entries = new List<VideoEntry>();
|
||||
string? cursor = null;
|
||||
for (var page = 0; page < MaxPages; page++)
|
||||
{
|
||||
var read = await library.ListAsync(new VideoQuery { Cursor = cursor, Limit = VideoQuery.MaxLimit }, cancellationToken).ConfigureAwait(false);
|
||||
entries.AddRange(read.Items.Select(FromLocal));
|
||||
cursor = read.Next;
|
||||
if (cursor is null) break;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>Every render of the server (<see cref="MaxPages"/> pages at most).</summary>
|
||||
public static async Task<IReadOnlyList<VideoEntry>> ReadServerAsync(IRemoteVideos remote, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(remote);
|
||||
var entries = new List<VideoEntry>();
|
||||
string? cursor = null;
|
||||
for (var page = 0; page < MaxPages; page++)
|
||||
{
|
||||
var read = await remote.ListAsync(new VideoQueryDto(Cursor: cursor, Limit: VideoQuery.MaxLimit), cancellationToken).ConfigureAwait(false);
|
||||
entries.AddRange(read.Items.Select(FromServer));
|
||||
cursor = read.Next;
|
||||
if (cursor is null) break;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The workspace renders not at their home yet, of every project whose ledger reads (one that does not is logged and
|
||||
/// skipped: it never hides the others).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<VideoEntry> ReadWorkspace(WorkspaceStore store, IEnumerable<WorkspaceEntry> projects)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
ArgumentNullException.ThrowIfNull(projects);
|
||||
var entries = new List<VideoEntry>();
|
||||
foreach (var project in projects.Where(p => p.IsReadable))
|
||||
{
|
||||
try
|
||||
{
|
||||
var folder = store.Project(project.ProjectId);
|
||||
foreach (var render in folder.ReadRenders().Unsent)
|
||||
{
|
||||
var path = folder.ExportFile(render.File);
|
||||
entries.Add(FromWorkspace(render, project, path, File.Exists(path) || Directory.Exists(path)));
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"The render ledger of workspace project {project.ProjectId} cannot be read", ex);
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>"H.264", "HEVC", "PNG"… for a codec as recorded; the recorded name in capitals for one this Chronos does not know.</summary>
|
||||
public static string CodecText(string? codec) =>
|
||||
codec is null or { Length: 0 } ? string.Empty
|
||||
: Enum.TryParse<VideoCodec>(codec, ignoreCase: true, out var known) && Enum.IsDefined(known) ? ExportNaming.CodecLabel(known)
|
||||
: codec.ToUpperInvariant();
|
||||
|
||||
/// <summary>The player pane can play the file as a video.</summary>
|
||||
public static bool PlaysAsVideo(string? path) => path is not null && VideoExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The player pane shows the file as an image.</summary>
|
||||
public static bool ShowsAsImage(string? path) => path is not null && ImageExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>The videos folder of this PC (decision 15): where Copy to folder puts renders.</summary>
|
||||
public static class VideosFolders
|
||||
{
|
||||
/// <summary><c>%USERPROFILE%\Videos\Chronos</c>; null when Windows names no videos folder (decision 15, Q12).</summary>
|
||||
public static string? Default()
|
||||
{
|
||||
var videos = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
|
||||
return string.IsNullOrEmpty(videos) ? null : Path.Combine(videos, "Chronos");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="folder"/> cannot be the videos folder, as one of <see cref="VideoErrors"/>: unset, or inside (or
|
||||
/// equal to) the archive root or the workspace; null when it can.
|
||||
/// </summary>
|
||||
public static string? Problem(string? folder, params string?[] refused)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(folder)) return VideoErrors.FolderUnset;
|
||||
string full;
|
||||
try
|
||||
{
|
||||
if (!Path.IsPathFullyQualified(folder)) return VideoErrors.FolderInvalid;
|
||||
full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
return VideoErrors.FolderInvalid;
|
||||
}
|
||||
foreach (var root in refused)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(root)) continue;
|
||||
string other;
|
||||
try
|
||||
{
|
||||
other = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (string.Equals(full, other, StringComparison.OrdinalIgnoreCase)
|
||||
|| full.StartsWith(other + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||
return VideoErrors.FolderInvalid;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Jobs;
|
||||
using Chronos.App.Sections;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Tests.Windows;
|
||||
using Chronos.App.Videos;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Windows.Shell;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Tests.Videos;
|
||||
|
||||
/// <summary>
|
||||
/// The Videos library's sources (owner review 1, R9; decision 20): this PC's, the server's and the workspace's renders
|
||||
/// merged by render id, the filters and the orders, the videos folder's checks, the player's fallback, and the copy's toast.
|
||||
/// </summary>
|
||||
public sealed class VideoSourcesTests
|
||||
{
|
||||
private static readonly Guid Harbour = Guid.CreateVersion7();
|
||||
private static readonly Guid Comet = Guid.CreateVersion7();
|
||||
|
||||
[Test]
|
||||
public void OneRowPerRenderWhereverItIs()
|
||||
{
|
||||
var shared = Guid.CreateVersion7();
|
||||
var local = new[] { Local(shared, Harbour, "Harbour sunset", 100), Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 200) };
|
||||
var server = new[] { Server(shared, Harbour, "Harbour sunset", 100, copies: ["/videos/harbour.mp4"]), Server(Guid.CreateVersion7(), Comet, "Comet", 300) };
|
||||
var unsent = Unsent(Guid.CreateVersion7(), Comet);
|
||||
// A render the workspace sent home already is the archive's: the workspace's row of it is dropped.
|
||||
var sentAlready = Unsent(local[1].Id, Harbour);
|
||||
|
||||
var merged = VideoSources.Merge(local, server, [unsent, sentAlready]);
|
||||
|
||||
Assert.Equal(4, merged.Count);
|
||||
Assert.Equal(merged.Count, merged.Select(e => e.Id).Distinct().Count());
|
||||
var twin = merged.Single(e => e.Id == shared);
|
||||
Assert.True(twin is { IsLocal: true, IsOnServer: true, IsUnsent: false }, "here and on the server: one row");
|
||||
Assert.Equal(local[0].LocalPath, twin.LocalPath);
|
||||
Assert.Contains("/videos/harbour.mp4", twin.Copies);
|
||||
Assert.True(merged.Single(e => e.Id == server[1].Id) is { IsLocal: false, IsOnServer: true, LocalPath: null });
|
||||
Assert.True(merged.Single(e => e.Id == local[1].Id) is { IsLocal: true, IsUnsent: false });
|
||||
Assert.True(merged.Single(e => e.Id == unsent.Id).IsUnsent);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheFiltersNarrowAndTheOrdersSort()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var old = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 500) with { Created = new DateTimeOffset(2024, 6, 1, 12, 0, 0, TimeSpan.Zero) };
|
||||
var still = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 50) with { Kind = RenderKind.Still, Codec = "png", Created = now.AddDays(-1) };
|
||||
var remote = Server(Guid.CreateVersion7(), Comet, "Comet over the lake", 900) with { Codec = "hevc", Created = now };
|
||||
var unsent = Unsent(Guid.CreateVersion7(), Comet) with { Created = now.AddHours(-2) };
|
||||
VideoEntry[] all = [old, still, remote, unsent];
|
||||
|
||||
Assert.SequenceEqual([remote.Id, unsent.Id, still.Id, old.Id], VideoFilter.None.Apply(all).Select(e => e.Id), "newest first by default");
|
||||
Assert.SequenceEqual([old.Id, still.Id, unsent.Id, remote.Id], new VideoFilter { Sort = VideoSorts.Oldest }.Apply(all).Select(e => e.Id));
|
||||
Assert.Equal(remote.Id, new VideoFilter { Sort = VideoSorts.Largest }.Apply(all)[0].Id);
|
||||
Assert.Equal("Comet over the lake", new VideoFilter { Sort = VideoSorts.Title }.Apply(all)[0].Title);
|
||||
|
||||
Assert.SequenceEqual([still.Id], new VideoFilter { Kind = RenderKind.Still }.Apply(all).Select(e => e.Id));
|
||||
Assert.SequenceEqual([remote.Id], new VideoFilter { Codec = "HEVC" }.Apply(all).Select(e => e.Id), "codecs match in any case");
|
||||
Assert.SequenceEqual([old.Id], new VideoFilter { Year = 2024 }.Apply(all).Select(e => e.Id));
|
||||
Assert.SequenceEqual([remote.Id], new VideoFilter { Source = VideoSourceFilter.Server }.Apply(all).Select(e => e.Id));
|
||||
Assert.SequenceEqual([unsent.Id], new VideoFilter { Source = VideoSourceFilter.NotSent }.Apply(all).Select(e => e.Id));
|
||||
Assert.Equal(3, new VideoFilter { Source = VideoSourceFilter.Local }.Apply(all).Count, "this PC: the archive's and the workspace's");
|
||||
Assert.Equal(2, new VideoFilter { SequenceId = Comet }.Apply(all).Count);
|
||||
Assert.SequenceEqual([unsent.Id], new VideoFilter { Text = "INSTAGRAM" }.Apply(all).Select(e => e.Id), "the preset name, in any case");
|
||||
Assert.Equal(2, new VideoFilter { Text = "harbour" }.Apply(all).Count, "the title, the preset or the file name");
|
||||
Assert.False(new VideoFilter { Sort = VideoSorts.Largest }.IsFiltered, "the order alone narrows nothing");
|
||||
Assert.True(new VideoFilter { SequenceId = Comet }.IsFiltered);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnOlderServerIsToldApartFromOneWithVideos()
|
||||
{
|
||||
static IRemoteVideos Connect() => throw new InvalidOperationException("not connected");
|
||||
var old = new ServerInfo("Studio NAS", "1.3.0", 1, [], null, [], new ServerLimits(0, 0));
|
||||
Assert.Equal(VideoServerState.Old, VideoServer.Of(old, long.MaxValue, Connect).State);
|
||||
Assert.Null(VideoServer.Of(old, long.MaxValue, Connect).Connect);
|
||||
Assert.Equal(VideoServerState.SignedOut, VideoServer.Of(null, 0, Connect).State);
|
||||
var current = old with { Capabilities = [ServerCapabilities.Videos] };
|
||||
var reader = VideoServer.Of(current, 0, Connect);
|
||||
Assert.True(reader is { State: VideoServerState.Available, CanEdit: false, CanDelete: false });
|
||||
var editor = VideoServer.Of(current, (long)(Permissions.Edit | Permissions.Delete), Connect);
|
||||
Assert.True(editor is { CanEdit: true, CanDelete: true });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheVideosFolderMustBeAbsoluteAndOutsideTheArchiveAndTheWorkspace()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), "chronos-videos-folder");
|
||||
var archive = Path.Combine(root, "Archive");
|
||||
var workspace = Path.Combine(root, "Workspace");
|
||||
Assert.Equal(VideoErrors.FolderUnset, VideosFolders.Problem(null, archive));
|
||||
Assert.Equal(VideoErrors.FolderUnset, VideosFolders.Problem(" ", archive));
|
||||
Assert.Equal(VideoErrors.FolderInvalid, VideosFolders.Problem("relative\\videos", archive));
|
||||
Assert.Equal(VideoErrors.FolderInvalid, VideosFolders.Problem(archive, archive, workspace));
|
||||
Assert.Equal(VideoErrors.FolderInvalid, VideosFolders.Problem(Path.Combine(archive, "2026", "Videos"), archive, workspace));
|
||||
Assert.Equal(VideoErrors.FolderInvalid, VideosFolders.Problem(Path.Combine(workspace, "Videos") + Path.DirectorySeparatorChar, archive, workspace));
|
||||
Assert.Null(VideosFolders.Problem(Path.Combine(root, "Videos"), archive, workspace));
|
||||
// A sibling whose name starts like the archive's is not inside it.
|
||||
Assert.Null(VideosFolders.Problem(archive + " videos", archive, workspace));
|
||||
Assert.Null(VideosFolders.Problem(Path.Combine(root, "Videos"), null, null));
|
||||
if (VideosFolders.Default() is { } folder) Assert.True(Path.IsPathFullyQualified(folder) && folder.EndsWith("Chronos", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ThePlayerSaysCannotPlayHereWhenWindowsCannotDecodeTheRender()
|
||||
{
|
||||
var folder = Directory.CreateTempSubdirectory("chronos-player").FullName;
|
||||
try
|
||||
{
|
||||
var mp4 = Path.Combine(folder, "harbour.mp4");
|
||||
var png = Path.Combine(folder, "harbour.png");
|
||||
var odd = Path.Combine(folder, "harbour.xyz");
|
||||
foreach (var path in new[] { mp4, png, odd }) File.WriteAllBytes(path, [0, 1, 2, 3]);
|
||||
var video = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 4) with { LocalPath = mp4, FileName = "harbour.mp4" };
|
||||
|
||||
Assert.Equal(VideoPlayerMode.Video, VideoPlayerViewModel.ModeOf(video));
|
||||
Assert.Equal(VideoPlayerMode.Image, VideoPlayerViewModel.ModeOf(video with { LocalPath = png, Kind = RenderKind.Still }));
|
||||
Assert.Equal(VideoPlayerMode.CannotPlay, VideoPlayerViewModel.ModeOf(video with { LocalPath = odd }), "an extension Windows does not play");
|
||||
Assert.Equal(VideoPlayerMode.CannotPlay, VideoPlayerViewModel.ModeOf(video with { LocalPath = Path.Combine(folder, "gone.mp4") }), "the file is gone");
|
||||
Assert.Equal(VideoPlayerMode.CannotPlay, VideoPlayerViewModel.ModeOf(video with { Kind = RenderKind.Sequence, LocalPath = folder }), "a folder of images");
|
||||
Assert.Equal(VideoPlayerMode.CannotPlay, VideoPlayerViewModel.ModeOf(video with { LocalPath = null, IsLocal = false, IsOnServer = true }), "the server's alone");
|
||||
|
||||
// Windows fails to decode the file once it is opened: the pane says so and keeps Show in folder.
|
||||
var player = new VideoPlayerViewModel(video, new RelayCommand(() => { }), new RelayCommand(() => { }));
|
||||
Assert.True(player is { IsVideo: true, CannotPlay: false });
|
||||
Assert.NotNull(player.Source);
|
||||
player.MediaFailed(new InvalidOperationException("0xC00D36C4"));
|
||||
Assert.True(player is { Mode: VideoPlayerMode.CannotPlay, IsVideo: false, CannotPlay: true, CanShowInFolder: true });
|
||||
Assert.Equal(Loc.L("Videos.Player.CannotPlay"), player.CannotPlayText);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(folder, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ACopyToTheVideosFolderEndsWithAToast()
|
||||
{
|
||||
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.VideoCopy, State = JobState.Done };
|
||||
Assert.Equal(JobNotice.Done, JobNotices.For(JobState.Running, job));
|
||||
Assert.Equal(JobNotice.Failed, JobNotices.For(JobState.Running, job with { State = JobState.Failed }));
|
||||
}
|
||||
|
||||
internal static VideoEntry Local(Guid id, Guid sequence, string title, long bytes) => new()
|
||||
{
|
||||
Id = id,
|
||||
SequenceId = sequence,
|
||||
Title = title,
|
||||
PresetName = "YouTube 4K",
|
||||
Codec = "h264",
|
||||
Width = 3840,
|
||||
Height = 2160,
|
||||
Fps = 25,
|
||||
DurationSeconds = 12,
|
||||
Bytes = bytes,
|
||||
Created = DateTimeOffset.UtcNow.AddMinutes(-bytes),
|
||||
Kind = RenderKind.Video,
|
||||
FileName = "harbour.mp4",
|
||||
LocalPath = Path.Combine(Path.GetTempPath(), "harbour-" + id.ToString("N") + ".mp4"),
|
||||
IsLocal = true,
|
||||
};
|
||||
|
||||
private static VideoEntry Server(Guid id, Guid sequence, string title, long bytes, IReadOnlyList<string>? copies = null) =>
|
||||
VideoSources.FromServer(new VideoDto(id, sequence, "YouTube 4K", "h264", 3840, 2160, 25, 12, bytes, DateTimeOffset.UtcNow.AddMinutes(-bytes), "server", null, null,
|
||||
null, RenderKind.Video, title, null, null, null, VideoStates.Ok, [.. (copies ?? []).Select(p => new VideoCopyDto(p, DateTimeOffset.UtcNow))],
|
||||
"comet.mp4"));
|
||||
|
||||
private static VideoEntry Unsent(Guid id, Guid sequence) => new()
|
||||
{
|
||||
Id = id,
|
||||
SequenceId = sequence,
|
||||
Title = "Comet over the lake",
|
||||
PresetName = "Instagram",
|
||||
Codec = "h264",
|
||||
Bytes = 10,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
Kind = RenderKind.Video,
|
||||
FileName = "comet-instagram.mp4",
|
||||
LocalPath = Path.Combine(Path.GetTempPath(), "comet-instagram.mp4"),
|
||||
IsUnsent = true,
|
||||
WorkspaceProjectId = Guid.CreateVersion7(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Videos section in the shell: an older server leaves this PC's videos with the reason, Delete… runs the dry run first
|
||||
/// and shows its bytes and what stays, Copy to folder says why without a videos folder, and Ctrl+4 opens it (Archive Ctrl+5).
|
||||
/// </summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
[Timeout(120_000)]
|
||||
public sealed class VideosSectionTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public Task AnOlderServerListsThisPcsVideosWithTheReason() => WithSectionAsync(async (shell, section, library, _) =>
|
||||
{
|
||||
var info = new ServerInfo("Studio NAS", "1.3.0", 1, [], null, [], new ServerLimits(0, 0));
|
||||
section.ServerVideos = () => VideoServer.Of(info, long.MaxValue, () => throw new InvalidOperationException("an older server is never asked"));
|
||||
await section.RefreshAsync();
|
||||
|
||||
Assert.Equal(library.Items.Count, section.Rows.Count);
|
||||
Assert.True(section.Rows.All(r => r.Entry.IsLocal));
|
||||
Assert.Equal(VideoServerState.Old, section.ServerState);
|
||||
Assert.True(section.IsServerLimited, "the status line shows");
|
||||
Assert.Equal(Loc.L("Tooltips.Videos.ServerOld"), section.ServerStatusToolTip);
|
||||
Assert.Equal(Loc.L("Tooltips.Videos.ServerOld"), section.CopyOnServerBlocker(section.Rows));
|
||||
|
||||
// A server with the library lists its videos with this PC's, one row per render.
|
||||
var remote = new FakeRemote([Dto(library.Items[0]), Dto(library.Items[0]) with { Id = Guid.CreateVersion7(), FileName = "server-only.mp4" }]);
|
||||
section.ServerVideos = () => VideoServer.Of(info with { Capabilities = [ServerCapabilities.Videos] }, (long)Permissions.Edit, () => remote);
|
||||
await section.RefreshAsync();
|
||||
Assert.Equal(VideoServerState.Available, section.ServerState);
|
||||
Assert.False(section.IsServerLimited);
|
||||
Assert.Equal(library.Items.Count + 1, section.Rows.Count);
|
||||
Assert.True(section.Rows.Single(r => r.Entry.Id == library.Items[0].Render.Id).Entry is { IsLocal: true, IsOnServer: true });
|
||||
|
||||
// The server stops answering: this PC's videos stay, with the reason.
|
||||
section.ServerVideos = () => VideoServer.Of(info with { Capabilities = [ServerCapabilities.Videos] }, 0, () => new FakeRemote([], fails: true));
|
||||
await section.RefreshAsync();
|
||||
Assert.Equal(VideoServerState.Unreachable, section.ServerState);
|
||||
Assert.Equal(library.Items.Count, section.Rows.Count);
|
||||
Assert.Equal(Loc.L("Videos.ServerUnreachable"), section.ServerStatusText);
|
||||
Assert.Empty(shell.PendingToasts.Where(t => t.IsError));
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task TheFiltersOfTheSectionNarrowItsRows() => WithSectionAsync(async (_, section, library, _) =>
|
||||
{
|
||||
await section.RefreshAsync();
|
||||
Assert.Equal(3, section.Rows.Count);
|
||||
section.SelectedKind = section.Kinds.Single(k => k.Value == RenderKind.Still);
|
||||
Assert.True(section.IsKindFiltered);
|
||||
Assert.Equal(library.Items[2].Render.Id, Assert.NotNull(section.Rows.SingleOrDefault()).Entry.Id);
|
||||
section.SelectedKind = section.Kinds[0];
|
||||
section.SearchText = "no such video";
|
||||
Assert.True(section.IsNoMatch);
|
||||
Assert.True(section.ClearFiltersCommand.CanExecute(null));
|
||||
section.ClearFiltersCommand.Execute(null);
|
||||
Assert.Equal(3, section.Rows.Count);
|
||||
section.SelectedSort = section.Sorts.Single(s => s.Value == VideoSorts.Largest);
|
||||
Assert.Equal(library.Items.Max(i => i.Render.Bytes), section.Rows[0].Entry.Bytes);
|
||||
// The Export footer's Videos: one sequence's renders, its title as the chip that clears it.
|
||||
section.ShowSequence(library.Items[1].Render.SequenceId, "Comet");
|
||||
Assert.True(section.IsSequenceFiltered);
|
||||
Assert.Equal("Comet", section.SequenceFilterText);
|
||||
Assert.True(section.Rows.All(r => r.Entry.SequenceId == library.Items[1].Render.SequenceId));
|
||||
// Selected rows stay selected when the list is made again.
|
||||
section.Rows[0].IsSelected = true;
|
||||
section.SearchText = "comet";
|
||||
Assert.True(section.Rows[0].IsSelected);
|
||||
Assert.True(section.HasSelection);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task DeleteRunsTheDryRunFirstAndShowsItsBytesAndWhatStays() => WithSectionAsync(async (shell, section, library, dialogs) =>
|
||||
{
|
||||
await section.RefreshAsync();
|
||||
foreach (var row in section.Rows.Where(r => r.Entry.Id != library.Items[2].Render.Id)) row.IsSelected = true;
|
||||
var selected = section.SelectedRows;
|
||||
Assert.Equal(2, selected.Count);
|
||||
Assert.Null(section.DeleteBlocker(selected));
|
||||
|
||||
// Kept: the plan was made, nothing was deleted.
|
||||
dialogs.Answer = false;
|
||||
await section.DeleteAsync(selected);
|
||||
Assert.SequenceEqual(["plan"], library.Calls);
|
||||
var request = Assert.NotNull(dialogs.Requests.SingleOrDefault());
|
||||
var plans = Assert.NotNull(section.LastDeletePlans);
|
||||
Assert.Equal(1, plans.Blocked);
|
||||
Assert.True(request.IsDestructive);
|
||||
Assert.Contains(Formatting.Bytes(library.Items[0].Render.Bytes), request.Message, "the bytes that go (a missing file counts nothing)");
|
||||
Assert.Contains(Loc.L("Videos.Delete.Missing"), request.Message);
|
||||
Assert.Contains(Loc.L("Videos.Delete.Blocked", Formatting.Count(1)), request.Detail!);
|
||||
Assert.Contains(VideoText.BlockReason(VideoBlockReasons.Busy), request.Detail!);
|
||||
|
||||
// Confirmed: the delete gives back the plan's fingerprint.
|
||||
dialogs.Answer = true;
|
||||
await section.DeleteAsync(selected);
|
||||
Assert.SequenceEqual(["plan", "plan", "delete:fingerprint-2"], library.Calls);
|
||||
Assert.Contains(shell.PendingToasts, t => t.Title == Loc.L("Videos.Delete.Done", Formatting.Count(2)) && !t.IsError);
|
||||
Assert.Equal(1, section.Rows.Count);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task ACopyWithoutAVideosFolderSaysWhy() => WithSectionAsync(async (shell, section, library, _) =>
|
||||
{
|
||||
var queued = new List<ArchiveJobRequest>();
|
||||
section.Enqueue = request =>
|
||||
{
|
||||
queued.Add(request);
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
await section.RefreshAsync();
|
||||
var row = section.Rows.Single(r => r.Entry.Id == library.Items[0].Render.Id);
|
||||
row.IsSelected = true;
|
||||
|
||||
section.Folder = () => null;
|
||||
Assert.Equal(Loc.L("Tooltips.Videos.FolderUnset"), section.CopyBlocker([row]));
|
||||
Assert.Equal(Loc.L("Tooltips.Videos.FolderUnset"), section.CopyToolTip);
|
||||
Assert.False(section.CopyCommand.CanExecute(null));
|
||||
await section.CopyAsync([row]);
|
||||
Assert.Empty(queued);
|
||||
Assert.Contains(shell.PendingToasts, t => t.Title == Loc.L("Tooltips.Videos.FolderUnset") && t.IsError);
|
||||
|
||||
// Inside the workspace: refused too.
|
||||
section.Folder = () => Path.Combine(shell.Services.Workspace.Root, "Videos");
|
||||
Assert.Equal(Loc.L("Errors.Videos.FolderInsideArchive"), section.CopyBlocker([row]));
|
||||
|
||||
// A folder of its own: one copy job of this PC's render, the folder given in full.
|
||||
var folder = context.CreateTempDirectory("videos-folder");
|
||||
section.Folder = () => folder;
|
||||
Assert.Null(section.CopyBlocker([row]));
|
||||
await section.CopyAsync([row]);
|
||||
var job = Assert.NotNull(queued.SingleOrDefault());
|
||||
Assert.Equal(JobKind.VideoCopy, job.Kind);
|
||||
var parameters = Assert.NotNull(VideoCopyParameters.Read(job.ParametersJson));
|
||||
Assert.SequenceEqual([row.Entry.Id], parameters.RenderIds);
|
||||
Assert.Equal(Path.GetFullPath(folder), parameters.Folder);
|
||||
Assert.False(parameters.FromServer);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task CtrlFourOpensVideosAndCtrlFiveTheArchive() => WithSectionAsync(async (shell, section, _, _) =>
|
||||
{
|
||||
Assert.SequenceEqual([SectionKey.Library, SectionKey.Import, SectionKey.Edit, SectionKey.Videos, SectionKey.Archive, SectionKey.Jobs, SectionKey.Server],
|
||||
shell.TopSections.Select(s => s.Key));
|
||||
var window = new MainWindow(shell);
|
||||
try
|
||||
{
|
||||
var bindings = window.InputBindings.OfType<KeyBinding>().Where(b => b.Modifiers == ModifierKeys.Control).ToList();
|
||||
foreach (var (key, expected) in new[]
|
||||
{
|
||||
(Key.D4, SectionKey.Videos), (Key.NumPad4, SectionKey.Videos), (Key.D5, SectionKey.Archive), (Key.NumPad5, SectionKey.Archive),
|
||||
(Key.D6, SectionKey.Jobs), (Key.D7, SectionKey.Server),
|
||||
})
|
||||
{
|
||||
var binding = bindings.Single(b => b.Key == key);
|
||||
Assert.True(binding.Command.CanExecute(binding.CommandParameter), $"Ctrl+{key}");
|
||||
binding.Command.Execute(binding.CommandParameter);
|
||||
Assert.Equal(expected, shell.Current.Key, $"Ctrl+{key}");
|
||||
}
|
||||
shell.OpenVideos(Guid.CreateVersion7(), "Harbour sunset");
|
||||
Assert.Same(section, shell.Current);
|
||||
Assert.Equal("Harbour sunset", section.SequenceFilterText);
|
||||
await section.RefreshAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
}
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task TheSectionLaysOutAsCardsAListAndWithThePlayer() => WithSectionAsync(async (shell, section, library, _) =>
|
||||
{
|
||||
await section.RefreshAsync();
|
||||
var view = new VideosView { DataContext = section };
|
||||
Layout(view);
|
||||
section.LayoutIndex = 1;
|
||||
section.Rows[0].IsSelected = true;
|
||||
Assert.True(section.PlayCommand.CanExecute(null));
|
||||
section.PlayCommand.Execute(null);
|
||||
var player = Assert.NotNull(section.Player);
|
||||
Assert.Equal(library.Items[0].Render.Id, player.Entry.Id);
|
||||
Layout(view);
|
||||
section.ClosePlayerCommand.Execute(null);
|
||||
Assert.False(section.IsPlayerOpen);
|
||||
// Settings › Archive shows the videos folder row.
|
||||
shell.Settings.Page = SettingsPage.Archive;
|
||||
var field = shell.Settings.VideosFolder;
|
||||
Assert.Equal(shell.Services.Settings.VideosFolder ?? string.Empty, field.Text);
|
||||
Layout(new SettingsView { DataContext = shell.Settings });
|
||||
field.Text = Path.Combine(shell.Services.Workspace.Root, "Videos");
|
||||
Assert.False(field.Commit(), "never inside the workspace");
|
||||
Assert.Equal(Loc.L("Errors.Videos.FolderInsideArchive"), field.Error);
|
||||
field.Text = string.Empty;
|
||||
Assert.True(field.Commit());
|
||||
Assert.Null(shell.Services.Settings.VideosFolder);
|
||||
var folder = context.CreateTempDirectory("videos-setting");
|
||||
field.Text = folder;
|
||||
Assert.True(field.Commit());
|
||||
Assert.Equal(Path.GetFullPath(folder), shell.Services.Settings.VideosFolder);
|
||||
Assert.True(shell.Settings.OpenVideosFolderCommand.CanExecute(null));
|
||||
});
|
||||
|
||||
private static void Layout(System.Windows.FrameworkElement view)
|
||||
{
|
||||
view.Measure(new System.Windows.Size(1200, 800));
|
||||
view.Arrange(new System.Windows.Rect(0, 0, 1200, 800));
|
||||
view.UpdateLayout();
|
||||
}
|
||||
|
||||
/// <summary>The section of a shell on a fresh data folder, reading <see cref="FakeLibrary"/>, signed out, no workspace renders.</summary>
|
||||
private Task WithSectionAsync(Func<ShellViewModel, VideosViewModel, FakeLibrary, ScriptedDialogs, Task> body) => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
var directory = context.CreateTempDirectory("videos-section");
|
||||
var environment = AppEnvironment.From(AppPaths.Resolve(Directory.CreateDirectory(Path.Combine(directory, "app")).FullName,
|
||||
Directory.CreateDirectory(Path.Combine(directory, "local")).FullName, []));
|
||||
UiLanguage.Apply("en");
|
||||
var dialogs = new ScriptedDialogs();
|
||||
var settings = new AppSettings { Language = "en", FirstRunCompleted = true, CheckForUpdates = false };
|
||||
var services = new AppServices(environment, settings, () => { }, dialogs);
|
||||
var shell = new ShellViewModel(services);
|
||||
var library = new FakeLibrary(directory);
|
||||
var section = shell.Videos;
|
||||
section.LocalLibrary = () => library;
|
||||
section.ServerVideos = () => VideoServer.SignedOut;
|
||||
section.WorkspaceRenders = _ => Task.FromResult<IReadOnlyList<VideoEntry>>([]);
|
||||
section.Posters = (_, _, _) => Task.FromResult<System.Windows.Media.ImageSource?>(null);
|
||||
try
|
||||
{
|
||||
await body(shell, section, library, dialogs);
|
||||
}
|
||||
finally
|
||||
{
|
||||
shell.Dispose();
|
||||
await services.DisposeAsync();
|
||||
}
|
||||
});
|
||||
|
||||
private static VideoDto Dto(VideoItem item) =>
|
||||
new(item.Render.Id, item.Render.SequenceId, item.Render.PresetName, item.Render.Codec, item.Render.Width, item.Render.Height, item.Render.Fps,
|
||||
item.Render.DurationSeconds, item.Render.Bytes, item.Render.Created, null, null, null, null, item.Kind, item.SequenceTitle, null, null, null, VideoStates.Ok, [],
|
||||
item.FileName);
|
||||
|
||||
/// <summary>This PC's videos library: a video, a missing one and a still; its delete plan leaves one render, busy, where it is.</summary>
|
||||
private sealed class FakeLibrary : IVideoLibrary
|
||||
{
|
||||
private int _plans;
|
||||
|
||||
public FakeLibrary(string folder)
|
||||
{
|
||||
var harbour = Guid.CreateVersion7();
|
||||
var comet = Guid.CreateVersion7();
|
||||
Items =
|
||||
[
|
||||
Item(harbour, "Harbour sunset", Path.Combine(folder, "harbour-4k.mp4"), 40_000_000, null, missing: false, DateTimeOffset.UtcNow.AddHours(-1)),
|
||||
Item(comet, "Comet", Path.Combine(folder, "comet.mp4"), 9_000_000, null, missing: true, DateTimeOffset.UtcNow.AddHours(-2)),
|
||||
Item(harbour, "Harbour sunset", Path.Combine(folder, "harbour.png"), 2_000_000, RenderKind.Still, missing: false, DateTimeOffset.UtcNow.AddHours(-3)),
|
||||
];
|
||||
File.WriteAllBytes(Items[0].FullPath, [0, 1, 2]);
|
||||
}
|
||||
|
||||
public List<VideoItem> Items { get; }
|
||||
|
||||
public List<string> Calls { get; } = [];
|
||||
|
||||
public bool IsAvailable => true;
|
||||
|
||||
public Task<VideoPage> ListAsync(VideoQuery query, CancellationToken cancellationToken = default) => Task.FromResult(new VideoPage([.. Items], null, Items.Count));
|
||||
|
||||
public Task<VideoItem?> GetAsync(Guid renderId, CancellationToken cancellationToken = default) => Task.FromResult(Items.FirstOrDefault(i => i.Render.Id == renderId));
|
||||
|
||||
public Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
lock (Calls) Calls.Add("plan");
|
||||
// Both go (the missing one only loses its row); another render, being sent, is named as staying.
|
||||
var wanted = Items.Where(i => renderIds.Contains(i.Render.Id)).ToList();
|
||||
var stays = new VideoBlocked(Items[2].Render.Id, VideoBlockReasons.Busy, Items[2]);
|
||||
return Task.FromResult(new VideoDeletePlan(wanted, [stays], "fingerprint-" + Interlocked.Increment(ref _plans)));
|
||||
}
|
||||
|
||||
public Task<VideoDeleteResult> DeleteAsync(IReadOnlyList<Guid> renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default)
|
||||
{
|
||||
lock (Calls) Calls.Add("delete:" + fingerprint);
|
||||
var gone = Items.Where(i => renderIds.Contains(i.Render.Id)).ToList();
|
||||
Items.RemoveAll(gone.Contains);
|
||||
return Task.FromResult(new VideoDeleteResult(gone, [], []));
|
||||
}
|
||||
|
||||
public Task<Render> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||
|
||||
public string? FolderProblem(string? folder) => string.IsNullOrWhiteSpace(folder) ? VideoErrors.FolderUnset : null;
|
||||
|
||||
public ArchiveJobRequest CopyJob(VideoCopyParameters parameters) =>
|
||||
new(JobKind.VideoCopy, parameters.RenderIds, null, parameters.ToJson(), JobPriority.User);
|
||||
|
||||
private static VideoItem Item(Guid sequence, string title, string path, long bytes, string? kind, bool missing, DateTimeOffset created) => new()
|
||||
{
|
||||
Render = new Render
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = sequence,
|
||||
PresetName = kind == RenderKind.Still ? "Still" : "YouTube 4K",
|
||||
OutputPath = Path.GetFileName(path),
|
||||
Codec = kind == RenderKind.Still ? "png" : "h264",
|
||||
Width = 3840,
|
||||
Height = 2160,
|
||||
Fps = 25,
|
||||
DurationSeconds = kind == RenderKind.Still ? 0 : 12,
|
||||
Bytes = bytes,
|
||||
Created = created,
|
||||
Kind = kind,
|
||||
},
|
||||
SequenceTitle = title,
|
||||
FullPath = path,
|
||||
Missing = missing,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The signed-in server's videos library; <c>fails</c>: the server does not answer.</summary>
|
||||
private sealed class FakeRemote(IReadOnlyList<VideoDto> videos, bool fails = false) : IRemoteVideos
|
||||
{
|
||||
public Task<VideoPageDto> ListAsync(VideoQueryDto query, CancellationToken cancellationToken = default) =>
|
||||
fails ? throw new HttpRequestException("unreachable") : Task.FromResult(new VideoPageDto(videos, null, videos.Count));
|
||||
|
||||
public Task<VideoDeletePlanDto> PlanDeleteAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||
|
||||
public Task<VideoDeletePlanDto> DeleteAsync(IReadOnlyList<Guid> ids, string fingerprint, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||
|
||||
public Task<VideoCopyResultDto> CopyAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default) => Task.FromResult(new VideoCopyResultDto(Guid.CreateVersion7()));
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Records every confirmation asked and answers it as told.</summary>
|
||||
private sealed class ScriptedDialogs : IAppDialogs
|
||||
{
|
||||
public bool Answer { get; set; }
|
||||
|
||||
public List<ConfirmRequest> Requests { get; } = [];
|
||||
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
|
||||
public string? PickJsonFile(string title) => null;
|
||||
|
||||
public bool Confirm(ConfirmRequest request)
|
||||
{
|
||||
Requests.Add(request);
|
||||
return Answer;
|
||||
}
|
||||
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user