From d4f9232dca9b11e577a74aa1fd5f7557fe5757fb Mon Sep 17 00:00:00 2001
From: hoyin-law <54151957+hoyin-law@users.noreply.github.com>
Date: Mon, 2 Nov 2026 22:10:13 +0800
Subject: [PATCH 1/5] Fix Office preview for handlers registered in the 32-bit
registry view only
---
OPTIONS.md | 7 +
.../QuickLook.Plugin.OfficeViewer/Plugin.cs | 62 ++--
.../PreviewHandlerRegistration.cs | 297 ++++++++++++++++++
3 files changed, 338 insertions(+), 28 deletions(-)
create mode 100644 QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
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..1452e1ba4 100644
--- a/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/Plugin.cs
+++ b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/Plugin.cs
@@ -60,41 +60,47 @@ public bool CanHandle(string path)
if (!checkPreviewHandler)
return true;
- if (!string.IsNullOrWhiteSpace(CLSIDRegister.GetName(previewHandler.ToString("B"))))
- {
+ // 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. See also:
+ // PreviewHandlerRegistration.
+ var fixPreviewHandlerRegistration = SettingHelper.Get("FixPreviewHandlerRegistration", true, "QuickLook.Plugin.OfficeViewer");
+ if (fixPreviewHandlerRegistration && PreviewHandlerRegistration.EnsureRegisteredForCurrentView(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.
+
+ if (PreviewHandlerRegistration.IsRegisteredForCurrentView(previewHandler))
+ return true;
+
+ // 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..92c773ec1
--- /dev/null
+++ b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
@@ -0,0 +1,297 @@
+// 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;
+
+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)
+ return false;
+
+ if (!source.IsLocalServer)
+ {
+ // 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,
+ InprocHandler32 = clsidKey.OpenSubKey(InprocHandler32Key)?.GetValue(string.Empty) as string,
+ InprocServer32 = clsidKey.OpenSubKey(InprocServer32Key)?.GetValue(string.Empty) as string,
+ };
+
+ using var localServer32 = clsidKey.OpenSubKey(LocalServer32Key);
+ if (localServer32 != null)
+ {
+ // Copy every value, including named values such as ServerExecutable, instead of
+ // only the default command line.
+ foreach (var name in localServer32.GetValueNames())
+ registration.LocalServerValues[name] = localServer32.GetValue(name) as string;
+ }
+
+ return registration;
+ }
+ catch (Exception e)
+ {
+ Debug.WriteLine("Error reading preview handler registration: " + e);
+ return null;
+ }
+ }
+
+ ///
+ /// 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;
+ }
+ }
+
+ ///
+ /// 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)
+ {
+ var keyPath = $@"Software\Classes\{ClassesRootPath}\{clsid:B}";
+ var createdNew = false;
+
+ try
+ {
+ using var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
+ createdNew = currentUser.OpenSubKey(keyPath) == null;
+
+ using var clsid64 = currentUser.CreateSubKey(keyPath);
+ if (clsid64 == null)
+ return false;
+
+ if (replaceExisting)
+ {
+ // 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 a value indicating whether an out-of-process server is registered.
+ public bool IsLocalServer => LocalServerValues.Count > 0;
+
+ /// 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;
+ }
+ }
+}
From ddb81980e684d57dc17599cc750afcd03f39efbb Mon Sep 17 00:00:00 2001
From: hoyin-law <54151957+hoyin-law@users.noreply.github.com>
Date: Wed, 4 Nov 2026 21:32:16 +0800
Subject: [PATCH 2/5] Run the registration fix before the CheckPreviewHandler
early return
- CanHandle now mirrors 32-bit handlers even when CheckPreviewHandler is
disabled. That setting skips the availability check; it does not opt out
of making an otherwise unusable handler work.
- Skip non-string LocalServer32 values instead of storing null. A single
REG_DWORD value made WriteMirror throw and left no mirror at all.
- Refuse to write a mirror when the 32-bit source has no display name.
---
.../QuickLook.Plugin.OfficeViewer/Plugin.cs | 14 ++++++++------
.../PreviewHandlerRegistration.cs | 17 +++++++++++++----
2 files changed, 21 insertions(+), 10 deletions(-)
diff --git a/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/Plugin.cs b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/Plugin.cs
index 1452e1ba4..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,20 +56,22 @@ public bool CanHandle(string path)
if (previewHandler == Guid.Empty)
return false;
- var checkPreviewHandler = SettingHelper.Get("CheckPreviewHandler", true, "QuickLook.Plugin.OfficeViewer");
- if (!checkPreviewHandler)
- return true;
-
// 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. See also:
+ // 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 (PreviewHandlerRegistration.IsRegisteredForCurrentView(previewHandler))
return true;
diff --git a/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
index 92c773ec1..08cf67601 100644
--- a/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
+++ b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
@@ -1,4 +1,4 @@
-// Copyright © 2017-2026 QL-Win Contributors
+// Copyright © 2017-2026 QL-Win Contributors
//
// This file is part of QuickLook program.
//
@@ -130,10 +130,14 @@ private static HandlerRegistration ReadRegistration(Guid clsid, RegistryView vie
using var localServer32 = clsidKey.OpenSubKey(LocalServer32Key);
if (localServer32 != null)
{
- // Copy every value, including named values such as ServerExecutable, instead of
- // only the default command line.
+ // 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())
- registration.LocalServerValues[name] = localServer32.GetValue(name) as string;
+ {
+ if (localServer32.GetValue(name) is string value)
+ registration.LocalServerValues[name] = value;
+ }
}
return registration;
@@ -174,6 +178,11 @@ private static bool IsMirror(Guid clsid)
/// 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;
From 5560d5118b3cf5e33cb19dfe81be6ec65c187846 Mon Sep 17 00:00:00 2001
From: hoyin-law <54151957+hoyin-law@users.noreply.github.com>
Date: Wed, 4 Nov 2026 21:32:20 +0800
Subject: [PATCH 3/5] Add registry-backed tests for PreviewHandlerRegistration
tests/QuickLook.Tests covers the 32-bit preview handler mirroring logic:
creation, named LocalServer32 values, non-string values, untouched
non-mirror registrations, refresh of stale mirrors, idempotency,
in-process only handlers, incomplete sources, and the display name plus
activation requirement.
The plugin targets .NET Framework 4.6.2, which a modern test project
cannot reference, so the single source file under test is compiled into
the test assembly. The tests use a unique CLSID per test and only touch
HKCU, deleting everything they create.
A tests workflow runs the suite on pull requests.
---
.github/workflows/tests.yml | 29 ++
.../PreviewHandlerRegistrationTests.cs | 264 ++++++++++++++++++
tests/QuickLook.Tests/QuickLook.Tests.csproj | 30 ++
3 files changed, 323 insertions(+)
create mode 100644 .github/workflows/tests.yml
create mode 100644 tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs
create mode 100644 tests/QuickLook.Tests/QuickLook.Tests.csproj
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/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs b/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs
new file mode 100644
index 000000000..2775ccd71
--- /dev/null
+++ b/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs
@@ -0,0 +1,264 @@
+// 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 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 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
+
+
+
+
+
+
+
+
+
+
From 5c9c42932029dcda5479a0f6b9699e2c0155457c Mon Sep 17 00:00:00 2001
From: hoyin-law <54151957+hoyin-law@users.noreply.github.com>
Date: Wed, 4 Nov 2026 21:41:17 +0800
Subject: [PATCH 4/5] Harden preview handler mirroring and cover it with tests
- Remove a QuickLook-created mirror only after confirming that the 32-bit
source key is really gone, so an uninstalled Office suite does not leave
a stale mirror behind. Read errors are treated as unknown, not absent.
- Treat a LocalServer32 key as registrable only when it has a non-blank
default command or a non-blank ServerExecutable value.
- Mark a mirror incomplete before refreshing it, and dispose the key used
to detect an existing mirror.
- Add tests for the three new behaviors (13 passing).
---
.../PreviewHandlerRegistration.cs | 72 +++++++++++++++++--
.../PreviewHandlerRegistrationTests.cs | 43 +++++++++++
2 files changed, 110 insertions(+), 5 deletions(-)
diff --git a/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
index 08cf67601..10b849861 100644
--- a/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
+++ b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
@@ -81,7 +81,14 @@ 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)
{
@@ -123,10 +130,14 @@ private static HandlerRegistration ReadRegistration(Guid clsid, RegistryView vie
var registration = new HandlerRegistration
{
DisplayName = clsidKey.GetValue(string.Empty) as string,
- InprocHandler32 = clsidKey.OpenSubKey(InprocHandler32Key)?.GetValue(string.Empty) as string,
- InprocServer32 = clsidKey.OpenSubKey(InprocServer32Key)?.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 = clsidKey.OpenSubKey(LocalServer32Key);
if (localServer32 != null)
{
@@ -169,6 +180,47 @@ private static bool IsMirror(Guid clsid)
}
}
+ ///
+ /// 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.
///
@@ -189,7 +241,8 @@ private static bool WriteMirror(Guid clsid, HandlerRegistration source, bool rep
try
{
using var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
- createdNew = currentUser.OpenSubKey(keyPath) == null;
+ using (var existing = currentUser.OpenSubKey(keyPath))
+ createdNew = existing == null;
using var clsid64 = currentUser.CreateSubKey(keyPath);
if (clsid64 == null)
@@ -197,6 +250,10 @@ private static bool WriteMirror(Guid clsid, HandlerRegistration source, bool rep
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);
@@ -262,8 +319,13 @@ private sealed class HandlerRegistration
/// Gets the LocalServer32 values, including named values.
public Dictionary LocalServerValues { get; } = new(StringComparer.OrdinalIgnoreCase);
- /// Gets a value indicating whether an out-of-process server is registered.
- public bool IsLocalServer => LocalServerValues.Count > 0;
+ ///
+ /// 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);
diff --git a/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs b/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs
index 2775ccd71..76968d289 100644
--- a/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs
+++ b/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs
@@ -185,6 +185,49 @@ public void EnsureRegisteredForCurrentView_ReturnsFalseWhen32BitRegistrationHasN
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_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()
{
From fd5a45feadc599cf9103a642f6844c1a6d593b1b Mon Sep 17 00:00:00 2001
From: hoyin-law <54151957+hoyin-law@users.noreply.github.com>
Date: Fri, 6 Nov 2026 11:58:39 +0800
Subject: [PATCH 5/5] Harden mirror lifecycle for unreadable sources and new
keys
- Remove a QuickLook mirror when the 32-bit source no longer registers an
out-of-process server, but keep it when LocalServer32 exists and cannot
be read (ACL, damaged hive): a failed read must not delete a mirror that
still works.
- Write the QuickLookMirror marker as soon as a new mirror key is created,
so an interrupted first write is repaired on the next attempt instead of
being mistaken for a user-owned registration.
- Tests: mirror removal when the source stops being a local server, and
mirror retention when LocalServer32 is unreadable (deny-read ACL).
15 tests, all passing.
---
.../PreviewHandlerRegistration.cs | 70 +++++++++++++++++-
.../PreviewHandlerRegistrationTests.cs | 72 +++++++++++++++++++
2 files changed, 141 insertions(+), 1 deletion(-)
diff --git a/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
index 10b849861..197e75b37 100644
--- a/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
+++ b/QuickLook.Plugin/QuickLook.Plugin.OfficeViewer/PreviewHandlerRegistration.cs
@@ -19,6 +19,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
+using System.Linq;
namespace QuickLook.Plugin.OfficeViewer;
@@ -92,6 +93,13 @@ public static bool EnsureRegisteredForCurrentView(Guid clsid)
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)
@@ -138,7 +146,7 @@ private static HandlerRegistration ReadRegistration(Guid clsid, RegistryView vie
using (var inprocServer32 = clsidKey.OpenSubKey(InprocServer32Key))
registration.InprocServer32 = inprocServer32?.GetValue(string.Empty) as string;
- using var localServer32 = clsidKey.OpenSubKey(LocalServer32Key);
+ using var localServer32 = TryOpenLocalServer32(clsidKey, registration);
if (localServer32 != null)
{
// Copy every string value, including named values such as ServerExecutable, instead
@@ -160,6 +168,55 @@ private static HandlerRegistration ReadRegistration(Guid clsid, RegistryView vie
}
}
+ ///
+ /// 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.
///
@@ -248,6 +305,11 @@ private static bool WriteMirror(Guid clsid, HandlerRegistration source, bool rep
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
@@ -319,6 +381,12 @@ private sealed class HandlerRegistration
/// 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.
diff --git a/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs b/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs
index 76968d289..fbb3e8185 100644
--- a/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs
+++ b/tests/QuickLook.Tests/PreviewHandlerRegistrationTests.cs
@@ -18,6 +18,8 @@
using Microsoft.Win32;
using QuickLook.Plugin.OfficeViewer;
using System;
+using System.Security.AccessControl;
+using System.Security.Principal;
using Xunit;
namespace QuickLook.Tests;
@@ -197,6 +199,76 @@ public void EnsureRegisteredForCurrentView_RemovesMirrorWhen32BitSourceIsGone()
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()
{