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.

Downloads show their speed and size above the progress

KnifeLemone1021a0d90c5
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 1b800812..dc137a33 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -72,6 +72,10 @@ named like the file will be, so the donut picks the profile by extension without
is made: a picture without an extension stands as `.jpg` and a link without one isn't offered. `ConversionService.Start`
gives the job a `WebDropFetcher` (`ISourceFetcher`): `JobQueue` saves every source first (half of its progress), then
converts. Failures are per file (`error.web_*`), cancelling stops a download, and the job toast/ring shows both phases.
+While files are saved, a badge pops up above the donut's progress ring and above the toast's progress bar with the
+speed and the amounts ("2.4 MB/s · 12.3 / 48.0 MB", "· 2 of 3 files" for several): `FileResult.Transfer` holds each
+file's byte count, `ConversionJob.Transfer()` sums them, and `DownloadBadge` (App) averages the speed over the last
+second with the Engines page's `TransferRate` and units, rewritten four times a second and shown after 300 ms.
- **Where**: Settings → General → "Files dragged from a browser" (`AppSettings.BrowserDrops`): the user's Downloads
folder (`IPlatformServices.DownloadsFolder`: the shell's known folder on Windows, `XDG_DOWNLOAD_DIR` on Linux,
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index e602a09e..4b495398 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -67,6 +67,8 @@
"toast.skipped": "Skipped (file exists)",
"toast.open_folder": "Show",
"toast.cancel": "Cancel",
+ "download.badge": "{0}/s · {1}",
+ "download.badge_files": "{0} · {1} of {2} files",
"error.unsupported_source": "This file type isn't supported",
"error.empty_file": "The file is empty (0 bytes). A file made with “New” in the right-click menu stays empty until you open it in its app and save it",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index bf69ee05..449ee4e5 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -62,6 +62,8 @@
"toast.skipped": "Omitido (el archivo ya existe)",
"toast.open_folder": "Mostrar",
"toast.cancel": "Cancelar",
+ "download.badge": "{0}/s · {1}",
+ "download.badge_files": "{0} · {1} de {2} archivos",
"error.unsupported_source": "Este tipo de archivo no es compatible",
"error.empty_file": "El archivo está vacío (0 bytes). Un archivo creado con «Nuevo» en el menú contextual sigue vacío hasta que lo abres en su aplicación y lo guardas",
"format_request.request": "Solicitar este formato",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index 8c12b334..115b3bed 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -62,6 +62,8 @@
"toast.skipped": "छोड़ा गया (फ़ाइल पहले से मौजूद है)",
"toast.open_folder": "दिखाएँ",
"toast.cancel": "रद्द करें",
+ "download.badge": "{0}/s · {1}",
+ "download.badge_files": "{0} · {2} में से {1} फ़ाइल",
"error.unsupported_source": "यह फ़ाइल प्रकार समर्थित नहीं है",
"error.empty_file": "फ़ाइल खाली है (0 बाइट)। राइट-क्लिक मेनू के “नया” से बनाई गई फ़ाइल तब तक खाली रहती है, जब तक आप उसे उसके ऐप में खोलकर सेव न करें",
"format_request.request": "इस फ़ॉर्मैट का अनुरोध करें",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index 5c7d5646..da0bc691 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -62,6 +62,8 @@
"toast.skipped": "スキップしました(同名のファイルがあります)",
"toast.open_folder": "表示",
"toast.cancel": "キャンセル",
+ "download.badge": "{0}/秒 · {1}",
+ "download.badge_files": "{0} · {2}件中{1}件目",
"error.unsupported_source": "このファイル形式には対応していません",
"error.empty_file": "ファイルが空です(0バイト)。右クリックメニューの「新規作成」で作ったファイルは、対応アプリで開いて保存するまで空のままです",
"format_request.request": "この形式への対応をリクエスト",
@@ -76,6 +78,11 @@
"error.needs_shaping": "この文字体系の文書を正しく変換するにはLibreOfficeが必要です。「設定」→「変換エンジン」でインストールしてください",
"error.runtime_missing": "このエンジンに必要なMicrosoft Visual C++ランタイムのファイルがないか、古くなっています。Filee を更新または再インストールするか、Microsoft Visual C++ 再頒布可能パッケージ(x64)をインストールしてください",
"error.conversion_failed": "変換エンジンからエラーが報告されました",
+ "error.web_download_failed": "ファイルをダウンロードできませんでした",
+ "error.web_page": "リンク先はファイルではなくWebページです。ログインが必要なファイルは Filee ではダウンロードできないため、先にブラウザーで保存してください",
+ "error.web_too_large": "ファイルが2 GBを超えています",
+ "error.web_blocked": "プログラム、インストーラー、スクリプトは保存しません",
+ "error.web_timeout": "サーバーから応答がありません",
"error.geo_empty": "ファイルに地物がありません",
"error.geo_unknown_crs": "座標が経度・緯度ではなく、ファイルに座標系の情報もありません(Shapefileは.prjファイルと一緒に置いてください)",
"error.geo_unsupported_crs": "この座標系にはまだ対応していません",
@@ -225,6 +232,11 @@
"general.default_output_hint": "保存先が「既定の保存先」のプリセットは、ここに保存します。\n保存先を個別に指定したプリセットには適用されません。",
"general.keep_dates": "すべての変換で元ファイルの日付を保持する",
"general.keep_dates_hint": "どのプリセットでも、変換後のファイルは元ファイルの作成日時と更新日時を引き継ぎます。\nオフの場合は、「元ファイルの日付を保持する」を有効にしたプリセットだけに適用されます。",
+ "general.browser_drops": "ブラウザーからドラッグしたファイル",
+ "general.browser_drops_hint": "キーを押しながら Chrome、Edge、Firefox、Safari から画像、ファイルへのリンク、ダウンロードをドラッグすると、自分のファイルと同じようにドーナツメニューが開きます。ファイルはこのフォルダーに保存され、元ファイルと同じフォルダーに保存するプリセットの変換結果もここに保存されます。\nリンクは Filee が直接ダウンロードします。ブラウザーのログイン情報は使いません。",
+ "general.browser_drops_folder": "保存先",
+ "general.browser_drops_only_converted": "変換後のファイルだけを保存する",
+ "general.browser_drops_only_converted_hint": "元ファイルは一時フォルダーに置かれ、変換が終わると削除されます。",
"general.zip_geo": "地理空間データの変換結果はすべてZIPで保存する",
"general.zip_geo_hint": "どのプリセットでも、Shapefile、GeoJSON、KML、GPXなどの地理空間データの変換結果をファイルごとに1つのZIPにまとめます。\nオフの場合は、「変換結果をZIPで保存」を有効にしたプリセットだけに適用されます。",
"general.check_updates": "更新を自動で確認",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 50d40276..65a2e51a 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -67,6 +67,8 @@
"toast.skipped": "건너뜀 (파일이 이미 있음)",
"toast.open_folder": "보기",
"toast.cancel": "취소",
+ "download.badge": "{0}/s · {1}",
+ "download.badge_files": "{0} · {2}개 중 {1}번째",
"error.unsupported_source": "지원하지 않는 파일 형식이에요",
"error.empty_file": "빈 파일이에요(0바이트). 우클릭 메뉴의 “새로 만들기”로 만든 파일은 앱에서 열어 저장해야 내용이 생겨요",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 3f23a6d1..705878b7 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -67,6 +67,8 @@
"toast.skipped": "Pominięto (plik istnieje)",
"toast.open_folder": "Pokaż",
"toast.cancel": "Anuluj",
+ "download.badge": "{0}/s · {1}",
+ "download.badge_files": "{0} · plik {1} z {2}",
"error.unsupported_source": "Ten typ pliku nie jest obsługiwany",
"error.empty_file": "Plik jest pusty (0 bajtów). Plik utworzony przez „Nowy” w menu kontekstowym pozostaje pusty, dopóki nie otworzysz go w jego aplikacji i nie zapiszesz",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index e0b8a6f6..aad3f9aa 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -67,6 +67,8 @@
"toast.skipped": "已跳过(文件已存在)",
"toast.open_folder": "查看",
"toast.cancel": "取消",
+ "download.badge": "{0}/s · {1}",
+ "download.badge_files": "{0} · 第 {1}/{2} 个文件",
"error.unsupported_source": "不支持此文件类型",
"error.empty_file": "文件是空的(0 字节)。用右键菜单“新建”创建的文件,要在对应的应用中打开并保存后才有内容",
diff --git a/src/Filee.App/Services/ConversionService.cs b/src/Filee.App/Services/ConversionService.cs
index 5d35256f..54f114f9 100644
--- a/src/Filee.App/Services/ConversionService.cs
+++ b/src/Filee.App/Services/ConversionService.cs
@@ -130,7 +130,7 @@ public sealed class ConversionService
{
try
{
- saved.Add(await fetcher.FetchAsync(placeholder, new Progress<double>(), CancellationToken.None));
+ saved.Add(await fetcher.FetchAsync(placeholder, new Progress<TransferProgress>(), CancellationToken.None));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
diff --git a/src/Filee.App/Services/RadialController.cs b/src/Filee.App/Services/RadialController.cs
index 41fa8e28..b9702ff0 100644
--- a/src/Filee.App/Services/RadialController.cs
+++ b/src/Filee.App/Services/RadialController.cs
@@ -341,6 +341,7 @@ public sealed class RadialController(
var donut = _window!.DonutControl;
_dropped = true;
_progressJob = job;
+ viewModel.ProgressJob = job;
_lastRingJob = job;
donut.BeginProgress();
donut.SetProgress(job.Progress / 100);
@@ -398,6 +399,7 @@ public sealed class RadialController(
if (_progressJob is not null)
_progressJob.PropertyChanged -= OnProgressJobChanged;
_progressJob = null;
+ viewModel.ProgressJob = null;
}
private void HideWindow()
diff --git a/src/Filee.App/ViewModels/DownloadBadge.cs b/src/Filee.App/ViewModels/DownloadBadge.cs
new file mode 100644
index 00000000..ec4843b7
--- /dev/null
+++ b/src/Filee.App/ViewModels/DownloadBadge.cs
@@ -0,0 +1,63 @@
+// The badge over a download's progress (the donut's ring, the toast): "2.4 MB/s · 12.3 / 48.0 MB", with "2 of 3
+// files" when several are saved. Amounts and speed use the Engines page's units and the user's decimal separator;
+// the speed is averaged over the last second and only shown once there is enough to tell.
+
+using Filee.App.Services;
+using Filee.Core.Conversion;
+using Filee.Core.Localization;
+using Filee.Engines.Infrastructure;
+
+namespace Filee.App.ViewModels;
+
+internal sealed class DownloadBadge(ILocalizer loc)
+{
+ /// <summary>How far back the speed is averaged.</summary>
+ public static readonly TimeSpan Window = TimeSpan.FromSeconds(1);
+
+ /// <summary>How long the download must run before the badge shows (a fast copy never shows one).</summary>
+ public static readonly TimeSpan Settle = TimeSpan.FromMilliseconds(300);
+
+ /// <summary>How often the badge is rewritten while it shows.</summary>
+ public static readonly TimeSpan Interval = TimeSpan.FromMilliseconds(250);
+
+ private readonly TransferRate _rate = new(Window, Settle);
+ private bool _measured;
+
+ /// <summary>
+ /// The badge's text for what the job saves at <paramref name="elapsed"/>, or null while it saves nothing or it is
+ /// too early to tell a speed.
+ /// </summary>
+ public string? Update(TimeSpan elapsed, JobTransfer? transfer)
+ {
+ if (transfer is not { } now)
+ return null;
+ _rate.Add(elapsed, now.Received);
+ _measured |= _rate.BytesPerSecond > 0;
+ return _measured ? Format(loc, _rate.BytesPerSecond, now) : null;
+ }
+
+ /// <summary>"2.4 MB/s · 12.3 / 48.0 MB", "2.4 MB/s · 12.3 MB" without a size, "… · 2 of 3 files" for several.</summary>
+ public static string Format(ILocalizer loc, double bytesPerSecond, JobTransfer transfer)
+ {
+ var text = loc.Format("download.badge", EnginePackageState.FormatAmount(bytesPerSecond), Amounts(transfer.Bytes, transfer.Total));
+ return transfer.Count > 1 ? loc.Format("download.badge_files", text, Math.Min(transfer.Saved + 1, transfer.Count), transfer.Count) : text;
+ }
+
+ /// <summary>"12.3 / 48.0 MB" (one unit when both share it), "850 KB / 1.20 GB", or "12.3 MB" without a total.</summary>
+ internal static string Amounts(long done, long? total)
+ {
+ var shown = EnginePackageState.FormatAmount(done);
+ if (total is not { } size)
+ return shown;
+ var whole = EnginePackageState.FormatAmount(size);
+ var (number, unit) = Split(shown);
+ var (_, wholeUnit) = Split(whole);
+ return unit == wholeUnit ? $"{number} / {whole}" : $"{shown} / {whole}";
+ }
+
+ private static (string Number, string Unit) Split(string amount)
+ {
+ var space = amount.LastIndexOf(' ');
+ return space < 0 ? (amount, "") : (amount[..space], amount[(space + 1)..]);
+ }
+}
diff --git a/src/Filee.App/ViewModels/JobViewModel.cs b/src/Filee.App/ViewModels/JobViewModel.cs
index 22704cdf..e5b06141 100644
--- a/src/Filee.App/ViewModels/JobViewModel.cs
+++ b/src/Filee.App/ViewModels/JobViewModel.cs
@@ -1,5 +1,7 @@
// One running / finished conversion as shown in the toast window.
+using System.Diagnostics;
+using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Filee.App.Services;
@@ -28,6 +30,39 @@ public sealed partial class JobViewModel : ObservableObject
var what = job.Sources.Count == 1 ? Path.GetFileName(job.Sources[0]) : loc.Format("home.files", job.Sources.Count);
Title = loc.Format("toast.converting", what, job.PresetDisplayName);
Refresh();
+ if (job.Fetcher is not null)
+ {
+ // Files from a browser are saved first: the speed and size badge, rewritten a few times a second.
+ _badge = new DownloadBadge(loc);
+ _badgeTimer = new DispatcherTimer(DownloadBadge.Interval, DispatcherPriority.Background, (_, _) => UpdateDownload(_badgeClock.Elapsed));
+ _badgeTimer.Start();
+ }
+ }
+
+ private readonly DownloadBadge? _badge;
+ private readonly DispatcherTimer? _badgeTimer;
+ private readonly Stopwatch _badgeClock = Stopwatch.StartNew();
+
+ /// <summary>
+ /// "2.4 MB/s · 12.3 / 48.0 MB" while the job downloads (saves files from a browser). The last text stays while the
+ /// badge pops out, so it doesn't go blank as it shrinks.
+ /// </summary>
+ [ObservableProperty] private string? _downloadText;
+
+ /// <summary>The download badge shows; false once the files are saved and converting starts.</summary>
+ [ObservableProperty] private bool _isDownloading;
+
+ /// <summary>Rewrites the download badge for <paramref name="elapsed"/> since the job was shown.</summary>
+ internal void UpdateDownload(TimeSpan elapsed)
+ {
+ if (_badge is null)
+ return;
+ var text = _badge.Update(elapsed, Job.Transfer());
+ if (text is not null)
+ DownloadText = text;
+ IsDownloading = text is not null;
+ if (Job.State is not (JobState.Queued or JobState.Running))
+ _badgeTimer?.Stop();
}
public ConversionJob Job { get; }
diff --git a/src/Filee.App/ViewModels/RadialViewModel.cs b/src/Filee.App/ViewModels/RadialViewModel.cs
index 37f25c5b..53ab6592 100644
--- a/src/Filee.App/ViewModels/RadialViewModel.cs
+++ b/src/Filee.App/ViewModels/RadialViewModel.cs
@@ -16,6 +16,9 @@ public sealed partial class RadialViewModel(UserDataStore store, ILocalizer loc,
[ObservableProperty] private IReadOnlyList<DonutItem> _items = [];
[ObservableProperty] private string _centerTitle = "";
[ObservableProperty] private string? _centerSubtitle;
+
+ /// <summary>The job the progress ring shows, for the download badge above it; null when the ring shows none.</summary>
+ [ObservableProperty] private JobViewModel? _progressJob;
[ObservableProperty] private double _outerRadius = 150;
[ObservableProperty] private double _holeRatio = 0.42;
[ObservableProperty] private double _sliceOpacity = 0.96;
diff --git a/src/Filee.App/Views/RadialWindow.axaml b/src/Filee.App/Views/RadialWindow.axaml
index 86c09bbb..d5ea3823 100644
--- a/src/Filee.App/Views/RadialWindow.axaml
+++ b/src/Filee.App/Views/RadialWindow.axaml
@@ -18,6 +18,26 @@
ShowActivated="False"
CanResize="False"
SizeToContent="WidthAndHeight">
+ <Window.Styles>
+ <!-- The download badge pops up above the progress ring and pops away once the files are saved. -->
+ <Style Selector="Border.download-badge">
+ <Setter Property="Opacity" Value="0" />
+ <Setter Property="RenderTransform" Value="scale(0.6)" />
+ <Setter Property="Transitions">
+ <Transitions>
+ <DoubleTransition Property="Opacity" Duration="0:0:0.16" />
+ <TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.22" Easing="BackEaseOut" />
+ </Transitions>
+ </Setter>
+ </Style>
+ <Style Selector="Border.download-badge.shown">
+ <Setter Property="Opacity" Value="1" />
+ <Setter Property="RenderTransform" Value="scale(1)" />
+ </Style>
+ <Style Selector="Window.reduced-motion Border.download-badge">
+ <Setter Property="Transitions" Value="{x:Null}" />
+ </Style>
+ </Window.Styles>
<Panel x:Name="Root" Background="{Binding HitBackground}" DragDrop.AllowDrop="True">
<c:DonutMenu x:Name="Donut"
Opacity="{Binding DonutOpacity}"
@@ -28,5 +48,14 @@
HoleRatio="{Binding HoleRatio}"
SliceOpacity="{Binding SliceOpacity}"
ReserveSubRing="{Binding ReserveSubRing}" />
+ <!-- Centred on the donut and lifted just above the ring (DonutMenu.RingRadius 36, its stroke and plate). -->
+ <Panel HorizontalAlignment="Center" VerticalAlignment="Center" IsHitTestVisible="False"
+ RenderTransform="translate(0px, -70px)">
+ <Border x:Name="DownloadBadge" Classes="download-badge" Classes.shown="{Binding ProgressJob.IsDownloading, FallbackValue=False}"
+ Background="{DynamicResource SurfaceBrush}" BorderBrush="{DynamicResource AccentBrush}" BorderThickness="1"
+ CornerRadius="{DynamicResource SoftRadius}" Padding="10,4" RenderTransformOrigin="50%,100%">
+ <TextBlock Text="{Binding ProgressJob.DownloadText, FallbackValue=''}" FontSize="12" FontWeight="SemiBold" />
+ </Border>
+ </Panel>
</Panel>
</Window>
diff --git a/src/Filee.App/Views/ToastWindow.axaml b/src/Filee.App/Views/ToastWindow.axaml
index 9d8498c9..b5585a8d 100644
--- a/src/Filee.App/Views/ToastWindow.axaml
+++ b/src/Filee.App/Views/ToastWindow.axaml
@@ -39,6 +39,32 @@
</Animation>
</Style.Animations>
</Style>
+ <!-- Download badge above the progress bar while files from a browser are saved: pops in, disappears when done. -->
+ <Style Selector="Border.download-badge">
+ <Style.Animations>
+ <Animation Duration="0:0:0.22" Easing="BackEaseOut" FillMode="Forward">
+ <KeyFrame Cue="0%">
+ <Setter Property="Opacity" Value="0" />
+ <Setter Property="ScaleTransform.ScaleX" Value="0.6" />
+ <Setter Property="ScaleTransform.ScaleY" Value="0.6" />
+ </KeyFrame>
+ <KeyFrame Cue="100%">
+ <Setter Property="Opacity" Value="1" />
+ <Setter Property="ScaleTransform.ScaleX" Value="1" />
+ <Setter Property="ScaleTransform.ScaleY" Value="1" />
+ </KeyFrame>
+ </Animation>
+ </Style.Animations>
+ </Style>
+ <Style Selector="Window.reduced-motion Border.download-badge">
+ <Style.Animations>
+ <Animation Duration="0:0:0.001" FillMode="Forward">
+ <KeyFrame Cue="100%">
+ <Setter Property="Opacity" Value="1" />
+ </KeyFrame>
+ </Animation>
+ </Style.Animations>
+ </Style>
<Style Selector="ProgressBar">
<Setter Property="CornerRadius" Value="999" />
<Setter Property="MinHeight" Value="6" />
@@ -62,6 +88,14 @@
</Button>
<TextBlock Text="{Binding Title}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
</DockPanel>
+ <Border Classes="download-badge" IsVisible="{Binding IsDownloading}" HorizontalAlignment="Left"
+ Background="{DynamicResource SurfaceBrush}" BorderBrush="{DynamicResource AccentBrush}" BorderThickness="1"
+ CornerRadius="{DynamicResource SoftRadius}" Padding="8,2" Margin="0,0,0,-4" RenderTransformOrigin="0%,100%">
+ <Border.RenderTransform>
+ <ScaleTransform />
+ </Border.RenderTransform>
+ <TextBlock Text="{Binding DownloadText}" FontSize="11" FontWeight="SemiBold" />
+ </Border>
<ProgressBar Value="{Binding Progress}" Maximum="100" IsVisible="{Binding IsRunning}" />
<DockPanel>
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Spacing="6">
diff --git a/src/Filee.Core/Conversion/ConversionJob.cs b/src/Filee.Core/Conversion/ConversionJob.cs
index 0d9d1ea2..df78b629 100644
--- a/src/Filee.Core/Conversion/ConversionJob.cs
+++ b/src/Filee.Core/Conversion/ConversionJob.cs
@@ -39,6 +39,15 @@ public sealed class FileResult
/// <summary>Localization key of the error (e.g. <c>error.no_route</c>), if any.</summary>
public string? ErrorKey { get; set; }
+ /// <summary>The job's fetcher saves this source first (a file from a browser).</summary>
+ public bool NeedsFetch { get; init; }
+
+ /// <summary>The fetcher has saved it (<see cref="SourcePath"/> is the saved file now).</summary>
+ public bool Saved { get; set; }
+
+ /// <summary>Bytes saved so far by the fetcher (the last count once it is saved); null before it starts.</summary>
+ public TransferProgress? Transfer { get; set; }
+
/// <summary>Raw error detail for logs / tooltips.</summary>
public string? ErrorDetail { get; set; }
@@ -60,7 +69,7 @@ public sealed class ConversionJob
Preset = preset.Clone(); // later edits of the preset must not affect a running job
PresetDisplayName = presetDisplayName;
Fetcher = fetcher;
- Files = sources.Select(s => new FileResult { SourcePath = s }).ToList();
+ Files = sources.Select(s => new FileResult { SourcePath = s, NeedsFetch = fetcher?.Fetches(s) ?? false }).ToList();
}
public string Id { get; } = Guid.NewGuid().ToString("N")[..10];
@@ -84,6 +93,24 @@ public sealed class ConversionJob
public CancellationToken CancellationToken => _cts.Token;
+ /// <summary>
+ /// What the job's fetcher is saving now, summed over the files being saved (several download at once), or null
+ /// when none is. The total is known only when every one of them says its size.
+ /// </summary>
+ public JobTransfer? Transfer()
+ {
+ var fetched = Files.Where(f => f.NeedsFetch)
+ // Read once: the queue's threads replace these values while the UI reads them.
+ .Select(f => (f.Transfer, f.Saved, Active: f.State == FileState.Running && !f.Saved))
+ .ToList();
+ var active = fetched.Where(f => f.Active).Select(f => f.Transfer).OfType<TransferProgress>().ToList();
+ if (active.Count == 0)
+ return null;
+ long? total = active.All(t => t.Total is not null) ? active.Sum(t => t.Total!.Value) : null;
+ return new JobTransfer(active.Sum(t => t.Bytes), total, fetched.Count(f => f.Saved), fetched.Count,
+ fetched.Sum(f => f.Transfer?.Bytes ?? 0));
+ }
+
/// <summary>Requests cancellation. Running engines stop as soon as they can.</summary>
public void Cancel() => _cts.Cancel();
}
@@ -99,7 +126,7 @@ public interface ISourceFetcher
/// <summary>Saves the file <paramref name="source"/> stands for and returns its path.</summary>
/// <exception cref="ConversionRefusedException">A reason the user can act on (a web page instead of a file, …).</exception>
- Task<string> FetchAsync(string source, IProgress<double> progress, CancellationToken cancellationToken);
+ Task<string> FetchAsync(string source, IProgress<TransferProgress> progress, CancellationToken cancellationToken);
/// <summary>
/// The job is over (finished, failed or cancelled before it ran): delete what only the conversion needed. Called
@@ -107,3 +134,18 @@ public interface ISourceFetcher
/// </summary>
void Release(ConversionJob job);
}
+
+/// <summary>How far saving one source has come: bytes so far, and the size when the source says it.</summary>
+public readonly record struct TransferProgress(long Bytes, long? Total)
+{
+ /// <summary>0..1, or null when the size isn't known.</summary>
+ public double? Fraction => Total is > 0 ? Math.Clamp((double)Bytes / Total.Value, 0, 1) : null;
+}
+
+/// <summary>What a job is saving now (see <see cref="ConversionJob.Transfer"/>).</summary>
+/// <param name="Bytes">Bytes saved so far by the files being saved.</param>
+/// <param name="Total">Their size together, or null when one of them doesn't say.</param>
+/// <param name="Saved">Files of the job already saved.</param>
+/// <param name="Count">Files of the job that are saved first.</param>
+/// <param name="Received">Every byte saved so far, finished files included: it only grows, for the speed.</param>
+public readonly record struct JobTransfer(long Bytes, long? Total, int Saved, int Count, long Received);
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 41ca46aa..638e1b64 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -141,22 +141,26 @@ public sealed class JobQueue : IAsyncDisposable
/// </summary>
private async Task FetchSourcesAsync(ConversionJob job, ISourceFetcher fetcher)
{
- var files = job.Files.Where(f => fetcher.Fetches(f.SourcePath)).ToList();
+ var files = job.Files.Where(f => f.NeedsFetch).ToList();
await Parallel.ForEachAsync(files, new ParallelOptions { MaxDegreeOfParallelism = 4 }, async (file, _) =>
{
file.State = FileState.Running;
+ file.Transfer = new TransferProgress(0, null);
Notify(job);
- var progress = new Progress<double>(p =>
+ var progress = new SyncProgress<TransferProgress>(p =>
{
- var value = Math.Clamp(p, 0, 1) * FetchShare;
- if (value <= file.Progress || file.State != FileState.Running)
+ if (file.State != FileState.Running || file.Saved)
return;
- file.Progress = value;
+ file.Transfer = p;
+ var value = (p.Fraction ?? 0) * FetchShare;
+ if (value > file.Progress)
+ file.Progress = value;
Notify(job);
});
try
{
file.SourcePath = await fetcher.FetchAsync(file.SourcePath, progress, job.CancellationToken);
+ file.Saved = true;
file.State = FileState.Pending;
file.Progress = FetchShare;
}
@@ -186,6 +190,15 @@ public sealed class JobQueue : IAsyncDisposable
}
}
+ /// <summary>
+ /// Reports on the reporting thread, in order: Progress&lt;T&gt; posts to the thread pool, where a late byte count could
+ /// land after the file was saved.
+ /// </summary>
+ private sealed class SyncProgress<T>(Action<T> report) : IProgress<T>
+ {
+ public void Report(T value) => report(value);
+ }
+
/// <summary>A file that didn't get as far as being converted (saving it failed or was cancelled).</summary>
private static bool Stopped(FileResult file) => file.State is FileState.Failed or FileState.Cancelled;
diff --git a/src/Filee.Core/Web/WebDownloader.cs b/src/Filee.Core/Web/WebDownloader.cs
index f92bbfff..57cc17fb 100644
--- a/src/Filee.Core/Web/WebDownloader.cs
+++ b/src/Filee.Core/Web/WebDownloader.cs
@@ -39,6 +39,9 @@ public sealed class WebDownloader : IDisposable
public int MaxRedirects { get; init; } = 5;
+ /// <summary>Least time between two progress reports while bytes arrive.</summary>
+ public TimeSpan ReportInterval { get; init; } = TimeSpan.FromMilliseconds(100);
+
/// <summary>How long the server may take to start answering.</summary>
public TimeSpan ResponseTimeout { get; init; } = TimeSpan.FromSeconds(30);
@@ -51,7 +54,7 @@ public sealed class WebDownloader : IDisposable
/// from the first bytes when they say what the file is.
/// </summary>
/// <exception cref="ConversionRefusedException">With the reason to show (<c>error.web_*</c>).</exception>
- public async Task<string> DownloadAsync(Uri url, string folder, string? suggestedName, IProgress<double>? progress,
+ public async Task<string> DownloadAsync(Uri url, string folder, string? suggestedName, IProgress<TransferProgress>? progress,
CancellationToken cancellationToken)
{
if (!IsWebAddress(url))
@@ -88,8 +91,19 @@ public sealed class WebDownloader : IDisposable
/// </param>
/// <exception cref="ConversionRefusedException">A program, a web page or a file over <see cref="MaxBytes"/>.</exception>
public async Task<string> SaveAsync(Stream source, string folder, string name, string? mime, long? length,
- IProgress<double>? progress, CancellationToken cancellationToken, bool refusePages = false)
+ IProgress<TransferProgress>? progress, CancellationToken cancellationToken, bool refusePages = false)
{
+ // Every chunk would flood the UI: a report at most every ReportInterval, and the last one always.
+ TimeSpan? lastReport = null;
+ var clock = System.Diagnostics.Stopwatch.StartNew();
+ void Report(long bytes, bool final = false)
+ {
+ if (progress is null || (!final && lastReport is { } last && clock.Elapsed - last < ReportInterval))
+ return;
+ lastReport = clock.Elapsed;
+ progress.Report(new TransferProgress(bytes, length is > 0 ? length : null));
+ }
+
var head = new byte[WebFormats.SniffLength];
var headLength = await ReadAtLeastAsync(source, head, cancellationToken);
if (WebFormats.LooksLikeProgram(head.AsSpan(0, headLength)))
@@ -108,6 +122,7 @@ public sealed class WebDownloader : IDisposable
{
await file.WriteAsync(head.AsMemory(0, headLength), cancellationToken);
long total = headLength;
+ Report(total);
var buffer = new byte[1 << 16];
while (true)
{
@@ -118,11 +133,10 @@ public sealed class WebDownloader : IDisposable
if (total > MaxBytes)
throw new ConversionRefusedException("error.web_too_large", Megabytes(total));
await file.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
- if (length is > 0)
- progress?.Report(Math.Min(1, (double)total / length.Value));
+ Report(total);
}
+ Report(total, final: true);
}
- progress?.Report(1);
return path;
}
catch
diff --git a/src/Filee.Core/Web/WebDrop.cs b/src/Filee.Core/Web/WebDrop.cs
index 27621cf6..e814806d 100644
--- a/src/Filee.Core/Web/WebDrop.cs
+++ b/src/Filee.Core/Web/WebDrop.cs
@@ -19,7 +19,7 @@ public abstract class WebDropItem : IDisposable
public string Name { get; }
/// <summary>Writes the file into <paramref name="folder"/> and returns its path.</summary>
- public abstract Task<string> SaveAsync(string folder, WebDownloader downloader, IProgress<double>? progress,
+ public abstract Task<string> SaveAsync(string folder, WebDownloader downloader, IProgress<TransferProgress>? progress,
CancellationToken cancellationToken);
public virtual void Dispose() => GC.SuppressFinalize(this);
@@ -40,7 +40,19 @@ public abstract class WebDropItem : IDisposable
public static WebDropItem FromTemporaryFile(string path) =>
new StreamItem(Path.GetFileName(path),
_ => Task.FromResult<Stream>(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 1 << 16, useAsync: true)),
- null, null, null);
+ SizeOf(path), null, null);
+
+ private static long? SizeOf(string path)
+ {
+ try
+ {
+ return new FileInfo(path).Length;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return null;
+ }
+ }
/// <summary>An address Filee downloads itself (without the browser's sign-in).</summary>
public static WebDropItem FromAddress(string name, Uri url) => new AddressItem(name, url);
@@ -48,7 +60,7 @@ public abstract class WebDropItem : IDisposable
private sealed class StreamItem(string name, Func<CancellationToken, Task<Stream>> open, long? size, string? mime, IDisposable? owner)
: WebDropItem(name)
{
- public override async Task<string> SaveAsync(string folder, WebDownloader downloader, IProgress<double>? progress,
+ public override async Task<string> SaveAsync(string folder, WebDownloader downloader, IProgress<TransferProgress>? progress,
CancellationToken cancellationToken)
{
await using var stream = await open(cancellationToken);
@@ -66,7 +78,7 @@ public abstract class WebDropItem : IDisposable
{
public Uri Url { get; } = url;
- public override Task<string> SaveAsync(string folder, WebDownloader downloader, IProgress<double>? progress,
+ public override Task<string> SaveAsync(string folder, WebDownloader downloader, IProgress<TransferProgress>? progress,
CancellationToken cancellationToken) =>
// A name the server sends wins; a guessed extension (".jpg" for a picture address without one) is
// corrected from the bytes.
@@ -209,7 +221,7 @@ public sealed class WebDropFetcher(WebDrop drop, WebDropOptions options, WebDown
public bool Fetches(string path) => drop.Holds(path);
- public Task<string> FetchAsync(string placeholder, IProgress<double> progress, CancellationToken cancellationToken) =>
+ public Task<string> FetchAsync(string placeholder, IProgress<TransferProgress> progress, CancellationToken cancellationToken) =>
drop.ItemFor(placeholder).SaveAsync(SaveFolder, downloader, progress, cancellationToken);
public void Release(ConversionJob job)
diff --git a/src/Filee.Engines/Infrastructure/TransferRate.cs b/src/Filee.Engines/Infrastructure/TransferRate.cs
index a60a236c..ad2c75b5 100644
--- a/src/Filee.Engines/Infrastructure/TransferRate.cs
+++ b/src/Filee.Engines/Infrastructure/TransferRate.cs
@@ -4,9 +4,12 @@
namespace Filee.Engines.Infrastructure;
/// <summary>Speed of a transfer computed from "bytes so far" samples over a sliding time window.</summary>
-public sealed class TransferRate(TimeSpan window)
+/// <param name="window">How far back the speed is averaged.</param>
+/// <param name="settle">How long the measured span must be before a speed is given (default half a second).</param>
+public sealed class TransferRate(TimeSpan window, TimeSpan? settle = null)
{
private readonly Queue<(TimeSpan Time, long Bytes)> _samples = new();
+ private readonly double _settleSeconds = (settle ?? TimeSpan.FromSeconds(0.5)).TotalSeconds;
public TransferRate()
: this(TimeSpan.FromSeconds(5))
@@ -25,7 +28,7 @@ public sealed class TransferRate(TimeSpan window)
_samples.Dequeue();
var (startTime, startBytes) = _samples.Peek();
var seconds = (elapsed - startTime).TotalSeconds;
- BytesPerSecond = seconds >= 0.5 ? Math.Max(0, bytes - startBytes) / seconds : BytesPerSecond;
+ BytesPerSecond = seconds >= _settleSeconds && seconds > 0 ? Math.Max(0, bytes - startBytes) / seconds : BytesPerSecond;
}
/// <summary>Estimated time until <paramref name="total"/> bytes are reached, or null while the speed is unknown.</summary>
diff --git a/tests/Filee.App.Tests/DownloadBadgeTests.cs b/tests/Filee.App.Tests/DownloadBadgeTests.cs
new file mode 100644
index 00000000..16e79f9a
--- /dev/null
+++ b/tests/Filee.App.Tests/DownloadBadgeTests.cs
@@ -0,0 +1,233 @@
+// The badge over a download's progress: its text (speed, amounts, files), when it shows, and how it looks above the
+// donut's ring and in the toast, light and dark.
+
+using System.Globalization;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Headless;
+using Avalonia.Headless.XUnit;
+using Avalonia.Styling;
+using Avalonia.Threading;
+using Avalonia.VisualTree;
+using Filee.App.Services;
+using Filee.App.ViewModels;
+using Filee.App.Views;
+using Filee.Core.Conversion;
+using Filee.Core.Localization;
+using Filee.Core.Platform;
+using Filee.Core.Presets;
+using Filee.Core.Settings;
+
+namespace Filee.App.Tests;
+
+[Collection("Motion")]
+public class DownloadBadgeTests
+{
+ private const long MB = 1_000_000;
+
+ private static void InCulture(string name, Action test)
+ {
+ var before = CultureInfo.CurrentCulture;
+ CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(name);
+ try
+ {
+ test();
+ }
+ finally
+ {
+ CultureInfo.CurrentCulture = before;
+ }
+ }
+
+ [AvaloniaFact]
+ public void Shows_speed_and_amounts_with_one_unit_when_they_share_it()
+ {
+ TestServices.EnsureInitialized("en");
+ var loc = AppHost.Get<ILocalizer>();
+ InCulture("en-US", () =>
+ {
+ Assert.Equal("2.4 MB/s · 12.3 / 48.0 MB", DownloadBadge.Format(loc, 2.4 * MB, new JobTransfer(12_300_000, 48 * MB, 0, 1, 12_300_000)));
+ Assert.Equal("2.4 MB/s · 12.3 MB", DownloadBadge.Format(loc, 2.4 * MB, new JobTransfer(12_300_000, null, 0, 1, 12_300_000)));
+ Assert.Equal("850 KB / 1.20 GB", DownloadBadge.Amounts(850_000, 1_200_000_000));
+ Assert.Equal("640 KB/s · 2.0 / 3.1 MB · 2 of 3 files",
+ DownloadBadge.Format(loc, 640_000, new JobTransfer(2 * MB, 3_100_000, 1, 3, 9 * MB)));
+ });
+ // The user's decimal separator, as on the Engines page.
+ InCulture("de-DE", () =>
+ Assert.Equal("2,4 MB/s · 12,3 / 48,0 MB", DownloadBadge.Format(loc, 2.4 * MB, new JobTransfer(12_300_000, 48 * MB, 0, 1, 12_300_000))));
+ }
+
+ [AvaloniaFact]
+ public void Each_language_has_its_own_files_counter()
+ {
+ TestServices.EnsureInitialized("ko");
+ var loc = AppHost.Get<ILocalizer>();
+ InCulture("en-US", () =>
+ Assert.Equal("640 KB/s · 2.0 / 3.1 MB · 3개 중 2번째", DownloadBadge.Format(loc, 640_000, new JobTransfer(2 * MB, 3_100_000, 1, 3, 9 * MB))));
+ TestServices.EnsureInitialized("en");
+ }
+
+ [AvaloniaFact]
+ public void Shows_once_the_speed_can_be_told_averaged_over_the_last_second()
+ {
+ TestServices.EnsureInitialized("en");
+ var badge = new DownloadBadge(AppHost.Get<ILocalizer>());
+ InCulture("en-US", () =>
+ {
+ Assert.Null(badge.Update(TimeSpan.Zero, null)); // nothing downloads
+ Assert.Null(badge.Update(TimeSpan.Zero, new JobTransfer(0, 10 * MB, 0, 1, 0)));
+ Assert.Null(badge.Update(TimeSpan.FromMilliseconds(250), new JobTransfer(MB / 2, 10 * MB, 0, 1, MB / 2))); // too early
+
+ // 2 MB/s for the first half second, then 3 MB/s: only the last second counts once there is one.
+ Assert.Equal("2.0 MB/s · 1.0 / 10.0 MB", badge.Update(TimeSpan.FromMilliseconds(500), new JobTransfer(MB, 10 * MB, 0, 1, MB)));
+ badge.Update(TimeSpan.FromMilliseconds(1000), new JobTransfer(2_500_000, 10 * MB, 0, 1, 2_500_000));
+ badge.Update(TimeSpan.FromMilliseconds(1500), new JobTransfer(4 * MB, 10 * MB, 0, 1, 4 * MB));
+ Assert.Equal("3.0 MB/s · 5.5 / 10.0 MB", badge.Update(TimeSpan.FromMilliseconds(2000), new JobTransfer(5_500_000, 10 * MB, 0, 1, 5_500_000)));
+ });
+ }
+
+ [AvaloniaFact]
+ public void A_finished_file_doesnt_drag_the_speed_down()
+ {
+ TestServices.EnsureInitialized("en");
+ var badge = new DownloadBadge(AppHost.Get<ILocalizer>());
+ InCulture("en-US", () =>
+ {
+ badge.Update(TimeSpan.Zero, new JobTransfer(0, 4 * MB, 0, 2, 0));
+ badge.Update(TimeSpan.FromSeconds(0.5), new JobTransfer(MB, 4 * MB, 0, 2, MB));
+ // The first file is saved: the bytes shown restart with the second, the speed keeps counting all of them.
+ Assert.Equal("2.0 MB/s · 0 KB / 4.0 MB · 2 of 2 files",
+ badge.Update(TimeSpan.FromSeconds(1), new JobTransfer(0, 4 * MB, 1, 2, 2 * MB)));
+ });
+ }
+
+ private static JobViewModel Downloading(string text)
+ {
+ var job = new ConversionJob([Path.Combine(Path.GetTempPath(), "cat.png")], new Preset { TargetFormat = "jpg" }, "JPG");
+ return new JobViewModel(job, AppHost.Get<ILocalizer>(), AppHost.Get<IPlatformServices>(), _ => { })
+ {
+ DownloadText = text,
+ IsDownloading = true,
+ };
+ }
+
+ private static void Pump()
+ {
+ for (var i = 0; i < 30; i++)
+ {
+ Dispatcher.UIThread.RunJobs();
+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();
+ }
+ }
+
+ private static void Save(TopLevel window, string name)
+ {
+ using var frame = window.CaptureRenderedFrame();
+ Assert.NotNull(frame);
+ using var stream = File.Create(Path.Combine(TestServices.ScreenshotDirectory, name));
+ frame.Save(stream, new Avalonia.Media.Imaging.PngBitmapEncoderOptions());
+ }
+
+ private static void InTheme(ThemeMode mode, Action test)
+ {
+ var store = AppHost.Get<UserDataStore>();
+ var before = store.Settings.Theme.Mode;
+ store.Settings.Theme.Mode = mode;
+ AppHost.Get<ThemeService>().Apply(store.Settings.Theme, "en");
+ Application.Current!.RequestedThemeVariant = mode == ThemeMode.Dark ? ThemeVariant.Dark : ThemeVariant.Light;
+ Motion.Set(false); // the badge snaps into place for the screenshot
+ try
+ {
+ test();
+ }
+ finally
+ {
+ Motion.Set(true);
+ store.Settings.Theme.Mode = before;
+ AppHost.Get<ThemeService>().Apply(store.Settings.Theme, "en");
+ Application.Current!.RequestedThemeVariant = ThemeVariant.Default;
+ }
+ }
+
+ [AvaloniaTheory]
+ [InlineData(ThemeMode.Light)]
+ [InlineData(ThemeMode.Dark)]
+ public void The_badge_pops_up_just_above_the_progress_ring(ThemeMode mode)
+ {
+ TestServices.EnsureInitialized("en");
+ InTheme(mode, () =>
+ {
+ var radial = AppHost.Get<RadialController>();
+ var model = AppHost.Get<RadialViewModel>();
+ // As the drop zone opens it (the drag-mode window stays see-through until a drag brings files).
+ radial.ShowForFiles(500, 500, [Path.Combine(Path.GetTempPath(), "cat.png")]);
+ var window = radial.Window!;
+ try
+ {
+ window.DonutControl.BeginProgress();
+ window.DonutControl.SetProgress(0.18);
+ for (var t = 0.0; t < 1.2; t += 1 / 60.0)
+ window.DonutControl.Advance(1 / 60.0); // the slices collapse and the ring springs in
+ var job = Downloading("2.4 MB/s · 12.3 / 48.0 MB");
+ model.ProgressJob = job;
+ Pump();
+
+ var badge = window.FindControl<Border>("DownloadBadge")!;
+ Assert.Contains("shown", badge.Classes);
+ Assert.Equal(1, badge.Opacity);
+ var donut = window.DonutControl;
+ var center = new Point(donut.Bounds.Width / 2, donut.Bounds.Height / 2);
+ var bottom = badge.TranslatePoint(new Point(badge.Bounds.Width / 2, badge.Bounds.Height), donut)!.Value;
+ Assert.InRange(center.Y - bottom.Y, 36 + 6, 60); // above the ring, close to it
+ Assert.Equal(center.X, bottom.X, 1);
+ Save(window, $"donut-download-badge-{mode.ToString().ToLowerInvariant()}.png");
+
+ // Downloads done, converting: the badge goes.
+ job.IsDownloading = false;
+ Pump();
+ Assert.DoesNotContain("shown", badge.Classes);
+ Assert.Equal(0, badge.Opacity);
+ }
+ finally
+ {
+ model.ProgressJob = null;
+ window.DonutControl.LeaveProgressMode();
+ radial.Close(animate: false);
+ }
+ });
+ }
+
+ [AvaloniaTheory]
+ [InlineData(ThemeMode.Light)]
+ [InlineData(ThemeMode.Dark)]
+ public void The_toast_shows_the_badge_above_its_progress_bar(ThemeMode mode)
+ {
+ TestServices.EnsureInitialized("en");
+ InTheme(mode, () =>
+ {
+ var conversions = AppHost.Get<ConversionService>();
+ var job = Downloading("640 KB/s · 2.0 / 3.1 MB · 2 of 3 files");
+ conversions.Jobs.Add(job);
+ conversions.ToastJobs.Add(job);
+ var toast = new ToastWindow { DataContext = conversions };
+ try
+ {
+ toast.Show();
+ Pump();
+ var text = toast.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Text == job.DownloadText);
+ Assert.True(text.IsEffectivelyVisible);
+ Save(toast, $"toast-download-badge-{mode.ToString().ToLowerInvariant()}.png");
+
+ job.IsDownloading = false;
+ Pump();
+ Assert.False(text.IsEffectivelyVisible);
+ }
+ finally
+ {
+ toast.Close();
+ conversions.ToastJobs.Remove(job);
+ conversions.Jobs.Remove(job);
+ }
+ });
+ }
+}
diff --git a/tests/Filee.Core.Tests/WebDownloaderTests.cs b/tests/Filee.Core.Tests/WebDownloaderTests.cs
index cbce856d..c8148291 100644
--- a/tests/Filee.Core.Tests/WebDownloaderTests.cs
+++ b/tests/Filee.Core.Tests/WebDownloaderTests.cs
@@ -232,7 +232,7 @@ public sealed class WebDownloaderTests : IDisposable
};
using var downloader = Downloader();
using var cancel = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
- var progress = new List<double>();
+ var progress = new List<TransferProgress>();
var download = downloader.DownloadAsync(Url("/slow.png"), _dir.Path, null, new SyncProgress(progress), cancel.Token);
await started.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
@@ -243,6 +243,44 @@ public sealed class WebDownloaderTests : IDisposable
Assert.Empty(Directory.GetFiles(_dir.Path));
}
+ [Fact]
+ public async Task Reports_the_bytes_so_far_and_the_size_when_the_server_says_it()
+ {
+ var body = new byte[300_000];
+ Png.CopyTo(body, 0);
+ Serve("/sized.png", body, "image/png");
+ Serve("/unsized.png", body, "image/png", chunked: true);
+ using var downloader = new WebDownloader { ReportInterval = TimeSpan.Zero };
+ var sized = new List<TransferProgress>();
+ var unsized = new List<TransferProgress>();
+
+ await downloader.DownloadAsync(Url("/sized.png"), _dir.Path, null, new SyncProgress(sized), TestContext.Current.CancellationToken);
+ await downloader.DownloadAsync(Url("/unsized.png"), _dir.Path, null, new SyncProgress(unsized), TestContext.Current.CancellationToken);
+
+ Assert.True(sized.Count >= 2);
+ Assert.All(sized, p => Assert.Equal(body.Length, p.Total));
+ Assert.Equal(sized.Select(p => p.Bytes).Order(), sized.Select(p => p.Bytes)); // only forward
+ Assert.Equal(new TransferProgress(body.Length, body.Length), sized[^1]);
+ Assert.Equal(1, sized[^1].Fraction);
+ Assert.All(unsized, p => Assert.Null(p.Total));
+ Assert.Equal(body.Length, unsized[^1].Bytes);
+ Assert.Null(unsized[^1].Fraction);
+ }
+
+ [Fact]
+ public async Task Reports_are_spaced_out_but_the_last_one_always_comes()
+ {
+ var body = new byte[400_000];
+ Png.CopyTo(body, 0);
+ Serve("/many.png", body, "image/png");
+ using var downloader = new WebDownloader { ReportInterval = TimeSpan.FromHours(1) };
+ var reports = new List<TransferProgress>();
+
+ await downloader.DownloadAsync(Url("/many.png"), _dir.Path, null, new SyncProgress(reports), TestContext.Current.CancellationToken);
+
+ Assert.Equal([new TransferProgress(WebFormats.SniffLength, body.Length), new TransferProgress(body.Length, body.Length)], reports);
+ }
+
[Fact]
public async Task Bytes_a_browser_handed_over_are_saved_like_a_download()
{
@@ -264,9 +302,9 @@ public sealed class WebDownloaderTests : IDisposable
await Task.Delay(10);
}
- private sealed class SyncProgress(List<double> values) : IProgress<double>
+ private sealed class SyncProgress(List<TransferProgress> values) : IProgress<TransferProgress>
{
- public void Report(double value)
+ public void Report(TransferProgress value)
{
lock (values)
values.Add(value);
diff --git a/tests/Filee.Core.Tests/WebDropJobTests.cs b/tests/Filee.Core.Tests/WebDropJobTests.cs
index 502fbe33..3a258470 100644
--- a/tests/Filee.Core.Tests/WebDropJobTests.cs
+++ b/tests/Filee.Core.Tests/WebDropJobTests.cs
@@ -156,6 +156,75 @@ public class WebDropJobTests
Assert.True(Directory.Exists(fresh));
}
+ /// <summary>Saves each source halfway, waits for the test, then finishes it.</summary>
+ private sealed class HalfwayFetcher(IReadOnlyDictionary<string, long?> sizes) : ISourceFetcher
+ {
+ public TaskCompletionSource Halfway { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public TaskCompletionSource Go { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ private int _waiting;
+
+ public bool Fetches(string source) => sizes.ContainsKey(source);
+
+ public async Task<string> FetchAsync(string source, IProgress<TransferProgress> progress, CancellationToken cancellationToken)
+ {
+ var size = sizes[source];
+ progress.Report(new TransferProgress(1000, size));
+ if (Interlocked.Increment(ref _waiting) == sizes.Count)
+ Halfway.TrySetResult();
+ await Go.Task.WaitAsync(cancellationToken);
+ progress.Report(new TransferProgress(size ?? 2000, size));
+ var path = Path.Combine(Path.GetTempPath(), "filee-tests", Guid.NewGuid().ToString("N")[..8], Path.GetFileName(source));
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ await File.WriteAllBytesAsync(path, Png, cancellationToken);
+ return path;
+ }
+
+ public void Release(ConversionJob job)
+ {
+ }
+ }
+
+ [Fact]
+ public async Task A_job_tells_what_it_is_saving_summed_over_its_downloads()
+ {
+ using var dir = new TempDir();
+ var local = dir.File("local.png");
+ var fetcher = new HalfwayFetcher(new Dictionary<string, long?> { ["web/a.png"] = 4000, ["web/b.png"] = 6000 });
+ await using var queue = Queue();
+ var job = new ConversionJob(["web/a.png", local, "web/b.png"], new Preset { TargetFormat = "jpg" }, "Test", fetcher);
+ Assert.Null(job.Transfer()); // nothing is being saved yet
+
+ var run = queue.RunAsync(job);
+ await fetcher.Halfway.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
+
+ Assert.Equal(new JobTransfer(2000, 10_000, 0, 2, 2000), job.Transfer());
+ Assert.Equal(0.125, job.Files[0].Progress, 3); // 1000 of 4000, saving being the first half of a file's progress
+ fetcher.Go.SetResult();
+ await run;
+
+ Assert.Null(job.Transfer());
+ Assert.All(job.Files.Where(f => f.NeedsFetch), f => Assert.True(f.Saved));
+ Assert.False(job.Files[1].NeedsFetch);
+ Assert.Equal(JobState.Completed, job.State);
+ }
+
+ [Fact]
+ public void A_total_is_only_given_when_every_download_says_its_size()
+ {
+ var fetcher = new HalfwayFetcher(new Dictionary<string, long?> { ["web/a.png"] = 4000, ["web/b.png"] = null });
+ var job = new ConversionJob(["web/a.png", "web/b.png"], new Preset { TargetFormat = "jpg" }, "Test", fetcher);
+ foreach (var file in job.Files)
+ file.State = FileState.Running;
+ job.Files[0].Transfer = new TransferProgress(1000, 4000);
+ job.Files[1].Transfer = new TransferProgress(500, null);
+ Assert.Equal(new JobTransfer(1500, null, 0, 2, 1500), job.Transfer());
+
+ // The second one is saved: what is left to show is the first, the speed still counts both.
+ job.Files[1].Transfer = new TransferProgress(900, null);
+ job.Files[1].Saved = true;
+ Assert.Equal(new JobTransfer(1000, 4000, 1, 2, 1900), job.Transfer());
+ }
+
private sealed class Disposer(Action action) : IDisposable
{
public void Dispose() => action();