Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Show PDF page previews in the editor

Perricheno8ef48ee9bfbb
diff --git a/src/Filee.App/ViewModels/PdfPageEditorViewModel.cs b/src/Filee.App/ViewModels/PdfPageEditorViewModel.cs
index 83684723..8ce4d8eb 100644
--- a/src/Filee.App/ViewModels/PdfPageEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PdfPageEditorViewModel.cs
@@ -2,6 +2,7 @@
// them in the chosen order and only changes /Rotate where requested.
using System.Collections.ObjectModel;
+using Avalonia.Media.Imaging;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Filee.App.Services;
@@ -16,7 +17,7 @@ using Microsoft.Extensions.Logging;
namespace Filee.App.ViewModels;
-public sealed partial class PdfPageItem(string path, int pageIndex, ILocalizer loc) : ObservableObject
+public sealed partial class PdfPageItem(string path, int pageIndex, ILocalizer loc) : ObservableObject, IDisposable
{
public string Path { get; } = path;
public int PageIndex { get; } = pageIndex;
@@ -26,8 +27,16 @@ public sealed partial class PdfPageItem(string path, int pageIndex, ILocalizer l
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(RotationText))]
+ [NotifyPropertyChangedFor(nameof(PreviewRotation))]
private int _rotation;
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(HasThumbnail))]
+ private Bitmap? _thumbnail;
+
+ [ObservableProperty]
+ private bool _isThumbnailLoading;
+
public string RotationText
{
get
@@ -36,16 +45,36 @@ public sealed partial class PdfPageItem(string path, int pageIndex, ILocalizer l
return signed == 0 ? "" : loc.Format("pdf_editor.rotation", signed);
}
}
+
+ public double PreviewRotation => Rotation > 180 ? Rotation - 360 : Rotation;
+ public bool HasThumbnail => Thumbnail is not null;
public PdfPageReference Reference => new(Path, PageIndex, Rotation);
+
+ internal void SetThumbnail(byte[] png)
+ {
+ using var stream = new MemoryStream(png);
+ var previous = Thumbnail;
+ Thumbnail = new Bitmap(stream);
+ previous?.Dispose();
+ }
+
+ public void Dispose()
+ {
+ Thumbnail?.Dispose();
+ Thumbnail = null;
+ }
}
-public sealed partial class PdfPageEditorViewModel : ObservableObject
+public sealed partial class PdfPageEditorViewModel : ObservableObject, IDisposable
{
private readonly Preset _preset;
private readonly ILocalizer _loc;
private readonly UserDataStore _store;
private readonly ILogger? _log;
private readonly string _primarySource;
+ private readonly SemaphoreSlim _thumbnailGate = new(1, 1);
+ private int _previewRequest;
+ private bool _closed;
public PdfPageEditorViewModel(IReadOnlyList<string> files, Preset preset, ILocalizer loc, UserDataStore store,
ILogger? log = null)
@@ -67,8 +96,16 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject
[NotifyCanExecuteChangedFor(nameof(DeleteCommand))]
[NotifyCanExecuteChangedFor(nameof(RotateLeftCommand))]
[NotifyCanExecuteChangedFor(nameof(RotateRightCommand))]
+ [NotifyPropertyChangedFor(nameof(SelectedPreviewRotation))]
private PdfPageItem? _selectedPage;
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(HasSelectedPreview))]
+ private Bitmap? _selectedPreview;
+
+ [ObservableProperty]
+ private bool _isPreviewLoading;
+
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanSave))]
[NotifyCanExecuteChangedFor(nameof(MoveUpCommand))]
@@ -84,6 +121,78 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject
public bool HasStatus => !string.IsNullOrWhiteSpace(Status);
public bool CanSave => !IsBusy && Pages.Count > 0;
+ public bool HasSelectedPreview => SelectedPreview is not null;
+ public double SelectedPreviewRotation => SelectedPage?.PreviewRotation ?? 0;
+
+ partial void OnSelectedPageChanged(PdfPageItem? value) => _ = LoadSelectedPreviewAsync(value);
+
+ /// <summary>Renders the page strip after the window is visible; PDF parsing never blocks its first frame.</summary>
+ public Task LoadThumbnailsAsync() => LoadThumbnailsAsync(Pages.ToList());
+
+ private async Task LoadThumbnailsAsync(IReadOnlyList<PdfPageItem> items)
+ {
+ await _thumbnailGate.WaitAsync();
+ try
+ {
+ foreach (var item in items.Where(item => item.Thumbnail is null))
+ {
+ if (_closed || !Pages.Contains(item))
+ return;
+ item.IsThumbnailLoading = true;
+ try
+ {
+ var preview = await Task.Run(() => PdfPageTools.Preview(item.Path, item.PageIndex, 260));
+ if (!_closed && Pages.Contains(item))
+ item.SetThumbnail(preview.Png);
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ _log?.LogDebug(ex, "Could not render thumbnail for page {Page} of {Path}", item.PageNumber, item.Path);
+ }
+ finally
+ {
+ item.IsThumbnailLoading = false;
+ }
+ }
+ }
+ finally
+ {
+ _thumbnailGate.Release();
+ }
+ }
+
+ private async Task LoadSelectedPreviewAsync(PdfPageItem? item)
+ {
+ var request = Interlocked.Increment(ref _previewRequest);
+ IsPreviewLoading = item is not null;
+ SelectedPreview?.Dispose();
+ SelectedPreview = null;
+ if (item is null)
+ return;
+ try
+ {
+ var preview = await Task.Run(() => PdfPageTools.Preview(item.Path, item.PageIndex, 1400));
+ using var stream = new MemoryStream(preview.Png);
+ var bitmap = new Bitmap(stream);
+ if (_closed || request != _previewRequest || !ReferenceEquals(item, SelectedPage))
+ {
+ bitmap.Dispose();
+ return;
+ }
+ SelectedPreview = bitmap;
+ if (item.Thumbnail is null)
+ item.SetThumbnail(preview.Png);
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ _log?.LogDebug(ex, "Could not render preview for page {Page} of {Path}", item.PageNumber, item.Path);
+ }
+ finally
+ {
+ if (request == _previewRequest)
+ IsPreviewLoading = false;
+ }
+ }
public async Task AddFilesAsync(IReadOnlyList<string> paths)
{
@@ -91,6 +200,7 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject
return;
IsBusy = true;
Status = _loc["pdf_editor.loading"];
+ var added = new List<PdfPageItem>();
try
{
var counts = await Task.Run(() => paths.Select(path =>
@@ -108,7 +218,11 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject
continue;
}
for (var page = 0; page < count; page++)
- Pages.Add(new PdfPageItem(path, page, _loc));
+ {
+ var item = new PdfPageItem(path, page, _loc);
+ Pages.Add(item);
+ added.Add(item);
+ }
}
SelectedPage ??= Pages.FirstOrDefault();
Status = failed ? _loc["error.conversion_failed"] : "";
@@ -123,6 +237,7 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject
{
IsBusy = false;
}
+ _ = LoadThumbnailsAsync(added);
}
private void AddFiles(IEnumerable<string> paths)
@@ -174,6 +289,7 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject
return;
var index = Pages.IndexOf(selected);
Pages.RemoveAt(index);
+ selected.Dispose();
SelectedPage = Pages[Math.Min(index, Pages.Count - 1)];
NotifyCollectionChanged();
}
@@ -189,6 +305,7 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject
if (SelectedPage is not { } selected)
return;
selected.Rotation = ((selected.Rotation + degrees) % 360 + 360) % 360;
+ OnPropertyChanged(nameof(SelectedPreviewRotation));
}
public Task<bool> SaveAsync() => WriteAsync(Pages, _preset, closeWhenDone: true);
@@ -278,4 +395,16 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject
RotateLeftCommand.NotifyCanExecuteChanged();
RotateRightCommand.NotifyCanExecuteChanged();
}
+
+ public void Dispose()
+ {
+ if (_closed)
+ return;
+ _closed = true;
+ Interlocked.Increment(ref _previewRequest);
+ SelectedPreview?.Dispose();
+ SelectedPreview = null;
+ foreach (var page in Pages)
+ page.Dispose();
+ }
}
diff --git a/src/Filee.App/Views/PdfPageEditorWindow.axaml b/src/Filee.App/Views/PdfPageEditorWindow.axaml
index 0bdac5fa..7cb4708b 100644
--- a/src/Filee.App/Views/PdfPageEditorWindow.axaml
+++ b/src/Filee.App/Views/PdfPageEditorWindow.axaml
@@ -6,7 +6,8 @@
x:DataType="vm:PdfPageEditorViewModel"
Title="{DynamicResource pdf_editor.title}"
Icon="avares://Filee/Assets/Icons/filee.ico"
- Width="620" Height="560" MinWidth="480" MinHeight="360"
+ Width="940" Height="660" MinWidth="720" MinHeight="500"
+ Opened="OnOpened"
WindowStartupLocation="CenterScreen">
<Window.KeyBindings>
<KeyBinding Gesture="Alt+Up" Command="{Binding MoveUpCommand}" />
@@ -57,28 +58,67 @@
</WrapPanel>
</StackPanel>
- <ListBox x:Name="PageOrder" Margin="20,0,20,14" ItemsSource="{Binding Pages}" SelectedItem="{Binding SelectedPage}"
- ScrollViewer.HorizontalScrollBarVisibility="Disabled">
- <ListBox.Styles>
- <Style Selector="ListBoxItem">
- <Setter Property="HorizontalContentAlignment" Value="Stretch" />
- </Style>
- </ListBox.Styles>
- <ListBox.ItemTemplate>
- <DataTemplate x:DataType="vm:PdfPageItem">
- <Grid ColumnDefinitions="Auto,*,Auto" Margin="5,7">
- <Border Width="34" Height="34" CornerRadius="8" Background="{DynamicResource SurfaceBrush}"
- BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1" Margin="0,0,10,0">
- <TextBlock Text="{Binding PageNumber}" HorizontalAlignment="Center" VerticalAlignment="Center" />
- </Border>
- <StackPanel Grid.Column="1" Spacing="2">
- <TextBlock Text="{Binding PageText}" />
- <TextBlock Classes="caption" Text="{Binding SourceName}" TextTrimming="CharacterEllipsis" />
+ <Grid ColumnDefinitions="280,10,*" Margin="20,0,20,14">
+ <ListBox x:Name="PageOrder" Grid.Column="0" ItemsSource="{Binding Pages}" SelectedItem="{Binding SelectedPage}"
+ ScrollViewer.HorizontalScrollBarVisibility="Disabled" Background="{DynamicResource SurfaceAltBrush}">
+ <ListBox.Styles>
+ <Style Selector="ListBoxItem">
+ <Setter Property="HorizontalContentAlignment" Value="Stretch" />
+ </Style>
+ </ListBox.Styles>
+ <ListBox.ItemTemplate>
+ <DataTemplate x:DataType="vm:PdfPageItem">
+ <Grid ColumnDefinitions="92,*" MinHeight="108" Margin="4,5">
+ <Border Width="82" Height="98" CornerRadius="6" Background="White"
+ BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1" ClipToBounds="True">
+ <Grid>
+ <Image Source="{Binding Thumbnail}" Stretch="Uniform" Margin="4"
+ RenderTransformOrigin="50%,50%" IsVisible="{Binding HasThumbnail}">
+ <Image.RenderTransform>
+ <RotateTransform Angle="{Binding PreviewRotation}" />
+ </Image.RenderTransform>
+ </Image>
+ <TextBlock Text="{Binding PageNumber}" Foreground="#666666" FontSize="20"
+ HorizontalAlignment="Center" VerticalAlignment="Center"
+ IsVisible="{Binding !HasThumbnail}" />
+ </Grid>
+ </Border>
+ <StackPanel Grid.Column="1" Spacing="3" VerticalAlignment="Center">
+ <TextBlock Text="{Binding PageText}" FontWeight="SemiBold" />
+ <TextBlock Classes="caption" Text="{Binding SourceName}" TextTrimming="CharacterEllipsis" />
+ <TextBlock Classes="caption" Text="{Binding RotationText}" />
+ </StackPanel>
+ </Grid>
+ </DataTemplate>
+ </ListBox.ItemTemplate>
+ </ListBox>
+
+ <GridSplitter Grid.Column="1" Width="4" HorizontalAlignment="Center" Background="Transparent" />
+
+ <Border Grid.Column="2" Background="{DynamicResource SurfaceAltBrush}" CornerRadius="8"
+ BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1" Padding="16">
+ <Grid RowDefinitions="Auto,*">
+ <Grid ColumnDefinitions="*,Auto" Margin="2,0,2,10">
+ <StackPanel Spacing="2">
+ <TextBlock Text="{Binding SelectedPage.PageText}" FontWeight="SemiBold" />
+ <TextBlock Classes="caption" Text="{Binding SelectedPage.SourceName}" TextTrimming="CharacterEllipsis" />
</StackPanel>
- <TextBlock Grid.Column="2" Classes="caption" Text="{Binding RotationText}" VerticalAlignment="Center" />
+ <TextBlock Grid.Column="1" Classes="caption" Text="{Binding SelectedPage.RotationText}"
+ VerticalAlignment="Center" />
+ </Grid>
+ <Grid Grid.Row="1" ClipToBounds="True">
+ <TextBlock Text="{DynamicResource pdf_editor.loading}" Classes="caption"
+ HorizontalAlignment="Center" VerticalAlignment="Center"
+ IsVisible="{Binding IsPreviewLoading}" />
+ <Image Source="{Binding SelectedPreview}" Stretch="Uniform" Margin="20"
+ RenderTransformOrigin="50%,50%" IsVisible="{Binding HasSelectedPreview}">
+ <Image.RenderTransform>
+ <RotateTransform Angle="{Binding SelectedPreviewRotation}" />
+ </Image.RenderTransform>
+ </Image>
</Grid>
- </DataTemplate>
- </ListBox.ItemTemplate>
- </ListBox>
+ </Grid>
+ </Border>
+ </Grid>
</DockPanel>
</Window>
diff --git a/src/Filee.App/Views/PdfPageEditorWindow.axaml.cs b/src/Filee.App/Views/PdfPageEditorWindow.axaml.cs
index 3721ce94..e1717358 100644
--- a/src/Filee.App/Views/PdfPageEditorWindow.axaml.cs
+++ b/src/Filee.App/Views/PdfPageEditorWindow.axaml.cs
@@ -21,6 +21,19 @@ public partial class PdfPageEditorWindow : Window
Motion.Track(this);
}
+ private async void OnOpened(object? sender, EventArgs e)
+ {
+ if (DataContext is PdfPageEditorViewModel vm)
+ await vm.LoadThumbnailsAsync();
+ }
+
+ protected override void OnClosed(EventArgs e)
+ {
+ if (DataContext is PdfPageEditorViewModel vm)
+ vm.Dispose();
+ base.OnClosed(e);
+ }
+
public async Task PickAndAddAsync()
{
if (DataContext is not PdfPageEditorViewModel vm)
diff --git a/tests/Filee.App.Tests/DonutFlipTests.cs b/tests/Filee.App.Tests/DonutFlipTests.cs
index ca80dffc..2b3d16e9 100644
--- a/tests/Filee.App.Tests/DonutFlipTests.cs
+++ b/tests/Filee.App.Tests/DonutFlipTests.cs
@@ -634,6 +634,37 @@ public class DonutFlipTests
}
}, language);
+ /// <summary>The PDF back face exposes Edit as a slice, then fans its six tools out around that slice.</summary>
+ [AvaloniaFact]
+ public void The_pdf_edit_group_renders_as_a_subring() => With(animations: false, back: null, () =>
+ {
+ var theme = AppHost.Get<ThemeService>();
+ try
+ {
+ theme.Apply(new ThemeSettings { Mode = ThemeMode.Dark, CornerRadius = 16 }, "en");
+ Motion.Configure(true, () => false);
+ var (vm, window, donut) = OpenClickMode(@"C:\docs\report.pdf");
+
+ Assert.True(donut.HandleKey(Key.Tab));
+ Assert.True(vm.IsBackFace);
+ Assert.Equal("pdf-edit", vm.Items[0].Id);
+ Assert.Equal(6, vm.Items[0].Children!.Count);
+
+ donut.SetExternalHit(new DonutHit(DonutHitKind.Segment, 0));
+ donut.ExpandPendingGroup();
+ donut.SetExternalHit(new DonutHit(DonutHitKind.SubSegment, 0, 3));
+ RenderTests.Pump();
+ RenderTests.Save(window, "donut-pdf-edit-en.png");
+
+ Assert.Equal(DonutHitKind.SubSegment, donut.HitTest(donut.SubSliceCenter(0, 3)).Kind);
+ window.Close();
+ }
+ finally
+ {
+ theme.Apply(new ThemeSettings(), "en");
+ }
+ });
+
/// <summary>
/// The editor's Front / Back switch: the donut shows and edits the back face, the front stays as it was, and
/// "Reset to default" puts the built-in back face back.
diff --git a/tests/Filee.App.Tests/PdfPageEditorTests.cs b/tests/Filee.App.Tests/PdfPageEditorTests.cs
index 530b7d7b..c83af14e 100644
--- a/tests/Filee.App.Tests/PdfPageEditorTests.cs
+++ b/tests/Filee.App.Tests/PdfPageEditorTests.cs
@@ -17,12 +17,20 @@ public class PdfPageEditorTests
{
var path = Path.Combine(folder, name);
using var document = new PdfDocument();
- foreach (var (width, rotation) in pages)
+ for (var index = 0; index < pages.Length; index++)
{
+ var (width, rotation) = pages[index];
var page = document.AddPage();
page.Width = XUnit.FromPoint(width);
page.Height = XUnit.FromPoint(500);
page.Rotate = rotation;
+ using var graphics = XGraphics.FromPdfPage(page);
+ var accent = new XSolidBrush(XColor.FromArgb(
+ (byte)(70 + index * 35), (byte)(100 + index * 20), (byte)(180 - index * 25)));
+ graphics.DrawRectangle(accent, 24, 24, width - 48, 88);
+ graphics.DrawRectangle(accent, 24, 148, width * .62, 24);
+ graphics.DrawRectangle(accent, 24, 192, width * .78, 16);
+ graphics.DrawRectangle(accent, 24, 228, width * .48, 16);
}
document.Save(path);
return path;
@@ -42,7 +50,7 @@ public class PdfPageEditorTests
var preset = BuiltInData.CreatePresets().Single(p => p.Id == "tool-pdf-pages");
preset.Output.Location = OutputLocation.CustomFolder;
preset.Output.CustomFolder = folder;
- var vm = new PdfPageEditorViewModel([first], preset, AppHost.Get<ILocalizer>(), store);
+ using var vm = new PdfPageEditorViewModel([first], preset, AppHost.Get<ILocalizer>(), store);
await vm.AddFilesAsync([added]);
vm.SelectedPage = vm.Pages[2];
@@ -69,7 +77,7 @@ public class PdfPageEditorTests
}
[AvaloniaFact]
- public void Editor_window_renders_all_actions_without_clipping()
+ public async Task Editor_window_renders_previews_and_all_actions_without_clipping()
{
TestServices.EnsureInitialized("en");
var folder = Directory.CreateTempSubdirectory("filee-pdf-pages-ui-").FullName;
@@ -88,11 +96,20 @@ public class PdfPageEditorTests
var window = new PdfPageEditorWindow { DataContext = vm };
window.Show();
+ await vm.LoadThumbnailsAsync();
+ for (var i = 0; i < 100 && !vm.HasSelectedPreview; i++)
+ {
+ RenderTests.Pump();
+ await Task.Delay(20, TestContext.Current.CancellationToken);
+ }
+
RenderTests.Pump();
RenderTests.Save(window, "pdf-page-editor-en.png");
- Assert.True(window.PageOrder.Bounds.Width > 400);
+ Assert.True(window.PageOrder.Bounds.Width > 220);
Assert.Equal(4, window.PageOrder.ItemsView.Count);
+ Assert.All(vm.Pages, page => Assert.True(page.HasThumbnail));
+ Assert.True(vm.HasSelectedPreview);
window.Close();
}
finally