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
Filee's own Windows installer (src/Filee.Setup)
KnifeLemon40acdf83f12e
diff --git a/Filee.slnx b/Filee.slnxindex 01b89402..98faa9b4 100644--- a/Filee.slnx+++ b/Filee.slnx@@ -7,6 +7,7 @@<Project Path="src/Filee.Platform.MacOS/Filee.Platform.MacOS.csproj" /><Project Path="src/Filee.App/Filee.App.csproj" /><Project Path="src/Filee.Cli/Filee.Cli.csproj" />+ <Project Path="src/Filee.Setup/Filee.Setup.csproj" /></Folder><Folder Name="/tests/"><Project Path="tests/Filee.Core.Tests/Filee.Core.Tests.csproj" />@@ -14,6 +15,7 @@<Project Path="tests/Filee.App.Tests/Filee.App.Tests.csproj" /><Project Path="tests/Filee.Cli.Tests/Filee.Cli.Tests.csproj" /><Project Path="tests/Filee.Platform.Tests/Filee.Platform.Tests.csproj" />+ <Project Path="tests/Filee.Setup.Tests/Filee.Setup.Tests.csproj" /></Folder><Folder Name="/Solution Items/"><File Path="Directory.Build.props" />diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 730407ed..0cd20f98 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -634,6 +634,73 @@"setup.done": "Done","setup.selection": "Download: {0}","setup.nothing_selected": "Nothing selected",+ "installer.title": "Filee Setup",+ "installer.back": "Back",+ "installer.next": "Next",+ "installer.install": "Install",+ "installer.update": "Update",+ "installer.finish": "Finish",+ "installer.step.welcome": "Welcome",+ "installer.step.options": "Options",+ "installer.step.engines": "Engines",+ "installer.step.install": "Install",+ "installer.step.done": "Done",+ "installer.step.uninstall": "Confirm",+ "installer.step.remove": "Remove",+ "installer.welcome.title": "Welcome to Filee",+ "installer.welcome.fresh": "Setup installs Filee {0} on this computer.",+ "installer.welcome.update": "Filee {0} is installed. Setup updates it to {1}; your settings, presets and engines stay as they are.",+ "installer.welcome.about": "Filee converts files where you are: hold a key while dragging files, or right-click them in File Explorer, and pick a format.",+ "installer.welcome.license": "Filee is free and open source (MIT license).",+ "installer.language": "Language",+ "installer.options.title": "Choose how Filee fits in",+ "installer.options.folder": "Install folder",+ "installer.options.browse": "Change…",+ "installer.options.space": "Filee needs about {0} of disk space.",+ "installer.options.later": "You can change these later in Filee under Settings → General.",+ "installer.options.update_note": "Filee keeps its other settings. Change them any time in Filee under Settings → General.",+ "installer.task.modern_menu": "Also show it at the top of the Windows 11 menu, not only under “Show more options”",+ "installer.task.cli": "Add the “filee” command to PATH (convert from the command line)",+ "installer.task.desktop_icon": "Create a desktop shortcut",+ "installer.engines.when": "Filee downloads the engines you pick from their official sources when it starts.",+ "installer.progress.install": "Installing Filee",+ "installer.progress.update": "Updating Filee",+ "installer.status.verifying": "Checking the setup file…",+ "installer.status.closing": "Closing Filee…",+ "installer.status.removing_old": "Removing the previous version (settings and engines are kept)…",+ "installer.status.copying": "Copying Filee's files…",+ "installer.status.explorer_menu": "Adding Filee to the File Explorer menu…",+ "installer.status.finishing": "Finishing…",+ "installer.status.rolling_back": "Undoing the changes…",+ "installer.status.removing": "Removing Filee…",+ "installer.done.title": "Filee is ready",+ "installer.done.text": "Filee runs in the notification area of the taskbar.\n\nTo convert files, drag them while holding the trigger key, or right-click them in File Explorer.",+ "installer.done.updated": "Filee is updated. Your settings, presets and engines are as they were.",+ "installer.done.engines": "The conversion engines you picked download when Filee starts.",+ "installer.done.launch": "Launch Filee",+ "installer.warning.explorer_menu": "Windows did not add Filee to the top of the File Explorer menu:\n\n{0}\n\nFilee still appears under “Show more options”. You can try again in Filee under Settings → General.",+ "installer.warning.runtime": "{0} can't run: it needs the Microsoft Visual C++ runtime ({1}), which this computer doesn't have. Everything else in Filee works. To fix it, install Microsoft's Visual C++ Redistributable (x64):\n{2}",+ "installer.error.title": "Filee was not installed",+ "installer.error.uninstall_title": "Filee was not removed completely",+ "installer.error.space": "There isn't enough free space on {0}: Filee needs {1}, but only {2} is free.",+ "installer.error.damaged": "This setup file is damaged. Download it again from filee.sh.",+ "installer.error.files": "Setup couldn't write Filee's files: {0}",+ "installer.error.unexpected": "Something went wrong: {0}",+ "installer.error.windows": "Filee needs 64-bit Windows 10 version 1809 or later.",+ "installer.error.rolled_back": "Setup put everything back: the previous Filee still works.",+ "installer.error.undone": "Setup undid its changes.",+ "installer.error.nothing_changed": "Nothing on this computer was changed.",+ "installer.error.log": "Details are in the log: {0}",+ "installer.uninstall.title": "Uninstall Filee",+ "installer.uninstall.text": "This removes Filee {0} from this computer, with its File Explorer menu entries, its startup entry and the conversion engines it downloaded.",+ "installer.uninstall.delete_settings": "Also delete my settings, presets and toolbars",+ "installer.uninstall.settings_where": "They are in {0}. Keep them to have them back when you install Filee again.",+ "installer.uninstall.button": "Uninstall",+ "installer.uninstall.progress": "Removing Filee",+ "installer.uninstall.done_title": "Filee was removed",+ "installer.uninstall.done": "Filee is no longer on this computer.",+ "installer.uninstall.settings_kept": "Your settings stay, for when you install Filee again.",+ "installer.uninstall.not_installed": "Filee is not installed in {0}.","watch.title": "Watch folders","watch.description": "Files that land in these folders are converted while Filee runs.\nDownloads and copies wait until they're complete.","watch.add": "Add folder",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex 033e997a..9d99f4af 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -615,6 +615,73 @@"setup.done": "Hecho","setup.selection": "Descarga: {0}","setup.nothing_selected": "Nada seleccionado",+ "installer.title": "Instalación de Filee",+ "installer.back": "Atrás",+ "installer.next": "Siguiente",+ "installer.install": "Instalar",+ "installer.update": "Actualizar",+ "installer.finish": "Finalizar",+ "installer.step.welcome": "Bienvenida",+ "installer.step.options": "Opciones",+ "installer.step.engines": "Motores",+ "installer.step.install": "Instalación",+ "installer.step.done": "Listo",+ "installer.step.uninstall": "Confirmar",+ "installer.step.remove": "Quitar",+ "installer.welcome.title": "Te damos la bienvenida a Filee",+ "installer.welcome.fresh": "El instalador instalará Filee {0} en este equipo.",+ "installer.welcome.update": "Filee {0} está instalado. El instalador lo actualizará a {1}; tus ajustes, ajustes preestablecidos y motores se mantienen.",+ "installer.welcome.about": "Filee convierte archivos donde estés: mantén pulsada una tecla mientras arrastras archivos, o haz clic derecho sobre ellos en el Explorador, y elige un formato.",+ "installer.welcome.license": "Filee es libre y de código abierto (licencia MIT).",+ "installer.language": "Idioma",+ "installer.options.title": "Elige cómo se integra Filee",+ "installer.options.folder": "Carpeta de instalación",+ "installer.options.browse": "Cambiar…",+ "installer.options.space": "Filee necesita unos {0} de espacio en disco.",+ "installer.options.later": "Puedes cambiarlo más tarde en Filee, en Ajustes → General.",+ "installer.options.update_note": "Filee conserva sus demás ajustes. Cámbialos cuando quieras en Filee, en Ajustes → General.",+ "installer.task.modern_menu": "Mostrarlo también arriba en el menú de Windows 11, no solo en «Mostrar más opciones»",+ "installer.task.cli": "Añadir el comando «filee» al PATH (convertir desde la línea de comandos)",+ "installer.task.desktop_icon": "Crear un acceso directo en el escritorio",+ "installer.engines.when": "Filee descarga los motores que elijas desde sus fuentes oficiales al iniciarse.",+ "installer.progress.install": "Instalando Filee",+ "installer.progress.update": "Actualizando Filee",+ "installer.status.verifying": "Comprobando el archivo de instalación…",+ "installer.status.closing": "Cerrando Filee…",+ "installer.status.removing_old": "Quitando la versión anterior (los ajustes y motores se mantienen)…",+ "installer.status.copying": "Copiando los archivos de Filee…",+ "installer.status.explorer_menu": "Añadiendo Filee al menú del Explorador…",+ "installer.status.finishing": "Terminando…",+ "installer.status.rolling_back": "Deshaciendo los cambios…",+ "installer.status.removing": "Quitando Filee…",+ "installer.done.title": "Filee está listo",+ "installer.done.text": "Filee se ejecuta en el área de notificación de la barra de tareas.\n\nPara convertir archivos, arrástralos mientras mantienes pulsada la tecla de activación, o haz clic derecho sobre ellos en el Explorador.",+ "installer.done.updated": "Filee se ha actualizado. Tus ajustes, ajustes preestablecidos y motores siguen igual.",+ "installer.done.engines": "Los motores de conversión que elegiste se descargan cuando Filee se inicia.",+ "installer.done.launch": "Iniciar Filee",+ "installer.warning.explorer_menu": "Windows no añadió Filee a la parte superior del menú del Explorador:\n\n{0}\n\nFilee sigue apareciendo en «Mostrar más opciones». Puedes volver a intentarlo en Filee, en Ajustes → General.",+ "installer.warning.runtime": "{0} no puede ejecutarse: necesita el runtime de Microsoft Visual C++ ({1}), que este equipo no tiene. El resto de Filee funciona. Para solucionarlo, instala el Visual C++ Redistributable (x64) de Microsoft:\n{2}",+ "installer.error.title": "Filee no se instaló",+ "installer.error.uninstall_title": "Filee no se quitó por completo",+ "installer.error.space": "No hay suficiente espacio libre en {0}: Filee necesita {1}, pero solo quedan {2}.",+ "installer.error.damaged": "Este archivo de instalación está dañado. Descárgalo de nuevo desde filee.sh.",+ "installer.error.files": "El instalador no pudo escribir los archivos de Filee: {0}",+ "installer.error.unexpected": "Algo salió mal: {0}",+ "installer.error.windows": "Filee necesita Windows 10 de 64 bits, versión 1809 o posterior.",+ "installer.error.rolled_back": "El instalador lo dejó todo como estaba: la versión anterior de Filee sigue funcionando.",+ "installer.error.undone": "El instalador deshizo sus cambios.",+ "installer.error.nothing_changed": "No se cambió nada en este equipo.",+ "installer.error.log": "Los detalles están en el registro: {0}",+ "installer.uninstall.title": "Desinstalar Filee",+ "installer.uninstall.text": "Esto quita Filee {0} de este equipo, junto con sus entradas del menú del Explorador, su inicio automático y los motores de conversión que descargó.",+ "installer.uninstall.delete_settings": "Eliminar también mis ajustes, ajustes preestablecidos y barras de herramientas",+ "installer.uninstall.settings_where": "Están en {0}. Si los conservas, volverán cuando instales Filee de nuevo.",+ "installer.uninstall.button": "Desinstalar",+ "installer.uninstall.progress": "Quitando Filee",+ "installer.uninstall.done_title": "Filee se ha quitado",+ "installer.uninstall.done": "Filee ya no está en este equipo.",+ "installer.uninstall.settings_kept": "Tus ajustes se conservan para cuando vuelvas a instalar Filee.",+ "installer.uninstall.not_installed": "Filee no está instalado en {0}.","watch.title": "Carpetas supervisadas","watch.description": "Los archivos que lleguen a estas carpetas se convierten mientras Filee esté en ejecución.\nLas descargas y las copias se convierten cuando terminan.","watch.add": "Añadir carpeta",diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.jsonindex 66a74ca9..e77728c6 100644--- a/src/Filee.App/Assets/i18n/hi.json+++ b/src/Filee.App/Assets/i18n/hi.json@@ -615,6 +615,73 @@"setup.done": "हो गया","setup.selection": "डाउनलोड: {0}","setup.nothing_selected": "कुछ भी चुना नहीं गया",+ "installer.title": "Filee सेटअप",+ "installer.back": "पीछे",+ "installer.next": "आगे",+ "installer.install": "इंस्टॉल करें",+ "installer.update": "अपडेट करें",+ "installer.finish": "समाप्त",+ "installer.step.welcome": "स्वागत",+ "installer.step.options": "विकल्प",+ "installer.step.engines": "इंजन",+ "installer.step.install": "इंस्टॉल",+ "installer.step.done": "हो गया",+ "installer.step.uninstall": "पुष्टि",+ "installer.step.remove": "हटाना",+ "installer.welcome.title": "Filee में आपका स्वागत है",+ "installer.welcome.fresh": "सेटअप इस कंप्यूटर पर Filee {0} इंस्टॉल करेगा।",+ "installer.welcome.update": "Filee {0} पहले से इंस्टॉल है। सेटअप इसे {1} में अपडेट करेगा; आपकी सेटिंग्स, प्रीसेट और इंजन वैसे ही रहेंगे।",+ "installer.welcome.about": "Filee फ़ाइलों को वहीं कन्वर्ट करता है जहाँ आप हैं: कोई कुंजी दबाए रखकर फ़ाइलें खींचें, या Explorer में उन पर राइट-क्लिक करें, और फ़ॉर्मेट चुनें।",+ "installer.welcome.license": "Filee मुफ़्त और ओपन सोर्स है (MIT लाइसेंस)।",+ "installer.language": "भाषा",+ "installer.options.title": "चुनें कि Filee कैसे काम करे",+ "installer.options.folder": "इंस्टॉल फ़ोल्डर",+ "installer.options.browse": "बदलें…",+ "installer.options.space": "Filee को लगभग {0} डिस्क स्थान चाहिए।",+ "installer.options.later": "आप इन्हें बाद में Filee में सेटिंग्स → सामान्य में बदल सकते हैं।",+ "installer.options.update_note": "Filee की बाकी सेटिंग्स वैसी ही रहेंगी। उन्हें कभी भी Filee में सेटिंग्स → सामान्य में बदलें।",+ "installer.task.modern_menu": "Windows 11 मेनू में सबसे ऊपर भी दिखाएँ, सिर्फ़ “और विकल्प दिखाएँ” में नहीं",+ "installer.task.cli": "“filee” कमांड को PATH में जोड़ें (कमांड लाइन से कन्वर्ट करें)",+ "installer.task.desktop_icon": "डेस्कटॉप शॉर्टकट बनाएँ",+ "installer.engines.when": "Filee शुरू होने पर आपके चुने इंजन उनके आधिकारिक स्रोतों से डाउनलोड करता है।",+ "installer.progress.install": "Filee इंस्टॉल हो रहा है",+ "installer.progress.update": "Filee अपडेट हो रहा है",+ "installer.status.verifying": "सेटअप फ़ाइल जाँची जा रही है…",+ "installer.status.closing": "Filee बंद किया जा रहा है…",+ "installer.status.removing_old": "पिछला संस्करण हटाया जा रहा है (सेटिंग्स और इंजन रहेंगे)…",+ "installer.status.copying": "Filee की फ़ाइलें कॉपी हो रही हैं…",+ "installer.status.explorer_menu": "Filee को Explorer मेनू में जोड़ा जा रहा है…",+ "installer.status.finishing": "पूरा किया जा रहा है…",+ "installer.status.rolling_back": "बदलाव वापस लिए जा रहे हैं…",+ "installer.status.removing": "Filee हटाया जा रहा है…",+ "installer.done.title": "Filee तैयार है",+ "installer.done.text": "Filee टास्कबार के सूचना क्षेत्र में चलता है।\n\nफ़ाइलें कन्वर्ट करने के लिए ट्रिगर कुंजी दबाए रखकर उन्हें खींचें, या Explorer में उन पर राइट-क्लिक करें।",+ "installer.done.updated": "Filee अपडेट हो गया। आपकी सेटिंग्स, प्रीसेट और इंजन पहले जैसे हैं।",+ "installer.done.engines": "आपके चुने कन्वर्ज़न इंजन Filee शुरू होने पर डाउनलोड होंगे।",+ "installer.done.launch": "Filee चलाएँ",+ "installer.warning.explorer_menu": "Windows ने Filee को Explorer मेनू में सबसे ऊपर नहीं जोड़ा:\n\n{0}\n\nFilee अब भी “और विकल्प दिखाएँ” में दिखता है। आप Filee में सेटिंग्स → सामान्य से फिर कोशिश कर सकते हैं।",+ "installer.warning.runtime": "{0} नहीं चल सकता: इसे Microsoft Visual C++ रनटाइम ({1}) चाहिए, जो इस कंप्यूटर पर नहीं है। Filee का बाकी सब काम करता है। ठीक करने के लिए Microsoft का Visual C++ Redistributable (x64) इंस्टॉल करें:\n{2}",+ "installer.error.title": "Filee इंस्टॉल नहीं हुआ",+ "installer.error.uninstall_title": "Filee पूरी तरह नहीं हटा",+ "installer.error.space": "{0} पर पर्याप्त खाली जगह नहीं है: Filee को {1} चाहिए, लेकिन सिर्फ़ {2} खाली है।",+ "installer.error.damaged": "यह सेटअप फ़ाइल खराब है। इसे filee.sh से फिर डाउनलोड करें।",+ "installer.error.files": "सेटअप Filee की फ़ाइलें नहीं लिख सका: {0}",+ "installer.error.unexpected": "कुछ गड़बड़ हो गई: {0}",+ "installer.error.windows": "Filee को 64-बिट Windows 10 संस्करण 1809 या नया चाहिए।",+ "installer.error.rolled_back": "सेटअप ने सब कुछ पहले जैसा कर दिया: पिछला Filee अब भी काम करता है।",+ "installer.error.undone": "सेटअप ने अपने बदलाव वापस ले लिए।",+ "installer.error.nothing_changed": "इस कंप्यूटर पर कुछ नहीं बदला।",+ "installer.error.log": "विवरण लॉग में है: {0}",+ "installer.uninstall.title": "Filee अनइंस्टॉल करें",+ "installer.uninstall.text": "यह इस कंप्यूटर से Filee {0} को हटाता है, साथ में उसकी Explorer मेनू प्रविष्टियाँ, स्टार्टअप प्रविष्टि और डाउनलोड किए गए कन्वर्ज़न इंजन भी।",+ "installer.uninstall.delete_settings": "मेरी सेटिंग्स, प्रीसेट और टूलबार भी मिटाएँ",+ "installer.uninstall.settings_where": "ये {0} में हैं। रखेंगे तो Filee दोबारा इंस्टॉल करने पर वापस मिल जाएँगी।",+ "installer.uninstall.button": "अनइंस्टॉल करें",+ "installer.uninstall.progress": "Filee हटाया जा रहा है",+ "installer.uninstall.done_title": "Filee हटा दिया गया",+ "installer.uninstall.done": "Filee अब इस कंप्यूटर पर नहीं है।",+ "installer.uninstall.settings_kept": "आपकी सेटिंग्स रखी गई हैं, ताकि Filee दोबारा इंस्टॉल करने पर काम आएँ।",+ "installer.uninstall.not_installed": "{0} में Filee इंस्टॉल नहीं है।","watch.title": "वॉच फ़ोल्डर","watch.description": "इन फ़ोल्डरों में आने वाली फ़ाइलें Filee चलते समय कन्वर्ट हो जाती हैं।\nडाउनलोड और कॉपी पूरी होने तक प्रतीक्षा करते हैं।","watch.add": "फ़ोल्डर जोड़ें",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 3f5d09bb..71c35334 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -634,6 +634,73 @@"setup.done": "완료","setup.selection": "다운로드: {0}","setup.nothing_selected": "선택한 엔진 없음",+ "installer.title": "Filee 설치",+ "installer.back": "이전",+ "installer.next": "다음",+ "installer.install": "설치",+ "installer.update": "업데이트",+ "installer.finish": "마침",+ "installer.step.welcome": "시작",+ "installer.step.options": "옵션",+ "installer.step.engines": "엔진",+ "installer.step.install": "설치",+ "installer.step.done": "완료",+ "installer.step.uninstall": "확인",+ "installer.step.remove": "제거",+ "installer.welcome.title": "Filee에 오신 걸 환영해요",+ "installer.welcome.fresh": "이 컴퓨터에 Filee {0} 버전을 설치해요.",+ "installer.welcome.update": "Filee {0} 버전이 설치되어 있어요. {1} 버전으로 업데이트하고, 설정·프리셋·엔진은 그대로 둬요.",+ "installer.welcome.about": "Filee는 지금 있는 자리에서 파일을 변환해요. 키를 누른 채 파일을 끌거나 탐색기에서 우클릭하고 형식을 고르면 돼요.",+ "installer.welcome.license": "Filee는 무료 오픈 소스예요 (MIT 라이선스).",+ "installer.language": "언어",+ "installer.options.title": "Filee를 어떻게 쓸지 골라 주세요",+ "installer.options.folder": "설치 폴더",+ "installer.options.browse": "변경…",+ "installer.options.space": "디스크 공간이 약 {0} 필요해요.",+ "installer.options.later": "나중에 Filee의 설정 → 일반에서 바꿀 수 있어요.",+ "installer.options.update_note": "다른 설정은 그대로 유지돼요. 언제든 Filee의 설정 → 일반에서 바꿀 수 있어요.",+ "installer.task.modern_menu": "Windows 11 기본 메뉴에도 표시 (“추가 옵션 표시”를 누르지 않아도 보여요)",+ "installer.task.cli": "“filee” 명령어를 PATH에 추가 (명령줄에서 변환)",+ "installer.task.desktop_icon": "바탕 화면 바로 가기 만들기",+ "installer.engines.when": "고른 엔진은 Filee가 시작하면서 공식 배포처에서 내려받아요.",+ "installer.progress.install": "Filee 설치 중",+ "installer.progress.update": "Filee 업데이트 중",+ "installer.status.verifying": "설치 파일을 확인하는 중…",+ "installer.status.closing": "Filee를 종료하는 중…",+ "installer.status.removing_old": "이전 버전을 정리하는 중 (설정과 엔진은 그대로 둬요)…",+ "installer.status.copying": "Filee 파일을 복사하는 중…",+ "installer.status.explorer_menu": "탐색기 메뉴에 Filee를 추가하는 중…",+ "installer.status.finishing": "마무리하는 중…",+ "installer.status.rolling_back": "변경 사항을 되돌리는 중…",+ "installer.status.removing": "Filee를 제거하는 중…",+ "installer.done.title": "Filee 준비 완료",+ "installer.done.text": "Filee는 작업 표시줄 알림 영역에서 실행돼요.\n\n파일을 변환하려면 지정한 키를 누른 채 파일을 끌거나, 탐색기에서 파일을 우클릭하세요.",+ "installer.done.updated": "Filee를 업데이트했어요. 설정, 프리셋, 엔진은 그대로예요.",+ "installer.done.engines": "선택한 변환 엔진은 Filee가 시작하면 내려받아요.",+ "installer.done.launch": "Filee 실행",+ "installer.warning.explorer_menu": "Windows가 탐색기 기본 메뉴에 Filee를 추가하지 못했어요:\n\n{0}\n\nFilee는 “추가 옵션 표시” 안에는 계속 나타나요. Filee의 설정 → 일반에서 다시 시도할 수 있어요.",+ "installer.warning.runtime": "{0}을(를) 실행할 수 없어요. 이 컴퓨터에 없는 Microsoft Visual C++ 런타임({1})이 필요해요. Filee의 나머지 기능은 정상이에요. Microsoft의 Visual C++ 재배포 가능 패키지(x64)를 설치하면 해결돼요:\n{2}",+ "installer.error.title": "Filee를 설치하지 못했어요",+ "installer.error.uninstall_title": "Filee를 모두 제거하지 못했어요",+ "installer.error.space": "{0}에 빈 공간이 부족해요. Filee에 {1}이(가) 필요한데 {2}만 남아 있어요.",+ "installer.error.damaged": "설치 파일이 손상됐어요. filee.sh에서 다시 내려받아 주세요.",+ "installer.error.files": "Filee 파일을 쓰지 못했어요: {0}",+ "installer.error.unexpected": "문제가 생겼어요: {0}",+ "installer.error.windows": "Filee는 64비트 Windows 10 버전 1809 이상이 필요해요.",+ "installer.error.rolled_back": "모든 변경 사항을 되돌렸어요. 이전 Filee는 그대로 쓸 수 있어요.",+ "installer.error.undone": "변경 사항을 되돌렸어요.",+ "installer.error.nothing_changed": "이 컴퓨터에서 바뀐 것은 없어요.",+ "installer.error.log": "자세한 내용은 로그에 있어요: {0}",+ "installer.uninstall.title": "Filee 제거",+ "installer.uninstall.text": "이 컴퓨터에서 Filee {0}을(를) 제거해요. 탐색기 메뉴 항목, 시작 프로그램 항목, 내려받은 변환 엔진도 함께 지워요.",+ "installer.uninstall.delete_settings": "설정, 프리셋, 툴바도 삭제",+ "installer.uninstall.settings_where": "{0}에 있어요. 남겨 두면 Filee를 다시 설치할 때 그대로 돌아와요.",+ "installer.uninstall.button": "제거",+ "installer.uninstall.progress": "Filee 제거 중",+ "installer.uninstall.done_title": "Filee를 제거했어요",+ "installer.uninstall.done": "Filee가 이 컴퓨터에서 제거됐어요.",+ "installer.uninstall.settings_kept": "설정은 남겨 뒀어요. Filee를 다시 설치하면 그대로 쓸 수 있어요.",+ "installer.uninstall.not_installed": "{0}에 Filee가 설치되어 있지 않아요.","watch.title": "자동 변환 폴더","watch.description": "Filee가 켜져 있는 동안 이 폴더에 들어온 파일을 자동으로 변환해요.\n다운로드·복사 중인 파일은 끝난 뒤에 변환해요.","watch.add": "폴더 추가",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 655a9180..ff377ccc 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -634,6 +634,73 @@"setup.done": "Gotowe","setup.selection": "Pobieranie: {0}","setup.nothing_selected": "Nic nie wybrano",+ "installer.title": "Instalator Filee",+ "installer.back": "Wstecz",+ "installer.next": "Dalej",+ "installer.install": "Zainstaluj",+ "installer.update": "Zaktualizuj",+ "installer.finish": "Zakończ",+ "installer.step.welcome": "Powitanie",+ "installer.step.options": "Opcje",+ "installer.step.engines": "Silniki",+ "installer.step.install": "Instalacja",+ "installer.step.done": "Gotowe",+ "installer.step.uninstall": "Potwierdzenie",+ "installer.step.remove": "Usuwanie",+ "installer.welcome.title": "Witaj w Filee",+ "installer.welcome.fresh": "Instalator zainstaluje Filee {0} na tym komputerze.",+ "installer.welcome.update": "Filee {0} jest zainstalowany. Instalator zaktualizuje go do wersji {1}; ustawienia, ustawienia wstępne i silniki pozostaną bez zmian.",+ "installer.welcome.about": "Filee konwertuje pliki tam, gdzie jesteś: przytrzymaj klawisz podczas przeciągania plików albo kliknij je prawym przyciskiem w Eksploratorze i wybierz format.",+ "installer.welcome.license": "Filee jest darmowy i ma otwarty kod źródłowy (licencja MIT).",+ "installer.language": "Język",+ "installer.options.title": "Wybierz, jak Filee ma działać",+ "installer.options.folder": "Folder instalacji",+ "installer.options.browse": "Zmień…",+ "installer.options.space": "Filee potrzebuje około {0} miejsca na dysku.",+ "installer.options.later": "Możesz to później zmienić w Filee: Ustawienia → Ogólne.",+ "installer.options.update_note": "Pozostałe ustawienia Filee nie zmienią się. Możesz je zmienić w każdej chwili w Filee: Ustawienia → Ogólne.",+ "installer.task.modern_menu": "Pokazuj też na górze menu Windows 11, nie tylko w „Pokaż więcej opcji”",+ "installer.task.cli": "Dodaj polecenie „filee” do PATH (konwersja z wiersza poleceń)",+ "installer.task.desktop_icon": "Utwórz skrót na pulpicie",+ "installer.engines.when": "Po uruchomieniu Filee pobierze wybrane silniki z ich oficjalnych źródeł.",+ "installer.progress.install": "Instalowanie Filee",+ "installer.progress.update": "Aktualizowanie Filee",+ "installer.status.verifying": "Sprawdzanie pliku instalacyjnego…",+ "installer.status.closing": "Zamykanie Filee…",+ "installer.status.removing_old": "Usuwanie poprzedniej wersji (ustawienia i silniki zostają)…",+ "installer.status.copying": "Kopiowanie plików Filee…",+ "installer.status.explorer_menu": "Dodawanie Filee do menu Eksploratora…",+ "installer.status.finishing": "Kończenie…",+ "installer.status.rolling_back": "Cofanie zmian…",+ "installer.status.removing": "Usuwanie Filee…",+ "installer.done.title": "Filee jest gotowy",+ "installer.done.text": "Filee działa w obszarze powiadomień paska zadań.\n\nAby przekonwertować pliki, przeciągnij je, przytrzymując klawisz wyzwalający, albo kliknij je prawym przyciskiem w Eksploratorze.",+ "installer.done.updated": "Filee został zaktualizowany. Ustawienia, ustawienia wstępne i silniki są takie jak wcześniej.",+ "installer.done.engines": "Wybrane silniki konwersji zostaną pobrane po uruchomieniu Filee.",+ "installer.done.launch": "Uruchom Filee",+ "installer.warning.explorer_menu": "Windows nie dodał Filee na górę menu Eksploratora:\n\n{0}\n\nFilee nadal jest dostępny w „Pokaż więcej opcji”. Możesz spróbować ponownie w Filee: Ustawienia → Ogólne.",+ "installer.warning.runtime": "Nie można uruchomić {0}: wymaga środowiska Microsoft Visual C++ ({1}), którego nie ma na tym komputerze. Reszta Filee działa. Aby to naprawić, zainstaluj Microsoft Visual C++ Redistributable (x64):\n{2}",+ "installer.error.title": "Nie zainstalowano Filee",+ "installer.error.uninstall_title": "Nie usunięto Filee całkowicie",+ "installer.error.space": "Za mało miejsca na {0}: Filee potrzebuje {1}, a wolne jest tylko {2}.",+ "installer.error.damaged": "Plik instalacyjny jest uszkodzony. Pobierz go ponownie z filee.sh.",+ "installer.error.files": "Instalator nie mógł zapisać plików Filee: {0}",+ "installer.error.unexpected": "Coś poszło nie tak: {0}",+ "installer.error.windows": "Filee wymaga 64-bitowego systemu Windows 10 w wersji 1809 lub nowszej.",+ "installer.error.rolled_back": "Instalator przywrócił wszystko: poprzednia wersja Filee nadal działa.",+ "installer.error.undone": "Instalator cofnął swoje zmiany.",+ "installer.error.nothing_changed": "Na tym komputerze nic nie zostało zmienione.",+ "installer.error.log": "Szczegóły są w dzienniku: {0}",+ "installer.uninstall.title": "Odinstaluj Filee",+ "installer.uninstall.text": "Spowoduje to usunięcie Filee {0} z tego komputera wraz z pozycjami w menu Eksploratora, autostartem i pobranymi silnikami konwersji.",+ "installer.uninstall.delete_settings": "Usuń też moje ustawienia, ustawienia wstępne i paski narzędzi",+ "installer.uninstall.settings_where": "Znajdują się w {0}. Jeśli je zostawisz, wrócą po ponownej instalacji Filee.",+ "installer.uninstall.button": "Odinstaluj",+ "installer.uninstall.progress": "Usuwanie Filee",+ "installer.uninstall.done_title": "Usunięto Filee",+ "installer.uninstall.done": "Filee nie ma już na tym komputerze.",+ "installer.uninstall.settings_kept": "Ustawienia zostały zachowane na wypadek ponownej instalacji Filee.",+ "installer.uninstall.not_installed": "Filee nie jest zainstalowany w {0}.","watch.title": "Obserwowane foldery","watch.description": "Pliki trafiające do tych folderów są konwertowane, gdy Filee działa.\nPobierane i kopiowane pliki czekają na zakończenie.","watch.add": "Dodaj folder",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex dcaae0b4..36b5f650 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -634,6 +634,73 @@"setup.done": "完成","setup.selection": "下载:{0}","setup.nothing_selected": "未选择引擎",+ "installer.title": "Filee 安装程序",+ "installer.back": "上一步",+ "installer.next": "下一步",+ "installer.install": "安装",+ "installer.update": "更新",+ "installer.finish": "完成",+ "installer.step.welcome": "欢迎",+ "installer.step.options": "选项",+ "installer.step.engines": "引擎",+ "installer.step.install": "安装",+ "installer.step.done": "完成",+ "installer.step.uninstall": "确认",+ "installer.step.remove": "移除",+ "installer.welcome.title": "欢迎使用 Filee",+ "installer.welcome.fresh": "安装程序将在这台电脑上安装 Filee {0}。",+ "installer.welcome.update": "已安装 Filee {0}。安装程序会将其更新到 {1},设置、预设和引擎保持不变。",+ "installer.welcome.about": "Filee 就地转换文件。按住按键拖动文件,或在资源管理器中右键单击文件,然后选择格式即可。",+ "installer.welcome.license": "Filee 是免费的开源软件(MIT 许可证)。",+ "installer.language": "语言",+ "installer.options.title": "选择 Filee 的使用方式",+ "installer.options.folder": "安装文件夹",+ "installer.options.browse": "更改…",+ "installer.options.space": "Filee 需要约 {0} 的磁盘空间。",+ "installer.options.later": "之后可以在 Filee 的 设置 → 常规 中更改。",+ "installer.options.update_note": "Filee 的其他设置保持不变,可随时在 Filee 的 设置 → 常规 中更改。",+ "installer.task.modern_menu": "也显示在 Windows 11 主菜单中,而不仅是“显示更多选项”里",+ "installer.task.cli": "将“filee”命令添加到 PATH(在命令行中转换)",+ "installer.task.desktop_icon": "创建桌面快捷方式",+ "installer.engines.when": "Filee 启动后会从官方来源下载你选择的引擎。",+ "installer.progress.install": "正在安装 Filee",+ "installer.progress.update": "正在更新 Filee",+ "installer.status.verifying": "正在检查安装文件…",+ "installer.status.closing": "正在关闭 Filee…",+ "installer.status.removing_old": "正在移除旧版本(保留设置和引擎)…",+ "installer.status.copying": "正在复制 Filee 的文件…",+ "installer.status.explorer_menu": "正在将 Filee 添加到资源管理器菜单…",+ "installer.status.finishing": "正在完成…",+ "installer.status.rolling_back": "正在撤销更改…",+ "installer.status.removing": "正在移除 Filee…",+ "installer.done.title": "Filee 已就绪",+ "installer.done.text": "Filee 在任务栏通知区域运行。\n\n要转换文件,请按住触发键拖动文件,或在资源管理器中右键单击文件。",+ "installer.done.updated": "Filee 已更新。设置、预设和引擎保持不变。",+ "installer.done.engines": "你选择的转换引擎会在 Filee 启动后下载。",+ "installer.done.launch": "启动 Filee",+ "installer.warning.explorer_menu": "Windows 未能将 Filee 添加到资源管理器主菜单。\n\n{0}\n\nFilee 仍会出现在“显示更多选项”中。你可以在 Filee 的 设置 → 常规 中重试。",+ "installer.warning.runtime": "{0} 无法运行,它需要这台电脑上没有的 Microsoft Visual C++ 运行库({1})。Filee 的其他功能都正常。安装 Microsoft 的 Visual C++ 可再发行组件包(x64)即可解决。\n{2}",+ "installer.error.title": "Filee 未能安装",+ "installer.error.uninstall_title": "Filee 未能完全移除",+ "installer.error.space": "{0} 上的可用空间不足。Filee 需要 {1},但只剩 {2}。",+ "installer.error.damaged": "安装文件已损坏。请从 filee.sh 重新下载。",+ "installer.error.files": "安装程序无法写入 Filee 的文件。{0}",+ "installer.error.unexpected": "出现了问题。{0}",+ "installer.error.windows": "Filee 需要 64 位 Windows 10 1809 或更高版本。",+ "installer.error.rolled_back": "安装程序已撤销所有更改,之前的 Filee 仍可使用。",+ "installer.error.undone": "安装程序已撤销所做的更改。",+ "installer.error.nothing_changed": "这台电脑上没有任何更改。",+ "installer.error.log": "详细信息见日志 {0}",+ "installer.uninstall.title": "卸载 Filee",+ "installer.uninstall.text": "将从这台电脑上移除 Filee {0},包括资源管理器菜单项、开机启动项以及它下载的转换引擎。",+ "installer.uninstall.delete_settings": "同时删除我的设置、预设和工具栏",+ "installer.uninstall.settings_where": "它们位于 {0}。保留它们,重新安装 Filee 时即可恢复。",+ "installer.uninstall.button": "卸载",+ "installer.uninstall.progress": "正在移除 Filee",+ "installer.uninstall.done_title": "Filee 已移除",+ "installer.uninstall.done": "Filee 已从这台电脑上移除。",+ "installer.uninstall.settings_kept": "你的设置已保留,重新安装 Filee 时即可使用。",+ "installer.uninstall.not_installed": "{0} 中没有安装 Filee。","watch.title": "自动转换文件夹","watch.description": "Filee 运行时,放入这些文件夹的文件会自动转换。\n正在下载或复制的文件会等完成后再转换。","watch.add": "添加文件夹",diff --git a/src/Filee.Setup/App.axaml b/src/Filee.Setup/App.axamlnew file mode 100644index 00000000..19a13596--- /dev/null+++ b/src/Filee.Setup/App.axaml@@ -0,0 +1,12 @@+<Application xmlns="https://github.com/avaloniaui"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ x:Class="Filee.Setup.App"+ Name="Filee Setup"+ RequestedThemeVariant="Default">+ <!-- Light or dark follows Windows (RequestedThemeVariant="Default"), like Filee's "System" theme. -->+ <Application.Styles>+ <FluentTheme />+ <StyleInclude Source="avares://Filee.Setup/Styles/Soft.axaml" />+ <StyleInclude Source="avares://Filee.Setup/Styles/Setup.axaml" />+ </Application.Styles>+</Application>diff --git a/src/Filee.Setup/App.axaml.cs b/src/Filee.Setup/App.axaml.csnew file mode 100644index 00000000..7879827f--- /dev/null+++ b/src/Filee.Setup/App.axaml.cs@@ -0,0 +1,56 @@+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.ApplicationLifetimes;+using Avalonia.Markup.Xaml;+using Avalonia.Media;+using Filee.App.Services;+using Filee.Setup.ViewModels;+using Filee.Setup.Views;++namespace Filee.Setup;++public sealed class App : Application+{+ /// <summary>The window's model, set by Program before Avalonia starts.</summary>+ internal static SetupViewModel? Model { get; set; }++ /// <summary>Setup's texts, published as resources.</summary>+ internal static SetupTexts? Texts { get; set; }++ /// <summary>/SILENT: start at once, show only the progress, close when done.</summary>+ internal static bool Silent { get; set; }++ public override void Initialize() => AvaloniaXamlLoader.Load(this);++ public override void OnFrameworkInitializationCompleted()+ {+ if (Texts is { } texts)+ ApplyLook(this, texts);+ if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && Model is { } model)+ {+ desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;+ desktop.MainWindow = new SetupWindow(model, Silent);+ }+ base.OnFrameworkInitializationCompleted();+ }++ /// <summary>Filee's look in <paramref name="texts"/>' language: default accent, radius and the font order; texts as resources.</summary>+ internal static void ApplyLook(Application app, SetupTexts texts)+ {+ var res = app.Resources;+ SoftPalette.ApplyAccent(res, Color.Parse(SoftPalette.DefaultAccent));+ SoftPalette.ApplyCornerRadius(res, SoftPalette.DefaultCornerRadius);+ void Apply()+ {+ res["AppFontFamily"] = SoftPalette.FontFamilyFor(texts.Language);+ texts.Publish(res);+ }+ Apply();+ texts.LanguageChanged += (_, _) => Apply();+ }+}++/// <summary>The app's embedded Noto fonts: <c>fonts:Filee#Noto Sans</c> and the others (see SoftPalette).</summary>+internal sealed class SetupFontCollection() : Avalonia.Media.Fonts.EmbeddedFontCollection(+ new Uri("fonts:Filee", UriKind.Absolute),+ new Uri("avares://Filee.Setup/Assets/Fonts", UriKind.Absolute));diff --git a/src/Filee.Setup/Filee.Setup.csproj b/src/Filee.Setup/Filee.Setup.csprojnew file mode 100644index 00000000..0b7aceda--- /dev/null+++ b/src/Filee.Setup/Filee.Setup.csproj@@ -0,0 +1,70 @@+<!--+ Filee.Setup: Filee's own Windows installer and uninstaller (Filee-<version>-win-Setup.exe, uninstall.exe).+ build/build-installer.ps1 publishes it as one self-contained, trimmed file (no .NET needed on the PC) and appends+ the published app to it as a compressed payload (build/tools/make-setup.cs). The same program without a payload,+ copied next to Filee.exe as uninstall.exe, is the uninstaller.+ It shares the app's look (Styles/Soft.axaml, SoftPalette, the Noto fonts) and translations (Assets/i18n).+-->+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <OutputType>WinExe</OutputType>+ <AssemblyName>Filee.Setup</AssemblyName>+ <RootNamespace>Filee.Setup</RootNamespace>+ <ApplicationManifest>app.manifest</ApplicationManifest>+ <ApplicationIcon>..\Filee.App\Assets\Icons\filee.ico</ApplicationIcon>+ <AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>+ <!-- Kept trim- and AOT-safe (no reflection, compiled bindings, source-generated COM), so the publish can be+ trimmed and could become Native AOT later. -->+ <IsAotCompatible>true</IsAotCompatible>+ <InvariantGlobalization>true</InvariantGlobalization>+ <SatelliteResourceLanguages>en</SatelliteResourceLanguages>+ <Product>Filee Setup</Product>+ </PropertyGroup>++ <!-- build/build-installer.ps1: dotnet publish -c Release -r win-x64 -p:FileeSetupPublish=true -->+ <PropertyGroup Condition="'$(FileeSetupPublish)' == 'true'">+ <SelfContained>true</SelfContained>+ <PublishSingleFile>true</PublishSingleFile>+ <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>+ <EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>+ <PublishTrimmed>true</PublishTrimmed>+ <TrimMode>full</TrimMode>+ <DebugType>none</DebugType>+ <UseSystemResourceKeys>false</UseSystemResourceKeys>+ <EventSourceSupport>false</EventSourceSupport>+ <StackTraceSupport>true</StackTraceSupport>+ </PropertyGroup>++ <ItemGroup>+ <ProjectReference Include="..\Filee.Platform.Windows\Filee.Platform.Windows.csproj" />+ </ItemGroup>++ <ItemGroup>+ <PackageReference Include="Avalonia" />+ <PackageReference Include="Avalonia.Desktop" />+ <PackageReference Include="Avalonia.Themes.Fluent" />+ <PackageReference Include="CommunityToolkit.Mvvm" />+ </ItemGroup>++ <!-- Shared with the app: its look, icon, fonts and translations. -->+ <ItemGroup>+ <Compile Include="..\Filee.App\Services\SoftPalette.cs" Link="Shared\SoftPalette.cs" />+ <AvaloniaResource Include="..\Filee.App\Styles\Soft.axaml" Link="Styles\Soft.axaml" />+ <AvaloniaResource Include="..\Filee.App\Assets\Icons\filee.ico" Link="Assets\Icons\filee.ico" />+ <AvaloniaResource Include="..\Filee.App\Assets\Icons\filee.png" Link="Assets\Icons\filee.png" />+ <AvaloniaResource Include="..\Filee.App\Assets\Fonts\*.ttf;..\Filee.App\Assets\Fonts\*.otf" Link="Assets\Fonts\%(Filename)%(Extension)" />+ <EmbeddedResource Include="..\Filee.App\Assets\i18n\*.json" Link="i18n\%(Filename)%(Extension)" LogicalName="i18n.%(Filename)%(Extension)" />+ </ItemGroup>++ <ItemGroup>+ <InternalsVisibleTo Include="Filee.Setup.Tests" />+ </ItemGroup>++ <ItemGroup>+ <AssemblyAttribute Include="System.Reflection.AssemblyMetadataAttribute">+ <_Parameter1>RepositoryUrl</_Parameter1>+ <_Parameter2>$(FileeRepositoryUrl)</_Parameter2>+ </AssemblyAttribute>+ </ItemGroup>+</Project>diff --git a/src/Filee.Setup/Installation/FileSwap.cs b/src/Filee.Setup/Installation/FileSwap.csnew file mode 100644index 00000000..d502604e--- /dev/null+++ b/src/Filee.Setup/Installation/FileSwap.cs@@ -0,0 +1,153 @@+// Puts the unpacked files into the install folder as one step that can be undone. The new files were unpacked and+// checked in a work folder inside the install folder (same volume, so every move is a rename). Each file that is+// replaced or no longer needed is first renamed into the work folder's backup: Windows lets a program in use, or a DLL+// Explorer has loaded (FileeExplorerMenu.dll), be renamed, just not overwritten or deleted. On failure everything is+// moved back; on success the backup is deleted, and what is still in use goes at the next restart.++using Filee.Setup.Platform;++namespace Filee.Setup.Installation;++public sealed class FileSwap(string installFolder, string workFolder, ISetupSystem system, SetupLog log)+{+ /// <summary>Prefix of the work folders inside the install folder. Left-overs of an interrupted Setup are removed.</summary>+ public const string WorkFolderPrefix = "~setup-";++ private readonly List<(string Target, string? Backup)> _done = [];+ private readonly string _backup = Path.Combine(workFolder, "old");+ private int _backups;++ /// <summary>Where the new files are unpacked.</summary>+ public string Staging { get; } = Path.Combine(workFolder, "new");++ /// <summary>Moves the staged file <paramref name="relative"/> into place, keeping the file it replaces.</summary>+ public void Replace(string relative)+ {+ var target = Path.Combine(installFolder, relative);+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);+ var backup = File.Exists(target) ? MoveToBackup(target) : null;+ _done.Add((target, backup));+ File.Move(Path.Combine(Staging, relative), target);+ }++ /// <summary>Moves an old file out of the install folder (deleted on <see cref="Commit"/>).</summary>+ public void Remove(string relative)+ {+ var target = Path.Combine(installFolder, relative);+ if (!File.Exists(target))+ return;+ _done.Add((target, MoveToBackup(target)));+ }++ private string MoveToBackup(string target)+ {+ // A flat, numbered backup: no folder structure to recreate, and names can't collide.+ Directory.CreateDirectory(_backup);+ var backup = Path.Combine(_backup, $"{_backups++:D5}-{Path.GetFileName(target)}");+ File.SetAttributes(target, FileAttributes.Normal);+ File.Move(target, backup);+ return backup;+ }++ /// <summary>Puts every file back as it was. Best effort: a file that can't be moved back is logged.</summary>+ public void Rollback()+ {+ for (var i = _done.Count - 1; i >= 0; i--)+ {+ var (target, backup) = _done[i];+ try+ {+ if (backup is null)+ {+ // A new file where there was none: take it away again (into the backup if it is in use).+ if (File.Exists(target))+ {+ try+ {+ File.Delete(target);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ MoveToBackup(target);+ }+ }+ continue;+ }+ if (File.Exists(target))+ File.Move(target, Path.Combine(_backup, $"{_backups++:D5}-new-{Path.GetFileName(target)}"));+ File.Move(backup, target);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ log.Error($"Rollback: could not restore {target}: {ex.Message}");+ }+ }+ _done.Clear();+ RemoveEmptyFolders(installFolder, keep: workFolder);+ Cleanup();+ }++ /// <summary>Deletes the replaced files and the work folder.</summary>+ public void Commit()+ {+ _done.Clear();+ RemoveEmptyFolders(installFolder, keep: workFolder);+ Cleanup();+ }++ /// <summary>Deletes the work folder; what is still in use goes at the next restart.</summary>+ public void Cleanup() => DeleteTree(workFolder, system, log);++ /// <summary>Deletes a folder tree; files still in use are deleted at the next restart.</summary>+ public static void DeleteTree(string folder, ISetupSystem system, SetupLog log)+ {+ if (!Directory.Exists(folder))+ return;+ foreach (var file in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))+ {+ try+ {+ File.SetAttributes(file, FileAttributes.Normal);+ File.Delete(file);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ log.Info($"In use, deleted at the next restart: {file}");+ system.DeleteAtRestart(file);+ }+ }+ foreach (var dir in Directory.EnumerateDirectories(folder, "*", SearchOption.AllDirectories)+ .OrderByDescending(d => d.Length).Append(folder))+ {+ try+ {+ Directory.Delete(dir);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ system.DeleteAtRestart(dir);+ }+ }+ }++ /// <summary>Removes empty folders below <paramref name="root"/> (not the root itself).</summary>+ public static void RemoveEmptyFolders(string root, string? keep = null)+ {+ if (!Directory.Exists(root))+ return;+ foreach (var dir in Directory.EnumerateDirectories(root, "*", SearchOption.AllDirectories).OrderByDescending(d => d.Length))+ {+ if (keep is not null && (dir.Equals(keep, StringComparison.OrdinalIgnoreCase)+ || dir.StartsWith(keep + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)))+ continue;+ try+ {+ if (!Directory.EnumerateFileSystemEntries(dir).Any())+ Directory.Delete(dir);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ }+ }+ }+}diff --git a/src/Filee.Setup/Installation/InstallRecord.cs b/src/Filee.Setup/Installation/InstallRecord.csnew file mode 100644index 00000000..1cc7fb94--- /dev/null+++ b/src/Filee.Setup/Installation/InstallRecord.cs@@ -0,0 +1,54 @@+// uninstall.json next to Filee.exe: the version, who it was installed for and every file Setup put there. The+// uninstaller removes exactly these files (a folder chosen by the user may hold other things); an update replaces them+// and removes the ones the new version no longer has.++using System.Text.Json;++namespace Filee.Setup.Installation;++public sealed record InstallRecord(string Version, InstallScope Scope, IReadOnlyList<string> Files)+{+ public static string PathIn(string installFolder) => Path.Combine(installFolder, SetupNames.InstallRecordFile);++ public byte[] ToJson()+ {+ using var stream = new MemoryStream();+ using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))+ {+ writer.WriteStartObject();+ writer.WriteString("version", Version);+ writer.WriteString("scope", Scope == InstallScope.Machine ? "machine" : "user");+ writer.WriteStartArray("files");+ foreach (var file in Files)+ writer.WriteStringValue(file);+ writer.WriteEndArray();+ writer.WriteEndObject();+ }+ return stream.ToArray();+ }++ /// <summary>The record in <paramref name="installFolder"/>, or null when there is none or it can't be read.</summary>+ public static InstallRecord? Read(string installFolder)+ {+ try+ {+ var path = PathIn(installFolder);+ if (!File.Exists(path))+ return null;+ using var json = JsonDocument.Parse(File.ReadAllBytes(path));+ var root = json.RootElement;+ var files = root.GetProperty("files").EnumerateArray().Select(f => f.GetString()!).ToList();+ foreach (var file in files)+ Payload.PayloadManifest.CheckPath(file);+ return new InstallRecord(+ root.GetProperty("version").GetString() ?? "",+ root.TryGetProperty("scope", out var scope) && scope.GetString() == "user" ? InstallScope.User : InstallScope.Machine,+ files);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or KeyNotFoundException+ or InvalidOperationException or InvalidDataException)+ {+ return null;+ }+ }+}diff --git a/src/Filee.Setup/Installation/Installer.cs b/src/Filee.Setup/Installation/Installer.csnew file mode 100644index 00000000..4e28327d--- /dev/null+++ b/src/Filee.Setup/Installation/Installer.cs@@ -0,0 +1,376 @@+// Installs or updates Filee, in this order (installer/Filee.iss did the same in 1.x):+// 1. checks free space and the payload's checksum: nothing has changed yet;+// 2. closes a running Filee ("Filee.exe --quit", which saves and exits), then ends what still runs from the folder;+// 3. removes Filee 1.1's per-user Velopack copy (settings and engines stay);+// 4. unpacks into a work folder inside the install folder, checking every file, with the uninstaller and its list;+// 5. swaps the files in (FileSwap: replaced and obsolete files go to a backup, Inno Setup's unins000.* too);+// 6. writes the uninstall entry (the same key Inno Setup used, so Apps & Features keeps one Filee), the shortcuts and+// PATH; on Windows 11 registers the top-level Explorer menu package;+// 7. deletes the backup, or on any failure in 4-6 puts everything back.+// Filee's own settings (Explorer menu entry, start at sign-in, engines, language) are handed to Filee when Setup+// starts it, as before: Filee applies them for the signed-in user.++using Filee.Platform.Windows;+using Filee.Setup.Payload;+using Filee.Setup.Platform;++namespace Filee.Setup.Installation;++public sealed class Installer(SetupContext context, SetupPayload payload)+{+ private ISetupRegistry Registry => context.Registry;+ private ISetupSystem System => context.System;+ private SetupPaths Paths => context.Paths;+ private SetupLog Log => context.Log;++ /// <summary>How long Filee may take to save and exit when asked (its own limit is 20 s).</summary>+ public static TimeSpan QuitTimeout { get; } = TimeSpan.FromSeconds(40);++ /// <summary>Space needed besides the files themselves (the uninstaller, Windows' own bookkeeping).</summary>+ private const long SpareSpace = 64L << 20;++ public InstallResult Run(InstallChoices choices, PreviousInstall? previous, IProgress<SetupProgress>? progress = null,+ CancellationToken cancellation = default)+ {+ var folder = Path.TrimEndingDirectorySeparator(Path.GetFullPath(choices.Folder));+ var update = previous is not null && string.Equals(previous.Folder, folder, StringComparison.OrdinalIgnoreCase);+ Log.Info($"{(update ? "Update" : choices.Portable ? "Portable copy" : "Install")} of Filee {payload.Manifest.Version} " ++ $"into {folder} for {(choices.Scope == InstallScope.Machine ? "all users" : "this user")}; " ++ $"previous: {(previous is null ? "none" : $"{previous.Version} in {previous.Folder}{(previous.ByInno ? " (Inno Setup)" : "")}")}; " ++ $"options: {choices.Tasks.ToInnoString()}; engines: {string.Join(',', choices.Engines)}; language: {choices.Language}");+ var warnings = new List<SetupWarning>();+ FileSwap? swap = null;+ var undo = new Stack<(string What, Action Action)>();+ var changing = false;+ var createdFolder = false;+ try+ {+ progress?.Report(new SetupProgress(SetupStep.Verifying, 0));+ CheckSpace(folder);+ payload.Verify(Scaled(progress, SetupStep.Verifying, 0, 0.08), cancellation);+ Log.Info("Payload checksum OK");++ var menuWasRegistered = !choices.Portable && System.ExplorerMenuSupported && System.IsExplorerMenuRegistered();+ var velopack = !choices.Portable && VelopackInstall.Exists(Paths);++ progress?.Report(new SetupProgress(SetupStep.Closing, 0.08));+ CloseFilee(folder, choices.ForceClose, velopack);+ cancellation.ThrowIfCancellationRequested();++ if (velopack)+ {+ progress?.Report(new SetupProgress(SetupStep.RemovingOld, 0.1));+ VelopackInstall.Remove(Paths, Registry, System, Log);+ }++ // 4. Unpack and check.+ createdFolder = !Directory.Exists(folder);+ Directory.CreateDirectory(folder);+ RemoveLeftoverWorkFolders(folder);+ var work = Path.Combine(folder, FileSwap.WorkFolderPrefix + Guid.NewGuid().ToString("N")[..8]);+ swap = new FileSwap(folder, work, System, Log);+ progress?.Report(new SetupProgress(SetupStep.Copying, 0.12));+ var total = Math.Max(1, payload.Manifest.TotalSize);+ payload.ExtractTo(swap.Staging, new SyncProgress<long>(bytes =>+ progress?.Report(new SetupProgress(SetupStep.Copying, 0.12 + 0.68 * bytes / total))), cancellation);+ Log.Info($"Unpacked and checked {payload.Manifest.Files.Count} files ({payload.Manifest.TotalSize / 1_000_000} MB)");+ var newFiles = payload.Manifest.Files.Select(f => f.Path).ToList();+ if (!choices.Portable)+ {+ payload.CopyProgramTo(Path.Combine(swap.Staging, SetupNames.UninstallerExe));+ newFiles.Add(SetupNames.UninstallerExe);+ newFiles.Add(SetupNames.InstallRecordFile);+ File.WriteAllBytes(Path.Combine(swap.Staging, SetupNames.InstallRecordFile),+ new InstallRecord(payload.Manifest.Version, choices.Scope, newFiles).ToJson());+ }+ var missing = RuntimeCheck.FindMissing(swap.Staging, Paths.SystemFolder);+ Log.Info($"Microsoft Visual C++ runtime check: {(missing.Count == 0 ? "nothing missing" : $"{missing.Count} missing")}");+ if (missing.Count > 0)+ {+ Log.Warn("Missing Microsoft Visual C++ runtime: " + string.Join(", ", missing.Select(m => $"{m.Program} needs {m.Dll}")));+ warnings.Add(new RuntimeWarning(missing));+ }+ cancellation.ThrowIfCancellationRequested();++ // 5. Swap. From here on, a failure puts everything back.+ changing = true;+ progress?.Report(new SetupProgress(SetupStep.Copying, 0.82));+ foreach (var file in newFiles)+ swap.Replace(file);+ var obsolete = (previous?.OwnedFiles() ?? []).Concat(SetupNames.InnoUninstallerFiles)+ .Except(newFiles, StringComparer.OrdinalIgnoreCase)+ .Where(f => !f.StartsWith(FileSwap.WorkFolderPrefix, StringComparison.OrdinalIgnoreCase))+ .Where(f => File.Exists(Path.Combine(folder, f)))+ .ToList();+ foreach (var file in obsolete)+ swap.Remove(file);+ Log.Info($"Installed {newFiles.Count} files; {obsolete.Count} files of the previous version are no longer needed");++ // 6. Register.+ progress?.Report(new SetupProgress(SetupStep.Finishing, 0.88));+ if (!choices.Portable)+ Register(folder, choices, update, undo);++ if (!choices.Portable && System.ExplorerMenuSupported)+ {+ progress?.Report(new SetupProgress(SetupStep.ExplorerMenu, 0.92));+ if (UpdateExplorerMenu(folder, choices, update, menuWasRegistered) is { } error)+ warnings.Add(new ExplorerMenuWarning(error));+ }++ // 7. Done: the old files go.+ progress?.Report(new SetupProgress(SetupStep.Finishing, 0.97));+ swap.Commit();+ progress?.Report(new SetupProgress(SetupStep.Finishing, 1));+ Log.Info("Done");+ var launch = choices.Portable ? null : new LaunchRequest(Path.Combine(folder, SetupNames.AppExe), LaunchArguments(choices, update));+ return new InstallResult(launch, warnings);+ }+ catch (Exception ex) when (ex is not OutOfMemoryException)+ {+ Log.Error($"Install failed: {ex}");+ if (changing)+ progress?.Report(new SetupProgress(SetupStep.RollingBack, 1));+ while (undo.TryPop(out var step))+ {+ try+ {+ step.Action();+ }+ catch (Exception undoError) when (undoError is not OutOfMemoryException)+ {+ Log.Error($"Undo {step.What} failed: {undoError.Message}");+ }+ }+ if (swap is not null)+ {+ if (changing)+ swap.Rollback();+ else+ swap.Cleanup();+ }+ if (createdFolder)+ DeleteIfEmpty(folder);+ return new InstallResult(null, warnings, ex, RolledBack: changing);+ }+ }++ private static void DeleteIfEmpty(string folder)+ {+ try+ {+ if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any())+ Directory.Delete(folder);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ }+ }++ /// <summary>The arguments Filee starts with: the choices of a fresh install, or "back to the tray" after an update.</summary>+ public static string LaunchArguments(InstallChoices choices, bool update) => update+ ? "--background"+ : $"--install-engines={string.Join(',', choices.Engines)} " ++ $"--start-with-windows={OnOff(choices.Tasks.Startup)} --context-menu={OnOff(choices.Tasks.ContextMenu)}" ++ (choices.LanguagePicked ? $" --language={choices.Language}" : "");++ private static string OnOff(bool value) => value ? "on" : "off";++ private void CheckSpace(string folder)+ {+ try+ {+ var root = Path.GetPathRoot(folder);+ if (string.IsNullOrEmpty(root) || root.StartsWith(@"\\", StringComparison.Ordinal))+ return;+ var drive = new DriveInfo(root);+ var needed = payload.Manifest.TotalSize + payload.Offset + SpareSpace;+ Log.Info($"Space on {root}: {drive.AvailableFreeSpace / 1_000_000} MB free, {needed / 1_000_000} MB needed");+ if (drive.AvailableFreeSpace < needed)+ throw new SetupException("installer.error.space", $"Not enough space on {root}",+ root, FormatSize(needed), FormatSize(drive.AvailableFreeSpace));+ }+ catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException)+ {+ Log.Warn($"Could not read the free space: {ex.Message}");+ }+ }++ /// <summary>"1.3 GB", "420 MB" (as the app writes sizes).</summary>+ public static string FormatSize(long bytes) => bytes >= 1_000_000_000+ ? string.Create(global::System.Globalization.CultureInfo.InvariantCulture, $"{bytes / 1_000_000_000.0:0.0} GB")+ : string.Create(global::System.Globalization.CultureInfo.InvariantCulture, $"{Math.Max(1, bytes / 1_000_000)} MB");++ /// <summary>+ /// Asks Filee to exit (it saves first and waits for running conversions to stop), then ends whatever still runs+ /// from the install folder (filee-cli, an engine), like Inno Setup's CloseApplications did.+ /// </summary>+ private void CloseFilee(string folder, bool force, bool velopack)+ {+ var exe = Path.Combine(folder, SetupNames.AppExe);+ if (File.Exists(exe))+ {+ var code = System.RunAndWait(exe, "--quit", QuitTimeout);+ Log.Info($"Filee --quit: exit code {code}");+ }+ var running = System.ProgramsIn(folder).ToList();+ if (velopack)+ running.AddRange(System.ProgramsIn(VelopackInstall.Root(Paths)));+ if (running.Count == 0)+ return;+ if (!force)+ {+ Log.Warn($"Still running, left alone (/NOCLOSEAPPLICATIONS): {string.Join(", ", running.Select(p => p.Path))}");+ return;+ }+ foreach (var program in running)+ {+ Log.Info($"Ending {program.Path} ({program.Id})");+ System.Kill(program.Id);+ }+ }++ private void RemoveLeftoverWorkFolders(string folder)+ {+ foreach (var leftover in Directory.EnumerateDirectories(folder, FileSwap.WorkFolderPrefix + "*"))+ {+ Log.Info($"Removing {leftover} (left by an interrupted Setup)");+ FileSwap.DeleteTree(leftover, System, Log);+ }+ }++ private void Register(string folder, InstallChoices choices, bool update, Stack<(string, Action)> undo)+ {+ var hive = PreviousInstall.HiveOf(choices.Scope);++ // The uninstall entry: the Inno Setup key, rewritten (its "Inno Setup: …" values and unins000.exe are gone).+ var before = Snapshot(hive, SetupNames.UninstallKey);+ undo.Push(("uninstall entry", () => Restore(hive, SetupNames.UninstallKey, before)));+ WriteUninstallEntry(hive, folder, choices);++ // Shortcuts.+ var startMenu = Path.Combine(Paths.StartMenu(choices.Scope), SetupNames.ShortcutName);+ var desktop = Path.Combine(Paths.Desktop(choices.Scope), SetupNames.ShortcutName);+ var exe = Path.Combine(folder, SetupNames.AppExe);+ if (!choices.NoIcons)+ {+ if (!File.Exists(startMenu))+ undo.Push(("Start menu shortcut", () => File.Delete(startMenu)));+ System.CreateShortcut(startMenu, exe, folder, "Filee");+ }+ if (choices.Tasks.DesktopIcon && !choices.NoIcons)+ {+ if (!File.Exists(desktop))+ undo.Push(("desktop shortcut", () => File.Delete(desktop)));+ System.CreateShortcut(desktop, exe, folder, "Filee");+ }+ else if (update && File.Exists(desktop))+ {+ // Unticked on an update: the shortcut goes (ticking it again brings it back).+ File.Delete(desktop);+ }++ // PATH.+ var cli = Path.Combine(folder, SetupNames.CliFolder);+ if (PathVariable.Set(Registry, choices.Scope, cli, choices.Tasks.Cli))+ {+ undo.Push(("PATH", () =>+ {+ PathVariable.Set(Registry, choices.Scope, cli, !choices.Tasks.Cli);+ System.BroadcastEnvironmentChange();+ }));+ System.BroadcastEnvironmentChange();+ Log.Info($"{(choices.Tasks.Cli ? "Added" : "Removed")} {cli} {(choices.Tasks.Cli ? "to" : "from")} PATH");+ }+ }++ private void WriteUninstallEntry(Hive hive, string folder, InstallChoices choices)+ {+ const string key = SetupNames.UninstallKey;+ var version = payload.Manifest.Version;+ var uninstaller = Path.Combine(folder, SetupNames.UninstallerExe);+ var repository = SetupInfo.RepositoryUrl.TrimEnd('/');+ Registry.DeleteKey(hive, key);+ Registry.SetString(hive, key, "DisplayName", SetupNames.AppName);+ Registry.SetString(hive, key, "DisplayVersion", version);+ Registry.SetString(hive, key, "Publisher", SetupNames.Publisher);+ Registry.SetString(hive, key, "DisplayIcon", Path.Combine(folder, SetupNames.AppExe));+ Registry.SetString(hive, key, "InstallLocation", folder + Path.DirectorySeparatorChar);+ Registry.SetString(hive, key, "UninstallString", SetupOptions.Quote(uninstaller));+ Registry.SetString(hive, key, "QuietUninstallString", SetupOptions.Quote(uninstaller) + " /VERYSILENT /SUPPRESSMSGBOXES /NORESTART");+ Registry.SetString(hive, key, "URLInfoAbout", repository);+ Registry.SetString(hive, key, "HelpLink", repository + "/issues");+ Registry.SetString(hive, key, "URLUpdateInfo", repository + "/releases");+ Registry.SetString(hive, key, "InstallDate", DateTime.Now.ToString("yyyyMMdd", global::System.Globalization.CultureInfo.InvariantCulture));+ Registry.SetNumber(hive, key, "NoModify", 1);+ Registry.SetNumber(hive, key, "NoRepair", 1);+ Registry.SetNumber(hive, key, "EstimatedSize", (int)Math.Min(int.MaxValue, (payload.Manifest.TotalSize + payload.Offset) / 1024));+ if (Version.TryParse(version.Split('-', '+')[0], out var parsed))+ {+ Registry.SetNumber(hive, key, "VersionMajor", parsed.Major);+ Registry.SetNumber(hive, key, "VersionMinor", parsed.Minor);+ }+ Registry.SetString(hive, key, SetupNames.TasksValue, choices.Tasks.ToInnoString());+ Registry.SetString(hive, key, SetupNames.LanguageValue, choices.Language);+ Registry.SetString(hive, key, SetupNames.ScopeValue, choices.Scope == InstallScope.Machine ? "machine" : "user");+ Log.Info($"Uninstall entry written ({(hive == Hive.LocalMachine ? "HKLM" : "HKCU")}\\{key})");+ }++ private Dictionary<string, RegistryEntry>? Snapshot(Hive hive, string key)+ {+ if (!Registry.KeyExists(hive, key))+ return null;+ return Registry.ValueNames(hive, key)+ .Select(name => (name, entry: Registry.Get(hive, key, name)))+ .Where(v => v.entry is not null)+ .ToDictionary(v => v.name, v => v.entry!, StringComparer.OrdinalIgnoreCase);+ }++ private void Restore(Hive hive, string key, Dictionary<string, RegistryEntry>? values)+ {+ Registry.DeleteKey(hive, key);+ foreach (var (name, entry) in values ?? [])+ {+ if (entry.Value is int number)+ Registry.SetNumber(hive, key, name, number);+ else+ Registry.SetString(hive, key, name, (string)entry.Value, entry.Expandable);+ }+ }++ /// <summary>+ /// A fresh install registers the top-level menu when ticked (removing an older registration first, which may point+ /// to another folder) and removes it when not; an update keeps what was chosen in Filee and refreshes it.+ /// Returns Windows' error when registering failed.+ /// </summary>+ private string? UpdateExplorerMenu(string folder, InstallChoices choices, bool update, bool wasRegistered)+ {+ if (!OperatingSystem.IsWindows() || !ExplorerMenuRegistration.HasFiles(folder))+ {+ Log.Warn("The Explorer menu files are not in this build");+ return null;+ }+ string? error = null;+ if (update ? wasRegistered : choices.Tasks.ContextMenu && choices.Tasks.ModernMenu)+ {+ Log.Info("Registering the Windows 11 Explorer menu package");+ error = System.RegisterExplorerMenu(folder, removeFirst: !update);+ }+ else if (!update && System.IsExplorerMenuRegistered())+ {+ System.UnregisterExplorerMenu();+ }+ if (error is not null)+ Log.Warn($"Windows did not register the Explorer menu: {error}");+ return error;+ }++ private static IProgress<double>? Scaled(IProgress<SetupProgress>? progress, SetupStep step, double from, double to) =>+ progress is null ? null : new SyncProgress<double>(f => progress.Report(new SetupProgress(step, from + (to - from) * f)));+}++/// <summary>Reports on the calling thread (Progress<T> posts to a synchronization context).</summary>+public sealed class SyncProgress<T>(Action<T> report) : IProgress<T>+{+ public void Report(T value) => report(value);+}diff --git a/src/Filee.Setup/Installation/PathVariable.cs b/src/Filee.Setup/Installation/PathVariable.csnew file mode 100644index 00000000..e5e440e4--- /dev/null+++ b/src/Filee.Setup/Installation/PathVariable.cs@@ -0,0 +1,57 @@+// The "filee" command on PATH: the install folder's cli subfolder in the system PATH (per-machine) or the user's PATH+// (per-user), written as REG_EXPAND_SZ like Windows' own value so %SystemRoot% entries keep working.++using Filee.Setup.Platform;++namespace Filee.Setup.Installation;++public static class PathVariable+{+ public static (Hive Hive, string Key) Location(InstallScope scope) => scope == InstallScope.Machine+ ? (Hive.LocalMachine, SetupNames.MachineEnvironmentKey)+ : (Hive.CurrentUser, SetupNames.UserEnvironmentKey);++ /// <summary>True when <paramref name="paths"/> (a PATH value) has <paramref name="folder"/> (case and a trailing backslash don't matter).</summary>+ public static bool Contains(string? paths, string folder) =>+ Entries(paths).Any(entry => Same(entry, folder));++ public static string Add(string? paths, string folder)+ {+ if (Contains(paths, folder))+ return paths!;+ var value = paths ?? "";+ if (value.Length > 0 && !value.EndsWith(';'))+ value += ";";+ return value + Path.TrimEndingDirectorySeparator(folder);+ }++ /// <summary>Removes every entry for <paramref name="folder"/>; the rest stays exactly as it was.</summary>+ public static string Remove(string? paths, string folder) =>+ string.Join(';', (paths ?? "").Split(';').Where(entry => entry.Trim().Length == 0 || !Same(entry, folder)));++ public static bool IsOnPath(ISetupRegistry registry, InstallScope scope, string folder)+ {+ var (hive, key) = Location(scope);+ return Contains(registry.Get(hive, key, "Path")?.Text, folder);+ }++ /// <summary>Adds or removes the folder; true when PATH changed (running programs should then be told).</summary>+ public static bool Set(ISetupRegistry registry, InstallScope scope, string folder, bool present)+ {+ var (hive, key) = Location(scope);+ var entry = registry.Get(hive, key, "Path");+ var current = entry?.Text;+ var updated = present ? Add(current, folder) : Remove(current, folder);+ if (string.Equals(current ?? "", updated, StringComparison.Ordinal))+ return false;+ // The system PATH is REG_EXPAND_SZ; a user PATH keeps the kind it had (new ones get REG_EXPAND_SZ too).+ registry.SetString(hive, key, "Path", updated, expandable: entry?.Expandable ?? true);+ return true;+ }++ private static IEnumerable<string> Entries(string? paths) =>+ (paths ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);++ private static bool Same(string entry, string folder) =>+ string.Equals(Path.TrimEndingDirectorySeparator(entry.Trim()), Path.TrimEndingDirectorySeparator(folder), StringComparison.OrdinalIgnoreCase);+}diff --git a/src/Filee.Setup/Installation/PreviousInstall.cs b/src/Filee.Setup/Installation/PreviousInstall.csnew file mode 100644index 00000000..1feba24c--- /dev/null+++ b/src/Filee.Setup/Installation/PreviousInstall.cs@@ -0,0 +1,125 @@+// Finds the Filee that is installed already: one installed by this Setup, by Filee 1.x's Inno Setup installer (same+// uninstall key, "Inno Setup: …" values, unins000.exe), or Filee 1.1's per-user Velopack copy. An update keeps the+// install folder and the user's choices, which come from what is registered now (the desktop shortcut, PATH, the+// Explorer menu package) rather than from what was ticked once.++using Filee.Setup.Platform;++namespace Filee.Setup.Installation;++/// <param name="Folder">The install folder (has Filee.exe).</param>+/// <param name="Version">DisplayVersion of the uninstall entry.</param>+/// <param name="ByInno">Installed by Filee 1.x's Inno Setup installer.</param>+/// <param name="RecordedTasks">The options of the last install ("Inno Setup: Selected Tasks" or ours).</param>+/// <param name="Record">uninstall.json of an install by this Setup.</param>+public sealed record PreviousInstall(+ string Folder,+ string? Version,+ InstallScope Scope,+ bool ByInno,+ SetupTasks? RecordedTasks,+ string? Language,+ InstallRecord? Record)+{+ public static Hive HiveOf(InstallScope scope) => scope == InstallScope.Machine ? Hive.LocalMachine : Hive.CurrentUser;++ /// <summary>The installed Filee for <paramref name="scope"/>, or null (also when its entry points to nothing).</summary>+ public static PreviousInstall? Find(ISetupRegistry registry, InstallScope scope)+ {+ var hive = HiveOf(scope);+ const string key = SetupNames.UninstallKey;+ if (!registry.KeyExists(hive, key))+ return null;+ var folder = registry.Get(hive, key, "InstallLocation")?.Text;+ if (string.IsNullOrWhiteSpace(folder))+ folder = registry.Get(hive, key, SetupNames.InnoAppPathValue)?.Text;+ if (string.IsNullOrWhiteSpace(folder))+ return null;+ folder = Path.TrimEndingDirectorySeparator(Environment.ExpandEnvironmentVariables(folder.Trim().Trim('"')));+ if (!File.Exists(Path.Combine(folder, SetupNames.AppExe)))+ return null;+ var byInno = registry.Get(hive, key, SetupNames.InnoVersionValue) is not null+ || File.Exists(Path.Combine(folder, SetupNames.InnoUninstallerFiles[0]));+ var tasks = registry.Get(hive, key, SetupNames.TasksValue)?.Text ?? registry.Get(hive, key, SetupNames.InnoTasksValue)?.Text;+ var language = registry.Get(hive, key, SetupNames.LanguageValue)?.Text ?? registry.Get(hive, key, SetupNames.InnoLanguageValue)?.Text;+ return new PreviousInstall(+ folder,+ registry.Get(hive, key, "DisplayVersion")?.Text,+ scope,+ byInno,+ tasks is null ? null : SetupTasks.FromInnoString(tasks),+ language,+ InstallRecord.Read(folder));+ }++ /// <summary>+ /// The files of this installation that an update replaces or removes: the recorded list, or for an Inno Setup+ /// install (which copied the whole published app recursively) everything in the folder, Inno's uninstaller files+ /// included. Paths are relative to <see cref="Folder"/>.+ /// </summary>+ public IReadOnlyList<string> OwnedFiles()+ {+ if (Record is not null)+ return Record.Files;+ if (!ByInno)+ return [];+ return Directory.EnumerateFiles(Folder, "*", SearchOption.AllDirectories)+ .Select(f => Path.GetRelativePath(Folder, f))+ .Where(f => !f.StartsWith(FileSwap.WorkFolderPrefix, StringComparison.OrdinalIgnoreCase))+ .ToList();+ }++ /// <summary>+ /// The options as they are now: the desktop shortcut and PATH entry exist or not, the Explorer menu package is+ /// registered or not. The Explorer menu entry and start at sign-in are Filee settings, which an update leaves to+ /// Filee: those come from the last install.+ /// </summary>+ public SetupTasks CurrentTasks(ISetupRegistry registry, ISetupSystem system, SetupPaths paths) => new(+ RecordedTasks?.ContextMenu ?? true,+ system.ExplorerMenuSupported && system.IsExplorerMenuRegistered(),+ RecordedTasks?.Startup ?? true,+ PathVariable.IsOnPath(registry, Scope, Path.Combine(Folder, SetupNames.CliFolder)),+ File.Exists(Path.Combine(paths.Desktop(Scope), SetupNames.ShortcutName)));+}++/// <summary>Filee 1.1 and earlier, installed by Velopack into %LocalAppData%\Filee for one user.</summary>+public static class VelopackInstall+{+ public static string Root(SetupPaths paths) => Path.Combine(paths.LocalAppData, "Filee");++ public static bool Exists(SetupPaths paths) =>+ File.Exists(Path.Combine(Root(paths), "Update.exe")) && Directory.Exists(Path.Combine(Root(paths), "current"));++ /// <summary>+ /// Removes it without running its uninstaller, which would also delete the downloaded engines (and the settings+ /// are in %APPDATA%). Its registry entries (context menu, startup) are rewritten by the new Filee.+ /// </summary>+ public static void Remove(SetupPaths paths, ISetupRegistry registry, ISetupSystem system, SetupLog log)+ {+ var root = Root(paths);+ log.Info($"Removing Filee 1.1 (Velopack) from {root}; settings and engines stay");+ // Its Explorer menu entry points into the folder that goes next.+ system.UnregisterExplorerMenu();+ foreach (var file in new[] { "Update.exe", SetupNames.AppExe })+ DeleteFile(Path.Combine(root, file), system, log);+ FileSwap.DeleteTree(Path.Combine(root, "current"), system, log);+ FileSwap.DeleteTree(Path.Combine(root, "packages"), system, log);+ DeleteFile(Path.Combine(paths.UserStartMenu, SetupNames.ShortcutName), system, log);+ DeleteFile(Path.Combine(paths.UserDesktop, SetupNames.ShortcutName), system, log);+ registry.DeleteKey(Hive.CurrentUser, SetupNames.VelopackUninstallKey);+ }++ private static void DeleteFile(string path, ISetupSystem system, SetupLog log)+ {+ try+ {+ if (File.Exists(path))+ File.Delete(path);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ log.Info($"In use, deleted at the next restart: {path}");+ system.DeleteAtRestart(path);+ }+ }+}diff --git a/src/Filee.Setup/Installation/RuntimeCheck.cs b/src/Filee.Setup/Installation/RuntimeCheck.csnew file mode 100644index 00000000..c7dc3518--- /dev/null+++ b/src/Filee.Setup/Installation/RuntimeCheck.cs@@ -0,0 +1,120 @@+// Does every program Setup installs find the Microsoft Visual C++ runtime it was built against? Filee itself is a+// self-contained .NET app and needs nothing; a bundled engine built with MSVC (rhwp.exe) needs vcruntime140.dll and+// friends, either next to it (app-local, as the build copies them) or installed in System32 by the Visual C+++// Redistributable. Setup reads the import table of each .exe and .dll and reports what would be missing on this PC,+// so a missing runtime is a clear message instead of an engine that fails to start.++using System.Buffers.Binary;+using System.Text;+using System.Text.RegularExpressions;++namespace Filee.Setup.Installation;++/// <summary>A program and a runtime DLL it imports that is neither next to it nor in System32.</summary>+/// <param name="Program">Relative to the install folder.</param>+public sealed record MissingRuntime(string Program, string Dll);++public static partial class RuntimeCheck+{+ /// <summary>The Visual C++ runtime DLLs (vcruntime140.dll, msvcp140_1.dll, concrt140.dll, vcomp140.dll …).</summary>+ [GeneratedRegex(@"^(vcruntime|msvcp|concrt|vcomp|vccorlib|mfc|mfcm)140[a-z0-9_]*\.dll$", RegexOptions.IgnoreCase)]+ private static partial Regex VcRuntimeDll();++ public static bool IsVcRuntime(string dll) => VcRuntimeDll().IsMatch(dll);++ /// <summary>Checks every program in <paramref name="folder"/>.</summary>+ public static IReadOnlyList<MissingRuntime> FindMissing(string folder, string systemFolder)+ {+ var missing = new List<MissingRuntime>();+ foreach (var file in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))+ {+ var extension = Path.GetExtension(file);+ if (!extension.Equals(".exe", StringComparison.OrdinalIgnoreCase) && !extension.Equals(".dll", StringComparison.OrdinalIgnoreCase))+ continue;+ var directory = Path.GetDirectoryName(file)!;+ foreach (var dll in ImportedDlls(file).Where(IsVcRuntime))+ {+ if (!File.Exists(Path.Combine(directory, dll)) && !File.Exists(Path.Combine(systemFolder, dll)))+ missing.Add(new MissingRuntime(Path.GetRelativePath(folder, file), dll.ToLowerInvariant()));+ }+ }+ return missing;+ }++ /// <summary>The DLL names in a PE file's import table (empty for anything else, .NET assemblies included).</summary>+ public static IReadOnlyList<string> ImportedDlls(string file)+ {+ try+ {+ using var stream = File.OpenRead(file);+ if (stream.Length < 0x40)+ return [];+ var headers = new byte[Math.Min(stream.Length, 4096)];+ stream.ReadExactly(headers);+ if (headers[0] != 'M' || headers[1] != 'Z')+ return [];+ var pe = BinaryPrimitives.ReadInt32LittleEndian(headers.AsSpan(0x3C));+ if (pe <= 0 || pe + 24 > headers.Length || BinaryPrimitives.ReadUInt32LittleEndian(headers.AsSpan(pe)) != 0x00004550)+ return [];+ var sections = BinaryPrimitives.ReadUInt16LittleEndian(headers.AsSpan(pe + 6));+ var optionalSize = BinaryPrimitives.ReadUInt16LittleEndian(headers.AsSpan(pe + 20));+ var optional = pe + 24;+ if (optional + optionalSize > headers.Length)+ return [];+ var magic = BinaryPrimitives.ReadUInt16LittleEndian(headers.AsSpan(optional));+ var directories = optional + (magic == 0x20B ? 112 : 96);+ var count = BinaryPrimitives.ReadUInt32LittleEndian(headers.AsSpan(directories - 4));+ if (count < 2)+ return [];+ var importRva = BinaryPrimitives.ReadUInt32LittleEndian(headers.AsSpan(directories + 8));+ if (importRva == 0)+ return [];+ var table = optional + optionalSize;+ var sectionList = new List<(uint Rva, uint Size, uint Raw)>();+ for (var i = 0; i < sections && table + (i + 1) * 40 <= headers.Length; i++)+ {+ var s = table + i * 40;+ var virtualSize = BinaryPrimitives.ReadUInt32LittleEndian(headers.AsSpan(s + 8));+ var rva = BinaryPrimitives.ReadUInt32LittleEndian(headers.AsSpan(s + 12));+ var rawSize = BinaryPrimitives.ReadUInt32LittleEndian(headers.AsSpan(s + 16));+ var raw = BinaryPrimitives.ReadUInt32LittleEndian(headers.AsSpan(s + 20));+ sectionList.Add((rva, Math.Max(virtualSize, rawSize), raw));+ }+ long? Offset(uint rva)+ {+ foreach (var (start, size, raw) in sectionList)+ if (rva >= start && rva < start + size)+ return raw + (long)(rva - start);+ return null;+ }++ var names = new List<string>();+ var descriptor = Offset(importRva);+ if (descriptor is null)+ return [];+ var entry = new byte[20];+ for (var i = 0; i < 4096; i++)+ {+ stream.Position = descriptor.Value + i * 20L;+ if (stream.Read(entry) < 20)+ break;+ var nameRva = BinaryPrimitives.ReadUInt32LittleEndian(entry.AsSpan(12));+ if (nameRva == 0 && BinaryPrimitives.ReadUInt32LittleEndian(entry) == 0)+ break;+ if (Offset(nameRva) is not { } nameOffset)+ continue;+ stream.Position = nameOffset;+ var name = new StringBuilder();+ for (int b; name.Length < 260 && (b = stream.ReadByte()) > 0;)+ name.Append((char)b);+ if (name.Length > 0)+ names.Add(name.ToString());+ }+ return names;+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentOutOfRangeException)+ {+ return [];+ }+ }+}diff --git a/src/Filee.Setup/Installation/SetupContext.cs b/src/Filee.Setup/Installation/SetupContext.csnew file mode 100644index 00000000..33c790e5--- /dev/null+++ b/src/Filee.Setup/Installation/SetupContext.cs@@ -0,0 +1,69 @@+// What an install or uninstall works with, and what it reports back.++using Filee.Setup.Platform;++namespace Filee.Setup.Installation;++/// <param name="Sandbox">A /SANDBOX run: Filee is never started.</param>+public sealed record SetupContext(ISetupRegistry Registry, ISetupSystem System, SetupPaths Paths, SetupLog Log, bool Sandbox = false);++/// <summary>What the user chose (or the command line said).</summary>+/// <param name="Folder">The install folder.</param>+/// <param name="Engines">Engine packages Filee downloads when it starts (a fresh install's choice).</param>+/// <param name="Language">Setup's language.</param>+/// <param name="LanguagePicked">The user picked <paramref name="Language"/> (or /LANG= did): a fresh Filee starts in+/// it too. Otherwise Filee keeps following Windows' language.</param>+/// <param name="NoIcons">/NOICONS: no Start menu or desktop shortcut.</param>+/// <param name="Portable">/PORTABLE=1: only the files.</param>+/// <param name="ForceClose">Programs still running from the install folder after "Filee --quit" are ended.</param>+public sealed record InstallChoices(+ string Folder,+ InstallScope Scope,+ SetupTasks Tasks,+ IReadOnlyList<string> Engines,+ string Language,+ bool LanguagePicked = false,+ bool NoIcons = false,+ bool Portable = false,+ bool ForceClose = true);++/// <summary>What Setup is doing (the progress page shows it in the UI language).</summary>+public enum SetupStep+{+ Verifying,+ Closing,+ RemovingOld,+ Copying,+ ExplorerMenu,+ Finishing,+ RollingBack,+ Removing,+}++public sealed record SetupProgress(SetupStep Step, double Fraction);++/// <summary>Something that didn't work but leaves a working Filee.</summary>+public abstract record SetupWarning;++/// <summary>Windows didn't register the top-level Explorer menu (Filee is still under "Show more options").</summary>+public sealed record ExplorerMenuWarning(string Error) : SetupWarning;++/// <summary>Programs that need a Microsoft Visual C++ runtime this PC doesn't have.</summary>+public sealed record RuntimeWarning(IReadOnlyList<MissingRuntime> Missing) : SetupWarning;++/// <summary>Start Filee as the signed-in user with these arguments.</summary>+public sealed record LaunchRequest(string Executable, string Arguments);++/// <summary>A problem with a message for the user (the key of a translated text and its arguments).</summary>+public sealed class SetupException(string textKey, string message, params string[] arguments) : Exception(message)+{+ public string TextKey { get; } = textKey;+ public IReadOnlyList<string> Arguments { get; } = arguments;+}++/// <param name="Error">Why it failed; null when it worked.</param>+/// <param name="RolledBack">The install folder is as it was before (the previous Filee still works).</param>+public sealed record InstallResult(LaunchRequest? Launch, IReadOnlyList<SetupWarning> Warnings, Exception? Error = null, bool RolledBack = false)+{+ public bool Succeeded => Error is null;+}diff --git a/src/Filee.Setup/Installation/SetupNames.cs b/src/Filee.Setup/Installation/SetupNames.csnew file mode 100644index 00000000..96513e34--- /dev/null+++ b/src/Filee.Setup/Installation/SetupNames.cs@@ -0,0 +1,54 @@+// Names Setup shares with Filee 1.x's Inno Setup installer, the app and Windows. Changing one breaks updates.++namespace Filee.Setup.Installation;++public static class SetupNames+{+ /// <summary>+ /// Inno Setup's AppId of Filee (installer/Filee.iss, 1.x). Apps & Features lists Filee under the uninstall key+ /// "{id}_is1"; Setup keeps that key, so an update from 1.x leaves one entry.+ /// </summary>+ public const string AppGuid = "C8686E06-8327-40A2-B0F7-3DEDD61D9248";++ public const string UninstallKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\{" + AppGuid + "}_is1";++ /// <summary>Filee 1.1 and earlier: Velopack installed it per user and registered it here (HKCU).</summary>+ public const string VelopackUninstallKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\Filee";++ public const string MachineEnvironmentKey = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";+ public const string UserEnvironmentKey = "Environment";++ public const string AppName = "Filee";+ public const string Publisher = "Filee contributors";+ public const string AppExe = "Filee.exe";++ /// <summary>The uninstaller next to Filee.exe (UpdateService.IsInstalled looks for it).</summary>+ public const string UninstallerExe = "uninstall.exe";++ /// <summary>The list of installed files next to Filee.exe: what the uninstaller removes and an update replaces.</summary>+ public const string InstallRecordFile = "uninstall.json";++ /// <summary>The "filee" command (cli\filee.cmd), the folder Setup puts on PATH.</summary>+ public const string CliFolder = "cli";++ /// <summary>Inno Setup's uninstaller files, removed when Setup takes over a 1.x installation.</summary>+ public static readonly IReadOnlyList<string> InnoUninstallerFiles = ["unins000.exe", "unins000.dat", "unins000.msg"];++ /// <summary>Start menu and desktop shortcut name.</summary>+ public const string ShortcutName = "Filee.lnk";++ /// <summary>Registry values Setup adds to the uninstall key (Inno Setup kept the same in "Inno Setup: …").</summary>+ public const string TasksValue = "Filee Setup: Tasks";+ public const string LanguageValue = "Filee Setup: Language";+ public const string ScopeValue = "Filee Setup: Scope";+ public const string InnoTasksValue = "Inno Setup: Selected Tasks";+ public const string InnoAppPathValue = "Inno Setup: App Path";+ public const string InnoVersionValue = "Inno Setup: Setup Version";+ public const string InnoLanguageValue = "Inno Setup: Language";++ /// <summary>Windows 10 1809: the oldest Windows Filee runs on (Inno Setup's MinVersion).</summary>+ public const int MinimumBuild = 17763;++ /// <summary>Where Microsoft offers the Visual C++ Redistributable (x64).</summary>+ public const string VcRedistUrl = "https://aka.ms/vs/17/release/vc_redist.x64.exe";+}diff --git a/src/Filee.Setup/Installation/SetupTasks.cs b/src/Filee.Setup/Installation/SetupTasks.csnew file mode 100644index 00000000..abaf112b--- /dev/null+++ b/src/Filee.Setup/Installation/SetupTasks.cs@@ -0,0 +1,101 @@+// The options ("tasks") of Setup, with the names Inno Setup used for them (installer/Filee.iss, 1.x): /TASKS= and+// /MERGETASKS= take these names, and an update from 1.x reads them from the registry ("Inno Setup: Selected Tasks").++namespace Filee.Setup.Installation;++/// <summary>What Setup sets up besides copying the files.</summary>+/// <param name="ContextMenu">"Convert with Filee" in the Explorer menu (a Filee setting, applied by Filee).</param>+/// <param name="ModernMenu">Also at the top of the Windows 11 menu: the sparse package, registered by Setup.</param>+/// <param name="Startup">Start Filee at sign-in (a Filee setting).</param>+/// <param name="Cli">The <c>filee</c> command on PATH.</param>+/// <param name="DesktopIcon">A desktop shortcut.</param>+public sealed record SetupTasks(bool ContextMenu, bool ModernMenu, bool Startup, bool Cli, bool DesktopIcon)+{+ public const string ContextMenuName = "contextmenu";+ public const string ModernMenuName = @"contextmenu\top";+ public const string StartupName = "startup";+ public const string CliName = "cli";+ public const string DesktopIconName = "desktopicon";++ /// <summary>Every task, parents before their children.</summary>+ public static readonly IReadOnlyList<string> Names = [ContextMenuName, ModernMenuName, StartupName, CliName, DesktopIconName];++ /// <summary>What a fresh install ticks: everything but the desktop shortcut.</summary>+ public static SetupTasks Defaults { get; } = new(true, true, true, true, false);++ /// <summary>+ /// /TASKS (only the listed tasks) and /MERGETASKS (changes to the defaults), as Inno Setup reads them:+ /// "!name" unticks, "*name" ticks the task and its children. A ticked child ticks its parent.+ /// </summary>+ public static SetupTasks FromCommandLine(string? tasks, string? mergeTasks)+ {+ var selected = tasks is null ? Defaults.ToSet() : new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ Apply(selected, tasks);+ Apply(selected, mergeTasks);+ return FromSet(selected);+ }++ /// <summary>The tasks in Inno Setup's registry format ("contextmenu,contextmenu\top,cli").</summary>+ public string ToInnoString() => string.Join(',', Names.Where(ToSet().Contains));++ /// <summary>Reads Inno Setup's "Inno Setup: Selected Tasks" (or our own copy of it).</summary>+ public static SetupTasks FromInnoString(string? value)+ {+ var selected = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ Apply(selected, value);+ return FromSet(selected);+ }++ /// <summary>The task names Setup knows in <paramref name="list"/> that it doesn't (logged).</summary>+ public static IEnumerable<string> UnknownNames(string? list) =>+ Split(list).Select(n => n.TrimStart('!', '*')).Where(n => !Names.Contains(n, StringComparer.OrdinalIgnoreCase));++ private static void Apply(HashSet<string> selected, string? list)+ {+ foreach (var entry in Split(list))+ {+ var name = entry.TrimStart('!', '*');+ if (!Names.Contains(name, StringComparer.OrdinalIgnoreCase))+ continue;+ var children = Names.Where(n => n.StartsWith(name + "\\", StringComparison.OrdinalIgnoreCase)).ToList();+ if (entry.StartsWith('!'))+ {+ selected.Remove(name);+ // An unticked parent unticks its children (they can't be on without it).+ children.ForEach(c => selected.Remove(c));+ continue;+ }+ selected.Add(name);+ if (entry.StartsWith('*'))+ children.ForEach(c => selected.Add(c));+ for (var slash = name.LastIndexOf('\\'); slash > 0; slash = name.LastIndexOf('\\', slash - 1))+ selected.Add(name[..slash]);+ }+ }++ private static IEnumerable<string> Split(string? list) =>+ (list ?? "").Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);++ private HashSet<string> ToSet()+ {+ var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ if (ContextMenu)+ set.Add(ContextMenuName);+ if (ContextMenu && ModernMenu)+ set.Add(ModernMenuName);+ if (Startup)+ set.Add(StartupName);+ if (Cli)+ set.Add(CliName);+ if (DesktopIcon)+ set.Add(DesktopIconName);+ return set;+ }++ private static SetupTasks FromSet(HashSet<string> set) => new(+ set.Contains(ContextMenuName),+ set.Contains(ContextMenuName) && set.Contains(ModernMenuName),+ set.Contains(StartupName),+ set.Contains(CliName),+ set.Contains(DesktopIconName));+}diff --git a/src/Filee.Setup/Installation/Uninstaller.cs b/src/Filee.Setup/Installation/Uninstaller.csnew file mode 100644index 00000000..261afd32--- /dev/null+++ b/src/Filee.Setup/Installation/Uninstaller.cs@@ -0,0 +1,138 @@+// Removes Filee:+// 1. "Filee.exe --uninstall-cleanup": Filee quits and removes what it registered for the user (Explorer menu entries,+// the Send To shortcut, the startup entry, the Windows 11 package) and the engines it downloaded;+// 2. ends what still runs from the install folder, removes the Explorer menu package if it is still there;+// 3. removes the shortcuts, the PATH entry, the files of uninstall.json, the install folder and the uninstall entry;+// 4. deletes the settings (%APPDATA%\Filee) only when the user asked for it: by default they stay for a reinstall.+// A file Windows keeps in use (FileeExplorerMenu.dll loaded by Explorer, the running uninstall.exe) is moved out of+// the folder into the trash folder and deleted at the next restart, so the folder itself goes now.++using Filee.Setup.Platform;++namespace Filee.Setup.Installation;++public sealed class Uninstaller(SetupContext context)+{+ private ISetupRegistry Registry => context.Registry;+ private ISetupSystem System => context.System;+ private SetupLog Log => context.Log;++ /// <summary>Filee's cleanup also removes the Explorer menu package through PowerShell, which takes a while.</summary>+ public static TimeSpan CleanupTimeout { get; } = TimeSpan.FromSeconds(90);++ /// <param name="trash">A folder outside the install folder (same volume if possible) for files still in use.</param>+ /// <returns>Files and folders that are deleted at the next restart.</returns>+ public IReadOnlyList<string> Run(string folder, InstallRecord record, bool deleteSettings, string trash,+ IProgress<SetupProgress>? progress = null)+ {+ folder = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));+ Log.Info($"Uninstalling Filee {record.Version} from {folder} ({record.Scope}); delete settings: {deleteSettings}");+ var later = new List<string>();+ progress?.Report(new SetupProgress(SetupStep.Closing, 0));++ var exe = Path.Combine(folder, SetupNames.AppExe);+ if (File.Exists(exe))+ Log.Info($"Filee --uninstall-cleanup: exit code {System.RunAndWait(exe, "--uninstall-cleanup", CleanupTimeout)}");+ foreach (var program in System.ProgramsIn(folder).Where(p => p.Id != Environment.ProcessId))+ {+ // Not the uninstaller that started this one: it waits for this one and ends by itself.+ if (Path.GetFileName(program.Path).Equals(SetupNames.UninstallerExe, StringComparison.OrdinalIgnoreCase))+ continue;+ Log.Info($"Ending {program.Path} ({program.Id})");+ System.Kill(program.Id);+ }+ progress?.Report(new SetupProgress(SetupStep.Removing, 0.3));+ if (System.ExplorerMenuSupported)+ System.UnregisterExplorerMenu();++ var hive = PreviousInstall.HiveOf(record.Scope);+ foreach (var shortcut in new[] { context.Paths.StartMenu(record.Scope), context.Paths.Desktop(record.Scope) })+ DeleteFile(Path.Combine(shortcut, SetupNames.ShortcutName), trash, later);+ if (PathVariable.Set(Registry, record.Scope, Path.Combine(folder, SetupNames.CliFolder), present: false))+ {+ System.BroadcastEnvironmentChange();+ Log.Info("Removed the filee command from PATH");+ }++ progress?.Report(new SetupProgress(SetupStep.Removing, 0.5));+ var files = record.Files.Concat([SetupNames.InstallRecordFile, SetupNames.UninstallerExe]).Concat(SetupNames.InnoUninstallerFiles)+ .Distinct(StringComparer.OrdinalIgnoreCase).ToList();+ for (var i = 0; i < files.Count; i++)+ {+ DeleteFile(Path.Combine(folder, files[i]), trash, later);+ progress?.Report(new SetupProgress(SetupStep.Removing, 0.5 + 0.4 * (i + 1) / files.Count));+ }+ // Left by an interrupted Setup, and FileeExplorerMenu.dll copies an update moved aside.+ if (Directory.Exists(folder))+ {+ foreach (var work in Directory.EnumerateDirectories(folder, FileSwap.WorkFolderPrefix + "*"))+ FileSwap.DeleteTree(work, System, Log);+ }+ FileSwap.RemoveEmptyFolders(folder);+ try+ {+ if (Directory.Exists(folder))+ Directory.Delete(folder);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ // Something that isn't Filee's is still in it (a folder the user chose), or a file is in use.+ Log.Warn($"{folder} stays: {ex.Message}");+ if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any())+ {+ System.DeleteAtRestart(folder);+ later.Add(folder);+ }+ }++ Registry.DeleteKey(hive, SetupNames.UninstallKey);+ progress?.Report(new SetupProgress(SetupStep.Removing, 0.95));+ if (deleteSettings)+ {+ Log.Info($"Deleting the settings in {context.Paths.SettingsFolder}");+ FileSwap.DeleteTree(context.Paths.SettingsFolder, System, Log);+ }+ progress?.Report(new SetupProgress(SetupStep.Removing, 1));+ Log.Info("Uninstalled");+ return later;+ }++ /// <summary>Deletes a file; one in use is moved into <paramref name="trash"/> (or renamed in place) and deleted at the next restart.</summary>+ private void DeleteFile(string path, string trash, List<string> later)+ {+ if (!File.Exists(path))+ return;+ try+ {+ File.SetAttributes(path, FileAttributes.Normal);+ File.Delete(path);+ return;+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ Log.Info($"In use: {path} ({ex.Message})");+ }+ var aside = Path.Combine(trash, $"{Guid.NewGuid():N}-{Path.GetFileName(path)}");+ try+ {+ Directory.CreateDirectory(trash);+ File.Move(path, aside);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ // Another volume: renaming works only on the same one. Stay in the folder under another name.+ aside = path + "." + Guid.NewGuid().ToString("N")[..8] + ".old";+ try+ {+ File.Move(path, aside);+ }+ catch (Exception again) when (again is IOException or UnauthorizedAccessException)+ {+ Log.Warn($"Could not move {path} aside: {again.Message} ({ex.Message})");+ aside = path;+ }+ }+ System.DeleteAtRestart(aside);+ later.Add(aside);+ }+}diff --git a/src/Filee.Setup/Payload/PayloadManifest.cs b/src/Filee.Setup/Payload/PayloadManifest.csnew file mode 100644index 00000000..bcf871c2--- /dev/null+++ b/src/Filee.Setup/Payload/PayloadManifest.cs@@ -0,0 +1,120 @@+// What Setup carries: the published Filee (every file with its size and SHA-256), the version, and the conversion+// engines Setup can offer (from EngineDownloads, written at build time by build/tools/make-setup.cs).++using System.Text;+using System.Text.Json;++namespace Filee.Setup.Payload;++/// <summary>One file of the app, relative to the install folder (backslashes).</summary>+public sealed record PayloadFile(string Path, long Size, string Sha256);++/// <summary>An engine package of Settings → Engines, as Setup offers it on a fresh install.</summary>+/// <param name="MarkerFolders">Folders under %LocalAppData%\Filee\engines that are all marked when it is installed.</param>+public sealed record EngineOffer(string Id, IReadOnlyList<string> MarkerFolders, long DownloadSize, long InstalledSize, bool Suggested);++public sealed record PayloadManifest(+ string Version,+ IReadOnlyList<PayloadFile> Files,+ string CompressedSha256,+ IReadOnlyList<EngineOffer> Engines,+ string EngineMarker)+{+ /// <summary>Format of the payload; a Setup refuses a payload with another one.</summary>+ public const int CurrentFormat = 1;++ public long TotalSize => Files.Sum(f => f.Size);++ public byte[] ToJson()+ {+ using var stream = new MemoryStream();+ using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))+ {+ writer.WriteStartObject();+ writer.WriteNumber("format", CurrentFormat);+ writer.WriteString("version", Version);+ writer.WriteString("compression", "brotli");+ writer.WriteString("compressedSha256", CompressedSha256);+ writer.WriteString("engineMarker", EngineMarker);+ writer.WriteStartArray("engines");+ foreach (var engine in Engines)+ {+ writer.WriteStartObject();+ writer.WriteString("id", engine.Id);+ writer.WriteStartArray("markerFolders");+ foreach (var folder in engine.MarkerFolders)+ writer.WriteStringValue(folder);+ writer.WriteEndArray();+ writer.WriteNumber("downloadSize", engine.DownloadSize);+ writer.WriteNumber("installedSize", engine.InstalledSize);+ writer.WriteBoolean("suggested", engine.Suggested);+ writer.WriteEndObject();+ }+ writer.WriteEndArray();+ writer.WriteStartArray("files");+ foreach (var file in Files)+ {+ writer.WriteStartObject();+ writer.WriteString("path", file.Path);+ writer.WriteNumber("size", file.Size);+ writer.WriteString("sha256", file.Sha256);+ writer.WriteEndObject();+ }+ writer.WriteEndArray();+ writer.WriteEndObject();+ }+ return stream.ToArray();+ }++ /// <summary>Reads and checks a manifest; throws <see cref="InvalidDataException"/> when it isn't one Setup can use.</summary>+ public static PayloadManifest FromJson(ReadOnlySpan<byte> json)+ {+ try+ {+ using var document = JsonDocument.Parse(json.ToArray());+ var root = document.RootElement;+ if (root.GetProperty("format").GetInt32() != CurrentFormat || root.GetProperty("compression").GetString() != "brotli")+ throw new InvalidDataException("Unknown payload format.");+ var files = root.GetProperty("files").EnumerateArray()+ .Select(f => new PayloadFile(f.GetProperty("path").GetString()!, f.GetProperty("size").GetInt64(), f.GetProperty("sha256").GetString()!))+ .ToList();+ foreach (var file in files)+ CheckPath(file.Path);+ if (files.Select(f => f.Path).Distinct(StringComparer.OrdinalIgnoreCase).Count() != files.Count)+ throw new InvalidDataException("The payload lists a file twice.");+ var engines = root.TryGetProperty("engines", out var list)+ ? list.EnumerateArray().Select(e => new EngineOffer(+ e.GetProperty("id").GetString()!,+ e.GetProperty("markerFolders").EnumerateArray().Select(m => m.GetString()!).ToList(),+ e.GetProperty("downloadSize").GetInt64(),+ e.GetProperty("installedSize").GetInt64(),+ e.GetProperty("suggested").GetBoolean())).ToList()+ : [];+ return new PayloadManifest(+ root.GetProperty("version").GetString()!,+ files,+ root.GetProperty("compressedSha256").GetString()!,+ engines,+ root.TryGetProperty("engineMarker", out var marker) ? marker.GetString() ?? "" : "");+ }+ catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException or NullReferenceException)+ {+ throw new InvalidDataException("The payload manifest can't be read.", ex);+ }+ }++ /// <summary>+ /// A relative path that stays inside the install folder: no root, no "..", no drive, no alternate data stream.+ /// The payload is checked by its hash anyway; this keeps a broken one from writing elsewhere.+ /// </summary>+ public static void CheckPath(string path)+ {+ if (string.IsNullOrWhiteSpace(path) || System.IO.Path.IsPathRooted(path) || path.Contains(':')+ || path.Split('\\', '/').Any(part => part is "" or "." or ".."))+ throw new InvalidDataException($"Bad path in the payload: {path}");+ }++ public static string Hex(byte[] hash) => Convert.ToHexString(hash).ToLowerInvariant();++ internal static Encoding Utf8 { get; } = new UTF8Encoding(false);+}diff --git a/src/Filee.Setup/Payload/SetupPayload.cs b/src/Filee.Setup/Payload/SetupPayload.csnew file mode 100644index 00000000..8c894c5a--- /dev/null+++ b/src/Filee.Setup/Payload/SetupPayload.cs@@ -0,0 +1,360 @@+// The payload appended to Setup.exe:+//+// [Setup program][Brotli stream: every file of the app, one after the other][manifest JSON][trailer, 72 bytes]+// (then, once Setup is signed, the Authenticode signature: the trailer sits right before it)+//+// Trailer: "FILEE-PAYLOAD-01", payload offset, compressed length, manifest length (little-endian Int64 each) and the+// SHA-256 of the manifest. The manifest holds the SHA-256 of the compressed stream and of every file. One stream for+// all files compresses far better than a zip (the .NET assemblies share much). Setup checks the stream's hash before+// it changes anything and every file's hash while unpacking.++using System.Buffers;+using System.Buffers.Binary;+using System.IO.Compression;+using System.Security.Cryptography;+using System.Text;++namespace Filee.Setup.Payload;++public sealed class SetupPayload : IDisposable+{+ public const string Magic = "FILEE-PAYLOAD-01";+ public const int TrailerLength = 16 + 8 + 8 + 8 + 32;+ private const int BufferSize = 1 << 20;++ private readonly FileStream _file;++ private SetupPayload(FileStream file, long offset, long length, PayloadManifest manifest)+ {+ _file = file;+ Offset = offset;+ CompressedLength = length;+ Manifest = manifest;+ }++ public PayloadManifest Manifest { get; }++ /// <summary>Where the payload starts: the Setup program before it is the uninstaller.</summary>+ public long Offset { get; }++ public long CompressedLength { get; }++ /// <summary>+ /// Opens the payload of <paramref name="exe"/>; null when it has none (uninstall.exe, a development build).+ /// Throws <see cref="InvalidDataException"/> when there is one but it is damaged.+ /// </summary>+ public static SetupPayload? Open(string exe)+ {+ var file = new FileStream(exe, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.SequentialScan);+ try+ {+ var end = OverlayEnd(file);+ if (end < TrailerLength)+ {+ file.Dispose();+ return null;+ }+ var trailer = new byte[TrailerLength];+ file.Position = end - TrailerLength;+ file.ReadExactly(trailer);+ if (Encoding.ASCII.GetString(trailer, 0, 16) != Magic)+ {+ file.Dispose();+ return null;+ }+ var offset = BinaryPrimitives.ReadInt64LittleEndian(trailer.AsSpan(16));+ var length = BinaryPrimitives.ReadInt64LittleEndian(trailer.AsSpan(24));+ var manifestLength = BinaryPrimitives.ReadInt64LittleEndian(trailer.AsSpan(32));+ var manifestHash = trailer.AsSpan(40, 32).ToArray();+ if (offset <= 0 || length < 0 || manifestLength <= 0 || manifestLength > 64 << 20+ || offset + length + manifestLength + TrailerLength != end)+ throw new InvalidDataException("The payload trailer is damaged.");+ var manifestBytes = new byte[manifestLength];+ file.Position = offset + length;+ file.ReadExactly(manifestBytes);+ if (!SHA256.HashData(manifestBytes).AsSpan().SequenceEqual(manifestHash))+ throw new InvalidDataException("The payload manifest is damaged.");+ return new SetupPayload(file, offset, length, PayloadManifest.FromJson(manifestBytes));+ }+ catch+ {+ file.Dispose();+ throw;+ }+ }++ /// <summary>+ /// End of the data appended to the program: the file's end, or where its Authenticode signature starts (signing+ /// appends the certificate table after the payload).+ /// </summary>+ internal static long OverlayEnd(Stream file)+ {+ var length = file.Length;+ try+ {+ Span<byte> buffer = stackalloc byte[8];+ file.Position = 0x3C;+ file.ReadExactly(buffer[..4]);+ var pe = BinaryPrimitives.ReadInt32LittleEndian(buffer);+ if (pe <= 0 || pe > length - 24)+ return length;+ file.Position = pe;+ file.ReadExactly(buffer[..4]);+ if (BinaryPrimitives.ReadUInt32LittleEndian(buffer) != 0x00004550) // "PE\0\0"+ return length;+ var optionalHeader = pe + 4 + 20;+ file.Position = optionalHeader;+ file.ReadExactly(buffer[..2]);+ var magic = BinaryPrimitives.ReadUInt16LittleEndian(buffer);+ var directories = optionalHeader + (magic == 0x20B ? 112 : 96);+ file.Position = directories + 4 * 8; // IMAGE_DIRECTORY_ENTRY_SECURITY+ file.ReadExactly(buffer);+ var certificates = BinaryPrimitives.ReadUInt32LittleEndian(buffer);+ var size = BinaryPrimitives.ReadUInt32LittleEndian(buffer[4..]);+ // The certificate table's "address" is a file offset.+ return certificates > 0 && certificates + (long)size == length ? certificates : length;+ }+ catch (EndOfStreamException)+ {+ return length;+ }+ }++ /// <summary>Checks the compressed stream against the manifest. Throws <see cref="InvalidDataException"/>.</summary>+ public void Verify(IProgress<double>? progress = null, CancellationToken cancellation = default)+ {+ using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);+ var buffer = ArrayPool<byte>.Shared.Rent(BufferSize);+ try+ {+ _file.Position = Offset;+ var left = CompressedLength;+ while (left > 0)+ {+ cancellation.ThrowIfCancellationRequested();+ var read = _file.Read(buffer, 0, (int)Math.Min(buffer.Length, left));+ if (read == 0)+ throw new InvalidDataException("The payload is shorter than its manifest says.");+ hash.AppendData(buffer, 0, read);+ left -= read;+ progress?.Report(1 - (double)left / Math.Max(1, CompressedLength));+ }+ }+ finally+ {+ ArrayPool<byte>.Shared.Return(buffer);+ }+ if (PayloadManifest.Hex(hash.GetHashAndReset()) != Manifest.CompressedSha256)+ throw new InvalidDataException("The payload doesn't match its checksum.");+ }++ /// <summary>+ /// Unpacks every file into <paramref name="folder"/> and checks its size and SHA-256. Reports the bytes written.+ /// Throws <see cref="InvalidDataException"/> when a file doesn't match (the folder is then incomplete).+ /// </summary>+ public void ExtractTo(string folder, IProgress<long>? progress = null, CancellationToken cancellation = default)+ {+ _file.Position = Offset;+ using var compressed = new BoundedReadStream(_file, CompressedLength);+ using var brotli = new BrotliStream(compressed, CompressionMode.Decompress);+ var buffer = ArrayPool<byte>.Shared.Rent(BufferSize);+ long written = 0;+ try+ {+ foreach (var file in Manifest.Files)+ {+ cancellation.ThrowIfCancellationRequested();+ var target = Path.Combine(folder, file.Path);+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);+ using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);+ using (var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize))+ {+ var left = file.Size;+ while (left > 0)+ {+ var read = brotli.Read(buffer, 0, (int)Math.Min(buffer.Length, left));+ if (read == 0)+ throw new InvalidDataException($"The payload ends inside {file.Path}.");+ hash.AppendData(buffer, 0, read);+ output.Write(buffer, 0, read);+ left -= read;+ written += read;+ progress?.Report(written);+ }+ }+ if (PayloadManifest.Hex(hash.GetHashAndReset()) != file.Sha256)+ throw new InvalidDataException($"{file.Path} doesn't match its checksum.");+ }+ if (brotli.Read(buffer, 0, 1) != 0)+ throw new InvalidDataException("The payload has more data than its manifest lists.");+ }+ finally+ {+ ArrayPool<byte>.Shared.Return(buffer);+ }+ }++ /// <summary>Writes the Setup program without the payload: the uninstaller.</summary>+ public void CopyProgramTo(string path)+ {+ _file.Position = 0;+ using var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, BufferSize);+ using var program = new BoundedReadStream(_file, Offset);+ program.CopyTo(output, BufferSize);+ }++ public void Dispose() => _file.Dispose();++ /// <summary>+ /// Appends <paramref name="appFolder"/> to a copy of <paramref name="setupProgram"/>: writes <paramref name="output"/>,+ /// the finished Setup. Brotli quality 11 with the largest window compresses best (and slowest).+ /// </summary>+ public static PayloadManifest Write(string setupProgram, string appFolder, string output, string version,+ IReadOnlyList<EngineOffer> engines, string engineMarker, int quality = 11, int window = 24, Action<string>? log = null)+ {+ appFolder = Path.GetFullPath(appFolder);+ // Similar files next to each other compress better: by extension, then by path.+ var paths = Directory.EnumerateFiles(appFolder, "*", SearchOption.AllDirectories)+ .Select(p => Path.GetRelativePath(appFolder, p))+ .OrderBy(p => Path.GetExtension(p), StringComparer.OrdinalIgnoreCase)+ .ThenBy(p => p, StringComparer.OrdinalIgnoreCase)+ .ToList();+ var files = new List<PayloadFile>();+ var partial = output + ".partial";+ using (var target = new FileStream(partial, FileMode.Create, FileAccess.ReadWrite, FileShare.None, BufferSize))+ {+ using (var program = File.OpenRead(setupProgram))+ {+ if (SetupPayload.OverlayEnd(program) != program.Length)+ throw new InvalidOperationException("Sign Setup after appending the payload, not before.");+ program.Position = 0;+ program.CopyTo(target);+ }+ var offset = target.Position;+ using var compressedHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);+ using (var compressor = new BrotliWriteStream(target, quality, window, compressedHash))+ {+ foreach (var relative in paths)+ {+ PayloadManifest.CheckPath(relative);+ using var input = File.OpenRead(Path.Combine(appFolder, relative));+ using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);+ var buffer = new byte[BufferSize];+ int read;+ long size = 0;+ while ((read = input.Read(buffer)) > 0)+ {+ hash.AppendData(buffer, 0, read);+ compressor.Write(buffer, 0, read);+ size += read;+ }+ files.Add(new PayloadFile(relative, size, PayloadManifest.Hex(hash.GetHashAndReset())));+ log?.Invoke(relative);+ }+ }+ var length = target.Position - offset;+ var manifest = new PayloadManifest(version, files, PayloadManifest.Hex(compressedHash.GetHashAndReset()), engines, engineMarker);+ var json = manifest.ToJson();+ target.Write(json);+ var trailer = new byte[TrailerLength];+ Encoding.ASCII.GetBytes(Magic).CopyTo(trailer, 0);+ BinaryPrimitives.WriteInt64LittleEndian(trailer.AsSpan(16), offset);+ BinaryPrimitives.WriteInt64LittleEndian(trailer.AsSpan(24), length);+ BinaryPrimitives.WriteInt64LittleEndian(trailer.AsSpan(32), json.Length);+ SHA256.HashData(json).CopyTo(trailer, 40);+ target.Write(trailer);+ }+ File.Move(partial, output, overwrite: true);+ using var check = Open(output) ?? throw new InvalidDataException("The payload was not written.");+ return check.Manifest;+ }++ /// <summary>Reads at most <c>length</c> bytes from the current position of a stream it doesn't own.</summary>+ private sealed class BoundedReadStream(Stream inner, long length) : Stream+ {+ private long _left = length;++ public override bool CanRead => true;+ public override bool CanSeek => false;+ public override bool CanWrite => false;+ public override long Length => throw new NotSupportedException();+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }++ public override int Read(byte[] buffer, int offset, int count)+ {+ if (_left <= 0)+ return 0;+ var read = inner.Read(buffer, offset, (int)Math.Min(count, _left));+ _left -= read;+ return read;+ }++ public override void Flush()+ {+ }++ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();+ public override void SetLength(long value) => throw new NotSupportedException();+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();+ }++ /// <summary>Brotli with a chosen window (BrotliStream only takes the quality), hashing what it writes.</summary>+ private sealed class BrotliWriteStream(Stream inner, int quality, int window, IncrementalHash hash) : Stream+ {+ private BrotliEncoder _encoder = new(quality, window);+ private readonly byte[] _output = new byte[BufferSize];++ public override bool CanRead => false;+ public override bool CanSeek => false;+ public override bool CanWrite => true;+ public override long Length => throw new NotSupportedException();+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }++ public override void Write(byte[] buffer, int offset, int count)+ {+ var input = buffer.AsSpan(offset, count);+ while (true)+ {+ var status = _encoder.Compress(input, _output, out var consumed, out var produced, isFinalBlock: false);+ Emit(produced);+ input = input[consumed..];+ if (status == OperationStatus.InvalidData)+ throw new InvalidDataException("Brotli refused the data.");+ if (input.IsEmpty && status == OperationStatus.Done)+ return;+ }+ }++ protected override void Dispose(bool disposing)+ {+ if (disposing)+ {+ while (true)+ {+ var status = _encoder.Compress(ReadOnlySpan<byte>.Empty, _output, out _, out var produced, isFinalBlock: true);+ Emit(produced);+ if (status == OperationStatus.Done)+ break;+ }+ _encoder.Dispose();+ }+ base.Dispose(disposing);+ }++ private void Emit(int produced)+ {+ if (produced == 0)+ return;+ inner.Write(_output, 0, produced);+ hash.AppendData(_output, 0, produced);+ }++ public override void Flush()+ {+ }++ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();+ public override void SetLength(long value) => throw new NotSupportedException();+ }+}diff --git a/src/Filee.Setup/Platform/NativeMethods.cs b/src/Filee.Setup/Platform/NativeMethods.csnew file mode 100644index 00000000..a4a9c52b--- /dev/null+++ b/src/Filee.Setup/Platform/NativeMethods.cs@@ -0,0 +1,211 @@+// Win32 functions Setup calls (source-generated P/Invoke, trim- and AOT-safe).++using System.Runtime.InteropServices;+using System.Runtime.Versioning;++namespace Filee.Setup.Platform;++[SupportedOSPlatform("windows")]+internal static partial class NativeMethods+{+ public const uint MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;+ private const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;+ private const uint TOKEN_QUERY = 0x0008;+ private const uint TOKEN_DUPLICATE = 0x0002;+ private const uint TOKEN_ASSIGN_PRIMARY = 0x0001;+ private const uint TOKEN_ADJUST_DEFAULT = 0x0080;+ private const uint TOKEN_ADJUST_SESSIONID = 0x0100;+ private const int TokenElevation = 20;+ private const int SecurityImpersonation = 2;+ private const int TokenPrimary = 1;+ private const int HWND_BROADCAST = 0xFFFF;+ private const uint WM_SETTINGCHANGE = 0x001A;+ private const uint SMTO_ABORTIFHUNG = 0x0002;+ public const uint MB_OK = 0x0;+ public const uint MB_YESNO = 0x4;+ public const uint MB_ICONERROR = 0x10;+ public const uint MB_ICONQUESTION = 0x20;+ public const uint MB_ICONWARNING = 0x30;+ public const uint MB_ICONINFORMATION = 0x40;+ public const uint MB_SETFOREGROUND = 0x10000;+ public const int IDYES = 6;++ [LibraryImport("kernel32.dll", EntryPoint = "MoveFileExW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]+ [return: MarshalAs(UnmanagedType.Bool)]+ public static partial bool MoveFileEx(string existing, string? replacement, uint flags);++ [LibraryImport("kernel32.dll", SetLastError = true)]+ private static partial nint OpenProcess(uint access, [MarshalAs(UnmanagedType.Bool)] bool inherit, uint processId);++ [LibraryImport("kernel32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static partial bool CloseHandle(nint handle);++ [LibraryImport("kernel32.dll", EntryPoint = "QueryFullProcessImageNameW", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static unsafe partial bool QueryFullProcessImageName(nint process, uint flags, char* name, ref uint size);++ [LibraryImport("kernel32.dll")]+ private static partial nint GetCurrentProcess();++ [LibraryImport("advapi32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static partial bool OpenProcessToken(nint process, uint access, out nint token);++ [LibraryImport("advapi32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static unsafe partial bool GetTokenInformation(nint token, int infoClass, void* info, uint length, out uint returned);++ [LibraryImport("advapi32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static partial bool DuplicateTokenEx(nint token, uint access, nint attributes, int level, int type, out nint newToken);++ [LibraryImport("advapi32.dll", EntryPoint = "CreateProcessWithTokenW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static unsafe partial bool CreateProcessWithToken(nint token, uint logonFlags, string? application, char* commandLine,+ uint creationFlags, nint environment, string? currentDirectory, StartupInfo* startupInfo, ProcessInformation* processInformation);++ [LibraryImport("user32.dll")]+ private static partial nint GetShellWindow();++ [LibraryImport("user32.dll")]+ private static partial uint GetWindowThreadProcessId(nint window, out uint processId);++ [LibraryImport("user32.dll", EntryPoint = "SendMessageTimeoutW", StringMarshalling = StringMarshalling.Utf16)]+ private static partial nint SendMessageTimeout(nint window, uint message, nint wParam, string lParam, uint flags, uint timeout, out nint result);++ [LibraryImport("user32.dll", EntryPoint = "MessageBoxW", StringMarshalling = StringMarshalling.Utf16)]+ public static partial int MessageBox(nint owner, string text, string caption, uint type);++ [LibraryImport("kernel32.dll", EntryPoint = "GetUserDefaultLocaleName", StringMarshalling = StringMarshalling.Utf16)]+ private static unsafe partial int GetUserDefaultLocaleName(char* name, int length);++ [LibraryImport("kernel32.dll")]+ private static partial ushort GetUserDefaultUILanguage();++ [LibraryImport("kernel32.dll", EntryPoint = "LCIDToLocaleName")]+ private static unsafe partial int LCIDToLocaleName(uint locale, char* name, int length, uint flags);++ [StructLayout(LayoutKind.Sequential)]+ private struct StartupInfo+ {+ public int Size;+ public nint Reserved;+ public nint Desktop;+ public nint Title;+ public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;+ public short ShowWindow, Reserved2;+ public nint Reserved3, StdInput, StdOutput, StdError;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct ProcessInformation+ {+ public nint Process;+ public nint Thread;+ public int ProcessId;+ public int ThreadId;+ }++ /// <summary>The full path of a process's program, or null when it can't be read.</summary>+ public static unsafe string? ImagePathOf(int processId)+ {+ var process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, (uint)processId);+ if (process == 0)+ return null;+ try+ {+ var buffer = stackalloc char[4096];+ uint size = 4096;+ return QueryFullProcessImageName(process, 0, buffer, ref size) ? new string(buffer, 0, (int)size) : null;+ }+ finally+ {+ CloseHandle(process);+ }+ }++ /// <summary>True when this process has administrator rights (an elevated token).</summary>+ public static unsafe bool IsElevated()+ {+ if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out var token))+ return false;+ try+ {+ uint elevated = 0;+ return GetTokenInformation(token, TokenElevation, &elevated, sizeof(uint), out _) && elevated != 0;+ }+ finally+ {+ CloseHandle(token);+ }+ }++ /// <summary>+ /// Starts a program with Explorer's rights: with the token of the desktop's process (the signed-in user, not+ /// elevated). For an elevated Setup that nobody unelevated started (run "as administrator", a package manager).+ /// </summary>+ public static unsafe bool StartAsShellUser(string executable, string arguments, string workingFolder, out string? error)+ {+ error = null;+ var desktop = GetShellWindow();+ if (desktop == 0 || GetWindowThreadProcessId(desktop, out var shellId) == 0 || shellId == 0)+ {+ error = "There is no Explorer desktop.";+ return false;+ }+ var shell = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, shellId);+ if (shell == 0)+ {+ error = $"OpenProcess: {Marshal.GetLastPInvokeError()}";+ return false;+ }+ nint shellToken = 0, token = 0;+ try+ {+ if (!OpenProcessToken(shell, TOKEN_DUPLICATE, out shellToken)+ || !DuplicateTokenEx(shellToken, TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID,+ 0, SecurityImpersonation, TokenPrimary, out token))+ {+ error = $"Token: {Marshal.GetLastPInvokeError()}";+ return false;+ }+ var commandLine = (SetupOptions.Quote(executable) + " " + arguments).TrimEnd() + "\0";+ var startup = new StartupInfo { Size = sizeof(StartupInfo) };+ ProcessInformation info;+ fixed (char* line = commandLine)+ {+ if (!CreateProcessWithToken(token, 0, executable, line, 0, 0, workingFolder, &startup, &info))+ {+ error = $"CreateProcessWithTokenW: {Marshal.GetLastPInvokeError()}";+ return false;+ }+ }+ CloseHandle(info.Thread);+ CloseHandle(info.Process);+ return true;+ }+ finally+ {+ if (token != 0)+ CloseHandle(token);+ if (shellToken != 0)+ CloseHandle(shellToken);+ CloseHandle(shell);+ }+ }++ public static void BroadcastEnvironmentChange() =>+ SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", SMTO_ABORTIFHUNG, 5000, out _);++ /// <summary>The Windows display language, e.g. "ko-KR" (with InvariantGlobalization .NET can't tell).</summary>+ public static unsafe string UiLanguage()+ {+ var buffer = stackalloc char[85];+ var length = LCIDToLocaleName(GetUserDefaultUILanguage(), buffer, 85, 0);+ if (length > 1)+ return new string(buffer, 0, length - 1);+ length = GetUserDefaultLocaleName(buffer, 85);+ return length > 1 ? new string(buffer, 0, length - 1) : "en-US";+ }+}diff --git a/src/Filee.Setup/Platform/SetupLog.cs b/src/Filee.Setup/Platform/SetupLog.csnew file mode 100644index 00000000..c6c29f3d--- /dev/null+++ b/src/Filee.Setup/Platform/SetupLog.cs@@ -0,0 +1,59 @@+// Setup's log: one line per step in %TEMP%\Filee-Setup-<time>.log (or the /LOG= file). The elevated Setup and the+// one that started it write into the same file.++using System.Globalization;+using System.Text;++namespace Filee.Setup.Platform;++public sealed class SetupLog+{+ private readonly object _lock = new();+ private readonly List<string> _lines = [];++ /// <param name="file">The log file; null keeps the lines in memory only (tests).</param>+ public SetupLog(string? file)+ {+ File = file;+ }++ public string? File { get; }++ /// <summary>Every line written so far (tests, and the error page's "details").</summary>+ public IReadOnlyList<string> Lines+ {+ get+ {+ lock (_lock)+ return _lines.ToList();+ }+ }++ public static string DefaultFile(string temp, string prefix) =>+ Path.Combine(temp, $"{prefix}-{DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture)}.log");++ public void Info(string message) => Write("INFO", message);++ public void Warn(string message) => Write("WARN", message);++ public void Error(string message) => Write("ERROR", message);++ private void Write(string level, string message)+ {+ var line = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)} [{Environment.ProcessId}] {level} {message}";+ lock (_lock)+ {+ _lines.Add(line);+ if (File is null)+ return;+ try+ {+ System.IO.File.AppendAllText(File, line + Environment.NewLine, Encoding.UTF8);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ // The log must never stop Setup.+ }+ }+ }+}diff --git a/src/Filee.Setup/Platform/SetupPaths.cs b/src/Filee.Setup/Platform/SetupPaths.csnew file mode 100644index 00000000..664cb13e--- /dev/null+++ b/src/Filee.Setup/Platform/SetupPaths.cs@@ -0,0 +1,78 @@+// The folders Setup reads and writes besides the install folder. A /SANDBOX run and the tests put all of them into a+// scratch folder.++namespace Filee.Setup.Platform;++/// <param name="ProgramFiles">Default parent of a per-machine install (Inno Setup's {autopf}).</param>+/// <param name="UserPrograms">Default parent of a per-user install (%LocalAppData%\Programs).</param>+/// <param name="CommonStartMenu">All users' Start menu programs folder.</param>+/// <param name="UserStartMenu">This user's Start menu programs folder.</param>+/// <param name="CommonDesktop">All users' desktop.</param>+/// <param name="UserDesktop">This user's desktop.</param>+/// <param name="AppData">%APPDATA%: Filee's settings are in AppData\Filee.</param>+/// <param name="LocalAppData">%LocalAppData%: downloaded engines (LocalAppData\Filee\engines), Filee 1.1's Velopack copy.</param>+/// <param name="Temp">Setup's temporary files.</param>+/// <param name="SystemFolder">System32 (the Microsoft C++ runtime, if installed).</param>+public sealed record SetupPaths(+ string ProgramFiles,+ string UserPrograms,+ string CommonStartMenu,+ string UserStartMenu,+ string CommonDesktop,+ string UserDesktop,+ string AppData,+ string LocalAppData,+ string Temp,+ string SystemFolder)+{+ /// <summary>Filee's settings folder (UserDataStore.DefaultDirectory without FILEE_DATA_DIR).</summary>+ public string SettingsFolder => Path.Combine(AppData, "Filee");++ /// <summary>Downloaded engines (EngineEnvironment.DownloadRoot).</summary>+ public string EnginesFolder => Path.Combine(LocalAppData, "Filee", "engines");++ public string StartMenu(InstallScope scope) => scope == InstallScope.Machine ? CommonStartMenu : UserStartMenu;++ public string Desktop(InstallScope scope) => scope == InstallScope.Machine ? CommonDesktop : UserDesktop;++ public string DefaultInstallFolder(InstallScope scope) =>+ Path.Combine(scope == InstallScope.Machine ? ProgramFiles : UserPrograms, "Filee");++ /// <summary>This PC's folders.</summary>+ public static SetupPaths Real()+ {+ static string Folder(Environment.SpecialFolder folder) =>+ Environment.GetFolderPath(folder, Environment.SpecialFolderOption.DoNotVerify);+ var localAppData = Folder(Environment.SpecialFolder.LocalApplicationData);+ return new SetupPaths(+ // A 64-bit process: this is "C:\Program Files", not the x86 one.+ Folder(Environment.SpecialFolder.ProgramFiles),+ Path.Combine(localAppData, "Programs"),+ Folder(Environment.SpecialFolder.CommonPrograms),+ Folder(Environment.SpecialFolder.Programs),+ Folder(Environment.SpecialFolder.CommonDesktopDirectory),+ Folder(Environment.SpecialFolder.DesktopDirectory),+ Folder(Environment.SpecialFolder.ApplicationData),+ localAppData,+ Path.GetTempPath(),+ Environment.SystemDirectory);+ }++ /// <summary>Every folder inside <paramref name="root"/> (System32 stays the real one: it is only read).</summary>+ public static SetupPaths Sandbox(string root)+ {+ root = Path.GetFullPath(root);+ string Sub(string name) => Path.Combine(root, name);+ return new SetupPaths(+ Sub("Program Files"),+ Sub(Path.Combine("LocalAppData", "Programs")),+ Sub(Path.Combine("ProgramData", "Start Menu", "Programs")),+ Sub(Path.Combine("AppData", "Start Menu", "Programs")),+ Sub(Path.Combine("Public", "Desktop")),+ Sub("Desktop"),+ Sub("AppData"),+ Sub("LocalAppData"),+ Sub("Temp"),+ Environment.SystemDirectory);+ }+}diff --git a/src/Filee.Setup/Platform/SetupRegistry.cs b/src/Filee.Setup/Platform/SetupRegistry.csnew file mode 100644index 00000000..9cc4c7e0--- /dev/null+++ b/src/Filee.Setup/Platform/SetupRegistry.cs@@ -0,0 +1,213 @@+// The registry as Setup uses it: the uninstall entry, PATH and the old Velopack entry. Behind an interface so tests and+// /SANDBOX runs use a registry of their own (MemoryRegistry) and never touch HKLM, HKCU or the user's PATH.++using System.Runtime.Versioning;+using System.Text;+using System.Text.Json;+using Microsoft.Win32;++namespace Filee.Setup.Platform;++/// <summary>The two hives Setup writes to.</summary>+public enum Hive+{+ LocalMachine,+ CurrentUser,+}++/// <summary>A registry value: a string (REG_SZ or REG_EXPAND_SZ) or a number (REG_DWORD).</summary>+public sealed record RegistryEntry(object Value, bool Expandable = false)+{+ public string? Text => Value as string;+}++public interface ISetupRegistry+{+ bool KeyExists(Hive hive, string key);++ /// <summary>The value, unexpanded (REG_EXPAND_SZ stays as written); null when missing.</summary>+ RegistryEntry? Get(Hive hive, string key, string name);++ IReadOnlyList<string> ValueNames(Hive hive, string key);++ void SetString(Hive hive, string key, string name, string value, bool expandable = false);++ void SetNumber(Hive hive, string key, string name, int value);++ void DeleteValue(Hive hive, string key, string name);++ /// <summary>Deletes the key with everything below it (nothing when it doesn't exist).</summary>+ void DeleteKey(Hive hive, string key);+}++/// <summary>The real registry, 64-bit view (Filee is a 64-bit program; Inno Setup wrote its entry there too).</summary>+[SupportedOSPlatform("windows")]+public sealed class WindowsRegistry : ISetupRegistry+{+ private static RegistryKey Base(Hive hive) =>+ RegistryKey.OpenBaseKey(hive == Hive.LocalMachine ? RegistryHive.LocalMachine : RegistryHive.CurrentUser, RegistryView.Registry64);++ public bool KeyExists(Hive hive, string key)+ {+ using var root = Base(hive);+ using var opened = root.OpenSubKey(key);+ return opened is not null;+ }++ public RegistryEntry? Get(Hive hive, string key, string name)+ {+ using var root = Base(hive);+ using var opened = root.OpenSubKey(key);+ var value = opened?.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);+ return value switch+ {+ string text => new RegistryEntry(text, opened!.GetValueKind(name) == RegistryValueKind.ExpandString),+ int number => new RegistryEntry(number),+ _ => null,+ };+ }++ public IReadOnlyList<string> ValueNames(Hive hive, string key)+ {+ using var root = Base(hive);+ using var opened = root.OpenSubKey(key);+ return opened?.GetValueNames() ?? [];+ }++ public void SetString(Hive hive, string key, string name, string value, bool expandable = false)+ {+ using var root = Base(hive);+ using var opened = root.CreateSubKey(key, writable: true);+ opened.SetValue(name, value, expandable ? RegistryValueKind.ExpandString : RegistryValueKind.String);+ }++ public void SetNumber(Hive hive, string key, string name, int value)+ {+ using var root = Base(hive);+ using var opened = root.CreateSubKey(key, writable: true);+ opened.SetValue(name, value, RegistryValueKind.DWord);+ }++ public void DeleteValue(Hive hive, string key, string name)+ {+ using var root = Base(hive);+ using var opened = root.OpenSubKey(key, writable: true);+ opened?.DeleteValue(name, throwOnMissingValue: false);+ }++ public void DeleteKey(Hive hive, string key)+ {+ using var root = Base(hive);+ root.DeleteSubKeyTree(key, throwOnMissingSubKey: false);+ }+}++/// <summary>+/// A registry in memory, optionally saved to a JSON file (the /SANDBOX registry). Key names compare case-insensitively+/// like the real one.+/// </summary>+public sealed class MemoryRegistry : ISetupRegistry+{+ private readonly Dictionary<string, Dictionary<string, RegistryEntry>> _keys = new(StringComparer.OrdinalIgnoreCase);+ private readonly string? _file;++ public MemoryRegistry(string? file = null)+ {+ _file = file;+ if (file is not null && File.Exists(file))+ Load(file);+ }++ private static string Path(Hive hive, string key) => (hive == Hive.LocalMachine ? "HKLM\\" : "HKCU\\") + key.Trim('\\');++ public bool KeyExists(Hive hive, string key)+ {+ var path = Path(hive, key);+ return _keys.Keys.Any(k => k.Equals(path, StringComparison.OrdinalIgnoreCase)+ || k.StartsWith(path + "\\", StringComparison.OrdinalIgnoreCase));+ }++ public RegistryEntry? Get(Hive hive, string key, string name) =>+ _keys.TryGetValue(Path(hive, key), out var values) && values.TryGetValue(name, out var entry) ? entry : null;++ public IReadOnlyList<string> ValueNames(Hive hive, string key) =>+ _keys.TryGetValue(Path(hive, key), out var values) ? values.Keys.ToList() : [];++ public void SetString(Hive hive, string key, string name, string value, bool expandable = false) =>+ Set(hive, key, name, new RegistryEntry(value, expandable));++ public void SetNumber(Hive hive, string key, string name, int value) => Set(hive, key, name, new RegistryEntry(value));++ public void DeleteValue(Hive hive, string key, string name)+ {+ if (_keys.TryGetValue(Path(hive, key), out var values) && values.Remove(name))+ Save();+ }++ public void DeleteKey(Hive hive, string key)+ {+ var path = Path(hive, key);+ foreach (var k in _keys.Keys.Where(k => k.Equals(path, StringComparison.OrdinalIgnoreCase)+ || k.StartsWith(path + "\\", StringComparison.OrdinalIgnoreCase)).ToList())+ _keys.Remove(k);+ Save();+ }++ private void Set(Hive hive, string key, string name, RegistryEntry entry)+ {+ var path = Path(hive, key);+ if (!_keys.TryGetValue(path, out var values))+ _keys[path] = values = new Dictionary<string, RegistryEntry>(StringComparer.OrdinalIgnoreCase);+ values[name] = entry;+ Save();+ }++ private void Save()+ {+ if (_file is null)+ return;+ using var stream = new MemoryStream();+ using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))+ {+ writer.WriteStartObject();+ foreach (var (key, values) in _keys.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase))+ {+ writer.WriteStartObject(key);+ foreach (var (name, entry) in values)+ {+ writer.WriteStartObject(name);+ if (entry.Value is int number)+ writer.WriteNumber("dword", number);+ else+ writer.WriteString(entry.Expandable ? "expand_sz" : "sz", (string)entry.Value);+ writer.WriteEndObject();+ }+ writer.WriteEndObject();+ }+ writer.WriteEndObject();+ }+ File.WriteAllBytes(_file, stream.ToArray());+ }++ private void Load(string file)+ {+ using var json = JsonDocument.Parse(File.ReadAllText(file, Encoding.UTF8));+ foreach (var key in json.RootElement.EnumerateObject())+ {+ var values = new Dictionary<string, RegistryEntry>(StringComparer.OrdinalIgnoreCase);+ foreach (var value in key.Value.EnumerateObject())+ {+ foreach (var typed in value.Value.EnumerateObject())+ {+ values[value.Name] = typed.Name switch+ {+ "dword" => new RegistryEntry(typed.Value.GetInt32()),+ "expand_sz" => new RegistryEntry(typed.Value.GetString() ?? "", Expandable: true),+ _ => new RegistryEntry(typed.Value.GetString() ?? ""),+ };+ }+ }+ _keys[key.Name] = values;+ }+ }+}diff --git a/src/Filee.Setup/Platform/SetupSystem.cs b/src/Filee.Setup/Platform/SetupSystem.csnew file mode 100644index 00000000..2b5e96f6--- /dev/null+++ b/src/Filee.Setup/Platform/SetupSystem.cs@@ -0,0 +1,220 @@+// What Setup does to Windows besides files and the registry: shortcuts, the Windows 11 Explorer menu package, running+// Filee's own installer commands, closing programs, telling Windows about a new PATH. Tests replace it with a fake;+// a /SANDBOX run with SandboxSystem, which leaves the PC alone.++using System.Diagnostics;+using System.Runtime.Versioning;+using Filee.Platform.Windows;++namespace Filee.Setup.Platform;++/// <summary>A process started from a file in the install folder.</summary>+public sealed record RunningProgram(int Id, string Path);++public interface ISetupSystem+{+ /// <summary>Windows 11 on x64: the top-level Explorer menu exists and Setup may offer it.</summary>+ bool ExplorerMenuSupported { get; }++ bool IsExplorerMenuRegistered();++ /// <summary>Registers the sparse package next to Filee.exe; returns why not, or null when it worked.</summary>+ string? RegisterExplorerMenu(string installFolder, bool removeFirst);++ void UnregisterExplorerMenu();++ void CreateShortcut(string path, string target, string workingFolder, string description);++ /// <summary>Tells running programs (new terminals) that PATH changed.</summary>+ void BroadcastEnvironmentChange();++ /// <summary>Runs a program without a window and waits; the exit code, or -1 when it failed or took too long.</summary>+ int RunAndWait(string executable, string arguments, TimeSpan timeout);++ IReadOnlyList<RunningProgram> ProgramsIn(string folder);++ void Kill(int processId);++ /// <summary>Has Windows delete a file or an empty folder at the next restart (what is still in use now).</summary>+ void DeleteAtRestart(string path);+}++/// <summary>The real thing.</summary>+[SupportedOSPlatform("windows")]+public class WindowsSetupSystem(SetupLog log) : ISetupSystem+{+ protected SetupLog Log { get; } = log;++ public virtual bool ExplorerMenuSupported => ExplorerMenuRegistration.IsSupportedOs;++ public virtual bool IsExplorerMenuRegistered()+ {+ try+ {+ return ExplorerMenuRegistration.Find() is not null;+ }+ catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException)+ {+ return false;+ }+ }++ public virtual string? RegisterExplorerMenu(string installFolder, bool removeFirst)+ {+ if (removeFirst)+ UnregisterExplorerMenu();+ var package = Path.Combine(installFolder, ExplorerMenuPackage.PackageFileName);+ return RunPowerShell(errorFile => ExplorerMenuRegistration.BuildAddScript(package, installFolder, errorFile));+ }++ public virtual void UnregisterExplorerMenu()+ {+ if (!IsExplorerMenuRegistered())+ return;+ if (RunPowerShell(ExplorerMenuRegistration.BuildRemoveScript) is { } error)+ Log.Warn($"Removing the Explorer menu package failed: {error}");+ }++ /// <summary>Windows PowerShell with Setup's rights (the Appx cmdlets); the error message, or null.</summary>+ private string? RunPowerShell(Func<string, string> buildScript)+ {+ var errorFile = Path.Combine(Path.GetTempPath(), $"Filee-Setup-powershell-{Guid.NewGuid():N}.txt");+ try+ {+ using var process = Process.Start(ExplorerMenuRegistration.CreateStartInfo(buildScript(errorFile), elevated: false));+ if (process is null)+ return "PowerShell did not start.";+ if (!process.WaitForExit(TimeSpan.FromMinutes(3)))+ {+ process.Kill();+ return "Windows did not finish within 3 minutes.";+ }+ if (process.ExitCode == 0)+ return null;+ var message = File.Exists(errorFile) ? ExplorerMenuRegistration.ShortenDeploymentError(File.ReadAllText(errorFile)) : "";+ return message.Length > 0 ? message : $"PowerShell exit code {process.ExitCode}.";+ }+ catch (System.ComponentModel.Win32Exception ex)+ {+ return ex.Message;+ }+ finally+ {+ TryDelete(errorFile);+ }+ }++ public virtual void CreateShortcut(string path, string target, string workingFolder, string description) =>+ ShellLink.Create(path, target, workingFolder, description);++ public virtual void BroadcastEnvironmentChange() => NativeMethods.BroadcastEnvironmentChange();++ public virtual int RunAndWait(string executable, string arguments, TimeSpan timeout)+ {+ try+ {+ using var process = Process.Start(CreateStartInfo(executable, arguments));+ if (process is null)+ return -1;+ if (process.WaitForExit(timeout))+ return process.ExitCode;+ Log.Warn($"{Path.GetFileName(executable)} {arguments} did not finish within {timeout.TotalSeconds:0} s");+ process.Kill();+ return -1;+ }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)+ {+ Log.Warn($"Could not run {executable} {arguments}: {ex.Message}");+ return -1;+ }+ }++ protected virtual ProcessStartInfo CreateStartInfo(string executable, string arguments) =>+ new(executable, arguments)+ {+ UseShellExecute = false,+ CreateNoWindow = true,+ WorkingDirectory = Path.GetDirectoryName(executable) ?? "",+ };++ public virtual IReadOnlyList<RunningProgram> ProgramsIn(string folder)+ {+ var prefix = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)) + Path.DirectorySeparatorChar;+ var found = new List<RunningProgram>();+ foreach (var process in Process.GetProcesses())+ {+ using (process)+ {+ if (process.Id == Environment.ProcessId)+ continue;+ var path = NativeMethods.ImagePathOf(process.Id);+ if (path is not null && path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))+ found.Add(new RunningProgram(process.Id, path));+ }+ }+ return found;+ }++ public virtual void Kill(int processId)+ {+ try+ {+ using var process = Process.GetProcessById(processId);+ process.Kill(entireProcessTree: false);+ process.WaitForExit(TimeSpan.FromSeconds(10));+ }+ catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or System.ComponentModel.Win32Exception)+ {+ // Ended meanwhile, or not ours to end: the file swap copes with files in use.+ }+ }++ public virtual void DeleteAtRestart(string path)+ {+ if (!NativeMethods.MoveFileEx(path, null, NativeMethods.MOVEFILE_DELAY_UNTIL_REBOOT))+ Log.Warn($"Could not schedule {path} for deletion at the next restart");+ }++ private static void TryDelete(string file)+ {+ try+ {+ File.Delete(file);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ }+ }+}++/// <summary>+/// /SANDBOX: no Explorer menu, no PATH broadcast, nothing scheduled for the next restart, and Filee's installer+/// commands run with FILEE_DATA_DIR in the sandbox, which gives that Filee its own data and single instance: it never+/// reaches (or quits) the Filee the user runs.+/// </summary>+[SupportedOSPlatform("windows")]+public sealed class SandboxSetupSystem(SetupLog log, string dataFolder) : WindowsSetupSystem(log)+{+ public override bool ExplorerMenuSupported => false;++ public override bool IsExplorerMenuRegistered() => false;++ public override string? RegisterExplorerMenu(string installFolder, bool removeFirst) => "Not in a sandbox.";++ public override void UnregisterExplorerMenu()+ {+ }++ public override void BroadcastEnvironmentChange()+ {+ }++ public override void DeleteAtRestart(string path) => Log.Info($"Sandbox: would delete {path} at the next restart");++ protected override ProcessStartInfo CreateStartInfo(string executable, string arguments)+ {+ var info = base.CreateStartInfo(executable, arguments);+ info.Environment["FILEE_DATA_DIR"] = dataFolder;+ return info;+ }+}diff --git a/src/Filee.Setup/Platform/ShellLink.cs b/src/Filee.Setup/Platform/ShellLink.csnew file mode 100644index 00000000..9c3e9d80--- /dev/null+++ b/src/Filee.Setup/Platform/ShellLink.cs@@ -0,0 +1,116 @@+// Writes .lnk shortcuts (Start menu, desktop) through the shell's ShellLink object, with source-generated COM+// interfaces: the trimmed Setup has no built-in COM interop.++using System.Runtime.InteropServices;+using System.Runtime.InteropServices.Marshalling;+using System.Runtime.Versioning;++namespace Filee.Setup.Platform;++[SupportedOSPlatform("windows")]+internal static partial class ShellLink+{+ private static readonly Guid ClsidShellLink = new("00021401-0000-0000-C000-000000000046");+ private static readonly Guid IidShellLinkW = new("000214F9-0000-0000-C000-000000000046");+ private const uint ClsctxInprocServer = 0x1;++ [LibraryImport("ole32.dll")]+ private static partial int CoCreateInstance(in Guid clsid, nint outer, uint context, in Guid iid, out nint instance);++ [LibraryImport("ole32.dll")]+ private static partial int CoInitializeEx(nint reserved, uint coInit);++ [LibraryImport("ole32.dll")]+ private static partial void CoUninitialize();++ /// <summary>Creates (or replaces) <paramref name="path"/>, a shortcut to <paramref name="target"/>.</summary>+ public static void Create(string path, string target, string workingFolder, string description)+ {+ // The shell objects want a single-threaded apartment: a thread of its own keeps the caller's apartment out of it.+ Exception? failure = null;+ var thread = new Thread(() =>+ {+ try+ {+ CreateOnThisThread(path, target, workingFolder, description);+ }+ catch (Exception ex) when (ex is COMException or InvalidCastException or IOException or UnauthorizedAccessException)+ {+ failure = ex;+ }+ })+ { IsBackground = true, Name = "Filee Setup shortcut" };+ thread.SetApartmentState(ApartmentState.STA);+ thread.Start();+ thread.Join();+ if (failure is not null)+ throw new IOException($"Could not create the shortcut {path}: {failure.Message}", failure);+ }++ private static void CreateOnThisThread(string path, string target, string workingFolder, string description)+ {+ var initialized = CoInitializeEx(0, 0x2 /* COINIT_APARTMENTTHREADED */) >= 0;+ try+ {+ Marshal.ThrowExceptionForHR(CoCreateInstance(ClsidShellLink, 0, ClsctxInprocServer, IidShellLinkW, out var pointer));+ var wrappers = new StrategyBasedComWrappers();+ try+ {+ var link = (IShellLinkW)wrappers.GetOrCreateObjectForComInstance(pointer, CreateObjectFlags.UniqueInstance);+ link.SetPath(target);+ link.SetWorkingDirectory(workingFolder);+ link.SetDescription(description);+ link.SetIconLocation(target, 0);+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ ((IPersistFile)link).Save(path, true);+ }+ finally+ {+ Marshal.Release(pointer);+ }+ }+ finally+ {+ if (initialized)+ CoUninitialize();+ }+ }++ // Only the methods Setup calls are typed; the others keep their vtable slot and are never called.+ [GeneratedComInterface(StringMarshalling = StringMarshalling.Utf16)]+ [Guid("000214F9-0000-0000-C000-000000000046")]+ internal partial interface IShellLinkW+ {+ void GetPath(nint file, int length, nint findData, uint flags);+ void GetIDList(nint idList);+ void SetIDList(nint idList);+ void GetDescription(nint name, int length);+ void SetDescription(string name);+ void GetWorkingDirectory(nint folder, int length);+ void SetWorkingDirectory(string folder);+ void GetArguments(nint arguments, int length);+ void SetArguments(string arguments);+ void GetHotkey(nint hotkey);+ void SetHotkey(ushort hotkey);+ void GetShowCmd(nint showCommand);+ void SetShowCmd(int showCommand);+ void GetIconLocation(nint iconPath, int length, nint icon);+ void SetIconLocation(string iconPath, int icon);+ void SetRelativePath(string relativePath, uint reserved);+ void Resolve(nint window, uint flags);+ void SetPath(string file);+ }++ [GeneratedComInterface(StringMarshalling = StringMarshalling.Utf16)]+ [Guid("0000010B-0000-0000-C000-000000000046")]+ internal partial interface IPersistFile+ {+ void GetClassID(out Guid classId);+ [PreserveSig]+ int IsDirty();+ void Load(string fileName, uint mode);+ void Save(string fileName, [MarshalAs(UnmanagedType.Bool)] bool remember);+ void SaveCompleted(string fileName);+ void GetCurFile(out nint fileName);+ }+}diff --git a/src/Filee.Setup/Program.cs b/src/Filee.Setup/Program.csnew file mode 100644index 00000000..0a6de9e7--- /dev/null+++ b/src/Filee.Setup/Program.cs@@ -0,0 +1,469 @@+// Entry point of Setup (Filee-<version>-win-Setup.exe, which carries a payload) and of the uninstaller (uninstall.exe,+// the same program without one).+//+// Rights: the program starts without administrator rights (asInvoker). An install for all users starts itself again+// with them (one UAC prompt) and waits; the elevated copy writes what to start at the end into a file, and this+// unelevated one starts Filee as the signed-in user: Filee must not run elevated (Windows blocks drag and drop from+// Explorer into elevated windows). The uninstaller first copies itself to %TEMP% and runs from there (with+// administrator rights when needed), so the install folder can be deleted.++using System.ComponentModel;+using System.Diagnostics;+using System.Runtime.InteropServices;+using Avalonia;+using Filee.Setup.Installation;+using Filee.Setup.Payload;+using Filee.Setup.Platform;+using Filee.Setup.ViewModels;++namespace Filee.Setup;++[System.Runtime.Versioning.SupportedOSPlatform("windows")]+internal static class Program+{+ private const int ExitOk = 0;+ private const int ExitInitFailed = 1;+ private const int ExitCancelled = 2;+ private const int ExitFailed = 4;++ /// <summary>Win32 ERROR_CANCELLED: the user declined the UAC prompt.</summary>+ private const int ErrorCancelled = 1223;++ [STAThread]+ public static int Main(string[] args)+ {+ if (!OperatingSystem.IsWindows())+ return ExitInitFailed;+ // Never hold a folder Setup may delete (the install folder) as the current directory.+ Environment.CurrentDirectory = Environment.SystemDirectory;+ var options = SetupOptions.Parse(args);+ var exe = Environment.ProcessPath ?? Path.Combine(AppContext.BaseDirectory, "uninstall.exe");+ var sandbox = options.Sandbox is { } root ? Path.GetFullPath(root) : null;+ var paths = sandbox is null ? SetupPaths.Real() : SetupPaths.Sandbox(sandbox);+ Directory.CreateDirectory(paths.Temp);++ SetupPayload? payload = null;+ Exception? damaged = null;+ try+ {+ payload = SetupPayload.Open(exe);+ }+ catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException)+ {+ damaged = ex;+ }+ var uninstall = options.Uninstall || (payload is null && damaged is null);+ var log = new SetupLog(options.LogFile ?? SetupLog.DefaultFile(paths.Temp, uninstall ? "Filee-Uninstall" : "Filee-Setup"));+ log.Info($"{(uninstall ? "Uninstaller" : "Setup")} {SetupInfo.Version}{(payload is null ? "" : $" with Filee {payload.Manifest.Version}")}: " ++ $"{exe} {SetupOptions.Join(args)}; administrator: {NativeMethods.IsElevated()}; Windows {Environment.OSVersion.Version} " ++ $"{RuntimeInformation.OSArchitecture}{(sandbox is null ? "" : $"; sandbox {sandbox}")}");+ foreach (var unknown in options.Unknown)+ log.Warn($"Unknown argument ignored: {unknown}");+ foreach (var ignored in options.Ignored)+ log.Info($"Accepted, changes nothing: {ignored}");+ foreach (var task in SetupTasks.UnknownNames(options.Tasks).Concat(SetupTasks.UnknownNames(options.MergeTasks)))+ log.Warn($"Unknown task ignored: {task}");++ var texts = new SetupTexts(options.Language ?? "auto");+ try+ {+ if (!IsSupportedWindows())+ {+ log.Error("Windows is too old or not 64-bit");+ Tell(options, texts["installer.error.windows"], NativeMethods.MB_ICONERROR);+ return ExitInitFailed;+ }+ if (damaged is not null)+ {+ log.Error($"Damaged payload: {damaged.Message}");+ Tell(options, texts["installer.error.damaged"], NativeMethods.MB_ICONERROR);+ return ExitInitFailed;+ }+ return uninstall+ ? Uninstall(args, options, exe, paths, sandbox, log, texts)+ : Install(args, options, exe, payload!, paths, sandbox, log, texts);+ }+ catch (Exception ex) when (ex is not OutOfMemoryException)+ {+ log.Error($"Setup failed: {ex}");+ Tell(options, texts.Format("installer.error.unexpected", ex.Message), NativeMethods.MB_ICONERROR);+ return ExitFailed;+ }+ finally+ {+ payload?.Dispose();+ }+ }++ /// <summary>Windows 10 1809 or later, 64-bit (x64, or ARM64 running x64 programs).</summary>+ private static bool IsSupportedWindows() =>+ Environment.OSVersion.Version.Build >= SetupNames.MinimumBuild+ && RuntimeInformation.OSArchitecture is Architecture.X64 or Architecture.Arm64;++ private static int Install(string[] args, SetupOptions options, string exe, SetupPayload payload, SetupPaths paths, string? sandbox,+ SetupLog log, SetupTexts texts)+ {+ var scope = options.Scope;+ if (!options.Portable && sandbox is null && scope == InstallScope.Machine && !NativeMethods.IsElevated())+ {+ payload.Dispose();+ return RunElevated(exe, args, log, launchFile: Path.Combine(Path.GetTempPath(), $"Filee-Setup-{Guid.NewGuid():N}.launch"));+ }++ var context = CreateContext(sandbox, paths, log);+ var previous = options.Portable ? null : PreviousInstall.Find(context.Registry, scope);+ if (options.Language is null && previous?.Language is { } recorded)+ texts.SetLanguage(recorded);+ var folder = previous?.Folder+ ?? (options.Directory is { } dir ? Path.GetFullPath(Environment.ExpandEnvironmentVariables(dir)) : null)+ ?? (options.Portable ? Path.Combine(Path.GetDirectoryName(exe)!, "Filee") : paths.DefaultInstallFolder(scope));+ if (previous is not null && options.Directory is { } asked+ && !Path.GetFullPath(Environment.ExpandEnvironmentVariables(asked)).TrimEnd('\\').Equals(previous.Folder, StringComparison.OrdinalIgnoreCase))+ log.Warn($"/DIR={asked} ignored: Filee is installed in {previous.Folder}, which an update keeps");++ var modernMenu = context.System.ExplorerMenuSupported && scope == InstallScope.Machine && !options.Portable;+ var tasks = previous is null+ ? SetupTasks.FromCommandLine(options.Tasks, options.MergeTasks)+ : UpdateTasks(previous.CurrentTasks(context.Registry, context.System, paths), options);+ if (!modernMenu)+ tasks = tasks with { ModernMenu = false };+ var marker = payload.Manifest.EngineMarker;+ var engines = previous is null+ ? payload.Manifest.Engines.Select(e => (e, EngineInstalled(e, paths, marker))).ToList()+ : [];+ var choices = new InstallChoices(folder, scope, tasks,+ engines.Where(e => e.e.Suggested && !e.Item2).Select(e => e.e.Id).ToList(),+ texts.Language, LanguagePicked: options.Language is not null,+ NoIcons: options.NoIcons, Portable: options.Portable, ForceClose: options.ForceCloseApplications);+ var runner = new SetupRunner(context, payload, previous);++ InstallResult? result;+ int exitCode;+ LaunchRequest? launch;+ if (options.Ui == SetupUi.VerySilent)+ {+ result = runner.Install(choices, new SyncProgress<SetupProgress>(_ => { }));+ exitCode = result.Succeeded ? ExitOk : ExitFailed;+ launch = result.Launch;+ }+ else+ {+ var model = new SetupViewModel(texts, runner, payload.Manifest.Version, choices, previous, engines, modernMenu,+ payload.Manifest.TotalSize + payload.Offset, languagePicked: options.Language is not null)+ {+ LogFile = log.File,+ };+ RunWindow(model, texts, options.Ui == SetupUi.Silent);+ result = model.Result;+ exitCode = model.ExitCode;+ launch = options.Ui == SetupUi.Silent ? result?.Launch : model.Launch;+ }++ if (result is { Succeeded: false } failed && options.IsSilent)+ {+ Tell(options, SetupMessages.Error(texts, failed.Error!) + Environment.NewLine + Environment.NewLine + log.File, NativeMethods.MB_ICONERROR);+ }+ if (result is { Succeeded: true } && options.Ui == SetupUi.Silent)+ {+ // /SILENT shows its window anyway: say what doesn't work. (The top-level menu, like before, only in the log.)+ foreach (var warning in result.Warnings.OfType<RuntimeWarning>())+ Tell(options, SetupMessages.Warning(texts, warning), NativeMethods.MB_ICONWARNING);+ }+ if (result is { Succeeded: true } && launch is not null)+ {+ if (options.NoLaunch || sandbox is not null)+ log.Info($"Not starting Filee ({(sandbox is null ? "/NOLAUNCH" : "sandbox")}): {launch.Executable} {launch.Arguments}");+ else+ StartFilee(launch, options.LaunchFile, log);+ }+ log.Info($"Exit code {exitCode}");+ return exitCode;+ }++ /// <summary>An update keeps the current state; /TASKS and /MERGETASKS may still change the PATH entry and the desktop icon.</summary>+ private static SetupTasks UpdateTasks(SetupTasks current, SetupOptions options)+ {+ if (options.Tasks is null && options.MergeTasks is null)+ return current;+ var asked = options.Tasks is null+ ? SetupTasks.FromCommandLine(current.ToInnoString(), options.MergeTasks)+ : SetupTasks.FromCommandLine(options.Tasks, options.MergeTasks);+ return current with { Cli = asked.Cli, DesktopIcon = asked.DesktopIcon };+ }++ private static bool EngineInstalled(EngineOffer engine, SetupPaths paths, string marker) =>+ marker.Length > 0 && engine.MarkerFolders.Count > 0+ && engine.MarkerFolders.All(folder => File.Exists(Path.Combine(paths.EnginesFolder, folder, marker)));++ private static int Uninstall(string[] args, SetupOptions options, string exe, SetupPaths paths, string? sandbox, SetupLog log, SetupTexts texts)+ {+ var folder = Path.TrimEndingDirectorySeparator(Path.GetFullPath(options.Directory ?? Path.GetDirectoryName(exe)!));+ var record = InstallRecord.Read(folder);+ if (record is null)+ {+ log.Error($"No {SetupNames.InstallRecordFile} in {folder}");+ Tell(options, texts.Format("installer.uninstall.not_installed", folder), NativeMethods.MB_ICONERROR);+ return ExitInitFailed;+ }+ var context = CreateContext(sandbox, paths, log);+ var hive = PreviousInstall.HiveOf(record.Scope);+ if (options.Language is null && context.Registry.Get(hive, SetupNames.UninstallKey, SetupNames.LanguageValue)?.Text is { } language)+ texts.SetLanguage(language);+ var needsAdmin = record.Scope == InstallScope.Machine && sandbox is null && !NativeMethods.IsElevated();++ // Phase 1: running from the install folder, which can't be deleted while this runs. Copy to %TEMP% and wait.+ var exeFolder = Path.TrimEndingDirectorySeparator(Path.GetDirectoryName(exe)!);+ if (exeFolder.Equals(folder, StringComparison.OrdinalIgnoreCase))+ {+ var temp = Path.Combine(paths.Temp, $"Filee-Uninstall-{Guid.NewGuid():N}");+ Directory.CreateDirectory(temp);+ var copy = Path.Combine(temp, SetupNames.UninstallerExe);+ File.Copy(exe, copy);+ var childArgs = args.Where(a => !HasName(a, "/DIR") && !HasName(a, "/LOG") && !HasName(a, "/UNINSTALL"))+ .Concat(["/UNINSTALL", $"/DIR={folder}", $"/LOG={log.File}"]);+ log.Info($"Continuing from {copy}");+ var code = RunAndWait(copy, childArgs, elevated: needsAdmin, log);+ if (code == ExitCancelled)+ TryDeleteFolder(temp);+ return code;+ }+ if (needsAdmin)+ return RunElevated(exe, args, log, launchFile: null);++ // Phase 2: from a copy in %TEMP%.+ var fromTemp = Path.GetFileName(exeFolder).StartsWith("Filee-Uninstall-", StringComparison.OrdinalIgnoreCase);+ var trash = fromTemp ? Path.Combine(exeFolder, "trash") : Path.Combine(paths.Temp, $"Filee-Uninstall-{Guid.NewGuid():N}");+ var runner = new SetupRunner(context, null, null, folder, record, trash);+ int exitCode;+ if (options.Ui == SetupUi.VerySilent)+ {+ exitCode = runner.Uninstall(deleteSettings: false, new SyncProgress<SetupProgress>(_ => { })) is { } error+ ? Fail(error)+ : ExitOk;+ }+ else+ {+ var model = new SetupViewModel(texts, runner, record.Version, new InstallChoices(folder, record.Scope, SetupTasks.Defaults, [], texts.Language),+ null, [], false, 0, uninstall: true)+ {+ LogFile = log.File,+ SettingsFolder = paths.SettingsFolder,+ };+ RunWindow(model, texts, options.Ui == SetupUi.Silent);+ exitCode = model.ExitCode;+ if (exitCode == 1 && options.IsSilent)+ Tell(options, model.ErrorText, NativeMethods.MB_ICONERROR);+ }+ // This copy and what was in use go once it has ended (and at the next restart, to be sure).+ CleanUpAfterExit(fromTemp ? exeFolder : trash, context.System, log);+ log.Info($"Exit code {exitCode}");+ return exitCode;++ int Fail(Exception error)+ {+ Tell(options, SetupMessages.Error(texts, error), NativeMethods.MB_ICONERROR);+ return ExitInitFailed;+ }+ }++ private static SetupContext CreateContext(string? sandbox, SetupPaths paths, SetupLog log)+ {+ if (sandbox is null)+ return new SetupContext(new WindowsRegistry(), new WindowsSetupSystem(log), paths, log);+ // The sandbox's registry is a JSON file; Filee runs with its data in the sandbox.+ return new SetupContext(new MemoryRegistry(Path.Combine(sandbox, "registry.json")),+ new SandboxSetupSystem(log, paths.SettingsFolder), paths, log, Sandbox: true);+ }++ private static void RunWindow(SetupViewModel model, SetupTexts texts, bool silent)+ {+ App.Model = model;+ App.Texts = texts;+ App.Silent = silent;+ BuildAvaloniaApp().StartWithClassicDesktopLifetime([]);+ }++ /// <summary>Also used by the XAML previewer and the tests' headless platform (with their own builder).</summary>+ public static AppBuilder BuildAvaloniaApp() =>+ AppBuilder.Configure<App>()+ .UsePlatformDetect()+ .ConfigureFonts(fonts => fonts.AddFontCollection(new SetupFontCollection()))+ .LogToTrace();++ /// <summary>+ /// Starts this program again with administrator rights and waits. With <paramref name="launchFile"/>, starts what+ /// the elevated copy wrote into it afterwards, as the signed-in user.+ /// </summary>+ private static int RunElevated(string exe, string[] args, SetupLog log, string? launchFile)+ {+ var childArgs = args.Where(a => !HasName(a, "/LAUNCHFILE") && !HasName(a, "/LOG"))+ .Concat(launchFile is null ? [] : [$"/LAUNCHFILE={launchFile}"])+ .Append($"/LOG={log.File}");+ log.Info("Asking for administrator rights");+ var code = RunAndWait(exe, childArgs, elevated: true, log);+ if (launchFile is not null && File.Exists(launchFile))+ {+ try+ {+ var lines = File.ReadAllLines(launchFile);+ File.Delete(launchFile);+ if (lines.Length >= 1 && Path.GetFileName(lines[0]).Equals(SetupNames.AppExe, StringComparison.OrdinalIgnoreCase) && File.Exists(lines[0]))+ Start(new LaunchRequest(lines[0], lines.Length > 1 ? lines[1] : ""), log);+ else+ log.Warn($"Not starting what {launchFile} names");+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ log.Warn($"Could not read {launchFile}: {ex.Message}");+ }+ }+ return code;+ }++ private static int RunAndWait(string exe, IEnumerable<string> args, bool elevated, SetupLog log)+ {+ var info = new ProcessStartInfo(exe, SetupOptions.Join(args))+ {+ UseShellExecute = true,+ WorkingDirectory = Environment.SystemDirectory,+ };+ if (elevated)+ info.Verb = "runas";+ try+ {+ using var child = Process.Start(info);+ if (child is null)+ return ExitInitFailed;+ child.WaitForExit();+ log.Info($"{Path.GetFileName(exe)} ended with exit code {child.ExitCode}");+ return child.ExitCode;+ }+ catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled)+ {+ log.Info("Administrator rights declined");+ return ExitCancelled;+ }+ catch (Win32Exception ex)+ {+ log.Error($"Could not start {exe}: {ex.Message}");+ return ExitInitFailed;+ }+ }++ private static bool HasName(string arg, string name) =>+ arg.Equals(name, StringComparison.OrdinalIgnoreCase) || arg.StartsWith(name + "=", StringComparison.OrdinalIgnoreCase);++ /// <summary>+ /// Starts Filee as the signed-in user: through the unelevated Setup that started this one (the launch file), else+ /// with Explorer's token when this Setup is elevated, else directly.+ /// </summary>+ private static void StartFilee(LaunchRequest launch, string? launchFile, SetupLog log)+ {+ if (launchFile is not null)+ {+ try+ {+ File.WriteAllLines(launchFile, [launch.Executable, launch.Arguments]);+ log.Info($"Filee starts from the unelevated Setup: {launch.Arguments}");+ return;+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ log.Warn($"Could not write {launchFile}: {ex.Message}");+ }+ }+ if (NativeMethods.IsElevated())+ {+ if (NativeMethods.StartAsShellUser(launch.Executable, launch.Arguments, Path.GetDirectoryName(launch.Executable)!, out var error))+ {+ log.Info($"Started Filee as the signed-in user: {launch.Arguments}");+ return;+ }+ // Filee notices it runs elevated and offers to restart without administrator rights.+ log.Warn($"Could not start Filee as the signed-in user ({error}); starting it with Setup's rights");+ }+ Start(launch, log);+ }++ private static void Start(LaunchRequest launch, SetupLog log)+ {+ try+ {+ using var _ = Process.Start(new ProcessStartInfo(launch.Executable, launch.Arguments)+ {+ UseShellExecute = false,+ WorkingDirectory = Path.GetDirectoryName(launch.Executable)!,+ });+ log.Info($"Started Filee: {launch.Arguments}");+ }+ catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)+ {+ log.Warn($"Could not start Filee: {ex.Message}");+ }+ }++ /// <summary>Deletes <paramref name="folder"/> (the uninstaller's copy and files that were in use) once this process has ended.</summary>+ private static void CleanUpAfterExit(string folder, ISetupSystem system, SetupLog log)+ {+ if (!Directory.Exists(folder))+ return;+ foreach (var file in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))+ system.DeleteAtRestart(file);+ system.DeleteAtRestart(folder);+ try+ {+ using var _ = Process.Start(new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "cmd.exe"),+ $"/d /c ping -n 4 127.0.0.1 >nul & rd /s /q \"{folder}\"")+ {+ UseShellExecute = false,+ CreateNoWindow = true,+ WorkingDirectory = Environment.SystemDirectory,+ });+ }+ catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)+ {+ log.Warn($"Could not clean up {folder}: {ex.Message}");+ }+ }++ private static void TryDeleteFolder(string folder)+ {+ try+ {+ Directory.Delete(folder, recursive: true);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ }+ }++ /// <summary>A message box, unless /SUPPRESSMSGBOXES (the log has everything anyway).</summary>+ private static void Tell(SetupOptions options, string text, uint icon)+ {+ if (options.CanShowMessages)+ NativeMethods.MessageBox(0, text, "Filee Setup", NativeMethods.MB_OK | icon | NativeMethods.MB_SETFOREGROUND);+ }+}++/// <summary>The real installer and uninstaller behind the window.</summary>+[System.Runtime.Versioning.SupportedOSPlatform("windows")]+internal sealed class SetupRunner(SetupContext context, SetupPayload? payload, PreviousInstall? previous,+ string? folder = null, InstallRecord? record = null, string? trash = null) : ISetupRunner+{+ public InstallResult Install(InstallChoices choices, IProgress<SetupProgress> progress) =>+ new Installer(context, payload ?? throw new InvalidOperationException("No payload.")).Run(choices, previous, progress);++ public Exception? Uninstall(bool deleteSettings, IProgress<SetupProgress> progress)+ {+ try+ {+ new Uninstaller(context).Run(folder!, record!, deleteSettings, trash!, progress);+ return null;+ }+ catch (Exception ex) when (ex is not OutOfMemoryException)+ {+ context.Log.Error($"Uninstall failed: {ex}");+ return ex;+ }+ }+}diff --git a/src/Filee.Setup/SetupInfo.cs b/src/Filee.Setup/SetupInfo.csnew file mode 100644index 00000000..b8abae72--- /dev/null+++ b/src/Filee.Setup/SetupInfo.cs@@ -0,0 +1,19 @@+using System.Reflection;++namespace Filee.Setup;++/// <summary>Facts about this Setup program.</summary>+public static class SetupInfo+{+ /// <summary>GitHub repository from Directory.Build.props (FileeRepositoryUrl).</summary>+ public static string RepositoryUrl =>+ typeof(SetupInfo).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>()+ .FirstOrDefault(a => a.Key == "RepositoryUrl")?.Value ?? "https://github.com/KnifeLemon/Filee";++ /// <summary>The website: one big download button.</summary>+ public const string WebsiteUrl = "https://filee.sh/";++ /// <summary>The version this Setup program was built as (the payload says which Filee it installs).</summary>+ public static string Version =>+ typeof(SetupInfo).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion.Split('+')[0] ?? "0.0.0";+}diff --git a/src/Filee.Setup/SetupOptions.cs b/src/Filee.Setup/SetupOptions.csnew file mode 100644index 00000000..573dc6f4--- /dev/null+++ b/src/Filee.Setup/SetupOptions.cs@@ -0,0 +1,208 @@+// Command line of Setup and the uninstaller. Setup takes the switches of the Inno Setup installer it replaces, because+// Filee 1.x updates itself by running the new Setup with "/SILENT /NORESTART" (UpdateService.InstallerArguments) and+// package managers (winget) pass Inno's silent switches:+//+// /SILENT no wizard: only the progress window+// /VERYSILENT no window at all+// /SUPPRESSMSGBOXES no message boxes (errors are logged; the default answer is taken)+// /NORESTART /SP- /NOCANCEL /RESTARTEXITCODE= /CLOSEAPPLICATIONS /RESTARTAPPLICATIONS (and their /NO… forms)+// accepted; Setup never restarts Windows and always closes a running Filee+// /NOCLOSEAPPLICATIONS don't force-close programs that still run from the install folder after "Filee --quit"+// /DIR="folder" install folder (environment variables are expanded)+// /LANG=ko language of Setup (and of a newly installed Filee): en, es, ko, zh-CN (Inno: zhcn),+// pl, hi, ja+// /TASKS="a,b" exactly these options; /MERGETASKS="a,!b" changes the defaults. "!" unticks, "*" ticks+// the children too. Names: contextmenu, contextmenu\top, startup, cli, desktopicon+// /NOICONS no Start menu and desktop shortcuts+// /ALLUSERS install for all users into Program Files (the default; needs administrator rights)+// /CURRENTUSER install for this user only into %LocalAppData%\Programs (no administrator rights; the+// Windows 11 top-level menu needs them and is left out)+// /PORTABLE=1 only unpack Filee into /DIR (no uninstaller, registry, shortcuts or PATH)+// /LOG, /LOG="file" Setup always logs (%TEMP%\Filee-Setup-*.log); /LOG= names the file+// /COMPONENTS= /TYPE= /GROUP= /PASSWORD= /LOADINF= /SAVEINF= accepted and ignored (Filee has none of these)+//+// Filee's own:+// /NOLAUNCH don't start Filee at the end+// /SANDBOX="folder" test run: everything (registry, Start menu, desktop, PATH, %APPDATA%) goes into this folder,+// nothing on the PC is touched and no administrator rights are asked for+// /UNINSTALL uninstall (uninstall.exe, which has no payload, does this without the switch)+// /LAUNCHFILE="file" internal: the unelevated Setup that asked for administrator rights starts Filee as the+// signed-in user from what the elevated one writes into this file++namespace Filee.Setup;++/// <summary>How much of Setup the user sees.</summary>+public enum SetupUi+{+ /// <summary>The wizard.</summary>+ Wizard,++ /// <summary>/SILENT: only the progress window.</summary>+ Silent,++ /// <summary>/VERYSILENT: nothing.</summary>+ VerySilent,+}++/// <summary>Where Filee goes and who it is installed for.</summary>+public enum InstallScope+{+ /// <summary>All users, Program Files, HKLM (administrator rights).</summary>+ Machine,++ /// <summary>This user, %LocalAppData%\Programs, HKCU.</summary>+ User,+}++/// <summary>A parsed Setup command line.</summary>+public sealed record SetupOptions+{+ public SetupUi Ui { get; init; }+ public bool SuppressMessageBoxes { get; init; }+ public string? Directory { get; init; }+ public string? Language { get; init; }+ public string? Tasks { get; init; }+ public string? MergeTasks { get; init; }+ public bool NoIcons { get; init; }+ public InstallScope Scope { get; init; } = InstallScope.Machine;+ public bool Portable { get; init; }+ public string? LogFile { get; init; }+ public bool ForceCloseApplications { get; init; } = true;+ public bool NoLaunch { get; init; }+ public bool Uninstall { get; init; }+ public string? Sandbox { get; init; }+ public string? LaunchFile { get; init; }++ /// <summary>Inno Setup switches that are accepted but change nothing.</summary>+ public IReadOnlyList<string> Ignored { get; init; } = [];++ /// <summary>Arguments Setup doesn't know (logged, otherwise ignored like Inno Setup does).</summary>+ public IReadOnlyList<string> Unknown { get; init; } = [];++ /// <summary>No window: errors can't be shown in the wizard.</summary>+ public bool IsSilent => Ui != SetupUi.Wizard;++ /// <summary>Message boxes may be shown (not with /SUPPRESSMSGBOXES; /VERYSILENT shows only errors).</summary>+ public bool CanShowMessages => !SuppressMessageBoxes;++ public static SetupOptions Parse(IReadOnlyList<string> args)+ {+ var options = new SetupOptions();+ var ignored = new List<string>();+ var unknown = new List<string>();+ foreach (var arg in args)+ {+ if (arg.Length < 2 || arg[0] != '/')+ {+ unknown.Add(arg);+ continue;+ }+ var equals = arg.IndexOf('=');+ var name = (equals < 0 ? arg[1..] : arg[1..equals]).ToUpperInvariant();+ var value = equals < 0 ? null : Unquote(arg[(equals + 1)..]);+ switch (name)+ {+ case "SILENT":+ if (options.Ui == SetupUi.Wizard)+ options = options with { Ui = SetupUi.Silent };+ break;+ case "VERYSILENT":+ options = options with { Ui = SetupUi.VerySilent };+ break;+ case "SUPPRESSMSGBOXES":+ options = options with { SuppressMessageBoxes = true };+ break;+ case "DIR" when !string.IsNullOrWhiteSpace(value):+ options = options with { Directory = value };+ break;+ case "LANG" when !string.IsNullOrWhiteSpace(value):+ options = options with { Language = value };+ break;+ case "TASKS" when value is not null:+ options = options with { Tasks = value };+ break;+ case "MERGETASKS" when value is not null:+ options = options with { MergeTasks = value };+ break;+ case "NOICONS":+ options = options with { NoIcons = true };+ break;+ case "ALLUSERS":+ options = options with { Scope = InstallScope.Machine };+ break;+ case "CURRENTUSER":+ options = options with { Scope = InstallScope.User };+ break;+ case "PORTABLE":+ options = options with { Portable = value is null || value == "1" };+ break;+ case "LOG":+ options = options with { LogFile = string.IsNullOrWhiteSpace(value) ? options.LogFile : value };+ break;+ case "NOCLOSEAPPLICATIONS":+ options = options with { ForceCloseApplications = false };+ break;+ case "CLOSEAPPLICATIONS" or "FORCECLOSEAPPLICATIONS":+ options = options with { ForceCloseApplications = true };+ break;+ case "NOLAUNCH":+ options = options with { NoLaunch = true };+ break;+ case "UNINSTALL":+ options = options with { Uninstall = true };+ break;+ case "SANDBOX" when !string.IsNullOrWhiteSpace(value):+ options = options with { Sandbox = value };+ break;+ case "LAUNCHFILE" when !string.IsNullOrWhiteSpace(value):+ options = options with { LaunchFile = value };+ break;+ case "SP-" or "NORESTART" or "NOCANCEL" or "RESTARTEXITCODE" or "NOFORCECLOSEAPPLICATIONS"+ or "LOGCLOSEAPPLICATIONS" or "RESTARTAPPLICATIONS" or "NORESTARTAPPLICATIONS" or "COMPONENTS"+ or "TYPE" or "GROUP" or "NOGROUP" or "PASSWORD" or "LOADINF" or "SAVEINF" or "HELP" or "?":+ ignored.Add(arg);+ break;+ default:+ unknown.Add(arg);+ break;+ }+ }+ return options with { Ignored = ignored, Unknown = unknown };+ }++ /// <summary>Inno Setup takes /DIR="C:\a b" and /DIR=C:\a b alike; quotes left over from a hand-made command line go.</summary>+ private static string Unquote(string value)+ {+ var trimmed = value.Trim();+ return trimmed.Length >= 2 && trimmed[0] == '"' && trimmed[^1] == '"' ? trimmed[1..^1] : trimmed;+ }++ /// <summary>+ /// One command line from <paramref name="args"/> with the quoting Windows programs (CommandLineToArgvW and the C+ /// runtime) undo: for starting Setup again with administrator rights.+ /// </summary>+ public static string Join(IEnumerable<string> args) => string.Join(' ', args.Select(Quote));++ /// <summary>Quotes one argument for <see cref="Join"/>.</summary>+ public static string Quote(string arg)+ {+ if (arg.Length > 0 && arg.IndexOfAny([' ', '\t', '\n', '\v', '"']) < 0)+ return arg;+ var builder = new System.Text.StringBuilder("\"");+ var backslashes = 0;+ foreach (var c in arg)+ {+ if (c == '\\')+ {+ backslashes++;+ continue;+ }+ // Backslashes before a quote are doubled, and the quote is escaped.+ builder.Append('\\', c == '"' ? backslashes * 2 + 1 : backslashes);+ backslashes = 0;+ builder.Append(c);+ }+ // Backslashes before the closing quote are doubled.+ return builder.Append('\\', backslashes * 2).Append('"').ToString();+ }+}diff --git a/src/Filee.Setup/SetupTexts.cs b/src/Filee.Setup/SetupTexts.csnew file mode 100644index 00000000..1a5d63e6--- /dev/null+++ b/src/Filee.Setup/SetupTexts.cs@@ -0,0 +1,120 @@+// Setup's texts: the app's own translation files (src/Filee.App/Assets/i18n, embedded), so Setup speaks every language+// Filee does in the same words. Setup's own keys start with "installer."; it also uses the app's names of the options+// and engines. Published as resources, so XAML binds them with DynamicResource like the app does.++using System.Globalization;+using System.Text.Json;+using Avalonia.Controls;++namespace Filee.Setup;++public sealed class SetupTexts+{+ /// <summary>Filee's languages: code → native name (LocalizationService.Languages in the app; a test compares).</summary>+ public static readonly IReadOnlyList<(string Code, string NativeName)> KnownLanguages =+ [+ ("en", "English"),+ ("es", "Español"),+ ("ko", "한국어"),+ ("zh-CN", "简体中文"),+ ("pl", "Polski"),+ ("hi", "हिन्दी"),+ ("ja", "日本語"),+ ];++ private readonly Dictionary<string, string> _english = Load("en");+ private Dictionary<string, string> _current;++ public SetupTexts(string language)+ {+ _current = _english;+ SetLanguage(language);+ }++ /// <summary>The languages whose translation file Setup carries.</summary>+ public static IReadOnlyList<(string Code, string NativeName)> Languages { get; } =+ KnownLanguages.Where(l => typeof(SetupTexts).Assembly.GetManifestResourceInfo($"i18n.{l.Code}.json") is not null).ToList();++ public string Language { get; private set; } = "en";++ public event EventHandler? LanguageChanged;++ public string this[string key] =>+ _current.TryGetValue(key, out var value) ? value+ : _english.TryGetValue(key, out var fallback) ? fallback+ : key;++ public string Format(string key, params object[] args)+ {+ try+ {+ return string.Format(CultureInfo.InvariantCulture, this[key], args);+ }+ catch (FormatException)+ {+ return this[key];+ }+ }++ public void SetLanguage(string language)+ {+ Language = Resolve(language, NativeMethodsUiLanguage);+ _current = Language == "en" ? _english : Load(Language);+ LanguageChanged?.Invoke(this, EventArgs.Empty);+ }++ /// <summary>Publishes every text into <paramref name="resources"/> (English for missing translations).</summary>+ public void Publish(IResourceDictionary resources)+ {+ foreach (var key in _english.Keys.Concat(_current.Keys).Distinct())+ resources[key] = this[key];+ }++ /// <summary>+ /// A language code for <paramref name="setting"/>: one of <see cref="Languages"/> ("zh-CN", Inno Setup's "zhcn",+ /// "ko-KR" …) or, for "auto" and anything unknown, Windows' display language, falling back to English.+ /// </summary>+ public static string Resolve(string? setting, Func<string> uiLanguage)+ {+ if (!string.IsNullOrWhiteSpace(setting) && !setting.Equals("auto", StringComparison.OrdinalIgnoreCase))+ {+ if (Match(setting) is { } code)+ return code;+ }+ return Match(uiLanguage()) ?? "en";+ }++ private static string? Match(string name)+ {+ var normalized = name.Trim().Replace('_', '-');+ if (normalized.Equals("zhcn", StringComparison.OrdinalIgnoreCase))+ normalized = "zh-CN";+ foreach (var (code, _) in Languages)+ {+ if (normalized.Equals(code, StringComparison.OrdinalIgnoreCase))+ return code;+ }+ // "ko-KR" → ko, "zh-Hans-CN" / "zh-TW" → zh-CN (the only Chinese), "es-MX" → es.+ var primary = normalized.Split('-')[0];+ foreach (var (code, _) in Languages)+ {+ if (code.Split('-')[0].Equals(primary, StringComparison.OrdinalIgnoreCase))+ return code;+ }+ return null;+ }++ private static string NativeMethodsUiLanguage() =>+ OperatingSystem.IsWindows() ? Platform.NativeMethods.UiLanguage() : CultureInfo.InstalledUICulture.Name;++ internal static Dictionary<string, string> Load(string code)+ {+ using var stream = typeof(SetupTexts).Assembly.GetManifestResourceStream($"i18n.{code}.json");+ if (stream is null)+ return [];+ using var json = JsonDocument.Parse(stream);+ return json.RootElement.EnumerateObject()+ .Where(p => p.Value.ValueKind == JsonValueKind.String)+ .ToDictionary(p => p.Name, p => p.Value.GetString() ?? "");+ }+}diff --git a/src/Filee.Setup/Styles/Setup.axaml b/src/Filee.Setup/Styles/Setup.axamlnew file mode 100644index 00000000..2988f0e4--- /dev/null+++ b/src/Filee.Setup/Styles/Setup.axaml@@ -0,0 +1,53 @@+<!-- Setup's own pieces on top of Filee's Soft.axaml: the step column and the option cards. -->+<Styles xmlns="https://github.com/avaloniaui"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">++ <Style Selector="Border.steps">+ <Setter Property="Background" Value="{DynamicResource SurfaceAltBrush}" />+ </Style>++ <Style Selector="TextBlock.step">+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />+ <Setter Property="TextWrapping" Value="Wrap" />+ </Style>+ <Style Selector="TextBlock.step.current">+ <Setter Property="Foreground" Value="{DynamicResource AccentStrongBrush}" />+ <Setter Property="FontWeight" Value="SemiBold" />+ </Style>+ <Style Selector="TextBlock.step.done">+ <Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />+ </Style>++ <Style Selector="Border.stepdot">+ <Setter Property="Width" Value="10" />+ <Setter Property="Height" Value="10" />+ <Setter Property="CornerRadius" Value="5" />+ <Setter Property="BorderThickness" Value="1.5" />+ <Setter Property="BorderBrush" Value="{DynamicResource TextSecondaryBrush}" />+ <Setter Property="Background" Value="Transparent" />+ </Style>+ <Style Selector="Border.stepdot.current">+ <Setter Property="BorderBrush" Value="{DynamicResource AccentBrush}" />+ <Setter Property="Background" Value="{DynamicResource AccentBrush}" />+ </Style>+ <Style Selector="Border.stepdot.done">+ <Setter Property="BorderBrush" Value="{DynamicResource AccentBrush}" />+ <Setter Property="Background" Value="{DynamicResource AccentSoftBrush}" />+ </Style>++ <!-- Options: one checkbox per row, its text wrapping in long languages. -->+ <Style Selector="CheckBox.option">+ <Setter Property="Margin" Value="0,2" />+ </Style>+ <Style Selector="CheckBox.option > TextBlock, CheckBox.option TextBlock">+ <Setter Property="TextWrapping" Value="Wrap" />+ </Style>++ <Style Selector="Border.warning">+ <Setter Property="Background" Value="{DynamicResource SurfaceBrush}" />+ <Setter Property="BorderBrush" Value="{DynamicResource WarningBrush}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="CornerRadius" Value="{DynamicResource SoftRadiusSmall}" />+ <Setter Property="Padding" Value="14,10" />+ </Style>+</Styles>diff --git a/src/Filee.Setup/ViewModels/SetupViewModel.cs b/src/Filee.Setup/ViewModels/SetupViewModel.csnew file mode 100644index 00000000..ae38c258--- /dev/null+++ b/src/Filee.Setup/ViewModels/SetupViewModel.cs@@ -0,0 +1,469 @@+// The wizard: Welcome (with the language) → Options (folder, Explorer menu, start at sign-in, PATH, desktop icon) →+// Engines (fresh installs, when there is something to download) → Install (progress) → Done ("Launch Filee").+// An update shows only what it may change (desktop icon, PATH); Filee's own settings stay as they are. The uninstaller+// uses the same window: Uninstall (keep or delete the settings) → progress → Done.++using System.Collections.ObjectModel;+using Avalonia.Threading;+using CommunityToolkit.Mvvm.ComponentModel;+using CommunityToolkit.Mvvm.Input;+using Filee.Setup.Installation;+using Filee.Setup.Payload;++namespace Filee.Setup.ViewModels;++public enum SetupPage+{+ Welcome,+ Options,+ Engines,+ Progress,+ Done,+ Failed,+ Uninstall,+ Uninstalled,+}++/// <summary>What the wizard does when the user goes ahead (the real installer, or a fake in tests).</summary>+public interface ISetupRunner+{+ InstallResult Install(InstallChoices choices, IProgress<SetupProgress> progress);++ /// <summary>Uninstalls; null when it worked, else the error.</summary>+ Exception? Uninstall(bool deleteSettings, IProgress<SetupProgress> progress);+}++/// <summary>A language in the picker.</summary>+public sealed record LanguageItem(string Code, string Name)+{+ public override string ToString() => Name;+}++/// <summary>An engine package on the Engines page.</summary>+public sealed partial class EngineItem(EngineOffer offer, bool installed) : ObservableObject+{+ public EngineOffer Offer { get; } = offer;+ public string Id => Offer.Id;+ public bool Installed { get; } = installed;+ public bool CanSelect => !Installed;++ [ObservableProperty] private bool _selected = !installed && offer.Suggested;+ [ObservableProperty] private string _name = offer.Id;+ [ObservableProperty] private string _detail = "";+}++/// <summary>A step in the left column.</summary>+public sealed partial class StepItem(string key, SetupPage[] pages) : ObservableObject+{+ public string Key { get; } = key;+ public SetupPage[] Pages { get; } = pages;+ [ObservableProperty] private string _title = "";+ [ObservableProperty] private bool _isCurrent;+ [ObservableProperty] private bool _isDone;+}++public sealed partial class SetupViewModel : ObservableObject+{+ private readonly SetupTexts _texts;+ private readonly ISetupRunner _runner;+ private readonly PreviousInstall? _previous;+ private readonly InstallChoices _initial;+ private readonly long _neededSpace;+ private bool _languagePicked;+ private InstallResult? _result;++ /// <param name="version">The Filee version Setup installs (or the uninstaller removes).</param>+ /// <param name="initial">The choices from the command line and the defaults.</param>+ /// <param name="engines">Packages offered on a fresh install, with whether each is installed already.</param>+ /// <param name="modernMenuSupported">Windows 11 x64 and administrator rights: the top-level menu can be offered.</param>+ /// <param name="uninstall">The uninstaller's window.</param>+ public SetupViewModel(SetupTexts texts, ISetupRunner runner, string version, InstallChoices initial, PreviousInstall? previous,+ IReadOnlyList<(EngineOffer Offer, bool Installed)> engines, bool modernMenuSupported, long neededSpace, bool uninstall = false,+ bool languagePicked = false)+ {+ _texts = texts;+ _runner = runner;+ _previous = previous;+ _initial = initial;+ _neededSpace = neededSpace;+ _languagePicked = languagePicked;+ Version = version;+ IsUninstall = uninstall;+ IsUpdate = previous is not null && !uninstall;+ ModernMenuSupported = modernMenuSupported;+ Languages = SetupTexts.Languages.Select(l => new LanguageItem(l.Code, l.NativeName)).ToList();+ _selectedLanguage = Languages.FirstOrDefault(l => l.Code == texts.Language) ?? Languages[0];+ _folder = initial.Folder;+ _contextMenu = initial.Tasks.ContextMenu;+ _modernMenu = initial.Tasks.ModernMenu && modernMenuSupported;+ _startup = initial.Tasks.Startup;+ _cli = initial.Tasks.Cli;+ _desktopIcon = initial.Tasks.DesktopIcon;+ Engines = new ObservableCollection<EngineItem>(engines.Select(e => new EngineItem(e.Offer, e.Installed)));+ foreach (var engine in Engines)+ {+ engine.PropertyChanged += (_, e) =>+ {+ if (e.PropertyName == nameof(EngineItem.Selected))+ UpdateEngineSelection();+ };+ }+ var steps = new List<StepItem>();+ if (uninstall)+ {+ steps.Add(new StepItem("installer.step.uninstall", [SetupPage.Uninstall]));+ steps.Add(new StepItem("installer.step.remove", [SetupPage.Progress, SetupPage.Failed]));+ steps.Add(new StepItem("installer.step.done", [SetupPage.Uninstalled]));+ }+ else+ {+ steps.Add(new StepItem("installer.step.welcome", [SetupPage.Welcome]));+ steps.Add(new StepItem("installer.step.options", [SetupPage.Options]));+ if (HasEnginesPage)+ steps.Add(new StepItem("installer.step.engines", [SetupPage.Engines]));+ steps.Add(new StepItem("installer.step.install", [SetupPage.Progress, SetupPage.Failed]));+ steps.Add(new StepItem("installer.step.done", [SetupPage.Done]));+ }+ Steps = steps;+ _page = uninstall ? SetupPage.Uninstall : SetupPage.Welcome;+ texts.LanguageChanged += (_, _) => RefreshTexts();+ RefreshTexts();+ }++ public string Version { get; }+ public bool IsUninstall { get; }+ public bool IsUpdate { get; }+ public bool IsFresh => !IsUpdate && !IsUninstall;+ public bool ModernMenuSupported { get; }+ public IReadOnlyList<LanguageItem> Languages { get; }+ public ObservableCollection<EngineItem> Engines { get; }+ public IReadOnlyList<StepItem> Steps { get; }++ /// <summary>Fresh installs offer the engines that aren't downloaded yet.</summary>+ public bool HasEnginesPage => IsFresh && Engines.Any(e => !e.Installed);++ /// <summary>Raised when the window should close (finished, cancelled).</summary>+ public event EventHandler? CloseRequested;++ /// <summary>Asks the view for a folder (the folder picker); null when cancelled.</summary>+ public Func<string, Task<string?>>? PickFolder { get; set; }++ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(IsWelcome), nameof(IsOptions), nameof(IsEngines), nameof(IsProgress), nameof(IsDone),+ nameof(IsFailed), nameof(IsUninstallPage), nameof(IsUninstalled), nameof(CanGoBack), nameof(ShowCancel), nameof(NextText),+ nameof(ShowNext))]+ private SetupPage _page;++ public bool IsWelcome => Page == SetupPage.Welcome;+ public bool IsOptions => Page == SetupPage.Options;+ public bool IsEngines => Page == SetupPage.Engines;+ public bool IsProgress => Page == SetupPage.Progress;+ public bool IsDone => Page == SetupPage.Done;+ public bool IsFailed => Page == SetupPage.Failed;+ public bool IsUninstallPage => Page == SetupPage.Uninstall;+ public bool IsUninstalled => Page == SetupPage.Uninstalled;++ [ObservableProperty] private LanguageItem _selectedLanguage;+ [ObservableProperty] private string _folder;+ [ObservableProperty] private bool _contextMenu;+ [ObservableProperty] private bool _modernMenu;+ [ObservableProperty] private bool _startup;+ [ObservableProperty] private bool _cli;+ [ObservableProperty] private bool _desktopIcon;+ [ObservableProperty] private bool _launchFilee = true;+ [ObservableProperty] private bool _deleteSettings;++ [ObservableProperty] private string _welcomeText = "";+ [ObservableProperty] private string _spaceText = "";+ [ObservableProperty] private string _statusText = "";+ [ObservableProperty] private double _percent;+ [ObservableProperty] private string _progressTitle = "";+ [ObservableProperty] private string _doneText = "";+ [ObservableProperty] private string _warningText = "";+ [ObservableProperty] private string _errorText = "";+ [ObservableProperty] private string _errorTitle = "";+ [ObservableProperty] private string _uninstallText = "";+ [ObservableProperty] private string _uninstalledText = "";+ [ObservableProperty] private string _engineSelectionText = "";+ [ObservableProperty] private string _logText = "";+ [ObservableProperty] private string _settingsText = "";++ /// <summary>Setup's log file (named on the error page).</summary>+ public string? LogFile+ {+ get;+ set+ {+ field = value;+ RefreshTexts();+ }+ }++ /// <summary>Filee's settings folder (named on the uninstall page).</summary>+ public string SettingsFolder+ {+ get;+ set+ {+ field = value;+ RefreshTexts();+ }+ } = "";++ /// <summary>The page has a working Back button.</summary>+ public bool CanGoBack => Page is SetupPage.Options or SetupPage.Engines;++ public bool ShowCancel => Page is SetupPage.Welcome or SetupPage.Options or SetupPage.Engines or SetupPage.Uninstall;++ public bool ShowNext => Page != SetupPage.Progress;++ public string NextText => Page switch+ {+ SetupPage.Options when !HasEnginesPage => _texts[IsUpdate ? "installer.update" : "installer.install"],+ SetupPage.Engines => _texts["installer.install"],+ SetupPage.Done => _texts["installer.finish"],+ SetupPage.Failed or SetupPage.Uninstalled => _texts["common.close"],+ SetupPage.Uninstall => _texts["installer.uninstall.button"],+ _ => _texts["installer.next"],+ };++ /// <summary>The fresh install's top-level menu option needs the Explorer menu option.</summary>+ public bool ModernMenuEnabled => ContextMenu;++ /// <summary>Exit code for Setup (Inno Setup's: 0 done, 2 cancelled before installing, 4 failed during installing).</summary>+ public int ExitCode { get; private set; } = 2;++ /// <summary>What to start when the window closes (Done with "Launch Filee").</summary>+ public LaunchRequest? Launch { get; private set; }++ public InstallResult? Result => _result;++ partial void OnSelectedLanguageChanged(LanguageItem value)+ {+ if (value is null || value.Code == _texts.Language)+ return;+ _languagePicked = true;+ _texts.SetLanguage(value.Code);+ }++ partial void OnContextMenuChanged(bool value) => OnPropertyChanged(nameof(ModernMenuEnabled));++ partial void OnPageChanged(SetupPage value)+ {+ var current = Steps.ToList().FindIndex(s => s.Pages.Contains(value));+ for (var i = 0; i < Steps.Count; i++)+ {+ Steps[i].IsCurrent = i == current;+ Steps[i].IsDone = i < current;+ }+ }++ /// <summary>Recomputes the texts with arguments (after a language change).</summary>+ private void RefreshTexts()+ {+ WelcomeText = IsUpdate+ ? _texts.Format("installer.welcome.update", _previous?.Version ?? "?", Version)+ : _texts.Format("installer.welcome.fresh", Version);+ SpaceText = _texts.Format("installer.options.space", Installer.FormatSize(_neededSpace));+ UninstallText = _texts.Format("installer.uninstall.text", Version);+ SettingsText = _texts.Format("installer.uninstall.settings_where", SettingsFolder);+ LogText = LogFile is null ? "" : _texts.Format("installer.error.log", LogFile);+ foreach (var step in Steps)+ step.Title = _texts[step.Key];+ foreach (var engine in Engines)+ {+ engine.Name = _texts[$"engines.package.{engine.Id}.name"];+ engine.Detail = engine.Installed+ ? _texts["engines.state.installed"]+ : _texts.Format("engines.package.size", Installer.FormatSize(engine.Offer.DownloadSize), Installer.FormatSize(engine.Offer.InstalledSize));+ }+ UpdateEngineSelection();+ ErrorTitle = _texts[IsUninstall ? "installer.error.uninstall_title" : "installer.error.title"];+ ProgressTitle = _texts[IsUninstall ? "installer.uninstall.progress" : IsUpdate ? "installer.progress.update" : "installer.progress.install"];+ OnPropertyChanged(nameof(NextText));+ OnPageChanged(Page);+ }++ private void UpdateEngineSelection()+ {+ var selected = Engines.Where(e => e.Selected).Select(e => e.Name).ToList();+ EngineSelectionText = selected.Count == 0 ? _texts["setup.nothing_selected"] : _texts.Format("setup.selection", string.Join(", ", selected));+ }++ [RelayCommand]+ private async Task BrowseAsync()+ {+ if (PickFolder is null)+ return;+ if (await PickFolder(Folder) is { } picked)+ {+ // A folder of its own, like Inno Setup: picking "D:\Apps" installs into "D:\Apps\Filee".+ Folder = Path.GetFileName(Path.TrimEndingDirectorySeparator(picked)).Equals("Filee", StringComparison.OrdinalIgnoreCase)+ ? picked+ : Path.Combine(picked, "Filee");+ }+ }++ [RelayCommand]+ private void Back()+ {+ Page = Page switch+ {+ SetupPage.Engines => SetupPage.Options,+ SetupPage.Options => SetupPage.Welcome,+ _ => Page,+ };+ }++ /// <summary>The window's close button: Cancel before installing, Finish on the Done page.</summary>+ public void WindowClosing()+ {+ if (Page == SetupPage.Done)+ Launch = LaunchFilee ? _result?.Launch : null;+ else if (Page is SetupPage.Welcome or SetupPage.Options or SetupPage.Engines or SetupPage.Uninstall)+ ExitCode = 2;+ }++ [RelayCommand]+ private void Cancel()+ {+ ExitCode = 2;+ CloseRequested?.Invoke(this, EventArgs.Empty);+ }++ [RelayCommand]+ private async Task NextAsync()+ {+ switch (Page)+ {+ case SetupPage.Welcome:+ Page = SetupPage.Options;+ break;+ case SetupPage.Options when HasEnginesPage:+ Page = SetupPage.Engines;+ break;+ case SetupPage.Options or SetupPage.Engines:+ await InstallAsync();+ break;+ case SetupPage.Uninstall:+ await UninstallAsync();+ break;+ case SetupPage.Done:+ Launch = LaunchFilee ? _result?.Launch : null;+ CloseRequested?.Invoke(this, EventArgs.Empty);+ break;+ default:+ CloseRequested?.Invoke(this, EventArgs.Empty);+ break;+ }+ }++ /// <summary>The choices as they stand on the pages.</summary>+ public InstallChoices Choices()+ {+ var tasks = new SetupTasks(ContextMenu, ContextMenu && ModernMenu && ModernMenuSupported, Startup, Cli, DesktopIcon);+ return _initial with+ {+ Folder = Folder,+ Tasks = tasks,+ Engines = IsFresh ? Engines.Where(e => e.Selected && !e.Installed).Select(e => e.Id).ToList() : [],+ Language = _texts.Language,+ LanguagePicked = _languagePicked,+ };+ }++ /// <summary>Installs with the current choices (also what /SILENT does right away).</summary>+ public async Task InstallAsync()+ {+ RefreshTexts();+ var choices = Choices();+ Page = SetupPage.Progress;+ Percent = 0;+ var progress = new SyncProgress<SetupProgress>(p => Dispatcher.UIThread.Post(() => ShowProgress(p)));+ _result = await Task.Run(() => _runner.Install(choices, progress));+ if (_result.Succeeded)+ {+ ExitCode = 0;+ DoneText = _texts[IsUpdate ? "installer.done.updated" : "installer.done.text"]+ + (choices.Engines.Count > 0 ? Environment.NewLine + Environment.NewLine + _texts["installer.done.engines"] : "");+ WarningText = string.Join(Environment.NewLine + Environment.NewLine, _result.Warnings.Select(WarningMessage));+ Page = SetupPage.Done;+ }+ else+ {+ ExitCode = 4;+ ErrorText = ErrorMessage(_result.Error!) + Environment.NewLine + Environment.NewLine+ + _texts[_result.RolledBack ? IsUpdate ? "installer.error.rolled_back" : "installer.error.undone" : "installer.error.nothing_changed"];+ Page = SetupPage.Failed;+ }+ }++ /// <summary>Uninstalls (also what a silent uninstall does right away).</summary>+ public async Task UninstallAsync()+ {+ RefreshTexts();+ var deleteSettings = DeleteSettings;+ Page = SetupPage.Progress;+ Percent = 0;+ var progress = new SyncProgress<SetupProgress>(p => Dispatcher.UIThread.Post(() => ShowProgress(p)));+ var error = await Task.Run(() => _runner.Uninstall(deleteSettings, progress));+ if (error is null)+ {+ ExitCode = 0;+ UninstalledText = _texts["installer.uninstall.done"]+ + (deleteSettings ? "" : Environment.NewLine + Environment.NewLine + _texts["installer.uninstall.settings_kept"]);+ Page = SetupPage.Uninstalled;+ }+ else+ {+ ExitCode = 1;+ ErrorText = ErrorMessage(error);+ Page = SetupPage.Failed;+ }+ }++ private void ShowProgress(SetupProgress progress)+ {+ Percent = Math.Round(progress.Fraction * 100, 1);+ StatusText = _texts[progress.Step switch+ {+ SetupStep.Verifying => "installer.status.verifying",+ SetupStep.Closing => "installer.status.closing",+ SetupStep.RemovingOld => "installer.status.removing_old",+ SetupStep.Copying => "installer.status.copying",+ SetupStep.ExplorerMenu => "installer.status.explorer_menu",+ SetupStep.RollingBack => "installer.status.rolling_back",+ SetupStep.Removing => "installer.status.removing",+ _ => "installer.status.finishing",+ }];+ }++ /// <summary>A warning in the UI language.</summary>+ public string WarningMessage(SetupWarning warning) => SetupMessages.Warning(_texts, warning);++ /// <summary>An error in the UI language.</summary>+ public string ErrorMessage(Exception error) => SetupMessages.Error(_texts, error);+}++/// <summary>Warnings and errors in the UI language.</summary>+public static class SetupMessages+{+ public static string Warning(SetupTexts texts, SetupWarning warning) => warning switch+ {+ ExplorerMenuWarning menu => texts.Format("installer.warning.explorer_menu", menu.Error),+ RuntimeWarning runtime => texts.Format("installer.warning.runtime",+ string.Join(", ", runtime.Missing.Select(m => Path.GetFileName(m.Program)).Distinct(StringComparer.OrdinalIgnoreCase)),+ string.Join(", ", runtime.Missing.Select(m => m.Dll).Distinct(StringComparer.OrdinalIgnoreCase)),+ SetupNames.VcRedistUrl),+ _ => warning.ToString(),+ };++ /// <summary>The technical message only for errors nobody expected.</summary>+ public static string Error(SetupTexts texts, Exception error) => error switch+ {+ SetupException known => texts.Format(known.TextKey, [.. known.Arguments]),+ InvalidDataException => texts["installer.error.damaged"],+ UnauthorizedAccessException or IOException => texts.Format("installer.error.files", error.Message),+ _ => texts.Format("installer.error.unexpected", error.Message),+ };+}diff --git a/src/Filee.Setup/Views/SetupWindow.axaml b/src/Filee.Setup/Views/SetupWindow.axamlnew file mode 100644index 00000000..89efd398--- /dev/null+++ b/src/Filee.Setup/Views/SetupWindow.axaml@@ -0,0 +1,192 @@+<!-- Setup and the uninstaller: steps on the left, the page on the right, the buttons below it. -->+<Window xmlns="https://github.com/avaloniaui"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:vm="using:Filee.Setup.ViewModels"+ x:Class="Filee.Setup.Views.SetupWindow"+ x:DataType="vm:SetupViewModel"+ Title="{DynamicResource installer.title}"+ Icon="avares://Filee.Setup/Assets/Icons/filee.ico"+ Width="800" Height="560" MinWidth="640" MinHeight="480"+ CanResize="True"+ WindowStartupLocation="CenterScreen">+ <Grid ColumnDefinitions="232,*">+ <!-- ───────── Steps ───────── -->+ <Border Classes="steps" Padding="24,26,20,22">+ <DockPanel>+ <StackPanel DockPanel.Dock="Top" Spacing="2" Margin="0,0,0,26">+ <Image Source="avares://Filee.Setup/Assets/Icons/filee.png" Width="52" Height="52" HorizontalAlignment="Left" Margin="0,0,0,10" />+ <TextBlock Classes="h2" Text="Filee" />+ <TextBlock Classes="caption" Text="{Binding Version}" />+ </StackPanel>+ <TextBlock DockPanel.Dock="Bottom" Classes="caption" Text="filee.sh" />+ <ItemsControl ItemsSource="{Binding Steps}" Focusable="False">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate>+ <StackPanel Spacing="14" />+ </ItemsPanelTemplate>+ </ItemsControl.ItemsPanel>+ <ItemsControl.ItemTemplate>+ <DataTemplate x:DataType="vm:StepItem">+ <DockPanel>+ <Border DockPanel.Dock="Left" Classes="stepdot" Classes.current="{Binding IsCurrent}" Classes.done="{Binding IsDone}"+ VerticalAlignment="Top" Margin="0,5,12,0" />+ <TextBlock Classes="step" Classes.current="{Binding IsCurrent}" Classes.done="{Binding IsDone}" Text="{Binding Title}" />+ </DockPanel>+ </DataTemplate>+ </ItemsControl.ItemTemplate>+ </ItemsControl>+ </DockPanel>+ </Border>++ <!-- ───────── Page ───────── -->+ <DockPanel Grid.Column="1" Margin="34,28,30,22">+ <!-- Buttons -->+ <DockPanel DockPanel.Dock="Bottom" Margin="0,16,0,0" LastChildFill="False">+ <Button DockPanel.Dock="Left" MinWidth="96" HorizontalContentAlignment="Center" Content="{DynamicResource installer.back}"+ Command="{Binding BackCommand}" IsVisible="{Binding CanGoBack}" />+ <Button x:Name="NextButton" DockPanel.Dock="Right" Classes="accent" MinWidth="112" HorizontalContentAlignment="Center"+ Content="{Binding NextText}" Command="{Binding NextCommand}" IsVisible="{Binding ShowNext}" IsDefault="True" />+ <Button DockPanel.Dock="Right" MinWidth="96" Margin="0,0,8,0" HorizontalContentAlignment="Center"+ Content="{DynamicResource common.cancel}" Command="{Binding CancelCommand}" IsVisible="{Binding ShowCancel}" IsCancel="True" />+ </DockPanel>++ <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto" Padding="0,0,6,0">+ <Panel>+ <!-- Welcome -->+ <StackPanel Spacing="10" IsVisible="{Binding IsWelcome}">+ <TextBlock Classes="h1" TextWrapping="Wrap" Text="{DynamicResource installer.welcome.title}" />+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{Binding WelcomeText}" />+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{DynamicResource installer.welcome.about}" />+ <TextBlock Classes="label" Margin="0,18,0,0" Text="{DynamicResource installer.language}" />+ <ComboBox x:Name="LanguageBox" MinWidth="240" ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}">+ <ComboBox.ItemTemplate>+ <DataTemplate x:DataType="vm:LanguageItem">+ <TextBlock Text="{Binding Name}" />+ </DataTemplate>+ </ComboBox.ItemTemplate>+ </ComboBox>+ <TextBlock Classes="caption" TextWrapping="Wrap" Margin="0,18,0,0" Text="{DynamicResource installer.welcome.license}" />+ </StackPanel>++ <!-- Options -->+ <StackPanel Spacing="12" IsVisible="{Binding IsOptions}">+ <TextBlock Classes="h1" TextWrapping="Wrap" Text="{DynamicResource installer.options.title}" />+ <StackPanel Spacing="4" IsVisible="{Binding IsFresh}">+ <TextBlock Classes="label" Text="{DynamicResource installer.options.folder}" />+ <DockPanel>+ <Button DockPanel.Dock="Right" Margin="8,0,0,0" Content="{DynamicResource installer.options.browse}" Command="{Binding BrowseCommand}" />+ <TextBox x:Name="FolderBox" Text="{Binding Folder}" />+ </DockPanel>+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding SpaceText}" />+ </StackPanel>+ <StackPanel Spacing="4" IsVisible="{Binding IsUpdate}">+ <TextBlock Classes="label" Text="{DynamicResource installer.options.folder}" />+ <TextBlock TextWrapping="Wrap" Text="{Binding Folder}" />+ </StackPanel>+ <Border Classes="card" Padding="16,12">+ <StackPanel Spacing="2">+ <CheckBox Classes="option" IsChecked="{Binding ContextMenu}" IsVisible="{Binding IsFresh}">+ <TextBlock Text="{DynamicResource general.context_menu}" />+ </CheckBox>+ <CheckBox Classes="option" Margin="28,0,0,2" IsChecked="{Binding ModernMenu}" IsEnabled="{Binding ModernMenuEnabled}">+ <CheckBox.IsVisible>+ <MultiBinding Converter="{x:Static BoolConverters.And}">+ <Binding Path="IsFresh" />+ <Binding Path="ModernMenuSupported" />+ </MultiBinding>+ </CheckBox.IsVisible>+ <TextBlock Text="{DynamicResource installer.task.modern_menu}" />+ </CheckBox>+ <CheckBox Classes="option" IsChecked="{Binding Startup}" IsVisible="{Binding IsFresh}">+ <TextBlock Text="{DynamicResource general.start_with_system}" />+ </CheckBox>+ <CheckBox Classes="option" IsChecked="{Binding Cli}">+ <TextBlock Text="{DynamicResource installer.task.cli}" />+ </CheckBox>+ <CheckBox Classes="option" IsChecked="{Binding DesktopIcon}">+ <TextBlock Text="{DynamicResource installer.task.desktop_icon}" />+ </CheckBox>+ </StackPanel>+ </Border>+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource installer.options.later}" IsVisible="{Binding IsFresh}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource installer.options.update_note}" IsVisible="{Binding IsUpdate}" />+ </StackPanel>++ <!-- Engines -->+ <StackPanel Spacing="12" IsVisible="{Binding IsEngines}">+ <TextBlock Classes="h1" TextWrapping="Wrap" Text="{DynamicResource setup.title}" />+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{DynamicResource setup.description}" />+ <ItemsControl ItemsSource="{Binding Engines}" Focusable="False">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate>+ <StackPanel Spacing="8" />+ </ItemsPanelTemplate>+ </ItemsControl.ItemsPanel>+ <ItemsControl.ItemTemplate>+ <DataTemplate x:DataType="vm:EngineItem">+ <Border Classes="card" Padding="14,10">+ <CheckBox Classes="option" IsChecked="{Binding Selected}" IsEnabled="{Binding CanSelect}">+ <StackPanel Spacing="2">+ <TextBlock FontWeight="SemiBold" TextWrapping="Wrap" Text="{Binding Name}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding Detail}" />+ </StackPanel>+ </CheckBox>+ </Border>+ </DataTemplate>+ </ItemsControl.ItemTemplate>+ </ItemsControl>+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{Binding EngineSelectionText}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource installer.engines.when}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource setup.note}" />+ </StackPanel>++ <!-- Progress -->+ <StackPanel Spacing="14" IsVisible="{Binding IsProgress}" VerticalAlignment="Center">+ <TextBlock Classes="h1" TextWrapping="Wrap" Text="{Binding ProgressTitle}" />+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{Binding StatusText}" />+ <ProgressBar Classes="soft" Minimum="0" Maximum="100" Value="{Binding Percent}" />+ </StackPanel>++ <!-- Done -->+ <StackPanel Spacing="12" IsVisible="{Binding IsDone}">+ <TextBlock Classes="h1" TextWrapping="Wrap" Text="{DynamicResource installer.done.title}" />+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{Binding DoneText}" />+ <Border Classes="warning" IsVisible="{Binding WarningText, Converter={x:Static StringConverters.IsNotNullOrEmpty}}">+ <SelectableTextBlock TextWrapping="Wrap" Text="{Binding WarningText}" />+ </Border>+ <CheckBox Classes="option" Margin="0,8,0,0" IsChecked="{Binding LaunchFilee}">+ <TextBlock Text="{DynamicResource installer.done.launch}" />+ </CheckBox>+ </StackPanel>++ <!-- Failed -->+ <StackPanel Spacing="12" IsVisible="{Binding IsFailed}">+ <TextBlock Classes="h1" TextWrapping="Wrap" Text="{Binding ErrorTitle}" />+ <SelectableTextBlock Classes="muted" TextWrapping="Wrap" Text="{Binding ErrorText}" />+ <SelectableTextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding LogText}" />+ </StackPanel>++ <!-- Uninstall -->+ <StackPanel Spacing="12" IsVisible="{Binding IsUninstallPage}">+ <TextBlock Classes="h1" TextWrapping="Wrap" Text="{DynamicResource installer.uninstall.title}" />+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{Binding UninstallText}" />+ <Border Classes="card" Padding="16,12" Margin="0,6,0,0">+ <StackPanel Spacing="4">+ <CheckBox Classes="option" IsChecked="{Binding DeleteSettings}">+ <TextBlock Text="{DynamicResource installer.uninstall.delete_settings}" />+ </CheckBox>+ <TextBlock Classes="caption" Margin="28,0,0,0" TextWrapping="Wrap" Text="{Binding SettingsText}" />+ </StackPanel>+ </Border>+ </StackPanel>++ <!-- Uninstalled -->+ <StackPanel Spacing="12" IsVisible="{Binding IsUninstalled}">+ <TextBlock Classes="h1" TextWrapping="Wrap" Text="{DynamicResource installer.uninstall.done_title}" />+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{Binding UninstalledText}" />+ </StackPanel>+ </Panel>+ </ScrollViewer>+ </DockPanel>+ </Grid>+</Window>diff --git a/src/Filee.Setup/Views/SetupWindow.axaml.cs b/src/Filee.Setup/Views/SetupWindow.axaml.csnew file mode 100644index 00000000..8e2bf6d0--- /dev/null+++ b/src/Filee.Setup/Views/SetupWindow.axaml.cs@@ -0,0 +1,83 @@+using Avalonia.Controls;+using Avalonia.Platform.Storage;+using Filee.Setup.ViewModels;++namespace Filee.Setup.Views;++public partial class SetupWindow : Window+{+ private readonly SetupViewModel _model;+ private bool _closing;++ /// <summary>For the XAML previewer.</summary>+ public SetupWindow() : this(null!, false)+ {+ }++ /// <param name="silent">/SILENT: install at once, show only the progress and close when done.</param>+ public SetupWindow(SetupViewModel model, bool silent)+ {+ InitializeComponent();+ _model = model;+ DataContext = model;+ if (model is null)+ return;+ model.PickFolder = PickFolderAsync;+ model.CloseRequested += (_, _) =>+ {+ _closing = true;+ Close();+ };+ // Installing can't be stopped halfway: the window stays until the files are in place (or back).+ Closing += (_, e) =>+ {+ if (_closing)+ return;+ if (model.IsProgress)+ e.Cancel = true;+ else+ model.WindowClosing();+ };+ Opened += async (_, _) =>+ {+ if (silent)+ {+ if (model.IsUninstall)+ await model.UninstallAsync();+ else+ await model.InstallAsync();+ SilentFinished?.Invoke(this, EventArgs.Empty);+ _closing = true;+ Close();+ return;+ }+ (model.IsUninstall ? (Control)NextButton : LanguageBox).Focus();+ };+ }++ /// <summary>A /SILENT run ended (before the window closes): Program shows an error message if there was one.</summary>+ public event EventHandler? SilentFinished;++ private async Task<string?> PickFolderAsync(string current)+ {+ IStorageFolder? start = null;+ try+ {+ var existing = current;+ while (!string.IsNullOrEmpty(existing) && !Directory.Exists(existing))+ existing = Path.GetDirectoryName(existing);+ if (!string.IsNullOrEmpty(existing))+ start = await StorageProvider.TryGetFolderFromPathAsync(existing);+ }+ catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)+ {+ }+ var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions+ {+ AllowMultiple = false,+ SuggestedStartLocation = start,+ Title = Title,+ });+ return folders.Count > 0 ? folders[0].TryGetLocalPath() : null;+ }+}diff --git a/src/Filee.Setup/app.manifest b/src/Filee.Setup/app.manifestnew file mode 100644index 00000000..13e539d1--- /dev/null+++ b/src/Filee.Setup/app.manifest@@ -0,0 +1,32 @@+<?xml version="1.0" encoding="utf-8"?>+<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">+ <assemblyIdentity version="1.0.0.0" name="Filee.Setup"/>++ <!--+ asInvoker: Setup asks for administrator rights itself (Program.RelaunchElevated) and keeps running unelevated+ meanwhile, so it can start Filee as the signed-in user at the end (Filee must not run elevated: Windows blocks+ drag and drop from Explorer into elevated windows). /CURRENTUSER, /PORTABLE=1 and /SANDBOX= need no rights.+ -->+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">+ <security>+ <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">+ <requestedExecutionLevel level="asInvoker" uiAccess="false" />+ </requestedPrivileges>+ </security>+ </trustInfo>++ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">+ <application>+ <!-- Windows 10 / 11 -->+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />+ </application>+ </compatibility>++ <application xmlns="urn:schemas-microsoft-com:asm.v3">+ <windowsSettings>+ <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>+ <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>+ <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>+ </windowsSettings>+ </application>+</assembly>diff --git a/tests/Filee.Setup.Tests/Filee.Setup.Tests.csproj b/tests/Filee.Setup.Tests/Filee.Setup.Tests.csprojnew file mode 100644index 00000000..26fbc656--- /dev/null+++ b/tests/Filee.Setup.Tests/Filee.Setup.Tests.csproj@@ -0,0 +1,25 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <OutputType>Exe</OutputType>+ <IsPackable>false</IsPackable>+ <IsTestProject>true</IsTestProject>+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>+ </PropertyGroup>++ <ItemGroup>+ <ProjectReference Include="..\..\src\Filee.Setup\Filee.Setup.csproj" />+ <!-- What Setup hands over must be what the app reads (CommandLine, EngineDownloads, LocalizationService). -->+ <ProjectReference Include="..\..\src\Filee.App\Filee.App.csproj" Aliases="app" />+ </ItemGroup>++ <ItemGroup>+ <PackageReference Include="Microsoft.NET.Test.Sdk" />+ <PackageReference Include="xunit.v3" />+ <PackageReference Include="xunit.runner.visualstudio" />+ <PackageReference Include="Avalonia.Headless.XUnit" />+ </ItemGroup>++ <ItemGroup>+ <Using Include="Xunit" />+ </ItemGroup>+</Project>diff --git a/tests/Filee.Setup.Tests/InstallerTests.cs b/tests/Filee.Setup.Tests/InstallerTests.csnew file mode 100644index 00000000..3f21f473--- /dev/null+++ b/tests/Filee.Setup.Tests/InstallerTests.cs@@ -0,0 +1,305 @@+// Installs, updates and uninstalls against a registry in memory, a fake Windows and scratch folders: nothing here+// touches HKLM, HKCU, PATH, the Start menu or a real Filee.++extern alias app;+using Filee.Setup.Installation;+using Filee.Setup.Platform;+using CommandLine = app::Filee.App.Services.CommandLine;++namespace Filee.Setup.Tests;++public class InstallerTests+{+ private const string Key = SetupNames.UninstallKey;++ [Fact]+ public void A_fresh_install_puts_everything_in_place()+ {+ using var bench = new SetupBench();+ var result = bench.Install();+ Assert.True(result.Succeeded, result.Error?.ToString());+ var folder = bench.InstallFolder;++ foreach (var file in new[] { "Filee.exe", "Filee.dll", @"cli\filee.cmd", @"engines\rhwp\rhwp.exe", "uninstall.exe", "uninstall.json" })+ Assert.True(File.Exists(Path.Combine(folder, file)), file);+ Assert.Empty(Directory.EnumerateDirectories(folder, FileSwap.WorkFolderPrefix + "*"));+ var record = InstallRecord.Read(folder)!;+ Assert.Equal("2.0.0", record.Version);+ Assert.Contains("uninstall.exe", record.Files);+ Assert.Contains(@"engines\rhwp\rhwp.exe", record.Files);++ // Apps & Features: Inno Setup's key, with everything Windows shows.+ var registry = bench.Registry;+ string? Value(string name) => registry.Get(Hive.LocalMachine, Key, name)?.Text;+ Assert.Equal("Filee", Value("DisplayName"));+ Assert.Equal("2.0.0", Value("DisplayVersion"));+ Assert.Equal("Filee contributors", Value("Publisher"));+ Assert.Equal(Path.Combine(folder, "Filee.exe"), Value("DisplayIcon"));+ Assert.Equal(folder + "\\", Value("InstallLocation"));+ Assert.Equal($"\"{folder}\\uninstall.exe\"", Value("UninstallString"));+ Assert.Equal($"\"{folder}\\uninstall.exe\" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART", Value("QuietUninstallString"));+ Assert.Equal(1, registry.Get(Hive.LocalMachine, Key, "NoModify")?.Value);+ Assert.True((int)registry.Get(Hive.LocalMachine, Key, "EstimatedSize")!.Value > 0);+ Assert.Equal(2, registry.Get(Hive.LocalMachine, Key, "VersionMajor")?.Value);+ Assert.Equal(@"contextmenu,contextmenu\top,startup,cli", Value(SetupNames.TasksValue));++ // Start menu, PATH (REG_EXPAND_SZ), no desktop shortcut by default.+ Assert.True(File.Exists(Path.Combine(bench.Paths.CommonStartMenu, "Filee.lnk")));+ Assert.False(File.Exists(Path.Combine(bench.Paths.CommonDesktop, "Filee.lnk")));+ var path = registry.Get(Hive.LocalMachine, SetupNames.MachineEnvironmentKey, "Path")!;+ Assert.True(path.Expandable);+ Assert.True(PathVariable.Contains(path.Text, Path.Combine(folder, "cli")));+ Assert.Contains("broadcast", bench.System.Calls);++ // Filee starts with the choices; it applies them for the signed-in user.+ Assert.Equal(Path.Combine(folder, "Filee.exe"), result.Launch!.Executable);+ Assert.Equal("--install-engines=pandoc --start-with-windows=on --context-menu=on", result.Launch.Arguments);+ }++ [Fact]+ public void The_windows_11_menu_is_registered_when_ticked()+ {+ using var bench = new SetupBench();+ bench.System.ExplorerMenuSupported = true;+ Assert.True(bench.Install().Succeeded);+ Assert.Contains($"register-menu {bench.InstallFolder} True", bench.System.Calls);+ }++ [Fact]+ public void A_fresh_install_without_the_top_menu_removes_an_old_registration()+ {+ using var bench = new SetupBench();+ bench.System.ExplorerMenuSupported = true;+ bench.System.MenuRegistered = true;+ Assert.True(bench.Install(bench.Choices(SetupTasks.Defaults with { ModernMenu = false })).Succeeded);+ Assert.Contains("unregister-menu", bench.System.Calls);+ Assert.DoesNotContain(bench.System.Calls, c => c.StartsWith("register-menu", StringComparison.Ordinal));+ }++ [Fact]+ public void A_failed_menu_registration_is_a_warning_not_a_failure()+ {+ using var bench = new SetupBench();+ bench.System.ExplorerMenuSupported = true;+ bench.System.RegisterError = "0x80073CF3 the package failed update";+ var result = bench.Install();+ Assert.True(result.Succeeded);+ Assert.Equal("0x80073CF3 the package failed update", Assert.IsType<ExplorerMenuWarning>(Assert.Single(result.Warnings)).Error);+ }++ [Fact]+ public void Updating_over_filee_1_x_takes_the_inno_setup_installation_over()+ {+ using var bench = new SetupBench();+ var folder = bench.InstallFolder;+ // Filee 1.12.0 as Inno Setup installed it: its files, unins000.*, the key with Inno's values, its PATH entry,+ // the desktop shortcut and the registered top menu.+ var temp = bench.Temp;+ foreach (var file in new[] { "Filee.exe", "Filee.dll", "OldOnly.dll", @"cli\filee.cmd", @"runtimes\win-x64\native\old.dll", "unins000.exe", "unins000.dat", "unins000.msg" })+ temp.Write(Path.Combine(Path.GetRelativePath(temp.Path, folder), file), "1.12");+ var registry = bench.Registry;+ registry.SetString(Hive.LocalMachine, Key, "Inno Setup: Setup Version", "7.1.0");+ registry.SetString(Hive.LocalMachine, Key, "Inno Setup: App Path", folder);+ registry.SetString(Hive.LocalMachine, Key, "InstallLocation", folder + "\\");+ registry.SetString(Hive.LocalMachine, Key, "Inno Setup: Selected Tasks", "cli,desktopicon");+ registry.SetString(Hive.LocalMachine, Key, "Inno Setup: Language", "ko");+ registry.SetString(Hive.LocalMachine, Key, "DisplayVersion", "1.12.0");+ registry.SetString(Hive.LocalMachine, Key, "UninstallString", $"\"{folder}\\unins000.exe\"");+ registry.SetString(Hive.LocalMachine, SetupNames.MachineEnvironmentKey, "Path", @"%SystemRoot%\system32;" + folder + @"\cli", expandable: true);+ temp.Write(Path.Combine(Path.GetRelativePath(temp.Path, bench.Paths.CommonDesktop), "Filee.lnk"), "old shortcut");+ bench.System.ExplorerMenuSupported = true;+ bench.System.MenuRegistered = true;+ bench.System.Running.Add(new RunningProgram(4242, Path.Combine(folder, "filee-cli.exe")));++ var previous = PreviousInstall.Find(registry, InstallScope.Machine)!;+ Assert.True(previous.ByInno);+ Assert.Equal("1.12.0", previous.Version);+ Assert.Equal("ko", previous.Language);+ var current = previous.CurrentTasks(registry, bench.System, bench.Paths);+ Assert.True(current.Cli);+ Assert.True(current.DesktopIcon);+ Assert.True(current.ModernMenu);++ var result = bench.Install(bench.Choices(current) with { Engines = [] }, previous);+ Assert.True(result.Succeeded, result.Error?.ToString());++ // Filee was asked to quit, what still ran from the folder was ended.+ Assert.Contains("run Filee.exe --quit", bench.System.Calls);+ Assert.Contains("kill 4242", bench.System.Calls);+ // Inno's uninstaller and the files 2.0 doesn't have are gone; the new files are in.+ foreach (var gone in new[] { "unins000.exe", "unins000.dat", "unins000.msg", "OldOnly.dll", @"runtimes\win-x64\native\old.dll" })+ Assert.False(File.Exists(Path.Combine(folder, gone)), gone);+ Assert.False(Directory.Exists(Path.Combine(folder, "runtimes")));+ Assert.Equal("Filee 2", File.ReadAllText(Path.Combine(folder, "Filee.exe")));+ Assert.True(File.Exists(Path.Combine(folder, "uninstall.exe")));+ // One uninstall entry, now ours: no "Inno Setup: …" values left.+ Assert.DoesNotContain(registry.ValueNames(Hive.LocalMachine, Key), n => n.StartsWith("Inno Setup", StringComparison.Ordinal));+ Assert.Equal("2.0.0", registry.Get(Hive.LocalMachine, Key, "DisplayVersion")?.Text);+ Assert.Equal($"\"{folder}\\uninstall.exe\"", registry.Get(Hive.LocalMachine, Key, "UninstallString")?.Text);+ // The user's choices stay: PATH once, the desktop shortcut, the top menu refreshed in place.+ var path = registry.Get(Hive.LocalMachine, SetupNames.MachineEnvironmentKey, "Path")!.Text!;+ Assert.Equal(@"%SystemRoot%\system32;" + folder + @"\cli", path);+ Assert.True(File.Exists(Path.Combine(bench.Paths.CommonDesktop, "Filee.lnk")));+ Assert.Contains($"register-menu {folder} False", bench.System.Calls);+ // Back to the tray, as before the update.+ Assert.Equal("--background", result.Launch!.Arguments);+ }++ [Fact]+ public void Updating_our_own_install_replaces_exactly_its_files()+ {+ using var bench = new SetupBench(version: "2.0.0", app: (temp, _) => temp.Write(@"app\Removed.dll", "only in 2.0.0"));+ Assert.True(bench.Install().Succeeded);+ var folder = bench.InstallFolder;+ // Something of the user's in the folder stays.+ File.WriteAllText(Path.Combine(folder, "notes.txt"), "mine");+ File.Delete(Path.Combine(bench.AppFolder, "Removed.dll"));+ File.WriteAllText(Path.Combine(bench.AppFolder, "Filee.exe"), "Filee 2.1");+ bench.MakeSetup("2.1.0");++ var previous = PreviousInstall.Find(bench.Registry, InstallScope.Machine)!;+ Assert.False(previous.ByInno);+ Assert.NotNull(previous.Record);+ var result = bench.Install(bench.Choices(previous.CurrentTasks(bench.Registry, bench.System, bench.Paths)) with { Engines = [] }, previous);+ Assert.True(result.Succeeded, result.Error?.ToString());+ Assert.False(File.Exists(Path.Combine(folder, "Removed.dll")));+ Assert.True(File.Exists(Path.Combine(folder, "notes.txt")));+ Assert.Equal("Filee 2.1", File.ReadAllText(Path.Combine(folder, "Filee.exe")));+ Assert.Equal("2.1.0", InstallRecord.Read(folder)!.Version);+ Assert.Equal("2.1.0", bench.Registry.Get(Hive.LocalMachine, Key, "DisplayVersion")?.Text);+ }++ [Fact]+ public void Unticking_on_an_update_removes_the_desktop_icon_and_the_path_entry()+ {+ using var bench = new SetupBench();+ Assert.True(bench.Install(bench.Choices(SetupTasks.Defaults with { DesktopIcon = true })).Succeeded);+ var desktop = Path.Combine(bench.Paths.CommonDesktop, "Filee.lnk");+ Assert.True(File.Exists(desktop));+ var previous = PreviousInstall.Find(bench.Registry, InstallScope.Machine)!;+ var tasks = previous.CurrentTasks(bench.Registry, bench.System, bench.Paths) with { DesktopIcon = false, Cli = false };+ Assert.True(bench.Install(bench.Choices(tasks), previous).Succeeded);+ Assert.False(File.Exists(desktop));+ Assert.False(PathVariable.IsOnPath(bench.Registry, InstallScope.Machine, Path.Combine(bench.InstallFolder, "cli")));+ }++ [Fact]+ public void A_failure_halfway_puts_the_previous_version_back()+ {+ using var bench = new SetupBench();+ Assert.True(bench.Install().Succeeded);+ var folder = bench.InstallFolder;+ var before = Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories)+ .ToDictionary(f => f, File.ReadAllText);+ var entryBefore = bench.Registry.ValueNames(Hive.LocalMachine, Key)+ .ToDictionary(n => n, n => bench.Registry.Get(Hive.LocalMachine, Key, n)!.Value);+ File.WriteAllText(Path.Combine(bench.AppFolder, "Filee.exe"), "Filee 3");+ bench.MakeSetup("3.0.0");+ File.Delete(Path.Combine(bench.Paths.CommonStartMenu, "Filee.lnk"));++ // The Start menu shortcut can't be written: everything after the file swap fails.+ bench.System.OnCreateShortcut = _ => throw new IOException("Access denied (test)");+ var previous = PreviousInstall.Find(bench.Registry, InstallScope.Machine)!;+ var result = bench.Install(previous: previous);+ Assert.False(result.Succeeded);+ Assert.True(result.RolledBack);+ Assert.Null(result.Launch);++ var after = Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).ToDictionary(f => f, File.ReadAllText);+ Assert.Equal(before, after);+ Assert.Equal("2.0.0", bench.Registry.Get(Hive.LocalMachine, Key, "DisplayVersion")?.Text);+ Assert.Equal(entryBefore.Keys.Order(), bench.Registry.ValueNames(Hive.LocalMachine, Key).Order());+ }++ [Fact]+ public void A_damaged_payload_changes_nothing()+ {+ using var bench = new SetupBench();+ long offset;+ using (var payload = Filee.Setup.Payload.SetupPayload.Open(bench.SetupExe)!)+ offset = payload.Offset;+ var bytes = File.ReadAllBytes(bench.SetupExe);+ bytes[offset + 3] ^= 0x55;+ File.WriteAllBytes(bench.SetupExe, bytes);++ var result = bench.Install();+ Assert.False(result.Succeeded);+ Assert.IsType<InvalidDataException>(result.Error);+ Assert.False(result.RolledBack);+ Assert.False(Directory.Exists(bench.InstallFolder));+ Assert.False(bench.Registry.KeyExists(Hive.LocalMachine, Key));+ Assert.Empty(bench.System.Calls);+ }++ [Fact]+ public void No_icons_and_portable()+ {+ using var bench = new SetupBench();+ Assert.True(bench.Install(bench.Choices() with { NoIcons = true }).Succeeded);+ Assert.False(File.Exists(Path.Combine(bench.Paths.CommonStartMenu, "Filee.lnk")));++ using var portable = new SetupBench();+ var folder = portable.Temp.Sub("Portable Filee");+ var result = portable.Install(portable.Choices() with { Folder = folder, Portable = true }, previous: null);+ Assert.True(result.Succeeded);+ Assert.Null(result.Launch);+ Assert.True(File.Exists(Path.Combine(folder, "Filee.exe")));+ // No uninstaller: the app counts itself as portable (UpdateService.IsInstalled).+ Assert.False(File.Exists(Path.Combine(folder, "uninstall.exe")));+ Assert.False(portable.Registry.KeyExists(Hive.LocalMachine, Key));+ Assert.Empty(portable.System.Calls);+ }++ [Fact]+ public void A_per_user_install_stays_in_the_users_part()+ {+ using var bench = new SetupBench();+ var folder = bench.Paths.DefaultInstallFolder(InstallScope.User);+ var result = bench.Install(bench.Choices() with { Folder = folder, Scope = InstallScope.User }, previous: null);+ Assert.True(result.Succeeded);+ Assert.True(bench.Registry.KeyExists(Hive.CurrentUser, Key));+ Assert.False(bench.Registry.KeyExists(Hive.LocalMachine, Key));+ Assert.True(PathVariable.IsOnPath(bench.Registry, InstallScope.User, Path.Combine(folder, "cli")));+ Assert.True(File.Exists(Path.Combine(bench.Paths.UserStartMenu, "Filee.lnk")));+ Assert.Equal(InstallScope.User, InstallRecord.Read(folder)!.Scope);+ Assert.NotNull(PreviousInstall.Find(bench.Registry, InstallScope.User));+ }++ [Fact]+ public void Filee_1_1_from_velopack_is_removed_but_its_engines_stay()+ {+ using var bench = new SetupBench();+ var root = VelopackInstall.Root(bench.Paths);+ bench.Temp.Write(Path.Combine(Path.GetRelativePath(bench.Temp.Path, root), "Update.exe"));+ bench.Temp.Write(Path.Combine(Path.GetRelativePath(bench.Temp.Path, root), @"current\Filee.exe"));+ bench.Temp.Write(Path.Combine(Path.GetRelativePath(bench.Temp.Path, root), @"packages\Filee-1.1.0-full.nupkg"));+ var engine = bench.Temp.Write(Path.Combine(Path.GetRelativePath(bench.Temp.Path, root), @"engines\pandoc\.filee-component"));+ bench.Registry.SetString(Hive.CurrentUser, SetupNames.VelopackUninstallKey, "DisplayName", "Filee");+ Assert.True(VelopackInstall.Exists(bench.Paths));++ Assert.True(bench.Install().Succeeded);+ Assert.False(File.Exists(Path.Combine(root, "Update.exe")));+ Assert.False(Directory.Exists(Path.Combine(root, "current")));+ Assert.False(Directory.Exists(Path.Combine(root, "packages")));+ Assert.True(File.Exists(engine));+ Assert.False(bench.Registry.KeyExists(Hive.CurrentUser, SetupNames.VelopackUninstallKey));+ }++ [Fact]+ public void What_setup_hands_to_filee_is_what_filee_reads()+ {+ var fresh = new InstallChoices(@"C:\Program Files\Filee", InstallScope.Machine, SetupTasks.Defaults with { Startup = false },+ ["pandoc", "ffmpeg"], "ko", LanguagePicked: true);+ var options = CommandLine.Parse(Installer.LaunchArguments(fresh, update: false).Split(' '));+ Assert.Equal(["pandoc", "ffmpeg"], options.InstallEngines);+ Assert.False(options.StartWithWindows);+ Assert.True(options.ContextMenu);+ Assert.Equal("ko", options.Language);++ // Setup's language only goes to Filee when the user picked it; else Filee keeps following Windows.+ Assert.Null(CommandLine.Parse(Installer.LaunchArguments(fresh with { LanguagePicked = false }, update: false).Split(' ')).Language);+ // Nothing picked is an answer too: Filee then doesn't ask on first run.+ Assert.Empty(CommandLine.Parse(Installer.LaunchArguments(fresh with { Engines = [] }, update: false).Split(' ')).InstallEngines!);+ Assert.True(CommandLine.Parse(Installer.LaunchArguments(fresh, update: true).Split(' ')).Background);+ }+}diff --git a/tests/Filee.Setup.Tests/PayloadTests.cs b/tests/Filee.Setup.Tests/PayloadTests.csnew file mode 100644index 00000000..8d9b9864--- /dev/null+++ b/tests/Filee.Setup.Tests/PayloadTests.cs@@ -0,0 +1,190 @@+// The payload appended to Setup.exe: written, found, verified and unpacked; damage and tricks are refused before+// anything is installed.++using System.Buffers.Binary;+using Filee.Setup.Payload;++namespace Filee.Setup.Tests;++public class PayloadTests+{+ [Fact]+ public void The_app_comes_back_byte_for_byte()+ {+ using var bench = new SetupBench(app: (temp, _) => temp.Write(@"app\data\big.bin", new string('z', 3_000_000)));+ using var payload = SetupPayload.Open(bench.SetupExe)!;+ Assert.Equal("2.0.0", payload.Manifest.Version);+ Assert.Contains(payload.Manifest.Files, f => f.Path == "Filee.exe");+ Assert.Contains(payload.Manifest.Files, f => f.Path == @"engines\rhwp\rhwp.exe");+ Assert.Equal("pandoc", Assert.Single(payload.Manifest.Engines).Id);+ Assert.Equal(".filee-component", payload.Manifest.EngineMarker);++ var progress = new List<double>();+ payload.Verify(new SyncProgress(progress.Add), TestContext.Current.CancellationToken);+ Assert.Equal(1, progress[^1], 3);++ var target = bench.Temp.Sub("out");+ long written = 0;+ payload.ExtractTo(target, new Installation.SyncProgress<long>(b => written = b), TestContext.Current.CancellationToken);+ Assert.Equal(payload.Manifest.TotalSize, written);+ foreach (var file in Directory.EnumerateFiles(bench.AppFolder, "*", SearchOption.AllDirectories))+ {+ var relative = Path.GetRelativePath(bench.AppFolder, file);+ Assert.Equal(File.ReadAllBytes(file), File.ReadAllBytes(Path.Combine(target, relative)));+ }+ // The same files compress well together: the payload is far smaller than the app.+ Assert.True(payload.CompressedLength < payload.Manifest.TotalSize / 10);+ }++ [Fact]+ public void The_uninstaller_is_the_program_without_its_payload()+ {+ using var bench = new SetupBench();+ using var payload = SetupPayload.Open(bench.SetupExe)!;+ var uninstaller = bench.Temp.Sub("uninstall.exe");+ payload.CopyProgramTo(uninstaller);+ Assert.Equal(File.ReadAllBytes(bench.Temp.Sub("program.exe")), File.ReadAllBytes(uninstaller));+ Assert.Null(SetupPayload.Open(uninstaller));+ }++ [Fact]+ public void A_program_without_payload_has_none()+ {+ using var temp = new TempFolder();+ Assert.Null(SetupPayload.Open(temp.Write("plain.exe", "MZ nothing appended")));+ Assert.Null(SetupPayload.Open(temp.Write("empty.exe", "")));+ }++ [Fact]+ public void A_damaged_payload_is_found_before_anything_is_unpacked()+ {+ using var bench = new SetupBench();+ long offset;+ using (var payload = SetupPayload.Open(bench.SetupExe)!)+ offset = payload.Offset;+ var bytes = File.ReadAllBytes(bench.SetupExe);+ bytes[offset + 10] ^= 0xFF;+ File.WriteAllBytes(bench.SetupExe, bytes);+ using var damaged = SetupPayload.Open(bench.SetupExe)!;+ Assert.Throws<InvalidDataException>(() => damaged.Verify(cancellation: TestContext.Current.CancellationToken));+ }++ [Fact]+ public void A_damaged_manifest_or_trailer_is_refused()+ {+ using var bench = new SetupBench();+ var bytes = File.ReadAllBytes(bench.SetupExe);+ var manifestLength = BinaryPrimitives.ReadInt64LittleEndian(bytes.AsSpan(bytes.Length - SetupPayload.TrailerLength + 32));+ var changed = (byte[])bytes.Clone();+ changed[bytes.Length - SetupPayload.TrailerLength - manifestLength + 5] ^= 0x01;+ File.WriteAllBytes(bench.SetupExe, changed);+ Assert.Throws<InvalidDataException>(() => SetupPayload.Open(bench.SetupExe));++ changed = (byte[])bytes.Clone();+ BinaryPrimitives.WriteInt64LittleEndian(changed.AsSpan(bytes.Length - SetupPayload.TrailerLength + 16), 7);+ File.WriteAllBytes(bench.SetupExe, changed);+ Assert.Throws<InvalidDataException>(() => SetupPayload.Open(bench.SetupExe));+ }++ [Fact]+ public void A_file_that_does_not_match_its_checksum_stops_unpacking()+ {+ using var bench = new SetupBench();+ // Same layout, but the manifest claims another hash for one file (and is re-sealed): Verify passes, ExtractTo must not.+ var bytes = File.ReadAllBytes(bench.SetupExe);+ var trailer = bytes.AsSpan(bytes.Length - SetupPayload.TrailerLength);+ var manifestLength = (int)BinaryPrimitives.ReadInt64LittleEndian(trailer[24..].Slice(8));+ var manifestStart = bytes.Length - SetupPayload.TrailerLength - manifestLength;+ var json = System.Text.Encoding.UTF8.GetString(bytes, manifestStart, manifestLength);+ var manifest = PayloadManifest.FromJson(bytes.AsSpan(manifestStart, manifestLength));+ var victim = manifest.Files.First(f => f.Path == "Filee.exe");+ var forged = json.Replace(victim.Sha256, new string('0', 64), StringComparison.Ordinal);+ Assert.Equal(json.Length, forged.Length);+ var forgedBytes = System.Text.Encoding.UTF8.GetBytes(forged);+ forgedBytes.CopyTo(bytes, manifestStart);+ System.Security.Cryptography.SHA256.HashData(forgedBytes).CopyTo(bytes, bytes.Length - 32);+ File.WriteAllBytes(bench.SetupExe, bytes);++ using var payload = SetupPayload.Open(bench.SetupExe)!;+ payload.Verify(cancellation: TestContext.Current.CancellationToken);+ var error = Assert.Throws<InvalidDataException>(() => payload.ExtractTo(bench.Temp.Sub("out"), cancellation: TestContext.Current.CancellationToken));+ Assert.Contains("Filee.exe", error.Message);+ }++ [Theory]+ [InlineData(@"..\evil.dll")]+ [InlineData(@"C:\Windows\evil.dll")]+ [InlineData(@"\evil.dll")]+ [InlineData(@"a\..\..\evil.dll")]+ [InlineData("file.txt:stream")]+ [InlineData("")]+ public void Paths_must_stay_inside_the_install_folder(string path) =>+ Assert.Throws<InvalidDataException>(() => PayloadManifest.CheckPath(path));++ [Fact]+ public void The_payload_is_found_in_front_of_an_authenticode_signature()+ {+ using var temp = new TempFolder();+ // A minimal PE32+ header whose certificate table (security directory) is the last 512 bytes of the file, as+ // signtool leaves a signed Setup: the payload sits right before it.+ var app = temp.Sub("app");+ temp.Write(@"app\Filee.exe", "Filee");+ var program = temp.Sub("program.exe");+ File.WriteAllBytes(program, MinimalPe(0, 0));+ var unsigned = temp.Sub("unsigned.exe");+ SetupPayload.Write(program, app, unsigned, "2.0.0", [], "", quality: 1);++ var body = File.ReadAllBytes(unsigned);+ var signed = new byte[body.Length + 512];+ body.CopyTo(signed, 0);+ var pe = BinaryPrimitives.ReadInt32LittleEndian(signed.AsSpan(0x3C));+ var security = pe + 4 + 20 + 112 + 4 * 8;+ BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(security), (uint)body.Length);+ BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(security + 4), 512);+ File.WriteAllBytes(temp.Sub("signed.exe"), signed);++ using var payload = SetupPayload.Open(temp.Sub("signed.exe"))!;+ payload.Verify(cancellation: TestContext.Current.CancellationToken);+ Assert.Equal("Filee.exe", Assert.Single(payload.Manifest.Files).Path);+ }++ [Fact]+ public void A_signed_program_cannot_get_a_payload()+ {+ // Signing has to come last: a payload behind the signature would not be covered by it.+ using var temp = new TempFolder();+ temp.Write(@"app\Filee.exe", "Filee");+ var program = temp.Sub("program.exe");+ var bytes = MinimalPe(0, 0);+ var pe = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(0x3C));+ var withCertificates = new byte[bytes.Length + 64];+ bytes.CopyTo(withCertificates, 0);+ BinaryPrimitives.WriteUInt32LittleEndian(withCertificates.AsSpan(pe + 4 + 20 + 112 + 32), (uint)bytes.Length);+ BinaryPrimitives.WriteUInt32LittleEndian(withCertificates.AsSpan(pe + 4 + 20 + 112 + 36), 64);+ File.WriteAllBytes(program, withCertificates);+ Assert.Throws<InvalidOperationException>(() => SetupPayload.Write(program, temp.Sub("app"), temp.Sub("out.exe"), "2.0.0", [], ""));+ }++ /// <summary>DOS header + PE32+ headers without sections (enough for the overlay and import readers).</summary>+ internal static byte[] MinimalPe(uint importRva, ushort sections, int size = 0x400)+ {+ var bytes = new byte[size];+ bytes[0] = (byte)'M';+ bytes[1] = (byte)'Z';+ BinaryPrimitives.WriteInt32LittleEndian(bytes.AsSpan(0x3C), 0x40);+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(0x40), 0x00004550);+ BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(0x44), 0x8664);+ BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(0x46), sections);+ BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(0x54), 240);+ var optional = 0x58;+ BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(optional), 0x20B);+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(optional + 108), 16);+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(optional + 112 + 8), importRva);+ return bytes;+ }++ private sealed class SyncProgress(Action<double> report) : IProgress<double>+ {+ public void Report(double value) => report(value);+ }+}diff --git a/tests/Filee.Setup.Tests/RuntimeCheckTests.cs b/tests/Filee.Setup.Tests/RuntimeCheckTests.csnew file mode 100644index 00000000..24a5940f--- /dev/null+++ b/tests/Filee.Setup.Tests/RuntimeCheckTests.cs@@ -0,0 +1,75 @@+using System.Buffers.Binary;+using System.Text;+using Filee.Setup.Installation;++namespace Filee.Setup.Tests;++public class RuntimeCheckTests+{+ [Fact]+ public void Imports_of_a_windows_program_are_read()+ {+ // Windows' own programs import system DLLs (some through API sets).+ var imports = RuntimeCheck.ImportedDlls(Path.Combine(Environment.SystemDirectory, "cmd.exe"));+ Assert.NotEmpty(imports);+ Assert.All(imports, d => Assert.EndsWith(".dll", d, StringComparison.OrdinalIgnoreCase));+ Assert.Empty(RuntimeCheck.ImportedDlls(typeof(RuntimeCheckTests).Assembly.Location.Replace(".dll", ".deps.json", StringComparison.Ordinal)));+ }++ [Theory]+ [InlineData("vcruntime140.dll", true)]+ [InlineData("VCRUNTIME140_1.dll", true)]+ [InlineData("msvcp140.dll", true)]+ [InlineData("msvcp140_codecvt_ids.dll", true)]+ [InlineData("concrt140.dll", true)]+ [InlineData("vcomp140.dll", true)]+ [InlineData("ucrtbase.dll", false)]+ [InlineData("api-ms-win-crt-runtime-l1-1-0.dll", false)]+ [InlineData("kernel32.dll", false)]+ public void Visual_cpp_runtime_dlls_are_recognised(string dll, bool runtime) => Assert.Equal(runtime, RuntimeCheck.IsVcRuntime(dll));++ [Fact]+ public void A_bundled_engine_without_its_runtime_is_reported()+ {+ using var temp = new TempFolder();+ var app = temp.Sub("app");+ var system = temp.Sub("system32");+ Directory.CreateDirectory(system);+ Directory.CreateDirectory(Path.Combine(app, "engines", "rhwp"));+ File.WriteAllBytes(Path.Combine(app, "engines", "rhwp", "rhwp.exe"), PeImporting("VCRUNTIME140.dll", "KERNEL32.dll"));++ var missing = Assert.Single(RuntimeCheck.FindMissing(app, system));+ Assert.Equal(@"engines\rhwp\rhwp.exe", missing.Program);+ Assert.Equal("vcruntime140.dll", missing.Dll);++ // App-local copies next to it (what fix/rhwp-vc-runtime ships) or the Redistributable in System32 both do.+ File.WriteAllText(Path.Combine(app, "engines", "rhwp", "vcruntime140.dll"), "");+ Assert.Empty(RuntimeCheck.FindMissing(app, system));+ File.Delete(Path.Combine(app, "engines", "rhwp", "vcruntime140.dll"));+ File.WriteAllText(Path.Combine(system, "VCRUNTIME140.dll"), "");+ Assert.Empty(RuntimeCheck.FindMissing(app, system));+ }++ /// <summary>A PE32+ file with one section holding an import table that names <paramref name="dlls"/>.</summary>+ private static byte[] PeImporting(params string[] dlls)+ {+ var bytes = PayloadTests.MinimalPe(importRva: 0x1000, sections: 1, size: 0x600);+ // Section header right after the optional header (0x58 + 240): ".idata", RVA 0x1000, raw data at 0x200.+ var section = 0x58 + 240;+ Encoding.ASCII.GetBytes(".idata").CopyTo(bytes, section);+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(section + 8), 0x400);+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(section + 12), 0x1000);+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(section + 16), 0x400);+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(section + 20), 0x200);+ // Import descriptors at RVA 0x1000 (file 0x200), names from RVA 0x1100 (file 0x300); a zero descriptor ends them.+ var nameRva = 0x1100;+ for (var i = 0; i < dlls.Length; i++)+ {+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(0x200 + i * 20), 0x1080);+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(0x200 + i * 20 + 12), (uint)nameRva);+ Encoding.ASCII.GetBytes(dlls[i]).CopyTo(bytes, 0x200 + (nameRva - 0x1000));+ nameRva += dlls[i].Length + 1;+ }+ return bytes;+ }+}diff --git a/tests/Filee.Setup.Tests/SetupOptionsTests.cs b/tests/Filee.Setup.Tests/SetupOptionsTests.csnew file mode 100644index 00000000..01f90516--- /dev/null+++ b/tests/Filee.Setup.Tests/SetupOptionsTests.cs@@ -0,0 +1,223 @@+// The command line callers already use: Filee 1.x's updater ("/SILENT /NORESTART"), winget's silent switches,+// build scripts and people who scripted the Inno Setup installer.++using Filee.Setup.Installation;++namespace Filee.Setup.Tests;++public class SetupOptionsTests+{+ [Fact]+ public void The_updater_of_filee_1_x_gets_the_progress_window_only()+ {+ // UpdateService.InstallerArguments in 1.x (and still in 2.0).+ var options = SetupOptions.Parse(["/SILENT", "/NORESTART"]);+ Assert.Equal(SetupUi.Silent, options.Ui);+ Assert.False(options.SuppressMessageBoxes);+ Assert.Contains("/NORESTART", options.Ignored);+ Assert.Empty(options.Unknown);+ Assert.True(options.IsSilent);+ }++ [Fact]+ public void Package_managers_get_no_window_at_all()+ {+ var options = SetupOptions.Parse(["/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/SP-"]);+ Assert.Equal(SetupUi.VerySilent, options.Ui);+ Assert.True(options.SuppressMessageBoxes);+ Assert.False(options.CanShowMessages);+ Assert.Equal(["/NORESTART", "/SP-"], options.Ignored);++ // /VERYSILENT wins whatever the order.+ Assert.Equal(SetupUi.VerySilent, SetupOptions.Parse(["/VERYSILENT", "/SILENT"]).Ui);+ Assert.Equal(SetupUi.VerySilent, SetupOptions.Parse(["/SILENT", "/VERYSILENT"]).Ui);+ Assert.Equal(SetupUi.Wizard, SetupOptions.Parse([]).Ui);+ }++ [Fact]+ public void Every_inno_setup_switch_is_understood()+ {+ var options = SetupOptions.Parse([+ "/silent", "/SuppressMsgBoxes", "/DIR=C:\\Tools\\Filee", "/LANG=zhcn", "/TASKS=cli,desktopicon",+ "/MERGETASKS=!startup", "/NOICONS", "/CURRENTUSER", "/LOG=C:\\logs\\setup.log", "/NOCLOSEAPPLICATIONS",+ "/NORESTART", "/SP-", "/NOCANCEL", "/RESTARTEXITCODE=3", "/CLOSEAPPLICATIONS", "/RESTARTAPPLICATIONS",+ "/NORESTARTAPPLICATIONS", "/NOFORCECLOSEAPPLICATIONS", "/LOGCLOSEAPPLICATIONS", "/COMPONENTS=a", "/TYPE=full",+ "/GROUP=Filee", "/NOGROUP", "/PASSWORD=x", "/LOADINF=a.inf", "/SAVEINF=b.inf",+ ]);+ Assert.Equal(SetupUi.Silent, options.Ui);+ Assert.True(options.SuppressMessageBoxes);+ Assert.Equal(@"C:\Tools\Filee", options.Directory);+ Assert.Equal("zhcn", options.Language);+ Assert.Equal("cli,desktopicon", options.Tasks);+ Assert.Equal("!startup", options.MergeTasks);+ Assert.True(options.NoIcons);+ Assert.Equal(InstallScope.User, options.Scope);+ Assert.Equal(@"C:\logs\setup.log", options.LogFile);+ // /CLOSEAPPLICATIONS came after /NOCLOSEAPPLICATIONS.+ Assert.True(options.ForceCloseApplications);+ Assert.Empty(options.Unknown);+ Assert.Equal(15, options.Ignored.Count);+ }++ [Fact]+ public void Scope_portable_and_logging()+ {+ Assert.Equal(InstallScope.Machine, SetupOptions.Parse([]).Scope);+ Assert.Equal(InstallScope.Machine, SetupOptions.Parse(["/CURRENTUSER", "/ALLUSERS"]).Scope);+ Assert.True(SetupOptions.Parse(["/PORTABLE=1"]).Portable);+ Assert.False(SetupOptions.Parse(["/PORTABLE=0"]).Portable);+ Assert.False(SetupOptions.Parse(["/NOCLOSEAPPLICATIONS"]).ForceCloseApplications);+ // Plain /LOG: Setup logs anyway, into %TEMP%.+ Assert.Null(SetupOptions.Parse(["/LOG"]).LogFile);+ }++ [Fact]+ public void Filee_switches_and_unknown_arguments()+ {+ var options = SetupOptions.Parse(["/NOLAUNCH", "/UNINSTALL", "/SANDBOX=D:\\scratch", "/LAUNCHFILE=C:\\t\\x.launch", "--weird", "/WHAT", "file.txt"]);+ Assert.True(options.NoLaunch);+ Assert.True(options.Uninstall);+ Assert.Equal(@"D:\scratch", options.Sandbox);+ Assert.Equal(@"C:\t\x.launch", options.LaunchFile);+ Assert.Equal(["--weird", "/WHAT", "file.txt"], options.Unknown);+ }++ [Theory]+ [InlineData("/DIR=\"C:\\Program Files\\Filee\"", @"C:\Program Files\Filee")]+ [InlineData("/DIR=C:\\Program Files\\Filee", @"C:\Program Files\Filee")]+ [InlineData("/dir= D:\\Apps\\Filee ", @"D:\Apps\Filee")]+ public void Folders_with_or_without_quotes(string arg, string folder) =>+ Assert.Equal(folder, SetupOptions.Parse([arg]).Directory);++ [Fact]+ public void Empty_values_are_not_taken()+ {+ var options = SetupOptions.Parse(["/DIR=", "/LANG=", "/SANDBOX="]);+ Assert.Null(options.Directory);+ Assert.Null(options.Language);+ Assert.Null(options.Sandbox);+ }++ [Theory]+ [InlineData("plain")]+ [InlineData("/DIR=C:\\Program Files\\Filee")]+ [InlineData("C:\\folder with space\\")]+ [InlineData("say \"hi\"")]+ [InlineData("back\\\\slashes\\\"quote")]+ [InlineData("")]+ public void Arguments_survive_being_passed_on(string arg)+ {+ // The elevated Setup gets the arguments again: Windows must split the joined line into the same ones.+ var line = SetupOptions.Join(["first", arg, "last"]);+ Assert.Equal(["first", arg, "last"], SplitLikeWindows(line));+ }++ /// <summary>CommandLineToArgvW's rules (what .NET does with a new process's command line).</summary>+ private static List<string> SplitLikeWindows(string line)+ {+ var args = new List<string>();+ var current = new System.Text.StringBuilder();+ var quoted = false;+ var started = false;+ for (var i = 0; i < line.Length; i++)+ {+ var c = line[i];+ if (c == '\\')+ {+ var backslashes = 0;+ while (i < line.Length && line[i] == '\\')+ {+ backslashes++;+ i++;+ }+ if (i < line.Length && line[i] == '"')+ {+ current.Append('\\', backslashes / 2);+ if (backslashes % 2 == 1)+ current.Append('"');+ else+ quoted = !quoted;+ }+ else+ {+ current.Append('\\', backslashes);+ i--;+ }+ started = true;+ }+ else if (c == '"')+ {+ quoted = !quoted;+ started = true;+ }+ else if (c == ' ' && !quoted)+ {+ if (started)+ args.Add(current.ToString());+ current.Clear();+ started = false;+ }+ else+ {+ current.Append(c);+ started = true;+ }+ }+ if (started)+ args.Add(current.ToString());+ return args;+ }+}++public class SetupTasksTests+{+ [Fact]+ public void A_fresh_install_ticks_everything_but_the_desktop_icon()+ {+ var tasks = SetupTasks.FromCommandLine(null, null);+ Assert.Equal(SetupTasks.Defaults, tasks);+ Assert.Equal(@"contextmenu,contextmenu\top,startup,cli", tasks.ToInnoString());+ }++ [Fact]+ public void Tasks_lists_exactly_the_ticked_ones()+ {+ Assert.Equal(new SetupTasks(false, false, false, true, true), SetupTasks.FromCommandLine("cli,desktopicon", null));+ // A parent alone doesn't tick its children; "*" does.+ Assert.Equal(new SetupTasks(true, false, false, false, false), SetupTasks.FromCommandLine("contextmenu", null));+ Assert.Equal(new SetupTasks(true, true, false, false, false), SetupTasks.FromCommandLine("*contextmenu", null));+ // A child ticks its parent.+ Assert.Equal(new SetupTasks(true, true, false, false, false), SetupTasks.FromCommandLine(@"contextmenu\top", null));+ Assert.Equal(new SetupTasks(false, false, false, false, false), SetupTasks.FromCommandLine("", null));+ }++ [Fact]+ public void Merge_tasks_change_the_defaults()+ {+ Assert.Equal(new SetupTasks(true, true, false, true, true), SetupTasks.FromCommandLine(null, "desktopicon,!startup"));+ // Unticking a parent unticks its children.+ Assert.Equal(new SetupTasks(false, false, true, true, false), SetupTasks.FromCommandLine(null, "!contextmenu"));+ Assert.Equal(new SetupTasks(true, false, true, true, false), SetupTasks.FromCommandLine(null, @"!contextmenu\top"));+ Assert.Equal(new SetupTasks(false, false, false, true, false), SetupTasks.FromCommandLine("cli", "!desktopicon"));+ }++ [Fact]+ public void Names_are_case_insensitive_and_unknown_ones_are_reported()+ {+ Assert.Equal(new SetupTasks(false, false, true, true, false), SetupTasks.FromCommandLine("STARTUP, Cli, engines", null));+ Assert.Equal(["engines", "foo"], SetupTasks.UnknownNames("STARTUP,engines,!foo"));+ }++ [Theory]+ [InlineData(@"contextmenu,contextmenu\top,startup,cli", true, true, true, true, false)]+ [InlineData("contextmenu,startup", true, false, true, false, false)]+ [InlineData("cli,desktopicon", false, false, false, true, true)]+ [InlineData("", false, false, false, false, false)]+ public void Inno_setup_registry_values_are_read(string value, bool menu, bool top, bool startup, bool cli, bool desktop)+ {+ // "Inno Setup: Selected Tasks" as Filee 1.x's installer wrote it.+ var tasks = SetupTasks.FromInnoString(value);+ Assert.Equal(new SetupTasks(menu, top, startup, cli, desktop), tasks);+ Assert.Equal(tasks, SetupTasks.FromInnoString(tasks.ToInnoString()));+ }+}diff --git a/tests/Filee.Setup.Tests/SetupTextsTests.cs b/tests/Filee.Setup.Tests/SetupTextsTests.csnew file mode 100644index 00000000..3b9b35cc--- /dev/null+++ b/tests/Filee.Setup.Tests/SetupTextsTests.cs@@ -0,0 +1,102 @@+// Setup speaks Filee's languages from the app's own translation files.++extern alias app;+using System.Text.Json;+using System.Text.RegularExpressions;+using Filee.Engines.Infrastructure;+using Filee.Setup.Platform;+using LocalizationService = app::Filee.App.Services.LocalizationService;++namespace Filee.Setup.Tests;++public partial class SetupTextsTests+{+ private static string Repository+ {+ get+ {+ var dir = AppContext.BaseDirectory;+ while (!File.Exists(Path.Combine(dir, "Filee.slnx")))+ dir = Path.GetDirectoryName(dir) ?? throw new InvalidOperationException("Repository root not found.");+ return dir;+ }+ }++ [Fact]+ public void Setup_offers_every_language_filee_has()+ {+ Assert.Equal(LocalizationService.Languages.Select(l => (l.Code, l.NativeName)), SetupTexts.Languages);+ // The names of languages that may come later are ready (a test in the app keeps its list).+ Assert.All(LocalizationService.Languages, l => Assert.Contains((l.Code, l.NativeName), SetupTexts.KnownLanguages));+ }++ [Theory]+ [InlineData("ko", "en-US", "ko")]+ [InlineData("zhcn", "en-US", "zh-CN")]+ [InlineData("ZH-cn", "en-US", "zh-CN")]+ [InlineData("auto", "ko-KR", "ko")]+ [InlineData(null, "zh-TW", "zh-CN")]+ [InlineData(null, "es-MX", "es")]+ [InlineData(null, "pl-PL", "pl")]+ [InlineData(null, "hi-IN", "hi")]+ [InlineData("xx", "de-DE", "en")]+ [InlineData("klingon", "pl-PL", "pl")]+ public void Languages_resolve_like_the_app_and_like_inno_setup(string? setting, string windows, string expected) =>+ Assert.Equal(expected, SetupTexts.Resolve(setting, () => windows));++ [Fact]+ public void Texts_fall_back_to_english_and_format()+ {+ var texts = new SetupTexts("ko");+ Assert.Equal("ko", texts.Language);+ Assert.NotEqual("installer.welcome.title", texts["installer.welcome.title"]);+ Assert.Contains("9.9.9", texts.Format("installer.welcome.fresh", "9.9.9"));+ Assert.Equal("no.such.key", texts["no.such.key"]);+ var changed = 0;+ texts.LanguageChanged += (_, _) => changed++;+ texts.SetLanguage("en");+ Assert.Equal(1, changed);+ Assert.Equal("Welcome to Filee", texts["installer.welcome.title"]);+ }++ [Fact]+ public void Every_key_setup_uses_exists_in_english()+ {+ var english = JsonSerializer.Deserialize<Dictionary<string, string>>(+ File.ReadAllText(Path.Combine(Repository, "src", "Filee.App", "Assets", "i18n", "en.json")))!;+ var source = Path.Combine(Repository, "src", "Filee.Setup");+ var used = Directory.EnumerateFiles(source, "*.axaml", SearchOption.AllDirectories)+ .SelectMany(f => DynamicResource().Matches(File.ReadAllText(f)).Select(m => m.Groups[1].Value))+ .Concat(Directory.EnumerateFiles(source, "*.cs", SearchOption.AllDirectories)+ .SelectMany(f => KeyLiteral().Matches(File.ReadAllText(f)).Select(m => m.Groups[1].Value)))+ .Where(k => k.Contains('.') && !k.EndsWith('.'))+ .Distinct()+ .ToList();+ Assert.Contains("installer.welcome.title", used);+ Assert.Contains("general.context_menu", used);+ Assert.DoesNotContain(used, k => !english.ContainsKey(k));+ // Engine names come from the app's own keys.+ Assert.All(EngineDownloads.Packages, p => Assert.True(english.ContainsKey($"engines.package.{p.Id}.name"), p.Id));+ }++ [Fact]+ public void Chinese_installer_texts_use_no_fullwidth_colon_or_semicolon()+ {+ var chinese = JsonSerializer.Deserialize<Dictionary<string, string>>(+ File.ReadAllText(Path.Combine(Repository, "src", "Filee.App", "Assets", "i18n", "zh-CN.json")))!;+ Assert.DoesNotContain(chinese, p => p.Key.StartsWith("installer.", StringComparison.Ordinal) && (p.Value.Contains(':') || p.Value.Contains(';')));+ }++ [Fact]+ public void Setup_looks_for_downloaded_engines_where_the_app_puts_them()+ {+ Assert.Equal(EngineEnvironment.DownloadRoot, SetupPaths.Real().EnginesFolder);+ Assert.Equal(Filee.Core.Settings.UserDataStore.DefaultDirectory, SetupPaths.Real().SettingsFolder);+ }++ [GeneratedRegex(@"\{DynamicResource ([\w.]+)\}")]+ private static partial Regex DynamicResource();++ [GeneratedRegex(@"""((?:installer|setup|engines|general|common)\.[\w.]+)""")]+ private static partial Regex KeyLiteral();+}diff --git a/tests/Filee.Setup.Tests/SetupWindowTests.cs b/tests/Filee.Setup.Tests/SetupWindowTests.csnew file mode 100644index 00000000..ce8060fb--- /dev/null+++ b/tests/Filee.Setup.Tests/SetupWindowTests.cs@@ -0,0 +1,281 @@+// Renders every page of Setup and the uninstaller headlessly (Skia) in Filee's languages, light and dark: catches XAML+// and binding errors, text that doesn't fit, and leaves screenshots in bin/.../screenshots for review.++using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Headless;+using Avalonia.Headless.XUnit;+using Avalonia.Input;+using Avalonia.Styling;+using Avalonia.Threading;+using Avalonia.VisualTree;+using Filee.Setup.Installation;+using Filee.Setup.Payload;+using Filee.Setup.ViewModels;+using Filee.Setup.Views;++namespace Filee.Setup.Tests;++public class SetupWindowTests+{+ public static TheoryData<string> Languages => new() { "en", "es", "ko", "zh-CN", "pl", "hi" };++ private sealed class FakeRunner : ISetupRunner+ {+ public InstallChoices? Installed { get; private set; }+ public bool? DeletedSettings { get; private set; }+ public InstallResult Result { get; set; } = new(new LaunchRequest(@"C:\Program Files\Filee\Filee.exe", "--background"), []);++ public InstallResult Install(InstallChoices choices, IProgress<SetupProgress> progress)+ {+ Installed = choices;+ progress.Report(new SetupProgress(SetupStep.Copying, 0.5));+ return Result;+ }++ public Exception? Uninstall(bool deleteSettings, IProgress<SetupProgress> progress)+ {+ DeletedSettings = deleteSettings;+ return null;+ }+ }++ private static readonly EngineOffer[] Offers =+ [+ new("libreoffice", ["libreoffice", "jre"], 520_000_000, 1_265_000_000, false),+ new("pandoc", ["pandoc"], 42_000_000, 236_000_000, true),+ new("ghostscript", ["ghostscript", "vcruntime"], 20_000_000, 31_000_000, false),+ new("ffmpeg", ["ffmpeg"], 99_000_000, 272_000_000, false),+ new("calibre", ["calibre"], 226_000_000, 663_000_000, false),+ ];++ private static (SetupViewModel Model, SetupTexts Texts, FakeRunner Runner) Model(string language, bool update = false, bool uninstall = false)+ {+ var texts = new SetupTexts(language);+ App.ApplyLook(Application.Current!, texts);+ var runner = new FakeRunner();+ var previous = update+ ? new PreviousInstall(@"C:\Program Files\Filee", "1.12.0", InstallScope.Machine, true, SetupTasks.Defaults, "en", null)+ : null;+ var choices = new InstallChoices(@"C:\Program Files\Filee", InstallScope.Machine, SetupTasks.Defaults, ["pandoc"], texts.Language);+ var engines = update || uninstall ? [] : Offers.Select(o => (o, o.Id == "ffmpeg")).ToList();+ var model = new SetupViewModel(texts, runner, "2.0.0", choices, previous, engines, modernMenuSupported: true,+ neededSpace: 420_000_000, uninstall: uninstall)+ {+ LogFile = @"C:\Users\me\AppData\Local\Temp\Filee-Setup-20261020-101500.log",+ SettingsFolder = @"C:\Users\me\AppData\Roaming\Filee",+ };+ return (model, texts, runner);+ }++ [AvaloniaTheory]+ [MemberData(nameof(Languages))]+ public async Task Every_install_page_renders_and_fits(string language)+ {+ var (model, _, runner) = Model(language);+ var window = Show(model);+ Check(window, $"setup-1-welcome-{language}.png");+ Assert.True(model.IsWelcome);++ await model.NextCommand.ExecuteAsync(null);+ Assert.True(model.IsOptions);+ Check(window, $"setup-2-options-{language}.png");++ await model.NextCommand.ExecuteAsync(null);+ Assert.True(model.IsEngines);+ // FFmpeg is installed already: shown, not offered.+ Assert.False(model.Engines.Single(e => e.Id == "ffmpeg").CanSelect);+ Check(window, $"setup-3-engines-{language}.png", mayScroll: true);++ model.Page = SetupPage.Progress;+ model.StatusText = new SetupTexts(language)["installer.status.copying"];+ model.Percent = 62;+ Check(window, $"setup-4-progress-{language}.png");++ runner.Result = new InstallResult(new LaunchRequest(@"C:\Program Files\Filee\Filee.exe", "--install-engines=pandoc"),+ [+ new ExplorerMenuWarning("Deployment failed with HRESULT: 0x80073CF3, Package failed updates, dependency or conflict validation."),+ new RuntimeWarning([new MissingRuntime(@"engines\rhwp\rhwp.exe", "vcruntime140.dll")]),+ ]);+ model.Page = SetupPage.Engines;+ await model.NextCommand.ExecuteAsync(null);+ Pump();+ Assert.True(model.IsDone);+ Check(window, $"setup-5-done-{language}.png", mayScroll: true);+ window.Close();+ }++ [AvaloniaFact]+ public async Task Update_and_failure_pages_render()+ {+ foreach (var language in new[] { "en", "ko", "hi" })+ {+ var (model, _, runner) = Model(language, update: true);+ var window = Show(model);+ Assert.False(model.HasEnginesPage);+ Check(window, $"setup-update-1-welcome-{language}.png");+ await model.NextCommand.ExecuteAsync(null);+ Check(window, $"setup-update-2-options-{language}.png");+ // An update offers only what it may change.+ Assert.Equal(model.NextText, new SetupTexts(language)["installer.update"]);++ runner.Result = new InstallResult(null, [], new SetupException("installer.error.space", "space", "C:\\", "420 MB", "12 MB"), RolledBack: false);+ await model.NextCommand.ExecuteAsync(null);+ Pump();+ Assert.True(model.IsFailed);+ Assert.Equal(4, model.ExitCode);+ Check(window, $"setup-update-3-failed-{language}.png");+ window.Close();+ }+ }++ [AvaloniaFact]+ public async Task Uninstall_pages_render_and_keep_the_settings_by_default()+ {+ foreach (var language in new[] { "en", "ko", "zh-CN", "pl" })+ {+ var (model, _, runner) = Model(language, uninstall: true);+ var window = Show(model);+ Assert.True(model.IsUninstallPage);+ Assert.False(model.DeleteSettings);+ Assert.Contains(@"C:\Users\me\AppData\Roaming\Filee", model.SettingsText);+ Check(window, $"uninstall-1-confirm-{language}.png");+ await model.NextCommand.ExecuteAsync(null);+ Pump();+ Assert.True(model.IsUninstalled);+ Assert.False(runner.DeletedSettings);+ Assert.Equal(0, model.ExitCode);+ Check(window, $"uninstall-2-done-{language}.png");+ window.Close();+ }+ }++ [AvaloniaFact]+ public void Dark_windows_follow_the_system()+ {+ var app = Application.Current!;+ try+ {+ app.RequestedThemeVariant = ThemeVariant.Dark;+ var (model, _, _) = Model("en");+ var window = Show(model);+ Check(window, "setup-dark-welcome-en.png");+ model.Page = SetupPage.Options;+ Check(window, "setup-dark-options-en.png");+ window.Close();+ var (uninstall, _, _) = Model("ko", uninstall: true);+ window = Show(uninstall);+ Check(window, "uninstall-dark-confirm-ko.png");+ window.Close();+ }+ finally+ {+ app.RequestedThemeVariant = ThemeVariant.Default;+ }+ }++ [AvaloniaFact]+ public void Picking_a_language_changes_every_text_and_is_handed_to_filee()+ {+ var (model, texts, _) = Model("en");+ var window = Show(model);+ model.SelectedLanguage = model.Languages.Single(l => l.Code == "ko");+ Pump();+ Assert.Equal("ko", texts.Language);+ Assert.Equal(texts["installer.next"], model.NextText);+ Assert.Equal(texts["installer.step.welcome"], model.Steps[0].Title);+ Assert.Contains("2.0.0", model.WelcomeText);+ var choices = model.Choices();+ Assert.Equal("ko", choices.Language);+ Assert.True(choices.LanguagePicked);+ Check(window, "setup-language-switched-ko.png");+ window.Close();+ }++ [AvaloniaFact]+ public void Choices_follow_the_checkboxes()+ {+ var (model, _, _) = Model("en");+ model.ContextMenu = false;+ Assert.False(model.ModernMenuEnabled);+ model.DesktopIcon = true;+ model.Engines.Single(e => e.Id == "pandoc").Selected = false;+ model.Engines.Single(e => e.Id == "calibre").Selected = true;+ var choices = model.Choices();+ Assert.False(choices.Tasks.ContextMenu);+ Assert.False(choices.Tasks.ModernMenu);+ Assert.True(choices.Tasks.DesktopIcon);+ Assert.Equal(["calibre"], choices.Engines);+ Assert.False(choices.LanguagePicked);+ }++ [AvaloniaFact]+ public void Keyboard_escape_cancels_and_enter_goes_on()+ {+ var (model, _, _) = Model("en");+ var window = Show(model);+ var closed = false;+ model.CloseRequested += (_, _) => closed = true;+ var next = window.FindControl<Button>("NextButton")!;+ Assert.True(next.IsDefault);+ next.Focus();+ window.KeyPressQwerty(PhysicalKey.Enter, RawInputModifiers.None);+ Pump();+ Assert.True(model.IsOptions);+ window.KeyPressQwerty(PhysicalKey.Escape, RawInputModifiers.None);+ Pump();+ Assert.True(closed);+ Assert.Equal(2, model.ExitCode);+ }++ [AvaloniaFact]+ public void Closing_the_window_before_installing_cancels()+ {+ var (model, _, _) = Model("en");+ model.LaunchFilee = true;+ model.WindowClosing();+ Assert.Equal(2, model.ExitCode);+ Assert.Null(model.Launch);+ }++ private static Window Show(SetupViewModel model)+ {+ var window = new SetupWindow(model, silent: false);+ window.Show();+ Pump();+ return window;+ }++ /// <summary>Saves a screenshot; the page must fit the window (no scrolling) and no button may cut its text.</summary>+ private static void Check(Window window, string name, bool mayScroll = false)+ {+ Pump();+ var scroller = window.GetVisualDescendants().OfType<ScrollViewer>().First();+ if (!mayScroll)+ Assert.True(scroller.Extent.Height <= scroller.Viewport.Height + 1, $"{name}: the page needs scrolling ({scroller.Extent.Height} > {scroller.Viewport.Height})");+ // Push buttons only: check boxes wrap their text.+ foreach (var button in window.GetVisualDescendants().OfType<Button>().Where(b => b is not ToggleButton && b.IsEffectivelyVisible))+ {+ button.Measure(Size.Infinity);+ var wanted = button.DesiredSize.Width - button.Margin.Left - button.Margin.Right;+ button.InvalidateMeasure();+ Assert.True(wanted <= button.Bounds.Width + 1, $"{name}: a button cuts its text ({button.Content})");+ }+ using var frame = window.CaptureRenderedFrame();+ Assert.NotNull(frame);+ var folder = Path.Combine(AppContext.BaseDirectory, "screenshots");+ Directory.CreateDirectory(folder);+ using var stream = File.Create(Path.Combine(folder, name));+ frame.Save(stream, new Avalonia.Media.Imaging.PngBitmapEncoderOptions());+ }++ private static void Pump()+ {+ for (var i = 0; i < 40; i++)+ {+ Dispatcher.UIThread.RunJobs();+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();+ }+ }+}diff --git a/tests/Filee.Setup.Tests/TestSupport.cs b/tests/Filee.Setup.Tests/TestSupport.csnew file mode 100644index 00000000..849d33ff--- /dev/null+++ b/tests/Filee.Setup.Tests/TestSupport.cs@@ -0,0 +1,171 @@+using Avalonia;+using Avalonia.Headless;+using Filee.Setup.Installation;+using Filee.Setup.Platform;++[assembly: AvaloniaTestApplication(typeof(Filee.Setup.Tests.TestAppBuilder))]+// One application for all tests (like Filee.App.Tests: reloading the embedded fonts per test crashed on Windows).+[assembly: AvaloniaTestIsolation(AvaloniaTestIsolationLevel.PerAssembly)]++namespace Filee.Setup.Tests;++/// <summary>Headless Avalonia with real Skia rendering, so the pages can be captured.</summary>+public static class TestAppBuilder+{+ public static AppBuilder BuildAvaloniaApp() =>+ AppBuilder.Configure<App>()+ .UseSkia()+ .UseHarfBuzz()+ .ConfigureFonts(fonts => fonts.AddFontCollection(new SetupFontCollection()))+ .UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false });+}++/// <summary>A scratch folder that goes away with the test.</summary>+public sealed class TempFolder : IDisposable+{+ public TempFolder()+ {+ Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "filee-setup-tests", Guid.NewGuid().ToString("N")[..10]);+ Directory.CreateDirectory(Path);+ }++ public string Path { get; }++ public string Sub(params string[] parts) => System.IO.Path.Combine([Path, .. parts]);++ /// <summary>Writes a file (and its folder) below the scratch folder; returns its full path.</summary>+ public string Write(string relative, string content = "x")+ {+ var path = Sub(relative);+ Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!);+ File.WriteAllText(path, content);+ return path;+ }++ public void Dispose()+ {+ try+ {+ Directory.Delete(Path, recursive: true);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ }+ }+}++/// <summary>Records what Setup asks Windows to do; never touches the PC.</summary>+public sealed class FakeSystem : ISetupSystem+{+ public bool ExplorerMenuSupported { get; set; }+ public bool MenuRegistered { get; set; }+ public string? RegisterError { get; set; }+ public List<string> Calls { get; } = [];+ public List<RunningProgram> Running { get; } = [];+ public Func<string, string, int> Run { get; set; } = (_, _) => 0;+ public Action<string>? OnCreateShortcut { get; set; }++ public bool IsExplorerMenuRegistered() => MenuRegistered;++ public string? RegisterExplorerMenu(string installFolder, bool removeFirst)+ {+ Calls.Add($"register-menu {installFolder} {removeFirst}");+ if (RegisterError is null)+ MenuRegistered = true;+ return RegisterError;+ }++ public void UnregisterExplorerMenu()+ {+ Calls.Add("unregister-menu");+ MenuRegistered = false;+ }++ public void CreateShortcut(string path, string target, string workingFolder, string description)+ {+ Calls.Add($"shortcut {path} -> {target}");+ OnCreateShortcut?.Invoke(path);+ Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!);+ File.WriteAllText(path, target);+ }++ public void BroadcastEnvironmentChange() => Calls.Add("broadcast");++ public int RunAndWait(string executable, string arguments, TimeSpan timeout)+ {+ Calls.Add($"run {System.IO.Path.GetFileName(executable)} {arguments}");+ return Run(executable, arguments);+ }++ public IReadOnlyList<RunningProgram> ProgramsIn(string folder) =>+ Running.Where(p => p.Path.StartsWith(folder, StringComparison.OrdinalIgnoreCase)).ToList();++ public void Kill(int processId)+ {+ Calls.Add($"kill {processId}");+ Running.RemoveAll(p => p.Id == processId);+ }++ public void DeleteAtRestart(string path) => Calls.Add($"delete-at-restart {path}");+}++/// <summary>A Setup.exe with a payload, a registry and a PC of its own, all in a scratch folder.</summary>+public sealed class SetupBench : IDisposable+{+ private readonly TempFolder _temp = new();++ public SetupBench(string version = "2.0.0", Action<TempFolder, string>? app = null)+ {+ Paths = SetupPaths.Sandbox(_temp.Sub("pc"));+ Directory.CreateDirectory(Paths.Temp);+ AppFolder = _temp.Sub("app");+ WriteApp(app);+ SetupExe = MakeSetup(version);+ Context = new SetupContext(Registry, System, Paths, Log);+ }++ public SetupPaths Paths { get; }+ public MemoryRegistry Registry { get; } = new();+ public FakeSystem System { get; } = new();+ public SetupLog Log { get; } = new(null);+ public SetupContext Context { get; }+ public string AppFolder { get; }+ public string SetupExe { get; private set; }+ public TempFolder Temp => _temp;++ public string InstallFolder => Paths.DefaultInstallFolder(InstallScope.Machine);++ /// <summary>The published app: Filee.exe, the "filee" command, an engine and a few more files.</summary>+ private void WriteApp(Action<TempFolder, string>? app)+ {+ _temp.Write(@"app\Filee.exe", "Filee 2");+ _temp.Write(@"app\Filee.dll", new string('a', 20_000));+ _temp.Write(@"app\cli\filee.cmd", "@\"%~dp0..\\filee-cli.exe\" %*");+ _temp.Write(@"app\filee-cli.exe", "cli");+ _temp.Write(@"app\engines\rhwp\rhwp.exe", "rhwp");+ _temp.Write(@"app\FileeExplorerMenu.dll", "menu");+ _temp.Write(@"app\FileeExplorerMenu.msix", "package");+ app?.Invoke(_temp, AppFolder);+ }++ /// <summary>Packs the app behind a stand-in Setup program (any bytes do: only the payload is read).</summary>+ public string MakeSetup(string version)+ {+ var program = _temp.Write("program.exe", "MZ stand-in for the Setup program " + new string('p', 3000));+ var output = _temp.Sub($"Filee-{version}-win-Setup.exe");+ Filee.Setup.Payload.SetupPayload.Write(program, AppFolder, output, version,+ [new Filee.Setup.Payload.EngineOffer("pandoc", ["pandoc"], 42_000_000, 236_000_000, true)], ".filee-component", quality: 5);+ return SetupExe = output;+ }++ public InstallChoices Choices(SetupTasks? tasks = null) =>+ new(InstallFolder, InstallScope.Machine, tasks ?? SetupTasks.Defaults, ["pandoc"], "en");++ public InstallResult Install(InstallChoices? choices = null, PreviousInstall? previous = null)+ {+ using var payload = Filee.Setup.Payload.SetupPayload.Open(SetupExe)!;+ return new Installer(Context, payload).Run(choices ?? Choices(), previous ?? PreviousInstall.Find(Registry, InstallScope.Machine));+ }++ public void Dispose() => _temp.Dispose();+}diff --git a/tests/Filee.Setup.Tests/UninstallerTests.cs b/tests/Filee.Setup.Tests/UninstallerTests.csnew file mode 100644index 00000000..73d63e14--- /dev/null+++ b/tests/Filee.Setup.Tests/UninstallerTests.cs@@ -0,0 +1,222 @@+using System.Runtime.InteropServices;+using Filee.Setup.Installation;+using Filee.Setup.Platform;++namespace Filee.Setup.Tests;++public class UninstallerTests+{+ private static (SetupBench Bench, InstallRecord Record) Installed(SetupTasks? tasks = null)+ {+ var bench = new SetupBench();+ Assert.True(bench.Install(bench.Choices(tasks)).Succeeded);+ return (bench, InstallRecord.Read(bench.InstallFolder)!);+ }++ [Fact]+ public void Uninstalling_removes_filee_and_keeps_the_settings()+ {+ var (bench, record) = Installed(SetupTasks.Defaults with { DesktopIcon = true });+ using var _ = bench;+ var settings = bench.Temp.Write(Path.Combine(Path.GetRelativePath(bench.Temp.Path, bench.Paths.SettingsFolder), "settings.json"), "{}");+ bench.Registry.SetString(Hive.LocalMachine, SetupNames.MachineEnvironmentKey, "Path",+ @"%SystemRoot%\system32;" + Path.Combine(bench.InstallFolder, "cli") + @";C:\Tools", expandable: true);+ bench.System.ExplorerMenuSupported = true;+ bench.System.MenuRegistered = true;++ var later = new Uninstaller(bench.Context).Run(bench.InstallFolder, record, deleteSettings: false, bench.Temp.Sub("trash"));++ Assert.Empty(later);+ // Filee cleaned up after itself for the user first (Explorer menu, startup entry, downloaded engines).+ Assert.Equal("run Filee.exe --uninstall-cleanup", bench.System.Calls.First(c => c.StartsWith("run ", StringComparison.Ordinal)));+ Assert.Contains("unregister-menu", bench.System.Calls);+ Assert.False(Directory.Exists(bench.InstallFolder));+ Assert.False(File.Exists(Path.Combine(bench.Paths.CommonStartMenu, "Filee.lnk")));+ Assert.False(File.Exists(Path.Combine(bench.Paths.CommonDesktop, "Filee.lnk")));+ Assert.False(bench.Registry.KeyExists(Hive.LocalMachine, SetupNames.UninstallKey));+ var path = bench.Registry.Get(Hive.LocalMachine, SetupNames.MachineEnvironmentKey, "Path")!;+ Assert.Equal(@"%SystemRoot%\system32;C:\Tools", path.Text);+ Assert.True(path.Expandable);+ Assert.True(File.Exists(settings));+ }++ [Fact]+ public void The_settings_go_when_the_user_asks()+ {+ var (bench, record) = Installed();+ using var _ = bench;+ bench.Temp.Write(Path.Combine(Path.GetRelativePath(bench.Temp.Path, bench.Paths.SettingsFolder), @"logs\filee.log"));+ new Uninstaller(bench.Context).Run(bench.InstallFolder, record, deleteSettings: true, bench.Temp.Sub("trash"));+ Assert.False(Directory.Exists(bench.Paths.SettingsFolder));+ // Only Filee's folder: %APPDATA% itself stays.+ Assert.True(Directory.Exists(bench.Paths.AppData));+ }++ [Fact]+ public void Files_that_are_not_filees_stay()+ {+ var (bench, record) = Installed();+ using var _ = bench;+ var mine = Path.Combine(bench.InstallFolder, "my notes.txt");+ File.WriteAllText(mine, "mine");+ new Uninstaller(bench.Context).Run(bench.InstallFolder, record, deleteSettings: false, bench.Temp.Sub("trash"));+ Assert.True(File.Exists(mine));+ Assert.Equal([mine], Directory.EnumerateFileSystemEntries(bench.InstallFolder, "*", SearchOption.AllDirectories));+ }++ [Fact]+ public void A_dll_explorer_has_loaded_is_moved_out_and_deleted_at_the_next_restart()+ {+ var (bench, record) = Installed();+ using var _ = bench;+ // Stand-in for FileeExplorerMenu.dll loaded by Explorer: a real DLL loaded into this process, which Windows+ // won't let anyone delete (but rename).+ var dll = Path.Combine(bench.InstallFolder, "FileeExplorerMenu.dll");+ File.Copy(Path.Combine(Environment.SystemDirectory, "msimg32.dll"), dll, overwrite: true);+ var handle = NativeLibrary.Load(dll);+ try+ {+ var trash = bench.Temp.Sub("trash");+ var later = new Uninstaller(bench.Context).Run(bench.InstallFolder, record, deleteSettings: false, trash);+ var moved = Assert.Single(later);+ Assert.StartsWith(trash, moved, StringComparison.OrdinalIgnoreCase);+ Assert.Contains($"delete-at-restart {moved}", bench.System.Calls);+ // So the install folder itself is gone now, not at the next restart.+ Assert.False(Directory.Exists(bench.InstallFolder));+ }+ finally+ {+ NativeLibrary.Free(handle);+ }+ }++ [Fact]+ public void Programs_left_running_are_ended_but_not_the_uninstaller_that_waits()+ {+ var (bench, record) = Installed();+ using var _ = bench;+ bench.System.Running.Add(new RunningProgram(11, Path.Combine(bench.InstallFolder, "filee-cli.exe")));+ bench.System.Running.Add(new RunningProgram(12, Path.Combine(bench.InstallFolder, "uninstall.exe")));+ new Uninstaller(bench.Context).Run(bench.InstallFolder, record, deleteSettings: false, bench.Temp.Sub("trash"));+ Assert.Contains("kill 11", bench.System.Calls);+ Assert.DoesNotContain("kill 12", bench.System.Calls);+ }++ [Fact]+ public void Install_record_round_trip_and_bad_records()+ {+ using var temp = new TempFolder();+ var record = new InstallRecord("2.0.0", InstallScope.User, ["Filee.exe", @"cli\filee.cmd"]);+ File.WriteAllBytes(InstallRecord.PathIn(temp.Path), record.ToJson());+ var read = InstallRecord.Read(temp.Path)!;+ Assert.Equal(record.Version, read.Version);+ Assert.Equal(record.Scope, read.Scope);+ Assert.Equal(record.Files, read.Files);++ // A record that points outside the folder is no record (the uninstaller then refuses).+ File.WriteAllText(InstallRecord.PathIn(temp.Path), """{"version":"2.0.0","scope":"machine","files":["..\\..\\Windows\\notepad.exe"]}""");+ Assert.Null(InstallRecord.Read(temp.Path));+ File.WriteAllText(InstallRecord.PathIn(temp.Path), "not json");+ Assert.Null(InstallRecord.Read(temp.Path));+ Assert.Null(InstallRecord.Read(temp.Sub("missing")));+ }+}++public class PreviousInstallTests+{+ [Fact]+ public void An_entry_without_filee_in_its_folder_is_no_installation()+ {+ using var temp = new TempFolder();+ var registry = new MemoryRegistry();+ registry.SetString(Hive.LocalMachine, SetupNames.UninstallKey, "InstallLocation", temp.Sub("gone") + "\\");+ Assert.Null(PreviousInstall.Find(registry, InstallScope.Machine));+ Assert.Null(PreviousInstall.Find(new MemoryRegistry(), InstallScope.Machine));+ }++ [Fact]+ public void Inno_setups_app_path_is_enough_and_the_scope_is_kept_apart()+ {+ using var temp = new TempFolder();+ temp.Write(@"Filee\Filee.exe");+ temp.Write(@"Filee\unins000.exe");+ var registry = new MemoryRegistry();+ registry.SetString(Hive.LocalMachine, SetupNames.UninstallKey, "Inno Setup: App Path", temp.Sub("Filee"));+ var previous = PreviousInstall.Find(registry, InstallScope.Machine)!;+ Assert.Equal(temp.Sub("Filee"), previous.Folder);+ Assert.True(previous.ByInno);+ Assert.Null(previous.RecordedTasks);+ Assert.Contains("unins000.exe", previous.OwnedFiles());+ Assert.Null(PreviousInstall.Find(registry, InstallScope.User));+ }++ [Fact]+ public void Current_tasks_come_from_what_is_registered_now()+ {+ using var temp = new TempFolder();+ var paths = SetupPaths.Sandbox(temp.Sub("pc"));+ var folder = Path.GetDirectoryName(temp.Write(@"pc\Program Files\Filee\Filee.exe"))!;+ var registry = new MemoryRegistry();+ registry.SetString(Hive.LocalMachine, SetupNames.UninstallKey, "InstallLocation", folder);+ // 1.x recorded the desktop icon and PATH, but the user deleted the shortcut since.+ registry.SetString(Hive.LocalMachine, SetupNames.UninstallKey, SetupNames.InnoTasksValue, @"contextmenu,startup,cli,desktopicon");+ registry.SetString(Hive.LocalMachine, SetupNames.MachineEnvironmentKey, "Path", folder.ToUpperInvariant() + @"\CLI\");+ var system = new FakeSystem { ExplorerMenuSupported = true, MenuRegistered = false };++ var tasks = PreviousInstall.Find(registry, InstallScope.Machine)!.CurrentTasks(registry, system, paths);+ Assert.Equal(new SetupTasks(ContextMenu: true, ModernMenu: false, Startup: true, Cli: true, DesktopIcon: false), tasks);+ }+}++public class PathVariableTests+{+ [Theory]+ [InlineData(null, @"C:\F\cli", @"C:\F\cli")]+ [InlineData("", @"C:\F\cli", @"C:\F\cli")]+ [InlineData(@"C:\a", @"C:\F\cli", @"C:\a;C:\F\cli")]+ [InlineData(@"C:\a;", @"C:\F\cli", @"C:\a;C:\F\cli")]+ [InlineData(@"C:\a;c:\f\CLI\", @"C:\F\cli", @"C:\a;c:\f\CLI\")]+ public void Add(string? paths, string folder, string expected) => Assert.Equal(expected, PathVariable.Add(paths, folder));++ [Theory]+ [InlineData(@"C:\a;C:\F\cli;C:\b", @"C:\a;C:\b")]+ [InlineData(@"C:\F\cli\;C:\a", @"C:\a")]+ [InlineData(@"C:\a;;C:\F\CLI;C:\b;", @"C:\a;;C:\b;")]+ [InlineData(@"C:\F\cli", "")]+ [InlineData(@"C:\a;C:\F\cli2", @"C:\a;C:\F\cli2")]+ public void Remove(string paths, string expected) => Assert.Equal(expected, PathVariable.Remove(paths, @"C:\F\cli"));++ [Fact]+ public void Setting_keeps_the_kind_and_reports_changes()+ {+ var registry = new MemoryRegistry();+ registry.SetString(Hive.CurrentUser, SetupNames.UserEnvironmentKey, "Path", @"C:\a", expandable: false);+ Assert.True(PathVariable.Set(registry, InstallScope.User, @"C:\F\cli", present: true));+ Assert.False(PathVariable.Set(registry, InstallScope.User, @"C:\F\cli", present: true));+ var entry = registry.Get(Hive.CurrentUser, SetupNames.UserEnvironmentKey, "Path")!;+ Assert.Equal(@"C:\a;C:\F\cli", entry.Text);+ Assert.False(entry.Expandable);+ Assert.True(PathVariable.Set(registry, InstallScope.User, @"C:\F\cli", present: false));+ Assert.False(PathVariable.Set(registry, InstallScope.User, @"C:\F\cli", present: false));+ // Never touched the machine PATH.+ Assert.False(registry.KeyExists(Hive.LocalMachine, SetupNames.MachineEnvironmentKey));+ }++ [Fact]+ public void The_sandbox_registry_survives_a_restart_of_setup()+ {+ using var temp = new TempFolder();+ var file = temp.Sub("registry.json");+ var registry = new MemoryRegistry(file);+ registry.SetString(Hive.LocalMachine, SetupNames.UninstallKey, "DisplayName", "Filee");+ registry.SetNumber(Hive.LocalMachine, SetupNames.UninstallKey, "NoModify", 1);+ registry.SetString(Hive.LocalMachine, SetupNames.MachineEnvironmentKey, "Path", "%SystemRoot%", expandable: true);+ var again = new MemoryRegistry(file);+ Assert.Equal("Filee", again.Get(Hive.LocalMachine, SetupNames.UninstallKey, "DisplayName")?.Text);+ Assert.Equal(1, again.Get(Hive.LocalMachine, SetupNames.UninstallKey, "NoModify")?.Value);+ Assert.True(again.Get(Hive.LocalMachine, SetupNames.MachineEnvironmentKey, "Path")!.Expandable);+ Assert.True(again.KeyExists(Hive.LocalMachine, @"Software\Microsoft\Windows\CurrentVersion\Uninstall"));+ again.DeleteKey(Hive.LocalMachine, @"Software\Microsoft");+ Assert.False(new MemoryRegistry(file).KeyExists(Hive.LocalMachine, SetupNames.UninstallKey));+ }+}