Compare commits

..
Author SHA1 Message Date
agrynco e8ebbc3b4e Prepare KSwitcher v0.6.127
Accept Enter for a single visible snippet suggestion and consume the key. Include the verified package manifest and checksum.
2026-11-21 23:56:12 +02:00
23 changed files with 157 additions and 663 deletions

No files matched your search

+3 -7
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.130 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.127 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
@@ -52,10 +52,7 @@ target_link_libraries(KSwitcherFiles PRIVATE kscore)
target_include_directories(kscore PUBLIC src PRIVATE vendor)
target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00)
target_link_libraries(kscore PUBLIC ws2_32 bcrypt iphlpapi winhttp user32 shell32 shlwapi advapi32 crypt32 imm32 comctl32 gdi32 ole32 oleaut32 taskschd comdlg32 uuid windowscodecs runtimeobject uiautomationcore)
set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-paused.ico")
set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1")
add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
target_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP)
target_link_libraries(KSwitcher PRIVATE kscore)
@@ -87,7 +84,7 @@ if(MSVC)
else()
target_link_options(KSwitcherFarSnippetTests PRIVATE -municode -static -static-libgcc -static-libstdc++)
endif()
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)
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)
target_link_libraries(KSwitcherInputTests PRIVATE kscore)
target_compile_definitions(KSwitcherInputTests PRIVATE KS_SCREENSHOT_RESOURCES)
add_executable(KSwitcherScreenshotUITests tests/screenshot_ui.cpp resources/app.rc)
@@ -271,7 +268,6 @@ 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 "$<TARGET_FILE:StayHereTest>")
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 "$<TARGET_FILE:KSwitcher>")
+4 -26
View File
@@ -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.
The Files shortcut is registered with Windows. The other configured shortcuts use the keyboard hook and can replace ordinary Windows/app
All configured shortcuts use the existing 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.
Pause input processing, choose another shortcut or exit KSwitcher to restore the original action. Windows protects
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,28 +201,6 @@ 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 purple **K** changes to two white pause bars on a gray tile. The tooltip says **Input processing paused** once 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**. Фіолетова **K** зміниться на дві білі смуги на сірому тлі. Підказка **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
@@ -538,13 +516,13 @@ For example, `$skill-name{pause:500}{enter} Draft text{cursor}` types the token,
### Application-specific snippets — v0.6.51
In **Settings → Snippets**, select a snippet and enable **Only in these applications**. Drag the crosshair next to **Add app** onto an open window to add its application. Repeat for each application. You can also select a process from the dropdown and click **Add app**, or type executable names separated by commas, such as `ms-teams.exe, outlook.exe`. Uncheck the option for a global snippet. A checked but empty restriction cannot be saved. Use **Save snippets** to apply the changes.
In **Settings → Snippets**, select a snippet and enable **Only in these applications**. Enter executable names separated by commas, or select a currently open application's process and choose **Add app**. For example: `ms-teams.exe, outlook.exe`. Uncheck the option for a global snippet. A checked but empty restriction cannot be saved. Use **Save snippets** to apply the changes.
A matching application-specific snippet takes precedence over a global snippet with the same trigger. The same trigger can be used for different applications; overlapping scopes for the same trigger are rejected. Existing snippets without a scope remain global. Matching is case-insensitive by process name, with or without `.exe`, and is checked before insertion. No OCR or timer is involved. Chrome scope means the entire browser, not one website.
Scopes are saved with snippets and included in manual import/export and synchronization; merge conflicts consider the application scopes. Use v0.6.51 or newer on every synchronizing PC before sharing scoped snippets: older versions do not understand the restriction and may treat the snippet as global.
**Українською.** У **Settings → Snippets** вибери сніпет і ввімкни **Only in these applications**. Перетягни мішень поруч із **Add app** на відкрите вікно, щоб додати його програму. Повтори для кожної потрібної програми. Також можна вибрати процес зі списку й натиснути **Add app** або вписати назви процесів через кому, наприклад `ms-teams.exe, outlook.exe`. Вимкнений прапорець означає всі програми. Увімкнений прапорець із порожнім списком не можна зберегти. Натисни **Save snippets**, щоб застосувати зміни.
**Українською.** У **Settings → Snippets** вибери сніпет, увімкни **Only in these applications** та задай назви процесів через кому або вибери відкриту програму зі списку й натисни **Add app**. Наприклад: `ms-teams.exe, outlook.exe`. Вимкнений прапорець означає всі програми. Увімкнений прапорець із порожнім списком не можна зберегти. Натисни **Save snippets**, щоб застосувати зміни.
Сніпет конкретної програми має пріоритет над глобальним із тим самим тригером. Для різних програм однакові тригери дозволені, для перетинних областей — ні. Старі сніпети залишаються глобальними. Зіставлення за назвою процесу не залежить від регістру та суфікса `.exe`; OCR і таймерів немає. Для Chrome це весь браузер, а не окремий сайт. Обмеження входять до експорту/імпорту та синхронізації. Перед синхронізацією онови всі ПК до v0.6.51 або новішої: старі версії не розуміють обмеження та можуть застосувати сніпет глобально.
### Existing features
-24
View File
@@ -1,29 +1,5 @@
# Latest Windows release
## v0.6.130 — 2026-11-22
The tray shows a purple **K** while KSwitcher processes input. Choose **Pause input processing** to see two white pause bars on a gray tile. The purple **K** returns after **Resume input processing** succeeds. If another program still holds a shortcut, the pause bars stay visible.
**Українською.**
Фіолетова **K** у треї означає, що KSwitcher обробляє введення. Після вибору **Pause input processing** з’являються дві білі смуги на сірому тлі. Фіолетова **K** повертається після успішного **Resume input processing**. Якщо інша програма ще утримує гарячу клавішу, значок паузи залишається.
## v0.6.129 — 2026-11-22
Choose **Pause input processing** in the tray to test another keyboard tool. The tooltip shows **Input processing paused** once KSwitcher releases its shortcuts and stops keyboard and mouse actions, snippets, autocorrection, automatic layout switching, LAN input and simulated F15 activity. Clipboard history can still record entries. Choose **Resume input processing** to restore input. If a shortcut is occupied, KSwitcher names it and stays paused until you retry. Restarting KSwitcher also clears the pause.
**Українською.**
Щоб протестувати іншу програму для клавіатури, виберіть **Pause input processing** у треї. Підказка **Input processing paused** з’явиться, коли KSwitcher звільнить гарячі клавіші та призупинить дії клавіатури й миші, сніпети, автокорекцію, автоматичне перемикання розкладки, LAN-керування й імітацію F15. Історія буфера може й далі записувати нові елементи. Виберіть **Resume input processing** для відновлення. Якщо комбінація зайнята, KSwitcher покаже її та залишиться на паузі до повторної спроби. Перезапуск KSwitcher також скидає паузу.
## v0.6.128 — 2026-11-22
In **Settings → Snippets**, drag the crosshair next to **Add app** onto an open window to add its application. Repeat for each application, then choose **Save snippets**. Esc cancels a drag. Picking the same application twice adds it only once.
**Українською.**
На вкладці **Settings → Snippets** перетягніть мішень поруч із **Add app** на відкрите вікно, щоб додати його програму. Повторіть для кожної потрібної програми й натисніть **Save snippets**. Esc скасовує перетягування. Повторний вибір програми не створює дубліката.
## v0.6.127 — 2026-11-21
When the snippet popup shows one match, pressing Enter expands it immediately and consumes the key. With several matches, use the arrow keys and then press Enter to confirm.
+1 -1
View File
@@ -1 +1 @@
28f0dc723444344dbc9bf363077c0e7d00a6089e714f8937b096c29c55db6a01 KSwitcher-win-x64.zip
da1e6b22619b9a9c32ec5b2d131055a96d2b60c185936ec65cdb160eae839979 KSwitcher-win-x64.zip
+12 -12
View File
@@ -2,23 +2,23 @@
"files": [
{
"path": "KSwitcher.exe",
"size": 2508800,
"sha256": "bacf777a44cc1859fcdc07f411f18f065801ed07c6673719f177ae72f4247c0e"
"size": 2491904,
"sha256": "cc43f9fc566047f29cded8d1fff3f044150e3657add7b355ff97510a9672b879"
},
{
"path": "KSwitcher.Config.exe",
"size": 2478080,
"sha256": "1b072b84be7e862ef94271bc300908f8e0525c57890867d21bca3d2a396252d8"
"size": 2462720,
"sha256": "10240cdf03cbf9f197b783a18df79c6ef3975d7f193137a3f7f0290d74f79b67"
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3077120,
"sha256": "088a4db4035c15393c908271d80897bdb19da3405c28f4b7ec8af9829895a569"
"size": 3063808,
"sha256": "b2ad1f46b1562add9be160c83dd959a497ed75fcc3a59aecb3278edccb98cfdd"
},
{
"path": "KSwitcher.Files.exe",
"size": 4377600,
"sha256": "6dace995d53dff51d0b752a5327092346f8be4b4801ccf12db38e3cc9e30e5ce"
"size": 4377088,
"sha256": "5e56dc39311287534486d85f67bd2cc48e41b0e9da717ddbcfd3228ad28e9719"
},
{
"path": "WebView2Loader.dll",
@@ -107,8 +107,8 @@
},
{
"path": "README.md",
"size": 101852,
"sha256": "e180efa5da9672111d8649422b661f55c85f33e458aba9e1b95060ea7c95ebe2"
"size": 99061,
"sha256": "bb045f8b3a47734b21c5aad830ec43bbc13f209ccd29d923de812fe0b5086d56"
},
{
"path": "LAN-PREVIEW.md",
@@ -153,7 +153,7 @@
{
"path": "tools/StayHere.exe",
"size": 133120,
"sha256": "d18778c437b3dda8258babb9db48a94d275fbe7272241f08e0da96173595abd9"
"sha256": "65f2b3787eabd5412bfd96df78ff3500e18ba634655082bf817194a85d592c1d"
},
{
"path": "tools/StayHere-README.md",
@@ -162,5 +162,5 @@
}
],
"schema": 1,
"version": "0.6.130"
"version": "0.6.127"
}
+1 -3
View File
@@ -107,12 +107,10 @@ try {
if ($LASTEXITCODE) { throw 'Test build failed' }
& .\build\KSwitcherTests.exe
if ($LASTEXITCODE) { throw 'Tests failed' }
& $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
& $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
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
+3 -4
View File
@@ -2,7 +2,6 @@
#include <windows.h>
#include "resource.h"
IDI_KSWITCHER ICON "kswitcher.ico"
IDI_KSWITCHER_PAUSED ICON "kswitcher-paused.ico"
#ifdef KS_SCREENSHOT_RESOURCES
IDI_SCREENSHOT_QUESTION ICON "icons/question.ico"
IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
@@ -10,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,6,130,0
PRODUCTVERSION 0,6,130,0
FILEVERSION 0,6,127,0
PRODUCTVERSION 0,6,127,0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
@@ -21,7 +20,7 @@ BEGIN
BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.6.130"
VALUE "FileVersion", "0.6.127"
END
END
BLOCK "VarFileInfo"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

-1
View File
@@ -4,5 +4,4 @@
#define IDI_FILES_VIEWER 103
#define IDI_FILES_EDITOR 104
#define IDI_FILES_COMPARE 105
#define IDI_KSWITCHER_PAUSED 106
#define IDC_SCREENSHOT_PENCIL 500
+45 -162
View File
@@ -143,16 +143,6 @@ 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()
{
@@ -806,7 +796,7 @@ App::App(HINSTANCE h, bool test, const std::filesystem::path &dataRoot, HWND ser
}
App::~App()
{
releaseInputHooks();
if (filesHotkeyId) UnregisterHotKey(window, filesHotkeyId);
if (snippetPopup) DestroyWindow(snippetPopup);
lanService.reset();
stopBrowserChatMonitor();
@@ -816,6 +806,10 @@ 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;
@@ -986,12 +980,6 @@ HICON trayInputIcon(HICON base, int width, int height, uint32_t color)
}
}
HICON App::trayBaseIcon(int width, int height) const
{
const auto resource = inputState == InputState::Active ? IDI_KSWITCHER : IDI_KSWITCHER_PAUSED;
return static_cast<HICON>(LoadImageW(instance, MAKEINTRESOURCEW(resource), IMAGE_ICON, width, height, LR_SHARED));
}
bool App::updateTray(DWORD action, bool notifyFile)
{
NOTIFYICONDATAW icon{sizeof(icon)};
@@ -1001,20 +989,17 @@ bool App::updateTray(DWORD action, bool notifyFile)
if (action == NIM_ADD) icon.uFlags |= NIF_MESSAGE;
icon.uCallbackMessage = TrayMessage;
const int width = GetSystemMetrics(SM_CXSMICON), height = GetSystemMetrics(SM_CYSMICON);
icon.hIcon = trayBaseIcon(width, height);
icon.hIcon = (HICON)LoadImageW(instance, MAKEINTRESOURCEW(IDI_KSWITCHER), IMAGE_ICON, width, height, LR_SHARED);
HICON badge{};
auto tip = localBuildTitle(L"KSwitcher");
const auto state = inputState.load();
tip += state == InputState::Active ? L" — Input processing active" :
state == InputState::Paused ? L" — Input processing paused" : L" — Pausing input processing…";
if (state == InputState::Active && trayInput.paired)
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"\nMouse & keyboard: ";
tip += L" — Mouse & keyboard: ";
if (trayInput.stopped) tip += L"connection stopped";
else if (!trayInput.online) tip += L"all paired PCs offline. Waiting for LAN discovery.";
else
@@ -1025,6 +1010,8 @@ 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);
@@ -1070,25 +1057,6 @@ 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;
@@ -1110,7 +1078,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 (" + *s.filesHotkey + L") is unavailable.";
if (!rollback) registrationWarning = L"The KSwitcher Files shortcut is unavailable. Choose another shortcut.";
return false;
}
if (filesHotkeyId) UnregisterHotKey(window, filesHotkeyId);
@@ -1123,24 +1091,14 @@ bool App::registerHotkeys(const Settings &s, bool rollback)
Bytes App::lanCommand(const Bytes &command)
{
if (!lanService) lanService = std::make_unique<LanService>(data,window,inputState != InputState::Active);
if (!lanService) lanService = std::make_unique<LanService>(data,window);
auto reply = lanService->command(command);
updateLanInputTimer();
if (lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr);
else KillTimer(window, 7);
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);
@@ -1217,7 +1175,7 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation)
}
predictor.configure(std::filesystem::path(executable()).parent_path() / L"dictionaries", s.autoLanguages);
}
if (inputState == InputState::Active && !registerHotkeys(s))
if (!registerHotkeys(s))
{
registerHotkeys(settings, true);
throw std::runtime_error(utf8(registrationWarning));
@@ -1241,7 +1199,7 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation)
catch (...)
{
}
if (inputState == InputState::Active) registerHotkeys(settings, true);
registerHotkeys(settings, true);
throw;
}
{
@@ -1285,7 +1243,7 @@ void App::reloadLayouts()
++inputVersion;
if (busy) diagnosticEvent(L"Input context changed: layouts reloaded version=" + std::to_wstring(inputVersion.load()));
}
if (inputState == InputState::Active) registerHotkeys(settings);
registerHotkeys(settings);
}
void App::clearHistory()
{
@@ -1695,8 +1653,7 @@ 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 inputState == InputState::Active && GetForegroundWindow() == target &&
windowLanguageProfileKey(profileSettings, target) == key; };
auto valid = [&] { return 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);
@@ -1707,7 +1664,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 (inputState != InputState::Active || ownKeyboardInput(key) || installingUpdate)
if (ownKeyboardInput(key) || installingUpdate)
return false;
if (key.vkCode < snippetKeys.size() && snippetKeys[key.vkCode])
{
@@ -1850,7 +1807,7 @@ void App::replayTyping()
}
LRESULT CALLBACK App::keyProc(int code, WPARAM wp, LPARAM lp)
{
if (code == HC_ACTION && current && current->inputState == InputState::Active && current->lanService &&
if (code == HC_ACTION && current && 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);
@@ -2105,7 +2062,7 @@ void App::dispatchMouseActions()
LRESULT CALLBACK App::mouseProc(int code, WPARAM wp, LPARAM lp)
{
if (code == HC_ACTION && current && current->inputState == InputState::Active)
if (code == HC_ACTION && current)
{
auto &app = *current;
const auto &mouse = *reinterpret_cast<const MSLLHOOKSTRUCT *>(lp);
@@ -2299,7 +2256,7 @@ void App::dispatch(int command)
}
void App::transform(int command, int snippet, size_t snippetLength, HWND snippetEditor)
{
if (installingUpdate || inputState != InputState::Active) return;
if (installingUpdate) return;
const auto attempt = ++transformAttempt;
const auto requestedAt = GetTickCount64();
HWND target = GetForegroundWindow();
@@ -2455,7 +2412,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
};
for (int i = 0; i < 8 && !modifiersReleased(); ++i)
Sleep(10);
if (!valid() || (!modifiersReleased() && command == AutoCorrect))
if (!modifiersReleased() && command == AutoCorrect)
return;
if (!modifiersReleased())
releaseModifiers();
@@ -2927,7 +2884,6 @@ 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;
@@ -3128,65 +3084,6 @@ 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;
@@ -3194,10 +3091,6 @@ 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…");
@@ -3228,7 +3121,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);
@@ -3254,9 +3147,6 @@ void App::trayMenu()
}
switch (cmd)
{
case ToggleInputProcessing:
toggleInputProcessing();
break;
case OpenFiles:
dispatch(OpenFiles);
break;
@@ -3457,7 +3347,6 @@ 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);
@@ -3502,8 +3391,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
case AutoCorrectMessage:
if (app->autoPending)
{
if (app->inputState == InputState::Active && !app->installingUpdate && !app->snippetTyping &&
app->settings.autoCorrect && app->inputVersion.load() == (uint64_t)wp)
if (!app->installingUpdate && !app->snippetTyping && app->settings.autoCorrect && app->inputVersion.load() == (uint64_t)wp)
app->transform(AutoCorrect);
else
app->replayTyping();
@@ -3512,7 +3400,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
case SnippetMessage:
if (app->snippetPending == (int)wp)
{
if (app->inputState == InputState::Active && !app->installingUpdate && app->inputVersion.load() == (uint64_t)lp &&
if (!app->installingUpdate && app->inputVersion.load() == (uint64_t)lp &&
(!app->snippetPendingEditor || GetForegroundWindow() == app->typingTarget))
app->transform(0, (int)wp, app->snippetPendingLength, app->snippetPendingEditor);
else
@@ -3601,22 +3489,9 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
}
case LanClipboardReadyMessage: app->receiveClipboard();return 0;
case LanInputReadyMessage:
app->pollLanInput();
if(app->lanService&&app->lanService->tickInput(!app->busy&&!app->suspended&&!app->hotkeyCapture))app->resetLanInput();
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();
@@ -3644,7 +3519,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
}
if (wp == 8)
{
if (app->inputState != InputState::Active || app->settings.appLanguageSets.empty() || app->busy || app->installingUpdate) return 0;
if (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);
@@ -3658,7 +3533,13 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
if (wp == 7)
{
app->pollLanInput();
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();
}
return 0;
}
if (wp == 6)
@@ -3696,7 +3577,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
PostMessageW(hwnd, WM_CLOSE, 0, 0);
return 0;
}
if (wp == 1 && app->inputState == InputState::Active && app->settings.awake)
if (app->settings.awake)
{
LASTINPUTINFO idle{sizeof(idle)};
if (GetLastInputInfo(&idle) && DWORD(GetTickCount() - idle.dwTime) >= 180000)
@@ -3792,6 +3673,8 @@ 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)
{
@@ -3803,28 +3686,28 @@ int App::execute()
});
settings.filesHotkey = conflict ? L"" : L"Ctrl+Alt+F";
}
if (!installInputHooks())
inputState = InputState::Paused;
else if (!registerHotkeys(settings) && settings.filesHotkey && !settings.filesHotkey->empty())
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 && inputState == InputState::Active) startBrowserChatMonitor();
if (!smoke) startBrowserChatMonitor();
if (!smoke && std::filesystem::exists(data / L"lan-pairing.bin"))
try { lanService = std::make_unique<LanService>(data,window,inputState != InputState::Active); }
try { lanService = std::make_unique<LanService>(data,window); }
catch (const std::exception &e) { report(L"LAN module: " + wide(e.what())); }
updateLanInputTimer();
if (lanService && lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr);
refreshTrayInput();
SetTimer(window, 1, 60000, nullptr);
if (!smoke) SetTimer(window, 6, 1000, nullptr);
if (!smoke && inputState == InputState::Active) SetTimer(window, 8, 250, nullptr);
if (!smoke) SetTimer(window, 8, 250, nullptr);
SetThreadExecutionState(ES_CONTINUOUS |
(settings.awake ? (ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED) : 0));
if (!registrationWarning.empty())
-9
View File
@@ -110,13 +110,6 @@ class App
void checkAutostartPath();
bool checkingAutostartPath{};
HHOOK keyboardHook{}, mouseHook{};
enum class InputState { Active, Pausing, Paused };
std::atomic<InputState> inputState{InputState::Active};
bool installInputHooks();
void releaseInputHooks();
void toggleInputProcessing();
void updateLanInputTimer();
void pollLanInput();
struct MousePress
{
HWND target{};
@@ -170,7 +163,6 @@ class App
bool trayRetryPending{};
LanInputConnections trayInput;
bool trayInputPulse{};
HICON trayBaseIcon(int width, int height) const;
bool updateTray(DWORD action, bool notifyFile = false);
void refreshTrayInput();
uint64_t transformAttempt{}, previousAttemptVersion{};
@@ -181,7 +173,6 @@ class App
HWND previousAttemptWindow{};
int previousAttemptCommand{}, repeatAttempts{};
std::vector<std::pair<int, Hotkey>> hookBindings;
std::vector<Hotkey> availableBeforePause;
Hotkey registeredFilesHotkey{};
int filesHotkeyId{};
HotkeyHook hotkeyHook;
+7 -39
View File
@@ -134,9 +134,6 @@ 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<bool> abortInput{false};
@@ -153,8 +150,7 @@ struct LanService::Impl
bool inputWorkerStopped{};
bool inputNeedsHelp{};
HWND inputWindow{};std::atomic<bool> inputNotification{false};
explicit Impl(const std::filesystem::path &root,HWND window,bool paused)
: path(root/L"lan-pairing.bin"),inputPaused(paused),inputWindow(window)
explicit Impl(const std::filesystem::path &root,HWND window) : path(root/L"lan-pairing.bin"),inputWindow(window)
{
if(std::filesystem::exists(path))
{
@@ -196,32 +192,13 @@ struct LanService::Impl
{
if(router)router->cancel(GetTickCount64());
router.reset();++inputConfiguration;
if(enabled&&shareInput&&!inputPaused){
if(enabled&&shareInput){
std::map<std::string,POINT> layout;for(auto &[peer,cell]:positions.items())if(trusted.contains(peer))layout[peer]={cell[0].get<LONG>(),cell[1].get<LONG>()};
router=std::make_unique<lan::InputMesh>(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();
@@ -467,7 +444,7 @@ struct LanService::Impl
if(peers.contains(target))send(socket,peers.at(target).address,packet);
});
clipboardActive=clipboard->active()||transfers->active();
if(shareInput&&!inputPaused)for(auto &[peer,entry]:trusted.items())
if(shareInput)for(auto &[peer,entry]:trusted.items())
{
const auto found=peers.find(peer);
const bool discovered=found!=peers.end()&&found->second.present(now);
@@ -493,13 +470,6 @@ struct LanService::Impl
}
}
std::vector<lan::RoutedInput> 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);
@@ -519,7 +489,6 @@ 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.");
@@ -533,7 +502,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&&!inputPaused&&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&&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);}
}
@@ -701,7 +670,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",inputPaused?"Input processing paused in the tray.":enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",!inputPaused&&enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
{"inputStatus",enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
{std::lock_guard inputLock(inputMutex);result["inputReady"]=inputReady;}
result["shareLogs"]=shareLogs;
result["files"]=Json::array();
@@ -729,7 +698,7 @@ struct LanService::Impl
return encoded(result);
}
};
LanService::LanService(const std::filesystem::path &path,HWND window,bool paused) : impl(std::make_unique<Impl>(path,window,paused)) {}
LanService::LanService(const std::filesystem::path &path,HWND window) : impl(std::make_unique<Impl>(path,window)) {}
LanService::~LanService()=default;
Bytes LanService::command(const Bytes &command) { return impl->command(command); }
bool LanService::clipboardEnabled()const
@@ -753,8 +722,7 @@ std::vector<LanClipboard> 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&&!impl->inputPaused;}
void LanService::setInputPaused(bool paused){impl->setInputPaused(paused);}
bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput;}
LanInputConnections LanService::inputConnections()const
{
std::lock_guard lock(impl->mutex);
+1 -2
View File
@@ -22,14 +22,13 @@ class LanService
struct Impl;
std::unique_ptr<Impl> impl;
public:
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr, bool inputPaused=false);
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr);
~LanService();
Bytes command(const Bytes &);
bool clipboardEnabled() const;
void publishClipboard(Bytes, const std::string &);
std::vector<LanClipboard> takeClipboard();
bool inputEnabled() const;
void setInputPaused(bool);
LanInputConnections inputConnections() const;
bool tickInput(bool allowEnter = true);
bool keyboard(const KBDLLHOOKSTRUCT &, bool down);
+14 -48
View File
@@ -1143,7 +1143,6 @@ struct SnippetView
App *app{};
std::vector<Snippet> snippets, saved;
int selection = -1;
HWND pickerOutline{};
};
struct SettingsView
{
@@ -1160,7 +1159,6 @@ struct SettingsView
SnippetView snippets;
};
bool snippetCommand(HWND, SnippetView *, WPARAM, bool embedded);
void snippetWindowPicked(HWND w, WPARAM target, LPARAM phase);
bool confirmSnippetClose(HWND, SnippetView *);
void refreshSnippetDraft(HWND, SnippetView *);
void updateSettingsState(HWND w, SettingsView *v);
@@ -1931,11 +1929,8 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
switch (msg)
{
case AppWindowPicked:
snippetWindowPicked(w, wp, lp);
return 0;
case WM_DRAWITEM:
if (wp == AppWindowPickerIcon || wp == AddMouseProfile || wp == RenameMouseProfile || wp == DeleteMouseProfile || wp == AddMouseEvent)
if (wp == AddMouseProfile || wp == RenameMouseProfile || wp == DeleteMouseProfile || wp == AddMouseEvent)
{
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
@@ -2111,10 +2106,6 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
}
return DefWindowProcW(w, msg, wp, lp);
}
void enableSnippetScopeControls(HWND w, bool enabled)
{
for (int id : {315, 316, 317, AppWindowPickerIcon}) EnableWindow(GetDlgItem(w, id), enabled);
}
void updateSnippetEditor(HWND w, SnippetView *v)
{
bool selected = v->selection >= 0 && v->selection < (int)v->snippets.size();
@@ -2131,7 +2122,7 @@ void updateSnippetEditor(HWND w, SnippetView *v)
CheckDlgButton(w, 314, restricted ? BST_CHECKED : BST_UNCHECKED);
for (int id : {302, 303, 311, 312, 313, 314})
EnableWindow(GetDlgItem(w, id), selected);
enableSnippetScopeControls(w, restricted);
for (int id : {315, 316, 317}) EnableWindow(GetDlgItem(w, id), selected && restricted);
}
void fillSnippets(HWND w, SnippetView *v)
{
@@ -2213,27 +2204,6 @@ bool confirmSnippetClose(HWND w, SnippetView *v)
if (choice == IDYES) saveSnippetDraft(w, v);
return choice == IDYES || choice == IDNO;
}
std::wstring snippetWindowExecutable(HWND window)
{
auto process = lower(processName(window));
return process.empty() ? L"" : process + L".exe";
}
void addSnippetApplication(HWND w, const std::wstring &app)
{
auto name = snippetAppName(app);
if (name.empty()) return;
auto current = value(w, 315);
std::wistringstream input(current);
std::wstring entry;
while (std::getline(input, entry, L','))
if (snippetAppName(entry) == name) return;
value(w, 315, current.empty() ? app : current + L", " + app);
}
void snippetWindowPicked(HWND w, WPARAM target, LPARAM phase)
{
if (phase == 1 && target)
addSnippetApplication(w, snippetWindowExecutable(reinterpret_cast<HWND>(target)));
}
bool snippetCommand(HWND w, SnippetView *v, WPARAM wp, bool embedded)
{
const int id = LOWORD(wp);
@@ -2243,12 +2213,19 @@ bool snippetCommand(HWND w, SnippetView *v, WPARAM wp, bool embedded)
if (id == 314)
{
bool restricted = IsDlgButtonChecked(w, 314) == BST_CHECKED;
enableSnippetScopeControls(w, restricted);
for (int field : {315, 316, 317}) EnableWindow(GetDlgItem(w, field), restricted);
return true;
}
if (id == 317)
{
addSnippetApplication(w, value(w, 316));
auto app = value(w, 316);
if (!app.empty())
{
auto current = value(w, 315);
std::wistringstream input(current); std::wstring entry;
while (std::getline(input, entry, L',')) if (snippetAppName(entry) == snippetAppName(app)) return true;
value(w, 315, current.empty() ? app : current + L", " + app);
}
return true;
}
if (id == 301 && HIWORD(wp) == LBN_SELCHANGE)
@@ -2328,9 +2305,8 @@ void createSnippetEditor(HWND w, SnippetView *view, bool embedded)
edit(w, 302, 232, top + 24, 452);
checkbox(w, L"Only in these &applications (unchecked: everywhere)", 314, 232, top + 55, 452);
edit(w, 315, 232, top + 83, 452);
control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL, 316, 232, top + 113, 296, 200);
button(w, L"Add a&pp", 317, 536, top + 110, 108);
createAppWindowPicker(w, AppWindowPickerIcon, 652, top + 110, 32, view->pickerOutline, createButtonTooltips(w));
control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL, 316, 232, top + 113, 330, 200);
button(w, L"Add a&pp", 317, 572, top + 110, 112);
label(w, L"Process names, comma-separated (for example chrome.exe)", 232, top + 144, 452);
label(w, L"&Replacement text", 232, top + 170, 452);
edit(w, 303, 232, top + 194, 452, textHeight, ES_MULTILINE | ES_WANTRETURN | ES_AUTOVSCROLL | WS_VSCROLL);
@@ -2349,11 +2325,7 @@ void createSnippetEditor(HWND w, SnippetView *view, bool embedded)
}
std::set<std::wstring> apps;
EnumWindows([](HWND candidate, LPARAM context)->BOOL {
if (IsWindowVisible(candidate))
{
auto name = snippetWindowExecutable(candidate);
if (!name.empty()) reinterpret_cast<std::set<std::wstring> *>(context)->insert(name);
}
if (IsWindowVisible(candidate)) { auto name = processName(candidate); if (!name.empty()) ((std::set<std::wstring>*)context)->insert(lower(name) + L".exe"); }
return TRUE;
}, (LPARAM)&apps);
for (const auto &name : apps) SendDlgItemMessageW(w, 316, CB_ADDSTRING, 0, (LPARAM)name.c_str());
@@ -2378,12 +2350,6 @@ LRESULT CALLBACK snippetProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (!v) return DefWindowProcW(w, msg, wp, lp);
try
{
if (msg == AppWindowPicked) { snippetWindowPicked(w, wp, lp); return 0; }
if (msg == WM_DRAWITEM && wp == AppWindowPickerIcon)
{
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if (msg == WM_COMMAND && snippetCommand(w, v, wp, false)) return 0;
if (msg == WM_CLOSE)
{
+4 -20
View File
@@ -177,27 +177,11 @@ LRESULT CALLBACK appWindowPickerProc(HWND button, UINT msg, WPARAM wp, LPARAM lp
if (msg == WM_NCDESTROY) RemoveWindowSubclass(button, appWindowPickerProc, id);
return DefSubclassProc(button, msg, wp, lp);
}
HWND createButtonTooltips(HWND owner)
void createAppWindowPicker(HWND w, int id, int x, int y, int width, HWND &outline)
{
return CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, owner, nullptr,
GetModuleHandleW(nullptr), nullptr);
}
void addButtonTooltip(HWND tips, HWND owner, int id, const wchar_t *text)
{
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND | TTF_SUBCLASS, owner,
reinterpret_cast<UINT_PTR>(GetDlgItem(owner, id))};
tool.lpszText = const_cast<wchar_t *>(text);
SendMessageW(tips, TTM_ADDTOOLW, 0, reinterpret_cast<LPARAM>(&tool));
}
constexpr int AppWindowPickerIcon = 753;
void createAppWindowPicker(HWND w, int id, int x, int y, int width, HWND &outline, HWND tips = nullptr)
{
const bool icon = id == AppWindowPickerIcon;
HWND picker = control(w, L"BUTTON", icon ? L"Drag to application window" : L" ⊕ Drag to window",
WS_TABSTOP | (icon ? BS_OWNERDRAW : BS_PUSHBUTTON | BS_LEFT), id, x, y, width, 28);
SetWindowSubclass(picker, appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&outline));
if (tips) addButtonTooltip(tips, w, id, L"Drag to an application window");
control(w, L"BUTTON", L" ⊕ Drag to window", WS_TABSTOP | BS_PUSHBUTTON | BS_LEFT,
id, x, y, width, 28);
SetWindowSubclass(GetDlgItem(w, id), appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&outline));
}
LRESULT CALLBACK appLanguagesProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
+28 -12
View File
@@ -272,6 +272,7 @@ struct MouseProfileEditor
constexpr int ActionApplications = 748, ActionApplicationName = 749, AddActionApp = 750, RemoveActionApp = 751;
constexpr int BrowseActionApp = 752;
constexpr int PickActionApp = 753;
constexpr int AddMouseProfile = 754, MouseProfileName = 755;
void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
@@ -294,7 +295,7 @@ void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
FrameRect(item.hDC, &folder, ink);
FillRect(item.hDC, &tab, ink);
}
else if (item.CtlID == AppWindowPickerIcon)
else if (item.CtlID == PickActionApp)
{
RECT target{x - half, y - half, x + half + 1, y + half + 1};
RECT horizontal{x - half - weight, y, x + half + weight + 1, y + 1};
@@ -343,6 +344,14 @@ void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
}
}
void addActionApplicationTooltip(HWND tips, HWND editor, int id, const wchar_t *text)
{
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND | TTF_SUBCLASS, editor,
reinterpret_cast<UINT_PTR>(GetDlgItem(editor, id))};
tool.lpszText = const_cast<wchar_t *>(text);
SendMessageW(tips, TTM_ADDTOOLW, 0, reinterpret_cast<LPARAM>(&tool));
}
void fillActionApplications(HWND w, const MouseProfileEditor &editor)
{
SendDlgItemMessageW(w, ActionApplications, LB_RESETCONTENT, 0, 0);
@@ -667,7 +676,7 @@ LRESULT CALLBACK mouseProfileNameProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
}
return 0;
}
if (msg == WM_DRAWITEM && (wp == AddActionApp || wp == RemoveActionApp || wp == BrowseActionApp || wp == AppWindowPickerIcon))
if (msg == WM_DRAWITEM && (wp == AddActionApp || wp == RemoveActionApp || wp == BrowseActionApp || wp == PickActionApp))
{
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
@@ -766,13 +775,18 @@ void showMouseProfileName(HWND owner, SettingsView &view, bool renaming)
control(w, L"BUTTON", L"&Remove application", WS_TABSTOP | BS_OWNERDRAW, RemoveActionApp, 430, 100, 32, 28);
HWND appName = edit(w, ActionApplicationName, 18, 207, 324);
SendMessageW(appName, EM_SETCUEBANNER, FALSE, reinterpret_cast<LPARAM>(L"Application executable (e.g. chrome.exe)"));
HWND tips = createButtonTooltips(w);
createAppWindowPicker(w, AppWindowPickerIcon, 350, 205, 32, editor->pickerOutline, tips);
HWND picker = control(w, L"BUTTON", L"Drag to application window", WS_TABSTOP | BS_OWNERDRAW,
PickActionApp, 350, 205, 32, 28);
SetWindowSubclass(picker, appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&editor->pickerOutline));
control(w, L"BUTTON", L"&Browse for application", WS_TABSTOP | BS_OWNERDRAW, BrowseActionApp, 390, 205, 32, 28);
control(w, L"BUTTON", L"Add a&pplication", WS_TABSTOP | BS_OWNERDRAW, AddActionApp, 430, 205, 32, 28);
addButtonTooltip(tips, w, RemoveActionApp, L"Remove application");
addButtonTooltip(tips, w, AddActionApp, L"Add application");
addButtonTooltip(tips, w, BrowseActionApp, L"Browse for an executable or shortcut");
HWND tips = CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, w, nullptr,
view.app->instance, nullptr);
addActionApplicationTooltip(tips, w, RemoveActionApp, L"Remove application");
addActionApplicationTooltip(tips, w, AddActionApp, L"Add application");
addActionApplicationTooltip(tips, w, BrowseActionApp, L"Browse for an executable or shortcut");
addActionApplicationTooltip(tips, w, PickActionApp, L"Drag to an application window");
fillActionApplications(w, *editor);
control(w, L"BUTTON", renaming ? L"&Apply" : L"&Add", WS_TABSTOP | BS_DEFPUSHBUTTON, IDOK, 248, 251, 100, 28);
button(w, L"Cancel", IDCANCEL, 362, 251, 100);
@@ -1032,11 +1046,13 @@ void createMousePage(HWND w, SettingsView &view)
control(w, L"BUTTON", L"Delete profile", WS_TABSTOP | BS_OWNERDRAW, DeleteMouseProfile, profilesRight - 80, 61, 24, 24);
control(w, L"BUTTON", L"Edit profile", WS_TABSTOP | BS_OWNERDRAW, RenameMouseProfile, profilesRight - 52, 61, 24, 24);
control(w, L"BUTTON", L"Add profile", WS_TABSTOP | BS_OWNERDRAW, AddMouseProfile, profilesRight - 24, 61, 24, 24);
HWND tips = createButtonTooltips(w);
addButtonTooltip(tips, w, AddMouseProfile, L"Add profile");
addButtonTooltip(tips, w, RenameMouseProfile, L"Edit profile");
addButtonTooltip(tips, w, DeleteMouseProfile, L"Delete profile");
addButtonTooltip(tips, w, AddMouseEvent, L"Add mouse event");
HWND tips = CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, w, nullptr,
view.app->instance, nullptr);
addActionApplicationTooltip(tips, w, AddMouseProfile, L"Add profile");
addActionApplicationTooltip(tips, w, RenameMouseProfile, L"Edit profile");
addActionApplicationTooltip(tips, w, DeleteMouseProfile, L"Delete profile");
addActionApplicationTooltip(tips, w, AddMouseEvent, L"Add mouse event");
constexpr int listTop = 90, listHeight = 224;
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES};
InitCommonControlsEx(&controls);
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.130";
inline constexpr wchar_t AppVersion[] = L"0.6.127";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+32 -50
View File
@@ -22,36 +22,6 @@ void require(bool ok, const char *message)
if (!ok) throw std::runtime_error(message);
++passed;
}
std::wstring pickTestApplication(HWND picker, bool cancel = false)
{
RECT dialogBounds{};
GetWindowRect(GetParent(picker), &dialogBounds);
MONITORINFO monitor{sizeof(monitor)};
require(GetMonitorInfoW(MonitorFromWindow(picker, MONITOR_DEFAULTTONEAREST), &monitor),
"monitor work area available");
const auto targetX = std::clamp(dialogBounds.left + 32, monitor.rcWork.left, monitor.rcWork.right - 120);
const auto targetY = std::clamp(dialogBounds.top + 100, monitor.rcWork.top, monitor.rcWork.bottom - 48);
HWND target = CreateWindowExW(WS_EX_TOPMOST | WS_EX_NOACTIVATE, L"EDIT", L"Picker fixture",
WS_POPUP | WS_VISIBLE, targetX, targetY, 120, 48,
nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
require(picker && target, "window picker and target available");
POINT drop{targetX + 1, targetY + 1};
require(GetAncestor(WindowFromPoint(drop), GA_ROOT) == target, "fixture window is under the drop point");
ScreenToClient(picker, &drop);
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
require(GetCapture() == picker, "window picker captures drag");
SendMessageW(picker, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(drop.x, drop.y));
HWND outline = findTestWindow(L"KSwitcher.AppPickerOutline", nullptr);
RECT outlineBounds{}, targetBounds{};
require(IsWindowVisible(outline) && GetWindowRect(outline, &outlineBounds) &&
GetWindowRect(target, &targetBounds) && EqualRect(&outlineBounds, &targetBounds), "drag highlights the target window");
if (cancel) SendMessageW(picker, WM_KEYDOWN, VK_ESCAPE, 0);
else SendMessageW(picker, WM_LBUTTONUP, 0, MAKELPARAM(drop.x, drop.y));
require(!IsWindow(outline) && GetCapture() != picker, "finishing the drag clears the outline and releases capture");
auto pickedApp = ks::applicationName(ks::processName(target));
DestroyWindow(target);
return pickedApp;
}
void lanWindowLayoutChecks(const std::filesystem::path &root)
{
const std::string peer(32,'b');
@@ -377,8 +347,36 @@ int main(int argc,char **argv)
SendDlgItemMessageW(dialog, 722, LB_SETSEL, TRUE, -1);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(722, LBN_SELCHANGE), 0);
HWND picker = GetDlgItem(dialog, 728);
pickTestApplication(picker, true);
auto pickedApp = pickTestApplication(picker);
RECT dialogBounds{};
GetWindowRect(dialog, &dialogBounds);
MONITORINFO monitor{sizeof(monitor)};
require(GetMonitorInfoW(MonitorFromWindow(dialog, MONITOR_DEFAULTTONEAREST), &monitor),
"monitor work area available");
const auto targetX = std::clamp(dialogBounds.left + 32, monitor.rcWork.left, monitor.rcWork.right - 120);
const auto targetY = std::clamp(dialogBounds.top + 100, monitor.rcWork.top, monitor.rcWork.bottom - 48);
HWND target = CreateWindowExW(WS_EX_TOPMOST | WS_EX_NOACTIVATE, L"EDIT", L"Picker fixture",
WS_POPUP | WS_VISIBLE, targetX, targetY, 120, 48,
nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
require(picker && target, "window picker and target available");
POINT drop{targetX + 1, targetY + 1};
require(GetAncestor(WindowFromPoint(drop), GA_ROOT) == target, "fixture window is under the drop point");
ScreenToClient(picker, &drop);
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
require(GetCapture() == picker, "window picker captures drag");
SendMessageW(picker, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(drop.x, drop.y));
HWND outline = findTestWindow(L"KSwitcher.AppPickerOutline", nullptr);
RECT outlineBounds{}, targetBounds{};
require(IsWindowVisible(outline) && GetWindowRect(outline, &outlineBounds) &&
GetWindowRect(target, &targetBounds) && EqualRect(&outlineBounds, &targetBounds), "drag highlights the target window");
SendMessageW(picker, WM_KEYDOWN, VK_ESCAPE, 0);
require(!IsWindow(outline) && GetCapture() != picker, "Escape clears the outline and releases capture");
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
SendMessageW(picker, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(drop.x, drop.y));
outline = findTestWindow(L"KSwitcher.AppPickerOutline", nullptr);
SendMessageW(picker, WM_LBUTTONUP, 0, MAKELPARAM(drop.x, drop.y));
require(!IsWindow(outline), "dropping clears the outline");
auto pickedApp = ks::applicationName(ks::processName(target));
DestroyWindow(target);
auto pickedRow = SendDlgItemMessageW(dialog, 720, LB_FINDSTRINGEXACT, -1, (LPARAM)pickedApp.c_str());
require(GetCapture() != picker && pickedRow >= 0 &&
SendDlgItemMessageW(dialog, 720, LB_GETCURSEL, 0, 0) == pickedRow, "dropping on a window selects its executable");
@@ -437,11 +435,8 @@ int main(int argc,char **argv)
SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0);
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
require(IsDlgButtonChecked(snippets,314)==BST_UNCHECKED, "old snippet shows everywhere");
HWND scopePicker = GetDlgItem(snippets, 753);
require(IsWindowVisible(scopePicker) && !IsWindowEnabled(scopePicker), "global snippet disables the window picker");
CheckDlgButton(snippets,314,BST_CHECKED);
SendMessageW(snippets,WM_COMMAND,314,0);
require(IsWindowEnabled(scopePicker), "restricting the snippet enables the window picker");
SetDlgItemTextW(snippets,315,L"Notepad.exe");
auto secondApp = SendDlgItemMessageW(snippets,316,CB_ADDSTRING,0,(LPARAM)L"MS-Teams.EXE");
SendDlgItemMessageW(snippets,316,CB_SETCURSEL,secondApp,0);
@@ -450,17 +445,8 @@ int main(int argc,char **argv)
wchar_t appList[128]{};
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList)==L"Notepad.exe, MS-Teams.EXE", "Add app appends a second application without duplicates");
pickTestApplication(scopePicker, true);
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList)==L"Notepad.exe, MS-Teams.EXE", "cancelling the picker preserves the snippet scope");
auto pickedProcess = pickTestApplication(scopePicker);
pickTestApplication(scopePicker);
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList) == L"Notepad.exe, MS-Teams.EXE, " + pickedProcess + L".exe",
"dropping on a window appends its process once to the existing snippet scope");
const std::vector<std::wstring> savedScope{L"notepad", L"ms-teams", pickedProcess};
SendMessageW(snippets,WM_COMMAND,318,0);
require(IsWindow(snippets) && app.settings.snippets[0].apps==savedScope, "inline snippet editor saves selected applications");
require(IsWindow(snippets) && app.settings.snippets[0].apps==std::vector<std::wstring>{L"notepad",L"ms-teams"}, "inline snippet editor saves selected applications");
require(!saveEnabled() && status()==L"No unsaved settings.","separately saved snippet edit leaves Settings clean");
RedrawWindow(snippets,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
RECT snippetRect{};GetClientRect(snippets,&snippetRect);
@@ -474,12 +460,8 @@ int main(int argc,char **argv)
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
require(IsDlgButtonChecked(snippets,314)==BST_CHECKED, "scope restored when reopening editor");
SetDlgItemTextW(snippets,315,L"chrome.exe");
pickTestApplication(GetDlgItem(snippets, 753));
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList) == L"chrome.exe, " + pickedProcess + L".exe",
"standalone snippet editor adds the dropped application");
SendMessageW(snippets,WM_COMMAND,IDCANCEL,0);
require(app.settings.snippets[0].apps==savedScope, "cancel preserves existing scope");
require(app.settings.snippets[0].apps==std::vector<std::wstring>{L"notepad",L"ms-teams"}, "cancel preserves existing scope");
ks::showSettings(app);parent=app.settingsWindow;
SendMessageW(parent,WM_COMMAND,262,0);
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
-54
View File
@@ -7,7 +7,6 @@
#include <commctrl.h>
#include <iostream>
#include <cmath>
#include "input_pause.h"
static int settingsCloseChoice = IDCANCEL;
static int settingsClosePrompts = 0;
static void CALLBACK answerSettingsClose(HWND, UINT, UINT_PTR, DWORD)
@@ -28,45 +27,6 @@ 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<App *>(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 == ProbeTrayIcon) return trayIconMatchesInput(app.trayBaseIcon(16, 16), wp != 0);
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<DWORD_PTR>(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<Snippet> &snippets) {
a.settings.snippets=snippets; a.settings.autoCorrect=false; a.busy=false;
a.snippetPending=-1; a.typingTarget=nullptr; a.snippetTyping=false;
@@ -209,20 +169,6 @@ 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, {});
-147
View File
@@ -1,147 +0,0 @@
#include "app.h"
#include "input_pause.h"
#include <iostream>
namespace {
void require(bool result, const char *message)
{
if (!result) throw std::runtime_error(message);
}
template<class Predicate> 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<HMENU>(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);
}
}
bool trayIconMatchesInput(HICON icon, bool active)
{
HDC dc = CreateCompatibleDC(nullptr);
HBITMAP bitmap = CreateBitmap(16, 16, 1, 32, nullptr);
bool matches = false;
if (dc && bitmap) {
const auto previous = SelectObject(dc, bitmap);
if (icon && DrawIconEx(dc, 0, 0, icon, 16, 16, 0, nullptr, DI_NORMAL)) {
const auto tile = GetPixel(dc, 2, 8);
const auto white = RGB(255, 255, 255);
const auto gap = GetPixel(dc, 8, 8);
// The active keycap is purple. The pause glyph has two white strokes with a gap.
matches = active ? GetBValue(tile) > GetRValue(tile) + 70 :
GetPixel(dc, 5, 8) == white && GetPixel(dc, 10, 8) == white &&
GetRValue(gap) < 160 && std::abs(GetBValue(gap) - GetRValue(gap)) < 32;
}
SelectObject(dc, previous);
}
if (bitmap) DeleteObject(bitmap);
if (dc) DeleteDC(dc);
return matches;
}
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");
require(query(resident, ProbeTrayIcon, TRUE), "active tray icon missing at startup");
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(query(resident, ProbeTrayIcon), "pause bars missing after pause");
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(query(resident, ProbeTrayIcon), "Files shortcut conflict cleared the pause icon");
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(query(resident, ProbeTrayIcon), "hook shortcut conflict cleared the pause icon");
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(query(resident, ProbeTrayIcon, TRUE), "active tray icon missing after resume");
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;
}
-7
View File
@@ -1,7 +0,0 @@
#pragma once
#include <windows.h>
inline constexpr UINT ProbeInputState = WM_APP + 200;
inline constexpr UINT ProbeTrayIcon = WM_APP + 201;
bool trayIconMatchesInput(HICON icon, bool active);
int testInputPause();
+1 -14
View File
@@ -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},{"shareInput",true},{"trusted",{
const auto saved=Json{{"version",1},{"id",a},{"enabled",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,19 +140,6 @@ 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")
{
-20
View File
@@ -45,26 +45,6 @@ frames[-1].save(root / 'kswitcher-files.ico', sizes=icon_sizes, append_images=fr
if args.files_only:
raise SystemExit
# Keep the two pause bars aligned to whole pixels at each tray size.
def draw_paused_icon(size):
scale = 8
tile = Image.new('RGBA', (size * scale, size * scale))
unit = size * scale / 32
ImageDraw.Draw(tile).rounded_rectangle(
(unit, unit, 31 * unit - 1, 31 * unit - 1), radius=7 * unit, fill='#575E68')
tile = tile.resize((size, size), Image.Resampling.LANCZOS)
draw = ImageDraw.Draw(tile)
top = round(size / 4)
left = round(size / 4)
width = round(size * 3 / 16)
for x in (left, size - left - width):
draw.rectangle((x, top, x + width - 1, size - top - 1), fill='white')
return tile
paused_frames = [draw_paused_icon(size) for size, _ in icon_sizes]
paused_frames[-1].save(root / 'kswitcher-paused.ico', sizes=icon_sizes, append_images=paused_frames[:-1])
# Geometric K: white stem/upper arm, mint lower arm on an indigo keycap.
polygons = [('#FFFFFF', [(8, 7), (12, 7), (12, 25), (8, 25)]),
('#FFFFFF', [(11, 15), (22, 6), (25, 9), (14, 18)]),