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
Fix Windows triggers: record Space, desktop selection, Hold next to Drag, shortcut scope by focus
KnifeLemond894d7815bf4
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.jsonindex 7350a25e..ab53dd93 100644--- a/src/Filee.App/Assets/i18n/ar.json+++ b/src/Filee.App/Assets/i18n/ar.json@@ -260,6 +260,7 @@"general.integration_macos": "يظهر الخيار في قائمة النقر بالزر الأيمن في Finder (ضمن الإجراءات السريعة أو الخدمات إذا كانت القائمة طويلة).\nأبقِ Filee في مجلد التطبيقات.","general.integration_linux": "إضافة إجراءات الملفات إلى Thunar وNautilus وNemo وDolphin.\nلتغيير اختصار Thunar، أغلقه أولًا ثم أعد فتحه.","general.integration_failed": "تعذّر تطبيق التكامل مع النظام: {0}",+ "general.startup_entry_missing": "حُذف إدخال التشغيل عند تسجيل الدخول أو تغيّر فور حفظه. ربما يحظره برنامج حماية.","general.modern_menu_hint": "في Windows 11، يظهر هذا الخيار ضمن «إظهار المزيد من الخيارات».\nيمكن إضافته إلى القائمة الرئيسية أيضًا (يطلب Windows صلاحيات المسؤول مرة واحدة).","general.modern_menu_on": "«تحويل باستخدام Filee» موجود في القائمة الرئيسية لـ Windows 11.","general.modern_menu_outdated": "يرتبط خيار القائمة الرئيسية بنسخة قديمة من Filee أو نُقلت من مكانها.\nأضفه مجددًا لتحديثه.",diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex d6da2e01..411f3eed 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -272,6 +272,7 @@"general.integration_macos": "Finder shows it in the right-click menu (under Quick Actions or Services when the menu is long).\nKeep Filee in Applications.","general.integration_linux": "Adds file actions to Thunar, Nautilus, Nemo and Dolphin.\nTo change Thunar's shortcut, close Thunar first and reopen it afterwards.","general.integration_failed": "Could not apply system integration: {0}",+ "general.startup_entry_missing": "The sign-in entry was removed or changed right after it was saved. Security software may be blocking it.","general.modern_menu_hint": "On Windows 11 this entry is under “Show more options”.\nIt can also go in the main menu (Windows asks for administrator permission once).","general.modern_menu_on": "“Convert with Filee” is in the main Windows 11 menu.","general.modern_menu_outdated": "The main-menu entry belongs to an older or moved copy of Filee.\nAdd it again to update it.",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex 46d0a29d..ec331cd3 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -260,6 +260,7 @@"general.integration_macos": "Finder lo muestra en el menú contextual (en Acciones rápidas o Servicios si el menú es largo).\nMantén Filee en Aplicaciones.","general.integration_linux": "Añade acciones de archivos a Thunar, Nautilus, Nemo y Dolphin.\nPara cambiar el atajo de Thunar, cierra Thunar antes y vuelve a abrirlo después.","general.integration_failed": "No se pudo aplicar la integración con el sistema: {0}",+ "general.startup_entry_missing": "La entrada de inicio de sesión se eliminó o cambió justo después de guardarse. Puede que un software de seguridad la esté bloqueando.","general.modern_menu_hint": "En Windows 11 esta entrada está en «Mostrar más opciones».\nTambién puede ir al menú principal (Windows pide permiso de administrador una sola vez).","general.modern_menu_on": "«Convertir con Filee» está en el menú principal de Windows 11.","general.modern_menu_outdated": "La entrada del menú principal pertenece a una copia antigua de Filee o a una que cambió de carpeta.\nAñádela otra vez para actualizarla.",diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.jsonindex 5e3a7d67..5fa7f56d 100644--- a/src/Filee.App/Assets/i18n/fr.json+++ b/src/Filee.App/Assets/i18n/fr.json@@ -272,6 +272,7 @@"general.integration_macos": "Le Finder l'affiche dans le menu contextuel (sous Actions rapides ou Services si le menu est long).\nGardez Filee dans le dossier Applications.","general.integration_linux": "Ajoute des actions sur les fichiers à Thunar, Nautilus, Nemo et Dolphin.\nPour changer le raccourci de Thunar, fermez d'abord Thunar, puis rouvrez-le ensuite.","general.integration_failed": "Impossible d'appliquer l'intégration au système : {0}",+ "general.startup_entry_missing": "L'entrée de démarrage a été supprimée ou modifiée juste après son enregistrement. Un logiciel de sécurité la bloque peut-être.","general.modern_menu_hint": "Sous Windows 11, cette entrée se trouve dans « Afficher d'autres options ».\nElle peut aussi aller dans le menu principal (Windows demande une seule fois l'autorisation administrateur).","general.modern_menu_on": "« Convertir avec Filee » est dans le menu principal de Windows 11.","general.modern_menu_outdated": "L'entrée du menu principal appartient à une copie de Filee plus ancienne ou déplacée.\nAjoutez-la à nouveau pour la mettre à jour.",diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.jsonindex ee9731ca..6feb9be9 100644--- a/src/Filee.App/Assets/i18n/hi.json+++ b/src/Filee.App/Assets/i18n/hi.json@@ -260,6 +260,7 @@"general.integration_macos": "Finder इसे राइट-क्लिक मेनू में दिखाता है (मेनू लंबा होने पर Quick Actions या Services के अंदर)।\nFilee को Applications में रखें।","general.integration_linux": "Thunar, Nautilus, Nemo और Dolphin में फ़ाइल एक्शन जोड़ता है।\nThunar का शॉर्टकट बदलने के लिए पहले Thunar बंद करें और बाद में दोबारा खोलें।","general.integration_failed": "सिस्टम इंटीग्रेशन लागू नहीं हो सका: {0}",+ "general.startup_entry_missing": "साइन-इन पर शुरू होने वाली एंट्री सहेजते ही हटा दी गई या बदल दी गई। हो सकता है कोई सुरक्षा सॉफ़्टवेयर इसे रोक रहा हो।","general.modern_menu_hint": "Windows 11 में यह एंट्री “और विकल्प दिखाएँ” के अंदर होती है।\nइसे मुख्य मेनू में भी रखा जा सकता है (Windows एक बार एडमिनिस्ट्रेटर अनुमति माँगता है)।","general.modern_menu_on": "“Filee से कन्वर्ट करें” Windows 11 के मुख्य मेनू में है।","general.modern_menu_outdated": "मुख्य मेनू की एंट्री Filee की किसी पुरानी या हटाई गई कॉपी की है।\nइसे अपडेट करने के लिए दोबारा जोड़ें।",diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.jsonindex 9ebf86df..4d7675a0 100644--- a/src/Filee.App/Assets/i18n/ja.json+++ b/src/Filee.App/Assets/i18n/ja.json@@ -260,6 +260,7 @@"general.integration_macos": "Finderの右クリックメニューに表示されます(メニューが長い場合は「クイックアクション」または「サービス」の中にあります)。\nFileeは「アプリケーション」フォルダーに置いてください。","general.integration_linux": "Thunar、Nautilus、Nemo、Dolphinにファイル操作を追加します。\nThunarのショートカットを変更するときは、先にThunarを閉じ、変更後に開き直してください。","general.integration_failed": "システム連携を適用できませんでした:{0}",+ "general.startup_entry_missing": "サインイン時の起動設定が保存直後に削除または変更されました。セキュリティソフトがブロックしている可能性があります。","general.modern_menu_hint": "Windows 11では、この項目は「その他のオプションを確認」の中にあります。\nメインメニューに追加することもできます(管理者の許可が一度必要です)。","general.modern_menu_on": "「Fileeで変換」はWindows 11のメインメニューに表示されています。","general.modern_menu_outdated": "メインメニューの項目は、古いバージョンのFileeか、移動前のFileeに紐づいています。\n項目を更新するには、もう一度追加してください。",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 0ed433f0..b89d8064 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -272,6 +272,7 @@"general.integration_macos": "Finder 우클릭 메뉴에 나타나요(메뉴가 길면 빠른 동작 또는 서비스 안에).\nFilee는 응용 프로그램 폴더에 두세요.","general.integration_linux": "Thunar, Nautilus, Nemo, Dolphin에 파일 동작을 추가해요.\nThunar 단축키를 바꿀 때는 Thunar를 닫았다가 적용한 뒤 다시 열어 주세요.","general.integration_failed": "시스템 연동을 적용하지 못했어요: {0}",+ "general.startup_entry_missing": "로그인 시작 항목이 저장하자마자 지워지거나 바뀌었어요. 보안 프로그램이 막고 있을 수 있어요.","general.modern_menu_hint": "Windows 11에서는 “추가 옵션 표시” 안에 있어요.\n기본 메뉴에도 넣을 수 있어요(관리자 권한을 한 번 요청해요).","general.modern_menu_on": "“Filee로 변환”이 Windows 11 기본 메뉴에 있어요.","general.modern_menu_outdated": "기본 메뉴 항목이 이전 버전이나 다른 위치의 Filee를 가리키고 있어요.\n다시 추가하면 업데이트돼요.",diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.jsonindex b94e0043..b8da2f87 100644--- a/src/Filee.App/Assets/i18n/ne.json+++ b/src/Filee.App/Assets/i18n/ne.json@@ -260,6 +260,7 @@"general.integration_macos": "Finder ले यसलाई दायाँ-क्लिक मेनुमा देखाउँछ (मेनु लामो हुँदा Quick Actions वा Services भित्र)।\nFilee लाई Applications मा राख्नुहोस्।","general.integration_linux": "Thunar, Nautilus, Nemo र Dolphin मा फाइल कार्यहरू थप्छ।\nThunar को सर्टकट परिवर्तन गर्न, पहिले Thunar बन्द गर्नुहोस् र पछि पुन: खोल्नुहोस्।","general.integration_failed": "प्रणाली एकीकरण लागू गर्न सकिएन: {0}",+ "general.startup_entry_missing": "साइन इन गर्दा सुरु हुने प्रविष्टि सेभ गरेलगत्तै हटाइयो वा बदलियो। सुरक्षा सफ्टवेयरले यसलाई रोकिरहेको हुन सक्छ।","general.modern_menu_hint": "Windows 11 मा यो प्रविष्टि “थप विकल्पहरू देखाउनुहोस्” अन्तर्गत हुन्छ।\nयसलाई मुख्य मेनुमा पनि राख्न सकिन्छ (Windows ले एक पटक प्रशासक अनुमति माग्छ)।","general.modern_menu_on": "“Filee मार्फत रूपान्तरण गर्नुहोस्” मुख्य Windows 11 मेनुमा छ।","general.modern_menu_outdated": "मुख्य मेनुको प्रविष्टि Filee को पुरानो वा सारिएको प्रतिलिपिसँग सम्बन्धित छ।\nयसलाई अपडेट गर्न पुन: थप्नुहोस्।",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 6dfe83f6..bd0cdcc8 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -272,6 +272,7 @@"general.integration_macos": "Finder pokazuje to w menu prawego przycisku (w Szybkich czynnościach lub Usługach, gdy menu jest długie).\nTrzymaj Filee w Aplikacjach.","general.integration_linux": "Dodaje akcje plików do Thunara, Nautilusa, Nemo i Dolphina.\nAby zmienić skrót w Thunarze, najpierw zamknij Thunara, a potem otwórz go ponownie.","general.integration_failed": "Nie udało się zastosować integracji z systemem: {0}",+ "general.startup_entry_missing": "Wpis uruchamiania po zalogowaniu został usunięty lub zmieniony zaraz po zapisaniu. Może go blokować oprogramowanie zabezpieczające.","general.modern_menu_hint": "W Windows 11 ta pozycja jest w „Pokaż więcej opcji”.\nMoże też trafić do głównego menu (Windows raz poprosi o uprawnienia administratora).","general.modern_menu_on": "„Konwertuj w Filee” jest w głównym menu Windows 11.","general.modern_menu_outdated": "Pozycja w głównym menu należy do starszej lub przeniesionej kopii Filee.\nDodaj ją ponownie, aby ją zaktualizować.",diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.jsonindex de22e05e..3bfb9aa5 100644--- a/src/Filee.App/Assets/i18n/pt-BR.json+++ b/src/Filee.App/Assets/i18n/pt-BR.json@@ -272,6 +272,7 @@"general.integration_macos": "O Finder mostra no menu do botão direito (em Ações rápidas ou Serviços quando o menu é longo).\nMantenha o Filee em Aplicativos.","general.integration_linux": "Adiciona ações de arquivo ao Thunar, Nautilus, Nemo e Dolphin.\nPara mudar o atalho do Thunar, feche o Thunar antes e abra de novo depois.","general.integration_failed": "Não foi possível aplicar a integração com o sistema: {0}",+ "general.startup_entry_missing": "A entrada de inicialização foi removida ou alterada logo depois de ser salva. Um software de segurança pode estar bloqueando.","general.modern_menu_hint": "No Windows 11 esta entrada fica em “Mostrar mais opções”.\nTambém pode ir no menu principal (o Windows pede permissão de administrador uma vez).","general.modern_menu_on": "“Converter com o Filee” está no menu principal do Windows 11.","general.modern_menu_outdated": "A entrada do menu principal pertence a uma cópia antiga ou movida do Filee.\nAdicione de novo para atualizá-la.",diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.jsonindex fdef315d..257e8694 100644--- a/src/Filee.App/Assets/i18n/ru.json+++ b/src/Filee.App/Assets/i18n/ru.json@@ -272,6 +272,7 @@"general.integration_macos": "Finder показывает пункт в меню по правой кнопке (в «Быстрых действиях» или «Службах», если меню длинное).\nДержите Filee в папке «Программы».","general.integration_linux": "Добавляет действия с файлами в Thunar, Nautilus, Nemo и Dolphin.\nЧтобы изменить сочетание клавиш для Thunar, сначала закройте Thunar, а потом откройте его снова.","general.integration_failed": "Не удалось встроиться в систему: {0}",+ "general.startup_entry_missing": "Запись автозапуска была удалена или изменена сразу после сохранения. Возможно, её блокирует защитное ПО.","general.modern_menu_hint": "В Windows 11 этот пункт находится в «Показать дополнительные параметры».\nЕго можно добавить и в основное меню (Windows один раз попросит права администратора).","general.modern_menu_on": "«Конвертировать с помощью Filee» есть в основном меню Windows 11.","general.modern_menu_outdated": "Пункт в основном меню относится к старой или перемещённой копии Filee.\nДобавьте его снова, чтобы обновить.",diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.jsonindex dafee331..a6ad1cfd 100644--- a/src/Filee.App/Assets/i18n/th.json+++ b/src/Filee.App/Assets/i18n/th.json@@ -260,6 +260,7 @@"general.integration_macos": "Finder จะแสดงในเมนูคลิกขวา (ใต้ Quick Actions หรือ Services เมื่อเมนูยาว)\nควรเก็บ Filee ไว้ในโฟลเดอร์ Applications","general.integration_linux": "เพิ่มการดำเนินการไฟล์ใน Thunar, Nautilus, Nemo และ Dolphin\nหากต้องการเปลี่ยนปุ่มลัดของ Thunar ให้ปิด Thunar ก่อนแล้วเปิดใหม่หลังจากนั้น","general.integration_failed": "ไม่สามารถตั้งค่าการเชื่อมต่อกับระบบได้: {0}",+ "general.startup_entry_missing": "รายการเปิดอัตโนมัติเมื่อเข้าสู่ระบบถูกลบหรือเปลี่ยนทันทีหลังบันทึก ซอฟต์แวร์ความปลอดภัยอาจบล็อกอยู่","general.modern_menu_hint": "บน Windows 11 รายการนี้จะอยู่ใต้ “แสดงตัวเลือกเพิ่มเติม” (Show more options)\nและสามารถนำไปไว้ในเมนูหลักได้เช่นกัน (Windows จะขอสิทธิ์ผู้ดูแลระบบหนึ่งครั้ง)","general.modern_menu_on": "“แปลงไฟล์ด้วย Filee” อยู่ในเมนูหลักของ Windows 11 แล้ว","general.modern_menu_outdated": "รายการในเมนูหลักเป็นของ Filee รุ่นเก่าหรือถูกย้ายตำแหน่ง\nโปรดเพิ่มใหม่อีกครั้งเพื่ออัปเดต",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex 04342f28..25b43e43 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -272,6 +272,7 @@"general.integration_macos": "Finder 的右键菜单中会出现此项(菜单较长时在“快速操作”或“服务”中)。\n请将 Filee 保留在“应用程序”文件夹中。","general.integration_linux": "为 Thunar、Nautilus、Nemo 和 Dolphin 添加文件操作。\n修改 Thunar 快捷键前请先关闭 Thunar,之后再重新打开。","general.integration_failed": "无法应用系统集成:{0}",+ "general.startup_entry_missing": "登录启动项在保存后立即被删除或更改。可能是安全软件阻止了它。","general.modern_menu_hint": "在 Windows 11 中,此项位于“显示更多选项”里。\n也可以添加到主菜单(Windows 会请求一次管理员权限)。","general.modern_menu_on": "“用 Filee 转换”已在 Windows 11 主菜单中。","general.modern_menu_outdated": "主菜单中的此项属于旧版本或其他位置的 Filee。\n重新添加即可更新。",diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.jsonindex f63d6a08..961a64ee 100644--- a/src/Filee.App/Assets/i18n/zh-TW.json+++ b/src/Filee.App/Assets/i18n/zh-TW.json@@ -272,6 +272,7 @@"general.integration_macos": "Finder 的右鍵選單中會出現此項目(選單較長時在「快速動作」或「服務」中)。\n請將 Filee 保留在「應用程式」資料夾中。","general.integration_linux": "為 Thunar、Nautilus、Nemo 和 Dolphin 新增檔案操作。\n修改 Thunar 快速鍵前請先關閉 Thunar,之後再重新開啟。","general.integration_failed": "無法套用系統整合:{0}",+ "general.startup_entry_missing": "登入啟動項目在儲存後立即被移除或變更。可能是安全軟體封鎖了它。","general.modern_menu_hint": "在 Windows 11 中,此項目位於「顯示更多選項」裡。\n也可以新增到主選單(Windows 會請求一次系統管理員權限)。","general.modern_menu_on": "「用 Filee 轉換」已在 Windows 11 主選單中。","general.modern_menu_outdated": "主選單中的此項目屬於舊版本或其他位置的 Filee。\n重新新增即可更新。",diff --git a/src/Filee.App/Services/SystemIntegrationService.cs b/src/Filee.App/Services/SystemIntegrationService.csindex a2097700..f22375b9 100644--- a/src/Filee.App/Services/SystemIntegrationService.cs+++ b/src/Filee.App/Services/SystemIntegrationService.cs@@ -67,6 +67,13 @@ public sealed class SystemIntegrationService(IPlatformServices platform, ILocalibool ApplyOne(Action action){try { action(); return true; }+ catch (StartupEntryNotKeptException ex)+ {+ // Security software took the entry away (#450): one line, and the switch says it in the user's language.+ log.LogWarning("Start with the system did not stay on: {Detail}", ex.Message);+ errors.Add(loc["general.startup_entry_missing"]);+ return false;+ }catch (Exception ex) when (ex is not OutOfMemoryException){log.LogWarning(ex, "Could not update system integration");diff --git a/src/Filee.App/Services/Triggers/GestureDetector.cs b/src/Filee.App/Services/Triggers/GestureDetector.csindex 6b0f60de..af433e43 100644--- a/src/Filee.App/Services/Triggers/GestureDetector.cs+++ b/src/Filee.App/Services/Triggers/GestureDetector.cs@@ -4,7 +4,9 @@// Drag gesture: button down with the exact modifiers → (armed) → moved past threshold → DragStarted// → button up → DragEnded// Hold gesture: button down with modifiers → (armed) → HoldElapsed without moving → HoldTriggered+// Drag and Hold on the same button and modifiers arm together: moving past the threshold drags, holding still holds.// Key chord: key down with the exact modifiers → KeyChordTriggered at the last known cursor position+// (the scope filter judges a key chord by the window in front, not by the cursor)using Filee.Core.Settings;@@ -17,10 +19,11 @@ public sealed class GestureDetectorprivate IReadOnlyList<TriggerGesture> _gestures = [];private Armed? _armed;private bool _dragActive;- private bool _lateRejected; // scope check failed for this drag; don't re-check on every move+ private bool _lateRejected; // no late-modifier drag for this press: its scope failed, or a hold already firedprivate int _lastX, _lastY;- private sealed record Armed(TriggerGesture Gesture, TriggerMouseButton Button, int X, int Y, long Token);+ /// <summary>A press that may still become a drag, a hold, or both until one of them happens.</summary>+ private sealed record Armed(TriggerGesture? Drag, TriggerGesture? Hold, int X, int Y, long Token);/// <summary>/// Decides whether a gesture may start at a screen point (scope / excluded apps / own windows).@@ -64,23 +67,25 @@ public sealed class GestureDetectorif (Paused)return;- var gesture = _gestures.FirstOrDefault(g =>- g.Kind is TriggerKind.Drag or TriggerKind.Hold &&- g.Button == button &&- g.Modifiers == modifiers);- if (gesture is null || !ScopeFilter(gesture, x, y))+ // A drag and a hold may share the button and modifiers (#450): both are armed, and what the pointer does+ // next decides between them.+ var drag = FirstInScope(TriggerKind.Drag, button, modifiers, x, y);+ holdGesture = FirstInScope(TriggerKind.Hold, button, modifiers, x, y);+ if (drag is null && holdGesture is null)return;token = Environment.TickCount64 ^ (x * 7919L) ^ y;- _armed = new Armed(gesture, button, x, y, token);- if (gesture.Kind == TriggerKind.Hold)- holdGesture = gesture;+ _armed = new Armed(drag, holdGesture, x, y, token);}if (holdGesture is not null)HoldTimerRequested?.Invoke(token, holdGesture.HoldMilliseconds);}+ /// <summary>The first gesture of a kind on this button and modifiers that may start here. Caller holds the lock.</summary>+ private TriggerGesture? FirstInScope(TriggerKind kind, TriggerMouseButton button, ModifierKeys modifiers, int x, int y) =>+ _gestures.FirstOrDefault(g => g.Kind == kind && g.Button == button && g.Modifiers == modifiers && ScopeFilter(g, x, y));+/// <summary>Pointer moved (physical pixels). <paramref name="heldButton"/> is the button currently held, or None.</summary>public void MouseMove(int x, int y, ModifierKeys modifiers, TriggerMouseButton heldButton = TriggerMouseButton.None){@@ -99,18 +104,26 @@ public sealed class GestureDetector}/// <summary>- /// An armed gesture moved: a drag gesture fires once the threshold is passed; a hold gesture is cancelled.- /// Caller holds the lock.+ /// An armed press moved: past its threshold a hold is cancelled, and a drag fires. Caller holds the lock./// </summary>private TriggerGesture? DetectDragPastThreshold(int x, int y){var armed = _armed!;- var threshold = armed.Gesture.DragThreshold > 0 ? armed.Gesture.DragThreshold : SystemDragThreshold;- if (Math.Abs(x - armed.X) <= threshold && Math.Abs(y - armed.Y) <= threshold)- return null;+ if (armed.Hold is { } hold && Moved(hold, armed, x, y))+ armed = armed with { Hold = null };+ if (armed.Drag is { } drag && Moved(drag, armed, x, y))+ {+ _armed = null;+ return drag;+ }+ _armed = armed.Drag is null && armed.Hold is null ? null : armed;+ return null;+ }- _armed = null;- return armed.Gesture.Kind == TriggerKind.Drag ? armed.Gesture : null;+ private bool Moved(TriggerGesture gesture, Armed armed, int x, int y)+ {+ var threshold = gesture.DragThreshold > 0 ? gesture.DragThreshold : SystemDragThreshold;+ return Math.Abs(x - armed.X) > threshold || Math.Abs(y - armed.Y) > threshold;}/// <summary>@@ -155,11 +168,12 @@ public sealed class GestureDetectorint x = 0, y = 0;lock (_lock){- if (_armed is { } armed && armed.Token == token && armed.Gesture.Kind == TriggerKind.Hold)+ if (_armed is { Hold: { } hold } armed && armed.Token == token){- fire = armed.Gesture;+ fire = hold;(x, y) = (armed.X, armed.Y);_armed = null;+ _lateRejected = true; // moving on after the hold doesn't start the drag that shares its modifiers}}if (fire is not null)@@ -175,13 +189,13 @@ public sealed class GestureDetector{if (Paused)return;+ (x, y) = (_lastX, _lastY);+ // Two shortcuts on one key (one per scope, say): the first whose scope fits fires.fire = _gestures.FirstOrDefault(g =>g.Kind == TriggerKind.KeyChord &&string.Equals(g.Key, key, StringComparison.OrdinalIgnoreCase) &&- g.Modifiers == modifiers);- (x, y) = (_lastX, _lastY);- if (fire is not null && !ScopeFilter(fire, x, y))- fire = null;+ g.Modifiers == modifiers &&+ ScopeFilter(g, x, y));}if (fire is not null)KeyChordTriggered?.Invoke(fire, x, y);diff --git a/src/Filee.App/Services/Triggers/TriggerService.cs b/src/Filee.App/Services/Triggers/TriggerService.csindex 95848e02..177c2c34 100644--- a/src/Filee.App/Services/Triggers/TriggerService.cs+++ b/src/Filee.App/Services/Triggers/TriggerService.cs@@ -265,12 +265,15 @@ public sealed class TriggerService : IDisposableinternal bool InScope(TriggerGesture gesture, int x, int y){- var process = _platform.ProcessNameAt(x, y);+ // A keyboard shortcut goes to the window in front, wherever the pointer is (over the taskbar, say: #450).+ // Mouse gestures go by the window under the pointer.+ var front = gesture.Kind == TriggerKind.KeyChord ? _platform.GetForegroundWindow() : null;+ var process = front is null ? _platform.ProcessNameAt(x, y) : front.ProcessName;if (Trace)- _log.LogInformation("Trace: {Gesture} at {X},{Y} over {Process}", gesture.Kind, x, y, process ?? "(none)");+ _log.LogInformation("Trace: {Gesture} at {X},{Y} {Where} {Process}", gesture.Kind, x, y, front is null ? "over" : "in front:", process ?? "(none)");if (process is not null && (string.Equals(process, _ownProcess, StringComparison.OrdinalIgnoreCase) || _excluded.Contains(process)))return false;- return gesture.Scope == TriggerScope.Anywhere || _platform.IsFileManagerAt(x, y)+ return gesture.Scope == TriggerScope.Anywhere || (front?.IsFileManager ?? _platform.IsFileManagerAt(x, y))// A picture or link dragged out of a web page opens the donut like a file.|| gesture.Kind == TriggerKind.Drag && WebBrowsers.IsBrowser(process);}diff --git a/src/Filee.App/Views/Pages/TriggersPage.axaml b/src/Filee.App/Views/Pages/TriggersPage.axamlindex 28bb1025..b88bec07 100644--- a/src/Filee.App/Views/Pages/TriggersPage.axaml+++ b/src/Filee.App/Views/Pages/TriggersPage.axaml@@ -85,7 +85,7 @@<Border Classes="badge" MinWidth="120" Padding="12,6"><TextBlock Text="{Binding KeyText}" FontWeight="SemiBold" /></Border>- <ToggleButton IsChecked="{Binding IsRecording}" KeyDown="OnRecorderKeyDown">+ <ToggleButton Classes="recorder" IsChecked="{Binding IsRecording}"><StackPanel Orientation="Horizontal" Spacing="6"><PathIcon Width="12" Height="12" Data="{StaticResource Icon.Record}" Foreground="{DynamicResource DangerBrush}" /><TextBlock Text="{Binding RecordLabel}" />@@ -129,7 +129,7 @@<Border Classes="badge" MinWidth="120" Padding="12,6"><TextBlock Text="{Binding KeyText}" FontWeight="SemiBold" /></Border>- <ToggleButton x:Name="FlipRecorder" IsChecked="{Binding IsRecording}" KeyDown="OnFlipRecorderKeyDown">+ <ToggleButton x:Name="FlipRecorder" IsChecked="{Binding IsRecording}"><StackPanel Orientation="Horizontal" Spacing="6"><PathIcon Width="12" Height="12" Data="{StaticResource Icon.Record}" Foreground="{DynamicResource DangerBrush}" /><TextBlock Text="{DynamicResource triggers.record}" />diff --git a/src/Filee.App/Views/Pages/TriggersPage.axaml.cs b/src/Filee.App/Views/Pages/TriggersPage.axaml.csindex a7e97058..a3fc8ea3 100644--- a/src/Filee.App/Views/Pages/TriggersPage.axaml.cs+++ b/src/Filee.App/Views/Pages/TriggersPage.axaml.cs@@ -1,25 +1,52 @@+using Avalonia;using Avalonia.Controls;using Avalonia.Controls.Primitives;using Avalonia.Input;+using Avalonia.Interactivity;+using Avalonia.VisualTree;using Filee.App.ViewModels.Pages;namespace Filee.App.Views.Pages;public partial class TriggersPage : UserControl{- public TriggersPage() => InitializeComponent();+ /// <summary>The key a recorder just took: its release is kept from the button too.</summary>+ private Key? _recordedKey;- /// <summary>While "Record" is on, the next key combination pressed on the button becomes the shortcut.</summary>+ public TriggersPage()+ {+ InitializeComponent();+ // Tunnel, so the recorder sees the key before the focused button does (#450): a button takes Space and Enter+ // for itself, and on Space's release it clicked, which switched recording off and kept the old shortcut.+ AddHandler(KeyDownEvent, OnRecorderKeyDown, RoutingStrategies.Tunnel);+ AddHandler(KeyUpEvent, OnRecorderKeyUp, RoutingStrategies.Tunnel);+ }++ /// <summary>+ /// While "Record" is on, the next key combination pressed on its button becomes the shortcut; on the flip+ /// recorder, the next key becomes the key that flips the donut.+ /// </summary>private void OnRecorderKeyDown(object? sender, KeyEventArgs e){- if (sender is ToggleButton { DataContext: TriggerGestureViewModel vm } && vm.IsRecording)- e.Handled = vm.Record(e.Key, e.KeyModifiers);+ var recorder = (e.Source as Visual)?.FindAncestorOfType<ToggleButton>(includeSelf: true);+ var recorded = recorder switch+ {+ { DataContext: TriggerGestureViewModel { IsRecording: true } vm } when recorder.Classes.Contains("recorder") =>+ vm.Record(e.Key, e.KeyModifiers),+ { Name: "FlipRecorder", DataContext: FlipOptionsViewModel { IsRecording: true } flip } => flip.Record(e.Key),+ _ => false,+ };+ if (!recorded)+ return;+ e.Handled = true;+ _recordedKey = e.Key;}- /// <summary>While "Record" is on, the next key pressed on the button flips the donut from now on.</summary>- private void OnFlipRecorderKeyDown(object? sender, KeyEventArgs e)+ private void OnRecorderKeyUp(object? sender, KeyEventArgs e){- if (sender is ToggleButton { DataContext: FlipOptionsViewModel vm } && vm.IsRecording)- e.Handled = vm.Record(e.Key);+ if (_recordedKey != e.Key)+ return;+ _recordedKey = null;+ e.Handled = true;}}diff --git a/src/Filee.Core/Platform/IPlatformServices.cs b/src/Filee.Core/Platform/IPlatformServices.csindex ebb8d640..109d2e1d 100644--- a/src/Filee.Core/Platform/IPlatformServices.cs+++ b/src/Filee.Core/Platform/IPlatformServices.cs@@ -24,6 +24,12 @@ public interface IPlatformServices/// <summary>Process name (without extension) owning the window under the point, or <c>null</c>.</summary>string? ProcessNameAt(int x, int y);+ /// <summary>+ /// The window in front, the one keys go to: a keyboard shortcut's scope goes by it, not by what the pointer is over.+ /// Null where the platform can't tell, and the pointer decides.+ /// </summary>+ ForegroundWindowInfo? GetForegroundWindow() => null;+/// <summary>/// Names of the apps that have a window open now, as <see cref="ProcessNameAt"/> reports them, sorted, without/// Filee. Windows reports a main window per process; macOS and Linux list the windows on screen.@@ -84,7 +90,10 @@ public interface IPlatformServices/// <summary>True if the user asked the OS to reduce animations.</summary>bool PrefersReducedMotion { get; }- /// <summary>Adds or removes "start with the system".</summary>+ /// <summary>+ /// Adds or removes "start with the system". Throws <see cref="StartupEntryNotKeptException"/> where the platform can+ /// tell that the entry it added didn't stay.+ /// </summary>void SetStartWithSystem(bool enabled, string executablePath);/// <summary>Adds or removes the file manager context-menu entry ("Convert with Filee") and Send To shortcut.</summary>@@ -121,6 +130,15 @@ public interface IPlatformServicesvoid RaiseTopmost(nint windowHandle);}+/// <summary>+/// The "start with the system" entry read back after writing it was gone or different: something (security software,+/// usually) took it away. The message is English, for the log; the UI says it in the user's language.+/// </summary>+public sealed class StartupEntryNotKeptException(string message) : IOException(message);++/// <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);+/// <summary>Whether "Convert with Filee" is in the top-level Windows 11 File Explorer menu (not just "Show more options").</summary>public enum ModernContextMenuState{diff --git a/src/Filee.Platform.Windows/DesktopShellView.cs b/src/Filee.Platform.Windows/DesktopShellView.csnew file mode 100644index 00000000..78593bc9--- /dev/null+++ b/src/Filee.Platform.Windows/DesktopShellView.cs@@ -0,0 +1,89 @@+// Explorer's desktop view, the one that shows the desktop's icons. Shell.Application.Windows() lists the folder+// windows but not the desktop, so the desktop's view is found through ShellWindows.FindWindowSW instead: Elevation uses+// it to start a program through Explorer, and the selection shortcut to read the icons selected on the desktop.++using System.Runtime.InteropServices;+using System.Runtime.Versioning;++namespace Filee.Platform.Windows;++[SupportedOSPlatform("windows")]+internal static class DesktopShellView+{+ /// <summary>+ /// Runs <paramref name="use"/> with the desktop view's IShellFolderViewDual, a dispatch object (its SelectedItems,+ /// its Application). Throws when Explorer's desktop isn't there (another shell, Explorer restarting).+ /// </summary>+ public static T Use<T>(Func<object, T> use)+ {+ var shellWindowsType = Type.GetTypeFromCLSID(new Guid("9BA05972-F6A8-11CF-A442-00A0C90A8F39"), throwOnError: true)!;+ object? shellWindows = null, desktop = null, browser = null, view = null, background = null;+ try+ {+ shellWindows = Activator.CreateInstance(shellWindowsType)+ ?? throw new InvalidOperationException("ShellWindows is not available.");+ object location = CSIDL_DESKTOP;+ object? empty = null; // VT_EMPTY+ desktop = ((IShellWindows)shellWindows).FindWindowSW(ref location, ref empty, SWC_DESKTOP, out _, SWFO_NEEDDISPATCH)+ ?? throw new InvalidOperationException("Explorer's desktop window was not found.");+ var topLevelBrowser = ShellInterop.SID_STopLevelBrowser;+ var shellBrowserId = typeof(ShellInterop.IShellBrowser).GUID;+ browser = ((ShellInterop.IServiceProvider)desktop).QueryService(ref topLevelBrowser, ref shellBrowserId);+ view = ((ShellInterop.IShellBrowser)browser).QueryActiveShellView();+ var dispatchId = IID_IDispatch;+ background = ((IShellView)view).GetItemObject(SVGIO_BACKGROUND, ref dispatchId);+ return use(background);+ }+ finally+ {+ // Released here, on the caller's thread. Two of them may be one object.+ foreach (var item in new[] { background, view, browser, desktop, shellWindows }+ .OfType<object>().Where(Marshal.IsComObject).Distinct(ReferenceEqualityComparer.Instance))+ Marshal.FinalReleaseComObject(item);+ }+ }++ private const int CSIDL_DESKTOP = 0;+ private const int SWC_DESKTOP = 8;+ private const int SWFO_NEEDDISPATCH = 1;+ private const uint SVGIO_BACKGROUND = 0;+ private static readonly Guid IID_IDispatch = new("00020400-0000-0000-C000-000000000046");++ // Only the methods Filee calls are typed; the slots before them keep the vtable order and are never called.++ [ComImport, Guid("85CB6900-4D95-11CF-960C-0080C7F4EE85"), InterfaceType(ComInterfaceType.InterfaceIsDual)]+ private interface IShellWindows+ {+ void get_Count();+ void Item();+ void _NewEnum();+ void Register();+ void RegisterPending();+ void Revoke();+ void OnNavigate();+ void OnActivated();++ [return: MarshalAs(UnmanagedType.IDispatch)]+ object? FindWindowSW(ref object location, ref object? locationRoot, int windowClass, out int hwnd, int options);+ }++ [ComImport, Guid("000214E3-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IShellView+ {+ void GetWindow();+ void ContextSensitiveHelp();+ void TranslateAccelerator();+ void EnableModeless();+ void UIActivate();+ void Refresh();+ void CreateViewWindow();+ void DestroyViewWindow();+ void GetCurrentInfo();+ void AddPropertySheetPages();+ void SaveViewState();+ void SelectItem();++ [return: MarshalAs(UnmanagedType.IUnknown)]+ object GetItemObject(uint item, ref Guid riid);+ }+}diff --git a/src/Filee.Platform.Windows/Elevation.cs b/src/Filee.Platform.Windows/Elevation.csindex b6fd9438..9b36bf04 100644--- a/src/Filee.Platform.Windows/Elevation.cs+++ b/src/Filee.Platform.Windows/Elevation.cs@@ -75,24 +75,9 @@ public static class Elevation}[SupportedOSPlatform("windows")]- private static void ShellExecuteFromDesktop(string executable, string arguments)- {- var shellWindowsType = Type.GetTypeFromCLSID(new Guid("9BA05972-F6A8-11CF-A442-00A0C90A8F39"), throwOnError: true)!;- object? shellWindows = null, desktop = null, browser = null, view = null, background = null;- try+ private static void ShellExecuteFromDesktop(string executable, string arguments) =>+ DesktopShellView.Use(background =>{- shellWindows = Activator.CreateInstance(shellWindowsType)- ?? throw new InvalidOperationException("ShellWindows is not available.");- object location = CSIDL_DESKTOP;- object? empty = null; // VT_EMPTY- desktop = ((IShellWindows)shellWindows).FindWindowSW(ref location, ref empty, SWC_DESKTOP, out _, SWFO_NEEDDISPATCH)- ?? throw new InvalidOperationException("Explorer's desktop window was not found.");- var topLevelBrowser = ShellInterop.SID_STopLevelBrowser;- var shellBrowserId = typeof(ShellInterop.IShellBrowser).GUID;- browser = ((ShellInterop.IServiceProvider)desktop).QueryService(ref topLevelBrowser, ref shellBrowserId);- view = ((ShellInterop.IShellBrowser)browser).QueryActiveShellView();- var dispatchId = IID_IDispatch;- background = ((IShellView)view).GetItemObject(SVGIO_BACKGROUND, ref dispatchId);// IShellFolderViewDual.Application is Explorer's IShellDispatch2: its ShellExecute runs in Explorer.dynamic folderView = background;dynamic application = folderView.Application;@@ -104,15 +89,8 @@ public static class Elevation{Marshal.FinalReleaseComObject((object)application);}- }- finally- {- // Released here, on their apartment's thread, which ends right after. Two of them may be one object.- foreach (var item in new[] { background, view, browser, desktop, shellWindows }- .OfType<object>().Where(Marshal.IsComObject).Distinct(ReferenceEqualityComparer.Instance))- Marshal.FinalReleaseComObject(item);- }- }+ return true;+ });/// <summary>Shows a plain Windows message box (for problems before Filee's own windows can open). No-op off Windows.</summary>public static void ShowWarning(string text)@@ -176,48 +154,5 @@ public static class Elevation}}- private const int CSIDL_DESKTOP = 0;- private const int SWC_DESKTOP = 8;- private const int SWFO_NEEDDISPATCH = 1;- private const uint SVGIO_BACKGROUND = 0;private const int SW_SHOWNORMAL = 1;- private static readonly Guid IID_IDispatch = new("00020400-0000-0000-C000-000000000046");-- // Only the methods Filee calls are typed; the slots before them keep the vtable order and are never called.-- [ComImport, Guid("85CB6900-4D95-11CF-960C-0080C7F4EE85"), InterfaceType(ComInterfaceType.InterfaceIsDual)]- private interface IShellWindows- {- void get_Count();- void Item();- void _NewEnum();- void Register();- void RegisterPending();- void Revoke();- void OnNavigate();- void OnActivated();-- [return: MarshalAs(UnmanagedType.IDispatch)]- object? FindWindowSW(ref object location, ref object? locationRoot, int windowClass, out int hwnd, int options);- }-- [ComImport, Guid("000214E3-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]- private interface IShellView- {- void GetWindow();- void ContextSensitiveHelp();- void TranslateAccelerator();- void EnableModeless();- void UIActivate();- void Refresh();- void CreateViewWindow();- void DestroyViewWindow();- void GetCurrentInfo();- void AddPropertySheetPages();- void SaveViewState();- void SelectItem();-- [return: MarshalAs(UnmanagedType.IUnknown)]- object GetItemObject(uint item, ref Guid riid);- }}diff --git a/src/Filee.Platform.Windows/WindowsPlatformServices.cs b/src/Filee.Platform.Windows/WindowsPlatformServices.csindex 1c03fdd1..38dde8fc 100644--- a/src/Filee.Platform.Windows/WindowsPlatformServices.cs+++ b/src/Filee.Platform.Windows/WindowsPlatformServices.cs@@ -68,19 +68,73 @@ public sealed class WindowsPlatformServices : IPlatformServicesreturn root == 0 ? null : ProcessNameOf(root);}+ public ForegroundWindowInfo? GetForegroundWindow()+ {+ var root = ForegroundRoot();+ if (root == 0)+ return null;+ var process = ProcessNameOf(root);+ return new ForegroundWindowInfo(process, IsFileManager(NativeMethods.ClassNameOf(root), process));+ }++ /// <summary>True for the desktop's window classes: its icons are not among Shell.Application's windows.</summary>+ internal static bool IsDesktop(string? windowClass) => windowClass is "Progman" or "WorkerW";+public 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.+ /// Reads the selection of the foreground Explorer window, or of the desktop, through the Shell automation objects./// Must be called on an STA thread (the Avalonia UI thread is STA)./// </summary>public IReadOnlyList<string> GetFileManagerSelection(){var foreground = NativeMethods.GetForegroundWindow();- return foreground == 0 ? [] : SelectionOf(foreground);+ if (foreground == 0)+ return [];+ return IsDesktop(NativeMethods.ClassNameOf(ForegroundRoot())) ? DesktopSelection() : SelectionOf(foreground);+ }++ /// <summary>The files selected on the desktop (#450).</summary>+ internal static IReadOnlyList<string> DesktopSelection()+ {+ try+ {+ return DesktopShellView.Use(view =>+ {+ dynamic folderView = view;+ dynamic items = folderView.SelectedItems();+ try+ {+ return ExistingFiles((object)items);+ }+ finally+ {+ Marshal.FinalReleaseComObject((object)items);+ }+ });+ }+ catch (Exception ex) when (ex is COMException or InvalidOperationException or InvalidCastException+ or Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)+ {+ // No Explorer desktop (another shell, Explorer restarting): nothing selected to read.+ return [];+ }+ }++ /// <summary>The paths of a shell item collection that are files on disk.</summary>+ private static List<string> ExistingFiles(object items)+ {+ var paths = new List<string>();+ foreach (dynamic item in (dynamic)items)+ {+ string path = item.Path;+ if (File.Exists(path))+ paths.Add(path);+ }+ return paths;}/// <summary>The selected files of an Explorer window; with tabs, of its active tab (see <see cref="ExplorerTabs"/>).</summary>@@ -129,13 +183,7 @@ public sealed class WindowsPlatformServices : IPlatformServicestry{dynamic items = window.Document.SelectedItems();- var paths = new List<string>();- foreach (dynamic item in items)- {- string path = item.Path;- if (File.Exists(path))- paths.Add(path);- }+ var paths = ExistingFiles((object)items);if (paths.Count > 0)return paths;}@@ -155,14 +203,19 @@ public sealed class WindowsPlatformServices : IPlatformServices}public string DescribeForegroundWindow()+ {+ var root = ForegroundRoot();+ return root == 0 ? "no foreground window" : $"{NativeMethods.ClassNameOf(root)} / {ProcessNameOf(root) ?? "?"}";+ }++ /// <summary>The top-level window of the foreground window, or 0 when there is none.</summary>+ private static nint ForegroundRoot(){var foreground = NativeMethods.GetForegroundWindow();if (foreground == 0)- return "no foreground window";+ return 0;var root = NativeMethods.GetAncestor(foreground, NativeMethods.GA_ROOT);- if (root == 0)- root = foreground;- return $"{NativeMethods.ClassNameOf(root)} / {ProcessNameOf(root) ?? "?"}";+ return root == 0 ? foreground : root;}public int SystemDragThreshold => Math.Max(2, NativeMethods.GetSystemMetrics(NativeMethods.SM_CXDRAG));@@ -173,10 +226,26 @@ public sealed class WindowsPlatformServices : IPlatformServicespublic void SetStartWithSystem(bool enabled, string executablePath){using var key = Registry.CurrentUser.CreateSubKey(RunKey);- if (enabled)- key.SetValue(AppName, $"\"{executablePath}\" --background");- else+ if (!enabled)+ {key.DeleteValue(AppName, throwOnMissingValue: false);+ return;+ }+ var command = $"\"{executablePath}\" --background";+ key.SetValue(AppName, command);+ // Security software can take the entry away as soon as it is written (#450): read it back, so the switch+ // says so instead of looking on while Filee doesn't start.+ CheckStartupEntry(command, key.GetValue(AppName));+ }++ /// <summary>Throws <see cref="StartupEntryNotKeptException"/> unless <paramref name="readBack"/> is the command written.</summary>+ internal static void CheckStartupEntry(string written, object? readBack)+ {+ if (readBack is string value && string.Equals(value, written, StringComparison.Ordinal))+ return;+ throw new StartupEntryNotKeptException(readBack is null+ ? $"The startup entry HKCU\\{RunKey}\\{AppName} was gone right after it was written."+ : $"The startup entry HKCU\\{RunKey}\\{AppName} reads \"{readBack}\" instead of \"{written}\".");}/// <summary>diff --git a/tests/Filee.App.Tests/GestureDetectorTests.cs b/tests/Filee.App.Tests/GestureDetectorTests.csindex c448b943..0944f7d9 100644--- a/tests/Filee.App.Tests/GestureDetectorTests.cs+++ b/tests/Filee.App.Tests/GestureDetectorTests.cs@@ -137,4 +137,74 @@ public class GestureDetectorTestsdetector.HoldElapsed(token);Assert.Equal(1, held);}++ [Fact]+ public void Drag_and_hold_on_the_same_press_both_wait_for_what_the_pointer_does()+ {+ // #450: with Drag listed first, a Hold on the same button and modifiers was never armed.+ var drag = new TriggerGesture { Kind = TriggerKind.Drag, Modifiers = ModifierKeys.Ctrl, Button = TriggerMouseButton.Left };+ var hold = new TriggerGesture { Kind = TriggerKind.Hold, Modifiers = ModifierKeys.Ctrl, Button = TriggerMouseButton.Left };+ var detector = Create(drag, hold);+ long token = 0;+ int dragged = 0, held = 0;+ detector.HoldTimerRequested += (t, _) => token = t;+ detector.DragStarted += (_, _, _) => dragged++;+ detector.HoldTriggered += (_, _, _) => held++;++ // Held still: the hold fires, and moving on afterwards doesn't start the drag too.+ detector.MouseDown(TriggerMouseButton.Left, 100, 100, ModifierKeys.Ctrl);+ Assert.NotEqual(0, token);+ detector.MouseMove(102, 101, ModifierKeys.Ctrl, TriggerMouseButton.Left); // inside the threshold+ detector.HoldElapsed(token);+ detector.MouseMove(180, 100, ModifierKeys.Ctrl, TriggerMouseButton.Left);+ detector.MouseUp(TriggerMouseButton.Left, 180, 100);+ Assert.Equal((0, 1), (dragged, held));++ // Moved: the drag fires, and the hold's timer finds nothing to fire.+ token = 0;+ detector.MouseDown(TriggerMouseButton.Left, 100, 100, ModifierKeys.Ctrl);+ detector.MouseMove(150, 100, ModifierKeys.Ctrl, TriggerMouseButton.Left);+ detector.HoldElapsed(token);+ detector.MouseUp(TriggerMouseButton.Left, 150, 100);+ Assert.Equal((1, 1), (dragged, held));++ // The order in the list doesn't matter.+ detector.Configure([hold, drag]);+ detector.MouseDown(TriggerMouseButton.Left, 100, 100, ModifierKeys.Ctrl);+ detector.MouseMove(150, 100, ModifierKeys.Ctrl, TriggerMouseButton.Left);+ Assert.Equal((2, 1), (dragged, held));+ }++ [Fact]+ public void A_drag_out_of_scope_still_lets_its_hold_fire()+ {+ var drag = new TriggerGesture { Kind = TriggerKind.Drag, Modifiers = ModifierKeys.Alt, Button = TriggerMouseButton.Left, Scope = TriggerScope.FileManager };+ var hold = new TriggerGesture { Kind = TriggerKind.Hold, Modifiers = ModifierKeys.Alt, Button = TriggerMouseButton.Left, Scope = TriggerScope.Anywhere };+ var detector = Create(drag, hold);+ detector.ScopeFilter = (g, _, _) => g.Scope == TriggerScope.Anywhere;+ long token = 0;+ var held = 0;+ detector.HoldTimerRequested += (t, _) => token = t;+ detector.HoldTriggered += (_, _, _) => held++;++ detector.MouseDown(TriggerMouseButton.Left, 0, 0, ModifierKeys.Alt);+ detector.HoldElapsed(token);++ Assert.Equal(1, held);+ }++ [Fact]+ public void Of_two_shortcuts_on_one_key_the_one_whose_scope_fits_fires()+ {+ var inFileManager = new TriggerGesture { Kind = TriggerKind.KeyChord, Modifiers = ModifierKeys.Ctrl, Key = "Space", Scope = TriggerScope.FileManager };+ var anywhere = new TriggerGesture { Kind = TriggerKind.KeyChord, Modifiers = ModifierKeys.Ctrl, Key = "Space", Scope = TriggerScope.Anywhere, HoldMilliseconds = 777 };+ var detector = Create(inFileManager, anywhere);+ detector.ScopeFilter = (g, _, _) => g.Scope == TriggerScope.Anywhere;+ TriggerGesture? fired = null;+ detector.KeyChordTriggered += (g, _, _) => fired = g;++ detector.KeyDown("Space", ModifierKeys.Ctrl);++ Assert.Equal(777, fired?.HoldMilliseconds);+ }}diff --git a/tests/Filee.App.Tests/ShortcutRecorderTests.cs b/tests/Filee.App.Tests/ShortcutRecorderTests.csnew file mode 100644index 00000000..0222afe9--- /dev/null+++ b/tests/Filee.App.Tests/ShortcutRecorderTests.cs@@ -0,0 +1,82 @@+// #450: the shortcut recorder couldn't take Space or Enter. The focused button handled them first, and Space's release+// clicked it, which switched recording off and kept the old shortcut, so even the default Ctrl+Alt+Space couldn't be+// recorded again.++using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Headless;+using Avalonia.Headless.XUnit;+using Avalonia.Input;+using Avalonia.Threading;+using Avalonia.VisualTree;+using Filee.App.Services;+using Filee.App.ViewModels.Pages;+using Filee.App.Views.Pages;+using Filee.Core.Localization;+using Filee.Core.Settings;++namespace Filee.App.Tests;++public sealed class ShortcutRecorderTests+{+ [AvaloniaFact]+ public void Ctrl_Alt_Space_is_recorded_on_the_button()+ {+ TestServices.EnsureInitialized();+ var store = AppHost.Get<UserDataStore>();+ var before = store.Settings.Triggers.Select(t => t.Clone()).ToList();+ Window? window = null;+ try+ {+ store.Settings.Triggers.Clear();+ store.Settings.Triggers.Add(new TriggerGesture { Kind = TriggerKind.KeyChord, Modifiers = ModifierKeys.Ctrl, Key = "K" });+ var vm = new TriggersPageViewModel(store, AppHost.Get<ILocalizer>());+ var shortcut = vm.Gestures.Single();+ window = new Window { Content = new TriggersPage { DataContext = vm }, Width = 820, Height = 1500 };+ window.Show();+ RenderTests.Pump();++ var recorder = window.GetVisualDescendants().OfType<ToggleButton>().Single(b => b.Classes.Contains("recorder"));+ Assert.True(recorder.Focus());+ shortcut.IsRecording = true;+ Assert.True(recorder.IsChecked);++ window.KeyPress(Key.Space, RawInputModifiers.Control | RawInputModifiers.Alt, PhysicalKey.Space, " ");+ window.KeyRelease(Key.Space, RawInputModifiers.Control | RawInputModifiers.Alt, PhysicalKey.Space, " ");+ Dispatcher.UIThread.RunJobs();++ Assert.False(shortcut.IsRecording); // and the release didn't click it back on+ Assert.False(recorder.IsChecked);+ Assert.Equal("Space", shortcut.Key);+ Assert.Equal(ModifierKeys.Ctrl | ModifierKeys.Alt, store.Settings.Triggers.Single().Modifiers);+ Assert.Equal("Space", store.Settings.Triggers.Single().Key);++ // Enter is taken as well, without clicking the button.+ shortcut.IsRecording = true;+ window.KeyPress(Key.Enter, RawInputModifiers.Shift, PhysicalKey.Enter, "\r");+ window.KeyRelease(Key.Enter, RawInputModifiers.Shift, PhysicalKey.Enter, "\r");+ Dispatcher.UIThread.RunJobs();+ Assert.False(shortcut.IsRecording);+ Assert.Equal(ModifierKeys.Shift, store.Settings.Triggers.Single().Modifiers);+ Assert.Equal("Enter", store.Settings.Triggers.Single().Key);++ // Space on the flip recorder is refused with the reason shown, instead of clicking the button.+ var flip = window.GetVisualDescendants().OfType<ToggleButton>().Single(b => b.Name == "FlipRecorder");+ Assert.True(flip.Focus());+ vm.Flip.IsRecording = true;+ window.KeyPress(Key.Space, RawInputModifiers.None, PhysicalKey.Space, " ");+ window.KeyRelease(Key.Space, RawInputModifiers.None, PhysicalKey.Space, " ");+ Dispatcher.UIThread.RunJobs();+ Assert.False(vm.Flip.IsRecording);+ Assert.NotNull(vm.Flip.Error);+ }+ finally+ {+ window?.Close();+ store.Settings.Triggers.Clear();+ store.Settings.Triggers.AddRange(before);+ store.Settings.Donut.FlipKey = DonutSettings.DefaultFlipKey;+ store.SaveSettings();+ }+ }+}diff --git a/tests/Filee.App.Tests/SystemIntegrationTests.cs b/tests/Filee.App.Tests/SystemIntegrationTests.csindex 5bdb042e..4bba1ef1 100644--- a/tests/Filee.App.Tests/SystemIntegrationTests.cs+++ b/tests/Filee.App.Tests/SystemIntegrationTests.cs@@ -40,6 +40,22 @@ public sealed class SystemIntegrationTestsAssert.Equal(2, platform.MenuCalls);}+ [Fact]+ public void A_startup_entry_that_did_not_stay_shows_under_the_switch_and_is_written_again_next_time()+ {+ // #450: security software removing the Run entry left the switch on with nothing said.+ var platform = new RecordingPlatform { LoseStartupEntry = true };+ var service = Create(platform);+ var settings = new AppSettings { StartWithSystem = true };+ service.Apply(settings);+ Assert.Equal("general.integration_failed: general.startup_entry_missing", service.Error);++ platform.LoseStartupEntry = false;+ service.Apply(settings);+ Assert.Null(service.Error);+ Assert.Equal(2, platform.StartupCalls);+ }+[Fact]public void Source_builds_do_not_register_os_integration(){@@ -89,7 +105,13 @@ public sealed class SystemIntegrationTestspublic int StartupCalls { get; private set; }public int MenuCalls { get; private set; }public bool FailMenu { get; set; }- public void SetStartWithSystem(bool enabled, string executablePath) => StartupCalls++;+ public bool LoseStartupEntry { get; set; }+ public void SetStartWithSystem(bool enabled, string executablePath)+ {+ StartupCalls++;+ if (LoseStartupEntry)+ throw new StartupEntryNotKeptException("gone");+ }public void SetContextMenu(bool enabled, string executablePath, string label){MenuCalls++;diff --git a/tests/Filee.App.Tests/TriggerScopeTests.cs b/tests/Filee.App.Tests/TriggerScopeTests.csnew file mode 100644index 00000000..318bd50f--- /dev/null+++ b/tests/Filee.App.Tests/TriggerScopeTests.cs@@ -0,0 +1,82 @@+// A keyboard shortcut goes by the window in front, a mouse gesture by the window under the pointer (#450): with+// Explorer focused and the pointer resting on the taskbar or another window, the shortcut was ignored.++using Filee.App.Services.Triggers;+using Filee.Core.Platform;+using Filee.Core.Settings;+using Microsoft.Extensions.Logging.Abstractions;++namespace Filee.App.Tests;++public sealed class TriggerScopeTests+{+ private static readonly TriggerGesture Shortcut = new() { Kind = TriggerKind.KeyChord, Modifiers = ModifierKeys.Ctrl | ModifierKeys.Alt, Key = "Space" };+ private static readonly TriggerGesture Drag = new() { Kind = TriggerKind.Drag, Modifiers = ModifierKeys.Ctrl, Button = TriggerMouseButton.Left };++ [Fact]+ public void A_shortcut_fires_for_the_file_manager_in_front_wherever_the_pointer_is()+ {+ var platform = new ScopePlatform { Front = new ForegroundWindowInfo("explorer", true), Pointer = ("notepad", false) };+ var service = new TriggerService(platform, NullLogger<TriggerService>.Instance);++ Assert.True(service.InScope(Shortcut, 10, 10));+ Assert.False(service.InScope(Drag, 10, 10)); // the pointer still decides for the mouse+ }++ [Fact]+ public void A_shortcut_is_ignored_in_another_app_in_front_even_with_the_pointer_over_explorer()+ {+ var platform = new ScopePlatform { Front = new ForegroundWindowInfo("notepad", false), Pointer = ("explorer", true) };+ var service = new TriggerService(platform, NullLogger<TriggerService>.Instance);++ Assert.False(service.InScope(Shortcut, 10, 10));+ Assert.True(service.InScope(Drag, 10, 10));+ }++ [Fact]+ public void An_excluded_app_in_front_blocks_a_shortcut_set_to_anywhere()+ {+ var platform = new ScopePlatform { Front = new ForegroundWindowInfo("Photoshop", false), Pointer = ("explorer", true) };+ var service = new TriggerService(platform, NullLogger<TriggerService>.Instance);+ var anywhere = Shortcut.Clone();+ anywhere.Scope = TriggerScope.Anywhere;+ Assert.True(service.InScope(anywhere, 10, 10));++ var settings = new AppSettings();+ settings.ExcludedProcesses.Add("Photoshop.exe");+ service.Apply(settings);++ Assert.False(service.InScope(anywhere, 10, 10));+ }++ [Fact]+ public void Without_a_window_in_front_the_pointer_decides_as_before()+ {+ var platform = new ScopePlatform { Front = null, Pointer = ("explorer", true) };+ var service = new TriggerService(platform, NullLogger<TriggerService>.Instance);++ Assert.True(service.InScope(Shortcut, 10, 10));+ platform.Pointer = ("notepad", false);+ Assert.False(service.InScope(Shortcut, 10, 10));+ }++ private sealed class ScopePlatform : IPlatformServices+ {+ public ForegroundWindowInfo? Front { get; set; }+ public (string Process, bool IsFileManager) Pointer { get; set; }+ public ForegroundWindowInfo? GetForegroundWindow() => Front;+ public bool IsFileManagerAt(int x, int y) => Pointer.IsFileManager;+ public string? ProcessNameAt(int x, int y) => Pointer.Process;+ public IReadOnlyList<string> GetFileManagerSelection() => [];+ public int SystemDragThreshold => 4;+ public bool PrefersReducedMotion => false;+ public void SetStartWithSystem(bool enabled, string executablePath) { }+ public void SetContextMenu(bool enabled, string executablePath, string label) { }+ public ModernContextMenuState GetModernContextMenuState(string executablePath) => ModernContextMenuState.Unsupported;+ public Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath) =>+ Task.FromResult(new ModernContextMenuResult(false));+ public void RevealInFileManager(string path) { }+ public void OpenFile(string path) { }+ public void RaiseTopmost(nint windowHandle) { }+ }+}diff --git a/tests/Filee.Platform.Tests/WindowsTriggerSupportTests.cs b/tests/Filee.Platform.Tests/WindowsTriggerSupportTests.csnew file mode 100644index 00000000..d201c253--- /dev/null+++ b/tests/Filee.Platform.Tests/WindowsTriggerSupportTests.cs@@ -0,0 +1,34 @@+// #450: the selection shortcut reads the desktop's selection when the desktop is in front, and "start at sign-in"+// says so when the entry it wrote didn't stay.++using System.Runtime.Versioning;+using Filee.Core.Platform;+using Filee.Platform.Windows;++namespace Filee.Platform.Tests;++// Plain checks: they run on every OS, the class is only marked for the Windows-only type.+[SupportedOSPlatform("windows")]+public sealed class WindowsTriggerSupportTests+{+ [Theory]+ [InlineData("Progman", true)]+ [InlineData("WorkerW", true)]+ [InlineData("CabinetWClass", false)] // a folder window: Shell.Application lists it+ [InlineData("Shell_TrayWnd", false)] // the taskbar+ [InlineData(null, false)]+ public void The_desktop_is_told_from_folder_windows(string? windowClass, bool desktop) =>+ Assert.Equal(desktop, WindowsPlatformServices.IsDesktop(windowClass));++ [Fact]+ public void The_startup_entry_read_back_must_be_the_one_written()+ {+ const string written = "\"C:\\Program Files\\Filee\\Filee.exe\" --background";+ WindowsPlatformServices.CheckStartupEntry(written, written);++ Assert.Throws<StartupEntryNotKeptException>(() => WindowsPlatformServices.CheckStartupEntry(written, null));+ Assert.Throws<StartupEntryNotKeptException>(() =>+ WindowsPlatformServices.CheckStartupEntry(written, "\"C:\\Program Files\\Filee\\Filee.exe\""));+ Assert.Throws<StartupEntryNotKeptException>(() => WindowsPlatformServices.CheckStartupEntry(written, new byte[] { 1 }));+ }+}