diff --git a/CMakeLists.txt b/CMakeLists.txt index 8320bb9..601b23e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -84,7 +84,7 @@ if(MSVC) else() target_link_options(KSwitcherFarSnippetTests PRIVATE -municode -static -static-libgcc -static-libstdc++) endif() -add_executable(KSwitcherInputTests tests/input.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc) +add_executable(KSwitcherInputTests tests/input.cpp tests/input_pause.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc) target_link_libraries(KSwitcherInputTests PRIVATE kscore) target_compile_definitions(KSwitcherInputTests PRIVATE KS_SCREENSHOT_RESOURCES) add_executable(KSwitcherScreenshotUITests tests/screenshot_ui.cpp resources/app.rc) @@ -268,6 +268,7 @@ add_test(NAME utilities-regressions COMMAND KSwitcherUtilitiesTests) add_test(NAME stayhere-lifecycle COMMAND powershell -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/stayhere.ps1" -Executable "$") add_test(NAME scroll-regressions COMMAND KSwitcherScrollTests) add_test(NAME input-regressions COMMAND KSwitcherInputTests) +add_test(NAME tray-input-pause COMMAND KSwitcherInputTests --input-pause) add_test(NAME screenshot-ui-regressions COMMAND KSwitcherScreenshotUITests) add_test(NAME screenshot-save-regressions COMMAND KSwitcherScreenshotUITests --save-only) add_test(NAME updater-regressions COMMAND powershell.exe -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/update.ps1" -Executable "$") diff --git a/README.md b/README.md index 41fe320..85c416b 100644 --- a/README.md +++ b/README.md @@ -185,10 +185,10 @@ Exit [Typlo](https://github.com/bitcodepro/Typlo) when using overlapping shortcu This also works for each layout's **Direct layout shortcut**. Backspace or Delete without modifiers clears a shortcut. Tab moves to the next field. The recorded shortcut is suppressed while the field has focus, so recording the conversion shortcut does not perform a conversion. -All configured shortcuts use the existing keyboard hook and can replace ordinary Windows/app +The Files shortcut is registered with Windows. The other configured shortcuts use the keyboard hook and can replace ordinary Windows/app shortcuts, including **Win+V** and **Win+Shift+S**, while KSwitcher is running. Only exact configured combinations are intercepted. Unassigned shortcuts and simulated copy/paste pass through. -Choose another shortcut or exit KSwitcher to restore the original action. Windows protects +Pause input processing, choose another shortcut or exit KSwitcher to restore the original action. Windows protects Ctrl+Alt+Delete and Win+L; these cannot be assigned. Keyboard and mouse input forwarded by Microsoft Mouse Without Borders follows the same input @@ -201,6 +201,28 @@ keys cannot trigger recursive commands or overwrite the recorded typing run. Oth is accepted, including key-up events and VK-only keyboard events. Unicode packets do not provide physical key positions and therefore reset recent-word tracking; selection conversion still works. +### Pause input processing + +Right-click the KSwitcher tray icon and choose **Pause input processing** before testing another keyboard tool. +The icon shows a gray dot and the tooltip says **Input processing paused**. KSwitcher releases its shortcuts and +stops keyboard and mouse actions, autocorrection, snippets, automatic layout switching, LAN mouse and keyboard +control, and simulated F15 activity. Clipboard history has its own pause control. You can browse entries +during an input pause and paste them after resuming. If you launched the standalone **StayHere** utility, +its own tray icon controls its F15 activity. + +Choose **Resume input processing** in the same menu after testing. The tooltip then shows **Input processing active**. If another program still holds a shortcut, +KSwitcher identifies the combination and stays paused. Release it in the other program and retry. +The pause lasts for the current run. + +**Українською.** Перед тестуванням іншої програми клацни правою кнопкою значок KSwitcher у треї й вибери +**Pause input processing**. Сіра крапка та підказка **Input processing paused** позначають паузу. KSwitcher +звільняє гарячі клавіші й призупиняє дії клавіатури та миші, автокорекцію, сніпети, автоматичне перемикання +розкладки, LAN-керування й імітацію F15. Історія буфера обміну має окремий перемикач. Записи можна переглядати +під час паузи та вставляти після відновлення. Якщо окремо запущена утиліта **StayHere**, її імітація F15 +керується з її власного значка в треї. +Для відновлення вибери **Resume input processing**. Підказка покаже **Input processing active**. Якщо комбінація зайнята, звільни вказаний хоткей +в іншій програмі та повтори спробу. Пауза діє до завершення поточного запуску. + ### Screen capture and annotations Press **Win+Shift+S**, choose **Capture screen region…** in the tray menu, or run diff --git a/build.ps1 b/build.ps1 index ba3f235..409d687 100644 --- a/build.ps1 +++ b/build.ps1 @@ -107,10 +107,12 @@ try { if ($LASTEXITCODE) { throw 'Test build failed' } & .\build\KSwitcherTests.exe if ($LASTEXITCODE) { throw 'Tests failed' } - & $compiler @common tests/input.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe + & $compiler @common tests/input.cpp tests/input_pause.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe if ($LASTEXITCODE) { throw 'Input test build failed' } & .\build\KSwitcherInputTests.exe if ($LASTEXITCODE) { throw 'Input tests failed' } + & .\build\KSwitcherInputTests.exe --input-pause + if ($LASTEXITCODE) { throw 'Tray pause/resume test failed' } & $compiler @common tests/chat_profiles.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherChatProfileTests.exe if ($LASTEXITCODE) { throw 'Chat profile test build failed' } & .\build\KSwitcherChatProfileTests.exe diff --git a/src/app.cpp b/src/app.cpp index 55a5a60..e1667b7 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -143,6 +143,16 @@ ULONG_PTR snippetReplayMarker() return reinterpret_cast(&marker); } constexpr int OpenFiles = 25, FilesHotkeyFirst = 0x4B10, FilesHotkeySecond = 0x4B11; +constexpr int ToggleInputProcessing = 26; +constexpr int ShortcutProbeId = FilesHotkeySecond + 1; +constexpr UINT_PTR PauseDrainTimer = 23; + +bool shortcutAvailable(HWND window, Hotkey key) +{ + if (!RegisterHotKey(window, ShortcutProbeId, key.modifiers | MOD_NOREPEAT, key.key)) return false; + UnregisterHotKey(window, ShortcutProbeId); + return true; +} bool activateFilesWindow() { @@ -796,7 +806,7 @@ App::App(HINSTANCE h, bool test, const std::filesystem::path &dataRoot, HWND ser } App::~App() { - if (filesHotkeyId) UnregisterHotKey(window, filesHotkeyId); + releaseInputHooks(); if (snippetPopup) DestroyWindow(snippetPopup); lanService.reset(); stopBrowserChatMonitor(); @@ -806,10 +816,6 @@ App::~App() if (syncWorker.joinable()) syncWorker.join(); if (updateWorker.joinable()) updateWorker.join(); - if (keyboardHook) - UnhookWindowsHookEx(keyboardHook); - if (mouseHook) - UnhookWindowsHookEx(mouseHook); { std::lock_guard lock(jobsMutex); stop = true; @@ -992,14 +998,21 @@ bool App::updateTray(DWORD action, bool notifyFile) icon.hIcon = (HICON)LoadImageW(instance, MAKEINTRESOURCEW(IDI_KSWITCHER), IMAGE_ICON, width, height, LR_SHARED); HICON badge{}; auto tip = localBuildTitle(L"KSwitcher"); - if (trayInput.paired) + if (inputState == InputState::Active) tip += L" — Input processing active"; + if (inputState != InputState::Active) + { + tip += inputState == InputState::Paused ? L" — Input processing paused" : L" — Pausing input processing…"; + badge = trayInputIcon(icon.hIcon, width, height, 0xff858585); + if (badge) icon.hIcon = badge; + } + else if (trayInput.paired) { const bool reconnecting = trayInput.reconnecting(); const uint32_t color = trayInput.stopped ? 0xfff16b66 : !trayInput.online ? 0xffa0a4ab : !reconnecting ? 0xff45d58c : trayInputPulse ? 0xffffc457 : 0xffac7830; badge = trayInputIcon(icon.hIcon, width, height, color); if (badge) icon.hIcon = badge; - tip += L" — Mouse & keyboard: "; + tip += L"\nMouse & keyboard: "; if (trayInput.stopped) tip += L"connection stopped"; else if (!trayInput.online) tip += L"all paired PCs offline. Waiting for LAN discovery."; else @@ -1010,8 +1023,6 @@ bool App::updateTray(DWORD action, bool notifyFile) std::to_wstring(trayInput.paired) + L" PCs connected)"; } } - else if (!incomingLanFileCount) - tip = localBuildTitle(L"KSwitcher — keyboard layouts & clipboard"); if (incomingLanFileCount) tip += L"\nFiles ready to save: " + std::to_wstring(incomingLanFileCount); wcsncpy_s(icon.szTip, tip.c_str(), _TRUNCATE); @@ -1057,6 +1068,25 @@ void App::addTray() trayRetryPending = SetTimer(window, TrayRetryTimer, TrayRetryIntervalMs, nullptr) != 0; } } +bool App::installInputHooks() +{ + keyboardHook = SetWindowsHookExW(WH_KEYBOARD_LL, keyProc, instance, 0); + if (keyboardHook) mouseHook = SetWindowsHookExW(WH_MOUSE_LL, mouseProc, instance, 0); + if (keyboardHook && mouseHook) return true; + registrationWarning = lastError(L"Keyboard and mouse interception could not start"); + releaseInputHooks(); + return false; +} + +void App::releaseInputHooks() +{ + if (filesHotkeyId) UnregisterHotKey(window, std::exchange(filesHotkeyId, 0)); + registeredFilesHotkey = {}; + hookBindings.clear(); + if (keyboardHook) UnhookWindowsHookEx(std::exchange(keyboardHook, nullptr)); + if (mouseHook) UnhookWindowsHookEx(std::exchange(mouseHook, nullptr)); +} + bool App::registerHotkeys(const Settings &s, bool rollback) { std::vector> bindings; @@ -1078,7 +1108,7 @@ bool App::registerHotkeys(const Settings &s, bool rollback) const int next = filesHotkeyId == FilesHotkeyFirst ? FilesHotkeySecond : FilesHotkeyFirst; if (files.key && !RegisterHotKey(window, next, files.modifiers | MOD_NOREPEAT, files.key)) { - if (!rollback) registrationWarning = L"The KSwitcher Files shortcut is unavailable. Choose another shortcut."; + if (!rollback) registrationWarning = L"The KSwitcher Files shortcut (" + *s.filesHotkey + L") is unavailable."; return false; } if (filesHotkeyId) UnregisterHotKey(window, filesHotkeyId); @@ -1091,14 +1121,24 @@ bool App::registerHotkeys(const Settings &s, bool rollback) Bytes App::lanCommand(const Bytes &command) { - if (!lanService) lanService = std::make_unique(data,window); + if (!lanService) lanService = std::make_unique(data,window,inputState != InputState::Active); auto reply = lanService->command(command); - if (lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr); - else KillTimer(window, 7); + updateLanInputTimer(); if (lanService->takeInputChange()) resetLanInput(); refreshTrayInput(); return reply; } +void App::updateLanInputTimer() +{ + if (lanService && lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr); + else KillTimer(window, 7); +} +void App::pollLanInput() +{ + // Temporary text transactions only block new handoffs. A tray pause removes + // the router entirely, including for already queued network notifications. + if (lanService && lanService->tickInput(!busy && !suspended && !hotkeyCapture)) resetLanInput(); +} void App::applySettings(const Settings &requested) { applySettings(requested, true); @@ -1175,7 +1215,7 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation) } predictor.configure(std::filesystem::path(executable()).parent_path() / L"dictionaries", s.autoLanguages); } - if (!registerHotkeys(s)) + if (inputState == InputState::Active && !registerHotkeys(s)) { registerHotkeys(settings, true); throw std::runtime_error(utf8(registrationWarning)); @@ -1199,7 +1239,7 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation) catch (...) { } - registerHotkeys(settings, true); + if (inputState == InputState::Active) registerHotkeys(settings, true); throw; } { @@ -1243,7 +1283,7 @@ void App::reloadLayouts() ++inputVersion; if (busy) diagnosticEvent(L"Input context changed: layouts reloaded version=" + std::to_wstring(inputVersion.load())); } - registerHotkeys(settings); + if (inputState == InputState::Active) registerHotkeys(settings); } void App::clearHistory() { @@ -1653,7 +1693,8 @@ void App::switchChatLayout(bool reverse) enqueue([this, target, key, cycle, available, reverse, profileSettings = settings] { struct Reset { std::atomic &busy; ~Reset() { busy = false; } } reset{busy}; - auto valid = [&] { return GetForegroundWindow() == target && windowLanguageProfileKey(profileSettings, target) == key; }; + auto valid = [&] { return inputState == InputState::Active && GetForegroundWindow() == target && + windowLanguageProfileKey(profileSettings, target) == key; }; if (key.starts_with(L"telegram-web\n") && readChromeChat(target) != key) return; if (!valid()) return; auto next = nextChatLayout(cycle, available, windowLayout(target), reverse); @@ -1664,7 +1705,7 @@ bool App::handleKeyboard(const KBDLLHOOKSTRUCT &key, bool down, UINT mods) { // Filter before capture, hotkey latching and typing history. External injected // down AND up events use exactly the same path as physical keyboard input. - if (ownKeyboardInput(key) || installingUpdate) + if (inputState != InputState::Active || ownKeyboardInput(key) || installingUpdate) return false; if (key.vkCode < snippetKeys.size() && snippetKeys[key.vkCode]) { @@ -1807,7 +1848,7 @@ void App::replayTyping() } LRESULT CALLBACK App::keyProc(int code, WPARAM wp, LPARAM lp) { - if (code == HC_ACTION && current && current->lanService && + if (code == HC_ACTION && current && current->inputState == InputState::Active && current->lanService && (wp == WM_KEYDOWN || wp == WM_SYSKEYDOWN || wp == WM_KEYUP || wp == WM_SYSKEYUP)) { bool consumed = current->lanService->keyboard(*(KBDLLHOOKSTRUCT *)lp, wp == WM_KEYDOWN || wp == WM_SYSKEYDOWN); @@ -2062,7 +2103,7 @@ void App::dispatchMouseActions() LRESULT CALLBACK App::mouseProc(int code, WPARAM wp, LPARAM lp) { - if (code == HC_ACTION && current) + if (code == HC_ACTION && current && current->inputState == InputState::Active) { auto &app = *current; const auto &mouse = *reinterpret_cast(lp); @@ -2256,7 +2297,7 @@ void App::dispatch(int command) } void App::transform(int command, int snippet, size_t snippetLength, HWND snippetEditor) { - if (installingUpdate) return; + if (installingUpdate || inputState != InputState::Active) return; const auto attempt = ++transformAttempt; const auto requestedAt = GetTickCount64(); HWND target = GetForegroundWindow(); @@ -2412,7 +2453,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet }; for (int i = 0; i < 8 && !modifiersReleased(); ++i) Sleep(10); - if (!modifiersReleased() && command == AutoCorrect) + if (!valid() || (!modifiersReleased() && command == AutoCorrect)) return; if (!modifiersReleased()) releaseModifiers(); @@ -2884,6 +2925,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet void App::pasteEntry(std::wstring id, bool plain) { if (historyService) { remoteHistory("paste", id, plain); return; } + if (inputState != InputState::Active) { report(L"Resume input processing in the tray to paste from history."); return; } if (installingUpdate) return; if (!history || busy.exchange(true)) return; @@ -3084,6 +3126,65 @@ void App::recognizeEntry(std::wstring id) } }); } +void App::toggleInputProcessing() +{ + if (inputState == InputState::Pausing) return; + if (inputState == InputState::Active) + { + inputState = InputState::Pausing; + // Some hook shortcuts intentionally override shell-owned combinations. + // Detect new Windows registrations across the pause without rejecting those. + availableBeforePause.clear(); + for (const auto &binding : hookBindings) + if (shortcutAvailable(window, binding.second)) availableBeforePause.push_back(binding.second); + releaseInputHooks(); + resetLanInput(); + mousePresses = {}; + KillTimer(window, MouseClickTimer); + for (size_t i = 0; i < mousePresses.size(); ++i) KillTimer(window, FirstMouseVolumeTimer + i); + PostMessageW(window, MouseVolumeReleasedMessage, 0, 0); + hideSnippetPopup(); + if (lanService) lanService->setInputPaused(true); + KillTimer(window, 8); + stopBrowserChatMonitor(); + // Cancel the worker via inputVersion. Its normal completion path restores + // the clipboard and handles any typing already buffered before the pause. + if (busy) SetTimer(window, PauseDrainTimer, 50, nullptr); + else inputState = InputState::Paused; + } + else + { + // Discard deliveries queued for the previous hook/registration before + // acquiring shortcuts again, even if Windows reuses a registration ID. + MSG stale{}; + while (PeekMessageW(&stale, window, WM_HOTKEY, WM_HOTKEY, PM_REMOVE)) {} + try + { + if (!installInputHooks() || !registerHotkeys(settings)) + throw std::runtime_error(utf8(registrationWarning)); + for (const auto &[id, key] : hookBindings) + if (std::find(availableBeforePause.begin(), availableBeforePause.end(), key) != availableBeforePause.end() && + !shortcutAvailable(window, key)) + throw std::runtime_error(utf8(L"The shortcut " + key.format() + L" is now in use.")); + if (!smoke) startBrowserChatMonitor(); + if (lanService) lanService->setInputPaused(false); + } + catch (const std::exception &e) + { + releaseInputHooks(); + stopBrowserChatMonitor(); + if (lanService) lanService->setInputPaused(true); + report(wide(e.what()) + L" Input remains paused. Retry from the tray when ready."); + return; + } + inputState = InputState::Active; + if (!smoke) SetTimer(window, 8, 250, nullptr); + } + updateLanInputTimer(); + refreshTrayInput(); + updateTray(NIM_MODIFY); +} + void App::trayMenu() { constexpr int utilityCommandBase = 1000; @@ -3091,6 +3192,10 @@ void App::trayMenu() auto utilities = discoverUtilities(std::filesystem::path(executable()).parent_path() / L"tools", utilitiesError); if (utilities.size() > 50000) utilities.resize(50000); HMENU menu = CreatePopupMenu(); + AppendMenuW(menu, MF_STRING | (inputState == InputState::Pausing ? MF_GRAYED : 0), ToggleInputProcessing, + inputState == InputState::Active ? L"Pause &input processing" : + inputState == InputState::Paused ? L"Resume &input processing" : L"Pausing input processing…"); + AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); AppendMenuW(menu, MF_STRING, 10, L"Clipboard &history"); AppendMenuW(menu, MF_STRING, 24, L"&Capture screen region…"); AppendMenuW(menu, MF_STRING, 11, L"&Settings…"); @@ -3121,7 +3226,7 @@ void App::trayMenu() AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); AppendMenuW(menu, MF_STRING, 16, L"&About KSwitcher"); AppendMenuW(menu, MF_STRING, 17, L"E&xit"); - POINT pt; + POINT pt{}; GetCursorPos(&pt); pasteTarget = GetForegroundWindow(); SetForegroundWindow(window); @@ -3147,6 +3252,9 @@ void App::trayMenu() } switch (cmd) { + case ToggleInputProcessing: + toggleInputProcessing(); + break; case OpenFiles: dispatch(OpenFiles); break; @@ -3347,6 +3455,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) return 0; } case WM_HOTKEY: + if (app->inputState != InputState::Active || wp == ShortcutProbeId) return 0; if (app->filesHotkeyId && wp == static_cast(app->filesHotkeyId)) { if(!activateFilesWindow()) app->dispatch(OpenFiles); @@ -3391,7 +3500,8 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) case AutoCorrectMessage: if (app->autoPending) { - if (!app->installingUpdate && !app->snippetTyping && app->settings.autoCorrect && app->inputVersion.load() == (uint64_t)wp) + if (app->inputState == InputState::Active && !app->installingUpdate && !app->snippetTyping && + app->settings.autoCorrect && app->inputVersion.load() == (uint64_t)wp) app->transform(AutoCorrect); else app->replayTyping(); @@ -3400,7 +3510,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) case SnippetMessage: if (app->snippetPending == (int)wp) { - if (!app->installingUpdate && app->inputVersion.load() == (uint64_t)lp && + if (app->inputState == InputState::Active && !app->installingUpdate && app->inputVersion.load() == (uint64_t)lp && (!app->snippetPendingEditor || GetForegroundWindow() == app->typingTarget)) app->transform(0, (int)wp, app->snippetPendingLength, app->snippetPendingEditor); else @@ -3489,9 +3599,22 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) } case LanClipboardReadyMessage: app->receiveClipboard();return 0; case LanInputReadyMessage: - if(app->lanService&&app->lanService->tickInput(!app->busy&&!app->suspended&&!app->hotkeyCapture))app->resetLanInput(); + app->pollLanInput(); return 0; case WM_TIMER: + if (wp == PauseDrainTimer) + { + if (!app->busy) + { + KillTimer(hwnd, PauseDrainTimer); + if (app->inputState == InputState::Pausing) + { + app->inputState = InputState::Paused; + app->updateTray(NIM_MODIFY); + } + } + return 0; + } if (wp == SnippetPopupTimer) { if (!app->snippetPopupCurrent()) app->hideSnippetPopup(); @@ -3519,7 +3642,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) } if (wp == 8) { - if (app->settings.appLanguageSets.empty() || app->busy || app->installingUpdate) return 0; + if (app->inputState != InputState::Active || app->settings.appLanguageSets.empty() || app->busy || app->installingUpdate) return 0; app->refreshChatContext(); if (!app->activeChat.starts_with(L"app\n")) return 0; auto cycle = chatCycle(app->settings, app->activeChat, app->layouts); @@ -3533,13 +3656,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) if (wp == 7) { - if (app->lanService) - { - // suspended also guards clipboard/text transactions (correction, - // conversion, snippets). Those must not disconnect remote input. - // Actual system suspension is handled by WM_POWERBROADCAST. - if (app->lanService->tickInput(!app->busy && !app->suspended && !app->hotkeyCapture)) app->resetLanInput(); - } + app->pollLanInput(); return 0; } if (wp == 6) @@ -3577,7 +3694,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) PostMessageW(hwnd, WM_CLOSE, 0, 0); return 0; } - if (app->settings.awake) + if (wp == 1 && app->inputState == InputState::Active && app->settings.awake) { LASTINPUTINFO idle{sizeof(idle)}; if (GetLastInputInfo(&idle) && DWORD(GetTickCount() - idle.dwTime) >= 180000) @@ -3673,8 +3790,6 @@ int App::execute() } return int(message.wParam); } - keyboardHook = SetWindowsHookExW(WH_KEYBOARD_LL, keyProc, instance, 0); - mouseHook = SetWindowsHookExW(WH_MOUSE_LL, mouseProc, instance, 0); const bool useDefaultFilesHotkey = !settings.filesHotkey; if (useDefaultFilesHotkey) { @@ -3686,28 +3801,28 @@ int App::execute() }); settings.filesHotkey = conflict ? L"" : L"Ctrl+Alt+F"; } - if (!registerHotkeys(settings) && settings.filesHotkey && !settings.filesHotkey->empty()) + if (!installInputHooks()) + inputState = InputState::Paused; + else if (!registerHotkeys(settings) && settings.filesHotkey && !settings.filesHotkey->empty()) { if (useDefaultFilesHotkey) settings.filesHotkey = L""; auto fallback = settings; fallback.filesHotkey = L""; registerHotkeys(fallback, true); } - if (!keyboardHook || !mouseHook) - report(L"Input tracking could not start. Automatic recent-text conversion is unavailable."); AddClipboardFormatListener(window); // Resume pending OCR, including older images without a saved OCR state. scheduleHistoryOcr(settings); addTray(); - if (!smoke) startBrowserChatMonitor(); + if (!smoke && inputState == InputState::Active) startBrowserChatMonitor(); if (!smoke && std::filesystem::exists(data / L"lan-pairing.bin")) - try { lanService = std::make_unique(data,window); } + try { lanService = std::make_unique(data,window,inputState != InputState::Active); } catch (const std::exception &e) { report(L"LAN module: " + wide(e.what())); } - if (lanService && lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr); + updateLanInputTimer(); refreshTrayInput(); SetTimer(window, 1, 60000, nullptr); if (!smoke) SetTimer(window, 6, 1000, nullptr); - if (!smoke) SetTimer(window, 8, 250, nullptr); + if (!smoke && inputState == InputState::Active) SetTimer(window, 8, 250, nullptr); SetThreadExecutionState(ES_CONTINUOUS | (settings.awake ? (ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED) : 0)); if (!registrationWarning.empty()) diff --git a/src/app.h b/src/app.h index 64d1bc3..6452b1a 100644 --- a/src/app.h +++ b/src/app.h @@ -110,6 +110,13 @@ class App void checkAutostartPath(); bool checkingAutostartPath{}; HHOOK keyboardHook{}, mouseHook{}; + enum class InputState { Active, Pausing, Paused }; + std::atomic inputState{InputState::Active}; + bool installInputHooks(); + void releaseInputHooks(); + void toggleInputProcessing(); + void updateLanInputTimer(); + void pollLanInput(); struct MousePress { HWND target{}; @@ -173,6 +180,7 @@ class App HWND previousAttemptWindow{}; int previousAttemptCommand{}, repeatAttempts{}; std::vector> hookBindings; + std::vector availableBeforePause; Hotkey registeredFilesHotkey{}; int filesHotkeyId{}; HotkeyHook hotkeyHook; diff --git a/src/lan.cpp b/src/lan.cpp index 38610ee..a78704c 100644 --- a/src/lan.cpp +++ b/src/lan.cpp @@ -134,6 +134,9 @@ struct LanService::Impl std::mutex mutex; std::thread worker; bool shareInput{}; + bool inputPaused{}; + std::mutex transportMutex; + bool resetInputChannels{}; std::string inputPeer; int inputEdge=1; std::atomic abortInput{false}; @@ -150,7 +153,8 @@ struct LanService::Impl bool inputWorkerStopped{}; bool inputNeedsHelp{}; HWND inputWindow{};std::atomic inputNotification{false}; - explicit Impl(const std::filesystem::path &root,HWND window) : path(root/L"lan-pairing.bin"),inputWindow(window) + explicit Impl(const std::filesystem::path &root,HWND window,bool paused) + : path(root/L"lan-pairing.bin"),inputPaused(paused),inputWindow(window) { if(std::filesystem::exists(path)) { @@ -192,13 +196,32 @@ struct LanService::Impl { if(router)router->cancel(GetTickCount64()); router.reset();++inputConfiguration; - if(enabled&&shareInput){ + if(enabled&&shareInput&&!inputPaused){ std::map layout;for(auto &[peer,cell]:positions.items())if(trusted.contains(peer))layout[peer]={cell[0].get(),cell[1].get()}; router=std::make_unique(id,lan::windowsInputEnvironment(),std::move(layout),[this](const auto &peer,auto f){return queue(peer,f);}); } inputStatus=enabled&&shareInput?"Connecting input channels...":"Input sharing disabled."; observedRevision=0; } + void setInputPaused(bool paused) + { + // A poll can own a batch outside the queues. Finish that poll before + // cancelling the router and discarding both directions of the old session. + std::lock_guard transportLock(transportMutex); + std::lock_guard lock(mutex); + if (inputPaused == paused) return; + inputPaused = paused; + configureRouter(); + if (paused) + { + resetInputChannels = true; + std::lock_guard queueLock(inputMutex); + inputIn.clear(); + inputOut.clear(); + inputReady.clear(); + inputConnectedPeers = inputOnlinePeers = 0; + } + } bool takeChange() { auto revision=router?router->revision():0;auto configuration=inputConfiguration.load(); @@ -444,7 +467,7 @@ struct LanService::Impl if(peers.contains(target))send(socket,peers.at(target).address,packet); }); clipboardActive=clipboard->active()||transfers->active(); - if(shareInput)for(auto &[peer,entry]:trusted.items()) + if(shareInput&&!inputPaused)for(auto &[peer,entry]:trusted.items()) { const auto found=peers.find(peer); const bool discovered=found!=peers.end()&&found->second.present(now); @@ -470,6 +493,13 @@ struct LanService::Impl } } std::vector out,in; + std::unique_lock transportLock(transportMutex); + if (resetInputChannels) + { + hub.poll({}, {}, in, now); + resetInputChannels = false; + } + if (inputPaused) endpoints.clear(); {std::lock_guard lock(inputMutex);out.swap(inputOut);} if(abortInput.exchange(false)){hub.disconnect();out.clear();} hub.poll(endpoints,out,in,now); @@ -489,6 +519,7 @@ struct LanService::Impl const auto online=hub.onlinePeers(); updateInputStatus(connected,online,online||endpoints.empty()?hub.status(): "All paired PCs are offline. Waiting for LAN discovery.",hub.needsHelp()); + transportLock.unlock(); fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,online||clipboardActive?5000:100000}; int ready=select(0,&read,nullptr,nullptr,&delay); if(ready==SOCKET_ERROR) throw std::runtime_error("LAN discovery socket failed."); @@ -502,7 +533,7 @@ struct LanService::Impl auto j=Json::parse(buffer,buffer+received); if(j.value("type","")=="input-udp"){ bool allowed=false;auto peer=j.value("id",""); - {std::lock_guard lock(mutex);allowed=shareInput&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;} + {std::lock_guard lock(mutex);allowed=shareInput&&!inputPaused&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;} if(allowed)hub.receiveDatagram(j,GetTickCount64()); }else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64(),filesListening);} } @@ -670,7 +701,7 @@ struct LanService::Impl } Json result={{"enabled",enabled},{"id",id},{"name",name},{"status",status},{"pending",pending&&!pending->confirmed},{"peers",Json::array()}, {"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnectedPeers!=0}, - {"inputStatus",enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}}; + {"inputStatus",inputPaused?"Input processing paused in the tray.":enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",!inputPaused&&enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}}; {std::lock_guard inputLock(inputMutex);result["inputReady"]=inputReady;} result["shareLogs"]=shareLogs; result["files"]=Json::array(); @@ -698,7 +729,7 @@ struct LanService::Impl return encoded(result); } }; -LanService::LanService(const std::filesystem::path &path,HWND window) : impl(std::make_unique(path,window)) {} +LanService::LanService(const std::filesystem::path &path,HWND window,bool paused) : impl(std::make_unique(path,window,paused)) {} LanService::~LanService()=default; Bytes LanService::command(const Bytes &command) { return impl->command(command); } bool LanService::clipboardEnabled()const @@ -722,7 +753,8 @@ std::vector LanService::takeClipboard() result.push_back({d.peer,impl->trusted.at(d.peer).at("name"),d.app,std::move(d.bytes),d.sequence}); impl->clipboard->deliveries.clear();return result; } -bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput;} +bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput&&!impl->inputPaused;} +void LanService::setInputPaused(bool paused){impl->setInputPaused(paused);} LanInputConnections LanService::inputConnections()const { std::lock_guard lock(impl->mutex); diff --git a/src/lan.h b/src/lan.h index babea44..84c39e2 100644 --- a/src/lan.h +++ b/src/lan.h @@ -22,13 +22,14 @@ class LanService struct Impl; std::unique_ptr impl; public: - explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr); + explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr, bool inputPaused=false); ~LanService(); Bytes command(const Bytes &); bool clipboardEnabled() const; void publishClipboard(Bytes, const std::string &); std::vector takeClipboard(); bool inputEnabled() const; + void setInputPaused(bool); LanInputConnections inputConnections() const; bool tickInput(bool allowEnter = true); bool keyboard(const KBDLLHOOKSTRUCT &, bool down); diff --git a/tests/input.cpp b/tests/input.cpp index 868ff6b..5f1f8b5 100644 --- a/tests/input.cpp +++ b/tests/input.cpp @@ -7,6 +7,7 @@ #include #include #include +#include "input_pause.h" static int settingsCloseChoice = IDCANCEL; static int settingsClosePrompts = 0; static void CALLBACK answerSettingsClose(HWND, UINT, UINT_PTR, DWORD) @@ -27,6 +28,44 @@ LRESULT CALLBACK countControlMoves(HWND w, UINT message, WPARAM wp, LPARAM lp, U } namespace ks { struct InputRegressionAccess { + static LRESULT CALLBACK probeInput(HWND w, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR context) { + auto &app = *reinterpret_cast(context); + static bool queuedSnippet = false; + // Queue a real expansion just before TrackPopupMenu returns the pause command. + if (msg == WM_EXITMENULOOP && app.inputState == App::InputState::Active) + queuedSnippet = app.queueSnippet(w, 0, 2, w); + if (msg != ProbeInputState) return DefSubclassProc(w, msg, wp, lp); + // Also exercise settings/layout updates that would normally re-register shortcuts. + if (wp && app.inputState == App::InputState::Paused) { + app.applySettings(app.settings); + app.reloadLayouts(); + app.dispatch(Toggle); + app.pasteEntry(L"fixture", false); + const auto version = app.inputVersion.load(); + KBDLLHOOKSTRUCT key{}; + key.vkCode = 'A'; + if (app.handleKeyboard(key, true, 0) || app.inputVersion != version) return 0; + const std::string status = R"({"action":"status"})"; + const auto response = app.lanCommand(Bytes(status.begin(), status.end())); + if (std::string(response.begin(), response.end()).find("Input processing paused") == std::string::npos) + return 0; + } + const bool bound = app.isHotkey(VK_F22, MOD_CONTROL | MOD_SHIFT); + if (app.inputState == App::InputState::Active && app.keyboardHook && app.mouseHook && + app.filesHotkeyId && bound) return 1; + if (app.inputState == App::InputState::Paused && !app.keyboardHook && !app.mouseHook && + !app.filesHotkeyId && !bound && !app.busy && app.snippetPending == -1 && + !app.snippetTyping && queuedSnippet && !app.transformAttempt) return 2; + return 0; + } + static void CALLBACK installProbe(HWND, UINT, UINT_PTR timer, DWORD) { + auto app = App::current; + if (app && app->window && SetWindowSubclass(app->window, probeInput, 1, reinterpret_cast(app))) { + KillTimer(app->window, 5); // Keep the input fixture independent of update checks. + SetTimer(app->window, 2, 60000, nullptr); + KillTimer(nullptr, timer); + } + } static int snippetChoice(App &a, const std::vector &snippets) { a.settings.snippets=snippets; a.settings.autoCorrect=false; a.busy=false; a.snippetPending=-1; a.typingTarget=nullptr; a.snippetTyping=false; @@ -169,6 +208,20 @@ struct InputRegressionAccess { }; } int main(int argc, char **argv) { + if (argc == 2 && std::string(argv[1]) == "--input-pause") return testInputPause(); + if (argc == 2 && std::string(argv[1]) == "--input-pause-resident") { + // The driver copies this binary alone into a fresh fixture folder. + auto folder = std::filesystem::path(ks::executable()).parent_path(); + if (!folder.filename().wstring().starts_with(L"KSwitcher-input-pause-")) return 1; + CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + ks::App app(GetModuleHandleW(nullptr), false, folder / L"data"); + app.settings.toggle = L"Ctrl+Shift+F22"; + app.settings.filesHotkey = L"Ctrl+Shift+F23"; + app.settings.snippets = {{L";t", L"fixture"}}; + app.settings.history = app.settings.autoCorrect = app.settings.autostart = false; + SetTimer(nullptr, 0, 10, ks::InputRegressionAccess::installProbe); + return app.execute(); + } if (argc == 2 && std::string(argv[1]) == "--update-check") { try { auto result = ks::runUpdate(false, {}); diff --git a/tests/input_pause.cpp b/tests/input_pause.cpp new file mode 100644 index 0000000..744a187 --- /dev/null +++ b/tests/input_pause.cpp @@ -0,0 +1,119 @@ +#include "app.h" +#include "input_pause.h" +#include + +namespace { +void require(bool result, const char *message) +{ + if (!result) throw std::runtime_error(message); +} + +template void until(Predicate ready, const char *message) +{ + auto deadline = GetTickCount64() + 4000; + while (!ready()) { + require(GetTickCount64() < deadline, message); + Sleep(10); + } +} + +HWND childWindow(DWORD pid, const wchar_t *type) +{ + HWND w{}; + while ((w = FindWindowExW(nullptr, w, type, nullptr))) { + DWORD owner{}; + GetWindowThreadProcessId(w, &owner); + if (owner == pid) return w; + } + return nullptr; +} + +DWORD_PTR query(HWND w, UINT msg, WPARAM wp = 0) +{ + DWORD_PTR result{}; + require(SendMessageTimeoutW(w, msg, wp, 0, SMTO_ABORTIFHUNG | SMTO_ERRORONEXIT, 2000, &result), + "test resident did not respond"); + return result; +} + +void chooseInputAction(HWND resident, DWORD pid, const wchar_t *expected) +{ + require(PostMessageW(resident, ks::TrayMessage, 0, WM_CONTEXTMENU), "cannot open tray menu"); + HWND popup{}; + until([&] { popup = childWindow(pid, L"#32768"); return popup && IsWindowVisible(popup); }, + "tray menu did not open"); + const auto menu = reinterpret_cast(query(popup, MN_GETHMENU)); + wchar_t label[100]{}; + require(GetMenuStringW(menu, 0, label, std::size(label), MF_BYPOSITION) && + std::wstring_view(label).starts_with(expected), "incorrect input state in tray menu"); + require(PostMessageW(popup, WM_CHAR, L'i', 0), "cannot select input menu item"); + until([&] { return !IsWindow(popup); }, "tray action did not close menu"); + query(resident, WM_NULL); +} +} + +int testInputPause() +{ + auto name = L"KSwitcher-input-pause-" + ks::newSnippetId(); + const auto folder = std::filesystem::temp_directory_path() / name; + PROCESS_INFORMATION child{}; + HWND resident{}; + int result = 1; + bool created = false; + try { + // Never switch the user's visible desktop or direct a command at their resident. + const auto desktop = CreateDesktopW(name.c_str(), nullptr, nullptr, 0, GENERIC_ALL, nullptr); + require(desktop && SetThreadDesktop(desktop), "cannot use private desktop"); + created = std::filesystem::create_directory(folder); + require(created, "cannot create fixture directory"); + const auto fixture = folder / L"KSwitcherInputTests.exe"; + std::filesystem::copy_file(ks::executable(), fixture); + auto command = L"\"" + fixture.wstring() + L"\" --input-pause-resident"; + STARTUPINFOW startup{sizeof(startup)}; + startup.lpDesktop = name.data(); + require(CreateProcessW(fixture.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, + nullptr, folder.c_str(), &startup, &child), "cannot start test resident"); + until([&] { + resident = childWindow(child.dwProcessId, L"KSwitcher.Main"); + return resident && query(resident, ProbeInputState) == 1; + }, "resident did not start with both hooks and shortcuts"); + constexpr UINT mods = MOD_CONTROL | MOD_SHIFT; + require(!RegisterHotKey(nullptr, 1, mods, VK_F23) && GetLastError() == ERROR_HOTKEY_ALREADY_REGISTERED, + "Files shortcut should be owned by resident before pause"); + chooseInputAction(resident, child.dwProcessId, L"Pause &input processing"); + until([&] { return query(resident, ProbeInputState) == 2; }, + "pause did not release both hooks and bindings and cancel the queued snippet"); + require(RegisterHotKey(nullptr, 1, mods, VK_F23), "another process could not acquire Files shortcut"); + require(query(resident, ProbeInputState, 1) == 2, "settings, layout reload or IPC restarted input"); + chooseInputAction(resident, child.dwProcessId, L"Resume &input processing"); + require(query(resident, ProbeInputState) == 2, "Files conflict partially resumed input"); + require(UnregisterHotKey(nullptr, 1), "cannot release Files shortcut"); + require(RegisterHotKey(nullptr, 2, mods, VK_F22), "cannot occupy hook shortcut during pause"); + chooseInputAction(resident, child.dwProcessId, L"Resume &input processing"); + require(query(resident, ProbeInputState) == 2, "hook shortcut conflict partially resumed input"); + require(RegisterHotKey(nullptr, 1, mods, VK_F23), "failed resume leaked Files registration"); + UnregisterHotKey(nullptr, 1); + UnregisterHotKey(nullptr, 2); + chooseInputAction(resident, child.dwProcessId, L"Resume &input processing"); + require(query(resident, ProbeInputState) == 1, "resume did not restore both hooks and shortcuts"); + require(!RegisterHotKey(nullptr, 1, mods, VK_F23) && GetLastError() == ERROR_HOTKEY_ALREADY_REGISTERED, + "resident did not reclaim Files shortcut"); + std::cout << "Tray pause/resume, hooks, settings reload, cross-process ownership and conflict rollback passed.\n"; + result = 0; + } catch (const std::exception &e) { + std::cerr << e.what() << '\n'; + } + if (child.hProcess) { + if (resident) PostMessageW(resident, WM_CLOSE, 0, 0); + if (WaitForSingleObject(child.hProcess, 2000) != WAIT_OBJECT_0) { + TerminateProcess(child.hProcess, 1); + WaitForSingleObject(child.hProcess, 2000); + result = 1; + } + CloseHandle(child.hThread); + CloseHandle(child.hProcess); + } + std::error_code error; + if (created) std::filesystem::remove_all(folder, error); + return result; +} diff --git a/tests/input_pause.h b/tests/input_pause.h new file mode 100644 index 0000000..d83c796 --- /dev/null +++ b/tests/input_pause.h @@ -0,0 +1,5 @@ +#pragma once +#include + +inline constexpr UINT ProbeInputState = WM_APP + 200; +int testInputPause(); diff --git a/tests/lan.cpp b/tests/lan.cpp index d7292e2..af04ec6 100644 --- a/tests/lan.cpp +++ b/tests/lan.cpp @@ -131,7 +131,7 @@ int main(int argc,char **argv) { const auto folder=root/L"wake"; std::filesystem::create_directory(folder); - const auto saved=Json{{"version",1},{"id",a},{"enabled",true},{"trusted",{ + const auto saved=Json{{"version",1},{"id",a},{"enabled",true},{"shareInput",true},{"trusted",{ {b,{{"name","Wake peer"},{"key",left.derived},{"wakeMac","02468ace1357"}}}, {c,{{"name","Legacy peer"},{"key",left.derived}}}}}}.dump(); atomicWrite(folder/L"lan-pairing.bin",protect(Bytes(saved.begin(),saved.end()))); @@ -140,6 +140,19 @@ int main(int argc,char **argv) check(peers.size()==2 && peers[0].at("id")==b && peers[0].at("address")=="" && peers[1].at("id")==c,"offline PCs remain selectable in Files with or without a saved MAC address"); check(peers.dump().find("02468ace1357")==std::string::npos,"Files snapshot omits the stored MAC address"); + const auto pairing = readFile(folder/L"lan-pairing.bin",256*1024); + check(restored.inputEnabled(), "paired LAN input starts enabled"); + restored.setInputPaused(true); + const auto state = request(restored,{{"action","status"}}); + check(!restored.inputEnabled() && state.at("enabled")==true && state.at("shareInput")==true && + state.at("controlMode")==0 && state.at("inputReady").empty() && + state.at("inputStatus")=="Input processing paused in the tray.", + "tray pause disables LAN input while keeping discovery and the saved permission"); + check(!restored.tickInput() && !restored.keyboard(KBDLLHOOKSTRUCT{},true) && + !restored.mouse(WM_MOUSEMOVE,MSLLHOOKSTRUCT{},true), "paused LAN router ignores input and queued ticks"); + restored.setInputPaused(false); + check(restored.inputEnabled() && readFile(folder/L"lan-pairing.bin",256*1024)==pairing, + "LAN input resumes from the original pairing without rewriting it"); } if(argc>1&&std::string(argv[1])=="--network") {