diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
new file mode 100644
index 000000000..664555952
--- /dev/null
+++ b/.github/workflows/tests.yml
@@ -0,0 +1,29 @@
+# Runs the automated tests. The build workflow only compiles the application, so the tests live in
+# their own project (tests/QuickLook.Tests) and are executed here.
+
+name: tests
+
+on:
+ push:
+ branches: [ "master" ]
+ pull_request:
+ branches: [ "master" ]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ runs-on: windows-latest
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up .NET
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 8.0.x
+
+ - name: Run tests
+ run: dotnet test tests/QuickLook.Tests/QuickLook.Tests.csproj -c Release --logger "console;verbosity=normal"
diff --git a/OPTIONS.md b/OPTIONS.md
index a5fd6b0cb..a0debb6c1 100644
--- a/OPTIONS.md
+++ b/OPTIONS.md
@@ -242,6 +242,13 @@ These keys are also stored in `QuickLook.config`.
- Example:
- `True`
+### ``
+- Default: `True`
+- Type: `Boolean`
+- Description: When `True`, a preview handler that is only registered in the 32-bit registry view (for example by WPS Office, which is a 32-bit application) is mirrored into the 64-bit registry view for the current user, so that QuickLook can resolve and activate it. Only out-of-process handlers registered through `LocalServer32` are mirrored; a 32-bit in-process handler (`InprocServer32`) cannot be loaded by a 64-bit process and is left untouched. Only `HKEY_CURRENT_USER\Software\Classes\CLSID` is written, no elevation is required, mirrored values are refreshed when the source registration changes, and deleting the mirrored keys reverts the change.
+- Example:
+ - `False`
+
## QuickLook.Plugin.MarkdownViewer.config options
### ``
diff --git a/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/Plugin.cs b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/Plugin.cs
index cc53a1f27..b4ad8bbe0 100644
--- a/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/Plugin.cs
+++ b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/Plugin.cs
@@ -1,4 +1,4 @@
-// Copyright © 2017-2026 QL-Win Contributors
+// Copyright © 2017-2026 QL-Win Contributors
//
// This file is part of QuickLook program.
//
@@ -56,45 +56,53 @@ public bool CanHandle(string path)
if (previewHandler == Guid.Empty)
return false;
+ // Office suites such as WPS Office are 32-bit applications and register their preview
+ // handlers only in the 32-bit registry view. QuickLook is a 64-bit process and cannot
+ // use such a registration, so mirror it into the 64-bit registry view for the current
+ // user. An existing mirror is refreshed when the source registration changes, therefore
+ // this must run before the plain registration check below. It also runs when
+ // CheckPreviewHandler is disabled: that setting skips the availability check, it does not
+ // opt out of making an otherwise unusable handler work. See also:
+ // PreviewHandlerRegistration.
+ var fixPreviewHandlerRegistration = SettingHelper.Get("FixPreviewHandlerRegistration", true, "QuickLook.Plugin.OfficeViewer");
+ if (fixPreviewHandlerRegistration && PreviewHandlerRegistration.EnsureRegisteredForCurrentView(previewHandler))
+ return true;
+
var checkPreviewHandler = SettingHelper.Get("CheckPreviewHandler", true, "QuickLook.Plugin.OfficeViewer");
if (!checkPreviewHandler)
return true;
- if (!string.IsNullOrWhiteSpace(CLSIDRegister.GetName(previewHandler.ToString("B"))))
- {
+ if (PreviewHandlerRegistration.IsRegisteredForCurrentView(previewHandler))
return true;
- }
- else
- {
- // Legacy: No more recovering registries for MS Office.
- // TODO: Add a setting page to let users choose the fallback preview handler if the current one is not working.
+
+ // Legacy: No more recovering registries for MS Office.
+ // TODO: Add a setting page to let users choose the fallback preview handler if the current one is not working.
#if false
- // To restore the preview handler CLSID to MS Office
- // if running with administrative privileges
- if (ShellExRegister.IsRunAsAdmin())
+ // To restore the preview handler CLSID to MS Office
+ // if running with administrative privileges
+ if (ShellExRegister.IsRunAsAdmin())
+ {
+ var fileExtension = Path.GetExtension(path);
+ var fallbackHandler = fileExtension switch
{
- var fileExtension = Path.GetExtension(path);
- var fallbackHandler = fileExtension switch
- {
- ".doc" or ".docx" or ".docm" or ".odt" => CLSIDRegister.MicrosoftWord,
- ".xls" or ".xlsx" or ".xlsm" or ".xlsb" or ".ods" => CLSIDRegister.MicrosoftExcel,
- ".ppt" or ".pptx" or ".odp" => CLSIDRegister.MicrosoftPowerPoint,
- ".vsd" or ".vsdx" => CLSIDRegister.MicrosoftVisio,
- _ => null,
- };
+ ".doc" or ".docx" or ".docm" or ".odt" => CLSIDRegister.MicrosoftWord,
+ ".xls" or ".xlsx" or ".xlsm" or ".xlsb" or ".ods" => CLSIDRegister.MicrosoftExcel,
+ ".ppt" or ".pptx" or ".odp" => CLSIDRegister.MicrosoftPowerPoint,
+ ".vsd" or ".vsdx" => CLSIDRegister.MicrosoftVisio,
+ _ => null,
+ };
- if (fallbackHandler == null)
- return false;
+ if (fallbackHandler == null)
+ return false;
- if (!string.IsNullOrWhiteSpace(CLSIDRegister.GetName(fallbackHandler)))
- {
- // Admin requested
- ShellExRegister.SetPreviewHandlerGUID(fileExtension, new Guid(fallbackHandler));
- return true;
- }
+ if (!string.IsNullOrWhiteSpace(CLSIDRegister.GetName(fallbackHandler)))
+ {
+ // Admin requested
+ ShellExRegister.SetPreviewHandlerGUID(fileExtension, new Guid(fallbackHandler));
+ return true;
}
-#endif
}
+#endif
return false;
}
diff --git a/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
new file mode 100644
index 000000000..197e75b37
--- /dev/null
+++ b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
@@ -0,0 +1,436 @@
+// Copyright © 2017-2026 QL-Win Contributors
+//
+// This file is part of QuickLook program.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see .
+
+using Microsoft.Win32;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+
+namespace QuickLook.Plugin.OfficeViewer;
+
+///
+/// Helps QuickLook use preview handlers registered by 32-bit Office suites (such as WPS Office).
+///
+///
+/// WPS Office is a 32-bit application and registers its preview handlers only in the 32-bit
+/// registry view (HKEY_CLASSES_ROOT\WOW6432Node\CLSID). QuickLook is a 64-bit process,
+/// so it can neither read the display name nor activate the COM class of those handlers, and
+/// the Office documents they are associated with appear to be unsupported.
+///
+/// For the current user only, this class mirrors such a registration into the 64-bit view
+/// (HKEY_CURRENT_USER\Software\Classes\CLSID). This requires no elevation, does not
+/// touch the machine-wide registration written by the Office suite, and is idempotent.
+/// Removing the created keys restores the previous state.
+///
+/// Only out-of-process preview handlers (LocalServer32) are mirrored. A 32-bit
+/// in-process handler (InprocServer32) cannot be loaded by a 64-bit process, so such a
+/// registration is intentionally left untouched and the handler remains unavailable to QuickLook.
+///
+internal static class PreviewHandlerRegistration
+{
+ private const string ClassesRootPath = @"CLSID";
+ private const string LocalServer32Key = @"LocalServer32";
+ private const string InprocServer32Key = @"InprocServer32";
+ private const string InprocHandler32Key = @"InprocHandler32";
+ private const string MirrorMarkerValue = "QuickLookMirror";
+ private const string Ole32 = "ole32.dll";
+
+ ///
+ /// Determines whether the specified preview handler is registered and can be activated in the
+ /// registry view of the current process.
+ ///
+ /// The CLSID of the preview handler.
+ ///
+ /// when the registration is complete (a display name plus either a
+ /// LocalServer32 or an InprocServer32 activation); otherwise
+ /// .
+ ///
+ public static bool IsRegisteredForCurrentView(Guid clsid)
+ {
+ var registration = ReadRegistration(clsid, RegistryView.Registry64);
+ return registration != null && registration.IsComplete;
+ }
+
+ ///
+ /// Ensures that the specified preview handler is registered in the registry view of the
+ /// current process. If it is only registered in the 32-bit registry view, a mirror of that
+ /// registration is created under HKEY_CURRENT_USER\Software\Classes\CLSID. A mirror
+ /// created by QuickLook is refreshed when the 32-bit source registration changes, for example
+ /// after an Office suite update moved its executable.
+ ///
+ /// The CLSID of the preview handler.
+ ///
+ /// when the handler is usable by this process after the call;
+ /// otherwise .
+ ///
+ public static bool EnsureRegisteredForCurrentView(Guid clsid)
+ {
+ var source = ReadRegistration(clsid, RegistryView.Registry32);
+ if (source == null)
+ {
+ // A handler that was uninstalled leaves a stale mirror behind. Remove it, but only
+ // when the 32-bit key is confirmed absent: a failed read is not proof of absence.
+ if (IsAbsentFrom32BitView(clsid))
+ RemoveMirror(clsid);
+
+ return false;
+ }
+
+ if (!source.IsLocalServer)
+ {
+ // The mirror only copies LocalServer32 activation, so a mirror left over from a
+ // previous registration must not keep a preview alive with an obsolete command.
+ // A failed read is not evidence that the registration changed, so keep the mirror
+ // in that case; the next successful read decides.
+ if (!source.LocalServerReadFailed)
+ RemoveMirror(clsid);
+
+ // A 32-bit in-process handler cannot be hosted by a 64-bit process, and pointing a
+ // 64-bit InprocServer32 entry at a 32-bit DLL would only break activation.
+ if (source.HasInprocServer)
+ Debug.WriteLine($"QuickLook: preview handler {clsid:B} is registered as a 32-bit in-process server and cannot be mirrored.");
+ return false;
+ }
+
+ var current = ReadRegistration(clsid, RegistryView.Registry64);
+ var isMirror = IsMirror(clsid);
+
+ // Never overwrite a registration that QuickLook did not create.
+ if (current != null && !isMirror)
+ return current.IsComplete;
+
+ if (current != null && current.IsComplete && current.Matches(source))
+ return true;
+
+ return WriteMirror(clsid, source, isMirror);
+ }
+
+ ///
+ /// Reads a preview handler registration from the given registry view.
+ ///
+ /// The CLSID of the preview handler.
+ /// The registry view to read from.
+ /// The registration, or when the CLSID is not registered in that view.
+ private static HandlerRegistration ReadRegistration(Guid clsid, RegistryView view)
+ {
+ try
+ {
+ using var classes = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, view);
+ using var clsidKey = classes.OpenSubKey($@"{ClassesRootPath}\{clsid:B}");
+ if (clsidKey == null)
+ return null;
+
+ var registration = new HandlerRegistration
+ {
+ DisplayName = clsidKey.GetValue(string.Empty) as string,
+ };
+
+ using (var inprocHandler32 = clsidKey.OpenSubKey(InprocHandler32Key))
+ registration.InprocHandler32 = inprocHandler32?.GetValue(string.Empty) as string;
+
+ using (var inprocServer32 = clsidKey.OpenSubKey(InprocServer32Key))
+ registration.InprocServer32 = inprocServer32?.GetValue(string.Empty) as string;
+
+ using var localServer32 = TryOpenLocalServer32(clsidKey, registration);
+ if (localServer32 != null)
+ {
+ // Copy every string value, including named values such as ServerExecutable, instead
+ // of only the default command line. Non-string values are skipped: they cannot be
+ // written back as a command line and would abort the whole mirror.
+ foreach (var name in localServer32.GetValueNames())
+ {
+ if (localServer32.GetValue(name) is string value)
+ registration.LocalServerValues[name] = value;
+ }
+ }
+
+ return registration;
+ }
+ catch (Exception e)
+ {
+ Debug.WriteLine("Error reading preview handler registration: " + e);
+ return null;
+ }
+ }
+
+ ///
+ /// Opens the LocalServer32 subkey, distinguishing "not registered" from "cannot be read".
+ ///
+ /// The CLSID key whose subkey is opened.
+ /// The registration that receives the read failure flag.
+ /// The opened subkey, or when it does not exist or cannot be read.
+ private static RegistryKey TryOpenLocalServer32(RegistryKey clsidKey, HandlerRegistration registration)
+ {
+ var exists = LocalServer32Exists(clsidKey);
+
+ try
+ {
+ var localServer32 = clsidKey.OpenSubKey(LocalServer32Key);
+ if (localServer32 == null && exists)
+ registration.LocalServerReadFailed = true;
+
+ return localServer32;
+ }
+ catch (Exception e)
+ {
+ // A registration whose LocalServer32 cannot be read must not be treated as if the
+ // handler had no out-of-process server: a valid mirror would be removed.
+ Debug.WriteLine("Error reading LocalServer32 subkey: " + e);
+ registration.LocalServerReadFailed = true;
+ return null;
+ }
+ }
+
+ ///
+ /// Determines whether the CLSID key has a LocalServer32 subkey, without reading its values.
+ ///
+ /// The CLSID key to inspect.
+ /// when the subkey is listed or its presence cannot be determined.
+ private static bool LocalServer32Exists(RegistryKey clsidKey)
+ {
+ try
+ {
+ return clsidKey.GetSubKeyNames()
+ .Any(name => string.Equals(name, LocalServer32Key, StringComparison.OrdinalIgnoreCase));
+ }
+ catch (Exception e)
+ {
+ // If the names cannot be enumerated, assume the subkey exists so that a read failure
+ // never removes a mirror.
+ Debug.WriteLine("Error enumerating preview handler subkeys: " + e);
+ return true;
+ }
+ }
+
+ ///
+ /// Determines whether the current-user 64-bit registration was created by QuickLook.
+ ///
+ /// The CLSID of the preview handler.
+ /// when the mirror marker is present.
+ private static bool IsMirror(Guid clsid)
+ {
+ try
+ {
+ using var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
+ using var clsidKey = currentUser.OpenSubKey($@"Software\Classes\{ClassesRootPath}\{clsid:B}");
+ return clsidKey?.GetValue(MirrorMarkerValue) != null;
+ }
+ catch (Exception e)
+ {
+ Debug.WriteLine("Error reading preview handler mirror marker: " + e);
+ return false;
+ }
+ }
+
+ ///
+ /// Determines whether the CLSID key is confirmed to be missing from the 32-bit registry view.
+ ///
+ /// The CLSID of the preview handler.
+ /// only when the key was successfully opened and does not exist.
+ private static bool IsAbsentFrom32BitView(Guid clsid)
+ {
+ try
+ {
+ using var classes = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry32);
+ using var clsidKey = classes.OpenSubKey($@"{ClassesRootPath}\{clsid:B}");
+ return clsidKey == null;
+ }
+ catch (Exception e)
+ {
+ // Treat an inspection error as "unknown", never as proof that the source is gone.
+ Debug.WriteLine("Error checking preview handler registration: " + e);
+ return false;
+ }
+ }
+
+ ///
+ /// Removes the current-user 64-bit registration, but only when QuickLook created it.
+ ///
+ /// The CLSID of the preview handler.
+ private static void RemoveMirror(Guid clsid)
+ {
+ if (!IsMirror(clsid))
+ return;
+
+ try
+ {
+ using var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
+ currentUser.DeleteSubKeyTree($@"Software\Classes\{ClassesRootPath}\{clsid:B}", false);
+ }
+ catch (Exception e)
+ {
+ Debug.WriteLine("Error removing stale preview handler mirror: " + e);
+ }
+ }
+
+ ///
+ /// Writes the per-user 64-bit mirror of a 32-bit out-of-process preview handler registration.
+ ///
+ /// The CLSID of the preview handler.
+ /// The 32-bit registration to mirror.
+ /// Whether an existing mirror created by QuickLook may be replaced.
+ /// when the mirrored registration is complete afterwards.
+ private static bool WriteMirror(Guid clsid, HandlerRegistration source, bool replaceExisting)
+ {
+ // Without a display name the mirror would never be considered registered, and writing a
+ // null default value would fail halfway through. Refuse instead of leaving a partial key.
+ if (source == null || string.IsNullOrWhiteSpace(source.DisplayName))
+ return false;
+
+ var keyPath = $@"Software\Classes\{ClassesRootPath}\{clsid:B}";
+ var createdNew = false;
+
+ try
+ {
+ using var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
+ using (var existing = currentUser.OpenSubKey(keyPath))
+ createdNew = existing == null;
+
+ using var clsid64 = currentUser.CreateSubKey(keyPath);
+ if (clsid64 == null)
+ return false;
+
+ // Record ownership before any child write, so an interrupted new mirror is repaired
+ // on the next attempt instead of being mistaken for a user-owned registration.
+ if (createdNew)
+ clsid64.SetValue(MirrorMarkerValue, "1");
+
+ if (replaceExisting)
+ {
+ // Mark the mirror incomplete until the refreshed values are written, so an
+ // interrupted refresh is repaired instead of being treated as registered.
+ clsid64.SetValue(string.Empty, string.Empty);
+
+ // Drop stale values of a previous mirror before copying the current source.
+ clsid64.DeleteSubKeyTree(LocalServer32Key, false);
+ clsid64.DeleteSubKeyTree(InprocHandler32Key, false);
+ }
+
+ using (var localServer64 = clsid64.CreateSubKey(LocalServer32Key))
+ {
+ if (localServer64 == null)
+ return false;
+
+ foreach (var pair in source.LocalServerValues)
+ localServer64.SetValue(pair.Key, pair.Value);
+ }
+
+ using (var inprocHandler64 = clsid64.CreateSubKey(InprocHandler32Key))
+ inprocHandler64?.SetValue(string.Empty, source.InprocHandler32 ?? Ole32);
+
+ clsid64.SetValue(MirrorMarkerValue, "1");
+
+ // Publish the display name last: it marks the mirror as complete, so an interrupted
+ // write is repaired on the next attempt instead of being treated as registered.
+ clsid64.SetValue(string.Empty, source.DisplayName);
+
+ Debug.WriteLine($"QuickLook: mirrored preview handler {clsid:B} ('{source.DisplayName}') into the 64-bit registry view.");
+ return IsRegisteredForCurrentView(clsid);
+ }
+ catch (Exception e)
+ {
+ Debug.WriteLine("Error mirroring preview handler registration: " + e);
+
+ // Only clean up a key that this attempt created; never delete a pre-existing one.
+ if (createdNew)
+ {
+ try
+ {
+ using var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
+ currentUser.DeleteSubKeyTree(keyPath, false);
+ }
+ catch (Exception cleanupError)
+ {
+ Debug.WriteLine("Error cleaning up partial preview handler mirror: " + cleanupError);
+ }
+ }
+
+ return false;
+ }
+ }
+
+ ///
+ /// Describes a preview handler registration read from one registry view.
+ ///
+ private sealed class HandlerRegistration
+ {
+ /// Gets or sets the display name (the CLSID key's default value).
+ public string DisplayName { get; set; }
+
+ /// Gets or sets the InprocHandler32 value.
+ public string InprocHandler32 { get; set; }
+
+ /// Gets or sets the InprocServer32 value.
+ public string InprocServer32 { get; set; }
+
+ /// Gets the LocalServer32 values, including named values.
+ public Dictionary LocalServerValues { get; } = new(StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// Gets or sets a value indicating that the LocalServer32 subkey exists but its
+ /// values could not be read, so the absence of a local server must not be assumed.
+ ///
+ public bool LocalServerReadFailed { get; set; }
+
+ ///
+ /// Gets a value indicating whether an executable for an out-of-process server is registered,
+ /// either as the default command line or through the named ServerExecutable value.
+ ///
+ public bool IsLocalServer =>
+ (LocalServerValues.TryGetValue(string.Empty, out var command) && !string.IsNullOrWhiteSpace(command))
+ || (LocalServerValues.TryGetValue("ServerExecutable", out var executable) && !string.IsNullOrWhiteSpace(executable));
+
+ /// Gets a value indicating whether an in-process server is registered.
+ public bool HasInprocServer => !string.IsNullOrWhiteSpace(InprocServer32);
+
+ /// Gets a value indicating whether the registration can be activated at all.
+ public bool HasActivation => IsLocalServer || HasInprocServer;
+
+ /// Gets a value indicating whether the registration has both a name and an activation.
+ public bool IsComplete => !string.IsNullOrWhiteSpace(DisplayName) && HasActivation;
+
+ ///
+ /// Determines whether this registration has the same activation data as another one.
+ ///
+ /// The registration to compare with.
+ /// when the values match.
+ public bool Matches(HandlerRegistration other)
+ {
+ if (other == null)
+ return false;
+
+ if (!string.Equals(DisplayName, other.DisplayName, StringComparison.Ordinal))
+ return false;
+
+ if (!string.Equals(InprocHandler32 ?? Ole32, other.InprocHandler32 ?? Ole32, StringComparison.OrdinalIgnoreCase))
+ return false;
+
+ if (LocalServerValues.Count != other.LocalServerValues.Count)
+ return false;
+
+ foreach (var pair in LocalServerValues)
+ {
+ if (!other.LocalServerValues.TryGetValue(pair.Key, out var otherValue)
+ || !string.Equals(pair.Value, otherValue, StringComparison.Ordinal))
+ return false;
+ }
+
+ return true;
+ }
+ }
+}
diff --git a/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs b/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs
new file mode 100644
index 000000000..fbb3e8185
--- /dev/null
+++ b/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs
@@ -0,0 +1,379 @@
+// Copyright © 2017-2026 QL-Win Contributors
+//
+// This file is part of QuickLook program.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see .
+
+using Microsoft.Win32;
+using QuickLook.Plugin.OfficeViewer;
+using System;
+using System.Security.AccessControl;
+using System.Security.Principal;
+using Xunit;
+
+namespace QuickLook.Tests;
+
+///
+/// Exercises against the real registry, using a unique
+/// CLSID per test. The 32-bit registration used as the source is written to
+/// HKCU\Software\Classes\WOW6432Node\CLSID, which is exactly what the 32-bit registry view
+/// of HKEY_CLASSES_ROOT maps to, so the production code path under test is unmodified.
+/// Everything a test creates lives under the current user and is deleted again in .
+///
+public sealed class PreviewHandlerRegistrationTests : IDisposable
+{
+ private const string LocalServer32Key = "LocalServer32";
+ private const string InprocServer32Key = "InprocServer32";
+ private const string InprocHandler32Key = "InprocHandler32";
+ private const string MirrorMarkerValue = "QuickLookMirror";
+
+ private readonly Guid _clsid = Guid.NewGuid();
+
+ public void Dispose()
+ {
+ DeleteKey(32);
+ DeleteKey(64);
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_Mirrors32BitLocalServerHandler()
+ {
+ Create32BitRegistration("WPS 文字 预览器", @"C:\Program Files (x86)\Kingsoft\WPS Office\wps.exe");
+
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+ Assert.True(PreviewHandlerRegistration.IsRegisteredForCurrentView(_clsid));
+
+ using var mirror = OpenMirror();
+ Assert.NotNull(mirror);
+ Assert.Equal("WPS 文字 预览器", mirror.GetValue(string.Empty) as string);
+ Assert.Equal("1", mirror.GetValue(MirrorMarkerValue) as string);
+ Assert.Equal("ole32.dll", mirror.OpenSubKey(InprocHandler32Key)?.GetValue(string.Empty) as string);
+ Assert.Equal(
+ @"C:\Program Files (x86)\Kingsoft\WPS Office\wps.exe",
+ mirror.OpenSubKey(LocalServer32Key)?.GetValue(string.Empty) as string);
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_CopiesNamedLocalServer32Values()
+ {
+ using (var source = Create32BitRegistration("WPS 表格 预览器", @"C:\Program Files (x86)\Kingsoft\WPS Office\et.exe"))
+ {
+ source.CreateSubKey(LocalServer32Key)?.SetValue("ServerExecutable", @"C:\Program Files (x86)\Kingsoft\WPS Office\et.exe");
+ }
+
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+
+ using var mirror = OpenMirror();
+ Assert.NotNull(mirror);
+ using var localServer = mirror.OpenSubKey(LocalServer32Key);
+ Assert.NotNull(localServer);
+ Assert.Equal(
+ @"C:\Program Files (x86)\Kingsoft\WPS Office\et.exe",
+ localServer.GetValue("ServerExecutable") as string);
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_IgnoresNonStringLocalServer32Values()
+ {
+ using (var source = Create32BitRegistration("WPS 演示 预览器", @"C:\Program Files (x86)\Kingsoft\WPS Office\wpp.exe"))
+ {
+ source.CreateSubKey(LocalServer32Key)?.SetValue("QuickLookTestDword", 1, RegistryValueKind.DWord);
+ }
+
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+
+ using var mirror = OpenMirror();
+ Assert.NotNull(mirror);
+ using var localServer = mirror.OpenSubKey(LocalServer32Key);
+ Assert.NotNull(localServer);
+ Assert.Equal(
+ @"C:\Program Files (x86)\Kingsoft\WPS Office\wpp.exe",
+ localServer.GetValue(string.Empty) as string);
+ Assert.DoesNotContain("QuickLookTestDword", localServer.GetValueNames());
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_ReturnsFalseWhenHandlerIsNotRegistered()
+ {
+ Assert.False(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+ Assert.False(PreviewHandlerRegistration.IsRegisteredForCurrentView(_clsid));
+ Assert.Null(OpenMirror());
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_Rejects32BitInProcessOnlyHandlers()
+ {
+ using (var source = Create32BitRegistration("32-bit in-process previewer", null))
+ {
+ source.CreateSubKey(InprocServer32Key)?.SetValue(string.Empty, @"C:\fake\preview32.dll");
+ }
+
+ Assert.False(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+ Assert.Null(OpenMirror());
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_DoesNotOverwriteRegistrationItDidNotCreate()
+ {
+ using (var current = OpenKey64(writable: true))
+ {
+ current.SetValue(string.Empty, "Microsoft Word Previewer");
+ current.CreateSubKey(LocalServer32Key)?.SetValue(string.Empty, @"C:\Office\wordprev.exe");
+ }
+
+ Create32BitRegistration("WPS 文字 预览器", @"C:\Program Files (x86)\Kingsoft\WPS Office\wps.exe");
+
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+
+ using var untouched = OpenKey64(writable: false);
+ Assert.NotNull(untouched);
+ Assert.Equal("Microsoft Word Previewer", untouched.GetValue(string.Empty) as string);
+ Assert.Null(untouched.GetValue(MirrorMarkerValue));
+ Assert.Equal(
+ @"C:\Office\wordprev.exe",
+ untouched.OpenSubKey(LocalServer32Key)?.GetValue(string.Empty) as string);
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_RefreshesMirrorWhen32BitSourceChanges()
+ {
+ Create32BitRegistration("WPS 文字 预览器", @"C:\Program Files (x86)\Kingsoft\WPS Office\wps.exe");
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+
+ using (var source = OpenKey32(writable: true))
+ {
+ source.CreateSubKey(LocalServer32Key).SetValue(string.Empty, @"D:\WPS\wps.exe");
+ source.SetValue(string.Empty, "WPS 文字 预览器 (更新)");
+ }
+
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+
+ using var mirror = OpenMirror();
+ Assert.NotNull(mirror);
+ Assert.Equal("WPS 文字 预览器 (更新)", mirror.GetValue(string.Empty) as string);
+ Assert.Equal(@"D:\WPS\wps.exe", mirror.OpenSubKey(LocalServer32Key)?.GetValue(string.Empty) as string);
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_IsIdempotent()
+ {
+ Create32BitRegistration("WPS 文字 预览器", @"C:\Program Files (x86)\Kingsoft\WPS Office\wps.exe");
+
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+
+ using var mirror = OpenMirror();
+ Assert.NotNull(mirror);
+ Assert.Equal("1", mirror.GetValue(MirrorMarkerValue) as string);
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_ReturnsFalseWhen32BitRegistrationHasNoDisplayName()
+ {
+ using var source = Create32BitRegistration(null, @"C:\Program Files (x86)\Kingsoft\WPS Office\wps.exe");
+
+ Assert.False(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+ Assert.Null(OpenMirror());
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_RemovesMirrorWhen32BitSourceIsGone()
+ {
+ Create32BitRegistration("WPS 文字 预览器", @"C:\Program Files (x86)\Kingsoft\WPS Office\wps.exe");
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+
+ DeleteKey(32);
+
+ Assert.False(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+ Assert.Null(OpenMirror());
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_RemovesMirrorWhen32BitSourceIsNoLongerALocalServer()
+ {
+ Create32BitRegistration("WPS 文字 预览器", @"C:\Program Files (x86)\Kingsoft\WPS Office\wps.exe");
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+
+ // The same CLSID is now registered as a 32-bit in-process handler only.
+ using (var source = OpenKey32(writable: true))
+ {
+ source.DeleteSubKeyTree(LocalServer32Key, false);
+ source.CreateSubKey(InprocServer32Key)?.SetValue(string.Empty, @"C:\fake\preview32.dll");
+ }
+
+ Assert.False(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+ Assert.Null(OpenMirror());
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_KeepsMirrorWhenLocalServer32CannotBeRead()
+ {
+ Create32BitRegistration("WPS 文字 预览器", @"C:\Program Files (x86)\Kingsoft\WPS Office\wps.exe");
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+
+ using var source = OpenKey32(writable: true);
+ using var localServer32 = source.OpenSubKey(
+ LocalServer32Key,
+ RegistryKeyPermissionCheck.ReadWriteSubTree,
+ RegistryRights.ChangePermissions | RegistryRights.ReadPermissions);
+ Assert.NotNull(localServer32);
+
+ var denyRule = new RegistryAccessRule(
+ WindowsIdentity.GetCurrent().User,
+ RegistryRights.ReadKey,
+ AccessControlType.Deny);
+
+ var deniedSecurity = localServer32.GetAccessControl();
+ deniedSecurity.AddAccessRule(denyRule);
+
+ try
+ {
+ localServer32.SetAccessControl(deniedSecurity);
+
+ // Sanity check: the subkey must really be unreadable now, otherwise the test proves nothing.
+ var denied = false;
+ try
+ {
+ using var probe = source.OpenSubKey(LocalServer32Key);
+ denied = probe == null;
+ }
+ catch (Exception)
+ {
+ denied = true;
+ }
+
+ Assert.True(denied, "the LocalServer32 subkey is still readable, so the test cannot prove the invariant");
+
+ // A failed read is not proof that the source is gone, so the mirror must survive.
+ Assert.False(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+ Assert.NotNull(OpenMirror());
+ }
+ finally
+ {
+ // Passing the originally captured security descriptor back does not remove the deny
+ // ACE (the descriptor is auto-inherited), so remove the rule explicitly.
+ var cleanup = localServer32.GetAccessControl();
+ cleanup.RemoveAccessRuleAll(denyRule);
+ localServer32.SetAccessControl(cleanup);
+ }
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_RejectsLocalServer32WithoutACommand()
+ {
+ using (var source = Create32BitRegistration("Previewer without a command", null))
+ {
+ source.CreateSubKey(LocalServer32Key)?.SetValue("ThreadingModel", "Both");
+ }
+
+ Assert.False(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+ Assert.Null(OpenMirror());
+ }
+
+ [Fact]
+ public void EnsureRegisteredForCurrentView_AcceptsServerExecutableWithoutADefaultCommand()
+ {
+ using (var source = Create32BitRegistration("WPS 表格 预览器", null))
+ {
+ source.CreateSubKey(LocalServer32Key)?.SetValue("ServerExecutable", @"C:\Program Files (x86)\Kingsoft\WPS Office\et.exe");
+ }
+
+ Assert.True(PreviewHandlerRegistration.EnsureRegisteredForCurrentView(_clsid));
+
+ using var mirror = OpenMirror();
+ Assert.NotNull(mirror);
+ using var localServer = mirror.OpenSubKey(LocalServer32Key);
+ Assert.NotNull(localServer);
+ Assert.Equal(
+ @"C:\Program Files (x86)\Kingsoft\WPS Office\et.exe",
+ localServer.GetValue("ServerExecutable") as string);
+ }
+
+ [Fact]
+ public void IsRegisteredForCurrentView_RequiresDisplayNameAndActivation()
+ {
+ using (var current = OpenKey64(writable: true))
+ {
+ current.SetValue(string.Empty, "Name only");
+ }
+
+ Assert.False(PreviewHandlerRegistration.IsRegisteredForCurrentView(_clsid));
+
+ using (var current = OpenKey64(writable: true))
+ {
+ current.SetValue(string.Empty, string.Empty);
+ current.CreateSubKey(LocalServer32Key)?.SetValue(string.Empty, @"C:\fake\server.exe");
+ }
+
+ Assert.False(PreviewHandlerRegistration.IsRegisteredForCurrentView(_clsid));
+
+ using (var current = OpenKey64(writable: true))
+ {
+ current.SetValue(string.Empty, "Complete registration");
+ }
+
+ Assert.True(PreviewHandlerRegistration.IsRegisteredForCurrentView(_clsid));
+ }
+
+ private RegistryKey Create32BitRegistration(string displayName, string localServerCommand)
+ {
+ using var classes = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
+ var key = classes.CreateSubKey(KeyPath32);
+
+ if (displayName != null)
+ key.SetValue(string.Empty, displayName);
+
+ if (localServerCommand != null)
+ key.CreateSubKey(LocalServer32Key)?.SetValue(string.Empty, localServerCommand);
+
+ return key;
+ }
+
+ private RegistryKey OpenKey32(bool writable)
+ {
+ using var classes = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
+ return writable
+ ? classes.CreateSubKey(KeyPath32)
+ : classes.OpenSubKey(KeyPath32);
+ }
+
+ private RegistryKey OpenKey64(bool writable)
+ {
+ using var classes = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
+ return writable
+ ? classes.CreateSubKey(KeyPath64)
+ : classes.OpenSubKey(KeyPath64);
+ }
+
+ private RegistryKey OpenMirror() => OpenKey64(writable: false);
+
+ private void DeleteKey(int view)
+ {
+ var path = view == 32 ? KeyPath32 : KeyPath64;
+
+ try
+ {
+ using var classes = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
+ classes.DeleteSubKeyTree(path, throwOnMissingSubKey: false);
+ }
+ catch (Exception)
+ {
+ // A test must not fail because cleanup raced with another test process.
+ }
+ }
+
+ private string KeyPath32 => $@"Software\Classes\WOW6432Node\CLSID\{_clsid:B}";
+
+ private string KeyPath64 => $@"Software\Classes\CLSID\{_clsid:B}";
+}
diff --git a/tests/QuickLook.Tests/QuickLook.Tests.csproj b/tests/QuickLook.Tests/QuickLook.Tests.csproj
new file mode 100644
index 000000000..f5af4cdf2
--- /dev/null
+++ b/tests/QuickLook.Tests/QuickLook.Tests.csproj
@@ -0,0 +1,30 @@
+
+
+
+ net8.0-windows
+ latest
+ disable
+ false
+ AnyCPU
+ QuickLook.Tests
+ QuickLook.Tests
+
+
+
+
+
+ PreviewHandlerRegistration.cs
+
+
+
+
+
+
+
+
+
+