Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Add "Replace the original" to presets (#332)

cre8ive-marketingfc452e7d46f8
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 5cd601a2..2de41078 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -48,6 +48,11 @@
Each name stays reserved while a conversion holds it. A conversion that fails or is cancelled deletes what it began
writing, but only at a path that was its alone: nothing was there before and no other conversion was handed the
same name ("Overwrite"). It frees its names and removes an output folder it made if that is left empty.
+ *Replace the original* (`OutputRule.ReplaceOriginal`, off by default) comes after that, for a finished result of
+ the source's own format: the source goes to the Recycle Bin / Trash (`IPlatformServices.MoveToTrash`) and the
+ result is moved to its path. When it can't go there (no Recycle Bin on the drive, a network share, a file open
+ elsewhere, the command line), both stay and the file's notice says why. Watch folders and files from a browser
+ never replace.
"Merge into one PDF" converts each file to PDF and merges with PDFsharp.
"Compress into one archive" packs the dropped files, unconverted, with the archive engine (`IFileCombiner`).
"Merge videos", "Merge audio" and "Video from images" join the files, in the order picked in the merge order
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index e97ca3ee..b6b322fb 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -104,6 +104,8 @@
"error.geo_unsupported_shape": "هذا النوع من الأشكال غير مدعوم",
"error.geo_too_large": "سيتجاوز ملف Shapefile حد الصيغة البالغ 2 غيغابايت",
"notice.pdf_not_smaller": "تعذّر تقليل الحجم، لذا نُسخ الملف كما هو",
+ "notice.original_kept": "تم الاحتفاظ بالأصل وحُفظت النتيجة كنسخة",
+ "notice.original_in_trash": "الأصل في سلة المحذوفات، واحتفظت النتيجة باسمها",
"notice.empty_spreadsheet_pages_removed": "تمت إزالة صفحات جدول البيانات الفارغة",
"notice.live_photo_pair": "حُفظ كصورة وملف MOV بالاسم نفسه. استوردهما معًا (صور iCloud أو AirDrop أو تطبيق الصور على Mac) لتحصل على Live Photo",
"notice.geo_datum_assumed": "المرجع الجيوديسي ليس WGS 84؛ حُوّلت المواقع على افتراض أنه كذلك، وقد تنحرف بمقدار يصل إلى مئات الأمتار",
@@ -604,6 +606,8 @@
"presets.keep_dates_hint": "تحصل الملفات المحوّلة على تاريخَي إنشاء الأصل وتعديله، فتبقى الصور مرتبة حسب التاريخ.",
"presets.zip_result": "حفظ النتيجة بصيغة ZIP",
"presets.zip_result_hint": "تُجمَّع ملفات النتيجة (مثل ‎.shp و‎.shx و‎.dbf و‎.prj و‎.cpg في Shapefile) في ZIP واحد بجانب الأصل، بدلًا من ملفات منفصلة.",
+ "presets.replace_original": "استبدال الأصل",
+ "presets.replace_original_hint": "تأخذ النتيجة اسم الأصل ومكانه، وينتقل الأصل إلى سلة المحذوفات. فقط عندما يكون للنتيجة التنسيق نفسه، ولا يحدث أبدًا لمجلدات المراقبة أو الملفات القادمة من متصفح. إذا تعذّر نقل الأصل، يبقى في مكانه وتُحفظ النتيجة كنسخة.",
"presets.conflict": "إذا كان الملف موجودًا",
"presets.conflict.Rename": "إضافة رقم",
"presets.conflict.Overwrite": "استبداله",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index a8576b23..426e2c62 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -110,6 +110,8 @@
"error.geo_unsupported_shape": "This kind of shape isn't supported",
"error.geo_too_large": "The Shapefile would pass the format's 2 GB limit",
"notice.pdf_not_smaller": "Couldn't make it smaller, so it was copied as it is",
+ "notice.original_kept": "The original was kept, the result was saved as a copy",
+ "notice.original_in_trash": "The original is in the Recycle Bin / Trash, the result kept its own name",
"notice.empty_spreadsheet_pages_removed": "Empty spreadsheet pages were removed",
"notice.live_photo_pair": "Saved as a photo and a MOV with the same name. Import both together (iCloud Photos, AirDrop or Photos on a Mac) to get a Live Photo",
"notice.geo_datum_assumed": "The datum isn't WGS 84; positions were converted as if it were and can be off by up to hundreds of metres",
@@ -619,6 +621,8 @@
"presets.keep_dates_hint": "Converted files get the created and modified dates of the original, so photos still sort by date.",
"presets.zip_result": "Save the result as a ZIP",
"presets.zip_result_hint": "The files of the result (a Shapefile's .shp, .shx, .dbf, .prj and .cpg) are packed into one ZIP next to the source, in place of loose files.",
+ "presets.replace_original": "Replace the original",
+ "presets.replace_original_hint": "The result takes the original's name and place, and the original goes to the Recycle Bin / Trash. Only when the result has the same format, never for watch folders or files from a browser. When the original can't go there, it stays and the result is saved as a copy.",
"presets.conflict": "If the file exists",
"presets.conflict.Rename": "Add a number",
"presets.conflict.Overwrite": "Replace it",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 91298bff..86a5d3b6 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -104,6 +104,8 @@
"error.geo_unsupported_shape": "Este tipo de forma no es compatible",
"error.geo_too_large": "El Shapefile superaría el límite de 2 GB del formato",
"notice.pdf_not_smaller": "No se pudo reducir su tamaño, por lo que se copió tal cual",
+ "notice.original_kept": "Se conservó el original, el resultado se guardó como copia",
+ "notice.original_in_trash": "El original está en la Papelera, el resultado conservó su propio nombre",
"notice.empty_spreadsheet_pages_removed": "Se eliminaron las páginas vacías de la hoja de cálculo",
"notice.live_photo_pair": "Guardado como una foto y un MOV con el mismo nombre. Impórtalos juntos (Fotos de iCloud, AirDrop o Fotos en un Mac) para obtener una Live Photo",
"notice.geo_datum_assumed": "El datum no es WGS 84; las posiciones se convirtieron como si lo fuera y pueden desviarse hasta cientos de metros",
@@ -604,6 +606,8 @@
"presets.keep_dates_hint": "Los archivos convertidos reciben las fechas de creación y modificación del original, así que las fotos siguen ordenándose por fecha.",
"presets.zip_result": "Guardar el resultado como ZIP",
"presets.zip_result_hint": "Los archivos del resultado (.shp, .shx, .dbf, .prj y .cpg de un Shapefile) se empaquetan en un solo ZIP junto al origen, en lugar de archivos sueltos.",
+ "presets.replace_original": "Reemplazar el original",
+ "presets.replace_original_hint": "El resultado toma el nombre y el lugar del original, y el original va a la Papelera de reciclaje. Solo cuando el resultado tiene el mismo formato, nunca en carpetas vigiladas ni con archivos de un navegador. Si el original no puede ir a la Papelera, se queda y el resultado se guarda como copia.",
"presets.conflict": "Si el archivo existe",
"presets.conflict.Rename": "Añadir un número",
"presets.conflict.Overwrite": "Reemplazarlo",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index c82921d5..ba62d5e7 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -110,6 +110,8 @@
"error.geo_unsupported_shape": "Ce type de forme n'est pas pris en charge",
"error.geo_too_large": "Le Shapefile dépasserait la limite de 2 Go du format",
"notice.pdf_not_smaller": "Impossible de réduire sa taille : le fichier a été copié tel quel",
+ "notice.original_kept": "L'original a été conservé, le résultat a été enregistré en copie",
+ "notice.original_in_trash": "L'original est dans la Corbeille, le résultat a gardé son propre nom",
"notice.empty_spreadsheet_pages_removed": "Les pages vides de la feuille de calcul ont été supprimées",
"notice.live_photo_pair": "Enregistré en une photo et un MOV de même nom. Importez-les ensemble (Photos iCloud, AirDrop ou Photos sur Mac) pour obtenir une Live Photo",
"notice.geo_datum_assumed": "Le datum n'est pas WGS 84 ; les positions ont été converties comme s'il l'était et peuvent être décalées de plusieurs centaines de mètres",
@@ -619,6 +621,8 @@
"presets.keep_dates_hint": "Les fichiers convertis reprennent les dates de création et de modification de l'original : les photos restent triées par date.",
"presets.zip_result": "Enregistrer le résultat en ZIP",
"presets.zip_result_hint": "Les fichiers du résultat (les .shp, .shx, .dbf, .prj et .cpg d'un Shapefile) sont regroupés dans un seul ZIP à côté de l'original, au lieu de fichiers séparés.",
+ "presets.replace_original": "Remplacer l'original",
+ "presets.replace_original_hint": "Le résultat prend le nom et la place de l'original, et l'original va dans la Corbeille. Seulement quand le résultat a le même format, jamais pour les dossiers surveillés ni les fichiers venant d'un navigateur. Si l'original ne peut pas aller dans la Corbeille, il reste et le résultat est enregistré en copie.",
"presets.conflict": "Si le fichier existe",
"presets.conflict.Rename": "Ajouter un numéro",
"presets.conflict.Overwrite": "Le remplacer",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index d72aeadb..61c196cb 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -104,6 +104,8 @@
"error.geo_unsupported_shape": "इस तरह का आकार समर्थित नहीं है",
"error.geo_too_large": "Shapefile फ़ॉर्मैट की 2 GB सीमा से बड़ी हो जाएगी",
"notice.pdf_not_smaller": "इसे छोटा नहीं किया जा सका, इसलिए जैसा है वैसा ही कॉपी कर दिया गया",
+ "notice.original_kept": "मूल फ़ाइल रखी गई, परिणाम कॉपी के रूप में सहेजा गया",
+ "notice.original_in_trash": "मूल फ़ाइल रीसायकल बिन / ट्रैश में है, परिणाम ने अपना नाम रखा",
"notice.empty_spreadsheet_pages_removed": "स्प्रेडशीट के खाली पृष्ठ हटा दिए गए",
"notice.live_photo_pair": "एक ही नाम की फ़ोटो और MOV के रूप में सहेजा गया। लाइव फ़ोटो पाने के लिए दोनों को साथ में इम्पोर्ट करें (iCloud Photos, AirDrop या Mac पर Photos)",
"notice.geo_datum_assumed": "डेटम WGS 84 नहीं है। स्थितियाँ ऐसे कन्वर्ट की गईं मानो वह WGS 84 हो, इसलिए वे कुछ सौ मीटर तक खिसक सकती हैं",
@@ -604,6 +606,8 @@
"presets.keep_dates_hint": "कन्वर्ट की गई फ़ाइलों को मूल फ़ाइल की बनाने और बदलने की तारीखें मिलती हैं, ताकि फ़ोटो अब भी तारीख के अनुसार क्रमित रहें।",
"presets.zip_result": "नतीजे को ZIP के रूप में सहेजें",
"presets.zip_result_hint": "नतीजे की फ़ाइलें (Shapefile की .shp, .shx, .dbf, .prj और .cpg) अलग-अलग रखने के बजाय स्रोत के बगल में एक ZIP में पैक की जाती हैं।",
+ "presets.replace_original": "मूल फ़ाइल बदलें",
+ "presets.replace_original_hint": "परिणाम मूल फ़ाइल का नाम और जगह ले लेता है, और मूल फ़ाइल रीसायकल बिन / ट्रैश में चली जाती है। केवल तब जब परिणाम का फ़ॉर्मैट वही हो, वॉच फ़ोल्डर या ब्राउज़र से आई फ़ाइलों के लिए कभी नहीं। अगर मूल फ़ाइल वहाँ नहीं जा सकती, तो वह रहती है और परिणाम एक कॉपी के रूप में सहेजा जाता है।",
"presets.conflict": "अगर फ़ाइल पहले से मौजूद हो",
"presets.conflict.Rename": "नंबर जोड़ें",
"presets.conflict.Overwrite": "बदल दें",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index 2bf8a1fa..e5cfa149 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -104,6 +104,8 @@
"error.geo_unsupported_shape": "この種類の図形には対応していません",
"error.geo_too_large": "Shapefile形式の上限(2 GB)を超えてしまいます",
"notice.pdf_not_smaller": "サイズを小さくできなかったため、元のままコピーしました",
+ "notice.original_kept": "元のファイルを残し、結果をコピーとして保存しました",
+ "notice.original_in_trash": "元のファイルはごみ箱にあります。結果は別の名前のままです",
"notice.empty_spreadsheet_pages_removed": "スプレッドシートの空白ページを削除しました",
"notice.live_photo_pair": "同じ名前の写真とMOVとして保存しました。両方を一緒に取り込むと(iCloud写真、AirDrop、Macの写真アプリ)Live Photoになります",
"notice.geo_datum_assumed": "測地系がWGS 84ではありません。WGS 84とみなして変換したため、位置が最大で数百メートルずれることがあります",
@@ -604,6 +606,8 @@
"presets.keep_dates_hint": "変換後のファイルに元ファイルの作成日時と更新日時を引き継ぎます。変換後も写真を日付順に並べられます。",
"presets.zip_result": "変換結果をZIPで保存",
"presets.zip_result_hint": "変換結果のファイル(Shapefileの.shp、.shx、.dbf、.prj、.cpg)を、ばらばらに置く代わりに元ファイルの隣の1つのZIPにまとめます。",
+ "presets.replace_original": "元のファイルを置き換える",
+ "presets.replace_original_hint": "変換結果が元のファイルの名前と場所を引き継ぎ、元のファイルはごみ箱に移動します。結果が同じ形式のときだけで、監視フォルダーやブラウザーからのファイルには使われません。元のファイルをごみ箱に移動できないときは残し、結果はコピーとして保存します。",
"presets.conflict": "同名ファイルがある場合",
"presets.conflict.Rename": "連番を付ける",
"presets.conflict.Overwrite": "上書き",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 19aaab67..f619fd02 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -110,6 +110,8 @@
"error.geo_unsupported_shape": "지원하지 않는 도형 종류예요",
"error.geo_too_large": "Shapefile의 한계인 2GB를 넘어요",
"notice.pdf_not_smaller": "더 작게 만들 수 없어서 그대로 복사했어요",
+ "notice.original_kept": "원본을 그대로 두고 결과를 사본으로 저장했습니다",
+ "notice.original_in_trash": "원본은 휴지통에 있고 결과는 자기 이름을 유지했습니다",
"notice.empty_spreadsheet_pages_removed": "스프레드시트의 빈 페이지를 제거했어요",
"notice.live_photo_pair": "같은 이름의 사진과 MOV로 저장했어요. 두 파일을 함께 가져오면(iCloud 사진, AirDrop, Mac의 사진 앱) 라이브 포토가 돼요",
"notice.geo_datum_assumed": "측지계가 WGS 84가 아니라서 같은 것으로 보고 변환했어요. 위치가 수백 m까지 어긋날 수 있어요",
@@ -619,6 +621,8 @@
"presets.keep_dates_hint": "변환한 파일에 원본의 만든 날짜와 수정한 날짜를 그대로 넣어요.\n그래서 사진을 날짜순으로 정렬해도 순서가 바뀌지 않아요.",
"presets.zip_result": "결과를 ZIP으로 저장",
"presets.zip_result_hint": "결과 파일들(Shapefile의 .shp, .shx, .dbf, .prj, .cpg)을 낱개로 두지 않고 원본 옆에 ZIP 하나로 묶어요.",
+ "presets.replace_original": "원본 바꾸기",
+ "presets.replace_original_hint": "결과가 원본의 이름과 위치를 가져가고 원본은 휴지통으로 이동합니다. 결과가 같은 형식일 때만 적용되며, 감시 폴더나 브라우저에서 가져온 파일에는 적용되지 않습니다. 원본을 휴지통으로 옮길 수 없으면 원본은 그대로 두고 결과를 사본으로 저장합니다.",
"presets.conflict": "같은 파일이 있으면",
"presets.conflict.Rename": "번호 붙이기",
"presets.conflict.Overwrite": "덮어쓰기",
diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json
index a1c291ff..d2f84a48 100644
--- a/src/Filee.App/Assets/i18n/ne.json
+++ b/src/Filee.App/Assets/i18n/ne.json
@@ -104,6 +104,8 @@
"error.geo_unsupported_shape": "यस प्रकारको आकार समर्थित छैन",
"error.geo_too_large": "Shapefile ढाँचाको २ GB सीमा नाघ्नेछ",
"notice.pdf_not_smaller": "यसलाई सानो बनाउन सकिएन, त्यसैले जस्तो छ त्यस्तै प्रतिलिपि गरियो",
+ "notice.original_kept": "मूल फाइल राखियो, नतिजा प्रतिलिपिको रूपमा सुरक्षित भयो",
+ "notice.original_in_trash": "मूल फाइल रिसाइकल बिन / ट्र्यासमा छ, नतिजाले आफ्नै नाम राख्यो",
"notice.empty_spreadsheet_pages_removed": "स्प्रेडसिटका खाली पृष्ठहरू हटाइए",
"notice.live_photo_pair": "एउटै नामको फोटो र MOV का रूपमा सुरक्षित गरियो। लाइभ फोटो पाउन दुवैलाई सँगै आयात गर्नुहोस् (iCloud Photos, AirDrop वा Mac मा Photos)",
"notice.geo_datum_assumed": "डेटम WGS 84 होइन; स्थितिहरू यो WGS 84 भए जस्तै रूपान्तरण गरिए, जसले केही सय मिटरसम्म फरक पार्न सक्छ",
@@ -604,6 +606,8 @@
"presets.keep_dates_hint": "रूपान्तरित फाइलहरूले मूल फाइलका सिर्जना र परिमार्जन मितिहरू पाउँछन्, जसले गर्दा फोटोहरू अझै मिति अनुसार क्रमबद्ध हुन्छन्।",
"presets.zip_result": "परिणामलाई ZIP को रूपमा सुरक्षित गर्नुहोस्",
"presets.zip_result_hint": "परिणामका फाइलहरू (Shapefile को .shp, .shx, .dbf, .prj र .cpg) छुट्टाछुट्टै राख्नुको सट्टा स्रोतको छेउमा एउटै ZIP मा प्याक गरिन्छ।",
+ "presets.replace_original": "मूल फाइल बदल्नुहोस्",
+ "presets.replace_original_hint": "नतिजाले मूल फाइलको नाम र ठाउँ लिन्छ, र मूल फाइल रिसाइकल बिन / ट्र्यासमा जान्छ। नतिजाको ढाँचा उही हुँदा मात्र, वाच फोल्डर वा ब्राउजरबाट आएका फाइलका लागि कहिल्यै होइन। मूल फाइल त्यहाँ जान नसके, त्यो रहन्छ र नतिजा प्रतिलिपिको रूपमा सुरक्षित हुन्छ।",
"presets.conflict": "यदि फाइल पहिले नै अवस्थित छ भने",
"presets.conflict.Rename": "नम्बर थप्नुहोस्",
"presets.conflict.Overwrite": "बदल्नुहोस् (अधिलेखन)",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index e07632dc..5a3ee6ec 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -110,6 +110,8 @@
"error.geo_unsupported_shape": "Ten rodzaj kształtu nie jest obsługiwany",
"error.geo_too_large": "Shapefile przekroczyłby limit 2 GB tego formatu",
"notice.pdf_not_smaller": "Nie udało się zmniejszyć pliku, więc skopiowano go bez zmian",
+ "notice.original_kept": "Oryginał został zachowany, wynik zapisano jako kopię",
+ "notice.original_in_trash": "Oryginał jest w Koszu, wynik zachował własną nazwę",
"notice.empty_spreadsheet_pages_removed": "Usunięto puste strony arkusza kalkulacyjnego",
"notice.live_photo_pair": "Zapisano jako zdjęcie i plik MOV o tej samej nazwie. Zaimportuj je razem (Zdjęcia iCloud, AirDrop lub Zdjęcia na Macu), aby otrzymać Live Photo",
"notice.geo_datum_assumed": "Datum nie jest WGS 84; pozycje przeliczono tak, jakby było, więc mogą się różnić nawet o setki metrów",
@@ -619,6 +621,8 @@
"presets.keep_dates_hint": "Przekonwertowane pliki dostają daty utworzenia i modyfikacji oryginału, więc zdjęcia nadal sortują się według daty.",
"presets.zip_result": "Zapisz wynik jako ZIP",
"presets.zip_result_hint": "Pliki wyniku (.shp, .shx, .dbf, .prj i .cpg Shapefile) są pakowane do jednego ZIP obok źródła zamiast luźnych plików.",
+ "presets.replace_original": "Zastąp oryginał",
+ "presets.replace_original_hint": "Wynik przejmuje nazwę i miejsce oryginału, a oryginał trafia do Kosza. Tylko gdy wynik ma ten sam format, nigdy dla obserwowanych folderów ani plików z przeglądarki. Jeśli oryginał nie może trafić do Kosza, zostaje, a wynik jest zapisywany jako kopia.",
"presets.conflict": "Jeśli plik istnieje",
"presets.conflict.Rename": "Dodaj numer",
"presets.conflict.Overwrite": "Zastąp",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index 59614122..43d209aa 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -110,6 +110,8 @@
"error.geo_unsupported_shape": "Este tipo de forma não é compatível",
"error.geo_too_large": "O Shapefile passaria do limite de 2 GB do formato",
"notice.pdf_not_smaller": "Não deu para deixar menor, então foi copiado como está",
+ "notice.original_kept": "O original foi mantido, o resultado foi salvo como cópia",
+ "notice.original_in_trash": "O original está na Lixeira, o resultado manteve o próprio nome",
"notice.empty_spreadsheet_pages_removed": "As páginas vazias da planilha foram removidas",
"notice.live_photo_pair": "Salvo como uma foto e um MOV com o mesmo nome. Importe os dois juntos (Fotos do iCloud, AirDrop ou Fotos no Mac) para obter uma Live Photo",
"notice.geo_datum_assumed": "O datum não é WGS 84; as posições foram convertidas como se fosse, e podem errar em até centenas de metros",
@@ -619,6 +621,8 @@
"presets.keep_dates_hint": "Os arquivos convertidos recebem as datas de criação e modificação do original, então as fotos continuam ordenadas por data.",
"presets.zip_result": "Salvar o resultado como ZIP",
"presets.zip_result_hint": "Os arquivos do resultado (os .shp, .shx, .dbf, .prj e .cpg de um Shapefile) são compactados num ZIP ao lado da origem, no lugar de arquivos soltos.",
+ "presets.replace_original": "Substituir o original",
+ "presets.replace_original_hint": "O resultado assume o nome e o lugar do original, e o original vai para a Lixeira. Só quando o resultado tem o mesmo formato, nunca para pastas monitoradas ou arquivos vindos de um navegador. Se o original não puder ir para a Lixeira, ele fica e o resultado é salvo como cópia.",
"presets.conflict": "Se o arquivo existir",
"presets.conflict.Rename": "Adicionar um número",
"presets.conflict.Overwrite": "Substituir",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 5e8d9564..e496bcbf 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -110,6 +110,8 @@
"error.geo_unsupported_shape": "Такой тип фигуры не поддерживается",
"error.geo_too_large": "Shapefile превысил бы предел формата в 2 ГБ",
"notice.pdf_not_smaller": "Уменьшить не получилось, файл скопирован как есть",
+ "notice.original_kept": "Оригинал оставлен, результат сохранён как копия",
+ "notice.original_in_trash": "Оригинал в Корзине, результат сохранил своё имя",
"notice.empty_spreadsheet_pages_removed": "Пустые страницы таблицы удалены",
"notice.live_photo_pair": "Сохранено как фото и MOV с одинаковым именем. Импортируйте их вместе (Фото iCloud, AirDrop или «Фото» на Mac), чтобы получить Live Photo",
"notice.geo_datum_assumed": "Датум отличается от WGS 84; координаты пересчитаны как для WGS 84 и могут сместиться на сотни метров",
@@ -619,6 +621,8 @@
"presets.keep_dates_hint": "Сконвертированные файлы получают даты создания и изменения оригинала, так что фото по-прежнему сортируются по дате.",
"presets.zip_result": "Сохранять результат в ZIP",
"presets.zip_result_hint": "Файлы результата (у Shapefile это .shp, .shx, .dbf, .prj и .cpg) упаковываются в один ZIP рядом с исходником вместо отдельных файлов.",
+ "presets.replace_original": "Заменить оригинал",
+ "presets.replace_original_hint": "Результат получает имя и место оригинала, а оригинал отправляется в Корзину. Только если у результата тот же формат, никогда для отслеживаемых папок и файлов из браузера. Если оригинал нельзя отправить в Корзину, он остаётся, а результат сохраняется как копия.",
"presets.conflict": "Если файл уже есть",
"presets.conflict.Rename": "Добавить номер",
"presets.conflict.Overwrite": "Заменить",
diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json
index 21a267b9..a87757d4 100644
--- a/src/Filee.App/Assets/i18n/th.json
+++ b/src/Filee.App/Assets/i18n/th.json
@@ -104,6 +104,8 @@
"error.geo_unsupported_shape": "ไม่รองรับรูปทรงเรขาคณิตประเภทนี้",
"error.geo_too_large": "Shapefile จะมีขนาดเกินขีดจำกัดของฟอร์แมตที่ 2 GB",
"notice.pdf_not_smaller": "ไม่สามารถบีบอัดให้เล็กลงได้ จึงคัดลอกไฟล์ตามเดิม",
+ "notice.original_kept": "เก็บไฟล์ต้นฉบับไว้ และบันทึกผลลัพธ์เป็นสำเนา",
+ "notice.original_in_trash": "ไฟล์ต้นฉบับอยู่ในถังขยะ ผลลัพธ์ยังใช้ชื่อของตัวเอง",
"notice.empty_spreadsheet_pages_removed": "ลบหน้าว่างของสเปรดชีตออกแล้ว",
"notice.live_photo_pair": "บันทึกเป็นรูปภาพและไฟล์ MOV ที่มีชื่อเดียวกัน นำเข้าทั้งสองไฟล์พร้อมกัน (ผ่านรูปภาพ iCloud, AirDrop หรือ Photos บน Mac) เพื่อใช้งานเป็น Live Photo",
"notice.geo_datum_assumed": "เดตัมไม่ใช่ WGS 84 ตำแหน่งถูกแปลงโดยถือว่าเป็น WGS 84 ซึ่งอาจคลาดเคลื่อนได้ถึงหลายร้อยเมตร",
@@ -604,6 +606,8 @@
"presets.keep_dates_hint": "ไฟล์ที่แปลงแล้วจะได้วันที่สร้างและแก้ไขตามไฟล์ต้นฉบับ เพื่อให้ภาพถ่ายยังคงเรียงตามวันที่ได้ถูกต้อง",
"presets.zip_result": "บันทึกผลลัพธ์เป็น ZIP",
"presets.zip_result_hint": "ไฟล์ผลลัพธ์ทั้งหมด (เช่น .shp, .shx, .dbf, .prj และ .cpg ของ Shapefile) จะถูกรวมเป็น ZIP เดียวไว้ข้างไฟล์ต้นฉบับ แทนที่จะเป็นไฟล์แยกเดี่ยวๆ",
+ "presets.replace_original": "แทนที่ไฟล์ต้นฉบับ",
+ "presets.replace_original_hint": "ผลลัพธ์จะใช้ชื่อและตำแหน่งของไฟล์ต้นฉบับ และไฟล์ต้นฉบับจะถูกย้ายไปที่ถังขยะ เฉพาะเมื่อผลลัพธ์มีรูปแบบเดียวกัน และไม่ใช้กับโฟลเดอร์เฝ้าดูหรือไฟล์จากเบราว์เซอร์ หากย้ายไฟล์ต้นฉบับไปถังขยะไม่ได้ ไฟล์จะยังอยู่ และผลลัพธ์จะถูกบันทึกเป็นสำเนา",
"presets.conflict": "หากมีไฟล์ชื่อนี้อยู่แล้ว",
"presets.conflict.Rename": "เติมตัวเลขต่อท้าย",
"presets.conflict.Overwrite": "เขียนทับ",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index cfa40e2b..2eb4e285 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -110,6 +110,8 @@
"error.geo_unsupported_shape": "不支持此类形状",
"error.geo_too_large": "将超过 Shapefile 2 GB 的上限",
"notice.pdf_not_smaller": "无法再缩小,已原样复制",
+ "notice.original_kept": "已保留原文件,结果另存为副本",
+ "notice.original_in_trash": "原文件已在回收站/废纸篓中,结果保留了自己的名称",
"notice.empty_spreadsheet_pages_removed": "已移除电子表格中的空白页面",
"notice.live_photo_pair": "已保存为同名的照片和 MOV。将两者一起导入(iCloud 照片、隔空投送或 Mac 上的“照片”)即可得到实况照片",
"notice.geo_datum_assumed": "基准面不是 WGS 84,已按相同处理,位置可能偏差数百米",
@@ -619,6 +621,8 @@
"presets.keep_dates_hint": "转换后的文件沿用原文件的创建和修改日期,按日期排序的照片顺序不变。",
"presets.zip_result": "将结果保存为 ZIP",
"presets.zip_result_hint": "结果文件(Shapefile 的 .shp、.shx、.dbf、.prj 和 .cpg)会打包成原文件旁的一个 ZIP,而不是零散的文件。",
+ "presets.replace_original": "替换原文件",
+ "presets.replace_original_hint": "结果会使用原文件的名称和位置,原文件移到回收站/废纸篓。仅在结果格式相同时生效,监视文件夹和来自浏览器的文件不会替换。若原文件无法移到回收站/废纸篓,则保留原文件,结果另存为副本。",
"presets.conflict": "文件已存在时",
"presets.conflict.Rename": "添加编号",
"presets.conflict.Overwrite": "覆盖",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index 3fc0e8cf..836ab80f 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -110,6 +110,8 @@
"error.geo_unsupported_shape": "不支援此類形狀",
"error.geo_too_large": "將超過 Shapefile 2 GB 的上限",
"notice.pdf_not_smaller": "無法再縮小,已原樣複製",
+ "notice.original_kept": "已保留原始檔案,結果另存為副本",
+ "notice.original_in_trash": "原始檔案已在資源回收筒/垃圾桶中,結果保留了自己的名稱",
"notice.empty_spreadsheet_pages_removed": "已移除試算表中的空白頁面",
"notice.live_photo_pair": "已儲存為同名的照片和 MOV。將兩者一起匯入(iCloud 照片、隔空投送或 Mac 上的「照片」)即可得到原況照片",
"notice.geo_datum_assumed": "基準面不是 WGS 84,已按相同處理,位置可能偏差數百公尺",
@@ -619,6 +621,8 @@
"presets.keep_dates_hint": "轉換後的檔案沿用原始檔案的建立和修改日期,按日期排序的照片順序不變。",
"presets.zip_result": "將結果儲存為 ZIP",
"presets.zip_result_hint": "結果檔案(Shapefile 的 .shp、.shx、.dbf、.prj 和 .cpg)會打包成原始檔案旁的一個 ZIP,而不是零散的檔案。",
+ "presets.replace_original": "取代原始檔案",
+ "presets.replace_original_hint": "結果會使用原始檔案的名稱和位置,原始檔案移到資源回收筒/垃圾桶。僅在結果格式相同時生效,監看資料夾和來自瀏覽器的檔案不會取代。若原始檔案無法移到資源回收筒/垃圾桶,則保留原始檔案,結果另存為副本。",
"presets.conflict": "檔案已存在時",
"presets.conflict.Rename": "新增編號",
"presets.conflict.Overwrite": "覆蓋",
diff --git a/src/Filee.App/Services/AppHost.cs b/src/Filee.App/Services/AppHost.cs
index bb6164d7..a235b676 100644
--- a/src/Filee.App/Services/AppHost.cs
+++ b/src/Filee.App/Services/AppHost.cs
@@ -57,7 +57,8 @@ public static class AppHost
sp.GetRequiredService<ILogger<JobQueue>>(),
EngineRegistry.FindFileCombiner(sp.GetRequiredService<IReadOnlyList<IConverter>>()),
EngineRegistry.FindTiffMerger(sp.GetRequiredService<IReadOnlyList<IConverter>>()),
- EngineRegistry.FindMediaJoiner(sp.GetRequiredService<IReadOnlyList<IConverter>>())));
+ EngineRegistry.FindMediaJoiner(sp.GetRequiredService<IReadOnlyList<IConverter>>()),
+ sp.GetRequiredService<IPlatformServices>().MoveToTrash));
// Files dragged from a browser with only an address are downloaded without the browser's cookies.
services.AddSingleton(_ => new WebDownloader(userAgent: $"Filee/{typeof(AppHost).Assembly.GetName().Version?.ToString(3)}"));
diff --git a/src/Filee.App/ViewModels/JobViewModel.cs b/src/Filee.App/ViewModels/JobViewModel.cs
index 847abb66..0077e5e8 100644
--- a/src/Filee.App/ViewModels/JobViewModel.cs
+++ b/src/Filee.App/ViewModels/JobViewModel.cs
@@ -123,7 +123,7 @@ public sealed partial class JobViewModel : ObservableObject
var noted = Job.Files.Where(f => f.State == FileState.Done && f.NoticeKey is not null).ToList();
HasNotices = noted.Count > 0;
Notices = noted.Count == 0 ? null : string.Join(Environment.NewLine,
- noted.Select(f => $"{Path.GetFileName(f.SourcePath)} — {_loc[f.NoticeKey!]}"));
+ noted.Select(f => $"{Path.GetFileName(f.SourcePath)} — {FailureText.Reason(_loc, f.NoticeKey, f.NoticeDetail)}"));
var missingFonts = Job.Files.SelectMany(f => f.MissingFonts)
.Distinct(StringComparer.OrdinalIgnoreCase)
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 5758e1c0..7ad8ddce 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -166,6 +166,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_pattern = _edit.Output.FileNamePattern;
_keepDates = _edit.Output.KeepDates;
_zipResult = _edit.Output.ZipResult;
+ _replaceOriginal = _edit.Output.ReplaceOriginal;
}
public string PresetId => _original.Id;
@@ -404,6 +405,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private bool _keepDates;
/// <summary>Geospatial targets: the result is saved as one ZIP (OutputRule.ZipResult).</summary>
[ObservableProperty] private bool _zipResult;
+ /// <summary>The result takes the original's place, which goes to the Recycle Bin / Trash (OutputRule.ReplaceOriginal).</summary>
+ [ObservableProperty] private bool _replaceOriginal;
[ObservableProperty] private Choice<MediaQuality> _mediaQuality;
[ObservableProperty] private Choice<int> _maxHeight;
[ObservableProperty] private Choice<int> _audioBitrate;
@@ -655,6 +658,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
output.KeepDates = KeepDates;
// Only for geospatial targets, where it is offered: a box ticked for Shapefile must not zip a later PNG.
output.ZipResult = ShowZipResult && ZipResult;
+ output.ReplaceOriginal = ReplaceOriginal;
return true;
}
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 717ccbcc..3ff1ddc9 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -405,6 +405,11 @@
ToolTip.Tip="{DynamicResource presets.keep_dates_hint}" />
<CheckBox Content="{DynamicResource presets.zip_result}" IsChecked="{Binding ZipResult}" IsVisible="{Binding ShowZipResult}"
ToolTip.Tip="{DynamicResource presets.zip_result_hint}" />
+ <StackPanel>
+ <CheckBox Content="{DynamicResource presets.replace_original}" IsChecked="{Binding ReplaceOriginal}" />
+ <TextBlock Classes="caption" Text="{DynamicResource presets.replace_original_hint}" TextWrapping="Wrap"
+ IsVisible="{Binding ReplaceOriginal}" Margin="28,2,0,0" />
+ </StackPanel>
</StackPanel>
</Border>
</StackPanel>
diff --git a/src/Filee.Cli/Cli.cs b/src/Filee.Cli/Cli.cs
index 6c804886..d48fba0b 100644
--- a/src/Filee.Cli/Cli.cs
+++ b/src/Filee.Cli/Cli.cs
@@ -156,7 +156,7 @@ internal static class Cli
return file.State switch
{
FileState.Done => $"ok {source} -> {string.Join(", ", file.Outputs.Select(Shorten))}"
- + (file.NoticeKey is null ? "" : $" ({texts[file.NoticeKey]})")
+ + (file.NoticeKey is null ? "" : $" ({Notice(file, texts)})")
+ (file.MissingFonts.Count == 0 ? "" : $" (missing fonts: {string.Join(", ", file.MissingFonts)})"),
FileState.Skipped => $"skip {source} (the output file already exists)",
FileState.Cancelled => $"stop {source} (cancelled)",
@@ -170,6 +170,9 @@ internal static class Cli
return string.IsNullOrWhiteSpace(file.ErrorDetail) ? message : $"{message} ({file.ErrorDetail})";
}
+ private static string Notice(FileResult file, ILocalizer texts) =>
+ string.IsNullOrWhiteSpace(file.NoticeDetail) ? texts[file.NoticeKey!] : $"{texts[file.NoticeKey!]} ({file.NoticeDetail})";
+
/// <summary>Relative to the current folder when the file is inside it, else the full path.</summary>
private static string Shorten(string path)
{
@@ -201,7 +204,7 @@ internal static class Cli
if (file.State is FileState.Failed or FileState.Cancelled)
json.WriteString("error", Error(file, texts));
else if (file.NoticeKey is not null)
- json.WriteString("notice", texts[file.NoticeKey]);
+ json.WriteString("notice", Notice(file, texts));
if (file.MissingFonts.Count > 0)
{
json.WriteStartArray("missingFonts");
diff --git a/src/Filee.Core/Conversion/ConversionJob.cs b/src/Filee.Core/Conversion/ConversionJob.cs
index c3d2434e..d99a676a 100644
--- a/src/Filee.Core/Conversion/ConversionJob.cs
+++ b/src/Filee.Core/Conversion/ConversionJob.cs
@@ -57,6 +57,9 @@ public sealed class FileResult
/// </summary>
public string? NoticeKey { get; set; }
+ /// <summary>Non-localized detail shown after the notice in brackets (why the original was kept), or null.</summary>
+ public string? NoticeDetail { get; set; }
+
/// <summary>
/// Referenced document font families that weren't installed before rendering. Conversion still completes with the
/// renderer's substitutions; the UI can offer trusted sources afterwards.
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index a9ccbd8a..bd2f8269 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -29,6 +29,7 @@ public sealed class JobQueue : IAsyncDisposable
/// <summary>Output folders this queue made (a subfolder, a fixed folder that wasn't there): removed again when left empty.</summary>
private readonly HashSet<string> _madeFolders = new(Platform.FileSystemPaths.Comparer);
private readonly Task _worker;
+ private readonly Func<string, string?>? _moveToTrash;
private int _busy;
/// <param name="catalog">Converters and their priority.</param>
@@ -37,9 +38,14 @@ public sealed class JobQueue : IAsyncDisposable
/// <param name="combiner">Used by "Compress into one archive" presets (<see cref="ArchiveOptions.CombineIntoOne"/>).</param>
/// <param name="tiffMerger">Used by multi-page TIFF presets (<see cref="ImageOptions.MultiPageTiff"/>).</param>
/// <param name="mediaJoiner">Used by "Merge videos", "Merge audio" and "Video from images" (<see cref="Preset.JoinsIntoOneMedia"/>).</param>
+ /// <param name="moveToTrash">
+ /// Moves a file to the Recycle Bin / Trash for <see cref="OutputRule.ReplaceOriginal"/>: null when it worked, else
+ /// why not. Without it originals are always kept.
+ /// </param>
public JobQueue(ConverterCatalog catalog, IPdfMerger? pdfMerger = null, ILogger<JobQueue>? log = null, IFileCombiner? combiner = null,
- ITiffMerger? tiffMerger = null, IMediaJoiner? mediaJoiner = null)
+ ITiffMerger? tiffMerger = null, IMediaJoiner? mediaJoiner = null, Func<string, string?>? moveToTrash = null)
{
+ _moveToTrash = moveToTrash;
_catalog = catalog;
_pdfMerger = pdfMerger;
_combiner = combiner;
@@ -766,6 +772,9 @@ public sealed class JobQueue : IAsyncDisposable
else if (finalOutput && inputs.Count == 1 && final is { Handed: 1 })
inputs = [NextToSource(job, file, index, inputs[0], final)];
+ if (finalOutput && !zipResult && inputs.Count == 1)
+ inputs = [ReplaceOriginal(job, file, source.Id, inputs[0])];
+
// A name the engine took but wrote nothing to is free again.
final?.Release(except: inputs);
if (finalOutput)
@@ -985,6 +994,38 @@ public sealed class JobQueue : IAsyncDisposable
return true;
}
+ /// <summary>
+ /// "Replace the original" (<see cref="OutputRule.ReplaceOriginal"/>): moves the source to the Recycle Bin / Trash and
+ /// the finished <paramref name="output"/> to its path, which is returned. Anything that stops it keeps the source and
+ /// the output as they are, with a note saying why.
+ /// </summary>
+ private string ReplaceOriginal(ConversionJob job, FileResult file, string sourceFormat, string output)
+ {
+ if (!job.Preset.Output.ReplaceOriginal || job.Fetcher is not null || !File.Exists(output)
+ || FormatRegistry.Detect(output)?.Id != sourceFormat
+ || string.Equals(Path.GetFullPath(output), Path.GetFullPath(file.SourcePath), Platform.FileSystemPaths.Comparison))
+ return output;
+ var reason = _moveToTrash is null ? "no Recycle Bin / Trash here" : _moveToTrash(file.SourcePath);
+ if (reason is null)
+ {
+ try
+ {
+ File.Move(output, file.SourcePath);
+ return file.SourcePath;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // The original is already in the Trash: the result stays where it was written.
+ _log.LogWarning(ex, "Could not move {Output} to {Source}", output, file.SourcePath);
+ reason = ex.Message;
+ }
+ }
+ _log.LogInformation("Kept the original {Source}: {Reason}", file.SourcePath, reason);
+ file.NoticeKey = File.Exists(file.SourcePath) ? "notice.original_kept" : "notice.original_in_trash";
+ file.NoticeDetail = reason;
+ return output;
+ }
+
/// <summary>Lets go of <paramref name="path"/> (under the lock): free once nobody holds it.</summary>
private void Unreserve(string path)
{
diff --git a/src/Filee.Core/Platform/IPlatformServices.cs b/src/Filee.Core/Platform/IPlatformServices.cs
index ebb8d640..e402e942 100644
--- a/src/Filee.Core/Platform/IPlatformServices.cs
+++ b/src/Filee.Core/Platform/IPlatformServices.cs
@@ -21,6 +21,12 @@ public interface IPlatformServices
/// <summary>True if the window at the screen point belongs to the file manager or desktop. Coordinates are pixels on Windows/Linux and desktop points on macOS.</summary>
bool IsFileManagerAt(int x, int y);
+ /// <summary>
+ /// Moves a file to the Recycle Bin / Trash, where the user can restore it (<see cref="Presets.OutputRule.ReplaceOriginal"/>).
+ /// Null when it worked; otherwise why not, in a few words, and the file is left where it is.
+ /// </summary>
+ string? MoveToTrash(string path) => "there is no Recycle Bin / Trash here";
+
/// <summary>Process name (without extension) owning the window under the point, or <c>null</c>.</summary>
string? ProcessNameAt(int x, int y);
diff --git a/src/Filee.Core/Presets/OutputRule.cs b/src/Filee.Core/Presets/OutputRule.cs
index 5fa4930a..c9dc828b 100644
--- a/src/Filee.Core/Presets/OutputRule.cs
+++ b/src/Filee.Core/Presets/OutputRule.cs
@@ -91,6 +91,14 @@ public sealed class OutputRule
/// </summary>
public bool OnlyIfSmaller { get; set; }
+ /// <summary>
+ /// The result takes the original's place and the original goes to the Recycle Bin / Trash (#332): only when the
+ /// result has the source's format, only after it is complete, never for watch folders or files from a browser.
+ /// When the original can't be moved there (a network drive, a file still open elsewhere, no Trash), it stays and
+ /// the result is saved as usual, with a note saying why.
+ /// </summary>
+ public bool ReplaceOriginal { get; set; }
+
public OutputRule Clone()
{
var clone = (OutputRule)MemberwiseClone();
diff --git a/src/Filee.Core/Watching/WatchRule.cs b/src/Filee.Core/Watching/WatchRule.cs
index 8aa65134..9f85821d 100644
--- a/src/Filee.Core/Watching/WatchRule.cs
+++ b/src/Filee.Core/Watching/WatchRule.cs
@@ -69,6 +69,8 @@ public sealed class WatchRule
applied.Output.Location = OutputLocation.CustomFolder;
applied.Output.CustomFolder = ResolvedOutputFolder;
applied.Output.KeepFoldersFrom = Folder;
+ // A watch folder never replaces what it watches: the result would be converted again.
+ applied.Output.ReplaceOriginal = false;
if (!string.IsNullOrWhiteSpace(FileNamePattern))
applied.Output.FileNamePattern = FileNamePattern.Trim();
// Steps without a pattern are being typed; leaving them out keeps the name as it is.
diff --git a/src/Filee.Platform.Linux/FreedesktopTrash.cs b/src/Filee.Platform.Linux/FreedesktopTrash.cs
new file mode 100644
index 00000000..b3d6b5a4
--- /dev/null
+++ b/src/Filee.Platform.Linux/FreedesktopTrash.cs
@@ -0,0 +1,72 @@
+// The freedesktop.org Trash (Nautilus, Dolphin, Thunar, Nemo and `gio trash` all use it): the file moves into
+// Trash/files and a Trash/info/<name>.trashinfo records where it came from, so the file manager can restore it
+// (OutputRule.ReplaceOriginal, #332). Only the home Trash is used, and only for files on the same filesystem; others
+// are left where they are.
+
+using System.Globalization;
+using System.Text;
+
+namespace Filee.Platform.Linux;
+
+internal static class FreedesktopTrash
+{
+ /// <summary>Null when <paramref name="path"/> is in <paramref name="trash"/>, otherwise why it was left where it is.</summary>
+ public static string? Move(string path, string trash)
+ {
+ var full = Path.GetFullPath(path);
+ if (!File.Exists(full))
+ return "the file is gone";
+ var files = Path.Combine(trash, "files");
+ var info = Path.Combine(trash, "info");
+ try
+ {
+ Directory.CreateDirectory(files);
+ Directory.CreateDirectory(info);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return "there is no Trash folder";
+ }
+ if (MountOf(full) != MountOf(files))
+ return "the Trash is on another drive";
+
+ var name = Path.GetFileName(full);
+ for (var n = 2; File.Exists(Path.Combine(files, name)) || File.Exists(Path.Combine(info, name + ".trashinfo")); n++)
+ name = $"{Path.GetFileNameWithoutExtension(full)} {n}{Path.GetExtension(full)}";
+ var record = Path.Combine(info, name + ".trashinfo");
+ try
+ {
+ // The record first, as the spec asks: a crash in between leaves no file in the Trash without one.
+ using (var stream = new FileStream(record, FileMode.CreateNew, FileAccess.Write))
+ using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
+ {
+ writer.Write($"[Trash Info]\nPath={Escape(full)}\nDeletionDate={DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture)}\n");
+ }
+ File.Move(full, Path.Combine(files, name));
+ return null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ try { File.Delete(record); } catch (IOException) { }
+ return File.Exists(full) ? "it couldn't be moved to the Trash" : null;
+ }
+ }
+
+ /// <summary>The path in the record: each part URL-encoded, the slashes kept.</summary>
+ internal static string Escape(string path) => string.Join('/', path.Split('/').Select(Uri.EscapeDataString));
+
+ /// <summary>The mount point a path is on: the longest mounted root that contains it.</summary>
+ private static string MountOf(string path)
+ {
+ try
+ {
+ return DriveInfo.GetDrives().Select(d => d.RootDirectory.FullName)
+ .Where(r => path.StartsWith(r, StringComparison.Ordinal))
+ .OrderByDescending(r => r.Length).FirstOrDefault() ?? "/";
+ }
+ catch (IOException)
+ {
+ return "/";
+ }
+ }
+}
diff --git a/src/Filee.Platform.Linux/LinuxPlatformServices.cs b/src/Filee.Platform.Linux/LinuxPlatformServices.cs
index 15ae1143..6d1e8252 100644
--- a/src/Filee.Platform.Linux/LinuxPlatformServices.cs
+++ b/src/Filee.Platform.Linux/LinuxPlatformServices.cs
@@ -56,6 +56,8 @@ public sealed class LinuxPlatformServices : IPlatformServices
// Wayland can't say which window is under the cursor, so any Ctrl+drag may open the (invisible) donut window;
// it only shows when files are dragged in, and excluded apps can't be told apart there either.
+ public string? MoveToTrash(string path) => FreedesktopTrash.Move(path, Path.Combine(XdgDirectory("XDG_DATA_HOME", ".local/share"), "Trash"));
+
public bool IsFileManagerAt(int x, int y) =>
WaylandGestures || ProcessNameAt(x, y) is { } name && FileManagers.Contains(name);
public string? ProcessNameAt(int x, int y) => X11WindowSystem.ProcessNameAt(x, y);
diff --git a/src/Filee.Platform.MacOS/MacOSPlatformServices.cs b/src/Filee.Platform.MacOS/MacOSPlatformServices.cs
index 4b762a06..ad3e4284 100644
--- a/src/Filee.Platform.MacOS/MacOSPlatformServices.cs
+++ b/src/Filee.Platform.MacOS/MacOSPlatformServices.cs
@@ -32,6 +32,8 @@ public sealed class MacOSPlatformServices : IPlatformServices
public string? LastSelectionError { get; private set; }
+ public string? MoveToTrash(string path) => NativeMethods.MoveToTrash(path);
+
public bool IsFileManagerAt(int x, int y) =>
string.Equals(ProcessNameAt(x, y), "Finder", StringComparison.OrdinalIgnoreCase);
diff --git a/src/Filee.Platform.MacOS/NativeMethods.cs b/src/Filee.Platform.MacOS/NativeMethods.cs
index cb83919a..46628367 100644
--- a/src/Filee.Platform.MacOS/NativeMethods.cs
+++ b/src/Filee.Platform.MacOS/NativeMethods.cs
@@ -181,6 +181,34 @@ internal static class NativeMethods
return succeeded;
}
+ /// <summary>
+ /// NSFileManager trashItemAtURL: the file goes to the Trash of its volume, where Finder can put it back. Null when
+ /// it worked, else the reason macOS gives.
+ /// </summary>
+ public static string? MoveToTrash(string path)
+ {
+ using var pool = new AutoreleasePool();
+ var text = CFStringCreateWithCString(0, Path.GetFullPath(path), 0x08000100);
+ try
+ {
+ var url = Send(objc_getClass("NSURL"), sel_registerName("fileURLWithPath:"), text);
+ var manager = Send(objc_getClass("NSFileManager"), sel_registerName("defaultManager"));
+ if (SendTrash(manager, sel_registerName("trashItemAtURL:resultingItemURL:error:"), url, 0, out var error))
+ return null;
+ var description = error == 0 ? 0 : Send(error, sel_registerName("localizedDescription"));
+ return description == 0 ? "macOS couldn't move it to the Trash"
+ : Marshal.PtrToStringUTF8(Send(description, sel_registerName("UTF8String")));
+ }
+ finally
+ {
+ CFRelease(text);
+ }
+ }
+
+ [DllImport(ObjC, EntryPoint = "objc_msgSend")]
+ [return: MarshalAs(UnmanagedType.I1)]
+ private static extern bool SendTrash(nint receiver, nint selector, nint url, nint resultingUrl, out nint error);
+
private readonly struct AutoreleasePool : IDisposable
{
private readonly nint _pool = Send(Send(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc")), sel_registerName("init"));
diff --git a/src/Filee.Platform.Windows/RecycleBin.cs b/src/Filee.Platform.Windows/RecycleBin.cs
new file mode 100644
index 00000000..7813e264
--- /dev/null
+++ b/src/Filee.Platform.Windows/RecycleBin.cs
@@ -0,0 +1,69 @@
+// Moves a file to the Recycle Bin (OutputRule.ReplaceOriginal, #332). SHFileOperation with FOF_ALLOWUNDO deletes a
+// file for good on a drive without a Recycle Bin (network shares, most USB sticks), so only local fixed drives are
+// tried, and a file another program holds open is refused before Windows is asked.
+
+using System.Runtime.InteropServices;
+
+namespace Filee.Platform.Windows;
+
+internal static class RecycleBin
+{
+ private const uint FO_DELETE = 3;
+ private const ushort FOF_SILENT = 0x4;
+ private const ushort FOF_NOCONFIRMATION = 0x10;
+ private const ushort FOF_ALLOWUNDO = 0x40;
+ private const ushort FOF_NOERRORUI = 0x400;
+
+ /// <summary>Null when <paramref name="path"/> is in the Recycle Bin, otherwise why it was left where it is.</summary>
+ public static string? Move(string path)
+ {
+ var full = Path.GetFullPath(path);
+ if (!File.Exists(full))
+ return "the file is gone";
+ var root = Path.GetPathRoot(full);
+ if (string.IsNullOrEmpty(root) || root.StartsWith(@"\\", StringComparison.Ordinal)
+ || new DriveInfo(root).DriveType != DriveType.Fixed)
+ return "this drive has no Recycle Bin";
+ try
+ {
+ using (new FileStream(full, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
+ {
+ }
+ }
+ catch (IOException)
+ {
+ return "the file is open in another program";
+ }
+ catch (UnauthorizedAccessException)
+ {
+ return "the file is read-only or not yours to remove";
+ }
+
+ var operation = new SHFILEOPSTRUCTW
+ {
+ wFunc = FO_DELETE,
+ pFrom = full + "\0\0",
+ fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT,
+ };
+ var result = SHFileOperationW(ref operation);
+ if (result != 0 || operation.fAnyOperationsAborted || File.Exists(full))
+ return $"Windows couldn't move it to the Recycle Bin (0x{result:X})";
+ return null;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct SHFILEOPSTRUCTW
+ {
+ public nint hwnd;
+ public uint wFunc;
+ public string pFrom;
+ public string? pTo;
+ public ushort fFlags;
+ [MarshalAs(UnmanagedType.Bool)] public bool fAnyOperationsAborted;
+ public nint hNameMappings;
+ public string? lpszProgressTitle;
+ }
+
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
+ private static extern int SHFileOperationW(ref SHFILEOPSTRUCTW operation);
+}
diff --git a/src/Filee.Platform.Windows/WindowsPlatformServices.cs b/src/Filee.Platform.Windows/WindowsPlatformServices.cs
index 1c03fdd1..d580ba04 100644
--- a/src/Filee.Platform.Windows/WindowsPlatformServices.cs
+++ b/src/Filee.Platform.Windows/WindowsPlatformServices.cs
@@ -49,6 +49,8 @@ public sealed class WindowsPlatformServices : IPlatformServices
NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOACTIVATE | NativeMethods.SWP_NOOWNERZORDER);
}
+ public string? MoveToTrash(string path) => RecycleBin.Move(path);
+
public bool IsFileManagerAt(int x, int y)
{
var root = RootWindowAt(x, y);
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index c3c85b97..e4f96663 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1629,6 +1629,21 @@ public class RenderTests
Assert.False(preset.Output.ZipResult);
}
+ [AvaloniaFact]
+ public void Preset_editor_saves_replace_the_original_off_by_default()
+ {
+ TestServices.EnsureInitialized("en");
+ var preset = new Filee.Core.Presets.Preset { TargetFormat = Filee.Core.Presets.BuiltInData.SameAsSource, Name = "Trim" };
+ var vm = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());
+ Assert.False(vm.ReplaceOriginal);
+
+ vm.ReplaceOriginal = true;
+ Assert.True(vm.Apply());
+ Assert.True(preset.Output.ReplaceOriginal);
+ Assert.True(new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>()).ReplaceOriginal);
+ Assert.Contains("Recycle Bin / Trash", AppHost.Get<ILocalizer>()["presets.replace_original_hint"]);
+ }
+
[AvaloniaFact]
public void Preset_editor_saves_media_and_archive_options()
{
diff --git a/tests/Filee.Core.Tests/ReplaceOriginalTests.cs b/tests/Filee.Core.Tests/ReplaceOriginalTests.cs
new file mode 100644
index 00000000..aafc30c0
--- /dev/null
+++ b/tests/Filee.Core.Tests/ReplaceOriginalTests.cs
@@ -0,0 +1,158 @@
+// "Replace the original" (#332): the finished result takes the source's place and the source goes to the Trash, or
+// both are kept with a note saying why.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Core.Watching;
+
+namespace Filee.Core.Tests;
+
+public class ReplaceOriginalTests
+{
+ private static readonly Preset Replacing = new() { TargetFormat = BuiltInData.SameAsSource, Output = { ReplaceOriginal = true } };
+
+ /// <summary>Moves files into a folder, or refuses with <paramref name="refuse"/>.</summary>
+ private sealed class FakeTrash(string folder, string? refuse = null)
+ {
+ public List<string> Moved { get; } = [];
+
+ public string? Move(string path)
+ {
+ if (refuse is not null)
+ return refuse;
+ File.Move(path, Path.Combine(folder, Path.GetFileName(path)));
+ Moved.Add(path);
+ return null;
+ }
+ }
+
+ private static async Task<ConversionJob> Run(FakeTrash trash, string source, Preset preset, ISourceFetcher? fetcher = null)
+ {
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "jpg"), new ConversionEdge("jpg", "png"))]),
+ moveToTrash: trash.Move);
+ var job = new ConversionJob([source], preset, "Test", fetcher);
+ await queue.RunAsync(job);
+ return job;
+ }
+
+ [Fact]
+ public async Task The_result_takes_the_place_of_the_original_which_goes_to_the_trash()
+ {
+ using var dir = new TempDir();
+ using var bin = new TempDir();
+ var source = dir.File("a.jpg");
+ var trash = new FakeTrash(bin.Path);
+
+ var job = await Run(trash, source, Replacing);
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal([source], trash.Moved);
+ Assert.Equal([source], job.Outputs);
+ Assert.Equal("a.jpg→jpg by magick", File.ReadAllText(source));
+ Assert.Equal("x", File.ReadAllText(Path.Combine(bin.Path, "a.jpg")));
+ Assert.Equal([source], Directory.GetFiles(dir.Path));
+ Assert.Null(job.Files[0].NoticeKey);
+ }
+
+ [Fact]
+ public async Task When_the_trash_refuses_both_are_kept_with_the_reason()
+ {
+ using var dir = new TempDir();
+ var source = dir.File("a.jpg");
+
+ var job = await Run(new FakeTrash(dir.Path, refuse: "the file is open in another program"), source, Replacing);
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal("x", File.ReadAllText(source));
+ var output = Assert.Single(job.Outputs);
+ Assert.NotEqual(source, output);
+ Assert.True(File.Exists(output));
+ Assert.Equal("notice.original_kept", job.Files[0].NoticeKey);
+ Assert.Equal("the file is open in another program", job.Files[0].NoticeDetail);
+ }
+
+ [Fact]
+ public async Task Without_a_trash_the_original_is_kept()
+ {
+ using var dir = new TempDir();
+ var source = dir.File("a.jpg");
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "jpg"))]));
+ var job = new ConversionJob([source], Replacing, "Test");
+
+ await queue.RunAsync(job);
+
+ Assert.Equal("x", File.ReadAllText(source));
+ Assert.Equal(2, Directory.GetFiles(dir.Path).Length);
+ Assert.Equal("notice.original_kept", job.Files[0].NoticeKey);
+ }
+
+ [Fact]
+ public async Task Another_format_is_saved_beside_the_original()
+ {
+ using var dir = new TempDir();
+ using var bin = new TempDir();
+ var source = dir.File("a.jpg");
+ var trash = new FakeTrash(bin.Path);
+
+ var job = await Run(trash, source, new Preset { TargetFormat = "png", Output = { ReplaceOriginal = true } });
+
+ Assert.Empty(trash.Moved);
+ Assert.Equal("x", File.ReadAllText(source));
+ Assert.Equal([Path.Combine(dir.Path, "a.png")], job.Outputs);
+ Assert.Null(job.Files[0].NoticeKey);
+ }
+
+ [Fact]
+ public async Task Off_by_default()
+ {
+ using var dir = new TempDir();
+ using var bin = new TempDir();
+ var source = dir.File("a.jpg");
+ var trash = new FakeTrash(bin.Path);
+
+ await Run(trash, source, new Preset { TargetFormat = BuiltInData.SameAsSource });
+
+ Assert.False(new OutputRule().ReplaceOriginal);
+ Assert.Empty(trash.Moved);
+ Assert.Equal("x", File.ReadAllText(source));
+ }
+
+ [Fact]
+ public async Task Files_from_a_browser_are_never_replaced()
+ {
+ using var dir = new TempDir();
+ using var bin = new TempDir();
+ var source = dir.File("a.jpg");
+ var trash = new FakeTrash(bin.Path);
+
+ await Run(trash, source, Replacing, new LocalFetcher());
+
+ Assert.Empty(trash.Moved);
+ Assert.Equal("x", File.ReadAllText(source));
+ }
+
+ [Fact]
+ public void Watch_folders_never_replace_what_they_watch()
+ {
+ var rule = new WatchRule { Folder = "in", OutputFolder = "out" };
+
+ Assert.False(rule.Apply(Replacing).Output.ReplaceOriginal);
+ Assert.True(Replacing.Output.ReplaceOriginal);
+ }
+
+ [Fact]
+ public void Survives_a_preset_round_trip()
+ {
+ var copy = Replacing.Clone();
+
+ Assert.True(copy.Output.ReplaceOriginal);
+ }
+
+ /// <summary>A browser drop whose files are already on disk.</summary>
+ private sealed class LocalFetcher : ISourceFetcher
+ {
+ public bool Fetches(string source) => false;
+ public Task<string> FetchAsync(string source, IProgress<TransferProgress> progress, CancellationToken cancellationToken) => Task.FromResult(source);
+ public void Release(ConversionJob job) { }
+ }
+}
diff --git a/tests/Filee.Platform.Tests/TrashTests.cs b/tests/Filee.Platform.Tests/TrashTests.cs
new file mode 100644
index 00000000..e2add294
--- /dev/null
+++ b/tests/Filee.Platform.Tests/TrashTests.cs
@@ -0,0 +1,85 @@
+// Moving an original to the Recycle Bin / Trash for "Replace the original" (#332): it works where there is one, and
+// anything else leaves the file where it is with a reason.
+
+using Filee.Platform.Linux;
+using Filee.Platform.MacOS;
+using Filee.Platform.Windows;
+
+namespace Filee.Platform.Tests;
+
+public sealed class TrashTests : IDisposable
+{
+ private readonly string _root = Path.Combine(Path.GetTempPath(), "filee-trash-" + Guid.NewGuid().ToString("N"));
+
+ public TrashTests() => Directory.CreateDirectory(_root);
+
+ public void Dispose() => Directory.Delete(_root, recursive: true);
+
+ [Fact]
+ public void A_file_open_elsewhere_stays_in_the_Recycle_Bins_place()
+ {
+ if (!OperatingSystem.IsWindows())
+ {
+ Assert.Skip("Requires Windows.");
+ return;
+ }
+ var file = Path.Combine(_root, "open.png");
+ File.WriteAllText(file, "x");
+
+ string? reason;
+ using (new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
+ reason = new WindowsPlatformServices().MoveToTrash(file);
+
+ Assert.Equal("the file is open in another program", reason);
+ Assert.Equal("x", File.ReadAllText(file));
+ }
+
+ [Fact]
+ public void A_missing_file_gives_a_reason()
+ {
+ var missing = Path.Combine(_root, "gone.png");
+ if (OperatingSystem.IsWindows())
+ Assert.NotNull(new WindowsPlatformServices().MoveToTrash(missing));
+ else if (OperatingSystem.IsMacOS())
+ Assert.NotNull(new MacOSPlatformServices().MoveToTrash(missing));
+ Assert.NotNull(FreedesktopTrash.Move(missing, Path.Combine(_root, "Trash")));
+ }
+
+ [Fact]
+ public void The_freedesktop_Trash_records_where_the_file_came_from()
+ {
+ if (!OperatingSystem.IsLinux())
+ {
+ Assert.Skip("Requires Linux paths.");
+ return;
+ }
+ var trash = Path.Combine(_root, "Trash");
+ var first = Path.Combine(_root, "my photo.png");
+ File.WriteAllText(first, "1");
+ Assert.Null(FreedesktopTrash.Move(first, trash));
+ File.WriteAllText(first, "2");
+ Assert.Null(FreedesktopTrash.Move(first, trash));
+
+ Assert.False(File.Exists(first));
+ Assert.Equal("1", File.ReadAllText(Path.Combine(trash, "files", "my photo.png")));
+ Assert.Equal("2", File.ReadAllText(Path.Combine(trash, "files", "my photo 2.png")));
+ var info = File.ReadAllText(Path.Combine(trash, "info", "my photo 2.png.trashinfo"));
+ Assert.StartsWith("[Trash Info]\nPath=" + FreedesktopTrash.Escape(first) + "\nDeletionDate=", info);
+ Assert.Contains("my%20photo.png", info);
+ }
+
+ [Fact]
+ public void The_macOS_Trash_takes_the_file()
+ {
+ if (!OperatingSystem.IsMacOS())
+ {
+ Assert.Skip("Requires macOS.");
+ return;
+ }
+ var file = Path.Combine(_root, "trash-me.png");
+ File.WriteAllText(file, "x");
+
+ Assert.Null(new MacOSPlatformServices().MoveToTrash(file));
+ Assert.False(File.Exists(file));
+ }
+}