Compare commits

...
Author SHA1 Message Date
agrynco 55405f79db Prepare KSwitcher v0.6.125
Run inline macros between verified text segments. Select the Codex skill suggestion directly and consume repeated Enter markers at the selection point. Record the verified release package manifest and checksum.
2026-11-21 23:33:10 +02:00
14 changed files with 402 additions and 83 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.124 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.125 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+7 -3
View File
@@ -495,20 +495,24 @@ 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 inserts and verifies the text, places `{cursor}`, then runs macros in the order written. A snippet needs some replacement text.
In **Settings → Snippets**, type macros into a snippet's replacement text. **Macro help…** sits beside the marker buttons below the editor, with **Save snippets** at the right. KSwitcher verifies each inserted text segment before running the macros that follow it. A leading macro runs after the first text segment, as in earlier versions. A snippet needs some replacement text.
- `{{shift}}`, `{{alt}}` and `{{tab}}` tap individual keys. Key names are case-insensitive. Letters, digits, `F1`–`F24`, navigation and editing keys also work.
- `{{altr}}+{{ctrl}}` holds both keys together. Join key markers with `+` without spaces and put modifiers before the final key, as in `{{ctrl}}+{{shift}}+{{A}}`. Use `l` or `r` after `ctrl`, `alt`, `shift` or `win` to select a side. The unsuffixed names use the left keys.
- `rider .{pause:50}{enter}` inserts `rider .`, waits 50 milliseconds, then presses Enter. One pause can be 0–10,000 milliseconds. Use `{{return}}` for Enter inside a chord, as in `{{ctrl}}+{{return}}`.
- Write `{{cursor}}`, `{{enter}}`, `{{pause:50}}` or `{{{shift}}}` to insert the corresponding marker literally.
**Українською.** Додавай макроси в текст заміни в **Settings → Snippets**. **Macro help…** розташована поруч із кнопками маркерів під редактором, а **Save snippets** — праворуч. KSwitcher вставляє й перевіряє текст, встановлює курсор за `{cursor}`, а далі виконує макроси в порядку запису. Сніпет має містити текст заміни.
**Українською.** Додавай макроси в текст заміни в **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.
У Codex `$skill-name{pause:500}{enter} Текст чернетки{cursor}` вибирає відповідний скіл зі списку підказок і далі вставляє чернетку. Повторні маркери Enter в тій самій позиції не спрацьовують. Якщо підказку не вдалося перевірити, розгортання зупиняється на назві скіла.
### Application-specific snippets — v0.6.51
In **Settings → Snippets**, select a snippet and enable **Only in these applications**. Enter executable names separated by commas, or select a currently open application's process and choose **Add app**. For example: `ms-teams.exe, outlook.exe`. Uncheck the option for a global snippet. A checked but empty restriction cannot be saved. Use **Save snippets** to apply the changes.
@@ -556,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;
after insertion and cursor placement, macros run in the order written, before buffered typing resumes.
macros run between verified text segments, before buffered typing resumes.
Automatic correction is suppressed during snippet expansion and for typing buffered by that expansion; the global setting is preserved.
If the trigger cannot be verified after the copy attempts, it is preserved, queued typing resumes,
and no key actions are sent. Snippets are stored as plaintext settings, as in [Typlo](https://github.com/bitcodepro/Typlo).
+8
View File
@@ -1,5 +1,13 @@
# Latest Windows release
## v0.6.125 — 2026-11-21
Snippet macros between text segments run before the next segment is inserted. In Codex, `$skill{pause:500}{enter} Draft text` selects the matching skill suggestion and leaves the following text in the composer. Extra Enter markers at the same selection point do not submit the draft. Expansion stops when the suggestion cannot be verified.
**Українською.**
Макроси між частинами сніпета виконуються перед вставленням наступної частини. У Codex `$skill{pause:500}{enter} Текст чернетки` вибирає відповідний скіл із підказок і залишає наступний текст у редакторі. Повторні маркери Enter у тій самій позиції не надсилають чернетку. Якщо підказку не вдалося перевірити, розгортання зупиняється.
## v0.6.124 — 2026-11-21
Snippets can tap keys such as `{{shift}}`, hold combinations such as `{{altr}}+{{ctrl}}`, and wait with `{pause:50}`. After verifying the inserted text and placing `{cursor}`, KSwitcher runs the macros in order. The Snippets tab groups marker buttons and **Macro help…** below the editor, with **Save snippets** at the right.
+1 -1
View File
@@ -1 +1 @@
17a584b5de09496bdfe7b1cd74e991b7a0e44f46198b4db72c241600df8643c9 KSwitcher-win-x64.zip
c0418b28d5bbfa6ac7c4ff8b76addc58e5b6abdf1c192895014a35d92424e13d KSwitcher-win-x64.zip
+41 -41
View File
@@ -1,166 +1,166 @@
{
"version": "0.6.124",
"schema": 1,
"version": "0.6.125",
"files": [
{
"size": 2489344,
"path": "KSwitcher.exe",
"sha256": "3a5537b81043a0bdbd6dc1b9c4c4b12ca538daf3a36c22c58a3d84b53c9929b7"
"size": 2497536,
"sha256": "c66a11c095c15a7d80d15ca0e19adeb284db65134babb3b403998d6756444b3d"
},
{
"size": 2463232,
"path": "KSwitcher.Config.exe",
"sha256": "220e722f5c09198c7392f10137c2bcc001b2f6f67776ebaf3291baf4d15144cc"
"size": 2462720,
"sha256": "bac341c5ef616ea90462e70f82e25e4b2a5550019d1bd8d729d311e41583f64a"
},
{
"size": 3064320,
"path": "KSwitcher.Screenshot.exe",
"sha256": "b706ff989e918053a62b49fc2c438293ea17b33c6e3f695be6deb1ac4e13bc44"
"size": 3063808,
"sha256": "c1b0c9aec507110d6949736b7e2beb9f83065c4153d53a4f0f1bb5f110f811a6"
},
{
"size": 4377088,
"path": "KSwitcher.Files.exe",
"sha256": "384c88517a5ab3c7db09cc737dc31d009a4fdf01a929d05e93869ddb22c5abd2"
"size": 4377088,
"sha256": "04db22229e93f01a482d3040b21854cd88ceb5dd6c84e3ec5928c2d3e5bb3099"
},
{
"size": 194912,
"path": "WebView2Loader.dll",
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
},
{
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
},
{
"size": 1521,
"path": "terminal/addon-fit.js",
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
},
{
"size": 527,
"path": "terminal/index.html",
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
},
{
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt",
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
},
{
"size": 100786,
"path": "terminal/markdown-it.js",
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
},
{
"size": 3599,
"path": "terminal/markdown.html",
"size": 3599,
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094"
},
{
"size": 17575,
"path": "terminal/markdown.js",
"size": 17575,
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8"
},
{
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt",
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
},
{
"size": 5537838,
"path": "terminal/mermaid.js",
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
},
{
"size": 5065,
"path": "terminal/terminal.js",
"size": 5065,
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
},
{
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
},
{
"size": 7112,
"path": "terminal/xterm.css",
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
},
{
"size": 488663,
"path": "terminal/xterm.js",
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
},
{
"size": 4401,
"path": "LICENSE",
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
},
{
"size": 1096,
"path": "json-LICENSE.txt",
"size": 1096,
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
},
{
"size": 883,
"path": "files-text-license.txt",
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
},
{
"size": 98328,
"path": "README.md",
"sha256": "c9a6911afe36f3183077d179d3e560b989f182548a7aa7f62108da0a63097f12"
"size": 99184,
"sha256": "2c37fa1783e45c8ea874801aa1ac74a9b02bf75690c7ae6c9aa0184215bf4604"
},
{
"size": 12353,
"path": "LAN-PREVIEW.md",
"size": 12353,
"sha256": "3ab51025826e8aa2f7c07b70b920b556409b002029b4bb92cb34c5b32dac6e54"
},
{
"size": 732485,
"path": "dictionaries/en.txt",
"size": 732485,
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
},
{
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20566,
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
},
{
"size": 2265,
"path": "dictionaries/README.md",
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
},
{
"size": 1109134,
"path": "dictionaries/ru.txt",
"size": 1109134,
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
},
{
"size": 1280,
"path": "dictionaries/sources.json",
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
},
{
"size": 940799,
"path": "dictionaries/uk.txt",
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
},
{
"size": 993,
"path": "tools/README.txt",
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
},
{
"size": 133120,
"path": "tools/StayHere.exe",
"sha256": "79a80ed066e8c1301ec0b22d63bd5590c5477feea4d59e65cf29deac86195149"
"size": 133120,
"sha256": "658052ec21e9a5619339f6036d11db8c75d8065666669245af123c5d906a7846"
},
{
"size": 2796,
"path": "tools/StayHere-README.md",
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
]
],
"schema": 1
}
+3 -3
View File
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,6,124,0
PRODUCTVERSION 0,6,124,0
FILEVERSION 0,6,125,0
PRODUCTVERSION 0,6,125,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.124"
VALUE "FileVersion", "0.6.125"
END
END
BLOCK "VarFileInfo"
+101 -22
View File
@@ -8,6 +8,7 @@
#include "configuration.h"
#include "diagnostics.h"
#include "paste_probe.h"
#include "snippet_skill.h"
#include "utilities.h"
#include "screenshot_notifications.h"
#include <algorithm>
@@ -695,6 +696,14 @@ class Transaction
check();
return true;
}
bool insertSnippetText(const std::wstring &text, bool typeSkill)
{
if (!typeSkill) return paste(textClip(text));
check();
if (!valid() || !typeSnippetSkill(text)) return false;
Sleep(75);
return valid();
}
bool nativeSelectionIs(const std::wstring &original) const
{
if (!valid()) return false;
@@ -722,6 +731,20 @@ class Transaction
content.substr(LOWORD(range), original.size()) == original;
}
};
bool placeSnippetCursor(Transaction &tx, const std::wstring &suffix)
{
if (suffix.empty()) return tx.valid();
if (!tx.select(caretSteps(suffix))) return false;
const auto selected = tx.copy();
if (!tx.valid()) return false;
if (newlines(selected) != newlines(suffix))
{
tx.finishSelection(false);
return false;
}
return tx.finishSelection(true);
}
} // namespace
App::App(HINSTANCE h, bool test, const std::filesystem::path &dataRoot, HWND service)
: historyService(service), instance(h), smoke(test)
@@ -2445,6 +2468,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
L" id=" + std::to_wstring(attempt));
bool automatic = false;
Template snippetTemplate;
bool codexSnippet = false;
if (command == AutoCorrect)
{
// The editor must select the complete previous word. Unlike manual
@@ -2513,16 +2537,21 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
if (snippet >= (int)config.snippets.size() || recent.window != target)
return;
const auto &sn = config.snippets[snippet];
if (!snippetAppPriority(sn, processName(target))) return;
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;
snippetTemplate = parseTemplate(sn.text);
result = std::move(snippetTemplate.text);
const auto end = snippetTemplate.actions.empty() ? snippetTemplate.text.size() :
snippetTemplate.actions.front().offset;
result = snippetTemplate.text.substr(0, end);
// A multiline clipboard paste can execute a console command
// before readback. Explicit key actions run after verification.
if (farSnippet && (result.empty() || result.find_first_of(L"\r\n") != result.npos ||
caretSteps(result) > 4096))
if (farSnippet && (snippetTemplate.text.empty() ||
snippetTemplate.text.find_first_of(L"\r\n") != result.npos ||
caretSteps(snippetTemplate.text) > 4096))
{
reason = L"far-snippet-template-unsupported";
return;
@@ -2666,8 +2695,23 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
}
diagnosticEvent(L"Conversion source=" + std::to_wstring(hint) + L" target=" + std::to_wstring(to) +
L" changed=" + std::to_wstring(result != text));
const auto 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<std::vector<WORD>>(&action->value);
if (keys && keys->size() == 1 && keys->front() == VK_RETURN)
return snippetSkillName(segment);
}
return std::wstring{};
};
std::wstring pendingSkill = skillToConfirm(result, result.size());
if (result != text)
sent = tx.paste(textClip(result));
sent = snippet >= 0 ? tx.insertSnippetText(result, !pendingSkill.empty()) : tx.paste(textClip(result));
else if (automatic && tx.valid())
tx.finishSelection(false);
if (requireReadback && result != text && !sent)
@@ -2687,7 +2731,9 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
reason = L"Conversion unchanged";
verification = L"calculated-result-equals-original";
}
if (sent && ((manual && config.writeLog) || requireReadback))
// When Chromium exposes a focused suggestion rather than the
// composer, verify against the suggestion before invoking it.
if (sent && pendingSkill.empty() && ((manual && config.writeLog) || requireReadback))
{
verification = probe.status;
if (tx.valid())
@@ -2701,7 +2747,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
if (!farSnippet && observed && newlines(*observed) == newlines(text) && tx.nativeSelectionIs(text))
{
diagnosticEvent(L"Paste retry: native Edit still selects the unchanged original");
if (tx.paste(textClip(result)) && tx.valid())
if (pendingSkill.empty() && tx.paste(textClip(result)) && tx.valid())
observed = probe.read((int)caretSteps(result));
else
observed.reset();
@@ -2752,20 +2798,15 @@ 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();
if (!snippetTemplate.suffix.empty())
{
if (!tx.select(caretSteps(snippetTemplate.suffix))) return;
auto suffix = tx.copy();
if (!tx.valid()) return;
if (newlines(suffix) != newlines(snippetTemplate.suffix))
{
tx.finishSelection(false);
return;
}
if (!tx.finishSelection(true)) return;
}
if (!snippetTemplate.actions.empty() && tx.valid())
size_t emitted = result.size();
if (!placeSnippetCursor(tx, cursorSuffix(0, emitted))) return;
if (!snippetTemplate.actions.empty())
{
tx.check();
// Clipboard shortcuts must see the user's clipboard, and
@@ -2773,17 +2814,54 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
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 count = caretSteps(segment);
const auto actual = farSnippet ? segmentTx.readFarSnippet(count) : probe.read(static_cast<int>(count));
if (!actual || !segmentTx.valid() || newlines(*actual) != newlines(segment))
return false;
}
if (!placeSnippetCursor(segmentTx, cursorSuffix(emitted, end))) return false;
emitted = end;
return true;
};
bool skillSelected = false;
for (const auto &action : snippetTemplate.actions)
{
if (!tx.valid()) return;
if (const auto *keys = std::get_if<std::vector<WORD>>(&action))
if (emitted != action.offset)
{
if (!insertSegment(action.offset)) return;
skillSelected = false;
}
if (const auto *keys = std::get_if<std::vector<WORD>>(&action.value))
{
if (!pendingSkill.empty() && keys->size() == 1 && keys->front() == VK_RETURN)
{
if (!skillSelected && !selectSnippetSkill(pendingSkill, target, valid))
{
reason = L"snippet-skill-suggestion-unavailable";
report(L"KSwitcher could not select the Codex skill. Choose it from the suggestions and continue your draft.");
return;
}
skillSelected = true;
continue;
}
if (!chord(*keys))
throw std::runtime_error("Windows could not send all snippet keys");
}
else
{
const auto deadline = GetTickCount64() + std::get<DWORD>(action);
const auto deadline = GetTickCount64() + std::get<DWORD>(action.value);
for (auto now = GetTickCount64(); now < deadline; now = GetTickCount64())
{
if (!tx.valid()) return;
@@ -2791,6 +2869,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
}
}
}
if (!insertSegment(snippetTemplate.text.size())) return;
}
if (to >= 0 && config.switchLayout && tx.valid() && (sent || result == text))
{
+10 -3
View File
@@ -428,9 +428,9 @@ Template parseTemplate(const std::wstring &text)
++t.cursors;
}
else if (depth == 1 && name == L"enter")
t.actions.emplace_back(std::vector<WORD>{VK_RETURN});
t.actions.push_back({t.text.size(), std::vector<WORD>{VK_RETURN}});
else if (depth == 1 && pause)
t.actions.emplace_back(*pause);
t.actions.push_back({t.text.size(), *pause});
else if (depth == 2 && key)
{
std::vector<WORD> keys{key};
@@ -445,7 +445,7 @@ Template parseTemplate(const std::wstring &text)
keys.push_back(nextKey);
remaining.remove_prefix(1 + next->length);
}
t.actions.emplace_back(std::move(keys));
t.actions.push_back({t.text.size(), std::move(keys)});
continue;
}
else if ((depth >= 2 && legacyEscape) || (depth == 2 && pause) || (depth == 3 && key))
@@ -456,6 +456,13 @@ Template parseTemplate(const std::wstring &text)
}
if (cursor != text.npos)
t.suffix = t.text.substr(cursor);
// A leading action has historically followed replacement of the trigger.
// Keep that behavior while allowing actions between text segments.
const auto first = std::find_if(t.actions.begin(), t.actions.end(),
[](const SnippetAction &action) { return action.offset != 0; });
const auto firstText = first == t.actions.end() ? t.text.size() : first->offset;
for (auto it = t.actions.begin(); it != first; ++it)
it->offset = firstText;
return t;
}
std::wstring Hotkey::format() const
+6 -1
View File
@@ -43,7 +43,12 @@ std::wstring snippetAppName(std::wstring);
int snippetAppPriority(const Snippet &, const std::wstring &process);
std::wstring snippetId(const Snippet &);
std::wstring newSnippetId();
using SnippetAction = std::variant<std::vector<WORD>, DWORD>;
struct SnippetAction
{
size_t offset;
std::variant<std::vector<WORD>, DWORD> value;
bool operator==(const SnippetAction &) const = default;
};
struct Template
{
std::wstring text, suffix;
+178
View File
@@ -0,0 +1,178 @@
#pragma once
#include "platform.h"
#include <algorithm>
#include <string_view>
#include <uiautomation.h>
#include <wrl/client.h>
namespace ks
{
inline std::wstring snippetSkillName(std::wstring_view text)
{
if (!text.starts_with(L'$') || text.size() < 2) return {};
auto name = lower(std::wstring(text.substr(1)));
if (name.find_first_not_of(L"abcdefghijklmnopqrstuvwxyz0123456789-_.") != name.npos)
return {};
return name;
}
inline bool typeSnippetSkill(std::wstring_view text)
{
std::vector<INPUT> inputs;
inputs.reserve(2 * text.size());
for (wchar_t ch : text)
for (DWORD flags : {DWORD{0}, DWORD{KEYEVENTF_KEYUP}})
{
auto input = keyboardInput(0, flags | KEYEVENTF_UNICODE);
input.ki.wScan = ch;
inputs.push_back(input);
}
return SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT)) == inputs.size();
}
enum class SnippetSkillMatch { None, LabelWithDescription, Exact };
inline SnippetSkillMatch snippetSkillLabelMatch(IUIAutomationElement *item, const std::wstring &name)
{
BSTR label{};
if (FAILED(item->get_CurrentName(&label))) return SnippetSkillMatch::None;
auto candidate = lower(std::wstring(label ? label : L"", SysStringLen(label)));
SysFreeString(label);
if (candidate.size() < name.size() ||
(candidate.size() > name.size() && candidate[name.size()] != L' '))
return SnippetSkillMatch::None;
auto end = candidate.begin() + name.size();
std::replace(candidate.begin(), end, L' ', L'-');
if (candidate.compare(0, name.size(), name) != 0) return SnippetSkillMatch::None;
return candidate.size() == name.size() ? SnippetSkillMatch::Exact : SnippetSkillMatch::LabelWithDescription;
}
inline std::vector<Microsoft::WRL::ComPtr<IUIAutomationElement>>
snippetSuggestionLists(IUIAutomation *automation, IUIAutomationElement *focused)
{
using Microsoft::WRL::ComPtr;
std::vector<ComPtr<IUIAutomationElement>> result;
ComPtr<IUIAutomationElementArray> controlled;
int count{};
if (SUCCEEDED(focused->get_CurrentControllerFor(&controlled)) && controlled)
controlled->get_Length(&count);
for (int i = 0; i < count; ++i)
{
ComPtr<IUIAutomationElement> list;
if (SUCCEEDED(controlled->GetElement(i, &list)) && list)
result.push_back(list);
}
if (!result.empty()) return result;
// Chromium can expose the active descendant of the combobox as the
// focused element. In that case follow the option to its owning listbox.
CONTROLTYPEID type{};
if (FAILED(focused->get_CurrentControlType(&type)) || type != UIA_ListItemControlTypeId)
return result;
ComPtr<IUIAutomationTreeWalker> walker;
if (FAILED(automation->get_RawViewWalker(&walker)) || !walker) return result;
ComPtr<IUIAutomationElement> node = focused;
for (int i = 0; i < 6; ++i)
{
ComPtr<IUIAutomationElement> parent;
if (FAILED(walker->GetParentElement(node.Get(), &parent)) || !parent)
break;
BSTR role{};
if (SUCCEEDED(parent->get_CurrentAriaRole(&role)))
{
const bool listbox = role && std::wstring_view(role, SysStringLen(role)) == L"listbox";
SysFreeString(role);
if (listbox)
{
result.push_back(parent);
break;
}
}
node = parent;
}
return result;
}
inline bool selectSnippetSkill(const std::wstring &name, HWND target, const std::function<bool()> &valid)
{
using Microsoft::WRL::ComPtr;
const auto deadline = GetTickCount64() + 500;
ComPtr<IUIAutomation2> automation;
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER, IID_IUIAutomation2,
reinterpret_cast<void **>(automation.GetAddressOf()))))
return false;
automation->put_ConnectionTimeout(150);
automation->put_TransactionTimeout(150);
VARIANT roleValue{};
roleValue.vt = VT_I4;
roleValue.lVal = UIA_ListItemControlTypeId;
ComPtr<IUIAutomationCondition> listItem;
if (FAILED(automation->CreatePropertyCondition(UIA_ControlTypePropertyId, roleValue, &listItem)))
return false;
roleValue.lVal = UIA_TextControlTypeId;
ComPtr<IUIAutomationCondition> textItem;
if (FAILED(automation->CreatePropertyCondition(UIA_ControlTypePropertyId, roleValue, &textItem)))
return false;
DWORD targetProcess{};
GetWindowThreadProcessId(target, &targetProcess);
while (valid() && GetTickCount64() < deadline)
{
ComPtr<IUIAutomationElement> focused;
int process{};
if (FAILED(automation->GetFocusedElement(&focused)) || !focused ||
FAILED(focused->get_CurrentProcessId(&process)) || static_cast<DWORD>(process) != targetProcess)
return false;
ComPtr<IUIAutomationElement> option;
auto bestMatch = SnippetSkillMatch::None;
bool ambiguous = false;
for (const auto &list : snippetSuggestionLists(automation.Get(), focused.Get()))
{
CONTROLTYPEID role{};
if (FAILED(list->get_CurrentControlType(&role)) || role != UIA_ListControlTypeId)
continue;
ComPtr<IUIAutomationElementArray> items;
int length{};
if (FAILED(list->FindAll(TreeScope_Descendants, listItem.Get(), &items)) || !items ||
FAILED(items->get_Length(&length)))
continue;
for (int index = 0; index < length; ++index)
{
ComPtr<IUIAutomationElement> item;
BOOL offscreen = TRUE, enabled = FALSE;
if (FAILED(items->GetElement(index, &item)) || !item ||
FAILED(item->get_CurrentIsOffscreen(&offscreen)) || offscreen ||
FAILED(item->get_CurrentIsEnabled(&enabled)) || !enabled)
continue;
auto match = snippetSkillLabelMatch(item.Get(), name);
if (match != SnippetSkillMatch::Exact)
{
ComPtr<IUIAutomationElement> caption;
if (SUCCEEDED(item->FindFirst(TreeScope_Descendants, textItem.Get(), &caption)) &&
caption && snippetSkillLabelMatch(caption.Get(), name) == SnippetSkillMatch::Exact)
match = SnippetSkillMatch::Exact;
}
if (match == SnippetSkillMatch::None || match < bestMatch) continue;
if (match > bestMatch)
{
option = item;
bestMatch = match;
ambiguous = false;
}
else ambiguous = true;
}
}
if (option && !ambiguous && valid())
{
ComPtr<IUIAutomationInvokePattern> invoke;
if (SUCCEEDED(option->GetCurrentPatternAs(UIA_InvokePatternId, IID_IUIAutomationInvokePattern,
reinterpret_cast<void **>(invoke.GetAddressOf()))) && invoke)
return valid() && SUCCEEDED(invoke->Invoke());
ComPtr<IUIAutomationLegacyIAccessiblePattern> accessible;
return SUCCEEDED(option->GetCurrentPatternAs(UIA_LegacyIAccessiblePatternId,
IID_IUIAutomationLegacyIAccessiblePattern, reinterpret_cast<void **>(accessible.GetAddressOf()))) &&
accessible && valid() && SUCCEEDED(accessible->DoDefaultAction());
}
Sleep(25);
}
return false;
}
}
+3 -1
View File
@@ -2264,7 +2264,9 @@ bool snippetCommand(HWND w, SnippetView *v, WPARAM wp, bool embedded)
if (id == SnippetMacros)
{
MessageBoxW(w,
L"After the text is inserted and {cursor} is placed, macros run in order.\n\n"
L"Macros run where they appear in the replacement text.\n"
L"In Codex, $skill{pause:500}{enter} Draft text selects a matching skill "
L"and leaves the rest as a draft.\n\n"
L"Tap a key: {{shift}}, {{altr}}, {{tab}}, {{F5}}\n"
L"Hold keys together: {{ctrl}}+{{shift}}+{{A}}\n"
L"Press Enter: {enter} or {{return}} in a combination\n"
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.124";
inline constexpr wchar_t AppVersion[] = L"0.6.125";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+31
View File
@@ -928,6 +928,35 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
case 83:
require(macroStart && GetFocus() == host && text() == L"prefix done" && enterPresses == 0,
"snippet macros stop when focus moves to a different control");
observeMacros = false;
moveFocusOnMacro = false;
expandMacroSnippet(L"left{pause:50}{enter}{enter}right{cursor}!");
stage = 92;
break;
case 92:
require(text() == L"prefix left\r\n\r\nright!" && enterPresses == 2,
"actions between text segments run before the next segment");
require(LOWORD(SendMessageW(field, EM_GETSEL, 0, 0)) == GetWindowTextLengthW(field) - 1,
"the cursor marker works in the final text segment");
require(ks::readClipboard(app->window).text() == sentinel,
"each verified snippet segment restores the clipboard");
finish();
break;
case 93:
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
app->settings.autoCorrect = false;
ActivateKeyboardLayout(app->layouts[en].handle, 0);
require(ks::lower(ks::processName(host)) == L"chatgpt",
"Codex skill guard fixture runs under the desktop executable name");
expandMacroSnippet(L"$example-skill{pause:50}{enter}{enter}{enter} Draft text{cursor}");
break;
case 94:
require(text() == L"prefix $example-skill" && enterPresses == 0,
"an unavailable skill suggestion cancels three Enter markers without sending the draft");
require(ks::readClipboard(app->window).text() == sentinel,
"skill confirmation failure preserves the clipboard");
finish();
break;
case 84:
@@ -1295,6 +1324,8 @@ 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")
stage = 93;
if (argc > 1 && std::string(argv[1]) == "--snippet-word-boundaries")
stage = 84;
SetTimer(host, 1, 100, nullptr);
+11 -6
View File
@@ -461,17 +461,17 @@ int main(int argc, char **argv)
require(ks::parseTemplate(L"{{cursor}}").text == L"{cursor}", "escaped cursor");
const auto enters = ks::parseTemplate(L"a{cursor}b{enter}{enter}");
require(enters.text == L"ab" && enters.suffix == L"b" &&
enters.actions == std::vector<ks::SnippetAction>{std::vector<WORD>{VK_RETURN},
std::vector<WORD>{VK_RETURN}},
enters.actions == std::vector<ks::SnippetAction>{{2, std::vector<WORD>{VK_RETURN}},
{2, std::vector<WORD>{VK_RETURN}}},
"Enter actions preserve the inserted text and cursor suffix");
const auto escaped = ks::parseTemplate(L"before {{cursor}} {{enter}} {{{shift}}} {{pause:50}} after");
require(escaped.text == L"before {cursor} {enter} {{shift}} {pause:50} after" && escaped.actions.empty(),
"escaped snippet markers are literal even inside text");
const auto macros = ks::parseTemplate(L"a{{SHIFT}}{cursor}b{pause:50}{{altr}}+{{ctrl}}+{{F5}}{{tab}}{{ctrl}}+{{return}}");
require(macros.text == L"ab" && macros.suffix == L"b" &&
macros.actions == std::vector<ks::SnippetAction>{std::vector<WORD>{VK_LSHIFT}, DWORD{50},
std::vector<WORD>{VK_RMENU, VK_LCONTROL, VK_F5}, std::vector<WORD>{VK_TAB},
std::vector<WORD>{VK_LCONTROL, VK_RETURN}},
macros.actions == std::vector<ks::SnippetAction>{{1, std::vector<WORD>{VK_LSHIFT}}, {2, DWORD{50}},
{2, std::vector<WORD>{VK_RMENU, VK_LCONTROL, VK_F5}}, {2, std::vector<WORD>{VK_TAB}},
{2, std::vector<WORD>{VK_LCONTROL, VK_RETURN}}},
"snippet macros preserve key chords, tap order, pauses and cursor placement");
const std::wstring literal = L"{{unknown}} + {pause:-1} {pause:10001} {pause:99999999999999} {pause:}";
const auto unrecognized = ks::parseTemplate(literal);
@@ -479,8 +479,13 @@ int main(int argc, char **argv)
"unknown keys and invalid pause durations remain literal");
const auto plus = ks::parseTemplate(L"2+{{left}}+1{pause:0}{pause:10000}");
require(plus.text == L"2++1" && plus.actions == std::vector<ks::SnippetAction>{
std::vector<WORD>{VK_LEFT}, DWORD{0}, DWORD{10000}},
{2, std::vector<WORD>{VK_LEFT}}, {4, DWORD{0}}, {4, DWORD{10000}}},
"only a plus between key markers forms a chord and pause bounds are inclusive");
const auto prompt = ks::parseTemplate(L"$example-skill{pause:500}{enter}{enter}{enter} Draft text{cursor}");
require(prompt.text == L"$example-skill Draft text" && prompt.suffix.empty() &&
prompt.actions == std::vector<ks::SnippetAction>{{14, DWORD{500}}, {14, std::vector<WORD>{VK_RETURN}},
{14, std::vector<WORD>{VK_RETURN}}, {14, std::vector<WORD>{VK_RETURN}}},
"all skill confirmation markers precede the prompt draft");
require(ks::parseTemplate(L"{cursor}{cursor}").cursors == 2, "duplicate cursor detection");
require(ks::Hotkey::parse(L"Ctrl+Alt+Shift+Space")->key == VK_SPACE, "hotkey parse");
require(!ks::Hotkey::parse(L"Ctrl+F25"), "invalid function key");