From 0de58834cfedabd3870d4f335791c60b45318764 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Mon, 23 Nov 2026 23:38:58 +0200 Subject: [PATCH] Release KSwitcher v0.6.132 with snippet key recording --- CMakeLists.txt | 2 +- README.md | 12 +- Release/README.md | 10 + Release/SHA256SUMS.txt | 2 +- Release/release-files.json | 132 ++++++------ resources/app.rc | 6 +- src/app.cpp | 9 +- src/config_main.cpp | 7 +- src/core.cpp | 48 +++++ src/core.h | 3 + src/platform.cpp | 14 +- src/platform.h | 4 +- src/storage.cpp | 53 +++-- src/storage.h | 2 +- src/ui.cpp | 376 ++++++++++++++++++++++++++--------- src/update.h | 2 +- tests/chat_profiles.cpp | 251 ++++++++++++++++++----- tests/clipboard_snapshot.cpp | 62 +++++- 18 files changed, 737 insertions(+), 258 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4607282..4a5883e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.6.131 LANGUAGES CXX RC) +project(KSwitcher VERSION 0.6.132 LANGUAGES CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() diff --git a/README.md b/README.md index f0c2634..1015fdf 100644 --- a/README.md +++ b/README.md @@ -7,11 +7,11 @@ The original [Typlo](https://github.com/bitcodepro/Typlo) project and its data r **[User guide / Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki)** — setup, features, shortcuts, dictionaries, screenshots and troubleshooting in **English** and **[Українська](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home-uk)**. Each wiki page links to its translation. From v0.6.72, use **Settings → Snippets** to edit snippets in place and -**Save snippets** to save them independently. **Clipboard** contains OCR +**Save** to apply snippet edits together with other settings. **Clipboard** contains OCR options. **Sync**, **Computers**, and **Diagnostics** have their own tabs. **Українською.** З v0.6.72 сніпети редагуються у **Settings → Snippets** -і зберігаються окремою кнопкою **Save snippets**. OCR розміщено у +і зберігаються разом з іншими налаштуваннями кнопкою **Save**. OCR розміщено у **Clipboard**, а для синхронізації, ПК та журналу є окремі вкладки **Sync**, **Computers** і **Diagnostics**. @@ -518,14 +518,14 @@ ChatGPT and Codex desktop editors use paced selection for snippet triggers. If o ### Snippet macros -In **Settings → Snippets**, type macros into a snippet's replacement text. **Macro help…** sits beside the marker buttons below the editor, with **Save snippets** at the right. KSwitcher runs each macro between text segments in the listed order. A leading macro runs after the first text segment, as in earlier versions. A snippet needs some replacement text. +In **Settings → Snippets**, choose **Insert macro or marker…**. Enter a pause duration or click the recording field and press the keys. They appear as you press them. Release the keys and click **Insert**. You can also type expressions into the replacement text. 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 виконує макроси між частинами тексту за порядком запису. Макрос на початку, як і раніше, виконується після першої частини тексту. Сніпет має містити текст заміни. +**Українською.** У **Settings → Snippets** натисни **Insert macro or marker…**. Для паузи введи тривалість, а для клавіш клацни поле запису й натисни потрібні клавіші. Вони з’являються під час натискання. Відпусти їх і натисни **Insert**. Макроси також можна вписати в текст заміни. KSwitcher виконує макроси між частинами тексту за порядком запису. Макрос на початку, як і раніше, виконується після першої частини тексту. Сніпет має містити текст заміни. - `{{shift}}`, `{{alt}}` і `{{tab}}` натискають окремі клавіші. Регістр назви клавіші не має значення. Також підтримуються літери, цифри, `F1`–`F24`, клавіші навігації та редагування. - `{{altr}}+{{ctrl}}` затискає обидві клавіші разом. З’єднуй маркери знаком `+` без пробілів і став модифікатори перед основною клавішею, як у `{{ctrl}}+{{shift}}+{{A}}`. Суфікси `l` і `r` у назвах `ctrl`, `alt`, `shift` і `win` вибирають ліву й праву клавіші. Без суфікса використовується ліва. @@ -538,13 +538,13 @@ For example, `$skill-name{pause:500}{enter} Draft text{cursor}` types the token, ### Application-specific snippets — v0.6.51 -In **Settings → Snippets**, select a snippet and enable **Only in these applications**. Drag the crosshair next to **Add app** onto an open window to add its application. Repeat for each application. You can also select a process from the dropdown and click **Add app**, or type executable names separated by commas, such as `ms-teams.exe, outlook.exe`. Uncheck the option for a global snippet. A checked but empty restriction cannot be saved. Use **Save snippets** to apply the changes. +In **Settings → Snippets**, select a snippet and enable **Only in these applications**. 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. Click **Save** at the bottom of Settings 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** на відкрите вікно, щоб додати його програму. Повтори для кожної потрібної програми. Також можна вибрати процес зі списку й натиснути **Add app** або вписати назви процесів через кому, наприклад `ms-teams.exe, outlook.exe`. Вимкнений прапорець означає всі програми. Увімкнений прапорець із порожнім списком не можна зберегти. Натисни **Save** внизу Settings, щоб застосувати зміни. Сніпет конкретної програми має пріоритет над глобальним із тим самим тригером. Для різних програм однакові тригери дозволені, для перетинних областей — ні. Старі сніпети залишаються глобальними. Зіставлення за назвою процесу не залежить від регістру та суфікса `.exe`; OCR і таймерів немає. Для Chrome це весь браузер, а не окремий сайт. Обмеження входять до експорту/імпорту та синхронізації. Перед синхронізацією онови всі ПК до v0.6.51 або новішої: старі версії не розуміють обмеження та можуть застосувати сніпет глобально. ### Existing features diff --git a/Release/README.md b/Release/README.md index 5995acd..cb506ca 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,15 @@ # Latest Windows release +## v0.6.132 — 2026-11-23 + +In **Settings → Snippets**, **Insert macro or marker…** can add cursor and Enter markers, a pause in milliseconds, or a recorded key or key combination. Keys appear as you press them. Release the keys, click **Insert**, and use the main **Save** button to apply snippet edits together with other settings. + +Clipboard snapshots track the sequence after Windows prepares delayed formats. A sequence advance caused by the read can no longer abort the text operation. When image backup fails, diagnostics include the helper's error. + +**Українською.** У **Settings → Snippets** кнопка **Insert macro or marker…** додає маркери курсора й Enter, паузу в мілісекундах або записану клавішу чи комбінацію. Клавіші видно під час натискання. Відпустіть їх, натисніть **Insert** і збережіть правки головною кнопкою **Save**. + +Під час створення копії буфера KSwitcher бере номер послідовності після підготовки відкладених форматів Windows. Зміна номера під час самого читання більше не перериває текстову операцію. Якщо резервне копіювання зображення не вдалося, журнал показує помилку допоміжного процесу. + ## v0.6.131 — 2026-11-23 In **Settings → Computers → Manage computers… → Trusted clients**, choose **Add client…** and select Dirlume.exe. Dirlume can then browse drives on computers already paired in KSwitcher and download regular files. Remove the executable to revoke access. After updating Dirlume, add the new executable again. diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index 3d3afa1..2542af7 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -fc1a6038c5c302f573debe4f53c669bf23e0499b8976add1da0537e76b02d2bf KSwitcher-win-x64.zip +1e5bccf13ad4675a59437d581233668d2d37039673da6a6688d77ac45a75d071 KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index b235d97..8fabe59 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,166 +1,166 @@ { "files": [ { + "sha256": "211e728b929fea538679afc6f7dc2229e0618909af21e5a024c741603c3ef429", "path": "KSwitcher.exe", - "size": 6004128, - "sha256": "49b922d35c4739f11f6acbf2f2757e393aeb5a2dbc1c39728cd25d2193fa1acb" + "size": 6009167 }, { + "sha256": "6e4ba1a47e88f1f0afbb16c57a05445cd95462d7fdc0ebd107aca628d149c3ae", "path": "KSwitcher.Config.exe", - "size": 6059357, - "sha256": "dcdb912b7fc45534ddd946791525c7c6b1c8ce21a9c1228ade9ac63c407d0a22" + "size": 6068346 }, { + "sha256": "16752a198293d0a1cd2e783c7a9c2440d8fff8b72cc3ca2e67217740b9f40a8d", "path": "KSwitcher.Screenshot.exe", - "size": 5785053, - "sha256": "83695a985f3496e9c99283b02fe5b27e393eaabcb2cd5ddd743856b84049aa0e" + "size": 5790537 }, { + "sha256": "d44f1ba8dacb123cc09f6b48bf84e37daa82f6510cbbd8b3b160181eb0504d04", "path": "KSwitcher.Files.exe", - "size": 4377600, - "sha256": "6dace995d53dff51d0b752a5327092346f8be4b4801ccf12db38e3cc9e30e5ce" + "size": 9475150 }, { + "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6", "path": "WebView2Loader.dll", - "size": 194912, - "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6" + "size": 194912 }, { + "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f", "path": "terminal/addon-fit-LICENSE.txt", - "size": 1103, - "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f" + "size": 1103 }, { + "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527", "path": "terminal/addon-fit.js", - "size": 1521, - "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527" + "size": 1521 }, { + "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef", "path": "terminal/index.html", - "size": 527, - "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef" + "size": 527 }, { + "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473", "path": "terminal/markdown-it-LICENSE.txt", - "size": 1073, - "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473" + "size": 1073 }, { + "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e", "path": "terminal/markdown-it.js", - "size": 100786, - "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e" + "size": 100786 }, { + "sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094", "path": "terminal/markdown.html", - "size": 3599, - "sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094" + "size": 3599 }, { + "sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8", "path": "terminal/markdown.js", - "size": 17575, - "sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8" + "size": 17575 }, { + "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80", "path": "terminal/mermaid-LICENSE.txt", - "size": 1089, - "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80" + "size": 1089 }, { + "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3", "path": "terminal/mermaid.js", - "size": 5537838, - "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3" + "size": 5537838 }, { + "sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b", "path": "terminal/terminal.js", - "size": 5065, - "sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b" + "size": 5065 }, { + "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd", "path": "terminal/xterm-LICENSE.txt", - "size": 1261, - "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd" + "size": 1261 }, { + "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6", "path": "terminal/xterm.css", - "size": 7112, - "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6" + "size": 7112 }, { + "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972", "path": "terminal/xterm.js", - "size": 488663, - "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972" + "size": 488663 }, { + "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c", "path": "LICENSE", - "size": 4401, - "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c" + "size": 4401 }, { + "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831", "path": "json-LICENSE.txt", - "size": 1096, - "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831" + "size": 1096 }, { + "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625", "path": "files-text-license.txt", - "size": 883, - "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625" + "size": 883 }, { + "sha256": "1a203d3299d4241cd661d50fe07945e63455e03c92f9d947617521ab371d2e33", "path": "README.md", - "size": 101852, - "sha256": "e180efa5da9672111d8649422b661f55c85f33e458aba9e1b95060ea7c95ebe2" + "size": 101073 }, { + "sha256": "6b9cb999f828a1a7b49c5b171db3995a233039a22ecec8d7bd4815db0b3f4faf", "path": "LAN-PREVIEW.md", - "size": 12900, - "sha256": "d64d7ae44afdd87abbbf054bd43b027efa8907a7043b57f7d348ec49e49bf46f" + "size": 12906 }, { + "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9", "path": "dictionaries/en.txt", - "size": 732485, - "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9" + "size": 732485 }, { + "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5", "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt", - "size": 20566, - "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5" + "size": 20566 }, { + "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311", "path": "dictionaries/README.md", - "size": 2265, - "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311" + "size": 2265 }, { + "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849", "path": "dictionaries/ru.txt", - "size": 1109134, - "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849" + "size": 1109134 }, { + "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408", "path": "dictionaries/sources.json", - "size": 1280, - "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408" + "size": 1280 }, { + "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf", "path": "dictionaries/uk.txt", - "size": 940799, - "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf" + "size": 940799 }, { + "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a", "path": "tools/README.txt", - "size": 993, - "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a" + "size": 993 }, { + "sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c", "path": "tools/StayHere.exe", - "size": 133120, - "sha256": "d18778c437b3dda8258babb9db48a94d275fbe7272241f08e0da96173595abd9" + "size": 540583 }, { + "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413", "path": "tools/StayHere-README.md", - "size": 2796, - "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413" + "size": 2796 } ], - "schema": 1, - "version": "0.6.131" + "version": "0.6.132", + "schema": 1 } diff --git a/resources/app.rc b/resources/app.rc index 58b12f7..0bac5e0 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -10,8 +10,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur" 1 RT_MANIFEST "app.manifest" 201 RCDATA "update.ps1" 1 VERSIONINFO - FILEVERSION 0,6,131,0 - PRODUCTVERSION 0,6,131,0 + FILEVERSION 0,6,132,0 + PRODUCTVERSION 0,6,132,0 FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN @@ -21,7 +21,7 @@ BEGIN BEGIN VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility" VALUE "ProductName", "KSwitcher" - VALUE "FileVersion", "0.6.131" + VALUE "FileVersion", "0.6.132" END END BLOCK "VarFileInfo" diff --git a/src/app.cpp b/src/app.cpp index e88f7b0..714f9db 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -299,9 +299,8 @@ class Transaction try { auto started = GetTickCount64(); - const bool image = IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) || - IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")); - snapshot.capture(app.window, expected); + const bool image = clipboardHasImage(); + expected = snapshot.capture(app.window, expected); if (expected != GetClipboardSequenceNumber()) throw std::runtime_error("Clipboard changed while taking snapshot"); diagnosticEvent(L"Clipboard snapshot captured: elapsedMs=" + @@ -3055,9 +3054,7 @@ void App::captureHistory() if(sequence==GetClipboardSequenceNumber())publishClipboard(std::move(clip),app); return; } - if (IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) || - IsClipboardFormatAvailable(CF_BITMAP) || - IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"))) + if (clipboardHasImage()) { if (history->captureImage(sequence, app, config)) { diff --git a/src/config_main.cpp b/src/config_main.cpp index 8f3a3f6..43f8204 100644 --- a/src/config_main.cpp +++ b/src/config_main.cpp @@ -229,16 +229,17 @@ int runConfigurator(HINSTANCE instance, bool snippets, bool logs) MSG message; while ((app.settingsWindow || app.snippetsWindow || app.logWindow) && GetMessageW(&message, nullptr, 0, 0) > 0) { - if (app.settingsWindow && !IsWindowEnabled(app.settingsWindow)) + const auto editor = app.settingsWindow ? app.settingsWindow : app.snippetsWindow; + if (editor && !IsWindowEnabled(editor)) { - HWND popup = GetLastActivePopup(app.settingsWindow); + HWND popup = GetLastActivePopup(editor); while (!IsWindowEnabled(popup)) { HWND next = GetLastActivePopup(popup); if (next == popup) break; popup = next; } - if (popup != app.settingsWindow && IsDialogMessageW(popup, &message)) continue; + if (popup != editor && IsDialogMessageW(popup, &message)) continue; } if (app.settingsWindow && IsDialogMessageW(app.settingsWindow, &message)) continue; if (app.snippetsWindow && IsDialogMessageW(app.snippetsWindow, &message)) continue; diff --git a/src/core.cpp b/src/core.cpp index 25f7ee8..34064cb 100644 --- a/src/core.cpp +++ b/src/core.cpp @@ -404,6 +404,54 @@ std::optional snippetPause(std::wstring_view token) return duration; } } // namespace +std::wstring snippetKeyName(WORD key) +{ + switch (key) + { + case VK_LSHIFT: return L"Shift"; + case VK_RSHIFT: return L"ShiftR"; + case VK_LCONTROL: return L"Ctrl"; + case VK_RCONTROL: return L"CtrlR"; + case VK_LMENU: return L"Alt"; + case VK_RMENU: return L"AltR"; + case VK_LWIN: return L"Win"; + case VK_RWIN: return L"WinR"; + default: return Hotkey{0, key}.format(); + } +} +std::wstring formatSnippetInsertion(SnippetInsertion type, std::wstring_view parameter) +{ + if (type == SnippetInsertion::Cursor) return L"{cursor}"; + if (type == SnippetInsertion::Enter) return L"{enter}"; + if (type == SnippetInsertion::Pause) + { + auto pause = L"pause:" + std::wstring(parameter); + return snippetPause(pause) ? L"{" + pause + L"}" : std::wstring{}; + } + const bool chord = type == SnippetInsertion::Chord; + if (!chord && type != SnippetInsertion::Key) return {}; + + std::wstring text; + std::vector keys; + while (true) + { + const auto end = parameter.find(L'+'); + const auto token = parameter.substr(0, end); + const auto first = token.find_first_not_of(L" \t"); + if (first == token.npos) return {}; + auto name = lower(std::wstring(token.substr(first, token.find_last_not_of(L" \t") - first + 1))); + if (name == L"enter") name = L"return"; + const auto key = snippetKey(name); + if (!key || std::find(keys.begin(), keys.end(), key) != keys.end()) return {}; + keys.push_back(key); + if (!text.empty()) text += L'+'; + text += L"{{" + name + L"}}"; + if (end == parameter.npos) break; + if (!chord) return {}; + parameter.remove_prefix(end + 1); + } + return chord && keys.size() < 2 ? std::wstring{} : text; +} Template parseTemplate(const std::wstring &text) { Template t; diff --git a/src/core.h b/src/core.h index b3a409a..0b0dd7a 100644 --- a/src/core.h +++ b/src/core.h @@ -56,6 +56,9 @@ struct Template int cursors = 0; }; Template parseTemplate(const std::wstring &); +enum class SnippetInsertion { Cursor, Enter, Pause, Key, Chord }; +std::wstring snippetKeyName(WORD); +std::wstring formatSnippetInsertion(SnippetInsertion, std::wstring_view parameter); struct Hotkey { UINT modifiers{}, key{}; diff --git a/src/platform.cpp b/src/platform.cpp index abf5ffa..731201a 100644 --- a/src/platform.cpp +++ b/src/platform.cpp @@ -349,14 +349,18 @@ bool launchThroughExplorer(const std::wstring &path) SysFreeString(executable); return SUCCEEDED(hr); } -Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional expected) +bool clipboardHasImage() +{ + return IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) || + IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")); +} +Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional expected, + DWORD *capturedSequence) { ClipboardLock lock(window); if (expected && *expected != GetClipboardSequenceNumber()) throw std::runtime_error("Clipboard changed while taking snapshot"); - if (mode == ClipboardRead::WithoutImages && - (IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) || - IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")))) + if (mode == ClipboardRead::WithoutImages && clipboardHasImage()) throw std::runtime_error("Clipboard changed to an image"); Clip c; size_t total = 0; @@ -392,6 +396,8 @@ Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional< total += size; c.formats.push_back(std::move(format)); } + // Delayed rendering can advance the sequence while this read holds the clipboard open. + if (capturedSequence) *capturedSequence = GetClipboardSequenceNumber(); return c; } DWORD writeClipboard(HWND window, const Clip &c) { return writeClipboardGuarded(window, c, {}); } diff --git a/src/platform.h b/src/platform.h index a52a299..4dcfc69 100644 --- a/src/platform.h +++ b/src/platform.h @@ -50,8 +50,10 @@ std::wstring processName(HWND); std::wstring mouseApplicationName(HWND); bool launchThroughExplorer(const std::wstring &); enum class ClipboardRead { All, Selection, WithoutImages }; +bool clipboardHasImage(); Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024, - ClipboardRead = ClipboardRead::All, std::optional expected = {}); + ClipboardRead = ClipboardRead::All, std::optional expected = {}, + DWORD *capturedSequence = nullptr); DWORD writeClipboard(HWND, const Clip &); DWORD writeClipboardGuarded(HWND, const Clip &, std::optional expected); Clip textClip(const std::wstring &); diff --git a/src/storage.cpp b/src/storage.cpp index 4798003..32b0a97 100644 --- a/src/storage.cpp +++ b/src/storage.cpp @@ -794,6 +794,7 @@ struct HistoryImageWorker struct ClipboardSnapshotControl { DWORD sequence; + char captureError[256]; }; } @@ -856,15 +857,14 @@ struct ClipboardSnapshot::Helper }; ClipboardSnapshot::ClipboardSnapshot() = default; ClipboardSnapshot::~ClipboardSnapshot() = default; -void ClipboardSnapshot::capture(HWND window, DWORD sequence) +DWORD ClipboardSnapshot::capture(HWND window, DWORD sequence) { helper_.reset(); clip_ = {}; - if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) && - !IsClipboardFormatAvailable(CF_BITMAP) && !IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"))) + if (!clipboardHasImage()) { - clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence); - return; + clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence, &sequence); + return sequence; } auto helper = std::make_unique(); auto &channel = helper->channel; @@ -876,9 +876,24 @@ void ClipboardSnapshot::capture(HWND window, DWORD sequence) if (!DuplicateHandle(self, self, self, &parent.value, SYNCHRONIZE, TRUE, 0)) throw std::runtime_error("Cannot pass resident lifetime to clipboard helper"); channel.start(L"--clipboard-snapshot", parent.value); - if (channel.waitForResponse(10000) != WAIT_OBJECT_0) - throw std::runtime_error("Clipboard snapshot helper failed to capture"); + const auto wait = channel.waitForResponse(10000); + if (wait == WAIT_TIMEOUT) + throw std::runtime_error("Clipboard snapshot helper timed out during capture"); + if (wait == WAIT_FAILED) + throw std::runtime_error(utf8(lastError(L"Cannot wait for clipboard snapshot helper"))); + if (wait != WAIT_OBJECT_0) + { + const auto &error = channel.view.control->captureError; + if (error[0]) throw std::runtime_error(std::string("Clipboard snapshot capture: ") + error); + DWORD exitCode{}; + if (GetExitCodeProcess(channel.process.value, &exitCode)) + throw std::runtime_error("Clipboard snapshot helper exited during capture (code " + + std::to_string(exitCode) + ")"); + throw std::runtime_error(utf8(lastError(L"Cannot read clipboard snapshot helper exit code"))); + } + sequence = channel.view.control->sequence; helper_ = std::move(helper); + return sequence; } DWORD ClipboardSnapshot::restore(HWND window, DWORD sequence) { @@ -898,15 +913,15 @@ DWORD ClipboardSnapshot::restore(HWND window, DWORD sequence) } int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent) { + ImageWorkerView view{static_cast( + MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, sizeof(ClipboardSnapshotControl)))}; + if (!view.control) return 1; try { - ImageWorkerView view{static_cast( - MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, sizeof(ClipboardSnapshotControl)))}; - if (!view.control) return 1; - const auto sequence = view.control->sequence; - const auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence); - if (sequence != GetClipboardSequenceNumber() || !SetEvent(responseReady)) return 1; - // Only the clipboard sequence crosses the channel. The captured formats stay in this process. + auto &sequence = view.control->sequence; + const auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence, &sequence); + if (!SetEvent(responseReady)) return 1; + // The captured formats stay in this process. HANDLE signals[]{parent, requestReady}; if (WaitForMultipleObjects(2, signals, FALSE, INFINITE) != WAIT_OBJECT_0 + 1) return 1; HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr); @@ -915,6 +930,12 @@ int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseRea view.control->sequence = writeClipboardGuarded(window, clip, view.control->sequence); return 0; } + catch (const std::exception &error) + { + auto &message = view.control->captureError; + strncpy_s(message, error.what(), _TRUNCATE); + return 1; + } catch (...) { return 1; } } bool History::captureImage(DWORD sequence, const std::wstring &app, const Settings &settings) @@ -976,9 +997,7 @@ int runImageHistoryCapture(const std::filesystem::path &request) !IsClipboardFormatAvailable(RegisterClipboardFormatW(L"Clipboard Viewer Ignore")); }; if (!valid()) return 2; - if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) && - !IsClipboardFormatAvailable(CF_BITMAP) && - !IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"))) return 2; + if (!clipboardHasImage()) return 2; auto clip = readClipboard(nullptr, size_t(settings.maxImageMiB) * 1024 * 1024); if (!valid()) return 2; for (const auto &format : clip.formats) diff --git a/src/storage.h b/src/storage.h index 442332b..aacfa98 100644 --- a/src/storage.h +++ b/src/storage.h @@ -69,7 +69,7 @@ class ClipboardSnapshot ClipboardSnapshot(const ClipboardSnapshot &) = delete; ClipboardSnapshot &operator=(const ClipboardSnapshot &) = delete; ~ClipboardSnapshot(); - void capture(HWND, DWORD sequence); + DWORD capture(HWND, DWORD sequence); DWORD restore(HWND, DWORD sequence); }; int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent); diff --git a/src/ui.cpp b/src/ui.cpp index 7cc2679..96c249e 100644 --- a/src/ui.cpp +++ b/src/ui.cpp @@ -1137,13 +1137,14 @@ 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, SnippetMacros = 320; struct SnippetView { App *app{}; std::vector snippets, saved; int selection = -1; HWND pickerOutline{}; + bool filling{}; }; struct SettingsView { @@ -1159,9 +1160,10 @@ struct SettingsView bool rawMouseRegistered{}; SnippetView snippets; }; -bool snippetCommand(HWND, SnippetView *, WPARAM, bool embedded); +bool snippetCommand(HWND, SnippetView *, WPARAM); void snippetWindowPicked(HWND w, WPARAM target, LPARAM phase); -bool confirmSnippetClose(HWND, SnippetView *); +bool snippetDraftChanged(HWND, SnippetView *); +bool mergeSnippetDraft(HWND, SnippetView *, Settings &); void refreshSnippetDraft(HWND, SnippetView *); void updateSettingsState(HWND w, SettingsView *v); void selectSettingsPage(HWND w, SettingsView *v) @@ -1862,11 +1864,13 @@ bool settingsChanged(HWND w, SettingsView *v) } void updateSettingsState(HWND w, SettingsView *v) { - if (!v || !v->ready || v->filling || v->refreshing) return; + if (!v || !v->ready || v->filling || v->snippets.filling || v->refreshing) return; v->refreshing = true; bool changed = settingsChanged(w, v); - EnableWindow(GetDlgItem(w, IDOK), changed || (v->app->settings.autostart && !isLocalBuild())); + bool snippetsChanged = snippetDraftChanged(w, &v->snippets); + EnableWindow(GetDlgItem(w, IDOK), changed || snippetsChanged || (v->app->settings.autostart && !isLocalBuild())); const wchar_t *text = changed ? L"Unsaved settings — click Save to apply." : + snippetsChanged ? L"Unsaved snippets — click Save to apply." : v->visitedLan ? L"No unsaved settings. Network changes save automatically in the Computers window." : L"No unsaved settings."; if (value(w, 261) != text) value(w, 261, text); v->refreshing = false; @@ -1882,12 +1886,20 @@ struct SettingsStateRefresh updateSettingsState(window, reinterpret_cast(GetWindowLongPtrW(window, GWLP_USERDATA))); } }; +void applySettingsDraft(HWND w, SettingsView *v) +{ + if (v->app->busy) + throw std::runtime_error("Wait for the current text operation to finish"); + auto settings = collectSettings(w, v); + mergeSnippetDraft(w, &v->snippets, settings); + v->app->applySettings(settings); +} void closeSettings(HWND w, SettingsView *v) { - if (settingsChanged(w, v)) + if (settingsChanged(w, v) || snippetDraftChanged(w, &v->snippets)) { int choice = MessageBoxW(w, - L"You have unsaved settings changes. Save them before closing?\n\n" + L"You have unsaved changes. Save them before closing?\n\n" L"Yes: save and close.\nNo: discard changes.\nCancel: keep editing.", L"KSwitcher — Unsaved settings", MB_YESNOCANCEL | MB_ICONWARNING | MB_DEFBUTTON3); if (choice != IDYES && choice != IDNO) @@ -1896,9 +1908,7 @@ void closeSettings(HWND w, SettingsView *v) { try { - if (v->app->busy) - throw std::runtime_error("Wait for the current text operation to finish"); - v->app->applySettings(collectSettings(w, v)); + applySettingsDraft(w, v); } catch (const std::exception &e) { @@ -1907,8 +1917,7 @@ void closeSettings(HWND w, SettingsView *v) } } } - if (confirmSnippetClose(w, &v->snippets)) - DestroyWindow(w); + DestroyWindow(w); } LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) { @@ -1957,6 +1966,7 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) v->draft = v->app->settings; fillSettings(w, v); refreshSnippetDraft(w, &v->snippets); + updateSettingsState(w, v); return 0; case WM_ENABLE: if (wp) updateSettingsState(w, v); @@ -1999,8 +2009,8 @@ 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 <= 317) || id == SnippetMacros) && + snippetCommand(w, &v->snippets, wp)) return 0; if (id == 220 && HIWORD(wp) == LBN_SELCHANGE && !v->filling) { @@ -2039,11 +2049,8 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) } if (id == IDOK) { - if (!settingsChanged(w, v) && (!v->app->settings.autostart || isLocalBuild())) return 0; - if (!confirmSnippetClose(w, &v->snippets)) return 0; - if (v->app->busy) - throw std::runtime_error("Wait for the current text operation to finish"); - v->app->applySettings(collectSettings(w, v)); + if (!IsWindowEnabled(GetDlgItem(w, IDOK))) return 0; + applySettingsDraft(w, v); DestroyWindow(w); return 0; } @@ -2117,6 +2124,7 @@ void enableSnippetScopeControls(HWND w, bool enabled) } void updateSnippetEditor(HWND w, SnippetView *v) { + v->filling = true; bool selected = v->selection >= 0 && v->selection < (int)v->snippets.size(); value(w, 302, selected ? v->snippets[v->selection].trigger : L""); value(w, 303, selected ? v->snippets[v->selection].text : L""); @@ -2129,9 +2137,10 @@ void updateSnippetEditor(HWND w, SnippetView *v) value(w, 315, apps); bool restricted = selected && !v->snippets[v->selection].apps.empty(); CheckDlgButton(w, 314, restricted ? BST_CHECKED : BST_UNCHECKED); - for (int id : {302, 303, 311, 312, 313, 314}) + for (int id : {302, 303, 311, 314, SnippetMacros}) EnableWindow(GetDlgItem(w, id), selected); enableSnippetScopeControls(w, restricted); + v->filling = false; } void fillSnippets(HWND w, SnippetView *v) { @@ -2173,45 +2182,27 @@ bool sameSnippets(const std::vector &left, const std::vector & return a.id == b.id && a.trigger == b.trigger && a.text == b.text && a.apps == b.apps; }); } -void refreshSnippetDraft(HWND w, SnippetView *v) +bool snippetDraftChanged(HWND w, SnippetView *v) { collectSnippet(w, v); - if (!sameSnippets(v->snippets, v->saved) || sameSnippets(v->saved, v->app->settings.snippets)) + return !sameSnippets(v->snippets, v->saved); +} +void refreshSnippetDraft(HWND w, SnippetView *v) +{ + if (snippetDraftChanged(w, v) || sameSnippets(v->saved, v->app->settings.snippets)) return; v->snippets = v->saved = v->app->settings.snippets; v->selection = -1; fillSnippets(w, v); - value(w, 319, L""); } -void saveSnippetDraft(HWND w, SnippetView *v) +bool mergeSnippetDraft(HWND w, SnippetView *v, Settings &settings) { - collectSnippet(w, v); - if (sameSnippets(v->snippets, v->saved)) return; - auto settings = v->app->settings; - if (v->app->busy) - throw std::runtime_error("Wait for the current operation"); - if (!sameSnippets(settings.snippets, v->saved) && !sameSnippets(settings.snippets, v->snippets)) + if (!snippetDraftChanged(w, v)) return false; + const auto ¤t = v->app->settings.snippets; + if (!sameSnippets(current, v->saved) && !sameSnippets(current, v->snippets)) throw std::runtime_error("Snippets changed elsewhere. Reopen Settings to load the current snippets."); settings.snippets = v->snippets; - v->app->applySettings(settings); - v->snippets = v->saved = v->app->settings.snippets; - if (v->selection >= (int)v->snippets.size()) v->selection = -1; - if (auto parent = v->app->settingsWindow) - { - auto *view = reinterpret_cast(GetWindowLongPtrW(parent, GWLP_USERDATA)); - view->draft.snippets = v->saved; - view->draft.snippetTombstones = v->app->settings.snippetTombstones; - updateSettingsState(parent, view); - } -} -bool confirmSnippetClose(HWND w, SnippetView *v) -{ - collectSnippet(w, v); - if (sameSnippets(v->snippets, v->saved)) return true; - const int choice = MessageBoxW(w, L"Save your snippet changes before closing?", - L"KSwitcher — Unsaved snippets", MB_YESNOCANCEL | MB_ICONWARNING | MB_DEFBUTTON3); - if (choice == IDYES) saveSnippetDraft(w, v); - return choice == IDYES || choice == IDNO; + return true; } std::wstring snippetWindowExecutable(HWND window) { @@ -2234,12 +2225,232 @@ void snippetWindowPicked(HWND w, WPARAM target, LPARAM phase) if (phase == 1 && target) addSnippetApplication(w, snippetWindowExecutable(reinterpret_cast(target))); } -bool snippetCommand(HWND w, SnippetView *v, WPARAM wp, bool embedded) +constexpr struct SnippetInsertionOption { + const wchar_t *name, *parameter, *initial; +} snippetInsertions[] = { + {L"Place cursor", L"", L""}, + {L"Press Enter", L"", L""}, + {L"Pause", L"&Milliseconds (0–10000)", L"50"}, + {L"Tap a key", L"Record &key", L""}, + {L"Press keys together", L"Record &keys", L""} +}; +constexpr int InsertionType = 321, InsertionLabel = 322, InsertionParameter = 323, InsertionPreview = 324; +constexpr int NumericParameterWidth = 62, TextParameterWidth = 210; +constexpr UINT SnippetKeyEvent = WM_APP + 160; +struct SnippetKeyCapture +{ + HWND window; + HHOOK hook{}; + std::vector keys, held; + bool releasing{}; +}; +thread_local SnippetKeyCapture *activeSnippetCapture{}; +SnippetInsertion selectedSnippetInsertion(HWND w) +{ + return static_cast(static_cast(SendDlgItemMessageW(w, InsertionType, CB_GETCURSEL, 0, 0))); +} +bool recordsSnippetKeys(SnippetInsertion type) +{ + return type == SnippetInsertion::Key || type == SnippetInsertion::Chord; +} +void stopSnippetCapture(SnippetKeyCapture &capture) +{ + if (!capture.hook) return; + activeSnippetCapture = nullptr; + UnhookWindowsHookEx(capture.hook); + capture.hook = nullptr; +} +LRESULT CALLBACK snippetCaptureHook(int code, WPARAM message, LPARAM data) +{ + auto *capture = activeSnippetCapture; + if (code == HC_ACTION && capture && GetForegroundWindow() == capture->window && + GetFocus() == GetDlgItem(capture->window, InsertionParameter)) + { + const auto &event = *reinterpret_cast(data); + PostMessageW(capture->window, SnippetKeyEvent, event.vkCode, message == WM_KEYDOWN || message == WM_SYSKEYDOWN); + return 1; + } + return CallNextHookEx(nullptr, code, message, data); +} +std::wstring snippetInsertionText(HWND w) +{ + return formatSnippetInsertion(selectedSnippetInsertion(w), value(w, InsertionParameter)); +} +void updateSnippetInsertion(HWND w, bool changedType) +{ + if (changedType) + { + const auto type = selectedSnippetInsertion(w); + const auto &option = snippetInsertions[static_cast(type)]; + const bool hasParameter = *option.parameter != L'\0'; + const bool textParameter = recordsSnippetKeys(type); + const auto parameter = GetDlgItem(w, InsertionParameter); + SendMessageW(parameter, EM_SETREADONLY, textParameter, 0); + SendMessageW(parameter, EM_SETCUEBANNER, TRUE, + reinterpret_cast(textParameter ? L"Click or press Space to record" : L"")); + auto &controls = windowLayoutState(w)->controls; + const auto bounds = std::find_if(controls.begin(), controls.end(), + [parameter](const auto &control) { return control.first == parameter; }); + if (bounds != controls.end()) + { + auto &rect = bounds->second; + rect.right = rect.left + (textParameter ? TextParameterWidth : NumericParameterWidth); + arrangeWindow(w); + } + SendMessageW(parameter, EM_SETLIMITTEXT, textParameter ? 96 : 5, 0); + value(w, InsertionLabel, hasParameter ? option.parameter : L"Parameter"); + value(w, InsertionParameter, option.initial); + EnableWindow(parameter, hasParameter); + } + const auto text = snippetInsertionText(w); + const auto *capture = reinterpret_cast(GetWindowLongPtrW(w, GWLP_USERDATA)); + const bool recording = capture && capture->hook; + const wchar_t *hint = recording ? L"Press the keys you want to record." : + recordsSnippetKeys(selectedSnippetInsertion(w)) ? L"" : L"Enter a valid duration (0–10000)."; + value(w, InsertionPreview, text.empty() ? hint : text); + EnableWindow(GetDlgItem(w, IDOK), !recording && !text.empty()); +} +void showRecordedSnippetKeys(const SnippetKeyCapture &capture) +{ + std::wstring text; + for (auto recorded : capture.keys) + { + auto name = snippetKeyName(recorded); + if (name.empty()) { text.clear(); break; } + if (!text.empty()) text += L'+'; + text += name; + } + value(capture.window, InsertionParameter, text); + updateSnippetInsertion(capture.window, false); +} +void recordSnippetKey(SnippetKeyCapture &capture, WORD key, bool down) +{ + if (!capture.hook) return; + auto &held = capture.held; + auto position = std::find(held.begin(), held.end(), key); + if (down) + { + if (position != held.end()) return; + held.push_back(key); + if (!capture.releasing) + { + capture.keys.push_back(key); + showRecordedSnippetKeys(capture); + } + return; + } + if (position == held.end()) return; + held.erase(position); + capture.releasing = true; + if (!held.empty()) return; + stopSnippetCapture(capture); + + updateSnippetInsertion(capture.window, false); + if (snippetInsertionText(capture.window).empty()) + value(capture.window, InsertionPreview, + selectedSnippetInsertion(capture.window) == SnippetInsertion::Chord ? + L"Record at least two supported keys held together." : L"Record one supported key."); +} +LRESULT CALLBACK snippetParameterProc(HWND field, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR ref) +{ + auto &capture = *reinterpret_cast(ref); + const bool recordKeys = recordsSnippetKeys(selectedSnippetInsertion(capture.window)); + if (recordKeys && ((msg == WM_LBUTTONUP) || (msg == WM_KEYUP && wp == VK_SPACE))) + { + if (msg == WM_LBUTTONUP) DefSubclassProc(field, msg, wp, lp); + if (!capture.hook) + { + capture.held.clear(); + capture.keys.clear(); + capture.releasing = false; + capture.hook = SetWindowsHookExW(WH_KEYBOARD_LL, snippetCaptureHook, GetModuleHandleW(nullptr), 0); + if (capture.hook) + { + activeSnippetCapture = &capture; + value(capture.window, InsertionParameter, L""); + updateSnippetInsertion(capture.window, false); + } + else value(capture.window, InsertionPreview, L"Could not start key recording. Try again."); + } + return 0; + } + if (msg == WM_KILLFOCUS && capture.hook) + { + stopSnippetCapture(capture); + value(capture.window, InsertionParameter, L""); + updateSnippetInsertion(capture.window, false); + } + return DefSubclassProc(field, msg, wp, lp); +} +LRESULT CALLBACK snippetInsertionProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) +{ + HWND parent = GetWindow(w, GW_OWNER); + auto *capture = reinterpret_cast(GetWindowLongPtrW(w, GWLP_USERDATA)); + if (msg == WM_DPICHANGED) { resizeForDpi(w, wp, lp); return 0; } + if (msg == SnippetKeyEvent && capture) + { + recordSnippetKey(*capture, static_cast(wp), lp != 0); + return 0; + } + if (msg == WM_COMMAND) + { + const int id = LOWORD(wp); + if (id == InsertionType && HIWORD(wp) == CBN_SELCHANGE) updateSnippetInsertion(w, true); + if (id == InsertionParameter && HIWORD(wp) == EN_CHANGE) updateSnippetInsertion(w, false); + if (id == IDOK && IsWindowEnabled(GetDlgItem(w, IDOK))) + { + const auto text = snippetInsertionText(w); + DestroyWindow(w); + SendDlgItemMessageW(parent, 303, EM_REPLACESEL, TRUE, reinterpret_cast(text.c_str())); + } + if (id == IDCANCEL) DestroyWindow(w); + return 0; + } + if (msg == WM_CLOSE) { DestroyWindow(w); return 0; } + if (msg == WM_NCDESTROY) + { + if (capture) + { + stopSnippetCapture(*capture); + delete capture; + SetWindowLongPtrW(w, GWLP_USERDATA, 0); + } + EnableWindow(parent, TRUE); + SetForegroundWindow(parent); + SetFocus(GetDlgItem(parent, 303)); + disposeFont(w); + } + return DefWindowProcW(w, msg, wp, lp); +} +void showSnippetInsertion(HWND parent, App &app) +{ + HWND w = makeWindow(app, L"KSwitcher.SnippetInsertion", L"Insert macro or marker", snippetInsertionProc, + 426, 150, 0, false, parent); + label(w, L"&Action", 18, 14, 166); + auto list = control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL, + InsertionType, 18, 38, 166, 174); + for (const auto &option : snippetInsertions) + SendMessageW(list, CB_ADDSTRING, 0, reinterpret_cast(option.name)); + SendMessageW(list, CB_SETCURSEL, 0, 0); + control(w, L"STATIC", L"", 0, InsertionLabel, 198, 14, 210, 22); + auto parameter = edit(w, InsertionParameter, 198, 38, NumericParameterWidth); + auto *capture = new SnippetKeyCapture{w}; + SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast(capture)); + SetWindowSubclass(parameter, snippetParameterProc, 1, reinterpret_cast(capture)); + label(w, L"Inserts", 18, 75, 59); + control(w, L"STATIC", L"", SS_ENDELLIPSIS, InsertionPreview, 78, 75, 330, 22); + button(w, L"&Insert", IDOK, 200, 105); + button(w, L"&Cancel", IDCANCEL, 308, 105); + updateSnippetInsertion(w, true); + EnableWindow(parent, FALSE); + showRequestedWindow(w); + SetFocus(list); +} +bool snippetCommand(HWND w, SnippetView *v, WPARAM wp) +{ + if (v->filling) return true; const int id = LOWORD(wp); - if (embedded && ((HIWORD(wp) == EN_CHANGE && (id == 302 || id == 303 || id == 315)) || - id == 310 || id == 311 || id == 314)) - value(w, 319, L""); if (id == 314) { bool restricted = IsDlgButtonChecked(w, 314) == BST_CHECKED; @@ -2278,38 +2489,9 @@ bool snippetCommand(HWND w, SnippetView *v, WPARAM wp, bool embedded) } return true; } - if (id == 312 || id == 313) - { - if (v->selection < 0 || v->selection >= (int)v->snippets.size()) return true; - 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); - if (embedded) - { - fillSnippets(w, v); - value(w, 319, L"Snippets saved."); - } - else DestroyWindow(w); - return true; - } - if (!embedded && id == IDCANCEL) - { - DestroyWindow(w); + if (v->selection >= 0 && v->selection < (int)v->snippets.size()) showSnippetInsertion(w, *v->app); return true; } return false; @@ -2334,15 +2516,8 @@ void createSnippetEditor(HWND w, SnippetView *view, bool embedded) 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); - if (embedded) - { - button(w, L"Sa&ve snippets", SaveSnippets, 572, actions, 112); - control(w, L"STATIC", L"", 0, 319, 232, actions + 33, 452, 24); - } - else + button(w, L"Insert ¯o or marker…", SnippetMacros, 232, actions, 202); + if (!embedded) { button(w, L"&Save", IDOK, 474, actions + 44, 100); button(w, L"&Cancel", IDCANCEL, 584, actions + 44, 100); @@ -2384,7 +2559,22 @@ LRESULT CALLBACK snippetProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) drawActionApplicationIcon(w, *reinterpret_cast(lp)); return TRUE; } - if (msg == WM_COMMAND && snippetCommand(w, v, wp, false)) return 0; + if (msg == WM_COMMAND) + { + if (LOWORD(wp) == IDOK) + { + auto settings = v->app->settings; + if (mergeSnippetDraft(w, v, settings)) + { + if (v->app->busy) throw std::runtime_error("Wait for the current operation"); + v->app->applySettings(settings); + } + DestroyWindow(w); + return 0; + } + if (LOWORD(wp) == IDCANCEL) { DestroyWindow(w); return 0; } + if (snippetCommand(w, v, wp)) return 0; + } if (msg == WM_CLOSE) { DestroyWindow(w); diff --git a/src/update.h b/src/update.h index 93c52b6..1d2b1c7 100644 --- a/src/update.h +++ b/src/update.h @@ -2,7 +2,7 @@ #include "platform.h" namespace ks { -inline constexpr wchar_t AppVersion[] = L"0.6.131"; +inline constexpr wchar_t AppVersion[] = L"0.6.132"; inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; diff --git a/tests/chat_profiles.cpp b/tests/chat_profiles.cpp index 9cc06f0..536bea9 100644 --- a/tests/chat_profiles.cpp +++ b/tests/chat_profiles.cpp @@ -193,6 +193,186 @@ void contextChecks() require(hook.update(VK_LSHIFT, true, MOD_ALT | MOD_CONTROL, true) == 0, "do not consume Ctrl+Alt+Shift"); require(hook.update('A', true, MOD_ALT, true) == 0, "ordinary keys pass"); } +void snippetEditorChecks(ks::App &app, const std::filesystem::path &root) +{ + app.settings.snippets = {{L";scope", L"Example{pause:50}", L"scope-fixture"}}; + ks::showSettings(app); + HWND parent = app.settingsWindow; + auto saveEnabled = [&] { return IsWindowEnabled(GetDlgItem(parent, IDOK)); }; + auto status = [&] { + wchar_t text[256]{}; + GetDlgItemTextW(parent, 261, text, 256); + return std::wstring(text); + }; + require(!saveEnabled(),"Settings starts clean before editing a snippet"); + ks::showSnippets(app); + HWND snippets = parent; + require(!app.snippetsWindow && IsWindowVisible(GetDlgItem(snippets, 301)), + "opening Snippets from Settings selects its inline editor"); + SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0); + SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0); + require(!GetDlgItem(snippets, 318), "inline editor has only the Settings Save button"); + require(!saveEnabled() && status()==L"No unsaved settings.", "selecting a snippet leaves the editor clean"); + const auto replacement = GetDlgItem(snippets, 303); + auto replaceSnippetText = [&](const wchar_t *text) { + SendMessageW(replacement, EM_SETSEL, 0, -1); + SendMessageW(replacement, EM_REPLACESEL, TRUE, reinterpret_cast(text)); + }; + auto selectInsertion = [](HWND picker, int action) { + SendDlgItemMessageW(picker, 321, CB_SETCURSEL, action, 0); + SendMessageW(picker, WM_COMMAND, MAKEWPARAM(321, CBN_SELCHANGE), 0); + }; + auto openInsertion = [&](int action) { + SendMessageW(snippets, WM_COMMAND, 320, 0); + const auto picker = findTestWindow(L"KSwitcher.SnippetInsertion", nullptr); + require(picker && !IsWindowEnabled(snippets), "insertion picker opens over the snippet editor"); + selectInsertion(picker, action); + return picker; + }; + auto captureInsertion = [](HWND picker, const wchar_t *file) { + RedrawWindow(picker, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN); + RECT client{}; + GetClientRect(picker, &client); + auto dc = GetDC(picker); + auto image = ks::screenshotClip(dc, client.right, client.bottom, {}); + ReleaseDC(picker, dc); + ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / file, + ks::encodePng(ks::decodeImage(image))); + }; + SendMessageW(replacement, EM_SETSEL, 7, -1); + auto insertion = openInsertion(0); + const auto parameter = GetDlgItem(insertion, 323); + RECT actionRect{}, markerParameter{}, pauseParameter{}, dialog{}; + GetWindowRect(GetDlgItem(insertion, 321), &actionRect); + GetWindowRect(parameter, &markerParameter); + GetClientRect(insertion, &dialog); + require(IsWindowVisible(parameter) && !IsWindowEnabled(parameter), "cursor marker keeps a visible disabled parameter"); + require(actionRect.top == markerParameter.top && actionRect.right < markerParameter.left && + dialog.bottom < MulDiv(170, GetDpiForWindow(insertion), 96), "compact picker places Action and Parameter on one row"); + captureInsertion(insertion, L"snippet-insertion-marker.png"); + selectInsertion(insertion, 2); + GetWindowRect(parameter, &pauseParameter); + require(IsWindowVisible(parameter) && IsWindowEnabled(parameter) && EqualRect(&markerParameter, &pauseParameter), + "pause enables its parameter without moving the field"); + require(pauseParameter.right - pauseParameter.left <= MulDiv(70, GetDpiForWindow(insertion), 96) && + SendMessageW(parameter, EM_GETLIMITTEXT, 0, 0) == 5, "pause uses a compact field limited to five digits"); + SetDlgItemTextW(insertion, 323, L"10001"); + require(!IsWindowEnabled(GetDlgItem(insertion, IDOK)), "invalid pause cannot be inserted"); + SetDlgItemTextW(insertion, 323, L"10000"); + require(IsWindowEnabled(GetDlgItem(insertion, IDOK)), "five-digit maximum pause fits the numeric field"); + SetDlgItemTextW(insertion, 323, L"100"); + require(IsWindowEnabled(GetDlgItem(insertion, IDOK)), "valid pause enables Insert"); + captureInsertion(insertion, L"snippet-insertion.png"); + SendMessageW(insertion, WM_COMMAND, IDOK, 0); + require(saveEnabled() && status().find(L"Unsaved snippets") == 0, + "editing just the pause enables the Settings Save button"); + auto replacementText = [&] { + wchar_t text[256]{}; + GetWindowTextW(replacement, text, 256); + return std::wstring(text); + }; + require(replacementText() == L"Example{pause:100}", "insertion replaces the selected pause"); + insertion = openInsertion(4); + RECT chordParameter{}; + GetWindowRect(GetDlgItem(insertion, 323), &chordParameter); + require(chordParameter.right - chordParameter.left > pauseParameter.right - pauseParameter.left && + SendDlgItemMessageW(insertion, 323, EM_GETLIMITTEXT, 0, 0) > 5, "key combinations retain a wider input"); + require((GetWindowLongPtrW(GetDlgItem(insertion, 323), GWL_STYLE) & ES_READONLY) && + !IsWindowEnabled(GetDlgItem(insertion, IDOK)), "key recorder starts empty and rejects typed text"); + auto record = [](HWND picker, std::initializer_list keys) { + SendDlgItemMessageW(picker, 323, WM_KEYUP, VK_SPACE, 0); + for (auto key : keys) SendMessageW(picker, WM_APP + 160, key, TRUE); + for (auto key : keys) SendMessageW(picker, WM_APP + 160, key, FALSE); + }; + record(insertion, {VK_LCONTROL}); + require(!IsWindowEnabled(GetDlgItem(insertion, IDOK)), "one pressed key cannot supply a combination"); + auto keyText = [&] { + wchar_t text[32]{}; + GetDlgItemTextW(insertion, 323, text, 32); + return std::wstring(text); + }; + SendDlgItemMessageW(insertion, 323, WM_KEYUP, VK_SPACE, 0); + SendMessageW(insertion, WM_APP + 160, VK_LCONTROL, TRUE); + require(keyText() == L"Ctrl", "first key appears before release"); + SendMessageW(insertion, WM_APP + 160, VK_RETURN, TRUE); + require(keyText() == L"Ctrl+Enter" && !IsWindowEnabled(GetDlgItem(insertion, IDOK)), + "the entire chord appears while keys are still held"); + captureInsertion(insertion, L"snippet-key-held.png"); + SendMessageW(insertion, WM_APP + 160, VK_LCONTROL, FALSE); + require(keyText() == L"Ctrl+Enter" && !IsWindowEnabled(GetDlgItem(insertion, IDOK)), + "releasing one key keeps the chord visible while recording finishes"); + SendMessageW(insertion, WM_APP + 160, VK_RETURN, FALSE); + require(IsWindowEnabled(GetDlgItem(insertion, IDOK)), "recorded Ctrl+Enter enables insertion"); + captureInsertion(insertion, L"snippet-key-recorded.png"); + SendMessageW(insertion, WM_COMMAND, IDOK, 0); + require(replacementText() == L"Example{pause:100}{{ctrl}}+{{return}}", "chord converts Enter to the supported key spelling"); + insertion = openInsertion(1); + require(IsWindowVisible(GetDlgItem(insertion, 323)) && !IsWindowEnabled(GetDlgItem(insertion, 323)), + "Enter marker keeps its parameter visible and disabled"); + SendMessageW(insertion, WM_COMMAND, IDOK, 0); + insertion = openInsertion(0); + SendMessageW(insertion, WM_COMMAND, IDOK, 0); + require(replacementText().ends_with(L"{enter}{cursor}"), "Enter and cursor markers use the same picker"); + insertion = openInsertion(3); + record(insertion, {VK_RSHIFT}); + wchar_t keyName[32]{}; + GetDlgItemTextW(insertion, 323, keyName, 32); + require(std::wstring(keyName) == L"ShiftR" && IsWindowEnabled(GetDlgItem(insertion, IDOK)), + "tap recording recognizes a right-hand modifier by itself"); + SendMessageW(insertion, WM_COMMAND, IDCANCEL, 0); + require(replacementText().ends_with(L"{enter}{cursor}"), "cancelling insertion preserves replacement text"); + replaceSnippetText(L"Example{pause:50}"); + require(!saveEnabled() && status()==L"No unsaved settings.", "reverting the pause clears the pending change"); + replaceSnippetText(L"Example{pause:100}"); + 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); + SendMessageW(snippets,WM_COMMAND,317,0); + SendMessageW(snippets,WM_COMMAND,317,0); + 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 savedScope{L"notepad", L"ms-teams", pickedProcess}; + RedrawWindow(snippets,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN); + RECT snippetRect{};GetClientRect(snippets,&snippetRect); + HDC snippetDc=GetDC(snippets); + auto snippetImage=ks::screenshotClip(snippetDc,snippetRect.right,snippetRect.bottom,{}); + ReleaseDC(snippets,snippetDc); + ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"snippet-scopes.png",ks::encodePng(ks::decodeImage(snippetImage))); + const auto logSetting = !app.settings.writeLog; + CheckDlgButton(parent, 208, logSetting ? BST_CHECKED : BST_UNCHECKED); + SendMessageW(parent, WM_COMMAND, MAKEWPARAM(208, BN_CLICKED), 0); + SendMessageW(parent, WM_COMMAND, IDOK, 0); + require(!IsWindow(parent), "Settings Save closes the inline snippet editor"); + const auto savedSettings = ks::loadSettings(root / L"settings.json", app.layouts); + require(savedSettings.snippets[0].apps == savedScope && savedSettings.snippets[0].text == L"Example{pause:100}" && + savedSettings.writeLog == logSetting, "one Save persists the snippet and general settings together"); + ks::showSnippets(app);snippets=app.snippetsWindow; + SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0); + 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"); +} } int main(int argc,char **argv) { @@ -207,6 +387,23 @@ int main(int argc,char **argv) CoUninitialize(); return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--snippets") + { + { + ks::App app(GetModuleHandleW(nullptr), true, root); + if (app.layouts.empty()) app.layouts.push_back({nullptr, L"win:04090409", L"English"}); + app.settings.cycle = {app.layouts.front().id}; + app.settings.toggle = app.settings.casing = app.settings.translit = app.settings.undo = L""; + app.settings.clipboard = app.settings.screenshot = L""; + app.settings.direct.assign(app.layouts.size(), L""); + app.settings.history = app.settings.autoCorrect = false; + snippetEditorChecks(app, root); + } + std::filesystem::remove_all(root); + CoUninitialize(); + std::cout << "PASS snippet editor (" << passed << " checks)\n"; + return 0; + } contextChecks(); { ks::App app(GetModuleHandleW(nullptr), true, root); @@ -427,59 +624,7 @@ int main(int argc,char **argv) SendMessageW(parent, WM_COMMAND, IDOK, 0); require(!ks::applicationLanguageSet(app.settings, L"codex"), "use defaults removes only selected application profile"); require(ks::applicationLanguageSet(app.settings, L"notepad") != nullptr, "default reset leaves other application profile intact"); - app.settings.snippets = {{L";scope", L"Example", L"scope-fixture"}}; - ks::showSettings(app); parent=app.settingsWindow; - require(!saveEnabled(),"Settings starts clean before separately saved snippet edit"); - ks::showSnippets(app); - HWND snippets = parent; - require(!app.snippetsWindow && IsWindowVisible(GetDlgItem(snippets, 301)), - "opening Snippets from Settings selects its inline editor"); - 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); - SendMessageW(snippets,WM_COMMAND,317,0); - SendMessageW(snippets,WM_COMMAND,317,0); - 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 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(!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); - HDC snippetDc=GetDC(snippets); - auto snippetImage=ks::screenshotClip(snippetDc,snippetRect.right,snippetRect.bottom,{}); - ReleaseDC(snippets,snippetDc); - ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"snippet-scopes.png",ks::encodePng(ks::decodeImage(snippetImage))); - SendMessageW(parent,WM_COMMAND,IDCANCEL,0); - ks::showSnippets(app);snippets=app.snippetsWindow; - SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0); - 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"); + snippetEditorChecks(app, root); ks::showSettings(app);parent=app.settingsWindow; SendMessageW(parent,WM_COMMAND,262,0); HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr); diff --git a/tests/clipboard_snapshot.cpp b/tests/clipboard_snapshot.cpp index d26f978..1cc662d 100644 --- a/tests/clipboard_snapshot.cpp +++ b/tests/clipboard_snapshot.cpp @@ -4,6 +4,8 @@ #include #include #include +#include +#include static void require(bool ok, const char *name) { if (!ok) throw std::runtime_error(name); std::cout << "PASS " << name << '\n'; @@ -39,6 +41,58 @@ static void verifyImage(HWND w) { } require(c.text()==L"Snapshot mixed text","preserves accompanying text"); } +static LRESULT CALLBACK delayedImageOwner(HWND window, UINT message, WPARAM format, LPARAM param) { + if (message == WM_RENDERFORMAT && format == CF_DIB) { + const auto dib = ks::imageDib(ks::Pixels{1, 1, ks::Bytes{77, 0, 0, 255}}); + if (auto data = GlobalAlloc(GMEM_MOVEABLE, dib.data.size())) { + if (auto bytes = GlobalLock(data)) { + memcpy(bytes, dib.data.data(), dib.data.size()); + GlobalUnlock(data); + if (SetClipboardData(CF_DIB, data)) return 0; + } + GlobalFree(data); + } + return 0; + } + return DefWindowProcW(window, message, format, param); +} +static void verifyDelayedImageSnapshot(HWND window) { + std::promise ready; + auto owner = ready.get_future(); + std::jthread publisher([&] { + WNDCLASSW wc{}; + wc.lpfnWndProc = delayedImageOwner; + wc.hInstance = GetModuleHandleW(nullptr); + wc.lpszClassName = L"KSwitcher.DelayedClipboardFixture"; + HWND delayed = RegisterClassW(&wc) ? CreateWindowExW(0, wc.lpszClassName, L"", 0, 0, 0, 0, 0, + HWND_MESSAGE, nullptr, wc.hInstance, nullptr) : nullptr; + bool published = false; + if (delayed && OpenClipboard(delayed)) { + if (EmptyClipboard()) SetClipboardData(CF_DIB, nullptr); + published = IsClipboardFormatAvailable(CF_DIB) && GetClipboardOwner() == delayed; + CloseClipboard(); + } + ready.set_value(published ? delayed : nullptr); + if (published) { + MSG message{}; + while (GetMessageW(&message, delayed, 0, 0) > 0 && message.message != WM_CLOSE) + DispatchMessageW(&message); + } + if (delayed) DestroyWindow(delayed); + }); + const auto delayed = owner.get(); + require(delayed != nullptr, "publishes a delayed image format"); + struct CloseOwner { HWND window; ~CloseOwner() { PostMessageW(window, WM_CLOSE, 0, 0); } } close{delayed}; + const auto before = GetClipboardSequenceNumber(); + ks::ClipboardSnapshot snapshot; + const auto captured = snapshot.capture(window, before); + require(captured == GetClipboardSequenceNumber(), "snapshot reports the sequence after delayed rendering"); + const auto temporary = ks::writeClipboard(window, ks::textClip(L"temporary")); + snapshot.restore(window, temporary); + const auto clip = ks::readClipboard(window); + const auto image = ks::decodeImage(clip); + require(image.width == 1 && image.height == 1 && image.bgra.front() == 77, "restores the delayed image"); +} int main(int argc,char**argv) { CoInitializeEx(nullptr,COINIT_MULTITHREADED); HWND w=owner(); int result=0; ks::Clip original; bool saved=false; @@ -90,8 +144,11 @@ int main(int argc,char**argv) { require(rejected,"resident rejects images before reading their data"); { ks::ClipboardSnapshot snapshot; - try {snapshot.capture(w,seq-1); rejected=false;} catch(...) {rejected=true;} - require(rejected,"stale image snapshot is rejected"); + try {snapshot.capture(w,seq-1); rejected=false;} + catch(const std::runtime_error &error) { + rejected=std::string_view(error.what()).find("Clipboard changed while taking snapshot") != std::string_view::npos; + } + require(rejected,"stale image snapshot reports the sequence mismatch"); snapshot.capture(w,seq); } require(GetClipboardSequenceNumber()==seq,"discarding an image snapshot leaves the clipboard untouched"); @@ -117,6 +174,7 @@ int main(int argc,char**argv) { auto marked=ks::textClip(L"line"); marked.formats.push_back({0,L"MSDEVLineSelect",ks::Bytes{1}}); ks::writeClipboard(w,marked); require(ks::readClipboard(w,1024,ks::ClipboardRead::Selection).formats.size()==2,"selection reader preserves editor guard metadata"); + verifyDelayedImageSnapshot(w); std::cout<<"PASS clipboard snapshot suite\n"; } } catch(const std::exception &e) {std::cerr<<"FAIL "<