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.

Undo: check every result first, remember each one moved, run off the UI thread

cre8ive-marketing32efd75911e6
diff --git a/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs b/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
index 9d7e1a48..663c6bfd 100644
--- a/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
@@ -57,11 +57,17 @@ public sealed partial class HistoryItemViewModel : ObservableObject
ThumbnailSource = picture is not null && HistoryThumbnails.CanShow(picture) ? picture : null;
// Only entries that remember their preset (Filee 1.8 and later) and still have a failed file to convert.
CanRetry = conversions is not null && entry.Preset is not null && entry.Failures.Any(f => ConversionService.Exists(f.Source));
- // Undo (#553): only while every result is still as the job left it, so a file changed since is never moved.
- CanUndo = store is not null && !entry.Undone && entry.Undoable.Count > 0 && entry.Undoable.All(o => o.Unchanged());
+ CanUndo = store is not null && UndoLeft();
UndoneText = entry.Undone ? loc[entry.OriginalsInTrash ? "home.undone_original" : "home.undone"] : "";
}
+ /// <summary>
+ /// Undo (#553) is offered while the results not moved yet are all as the job left them, so a file changed since is
+ /// never moved; after an Undo that stopped half-way, for the ones it didn't get to.
+ /// </summary>
+ private bool UndoLeft() =>
+ !_entry.Undone && _entry.Undoable.Where(o => !o.Trashed).ToList() is { Count: > 0 } left && left.All(o => o.Unchanged());
+
public string Title { get; }
public string Subtitle { get; }
public string Time { get; }
@@ -109,7 +115,7 @@ public sealed partial class HistoryItemViewModel : ObservableObject
_conversions.Retry(_entry.Failures.Select(f => f.Source), _entry.Preset, _entry.WatchRuleId);
}
- public bool CanUndo { get; }
+ [ObservableProperty] private bool _canUndo;
/// <summary>"Undone: the results are in the Recycle Bin / Trash", or empty.</summary>
public string UndoneText { get; }
@@ -122,30 +128,49 @@ public sealed partial class HistoryItemViewModel : ObservableObject
public bool HasUndoError => UndoError.Length > 0;
/// <summary>
- /// Moves the job's results to the Recycle Bin / Trash. A result moved by an earlier try is skipped, one changed
- /// since is kept. "Replace the original" sent the originals there already: they stay, and the card says so.
+ /// Moves the job's results to the Recycle Bin / Trash, off the UI thread (Windows' Recycle Bin takes a moment per
+ /// file); the button is disabled meanwhile. Every result is checked first, so a changed one stops it with nothing
+ /// moved. Each result moved is saved as such, so an Undo the Trash stops half-way can be tried again for the rest.
+ /// "Replace the original" sent the originals there already: they stay, and the card says so.
/// </summary>
[RelayCommand]
- private void Undo()
+ private async Task UndoAsync()
{
if (!CanUndo || _store is null)
return;
UndoError = "";
- foreach (var output in _entry.Undoable)
+ var left = _entry.Undoable.Where(o => !o.Trashed).ToList();
+ if (left.FirstOrDefault(o => !o.Unchanged()) is { } changed)
+ {
+ Refused(changed, new TrashRefusal("trash.changed"));
+ return;
+ }
+ var refused = await Task.Run(() =>
{
- if (!File.Exists(output.Path))
- continue;
- var refusal = output.Unchanged() ? _platform.MoveToTrash(output.Path) : new TrashRefusal("trash.changed");
- if (refusal is not null)
+ foreach (var output in left)
{
- UndoError = _loc.Format("home.undo_failed", Path.GetFileName(output.Path), _loc[refusal.ReasonKey]);
- return;
+ if (_platform.MoveToTrash(output.Path) is { } refusal)
+ return (output, refusal);
+ output.Trashed = true;
}
+ return default((HistoryOutput, TrashRefusal)?);
+ });
+ if (refused is { } stop)
+ {
+ _store.SaveHistory(notify: false); // the moved ones stay moved; this card says why it stopped
+ Refused(stop.Item1, stop.Item2);
+ return;
}
_entry.Undone = true;
_store.SaveHistory();
}
+ private void Refused(HistoryOutput output, TrashRefusal refusal)
+ {
+ UndoError = _loc.Format("home.undo_failed", Path.GetFileName(output.Path), _loc[refusal.ReasonKey]);
+ CanUndo = UndoLeft();
+ }
+
[RelayCommand]
private void OpenFolder()
{
diff --git a/src/Filee.Core/History/HistoryEntry.cs b/src/Filee.Core/History/HistoryEntry.cs
index 4de6001f..5a606c2e 100644
--- a/src/Filee.Core/History/HistoryEntry.cs
+++ b/src/Filee.Core/History/HistoryEntry.cs
@@ -67,9 +67,16 @@ public sealed class HistoryEntry
};
}
+ /// <summary>
+ /// More results than this ("Save every frame", a long PDF split into pages) get no Undo, so history.json stays
+ /// small and an Undo never takes minutes.
+ /// </summary>
+ public const int MaxUndoable = 500;
+
private static List<HistoryOutput> UndoableOutputs(ConversionJob job)
{
var outputs = new List<HistoryOutput>();
+ var seen = new HashSet<string>(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
foreach (var file in job.Files)
{
foreach (var output in file.Outputs)
@@ -77,11 +84,15 @@ public sealed class HistoryEntry
// A source left as it was ("Only if smaller" with "Replace the original") is the user's file, not a result.
if (!file.OriginalInTrash && string.Equals(Path.GetFullPath(output), Path.GetFullPath(file.SourcePath), Platform.FileSystemPaths.Comparison))
continue;
- // shortcut: an output folder (Extract) takes Undo away from the whole job; Undo only moves files.
- if (!File.Exists(output))
+ // An output folder (Extract), or a document whose pictures Pandoc wrote into "<name>_files" beside it
+ // (not one of the outputs): Undo only moves files, so the whole job gets none rather than half of it.
+ if (!File.Exists(output)
+ || Directory.Exists(Path.Combine(Path.GetDirectoryName(output)!, Path.GetFileNameWithoutExtension(output) + "_files")))
return [];
- if (outputs.Any(o => string.Equals(o.Path, output, Platform.FileSystemPaths.Comparison)))
+ if (!seen.Add(output))
continue;
+ if (outputs.Count == MaxUndoable)
+ return [];
var info = new FileInfo(output);
outputs.Add(new HistoryOutput { Path = output, Length = info.Length, WrittenUtc = info.LastWriteTimeUtc });
}
@@ -97,6 +108,9 @@ public sealed class HistoryOutput
public long Length { get; set; }
public DateTime WrittenUtc { get; set; }
+ /// <summary>Undo moved it to the Recycle Bin / Trash, also when a later result was refused there.</summary>
+ public bool Trashed { get; set; }
+
/// <summary>Still there, the same size and last written at the same time.</summary>
public bool Unchanged()
{
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 3670f892..654fb8c6 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -131,11 +131,15 @@ public sealed class UserDataStore
HistoryChanged?.Invoke(this, EventArgs.Empty);
}
- /// <summary>Saves a change to an entry already in <see cref="History"/> (Undo marks it undone).</summary>
- public void SaveHistory()
+ /// <summary>
+ /// Saves a change to an entry already in <see cref="History"/> (Undo marks results moved, and the entry undone).
+ /// <paramref name="notify"/> false leaves the list as it is shown, so the card can say why it stopped.
+ /// </summary>
+ public void SaveHistory(bool notify = true)
{
Write(HistoryPath, History, FileeJsonContext.Default.ListHistoryEntry);
- HistoryChanged?.Invoke(this, EventArgs.Empty);
+ if (notify)
+ HistoryChanged?.Invoke(this, EventArgs.Empty);
}
public void ClearHistory()
diff --git a/tests/Filee.App.Tests/RecentConversionTests.cs b/tests/Filee.App.Tests/RecentConversionTests.cs
index f7219746..5b5f7292 100644
--- a/tests/Filee.App.Tests/RecentConversionTests.cs
+++ b/tests/Filee.App.Tests/RecentConversionTests.cs
@@ -252,7 +252,7 @@ public class RecentConversionTests
}
[AvaloniaFact]
- public void Undo_moves_the_results_to_the_trash_while_they_are_as_the_job_left_them()
+ public async Task Undo_moves_the_results_to_the_trash_while_they_are_as_the_job_left_them()
{
TestServices.EnsureInitialized("en");
var loc = AppHost.Get<ILocalizer>();
@@ -273,17 +273,25 @@ public class RecentConversionTests
// Only the Home page (with the history to save) offers it.
Assert.False(new HistoryItemViewModel(entry, loc, platform).CanUndo);
- // The Trash refuses: the card says why, and the entry isn't marked undone.
+ // The Trash refuses the second result: the first stays moved (and saved as such), the card says why and
+ // still offers Undo for the one left, even rebuilt from the saved history.
platform.Refuse = new TrashRefusal("trash.in_use");
+ platform.RefuseOnly = b;
var item = new HistoryItemViewModel(entry, loc, platform, store: store);
Assert.True(item.CanUndo);
- item.UndoCommand.Execute(null);
- Assert.Equal("a.png couldn't be moved to the Recycle Bin / Trash: the file is open in another program", item.UndoError);
+ await item.UndoCommand.ExecuteAsync(null);
+ Assert.Equal("b.png couldn't be moved to the Recycle Bin / Trash: the file is open in another program", item.UndoError);
+ Assert.Equal([a], platform.Trashed);
Assert.False(entry.Undone);
+ Assert.True(item.CanUndo);
+ var reloaded = new UserDataStore(store.Directory);
+ reloaded.Load();
+ Assert.Equal([true, false], Assert.Single(reloaded.History).Undoable.Select(o => o.Trashed));
+ Assert.True(new HistoryItemViewModel(reloaded.History[0], loc, platform, store: store).CanUndo);
platform.Refuse = null;
- item.UndoCommand.Execute(null);
- Assert.Equal([a, b], platform.Trashed);
+ await item.UndoCommand.ExecuteAsync(null);
+ Assert.Equal([a, b], platform.Trashed); // the first isn't asked for again
Assert.True(Assert.Single(store.History).Undone);
var undone = new HistoryItemViewModel(store.History[0], loc, platform, store: store);
Assert.False(undone.CanUndo);
@@ -302,6 +310,21 @@ public class RecentConversionTests
File.AppendAllText(c, "edited");
Assert.False(new HistoryItemViewModel(changed, loc, platform, store: store).CanUndo);
Assert.True(File.Exists(c));
+
+ // Every result is checked before any moves: one changed while the card was open stops it with nothing moved.
+ var d = Path.Combine(folder, "d.png");
+ var e = Path.Combine(folder, "e.png");
+ File.WriteAllBytes(d, [4]);
+ File.WriteAllBytes(e, [5]);
+ var pair = Entry([d, e]);
+ pair.Undoable = [Stamp(d), Stamp(e)];
+ var open = new HistoryItemViewModel(pair, loc, platform, store: store);
+ File.AppendAllText(e, "edited");
+ await open.UndoCommand.ExecuteAsync(null);
+ Assert.Equal("e.png couldn't be moved to the Recycle Bin / Trash: it was changed after the conversion", open.UndoError);
+ Assert.True(File.Exists(d));
+ Assert.DoesNotContain(d, platform.Trashed);
+ Assert.False(open.CanUndo);
}
finally
{
@@ -450,9 +473,12 @@ public class RecentConversionTests
public List<string> Trashed { get; } = [];
public TrashRefusal? Refuse { get; set; }
+ /// <summary>Refuses only this path, when set.</summary>
+ public string? RefuseOnly { get; set; }
+
public TrashRefusal? MoveToTrash(string path)
{
- if (Refuse is not null)
+ if (Refuse is not null && (RefuseOnly is null || RefuseOnly == path))
return Refuse;
File.Delete(path);
Trashed.Add(path);
diff --git a/tests/Filee.Core.Tests/HistoryEntryTests.cs b/tests/Filee.Core.Tests/HistoryEntryTests.cs
index db13b9dd..bf484177 100644
--- a/tests/Filee.Core.Tests/HistoryEntryTests.cs
+++ b/tests/Filee.Core.Tests/HistoryEntryTests.cs
@@ -81,6 +81,34 @@ public class HistoryEntryTests
Assert.False(result.Unchanged());
}
+ [Fact]
+ public async Task A_document_whose_pictures_pandoc_put_beside_it_has_no_undo()
+ {
+ using var dir = new TempDir();
+ var doc = dir.File("notes.docx");
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("pandoc", new ConversionEdge("docx", "md")) { PictureFolder = true }]));
+ var job = new ConversionJob([doc], new Preset { TargetFormat = "md" }, "MD");
+ await queue.RunAsync(job);
+
+ // Undo would move the .md and leave its "_files" folder of pictures behind.
+ Assert.True(Directory.Exists(Path.Combine(dir.Path, "notes_files")));
+ Assert.Empty(HistoryEntry.From(job).Undoable);
+ }
+
+ [Fact]
+ public async Task A_job_with_more_results_than_undo_takes_has_none()
+ {
+ using var dir = new TempDir();
+ var pdf = dir.File("book.pdf");
+ var converter = new FakeConverter("pdfium", new ConversionEdge("pdf", "png")) { OutputsPerInput = HistoryEntry.MaxUndoable + 1 };
+ await using var queue = new JobQueue(new ConverterCatalog([converter]));
+ var job = new ConversionJob([pdf], new Preset { TargetFormat = "png" }, "PNG");
+ await queue.RunAsync(job);
+
+ Assert.Equal(HistoryEntry.MaxUndoable + 1, job.Outputs.Count());
+ Assert.Empty(HistoryEntry.From(job).Undoable);
+ }
+
[Fact]
public void An_entry_from_before_undo_has_nothing_to_undo()
{