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
Pictures, links and downloads dragged from a browser open the donut
KnifeLemon62f7936e9432
diff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.csindex 49d1e2f7..5ae7e683 100644--- a/src/Filee.App/App.axaml.cs+++ b/src/Filee.App/App.axaml.cs@@ -127,6 +127,8 @@ public partial class App : ApplicationAppHost.Get<WindowService>().EnsureToast();AppHost.Get<ConversionService>().FeedbackDue += (_, _) => AppHost.Get<WindowService>().ShowFeedbackNotice();AppHost.Get<WatchFolderService>().Start();+ // Originals of files from a browser that a crash kept from being deleted ("Save only the converted file").+ _ = Task.Run(() => Filee.Core.Web.WebDrop.DeleteStale(Filee.Core.Web.WebDrop.DefaultWorkRoot, TimeSpan.FromDays(1)));// Once LibreOffice is installed: prepare its profiles while the user isn't converting yet.AppHost.Get<EngineDownloadService>().WarmUpInBackground(TimeSpan.FromSeconds(10));diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 730407ed..0ab0da13 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -80,6 +80,11 @@"error.rhwp_timeout_calibre": "rhwp couldn't finish this long document in time. For an e-book, move Calibre above the HWPX writer in Settings → Engines, and Calibre makes the PDF much faster","error.needs_shaping": "This script needs LibreOffice to convert correctly. Install it in Settings → Engines","error.conversion_failed": "The engine reported an error",+ "error.web_download_failed": "Couldn't download the file",+ "error.web_page": "The link opens a web page, not a file. Filee can't download a file that needs you to sign in: save it from the browser first",+ "error.web_too_large": "The file is larger than 2 GB",+ "error.web_blocked": "Programs, installers and scripts aren't saved",+ "error.web_timeout": "The server stopped responding","notice.pdf_not_smaller": "Couldn't make it smaller, so it was copied as it is","engine.reason.not_installed": "Not installed",@@ -208,6 +213,11 @@"general.default_output_hint": "Presets set to “Default save location” save here.\nA preset with its own location keeps it.","general.keep_dates": "Keep the original file dates for every conversion","general.keep_dates_hint": "Converted files keep the original's created and modified dates, with every preset.\nOff: only presets with \"Keep the original file dates\" do it.",+ "general.browser_drops": "Files dragged from a browser",+ "general.browser_drops_hint": "Hold the key and drag a picture, a link to a file or a download out of Chrome, Edge, Firefox or Safari: the donut toolbar opens as it does for your own files. The file is saved in this folder, and presets that save next to the original put the converted file here too.\nFilee downloads a link itself, without your browser's sign-in.",+ "general.browser_drops_folder": "Save to",+ "general.browser_drops_only_converted": "Save only the converted file",+ "general.browser_drops_only_converted_hint": "The original waits in a temporary folder and is deleted once it's converted.","general.check_updates": "Check for updates automatically","general.close_action": "When I close the window","general.close.Ask": "Ask every time",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex 033e997a..3fcb96d7 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -74,6 +74,11 @@"error.rhwp_timeout_calibre": "rhwp no pudo terminar este documento largo a tiempo. Para un libro electrónico, mueve Calibre por encima del escritor HWPX en Ajustes → Motores; Calibre genera el PDF mucho más rápido","error.needs_shaping": "Este sistema de escritura necesita LibreOffice para convertirse bien. Instálalo en Ajustes → Motores","error.conversion_failed": "El motor devolvió un error",+ "error.web_download_failed": "No se pudo descargar el archivo",+ "error.web_page": "El enlace abre una página web, no un archivo. Filee no puede descargar un archivo que requiere iniciar sesión: guárdalo primero desde el navegador",+ "error.web_too_large": "El archivo supera los 2 GB",+ "error.web_blocked": "No se guardan programas, instaladores ni scripts",+ "error.web_timeout": "El servidor dejó de responder","notice.pdf_not_smaller": "No se pudo reducir su tamaño, por lo que se copió tal cual","engine.reason.not_installed": "No instalado","engine.reason.error": "Error al comprobar",@@ -197,6 +202,11 @@"general.default_output_hint": "Los ajustes preestablecidos configurados en «Carpeta de guardado predeterminada» guardan aquí.\nUn ajuste preestablecido con su propia carpeta la conserva.","general.keep_dates": "Conservar las fechas originales de los archivos en todas las conversiones","general.keep_dates_hint": "Los archivos convertidos conservan las fechas de creación y modificación del original, con todos los ajustes preestablecidos.\nDesactivado: solo lo hacen los ajustes preestablecidos con «Conservar las fechas del archivo original».",+ "general.browser_drops": "Archivos arrastrados desde un navegador",+ "general.browser_drops_hint": "Mantén pulsada la tecla y arrastra una imagen, un enlace a un archivo o una descarga desde Chrome, Edge, Firefox o Safari: el menú circular se abre igual que con tus propios archivos. El archivo se guarda en esta carpeta, y los ajustes preestablecidos que guardan junto al original también guardan aquí el archivo convertido.\nFilee descarga los enlaces por sí mismo, sin la sesión iniciada en tu navegador.",+ "general.browser_drops_folder": "Guardar en",+ "general.browser_drops_only_converted": "Guardar solo el archivo convertido",+ "general.browser_drops_only_converted_hint": "El original espera en una carpeta temporal y se elimina en cuanto se convierte.","general.check_updates": "Buscar actualizaciones automáticamente","general.close_action": "Al cerrar la ventana","general.close.Ask": "Preguntar cada vez",diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.jsonindex 66a74ca9..b73996dc 100644--- a/src/Filee.App/Assets/i18n/hi.json+++ b/src/Filee.App/Assets/i18n/hi.json@@ -74,6 +74,11 @@"error.rhwp_timeout_calibre": "rhwp इस लंबे दस्तावेज़ को समय पर पूरा नहीं कर सका। ई-बुक के लिए, सेटिंग्स → इंजन में Calibre को HWPX writer के ऊपर ले जाएँ, तब Calibre PDF बहुत तेज़ी से बनाएगा","error.needs_shaping": "इस लिपि को सही ढंग से कन्वर्ट करने के लिए LibreOffice चाहिए। इसे सेटिंग्स → इंजन में इंस्टॉल करें","error.conversion_failed": "इंजन ने एक त्रुटि बताई",+ "error.web_download_failed": "फ़ाइल डाउनलोड नहीं हो सकी",+ "error.web_page": "यह लिंक फ़ाइल नहीं, एक वेब पेज खोलता है। जिस फ़ाइल के लिए साइन-इन ज़रूरी है उसे Filee डाउनलोड नहीं कर सकता: पहले उसे ब्राउज़र से सेव करें",+ "error.web_too_large": "फ़ाइल 2 GB से बड़ी है",+ "error.web_blocked": "प्रोग्राम, इंस्टॉलर और स्क्रिप्ट सेव नहीं किए जाते",+ "error.web_timeout": "सर्वर ने जवाब देना बंद कर दिया","notice.pdf_not_smaller": "इसे छोटा नहीं किया जा सका, इसलिए जैसा है वैसा ही कॉपी कर दिया गया","engine.reason.not_installed": "इंस्टॉल नहीं है","engine.reason.error": "जाँच के दौरान त्रुटि",@@ -197,6 +202,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.check_updates": "अपडेट अपने-आप जाँचें","general.close_action": "जब मैं विंडो बंद करूँ","general.close.Ask": "हर बार पूछें",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 3f5d09bb..39d863f2 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -80,6 +80,11 @@"error.rhwp_timeout_calibre": "문서가 길어서 rhwp가 제한 시간 안에 끝내지 못했어요. 전자책이라면 설정 → 변환 엔진에서 Calibre를 HWPX writer보다 위로 옮겨 주세요. Calibre가 PDF를 훨씬 빨리 만들어요","error.needs_shaping": "이 문자는 LibreOffice가 있어야 제대로 변환돼요. 설정 → 변환 엔진에서 설치해 주세요","error.conversion_failed": "엔진에서 오류가 발생했어요",+ "error.web_download_failed": "파일을 내려받지 못했어요",+ "error.web_page": "링크가 파일이 아니라 웹페이지로 열려요. 로그인이 필요한 파일은 Filee가 내려받을 수 없으니 브라우저에서 먼저 저장해 주세요",+ "error.web_too_large": "2GB보다 큰 파일이에요",+ "error.web_blocked": "프로그램, 설치 파일, 스크립트는 저장하지 않아요",+ "error.web_timeout": "서버가 응답하지 않아요","notice.pdf_not_smaller": "더 작게 만들 수 없어서 그대로 복사했어요","engine.reason.not_installed": "설치되지 않음",@@ -208,6 +213,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.check_updates": "자동으로 업데이트 확인","general.close_action": "창을 닫을 때","general.close.Ask": "매번 묻기",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 655a9180..0a2a49f4 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -80,6 +80,11 @@"error.rhwp_timeout_calibre": "rhwp nie zdążył przetworzyć tego długiego dokumentu. Dla e-booka przenieś Calibre nad HWPX writer w Ustawienia → Silniki, a Calibre zrobi PDF znacznie szybciej","error.needs_shaping": "To pismo wymaga LibreOffice do poprawnej konwersji. Zainstaluj go w Ustawienia → Silniki","error.conversion_failed": "Silnik zgłosił błąd",+ "error.web_download_failed": "Nie udało się pobrać pliku",+ "error.web_page": "Link otwiera stronę internetową, a nie plik. Filee nie pobierze pliku, który wymaga zalogowania: najpierw zapisz go w przeglądarce",+ "error.web_too_large": "Plik jest większy niż 2 GB",+ "error.web_blocked": "Programy, instalatory i skrypty nie są zapisywane",+ "error.web_timeout": "Serwer przestał odpowiadać","notice.pdf_not_smaller": "Nie udało się zmniejszyć pliku, więc skopiowano go bez zmian","engine.reason.not_installed": "Nie zainstalowano",@@ -208,6 +213,11 @@"general.default_output_hint": "Ustawienia z „Domyślne miejsce zapisu” zapisują tutaj.\nUstawienie z własnym miejscem je zachowuje.","general.keep_dates": "Zachowuj oryginalne daty plików przy każdej konwersji","general.keep_dates_hint": "Przekonwertowane pliki zachowują daty utworzenia i modyfikacji oryginału, w każdym ustawieniu.\nWyłączone: robią to tylko ustawienia z „Zachowaj oryginalne daty plików”.",+ "general.browser_drops": "Pliki przeciągnięte z przeglądarki",+ "general.browser_drops_hint": "Przytrzymaj klawisz i przeciągnij obraz, link do pliku lub pobieranie z Chrome, Edge, Firefoksa albo Safari: pasek-pierścień otworzy się tak samo jak dla Twoich plików. Plik zostanie zapisany w tym folderze, a ustawienia zapisujące obok oryginału też zapiszą tu przekonwertowany plik.\nLinki Filee pobiera samo, bez logowania z Twojej przeglądarki.",+ "general.browser_drops_folder": "Zapisz w",+ "general.browser_drops_only_converted": "Zapisuj tylko przekonwertowany plik",+ "general.browser_drops_only_converted_hint": "Oryginał czeka w folderze tymczasowym i jest usuwany po konwersji.","general.check_updates": "Automatycznie sprawdzaj aktualizacje","general.close_action": "Po zamknięciu okna","general.close.Ask": "Pytaj za każdym razem",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex dcaae0b4..e168f891 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -80,6 +80,11 @@"error.rhwp_timeout_calibre": "文档太长,rhwp 未能在时限内完成。如果是电子书,请在“设置 → 转换引擎”中把 Calibre 移到 HWPX writer 之上,Calibre 生成 PDF 要快得多","error.needs_shaping": "这种文字需要 LibreOffice 才能正确转换,请在“设置 → 转换引擎”中安装","error.conversion_failed": "转换引擎出错",+ "error.web_download_failed": "无法下载该文件",+ "error.web_page": "该链接打开的是网页,不是文件。需要登录才能获取的文件 Filee 无法下载,请先在浏览器中保存",+ "error.web_too_large": "文件大于 2 GB",+ "error.web_blocked": "不保存程序、安装包和脚本",+ "error.web_timeout": "服务器没有响应","notice.pdf_not_smaller": "无法再缩小,已原样复制","engine.reason.not_installed": "未安装",@@ -208,6 +213,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.check_updates": "自动检查更新","general.close_action": "关闭窗口时","general.close.Ask": "每次询问",diff --git a/src/Filee.App/Services/AppHost.cs b/src/Filee.App/Services/AppHost.csindex 533c35f4..2294da85 100644--- a/src/Filee.App/Services/AppHost.cs+++ b/src/Filee.App/Services/AppHost.cs@@ -6,6 +6,7 @@ using Filee.Core.Conversion;using Filee.Core.Localization;using Filee.Core.Platform;using Filee.Core.Settings;+using Filee.Core.Web;using Filee.Engines;using Filee.Engines.Infrastructure;using Filee.Platform.Linux;@@ -57,6 +58,8 @@ public static class AppHostEngineRegistry.FindFileCombiner(sp.GetRequiredService<IReadOnlyList<IConverter>>()),EngineRegistry.FindTiffMerger(sp.GetRequiredService<IReadOnlyList<IConverter>>())));+ // Files dragged from a browser with only an address are downloaded without the browser's cookies.+ services.AddSingleton(_ => new WebDownloader(userAgent: $"Filee/{typeof(AppHost).Assembly.GetName().Version?.ToString(3)}"));services.AddSingleton<EngineDownloadService>();services.AddSingleton<PresetAvailability>();services.AddSingleton<RadialViewModel>();diff --git a/src/Filee.App/Services/BrowserDrags.cs b/src/Filee.App/Services/BrowserDrags.csnew file mode 100644index 00000000..e663d53e--- /dev/null+++ b/src/Filee.App/Services/BrowserDrags.cs@@ -0,0 +1,202 @@+// Files dragged out of a web browser, read from Avalonia's drag data. Avalonia 12 gives Windows virtual files+// (FileGroupDescriptorW + FileContents: a picture Chrome or Edge hands over) as storage items without a local path,+// and every other format a drag offers as a platform format by its native name. Which of those make a file is decided+// in Filee.Core (BrowserDrag); this file only collects them.+//+// Linux: Avalonia turns text/uri-list into local files only (http addresses are dropped), so links come from+// text/x-moz-url and _NETSCAPE_URL there. macOS: file promises can't be received; public.url, HTML and picture data can.++using Avalonia.Input;+using Avalonia.Media.Imaging;+using Avalonia.Platform.Storage;+using Filee.Core.Platform;+using Filee.Core.Web;++namespace Filee.App.Services;++internal static class BrowserDrags+{+ /// <summary>Formats whose text Filee reads, by native name.</summary>+ private static readonly string[] TextFormats =+ [+ BrowserDragFormats.UniformResourceLocatorW, BrowserDragFormats.UniformResourceLocator, BrowserDragFormats.MozUrl,+ BrowserDragFormats.NetscapeUrl, BrowserDragFormats.UriList, BrowserDragFormats.DownloadUrlFormat,+ BrowserDragFormats.MozFilePromiseUrl, BrowserDragFormats.MozFilePromiseName, BrowserDragFormats.MacUrl,+ BrowserDragFormats.MacUrlName, BrowserDragFormats.Html, BrowserDragFormats.WindowsHtml, BrowserDragFormats.MacHtml,+ ];++ /// <summary>Picture data some browsers put on a drag (macOS, X11), with the extension it is saved with.</summary>+ private static readonly (string Format, string Extension)[] PictureFormats =+ [+ ("public.jpeg", "jpg"), ("public.tiff", "tiff"), ("com.compuserve.gif", "gif"), ("org.webmproject.webp", "webp"),+ ("image/png", "png"), ("image/jpeg", "jpg"), ("image/gif", "gif"), ("image/webp", "webp"),+ ];++ /// <summary>+ /// Whether the drag may hold a file from a browser (an address or a virtual file): cheap, for the drop effect while+ /// dragging over the drop zone.+ /// </summary>+ public static bool MayOffer(IDataTransfer data) =>+ data.Formats.Any(f => f.Kind == DataFormatKind.Platform+ && (BrowserDragFormats.FileGroupDescriptorW.Equals(f.Identifier, StringComparison.OrdinalIgnoreCase)+ || BrowserDragContent.AddressFormatNames.Contains(f.Identifier, StringComparer.OrdinalIgnoreCase)));++ /// <summary>+ /// The files of a drag from a browser (or another app that holds them only in memory), standing as placeholders;+ /// null when there are none or the drag holds files on disk (those are read as they are).+ /// </summary>+ /// <param name="forDrop">+ /// False while dragging: only the names count, and names a Windows drag lists without handing their bytes yet are+ /// taken too. The returned drop must be disposed either way.+ /// </param>+ public static WebDrop? Read(IDataTransfer data, bool forDrop) =>+ Read(data, forDrop, WebDrop.DefaultWorkRoot, IsTemporary);++ internal static WebDrop? Read(IDataTransfer data, bool forDrop, string workRoot, Func<string, bool> isTemporary)+ {+ var content = Content(data, forDrop, isTemporary);+ if (content is null)+ return null;+ var items = BrowserDrag.Files(content);+ return items.Count == 0 ? null : new WebDrop(items, workRoot);+ }++ internal static BrowserDragContent? Content(IDataTransfer data, bool forDrop, Func<string, bool> isTemporary)+ {+ var texts = Texts(data);+ var hasAddress = new BrowserDragContent { Texts = texts }.HasAddress;+ var storageItems = data.TryGetFiles() ?? [];++ var files = new List<WebDropItem>();+ foreach (var storageItem in storageItems)+ {+ if (storageItem.TryGetLocalPath() is { } path)+ {+ // A file on disk is read as it is, unless it is a browser's temporary copy (Firefox writes the dragged+ // picture into the temp folder): that one is saved like any file from the browser.+ if (!hasAddress || !isTemporary(path) || !File.Exists(path))+ {+ DisposeAll(files);+ return null;+ }+ files.Add(WebDropItem.FromTemporaryFile(path));+ }+ else if (storageItem is IStorageFile file)+ {+ // Disposing a Windows virtual file ends the transfer with the source app: only the drop's files, once+ // saved. While dragging, the drag still needs it.+ files.Add(WebDropItem.FromStream(file.Name, _ => file.OpenReadAsync(), owner: forDrop ? file : null));+ }+ }++ // While dragging, Windows may list a browser's files before it hands over their bytes.+ if (files.Count == 0 && !forDrop && Raw(data, BrowserDragFormats.FileGroupDescriptorW) is byte[] descriptor)+ {+ foreach (var entry in BrowserDragFormats.ParseFileGroupDescriptor(descriptor).Where(e => !e.IsFolder))+ files.Add(WebDropItem.FromStream(entry.Name, _ => throw new IOException("The file's contents weren't handed over.")));+ }++ if (files.Count == 0 && !hasAddress)+ return null;+ return new BrowserDragContent { Files = files, Texts = texts, Picture = Picture(data, texts) };+ }++ /// <summary>True for a path in the system's temporary folder (but not in Filee's own work folders).</summary>+ internal static bool IsTemporary(string path)+ {+ try+ {+ var full = Path.GetFullPath(path);+ var temp = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())) + Path.DirectorySeparatorChar;+ var own = Path.TrimEndingDirectorySeparator(Path.GetFullPath(WebDrop.DefaultWorkRoot)) + Path.DirectorySeparatorChar;+ return full.StartsWith(temp, FileSystemPaths.Comparison) && !full.StartsWith(own, FileSystemPaths.Comparison);+ }+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)+ {+ return false;+ }+ }++ private static Dictionary<string, string> Texts(IDataTransfer data)+ {+ var texts = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);+ foreach (var item in data.Items)+ {+ foreach (var format in item.Formats)+ {+ if (format.Kind != DataFormatKind.Platform || texts.ContainsKey(format.Identifier)+ || !TextFormats.Contains(format.Identifier, StringComparer.OrdinalIgnoreCase))+ continue;+ var text = Text(item.TryGetRaw(format));+ if (!string.IsNullOrWhiteSpace(text))+ texts[format.Identifier] = text;+ }+ }+ // Formats are matched by their native name, whatever its case: keep one spelling, the constants'.+ return TextFormats.Where(texts.ContainsKey).ToDictionary(f => f, f => texts[f], StringComparer.OrdinalIgnoreCase);+ }++ private static string? Text(object? raw) => raw switch+ {+ string text => text.TrimEnd('\0'),+ byte[] bytes => BrowserDragFormats.DecodeText(bytes),+ _ => null,+ };++ private static object? Raw(IDataTransfer data, string identifier)+ {+ foreach (var item in data.Items)+ {+ foreach (var format in item.Formats)+ {+ if (format.Kind == DataFormatKind.Platform && format.Identifier.Equals(identifier, StringComparison.OrdinalIgnoreCase))+ return item.TryGetRaw(format);+ }+ }+ return null;+ }++ /// <summary>The picture's pixels from the drag, made into a file when nothing better is found (a blob: picture).</summary>+ private static Func<WebDropItem?>? Picture(IDataTransfer data, IReadOnlyDictionary<string, string> texts)+ {+ var raw = PictureFormats.FirstOrDefault(p => Raw(data, p.Format) is byte[] { Length: > 0 });+ var hasBitmap = data.Formats.Contains(DataFormat.Bitmap);+ if (raw.Format is null && !hasBitmap)+ return null;+ return () =>+ {+ var name = PictureName(texts);+ if (raw.Format is not null && Raw(data, raw.Format) is byte[] { Length: > 0 } bytes)+ return WebDropItem.FromBytes($"{name}.{raw.Extension}", bytes);+ if (data.TryGetValue(DataFormat.Bitmap) is not Bitmap bitmap)+ return null;+ using (bitmap)+ {+ using var png = new MemoryStream();+ bitmap.Save(png, new PngBitmapEncoderOptions());+ return WebDropItem.FromBytes($"{name}.png", png.ToArray());+ }+ };+ }++ /// <summary>The picture's name from its address ("photo" for …/photo.jpg?w=200), else "image".</summary>+ private static string PictureName(IReadOnlyDictionary<string, string> texts)+ {+ foreach (var format in BrowserDragContent.AddressFormatNames)+ {+ if (!texts.TryGetValue(format, out var text))+ continue;+ var first = BrowserDragFormats.ParseMozUrl(text).FirstOrDefault();+ if (first is not null && Uri.TryCreate(first, UriKind.Absolute, out var url) && WebFileNames.FromUrl(url) is { } fromUrl+ && !WebFileNames.IsPage(fromUrl))+ return Path.GetFileNameWithoutExtension(WebFileNames.Sanitize(fromUrl, "image"));+ }+ return "image";+ }++ private static void DisposeAll(List<WebDropItem> items)+ {+ foreach (var item in items)+ item.Dispose();+ }+}diff --git a/src/Filee.App/Services/ConversionService.cs b/src/Filee.App/Services/ConversionService.csindex 714c0dd4..2104f2ac 100644--- a/src/Filee.App/Services/ConversionService.cs+++ b/src/Filee.App/Services/ConversionService.cs@@ -11,6 +11,7 @@ using Filee.Core.Localization;using Filee.Core.Platform;using Filee.Core.Presets;using Filee.Core.Settings;+using Filee.Core.Web;namespace Filee.App.Services;@@ -26,18 +27,20 @@ public sealed class ConversionServiceprivate readonly UserDataStore _store;private readonly ILocalizer _loc;private readonly IPlatformServices _platform;+ private readonly WebDownloader _downloader;private readonly System.Collections.Concurrent.ConcurrentDictionary<string, JobViewModel> _byId = new();private readonly System.Collections.Concurrent.ConcurrentDictionary<string, TaskCompletionSource<ConversionJob>> _waiting = new();/// <summary>Jobs that came from a watch folder: job id → rule id (for the history and for retrying).</summary>private readonly System.Collections.Concurrent.ConcurrentDictionary<string, string> _watchJobs = new();- public ConversionService(JobQueue queue, UserDataStore store, ILocalizer loc, IPlatformServices platform)+ public ConversionService(JobQueue queue, UserDataStore store, ILocalizer loc, IPlatformServices platform, WebDownloader downloader){_queue = queue;_store = store;_loc = loc;_platform = platform;+ _downloader = downloader;_queue.JobUpdated += OnJobUpdated;_queue.JobFinished += OnJobFinished;}@@ -58,14 +61,28 @@ public sealed class ConversionService/// <param name="files">Source files.</param>/// <param name="preset">Preset to apply.</param>/// <param name="showInToast">False when another view (the donut's progress ring) displays the job first.</param>+ /// <param name="web">+ /// The browser drop <paramref name="files"/> stand for: the job saves them first, into the folder Settings ›+ /// General names for files from a browser. The job owns it from now on (disposed here when nothing starts).+ /// </param>/// <returns>The job's view model, or null when there was nothing to convert.</returns>- public JobViewModel? Start(IReadOnlyList<string> files, Preset preset, bool showInToast = true)+ public JobViewModel? Start(IReadOnlyList<string> files, Preset preset, bool showInToast = true, WebDrop? web = null){if (files.Count == 0 || preset.IsGroup)+ {+ web?.Dispose();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));+ WebDropFetcher? fetcher = null;+ if (web is not null)+ {+ fetcher = web.CreateFetcher(BrowserDropOptions(), _downloader);+ // "Next to the source" is the download folder, also when the original is only kept until converted.+ preset = fetcher.Apply(preset);+ }+ var job = _queue.Enqueue(files, preset, _loc.DisplayName(preset), fetcher);var vm = new JobViewModel(job, _loc, _platform, Remove, RetryFailed);_byId[job.Id] = vm;Jobs.Insert(0, vm);@@ -98,6 +115,14 @@ public sealed class ConversionServicereturn Start(files, preset);}+ /// <summary>Where files dragged from a browser are saved, as Settings › General says now.</summary>+ public WebDropOptions BrowserDropOptions()+ {+ var settings = _store.Settings.BrowserDrops;+ var folder = string.IsNullOrWhiteSpace(settings.Folder) ? _platform.DownloadsFolder : settings.Folder.Trim();+ return new WebDropOptions(folder, settings.SaveOnlyConverted);+ }+/// <summary>True when a source file (or folder) is still where it was.</summary>public static bool Exists(string path) => File.Exists(path) || Directory.Exists(path);diff --git a/src/Filee.App/Services/DraggedFiles.cs b/src/Filee.App/Services/DraggedFiles.csindex e5fca059..bc43472a 100644--- a/src/Filee.App/Services/DraggedFiles.cs+++ b/src/Filee.App/Services/DraggedFiles.cs@@ -1,19 +1,44 @@-// The local files in a drag. Avalonia reads file URLs (what Explorer, Finder and Linux file managers offer); on macOS+// The files in a drag. Avalonia reads file URLs (what Explorer, Finder and Linux file managers offer); on macOS// some other file managers offer the older NSFilenamesPboardType array of paths instead (QSpace Pro, issue #160),-// which Avalonia passes through as a platform format of its own.+// which Avalonia passes through as a platform format of its own. Pictures, links and downloads dragged out of a web+// browser are read by BrowserDrags and stand as placeholders until their conversion saves them.using Avalonia.Input;using Avalonia.Platform.Storage;using Filee.Core.Platform;+using Filee.Core.Web;using Filee.Platform.MacOS;namespace Filee.App.Services;+/// <summary>What a drag brought: local files, or placeholders for files from a browser (<paramref name="Web"/>).</summary>+/// <param name="Files">The paths the donut and the conversion take.</param>+/// <param name="Web">The browser drop the paths stand for, or null for files on disk. Its owner disposes it.</param>+internal sealed record DraggedItems(IReadOnlyList<string> Files, WebDrop? Web)+{+ public static DraggedItems None { get; } = new([], null);+}+internal static class DraggedFiles{- /// <summary>Whether the drag offers files in a form Filee reads (they may still turn out to be folders).</summary>+ /// <summary>+ /// Whether the drag offers files in a form Filee reads (they may still turn out to be folders, or a link to a web+ /// page).+ /// </summary>public static bool Offered(IDataTransfer data) =>- data.Contains(DataFormat.File) || data.Items.Any(item => item.Formats.Any(IsFilenames));+ data.Contains(DataFormat.File) || data.Items.Any(item => item.Formats.Any(IsFilenames)) || BrowserDrags.MayOffer(data);++ /// <summary>+ /// The files in a drag: from a browser when it brought some (as placeholders, see <see cref="BrowserDrags"/>),+ /// else the local files. <paramref name="forDrop"/>: see <see cref="BrowserDrags.Read(IDataTransfer, bool)"/>.+ /// </summary>+ public static DraggedItems Read(IDataTransfer data, bool forDrop)+ {+ if (BrowserDrags.Read(data, forDrop) is { } web)+ return new DraggedItems(web.Placeholders, web);+ var files = Local(data);+ return files.Count == 0 ? DraggedItems.None : new DraggedItems(files, null);+ }/// <summary>/// Local file paths in the drag (folders and virtual items are ignored). A shortcut counts as the file it pointsdiff --git a/src/Filee.App/Services/RadialController.cs b/src/Filee.App/Services/RadialController.csindex cc7dcb9c..e573412f 100644--- a/src/Filee.App/Services/RadialController.cs+++ b/src/Filee.App/Services/RadialController.cs@@ -4,6 +4,8 @@// gesture detected → an invisible window waits at the cursor (not activated) → DragEnter brings the file list →// the donut pops out → drop on a slice converts / drop in the hole or release elsewhere closes. Without files// (text, a rubber-band selection) nothing ever shows.+// Files from a web browser (a picture, a link to a PDF) stand as placeholder paths named like the files will be, so the+// donut shows their slices at once; they are saved when the conversion starts (WebDrop, ConversionService).// Click mode (keyboard shortcut, context menu, drop zone):// files are known up front → donut appears activated → click a slice to convert, right-click to edit,// Esc / click outside closes.@@ -21,6 +23,7 @@ using Filee.Core.Conversion;using Filee.Core.Platform;using Filee.Core.Profiles;using Filee.Core.Settings;+using Filee.Core.Web;using Microsoft.Extensions.Logging;namespace Filee.App.Services;@@ -55,6 +58,7 @@ public sealed class RadialController(private static readonly LogThrottle Throttle = new(TimeSpan.FromMinutes(1));private bool _converted; // a conversion started from the files on the donut nowprivate readonly HashSet<string> _formatRequestsOffered = new(StringComparer.OrdinalIgnoreCase);+ private WebDrop? _web; // the browser drop the click-mode donut's files stand for, until a conversion takes it/// <summary>/// How long a drag that never brought files may keep the invisible window up, in case the button release is@@ -75,6 +79,7 @@ public sealed class RadialController({ReleaseProgressToToast();_grace.Cancel();+ ReplaceWeb(null);var window = EnsureWindow();// A ring from an earlier conversion (finished or handed to the toast) must not keep this gesture's window up.window.DonutControl.LeaveProgressMode();@@ -96,14 +101,20 @@ public sealed class RadialController(/// <summary>/// Opens the donut for known files (click mode). Shortcuts among them stand for the files they point to./// <paramref name="forAnotherProcess"/>: the files came from a later launch or the Services menu, so on macOS the- /// donut may lose focus once while Filee becomes the active app.+ /// donut may lose focus once while Filee becomes the active app. <paramref name="web"/>: the files are placeholders+ /// of this browser drop (the drop zone), which the donut now owns./// </summary>- public void ShowForFiles(int x, int y, IReadOnlyList<string> files, bool forAnotherProcess = false)+ public void ShowForFiles(int x, int y, IReadOnlyList<string> files, bool forAnotherProcess = false, WebDrop? web = null){- files = platform.ResolveShortcuts(files);+ if (web is null)+ files = platform.ResolveShortcuts(files);if (files.Count == 0)+ {+ web?.Dispose();return;+ }ReleaseProgressToToast();+ ReplaceWeb(web);if (forAnotherProcess && OperatingSystem.IsMacOS())_grace.Start();else@@ -162,6 +173,7 @@ public sealed class RadialController(}_visible = false;_grace.Cancel();+ ReplaceWeb(null);var window = _window;// A group about to open (its dwell timer running) must not open on a closing donut.window.DonutControl.CollapseGroup();@@ -209,18 +221,23 @@ public sealed class RadialController(};window.FilesEntered += files =>{- if (viewModel.IsClickMode || SameFiles(files, viewModel.Files))+ if (viewModel.IsClickMode || SameFiles(files, viewModel.Files) || SameWebFiles(files, viewModel.Files))return;viewModel.Load(files, clickMode: false);donut.PlayOpenAnimation();};- window.Dropped += (hit, files) =>+ window.Dropped += (hit, dropped) =>{_dropped = true;if (hit.Kind is DonutHitKind.Segment or DonutHitKind.SubSegment)- Convert(hit.Index, hit.Sub, files.Count > 0 ? files : viewModel.Files);+ {+ Convert(hit.Index, hit.Sub, dropped.Files.Count > 0 ? dropped.Files : viewModel.Files, dropped.Web);+ }else+ {+ dropped.Web?.Dispose();Close();+ }};// One line per drag, to tell "the drag never reached the donut" from "it did but nothing lit up" when someone// reports a donut that doesn't react.@@ -246,8 +263,8 @@ public sealed class RadialController(};donut.ActiveIndexChanged += (_, index) => viewModel.ShowHint(index, donut.ActiveSubIndex, donut.IsCenterHot);- donut.SegmentInvoked += (_, index) => Convert(index, -1, viewModel.Files);- donut.SubSegmentInvoked += (_, hit) => Convert(hit.Group, hit.Sub, viewModel.Files);+ donut.SegmentInvoked += (_, index) => Convert(index, -1, viewModel.Files, TakeWeb());+ donut.SubSegmentInvoked += (_, hit) => Convert(hit.Group, hit.Sub, viewModel.Files, TakeWeb());donut.CenterInvoked += (_, _) => Close();donut.SegmentContextRequested += async (_, index) => await EditPresetAsync(index);donut.SubSegmentContextRequested += async (_, hit) => await EditPresetAsync(hit.Group, hit.Sub);@@ -262,17 +279,24 @@ public sealed class RadialController(return window;}- /// <summary>Converts with slice <paramref name="index"/>, or with slice <paramref name="sub"/> of that group's ring.</summary>- private void Convert(int index, int sub, IReadOnlyList<string> files)+ /// <summary>+ /// Converts with slice <paramref name="index"/>, or with slice <paramref name="sub"/> of that group's ring.+ /// <paramref name="web"/>: the browser drop the files stand for, handed to the conversion (or disposed).+ /// </summary>+ private void Convert(int index, int sub, IReadOnlyList<string> files, WebDrop? web = null){- if (viewModel.PresetAt(index, sub) is not { } preset || files.Count == 0)+ // Placeholders whose drop is gone (the drag listed files it didn't hand over in the end) can't be converted.+ var orphaned = web is null && files.Any(WebDrop.IsPlaceholder);+ if (viewModel.PresetAt(index, sub) is not { } preset || files.Count == 0 || orphaned){+ web?.Dispose();Close();return;}- log.LogInformation("Converting {Count} file(s) with preset {Preset}", files.Count, preset.Id);- var job = conversions.Start(files, preset, showInToast: false);+ log.LogInformation("Converting {Count} file(s) with preset {Preset}{Web}", files.Count, preset.Id,+ web is null ? "" : " (from a browser)");+ var job = conversions.Start(files, preset, showInToast: false, web);if (job is null || _window is null){Close();@@ -427,4 +451,25 @@ public sealed class RadialController(private static bool SameFiles(IReadOnlyList<string> a, IReadOnlyList<string> b) =>a.Count == b.Count && a.SequenceEqual(b, FileSystemPaths.Comparer);++ /// <summary>The same browser files dragged in again: each entry makes new placeholders, with the same names.</summary>+ private static bool SameWebFiles(IReadOnlyList<string> a, IReadOnlyList<string> b) =>+ a.Count == b.Count && a.All(WebDrop.IsPlaceholder) && b.All(WebDrop.IsPlaceholder)+ && a.Select(Path.GetFileName).SequenceEqual(b.Select(Path.GetFileName), StringComparer.Ordinal);++ /// <summary>Hands the click-mode donut's browser drop to a conversion.</summary>+ private WebDrop? TakeWeb()+ {+ var web = _web;+ _web = null;+ return web;+ }++ /// <summary>The click-mode donut now stands for <paramref name="web"/>'s files (or local ones): the old drop is done.</summary>+ private void ReplaceWeb(WebDrop? web)+ {+ if (!ReferenceEquals(_web, web))+ _web?.Dispose();+ _web = web;+ }}diff --git a/src/Filee.App/ViewModels/JobViewModel.cs b/src/Filee.App/ViewModels/JobViewModel.csindex 6cf19a25..22704cdf 100644--- a/src/Filee.App/ViewModels/JobViewModel.cs+++ b/src/Filee.App/ViewModels/JobViewModel.cs@@ -70,7 +70,9 @@ public sealed partial class JobViewModel : ObservableObjectHasErrors = failed.Count > 0;ErrorDetails = failed.Count == 0 ? null : string.Join(Environment.NewLine,failed.Select(f => $"{Path.GetFileName(f.SourcePath)} — {FailureText.Reason(_loc, f.ErrorKey, f.ErrorDetail)}"));- CanRetry = _retry is not null && !IsRunning && failed.Count > 0;+ // A file from a browser that couldn't be saved, or whose original wasn't kept, is gone: nothing to retry with.+ CanRetry = _retry is not null && !IsRunning && failed.Count > 0+ && (Job.Fetcher is null || failed.Any(f => File.Exists(f.SourcePath)));IReadOnlyList<string> unknown = IsRunning ? [] : FormatRequest.UnknownExtensions(failed.Where(f => f.ErrorKey == "error.unsupported_source").Select(f => f.SourcePath));if (!unknown.SequenceEqual(UnknownExtensions))diff --git a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.csindex 864b8ccc..a3218fdc 100644--- a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs@@ -46,6 +46,8 @@ public sealed partial class GeneralPageViewModel : ObservableObject, IDisposable_defaultSubfolder = output.SubfolderName;_defaultFolder = output.CustomFolder;_keepFileDates = store.Settings.KeepFileDates;+ _browserFolder = store.Settings.BrowserDrops.Folder;+ _saveOnlyConverted = store.Settings.BrowserDrops.SaveOnlyConverted;CloseChoices = Enum.GetValues<CloseAction>().Select(v => new Choice<CloseAction>(v, loc[$"general.close.{v}"])).ToList();_closeChoice = CloseChoices.First(c => c.Value == store.Settings.CloseAction);store.SettingsChanged += OnSettingsChanged;@@ -89,6 +91,21 @@ public sealed partial class GeneralPageViewModel : ObservableObject, IDisposable[ObservableProperty] private bool _keepFileDates;+ /// <summary>Where files dragged from a browser are saved; empty for the Downloads folder.</summary>+ [ObservableProperty] private string _browserFolder;++ [ObservableProperty] private bool _saveOnlyConverted;++ /// <summary>The user's Downloads folder, shown while no other folder is set.</summary>+ public string DownloadsFolder => _platform.DownloadsFolder;++ /// <summary>The folder files from a browser go to now.</summary>+ public string BrowserFolderInUse => string.IsNullOrWhiteSpace(BrowserFolder) ? DownloadsFolder : BrowserFolder.Trim();++ partial void OnBrowserFolderChanged(string value) => Save(s => s.BrowserDrops.Folder = value.Trim());++ partial void OnSaveOnlyConvertedChanged(bool value) => Save(s => s.BrowserDrops.SaveOnlyConverted = value);+/// <summary>What closing the main window does; its "Don't ask again" also sets it.</summary>public IReadOnlyList<Choice<CloseAction>> CloseChoices { get; }diff --git a/src/Filee.App/Views/Pages/GeneralPage.axaml b/src/Filee.App/Views/Pages/GeneralPage.axamlindex b3bcbe17..73cd06cc 100644--- a/src/Filee.App/Views/Pages/GeneralPage.axaml+++ b/src/Filee.App/Views/Pages/GeneralPage.axaml@@ -59,6 +59,23 @@</StackPanel></Border>+ <!-- Pictures, links and downloads dragged out of a web browser (AppSettings.BrowserDrops). -->+ <Border Classes="card">+ <StackPanel Spacing="10">+ <TextBlock Classes="h2" Text="{DynamicResource general.browser_drops}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource general.browser_drops_hint}" />+ <StackPanel>+ <TextBlock Classes="label" Text="{DynamicResource general.browser_drops_folder}" />+ <DockPanel HorizontalAlignment="Left">+ <Button DockPanel.Dock="Right" Margin="8,0,0,0" Content="{DynamicResource presets.browse}" Click="OnBrowseBrowserFolder" />+ <TextBox Text="{Binding BrowserFolder}" PlaceholderText="{Binding DownloadsFolder}" Width="440" />+ </DockPanel>+ </StackPanel>+ <CheckBox Content="{DynamicResource general.browser_drops_only_converted}" IsChecked="{Binding SaveOnlyConverted}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource general.browser_drops_only_converted_hint}" Margin="0,-6,0,0" />+ </StackPanel>+ </Border>+<Border Classes="card"><StackPanel Spacing="12"><TextBlock Classes="h2" Text="{DynamicResource general.history}" />diff --git a/src/Filee.App/Views/Pages/GeneralPage.axaml.cs b/src/Filee.App/Views/Pages/GeneralPage.axaml.csindex d7b58d98..b880be0e 100644--- a/src/Filee.App/Views/Pages/GeneralPage.axaml.cs+++ b/src/Filee.App/Views/Pages/GeneralPage.axaml.cs@@ -38,6 +38,16 @@ public partial class GeneralPage : UserControlVm.DefaultFolder = path;}+ private async void OnBrowseBrowserFolder(object? sender, RoutedEventArgs e)+ {+ if (Vm is null || TopLevel.GetTopLevel(this) is not { } top)+ return;+ var start = await top.StorageProvider.TryGetFolderFromPathAsync(Vm.BrowserFolderInUse);+ var folders = await top.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { AllowMultiple = false, SuggestedStartLocation = start });+ if (folders.FirstOrDefault()?.TryGetLocalPath() is { } path)+ Vm.BrowserFolder = 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/Pages/HomePage.axaml.cs b/src/Filee.App/Views/Pages/HomePage.axaml.csindex 2d233609..8980e269 100644--- a/src/Filee.App/Views/Pages/HomePage.axaml.cs+++ b/src/Filee.App/Views/Pages/HomePage.axaml.cs@@ -1,4 +1,5 @@-// Drop zone: files dropped on the Home page open the donut (click mode) at the drop position.+// Drop zone: files dropped on the Home page open the donut (click mode) at the drop position, also pictures, links and+// downloads dragged from a browser.using Avalonia;using Avalonia.Controls;@@ -36,12 +37,15 @@ public partial class HomePage : UserControlprivate void OnDrop(object? sender, DragEventArgs e){DropZone.Classes.Remove("over");- var files = DraggedFiles.Local(e.DataTransfer);- if (files.Count == 0)+ var dragged = DraggedFiles.Read(e.DataTransfer, forDrop: true);+ if (dragged.Files.Count == 0)+ {+ e.DragEffects = DragDropEffects.None;return;+ }e.DragEffects = DragDropEffects.Copy;var screenPoint = this.PointToScreen(e.GetPosition(this));- AppHost.Get<RadialController>().ShowForFiles(screenPoint.X, screenPoint.Y, files);+ AppHost.Get<RadialController>().ShowForFiles(screenPoint.X, screenPoint.Y, dragged.Files, web: dragged.Web);}}diff --git a/src/Filee.App/Views/RadialWindow.axaml.cs b/src/Filee.App/Views/RadialWindow.axaml.csindex 64dcdb23..8f486dc4 100644--- a/src/Filee.App/Views/RadialWindow.axaml.cs+++ b/src/Filee.App/Views/RadialWindow.axaml.cs@@ -33,8 +33,8 @@ public partial class RadialWindow : Window/// <summary>A drag without files Filee reads entered the window: the formats it offered (for the log).</summary>public event Action<string>? DragWithoutFiles;- /// <summary>A drop landed on the donut: (hit, files).</summary>- public event Action<DonutHit, IReadOnlyList<string>>? Dropped;+ /// <summary>A drop landed on the donut: (hit, what it brought). The handler owns the browser drop in it.</summary>+ internal event Action<DonutHit, DraggedItems>? Dropped;public event Action? DragLeft;@@ -52,8 +52,11 @@ public partial class RadialWindow : Windowprivate void OnDragEnter(object? sender, DragEventArgs e){DragEntered?.Invoke();- var files = DraggedFiles.Local(e.DataTransfer);- _dragOffersFiles = DraggedFiles.Offered(e.DataTransfer);+ // Only the names count while dragging: a browser's files are read again from the drop.+ var dragged = DraggedFiles.Read(e.DataTransfer, forDrop: false);+ dragged.Web?.Dispose();+ var files = dragged.Files;+ _dragOffersFiles = files.Count > 0 || DraggedFiles.Offered(e.DataTransfer);if (files.Count == 0){DragWithoutFiles?.Invoke(DraggedFiles.Describe(e.DataTransfer));@@ -94,7 +97,11 @@ public partial class RadialWindow : WindowDonut.CollapseGroup();Donut.SetExternalHighlight(-1);e.DragEffects = Donut.Converts(hit) ? DragDropEffects.Copy : DragDropEffects.None;- Dropped?.Invoke(hit, DraggedFiles.Local(e.DataTransfer));+ var dropped = DraggedFiles.Read(e.DataTransfer, forDrop: true);+ if (Dropped is { } handler)+ handler(hit, dropped);+ else+ dropped.Web?.Dispose();e.Handled = true;}diff --git a/src/Filee.Platform.Linux/LinuxPlatformServices.cs b/src/Filee.Platform.Linux/LinuxPlatformServices.csindex b09f22c2..ac0e2305 100644--- a/src/Filee.Platform.Linux/LinuxPlatformServices.cs+++ b/src/Filee.Platform.Linux/LinuxPlatformServices.cs@@ -103,6 +103,25 @@ public sealed class LinuxPlatformServices : IPlatformServicespublic void RaiseTopmost(nint windowHandle) => X11WindowSystem.RaiseTopmost(windowHandle);+ /// <summary>XDG_DOWNLOAD_DIR from user-dirs.dirs (a localized desktop calls it "다운로드"), else ~/Downloads.</summary>+ public string DownloadsFolder+ {+ get+ {+ var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);+ var file = Path.Combine(XdgDirectory("XDG_CONFIG_HOME", ".config"), "user-dirs.dirs");+ try+ {+ if (File.Exists(file) && XdgUserDirs.Download(File.ReadAllText(file), home) is { } configured)+ return configured;+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ }+ return Path.Combine(home, "Downloads");+ }+ }+private static string XdgDirectory(string variable, string fallback){var configured = Environment.GetEnvironmentVariable(variable);diff --git a/src/Filee.Platform.Linux/XdgUserDirs.cs b/src/Filee.Platform.Linux/XdgUserDirs.csnew file mode 100644index 00000000..e08ae4e1--- /dev/null+++ b/src/Filee.Platform.Linux/XdgUserDirs.cs@@ -0,0 +1,23 @@+// The user's folders as xdg-user-dirs names them (~/.config/user-dirs.dirs): a localized desktop has "다운로드" or+// "Téléchargements" instead of "Downloads". Pure parsing, so it can be tested anywhere.++namespace Filee.Platform.Linux;++public static class XdgUserDirs+{+ /// <summary>The XDG_DOWNLOAD_DIR line of a user-dirs.dirs file, with $HOME expanded; null when there is none.</summary>+ public static string? Download(string text, string home)+ {+ foreach (var raw in text.Split('\n'))+ {+ var line = raw.Trim();+ if (!line.StartsWith("XDG_DOWNLOAD_DIR=", StringComparison.Ordinal))+ continue;+ var value = line["XDG_DOWNLOAD_DIR=".Length..].Trim().Trim('"');+ value = value.Replace("$HOME", home, StringComparison.Ordinal);+ // "$HOME/" alone means the home folder itself, which the spec says turns the folder off.+ return value.StartsWith('/') && value.TrimEnd('/') != home.TrimEnd('/') ? value : null;+ }+ return null;+ }+}diff --git a/src/Filee.Platform.MacOS/PasteboardPaths.cs b/src/Filee.Platform.MacOS/PasteboardPaths.csindex f745c55d..6def3e1f 100644--- a/src/Filee.Platform.MacOS/PasteboardPaths.cs+++ b/src/Filee.Platform.MacOS/PasteboardPaths.cs@@ -26,12 +26,15 @@ public static class PasteboardPaths/// <summary>/// Types the donut registers for on top of Avalonia's own, so a drag offering only these still reaches it (and its- /// types get logged when Filee can't read them). The last three are file promises, which Filee can't receive.+ /// types get logged when Filee can't read them). The three file promise types can't be received; a browser drag+ /// that offers one also offers the picture's or link's address (public.url) and HTML, which Filee reads instead,+ /// and sometimes the picture itself./// </summary>public static IReadOnlyList<string> DragTypes { get; } =[FileUrlType, FilenamesType,"com.apple.NSFilePromiseItemMetaData", "com.apple.pasteboard.promised-file-url", "Apple files promise pasteboard type",+ "public.url", "public.html", "public.png", "public.jpeg", "public.tiff", "com.compuserve.gif", "org.webmproject.webp",];/// <summary>Whether <paramref name="type"/> names NSFilenamesPboardType, by its name or its dynamic UTI.</summary>diff --git a/src/Filee.Platform.Windows/KnownFolders.cs b/src/Filee.Platform.Windows/KnownFolders.csnew file mode 100644index 00000000..1ad3b148--- /dev/null+++ b/src/Filee.Platform.Windows/KnownFolders.cs@@ -0,0 +1,31 @@+// Folders the shell knows by id: they can be moved (Downloads on another drive), so their path is asked, not assumed.++using System.Runtime.InteropServices;++namespace Filee.Platform.Windows;++internal static partial class KnownFolders+{+ private static readonly Guid DownloadsId = new("374DE290-123F-4565-9164-39C4925E467B");++ /// <summary>The user's Downloads folder, or null when the shell can't tell.</summary>+ public static string? Downloads => Path(DownloadsId);++ private static string? Path(Guid id)+ {+ if (!OperatingSystem.IsWindows())+ return null;+ var result = SHGetKnownFolderPath(id, 0, 0, out var pointer);+ try+ {+ return result == 0 ? Marshal.PtrToStringUni(pointer) : null;+ }+ finally+ {+ Marshal.FreeCoTaskMem(pointer);+ }+ }++ [LibraryImport("shell32.dll")]+ private static partial int SHGetKnownFolderPath(in Guid folderId, uint flags, nint token, out nint path);+}diff --git a/src/Filee.Platform.Windows/WindowsPlatformServices.cs b/src/Filee.Platform.Windows/WindowsPlatformServices.csindex 34337327..352b36a8 100644--- a/src/Filee.Platform.Windows/WindowsPlatformServices.cs+++ b/src/Filee.Platform.Windows/WindowsPlatformServices.cs@@ -70,6 +70,9 @@ public sealed class WindowsPlatformServices : IPlatformServicespublic string? ShortcutTarget(string path) => ShellLinks.TargetOf(path);+ public string DownloadsFolder => KnownFolders.Downloads+ ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");+/// <summary>/// Reads the selection of the foreground Explorer window through the Shell automation object./// Must be called on an STA thread (the Avalonia UI thread is STA).diff --git a/tests/Filee.App.Tests/BrowserDropTests.cs b/tests/Filee.App.Tests/BrowserDropTests.csnew file mode 100644index 00000000..c7c44b51--- /dev/null+++ b/tests/Filee.App.Tests/BrowserDropTests.cs@@ -0,0 +1,348 @@+// Files dragged out of a web browser, as Avalonia hands them to Filee: a Chrome picture (a Windows virtual file with+// its address), Firefox's temporary copy, a Linux link. They reach the donut and the drop zone as placeholders named+// like the files, and a drop on a slice saves and converts them into the folder Settings › General names.++using System.Reflection;+using System.Text;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Headless;+using Avalonia.Headless.XUnit;+using Avalonia.Input;+using Avalonia.Platform.Storage;+using Avalonia.Threading;+using Avalonia.VisualTree;+using Filee.App.Controls;+using Filee.App.Services;+using Filee.App.ViewModels;+using Filee.App.Views;+using Filee.App.Views.Pages;+using Filee.Core.Conversion;+using Filee.Core.Settings;+using Filee.Core.Web;++namespace Filee.App.Tests;++public class BrowserDropTests+{+ /// <summary>A 1×1 PNG.</summary>+ private static readonly byte[] Png = Convert.FromBase64String(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==");++ /// <summary>+ /// What Avalonia gives for a Windows virtual file: a storage file with no local path (with <c>local</c>, a file on+ /// disk). Avalonia's storage interfaces can't be implemented by hand, so a proxy answers for one.+ /// </summary>+ public class VirtualFile : DispatchProxy+ {+ private string _name = "";+ private byte[] _contents = [];+ private string? _local;++ public bool Disposed { get; private set; }++ public IStorageFile Item { get; private set; } = null!;++ public static VirtualFile Create(string name, byte[] contents, string? local = null)+ {+ var item = DispatchProxy.Create<IStorageFile, VirtualFile>();+ var file = (VirtualFile)(object)item;+ (file._name, file._contents, file._local, file.Item) = (name, contents, local, item);+ return file;+ }++ protected override object? Invoke(MethodInfo? method, object?[]? args) => method?.Name switch+ {+ "get_Name" => _name,+ "get_Path" => _local is null ? new Uri($"virtual-file:///{Uri.EscapeDataString(_name)}") : new Uri(_local),+ "get_CanBookmark" => false,+ "OpenReadAsync" => Task.FromResult<Stream>(new MemoryStream(_contents, writable: false)),+ "GetBasicPropertiesAsync" => Task.FromResult(new StorageItemProperties((ulong)_contents.Length)),+ "Dispose" => Dispose(),+ _ => throw new NotSupportedException(method?.Name),+ };++ private object? Dispose()+ {+ Disposed = true;+ return null;+ }+ }++ private static DataTransferItem Platform(string format, string text, bool utf16 = true) =>+ DataTransferItem.Create(DataFormat.CreateBytesPlatformFormat(format), (utf16 ? Encoding.Unicode : Encoding.UTF8).GetBytes(text + "\0"));++ /// <summary>Chrome or Edge on Windows dragging a picture: its bytes as a virtual file, plus where it came from.</summary>+ private static DataTransfer ChromePicture(VirtualFile file)+ {+ var data = new DataTransfer();+ data.Add(DataTransferItem.CreateFile(file.Item));+ data.Add(Platform(BrowserDragFormats.UniformResourceLocatorW, "https://example.com/gallery/cat.png"));+ data.Add(Platform(BrowserDragFormats.MozUrl, "https://example.com/gallery/cat.png\nA cat"));+ data.Add(DataTransferItem.Create(DataFormat.CreateBytesPlatformFormat(BrowserDragFormats.FileGroupDescriptorW),+ BrowserDragFormats.BuildFileGroupDescriptor([new FileDescriptor(file.Item.Name, Png.Length, false)])));+ return data;+ }++ private static void Pump()+ {+ for (var i = 0; i < 20; i++)+ {+ Dispatcher.UIThread.RunJobs();+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();+ }+ }++ private static ConversionJob WaitFor(JobViewModel vm)+ {+ var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(60);+ while (vm.Job.State is JobState.Queued or JobState.Running && DateTime.UtcNow < deadline)+ {+ Dispatcher.UIThread.RunJobs();+ Thread.Sleep(20);+ }+ Pump();+ return vm.Job;+ }++ private static string UseFolder(UserDataStore store, bool saveOnlyConverted)+ {+ var folder = Path.Combine(Path.GetTempPath(), "filee-app-tests", "downloads-" + Guid.NewGuid().ToString("N")[..8]);+ Directory.CreateDirectory(folder);+ store.Settings.BrowserDrops.Folder = folder;+ store.Settings.BrowserDrops.SaveOnlyConverted = saveOnlyConverted;+ return folder;+ }++ private static void Reset(UserDataStore store, string folder)+ {+ store.Settings.BrowserDrops.Folder = "";+ store.Settings.BrowserDrops.SaveOnlyConverted = false;+ try { Directory.Delete(folder, recursive: true); } catch (IOException) { }+ }++ [AvaloniaFact]+ public void A_picture_dragged_from_Chrome_is_offered_as_a_file_named_like_it()+ {+ TestServices.EnsureInitialized("en");+ var file = VirtualFile.Create("cat.png", Png);+ using var data = ChromePicture(file);++ Assert.True(DraggedFiles.Offered(data));+ var dragged = DraggedFiles.Read(data, forDrop: true);++ Assert.NotNull(dragged.Web);+ Assert.Equal("cat.png", Path.GetFileName(Assert.Single(dragged.Files)));+ Assert.False(File.Exists(dragged.Files[0]));+ dragged.Web.Dispose();+ Assert.True(file.Disposed); // the source app learns the transfer is over+ }++ [AvaloniaFact]+ public void Links_to_pages_and_text_selections_bring_nothing_but_links_to_files_do()+ {+ TestServices.EnsureInitialized("en");++ using var page = new DataTransfer();+ page.Add(Platform(BrowserDragFormats.UniformResourceLocatorW, "https://example.com/news/today"));+ page.Add(DataTransferItem.CreateText("https://example.com/news/today"));+ Assert.Same(DraggedItems.None, DraggedFiles.Read(page, forDrop: true));++ using var selection = new DataTransfer();+ selection.Add(DataTransferItem.CreateText("Read the report at https://example.com/report.pdf"));+ selection.Add(Platform(BrowserDragFormats.WindowsHtml, "<p>Read the <a href=\"https://example.com/report.pdf\">report</a></p>", utf16: false));+ Assert.Same(DraggedItems.None, DraggedFiles.Read(selection, forDrop: true));++ // Firefox or Chrome on Linux: the link's address and title, in UTF-8.+ using var linux = new DataTransfer();+ linux.Add(Platform(BrowserDragFormats.NetscapeUrl, "https://example.com/files/report.pdf\nQ3 report", utf16: false));+ var dragged = DraggedFiles.Read(linux, forDrop: true);+ Assert.Equal("report.pdf", Path.GetFileName(Assert.Single(dragged.Files)));+ dragged.Web!.Dispose();+ }++ [AvaloniaFact]+ public void Firefox_temporary_copies_count_as_browser_files_but_files_on_disk_stay_local()+ {+ TestServices.EnsureInitialized("en");+ var temp = Path.Combine(Path.GetTempPath(), "filee-app-tests", "moz-" + Guid.NewGuid().ToString("N")[..6], "dog.png");+ Directory.CreateDirectory(Path.GetDirectoryName(temp)!);+ File.WriteAllBytes(temp, Png);+ try+ {+ using var firefox = new DataTransfer();+ firefox.Add(DataTransferItem.CreateFile(StorageItem(temp)));+ firefox.Add(Platform(BrowserDragFormats.MozUrl, "https://example.com/dog.png\nDog"));+ var dragged = DraggedFiles.Read(firefox, forDrop: true);+ Assert.NotNull(dragged.Web);+ Assert.Equal("dog.png", Path.GetFileName(Assert.Single(dragged.Files)));+ Assert.NotEqual(temp, dragged.Files[0]);+ dragged.Web.Dispose();++ // The same file dragged from the file manager (no address): an ordinary local file.+ using var explorer = new DataTransfer();+ explorer.Add(DataTransferItem.CreateFile(StorageItem(temp)));+ var local = DraggedFiles.Read(explorer, forDrop: true);+ Assert.Null(local.Web);+ Assert.Equal([temp], local.Files);+ }+ finally+ {+ File.Delete(temp);+ }+ }++ private static IStorageItem StorageItem(string path) => VirtualFile.Create(Path.GetFileName(path), Png, path).Item;++ [AvaloniaFact]+ public void A_picture_dropped_on_a_donut_slice_is_saved_converted_and_only_the_converted_file_kept()+ {+ TestServices.EnsureInitialized("en");+ var store = AppHost.Get<UserDataStore>();+ var folder = UseFolder(store, saveOnlyConverted: true);+ var radial = AppHost.Get<RadialController>();+ var conversions = AppHost.Get<ConversionService>();+ try+ {+ radial.ShowForDrag(500, 500);+ var window = radial.Window!;+ var root = window.FindControl<Panel>("Root")!;+ var donut = window.DonutControl;+ var file = VirtualFile.Create("cat.png", Png);+ using var data = ChromePicture(file);++ root.RaiseEvent(new DragEventArgs(DragDrop.DragEnterEvent, data, root, new Point(5, 5), KeyModifiers.Control));+ Pump();+ var model = AppHost.Get<RadialViewModel>();+ Assert.Equal("cat.png", Path.GetFileName(Assert.Single(model.Files)));+ Assert.True(WebDrop.IsPlaceholder(model.Files[0]));+ Assert.False(file.Disposed); // the transfer isn't ended while the drag goes on++ var (at, preset) = FirstSlice(donut, model);+ var dropFile = VirtualFile.Create("cat.png", Png);+ using var dropData = ChromePicture(dropFile);+ var before = conversions.Jobs.Count;+ root.RaiseEvent(new DragEventArgs(DragDrop.DropEvent, dropData, root, donut.TranslatePoint(at, root)!.Value, KeyModifiers.Control));+ Assert.True(conversions.Jobs.Count > before, $"no conversion started for {preset}");++ var job = WaitFor(conversions.Jobs[0]);++ Assert.Equal(JobState.Completed, job.State);+ var output = Assert.Single(job.Outputs);+ Assert.Equal(folder, Path.GetDirectoryName(output));+ Assert.Equal([output], Directory.GetFiles(folder)); // the original wasn't kept+ Assert.False(File.Exists(job.Files[0].SourcePath));+ Assert.True(dropFile.Disposed);+ }+ finally+ {+ radial.Close(animate: false);+ Reset(store, folder);+ }+ }++ /// <summary>A point on a slice that converts these files, and its preset.</summary>+ private static (Point At, string Preset) FirstSlice(DonutMenu donut, RadialViewModel model)+ {+ var center = new Point(donut.Bounds.Width / 2, donut.Bounds.Height / 2);+ var radius = model.OuterRadius * 0.75;+ for (var degrees = 0; degrees < 360; degrees += 5)+ {+ var angle = degrees * Math.PI / 180;+ var p = new Point(center.X + radius * Math.Cos(angle), center.Y + radius * Math.Sin(angle));+ var hit = donut.HitTest(p);+ if (hit.Kind == DonutHitKind.Segment && model.PresetAt(hit.Index, -1) is { } preset && donut.Converts(hit))+ return (p, preset.Id);+ }+ throw new InvalidOperationException("No slice converts a PNG.");+ }++ [AvaloniaFact]+ public void A_picture_dropped_on_the_drop_zone_opens_the_donut_for_it_and_closing_lets_it_go()+ {+ TestServices.EnsureInitialized("en");+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<Filee.Core.Localization.ILocalizer>(), AppHost.Get<UpdateService>());+ vm.Navigate("home");+ var window = new MainWindow { DataContext = vm, Width = 1080, Height = 820 };+ window.Show();+ Pump();+ var radial = AppHost.Get<RadialController>();+ try+ {+ var page = window.GetVisualDescendants().OfType<HomePage>().Single();+ var zone = page.FindControl<Border>("DropZone")!;+ var file = VirtualFile.Create("cat.png", Png);+ using var data = ChromePicture(file);++ zone.RaiseEvent(new DragEventArgs(DragDrop.DropEvent, data, zone, new Point(20, 20), KeyModifiers.None));+ Pump();++ var model = AppHost.Get<RadialViewModel>();+ Assert.True(radial.IsVisible);+ Assert.True(model.IsClickMode);+ Assert.Equal("cat.png", Path.GetFileName(Assert.Single(model.Files)));+ Assert.NotEmpty(model.Presets);+ Assert.False(file.Disposed);++ radial.Close(animate: false);+ Assert.True(file.Disposed);+ }+ finally+ {+ radial.Close(animate: false);+ window.Close();+ }+ }++ [AvaloniaTheory]+ [InlineData("en")]+ [InlineData("ko")]+ [InlineData("zh-CN")]+ public void The_settings_for_files_from_a_browser_render_and_save(string language)+ {+ TestServices.EnsureInitialized(language);+ var store = AppHost.Get<UserDataStore>();+ var loc = AppHost.Get<Filee.Core.Localization.ILocalizer>();+ var vm = new MainWindowViewModel(AppHost.Services, loc, AppHost.Get<UpdateService>());+ vm.Navigate("general");+ var window = new MainWindow { DataContext = vm, Width = 1080, Height = 820 };+ window.Show();+ Pump();+ try+ {+ var page = (Filee.App.ViewModels.Pages.GeneralPageViewModel)vm.CurrentPage;+ var title = window.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Text == loc["general.browser_drops"]);+ var card = title.FindAncestorOfType<Border>()!;+ var folderBox = card.GetVisualDescendants().OfType<TextBox>().Single();+ var check = card.GetVisualDescendants().OfType<CheckBox>().Single();++ // Nothing chosen: the Downloads folder shows as the placeholder.+ Assert.Equal("", folderBox.Text ?? "");+ Assert.Equal(AppHost.Get<Filee.Core.Platform.IPlatformServices>().DownloadsFolder, folderBox.PlaceholderText);+ Assert.Equal(page.DownloadsFolder, page.BrowserFolderInUse);++ card.BringIntoView();+ Pump();+ using (var frame = window.CaptureRenderedFrame())+ {+ Assert.NotNull(frame);+ using var stream = File.Create(Path.Combine(TestServices.ScreenshotDirectory, $"page-general-browser-drops-{language}.png"));+ frame.Save(stream, new Avalonia.Media.Imaging.PngBitmapEncoderOptions());+ }++ var chosen = Path.Combine(Path.GetTempPath(), "Web downloads");+ page.BrowserFolder = " " + chosen + " ";+ check.IsChecked = true;+ Pump();+ Assert.Equal(chosen, store.Settings.BrowserDrops.Folder);+ Assert.True(store.Settings.BrowserDrops.SaveOnlyConverted);+ Assert.Equal(new WebDropOptions(chosen, true), AppHost.Get<ConversionService>().BrowserDropOptions());+ }+ finally+ {+ store.Settings.BrowserDrops.Folder = "";+ store.Settings.BrowserDrops.SaveOnlyConverted = false;+ window.Close();+ }+ }+}diff --git a/tests/Filee.Platform.Tests/DownloadsFolderTests.cs b/tests/Filee.Platform.Tests/DownloadsFolderTests.csnew file mode 100644index 00000000..8bff0957--- /dev/null+++ b/tests/Filee.Platform.Tests/DownloadsFolderTests.cs@@ -0,0 +1,46 @@+// Where files dragged from a browser are saved by default: the user's Downloads folder, as each platform knows it.++using Filee.Core.Platform;+using Filee.Platform.Linux;+using Filee.Platform.MacOS;+using Filee.Platform.Windows;++namespace Filee.Platform.Tests;++public class DownloadsFolderTests+{+ [Fact]+ public void Linux_reads_a_localized_downloads_folder_from_user_dirs()+ {+ const string userDirs = "# written by xdg-user-dirs-update\nXDG_DESKTOP_DIR=\"$HOME/바탕화면\"\nXDG_DOWNLOAD_DIR=\"$HOME/다운로드\"\n";+ Assert.Equal("/home/me/다운로드", XdgUserDirs.Download(userDirs, "/home/me"));+ Assert.Equal("/data/dl", XdgUserDirs.Download("XDG_DOWNLOAD_DIR=\"/data/dl\"", "/home/me"));+ // "$HOME/" alone turns the folder off; a relative path or no line at all means nothing.+ Assert.Null(XdgUserDirs.Download("XDG_DOWNLOAD_DIR=\"$HOME/\"", "/home/me"));+ Assert.Null(XdgUserDirs.Download("XDG_DOWNLOAD_DIR=\"dl\"", "/home/me"));+ Assert.Null(XdgUserDirs.Download("XDG_MUSIC_DIR=\"$HOME/Music\"", "/home/me"));+ }++ [Fact]+ public void Each_platform_names_an_absolute_downloads_folder()+ {+ IPlatformServices platform = new NullPlatformServices();+ if (OperatingSystem.IsWindows())+ platform = new WindowsPlatformServices();+ else if (OperatingSystem.IsMacOS())+ platform = new MacOSPlatformServices();+ else if (OperatingSystem.IsLinux())+ platform = new LinuxPlatformServices();+ Assert.True(Path.IsPathFullyQualified(platform.DownloadsFolder));+ Assert.Equal(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads"),+ ((IPlatformServices)new NullPlatformServices()).DownloadsFolder);+ }++ [Fact]+ public void The_donut_accepts_drags_that_offer_only_a_web_address_or_a_picture()+ {+ Assert.Contains("public.url", PasteboardPaths.DragTypes);+ Assert.Contains("public.html", PasteboardPaths.DragTypes);+ Assert.Contains("public.jpeg", PasteboardPaths.DragTypes);+ }+}