Compare commits

...
1 Commits
Author SHA1 Message Date
agrynco 187334aed2 Show KSwitcher snippet suggestions in WebView2 text fields
Refs #209
2026-11-27 16:06:50 +02:00
5 changed files with 158 additions and 26 deletions

No files matched your search

+7
View File
@@ -1044,6 +1044,13 @@ embedded in KSwitcher.Files.exe.
.\tests\configuration.ps1 # Separate-process settings tests; close KSwitcher first
```
To check snippet suggestions in a WebView2 app, focus a blank editable field and
run `KSwitcherIntegration.exe --snippet-external-editor` without changing the
foreground window. The test types `;`, checks that the popup opens without
stealing focus, dismisses it, and removes the test character. In Dirlume, repeat
in the Command line, the terminal at an idle prompt, and the text editor. Use
`--insert` as the second argument to test Tab insertion in a blank text field.
`-Test` also checks remote/own input separation, hidden Settings layout and scrolling, and updater
package validation, file preservation and rollback in temporary fixture directories. It does not
replace a running installation. Optional read-only network checks:
+46 -16
View File
@@ -45,7 +45,7 @@ GUITHREADINFO snippetGuiInfo(HWND target)
return info;
}
std::optional<RECT> accessibleSnippetCaret(HWND target)
std::optional<SnippetAnchor> accessibleSnippetCaret(HWND target)
{
using Microsoft::WRL::ComPtr;
ComPtr<IUIAutomation2> automation;
@@ -57,14 +57,28 @@ std::optional<RECT> accessibleSnippetCaret(HWND target)
ComPtr<IUIAutomationElement> focused;
if (FAILED(automation->GetFocusedElement(&focused)) || !focused)
return {};
DWORD process{};
GetWindowThreadProcessId(target, &process);
int focusedProcess{};
BOOL password = TRUE;
if (!process || FAILED(focused->get_CurrentProcessId(&focusedProcess)) ||
process != static_cast<DWORD>(focusedProcess) ||
FAILED(focused->get_CurrentIsPassword(&password)) || password)
if (FAILED(focused->get_CurrentIsPassword(&password)) || password ||
!focusedTextBelongsToWindow(automation.Get(), focused.Get(), target))
return {};
// The xterm.js input follows the terminal cursor for IME. It doesn't
// expose the shell's selection, so the popup can only display triggers.
BSTR className{};
const bool terminalInput = SUCCEEDED(focused->get_CurrentClassName(&className)) && className &&
std::wstring_view(className) == L"xterm-helper-textarea";
SysFreeString(className);
if (terminalInput)
{
RECT cell{};
BOOL offscreen = TRUE;
if (SUCCEEDED(focused->get_CurrentIsOffscreen(&offscreen)) && !offscreen &&
SUCCEEDED(focused->get_CurrentBoundingRectangle(&cell)) && cell.right > cell.left &&
cell.bottom > cell.top)
return SnippetAnchor{{cell.left, cell.top, cell.left, cell.bottom}, false};
return {};
}
ComPtr<IUIAutomationTextPattern2> pattern;
ComPtr<IUIAutomationTextRange> range;
BOOL active{};
@@ -121,7 +135,7 @@ std::optional<RECT> accessibleSnippetCaret(HWND target)
}
}
SafeArrayDestroy(rectangles);
if (anchor && anchor->bottom > anchor->top) return anchor;
if (anchor && anchor->bottom > anchor->top) return SnippetAnchor{*anchor};
}
return {};
}
@@ -1485,6 +1499,12 @@ void App::matchSnippets(HWND fg, bool expandExact)
!snippetWordCharacter(layout->at(physicalLayout().code(previous)));
}))
{
if (!snippetPopupAnchor.canInsert && snippetTarget == fg && snippetPopup &&
IsWindowVisible(snippetPopup) && snippetFocus == snippetGuiInfo(fg).hwndFocus)
{
hideSnippetPopup();
return;
}
queueSnippet(fg, i, sn.trigger.size());
return;
}
@@ -1559,11 +1579,11 @@ void App::showSnippetPopup()
if ((info.rcCaret.left || info.rcCaret.top || anchor.bottom - anchor.top >= 4) &&
snippetCaretInside(anchor, bounds))
{
placeSnippetPopup(anchor);
placeSnippetPopup({anchor});
return;
}
}
if (snippetPopup && IsWindowVisible(snippetPopup) && snippetCaretInside(snippetPopupAnchor, bounds))
if (snippetPopup && IsWindowVisible(snippetPopup) && snippetCaretInside(snippetPopupAnchor.bounds, bounds))
placeSnippetPopup(snippetPopupAnchor);
if (snippetCaretPending) return;
snippetCaretPending = true;
@@ -1572,6 +1592,14 @@ void App::showSnippetPopup()
const auto receiver = window;
enqueue([this, version, target, receiver] {
auto caret = GetForegroundWindow() == target ? accessibleSnippetCaret(target) : std::nullopt;
if (!caret && inputVersion == version && GetForegroundWindow() == target)
{
// A WebView can expose the old, empty field while the keystroke
// that requested suggestions is still reaching its renderer.
Sleep(45);
if (inputVersion == version && GetForegroundWindow() == target)
caret = accessibleSnippetCaret(target);
}
{
std::lock_guard lock(stateMutex);
snippetCaret = caret;
@@ -1579,9 +1607,10 @@ void App::showSnippetPopup()
PostMessageW(receiver, SnippetCaretMessage, static_cast<WPARAM>(version), 0);
});
}
void App::placeSnippetPopup(RECT anchor)
void App::placeSnippetPopup(SnippetAnchor placement)
{
snippetPopupAnchor = anchor;
snippetPopupAnchor = placement;
const auto &anchor = placement.bounds;
if (!snippetPopup)
{
WNDCLASSW cls{};
@@ -1632,7 +1661,7 @@ void App::placeSnippetPopup(RECT anchor)
}
void App::selectSnippet(size_t row)
{
if (row >= snippetMatches.size() || !snippetPopupCurrent()) return;
if (!snippetPopupAnchor.canInsert || row >= snippetMatches.size() || !snippetPopupCurrent()) return;
const auto index = snippetMatches[row];
const auto length = snippetPrefixLength;
hideSnippetPopup();
@@ -1642,6 +1671,7 @@ void App::selectSnippet(size_t row)
}
bool App::handleSnippetKey(DWORD vk, UINT mods)
{
if (!snippetPopupAnchor.canInsert && vk != VK_ESCAPE) return false;
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) ||
@@ -1690,7 +1720,7 @@ LRESULT CALLBACK App::snippetPopupProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
const LONG top = static_cast<LONG>(i - first) * app->snippetRowHeight;
RECT row{0, top, bounds.right, top + app->snippetRowHeight};
const bool selected = i == app->snippetSelection;
const bool selected = app->snippetPopupAnchor.canInsert && i == app->snippetSelection;
if (selected) FillRect(dc, &row, GetSysColorBrush(COLOR_HIGHLIGHT));
SetTextColor(dc, GetSysColor(selected ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT));
row.left += MulDiv(8, dpi, 96);
@@ -3603,13 +3633,13 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
app->showSnippetPopup();
return 0;
}
std::optional<RECT> caret;
std::optional<SnippetAnchor> caret;
{
std::lock_guard lock(app->stateMutex);
caret = app->snippetCaret;
}
RECT bounds{};
if (caret && GetWindowRect(app->snippetTarget, &bounds) && snippetCaretInside(*caret, bounds))
if (caret && GetWindowRect(app->snippetTarget, &bounds) && snippetCaretInside(caret->bounds, bounds))
{
app->placeSnippetPopup(*caret);
return 0;
+8 -3
View File
@@ -23,6 +23,11 @@ inline constexpr int Toggle = 1, Case = 2, Translit = 3, Undo = 4, ShowHistory =
inline constexpr UINT AutoCorrectMessage = WM_APP + 6;
inline constexpr UINT ReplayTypingMessage = WM_APP + 30;
inline constexpr UINT CaptureHotkeyMessage = WM_APP + 5;
struct SnippetAnchor
{
RECT bounds{};
bool canInsert = true;
};
struct LastTransform
{
HWND window{};
@@ -203,16 +208,16 @@ class App
bool snippetNavigated{};
int snippetRowHeight{};
UINT snippetDpi{96};
RECT snippetPopupAnchor{};
SnippetAnchor snippetPopupAnchor{};
bool snippetCaretPending{};
std::optional<RECT> snippetCaret;
std::optional<SnippetAnchor> snippetCaret;
std::vector<std::pair<std::wstring, std::vector<std::wstring>>> snippetTriggers;
std::vector<size_t> snippetMatches;
std::array<bool, 256> snippetKeys{};
void matchSnippets(HWND, bool expandExact);
bool queueSnippet(HWND, size_t index, size_t length, HWND editor = nullptr);
void showSnippetPopup();
void placeSnippetPopup(RECT);
void placeSnippetPopup(SnippetAnchor);
void hideSnippetPopup();
bool snippetPopupCurrent() const;
bool handleSnippetKey(DWORD, UINT);
+38 -5
View File
@@ -1,9 +1,46 @@
#pragma once
#include "platform.h"
#include <uiautomation.h>
#include <wrl/client.h>
namespace ks
{
inline bool focusedTextBelongsToWindow(IUIAutomation *automation, IUIAutomationElement *focused, HWND target)
{
using Microsoft::WRL::ComPtr;
DWORD process{};
GetWindowThreadProcessId(target, &process);
int focusedProcess{};
if (!process || FAILED(focused->get_CurrentProcessId(&focusedProcess))) return false;
if (process == static_cast<DWORD>(focusedProcess)) return true;
BOOL hasFocus{}, readOnly = TRUE;
ComPtr<IUIAutomationValuePattern> value;
if (FAILED(focused->get_CurrentHasKeyboardFocus(&hasFocus)) || !hasFocus ||
FAILED(focused->GetCurrentPatternAs(UIA_ValuePatternId, IID_PPV_ARGS(&value))) || !value ||
FAILED(value->get_CurrentIsReadOnly(&readOnly)) || readOnly)
return false;
// WebView2 exposes text through a different process. Its accessibility
// ancestors lead back to a native child window of the foreground app.
ComPtr<IUIAutomationTreeWalker> walker;
if (FAILED(automation->get_RawViewWalker(&walker)) || !walker)
return false;
ComPtr<IUIAutomationElement> element = focused;
for (int depth = 0; element && depth < 32; ++depth)
{
UIA_HWND native{};
if (SUCCEEDED(element->get_CurrentNativeWindowHandle(&native)) && native)
{
const auto hwnd = reinterpret_cast<HWND>(native);
return hwnd == target || IsChild(target, hwnd);
}
ComPtr<IUIAutomationElement> parent;
if (FAILED(walker->GetParentElement(element.Get(), &parent))) return false;
element = std::move(parent);
}
return false;
}
// Read-only UI Automation: never select, move the caret, or touch the clipboard.
class PasteProbe
{
@@ -38,11 +75,7 @@ class PasteProbe
return;
if (target)
{
DWORD process{};
GetWindowThreadProcessId(target, &process);
int focusedProcess{};
if (!process || FAILED(element->get_CurrentProcessId(&focusedProcess)) ||
process != static_cast<DWORD>(focusedProcess) || GetForegroundWindow() != target)
if (GetForegroundWindow() != target || !focusedTextBelongsToWindow(automation, element, target))
{
status = L"focused-control-changed";
return;
+59 -2
View File
@@ -1,5 +1,6 @@
#include "app.h"
#include "diagnostics.h"
#include "paste_probe.h"
#include <algorithm>
#include <iostream>
#include <fstream>
@@ -61,6 +62,10 @@ namespace
{
ks::App *app{};
HWND host{}, field{};
HWND externalEditor{};
ULONGLONG externalPopupUntil{};
bool insertExternalSnippet{};
constexpr wchar_t externalSnippetText[] = L"snippet test";
ks::Clip saved;
bool snippetRecoveryOnly = false;
LONG unfilteredSnippetWidth{};
@@ -337,6 +342,47 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
}
switch (stage++)
{
case 101:
require(GetForegroundWindow() == externalEditor, "external editor retains foreground before typing");
app->settings.snippets = {{L";ksw-regression", externalSnippetText}};
app->resetInput();
externalPopupUntil = GetTickCount64() + 2000;
typeKeys({VK_OEM_1});
break;
case 102:
{
if (GetForegroundWindow() != externalEditor)
throw std::runtime_error("External editor lost foreground while typing");
const bool visible = ks::InputRegressionAccess::suggestionsVisible(*app);
if (!visible && GetTickCount64() < externalPopupUntil)
{
stage = 102;
break;
}
if (!visible) typeKeys({VK_BACK});
else if (insertExternalSnippet) typeKeys({VK_TAB});
else typeKeys({VK_ESCAPE, VK_BACK});
require(visible, "semicolon shows suggestions in the external editor");
break;
}
case 103:
if (insertExternalSnippet)
{
require(GetForegroundWindow() == externalEditor, "insertion leaves the external editor focused");
ks::PasteProbe probe(true, externalEditor);
const auto text = probe.read(static_cast<int>(std::size(externalSnippetText) - 1));
const bool inserted = text && *text == externalSnippetText;
if (inserted)
{
ks::chord('A', MOD_CONTROL);
typeKeys({VK_BACK});
}
require(inserted, "Tab inserts the selected snippet in the external editor");
}
else
require(!ks::InputRegressionAccess::suggestionsVisible(*app), "Escape dismisses external suggestions");
finish();
break;
case 0:
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
@@ -1196,6 +1242,14 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
} // namespace
int main(int argc, char **argv)
{
const bool externalEditorTest = argc > 1 && std::string_view(argv[1]) == "--snippet-external-editor";
if (externalEditorTest)
{
insertExternalSnippet = argc > 2 && std::string_view(argv[2]) == "--insert";
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
externalEditor = GetForegroundWindow();
if (!externalEditor) return 1;
}
conversionOnly = argc > 1 && std::string(argv[1]) == "--conversion-only";
typosOnly = argc > 1 && std::string(argv[1]) == "--typos-only";
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
@@ -1362,7 +1416,7 @@ int main(int argc, char **argv)
if (language == 0x419)
ru = i;
}
if (en < 0 || ru < 0)
if (!externalEditorTest && (en < 0 || ru < 0))
throw std::runtime_error(
"Integration test requires installed English US and Russian layouts");
WNDCLASSW cls{};
@@ -1372,7 +1426,8 @@ int main(int argc, char **argv)
cls.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
RegisterClassW(&cls);
host = CreateWindowW(cls.lpszClassName, L"KSwitcher — automated test editor",
WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 100, 650, 320, nullptr, nullptr,
WS_OVERLAPPEDWINDOW | (externalEditorTest ? 0 : WS_VISIBLE),
100, 100, 650, 320, nullptr, nullptr,
cls.hInstance, nullptr);
field =
CreateWindowW(L"EDIT", L"", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_MULTILINE | ES_WANTRETURN,
@@ -1392,6 +1447,8 @@ int main(int argc, char **argv)
stage = 93;
if (argc > 1 && std::string(argv[1]) == "--snippet-word-boundaries")
stage = 84;
if (externalEditorTest)
stage = 101;
SetTimer(host, 1, 100, nullptr);
auto forwarding = SetWindowsHookExW(WH_KEYBOARD_LL,forwardingHook,GetModuleHandleW(nullptr),0);
require(forwarding!=nullptr,"downstream forwarding fixture installed before application hook");