Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
55405f79db |
No files matched your search
+3
-7
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.130 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.6.125 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>")
|
||||
|
||||
@@ -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
|
||||
@@ -483,11 +461,10 @@ Recognition uses Chrome accessibility: the address bar and active document must
|
||||
|
||||
### Snippet autocomplete — v0.6.69
|
||||
|
||||
**Enter** accepts a single visible suggestion directly. When several suggestions
|
||||
are visible, navigate the list with **↑ / ↓** to select one for **Enter**.
|
||||
|
||||
**Українською.** **Enter** одразу підтверджує єдину видиму підказку. Якщо
|
||||
підказок кілька, виберіть потрібну стрілками **↑ / ↓**, а тоді натисніть **Enter**.
|
||||
Starting with v0.6.71, **Enter** accepts a suggestion after you navigate
|
||||
the list with **↑ / ↓**. Without arrow navigation, **Enter** goes to the
|
||||
editor. З v0.6.71 **Enter** після вибору стрілками вставляє сніпет. Без
|
||||
переміщення списком **Enter** надходить до редактора.
|
||||
|
||||
Starting with v0.6.70, suggestions open at the text caret. If the editor
|
||||
provides no caret position, you can still type the complete trigger to
|
||||
@@ -518,33 +495,33 @@ ChatGPT and Codex desktop editors use paced selection for snippet triggers. If o
|
||||
|
||||
### Snippet macros
|
||||
|
||||
In **Settings → Snippets**, type macros into a snippet's replacement text. **Macro help…** sits beside the marker buttons below the editor, with **Save snippets** at the right. KSwitcher runs each macro between text segments in the listed order. A leading macro runs after the first text segment, as in earlier versions. A snippet needs some replacement text.
|
||||
In **Settings → Snippets**, type macros into a snippet's replacement text. **Macro help…** sits beside the marker buttons below the editor, with **Save snippets** at the right. KSwitcher verifies each inserted text segment before running the macros that follow it. A leading macro runs after the first text segment, as in earlier versions. A snippet needs some replacement text.
|
||||
|
||||
- `{{shift}}`, `{{alt}}` and `{{tab}}` tap individual keys. Key names are case-insensitive. Letters, digits, `F1`–`F24`, navigation and editing keys also work.
|
||||
- `{{altr}}+{{ctrl}}` holds both keys together. Join key markers with `+` without spaces and put modifiers before the final key, as in `{{ctrl}}+{{shift}}+{{A}}`. Use `l` or `r` after `ctrl`, `alt`, `shift` or `win` to select a side. The unsuffixed names use the left keys.
|
||||
- `rider .{pause:50}{enter}` inserts `rider .`, waits 50 milliseconds, then presses Enter. One pause can be 0–10,000 milliseconds. Use `{{return}}` for Enter inside a chord, as in `{{ctrl}}+{{return}}`.
|
||||
- Write `{{cursor}}`, `{{enter}}`, `{{pause:50}}` or `{{{shift}}}` to insert the corresponding marker literally.
|
||||
|
||||
**Українською.** Додавай макроси в текст заміни в **Settings → Snippets**. **Macro help…** розташована поруч із кнопками маркерів під редактором, а **Save snippets** — праворуч. KSwitcher виконує макроси між частинами тексту за порядком запису. Макрос на початку, як і раніше, виконується після першої частини тексту. Сніпет має містити текст заміни.
|
||||
**Українською.** Додавай макроси в текст заміни в **Settings → Snippets**. **Macro help…** розташована поруч із кнопками маркерів під редактором, а **Save snippets** — праворуч. KSwitcher перевіряє кожну вставлену частину тексту перед виконанням наступних макросів. Макрос на початку, як і раніше, виконується після першої частини тексту. Сніпет має містити текст заміни.
|
||||
|
||||
- `{{shift}}`, `{{alt}}` і `{{tab}}` натискають окремі клавіші. Регістр назви клавіші не має значення. Також підтримуються літери, цифри, `F1`–`F24`, клавіші навігації та редагування.
|
||||
- `{{altr}}+{{ctrl}}` затискає обидві клавіші разом. З’єднуй маркери знаком `+` без пробілів і став модифікатори перед основною клавішею, як у `{{ctrl}}+{{shift}}+{{A}}`. Суфікси `l` і `r` у назвах `ctrl`, `alt`, `shift` і `win` вибирають ліву й праву клавіші. Без суфікса використовується ліва.
|
||||
- `rider .{pause:50}{enter}` вставляє `rider .`, чекає 50 мілісекунд і натискає Enter. Допустимий діапазон однієї паузи — від 0 до 10 000 мілісекунд. Для Enter у комбінації використовуй `{{return}}`, наприклад `{{ctrl}}+{{return}}`.
|
||||
- Записуй `{{cursor}}`, `{{enter}}`, `{{pause:50}}` або `{{{shift}}}`, щоб вставити відповідний маркер як звичайний текст.
|
||||
|
||||
For example, `$skill-name{pause:500}{enter} Draft text{cursor}` types the token, waits 500 milliseconds, presses Enter once, then types the draft. The focused application handles Enter. Each `{enter}` sends a separate press.
|
||||
In Codex, `$skill-name{pause:500}{enter} Draft text{cursor}` selects the matching skill suggestion and then inserts the draft. Further Enter markers at the same position have no effect. If the suggestion cannot be verified, expansion stops at the skill name.
|
||||
|
||||
Наприклад, `$skill-name{pause:500}{enter} Текст чернетки{cursor}` вводить назву, чекає 500 мілісекунд, натискає Enter один раз і вводить чернетку. Enter обробляє програма у фокусі. Кожен `{enter}` надсилає окреме натискання.
|
||||
У Codex `$skill-name{pause:500}{enter} Текст чернетки{cursor}` вибирає відповідний скіл зі списку підказок і далі вставляє чернетку. Повторні маркери Enter в тій самій позиції не спрацьовують. Якщо підказку не вдалося перевірити, розгортання зупиняється на назві скіла.
|
||||
|
||||
### 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
|
||||
@@ -583,7 +560,7 @@ Scopes are saved with snippets and included in manual import/export and synchron
|
||||
repeat-conversion state and does not switch the Windows layout.
|
||||
- Case cycling, Russian/Ukrainian transliteration, verified undo and repeated conversion.
|
||||
- Text snippets across layouts, multiline insertion and a verified `{cursor}` position;
|
||||
macros run between text segments, before buffered typing resumes.
|
||||
macros run between verified text segments, before buffered typing resumes.
|
||||
Automatic correction is suppressed during snippet expansion and for typing buffered by that expansion; the global setting is preserved.
|
||||
If the trigger cannot be verified after the copy attempts, it is preserved, queued typing resumes,
|
||||
and no key actions are sent. Snippets are stored as plaintext settings, as in [Typlo](https://github.com/bitcodepro/Typlo).
|
||||
|
||||
+1
-41
@@ -1,46 +1,6 @@
|
||||
# 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.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Якщо у списку підказок є один збіг, Enter одразу розгортає сніпет. KSwitcher перехоплює це натискання. Якщо збігів кілька, виберіть потрібний стрілками й підтвердьте через Enter.
|
||||
|
||||
## v0.6.126 — 2026-11-21 (withdrawn / відкликано)
|
||||
|
||||
Snippet macros send the configured keys at the position where they appear. `$skill{pause:500}{enter} Draft text` types the name, waits 500 milliseconds, presses Enter once, then types the remaining text. The focused application handles each key.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Макроси сніпетів натискають задані клавіші в указаній позиції. `$skill{pause:500}{enter} Текст` вводить назву, чекає 500 мілісекунд, один раз натискає Enter і вводить решту тексту. Кожне натискання обробляє програма у фокусі.
|
||||
|
||||
## v0.6.125 — 2026-11-21 (withdrawn / відкликано)
|
||||
## v0.6.125 — 2026-11-21
|
||||
|
||||
Snippet macros between text segments run before the next segment is inserted. In Codex, `$skill{pause:500}{enter} Draft text` selects the matching skill suggestion and leaves the following text in the composer. Extra Enter markers at the same selection point do not submit the draft. Expansion stops when the suggestion cannot be verified.
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
28f0dc723444344dbc9bf363077c0e7d00a6089e714f8937b096c29c55db6a01 KSwitcher-win-x64.zip
|
||||
c0418b28d5bbfa6ac7c4ff8b76addc58e5b6abdf1c192895014a35d92424e13d KSwitcher-win-x64.zip
|
||||
+13
-13
@@ -1,24 +1,25 @@
|
||||
{
|
||||
"version": "0.6.125",
|
||||
"files": [
|
||||
{
|
||||
"path": "KSwitcher.exe",
|
||||
"size": 2508800,
|
||||
"sha256": "bacf777a44cc1859fcdc07f411f18f065801ed07c6673719f177ae72f4247c0e"
|
||||
"size": 2497536,
|
||||
"sha256": "c66a11c095c15a7d80d15ca0e19adeb284db65134babb3b403998d6756444b3d"
|
||||
},
|
||||
{
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"size": 2478080,
|
||||
"sha256": "1b072b84be7e862ef94271bc300908f8e0525c57890867d21bca3d2a396252d8"
|
||||
"size": 2462720,
|
||||
"sha256": "bac341c5ef616ea90462e70f82e25e4b2a5550019d1bd8d729d311e41583f64a"
|
||||
},
|
||||
{
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"size": 3077120,
|
||||
"sha256": "088a4db4035c15393c908271d80897bdb19da3405c28f4b7ec8af9829895a569"
|
||||
"size": 3063808,
|
||||
"sha256": "c1b0c9aec507110d6949736b7e2beb9f83065c4153d53a4f0f1bb5f110f811a6"
|
||||
},
|
||||
{
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"size": 4377600,
|
||||
"sha256": "6dace995d53dff51d0b752a5327092346f8be4b4801ccf12db38e3cc9e30e5ce"
|
||||
"size": 4377088,
|
||||
"sha256": "04db22229e93f01a482d3040b21854cd88ceb5dd6c84e3ec5928c2d3e5bb3099"
|
||||
},
|
||||
{
|
||||
"path": "WebView2Loader.dll",
|
||||
@@ -107,8 +108,8 @@
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"size": 101852,
|
||||
"sha256": "e180efa5da9672111d8649422b661f55c85f33e458aba9e1b95060ea7c95ebe2"
|
||||
"size": 99184,
|
||||
"sha256": "2c37fa1783e45c8ea874801aa1ac74a9b02bf75690c7ae6c9aa0184215bf4604"
|
||||
},
|
||||
{
|
||||
"path": "LAN-PREVIEW.md",
|
||||
@@ -153,7 +154,7 @@
|
||||
{
|
||||
"path": "tools/StayHere.exe",
|
||||
"size": 133120,
|
||||
"sha256": "d18778c437b3dda8258babb9db48a94d275fbe7272241f08e0da96173595abd9"
|
||||
"sha256": "658052ec21e9a5619339f6036d11db8c75d8065666669245af123c5d906a7846"
|
||||
},
|
||||
{
|
||||
"path": "tools/StayHere-README.md",
|
||||
@@ -161,6 +162,5 @@
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
|
||||
}
|
||||
],
|
||||
"schema": 1,
|
||||
"version": "0.6.130"
|
||||
"schema": 1
|
||||
}
|
||||
@@ -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
@@ -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,125,0
|
||||
PRODUCTVERSION 0,6,125,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.125"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 13 KiB |
@@ -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
|
||||
+112
-223
@@ -8,6 +8,7 @@
|
||||
#include "configuration.h"
|
||||
#include "diagnostics.h"
|
||||
#include "paste_probe.h"
|
||||
#include "snippet_skill.h"
|
||||
#include "utilities.h"
|
||||
#include "screenshot_notifications.h"
|
||||
#include <algorithm>
|
||||
@@ -143,16 +144,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()
|
||||
{
|
||||
@@ -243,28 +234,6 @@ std::wstring newlines(std::wstring text)
|
||||
}
|
||||
return out;
|
||||
}
|
||||
bool canTypeSnippetText(const std::wstring &text)
|
||||
{
|
||||
return std::all_of(text.begin(), text.end(), [](wchar_t ch) { return ch >= L' ' && ch != L'\x7f'; });
|
||||
}
|
||||
bool typeSnippetText(const std::wstring &text, const std::function<bool()> &valid)
|
||||
{
|
||||
constexpr size_t batchSize = 64;
|
||||
for (size_t offset = 0; offset < text.size(); offset += batchSize)
|
||||
{
|
||||
std::vector<INPUT> inputs;
|
||||
for (wchar_t ch : std::wstring_view(text).substr(offset, batchSize))
|
||||
for (DWORD flags : {DWORD{0}, DWORD{KEYEVENTF_KEYUP}})
|
||||
{
|
||||
auto input = keyboardInput(0, flags | KEYEVENTF_UNICODE);
|
||||
input.ki.wScan = ch;
|
||||
inputs.push_back(input);
|
||||
}
|
||||
if (!valid() || SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT)) != inputs.size())
|
||||
return false;
|
||||
}
|
||||
return valid();
|
||||
}
|
||||
// Every transaction checks input, foreground and clipboard ownership before replacing text.
|
||||
class Transaction
|
||||
{
|
||||
@@ -727,6 +696,14 @@ class Transaction
|
||||
check();
|
||||
return true;
|
||||
}
|
||||
bool insertSnippetText(const std::wstring &text, bool typeSkill)
|
||||
{
|
||||
if (!typeSkill) return paste(textClip(text));
|
||||
check();
|
||||
if (!valid() || !typeSnippetSkill(text)) return false;
|
||||
Sleep(75);
|
||||
return valid();
|
||||
}
|
||||
bool nativeSelectionIs(const std::wstring &original) const
|
||||
{
|
||||
if (!valid()) return false;
|
||||
@@ -806,7 +783,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 +793,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 +967,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 +976,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 +997,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 +1044,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 +1065,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 +1078,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 +1162,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 +1186,7 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation)
|
||||
catch (...)
|
||||
{
|
||||
}
|
||||
if (inputState == InputState::Active) registerHotkeys(settings, true);
|
||||
registerHotkeys(settings, true);
|
||||
throw;
|
||||
}
|
||||
{
|
||||
@@ -1285,7 +1230,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()
|
||||
{
|
||||
@@ -1613,8 +1558,7 @@ void App::selectSnippet(size_t row)
|
||||
}
|
||||
bool App::handleSnippetKey(DWORD vk, UINT mods)
|
||||
{
|
||||
const bool accept = vk == VK_TAB ||
|
||||
(vk == VK_RETURN && (snippetNavigated || snippetMatches.size() == 1));
|
||||
const bool accept = vk == VK_TAB || (vk == VK_RETURN && snippetNavigated);
|
||||
if (mods || (!accept && vk != VK_UP && vk != VK_DOWN && vk != VK_ESCAPE) ||
|
||||
!snippetPopup || !IsWindowVisible(snippetPopup) || !snippetPopupCurrent())
|
||||
return false;
|
||||
@@ -1695,8 +1639,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 +1650,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 +1793,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 +2048,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 +2242,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 +2398,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();
|
||||
@@ -2525,6 +2468,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
|
||||
L" id=" + std::to_wstring(attempt));
|
||||
bool automatic = false;
|
||||
Template snippetTemplate;
|
||||
bool codexSnippet = false;
|
||||
if (command == AutoCorrect)
|
||||
{
|
||||
// The editor must select the complete previous word. Unlike manual
|
||||
@@ -2595,6 +2539,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
|
||||
const auto &sn = config.snippets[snippet];
|
||||
const auto process = lower(processName(target));
|
||||
if (!snippetAppPriority(sn, process)) return;
|
||||
codexSnippet = process == L"codex" || process == L"chatgpt";
|
||||
const auto length = snippetLength ? snippetLength : sn.trigger.size();
|
||||
if (recent.keys.size() < length)
|
||||
return;
|
||||
@@ -2750,23 +2695,23 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
|
||||
}
|
||||
diagnosticEvent(L"Conversion source=" + std::to_wstring(hint) + L" target=" + std::to_wstring(to) +
|
||||
L" changed=" + std::to_wstring(result != text));
|
||||
const auto cursor = snippetTemplate.text.size() - snippetTemplate.suffix.size();
|
||||
auto cursorSuffix = [&](size_t start, size_t end) {
|
||||
return cursor >= start && cursor < end ?
|
||||
snippetTemplate.text.substr(cursor, end - cursor) : std::wstring{};
|
||||
};
|
||||
const bool ordered = snippet >= 0 && result.size() < snippetTemplate.text.size();
|
||||
const bool typeFirst = ordered && !farSnippet && canTypeSnippetText(result);
|
||||
bool clipboardRestored = false;
|
||||
if (result != text && typeFirst && cursor >= result.size())
|
||||
const auto skillToConfirm = [&](const std::wstring &segment, size_t end)
|
||||
{
|
||||
tx.check();
|
||||
tx.restoreClipboard();
|
||||
clipboardRestored = true;
|
||||
suspended = false;
|
||||
}
|
||||
if (!codexSnippet) return std::wstring{};
|
||||
const auto &actions = snippetTemplate.actions;
|
||||
auto action = std::lower_bound(actions.begin(), actions.end(), end,
|
||||
[](const SnippetAction &candidate, size_t offset) { return candidate.offset < offset; });
|
||||
for (; action != actions.end() && action->offset == end; ++action)
|
||||
{
|
||||
const auto *keys = std::get_if<std::vector<WORD>>(&action->value);
|
||||
if (keys && keys->size() == 1 && keys->front() == VK_RETURN)
|
||||
return snippetSkillName(segment);
|
||||
}
|
||||
return std::wstring{};
|
||||
};
|
||||
std::wstring pendingSkill = skillToConfirm(result, result.size());
|
||||
if (result != text)
|
||||
sent = typeFirst ? typeSnippetText(result, valid) : tx.paste(textClip(result));
|
||||
sent = snippet >= 0 ? tx.insertSnippetText(result, !pendingSkill.empty()) : tx.paste(textClip(result));
|
||||
else if (automatic && tx.valid())
|
||||
tx.finishSelection(false);
|
||||
if (requireReadback && result != text && !sent)
|
||||
@@ -2786,7 +2731,9 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
|
||||
reason = L"Conversion unchanged";
|
||||
verification = L"calculated-result-equals-original";
|
||||
}
|
||||
if (sent && !typeFirst && ((manual && config.writeLog) || requireReadback))
|
||||
// When Chromium exposes a focused suggestion rather than the
|
||||
// composer, verify against the suggestion before invoking it.
|
||||
if (sent && pendingSkill.empty() && ((manual && config.writeLog) || requireReadback))
|
||||
{
|
||||
verification = probe.status;
|
||||
if (tx.valid())
|
||||
@@ -2800,7 +2747,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
|
||||
if (!farSnippet && observed && newlines(*observed) == newlines(text) && tx.nativeSelectionIs(text))
|
||||
{
|
||||
diagnosticEvent(L"Paste retry: native Edit still selects the unchanged original");
|
||||
if (tx.paste(textClip(result)) && tx.valid())
|
||||
if (pendingSkill.empty() && tx.paste(textClip(result)) && tx.valid())
|
||||
observed = probe.read((int)caretSteps(result));
|
||||
else
|
||||
observed.reset();
|
||||
@@ -2851,48 +2798,64 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
|
||||
}
|
||||
if (snippet >= 0 && sent && tx.valid())
|
||||
{
|
||||
const auto cursor = snippetTemplate.text.size() - snippetTemplate.suffix.size();
|
||||
auto cursorSuffix = [&](size_t start, size_t end) {
|
||||
return cursor >= start && cursor < end ?
|
||||
snippetTemplate.text.substr(cursor, end - cursor) : std::wstring{};
|
||||
};
|
||||
tx.check();
|
||||
size_t emitted = result.size();
|
||||
if (!clipboardRestored)
|
||||
if (!placeSnippetCursor(tx, cursorSuffix(0, emitted))) return;
|
||||
if (!snippetTemplate.actions.empty())
|
||||
{
|
||||
tx.check();
|
||||
if (!placeSnippetCursor(tx, cursorSuffix(0, emitted))) return;
|
||||
if (!snippetTemplate.actions.empty())
|
||||
{
|
||||
tx.check();
|
||||
// Clipboard shortcuts read and change the user's clipboard.
|
||||
tx.restoreClipboard();
|
||||
suspended = false;
|
||||
}
|
||||
// Clipboard shortcuts must see the user's clipboard, and
|
||||
// any copies they make must survive the transaction.
|
||||
tx.restoreClipboard();
|
||||
suspended = false;
|
||||
}
|
||||
auto insertSegment = [&](size_t end)
|
||||
{
|
||||
if (end == emitted) return true;
|
||||
if (!tx.valid()) return false;
|
||||
Transaction segmentTx(*this, target, version, farSnippet, snippetEditor);
|
||||
const auto segment = snippetTemplate.text.substr(emitted, end - emitted);
|
||||
const auto suffix = cursorSuffix(emitted, end);
|
||||
if (!farSnippet && canTypeSnippetText(segment) && suffix.empty())
|
||||
pendingSkill = skillToConfirm(segment, end);
|
||||
if (!segmentTx.insertSnippetText(segment, !pendingSkill.empty()) || !segmentTx.valid())
|
||||
return false;
|
||||
if (pendingSkill.empty())
|
||||
{
|
||||
if (!typeSnippetText(segment, valid)) return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
Transaction segmentTx(*this, target, version, farSnippet, snippetEditor);
|
||||
if (!segmentTx.paste(textClip(segment)) || !segmentTx.valid()) return false;
|
||||
const auto count = caretSteps(segment);
|
||||
const auto actual = farSnippet ? segmentTx.readFarSnippet(count) : probe.read(static_cast<int>(count));
|
||||
if (!actual || !segmentTx.valid() || newlines(*actual) != newlines(segment) ||
|
||||
!placeSnippetCursor(segmentTx, suffix))
|
||||
if (!actual || !segmentTx.valid() || newlines(*actual) != newlines(segment))
|
||||
return false;
|
||||
}
|
||||
if (!placeSnippetCursor(segmentTx, cursorSuffix(emitted, end))) return false;
|
||||
emitted = end;
|
||||
return true;
|
||||
};
|
||||
bool skillSelected = false;
|
||||
for (const auto &action : snippetTemplate.actions)
|
||||
{
|
||||
if (!tx.valid()) return;
|
||||
if (!insertSegment(action.offset)) return;
|
||||
if (emitted != action.offset)
|
||||
{
|
||||
if (!insertSegment(action.offset)) return;
|
||||
skillSelected = false;
|
||||
}
|
||||
if (const auto *keys = std::get_if<std::vector<WORD>>(&action.value))
|
||||
{
|
||||
if (!pendingSkill.empty() && keys->size() == 1 && keys->front() == VK_RETURN)
|
||||
{
|
||||
if (!skillSelected && !selectSnippetSkill(pendingSkill, target, valid))
|
||||
{
|
||||
reason = L"snippet-skill-suggestion-unavailable";
|
||||
report(L"KSwitcher could not select the Codex skill. Choose it from the suggestions and continue your draft.");
|
||||
return;
|
||||
}
|
||||
skillSelected = true;
|
||||
continue;
|
||||
}
|
||||
if (!chord(*keys))
|
||||
throw std::runtime_error("Windows could not send all snippet keys");
|
||||
}
|
||||
@@ -2927,7 +2890,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 +3090,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 +3097,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 +3127,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 +3153,6 @@ void App::trayMenu()
|
||||
}
|
||||
switch (cmd)
|
||||
{
|
||||
case ToggleInputProcessing:
|
||||
toggleInputProcessing();
|
||||
break;
|
||||
case OpenFiles:
|
||||
dispatch(OpenFiles);
|
||||
break;
|
||||
@@ -3457,7 +3353,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 +3397,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 +3406,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 +3495,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 +3525,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 +3539,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 +3583,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 +3679,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 +3692,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())
|
||||
|
||||
@@ -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
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
#pragma once
|
||||
#include "platform.h"
|
||||
#include <algorithm>
|
||||
#include <string_view>
|
||||
#include <uiautomation.h>
|
||||
#include <wrl/client.h>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline std::wstring snippetSkillName(std::wstring_view text)
|
||||
{
|
||||
if (!text.starts_with(L'$') || text.size() < 2) return {};
|
||||
auto name = lower(std::wstring(text.substr(1)));
|
||||
if (name.find_first_not_of(L"abcdefghijklmnopqrstuvwxyz0123456789-_.") != name.npos)
|
||||
return {};
|
||||
return name;
|
||||
}
|
||||
|
||||
inline bool typeSnippetSkill(std::wstring_view text)
|
||||
{
|
||||
std::vector<INPUT> inputs;
|
||||
inputs.reserve(2 * text.size());
|
||||
for (wchar_t ch : text)
|
||||
for (DWORD flags : {DWORD{0}, DWORD{KEYEVENTF_KEYUP}})
|
||||
{
|
||||
auto input = keyboardInput(0, flags | KEYEVENTF_UNICODE);
|
||||
input.ki.wScan = ch;
|
||||
inputs.push_back(input);
|
||||
}
|
||||
return SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT)) == inputs.size();
|
||||
}
|
||||
|
||||
enum class SnippetSkillMatch { None, LabelWithDescription, Exact };
|
||||
|
||||
inline SnippetSkillMatch snippetSkillLabelMatch(IUIAutomationElement *item, const std::wstring &name)
|
||||
{
|
||||
BSTR label{};
|
||||
if (FAILED(item->get_CurrentName(&label))) return SnippetSkillMatch::None;
|
||||
auto candidate = lower(std::wstring(label ? label : L"", SysStringLen(label)));
|
||||
SysFreeString(label);
|
||||
if (candidate.size() < name.size() ||
|
||||
(candidate.size() > name.size() && candidate[name.size()] != L' '))
|
||||
return SnippetSkillMatch::None;
|
||||
auto end = candidate.begin() + name.size();
|
||||
std::replace(candidate.begin(), end, L' ', L'-');
|
||||
if (candidate.compare(0, name.size(), name) != 0) return SnippetSkillMatch::None;
|
||||
return candidate.size() == name.size() ? SnippetSkillMatch::Exact : SnippetSkillMatch::LabelWithDescription;
|
||||
}
|
||||
|
||||
inline std::vector<Microsoft::WRL::ComPtr<IUIAutomationElement>>
|
||||
snippetSuggestionLists(IUIAutomation *automation, IUIAutomationElement *focused)
|
||||
{
|
||||
using Microsoft::WRL::ComPtr;
|
||||
std::vector<ComPtr<IUIAutomationElement>> result;
|
||||
ComPtr<IUIAutomationElementArray> controlled;
|
||||
int count{};
|
||||
if (SUCCEEDED(focused->get_CurrentControllerFor(&controlled)) && controlled)
|
||||
controlled->get_Length(&count);
|
||||
for (int i = 0; i < count; ++i)
|
||||
{
|
||||
ComPtr<IUIAutomationElement> list;
|
||||
if (SUCCEEDED(controlled->GetElement(i, &list)) && list)
|
||||
result.push_back(list);
|
||||
}
|
||||
if (!result.empty()) return result;
|
||||
// Chromium can expose the active descendant of the combobox as the
|
||||
// focused element. In that case follow the option to its owning listbox.
|
||||
CONTROLTYPEID type{};
|
||||
if (FAILED(focused->get_CurrentControlType(&type)) || type != UIA_ListItemControlTypeId)
|
||||
return result;
|
||||
ComPtr<IUIAutomationTreeWalker> walker;
|
||||
if (FAILED(automation->get_RawViewWalker(&walker)) || !walker) return result;
|
||||
ComPtr<IUIAutomationElement> node = focused;
|
||||
for (int i = 0; i < 6; ++i)
|
||||
{
|
||||
ComPtr<IUIAutomationElement> parent;
|
||||
if (FAILED(walker->GetParentElement(node.Get(), &parent)) || !parent)
|
||||
break;
|
||||
BSTR role{};
|
||||
if (SUCCEEDED(parent->get_CurrentAriaRole(&role)))
|
||||
{
|
||||
const bool listbox = role && std::wstring_view(role, SysStringLen(role)) == L"listbox";
|
||||
SysFreeString(role);
|
||||
if (listbox)
|
||||
{
|
||||
result.push_back(parent);
|
||||
break;
|
||||
}
|
||||
}
|
||||
node = parent;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
inline bool selectSnippetSkill(const std::wstring &name, HWND target, const std::function<bool()> &valid)
|
||||
{
|
||||
using Microsoft::WRL::ComPtr;
|
||||
const auto deadline = GetTickCount64() + 500;
|
||||
ComPtr<IUIAutomation2> automation;
|
||||
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER, IID_IUIAutomation2,
|
||||
reinterpret_cast<void **>(automation.GetAddressOf()))))
|
||||
return false;
|
||||
automation->put_ConnectionTimeout(150);
|
||||
automation->put_TransactionTimeout(150);
|
||||
VARIANT roleValue{};
|
||||
roleValue.vt = VT_I4;
|
||||
roleValue.lVal = UIA_ListItemControlTypeId;
|
||||
ComPtr<IUIAutomationCondition> listItem;
|
||||
if (FAILED(automation->CreatePropertyCondition(UIA_ControlTypePropertyId, roleValue, &listItem)))
|
||||
return false;
|
||||
roleValue.lVal = UIA_TextControlTypeId;
|
||||
ComPtr<IUIAutomationCondition> textItem;
|
||||
if (FAILED(automation->CreatePropertyCondition(UIA_ControlTypePropertyId, roleValue, &textItem)))
|
||||
return false;
|
||||
DWORD targetProcess{};
|
||||
GetWindowThreadProcessId(target, &targetProcess);
|
||||
while (valid() && GetTickCount64() < deadline)
|
||||
{
|
||||
ComPtr<IUIAutomationElement> focused;
|
||||
int process{};
|
||||
if (FAILED(automation->GetFocusedElement(&focused)) || !focused ||
|
||||
FAILED(focused->get_CurrentProcessId(&process)) || static_cast<DWORD>(process) != targetProcess)
|
||||
return false;
|
||||
ComPtr<IUIAutomationElement> option;
|
||||
auto bestMatch = SnippetSkillMatch::None;
|
||||
bool ambiguous = false;
|
||||
for (const auto &list : snippetSuggestionLists(automation.Get(), focused.Get()))
|
||||
{
|
||||
CONTROLTYPEID role{};
|
||||
if (FAILED(list->get_CurrentControlType(&role)) || role != UIA_ListControlTypeId)
|
||||
continue;
|
||||
ComPtr<IUIAutomationElementArray> items;
|
||||
int length{};
|
||||
if (FAILED(list->FindAll(TreeScope_Descendants, listItem.Get(), &items)) || !items ||
|
||||
FAILED(items->get_Length(&length)))
|
||||
continue;
|
||||
for (int index = 0; index < length; ++index)
|
||||
{
|
||||
ComPtr<IUIAutomationElement> item;
|
||||
BOOL offscreen = TRUE, enabled = FALSE;
|
||||
if (FAILED(items->GetElement(index, &item)) || !item ||
|
||||
FAILED(item->get_CurrentIsOffscreen(&offscreen)) || offscreen ||
|
||||
FAILED(item->get_CurrentIsEnabled(&enabled)) || !enabled)
|
||||
continue;
|
||||
auto match = snippetSkillLabelMatch(item.Get(), name);
|
||||
if (match != SnippetSkillMatch::Exact)
|
||||
{
|
||||
ComPtr<IUIAutomationElement> caption;
|
||||
if (SUCCEEDED(item->FindFirst(TreeScope_Descendants, textItem.Get(), &caption)) &&
|
||||
caption && snippetSkillLabelMatch(caption.Get(), name) == SnippetSkillMatch::Exact)
|
||||
match = SnippetSkillMatch::Exact;
|
||||
}
|
||||
if (match == SnippetSkillMatch::None || match < bestMatch) continue;
|
||||
if (match > bestMatch)
|
||||
{
|
||||
option = item;
|
||||
bestMatch = match;
|
||||
ambiguous = false;
|
||||
}
|
||||
else ambiguous = true;
|
||||
}
|
||||
}
|
||||
if (option && !ambiguous && valid())
|
||||
{
|
||||
ComPtr<IUIAutomationInvokePattern> invoke;
|
||||
if (SUCCEEDED(option->GetCurrentPatternAs(UIA_InvokePatternId, IID_IUIAutomationInvokePattern,
|
||||
reinterpret_cast<void **>(invoke.GetAddressOf()))) && invoke)
|
||||
return valid() && SUCCEEDED(invoke->Invoke());
|
||||
ComPtr<IUIAutomationLegacyIAccessiblePattern> accessible;
|
||||
return SUCCEEDED(option->GetCurrentPatternAs(UIA_LegacyIAccessiblePatternId,
|
||||
IID_IUIAutomationLegacyIAccessiblePattern, reinterpret_cast<void **>(accessible.GetAddressOf()))) &&
|
||||
accessible && valid() && SUCCEEDED(accessible->DoDefaultAction());
|
||||
}
|
||||
Sleep(25);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+18
-50
@@ -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)
|
||||
@@ -2287,10 +2264,12 @@ bool snippetCommand(HWND w, SnippetView *v, WPARAM wp, bool embedded)
|
||||
if (id == SnippetMacros)
|
||||
{
|
||||
MessageBoxW(w,
|
||||
L"Macros between text segments run before the next segment.\n\n"
|
||||
L"Macros run where they appear in the replacement text.\n"
|
||||
L"In Codex, $skill{pause:500}{enter} Draft text selects a matching skill "
|
||||
L"and leaves the rest as a draft.\n\n"
|
||||
L"Tap a key: {{shift}}, {{altr}}, {{tab}}, {{F5}}\n"
|
||||
L"Hold keys together: {{ctrl}}+{{shift}}+{{A}}\n"
|
||||
L"Press Enter once per {enter} marker. Use {{return}} in a combination.\n"
|
||||
L"Press Enter: {enter} or {{return}} in a combination\n"
|
||||
L"Wait: {pause:50} for 50 milliseconds (0–10000)\n\n"
|
||||
L"Use an extra pair of braces for literal markers, for example {{enter}} or {{{shift}}}.",
|
||||
L"Snippet macros", MB_OK | MB_ICONINFORMATION);
|
||||
@@ -2328,9 +2307,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 +2327,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 +2352,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)
|
||||
{
|
||||
|
||||
@@ -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
@@ -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
@@ -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.125";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
+32
-50
@@ -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);
|
||||
|
||||
@@ -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, {});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
+8
-46
@@ -14,7 +14,6 @@ struct InputRegressionAccess
|
||||
{
|
||||
return app.snippetPopup && IsWindowVisible(app.snippetPopup);
|
||||
}
|
||||
static size_t suggestionCount(const App &app) { return app.snippetMatches.size(); }
|
||||
static bool suggestionsNearCaret(const App &app)
|
||||
{
|
||||
GUITHREADINFO info{sizeof(info)};
|
||||
@@ -70,9 +69,6 @@ bool conversionOnly = false;
|
||||
bool typosOnly = false;
|
||||
int pasteBehavior = 0;
|
||||
int enterPresses = 0;
|
||||
bool observeLiteralSequence = false;
|
||||
ULONGLONG literalTextAt{}, literalEnterAt{};
|
||||
std::wstring literalTextBeforeEnter;
|
||||
bool observeMacros = false, moveFocusOnMacro = false;
|
||||
bool rightAltAndCtrl = false, rightShift = false;
|
||||
bool typeDuringMacros = false;
|
||||
@@ -191,19 +187,7 @@ LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_P
|
||||
if (pasteBehavior == 2) SendMessageW(w, EM_REPLACESEL, TRUE, (LPARAM)L"other!");
|
||||
return 0;
|
||||
}
|
||||
if (observeLiteralSequence && message == WM_CHAR && wp == L'l' && !enterPresses)
|
||||
literalTextAt = GetTickCount64();
|
||||
if (message == WM_KEYDOWN && wp == VK_RETURN)
|
||||
{
|
||||
if (observeLiteralSequence && !enterPresses)
|
||||
{
|
||||
literalEnterAt = GetTickCount64();
|
||||
wchar_t before[128]{};
|
||||
GetWindowTextW(w, before, std::size(before));
|
||||
literalTextBeforeEnter = before;
|
||||
}
|
||||
++enterPresses;
|
||||
}
|
||||
if (message == WM_KEYDOWN && wp == VK_RETURN) ++enterPresses;
|
||||
return DefSubclassProc(w, message, wp, lp);
|
||||
}
|
||||
int stage = 0, ru = -1, en = -1;
|
||||
@@ -741,28 +725,10 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
case 73:
|
||||
require(enterPresses == 1 && text() == L"prefix ;qz\r\n" &&
|
||||
!ks::InputRegressionAccess::suggestionsVisible(*app),
|
||||
"Enter reaches the editor while multiple suggestions await navigation");
|
||||
prepare(L"prefix ", false);
|
||||
typeKeys({VK_OEM_1, 'Q', 'Z', VK_OEM_MINUS, 'S'});
|
||||
stage = 75;
|
||||
break;
|
||||
case 75:
|
||||
require(ks::InputRegressionAccess::suggestionsVisible(*app) &&
|
||||
ks::InputRegressionAccess::suggestionCount(*app) == 1,
|
||||
"a filtered prefix leaves one visible suggestion");
|
||||
enterPresses = 0;
|
||||
typeKeys({VK_RETURN});
|
||||
break;
|
||||
case 76:
|
||||
require(text() == L"prefix second" && enterPresses == 0 &&
|
||||
!ks::InputRegressionAccess::suggestionsVisible(*app),
|
||||
"Enter accepts the only suggestion without arrows or forwarding the key");
|
||||
require(ks::readClipboard(app->window).text() == sentinel,
|
||||
"accepting a single suggestion restores the clipboard");
|
||||
"Enter without arrow navigation reaches the editor");
|
||||
app->resetInput();
|
||||
SetFocus(host);
|
||||
typeKeys({VK_OEM_1});
|
||||
stage = 74;
|
||||
break;
|
||||
case 74:
|
||||
if (ks::InputRegressionAccess::findingSuggestionCaret(*app))
|
||||
@@ -983,18 +949,14 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
app->settings.autoCorrect = false;
|
||||
ActivateKeyboardLayout(app->layouts[en].handle, 0);
|
||||
require(ks::lower(ks::processName(host)) == L"chatgpt",
|
||||
"literal macro fixture runs under the Codex executable name");
|
||||
observeLiteralSequence = true;
|
||||
expandMacroSnippet(L"$example-skill{pause:500}{enter}{enter}{enter} Draft text{cursor}");
|
||||
"Codex skill guard fixture runs under the desktop executable name");
|
||||
expandMacroSnippet(L"$example-skill{pause:50}{enter}{enter}{enter} Draft text{cursor}");
|
||||
break;
|
||||
case 94:
|
||||
require(text() == L"prefix $example-skill\r\n\r\n\r\n Draft text" && enterPresses == 3,
|
||||
"three Enter markers send three keys before the tail without requiring a suggestion");
|
||||
require(literalTextBeforeEnter == L"prefix $example-skill" && literalTextAt &&
|
||||
literalEnterAt >= literalTextAt + 475,
|
||||
"the first Enter follows the typed prefix and the configured 500 ms pause");
|
||||
require(text() == L"prefix $example-skill" && enterPresses == 0,
|
||||
"an unavailable skill suggestion cancels three Enter markers without sending the draft");
|
||||
require(ks::readClipboard(app->window).text() == sentinel,
|
||||
"literal snippet actions restore the clipboard");
|
||||
"skill confirmation failure preserves the clipboard");
|
||||
finish();
|
||||
break;
|
||||
case 84:
|
||||
@@ -1362,7 +1324,7 @@ int main(int argc, char **argv)
|
||||
stage = 66;
|
||||
if (argc > 1 && std::string(argv[1]) == "--snippet-macros")
|
||||
stage = 80;
|
||||
if (argc > 1 && std::string(argv[1]) == "--snippet-literal-keys")
|
||||
if (argc > 1 && std::string(argv[1]) == "--snippet-skill-guard")
|
||||
stage = 93;
|
||||
if (argc > 1 && std::string(argv[1]) == "--snippet-word-boundaries")
|
||||
stage = 84;
|
||||
|
||||
+1
-14
@@ -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")
|
||||
{
|
||||
|
||||
+1
-1
@@ -485,7 +485,7 @@ int main(int argc, char **argv)
|
||||
require(prompt.text == L"$example-skill Draft text" && prompt.suffix.empty() &&
|
||||
prompt.actions == std::vector<ks::SnippetAction>{{14, DWORD{500}}, {14, std::vector<WORD>{VK_RETURN}},
|
||||
{14, std::vector<WORD>{VK_RETURN}}, {14, std::vector<WORD>{VK_RETURN}}},
|
||||
"all three Enter markers stay before the tail text");
|
||||
"all skill confirmation markers precede the prompt draft");
|
||||
require(ks::parseTemplate(L"{cursor}{cursor}").cursors == 2, "duplicate cursor detection");
|
||||
require(ks::Hotkey::parse(L"Ctrl+Alt+Shift+Space")->key == VK_SPACE, "hotkey parse");
|
||||
require(!ks::Hotkey::parse(L"Ctrl+F25"), "invalid function key");
|
||||
|
||||
@@ -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)]),
|
||||
|
||||
Reference in new issue
Block a user