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
feat(macos): Shift+Cmd+V converts what's on the clipboard and puts the result back
skyhilam574faa311e2e
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 17464aea..29d10cab 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -332,6 +332,15 @@ can't be received through Avalonia; for a browser drag Filee reads the address aregisters too (see "Files dragged from a web browser"). A click-mode donut opened for a later launch or the service forgives one loss offocus within a second of opening (`ActivationGrace`): Filee becoming the active app can take focus away from it.+A keyboard shortcut with `TriggerGesture.Clipboard` (macOS: Shift + Cmd + V everywhere, added by settings schema 55)+reads the clipboard (`IPlatformServices.ReadClipboard`, `MacOSClipboard`) before the selection: copied files (file URLs,+then `NSFilenamesPboardType`; copied files that are gone give nothing, not Finder's icon), else a picture+(`PasteboardPaths.PictureTypes`, PNG first, TIFF last). A picture becomes a one-item `WebDrop` with+`SaveOnlyConverted`, so it is saved into the browser-drop folder when it converts and only the result stays. The+donut's jobs are started with `toClipboard`, and `ConversionService` puts their outputs back on the clipboard when they+finish (`CopyToClipboard`: a file URL per item, a single picture also as itself). The global hook can't hold the keys+back, so the app in front also gets Shift + Cmd + V (Paste and Match Style).+The donut, the toast and the notices are transparent windows. On Windows Filee keeps Avalonia's rendering defaults(ANGLE on Direct3D 11 composed through WinUI composition, then DirectComposition, then the window's redirectionsurface; software rendering when Direct3D 11 fails): each of them keeps per-pixel transparency. The log says what wasdiff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.csindex 68887386..ae0ed889 100644--- a/src/Filee.App/App.axaml.cs+++ b/src/Filee.App/App.axaml.cs@@ -98,6 +98,9 @@ public partial class App : Application_selectionPending = true;try{+ // The clipboard shortcut: what is on the clipboard first, the selection when there is nothing.+ if (e.Gesture is { Clipboard: true } && platform.SupportsClipboard && ShowForClipboard(radial, platform, e.X, e.Y, log))+ return;var files = OperatingSystem.IsMacOS()? await Task.Run(platform.GetFileManagerSelection) : platform.GetFileManagerSelection();if (files.Count > 0 && !store.Settings.Paused)@@ -202,6 +205,41 @@ public partial class App : ApplicationDispatcherTimer.RunOnce(() => AppHost.Get<WindowService>().ShowElevationNotice(), TimeSpan.FromSeconds(2));}+ /// <summary>+ /// Opens the donut for the files on the clipboard, else for its picture (a screenshot), which is saved when it+ /// converts, like a picture from a browser, without keeping the original. The results go back on the clipboard.+ /// False when the clipboard holds neither.+ /// </summary>+ private static bool ShowForClipboard(RadialController radial, IPlatformServices platform, int x, int y, ILogger log)+ {+ ClipboardContent? content;+ try+ {+ content = platform.ReadClipboard();+ }+ catch (Exception ex) when (ex is not OutOfMemoryException)+ {+ log.LogWarning(ex, "Could not read the clipboard");+ return false;+ }+ if (content is { Files.Count: > 0 })+ {+ radial.ShowForFiles(x, y, content.Files, toClipboard: true);+ return true;+ }+ if (content?.Picture is not { Length: > 0 } picture)+ return false;+ var name = $"Clipboard {DateTime.Now:yyyy-MM-dd HH.mm.ss}.{content.PictureExtension ?? "png"}";+ var web = new Filee.Core.Web.WebDrop([Filee.Core.Web.WebDropItem.FromBytes(name, picture)], Filee.Core.Web.WebDrop.DefaultWorkRoot)+ {+ SaveOnlyConverted = true,+ };+ log.LogInformation("The clipboard shortcut opens the donut for a {Extension} picture of {Bytes} bytes",+ content.PictureExtension, picture.Length);+ radial.ShowForFiles(x, y, web.Placeholders, web: web, toClipboard: true);+ return true;+ }+private void ListenForLaterLaunches(SingleInstance instance, ILogger log){instance.ArgumentsReceived += args =>diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.jsonindex 2e42b067..acdc03c7 100644--- a/src/Filee.App/Assets/i18n/ar.json+++ b/src/Filee.App/Assets/i18n/ar.json@@ -548,6 +548,8 @@"triggers.record": "تسجيل","triggers.recording": "اضغط على مجموعة مفاتيح…","triggers.clear": "مسح",+ "triggers.clipboard": "تحويل محتوى الحافظة",+ "triggers.clipboard_note": "الملفات المنسوخة أولًا، وإلا فالصورة المنسوخة (لقطة شاشة مأخوذة مع الضغط على Control). تحل النتيجة محلها في الحافظة جاهزة للصق؛ وتُحفظ نتيجة الصورة حيث تُحفظ ملفات المتصفح. إن لم يوجد أي منهما، فالملفات المحددة.","triggers.recording_key": "اضغط على مفتاح…","triggers.flip_title": "قلب الشريط الدائري","triggers.flip_description": "أثناء فتح الشريط الدائري، يعرض هذا المفتاح أو تدوير عجلة الماوس وجهه الخلفي. يمكنك إعداد الوجه الخلفي لكل شريط من قسم شريط الأدوات الدائري.",diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.jsonindex 9ff6b6d6..eb90cd17 100644--- a/src/Filee.App/Assets/i18n/de.json+++ b/src/Filee.App/Assets/i18n/de.json@@ -548,6 +548,8 @@"triggers.record": "Aufzeichnen","triggers.recording": "Tastenkombination drücken…","triggers.clear": "Leeren",+ "triggers.clipboard": "Inhalt der Zwischenablage umwandeln",+ "triggers.clipboard_note": "Zuerst kopierte Dateien, sonst ein kopiertes Bild (ein Bildschirmfoto mit gedrückter Control-Taste). Das Ergebnis ersetzt es in der Zwischenablage und lässt sich sofort einfügen; das Ergebnis eines Bildes wird dort gespeichert, wo Dateien aus dem Browser landen. Ist keins von beiden da, die ausgewählten Dateien.","triggers.recording_key": "Taste drücken…","triggers.flip_title": "Ringmenü wenden","triggers.flip_description": "Bei geöffnetem Ringmenü zeigt diese Taste oder das Mausrad die Rückseite. Die Rückseite jedes Ringmenüs wird unter Ringmenü eingerichtet.",diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 5d09bbf7..368e69eb 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -561,6 +561,8 @@"triggers.record": "Record","triggers.recording": "Press a key combination…","triggers.clear": "Clear",+ "triggers.clipboard": "Convert what's on the clipboard",+ "triggers.clipboard_note": "Copied files first, else a copied picture (a screenshot taken with Control held). The result replaces it on the clipboard, ready to paste; a picture's result is saved where files from a browser go. With neither, the selected files.","triggers.recording_key": "Press a key…","triggers.flip_title": "Flip the donut","triggers.flip_description": "While the donut is open, this key or a turn of the mouse wheel shows its back. Each donut gets its back under Donut toolbar.",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex 048ceac5..7cfe20ba 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -548,6 +548,8 @@"triggers.record": "Grabar","triggers.recording": "Pulsa una combinación de teclas…","triggers.clear": "Borrar",+ "triggers.clipboard": "Convertir lo que hay en el portapapeles",+ "triggers.clipboard_note": "Primero los archivos copiados; si no, una imagen copiada (una captura hecha con Control pulsado). El resultado la sustituye en el portapapeles, listo para pegar; el de una imagen se guarda donde van los archivos del navegador. Sin ninguno de los dos, los archivos seleccionados.","triggers.recording_key": "Pulsa una tecla…","triggers.flip_title": "Dar la vuelta al menú circular","triggers.flip_description": "Con el menú circular abierto, esta tecla o un giro de la rueda del ratón muestra su reverso. El reverso de cada menú se elige en Menú circular.",diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.jsonindex 7b517140..ffbeaeac 100644--- a/src/Filee.App/Assets/i18n/fr.json+++ b/src/Filee.App/Assets/i18n/fr.json@@ -561,6 +561,8 @@"triggers.record": "Enregistrer","triggers.recording": "Appuyez sur une combinaison de touches…","triggers.clear": "Effacer",+ "triggers.clipboard": "Convertir le contenu du presse-papiers",+ "triggers.clipboard_note": "D'abord les fichiers copiés, sinon une image copiée (une capture prise en maintenant Contrôle). Le résultat la remplace dans le presse-papiers, prêt à coller ; celui d'une image est enregistré là où vont les fichiers du navigateur. Sans l'un ni l'autre, les fichiers sélectionnés.","triggers.recording_key": "Appuyez sur une touche…","triggers.flip_title": "Retourner le menu circulaire","triggers.flip_description": "Quand le menu circulaire est ouvert, cette touche ou un cran de molette affiche son verso. Le verso de chaque menu se règle dans Menu circulaire.",diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.jsonindex e44149bf..17f01a10 100644--- a/src/Filee.App/Assets/i18n/hi.json+++ b/src/Filee.App/Assets/i18n/hi.json@@ -548,6 +548,8 @@"triggers.record": "रिकॉर्ड करें","triggers.recording": "कुंजी संयोजन दबाएँ…","triggers.clear": "साफ़ करें",+ "triggers.clipboard": "क्लिपबोर्ड की सामग्री बदलें",+ "triggers.clipboard_note": "पहले कॉपी की गई फ़ाइलें, नहीं तो कॉपी की गई तस्वीर (Control दबाकर लिया गया स्क्रीनशॉट)। नतीजा क्लिपबोर्ड पर उसकी जगह ले लेता है और पेस्ट के लिए तैयार रहता है; तस्वीर का नतीजा वहाँ सहेजा जाता है जहाँ ब्राउज़र की फ़ाइलें जाती हैं। दोनों न हों तो चुनी गई फ़ाइलें।","triggers.recording_key": "कोई कुंजी दबाएँ…","triggers.flip_title": "डोनट पलटें","triggers.flip_description": "डोनट खुला हो, तो यह कुंजी दबाने या माउस व्हील घुमाने पर उसका पिछला भाग दिखता है। हर डोनट का पिछला भाग डोनट टूलबार में चुनें।",diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.jsonindex cc0d2b3e..0d772878 100644--- a/src/Filee.App/Assets/i18n/ja.json+++ b/src/Filee.App/Assets/i18n/ja.json@@ -548,6 +548,8 @@"triggers.record": "記録","triggers.recording": "キーの組み合わせを押してください…","triggers.clear": "クリア",+ "triggers.clipboard": "クリップボードの内容を変換",+ "triggers.clipboard_note": "コピーしたファイルを優先し、なければコピーした画像(Control を押しながら撮ったスクリーンショット)を使います。結果はクリップボードの内容と置き換わり、そのまま貼り付けられます。画像の結果はブラウザーのファイルの保存先に保存されます。どちらもなければ選択中のファイルを使います。","triggers.recording_key": "キーを押してください…","triggers.flip_title": "ドーナツメニューを裏返す","triggers.flip_description": "ドーナツメニューが開いているときにこのキーを押すか、マウスホイールを回すと裏面が表示されます。各ドーナツメニューの裏面は「ドーナツメニュー」で設定します。",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex d5f1e16e..484cfd30 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -561,6 +561,8 @@"triggers.record": "키 입력","triggers.recording": "키 조합을 누르세요…","triggers.clear": "지우기",+ "triggers.clipboard": "클립보드의 내용 변환",+ "triggers.clipboard_note": "복사한 파일을 먼저, 없으면 복사한 그림(Control을 누른 채 찍은 스크린샷)을 씁니다. 결과는 클립보드의 내용을 대신해 바로 붙여넣을 수 있고, 그림의 결과는 브라우저 파일을 저장하는 폴더에 저장됩니다. 둘 다 없으면 선택한 파일을 씁니다.","triggers.recording_key": "키를 누르세요…","triggers.flip_title": "도넛 뒤집기","triggers.flip_description": "도넛이 열려 있을 때 이 키를 누르거나 마우스 휠을 돌리면 뒷면이 나와요. 도넛마다 뒷면은 원형 툴바에서 정해요.",diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.jsonindex 5e8926ee..d2aafceb 100644--- a/src/Filee.App/Assets/i18n/ne.json+++ b/src/Filee.App/Assets/i18n/ne.json@@ -548,6 +548,8 @@"triggers.record": "रेकर्ड गर्नुहोस्","triggers.recording": "कुञ्जी थिच्नुहोस्...","triggers.clear": "खाली गर्नुहोस्",+ "triggers.clipboard": "क्लिपबोर्डमा भएको कुरा रूपान्तरण गर्नुहोस्",+ "triggers.clipboard_note": "पहिले प्रतिलिपि गरिएका फाइलहरू, नभए प्रतिलिपि गरिएको तस्बिर (Control थिचेर लिइएको स्क्रिनसट)। नतिजाले क्लिपबोर्डमा त्यसको ठाउँ लिन्छ र टाँस्न तयार हुन्छ; तस्बिरको नतिजा ब्राउजरका फाइलहरू जाने ठाउँमा सेभ हुन्छ। दुवै नभए, चयन गरिएका फाइलहरू।","triggers.recording_key": "कुञ्जी थिच्नुहोस्...","triggers.flip_title": "डोनट पल्टाउनुहोस्","triggers.flip_description": "डोनट खुला हुँदा, यो कुञ्जी थिच्दा वा माउस ह्विल घुमाउँदा यसको पछाडिको भाग देखिन्छ। प्रत्येक डोनटको पछाडिको भाग डोनट टुलबार अन्तर्गत छान्न सकिन्छ।",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 8f50edcc..be2b5dae 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -561,6 +561,8 @@"triggers.record": "Nagraj","triggers.recording": "Naciśnij kombinację klawiszy…","triggers.clear": "Wyczyść",+ "triggers.clipboard": "Konwertuj zawartość schowka",+ "triggers.clipboard_note": "Najpierw skopiowane pliki, a jeśli ich nie ma, skopiowany obraz (zrzut ekranu zrobiony z wciśniętym Control). Wynik zastępuje go w schowku i jest gotowy do wklejenia; wynik obrazu jest zapisywany tam, gdzie pliki z przeglądarki. Gdy nie ma żadnego z nich, zaznaczone pliki.","triggers.recording_key": "Naciśnij klawisz…","triggers.flip_title": "Obracanie pierścienia","triggers.flip_description": "Gdy pierścień jest otwarty, ten klawisz lub obrót kółka myszy pokazuje jego tył. Tył każdego pierścienia ustawisz w Pasku-pierścieniu.",diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.jsonindex 9b96f02f..db682dc2 100644--- a/src/Filee.App/Assets/i18n/pt-BR.json+++ b/src/Filee.App/Assets/i18n/pt-BR.json@@ -561,6 +561,8 @@"triggers.record": "Gravar","triggers.recording": "Pressione uma combinação de teclas…","triggers.clear": "Limpar",+ "triggers.clipboard": "Converter o que está na área de transferência",+ "triggers.clipboard_note": "Primeiro os arquivos copiados; senão, uma imagem copiada (uma captura feita segurando Control). O resultado a substitui na área de transferência, pronto para colar; o de uma imagem é salvo onde ficam os arquivos do navegador. Sem nenhum dos dois, os arquivos selecionados.","triggers.recording_key": "Pressione uma tecla…","triggers.flip_title": "Virar o menu","triggers.flip_description": "Com o menu aberto, esta tecla ou um giro da roda do mouse mostra o verso. Cada menu recebe o verso em Menu circular.",diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.jsonindex 41c27c75..f776441e 100644--- a/src/Filee.App/Assets/i18n/pt-PT.json+++ b/src/Filee.App/Assets/i18n/pt-PT.json@@ -561,6 +561,8 @@"triggers.record": "Gravar","triggers.recording": "Prime uma combinação de teclas…","triggers.clear": "Limpar",+ "triggers.clipboard": "Converter o conteúdo da área de transferência",+ "triggers.clipboard_note": "Primeiro os ficheiros copiados; caso contrário, uma imagem copiada (uma captura feita com Control premido). O resultado substitui-a na área de transferência, pronto a colar; o de uma imagem é guardado onde ficam os ficheiros do browser. Sem nenhum dos dois, os ficheiros selecionados.","triggers.recording_key": "Prime uma tecla…","triggers.flip_title": "Virar a barra circular","triggers.flip_description": "Com a barra circular aberta, esta tecla ou a roda do rato mostra o verso. Configura o verso de cada barra em Barra circular.",diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.jsonindex e1a24eb7..6008cb51 100644--- a/src/Filee.App/Assets/i18n/ru.json+++ b/src/Filee.App/Assets/i18n/ru.json@@ -561,6 +561,8 @@"triggers.record": "Записать","triggers.recording": "Нажмите сочетание клавиш…","triggers.clear": "Очистить",+ "triggers.clipboard": "Конвертировать содержимое буфера обмена",+ "triggers.clipboard_note": "Сначала скопированные файлы, иначе скопированное изображение (снимок экрана, сделанный с нажатой Control). Результат заменяет его в буфере обмена и готов к вставке; результат изображения сохраняется туда же, куда файлы из браузера. Если нет ни того, ни другого — выбранные файлы.","triggers.recording_key": "Нажмите клавишу…","triggers.flip_title": "Переворот кругового меню","triggers.flip_description": "Когда круговое меню открыто, эта клавиша или поворот колеса мыши показывает его обратную сторону. Обратную сторону каждого меню настраивают в разделе «Круговое меню».",diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.jsonindex 536d044e..5dd7197f 100644--- a/src/Filee.App/Assets/i18n/th.json+++ b/src/Filee.App/Assets/i18n/th.json@@ -548,6 +548,8 @@"triggers.record": "บันทึกปุ่ม","triggers.recording": "กดปุ่มคีย์ลัดที่ต้องการ…","triggers.clear": "ล้างค่า",+ "triggers.clipboard": "แปลงสิ่งที่อยู่ในคลิปบอร์ด",+ "triggers.clipboard_note": "ใช้ไฟล์ที่คัดลอกไว้ก่อน ถ้าไม่มีจึงใช้รูปที่คัดลอกไว้ (ภาพหน้าจอที่ถ่ายขณะกด Control) ผลลัพธ์จะแทนที่ในคลิปบอร์ดพร้อมวาง ผลลัพธ์ของรูปจะบันทึกไว้ที่เดียวกับไฟล์จากเบราว์เซอร์ ถ้าไม่มีทั้งสองอย่าง จะใช้ไฟล์ที่เลือกไว้","triggers.recording_key": "กดปุ่ม…","triggers.flip_title": "พลิกแถบโดนัท","triggers.flip_description": "ขณะที่แถบโดนัทเปิดอยู่ การกดปุ่มนี้หรือหมุนล้อเมาส์จะแสดงด้านหลัง โดนัทแต่ละอันสามารถตั้งค่าด้านหลังได้ที่ แถบโดนัท",diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.jsonindex 449f8b30..e6b66219 100644--- a/src/Filee.App/Assets/i18n/tr.json+++ b/src/Filee.App/Assets/i18n/tr.json@@ -548,6 +548,8 @@"triggers.record": "Kaydet","triggers.recording": "Bir tuş birleşimine basın…","triggers.clear": "Temizle",+ "triggers.clipboard": "Panodakini dönüştür",+ "triggers.clipboard_note": "Önce kopyalanan dosyalar, yoksa kopyalanan bir resim (Control basılıyken alınan ekran görüntüsü). Sonuç panoda onun yerini alır ve yapıştırmaya hazırdır; bir resmin sonucu tarayıcıdan gelen dosyaların kaydedildiği yere kaydedilir. İkisi de yoksa seçili dosyalar.","triggers.recording_key": "Bir tuşa basın…","triggers.flip_title": "Halkayı çevir","triggers.flip_description": "Halka açıkken bu tuş veya fare tekerleği arka yüzü gösterir. Her halkanın arka yüzünü Halka araç çubuğu bölümünden ayarlayabilirsiniz.",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex 8d069c66..0a5de556 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -561,6 +561,8 @@"triggers.record": "录制","triggers.recording": "请按下组合键…","triggers.clear": "清除",+ "triggers.clipboard": "转换剪贴板上的内容",+ "triggers.clipboard_note": "先用复制的文件,否则用复制的图片(按住 Control 截的屏)。结果会替换剪贴板上的内容,可直接粘贴;图片的结果保存到浏览器文件所在的文件夹。两者都没有时,使用选中的文件。","triggers.recording_key": "请按下一个键…","triggers.flip_title": "翻转圆环","triggers.flip_description": "圆环打开时,按下此键或转动鼠标滚轮即可显示背面。每个圆环的背面在环形工具栏中设置。",diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.jsonindex 5d555109..d1df6aa3 100644--- a/src/Filee.App/Assets/i18n/zh-TW.json+++ b/src/Filee.App/Assets/i18n/zh-TW.json@@ -561,6 +561,8 @@"triggers.record": "錄製","triggers.recording": "請按下組合鍵…","triggers.clear": "清除",+ "triggers.clipboard": "轉換剪貼簿上的內容",+ "triggers.clipboard_note": "先用複製的檔案,否則用複製的圖片(按住 Control 拍的截圖)。結果會取代剪貼簿上的內容,可直接貼上;圖片的結果存到瀏覽器檔案的資料夾。兩者都沒有時,使用選取的檔案。","triggers.recording_key": "請按下一個鍵…","triggers.flip_title": "翻轉圓環","triggers.flip_description": "圓環開啟時,按下此鍵或轉動滑鼠滾輪即可顯示背面。每個圓環的背面在環形工具列中設定。",diff --git a/src/Filee.App/Services/ConversionService.cs b/src/Filee.App/Services/ConversionService.csindex 44b0c0fd..f3c121d1 100644--- a/src/Filee.App/Services/ConversionService.cs+++ b/src/Filee.App/Services/ConversionService.cs@@ -12,6 +12,7 @@ using Filee.Core.Platform;using Filee.Core.Presets;using Filee.Core.Settings;using Filee.Core.Web;+using Microsoft.Extensions.Logging;namespace Filee.App.Services;@@ -28,14 +29,20 @@ public sealed class ConversionServiceprivate readonly ILocalizer _loc;private readonly IPlatformServices _platform;private readonly WebDownloader _downloader;+ private readonly ILogger<ConversionService>? _log;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, WebDownloader downloader)+ /// <summary>Jobs whose results go on the clipboard when they finish (the clipboard shortcut).</summary>+ private readonly System.Collections.Concurrent.ConcurrentDictionary<string, byte> _clipboardJobs = new();++ public ConversionService(JobQueue queue, UserDataStore store, ILocalizer loc, IPlatformServices platform, WebDownloader downloader,+ ILogger<ConversionService>? log = null){+ _log = log;_queue = queue;_store = store;_loc = loc;@@ -65,8 +72,10 @@ public sealed class ConversionService/// 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>+ /// <param name="toClipboard">The results go on the clipboard when the job has finished (the clipboard shortcut).</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, WebDrop? web = null)+ public JobViewModel? Start(IReadOnlyList<string> files, Preset preset, bool showInToast = true, WebDrop? web = null,+ bool toClipboard = false){if (files.Count == 0 || preset.IsGroup || preset.IsTool){@@ -78,11 +87,21 @@ public sealed class ConversionServiceWebDropFetcher? fetcher = null;if (web is not null){- fetcher = web.CreateFetcher(BrowserDropOptions(), _downloader);+ var options = BrowserDropOptions();+ if (web.SaveOnlyConverted is { } only)+ options = options with { SaveOnlyConverted = only };+ fetcher = web.CreateFetcher(options, _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);+ if (toClipboard)+ {+ _clipboardJobs[job.Id] = 0;+ // It may have finished already (nothing to convert): OnJobFinished found no mark then.+ if (job.State is not (JobState.Queued or JobState.Running) && _clipboardJobs.TryRemove(job.Id, out _))+ Dispatcher.UIThread.Post(() => CopyResults(job));+ }var vm = new JobViewModel(job, _loc, _platform, Remove, RetryFailed);_byId[job.Id] = vm;Jobs.Insert(0, vm);@@ -217,8 +236,11 @@ public sealed class ConversionService_store.AddHistory(entry);if (_waiting.TryGetValue(job.Id, out var waiting))waiting.TrySetResult(job);+ var toClipboard = _clipboardJobs.TryRemove(job.Id, out _);Dispatcher.UIThread.Post(() =>{+ if (toClipboard)+ CopyResults(job);if (!_byId.TryGetValue(job.Id, out var vm))return;vm.Refresh();@@ -229,6 +251,21 @@ public sealed class ConversionService});}+ /// <summary>+ /// Puts what a clipboard shortcut's job made on the clipboard, in place of what it was made from. A cancelled job,+ /// or one that made nothing, leaves the clipboard alone. UI thread.+ /// </summary>+ private void CopyResults(ConversionJob job)+ {+ if (job.State == JobState.Cancelled)+ return;+ var outputs = job.Outputs.Where(File.Exists).Distinct(StringComparer.Ordinal).ToList();+ if (outputs.Count > 0 && !_platform.CopyToClipboard(outputs))+ _log?.LogWarning("Could not put {Count} converted file(s) on the clipboard", outputs.Count);+ else if (outputs.Count > 0)+ _log?.LogInformation("Put {Count} converted file(s) on the clipboard", outputs.Count);+ }+/// <summary>Counts a fully successful conversion; true when the feedback card is due now (only once).</summary>private bool CountSuccess(ConversionJob job){@@ -247,5 +284,6 @@ public sealed class ConversionServiceToastJobs.Remove(vm);_byId.TryRemove(vm.Job.Id, out _);_watchJobs.TryRemove(vm.Job.Id, out _);+ _clipboardJobs.TryRemove(vm.Job.Id, out _);}}diff --git a/src/Filee.App/Services/RadialController.cs b/src/Filee.App/Services/RadialController.csindex 943831e6..344b8b07 100644--- a/src/Filee.App/Services/RadialController.cs+++ b/src/Filee.App/Services/RadialController.cs@@ -65,6 +65,7 @@ public sealed class RadialController(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+ private bool _toClipboard; // the click-mode donut's files came from the clipboard: their results go back on it/// <summary>/// How long a drag that never brought files may keep the invisible window up, in case the button release is@@ -86,6 +87,7 @@ public sealed class RadialController(ReleaseProgressToToast();_grace.Cancel();ReplaceWeb(null);+ _toClipboard = false;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();@@ -109,9 +111,11 @@ public sealed class RadialController(/// 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. <paramref name="web"/>: the files are placeholders- /// of this browser drop (the drop zone), which the donut now owns.+ /// of this browser drop (the drop zone, a picture on the clipboard), which the donut now owns.+ /// <paramref name="toClipboard"/>: the files came from the clipboard, and their results go back on it./// </summary>- public void ShowForFiles(int x, int y, IReadOnlyList<string> files, bool forAnotherProcess = false, WebDrop? web = null)+ public void ShowForFiles(int x, int y, IReadOnlyList<string> files, bool forAnotherProcess = false, WebDrop? web = null,+ bool toClipboard = false){if (web is null)files = platform.ResolveShortcuts(files);@@ -122,6 +126,7 @@ public sealed class RadialController(}ReleaseProgressToToast();ReplaceWeb(web);+ _toClipboard = toClipboard;if (forAnotherProcess && OperatingSystem.IsMacOS())_grace.Start();else@@ -342,7 +347,7 @@ public sealed class RadialController(if ((preset.TargetFormat == "pdf" && preset.Pdf.MergeIntoSingle || preset.JoinsIntoOneMedia || preset.JoinsImages) && sources.Count > 1){Close(animate: false);- _ = MergeInOrderAsync(sources, preset.Clone(), web);+ _ = MergeInOrderAsync(sources, preset.Clone(), web, _toClipboard);return;}@@ -351,13 +356,13 @@ public sealed class RadialController(if (preset.Output.AskEveryTime && web is null){Close(animate: false);- _ = AskThenConvertAsync(sources, preset);+ _ = AskThenConvertAsync(sources, preset, _toClipboard);return;}- log.LogInformation("Converting {Count} file(s) with preset {Preset}{Web}", sources.Count, preset.Id,- web is null ? "" : " (from a browser)");- var job = conversions.Start(sources, preset, showInToast: false, web);+ log.LogInformation("Converting {Count} file(s) with preset {Preset}{Web}{Clipboard}", sources.Count, preset.Id,+ web is null ? "" : " (from a browser)", _toClipboard ? " (from the clipboard)" : "");+ var job = conversions.Start(sources, preset, showInToast: false, web, _toClipboard);if (job is null || _window is null){Close();@@ -367,7 +372,7 @@ public sealed class RadialController(ShowProgress(job);}- private async Task MergeInOrderAsync(IReadOnlyList<string> files, Preset preset, WebDrop? web)+ private async Task MergeInOrderAsync(IReadOnlyList<string> files, Preset preset, WebDrop? web, bool toClipboard){try{@@ -375,10 +380,10 @@ public sealed class RadialController(if (ordered is not null && preset.JoinsImages)RememberMergeLayout(preset);if (ordered is not null && preset.Output.AskEveryTime && web is null)- await AskThenConvertAsync(ordered, preset);+ await AskThenConvertAsync(ordered, preset, toClipboard);else if (ordered is not null){- conversions.Start(ordered, preset, web: web);+ conversions.Start(ordered, preset, web: web, toClipboard: toClipboard);web = null; // the conversion owns the browser drop now}}@@ -418,7 +423,7 @@ public sealed class RadialController(}}- private async Task AskThenConvertAsync(IReadOnlyList<string> sources, Preset preset)+ private async Task AskThenConvertAsync(IReadOnlyList<string> sources, Preset preset, bool toClipboard){try{@@ -427,7 +432,7 @@ public sealed class RadialController(if (await windows.AskSaveLocationAsync(sources, running, AskedLocation.MakesOneResult(running, sources.Count)) is { } asked){log.LogInformation("Converting {Count} file(s) with preset {Preset} where the user chose", sources.Count, preset.Id);- conversions.Start(sources, asked);+ conversions.Start(sources, asked, toClipboard: toClipboard);}}catch (Exception ex) when (ex is not OutOfMemoryException)diff --git a/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs b/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.csindex 45f903e6..1b1fca15 100644--- a/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs@@ -22,10 +22,12 @@ public sealed partial class TriggerGestureViewModel : ObservableObjectprivate readonly Action _save;private bool _loading = true;- public TriggerGestureViewModel(TriggerGesture gesture, ILocalizer loc, Action save)+ /// <param name="clipboardAvailable">The platform can read the clipboard (<see cref="IPlatformServices.SupportsClipboard"/>).</param>+ public TriggerGestureViewModel(TriggerGesture gesture, ILocalizer loc, Action save, bool clipboardAvailable = false){_gesture = gesture;_save = save;+ ClipboardAvailable = clipboardAvailable;Kinds = Enum.GetValues<TriggerKind>().Select(k => new Choice<TriggerKind>(k, loc[$"triggers.kind.{k}"])).ToList();Buttons = Enum.GetValues<TriggerMouseButton>().Where(b => b != TriggerMouseButton.None).Select(b => new Choice<TriggerMouseButton>(b, loc[$"triggers.button.{b}"])).ToList();@@ -49,6 +51,7 @@ public sealed partial class TriggerGestureViewModel : ObservableObjectDragThreshold = gesture.DragThreshold;HoldMilliseconds = gesture.HoldMilliseconds;Scope = Scopes.First(s => s.Value == gesture.Scope);+ Clipboard = gesture.Clipboard;_loading = false;}@@ -60,10 +63,11 @@ public sealed partial class TriggerGestureViewModel : ObservableObjectpublic string RecordingLabel { get; }public string SystemLabel { get; }public string MetaLabel => OperatingSystem.IsMacOS() ? "⌘ Cmd" : "Win";+ public bool ClipboardAvailable { get; }[ObservableProperty] private bool _enabled;- [ObservableProperty, NotifyPropertyChangedFor(nameof(UsesMouse), nameof(UsesKey), nameof(UsesThreshold), nameof(UsesHold))]+ [ObservableProperty, NotifyPropertyChangedFor(nameof(UsesMouse), nameof(UsesKey), nameof(UsesThreshold), nameof(UsesHold), nameof(UsesClipboard))]private Choice<TriggerKind> _kind = null!;[ObservableProperty] private bool _ctrl;@@ -75,12 +79,15 @@ public sealed partial class TriggerGestureViewModel : ObservableObject[ObservableProperty, NotifyPropertyChangedFor(nameof(ThresholdText))] private int _dragThreshold;[ObservableProperty] private int _holdMilliseconds;[ObservableProperty] private Choice<TriggerScope> _scope = null!;+ [ObservableProperty] private bool _clipboard;[ObservableProperty, NotifyPropertyChangedFor(nameof(KeyText))] private bool _isRecording;public bool UsesMouse => Kind.Value != TriggerKind.KeyChord;public bool UsesKey => Kind.Value == TriggerKind.KeyChord;public bool UsesThreshold => Kind.Value == TriggerKind.Drag;public bool UsesHold => Kind.Value == TriggerKind.Hold;+ /// <summary>A keyboard shortcut where the clipboard can be read: it may convert what is on the clipboard.</summary>+ public bool UsesClipboard => UsesKey && ClipboardAvailable;public string KeyText => IsRecording ? RecordingLabel : string.IsNullOrEmpty(Key) ? "—" : Key;public string ThresholdText => DragThreshold == 0 ? SystemLabel : $"{DragThreshold}px";public string Summary => GestureText.Describe(_gesture);@@ -94,7 +101,7 @@ public sealed partial class TriggerGestureViewModel : ObservableObject{base.OnPropertyChanged(e);if (_loading || e.PropertyName is nameof(IsRecording) or nameof(KeyText) or nameof(ThresholdText) or nameof(Summary)- or nameof(UsesMouse) or nameof(UsesKey) or nameof(UsesThreshold) or nameof(UsesHold))+ or nameof(UsesMouse) or nameof(UsesKey) or nameof(UsesThreshold) or nameof(UsesHold) or nameof(UsesClipboard))return;_gesture.Enabled = Enabled;@@ -106,6 +113,7 @@ public sealed partial class TriggerGestureViewModel : ObservableObject_gesture.DragThreshold = Math.Clamp(DragThreshold, 0, 200);_gesture.HoldMilliseconds = Math.Clamp(HoldMilliseconds, 150, 3000);_gesture.Scope = Scope.Value;+ _gesture.Clipboard = Clipboard;OnPropertyChanged(nameof(Summary));_save();}@@ -251,7 +259,7 @@ public sealed partial class TriggersPageViewModel : ObservableObject, IDisposablif (triggers is not null)triggers.StatusChanged += OnTriggerStatusChanged;foreach (var gesture in store.Settings.Triggers)- Gestures.Add(new TriggerGestureViewModel(gesture, loc, Save));+ Gestures.Add(new TriggerGestureViewModel(gesture, loc, Save, platform?.SupportsClipboard == true));ExcludedApps = new ExcludedAppsViewModel(store.Settings.ExcludedProcesses, platform, Save);Flip = new FlipOptionsViewModel(store, loc, Save);}@@ -335,7 +343,7 @@ public sealed partial class TriggersPageViewModel : ObservableObject, IDisposabl{var gesture = new TriggerGesture { Modifiers = ModifierKeys.Alt, Button = TriggerMouseButton.Left };_store.Settings.Triggers.Add(gesture);- Gestures.Add(new TriggerGestureViewModel(gesture, _loc, Save));+ Gestures.Add(new TriggerGestureViewModel(gesture, _loc, Save, _platform?.SupportsClipboard == true));Save();}diff --git a/src/Filee.App/Views/Pages/TriggersPage.axaml b/src/Filee.App/Views/Pages/TriggersPage.axamlindex 8faaabb3..73940d7d 100644--- a/src/Filee.App/Views/Pages/TriggersPage.axaml+++ b/src/Filee.App/Views/Pages/TriggersPage.axaml@@ -98,6 +98,17 @@</StackPanel></Grid>+ <!-- Clipboard shortcut: converts the files or the picture on the clipboard and puts the results back -->+ <DockPanel IsVisible="{Binding UsesClipboard}">+ <ToggleSwitch DockPanel.Dock="Right" OnContent="{x:Null}" OffContent="{x:Null}" MinWidth="0" Margin="12,0,0,0"+ VerticalAlignment="Center" IsChecked="{Binding Clipboard}"+ AutomationProperties.Name="{DynamicResource triggers.clipboard}" />+ <StackPanel Spacing="2">+ <TextBlock Text="{DynamicResource triggers.clipboard}" TextWrapping="Wrap" />+ <TextBlock Classes="caption" Text="{DynamicResource triggers.clipboard_note}" TextWrapping="Wrap" />+ </StackPanel>+ </DockPanel>+<StackPanel IsVisible="{Binding UsesThreshold}"><DockPanel><TextBlock DockPanel.Dock="Right" Text="{Binding ThresholdText}" FontWeight="SemiBold" />diff --git a/src/Filee.Core/Platform/IPlatformServices.cs b/src/Filee.Core/Platform/IPlatformServices.csindex d3690414..f42457f5 100644--- a/src/Filee.Core/Platform/IPlatformServices.cs+++ b/src/Filee.Core/Platform/IPlatformServices.cs@@ -78,6 +78,23 @@ public interface IPlatformServices/// <summary>Files currently selected in the foreground file manager window (empty if none).</summary>IReadOnlyList<string> GetFileManagerSelection();+ /// <summary>+ /// Whether a keyboard shortcut can read the clipboard and put results back on it (<see cref="Settings.TriggerGesture.Clipboard"/>).+ /// </summary>+ bool SupportsClipboard => false;++ /// <summary>+ /// What is on the clipboard for a conversion: the existing files copied there, else a picture (a screenshot);+ /// null for anything else (text, nothing). Call it on the UI thread.+ /// </summary>+ ClipboardContent? ReadClipboard() => null;++ /// <summary>+ /// Puts <paramref name="paths"/> on the clipboard as files, a single picture also as itself, so it pastes into+ /// a file manager, a chat or a document. Call it on the UI thread. False when it couldn't.+ /// </summary>+ bool CopyToClipboard(IReadOnlyList<string> paths) => false;+/// <summary>/// For the log when a shortcut found no selected files: the foreground window's class and process/// ("CabinetWClass / explorer"). Empty where the platform can't tell.@@ -142,6 +159,17 @@ public interface IPlatformServices/// </summary>public sealed class StartupEntryNotKeptException(string message) : IOException(message);+/// <summary>+/// What <see cref="IPlatformServices.ReadClipboard"/> found: <see cref="Files"/>, or else the bytes of a picture in+/// <see cref="PictureExtension"/>'s format ("png").+/// </summary>+public sealed record ClipboardContent(IReadOnlyList<string> Files, byte[]? Picture = null, string? PictureExtension = null)+{+ public static ClipboardContent OfFiles(IReadOnlyList<string> files) => new(files);++ public static ClipboardContent OfPicture(byte[] bytes, string extension) => new([], bytes, extension);+}+/// <summary>The window in front: its process name as <see cref="IPlatformServices.ProcessNameAt"/> reports it, and whether it belongs to the file manager or desktop.</summary>public sealed record ForegroundWindowInfo(string? ProcessName, bool IsFileManager);diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.csindex f32156ea..08f12f75 100644--- a/src/Filee.Core/Settings/AppSettings.cs+++ b/src/Filee.Core/Settings/AppSettings.cs@@ -123,7 +123,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 = 54;+ public const int CurrentSchemaVersion = 55;public int SchemaVersion { get; set; } = CurrentSchemaVersion;diff --git a/src/Filee.Core/Settings/TriggerGesture.cs b/src/Filee.Core/Settings/TriggerGesture.csindex d7a870a0..c2e3475d 100644--- a/src/Filee.Core/Settings/TriggerGesture.cs+++ b/src/Filee.Core/Settings/TriggerGesture.cs@@ -72,6 +72,13 @@ public sealed class TriggerGesturepublic TriggerScope Scope { get; set; } = TriggerScope.FileManager;+ /// <summary>+ /// <see cref="TriggerKind.KeyChord"/> only, where the platform has a clipboard (<c>SupportsClipboard</c>): the+ /// donut opens for the files on the clipboard, else the picture on it (a screenshot), and the results are put back+ /// on the clipboard. With neither on it, the file manager's selection as without this.+ /// </summary>+ public bool Clipboard { get; set; }+public TriggerGesture Clone() => (TriggerGesture)MemberwiseClone();/// <summary>Default gestures for the current OS.</summary>@@ -79,10 +86,24 @@ public sealed class TriggerGesture{// On macOS Ctrl+click means right-click, and Option already means "copy" in Finder.var dragModifier = OperatingSystem.IsMacOS() ? ModifierKeys.Alt : ModifierKeys.Ctrl;- return+ List<TriggerGesture> defaults =[new() { Kind = TriggerKind.Drag, Modifiers = dragModifier, Button = TriggerMouseButton.Left },new() { Kind = TriggerKind.KeyChord, Modifiers = ModifierKeys.Ctrl | ModifierKeys.Alt, Button = TriggerMouseButton.None, Key = "Space" },];+ if (OperatingSystem.IsMacOS())+ defaults.Add(ClipboardShortcut());+ return defaults;}++ /// <summary>+ /// macOS: Shift + Cmd + V everywhere converts what is on the clipboard (a screenshot taken with Ctrl, files copied+ /// in Finder) and puts the result back, ready to paste. The hook can't hold the keys back, so the app in front+ /// also sees them (Paste and Match Style).+ /// </summary>+ public static TriggerGesture ClipboardShortcut() => new()+ {+ Kind = TriggerKind.KeyChord, Modifiers = ModifierKeys.Shift | ModifierKeys.Meta, Button = TriggerMouseButton.None,+ Key = "V", Scope = TriggerScope.Anywhere, Clipboard = true,+ };}diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.csindex b788b690..18677ac3 100644--- a/src/Filee.Core/Settings/UserDataStore.cs+++ b/src/Filee.Core/Settings/UserDataStore.cs@@ -438,9 +438,27 @@ internal static class SettingsMigrationsif (settings.Triggers.Count == 0)settings.Triggers = TriggerGesture.Defaults();+ // v55: macOS gets Shift + Cmd + V for the clipboard (a screenshot copied with Ctrl, files copied in Finder).+ if (settings.SchemaVersion < 55 && OperatingSystem.IsMacOS())+ AddClipboardShortcut(settings.Triggers);+settings.SchemaVersion = AppSettings.CurrentSchemaVersion;}+ /// <summary>+ /// Adds <see cref="TriggerGesture.ClipboardShortcut"/> unless a keyboard shortcut already takes its keys (the user's+ /// own stays as it is). True when it was added.+ /// </summary>+ internal static bool AddClipboardShortcut(List<TriggerGesture> triggers)+ {+ var shortcut = TriggerGesture.ClipboardShortcut();+ if (triggers.Any(g => g.Kind == TriggerKind.KeyChord && g.Modifiers == shortcut.Modifiers+ && string.Equals(g.Key, shortcut.Key, StringComparison.OrdinalIgnoreCase)))+ return false;+ triggers.Add(shortcut);+ return true;+ }+/// <summary>Upgrades presets and profiles written with settings schema <paramref name="from"/>.</summary>/// <returns>True when something was added.</returns>public static bool ApplyToLibrary(int from, List<Preset> presets, List<ToolbarProfile> profiles)diff --git a/src/Filee.Core/Web/WebDrop.cs b/src/Filee.Core/Web/WebDrop.csindex e814806d..247333e0 100644--- a/src/Filee.Core/Web/WebDrop.cs+++ b/src/Filee.Core/Web/WebDrop.cs@@ -116,6 +116,12 @@ public sealed class WebDrop : IDisposable/// <summary>This drop's own folder inside the work root.</summary>public string WorkFolder { get; }+ /// <summary>+ /// Whether only the converted file is kept, whatever Settings says (<see cref="WebDropOptions.SaveOnlyConverted"/>);+ /// null follows Settings. A picture from the clipboard keeps only its result: the original was never a file.+ /// </summary>+ public bool? SaveOnlyConverted { get; init; }+/// <summary>The paths the files stand as until they are saved.</summary>public IReadOnlyList<string> Placeholders => _placeholders;diff --git a/src/Filee.Platform.MacOS/MacOSClipboard.cs b/src/Filee.Platform.MacOS/MacOSClipboard.csnew file mode 100644index 00000000..f094e714--- /dev/null+++ b/src/Filee.Platform.MacOS/MacOSClipboard.cs@@ -0,0 +1,151 @@+// The general pasteboard (the clipboard) for the clipboard shortcut (TriggerGesture.Clipboard): files copied in Finder,+// or a picture (a screenshot taken with Ctrl held), come in; the converted files go back, ready to paste.++using System.Runtime.InteropServices;+using System.Runtime.Versioning;+using Filee.Core.Platform;++namespace Filee.Platform.MacOS;++[SupportedOSPlatform("macos")]+internal static class MacOSClipboard+{+ private const string ObjC = "/usr/lib/libobjc.dylib";++ /// <summary>+ /// The largest picture also put on the clipboard as itself, beside the file; a larger one goes as the file only,+ /// so the clipboard doesn't hold a copy of a huge file in memory.+ /// </summary>+ private const long PictureLimit = 64L << 20;++ private static readonly nint AppKit = NativeLibrary.Load("/System/Library/Frameworks/AppKit.framework/AppKit");++ /// <summary>+ /// The existing files copied to the clipboard, else its picture in the first of+ /// <see cref="PasteboardPaths.PictureTypes"/> it has; null for neither. Copied files that are gone give null, not+ /// the icon Finder puts beside them.+ /// </summary>+ internal static ClipboardContent? Read()+ {+ GC.KeepAlive(AppKit);+ using var pool = new AutoreleasePool();+ var pasteboard = GeneralPasteboard();+ if (Available(pasteboard, [PasteboardPaths.FileUrlType, PasteboardPaths.FilenamesType]) is not null)+ {+ var files = PasteboardPaths.FirstExisting(+ [+ () => MacOSServicesProvider.FileUrls(pasteboard),+ () => MacOSServicesProvider.Strings(Send(pasteboard, sel_registerName("propertyListForType:"), NSString(PasteboardPaths.FilenamesType))),+ ], PasteboardPaths.Exists);+ return files.Count > 0 ? ClipboardContent.OfFiles(files) : null;+ }++ if (Available(pasteboard, [.. PasteboardPaths.PictureTypes.Select(t => t.Type)]) is not { } type)+ return null;+ var bytes = Bytes(Send(pasteboard, sel_registerName("dataForType:"), NSString(type)));+ var extension = PasteboardPaths.PictureTypes.First(t => t.Type == type).Extension;+ return bytes is { Length: > 0 } ? ClipboardContent.OfPicture(bytes, extension) : null;+ }++ /// <summary>+ /// Replaces the clipboard with <paramref name="paths"/>, one item per file (its file URL); a single picture also+ /// carries its bytes under its own type, for apps that paste pictures but not files.+ /// </summary>+ internal static bool Write(IReadOnlyList<string> paths)+ {+ GC.KeepAlive(AppKit);+ if (paths.Count == 0)+ return false;+ using var pool = new AutoreleasePool();+ var items = Send(objc_getClass("NSMutableArray"), sel_registerName("array"));+ var fileUrlType = NSString(PasteboardPaths.FileUrlType);+ foreach (var path in paths.Select(Path.GetFullPath))+ {+ var item = Send(Send(objc_getClass("NSPasteboardItem"), sel_registerName("alloc")), sel_registerName("init"));+ var url = Send(objc_getClass("NSURL"), sel_registerName("fileURLWithPath:"), NSString(path));+ SendBool(item, sel_registerName("setString:forType:"), Send(url, sel_registerName("absoluteString")), fileUrlType);+ if (paths.Count == 1 && PasteboardPaths.PictureTypeOf(path) is { } type && new FileInfo(path).Length <= PictureLimit)+ {+ var data = Send(objc_getClass("NSData"), sel_registerName("dataWithContentsOfFile:"), NSString(path));+ if (data != 0)+ SendBool(item, sel_registerName("setData:forType:"), data, NSString(type));+ }+ SendVoid(items, sel_registerName("addObject:"), item);+ SendVoid(item, sel_registerName("release"));+ }+ var pasteboard = GeneralPasteboard();+ Send(pasteboard, sel_registerName("clearContents"));+ return SendBool(pasteboard, sel_registerName("writeObjects:"), items);+ }++ private static nint GeneralPasteboard() => Send(objc_getClass("NSPasteboard"), sel_registerName("generalPasteboard"));++ /// <summary>The first of <paramref name="types"/> the pasteboard has, or null.</summary>+ private static string? Available(nint pasteboard, IReadOnlyList<string> types)+ {+ var array = Send(objc_getClass("NSMutableArray"), sel_registerName("array"));+ foreach (var type in types)+ SendVoid(array, sel_registerName("addObject:"), NSString(type));+ var found = Send(pasteboard, sel_registerName("availableTypeFromArray:"), array);+ return found == 0 ? null : Marshal.PtrToStringUTF8(Send(found, sel_registerName("UTF8String")));+ }++ /// <summary>A copy of an NSData's bytes; null for nil.</summary>+ private static byte[]? Bytes(nint data)+ {+ if (data == 0)+ return null;+ var length = (int)Math.Min(Send(data, sel_registerName("length")), int.MaxValue);+ var bytes = new byte[length];+ if (length > 0)+ Marshal.Copy(Send(data, sel_registerName("bytes")), bytes, 0, length);+ return bytes;+ }++ /// <summary>An autoreleased NSString, released with the surrounding <see cref="AutoreleasePool"/>.</summary>+ private static nint NSString(string value)+ {+ var utf8 = Marshal.StringToCoTaskMemUTF8(value);+ try+ {+ return Send(objc_getClass("NSString"), sel_registerName("stringWithUTF8String:"), utf8);+ }+ finally+ {+ Marshal.FreeCoTaskMem(utf8);+ }+ }++ private readonly struct AutoreleasePool : IDisposable+ {+ private readonly nint _pool = Send(Send(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc")), sel_registerName("init"));+ public AutoreleasePool() { }+ public void Dispose() => SendVoid(_pool, sel_registerName("drain"));+ }++ [DllImport(ObjC)]+ private static extern nint objc_getClass([MarshalAs(UnmanagedType.LPUTF8Str)] string name);++ [DllImport(ObjC)]+ private static extern nint sel_registerName([MarshalAs(UnmanagedType.LPUTF8Str)] string name);++ [DllImport(ObjC, EntryPoint = "objc_msgSend")]+ private static extern nint Send(nint receiver, nint selector);++ [DllImport(ObjC, EntryPoint = "objc_msgSend")]+ private static extern nint Send(nint receiver, nint selector, nint argument);++ [DllImport(ObjC, EntryPoint = "objc_msgSend")]+ private static extern void SendVoid(nint receiver, nint selector);++ [DllImport(ObjC, EntryPoint = "objc_msgSend")]+ private static extern void SendVoid(nint receiver, nint selector, nint argument);++ [DllImport(ObjC, EntryPoint = "objc_msgSend")]+ [return: MarshalAs(UnmanagedType.I1)]+ private static extern bool SendBool(nint receiver, nint selector, nint argument);++ [DllImport(ObjC, EntryPoint = "objc_msgSend")]+ [return: MarshalAs(UnmanagedType.I1)]+ private static extern bool SendBool(nint receiver, nint selector, nint first, nint second);+}diff --git a/src/Filee.Platform.MacOS/MacOSPlatformServices.cs b/src/Filee.Platform.MacOS/MacOSPlatformServices.csindex a7a53a6b..30c923b9 100644--- a/src/Filee.Platform.MacOS/MacOSPlatformServices.cs+++ b/src/Filee.Platform.MacOS/MacOSPlatformServices.cs@@ -62,6 +62,12 @@ public sealed class MacOSPlatformServices : IPlatformServices}}+ public bool SupportsClipboard => true;++ public ClipboardContent? ReadClipboard() => MacOSClipboard.Read();++ public bool CopyToClipboard(IReadOnlyList<string> paths) => MacOSClipboard.Write(paths);+// AppKit exposes no public system drag-distance preference; match its usual four-point threshold.public int SystemDragThreshold => 4;diff --git a/src/Filee.Platform.MacOS/MacOSServicesProvider.cs b/src/Filee.Platform.MacOS/MacOSServicesProvider.csindex 495a1073..eacf362f 100644--- a/src/Filee.Platform.MacOS/MacOSServicesProvider.cs+++ b/src/Filee.Platform.MacOS/MacOSServicesProvider.cs@@ -82,7 +82,7 @@ public static class MacOSServicesProvider], PasteboardPaths.Exists);/// <summary>File URLs read as NSURL objects (AppKit resolves file reference URLs).</summary>- private static List<string> FileUrls(nint pasteboard)+ internal static List<string> FileUrls(nint pasteboard){var files = new List<string>();var classes = Send(objc_getClass("NSArray"), sel_registerName("arrayWithObject:"), objc_getClass("NSURL"));@@ -121,7 +121,7 @@ public static class MacOSServicesProvider}/// <summary>The strings in an NSArray (anything else in it is skipped); none for nil or any other object.</summary>- private static List<string> Strings(nint array)+ internal static List<string> Strings(nint array){var values = new List<string>();if (array == 0 || !SendBool(array, sel_registerName("isKindOfClass:"), objc_getClass("NSArray")))diff --git a/src/Filee.Platform.MacOS/PasteboardPaths.cs b/src/Filee.Platform.MacOS/PasteboardPaths.csindex 6def3e1f..96b342d4 100644--- a/src/Filee.Platform.MacOS/PasteboardPaths.cs+++ b/src/Filee.Platform.MacOS/PasteboardPaths.cs@@ -37,6 +37,31 @@ public static class PasteboardPaths"public.url", "public.html", "public.png", "public.jpeg", "public.tiff", "com.compuserve.gif", "org.webmproject.webp",];+ /// <summary>+ /// Picture types read from the clipboard, in order of preference, with the extension their bytes are saved under.+ /// A screenshot copied with Ctrl comes as PNG and TIFF: PNG first, TIFF (the largest) last.+ /// </summary>+ public static IReadOnlyList<(string Type, string Extension)> PictureTypes { get; } =+ [+ ("public.png", "png"), ("public.jpeg", "jpg"), ("public.heic", "heic"), ("org.webmproject.webp", "webp"),+ ("com.compuserve.gif", "gif"), ("public.tiff", "tiff"),+ ];++ /// <summary>+ /// The pasteboard type of the picture at <paramref name="path"/>, by its extension, for pasting it as itself; null+ /// for anything else.+ /// </summary>+ public static string? PictureTypeOf(string path)+ {+ var extension = Path.GetExtension(path).TrimStart('.').ToLowerInvariant() switch+ {+ "jpeg" or "jpe" => "jpg",+ "tif" => "tiff",+ var other => other,+ };+ return PictureTypes.FirstOrDefault(t => t.Extension == extension).Type;+ }+/// <summary>Whether <paramref name="type"/> names NSFilenamesPboardType, by its name or its dynamic UTI.</summary>public static bool IsFilenamesType(string type) => type is FilenamesType or FilenamesUti;diff --git a/tests/Filee.App.Tests/ClipboardShortcutTests.cs b/tests/Filee.App.Tests/ClipboardShortcutTests.csnew file mode 100644index 00000000..f5efa693--- /dev/null+++ b/tests/Filee.App.Tests/ClipboardShortcutTests.cs@@ -0,0 +1,53 @@+// The clipboard switch of a keyboard shortcut on the Shortcuts page, and Shift + Cmd + V reaching the detector.++using Filee.App.Services.Triggers;+using Filee.App.ViewModels.Pages;+using Filee.Core.Settings;++namespace Filee.App.Tests;++public class ClipboardShortcutTests+{+ [Fact]+ public void Only_a_keyboard_shortcut_where_the_clipboard_can_be_read_offers_the_switch()+ {+ var shortcut = new TriggerGestureViewModel(TriggerGesture.ClipboardShortcut(), new KeyLocalizer(), () => { }, clipboardAvailable: true);+ Assert.True(shortcut.UsesClipboard);+ Assert.True(shortcut.Clipboard);++ var drag = new TriggerGestureViewModel(new TriggerGesture { Kind = TriggerKind.Drag }, new KeyLocalizer(), () => { }, clipboardAvailable: true);+ Assert.False(drag.UsesClipboard);++ var elsewhere = new TriggerGestureViewModel(TriggerGesture.ClipboardShortcut(), new KeyLocalizer(), () => { });+ Assert.False(elsewhere.UsesClipboard);+ }++ [Fact]+ public void Switching_it_saves_the_shortcut()+ {+ var gesture = new TriggerGesture { Kind = TriggerKind.KeyChord, Modifiers = ModifierKeys.Ctrl | ModifierKeys.Alt, Key = "Space" };+ var saves = 0;+ var vm = new TriggerGestureViewModel(gesture, new KeyLocalizer(), () => saves++, clipboardAvailable: true);++ vm.Clipboard = true;++ Assert.True(gesture.Clipboard);+ Assert.Equal(1, saves);+ }++ [Fact]+ public void Shift_cmd_v_fires_the_clipboard_shortcut()+ {+ var detector = new GestureDetector();+ detector.Configure([TriggerGesture.ClipboardShortcut()]);+ TriggerGesture? fired = null;+ detector.KeyChordTriggered += (g, _, _) => fired = g;++ detector.KeyDown("V", ModifierKeys.Meta);+ Assert.Null(fired);+ detector.KeyDown("V", ModifierKeys.Shift | ModifierKeys.Meta);++ Assert.NotNull(fired);+ Assert.True(fired.Clipboard);+ }+}diff --git a/tests/Filee.Core.Tests/ClipboardShortcutTests.cs b/tests/Filee.Core.Tests/ClipboardShortcutTests.csnew file mode 100644index 00000000..a021d464--- /dev/null+++ b/tests/Filee.Core.Tests/ClipboardShortcutTests.cs@@ -0,0 +1,69 @@+// The clipboard shortcut (Shift + Cmd + V on macOS, settings schema 55): converts what is on the clipboard and puts the+// result back.++using System.Text.Json.Nodes;+using Filee.Core.Settings;++namespace Filee.Core.Tests;++public class ClipboardShortcutTests+{+ [Fact]+ public void The_clipboard_shortcut_is_shift_cmd_v_everywhere()+ {+ var shortcut = TriggerGesture.ClipboardShortcut();++ Assert.Equal(TriggerKind.KeyChord, shortcut.Kind);+ Assert.Equal(ModifierKeys.Shift | ModifierKeys.Meta, shortcut.Modifiers);+ Assert.Equal("V", shortcut.Key);+ Assert.Equal(TriggerScope.Anywhere, shortcut.Scope);+ Assert.True(shortcut.Clipboard);+ Assert.True(shortcut.Clone().Clipboard);+ }++ [Fact]+ public void Only_macos_gets_it_by_default()+ {+ Assert.Equal(OperatingSystem.IsMacOS(), TriggerGesture.Defaults().Any(g => g.Clipboard));+ }++ [Fact]+ public void An_upgrade_adds_it_once()+ {+ var triggers = TriggerGesture.Defaults().Where(g => !g.Clipboard).ToList();++ Assert.True(SettingsMigrations.AddClipboardShortcut(triggers));+ Assert.False(SettingsMigrations.AddClipboardShortcut(triggers));+ Assert.Single(triggers, g => g.Clipboard);+ }++ [Fact]+ public void A_shortcut_of_the_users_own_on_those_keys_stays_as_it_is()+ {+ var own = new TriggerGesture+ {+ Kind = TriggerKind.KeyChord, Modifiers = ModifierKeys.Shift | ModifierKeys.Meta, Key = "v", Button = TriggerMouseButton.None,+ };+ List<TriggerGesture> triggers = [own];++ Assert.False(SettingsMigrations.AddClipboardShortcut(triggers));+ Assert.Same(own, Assert.Single(triggers));+ Assert.False(own.Clipboard);+ }++ [Fact]+ public void The_option_is_saved_and_read_back()+ {+ using var dir = new TempDir();+ var store = new UserDataStore(dir.Path);+ store.Load();+ store.Settings.Triggers = [TriggerGesture.ClipboardShortcut()];+ store.SaveSettings();++ var json = JsonNode.Parse(File.ReadAllText(Path.Combine(dir.Path, "settings.json")))!;+ Assert.True(json["triggers"]![0]!["clipboard"]!.GetValue<bool>());+ var again = new UserDataStore(dir.Path);+ again.Load();+ Assert.True(Assert.Single(again.Settings.Triggers).Clipboard);+ }+}diff --git a/tests/Filee.Platform.Tests/PasteboardPathsTests.cs b/tests/Filee.Platform.Tests/PasteboardPathsTests.csindex fcf3db2a..d5b2f038 100644--- a/tests/Filee.Platform.Tests/PasteboardPathsTests.cs+++ b/tests/Filee.Platform.Tests/PasteboardPathsTests.cs@@ -97,4 +97,25 @@ public sealed class PasteboardPathsTestsAssert.Contains(PasteboardPaths.FilenamesType, PasteboardPaths.DragTypes);Assert.Contains(PasteboardPaths.FileUrlType, PasteboardPaths.DragTypes);}++ [Fact]+ public void AScreenshotOnTheClipboardIsReadAsPngBeforeTiff()+ {+ var types = PasteboardPaths.PictureTypes.Select(t => t.Type).ToList();++ Assert.Equal("public.png", types[0]);+ Assert.Equal("public.tiff", types[^1]);+ Assert.Equal(types.Count, types.Distinct().Count());+ }++ [Theory]+ [InlineData("/Users/a/shot_compressed.png", "public.png")]+ [InlineData("/Users/a/shot.JPEG", "public.jpeg")]+ [InlineData("/Users/a/shot.jpg", "public.jpeg")]+ [InlineData("/Users/a/shot.webp", "org.webmproject.webp")]+ [InlineData("/Users/a/scan.tif", "public.tiff")]+ [InlineData("/Users/a/report.pdf", null)]+ [InlineData("/Users/a/no-extension", null)]+ public void AConvertedPictureGoesOnTheClipboardUnderItsOwnType(string path, string? type) =>+ Assert.Equal(type, PasteboardPaths.PictureTypeOf(path));}