Compare commits

...

4 Commits

17 changed files with 312 additions and 49 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24) cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.40 LANGUAGES CXX RC) project(KSwitcher VERSION 0.6.44 LANGUAGES CXX RC)
if(NOT WIN32) if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs") message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif() endif()
+16 -1
View File
@@ -75,6 +75,9 @@ Ctrl+Alt+Delete and Win+L; these cannot be assigned.
Keyboard and mouse input forwarded by Microsoft Mouse Without Borders follows the same input Keyboard and mouse input forwarded by Microsoft Mouse Without Borders follows the same input
path as a local keyboard/mouse, including shortcuts, recent-word conversion and snippets. path as a local keyboard/mouse, including shortcuts, recent-word conversion and snippets.
On the sending computer, KSwitcher ignores keyboard events consumed by another keyboard hook
(including Mouse Without Borders forwarding). The receiving computer still processes delivered
input normally, so both computers can run KSwitcher without starting duplicate snippet operations.
KSwitcher marks its own generated input so copy/paste, selection, modifier releases and shell-mask KSwitcher marks its own generated input so copy/paste, selection, modifier releases and shell-mask
keys cannot trigger recursive commands or overwrite the recorded typing run. Other injected input keys cannot trigger recursive commands or overwrite the recorded typing run. Other injected input
is accepted, including key-up events and VK-only keyboard events. Unicode packets do not provide is accepted, including key-up events and VK-only keyboard events. Unicode packets do not provide
@@ -274,10 +277,18 @@ thumbnails and source labels aligned with the scaled fonts and spacing.
of the complete expected text. Browser/editor compatibility depends on its handling of simulated input. of the complete expected text. Browser/editor compatibility depends on its handling of simulated input.
- Selection conversion and verified recent input (physical scan codes, 2-second typing-run boundary). - Selection conversion and verified recent input (physical scan codes, 2-second typing-run boundary).
- Same-process clipboard ownership plus verified WebView2 descendants, including the Teams fix. - Same-process clipboard ownership plus verified WebView2 descendants, including the Teams fix.
Clipboard synchronizers such as Mouse Without Borders may republish a copy only when
KSwitcher first observed it owned by the target application and the selection text and
editor selection metadata remain identical. Unobserved or altered foreign copies are rejected.
Snippets require accessibility verification of their selected trigger and pasted text,
even with logging disabled. If verification is unavailable or the paste differs, expansion
stops without running cursor or Enter actions. Clipboard changes during paste also cancel actions.
- Teams recent-word conversion uses a single word-selection command and validates the copied range. - Teams recent-word conversion uses a single word-selection command and validates the copied range.
If the editor's word boundary differs from the recorded typing, it falls back to paced character If the editor's word boundary differs from the recorded typing, it falls back to paced character
selection: Teams can coalesce a burst of Shift+Left events into just one character. selection: Teams can coalesce a burst of Shift+Left events into just one character.
- Clipboard snapshot/restoration with concurrent-copy, foreground and input-version checks. - Clipboard snapshot/restoration with concurrent-copy, foreground and input-version checks.
A snapshot interrupted by a concurrent clipboard publication is retried up to three total
attempts before selection starts, provided the foreground and input context remain unchanged.
A silently dropped copy is retried up to three total attempts while the clipboard and input A silently dropped copy is retried up to three total attempts while the clipboard and input
context remain unchanged. Temporary transaction contents are excluded from Windows clipboard context remain unchanged. Temporary transaction contents are excluded from Windows clipboard
history and cloud synchronization. Paste is not blindly retried: with manual paste readback history and cloud synchronization. Paste is not blindly retried: with manual paste readback
@@ -720,9 +731,13 @@ Consecutive duplicates use SHA-256 fingerprints inside the encrypted history ind
Moving OCR isolates its temporary memory rather than reducing the combined processing peak. A controlled three-run comparison retained about 0.8 MiB less private RAM in the caller after recognition; combined peak RAM was about 55.6 MiB before and 56.6 MiB with the helper. Results depend on the image, OCR engine and system. Moving OCR isolates its temporary memory rather than reducing the combined processing peak. A controlled three-run comparison retained about 0.8 MiB less private RAM in the caller after recognition; combined peak RAM was about 55.6 MiB before and 56.6 MiB with the helper. Results depend on the image, OCR engine and system.
### Pinned history checkbox — v0.6.42
Check **★ Pinned only** beside the history search box to show only pinned entries; uncheck it to show all entries. The checkbox sits on the left, immediately followed by the search box; its right edge stays aligned with the history list when resizing. The text search applies within that filter. Unpinning an item removes it from the pinned view immediately. The checkbox state and search are remembered after closing and reopening history. **Clear history…** still deletes the entire history after confirmation, including entries hidden by the filter.
### History process and clipboard memory — v0.6.40 ### History process and clipboard memory — v0.6.40
History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc** closes it even when focus is on the window or an action button, releasing Windows UI allocations with the process. The resident keeps keyboard hooks, clipboard capture and history storage. Search, selection and the top entry are preserved in encrypted view state. If a full-text item viewer is still open, the helper stays alive until the last viewer closes. Pin/delete, formatted/plain paste and OCR remain available; settings and default shortcuts are unchanged. History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc** closes it even when focus is on the window or an action button, releasing Windows UI allocations with the process. The resident keeps keyboard hooks, clipboard capture and history storage. Search and the pinned-only filter are preserved in encrypted view state. Each fresh opening selects and reveals the newest matching entry; background refreshes preserve the selected record while browsing. If a full-text item viewer is still open, the helper stays alive until the last viewer closes. Pin/delete, formatted/plain paste and OCR remain available; settings and default shortcuts are unchanged.
Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels. Image clipboard backup/restore also uses that helper and encrypted temporary files, with clipboard-sequence checks before restoring. Selection reads avoid loading image formats. Keep all three executables together; no fourth executable is required. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident. Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels. Image clipboard backup/restore also uses that helper and encrypted temporary files, with clipboard-sequence checks before restoring. Selection reads avoid loading image formats. Keep all three executables together; no fourth executable is required. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
Binary file not shown.
+9 -13
View File
@@ -1,24 +1,20 @@
# Latest Windows release # Latest Windows release
## v0.6.40 — 2026-11-04 ## v0.6.44 — 2026-11-05
v0.6.40 supersedes v0.6.39 to align Windows resource version metadata in the tagged source with the shipped binaries. Functional memory fixes are unchanged.
## Changes ## Changes
- Clipboard history runs in a separate, short-lived instance of KSwitcher.exe. Closing history with Esc releases its UI process instead of retaining Windows UI allocations in the resident. Esc also works when the window itself or an action button has focus. - Opening clipboard history selects and reveals the newest matching entry instead of restoring an older selection. This fixes reopening history after recording a new screenshot.
- Search, selected/top entry, pinning, deletion, formatted/plain paste and OCR remain available. Search and selection are saved in encrypted view state. An open full-text viewer keeps the history process alive until that viewer closes. - Search and the pinned-only filter remain saved. Clear the search and uncheck **★ Pinned only** if the new screenshot is hidden.
- Large image clipboard backups and image thumbnail decoding run in KSwitcher.Screenshot.exe. Encrypted temporary files and clipboard-sequence checks preserve the clipboard without keeping full backup images in the resident. Selection reads avoid unnecessary image copies. - Background clipboard/OCR refreshes preserve the selected record while browsing. Invoking the history shortcut while history is already active retains its existing quick-paste behavior.
- History paste waits briefly for the target application's foreground activation after the history process closes, while retaining input and clipboard ownership checks. Settings and default shortcuts are unchanged; UI Automation remains in the resident. - No shortcuts, settings, capture behavior or storage format changed.
## Validation and memory ## Validation
The complete staged build passed dictionary equivalence (140,939 words), 105 sync checks, 315 native checks, 561 input checks, screenshot UI/save/registration, 48 updater checks and progress UI, clipboard snapshot/image capture integration, conversion/snippet integration and Windows OCR. Dedicated 500-entry history tests cover repeated Esc, search persistence, pin/delete, full-viewer lifetime, text/image paste, clipboard restoration, rejected foreign requests and helper shutdown. Actual selected/repeated Viber conversion and live Esc were also checked during development. Passed dictionary equivalence checks for 140,939 words, 105 sync checks, shared wheel regressions, 319 native checks, 574 input checks, screenshot editor UI/save/registration, 48 updater checks and updater progress UI checks. The history regression covers reopening after a new image and preserving an explicitly selected older record during background refresh.
A local live development-build comparison measured **4.37 MiB before opening history and 4.35 MiB after two open/Esc cycles**, versus an earlier roughly 8–9 MiB plateau after closing history. A same-image backup benchmark reduced retained private resident memory from 12.78 MiB to 0.05 MiB. These are workload-specific observations, not a guaranteed footprint. Count all helper processes while history/OCR is active: combined active memory can be higher. No forced working-set trimming was used.
## Upgrade ## Upgrade
Choose **Update** in the tray menu. Legacy v0.3.0–v0.4.1 clients first receive the v0.4.2 compatibility bridge, then the current full release. v0.2.3 and earlier require manual installation. Choose **Update** in the tray menu. Legacy v0.3.0–v0.4.1 clients first receive the v0.4.2 compatibility bridge, then the current full release. v0.2.3 and earlier require manual installation.
For manual installation, exit KSwitcher, close screenshot editors and extract the entire ZIP into its installation folder. Keep personal `data/` and customized dictionaries. For manual installation, exit KSwitcher, close its configurator and screenshot editors, and extract the entire ZIP into its installation folder. Keep personal `data/` and customized dictionaries.
Download **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**. Keep all three executables together; history uses another instance of KSwitcher.exe, so no fourth executable is required. The package contains no personal settings, credentials or clipboard history. Download **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**. Keep all three executables together; history uses another instance of KSwitcher.exe. The package contains no personal settings, credentials or clipboard history.
Publish stable `release-vX.Y.Z` tags matching the executable version. Keep `v0.4.2` as the last legacy tag. Publish stable `release-vX.Y.Z` tags matching the executable version. Keep `v0.4.2` as the last legacy tag.
+1 -1
View File
@@ -1 +1 @@
cbe7839c849758b4623939dc025ec246a9fb97f5587df37ca6c3bd8eec244136 KSwitcher-win-x64.zip a3e8a42db787ab5b8edca698fc97943a3e0d5348c5000cc632aeb07179210469 KSwitcher-win-x64.zip
+3 -3
View File
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest" 1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1" 201 RCDATA "update.ps1"
1 VERSIONINFO 1 VERSIONINFO
FILEVERSION 0,6,40,0 FILEVERSION 0,6,44,0
PRODUCTVERSION 0,6,40,0 PRODUCTVERSION 0,6,44,0
FILEOS VOS_NT_WINDOWS32 FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP FILETYPE VFT_APP
BEGIN BEGIN
@@ -20,7 +20,7 @@ BEGIN
BEGIN BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility" VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher" VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.6.40" VALUE "FileVersion", "0.6.44"
END END
END END
BLOCK "VarFileInfo" BLOCK "VarFileInfo"
+101 -17
View File
@@ -78,6 +78,8 @@ class Transaction
mutable bool invalidLogged{}; mutable bool invalidLogged{};
unsigned copyNumber{}; unsigned copyNumber{};
std::wstring adopted; std::wstring adopted;
Bytes adoptedFormats;
bool trustedContentsObserved{};
std::unique_ptr<PasteProbe> selectionProof; std::unique_ptr<PasteProbe> selectionProof;
std::wstring provenSelection; std::wstring provenSelection;
@@ -87,10 +89,26 @@ class Transaction
app.suspended = true; app.suspended = true;
try try
{ {
expected = GetClipboardSequenceNumber(); for (unsigned attempt = 0; ; ++attempt)
snapshot.capture(app.window, expected); {
if (expected != GetClipboardSequenceNumber()) expected = GetClipboardSequenceNumber();
throw std::runtime_error("Clipboard changed while taking snapshot"); try
{
snapshot.capture(app.window, expected);
if (expected != GetClipboardSequenceNumber())
throw std::runtime_error("Clipboard changed while taking snapshot");
break;
}
catch (...)
{
// No selection or clipboard write has happened yet. Recapture
// the latest clipboard after a concurrent publisher settles.
if (attempt >= 2 || !valid() || expected == GetClipboardSequenceNumber())
throw;
diagnosticEvent(L"Snapshot retry: clipboard changed during capture");
Sleep(20);
}
}
captured = true; captured = true;
} }
catch (...) catch (...)
@@ -132,9 +150,19 @@ class Transaction
if (GetClipboardSequenceNumber() != expected) if (GetClipboardSequenceNumber() != expected)
{ {
auto now = GetClipboardSequenceNumber(); auto now = GetClipboardSequenceNumber();
if (adopted.empty() || !ownsClipboard(target) || readClipboard(app.window, 32 * 1024 * 1024, ClipboardRead::Selection).text() != adopted || auto current = readClipboard(app.window, 32 * 1024 * 1024, ClipboardRead::Selection);
GetClipboardSequenceNumber() != now) const bool sameContents = selectionClipboardIdentity(current) == adoptedFormats;
if (adopted.empty() || (!trustedContentsObserved && !ownsClipboard(target)) ||
!sameContents || GetClipboardSequenceNumber() != now)
{
diagnosticEvent(L"Clipboard check rejected: expectedSequence=" + std::to_wstring(expected) +
L" readSequence=" + std::to_wstring(now) + L" currentSequence=" +
std::to_wstring(GetClipboardSequenceNumber()) + L" owner=" +
std::to_wstring((uintptr_t)GetClipboardOwner()) + L" sameContents=" +
std::to_wstring(sameContents) + L" expectedText=" + diagnosticText(adopted) +
L" currentText=" + diagnosticText(current.text()));
throw std::runtime_error("Operation cancelled: another application changed the clipboard"); throw std::runtime_error("Operation cancelled: another application changed the clipboard");
}
expected = now; expected = now;
} }
} }
@@ -142,6 +170,8 @@ class Transaction
{ {
check(); check();
adopted.clear(); adopted.clear();
adoptedFormats.clear();
trustedContentsObserved = false;
// These are temporary transaction contents, not a user's clipboard entry. // These are temporary transaction contents, not a user's clipboard entry.
// In particular, do not invite the Windows history service to read our // In particular, do not invite the Windows history service to read our
// sentinel while the target editor is trying to open the clipboard. // sentinel while the target editor is trying to open the clipboard.
@@ -164,10 +194,12 @@ class Transaction
const auto number = ++copyNumber; const auto number = ++copyNumber;
if (!valid()) if (!valid())
return {}; return {};
write(textClip(L"\x2063KSwitcher-" + std::to_wstring(GetTickCount64()))); const auto sentinel = L"\x2063KSwitcher-" + std::to_wstring(GetTickCount64());
write(textClip(sentinel));
DWORD before = expected; DWORD before = expected;
diagnosticEvent(L"Copy begin number=" + std::to_wstring(number) + L" sentinelSequence=" + diagnosticEvent(L"Copy begin number=" + std::to_wstring(number) + L" sentinelSequence=" +
std::to_wstring(before) + L" target=" + std::to_wstring((uintptr_t)target)); std::to_wstring(before) + L" target=" + std::to_wstring((uintptr_t)target) +
L" sentinel=" + diagnosticText(sentinel));
if (!valid() || !chord(L'C', MOD_CONTROL)) if (!valid() || !chord(L'C', MOD_CONTROL))
{ {
diagnosticEvent(L"Copy failed: context changed or simulated Ctrl+C blocked"); diagnosticEvent(L"Copy failed: context changed or simulated Ctrl+C blocked");
@@ -179,6 +211,7 @@ class Transaction
DWORD changed = before; DWORD changed = before;
ULONGLONG stable = 0; ULONGLONG stable = 0;
bool changedAgain = false; bool changedAgain = false;
std::optional<Bytes> observedTargetCopy;
while (GetTickCount64() < deadline) while (GetTickCount64() < deadline)
{ {
if (!valid()) if (!valid())
@@ -193,6 +226,18 @@ class Transaction
changedAgain |= changed != before; changedAgain |= changed != before;
changed = now; changed = now;
stable = GetTickCount64(); stable = GetTickCount64();
// Clipboard synchronizers can republish a legitimate copy under
// their own HWND. Record provenance before that handoff; an
// unobserved or altered foreign copy must still be rejected.
if (ownsClipboard(target))
{
auto candidate = readClipboard(app.window, 32 * 1024 * 1024, ClipboardRead::Selection);
if (GetClipboardSequenceNumber() == now && ownsClipboard(target) && !candidate.text().empty())
{
observedTargetCopy = selectionClipboardIdentity(candidate);
diagnosticEvent(L"Copy: target-owned selection observed number=" + std::to_wstring(number));
}
}
} }
if (changed != before && GetTickCount64() - stable >= 60) if (changed != before && GetTickCount64() - stable >= 60)
break; break;
@@ -224,16 +269,31 @@ class Transaction
L"Copy failed: context changed"); L"Copy failed: context changed");
return {}; return {};
} }
if ((GetClipboardOwner() ? !ownsClipboard(target) : changedAgain) || const bool targetOwned = ownsClipboard(target);
changed != GetClipboardSequenceNumber())
throw std::runtime_error("Operation cancelled: copy did not belong to the target application");
expected = changed;
auto clip = readClipboard(app.window, 32 * 1024 * 1024, ClipboardRead::Selection); auto clip = readClipboard(app.window, 32 * 1024 * 1024, ClipboardRead::Selection);
const auto formats = selectionClipboardIdentity(clip);
const bool verifiedRelay = observedTargetCopy && *observedTargetCopy == formats;
if (((GetClipboardOwner() ? !targetOwned : changedAgain) && !verifiedRelay) ||
changed != GetClipboardSequenceNumber())
{
diagnosticEvent(L"Copy rejected: observedTarget=" + std::to_wstring(observedTargetCopy.has_value()) +
L" verifiedRelay=" + std::to_wstring(verifiedRelay) + L" expectedSequence=" +
std::to_wstring(changed) + L" currentSequence=" + std::to_wstring(GetClipboardSequenceNumber()) +
L" owner=" + std::to_wstring((uintptr_t)GetClipboardOwner()) + L" targetText=" +
diagnosticText(observedTargetCopy ? decodeClip(*observedTargetCopy).text() : L"") +
L" currentText=" + diagnosticText(clip.text()));
throw std::runtime_error("Operation cancelled: copy did not belong to the target application");
}
if (!targetOwned && verifiedRelay)
diagnosticEvent(L"Copy: identical target selection republished by clipboard synchronizer");
expected = changed;
auto text = clip.text(); auto text = clip.text();
diagnosticEvent(L"Copy result number=" + std::to_wstring(number) + L" attempts=" + diagnosticEvent(L"Copy result number=" + std::to_wstring(number) + L" attempts=" +
std::to_wstring(attempts) + L" elapsedMs=" + std::to_wstring(GetTickCount64() - started) + std::to_wstring(attempts) + L" elapsedMs=" + std::to_wstring(GetTickCount64() - started) +
L" text=" + diagnosticText(text)); L" text=" + diagnosticText(text));
adopted = text; adopted = text;
adoptedFormats = formats;
trustedContentsObserved = targetOwned || verifiedRelay;
check(); check();
for (auto &f : clip.formats) for (auto &f : clip.formats)
{ {
@@ -359,6 +419,14 @@ class Transaction
if (!valid()) if (!valid())
return false; return false;
write(clip); write(clip);
// Our verified payload is also trusted across an identical relay. The
// sentinel written by copy() deliberately does not get this allowance.
if (clip.formats.size() == 1 && clip.formats.front().id == CF_UNICODETEXT)
{
adopted = clip.text();
adoptedFormats = selectionClipboardIdentity(clip);
trustedContentsObserved = true;
}
// Viber's Qt editor observes clipboard changes asynchronously. Give it // Viber's Qt editor observes clipboard changes asynchronously. Give it
// a chance to discard the data object from Ctrl+C before requesting paste. // a chance to discard the data object from Ctrl+C before requesting paste.
// Recheck ownership and input below; never retry a possibly applied paste. // Recheck ownership and input below; never retry a possibly applied paste.
@@ -376,6 +444,10 @@ class Transaction
if (!chord(L'V', MOD_CONTROL)) if (!chord(L'V', MOD_CONTROL))
throw std::runtime_error("Windows blocked simulated input; check application privilege levels"); throw std::runtime_error("Windows blocked simulated input; check application privilege levels");
Sleep(300); Sleep(300);
// A clipboard synchronizer may replace our payload after Ctrl+V is
// queued but before the editor consumes it. Do not run snippet actions
// (especially Enter) after such a race.
check();
return true; return true;
} }
bool nativeSelectionIs(const std::wstring &original) const bool nativeSelectionIs(const std::wstring &original) const
@@ -955,6 +1027,15 @@ void App::replayTyping()
} }
LRESULT CALLBACK App::keyProc(int code, WPARAM wp, LPARAM lp) LRESULT CALLBACK App::keyProc(int code, WPARAM wp, LPARAM lp)
{ {
// MWB suppresses source-machine events that it forwards elsewhere. Let
// downstream hooks route the event before tracking it or starting a snippet.
// Call the chain exactly once; a local event can still be consumed below.
const auto routed = CallNextHookEx(nullptr, code, wp, lp);
return keyboardAfterHooks(code, wp, lp, routed);
}
LRESULT App::keyboardAfterHooks(int code, WPARAM wp, LPARAM lp, LRESULT routed)
{
if (routed) return routed;
if (code == HC_ACTION && current && if (code == HC_ACTION && current &&
(wp == WM_KEYDOWN || wp == WM_SYSKEYDOWN || wp == WM_KEYUP || wp == WM_SYSKEYUP)) (wp == WM_KEYDOWN || wp == WM_SYSKEYDOWN || wp == WM_KEYUP || wp == WM_SYSKEYUP))
{ {
@@ -969,7 +1050,7 @@ LRESULT CALLBACK App::keyProc(int code, WPARAM wp, LPARAM lp)
wp == WM_KEYDOWN || wp == WM_SYSKEYDOWN, mods)) wp == WM_KEYDOWN || wp == WM_SYSKEYDOWN, mods))
return 1; return 1;
} }
return CallNextHookEx(nullptr, code, wp, lp); return routed;
} }
LRESULT CALLBACK App::mouseProc(int code, WPARAM wp, LPARAM lp) LRESULT CALLBACK App::mouseProc(int code, WPARAM wp, LPARAM lp)
{ {
@@ -1398,11 +1479,11 @@ void App::transform(int command, int snippet)
} }
} }
bool sent = false; bool sent = false;
const bool requireReadback = tx.recoveredSelection(); const bool requireReadback = tx.recoveredSelection() || snippet >= 0;
PasteProbe probe(((config.writeLog && manual) || requireReadback) && result != text, text, target); PasteProbe probe(((config.writeLog && manual) || requireReadback) && result != text, text, target);
if (requireReadback && result != text && probe.status != L"ready") if (requireReadback && result != text && probe.status != L"ready")
{ {
reason = L"recovered-selection-unavailable"; reason = snippet >= 0 ? L"snippet-verification-unavailable" : L"recovered-selection-unavailable";
std::lock_guard lock(stateMutex); std::lock_guard lock(stateMutex);
last.reset(); last.reset();
run.reset(); run.reset();
@@ -1416,7 +1497,7 @@ void App::transform(int command, int snippet)
chord(VK_RIGHT); chord(VK_RIGHT);
if (requireReadback && result != text && !sent) if (requireReadback && result != text && !sent)
{ {
reason = L"recovered-selection-paste-cancelled"; reason = snippet >= 0 ? L"snippet-paste-cancelled" : L"recovered-selection-paste-cancelled";
std::lock_guard lock(stateMutex); std::lock_guard lock(stateMutex);
last.reset(); last.reset();
run.reset(); run.reset();
@@ -1900,7 +1981,9 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
app->replayTyping(); app->replayTyping();
return 0; return 0;
case TrayMessage: case TrayMessage:
if (LOWORD(lp) == WM_CONTEXTMENU) if (LOWORD(lp) == NIN_BALLOONUSERCLICK)
showLogs(*app);
else if (LOWORD(lp) == WM_CONTEXTMENU)
app->trayMenu(); app->trayMenu();
else if (LOWORD(lp) == WM_LBUTTONDBLCLK) else if (LOWORD(lp) == WM_LBUTTONDBLCLK)
// The shell still owns the mouse gesture on the second button-down. // The shell still owns the mouse gesture on the second button-down.
@@ -2078,6 +2161,7 @@ int App::execute()
historySelection = wide(state.value("selection", std::string{})); historySelection = wide(state.value("selection", std::string{}));
historyTop = wide(state.value("top", std::string{})); historyTop = wide(state.value("top", std::string{}));
historyQuery = wide(state.value("query", std::string{})); historyQuery = wide(state.value("query", std::string{}));
historyPinnedOnly = state.value("pinnedOnly", false);
} catch (...) {} } catch (...) {}
showHistory(*this); showHistory(*this);
remoteHistory("ready", std::to_wstring(reinterpret_cast<uintptr_t>(historyWindow))); remoteHistory("ready", std::to_wstring(reinterpret_cast<uintptr_t>(historyWindow)));
+3 -1
View File
@@ -37,6 +37,7 @@ class App
bool isolateHistory{}; bool isolateHistory{};
unsigned historyEntryWindows{}; unsigned historyEntryWindows{};
std::wstring historySelection, historyTop, historyQuery; std::wstring historySelection, historyTop, historyQuery;
bool historyPinnedOnly{};
HINSTANCE instance{}; HINSTANCE instance{};
std::filesystem::path data; std::filesystem::path data;
std::vector<Layout> layouts; std::vector<Layout> layouts;
@@ -80,7 +81,7 @@ class App
void refreshHistoryProcess(); void refreshHistoryProcess();
void remoteHistory(const char *action, const std::wstring &id = {}, bool plain = false); void remoteHistory(const char *action, const std::wstring &id = {}, bool plain = false);
LRESULT historyRequest(HWND, const COPYDATASTRUCT &); LRESULT historyRequest(HWND, const COPYDATASTRUCT &);
void saveHistoryView(const std::wstring &, const std::wstring &, const std::wstring &); void saveHistoryView(const std::wstring &, const std::wstring &, const std::wstring &, bool);
void clearLog(bool previous); void clearLog(bool previous);
void setHotkeyCapture(HWND); void setHotkeyCapture(HWND);
bool isHotkey(DWORD, UINT); bool isHotkey(DWORD, UINT);
@@ -142,6 +143,7 @@ class App
void replayTyping(); void replayTyping();
static LRESULT CALLBACK windowProc(HWND, UINT, WPARAM, LPARAM); static LRESULT CALLBACK windowProc(HWND, UINT, WPARAM, LPARAM);
static LRESULT CALLBACK keyProc(int, WPARAM, LPARAM); static LRESULT CALLBACK keyProc(int, WPARAM, LPARAM);
static LRESULT keyboardAfterHooks(int, WPARAM, LPARAM, LRESULT);
static LRESULT CALLBACK mouseProc(int, WPARAM, LPARAM); static LRESULT CALLBACK mouseProc(int, WPARAM, LPARAM);
}; };
void showHistory(App &, bool visible = true); void showHistory(App &, bool visible = true);
+2 -2
View File
@@ -90,11 +90,11 @@ LRESULT App::historyRequest(HWND sender, const COPYDATASTRUCT &message)
return TRUE; return TRUE;
} catch (...) { return FALSE; } } catch (...) { return FALSE; }
} }
void App::saveHistoryView(const std::wstring &selection, const std::wstring &top, const std::wstring &query) void App::saveHistoryView(const std::wstring &selection, const std::wstring &top, const std::wstring &query, bool pinnedOnly)
{ {
if (!historyService) return; if (!historyService) return;
try { try {
auto text = HistoryJson{{"selection", utf8(selection)}, {"top", utf8(top)}, {"query", utf8(query)}}.dump(); auto text = HistoryJson{{"selection", utf8(selection)}, {"top", utf8(top)}, {"query", utf8(query)}, {"pinnedOnly", pinnedOnly}}.dump();
atomicWrite(data / L"history-view.bin", protect(Bytes(text.begin(), text.end()))); atomicWrite(data / L"history-view.bin", protect(Bytes(text.begin(), text.end())));
} catch (...) {} // Closing the UI must still release its process if state cannot be saved. } catch (...) {} // Closing the UI must still release its process if state cannot be saved.
} }
+16 -1
View File
@@ -344,6 +344,20 @@ Bytes encodeClip(const Clip &clip)
} }
return b; return b;
} }
Bytes selectionClipboardIdentity(const Clip &clip)
{
auto normalized = clip;
// GlobalSize includes allocation slack. A clipboard relay may allocate a
// different-sized block for the same NUL-terminated Unicode string.
for (auto &format : normalized.formats)
if (format.id == CF_UNICODETEXT)
format = textClip(clip.text()).formats.front();
std::sort(normalized.formats.begin(), normalized.formats.end(), [](const Format &a, const Format &b)
{
return std::tie(a.name, a.id) < std::tie(b.name, b.id);
});
return encodeClip(normalized);
}
Clip decodeClip(const Bytes &b) Clip decodeClip(const Bytes &b)
{ {
size_t p = 0; size_t p = 0;
@@ -924,9 +938,10 @@ std::optional<std::wstring> History::ocrText(const std::wstring &id, const std::
if (bytes.empty() || bytes.front() != 1) throw std::runtime_error("Invalid OCR text format"); if (bytes.empty() || bytes.front() != 1) throw std::runtime_error("Invalid OCR text format");
return wide(std::string(bytes.begin() + 1, bytes.end())); return wide(std::string(bytes.begin() + 1, bytes.end()));
} }
std::vector<Entry> History::search(const std::wstring &query) const std::vector<Entry> History::search(const std::wstring &query, bool pinnedOnly) const
{ {
auto items = entries(); auto items = entries();
if (pinnedOnly) std::erase_if(items, [](const Entry &entry) { return !entry.pinned; });
if (query.empty()) if (query.empty())
return items; return items;
auto q = lower(query); auto q = lower(query);
+2 -1
View File
@@ -43,9 +43,10 @@ class History
void remove(const std::wstring &); void remove(const std::wstring &);
void pin(const std::wstring &); void pin(const std::wstring &);
void clear(); void clear();
std::vector<Entry> search(const std::wstring &) const; std::vector<Entry> search(const std::wstring &, bool pinnedOnly = false) const;
}; };
Bytes encodeClip(const Clip &); Bytes encodeClip(const Clip &);
Bytes selectionClipboardIdentity(const Clip &);
Clip decodeClip(const Bytes &); Clip decodeClip(const Bytes &);
bool sameClipboardImage(const Clip &, const Clip &); bool sameClipboardImage(const Clip &, const Clip &);
int runImageHistoryCapture(const std::filesystem::path &request); int runImageHistoryCapture(const std::filesystem::path &request);
+29 -5
View File
@@ -493,6 +493,7 @@ struct HistoryView
std::set<std::wstring> pending; std::set<std::wstring> pending;
bool scrolling{}; bool scrolling{};
bool closed{}; bool closed{};
bool selectFirstOnResults{};
}; };
bool selectedImage(HWND w, HistoryView *v) bool selectedImage(HWND w, HistoryView *v)
{ {
@@ -514,15 +515,16 @@ void search(HWND w, HistoryView *v)
v->previewActive = std::make_shared<std::atomic<bool>>(true); v->previewActive = std::make_shared<std::atomic<bool>>(true);
v->closed = false; v->closed = false;
auto q = value(w, 101); auto q = value(w, 101);
const bool pinnedOnly = SendDlgItemMessageW(w, 117, BM_GETCHECK, 0, 0) == BST_CHECKED;
auto generation = ++v->generation; auto generation = ++v->generation;
v->pending.clear(); v->pending.clear();
auto *app = v->app; auto *app = v->app;
app->enqueueHistorySearch( app->enqueueHistorySearch(
[w, app, q, generation] [w, app, q, generation, pinnedOnly]
{ {
try try
{ {
auto result = new SearchResult{generation, app->history->search(q)}; auto result = new SearchResult{generation, app->history->search(q, pinnedOnly)};
if (!PostMessageW(w, ResultsMessage, 0, (LPARAM)result)) if (!PostMessageW(w, ResultsMessage, 0, (LPARAM)result))
delete result; delete result;
} }
@@ -739,6 +741,12 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
case WM_COMMAND: case WM_COMMAND:
{ {
int id = LOWORD(wp); int id = LOWORD(wp);
if (id == 117 && HIWORD(wp) == BN_CLICKED)
{
KillTimer(w, 1);
search(w, v);
return 0;
}
if (id == 101 && HIWORD(wp) == EN_CHANGE) if (id == 101 && HIWORD(wp) == EN_CHANGE)
{ {
// Reject an older result even during the debounce interval. // Reject an older result even during the debounce interval.
@@ -809,6 +817,14 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
int top=(int)SendDlgItemMessageW(w,102,LB_GETTOPINDEX,0,0); int top=(int)SendDlgItemMessageW(w,102,LB_GETTOPINDEX,0,0);
auto topId=top>=0 && top<(int)v->items.size()?v->items[top].id:L""; auto topId=top>=0 && top<(int)v->items.size()?v->items[top].id:L"";
if (topId.empty()) topId = v->rememberedTop; if (topId.empty()) topId = v->rememberedTop;
if (v->selectFirstOnResults)
{
old.clear();
topId.clear();
v->rememberedSelection.clear();
v->rememberedTop.clear();
v->selectFirstOnResults = false;
}
v->items = std::move(result->items); v->items = std::move(result->items);
SendDlgItemMessageW(w, 102, WM_SETREDRAW, FALSE, 0); SendDlgItemMessageW(w, 102, WM_SETREDRAW, FALSE, 0);
SendDlgItemMessageW(w, 102, LB_RESETCONTENT, 0, 0); SendDlgItemMessageW(w, 102, LB_RESETCONTENT, 0, 0);
@@ -910,7 +926,8 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
v->rememberedSelection = selected(w, v); v->rememberedSelection = selected(w, v);
int top = (int)SendDlgItemMessageW(w,102,LB_GETTOPINDEX,0,0); int top = (int)SendDlgItemMessageW(w,102,LB_GETTOPINDEX,0,0);
v->rememberedTop = top >= 0 && top < (int)v->items.size() ? v->items[top].id : L""; v->rememberedTop = top >= 0 && top < (int)v->items.size() ? v->items[top].id : L"";
v->app->saveHistoryView(v->rememberedSelection, v->rememberedTop, value(w, 101)); v->app->saveHistoryView(v->rememberedSelection, v->rememberedTop, value(w, 101),
SendDlgItemMessageW(w, 117, BM_GETCHECK, 0, 0) == BST_CHECKED);
KillTimer(w, 1); KillTimer(w, 1);
v->closed = true; v->closed = true;
v->previewActive->store(false); v->previewActive->store(false);
@@ -1737,8 +1754,11 @@ void showHistory(App &app, bool visible)
HWND w = makeWindow(app, L"KSwitcher.History", L"Clipboard history", historyProc, 760, 500); HWND w = makeWindow(app, L"KSwitcher.History", L"Clipboard history", historyProc, 760, 500);
app.historyWindow = w; app.historyWindow = w;
windowLayoutState(w)->history = true; windowLayoutState(w)->history = true;
label(w, L"&Search clipboard history", 16, 12, 500); auto filter = control(w, L"BUTTON", L"★ Pinned only", WS_TABSTOP | BS_AUTOCHECKBOX,
edit(w, 101, 16, 38, 728); 117, 16, 38, 112, 25);
SendMessageW(filter, BM_SETCHECK, app.historyPinnedOnly ? BST_CHECKED : BST_UNCHECKED, 0);
label(w, L"&Search clipboard history", 136, 12, 500);
edit(w, 101, 136, 38, 608);
auto list = control(w, L"LISTBOX", L"", auto list = control(w, L"LISTBOX", L"",
WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER | WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER |
LBS_OWNERDRAWFIXED | LBS_HASSTRINGS, LBS_OWNERDRAWFIXED | LBS_HASSTRINGS,
@@ -1760,6 +1780,10 @@ void showHistory(App &app, bool visible)
} }
} }
if (!visible) return; if (!visible) return;
// A fresh invocation starts at the newest matching item. Background search
// and OCR refreshes still preserve the user's selection while browsing.
auto *view = (HistoryView *)GetWindowLongPtrW(app.historyWindow, GWLP_USERDATA);
view->selectFirstOnResults = true;
POINT cursor; POINT cursor;
GetCursorPos(&cursor); GetCursorPos(&cursor);
MONITORINFO monitor{sizeof(monitor)}; MONITORINFO monitor{sizeof(monitor)};
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h" #include "platform.h"
namespace ks namespace ks
{ {
inline constexpr wchar_t AppVersion[] = L"0.6.40"; inline constexpr wchar_t AppVersion[] = L"0.6.44";
inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+16 -1
View File
@@ -112,9 +112,24 @@ int main() {
auto w=open();send(w,WM_COMMAND,112); auto w=open();send(w,WM_COMMAND,112);
until([&]{history.reload();return history.entries().front().pinned;},"resident pin mutation"); until([&]{history.reload();return history.entries().front().pinned;},"resident pin mutation");
require(history.entries().front().id==textId,"pin preserves history identity"); require(history.entries().front().id==textId,"pin preserves history identity");
auto filter=[&](HWND window,int index) {
auto checkbox=GetDlgItem(window,117);
if(send(checkbox,BM_GETCHECK)!=(index ? BST_CHECKED : BST_UNCHECKED)) send(checkbox,BM_CLICK);
};
filter(w,1);
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==1;},"pinned filter hides unpinned entries");
send(GetDlgItem(w,101),WM_SETTEXT,0,LPARAM(L"History fixture 497"));
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==0;},"search cannot match an unpinned item in pinned view");
send(GetDlgItem(w,101),WM_SETTEXT,0,LPARAM(L"History fixture 498")); send(GetDlgItem(w,101),WM_SETTEXT,0,LPARAM(L"History fixture 498"));
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==1;},"history search"); until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==1;},"history search");
send(w,WM_COMMAND,112);
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==0;},"unpin removes the last pinned result");
filter(w,0);
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==1;},"all items restores the matching unpinned entry");
send(w,WM_COMMAND,112);
filter(w,1);
close(w);w=open(); close(w);w=open();
require(send(GetDlgItem(w,117),BM_GETCHECK)==BST_CHECKED,"pinned checkbox survives helper restart");
wchar_t query[100]{};send(GetDlgItem(w,101),WM_GETTEXT,100,LPARAM(query)); wchar_t query[100]{};send(GetDlgItem(w,101),WM_GETTEXT,100,LPARAM(query));
require(std::wstring(query)==L"History fixture 498","search survives helper restart"); require(std::wstring(query)==L"History fixture 498","search survives helper restart");
send(w,WM_COMMAND,114); send(w,WM_COMMAND,114);
@@ -124,7 +139,7 @@ int main() {
require(WaitForSingleObject(child,0)==WAIT_TIMEOUT && IsWindow(entry),"full item remains usable after closing history"); require(WaitForSingleObject(child,0)==WAIT_TIMEOUT && IsWindow(entry),"full item remains usable after closing history");
send(entry,WM_CLOSE); send(entry,WM_CLOSE);
until([&]{return WaitForSingleObject(child,0)==WAIT_OBJECT_0;},"helper exits after last full item closes");CloseHandle(child); until([&]{return WaitForSingleObject(child,0)==WAIT_OBJECT_0;},"helper exits after last full item closes");CloseHandle(child);
w=open();send(GetDlgItem(w,101),WM_SETTEXT,0,LPARAM(L"")); w=open();filter(w,0);send(GetDlgItem(w,101),WM_SETTEXT,0,LPARAM(L""));
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==500;},"clear search");close(w); until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==500;},"clear search");close(w);
ks::writeClipboard(target,excluded(image)); ks::writeClipboard(target,excluded(image));
w=open();send(w,WM_COMMAND,111); w=open();send(w,WM_COMMAND,111);
+36
View File
@@ -2,6 +2,7 @@
#include "ui_scroll.h" #include "ui_scroll.h"
#include "ui_geometry.h" #include "ui_geometry.h"
#include "screenshot.h" #include "screenshot.h"
#include "ocr.h"
#include <commctrl.h> #include <commctrl.h>
#include <iostream> #include <iostream>
#include <cmath> #include <cmath>
@@ -94,6 +95,9 @@ struct InputRegressionAccess {
} }
static void notificationSetup(App &a) { a.updateNotifier = notify; } static void notificationSetup(App &a) { a.updateNotifier = notify; }
static void setup(App &a) { a.hookBindings = {{Toggle,{MOD_CONTROL,VK_F12}}, {Case,{MOD_CONTROL|MOD_SHIFT,'U'}}}; } static void setup(App &a) { a.hookBindings = {{Toggle,{MOD_CONTROL,VK_F12}}, {Case,{MOD_CONTROL|MOD_SHIFT,'U'}}}; }
static LRESULT routedKey(int code, UINT message, const KBDLLHOOKSTRUCT &key, LRESULT routed) {
return App::keyboardAfterHooks(code,message,(LPARAM)&key,routed);
}
static bool updateTimer(App &a) { static bool updateTimer(App &a) {
a.updateRunning=true; // Exercise timer scheduling without launching a network request. a.updateRunning=true; // Exercise timer scheduling without launching a network request.
App::windowProc(a.window,WM_TIMER,5,0); App::windowProc(a.window,WM_TIMER,5,0);
@@ -648,6 +652,22 @@ int main(int argc, char **argv) {
}; };
auto commands=[&] { MSG m{}; int n=0; while(PeekMessageW(&m,app.window,WM_HOTKEY,WM_HOTKEY,PM_REMOVE)) ++n; return n; }; auto commands=[&] { MSG m{}; int n=0; while(PeekMessageW(&m,app.window,WM_HOTKEY,WM_HOTKEY,PM_REMOVE)) ++n; return n; };
auto f12=event(VK_F12); auto f12=event(VK_F12);
{
const auto before = app.inputVersion.load();
const auto recorded = app.run.keys;
for (UINT message : {WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, WM_SYSKEYUP})
require(ks::InputRegressionAccess::routedKey(HC_ACTION,message,event('A',30),7)==7,
"forwarded keyboard events preserve downstream suppression");
require(app.inputVersion==before && app.run.keys==recorded && commands()==0,
"forwarded events never track text, invalidate transactions or dispatch shortcuts");
require(ks::InputRegressionAccess::routedKey(-1,WM_KEYDOWN,event('A',30),0)==0 &&
app.inputVersion==before,"negative hook codes do not process keyboard input");
require(ks::InputRegressionAccess::routedKey(HC_ACTION,WM_KEYDOWN,event('A',30,true),0)==0 &&
app.inputVersion==before,"own input remains excluded after downstream routing");
require(ks::InputRegressionAccess::routedKey(HC_ACTION,WM_KEYDOWN,event('A',30),0)==0 &&
app.inputVersion>before,"delivered remote input is still processed on the receiver");
app.run.reset();
}
require(!app.handleKeyboard(event(VK_LCONTROL),true,0),"remote modifier passes through"); require(!app.handleKeyboard(event(VK_LCONTROL),true,0),"remote modifier passes through");
require(app.handleKeyboard(f12,true,MOD_CONTROL),"remote Ctrl+F12 handled"); require(app.handleKeyboard(f12,true,MOD_CONTROL),"remote Ctrl+F12 handled");
require(app.handleKeyboard(f12,true,MOD_CONTROL),"remote repeat suppressed"); require(app.handleKeyboard(f12,true,MOD_CONTROL),"remote repeat suppressed");
@@ -961,6 +981,22 @@ int main(int argc, char **argv) {
require(pumpUntil(2),"history reloads after releasing hidden rows"); require(pumpUntil(2),"history reloads after releasing hidden rows");
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==1, require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==1,
"history retains selected record across close and reload"); "history retains selected record across close and reload");
SendMessageW(history,WM_CLOSE,0,0);
ks::Pixels screenshot{2,2,ks::Bytes(16,255)};
app.history->add(ks::Clip{{ks::imageDib(screenshot)}},L"screenshot",app.settings);
require(app.history->entries().front().image,"new screenshot is the newest history entry");
ks::showHistory(app);
require(pumpUntil(3),"reopening history loads the new screenshot");
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==0 &&
SendDlgItemMessageW(history,102,LB_GETTOPINDEX,0,0)==0,
"fresh history invocation selects and reveals newest screenshot instead of saved selection");
SendDlgItemMessageW(history,102,LB_SETCURSEL,2,0);
app.history->add(ks::textClip(L"background clipboard update"),L"test",app.settings);
ks::refreshHistory(app);
require(pumpUntil(4),"background refresh loads a new item");
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==3,
"background refresh preserves the selected record while browsing");
ShowWindow(history,SW_HIDE);
} }
auto childRect=[&](int id) { RECT r{}; GetWindowRect(GetDlgItem(history,id),&r); MapWindowPoints(nullptr,history,(POINT*)&r,2); return r; }; auto childRect=[&](int id) { RECT r{}; GetWindowRect(GetDlgItem(history,id),&r); MapWindowPoints(nullptr,history,(POINT*)&r,2); return r; };
RECT historyFrame{}; GetWindowRect(history,&historyFrame); RECT historyFrame{}; GetWindowRect(history,&historyFrame);
+58 -1
View File
@@ -33,6 +33,17 @@ bool trimCopiedSpaces = false;
int trimmedCopies = 0; int trimmedCopies = 0;
bool temporaryClipboardExcluded = true; bool temporaryClipboardExcluded = true;
bool clipboardAccessTimedOut = false; bool clipboardAccessTimedOut = false;
uint64_t forwardedVersion{};
int forwardedEvents{};
LRESULT CALLBACK forwardingHook(int code, WPARAM wp, LPARAM lp)
{
if (code == HC_ACTION && reinterpret_cast<KBDLLHOOKSTRUCT *>(lp)->dwExtraInfo == 456)
{
++forwardedEvents;
return 1; // Model MWB consuming source input routed to another machine.
}
return CallNextHookEx(nullptr, code, wp, lp);
}
LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR) LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{ {
if (message == WM_KEYDOWN && wp == VK_LEFT && droppedSelectionKeys > 0 && if (message == WM_KEYDOWN && wp == VK_LEFT && droppedSelectionKeys > 0 &&
@@ -577,10 +588,41 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
require(ks::readClipboard(app->window).text() == sentinel, "selected and repeated conversions restore clipboard"); require(ks::readClipboard(app->window).text() == sentinel, "selected and repeated conversions restore clipboard");
finish(); finish();
break; break;
case 62:
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
app->settings.snippets = {{L";r", L"unexpected{enter}"}};
ActivateKeyboardLayout(app->layouts[en].handle, 0);
prepare(L"prefix ", false);
forwardedVersion = app->inputVersion.load();
copyRequests = forwardedEvents = 0;
{
std::vector<INPUT> inputs;
for (WORD key : {WORD(VK_OEM_1), WORD('R')})
for (DWORD flags : {DWORD(0), DWORD(KEYEVENTF_KEYUP)})
{
auto input = ks::keyboardInput(key, flags);
input.ki.dwExtraInfo = 456;
inputs.push_back(input);
}
require(SendInput((UINT)inputs.size(),inputs.data(),sizeof(INPUT))==inputs.size(),
"forwarded snippet input submitted to real hook chain");
}
break;
case 63:
require(forwardedEvents==4,"downstream forwarding hook consumed every key event");
require(app->inputVersion==forwardedVersion && copyRequests==0,
"forwarded snippet does not start tracking or clipboard work on source computer");
require(text()==L"prefix " && ks::readClipboard(app->window).text()==sentinel,
"forwarded snippet leaves source editor and clipboard untouched");
stage = 30;
break;
case 30: case 30:
case 32: case 32:
case 34: case 34:
case 37: case 37:
case 60:
// Earlier password/word tests replace the original multiline // Earlier password/word tests replace the original multiline
// editor with a single-line EDIT. Restore the snippet fixture: // editor with a single-line EDIT. Restore the snippet fixture:
// a single-line control cannot insert the tested Enter action. // a single-line control cannot insert the tested Enter action.
@@ -609,6 +651,11 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
enterPresses = 0; enterPresses = 0;
copyRequests = 0; copyRequests = 0;
copyFailuresRemaining = stage == 38 ? 10 : stage == 33 ? 1 : 0; copyFailuresRemaining = stage == 38 ? 10 : stage == 33 ? 1 : 0;
if (stage == 61)
{
pasteBehavior = 2; // Editor inserts unrelated clipboard text.
app->settings.writeLog = false;
}
temporaryClipboardExcluded = true; temporaryClipboardExcluded = true;
ActivateKeyboardLayout(app->layouts[en].handle, 0); ActivateKeyboardLayout(app->layouts[en].handle, 0);
prepare(L"prefix ", false); prepare(L"prefix ", false);
@@ -672,6 +719,13 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
require(ks::readClipboard(app->window).text() == sentinel, require(ks::readClipboard(app->window).text() == sentinel,
"exhausted copy retries restore the clipboard"); "exhausted copy retries restore the clipboard");
copyFailuresRemaining = 0; copyFailuresRemaining = 0;
stage = 60;
break;
case 61:
require(text() == L"prefix other! x", "incorrect snippet paste preserves following typing");
require(enterPresses == 0, "unverified snippet never submits Enter even without logging");
require(ks::readClipboard(app->window).text() == sentinel, "rejected snippet restores clipboard");
pasteBehavior = 0;
finish(); finish();
break; break;
case 20: case 20:
@@ -985,9 +1039,12 @@ int main(int argc, char **argv)
if (typosOnly || (argc > 1 && std::string(argv[1]) == "--typing-only")) if (typosOnly || (argc > 1 && std::string(argv[1]) == "--typing-only"))
stage = 20; stage = 20;
if (argc > 1 && std::string(argv[1]) == "--snippets-only") if (argc > 1 && std::string(argv[1]) == "--snippets-only")
stage = 30; stage = 62;
SetTimer(host, 1, 100, nullptr); SetTimer(host, 1, 100, nullptr);
auto forwarding = SetWindowsHookExW(WH_KEYBOARD_LL,forwardingHook,GetModuleHandleW(nullptr),0);
require(forwarding!=nullptr,"downstream forwarding fixture installed before application hook");
app->execute(); app->execute();
UnhookWindowsHookEx(forwarding);
} }
std::filesystem::remove_all(root); std::filesystem::remove_all(root);
} }
+18
View File
@@ -517,6 +517,24 @@ int main(int argc, char **argv)
auto encoded = ks::encodeClip(clip); auto encoded = ks::encodeClip(clip);
require(ks::decodeClip(encoded).text() == clip.text(), "clipboard Unicode roundtrip"); require(ks::decodeClip(encoded).text() == clip.text(), "clipboard Unicode roundtrip");
require(ks::decodeClip(encoded).formats[1].name == L"HTML Format", "registered format identity"); require(ks::decodeClip(encoded).formats[1].name == L"HTML Format", "registered format identity");
auto selection = ks::textClip(L";pa");
selection.formats.push_back({0, L"vscode-editor-data", {1, 2, 3}});
auto relayed = selection;
relayed.formats.front().data.resize(128, 0xab);
std::reverse(relayed.formats.begin(), relayed.formats.end());
require(ks::selectionClipboardIdentity(selection) == ks::selectionClipboardIdentity(relayed),
"clipboard relay tolerates Unicode allocation slack and format order");
relayed.formats.front().data[0] ^= 1;
require(ks::selectionClipboardIdentity(selection) != ks::selectionClipboardIdentity(relayed),
"clipboard relay rejects changed editor metadata");
relayed = selection;
relayed.formats.pop_back();
require(ks::selectionClipboardIdentity(selection) != ks::selectionClipboardIdentity(relayed),
"clipboard relay rejects missing editor metadata");
relayed = selection;
relayed.formats.front() = ks::textClip(L";pb").formats.front();
require(ks::selectionClipboardIdentity(selection) != ks::selectionClipboardIdentity(relayed),
"clipboard relay rejects changed Unicode text");
auto encrypted = ks::protect(encoded); auto encrypted = ks::protect(encoded);
require(encrypted != encoded, "history ciphertext differs"); require(encrypted != encoded, "history ciphertext differs");
require(ks::unprotect(encrypted) == encoded, "Windows DPAPI roundtrip"); require(ks::unprotect(encrypted) == encoded, "Windows DPAPI roundtrip");