Files
hrynco-kswitcher/tests/chat_profiles.cpp
T
agrynco ee9b953533 Release KSwitcher v0.7.3
Commit Settings drafts through Apply or Save and make Close and Cancel reflect the pending state.
2026-11-24 21:22:57 +02:00

1167 lines
78 KiB
C++

#include "app.h"
#include "mouse_buttons.h"
#include "ocr.h"
#include "screenshot.h"
#include "lan_pairing.h"
#include "settings_ui.h"
#include <iostream>
#include <commctrl.h>
namespace
{
constexpr int SettingsApply = 272;
HWND findTestWindow(LPCWSTR className, LPCWSTR title)
{
HWND window=nullptr;
while((window=FindWindowExW(nullptr,window,className,title))) {
DWORD process{}; GetWindowThreadProcessId(window,&process);
if(process==GetCurrentProcessId()) return window;
}
return nullptr;
}
int passed{};
void require(bool ok, const char *message)
{
if (!ok) throw std::runtime_error(message);
++passed;
}
void settingsWindowStateChecks(const std::filesystem::path &root)
{
ks::App app(GetModuleHandleW(nullptr), true, root);
ks::showSettings(app);
auto settings = app.settingsWindow;
MONITORINFO monitor{sizeof(monitor)};
require(GetMonitorInfoW(MonitorFromWindow(settings, MONITOR_DEFAULTTONEAREST), &monitor),
"settings opens on a monitor");
const int dpi = GetDpiForWindow(settings);
const auto work = monitor.rcWork;
const int width = std::min<int>(work.right - work.left, MulDiv(810, dpi, 96));
const int height = std::min<int>(work.bottom - work.top, MulDiv(490, dpi, 96));
SetWindowPos(settings, nullptr, std::min<int>(work.left + MulDiv(45, dpi, 96), work.right - width),
std::min<int>(work.top + MulDiv(55, dpi, 96), work.bottom - height),
width, height, SWP_NOZORDER | SWP_NOACTIVATE);
selectSettingsPage(settings, 14);
const auto splitter = GetDlgItem(settings, 270);
SendMessageW(splitter, WM_KEYDOWN, VK_RIGHT, 0);
SendMessageW(splitter, WM_KEYDOWN, VK_RIGHT, 0);
RECT frame{}, split{};
GetWindowRect(settings, &frame);
GetWindowRect(splitter, &split);
SendMessageW(settings, WM_CLOSE, 0, 0);
require(!app.settingsWindow && std::filesystem::exists(root / L"configurator-window.json") &&
!std::filesystem::exists(root / L"settings.json"), "closing saves only display preferences");
ks::showSettings(app);
settings = app.settingsWindow;
RECT restored{}, restoredSplit{};
GetWindowRect(settings, &restored);
GetWindowRect(GetDlgItem(settings, 270), &restoredSplit);
const auto navigation = settingsNavigation(settings);
require(EqualRect(&restored, &frame) && EqualRect(&restoredSplit, &split),
"reopen restores position, size and sidebar width");
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 14) &&
IsWindowVisible(GetDlgItem(settingsViewport(settings), 412)), "reopen restores the nested selection");
ShowWindow(settings, SW_MAXIMIZE);
SendMessageW(settings, WM_CLOSE, 0, 0);
ks::showSettings(app);
settings = app.settingsWindow;
require(IsZoomed(settings), "reopen restores maximization");
ShowWindow(settings, SW_RESTORE);
GetWindowRect(settings, &restored);
require(EqualRect(&restored, &frame), "normal frame survives maximization");
ShowWindow(settings, SW_MINIMIZE);
SendMessageW(settings, WM_CLOSE, 0, 0);
ks::showSettings(app);
settings = app.settingsWindow;
GetWindowRect(settings, &restored);
require(!IsIconic(settings) && EqualRect(&restored, &frame), "closing minimized retains the normal frame");
SendMessageW(settings, WM_CLOSE, 0, 0);
const auto file = root / L"configurator-window.json";
const auto offscreen = R"({"frame":[-20000,-20000,-18000,-18800],"page":"retired-page"})";
ks::atomicWrite(file, ks::Bytes(offscreen, offscreen + std::char_traits<char>::length(offscreen)));
ks::showSettings(app);
settings = app.settingsWindow;
GetWindowRect(settings, &restored);
GetMonitorInfoW(MonitorFromWindow(settings, MONITOR_DEFAULTTONEAREST), &monitor);
require(restored.left >= monitor.rcWork.left && restored.top >= monitor.rcWork.top &&
restored.right <= monitor.rcWork.right && restored.bottom <= monitor.rcWork.bottom,
"placement from a disconnected monitor fits the current work area");
require(TreeView_GetSelection(settingsNavigation(settings)) == settingsSection(settingsNavigation(settings), 0),
"unknown page falls back to General");
SendMessageW(settings, WM_CLOSE, 0, 0);
}
std::wstring pickTestApplication(HWND picker, bool cancel = false)
{
RECT dialogBounds{};
GetWindowRect(GetParent(picker), &dialogBounds);
MONITORINFO monitor{sizeof(monitor)};
require(GetMonitorInfoW(MonitorFromWindow(picker, MONITOR_DEFAULTTONEAREST), &monitor),
"monitor work area available");
const auto targetX = std::clamp(dialogBounds.left + 32, monitor.rcWork.left, monitor.rcWork.right - 120);
const auto targetY = std::clamp(dialogBounds.top + 100, monitor.rcWork.top, monitor.rcWork.bottom - 48);
HWND target = CreateWindowExW(WS_EX_TOPMOST | WS_EX_NOACTIVATE, L"EDIT", L"Picker fixture",
WS_POPUP | WS_VISIBLE, targetX, targetY, 120, 48,
nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
require(picker && target, "window picker and target available");
POINT drop{targetX + 1, targetY + 1};
require(GetAncestor(WindowFromPoint(drop), GA_ROOT) == target, "fixture window is under the drop point");
ScreenToClient(picker, &drop);
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
require(GetCapture() == picker, "window picker captures drag");
SendMessageW(picker, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(drop.x, drop.y));
HWND outline = findTestWindow(L"KSwitcher.AppPickerOutline", nullptr);
RECT outlineBounds{}, targetBounds{};
require(IsWindowVisible(outline) && GetWindowRect(outline, &outlineBounds) &&
GetWindowRect(target, &targetBounds) && EqualRect(&outlineBounds, &targetBounds), "drag highlights the target window");
if (cancel) SendMessageW(picker, WM_KEYDOWN, VK_ESCAPE, 0);
else SendMessageW(picker, WM_LBUTTONUP, 0, MAKELPARAM(drop.x, drop.y));
require(!IsWindow(outline) && GetCapture() != picker, "finishing the drag clears the outline and releases capture");
auto pickedApp = ks::applicationName(ks::processName(target));
DestroyWindow(target);
return pickedApp;
}
void lanWindowLayoutChecks(const std::filesystem::path &root)
{
const std::string peer(32,'b');
const nlohmann::json fixture={{"version",1},{"id",std::string(32,'a')},{"enabled",false},
{"trusted",{{peer,{{"name","Paired desktop"},{"key",std::string(64,'f')}}}}},
{"positions",{{peer,nlohmann::json::array({1,0})}}}};
const auto data=fixture.dump();
std::filesystem::create_directories(root);
ks::atomicWrite(root/L"lan-pairing.bin",ks::protect(ks::Bytes(data.begin(),data.end())));
ks::App app(GetModuleHandleW(nullptr),true,root);
ks::showSettings(app);
HWND lan=showComputerSettings(app.settingsWindow);
require(lan && IsWindowVisible(lan),"Computers panel is visible");
require(!GetDlgItem(lan, 726) && !GetDlgItem(lan, 730), "Computers panel omits direct file transfer actions");
require(IsWindowVisible(GetDlgItem(lan, 727)) && IsWindowVisible(GetDlgItem(lan, 728)),
"Computers panel retains current and previous diagnostic log actions");
const auto dpi=GetDpiForWindow(lan);
RECT client{};GetClientRect(lan,&client);
std::vector<std::pair<int,RECT>> placed;
for(HWND child=GetWindow(lan,GW_CHILD);child;child=GetWindow(child,GW_HWNDNEXT))
{
if (!IsWindowVisible(child)) continue;
RECT bounds{};GetWindowRect(child,&bounds);
MapWindowPoints(nullptr,lan,reinterpret_cast<POINT *>(&bounds),2);
require(bounds.left>=0&&bounds.top>=0&&bounds.right<=client.right&&bounds.bottom<=client.bottom,
"Computers control is fully visible");
const int id=GetDlgCtrlID(child);
for(const auto &[otherId,other]:placed)
{
RECT overlap{};
if(IntersectRect(&overlap,&bounds,&other))
throw std::runtime_error("Computers controls overlap: "+std::to_string(id)+" and "+std::to_string(otherId)+
" at "+std::to_string(overlap.left)+","+std::to_string(overlap.top));
}
placed.push_back({id,bounds});
}
auto boundsFor = [&](int id)
{
RECT rect{};
require(GetWindowRect(GetDlgItem(lan, id), &rect), "pairing control has bounds");
return rect;
};
const auto code = boundsFor(703), generate = boundsFor(704);
const auto pair = boundsFor(705), cancel = boundsFor(706), forget = boundsFor(707);
const auto help = boundsFor(722), permission = boundsFor(729);
const auto currentLog = boundsFor(727), previousLog = boundsFor(728);
require(help.bottom < permission.top && permission.bottom < currentLog.top &&
currentLog.top == previousLog.top && currentLog.bottom == previousLog.bottom &&
std::abs((currentLog.right - currentLog.left) - (previousLog.right - previousLog.left)) <= 1 &&
currentLog.left == permission.left && std::abs(previousLog.right - permission.right) <= 1,
"diagnostic logs have a separate full-width group with equal actions");
const int gap = MulDiv(10, dpi, 96);
require(code.top == generate.top && code.bottom == generate.bottom &&
std::abs(generate.left - code.right - gap) <= 1, "code input and Generate code share the same row");
require(pair.top == cancel.top && cancel.top == forget.top &&
pair.bottom == cancel.bottom && cancel.bottom == forget.bottom &&
std::abs((pair.right - pair.left) - (cancel.right - cancel.left)) <= 1 &&
std::abs((cancel.right - cancel.left) - (forget.right - forget.left)) <= 1 &&
pair.left == code.left && std::abs(forget.right - generate.right) <= 1 &&
std::abs(cancel.left - pair.right - gap) <= 1 && std::abs(forget.left - cancel.right - gap) <= 1,
"pairing buttons align with the code row and have equal widths and gaps");
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
auto dc=GetDC(lan);
auto screenshot=ks::screenshotClip(dc,client.right,client.bottom,{});
ReleaseDC(lan,dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-compact-layout.png",
ks::encodePng(ks::decodeImage(screenshot)));
SendMessageW(app.settingsWindow,WM_COMMAND,IDCANCEL,0);
std::cout<<"Computers layout verified at "<<dpi<<" DPI.\n";
}
void contextChecks()
{
ks::Settings scoped;
scoped.snippets = {{L";sig", L"Global", L"global"},
{L";sig", L"Work", L"teams", {L"MS-Teams.EXE", L"OUTLOOK.exe"}},
{L";sig", L"Personal", L"telegram", {L"telegram"}}};
ks::validateSettings(scoped);
require(ks::snippetAppPriority(scoped.snippets[1], L"ms-teams") > ks::snippetAppPriority(scoped.snippets[0], L"ms-teams"), "app snippet precedes global regardless of list order");
require(ks::snippetAppPriority(scoped.snippets[1], L"Telegram.exe") == 0, "restricted snippet cannot run in another app");
require(ks::snippetAppPriority(scoped.snippets[1], L"Outlook.EXE") == 2, "restricted snippet also runs in its second application");
require(ks::snippetAppPriority(scoped.snippets[0], L"") == 1, "legacy/global snippets remain available");
auto scopedRoundtrip = ks::decodeSettings(ks::encodeSettings(scoped), {});
require(scopedRoundtrip.snippets[1].apps == std::vector<std::wstring>{L"ms-teams", L"outlook"}, "scopes normalize and persist");
require(scopedRoundtrip.snippets[0].apps.empty(), "absent scope remains global");
auto collision = scoped; collision.snippets.push_back({L";SIG", L"Ambiguous", L"other", {L"outlook.exe"}});
bool collisionRejected=false;try { ks::validateSettings(collision); } catch(...) { collisionRejected=true; }
require(collisionRejected, "overlapping app lists with same trigger rejected");
auto emptyScope = scoped; emptyScope.snippets[1].apps={L""};
bool emptyRejected=false;try { ks::validateSettings(emptyScope); } catch(...) { emptyRejected=true; }
require(emptyRejected, "empty explicit restriction cannot become global");
require(ks::telegramWebKey(L"https://web.telegram.org/k/#@Example") == L"telegram-web\n@example", "Telegram Web username normalized");
require(ks::telegramWebKey(L"web.telegram.org/a/#-123456") == L"telegram-web\n-123456", "Telegram Web numeric peer");
for (const auto *url : {L"https://web.telegram.org/k/", L"https://web.telegram.org.evil/k/#@example",
L"http://web.telegram.org/k/#@example", L"https://evil/web.telegram.org/k/#@example",
L"https://web.telegram.org/k/#@example?foo", L"https://web.telegram.org/k/#@",
L"https://web.telegram.org/k/#-", L"https://web.telegram.org/k/#settings"})
require(ks::telegramWebKey(url).empty(), "Reject non-chat or untrusted Telegram Web URL");
const auto key = ks::chatKey(L"Telegram.exe", L"\u200eТестовий чат \u2013 (12)");
require(key == L"telegram\nТестовий чат", "Telegram unread suffix");
require(ks::chatKey(L"Telegram", L"Тестовий чат") == key, "stable unread profile");
require(ks::chatKey(L"Telegram", L"Team (2026)") == L"telegram\nTeam (2026)", "preserve parentheses");
require(ks::chatKey(L"Telegram", L"Telegram").empty(), "no profile on home");
require(ks::chatKey(L"Viber", L"Rakuten Viber").empty(), "Viber generic window title is not a chat");
require(ks::chatKey(L"ms-teams", L"Chat | Alice | Microsoft Teams") == L"ms-teams\nAlice", "Teams chat");
require(ks::chatKey(L"ms-teams", L"Calendar | Alice | Microsoft Teams").empty(), "Teams calendar excluded");
require(ks::chatKey(L"ms-teams", L"Chat | Microsoft Teams").empty(), "Teams chat home excluded");
require(ks::chatKey(L"other", L"Chat | Alice | Microsoft Teams").empty(), "app identity required");
ks::Settings settings;
settings.cycle = {L"win:04090409", L"win:04220422", L"win:04190419"};
settings.chatCycles[key] = {settings.cycle[1], settings.cycle[0]};
settings.chatCycles[L"viber\nТестовий контакт"] = {settings.cycle[1], settings.cycle[0]};
settings.chatCycles[L"telegram-web\n@example"] = {settings.cycle[0], settings.cycle[1]};
std::vector<ks::Layout> installed(3);
for (size_t i = 0; i < installed.size(); ++i)
{
installed[i].id = settings.cycle[i];
installed[i].handle = (HKL)(uintptr_t)(i + 1);
}
auto subset = settings.chatCycles[key];
require(ks::nextChatLayout(subset, installed, installed[1].handle, false) == installed[0].handle, "cycle within subset");
require(ks::nextChatLayout(subset, installed, installed[0].handle, false) == installed[1].handle, "wrap skips excluded language");
require(ks::nextChatLayout(subset, installed, installed[2].handle, false) == installed[1].handle, "outside subset enters first language");
require(ks::nextChatLayout(settings.cycle, installed, installed[0].handle, true) == installed[2].handle, "reverse wraps");
require(ks::nextChatLayout({settings.cycle[1]}, installed, installed[0].handle, false) == installed[1].handle, "single language selects allowed layout");
require(!ks::nextChatLayout({L"win:04070407"}, installed, installed[0].handle, false), "missing layout is not activated");
require(ks::nextConversionLayout(L"", installed, {1}, 0) == 1, "conversion uses single allowed language");
require(ks::chatCycle(settings, key, installed) == settings.chatCycles[key], "profile order");
require(ks::chatCycle(settings, L"telegram\nOther", installed) == settings.cycle, "unknown fallback");
require(ks::decodeSettings(ks::encodeSettings(settings), installed).chatCycles == settings.chatCycles, "Unicode roundtrip");
require(ks::decodeSettings({}, installed).chatCycles.empty(), "old defaults without profiles");
auto withoutProfiles = settings;
withoutProfiles.chatCycles.clear();
require(ks::sharedSyncSettings(settings) != ks::sharedSyncSettings(withoutProfiles), "profiles included in sync");
auto restored = ks::restoreSyncSettings(ks::sharedSyncSettings(settings), withoutProfiles, installed, false);
require(restored.chatCycles == settings.chatCycles, "sync transfers chat profiles to another PC");
settings.chatCycles[key] = {settings.cycle[1]};
require(ks::chatCycle(settings, key, installed).size() == 1, "one-language profile");
settings.chatCycles[key] = {L"win:04070407"};
require(ks::chatCycle(settings, key, installed) == settings.cycle, "missing layouts fallback");
settings.chatCycles[key] = {};
bool rejected = false;
try { ks::encodeSettings(settings); } catch (...) { rejected = true; }
require(rejected, "empty profile rejected");
settings.chatCycles[key] = {settings.cycle[0], settings.cycle[0]};
rejected = false;
try { ks::encodeSettings(settings); } catch (...) { rejected = true; }
require(rejected, "duplicate profile layout rejected");
ks::ChatSwitchHook hook;
require(hook.update(VK_SPACE, true, MOD_WIN, false) == 0, "unprofiled Win+Space passes");
require(hook.update(VK_SPACE, true, MOD_WIN, true) == 1, "Win+Space forward");
require(hook.update(VK_SPACE, true, MOD_WIN, true) == -1, "consume repeat");
require(hook.update(VK_SPACE, false, 0, false) == -1, "release after profile change");
require(hook.update(VK_SPACE, true, MOD_WIN | MOD_SHIFT, true) == 2, "reverse cycle");
hook.update(VK_SPACE, false, 0, true);
require(hook.update(VK_LSHIFT, true, MOD_ALT, true) == 1, "Alt then Shift");
hook.update(VK_LSHIFT, false, 0, true);
require(hook.update(VK_LMENU, true, MOD_SHIFT, true) == 1, "Shift then Alt");
hook.update(VK_LMENU, false, 0, true);
require(hook.update(VK_LSHIFT, true, MOD_ALT | MOD_CONTROL, true) == 0, "do not consume Ctrl+Alt+Shift");
require(hook.update('A', true, MOD_ALT, true) == 0, "ordinary keys pass");
}
void snippetEditorChecks(ks::App &app, const std::filesystem::path &root)
{
app.settings.snippets = {{L";scope", L"Example{pause:50}", L"scope-fixture"}};
ks::showSettings(app);
HWND parent = app.settingsWindow;
auto saveEnabled = [&] { return IsWindowEnabled(GetDlgItem(parent, IDOK)); };
auto status = [&] {
wchar_t text[256]{};
GetDlgItemTextW(parent, 261, text, 256);
return std::wstring(text);
};
require(!saveEnabled(),"Settings starts clean before editing a snippet");
ks::showSnippets(app);
HWND snippets = settingsViewport(parent);
require(!app.snippetsWindow && IsWindowVisible(GetDlgItem(snippets, 301)),
"opening Snippets from Settings selects its inline editor");
SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0);
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
require(!GetDlgItem(snippets, 318), "inline editor has only the Settings Save button");
require(!saveEnabled() && status()==L"No unsaved settings.", "selecting a snippet leaves the editor clean");
const auto replacement = GetDlgItem(snippets, 303);
auto replaceSnippetText = [&](const wchar_t *text) {
SendMessageW(replacement, EM_SETSEL, 0, -1);
SendMessageW(replacement, EM_REPLACESEL, TRUE, reinterpret_cast<LPARAM>(text));
};
auto selectInsertion = [](HWND picker, int action) {
SendDlgItemMessageW(picker, 321, CB_SETCURSEL, action, 0);
SendMessageW(picker, WM_COMMAND, MAKEWPARAM(321, CBN_SELCHANGE), 0);
};
auto openInsertion = [&](int action) {
SendMessageW(snippets, WM_COMMAND, 320, 0);
const auto picker = findTestWindow(L"KSwitcher.SnippetInsertion", nullptr);
require(picker && GetWindow(picker, GW_OWNER) == parent && !IsWindowEnabled(parent),
"insertion picker opens over the snippet editor");
selectInsertion(picker, action);
return picker;
};
auto captureInsertion = [](HWND picker, const wchar_t *file) {
RedrawWindow(picker, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
RECT client{};
GetClientRect(picker, &client);
auto dc = GetDC(picker);
auto image = ks::screenshotClip(dc, client.right, client.bottom, {});
ReleaseDC(picker, dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / file,
ks::encodePng(ks::decodeImage(image)));
};
SendMessageW(replacement, EM_SETSEL, 7, -1);
auto insertion = openInsertion(0);
const auto parameter = GetDlgItem(insertion, 323);
RECT actionRect{}, markerParameter{}, pauseParameter{}, dialog{};
GetWindowRect(GetDlgItem(insertion, 321), &actionRect);
GetWindowRect(parameter, &markerParameter);
GetClientRect(insertion, &dialog);
require(IsWindowVisible(parameter) && !IsWindowEnabled(parameter), "cursor marker keeps a visible disabled parameter");
require(actionRect.top == markerParameter.top && actionRect.right < markerParameter.left &&
dialog.bottom < MulDiv(170, GetDpiForWindow(insertion), 96), "compact picker places Action and Parameter on one row");
captureInsertion(insertion, L"snippet-insertion-marker.png");
selectInsertion(insertion, 2);
GetWindowRect(parameter, &pauseParameter);
require(IsWindowVisible(parameter) && IsWindowEnabled(parameter) && EqualRect(&markerParameter, &pauseParameter),
"pause enables its parameter without moving the field");
require(pauseParameter.right - pauseParameter.left <= MulDiv(70, GetDpiForWindow(insertion), 96) &&
SendMessageW(parameter, EM_GETLIMITTEXT, 0, 0) == 5, "pause uses a compact field limited to five digits");
SetDlgItemTextW(insertion, 323, L"10001");
require(!IsWindowEnabled(GetDlgItem(insertion, IDOK)), "invalid pause cannot be inserted");
SetDlgItemTextW(insertion, 323, L"10000");
require(IsWindowEnabled(GetDlgItem(insertion, IDOK)), "five-digit maximum pause fits the numeric field");
SetDlgItemTextW(insertion, 323, L"100");
require(IsWindowEnabled(GetDlgItem(insertion, IDOK)), "valid pause enables Insert");
captureInsertion(insertion, L"snippet-insertion.png");
SendMessageW(insertion, WM_COMMAND, IDOK, 0);
require(saveEnabled() && status().find(L"Unsaved snippets") == 0,
"editing just the pause enables the Settings Save button");
auto replacementText = [&] {
wchar_t text[256]{};
GetWindowTextW(replacement, text, 256);
return std::wstring(text);
};
require(replacementText() == L"Example{pause:100}", "insertion replaces the selected pause");
insertion = openInsertion(4);
RECT chordParameter{};
GetWindowRect(GetDlgItem(insertion, 323), &chordParameter);
require(chordParameter.right - chordParameter.left > pauseParameter.right - pauseParameter.left &&
SendDlgItemMessageW(insertion, 323, EM_GETLIMITTEXT, 0, 0) > 5, "key combinations retain a wider input");
require((GetWindowLongPtrW(GetDlgItem(insertion, 323), GWL_STYLE) & ES_READONLY) &&
!IsWindowEnabled(GetDlgItem(insertion, IDOK)), "key recorder starts empty and rejects typed text");
auto record = [](HWND picker, std::initializer_list<WORD> keys) {
SendDlgItemMessageW(picker, 323, WM_KEYUP, VK_SPACE, 0);
for (auto key : keys) SendMessageW(picker, WM_APP + 160, key, TRUE);
for (auto key : keys) SendMessageW(picker, WM_APP + 160, key, FALSE);
};
record(insertion, {VK_LCONTROL});
require(!IsWindowEnabled(GetDlgItem(insertion, IDOK)), "one pressed key cannot supply a combination");
auto keyText = [&] {
wchar_t text[32]{};
GetDlgItemTextW(insertion, 323, text, 32);
return std::wstring(text);
};
SendDlgItemMessageW(insertion, 323, WM_KEYUP, VK_SPACE, 0);
SendMessageW(insertion, WM_APP + 160, VK_LCONTROL, TRUE);
require(keyText() == L"Ctrl", "first key appears before release");
SendMessageW(insertion, WM_APP + 160, VK_RETURN, TRUE);
require(keyText() == L"Ctrl+Enter" && !IsWindowEnabled(GetDlgItem(insertion, IDOK)),
"the entire chord appears while keys are still held");
captureInsertion(insertion, L"snippet-key-held.png");
SendMessageW(insertion, WM_APP + 160, VK_LCONTROL, FALSE);
require(keyText() == L"Ctrl+Enter" && !IsWindowEnabled(GetDlgItem(insertion, IDOK)),
"releasing one key keeps the chord visible while recording finishes");
SendMessageW(insertion, WM_APP + 160, VK_RETURN, FALSE);
require(IsWindowEnabled(GetDlgItem(insertion, IDOK)), "recorded Ctrl+Enter enables insertion");
captureInsertion(insertion, L"snippet-key-recorded.png");
SendMessageW(insertion, WM_COMMAND, IDOK, 0);
require(replacementText() == L"Example{pause:100}{{ctrl}}+{{return}}", "chord converts Enter to the supported key spelling");
insertion = openInsertion(1);
require(IsWindowVisible(GetDlgItem(insertion, 323)) && !IsWindowEnabled(GetDlgItem(insertion, 323)),
"Enter marker keeps its parameter visible and disabled");
SendMessageW(insertion, WM_COMMAND, IDOK, 0);
insertion = openInsertion(0);
SendMessageW(insertion, WM_COMMAND, IDOK, 0);
require(replacementText().ends_with(L"{enter}{cursor}"), "Enter and cursor markers use the same picker");
insertion = openInsertion(3);
record(insertion, {VK_RSHIFT});
wchar_t keyName[32]{};
GetDlgItemTextW(insertion, 323, keyName, 32);
require(std::wstring(keyName) == L"ShiftR" && IsWindowEnabled(GetDlgItem(insertion, IDOK)),
"tap recording recognizes a right-hand modifier by itself");
SendMessageW(insertion, WM_COMMAND, IDCANCEL, 0);
require(replacementText().ends_with(L"{enter}{cursor}"), "cancelling insertion preserves replacement text");
replaceSnippetText(L"Example{pause:50}");
require(!saveEnabled() && status()==L"No unsaved settings.", "reverting the pause clears the pending change");
replaceSnippetText(L"Example{pause:100}");
require(IsDlgButtonChecked(snippets,314)==BST_UNCHECKED, "old snippet shows everywhere");
HWND scopePicker = GetDlgItem(snippets, 753);
require(IsWindowVisible(scopePicker) && !IsWindowEnabled(scopePicker), "global snippet disables the window picker");
CheckDlgButton(snippets,314,BST_CHECKED);
SendMessageW(snippets,WM_COMMAND,314,0);
require(IsWindowEnabled(scopePicker), "restricting the snippet enables the window picker");
SetDlgItemTextW(snippets,315,L"Notepad.exe");
auto secondApp = SendDlgItemMessageW(snippets,316,CB_ADDSTRING,0,(LPARAM)L"MS-Teams.EXE");
SendDlgItemMessageW(snippets,316,CB_SETCURSEL,secondApp,0);
SendMessageW(snippets,WM_COMMAND,317,0);
SendMessageW(snippets,WM_COMMAND,317,0);
wchar_t appList[128]{};
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList)==L"Notepad.exe, MS-Teams.EXE", "Add app appends a second application without duplicates");
pickTestApplication(scopePicker, true);
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList)==L"Notepad.exe, MS-Teams.EXE", "cancelling the picker preserves the snippet scope");
auto pickedProcess = pickTestApplication(scopePicker);
pickTestApplication(scopePicker);
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList) == L"Notepad.exe, MS-Teams.EXE, " + pickedProcess + L".exe",
"dropping on a window appends its process once to the existing snippet scope");
const std::vector<std::wstring> savedScope{L"notepad", L"ms-teams", pickedProcess};
RedrawWindow(snippets,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
RECT snippetRect{};GetClientRect(snippets,&snippetRect);
HDC snippetDc=GetDC(snippets);
auto snippetImage=ks::screenshotClip(snippetDc,snippetRect.right,snippetRect.bottom,{});
ReleaseDC(snippets,snippetDc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"snippet-scopes.png",ks::encodePng(ks::decodeImage(snippetImage)));
const auto logSetting = !app.settings.writeLog;
CheckDlgButton(settingsViewport(parent), 208, logSetting ? BST_CHECKED : BST_UNCHECKED);
SendMessageW(parent, WM_COMMAND, MAKEWPARAM(208, BN_CLICKED), 0);
SendMessageW(parent, WM_COMMAND, IDOK, 0);
require(!IsWindow(parent), "Settings Save closes the inline snippet editor");
const auto savedSettings = ks::loadSettings(root / L"settings.json", app.layouts);
require(savedSettings.snippets[0].apps == savedScope && savedSettings.snippets[0].text == L"Example{pause:100}" &&
savedSettings.writeLog == logSetting, "one Save persists the snippet and general settings together");
ks::showSnippets(app);snippets=app.snippetsWindow;
SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0);
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
require(IsDlgButtonChecked(snippets,314)==BST_CHECKED, "scope restored when reopening editor");
SetDlgItemTextW(snippets,315,L"chrome.exe");
pickTestApplication(GetDlgItem(snippets, 753));
GetDlgItemTextW(snippets,315,appList,128);
require(std::wstring(appList) == L"chrome.exe, " + pickedProcess + L".exe",
"standalone snippet editor adds the dropped application");
SendMessageW(snippets,WM_COMMAND,IDCANCEL,0);
require(app.settings.snippets[0].apps==savedScope, "cancel preserves existing scope");
}
}
int main(int argc,char **argv)
{
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-chat-tests-" + std::to_wstring(GetCurrentProcessId()));
try
{
if(argc==2 && std::string_view(argv[1])=="--lan-layout")
{
lanWindowLayoutChecks(root);
std::filesystem::remove_all(root);
CoUninitialize();
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--snippets")
{
{
ks::App app(GetModuleHandleW(nullptr), true, root);
if (app.layouts.empty()) app.layouts.push_back({nullptr, L"win:04090409", L"English"});
app.settings.cycle = {app.layouts.front().id};
app.settings.toggle = app.settings.casing = app.settings.translit = app.settings.undo = L"";
app.settings.clipboard = app.settings.screenshot = L"";
app.settings.direct.assign(app.layouts.size(), L"");
app.settings.history = app.settings.autoCorrect = false;
snippetEditorChecks(app, root);
}
std::filesystem::remove_all(root);
CoUninitialize();
std::cout << "PASS snippet editor (" << passed << " checks)\n";
return 0;
}
contextChecks();
settingsWindowStateChecks(root / L"window-state");
{
ks::App app(GetModuleHandleW(nullptr), true, root);
require(!app.layouts.empty(), "installed layouts available");
app.settings.toggle = app.settings.casing = app.settings.translit = app.settings.undo = L"";
app.settings.clipboard = app.settings.screenshot = L"";
app.settings.direct.assign(app.layouts.size(), L"");
app.settings.history = app.settings.autoCorrect = false;
const std::wstring key = L"telegram\n! Fixture chat";
app.settings.chatCycles[key] = {app.layouts[0].id};
ks::showSettings(app);
HWND parent = app.settingsWindow;
auto saveEnabled=[&] { return IsWindowEnabled(GetDlgItem(parent,IDOK))!=FALSE; };
auto status=[&] { wchar_t text[256]{}; GetDlgItemTextW(parent,261,text,256); return std::wstring(text); };
const auto applyEnabled = [&] { return IsWindowEnabled(GetDlgItem(parent, SettingsApply)) != FALSE; };
const auto closeCaption = [&] {
wchar_t caption[24]{};
GetDlgItemTextW(parent, IDCANCEL, caption, std::size(caption));
return std::wstring(caption);
};
require(!saveEnabled() && !applyEnabled() && status() == L"No unsaved settings." && closeCaption() == L"&Close",
"new Settings offers Close and disables Save and Apply");
SendMessageW(parent,WM_COMMAND,IDOK,0);
require(IsWindow(parent),"Save command with no changes does not apply or close Settings");
bool originalLog=IsDlgButtonChecked(settingsViewport(parent),208)==BST_CHECKED;
CheckDlgButton(settingsViewport(parent),208,originalLog?BST_UNCHECKED:BST_CHECKED);
SendMessageW(parent,WM_COMMAND,MAKEWPARAM(208,BN_CLICKED),0);
require(saveEnabled() && applyEnabled() && status().find(L"Unsaved settings") == 0 && closeCaption() == L"&Cancel",
"checkbox edits offer Cancel, Save and Apply");
CheckDlgButton(settingsViewport(parent),208,originalLog?BST_CHECKED:BST_UNCHECKED);
SendMessageW(parent,WM_COMMAND,MAKEWPARAM(208,BN_CLICKED),0);
require(!saveEnabled() && !applyEnabled() && closeCaption() == L"&Close",
"reverting the checkbox restores Close");
wchar_t originalLimit[32]{}; GetDlgItemTextW(settingsViewport(parent),240,originalLimit,32);
SetDlgItemTextW(settingsViewport(parent),240,L"invalid");
require(saveEnabled(),"invalid text remains an unsaved edit");
SetDlgItemTextW(settingsViewport(parent),240,originalLimit);
require(!saveEnabled(),"restoring valid original text clears dirty state");
SendMessageW(parent,WM_COMMAND,257,0);
HWND ocr=findTestWindow(L"KSwitcher.OcrOptions",nullptr);
require(ocr!=nullptr,"OCR preferences open");
wchar_t languages[128]{}; GetDlgItemTextW(ocr,503,languages,128);
SetDlgItemTextW(ocr,503,L"eng");
SendMessageW(ocr,WM_COMMAND,IDCANCEL,0);
require(!saveEnabled(),"cancelled child changes leave Settings clean");
SendMessageW(parent,WM_COMMAND,257,0);
ocr=findTestWindow(L"KSwitcher.OcrOptions",nullptr);
SetDlgItemTextW(ocr,503,std::wstring(languages)==L"eng"?L"ukr":L"eng");
SendMessageW(ocr,WM_COMMAND,IDOK,0);
require(!IsWindow(ocr) && saveEnabled(),"accepted OCR edits enable parent Save");
SendMessageW(parent,WM_COMMAND,257,0);
ocr=findTestWindow(L"KSwitcher.OcrOptions",nullptr);
SetDlgItemTextW(ocr,503,languages);
SendMessageW(ocr,WM_COMMAND,IDOK,0);
require(!saveEnabled(),"reverting OCR draft in child clears parent dirty state");
const auto correction = settingsViewport(parent);
require(!GetDlgItem(correction, 255), "General no longer has a correction options button");
selectSettingsPage(parent, 16);
require(IsWindowVisible(GetDlgItem(correction, 414)) && IsWindowEnabled(parent) &&
!findTestWindow(L"KSwitcher.AutoOptions", nullptr), "correction options open inline");
const bool replace = IsDlgButtonChecked(correction, 414) == BST_CHECKED;
SendMessageW(GetDlgItem(correction, 414), BM_CLICK, 0, 0);
require(saveEnabled(), "inline correction edits enable Save");
selectSettingsPage(parent, 0);
selectSettingsPage(parent, 16);
require((IsDlgButtonChecked(correction, 414) == BST_CHECKED) != replace,
"correction edits survive switching pages");
SendMessageW(GetDlgItem(correction, 414), BM_CLICK, 0, 0);
require(!saveEnabled(), "reverting an inline correction edit disables Save");
HWND navigation = settingsNavigation(parent);
constexpr int sections = 18;
require(navigation && TreeView_GetCount(navigation) == sections &&
TreeView_GetParent(navigation, settingsSection(navigation, 10)) == settingsSection(navigation, 7) &&
TreeView_GetParent(navigation, settingsSection(navigation, 11)) == settingsSection(navigation, 0),
"correction and computer settings are nested under their sections");
for (int section = 12; section <= 16; ++section)
require(TreeView_GetParent(navigation, settingsSection(navigation, section)) == settingsSection(navigation, 11),
"each correction subsection belongs to the correction branch");
require(!GetDlgItem(parent, 262), "no separate Manage computers button");
wchar_t mcpConfig[4096]{};
GetDlgItemTextW(settingsViewport(parent), 281, mcpConfig, std::size(mcpConfig));
const std::wstring config(mcpConfig);
require(config.starts_with(L"[mcp_servers.kswitcher]\r\ncommand = \"") &&
config.find(L"KSwitcher.Config.exe\"\r\nargs = [\"--mcp\"]") != std::wstring::npos,
"MCP section shows a Codex stdio configuration");
RECT originalFrame{};
GetWindowRect(parent, &originalFrame);
MONITORINFO captureMonitor{sizeof(captureMonitor)};
if (GetMonitorInfoW(MonitorFromWindow(parent, MONITOR_DEFAULTTONEAREST), &captureMonitor))
SetWindowPos(parent, nullptr, originalFrame.left, captureMonitor.rcWork.top,
originalFrame.right - originalFrame.left,
std::min(captureMonitor.rcWork.bottom - captureMonitor.rcWork.top,
LONG(MulDiv(820, GetDpiForWindow(parent), 96))), SWP_NOZORDER | SWP_NOACTIVATE);
for (int page = 0; page < sections; ++page)
{
selectSettingsPage(parent, page);
std::vector<RECT> boxes;
for (HWND child = GetWindow(settingsViewport(parent), GW_CHILD); child; child = GetWindow(child, GW_HWNDNEXT))
{
if (!(GetWindowLongPtrW(child, GWL_STYLE) & WS_VISIBLE)) continue;
RECT rect{}; GetWindowRect(child, &rect);
for (const auto &other : boxes)
{
RECT overlap{};
require(!IntersectRect(&overlap, &rect, &other), "visible settings controls never overlap");
}
boxes.push_back(rect);
}
RedrawWindow(parent, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
RECT rect{}; GetClientRect(parent, &rect);
HDC dc = GetDC(parent);
auto clip = ks::screenshotClip(dc, rect.right, rect.bottom, {});
ReleaseDC(parent, dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / (L"settings-section-" + std::to_wstring(page) + L".png"),
ks::encodePng(ks::decodeImage(clip)));
}
SetWindowPos(parent, nullptr, originalFrame.left, originalFrame.top,
originalFrame.right - originalFrame.left, originalFrame.bottom - originalFrame.top,
SWP_NOZORDER | SWP_NOACTIVATE);
selectSettingsPage(parent, 11);
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 12) &&
IsWindowVisible(GetDlgItem(correction, 401)), "selecting an empty group opens its first page");
selectSettingsPage(parent, 0);
SetFocus(navigation);
SendMessageW(navigation, WM_KEYDOWN, VK_DOWN, 0);
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 12) &&
IsWindowVisible(GetDlgItem(correction, 401)), "arrow keys enter the first correction subsection");
SendMessageW(navigation, WM_KEYDOWN, VK_UP, 0);
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 0),
"Up from the first child skips the empty parent");
SendMessageW(navigation, WM_KEYDOWN, VK_DOWN, 0);
SendMessageW(navigation, WM_KEYDOWN, VK_DOWN, 0);
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 13),
"Down reaches the subsequent child");
SendMessageW(navigation, WM_KEYDOWN, VK_LEFT, 0);
const auto correctionBranch = settingsSection(navigation, 11);
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 0) &&
!(TreeView_GetItemState(navigation, correctionBranch, TVIS_EXPANDED) & TVIS_EXPANDED),
"Left exits and collapses the group");
selectSettingsPage(parent, 16);
SendMessageW(navigation, WM_KEYDOWN, VK_DOWN, 0);
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 1) &&
IsWindowVisible(GetDlgItem(settingsViewport(parent), 220)) &&
!IsWindowVisible(GetDlgItem(settingsViewport(parent), 201)), "arrow keys select the visible page");
MSG tab{navigation, WM_KEYDOWN, VK_TAB};
require(IsDialogMessageW(parent, &tab) && GetFocus() == GetDlgItem(settingsViewport(parent), 220),
"Tab enters the active settings page");
RECT frame{};
GetWindowRect(parent, &frame);
const UINT dpi = GetDpiForWindow(parent);
const auto rootNode = TreeView_GetRoot(navigation);
const auto dictionariesNode = settingsSection(navigation, 12);
const auto checkLabelIndent = [&](UINT targetDpi)
{
RECT rootLabel{}, childLabel{}, dictionariesLabel{};
require(TreeView_GetItemRect(navigation, rootNode, &rootLabel, TRUE) &&
TreeView_GetItemRect(navigation, correctionBranch, &childLabel, TRUE) &&
TreeView_GetItemRect(navigation, dictionariesNode, &dictionariesLabel, TRUE),
"measure tree labels on all three levels");
const int indent = MulDiv(16, targetDpi, 96);
require(childLabel.left - rootLabel.left == indent &&
dictionariesLabel.left - childLabel.left == indent,
"tree labels use a compact indent at the current DPI");
};
checkLabelIndent(dpi);
for (const UINT targetDpi : {96u, 144u, 192u, 240u, dpi})
{
SendMessageW(parent, WM_DPICHANGED, MAKEWPARAM(targetDpi, targetDpi), reinterpret_cast<LPARAM>(&frame));
checkLabelIndent(targetDpi);
}
const auto splitter = GetDlgItem(parent, 270);
const auto viewport = settingsViewport(parent);
RECT paneBefore{}, paneAfter{}, footerBefore{}, footerAfter{};
GetWindowRect(viewport, &paneBefore);
GetWindowRect(GetDlgItem(parent, IDCANCEL), &footerBefore);
const int grip = MulDiv(4, dpi, 96), movement = MulDiv(50, dpi, 96);
SendMessageW(splitter, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(grip, 10));
require(GetCapture() == splitter, "splitter captures a drag");
SendMessageW(splitter, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(grip + movement, 10));
SendMessageW(splitter, WM_LBUTTONUP, 0, MAKELPARAM(grip, 10));
GetWindowRect(viewport, &paneAfter);
GetWindowRect(GetDlgItem(parent, IDCANCEL), &footerAfter);
require(GetCapture() != splitter && std::abs(paneAfter.left - paneBefore.left - movement) <= 1 &&
paneAfter.right == paneBefore.right && EqualRect(&footerBefore, &footerAfter),
"dragging resizes the two panes and keeps the footer fixed");
const int draggedPosition = paneAfter.left;
SendMessageW(splitter, WM_KEYDOWN, VK_LEFT, 0);
GetWindowRect(viewport, &paneAfter);
require(std::abs(paneAfter.left - draggedPosition + MulDiv(12, dpi, 96)) <= 1,
"arrow keys resize the panes");
const auto heading = GetDlgItem(parent, 266);
const auto exportButton = GetDlgItem(parent, 251);
const int inset = MulDiv(8, dpi, 96);
const COLORREF stale = RGB(7, 97, 83);
RedrawWindow(parent, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_UPDATENOW | RDW_ALLCHILDREN);
// Simulate stale splitter and button pixels in the areas affected by a drag.
for (HWND child : {heading, exportButton})
{
const auto dc = GetDC(child);
const bool marked = SetPixelV(dc, inset, inset, stale) && GetPixel(dc, inset, inset) == stale;
ReleaseDC(child, dc);
require(marked, "fixture can plant a stale pixel");
}
SendMessageW(splitter, WM_LBUTTONDBLCLK, MK_LBUTTON, MAKELPARAM(grip, 10));
GetWindowRect(viewport, &paneAfter);
require(EqualRect(&paneBefore, &paneAfter), "double-click restores the default split");
RedrawWindow(parent, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN);
for (HWND child : {heading, exportButton})
{
const auto dc = GetDC(child);
const auto pixel = GetPixel(dc, inset, inset);
ReleaseDC(child, dc);
require(pixel != CLR_INVALID && pixel != stale, "moving the splitter repaints the heading and footer");
}
RECT repaintClient{};
GetClientRect(parent, &repaintClient);
const auto checkAccent = [&](DWORD argb)
{
SendMessageW(parent, WM_DWMCOLORIZATIONCOLORCHANGED, argb, TRUE);
RedrawWindow(parent, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN);
const auto dc = GetDC(parent);
const auto rail = GetPixel(dc, inset, inset);
const auto footer = GetPixel(dc, inset, repaintClient.bottom - inset);
ReleaseDC(parent, dc);
require(rail != CLR_INVALID && rail == footer && rail == TreeView_GetBkColor(navigation),
"the rendered sidebar, navigation tree and footer use the same background");
return rail;
};
HIGHCONTRASTW contrast{sizeof(contrast)};
SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0);
const bool highContrast = (contrast.dwFlags & HCF_HIGHCONTRASTON) != 0;
const auto warmAccent = checkAccent(0xFFFF4000);
const auto coolAccent = checkAccent(0xFF0040FF);
require(highContrast ? warmAccent == GetSysColor(COLOR_WINDOW) && warmAccent == coolAccent
: GetRValue(warmAccent) > GetRValue(coolAccent) &&
GetBValue(warmAccent) < GetBValue(coolAccent),
"open Settings follows Windows accent changes and respects contrast themes");
SendMessageW(parent, WM_SYSCOLORCHANGE, 0, 0);
RedrawWindow(parent, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN);
const auto repaintDc = GetDC(parent);
auto repaint = ks::screenshotClip(repaintDc, repaintClient.right, repaintClient.bottom, {});
ReleaseDC(parent, repaintDc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"settings-splitter-repaint.png",
ks::encodePng(ks::decodeImage(repaint)));
TreeView_SetItemHeight(navigation, 30);
SendMessageW(parent, WM_DPICHANGED, MAKEWPARAM(dpi, dpi), reinterpret_cast<LPARAM>(&frame));
require(TreeView_GetItemHeight(navigation) == (MulDiv(30, dpi, 96) & ~1),
"the navigation row height follows the window DPI");
selectSettingsPage(parent, 5);
SetWindowPos(parent, nullptr, 0, 0, frame.right - frame.left, MulDiv(430, dpi, 96),
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
const auto pane = settingsViewport(parent);
const auto cancel = GetDlgItem(parent, IDCANCEL);
RECT before{}, after{};
GetWindowRect(cancel, &before);
SendMessageW(pane, WM_VSCROLL, SB_BOTTOM, 0);
SCROLLINFO scroll{sizeof(scroll), SIF_POS};
GetScrollInfo(pane, SB_VERT, &scroll);
GetWindowRect(cancel, &after);
require(scroll.nPos > 0 && EqualRect(&before, &after), "the footer stays fixed while the page scrolls");
selectSettingsPage(parent, 0);
selectSettingsPage(parent, 5);
SCROLLINFO restored{sizeof(restored), SIF_POS};
GetScrollInfo(pane, SB_VERT, &restored);
require(restored.nPos == scroll.nPos, "returning to a page preserves its scroll position");
SetWindowPos(parent, nullptr, 0, 0, frame.right - frame.left, frame.bottom - frame.top,
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
const auto search = GetDlgItem(parent, 269);
SetWindowTextW(search, L"mou");
const auto profilesResult = TreeView_GetChild(navigation, TreeView_GetRoot(navigation));
const auto eventsResult = TreeView_GetNextSibling(navigation, profilesResult);
require(profilesResult && eventsResult, "Mouse search exposes two results on the same page");
SetFocus(navigation);
TreeView_SelectItem(navigation, profilesResult);
require(TreeView_GetSelection(navigation) == profilesResult, "the search tree selects Profiles");
const auto profilesLabel = FindWindowExW(pane, nullptr, L"Static", L"Profiles");
const auto eventsLabel = FindWindowExW(pane, nullptr, L"Static", L"Mouse events");
require(profilesLabel && eventsLabel, "both search targets are on the Mouse page");
auto outline = [&](HWND label)
{
RECT bounds{};
GetWindowRect(label, &bounds);
MapWindowPoints(nullptr, pane, reinterpret_cast<POINT *>(&bounds), 2);
const auto dc = GetDC(pane);
const auto color = GetPixel(dc, bounds.left - MulDiv(3, dpi, 96), (bounds.top + bounds.bottom) / 2);
ReleaseDC(pane, dc);
return color;
};
RedrawWindow(pane, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN);
if (!highContrast)
require(outline(profilesLabel) == RGB(7, 97, 83) && outline(eventsLabel) == RGB(157, 111, 21),
"the selected result has its own outline within the current page");
SendMessageW(navigation, WM_KEYDOWN, VK_DOWN, 0);
require(TreeView_GetSelection(navigation) == eventsResult, "Down selects the next result");
RedrawWindow(pane, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN);
if (!highContrast)
require(outline(profilesLabel) == RGB(157, 111, 21) && outline(eventsLabel) == RGB(7, 97, 83),
"the active outline moves when selecting another result on the same page");
SetWindowTextW(search, L"correction options personal dictionary Ukrainian");
SetFocus(search);
SendMessageW(search, WM_KEYDOWN, VK_RETURN, 0);
SendMessageW(navigation, WM_KEYDOWN, VK_RETURN, 0);
require(GetFocus() == GetDlgItem(correction, 412), "search follows the correction hierarchy to a specific dictionary");
SetWindowTextW(search, L"clipboard max count");
SetFocus(search);
SendMessageW(search, WM_KEYDOWN, VK_RETURN, 0);
SendMessageW(navigation, WM_KEYDOWN, VK_RETURN, 0);
require(GetFocus() == GetDlgItem(settingsViewport(parent), 240),
"search finds a field by its aliases and Enter focuses the field");
SetWindowTextW(search, L"gEnErAtE CoDe");
auto match = TreeView_GetChild(navigation, TreeView_GetRoot(navigation));
require(TreeView_GetCount(navigation) >= 2 && match, "search finds a nested action case-insensitively");
TreeView_SelectItem(navigation, match);
const auto embedded = GetDlgItem(settingsViewport(parent), 262);
require(IsWindowVisible(embedded) && IsWindowEnabled(parent) &&
!findTestWindow(L"KSwitcher.LAN", nullptr), "search opens Manage computers in the configurator");
RedrawWindow(parent, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
RECT searchRect{};
GetClientRect(parent, &searchRect);
auto searchDc = GetDC(parent);
const auto searchImage = ks::screenshotClip(searchDc, searchRect.right, searchRect.bottom, {});
ReleaseDC(parent, searchDc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"settings-search.png",
ks::encodePng(ks::decodeImage(searchImage)));
SetWindowTextW(search, L"no-such-setting-123");
require(TreeView_GetCount(navigation) == 1, "no matches leaves a single result message");
SetWindowTextW(search, L"");
require(TreeView_GetCount(navigation) == sections &&
TreeView_GetSelection(navigation) == settingsSection(navigation, 10),
"clearing search restores the tree and its active page");
SetWindowTextW(search, L"OpenBao server");
const auto serverResult = TreeView_GetChild(navigation, TreeView_GetRoot(navigation));
require(serverResult && TreeView_SelectItem(navigation, serverResult), "search finds the OpenBao server field");
const auto sync = GetDlgItem(pane, 271);
require(IsWindowVisible(GetDlgItem(sync, 602)) && IsWindowEnabled(parent),
"search reveals the embedded OpenBao page");
SetWindowTextW(search, L"");
selectSettingsPage(parent, 1);
require(!saveEnabled(),"changing sections leaves Settings clean");
SendMessageW(parent, WM_COMMAND, 259, 0);
HWND dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr);
require(dialog && !IsWindowEnabled(parent), "chat dialog opens with disabled parent");
auto findFixtureChat = [&](HWND chatDialog) {
SetDlgItemTextW(chatDialog, 714, L"! fIXTURE CHAT");
HWND list = GetDlgItem(chatDialog, 710);
require(ListView_GetItemCount(list) == 1, "case-insensitive contact search finds saved chat");
wchar_t appName[32]{};
ListView_GetItemText(list, 0, 1, appName, std::size(appName));
require(std::wstring(appName) == L"Telegram", "chat list shows the source app separately");
};
SetDlgItemTextW(dialog, 714, L"No matching fixture 8031");
require(ListView_GetItemCount(GetDlgItem(dialog, 710)) == 0 &&
!IsWindowEnabled(GetDlgItem(dialog, IDOK)), "empty search results disable profile actions");
findFixtureChat(dialog);
require(SendDlgItemMessageW(dialog, 711, LB_GETSELCOUNT, 0, 0) == 1, "saved single language selected");
RedrawWindow(dialog, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
RECT rect{}; GetClientRect(dialog, &rect);
HDC dc = GetDC(dialog);
auto clip = ks::screenshotClip(dc, rect.right, rect.bottom, {});
ReleaseDC(dialog, dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"chat-languages.png",
ks::encodePng(ks::decodeImage(clip)));
SendDlgItemMessageW(dialog, 711, LB_SETSEL, TRUE, -1);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(711, LBN_SELCHANGE), 0);
SendMessageW(dialog, WM_COMMAND, IDCANCEL, 0);
require(!IsWindow(dialog) && IsWindowEnabled(parent), "cancel closes dialog");
require(!saveEnabled(),"cancelled chat edits do not enable Save");
SendMessageW(parent, WM_COMMAND, 259, 0);
dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr);
findFixtureChat(dialog);
require(SendDlgItemMessageW(dialog, 711, LB_GETSELCOUNT, 0, 0) == 1, "cancel discards language edits");
SendDlgItemMessageW(dialog, 711, LB_SETSEL, TRUE, -1);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(711, LBN_SELCHANGE), 0);
SendMessageW(dialog, WM_COMMAND, IDOK, 0);
require(!IsWindow(dialog) && IsWindowEnabled(parent), "profile applies to settings draft");
require(saveEnabled() == (app.layouts.size()>1),"accepted chat edits refresh Save immediately");
selectSettingsPage(parent, 16);
SetDlgItemTextW(correction, 412, L"Релізик\r\nрелізик, словечко");
SetDlgItemTextW(correction, 416, L" HeLo = Hello\r\n");
SendMessageW(parent, WM_COMMAND, IDOK, 0);
require(!app.settingsWindow && app.settings.chatCycles.at(key).size() == app.layouts.size(), "settings saves selected languages");
const auto saved = ks::loadSettings(root / L"settings.json", app.layouts);
require(saved.chatCycles == app.settings.chatCycles, "profile saved to disk");
require(saved.autoWords.at(L"uk") == std::vector<std::wstring>{L"релізик", L"словечко"} &&
saved.autoReplacements.at(L"helo") == L"hello", "Settings Save normalizes and persists correction edits");
ks::showSettings(app);
parent = app.settingsWindow;
require(!saveEnabled(),"reopened saved Settings is clean");
SendMessageW(parent, WM_COMMAND, 259, 0);
dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr);
findFixtureChat(dialog);
SendMessageW(dialog, WM_COMMAND, 713, 0);
require(IsWindow(dialog), "chat reset keeps dialog open");
SendMessageW(dialog, WM_COMMAND, IDOK, 0);
require(saveEnabled() && status().find(L"Unsaved settings")==0,"removing child profile immediately marks parent dirty");
RedrawWindow(parent,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
GetClientRect(parent,&rect); dc=GetDC(parent);
clip=ks::screenshotClip(dc,rect.right,rect.bottom,{}); ReleaseDC(parent,dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"settings-unsaved.png",
ks::encodePng(ks::decodeImage(clip)));
SendMessageW(parent, WM_COMMAND, IDOK, 0);
require(!app.settings.chatCycles.contains(key), "remove profile restores default");
// Existing shared sets become independent application drafts on edit.
app.settings.appLanguageSets[L"Legacy shared"] = {{app.layouts[0].id}, {L"Codex.exe", L"notepad"}};
ks::showSettings(app);
parent = app.settingsWindow;
SendMessageW(parent, WM_COMMAND, 263, 0);
dialog = findTestWindow(L"KSwitcher.AppLanguages", nullptr);
require(dialog && !IsWindowEnabled(parent), "application language editor opens");
auto selectApp = [&](const wchar_t *name) {
int index = (int)SendDlgItemMessageW(dialog, 720, LB_FINDSTRINGEXACT, -1, (LPARAM)name);
require(index >= 0, "application listed");
SendDlgItemMessageW(dialog, 720, LB_SETCURSEL, index, 0);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(720, LBN_SELCHANGE), 0);
};
selectApp(L"codex");
require(SendDlgItemMessageW(dialog, 722, LB_GETSELCOUNT, 0, 0) == 1, "legacy languages displayed");
SendDlgItemMessageW(dialog, 722, LB_SETSEL, TRUE, -1);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(722, LBN_SELCHANGE), 0);
HWND picker = GetDlgItem(dialog, 728);
pickTestApplication(picker, true);
auto pickedApp = pickTestApplication(picker);
auto pickedRow = SendDlgItemMessageW(dialog, 720, LB_FINDSTRINGEXACT, -1, (LPARAM)pickedApp.c_str());
require(GetCapture() != picker && pickedRow >= 0 &&
SendDlgItemMessageW(dialog, 720, LB_GETCURSEL, 0, 0) == pickedRow, "dropping on a window selects its executable");
selectApp(L"notepad");
require(SendDlgItemMessageW(dialog, 722, LB_GETSELCOUNT, 0, 0) == 1, "editing one app leaves formerly shared app unchanged");
selectApp(L"codex");
require(SendDlgItemMessageW(dialog, 722, LB_GETSELCOUNT, 0, 0) == (LRESULT)app.layouts.size(), "application navigation preserves drafts");
RedrawWindow(dialog, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
GetClientRect(dialog, &rect);
dc = GetDC(dialog);
clip = ks::screenshotClip(dc, rect.right, rect.bottom, {});
ReleaseDC(dialog, dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"application-languages.png",
ks::encodePng(ks::decodeImage(clip)));
SendMessageW(dialog, WM_COMMAND, IDCANCEL, 0);
SendMessageW(parent, WM_COMMAND, IDOK, 0);
require(app.settings.appLanguageSets.size() == 1 && app.settings.appLanguageSets.contains(L"Legacy shared"), "cancel preserves legacy settings unchanged");
ks::showSettings(app);
parent = app.settingsWindow;
SendMessageW(parent, WM_COMMAND, 263, 0);
dialog = findTestWindow(L"KSwitcher.AppLanguages", nullptr);
selectApp(L"codex");
SendDlgItemMessageW(dialog, 722, LB_SETSEL, TRUE, -1);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(722, LBN_SELCHANGE), 0);
selectApp(L"notepad");
SetDlgItemTextW(dialog, 726, L"Fixture-App.EXE");
SendMessageW(dialog, WM_COMMAND, 727, 0);
require(!IsWindowEnabled(GetDlgItem(dialog, 725)), "new application inherits defaults");
selectApp(L"codex");
SendMessageW(dialog, WM_COMMAND, IDOK, 0);
SendMessageW(parent, WM_COMMAND, IDOK, 0);
require(app.settings.appLanguageSets.size() == 2, "viewing an app does not create a profile");
require(app.settings.appLanguageSets.at(L"codex").languages.size() == app.layouts.size(), "edited application languages saved");
require(app.settings.appLanguageSets.at(L"notepad").languages == std::vector<std::wstring>{app.layouts[0].id}, "other application retains original languages");
require(ks::loadSettings(root / L"settings.json", app.layouts).appLanguageSets == app.settings.appLanguageSets, "independent application profiles saved to disk");
ks::showSettings(app);
parent = app.settingsWindow;
SendMessageW(parent, WM_COMMAND, 263, 0);
dialog = findTestWindow(L"KSwitcher.AppLanguages", nullptr);
selectApp(L"codex");
SendMessageW(dialog, WM_COMMAND, 725, 0);
selectApp(L"notepad");
selectApp(L"codex");
require(!IsWindowEnabled(GetDlgItem(dialog, 725)), "default reset survives navigation");
SendMessageW(dialog, WM_COMMAND, IDOK, 0);
SendMessageW(parent, WM_COMMAND, IDOK, 0);
require(!ks::applicationLanguageSet(app.settings, L"codex"), "use defaults removes only selected application profile");
require(ks::applicationLanguageSet(app.settings, L"notepad") != nullptr, "default reset leaves other application profile intact");
snippetEditorChecks(app, root);
ks::showSettings(app);parent=app.settingsWindow;
HWND lan=showComputerSettings(parent);
require(lan && IsWindowVisible(lan) && IsWindowEnabled(parent),
"LAN pairing opens in the Settings content area");
require(!IsWindowEnabled(GetDlgItem(lan,705)),"pairing disabled without discovered peer");
require(!IsWindowEnabled(GetDlgItem(lan,706)),"no cancellation without pending pairing");
require(!IsWindowEnabled(GetDlgItem(lan,707)),"cannot forget nonexistent pair");
require(!IsWindowEnabled(GetDlgItem(lan,715)),"input sharing requires a paired computer");
require(!IsWindowEnabled(GetDlgItem(lan,716)),"stop input disabled when sharing is off");
require(GetDlgItem(lan,721)!=nullptr,"monitor arrangement grid is present");
require((GetWindowLongPtrW(lan,GWL_STYLE)&WS_CHILD)!=0,"LAN content is a child panel");
require(GetDlgItem(lan,711)==nullptr,"obsolete side radios are removed");
require(SendDlgItemMessageW(lan,702,LB_GETCOUNT,0,0)==0,"disabled discovery lists no generic network devices");
require(!std::filesystem::exists(root/L"lan-pairing.bin"),"opening LAN settings does not enable or save discovery");
SendMessageW(lan,WM_COMMAND,722,0);
auto help=findTestWindow(L"KSwitcher.LAN.Help",nullptr);
require(help&&!IsWindowEnabled(parent),"connection help opens without changing network settings");
wchar_t command[4096]{};GetDlgItemTextW(help,723,command,4096);
require(std::wstring(command).find(ks::executable())!=std::wstring::npos&&
std::wstring(command).find(L"-LocalPort 45884")!=std::wstring::npos&&
std::wstring(command).find(L"-LocalPort 45883")!=std::wstring::npos&&
std::wstring(command).find(L"-RemoteAddress LocalSubnet")!=std::wstring::npos,
"help supplies local-subnet firewall commands for the actual resident executable and both transports");
RedrawWindow(help,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
RECT helpRect{};GetClientRect(help,&helpRect);HDC helpDc=GetDC(help);
auto helpImage=ks::screenshotClip(helpDc,helpRect.right,helpRect.bottom,{});ReleaseDC(help,helpDc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-connection-help.png",ks::encodePng(ks::decodeImage(helpImage)));
SendMessageW(help,WM_COMMAND,IDCANCEL,0);
require(IsWindowEnabled(parent),"closing connection help returns to LAN setup");
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
RECT lanRect{};GetClientRect(lan,&lanRect);HDC lanDc=GetDC(lan);
auto lanImage=ks::screenshotClip(lanDc,lanRect.right,lanRect.bottom,{});ReleaseDC(lan,lanDc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-pairing.png",ks::encodePng(ks::decodeImage(lanImage)));
require(IsWindowEnabled(parent) && !saveEnabled() && status() == L"No unsaved settings.",
"opening discovery leaves Settings clean");
SendMessageW(lan, WM_COMMAND, 701, 0);
require(saveEnabled() && !std::filesystem::exists(root / L"lan-pairing.bin"),
"discovery is staged until Save");
SendMessageW(lan, WM_TIMER, 1, 0);
SendMessageW(lan, WM_COMMAND, 701, 0);
require(!saveEnabled(), "reverting discovery clears its draft");
SendMessageW(parent,WM_COMMAND,IDCANCEL,0);
}
{
ks::lan::Json fixture={{"version",1},{"id",std::string(32,'a')},{"enabled",false},{"inputPeer",std::string(32,'b')},{"inputEdge",1},
{"trusted",{{std::string(32,'b'),{{"name","Test paired KSwitcher"},{"key",std::string(64,'f')}}}}}};
auto text=fixture.dump();ks::atomicWrite(root/L"lan-pairing.bin",ks::protect(ks::Bytes(text.begin(),text.end())));
ks::App pairedApp(GetModuleHandleW(nullptr), true, root);
const auto settingsPath = root / L"settings.json";
const auto previousSettings = ks::readFile(settingsPath, 8 * 1024 * 1024);
auto next = pairedApp.settings;
next.writeLog = !next.writeLog;
const auto failedDraft = ks::lan::Json{
{"lan", {{"positions", {{"missing-peer", ks::lan::Json::array({0, -1})}}}}},
{"sync", {{"config", ks::encodeSyncConfig({})}, {"base", ks::encodeSyncConfig({})},
{"password", ks::Bytes{}}, {"forget", false}}}}.dump();
bool rejected = false;
try { pairedApp.applySettings(next, ks::Bytes(failedDraft.begin(), failedDraft.end())); }
catch (const std::runtime_error &) { rejected = true; }
require(rejected && pairedApp.settings.writeLog != next.writeLog &&
ks::readFile(settingsPath, 8 * 1024 * 1024) == previousSettings && !ks::syncVisible(root),
"a rejected LAN change rolls back the general and OpenBao settings");
ks::showSettings(pairedApp);
HWND lan=showComputerSettings(pairedApp.settingsWindow);
require(SendDlgItemMessageW(lan,702,LB_GETCURSEL,0,0)==0,"single saved pair selected automatically when opening LAN settings");
wchar_t pairState[512]{};GetDlgItemTextW(lan,710,pairState,std::size(pairState));
require(std::wstring(pairState).find(L"Pair saved — input disabled here")!=std::wstring::npos,"saved pairing does not imply an active input connection");
require(!IsWindowEnabled(GetDlgItem(lan,705))&&!IsWindowEnabled(GetDlgItem(lan,703))&&!IsWindowEnabled(GetDlgItem(lan,704)),"saved pair disables pairing and code controls");
SendDlgItemMessageW(lan,702,LB_SETCURSEL,-1,0);
SendMessageW(lan,WM_TIMER,1,0);
require(SendDlgItemMessageW(lan,702,LB_GETCURSEL,0,0)==0,"refresh restores single paired selection without a peer list change");
auto grid=GetDlgItem(lan,721);
SendMessageW(grid,WM_KEYDOWN,VK_UP,0);SendMessageW(grid,WM_KEYDOWN,VK_LEFT,0);
auto window = pairedApp.settingsWindow;
require(IsWindowEnabled(GetDlgItem(window, IDOK)), "moving a monitor enables the global Save button");
require(ks::lan::Json::parse(ks::unprotect(ks::readFile(root / L"lan-pairing.bin", 256 * 1024))) == fixture,
"moving a monitor leaves the saved configuration intact");
SendMessageW(lan,WM_TIMER,1,0);
require(!IsWindowEnabled(GetDlgItem(lan,715)),"input cannot start while discovery is disabled");
// Let the native radio-button theme animation finish before visual capture.
auto repaintUntil=GetTickCount64()+200;
while(GetTickCount64()<repaintUntil)
{
MSG message{};
while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE)){TranslateMessage(&message);DispatchMessageW(&message);}
Sleep(10);
}
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
RECT r{};GetClientRect(lan,&r);HDC dc=GetDC(lan);auto screenshot=ks::screenshotClip(dc,r.right,r.bottom,{});ReleaseDC(lan,dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-screen-layout.png",ks::encodePng(ks::decodeImage(screenshot)));
CheckDlgButton(lan, 729, BST_CHECKED);
SendMessageW(lan, WM_COMMAND, 729, 0);
SendMessageW(lan, WM_TIMER, 1, 0);
require(IsDlgButtonChecked(lan, 729) == BST_CHECKED, "status polling preserves the pending log permission");
selectSettingsPage(window, 5);
const auto actions = GetDlgItem(settingsViewport(window), 733);
LVFINDINFOW xButton{LVFI_PARAM};
xButton.lParam = 3;
const int row = ListView_FindItem(actions, -1, &xButton);
require(row >= 0, "mouse action list contains XButton1");
ListView_SetItemState(actions, row, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
SendMessageW(window, WM_COMMAND, 735, 0);
const auto mouse = findTestWindow(L"KSwitcher.MouseAction", nullptr);
require(mouse != nullptr, "mouse action editor opens");
SendDlgItemMessageW(mouse, 734, CB_SETCURSEL, static_cast<int>(ks::MouseActionType::Mute), 0);
SendMessageW(mouse, WM_COMMAND, MAKEWPARAM(734, CBN_SELCHANGE), 0);
RedrawWindow(mouse, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
RECT mouseClient{};
GetClientRect(mouse, &mouseClient);
auto mouseDc = GetDC(mouse);
const auto mouseCapture = ks::screenshotClip(mouseDc, mouseClient.right, mouseClient.bottom, {});
ReleaseDC(mouse, mouseDc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"settings-mouse-action.png",
ks::encodePng(ks::decodeImage(mouseCapture)));
SendMessageW(mouse, WM_COMMAND, IDOK, 0);
require(!IsWindow(mouse) && !ks::mouseBinding(pairedApp.settings, ks::GlobalMouseProfile, int(xButton.lParam)),
"Use action accepts the draft without changing the active binding");
selectSettingsPage(window, 17);
const auto sync = GetDlgItem(settingsViewport(window), 271);
require(sync && IsWindowVisible(sync), "OpenBao opens inside Settings");
CheckDlgButton(sync, 601, BST_CHECKED);
SendMessageW(sync, WM_COMMAND, 601, 0);
SetDlgItemTextW(sync, 602, L"https://vault.invalid");
SetDlgItemTextW(sync, 603, L"fixture");
require(!ks::syncVisible(root) && !IsWindowEnabled(GetDlgItem(sync, 614)),
"a pending connection neither saves nor starts sync");
const auto tree = settingsNavigation(window);
const auto selected = TreeView_GetSelection(tree);
SendMessageW(window, WM_COMMAND, SettingsApply, 0);
require(IsWindow(window) && TreeView_GetSelection(tree) == selected && IsWindowVisible(sync),
"Apply keeps the same Settings page open");
require(!IsWindowEnabled(GetDlgItem(window, SettingsApply)) &&
!IsWindowEnabled(GetDlgItem(window, IDOK)) && IsWindowEnabled(GetDlgItem(sync, 614)),
"Apply refreshes the saved baseline and enables actions for the saved OpenBao connection");
wchar_t closeCaption[24]{};
GetDlgItemTextW(window, IDCANCEL, closeCaption, std::size(closeCaption));
require(std::wstring_view(closeCaption) == L"&Close", "Apply restores Close");
auto saved = ks::lan::Json::parse(ks::unprotect(ks::readFile(root / L"lan-pairing.bin", 256 * 1024)));
require(saved["positions"][std::string(32, 'b')] == ks::lan::Json::array({0, -1}) &&
saved["inputEdge"] == 2 && saved["shareLogs"] == true,
"one Apply commits the monitor arrangement and log permission");
const auto action = ks::mouseBinding(pairedApp.settings, ks::GlobalMouseProfile, int(xButton.lParam));
require(action && action->type == ks::MouseActionType::Mute,
"the same Apply commits the mouse action");
require(ks::loadSyncConfig(root).enabled && ks::loadSyncConfig(root).username == L"fixture",
"the same Apply commits the OpenBao connection");
selectSettingsPage(window, 10);
CheckDlgButton(lan, 729, BST_UNCHECKED);
SendMessageW(lan, WM_COMMAND, 729, 0);
GetDlgItemTextW(window, IDCANCEL, closeCaption, std::size(closeCaption));
require(std::wstring_view(closeCaption) == L"&Cancel", "editing again after Apply restores Cancel");
SendMessageW(window, WM_COMMAND, IDOK, 0);
require(!IsWindow(window) &&
ks::lan::Json::parse(ks::unprotect(ks::readFile(root / L"lan-pairing.bin", 256 * 1024)))
.at("shareLogs") == false,
"after Apply, Save can commit a new edit and close the window");
ks::saveSyncConfig(root, {});
}
{
using J=ks::lan::Json;const std::string b(32,'b'),c(32,'c');
J fixture={{"version",1},{"id",std::string(32,'a')},{"enabled",false},{"inputPeer",b},{"inputEdge",0},
{"trusted",{{b,{{"name","Left desktop"},{"key",std::string(64,'f')}}},{c,{{"name","Right laptop"},{"key",std::string(64,'e')}}}}},
{"positions",{{b,J::array({-1,0})},{c,J::array({1,0})}}}};
auto text=fixture.dump();ks::atomicWrite(root/L"lan-pairing.bin",ks::protect(ks::Bytes(text.begin(),text.end())));
ks::App layoutApp(GetModuleHandleW(nullptr),true,root);ks::showSettings(layoutApp);
auto lan=showComputerSettings(layoutApp.settingsWindow);auto grid=GetDlgItem(lan,721);
RECT r{};GetClientRect(grid,&r);
auto point=[&](int column,int row){return MAKELPARAM((2*column+1)*r.right/10,(2*row+1)*r.bottom/6);};
SendMessageW(grid,WM_LBUTTONDOWN,MK_LBUTTON,point(1,1));SendMessageW(grid,WM_MOUSEMOVE,MK_LBUTTON,point(1,0));SendMessageW(grid,WM_LBUTTONUP,0,point(1,0));
auto saved=J::parse(ks::unprotect(ks::readFile(root/L"lan-pairing.bin",256*1024)));
require(saved == fixture, "dragging a monitor leaves the saved layout intact");
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
GetClientRect(lan,&r);auto dc=GetDC(lan);auto screenshot=ks::screenshotClip(dc,r.right,r.bottom,{});ReleaseDC(lan,dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-three-computers.png",ks::encodePng(ks::decodeImage(screenshot)));
const auto wnd = layoutApp.settingsWindow;
const auto discard = SetTimer(wnd, 871, 30, [](HWND window, UINT, UINT_PTR id, DWORD) {
const auto dialog = findTestWindow(L"#32770", L"KSwitcher — Unsaved settings");
if (!dialog) return;
KillTimer(window, id);
PostMessageW(dialog, WM_COMMAND, IDYES, 0);
});
require(discard != 0, "can answer the discard confirmation");
SendMessageW(wnd, WM_COMMAND, IDCANCEL, 0);
require(!IsWindow(wnd) &&
J::parse(ks::unprotect(ks::readFile(root / L"lan-pairing.bin", 256 * 1024))) == fixture,
"Cancel discards a staged monitor drag without saving it");
}
std::filesystem::remove_all(root);
std::cout << "Passed " << passed << " chat profile checks\n";
CoUninitialize();
return 0;
}
catch (const std::exception &e) { std::cerr << "FAIL: " << e.what() << '\n'; CoUninitialize(); return 1; }
}