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.

Crop keeps the source's quality and shows failures and skips

KnifeLemon9f500d3dfd57
diff --git a/src/Filee.App/Controls/CropCanvas.cs b/src/Filee.App/Controls/CropCanvas.cs
index 7d756a49..1ec71590 100644
--- a/src/Filee.App/Controls/CropCanvas.cs
+++ b/src/Filee.App/Controls/CropCanvas.cs
@@ -225,7 +225,7 @@ public sealed class CropCanvas : Control
// 4. Draw Crop Rectangle Border
context.DrawRectangle(null, CropBorderPen, crop);
- // 5. Draw macOS Native Style Corner Brackets and Edge Bars
+ // 5. Corner brackets and edge bars
DrawCornerBracket(context, crop.TopLeft, 1, 1);
DrawCornerBracket(context, crop.TopRight, -1, 1);
DrawCornerBracket(context, crop.BottomLeft, 1, -1);
diff --git a/src/Filee.App/Services/CropService.cs b/src/Filee.App/Services/CropService.cs
index f25e7e34..e3a72ce1 100644
--- a/src/Filee.App/Services/CropService.cs
+++ b/src/Filee.App/Services/CropService.cs
@@ -134,9 +134,6 @@ public static class CropService
image.SetProfile(exif);
}
- if (appliedPreset.Image.Quality is > 0 and <= 100)
- image.Quality = (uint)appliedPreset.Image.Quality;
-
image.Write(outputPath);
if (appliedPreset.Output.KeepDates || store.Settings.KeepFileDates)
@@ -154,6 +151,11 @@ public static class CropService
return new CropResult(CropStatus.Success, outputPath, null, null);
}
+ catch (NotSupportedException ex)
+ {
+ log?.LogInformation(ex, "Not cropping {File}", inputPath);
+ return new CropResult(CropStatus.Failed, null, "error.unsupported_source", null);
+ }
catch (Exception ex)
{
log?.LogError(ex, "Failed to crop {File}", inputPath);
diff --git a/src/Filee.App/ViewModels/CropOverlayViewModel.cs b/src/Filee.App/ViewModels/CropOverlayViewModel.cs
index 97b662c8..f2484717 100644
--- a/src/Filee.App/ViewModels/CropOverlayViewModel.cs
+++ b/src/Filee.App/ViewModels/CropOverlayViewModel.cs
@@ -1,5 +1,6 @@
// State of the interactive crop overlay.
+using System.Collections.ObjectModel;
using System.IO;
using Avalonia;
using Avalonia.Media.Imaging;
@@ -28,6 +29,10 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable
private readonly List<HistoryFailure> _failures = [];
private bool _historyRecorded;
+ // Set when the window closes. A crop or preview load still running then finishes without touching the closed
+ // view (its bitmap disposed, no next file) and records the history with its output.
+ private bool _closed;
+
[ObservableProperty] private int _currentIndex;
[ObservableProperty] private string _currentFileName = "";
[ObservableProperty] private string _counterText = "";
@@ -52,6 +57,21 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable
public bool HasStatusNotice => !string.IsNullOrWhiteSpace(StatusNotice);
+ /// <summary>
+ /// All files are done and some failed or were skipped: the overlay stays open on <see cref="Summary"/> and
+ /// <see cref="Problems"/> until the user closes it, so a problem with the last (or only) file is seen too.
+ /// </summary>
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(IsEditing))]
+ private bool _isFinished;
+
+ public bool IsEditing => !IsFinished;
+
+ [ObservableProperty] private string _summary = "";
+
+ /// <summary>"file: reason" for each file that failed or was skipped.</summary>
+ public ObservableCollection<string> Problems { get; } = [];
+
public bool IsAspectFree => SelectedAspect == "free";
public bool IsAspectOriginal => SelectedAspect == "original";
public bool IsAspectSquare => SelectedAspect == "1:1";
@@ -93,6 +113,12 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable
try
{
var (bitmap, origW, origH) = await CropService.LoadPreviewAsync(path);
+ if (_closed)
+ {
+ bitmap.Dispose();
+ RecordHistoryOnce();
+ return;
+ }
var old = PreviewImage;
PreviewImage = bitmap;
old?.Dispose();
@@ -109,15 +135,15 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable
catch (Exception ex)
{
_log?.LogError(ex, "Failed to load preview for {File}", path);
- _processedSources.Add(path);
- var errKey = ex is NotSupportedException ? "error.unsupported_source" : "error.conversion_failed";
- _failures.Add(new HistoryFailure
+ if (_closed)
{
- Source = path,
- ErrorKey = errKey,
- ErrorDetail = ex.Message,
- });
- StatusNotice = $"{Path.GetFileName(path)}: {_loc[errKey]}";
+ RecordHistoryOnce();
+ return;
+ }
+ _processedSources.Add(path);
+ // The animated / multi-frame check throws NotSupportedException: its English message stays in the log.
+ var unsupported = ex is NotSupportedException;
+ AddFailure(path, unsupported ? "error.unsupported_source" : "error.conversion_failed", unsupported ? null : ex.Message);
if (index < _files.Count - 1)
await LoadFileAsync(index + 1);
@@ -141,7 +167,7 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable
[RelayCommand]
public async Task CropAndSaveAsync()
{
- if (IsBusy || CurrentIndex >= _files.Count)
+ if (IsBusy || IsFinished || _closed || CurrentIndex >= _files.Count)
return;
IsBusy = true;
@@ -157,46 +183,27 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable
{
var result = await CropService.CropFileAsync(path, x, y, w, h, _preset, _store, _loc, _log);
if (result.Status == CropStatus.Success && result.OutputPath is not null)
- {
_outputs.Add(result.OutputPath);
- }
else if (result.Status == CropStatus.SkippedExists)
- {
- _failures.Add(new HistoryFailure
- {
- Source = path,
- ErrorKey = result.ErrorKey,
- ErrorDetail = result.ErrorDetail,
- });
- StatusNotice = $"{Path.GetFileName(path)}: {_loc["toast.skipped"]}";
- }
+ AddProblem(path, "toast.skipped"); // as in the job queue: skipped counts as done, not as a failure
else
- {
- _failures.Add(new HistoryFailure
- {
- Source = path,
- ErrorKey = result.ErrorKey ?? "error.conversion_failed",
- ErrorDetail = result.ErrorDetail,
- });
- StatusNotice = $"{Path.GetFileName(path)}: {_loc["error.conversion_failed"]}";
- }
+ AddFailure(path, result.ErrorKey ?? "error.conversion_failed", result.ErrorDetail);
}
catch (Exception ex)
{
_log?.LogError(ex, "Failed to crop {File}", path);
- _failures.Add(new HistoryFailure
- {
- Source = path,
- ErrorKey = "error.conversion_failed",
- ErrorDetail = ex.Message,
- });
- StatusNotice = $"{Path.GetFileName(path)}: {_loc["error.conversion_failed"]}";
+ AddFailure(path, "error.conversion_failed", ex.Message);
}
finally
{
IsBusy = false;
}
+ if (_closed)
+ {
+ RecordHistoryOnce();
+ return;
+ }
if (CurrentIndex < _files.Count - 1)
{
await LoadFileAsync(CurrentIndex + 1);
@@ -210,7 +217,7 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable
[RelayCommand]
public async Task SkipAsync()
{
- if (IsBusy)
+ if (IsBusy || IsFinished || _closed)
return;
if (CurrentIndex < _files.Count - 1)
@@ -228,10 +235,12 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable
ResetRequested?.Invoke();
}
+ /// <summary>Cancel, or Close once finished. A crop still saving finishes and goes into the history.</summary>
[RelayCommand]
public void Cancel()
{
- FinishAndClose();
+ Shutdown();
+ CloseRequested?.Invoke();
}
[RelayCommand]
@@ -251,10 +260,44 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable
AspectRatioChanged?.Invoke(ratio);
}
+ private void AddFailure(string path, string errorKey, string? detail)
+ {
+ _failures.Add(new HistoryFailure { Source = path, ErrorKey = errorKey, ErrorDetail = detail });
+ AddProblem(path, errorKey);
+ }
+
+ private void AddProblem(string path, string key)
+ {
+ var line = $"{Path.GetFileName(path)}: {_loc[key]}";
+ Problems.Add(line);
+ StatusNotice = line;
+ }
+
+ /// <summary>Closes after the last file, or stays open on the summary when a file failed or was skipped.</summary>
private void FinishAndClose()
{
RecordHistoryOnce();
- CloseRequested?.Invoke();
+ if (Problems.Count == 0)
+ {
+ CloseRequested?.Invoke();
+ return;
+ }
+ Summary = _failures.Count > 0
+ ? _loc.Format("toast.done_errors", _failures.Count, _processedSources.Count)
+ : _loc["toast.done"];
+ StatusNotice = "";
+ HasMultipleFiles = false;
+ var old = PreviewImage;
+ PreviewImage = null;
+ old?.Dispose();
+ IsFinished = true;
+ }
+
+ private void Shutdown()
+ {
+ _closed = true;
+ if (!IsBusy)
+ RecordHistoryOnce();
}
private void RecordHistoryOnce()
@@ -277,13 +320,14 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable
Sources = [.. _processedSources],
Outputs = [.. _outputs],
Failures = [.. _failures],
- Preset = _failures.Count > 0 ? _preset.Clone() : null,
+ // No Retry on Home: it would run the preset through ConversionService, which doesn't run tools.
+ Preset = null,
});
}
public void Dispose()
{
- RecordHistoryOnce();
+ Shutdown();
PreviewImage?.Dispose();
PreviewImage = null;
}
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 2794f93c..446dcd31 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -161,7 +161,6 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public string PresetId => _original.Id;
public bool IsTool => _original.IsTool;
public bool CanChangeTarget => !IsTool;
- public bool ShowImageTools => !IsTool;
public IReadOnlyList<Choice<string>> Targets { get; }
public IReadOnlyList<Choice<ResizeMode>> ResizeModes { get; }
@@ -392,12 +391,13 @@ public sealed partial class PresetEditorViewModel : ObservableObject
private bool TargetIsLossyMedia => TargetIsVideo
|| (TargetIsAudio && !LosslessAudioTargets.Contains(TargetId) && MediaCodecs.Effective(TargetId, _audioCodecValue) != AudioCodec.Alac);
- public bool ShowImage => TargetIsImage;
+ /// <summary>A tool (Crop) keeps the source as it is: none of the image options apply.</summary>
+ public bool ShowImage => !IsTool && TargetIsImage;
/// <summary>Images and PDFs (pictures placed on pages) can be turned and flipped.</summary>
private bool CanTurn => TargetIsImage || TargetId == "pdf";
/// <summary>Rotate and flip for a PDF target, which has no image card to show them in.</summary>
public bool ShowTurnForPdf => TargetId == "pdf";
- public bool ShowQuality => TargetId == BuiltInData.SameAsSource || LossyTargets.Contains(TargetId);
+ public bool ShowQuality => !IsTool && (TargetId == BuiltInData.SameAsSource || LossyTargets.Contains(TargetId));
public bool ShowTiff => TargetId is "tiff" or BuiltInData.SameAsSource;
public bool ShowWebp => TargetId is "webp" or BuiltInData.SameAsSource;
public bool ShowMultiPageTiff => TargetId is "tiff";
diff --git a/src/Filee.App/Views/CropOverlayWindow.axaml b/src/Filee.App/Views/CropOverlayWindow.axaml
index 15fa44ae..08712329 100644
--- a/src/Filee.App/Views/CropOverlayWindow.axaml
+++ b/src/Filee.App/Views/CropOverlayWindow.axaml
@@ -58,15 +58,17 @@
<StackPanel Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
<PathIcon Width="16" Height="16" Data="{StaticResource Icon.Crop}" Foreground="{DynamicResource AccentBrush}" />
<TextBlock Text="{DynamicResource preset.crop}" FontWeight="SemiBold" FontSize="14" Foreground="{DynamicResource TextPrimaryBrush}" />
- <TextBlock Text="—" Foreground="{DynamicResource TextSecondaryBrush}" />
- <TextBlock Text="{Binding CurrentFileName}" FontSize="13" Foreground="{DynamicResource TextSecondaryBrush}" TextTrimming="CharacterEllipsis" MaxWidth="360" />
+ <TextBlock Text="—" Foreground="{DynamicResource TextSecondaryBrush}" IsVisible="{Binding IsEditing}" />
+ <TextBlock Text="{Binding CurrentFileName}" IsVisible="{Binding IsEditing}" FontSize="13" Foreground="{DynamicResource TextSecondaryBrush}" TextTrimming="CharacterEllipsis" MaxWidth="360" />
<Border IsVisible="{Binding HasMultipleFiles}" Background="{DynamicResource AccentSoftBrush}" CornerRadius="10" Padding="8,2">
<TextBlock Text="{Binding CounterText}" FontSize="11" Foreground="{DynamicResource TextPrimaryBrush}" />
</Border>
- <Border IsVisible="{Binding HasStatusNotice}" Background="{DynamicResource CardShadow}" CornerRadius="10" Padding="8,2">
- <TextBlock Text="{Binding StatusNotice}" FontSize="11" Foreground="{DynamicResource TextSecondaryBrush}" />
+ <Border IsVisible="{Binding HasStatusNotice}" Background="{DynamicResource SurfaceBrush}"
+ BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1" CornerRadius="10" Padding="8,2">
+ <TextBlock Text="{Binding StatusNotice}" FontSize="11" Foreground="{DynamicResource TextSecondaryBrush}"
+ TextTrimming="CharacterEllipsis" MaxWidth="320" />
</Border>
</StackPanel>
</DockPanel>
@@ -77,7 +79,9 @@
Background="{DynamicResource SurfaceAltBrush}">
<DockPanel>
<!-- Action Buttons on the Right -->
- <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Spacing="8" VerticalAlignment="Center">
+ <Button DockPanel.Dock="Right" Content="{DynamicResource common.close}" Command="{Binding CancelCommand}"
+ IsVisible="{Binding IsFinished}" IsDefault="{Binding IsFinished}" Classes="accent" FontWeight="SemiBold" Padding="14,6" CornerRadius="6" />
+ <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Spacing="8" VerticalAlignment="Center" IsVisible="{Binding IsEditing}">
<Button Content="{DynamicResource crop.reset}" Command="{Binding ResetCommand}"
Classes="aspect" />
<Button Content="{DynamicResource crop.skip}" Command="{Binding SkipCommand}"
@@ -85,11 +89,11 @@
<Button Content="{DynamicResource common.cancel}" Command="{Binding CancelCommand}"
IsCancel="True" Classes="aspect" />
<Button Content="{DynamicResource crop.save}" Command="{Binding CropAndSaveCommand}"
- IsDefault="True" Classes="accent" FontWeight="SemiBold" Padding="14,6" CornerRadius="6" />
+ IsDefault="{Binding IsEditing}" Classes="accent" FontWeight="SemiBold" Padding="14,6" CornerRadius="6" />
</StackPanel>
<!-- Aspect ratio selector on the Left -->
- <StackPanel Orientation="Horizontal" Spacing="6" VerticalAlignment="Center">
+ <StackPanel Orientation="Horizontal" Spacing="6" VerticalAlignment="Center" IsVisible="{Binding IsEditing}">
<TextBlock Text="{DynamicResource crop.aspect_title}" VerticalAlignment="Center" FontSize="12" Foreground="{DynamicResource TextSecondaryBrush}" Margin="0,0,2,0" />
<Button Classes="aspect" Classes.active="{Binding IsAspectFree}" Content="{DynamicResource crop.aspect_free}" Command="{Binding SetAspectCommand}" CommandParameter="free" />
<Button Classes="aspect" Classes.active="{Binding IsAspectSquare}" Content="1:1" Command="{Binding SetAspectCommand}" CommandParameter="1:1" />
@@ -109,7 +113,25 @@
<c:CropCanvas x:Name="Canvas"
SourceImage="{Binding PreviewImage}"
HorizontalAlignment="Stretch"
- VerticalAlignment="Stretch" />
+ VerticalAlignment="Stretch" IsVisible="{Binding IsEditing}" />
+
+ <!-- After the last file, when files failed or were skipped -->
+ <Border IsVisible="{Binding IsFinished}" HorizontalAlignment="Center" VerticalAlignment="Center" MaxWidth="560" Margin="24"
+ Background="{DynamicResource SurfaceBrush}" BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1"
+ CornerRadius="{DynamicResource SoftRadius}" Padding="20,16">
+ <StackPanel Spacing="10">
+ <TextBlock Text="{Binding Summary}" FontWeight="SemiBold" FontSize="14" Foreground="{DynamicResource TextPrimaryBrush}" />
+ <ScrollViewer MaxHeight="320">
+ <ItemsControl ItemsSource="{Binding Problems}">
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="x:String">
+ <TextBlock Text="{Binding}" FontSize="12" Margin="0,2" TextWrapping="Wrap" Foreground="{DynamicResource TextSecondaryBrush}" />
+ </DataTemplate>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+ </ScrollViewer>
+ </StackPanel>
+ </Border>
<!-- Loading spinner / busy indicator -->
<Border IsVisible="{Binding IsBusy}" Background="#44000000" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 824c4934..be17c37f 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -49,82 +49,80 @@
</DockPanel>
<Slider Minimum="1" Maximum="100" Value="{Binding Quality}" TickFrequency="1" IsSnapToTickEnabled="True" />
</StackPanel>
- <StackPanel Spacing="10" IsVisible="{Binding ShowImageTools}">
- <Grid ColumnDefinitions="*,12,*">
- <StackPanel>
- <TextBlock Classes="label" Text="{DynamicResource presets.resize}" />
- <ComboBox ItemsSource="{Binding ResizeModes}" SelectedItem="{Binding Resize}" HorizontalAlignment="Stretch" />
- </StackPanel>
- <StackPanel Grid.Column="2" IsVisible="{Binding ShowPercent}">
- <TextBlock Classes="label" Text="{DynamicResource presets.percent}" />
- <NumericUpDown Value="{Binding ResizePercent}" Minimum="1" Maximum="1000" Increment="5" FormatString="0" />
- </StackPanel>
- <StackPanel Grid.Column="2" IsVisible="{Binding ShowLongEdge}">
- <TextBlock Classes="label" Text="{DynamicResource presets.long_edge}" />
- <NumericUpDown Value="{Binding LongEdge}" Minimum="16" Maximum="20000" Increment="100" FormatString="0" />
- </StackPanel>
- <StackPanel Grid.Column="2" IsVisible="{Binding ShowWidth}">
- <TextBlock Classes="label" Text="{DynamicResource presets.width}" />
- <NumericUpDown Value="{Binding Width}" Minimum="16" Maximum="20000" Increment="100" FormatString="0" />
- </StackPanel>
- </Grid>
- <Grid ColumnDefinitions="*,12,*">
- <StackPanel>
- <TextBlock Classes="label" Text="{DynamicResource presets.rotation}" />
- <ComboBox ItemsSource="{Binding Rotations}" SelectedItem="{Binding Rotation}" HorizontalAlignment="Stretch" />
- </StackPanel>
- <StackPanel Grid.Column="2">
- <TextBlock Classes="label" Text="{DynamicResource presets.flip}" />
- <ComboBox ItemsSource="{Binding Flips}" SelectedItem="{Binding Flip}" HorizontalAlignment="Stretch" />
- </StackPanel>
- </Grid>
- <Grid ColumnDefinitions="Auto,12,*">
- <CheckBox Content="{DynamicResource presets.dpi}" IsChecked="{Binding SetDpi}" />
- <NumericUpDown Grid.Column="2" Value="{Binding Dpi}" Minimum="36" Maximum="2400" Increment="50" FormatString="0" IsEnabled="{Binding SetDpi}" />
- </Grid>
- <WrapPanel>
- <CheckBox Content="{DynamicResource presets.keep_metadata}" IsChecked="{Binding KeepMetadata}" Margin="0,0,18,0" />
- <CheckBox Content="{DynamicResource presets.keep_color_profile}" IsChecked="{Binding ColorProfileChecked}"
- IsEnabled="{Binding CanChangeColorProfile}" ToolTip.Tip="{DynamicResource presets.keep_color_profile_hint}" ToolTip.ShowOnDisabled="True" Margin="0,0,18,0" />
- <CheckBox Content="{DynamicResource presets.grayscale}" IsChecked="{Binding Grayscale}" Margin="0,0,18,0" />
- <CheckBox Content="{DynamicResource presets.webp_lossless}" IsChecked="{Binding WebpLossless}" IsVisible="{Binding ShowWebp}" />
- </WrapPanel>
- <CheckBox Content="{DynamicResource presets.remove_background}" IsChecked="{Binding RemoveBackground}"
- ToolTip.Tip="{DynamicResource presets.remove_background_hint}" />
- <StackPanel Spacing="6" IsVisible="{Binding RemoveBackground}">
- <DockPanel>
- <TextBlock DockPanel.Dock="Right" Text="{Binding BackgroundTolerance}" FontWeight="SemiBold" />
- <TextBlock Classes="label" Text="{DynamicResource presets.background_tolerance}" />
- </DockPanel>
- <Slider Minimum="0" Maximum="100" Value="{Binding BackgroundTolerance}" TickFrequency="1" IsSnapToTickEnabled="True"
- ToolTip.Tip="{DynamicResource presets.background_tolerance_hint}" />
- <CheckBox Content="{DynamicResource presets.keep_enclosed_background}" IsChecked="{Binding KeepEnclosedBackground}"
- ToolTip.Tip="{DynamicResource presets.keep_enclosed_background_hint}" />
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.resize}" />
+ <ComboBox ItemsSource="{Binding ResizeModes}" SelectedItem="{Binding Resize}" HorizontalAlignment="Stretch" />
</StackPanel>
- <Grid ColumnDefinitions="*,12,*">
- <StackPanel>
- <TextBlock Classes="label" Text="{DynamicResource presets.background}" />
- <TextBox Text="{Binding Background}" PlaceholderText="#FFFFFF" />
- </StackPanel>
- <StackPanel Grid.Column="2" IsVisible="{Binding ShowTiff}">
- <TextBlock Classes="label" Text="{DynamicResource presets.tiff_compression}" />
- <ComboBox ItemsSource="{Binding TiffCompressions}" SelectedItem="{Binding TiffCompression}" HorizontalAlignment="Stretch" />
- </StackPanel>
- <StackPanel Grid.Column="2" IsVisible="{Binding ShowIco}">
- <TextBlock Classes="label" Text="{DynamicResource presets.ico_sizes}" />
- <TextBox Text="{Binding IcoSizes}" PlaceholderText="256, 64, 48, 32, 16" />
- </StackPanel>
- </Grid>
- <Grid ColumnDefinitions="*,12,*" IsVisible="{Binding ShowAnimationSpeed}">
- <StackPanel>
- <TextBlock Classes="label" Text="{DynamicResource presets.animation_speed}" />
- <ComboBox ItemsSource="{Binding AnimationSpeeds}" SelectedItem="{Binding AnimationSpeed}" HorizontalAlignment="Stretch"
- ToolTip.Tip="{DynamicResource presets.animation_speed_hint}" />
- </StackPanel>
- </Grid>
- <CheckBox Content="{DynamicResource presets.multipage_tiff}" IsChecked="{Binding MultiPageTiff}" IsVisible="{Binding ShowMultiPageTiff}"
- ToolTip.Tip="{DynamicResource presets.multipage_tiff_hint}" />
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowPercent}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.percent}" />
+ <NumericUpDown Value="{Binding ResizePercent}" Minimum="1" Maximum="1000" Increment="5" FormatString="0" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowLongEdge}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.long_edge}" />
+ <NumericUpDown Value="{Binding LongEdge}" Minimum="16" Maximum="20000" Increment="100" FormatString="0" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowWidth}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.width}" />
+ <NumericUpDown Value="{Binding Width}" Minimum="16" Maximum="20000" Increment="100" FormatString="0" />
+ </StackPanel>
+ </Grid>
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.rotation}" />
+ <ComboBox ItemsSource="{Binding Rotations}" SelectedItem="{Binding Rotation}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel Grid.Column="2">
+ <TextBlock Classes="label" Text="{DynamicResource presets.flip}" />
+ <ComboBox ItemsSource="{Binding Flips}" SelectedItem="{Binding Flip}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ </Grid>
+ <Grid ColumnDefinitions="Auto,12,*">
+ <CheckBox Content="{DynamicResource presets.dpi}" IsChecked="{Binding SetDpi}" />
+ <NumericUpDown Grid.Column="2" Value="{Binding Dpi}" Minimum="36" Maximum="2400" Increment="50" FormatString="0" IsEnabled="{Binding SetDpi}" />
+ </Grid>
+ <WrapPanel>
+ <CheckBox Content="{DynamicResource presets.keep_metadata}" IsChecked="{Binding KeepMetadata}" Margin="0,0,18,0" />
+ <CheckBox Content="{DynamicResource presets.keep_color_profile}" IsChecked="{Binding ColorProfileChecked}"
+ IsEnabled="{Binding CanChangeColorProfile}" ToolTip.Tip="{DynamicResource presets.keep_color_profile_hint}" ToolTip.ShowOnDisabled="True" Margin="0,0,18,0" />
+ <CheckBox Content="{DynamicResource presets.grayscale}" IsChecked="{Binding Grayscale}" Margin="0,0,18,0" />
+ <CheckBox Content="{DynamicResource presets.webp_lossless}" IsChecked="{Binding WebpLossless}" IsVisible="{Binding ShowWebp}" />
+ </WrapPanel>
+ <CheckBox Content="{DynamicResource presets.remove_background}" IsChecked="{Binding RemoveBackground}"
+ ToolTip.Tip="{DynamicResource presets.remove_background_hint}" />
+ <StackPanel Spacing="6" IsVisible="{Binding RemoveBackground}">
+ <DockPanel>
+ <TextBlock DockPanel.Dock="Right" Text="{Binding BackgroundTolerance}" FontWeight="SemiBold" />
+ <TextBlock Classes="label" Text="{DynamicResource presets.background_tolerance}" />
+ </DockPanel>
+ <Slider Minimum="0" Maximum="100" Value="{Binding BackgroundTolerance}" TickFrequency="1" IsSnapToTickEnabled="True"
+ ToolTip.Tip="{DynamicResource presets.background_tolerance_hint}" />
+ <CheckBox Content="{DynamicResource presets.keep_enclosed_background}" IsChecked="{Binding KeepEnclosedBackground}"
+ ToolTip.Tip="{DynamicResource presets.keep_enclosed_background_hint}" />
</StackPanel>
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.background}" />
+ <TextBox Text="{Binding Background}" PlaceholderText="#FFFFFF" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowTiff}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.tiff_compression}" />
+ <ComboBox ItemsSource="{Binding TiffCompressions}" SelectedItem="{Binding TiffCompression}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowIco}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.ico_sizes}" />
+ <TextBox Text="{Binding IcoSizes}" PlaceholderText="256, 64, 48, 32, 16" />
+ </StackPanel>
+ </Grid>
+ <Grid ColumnDefinitions="*,12,*" IsVisible="{Binding ShowAnimationSpeed}">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.animation_speed}" />
+ <ComboBox ItemsSource="{Binding AnimationSpeeds}" SelectedItem="{Binding AnimationSpeed}" HorizontalAlignment="Stretch"
+ ToolTip.Tip="{DynamicResource presets.animation_speed_hint}" />
+ </StackPanel>
+ </Grid>
+ <CheckBox Content="{DynamicResource presets.multipage_tiff}" IsChecked="{Binding MultiPageTiff}" IsVisible="{Binding ShowMultiPageTiff}"
+ ToolTip.Tip="{DynamicResource presets.multipage_tiff_hint}" />
<StackPanel Spacing="6" IsVisible="{Binding ShowSaveEveryFrame}">
<CheckBox Content="{DynamicResource presets.save_every_frame}" IsChecked="{Binding SaveEveryFrame}"
ToolTip.Tip="{DynamicResource presets.save_every_frame_hint}" />
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index 1743bb8d..ee1645fa 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -18,7 +18,8 @@ public enum PresetKind
Group,
/// <summary>
- /// An interactive zero-window desktop tool (such as Crop) that opens an on-screen HUD upon drop.
+ /// Opens its own window on the dropped files instead of converting them (the interactive Crop). Like a group,
+ /// never offered where a conversion is picked.
/// </summary>
Tool,
}
diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csproj
index 2da7d6ac..a0219929 100644
--- a/src/Filee.Engines/Filee.Engines.csproj
+++ b/src/Filee.Engines/Filee.Engines.csproj
@@ -37,8 +37,6 @@
<ItemGroup>
<InternalsVisibleTo Include="Filee" />
- <InternalsVisibleTo Include="Filee.App" />
- <InternalsVisibleTo Include="Filee.App.Tests" />
<InternalsVisibleTo Include="Filee.Engines.Tests" />
</ItemGroup>
diff --git a/tests/Filee.App.Tests/CropServiceTests.cs b/tests/Filee.App.Tests/CropServiceTests.cs
index 9989d3a9..fd8fc69e 100644
--- a/tests/Filee.App.Tests/CropServiceTests.cs
+++ b/tests/Filee.App.Tests/CropServiceTests.cs
@@ -1,8 +1,11 @@
-// Tests for CropService: output resolving, conflict policies, and thumbnail handling.
+// Tests for CropService and the crop overlay: output resolving, conflict policies, quality, failures and skips.
using System.IO;
using Avalonia.Headless.XUnit;
+using Avalonia.Threading;
using Filee.App.Services;
+using Filee.App.ViewModels;
+using Filee.Core.Conversion;
using Filee.Core.Localization;
using Filee.Core.Presets;
using Filee.Core.Settings;
@@ -97,4 +100,134 @@ public class CropServiceTests
try { Directory.Delete(folder, true); } catch (IOException) { }
}
}
+
+ [AvaloniaFact]
+ public async Task CropFileAsync_keeps_the_sources_quality()
+ {
+ TestServices.EnsureInitialized("en");
+ var folder = Directory.CreateTempSubdirectory("filee-crop-quality-").FullName;
+ try
+ {
+ var store = AppHost.Get<UserDataStore>();
+ var loc = AppHost.Get<ILocalizer>();
+ var preset = BuiltInData.CreatePresets().Single(p => p.Id == "tool-crop");
+
+ // A JPEG saved at 75 isn't saved again at a higher quality.
+ var jpeg = Path.Combine(folder, "photo.jpg");
+ using (var image = new MagickImage("plasma:", 120, 90))
+ {
+ image.Quality = 75;
+ image.Write(jpeg, MagickFormat.Jpeg);
+ }
+ var jpegResult = await CropService.CropFileAsync(jpeg, 10, 10, 60, 40, preset, store, loc);
+ Assert.Equal(CropStatus.Success, jpegResult.Status);
+ using (var cropped = new MagickImage(jpegResult.OutputPath!))
+ Assert.InRange(cropped.Quality, 73u, 77u);
+
+ // A lossless WebP (VP8L) stays lossless instead of becoming lossy (VP8).
+ var webp = Path.Combine(folder, "logo.webp");
+ using (var image = new MagickImage("plasma:", 120, 90))
+ {
+ image.Settings.SetDefine(MagickFormat.WebP, "lossless", true);
+ image.Write(webp, MagickFormat.WebP);
+ }
+ Assert.True(IsLosslessWebp(webp));
+ var webpResult = await CropService.CropFileAsync(webp, 10, 10, 60, 40, preset, store, loc);
+ Assert.Equal(CropStatus.Success, webpResult.Status);
+ Assert.True(IsLosslessWebp(webpResult.OutputPath!));
+ }
+ finally
+ {
+ try { Directory.Delete(folder, true); } catch (IOException) { }
+ }
+ }
+
+ /// <summary>True when the WebP's image chunk is VP8L (lossless), not VP8 (lossy).</summary>
+ private static bool IsLosslessWebp(string path)
+ {
+ var text = System.Text.Encoding.ASCII.GetString(File.ReadAllBytes(path));
+ return text.Contains("VP8L", StringComparison.Ordinal) && !text.Contains("VP8 ", StringComparison.Ordinal);
+ }
+
+ [AvaloniaFact]
+ public async Task An_only_file_that_cant_be_cropped_keeps_the_overlay_open_with_the_reason_and_no_retry()
+ {
+ TestServices.EnsureInitialized("en");
+ var folder = Directory.CreateTempSubdirectory("filee-crop-animated-").FullName;
+ try
+ {
+ var store = AppHost.Get<UserDataStore>();
+ var loc = AppHost.Get<ILocalizer>();
+ var gif = Path.Combine(folder, "spinner.gif");
+ using (var frames = new MagickImageCollection())
+ {
+ frames.Add(new MagickImage(MagickColors.Red, 40, 40));
+ frames.Add(new MagickImage(MagickColors.Blue, 40, 40));
+ frames.Write(gif, MagickFormat.Gif);
+ }
+ var preset = BuiltInData.CreatePresets().Single(p => p.Id == "tool-crop");
+
+ using var vm = new CropOverlayViewModel([gif], preset, loc, store);
+ var closed = false;
+ vm.CloseRequested += () => closed = true;
+ await WaitFor(() => vm.IsFinished);
+
+ Assert.False(closed);
+ Assert.Equal(["spinner.gif: " + loc["error.unsupported_source"]], vm.Problems);
+ var entry = store.History.First(h => h.Sources.Contains(gif));
+ Assert.Equal(JobState.Failed, entry.State);
+ var failure = Assert.Single(entry.Failures);
+ Assert.Equal("error.unsupported_source", failure.ErrorKey);
+ Assert.Null(failure.ErrorDetail); // the English exception text stays in the log
+ Assert.Null(entry.Preset); // Home offers no Retry: ConversionService doesn't run tools
+
+ vm.CancelCommand.Execute(null);
+ Assert.True(closed);
+ }
+ finally
+ {
+ try { Directory.Delete(folder, true); } catch (IOException) { }
+ }
+ }
+
+ [AvaloniaFact]
+ public async Task A_file_skipped_because_the_output_exists_is_shown_but_isnt_a_failure()
+ {
+ TestServices.EnsureInitialized("en");
+ var folder = Directory.CreateTempSubdirectory("filee-crop-skip-").FullName;
+ try
+ {
+ var store = AppHost.Get<UserDataStore>();
+ var loc = AppHost.Get<ILocalizer>();
+ var source = CreateTestImage(folder, "scan.png");
+ File.WriteAllBytes(Path.Combine(folder, "scan_cropped.png"), [0x89, 0x50, 0x4E, 0x47]);
+ var preset = BuiltInData.CreatePresets().Single(p => p.Id == "tool-crop");
+ preset.Output.Conflict = ConflictPolicy.Skip;
+
+ using var vm = new CropOverlayViewModel([source], preset, loc, store);
+ await WaitFor(() => !vm.IsBusy && vm.OriginalWidth > 0);
+ await vm.CropAndSaveAsync();
+
+ Assert.True(vm.IsFinished);
+ Assert.Equal(["scan.png: " + loc["toast.skipped"]], vm.Problems);
+ Assert.Equal(loc["toast.done"], vm.Summary);
+ var entry = store.History.First(h => h.Sources.Contains(source));
+ Assert.Equal(JobState.Completed, entry.State);
+ Assert.Empty(entry.Failures);
+ }
+ finally
+ {
+ try { Directory.Delete(folder, true); } catch (IOException) { }
+ }
+ }
+
+ private static async Task WaitFor(Func<bool> condition)
+ {
+ for (var i = 0; i < 500 && !condition(); i++)
+ {
+ Dispatcher.UIThread.RunJobs();
+ await Task.Delay(20);
+ }
+ Assert.True(condition());
+ }
}