From 7626e6c9c2494286aed0db4cf2fed1911abdf19e Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Sat, 21 Nov 2026 23:45:42 +0200 Subject: [PATCH] Release KSwitcher v0.6.126 (#72) Ship literal snippet key presses and the configured pause without application-specific suggestion handling. --- CMakeLists.txt | 2 +- README.md | 10 +-- Release/README.md | 10 ++- Release/SHA256SUMS.txt | 2 +- Release/release-files.json | 18 ++-- resources/app.rc | 6 +- src/app.cpp | 125 ++++++++++++-------------- src/snippet_skill.h | 178 ------------------------------------- src/ui.cpp | 6 +- src/update.h | 2 +- tests/integration.cpp | 33 +++++-- tests/tests.cpp | 2 +- 12 files changed, 117 insertions(+), 277 deletions(-) delete mode 100644 src/snippet_skill.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 8a22701..5b10506 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.6.125 LANGUAGES CXX RC) +project(KSwitcher VERSION 0.6.126 LANGUAGES CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() diff --git a/README.md b/README.md index 7b2aaaa..86ff664 100644 --- a/README.md +++ b/README.md @@ -495,23 +495,23 @@ 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 verifies each inserted text segment before running the macros that follow it. A leading macro runs after the first text segment, as in earlier versions. A snippet needs some replacement text. +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 перевіряє кожну вставлену частину тексту перед виконанням наступних макросів. Макрос на початку, як і раніше, виконується після першої частини тексту. Сніпет має містити текст заміни. +**Українською.** Додавай макроси в текст заміни в **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}}}`, щоб вставити відповідний маркер як звичайний текст. -In Codex, `$skill-name{pause:500}{enter} Draft text{cursor}` selects the matching skill suggestion and then inserts the draft. Further Enter markers at the same position have no effect. If the suggestion cannot be verified, expansion stops at the skill name. +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. -У Codex `$skill-name{pause:500}{enter} Текст чернетки{cursor}` вибирає відповідний скіл зі списку підказок і далі вставляє чернетку. Повторні маркери Enter в тій самій позиції не спрацьовують. Якщо підказку не вдалося перевірити, розгортання зупиняється на назві скіла. +Наприклад, `$skill-name{pause:500}{enter} Текст чернетки{cursor}` вводить назву, чекає 500 мілісекунд, натискає Enter один раз і вводить чернетку. Enter обробляє програма у фокусі. Кожен `{enter}` надсилає окреме натискання. ### Application-specific snippets — v0.6.51 @@ -560,7 +560,7 @@ Scopes are saved with snippets and included in manual import/export and synchron repeat-conversion state and does not switch the Windows layout. - Case cycling, Russian/Ukrainian transliteration, verified undo and repeated conversion. - Text snippets across layouts, multiline insertion and a verified `{cursor}` position; - macros run between verified text segments, before buffered typing resumes. + macros run between text segments, before buffered typing resumes. Automatic correction is suppressed during snippet expansion and for typing buffered by that expansion; the global setting is preserved. If the trigger cannot be verified after the copy attempts, it is preserved, queued typing resumes, and no key actions are sent. Snippets are stored as plaintext settings, as in [Typlo](https://github.com/bitcodepro/Typlo). diff --git a/Release/README.md b/Release/README.md index 5c953b7..01f8a1d 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,6 +1,14 @@ # Latest Windows release -## v0.6.125 — 2026-11-21 +## v0.6.126 — 2026-11-21 + +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. diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index 706bbff..6b53f89 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -c0418b28d5bbfa6ac7c4ff8b76addc58e5b6abdf1c192895014a35d92424e13d KSwitcher-win-x64.zip +6d948270b424483b3923e3f15b6e97f0aa6de8ab9038f91a8b8d92af3b45e4fc KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index 5958dc6..ac76355 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,25 +1,25 @@ { - "version": "0.6.125", + "version": "0.6.126", "files": [ { "path": "KSwitcher.exe", - "size": 2497536, - "sha256": "c66a11c095c15a7d80d15ca0e19adeb284db65134babb3b403998d6756444b3d" + "size": 2491904, + "sha256": "03834ebd6f64d04e483d07b4cabff23a8a6d7a0fcb4b20a29dddb7f382951afb" }, { "path": "KSwitcher.Config.exe", "size": 2462720, - "sha256": "bac341c5ef616ea90462e70f82e25e4b2a5550019d1bd8d729d311e41583f64a" + "sha256": "255762c1fa98b8e01de66794c5870c939e7beaa9115e0ff3d32a89a254be68b0" }, { "path": "KSwitcher.Screenshot.exe", "size": 3063808, - "sha256": "c1b0c9aec507110d6949736b7e2beb9f83065c4153d53a4f0f1bb5f110f811a6" + "sha256": "e2254ce28a2e943530c0307be84706639d1bb3eb097479c2beae6c4f37724555" }, { "path": "KSwitcher.Files.exe", "size": 4377088, - "sha256": "04db22229e93f01a482d3040b21854cd88ceb5dd6c84e3ec5928c2d3e5bb3099" + "sha256": "6e28d6bc10b10f16a71fef06730c5c0d25f2e66ada1d8c77b131f0451321520b" }, { "path": "WebView2Loader.dll", @@ -108,8 +108,8 @@ }, { "path": "README.md", - "size": 99184, - "sha256": "2c37fa1783e45c8ea874801aa1ac74a9b02bf75690c7ae6c9aa0184215bf4604" + "size": 98985, + "sha256": "755b91fa671fbaee2d4336e22538997dd3ba6fddd9df01471ba6b74f38edfa83" }, { "path": "LAN-PREVIEW.md", @@ -154,7 +154,7 @@ { "path": "tools/StayHere.exe", "size": 133120, - "sha256": "658052ec21e9a5619339f6036d11db8c75d8065666669245af123c5d906a7846" + "sha256": "50ff530d296956cc31f2310bcc4215ea47f7ffb2cf7d7ab07e24bf56fdc6d60c" }, { "path": "tools/StayHere-README.md", diff --git a/resources/app.rc b/resources/app.rc index 809cba0..fcaca14 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -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,125,0 - PRODUCTVERSION 0,6,125,0 + FILEVERSION 0,6,126,0 + PRODUCTVERSION 0,6,126,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.125" + VALUE "FileVersion", "0.6.126" END END BLOCK "VarFileInfo" diff --git a/src/app.cpp b/src/app.cpp index 82eb57c..5fb3e81 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -8,7 +8,6 @@ #include "configuration.h" #include "diagnostics.h" #include "paste_probe.h" -#include "snippet_skill.h" #include "utilities.h" #include "screenshot_notifications.h" #include @@ -234,6 +233,28 @@ 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 &valid) +{ + constexpr size_t batchSize = 64; + for (size_t offset = 0; offset < text.size(); offset += batchSize) + { + std::vector 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(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 { @@ -696,14 +717,6 @@ class Transaction check(); return true; } - bool insertSnippetText(const std::wstring &text, bool typeSkill) - { - if (!typeSkill) return paste(textClip(text)); - check(); - if (!valid() || !typeSnippetSkill(text)) return false; - Sleep(75); - return valid(); - } bool nativeSelectionIs(const std::wstring &original) const { if (!valid()) return false; @@ -2468,7 +2481,6 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet L" id=" + std::to_wstring(attempt)); bool automatic = false; Template snippetTemplate; - bool codexSnippet = false; if (command == AutoCorrect) { // The editor must select the complete previous word. Unlike manual @@ -2539,7 +2551,6 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet const auto &sn = config.snippets[snippet]; const auto process = lower(processName(target)); if (!snippetAppPriority(sn, process)) return; - codexSnippet = process == L"codex" || process == L"chatgpt"; const auto length = snippetLength ? snippetLength : sn.trigger.size(); if (recent.keys.size() < length) return; @@ -2695,23 +2706,23 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet } diagnosticEvent(L"Conversion source=" + std::to_wstring(hint) + L" target=" + std::to_wstring(to) + L" changed=" + std::to_wstring(result != text)); - const auto skillToConfirm = [&](const std::wstring &segment, size_t end) - { - if (!codexSnippet) return std::wstring{}; - const auto &actions = snippetTemplate.actions; - auto action = std::lower_bound(actions.begin(), actions.end(), end, - [](const SnippetAction &candidate, size_t offset) { return candidate.offset < offset; }); - for (; action != actions.end() && action->offset == end; ++action) - { - const auto *keys = std::get_if>(&action->value); - if (keys && keys->size() == 1 && keys->front() == VK_RETURN) - return snippetSkillName(segment); - } - return std::wstring{}; + 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{}; }; - std::wstring pendingSkill = skillToConfirm(result, result.size()); + 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 = snippet >= 0 ? tx.insertSnippetText(result, !pendingSkill.empty()) : tx.paste(textClip(result)); + sent = typeFirst ? typeSnippetText(result, valid) : tx.paste(textClip(result)); else if (automatic && tx.valid()) tx.finishSelection(false); if (requireReadback && result != text && !sent) @@ -2731,9 +2742,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet reason = L"Conversion unchanged"; verification = L"calculated-result-equals-original"; } - // When Chromium exposes a focused suggestion rather than the - // composer, verify against the suggestion before invoking it. - if (sent && pendingSkill.empty() && ((manual && config.writeLog) || requireReadback)) + if (sent && !typeFirst && ((manual && config.writeLog) || requireReadback)) { verification = probe.status; if (tx.valid()) @@ -2747,7 +2756,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet if (!farSnippet && observed && newlines(*observed) == newlines(text) && tx.nativeSelectionIs(text)) { diagnosticEvent(L"Paste retry: native Edit still selects the unchanged original"); - if (pendingSkill.empty() && tx.paste(textClip(result)) && tx.valid()) + if (tx.paste(textClip(result)) && tx.valid()) observed = probe.read((int)caretSteps(result)); else observed.reset(); @@ -2798,64 +2807,48 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet } if (snippet >= 0 && sent && tx.valid()) { - const auto cursor = snippetTemplate.text.size() - snippetTemplate.suffix.size(); - auto cursorSuffix = [&](size_t start, size_t end) { - return cursor >= start && cursor < end ? - snippetTemplate.text.substr(cursor, end - cursor) : std::wstring{}; - }; - tx.check(); size_t emitted = result.size(); - if (!placeSnippetCursor(tx, cursorSuffix(0, emitted))) return; - if (!snippetTemplate.actions.empty()) + if (!clipboardRestored) { tx.check(); - // Clipboard shortcuts must see the user's clipboard, and - // any copies they make must survive the transaction. - tx.restoreClipboard(); - suspended = false; + 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; + } } auto insertSegment = [&](size_t end) { if (end == emitted) return true; if (!tx.valid()) return false; - Transaction segmentTx(*this, target, version, farSnippet, snippetEditor); const auto segment = snippetTemplate.text.substr(emitted, end - emitted); - pendingSkill = skillToConfirm(segment, end); - if (!segmentTx.insertSnippetText(segment, !pendingSkill.empty()) || !segmentTx.valid()) - return false; - if (pendingSkill.empty()) + 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(count)); - if (!actual || !segmentTx.valid() || newlines(*actual) != newlines(segment)) + if (!actual || !segmentTx.valid() || newlines(*actual) != newlines(segment) || + !placeSnippetCursor(segmentTx, suffix)) return false; } - if (!placeSnippetCursor(segmentTx, cursorSuffix(emitted, end))) return false; emitted = end; return true; }; - bool skillSelected = false; for (const auto &action : snippetTemplate.actions) { if (!tx.valid()) return; - if (emitted != action.offset) - { - if (!insertSegment(action.offset)) return; - skillSelected = false; - } + if (!insertSegment(action.offset)) return; if (const auto *keys = std::get_if>(&action.value)) { - if (!pendingSkill.empty() && keys->size() == 1 && keys->front() == VK_RETURN) - { - if (!skillSelected && !selectSnippetSkill(pendingSkill, target, valid)) - { - reason = L"snippet-skill-suggestion-unavailable"; - report(L"KSwitcher could not select the Codex skill. Choose it from the suggestions and continue your draft."); - return; - } - skillSelected = true; - continue; - } if (!chord(*keys)) throw std::runtime_error("Windows could not send all snippet keys"); } diff --git a/src/snippet_skill.h b/src/snippet_skill.h deleted file mode 100644 index 4bf1b82..0000000 --- a/src/snippet_skill.h +++ /dev/null @@ -1,178 +0,0 @@ -#pragma once -#include "platform.h" -#include -#include -#include -#include - -namespace ks -{ -inline std::wstring snippetSkillName(std::wstring_view text) -{ - if (!text.starts_with(L'$') || text.size() < 2) return {}; - auto name = lower(std::wstring(text.substr(1))); - if (name.find_first_not_of(L"abcdefghijklmnopqrstuvwxyz0123456789-_.") != name.npos) - return {}; - return name; -} - -inline bool typeSnippetSkill(std::wstring_view text) -{ - std::vector inputs; - inputs.reserve(2 * text.size()); - for (wchar_t ch : text) - for (DWORD flags : {DWORD{0}, DWORD{KEYEVENTF_KEYUP}}) - { - auto input = keyboardInput(0, flags | KEYEVENTF_UNICODE); - input.ki.wScan = ch; - inputs.push_back(input); - } - return SendInput(static_cast(inputs.size()), inputs.data(), sizeof(INPUT)) == inputs.size(); -} - -enum class SnippetSkillMatch { None, LabelWithDescription, Exact }; - -inline SnippetSkillMatch snippetSkillLabelMatch(IUIAutomationElement *item, const std::wstring &name) -{ - BSTR label{}; - if (FAILED(item->get_CurrentName(&label))) return SnippetSkillMatch::None; - auto candidate = lower(std::wstring(label ? label : L"", SysStringLen(label))); - SysFreeString(label); - if (candidate.size() < name.size() || - (candidate.size() > name.size() && candidate[name.size()] != L' ')) - return SnippetSkillMatch::None; - auto end = candidate.begin() + name.size(); - std::replace(candidate.begin(), end, L' ', L'-'); - if (candidate.compare(0, name.size(), name) != 0) return SnippetSkillMatch::None; - return candidate.size() == name.size() ? SnippetSkillMatch::Exact : SnippetSkillMatch::LabelWithDescription; -} - -inline std::vector> -snippetSuggestionLists(IUIAutomation *automation, IUIAutomationElement *focused) -{ - using Microsoft::WRL::ComPtr; - std::vector> result; - ComPtr controlled; - int count{}; - if (SUCCEEDED(focused->get_CurrentControllerFor(&controlled)) && controlled) - controlled->get_Length(&count); - for (int i = 0; i < count; ++i) - { - ComPtr list; - if (SUCCEEDED(controlled->GetElement(i, &list)) && list) - result.push_back(list); - } - if (!result.empty()) return result; - // Chromium can expose the active descendant of the combobox as the - // focused element. In that case follow the option to its owning listbox. - CONTROLTYPEID type{}; - if (FAILED(focused->get_CurrentControlType(&type)) || type != UIA_ListItemControlTypeId) - return result; - ComPtr walker; - if (FAILED(automation->get_RawViewWalker(&walker)) || !walker) return result; - ComPtr node = focused; - for (int i = 0; i < 6; ++i) - { - ComPtr parent; - if (FAILED(walker->GetParentElement(node.Get(), &parent)) || !parent) - break; - BSTR role{}; - if (SUCCEEDED(parent->get_CurrentAriaRole(&role))) - { - const bool listbox = role && std::wstring_view(role, SysStringLen(role)) == L"listbox"; - SysFreeString(role); - if (listbox) - { - result.push_back(parent); - break; - } - } - node = parent; - } - return result; -} - -inline bool selectSnippetSkill(const std::wstring &name, HWND target, const std::function &valid) -{ - using Microsoft::WRL::ComPtr; - const auto deadline = GetTickCount64() + 500; - ComPtr automation; - if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER, IID_IUIAutomation2, - reinterpret_cast(automation.GetAddressOf())))) - return false; - automation->put_ConnectionTimeout(150); - automation->put_TransactionTimeout(150); - VARIANT roleValue{}; - roleValue.vt = VT_I4; - roleValue.lVal = UIA_ListItemControlTypeId; - ComPtr listItem; - if (FAILED(automation->CreatePropertyCondition(UIA_ControlTypePropertyId, roleValue, &listItem))) - return false; - roleValue.lVal = UIA_TextControlTypeId; - ComPtr textItem; - if (FAILED(automation->CreatePropertyCondition(UIA_ControlTypePropertyId, roleValue, &textItem))) - return false; - DWORD targetProcess{}; - GetWindowThreadProcessId(target, &targetProcess); - while (valid() && GetTickCount64() < deadline) - { - ComPtr focused; - int process{}; - if (FAILED(automation->GetFocusedElement(&focused)) || !focused || - FAILED(focused->get_CurrentProcessId(&process)) || static_cast(process) != targetProcess) - return false; - ComPtr option; - auto bestMatch = SnippetSkillMatch::None; - bool ambiguous = false; - for (const auto &list : snippetSuggestionLists(automation.Get(), focused.Get())) - { - CONTROLTYPEID role{}; - if (FAILED(list->get_CurrentControlType(&role)) || role != UIA_ListControlTypeId) - continue; - ComPtr items; - int length{}; - if (FAILED(list->FindAll(TreeScope_Descendants, listItem.Get(), &items)) || !items || - FAILED(items->get_Length(&length))) - continue; - for (int index = 0; index < length; ++index) - { - ComPtr item; - BOOL offscreen = TRUE, enabled = FALSE; - if (FAILED(items->GetElement(index, &item)) || !item || - FAILED(item->get_CurrentIsOffscreen(&offscreen)) || offscreen || - FAILED(item->get_CurrentIsEnabled(&enabled)) || !enabled) - continue; - auto match = snippetSkillLabelMatch(item.Get(), name); - if (match != SnippetSkillMatch::Exact) - { - ComPtr caption; - if (SUCCEEDED(item->FindFirst(TreeScope_Descendants, textItem.Get(), &caption)) && - caption && snippetSkillLabelMatch(caption.Get(), name) == SnippetSkillMatch::Exact) - match = SnippetSkillMatch::Exact; - } - if (match == SnippetSkillMatch::None || match < bestMatch) continue; - if (match > bestMatch) - { - option = item; - bestMatch = match; - ambiguous = false; - } - else ambiguous = true; - } - } - if (option && !ambiguous && valid()) - { - ComPtr invoke; - if (SUCCEEDED(option->GetCurrentPatternAs(UIA_InvokePatternId, IID_IUIAutomationInvokePattern, - reinterpret_cast(invoke.GetAddressOf()))) && invoke) - return valid() && SUCCEEDED(invoke->Invoke()); - ComPtr accessible; - return SUCCEEDED(option->GetCurrentPatternAs(UIA_LegacyIAccessiblePatternId, - IID_IUIAutomationLegacyIAccessiblePattern, reinterpret_cast(accessible.GetAddressOf()))) && - accessible && valid() && SUCCEEDED(accessible->DoDefaultAction()); - } - Sleep(25); - } - return false; -} -} diff --git a/src/ui.cpp b/src/ui.cpp index be3dbf2..ac2306f 100644 --- a/src/ui.cpp +++ b/src/ui.cpp @@ -2264,12 +2264,10 @@ bool snippetCommand(HWND w, SnippetView *v, WPARAM wp, bool embedded) if (id == SnippetMacros) { MessageBoxW(w, - L"Macros run where they appear in the replacement text.\n" - L"In Codex, $skill{pause:500}{enter} Draft text selects a matching skill " - L"and leaves the rest as a draft.\n\n" + L"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: {enter} or {{return}} in a combination\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); diff --git a/src/update.h b/src/update.h index 2f660aa..6555e97 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.125"; +inline constexpr wchar_t AppVersion[] = L"0.6.126"; 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/integration.cpp b/tests/integration.cpp index 3a6782d..ba5b232 100644 --- a/tests/integration.cpp +++ b/tests/integration.cpp @@ -69,6 +69,9 @@ 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; @@ -187,7 +190,19 @@ 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 (message == WM_KEYDOWN && wp == VK_RETURN) ++enterPresses; + 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; + } return DefSubclassProc(w, message, wp, lp); } int stage = 0, ru = -1, en = -1; @@ -949,14 +964,18 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp) app->settings.autoCorrect = false; ActivateKeyboardLayout(app->layouts[en].handle, 0); require(ks::lower(ks::processName(host)) == L"chatgpt", - "Codex skill guard fixture runs under the desktop executable name"); - expandMacroSnippet(L"$example-skill{pause:50}{enter}{enter}{enter} Draft text{cursor}"); + "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" && enterPresses == 0, - "an unavailable skill suggestion cancels three Enter markers without sending the draft"); + 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, - "skill confirmation failure preserves the clipboard"); + "literal snippet actions restore the clipboard"); finish(); break; case 84: @@ -1324,7 +1343,7 @@ int main(int argc, char **argv) stage = 66; if (argc > 1 && std::string(argv[1]) == "--snippet-macros") stage = 80; - if (argc > 1 && std::string(argv[1]) == "--snippet-skill-guard") + if (argc > 1 && std::string(argv[1]) == "--snippet-literal-keys") stage = 93; if (argc > 1 && std::string(argv[1]) == "--snippet-word-boundaries") stage = 84; diff --git a/tests/tests.cpp b/tests/tests.cpp index 39bf440..adb8096 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -485,7 +485,7 @@ int main(int argc, char **argv) require(prompt.text == L"$example-skill Draft text" && prompt.suffix.empty() && prompt.actions == std::vector{{14, DWORD{500}}, {14, std::vector{VK_RETURN}}, {14, std::vector{VK_RETURN}}, {14, std::vector{VK_RETURN}}}, - "all skill confirmation markers precede the prompt draft"); + "all three Enter markers stay before the tail text"); 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");