Compare commits

..
18 changed files with 728 additions and 345 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.8.3 LANGUAGES C CXX RC)
project(KSwitcher VERSION 0.8.4 LANGUAGES C CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+10 -2
View File
@@ -35,7 +35,8 @@ retain their original reply formats.
- `capabilities` optionally takes a `peer`. It returns the broker `protocol`
(2), `hostRevision`, and boolean `write`, `delete`, `move`,
`revisionRead`, `onHostTransfer`, and `localEndpoint` fields. With no peer,
`revisionRead`, `onHostTransfer`, `localEndpoint`, and optional
`conflictPrompt` fields. With no peer,
the fields describe the local broker and its grants. With a peer, the flags
also account for its supported protocol. A peer with revision 0 still
supports legacy browsing and downloading.
@@ -57,7 +58,8 @@ retain their original reply formats.
The recycle bin is subject to Windows availability on the paired host.
- `transfer` takes `source` and `target` objects with a `peer` and `path`
each, optional `move` (default false), and a `conflict` policy of `fail`
(default), `skip`, or `replace`. Replace merges directories and replaces
(default), `skip`, `replace`, or `ask` when `conflictPrompt` is available.
Replace merges directories and replaces
regular files after validating the destination revision. The broker
allows at most one local endpoint, represented by `"peer": null`. For a
local endpoint the client must open the pipe with Windows impersonation
@@ -69,6 +71,12 @@ retain their original reply formats.
final frame has `type: "complete"` and counts, or an error. Transfers
on one paired computer use its own file service even across drives. The
local pipe exchanges only control and status for transfers.
- Ask merges directories and reports individual collisions in a JSON frame
with `type: "conflict"`, target `path`, `incoming` and `existing` metadata
(as in `stat`), and boolean `replaceable`. Respond with a JSON frame
containing `decision: "replace"`, `"skip"`, or `"cancel"`. Send
`decision: "wait"` at least once every five seconds while a prompt is open.
Access is checked again after each reply and before publishing the file.
- For a move, the copy phase finishes before source deletion begins.
Skipped items remain at the source. Cancellation or failure can leave
previously completed destination items. Failure during source cleanup
+20 -8
View File
@@ -440,9 +440,10 @@ Drag the divider to resize navigation. The window remembers its size, position,
Switching sections preserves your edits. Save, Cancel, Import and Export stay below every page.
Open the desired chat in Telegram Desktop or Microsoft Teams, then open Settings → Languages →
**Languages for a chat…**. Select the chat and click the languages to include. Choose
**Use languages**, then **Save** in Settings. The subset order is saved from the main
layout list when editing the profile; one-language profiles are supported. **Remove profile** restores default behavior.
**Languages for a chat** in the navigation tree. Find the contact, select the chat and
choose the layouts to include. Click **Apply** to keep Settings open or **Save** to close it.
A profile can contain a single layout and cycles through its layouts in the order shown.
Use **Remove profile** and apply or save the change to restore default behavior.
For a matching chat, **Alt+Shift**, **Win+Space** (and reverse **Win+Shift+Space**) cycle
through that subset. KSwitcher's **Next layout** conversion uses the same subset.
@@ -461,10 +462,11 @@ From v0.6.53, chat profiles (application, visible chat name and ordered language
**Українською.** Вибирайте розділ у дереві Settings або шукайте окремий параметр через **Search settings**.
Перетягніть розділювач, щоб змінити ширину дерева. Settings запам’ятовує розмір і положення вікна
та активний розділ. Перехід між розділами зберігає чернетку. Save, Cancel, Import і Export доступні знизу. Відкрий потрібний чат у Telegram або Teams, потім **Settings → Languages → Languages
for a chat…**. Вибери чат і потрібні мови, натисни **Use languages**, а потім **Save**.
for a chat** у дереві налаштувань. Знайдіть контакт, виберіть чат і потрібні розкладки.
Натисніть **Apply**, щоб залишити Settings відкритим, або **Save**, щоб закрити його.
Набір діє для **Alt+Shift**, **Win+Space**, **Win+Shift+Space** та **Next layout** KSwitcher.
Можна вибрати й одну мову; порядок зберігається із загального списку під час редагування профілю. **Remove profile**
повертає звичайну поведінку. Без профілю системні комбінації працюють як раніше,
Можна вибрати одну розкладку. Розкладки перемикаються в порядку, показаному в списку.
Натисніть **Remove profile** і застосуйте або збережіть зміни, щоб повернути звичайну поведінку. Без профілю системні комбінації працюють як раніше,
а Next layout використовує загальний набір. Видалені з Windows розкладки пропускаються;
якщо доступних мов профілю не залишилося, використовується загальний набір.
Прямі комбінації мов не змінюються; явно задані комбінації KSwitcher мають пріоритет.
@@ -478,11 +480,11 @@ Telegram ігнорується. Teams підтримує зазначений
### Telegram Web in Chrome — v0.6.51
Open a chat in Telegram Web K (`https://web.telegram.org/k/`) in Chrome, then use **Settings → Languages → Languages for a chat...** and select **Telegram Web: name**. Choose languages, then **Use languages → Save**. The same subset applies to Alt+Shift, Win+Space, Win+Shift+Space and Next layout. Web profiles are separate from desktop Telegram profiles. Same-name chats across browser profiles/accounts share a web profile.
Open a chat in Telegram Web K (`https://web.telegram.org/k/`) in Chrome, then use **Settings → Languages → Languages for a chat** and select the contact with **Telegram Web** in the App column. Choose layouts and click **Apply** or **Save**. The same subset applies to Alt+Shift, Win+Space, Win+Shift+Space and Next layout. Web profiles are separate from desktop Telegram profiles. Same-name chats across browser profiles/accounts share a web profile.
Recognition uses Chrome accessibility: the address bar and active document must both identify a Telegram chat, then the visible header supplies the name. The app watches foreground/focus and address/header-change events; it does not use OCR, a polling timer, an extension, or message-history extraction. The address bar, home page and unsupported URLs do not match. Web A and other browsers have not been validated and are not advertised as supported. Page or accessibility changes can make a chat unavailable instead of guessing.
**Українською.** З v0.6.51 підтримано Telegram Web K у Chrome. Відкрий чат, потім **Settings → Languages → Languages for a chat...**, вибери **Telegram Web: ім’я**, мови та **Use languages → Save**. Набір діє для Alt+Shift, Win+Space, Win+Shift+Space і Next layout. Вебпрофілі окремі від Telegram Desktop; однакові назви в різних акаунтах/профілях браузера мають спільний вебпрофіль. Адреса й назва беруться через accessibility, без OCR, таймера, розширення та читання історії повідомлень. В адресному рядку, на головній сторінці й для непідтримуваних адрес профіль не діє. Web A та інші браузери не перевірені й не заявлені як підтримувані.
**Українською.** З v0.6.51 підтримано Telegram Web K у Chrome. Відкрий чат, потім **Settings → Languages → Languages for a chat**, вибери контакт із **Telegram Web** у колонці App та потрібні розкладки, а потім натисни **Apply** або **Save**. Набір діє для Alt+Shift, Win+Space, Win+Shift+Space і Next layout. Вебпрофілі окремі від Telegram Desktop; однакові назви в різних акаунтах/профілях браузера мають спільний вебпрофіль. Адреса й назва беруться через accessibility, без OCR, таймера, розширення та читання історії повідомлень. В адресному рядку, на головній сторінці й для непідтримуваних адрес профіль не діє. Web A та інші браузери не перевірені й не заявлені як підтримувані.
### Snippet autocomplete — v0.6.69
@@ -1042,6 +1044,16 @@ 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.
With a Dirlume build that supports KSwitcher terminal insertion, use
`--terminal-insert` at a blank shell prompt and check that `snippet test`
appears as an editable draft. Clear that draft without submitting it.
`-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:
+10
View File
@@ -1,5 +1,15 @@
# Latest Windows release
## v0.8.4 — 2026-11-27
- **Settings.** Open **Languages → Languages for a chat** in the Settings tree to search for a chat and choose its keyboard layouts. Save changes with **Apply** or **Save**.
- **Trusted LAN clients.** Clients such as Dirlume can ask how to handle individual file conflicts during copy or move. When supported, choose to replace, skip or cancel.
**Українською.**
- **Налаштування.** Відкрийте **Languages → Languages for a chat** у дереві Settings, щоб знайти чат і вибрати його розкладки. Застосуйте зміни кнопкою **Apply** або **Save**.
- **Довірені клієнти LAN.** Клієнти на кшталт Dirlume можуть запитувати, як обробити окремі конфлікти файлів під час копіювання або переміщення. Якщо клієнт підтримує цю можливість, виберіть заміну, пропуск або скасування.
## v0.8.3 — 2026-11-26
- **Files.** Lavender now shows compact path segments with chevrons above both panes. The current folder has a rounded highlight. Click an ancestor to open it, the current folder to edit the path, or an ellipsis to reveal hidden folders.
+1 -1
View File
@@ -1 +1 @@
0726c819b43cd1508c4fa22b717ab13b0da826f5a48bbc3a4b0f10e6418d207a KSwitcher-win-x64.zip
9035578c4aa96533a78dd1830966cf0b2f8d9de623f51ec2d111e62249d1c65d KSwitcher-win-x64.zip
+42 -42
View File
@@ -1,181 +1,181 @@
{
"version": "0.8.3",
"schema": 1,
"files": [
{
"sha256": "134aff7d86cdba13eecf9e32a0556e0267c0900800bd6dc1e9b005729190eb7a",
"path": "KSwitcher.exe",
"size": 3247616
"sha256": "a7ad4db3cb46825c65b851c7e4cbd214f779eb5325a91ca7cdb96a3fe944d8a4",
"size": 3251712
},
{
"sha256": "7f90f6af18c9ac7f9e0f8255bfd339c49c9ea28e2da88d6b6e3443f6a867a1dd",
"path": "KSwitcher.Config.exe",
"size": 2849792
"sha256": "c9d2dddc6e2a5e14be02680c1177e4813515e207bada399f255fcbf4aef5e884",
"size": 2850304
},
{
"sha256": "f010f82aba8ace45abf0b90db991804964c1ec18f783a4169add56f478c96344",
"path": "KSwitcher.Screenshot.exe",
"sha256": "1112fd25921d49ef20b3f71b0b8234eea3e9df47b1c1d207bfa22a9f7da34028",
"size": 3193344
},
{
"sha256": "caa66e3d8cddd094f1de317fb1a6410d4413f30034cdb61f130d7fcee21004bb",
"path": "KSwitcher.Files.exe",
"size": 6000640
"sha256": "b2843967c9b70839e45ec3b8b48bffde41ff8994ea345317beb1bda28e6d6dff",
"size": 6002688
},
{
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912
},
{
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103
},
{
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521
},
{
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527
},
{
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"path": "terminal/markdown-it-LICENSE.txt",
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"size": 1073
},
{
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"path": "terminal/markdown-it.js",
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"size": 100786
},
{
"sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2",
"path": "terminal/markdown.html",
"sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2",
"size": 3800
},
{
"sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96",
"path": "terminal/markdown.js",
"sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96",
"size": 18721
},
{
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"path": "terminal/mermaid-LICENSE.txt",
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"size": 1089
},
{
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"path": "terminal/mermaid.js",
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"size": 5537838
},
{
"sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7",
"path": "terminal/terminal.js",
"sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7",
"size": 6627
},
{
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261
},
{
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112
},
{
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663
},
{
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401
},
{
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"path": "json-LICENSE.txt",
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"size": 1096
},
{
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883
},
{
"sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d",
"path": "files-archive-license.txt",
"sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d",
"size": 4990
},
{
"sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4",
"path": "files-image-license.txt",
"sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4",
"size": 3044
},
{
"sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594",
"path": "files-sftp-license.txt",
"sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594",
"size": 2064
},
{
"sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01",
"path": "README.md",
"size": 105515
"sha256": "7f179b561fab6125f167203a6ae180a7050d876b056c39f62f3be36cf4bad733",
"size": 105904
},
{
"sha256": "917c2f41b3943647fdfafa911d93f72b8c6fb0d08592016ce1a698d256e038bb",
"path": "LAN-PREVIEW.md",
"size": 16722
"sha256": "4eac1f410e6b544aa45756e24f4fdfe9193c6f732410656160be54ab27a0d7e4",
"size": 17245
},
{
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"path": "dictionaries/en.txt",
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"size": 732485
},
{
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"size": 20566
},
{
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265
},
{
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"path": "dictionaries/ru.txt",
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"size": 1109134
},
{
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280
},
{
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799
},
{
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993
},
{
"sha256": "b6a36bcdc26fc6bb55083e023e2fafb60236e541e9b1b7e598c66816a3089175",
"path": "tools/StayHere.exe",
"sha256": "1530796fac99f1542b992e4254fc30c16c24ee7e6c6dc7b6ba41d241e3ea6417",
"size": 133120
},
{
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796
}
]
],
"version": "0.8.4"
}
+3 -3
View File
@@ -14,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,8,3,0
PRODUCTVERSION 0,8,3,0
FILEVERSION 0,8,4,0
PRODUCTVERSION 0,8,4,0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
@@ -25,7 +25,7 @@ BEGIN
BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.8.3"
VALUE "FileVersion", "0.8.4"
END
END
BLOCK "VarFileInfo"
+196 -29
View File
@@ -45,26 +45,107 @@ GUITHREADINFO snippetGuiInfo(HWND target)
return info;
}
std::optional<RECT> accessibleSnippetCaret(HWND target)
using Microsoft::WRL::ComPtr;
constexpr std::wstring_view terminalSnippetTicketPrefix = L"dirlume-terminal-snippet-v1:";
bool snippetElementClass(IUIAutomationElement *element, std::wstring_view name)
{
BSTR className{};
const bool matches = SUCCEEDED(element->get_CurrentClassName(&className)) && className && className == name;
SysFreeString(className);
return matches;
}
ComPtr<IUIAutomationElement> focusedSnippetElement(IUIAutomation2 *automation, HWND target)
{
using Microsoft::WRL::ComPtr;
ComPtr<IUIAutomation2> automation;
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER,
IID_IUIAutomation2, reinterpret_cast<void **>(automation.GetAddressOf()))))
return {};
automation->put_ConnectionTimeout(150);
automation->put_TransactionTimeout(150);
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, focused.Get(), target))
return {};
return focused;
}
ComPtr<IUIAutomation2> snippetAutomation()
{
ComPtr<IUIAutomation2> automation;
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&automation))))
return {};
automation->put_ConnectionTimeout(150);
automation->put_TransactionTimeout(150);
return automation;
}
ComPtr<IUIAutomationValuePattern> terminalSnippetInput(IUIAutomation *automation, IUIAutomationElement *focused)
{
// The receiver is a sibling of this terminal's focused xterm input.
ComPtr<IUIAutomationTreeWalker> walker;
ComPtr<IUIAutomationElement> parent, input;
ComPtr<IUIAutomationCondition> condition;
if (FAILED(automation->get_RawViewWalker(&walker)) || !walker ||
FAILED(walker->GetParentElement(focused, &parent)) || !parent)
return {};
VARIANT className{};
className.vt = VT_BSTR;
className.bstrVal = SysAllocString(L"dirlume-terminal-snippet-input");
const auto result = automation->CreatePropertyCondition(UIA_ClassNamePropertyId, className, &condition);
VariantClear(&className);
if (FAILED(result) || !condition ||
FAILED(parent->FindFirst(TreeScope_Children, condition.Get(), &input)) || !input)
return {};
ComPtr<IUIAutomationValuePattern> value;
input->GetCurrentPatternAs(UIA_ValuePatternId, IID_PPV_ARGS(&value));
return value;
}
std::wstring terminalSnippetTicket(IUIAutomationValuePattern *value)
{
if (!value) return {};
BSTR ticket{};
const auto result = value->get_CurrentValue(&ticket);
const std::wstring_view text(ticket ? ticket : L"", SysStringLen(ticket));
auto accepted = SUCCEEDED(result) && text.size() == terminalSnippetTicketPrefix.size() + 36 &&
text.starts_with(terminalSnippetTicketPrefix) ? std::wstring(text) : std::wstring();
SysFreeString(ticket);
return accepted;
}
std::optional<Template> terminalSnippetTemplate(const Snippet &snippet)
{
auto value = parseTemplate(snippet.text);
if (value.text.empty() || value.text.size() > 8192 || !value.actions.empty() ||
std::any_of(value.text.begin(), value.text.end(), [](wchar_t c) {
return c < 0x20 || (c >= 0x7f && c <= 0x9f) || c == 0x2028 || c == 0x2029;
})) return {};
return value;
}
std::optional<SnippetAnchor> accessibleSnippetCaret(HWND target)
{
const auto automation = snippetAutomation();
if (!automation) return {};
const auto focused = focusedSnippetElement(automation.Get(), target);
if (!focused) return {};
// The xterm.js input follows the terminal cursor for IME. Dirlume
// handles replacement in the active shell draft through a separate input.
if (snippetElementClass(focused.Get(), L"xterm-helper-textarea"))
{
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)
{
auto ticket = lower(processName(target)) == L"dirlume" ?
terminalSnippetTicket(terminalSnippetInput(automation.Get(), focused.Get()).Get()) : std::wstring();
return SnippetAnchor{{cell.left, cell.top, cell.left, cell.bottom}, true, std::move(ticket)};
}
return {};
}
ComPtr<IUIAutomationTextPattern2> pattern;
ComPtr<IUIAutomationTextRange> range;
BOOL active{};
@@ -121,7 +202,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 +1566,12 @@ void App::matchSnippets(HWND fg, bool expandExact)
!snippetWordCharacter(layout->at(physicalLayout().code(previous)));
}))
{
if (snippetPopupAnchor.terminal && snippetTarget == fg && snippetPopup &&
IsWindowVisible(snippetPopup) && snippetFocus == snippetGuiInfo(fg).hwndFocus)
{
hideSnippetPopup();
return;
}
queueSnippet(fg, i, sn.trigger.size());
return;
}
@@ -1559,11 +1646,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 +1659,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 +1674,22 @@ void App::showSnippetPopup()
PostMessageW(receiver, SnippetCaretMessage, static_cast<WPARAM>(version), 0);
});
}
void App::placeSnippetPopup(RECT anchor)
void App::placeSnippetPopup(SnippetAnchor placement)
{
snippetPopupAnchor = anchor;
if (placement.terminal && placement.canInsert())
{
const auto previous = snippetMatches[snippetSelection];
std::erase_if(snippetMatches, [&](size_t index) { return !terminalSnippetTemplate(settings.snippets[index]); });
if (snippetMatches.empty())
{
hideSnippetPopup();
return;
}
const auto selected = std::find(snippetMatches.begin(), snippetMatches.end(), previous);
snippetSelection = selected == snippetMatches.end() ? 0 : static_cast<size_t>(selected - snippetMatches.begin());
}
snippetPopupAnchor = std::move(placement);
const auto &anchor = snippetPopupAnchor.bounds;
if (!snippetPopup)
{
WNDCLASSW cls{};
@@ -1630,24 +1738,83 @@ void App::placeSnippetPopup(RECT anchor)
InvalidateRect(snippetPopup, nullptr, FALSE);
SetTimer(window, SnippetPopupTimer, 100, nullptr);
}
void App::selectSnippet(size_t row)
bool App::selectSnippet(size_t row)
{
if (row >= snippetMatches.size() || !snippetPopupCurrent()) return;
if (!snippetPopupAnchor.canInsert() || row >= snippetMatches.size() || !snippetPopupCurrent()) return false;
const auto index = snippetMatches[row];
const auto length = snippetPrefixLength;
hideSnippetPopup();
std::lock_guard lock(stateMutex);
if (snippetPopupVersion == inputVersion && !busy)
queueSnippet(snippetTarget, index, length, snippetFocus);
if (!snippetPopupCurrent()) return false;
if (!snippetPopupAnchor.terminal)
{
hideSnippetPopup();
return queueSnippet(snippetTarget, index, length, snippetFocus);
}
const auto layout = std::find_if(layouts.begin(), layouts.end(), [&](const auto &item) {
return item.handle == run.layout && item.convertible;
});
if (layout == layouts.end() || run.window != snippetTarget || run.keys.size() < length)
return false;
const auto replacement = terminalSnippetTemplate(settings.snippets[index]);
if (!replacement) return false;
std::wstring prefix;
for (wchar_t key : std::wstring_view(run.keys).substr(run.keys.size() - length))
prefix += layout->at(physicalLayout().code(key));
if (prefix.empty() || prefix.find(L'\0') != prefix.npos) return false;
const auto ticket = snippetPopupAnchor.terminalTicket;
const auto target = snippetTarget;
const auto editor = snippetFocus;
const auto request = wide(DiagnosticJson::array({utf8(ticket), utf8(prefix), utf8(replacement->text),
replacement->text.size() - replacement->suffix.size()}).dump(-1, ' ', true, DiagnosticJson::error_handler_t::replace));
hideSnippetPopup();
run.reset();
const auto version = ++inputVersion;
typingTarget = target;
snippetTyping = true;
busy = true;
enqueue([this, target, editor, version, ticket, request] {
struct Replay
{
HWND window;
~Replay() { PostMessageW(window, ReplayTypingMessage, 0, 0); }
} replay{window};
const auto current = [&] {
return inputVersion == version && GetForegroundWindow() == target && snippetGuiInfo(target).hwndFocus == editor;
};
if (!current()) return;
const auto automation = snippetAutomation();
if (!automation) return;
const auto focused = focusedSnippetElement(automation.Get(), target);
if (!focused || !snippetElementClass(focused.Get(), L"xterm-helper-textarea")) return;
const auto input = terminalSnippetInput(automation.Get(), focused.Get());
if (terminalSnippetTicket(input.Get()) != ticket || !current()) return;
BSTR payload = SysAllocStringLen(request.data(), static_cast<UINT>(request.size()));
if (!payload) return;
const auto sent = input->SetValue(payload);
SysFreeString(payload);
if (FAILED(sent)) return;
// Keep subsequent keystrokes ordered behind the renderer's draft edit.
const auto until = GetTickCount64() + 200;
while (current() && GetTickCount64() < until)
{
const auto reply = terminalSnippetTicket(input.Get());
if (!reply.empty() && reply != ticket) return;
Sleep(10);
}
});
return true;
}
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));
(!snippetPopupAnchor.terminal && 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;
if (accept) selectSnippet(snippetSelection);
if (accept) return selectSnippet(snippetSelection);
else if (vk == VK_ESCAPE) hideSnippetPopup();
else
{
@@ -1690,7 +1857,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 +3770,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;
+11 -4
View File
@@ -23,6 +23,13 @@ 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 terminal{};
std::wstring terminalTicket;
bool canInsert() const { return !terminal || !terminalTicket.empty(); }
};
struct LastTransform
{
HWND window{};
@@ -203,20 +210,20 @@ 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);
void selectSnippet(size_t);
bool selectSnippet(size_t);
static LRESULT CALLBACK snippetPopupProc(HWND, UINT, WPARAM, LPARAM);
std::vector<INPUT> deferredTyping;
bool beginTypingDeferral(HWND, uint64_t, bool snippet = false);
+25 -5
View File
@@ -48,7 +48,8 @@ Json capabilities(bool write, bool erase, unsigned host)
{
return {{"protocol", 2}, {"hostRevision", host}, {"write", write && host},
{"delete", erase && host}, {"move", write && erase && host},
{"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0}};
{"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0},
{"conflictPrompt", host != 0}};
}
fs::path itemPath(const Json &value)
{
@@ -128,6 +129,27 @@ class ClientTransfer
if (!result.at("continue").get<bool>()) throw std::system_error(ERROR_CANCELLED, std::system_category());
guard();
}
bool resolveConflict(const fs::path &path, const Json &incoming, const Json &existing)
{
if (conflict == "skip") return false;
const bool replaceable = directory(incoming) == directory(existing) && !reparse(existing);
if (conflict == "replace" && replaceable) return true;
if (conflict != "ask") throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category());
if (replaceable && directory(existing)) return true;
sendJson(send, {{"type", "conflict"}, {"path", utf8(path.native())},
{"incoming", incoming}, {"existing", existing}, {"replaceable", replaceable}});
for (;;)
{
const auto answer = Json::parse(receive(256)).at("decision").get<std::string>();
guard();
if (answer == "wait") continue;
if (answer == "skip") return false;
if (answer == "replace" && replaceable) return true;
if (answer == "cancel") throw std::system_error(ERROR_CANCELLED, std::system_category());
throw std::runtime_error("Invalid transfer conflict decision.");
}
}
bool copy(const fs::path &from, const fs::path &to, unsigned depth)
{
if (depth > 256) throw std::runtime_error("The file tree is too deep.");
@@ -139,9 +161,7 @@ class ClientTransfer
if (found)
{
checkFileReply(existing);
if (conflict == "skip") { ++skipped; return false; }
if (conflict != "replace" || directory(original) != directory(existing))
throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category());
if (!resolveConflict(to, original, existing)) { ++skipped; return false; }
requireRegular(existing);
}
@@ -199,7 +219,7 @@ public:
void run(const fs::path &from, const fs::path &to)
{
if (conflict != "fail" && conflict != "skip" && conflict != "replace")
if (conflict != "fail" && conflict != "skip" && conflict != "replace" && conflict != "ask")
throw std::runtime_error("Unknown conflict policy.");
if (sameHost)
{
+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;
+144 -193
View File
@@ -1210,7 +1210,8 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
#ifndef KS_RESIDENT_APP
constexpr int LanguagesPage = 1, ShortcutsPage = 2, ClipboardPage = 3, SnippetsPage = 4, MousePage = 5;
constexpr int ExceptionsPage = 13, PersonalDictionariesPage = 14, WordBoundariesPage = 15, SnippetMacros = 320;
constexpr int CustomReplacementsPage = 16;
constexpr int CustomReplacementsPage = 16, ChatLanguagesPage = 20;
constexpr int ChatContacts = 710, ChatLayouts = 711, ChatProfileStatus = 712, ChatRemoveProfile = 713, ChatSearch = 714;
constexpr int ClipboardExcludedApps = 243, ClipboardAppName = 244, ClipboardAddApp = 245,
ClipboardRemoveApp = 246, ClipboardAppPicker = 247;
constexpr UINT AppWindowPicked = WM_APP + 78;
@@ -1254,6 +1255,7 @@ constexpr struct SettingsSection
{"openbao", L"OpenBao", L"Connect to OpenBao and synchronize your saved settings.", SyncPage},
{"google-drive", L"Google Drive", L"Synchronize settings across PCs or manage manual backups.", SyncPage},
{"ocr", L"Image text recognition", L"Choose Windows OCR or Tesseract. Recognition runs on this computer.", ClipboardPage},
{"chat-languages", L"Languages for a chat", L"Choose which keyboard layouts to cycle through in a chat.", LanguagesPage},
};
constexpr wchar_t SettingsWindowFile[] = L"configurator-window.json";
struct SettingsWindowState
@@ -1353,6 +1355,9 @@ struct SettingsView
SIZE mouseProfileCheckSize{};
unsigned mouseEvents{}, rawMouseEvents{};
bool rawMouseRegistered{};
std::vector<std::wstring> chatKeys;
int chatSelection = -1;
bool updatingChatContacts{};
SnippetView snippets;
HWND clipboardPickerOutline{};
};
@@ -1863,6 +1868,8 @@ void reflowSettingsPage(HWND pane, WindowLayout &layout, int width, int height)
}
layout.height = fitSettingsColumns(layout, page.first, page.end, available, grid);
const int extra = height * 96 / static_cast<int>(dpi) - layout.height;
if (v.selectedPage == ChatLanguagesPage)
stretchSettingsEditors(layout, page.first, page.end, std::min(extra, 160), {ChatContacts, ChatLayouts}, true);
if (v.selectedPage == SnippetsPage)
stretchSettingsEditors(layout, page.first, page.end, extra, {301, 303}, available < grid.wrapAt);
if (v.selectedPage == MousePage)
@@ -1954,6 +1961,7 @@ void reflowClipboard(HWND pane, WindowLayout &layout, int width, int height)
if (scale(pane, layout.height) > height)
fit(width - GetSystemMetricsForDpi(SM_CXVSCROLL, dpi));
}
void refreshChatLanguages(SettingsView &v);
void selectSettingsPage(SettingsView &v, int selected)
{
if (selected < 0 || selected >= (int)v.pages.size() || selected == v.selectedPage) return;
@@ -1968,6 +1976,7 @@ void selectSettingsPage(SettingsView &v, int selected)
ShowWindow(layout.controls[i].first, SW_HIDE);
}
v.selectedPage = selected;
if (selected == ChatLanguagesPage) refreshChatLanguages(v);
SetWindowTextW(v.heading, settingsSections[selected].name);
SetWindowTextW(v.description, settingsSections[selected].description);
const auto &page = v.pages[selected];
@@ -2274,81 +2283,42 @@ void indexSettingsControl(SettingsView &v, int page, HWND child)
}
v.searchEntries.push_back({page, child, target, std::move(text), aliases});
}
struct ChatLanguagesView
void fillChatLanguages(SettingsView &v)
{
HWND parent{};
SettingsView *settings{};
std::vector<std::wstring> keys;
Settings draft;
int selection = -1;
bool dirty{};
bool updatingList{};
std::wstring search;
};
void collectChatLanguages(HWND w, ChatLanguagesView *v)
{
if (!v->dirty || v->selection < 0) return;
std::vector<std::wstring> cycle;
for (size_t i = 0; i < v->settings->order.size(); ++i)
if (SendDlgItemMessageW(w, 711, LB_GETSEL, i, 0) > 0)
cycle.push_back(v->settings->app->layouts[v->settings->order[i]].id);
if (cycle.empty()) throw std::runtime_error("Select at least one language.");
v->draft.chatCycles[v->keys[v->selection]] = std::move(cycle);
v->dirty = false;
}
void fillChatLanguages(HWND w, ChatLanguagesView *v)
{
int index = v->selection;
EnableWindow(GetDlgItem(w, 711), index >= 0);
EnableWindow(GetDlgItem(w, IDOK), index >= 0);
if (index < 0)
HWND pane = v.viewport;
const bool selected = v.chatSelection >= 0;
EnableWindow(GetDlgItem(pane, ChatLayouts), selected && !v.order.empty());
if (!selected)
{
SendDlgItemMessageW(w, 711, LB_SETSEL, FALSE, -1);
EnableWindow(GetDlgItem(w, 713), FALSE);
value(w, 712, v->keys.empty() ? L"Open a chat, then reopen this dialog to add it." :
L"No contacts match your search.");
SendDlgItemMessageW(pane, ChatLayouts, LB_SETSEL, FALSE, -1);
EnableWindow(GetDlgItem(pane, ChatRemoveProfile), FALSE);
value(pane, ChatProfileStatus, v.chatKeys.empty() ?
L"Open a chat, then return to this page." : L"No matching chat selected.");
return;
}
const auto &draft = v->draft;
auto saved = draft.chatCycles.find(v->keys[index]);
const auto &cycle = saved == draft.chatCycles.end() ? draft.cycle : saved->second;
for (size_t i = 0; i < v->settings->order.size(); ++i)
const auto saved = v.draft.chatCycles.find(v.chatKeys[v.chatSelection]);
const bool hasProfile = saved != v.draft.chatCycles.end();
const auto &cycle = hasProfile ? saved->second : v.draft.cycle;
for (size_t i = 0; i < v.order.size(); ++i)
{
auto &layout = v->settings->app->layouts[v->settings->order[i]];
SendDlgItemMessageW(w, 711, LB_SETSEL,
std::find(cycle.begin(), cycle.end(), layout.id) != cycle.end(), i);
const auto &layout = v.app->layouts[v.order[i]];
SendDlgItemMessageW(pane, ChatLayouts, LB_SETSEL, std::ranges::find(cycle, layout.id) != cycle.end(), i);
}
value(w, 712, saved == draft.chatCycles.end() ? L"No profile yet. Select the languages for this chat." :
L"Chat profile. Select languages, or remove it to use the defaults.");
EnableWindow(GetDlgItem(w, 713), saved != draft.chatCycles.end());
value(pane, ChatProfileStatus, hasProfile ? L"Chat profile" : L"Using the default language cycle");
EnableWindow(GetDlgItem(pane, ChatRemoveProfile), hasProfile);
}
void selectChatRow(HWND list, int index)
void filterChatRows(SettingsView &v, const std::wstring &previous)
{
int row = -1;
if (index >= 0)
{
LVFINDINFOW find{LVFI_PARAM};
find.lParam = index;
row = ListView_FindItem(list, -1, &find);
}
ListView_SetItemState(list, -1, 0, LVIS_SELECTED | LVIS_FOCUSED);
if (row >= 0)
{
ListView_SetItemState(list, row, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
ListView_EnsureVisible(list, row, FALSE);
}
}
void filterChatRows(HWND w, ChatLanguagesView *v)
{
auto list = GetDlgItem(w, 710);
auto search = lower(v->search);
int selection = -1;
v->updatingList = true;
auto list = GetDlgItem(v.viewport, ChatContacts);
const auto search = lower(value(v.viewport, ChatSearch));
int selectedRow = -1;
v.chatSelection = -1;
v.updatingChatContacts = true;
SendMessageW(list, WM_SETREDRAW, FALSE, 0);
ListView_DeleteAllItems(list);
for (size_t i = 0; i < v->keys.size(); ++i)
for (size_t i = 0; i < v.chatKeys.size(); ++i)
{
const auto &key = v->keys[i];
const auto &key = v.chatKeys[i];
auto contact = key.substr(key.find(L'\n') + 1);
if (lower(contact).find(search) == std::wstring::npos) continue;
auto app = key.starts_with(L"telegram\n") ? L"Telegram" :
@@ -2358,153 +2328,99 @@ void filterChatRows(HWND w, ChatLanguagesView *v)
item.iItem = ListView_GetItemCount(list);
item.pszText = contact.data();
item.lParam = static_cast<LPARAM>(i);
int row = ListView_InsertItem(list, &item);
const int row = ListView_InsertItem(list, &item);
if (row < 0) continue;
ListView_SetItemText(list, row, 1, const_cast<wchar_t *>(app));
if (selection < 0 || static_cast<int>(i) == v->selection) selection = static_cast<int>(i);
if (selectedRow < 0 || key == previous)
{
selectedRow = row;
v.chatSelection = static_cast<int>(i);
}
}
if (selectedRow >= 0)
{
ListView_SetItemState(list, selectedRow, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
ListView_EnsureVisible(list, selectedRow, FALSE);
}
selectChatRow(list, selection);
SendMessageW(list, WM_SETREDRAW, TRUE, 0);
InvalidateRect(list, nullptr, TRUE);
v->updatingList = false;
v->selection = selection;
fillChatLanguages(w, v);
v.updatingChatContacts = false;
fillChatLanguages(v);
}
LRESULT CALLBACK chatLanguagesProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
std::wstring selectedChatKey(const SettingsView &v)
{
auto *v = (ChatLanguagesView *)GetWindowLongPtrW(w, GWLP_USERDATA);
if (!v) return DefWindowProcW(w, msg, wp, lp);
try
{
if (msg == WM_NOTIFY && !v->updatingList)
{
auto *change = reinterpret_cast<const NMLISTVIEW *>(lp);
if (change->hdr.idFrom == 710 && change->hdr.code == LVN_ITEMCHANGED &&
(change->uNewState & LVIS_SELECTED) && !(change->uOldState & LVIS_SELECTED))
{
int selected = static_cast<int>(change->lParam);
if (selected == v->selection) return 0;
try { collectChatLanguages(w, v); }
catch (...)
{
v->updatingList = true;
selectChatRow(change->hdr.hwndFrom, v->selection);
v->updatingList = false;
throw;
}
v->selection = selected;
fillChatLanguages(w, v);
return 0;
}
}
if (msg == WM_COMMAND)
{
int id = LOWORD(wp);
if (id == 711 && HIWORD(wp) == LBN_SELCHANGE) { v->dirty = true; return 0; }
if (id == 714 && HIWORD(wp) == EN_CHANGE && !v->updatingList)
{
try { collectChatLanguages(w, v); }
catch (...)
{
v->updatingList = true;
value(w, 714, v->search);
v->updatingList = false;
throw;
}
v->search = value(w, 714);
filterChatRows(w, v);
return 0;
}
if (id == IDOK || id == 713)
{
int selected = v->selection;
if (id == IDOK && selected < 0) return 0;
if (selected < 0 || selected >= (int)v->keys.size())
throw std::runtime_error("Open a Telegram or Teams chat, then reopen this dialog.");
if (id == 713)
{
v->draft.chatCycles.erase(v->keys[selected]);
v->dirty = false;
fillChatLanguages(w, v);
return 0;
}
collectChatLanguages(w, v);
validateSettings(v->draft);
v->settings->draft.chatCycles = std::move(v->draft.chatCycles);
DestroyWindow(w);
return 0;
}
if (id == IDCANCEL) { DestroyWindow(w); return 0; }
}
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
if (msg == WM_DPICHANGED)
{
resizeForDpi(w, wp, lp);
auto list = GetDlgItem(w, 710);
ListView_SetColumnWidth(list, 0, scale(w, 442));
ListView_SetColumnWidth(list, 1, scale(w, 140));
return 0;
}
if (msg == WM_NCDESTROY)
{
EnableWindow(v->parent, TRUE);
SetForegroundWindow(v->parent);
disposeFont(w);
delete v;
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
}
}
catch (const std::exception &e) { error(w, e); }
return DefWindowProcW(w, msg, wp, lp);
return v.chatSelection < 0 ? std::wstring{} : v.chatKeys[v.chatSelection];
}
void showChatLanguages(HWND parent, SettingsView *settings)
void refreshChatLanguages(SettingsView &v)
{
const auto previous = selectedChatKey(v);
std::set<std::wstring> keys;
for (const auto &[key, cycle] : settings->draft.chatCycles) keys.insert(key);
struct Context { std::set<std::wstring> &keys; const Settings &settings; } context{keys, settings->draft};
for (const auto &[key, cycle] : v.draft.chatCycles) keys.insert(key);
EnumWindows([](HWND candidate, LPARAM context) -> BOOL
{
if (!IsWindowVisible(candidate)) return TRUE;
auto &data = *(Context *)context;
auto &contacts = *reinterpret_cast<std::set<std::wstring> *>(context);
auto key = lower(processName(candidate)) == L"chrome" ? readChromeChat(candidate) : windowChatKey(candidate);
if (!key.empty()) data.keys.insert(std::move(key));
if (!key.empty()) contacts.insert(std::move(key));
return TRUE;
}, (LPARAM)&context);
}, reinterpret_cast<LPARAM>(&keys));
v.chatKeys.assign(keys.begin(), keys.end());
SendDlgItemMessageW(v.viewport, ChatLayouts, LB_RESETCONTENT, 0, 0);
for (int index : v.order)
SendDlgItemMessageW(v.viewport, ChatLayouts, LB_ADDSTRING, 0,
reinterpret_cast<LPARAM>(v.app->layouts[index].name.c_str()));
filterChatRows(v, previous);
}
void editChatLanguages(SettingsView &v)
{
if (v.chatSelection < 0) return;
std::vector<std::wstring> cycle;
for (size_t i = 0; i < v.order.size(); ++i)
if (SendDlgItemMessageW(v.viewport, ChatLayouts, LB_GETSEL, i, 0) > 0)
cycle.push_back(v.app->layouts[v.order[i]].id);
const bool hasLayouts = !cycle.empty();
if (hasLayouts) v.draft.chatCycles[v.chatKeys[v.chatSelection]] = std::move(cycle);
fillChatLanguages(v);
if (!hasLayouts) value(v.viewport, ChatProfileStatus, L"Select at least one layout, or remove the profile.");
}
void sizeChatContactColumns(HWND list)
{
RECT bounds{};
GetClientRect(list, &bounds);
const int appWidth = scale(list, 140);
const int scrollWidth = GetSystemMetricsForDpi(SM_CXVSCROLL, GetDpiForWindow(list));
ListView_SetColumnWidth(list, 0, std::max(0L, bounds.right - appWidth - scrollWidth));
ListView_SetColumnWidth(list, 1, appWidth);
}
LRESULT CALLBACK chatContactsProc(HWND list, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
const auto result = DefSubclassProc(list, msg, wp, lp);
if (msg == WM_SIZE) sizeChatContactColumns(list);
return result;
}
void createChatLanguages(HWND pane)
{
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES};
InitCommonControlsEx(&controls);
HWND w = makeWindow(*settings->app, L"KSwitcher.ChatLanguages", L"Languages for a chat", chatLanguagesProc, 640, 524);
auto *v = new ChatLanguagesView{parent, settings, {keys.begin(), keys.end()}};
v->draft = settings->draft;
v->updatingList = true;
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v);
label(w, L"&Find contact", 18, 19, 106);
edit(w, 714, 130, 14, 492);
auto list = control(w, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SINGLESEL |
LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, 710, 18, 48, 604, 136);
label(pane, L"&Find contact", 24, 68, 660);
edit(pane, ChatSearch, 24, 94, 660);
const auto list = control(pane, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SINGLESEL |
LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, ChatContacts, 24, 126, 660, 106);
ListView_SetExtendedListViewStyle(list, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | LVS_EX_LABELTIP);
for (const auto &[title, width] : {std::pair{L"Contact", 442}, std::pair{L"App", 140}})
for (const auto *title : {L"Contact", L"App"})
{
LVCOLUMNW column{LVCF_TEXT | LVCF_WIDTH};
LVCOLUMNW column{LVCF_TEXT};
column.pszText = const_cast<wchar_t *>(title);
column.cx = scale(w, width);
ListView_InsertColumn(list, Header_GetItemCount(ListView_GetHeader(list)), &column);
}
control(w, L"STATIC", L"Open a chat, then reopen this dialog to add it.", 0, 712, 18, 194, 604, 26);
label(w, L"Click languages to include (saved in the order shown)", 18, 228, 604);
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_MULTIPLESEL | LBS_NOINTEGRALHEIGHT | WS_BORDER,
711, 18, 256, 604, 132);
for (int i : settings->order)
SendDlgItemMessageW(w, 711, LB_ADDSTRING, 0, (LPARAM)settings->app->layouts[i].name.c_str());
label(w, L"Applies to Alt+Shift, Win+Space and KSwitcher Next layout.", 18, 402, 604);
label(w, L"Switch chats freely. Use languages, then Save settings.", 18, 430, 604);
button(w, L"&Remove profile", 713, 18, 476, 170);
button(w, L"&Use languages", IDOK, 300, 476, 170);
button(w, L"&Cancel", IDCANCEL, 486, 476, 136);
filterChatRows(w, v);
EnableWindow(parent, FALSE);
showRequestedWindow(w);
SetFocus(GetDlgItem(w, 714));
SetWindowSubclass(list, chatContactsProc, 1, 0);
sizeChatContactColumns(list);
control(pane, L"STATIC", L"", 0, ChatProfileStatus, 24, 242, 660, 24);
label(pane, L"Select layouts to include, in the order shown.", 24, 270, 660);
control(pane, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_MULTIPLESEL | LBS_NOINTEGRALHEIGHT |
WS_BORDER, ChatLayouts, 24, 296, 660, 80);
button(pane, L"&Remove profile", ChatRemoveProfile, 24, 388, 170);
label(pane, L"Applies to Alt+Shift, Win+Space, Win+Shift+Space and KSwitcher Next layout.", 24, 424, 660);
}
#include "ui_app_languages.inl"
#include "ui_mouse_buttons.inl"
@@ -2647,6 +2563,7 @@ void fillSettings(HWND root, SettingsView *v)
v->order.push_back(i);
v->selection = 0;
fillLayouts(v);
if (v->selectedPage == ChatLanguagesPage) refreshChatLanguages(*v);
fillMouseProfiles(root, *v);
fillCorrectionOptions(w, s);
v->filling = false;
@@ -3057,6 +2974,20 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (LOWORD(wp) != WA_INACTIVE) updateSettingsState(w, v);
break;
case WM_NOTIFY:
if (reinterpret_cast<const NMHDR *>(lp)->idFrom == ChatContacts &&
reinterpret_cast<const NMHDR *>(lp)->code == LVN_ITEMCHANGED)
{
const auto &change = *reinterpret_cast<const NMLISTVIEW *>(lp);
if (!v->updatingChatContacts && ((change.uNewState ^ change.uOldState) & LVIS_SELECTED))
{
if (change.uNewState & LVIS_SELECTED)
v->chatSelection = static_cast<int>(change.lParam);
else if (!ListView_GetSelectedCount(change.hdr.hwndFrom))
v->chatSelection = -1;
fillChatLanguages(*v);
}
return 0;
}
if (reinterpret_cast<const NMHDR *>(lp)->idFrom == SettingsNavigation)
{
const auto code = reinterpret_cast<const NMHDR *>(lp)->code;
@@ -3189,7 +3120,25 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
}
if (id == 263) { collectLayout(v); showAppLanguages(w, v); return 0; }
if (handleMouseBindings(w, *v, wp)) return 0;
if (id == 259) { collectLayout(v); showChatLanguages(w, v); return 0; }
if (id == ChatSearch && HIWORD(wp) == EN_CHANGE)
{
if (v->ready) filterChatRows(*v, selectedChatKey(*v));
return 0;
}
if (id == ChatLayouts && HIWORD(wp) == LBN_SELCHANGE)
{
editChatLanguages(*v);
return 0;
}
if (id == ChatRemoveProfile && HIWORD(wp) == BN_CLICKED)
{
if (v->chatSelection >= 0)
{
v->draft.chatCycles.erase(v->chatKeys[v->chatSelection]);
fillChatLanguages(*v);
}
return 0;
}
if (id == 230)
{
collectLayout(v);
@@ -3985,8 +3934,7 @@ void showSettings(App &app, bool visible)
hotkeyEdit(app, pane, 231, 454, 234, 230);
label(pane, L"Backspace / Delete clears it", 454, 270, 230);
button(pane, L"Re&fresh layouts", 253, 454, 322, 230);
button(pane, L"Languages for a &chat...", 259, 24, 378, 230);
button(pane, L"Languages for &applications...", 263, 272, 378, 300);
button(pane, L"Languages for &applications...", 263, 24, 378, 300);
page();
settingsGroupLabel(pane, L"Keyboard shortcuts", 24, 68);
@@ -4111,6 +4059,9 @@ void showSettings(App &app, bool visible)
createOcrSettings(pane);
page();
createChatLanguages(pane);
page();
v->splitter = control(w, L"STATIC", L"Resize navigation pane", SS_NOTIFY | WS_TABSTOP,
SettingsSplitter, 0, 0, 0, 0);
SetWindowSubclass(v->splitter, settingsSplitterProc, 1, reinterpret_cast<DWORD_PTR>(v));
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.8.3";
inline constexpr wchar_t AppVersion[] = L"0.8.4";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+62 -45
View File
@@ -854,13 +854,16 @@ int main(int argc,char **argv)
SendMessageW(GetDlgItem(correction, 414), BM_CLICK, 0, 0);
require(!saveEnabled(), "reverting an inline correction edit disables Save");
HWND navigation = settingsNavigation(parent);
constexpr int sections = 20;
constexpr int chatLanguagesPage = 20;
constexpr int sections = 21;
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");
require(TreeView_GetParent(navigation, settingsSection(navigation, 19)) == settingsSection(navigation, 3),
"image text recognition is nested under Clipboard");
require(TreeView_GetParent(navigation, settingsSection(navigation, chatLanguagesPage)) ==
settingsSection(navigation, 1), "chat profiles appear under Languages");
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");
@@ -1124,44 +1127,51 @@ int main(int argc,char **argv)
"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(!saveEnabled() && !GetDlgItem(pane, 259), "Languages uses the tree to open chat profiles");
selectSettingsPage(parent, chatLanguagesPage);
constexpr int contactsId = 710, layoutsId = 711, removeProfileId = 713, searchContactsId = 714;
require(IsWindowVisible(GetDlgItem(pane, contactsId)) && IsWindowEnabled(parent) &&
!findTestWindow(L"KSwitcher.ChatLanguages", nullptr), "chat profiles open within Settings");
auto findFixtureChat = [&] {
const auto chatPage = settingsViewport(parent);
SetDlgItemTextW(chatPage, searchContactsId, L"! fIXTURE CHAT");
const auto list = GetDlgItem(chatPage, contactsId);
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 selectChatLayouts = [&](bool select) {
const auto chatPage = settingsViewport(parent);
SendDlgItemMessageW(chatPage, layoutsId, LB_SETSEL, select, -1);
SendMessageW(chatPage, WM_COMMAND, MAKEWPARAM(layoutsId, LBN_SELCHANGE), 0);
};
SetDlgItemTextW(pane, searchContactsId, L"No matching fixture 8031");
require(ListView_GetItemCount(GetDlgItem(pane, contactsId)) == 0 &&
!IsWindowEnabled(GetDlgItem(pane, layoutsId)) &&
!IsWindowEnabled(GetDlgItem(pane, removeProfileId)), "empty search disables profile editing");
findFixtureChat();
require(SendDlgItemMessageW(pane, layoutsId, LB_GETSELCOUNT, 0, 0) == 1, "saved single language selected");
selectChatLayouts(false);
require(SendDlgItemMessageW(pane, layoutsId, LB_GETSELCOUNT, 0, 0) == 1 && !saveEnabled(),
"deselecting the last layout keeps the profile");
findFixtureChat();
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(dialog, dc);
ReleaseDC(parent, 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");
selectChatLayouts(true);
require(saveEnabled() == (app.layouts.size() > 1) && saveEnabled() == applyEnabled(),
"editing a profile immediately refreshes Apply and Save");
require(app.settings.chatCycles.at(key).size() == 1, "inline editing leaves saved settings untouched");
selectSettingsPage(parent, 1);
selectSettingsPage(parent, chatLanguagesPage);
require(SendDlgItemMessageW(pane, layoutsId, LB_GETSELCOUNT, 0, 0) == static_cast<LRESULT>(app.layouts.size()),
"profile edits survive navigating away and returning");
selectSettingsPage(parent, 16);
SetDlgItemTextW(correction, 412, L"Релізик\r\nрелізик, словечко");
SetDlgItemTextW(correction, 416, L" HeLo = Hello\r\n");
@@ -1174,26 +1184,33 @@ int main(int argc,char **argv)
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",
selectSettingsPage(parent, chatLanguagesPage);
findFixtureChat();
const auto chatPage = settingsViewport(parent);
require(SendDlgItemMessageW(chatPage, layoutsId, LB_GETSELCOUNT, 0, 0) ==
static_cast<LRESULT>(app.layouts.size()), "reopening shows the saved profile");
SendMessageW(GetDlgItem(chatPage, removeProfileId), BM_CLICK, 0, 0);
require(saveEnabled() && applyEnabled() && status().starts_with(L"Unsaved settings"),
"removing a profile immediately marks Settings 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");
SendMessageW(parent, WM_COMMAND, SettingsApply, 0);
require(IsWindow(parent) && !saveEnabled() && !applyEnabled() &&
!app.settings.chatCycles.contains(key) &&
!ks::loadSettings(root / L"settings.json", app.layouts).chatCycles.contains(key),
"Apply restores the default, saves the removal and keeps Settings open");
SendMessageW(parent, WM_COMMAND, IDCANCEL, 0);
// 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);
HWND 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);
+1 -1
View File
@@ -1138,7 +1138,7 @@ int main(int argc, char **argv) {
auto events = GetDlgItem(pane, 733);
auto visible = [&](int id) { return (GetWindowLongPtrW(GetDlgItem(pane, id), GWL_STYLE) & WS_VISIBLE) != 0; };
auto selectPage = [&](int index) { selectSettingsPage(settings, index); };
require(TreeView_GetCount(navigation) == 20, "all Settings sections are listed");
require(TreeView_GetCount(navigation) == 21, "all Settings sections are listed");
selectPage(3);
require(visible(243) && !visible(501), "Clipboard lists excluded apps separately from OCR");
require(TreeView_GetParent(navigation, settingsSection(navigation, 19)) == settingsSection(navigation, 3),
+4 -3
View File
@@ -67,9 +67,10 @@ void chooseInputAction(HWND resident, DWORD pid, const wchar_t *expected)
}
}
require(donationSeparated && donation.hbmpItem, "tray donation item has an icon and both separators");
require(help && GetMenuItemCount(help) == 2 && menuTitle(help, 0) == L"&User guide" &&
menuTitle(help, 1) == L"&About KSwitcher",
"tray Help submenu contains User guide and About KSwitcher");
require(help && GetMenuItemCount(help) == 3 && menuTitle(help, 0) == L"&User guide" &&
menuTitle(help, 1) == ks::whatsNewTitle(GetThreadUILanguage()) &&
menuTitle(help, 2) == L"&About KSwitcher",
"tray Help submenu contains User guide, release notes and About KSwitcher");
require(PostMessageW(popup, WM_CHAR, L'i', 0), "cannot select input menu item");
until([&] { return !IsWindow(popup); }, "tray action did not close menu");
query(resident, WM_NULL);
+123 -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,11 @@ namespace
{
ks::App *app{};
HWND host{}, field{};
HWND externalEditor{};
ULONGLONG externalPopupUntil{};
bool insertExternalSnippet{};
bool insertTerminalSnippet{};
constexpr wchar_t externalSnippetText[] = L"snippet test";
ks::Clip saved;
bool snippetRecoveryOnly = false;
LONG unfilteredSnippetWidth{};
@@ -278,6 +284,53 @@ void expandMacroSnippet(const wchar_t *replacement)
record(L";zmtest");
app->transform(0, 0, 0, field);
}
bool terminalShowsTestDraft()
{
using Microsoft::WRL::ComPtr;
ComPtr<IUIAutomation2> automation;
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&automation))))
return false;
automation->put_TransactionTimeout(150);
ComPtr<IUIAutomationElement> element;
ComPtr<IUIAutomationTreeWalker> walker;
if (FAILED(automation->GetFocusedElement(&element)) || !element ||
!ks::focusedTextBelongsToWindow(automation.Get(), element.Get(), externalEditor) ||
FAILED(automation->get_RawViewWalker(&walker)) || !walker)
return false;
// The xterm accessibility tree is beside the input's screen element.
for (int depth = 0; element && depth < 3; ++depth)
{
ComPtr<IUIAutomationElement> parent;
walker->GetParentElement(element.Get(), &parent);
element = std::move(parent);
}
if (!element) return false;
VARIANT className{};
className.vt = VT_BSTR;
className.bstrVal = SysAllocString(L"xterm-accessibility-tree");
ComPtr<IUIAutomationCondition> condition;
const auto hr = automation->CreatePropertyCondition(UIA_ClassNamePropertyId, className, &condition);
VariantClear(&className);
ComPtr<IUIAutomationElement> tree, row;
if (FAILED(hr) || !condition || FAILED(element->FindFirst(TreeScope_Descendants, condition.Get(), &tree)) ||
!tree || FAILED(walker->GetLastChildElement(tree.Get(), &row))) return false;
while (row)
{
BSTR name{};
row->get_CurrentName(&name);
std::wstring_view line(name ? name : L"", SysStringLen(name));
const auto end = line.find_last_not_of(L" \t\r\n\u00a0");
const bool matches = end != line.npos && line.substr(0, end + 1).ends_with(externalSnippetText);
SysFreeString(name);
if (end != line.npos) return matches;
ComPtr<IUIAutomationElement> previous;
walker->GetPreviousSiblingElement(row.Get(), &previous);
row = std::move(previous);
}
return false;
}
void finish()
{
KillTimer(host, 1);
@@ -337,6 +390,62 @@ 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 || insertTerminalSnippet)
{
externalPopupUntil = GetTickCount64() + 3000;
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 if (insertTerminalSnippet)
{
const bool inserted = GetForegroundWindow() == externalEditor &&
!ks::InputRegressionAccess::suggestionsVisible(*app) && terminalShowsTestDraft();
if (!inserted && GetTickCount64() < externalPopupUntil)
{
stage = 103;
break;
}
require(inserted, "Tab replaces the prefix in the live shell prompt");
}
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 +1305,15 @@ 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";
insertTerminalSnippet = argc > 2 && std::string_view(argv[2]) == "--terminal-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 +1480,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 +1490,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 +1511,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");
+36
View File
@@ -228,6 +228,42 @@ void verifyFiles(LanClients &clients, const Json &trusted, const std::wstring &p
require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "replace")).at("type") == "complete" &&
read(to / L"content.txt") == content, "replace conflict policy failed");
const auto ask = [&](const char *decision, bool replaceable) {
Pipe client(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "ask"));
unsigned prompts = 0;
for (;;)
{
auto result = client.reply();
const auto type = result.value("type", "");
if (type == "progress") client.sendJson({{"continue", true}});
else if (type == "conflict")
{
++prompts;
require(result.at("path") == utf8((to / L"content.txt").native()) &&
result.at("replaceable") == replaceable &&
result.at("incoming").at("size") == content.size(), "incorrect conflict prompt");
client.sendJson({{"decision", "wait"}});
client.sendJson({{"decision", decision}});
}
else
{
client.ack();
require(prompts == 1, "ask did not report the nested collision exactly once");
return result;
}
}
};
save(to / L"content.txt", "keep me");
require(ask("skip", true).at("skipped") == 1 && read(to / L"content.txt") == "keep me",
"skipping a prompted collision changed its destination");
require(ask("replace", true).at("type") == "complete" && read(to / L"content.txt") == content,
"confirming a prompted collision did not replace its destination");
fs::remove(to / L"content.txt");
fs::create_directory(to / L"content.txt");
require(ask("replace", false).contains("error") && fs::is_directory(to / L"content.txt"),
"a prompted type mismatch allowed replacement");
fs::remove(to / L"content.txt");
const auto localCopy = root / L"local.txt";
const auto fromLocal = transfer(endpoint(nullptr, file), endpoint(b, dst / L"from-local.txt"), false);
require(runTransfer(pipe, fromLocal).contains("error"), "identification-only pipe accessed local files");