Pause and resume resident input processing from the tray

This commit is contained in:
agrynco committed 2026-11-22 12:30:53 +02:00
1 parent f5fc7d205c
commit 3be628cd8f
11 files changed
+428 -57

No files matched your search

+159 -44
View File
@@ -143,6 +143,16 @@ ULONG_PTR snippetReplayMarker()
return reinterpret_cast<ULONG_PTR>(&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<std::pair<int, Hotkey>> 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<LanService>(data,window);
if (!lanService) lanService = std::make_unique<LanService>(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<bool> &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<const MSLLHOOKSTRUCT *>(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<WPARAM>(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<LanService>(data,window); }
try { lanService = std::make_unique<LanService>(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())