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
Add "Convert with Filee" to the Windows 11 top-level Explorer menu
KnifeLemonef4999334ef3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 32745737..b28bb9d9 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -28,6 +28,20 @@ jobs:- name: Buildrun: dotnet build Filee.slnx --no-restore -c Release+ # Windows 11 Explorer menu (native DLL + unsigned sparse package); its tests load the DLL in-process.+ - name: Cache Zig toolchain+ uses: actions/cache@v4+ with:+ path: |+ build/.cache/zig-x86_64-windows-0.16.0+ build/.cache/zig-cache+ key: zig-0.16.0-${{ hashFiles('src/Filee.ExplorerMenu/**') }}+ restore-keys: zig-0.16.0-++ - name: Build Explorer menu extension+ shell: pwsh+ run: ./build/build-explorer-menu.ps1+# rhwp + Pandoc are small; with them the HWP/HWPX engine tests run too (LibreOffice is skipped to save time).- name: Fetch rhwp and Pandoc for engine testsshell: pwshdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex f3005cf2..f848fa65 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -35,6 +35,12 @@ jobs:shell: pwshrun: ./build/fetch-fonts.ps1+ # Windows 11 top-level Explorer menu: FileeExplorerMenu.dll (C, built with a pinned Zig toolchain) and the+ # unsigned sparse package FileeExplorerMenu.msix. Built before the tests so they check the real files.+ - name: Build Explorer menu extension+ shell: pwsh+ run: ./build/build-explorer-menu.ps1 -Version ${{ steps.version.outputs.value }}+- name: Testrun: dotnet test Filee.slnx -c Release@@ -45,6 +51,11 @@ jobs:-p:PublishReadyToRun=true-o ${{ env.PUBLISH_DIR }}+ # Must sit next to Filee.exe: the package's external location is the install folder.+ - name: Add Explorer menu extension+ shell: pwsh+ run: Copy-Item build/.cache/explorer-menu/FileeExplorerMenu.dll, build/.cache/explorer-menu/FileeExplorerMenu.msix "${{ env.PUBLISH_DIR }}"+# Only the small rhwp is bundled. LibreOffice (+ H2Orestart, Java) and Pandoc are large and are downloaded by# the app when the user picks them (first-run setup or Settings > Engines), see engines.json.- name: Bundle conversion engines (rhwp)diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdindex 05fb3bc0..eb9c91a4 100644--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@ -43,6 +43,16 @@ Downloaded from their official release pages when the user chooses to install thThese programs run as separate processes. Their source code is available from the linked projects.+## Windows 11 Explorer menu (FileeExplorerMenu.dll)++The DLL is Filee's own C code, compiled with the Zig toolchain (a build tool, not shipped) against the mingw-w64+Windows headers, without a C runtime. Pieces of these projects that can end up in the binary:++| Component | License | Project |+|---|---|---|+| Zig compiler_rt (compiler support routines) | MIT | https://github.com/ziglang/zig |+| mingw-w64 Windows headers and import library definitions | Public domain / ZPL-2.1 | https://www.mingw-w64.org |+## Fonts and icons| Component | License | Project |diff --git a/build/build-explorer-menu.ps1 b/build/build-explorer-menu.ps1new file mode 100644index 00000000..e6efe04a--- /dev/null+++ b/build/build-explorer-menu.ps1@@ -0,0 +1,117 @@+<#+.SYNOPSIS+ Builds the Windows 11 File Explorer menu extension: FileeExplorerMenu.dll + FileeExplorerMenu.msix.++.DESCRIPTION+ The DLL (src/Filee.ExplorerMenu, plain C, no C runtime) is compiled with a pinned, portable Zig toolchain that is+ downloaded into build/.cache (SHA-256 verified), so neither Visual C++ nor the Windows SDK is needed - locally or+ on GitHub's windows-latest runner. The unsigned sparse package is packed by build/tools/make-explorer-package.cs+ through the packaging API that ships with Windows.++ Both files belong next to Filee.exe; the release workflow passes the publish folder as -Destination.++.EXAMPLE+ pwsh build/build-explorer-menu.ps1+ pwsh build/build-explorer-menu.ps1 -Destination publish/win-x64 -Version 1.2.0+#>+[CmdletBinding()]+param(+ [string]$Destination = (Join-Path $PSScriptRoot '.cache\explorer-menu'),+ # Written into the DLL's version resource; defaults to <Version> in Directory.Build.props.+ [string]$Version+)++$ErrorActionPreference = 'Stop'+$root = Resolve-Path (Join-Path $PSScriptRoot '..')+$cache = Join-Path $PSScriptRoot '.cache'++# Zig 0.16.0 for x86_64 Windows. Update the version, hash and size together.+$zigName = 'zig-x86_64-windows-0.16.0'+$zigSha256 = '68659EB5F1E4EB1437A722F1DD889C5A322C9954607F5EDCF337BC3684A75A7E'+$zigSize = 97217739+# ziglang.org asks automated builds to prefer the community mirrors (https://ziglang.org/download/community-mirrors/);+# the archive is verified with SHA-256 whichever server it comes from.+$zigUrls = @(+ "https://ziglang.freetls.fastly.net/$zigName.zip",+ "https://pkg.hexops.org/zig/$zigName.zip",+ "https://ziglang.org/download/0.16.0/$zigName.zip"+)++function Get-Zig {+ $folder = Join-Path $cache $zigName+ $exe = Join-Path $folder 'zig.exe'+ if (Test-Path $exe) { return $exe }++ New-Item -ItemType Directory -Force -Path $cache | Out-Null+ $zip = Join-Path $cache "$zigName.zip"+ $ok = (Test-Path $zip) -and (Get-FileHash $zip -Algorithm SHA256).Hash -eq $zigSha256+ foreach ($url in $zigUrls) {+ if ($ok) { break }+ Write-Host "get $url"+ try {+ # curl.exe (part of Windows) is much faster than Invoke-WebRequest for ~100 MB.+ & curl.exe --fail --location --silent --show-error --retry 2 --max-time 900 --output $zip $url+ if ($LASTEXITCODE -ne 0) { throw "curl exit code $LASTEXITCODE" }+ $hash = (Get-FileHash $zip -Algorithm SHA256).Hash+ if ($hash -ne $zigSha256) { throw "checksum mismatch (got $hash, size $((Get-Item $zip).Length), expected $zigSize bytes)" }+ $ok = $true+ }+ catch {+ Write-Warning "Download from $url failed: $($_.Exception.Message)"+ Remove-Item $zip -ErrorAction SilentlyContinue+ }+ }+ if (-not $ok) { throw "Could not download $zigName from any mirror." }++ Write-Host "unpack $zigName"+ $partial = Join-Path $cache "$zigName.partial"+ Remove-Item $partial -Recurse -Force -ErrorAction SilentlyContinue+ New-Item -ItemType Directory -Force -Path $partial | Out-Null+ & tar.exe -xf $zip -C $partial+ if ($LASTEXITCODE -ne 0) { throw "tar failed with exit code $LASTEXITCODE" }+ Move-Item (Join-Path $partial $zigName) $folder+ Remove-Item $partial -Recurse -Force+ Remove-Item $zip+ return $exe+}++if (-not $Version) {+ $Version = ([xml](Get-Content (Join-Path $root 'Directory.Build.props'))).Project.PropertyGroup.Version | Where-Object { $_ } | Select-Object -First 1+}+$parts = ($Version -split '[-+]')[0].Split('.') + @('0', '0', '0')+$major, $minor, $patch = [int]$parts[0], [int]$parts[1], [int]$parts[2]++$zig = Get-Zig+$env:ZIG_GLOBAL_CACHE_DIR = Join-Path $cache 'zig-cache'+$env:ZIG_LOCAL_CACHE_DIR = Join-Path $cache 'zig-cache'+$source = Join-Path $root 'src\Filee.ExplorerMenu'+$obj = Join-Path $cache 'explorer-menu-obj'+New-Item -ItemType Directory -Force -Path $obj, $Destination | Out-Null++# The version resource gets the numbers through a generated header-like prefix (zig's resource compiler has no -D).+$rc = Join-Path $obj 'FileeExplorerMenu.rc'+$defines = "#define FILEE_VERSION_MAJOR $major`r`n#define FILEE_VERSION_MINOR $minor`r`n#define FILEE_VERSION_PATCH $patch`r`n#define FILEE_VERSION_TEXT `"$Version`"`r`n"+Set-Content -Path $rc -Value ($defines + (Get-Content (Join-Path $source 'FileeExplorerMenu.rc') -Raw)) -Encoding utf8NoBOM -NoNewline++Write-Host "build FileeExplorerMenu.dll $Version"+$dll = Join-Path $obj 'FileeExplorerMenu.dll'+# -nostdlib: no C runtime inside explorer.exe; the entry point is DllMain itself. -s strips symbols.+& $zig cc -target x86_64-windows-gnu -shared -O2 -s -nostdlib -Wall -Wextra -Werror `+ -isystem (Join-Path (Split-Path $zig) 'lib\libc\include\any-windows-any') `+ (Join-Path $source 'FileeExplorerMenu.c') (Join-Path $source 'FileeExplorerMenu.def') $rc `+ -lkernel32 -luser32 -lole32 -lshell32 -lshlwapi '-Wl,--entry=DllMain' -o $dll+if ($LASTEXITCODE -ne 0) { throw "zig cc failed with exit code $LASTEXITCODE" }+Copy-Item $dll $Destination -Force++Write-Host "pack FileeExplorerMenu.msix"+$Destination = (Resolve-Path $Destination).Path+Push-Location $root+try {+ & dotnet run build/tools/make-explorer-package.cs -- $Destination+ if ($LASTEXITCODE -ne 0) { throw "make-explorer-package failed with exit code $LASTEXITCODE" }+}+finally {+ Pop-Location+}++Write-Host "Explorer menu ready in $Destination"diff --git a/build/tools/make-explorer-package.cs b/build/tools/make-explorer-package.csnew file mode 100644index 00000000..d3c3c8c1--- /dev/null+++ b/build/tools/make-explorer-package.cs@@ -0,0 +1,143 @@+// Packs FileeExplorerMenu.msix, the unsigned sparse package behind the Windows 11 "Convert with Filee" menu entry.+// Run by build/build-explorer-menu.ps1: dotnet run build/tools/make-explorer-package.cs -- <output folder>+// Uses the Windows packaging API (AppxPackaging.dll, part of Windows 10/11): it validates the manifest and writes the+// block map and content types exactly like MakeAppx, so no Windows SDK is needed. The manifest comes from+// ExplorerMenuPackage.CreateManifest (unit tested).+#:project ../../src/Filee.Platform.Windows/Filee.Platform.Windows.csproj+#:property AllowUnsafeBlocks=true+#:property PublishAot=false++using System.Runtime.InteropServices;+using System.Text;+using Filee.Platform.Windows;++if (args.Length != 1)+{+ Console.Error.WriteLine("usage: dotnet run build/tools/make-explorer-package.cs -- <output folder>");+ return 2;+}++var output = Path.GetFullPath(args[0]);+Directory.CreateDirectory(output);+var repo = Environment.CurrentDirectory;+while (!File.Exists(Path.Combine(repo, "Filee.slnx")))+ repo = Path.GetDirectoryName(repo) ?? throw new InvalidOperationException("Run this from inside the Filee repository.");++var work = Directory.CreateTempSubdirectory("filee-msix-");+try+{+ var manifestPath = Path.Combine(work.FullName, "AppxManifest.xml");+ File.WriteAllText(manifestPath, ExplorerMenuPackage.CreateManifest(), new UTF8Encoding(false));+ var packagePath = Path.Combine(output, ExplorerMenuPackage.PackageFileName);+ var logo = Path.Combine(repo, "src", "Filee.App", "Assets", "Icons", "filee.png");+ Appx.Pack(packagePath, manifestPath, [(ExplorerMenuPackage.LogoPath, logo, "image/png")]);+ Console.WriteLine($"Wrote {packagePath} ({new FileInfo(packagePath).Length:N0} bytes, manifest {ExplorerMenuPackage.ManifestVersion})");+}+finally+{+ work.Delete(recursive: true);+}+return 0;++/// <summary>Minimal raw-vtable client of IAppxFactory / IAppxPackageWriter (no COM interop marshalling needed).</summary>+internal static unsafe class Appx+{+ private static readonly Guid ClsidAppxFactory = new("5842a140-ff9f-4166-8f5c-62f5b7b0c781");+ private static readonly Guid IidAppxFactory = new("beb94909-e451-438b-b5a7-d79e767b75d8");+ private const uint ClsctxInprocServer = 1;+ private const uint CoinitMultithreaded = 0;+ private const int RpcEChangedMode = unchecked((int)0x80010106);+ private const uint StgmRead = 0, StgmWrite = 1, StgmShareDenyWrite = 0x20, StgmShareExclusive = 0x10, StgmCreate = 0x1000;+ private const int AppxCompressionNormal = 1;++ [StructLayout(LayoutKind.Sequential)]+ private struct PackageSettings+ {+ public int ForceZip32;+ public nint HashMethod; // IUri*+ }++ public static void Pack(string packagePath, string manifestPath, IEnumerable<(string Name, string Path, string Type)> payload)+ {+ var init = CoInitializeEx(0, CoinitMultithreaded);+ if (init != RpcEChangedMode) // the console main thread may already be an MTA/STA; either works+ Check(init, "CoInitializeEx");+ nint factory = 0, output = 0, hash = 0, writer = 0;+ try+ {+ var clsid = ClsidAppxFactory;+ var iid = IidAppxFactory;+ Check(CoCreateInstance(&clsid, 0, ClsctxInprocServer, &iid, out factory), "CoCreateInstance(AppxFactory)");+ Check(SHCreateStreamOnFileEx(packagePath, StgmCreate | StgmWrite | StgmShareExclusive, 0x80, 1, 0, out output), "create " + packagePath);+ Check(CreateUri("http://www.w3.org/2001/04/xmlenc#sha256", 0, 0, out hash), "CreateUri");+ var settings = new PackageSettings { ForceZip32 = 1, HashMethod = hash };+ // IAppxFactory::CreatePackageWriter(IStream*, APPX_PACKAGE_SETTINGS*, IAppxPackageWriter**) is slot 3.+ var create = (delegate* unmanaged[Stdcall]<nint, nint, PackageSettings*, nint*, int>)Slot(factory, 3);+ nint created;+ Check(create(factory, output, &settings, &created), "CreatePackageWriter");+ writer = created;++ foreach (var (name, path, type) in payload)+ {+ Check(SHCreateStreamOnFileEx(path, StgmRead | StgmShareDenyWrite, 0, 0, 0, out var input), "open " + path);+ try+ {+ // IAppxPackageWriter::AddPayloadFile(LPCWSTR, LPCWSTR, APPX_COMPRESSION_OPTION, IStream*) is slot 3.+ var add = (delegate* unmanaged[Stdcall]<nint, char*, char*, int, nint, int>)Slot(writer, 3);+ fixed (char* n = name)+ fixed (char* t = type)+ Check(add(writer, n, t, AppxCompressionNormal, input), "AddPayloadFile " + name);+ }+ finally+ {+ Release(input);+ }+ }++ Check(SHCreateStreamOnFileEx(manifestPath, StgmRead | StgmShareDenyWrite, 0, 0, 0, out var manifest), "open manifest");+ try+ {+ // IAppxPackageWriter::Close(IStream* manifest) is slot 4; it validates the manifest against the schema.+ var close = (delegate* unmanaged[Stdcall]<nint, nint, int>)Slot(writer, 4);+ Check(close(writer, manifest), "Close (manifest validation)");+ }+ finally+ {+ Release(manifest);+ }+ }+ finally+ {+ Release(writer);+ Release(hash);+ Release(output);+ Release(factory);+ }+ }++ private static nint Slot(nint instance, int index) => (*(nint**)instance)[index];++ private static void Release(nint instance)+ {+ if (instance != 0)+ ((delegate* unmanaged[Stdcall]<nint, uint>)Slot(instance, 2))(instance);+ }++ private static void Check(int hr, string what)+ {+ if (hr < 0)+ throw new InvalidOperationException($"{what} failed: 0x{hr:X8} {Marshal.GetExceptionForHR(hr)?.Message}");+ }++ [DllImport("ole32.dll")]+ private static extern int CoInitializeEx(nint reserved, uint coinit);++ [DllImport("ole32.dll")]+ private static extern int CoCreateInstance(Guid* clsid, nint outer, uint context, Guid* iid, out nint instance);++ [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]+ private static extern int SHCreateStreamOnFileEx(string file, uint mode, uint attributes, int create, nint template, out nint stream);++ [DllImport("urlmon.dll", CharSet = CharSet.Unicode)]+ private static extern int CreateUri(string uri, uint flags, nuint reserved, out nint result);+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex d0f651b2..136f57b8 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -66,3 +66,46 @@ Bump `AppSettings.CurrentSchemaVersion` and add a step to `SettingsMigrations` wEverything OS-specific goes through `IPlatformServices` (`Filee.Core/Platform`). Windows lives in`Filee.Platform.Windows`; macOS will get its own project. Global input uses SharpHook on both.++## Explorer integration++Settings → General → "Show “Convert with Filee” in the Explorer context menu" (`AppSettings.ContextMenuEnabled`) is+applied by `WindowsPlatformServices.SetContextMenu` at start-up and whenever settings change (installed builds only):++- **Classic verb** `HKCU\Software\Classes\*\shell\Filee` (`Filee.exe --convert "%1"`, one process per file; the running+ instance collects them through `SingleInstance`) and a **Send To** shortcut. Per user, no admin rights. On Windows 10+ this is the entry; on Windows 11 it sits under "Show more options".+- **Windows 11 top-level entry** (optional): an `IExplorerCommand` in `FileeExplorerMenu.dll`+ (`src/Filee.ExplorerMenu`, plain C, no C runtime) declared by the sparse package `FileeExplorerMenu.msix`+ (`ExplorerMenuPackage.CreateManifest`: `desktop4:FileExplorerContextMenus`, `desktop5:ItemType Type="*"`,+ `com:SurrogateServer`, `uap10:AllowExternalContent`, `AppListEntry="none"`). Both files ship next to Filee.exe and the+ package's external location is the install folder (`%LocalAppData%\Filee\current`, stable across Velopack updates).+ - The package is **unsigned** (publisher contains `OID.2.25.311729368913984317654407730594956997722=1`; Filee has no+ code-signing certificate). Windows only registers an unsigned package with executable content **with+ administrator rights** (it installs it for all users); a per-user attempt fails with 0x80073D2B "an unsigned+ package cannot include Executable activations". So it is opt-in: the General page shows "Add to the main menu"+ on Windows 11 x64, which runs `Add-AppxPackage -Path … -ExternalLocation … -AllowUnsigned` in Windows PowerShell+ through one UAC prompt (`ExplorerMenuRegistration`). A signed package would register per user without a prompt.+ - The manifest version (`ExplorerMenuPackage.ManifestVersion`) is independent of the app version, so app updates+ don't need a new prompt: the DLL is loaded from the install folder and updated with the app. Bump it only when the+ manifest changes; the page then offers to add the entry again ("Outdated").+ - The DLL shows the entry only for files (not folders or items inside ZIP folders) and only while+ `%APPDATA%\Filee\explorer-menu.txt` exists. The app writes the title in the UI language there while the setting is+ on and deletes it when the setting is off, so switching the setting takes effect without re-registering. While the+ package is registered the classic verb is removed (Windows lists packaged commands under "Show more options" too).+ - Invoke starts `Filee.exe --convert "<path>"…` next to the DLL and returns at once. Selections longer than a+ command line go through `%TEMP%\Filee-convert-*.txt` (`--convert-list`, one path per line), which the app deletes.+ - Velopack: an update renames the `current` folder even while Explorer has the DLL loaded (Windows allows renaming+ folders that contain loaded DLLs; only deleting the file fails, so an old copy may stay in Velopack's temp folder+ until Explorer unloads it). Uninstall removes the package (`UninstallCleanup`, no admin needed) and the title file.+ - Build: `pwsh build/build-explorer-menu.ps1` downloads a pinned Zig (SHA-256 checked) into `build/.cache`, compiles+ the DLL and packs the MSIX with `build/tools/make-explorer-package.cs` (Windows' own packaging API, no SDK).+ Output: `build/.cache/explorer-menu`; CI builds it for the tests, the release workflow copies it into the publish+ folder.++Debugging: `Get-AppxPackage Filee.ExplorerMenu` shows the registration (`InstallLocation` is the external location);+`Get-AppPackageLog -ActivityID <id>` explains a failed deployment. To try a local build, copy+`FileeExplorerMenu.dll` + `.msix` next to an installed Filee.exe and use the button, or run elevated:+`Add-AppxPackage -Path FileeExplorerMenu.msix -ExternalLocation <folder with Filee.exe> -AllowUnsigned`. Explorer picks+the entry up for new menus; if not, restart Explorer. To remove it by hand:+`Get-AppxPackage Filee.ExplorerMenu | Remove-AppxPackage`.diff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.csindex d65b90cf..5e9ca6c2 100644--- a/src/Filee.App/App.axaml.cs+++ b/src/Filee.App/App.axaml.cs@@ -135,6 +135,8 @@ public partial class App : Applicationprivate void HandleCommandLine(CommandLine options, bool firstLaunch = false){+ // The Windows 11 Explorer menu hands over huge selections in a temp file; its paths are in ConvertFiles now.+ options.DeleteListFile();if (options.ConvertFiles.Count > 0){// Explorer may start one process per selected file: collect them for a moment, then open once.diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex ca855ad4..f95dcef1 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -85,6 +85,15 @@"general.start_with_system": "Start Filee when I sign in","general.context_menu": "Show “Convert with Filee” in the Explorer context menu","general.context_menu_label": "Convert with Filee",+ "general.modern_menu_hint": "On Windows 11 this entry is under “Show more options”. Filee can also add it to the main menu; Windows asks for administrator permission once.",+ "general.modern_menu_on": "“Convert with Filee” is in the main Windows 11 menu.",+ "general.modern_menu_outdated": "The main-menu entry belongs to an older or moved copy of Filee. Add it again to update it.",+ "general.modern_menu_add": "Add to the main menu",+ "general.modern_menu_remove": "Remove from the main menu",+ "general.modern_menu_busy": "Waiting for Windows…",+ "general.modern_menu_cancelled": "Cancelled. The entry stays under “Show more options”.",+ "general.modern_menu_failed": "Windows did not add the entry: {0}",+ "general.modern_menu_remove_failed": "Windows did not remove the entry: {0}","general.check_updates": "Check for updates automatically","general.check_now": "Check now","general.update_available": "Version {0} is available",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex c45e8822..d1145e42 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -85,6 +85,15 @@"general.start_with_system": "로그인할 때 Filee 시작","general.context_menu": "탐색기 우클릭 메뉴에 “Filee로 변환” 표시","general.context_menu_label": "Filee로 변환",+ "general.modern_menu_hint": "Windows 11에서는 이 항목이 “추가 옵션 표시” 안에 있어요. 기본 메뉴에도 추가할 수 있고, 이때 Windows가 관리자 권한을 한 번 요청해요.",+ "general.modern_menu_on": "“Filee로 변환”이 Windows 11 기본 메뉴에 있어요.",+ "general.modern_menu_outdated": "기본 메뉴 항목이 이전 버전이나 다른 위치의 Filee를 가리키고 있어요. 다시 추가하면 업데이트돼요.",+ "general.modern_menu_add": "기본 메뉴에 추가",+ "general.modern_menu_remove": "기본 메뉴에서 제거",+ "general.modern_menu_busy": "Windows의 응답을 기다리는 중…",+ "general.modern_menu_cancelled": "취소했어요. 항목은 “추가 옵션 표시” 안에 그대로 있어요.",+ "general.modern_menu_failed": "Windows가 항목을 추가하지 못했어요: {0}",+ "general.modern_menu_remove_failed": "Windows가 항목을 제거하지 못했어요: {0}","general.check_updates": "자동으로 업데이트 확인","general.check_now": "지금 확인","general.update_available": "{0} 버전을 사용할 수 있어요",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex de9260d8..99832174 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -85,6 +85,15 @@"general.start_with_system": "登录时启动 Filee","general.context_menu": "在资源管理器右键菜单中显示“用 Filee 转换”","general.context_menu_label": "用 Filee 转换",+ "general.modern_menu_hint": "在 Windows 11 中,此项位于“显示更多选项”里。Filee 也可以把它添加到主菜单,Windows 会请求一次管理员权限。",+ "general.modern_menu_on": "“用 Filee 转换”已在 Windows 11 主菜单中。",+ "general.modern_menu_outdated": "主菜单中的此项属于旧版本或其他位置的 Filee。重新添加即可更新。",+ "general.modern_menu_add": "添加到主菜单",+ "general.modern_menu_remove": "从主菜单移除",+ "general.modern_menu_busy": "正在等待 Windows…",+ "general.modern_menu_cancelled": "已取消。此项仍在“显示更多选项”中。",+ "general.modern_menu_failed": "Windows 未能添加此项:{0}",+ "general.modern_menu_remove_failed": "Windows 未能移除此项:{0}","general.check_updates": "自动检查更新","general.check_now": "立即检查","general.update_available": "有新版本 {0}",diff --git a/src/Filee.App/Services/CommandLine.cs b/src/Filee.App/Services/CommandLine.csindex be1b9250..a9120671 100644--- a/src/Filee.App/Services/CommandLine.cs+++ b/src/Filee.App/Services/CommandLine.cs@@ -1,22 +1,40 @@// Command line options:-// Filee.exe open the main window-// Filee.exe --background start in the tray only (used by "start with Windows")-// Filee.exe --settings open the main window-// Filee.exe --convert a b ... open the donut for these files (Explorer context menu / Send To)+// Filee.exe open the main window+// Filee.exe --background start in the tray only (used by "start with Windows")+// Filee.exe --settings open the main window+// Filee.exe --convert a b ... open the donut for these files (Explorer context menu / Send To)+// Filee.exe --convert-list <file> same, with one path per line in a UTF-8 file (Windows 11 Explorer menu, for+// selections too long for a command line); the app deletes the file afterwards++using System.Text;namespace Filee.App.Services;-public sealed record CommandLine(bool Background, bool ShowSettings, IReadOnlyList<string> ConvertFiles)+/// <summary>Parsed command line.</summary>+/// <param name="ListFile">The <c>--convert-list</c> file, if any (see <see cref="DeleteListFile"/>).</param>+public sealed record CommandLine(bool Background, bool ShowSettings, IReadOnlyList<string> ConvertFiles, string? ListFile = null){+ /// <summary>File name prefix of list files written by FileeExplorerMenu.dll (LIST_PREFIX there) into %TEMP%.</summary>+ public const string ListFilePrefix = "Filee-convert-";+public static CommandLine Parse(IReadOnlyList<string> args){var background = false;var settings = false;var files = new List<string>();+ string? listFile = null;var collecting = false;+ var expectList = false;foreach (var arg in args){+ if (expectList)+ {+ expectList = false;+ listFile = arg;+ files.AddRange(ReadListFile(arg).Where(Exists).Select(Path.GetFullPath));+ continue;+ }switch (arg.ToLowerInvariant()){case "--background":@@ -28,13 +46,74 @@ public sealed record CommandLine(bool Background, bool ShowSettings, IReadOnlyLicase "--convert":collecting = true;break;+ case "--convert-list":+ expectList = true;+ break;default:// Velopack passes its own --veloapp-* arguments; ignore anything unknown that isn't a file.- if (collecting && !arg.StartsWith("--", StringComparison.Ordinal) && (File.Exists(arg) || Directory.Exists(arg)))+ if (collecting && !arg.StartsWith("--", StringComparison.Ordinal) && Exists(arg))files.Add(Path.GetFullPath(arg));break;}}- return new CommandLine(background, settings, files);+ return new CommandLine(background, settings, files, listFile);+ }++ /// <summary>+ /// Deletes the list file once its paths were taken over. Only files the Explorer menu wrote (prefix, temp+ /// folder) are deleted, so a crafted command line cannot make Filee delete anything else.+ /// </summary>+ public void DeleteListFile()+ {+ if (ListFile is null || !IsOwnListFile(ListFile))+ return;+ try+ {+ File.Delete(ListFile);+ }+ catch (IOException) { }+ catch (UnauthorizedAccessException) { }+ }++ /// <summary>True for <c>%TEMP%\Filee-convert-*.txt</c>.</summary>+ internal static bool IsOwnListFile(string path)+ {+ try+ {+ var full = Path.GetFullPath(path);+ return Path.GetFileName(full).StartsWith(ListFilePrefix, StringComparison.OrdinalIgnoreCase)+ && full.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)+ && string.Equals(Path.TrimEndingDirectorySeparator(Path.GetDirectoryName(full) ?? ""),+ Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())), StringComparison.OrdinalIgnoreCase);+ }+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)+ {+ return false;+ }+ }++ /// <summary>One path per line (UTF-8, with or without BOM); blank lines are skipped. Unreadable → empty.</summary>+ internal static IEnumerable<string> ReadListFile(string path)+ {+ try+ {+ return File.ReadAllLines(path, Encoding.UTF8).Select(l => l.Trim()).Where(l => l.Length > 0).ToList();+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)+ {+ return [];+ }+ }++ private static bool Exists(string path)+ {+ try+ {+ return File.Exists(path) || Directory.Exists(path);+ }+ catch (ArgumentException)+ {+ return false;+ }}}diff --git a/src/Filee.App/Services/UninstallCleanup.cs b/src/Filee.App/Services/UninstallCleanup.csindex 4cd3251c..5bc5e428 100644--- a/src/Filee.App/Services/UninstallCleanup.cs+++ b/src/Filee.App/Services/UninstallCleanup.cs@@ -1,4 +1,5 @@-// Runs from the Velopack uninstall hook: removes registry entries Filee created for the current user.+// Runs from the Velopack uninstall hook: removes registry entries, the Windows 11 Explorer menu package and other+// integration Filee created for the current user.using Filee.Platform.Windows;@@ -13,8 +14,13 @@ internal static class UninstallCleanuptry{var platform = new WindowsPlatformServices();+ // Deletes the classic verb, Send To and the title file (which already hides the top-level entry).platform.SetContextMenu(false, "", "");platform.SetStartWithSystem(false, "");+ // Removing the package needs no administrator rights; there is no UI for a UAC prompt here, and Velopack+ // gives the hook about a minute.+ if (ExplorerMenuRegistration.IsSupportedOs)+ ExplorerMenuRegistration.RemoveAsync(allowElevation: false).Wait(TimeSpan.FromSeconds(40));// Engines downloaded later live outside the app folder (see EngineEnvironment.DownloadRoot).if (Directory.Exists(Filee.Engines.Infrastructure.EngineEnvironment.DownloadRoot))Directory.Delete(Filee.Engines.Infrastructure.EngineEnvironment.DownloadRoot, recursive: true);diff --git a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.csindex d2797429..d5ee544e 100644--- a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs@@ -33,6 +33,7 @@ public sealed partial class GeneralPageViewModel : ObservableObject_contextMenu = store.Settings.ContextMenuEnabled;_checkForUpdates = store.Settings.CheckForUpdates;ShowUpdateState(updates.LatestVersion);+ RefreshModernMenu();}public IReadOnlyList<Choice<string>> Languages { get; }@@ -47,9 +48,64 @@ public sealed partial class GeneralPageViewModel : ObservableObject[ObservableProperty] private bool _updateAvailable;[ObservableProperty] private string? _libraryMessage;+ // Windows 11 top-level Explorer menu entry (see ExplorerMenuRegistration). Only shown when this build ships it.+ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(ShowModernMenu), nameof(CanAddModernMenu), nameof(CanRemoveModernMenu))]+ private ModernContextMenuState _modernMenuState;++ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(CanAddModernMenu), nameof(CanRemoveModernMenu))]+ private bool _modernMenuBusy;++ [ObservableProperty] private string? _modernMenuStatus;++ public bool ShowModernMenu => ContextMenu && ModernMenuState != ModernContextMenuState.Unsupported;+ public bool CanAddModernMenu => !ModernMenuBusy && ModernMenuState is ModernContextMenuState.Off or ModernContextMenuState.Outdated;+ public bool CanRemoveModernMenu => !ModernMenuBusy && ModernMenuState is ModernContextMenuState.On or ModernContextMenuState.Outdated;+partial void OnLanguageChanged(Choice<string> value) => Save(s => s.Language = value.Value);partial void OnStartWithSystemChanged(bool value) => Save(s => s.StartWithSystem = value);- partial void OnContextMenuChanged(bool value) => Save(s => s.ContextMenuEnabled = value);++ partial void OnContextMenuChanged(bool value)+ {+ Save(s => s.ContextMenuEnabled = value);+ OnPropertyChanged(nameof(ShowModernMenu));+ }++ /// <summary>Registers the top-level entry; Windows shows one administrator prompt.</summary>+ [RelayCommand]+ private Task AddModernMenu() => ChangeModernMenu(true);++ [RelayCommand]+ private Task RemoveModernMenu() => ChangeModernMenu(false);++ private async Task ChangeModernMenu(bool enabled)+ {+ if (Environment.ProcessPath is not { } exe)+ return;+ ModernMenuBusy = true;+ ModernMenuStatus = _loc["general.modern_menu_busy"];+ var result = await _platform.SetModernContextMenuAsync(enabled, exe);+ ModernMenuBusy = false;+ RefreshModernMenu();+ if (result.Cancelled)+ ModernMenuStatus = _loc["general.modern_menu_cancelled"];+ else if (!result.Succeeded)+ ModernMenuStatus = _loc.Format(enabled ? "general.modern_menu_failed" : "general.modern_menu_remove_failed", result.Error ?? "");+ }++ private void RefreshModernMenu()+ {+ ModernMenuState = Environment.ProcessPath is { } exe+ ? _platform.GetModernContextMenuState(exe)+ : ModernContextMenuState.Unsupported;+ ModernMenuStatus = _loc[ModernMenuState switch+ {+ ModernContextMenuState.On => "general.modern_menu_on",+ ModernContextMenuState.Outdated => "general.modern_menu_outdated",+ _ => "general.modern_menu_hint",+ }];+ }partial void OnCheckForUpdatesChanged(bool value) => Save(s => s.CheckForUpdates = value);private void Save(Action<AppSettings> change)diff --git a/src/Filee.App/Views/Pages/GeneralPage.axaml b/src/Filee.App/Views/Pages/GeneralPage.axamlindex d6298d56..97bb96f0 100644--- a/src/Filee.App/Views/Pages/GeneralPage.axaml+++ b/src/Filee.App/Views/Pages/GeneralPage.axaml@@ -14,6 +14,14 @@</StackPanel><ToggleSwitch Content="{DynamicResource general.start_with_system}" IsChecked="{Binding StartWithSystem}" /><ToggleSwitch Content="{DynamicResource general.context_menu}" IsChecked="{Binding ContextMenu}" IsVisible="{Binding IsWindows}" />+ <!-- Windows 11: optional top-level entry (needs one administrator prompt), see ExplorerMenuRegistration. -->+ <StackPanel Spacing="8" IsVisible="{Binding ShowModernMenu}">+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{Binding ModernMenuStatus}" />+ <StackPanel Orientation="Horizontal" Spacing="8">+ <Button Content="{DynamicResource general.modern_menu_add}" Command="{Binding AddModernMenuCommand}" IsVisible="{Binding CanAddModernMenu}" />+ <Button Content="{DynamicResource general.modern_menu_remove}" Command="{Binding RemoveModernMenuCommand}" IsVisible="{Binding CanRemoveModernMenu}" />+ </StackPanel>+ </StackPanel></StackPanel></Border>diff --git a/src/Filee.Core/Platform/IPlatformServices.cs b/src/Filee.Core/Platform/IPlatformServices.csindex e29485a2..e9b4f4a4 100644--- a/src/Filee.Core/Platform/IPlatformServices.cs+++ b/src/Filee.Core/Platform/IPlatformServices.cs@@ -27,10 +27,41 @@ public interface IPlatformServices/// <summary>Adds or removes the file manager context-menu entry ("Convert with Filee") and Send To shortcut.</summary>void SetContextMenu(bool enabled, string executablePath, string label);+ /// <summary>State of the Windows 11 top-level File Explorer menu entry for the app at <paramref name="executablePath"/>.</summary>+ ModernContextMenuState GetModernContextMenuState(string executablePath);++ /// <summary>+ /// Adds (the OS asks for administrator permission once) or removes the Windows 11 top-level menu entry.+ /// Runs in the background and never blocks the calling thread.+ /// </summary>+ Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath);+/// <summary>Opens a folder in the file manager and selects the file, if given.</summary>void RevealInFileManager(string path);}+/// <summary>Whether "Convert with Filee" is in the top-level Windows 11 File Explorer menu (not just "Show more options").</summary>+public enum ModernContextMenuState+{+ /// <summary>Not possible here: another OS, Windows 10, ARM64, or a build without the Explorer extension files.</summary>+ Unsupported,++ /// <summary>Possible but not registered.</summary>+ Off,++ /// <summary>Registered for this installation.</summary>+ On,++ /// <summary>Registered, but for an older package version or another install folder: registering again fixes it.</summary>+ Outdated,+}++/// <summary>Outcome of <see cref="IPlatformServices.SetModernContextMenuAsync"/>.</summary>+/// <param name="Succeeded">True when the entry is now in the requested state.</param>+/// <param name="Cancelled">True when the user declined the administrator prompt.</param>+/// <param name="Error">Why it failed (English, from the OS), when it failed for another reason.</param>+public sealed record ModernContextMenuResult(bool Succeeded, bool Cancelled = false, string? Error = null);+/// <summary>Fallback used on platforms without an implementation yet. Everything is a no-op.</summary>public sealed class NullPlatformServices : IPlatformServices{@@ -41,6 +72,10 @@ public sealed class NullPlatformServices : IPlatformServicespublic bool PrefersReducedMotion => false;public void SetStartWithSystem(bool enabled, string executablePath) { }public void SetContextMenu(bool enabled, string executablePath, string label) { }+ public ModernContextMenuState GetModernContextMenuState(string executablePath) => ModernContextMenuState.Unsupported;++ public Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath) =>+ Task.FromResult(new ModernContextMenuResult(false, Error: "Not supported on this platform."));public void RevealInFileManager(string path){diff --git a/src/Filee.ExplorerMenu/FileeExplorerMenu.c b/src/Filee.ExplorerMenu/FileeExplorerMenu.cnew file mode 100644index 00000000..97075189--- /dev/null+++ b/src/Filee.ExplorerMenu/FileeExplorerMenu.c@@ -0,0 +1,515 @@+// "Convert with Filee" in the top-level Windows 11 File Explorer context menu: a tiny in-process COM server+// (IClassFactory + IExplorerCommand) that Explorer loads through the Filee sparse package. Built with+// build/build-explorer-menu.ps1; the package side lives in src/Filee.Platform.Windows/ExplorerMenu*.cs.+//+// This code runs inside explorer.exe, so it is deliberately small and defensive:+// - no C runtime (linked with -nostdlib): only kernel32/user32/ole32/shell32/shlwapi are used;+// - menu construction (GetTitle/GetState) only reads one tiny local file and shell attributes;+// - Invoke starts Filee.exe next to this DLL and returns immediately (no waiting, no network).++#define WIN32_LEAN_AND_MEAN+#define COBJMACROS+#define CINTERFACE+#include <windows.h>+#include <shobjidl.h>+#include <shlobj.h>+#include <shlwapi.h>++// {6DB0E670-807F-4D22-BE3F-20492D0F4AB1}; must match ExplorerMenuPackage.ClassId (C#) and the package manifest.+static const CLSID kClsidCommand = {0x6db0e670, 0x807f, 0x4d22, {0xbe, 0x3f, 0x20, 0x49, 0x2d, 0x0f, 0x4a, 0xb1}};+// Local copies of the interface and folder ids, so the DLL does not need libuuid.+static const IID kIidUnknown = {0x00000000, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};+static const IID kIidClassFactory = {0x00000001, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};+static const IID kIidExplorerCommand = {0xa08ce4d0, 0xfa25, 0x44ab, {0xb5, 0x7c, 0xc7, 0xb1, 0xc3, 0x23, 0xe0, 0xb9}};+static const KNOWNFOLDERID kFolderRoamingAppData = {0x3eb685db, 0x65f9, 0x4cf6, {0xa0, 0x3a, 0xe3, 0xef, 0x65, 0x72, 0x9f, 0x3d}};++#define DEFAULT_TITLE L"Convert with Filee"+// Written by the app into its data folder (%APPDATA%\Filee, which survives app updates) while the Explorer menu+// setting is on; first line = the title in the UI language. No file = the entry is hidden, so the setting can switch+// the entry off and on again without re-registering the package (which needs administrator rights).+// Must match ExplorerMenuPackage.TitleFileName.+#define TITLE_FILE L"Filee\\explorer-menu.txt"+#define APP_EXE L"Filee.exe"+#define LIST_PREFIX L"Filee-convert-" // CommandLine.ListFilePrefix in the app+// CreateProcess accepts at most 32767 characters; longer selections go through a list file.+#define MAX_COMMAND_LINE 32000++static HMODULE g_module;+static volatile LONG g_locks; // live objects + class factory references + LockServer calls++static BOOL SameGuid(const GUID *a, const GUID *b)+{+ const BYTE *x = (const BYTE *)a;+ const BYTE *y = (const BYTE *)b;+ for (int i = 0; i < (int)sizeof(GUID); i++)+ {+ if (x[i] != y[i])+ return FALSE;+ }+ return TRUE;+}++// ---- Small helpers (no CRT) ------------------------------------------------------------------------------------++/// Growable UTF-16 buffer on the process heap.+typedef struct Text+{+ WCHAR *data;+ SIZE_T length;+ SIZE_T capacity;+ BOOL failed;+} Text;++static void TextAppendN(Text *text, const WCHAR *value, SIZE_T count)+{+ if (text->failed)+ return;+ if (text->length + count + 1 > text->capacity)+ {+ SIZE_T capacity = text->capacity ? text->capacity : 1024;+ while (text->length + count + 1 > capacity)+ capacity *= 2;+ WCHAR *grown = text->data+ ? (WCHAR *)HeapReAlloc(GetProcessHeap(), 0, text->data, capacity * sizeof(WCHAR))+ : (WCHAR *)HeapAlloc(GetProcessHeap(), 0, capacity * sizeof(WCHAR));+ if (!grown)+ {+ text->failed = TRUE;+ return;+ }+ text->data = grown;+ text->capacity = capacity;+ }+ for (SIZE_T i = 0; i < count; i++)+ text->data[text->length + i] = value[i];+ text->length += count;+ text->data[text->length] = 0;+}++static void TextAppend(Text *text, const WCHAR *value)+{+ TextAppendN(text, value, (SIZE_T)lstrlenW(value));+}++static void TextFree(Text *text)+{+ if (text->data)+ HeapFree(GetProcessHeap(), 0, text->data);+ text->data = NULL;+ text->length = text->capacity = 0;+}++/// Full path of a file next to this DLL (the Filee install folder, i.e. the package's external location).+static BOOL PathNextToModule(const WCHAR *name, WCHAR *buffer, DWORD size)+{+ DWORD length = GetModuleFileNameW(g_module, buffer, size);+ if (length == 0 || length >= size)+ return FALSE;+ while (length > 0 && buffer[length - 1] != L'\\')+ length--;+ if (length == 0 || length + (DWORD)lstrlenW(name) >= size)+ return FALSE;+ lstrcpyW(buffer + length, name);+ return TRUE;+}++/// Reads the localized title the app writes into its data folder. Returns FALSE when missing or unusable.+static BOOL ReadTitle(WCHAR *title, int size)+{+ PWSTR folder = NULL;+ if (FAILED(SHGetKnownFolderPath(&kFolderRoamingAppData, 0, NULL, &folder)) || !folder)+ return FALSE;+ WCHAR path[1024];+ BOOL fits = lstrlenW(folder) + 1 + lstrlenW(TITLE_FILE) < (int)ARRAYSIZE(path);+ if (fits)+ {+ lstrcpyW(path, folder);+ lstrcatW(path, L"\\");+ lstrcatW(path, TITLE_FILE);+ }+ CoTaskMemFree(folder);+ if (!fits)+ return FALSE;+ HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,+ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);+ if (file == INVALID_HANDLE_VALUE)+ return FALSE;+ char bytes[512];+ DWORD read = 0;+ BOOL ok = ReadFile(file, bytes, sizeof(bytes) - 1, &read, NULL);+ CloseHandle(file);+ if (!ok)+ return FALSE;++ int start = 0;+ if (read >= 3 && (BYTE)bytes[0] == 0xEF && (BYTE)bytes[1] == 0xBB && (BYTE)bytes[2] == 0xBF)+ start = 3; // UTF-8 byte order mark+ int end = start;+ while (end < (int)read && bytes[end] != '\r' && bytes[end] != '\n')+ end++;+ if (end == start)+ return FALSE;+ int chars = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, bytes + start, end - start, title, size - 1);+ if (chars <= 0)+ return FALSE;+ title[chars] = 0;+ while (chars > 0 && (title[chars - 1] == L' ' || title[chars - 1] == L'\t'))+ title[--chars] = 0;+ return chars > 0;+}++/// Writes the paths (one per line, UTF-8) to a new file in %TEMP% for `Filee.exe --convert-list <file>`.+static BOOL WriteListFile(const Text *lines, WCHAR *path, DWORD size)+{+ WCHAR folder[MAX_PATH + 1];+ DWORD length = GetTempPathW(ARRAYSIZE(folder), folder);+ if (length == 0 || length >= ARRAYSIZE(folder))+ return FALSE;++ int bytes = WideCharToMultiByte(CP_UTF8, 0, lines->data, (int)lines->length, NULL, 0, NULL, NULL);+ if (bytes <= 0)+ return FALSE;+ char *utf8 = (char *)HeapAlloc(GetProcessHeap(), 0, (SIZE_T)bytes);+ if (!utf8)+ return FALSE;+ WideCharToMultiByte(CP_UTF8, 0, lines->data, (int)lines->length, utf8, bytes, NULL, NULL);++ BOOL written = FALSE;+ for (int attempt = 0; attempt < 5 && !written; attempt++)+ {+ if (wsprintfW(path, L"%s" LIST_PREFIX L"%lu-%lu-%d.txt", folder, GetCurrentProcessId(), GetTickCount(), attempt) <= 0+ || (DWORD)lstrlenW(path) >= size)+ break;+ HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, NULL);+ if (file == INVALID_HANDLE_VALUE)+ continue; // name collision: try the next suffix+ DWORD done = 0;+ written = WriteFile(file, utf8, (DWORD)bytes, &done, NULL) && done == (DWORD)bytes;+ CloseHandle(file);+ if (!written)+ DeleteFileW(path);+ }+ HeapFree(GetProcessHeap(), 0, utf8);+ return written;+}++/// Starts Filee.exe with the given command line and returns without waiting for it.+static HRESULT StartFilee(const WCHAR *exe, WCHAR *commandLine)+{+ WCHAR folder[1024];+ lstrcpynW(folder, exe, ARRAYSIZE(folder));+ for (int i = lstrlenW(folder) - 1; i >= 0 && folder[i] != L'\\'; i--)+ folder[i] = 0;++ STARTUPINFOW startup;+ PROCESS_INFORMATION process;+ ZeroMemory(&startup, sizeof(startup));+ ZeroMemory(&process, sizeof(process));+ startup.cb = sizeof(startup);+ if (!CreateProcessW(exe, commandLine, NULL, NULL, FALSE, 0, NULL, folder, &startup, &process))+ return HRESULT_FROM_WIN32(GetLastError());+ // Explorer owns the foreground; let the running Filee bring its donut to the front.+ AllowSetForegroundWindow(process.dwProcessId);+ CloseHandle(process.hThread);+ CloseHandle(process.hProcess);+ return S_OK;+}++// ---- IExplorerCommand ------------------------------------------------------------------------------------------++typedef struct Command+{+ IExplorerCommand iface;+ volatile LONG refs;+} Command;++static HRESULT STDMETHODCALLTYPE Command_QueryInterface(IExplorerCommand *self, REFIID riid, void **result)+{+ if (!result)+ return E_POINTER;+ if (SameGuid(riid, &kIidUnknown) || SameGuid(riid, &kIidExplorerCommand))+ {+ *result = self;+ IExplorerCommand_AddRef(self);+ return S_OK;+ }+ *result = NULL;+ return E_NOINTERFACE;+}++static ULONG STDMETHODCALLTYPE Command_AddRef(IExplorerCommand *self)+{+ return (ULONG)InterlockedIncrement(&((Command *)self)->refs);+}++static ULONG STDMETHODCALLTYPE Command_Release(IExplorerCommand *self)+{+ LONG refs = InterlockedDecrement(&((Command *)self)->refs);+ if (refs == 0)+ {+ HeapFree(GetProcessHeap(), 0, self);+ InterlockedDecrement(&g_locks);+ }+ return (ULONG)refs;+}++static HRESULT STDMETHODCALLTYPE Command_GetTitle(IExplorerCommand *self, IShellItemArray *items, LPWSTR *name)+{+ (void)self;+ (void)items;+ if (!name)+ return E_POINTER;+ *name = NULL;+ WCHAR title[128];+ if (!ReadTitle(title, ARRAYSIZE(title)))+ lstrcpyW(title, DEFAULT_TITLE);+ return SHStrDupW(title, name);+}++static HRESULT STDMETHODCALLTYPE Command_GetIcon(IExplorerCommand *self, IShellItemArray *items, LPWSTR *icon)+{+ (void)self;+ (void)items;+ if (!icon)+ return E_POINTER;+ *icon = NULL;+ WCHAR path[1024];+ if (!PathNextToModule(APP_EXE L",0", path, ARRAYSIZE(path)))+ return E_FAIL;+ return SHStrDupW(path, icon);+}++static HRESULT STDMETHODCALLTYPE Command_GetToolTip(IExplorerCommand *self, IShellItemArray *items, LPWSTR *tip)+{+ (void)self;+ (void)items;+ if (tip)+ *tip = NULL;+ return E_NOTIMPL;+}++static HRESULT STDMETHODCALLTYPE Command_GetCanonicalName(IExplorerCommand *self, GUID *name)+{+ (void)self;+ if (!name)+ return E_POINTER;+ *name = kClsidCommand;+ return S_OK;+}++/// Shown only while the app's setting is on (the title file exists) and every selected item is a file on disk:+/// folders, drives and virtual items (e.g. inside a ZIP folder) have no file-system stream.+static HRESULT STDMETHODCALLTYPE Command_GetState(IExplorerCommand *self, IShellItemArray *items, BOOL okToBeSlow,+ EXPCMDSTATE *state)+{+ (void)self;+ (void)okToBeSlow;+ if (!state)+ return E_POINTER;+ *state = ECS_HIDDEN;+ WCHAR title[128];+ if (!ReadTitle(title, ARRAYSIZE(title)))+ return S_OK;+ const SFGAOF wanted = SFGAO_FILESYSTEM | SFGAO_STREAM;+ SFGAOF attributes = 0;+ if (items && SUCCEEDED(IShellItemArray_GetAttributes(items, SIATTRIBFLAGS_AND, wanted, &attributes))+ && (attributes & wanted) == wanted)+ *state = ECS_ENABLED;+ return S_OK;+}++static HRESULT STDMETHODCALLTYPE Command_Invoke(IExplorerCommand *self, IShellItemArray *items, IBindCtx *context)+{+ (void)self;+ (void)context;+ if (!items)+ return E_INVALIDARG;+ WCHAR exe[1024];+ if (!PathNextToModule(APP_EXE, exe, ARRAYSIZE(exe)))+ return E_FAIL;++ DWORD count = 0;+ HRESULT hr = IShellItemArray_GetCount(items, &count);+ if (FAILED(hr))+ return hr;++ // Build both forms at once: quoted arguments for the usual case, one path per line for huge selections.+ Text args = {0};+ Text lines = {0};+ TextAppend(&args, L"\"");+ TextAppend(&args, exe);+ TextAppend(&args, L"\" --convert");+ DWORD added = 0;+ for (DWORD i = 0; i < count; i++)+ {+ IShellItem *item = NULL;+ if (FAILED(IShellItemArray_GetItemAt(items, i, &item)))+ continue;+ LPWSTR path = NULL;+ if (SUCCEEDED(IShellItem_GetDisplayName(item, SIGDN_FILESYSPATH, &path)) && path)+ {+ TextAppend(&args, L" \"");+ TextAppend(&args, path);+ TextAppend(&args, L"\"");+ TextAppend(&lines, path);+ TextAppend(&lines, L"\r\n");+ added++;+ CoTaskMemFree(path);+ }+ IShellItem_Release(item);+ }++ if (args.failed || lines.failed)+ hr = E_OUTOFMEMORY;+ else if (added == 0)+ hr = S_FALSE;+ else if (args.length < MAX_COMMAND_LINE)+ hr = StartFilee(exe, args.data);+ else+ {+ WCHAR list[MAX_PATH + 64];+ hr = E_FAIL;+ if (WriteListFile(&lines, list, ARRAYSIZE(list)))+ {+ Text command = {0};+ TextAppend(&command, L"\"");+ TextAppend(&command, exe);+ TextAppend(&command, L"\" --convert-list \"");+ TextAppend(&command, list);+ TextAppend(&command, L"\"");+ hr = command.failed ? E_OUTOFMEMORY : StartFilee(exe, command.data);+ if (FAILED(hr))+ DeleteFileW(list);+ TextFree(&command);+ }+ }+ TextFree(&args);+ TextFree(&lines);+ return hr;+}++static HRESULT STDMETHODCALLTYPE Command_GetFlags(IExplorerCommand *self, EXPCMDFLAGS *flags)+{+ (void)self;+ if (!flags)+ return E_POINTER;+ *flags = ECF_DEFAULT;+ return S_OK;+}++static HRESULT STDMETHODCALLTYPE Command_EnumSubCommands(IExplorerCommand *self, IEnumExplorerCommand **commands)+{+ (void)self;+ if (commands)+ *commands = NULL;+ return E_NOTIMPL;+}++static IExplorerCommandVtbl g_commandVtbl = {+ Command_QueryInterface,+ Command_AddRef,+ Command_Release,+ Command_GetTitle,+ Command_GetIcon,+ Command_GetToolTip,+ Command_GetCanonicalName,+ Command_GetState,+ Command_Invoke,+ Command_GetFlags,+ Command_EnumSubCommands,+};++// ---- IClassFactory (a single static instance) ------------------------------------------------------------------++static HRESULT STDMETHODCALLTYPE Factory_QueryInterface(IClassFactory *self, REFIID riid, void **result)+{+ if (!result)+ return E_POINTER;+ if (SameGuid(riid, &kIidUnknown) || SameGuid(riid, &kIidClassFactory))+ {+ *result = self;+ IClassFactory_AddRef(self);+ return S_OK;+ }+ *result = NULL;+ return E_NOINTERFACE;+}++static ULONG STDMETHODCALLTYPE Factory_AddRef(IClassFactory *self)+{+ (void)self;+ return (ULONG)InterlockedIncrement(&g_locks);+}++static ULONG STDMETHODCALLTYPE Factory_Release(IClassFactory *self)+{+ (void)self;+ return (ULONG)InterlockedDecrement(&g_locks);+}++static HRESULT STDMETHODCALLTYPE Factory_CreateInstance(IClassFactory *self, IUnknown *outer, REFIID riid, void **result)+{+ (void)self;+ if (!result)+ return E_POINTER;+ *result = NULL;+ if (outer)+ return CLASS_E_NOAGGREGATION;+ Command *command = (Command *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(Command));+ if (!command)+ return E_OUTOFMEMORY;+ command->iface.lpVtbl = &g_commandVtbl;+ command->refs = 1;+ InterlockedIncrement(&g_locks);+ HRESULT hr = Command_QueryInterface(&command->iface, riid, result);+ Command_Release(&command->iface); // the caller's reference (if any) keeps it alive+ return hr;+}++static HRESULT STDMETHODCALLTYPE Factory_LockServer(IClassFactory *self, BOOL lock)+{+ (void)self;+ if (lock)+ InterlockedIncrement(&g_locks);+ else+ InterlockedDecrement(&g_locks);+ return S_OK;+}++static IClassFactoryVtbl g_factoryVtbl = {+ Factory_QueryInterface,+ Factory_AddRef,+ Factory_Release,+ Factory_CreateInstance,+ Factory_LockServer,+};+static IClassFactory g_factory = {&g_factoryVtbl};++// ---- DLL exports -----------------------------------------------------------------------------------------------++HRESULT __stdcall DllGetClassObject(REFCLSID clsid, REFIID riid, void **result)+{+ if (!result)+ return E_POINTER;+ *result = NULL;+ if (!SameGuid(clsid, &kClsidCommand))+ return CLASS_E_CLASSNOTAVAILABLE;+ return Factory_QueryInterface(&g_factory, riid, result);+}++HRESULT __stdcall DllCanUnloadNow(void)+{+ return g_locks == 0 ? S_OK : S_FALSE;+}++// Entry point (there is no C runtime to initialise).+BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved)+{+ (void)reserved;+ if (reason == DLL_PROCESS_ATTACH)+ {+ g_module = instance;+ DisableThreadLibraryCalls(instance);+ }+ return TRUE;+}diff --git a/src/Filee.ExplorerMenu/FileeExplorerMenu.def b/src/Filee.ExplorerMenu/FileeExplorerMenu.defnew file mode 100644index 00000000..069d3167--- /dev/null+++ b/src/Filee.ExplorerMenu/FileeExplorerMenu.def@@ -0,0 +1,5 @@+; Exports of the Explorer context-menu COM server (see FileeExplorerMenu.c).+LIBRARY FileeExplorerMenu+EXPORTS+ DllGetClassObject PRIVATE+ DllCanUnloadNow PRIVATEdiff --git a/src/Filee.ExplorerMenu/FileeExplorerMenu.rc b/src/Filee.ExplorerMenu/FileeExplorerMenu.rcnew file mode 100644index 00000000..ec0ef221--- /dev/null+++ b/src/Filee.ExplorerMenu/FileeExplorerMenu.rc@@ -0,0 +1,40 @@+// Version information of the Explorer context-menu DLL. build/build-explorer-menu.ps1 passes the app version as+// FILEE_VERSION_MAJOR/MINOR/PATCH and FILEE_VERSION_TEXT.++#include <winver.h>++#ifndef FILEE_VERSION_MAJOR+#define FILEE_VERSION_MAJOR 0+#define FILEE_VERSION_MINOR 0+#define FILEE_VERSION_PATCH 0+#define FILEE_VERSION_TEXT "0.0.0"+#endif++VS_VERSION_INFO VERSIONINFO+FILEVERSION FILEE_VERSION_MAJOR, FILEE_VERSION_MINOR, FILEE_VERSION_PATCH, 0+PRODUCTVERSION FILEE_VERSION_MAJOR, FILEE_VERSION_MINOR, FILEE_VERSION_PATCH, 0+FILEFLAGSMASK VS_FFI_FILEFLAGSMASK+FILEFLAGS 0+FILEOS VOS_NT_WINDOWS32+FILETYPE VFT_DLL+FILESUBTYPE VFT2_UNKNOWN+BEGIN+ BLOCK "StringFileInfo"+ BEGIN+ BLOCK "040904B0"+ BEGIN+ VALUE "CompanyName", "Filee contributors"+ VALUE "FileDescription", "Filee File Explorer context menu"+ VALUE "FileVersion", FILEE_VERSION_TEXT+ VALUE "InternalName", "FileeExplorerMenu"+ VALUE "LegalCopyright", "Copyright (c) Filee contributors. MIT License."+ VALUE "OriginalFilename", "FileeExplorerMenu.dll"+ VALUE "ProductName", "Filee"+ VALUE "ProductVersion", FILEE_VERSION_TEXT+ END+ END+ BLOCK "VarFileInfo"+ BEGIN+ VALUE "Translation", 0x0409, 1200+ END+ENDdiff --git a/src/Filee.Platform.Windows/ExplorerMenuPackage.cs b/src/Filee.Platform.Windows/ExplorerMenuPackage.csnew file mode 100644index 00000000..a4da7b42--- /dev/null+++ b/src/Filee.Platform.Windows/ExplorerMenuPackage.cs@@ -0,0 +1,145 @@+// The sparse ("packaged with external location") MSIX that puts "Convert with Filee" into the top-level Windows 11+// File Explorer context menu. The package holds only AppxManifest.xml and a logo; the COM server it declares is the+// native FileeExplorerMenu.dll in the Filee install folder (src/Filee.ExplorerMenu).++using System.Globalization;+using System.Xml.Linq;++namespace Filee.Platform.Windows;++/// <summary>+/// Identity, file names and manifest of the Explorer context-menu package. build/tools/make-explorer-package.cs packs+/// <see cref="CreateManifest"/> at build time; <see cref="ExplorerMenuRegistration"/> registers the result.+/// </summary>+public static class ExplorerMenuPackage+{+ /// <summary>Package name (the <c>Identity/@Name</c>); also used to find and remove the registration.</summary>+ public const string PackageName = "Filee.ExplorerMenu";++ /// <summary>+ /// Publisher of the unsigned package. Windows 11 only registers unsigned packages whose publisher contains this+ /// special OID, so they can never collide with (or spoof) a signed package.+ /// </summary>+ public const string Publisher = "CN=Filee, OID.2.25.311729368913984317654407730594956997722=1";++ /// <summary>+ /// Package family name = name + "_" + a hash of <see cref="Publisher"/> (checked by a test against+ /// <c>PackageFamilyNameFromId</c>). Used to look the registration up without PowerShell.+ /// </summary>+ public const string FamilyName = "Filee.ExplorerMenu_c73vxh346rtay";++ /// <summary>+ /// Version of the manifest, deliberately independent of the app version: registering an unsigned package with a+ /// COM server needs administrator rights, so the package must stay valid across app updates (the DLL itself is+ /// loaded from the install folder and is updated with the app). Bump it only when the manifest changes; the app+ /// then offers to register again.+ /// </summary>+ public static readonly Version ManifestVersion = new(1, 0, 0, 0);++ /// <summary>CLSID of the IExplorerCommand in FileeExplorerMenu.dll (kClsidCommand in FileeExplorerMenu.c).</summary>+ public static readonly Guid ClassId = new("6DB0E670-807F-4D22-BE3F-20492D0F4AB1");++ /// <summary>The native COM server next to Filee.exe.</summary>+ public const string DllFileName = "FileeExplorerMenu.dll";++ /// <summary>The package file next to Filee.exe.</summary>+ public const string PackageFileName = "FileeExplorerMenu.msix";++ /// <summary>+ /// File in the data folder (%APPDATA%\Filee, TITLE_FILE in FileeExplorerMenu.c) whose first line is the menu title+ /// in the UI language. It exists while the Explorer menu setting is on; without it the DLL hides the entry.+ /// </summary>+ public const string TitleFileName = "explorer-menu.txt";++ /// <summary>Processor architecture of the DLL (it is loaded into explorer.exe, so it must match Explorer).</summary>+ public const string Architecture = "x64";++ /// <summary>Windows 11 (build 22000) is the first version with the new context menu and unsigned packages.</summary>+ public const int MinimumBuild = 22000;++ /// <summary>Path of the logo inside the package (shown in package lists only; the menu uses Filee.exe's icon).</summary>+ public const string LogoPath = @"Assets\Logo.png";++ private static readonly XNamespace Foundation = "http://schemas.microsoft.com/appx/manifest/foundation/windows10";+ private static readonly XNamespace Uap = "http://schemas.microsoft.com/appx/manifest/uap/windows10";+ private static readonly XNamespace Uap10 = "http://schemas.microsoft.com/appx/manifest/uap/windows10/10";+ private static readonly XNamespace Desktop4 = "http://schemas.microsoft.com/appx/manifest/desktop/windows10/4";+ private static readonly XNamespace Desktop5 = "http://schemas.microsoft.com/appx/manifest/desktop/windows10/5";+ private static readonly XNamespace Com = "http://schemas.microsoft.com/appx/manifest/com/windows10";+ private static readonly XNamespace Rescap = "http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities";++ /// <summary>+ /// Builds AppxManifest.xml. Paths in it (Filee.exe, the DLL) are relative to the external location, i.e. the+ /// install folder given at registration.+ /// </summary>+ public static string CreateManifest()+ {+ var clsid = ClassId.ToString("D").ToUpperInvariant();+ var package = new XElement(Foundation + "Package",+ new XAttribute("xmlns", Foundation.NamespaceName),+ new XAttribute(XNamespace.Xmlns + "uap", Uap),+ new XAttribute(XNamespace.Xmlns + "uap10", Uap10),+ new XAttribute(XNamespace.Xmlns + "desktop4", Desktop4),+ new XAttribute(XNamespace.Xmlns + "desktop5", Desktop5),+ new XAttribute(XNamespace.Xmlns + "com", Com),+ new XAttribute(XNamespace.Xmlns + "rescap", Rescap),+ new XAttribute("IgnorableNamespaces", "uap uap10 desktop4 desktop5 com rescap"),+ new XElement(Foundation + "Identity",+ new XAttribute("Name", PackageName),+ new XAttribute("Publisher", Publisher),+ new XAttribute("Version", ManifestVersion.ToString(4)),+ new XAttribute("ProcessorArchitecture", Architecture)),+ new XElement(Foundation + "Properties",+ new XElement(Foundation + "DisplayName", "Filee"),+ new XElement(Foundation + "PublisherDisplayName", "Filee contributors"),+ new XElement(Foundation + "Logo", LogoPath),+ new XElement(Uap10 + "AllowExternalContent", "true")),+ new XElement(Foundation + "Resources",+ new XElement(Foundation + "Resource", new XAttribute("Language", "en-us"))),+ new XElement(Foundation + "Dependencies",+ new XElement(Foundation + "TargetDeviceFamily",+ new XAttribute("Name", "Windows.Desktop"),+ new XAttribute("MinVersion", "10.0." + MinimumBuild.ToString(CultureInfo.InvariantCulture) + ".0"),+ new XAttribute("MaxVersionTested", "10.0.26100.0"))),+ new XElement(Foundation + "Capabilities",+ new XElement(Rescap + "Capability", new XAttribute("Name", "runFullTrust")),+ new XElement(Rescap + "Capability", new XAttribute("Name", "unvirtualizedResources"))),+ new XElement(Foundation + "Applications",+ new XElement(Foundation + "Application",+ new XAttribute("Id", "Filee"),+ new XAttribute("Executable", "Filee.exe"),+ new XAttribute(Uap10 + "TrustLevel", "mediumIL"),+ new XAttribute(Uap10 + "RuntimeBehavior", "win32App"),+ // AppListEntry="none": the package only carries the shell extension, it adds no Start menu entry.+ new XElement(Uap + "VisualElements",+ new XAttribute("AppListEntry", "none"),+ new XAttribute("DisplayName", "Filee"),+ new XAttribute("Description", "Filee File Explorer integration"),+ new XAttribute("BackgroundColor", "transparent"),+ new XAttribute("Square150x150Logo", LogoPath),+ new XAttribute("Square44x44Logo", LogoPath)),+ new XElement(Foundation + "Extensions",+ // Type="*": files only (folders would be "Directory"); the DLL additionally hides the+ // command for virtual items (e.g. inside a ZIP folder) and mixed selections.+ new XElement(Desktop4 + "Extension",+ new XAttribute("Category", "windows.fileExplorerContextMenus"),+ new XElement(Desktop4 + "FileExplorerContextMenus",+ new XElement(Desktop5 + "ItemType",+ new XAttribute("Type", "*"),+ new XElement(Desktop5 + "Verb",+ new XAttribute("Id", "ConvertWithFilee"),+ new XAttribute("Clsid", clsid))))),+ new XElement(Com + "Extension",+ new XAttribute("Category", "windows.comServer"),+ new XElement(Com + "ComServer",+ new XElement(Com + "SurrogateServer",+ new XAttribute("DisplayName", "Filee context menu"),+ new XElement(Com + "Class",+ new XAttribute("Id", clsid),+ new XAttribute("Path", DllFileName),+ new XAttribute("ThreadingModel", "STA")))))))));++ var document = new XDocument(new XDeclaration("1.0", "utf-8", null), package);+ return document.Declaration + Environment.NewLine + document.Root;+ }+}diff --git a/src/Filee.Platform.Windows/ExplorerMenuRegistration.cs b/src/Filee.Platform.Windows/ExplorerMenuRegistration.csnew file mode 100644index 00000000..e3f81368--- /dev/null+++ b/src/Filee.Platform.Windows/ExplorerMenuRegistration.cs@@ -0,0 +1,303 @@+// Registers and removes the Windows 11 File Explorer menu package (ExplorerMenuPackage) and reports its state.+// Windows accepts an unsigned package that contains a COM server only when it is added with administrator rights+// (it is then installed for all users), so adding goes through one UAC prompt; state queries are kernel32 calls.++using System.ComponentModel;+using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Runtime.Versioning;+using System.Text;+using Filee.Core.Platform;+using Filee.Core.Settings;++namespace Filee.Platform.Windows;++/// <summary>Adds, removes and inspects the Explorer menu package for the current user.</summary>+[SupportedOSPlatform("windows")]+public static class ExplorerMenuRegistration+{+ /// <summary>Win32 ERROR_CANCELLED: the user declined the UAC prompt.</summary>+ private const int ErrorCancelled = 1223;++ /// <summary>Add-AppxPackage usually takes a few seconds; after this the attempt counts as failed.</summary>+ private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(3);++ /// <summary>A registered copy of the package.</summary>+ /// <param name="FullName">Package full name, e.g. <c>Filee.ExplorerMenu_1.0.0.0_x64__c73vxh346rtay</c>.</param>+ /// <param name="Version">Identity version from the full name.</param>+ /// <param name="ExternalLocation">Folder the package points at (null when Windows does not say).</param>+ public sealed record RegisteredPackage(string FullName, Version Version, string? ExternalLocation);++ /// <summary>Windows 11 on x64: the new context menu exists and Explorer can load the x64 DLL.</summary>+ public static bool IsSupportedOs =>+ OperatingSystem.IsWindowsVersionAtLeast(10, 0, ExplorerMenuPackage.MinimumBuild)+ && RuntimeInformation.OSArchitecture == Architecture.X64;++ /// <summary>The title file the DLL reads (see <see cref="ExplorerMenuPackage.TitleFileName"/>).</summary>+ public static string TitleFilePath => Path.Combine(UserDataStore.DefaultDirectory, ExplorerMenuPackage.TitleFileName);++ /// <summary>True when the DLL and the package were shipped next to Filee.exe (installed builds).</summary>+ public static bool HasFiles(string installFolder) =>+ File.Exists(Path.Combine(installFolder, ExplorerMenuPackage.DllFileName))+ && File.Exists(Path.Combine(installFolder, ExplorerMenuPackage.PackageFileName));++ /// <summary>State of the top-level menu entry for the Filee in <paramref name="installFolder"/>.</summary>+ public static ModernContextMenuState GetState(string installFolder)+ {+ if (!IsSupportedOs || !HasFiles(installFolder))+ return ModernContextMenuState.Unsupported;+ var package = Find();+ if (package is null)+ return ModernContextMenuState.Off;+ var sameFolder = package.ExternalLocation is null || SamePath(package.ExternalLocation, installFolder);+ return sameFolder && package.Version >= ExplorerMenuPackage.ManifestVersion+ ? ModernContextMenuState.On+ : ModernContextMenuState.Outdated;+ }++ /// <summary>The package as registered for the current user, or null.</summary>+ public static unsafe RegisteredPackage? Find()+ {+ uint count = 0, length = 0;+ var rc = NativeMethods.GetPackagesByPackageFamily(ExplorerMenuPackage.FamilyName, ref count, null, ref length, null);+ if (rc != NativeMethods.ERROR_INSUFFICIENT_BUFFER || count == 0)+ return null;++ var names = new nint[count];+ var buffer = new char[length];+ string fullName;+ fixed (nint* pNames = names)+ fixed (char* pBuffer = buffer)+ {+ if (NativeMethods.GetPackagesByPackageFamily(ExplorerMenuPackage.FamilyName, ref count, (char**)pNames, ref length, pBuffer) != 0+ || count == 0)+ return null;+ fullName = new string((char*)pNames[0]);+ }++ // Full name = Name_Version_Architecture_ResourceId_PublisherId.+ var parts = fullName.Split('_');+ var version = parts.Length > 1 && Version.TryParse(parts[1], out var v) ? v : new Version(0, 0);+ return new RegisteredPackage(fullName, version, ExternalLocationOf(fullName));+ }++ /// <summary>+ /// Shows the entry with this title (the UI language), or hides it (<c>null</c>). The DLL reads the file on every+ /// right-click, so this takes effect immediately and needs no administrator rights.+ /// </summary>+ public static void SetTitle(string? title)+ {+ var path = TitleFilePath;+ if (title is null)+ {+ if (File.Exists(path))+ File.Delete(path);+ return;+ }+ var content = title.ReplaceLineEndings(" ").Trim() + "\r\n";+ if (File.Exists(path) && File.ReadAllText(path, Encoding.UTF8) == content)+ return;+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ File.WriteAllText(path, content, new UTF8Encoding(false));+ }++ /// <summary>The current title, or null when the entry is switched off.</summary>+ public static string? ReadTitle()+ {+ try+ {+ var path = TitleFilePath;+ return File.Exists(path) ? File.ReadLines(path, Encoding.UTF8).FirstOrDefault()?.Trim() : null;+ }+ catch (IOException)+ {+ return null;+ }+ }++ /// <summary>Registers the package that ships next to Filee.exe, with the install folder as external location.</summary>+ public static async Task<ModernContextMenuResult> AddAsync(string installFolder)+ {+ if (!IsSupportedOs)+ return new ModernContextMenuResult(false, Error: "The top-level Explorer menu needs Windows 11 (x64).");+ if (!HasFiles(installFolder))+ return new ModernContextMenuResult(false, Error: $"{ExplorerMenuPackage.PackageFileName} or {ExplorerMenuPackage.DllFileName} is missing in {installFolder}.");++ var package = Path.Combine(installFolder, ExplorerMenuPackage.PackageFileName);+ var result = await RunPowerShellAsync(errorFile => BuildAddScript(package, installFolder, errorFile), elevated: true);+ if (result.Succeeded && GetState(installFolder) != ModernContextMenuState.On)+ {+ return new ModernContextMenuResult(false, Error:+ "Windows accepted the package, but it is not registered for this user account (was another administrator account used?).");+ }+ return result;+ }++ /// <summary>+ /// Removes the package for the current user. Normally no administrator rights are needed; with+ /// <paramref name="allowElevation"/> a failed attempt is repeated through a UAC prompt.+ /// </summary>+ public static async Task<ModernContextMenuResult> RemoveAsync(bool allowElevation)+ {+ if (Find() is null)+ return new ModernContextMenuResult(true);+ var result = await RunPowerShellAsync(BuildRemoveScript, elevated: false);+ if (!result.Succeeded && allowElevation && Find() is not null)+ result = await RunPowerShellAsync(BuildRemoveScript, elevated: true);+ return result.Succeeded && Find() is not null+ ? new ModernContextMenuResult(false, Error: "The package is still registered.")+ : result;+ }++ /// <summary>PowerShell that registers the package and writes the error message to <paramref name="errorFile"/>.</summary>+ public static string BuildAddScript(string packagePath, string externalLocation, string errorFile) =>+ WrapScript(+ $"Add-AppxPackage -Path {Quote(packagePath)} -ExternalLocation {Quote(externalLocation)} -AllowUnsigned -ForceUpdateFromAnyVersion",+ errorFile);++ /// <summary>PowerShell that removes every registered version of the package.</summary>+ public static string BuildRemoveScript(string errorFile) =>+ WrapScript($"Get-AppxPackage -Name {Quote(ExplorerMenuPackage.PackageName)} | Remove-AppxPackage", errorFile);++ /// <summary>+ /// Start info for Windows PowerShell (part of Windows; the Appx cmdlets are not in PowerShell 7 everywhere).+ /// The script goes in as plain <c>-Command</c> text rather than <c>-EncodedCommand</c>, which security software+ /// tends to distrust; it only contains single-quoted strings, so wrapping it in double quotes is safe.+ /// </summary>+ public static ProcessStartInfo CreateStartInfo(string script, bool elevated)+ {+ if (script.Contains('"'))+ throw new ArgumentException("The script must not contain double quotes.", nameof(script));+ var info = new ProcessStartInfo(+ Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"),+ $"-NoLogo -NoProfile -NonInteractive -Command \"{script}\"");+ if (elevated)+ {+ info.UseShellExecute = true;+ info.Verb = "runas";+ info.WindowStyle = ProcessWindowStyle.Hidden;+ }+ else+ {+ info.UseShellExecute = false;+ info.CreateNoWindow = true;+ }+ return info;+ }++ /// <summary>+ /// A PowerShell single-quoted string literal. PowerShell also treats the typographic quotes ‘ ’ ‚ ‛ as single+ /// quotes (a folder may be called "Kim’s PC"), so those are doubled as well.+ /// </summary>+ public static string Quote(string value)+ {+ var builder = new StringBuilder(value.Length + 2).Append('\'');+ foreach (var c in value)+ {+ builder.Append(c);+ if (c is '\'' or '‘' or '’' or '‚' or '‛')+ builder.Append(c);+ }+ return builder.Append('\'').ToString();+ }++ /// <summary>Family name computed by Windows from the package name and publisher (to check <see cref="ExplorerMenuPackage.FamilyName"/>).</summary>+ public static unsafe string ComputeFamilyName()+ {+ fixed (char* name = ExplorerMenuPackage.PackageName)+ fixed (char* publisher = ExplorerMenuPackage.Publisher)+ {+ var id = new NativeMethods.PACKAGE_ID { Name = name, Publisher = publisher };+ uint length = 0;+ var rc = NativeMethods.PackageFamilyNameFromId(&id, ref length, null);+ if (rc != NativeMethods.ERROR_INSUFFICIENT_BUFFER)+ throw new Win32Exception(rc);+ var buffer = new char[length];+ fixed (char* pBuffer = buffer)+ {+ rc = NativeMethods.PackageFamilyNameFromId(&id, ref length, pBuffer);+ if (rc != 0)+ throw new Win32Exception(rc);+ return new string(pBuffer);+ }+ }+ }++ private static string WrapScript(string command, string errorFile) =>+ $"$ErrorActionPreference = 'Stop'; try {{ {command}; exit 0 }} " ++ $"catch {{ [IO.File]::WriteAllText({Quote(errorFile)}, $_.Exception.Message); exit 1 }}";++ private static async Task<ModernContextMenuResult> RunPowerShellAsync(Func<string, string> buildScript, bool elevated)+ {+ var errorFile = Path.Combine(Path.GetTempPath(), $"Filee-explorer-menu-{Guid.NewGuid():N}.txt");+ try+ {+ using var process = Process.Start(CreateStartInfo(buildScript(errorFile), elevated));+ if (process is null)+ return new ModernContextMenuResult(false, Error: "PowerShell did not start.");+ using var timeout = new CancellationTokenSource(Timeout);+ try+ {+ await process.WaitForExitAsync(timeout.Token);+ }+ catch (OperationCanceledException)+ {+ if (!elevated)+ process.Kill();+ return new ModernContextMenuResult(false, Error: "Windows did not finish within " + Timeout.TotalMinutes + " minutes.");+ }+ if (process.ExitCode == 0)+ return new ModernContextMenuResult(true);+ var message = File.Exists(errorFile) ? ShortenDeploymentError(File.ReadAllText(errorFile)) : "";+ return new ModernContextMenuResult(false, Error: message.Length > 0 ? message : $"PowerShell exit code {process.ExitCode}.");+ }+ catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled)+ {+ return new ModernContextMenuResult(false, Cancelled: true);+ }+ catch (Win32Exception ex)+ {+ return new ModernContextMenuResult(false, Error: ex.Message);+ }+ finally+ {+ try+ {+ File.Delete(errorFile);+ }+ catch (IOException) { }+ catch (UnauthorizedAccessException) { }+ }+ }++ /// <summary>+ /// Deployment errors end with "NOTE: For additional information, look for [ActivityId] ..." and span several+ /// lines; the UI shows one paragraph without that tail.+ /// </summary>+ public static string ShortenDeploymentError(string message)+ {+ var note = message.IndexOf("NOTE: For additional information", StringComparison.Ordinal);+ if (note >= 0)+ message = message[..note];+ return string.Join(' ', message.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));+ }++ private static unsafe string? ExternalLocationOf(string fullName)+ {+ uint length = 0;+ if (NativeMethods.GetPackagePathByFullName2(fullName, NativeMethods.PackagePathType_EffectiveExternal, ref length, null)+ != NativeMethods.ERROR_INSUFFICIENT_BUFFER || length == 0)+ return null;+ var buffer = new char[length];+ fixed (char* pBuffer = buffer)+ {+ return NativeMethods.GetPackagePathByFullName2(fullName, NativeMethods.PackagePathType_EffectiveExternal, ref length, pBuffer) == 0+ ? new string(pBuffer)+ : null;+ }+ }++ private static bool SamePath(string a, string b) =>+ string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(a)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(b)),+ StringComparison.OrdinalIgnoreCase);+}diff --git a/src/Filee.Platform.Windows/NativeMethods.cs b/src/Filee.Platform.Windows/NativeMethods.csindex 8fcef88d..592de999 100644--- a/src/Filee.Platform.Windows/NativeMethods.cs+++ b/src/Filee.Platform.Windows/NativeMethods.cs@@ -39,6 +39,31 @@ internal static partial class NativeMethods[return: MarshalAs(UnmanagedType.Bool)]public static partial bool SystemParametersInfo(uint action, uint param, [MarshalAs(UnmanagedType.Bool)] out bool value, uint winIni);+ // Package queries (appmodel.h, Windows 8+ / PackagePathType_EffectiveExternal: Windows 10 2004+).+ public const int ERROR_INSUFFICIENT_BUFFER = 122;+ public const int PackagePathType_EffectiveExternal = 5;++ [StructLayout(LayoutKind.Sequential, Pack = 4)]+ public unsafe struct PACKAGE_ID+ {+ public uint Reserved;+ public uint ProcessorArchitecture;+ public ulong Version;+ public char* Name;+ public char* Publisher;+ public char* ResourceId;+ public char* PublisherId;+ }++ [LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)]+ public static unsafe partial int GetPackagesByPackageFamily(string packageFamilyName, ref uint count, char** packageFullNames, ref uint bufferLength, char* buffer);++ [LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)]+ public static unsafe partial int GetPackagePathByFullName2(string packageFullName, int packagePathType, ref uint pathLength, char* path);++ [LibraryImport("kernel32.dll")]+ public static unsafe partial int PackageFamilyNameFromId(PACKAGE_ID* packageId, ref uint packageFamilyNameLength, char* packageFamilyName);+/// <summary>Returns the Win32 class name of a window ("CabinetWClass" for Explorer, ...).</summary>public static string ClassNameOf(nint hwnd){diff --git a/src/Filee.Platform.Windows/WindowsPlatformServices.cs b/src/Filee.Platform.Windows/WindowsPlatformServices.csindex 81db09aa..ce4a28be 100644--- a/src/Filee.Platform.Windows/WindowsPlatformServices.cs+++ b/src/Filee.Platform.Windows/WindowsPlatformServices.cs@@ -114,32 +114,72 @@ public sealed class WindowsPlatformServices : IPlatformServices/// <summary>/// Registers a per-user "Convert with Filee" verb for all files (no admin rights needed) and a Send To shortcut.- /// On Windows 11 the verb appears under "Show more options"; a top-level entry needs a packaged- /// IExplorerCommand, which is planned for a later version.+ /// On Windows 11 the classic verb appears under "Show more options"; the top-level entry is the packaged+ /// IExplorerCommand (<see cref="ExplorerMenuRegistration"/>), which this switches on and off through its title file.+ /// When that package is registered the classic verb is removed, because Windows also lists the packaged command+ /// under "Show more options" and the entry would appear twice there./// </summary>public void SetContextMenu(bool enabled, string executablePath, string label){+ if (ExplorerMenuRegistration.IsSupportedOs)+ ExplorerMenuRegistration.SetTitle(enabled ? label : null);+if (!enabled){- Registry.CurrentUser.DeleteSubKeyTree(ContextMenuKey, throwOnMissingSubKey: false);+ RemoveClassicVerb();TryDelete(SendToShortcutPath);return;}- using (var verb = Registry.CurrentUser.CreateSubKey(ContextMenuKey))+ if (GetModernContextMenuState(executablePath) == ModernContextMenuState.On)+ RemoveClassicVerb();+ else+ WriteClassicVerb(executablePath, label);++ CreateShortcut(SendToShortcutPath, executablePath, "--convert", label);+ }++ public ModernContextMenuState GetModernContextMenuState(string executablePath) =>+ Path.GetDirectoryName(executablePath) is { Length: > 0 } folder+ ? ExplorerMenuRegistration.GetState(folder)+ : ModernContextMenuState.Unsupported;++ public Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath) => Task.Run(async () =>+ {+ var folder = Path.GetDirectoryName(executablePath);+ if (string.IsNullOrEmpty(folder))+ return new ModernContextMenuResult(false, Error: "Unknown install folder.");++ var result = enabled+ ? await ExplorerMenuRegistration.AddAsync(folder)+ : await ExplorerMenuRegistration.RemoveAsync(allowElevation: true);++ // Keep exactly one entry: the title file exists while the Explorer menu setting is on.+ if (ExplorerMenuRegistration.ReadTitle() is { Length: > 0 } title){- verb.SetValue("MUIVerb", label);- verb.SetValue("Icon", $"\"{executablePath}\",0");- // "Player": Explorer invokes the verb once per selected file; the running instance- // collects the calls (see SingleInstance / --convert handling in the app).- verb.SetValue("MultiSelectModel", "Player");- using var command = verb.CreateSubKey("command");- command.SetValue(null, $"\"{executablePath}\" --convert \"%1\"");+ if (GetModernContextMenuState(executablePath) == ModernContextMenuState.On)+ RemoveClassicVerb();+ else+ WriteClassicVerb(executablePath, title);}+ return result;+ });- CreateShortcut(SendToShortcutPath, executablePath, "--convert", label);+ private static void WriteClassicVerb(string executablePath, string label)+ {+ using var verb = Registry.CurrentUser.CreateSubKey(ContextMenuKey);+ verb.SetValue("MUIVerb", label);+ verb.SetValue("Icon", $"\"{executablePath}\",0");+ // "Player": Explorer invokes the verb once per selected file; the running instance+ // collects the calls (see SingleInstance / --convert handling in the app).+ verb.SetValue("MultiSelectModel", "Player");+ using var command = verb.CreateSubKey("command");+ command.SetValue(null, $"\"{executablePath}\" --convert \"%1\"");}+ private static void RemoveClassicVerb() =>+ Registry.CurrentUser.DeleteSubKeyTree(ContextMenuKey, throwOnMissingSubKey: false);+public void RevealInFileManager(string path){var args = File.Exists(path) ? $"/select,\"{path}\"" : $"\"{path}\"";diff --git a/tests/Filee.App.Tests/ExplorerMenuTests.cs b/tests/Filee.App.Tests/ExplorerMenuTests.csnew file mode 100644index 00000000..8daf4eb7--- /dev/null+++ b/tests/Filee.App.Tests/ExplorerMenuTests.cs@@ -0,0 +1,311 @@+// Tests for the Windows 11 File Explorer menu: package manifest, registration scripts, the --convert-list hand-over+// and (when build/build-explorer-menu.ps1 has run) the native FileeExplorerMenu.dll loaded in-process.++using System.Globalization;+using System.IO.Compression;+using System.Runtime.InteropServices;+using System.Runtime.Versioning;+using System.Text.RegularExpressions;+using System.Xml.Linq;+using Filee.App.Services;+using Filee.Platform.Windows;++namespace Filee.App.Tests;++// Registration and the DLL only exist on Windows; the tests that need them skip elsewhere.+[SupportedOSPlatform("windows")]+public class ExplorerMenuTests+{+ private static readonly XNamespace F = "http://schemas.microsoft.com/appx/manifest/foundation/windows10";+ private static readonly XNamespace Uap = "http://schemas.microsoft.com/appx/manifest/uap/windows10";+ private static readonly XNamespace Uap10 = "http://schemas.microsoft.com/appx/manifest/uap/windows10/10";+ private static readonly XNamespace Desktop4 = "http://schemas.microsoft.com/appx/manifest/desktop/windows10/4";+ private static readonly XNamespace Desktop5 = "http://schemas.microsoft.com/appx/manifest/desktop/windows10/5";+ private static readonly XNamespace Com = "http://schemas.microsoft.com/appx/manifest/com/windows10";++ private static string RepoRoot+ {+ 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;+ }+ }++ private static string BuiltFolder => Path.Combine(RepoRoot, "build", ".cache", "explorer-menu");++ [Fact]+ public void Manifest_declares_an_unsigned_sparse_package_with_the_explorer_command()+ {+ var manifest = XDocument.Parse(ExplorerMenuPackage.CreateManifest()).Root!;+ Assert.Equal(F + "Package", manifest.Name);++ var identity = manifest.Element(F + "Identity")!;+ Assert.Equal(ExplorerMenuPackage.PackageName, (string?)identity.Attribute("Name"));+ Assert.Contains("OID.2.25.311729368913984317654407730594956997722=1", (string?)identity.Attribute("Publisher"));+ Assert.Equal(ExplorerMenuPackage.ManifestVersion.ToString(4), (string?)identity.Attribute("Version"));+ Assert.Equal("x64", (string?)identity.Attribute("ProcessorArchitecture"));+ Assert.Equal("true", (string?)manifest.Element(F + "Properties")!.Element(Uap10 + "AllowExternalContent"));+ Assert.Equal("10.0.22000.0", (string?)manifest.Descendants(F + "TargetDeviceFamily").Single().Attribute("MinVersion"));++ var app = manifest.Descendants(F + "Application").Single();+ Assert.Equal("Filee.exe", (string?)app.Attribute("Executable"));+ Assert.Equal("mediumIL", (string?)app.Attribute(Uap10 + "TrustLevel"));+ Assert.Equal("win32App", (string?)app.Attribute(Uap10 + "RuntimeBehavior"));+ Assert.Equal("none", (string?)app.Element(Uap + "VisualElements")!.Attribute("AppListEntry"));++ var clsid = ExplorerMenuPackage.ClassId.ToString("D");+ var itemType = app.Descendants(Desktop4 + "FileExplorerContextMenus").Single().Element(Desktop5 + "ItemType")!;+ Assert.Equal("*", (string?)itemType.Attribute("Type"));+ Assert.Equal(clsid, (string?)itemType.Element(Desktop5 + "Verb")!.Attribute("Clsid"), ignoreCase: true);++ var comClass = app.Descendants(Com + "Class").Single();+ Assert.Equal(clsid, (string?)comClass.Attribute("Id"), ignoreCase: true);+ Assert.Equal(ExplorerMenuPackage.DllFileName, (string?)comClass.Attribute("Path"));+ }++ [Fact]+ public void Native_source_uses_the_same_class_id_list_prefix_and_title_file()+ {+ var source = File.ReadAllText(Path.Combine(RepoRoot, "src", "Filee.ExplorerMenu", "FileeExplorerMenu.c"));+ var match = Regex.Match(source, @"kClsidCommand = \{(?<parts>[^;]+)\};");+ Assert.True(match.Success);+ var n = Regex.Matches(match.Groups["parts"].Value, "0x([0-9a-fA-F]+)")+ .Select(m => ulong.Parse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture)).ToArray();+ Assert.Equal(11, n.Length);+ var fromSource = new Guid((uint)n[0], (ushort)n[1], (ushort)n[2],+ (byte)n[3], (byte)n[4], (byte)n[5], (byte)n[6], (byte)n[7], (byte)n[8], (byte)n[9], (byte)n[10]);+ Assert.Equal(ExplorerMenuPackage.ClassId, fromSource);++ Assert.Contains($"#define LIST_PREFIX L\"{CommandLine.ListFilePrefix}\"", source);+ Assert.Contains($"#define TITLE_FILE L\"Filee\\\\{ExplorerMenuPackage.TitleFileName}\"", source);+ }++ [Fact]+ public void Family_name_matches_what_Windows_computes_from_the_publisher()+ {+ Assert.SkipUnless(OperatingSystem.IsWindowsVersionAtLeast(10), "Package APIs need Windows.");+ Assert.Equal(ExplorerMenuPackage.FamilyName, ExplorerMenuRegistration.ComputeFamilyName());+ }++ [Fact]+ public void PowerShell_literals_escape_straight_and_typographic_single_quotes()+ {+ Assert.Equal(@"'C:\Users\Kim''s PC\Filee'", ExplorerMenuRegistration.Quote(@"C:\Users\Kim's PC\Filee"));+ Assert.Equal("'Kim\u2019\u2019s'", ExplorerMenuRegistration.Quote("Kim\u2019s"));+ }++ [Fact]+ public void Add_script_registers_the_package_unsigned_with_the_install_folder_as_external_location()+ {+ var script = ExplorerMenuRegistration.BuildAddScript(@"C:\Apps\Filee\current\FileeExplorerMenu.msix",+ @"C:\Apps\Filee\current", @"C:\Temp\err.txt");+ Assert.Contains(@"Add-AppxPackage -Path 'C:\Apps\Filee\current\FileeExplorerMenu.msix' -ExternalLocation 'C:\Apps\Filee\current' -AllowUnsigned", script);+ Assert.Contains(@"[IO.File]::WriteAllText('C:\Temp\err.txt', $_.Exception.Message); exit 1", script);+ Assert.DoesNotContain("\"", script);++ var remove = ExplorerMenuRegistration.BuildRemoveScript(@"C:\Temp\err.txt");+ Assert.Contains("Get-AppxPackage -Name 'Filee.ExplorerMenu' | Remove-AppxPackage", remove);+ }++ [Fact]+ public void Deployment_errors_lose_the_activity_id_note_and_line_breaks()+ {+ const string message = "Deployment failed with HRESULT: 0x80073D2B, The package could not be installed.\r\n\r\n" ++ "Windows cannot install package Filee.ExplorerMenu.\r\n\r\n" ++ "NOTE: For additional information, look for [ActivityId] 3a41 in the Event Log";+ Assert.Equal("Deployment failed with HRESULT: 0x80073D2B, The package could not be installed. Windows cannot install package Filee.ExplorerMenu.",+ ExplorerMenuRegistration.ShortenDeploymentError(message));+ }++ [Fact]+ public void PowerShell_start_info_elevates_only_when_asked()+ {+ Assert.SkipUnless(OperatingSystem.IsWindows(), "Windows only.");+ var elevated = ExplorerMenuRegistration.CreateStartInfo("exit 0", elevated: true);+ Assert.True(elevated.UseShellExecute);+ Assert.Equal("runas", elevated.Verb);+ Assert.EndsWith(@"WindowsPowerShell\v1.0\powershell.exe", elevated.FileName, StringComparison.OrdinalIgnoreCase);+ Assert.Equal("-NoLogo -NoProfile -NonInteractive -Command \"exit 0\"", elevated.Arguments);++ var plain = ExplorerMenuRegistration.CreateStartInfo("exit 0", elevated: false);+ Assert.False(plain.UseShellExecute);+ Assert.True(plain.CreateNoWindow);+ Assert.Throws<ArgumentException>(() => ExplorerMenuRegistration.CreateStartInfo("echo \"x\"", elevated: false));+ }++ [Fact]+ public void Convert_list_reads_existing_paths_and_only_deletes_its_own_temp_file()+ {+ var folder = Directory.CreateTempSubdirectory("filee-list-test-").FullName;+ var list = Path.Combine(Path.GetTempPath(), CommandLine.ListFilePrefix + Guid.NewGuid().ToString("N") + ".txt");+ var foreign = Path.Combine(folder, CommandLine.ListFilePrefix + "elsewhere.txt");+ try+ {+ var a = Path.Combine(folder, "a 1.png");+ var b = Path.Combine(folder, "b, 한글.pdf");+ File.WriteAllText(a, "x");+ File.WriteAllText(b, "x");+ File.WriteAllText(list, $"{a}\r\n\r\n{Path.Combine(folder, "missing.txt")}\r\n{b}\r\n", new System.Text.UTF8Encoding(true));+ File.WriteAllText(foreign, a);++ var options = CommandLine.Parse(["--convert-list", list]);+ Assert.Equal(new[] { a, b }, options.ConvertFiles);+ Assert.Equal(list, options.ListFile);+ options.DeleteListFile();+ Assert.False(File.Exists(list));++ var other = CommandLine.Parse(["--convert-list", foreign]);+ Assert.Equal(new[] { a }, other.ConvertFiles);+ other.DeleteListFile();+ Assert.True(File.Exists(foreign)); // not in %TEMP% itself: never deleted++ Assert.Empty(CommandLine.Parse(["--convert-list", Path.Combine(folder, "nope.txt")]).ConvertFiles);+ }+ finally+ {+ File.Delete(list);+ Directory.Delete(folder, recursive: true);+ }+ }++ [Fact]+ public void Built_package_contains_the_current_manifest()+ {+ var package = Path.Combine(BuiltFolder, ExplorerMenuPackage.PackageFileName);+ Assert.SkipUnless(File.Exists(package), "Run build/build-explorer-menu.ps1 first.");+ using var zip = ZipFile.OpenRead(package);+ Assert.NotNull(zip.GetEntry("AppxBlockMap.xml"));+ Assert.NotNull(zip.GetEntry("[Content_Types].xml"));+ Assert.NotNull(zip.GetEntry(ExplorerMenuPackage.LogoPath.Replace('\\', '/')));+ using var stream = zip.GetEntry("AppxManifest.xml")!.Open();+ Assert.True(XNode.DeepEquals(XDocument.Parse(ExplorerMenuPackage.CreateManifest()).Root, XDocument.Load(stream).Root),+ "The package is stale: run build/build-explorer-menu.ps1 again.");+ }++ [Fact]+ public void Native_dll_serves_the_explorer_command_in_process()+ {+ var dll = Path.Combine(BuiltFolder, ExplorerMenuPackage.DllFileName);+ Assert.SkipUnless(OperatingSystem.IsWindows() && RuntimeInformation.ProcessArchitecture == Architecture.X64 && File.Exists(dll),+ "Run build/build-explorer-menu.ps1 first (x64 Windows).");++ using var command = NativeCommand.Create(dll);+ // The title comes from the file the app writes into its data folder; without it the English default is used.+ var expectedTitle = ExplorerMenuRegistration.ReadTitle();+ Assert.Equal(expectedTitle ?? "Convert with Filee", command.GetTitle());+ Assert.Equal(Path.Combine(BuiltFolder, "Filee.exe") + ",0", command.GetIcon(), ignoreCase: true);+ Assert.Equal(ExplorerMenuPackage.ClassId, command.GetCanonicalName());++ const int enabled = 0, hidden = 2;+ var file = Path.GetTempFileName();+ var folder = Directory.CreateTempSubdirectory("filee-menu-test-").FullName;+ try+ {+ Assert.Equal(expectedTitle is null ? hidden : enabled, command.GetState(file));+ Assert.Equal(hidden, command.GetState(folder)); // folders never get the entry+ }+ finally+ {+ File.Delete(file);+ Directory.Delete(folder);+ }+ }++ /// <summary>Calls FileeExplorerMenu.dll through its exports and the raw IExplorerCommand vtable.</summary>+ private sealed class NativeCommand : IDisposable+ {+ private static readonly Guid IidClassFactory = new("00000001-0000-0000-C000-000000000046");+ private static readonly Guid IidExplorerCommand = new("a08ce4d0-fa25-44ab-b57c-c7b1c323e0b9");+ private static readonly Guid IidShellItem = new("43826d1e-e718-42ee-bc55-a1e261c37bfe");+ private static readonly Guid IidShellItemArray = new("b63ea76d-1f85-456f-a19c-48159efa858b");++ private readonly nint _library;+ private readonly nint _command;++ private delegate int GetClassObjectFn(ref Guid clsid, ref Guid iid, out nint result);+ private delegate int CreateInstanceFn(nint self, nint outer, ref Guid iid, out nint result);+ private delegate int GetStringFn(nint self, nint items, out nint value);+ private delegate int GetGuidFn(nint self, out Guid value);+ private delegate int GetStateFn(nint self, nint items, int okToBeSlow, out int state);+ private delegate uint ReleaseFn(nint self);++ private NativeCommand(nint library, nint command)+ {+ _library = library;+ _command = command;+ }++ public static NativeCommand Create(string dll)+ {+ var library = NativeLibrary.Load(dll);+ var getClassObject = Marshal.GetDelegateForFunctionPointer<GetClassObjectFn>(NativeLibrary.GetExport(library, "DllGetClassObject"));+ var clsid = ExplorerMenuPackage.ClassId;+ var iid = IidClassFactory;+ Assert.Equal(0, getClassObject(ref clsid, ref iid, out var factory));+ iid = IidExplorerCommand;+ Assert.Equal(0, Method<CreateInstanceFn>(factory, 3)(factory, 0, ref iid, out var command));+ Release(factory);+ return new NativeCommand(library, command);+ }++ public string? GetTitle() => GetString(3);+ public string? GetIcon() => GetString(4);++ public Guid GetCanonicalName()+ {+ Assert.Equal(0, Method<GetGuidFn>(_command, 6)(_command, out var name));+ return name;+ }++ public int GetState(string path)+ {+ var iid = IidShellItem;+ Assert.Equal(0, SHCreateItemFromParsingName(path, 0, ref iid, out var item));+ iid = IidShellItemArray;+ Assert.Equal(0, SHCreateShellItemArrayFromShellItem(item, ref iid, out var array));+ Release(item);+ try+ {+ Assert.Equal(0, Method<GetStateFn>(_command, 7)(_command, array, 1, out var state));+ return state;+ }+ finally+ {+ Release(array);+ }+ }++ public void Dispose()+ {+ Release(_command);+ NativeLibrary.Free(_library);+ }++ private string? GetString(int slot)+ {+ Assert.Equal(0, Method<GetStringFn>(_command, slot)(_command, 0, out var value));+ try+ {+ return Marshal.PtrToStringUni(value);+ }+ finally+ {+ Marshal.FreeCoTaskMem(value);+ }+ }++ private static T Method<T>(nint instance, int slot) where T : Delegate =>+ Marshal.GetDelegateForFunctionPointer<T>(Marshal.ReadIntPtr(Marshal.ReadIntPtr(instance), slot * IntPtr.Size));++ private static void Release(nint instance) => Method<ReleaseFn>(instance, 2)(instance);++ [DllImport("shell32.dll", CharSet = CharSet.Unicode)]+ private static extern int SHCreateItemFromParsingName(string path, nint bindContext, ref Guid iid, out nint item);++ [DllImport("shell32.dll")]+ private static extern int SHCreateShellItemArrayFromShellItem(nint item, ref Guid iid, out nint array);+ }+}