diff --git a/QuickLook.Native/QuickLook.Native32/Everything.cpp b/QuickLook.Native/QuickLook.Native32/Everything.cpp
index b4e4177c3..8f8ca487e 100644
--- a/QuickLook.Native/QuickLook.Native32/Everything.cpp
+++ b/QuickLook.Native/QuickLook.Native32/Everything.cpp
@@ -1,68 +1,360 @@
// 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 .
#include "stdafx.h"
#include "Everything.h"
+#include
+
+// Everything 1.4 has no IPC call that returns the selected file, so QuickLook asks Everything to
+// copy the selected path to the clipboard and reads it from there. Without care that destroys
+// whatever the user had copied (issues #593, #1179), so the user's clipboard is saved before the
+// copy and put back afterwards.
+
+namespace
+{
+ // Don't keep more than this much clipboard data in memory for the restore. Above it, the
+ // clipboard is left as Everything set it (the old behaviour) rather than risk a huge allocation.
+ const SIZE_T MAX_BACKUP_BYTES = 256 * 1024 * 1024;
+
+ struct ClipboardItem
+ {
+ UINT format;
+ HANDLE data;
+ };
+
+ bool OpenClipboardWithRetry(HWND owner)
+ {
+ // Another program (often a clipboard manager reacting to Everything's copy) may have the
+ // clipboard open for a moment.
+ for (int i = 0; i < 20; i++)
+ {
+ if (OpenClipboard(owner))
+ return true;
+ Sleep(10);
+ }
+ return false;
+ }
+
+ bool IsOleInternalFormat(UINT format)
+ {
+ // These describe the OLE data object that put the data on the clipboard. It is gone once
+ // the clipboard changes, so restoring them would point OLE at a dead object. Without them
+ // OLE falls back to the plain formats, which are restored.
+ static const UINT cfDataObject = RegisterClipboardFormatW(L"DataObject");
+ static const UINT cfOlePrivateData = RegisterClipboardFormatW(L"Ole Private Data");
+ return format == cfDataObject || format == cfOlePrivateData;
+ }
+
+ HANDLE DuplicateGlobal(HANDLE source, SIZE_T& budget, bool& overBudget)
+ {
+ SIZE_T size = GlobalSize(source);
+ if (size == 0)
+ return nullptr;
+ if (size > budget)
+ {
+ overBudget = true;
+ return nullptr;
+ }
+
+ void* src = GlobalLock(source);
+ if (src == nullptr)
+ return nullptr;
+
+ HGLOBAL copy = GlobalAlloc(GMEM_MOVEABLE, size);
+ if (copy != nullptr)
+ {
+ void* dst = GlobalLock(copy);
+ if (dst != nullptr)
+ {
+ memcpy(dst, src, size);
+ GlobalUnlock(copy);
+ budget -= size;
+ }
+ else
+ {
+ GlobalFree(copy);
+ copy = nullptr;
+ }
+ }
+
+ GlobalUnlock(source);
+ return copy;
+ }
+
+ HANDLE DuplicateMetafilePict(HANDLE source)
+ {
+ auto src = static_cast(GlobalLock(source));
+ if (src == nullptr)
+ return nullptr;
+
+ HGLOBAL copy = nullptr;
+ HMETAFILE metafile = CopyMetaFileW(src->hMF, nullptr);
+ if (metafile != nullptr)
+ {
+ copy = GlobalAlloc(GMEM_MOVEABLE, sizeof(METAFILEPICT));
+ auto dst = copy != nullptr ? static_cast(GlobalLock(copy)) : nullptr;
+ if (dst != nullptr)
+ {
+ *dst = *src;
+ dst->hMF = metafile;
+ GlobalUnlock(copy);
+ }
+ else
+ {
+ if (copy != nullptr)
+ GlobalFree(copy);
+ copy = nullptr;
+ DeleteMetaFile(metafile);
+ }
+ }
+
+ GlobalUnlock(source);
+ return copy;
+ }
+
+ // Returns a copy of one clipboard item that can be handed to SetClipboardData later, or nullptr
+ // for items that can't be copied (they are skipped).
+ HANDLE DuplicateClipboardData(UINT format, HANDLE source, SIZE_T& budget, bool& overBudget)
+ {
+ switch (format)
+ {
+ case CF_BITMAP:
+ case CF_DSPBITMAP:
+ return CopyImage(source, IMAGE_BITMAP, 0, 0, 0);
+ case CF_ENHMETAFILE:
+ case CF_DSPENHMETAFILE:
+ return CopyEnhMetaFileW(static_cast(source), nullptr);
+ case CF_METAFILEPICT:
+ case CF_DSPMETAFILEPICT:
+ return DuplicateMetafilePict(source);
+ case CF_PALETTE: // GDI palette; Windows rebuilds it from the bitmap formats
+ case CF_OWNERDISPLAY: // drawn on demand by the original owner window
+ return nullptr;
+ default:
+ break;
+ }
+
+ // Private and GDI-object formats hold handles whose type only the owner knows.
+ if ((format >= CF_PRIVATEFIRST && format <= CF_PRIVATELAST) ||
+ (format >= CF_GDIOBJFIRST && format <= CF_GDIOBJLAST) ||
+ IsOleInternalFormat(format))
+ return nullptr;
+
+ // Everything else, including registered formats such as file lists, is global memory.
+ return DuplicateGlobal(source, budget, overBudget);
+ }
+
+ void FreeClipboardData(const ClipboardItem& item)
+ {
+ switch (item.format)
+ {
+ case CF_BITMAP:
+ case CF_DSPBITMAP:
+ DeleteObject(item.data);
+ break;
+ case CF_ENHMETAFILE:
+ case CF_DSPENHMETAFILE:
+ DeleteEnhMetaFile(static_cast(item.data));
+ break;
+ case CF_METAFILEPICT:
+ case CF_DSPMETAFILEPICT:
+ {
+ auto pict = static_cast(GlobalLock(item.data));
+ if (pict != nullptr)
+ {
+ DeleteMetaFile(pict->hMF);
+ GlobalUnlock(item.data);
+ }
+ GlobalFree(item.data);
+ break;
+ }
+ default:
+ GlobalFree(item.data);
+ break;
+ }
+ }
+
+ void FreeClipboardBackup(std::vector& backup)
+ {
+ for (auto& item : backup)
+ FreeClipboardData(item);
+ backup.clear();
+ }
+
+ // Copies every format currently on the clipboard. Returns false if the clipboard couldn't be
+ // read or was too large; the backup is then empty and nothing should be restored.
+ bool BackupClipboard(std::vector& backup)
+ {
+ if (!OpenClipboardWithRetry(nullptr))
+ return false;
+
+ SIZE_T budget = MAX_BACKUP_BYTES;
+ bool overBudget = false;
+
+ // Enumeration order is the owner's order of preference, so keep it for the restore.
+ for (UINT format = EnumClipboardFormats(0); format != 0 && !overBudget;
+ format = EnumClipboardFormats(format))
+ {
+ HANDLE data = GetClipboardData(format);
+ if (data == nullptr)
+ continue;
+
+ HANDLE copy = DuplicateClipboardData(format, data, budget, overBudget);
+ if (copy != nullptr)
+ backup.push_back({ format, copy });
+ }
+
+ CloseClipboard();
+
+ if (overBudget)
+ FreeClipboardBackup(backup);
+ return !overBudget;
+ }
+
+ // Puts the backed-up items back on the clipboard. Ownership of every handle passes to the
+ // clipboard (or is freed here), so the backup is empty afterwards.
+ void RestoreClipboard(std::vector& backup, DWORD expectedSequence)
+ {
+ // EmptyClipboard() makes the window passed to OpenClipboard() the clipboard owner, and
+ // SetClipboardData() fails when that owner is NULL, so open it with a window of our own.
+ HWND owner = CreateWindowExW(0, L"STATIC", nullptr, 0, 0, 0, 0, 0,
+ HWND_MESSAGE, nullptr, nullptr, nullptr);
+ if (owner == nullptr)
+ {
+ FreeClipboardBackup(backup);
+ return;
+ }
+
+ if (OpenClipboardWithRetry(owner))
+ {
+ // If anything other than Everything has changed the clipboard since we read the
+ // path, that content is newer than the backup: keep it.
+ if (GetClipboardSequenceNumber() == expectedSequence && EmptyClipboard())
+ {
+ for (auto& item : backup)
+ {
+ if (SetClipboardData(item.format, item.data) == nullptr)
+ FreeClipboardData(item); // not taken by the clipboard
+ }
+ backup.clear();
+ }
+ CloseClipboard();
+ }
+
+ FreeClipboardBackup(backup); // frees anything not handed to the clipboard
+ DestroyWindow(owner);
+ }
+
+ // Copies the first line of the CF_UNICODETEXT clipboard item into buffer. Returns the
+ // clipboard sequence number at the time it was read, or 0 if nothing was read.
+ DWORD ReadPathFromClipboard(PWCHAR buffer)
+ {
+ if (!OpenClipboardWithRetry(nullptr))
+ return 0;
+
+ DWORD sequence = 0;
+ HANDLE data = GetClipboardData(CF_UNICODETEXT);
+ auto text = data != nullptr ? static_cast(GlobalLock(data)) : nullptr;
+ if (text != nullptr)
+ {
+ sequence = GetClipboardSequenceNumber();
+
+ // Don't trust the text to be null-terminated within its allocation.
+ size_t length = wcsnlen(text, GlobalSize(data) / sizeof(WCHAR));
+ auto lineEnd = wmemchr(text, L'\r', length);
+ if (lineEnd != nullptr)
+ length = lineEnd - text;
+
+ // Everything's "Double quote copy as path" option wraps the path in quotes.
+ if (length >= 2 && text[0] == L'"' && text[length - 1] == L'"')
+ {
+ text++;
+ length -= 2;
+ }
+
+ // A longer path would be truncated into a different one; return nothing instead.
+ if (length > 0 && length < MAX_PATH_EX)
+ wcsncpy_s(buffer, MAX_PATH_EX, text, length);
+
+ GlobalUnlock(data);
+ }
+
+ CloseClipboard();
+ return sequence;
+ }
+}
+
void Everything::GetSelected(PWCHAR buffer)
{
auto hWinFG = GetForegroundWindow();
-
+
// Everything v1.5 IPC via hidden window.
HWND hWinI = FindWindowExW(hWinFG, NULL, EVERYTHING_IPC_HIDDEN_WIN_CLASS, NULL);
-
+
if (hWinI != nullptr) {
- int pLength = GetWindowTextLength(hWinI);
- wchar_t* pText = new wchar_t[pLength + 1];
- GetWindowText(hWinI, pText, pLength + 1);
- wcsncpy_s(buffer, MAX_PATH_EX, pText, pLength);
+ int length = GetWindowTextLengthW(hWinI);
+ if (length > 0 && length < MAX_PATH_EX)
+ GetWindowTextW(hWinI, buffer, MAX_PATH_EX);
return; // Success. Clipboard access unnecessary.
}
HWND hWin = FindWindowW(EVERYTHING_IPC_WINDOW_CLASS, NULL);
+ if (hWin == nullptr)
+ return;
- if (hWin != nullptr) {
- // Everything IPC Clipboard
- SendMessageW(
- hWin,
- WM_COMMAND,
- MAKEWPARAM(EVERYTHING_IPC_COPY_TO_CLIPBOARD, 0),
- 0);
-
- Sleep(100);
-
- if (!OpenClipboard(nullptr))
- return;
-
- auto hData = GetClipboardData(CF_UNICODETEXT);
- if (hData == nullptr)
- return;
+ std::vector backup;
+ bool haveBackup = BackupClipboard(backup);
+ DWORD sequenceBefore = GetClipboardSequenceNumber();
- auto pText = static_cast(GlobalLock(hData));
- if (pText == nullptr)
- return;
+ // Everything IPC Clipboard. Don't hang if Everything isn't responding.
+ DWORD_PTR result = 0;
+ if (!SendMessageTimeoutW(
+ hWin,
+ WM_COMMAND,
+ MAKEWPARAM(EVERYTHING_IPC_COPY_TO_CLIPBOARD, 0),
+ 0,
+ SMTO_ABORTIFHUNG,
+ 1000,
+ &result))
+ {
+ FreeClipboardBackup(backup);
+ return;
+ }
- auto p = wcsstr(pText, L"\r\n");
- auto l = p == nullptr ? wcslen(pText) : p - pText;
- wcsncpy_s(buffer, MAX_PATH_EX, pText, l); // Everything supports Long Path
-
- GlobalUnlock(hData);
- CloseClipboard();
+ // Everything normally copies before SendMessage returns, but give it a moment in case it
+ // doesn't.
+ for (int i = 0; i < 20 && GetClipboardSequenceNumber() == sequenceBefore; i++)
+ Sleep(10);
+
+ if (GetClipboardSequenceNumber() == sequenceBefore)
+ {
+ // Nothing was copied (e.g. nothing is selected). The clipboard still holds the user's
+ // own data, which is not a path, so don't read it.
+ FreeClipboardBackup(backup);
+ return;
}
+
+ DWORD sequenceRead = ReadPathFromClipboard(buffer);
+
+ if (haveBackup && sequenceRead != 0)
+ RestoreClipboard(backup, sequenceRead);
+ else
+ FreeClipboardBackup(backup);
}
bool Everything::MatchClass(PWCHAR classBuffer)
@@ -73,13 +365,3 @@ bool Everything::MatchClass(PWCHAR classBuffer)
wcsncpy_s(sMatchC, classBuffer, iLen);
return (0 == wcscmp(sMatchC, sMatchS));
}
-
-void Everything::backupClipboard()
-{
- // TODO
-}
-
-void Everything::restoreClipboard()
-{
- // TODO
-}
diff --git a/QuickLook.Native/QuickLook.Native32/Everything.h b/QuickLook.Native/QuickLook.Native32/Everything.h
index aa9707d7f..c99830fa9 100644
--- a/QuickLook.Native/QuickLook.Native32/Everything.h
+++ b/QuickLook.Native/QuickLook.Native32/Everything.h
@@ -25,8 +25,4 @@ class Everything
public:
static void GetSelected(PWCHAR buffer);
static bool MatchClass(PWCHAR classBuffer);
-
-private:
- static void backupClipboard();
- static void restoreClipboard();
};
diff --git a/QuickLook/FocusMonitor.cs b/QuickLook/FocusMonitor.cs
index 1cb616b06..e3b8b3de9 100644
--- a/QuickLook/FocusMonitor.cs
+++ b/QuickLook/FocusMonitor.cs
@@ -15,6 +15,7 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
+using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
@@ -36,15 +37,35 @@ public void Start()
new Task(() =>
{
var last = string.Empty;
+ uint? lastEverythingInput = null;
+ var everythingQueried = false;
while (IsRunning)
{
Thread.Sleep(500);
- if (NativeMethods.QuickLook.GetFocusedWindowType() ==
- NativeMethods.QuickLook.FocusedWindowType.Invalid)
+ var windowType = NativeMethods.QuickLook.GetFocusedWindowType();
+ if (windowType == NativeMethods.QuickLook.FocusedWindowType.Invalid)
continue;
+ // Everything 1.4 only gives out the selected file by copying its path to the
+ // clipboard, so every query rewrites the clipboard (#593, #1179). The selection
+ // can't change without keyboard or mouse input, so don't ask again until there
+ // has been some.
+ if (windowType == NativeMethods.QuickLook.FocusedWindowType.Everything)
+ {
+ var input = GetLastInputTick();
+ if (everythingQueried && input != null && input == lastEverythingInput)
+ continue;
+
+ lastEverythingInput = input;
+ everythingQueried = true;
+ }
+ else
+ {
+ everythingQueried = false;
+ }
+
var path = NativeMethods.QuickLook.GetCurrentSelection();
if (IsRunning && last != path)
{
@@ -64,4 +85,21 @@ internal static FocusMonitor GetInstance()
{
return _instance ??= new FocusMonitor();
}
+
+ private static uint? GetLastInputTick()
+ {
+ var info = new LASTINPUTINFO { cbSize = (uint)Marshal.SizeOf() };
+ return GetLastInputInfo(ref info) ? info.dwTime : (uint?)null;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct LASTINPUTINFO
+ {
+ public uint cbSize;
+ public uint dwTime;
+ }
+
+ [DllImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
}