Compare commits

..
Author SHA1 Message Date
agrynco 83e81aad07 Prepare KSwitcher v0.6.122
Allow active TCP attempts to finish before starting UDP fallback. Show input connection status in the tray and log declined cursor handoffs. Ship the verified Windows x64 package manifest and checksum.
2026-11-20 18:43:19 +02:00
25 changed files with 338 additions and 915 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.128 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.122 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+4 -10
View File
@@ -59,11 +59,10 @@ the local resident process running and log downloads enabled on the remote PC.
into the source computer restores its cursor at the corresponding edge. Empty
cells, diagonal-only neighbors and offline PCs do not transfer control.
When input sharing is enabled, the tray icon shows a steady gray dot if all
paired PCs are offline, a pulsing amber dot while a discovered PC is connecting,
a green dot when all online paired PCs are connected, and a red dot if the LAN
worker stops. Hover over the icon to see the connection status and the connected
count when only some paired PCs are connected.
When input sharing is enabled, the KSwitcher tray icon shows a green dot while
all paired PCs are connected, a pulsing amber dot while connections are pending,
and a red dot if the LAN worker stops. Hover over the icon to see how many PCs
are connected while KSwitcher retries.
The source cursor is parked and hidden beneath a tiny no-activation window. A
small banner identifies remote control; no full-screen layered bitmap is retained.
@@ -111,11 +110,6 @@ VLANs, public IPv4 and IPv6-only networks are not supported by discovery yet.
A second LAN-enabled KSwitcher cannot use the same ports on one computer.
Input first tries TCP in the usual direction, then reverse TCP after 1.5 seconds.
LAN discovery authenticates paired PCs before starting new input connections.
Discovery remains active while all paired PCs are offline and wakes input sharing
when one reappears. An authenticated input connection survives missed discovery
announcements. Once discovery has expired and the channel closes, further input
attempts wait for fresh discovery.
After at least 5 seconds, the lower-ID peer starts encrypted UDP fallback on the
discovery socket (UDP 45883) once its current TCP connection attempt has failed
or reached its 10-second deadline.
+12 -31
View File
@@ -461,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
@@ -494,35 +493,15 @@ ChatGPT and Codex desktop editors use paced selection for snippet triggers. If o
**Українською.** У настільних ChatGPT і Codex тригер виділяється з паузами між натисканнями. Якщо виділилася лише перевірена кінцева частина, KSwitcher доповнює виділення й перевіряє весь тригер перед заміною. Інший текст або зміна фокусу скасовують операцію. Тригери розпізнаються в різних розкладках. Один сніпет можна прив’язати до кількох програм через **Add app** або назви процесів через кому; ці прив’язки вже підтримують синхронізацію.
### 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.
- `{{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 виконує макроси між частинами тексту за порядком запису. Макрос на початку, як і раніше, виконується після першої частини тексту. Сніпет має містити текст заміни.
- `{{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.
Наприклад, `$skill-name{pause:500}{enter} Текст чернетки{cursor}` вводить назву, чекає 500 мілісекунд, натискає Enter один раз і вводить чернетку. Enter обробляє програма у фокусі. Кожен `{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
@@ -539,12 +518,12 @@ Scopes are saved with snippets and included in manual import/export and synchron
editor selection metadata remain identical. Unobserved or altered foreign copies are rejected.
Snippets normally require accessibility verification of their selected trigger and pasted text,
even with logging disabled. If verification is unavailable or the paste differs, expansion
stops before placing the cursor or running key actions. Clipboard changes during paste also cancel actions.
stops without running cursor or Enter actions. Clipboard changes during paste also cancel actions.
Far Manager uses its native Alt+Shift+Arrow selection, Ctrl+Insert copy and Shift+Insert
paste commands instead: both the trigger and inserted text must match verified clipboard
copies from Far. Cancellation restores the full temporary selection, not one cursor step.
Far supports nonempty single-line replacements up to 4096 caret steps, including
`{cursor}` and key macros after verification. Empty or multiline replacements are rejected
`{cursor}` and verified `{enter}` actions. Empty or multiline replacements are rejected
before selection; pasting a newline could execute a command before it can be verified.
- Teams recent-word conversion uses a single word-selection command and validates the copied range.
If the editor's word boundary differs from the recorded typing, it falls back to paced character
@@ -561,10 +540,12 @@ 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.
`{enter}` presses Enter after insertion and cursor placement (once per marker), before buffered typing resumes.
For example, `rider .{enter}` inserts `rider .` and presses Enter.
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).
and no Enter action is sent.
`{{cursor}}` and `{{enter}}` insert literal markers. Snippets are stored as plaintext settings, as in [Typlo](https://github.com/bitcodepro/Typlo).
- Clipboard history for text, HTML/RTF, file lists, DIB and PNG images; plain-text paste;
full-text search, pinning, deletion, full text viewing and image previews.
- Image thumbnails and text/file icons appear directly in the history list. Only visible rows
-50
View File
@@ -1,55 +1,5 @@
# Latest Windows release
## 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 / відкликано)
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.
**Українською.**
Макроси між частинами сніпета виконуються перед вставленням наступної частини. У Codex `$skill{pause:500}{enter} Текст чернетки` вибирає відповідний скіл із підказок і залишає наступний текст у редакторі. Повторні маркери Enter у тій самій позиції не надсилають чернетку. Якщо підказку не вдалося перевірити, розгортання зупиняється.
## v0.6.124 — 2026-11-21
Snippets can tap keys such as `{{shift}}`, hold combinations such as `{{altr}}+{{ctrl}}`, and wait with `{pause:50}`. After verifying the inserted text and placing `{cursor}`, KSwitcher runs the macros in order. The Snippets tab groups marker buttons and **Macro help…** below the editor, with **Save snippets** at the right.
**Українською.**
Сніпети підтримують окремі клавіші, як-от `{{shift}}`, комбінації на кшталт `{{altr}}+{{ctrl}}` і паузи, як-от `{pause:50}` на 50 мс. KSwitcher виконує макроси за порядком запису після перевірки вставленого тексту й встановлення `{cursor}`. На вкладці **Snippets** кнопки маркерів і **Macro help…** згруповані під редактором, а **Save snippets** розташована праворуч.
## v0.6.123 — 2026-11-20
- The tray shows a steady gray dot when all paired PCs are offline. The amber dot pulses while a discovered PC is connecting. Green means every online paired PC is connected.
- LAN discovery stays active. Once discovery has expired and the last input channel closes, KSwitcher pauses mouse and keyboard connection attempts until a paired PC reappears.
**Українською.**
- Коли всі спаровані ПК офлайн, у треї видно статичну сіру крапку. Жовта крапка пульсує під час підключення до знайденого ПК. Зелена означає, що всі доступні спаровані ПК під’єднані.
- Пошук у LAN продовжує працювати. Коли строк дії підтвердження присутності спливає й останній канал вводу закривається, KSwitcher призупиняє спроби підключення миші та клавіатури до появи спарованого ПК.
## v0.6.122 — 2026-11-20
- LAN mouse and keyboard sharing lets a TCP attempt finish or time out before starting the encrypted UDP fallback.
+1 -1
View File
@@ -1 +1 @@
641c56c3f071801bee71cdfac19f34a0d13a2ab275a566b192306f8fe098fac0 KSwitcher-win-x64.zip
074dce23470876852c0006cece4becf64e42a616a72e3502857fe76beed505d5 KSwitcher-win-x64.zip
+67 -67
View File
@@ -1,166 +1,166 @@
{
"schema": 1,
"version": "0.6.122",
"files": [
{
"size": 5892662,
"path": "KSwitcher.exe",
"sha256": "a9eba8784f709e8ffbcb80c2db9c2d9e31178ac93dd461d97c9b93d9ae9c7547",
"size": 2491904
"sha256": "10d2dbdec8dbc9b8c051a5befdec61319c4532ddcf3dfb3f4484d60feca593e1"
},
{
"size": 5948775,
"path": "KSwitcher.Config.exe",
"sha256": "3dbace0bfb9de3682020f8b7b5d95c7c3b957228d26b5dfdb849989dbcef6853",
"size": 2463232
"sha256": "4bc59946afd29f843be98e4b0389cc1c40363ecc50a3598629af074adb7abe25"
},
{
"size": 5763947,
"path": "KSwitcher.Screenshot.exe",
"sha256": "01ca23845f8757fd1706999260f460263e09213aa4519335fb528c386360c8a5",
"size": 3063808
"sha256": "4444dd1f7efd4e607833699fd841f50c6f04094da024474b705fb8247ec4fbe8"
},
{
"size": 9395091,
"path": "KSwitcher.Files.exe",
"sha256": "b5f64909dd0e87992d2d8899c61d9f7389b9ce819c545e353b70663722b6a432",
"size": 4377088
"sha256": "140455238ce9fa909dbb550d1c67ff6ff1aa2eebdfa8297183cc5d0b16ce14a0"
},
{
"size": 194912,
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
},
{
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
},
{
"size": 1521,
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
},
{
"size": 527,
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
},
{
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt",
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"size": 1073
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
},
{
"size": 100786,
"path": "terminal/markdown-it.js",
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"size": 100786
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
},
{
"size": 3599,
"path": "terminal/markdown.html",
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
"size": 3599
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094"
},
{
"size": 17575,
"path": "terminal/markdown.js",
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
"size": 17575
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8"
},
{
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt",
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"size": 1089
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
},
{
"size": 5537838,
"path": "terminal/mermaid.js",
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"size": 5537838
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
},
{
"size": 5065,
"path": "terminal/terminal.js",
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"size": 5065
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
},
{
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
},
{
"size": 7112,
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
},
{
"size": 488663,
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
},
{
"size": 4401,
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
},
{
"size": 1096,
"path": "json-LICENSE.txt",
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"size": 1096
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
},
{
"size": 883,
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
},
{
"size": 95524,
"path": "README.md",
"sha256": "13db0547936317dd235944cd1e53b9f8ce187cd022f04c16ce2480391ee2c55d",
"size": 99389
"sha256": "23d203a1fe73d1adc5e51d088420848cfabf03929401b78c4dbb249d0b5bdbf6"
},
{
"size": 11906,
"path": "LAN-PREVIEW.md",
"sha256": "3ab51025826e8aa2f7c07b70b920b556409b002029b4bb92cb34c5b32dac6e54",
"size": 12353
"sha256": "c1ee730c9b42b63f9501eaeb3fa4b5f16af17953615e526c53b76ac4fb7541bf"
},
{
"size": 732485,
"path": "dictionaries/en.txt",
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"size": 732485
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
},
{
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"size": 20566
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
},
{
"size": 2265,
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
},
{
"size": 1109134,
"path": "dictionaries/ru.txt",
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"size": 1109134
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
},
{
"size": 1280,
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
},
{
"size": 940799,
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
},
{
"size": 993,
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
},
{
"size": 540583,
"path": "tools/StayHere.exe",
"sha256": "791bdc0b627268dabc4ade81417b54b861e209d505a055466adb444cef944721",
"size": 133120
"sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c"
},
{
"size": 2796,
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
],
"schema": 1,
"version": "0.6.128"
]
}
+3 -3
View File
@@ -9,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,128,0
PRODUCTVERSION 0,6,128,0
FILEVERSION 0,6,122,0
PRODUCTVERSION 0,6,122,0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
@@ -20,7 +20,7 @@ BEGIN
BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.6.128"
VALUE "FileVersion", "0.6.122"
END
END
BLOCK "VarFileInfo"
+38 -140
View File
@@ -233,28 +233,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
{
@@ -322,7 +300,9 @@ class Transaction
if (captured && clipboardModified && GetClipboardSequenceNumber() == expected)
try
{
restoreClipboard();
auto started = GetTickCount64();
app.ownSequence = snapshot.restore(app.window, expected);
diagnosticEvent(L"Clipboard snapshot restored: elapsedMs=" + std::to_wstring(GetTickCount64() - started));
}
catch (...)
{
@@ -367,13 +347,6 @@ class Transaction
expected = now;
}
}
void restoreClipboard()
{
const auto started = GetTickCount64();
clipboardModified = false;
app.ownSequence = snapshot.restore(app.window, expected);
diagnosticEvent(L"Clipboard snapshot restored: elapsedMs=" + std::to_wstring(GetTickCount64() - started));
}
void write(const Clip &c)
{
check();
@@ -744,20 +717,6 @@ class Transaction
content.substr(LOWORD(range), original.size()) == original;
}
};
bool placeSnippetCursor(Transaction &tx, const std::wstring &suffix)
{
if (suffix.empty()) return tx.valid();
if (!tx.select(caretSteps(suffix))) return false;
const auto selected = tx.copy();
if (!tx.valid()) return false;
if (newlines(selected) != newlines(suffix))
{
tx.finishSelection(false);
return false;
}
return tx.finishSelection(true);
}
} // namespace
App::App(HINSTANCE h, bool test, const std::filesystem::path &dataRoot, HWND service)
: historyService(service), instance(h), smoke(test)
@@ -994,21 +953,17 @@ bool App::updateTray(DWORD action, bool notifyFile)
auto tip = localBuildTitle(L"KSwitcher");
if (trayInput.paired)
{
const bool reconnecting = trayInput.reconnecting();
const uint32_t color = trayInput.stopped ? 0xfff16b66 : !trayInput.online ? 0xffa0a4ab :
!reconnecting ? 0xff45d58c : trayInputPulse ? 0xffffc457 : 0xffac7830;
const bool connected = trayInput.connected == trayInput.paired;
const uint32_t color = trayInput.stopped ? 0xfff16b66 : connected ? 0xff45d58c :
trayInputPulse ? 0xffffc457 : 0xffac7830;
badge = trayInputIcon(icon.hIcon, width, height, color);
if (badge) icon.hIcon = badge;
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 if (connected) tip += L"connected";
else
{
tip += reconnecting ? L"reconnecting" : L"connected";
if (trayInput.connected < trayInput.paired)
tip += L" (" + std::to_wstring(trayInput.connected) + L"/" +
std::to_wstring(trayInput.paired) + L" PCs connected)";
}
tip += L"reconnecting (" + std::to_wstring(trayInput.connected) + L"/" +
std::to_wstring(trayInput.paired) + L" PCs connected)";
}
else if (!incomingLanFileCount)
tip = localBuildTitle(L"KSwitcher — keyboard layouts & clipboard");
@@ -1033,7 +988,7 @@ void App::refreshTrayInput()
if (state == trayInput) return;
trayInput = state;
trayInputPulse = true;
if (state.reconnecting())
if (state.connected < state.paired && !state.stopped)
SetTimer(window, TrayInputTimer, TrayInputPulseMs, nullptr);
else
KillTimer(window, TrayInputTimer);
@@ -1441,7 +1396,7 @@ bool App::queueSnippet(HWND target, size_t index, size_t length, HWND editor)
typingTarget = target;
snippetPending = static_cast<int>(index);
snippetPendingLength = length;
snippetPendingEditor = editor ? editor : snippetGuiInfo(target).hwndFocus;
snippetPendingEditor = editor;
snippetTyping = true;
busy = true;
if (PostMessageW(window, SnippetMessage, index, static_cast<LPARAM>(inputVersion.load())))
@@ -1571,8 +1526,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;
@@ -2481,7 +2435,6 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
std::to_wstring(recent.at ? start - recent.at : 0) +
L" id=" + std::to_wstring(attempt));
bool automatic = false;
Template snippetTemplate;
if (command == AutoCorrect)
{
// The editor must select the complete previous word. Unlike manual
@@ -2550,20 +2503,15 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
if (snippet >= (int)config.snippets.size() || recent.window != target)
return;
const auto &sn = config.snippets[snippet];
const auto process = lower(processName(target));
if (!snippetAppPriority(sn, process)) return;
if (!snippetAppPriority(sn, processName(target))) return;
const auto length = snippetLength ? snippetLength : sn.trigger.size();
if (recent.keys.size() < length)
return;
snippetTemplate = parseTemplate(sn.text);
const auto end = snippetTemplate.actions.empty() ? snippetTemplate.text.size() :
snippetTemplate.actions.front().offset;
result = snippetTemplate.text.substr(0, end);
result = parseTemplate(sn.text).text;
// A multiline clipboard paste can execute a console command
// before readback. Explicit key actions run after verification.
if (farSnippet && (snippetTemplate.text.empty() ||
snippetTemplate.text.find_first_of(L"\r\n") != result.npos ||
caretSteps(snippetTemplate.text) > 4096))
// before readback. Only explicit, verified {enter} may do so.
if (farSnippet && (result.empty() || result.find_first_of(L"\r\n") != result.npos ||
caretSteps(result) > 4096))
{
reason = L"far-snippet-template-unsupported";
return;
@@ -2707,23 +2655,8 @@ 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())
{
tx.check();
tx.restoreClipboard();
clipboardRestored = true;
suspended = false;
}
if (result != text)
sent = typeFirst ? typeSnippetText(result, valid) : tx.paste(textClip(result));
sent = tx.paste(textClip(result));
else if (automatic && tx.valid())
tx.finishSelection(false);
if (requireReadback && result != text && !sent)
@@ -2743,7 +2676,7 @@ 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))
if (sent && ((manual && config.writeLog) || requireReadback))
{
verification = probe.status;
if (tx.valid())
@@ -2808,62 +2741,27 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
}
if (snippet >= 0 && sent && tx.valid())
{
size_t emitted = result.size();
if (!clipboardRestored)
tx.check();
auto t = parseTemplate(config.snippets[snippet].text);
if (!t.suffix.empty())
{
if (!tx.select(caretSteps(t.suffix))) return;
auto suffix = tx.copy();
if (!tx.valid()) return;
if (newlines(suffix) != newlines(t.suffix))
{
tx.finishSelection(false);
return;
}
if (!tx.finishSelection(true)) return;
}
// Action markers run after insertion and cursor placement,
// before any physical typing buffered during expansion.
for (int i = 0; i < t.enters && tx.valid(); ++i)
{
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;
}
if (!chord(VK_RETURN)) break;
}
auto insertSegment = [&](size_t end)
{
if (end == emitted) return true;
if (!tx.valid()) return false;
const auto segment = snippetTemplate.text.substr(emitted, end - emitted);
const auto suffix = cursorSuffix(emitted, end);
if (!farSnippet && canTypeSnippetText(segment) && suffix.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))
return false;
}
emitted = end;
return true;
};
for (const auto &action : snippetTemplate.actions)
{
if (!tx.valid()) return;
if (!insertSegment(action.offset)) return;
if (const auto *keys = std::get_if<std::vector<WORD>>(&action.value))
{
if (!chord(*keys))
throw std::runtime_error("Windows could not send all snippet keys");
}
else
{
const auto deadline = GetTickCount64() + std::get<DWORD>(action.value);
for (auto now = GetTickCount64(); now < deadline; now = GetTickCount64())
{
if (!tx.valid()) return;
Sleep(static_cast<DWORD>(std::min<ULONGLONG>(deadline - now, 15)));
}
}
}
if (!insertSegment(snippetTemplate.text.size())) return;
}
if (to >= 0 && config.switchLayout && tx.valid() && (sent || result == text))
{
@@ -3504,7 +3402,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
}
if (wp == TrayInputTimer)
{
if (app->trayInput.reconnecting())
if (app->trayInput.connected < app->trayInput.paired && !app->trayInput.stopped)
{
app->trayInputPulse = !app->trayInputPulse;
app->updateTray(NIM_MODIFY);
+60 -122
View File
@@ -319,6 +319,40 @@ std::wstring transliterate(const std::wstring &text)
}
return out;
}
Template parseTemplate(const std::wstring &text)
{
Template t;
size_t cursor = std::wstring::npos;
for (size_t i = 0; i < text.size();)
{
if (text.compare(i, 9, L"{{enter}}") == 0)
{
t.text += L"{enter}";
i += 9;
}
else if (text.compare(i, 7, L"{enter}") == 0)
{
++t.enters;
i += 7;
}
else if (text.compare(i, 10, L"{{cursor}}\0", 10) == 0)
{
t.text += L"{cursor}";
i += 10;
}
else if (text.compare(i, 8, L"{cursor}") == 0)
{
cursor = t.text.size();
++t.cursors;
i += 8;
}
else
t.text += text[i++];
}
if (cursor != text.npos)
t.suffix = t.text.substr(cursor);
return t;
}
namespace
{
const std::vector<std::pair<UINT, std::wstring>> &namedKeys()
@@ -343,128 +377,7 @@ const std::vector<std::pair<UINT, std::wstring>> &namedKeys()
{VK_DIVIDE, L"Divide"}, {VK_DECIMAL, L"Decimal"}};
return names;
}
WORD namedKey(const std::wstring &token)
{
if (token.size() == 1 && ((token[0] >= L'a' && token[0] <= L'z') || iswdigit(token[0])))
return upper(token)[0];
if (token.size() == 4 && token.starts_with(L"num") && token[3] >= L'0' && token[3] <= L'9')
return VK_NUMPAD0 + token[3] - L'0';
if (token.size() >= 2 && token[0] == L'f')
{
wchar_t *tail{};
long n = wcstol(token.c_str() + 1, &tail, 10);
if (!*tail && n >= 1 && n <= 24) return static_cast<WORD>(VK_F1 + n - 1);
return 0;
}
for (const auto &[key, name] : namedKeys())
if (lower(name) == token) return static_cast<WORD>(key);
return 0;
}
WORD snippetKey(std::wstring_view name)
{
const auto token = lower(std::wstring(name));
static constexpr std::pair<std::wstring_view, WORD> modifiers[] = {
{L"shift", VK_LSHIFT}, {L"shiftl", VK_LSHIFT}, {L"shiftr", VK_RSHIFT},
{L"ctrl", VK_LCONTROL}, {L"ctrll", VK_LCONTROL}, {L"ctrlr", VK_RCONTROL},
{L"alt", VK_LMENU}, {L"altl", VK_LMENU}, {L"altr", VK_RMENU},
{L"win", VK_LWIN}, {L"winl", VK_LWIN}, {L"winr", VK_RWIN}};
for (const auto &[label, key] : modifiers)
if (label == token) return key;
if (token == L"return") return VK_RETURN;
// The old double-braced Enter marker is still an escape.
return token == L"enter" ? 0 : namedKey(token);
}
struct SnippetMarker
{
std::wstring_view name;
size_t length, depth;
};
std::optional<SnippetMarker> snippetMarker(std::wstring_view input)
{
if (!input.starts_with(L'{')) return {};
size_t depth = 1;
while (depth < 3 && depth < input.size() && input[depth] == L'{') ++depth;
const auto end = input.find_first_of(L"{}", depth);
if (end == input.npos || !input.substr(end).starts_with(std::wstring_view(L"}}}", depth)))
return {};
return SnippetMarker{input.substr(depth, end - depth), end + depth, depth};
}
std::optional<DWORD> snippetPause(std::wstring_view token)
{
constexpr std::wstring_view prefix = L"pause:";
constexpr DWORD maxPause = 10000;
if (!token.starts_with(prefix) || token.size() == prefix.size()) return {};
DWORD duration = 0;
for (wchar_t digit : token.substr(prefix.size()))
{
if (digit < L'0' || digit > L'9') return {};
duration = duration * 10 + (digit - L'0');
if (duration > maxPause) return {};
}
return duration;
}
} // namespace
Template parseTemplate(const std::wstring &text)
{
Template t;
std::wstring_view remaining(text);
size_t cursor = text.npos;
while (!remaining.empty())
{
const auto marker = snippetMarker(remaining);
if (!marker)
{
t.text += remaining.front();
remaining.remove_prefix(1);
continue;
}
const auto [name, length, depth] = *marker;
const auto pause = depth <= 2 ? snippetPause(name) : std::nullopt;
const WORD key = depth >= 2 ? snippetKey(name) : 0;
const bool legacyEscape = name == L"cursor" || name == L"enter";
if (depth == 1 && name == L"cursor")
{
cursor = t.text.size();
++t.cursors;
}
else if (depth == 1 && name == L"enter")
t.actions.push_back({t.text.size(), std::vector<WORD>{VK_RETURN}});
else if (depth == 1 && pause)
t.actions.push_back({t.text.size(), *pause});
else if (depth == 2 && key)
{
std::vector<WORD> keys{key};
remaining.remove_prefix(length);
while (remaining.starts_with(L'+'))
{
const auto next = snippetMarker(remaining.substr(1));
if (!next || next->depth != 2) break;
const WORD nextKey = snippetKey(next->name);
if (!nextKey) break;
if (std::find(keys.begin(), keys.end(), nextKey) == keys.end())
keys.push_back(nextKey);
remaining.remove_prefix(1 + next->length);
}
t.actions.push_back({t.text.size(), std::move(keys)});
continue;
}
else if ((depth >= 2 && legacyEscape) || (depth == 2 && pause) || (depth == 3 && key))
t.text += remaining.substr(1, length - 2);
else
t.text += remaining.substr(0, length);
remaining.remove_prefix(length);
}
if (cursor != text.npos)
t.suffix = t.text.substr(cursor);
// A leading action has historically followed replacement of the trigger.
// Keep that behavior while allowing actions between text segments.
const auto first = std::find_if(t.actions.begin(), t.actions.end(),
[](const SnippetAction &action) { return action.offset != 0; });
const auto firstText = first == t.actions.end() ? t.text.size() : first->offset;
for (auto it = t.actions.begin(); it != first; ++it)
it->offset = firstText;
return t;
}
std::wstring Hotkey::format() const
{
if (!key)
@@ -510,7 +423,32 @@ std::optional<Hotkey> Hotkey::parse(std::wstring s)
h.modifiers |= MOD_WIN;
else
{
if (h.key || !(h.key = namedKey(token))) return {};
if (h.key)
return {};
if (token.size() == 1 && ((token[0] >= L'a' && token[0] <= L'z') || iswdigit(token[0])))
h.key = upper(token)[0];
else if (token.size() == 4 && token.substr(0, 3) == L"num" && token[3] >= L'0' &&
token[3] <= L'9')
h.key = VK_NUMPAD0 + token[3] - L'0';
else if (token.size() >= 2 && token[0] == L'f')
{
wchar_t *tail{};
long n = wcstol(token.c_str() + 1, &tail, 10);
if (*tail || n < 1 || n > 24)
return {};
h.key = VK_F1 + (UINT)n - 1;
}
else
{
for (auto &[key, name] : namedKeys())
if (lower(name) == token)
{
h.key = key;
break;
}
if (!h.key)
return {};
}
}
if (end == s.npos)
break;
+1 -8
View File
@@ -5,7 +5,6 @@
#include <optional>
#include <set>
#include <string>
#include <variant>
#include <vector>
#include <windows.h>
@@ -43,17 +42,11 @@ std::wstring snippetAppName(std::wstring);
int snippetAppPriority(const Snippet &, const std::wstring &process);
std::wstring snippetId(const Snippet &);
std::wstring newSnippetId();
struct SnippetAction
{
size_t offset;
std::variant<std::vector<WORD>, DWORD> value;
bool operator==(const SnippetAction &) const = default;
};
struct Template
{
std::wstring text, suffix;
std::vector<SnippetAction> actions;
int cursors = 0;
int enters = 0;
};
Template parseTemplate(const std::wstring &);
struct Hotkey
+20 -46
View File
@@ -110,14 +110,7 @@ void lan::wakeFilesPeer(const std::string &id)
struct LanService::Impl
{
struct Peer
{
std::string name,epoch;
sockaddr_in address{};
uint64_t seen{},verified{};
bool files{};
bool present(uint64_t now)const{return verified && now-verified<lan::PeerLifetime;}
};
struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; bool files{}; };
std::filesystem::path path;
std::string id,epoch=lan::randomHex(16),name=hostName(),status="Disabled.";
std::map<std::string,Peer> peers;
@@ -146,7 +139,7 @@ struct LanService::Impl
std::map<std::string,uint64_t> inputReady;
std::unique_ptr<lan::InputMesh> router;
std::string inputStatus="Input sharing disabled.";
size_t inputConnectedPeers{}, inputOnlinePeers{};
size_t inputConnectedPeers{};
bool inputWorkerStopped{};
bool inputNeedsHelp{};
HWND inputWindow{};std::atomic<bool> inputNotification{false};
@@ -221,7 +214,7 @@ struct LanService::Impl
void start()
{
stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers...";
updateInputStatus(0,0,"Waiting for paired computers...",false);
updateInputStatus(0,"Connecting input channels...",false);
worker=std::thread([this]{ run(); });
}
void stop()
@@ -233,14 +226,13 @@ struct LanService::Impl
transfers=std::make_unique<lan::ClipboardExchange>(id,"file-transfer");incomingFiles.clear();logDownload.reset();
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,0,FALSE);
}
void updateInputStatus(size_t connected,size_t online,std::string status,bool needsHelp,bool stopped=false)
void updateInputStatus(size_t connected,std::string status,bool needsHelp,bool stopped=false)
{
bool changed;
{
std::lock_guard lock(mutex);
changed=connected!=inputConnectedPeers||online!=inputOnlinePeers||stopped!=inputWorkerStopped;
changed=connected!=inputConnectedPeers||stopped!=inputWorkerStopped;
inputConnectedPeers=connected;
inputOnlinePeers=online;
inputWorkerStopped=stopped;
inputStatus=std::move(status);
inputNeedsHelp=needsHelp;
@@ -252,16 +244,6 @@ struct LanService::Impl
auto bytes=j.dump(); if(bytes.size()>2048) return;
sendto(socket,bytes.data(),int(bytes.size()),0,(const sockaddr*)&address,sizeof(address));
}
Json discoveryAnnouncement(bool filesListening)const
{
auto hello=lan::envelope("hello",id);
hello["name"]=name;
hello["epoch"]=epoch;
hello["clipboardSession"]=clipboard->session();
hello["fileSession"]=transfers->session();
hello["filesBrowse"]=filesListening;
return hello;
}
std::string heartbeat(const std::string &from,const std::string &to,const std::string &a,const std::string &b)
{ return "KSwitcher LAN v1|presence|"+from+"|"+to+"|"+a+"|"+b; }
void receiveTransfers(uint64_t now)
@@ -299,7 +281,7 @@ struct LanService::Impl
}
transfers->deliveries.clear();
}
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now,bool filesListening)
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now)
{
if(j.value("app","")!="KSwitcher-LAN" || j.value("version",0)!=1) return;
auto other=j.value("id",""); if(!lan::identifier(other)||other==id) return;
@@ -310,23 +292,19 @@ struct LanService::Impl
if(display.empty()||display.size()>128||!lan::identifier(session)||
std::any_of(display.begin(),display.end(),[](unsigned char c){return c<32||c==127;})) return;
// Discovery is untrusted and never grants input access.
const bool firstAnnouncement=!peers.contains(other);
if(firstAnnouncement && peers.size()>=64) return;
if(!peers.contains(other) && peers.size()>=64) return;
auto &peer=peers[other];
// A fresh announcement rotates the challenge every three seconds; it
// does not revoke a recent successful proof for the same address.
// Only a valid presence response renews verified, so untrusted/replayed
// announcements cannot extend its PeerLifetime expiry.
const bool addressChanged=peer.address.sin_addr.s_addr!=address.sin_addr.s_addr;
if(addressChanged) peer.verified=0;
if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) peer.verified=0;
clipboard->peerSession(other,j.value("clipboardSession",""));
transfers->peerSession(other,j.value("fileSession",""));
peer.files=j.value("filesBrowse",false);
peer.name=display; peer.epoch=session; peer.address=address; peer.seen=now;
if(trusted.contains(other))
{
// A returning peer can prove presence right away using our current challenge.
if(firstAnnouncement) send(socket,address,discoveryAnnouncement(filesListening));
auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch;
const auto &key=trusted[other].at("key");
const auto challenge=heartbeat(id,other,epoch,session);
@@ -445,16 +423,13 @@ struct LanService::Impl
});
clipboardActive=clipboard->active()||transfers->active();
if(shareInput)for(auto &[peer,entry]:trusted.items())
{
const auto found=peers.find(peer);
const bool discovered=found!=peers.end()&&found->second.present(now);
endpoints.push_back({.id=peer,.key=entry.at("key"),
.address=discovered?found->second.address.sin_addr.s_addr:0,.discovered=discovered});
}
endpoints.push_back({peer,entry.at("key"),peers.contains(peer)?peers.at(peer).address.sin_addr.s_addr:0});
if(refreshFiles.exchange(false) || now>=nextHello)
{
epoch=lan::randomHex(16); // Fresh challenge prevents replayed presence from staying online.
const auto hello=discoveryAnnouncement(filesListening);
auto hello=lan::envelope("hello",id); hello["name"]=name; hello["epoch"]=epoch;hello["clipboardSession"]=clipboard->session();
hello["fileSession"]=transfers->session();
hello["filesBrowse"]=filesListening;
for(auto ip:broadcasts()) { auto address=bound; address.sin_addr.s_addr=ip; send(socket,address,hello); }
nextHello=now+3000;
}
@@ -486,10 +461,8 @@ struct LanService::Impl
}
if(!in.empty()&&inputWindow&&!inputNotification.exchange(true))
if(!PostMessageW(inputWindow,LanInputReadyMessage,0,0))inputNotification=false;
const auto online=hub.onlinePeers();
updateInputStatus(connected,online,online||endpoints.empty()?hub.status():
"All paired PCs are offline. Waiting for LAN discovery.",hub.needsHelp());
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,online||clipboardActive?5000:100000};
updateInputStatus(connected,hub.status(),hub.needsHelp());
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,!endpoints.empty()||clipboardActive?5000:100000};
int ready=select(0,&read,nullptr,nullptr,&delay);
if(ready==SOCKET_ERROR) throw std::runtime_error("LAN discovery socket failed.");
if(ready>0) for(int count=0;count<64;++count)
@@ -504,7 +477,7 @@ struct LanService::Impl
bool allowed=false;auto peer=j.value("id","");
{std::lock_guard lock(mutex);allowed=shareInput&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;}
if(allowed)hub.receiveDatagram(j,GetTickCount64());
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64(),filesListening);}
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64());}
}
catch(const Json::exception &) {} // Malformed network data cannot interrupt discovery.
}
@@ -513,7 +486,7 @@ struct LanService::Impl
catch(const std::exception &e) { std::lock_guard lock(mutex); status=std::string("LAN stopped: ")+e.what(); }
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
++inputEpoch;
updateInputStatus(0,0,"Input connection closed.",false,true);
updateInputStatus(0,"Input connection closed.",false,true);
if(socket!=INVALID_SOCKET) closesocket(socket);
if(winsock) WSACleanup();
}
@@ -545,7 +518,8 @@ struct LanService::Impl
{
auto peer=j.at("peer").get<std::string>();
const auto checkPeer = [&] {
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).present(now))
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified||
now-peers.at(peer).verified>=lan::PeerLifetime)
throw std::runtime_error("Select an online paired computer.");
if(!transfers->hasSession(peer))
throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers.");
@@ -690,7 +664,7 @@ struct LanService::Impl
if(action=="filesPeers" && !trusted.contains(peer)) continue;
char ip[INET_ADDRSTRLEN]{}; InetNtopA(AF_INET,(void*)&p.address.sin_addr,ip,sizeof(ip));
result["peers"].push_back({{"id",peer},{"name",p.name},{"address",ip},{"paired",trusted.contains(peer)},
{"verified",p.present(now)},{"online",true},
{"verified",p.verified && now-p.verified<lan::PeerLifetime},{"online",true},
{"fileTransfer",transfers->hasSession(peer)},{"filesBrowse",p.files}});
}
for(const auto &[peer,p]:trusted.items()) if(!peers.contains(peer))
@@ -728,7 +702,7 @@ LanInputConnections LanService::inputConnections()const
std::lock_guard lock(impl->mutex);
if(!inputEnabled())return {};
const auto paired=impl->trusted.size();
return {std::min(impl->inputConnectedPeers,paired),std::min(impl->inputOnlinePeers,paired),paired,impl->inputWorkerStopped};
return {std::min(impl->inputConnectedPeers,paired),paired,impl->inputWorkerStopped};
}
bool LanService::tickInput(bool allowEnter){return impl->tickInput(allowEnter);}
bool LanService::keyboard(const KBDLLHOOKSTRUCT &k,bool down){return impl->router&&impl->router->keyboard(k,down,GetTickCount64());}
+1 -2
View File
@@ -11,9 +11,8 @@ inline constexpr UINT LanInputStatusMessage=WM_APP+91;
struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};};
struct LanInputConnections
{
size_t connected{}, online{}, paired{};
size_t connected{}, paired{};
bool stopped{};
bool reconnecting()const{return !stopped&&connected<online;}
bool operator==(const LanInputConnections &) const = default;
};
// Discovery, pairing and optional encrypted input within the resident process.
+10 -20
View File
@@ -222,16 +222,7 @@ void InputChannel::disconnect(){impl->reset(GetTickCount64(),"Input disconnected
std::string InputChannel::transport()const{return impl->reverse?"reverse TCP":"direct TCP";}
struct InputHub::Impl
{
struct Link
{
InputEndpoint endpoint;
std::unique_ptr<InputChannel> channel;
std::unique_ptr<InputDatagram> udp;
uint64_t generation{},epoch{},since{},failedSince{};
bool udpReady{};
std::string lastState;
bool ready()const{return channel->ready()||udp->ready();}
};
struct Link { InputEndpoint endpoint;std::unique_ptr<InputChannel> channel;std::unique_ptr<InputDatagram> udp;uint64_t generation{},epoch{},since{},failedSince{};bool udpReady{};std::string lastState; };
struct Pending {SOCKET socket;uint32_t address;uint64_t since;};
std::string local;uint16_t port;SOCKET listener=INVALID_SOCKET;
std::map<std::string,Link> links;std::vector<Pending> pending;uint64_t epoch{},retry{};
@@ -245,18 +236,17 @@ struct InputHub::Impl
currentTime=now;
for(auto it=links.begin();it!=links.end();){
auto match=std::find_if(endpoints.begin(),endpoints.end(),[&](auto &e){return e.id==it->first&&e.key==it->second.endpoint.key&&e.port==it->second.endpoint.port;});
// Discovery gates new attempts. An authenticated connection can outlive discovery.
if(match==endpoints.end()||(!match->discovered&&!it->second.ready()))it=links.erase(it);else ++it;
if(match==endpoints.end())it=links.erase(it);else ++it;
}
for(auto &e:endpoints)if(e.discovered&&e.id!=local&&!links.contains(e.id)){
for(auto &e:endpoints)if(e.id!=local&&!links.contains(e.id)){
Link link;link.endpoint=e;link.channel=std::make_unique<InputChannel>(local,e.id,e.key,0,e.port,true);
link.udp=std::make_unique<InputDatagram>(local,e.id,e.key);link.since=link.failedSince=now;link.epoch=++epoch;links.emplace(e.id,std::move(link));
}
// Discovery is a hint, not the lifetime of authenticated input sessions.
// Keep the last usable address across missed announcements. A new address
// is used only once a channel is down, never to tear down working input.
for(auto &e:endpoints){if(!e.discovered||e.id==local)continue;auto &link=links.at(e.id);
if(e.address&&!link.ready()&&e.address!=link.endpoint.address){
for(auto &e:endpoints){if(e.id==local)continue;auto &link=links.at(e.id);
if(e.address&&!link.channel->ready()&&e.address!=link.endpoint.address){
link.channel->disconnect();link.endpoint.address=e.address;
}
}
@@ -299,7 +289,8 @@ struct InputHub::Impl
if(!link.udp->active()){link.since=now;link.channel->disconnect();received.clear();}
}else link.channel->poll(link.endpoint.address,frames,received,now);
if(link.udpReady!=link.udp->ready()){link.udpReady=link.udp->ready();link.epoch=++epoch;}
if(link.ready())link.failedSince=link.since=now;
bool ready=link.channel->ready()||link.udp->ready();
if(ready)link.failedSince=link.since=now;
auto state=link.udp->ready()?"Input connected via encrypted UDP.":link.udp->active()?"Trying encrypted UDP over discovery...":link.channel->ready()?"Input connected via "+link.channel->transport()+".":link.channel->status();
if(state!=link.lastState){link.lastState=state;log(L"LAN input peer "+wide(id.substr(0,8))+L": "+wide(state));}
if(link.generation!=link.channel->generation()){link.generation=link.channel->generation();link.epoch=++epoch;}
@@ -310,8 +301,7 @@ struct InputHub::Impl
InputHub::InputHub(std::string id,uint16_t port):impl(std::make_unique<Impl>(std::move(id),port)){}
InputHub::~InputHub()=default;
void InputHub::poll(const std::vector<InputEndpoint> &peers,const std::vector<RoutedInput> &out,std::vector<RoutedInput> &in,uint64_t now){impl->poll(peers,out,in,now);}
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.ready())result[id]=l.epoch;return result;}
size_t InputHub::onlinePeers()const{return impl->links.size();}
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.channel->ready()||l.udp->ready())result[id]=l.epoch;return result;}
std::string InputHub::status()const{
auto count=ready().size();if(count==impl->links.size()&&count){
std::string routes;for(auto &[id,l]:impl->links){if(!routes.empty())routes+=", ";routes+=id.substr(0,8)+": "+(l.udp->ready()?"encrypted UDP":l.channel->transport());}
@@ -319,7 +309,7 @@ std::string InputHub::status()const{
}
if(needsHelp())return "Automatic connection attempts have not succeeded for every PC. Enable input on both PCs. Open Connection help for firewall commands.";
if(!impl->error.empty())return impl->error;
for(auto &[id,l]:impl->links)if(!l.ready())return l.lastState;
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready())return l.lastState;
return "Waiting for paired computers...";
}
void InputHub::disconnect(){for(auto &[id,l]:impl->links){l.channel->disconnect();l.udp->reset();l.since=impl->currentTime;}}
@@ -332,7 +322,7 @@ void InputHub::receiveDatagram(const Json &j,uint64_t now){
if(!active&&link.udp->active())link.channel->disconnect();
}
bool InputHub::needsHelp()const{
for(auto &[id,l]:impl->links)if(!l.ready()&&impl->currentTime-l.failedSince>=15000)return true;
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready()&&impl->currentTime-l.failedSince>=15000)return true;
return false;
}
}
+1 -8
View File
@@ -61,13 +61,7 @@ class InputChannel
void disconnect();
std::string transport()const;
};
struct InputEndpoint
{
std::string id,key;
uint32_t address{};
uint16_t port=45884;
bool discovered=true;
};
struct InputEndpoint {std::string id,key;uint32_t address{};uint16_t port=45884;};
struct RoutedInput {std::string peer;InputFrame frame;uint64_t epoch{};};
class InputHub
{
@@ -77,7 +71,6 @@ class InputHub
~InputHub();
void poll(const std::vector<InputEndpoint> &,const std::vector<RoutedInput> &,std::vector<RoutedInput> &,uint64_t now);
std::map<std::string,uint64_t> ready()const;
size_t onlinePeers()const;
std::string status()const;
void disconnect();
using SendDatagram=std::function<void(const std::string &,const Json &)>;
+16 -28
View File
@@ -490,44 +490,32 @@ INPUT keyboardInput(WORD key, DWORD flags)
return input;
}
bool chord(WORD key, UINT mods)
{
WORD keys[5];
size_t count = 0;
for (auto [modifier, vk] : {std::pair<UINT, WORD>{MOD_CONTROL, VK_CONTROL},
{MOD_ALT, VK_MENU}, {MOD_SHIFT, VK_SHIFT}, {MOD_WIN, VK_LWIN}})
if (mods & modifier)
keys[count++] = vk;
keys[count++] = key;
return chord(std::span<const WORD>(keys, count));
}
bool chord(std::span<const WORD> keys)
{
std::vector<INPUT> inputs;
inputs.reserve(2 * keys.size());
auto add = [&](WORD k, bool up)
{
INPUT i = keyboardInput(k, up ? KEYEVENTF_KEYUP : 0);
if (k >= VK_LSHIFT && k <= VK_RMENU)
{
i.ki.wScan = static_cast<WORD>(MapVirtualKeyW(k, MAPVK_VK_TO_VSC));
i.ki.dwFlags |= KEYEVENTF_SCANCODE;
}
if ((k >= VK_PRIOR && k <= VK_DOWN) || k == VK_INSERT || k == VK_DELETE ||
k == VK_DIVIDE || k == VK_LWIN || k == VK_RWIN || k == VK_RMENU ||
k == VK_RCONTROL || k == VK_SNAPSHOT ||
k == VK_DIVIDE || k == VK_LWIN || k == VK_SNAPSHOT ||
(k >= VK_VOLUME_MUTE && k <= VK_VOLUME_UP))
i.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
inputs.push_back(i);
};
for (WORD key : keys) add(key, false);
for (auto it = keys.rbegin(); it != keys.rend(); ++it) add(*it, true);
const auto sent = SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT));
if (sent == inputs.size()) return true;
// Release any keys already pressed if Windows accepted only part of the chord.
const auto pending = std::min<size_t>(sent, inputs.size() - sent);
if (pending)
SendInput(static_cast<UINT>(pending), inputs.data() + inputs.size() - pending, sizeof(INPUT));
return false;
for (auto [m, k] : {std::pair<UINT, WORD>{MOD_CONTROL, VK_CONTROL},
{MOD_ALT, VK_MENU},
{MOD_SHIFT, VK_SHIFT},
{MOD_WIN, VK_LWIN}})
if (mods & m)
add(k, false);
add(key, false);
add(key, true);
for (auto [m, k] : {std::pair<UINT, WORD>{MOD_WIN, VK_LWIN},
{MOD_SHIFT, VK_SHIFT},
{MOD_ALT, VK_MENU},
{MOD_CONTROL, VK_CONTROL}})
if (mods & m)
add(k, true);
return SendInput((UINT)inputs.size(), inputs.data(), sizeof(INPUT)) == inputs.size();
}
std::optional<SystemVolume> changeSystemVolume(MouseActionType action, int step)
{
-1
View File
@@ -56,7 +56,6 @@ DWORD writeClipboard(HWND, const Clip &);
DWORD writeClipboardGuarded(HWND, const Clip &, std::optional<DWORD> expected);
Clip textClip(const std::wstring &);
bool chord(WORD key, UINT modifiers = 0);
bool chord(std::span<const WORD> keys);
struct SystemVolume
{
int percent{};
+25 -72
View File
@@ -1137,13 +1137,12 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
#endif
#ifndef KS_RESIDENT_APP
constexpr int SnippetsPage = 4, SaveSnippets = 318, SnippetMacros = 320;
constexpr int SnippetsPage = 4, SaveSnippets = 318;
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;
@@ -1999,8 +1994,7 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
value(w, 283, L"Copied to clipboard.");
return 0;
}
if (((id >= 301 && id <= SaveSnippets) || id == SnippetMacros) &&
snippetCommand(w, &v->snippets, wp, true))
if (id >= 301 && id <= SaveSnippets && snippetCommand(w, &v->snippets, wp, true))
return 0;
if (id == 220 && HIWORD(wp) == LBN_SELCHANGE && !v->filling)
{
@@ -2111,10 +2105,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 +2121,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 +2203,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 +2212,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)
@@ -2284,18 +2260,6 @@ bool snippetCommand(HWND w, SnippetView *v, WPARAM wp, bool embedded)
SendDlgItemMessageW(w, 303, EM_REPLACESEL, TRUE, (LPARAM)(id == 312 ? L"{cursor}" : L"{enter}"));
return true;
}
if (id == SnippetMacros)
{
MessageBoxW(w,
L"Macros between text segments run before the next segment.\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"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);
return true;
}
if (id == (embedded ? SaveSnippets : IDOK))
{
saveSnippetDraft(w, v);
@@ -2322,38 +2286,33 @@ void createSnippetEditor(HWND w, SnippetView *view, bool embedded)
label(w, L"Triggers", 24, top, 186);
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER,
301, 24, top + 24, 186, 170 + textHeight);
button(w, L"&Add", 310, 24, actions, 88);
button(w, L"&Delete", 311, 122, actions, 88);
button(w, L"&Add", 310, 24, actions, 86);
button(w, L"&Delete", 311, 120, actions, 90);
label(w, L"&Trigger (for example ;addr)", 232, top, 452);
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);
button(w, L"Cursor &marker", 312, 232, actions, 108);
button(w, L"&Enter marker", 313, 348, actions, 100);
button(w, L"Macro &help…", SnippetMacros, 456, actions, 96);
button(w, L"Insert cursor &marker", 312, 232, actions, 190);
button(w, L"Insert &Enter marker", 313, 432, actions, 190);
if (embedded)
{
button(w, L"Sa&ve snippets", SaveSnippets, 572, actions, 112);
control(w, L"STATIC", L"", 0, 319, 232, actions + 33, 452, 24);
control(w, L"STATIC", L"", 0, 319, 232, actions + 35, 286, 24);
button(w, L"Sa&ve snippets", SaveSnippets, 530, actions + 30, 154);
}
else
{
button(w, L"&Save", IDOK, 474, actions + 44, 100);
button(w, L"&Cancel", IDCANCEL, 584, actions + 44, 100);
control(w, L"STATIC", L"Use {{cursor}} / {{enter}} for literal markers.", 0, 0, 232, actions + 35, 452, 22);
button(w, L"&Save", IDOK, 474, actions + 65, 100);
button(w, L"&Cancel", IDCANCEL, 584, actions + 65, 100);
}
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 +2337,6 @@ LRESULT CALLBACK snippetProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (!v) return DefWindowProcW(w, msg, wp, lp);
try
{
if (msg == AppWindowPicked) { snippetWindowPicked(w, wp, lp); return 0; }
if (msg == WM_DRAWITEM && wp == AppWindowPickerIcon)
{
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if (msg == WM_COMMAND && snippetCommand(w, v, wp, false)) return 0;
if (msg == WM_CLOSE)
{
+4 -20
View File
@@ -177,27 +177,11 @@ LRESULT CALLBACK appWindowPickerProc(HWND button, UINT msg, WPARAM wp, LPARAM lp
if (msg == WM_NCDESTROY) RemoveWindowSubclass(button, appWindowPickerProc, id);
return DefSubclassProc(button, msg, wp, lp);
}
HWND createButtonTooltips(HWND owner)
void createAppWindowPicker(HWND w, int id, int x, int y, int width, HWND &outline)
{
return CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, owner, nullptr,
GetModuleHandleW(nullptr), nullptr);
}
void addButtonTooltip(HWND tips, HWND owner, int id, const wchar_t *text)
{
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND | TTF_SUBCLASS, owner,
reinterpret_cast<UINT_PTR>(GetDlgItem(owner, id))};
tool.lpszText = const_cast<wchar_t *>(text);
SendMessageW(tips, TTM_ADDTOOLW, 0, reinterpret_cast<LPARAM>(&tool));
}
constexpr int AppWindowPickerIcon = 753;
void createAppWindowPicker(HWND w, int id, int x, int y, int width, HWND &outline, HWND tips = nullptr)
{
const bool icon = id == AppWindowPickerIcon;
HWND picker = control(w, L"BUTTON", icon ? L"Drag to application window" : L" ⊕ Drag to window",
WS_TABSTOP | (icon ? BS_OWNERDRAW : BS_PUSHBUTTON | BS_LEFT), id, x, y, width, 28);
SetWindowSubclass(picker, appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&outline));
if (tips) addButtonTooltip(tips, w, id, L"Drag to an application window");
control(w, L"BUTTON", L" ⊕ Drag to window", WS_TABSTOP | BS_PUSHBUTTON | BS_LEFT,
id, x, y, width, 28);
SetWindowSubclass(GetDlgItem(w, id), appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&outline));
}
LRESULT CALLBACK appLanguagesProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
+28 -12
View File
@@ -272,6 +272,7 @@ struct MouseProfileEditor
constexpr int ActionApplications = 748, ActionApplicationName = 749, AddActionApp = 750, RemoveActionApp = 751;
constexpr int BrowseActionApp = 752;
constexpr int PickActionApp = 753;
constexpr int AddMouseProfile = 754, MouseProfileName = 755;
void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
@@ -294,7 +295,7 @@ void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
FrameRect(item.hDC, &folder, ink);
FillRect(item.hDC, &tab, ink);
}
else if (item.CtlID == AppWindowPickerIcon)
else if (item.CtlID == PickActionApp)
{
RECT target{x - half, y - half, x + half + 1, y + half + 1};
RECT horizontal{x - half - weight, y, x + half + weight + 1, y + 1};
@@ -343,6 +344,14 @@ void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
}
}
void addActionApplicationTooltip(HWND tips, HWND editor, int id, const wchar_t *text)
{
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND | TTF_SUBCLASS, editor,
reinterpret_cast<UINT_PTR>(GetDlgItem(editor, id))};
tool.lpszText = const_cast<wchar_t *>(text);
SendMessageW(tips, TTM_ADDTOOLW, 0, reinterpret_cast<LPARAM>(&tool));
}
void fillActionApplications(HWND w, const MouseProfileEditor &editor)
{
SendDlgItemMessageW(w, ActionApplications, LB_RESETCONTENT, 0, 0);
@@ -667,7 +676,7 @@ LRESULT CALLBACK mouseProfileNameProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
}
return 0;
}
if (msg == WM_DRAWITEM && (wp == AddActionApp || wp == RemoveActionApp || wp == BrowseActionApp || wp == AppWindowPickerIcon))
if (msg == WM_DRAWITEM && (wp == AddActionApp || wp == RemoveActionApp || wp == BrowseActionApp || wp == PickActionApp))
{
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
@@ -766,13 +775,18 @@ void showMouseProfileName(HWND owner, SettingsView &view, bool renaming)
control(w, L"BUTTON", L"&Remove application", WS_TABSTOP | BS_OWNERDRAW, RemoveActionApp, 430, 100, 32, 28);
HWND appName = edit(w, ActionApplicationName, 18, 207, 324);
SendMessageW(appName, EM_SETCUEBANNER, FALSE, reinterpret_cast<LPARAM>(L"Application executable (e.g. chrome.exe)"));
HWND tips = createButtonTooltips(w);
createAppWindowPicker(w, AppWindowPickerIcon, 350, 205, 32, editor->pickerOutline, tips);
HWND picker = control(w, L"BUTTON", L"Drag to application window", WS_TABSTOP | BS_OWNERDRAW,
PickActionApp, 350, 205, 32, 28);
SetWindowSubclass(picker, appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&editor->pickerOutline));
control(w, L"BUTTON", L"&Browse for application", WS_TABSTOP | BS_OWNERDRAW, BrowseActionApp, 390, 205, 32, 28);
control(w, L"BUTTON", L"Add a&pplication", WS_TABSTOP | BS_OWNERDRAW, AddActionApp, 430, 205, 32, 28);
addButtonTooltip(tips, w, RemoveActionApp, L"Remove application");
addButtonTooltip(tips, w, AddActionApp, L"Add application");
addButtonTooltip(tips, w, BrowseActionApp, L"Browse for an executable or shortcut");
HWND tips = CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, w, nullptr,
view.app->instance, nullptr);
addActionApplicationTooltip(tips, w, RemoveActionApp, L"Remove application");
addActionApplicationTooltip(tips, w, AddActionApp, L"Add application");
addActionApplicationTooltip(tips, w, BrowseActionApp, L"Browse for an executable or shortcut");
addActionApplicationTooltip(tips, w, PickActionApp, L"Drag to an application window");
fillActionApplications(w, *editor);
control(w, L"BUTTON", renaming ? L"&Apply" : L"&Add", WS_TABSTOP | BS_DEFPUSHBUTTON, IDOK, 248, 251, 100, 28);
button(w, L"Cancel", IDCANCEL, 362, 251, 100);
@@ -1032,11 +1046,13 @@ void createMousePage(HWND w, SettingsView &view)
control(w, L"BUTTON", L"Delete profile", WS_TABSTOP | BS_OWNERDRAW, DeleteMouseProfile, profilesRight - 80, 61, 24, 24);
control(w, L"BUTTON", L"Edit profile", WS_TABSTOP | BS_OWNERDRAW, RenameMouseProfile, profilesRight - 52, 61, 24, 24);
control(w, L"BUTTON", L"Add profile", WS_TABSTOP | BS_OWNERDRAW, AddMouseProfile, profilesRight - 24, 61, 24, 24);
HWND tips = createButtonTooltips(w);
addButtonTooltip(tips, w, AddMouseProfile, L"Add profile");
addButtonTooltip(tips, w, RenameMouseProfile, L"Edit profile");
addButtonTooltip(tips, w, DeleteMouseProfile, L"Delete profile");
addButtonTooltip(tips, w, AddMouseEvent, L"Add mouse event");
HWND tips = CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, w, nullptr,
view.app->instance, nullptr);
addActionApplicationTooltip(tips, w, AddMouseProfile, L"Add profile");
addActionApplicationTooltip(tips, w, RenameMouseProfile, L"Edit profile");
addActionApplicationTooltip(tips, w, DeleteMouseProfile, L"Delete profile");
addActionApplicationTooltip(tips, w, AddMouseEvent, L"Add mouse event");
constexpr int listTop = 90, listHeight = 224;
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES};
InitCommonControlsEx(&controls);
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.128";
inline constexpr wchar_t AppVersion[] = L"0.6.122";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+32 -50
View File
@@ -22,36 +22,6 @@ void require(bool ok, const char *message)
if (!ok) throw std::runtime_error(message);
++passed;
}
std::wstring pickTestApplication(HWND picker, bool cancel = false)
{
RECT dialogBounds{};
GetWindowRect(GetParent(picker), &dialogBounds);
MONITORINFO monitor{sizeof(monitor)};
require(GetMonitorInfoW(MonitorFromWindow(picker, MONITOR_DEFAULTTONEAREST), &monitor),
"monitor work area available");
const auto targetX = std::clamp(dialogBounds.left + 32, monitor.rcWork.left, monitor.rcWork.right - 120);
const auto targetY = std::clamp(dialogBounds.top + 100, monitor.rcWork.top, monitor.rcWork.bottom - 48);
HWND target = CreateWindowExW(WS_EX_TOPMOST | WS_EX_NOACTIVATE, L"EDIT", L"Picker fixture",
WS_POPUP | WS_VISIBLE, targetX, targetY, 120, 48,
nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
require(picker && target, "window picker and target available");
POINT drop{targetX + 1, targetY + 1};
require(GetAncestor(WindowFromPoint(drop), GA_ROOT) == target, "fixture window is under the drop point");
ScreenToClient(picker, &drop);
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
require(GetCapture() == picker, "window picker captures drag");
SendMessageW(picker, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(drop.x, drop.y));
HWND outline = findTestWindow(L"KSwitcher.AppPickerOutline", nullptr);
RECT outlineBounds{}, targetBounds{};
require(IsWindowVisible(outline) && GetWindowRect(outline, &outlineBounds) &&
GetWindowRect(target, &targetBounds) && EqualRect(&outlineBounds, &targetBounds), "drag highlights the target window");
if (cancel) SendMessageW(picker, WM_KEYDOWN, VK_ESCAPE, 0);
else SendMessageW(picker, WM_LBUTTONUP, 0, MAKELPARAM(drop.x, drop.y));
require(!IsWindow(outline) && GetCapture() != picker, "finishing the drag clears the outline and releases capture");
auto pickedApp = ks::applicationName(ks::processName(target));
DestroyWindow(target);
return pickedApp;
}
void lanWindowLayoutChecks(const std::filesystem::path &root)
{
const std::string peer(32,'b');
@@ -377,8 +347,36 @@ int main(int argc,char **argv)
SendDlgItemMessageW(dialog, 722, LB_SETSEL, TRUE, -1);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(722, LBN_SELCHANGE), 0);
HWND picker = GetDlgItem(dialog, 728);
pickTestApplication(picker, true);
auto pickedApp = pickTestApplication(picker);
RECT dialogBounds{};
GetWindowRect(dialog, &dialogBounds);
MONITORINFO monitor{sizeof(monitor)};
require(GetMonitorInfoW(MonitorFromWindow(dialog, MONITOR_DEFAULTTONEAREST), &monitor),
"monitor work area available");
const auto targetX = std::clamp(dialogBounds.left + 32, monitor.rcWork.left, monitor.rcWork.right - 120);
const auto targetY = std::clamp(dialogBounds.top + 100, monitor.rcWork.top, monitor.rcWork.bottom - 48);
HWND target = CreateWindowExW(WS_EX_TOPMOST | WS_EX_NOACTIVATE, L"EDIT", L"Picker fixture",
WS_POPUP | WS_VISIBLE, targetX, targetY, 120, 48,
nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
require(picker && target, "window picker and target available");
POINT drop{targetX + 1, targetY + 1};
require(GetAncestor(WindowFromPoint(drop), GA_ROOT) == target, "fixture window is under the drop point");
ScreenToClient(picker, &drop);
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
require(GetCapture() == picker, "window picker captures drag");
SendMessageW(picker, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(drop.x, drop.y));
HWND outline = findTestWindow(L"KSwitcher.AppPickerOutline", nullptr);
RECT outlineBounds{}, targetBounds{};
require(IsWindowVisible(outline) && GetWindowRect(outline, &outlineBounds) &&
GetWindowRect(target, &targetBounds) && EqualRect(&outlineBounds, &targetBounds), "drag highlights the target window");
SendMessageW(picker, WM_KEYDOWN, VK_ESCAPE, 0);
require(!IsWindow(outline) && GetCapture() != picker, "Escape clears the outline and releases capture");
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
SendMessageW(picker, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(drop.x, drop.y));
outline = findTestWindow(L"KSwitcher.AppPickerOutline", nullptr);
SendMessageW(picker, WM_LBUTTONUP, 0, MAKELPARAM(drop.x, drop.y));
require(!IsWindow(outline), "dropping clears the outline");
auto pickedApp = ks::applicationName(ks::processName(target));
DestroyWindow(target);
auto pickedRow = SendDlgItemMessageW(dialog, 720, LB_FINDSTRINGEXACT, -1, (LPARAM)pickedApp.c_str());
require(GetCapture() != picker && pickedRow >= 0 &&
SendDlgItemMessageW(dialog, 720, LB_GETCURSEL, 0, 0) == pickedRow, "dropping on a window selects its executable");
@@ -437,11 +435,8 @@ int main(int argc,char **argv)
SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0);
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
require(IsDlgButtonChecked(snippets,314)==BST_UNCHECKED, "old snippet shows everywhere");
HWND scopePicker = GetDlgItem(snippets, 753);
require(IsWindowVisible(scopePicker) && !IsWindowEnabled(scopePicker), "global snippet disables the window picker");
CheckDlgButton(snippets,314,BST_CHECKED);
SendMessageW(snippets,WM_COMMAND,314,0);
require(IsWindowEnabled(scopePicker), "restricting the snippet enables the window picker");
SetDlgItemTextW(snippets,315,L"Notepad.exe");
auto secondApp = SendDlgItemMessageW(snippets,316,CB_ADDSTRING,0,(LPARAM)L"MS-Teams.EXE");
SendDlgItemMessageW(snippets,316,CB_SETCURSEL,secondApp,0);
@@ -450,17 +445,8 @@ int main(int argc,char **argv)
wchar_t appList[128]{};
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList)==L"Notepad.exe, MS-Teams.EXE", "Add app appends a second application without duplicates");
pickTestApplication(scopePicker, true);
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList)==L"Notepad.exe, MS-Teams.EXE", "cancelling the picker preserves the snippet scope");
auto pickedProcess = pickTestApplication(scopePicker);
pickTestApplication(scopePicker);
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList) == L"Notepad.exe, MS-Teams.EXE, " + pickedProcess + L".exe",
"dropping on a window appends its process once to the existing snippet scope");
const std::vector<std::wstring> savedScope{L"notepad", L"ms-teams", pickedProcess};
SendMessageW(snippets,WM_COMMAND,318,0);
require(IsWindow(snippets) && app.settings.snippets[0].apps==savedScope, "inline snippet editor saves selected applications");
require(IsWindow(snippets) && app.settings.snippets[0].apps==std::vector<std::wstring>{L"notepad",L"ms-teams"}, "inline snippet editor saves selected applications");
require(!saveEnabled() && status()==L"No unsaved settings.","separately saved snippet edit leaves Settings clean");
RedrawWindow(snippets,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
RECT snippetRect{};GetClientRect(snippets,&snippetRect);
@@ -474,12 +460,8 @@ int main(int argc,char **argv)
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
require(IsDlgButtonChecked(snippets,314)==BST_CHECKED, "scope restored when reopening editor");
SetDlgItemTextW(snippets,315,L"chrome.exe");
pickTestApplication(GetDlgItem(snippets, 753));
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList) == L"chrome.exe, " + pickedProcess + L".exe",
"standalone snippet editor adds the dropped application");
SendMessageW(snippets,WM_COMMAND,IDCANCEL,0);
require(app.settings.snippets[0].apps==savedScope, "cancel preserves existing scope");
require(app.settings.snippets[0].apps==std::vector<std::wstring>{L"notepad",L"ms-teams"}, "cancel preserves existing scope");
ks::showSettings(app);parent=app.settingsWindow;
SendMessageW(parent,WM_COMMAND,262,0);
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
-19
View File
@@ -830,25 +830,6 @@ int main(int argc, char **argv) {
require(visible(208) && visible(256), "logging controls are in Diagnostics");
selectPage(4);
require(visible(301) && visible(303) && visible(318), "Snippets has an inline editor and its own Save button");
auto snippetBounds = [&](int id) {
RECT bounds{};
GetWindowRect(GetDlgItem(settings, id), &bounds);
return bounds;
};
const RECT list = snippetBounds(301), replacement = snippetBounds(303);
const RECT add = snippetBounds(310), remove = snippetBounds(311);
const RECT cursor = snippetBounds(312), enter = snippetBounds(313);
const RECT help = snippetBounds(320), save = snippetBounds(318), status = snippetBounds(319);
require(visible(320) && add.left == list.left && remove.right == list.right &&
add.top == cursor.top && remove.top == cursor.top && cursor.top > replacement.bottom &&
enter.top == cursor.top && help.top == cursor.top && save.top == cursor.top &&
cursor.left == replacement.left && save.right == replacement.right &&
add.right < remove.left && remove.right < cursor.left &&
cursor.right < enter.left && enter.right < help.left && help.right < save.left &&
status.top >= save.bottom && status.bottom <= snippetBounds(261).top,
"snippet buttons share a clear aligned row above separate save feedback");
require(IsWindowEnabled(GetDlgItem(settings, 320)) && !IsWindowEnabled(GetDlgItem(settings, 312)),
"macro help is available before a snippet is selected");
const bool awake = app.settings.awake;
SendDlgItemMessageW(settings, 205, BM_SETCHECK, awake ? BST_UNCHECKED : BST_CHECKED, 0);
SendMessageW(settings, WM_COMMAND, 310, 0);
+3 -133
View File
@@ -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,13 +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;
ULONGLONG macroStart{}, macroEnd{};
int copyFailuresRemaining = 0, copyRequests = 0;
int droppedSelectionKeys = 0;
bool trimCopiedSpaces = false;
@@ -96,18 +88,6 @@ LRESULT CALLBACK forwardingHook(int code, WPARAM wp, LPARAM lp)
}
LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
if (observeMacros && (message == WM_KEYDOWN || message == WM_SYSKEYDOWN) && wp == VK_F8)
{
macroStart = GetTickCount64();
rightAltAndCtrl = (GetKeyState(VK_RMENU) & 0x8000) && (GetKeyState(VK_RCONTROL) & 0x8000);
if (moveFocusOnMacro) SetFocus(host);
return 0;
}
if (observeMacros && macroStart && message == WM_KEYDOWN && wp == VK_LEFT)
{
macroEnd = GetTickCount64();
rightShift = (GetKeyState(VK_RSHIFT) & 0x8000) != 0;
}
if (message == WM_KEYDOWN && wp == VK_LEFT && droppedSelectionKeys > 0 &&
(GetKeyState(VK_SHIFT) & 0x8000))
{
@@ -191,19 +171,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;
@@ -269,14 +237,7 @@ void typeKeys(std::initializer_list<WORD> keys)
inputs.push_back(input);
}
require(SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT)) == inputs.size(),
"snippet keyboard input submitted");
}
void expandMacroSnippet(const wchar_t *replacement)
{
app->settings.snippets = {{L";zmtest", replacement}};
prepare(L"prefix ;zmtest", false);
record(L";zmtest");
app->transform(0, 0, 0, field);
"snippet autocomplete keyboard input submitted");
}
void finish()
{
@@ -311,11 +272,6 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
throw std::runtime_error("Native integration timed out");
if (app->busy)
{
if (typeDuringMacros && ks::InputRegressionAccess::deferring(*app))
{
typeDuringMacros = false;
typeKeys({VK_SPACE, 'X'});
}
if (typeDuringCorrection && ks::InputRegressionAccess::deferring(*app))
{
typeDuringCorrection = false;
@@ -741,28 +697,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))
@@ -931,70 +869,6 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
require(enterPresses == 0, "unverified snippet never submits Enter even without logging");
require(ks::readClipboard(app->window).text() == sentinel, "rejected snippet restores clipboard");
pasteBehavior = 0;
stage = 80;
break;
case 80:
if (!captured) saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
app->settings.autoCorrect = false;
ActivateKeyboardLayout(app->layouts[en].handle, 0);
observeMacros = true;
typeDuringMacros = true;
expandMacroSnippet(L"left{cursor}right{{ctrlr}}+{{altr}}+{{F8}}{pause:150}{{shiftr}}+{{left}}{enter}");
break;
case 81:
require(rightAltAndCtrl && rightShift && ks::modifiersReleased(),
"snippet chords press the specified right modifiers and release them");
require(macroStart && macroEnd >= macroStart + 140, "snippet pause separates actual keyboard events");
require(text() == L"prefix lef\r\n xright",
"snippet macros start at the cursor marker and finish before buffered typing");
require(ks::readClipboard(app->window).text() == sentinel, "snippet macros restore the clipboard");
expandMacroSnippet(L"left{cursor}right{{ctrl}}+{{V}}");
break;
case 82:
require(text() == L"prefix left" + sentinel + L"right", "a snippet paste chord uses the user's clipboard");
enterPresses = 0;
macroStart = 0;
moveFocusOnMacro = true;
expandMacroSnippet(L"done{{F8}}{pause:250}{enter}");
break;
case 83:
require(macroStart && GetFocus() == host && text() == L"prefix done" && enterPresses == 0,
"snippet macros stop when focus moves to a different control");
observeMacros = false;
moveFocusOnMacro = false;
expandMacroSnippet(L"left{pause:50}{enter}{enter}right{cursor}!");
stage = 92;
break;
case 92:
require(text() == L"prefix left\r\n\r\nright!" && enterPresses == 2,
"actions between text segments run before the next segment");
require(LOWORD(SendMessageW(field, EM_GETSEL, 0, 0)) == GetWindowTextLengthW(field) - 1,
"the cursor marker works in the final text segment");
require(ks::readClipboard(app->window).text() == sentinel,
"each verified snippet segment restores the clipboard");
finish();
break;
case 93:
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
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}");
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(ks::readClipboard(app->window).text() == sentinel,
"literal snippet actions restore the clipboard");
finish();
break;
case 84:
@@ -1360,10 +1234,6 @@ int main(int argc, char **argv)
stage = 64;
if (argc > 1 && std::string(argv[1]) == "--snippet-autocomplete")
stage = 66;
if (argc > 1 && std::string(argv[1]) == "--snippet-macros")
stage = 80;
if (argc > 1 && std::string(argv[1]) == "--snippet-literal-keys")
stage = 93;
if (argc > 1 && std::string(argv[1]) == "--snippet-word-boundaries")
stage = 84;
SetTimer(host, 1, 100, nullptr);
+4 -43
View File
@@ -319,10 +319,10 @@ void hubChecks()
while((hubs[0]->ready().size()!=2||hubs[1]->ready().size()!=2||hubs[2]->ready().size()!=2)&&GetTickCount64()<deadline)pump();
check(hubs[0]->ready().size()==2&&hubs[1]->ready().size()==2&&hubs[2]->ready().size()==2,"three TCP hubs authenticate all independent pair channels on one listener per PC");
auto generation=hubs[0]->ready();
for(auto &list:endpoints)for(auto &e:list){e.address=0;e.discovered=false;}
for(auto &list:endpoints)for(auto &e:list)e.address=0;
for(int n=0;n<20;++n)pump();
check(hubs[0]->ready()==generation&&hubs[1]->ready().size()==2&&hubs[2]->ready().size()==2,"expired discovery does not destroy authenticated channels");
for(auto &list:endpoints)for(auto &e:list){e.address=htonl(INADDR_LOOPBACK);e.discovered=true;}
for(auto &list:endpoints)for(auto &e:list)e.address=htonl(INADDR_LOOPBACK);
InputFrame keyFrame{InputType::Key,7,'A',0,1},cross{InputType::Cross,8,2,30000};
hubs[0]->poll(endpoints[0],{{ids[1],keyFrame},{ids[2],cross}},incoming[0],GetTickCount64());
for(int n=0;n<100&&(incoming[1].empty()||incoming[2].empty());++n)pump();
@@ -340,50 +340,11 @@ void hubChecks()
for(int n=0;n<300&&(server.ready().empty()||client.ready().empty());++n){
server.poll(unknown,{},a,GetTickCount64());client.poll(known,{},b,GetTickCount64());Sleep(1);
}
check(server.ready().size()==1&&client.ready().size()==1,"available peer can accept inbound TCP without dialing");
check(server.ready().size()==1&&client.ready().size()==1,"saved pair listens and authenticates without receiving a discovery announcement");
}
endpoints[0].erase(endpoints[0].begin());hubs[0]->poll(endpoints[0],{},incoming[0],GetTickCount64()+1800);
check(!hubs[0]->ready().contains(ids[1])&&hubs[0]->ready().contains(ids[2]),"forgetting one pair revokes only its channel");
}
void offlineDiscoveryChecks()
{
WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup");
struct Close{~Close(){WSACleanup();}} close;
std::string a(32,'a'),b(32,'b'),key(64,'f');
const auto pa=freePort(),pb=freePort();
InputHub left(a,pa),right(b,pb);
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),pb,false}},eb{{a,key,htonl(INADDR_LOOPBACK),pa,false}};
std::vector<RoutedInput> ia,ib;
int datagrams=0;
left.datagrams([&](const auto &,const auto &){++datagrams;});
auto now=GetTickCount64();
auto pump=[&](uint64_t step=1){now+=step;right.poll(eb,{},ib,now);left.poll(ea,{},ia,now);};
auto checkIdle=[&]{
check(left.onlinePeers()==0&&left.ready().empty()&&!left.needsHelp()&&datagrams==0,
"offline saved peer does not trigger input retries or connection help");
SOCKET probe=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
sockaddr_in addr{};addr.sin_family=AF_INET;addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);addr.sin_port=htons(pa);
int result=connect(probe,(sockaddr*)&addr,sizeof(addr));
const auto error=WSAGetLastError();closesocket(probe);
check(result==SOCKET_ERROR&&error==WSAECONNREFUSED,"input TCP listener is closed while all peers are offline");
};
pump();pump(20000);checkIdle();
auto rediscover=[&]{
ea.front().discovered=eb.front().discovered=true;
for(int n=0;n<200&&(left.ready().empty()||right.ready().empty());++n){pump(20);Sleep(1);}
check(left.onlinePeers()==1&&left.ready().contains(b)&&right.ready().contains(a),
"input TCP connects when the saved peer reappears in discovery");
};
rediscover();
const auto oldEpoch=left.ready().at(b);
ea.front().discovered=false;
eb.clear(); // The other instance stops while discovery is already stale.
for(int n=0;n<30;++n){pump(20);Sleep(1);}
pump(20000);checkIdle();
eb={{a,key,htonl(INADDR_LOOPBACK),pa,false}};
rediscover();
check(left.ready().at(b)!=oldEpoch,"rediscovery replaces the disconnected input generation");
}
void fallbackChecks()
{
WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup");
@@ -567,6 +528,6 @@ void channelChecks()
}
int main()
{
try{channelChecks();hubChecks();offlineDiscoveryChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
try{channelChecks();hubChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
catch(const std::exception &e){std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;}
}
+6 -27
View File
@@ -459,33 +459,12 @@ int main(int argc, char **argv)
require(ks::transliterate(L"Shchuka") == L"Щука", "reverse transliteration");
require(ks::parseTemplate(L"a{cursor}b").suffix == L"b", "snippet suffix");
require(ks::parseTemplate(L"{{cursor}}").text == L"{cursor}", "escaped cursor");
const auto enters = ks::parseTemplate(L"a{cursor}b{enter}{enter}");
require(enters.text == L"ab" && enters.suffix == L"b" &&
enters.actions == std::vector<ks::SnippetAction>{{2, std::vector<WORD>{VK_RETURN}},
{2, std::vector<WORD>{VK_RETURN}}},
"Enter actions preserve the inserted text and cursor suffix");
const auto escaped = ks::parseTemplate(L"before {{cursor}} {{enter}} {{{shift}}} {{pause:50}} after");
require(escaped.text == L"before {cursor} {enter} {{shift}} {pause:50} after" && escaped.actions.empty(),
"escaped snippet markers are literal even inside text");
const auto macros = ks::parseTemplate(L"a{{SHIFT}}{cursor}b{pause:50}{{altr}}+{{ctrl}}+{{F5}}{{tab}}{{ctrl}}+{{return}}");
require(macros.text == L"ab" && macros.suffix == L"b" &&
macros.actions == std::vector<ks::SnippetAction>{{1, std::vector<WORD>{VK_LSHIFT}}, {2, DWORD{50}},
{2, std::vector<WORD>{VK_RMENU, VK_LCONTROL, VK_F5}}, {2, std::vector<WORD>{VK_TAB}},
{2, std::vector<WORD>{VK_LCONTROL, VK_RETURN}}},
"snippet macros preserve key chords, tap order, pauses and cursor placement");
const std::wstring literal = L"{{unknown}} + {pause:-1} {pause:10001} {pause:99999999999999} {pause:}";
const auto unrecognized = ks::parseTemplate(literal);
require(unrecognized.text == literal && unrecognized.actions.empty(),
"unknown keys and invalid pause durations remain literal");
const auto plus = ks::parseTemplate(L"2+{{left}}+1{pause:0}{pause:10000}");
require(plus.text == L"2++1" && plus.actions == std::vector<ks::SnippetAction>{
{2, std::vector<WORD>{VK_LEFT}}, {4, DWORD{0}}, {4, DWORD{10000}}},
"only a plus between key markers forms a chord and pause bounds are inclusive");
const auto prompt = ks::parseTemplate(L"$example-skill{pause:500}{enter}{enter}{enter} Draft text{cursor}");
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");
require(ks::parseTemplate(L"rider .{enter}").text == L"rider ." &&
ks::parseTemplate(L"rider .{enter}").enters == 1, "Enter is an action, not inserted text");
require(ks::parseTemplate(L"a{cursor}b{enter}{enter}").suffix == L"b" &&
ks::parseTemplate(L"a{cursor}b{enter}{enter}").enters == 2, "Enter actions preserve cursor suffix");
require(ks::parseTemplate(L"{{enter}}").text == L"{enter}" &&
ks::parseTemplate(L"{{enter}}").enters == 0, "escaped Enter is literal");
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");