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.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Install updates from inside Filee, default save location (1.4.0)
KnifeLemon7b6823ce04d3
diff --git a/Directory.Build.props b/Directory.Build.propsindex 05fea92f..5e283e06 100644--- a/Directory.Build.props+++ b/Directory.Build.props@@ -14,7 +14,7 @@parameters of a member is fine (CS1573). --><NoWarn>$(NoWarn);CS1591;CS1573</NoWarn>- <Version>1.3.1</Version>+ <Version>1.4.0</Version><Product>Filee</Product><Authors>Filee contributors</Authors><Copyright>Copyright (c) Filee contributors</Copyright>diff --git a/README.ko.md b/README.ko.mdindex a53887a0..17fe74d6 100644--- a/README.ko.md+++ b/README.ko.md@@ -52,9 +52,10 @@로그인할 때 시작, 그리고 추가 엔진을 크기를 보며 고를 수 있어요: 동영상·오디오(FFmpeg, 약 100MB)와 드문형식(LibreOffice, calibre, Ghostscript, Pandoc). 고른 엔진은 설치가 끝나고 Filee가 시작되면서 내려받고, 설정 → 변환엔진에서 다운로드 속도와 남은 시간을 보며 언제든 설치하거나 지울 수 있어요.-- **업데이트는 알려 드려요.** 새 버전이 나오면 메뉴 하단, 알림, 트레이 메뉴에 표시되고 누르면 최신 릴리스 페이지가- 열려요. 새 설치 파일을 실행하면 Filee를 닫고 업데이트하며, 설정과 엔진은 그대로 유지돼요. 사용자별로 설치된- Filee 1.1 이하도 같은 방법으로 넘겨받아요.+- **업데이트는 알아서 설치돼요.** 새 버전이 나오면 메뉴 하단, 알림, 트레이 메뉴에 표시돼요. 업데이트를 누르면 새 설치+ 파일을 받아 릴리스의 SHA-256 값과 맞춰 본 뒤, 관리자 확인 한 번을 거쳐 설치해요. 설치 프로그램이 Filee를 닫고+ 업데이트한 다음 다시 켜 주고, 설정과 엔진은 그대로 남아요. 휴대용 버전은 대신 릴리스 페이지가 열려요. 사용자별로+ 설치된 Filee 1.1 이하도 새 설치 파일이 넘겨받아요.macOS 지원을 계획 중이고, Linux 지원도 검토하고 있어요.@@ -66,7 +67,9 @@ macOS 지원을 계획 중이고, Linux 지원도 검토하고 있어요.압축 파일, CAD, 글꼴, 그리고 여러 종류를 함께 골랐을 때의 툴바. 실제 도넛 위에서 드래그 앤 드롭으로 프리셋을 배치하고,확장자는 태그로 추가하고, 우클릭이나 ✎로 프리셋을 편집해요.- **프리셋.** 품질, 크기 조정, DPI, 메타데이터, PDF 합치기·나누기, 페이지 범위, 동영상 화질·해상도, 오디오 비트레이트,- 압축 수준, 저장 위치, 파일 이름 패턴, 이름 충돌 처리, 원본 파일 날짜 유지.+ 압축 수준, 저장 위치, 파일 이름 패턴, 이름 충돌 처리, 원본 파일 날짜 유지. 변환된 파일은 기본으로 원본 옆에+ 저장되고, 설정 > 일반의 기본 저장 위치(하위 폴더나 지정한 폴더 하나)를 바꾸면 저장 위치를 따로 정하지 않은+ 프리셋이 모두 따라가요.- **일괄 변환.** 1개든 100개든 동시에 변환하고, 하나가 실패해도 나머지는 계속돼요. "ZIP 하나로"는 어떤 파일이든 압축 파일하나로, "PDF 병합"은 PDF 하나로 묶어요.- **경로 자동 계획.** 여러 단계 변환도 알아서 찾아요(예: HWP → HWPX → DOCX, EPUB → HWPX → PDF → PNG). 단계마다 가장 잘하는diff --git a/README.md b/README.mdindex dbe08a7b..2503b3d5 100644--- a/README.md+++ b/README.md@@ -54,9 +54,11 @@ administrator rights once and installs Filee for all users in Program Files. Pre(FFmpeg, ~100 MB) and rare formats (LibreOffice, calibre, Ghostscript, Pandoc), each with its size. Filee downloadsthe chosen engines when Setup starts it; install or remove them any time in Settings → Engines, which shows downloadspeed and time left.-- **You hear about updates.** When a new release is out, Filee says so at the bottom of the menu, in a notice and in- the tray menu, and opens the latest release to download it. Run the new installer: it closes Filee, updates it and- keeps your settings and engines. Filee 1.1 and earlier (installed per user) are taken over the same way.+- **Updates install themselves.** When a new release is out, Filee says so at the bottom of the menu, in a notice and+ in the tray menu. Press Update and Filee downloads the new installer, checks it against the release's SHA-256 file+ and runs it after one administrator prompt. Setup closes Filee, updates it, keeps your settings and engines, and+ starts it again. The portable copy opens the release page instead. Filee 1.1 and earlier (installed per user) are+ taken over by the new installer too.macOS support is planned, and Linux is being considered.@@ -70,6 +72,8 @@ macOS support is planned, and Linux is being considered.drag & drop, add extensions as tags, right-click or ✎ to edit a preset.- **Presets.** Quality, resizing, DPI, metadata, PDF merge and split, page ranges, video quality and resolution, audiobitrate, archive compression, output folder, file name pattern, conflict handling and keeping the original file dates.+ Converted files go next to the original by default. Settings → General sets another default save location (a+ subfolder or one fixed folder) for every preset that has no location of its own.- **Batch conversion.** 1 file or 100, converted in parallel; one failure never stops the rest. "One ZIP" packs anyfiles into a single archive, "Merge PDF" makes one PDF.- **Planned routes.** Multi-step conversions are found automatically (e.g. HWP → HWPX → DOCX, EPUB → HWPX → PDF → PNG),diff --git a/README.zh-CN.md b/README.zh-CN.mdindex d8930c14..b194ce00 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -51,8 +51,9 @@ Program Files。不想安装?把 `Filee-<版本>-win-Portable.zip` 解压到“显示更多选项”)、登录时启动,并按大小挑选可选引擎:视频/音频(FFmpeg,约 100 MB)和少见格式(LibreOffice、calibre、Ghostscript、Pandoc)。所选引擎会在安装完成、Filee 启动后下载;之后可随时在“设置 → 转换引擎”中安装或删除,并显示下载速度和剩余时间。-- **有更新会提醒你。** 新版本发布后,Filee 会在菜单底部、通知和托盘菜单中提示,点击即可打开最新发布页面下载。- 运行新的安装程序会关闭 Filee 并完成更新,设置和引擎都会保留。按用户安装的 Filee 1.1 及更早版本也会以同样方式接管。+- **更新自动安装。** 新版本发布后,Filee 会在菜单底部、通知和托盘菜单中提示。点击“更新”后,Filee 会下载新的安装程序,+ 用发布页的 SHA-256 校验文件核对,再经过一次管理员确认后运行。安装程序会关闭 Filee、完成更新并重新启动它,设置和引擎都会保留。+ 便携版则会打开发布页面。按用户安装的 Filee 1.1 及更早版本也会由新的安装程序接管。macOS 版本正在计划中,也在考虑支持 Linux。@@ -63,7 +64,8 @@ macOS 版本正在计划中,也在考虑支持 Linux。- **按文件类型的工具栏。** 图片、PDF、文档、表格、演示文稿、HWP、文本、电子书、视频、音频、矢量图、压缩包、CAD 和字体,以及用于混合选择的工具栏。直接在圆环上拖放来排列预设,以标签方式添加扩展名,右键或 ✎ 编辑预设。- **预设。** 质量、缩放、DPI、元数据、PDF 合并与拆分、页码范围、视频画质与分辨率、音频码率、压缩级别、保存位置、- 文件名模板、重名处理和保留原文件日期。+ 文件名模板、重名处理和保留原文件日期。转换后的文件默认保存在原文件旁边;在“设置 > 常规”里修改默认保存位置+ (子文件夹或某个固定文件夹)后,所有未单独设置保存位置的预设都会跟着改变。- **批量转换。** 1 个或 100 个文件并行转换,某个文件失败也不影响其余文件。"打包成一个 ZIP"可把任意文件压缩为一个压缩包,"合并 PDF"生成一个 PDF。- **自动规划路径。** 自动找到多步转换路径(例如 HWP → HWPX → DOCX、EPUB → HWPX → PDF → PNG),每一步使用最擅长的引擎。diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 260ddb3e..bf8f43bc 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -16,7 +16,7 @@"tray.pause": "Pause shortcuts","tray.resume": "Resume shortcuts","tray.quit": "Quit",- "tray.update": "Download update ({0})",+ "tray.update": "Update to {0}","tray.tooltip": "Filee: hold {0} and drag files","home.title": "Home",@@ -134,6 +134,8 @@"general.modern_menu_cancelled": "Cancelled. The entry stays under “Show more options”.","general.modern_menu_failed": "Windows did not add the entry: {0}","general.modern_menu_remove_failed": "Windows did not remove the entry: {0}",+ "general.default_output": "Default save location",+ "general.default_output_hint": "Presets set to “Default save location” save here. A preset with its own location keeps it.","general.check_updates": "Check for updates automatically","general.history": "Conversion history","general.no_history": "Don't keep a history of recent conversions",@@ -145,9 +147,16 @@"general.update_none": "You're up to date ({0})","update.sidebar": "Update to {0}","update.notice_title": "Filee {0} is available",- "update.notice_text": "Download the new installer from GitHub and run it to update. Your settings are kept.",+ "update.notice_text": "Press Update and Filee downloads and installs the new version. Your settings are kept.","update.download": "Download","update.later": "Later",+ "update.install": "Update",+ "update.notice_text_portable": "This is the portable version. Download the new zip and unpack it over this folder. Your settings are kept.",+ "update.downloading": "Downloading the update… {0}%",+ "update.installing_short": "Installing…",+ "update.installing": "The installer is running. Filee starts again when it is done.",+ "update.failed": "Couldn't update automatically, so the download page is open in your browser.",+ "update.cancelled": "Update cancelled. Press Update again to install it.","general.data_folder": "Settings folder","general.open_data_folder": "Open","general.library": "Presets and toolbars",@@ -291,6 +300,7 @@"presets.extract_note": "Each archive is extracted into a folder of its own. Where it goes is set under Output.","presets.group.output": "Output","presets.location": "Save to",+ "presets.location.Default": "Default save location (Settings > General)","presets.location.SameFolder": "Same folder as the source","presets.location.Subfolder": "A subfolder","presets.location.CustomFolder": "A fixed folder",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex d0f15be9..52134a67 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -16,7 +16,7 @@"tray.pause": "단축키 일시 중지","tray.resume": "단축키 다시 사용","tray.quit": "종료",- "tray.update": "업데이트 받기 ({0})",+ "tray.update": "{0} 버전으로 업데이트","tray.tooltip": "Filee: {0} 누른 채 파일 드래그","home.title": "홈",@@ -134,6 +134,8 @@"general.modern_menu_cancelled": "취소했어요. 항목은 “추가 옵션 표시” 안에 그대로 있어요.","general.modern_menu_failed": "Windows가 항목을 추가하지 못했어요: {0}","general.modern_menu_remove_failed": "Windows가 항목을 제거하지 못했어요: {0}",+ "general.default_output": "기본 저장 위치",+ "general.default_output_hint": "저장 위치가 “기본 저장 위치”인 프리셋은 여기에 저장해요. 저장 위치를 따로 정한 프리셋은 그대로예요.","general.check_updates": "자동으로 업데이트 확인","general.history": "변환 기록","general.no_history": "최근 변환 기록 남기지 않기",@@ -145,9 +147,16 @@"general.update_none": "최신 버전이에요 ({0})","update.sidebar": "{0} 업데이트","update.notice_title": "Filee {0} 버전이 나왔어요",- "update.notice_text": "GitHub에서 새 설치 파일을 받아 실행하면 업데이트돼요. 설정은 그대로 남아요.",+ "update.notice_text": "업데이트를 누르면 새 버전을 받아서 설치해요. 설정은 그대로 남아요.","update.download": "다운로드","update.later": "나중에",+ "update.install": "업데이트",+ "update.notice_text_portable": "휴대용 버전이라 새 zip을 받아서 지금 폴더에 덮어 풀어야 해요. 설정은 그대로 남아요.",+ "update.downloading": "새 버전 받는 중… {0}%",+ "update.installing_short": "설치하는 중…",+ "update.installing": "설치 프로그램이 열렸어요. 설치가 끝나면 Filee가 다시 켜져요.",+ "update.failed": "자동 업데이트가 안 돼서 브라우저에 다운로드 페이지를 열었어요.",+ "update.cancelled": "업데이트를 취소했어요. 다시 누르면 설치해요.","general.data_folder": "설정 폴더","general.open_data_folder": "열기","general.library": "프리셋과 툴바",@@ -291,6 +300,7 @@"presets.extract_note": "압축 파일마다 따로 폴더를 만들어 풀어요. 저장 위치는 아래 출력에서 정해요.","presets.group.output": "출력","presets.location": "저장 위치",+ "presets.location.Default": "기본 저장 위치 (설정 > 일반)","presets.location.SameFolder": "원본과 같은 폴더","presets.location.Subfolder": "하위 폴더","presets.location.CustomFolder": "지정한 폴더",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex a5957bbf..247a2cc5 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -16,7 +16,7 @@"tray.pause": "暂停快捷操作","tray.resume": "恢复快捷操作","tray.quit": "退出",- "tray.update": "下载更新({0})",+ "tray.update": "更新到 {0}","tray.tooltip": "Filee:按住 {0} 拖动文件","home.title": "首页",@@ -134,6 +134,8 @@"general.modern_menu_cancelled": "已取消。此项仍在“显示更多选项”中。","general.modern_menu_failed": "Windows 未能添加此项:{0}","general.modern_menu_remove_failed": "Windows 未能移除此项:{0}",+ "general.default_output": "默认保存位置",+ "general.default_output_hint": "保存位置为“默认保存位置”的预设会保存到这里。单独设置了保存位置的预设不受影响。","general.check_updates": "自动检查更新","general.history": "转换记录","general.no_history": "不保留最近的转换记录",@@ -145,9 +147,16 @@"general.update_none": "已是最新版本({0})","update.sidebar": "更新到 {0}","update.notice_title": "Filee {0} 已发布",- "update.notice_text": "从 GitHub 下载新的安装程序并运行即可更新,设置会保留。",+ "update.notice_text": "点击“更新”,Filee 会下载并安装新版本,设置会保留。","update.download": "下载","update.later": "稍后",+ "update.install": "更新",+ "update.notice_text_portable": "这是便携版,请下载新的 zip 并解压覆盖当前文件夹,设置会保留。",+ "update.downloading": "正在下载更新… {0}%",+ "update.installing_short": "正在安装…",+ "update.installing": "安装程序正在运行,完成后 Filee 会重新启动。",+ "update.failed": "无法自动更新,已在浏览器中打开下载页面。",+ "update.cancelled": "已取消更新,再次点击“更新”即可安装。","general.data_folder": "设置文件夹","general.open_data_folder": "打开","general.library": "预设与工具栏",@@ -291,6 +300,7 @@"presets.extract_note": "每个压缩文件解压到各自的文件夹。保存位置在下方“输出”中设置。","presets.group.output": "输出","presets.location": "保存到",+ "presets.location.Default": "默认保存位置(设置 > 常规)","presets.location.SameFolder": "与源文件相同的文件夹","presets.location.Subfolder": "子文件夹","presets.location.CustomFolder": "指定文件夹",diff --git a/src/Filee.App/Services/ConversionService.cs b/src/Filee.App/Services/ConversionService.csindex b49473b2..51be5f72 100644--- a/src/Filee.App/Services/ConversionService.cs+++ b/src/Filee.App/Services/ConversionService.cs@@ -60,6 +60,8 @@ public sealed class ConversionService{if (files.Count == 0)return null;+ // A preset on "Default" saves where Settings > General says (read now, so a changed default applies at once).+ preset = _store.Settings.WithDefaultOutput(preset);var job = _queue.Enqueue(files, preset, _loc.DisplayName(preset));var vm = new JobViewModel(job, _loc, _platform, Remove);_byId[job.Id] = vm;diff --git a/src/Filee.App/Services/TrayService.cs b/src/Filee.App/Services/TrayService.csindex 7141968a..065412c8 100644--- a/src/Filee.App/Services/TrayService.cs+++ b/src/Filee.App/Services/TrayService.cs@@ -1,4 +1,4 @@-// System tray icon: open settings, pause gestures, download a new version, quit.+// System tray icon: open settings, pause gestures, install a new version, quit.using Avalonia;using Avalonia.Controls;@@ -28,7 +28,7 @@ public sealed class TrayService(UserDataStore store, ILocalizer loc, WindowServi_quit = new NativeMenuItem();_quit.Click += (_, _) => (app.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown();_update = new NativeMenuItem();- _update.Click += (_, _) => updates.OpenDownloadPage();+ _update.Click += async (_, _) => await updates.UpdateAsync();_tray = new TrayIcon{@@ -44,7 +44,7 @@ public sealed class TrayService(UserDataStore store, ILocalizer loc, WindowServistore.SettingsChanged += (_, _) => Refresh();updates.PropertyChanged += (_, e) =>{- if (e.PropertyName == nameof(UpdateService.LatestVersion))+ if (UpdateTexts.Affects(e.PropertyName))Refresh();};}@@ -53,10 +53,12 @@ public sealed class TrayService(UserDataStore store, ILocalizer loc, WindowServi{if (_tray?.Menu is not { } menu)return;- // "Download update (x.y.z)" sits at the top of the menu while a newer release is out.+ // "Update to x.y.z" sits at the top of the menu while a newer release is out ("Downloading… 42%" meanwhile).if (updates.LatestVersion is { } latest){- _update!.Header = loc.Format("tray.update", latest);+ _update!.Header = updates.Step is UpdateStep.Downloading or UpdateStep.Installing+ ? UpdateTexts.Short(updates, loc)+ : loc.Format("tray.update", latest);if (!menu.Items.Contains(_update))menu.Items.Insert(0, _update);}diff --git a/src/Filee.App/Services/UpdateService.cs b/src/Filee.App/Services/UpdateService.csindex bc9006ba..73cfdf29 100644--- a/src/Filee.App/Services/UpdateService.cs+++ b/src/Filee.App/Services/UpdateService.cs@@ -1,10 +1,13 @@-// Update check against GitHub Releases. When a newer version is out the app says so (sidebar, notice, tray) and sends-// the user to the latest release page to download it; running the new installer updates Filee in place and keeps the-// settings. Works in every build, also when run from source.+// Update check against GitHub Releases. When a newer version is out the app says so (sidebar, notice, tray). In an+// installed copy "Update" downloads the new installer, checks it against the release's SHA256SUMS file and runs it;+// Setup closes Filee, updates it in place (settings are kept) and starts it again. A portable copy, a copy run from+// source, or a failed download opens a download page instead. The check works in every build.+using System.ComponentModel;using System.Diagnostics;using System.Net.Http.Headers;using System.Reflection;+using System.Security.Cryptography;using System.Text.Json;using Avalonia.Threading;using CommunityToolkit.Mvvm.ComponentModel;@@ -12,14 +15,41 @@ using Microsoft.Extensions.Logging;namespace Filee.App.Services;+/// <summary>Where an in-app update stands.</summary>+public enum UpdateStep+{+ Idle,+ Downloading,+ /// <summary>The installer is running (it shows its own progress window and closes Filee).</summary>+ Installing,+ /// <summary>The update did not work; the download page was opened instead.</summary>+ Failed,+ /// <summary>The user said no to the administrator prompt, or closed Setup.</summary>+ Cancelled,+}+public sealed partial class UpdateService : ObservableObject{/// <summary>How often a running Filee (it lives in the tray for days) looks for a new version.</summary>private static readonly TimeSpan CheckInterval = TimeSpan.FromHours(6);+ /// <summary>A download that receives nothing for this long is given up.</summary>+ private static readonly TimeSpan StallTimeout = TimeSpan.FromSeconds(30);++ /// <summary>Win32 ERROR_CANCELLED: the user declined the UAC prompt.</summary>+ private const int ErrorCancelled = 1223;++ /// <summary>+ /// Setup without the wizard: only its progress window shows. Updates keep the earlier choices anyway, and Setup+ /// starts Filee again when it is done.+ /// </summary>+ internal const string InstallerArguments = "/SILENT /NORESTART";+private readonly ILogger<UpdateService> _log;private readonly HttpClient _http;private DispatcherTimer? _timer;+ private ReleaseFile? _installer;+ private ReleaseFile? _checksums;public UpdateService(ILogger<UpdateService> log) : this(log, new HttpClientHandler()){@@ -29,6 +59,7 @@ public sealed partial class UpdateService : ObservableObjectinternal UpdateService(ILogger<UpdateService> log, HttpMessageHandler handler){_log = log;+ // Downloads use their own stall timeout (StallTimeout); this one covers the API call and the response headers._http = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(20) };_http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Filee", CurrentVersion));_http.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json");@@ -46,9 +77,19 @@ public sealed partial class UpdateService : ObservableObject/// <summary>GitHub's "new issue" page (bug report or feature request template).</summary>public static string NewIssueUrl => RepositoryUrl.TrimEnd('/') + "/issues/new/choose";- /// <summary>Page with the newest installer.</summary>+ /// <summary>Release page with every file, including the portable zip.</summary>public static string LatestReleaseUrl => RepositoryUrl.TrimEnd('/') + "/releases/latest";+ /// <summary>The website: one big download button, friendlier than the GitHub release page.</summary>+ public const string WebsiteUrl = "https://filee.sh/";++ /// <summary>+ /// True when this copy was installed by Setup (Inno Setup puts its uninstaller next to Filee.exe). Only then can+ /// the new installer update it in place; the portable zip and a copy run from source have no uninstaller.+ /// </summary>+ public static bool IsInstalled { get; } = OperatingSystem.IsWindows()+ && File.Exists(Path.Combine(AppContext.BaseDirectory, "unins000.exe"));+/// <summary>The newer version found by the last check (e.g. "1.0.2"), or null when up to date / unknown.</summary>[ObservableProperty][NotifyPropertyChangedFor(nameof(IsUpdateAvailable))]@@ -56,6 +97,16 @@ public sealed partial class UpdateService : ObservableObjectpublic bool IsUpdateAvailable => LatestVersion is not null;+ /// <summary>Progress of an in-app update.</summary>+ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(IsBusy))]+ private UpdateStep _step;++ /// <summary>Download progress, 0 to 100.</summary>+ [ObservableProperty] private int _downloadPercent;++ public bool IsBusy => Step is UpdateStep.Downloading or UpdateStep.Installing;+/// <summary>Raised on the UI thread when a check finds a newer version than before.</summary>public event EventHandler<string>? UpdateFound;@@ -84,6 +135,7 @@ public sealed partial class UpdateService : ObservableObjectusing var json = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);var tag = json.RootElement.TryGetProperty("tag_name", out var value) ? value.GetString() : null;var newer = IsNewer(tag, CurrentVersion) ? Normalize(tag!) : null;+ (_installer, _checksums) = FindFiles(json.RootElement);await Dispatcher.UIThread.InvokeAsync(() => Publish(newer));return newer;}@@ -112,19 +164,162 @@ public sealed partial class UpdateService : ObservableObject_timer.Start();}- /// <summary>Opens the latest release page in the browser.</summary>+ /// <summary>+ /// What every "Update" button does. An installed copy downloads, verifies and runs the new installer; anything+ /// else (portable, run from source, the release has no installer) opens a download page. Safe to call twice.+ /// </summary>+ public async Task UpdateAsync()+ {+ if (IsBusy)+ return;+ if (!IsInstalled || _installer is null || _checksums is null)+ {+ OpenDownloadPage();+ return;+ }++ Step = UpdateStep.Downloading;+ DownloadPercent = 0;+ string installer;+ try+ {+ var progress = new Progress<int>(percent => DownloadPercent = percent);+ installer = await DownloadInstallerAsync(Path.Combine(Path.GetTempPath(), "Filee-update"), progress);+ }+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException+ or InvalidDataException or UnauthorizedAccessException)+ {+ Fail("download", ex);+ return;+ }++ Process? setup;+ try+ {+ setup = Process.Start(new ProcessStartInfo(installer, InstallerArguments) { UseShellExecute = true });+ }+ catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled)+ {+ _log.LogInformation("Update cancelled at the administrator prompt");+ Step = UpdateStep.Cancelled;+ return;+ }+ catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)+ {+ Fail("start", ex);+ return;+ }++ _log.LogInformation("Started the installer for {Version}", LatestVersion);+ Step = UpdateStep.Installing;+ if (setup is null)+ return;++ // A successful update closes Filee before Setup exits, so getting here means Setup ended without updating:+ // the administrator prompt was declined (Setup asks for it itself), or the user cancelled.+ using (setup)+ await setup.WaitForExitAsync();+ _log.LogInformation("Installer ended with exit code {Code}", setup.ExitCode);+ Step = setup.ExitCode == 0 ? UpdateStep.Idle : UpdateStep.Cancelled;+ }++ /// <summary>+ /// Downloads the installer of the latest release into <paramref name="folder"/> and checks its SHA-256 against+ /// the release's checksum file. Returns the verified file; throws <see cref="InvalidDataException"/> when it does+ /// not match.+ /// </summary>+ internal async Task<string> DownloadInstallerAsync(string folder, IProgress<int>? progress,+ CancellationToken cancellationToken = default)+ {+ var installer = _installer ?? throw new InvalidOperationException("No installer in the latest release");+ var checksums = _checksums ?? throw new InvalidOperationException("No checksum file in the latest release");++ var sums = await GetTextAsync(checksums.Url, cancellationToken);+ var expected = ParseChecksum(sums, installer.Name)+ ?? throw new InvalidDataException($"{checksums.Name} has no line for {installer.Name}");++ Directory.CreateDirectory(folder);+ var target = Path.Combine(folder, installer.Name);+ // Downloaded already (Update pressed again after a declined prompt): reuse it if it is still intact.+ if (File.Exists(target) && await Sha256Async(target, cancellationToken) == expected)+ {+ progress?.Report(100);+ return target;+ }+ foreach (var old in Directory.EnumerateFiles(folder))+ TryDelete(old);++ var partial = target + ".part";+ await DownloadAsync(installer, partial, progress, cancellationToken);+ var actual = await Sha256Async(partial, cancellationToken);+ if (actual != expected)+ {+ TryDelete(partial);+ throw new InvalidDataException($"{installer.Name}: SHA-256 {actual} does not match {expected}");+ }+ File.Move(partial, target, overwrite: true);+ return target;+ }++ private async Task DownloadAsync(ReleaseFile file, string path, IProgress<int>? progress, CancellationToken cancellationToken)+ {+ using var stall = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);+ stall.CancelAfter(StallTimeout);+ using var request = new HttpRequestMessage(HttpMethod.Get, file.Url);+ request.Headers.Accept.ParseAdd("application/octet-stream");+ using var response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, stall.Token);+ response.EnsureSuccessStatusCode();++ var total = response.Content.Headers.ContentLength ?? file.Size;+ await using var source = await response.Content.ReadAsStreamAsync(stall.Token);+ await using var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 81920, useAsync: true);+ var buffer = new byte[81920];+ long received = 0;+ var lastPercent = -1;+ int read;+ while ((read = await source.ReadAsync(buffer, stall.Token)) > 0)+ {+ stall.CancelAfter(StallTimeout); // the timeout is for silence, not for the whole 100 MB+ await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);+ received += read;+ var percent = total > 0 ? (int)Math.Min(100, received * 100 / total) : 0;+ if (percent != lastPercent)+ progress?.Report(lastPercent = percent);+ }+ if (file.Size > 0 && received != file.Size)+ throw new IOException($"{file.Name}: got {received} of {file.Size} bytes");+ }++ private async Task<string> GetTextAsync(string url, CancellationToken cancellationToken)+ {+ using var request = new HttpRequestMessage(HttpMethod.Get, url);+ request.Headers.Accept.ParseAdd("application/octet-stream");+ using var response = await _http.SendAsync(request, cancellationToken);+ response.EnsureSuccessStatusCode();+ return await response.Content.ReadAsStringAsync(cancellationToken);+ }++ /// <summary>Opens a download page: the website for installed copies, the release page (portable zip) otherwise.</summary>public void OpenDownloadPage(){+ var url = IsInstalled ? WebsiteUrl : LatestReleaseUrl;try{- Process.Start(new ProcessStartInfo(LatestReleaseUrl) { UseShellExecute = true });+ Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });}- catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)+ catch (Exception ex) when (ex is Win32Exception or InvalidOperationException){- _log.LogWarning(ex, "Could not open {Url}", LatestReleaseUrl);+ _log.LogWarning(ex, "Could not open {Url}", url);}}+ private void Fail(string stage, Exception ex)+ {+ _log.LogWarning(ex, "In-app update failed ({Stage}); opening the download page", stage);+ Step = UpdateStep.Failed;+ OpenDownloadPage();+ }+private void Publish(string? newer){var previous = LatestVersion;@@ -133,6 +328,63 @@ public sealed partial class UpdateService : ObservableObjectUpdateFound?.Invoke(this, newer);}+ /// <summary>A file attached to a release.</summary>+ internal sealed record ReleaseFile(string Name, string Url, long Size);++ /// <summary>Picks the Windows installer and the checksum file from a GitHub release (null when missing).</summary>+ internal static (ReleaseFile? Installer, ReleaseFile? Checksums) FindFiles(JsonElement release)+ {+ ReleaseFile? installer = null, checksums = null;+ if (!release.TryGetProperty("assets", out var assets) || assets.ValueKind != JsonValueKind.Array)+ return (null, null);+ foreach (var asset in assets.EnumerateArray())+ {+ var name = asset.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";+ var url = asset.TryGetProperty("browser_download_url", out var u) ? u.GetString() ?? "" : "";+ var size = asset.TryGetProperty("size", out var s) && s.TryGetInt64(out var bytes) ? bytes : 0;+ if (name.Length == 0 || !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))+ continue;+ if (name.EndsWith("-win-Setup.exe", StringComparison.OrdinalIgnoreCase))+ installer = new ReleaseFile(name, url, size);+ else if (name.EndsWith("-SHA256SUMS.txt", StringComparison.OrdinalIgnoreCase))+ checksums = new ReleaseFile(name, url, size);+ }+ return (installer, checksums);+ }++ /// <summary>Finds the hash for <paramref name="fileName"/> in a <c>sha256sum</c>-style file ("hash name" lines).</summary>+ internal static string? ParseChecksum(string sums, string fileName)+ {+ foreach (var line in sums.Split('\n'))+ {+ var parts = line.Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);+ if (parts.Length == 2 && parts[1].Trim().TrimStart('*') == fileName && parts[0].Length == 64)+ return parts[0].ToLowerInvariant();+ }+ return null;+ }++ /// <summary>Lets tests hand in a release without calling GitHub.</summary>+ internal void UseRelease(ReleaseFile? installer, ReleaseFile? checksums) => (_installer, _checksums) = (installer, checksums);++ private static async Task<string> Sha256Async(string path, CancellationToken cancellationToken)+ {+ await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true);+ return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, cancellationToken));+ }++ private void TryDelete(string path)+ {+ try+ {+ File.Delete(path);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ _log.LogInformation("Could not delete {Path}: {Message}", path, ex.Message);+ }+ }+/// <summary>True when release tag <paramref name="tag"/> ("v1.2.0") is a higher version than <paramref name="current"/>.</summary>internal static bool IsNewer(string? tag, string current) =>TryParse(tag, out var latest) && TryParse(current, out var installed) && latest > installed;diff --git a/src/Filee.App/Services/UpdateTexts.cs b/src/Filee.App/Services/UpdateTexts.csnew file mode 100644index 00000000..954e244d--- /dev/null+++ b/src/Filee.App/Services/UpdateTexts.cs@@ -0,0 +1,36 @@+// Labels for the update buttons and status lines, shared by the sidebar, the tray, Settings > General and the notice.++using Filee.Core.Localization;++namespace Filee.App.Services;++public static class UpdateTexts+{+ /// <summary>Button text: "Update" in an installed copy (it installs by itself), "Download" in a portable one.</summary>+ public static string ButtonKey => UpdateService.IsInstalled ? "update.install" : "update.download";++ /// <summary>What the update button does, for the notice and tooltips.</summary>+ public static string HowKey => UpdateService.IsInstalled ? "update.notice_text" : "update.notice_text_portable";++ /// <summary>Short label for the sidebar button and the tray menu ("Update to 1.4.0", "Downloading… 42%").</summary>+ public static string Short(UpdateService updates, ILocalizer loc) => updates.Step switch+ {+ UpdateStep.Downloading => loc.Format("update.downloading", updates.DownloadPercent),+ UpdateStep.Installing => loc["update.installing_short"],+ _ => updates.LatestVersion is { } latest ? loc.Format("update.sidebar", latest) : "",+ };++ /// <summary>A sentence about the update in progress, or null when nothing is going on.</summary>+ public static string? Status(UpdateService updates, ILocalizer loc) => updates.Step switch+ {+ UpdateStep.Downloading => loc.Format("update.downloading", updates.DownloadPercent),+ UpdateStep.Installing => loc["update.installing"],+ UpdateStep.Failed => loc["update.failed"],+ UpdateStep.Cancelled => loc["update.cancelled"],+ _ => null,+ };++ /// <summary>True for property changes that alter the texts above.</summary>+ public static bool Affects(string? propertyName) =>+ propertyName is nameof(UpdateService.LatestVersion) or nameof(UpdateService.Step) or nameof(UpdateService.DownloadPercent);+}diff --git a/src/Filee.App/Services/WindowService.cs b/src/Filee.App/Services/WindowService.csindex 8fd5734d..222a8c9b 100644--- a/src/Filee.App/Services/WindowService.cs+++ b/src/Filee.App/Services/WindowService.cs@@ -73,7 +73,7 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services)public void ShowUpdateNotice(string version){_updateNotice?.Close();- var notice = new UpdateNoticeWindow(services.GetRequiredService<UpdateService>(), loc.Format("update.notice_title", version))+ var notice = new UpdateNoticeWindow(services.GetRequiredService<UpdateService>(), loc, loc.Format("update.notice_title", version)){BottomOffset = _toast is { IsVisible: true } toast? (int)Math.Ceiling(toast.Bounds.Height * (toast.Screens.Primary?.Scaling ?? 1))diff --git a/src/Filee.App/ViewModels/MainWindowViewModel.cs b/src/Filee.App/ViewModels/MainWindowViewModel.csindex 09ef6fc7..37b8c6ac 100644--- a/src/Filee.App/ViewModels/MainWindowViewModel.cs+++ b/src/Filee.App/ViewModels/MainWindowViewModel.cs@@ -38,7 +38,7 @@ public sealed partial class MainWindowViewModel : ObservableObjectUpdates = updates;updates.PropertyChanged += (_, e) =>{- if (e.PropertyName == nameof(UpdateService.LatestVersion))+ if (UpdateTexts.Affects(e.PropertyName))RefreshVersionTexts();};RefreshVersionTexts();@@ -84,15 +84,17 @@ public sealed partial class MainWindowViewModel : ObservableObjectpublic ScrollBarVisibility PageScroll => CurrentPage is IFitsWindowHeight ? ScrollBarVisibility.Disabled : ScrollBarVisibility.Auto;[ObservableProperty] private string _versionText = "";[ObservableProperty] private string _updateText = "";+ [ObservableProperty] private string _updateTip = "";- /// <summary>Opens the latest release page to download the new installer.</summary>+ /// <summary>Downloads and runs the new installer (or opens the download page in a portable copy).</summary>[RelayCommand]- private void DownloadUpdate() => Updates.OpenDownloadPage();+ private Task DownloadUpdate() => Updates.UpdateAsync();private void RefreshVersionTexts(){VersionText = _loc.Format("about.version", UpdateService.CurrentVersion);- UpdateText = Updates.LatestVersion is { } latest ? _loc.Format("update.sidebar", latest) : "";+ UpdateText = UpdateTexts.Short(Updates, _loc);+ UpdateTip = UpdateTexts.Status(Updates, _loc) ?? _loc[UpdateTexts.HowKey];}public void Navigate(string key)diff --git a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.csindex 51e715e2..86092656 100644--- a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs@@ -5,11 +5,12 @@ using CommunityToolkit.Mvvm.Input;using Filee.App.Services;using Filee.Core.Localization;using Filee.Core.Platform;+using Filee.Core.Presets;using Filee.Core.Settings;namespace Filee.App.ViewModels.Pages;-public sealed partial class GeneralPageViewModel : ObservableObject+public sealed partial class GeneralPageViewModel : ObservableObject, IDisposable{private readonly UserDataStore _store;private readonly ILocalizer _loc;@@ -33,15 +34,53 @@ public sealed partial class GeneralPageViewModel : ObservableObject_contextMenu = store.Settings.ContextMenuEnabled;_checkForUpdates = store.Settings.CheckForUpdates;_noHistory = !store.Settings.KeepHistory;+ OutputLocations = new[] { OutputLocation.SameFolder, OutputLocation.Subfolder, OutputLocation.CustomFolder }+ .Select(v => new Choice<OutputLocation>(v, loc[$"presets.location.{v}"])).ToList();+ var output = store.Settings.DefaultOutput;+ _defaultLocation = OutputLocations.FirstOrDefault(l => l.Value == output.Location) ?? OutputLocations[0];+ _defaultSubfolder = output.SubfolderName;+ _defaultFolder = output.CustomFolder;_historyCount = store.History.Count;ShowUpdateState(updates.LatestVersion);+ updates.PropertyChanged += OnUpdatesChanged;RefreshModernMenu();}+ /// <summary>The page is rebuilt on every visit; the update service lives on.</summary>+ public void Dispose() => _updates.PropertyChanged -= OnUpdatesChanged;++ private void OnUpdatesChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)+ {+ if (UpdateTexts.Affects(e.PropertyName))+ ShowUpdateState(_updates.LatestVersion);+ }++ /// <summary>"Update" in an installed copy, "Download" in a portable one.</summary>+ public string UpdateButtonText => _loc[UpdateTexts.ButtonKey];+public IReadOnlyList<Choice<string>> Languages { get; }public string DataFolder => _store.Directory;public bool IsWindows => OperatingSystem.IsWindows();+ /// <summary>Choices for the default save location (everything but "Default" itself).</summary>+ public IReadOnlyList<Choice<OutputLocation>> OutputLocations { get; }++ [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowDefaultSubfolder), nameof(ShowDefaultFolder))]+ private Choice<OutputLocation> _defaultLocation;++ [ObservableProperty] private string _defaultSubfolder;+ [ObservableProperty] private string _defaultFolder;++ public bool ShowDefaultSubfolder => DefaultLocation.Value == OutputLocation.Subfolder;+ public bool ShowDefaultFolder => DefaultLocation.Value == OutputLocation.CustomFolder;++ partial void OnDefaultLocationChanged(Choice<OutputLocation> value) => Save(s => s.DefaultOutput.Location = value.Value);++ partial void OnDefaultSubfolderChanged(string value) =>+ Save(s => s.DefaultOutput.SubfolderName = string.IsNullOrWhiteSpace(value) ? "converted" : value.Trim());++ partial void OnDefaultFolderChanged(string value) => Save(s => s.DefaultOutput.CustomFolder = value.Trim());+[ObservableProperty] private Choice<string> _language;[ObservableProperty] private bool _startWithSystem;[ObservableProperty] private bool _contextMenu;@@ -157,14 +196,15 @@ public sealed partial class GeneralPageViewModel : ObservableObject[RelayCommand]private async Task CheckNow() => ShowUpdateState(await _updates.CheckAsync(), afterCheck: true);- /// <summary>Opens the latest release page; the new installer updates Filee in place.</summary>+ /// <summary>Downloads and runs the new installer, which updates Filee in place (a portable copy opens the download page).</summary>[RelayCommand]- private void DownloadUpdate() => _updates.OpenDownloadPage();+ private Task DownloadUpdate() => _updates.UpdateAsync();private void ShowUpdateState(string? newer, bool afterCheck = false){- UpdateAvailable = newer is not null;- UpdateStatus = newer is not null ? _loc.Format("general.update_available", newer)+ UpdateAvailable = newer is not null && !_updates.IsBusy;+ UpdateStatus = UpdateTexts.Status(_updates, _loc) is { } progress ? progress+ : newer is not null ? _loc.Format("general.update_available", newer): afterCheck ? _loc.Format("general.update_none", UpdateService.CurrentVersion): _loc.Format("about.version", UpdateService.CurrentVersion);}diff --git a/src/Filee.App/Views/MainWindow.axaml b/src/Filee.App/Views/MainWindow.axamlindex 67cb631b..7bd24e27 100644--- a/src/Filee.App/Views/MainWindow.axaml+++ b/src/Filee.App/Views/MainWindow.axaml@@ -23,7 +23,7 @@<StackPanel DockPanel.Dock="Bottom" Spacing="8" Margin="4,12,4,0"><Button x:Name="UpdateButton" Classes="accent" HorizontalAlignment="Stretch" HorizontalContentAlignment="Left"Command="{Binding DownloadUpdateCommand}" IsVisible="{Binding Updates.IsUpdateAvailable}"- ToolTip.Tip="{DynamicResource update.notice_text}">+ ToolTip.Tip="{Binding UpdateTip}"><StackPanel Orientation="Horizontal" Spacing="8"><PathIcon Width="14" Height="14" Data="{StaticResource Icon.Download}" /><TextBlock Text="{Binding UpdateText}" TextTrimming="CharacterEllipsis" />diff --git a/src/Filee.App/Views/Pages/GeneralPage.axaml b/src/Filee.App/Views/Pages/GeneralPage.axamlindex df72fe9a..806fe7a6 100644--- a/src/Filee.App/Views/Pages/GeneralPage.axaml+++ b/src/Filee.App/Views/Pages/GeneralPage.axaml@@ -25,6 +25,26 @@</StackPanel></Border>+ <!-- Where presets set to "Default" save (AppSettings.DefaultOutput). -->+ <Border Classes="card">+ <StackPanel Spacing="10">+ <TextBlock Classes="h2" Text="{DynamicResource general.default_output}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource general.default_output_hint}" />+ <ComboBox ItemsSource="{Binding OutputLocations}" SelectedItem="{Binding DefaultLocation}" MinWidth="240" />+ <StackPanel IsVisible="{Binding ShowDefaultSubfolder}">+ <TextBlock Classes="label" Text="{DynamicResource presets.subfolder}" />+ <TextBox Text="{Binding DefaultSubfolder}" PlaceholderText="converted" MaxWidth="420" HorizontalAlignment="Left" MinWidth="240" />+ </StackPanel>+ <StackPanel IsVisible="{Binding ShowDefaultFolder}">+ <TextBlock Classes="label" Text="{DynamicResource presets.custom_folder}" />+ <DockPanel MaxWidth="560" HorizontalAlignment="Stretch">+ <Button DockPanel.Dock="Right" Margin="8,0,0,0" Content="{DynamicResource presets.browse}" Click="OnBrowseDefaultFolder" />+ <TextBox Text="{Binding DefaultFolder}" />+ </DockPanel>+ </StackPanel>+ </StackPanel>+ </Border>+<Border Classes="card"><StackPanel Spacing="12"><ToggleSwitch Content="{DynamicResource general.check_updates}" IsChecked="{Binding CheckForUpdates}" />@@ -33,7 +53,7 @@<Button Classes="accent" Command="{Binding DownloadUpdateCommand}" IsVisible="{Binding UpdateAvailable}"><StackPanel Orientation="Horizontal" Spacing="6"><PathIcon Width="13" Height="13" Data="{StaticResource Icon.Download}" />- <TextBlock Text="{DynamicResource update.download}" />+ <TextBlock Text="{Binding UpdateButtonText}" /></StackPanel></Button><TextBlock Classes="muted" VerticalAlignment="Center" Text="{Binding UpdateStatus}" />diff --git a/src/Filee.App/Views/Pages/GeneralPage.axaml.cs b/src/Filee.App/Views/Pages/GeneralPage.axaml.csindex 69a0cf7e..d7b58d98 100644--- a/src/Filee.App/Views/Pages/GeneralPage.axaml.cs+++ b/src/Filee.App/Views/Pages/GeneralPage.axaml.cs@@ -29,6 +29,15 @@ public partial class GeneralPage : UserControlVm.Export(path);}+ private async void OnBrowseDefaultFolder(object? sender, RoutedEventArgs e)+ {+ if (Vm is null || TopLevel.GetTopLevel(this) is not { } top)+ return;+ var folders = await top.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { AllowMultiple = false });+ if (folders.FirstOrDefault()?.TryGetLocalPath() is { } path)+ Vm.DefaultFolder = path;+ }+private async void OnImport(object? sender, RoutedEventArgs e){if (Vm is null || TopLevel.GetTopLevel(this) is not { } top)diff --git a/src/Filee.App/Views/UpdateNoticeWindow.axaml b/src/Filee.App/Views/UpdateNoticeWindow.axamlindex 801ff33d..8fc8f121 100644--- a/src/Filee.App/Views/UpdateNoticeWindow.axaml+++ b/src/Filee.App/Views/UpdateNoticeWindow.axaml@@ -23,12 +23,13 @@</Button><TextBlock x:Name="TitleText" FontWeight="SemiBold" TextWrapping="Wrap" VerticalAlignment="Center" /></DockPanel>- <TextBlock Classes="caption" Text="{DynamicResource update.notice_text}" TextWrapping="Wrap" />- <StackPanel Orientation="Horizontal" Spacing="8" Margin="0,2,0,0">+ <TextBlock x:Name="CaptionText" Classes="caption" TextWrapping="Wrap" />+ <ProgressBar x:Name="Progress" Minimum="0" Maximum="100" IsVisible="False" />+ <StackPanel x:Name="Buttons" Orientation="Horizontal" Spacing="8" Margin="0,2,0,0"><Button Classes="accent" Click="OnDownload" Padding="12,5"><StackPanel Orientation="Horizontal" Spacing="6"><PathIcon Width="13" Height="13" Data="{StaticResource Icon.Download}" />- <TextBlock Text="{DynamicResource update.download}" />+ <TextBlock x:Name="DownloadText" /></StackPanel></Button><Button Content="{DynamicResource update.later}" Click="OnClose" Padding="12,5" />diff --git a/src/Filee.App/Views/UpdateNoticeWindow.axaml.cs b/src/Filee.App/Views/UpdateNoticeWindow.axaml.csindex 2d5a2c3b..904ef1c4 100644--- a/src/Filee.App/Views/UpdateNoticeWindow.axaml.cs+++ b/src/Filee.App/Views/UpdateNoticeWindow.axaml.cs@@ -1,37 +1,72 @@+using System.ComponentModel;using Avalonia;using Avalonia.Controls;using Avalonia.Interactivity;using Filee.App.Services;+using Filee.Core.Localization;namespace Filee.App.Views;-/// <summary>Bottom-right notice about a new version. "Download" opens the latest release page.</summary>+/// <summary>+/// Bottom-right notice about a new version. "Update" downloads and runs the new installer and the card shows the+/// download progress; a portable copy gets "Download", which opens the release page.+/// </summary>public partial class UpdateNoticeWindow : Window{private const int ScreenMargin = 12;private readonly UpdateService? _updates;+ private readonly ILocalizer? _loc;public UpdateNoticeWindow() => InitializeComponent();- public UpdateNoticeWindow(UpdateService updates, string title) : this()+ public UpdateNoticeWindow(UpdateService updates, ILocalizer loc, string title) : this(){_updates = updates;+ _loc = loc;TitleText.Text = title;+ DownloadText.Text = loc[UpdateTexts.ButtonKey];Motion.Track(this);SizeChanged += (_, _) => PlaceBottomRight();+ updates.PropertyChanged += OnUpdatesChanged;+ Closed += (_, _) => updates.PropertyChanged -= OnUpdatesChanged;+ ShowState();}/// <summary>Extra distance from the bottom of the screen, e.g. to stay above the conversion toast.</summary>public int BottomOffset { get; set; }- private void OnDownload(object? sender, RoutedEventArgs e)+ private async void OnDownload(object? sender, RoutedEventArgs e){- _updates?.OpenDownloadPage();- Close();+ if (_updates is null)+ return;+ if (!UpdateService.IsInstalled)+ {+ _updates.OpenDownloadPage();+ Close();+ return;+ }+ // Stays open: the download takes a while and this card is where the user is looking.+ await _updates.UpdateAsync();}private void OnClose(object? sender, RoutedEventArgs e) => Close();+ private void OnUpdatesChanged(object? sender, PropertyChangedEventArgs e)+ {+ if (UpdateTexts.Affects(e.PropertyName))+ ShowState();+ }++ private void ShowState()+ {+ if (_updates is null || _loc is null)+ return;+ CaptionText.Text = UpdateTexts.Status(_updates, _loc) ?? _loc[UpdateTexts.HowKey];+ Progress.IsVisible = _updates.Step == UpdateStep.Downloading;+ Progress.Value = _updates.DownloadPercent;+ Buttons.IsVisible = !_updates.IsBusy;+ }+private void PlaceBottomRight(){var screen = Screens.Primary;diff --git a/src/Filee.Core/Presets/OutputRule.cs b/src/Filee.Core/Presets/OutputRule.csindex 62d046c5..564e8e89 100644--- a/src/Filee.Core/Presets/OutputRule.cs+++ b/src/Filee.Core/Presets/OutputRule.cs@@ -5,6 +5,11 @@ namespace Filee.Core.Presets;/// <summary>Where converted files go.</summary>public enum OutputLocation{+ /// <summary>+ /// The default save location from Settings → General (<see cref="Settings.AppSettings.DefaultOutput"/>). Where+ /// nothing resolves it (the command line), it means <see cref="SameFolder"/>.+ /// </summary>+ Default,/// <summary>Next to the source file.</summary>SameFolder,/// <summary>In a sub folder (see <see cref="OutputRule.SubfolderName"/>) next to the source file.</summary>@@ -27,7 +32,7 @@ public enum ConflictPolicy/// <summary>Output placement and naming rules.</summary>public sealed class OutputRule{- public OutputLocation Location { get; set; } = OutputLocation.SameFolder;+ public OutputLocation Location { get; set; } = OutputLocation.Default;public string SubfolderName { get; set; } = "converted";diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.csindex 51cb09a4..37b2d6fa 100644--- a/src/Filee.Core/Settings/AppSettings.cs+++ b/src/Filee.Core/Settings/AppSettings.cs@@ -1,5 +1,7 @@// Root settings object persisted to settings.json.+using Filee.Core.Presets;+namespace Filee.Core.Settings;public enum ThemeMode@@ -48,7 +50,7 @@ public sealed class DonutSettingspublic sealed class AppSettings{/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>- public const int CurrentSchemaVersion = 7;+ public const int CurrentSchemaVersion = 8;public int SchemaVersion { get; set; } = CurrentSchemaVersion;@@ -99,4 +101,33 @@ public sealed class AppSettings/// <summary>Folders whose new files are converted automatically (Settings → Watch folders).</summary>public List<Watching.WatchRule> WatchFolders { get; set; } = [];++ /// <summary>Where presets set to "Default" save (Settings → General).</summary>+ public DefaultOutputSettings DefaultOutput { get; set; } = new();++ /// <summary>+ /// Returns <paramref name="preset"/> itself, or a copy that saves to <see cref="DefaultOutput"/> when the preset's+ /// location is <see cref="OutputLocation.Default"/>. Name pattern, conflict handling and dates stay the preset's.+ /// </summary>+ public Preset WithDefaultOutput(Preset preset)+ {+ if (preset.Output.Location != OutputLocation.Default)+ return preset;+ var copy = preset.Clone();+ copy.Output.Location = DefaultOutput.Location == OutputLocation.Default ? OutputLocation.SameFolder : DefaultOutput.Location;+ copy.Output.SubfolderName = DefaultOutput.SubfolderName;+ copy.Output.CustomFolder = DefaultOutput.CustomFolder;+ return copy;+ }+}++/// <summary>The save location presets set to "Default" use. Starts as "next to the source file", as before 1.4.</summary>+public sealed class DefaultOutputSettings+{+ /// <summary><see cref="OutputLocation.SameFolder"/>, <see cref="OutputLocation.Subfolder"/> or <see cref="OutputLocation.CustomFolder"/>.</summary>+ public OutputLocation Location { get; set; } = OutputLocation.SameFolder;++ public string SubfolderName { get; set; } = "converted";++ public string CustomFolder { get; set; } = "";}diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.csindex 867a9ee8..92f261ec 100644--- a/src/Filee.Core/Settings/UserDataStore.cs+++ b/src/Filee.Core/Settings/UserDataStore.cs@@ -326,6 +326,18 @@ internal static class SettingsMigrationsforeach (var (profile, preset, after) in Version7Offers)changed |= Offer(presets, profiles, profile, preset, after);}++ // v8: Settings → General has a default save location. "Same folder as the source" was the default until now,+ // so presets still on it follow the new setting, which starts as the same folder: nothing moves until the+ // user picks another default.+ if (from < 8)+ {+ foreach (var preset in presets.Where(p => p.Output.Location == OutputLocation.SameFolder))+ {+ preset.Output.Location = OutputLocation.Default;+ changed = true;+ }+ }return changed;}diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.csindex faa69276..30239158 100644--- a/tests/Filee.App.Tests/RenderTests.cs+++ b/tests/Filee.App.Tests/RenderTests.cs@@ -217,10 +217,20 @@ public class RenderTestsAssert.Contains("9.9.9", vm.UpdateText);Save(window, $"sidebar-update-{language}.png");- var notice = new UpdateNoticeWindow(updates, AppHost.Get<Filee.Core.Localization.ILocalizer>().Format("update.notice_title", "9.9.9"));+ var loc = AppHost.Get<Filee.Core.Localization.ILocalizer>();+ var notice = new UpdateNoticeWindow(updates, loc, loc.Format("update.notice_title", "9.9.9"));notice.Show();Pump();Save(notice, $"update-notice-{language}.png");++ // While the installer downloads, the card, the sidebar button and the tray show the progress.+ updates.Step = UpdateStep.Downloading;+ updates.DownloadPercent = 42;+ Pump();+ Assert.Contains("42", vm.UpdateText);+ Save(notice, $"update-notice-downloading-{language}.png");+ Save(window, $"sidebar-update-downloading-{language}.png");+ updates.Step = UpdateStep.Idle;notice.Close();var feedback = new FeedbackNoticeWindow();@@ -231,6 +241,7 @@ public class RenderTests}finally{+ updates.Step = UpdateStep.Idle;updates.LatestVersion = null;window.Close();}diff --git a/tests/Filee.App.Tests/UpdateServiceTests.cs b/tests/Filee.App.Tests/UpdateServiceTests.csindex 3820ece0..38f1e879 100644--- a/tests/Filee.App.Tests/UpdateServiceTests.cs+++ b/tests/Filee.App.Tests/UpdateServiceTests.cs@@ -1,5 +1,8 @@using System.Net;using System.Net.Sockets;+using System.Security.Cryptography;+using System.Text;+using System.Text.Json;using Filee.App.Services;using Microsoft.Extensions.Logging.Abstractions;@@ -59,6 +62,171 @@ public class UpdateServiceTestspublic override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();}+ // ───────── In-app update: find, download and verify the installer ─────────++ private const string Base = "https://example.test/v9.9.9/";++ [Fact]+ public void Release_files_are_the_installer_and_the_checksums()+ {+ using var release = JsonDocument.Parse($$"""+ {"tag_name": "v9.9.9", "assets": [+ {"name": "Filee-9.9.9-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-SHA256SUMS.txt"},+ {"name": "Filee-9.9.9-win-Portable.zip", "size": 5, "browser_download_url": "{{Base}}Filee-9.9.9-win-Portable.zip"},+ {"name": "Filee-9.9.9-win-Setup.exe", "size": 1234, "browser_download_url": "{{Base}}Filee-9.9.9-win-Setup.exe"}+ ]}+ """);++ var (installer, checksums) = UpdateService.FindFiles(release.RootElement);++ Assert.Equal(new UpdateService.ReleaseFile("Filee-9.9.9-win-Setup.exe", Base + "Filee-9.9.9-win-Setup.exe", 1234), installer);+ Assert.Equal("Filee-9.9.9-SHA256SUMS.txt", checksums?.Name);+ }++ [Fact]+ public void Release_without_files_or_with_plain_http_links_has_no_installer()+ {+ using var empty = JsonDocument.Parse("""{"tag_name": "v9.9.9"}""");+ using var http = JsonDocument.Parse("""+ {"assets": [{"name": "Filee-9.9.9-win-Setup.exe", "size": 1, "browser_download_url": "http://example.test/a.exe"}]}+ """);++ Assert.Equal((null, null), UpdateService.FindFiles(empty.RootElement));+ Assert.Null(UpdateService.FindFiles(http.RootElement).Installer);+ }++ [Fact]+ public void Checksum_lines_are_matched_by_file_name()+ {+ var hash = new string('A', 64);+ var sums = $"{new string('1', 64)} Filee-9.9.9-win-Portable.zip\r\n{hash} Filee-9.9.9-win-Setup.exe\r\n";++ Assert.Equal(hash.ToLowerInvariant(), UpdateService.ParseChecksum(sums, "Filee-9.9.9-win-Setup.exe"));+ Assert.Equal(hash.ToLowerInvariant(), UpdateService.ParseChecksum($"{hash} *Filee-9.9.9-win-Setup.exe", "Filee-9.9.9-win-Setup.exe"));+ Assert.Null(UpdateService.ParseChecksum(sums, "Filee-9.9.8-win-Setup.exe"));+ Assert.Null(UpdateService.ParseChecksum("tooshort Filee-9.9.9-win-Setup.exe", "Filee-9.9.9-win-Setup.exe"));+ }++ [Fact]+ public async Task Installer_is_downloaded_verified_and_reused()+ {+ var installer = RandomNumberGenerator.GetBytes(300_000);+ var network = new FakeRelease(installer, Sha256(installer));+ var updates = Updates(network, installer.Length);+ var folder = TempFolder();+ File.WriteAllText(Path.Combine(folder, "Filee-9.9.8-win-Setup.exe"), "an older download");+ var progress = new List<int>();++ var path = await updates.DownloadInstallerAsync(folder, new SyncProgress(progress.Add), TestContext.Current.CancellationToken);++ Assert.Equal(Path.Combine(folder, "Filee-9.9.9-win-Setup.exe"), path);+ Assert.Equal(installer, File.ReadAllBytes(path));+ Assert.Equal([path], Directory.GetFiles(folder)); // the older download and the .part file are gone+ Assert.Equal(100, progress[^1]);+ Assert.True(progress.SequenceEqual(progress.Order()), "progress only goes up");++ // Pressing Update again (e.g. after saying no to the administrator prompt) does not download it again.+ await updates.DownloadInstallerAsync(folder, null, TestContext.Current.CancellationToken);+ Assert.Equal(1, network.InstallerRequests);+ }++ [Fact]+ public async Task Installer_with_the_wrong_checksum_is_thrown_away()+ {+ var installer = RandomNumberGenerator.GetBytes(10_000);+ var updates = Updates(new FakeRelease(installer, new string('0', 64)), installer.Length);+ var folder = TempFolder();++ await Assert.ThrowsAsync<InvalidDataException>(() =>+ updates.DownloadInstallerAsync(folder, null, TestContext.Current.CancellationToken));+ Assert.Empty(Directory.GetFiles(folder));+ }++ [Fact]+ public async Task Cut_off_download_fails()+ {+ var installer = RandomNumberGenerator.GetBytes(10_000);+ // GitHub said the file is bigger than what arrived.+ var updates = Updates(new FakeRelease(installer, Sha256(installer)), installer.Length + 500);++ await Assert.ThrowsAsync<IOException>(() =>+ updates.DownloadInstallerAsync(TempFolder(), null, TestContext.Current.CancellationToken));+ }++ [Fact]+ public async Task Checksum_file_without_the_installer_fails()+ {+ var installer = RandomNumberGenerator.GetBytes(1_000);+ var updates = Updates(new FakeRelease(installer, Sha256(installer), sumsName: "Filee-9.9.8-win-Setup.exe"), installer.Length);++ await Assert.ThrowsAsync<InvalidDataException>(() =>+ updates.DownloadInstallerAsync(TempFolder(), null, TestContext.Current.CancellationToken));+ }++ [Fact]+ public async Task Download_errors_are_reported_as_http_errors()+ {+ var installer = RandomNumberGenerator.GetBytes(1_000);+ var updates = Updates(new FakeRelease(installer, Sha256(installer), installerStatus: HttpStatusCode.NotFound), installer.Length);++ await Assert.ThrowsAsync<HttpRequestException>(() =>+ updates.DownloadInstallerAsync(TempFolder(), null, TestContext.Current.CancellationToken));+ }++ [Fact]+ public void Installer_runs_without_the_wizard_and_without_restarting_windows()+ {+ Assert.Contains("/SILENT", UpdateService.InstallerArguments);+ Assert.Contains("/NORESTART", UpdateService.InstallerArguments);+ }++ private static UpdateService Updates(FakeRelease network, long installerSize)+ {+ var updates = new UpdateService(NullLogger<UpdateService>.Instance, network);+ updates.UseRelease(new UpdateService.ReleaseFile("Filee-9.9.9-win-Setup.exe", Base + "Filee-9.9.9-win-Setup.exe", installerSize),+ new UpdateService.ReleaseFile("Filee-9.9.9-SHA256SUMS.txt", Base + "Filee-9.9.9-SHA256SUMS.txt", 100));+ return updates;+ }++ private static string Sha256(byte[] data) => Convert.ToHexStringLower(SHA256.HashData(data));++ private static string TempFolder()+ {+ var folder = Path.Combine(Path.GetTempPath(), "filee-update-test-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(folder);+ return folder;+ }++ /// <summary>Reports on the calling thread (Progress<T> posts later, which makes the order racy in tests).</summary>+ private sealed class SyncProgress(Action<int> report) : IProgress<int>+ {+ public void Report(int value) => report(value);+ }++ /// <summary>Serves a release's checksum file and installer.</summary>+ private sealed class FakeRelease(byte[] installer, string hash, string sumsName = "Filee-9.9.9-win-Setup.exe",+ HttpStatusCode installerStatus = HttpStatusCode.OK) : HttpMessageHandler+ {+ public int InstallerRequests { get; private set; }++ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)+ {+ var url = request.RequestUri!.ToString();+ if (url.EndsWith("SHA256SUMS.txt", StringComparison.Ordinal))+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)+ {+ Content = new StringContent($"{new string('1', 64)} Filee-9.9.9-win-Portable.zip\n{hash} {sumsName}\n", Encoding.ASCII),+ });+ if (url.EndsWith("-win-Setup.exe", StringComparison.Ordinal))+ {+ InstallerRequests++;+ Assert.Contains("application/octet-stream", request.Headers.Accept.ToString());+ return Task.FromResult(new HttpResponseMessage(installerStatus) { Content = new ByteArrayContent(installer) });+ }+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound));+ }+ }+[Fact]public void Download_page_is_the_latest_release(){diff --git a/tests/Filee.Core.Tests/DefaultOutputTests.cs b/tests/Filee.Core.Tests/DefaultOutputTests.csnew file mode 100644index 00000000..a78207e9--- /dev/null+++ b/tests/Filee.Core.Tests/DefaultOutputTests.cs@@ -0,0 +1,117 @@+using Filee.Core.Presets;+using Filee.Core.Settings;++namespace Filee.Core.Tests;++/// <summary>The default save location in Settings → General and the presets that follow it.</summary>+public class DefaultOutputTests+{+ [Fact]+ public void New_and_built_in_presets_follow_the_default()+ {+ Assert.Equal(OutputLocation.Default, new Preset().Output.Location);+ // Only presets that need their own place keep it (PDF split pages go into a folder per document).+ Assert.All(BuiltInData.CreatePresets().Where(p => p.Id != "pdf-split"),+ p => Assert.Equal(OutputLocation.Default, p.Output.Location));+ }++ [Fact]+ public void Default_starts_as_the_source_folder_like_before()+ {+ var settings = new AppSettings();+ var preset = new Preset { TargetFormat = "png", Output = { FileNamePattern = "{name}_x" } };++ var used = settings.WithDefaultOutput(preset);++ Assert.Equal(OutputLocation.SameFolder, used.Output.Location);+ Assert.Equal("{name}_x", used.Output.FileNamePattern);+ Assert.Equal(OutputLocation.Default, preset.Output.Location); // the saved preset is not changed+ }++ [Fact]+ public void Presets_on_default_save_to_the_folder_from_settings()+ {+ var settings = new AppSettings+ {+ DefaultOutput = { Location = OutputLocation.CustomFolder, CustomFolder = Path.Combine("D:", "Converted") },+ };+ var preset = new Preset { TargetFormat = "png", Output = { Conflict = ConflictPolicy.Overwrite, KeepDates = true } };++ var used = settings.WithDefaultOutput(preset);+ var path = OutputPathResolver.Resolve(used.Output,+ new OutputPathResolver.Tokens(Path.Combine("C:", "Users", "me", "Documents", "a.jpg"), "PNG", 1, DateTime.Now),+ "png", _ => false);++ Assert.Equal(Path.Combine("D:", "Converted", "a.png"), path);+ Assert.Equal(ConflictPolicy.Overwrite, used.Output.Conflict);+ Assert.True(used.Output.KeepDates);+ Assert.Equal(preset.Id, used.Id);+ }++ [Fact]+ public void Default_subfolder_is_next_to_the_source()+ {+ var settings = new AppSettings { DefaultOutput = { Location = OutputLocation.Subfolder, SubfolderName = "out" } };++ var used = settings.WithDefaultOutput(new Preset { TargetFormat = "png" });++ Assert.Equal(OutputLocation.Subfolder, used.Output.Location);+ Assert.Equal("out", used.Output.SubfolderName);+ }++ [Fact]+ public void Presets_with_their_own_location_ignore_the_default()+ {+ var settings = new AppSettings { DefaultOutput = { Location = OutputLocation.CustomFolder, CustomFolder = @"D:\x" } };+ var own = new Preset { Output = { Location = OutputLocation.SameFolder } };++ Assert.Same(own, settings.WithDefaultOutput(own));+ }++ [Fact]+ public void Default_without_settings_means_the_source_folder()+ {+ // The command line resolves presets without Settings → General.+ using var dir = new TempDir();+ var source = dir.File("a.jpg");++ var path = OutputPathResolver.Resolve(new OutputRule(), new OutputPathResolver.Tokens(source, "PNG", 1, DateTime.Now), "png", File.Exists);++ Assert.Equal(Path.Combine(dir.Path, "a.png"), path);+ }++ [Fact]+ public void Version_7_presets_on_the_source_folder_follow_the_default()+ {+ // As written by 1.3.1: "same folder" was the only default, a user preset chose a fixed folder.+ var presets = BuiltInData.CreatePresets();+ foreach (var preset in presets.Where(p => p.Output.Location == OutputLocation.Default))+ preset.Output.Location = OutputLocation.SameFolder;+ presets.Add(new Preset { Id = "mine", Output = { Location = OutputLocation.CustomFolder, CustomFolder = @"D:\out" } });+ var profiles = BuiltInData.CreateProfiles();++ Assert.True(SettingsMigrations.ApplyToLibrary(7, presets, profiles));++ Assert.Equal(OutputLocation.Default, presets.Single(p => p.Id == "to-png").Output.Location);+ Assert.Equal(OutputLocation.Subfolder, presets.Single(p => p.Id == "pdf-split").Output.Location);+ Assert.Equal(OutputLocation.CustomFolder, presets.Single(p => p.Id == "mine").Output.Location);+ Assert.False(SettingsMigrations.ApplyToLibrary(7, presets, profiles)); // once only+ }++ [Fact]+ public void Default_save_location_survives_a_restart()+ {+ using var dir = new TempDir();+ var store = new UserDataStore(dir.Path);+ store.Load();+ store.Settings.DefaultOutput.Location = OutputLocation.CustomFolder;+ store.Settings.DefaultOutput.CustomFolder = @"D:\Converted";+ store.SaveSettings();++ var next = new UserDataStore(dir.Path);+ next.Load();++ Assert.Equal(OutputLocation.CustomFolder, next.Settings.DefaultOutput.Location);+ Assert.Equal(@"D:\Converted", next.Settings.DefaultOutput.CustomFolder);+ }+}