Compare commits

...
Author SHA1 Message Date
agrynco 8b3fe947a6 Release KSwitcher v0.6.127 (#73)
Confirm a single snippet suggestion with Enter before the focused application receives the key.
2026-11-21 23:56:17 +02:00
agrynco 7626e6c9c2 Release KSwitcher v0.6.126 (#72)
Ship literal snippet key presses and the configured pause without application-specific suggestion handling.
2026-11-21 23:45:42 +02:00
12 changed files with 153 additions and 284 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.125 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.127 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+10 -9
View File
@@ -461,10 +461,11 @@ Recognition uses Chrome accessibility: the address bar and active document must
### Snippet autocomplete — v0.6.69
Starting with v0.6.71, **Enter** accepts a suggestion after you navigate
the list with **↑ / ↓**. Without arrow navigation, **Enter** goes to the
editor. З v0.6.71 **Enter** після вибору стрілками вставляє сніпет. Без
переміщення списком **Enter** надходить до редактора.
**Enter** accepts a single visible suggestion directly. When several suggestions
are visible, navigate the list with **↑ / ↓** to select one for **Enter**.
**Українською.** **Enter** одразу підтверджує єдину видиму підказку. Якщо
підказок кілька, виберіть потрібну стрілками **↑ / ↓**, а тоді натисніть **Enter**.
Starting with v0.6.70, suggestions open at the text caret. If the editor
provides no caret position, you can still type the complete trigger to
@@ -495,23 +496,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 +561,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).
+17 -1
View File
@@ -1,6 +1,22 @@
# Latest Windows release
## v0.6.125 — 2026-11-21
## v0.6.127 — 2026-11-21
When the snippet popup shows one match, pressing Enter expands it immediately and consumes the key. With several matches, use the arrow keys and then press Enter to confirm.
**Українською.**
Якщо у списку підказок є один збіг, Enter одразу розгортає сніпет. KSwitcher перехоплює це натискання. Якщо збігів кілька, виберіть потрібний стрілками й підтвердьте через Enter.
## v0.6.126 — 2026-11-21 (withdrawn / відкликано)
Snippet macros send the configured keys at the position where they appear. `$skill{pause:500}{enter} Draft text` types the name, waits 500 milliseconds, presses Enter once, then types the remaining text. The focused application handles each key.
**Українською.**
Макроси сніпетів натискають задані клавіші в указаній позиції. `$skill{pause:500}{enter} Текст` вводить назву, чекає 500 мілісекунд, один раз натискає Enter і вводить решту тексту. Кожне натискання обробляє програма у фокусі.
## v0.6.125 — 2026-11-21 (withdrawn / відкликано)
Snippet macros between text segments run before the next segment is inserted. In Codex, `$skill{pause:500}{enter} Draft text` selects the matching skill suggestion and leaves the following text in the composer. Extra Enter markers at the same selection point do not submit the draft. Expansion stops when the suggestion cannot be verified.
+1 -1
View File
@@ -1 +1 @@
c0418b28d5bbfa6ac7c4ff8b76addc58e5b6abdf1c192895014a35d92424e13d KSwitcher-win-x64.zip
da1e6b22619b9a9c32ec5b2d131055a96d2b60c185936ec65cdb160eae839979 KSwitcher-win-x64.zip
+10 -10
View File
@@ -1,25 +1,24 @@
{
"version": "0.6.125",
"files": [
{
"path": "KSwitcher.exe",
"size": 2497536,
"sha256": "c66a11c095c15a7d80d15ca0e19adeb284db65134babb3b403998d6756444b3d"
"size": 2491904,
"sha256": "cc43f9fc566047f29cded8d1fff3f044150e3657add7b355ff97510a9672b879"
},
{
"path": "KSwitcher.Config.exe",
"size": 2462720,
"sha256": "bac341c5ef616ea90462e70f82e25e4b2a5550019d1bd8d729d311e41583f64a"
"sha256": "10240cdf03cbf9f197b783a18df79c6ef3975d7f193137a3f7f0290d74f79b67"
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3063808,
"sha256": "c1b0c9aec507110d6949736b7e2beb9f83065c4153d53a4f0f1bb5f110f811a6"
"sha256": "b2ad1f46b1562add9be160c83dd959a497ed75fcc3a59aecb3278edccb98cfdd"
},
{
"path": "KSwitcher.Files.exe",
"size": 4377088,
"sha256": "04db22229e93f01a482d3040b21854cd88ceb5dd6c84e3ec5928c2d3e5bb3099"
"sha256": "5e56dc39311287534486d85f67bd2cc48e41b0e9da717ddbcfd3228ad28e9719"
},
{
"path": "WebView2Loader.dll",
@@ -108,8 +107,8 @@
},
{
"path": "README.md",
"size": 99184,
"sha256": "2c37fa1783e45c8ea874801aa1ac74a9b02bf75690c7ae6c9aa0184215bf4604"
"size": 99061,
"sha256": "bb045f8b3a47734b21c5aad830ec43bbc13f209ccd29d923de812fe0b5086d56"
},
{
"path": "LAN-PREVIEW.md",
@@ -154,7 +153,7 @@
{
"path": "tools/StayHere.exe",
"size": 133120,
"sha256": "658052ec21e9a5619339f6036d11db8c75d8065666669245af123c5d906a7846"
"sha256": "65f2b3787eabd5412bfd96df78ff3500e18ba634655082bf817194a85d592c1d"
},
{
"path": "tools/StayHere-README.md",
@@ -162,5 +161,6 @@
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
],
"schema": 1
"schema": 1,
"version": "0.6.127"
}
+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,125,0
PRODUCTVERSION 0,6,125,0
FILEVERSION 0,6,127,0
PRODUCTVERSION 0,6,127,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.127"
END
END
BLOCK "VarFileInfo"
+61 -67
View File
@@ -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 <algorithm>
@@ -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<bool()> &valid)
{
constexpr size_t batchSize = 64;
for (size_t offset = 0; offset < text.size(); offset += batchSize)
{
std::vector<INPUT> inputs;
for (wchar_t ch : std::wstring_view(text).substr(offset, batchSize))
for (DWORD flags : {DWORD{0}, DWORD{KEYEVENTF_KEYUP}})
{
auto input = keyboardInput(0, flags | KEYEVENTF_UNICODE);
input.ki.wScan = ch;
inputs.push_back(input);
}
if (!valid() || SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT)) != inputs.size())
return false;
}
return valid();
}
// Every transaction checks input, foreground and clipboard ownership before replacing text.
class Transaction
{
@@ -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;
@@ -1558,7 +1571,8 @@ void App::selectSnippet(size_t row)
}
bool App::handleSnippetKey(DWORD vk, UINT mods)
{
const bool accept = vk == VK_TAB || (vk == VK_RETURN && snippetNavigated);
const bool accept = vk == VK_TAB ||
(vk == VK_RETURN && (snippetNavigated || snippetMatches.size() == 1));
if (mods || (!accept && vk != VK_UP && vk != VK_DOWN && vk != VK_ESCAPE) ||
!snippetPopup || !IsWindowVisible(snippetPopup) || !snippetPopupCurrent())
return false;
@@ -2468,7 +2482,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 +2552,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 +2707,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{};
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 +2743,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 +2757,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 +2808,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<int>(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<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");
}
-178
View File
@@ -1,178 +0,0 @@
#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;
}
}
+2 -4
View File
@@ -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);
+1 -1
View File
@@ -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.127";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+46 -8
View File
@@ -14,6 +14,7 @@ struct InputRegressionAccess
{
return app.snippetPopup && IsWindowVisible(app.snippetPopup);
}
static size_t suggestionCount(const App &app) { return app.snippetMatches.size(); }
static bool suggestionsNearCaret(const App &app)
{
GUITHREADINFO info{sizeof(info)};
@@ -69,6 +70,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 +191,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;
@@ -725,10 +741,28 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
case 73:
require(enterPresses == 1 && text() == L"prefix ;qz\r\n" &&
!ks::InputRegressionAccess::suggestionsVisible(*app),
"Enter without arrow navigation reaches the editor");
"Enter reaches the editor while multiple suggestions await navigation");
prepare(L"prefix ", false);
typeKeys({VK_OEM_1, 'Q', 'Z', VK_OEM_MINUS, 'S'});
stage = 75;
break;
case 75:
require(ks::InputRegressionAccess::suggestionsVisible(*app) &&
ks::InputRegressionAccess::suggestionCount(*app) == 1,
"a filtered prefix leaves one visible suggestion");
enterPresses = 0;
typeKeys({VK_RETURN});
break;
case 76:
require(text() == L"prefix second" && enterPresses == 0 &&
!ks::InputRegressionAccess::suggestionsVisible(*app),
"Enter accepts the only suggestion without arrows or forwarding the key");
require(ks::readClipboard(app->window).text() == sentinel,
"accepting a single suggestion restores the clipboard");
app->resetInput();
SetFocus(host);
typeKeys({VK_OEM_1});
stage = 74;
break;
case 74:
if (ks::InputRegressionAccess::findingSuggestionCaret(*app))
@@ -949,14 +983,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 +1362,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;
+1 -1
View File
@@ -485,7 +485,7 @@ int main(int argc, char **argv)
require(prompt.text == L"$example-skill Draft text" && prompt.suffix.empty() &&
prompt.actions == std::vector<ks::SnippetAction>{{14, DWORD{500}}, {14, std::vector<WORD>{VK_RETURN}},
{14, std::vector<WORD>{VK_RETURN}}, {14, std::vector<WORD>{VK_RETURN}}},
"all 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");